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