1 /***************************************************************************
3 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
4 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
5 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
6 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
10 * Copyright (C) 2005 Dave Chapman
12 * All files in this archive are subject to the GNU General Public License.
13 * See the file COPYING in the source tree root for full license agreement.
15 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
16 * KIND, either express or implied.
18 ****************************************************************************/
21 #include <codecs/libffmpegFLAC/decoder.h>
25 /* The output buffers containing the decoded samples (channels 0 and 1) */
26 int32_t decoded0
[MAX_BLOCKSIZE
] IBSS_ATTR_FLAC_DECODED0
;
27 int32_t decoded1
[MAX_BLOCKSIZE
] IBSS_ATTR
;
29 #define MAX_SUPPORTED_SEEKTABLE_SIZE 5000
31 /* Notes about seeking:
33 The full seek table consists of:
34 uint64_t sample (only 36 bits are used)
38 We also limit the sample and offset values to 32-bits - Rockbox doesn't
39 support files bigger than 2GB on FAT32 filesystems.
41 The reference FLAC encoder produces a seek table with points every
42 10 seconds, but this can be overridden by the user when encoding a file.
44 With the default settings, a typical 4 minute track will contain
47 Taking the extreme case of a Rockbox supported file to be a 2GB (compressed)
48 16-bit/44.1KHz mono stream with a likely uncompressed size of 4GB:
49 Total duration is: 48694 seconds (about 810 minutes - 13.5 hours)
50 Total number of seek points: 4869
52 Therefore we limit the number of seek points to 5000. This is a
53 very extreme case, and requires 5000*8=40000 bytes of storage.
55 If we come across a FLAC file with more than this number of seekpoints, we
56 just use the first 5000.
60 struct FLACseekpoints
{
66 struct FLACseekpoints seekpoints
[MAX_SUPPORTED_SEEKTABLE_SIZE
];
69 static int8_t *bit_buffer
;
70 static size_t buff_size
;
72 static bool flac_init(FLACContext
* fc
, int first_frame_offset
)
74 unsigned char buf
[255];
75 bool found_streaminfo
=false;
76 uint32_t seekpoint_hi
,seekpoint_lo
;
77 uint32_t offset_hi
,offset_lo
;
82 ci
->memset(fc
,0,sizeof(FLACContext
));
87 /* Skip any foreign tags at start of file */
88 ci
->seek_buffer(first_frame_offset
);
90 fc
->metadatalength
= first_frame_offset
;
92 if (ci
->read_filebuf(buf
, 4) < 4)
97 if (ci
->memcmp(buf
,"fLaC",4) != 0)
101 fc
->metadatalength
+= 4;
103 while (!endofmetadata
) {
104 if (ci
->read_filebuf(buf
, 4) < 4)
109 endofmetadata
=(buf
[0]&0x80);
110 blocklength
= (buf
[1] << 16) | (buf
[2] << 8) | buf
[3];
111 fc
->metadatalength
+=blocklength
+4;
113 if ((buf
[0] & 0x7f) == 0) /* 0 is the STREAMINFO block */
115 if (ci
->read_filebuf(buf
, blocklength
) < blocklength
) return false;
117 fc
->filesize
= ci
->filesize
;
118 fc
->min_blocksize
= (buf
[0] << 8) | buf
[1];
119 fc
->max_blocksize
= (buf
[2] << 8) | buf
[3];
120 fc
->min_framesize
= (buf
[4] << 16) | (buf
[5] << 8) | buf
[6];
121 fc
->max_framesize
= (buf
[7] << 16) | (buf
[8] << 8) | buf
[9];
122 fc
->samplerate
= (buf
[10] << 12) | (buf
[11] << 4)
123 | ((buf
[12] & 0xf0) >> 4);
124 fc
->channels
= ((buf
[12]&0x0e)>>1) + 1;
125 fc
->bps
= (((buf
[12]&0x01) << 4) | ((buf
[13]&0xf0)>>4) ) + 1;
127 /* totalsamples is a 36-bit field, but we assume <= 32 bits are
129 fc
->totalsamples
= (buf
[14] << 24) | (buf
[15] << 16)
130 | (buf
[16] << 8) | buf
[17];
132 /* Calculate track length (in ms) and estimate the bitrate
134 fc
->length
= (fc
->totalsamples
/ fc
->samplerate
) * 1000;
136 found_streaminfo
=true;
137 } else if ((buf
[0] & 0x7f) == 3) { /* 3 is the SEEKTABLE block */
138 while ((nseekpoints
< MAX_SUPPORTED_SEEKTABLE_SIZE
) &&
139 (blocklength
>= 18)) {
140 if (ci
->read_filebuf(buf
,18) < 18) return false;
143 seekpoint_hi
=(buf
[0] << 24) | (buf
[1] << 16) |
144 (buf
[2] << 8) | buf
[3];
145 seekpoint_lo
=(buf
[4] << 24) | (buf
[5] << 16) |
146 (buf
[6] << 8) | buf
[7];
147 offset_hi
=(buf
[8] << 24) | (buf
[9] << 16) |
148 (buf
[10] << 8) | buf
[11];
149 offset_lo
=(buf
[12] << 24) | (buf
[13] << 16) |
150 (buf
[14] << 8) | buf
[15];
152 blocksize
=(buf
[16] << 8) | buf
[17];
154 /* Only store seekpoints where the high 32 bits are zero */
155 if ((seekpoint_hi
== 0) && (seekpoint_lo
!= 0xffffffff) &&
157 seekpoints
[nseekpoints
].sample
=seekpoint_lo
;
158 seekpoints
[nseekpoints
].offset
=offset_lo
;
159 seekpoints
[nseekpoints
].blocksize
=blocksize
;
163 /* Skip any unread seekpoints */
165 ci
->advance_buffer(blocklength
);
167 /* Skip to next metadata block */
168 ci
->advance_buffer(blocklength
);
172 if (found_streaminfo
) {
173 fc
->bitrate
= ((fc
->filesize
-fc
->metadatalength
) * 8) / fc
->length
;
180 /* Synchronize to next frame in stream - adapted from libFLAC 1.1.3b2 */
181 bool frame_sync(FLACContext
* fc
) {
185 /* Make sure we're byte aligned. */
186 align_get_bits(&fc
->gb
);
189 if(fc
->gb
.size_in_bits
- get_bits_count(&fc
->gb
) < 8) {
190 /* Error, end of bitstream, a valid stream should never reach here
191 * since the buffer should contain at least one frame header.
199 x
= get_bits(&fc
->gb
, 8);
201 if(x
== 0xff) { /* MAGIC NUMBER for first 8 frame sync bits. */
202 x
= get_bits(&fc
->gb
, 8);
203 /* We have to check if we just read two 0xff's in a row; the second
204 * may actually be the beginning of the sync code.
206 if(x
== 0xff) { /* MAGIC NUMBER for first 8 frame sync bits. */
209 else if(x
>> 2 == 0x3e) { /* MAGIC NUMBER for last 6 sync bits. */
210 /* Succesfully synced. */
216 /* Advance and init bit buffer to the new frame. */
217 ci
->advance_buffer((get_bits_count(&fc
->gb
)-16)>>3); /* consumed bytes */
218 bit_buffer
= ci
->request_buffer(&buff_size
, MAX_FRAMESIZE
+16);
219 init_get_bits(&fc
->gb
, bit_buffer
, buff_size
*8);
221 /* Decode the frame to verify the frame crc and
222 * fill fc with its metadata.
224 if(flac_decode_frame(fc
, decoded0
, decoded1
,
225 bit_buffer
, buff_size
, ci
->yield
) < 0) {
232 /* Seek to sample - adapted from libFLAC 1.1.3b2+ */
233 bool flac_seek(FLACContext
* fc
, uint32_t target_sample
) {
234 off_t orig_pos
= ci
->curpos
;
236 unsigned long lower_bound
, upper_bound
;
237 unsigned long lower_bound_sample
, upper_bound_sample
;
239 unsigned approx_bytes_per_frame
;
240 uint32_t this_frame_sample
= fc
->samplenumber
;
241 unsigned this_block_size
= fc
->blocksize
;
242 bool needs_seek
= true, first_seek
= true;
244 /* We are just guessing here. */
245 if(fc
->max_framesize
> 0)
246 approx_bytes_per_frame
= (fc
->max_framesize
+ fc
->min_framesize
)/2 + 1;
247 /* Check if it's a known fixed-blocksize stream. */
248 else if(fc
->min_blocksize
== fc
->max_blocksize
&& fc
->min_blocksize
> 0)
249 approx_bytes_per_frame
= fc
->min_blocksize
*fc
->channels
*fc
->bps
/8 + 64;
251 approx_bytes_per_frame
= 4608 * fc
->channels
* fc
->bps
/8 + 64;
253 /* Set an upper and lower bound on where in the stream we will search. */
254 lower_bound
= fc
->metadatalength
;
255 lower_bound_sample
= 0;
256 upper_bound
= fc
->filesize
;
257 upper_bound_sample
= fc
->totalsamples
>0 ? fc
->totalsamples
: target_sample
;
259 /* Refine the bounds if we have a seektable with suitable points. */
260 if(nseekpoints
> 0) {
261 /* Find the closest seek point <= target_sample, if it exists. */
262 for(i
= nseekpoints
-1; i
>= 0; i
--) {
263 if(seekpoints
[i
].sample
<= target_sample
)
266 if(i
>= 0) { /* i.e. we found a suitable seek point... */
267 lower_bound
= fc
->metadatalength
+ seekpoints
[i
].offset
;
268 lower_bound_sample
= seekpoints
[i
].sample
;
271 /* Find the closest seek point > target_sample, if it exists. */
272 for(i
= 0; i
< nseekpoints
; i
++) {
273 if(seekpoints
[i
].sample
> target_sample
)
276 if(i
< nseekpoints
) { /* i.e. we found a suitable seek point... */
277 upper_bound
= fc
->metadatalength
+ seekpoints
[i
].offset
;
278 upper_bound_sample
= seekpoints
[i
].sample
;
283 /* Check if bounds are still ok. */
284 if(lower_bound_sample
>= upper_bound_sample
||
285 lower_bound
> upper_bound
) {
289 /* Calculate new seek position */
291 pos
= (off_t
)(lower_bound
+
292 (((target_sample
- lower_bound_sample
) *
293 (int64_t)(upper_bound
- lower_bound
)) /
294 (upper_bound_sample
- lower_bound_sample
)) -
295 approx_bytes_per_frame
);
297 if(pos
>= (off_t
)upper_bound
)
298 pos
= (off_t
)upper_bound
-1;
299 if(pos
< (off_t
)lower_bound
)
300 pos
= (off_t
)lower_bound
;
303 if(!ci
->seek_buffer(pos
))
306 bit_buffer
= ci
->request_buffer(&buff_size
, MAX_FRAMESIZE
+16);
307 init_get_bits(&fc
->gb
, bit_buffer
, buff_size
*8);
309 /* Now we need to get a frame. It is possible for our seek
310 * to land in the middle of audio data that looks exactly like
311 * a frame header from a future version of an encoder. When
312 * that happens, frame_sync() will return false.
313 * But there is a remote possibility that it is properly
314 * synced at such a "future-codec frame", so to make sure,
315 * we wait to see several "unparseable" errors in a row before
319 unsigned unparseable_count
;
320 bool got_a_frame
= false;
321 for(unparseable_count
= 0; !got_a_frame
322 && unparseable_count
< 10; unparseable_count
++) {
327 ci
->seek_buffer(orig_pos
);
332 this_frame_sample
= fc
->samplenumber
;
333 this_block_size
= fc
->blocksize
;
335 if(target_sample
>= this_frame_sample
336 && target_sample
< this_frame_sample
+this_block_size
) {
337 /* Found the frame containing the target sample. */
338 fc
->sample_skip
= target_sample
- this_frame_sample
;
342 if(this_frame_sample
+ this_block_size
>= upper_bound_sample
&&
344 if(pos
== (off_t
)lower_bound
|| !needs_seek
) {
345 ci
->seek_buffer(orig_pos
);
348 /* Our last move backwards wasn't big enough, try again. */
349 approx_bytes_per_frame
*= 2;
352 /* Allow one seek over upper bound,
353 * required for streams with unknown total samples.
357 /* Make sure we are not seeking in a corrupted stream */
358 if(this_frame_sample
< lower_bound_sample
) {
359 ci
->seek_buffer(orig_pos
);
363 approx_bytes_per_frame
= this_block_size
*fc
->channels
*fc
->bps
/8 + 64;
365 /* We need to narrow the search. */
366 if(target_sample
< this_frame_sample
) {
367 upper_bound_sample
= this_frame_sample
;
368 upper_bound
= ci
->curpos
;
370 else { /* Target is beyond this frame. */
371 /* We are close, continue in decoding next frames. */
372 if(target_sample
< this_frame_sample
+ 4*this_block_size
) {
373 pos
= ci
->curpos
+ fc
->framesize
;
377 lower_bound_sample
= this_frame_sample
+ this_block_size
;
378 lower_bound
= ci
->curpos
+ fc
->framesize
;
385 /* Seek to file offset */
386 bool flac_seek_offset(FLACContext
* fc
, uint32_t offset
) {
387 unsigned unparseable_count
;
388 bool got_a_frame
= false;
390 if(!ci
->seek_buffer(offset
))
393 bit_buffer
= ci
->request_buffer(&buff_size
, MAX_FRAMESIZE
);
394 init_get_bits(&fc
->gb
, bit_buffer
, buff_size
*8);
396 for(unparseable_count
= 0; !got_a_frame
397 && unparseable_count
< 10; unparseable_count
++) {
403 ci
->seek_buffer(fc
->metadatalength
);
410 /* this is the codec entry point */
411 enum codec_status
codec_main(void)
415 uint32_t samplesdone
= 0;
416 uint32_t elapsedtime
;
423 /* Generic codec initialisation */
424 ci
->configure(CODEC_SET_FILEBUF_WATERMARK
, 1024*512);
426 ci
->configure(DSP_SET_SAMPLE_DEPTH
, FLAC_OUTPUT_DEPTH
-1);
430 /* Need to save offset for later use (cleared indirectly by flac_init) */
431 samplesdone
=ci
->id3
->offset
;
434 LOGF("FLAC: Error initialising codec\n");
435 retval
= CODEC_ERROR
;
439 if (!flac_init(&fc
,ci
->id3
->first_frame_offset
)) {
440 LOGF("FLAC: Error initialising codec\n");
441 retval
= CODEC_ERROR
;
445 while (!*ci
->taginfo_ready
&& !ci
->stop_codec
)
448 ci
->configure(DSP_SWITCH_FREQUENCY
, ci
->id3
->frequency
);
449 ci
->configure(DSP_SET_STEREO_MODE
, fc
.channels
== 1 ?
450 STEREO_MONO
: STEREO_NONINTERLEAVED
);
451 codec_set_replaygain(ci
->id3
);
454 flac_seek_offset(&fc
, samplesdone
);
458 /* The main decoding loop */
460 buf
= ci
->request_buffer(&bytesleft
, MAX_FRAMESIZE
);
463 if (ci
->stop_codec
|| ci
->new_track
) {
467 /* Deal with any pending seek requests */
469 if (flac_seek(&fc
,(uint32_t)(((uint64_t)(ci
->seek_time
-1)
470 *ci
->id3
->frequency
)/1000))) {
471 /* Refill the input buffer */
472 buf
= ci
->request_buffer(&bytesleft
, MAX_FRAMESIZE
);
477 if((res
=flac_decode_frame(&fc
,decoded0
,decoded1
,buf
,
478 bytesleft
,ci
->yield
)) < 0) {
479 LOGF("FLAC: Frame %d, error %d\n",frame
,res
);
480 retval
= CODEC_ERROR
;
483 consumed
=fc
.gb
.index
/8;
487 ci
->pcmbuf_insert(&decoded0
[fc
.sample_skip
], &decoded1
[fc
.sample_skip
],
488 fc
.blocksize
- fc
.sample_skip
);
492 /* Update the elapsed-time indicator */
493 samplesdone
=fc
.samplenumber
+fc
.blocksize
;
494 elapsedtime
=(samplesdone
*10)/(ci
->id3
->frequency
/100);
495 ci
->set_elapsed(elapsedtime
);
497 ci
->advance_buffer(consumed
);
499 buf
= ci
->request_buffer(&bytesleft
, MAX_FRAMESIZE
);
504 LOGF("FLAC: Decoded %ld samples\n",samplesdone
);
506 if (ci
->request_next_track())