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