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