fixes based on a pass over everything with autoconf/automake
[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, 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, 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, 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, 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                 OggFLAC__stream_decoder_set_read_callback(decoder_session->decoder.ogg.stream, read_callback);
287                 /*
288                  * The three ugly casts here are to 'downcast' the 'void *' argument of
289                  * the callback down to 'FLAC__StreamDecoder *'.  In C++ this would be
290                  * unnecessary but here the cast makes the C compiler happy.
291                  */
292                 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);
293                 OggFLAC__stream_decoder_set_metadata_callback(decoder_session->decoder.ogg.stream, (void (*)(const OggFLAC__StreamDecoder *, const FLAC__StreamMetadata *, void *))metadata_callback);
294                 OggFLAC__stream_decoder_set_error_callback(decoder_session->decoder.ogg.stream, (void (*)(const OggFLAC__StreamDecoder *, FLAC__StreamDecoderErrorStatus, void *))error_callback);
295                 OggFLAC__stream_decoder_set_client_data(decoder_session->decoder.ogg.stream, decoder_session);
296
297                 if(OggFLAC__stream_decoder_init(decoder_session->decoder.ogg.stream) != OggFLAC__STREAM_DECODER_OK) {
298                         print_error_with_state(decoder_session, "ERROR initializing decoder");
299                         return false;
300                 }
301         }
302         else
303 #endif
304         {
305                 decoder_session->decoder.flac.file = FLAC__file_decoder_new();
306
307                 if(0 == decoder_session->decoder.flac.file) {
308                         fprintf(stderr, "%s: ERROR creating the decoder instance\n", decoder_session->inbasefilename);
309                         return false;
310                 }
311
312                 FLAC__file_decoder_set_md5_checking(decoder_session->decoder.flac.file, true);
313                 FLAC__file_decoder_set_filename(decoder_session->decoder.flac.file, infilename);
314                 /*
315                  * The three ugly casts here are to 'downcast' the 'void *' argument of
316                  * the callback down to 'FLAC__FileDecoder *'.
317                  */
318                 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);
319                 FLAC__file_decoder_set_metadata_callback(decoder_session->decoder.flac.file, (void (*)(const FLAC__FileDecoder *, const FLAC__StreamMetadata *, void *))metadata_callback);
320                 FLAC__file_decoder_set_error_callback(decoder_session->decoder.flac.file, (void (*)(const FLAC__FileDecoder *, FLAC__StreamDecoderErrorStatus, void *))error_callback);
321                 FLAC__file_decoder_set_client_data(decoder_session->decoder.flac.file, decoder_session);
322
323                 if(FLAC__file_decoder_init(decoder_session->decoder.flac.file) != FLAC__FILE_DECODER_OK) {
324                         print_error_with_state(decoder_session, "ERROR initializing decoder");
325                         return false;
326                 }
327         }
328
329         return true;
330 }
331
332 FLAC__bool DecoderSession_process(DecoderSession *d)
333 {
334         if(d->skip > 0) {
335 #ifdef FLAC__HAS_OGG
336                 if(d->is_ogg) { /*@@@ (move this check into main.c) */
337                         fprintf(stderr, "%s: ERROR, can't skip when decoding Ogg-FLAC yet; convert to native-FLAC first\n", d->inbasefilename);
338                         return false;
339                 }
340 #endif
341                 if(!FLAC__file_decoder_process_until_end_of_metadata(d->decoder.flac.file)) {
342                         print_error_with_state(d, "ERROR while decoding metadata");
343                         return false;
344                 }
345                 if(d->abort_flag)
346                         return false;
347                 if(!FLAC__file_decoder_seek_absolute(d->decoder.flac.file, d->skip)) {
348                         print_error_with_state(d, "ERROR seeking while skipping bytes");
349                         return false;
350                 }
351                 if(!FLAC__file_decoder_process_until_end_of_file(d->decoder.flac.file)) {
352                         if(d->verbose) fprintf(stderr, "\n");
353                         print_error_with_state(d, "ERROR while decoding frames");
354                         return false;
355                 }
356                 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) {
357                         if(d->verbose) fprintf(stderr, "\n");
358                         print_error_with_state(d, "ERROR during decoding");
359                         return false;
360                 }
361         }
362         else {
363 #ifdef FLAC__HAS_OGG
364                 if(d->is_ogg) {
365                         if(!OggFLAC__stream_decoder_process_until_end_of_stream(d->decoder.ogg.stream)) {
366                                 if(d->verbose) fprintf(stderr, "\n");
367                                 print_error_with_state(d, "ERROR while decoding data");
368                                 return false;
369                         }
370                         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) {
371                                 if(d->verbose) fprintf(stderr, "\n");
372                                 print_error_with_state(d, "ERROR during decoding");
373                                 return false;
374                         }
375                 }
376                 else
377 #endif
378                 {
379                         if(!FLAC__file_decoder_process_until_end_of_file(d->decoder.flac.file)) {
380                                 if(d->verbose) fprintf(stderr, "\n");
381                                 print_error_with_state(d, "ERROR while decoding data");
382                                 return false;
383                         }
384                         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) {
385                                 if(d->verbose) fprintf(stderr, "\n");
386                                 print_error_with_state(d, "ERROR during decoding");
387                                 return false;
388                         }
389                 }
390         }
391
392         return true;
393 }
394
395 int DecoderSession_finish_ok(DecoderSession *d)
396 {
397         FLAC__bool md5_failure = false;
398
399 #ifdef FLAC__HAS_OGG
400         if(d->is_ogg) {
401                 if(d->decoder.ogg.stream) {
402                         OggFLAC__stream_decoder_finish(d->decoder.ogg.stream);
403                         md5_failure = false;
404                         print_stats(d);
405                         OggFLAC__stream_decoder_delete(d->decoder.ogg.stream);
406                 }
407         }
408         else
409 #endif
410         {
411                 if(d->decoder.flac.file) {
412                         md5_failure = !FLAC__file_decoder_finish(d->decoder.flac.file);
413                         print_stats(d);
414                         FLAC__file_decoder_delete(d->decoder.flac.file);
415                 }
416         }
417         if(d->analysis_mode)
418                 flac__analyze_finish(d->aopts);
419         if(md5_failure) {
420                 fprintf(stderr, "\r%s: WARNING, MD5 signature mismatch\n", d->inbasefilename);
421         }
422         else {
423                 if(d->verbose)
424                         fprintf(stderr, "\r%s: %s         \n", d->inbasefilename, d->test_only? "ok           ":d->analysis_mode?"done           ":"done");
425         }
426         DecoderSession_destroy(d, /*error_occurred=*/false);
427         if(d->is_wave_out && d->wave_chunk_size_fixup.needs_fixup)
428                 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))
429                         return 1;
430         return 0;
431 }
432
433 int DecoderSession_finish_error(DecoderSession *d)
434 {
435 #ifdef FLAC__HAS_OGG
436         if(d->is_ogg) {
437                 if(d->decoder.ogg.stream) {
438                         OggFLAC__stream_decoder_finish(d->decoder.ogg.stream);
439                         OggFLAC__stream_decoder_delete(d->decoder.ogg.stream);
440                 }
441         }
442         else
443 #endif
444         {
445                 if(d->decoder.flac.file) {
446                         FLAC__file_decoder_finish(d->decoder.flac.file);
447                         FLAC__file_decoder_delete(d->decoder.flac.file);
448                 }
449         }
450         if(d->analysis_mode)
451                 flac__analyze_finish(d->aopts);
452         DecoderSession_destroy(d, /*error_occurred=*/true);
453         return 1;
454 }
455
456 FLAC__bool write_little_endian_uint16(FILE *f, FLAC__uint16 val)
457 {
458         FLAC__byte *b = (FLAC__byte*)(&val);
459         if(is_big_endian_host_) {
460                 FLAC__byte tmp;
461                 tmp = b[1]; b[1] = b[0]; b[0] = tmp;
462         }
463         return fwrite(b, 1, 2, f) == 2;
464 }
465
466 FLAC__bool write_little_endian_uint32(FILE *f, FLAC__uint32 val)
467 {
468         FLAC__byte *b = (FLAC__byte*)(&val);
469         if(is_big_endian_host_) {
470                 FLAC__byte tmp;
471                 tmp = b[3]; b[3] = b[0]; b[0] = tmp;
472                 tmp = b[2]; b[2] = b[1]; b[1] = tmp;
473         }
474         return fwrite(b, 1, 4, f) == 4;
475 }
476
477 FLAC__bool fixup_wave_chunk_size(const char *outfilename, unsigned riff_offset, unsigned data_offset, FLAC__uint32 data_size)
478 {
479         FILE *f = fopen(outfilename, "r+b");
480         if(0 == f) {
481                 fprintf(stderr, "ERROR, couldn't open file %s while fixing up WAVE chunk size\n", outfilename);
482                 return false;
483         }
484         if(fseek(f, riff_offset, SEEK_SET) < 0) {
485                 fprintf(stderr, "ERROR, couldn't seek in file %s while fixing up WAVE chunk size\n", outfilename);
486                 fclose(f);
487                 return false;
488         }
489         if(!write_little_endian_uint32(f, data_size + 36)) {
490                 fprintf(stderr, "ERROR, couldn't write size in file %s while fixing up WAVE chunk size\n", outfilename);
491                 fclose(f);
492                 return false;
493         }
494         if(fseek(f, data_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)) {
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         fclose(f);
505         return true;
506 }
507
508 #ifdef FLAC__HAS_OGG
509 FLAC__StreamDecoderReadStatus read_callback(const OggFLAC__StreamDecoder *decoder, FLAC__byte buffer[], unsigned *bytes, void *client_data)
510 {
511         DecoderSession *decoder_session = (DecoderSession*)client_data;
512         FILE *fin = decoder_session->fin;
513         size_t bytes_read;
514
515         (void)decoder; /* avoid compiler warning */
516
517         if (decoder_session->abort_flag)
518                 return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
519
520         if(feof(fin))
521                 return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
522
523         bytes_read = fread(buffer, 1, *bytes, fin);
524
525         if(ferror(fin))
526                 return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
527
528         *bytes = (unsigned)bytes_read;
529
530         return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
531 }
532 #endif
533
534 FLAC__StreamDecoderWriteStatus write_callback(const void *decoder, const FLAC__Frame *frame, const FLAC__int32 *buffer[], void *client_data)
535 {
536         DecoderSession *decoder_session = (DecoderSession*)client_data;
537         FILE *fout = decoder_session->fout;
538         unsigned bps = decoder_session->bps, channels = decoder_session->channels;
539         FLAC__bool is_big_endian = (decoder_session->is_wave_out? false : decoder_session->is_big_endian);
540         FLAC__bool is_unsigned_samples = (decoder_session->is_wave_out? bps<=8 : decoder_session->is_unsigned_samples);
541         unsigned wide_samples = frame->header.blocksize, wide_sample, sample, channel, byte;
542         static FLAC__int8 s8buffer[FLAC__MAX_BLOCK_SIZE * FLAC__MAX_CHANNELS * sizeof(FLAC__int32)]; /* WATCHOUT: can be up to 2 megs */
543         FLAC__uint8  *u8buffer  = (FLAC__uint8  *)s8buffer;
544         FLAC__int16  *s16buffer = (FLAC__int16  *)s8buffer;
545         FLAC__uint16 *u16buffer = (FLAC__uint16 *)s8buffer;
546         FLAC__int32  *s32buffer = (FLAC__int32  *)s8buffer;
547         FLAC__uint32 *u32buffer = (FLAC__uint32 *)s8buffer;
548
549         (void)decoder;
550
551         if(decoder_session->abort_flag)
552                 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
553
554         decoder_session->samples_processed += wide_samples;
555         decoder_session->frame_counter++;
556
557         if(decoder_session->verbose && !(decoder_session->frame_counter & 0x3f))
558                 print_stats(decoder_session);
559
560         if(decoder_session->analysis_mode) {
561                 flac__analyze_frame(frame, decoder_session->frame_counter-1, decoder_session->aopts, fout);
562         }
563         else if(!decoder_session->test_only) {
564                 if(bps == 8) {
565                         if(is_unsigned_samples) {
566                                 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
567                                         for(channel = 0; channel < channels; channel++, sample++)
568                                                 u8buffer[sample] = (FLAC__uint8)(buffer[channel][wide_sample] + 0x80);
569                         }
570                         else {
571                                 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
572                                         for(channel = 0; channel < channels; channel++, sample++)
573                                                 s8buffer[sample] = (FLAC__int8)(buffer[channel][wide_sample]);
574                         }
575                         if(fwrite(u8buffer, 1, sample, fout) != sample)
576                                 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
577                 }
578                 else if(bps == 16) {
579                         if(is_unsigned_samples) {
580                                 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
581                                         for(channel = 0; channel < channels; channel++, sample++)
582                                                 u16buffer[sample] = (FLAC__uint16)(buffer[channel][wide_sample] + 0x8000);
583                         }
584                         else {
585                                 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
586                                         for(channel = 0; channel < channels; channel++, sample++)
587                                                 s16buffer[sample] = (FLAC__int16)(buffer[channel][wide_sample]);
588                         }
589                         if(is_big_endian != is_big_endian_host_) {
590                                 unsigned char tmp;
591                                 const unsigned bytes = sample * 2;
592                                 for(byte = 0; byte < bytes; byte += 2) {
593                                         tmp = u8buffer[byte];
594                                         u8buffer[byte] = u8buffer[byte+1];
595                                         u8buffer[byte+1] = tmp;
596                                 }
597                         }
598                         if(fwrite(u16buffer, 2, sample, fout) != sample)
599                                 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
600                 }
601                 else if(bps == 24) {
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                                                 u32buffer[sample] = buffer[channel][wide_sample] + 0x800000;
606                         }
607                         else {
608                                 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
609                                         for(channel = 0; channel < channels; channel++, sample++)
610                                                 s32buffer[sample] = buffer[channel][wide_sample];
611                         }
612                         if(is_big_endian != is_big_endian_host_) {
613                                 unsigned char tmp;
614                                 const unsigned bytes = sample * 4;
615                                 for(byte = 0; byte < bytes; byte += 4) {
616                                         tmp = u8buffer[byte];
617                                         u8buffer[byte] = u8buffer[byte+3];
618                                         u8buffer[byte+3] = tmp;
619                                         tmp = u8buffer[byte+1];
620                                         u8buffer[byte+1] = u8buffer[byte+2];
621                                         u8buffer[byte+2] = tmp;
622                                 }
623                         }
624                         if(is_big_endian) {
625                                 unsigned lbyte;
626                                 const unsigned bytes = sample * 4;
627                                 for(lbyte = byte = 0; byte < bytes; ) {
628                                         byte++;
629                                         u8buffer[lbyte++] = u8buffer[byte++];
630                                         u8buffer[lbyte++] = u8buffer[byte++];
631                                         u8buffer[lbyte++] = u8buffer[byte++];
632                                 }
633                         }
634                         else {
635                                 unsigned lbyte;
636                                 const unsigned bytes = sample * 4;
637                                 for(lbyte = byte = 0; byte < bytes; ) {
638                                         u8buffer[lbyte++] = u8buffer[byte++];
639                                         u8buffer[lbyte++] = u8buffer[byte++];
640                                         u8buffer[lbyte++] = u8buffer[byte++];
641                                         byte++;
642                                 }
643                         }
644                         if(fwrite(u8buffer, 3, sample, fout) != sample)
645                                 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
646                 }
647                 else {
648                         FLAC__ASSERT(0);
649                 }
650         }
651         return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
652 }
653
654 void metadata_callback(const void *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
655 {
656         DecoderSession *decoder_session = (DecoderSession*)client_data;
657         (void)decoder;
658         if(metadata->type == FLAC__METADATA_TYPE_STREAMINFO) {
659                 /* remember, metadata->data.stream_info.total_samples can be 0, meaning 'unknown' */
660                 if(metadata->data.stream_info.total_samples > 0 && decoder_session->skip >= metadata->data.stream_info.total_samples) {
661                         fprintf(stderr, "%s: ERROR trying to skip more samples than in stream\n", decoder_session->inbasefilename);
662                         decoder_session->abort_flag = true;
663                         return;
664                 }
665                 else if(metadata->data.stream_info.total_samples == 0 && decoder_session->skip > 0) {
666                         fprintf(stderr, "%s: ERROR, can't skip when FLAC metadata has total sample count of 0\n", decoder_session->inbasefilename);
667                         decoder_session->abort_flag = true;
668                         return;
669                 }
670                 else
671                         decoder_session->total_samples = metadata->data.stream_info.total_samples - decoder_session->skip;
672                 decoder_session->bps = metadata->data.stream_info.bits_per_sample;
673                 decoder_session->channels = metadata->data.stream_info.channels;
674                 decoder_session->sample_rate = metadata->data.stream_info.sample_rate;
675
676                 if(decoder_session->bps != 8 && decoder_session->bps != 16 && decoder_session->bps != 24) {
677                         fprintf(stderr, "%s: ERROR: bits per sample is not 8/16/24\n", decoder_session->inbasefilename);
678                         decoder_session->abort_flag = true;
679                         return;
680                 }
681
682                 /* write the WAVE headers if necessary */
683                 if(!decoder_session->analysis_mode && !decoder_session->test_only && decoder_session->is_wave_out) {
684                         FLAC__uint64 data_size = decoder_session->total_samples * decoder_session->channels * ((decoder_session->bps+7)/8);
685                         if(decoder_session->total_samples == 0) {
686                                 if(decoder_session->fout == stdout) {
687                                         fprintf(stderr, "%s: WARNING, don't have accurate sample count available for WAVE header.\n", decoder_session->inbasefilename);
688                                         fprintf(stderr, "             Generated WAVE file will have a data chunk size of 0.  Try\n");
689                                         fprintf(stderr, "             decoding directly to a file instead.\n");
690                                 }
691                                 else {
692                                         decoder_session->wave_chunk_size_fixup.needs_fixup = true;
693                                 }
694                         }
695                         if(data_size >= 0xFFFFFFDC) {
696                                 fprintf(stderr, "%s: ERROR: stream is too big to fit in a single WAVE file chunk\n", decoder_session->inbasefilename);
697                                 decoder_session->abort_flag = true;
698                                 return;
699                         }
700                         if(fwrite("RIFF", 1, 4, decoder_session->fout) != 4) decoder_session->abort_flag = true;
701                         if(decoder_session->wave_chunk_size_fixup.needs_fixup)
702                                 decoder_session->wave_chunk_size_fixup.riff_offset = ftell(decoder_session->fout);
703                         if(!write_little_endian_uint32(decoder_session->fout, (FLAC__uint32)(data_size+36))) decoder_session->abort_flag = true; /* filesize-8 */
704                         if(fwrite("WAVEfmt ", 1, 8, decoder_session->fout) != 8) decoder_session->abort_flag = true;
705                         if(fwrite("\020\000\000\000", 1, 4, decoder_session->fout) != 4) decoder_session->abort_flag = true; /* chunk size = 16 */
706                         if(fwrite("\001\000", 1, 2, decoder_session->fout) != 2) decoder_session->abort_flag = true; /* compression code == 1 */
707                         if(!write_little_endian_uint16(decoder_session->fout, (FLAC__uint16)(decoder_session->channels))) decoder_session->abort_flag = true;
708                         if(!write_little_endian_uint32(decoder_session->fout, decoder_session->sample_rate)) decoder_session->abort_flag = true;
709                         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 ??? */
710                         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 */
711                         if(!write_little_endian_uint16(decoder_session->fout, (FLAC__uint16)(decoder_session->bps))) decoder_session->abort_flag = true; /* bits per sample */
712                         if(fwrite("data", 1, 4, decoder_session->fout) != 4) decoder_session->abort_flag = true;
713                         if(decoder_session->wave_chunk_size_fixup.needs_fixup)
714                                 decoder_session->wave_chunk_size_fixup.data_offset = ftell(decoder_session->fout);
715                         if(!write_little_endian_uint32(decoder_session->fout, (FLAC__uint32)data_size)) decoder_session->abort_flag = true; /* data size */
716                 }
717         }
718 }
719
720 void error_callback(const void *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
721 {
722         DecoderSession *decoder_session = (DecoderSession*)client_data;
723         (void)decoder;
724         fprintf(stderr, "%s: *** Got error code %d:%s\n", decoder_session->inbasefilename, status, FLAC__StreamDecoderErrorStatusString[status]);
725         if(!decoder_session->continue_through_decode_errors)
726                 decoder_session->abort_flag = true;
727 }
728
729 void print_error_with_state(const DecoderSession *d, const char *message)
730 {
731         const int ilen = strlen(d->inbasefilename) + 1;
732
733         fprintf(stderr, "\n%s: %s\n", d->inbasefilename, message);
734
735 #ifdef FLAC__HAS_OGG
736         if(d->is_ogg) {
737                 const OggFLAC__StreamDecoderState osd_state = OggFLAC__stream_decoder_get_state(d->decoder.ogg.stream);
738                 if(osd_state != OggFLAC__STREAM_DECODER_FLAC_STREAM_DECODER_ERROR) {
739                         fprintf(stderr, "%*s state = %d:%s\n", ilen, "", (int)osd_state, OggFLAC__StreamDecoderStateString[osd_state]);
740                 }
741                 else {
742                         const FLAC__StreamDecoderState fsd_state = OggFLAC__stream_decoder_get_FLAC_stream_decoder_state(d->decoder.ogg.stream);
743                         fprintf(stderr, "%*s state = %d:%s\n", ilen, "", (int)fsd_state, FLAC__StreamDecoderStateString[fsd_state]);
744                 }
745         }
746         else
747 #endif
748         {
749                 const FLAC__FileDecoderState ffd_state = FLAC__file_decoder_get_state(d->decoder.flac.file);
750                 if(ffd_state != FLAC__FILE_DECODER_SEEKABLE_STREAM_DECODER_ERROR) {
751                         fprintf(stderr, "%*s state = %d:%s\n", ilen, "", (int)ffd_state, FLAC__FileDecoderStateString[ffd_state]);
752                 }
753                 else {
754                         const FLAC__SeekableStreamDecoderState fssd_state = FLAC__file_decoder_get_seekable_stream_decoder_state(d->decoder.flac.file);
755                         if(fssd_state != FLAC__SEEKABLE_STREAM_DECODER_STREAM_DECODER_ERROR) {
756                                 fprintf(stderr, "%*s state = %d:%s\n", ilen, "", (int)fssd_state, FLAC__SeekableStreamDecoderStateString[fssd_state]);
757                         }
758                         else {
759                                 const FLAC__StreamDecoderState fsd_state = FLAC__file_decoder_get_stream_decoder_state(d->decoder.flac.file);
760                                 fprintf(stderr, "%*s state = %d:%s\n", ilen, "", (int)fsd_state, FLAC__StreamDecoderStateString[fsd_state]);
761                         }
762                 }
763         }
764 }
765
766 void print_stats(const DecoderSession *decoder_session)
767 {
768         if(decoder_session->verbose) {
769 #if defined _MSC_VER || defined __MINGW32__
770                 /* with VC++ you have to spoon feed it the casting */
771                 const double progress = (double)(FLAC__int64)decoder_session->samples_processed / (double)(FLAC__int64)decoder_session->total_samples * 100.0;
772 #else
773                 const double progress = (double)decoder_session->samples_processed / (double)decoder_session->total_samples * 100.0;
774 #endif
775                 if(decoder_session->total_samples > 0) {
776                         fprintf(stderr, "\r%s: %s%u%% complete",
777                                 decoder_session->inbasefilename,
778                                 decoder_session->test_only? "testing, " : decoder_session->analysis_mode? "analyzing, " : "",
779                                 (unsigned)floor(progress + 0.5)
780                         );
781                 }
782                 else {
783                         fprintf(stderr, "\r%s: %s %u samples",
784                                 decoder_session->inbasefilename,
785                                 decoder_session->test_only? "tested" : decoder_session->analysis_mode? "analyzed" : "wrote",
786                                 (unsigned)decoder_session->samples_processed
787                         );
788                 }
789         }
790 }