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