add checking based on number_type in the frame header
[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 <stdio.h>
21 #include <stdlib.h> /* for malloc() */
22 #include <string.h> /* for strcmp() */
23 #include <sys/stat.h> /* for stat() */
24 #include "FLAC/assert.h"
25 #include "protected/file_decoder.h"
26 #include "protected/stream_decoder.h"
27 #include "private/md5.h"
28
29 /***********************************************************************
30  *
31  * Private class method prototypes
32  *
33  ***********************************************************************/
34
35 static FLAC__StreamDecoderReadStatus read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], unsigned *bytes, void *client_data);
36 static FLAC__StreamDecoderWriteStatus write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 *buffer[], void *client_data);
37 static void metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetaData *metadata, void *client_data);
38 static void error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
39 static FLAC__bool seek_to_absolute_sample_(FLAC__FileDecoder *decoder, long filesize, FLAC__uint64 target_sample);
40
41 /***********************************************************************
42  *
43  * Private class data
44  *
45  ***********************************************************************/
46
47 typedef struct FLAC__FileDecoderPrivate {
48         FLAC__StreamDecoderWriteStatus (*write_callback)(const FLAC__FileDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 *buffer[], void *client_data);
49         void (*metadata_callback)(const FLAC__FileDecoder *decoder, const FLAC__StreamMetaData *metadata, void *client_data);
50         void (*error_callback)(const FLAC__FileDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
51         void *client_data;
52         FILE *file;
53         char *filename; /* == NULL if stdin */
54         FLAC__StreamDecoder *stream_decoder;
55         struct MD5Context md5context;
56         FLAC__byte stored_md5sum[16]; /* this is what is stored in the metadata */
57         FLAC__byte computed_md5sum[16]; /* this is the sum we computed from the decoded data */
58         /* the rest of these are only used for seeking: */
59         FLAC__StreamMetaData_StreamInfo stream_info; /* we keep this around so we can figure out how to seek quickly */
60         const FLAC__StreamMetaData_SeekTable *seek_table; /* we hold a pointer to the stream decoder's seek table for the same reason */
61         FLAC__Frame last_frame; /* holds the info of the last frame we seeked to */
62         FLAC__uint64 target_sample;
63 } FLAC__FileDecoderPrivate;
64
65 /***********************************************************************
66  *
67  * Public static class data
68  *
69  ***********************************************************************/
70
71 const char *FLAC__FileDecoderStateString[] = {
72         "FLAC__FILE_DECODER_OK",
73         "FLAC__FILE_DECODER_SEEKING",
74         "FLAC__FILE_DECODER_END_OF_FILE",
75         "FLAC__FILE_DECODER_ERROR_OPENING_FILE",
76         "FLAC__FILE_DECODER_MEMORY_ALLOCATION_ERROR",
77         "FLAC__FILE_DECODER_SEEK_ERROR",
78         "FLAC__FILE_DECODER_STREAM_ERROR",
79         "FLAC__FILE_DECODER_STREAM_DECODER_ERROR",
80         "FLAC__FILE_DECODER_ALREADY_INITIALIZED",
81         "FLAC__FILE_DECODER_INVALID_CALLBACK",
82         "FLAC__FILE_DECODER_UNINITIALIZED"
83 };
84
85 /***********************************************************************
86  *
87  * Class constructor/destructor
88  *
89  ***********************************************************************/
90
91 FLAC__FileDecoder *FLAC__file_decoder_new()
92 {
93         FLAC__FileDecoder *decoder;
94
95         FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
96
97         decoder = (FLAC__FileDecoder*)malloc(sizeof(FLAC__FileDecoder));
98         if(decoder == 0) {
99                 return 0;
100         }
101         decoder->protected = (FLAC__FileDecoderProtected*)malloc(sizeof(FLAC__FileDecoderProtected));
102         if(decoder->protected == 0) {
103                 free(decoder);
104                 return 0;
105         }
106         decoder->private = (FLAC__FileDecoderPrivate*)malloc(sizeof(FLAC__FileDecoderPrivate));
107         if(decoder->private == 0) {
108                 free(decoder->protected);
109                 free(decoder);
110                 return 0;
111         }
112
113         decoder->protected->state = FLAC__FILE_DECODER_UNINITIALIZED;
114
115         decoder->private->filename = 0;
116         decoder->private->write_callback = 0;
117         decoder->private->metadata_callback = 0;
118         decoder->private->error_callback = 0;
119         decoder->private->client_data = 0;
120
121         return decoder;
122 }
123
124 void FLAC__file_decoder_delete(FLAC__FileDecoder *decoder)
125 {
126         FLAC__ASSERT(decoder != 0);
127         FLAC__ASSERT(decoder->protected != 0);
128         FLAC__ASSERT(decoder->private != 0);
129
130         free(decoder->private);
131         free(decoder->protected);
132         free(decoder);
133 }
134
135 /***********************************************************************
136  *
137  * Public class methods
138  *
139  ***********************************************************************/
140
141 FLAC__FileDecoderState FLAC__file_decoder_init(FLAC__FileDecoder *decoder)
142 {
143         FLAC__ASSERT(decoder != 0);
144
145         if(decoder->protected->state != FLAC__FILE_DECODER_UNINITIALIZED)
146                 return decoder->protected->state = FLAC__FILE_DECODER_ALREADY_INITIALIZED;
147
148         decoder->protected->state = FLAC__FILE_DECODER_OK;
149
150         if(0 == decoder->private->write_callback || 0 == decoder->private->metadata_callback || 0 == decoder->private->error_callback)
151                 return decoder->protected->state = FLAC__FILE_DECODER_INVALID_CALLBACK;
152
153         decoder->private->file = 0;
154         decoder->private->stream_decoder = 0;
155         decoder->private->seek_table = 0;
156
157         if(0 == strcmp(decoder->private->filename, "-"))
158                 decoder->private->file = stdin;
159         else
160                 decoder->private->file = fopen(decoder->private->filename, "rb");
161
162         if(decoder->private->file == 0)
163                 return decoder->protected->state = FLAC__FILE_DECODER_ERROR_OPENING_FILE;
164
165         /* We initialize the MD5Context even though we may never use it.  This is
166          * because md5_checking may be turned on to start and then turned off if a
167          * seek occurs.  So we always init the context here and finalize it in
168          * FLAC__file_decoder_finish() to make sure things are always cleaned up
169          * properly.
170          */
171         MD5Init(&decoder->private->md5context);
172
173         decoder->private->stream_decoder = FLAC__stream_decoder_new();
174
175         FLAC__stream_decoder_set_read_callback(decoder->private->stream_decoder, read_callback_);
176         FLAC__stream_decoder_set_write_callback(decoder->private->stream_decoder, write_callback_);
177         FLAC__stream_decoder_set_metadata_callback(decoder->private->stream_decoder, metadata_callback_);
178         FLAC__stream_decoder_set_error_callback(decoder->private->stream_decoder, error_callback_);
179         FLAC__stream_decoder_set_client_data(decoder->private->stream_decoder, decoder);
180
181         if(FLAC__stream_decoder_init(decoder->private->stream_decoder) != FLAC__STREAM_DECODER_SEARCH_FOR_METADATA)
182                 return decoder->protected->state = FLAC__FILE_DECODER_STREAM_DECODER_ERROR;
183
184         return decoder->protected->state;
185 }
186
187 FLAC__bool FLAC__file_decoder_finish(FLAC__FileDecoder *decoder)
188 {
189         FLAC__bool md5_failed = false;
190
191         FLAC__ASSERT(decoder != 0);
192         if(decoder->protected->state == FLAC__FILE_DECODER_UNINITIALIZED)
193                 return true;
194         if(decoder->private->file != 0 && decoder->private->file != stdin)
195                 fclose(decoder->private->file);
196         if(0 != decoder->private->filename)
197                 free(decoder->private->filename);
198         /* see the comment in FLAC__file_decoder_init() as to why we always
199          * call MD5Final()
200          */
201         MD5Final(decoder->private->computed_md5sum, &decoder->private->md5context);
202         if(decoder->private->stream_decoder != 0) {
203                 FLAC__stream_decoder_finish(decoder->private->stream_decoder);
204                 FLAC__stream_decoder_delete(decoder->private->stream_decoder);
205         }
206         if(decoder->protected->md5_checking) {
207                 if(memcmp(decoder->private->stored_md5sum, decoder->private->computed_md5sum, 16))
208                         md5_failed = true;
209         }
210         decoder->protected->state = FLAC__FILE_DECODER_UNINITIALIZED;
211         return !md5_failed;
212 }
213
214 FLAC__bool FLAC__file_decoder_set_md5_checking(const FLAC__FileDecoder *decoder, FLAC__bool value)
215 {
216         if(decoder->protected->state != FLAC__FILE_DECODER_UNINITIALIZED)
217                 return false;
218         decoder->protected->md5_checking = value;
219         return true;
220 }
221
222 FLAC__bool FLAC__file_decoder_set_filename(const FLAC__FileDecoder *decoder, const char *value)
223 {
224         if(decoder->protected->state != FLAC__FILE_DECODER_UNINITIALIZED)
225                 return false;
226         if(0 == (decoder->private->filename = (char*)malloc(strlen(value)+1))) {
227                 decoder->protected->state = FLAC__FILE_DECODER_MEMORY_ALLOCATION_ERROR;
228                 return false;
229         }
230         strcpy(decoder->private->filename, value);
231         return true;
232 }
233
234 FLAC__bool FLAC__file_decoder_set_write_callback(const FLAC__FileDecoder *decoder, FLAC__StreamDecoderWriteStatus (*value)(const FLAC__FileDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 *buffer[], void *client_data))
235 {
236         if(decoder->protected->state != FLAC__FILE_DECODER_UNINITIALIZED)
237                 return false;
238         decoder->private->write_callback = value;
239         return true;
240 }
241
242 FLAC__bool FLAC__file_decoder_set_metadata_callback(const FLAC__FileDecoder *decoder, void (*value)(const FLAC__FileDecoder *decoder, const FLAC__StreamMetaData *metadata, void *client_data))
243 {
244         if(decoder->protected->state != FLAC__FILE_DECODER_UNINITIALIZED)
245                 return false;
246         decoder->private->metadata_callback = value;
247         return true;
248 }
249
250 FLAC__bool FLAC__file_decoder_set_error_callback(const FLAC__FileDecoder *decoder, void (*value)(const FLAC__FileDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data))
251 {
252         if(decoder->protected->state != FLAC__FILE_DECODER_UNINITIALIZED)
253                 return false;
254         decoder->private->error_callback = value;
255         return true;
256 }
257
258 FLAC__bool FLAC__file_decoder_set_client_data(const FLAC__FileDecoder *decoder, void *value)
259 {
260         if(decoder->protected->state != FLAC__FILE_DECODER_UNINITIALIZED)
261                 return false;
262         decoder->private->client_data = value;
263         return true;
264 }
265
266 FLAC__FileDecoderState FLAC__file_decoder_get_state(const FLAC__FileDecoder *decoder)
267 {
268         return decoder->protected->state;
269 }
270
271 FLAC__bool FLAC__file_decoder_get_md5_checking(const FLAC__FileDecoder *decoder)
272 {
273         return decoder->protected->md5_checking;
274 }
275
276 FLAC__bool FLAC__file_decoder_process_whole_file(FLAC__FileDecoder *decoder)
277 {
278         FLAC__bool ret;
279         FLAC__ASSERT(decoder != 0);
280
281         if(decoder->private->stream_decoder->protected->state == FLAC__STREAM_DECODER_END_OF_STREAM)
282                 decoder->protected->state = FLAC__FILE_DECODER_END_OF_FILE;
283
284         if(decoder->protected->state == FLAC__FILE_DECODER_END_OF_FILE)
285                 return true;
286
287         FLAC__ASSERT(decoder->protected->state == FLAC__FILE_DECODER_OK);
288
289         ret = FLAC__stream_decoder_process_whole_stream(decoder->private->stream_decoder);
290         if(!ret)
291                 decoder->protected->state = FLAC__FILE_DECODER_STREAM_ERROR;
292
293         return ret;
294 }
295
296 FLAC__bool FLAC__file_decoder_process_metadata(FLAC__FileDecoder *decoder)
297 {
298         FLAC__bool ret;
299         FLAC__ASSERT(decoder != 0);
300
301         if(decoder->private->stream_decoder->protected->state == FLAC__STREAM_DECODER_END_OF_STREAM)
302                 decoder->protected->state = FLAC__FILE_DECODER_END_OF_FILE;
303
304         if(decoder->protected->state == FLAC__FILE_DECODER_END_OF_FILE)
305                 return true;
306
307         FLAC__ASSERT(decoder->protected->state == FLAC__FILE_DECODER_OK);
308
309         ret = FLAC__stream_decoder_process_metadata(decoder->private->stream_decoder);
310         if(!ret)
311                 decoder->protected->state = FLAC__FILE_DECODER_STREAM_ERROR;
312
313         return ret;
314 }
315
316 FLAC__bool FLAC__file_decoder_process_one_frame(FLAC__FileDecoder *decoder)
317 {
318         FLAC__bool ret;
319         FLAC__ASSERT(decoder != 0);
320
321         if(decoder->private->stream_decoder->protected->state == FLAC__STREAM_DECODER_END_OF_STREAM)
322                 decoder->protected->state = FLAC__FILE_DECODER_END_OF_FILE;
323
324         if(decoder->protected->state == FLAC__FILE_DECODER_END_OF_FILE)
325                 return true;
326
327         FLAC__ASSERT(decoder->protected->state == FLAC__FILE_DECODER_OK);
328
329         ret = FLAC__stream_decoder_process_one_frame(decoder->private->stream_decoder);
330         if(!ret)
331                 decoder->protected->state = FLAC__FILE_DECODER_STREAM_ERROR;
332
333         return ret;
334 }
335
336 FLAC__bool FLAC__file_decoder_process_remaining_frames(FLAC__FileDecoder *decoder)
337 {
338         FLAC__bool ret;
339         FLAC__ASSERT(decoder != 0);
340
341         if(decoder->private->stream_decoder->protected->state == FLAC__STREAM_DECODER_END_OF_STREAM)
342                 decoder->protected->state = FLAC__FILE_DECODER_END_OF_FILE;
343
344         if(decoder->protected->state == FLAC__FILE_DECODER_END_OF_FILE)
345                 return true;
346
347         FLAC__ASSERT(decoder->protected->state == FLAC__FILE_DECODER_OK);
348
349         ret = FLAC__stream_decoder_process_remaining_frames(decoder->private->stream_decoder);
350         if(!ret)
351                 decoder->protected->state = FLAC__FILE_DECODER_STREAM_ERROR;
352
353         return ret;
354 }
355
356 /***********************************************************************
357  *
358  * Private class methods
359  *
360  ***********************************************************************/
361
362 FLAC__bool FLAC__file_decoder_seek_absolute(FLAC__FileDecoder *decoder, FLAC__uint64 sample)
363 {
364         long filesize;
365         struct stat filestats;
366
367         FLAC__ASSERT(decoder != 0);
368         FLAC__ASSERT(decoder->protected->state == FLAC__FILE_DECODER_OK);
369
370         if(decoder->private->filename == 0) { /* means the file is stdin... */
371                 decoder->protected->state = FLAC__FILE_DECODER_SEEK_ERROR;
372                 return false;
373         }
374
375         decoder->protected->state = FLAC__FILE_DECODER_SEEKING;
376
377         /* turn off md5 checking if a seek is attempted */
378         decoder->protected->md5_checking = false;
379
380         if(!FLAC__stream_decoder_reset(decoder->private->stream_decoder)) {
381                 decoder->protected->state = FLAC__FILE_DECODER_STREAM_ERROR;
382                 return false;
383         }
384         /* get the file length */
385         if(stat(decoder->private->filename, &filestats) != 0) {
386                 decoder->protected->state = FLAC__FILE_DECODER_SEEK_ERROR;
387                 return false;
388         }
389         filesize = filestats.st_size;
390         /* rewind */
391         if(0 != fseek(decoder->private->file, 0, SEEK_SET)) {
392                 decoder->protected->state = FLAC__FILE_DECODER_SEEK_ERROR;
393                 return false;
394         }
395         if(!FLAC__stream_decoder_process_metadata(decoder->private->stream_decoder)) {
396                 decoder->protected->state = FLAC__FILE_DECODER_STREAM_ERROR;
397                 return false;
398         }
399         if(sample > decoder->private->stream_info.total_samples) {
400                 decoder->protected->state = FLAC__FILE_DECODER_SEEK_ERROR;
401                 return false;
402         }
403
404         return seek_to_absolute_sample_(decoder, filesize, sample);
405 }
406
407 FLAC__StreamDecoderReadStatus read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], unsigned *bytes, void *client_data)
408 {
409         FLAC__FileDecoder *file_decoder = (FLAC__FileDecoder *)client_data;
410         (void)decoder;
411         if(feof(file_decoder->private->file)) {
412                 file_decoder->protected->state = FLAC__FILE_DECODER_END_OF_FILE;
413                 return FLAC__STREAM_DECODER_READ_END_OF_STREAM;
414         }
415         else if(*bytes > 0) {
416                 size_t bytes_read = fread(buffer, sizeof(FLAC__byte), *bytes, file_decoder->private->file);
417                 if(bytes_read == 0) {
418                         if(feof(file_decoder->private->file)) {
419                                 file_decoder->protected->state = FLAC__FILE_DECODER_END_OF_FILE;
420                                 return FLAC__STREAM_DECODER_READ_END_OF_STREAM;
421                         }
422                         else
423                                 return FLAC__STREAM_DECODER_READ_ABORT;
424                 }
425                 else {
426                         *bytes = (unsigned)bytes_read;
427                         return FLAC__STREAM_DECODER_READ_CONTINUE;
428                 }
429         }
430         else
431                 return FLAC__STREAM_DECODER_READ_ABORT; /* abort to avoid a deadlock */
432 }
433
434 FLAC__StreamDecoderWriteStatus write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 *buffer[], void *client_data)
435 {
436         FLAC__FileDecoder *file_decoder = (FLAC__FileDecoder *)client_data;
437         (void)decoder;
438
439         if(file_decoder->protected->state == FLAC__FILE_DECODER_SEEKING) {
440                 FLAC__uint64 this_frame_sample = frame->header.number.sample_number;
441                 FLAC__uint64 next_frame_sample = this_frame_sample + (FLAC__uint64)frame->header.blocksize;
442                 FLAC__uint64 target_sample = file_decoder->private->target_sample;
443
444                 FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
445
446                 file_decoder->private->last_frame = *frame; /* save the frame in the private */
447                 if(this_frame_sample <= target_sample && target_sample < next_frame_sample) { /* we hit our target frame */
448                         unsigned delta = (unsigned)(target_sample - this_frame_sample);
449                         /* kick out of seek mode */
450                         file_decoder->protected->state = FLAC__FILE_DECODER_OK;
451                         /* shift out the samples before target_sample */
452                         if(delta > 0) {
453                                 unsigned channel;
454                                 const FLAC__int32 *newbuffer[FLAC__MAX_CHANNELS];
455                                 for(channel = 0; channel < frame->header.channels; channel++)
456                                         newbuffer[channel] = buffer[channel] + delta;
457                                 file_decoder->private->last_frame.header.blocksize -= delta;
458                                 file_decoder->private->last_frame.header.number.sample_number += (FLAC__uint64)delta;
459                                 /* write the relevant samples */
460                                 return file_decoder->private->write_callback(file_decoder, &file_decoder->private->last_frame, newbuffer, file_decoder->private->client_data);
461                         }
462                         else {
463                                 /* write the relevant samples */
464                                 return file_decoder->private->write_callback(file_decoder, frame, buffer, file_decoder->private->client_data);
465                         }
466                 }
467                 else {
468                         return FLAC__STREAM_DECODER_WRITE_CONTINUE;
469                 }
470         }
471         else {
472                 if(file_decoder->protected->md5_checking) {
473                         if(!FLAC__MD5Accumulate(&file_decoder->private->md5context, buffer, frame->header.channels, frame->header.blocksize, (frame->header.bits_per_sample+7) / 8))
474                                 return FLAC__STREAM_DECODER_WRITE_ABORT;
475                 }
476                 return file_decoder->private->write_callback(file_decoder, frame, buffer, file_decoder->private->client_data);
477         }
478 }
479
480 void metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetaData *metadata, void *client_data)
481 {
482         FLAC__FileDecoder *file_decoder = (FLAC__FileDecoder *)client_data;
483         (void)decoder;
484
485         if(metadata->type == FLAC__METADATA_TYPE_STREAMINFO) {
486                 file_decoder->private->stream_info = metadata->data.stream_info;
487                 /* save the MD5 signature for comparison later */
488                 memcpy(file_decoder->private->stored_md5sum, metadata->data.stream_info.md5sum, 16);
489                 if(0 == memcmp(file_decoder->private->stored_md5sum, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", 16))
490                         file_decoder->protected->md5_checking = false;
491         }
492         else if(metadata->type == FLAC__METADATA_TYPE_SEEKTABLE) {
493                 file_decoder->private->seek_table = &metadata->data.seek_table;
494         }
495
496         if(file_decoder->protected->state != FLAC__FILE_DECODER_SEEKING)
497                 file_decoder->private->metadata_callback(file_decoder, metadata, file_decoder->private->client_data);
498 }
499
500 void error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
501 {
502         FLAC__FileDecoder *file_decoder = (FLAC__FileDecoder *)client_data;
503         (void)decoder;
504
505         if(file_decoder->protected->state != FLAC__FILE_DECODER_SEEKING)
506                 file_decoder->private->error_callback(file_decoder, status, file_decoder->private->client_data);
507 }
508
509 FLAC__bool seek_to_absolute_sample_(FLAC__FileDecoder *decoder, long filesize, FLAC__uint64 target_sample)
510 {
511         /* @@@ we should really change long to off_t and start using lseek(); with fseek() we have the 2GB file limit. */
512         long first_frame_offset, lower_bound, upper_bound, pos = -1, last_pos = -1;
513         int i, lower_seek_point = -1, upper_seek_point = -1;
514         unsigned approx_bytes_per_frame;
515         FLAC__uint64 last_frame_sample = 0xffffffffffffffff;
516         FLAC__bool needs_seek;
517         const FLAC__bool is_variable_blocksize_stream = (decoder->private->stream_info.min_blocksize != decoder->private->stream_info.max_blocksize);
518
519         /* we are just guessing here, but we want to guess high, not low */
520         if(decoder->private->stream_info.max_framesize > 0) {
521                 approx_bytes_per_frame = decoder->private->stream_info.max_framesize;
522         }
523         else if(!is_variable_blocksize_stream) {
524                 /* note there are no () around 'decoder->private->stream_info.bits_per_sample/8' to keep precision up since it's an integer calulation */
525                 approx_bytes_per_frame = decoder->private->stream_info.min_blocksize * decoder->private->stream_info.channels * decoder->private->stream_info.bits_per_sample/8 + 64;
526         }
527         else
528                 approx_bytes_per_frame = 1152 * decoder->private->stream_info.channels * decoder->private->stream_info.bits_per_sample/8 + 64;
529
530         /*
531          * The file pointer is currently at the first frame plus any read
532          * ahead data, so first we get the file pointer, then subtract
533          * uncomsumed bytes to get the position of the first frame in the
534          * file.
535          */
536         if(-1 == (first_frame_offset = ftell(decoder->private->file))) {
537                 decoder->protected->state = FLAC__FILE_DECODER_SEEK_ERROR;
538                 return false;
539         }
540         first_frame_offset -= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder->private->stream_decoder);
541         FLAC__ASSERT(first_frame_offset >= 0);
542
543         /*
544          * First, we set an upper and lower bound on where in the
545          * file we will search.  For now we assume the worst case
546          * scenario, which is our best guess at the beginning of
547          * the first and last frames.
548          */
549         lower_bound = first_frame_offset;
550
551         /* calc the upper_bound, beyond which we never want to seek */
552         if(decoder->private->stream_info.max_framesize > 0)
553                 upper_bound = filesize - (decoder->private->stream_info.max_framesize + 128 + 2); /* 128 for a possible ID3V1 tag, 2 for indexing differences */
554         else
555                 upper_bound = filesize - ((decoder->private->stream_info.channels * decoder->private->stream_info.bits_per_sample * FLAC__MAX_BLOCK_SIZE) / 8 + 128 + 2);
556
557         /*
558          * Now we refine the bounds if we have a seektable with
559          * suitable points.  Note that according to the spec they
560          * must be ordered by ascending sample number.
561          */
562         if(0 != decoder->private->seek_table) {
563                 /* find the closest seek point <= target_sample, if it exists */
564                 for(i = (int)decoder->private->seek_table->num_points - 1; i >= 0; i--) {
565                         if(decoder->private->seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER && decoder->private->seek_table->points[i].sample_number <= target_sample)
566                                 break;
567                 }
568                 if(i >= 0) { /* i.e. we found a suitable seek point... */
569                         lower_bound = first_frame_offset + (long)decoder->private->seek_table->points[i].stream_offset;
570                         lower_seek_point = i;
571                 }
572
573                 /* find the closest seek point > target_sample, if it exists */
574                 for(i = 0; i < (int)decoder->private->seek_table->num_points; i++) {
575                         if(decoder->private->seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER && decoder->private->seek_table->points[i].sample_number > target_sample)
576                                 break;
577                 }
578                 if(i < (int)decoder->private->seek_table->num_points) { /* i.e. we found a suitable seek point... */
579                         upper_bound = first_frame_offset + (long)decoder->private->seek_table->points[i].stream_offset;
580                         upper_seek_point = i;
581                 }
582         }
583
584         /*
585          * Now guess at where within those bounds our target
586          * sample will be.
587          */
588         if(lower_seek_point >= 0) {
589                 /* first see if our sample is within a few frames of the lower seekpoint */
590                 if(decoder->private->seek_table->points[lower_seek_point].sample_number <= target_sample && target_sample < decoder->private->seek_table->points[lower_seek_point].sample_number + (decoder->private->seek_table->points[lower_seek_point].frame_samples * 4)) {
591                         pos = lower_bound;
592                 }
593                 else if(upper_seek_point >= 0) {
594                         const FLAC__uint64 target_offset = target_sample - decoder->private->seek_table->points[lower_seek_point].sample_number;
595                         const FLAC__uint64 range_samples = decoder->private->seek_table->points[upper_seek_point].sample_number - decoder->private->seek_table->points[lower_seek_point].sample_number;
596                         const long range_bytes = upper_bound - lower_bound;
597 #ifdef _MSC_VER
598                         /* with VC++ you have to spoon feed it the casting */
599                         pos = lower_bound + (long)((double)(FLAC__int64)target_offset / (double)(FLAC__int64)range_samples * (double)(range_bytes-1)) - approx_bytes_per_frame;
600 #else
601                         pos = lower_bound + (long)((double)target_offset / (double)range_samples * (double)(range_bytes-1)) - approx_bytes_per_frame;
602 #endif
603                 }
604         }
605         if(pos < 0) {
606                 /* We need to use the metadata and the filelength to estimate the position of the frame with the correct sample */
607 #ifdef _MSC_VER
608                 /* with VC++ you have to spoon feed it the casting */
609                 pos = first_frame_offset + (long)((double)(FLAC__int64)target_sample / (double)(FLAC__int64)decoder->private->stream_info.total_samples * (double)(filesize-first_frame_offset-1)) - approx_bytes_per_frame;
610 #else
611                 pos = first_frame_offset + (long)((double)target_sample / (double)decoder->private->stream_info.total_samples * (double)(filesize-first_frame_offset-1)) - approx_bytes_per_frame;
612 #endif
613         }
614
615         /* clip the position to the bounds, lower bound takes precedence */
616         if(pos >= upper_bound)
617                 pos = upper_bound-1;
618         if(pos < lower_bound)
619                 pos = lower_bound;
620         needs_seek = true;
621
622         decoder->private->target_sample = target_sample;
623         while(1) {
624                 if(needs_seek) {
625                         if(-1 == fseek(decoder->private->file, pos, SEEK_SET)) {
626                                 decoder->protected->state = FLAC__FILE_DECODER_SEEK_ERROR;
627                                 return false;
628                         }
629                         if(!FLAC__stream_decoder_flush(decoder->private->stream_decoder)) {
630                                 decoder->protected->state = FLAC__FILE_DECODER_STREAM_ERROR;
631                                 return false;
632                         }
633                 }
634                 if(!FLAC__stream_decoder_process_one_frame(decoder->private->stream_decoder)) {
635                         decoder->protected->state = FLAC__FILE_DECODER_SEEK_ERROR;
636                         return false;
637                 }
638                 /* our write callback will change the state when it gets to the target frame */
639                 if(decoder->protected->state != FLAC__FILE_DECODER_SEEKING) {
640                         break;
641                 }
642                 else { /* we need to narrow the search */
643                         FLAC__uint64 this_frame_sample = decoder->private->last_frame.header.number.sample_number;
644                         FLAC__ASSERT(decoder->private->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
645                         if(this_frame_sample == last_frame_sample) {
646                                 /* our last move backwards wasn't big enough */
647                                 pos -= (last_pos - pos);
648                                 needs_seek = true;
649                         }
650                         else {
651                                 if(target_sample < this_frame_sample) {
652                                         last_pos = pos;
653                                         approx_bytes_per_frame = decoder->private->last_frame.header.blocksize * decoder->private->last_frame.header.channels * decoder->private->last_frame.header.bits_per_sample/8 + 64;
654                                         pos -= approx_bytes_per_frame;
655                                         needs_seek = true;
656                                 }
657                                 else { /* target_sample >= this_frame_sample + this frame's blocksize */
658                                         last_pos = pos;
659                                         if(-1 == (pos = ftell(decoder->private->file))) {
660                                                 decoder->protected->state = FLAC__FILE_DECODER_SEEK_ERROR;
661                                                 return false;
662                                         }
663                                         pos -= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder->private->stream_decoder);
664                                         needs_seek = false;
665                                 }
666                         }
667                         if(pos < lower_bound)
668                                 pos = lower_bound;
669                         last_frame_sample = this_frame_sample;
670                 }
671         }
672
673         return true;
674 }