change Coder to Codec everywhere
[flac.git] / src / libFLAC / file_decoder.c
1 /* libFLAC - Free Lossless Audio Codec library
2  * Copyright (C) 2000,2001  Josh Coalson
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Library General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library 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 GNU
12  * Library General Public License for more details.
13  *
14  * You should have received a copy of the GNU Library General Public
15  * License along with this library; if not, write to the
16  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17  * Boston, MA  02111-1307, USA.
18  */
19
20 #include <assert.h>
21 #include <stdio.h>
22 #include <stdlib.h> /* for malloc() */
23 #include <string.h> /* for strcmp() */
24 #include "FLAC/file_decoder.h"
25 #include "protected/stream_decoder.h"
26 #include "private/md5.h"
27
28 typedef struct FLAC__FileDecoderPrivate {
29         FLAC__StreamDecoderWriteStatus (*write_callback)(const FLAC__FileDecoder *decoder, const FLAC__Frame *frame, const int32 *buffer[], void *client_data);
30         void (*metadata_callback)(const FLAC__FileDecoder *decoder, const FLAC__StreamMetaData *metadata, void *client_data);
31         void (*error_callback)(const FLAC__FileDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
32         void *client_data;
33         FILE *file;
34         FLAC__StreamDecoder *stream;
35         struct MD5Context md5context;
36         byte stored_md5sum[16]; /* this is what is stored in the metadata */
37         byte computed_md5sum[16]; /* this is the sum we computed from the decoded data */
38         /* the rest of these are only used for seeking: */
39         FLAC__StreamMetaData_Encoding metadata; /* we keep this around so we can figure out how to seek quickly */
40         FLAC__Frame last_frame; /* holds the info of the last frame we seeked to */
41         uint64 target_sample;
42 } FLAC__FileDecoderPrivate;
43
44 static FLAC__StreamDecoderReadStatus read_callback_(const FLAC__StreamDecoder *decoder, byte buffer[], unsigned *bytes, void *client_data);
45 static FLAC__StreamDecoderWriteStatus write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const int32 *buffer[], void *client_data);
46 static void metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetaData *metadata, void *client_data);
47 static void error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
48 static bool seek_to_absolute_sample_(FLAC__FileDecoder *decoder, long filesize, uint64 target_sample);
49
50 const char *FLAC__FileDecoderStateString[] = {
51         "FLAC__FILE_DECODER_OK",
52         "FLAC__FILE_DECODER_SEEKING",
53         "FLAC__FILE_DECODER_END_OF_FILE",
54         "FLAC__FILE_DECODER_ERROR_OPENING_FILE",
55         "FLAC__FILE_DECODER_MEMORY_ALLOCATION_ERROR",
56         "FLAC__FILE_DECODER_SEEK_ERROR",
57         "FLAC__FILE_DECODER_STREAM_ERROR",
58         "FLAC__FILE_DECODER_UNINITIALIZED"
59 };
60
61 FLAC__FileDecoder *FLAC__file_decoder_get_new_instance()
62 {
63         FLAC__FileDecoder *decoder = (FLAC__FileDecoder*)malloc(sizeof(FLAC__FileDecoder));
64         if(decoder != 0) {
65                 decoder->state = FLAC__FILE_DECODER_UNINITIALIZED;
66                 decoder->guts = 0;
67         }
68         return decoder;
69 }
70
71 void FLAC__file_decoder_free_instance(FLAC__FileDecoder *decoder)
72 {
73         free(decoder);
74 }
75
76 FLAC__FileDecoderState FLAC__file_decoder_init(
77         FLAC__FileDecoder *decoder,
78         const char *filename,
79         FLAC__StreamDecoderWriteStatus (*write_callback)(const FLAC__FileDecoder *decoder, const FLAC__Frame *frame, const int32 *buffer[], void *client_data),
80         void (*metadata_callback)(const FLAC__FileDecoder *decoder, const FLAC__StreamMetaData *metadata, void *client_data),
81         void (*error_callback)(const FLAC__FileDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data),
82         void *client_data
83 )
84 {
85         assert(sizeof(int) >= 4); /* we want to die right away if this is not true */
86         assert(decoder != 0);
87         assert(write_callback != 0);
88         assert(metadata_callback != 0);
89         assert(error_callback != 0);
90         assert(decoder->state == FLAC__FILE_DECODER_UNINITIALIZED);
91         assert(decoder->guts == 0);
92
93         decoder->state = FLAC__FILE_DECODER_OK;
94
95         decoder->guts = (FLAC__FileDecoderPrivate*)malloc(sizeof(FLAC__FileDecoderPrivate));
96         if(decoder->guts == 0)
97                 return decoder->state = FLAC__FILE_DECODER_MEMORY_ALLOCATION_ERROR;
98
99         decoder->guts->write_callback = write_callback;
100         decoder->guts->metadata_callback = metadata_callback;
101         decoder->guts->error_callback = error_callback;
102         decoder->guts->client_data = client_data;
103         decoder->guts->stream = 0;
104
105         if(0 == strcmp(filename, "-"))
106                 decoder->guts->file = stdin;
107         else
108                 decoder->guts->file = fopen(filename, "rb");
109         if(decoder->guts->file == 0)
110                 return decoder->state = FLAC__FILE_DECODER_ERROR_OPENING_FILE;
111
112         /* We initialize the MD5Context even though we may never use it.  This is
113          * because check_md5 may be turned on to start and then turned off if a
114          * seek occurs.  So we always init the context here and finalize it in
115          * FLAC__file_decoder_finish() to make sure things are always cleaned up
116          *properly.
117          */
118         MD5Init(&decoder->guts->md5context);
119
120         decoder->guts->stream = FLAC__stream_decoder_get_new_instance();
121         if(FLAC__stream_decoder_init(decoder->guts->stream, read_callback_, write_callback_, metadata_callback_, error_callback_, decoder) != FLAC__STREAM_DECODER_SEARCH_FOR_METADATA)
122                 return decoder->state = FLAC__FILE_DECODER_MEMORY_ALLOCATION_ERROR; /* this is based on internal knowledge of FLAC__stream_decoder_init() */
123
124         return decoder->state;
125 }
126
127 bool FLAC__file_decoder_finish(FLAC__FileDecoder *decoder)
128 {
129         bool md5_failed = false;
130
131         assert(decoder != 0);
132         if(decoder->state == FLAC__FILE_DECODER_UNINITIALIZED)
133                 return true;
134         if(decoder->guts != 0) {
135                 if(decoder->guts->file != 0 && decoder->guts->file != stdin)
136                         fclose(decoder->guts->file);
137                 /* see the comment in FLAC__file_decoder_init() as to why we always
138                  * call MD5Final()
139                  */
140                 MD5Final(decoder->guts->computed_md5sum, &decoder->guts->md5context);
141                 if(decoder->guts->stream != 0) {
142                         FLAC__stream_decoder_finish(decoder->guts->stream);
143                         FLAC__stream_decoder_free_instance(decoder->guts->stream);
144                 }
145                 if(decoder->check_md5) {
146                         if(memcmp(decoder->guts->stored_md5sum, decoder->guts->computed_md5sum, 16))
147                                 md5_failed = true;
148                 }
149                 free(decoder->guts);
150                 decoder->guts = 0;
151         }
152         decoder->state = FLAC__FILE_DECODER_UNINITIALIZED;
153         return !md5_failed;
154 }
155
156 bool FLAC__file_decoder_process_whole_file(FLAC__FileDecoder *decoder)
157 {
158         bool ret;
159         assert(decoder != 0);
160
161         if(decoder->state == FLAC__FILE_DECODER_END_OF_FILE)
162                 return true;
163
164         assert(decoder->state == FLAC__FILE_DECODER_OK);
165
166         ret = FLAC__stream_decoder_process_whole_stream(decoder->guts->stream);
167         if(!ret)
168                 decoder->state = FLAC__FILE_DECODER_STREAM_ERROR;
169
170         return ret;
171 }
172
173 bool FLAC__file_decoder_process_metadata(FLAC__FileDecoder *decoder)
174 {
175         bool ret;
176         assert(decoder != 0);
177
178         if(decoder->state == FLAC__FILE_DECODER_END_OF_FILE)
179                 return true;
180
181         assert(decoder->state == FLAC__FILE_DECODER_OK);
182
183         ret = FLAC__stream_decoder_process_metadata(decoder->guts->stream);
184         if(!ret)
185                 decoder->state = FLAC__FILE_DECODER_STREAM_ERROR;
186
187         return ret;
188 }
189
190 bool FLAC__file_decoder_process_one_frame(FLAC__FileDecoder *decoder)
191 {
192         bool ret;
193         assert(decoder != 0);
194
195         if(decoder->state == FLAC__FILE_DECODER_END_OF_FILE)
196                 return true;
197
198         assert(decoder->state == FLAC__FILE_DECODER_OK);
199
200         ret = FLAC__stream_decoder_process_one_frame(decoder->guts->stream);
201         if(!ret)
202                 decoder->state = FLAC__FILE_DECODER_STREAM_ERROR;
203
204         return ret;
205 }
206
207 bool FLAC__file_decoder_process_remaining_frames(FLAC__FileDecoder *decoder)
208 {
209         bool ret;
210         assert(decoder != 0);
211
212         if(decoder->state == FLAC__FILE_DECODER_END_OF_FILE)
213                 return true;
214
215         assert(decoder->state == FLAC__FILE_DECODER_OK);
216
217         ret = FLAC__stream_decoder_process_remaining_frames(decoder->guts->stream);
218         if(!ret)
219                 decoder->state = FLAC__FILE_DECODER_STREAM_ERROR;
220
221         return ret;
222 }
223
224 bool FLAC__file_decoder_seek_absolute(FLAC__FileDecoder *decoder, uint64 sample)
225 {
226         long filesize;
227
228         assert(decoder != 0);
229         assert(decoder->state == FLAC__FILE_DECODER_OK);
230
231         decoder->state = FLAC__FILE_DECODER_SEEKING;
232
233         /* turn off md5 checking if a seek is attempted */
234         decoder->check_md5 = false;
235
236         if(!FLAC__stream_decoder_reset(decoder->guts->stream)) {
237                 decoder->state = FLAC__FILE_DECODER_STREAM_ERROR;
238                 return false;
239         }
240         /* get the file length */
241         if(0 != fseek(decoder->guts->file, 0, SEEK_END)) {
242                 decoder->state = FLAC__FILE_DECODER_SEEK_ERROR;
243                 return false;
244         }
245         fflush(decoder->guts->file);
246         if(-1 == (filesize = ftell(decoder->guts->file))) {
247                 decoder->state = FLAC__FILE_DECODER_SEEK_ERROR;
248                 return false;
249         }
250         /* rewind */
251         if(0 != fseek(decoder->guts->file, 0, SEEK_SET)) {
252                 decoder->state = FLAC__FILE_DECODER_SEEK_ERROR;
253                 return false;
254         }
255         if(!FLAC__stream_decoder_process_metadata(decoder->guts->stream)) {
256                 decoder->state = FLAC__FILE_DECODER_STREAM_ERROR;
257                 return false;
258         }
259         if(sample > decoder->guts->metadata.total_samples) {
260                 decoder->state = FLAC__FILE_DECODER_SEEK_ERROR;
261                 return false;
262         }
263
264         return seek_to_absolute_sample_(decoder, filesize, sample);
265 }
266
267 FLAC__StreamDecoderReadStatus read_callback_(const FLAC__StreamDecoder *decoder, byte buffer[], unsigned *bytes, void *client_data)
268 {
269         FLAC__FileDecoder *file_decoder = (FLAC__FileDecoder *)client_data;
270         (void)decoder;
271         if(feof(file_decoder->guts->file)) {
272                 file_decoder->state = FLAC__FILE_DECODER_END_OF_FILE;
273                 return FLAC__STREAM_DECODER_READ_END_OF_STREAM;
274         }
275         else if(*bytes > 0) {
276                 size_t bytes_read = fread(buffer, sizeof(byte), *bytes, file_decoder->guts->file);
277                 if(bytes_read == 0) {
278                         if(feof(file_decoder->guts->file)) {
279                                 file_decoder->state = FLAC__FILE_DECODER_END_OF_FILE;
280                                 return FLAC__STREAM_DECODER_READ_END_OF_STREAM;
281                         }
282                         else
283                                 return FLAC__STREAM_DECODER_READ_ABORT;
284                 }
285                 else {
286                         *bytes = (unsigned)bytes_read;
287                         return FLAC__STREAM_DECODER_READ_CONTINUE;
288                 }
289         }
290         else
291                 return FLAC__STREAM_DECODER_READ_ABORT; /* abort to avoid a deadlock */
292 }
293
294 FLAC__StreamDecoderWriteStatus write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const int32 *buffer[], void *client_data)
295 {
296         FLAC__FileDecoder *file_decoder = (FLAC__FileDecoder *)client_data;
297         (void)decoder;
298
299         if(file_decoder->state == FLAC__FILE_DECODER_SEEKING) {
300                 uint64 this_frame_sample = frame->header.number.sample_number;
301                 uint64 next_frame_sample = this_frame_sample + (uint64)frame->header.blocksize;
302                 uint64 target_sample = file_decoder->guts->target_sample;
303
304                 file_decoder->guts->last_frame = *frame; /* save the frame in the guts */
305                 if(this_frame_sample <= target_sample && target_sample < next_frame_sample) { /* we hit our target frame */
306                         unsigned delta = (unsigned)(target_sample - this_frame_sample);
307                         /* kick out of seek mode */
308                         file_decoder->state = FLAC__FILE_DECODER_OK;
309                         /* shift out the samples before target_sample */
310                         if(delta > 0) {
311                                 unsigned channel;
312                                 const int32 *newbuffer[FLAC__MAX_CHANNELS];
313                                 for(channel = 0; channel < frame->header.channels; channel++)
314                                         newbuffer[channel] = buffer[channel] + delta;
315                                 file_decoder->guts->last_frame.header.blocksize -= delta;
316                                 file_decoder->guts->last_frame.header.number.sample_number += (uint64)delta;
317                                 /* write the relevant samples */
318                                 return file_decoder->guts->write_callback(file_decoder, &file_decoder->guts->last_frame, newbuffer, file_decoder->guts->client_data);
319                         }
320                         else {
321                                 /* write the relevant samples */
322                                 return file_decoder->guts->write_callback(file_decoder, frame, buffer, file_decoder->guts->client_data);
323                         }
324                 }
325                 else {
326                         return FLAC__STREAM_DECODER_WRITE_CONTINUE;
327                 }
328         }
329         else {
330                 if(file_decoder->check_md5) {
331                         if(!FLAC__MD5Accumulate(&file_decoder->guts->md5context, buffer, frame->header.channels, frame->header.blocksize, (frame->header.bits_per_sample+7) / 8))
332                                 return FLAC__STREAM_DECODER_WRITE_ABORT;
333                 }
334                 return file_decoder->guts->write_callback(file_decoder, frame, buffer, file_decoder->guts->client_data);
335         }
336 }
337
338 void metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetaData *metadata, void *client_data)
339 {
340         FLAC__FileDecoder *file_decoder = (FLAC__FileDecoder *)client_data;
341         (void)decoder;
342
343         if(metadata->type == FLAC__METADATA_TYPE_ENCODING) {
344                 file_decoder->guts->metadata = metadata->data.encoding;
345                 /* save the MD5 signature for comparison later */
346                 memcpy(file_decoder->guts->stored_md5sum, metadata->data.encoding.md5sum, 16);
347                 if(0 == memcmp(file_decoder->guts->stored_md5sum, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", 16))
348                         file_decoder->check_md5 = false;
349         }
350         if(file_decoder->state != FLAC__FILE_DECODER_SEEKING)
351                 file_decoder->guts->metadata_callback(file_decoder, metadata, file_decoder->guts->client_data);
352 }
353
354 void error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
355 {
356         FLAC__FileDecoder *file_decoder = (FLAC__FileDecoder *)client_data;
357         (void)decoder;
358
359         if(file_decoder->state != FLAC__FILE_DECODER_SEEKING)
360                 file_decoder->guts->error_callback(file_decoder, status, file_decoder->guts->client_data);
361 }
362
363 bool seek_to_absolute_sample_(FLAC__FileDecoder *decoder, long filesize, uint64 target_sample)
364 {
365         long l, r, pos, last_pos = -1;
366         unsigned approx_bytes_per_frame;
367         uint64 last_frame_sample = 0xffffffffffffffff;
368         bool needs_seek;
369         const bool is_variable_blocksize_stream = (decoder->guts->metadata.min_blocksize != decoder->guts->metadata.max_blocksize);
370
371         if(!is_variable_blocksize_stream) {
372                 /* we are just guessing here, but we want to guess high, not low */
373                 /* note there are no () around 'decoder->guts->metadata.bits_per_sample/8' to keep precision up since it's an integer calulation */
374                 approx_bytes_per_frame = decoder->guts->metadata.min_blocksize * decoder->guts->metadata.channels * decoder->guts->metadata.bits_per_sample/8 + 64;
375         }
376         else
377                 approx_bytes_per_frame = 1152 * decoder->guts->metadata.channels * decoder->guts->metadata.bits_per_sample/8 + 64;
378
379         /* Now we need to use the metadata and the filelength to search to the frame with the correct sample */
380         if(-1 == (l = ftell(decoder->guts->file))) {
381                 decoder->state = FLAC__FILE_DECODER_SEEK_ERROR;
382                 return false;
383         }
384         l -= FLAC__stream_decoder_input_bytes_unconsumed(decoder->guts->stream);
385 #ifdef _MSC_VER
386         /* with VC++ you have to spoon feed it the casting */
387         pos = l + (long)((double)(int64)target_sample / (double)(int64)decoder->guts->metadata.total_samples * (double)(filesize-l+1)) - approx_bytes_per_frame;
388 #else
389         pos = l + (long)((double)target_sample / (double)decoder->guts->metadata.total_samples * (double)(filesize-l+1)) - approx_bytes_per_frame;
390 #endif
391         r = filesize - ((decoder->guts->metadata.channels * decoder->guts->metadata.bits_per_sample * FLAC__MAX_BLOCK_SIZE) / 8 + 64);
392         if(pos >= r)
393                 pos = r-1;
394         if(pos < l)
395                 pos = l;
396         needs_seek = true;
397
398         decoder->guts->target_sample = target_sample;
399         while(1) {
400                 if(needs_seek) {
401                         if(-1 == fseek(decoder->guts->file, pos, SEEK_SET)) {
402                                 decoder->state = FLAC__FILE_DECODER_SEEK_ERROR;
403                                 return false;
404                         }
405                         if(!FLAC__stream_decoder_flush(decoder->guts->stream)) {
406                                 decoder->state = FLAC__FILE_DECODER_STREAM_ERROR;
407                                 return false;
408                         }
409                 }
410                 if(!FLAC__stream_decoder_process_one_frame(decoder->guts->stream)) {
411                         decoder->state = FLAC__FILE_DECODER_SEEK_ERROR;
412                         return false;
413                 }
414                 /* our write callback will change the state when it gets to the target frame */
415                 if(decoder->state != FLAC__FILE_DECODER_SEEKING) {
416                         break;
417                 }
418                 else { /* we need to narrow the search */
419                         uint64 this_frame_sample = decoder->guts->last_frame.header.number.sample_number;
420                         if(this_frame_sample == last_frame_sample) {
421                                 /* our last move backwards wasn't big enough */
422                                 pos -= (last_pos - pos);
423                                 needs_seek = true;
424                         }
425                         else {
426                                 if(target_sample < this_frame_sample) {
427                                         last_pos = pos;
428                                         approx_bytes_per_frame = decoder->guts->last_frame.header.blocksize * decoder->guts->last_frame.header.channels * decoder->guts->last_frame.header.bits_per_sample/8 + 64;
429                                         pos -= approx_bytes_per_frame;
430                                         needs_seek = true;
431                                 }
432                                 else {
433                                         last_pos = pos;
434                                         if(-1 == (pos = ftell(decoder->guts->file))) {
435                                                 decoder->state = FLAC__FILE_DECODER_SEEK_ERROR;
436                                                 return false;
437                                         }
438                                         pos -= FLAC__stream_decoder_input_bytes_unconsumed(decoder->guts->stream);
439                                         needs_seek = false;
440                                 }
441                         }
442                         if(pos < l)
443                                 pos = l;
444                         last_frame_sample = this_frame_sample;
445                 }
446         }
447
448         return true;
449 }