fix bug where pos could move to before the beginning of the file
[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_StreamInfo stream_info; /* 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->guts->stream->state == FLAC__STREAM_DECODER_END_OF_STREAM)
162                 decoder->state = FLAC__FILE_DECODER_END_OF_FILE;
163
164         if(decoder->state == FLAC__FILE_DECODER_END_OF_FILE)
165                 return true;
166
167         assert(decoder->state == FLAC__FILE_DECODER_OK);
168
169         ret = FLAC__stream_decoder_process_whole_stream(decoder->guts->stream);
170         if(!ret)
171                 decoder->state = FLAC__FILE_DECODER_STREAM_ERROR;
172
173         return ret;
174 }
175
176 bool FLAC__file_decoder_process_metadata(FLAC__FileDecoder *decoder)
177 {
178         bool ret;
179         assert(decoder != 0);
180
181         if(decoder->guts->stream->state == FLAC__STREAM_DECODER_END_OF_STREAM)
182                 decoder->state = FLAC__FILE_DECODER_END_OF_FILE;
183
184         if(decoder->state == FLAC__FILE_DECODER_END_OF_FILE)
185                 return true;
186
187         assert(decoder->state == FLAC__FILE_DECODER_OK);
188
189         ret = FLAC__stream_decoder_process_metadata(decoder->guts->stream);
190         if(!ret)
191                 decoder->state = FLAC__FILE_DECODER_STREAM_ERROR;
192
193         return ret;
194 }
195
196 bool FLAC__file_decoder_process_one_frame(FLAC__FileDecoder *decoder)
197 {
198         bool ret;
199         assert(decoder != 0);
200
201         if(decoder->guts->stream->state == FLAC__STREAM_DECODER_END_OF_STREAM)
202                 decoder->state = FLAC__FILE_DECODER_END_OF_FILE;
203
204         if(decoder->state == FLAC__FILE_DECODER_END_OF_FILE)
205                 return true;
206
207         assert(decoder->state == FLAC__FILE_DECODER_OK);
208
209         ret = FLAC__stream_decoder_process_one_frame(decoder->guts->stream);
210         if(!ret)
211                 decoder->state = FLAC__FILE_DECODER_STREAM_ERROR;
212
213         return ret;
214 }
215
216 bool FLAC__file_decoder_process_remaining_frames(FLAC__FileDecoder *decoder)
217 {
218         bool ret;
219         assert(decoder != 0);
220
221         if(decoder->guts->stream->state == FLAC__STREAM_DECODER_END_OF_STREAM)
222                 decoder->state = FLAC__FILE_DECODER_END_OF_FILE;
223
224         if(decoder->state == FLAC__FILE_DECODER_END_OF_FILE)
225                 return true;
226
227         assert(decoder->state == FLAC__FILE_DECODER_OK);
228
229         ret = FLAC__stream_decoder_process_remaining_frames(decoder->guts->stream);
230         if(!ret)
231                 decoder->state = FLAC__FILE_DECODER_STREAM_ERROR;
232
233         return ret;
234 }
235
236 bool FLAC__file_decoder_seek_absolute(FLAC__FileDecoder *decoder, uint64 sample)
237 {
238         long filesize;
239
240         assert(decoder != 0);
241         assert(decoder->state == FLAC__FILE_DECODER_OK);
242
243         decoder->state = FLAC__FILE_DECODER_SEEKING;
244
245         /* turn off md5 checking if a seek is attempted */
246         decoder->check_md5 = false;
247
248         if(!FLAC__stream_decoder_reset(decoder->guts->stream)) {
249                 decoder->state = FLAC__FILE_DECODER_STREAM_ERROR;
250                 return false;
251         }
252         /* get the file length */
253         if(0 != fseek(decoder->guts->file, 0, SEEK_END)) {
254                 decoder->state = FLAC__FILE_DECODER_SEEK_ERROR;
255                 return false;
256         }
257         fflush(decoder->guts->file);
258         if(-1 == (filesize = ftell(decoder->guts->file))) {
259                 decoder->state = FLAC__FILE_DECODER_SEEK_ERROR;
260                 return false;
261         }
262         /* rewind */
263         if(0 != fseek(decoder->guts->file, 0, SEEK_SET)) {
264                 decoder->state = FLAC__FILE_DECODER_SEEK_ERROR;
265                 return false;
266         }
267         if(!FLAC__stream_decoder_process_metadata(decoder->guts->stream)) {
268                 decoder->state = FLAC__FILE_DECODER_STREAM_ERROR;
269                 return false;
270         }
271         if(sample > decoder->guts->stream_info.total_samples) {
272                 decoder->state = FLAC__FILE_DECODER_SEEK_ERROR;
273                 return false;
274         }
275
276         return seek_to_absolute_sample_(decoder, filesize, sample);
277 }
278
279 FLAC__StreamDecoderReadStatus read_callback_(const FLAC__StreamDecoder *decoder, byte buffer[], unsigned *bytes, void *client_data)
280 {
281         FLAC__FileDecoder *file_decoder = (FLAC__FileDecoder *)client_data;
282         (void)decoder;
283         if(feof(file_decoder->guts->file)) {
284                 file_decoder->state = FLAC__FILE_DECODER_END_OF_FILE;
285                 return FLAC__STREAM_DECODER_READ_END_OF_STREAM;
286         }
287         else if(*bytes > 0) {
288                 size_t bytes_read = fread(buffer, sizeof(byte), *bytes, file_decoder->guts->file);
289                 if(bytes_read == 0) {
290                         if(feof(file_decoder->guts->file)) {
291                                 file_decoder->state = FLAC__FILE_DECODER_END_OF_FILE;
292                                 return FLAC__STREAM_DECODER_READ_END_OF_STREAM;
293                         }
294                         else
295                                 return FLAC__STREAM_DECODER_READ_ABORT;
296                 }
297                 else {
298                         *bytes = (unsigned)bytes_read;
299                         return FLAC__STREAM_DECODER_READ_CONTINUE;
300                 }
301         }
302         else
303                 return FLAC__STREAM_DECODER_READ_ABORT; /* abort to avoid a deadlock */
304 }
305
306 FLAC__StreamDecoderWriteStatus write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const int32 *buffer[], void *client_data)
307 {
308         FLAC__FileDecoder *file_decoder = (FLAC__FileDecoder *)client_data;
309         (void)decoder;
310
311         if(file_decoder->state == FLAC__FILE_DECODER_SEEKING) {
312                 uint64 this_frame_sample = frame->header.number.sample_number;
313                 uint64 next_frame_sample = this_frame_sample + (uint64)frame->header.blocksize;
314                 uint64 target_sample = file_decoder->guts->target_sample;
315
316                 file_decoder->guts->last_frame = *frame; /* save the frame in the guts */
317                 if(this_frame_sample <= target_sample && target_sample < next_frame_sample) { /* we hit our target frame */
318                         unsigned delta = (unsigned)(target_sample - this_frame_sample);
319                         /* kick out of seek mode */
320                         file_decoder->state = FLAC__FILE_DECODER_OK;
321                         /* shift out the samples before target_sample */
322                         if(delta > 0) {
323                                 unsigned channel;
324                                 const int32 *newbuffer[FLAC__MAX_CHANNELS];
325                                 for(channel = 0; channel < frame->header.channels; channel++)
326                                         newbuffer[channel] = buffer[channel] + delta;
327                                 file_decoder->guts->last_frame.header.blocksize -= delta;
328                                 file_decoder->guts->last_frame.header.number.sample_number += (uint64)delta;
329                                 /* write the relevant samples */
330                                 return file_decoder->guts->write_callback(file_decoder, &file_decoder->guts->last_frame, newbuffer, file_decoder->guts->client_data);
331                         }
332                         else {
333                                 /* write the relevant samples */
334                                 return file_decoder->guts->write_callback(file_decoder, frame, buffer, file_decoder->guts->client_data);
335                         }
336                 }
337                 else {
338                         return FLAC__STREAM_DECODER_WRITE_CONTINUE;
339                 }
340         }
341         else {
342                 if(file_decoder->check_md5) {
343                         if(!FLAC__MD5Accumulate(&file_decoder->guts->md5context, buffer, frame->header.channels, frame->header.blocksize, (frame->header.bits_per_sample+7) / 8))
344                                 return FLAC__STREAM_DECODER_WRITE_ABORT;
345                 }
346                 return file_decoder->guts->write_callback(file_decoder, frame, buffer, file_decoder->guts->client_data);
347         }
348 }
349
350 void metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetaData *metadata, void *client_data)
351 {
352         FLAC__FileDecoder *file_decoder = (FLAC__FileDecoder *)client_data;
353         (void)decoder;
354
355         if(metadata->type == FLAC__METADATA_TYPE_STREAMINFO) {
356                 file_decoder->guts->stream_info = metadata->data.stream_info;
357                 /* save the MD5 signature for comparison later */
358                 memcpy(file_decoder->guts->stored_md5sum, metadata->data.stream_info.md5sum, 16);
359                 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))
360                         file_decoder->check_md5 = false;
361         }
362         if(file_decoder->state != FLAC__FILE_DECODER_SEEKING)
363                 file_decoder->guts->metadata_callback(file_decoder, metadata, file_decoder->guts->client_data);
364 }
365
366 void error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
367 {
368         FLAC__FileDecoder *file_decoder = (FLAC__FileDecoder *)client_data;
369         (void)decoder;
370
371         if(file_decoder->state != FLAC__FILE_DECODER_SEEKING)
372                 file_decoder->guts->error_callback(file_decoder, status, file_decoder->guts->client_data);
373 }
374
375 bool seek_to_absolute_sample_(FLAC__FileDecoder *decoder, long filesize, uint64 target_sample)
376 {
377         long l, r, pos, last_pos = -1;
378         unsigned approx_bytes_per_frame;
379         uint64 last_frame_sample = 0xffffffffffffffff;
380         bool needs_seek;
381         const bool is_variable_blocksize_stream = (decoder->guts->stream_info.min_blocksize != decoder->guts->stream_info.max_blocksize);
382
383         if(!is_variable_blocksize_stream) {
384                 /* we are just guessing here, but we want to guess high, not low */
385                 /* note there are no () around 'decoder->guts->stream_info.bits_per_sample/8' to keep precision up since it's an integer calulation */
386                 approx_bytes_per_frame = decoder->guts->stream_info.min_blocksize * decoder->guts->stream_info.channels * decoder->guts->stream_info.bits_per_sample/8 + 64;
387         }
388         else
389                 approx_bytes_per_frame = 1152 * decoder->guts->stream_info.channels * decoder->guts->stream_info.bits_per_sample/8 + 64;
390
391         /* Now we need to use the metadata and the filelength to search to the frame with the correct sample */
392         if(-1 == (l = ftell(decoder->guts->file))) {
393                 decoder->state = FLAC__FILE_DECODER_SEEK_ERROR;
394                 return false;
395         }
396         l -= FLAC__stream_decoder_input_bytes_unconsumed(decoder->guts->stream);
397 #ifdef _MSC_VER
398         /* with VC++ you have to spoon feed it the casting */
399         pos = l + (long)((double)(int64)target_sample / (double)(int64)decoder->guts->stream_info.total_samples * (double)(filesize-l+1)) - approx_bytes_per_frame;
400 #else
401         pos = l + (long)((double)target_sample / (double)decoder->guts->stream_info.total_samples * (double)(filesize-l+1)) - approx_bytes_per_frame;
402 #endif
403         r = filesize - ((decoder->guts->stream_info.channels * decoder->guts->stream_info.bits_per_sample * FLAC__MAX_BLOCK_SIZE) / 8 + 64);
404         if(pos >= r)
405                 pos = r-1;
406         if(pos < l)
407                 pos = l;
408         needs_seek = true;
409
410         decoder->guts->target_sample = target_sample;
411         while(1) {
412                 if(needs_seek) {
413                         if(-1 == fseek(decoder->guts->file, pos, SEEK_SET)) {
414                                 decoder->state = FLAC__FILE_DECODER_SEEK_ERROR;
415                                 return false;
416                         }
417                         if(!FLAC__stream_decoder_flush(decoder->guts->stream)) {
418                                 decoder->state = FLAC__FILE_DECODER_STREAM_ERROR;
419                                 return false;
420                         }
421                 }
422                 if(!FLAC__stream_decoder_process_one_frame(decoder->guts->stream)) {
423                         decoder->state = FLAC__FILE_DECODER_SEEK_ERROR;
424                         return false;
425                 }
426                 /* our write callback will change the state when it gets to the target frame */
427                 if(decoder->state != FLAC__FILE_DECODER_SEEKING) {
428                         break;
429                 }
430                 else { /* we need to narrow the search */
431                         uint64 this_frame_sample = decoder->guts->last_frame.header.number.sample_number;
432                         if(this_frame_sample == last_frame_sample) {
433                                 /* our last move backwards wasn't big enough */
434                                 pos -= (last_pos - pos);
435                                 needs_seek = true;
436                         }
437                         else {
438                                 if(target_sample < this_frame_sample) {
439                                         last_pos = pos;
440                                         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;
441                                         pos -= approx_bytes_per_frame;
442                                         needs_seek = true;
443                                 }
444                                 else {
445                                         last_pos = pos;
446                                         if(-1 == (pos = ftell(decoder->guts->file))) {
447                                                 decoder->state = FLAC__FILE_DECODER_SEEK_ERROR;
448                                                 return false;
449                                         }
450                                         pos -= FLAC__stream_decoder_input_bytes_unconsumed(decoder->guts->stream);
451                                         needs_seek = false;
452                                 }
453                         }
454                         if(pos < l)
455                                 pos = l;
456                         if(pos < 0)
457                                 pos = 0;
458                         last_frame_sample = this_frame_sample;
459                 }
460         }
461
462         return true;
463 }