change unparseable frame handling, from a fatal error and FLAC__STREAM_DECODER_UNPARS...
[platform/upstream/flac.git] / src / flac / decode.c
1 /* flac - Command-line FLAC encoder/decoder
2  * Copyright (C) 2000,2001,2002,2003,2004,2005,2006  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 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 #if defined _MSC_VER || defined __MINGW32__
30 #include <sys/types.h> /* for off_t */
31 //@@@ [2G limit] hacks for MSVC6
32 #define fseeko fseek
33 #define ftello ftell
34 #endif
35 #include <errno.h>
36 #include <math.h> /* for floor() */
37 #include <stdio.h> /* for FILE etc. */
38 #include <string.h> /* for strcmp(), strerror() */
39 #include "FLAC/all.h"
40 #include "share/grabbag.h"
41 #include "share/replaygain_synthesis.h"
42 #include "decode.h"
43
44 #ifdef FLAC__HAS_OGG
45 #include "OggFLAC/file_decoder.h"
46 #endif
47
48 typedef struct {
49 #ifdef FLAC__HAS_OGG
50         FLAC__bool is_ogg;
51 #endif
52
53         FLAC__bool is_aiff_out;
54         FLAC__bool is_wave_out;
55         FLAC__bool continue_through_decode_errors;
56
57         struct {
58                 replaygain_synthesis_spec_t spec;
59                 FLAC__bool apply; /* 'spec.apply' is just a request; this 'apply' means we actually parsed the RG tags and are ready to go */
60                 double scale;
61                 DitherContext dither_context;
62         } replaygain;
63
64         FLAC__bool test_only;
65         FLAC__bool analysis_mode;
66         analysis_options aopts;
67         utils__SkipUntilSpecification *skip_specification;
68         utils__SkipUntilSpecification *until_specification; /* a canonicalized value of 0 mean end-of-stream (i.e. --until=-0) */
69         utils__CueSpecification *cue_specification;
70
71         const char *inbasefilename;
72         const char *outfilename;
73
74         FLAC__uint64 samples_processed;
75         unsigned frame_counter;
76         FLAC__bool abort_flag;
77         FLAC__bool aborting_due_to_until; /* true if we intentionally abort decoding prematurely because we hit the --until point */
78         FLAC__bool aborting_due_to_unparseable; /* true if we abort decoding because we hit an unparseable frame */
79
80         FLAC__bool iff_headers_need_fixup;
81
82         FLAC__bool is_big_endian;
83         FLAC__bool is_unsigned_samples;
84         FLAC__bool got_stream_info;
85         FLAC__uint64 total_samples;
86         unsigned bps;
87         unsigned channels;
88         unsigned sample_rate;
89
90         union {
91                 union {
92                         FLAC__FileDecoder *file;
93                 } flac;
94 #ifdef FLAC__HAS_OGG
95                 union {
96                         OggFLAC__FileDecoder *file;
97                 } ogg;
98 #endif
99         } decoder;
100
101         FILE *fout;
102 } DecoderSession;
103
104
105 static FLAC__bool is_big_endian_host_;
106
107
108 /*
109  * local routines
110  */
111 static FLAC__bool DecoderSession_construct(DecoderSession *d, FLAC__bool is_ogg, FLAC__bool is_aiff_out, FLAC__bool is_wave_out, FLAC__bool continue_through_decode_errors, replaygain_synthesis_spec_t replaygain_synthesis_spec, FLAC__bool analysis_mode, analysis_options aopts, utils__SkipUntilSpecification *skip_specification, utils__SkipUntilSpecification *until_specification, utils__CueSpecification *cue_specification, const char *infilename, const char *outfilename);
112 static void DecoderSession_destroy(DecoderSession *d, FLAC__bool error_occurred);
113 static FLAC__bool DecoderSession_init_decoder(DecoderSession *d, decode_options_t decode_options, const char *infilename);
114 static FLAC__bool DecoderSession_process(DecoderSession *d);
115 static int DecoderSession_finish_ok(DecoderSession *d);
116 static int DecoderSession_finish_error(DecoderSession *d);
117 static FLAC__bool canonicalize_until_specification(utils__SkipUntilSpecification *spec, const char *inbasefilename, unsigned sample_rate, FLAC__uint64 skip, FLAC__uint64 total_samples_in_input);
118 static FLAC__bool write_iff_headers(FILE *f, DecoderSession *decoder_session, FLAC__uint64 samples);
119 static FLAC__bool write_little_endian_uint16(FILE *f, FLAC__uint16 val);
120 static FLAC__bool write_little_endian_uint32(FILE *f, FLAC__uint32 val);
121 static FLAC__bool write_big_endian_uint16(FILE *f, FLAC__uint16 val);
122 static FLAC__bool write_big_endian_uint32(FILE *f, FLAC__uint32 val);
123 static FLAC__bool write_sane_extended(FILE *f, unsigned val);
124 static FLAC__bool fixup_iff_headers(DecoderSession *d);
125 /*
126  * We use 'void *' so that we can use the same callbacks for the
127  * FLAC__StreamDecoder and FLAC__FileDecoder.  The 'decoder' argument is
128  * actually never used in the callbacks.
129  */
130 static FLAC__StreamDecoderWriteStatus write_callback(const void *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
131 static void metadata_callback(const void *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
132 static void error_callback(const void *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
133 static void print_error_with_state(const DecoderSession *d, const char *message);
134 static void print_stats(const DecoderSession *decoder_session);
135
136
137 /*
138  * public routines
139  */
140 int flac__decode_aiff(const char *infilename, const char *outfilename, FLAC__bool analysis_mode, analysis_options aopts, wav_decode_options_t options)
141 {
142         DecoderSession decoder_session;
143
144         if(!
145                 DecoderSession_construct(
146                         &decoder_session,
147 #ifdef FLAC__HAS_OGG
148                         options.common.is_ogg,
149 #else
150                         /*is_ogg=*/false,
151 #endif
152                         /*is_aiff_out=*/true,
153                         /*is_wave_out=*/false,
154                         options.common.continue_through_decode_errors,
155                         options.common.replaygain_synthesis_spec,
156                         analysis_mode,
157                         aopts,
158                         &options.common.skip_specification,
159                         &options.common.until_specification,
160                         options.common.has_cue_specification? &options.common.cue_specification : 0,
161                         infilename,
162                         outfilename
163                 )
164         )
165                 return 1;
166
167         if(!DecoderSession_init_decoder(&decoder_session, options.common, infilename))
168                 return DecoderSession_finish_error(&decoder_session);
169
170         if(!DecoderSession_process(&decoder_session))
171                 return DecoderSession_finish_error(&decoder_session);
172
173         return DecoderSession_finish_ok(&decoder_session);
174 }
175
176 int flac__decode_wav(const char *infilename, const char *outfilename, FLAC__bool analysis_mode, analysis_options aopts, wav_decode_options_t options)
177 {
178         DecoderSession decoder_session;
179
180         if(!
181                 DecoderSession_construct(
182                         &decoder_session,
183 #ifdef FLAC__HAS_OGG
184                         options.common.is_ogg,
185 #else
186                         /*is_ogg=*/false,
187 #endif
188                         /*is_aiff_out=*/false,
189                         /*is_wave_out=*/true,
190                         options.common.continue_through_decode_errors,
191                         options.common.replaygain_synthesis_spec,
192                         analysis_mode,
193                         aopts,
194                         &options.common.skip_specification,
195                         &options.common.until_specification,
196                         options.common.has_cue_specification? &options.common.cue_specification : 0,
197                         infilename,
198                         outfilename
199                 )
200         )
201                 return 1;
202
203         if(!DecoderSession_init_decoder(&decoder_session, options.common, infilename))
204                 return DecoderSession_finish_error(&decoder_session);
205
206         if(!DecoderSession_process(&decoder_session))
207                 return DecoderSession_finish_error(&decoder_session);
208
209         return DecoderSession_finish_ok(&decoder_session);
210 }
211
212 int flac__decode_raw(const char *infilename, const char *outfilename, FLAC__bool analysis_mode, analysis_options aopts, raw_decode_options_t options)
213 {
214         DecoderSession decoder_session;
215
216         decoder_session.is_big_endian = options.is_big_endian;
217         decoder_session.is_unsigned_samples = options.is_unsigned_samples;
218
219         if(!
220                 DecoderSession_construct(
221                         &decoder_session,
222 #ifdef FLAC__HAS_OGG
223                         options.common.is_ogg,
224 #else
225                         /*is_ogg=*/false,
226 #endif
227                         /*is_aiff_out=*/false,
228                         /*is_wave_out=*/false,
229                         options.common.continue_through_decode_errors,
230                         options.common.replaygain_synthesis_spec,
231                         analysis_mode,
232                         aopts,
233                         &options.common.skip_specification,
234                         &options.common.until_specification,
235                         options.common.has_cue_specification? &options.common.cue_specification : 0,
236                         infilename,
237                         outfilename
238                 )
239         )
240                 return 1;
241
242         if(!DecoderSession_init_decoder(&decoder_session, options.common, infilename))
243                 return DecoderSession_finish_error(&decoder_session);
244
245         if(!DecoderSession_process(&decoder_session))
246                 return DecoderSession_finish_error(&decoder_session);
247
248         return DecoderSession_finish_ok(&decoder_session);
249 }
250
251 FLAC__bool DecoderSession_construct(DecoderSession *d, FLAC__bool is_ogg, FLAC__bool is_aiff_out, FLAC__bool is_wave_out, FLAC__bool continue_through_decode_errors, replaygain_synthesis_spec_t replaygain_synthesis_spec, FLAC__bool analysis_mode, analysis_options aopts, utils__SkipUntilSpecification *skip_specification, utils__SkipUntilSpecification *until_specification, utils__CueSpecification *cue_specification, const char *infilename, const char *outfilename)
252 {
253 #ifdef FLAC__HAS_OGG
254         d->is_ogg = is_ogg;
255 #else
256         (void)is_ogg;
257 #endif
258
259         d->is_aiff_out = is_aiff_out;
260         d->is_wave_out = is_wave_out;
261         d->continue_through_decode_errors = continue_through_decode_errors;
262         d->replaygain.spec = replaygain_synthesis_spec;
263         d->replaygain.apply = false;
264         d->replaygain.scale = 0.0;
265         /* d->replaygain.dither_context gets initialized later once we know the sample resolution */
266         d->test_only = (0 == outfilename);
267         d->analysis_mode = analysis_mode;
268         d->aopts = aopts;
269         d->skip_specification = skip_specification;
270         d->until_specification = until_specification;
271         d->cue_specification = cue_specification;
272
273         d->inbasefilename = grabbag__file_get_basename(infilename);
274         d->outfilename = outfilename;
275
276         d->samples_processed = 0;
277         d->frame_counter = 0;
278         d->abort_flag = false;
279         d->aborting_due_to_until = false;
280         d->aborting_due_to_unparseable = false;
281
282         d->iff_headers_need_fixup = false;
283
284         d->total_samples = 0;
285         d->got_stream_info = false;
286         d->bps = 0;
287         d->channels = 0;
288         d->sample_rate = 0;
289
290         d->decoder.flac.file = 0;
291 #ifdef FLAC__HAS_OGG
292         d->decoder.ogg.file = 0;
293 #endif
294
295         d->fout = 0; /* initialized with an open file later if necessary */
296
297         FLAC__ASSERT(!(d->test_only && d->analysis_mode));
298
299         if(!d->test_only) {
300                 if(0 == strcmp(outfilename, "-")) {
301                         d->fout = grabbag__file_get_binary_stdout();
302                 }
303                 else {
304                         if(0 == (d->fout = fopen(outfilename, "wb"))) {
305                                 flac__utils_printf(stderr, 1, "%s: ERROR: can't open output file %s: %s\n", d->inbasefilename, outfilename, strerror(errno));
306                                 DecoderSession_destroy(d, /*error_occurred=*/true);
307                                 return false;
308                         }
309                 }
310         }
311
312         if(analysis_mode)
313                 flac__analyze_init(aopts);
314
315         return true;
316 }
317
318 void DecoderSession_destroy(DecoderSession *d, FLAC__bool error_occurred)
319 {
320         if(0 != d->fout && d->fout != stdout) {
321                 fclose(d->fout);
322                 if(error_occurred)
323                         unlink(d->outfilename);
324         }
325 }
326
327 FLAC__bool DecoderSession_init_decoder(DecoderSession *decoder_session, decode_options_t decode_options, const char *infilename)
328 {
329         FLAC__uint32 test = 1;
330
331         is_big_endian_host_ = (*((FLAC__byte*)(&test)))? false : true;
332
333 #ifdef FLAC__HAS_OGG
334         if(decoder_session->is_ogg) {
335                 decoder_session->decoder.ogg.file = OggFLAC__file_decoder_new();
336
337                 if(0 == decoder_session->decoder.ogg.file) {
338                         flac__utils_printf(stderr, 1, "%s: ERROR creating the decoder instance\n", decoder_session->inbasefilename);
339                         return false;
340                 }
341
342                 OggFLAC__file_decoder_set_md5_checking(decoder_session->decoder.ogg.file, true);
343                 OggFLAC__file_decoder_set_filename(decoder_session->decoder.ogg.file, infilename);
344                 if(!decode_options.use_first_serial_number)
345                         OggFLAC__file_decoder_set_serial_number(decoder_session->decoder.ogg.file, decode_options.serial_number);
346                 if (0 != decoder_session->cue_specification)
347                         OggFLAC__file_decoder_set_metadata_respond(decoder_session->decoder.ogg.file, FLAC__METADATA_TYPE_CUESHEET);
348                 if (decoder_session->replaygain.spec.apply)
349                         OggFLAC__file_decoder_set_metadata_respond(decoder_session->decoder.ogg.file, FLAC__METADATA_TYPE_VORBIS_COMMENT);
350
351                 /*
352                  * The three ugly casts here are to 'downcast' the 'void *' argument of
353                  * the callback down to 'OggFLAC__FileDecoder *'.  In C++ this would be
354                  * unnecessary but here the cast makes the C compiler happy.
355                  */
356                 OggFLAC__file_decoder_set_write_callback(decoder_session->decoder.ogg.file, (FLAC__StreamDecoderWriteStatus (*)(const OggFLAC__FileDecoder *, const FLAC__Frame *, const FLAC__int32 * const [], void *))write_callback);
357                 OggFLAC__file_decoder_set_metadata_callback(decoder_session->decoder.ogg.file, (void (*)(const OggFLAC__FileDecoder *, const FLAC__StreamMetadata *, void *))metadata_callback);
358                 OggFLAC__file_decoder_set_error_callback(decoder_session->decoder.ogg.file, (void (*)(const OggFLAC__FileDecoder *, FLAC__StreamDecoderErrorStatus, void *))error_callback);
359                 OggFLAC__file_decoder_set_client_data(decoder_session->decoder.ogg.file, decoder_session);
360
361                 if(OggFLAC__file_decoder_init(decoder_session->decoder.ogg.file) != OggFLAC__FILE_DECODER_OK) {
362                         print_error_with_state(decoder_session, "ERROR initializing decoder");
363                         return false;
364                 }
365         }
366         else
367 #else
368         (void)decode_options;
369 #endif
370         {
371                 decoder_session->decoder.flac.file = FLAC__file_decoder_new();
372
373                 if(0 == decoder_session->decoder.flac.file) {
374                         flac__utils_printf(stderr, 1, "%s: ERROR creating the decoder instance\n", decoder_session->inbasefilename);
375                         return false;
376                 }
377
378                 FLAC__file_decoder_set_md5_checking(decoder_session->decoder.flac.file, true);
379                 FLAC__file_decoder_set_filename(decoder_session->decoder.flac.file, infilename);
380                 if (0 != decoder_session->cue_specification)
381                         FLAC__file_decoder_set_metadata_respond(decoder_session->decoder.flac.file, FLAC__METADATA_TYPE_CUESHEET);
382                 if (decoder_session->replaygain.spec.apply)
383                         FLAC__file_decoder_set_metadata_respond(decoder_session->decoder.flac.file, FLAC__METADATA_TYPE_VORBIS_COMMENT);
384                 /*
385                  * The three ugly casts here are to 'downcast' the 'void *' argument of
386                  * the callback down to 'FLAC__FileDecoder *'.
387                  */
388                 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);
389                 FLAC__file_decoder_set_metadata_callback(decoder_session->decoder.flac.file, (void (*)(const FLAC__FileDecoder *, const FLAC__StreamMetadata *, void *))metadata_callback);
390                 FLAC__file_decoder_set_error_callback(decoder_session->decoder.flac.file, (void (*)(const FLAC__FileDecoder *, FLAC__StreamDecoderErrorStatus, void *))error_callback);
391                 FLAC__file_decoder_set_client_data(decoder_session->decoder.flac.file, decoder_session);
392
393                 if(FLAC__file_decoder_init(decoder_session->decoder.flac.file) != FLAC__FILE_DECODER_OK) {
394                         print_error_with_state(decoder_session, "ERROR initializing decoder");
395                         return false;
396                 }
397         }
398
399         return true;
400 }
401
402 FLAC__bool DecoderSession_process(DecoderSession *d)
403 {
404 #ifdef FLAC__HAS_OGG
405         if(d->is_ogg) {
406                 if(!OggFLAC__file_decoder_process_until_end_of_metadata(d->decoder.ogg.file)) {
407                         flac__utils_printf(stderr, 2, "\n");
408                         print_error_with_state(d, "ERROR while decoding metadata");
409                         return false;
410                 }
411                 if(OggFLAC__file_decoder_get_state(d->decoder.ogg.file) != OggFLAC__FILE_DECODER_OK && OggFLAC__file_decoder_get_state(d->decoder.ogg.file) != OggFLAC__FILE_DECODER_END_OF_FILE) {
412                         flac__utils_printf(stderr, 2, "\n");
413                         print_error_with_state(d, "ERROR during metadata decoding");
414                         if(!d->continue_through_decode_errors)
415                                 return false;
416                 }
417         }
418         else
419 #endif
420         {
421                 if(!FLAC__file_decoder_process_until_end_of_metadata(d->decoder.flac.file)) {
422                         flac__utils_printf(stderr, 2, "\n");
423                         print_error_with_state(d, "ERROR while decoding metadata");
424                         return false;
425                 }
426                 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) {
427                         flac__utils_printf(stderr, 2, "\n");
428                         print_error_with_state(d, "ERROR during metadata decoding");
429                         if(!d->continue_through_decode_errors)
430                                 return false;
431                 }
432         }
433         if(d->abort_flag)
434                 return false;
435
436         /* write the WAVE/AIFF headers if necessary */
437         if(!d->analysis_mode && !d->test_only && (d->is_wave_out || d->is_aiff_out)) {
438                 if(!write_iff_headers(d->fout, d, d->total_samples)) {
439                         d->abort_flag = true;
440                         return false;
441                 }
442         }
443
444         if(d->skip_specification->value.samples > 0) {
445                 const FLAC__uint64 skip = (FLAC__uint64)d->skip_specification->value.samples;
446
447 #ifdef FLAC__HAS_OGG
448                 if(d->is_ogg) {
449                         if(!OggFLAC__file_decoder_seek_absolute(d->decoder.ogg.file, skip)) {
450                                 print_error_with_state(d, "ERROR seeking while skipping bytes");
451                                 return false;
452                         }
453                         if(!OggFLAC__file_decoder_process_until_end_of_file(d->decoder.ogg.file) && !d->aborting_due_to_until) {
454                                 flac__utils_printf(stderr, 2, "\n");
455                                 print_error_with_state(d, "ERROR while decoding frames");
456                                 return false;
457                         }
458                         if(OggFLAC__file_decoder_get_state(d->decoder.ogg.file) != OggFLAC__FILE_DECODER_OK && OggFLAC__file_decoder_get_state(d->decoder.ogg.file) != OggFLAC__FILE_DECODER_END_OF_FILE && !d->aborting_due_to_until) {
459                                 flac__utils_printf(stderr, 2, "\n");
460                                 print_error_with_state(d, "ERROR during decoding");
461                                 return false;
462                         }
463                 }
464                 else
465 #endif
466                 {
467                         if(!FLAC__file_decoder_seek_absolute(d->decoder.flac.file, skip)) {
468                                 print_error_with_state(d, "ERROR seeking while skipping bytes");
469                                 return false;
470                         }
471                         if(!FLAC__file_decoder_process_until_end_of_file(d->decoder.flac.file) && !d->aborting_due_to_until) {
472                                 flac__utils_printf(stderr, 2, "\n");
473                                 print_error_with_state(d, "ERROR while decoding frames");
474                                 return false;
475                         }
476                         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 && !d->aborting_due_to_until) {
477                                 flac__utils_printf(stderr, 2, "\n");
478                                 print_error_with_state(d, "ERROR during decoding");
479                                 return false;
480                         }
481                 }
482         }
483         else {
484 #ifdef FLAC__HAS_OGG
485                 if(d->is_ogg) {
486                         if(!OggFLAC__file_decoder_process_until_end_of_file(d->decoder.ogg.file) && !d->aborting_due_to_until) {
487                                 flac__utils_printf(stderr, 2, "\n");
488                                 print_error_with_state(d, "ERROR while decoding data");
489                                 return false;
490                         }
491                         if(OggFLAC__file_decoder_get_state(d->decoder.ogg.file) != OggFLAC__FILE_DECODER_OK && OggFLAC__file_decoder_get_state(d->decoder.ogg.file) != OggFLAC__FILE_DECODER_END_OF_FILE && !d->aborting_due_to_until) {
492                                 flac__utils_printf(stderr, 2, "\n");
493                                 print_error_with_state(d, "ERROR during decoding");
494                                 return false;
495                         }
496                 }
497                 else
498 #endif
499                 {
500                         if(!FLAC__file_decoder_process_until_end_of_file(d->decoder.flac.file) && !d->aborting_due_to_until) {
501                                 flac__utils_printf(stderr, 2, "\n");
502                                 print_error_with_state(d, "ERROR while decoding data");
503                                 return false;
504                         }
505                         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 && !d->aborting_due_to_until) {
506                                 flac__utils_printf(stderr, 2, "\n");
507                                 print_error_with_state(d, "ERROR during decoding");
508                                 return false;
509                         }
510                 }
511         }
512
513         if((d->is_wave_out || d->is_aiff_out) && ((d->total_samples * d->channels * ((d->bps+7)/8)) & 1)) {
514                 if(flac__utils_fwrite("\000", 1, 1, d->fout) != 1) {
515                         print_error_with_state(d, d->is_wave_out?
516                                 "ERROR writing pad byte to WAVE data chunk" :
517                                 "ERROR writing pad byte to AIFF SSND chunk"
518                         );
519                         return false;
520                 }
521         }
522
523         return true;
524 }
525
526 int DecoderSession_finish_ok(DecoderSession *d)
527 {
528         FLAC__bool md5_failure = false;
529
530 #ifdef FLAC__HAS_OGG
531         if(d->is_ogg) {
532                 if(d->decoder.ogg.file) {
533                         md5_failure = !OggFLAC__file_decoder_finish(d->decoder.ogg.file) && !d->aborting_due_to_until;
534                         print_stats(d);
535                         OggFLAC__file_decoder_delete(d->decoder.ogg.file);
536                 }
537         }
538         else
539 #endif
540         {
541                 if(d->decoder.flac.file) {
542                         md5_failure = !FLAC__file_decoder_finish(d->decoder.flac.file) && !d->aborting_due_to_until;
543                         print_stats(d);
544                         FLAC__file_decoder_delete(d->decoder.flac.file);
545                 }
546         }
547         if(d->analysis_mode)
548                 flac__analyze_finish(d->aopts);
549         if(md5_failure) {
550                 flac__utils_printf(stderr, 1, "\r%s: WARNING, MD5 signature mismatch\n", d->inbasefilename);
551         }
552         else if(!d->got_stream_info) {
553                 flac__utils_printf(stderr, 1, "\r%s: WARNING, cannot check MD5 signature since there was no STREAMINFO\n", d->inbasefilename);
554         }
555         else {
556                 flac__utils_printf(stderr, 2, "\r%s: %s         \n", d->inbasefilename, d->test_only? "ok           ":d->analysis_mode?"done           ":"done");
557         }
558         DecoderSession_destroy(d, /*error_occurred=*/false);
559         if((d->is_wave_out || d->is_aiff_out) && (d->iff_headers_need_fixup || (!d->got_stream_info && strcmp(d->outfilename, "-"))))
560                 if(!fixup_iff_headers(d))
561                         return 1;
562         return 0;
563 }
564
565 int DecoderSession_finish_error(DecoderSession *d)
566 {
567 #ifdef FLAC__HAS_OGG
568         if(d->is_ogg) {
569                 if(d->decoder.ogg.file) {
570                         OggFLAC__file_decoder_finish(d->decoder.ogg.file);
571                         OggFLAC__file_decoder_delete(d->decoder.ogg.file);
572                 }
573         }
574         else
575 #endif
576         {
577                 if(d->decoder.flac.file) {
578                         FLAC__file_decoder_finish(d->decoder.flac.file);
579                         FLAC__file_decoder_delete(d->decoder.flac.file);
580                 }
581         }
582         if(d->analysis_mode)
583                 flac__analyze_finish(d->aopts);
584         DecoderSession_destroy(d, /*error_occurred=*/true);
585         return 1;
586 }
587
588 FLAC__bool canonicalize_until_specification(utils__SkipUntilSpecification *spec, const char *inbasefilename, unsigned sample_rate, FLAC__uint64 skip, FLAC__uint64 total_samples_in_input)
589 {
590         /* convert from mm:ss.sss to sample number if necessary */
591         flac__utils_canonicalize_skip_until_specification(spec, sample_rate);
592
593         /* special case: if "--until=-0", use the special value '0' to mean "end-of-stream" */
594         if(spec->is_relative && spec->value.samples == 0) {
595                 spec->is_relative = false;
596                 return true;
597         }
598
599         /* in any other case the total samples in the input must be known */
600         if(total_samples_in_input == 0) {
601                 flac__utils_printf(stderr, 1, "%s: ERROR, cannot use --until when FLAC metadata has total sample count of 0\n", inbasefilename);
602                 return false;
603         }
604
605         FLAC__ASSERT(spec->value_is_samples);
606
607         /* convert relative specifications to absolute */
608         if(spec->is_relative) {
609                 if(spec->value.samples <= 0)
610                         spec->value.samples += (FLAC__int64)total_samples_in_input;
611                 else
612                         spec->value.samples += skip;
613                 spec->is_relative = false;
614         }
615
616         /* error check */
617         if(spec->value.samples < 0) {
618                 flac__utils_printf(stderr, 1, "%s: ERROR, --until value is before beginning of input\n", inbasefilename);
619                 return false;
620         }
621         if((FLAC__uint64)spec->value.samples <= skip) {
622                 flac__utils_printf(stderr, 1, "%s: ERROR, --until value is before --skip point\n", inbasefilename);
623                 return false;
624         }
625         if((FLAC__uint64)spec->value.samples > total_samples_in_input) {
626                 flac__utils_printf(stderr, 1, "%s: ERROR, --until value is after end of input\n", inbasefilename);
627                 return false;
628         }
629
630         return true;
631 }
632
633 FLAC__bool write_iff_headers(FILE *f, DecoderSession *decoder_session, FLAC__uint64 samples)
634 {
635         const char *fmt_desc = decoder_session->is_wave_out? "WAVE" : "AIFF";
636         FLAC__uint64 data_size = samples * decoder_session->channels * ((decoder_session->bps+7)/8);
637         const FLAC__uint32 aligned_data_size = (FLAC__uint32)((data_size+1) & (~1U)); /* we'll check for overflow later */
638         if(samples == 0) {
639                 if(f == stdout) {
640                         flac__utils_printf(stderr, 1, "%s: WARNING, don't have accurate sample count available for %s header.\n", decoder_session->inbasefilename, fmt_desc);
641                         flac__utils_printf(stderr, 1, "             Generated %s file will have a data chunk size of 0.  Try\n", fmt_desc);
642                         flac__utils_printf(stderr, 1, "             decoding directly to a file instead.\n");
643                 }
644                 else {
645                         decoder_session->iff_headers_need_fixup = true;
646                 }
647         }
648         if(data_size >= 0xFFFFFFDC) {
649                 flac__utils_printf(stderr, 1, "%s: ERROR: stream is too big to fit in a single %s file chunk\n", decoder_session->inbasefilename, fmt_desc);
650                 return false;
651         }
652         if(decoder_session->is_wave_out) {
653                 if(flac__utils_fwrite("RIFF", 1, 4, f) != 4)
654                         return false;
655
656                 if(!write_little_endian_uint32(f, aligned_data_size+36)) /* filesize-8 */
657                         return false;
658
659                 if(flac__utils_fwrite("WAVEfmt ", 1, 8, f) != 8)
660                         return false;
661
662                 if(flac__utils_fwrite("\020\000\000\000", 1, 4, f) != 4) /* chunk size = 16 */
663                         return false;
664
665                 if(flac__utils_fwrite("\001\000", 1, 2, f) != 2) /* compression code == 1 */
666                         return false;
667
668                 if(!write_little_endian_uint16(f, (FLAC__uint16)(decoder_session->channels)))
669                         return false;
670
671                 if(!write_little_endian_uint32(f, decoder_session->sample_rate))
672                         return false;
673
674                 if(!write_little_endian_uint32(f, decoder_session->sample_rate * decoder_session->channels * ((decoder_session->bps+7) / 8))) /* @@@ or is it (sample_rate*channels*bps) / 8 ??? */
675                         return false;
676
677                 if(!write_little_endian_uint16(f, (FLAC__uint16)(decoder_session->channels * ((decoder_session->bps+7) / 8)))) /* block align */
678                         return false;
679
680                 if(!write_little_endian_uint16(f, (FLAC__uint16)(decoder_session->bps))) /* bits per sample */
681                         return false;
682
683                 if(flac__utils_fwrite("data", 1, 4, f) != 4)
684                         return false;
685
686                 if(!write_little_endian_uint32(f, (FLAC__uint32)data_size)) /* data size */
687                         return false;
688         }
689         else {
690                 if(flac__utils_fwrite("FORM", 1, 4, f) != 4)
691                         return false;
692
693                 if(!write_big_endian_uint32(f, aligned_data_size+46)) /* filesize-8 */
694                         return false;
695
696                 if(flac__utils_fwrite("AIFFCOMM", 1, 8, f) != 8)
697                         return false;
698
699                 if(flac__utils_fwrite("\000\000\000\022", 1, 4, f) != 4) /* chunk size = 18 */
700                         return false;
701
702                 if(!write_big_endian_uint16(f, (FLAC__uint16)(decoder_session->channels)))
703                         return false;
704
705                 if(!write_big_endian_uint32(f, (FLAC__uint32)samples))
706                         return false;
707
708                 if(!write_big_endian_uint16(f, (FLAC__uint16)(decoder_session->bps)))
709                         return false;
710
711                 if(!write_sane_extended(f, decoder_session->sample_rate))
712                         return false;
713
714                 if(flac__utils_fwrite("SSND", 1, 4, f) != 4)
715                         return false;
716
717                 if(!write_big_endian_uint32(f, (FLAC__uint32)data_size+8)) /* data size */
718                         return false;
719
720                 if(!write_big_endian_uint32(f, 0/*offset*/))
721                         return false;
722
723                 if(!write_big_endian_uint32(f, 0/*block_size*/))
724                         return false;
725         }
726
727         return true;
728 }
729
730 FLAC__bool write_little_endian_uint16(FILE *f, FLAC__uint16 val)
731 {
732         FLAC__byte *b = (FLAC__byte*)(&val);
733         if(is_big_endian_host_) {
734                 FLAC__byte tmp;
735                 tmp = b[1]; b[1] = b[0]; b[0] = tmp;
736         }
737         return flac__utils_fwrite(b, 1, 2, f) == 2;
738 }
739
740 FLAC__bool write_little_endian_uint32(FILE *f, FLAC__uint32 val)
741 {
742         FLAC__byte *b = (FLAC__byte*)(&val);
743         if(is_big_endian_host_) {
744                 FLAC__byte tmp;
745                 tmp = b[3]; b[3] = b[0]; b[0] = tmp;
746                 tmp = b[2]; b[2] = b[1]; b[1] = tmp;
747         }
748         return flac__utils_fwrite(b, 1, 4, f) == 4;
749 }
750
751 FLAC__bool write_big_endian_uint16(FILE *f, FLAC__uint16 val)
752 {
753         FLAC__byte *b = (FLAC__byte*)(&val);
754         if(!is_big_endian_host_) {
755                 FLAC__byte tmp;
756                 tmp = b[1]; b[1] = b[0]; b[0] = tmp;
757         }
758         return flac__utils_fwrite(b, 1, 2, f) == 2;
759 }
760
761 FLAC__bool write_big_endian_uint32(FILE *f, FLAC__uint32 val)
762 {
763         FLAC__byte *b = (FLAC__byte*)(&val);
764         if(!is_big_endian_host_) {
765                 FLAC__byte tmp;
766                 tmp = b[3]; b[3] = b[0]; b[0] = tmp;
767                 tmp = b[2]; b[2] = b[1]; b[1] = tmp;
768         }
769         return flac__utils_fwrite(b, 1, 4, f) == 4;
770 }
771
772 FLAC__bool write_sane_extended(FILE *f, unsigned val)
773         /* Write to 'f' a SANE extended representation of 'val'.  Return false if
774         * the write succeeds; return true otherwise.
775         *
776         * SANE extended is an 80-bit IEEE-754 representation with sign bit, 15 bits
777         * of exponent, and 64 bits of significand (mantissa).  Unlike most IEEE-754
778         * representations, it does not imply a 1 above the MSB of the significand.
779         *
780         * Preconditions:
781         *  val!=0U
782         */
783 {
784         unsigned int shift, exponent;
785
786         FLAC__ASSERT(val!=0U); /* handling 0 would require a special case */
787
788         for(shift= 0U; (val>>(31-shift))==0U; ++shift)
789                 ;
790         val<<= shift;
791         exponent= 63U-(shift+32U); /* add 32 for unused second word */
792
793         if(!write_big_endian_uint16(f, (FLAC__uint16)(exponent+0x3FFF)))
794                 return false;
795         if(!write_big_endian_uint32(f, val))
796                 return false;
797         if(!write_big_endian_uint32(f, 0)) /* unused second word */
798                 return false;
799
800         return true;
801 }
802
803 FLAC__bool fixup_iff_headers(DecoderSession *d)
804 {
805         const char *fmt_desc = (d->is_wave_out? "WAVE" : "AIFF");
806         FILE *f = fopen(d->outfilename, "r+b"); /* stream is positioned at beginning of file */
807
808         if(0 == f) {
809                 flac__utils_printf(stderr, 1, "ERROR, couldn't open file %s while fixing up %s chunk size: %s\n", d->outfilename, fmt_desc, strerror(errno));
810                 return false;
811         }
812
813         if(!write_iff_headers(f, d, d->samples_processed)) {
814                 fclose(f);
815                 return false;
816         }
817
818         fclose(f);
819         return true;
820 }
821
822 FLAC__StreamDecoderWriteStatus write_callback(const void *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
823 {
824         DecoderSession *decoder_session = (DecoderSession*)client_data;
825         FILE *fout = decoder_session->fout;
826         const unsigned bps = frame->header.bits_per_sample, channels = frame->header.channels;
827         FLAC__bool is_big_endian = (decoder_session->is_aiff_out? true : (decoder_session->is_wave_out? false : decoder_session->is_big_endian));
828         FLAC__bool is_unsigned_samples = (decoder_session->is_aiff_out? false : (decoder_session->is_wave_out? bps<=8 : decoder_session->is_unsigned_samples));
829         unsigned wide_samples = frame->header.blocksize, wide_sample, sample, channel, byte;
830         static FLAC__int8 s8buffer[FLAC__MAX_BLOCK_SIZE * FLAC__MAX_CHANNELS * sizeof(FLAC__int32)]; /* WATCHOUT: can be up to 2 megs */
831         FLAC__uint8  *u8buffer  = (FLAC__uint8  *)s8buffer;
832         FLAC__int16  *s16buffer = (FLAC__int16  *)s8buffer;
833         FLAC__uint16 *u16buffer = (FLAC__uint16 *)s8buffer;
834         FLAC__int32  *s32buffer = (FLAC__int32  *)s8buffer;
835         FLAC__uint32 *u32buffer = (FLAC__uint32 *)s8buffer;
836         size_t bytes_to_write = 0;
837
838         (void)decoder;
839
840         if(decoder_session->abort_flag)
841                 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
842
843         /* sanity-check the bits-per-sample */
844         if(decoder_session->bps) {
845                 if(bps != decoder_session->bps) {
846                         if(decoder_session->got_stream_info)
847                                 flac__utils_printf(stderr, 1, "%s: ERROR, bits-per-sample is %u in frame but %u in STREAMINFO\n", decoder_session->inbasefilename, bps, decoder_session->bps);
848                         else
849                                 flac__utils_printf(stderr, 1, "%s: ERROR, bits-per-sample is %u in this frame but %u in previous frames\n", decoder_session->inbasefilename, bps, decoder_session->bps);
850                         if(!decoder_session->continue_through_decode_errors)
851                                 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
852                 }
853         }
854         else {
855                 /* must not have gotten STREAMINFO, save the bps from the frame header */
856                 FLAC__ASSERT(!decoder_session->got_stream_info);
857                 decoder_session->bps = bps;
858         }
859
860         /* sanity-check the #channels */
861         if(decoder_session->channels) {
862                 if(channels != decoder_session->channels) {
863                         if(decoder_session->got_stream_info)
864                                 flac__utils_printf(stderr, 1, "%s: ERROR, channels is %u in frame but %u in STREAMINFO\n", decoder_session->inbasefilename, channels, decoder_session->channels);
865                         else
866                                 flac__utils_printf(stderr, 1, "%s: ERROR, channels is %u in this frame but %u in previous frames\n", decoder_session->inbasefilename, channels, decoder_session->channels);
867                         if(!decoder_session->continue_through_decode_errors)
868                                 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
869                 }
870         }
871         else {
872                 /* must not have gotten STREAMINFO, save the #channels from the frame header */
873                 FLAC__ASSERT(!decoder_session->got_stream_info);
874                 decoder_session->channels = channels;
875         }
876
877         /* sanity-check the sample rate */
878         if(decoder_session->sample_rate) {
879                 if(frame->header.sample_rate != decoder_session->sample_rate) {
880                         if(decoder_session->got_stream_info)
881                                 flac__utils_printf(stderr, 1, "%s: ERROR, sample rate is %u in frame but %u in STREAMINFO\n", decoder_session->inbasefilename, frame->header.sample_rate, decoder_session->sample_rate);
882                         else
883                                 flac__utils_printf(stderr, 1, "%s: ERROR, sample rate is %u in this frame but %u in previous frames\n", decoder_session->inbasefilename, frame->header.sample_rate, decoder_session->sample_rate);
884                         if(!decoder_session->continue_through_decode_errors)
885                                 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
886                 }
887         }
888         else {
889                 /* must not have gotten STREAMINFO, save the sample rate from the frame header */
890                 FLAC__ASSERT(!decoder_session->got_stream_info);
891                 decoder_session->sample_rate = frame->header.sample_rate;
892         }
893
894         /*
895          * limit the number of samples to accept based on --until
896          */
897         FLAC__ASSERT(!decoder_session->skip_specification->is_relative);
898         /* if we never got the total_samples from the metadata, the skip and until specs would never have been canonicalized, so protect against that: */
899         if(decoder_session->skip_specification->is_relative) {
900                 if(decoder_session->skip_specification->value.samples == 0) /* special case for when no --skip was given */
901                         decoder_session->skip_specification->is_relative = false; /* convert to our meaning of beginning-of-stream */
902                 else {
903                         flac__utils_printf(stderr, 1, "%s: ERROR, cannot use --skip because the total sample count was not found in the metadata\n", decoder_session->inbasefilename);
904                         return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
905                 }
906         }
907         if(decoder_session->until_specification->is_relative) {
908                 if(decoder_session->until_specification->value.samples == 0) /* special case for when no --until was given */
909                         decoder_session->until_specification->is_relative = false; /* convert to our meaning of end-of-stream */
910                 else {
911                         flac__utils_printf(stderr, 1, "%s: ERROR, cannot use --until because the total sample count was not found in the metadata\n", decoder_session->inbasefilename);
912                         return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
913                 }
914         }
915         FLAC__ASSERT(decoder_session->skip_specification->value.samples >= 0);
916         FLAC__ASSERT(decoder_session->until_specification->value.samples >= 0);
917         if(decoder_session->until_specification->value.samples > 0) {
918                 const FLAC__uint64 skip = (FLAC__uint64)decoder_session->skip_specification->value.samples;
919                 const FLAC__uint64 until = (FLAC__uint64)decoder_session->until_specification->value.samples;
920                 const FLAC__uint64 input_samples_passed = skip + decoder_session->samples_processed;
921                 FLAC__ASSERT(until >= input_samples_passed);
922                 if(input_samples_passed + wide_samples > until)
923                         wide_samples = (unsigned)(until - input_samples_passed);
924                 if (wide_samples == 0) {
925                         decoder_session->abort_flag = true;
926                         decoder_session->aborting_due_to_until = true;
927                         return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
928                 }
929         }
930
931         if(wide_samples > 0) {
932                 decoder_session->samples_processed += wide_samples;
933                 decoder_session->frame_counter++;
934
935                 if(!(decoder_session->frame_counter & 0x3f))
936                         print_stats(decoder_session);
937
938                 if(decoder_session->analysis_mode) {
939                         flac__analyze_frame(frame, decoder_session->frame_counter-1, decoder_session->aopts, fout);
940                 }
941                 else if(!decoder_session->test_only) {
942                         if (decoder_session->replaygain.apply) {
943                                 bytes_to_write = FLAC__replaygain_synthesis__apply_gain(
944                                         u8buffer,
945                                         !is_big_endian,
946                                         is_unsigned_samples,
947                                         buffer,
948                                         wide_samples,
949                                         channels,
950                                         bps, /* source_bps */
951                                         bps, /* target_bps */
952                                         decoder_session->replaygain.scale,
953                                         decoder_session->replaygain.spec.limiter == RGSS_LIMIT__HARD, /* hard_limit */
954                                         decoder_session->replaygain.spec.noise_shaping != NOISE_SHAPING_NONE, /* do_dithering */
955                                         &decoder_session->replaygain.dither_context
956                                 );
957                         }
958                         else if(bps == 8) {
959                                 if(is_unsigned_samples) {
960                                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
961                                                 for(channel = 0; channel < channels; channel++, sample++)
962                                                         u8buffer[sample] = (FLAC__uint8)(buffer[channel][wide_sample] + 0x80);
963                                 }
964                                 else {
965                                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
966                                                 for(channel = 0; channel < channels; channel++, sample++)
967                                                         s8buffer[sample] = (FLAC__int8)(buffer[channel][wide_sample]);
968                                 }
969                                 bytes_to_write = sample;
970                         }
971                         else if(bps == 16) {
972                                 if(is_unsigned_samples) {
973                                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
974                                                 for(channel = 0; channel < channels; channel++, sample++)
975                                                         u16buffer[sample] = (FLAC__uint16)(buffer[channel][wide_sample] + 0x8000);
976                                 }
977                                 else {
978                                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
979                                                 for(channel = 0; channel < channels; channel++, sample++)
980                                                         s16buffer[sample] = (FLAC__int16)(buffer[channel][wide_sample]);
981                                 }
982                                 if(is_big_endian != is_big_endian_host_) {
983                                         unsigned char tmp;
984                                         const unsigned bytes = sample * 2;
985                                         for(byte = 0; byte < bytes; byte += 2) {
986                                                 tmp = u8buffer[byte];
987                                                 u8buffer[byte] = u8buffer[byte+1];
988                                                 u8buffer[byte+1] = tmp;
989                                         }
990                                 }
991                                 bytes_to_write = 2 * sample;
992                         }
993                         else if(bps == 24) {
994                                 if(is_unsigned_samples) {
995                                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
996                                                 for(channel = 0; channel < channels; channel++, sample++)
997                                                         u32buffer[sample] = buffer[channel][wide_sample] + 0x800000;
998                                 }
999                                 else {
1000                                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1001                                                 for(channel = 0; channel < channels; channel++, sample++)
1002                                                         s32buffer[sample] = buffer[channel][wide_sample];
1003                                 }
1004                                 if(is_big_endian != is_big_endian_host_) {
1005                                         unsigned char tmp;
1006                                         const unsigned bytes = sample * 4;
1007                                         for(byte = 0; byte < bytes; byte += 4) {
1008                                                 tmp = u8buffer[byte];
1009                                                 u8buffer[byte] = u8buffer[byte+3];
1010                                                 u8buffer[byte+3] = tmp;
1011                                                 tmp = u8buffer[byte+1];
1012                                                 u8buffer[byte+1] = u8buffer[byte+2];
1013                                                 u8buffer[byte+2] = tmp;
1014                                         }
1015                                 }
1016                                 if(is_big_endian) {
1017                                         unsigned lbyte;
1018                                         const unsigned bytes = sample * 4;
1019                                         for(lbyte = byte = 0; byte < bytes; ) {
1020                                                 byte++;
1021                                                 u8buffer[lbyte++] = u8buffer[byte++];
1022                                                 u8buffer[lbyte++] = u8buffer[byte++];
1023                                                 u8buffer[lbyte++] = u8buffer[byte++];
1024                                         }
1025                                 }
1026                                 else {
1027                                         unsigned lbyte;
1028                                         const unsigned bytes = sample * 4;
1029                                         for(lbyte = byte = 0; byte < bytes; ) {
1030                                                 u8buffer[lbyte++] = u8buffer[byte++];
1031                                                 u8buffer[lbyte++] = u8buffer[byte++];
1032                                                 u8buffer[lbyte++] = u8buffer[byte++];
1033                                                 byte++;
1034                                         }
1035                                 }
1036                                 bytes_to_write = 3 * sample;
1037                         }
1038                         else {
1039                                 FLAC__ASSERT(0);
1040                         }
1041                 }
1042         }
1043         if(bytes_to_write > 0) {
1044                 if(flac__utils_fwrite(u8buffer, 1, bytes_to_write, fout) != bytes_to_write) {
1045                         /* if a pipe closed when writing to stdout, we let it go without an error message */
1046                         if(errno == EPIPE && decoder_session->fout == stdout)
1047                                 decoder_session->aborting_due_to_until = true;
1048                         decoder_session->abort_flag = true;
1049                         return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
1050                 }
1051         }
1052         return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
1053 }
1054
1055 void metadata_callback(const void *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
1056 {
1057         DecoderSession *decoder_session = (DecoderSession*)client_data;
1058         (void)decoder;
1059         if(metadata->type == FLAC__METADATA_TYPE_STREAMINFO) {
1060                 FLAC__uint64 skip, until;
1061                 decoder_session->got_stream_info = true;
1062                 decoder_session->bps = metadata->data.stream_info.bits_per_sample;
1063                 decoder_session->channels = metadata->data.stream_info.channels;
1064                 decoder_session->sample_rate = metadata->data.stream_info.sample_rate;
1065
1066                 flac__utils_canonicalize_skip_until_specification(decoder_session->skip_specification, decoder_session->sample_rate);
1067                 FLAC__ASSERT(decoder_session->skip_specification->value.samples >= 0);
1068                 skip = (FLAC__uint64)decoder_session->skip_specification->value.samples;
1069
1070                 /* remember, metadata->data.stream_info.total_samples can be 0, meaning 'unknown' */
1071                 if(metadata->data.stream_info.total_samples > 0 && skip >= metadata->data.stream_info.total_samples) {
1072                         flac__utils_printf(stderr, 1, "%s: ERROR trying to --skip more samples than in stream\n", decoder_session->inbasefilename);
1073                         decoder_session->abort_flag = true;
1074                         return;
1075                 }
1076                 else if(metadata->data.stream_info.total_samples == 0 && skip > 0) {
1077                         flac__utils_printf(stderr, 1, "%s: ERROR, can't --skip when FLAC metadata has total sample count of 0\n", decoder_session->inbasefilename);
1078                         decoder_session->abort_flag = true;
1079                         return;
1080                 }
1081                 FLAC__ASSERT(skip == 0 || 0 == decoder_session->cue_specification);
1082                 decoder_session->total_samples = metadata->data.stream_info.total_samples - skip;
1083
1084                 /* note that we use metadata->data.stream_info.total_samples instead of decoder_session->total_samples */
1085                 if(!canonicalize_until_specification(decoder_session->until_specification, decoder_session->inbasefilename, decoder_session->sample_rate, skip, metadata->data.stream_info.total_samples)) {
1086                         decoder_session->abort_flag = true;
1087                         return;
1088                 }
1089                 FLAC__ASSERT(decoder_session->until_specification->value.samples >= 0);
1090                 until = (FLAC__uint64)decoder_session->until_specification->value.samples;
1091
1092                 if(until > 0) {
1093                         FLAC__ASSERT(decoder_session->total_samples != 0);
1094                         FLAC__ASSERT(0 == decoder_session->cue_specification);
1095                         decoder_session->total_samples -= (metadata->data.stream_info.total_samples - until);
1096                 }
1097
1098                 if(decoder_session->bps != 8 && decoder_session->bps != 16 && decoder_session->bps != 24) {
1099                         flac__utils_printf(stderr, 1, "%s: ERROR: bits per sample is not 8/16/24\n", decoder_session->inbasefilename);
1100                         decoder_session->abort_flag = true;
1101                         return;
1102                 }
1103         }
1104         else if(metadata->type == FLAC__METADATA_TYPE_CUESHEET) {
1105                 /* remember, at this point, decoder_session->total_samples can be 0, meaning 'unknown' */
1106                 if(decoder_session->total_samples == 0) {
1107                         flac__utils_printf(stderr, 1, "%s: ERROR can't use --cue when FLAC metadata has total sample count of 0\n", decoder_session->inbasefilename);
1108                         decoder_session->abort_flag = true;
1109                         return;
1110                 }
1111
1112                 flac__utils_canonicalize_cue_specification(decoder_session->cue_specification, &metadata->data.cue_sheet, decoder_session->total_samples, decoder_session->skip_specification, decoder_session->until_specification);
1113
1114                 FLAC__ASSERT(!decoder_session->skip_specification->is_relative);
1115                 FLAC__ASSERT(decoder_session->skip_specification->value_is_samples);
1116
1117                 FLAC__ASSERT(!decoder_session->until_specification->is_relative);
1118                 FLAC__ASSERT(decoder_session->until_specification->value_is_samples);
1119
1120                 FLAC__ASSERT(decoder_session->skip_specification->value.samples >= 0);
1121                 FLAC__ASSERT(decoder_session->until_specification->value.samples >= 0);
1122                 FLAC__ASSERT((FLAC__uint64)decoder_session->until_specification->value.samples <= decoder_session->total_samples);
1123                 FLAC__ASSERT(decoder_session->skip_specification->value.samples <= decoder_session->until_specification->value.samples);
1124
1125                 decoder_session->total_samples = decoder_session->until_specification->value.samples - decoder_session->skip_specification->value.samples;
1126         }
1127         else if(metadata->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
1128                 if (decoder_session->replaygain.spec.apply) {
1129                         double gain, peak;
1130                         if (!(decoder_session->replaygain.apply = grabbag__replaygain_load_from_vorbiscomment(metadata, decoder_session->replaygain.spec.use_album_gain, /*strict=*/false, &gain, &peak))) {
1131                                 flac__utils_printf(stderr, 1, "%s: WARNING: can't get %s (or even %s) ReplayGain tags\n", decoder_session->inbasefilename, decoder_session->replaygain.spec.use_album_gain? "album":"track", decoder_session->replaygain.spec.use_album_gain? "track":"album");
1132                         }
1133                         else {
1134                                 const char *ls[] = { "no", "peak", "hard" };
1135                                 const char *ns[] = { "no", "low", "medium", "high" };
1136                                 decoder_session->replaygain.scale = grabbag__replaygain_compute_scale_factor(peak, gain, decoder_session->replaygain.spec.preamp, decoder_session->replaygain.spec.limiter == RGSS_LIMIT__PEAK);
1137                                 FLAC__ASSERT(decoder_session->bps > 0 && decoder_session->bps <= 32);
1138                                 FLAC__replaygain_synthesis__init_dither_context(&decoder_session->replaygain.dither_context, decoder_session->bps, decoder_session->replaygain.spec.noise_shaping);
1139                                 flac__utils_printf(stderr, 1, "%s: INFO: applying %s ReplayGain (gain=%0.2fdB+preamp=%0.1fdB, %s noise shaping, %s limiting) to output\n", decoder_session->inbasefilename, decoder_session->replaygain.spec.use_album_gain? "album":"track", gain, decoder_session->replaygain.spec.preamp, ns[decoder_session->replaygain.spec.noise_shaping], ls[decoder_session->replaygain.spec.limiter]);
1140                                 flac__utils_printf(stderr, 1, "%s: WARNING: applying ReplayGain is not lossless\n", decoder_session->inbasefilename);
1141                         }
1142                 }
1143         }
1144 }
1145
1146 void error_callback(const void *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
1147 {
1148         DecoderSession *decoder_session = (DecoderSession*)client_data;
1149         (void)decoder;
1150         flac__utils_printf(stderr, 1, "%s: *** Got error code %d:%s\n", decoder_session->inbasefilename, status, FLAC__StreamDecoderErrorStatusString[status]);
1151         if(!decoder_session->continue_through_decode_errors) {
1152                 decoder_session->abort_flag = true;
1153                 if(status == FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM)
1154                         decoder_session->aborting_due_to_unparseable = true;
1155         }
1156 }
1157
1158 void print_error_with_state(const DecoderSession *d, const char *message)
1159 {
1160         const int ilen = strlen(d->inbasefilename) + 1;
1161         const char *state_string;
1162
1163         flac__utils_printf(stderr, 1, "\n%s: %s\n", d->inbasefilename, message);
1164
1165 #ifdef FLAC__HAS_OGG
1166         if(d->is_ogg) {
1167                 state_string = OggFLAC__file_decoder_get_resolved_state_string(d->decoder.ogg.file);
1168         }
1169         else
1170 #endif
1171         {
1172                 state_string = FLAC__file_decoder_get_resolved_state_string(d->decoder.flac.file);
1173         }
1174
1175         flac__utils_printf(stderr, 1, "%*s state = %s\n", ilen, "", state_string);
1176
1177         /* print out some more info for some errors: */
1178         if (d->aborting_due_to_unparseable) {
1179                 flac__utils_printf(stderr, 1,
1180                         "\n"
1181                         "The FLAC stream may have been created by a more advanced encoder.  Try\n"
1182                         "  metaflac --show-vendor-tag %s\n"
1183                         "If the version number is greater than %s, this decoder is probably\n"
1184                         "not able to decode the file.  If the version number is not, the file\n"
1185                         "may be corrupted, or you may have found a bug.  In this case please\n"
1186                         "submit a bug report to\n"
1187                         "    http://sourceforge.net/bugs/?func=addbug&group_id=13478\n"
1188                         "Make sure to use the \"Monitor\" feature to monitor the bug status.\n",
1189                         d->inbasefilename, FLAC__VERSION_STRING
1190                 );
1191         }
1192         else if (
1193                 0 == strcmp(state_string, FLAC__FileDecoderStateString[FLAC__FILE_DECODER_ERROR_OPENING_FILE])
1194 #ifdef FLAC__HAS_OGG
1195                 || 0 == strcmp(state_string, OggFLAC__FileDecoderStateString[OggFLAC__FILE_DECODER_ERROR_OPENING_FILE])
1196 #endif
1197         ) {
1198                 flac__utils_printf(stderr, 1,
1199                         "\n"
1200                         "An error occurred opening the input file; it is likely that it does not exist\n"
1201                         "or is not readable.\n"
1202                 );
1203         }
1204 }
1205
1206 void print_stats(const DecoderSession *decoder_session)
1207 {
1208         if(flac__utils_verbosity_ >= 2) {
1209 #if defined _MSC_VER || defined __MINGW32__
1210                 /* with MSVC you have to spoon feed it the casting */
1211                 const double progress = (double)(FLAC__int64)decoder_session->samples_processed / (double)(FLAC__int64)decoder_session->total_samples * 100.0;
1212 #else
1213                 const double progress = (double)decoder_session->samples_processed / (double)decoder_session->total_samples * 100.0;
1214 #endif
1215                 if(decoder_session->total_samples > 0) {
1216                         fprintf(stderr, "\r%s: %s%u%% complete",
1217                                 decoder_session->inbasefilename,
1218                                 decoder_session->test_only? "testing, " : decoder_session->analysis_mode? "analyzing, " : "",
1219                                 (unsigned)floor(progress + 0.5)
1220                         );
1221                 }
1222                 else {
1223                         fprintf(stderr, "\r%s: %s %u samples",
1224                                 decoder_session->inbasefilename,
1225                                 decoder_session->test_only? "tested" : decoder_session->analysis_mode? "analyzed" : "wrote",
1226                                 (unsigned)decoder_session->samples_processed
1227                         );
1228                 }
1229         }
1230 }