1 /***************************************************************************
3 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
4 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
5 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
6 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
10 * Copyright (C) 2005 Dave Chapman
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation; either version 2
15 * of the License, or (at your option) any later version.
17 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
18 * KIND, either express or implied.
20 ****************************************************************************/
23 #include <codecs/libffmpegFLAC/decoder.h>
27 /* The output buffers containing the decoded samples (channels 0 and 1) */
28 static int32_t decoded0
[MAX_BLOCKSIZE
] IBSS_ATTR_FLAC_DECODED0
;
29 static int32_t decoded1
[MAX_BLOCKSIZE
] IBSS_ATTR
;
31 #define MAX_SUPPORTED_SEEKTABLE_SIZE 5000
33 /* Notes about seeking:
35 The full seek table consists of:
36 uint64_t sample (only 36 bits are used)
40 We also limit the sample and offset values to 32-bits - Rockbox doesn't
41 support files bigger than 2GB on FAT32 filesystems.
43 The reference FLAC encoder produces a seek table with points every
44 10 seconds, but this can be overridden by the user when encoding a file.
46 With the default settings, a typical 4 minute track will contain
49 Taking the extreme case of a Rockbox supported file to be a 2GB (compressed)
50 16-bit/44.1KHz mono stream with a likely uncompressed size of 4GB:
51 Total duration is: 48694 seconds (about 810 minutes - 13.5 hours)
52 Total number of seek points: 4869
54 Therefore we limit the number of seek points to 5000. This is a
55 very extreme case, and requires 5000*8=40000 bytes of storage.
57 If we come across a FLAC file with more than this number of seekpoints, we
58 just use the first 5000.
62 struct FLACseekpoints
{
68 static struct FLACseekpoints seekpoints
[MAX_SUPPORTED_SEEKTABLE_SIZE
];
69 static int nseekpoints
;
71 static int8_t *bit_buffer
;
72 static size_t buff_size
;
74 static bool flac_init(FLACContext
* fc
, int first_frame_offset
)
76 unsigned char buf
[255];
77 bool found_streaminfo
=false;
78 uint32_t seekpoint_hi
,seekpoint_lo
;
79 uint32_t offset_hi
,offset_lo
;
84 ci
->memset(fc
,0,sizeof(FLACContext
));
89 /* Skip any foreign tags at start of file */
90 ci
->seek_buffer(first_frame_offset
);
92 fc
->metadatalength
= first_frame_offset
;
94 if (ci
->read_filebuf(buf
, 4) < 4)
99 if (ci
->memcmp(buf
,"fLaC",4) != 0)
103 fc
->metadatalength
+= 4;
105 while (!endofmetadata
) {
106 if (ci
->read_filebuf(buf
, 4) < 4)
111 endofmetadata
=(buf
[0]&0x80);
112 blocklength
= (buf
[1] << 16) | (buf
[2] << 8) | buf
[3];
113 fc
->metadatalength
+=blocklength
+4;
115 if ((buf
[0] & 0x7f) == 0) /* 0 is the STREAMINFO block */
117 if (ci
->read_filebuf(buf
, blocklength
) < blocklength
) return false;
119 fc
->filesize
= ci
->filesize
;
120 fc
->min_blocksize
= (buf
[0] << 8) | buf
[1];
121 int max_blocksize
= (buf
[2] << 8) | buf
[3];
122 if (max_blocksize
> MAX_BLOCKSIZE
)
124 LOGF("FLAC: Maximum blocksize is too large\n");
127 fc
->max_blocksize
= max_blocksize
;
128 fc
->min_framesize
= (buf
[4] << 16) | (buf
[5] << 8) | buf
[6];
129 fc
->max_framesize
= (buf
[7] << 16) | (buf
[8] << 8) | buf
[9];
130 fc
->samplerate
= (buf
[10] << 12) | (buf
[11] << 4)
131 | ((buf
[12] & 0xf0) >> 4);
132 fc
->channels
= ((buf
[12]&0x0e)>>1) + 1;
133 fc
->bps
= (((buf
[12]&0x01) << 4) | ((buf
[13]&0xf0)>>4) ) + 1;
135 /* totalsamples is a 36-bit field, but we assume <= 32 bits are
137 fc
->totalsamples
= (buf
[14] << 24) | (buf
[15] << 16)
138 | (buf
[16] << 8) | buf
[17];
140 /* Calculate track length (in ms) and estimate the bitrate
142 fc
->length
= ((int64_t) fc
->totalsamples
* 1000) / fc
->samplerate
;
144 found_streaminfo
=true;
145 } else if ((buf
[0] & 0x7f) == 3) { /* 3 is the SEEKTABLE block */
146 while ((nseekpoints
< MAX_SUPPORTED_SEEKTABLE_SIZE
) &&
147 (blocklength
>= 18)) {
148 if (ci
->read_filebuf(buf
,18) < 18) return false;
151 seekpoint_hi
=(buf
[0] << 24) | (buf
[1] << 16) |
152 (buf
[2] << 8) | buf
[3];
153 seekpoint_lo
=(buf
[4] << 24) | (buf
[5] << 16) |
154 (buf
[6] << 8) | buf
[7];
155 offset_hi
=(buf
[8] << 24) | (buf
[9] << 16) |
156 (buf
[10] << 8) | buf
[11];
157 offset_lo
=(buf
[12] << 24) | (buf
[13] << 16) |
158 (buf
[14] << 8) | buf
[15];
160 blocksize
=(buf
[16] << 8) | buf
[17];
162 /* Only store seekpoints where the high 32 bits are zero */
163 if ((seekpoint_hi
== 0) && (seekpoint_lo
!= 0xffffffff) &&
165 seekpoints
[nseekpoints
].sample
=seekpoint_lo
;
166 seekpoints
[nseekpoints
].offset
=offset_lo
;
167 seekpoints
[nseekpoints
].blocksize
=blocksize
;
171 /* Skip any unread seekpoints */
173 ci
->advance_buffer(blocklength
);
175 /* Skip to next metadata block */
176 ci
->advance_buffer(blocklength
);
180 if (found_streaminfo
) {
181 fc
->bitrate
= ((int64_t) (fc
->filesize
-fc
->metadatalength
) * 8)
189 /* Synchronize to next frame in stream - adapted from libFLAC 1.1.3b2 */
190 static bool frame_sync(FLACContext
* fc
) {
194 /* Make sure we're byte aligned. */
195 align_get_bits(&fc
->gb
);
198 if(fc
->gb
.size_in_bits
- get_bits_count(&fc
->gb
) < 8) {
199 /* Error, end of bitstream, a valid stream should never reach here
200 * since the buffer should contain at least one frame header.
208 x
= get_bits(&fc
->gb
, 8);
210 if(x
== 0xff) { /* MAGIC NUMBER for first 8 frame sync bits. */
211 x
= get_bits(&fc
->gb
, 8);
212 /* We have to check if we just read two 0xff's in a row; the second
213 * may actually be the beginning of the sync code.
215 if(x
== 0xff) { /* MAGIC NUMBER for first 8 frame sync bits. */
218 else if(x
>> 2 == 0x3e) { /* MAGIC NUMBER for last 6 sync bits. */
219 /* Succesfully synced. */
225 /* Advance and init bit buffer to the new frame. */
226 ci
->advance_buffer((get_bits_count(&fc
->gb
)-16)>>3); /* consumed bytes */
227 bit_buffer
= ci
->request_buffer(&buff_size
, MAX_FRAMESIZE
+16);
228 init_get_bits(&fc
->gb
, bit_buffer
, buff_size
*8);
230 /* Decode the frame to verify the frame crc and
231 * fill fc with its metadata.
233 if(flac_decode_frame(fc
, decoded0
, decoded1
,
234 bit_buffer
, buff_size
, ci
->yield
) < 0) {
241 /* Seek to sample - adapted from libFLAC 1.1.3b2+ */
242 static bool flac_seek(FLACContext
* fc
, uint32_t target_sample
) {
243 off_t orig_pos
= ci
->curpos
;
245 unsigned long lower_bound
, upper_bound
;
246 unsigned long lower_bound_sample
, upper_bound_sample
;
248 unsigned approx_bytes_per_frame
;
249 uint32_t this_frame_sample
= fc
->samplenumber
;
250 unsigned this_block_size
= fc
->blocksize
;
251 bool needs_seek
= true, first_seek
= true;
253 /* We are just guessing here. */
254 if(fc
->max_framesize
> 0)
255 approx_bytes_per_frame
= (fc
->max_framesize
+ fc
->min_framesize
)/2 + 1;
256 /* Check if it's a known fixed-blocksize stream. */
257 else if(fc
->min_blocksize
== fc
->max_blocksize
&& fc
->min_blocksize
> 0)
258 approx_bytes_per_frame
= fc
->min_blocksize
*fc
->channels
*fc
->bps
/8 + 64;
260 approx_bytes_per_frame
= 4608 * fc
->channels
* fc
->bps
/8 + 64;
262 /* Set an upper and lower bound on where in the stream we will search. */
263 lower_bound
= fc
->metadatalength
;
264 lower_bound_sample
= 0;
265 upper_bound
= fc
->filesize
;
266 upper_bound_sample
= fc
->totalsamples
>0 ? fc
->totalsamples
: target_sample
;
268 /* Refine the bounds if we have a seektable with suitable points. */
269 if(nseekpoints
> 0) {
270 /* Find the closest seek point <= target_sample, if it exists. */
271 for(i
= nseekpoints
-1; i
>= 0; i
--) {
272 if(seekpoints
[i
].sample
<= target_sample
)
275 if(i
>= 0) { /* i.e. we found a suitable seek point... */
276 lower_bound
= fc
->metadatalength
+ seekpoints
[i
].offset
;
277 lower_bound_sample
= seekpoints
[i
].sample
;
280 /* Find the closest seek point > target_sample, if it exists. */
281 for(i
= 0; i
< nseekpoints
; i
++) {
282 if(seekpoints
[i
].sample
> target_sample
)
285 if(i
< nseekpoints
) { /* i.e. we found a suitable seek point... */
286 upper_bound
= fc
->metadatalength
+ seekpoints
[i
].offset
;
287 upper_bound_sample
= seekpoints
[i
].sample
;
292 /* Check if bounds are still ok. */
293 if(lower_bound_sample
>= upper_bound_sample
||
294 lower_bound
> upper_bound
) {
298 /* Calculate new seek position */
300 pos
= (off_t
)(lower_bound
+
301 (((target_sample
- lower_bound_sample
) *
302 (int64_t)(upper_bound
- lower_bound
)) /
303 (upper_bound_sample
- lower_bound_sample
)) -
304 approx_bytes_per_frame
);
306 if(pos
>= (off_t
)upper_bound
)
307 pos
= (off_t
)upper_bound
-1;
308 if(pos
< (off_t
)lower_bound
)
309 pos
= (off_t
)lower_bound
;
312 if(!ci
->seek_buffer(pos
))
315 bit_buffer
= ci
->request_buffer(&buff_size
, MAX_FRAMESIZE
+16);
316 init_get_bits(&fc
->gb
, bit_buffer
, buff_size
*8);
318 /* Now we need to get a frame. It is possible for our seek
319 * to land in the middle of audio data that looks exactly like
320 * a frame header from a future version of an encoder. When
321 * that happens, frame_sync() will return false.
322 * But there is a remote possibility that it is properly
323 * synced at such a "future-codec frame", so to make sure,
324 * we wait to see several "unparseable" errors in a row before
328 unsigned unparseable_count
;
329 bool got_a_frame
= false;
330 for(unparseable_count
= 0; !got_a_frame
331 && unparseable_count
< 10; unparseable_count
++) {
336 ci
->seek_buffer(orig_pos
);
341 this_frame_sample
= fc
->samplenumber
;
342 this_block_size
= fc
->blocksize
;
344 if(target_sample
>= this_frame_sample
345 && target_sample
< this_frame_sample
+this_block_size
) {
346 /* Found the frame containing the target sample. */
347 fc
->sample_skip
= target_sample
- this_frame_sample
;
351 if(this_frame_sample
+ this_block_size
>= upper_bound_sample
&&
353 if(pos
== (off_t
)lower_bound
|| !needs_seek
) {
354 ci
->seek_buffer(orig_pos
);
357 /* Our last move backwards wasn't big enough, try again. */
358 approx_bytes_per_frame
*= 2;
361 /* Allow one seek over upper bound,
362 * required for streams with unknown total samples.
366 /* Make sure we are not seeking in a corrupted stream */
367 if(this_frame_sample
< lower_bound_sample
) {
368 ci
->seek_buffer(orig_pos
);
372 approx_bytes_per_frame
= this_block_size
*fc
->channels
*fc
->bps
/8 + 64;
374 /* We need to narrow the search. */
375 if(target_sample
< this_frame_sample
) {
376 upper_bound_sample
= this_frame_sample
;
377 upper_bound
= ci
->curpos
;
379 else { /* Target is beyond this frame. */
380 /* We are close, continue in decoding next frames. */
381 if(target_sample
< this_frame_sample
+ 4*this_block_size
) {
382 pos
= ci
->curpos
+ fc
->framesize
;
386 lower_bound_sample
= this_frame_sample
+ this_block_size
;
387 lower_bound
= ci
->curpos
+ fc
->framesize
;
394 /* Seek to file offset */
395 static bool flac_seek_offset(FLACContext
* fc
, uint32_t offset
) {
396 unsigned unparseable_count
;
397 bool got_a_frame
= false;
399 if(!ci
->seek_buffer(offset
))
402 bit_buffer
= ci
->request_buffer(&buff_size
, MAX_FRAMESIZE
);
403 init_get_bits(&fc
->gb
, bit_buffer
, buff_size
*8);
405 for(unparseable_count
= 0; !got_a_frame
406 && unparseable_count
< 10; unparseable_count
++) {
412 ci
->seek_buffer(fc
->metadatalength
);
419 /* this is the codec entry point */
420 enum codec_status
codec_main(void)
424 uint32_t samplesdone
= 0;
425 uint32_t elapsedtime
;
432 /* Generic codec initialisation */
433 ci
->configure(DSP_SET_SAMPLE_DEPTH
, FLAC_OUTPUT_DEPTH
-1);
437 /* Need to save offset for later use (cleared indirectly by flac_init) */
438 samplesdone
=ci
->id3
->offset
;
441 LOGF("FLAC: Error initialising codec\n");
442 retval
= CODEC_ERROR
;
446 while (!*ci
->taginfo_ready
&& !ci
->stop_codec
)
449 if (!flac_init(&fc
,ci
->id3
->first_frame_offset
)) {
450 LOGF("FLAC: Error initialising codec\n");
451 retval
= CODEC_ERROR
;
455 ci
->configure(DSP_SWITCH_FREQUENCY
, ci
->id3
->frequency
);
456 ci
->configure(DSP_SET_STEREO_MODE
, fc
.channels
== 1 ?
457 STEREO_MONO
: STEREO_NONINTERLEAVED
);
458 codec_set_replaygain(ci
->id3
);
461 flac_seek_offset(&fc
, samplesdone
);
465 /* The main decoding loop */
467 buf
= ci
->request_buffer(&bytesleft
, MAX_FRAMESIZE
);
470 if (ci
->stop_codec
|| ci
->new_track
) {
474 /* Deal with any pending seek requests */
476 if (flac_seek(&fc
,(uint32_t)(((uint64_t)(ci
->seek_time
-1)
477 *ci
->id3
->frequency
)/1000))) {
478 /* Refill the input buffer */
479 buf
= ci
->request_buffer(&bytesleft
, MAX_FRAMESIZE
);
484 if((res
=flac_decode_frame(&fc
,decoded0
,decoded1
,buf
,
485 bytesleft
,ci
->yield
)) < 0) {
486 LOGF("FLAC: Frame %d, error %d\n",frame
,res
);
487 retval
= CODEC_ERROR
;
490 consumed
=fc
.gb
.index
/8;
494 ci
->pcmbuf_insert(&decoded0
[fc
.sample_skip
], &decoded1
[fc
.sample_skip
],
495 fc
.blocksize
- fc
.sample_skip
);
499 /* Update the elapsed-time indicator */
500 samplesdone
=fc
.samplenumber
+fc
.blocksize
;
501 elapsedtime
=(samplesdone
*10)/(ci
->id3
->frequency
/100);
502 ci
->set_elapsed(elapsedtime
);
504 ci
->advance_buffer(consumed
);
506 buf
= ci
->request_buffer(&bytesleft
, MAX_FRAMESIZE
);
511 LOGF("FLAC: Decoded %lu samples\n",(unsigned long)samplesdone
);
513 if (ci
->request_next_track())