be more precise in long long int literal specification for ANSI compilers (gcc3 requi...
[flac.git] / src / libFLAC / seekable_stream_decoder.c
1 /* libFLAC - Free Lossless Audio Codec library
2  * Copyright (C) 2000,2001,2002,2003,2004  Josh Coalson
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * - Redistributions of source code must retain the above copyright
9  * notice, this list of conditions and the following disclaimer.
10  *
11  * - Redistributions in binary form must reproduce the above copyright
12  * notice, this list of conditions and the following disclaimer in the
13  * documentation and/or other materials provided with the distribution.
14  *
15  * - Neither the name of the Xiph.org Foundation nor the names of its
16  * contributors may be used to endorse or promote products derived from
17  * this software without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22  * A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR
23  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
26  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
27  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30  */
31
32 #include <stdio.h>
33 #include <stdlib.h> /* for calloc() */
34 #include <string.h> /* for memcpy()/memcmp() */
35 #include "FLAC/assert.h"
36 #include "protected/seekable_stream_decoder.h"
37 #include "protected/stream_decoder.h"
38 #include "private/md5.h"
39
40 /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
41 #ifdef _MSC_VER
42 #define FLAC__U64L(x) x
43 #else
44 #define FLAC__U64L(x) x##LLU
45 #endif
46
47 /***********************************************************************
48  *
49  * Private class method prototypes
50  *
51  ***********************************************************************/
52
53 static void set_defaults_(FLAC__SeekableStreamDecoder *decoder);
54 static FLAC__StreamDecoderReadStatus read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], unsigned *bytes, void *client_data);
55 static FLAC__StreamDecoderWriteStatus write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
56 static void metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
57 static void error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
58 static FLAC__bool seek_to_absolute_sample_(FLAC__SeekableStreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
59
60 /***********************************************************************
61  *
62  * Private class data
63  *
64  ***********************************************************************/
65
66 typedef struct FLAC__SeekableStreamDecoderPrivate {
67         FLAC__SeekableStreamDecoderReadCallback read_callback;
68         FLAC__SeekableStreamDecoderSeekCallback seek_callback;
69         FLAC__SeekableStreamDecoderTellCallback tell_callback;
70         FLAC__SeekableStreamDecoderLengthCallback length_callback;
71         FLAC__SeekableStreamDecoderEofCallback eof_callback;
72         FLAC__SeekableStreamDecoderWriteCallback write_callback;
73         FLAC__SeekableStreamDecoderMetadataCallback metadata_callback;
74         FLAC__SeekableStreamDecoderErrorCallback error_callback;
75         void *client_data;
76         FLAC__StreamDecoder *stream_decoder;
77         FLAC__bool do_md5_checking; /* initially gets protected_->md5_checking but is turned off after a seek */
78         struct FLAC__MD5Context md5context;
79         FLAC__byte stored_md5sum[16]; /* this is what is stored in the metadata */
80         FLAC__byte computed_md5sum[16]; /* this is the sum we computed from the decoded data */
81         /* the rest of these are only used for seeking: */
82         FLAC__StreamMetadata_StreamInfo stream_info; /* we keep this around so we can figure out how to seek quickly */
83         const FLAC__StreamMetadata_SeekTable *seek_table; /* we hold a pointer to the stream decoder's seek table for the same reason */
84         /* Since we always want to see the STREAMINFO and SEEK_TABLE blocks at this level, we need some extra flags to keep track of whether they should be passed on up through the metadata_callback */
85         FLAC__bool ignore_stream_info_block;
86         FLAC__bool ignore_seek_table_block;
87         FLAC__Frame last_frame; /* holds the info of the last frame we seeked to */
88         FLAC__uint64 target_sample;
89 } FLAC__SeekableStreamDecoderPrivate;
90
91 /***********************************************************************
92  *
93  * Public static class data
94  *
95  ***********************************************************************/
96
97 FLAC_API const char * const FLAC__SeekableStreamDecoderStateString[] = {
98         "FLAC__SEEKABLE_STREAM_DECODER_OK",
99         "FLAC__SEEKABLE_STREAM_DECODER_SEEKING",
100         "FLAC__SEEKABLE_STREAM_DECODER_END_OF_STREAM",
101         "FLAC__SEEKABLE_STREAM_DECODER_MEMORY_ALLOCATION_ERROR",
102         "FLAC__SEEKABLE_STREAM_DECODER_STREAM_DECODER_ERROR",
103         "FLAC__SEEKABLE_STREAM_DECODER_READ_ERROR",
104         "FLAC__SEEKABLE_STREAM_DECODER_SEEK_ERROR",
105         "FLAC__SEEKABLE_STREAM_DECODER_ALREADY_INITIALIZED",
106         "FLAC__SEEKABLE_STREAM_DECODER_INVALID_CALLBACK",
107         "FLAC__SEEKABLE_STREAM_DECODER_UNINITIALIZED"
108 };
109
110 FLAC_API const char * const FLAC__SeekableStreamDecoderReadStatusString[] = {
111         "FLAC__SEEKABLE_STREAM_DECODER_READ_STATUS_OK",
112         "FLAC__SEEKABLE_STREAM_DECODER_READ_STATUS_ERROR"
113 };
114
115 FLAC_API const char * const FLAC__SeekableStreamDecoderSeekStatusString[] = {
116         "FLAC__SEEKABLE_STREAM_DECODER_SEEK_STATUS_OK",
117         "FLAC__SEEKABLE_STREAM_DECODER_SEEK_STATUS_ERROR"
118 };
119
120 FLAC_API const char * const FLAC__SeekableStreamDecoderTellStatusString[] = {
121         "FLAC__SEEKABLE_STREAM_DECODER_TELL_STATUS_OK",
122         "FLAC__SEEKABLE_STREAM_DECODER_TELL_STATUS_ERROR"
123 };
124
125 FLAC_API const char * const FLAC__SeekableStreamDecoderLengthStatusString[] = {
126         "FLAC__SEEKABLE_STREAM_DECODER_LENGTH_STATUS_OK",
127         "FLAC__SEEKABLE_STREAM_DECODER_LENGTH_STATUS_ERROR"
128 };
129
130
131 /***********************************************************************
132  *
133  * Class constructor/destructor
134  *
135  ***********************************************************************/
136
137 FLAC_API FLAC__SeekableStreamDecoder *FLAC__seekable_stream_decoder_new()
138 {
139         FLAC__SeekableStreamDecoder *decoder;
140
141         FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
142
143         decoder = (FLAC__SeekableStreamDecoder*)calloc(1, sizeof(FLAC__SeekableStreamDecoder));
144         if(decoder == 0) {
145                 return 0;
146         }
147
148         decoder->protected_ = (FLAC__SeekableStreamDecoderProtected*)calloc(1, sizeof(FLAC__SeekableStreamDecoderProtected));
149         if(decoder->protected_ == 0) {
150                 free(decoder);
151                 return 0;
152         }
153
154         decoder->private_ = (FLAC__SeekableStreamDecoderPrivate*)calloc(1, sizeof(FLAC__SeekableStreamDecoderPrivate));
155         if(decoder->private_ == 0) {
156                 free(decoder->protected_);
157                 free(decoder);
158                 return 0;
159         }
160
161         decoder->private_->stream_decoder = FLAC__stream_decoder_new();
162         if(0 == decoder->private_->stream_decoder) {
163                 free(decoder->private_);
164                 free(decoder->protected_);
165                 free(decoder);
166                 return 0;
167         }
168
169         set_defaults_(decoder);
170
171         decoder->protected_->state = FLAC__SEEKABLE_STREAM_DECODER_UNINITIALIZED;
172
173         return decoder;
174 }
175
176 FLAC_API void FLAC__seekable_stream_decoder_delete(FLAC__SeekableStreamDecoder *decoder)
177 {
178         FLAC__ASSERT(0 != decoder);
179         FLAC__ASSERT(0 != decoder->protected_);
180         FLAC__ASSERT(0 != decoder->private_);
181         FLAC__ASSERT(0 != decoder->private_->stream_decoder);
182
183         (void)FLAC__seekable_stream_decoder_finish(decoder);
184
185         FLAC__stream_decoder_delete(decoder->private_->stream_decoder);
186
187         free(decoder->private_);
188         free(decoder->protected_);
189         free(decoder);
190 }
191
192 /***********************************************************************
193  *
194  * Public class methods
195  *
196  ***********************************************************************/
197
198 FLAC_API FLAC__SeekableStreamDecoderState FLAC__seekable_stream_decoder_init(FLAC__SeekableStreamDecoder *decoder)
199 {
200         FLAC__ASSERT(0 != decoder);
201
202         if(decoder->protected_->state != FLAC__SEEKABLE_STREAM_DECODER_UNINITIALIZED)
203                 return decoder->protected_->state = FLAC__SEEKABLE_STREAM_DECODER_ALREADY_INITIALIZED;
204
205         if(0 == decoder->private_->read_callback || 0 == decoder->private_->seek_callback || 0 == decoder->private_->tell_callback || 0 == decoder->private_->length_callback || 0 == decoder->private_->eof_callback)
206                 return decoder->protected_->state = FLAC__SEEKABLE_STREAM_DECODER_INVALID_CALLBACK;
207
208         if(0 == decoder->private_->write_callback || 0 == decoder->private_->metadata_callback || 0 == decoder->private_->error_callback)
209                 return decoder->protected_->state = FLAC__SEEKABLE_STREAM_DECODER_INVALID_CALLBACK;
210
211         decoder->private_->seek_table = 0;
212
213         decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
214
215         /* We initialize the FLAC__MD5Context even though we may never use it.  This
216          * is because md5 checking may be turned on to start and then turned off if
217          * a seek occurs.  So we always init the context here and finalize it in
218          * FLAC__seekable_stream_decoder_finish() to make sure things are always
219          * cleaned up properly.
220          */
221         FLAC__MD5Init(&decoder->private_->md5context);
222
223         FLAC__stream_decoder_set_read_callback(decoder->private_->stream_decoder, read_callback_);
224         FLAC__stream_decoder_set_write_callback(decoder->private_->stream_decoder, write_callback_);
225         FLAC__stream_decoder_set_metadata_callback(decoder->private_->stream_decoder, metadata_callback_);
226         FLAC__stream_decoder_set_error_callback(decoder->private_->stream_decoder, error_callback_);
227         FLAC__stream_decoder_set_client_data(decoder->private_->stream_decoder, decoder);
228
229         /* We always want to see these blocks.  Whether or not we pass them up
230          * through the metadata callback will be determined by flags set in our
231          * implementation of ..._set_metadata_respond/ignore...()
232          */
233         FLAC__stream_decoder_set_metadata_respond(decoder->private_->stream_decoder, FLAC__METADATA_TYPE_STREAMINFO);
234         FLAC__stream_decoder_set_metadata_respond(decoder->private_->stream_decoder, FLAC__METADATA_TYPE_SEEKTABLE);
235
236         if(FLAC__stream_decoder_init(decoder->private_->stream_decoder) != FLAC__STREAM_DECODER_SEARCH_FOR_METADATA)
237                 return decoder->protected_->state = FLAC__SEEKABLE_STREAM_DECODER_STREAM_DECODER_ERROR;
238
239         return decoder->protected_->state = FLAC__SEEKABLE_STREAM_DECODER_OK;
240 }
241
242 FLAC_API FLAC__bool FLAC__seekable_stream_decoder_finish(FLAC__SeekableStreamDecoder *decoder)
243 {
244         FLAC__bool md5_failed = false;
245
246         FLAC__ASSERT(0 != decoder);
247         FLAC__ASSERT(0 != decoder->private_);
248         FLAC__ASSERT(0 != decoder->protected_);
249
250         if(decoder->protected_->state == FLAC__SEEKABLE_STREAM_DECODER_UNINITIALIZED)
251                 return true;
252
253         FLAC__ASSERT(0 != decoder->private_->stream_decoder);
254
255         /* see the comment in FLAC__seekable_stream_decoder_init() as to why we
256          * always call FLAC__MD5Final()
257          */
258         FLAC__MD5Final(decoder->private_->computed_md5sum, &decoder->private_->md5context);
259
260         FLAC__stream_decoder_finish(decoder->private_->stream_decoder);
261
262         if(decoder->private_->do_md5_checking) {
263                 if(memcmp(decoder->private_->stored_md5sum, decoder->private_->computed_md5sum, 16))
264                         md5_failed = true;
265         }
266
267         set_defaults_(decoder);
268
269         decoder->protected_->state = FLAC__SEEKABLE_STREAM_DECODER_UNINITIALIZED;
270
271         return !md5_failed;
272 }
273
274 FLAC_API FLAC__bool FLAC__seekable_stream_decoder_set_md5_checking(FLAC__SeekableStreamDecoder *decoder, FLAC__bool value)
275 {
276         FLAC__ASSERT(0 != decoder);
277         FLAC__ASSERT(0 != decoder->protected_);
278         if(decoder->protected_->state != FLAC__SEEKABLE_STREAM_DECODER_UNINITIALIZED)
279                 return false;
280         decoder->protected_->md5_checking = value;
281         return true;
282 }
283
284 FLAC_API FLAC__bool FLAC__seekable_stream_decoder_set_read_callback(FLAC__SeekableStreamDecoder *decoder, FLAC__SeekableStreamDecoderReadCallback value)
285 {
286         FLAC__ASSERT(0 != decoder);
287         FLAC__ASSERT(0 != decoder->private_);
288         FLAC__ASSERT(0 != decoder->protected_);
289         if(decoder->protected_->state != FLAC__SEEKABLE_STREAM_DECODER_UNINITIALIZED)
290                 return false;
291         decoder->private_->read_callback = value;
292         return true;
293 }
294
295 FLAC_API FLAC__bool FLAC__seekable_stream_decoder_set_seek_callback(FLAC__SeekableStreamDecoder *decoder, FLAC__SeekableStreamDecoderSeekCallback value)
296 {
297         FLAC__ASSERT(0 != decoder);
298         FLAC__ASSERT(0 != decoder->private_);
299         FLAC__ASSERT(0 != decoder->protected_);
300         if(decoder->protected_->state != FLAC__SEEKABLE_STREAM_DECODER_UNINITIALIZED)
301                 return false;
302         decoder->private_->seek_callback = value;
303         return true;
304 }
305
306 FLAC_API FLAC__bool FLAC__seekable_stream_decoder_set_tell_callback(FLAC__SeekableStreamDecoder *decoder, FLAC__SeekableStreamDecoderTellCallback value)
307 {
308         FLAC__ASSERT(0 != decoder);
309         FLAC__ASSERT(0 != decoder->private_);
310         FLAC__ASSERT(0 != decoder->protected_);
311         if(decoder->protected_->state != FLAC__SEEKABLE_STREAM_DECODER_UNINITIALIZED)
312                 return false;
313         decoder->private_->tell_callback = value;
314         return true;
315 }
316
317 FLAC_API FLAC__bool FLAC__seekable_stream_decoder_set_length_callback(FLAC__SeekableStreamDecoder *decoder, FLAC__SeekableStreamDecoderLengthCallback value)
318 {
319         FLAC__ASSERT(0 != decoder);
320         FLAC__ASSERT(0 != decoder->private_);
321         FLAC__ASSERT(0 != decoder->protected_);
322         if(decoder->protected_->state != FLAC__SEEKABLE_STREAM_DECODER_UNINITIALIZED)
323                 return false;
324         decoder->private_->length_callback = value;
325         return true;
326 }
327
328 FLAC_API FLAC__bool FLAC__seekable_stream_decoder_set_eof_callback(FLAC__SeekableStreamDecoder *decoder, FLAC__SeekableStreamDecoderEofCallback value)
329 {
330         FLAC__ASSERT(0 != decoder);
331         FLAC__ASSERT(0 != decoder->private_);
332         FLAC__ASSERT(0 != decoder->protected_);
333         if(decoder->protected_->state != FLAC__SEEKABLE_STREAM_DECODER_UNINITIALIZED)
334                 return false;
335         decoder->private_->eof_callback = value;
336         return true;
337 }
338
339 FLAC_API FLAC__bool FLAC__seekable_stream_decoder_set_write_callback(FLAC__SeekableStreamDecoder *decoder, FLAC__SeekableStreamDecoderWriteCallback value)
340 {
341         FLAC__ASSERT(0 != decoder);
342         FLAC__ASSERT(0 != decoder->private_);
343         FLAC__ASSERT(0 != decoder->protected_);
344         if(decoder->protected_->state != FLAC__SEEKABLE_STREAM_DECODER_UNINITIALIZED)
345                 return false;
346         decoder->private_->write_callback = value;
347         return true;
348 }
349
350 FLAC_API FLAC__bool FLAC__seekable_stream_decoder_set_metadata_callback(FLAC__SeekableStreamDecoder *decoder, FLAC__SeekableStreamDecoderMetadataCallback value)
351 {
352         FLAC__ASSERT(0 != decoder);
353         FLAC__ASSERT(0 != decoder->private_);
354         FLAC__ASSERT(0 != decoder->protected_);
355         if(decoder->protected_->state != FLAC__SEEKABLE_STREAM_DECODER_UNINITIALIZED)
356                 return false;
357         decoder->private_->metadata_callback = value;
358         return true;
359 }
360
361 FLAC_API FLAC__bool FLAC__seekable_stream_decoder_set_error_callback(FLAC__SeekableStreamDecoder *decoder, FLAC__SeekableStreamDecoderErrorCallback value)
362 {
363         FLAC__ASSERT(0 != decoder);
364         FLAC__ASSERT(0 != decoder->private_);
365         FLAC__ASSERT(0 != decoder->protected_);
366         if(decoder->protected_->state != FLAC__SEEKABLE_STREAM_DECODER_UNINITIALIZED)
367                 return false;
368         decoder->private_->error_callback = value;
369         return true;
370 }
371
372 FLAC_API FLAC__bool FLAC__seekable_stream_decoder_set_client_data(FLAC__SeekableStreamDecoder *decoder, void *value)
373 {
374         FLAC__ASSERT(0 != decoder);
375         FLAC__ASSERT(0 != decoder->private_);
376         FLAC__ASSERT(0 != decoder->protected_);
377         if(decoder->protected_->state != FLAC__SEEKABLE_STREAM_DECODER_UNINITIALIZED)
378                 return false;
379         decoder->private_->client_data = value;
380         return true;
381 }
382
383 FLAC_API FLAC__bool FLAC__seekable_stream_decoder_set_metadata_respond(FLAC__SeekableStreamDecoder *decoder, FLAC__MetadataType type)
384 {
385         FLAC__ASSERT(0 != decoder);
386         FLAC__ASSERT(0 != decoder->private_);
387         FLAC__ASSERT(0 != decoder->protected_);
388         FLAC__ASSERT(0 != decoder->private_->stream_decoder);
389         if(decoder->protected_->state != FLAC__SEEKABLE_STREAM_DECODER_UNINITIALIZED)
390                 return false;
391         if(type == FLAC__METADATA_TYPE_STREAMINFO)
392                 decoder->private_->ignore_stream_info_block = false;
393         else if(type == FLAC__METADATA_TYPE_SEEKTABLE)
394                 decoder->private_->ignore_seek_table_block = false;
395         return FLAC__stream_decoder_set_metadata_respond(decoder->private_->stream_decoder, type);
396 }
397
398 FLAC_API FLAC__bool FLAC__seekable_stream_decoder_set_metadata_respond_application(FLAC__SeekableStreamDecoder *decoder, const FLAC__byte id[4])
399 {
400         FLAC__ASSERT(0 != decoder);
401         FLAC__ASSERT(0 != decoder->private_);
402         FLAC__ASSERT(0 != decoder->protected_);
403         FLAC__ASSERT(0 != decoder->private_->stream_decoder);
404         if(decoder->protected_->state != FLAC__SEEKABLE_STREAM_DECODER_UNINITIALIZED)
405                 return false;
406         return FLAC__stream_decoder_set_metadata_respond_application(decoder->private_->stream_decoder, id);
407 }
408
409 FLAC_API FLAC__bool FLAC__seekable_stream_decoder_set_metadata_respond_all(FLAC__SeekableStreamDecoder *decoder)
410 {
411         FLAC__ASSERT(0 != decoder);
412         FLAC__ASSERT(0 != decoder->private_);
413         FLAC__ASSERT(0 != decoder->protected_);
414         FLAC__ASSERT(0 != decoder->private_->stream_decoder);
415         if(decoder->protected_->state != FLAC__SEEKABLE_STREAM_DECODER_UNINITIALIZED)
416                 return false;
417         decoder->private_->ignore_stream_info_block = false;
418         decoder->private_->ignore_seek_table_block = false;
419         return FLAC__stream_decoder_set_metadata_respond_all(decoder->private_->stream_decoder);
420 }
421
422 FLAC_API FLAC__bool FLAC__seekable_stream_decoder_set_metadata_ignore(FLAC__SeekableStreamDecoder *decoder, FLAC__MetadataType type)
423 {
424         FLAC__ASSERT(0 != decoder);
425         FLAC__ASSERT(0 != decoder->private_);
426         FLAC__ASSERT(0 != decoder->protected_);
427         FLAC__ASSERT(0 != decoder->private_->stream_decoder);
428         if(decoder->protected_->state != FLAC__SEEKABLE_STREAM_DECODER_UNINITIALIZED)
429                 return false;
430         if(type == FLAC__METADATA_TYPE_STREAMINFO) {
431                 decoder->private_->ignore_stream_info_block = true;
432                 return true;
433         }
434         else if(type == FLAC__METADATA_TYPE_SEEKTABLE) {
435                 decoder->private_->ignore_seek_table_block = true;
436                 return true;
437         }
438         else
439                 return FLAC__stream_decoder_set_metadata_ignore(decoder->private_->stream_decoder, type);
440 }
441
442 FLAC_API FLAC__bool FLAC__seekable_stream_decoder_set_metadata_ignore_application(FLAC__SeekableStreamDecoder *decoder, const FLAC__byte id[4])
443 {
444         FLAC__ASSERT(0 != decoder);
445         FLAC__ASSERT(0 != decoder->private_);
446         FLAC__ASSERT(0 != decoder->protected_);
447         FLAC__ASSERT(0 != decoder->private_->stream_decoder);
448         if(decoder->protected_->state != FLAC__SEEKABLE_STREAM_DECODER_UNINITIALIZED)
449                 return false;
450         return FLAC__stream_decoder_set_metadata_ignore_application(decoder->private_->stream_decoder, id);
451 }
452
453 FLAC_API FLAC__bool FLAC__seekable_stream_decoder_set_metadata_ignore_all(FLAC__SeekableStreamDecoder *decoder)
454 {
455         FLAC__ASSERT(0 != decoder);
456         FLAC__ASSERT(0 != decoder->private_);
457         FLAC__ASSERT(0 != decoder->protected_);
458         FLAC__ASSERT(0 != decoder->private_->stream_decoder);
459         if(decoder->protected_->state != FLAC__SEEKABLE_STREAM_DECODER_UNINITIALIZED)
460                 return false;
461         decoder->private_->ignore_stream_info_block = true;
462         decoder->private_->ignore_seek_table_block = true;
463         return
464                 FLAC__stream_decoder_set_metadata_ignore_all(decoder->private_->stream_decoder) &&
465                 FLAC__stream_decoder_set_metadata_respond(decoder->private_->stream_decoder, FLAC__METADATA_TYPE_STREAMINFO) &&
466                 FLAC__stream_decoder_set_metadata_respond(decoder->private_->stream_decoder, FLAC__METADATA_TYPE_SEEKTABLE);
467 }
468
469 FLAC_API FLAC__SeekableStreamDecoderState FLAC__seekable_stream_decoder_get_state(const FLAC__SeekableStreamDecoder *decoder)
470 {
471         FLAC__ASSERT(0 != decoder);
472         FLAC__ASSERT(0 != decoder->protected_);
473         return decoder->protected_->state;
474 }
475
476 FLAC_API FLAC__StreamDecoderState FLAC__seekable_stream_decoder_get_stream_decoder_state(const FLAC__SeekableStreamDecoder *decoder)
477 {
478         FLAC__ASSERT(0 != decoder);
479         FLAC__ASSERT(0 != decoder->private_);
480         return FLAC__stream_decoder_get_state(decoder->private_->stream_decoder);
481 }
482
483 FLAC_API const char *FLAC__seekable_stream_decoder_get_resolved_state_string(const FLAC__SeekableStreamDecoder *decoder)
484 {
485         if(decoder->protected_->state != FLAC__SEEKABLE_STREAM_DECODER_STREAM_DECODER_ERROR)
486                 return FLAC__SeekableStreamDecoderStateString[decoder->protected_->state];
487         else
488                 return FLAC__stream_decoder_get_resolved_state_string(decoder->private_->stream_decoder);
489 }
490
491 FLAC_API FLAC__bool FLAC__seekable_stream_decoder_get_md5_checking(const FLAC__SeekableStreamDecoder *decoder)
492 {
493         FLAC__ASSERT(0 != decoder);
494         FLAC__ASSERT(0 != decoder->protected_);
495         return decoder->protected_->md5_checking;
496 }
497
498 FLAC_API unsigned FLAC__seekable_stream_decoder_get_channels(const FLAC__SeekableStreamDecoder *decoder)
499 {
500         FLAC__ASSERT(0 != decoder);
501         FLAC__ASSERT(0 != decoder->private_);
502         return FLAC__stream_decoder_get_channels(decoder->private_->stream_decoder);
503 }
504
505 FLAC_API FLAC__ChannelAssignment FLAC__seekable_stream_decoder_get_channel_assignment(const FLAC__SeekableStreamDecoder *decoder)
506 {
507         FLAC__ASSERT(0 != decoder);
508         FLAC__ASSERT(0 != decoder->private_);
509         return FLAC__stream_decoder_get_channel_assignment(decoder->private_->stream_decoder);
510 }
511
512 FLAC_API unsigned FLAC__seekable_stream_decoder_get_bits_per_sample(const FLAC__SeekableStreamDecoder *decoder)
513 {
514         FLAC__ASSERT(0 != decoder);
515         FLAC__ASSERT(0 != decoder->private_);
516         return FLAC__stream_decoder_get_bits_per_sample(decoder->private_->stream_decoder);
517 }
518
519 FLAC_API unsigned FLAC__seekable_stream_decoder_get_sample_rate(const FLAC__SeekableStreamDecoder *decoder)
520 {
521         FLAC__ASSERT(0 != decoder);
522         FLAC__ASSERT(0 != decoder->private_);
523         return FLAC__stream_decoder_get_sample_rate(decoder->private_->stream_decoder);
524 }
525
526 FLAC_API unsigned FLAC__seekable_stream_decoder_get_blocksize(const FLAC__SeekableStreamDecoder *decoder)
527 {
528         FLAC__ASSERT(0 != decoder);
529         FLAC__ASSERT(0 != decoder->private_);
530         return FLAC__stream_decoder_get_blocksize(decoder->private_->stream_decoder);
531 }
532
533 FLAC_API FLAC__bool FLAC__seekable_stream_decoder_get_decode_position(const FLAC__SeekableStreamDecoder *decoder, FLAC__uint64 *position)
534 {
535         FLAC__ASSERT(0 != decoder);
536         FLAC__ASSERT(0 != decoder->private_);
537         FLAC__ASSERT(0 != position);
538
539         if(decoder->private_->tell_callback(decoder, position, decoder->private_->client_data) != FLAC__SEEKABLE_STREAM_DECODER_TELL_STATUS_OK)
540                 return false;
541         FLAC__ASSERT(*position >= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder->private_->stream_decoder));
542         *position -= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder->private_->stream_decoder);
543         return true;
544 }
545
546 FLAC_API FLAC__bool FLAC__seekable_stream_decoder_flush(FLAC__SeekableStreamDecoder *decoder)
547 {
548         FLAC__ASSERT(0 != decoder);
549         FLAC__ASSERT(0 != decoder->private_);
550         FLAC__ASSERT(0 != decoder->protected_);
551
552         decoder->private_->do_md5_checking = false;
553
554         if(!FLAC__stream_decoder_flush(decoder->private_->stream_decoder)) {
555                 decoder->protected_->state = FLAC__SEEKABLE_STREAM_DECODER_STREAM_DECODER_ERROR;
556                 return false;
557         }
558
559         decoder->protected_->state = FLAC__SEEKABLE_STREAM_DECODER_OK;
560
561         return true;
562 }
563
564 FLAC_API FLAC__bool FLAC__seekable_stream_decoder_reset(FLAC__SeekableStreamDecoder *decoder)
565 {
566         FLAC__ASSERT(0 != decoder);
567         FLAC__ASSERT(0 != decoder->private_);
568         FLAC__ASSERT(0 != decoder->protected_);
569
570         if(!FLAC__seekable_stream_decoder_flush(decoder)) {
571                 decoder->protected_->state = FLAC__SEEKABLE_STREAM_DECODER_STREAM_DECODER_ERROR;
572                 return false;
573         }
574
575         if(!FLAC__stream_decoder_reset(decoder->private_->stream_decoder)) {
576                 decoder->protected_->state = FLAC__SEEKABLE_STREAM_DECODER_STREAM_DECODER_ERROR;
577                 return false;
578         }
579
580         decoder->private_->seek_table = 0;
581
582         decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
583
584         /* We initialize the FLAC__MD5Context even though we may never use it.  This
585          * is because md5 checking may be turned on to start and then turned off if
586          * a seek occurs.  So we always init the context here and finalize it in
587          * FLAC__seekable_stream_decoder_finish() to make sure things are always
588          * cleaned up properly.
589          */
590         FLAC__MD5Init(&decoder->private_->md5context);
591
592         decoder->protected_->state = FLAC__SEEKABLE_STREAM_DECODER_OK;
593
594         return true;
595 }
596
597 FLAC_API FLAC__bool FLAC__seekable_stream_decoder_process_single(FLAC__SeekableStreamDecoder *decoder)
598 {
599         FLAC__bool ret;
600         FLAC__ASSERT(0 != decoder);
601
602         if(decoder->private_->stream_decoder->protected_->state == FLAC__STREAM_DECODER_END_OF_STREAM)
603                 decoder->protected_->state = FLAC__SEEKABLE_STREAM_DECODER_END_OF_STREAM;
604
605         if(decoder->protected_->state == FLAC__SEEKABLE_STREAM_DECODER_END_OF_STREAM)
606                 return true;
607
608         FLAC__ASSERT(decoder->protected_->state == FLAC__SEEKABLE_STREAM_DECODER_OK);
609
610         ret = FLAC__stream_decoder_process_single(decoder->private_->stream_decoder);
611         if(!ret)
612                 decoder->protected_->state = FLAC__SEEKABLE_STREAM_DECODER_STREAM_DECODER_ERROR;
613
614         return ret;
615 }
616
617 FLAC_API FLAC__bool FLAC__seekable_stream_decoder_process_until_end_of_metadata(FLAC__SeekableStreamDecoder *decoder)
618 {
619         FLAC__bool ret;
620         FLAC__ASSERT(0 != decoder);
621
622         if(decoder->private_->stream_decoder->protected_->state == FLAC__STREAM_DECODER_END_OF_STREAM)
623                 decoder->protected_->state = FLAC__SEEKABLE_STREAM_DECODER_END_OF_STREAM;
624
625         if(decoder->protected_->state == FLAC__SEEKABLE_STREAM_DECODER_END_OF_STREAM)
626                 return true;
627
628         FLAC__ASSERT(decoder->protected_->state == FLAC__SEEKABLE_STREAM_DECODER_OK);
629
630         ret = FLAC__stream_decoder_process_until_end_of_metadata(decoder->private_->stream_decoder);
631         if(!ret)
632                 decoder->protected_->state = FLAC__SEEKABLE_STREAM_DECODER_STREAM_DECODER_ERROR;
633
634         return ret;
635 }
636
637 FLAC_API FLAC__bool FLAC__seekable_stream_decoder_process_until_end_of_stream(FLAC__SeekableStreamDecoder *decoder)
638 {
639         FLAC__bool ret;
640         FLAC__ASSERT(0 != decoder);
641
642         if(decoder->private_->stream_decoder->protected_->state == FLAC__STREAM_DECODER_END_OF_STREAM)
643                 decoder->protected_->state = FLAC__SEEKABLE_STREAM_DECODER_END_OF_STREAM;
644
645         if(decoder->protected_->state == FLAC__SEEKABLE_STREAM_DECODER_END_OF_STREAM)
646                 return true;
647
648         FLAC__ASSERT(decoder->protected_->state == FLAC__SEEKABLE_STREAM_DECODER_OK);
649
650         ret = FLAC__stream_decoder_process_until_end_of_stream(decoder->private_->stream_decoder);
651         if(!ret)
652                 decoder->protected_->state = FLAC__SEEKABLE_STREAM_DECODER_STREAM_DECODER_ERROR;
653
654         return ret;
655 }
656
657 FLAC_API FLAC__bool FLAC__seekable_stream_decoder_skip_single_frame(FLAC__SeekableStreamDecoder *decoder)
658 {
659         FLAC__bool ret;
660         FLAC__ASSERT(0 != decoder);
661
662         if(decoder->private_->stream_decoder->protected_->state == FLAC__STREAM_DECODER_END_OF_STREAM)
663                 decoder->protected_->state = FLAC__SEEKABLE_STREAM_DECODER_END_OF_STREAM;
664
665         if(decoder->protected_->state == FLAC__SEEKABLE_STREAM_DECODER_END_OF_STREAM)
666                 return true;
667
668         FLAC__ASSERT(decoder->protected_->state == FLAC__SEEKABLE_STREAM_DECODER_OK);
669
670         ret = FLAC__stream_decoder_skip_single_frame(decoder->private_->stream_decoder);
671         if(!ret)
672                 decoder->protected_->state = FLAC__SEEKABLE_STREAM_DECODER_STREAM_DECODER_ERROR;
673
674         return ret;
675 }
676
677 FLAC_API FLAC__bool FLAC__seekable_stream_decoder_seek_absolute(FLAC__SeekableStreamDecoder *decoder, FLAC__uint64 sample)
678 {
679         FLAC__uint64 length;
680
681         FLAC__ASSERT(0 != decoder);
682         FLAC__ASSERT(decoder->protected_->state == FLAC__SEEKABLE_STREAM_DECODER_OK || decoder->protected_->state == FLAC__SEEKABLE_STREAM_DECODER_END_OF_STREAM);
683
684         decoder->protected_->state = FLAC__SEEKABLE_STREAM_DECODER_SEEKING;
685
686         /* turn off md5 checking if a seek is attempted */
687         decoder->private_->do_md5_checking = false;
688
689         if(!FLAC__stream_decoder_reset(decoder->private_->stream_decoder)) {
690                 decoder->protected_->state = FLAC__SEEKABLE_STREAM_DECODER_STREAM_DECODER_ERROR;
691                 return false;
692         }
693         /* get the file length */
694         if(decoder->private_->length_callback(decoder, &length, decoder->private_->client_data) != FLAC__SEEKABLE_STREAM_DECODER_LENGTH_STATUS_OK) {
695                 decoder->protected_->state = FLAC__SEEKABLE_STREAM_DECODER_SEEK_ERROR;
696                 return false;
697         }
698         /* rewind */
699         if(decoder->private_->seek_callback(decoder, 0, decoder->private_->client_data) != FLAC__SEEKABLE_STREAM_DECODER_SEEK_STATUS_OK) {
700                 decoder->protected_->state = FLAC__SEEKABLE_STREAM_DECODER_SEEK_ERROR;
701                 return false;
702         }
703         if(!FLAC__stream_decoder_process_until_end_of_metadata(decoder->private_->stream_decoder)) {
704                 decoder->protected_->state = FLAC__SEEKABLE_STREAM_DECODER_STREAM_DECODER_ERROR;
705                 return false;
706         }
707         if(decoder->private_->stream_info.total_samples > 0 && sample >= decoder->private_->stream_info.total_samples) {
708                 decoder->protected_->state = FLAC__SEEKABLE_STREAM_DECODER_SEEK_ERROR;
709                 return false;
710         }
711
712         return seek_to_absolute_sample_(decoder, length, sample);
713 }
714
715 /***********************************************************************
716  *
717  * Private class methods
718  *
719  ***********************************************************************/
720
721 void set_defaults_(FLAC__SeekableStreamDecoder *decoder)
722 {
723         decoder->private_->read_callback = 0;
724         decoder->private_->seek_callback = 0;
725         decoder->private_->tell_callback = 0;
726         decoder->private_->length_callback = 0;
727         decoder->private_->eof_callback = 0;
728         decoder->private_->write_callback = 0;
729         decoder->private_->metadata_callback = 0;
730         decoder->private_->error_callback = 0;
731         decoder->private_->client_data = 0;
732         /* WATCHOUT: these should match the default behavior of FLAC__StreamDecoder */
733         decoder->private_->ignore_stream_info_block = false;
734         decoder->private_->ignore_seek_table_block = true;
735
736         decoder->protected_->md5_checking = false;
737 }
738
739 FLAC__StreamDecoderReadStatus read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], unsigned *bytes, void *client_data)
740 {
741         FLAC__SeekableStreamDecoder *seekable_stream_decoder = (FLAC__SeekableStreamDecoder *)client_data;
742         (void)decoder;
743         if(seekable_stream_decoder->private_->eof_callback(seekable_stream_decoder, seekable_stream_decoder->private_->client_data)) {
744                 *bytes = 0;
745 #if 0
746 @@@@@@ verify that this is not needed
747                 seekable_stream_decoder->protected_->state = FLAC__SEEKABLE_STREAM_DECODER_END_OF_STREAM;
748 #endif
749                 return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
750         }
751         else if(*bytes > 0) {
752                 if(seekable_stream_decoder->private_->read_callback(seekable_stream_decoder, buffer, bytes, seekable_stream_decoder->private_->client_data) != FLAC__SEEKABLE_STREAM_DECODER_READ_STATUS_OK) {
753                         seekable_stream_decoder->protected_->state = FLAC__SEEKABLE_STREAM_DECODER_READ_ERROR;
754                         return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
755                 }
756                 if(*bytes == 0) {
757                         if(seekable_stream_decoder->private_->eof_callback(seekable_stream_decoder, seekable_stream_decoder->private_->client_data)) {
758 #if 0
759 @@@@@@ verify that this is not needed
760                                 seekable_stream_decoder->protected_->state = FLAC__SEEKABLE_STREAM_DECODER_END_OF_STREAM;
761 #endif
762                                 return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
763                         }
764                         else
765                                 return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
766                 }
767                 else {
768                         return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
769                 }
770         }
771         else
772                 return FLAC__STREAM_DECODER_READ_STATUS_ABORT; /* abort to avoid a deadlock */
773 }
774
775 FLAC__StreamDecoderWriteStatus write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
776 {
777         FLAC__SeekableStreamDecoder *seekable_stream_decoder = (FLAC__SeekableStreamDecoder *)client_data;
778         (void)decoder;
779
780         if(seekable_stream_decoder->protected_->state == FLAC__SEEKABLE_STREAM_DECODER_SEEKING) {
781                 FLAC__uint64 this_frame_sample = frame->header.number.sample_number;
782                 FLAC__uint64 next_frame_sample = this_frame_sample + (FLAC__uint64)frame->header.blocksize;
783                 FLAC__uint64 target_sample = seekable_stream_decoder->private_->target_sample;
784
785                 FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
786
787                 seekable_stream_decoder->private_->last_frame = *frame; /* save the frame */
788                 if(this_frame_sample <= target_sample && target_sample < next_frame_sample) { /* we hit our target frame */
789                         unsigned delta = (unsigned)(target_sample - this_frame_sample);
790                         /* kick out of seek mode */
791                         seekable_stream_decoder->protected_->state = FLAC__SEEKABLE_STREAM_DECODER_OK;
792                         /* shift out the samples before target_sample */
793                         if(delta > 0) {
794                                 unsigned channel;
795                                 const FLAC__int32 *newbuffer[FLAC__MAX_CHANNELS];
796                                 for(channel = 0; channel < frame->header.channels; channel++)
797                                         newbuffer[channel] = buffer[channel] + delta;
798                                 seekable_stream_decoder->private_->last_frame.header.blocksize -= delta;
799                                 seekable_stream_decoder->private_->last_frame.header.number.sample_number += (FLAC__uint64)delta;
800                                 /* write the relevant samples */
801                                 return seekable_stream_decoder->private_->write_callback(seekable_stream_decoder, &seekable_stream_decoder->private_->last_frame, newbuffer, seekable_stream_decoder->private_->client_data);
802                         }
803                         else {
804                                 /* write the relevant samples */
805                                 return seekable_stream_decoder->private_->write_callback(seekable_stream_decoder, frame, buffer, seekable_stream_decoder->private_->client_data);
806                         }
807                 }
808                 else {
809                         return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
810                 }
811         }
812         else {
813                 if(seekable_stream_decoder->private_->do_md5_checking) {
814                         if(!FLAC__MD5Accumulate(&seekable_stream_decoder->private_->md5context, buffer, frame->header.channels, frame->header.blocksize, (frame->header.bits_per_sample+7) / 8))
815                                 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
816                 }
817                 return seekable_stream_decoder->private_->write_callback(seekable_stream_decoder, frame, buffer, seekable_stream_decoder->private_->client_data);
818         }
819 }
820
821 void metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
822 {
823         FLAC__SeekableStreamDecoder *seekable_stream_decoder = (FLAC__SeekableStreamDecoder *)client_data;
824         (void)decoder;
825
826         if(metadata->type == FLAC__METADATA_TYPE_STREAMINFO) {
827                 seekable_stream_decoder->private_->stream_info = metadata->data.stream_info;
828                 /* save the MD5 signature for comparison later */
829                 memcpy(seekable_stream_decoder->private_->stored_md5sum, metadata->data.stream_info.md5sum, 16);
830                 if(0 == memcmp(seekable_stream_decoder->private_->stored_md5sum, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", 16))
831                         seekable_stream_decoder->private_->do_md5_checking = false;
832         }
833         else if(metadata->type == FLAC__METADATA_TYPE_SEEKTABLE) {
834                 seekable_stream_decoder->private_->seek_table = &metadata->data.seek_table;
835         }
836
837         if(seekable_stream_decoder->protected_->state != FLAC__SEEKABLE_STREAM_DECODER_SEEKING) {
838                 FLAC__bool ignore_block = false;
839                 if(metadata->type == FLAC__METADATA_TYPE_STREAMINFO && seekable_stream_decoder->private_->ignore_stream_info_block)
840                         ignore_block = true;
841                 else if(metadata->type == FLAC__METADATA_TYPE_SEEKTABLE && seekable_stream_decoder->private_->ignore_seek_table_block)
842                         ignore_block = true;
843                 if(!ignore_block)
844                         seekable_stream_decoder->private_->metadata_callback(seekable_stream_decoder, metadata, seekable_stream_decoder->private_->client_data);
845         }
846 }
847
848 void error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
849 {
850         FLAC__SeekableStreamDecoder *seekable_stream_decoder = (FLAC__SeekableStreamDecoder *)client_data;
851         (void)decoder;
852
853         if(seekable_stream_decoder->protected_->state != FLAC__SEEKABLE_STREAM_DECODER_SEEKING)
854                 seekable_stream_decoder->private_->error_callback(seekable_stream_decoder, status, seekable_stream_decoder->private_->client_data);
855 }
856
857 FLAC__bool seek_to_absolute_sample_(FLAC__SeekableStreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
858 {
859         FLAC__uint64 first_frame_offset, lower_bound, upper_bound;
860         FLAC__int64 pos = -1, last_pos = -1;
861         int i, lower_seek_point = -1, upper_seek_point = -1;
862         unsigned approx_bytes_per_frame;
863         FLAC__uint64 last_frame_sample = FLAC__U64L(0xffffffffffffffff);
864         FLAC__bool needs_seek;
865         const FLAC__uint64 total_samples = decoder->private_->stream_info.total_samples;
866         const unsigned min_blocksize = decoder->private_->stream_info.min_blocksize;
867         const unsigned max_blocksize = decoder->private_->stream_info.max_blocksize;
868         const unsigned max_framesize = decoder->private_->stream_info.max_framesize;
869         const unsigned channels = FLAC__seekable_stream_decoder_get_channels(decoder);
870         const unsigned bps = FLAC__seekable_stream_decoder_get_bits_per_sample(decoder);
871
872         /* we are just guessing here, but we want to guess high, not low */
873         if(max_framesize > 0) {
874                 approx_bytes_per_frame = max_framesize;
875         }
876         /*
877          * Check if it's a known fixed-blocksize stream.  Note that though
878          * the spec doesn't allow zeroes in the STREAMINFO block, we may
879          * never get a STREAMINFO block when decoding so the value of
880          * min_blocksize might be zero.
881          */
882         else if(min_blocksize == max_blocksize && min_blocksize > 0) {
883                 /* note there are no () around 'bps/8' to keep precision up since it's an integer calulation */
884                 approx_bytes_per_frame = min_blocksize * channels * bps/8 + 64;
885         }
886         else
887                 approx_bytes_per_frame = 4608 * channels * bps/8 + 64;
888
889         /*
890          * The decode position is currently at the first frame since we
891          * rewound and processed metadata.
892          */
893         if(!FLAC__seekable_stream_decoder_get_decode_position(decoder, &first_frame_offset)) {
894                 decoder->protected_->state = FLAC__SEEKABLE_STREAM_DECODER_SEEK_ERROR;
895                 return false;
896         }
897
898         /*
899          * First, we set an upper and lower bound on where in the
900          * stream we will search.  For now we assume the worst case
901          * scenario, which is our best guess at the beginning of
902          * the first and last frames.
903          */
904         lower_bound = first_frame_offset;
905
906         /* calc the upper_bound, beyond which we never want to seek */
907         if(max_framesize > 0)
908                 upper_bound = stream_length - (max_framesize + 128 + 2); /* 128 for a possible ID3V1 tag, 2 for indexing differences */
909         else
910                 upper_bound = stream_length - ((channels * bps * FLAC__MAX_BLOCK_SIZE) / 8 + 128 + 2);
911
912         /*
913          * Now we refine the bounds if we have a seektable with
914          * suitable points.  Note that according to the spec they
915          * must be ordered by ascending sample number.
916          */
917         if(0 != decoder->private_->seek_table) {
918                 /* find the closest seek point <= target_sample, if it exists */
919                 for(i = (int)decoder->private_->seek_table->num_points - 1; i >= 0; i--) {
920                         if(decoder->private_->seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER && decoder->private_->seek_table->points[i].sample_number <= target_sample)
921                                 break;
922                 }
923                 if(i >= 0) { /* i.e. we found a suitable seek point... */
924                         lower_bound = first_frame_offset + decoder->private_->seek_table->points[i].stream_offset;
925                         lower_seek_point = i;
926                 }
927
928                 /* find the closest seek point > target_sample, if it exists */
929                 for(i = 0; i < (int)decoder->private_->seek_table->num_points; i++) {
930                         if(decoder->private_->seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER && decoder->private_->seek_table->points[i].sample_number > target_sample)
931                                 break;
932                 }
933                 if(i < (int)decoder->private_->seek_table->num_points) { /* i.e. we found a suitable seek point... */
934                         upper_bound = first_frame_offset + decoder->private_->seek_table->points[i].stream_offset;
935                         upper_seek_point = i;
936                 }
937         }
938
939         /*
940          * Now guess at where within those bounds our target
941          * sample will be.
942          */
943         if(lower_seek_point >= 0) {
944                 /* first see if our sample is within a few frames of the lower seekpoint */
945                 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)) {
946                         pos = (FLAC__int64)lower_bound;
947                 }
948                 else if(upper_seek_point >= 0) {
949                         const FLAC__uint64 target_offset = target_sample - decoder->private_->seek_table->points[lower_seek_point].sample_number;
950                         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;
951                         const FLAC__uint64 range_bytes = upper_bound - lower_bound;
952 #if defined _MSC_VER || defined __MINGW32__
953                         /* with VC++ you have to spoon feed it the casting */
954                         pos = (FLAC__int64)lower_bound + (FLAC__int64)((double)(FLAC__int64)target_offset / (double)(FLAC__int64)range_samples * (double)(FLAC__int64)(range_bytes-1)) - approx_bytes_per_frame;
955 #else
956                         pos = (FLAC__int64)lower_bound + (FLAC__int64)((double)target_offset / (double)range_samples * (double)(range_bytes-1)) - approx_bytes_per_frame;
957 #endif
958                 }
959         }
960
961         /*
962          * If there's no seek table, we need to use the metadata (if we
963          * have it) and the filelength to estimate the position of the
964          * frame with the correct sample.
965          */
966         if(pos < 0 && total_samples > 0) {
967 #if defined _MSC_VER || defined __MINGW32__
968                 /* with VC++ you have to spoon feed it the casting */
969                 pos = (FLAC__int64)first_frame_offset + (FLAC__int64)((double)(FLAC__int64)target_sample / (double)(FLAC__int64)total_samples * (double)(FLAC__int64)(stream_length-first_frame_offset-1)) - approx_bytes_per_frame;
970 #else
971                 pos = (FLAC__int64)first_frame_offset + (FLAC__int64)((double)target_sample / (double)total_samples * (double)(stream_length-first_frame_offset-1)) - approx_bytes_per_frame;
972 #endif
973         }
974
975         /*
976          * If there's no seek table and total_samples is unknown, we
977          * don't even bother trying to figure out a target, we just use
978          * our current position.
979          */
980         if(pos < 0) {
981                 FLAC__uint64 upos;
982                 if(decoder->private_->tell_callback(decoder, &upos, decoder->private_->client_data) != FLAC__SEEKABLE_STREAM_DECODER_TELL_STATUS_OK) {
983                         decoder->protected_->state = FLAC__SEEKABLE_STREAM_DECODER_SEEK_ERROR;
984                         return false;
985                 }
986                 pos = (FLAC__int64)upos;
987                 needs_seek = false;
988         }
989         else
990                 needs_seek = true;
991
992         /* clip the position to the bounds, lower bound takes precedence */
993         if(pos >= (FLAC__int64)upper_bound) {
994                 pos = (FLAC__int64)upper_bound-1;
995                 needs_seek = true;
996         }
997         if(pos < (FLAC__int64)lower_bound) {
998                 pos = (FLAC__int64)lower_bound;
999                 needs_seek = true;
1000         }
1001
1002         decoder->private_->target_sample = target_sample;
1003         while(1) {
1004                 if(needs_seek) {
1005                         if(decoder->private_->seek_callback(decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__SEEKABLE_STREAM_DECODER_SEEK_STATUS_OK) {
1006                                 decoder->protected_->state = FLAC__SEEKABLE_STREAM_DECODER_SEEK_ERROR;
1007                                 return false;
1008                         }
1009                         if(!FLAC__stream_decoder_flush(decoder->private_->stream_decoder)) {
1010                                 decoder->protected_->state = FLAC__SEEKABLE_STREAM_DECODER_STREAM_DECODER_ERROR;
1011                                 return false;
1012                         }
1013                 }
1014                 /* Now we need to get a frame.  It is possible for our seek
1015                  * to land in the middle of audio data that looks exactly like
1016                  * a frame header from a future version of an encoder.  When
1017                  * that happens, FLAC__stream_decoder_process_single() will
1018                  * return false and the state will be
1019                  * FLAC__STREAM_DECODER_UNPARSEABLE_STREAM.  But there is a
1020                  * remote possibility that it is properly synced at such a
1021                  * "future-codec frame", so to make sure, we wait to see
1022                  * several "unparseable" errors in a row before bailing out.
1023                  */
1024                 {
1025                         unsigned unparseable_count;
1026                         FLAC__bool got_a_frame = false;
1027                         for (unparseable_count = 0; !got_a_frame && unparseable_count < 10; unparseable_count++) {
1028                                 if(FLAC__stream_decoder_process_single(decoder->private_->stream_decoder))
1029                                         got_a_frame = true;
1030                                 else if(decoder->private_->stream_decoder->protected_->state == FLAC__STREAM_DECODER_UNPARSEABLE_STREAM)
1031                                         /* try again.  we don't want to flush the decoder since that clears the bitbuffer */
1032                                         decoder->private_->stream_decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
1033                                 else /* it's a real error */
1034                                         break;
1035                         }
1036                         if (!got_a_frame) {
1037                                 decoder->protected_->state = FLAC__SEEKABLE_STREAM_DECODER_SEEK_ERROR;
1038                                 return false;
1039                         }
1040                 }
1041                 /* our write callback will change the state when it gets to the target frame */
1042                 if(decoder->protected_->state != FLAC__SEEKABLE_STREAM_DECODER_SEEKING) {
1043                         break;
1044                 }
1045                 else { /* we need to narrow the search */
1046                         const FLAC__uint64 this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
1047                         FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
1048                         if(this_frame_sample == last_frame_sample && pos < last_pos) {
1049                                 /* our last move backwards wasn't big enough, double it */
1050                                 pos -= (last_pos - pos);
1051                                 needs_seek = true;
1052                         }
1053                         else {
1054                                 if(target_sample < this_frame_sample) {
1055                                         last_pos = pos;
1056                                         approx_bytes_per_frame = decoder->private_->last_frame.header.blocksize * channels * bps/8 + 64;
1057                                         pos -= approx_bytes_per_frame;
1058                                         needs_seek = true;
1059                                 }
1060                                 else { /* target_sample >= this_frame_sample + this frame's blocksize */
1061                                         FLAC__uint64 upos;
1062                                         if(decoder->private_->tell_callback(decoder, &upos, decoder->private_->client_data) != FLAC__SEEKABLE_STREAM_DECODER_TELL_STATUS_OK) {
1063                                                 decoder->protected_->state = FLAC__SEEKABLE_STREAM_DECODER_SEEK_ERROR;
1064                                                 return false;
1065                                         }
1066                                         last_pos = pos;
1067                                         pos = (FLAC__int64)upos;
1068                                         pos -= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder->private_->stream_decoder);
1069                                         needs_seek = false;
1070                                         /*
1071                                          * if we haven't hit the target frame yet and our position hasn't changed,
1072                                          * it means we're at the end of the stream and the seek target does not exist.
1073                                          */
1074                                         if(last_pos == pos) {
1075                                                 decoder->protected_->state = FLAC__SEEKABLE_STREAM_DECODER_SEEK_ERROR;
1076                                                 return false;
1077                                         }
1078                                 }
1079                         }
1080                         if(pos < (FLAC__int64)lower_bound)
1081                                 pos = (FLAC__int64)lower_bound;
1082                         last_frame_sample = this_frame_sample;
1083                 }
1084         }
1085
1086         return true;
1087 }