13c33482d2110c2db6e230054b9df7fbb6b5e685
[platform/upstream/flac.git] / src / flac / decode.c
1 /* flac - Command-line FLAC encoder/decoder
2  * Copyright (C) 2000,2001,2002  Josh Coalson
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
17  */
18
19 #ifdef HAVE_CONFIG_H
20 #include <config.h>
21 #endif
22
23 #if defined _WIN32 && !defined __CYGWIN__
24 /* where MSVC puts unlink() */
25 # include <io.h>
26 #else
27 # include <unistd.h>
28 #endif
29 #include <math.h> /* for floor() */
30 #include <stdio.h> /* for FILE et al. */
31 #include <string.h> /* for strcmp() */
32 #include "FLAC/all.h"
33 #include "share/grabbag.h"
34 #include "decode.h"
35
36 #ifdef FLAC__HAS_OGG
37 #include "OggFLAC/stream_decoder.h"
38 #endif
39
40 typedef struct {
41 #ifdef FLAC__HAS_OGG
42         FLAC__bool is_ogg;
43 #endif
44
45         FLAC__bool verbose;
46         FLAC__bool is_wave_out;
47         FLAC__bool continue_through_decode_errors;
48         FLAC__bool test_only;
49         FLAC__bool analysis_mode;
50         analysis_options aopts;
51         utils__SkipUntilSpecification *skip_specification;
52         utils__SkipUntilSpecification *until_specification; /* a canonicalized value of 0 mean end-of-stream (i.e. --until=-0) */
53
54         const char *inbasefilename;
55         const char *outfilename;
56
57         FLAC__uint64 samples_processed;
58         unsigned frame_counter;
59         FLAC__bool abort_flag;
60
61         struct {
62                 FLAC__bool needs_fixup;
63                 unsigned riff_offset;
64                 unsigned data_offset;
65         } wave_chunk_size_fixup;
66
67         FLAC__bool is_big_endian;
68         FLAC__bool is_unsigned_samples;
69         FLAC__uint64 total_samples;
70         unsigned bps;
71         unsigned channels;
72         unsigned sample_rate;
73
74         union {
75                 union {
76                         FLAC__FileDecoder *file;
77                 } flac;
78 #ifdef FLAC__HAS_OGG
79                 union {
80                         OggFLAC__StreamDecoder *stream;
81                 } ogg;
82 #endif
83         } decoder;
84
85 #ifdef FLAC__HAS_OGG
86         FILE *fin;
87 #endif
88         FILE *fout;
89 } DecoderSession;
90
91
92 static FLAC__bool is_big_endian_host_;
93
94
95 /*
96  * local routines
97  */
98 static FLAC__bool DecoderSession_construct(DecoderSession *d, FLAC__bool is_ogg, FLAC__bool verbose, FLAC__bool is_wave_out, FLAC__bool continue_through_decode_errors, FLAC__bool analysis_mode, analysis_options aopts, utils__SkipUntilSpecification *skip_specification, utils__SkipUntilSpecification *until_specification, const char *infilename, const char *outfilename);
99 static void DecoderSession_destroy(DecoderSession *d, FLAC__bool error_occurred);
100 static FLAC__bool DecoderSession_init_decoder(DecoderSession *d, decode_options_t decode_options, const char *infilename);
101 static FLAC__bool DecoderSession_process(DecoderSession *d);
102 static int DecoderSession_finish_ok(DecoderSession *d);
103 static int DecoderSession_finish_error(DecoderSession *d);
104 static FLAC__bool canonicalize_until_specification(utils__SkipUntilSpecification *spec, const char *inbasefilename, unsigned sample_rate, FLAC__uint64 skip, FLAC__uint64 total_samples_in_input);
105 static FLAC__bool write_little_endian_uint16(FILE *f, FLAC__uint16 val);
106 static FLAC__bool write_little_endian_uint32(FILE *f, FLAC__uint32 val);
107 static FLAC__bool fixup_wave_chunk_size(const char *outfilename, unsigned riff_offset, unsigned data_offset, FLAC__uint32 data_size);
108 #ifdef FLAC__HAS_OGG
109 static FLAC__StreamDecoderReadStatus read_callback(const OggFLAC__StreamDecoder *decoder, FLAC__byte buffer[], unsigned *bytes, void *client_data);
110 #endif
111 /*
112  * We use 'void *' so that we can use the same callbacks for the
113  * FLAC__StreamDecoder and FLAC__FileDecoder.  The 'decoder' argument is
114  * actually never used in the callbacks.
115  */
116 static FLAC__StreamDecoderWriteStatus write_callback(const void *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
117 static void metadata_callback(const void *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
118 static void error_callback(const void *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
119 static void print_error_with_state(const DecoderSession *d, const char *message);
120 static void print_stats(const DecoderSession *decoder_session);
121
122
123 /*
124  * public routines
125  */
126 int flac__decode_wav(const char *infilename, const char *outfilename, FLAC__bool analysis_mode, analysis_options aopts, wav_decode_options_t options)
127 {
128         DecoderSession decoder_session;
129
130         if(!
131                 DecoderSession_construct(
132                         &decoder_session,
133 #ifdef FLAC__HAS_OGG
134                         options.common.is_ogg,
135 #else
136                         /*is_ogg=*/false,
137 #endif
138                         options.common.verbose,
139                         /*is_wave_out=*/true,
140                         options.common.continue_through_decode_errors,
141                         analysis_mode,
142                         aopts,
143                         &options.common.skip_specification,
144                         &options.common.until_specification,
145                         infilename,
146                         outfilename
147                 )
148         )
149                 return 1;
150
151         if(!DecoderSession_init_decoder(&decoder_session, options.common, infilename))
152                 return DecoderSession_finish_error(&decoder_session);
153
154         if(!DecoderSession_process(&decoder_session))
155                 return DecoderSession_finish_error(&decoder_session);
156
157         return DecoderSession_finish_ok(&decoder_session);
158 }
159
160 int flac__decode_raw(const char *infilename, const char *outfilename, FLAC__bool analysis_mode, analysis_options aopts, raw_decode_options_t options)
161 {
162         DecoderSession decoder_session;
163
164         decoder_session.is_big_endian = options.is_big_endian;
165         decoder_session.is_unsigned_samples = options.is_unsigned_samples;
166
167         if(!
168                 DecoderSession_construct(
169                         &decoder_session,
170 #ifdef FLAC__HAS_OGG
171                         options.common.is_ogg,
172 #else
173                         /*is_ogg=*/false,
174 #endif
175                         options.common.verbose,
176                         /*is_wave_out=*/false,
177                         options.common.continue_through_decode_errors,
178                         analysis_mode,
179                         aopts,
180                         &options.common.skip_specification,
181                         &options.common.until_specification,
182                         infilename,
183                         outfilename
184                 )
185         )
186                 return 1;
187
188         if(!DecoderSession_init_decoder(&decoder_session, options.common, infilename))
189                 return DecoderSession_finish_error(&decoder_session);
190
191         if(!DecoderSession_process(&decoder_session))
192                 return DecoderSession_finish_error(&decoder_session);
193
194         return DecoderSession_finish_ok(&decoder_session);
195 }
196
197 FLAC__bool DecoderSession_construct(DecoderSession *d, FLAC__bool is_ogg, FLAC__bool verbose, FLAC__bool is_wave_out, FLAC__bool continue_through_decode_errors, FLAC__bool analysis_mode, analysis_options aopts, utils__SkipUntilSpecification *skip_specification, utils__SkipUntilSpecification *until_specification, const char *infilename, const char *outfilename)
198 {
199 #ifdef FLAC__HAS_OGG
200         d->is_ogg = is_ogg;
201 #else
202         (void)is_ogg;
203 #endif
204
205         d->verbose = verbose;
206         d->is_wave_out = is_wave_out;
207         d->continue_through_decode_errors = continue_through_decode_errors;
208         d->test_only = (0 == outfilename);
209         d->analysis_mode = analysis_mode;
210         d->aopts = aopts;
211         d->skip_specification = skip_specification;
212         d->until_specification = until_specification;
213
214         d->inbasefilename = grabbag__file_get_basename(infilename);
215         d->outfilename = outfilename;
216
217         d->samples_processed = 0;
218         d->frame_counter = 0;
219         d->abort_flag = false;
220
221         d->wave_chunk_size_fixup.needs_fixup = false;
222
223         d->decoder.flac.file = 0;
224 #ifdef FLAC__HAS_OGG
225         d->decoder.ogg.stream = 0;
226 #endif
227
228 #ifdef FLAC__HAS_OGG
229         d->fin = 0;
230 #endif
231         d->fout = 0; /* initialized with an open file later if necessary */
232
233         FLAC__ASSERT(!(d->test_only && d->analysis_mode));
234
235         if(!d->test_only) {
236                 if(0 == strcmp(outfilename, "-")) {
237                         d->fout = grabbag__file_get_binary_stdout();
238                 }
239                 else {
240                         if(0 == (d->fout = fopen(outfilename, "wb"))) {
241                                 fprintf(stderr, "%s: ERROR: can't open output file %s\n", d->inbasefilename, outfilename);
242                                 DecoderSession_destroy(d, /*error_occurred=*/true);
243                                 return false;
244                         }
245                 }
246         }
247
248 #ifdef FLAC__HAS_OGG
249         if(d->is_ogg) {
250                 if (0 == strcmp(infilename, "-")) {
251                         d->fin = grabbag__file_get_binary_stdin();
252                 } else {
253                         if (0 == (d->fin = fopen(infilename, "rb"))) {
254                                 fprintf(stderr, "%s: ERROR: can't open input file %s\n", d->inbasefilename, infilename);
255                                 DecoderSession_destroy(d, /*error_occurred=*/true);
256                                 return false;
257                         }
258                 }
259         }
260 #endif
261
262         if(analysis_mode)
263                 flac__analyze_init(aopts);
264
265         return true;
266 }
267
268 void DecoderSession_destroy(DecoderSession *d, FLAC__bool error_occurred)
269 {
270         if(0 != d->fout && d->fout != stdout) {
271                 fclose(d->fout);
272                 if(error_occurred)
273                         unlink(d->outfilename);
274         }
275 #ifdef FLAC__HAS_OGG
276         if(0 != d->fin && d->fin != stdin)
277                 fclose(d->fin);
278 #endif
279 }
280
281 FLAC__bool DecoderSession_init_decoder(DecoderSession *decoder_session, decode_options_t decode_options, const char *infilename)
282 {
283         FLAC__uint32 test = 1;
284
285         is_big_endian_host_ = (*((FLAC__byte*)(&test)))? false : true;
286
287 #ifdef FLAC__HAS_OGG
288         if(decoder_session->is_ogg) {
289                 decoder_session->decoder.ogg.stream = OggFLAC__stream_decoder_new();
290
291                 if(0 == decoder_session->decoder.ogg.stream) {
292                         fprintf(stderr, "%s: ERROR creating the decoder instance\n", decoder_session->inbasefilename);
293                         return false;
294                 }
295
296                 if(!decode_options.use_first_serial_number)
297                         OggFLAC__stream_decoder_set_serial_number(decoder_session->decoder.ogg.stream, decode_options.serial_number);
298
299                 OggFLAC__stream_decoder_set_read_callback(decoder_session->decoder.ogg.stream, read_callback);
300                 /*
301                  * The three ugly casts here are to 'downcast' the 'void *' argument of
302                  * the callback down to 'FLAC__StreamDecoder *'.  In C++ this would be
303                  * unnecessary but here the cast makes the C compiler happy.
304                  */
305                 OggFLAC__stream_decoder_set_write_callback(decoder_session->decoder.ogg.stream, (FLAC__StreamDecoderWriteStatus (*)(const OggFLAC__StreamDecoder *, const FLAC__Frame *, const FLAC__int32 * const [], void *))write_callback);
306                 OggFLAC__stream_decoder_set_metadata_callback(decoder_session->decoder.ogg.stream, (void (*)(const OggFLAC__StreamDecoder *, const FLAC__StreamMetadata *, void *))metadata_callback);
307                 OggFLAC__stream_decoder_set_error_callback(decoder_session->decoder.ogg.stream, (void (*)(const OggFLAC__StreamDecoder *, FLAC__StreamDecoderErrorStatus, void *))error_callback);
308                 OggFLAC__stream_decoder_set_client_data(decoder_session->decoder.ogg.stream, decoder_session);
309
310                 if(OggFLAC__stream_decoder_init(decoder_session->decoder.ogg.stream) != OggFLAC__STREAM_DECODER_OK) {
311                         print_error_with_state(decoder_session, "ERROR initializing decoder");
312                         return false;
313                 }
314         }
315         else
316 #else
317         (void)decode_options;
318 #endif
319         {
320                 decoder_session->decoder.flac.file = FLAC__file_decoder_new();
321
322                 if(0 == decoder_session->decoder.flac.file) {
323                         fprintf(stderr, "%s: ERROR creating the decoder instance\n", decoder_session->inbasefilename);
324                         return false;
325                 }
326
327                 FLAC__file_decoder_set_md5_checking(decoder_session->decoder.flac.file, true);
328                 FLAC__file_decoder_set_filename(decoder_session->decoder.flac.file, infilename);
329                 /*
330                  * The three ugly casts here are to 'downcast' the 'void *' argument of
331                  * the callback down to 'FLAC__FileDecoder *'.
332                  */
333                 FLAC__file_decoder_set_write_callback(decoder_session->decoder.flac.file, (FLAC__StreamDecoderWriteStatus (*)(const FLAC__FileDecoder *, const FLAC__Frame *, const FLAC__int32 * const [], void *))write_callback);
334                 FLAC__file_decoder_set_metadata_callback(decoder_session->decoder.flac.file, (void (*)(const FLAC__FileDecoder *, const FLAC__StreamMetadata *, void *))metadata_callback);
335                 FLAC__file_decoder_set_error_callback(decoder_session->decoder.flac.file, (void (*)(const FLAC__FileDecoder *, FLAC__StreamDecoderErrorStatus, void *))error_callback);
336                 FLAC__file_decoder_set_client_data(decoder_session->decoder.flac.file, decoder_session);
337
338                 if(FLAC__file_decoder_init(decoder_session->decoder.flac.file) != FLAC__FILE_DECODER_OK) {
339                         print_error_with_state(decoder_session, "ERROR initializing decoder");
340                         return false;
341                 }
342         }
343
344         return true;
345 }
346
347 FLAC__bool DecoderSession_process(DecoderSession *d)
348 {
349 #ifdef FLAC__HAS_OGG
350         if(d->is_ogg) {
351                 if(!OggFLAC__stream_decoder_process_until_end_of_metadata(d->decoder.ogg.stream)) {
352                         if(d->verbose) fprintf(stderr, "\n");
353                         print_error_with_state(d, "ERROR while decoding metadata");
354                         return false;
355                 }
356                 if(OggFLAC__stream_decoder_get_FLAC_stream_decoder_state(d->decoder.ogg.stream) != FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC && OggFLAC__stream_decoder_get_FLAC_stream_decoder_state(d->decoder.ogg.stream) != FLAC__STREAM_DECODER_END_OF_STREAM) {
357                         if(d->verbose) fprintf(stderr, "\n");
358                         print_error_with_state(d, "ERROR during metadata decoding");
359                         return false;
360                 }
361         }
362         else
363 #endif
364         {
365                 if(!FLAC__file_decoder_process_until_end_of_metadata(d->decoder.flac.file)) {
366                         if(d->verbose) fprintf(stderr, "\n");
367                         print_error_with_state(d, "ERROR while decoding metadata");
368                         return false;
369                 }
370                 if(FLAC__file_decoder_get_state(d->decoder.flac.file) != FLAC__FILE_DECODER_OK && FLAC__file_decoder_get_state(d->decoder.flac.file) != FLAC__FILE_DECODER_END_OF_FILE) {
371                         if(d->verbose) fprintf(stderr, "\n");
372                         print_error_with_state(d, "ERROR during metadata decoding");
373                         return false;
374                 }
375         }
376         if(d->abort_flag)
377                 return false;
378
379         if(d->skip_specification->value.samples > 0) {
380                 const FLAC__uint64 skip = (FLAC__uint64)d->skip_specification->value.samples;
381
382 #ifdef FLAC__HAS_OGG
383                 if(d->is_ogg) { /*@@@ (move this check into main.c) */
384                         fprintf(stderr, "%s: ERROR, can't skip when decoding Ogg-FLAC yet; convert to native-FLAC first\n", d->inbasefilename);
385                         return false;
386                 }
387 #endif
388                 if(!FLAC__file_decoder_seek_absolute(d->decoder.flac.file, skip)) {
389                         print_error_with_state(d, "ERROR seeking while skipping bytes");
390                         return false;
391                 }
392                 if(!FLAC__file_decoder_process_until_end_of_file(d->decoder.flac.file)) {
393                         if(d->verbose) fprintf(stderr, "\n");
394                         print_error_with_state(d, "ERROR while decoding frames");
395                         return false;
396                 }
397                 if(FLAC__file_decoder_get_state(d->decoder.flac.file) != FLAC__FILE_DECODER_OK && FLAC__file_decoder_get_state(d->decoder.flac.file) != FLAC__FILE_DECODER_END_OF_FILE) {
398                         if(d->verbose) fprintf(stderr, "\n");
399                         print_error_with_state(d, "ERROR during decoding");
400                         return false;
401                 }
402         }
403         else {
404 #ifdef FLAC__HAS_OGG
405                 if(d->is_ogg) {
406                         if(!OggFLAC__stream_decoder_process_until_end_of_stream(d->decoder.ogg.stream)) {
407                                 if(d->verbose) fprintf(stderr, "\n");
408                                 print_error_with_state(d, "ERROR while decoding data");
409                                 return false;
410                         }
411                         if(OggFLAC__stream_decoder_get_FLAC_stream_decoder_state(d->decoder.ogg.stream) != FLAC__STREAM_DECODER_SEARCH_FOR_METADATA && OggFLAC__stream_decoder_get_FLAC_stream_decoder_state(d->decoder.ogg.stream) != FLAC__STREAM_DECODER_END_OF_STREAM) {
412                                 if(d->verbose) fprintf(stderr, "\n");
413                                 print_error_with_state(d, "ERROR during decoding");
414                                 return false;
415                         }
416                 }
417                 else
418 #endif
419                 {
420                         if(!FLAC__file_decoder_process_until_end_of_file(d->decoder.flac.file)) {
421                                 if(d->verbose) fprintf(stderr, "\n");
422                                 print_error_with_state(d, "ERROR while decoding data");
423                                 return false;
424                         }
425                         if(FLAC__file_decoder_get_state(d->decoder.flac.file) != FLAC__FILE_DECODER_OK && FLAC__file_decoder_get_state(d->decoder.flac.file) != FLAC__FILE_DECODER_END_OF_FILE) {
426                                 if(d->verbose) fprintf(stderr, "\n");
427                                 print_error_with_state(d, "ERROR during decoding");
428                                 return false;
429                         }
430                 }
431         }
432
433         return true;
434 }
435
436 int DecoderSession_finish_ok(DecoderSession *d)
437 {
438         FLAC__bool md5_failure = false;
439
440 #ifdef FLAC__HAS_OGG
441         if(d->is_ogg) {
442                 if(d->decoder.ogg.stream) {
443                         OggFLAC__stream_decoder_finish(d->decoder.ogg.stream);
444                         md5_failure = false;
445                         print_stats(d);
446                         OggFLAC__stream_decoder_delete(d->decoder.ogg.stream);
447                 }
448         }
449         else
450 #endif
451         {
452                 if(d->decoder.flac.file) {
453                         md5_failure = !FLAC__file_decoder_finish(d->decoder.flac.file);
454                         print_stats(d);
455                         FLAC__file_decoder_delete(d->decoder.flac.file);
456                 }
457         }
458         if(d->analysis_mode)
459                 flac__analyze_finish(d->aopts);
460         if(md5_failure) {
461                 fprintf(stderr, "\r%s: WARNING, MD5 signature mismatch\n", d->inbasefilename);
462         }
463         else {
464                 if(d->verbose)
465                         fprintf(stderr, "\r%s: %s         \n", d->inbasefilename, d->test_only? "ok           ":d->analysis_mode?"done           ":"done");
466         }
467         DecoderSession_destroy(d, /*error_occurred=*/false);
468         if(d->is_wave_out && d->wave_chunk_size_fixup.needs_fixup)
469                 if(!fixup_wave_chunk_size(d->outfilename, d->wave_chunk_size_fixup.riff_offset, d->wave_chunk_size_fixup.data_offset, (FLAC__uint32)d->samples_processed))
470                         return 1;
471         return 0;
472 }
473
474 int DecoderSession_finish_error(DecoderSession *d)
475 {
476 #ifdef FLAC__HAS_OGG
477         if(d->is_ogg) {
478                 if(d->decoder.ogg.stream) {
479                         OggFLAC__stream_decoder_finish(d->decoder.ogg.stream);
480                         OggFLAC__stream_decoder_delete(d->decoder.ogg.stream);
481                 }
482         }
483         else
484 #endif
485         {
486                 if(d->decoder.flac.file) {
487                         FLAC__file_decoder_finish(d->decoder.flac.file);
488                         FLAC__file_decoder_delete(d->decoder.flac.file);
489                 }
490         }
491         if(d->analysis_mode)
492                 flac__analyze_finish(d->aopts);
493         DecoderSession_destroy(d, /*error_occurred=*/true);
494         return 1;
495 }
496
497 FLAC__bool canonicalize_until_specification(utils__SkipUntilSpecification *spec, const char *inbasefilename, unsigned sample_rate, FLAC__uint64 skip, FLAC__uint64 total_samples_in_input)
498 {
499         /* convert from mm:ss.sss to sample number if necessary */
500         flac__utils_canonicalize_skip_until_specification(spec, sample_rate);
501
502         /* special case: if "--until=-0", use the special value '0' to mean "end-of-stream" */
503         if(spec->is_relative && spec->value.samples == 0) {
504                 spec->is_relative = false;
505                 return true;
506         }
507
508         /* in any other case the total samples in the input must be known */
509         if(total_samples_in_input == 0) {
510                 fprintf(stderr, "%s: ERROR, cannot use --until when FLAC metadata has total sample count of 0\n", inbasefilename);
511                 return false;
512         }
513
514         FLAC__ASSERT(spec->value_is_samples);
515
516         /* convert relative specifications to absolute */
517         if(spec->is_relative) {
518                 if(spec->value.samples <= 0)
519                         spec->value.samples += (FLAC__int64)total_samples_in_input;
520                 else
521                         spec->value.samples += skip;
522                 spec->is_relative = false;
523         }
524
525         /* error check */
526         if(spec->value.samples < 0) {
527                 fprintf(stderr, "%s: ERROR, --until value is before beginning of input\n", inbasefilename);
528                 return false;
529         }
530         if((FLAC__uint64)spec->value.samples <= skip) {
531                 fprintf(stderr, "%s: ERROR, --until value is before --skip point\n", inbasefilename);
532                 return false;
533         }
534         if((FLAC__uint64)spec->value.samples > total_samples_in_input) {
535                 fprintf(stderr, "%s: ERROR, --until value is after end of input\n", inbasefilename);
536                 return false;
537         }
538
539         return true;
540 }
541
542 FLAC__bool write_little_endian_uint16(FILE *f, FLAC__uint16 val)
543 {
544         FLAC__byte *b = (FLAC__byte*)(&val);
545         if(is_big_endian_host_) {
546                 FLAC__byte tmp;
547                 tmp = b[1]; b[1] = b[0]; b[0] = tmp;
548         }
549         return fwrite(b, 1, 2, f) == 2;
550 }
551
552 FLAC__bool write_little_endian_uint32(FILE *f, FLAC__uint32 val)
553 {
554         FLAC__byte *b = (FLAC__byte*)(&val);
555         if(is_big_endian_host_) {
556                 FLAC__byte tmp;
557                 tmp = b[3]; b[3] = b[0]; b[0] = tmp;
558                 tmp = b[2]; b[2] = b[1]; b[1] = tmp;
559         }
560         return fwrite(b, 1, 4, f) == 4;
561 }
562
563 FLAC__bool fixup_wave_chunk_size(const char *outfilename, unsigned riff_offset, unsigned data_offset, FLAC__uint32 data_size)
564 {
565         FILE *f = fopen(outfilename, "r+b");
566         if(0 == f) {
567                 fprintf(stderr, "ERROR, couldn't open file %s while fixing up WAVE chunk size\n", outfilename);
568                 return false;
569         }
570         if(fseek(f, riff_offset, SEEK_SET) < 0) {
571                 fprintf(stderr, "ERROR, couldn't seek in file %s while fixing up WAVE chunk size\n", outfilename);
572                 fclose(f);
573                 return false;
574         }
575         if(!write_little_endian_uint32(f, data_size + 36)) {
576                 fprintf(stderr, "ERROR, couldn't write size in file %s while fixing up WAVE chunk size\n", outfilename);
577                 fclose(f);
578                 return false;
579         }
580         if(fseek(f, data_offset, SEEK_SET) < 0) {
581                 fprintf(stderr, "ERROR, couldn't seek in file %s while fixing up WAVE chunk size\n", outfilename);
582                 fclose(f);
583                 return false;
584         }
585         if(!write_little_endian_uint32(f, data_size)) {
586                 fprintf(stderr, "ERROR, couldn't write size in file %s while fixing up WAVE chunk size\n", outfilename);
587                 fclose(f);
588                 return false;
589         }
590         fclose(f);
591         return true;
592 }
593
594 #ifdef FLAC__HAS_OGG
595 FLAC__StreamDecoderReadStatus read_callback(const OggFLAC__StreamDecoder *decoder, FLAC__byte buffer[], unsigned *bytes, void *client_data)
596 {
597         DecoderSession *decoder_session = (DecoderSession*)client_data;
598         FILE *fin = decoder_session->fin;
599         size_t bytes_read;
600
601         (void)decoder; /* avoid compiler warning */
602
603         if (decoder_session->abort_flag)
604                 return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
605
606         if(feof(fin))
607                 return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
608
609         bytes_read = fread(buffer, 1, *bytes, fin);
610
611         if(ferror(fin))
612                 return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
613
614         *bytes = (unsigned)bytes_read;
615
616         return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
617 }
618 #endif
619
620 FLAC__StreamDecoderWriteStatus write_callback(const void *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
621 {
622         DecoderSession *decoder_session = (DecoderSession*)client_data;
623         FILE *fout = decoder_session->fout;
624         const unsigned bps = frame->header.bits_per_sample, channels = frame->header.channels;
625         FLAC__bool is_big_endian = (decoder_session->is_wave_out? false : decoder_session->is_big_endian);
626         FLAC__bool is_unsigned_samples = (decoder_session->is_wave_out? bps<=8 : decoder_session->is_unsigned_samples);
627         unsigned wide_samples = frame->header.blocksize, wide_sample, sample, channel, byte;
628         static FLAC__int8 s8buffer[FLAC__MAX_BLOCK_SIZE * FLAC__MAX_CHANNELS * sizeof(FLAC__int32)]; /* WATCHOUT: can be up to 2 megs */
629         FLAC__uint8  *u8buffer  = (FLAC__uint8  *)s8buffer;
630         FLAC__int16  *s16buffer = (FLAC__int16  *)s8buffer;
631         FLAC__uint16 *u16buffer = (FLAC__uint16 *)s8buffer;
632         FLAC__int32  *s32buffer = (FLAC__int32  *)s8buffer;
633         FLAC__uint32 *u32buffer = (FLAC__uint32 *)s8buffer;
634
635         (void)decoder;
636
637         if(decoder_session->abort_flag)
638                 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
639
640         if(bps != decoder_session->bps) {
641                 fprintf(stderr, "%s: ERROR, bits-per-sample is %u in frame but %u in STREAMINFO\n", decoder_session->inbasefilename, bps, decoder_session->bps);
642                 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
643         }
644         if(channels != decoder_session->channels) {
645                 fprintf(stderr, "%s: ERROR, channels is %u in frame but %u in STREAMINFO\n", decoder_session->inbasefilename, channels, decoder_session->channels);
646                 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
647         }
648         if(frame->header.sample_rate != decoder_session->sample_rate) {
649                 fprintf(stderr, "%s: ERROR, sample rate is %u in frame but %u in STREAMINFO\n", decoder_session->inbasefilename, frame->header.sample_rate, decoder_session->sample_rate);
650                 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
651         }
652
653         /*
654          * limit the number of samples to accept based on --until
655          */
656         FLAC__ASSERT(!decoder_session->skip_specification->is_relative);
657         FLAC__ASSERT(decoder_session->skip_specification->value.samples >= 0);
658         FLAC__ASSERT(!decoder_session->until_specification->is_relative);
659         FLAC__ASSERT(decoder_session->until_specification->value.samples >= 0);
660         if(decoder_session->until_specification->value.samples > 0) {
661                 const FLAC__uint64 skip = (FLAC__uint64)decoder_session->skip_specification->value.samples;
662                 const FLAC__uint64 until = (FLAC__uint64)decoder_session->until_specification->value.samples;
663                 const FLAC__uint64 input_samples_passed = skip + decoder_session->samples_processed;
664                 FLAC__ASSERT(until >= input_samples_passed);
665                 if(input_samples_passed + wide_samples > until)
666                         wide_samples = until - input_samples_passed;
667         }
668
669         if(wide_samples > 0) {
670                 decoder_session->samples_processed += wide_samples;
671                 decoder_session->frame_counter++;
672
673                 if(decoder_session->verbose && !(decoder_session->frame_counter & 0x3f))
674                         print_stats(decoder_session);
675
676                 if(decoder_session->analysis_mode) {
677                         flac__analyze_frame(frame, decoder_session->frame_counter-1, decoder_session->aopts, fout);
678                 }
679                 else if(!decoder_session->test_only) {
680                         if(bps == 8) {
681                                 if(is_unsigned_samples) {
682                                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
683                                                 for(channel = 0; channel < channels; channel++, sample++)
684                                                         u8buffer[sample] = (FLAC__uint8)(buffer[channel][wide_sample] + 0x80);
685                                 }
686                                 else {
687                                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
688                                                 for(channel = 0; channel < channels; channel++, sample++)
689                                                         s8buffer[sample] = (FLAC__int8)(buffer[channel][wide_sample]);
690                                 }
691                                 if(fwrite(u8buffer, 1, sample, fout) != sample)
692                                         return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
693                         }
694                         else if(bps == 16) {
695                                 if(is_unsigned_samples) {
696                                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
697                                                 for(channel = 0; channel < channels; channel++, sample++)
698                                                         u16buffer[sample] = (FLAC__uint16)(buffer[channel][wide_sample] + 0x8000);
699                                 }
700                                 else {
701                                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
702                                                 for(channel = 0; channel < channels; channel++, sample++)
703                                                         s16buffer[sample] = (FLAC__int16)(buffer[channel][wide_sample]);
704                                 }
705                                 if(is_big_endian != is_big_endian_host_) {
706                                         unsigned char tmp;
707                                         const unsigned bytes = sample * 2;
708                                         for(byte = 0; byte < bytes; byte += 2) {
709                                                 tmp = u8buffer[byte];
710                                                 u8buffer[byte] = u8buffer[byte+1];
711                                                 u8buffer[byte+1] = tmp;
712                                         }
713                                 }
714                                 if(fwrite(u16buffer, 2, sample, fout) != sample)
715                                         return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
716                         }
717                         else if(bps == 24) {
718                                 if(is_unsigned_samples) {
719                                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
720                                                 for(channel = 0; channel < channels; channel++, sample++)
721                                                         u32buffer[sample] = buffer[channel][wide_sample] + 0x800000;
722                                 }
723                                 else {
724                                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
725                                                 for(channel = 0; channel < channels; channel++, sample++)
726                                                         s32buffer[sample] = buffer[channel][wide_sample];
727                                 }
728                                 if(is_big_endian != is_big_endian_host_) {
729                                         unsigned char tmp;
730                                         const unsigned bytes = sample * 4;
731                                         for(byte = 0; byte < bytes; byte += 4) {
732                                                 tmp = u8buffer[byte];
733                                                 u8buffer[byte] = u8buffer[byte+3];
734                                                 u8buffer[byte+3] = tmp;
735                                                 tmp = u8buffer[byte+1];
736                                                 u8buffer[byte+1] = u8buffer[byte+2];
737                                                 u8buffer[byte+2] = tmp;
738                                         }
739                                 }
740                                 if(is_big_endian) {
741                                         unsigned lbyte;
742                                         const unsigned bytes = sample * 4;
743                                         for(lbyte = byte = 0; byte < bytes; ) {
744                                                 byte++;
745                                                 u8buffer[lbyte++] = u8buffer[byte++];
746                                                 u8buffer[lbyte++] = u8buffer[byte++];
747                                                 u8buffer[lbyte++] = u8buffer[byte++];
748                                         }
749                                 }
750                                 else {
751                                         unsigned lbyte;
752                                         const unsigned bytes = sample * 4;
753                                         for(lbyte = byte = 0; byte < bytes; ) {
754                                                 u8buffer[lbyte++] = u8buffer[byte++];
755                                                 u8buffer[lbyte++] = u8buffer[byte++];
756                                                 u8buffer[lbyte++] = u8buffer[byte++];
757                                                 byte++;
758                                         }
759                                 }
760                                 if(fwrite(u8buffer, 3, sample, fout) != sample)
761                                         return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
762                         }
763                         else {
764                                 FLAC__ASSERT(0);
765                         }
766                 }
767         }
768         return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
769 }
770
771 void metadata_callback(const void *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
772 {
773         DecoderSession *decoder_session = (DecoderSession*)client_data;
774         (void)decoder;
775         if(metadata->type == FLAC__METADATA_TYPE_STREAMINFO) {
776                 FLAC__uint64 skip, until;
777                 decoder_session->bps = metadata->data.stream_info.bits_per_sample;
778                 decoder_session->channels = metadata->data.stream_info.channels;
779                 decoder_session->sample_rate = metadata->data.stream_info.sample_rate;
780
781                 flac__utils_canonicalize_skip_until_specification(decoder_session->skip_specification, decoder_session->sample_rate);
782                 FLAC__ASSERT(decoder_session->skip_specification->value.samples >= 0);
783                 skip = (FLAC__uint64)decoder_session->skip_specification->value.samples;
784
785                 /* remember, metadata->data.stream_info.total_samples can be 0, meaning 'unknown' */
786                 if(metadata->data.stream_info.total_samples > 0 && skip >= metadata->data.stream_info.total_samples) {
787                         fprintf(stderr, "%s: ERROR trying to --skip more samples than in stream\n", decoder_session->inbasefilename);
788                         decoder_session->abort_flag = true;
789                         return;
790                 }
791                 else if(metadata->data.stream_info.total_samples == 0 && skip > 0) {
792                         fprintf(stderr, "%s: ERROR, can't --skip when FLAC metadata has total sample count of 0\n", decoder_session->inbasefilename);
793                         decoder_session->abort_flag = true;
794                         return;
795                 }
796                 decoder_session->total_samples = metadata->data.stream_info.total_samples - skip;
797
798                 /* note that we use metadata->data.stream_info.total_samples instead of decoder_session->total_samples */
799                 if(!canonicalize_until_specification(decoder_session->until_specification, decoder_session->inbasefilename, decoder_session->sample_rate, skip, metadata->data.stream_info.total_samples)) {
800                         decoder_session->abort_flag = true;
801                         return;
802                 }
803                 FLAC__ASSERT(decoder_session->until_specification->value.samples >= 0);
804                 until = (FLAC__uint64)decoder_session->until_specification->value.samples;
805
806                 if(until > 0)
807                         decoder_session->total_samples -= (metadata->data.stream_info.total_samples - until);
808
809                 if(decoder_session->bps != 8 && decoder_session->bps != 16 && decoder_session->bps != 24) {
810                         fprintf(stderr, "%s: ERROR: bits per sample is not 8/16/24\n", decoder_session->inbasefilename);
811                         decoder_session->abort_flag = true;
812                         return;
813                 }
814
815                 /* write the WAVE headers if necessary */
816                 if(!decoder_session->analysis_mode && !decoder_session->test_only && decoder_session->is_wave_out) {
817                         FLAC__uint64 data_size = decoder_session->total_samples * decoder_session->channels * ((decoder_session->bps+7)/8);
818                         if(decoder_session->total_samples == 0) {
819                                 if(decoder_session->fout == stdout) {
820                                         fprintf(stderr, "%s: WARNING, don't have accurate sample count available for WAVE header.\n", decoder_session->inbasefilename);
821                                         fprintf(stderr, "             Generated WAVE file will have a data chunk size of 0.  Try\n");
822                                         fprintf(stderr, "             decoding directly to a file instead.\n");
823                                 }
824                                 else {
825                                         decoder_session->wave_chunk_size_fixup.needs_fixup = true;
826                                 }
827                         }
828                         if(data_size >= 0xFFFFFFDC) {
829                                 fprintf(stderr, "%s: ERROR: stream is too big to fit in a single WAVE file chunk\n", decoder_session->inbasefilename);
830                                 decoder_session->abort_flag = true;
831                                 return;
832                         }
833                         if(fwrite("RIFF", 1, 4, decoder_session->fout) != 4) decoder_session->abort_flag = true;
834                         if(decoder_session->wave_chunk_size_fixup.needs_fixup)
835                                 decoder_session->wave_chunk_size_fixup.riff_offset = ftell(decoder_session->fout);
836                         if(!write_little_endian_uint32(decoder_session->fout, (FLAC__uint32)(data_size+36))) decoder_session->abort_flag = true; /* filesize-8 */
837                         if(fwrite("WAVEfmt ", 1, 8, decoder_session->fout) != 8) decoder_session->abort_flag = true;
838                         if(fwrite("\020\000\000\000", 1, 4, decoder_session->fout) != 4) decoder_session->abort_flag = true; /* chunk size = 16 */
839                         if(fwrite("\001\000", 1, 2, decoder_session->fout) != 2) decoder_session->abort_flag = true; /* compression code == 1 */
840                         if(!write_little_endian_uint16(decoder_session->fout, (FLAC__uint16)(decoder_session->channels))) decoder_session->abort_flag = true;
841                         if(!write_little_endian_uint32(decoder_session->fout, decoder_session->sample_rate)) decoder_session->abort_flag = true;
842                         if(!write_little_endian_uint32(decoder_session->fout, decoder_session->sample_rate * decoder_session->channels * ((decoder_session->bps+7) / 8))) decoder_session->abort_flag = true; /* @@@ or is it (sample_rate*channels*bps) / 8 ??? */
843                         if(!write_little_endian_uint16(decoder_session->fout, (FLAC__uint16)(decoder_session->channels * ((decoder_session->bps+7) / 8)))) decoder_session->abort_flag = true; /* block align */
844                         if(!write_little_endian_uint16(decoder_session->fout, (FLAC__uint16)(decoder_session->bps))) decoder_session->abort_flag = true; /* bits per sample */
845                         if(fwrite("data", 1, 4, decoder_session->fout) != 4) decoder_session->abort_flag = true;
846                         if(decoder_session->wave_chunk_size_fixup.needs_fixup)
847                                 decoder_session->wave_chunk_size_fixup.data_offset = ftell(decoder_session->fout);
848                         if(!write_little_endian_uint32(decoder_session->fout, (FLAC__uint32)data_size)) decoder_session->abort_flag = true; /* data size */
849                 }
850         }
851 }
852
853 void error_callback(const void *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
854 {
855         DecoderSession *decoder_session = (DecoderSession*)client_data;
856         (void)decoder;
857         fprintf(stderr, "%s: *** Got error code %d:%s\n", decoder_session->inbasefilename, status, FLAC__StreamDecoderErrorStatusString[status]);
858         if(!decoder_session->continue_through_decode_errors)
859                 decoder_session->abort_flag = true;
860 }
861
862 void print_error_with_state(const DecoderSession *d, const char *message)
863 {
864         const int ilen = strlen(d->inbasefilename) + 1;
865
866         fprintf(stderr, "\n%s: %s\n", d->inbasefilename, message);
867
868 #ifdef FLAC__HAS_OGG
869         if(d->is_ogg) {
870                 const OggFLAC__StreamDecoderState osd_state = OggFLAC__stream_decoder_get_state(d->decoder.ogg.stream);
871                 if(osd_state != OggFLAC__STREAM_DECODER_FLAC_STREAM_DECODER_ERROR) {
872                         fprintf(stderr, "%*s state = %d:%s\n", ilen, "", (int)osd_state, OggFLAC__StreamDecoderStateString[osd_state]);
873                 }
874                 else {
875                         const FLAC__StreamDecoderState fsd_state = OggFLAC__stream_decoder_get_FLAC_stream_decoder_state(d->decoder.ogg.stream);
876                         fprintf(stderr, "%*s state = %d:%s\n", ilen, "", (int)fsd_state, FLAC__StreamDecoderStateString[fsd_state]);
877                 }
878         }
879         else
880 #endif
881         {
882                 const FLAC__FileDecoderState ffd_state = FLAC__file_decoder_get_state(d->decoder.flac.file);
883                 if(ffd_state != FLAC__FILE_DECODER_SEEKABLE_STREAM_DECODER_ERROR) {
884                         fprintf(stderr, "%*s state = %d:%s\n", ilen, "", (int)ffd_state, FLAC__FileDecoderStateString[ffd_state]);
885                 }
886                 else {
887                         const FLAC__SeekableStreamDecoderState fssd_state = FLAC__file_decoder_get_seekable_stream_decoder_state(d->decoder.flac.file);
888                         if(fssd_state != FLAC__SEEKABLE_STREAM_DECODER_STREAM_DECODER_ERROR) {
889                                 fprintf(stderr, "%*s state = %d:%s\n", ilen, "", (int)fssd_state, FLAC__SeekableStreamDecoderStateString[fssd_state]);
890                         }
891                         else {
892                                 const FLAC__StreamDecoderState fsd_state = FLAC__file_decoder_get_stream_decoder_state(d->decoder.flac.file);
893                                 fprintf(stderr, "%*s state = %d:%s\n", ilen, "", (int)fsd_state, FLAC__StreamDecoderStateString[fsd_state]);
894                         }
895                 }
896         }
897 }
898
899 void print_stats(const DecoderSession *decoder_session)
900 {
901         if(decoder_session->verbose) {
902 #if defined _MSC_VER || defined __MINGW32__
903                 /* with VC++ you have to spoon feed it the casting */
904                 const double progress = (double)(FLAC__int64)decoder_session->samples_processed / (double)(FLAC__int64)decoder_session->total_samples * 100.0;
905 #else
906                 const double progress = (double)decoder_session->samples_processed / (double)decoder_session->total_samples * 100.0;
907 #endif
908                 if(decoder_session->total_samples > 0) {
909                         fprintf(stderr, "\r%s: %s%u%% complete",
910                                 decoder_session->inbasefilename,
911                                 decoder_session->test_only? "testing, " : decoder_session->analysis_mode? "analyzing, " : "",
912                                 (unsigned)floor(progress + 0.5)
913                         );
914                 }
915                 else {
916                         fprintf(stderr, "\r%s: %s %u samples",
917                                 decoder_session->inbasefilename,
918                                 decoder_session->test_only? "tested" : decoder_session->analysis_mode? "analyzed" : "wrote",
919                                 (unsigned)decoder_session->samples_processed
920                         );
921                 }
922         }
923 }