Improved FPS test plugin: * Better precision for low frame rates (take extra ticks...
[Rockbox.git] / apps / codecs / flac.c
blob2eb0deb9f53dbbadeedd918e4226c016bf5c6de5
1 /***************************************************************************
2 * __________ __ ___.
3 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
4 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
5 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
6 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
7 * \/ \/ \/ \/ \/
8 * $Id$
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 ****************************************************************************/
20 #include "codeclib.h"
21 #include <codecs/libffmpegFLAC/decoder.h>
23 CODEC_HEADER
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)
35 uint64_t offset
36 uint32_t blocksize
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
45 24 seek points.
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 {
61 uint32_t sample;
62 uint32_t offset;
63 uint16_t blocksize;
66 struct FLACseekpoints seekpoints[MAX_SUPPORTED_SEEKTABLE_SIZE];
67 int nseekpoints;
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;
78 uint16_t blocksize;
79 int endofmetadata=0;
80 int blocklength;
81 int n;
83 ci->memset(fc,0,sizeof(FLACContext));
84 nseekpoints=0;
86 fc->sample_skip = 0;
88 /* Skip any foreign tags at start of file */
89 ci->seek_buffer(first_frame_offset);
91 fc->metadatalength = first_frame_offset;
93 if (ci->read_filebuf(buf, 4) < 4)
95 return false;
98 if (ci->memcmp(buf,"fLaC",4) != 0)
100 return false;
102 fc->metadatalength += 4;
104 while (!endofmetadata) {
105 if (ci->read_filebuf(buf, 4) < 4)
107 return false;
110 endofmetadata=(buf[0]&0x80);
111 blocklength = (buf[1] << 16) | (buf[2] << 8) | buf[3];
112 fc->metadatalength+=blocklength+4;
114 if ((buf[0] & 0x7f) == 0) /* 0 is the STREAMINFO block */
116 /* FIXME: Don't trust the value of blocklength, use actual return
117 * value in bytes instead */
118 ci->read_filebuf(buf, blocklength);
120 fc->filesize = ci->filesize;
121 fc->min_blocksize = (buf[0] << 8) | buf[1];
122 fc->max_blocksize = (buf[2] << 8) | buf[3];
123 fc->min_framesize = (buf[4] << 16) | (buf[5] << 8) | buf[6];
124 fc->max_framesize = (buf[7] << 16) | (buf[8] << 8) | buf[9];
125 fc->samplerate = (buf[10] << 12) | (buf[11] << 4)
126 | ((buf[12] & 0xf0) >> 4);
127 fc->channels = ((buf[12]&0x0e)>>1) + 1;
128 fc->bps = (((buf[12]&0x01) << 4) | ((buf[13]&0xf0)>>4) ) + 1;
130 /* totalsamples is a 36-bit field, but we assume <= 32 bits are
131 used */
132 fc->totalsamples = (buf[14] << 24) | (buf[15] << 16)
133 | (buf[16] << 8) | buf[17];
135 /* Calculate track length (in ms) and estimate the bitrate
136 (in kbit/s) */
137 fc->length = (fc->totalsamples / fc->samplerate) * 1000;
139 found_streaminfo=true;
140 } else if ((buf[0] & 0x7f) == 3) { /* 3 is the SEEKTABLE block */
141 while ((nseekpoints < MAX_SUPPORTED_SEEKTABLE_SIZE) &&
142 (blocklength >= 18)) {
143 n=ci->read_filebuf(buf,18);
144 if (n < 18) return false;
145 blocklength-=n;
147 seekpoint_hi=(buf[0] << 24) | (buf[1] << 16) |
148 (buf[2] << 8) | buf[3];
149 seekpoint_lo=(buf[4] << 24) | (buf[5] << 16) |
150 (buf[6] << 8) | buf[7];
151 offset_hi=(buf[8] << 24) | (buf[9] << 16) |
152 (buf[10] << 8) | buf[11];
153 offset_lo=(buf[12] << 24) | (buf[13] << 16) |
154 (buf[14] << 8) | buf[15];
156 blocksize=(buf[16] << 8) | buf[17];
158 /* Only store seekpoints where the high 32 bits are zero */
159 if ((seekpoint_hi == 0) && (seekpoint_lo != 0xffffffff) &&
160 (offset_hi == 0)) {
161 seekpoints[nseekpoints].sample=seekpoint_lo;
162 seekpoints[nseekpoints].offset=offset_lo;
163 seekpoints[nseekpoints].blocksize=blocksize;
164 nseekpoints++;
167 /* Skip any unread seekpoints */
168 if (blocklength > 0)
169 ci->advance_buffer(blocklength);
170 } else {
171 /* Skip to next metadata block */
172 ci->advance_buffer(blocklength);
176 if (found_streaminfo) {
177 fc->bitrate = ((fc->filesize-fc->metadatalength) * 8) / fc->length;
178 return true;
179 } else {
180 return false;
184 /* Synchronize to next frame in stream - adapted from libFLAC 1.1.3b2 */
185 bool frame_sync(FLACContext* fc) {
186 unsigned int x = 0;
187 bool cached = false;
189 /* Make sure we're byte aligned. */
190 align_get_bits(&fc->gb);
192 while(1) {
193 if(fc->gb.size_in_bits - get_bits_count(&fc->gb) < 8) {
194 /* Error, end of bitstream, a valid stream should never reach here
195 * since the buffer should contain at least one frame header.
197 return false;
200 if(cached)
201 cached = false;
202 else
203 x = get_bits(&fc->gb, 8);
205 if(x == 0xff) { /* MAGIC NUMBER for first 8 frame sync bits. */
206 x = get_bits(&fc->gb, 8);
207 /* We have to check if we just read two 0xff's in a row; the second
208 * may actually be the beginning of the sync code.
210 if(x == 0xff) { /* MAGIC NUMBER for first 8 frame sync bits. */
211 cached = true;
213 else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for last 6 sync bits. */
214 /* Succesfully synced. */
215 break;
220 /* Advance and init bit buffer to the new frame. */
221 ci->advance_buffer((get_bits_count(&fc->gb)-16)>>3); /* consumed bytes */
222 bit_buffer = ci->request_buffer(&buff_size, MAX_FRAMESIZE+16);
223 init_get_bits(&fc->gb, bit_buffer, buff_size*8);
225 /* Decode the frame to verify the frame crc and
226 * fill fc with its metadata.
228 if(flac_decode_frame(fc, decoded0, decoded1,
229 bit_buffer, buff_size, ci->yield) < 0) {
230 return false;
233 return true;
236 /* Seek to sample - adapted from libFLAC 1.1.3b2+ */
237 bool flac_seek(FLACContext* fc, uint32_t target_sample) {
238 off_t orig_pos = ci->curpos;
239 off_t pos = -1;
240 unsigned long lower_bound, upper_bound;
241 unsigned long lower_bound_sample, upper_bound_sample;
242 int i;
243 unsigned approx_bytes_per_frame;
244 uint32_t this_frame_sample = fc->samplenumber;
245 unsigned this_block_size = fc->blocksize;
246 bool needs_seek = true, first_seek = true;
248 /* We are just guessing here. */
249 if(fc->max_framesize > 0)
250 approx_bytes_per_frame = (fc->max_framesize + fc->min_framesize)/2 + 1;
251 /* Check if it's a known fixed-blocksize stream. */
252 else if(fc->min_blocksize == fc->max_blocksize && fc->min_blocksize > 0)
253 approx_bytes_per_frame = fc->min_blocksize*fc->channels*fc->bps/8 + 64;
254 else
255 approx_bytes_per_frame = 4608 * fc->channels * fc->bps/8 + 64;
257 /* Set an upper and lower bound on where in the stream we will search. */
258 lower_bound = fc->metadatalength;
259 lower_bound_sample = 0;
260 upper_bound = fc->filesize;
261 upper_bound_sample = fc->totalsamples>0 ? fc->totalsamples : target_sample;
263 /* Refine the bounds if we have a seektable with suitable points. */
264 if(nseekpoints > 0) {
265 /* Find the closest seek point <= target_sample, if it exists. */
266 for(i = nseekpoints-1; i >= 0; i--) {
267 if(seekpoints[i].sample <= target_sample)
268 break;
270 if(i >= 0) { /* i.e. we found a suitable seek point... */
271 lower_bound = fc->metadatalength + seekpoints[i].offset;
272 lower_bound_sample = seekpoints[i].sample;
275 /* Find the closest seek point > target_sample, if it exists. */
276 for(i = 0; i < nseekpoints; i++) {
277 if(seekpoints[i].sample > target_sample)
278 break;
280 if(i < nseekpoints) { /* i.e. we found a suitable seek point... */
281 upper_bound = fc->metadatalength + seekpoints[i].offset;
282 upper_bound_sample = seekpoints[i].sample;
286 while(1) {
287 /* Check if bounds are still ok. */
288 if(lower_bound_sample >= upper_bound_sample ||
289 lower_bound > upper_bound) {
290 return false;
293 /* Calculate new seek position */
294 if(needs_seek) {
295 pos = (off_t)(lower_bound +
296 (((target_sample - lower_bound_sample) *
297 (int64_t)(upper_bound - lower_bound)) /
298 (upper_bound_sample - lower_bound_sample)) -
299 approx_bytes_per_frame);
301 if(pos >= (off_t)upper_bound)
302 pos = (off_t)upper_bound-1;
303 if(pos < (off_t)lower_bound)
304 pos = (off_t)lower_bound;
307 if(!ci->seek_buffer(pos))
308 return false;
310 bit_buffer = ci->request_buffer(&buff_size, MAX_FRAMESIZE+16);
311 init_get_bits(&fc->gb, bit_buffer, buff_size*8);
313 /* Now we need to get a frame. It is possible for our seek
314 * to land in the middle of audio data that looks exactly like
315 * a frame header from a future version of an encoder. When
316 * that happens, frame_sync() will return false.
317 * But there is a remote possibility that it is properly
318 * synced at such a "future-codec frame", so to make sure,
319 * we wait to see several "unparseable" errors in a row before
320 * bailing out.
323 unsigned unparseable_count;
324 bool got_a_frame = false;
325 for(unparseable_count = 0; !got_a_frame
326 && unparseable_count < 10; unparseable_count++) {
327 if(frame_sync(fc))
328 got_a_frame = true;
330 if(!got_a_frame) {
331 ci->seek_buffer(orig_pos);
332 return false;
336 this_frame_sample = fc->samplenumber;
337 this_block_size = fc->blocksize;
339 if(target_sample >= this_frame_sample
340 && target_sample < this_frame_sample+this_block_size) {
341 /* Found the frame containing the target sample. */
342 fc->sample_skip = target_sample - this_frame_sample;
343 break;
346 if(this_frame_sample + this_block_size >= upper_bound_sample &&
347 !first_seek) {
348 if(pos == (off_t)lower_bound || !needs_seek) {
349 ci->seek_buffer(orig_pos);
350 return false;
352 /* Our last move backwards wasn't big enough, try again. */
353 approx_bytes_per_frame *= 2;
354 continue;
356 /* Allow one seek over upper bound,
357 * required for streams with unknown total samples.
359 first_seek = false;
361 /* Make sure we are not seeking in a corrupted stream */
362 if(this_frame_sample < lower_bound_sample) {
363 ci->seek_buffer(orig_pos);
364 return false;
367 approx_bytes_per_frame = this_block_size*fc->channels*fc->bps/8 + 64;
369 /* We need to narrow the search. */
370 if(target_sample < this_frame_sample) {
371 upper_bound_sample = this_frame_sample;
372 upper_bound = ci->curpos;
374 else { /* Target is beyond this frame. */
375 /* We are close, continue in decoding next frames. */
376 if(target_sample < this_frame_sample + 4*this_block_size) {
377 pos = ci->curpos + fc->framesize;
378 needs_seek = false;
381 lower_bound_sample = this_frame_sample + this_block_size;
382 lower_bound = ci->curpos + fc->framesize;
386 return true;
389 /* Seek to file offset */
390 bool flac_seek_offset(FLACContext* fc, uint32_t offset) {
391 unsigned unparseable_count;
392 bool got_a_frame = false;
394 if(!ci->seek_buffer(offset))
395 return false;
397 bit_buffer = ci->request_buffer(&buff_size, MAX_FRAMESIZE);
398 init_get_bits(&fc->gb, bit_buffer, buff_size*8);
400 for(unparseable_count = 0; !got_a_frame
401 && unparseable_count < 10; unparseable_count++) {
402 if(frame_sync(fc))
403 got_a_frame = true;
406 if(!got_a_frame) {
407 ci->seek_buffer(fc->metadatalength);
408 return false;
411 return true;
414 /* this is the codec entry point */
415 enum codec_status codec_main(void)
417 int8_t *buf;
418 FLACContext fc;
419 uint32_t samplesdone = 0;
420 uint32_t elapsedtime;
421 size_t bytesleft;
422 int consumed;
423 int res;
424 int frame;
425 int retval;
427 /* Generic codec initialisation */
428 ci->configure(CODEC_SET_FILEBUF_WATERMARK, 1024*512);
429 ci->configure(CODEC_SET_FILEBUF_CHUNKSIZE, 1024*128);
431 ci->configure(DSP_SET_SAMPLE_DEPTH, FLAC_OUTPUT_DEPTH-1);
433 next_track:
435 /* Need to save offset for later use (cleared indirectly by flac_init) */
436 samplesdone=ci->id3->offset;
438 if (codec_init()) {
439 LOGF("FLAC: Error initialising codec\n");
440 retval = CODEC_ERROR;
441 goto exit;
444 if (!flac_init(&fc,ci->id3->first_frame_offset)) {
445 LOGF("FLAC: Error initialising codec\n");
446 retval = CODEC_ERROR;
447 goto done;
450 while (!*ci->taginfo_ready && !ci->stop_codec)
451 ci->sleep(1);
453 ci->configure(DSP_SWITCH_FREQUENCY, ci->id3->frequency);
454 ci->configure(DSP_SET_STEREO_MODE, fc.channels == 1 ?
455 STEREO_MONO : STEREO_NONINTERLEAVED);
456 codec_set_replaygain(ci->id3);
458 if (samplesdone) {
459 flac_seek_offset(&fc, samplesdone);
460 samplesdone=0;
463 /* The main decoding loop */
464 frame=0;
465 buf = ci->request_buffer(&bytesleft, MAX_FRAMESIZE);
466 while (bytesleft) {
467 ci->yield();
468 if (ci->stop_codec || ci->new_track) {
469 break;
472 /* Deal with any pending seek requests */
473 if (ci->seek_time) {
474 if (flac_seek(&fc,(uint32_t)(((uint64_t)(ci->seek_time-1)
475 *ci->id3->frequency)/1000))) {
476 /* Refill the input buffer */
477 buf = ci->request_buffer(&bytesleft, MAX_FRAMESIZE);
479 ci->seek_complete();
482 if((res=flac_decode_frame(&fc,decoded0,decoded1,buf,
483 bytesleft,ci->yield)) < 0) {
484 LOGF("FLAC: Frame %d, error %d\n",frame,res);
485 retval = CODEC_ERROR;
486 goto done;
488 consumed=fc.gb.index/8;
489 frame++;
491 ci->yield();
492 ci->pcmbuf_insert(&decoded0[fc.sample_skip], &decoded1[fc.sample_skip],
493 fc.blocksize - fc.sample_skip);
495 fc.sample_skip = 0;
497 /* Update the elapsed-time indicator */
498 samplesdone=fc.samplenumber+fc.blocksize;
499 elapsedtime=(samplesdone*10)/(ci->id3->frequency/100);
500 ci->set_elapsed(elapsedtime);
502 ci->advance_buffer(consumed);
504 buf = ci->request_buffer(&bytesleft, MAX_FRAMESIZE);
506 retval = CODEC_OK;
508 done:
509 LOGF("FLAC: Decoded %ld samples\n",samplesdone);
511 if (ci->request_next_track())
512 goto next_track;
514 exit:
515 return retval;