c92cd96f2e8f0adbdc781b4092fa022629d3b666
[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         FLAC__uint64 skip;
52
53         const char *inbasefilename;
54         const char *outfilename;
55
56         FLAC__uint64 samples_processed;
57         unsigned frame_counter;
58         FLAC__bool abort_flag;
59
60         struct {
61                 FLAC__bool needs_fixup;
62                 unsigned riff_offset;
63                 unsigned data_offset;
64         } wave_chunk_size_fixup;
65
66         FLAC__bool is_big_endian;
67         FLAC__bool is_unsigned_samples;
68         FLAC__uint64 total_samples;
69         unsigned bps;
70         unsigned channels;
71         unsigned sample_rate;
72
73         union {
74                 union {
75                         FLAC__FileDecoder *file;
76                 } flac;
77 #ifdef FLAC__HAS_OGG
78                 union {
79                         OggFLAC__StreamDecoder *stream;
80                 } ogg;
81 #endif
82         } decoder;
83
84 #ifdef FLAC__HAS_OGG
85         FILE *fin;
86 #endif
87         FILE *fout;
88 } DecoderSession;
89
90
91 static FLAC__bool is_big_endian_host_;
92
93
94 /*
95  * local routines
96  */
97 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, FLAC__uint64 skip, const char *infilename, const char *outfilename);
98 static void DecoderSession_destroy(DecoderSession *d, FLAC__bool error_occurred);
99 static FLAC__bool DecoderSession_init_decoder(DecoderSession *d, decode_options_t decode_options, const char *infilename);
100 static FLAC__bool DecoderSession_process(DecoderSession *d);
101 static int DecoderSession_finish_ok(DecoderSession *d);
102 static int DecoderSession_finish_error(DecoderSession *d);
103 static FLAC__bool write_little_endian_uint16(FILE *f, FLAC__uint16 val);
104 static FLAC__bool write_little_endian_uint32(FILE *f, FLAC__uint32 val);
105 static FLAC__bool fixup_wave_chunk_size(const char *outfilename, unsigned riff_offset, unsigned data_offset, FLAC__uint32 data_size);
106 #ifdef FLAC__HAS_OGG
107 static FLAC__StreamDecoderReadStatus read_callback(const OggFLAC__StreamDecoder *decoder, FLAC__byte buffer[], unsigned *bytes, void *client_data);
108 #endif
109 /*
110  * We use 'void *' so that we can use the same callbacks for the
111  * FLAC__StreamDecoder and FLAC__FileDecoder.  The 'decoder' argument is
112  * actually never used in the callbacks.
113  */
114 static FLAC__StreamDecoderWriteStatus write_callback(const void *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
115 static void metadata_callback(const void *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
116 static void error_callback(const void *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
117 static void print_error_with_state(const DecoderSession *d, const char *message);
118 static void print_stats(const DecoderSession *decoder_session);
119
120
121 /*
122  * public routines
123  */
124 int flac__decode_wav(const char *infilename, const char *outfilename, FLAC__bool analysis_mode, analysis_options aopts, wav_decode_options_t options)
125 {
126         DecoderSession decoder_session;
127
128         if(!
129                 DecoderSession_construct(
130                         &decoder_session,
131 #ifdef FLAC__HAS_OGG
132                         options.common.is_ogg,
133 #else
134                         /*is_ogg=*/false,
135 #endif
136                         options.common.verbose,
137                         /*is_wave_out=*/true,
138                         options.common.continue_through_decode_errors,
139                         analysis_mode,
140                         aopts,
141                         options.common.skip,
142                         infilename,
143                         outfilename
144                 )
145         )
146                 return 1;
147
148         if(!DecoderSession_init_decoder(&decoder_session, options.common, infilename))
149                 return DecoderSession_finish_error(&decoder_session);
150
151         if(!DecoderSession_process(&decoder_session))
152                 return DecoderSession_finish_error(&decoder_session);
153
154         return DecoderSession_finish_ok(&decoder_session);
155 }
156
157 int flac__decode_raw(const char *infilename, const char *outfilename, FLAC__bool analysis_mode, analysis_options aopts, raw_decode_options_t options)
158 {
159         DecoderSession decoder_session;
160
161         decoder_session.is_big_endian = options.is_big_endian;
162         decoder_session.is_unsigned_samples = options.is_unsigned_samples;
163
164         if(!
165                 DecoderSession_construct(
166                         &decoder_session,
167 #ifdef FLAC__HAS_OGG
168                         options.common.is_ogg,
169 #else
170                         /*is_ogg=*/false,
171 #endif
172                         options.common.verbose,
173                         /*is_wave_out=*/false,
174                         options.common.continue_through_decode_errors,
175                         analysis_mode,
176                         aopts,
177                         options.common.skip,
178                         infilename,
179                         outfilename
180                 )
181         )
182                 return 1;
183
184         if(!DecoderSession_init_decoder(&decoder_session, options.common, infilename))
185                 return DecoderSession_finish_error(&decoder_session);
186
187         if(!DecoderSession_process(&decoder_session))
188                 return DecoderSession_finish_error(&decoder_session);
189
190         return DecoderSession_finish_ok(&decoder_session);
191 }
192
193 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, FLAC__uint64 skip, const char *infilename, const char *outfilename)
194 {
195 #ifdef FLAC__HAS_OGG
196         d->is_ogg = is_ogg;
197 #else
198         (void)is_ogg;
199 #endif
200
201         d->verbose = verbose;
202         d->is_wave_out = is_wave_out;
203         d->continue_through_decode_errors = continue_through_decode_errors;
204         d->test_only = (0 == outfilename);
205         d->analysis_mode = analysis_mode;
206         d->aopts = aopts;
207         d->skip = skip;
208
209         d->inbasefilename = grabbag__file_get_basename(infilename);
210         d->outfilename = outfilename;
211
212         d->samples_processed = 0;
213         d->frame_counter = 0;
214         d->abort_flag = false;
215
216         d->wave_chunk_size_fixup.needs_fixup = false;
217
218         d->decoder.flac.file = 0;
219 #ifdef FLAC__HAS_OGG
220         d->decoder.ogg.stream = 0;
221 #endif
222
223 #ifdef FLAC__HAS_OGG
224         d->fin = 0;
225 #endif
226         d->fout = 0; /* initialized with an open file later if necessary */
227
228         FLAC__ASSERT(!(d->test_only && d->analysis_mode));
229
230         if(!d->test_only) {
231                 if(0 == strcmp(outfilename, "-")) {
232                         d->fout = grabbag__file_get_binary_stdout();
233                 }
234                 else {
235                         if(0 == (d->fout = fopen(outfilename, "wb"))) {
236                                 fprintf(stderr, "%s: ERROR: can't open output file %s\n", d->inbasefilename, outfilename);
237                                 DecoderSession_destroy(d, /*error_occurred=*/true);
238                                 return false;
239                         }
240                 }
241         }
242
243 #ifdef FLAC__HAS_OGG
244         if(d->is_ogg) {
245                 if (0 == strcmp(infilename, "-")) {
246                         d->fin = grabbag__file_get_binary_stdin();
247                 } else {
248                         if (0 == (d->fin = fopen(infilename, "rb"))) {
249                                 fprintf(stderr, "%s: ERROR: can't open input file %s\n", d->inbasefilename, infilename);
250                                 DecoderSession_destroy(d, /*error_occurred=*/true);
251                                 return false;
252                         }
253                 }
254         }
255 #endif
256
257         if(analysis_mode)
258                 flac__analyze_init(aopts);
259
260         return true;
261 }
262
263 void DecoderSession_destroy(DecoderSession *d, FLAC__bool error_occurred)
264 {
265         if(0 != d->fout && d->fout != stdout) {
266                 fclose(d->fout);
267                 if(error_occurred)
268                         unlink(d->outfilename);
269         }
270 #ifdef FLAC__HAS_OGG
271         if(0 != d->fin && d->fin != stdin)
272                 fclose(d->fin);
273 #endif
274 }
275
276 FLAC__bool DecoderSession_init_decoder(DecoderSession *decoder_session, decode_options_t decode_options, const char *infilename)
277 {
278         FLAC__uint32 test = 1;
279
280         is_big_endian_host_ = (*((FLAC__byte*)(&test)))? false : true;
281
282 #ifdef FLAC__HAS_OGG
283         if(decoder_session->is_ogg) {
284                 decoder_session->decoder.ogg.stream = OggFLAC__stream_decoder_new();
285
286                 if(0 == decoder_session->decoder.ogg.stream) {
287                         fprintf(stderr, "%s: ERROR creating the decoder instance\n", decoder_session->inbasefilename);
288                         return false;
289                 }
290
291                 if(!decode_options.use_first_serial_number)
292                         OggFLAC__stream_decoder_set_serial_number(decoder_session->decoder.ogg.stream, decode_options.serial_number);
293
294                 OggFLAC__stream_decoder_set_read_callback(decoder_session->decoder.ogg.stream, read_callback);
295                 /*
296                  * The three ugly casts here are to 'downcast' the 'void *' argument of
297                  * the callback down to 'FLAC__StreamDecoder *'.  In C++ this would be
298                  * unnecessary but here the cast makes the C compiler happy.
299                  */
300                 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);
301                 OggFLAC__stream_decoder_set_metadata_callback(decoder_session->decoder.ogg.stream, (void (*)(const OggFLAC__StreamDecoder *, const FLAC__StreamMetadata *, void *))metadata_callback);
302                 OggFLAC__stream_decoder_set_error_callback(decoder_session->decoder.ogg.stream, (void (*)(const OggFLAC__StreamDecoder *, FLAC__StreamDecoderErrorStatus, void *))error_callback);
303                 OggFLAC__stream_decoder_set_client_data(decoder_session->decoder.ogg.stream, decoder_session);
304
305                 if(OggFLAC__stream_decoder_init(decoder_session->decoder.ogg.stream) != OggFLAC__STREAM_DECODER_OK) {
306                         print_error_with_state(decoder_session, "ERROR initializing decoder");
307                         return false;
308                 }
309         }
310         else
311 #else
312         (void)decode_options;
313 #endif
314         {
315                 decoder_session->decoder.flac.file = FLAC__file_decoder_new();
316
317                 if(0 == decoder_session->decoder.flac.file) {
318                         fprintf(stderr, "%s: ERROR creating the decoder instance\n", decoder_session->inbasefilename);
319                         return false;
320                 }
321
322                 FLAC__file_decoder_set_md5_checking(decoder_session->decoder.flac.file, true);
323                 FLAC__file_decoder_set_filename(decoder_session->decoder.flac.file, infilename);
324                 /*
325                  * The three ugly casts here are to 'downcast' the 'void *' argument of
326                  * the callback down to 'FLAC__FileDecoder *'.
327                  */
328                 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);
329                 FLAC__file_decoder_set_metadata_callback(decoder_session->decoder.flac.file, (void (*)(const FLAC__FileDecoder *, const FLAC__StreamMetadata *, void *))metadata_callback);
330                 FLAC__file_decoder_set_error_callback(decoder_session->decoder.flac.file, (void (*)(const FLAC__FileDecoder *, FLAC__StreamDecoderErrorStatus, void *))error_callback);
331                 FLAC__file_decoder_set_client_data(decoder_session->decoder.flac.file, decoder_session);
332
333                 if(FLAC__file_decoder_init(decoder_session->decoder.flac.file) != FLAC__FILE_DECODER_OK) {
334                         print_error_with_state(decoder_session, "ERROR initializing decoder");
335                         return false;
336                 }
337         }
338
339         return true;
340 }
341
342 FLAC__bool DecoderSession_process(DecoderSession *d)
343 {
344         if(d->skip > 0) {
345 #ifdef FLAC__HAS_OGG
346                 if(d->is_ogg) { /*@@@ (move this check into main.c) */
347                         fprintf(stderr, "%s: ERROR, can't skip when decoding Ogg-FLAC yet; convert to native-FLAC first\n", d->inbasefilename);
348                         return false;
349                 }
350 #endif
351                 if(!FLAC__file_decoder_process_until_end_of_metadata(d->decoder.flac.file)) {
352                         print_error_with_state(d, "ERROR while decoding metadata");
353                         return false;
354                 }
355                 if(d->abort_flag)
356                         return false;
357                 if(!FLAC__file_decoder_seek_absolute(d->decoder.flac.file, d->skip)) {
358                         print_error_with_state(d, "ERROR seeking while skipping bytes");
359                         return false;
360                 }
361                 if(!FLAC__file_decoder_process_until_end_of_file(d->decoder.flac.file)) {
362                         if(d->verbose) fprintf(stderr, "\n");
363                         print_error_with_state(d, "ERROR while decoding frames");
364                         return false;
365                 }
366                 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) {
367                         if(d->verbose) fprintf(stderr, "\n");
368                         print_error_with_state(d, "ERROR during decoding");
369                         return false;
370                 }
371         }
372         else {
373 #ifdef FLAC__HAS_OGG
374                 if(d->is_ogg) {
375                         if(!OggFLAC__stream_decoder_process_until_end_of_stream(d->decoder.ogg.stream)) {
376                                 if(d->verbose) fprintf(stderr, "\n");
377                                 print_error_with_state(d, "ERROR while decoding data");
378                                 return false;
379                         }
380                         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) {
381                                 if(d->verbose) fprintf(stderr, "\n");
382                                 print_error_with_state(d, "ERROR during decoding");
383                                 return false;
384                         }
385                 }
386                 else
387 #endif
388                 {
389                         if(!FLAC__file_decoder_process_until_end_of_file(d->decoder.flac.file)) {
390                                 if(d->verbose) fprintf(stderr, "\n");
391                                 print_error_with_state(d, "ERROR while decoding data");
392                                 return false;
393                         }
394                         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) {
395                                 if(d->verbose) fprintf(stderr, "\n");
396                                 print_error_with_state(d, "ERROR during decoding");
397                                 return false;
398                         }
399                 }
400         }
401
402         return true;
403 }
404
405 int DecoderSession_finish_ok(DecoderSession *d)
406 {
407         FLAC__bool md5_failure = false;
408
409 #ifdef FLAC__HAS_OGG
410         if(d->is_ogg) {
411                 if(d->decoder.ogg.stream) {
412                         OggFLAC__stream_decoder_finish(d->decoder.ogg.stream);
413                         md5_failure = false;
414                         print_stats(d);
415                         OggFLAC__stream_decoder_delete(d->decoder.ogg.stream);
416                 }
417         }
418         else
419 #endif
420         {
421                 if(d->decoder.flac.file) {
422                         md5_failure = !FLAC__file_decoder_finish(d->decoder.flac.file);
423                         print_stats(d);
424                         FLAC__file_decoder_delete(d->decoder.flac.file);
425                 }
426         }
427         if(d->analysis_mode)
428                 flac__analyze_finish(d->aopts);
429         if(md5_failure) {
430                 fprintf(stderr, "\r%s: WARNING, MD5 signature mismatch\n", d->inbasefilename);
431         }
432         else {
433                 if(d->verbose)
434                         fprintf(stderr, "\r%s: %s         \n", d->inbasefilename, d->test_only? "ok           ":d->analysis_mode?"done           ":"done");
435         }
436         DecoderSession_destroy(d, /*error_occurred=*/false);
437         if(d->is_wave_out && d->wave_chunk_size_fixup.needs_fixup)
438                 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))
439                         return 1;
440         return 0;
441 }
442
443 int DecoderSession_finish_error(DecoderSession *d)
444 {
445 #ifdef FLAC__HAS_OGG
446         if(d->is_ogg) {
447                 if(d->decoder.ogg.stream) {
448                         OggFLAC__stream_decoder_finish(d->decoder.ogg.stream);
449                         OggFLAC__stream_decoder_delete(d->decoder.ogg.stream);
450                 }
451         }
452         else
453 #endif
454         {
455                 if(d->decoder.flac.file) {
456                         FLAC__file_decoder_finish(d->decoder.flac.file);
457                         FLAC__file_decoder_delete(d->decoder.flac.file);
458                 }
459         }
460         if(d->analysis_mode)
461                 flac__analyze_finish(d->aopts);
462         DecoderSession_destroy(d, /*error_occurred=*/true);
463         return 1;
464 }
465
466 FLAC__bool write_little_endian_uint16(FILE *f, FLAC__uint16 val)
467 {
468         FLAC__byte *b = (FLAC__byte*)(&val);
469         if(is_big_endian_host_) {
470                 FLAC__byte tmp;
471                 tmp = b[1]; b[1] = b[0]; b[0] = tmp;
472         }
473         return fwrite(b, 1, 2, f) == 2;
474 }
475
476 FLAC__bool write_little_endian_uint32(FILE *f, FLAC__uint32 val)
477 {
478         FLAC__byte *b = (FLAC__byte*)(&val);
479         if(is_big_endian_host_) {
480                 FLAC__byte tmp;
481                 tmp = b[3]; b[3] = b[0]; b[0] = tmp;
482                 tmp = b[2]; b[2] = b[1]; b[1] = tmp;
483         }
484         return fwrite(b, 1, 4, f) == 4;
485 }
486
487 FLAC__bool fixup_wave_chunk_size(const char *outfilename, unsigned riff_offset, unsigned data_offset, FLAC__uint32 data_size)
488 {
489         FILE *f = fopen(outfilename, "r+b");
490         if(0 == f) {
491                 fprintf(stderr, "ERROR, couldn't open file %s while fixing up WAVE chunk size\n", outfilename);
492                 return false;
493         }
494         if(fseek(f, riff_offset, SEEK_SET) < 0) {
495                 fprintf(stderr, "ERROR, couldn't seek in file %s while fixing up WAVE chunk size\n", outfilename);
496                 fclose(f);
497                 return false;
498         }
499         if(!write_little_endian_uint32(f, data_size + 36)) {
500                 fprintf(stderr, "ERROR, couldn't write size in file %s while fixing up WAVE chunk size\n", outfilename);
501                 fclose(f);
502                 return false;
503         }
504         if(fseek(f, data_offset, SEEK_SET) < 0) {
505                 fprintf(stderr, "ERROR, couldn't seek in file %s while fixing up WAVE chunk size\n", outfilename);
506                 fclose(f);
507                 return false;
508         }
509         if(!write_little_endian_uint32(f, data_size)) {
510                 fprintf(stderr, "ERROR, couldn't write size in file %s while fixing up WAVE chunk size\n", outfilename);
511                 fclose(f);
512                 return false;
513         }
514         fclose(f);
515         return true;
516 }
517
518 #ifdef FLAC__HAS_OGG
519 FLAC__StreamDecoderReadStatus read_callback(const OggFLAC__StreamDecoder *decoder, FLAC__byte buffer[], unsigned *bytes, void *client_data)
520 {
521         DecoderSession *decoder_session = (DecoderSession*)client_data;
522         FILE *fin = decoder_session->fin;
523         size_t bytes_read;
524
525         (void)decoder; /* avoid compiler warning */
526
527         if (decoder_session->abort_flag)
528                 return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
529
530         if(feof(fin))
531                 return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
532
533         bytes_read = fread(buffer, 1, *bytes, fin);
534
535         if(ferror(fin))
536                 return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
537
538         *bytes = (unsigned)bytes_read;
539
540         return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
541 }
542 #endif
543
544 FLAC__StreamDecoderWriteStatus write_callback(const void *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
545 {
546         DecoderSession *decoder_session = (DecoderSession*)client_data;
547         FILE *fout = decoder_session->fout;
548         const unsigned bps = frame->header.bits_per_sample, channels = frame->header.channels;
549         FLAC__bool is_big_endian = (decoder_session->is_wave_out? false : decoder_session->is_big_endian);
550         FLAC__bool is_unsigned_samples = (decoder_session->is_wave_out? bps<=8 : decoder_session->is_unsigned_samples);
551         unsigned wide_samples = frame->header.blocksize, wide_sample, sample, channel, byte;
552         static FLAC__int8 s8buffer[FLAC__MAX_BLOCK_SIZE * FLAC__MAX_CHANNELS * sizeof(FLAC__int32)]; /* WATCHOUT: can be up to 2 megs */
553         FLAC__uint8  *u8buffer  = (FLAC__uint8  *)s8buffer;
554         FLAC__int16  *s16buffer = (FLAC__int16  *)s8buffer;
555         FLAC__uint16 *u16buffer = (FLAC__uint16 *)s8buffer;
556         FLAC__int32  *s32buffer = (FLAC__int32  *)s8buffer;
557         FLAC__uint32 *u32buffer = (FLAC__uint32 *)s8buffer;
558
559         (void)decoder;
560
561         if(decoder_session->abort_flag)
562                 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
563
564         if(bps != decoder_session->bps) {
565                 fprintf(stderr, "%s: ERROR, bits-per-sample is %u in frame but %u in STREAMINFO\n", decoder_session->inbasefilename, bps, decoder_session->bps);
566                 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
567         }
568         if(channels != decoder_session->channels) {
569                 fprintf(stderr, "%s: ERROR, channels is %u in frame but %u in STREAMINFO\n", decoder_session->inbasefilename, channels, decoder_session->channels);
570                 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
571         }
572         if(frame->header.sample_rate != decoder_session->sample_rate) {
573                 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);
574                 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
575         }
576
577         decoder_session->samples_processed += wide_samples;
578         decoder_session->frame_counter++;
579
580         if(decoder_session->verbose && !(decoder_session->frame_counter & 0x3f))
581                 print_stats(decoder_session);
582
583         if(decoder_session->analysis_mode) {
584                 flac__analyze_frame(frame, decoder_session->frame_counter-1, decoder_session->aopts, fout);
585         }
586         else if(!decoder_session->test_only) {
587                 if(bps == 8) {
588                         if(is_unsigned_samples) {
589                                 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
590                                         for(channel = 0; channel < channels; channel++, sample++)
591                                                 u8buffer[sample] = (FLAC__uint8)(buffer[channel][wide_sample] + 0x80);
592                         }
593                         else {
594                                 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
595                                         for(channel = 0; channel < channels; channel++, sample++)
596                                                 s8buffer[sample] = (FLAC__int8)(buffer[channel][wide_sample]);
597                         }
598                         if(fwrite(u8buffer, 1, sample, fout) != sample)
599                                 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
600                 }
601                 else if(bps == 16) {
602                         if(is_unsigned_samples) {
603                                 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
604                                         for(channel = 0; channel < channels; channel++, sample++)
605                                                 u16buffer[sample] = (FLAC__uint16)(buffer[channel][wide_sample] + 0x8000);
606                         }
607                         else {
608                                 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
609                                         for(channel = 0; channel < channels; channel++, sample++)
610                                                 s16buffer[sample] = (FLAC__int16)(buffer[channel][wide_sample]);
611                         }
612                         if(is_big_endian != is_big_endian_host_) {
613                                 unsigned char tmp;
614                                 const unsigned bytes = sample * 2;
615                                 for(byte = 0; byte < bytes; byte += 2) {
616                                         tmp = u8buffer[byte];
617                                         u8buffer[byte] = u8buffer[byte+1];
618                                         u8buffer[byte+1] = tmp;
619                                 }
620                         }
621                         if(fwrite(u16buffer, 2, sample, fout) != sample)
622                                 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
623                 }
624                 else if(bps == 24) {
625                         if(is_unsigned_samples) {
626                                 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
627                                         for(channel = 0; channel < channels; channel++, sample++)
628                                                 u32buffer[sample] = buffer[channel][wide_sample] + 0x800000;
629                         }
630                         else {
631                                 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
632                                         for(channel = 0; channel < channels; channel++, sample++)
633                                                 s32buffer[sample] = buffer[channel][wide_sample];
634                         }
635                         if(is_big_endian != is_big_endian_host_) {
636                                 unsigned char tmp;
637                                 const unsigned bytes = sample * 4;
638                                 for(byte = 0; byte < bytes; byte += 4) {
639                                         tmp = u8buffer[byte];
640                                         u8buffer[byte] = u8buffer[byte+3];
641                                         u8buffer[byte+3] = tmp;
642                                         tmp = u8buffer[byte+1];
643                                         u8buffer[byte+1] = u8buffer[byte+2];
644                                         u8buffer[byte+2] = tmp;
645                                 }
646                         }
647                         if(is_big_endian) {
648                                 unsigned lbyte;
649                                 const unsigned bytes = sample * 4;
650                                 for(lbyte = byte = 0; byte < bytes; ) {
651                                         byte++;
652                                         u8buffer[lbyte++] = u8buffer[byte++];
653                                         u8buffer[lbyte++] = u8buffer[byte++];
654                                         u8buffer[lbyte++] = u8buffer[byte++];
655                                 }
656                         }
657                         else {
658                                 unsigned lbyte;
659                                 const unsigned bytes = sample * 4;
660                                 for(lbyte = byte = 0; byte < bytes; ) {
661                                         u8buffer[lbyte++] = u8buffer[byte++];
662                                         u8buffer[lbyte++] = u8buffer[byte++];
663                                         u8buffer[lbyte++] = u8buffer[byte++];
664                                         byte++;
665                                 }
666                         }
667                         if(fwrite(u8buffer, 3, sample, fout) != sample)
668                                 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
669                 }
670                 else {
671                         FLAC__ASSERT(0);
672                 }
673         }
674         return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
675 }
676
677 void metadata_callback(const void *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
678 {
679         DecoderSession *decoder_session = (DecoderSession*)client_data;
680         (void)decoder;
681         if(metadata->type == FLAC__METADATA_TYPE_STREAMINFO) {
682                 /* remember, metadata->data.stream_info.total_samples can be 0, meaning 'unknown' */
683                 if(metadata->data.stream_info.total_samples > 0 && decoder_session->skip >= metadata->data.stream_info.total_samples) {
684                         fprintf(stderr, "%s: ERROR trying to skip more samples than in stream\n", decoder_session->inbasefilename);
685                         decoder_session->abort_flag = true;
686                         return;
687                 }
688                 else if(metadata->data.stream_info.total_samples == 0 && decoder_session->skip > 0) {
689                         fprintf(stderr, "%s: ERROR, can't skip when FLAC metadata has total sample count of 0\n", decoder_session->inbasefilename);
690                         decoder_session->abort_flag = true;
691                         return;
692                 }
693                 else
694                         decoder_session->total_samples = metadata->data.stream_info.total_samples - decoder_session->skip;
695                 decoder_session->bps = metadata->data.stream_info.bits_per_sample;
696                 decoder_session->channels = metadata->data.stream_info.channels;
697                 decoder_session->sample_rate = metadata->data.stream_info.sample_rate;
698
699                 if(decoder_session->bps != 8 && decoder_session->bps != 16 && decoder_session->bps != 24) {
700                         fprintf(stderr, "%s: ERROR: bits per sample is not 8/16/24\n", decoder_session->inbasefilename);
701                         decoder_session->abort_flag = true;
702                         return;
703                 }
704
705                 /* write the WAVE headers if necessary */
706                 if(!decoder_session->analysis_mode && !decoder_session->test_only && decoder_session->is_wave_out) {
707                         FLAC__uint64 data_size = decoder_session->total_samples * decoder_session->channels * ((decoder_session->bps+7)/8);
708                         if(decoder_session->total_samples == 0) {
709                                 if(decoder_session->fout == stdout) {
710                                         fprintf(stderr, "%s: WARNING, don't have accurate sample count available for WAVE header.\n", decoder_session->inbasefilename);
711                                         fprintf(stderr, "             Generated WAVE file will have a data chunk size of 0.  Try\n");
712                                         fprintf(stderr, "             decoding directly to a file instead.\n");
713                                 }
714                                 else {
715                                         decoder_session->wave_chunk_size_fixup.needs_fixup = true;
716                                 }
717                         }
718                         if(data_size >= 0xFFFFFFDC) {
719                                 fprintf(stderr, "%s: ERROR: stream is too big to fit in a single WAVE file chunk\n", decoder_session->inbasefilename);
720                                 decoder_session->abort_flag = true;
721                                 return;
722                         }
723                         if(fwrite("RIFF", 1, 4, decoder_session->fout) != 4) decoder_session->abort_flag = true;
724                         if(decoder_session->wave_chunk_size_fixup.needs_fixup)
725                                 decoder_session->wave_chunk_size_fixup.riff_offset = ftell(decoder_session->fout);
726                         if(!write_little_endian_uint32(decoder_session->fout, (FLAC__uint32)(data_size+36))) decoder_session->abort_flag = true; /* filesize-8 */
727                         if(fwrite("WAVEfmt ", 1, 8, decoder_session->fout) != 8) decoder_session->abort_flag = true;
728                         if(fwrite("\020\000\000\000", 1, 4, decoder_session->fout) != 4) decoder_session->abort_flag = true; /* chunk size = 16 */
729                         if(fwrite("\001\000", 1, 2, decoder_session->fout) != 2) decoder_session->abort_flag = true; /* compression code == 1 */
730                         if(!write_little_endian_uint16(decoder_session->fout, (FLAC__uint16)(decoder_session->channels))) decoder_session->abort_flag = true;
731                         if(!write_little_endian_uint32(decoder_session->fout, decoder_session->sample_rate)) decoder_session->abort_flag = true;
732                         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 ??? */
733                         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 */
734                         if(!write_little_endian_uint16(decoder_session->fout, (FLAC__uint16)(decoder_session->bps))) decoder_session->abort_flag = true; /* bits per sample */
735                         if(fwrite("data", 1, 4, decoder_session->fout) != 4) decoder_session->abort_flag = true;
736                         if(decoder_session->wave_chunk_size_fixup.needs_fixup)
737                                 decoder_session->wave_chunk_size_fixup.data_offset = ftell(decoder_session->fout);
738                         if(!write_little_endian_uint32(decoder_session->fout, (FLAC__uint32)data_size)) decoder_session->abort_flag = true; /* data size */
739                 }
740         }
741 }
742
743 void error_callback(const void *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
744 {
745         DecoderSession *decoder_session = (DecoderSession*)client_data;
746         (void)decoder;
747         fprintf(stderr, "%s: *** Got error code %d:%s\n", decoder_session->inbasefilename, status, FLAC__StreamDecoderErrorStatusString[status]);
748         if(!decoder_session->continue_through_decode_errors)
749                 decoder_session->abort_flag = true;
750 }
751
752 void print_error_with_state(const DecoderSession *d, const char *message)
753 {
754         const int ilen = strlen(d->inbasefilename) + 1;
755
756         fprintf(stderr, "\n%s: %s\n", d->inbasefilename, message);
757
758 #ifdef FLAC__HAS_OGG
759         if(d->is_ogg) {
760                 const OggFLAC__StreamDecoderState osd_state = OggFLAC__stream_decoder_get_state(d->decoder.ogg.stream);
761                 if(osd_state != OggFLAC__STREAM_DECODER_FLAC_STREAM_DECODER_ERROR) {
762                         fprintf(stderr, "%*s state = %d:%s\n", ilen, "", (int)osd_state, OggFLAC__StreamDecoderStateString[osd_state]);
763                 }
764                 else {
765                         const FLAC__StreamDecoderState fsd_state = OggFLAC__stream_decoder_get_FLAC_stream_decoder_state(d->decoder.ogg.stream);
766                         fprintf(stderr, "%*s state = %d:%s\n", ilen, "", (int)fsd_state, FLAC__StreamDecoderStateString[fsd_state]);
767                 }
768         }
769         else
770 #endif
771         {
772                 const FLAC__FileDecoderState ffd_state = FLAC__file_decoder_get_state(d->decoder.flac.file);
773                 if(ffd_state != FLAC__FILE_DECODER_SEEKABLE_STREAM_DECODER_ERROR) {
774                         fprintf(stderr, "%*s state = %d:%s\n", ilen, "", (int)ffd_state, FLAC__FileDecoderStateString[ffd_state]);
775                 }
776                 else {
777                         const FLAC__SeekableStreamDecoderState fssd_state = FLAC__file_decoder_get_seekable_stream_decoder_state(d->decoder.flac.file);
778                         if(fssd_state != FLAC__SEEKABLE_STREAM_DECODER_STREAM_DECODER_ERROR) {
779                                 fprintf(stderr, "%*s state = %d:%s\n", ilen, "", (int)fssd_state, FLAC__SeekableStreamDecoderStateString[fssd_state]);
780                         }
781                         else {
782                                 const FLAC__StreamDecoderState fsd_state = FLAC__file_decoder_get_stream_decoder_state(d->decoder.flac.file);
783                                 fprintf(stderr, "%*s state = %d:%s\n", ilen, "", (int)fsd_state, FLAC__StreamDecoderStateString[fsd_state]);
784                         }
785                 }
786         }
787 }
788
789 void print_stats(const DecoderSession *decoder_session)
790 {
791         if(decoder_session->verbose) {
792 #if defined _MSC_VER || defined __MINGW32__
793                 /* with VC++ you have to spoon feed it the casting */
794                 const double progress = (double)(FLAC__int64)decoder_session->samples_processed / (double)(FLAC__int64)decoder_session->total_samples * 100.0;
795 #else
796                 const double progress = (double)decoder_session->samples_processed / (double)decoder_session->total_samples * 100.0;
797 #endif
798                 if(decoder_session->total_samples > 0) {
799                         fprintf(stderr, "\r%s: %s%u%% complete",
800                                 decoder_session->inbasefilename,
801                                 decoder_session->test_only? "testing, " : decoder_session->analysis_mode? "analyzing, " : "",
802                                 (unsigned)floor(progress + 0.5)
803                         );
804                 }
805                 else {
806                         fprintf(stderr, "\r%s: %s %u samples",
807                                 decoder_session->inbasefilename,
808                                 decoder_session->test_only? "tested" : decoder_session->analysis_mode? "analyzed" : "wrote",
809                                 (unsigned)decoder_session->samples_processed
810                         );
811                 }
812         }
813 }