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