commit patch for compiling on mingw32
[flac.git] / src / flac / decode.c
1 /* flac - Command-line FLAC encoder/decoder
2  * Copyright (C) 2000,2001  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 = 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 = 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(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                         if(FLAC__stream_decoder_get_state(stream_info.decoder.stream) != FLAC__STREAM_DECODER_UNINITIALIZED)
217                                 FLAC__stream_decoder_finish(stream_info.decoder.stream);
218                         md5_failure = false;
219                         print_stats(&stream_info);
220                         FLAC__stream_decoder_delete(stream_info.decoder.stream);
221                 }
222         }
223         else
224 #endif
225         {
226                 if(stream_info.decoder.file) {
227                         if(FLAC__file_decoder_get_state(stream_info.decoder.file) != FLAC__FILE_DECODER_UNINITIALIZED)
228                                 md5_failure = !FLAC__file_decoder_finish(stream_info.decoder.file);
229                         print_stats(&stream_info);
230                         FLAC__file_decoder_delete(stream_info.decoder.file);
231                 }
232         }
233         if(0 != stream_info.fout && stream_info.fout != stdout)
234                 fclose(stream_info.fout);
235 #ifdef FLAC__HAS_OGG
236         if(stream_info.is_ogg) {
237                 if(0 != stream_info.fin && stream_info.fin != stdin)
238                         fclose(stream_info.fin);
239         }
240 #endif
241         if(analysis_mode)
242                 flac__analyze_finish(aopts);
243         if(md5_failure) {
244                 fprintf(stderr, "\r%s: WARNING, MD5 signature mismatch\n", stream_info.inbasefilename);
245         }
246         else {
247                 if(stream_info.verbose)
248                         fprintf(stderr, "\r%s: %s         \n", stream_info.inbasefilename, stream_info.test_only? "ok           ":analysis_mode?"done           ":"done");
249         }
250         return 0;
251 wav_abort_:
252 #ifdef FLAC__HAS_OGG
253         if(stream_info.is_ogg) {
254                 if(stream_info.decoder.stream) {
255                         if(FLAC__stream_decoder_get_state(stream_info.decoder.stream) != FLAC__STREAM_DECODER_UNINITIALIZED)
256                                 FLAC__stream_decoder_finish(stream_info.decoder.stream);
257                         FLAC__stream_decoder_delete(stream_info.decoder.stream);
258                 }
259         }
260         else
261 #endif
262         {
263                 if(stream_info.decoder.file) {
264                         if(FLAC__file_decoder_get_state(stream_info.decoder.file) != FLAC__FILE_DECODER_UNINITIALIZED)
265                                 FLAC__file_decoder_finish(stream_info.decoder.file);
266                         FLAC__file_decoder_delete(stream_info.decoder.file);
267                 }
268         }
269         if(0 != stream_info.fout && stream_info.fout != stdout) {
270                 fclose(stream_info.fout);
271                 unlink(outfilename);
272         }
273 #ifdef FLAC__HAS_OGG
274         if(stream_info.is_ogg) {
275                 if(0 != stream_info.fin && stream_info.fin != stdin)
276                         fclose(stream_info.fin);
277         }
278 #endif
279         if(analysis_mode)
280                 flac__analyze_finish(aopts);
281         return 1;
282 }
283
284 int flac__decode_raw(const char *infilename, const char *outfilename, FLAC__bool analysis_mode, analysis_options aopts, raw_decode_options_t options)
285 {
286         FLAC__bool md5_failure = false;
287         stream_info_struct stream_info;
288
289         stream_info.abort_flag = false;
290         stream_info.analysis_mode = analysis_mode;
291         stream_info.aopts = aopts;
292         stream_info.test_only = (outfilename == 0);
293         stream_info.is_wave_out = false;
294         stream_info.is_big_endian = options.is_big_endian;
295         stream_info.is_unsigned_samples = options.is_unsigned_samples;
296         stream_info.verbose = options.common.verbose;
297         stream_info.skip = options.common.skip;
298         stream_info.skip_count_too_high = false;
299         stream_info.samples_processed = 0;
300         stream_info.frame_counter = 0;
301 #ifdef FLAC__HAS_OGG
302         stream_info.is_ogg = options.common.is_ogg;
303 #endif
304         stream_info.decoder.file = 0; /* this zeroes stream_info.decoder.stream also */
305         stream_info.inbasefilename = flac__file_get_basename(infilename);
306         stream_info.fout = 0; /* initialized with an open file later if necessary */
307
308         FLAC__ASSERT(!(stream_info.test_only && stream_info.analysis_mode));
309
310         if(!stream_info.test_only) {
311                 if(0 == strcmp(outfilename, "-")) {
312                         stream_info.fout = stdout;
313                 }
314                 else {
315                         if(0 == (stream_info.fout = fopen(outfilename, "wb"))) {
316                                 fprintf(stderr, "%s: ERROR: can't open output file %s\n", stream_info.inbasefilename, outfilename);
317                                 return 1;
318                         }
319                 }
320         }
321
322 #ifdef FLAC__HAS_OGG
323         if(stream_info.is_ogg) {
324                 if (0 == strcmp(infilename, "-")) {
325                         stream_info.fin = stdin;
326                 } else {
327                         if (0 == (stream_info.fin = fopen(infilename, "rb"))) {
328                                 fprintf(stderr, "%s: ERROR: can't open input file %s\n", stream_info.inbasefilename, infilename);
329                                 if(stream_info.fout != stdout)
330                                         fclose(stream_info.fout);
331                                 return 1;
332                         }
333                 }
334         }
335 #endif
336
337         if(analysis_mode)
338                 flac__analyze_init(aopts);
339
340         if(!init(infilename, &stream_info))
341                 goto raw_abort_;
342
343         if(stream_info.skip > 0) {
344 #ifdef FLAC__HAS_OGG
345                 if(stream_info.is_ogg) { //@@@ (move this check into main.c)
346                         fprintf(stderr, "%s: ERROR, can't skip when decoding Ogg-FLAC yet; convert to native-FLAC first\n", stream_info.inbasefilename);
347                         goto raw_abort_;
348                 }
349 #endif
350                 if(!FLAC__file_decoder_process_metadata(stream_info.decoder.file)) {
351                         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)]);
352                         goto raw_abort_;
353                 }
354                 if(stream_info.skip_count_too_high) {
355                         fprintf(stderr, "%s: ERROR trying to skip more samples than in stream\n", stream_info.inbasefilename);
356                         goto raw_abort_;
357                 }
358                 if(!FLAC__file_decoder_seek_absolute(stream_info.decoder.file, stream_info.skip)) {
359                         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)]);
360                         goto raw_abort_;
361                 }
362                 if(!FLAC__file_decoder_process_remaining_frames(stream_info.decoder.file)) {
363                         if(stream_info.verbose) fprintf(stderr, "\n");
364                         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)]);
365                         goto raw_abort_;
366                 }
367                 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) {
368                         if(stream_info.verbose) fprintf(stderr, "\n");
369                         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)]);
370                         goto raw_abort_;
371                 }
372         }
373         else {
374 #ifdef FLAC__HAS_OGG
375                 if(stream_info.is_ogg) {
376                         if(!FLAC__stream_decoder_process_whole_stream(stream_info.decoder.stream)) {
377                                 if(stream_info.verbose) fprintf(stderr, "\n");
378                                 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)]);
379                                 goto raw_abort_;
380                         }
381                         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) {
382                                 if(stream_info.verbose) fprintf(stderr, "\n");
383                                 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)]);
384                                 goto raw_abort_;
385                         }
386                 }
387                 else
388 #endif
389                 {
390                         if(!FLAC__file_decoder_process_whole_file(stream_info.decoder.file)) {
391                                 if(stream_info.verbose) fprintf(stderr, "\n");
392                                 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)]);
393                                 goto raw_abort_;
394                         }
395                         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) {
396                                 if(stream_info.verbose) fprintf(stderr, "\n");
397                                 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)]);
398                                 goto raw_abort_;
399                         }
400                 }
401         }
402
403 #ifdef FLAC__HAS_OGG
404         if(stream_info.is_ogg) {
405                 if(stream_info.decoder.stream) {
406                         if(FLAC__stream_decoder_get_state(stream_info.decoder.stream) != FLAC__STREAM_DECODER_UNINITIALIZED)
407                                 FLAC__stream_decoder_finish(stream_info.decoder.stream);
408                         md5_failure = false;
409                         print_stats(&stream_info);
410                         FLAC__stream_decoder_delete(stream_info.decoder.stream);
411                 }
412         }
413         else
414 #endif
415         {
416                 if(stream_info.decoder.file) {
417                         if(FLAC__file_decoder_get_state(stream_info.decoder.file) != FLAC__FILE_DECODER_UNINITIALIZED)
418                                 md5_failure = !FLAC__file_decoder_finish(stream_info.decoder.file);
419                         print_stats(&stream_info);
420                         FLAC__file_decoder_delete(stream_info.decoder.file);
421                 }
422         }
423         if(0 != stream_info.fout && stream_info.fout != stdout)
424                 fclose(stream_info.fout);
425 #ifdef FLAC__HAS_OGG
426         if(stream_info.is_ogg) {
427                 if(0 != stream_info.fin && stream_info.fin != stdin)
428                         fclose(stream_info.fin);
429         }
430 #endif
431         if(analysis_mode)
432                 flac__analyze_finish(aopts);
433         if(md5_failure) {
434                 fprintf(stderr, "\r%s: WARNING, MD5 signature mismatch\n", stream_info.inbasefilename);
435         }
436         else {
437                 if(stream_info.verbose)
438                         fprintf(stderr, "\r%s: %s         \n", stream_info.inbasefilename, stream_info.test_only? "ok           ":analysis_mode?"done           ":"done");
439         }
440         return 0;
441 raw_abort_:
442 #ifdef FLAC__HAS_OGG
443         if(stream_info.is_ogg) {
444                 if(stream_info.decoder.stream) {
445                         if(FLAC__stream_decoder_get_state(stream_info.decoder.stream) != FLAC__STREAM_DECODER_UNINITIALIZED)
446                                 FLAC__stream_decoder_finish(stream_info.decoder.stream);
447                         FLAC__stream_decoder_delete(stream_info.decoder.stream);
448                 }
449         }
450         else
451 #endif
452         {
453                 if(stream_info.decoder.file) {
454                         if(FLAC__file_decoder_get_state(stream_info.decoder.file) != FLAC__FILE_DECODER_UNINITIALIZED)
455                                 FLAC__file_decoder_finish(stream_info.decoder.file);
456                         FLAC__file_decoder_delete(stream_info.decoder.file);
457                 }
458         }
459         if(0 != stream_info.fout && stream_info.fout != stdout) {
460                 fclose(stream_info.fout);
461                 unlink(outfilename);
462         }
463 #ifdef FLAC__HAS_OGG
464         if(stream_info.is_ogg) {
465                 if(0 != stream_info.fin && stream_info.fin != stdin)
466                         fclose(stream_info.fin);
467         }
468 #endif
469         if(analysis_mode)
470                 flac__analyze_finish(aopts);
471         return 1;
472 }
473
474 FLAC__bool init(const char *infilename, stream_info_struct *stream_info)
475 {
476         FLAC__uint32 test = 1;
477
478         is_big_endian_host = (*((FLAC__byte*)(&test)))? false : true;
479
480 #ifdef FLAC__HAS_OGG
481         if(stream_info->is_ogg) {
482                 stream_info->decoder.stream = FLAC__stream_decoder_new();
483
484                 if(0 == stream_info->decoder.stream) {
485                         fprintf(stderr, "%s: ERROR creating the decoder instance\n", stream_info->inbasefilename);
486                         return false;
487                 }
488
489                 FLAC__stream_decoder_set_read_callback(stream_info->decoder.stream, read_callback);
490                 /*
491                  * The three ugly casts here are to 'downcast' the 'void *' argument of
492                  * the callback down to 'FLAC__StreamDecoder *'.  In C++ this would be
493                  * unnecessary but here the cast makes the C compiler happy.
494                  */
495                 FLAC__stream_decoder_set_write_callback(stream_info->decoder.stream, (FLAC__StreamDecoderWriteStatus (*)(const FLAC__StreamDecoder *, const FLAC__Frame *, const FLAC__int32 *[], void *))write_callback);
496                 FLAC__stream_decoder_set_metadata_callback(stream_info->decoder.stream, (void (*)(const FLAC__StreamDecoder *, const FLAC__StreamMetaData *, void *))metadata_callback);
497                 FLAC__stream_decoder_set_error_callback(stream_info->decoder.stream, (void (*)(const FLAC__StreamDecoder *, FLAC__StreamDecoderErrorStatus, void *))error_callback);
498                 FLAC__stream_decoder_set_client_data(stream_info->decoder.stream, stream_info);
499
500                 if(FLAC__stream_decoder_init(stream_info->decoder.stream) != FLAC__STREAM_DECODER_SEARCH_FOR_METADATA) {
501                         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)]);
502                         return false;
503                 }
504
505                 ogg_stream_init(&stream_info->ogg.os, 0);
506                 ogg_sync_init(&stream_info->ogg.oy);
507         }
508         else
509 #endif
510         {
511                 stream_info->decoder.file = FLAC__file_decoder_new();
512
513                 if(0 == stream_info->decoder.file) {
514                         fprintf(stderr, "%s: ERROR creating the decoder instance\n", stream_info->inbasefilename);
515                         return false;
516                 }
517
518                 FLAC__file_decoder_set_md5_checking(stream_info->decoder.file, true);
519                 FLAC__file_decoder_set_filename(stream_info->decoder.file, infilename);
520                 /*
521                  * The three ugly casts here are to 'downcast' the 'void *' argument of
522                  * the callback down to 'FLAC__FileDecoder *'.  In C++ this would be
523                  * unnecessary but here the cast makes the C compiler happy.
524                  */
525                 FLAC__file_decoder_set_write_callback(stream_info->decoder.file, (FLAC__StreamDecoderWriteStatus (*)(const FLAC__FileDecoder *, const FLAC__Frame *, const FLAC__int32 *[], void *))write_callback);
526                 FLAC__file_decoder_set_metadata_callback(stream_info->decoder.file, (void (*)(const FLAC__FileDecoder *, const FLAC__StreamMetaData *, void *))metadata_callback);
527                 FLAC__file_decoder_set_error_callback(stream_info->decoder.file, (void (*)(const FLAC__FileDecoder *, FLAC__StreamDecoderErrorStatus, void *))error_callback);
528                 FLAC__file_decoder_set_client_data(stream_info->decoder.file, stream_info);
529
530                 if(FLAC__file_decoder_init(stream_info->decoder.file) != FLAC__FILE_DECODER_OK) {
531                         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)]);
532                         return false;
533                 }
534         }
535
536         return true;
537 }
538
539 FLAC__bool write_little_endian_uint16(FILE *f, FLAC__uint16 val)
540 {
541         FLAC__byte *b = (FLAC__byte*)(&val);
542         if(is_big_endian_host) {
543                 FLAC__byte tmp;
544                 tmp = b[1]; b[1] = b[0]; b[0] = tmp;
545         }
546         return fwrite(b, 1, 2, f) == 2;
547 }
548
549 FLAC__bool write_little_endian_uint32(FILE *f, FLAC__uint32 val)
550 {
551         FLAC__byte *b = (FLAC__byte*)(&val);
552         if(is_big_endian_host) {
553                 FLAC__byte tmp;
554                 tmp = b[3]; b[3] = b[0]; b[0] = tmp;
555                 tmp = b[2]; b[2] = b[1]; b[1] = tmp;
556         }
557         return fwrite(b, 1, 4, f) == 4;
558 }
559
560 #ifdef FLAC__HAS_OGG
561 #define OGG_READ_BUFFER_SIZE 4096
562 FLAC__StreamDecoderReadStatus read_callback(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], unsigned *bytes, void *client_data)
563 {
564         stream_info_struct *stream_info = (stream_info_struct *)client_data;
565         FILE *fin = stream_info->fin;
566         size_t bytes_read;
567         ogg_page og;
568         char *oggbuf;
569         unsigned int offset = 0;
570
571         *bytes = 0;
572
573         if (stream_info->abort_flag)
574                 return FLAC__STREAM_DECODER_READ_ABORT;
575
576         oggbuf = ogg_sync_buffer(&stream_info->ogg.oy, OGG_READ_BUFFER_SIZE);
577
578         (void)decoder; /* avoid compiler warning */
579
580         if(feof(fin))
581                 return FLAC__STREAM_DECODER_READ_END_OF_STREAM;
582
583         bytes_read = fread(oggbuf, 1, OGG_READ_BUFFER_SIZE, fin);
584
585         if(ferror(fin))
586                 return FLAC__STREAM_DECODER_READ_ABORT;
587
588         if(ogg_sync_wrote(&stream_info->ogg.oy, bytes_read) < 0)
589                 return FLAC__STREAM_DECODER_READ_ABORT;
590
591         while(ogg_sync_pageout(&stream_info->ogg.oy, &og) == 1) {
592                 if(ogg_stream_pagein(&stream_info->ogg.os, &og) == 0) {
593                         ogg_packet op;
594
595                         while(ogg_stream_packetout(&stream_info->ogg.os, &op) == 1) {
596                                 memcpy(buffer + offset, op.packet, op.bytes);
597                                 *bytes += op.bytes;
598                                 offset += op.bytes;
599                         }
600                 } else {
601                         return FLAC__STREAM_DECODER_READ_ABORT;
602                 }
603         }
604
605         return FLAC__STREAM_DECODER_READ_CONTINUE;
606 }
607 #endif
608
609 FLAC__StreamDecoderWriteStatus write_callback(const void *decoder, const FLAC__Frame *frame, const FLAC__int32 *buffer[], void *client_data)
610 {
611         stream_info_struct *stream_info = (stream_info_struct *)client_data;
612         FILE *fout = stream_info->fout;
613         unsigned bps = stream_info->bps, channels = stream_info->channels;
614         FLAC__bool is_big_endian = (stream_info->is_wave_out? false : stream_info->is_big_endian);
615         FLAC__bool is_unsigned_samples = (stream_info->is_wave_out? bps<=8 : stream_info->is_unsigned_samples);
616         unsigned wide_samples = frame->header.blocksize, wide_sample, sample, channel, byte;
617         static FLAC__int8 s8buffer[FLAC__MAX_BLOCK_SIZE * FLAC__MAX_CHANNELS * sizeof(FLAC__int32)]; /* WATCHOUT: can be up to 2 megs */
618         /* 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 */
619         FLAC__uint8  *u8buffer  = (FLAC__uint8  *)s8buffer;
620         FLAC__int16  *s16buffer = (FLAC__int16  *)s8buffer;
621         FLAC__uint16 *u16buffer = (FLAC__uint16 *)s8buffer;
622         FLAC__int32  *s32buffer = (FLAC__int32  *)s8buffer;
623         FLAC__uint32 *u32buffer = (FLAC__uint32 *)s8buffer;
624
625         (void)decoder;
626
627         if(stream_info->abort_flag)
628                 return FLAC__STREAM_DECODER_WRITE_ABORT;
629
630         stream_info->samples_processed += wide_samples;
631         stream_info->frame_counter++;
632
633         if(stream_info->verbose && !(stream_info->frame_counter & 0x7f))
634                 print_stats(stream_info);
635
636         if(stream_info->analysis_mode) {
637                 flac__analyze_frame(frame, stream_info->frame_counter-1, stream_info->aopts, fout);
638         }
639         else if(!stream_info->test_only) {
640                 if(bps == 8) {
641                         if(is_unsigned_samples) {
642                                 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
643                                         for(channel = 0; channel < channels; channel++, sample++)
644                                                 u8buffer[sample] = (FLAC__uint8)(buffer[channel][wide_sample] + 0x80);
645                         }
646                         else {
647                                 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
648                                         for(channel = 0; channel < channels; channel++, sample++)
649                                                 s8buffer[sample] = (FLAC__int8)(buffer[channel][wide_sample]);
650                         }
651                         if(fwrite(u8buffer, 1, sample, fout) != sample)
652                                 return FLAC__STREAM_DECODER_WRITE_ABORT;
653                 }
654                 else if(bps == 16) {
655                         if(is_unsigned_samples) {
656                                 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
657                                         for(channel = 0; channel < channels; channel++, sample++)
658                                                 u16buffer[sample] = (FLAC__uint16)(buffer[channel][wide_sample] + 0x8000);
659                         }
660                         else {
661                                 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
662                                         for(channel = 0; channel < channels; channel++, sample++)
663                                                 s16buffer[sample] = (FLAC__int16)(buffer[channel][wide_sample]);
664                         }
665                         if(is_big_endian != is_big_endian_host) {
666                                 unsigned char tmp;
667                                 const unsigned bytes = sample * 2;
668                                 for(byte = 0; byte < bytes; byte += 2) {
669                                         tmp = u8buffer[byte];
670                                         u8buffer[byte] = u8buffer[byte+1];
671                                         u8buffer[byte+1] = tmp;
672                                 }
673                         }
674                         if(fwrite(u16buffer, 2, sample, fout) != sample)
675                                 return FLAC__STREAM_DECODER_WRITE_ABORT;
676                 }
677                 else if(bps == 24) {
678                         if(is_unsigned_samples) {
679                                 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
680                                         for(channel = 0; channel < channels; channel++, sample++)
681                                                 u32buffer[sample] = buffer[channel][wide_sample] + 0x800000;
682                         }
683                         else {
684                                 for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
685                                         for(channel = 0; channel < channels; channel++, sample++)
686                                                 s32buffer[sample] = buffer[channel][wide_sample];
687                         }
688                         if(is_big_endian != is_big_endian_host) {
689                                 unsigned char tmp;
690                                 const unsigned bytes = sample * 4;
691                                 for(byte = 0; byte < bytes; byte += 4) {
692                                         tmp = u8buffer[byte];
693                                         u8buffer[byte] = u8buffer[byte+3];
694                                         u8buffer[byte+3] = tmp;
695                                         tmp = u8buffer[byte+1];
696                                         u8buffer[byte+1] = u8buffer[byte+2];
697                                         u8buffer[byte+2] = tmp;
698                                 }
699                         }
700                         if(is_big_endian) {
701                                 unsigned lbyte;
702                                 const unsigned bytes = sample * 4;
703                                 for(lbyte = byte = 0; byte < bytes; ) {
704                                         byte++;
705                                         u8buffer[lbyte++] = u8buffer[byte++];
706                                         u8buffer[lbyte++] = u8buffer[byte++];
707                                         u8buffer[lbyte++] = u8buffer[byte++];
708                                 }
709                         }
710                         else {
711                                 unsigned lbyte;
712                                 const unsigned bytes = sample * 4;
713                                 for(lbyte = byte = 0; byte < bytes; ) {
714                                         u8buffer[lbyte++] = u8buffer[byte++];
715                                         u8buffer[lbyte++] = u8buffer[byte++];
716                                         u8buffer[lbyte++] = u8buffer[byte++];
717                                         byte++;
718                                 }
719                         }
720                         if(fwrite(u8buffer, 3, sample, fout) != sample)
721                                 return FLAC__STREAM_DECODER_WRITE_ABORT;
722                 }
723                 else {
724                         FLAC__ASSERT(0);
725                 }
726         }
727         return FLAC__STREAM_DECODER_WRITE_CONTINUE;
728 }
729
730 void metadata_callback(const void *decoder, const FLAC__StreamMetaData *metadata, void *client_data)
731 {
732         stream_info_struct *stream_info = (stream_info_struct *)client_data;
733         (void)decoder;
734         if(metadata->type == FLAC__METADATA_TYPE_STREAMINFO) {
735                 /* remember, metadata->data.stream_info.total_samples can be 0, meaning 'unknown' */
736                 if(metadata->data.stream_info.total_samples > 0 && stream_info->skip >= metadata->data.stream_info.total_samples) {
737                         stream_info->total_samples = 0;
738                         stream_info->skip_count_too_high = true;
739                 }
740                 else
741                         stream_info->total_samples = metadata->data.stream_info.total_samples - stream_info->skip;
742                 stream_info->bps = metadata->data.stream_info.bits_per_sample;
743                 stream_info->channels = metadata->data.stream_info.channels;
744                 stream_info->sample_rate = metadata->data.stream_info.sample_rate;
745
746                 if(stream_info->bps != 8 && stream_info->bps != 16 && stream_info->bps != 24) {
747                         fprintf(stderr, "%s: ERROR: bits per sample is not 8/16/24\n", stream_info->inbasefilename);
748                         stream_info->abort_flag = true;
749                         return;
750                 }
751
752                 /* write the WAVE headers if necessary */
753                 if(!stream_info->analysis_mode && !stream_info->test_only && stream_info->is_wave_out) {
754                         FLAC__uint64 data_size = stream_info->total_samples * stream_info->channels * ((stream_info->bps+7)/8);
755                         if(data_size >= 0xFFFFFFDC) {
756                                 fprintf(stderr, "%s: ERROR: stream is too big to fit in a single WAVE file chunk\n", stream_info->inbasefilename);
757                                 stream_info->abort_flag = true;
758                                 return;
759                         }
760                         if(fwrite("RIFF", 1, 4, stream_info->fout) != 4) stream_info->abort_flag = true;
761                         if(!write_little_endian_uint32(stream_info->fout, (FLAC__uint32)(data_size+36))) stream_info->abort_flag = true; /* filesize-8 */
762                         if(fwrite("WAVEfmt ", 1, 8, stream_info->fout) != 8) stream_info->abort_flag = true;
763                         if(fwrite("\020\000\000\000", 1, 4, stream_info->fout) != 4) stream_info->abort_flag = true; /* chunk size = 16 */
764                         if(fwrite("\001\000", 1, 2, stream_info->fout) != 2) stream_info->abort_flag = true; /* compression code == 1 */
765                         if(!write_little_endian_uint16(stream_info->fout, (FLAC__uint16)(stream_info->channels))) stream_info->abort_flag = true;
766                         if(!write_little_endian_uint32(stream_info->fout, stream_info->sample_rate)) stream_info->abort_flag = true;
767                         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 ??? */
768                         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 */
769                         if(!write_little_endian_uint16(stream_info->fout, (FLAC__uint16)(stream_info->bps))) stream_info->abort_flag = true; /* bits per sample */
770                         if(fwrite("data", 1, 4, stream_info->fout) != 4) stream_info->abort_flag = true;
771                         if(!write_little_endian_uint32(stream_info->fout, (FLAC__uint32)data_size)) stream_info->abort_flag = true; /* data size */
772                 }
773         }
774 }
775
776 void error_callback(const void *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
777 {
778         stream_info_struct *stream_info = (stream_info_struct *)client_data;
779         (void)decoder;
780         fprintf(stderr, "%s: *** Got error code %d:%s\n", stream_info->inbasefilename, status, FLAC__StreamDecoderErrorStatusString[status]);
781         stream_info->abort_flag = true;
782 }
783
784 void print_stats(const stream_info_struct *stream_info)
785 {
786         if(stream_info->verbose) {
787 #if defined _MSC_VER || defined __MINGW32__
788                 /* with VC++ you have to spoon feed it the casting */
789                 const double progress = (double)(FLAC__int64)stream_info->samples_processed / (double)(FLAC__int64)stream_info->total_samples * 100.0;
790 #else
791                 const double progress = (double)stream_info->samples_processed / (double)stream_info->total_samples * 100.0;
792 #endif
793                 if(stream_info->total_samples > 0) {
794                         fprintf(stderr, "\r%s: %s%u%% complete",
795                                 stream_info->inbasefilename,
796                                 stream_info->test_only? "testing, " : stream_info->analysis_mode? "analyzing, " : "",
797                                 (unsigned)floor(progress + 0.5)
798                         );
799                 }
800                 else {
801                         fprintf(stderr, "\r%s: %s %u samples",
802                                 stream_info->inbasefilename,
803                                 stream_info->test_only? "tested" : stream_info->analysis_mode? "analyzed" : "wrote",
804                                 (unsigned)stream_info->samples_processed
805                         );
806                 }
807         }
808 }