Fix remote screen check in graphic equalizer, so that it can be used on logf-enabled...
[Rockbox.git] / firmware / mp3data.c
blob0710090b377d6b6f83c0bd5e59108629e4483f49
1 /***************************************************************************
2 * __________ __ ___.
3 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
4 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
5 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
6 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
7 * \/ \/ \/ \/ \/
8 * $Id$
10 * Copyright (C) 2002 by Daniel Stenberg
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 * Parts of this code has been stolen from the Ample project and was written
22 * by David Härdeman. It has since been extended and enhanced pretty much by
23 * all sorts of friendly Rockbox people.
25 * A nice reference for MPEG header info:
26 * http://rockbox.haxx.se/docs/mpeghdr.html
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #include <stdbool.h>
34 #include <limits.h>
35 #include "debug.h"
36 #include "logf.h"
37 #include "mp3data.h"
38 #include "file.h"
39 #include "buffer.h"
41 #define DEBUG_VERBOSE
43 #define BYTES2INT(b1,b2,b3,b4) (((long)(b1 & 0xFF) << (3*8)) | \
44 ((long)(b2 & 0xFF) << (2*8)) | \
45 ((long)(b3 & 0xFF) << (1*8)) | \
46 ((long)(b4 & 0xFF) << (0*8)))
48 #define SYNC_MASK (0x7ffL << 21)
49 #define VERSION_MASK (3L << 19)
50 #define LAYER_MASK (3L << 17)
51 #define PROTECTION_MASK (1L << 16)
52 #define BITRATE_MASK (0xfL << 12)
53 #define SAMPLERATE_MASK (3L << 10)
54 #define PADDING_MASK (1L << 9)
55 #define PRIVATE_MASK (1L << 8)
56 #define CHANNELMODE_MASK (3L << 6)
57 #define MODE_EXT_MASK (3L << 4)
58 #define COPYRIGHT_MASK (1L << 3)
59 #define ORIGINAL_MASK (1L << 2)
60 #define EMPHASIS_MASK 3L
62 /* MPEG Version table, sorted by version index */
63 static const signed char version_table[4] = {
64 MPEG_VERSION2_5, -1, MPEG_VERSION2, MPEG_VERSION1
67 /* Bitrate table for mpeg audio, indexed by row index and birate index */
68 static const short bitrates[5][16] = {
69 {0,32,64,96,128,160,192,224,256,288,320,352,384,416,448,0}, /* V1 L1 */
70 {0,32,48,56, 64, 80, 96,112,128,160,192,224,256,320,384,0}, /* V1 L2 */
71 {0,32,40,48, 56, 64, 80, 96,112,128,160,192,224,256,320,0}, /* V1 L3 */
72 {0,32,48,56, 64, 80, 96,112,128,144,160,176,192,224,256,0}, /* V2 L1 */
73 {0, 8,16,24, 32, 40, 48, 56, 64, 80, 96,112,128,144,160,0} /* V2 L2+L3 */
76 /* Bitrate pointer table, indexed by version and layer */
77 static const short *bitrate_table[3][3] =
79 {bitrates[0], bitrates[1], bitrates[2]},
80 {bitrates[3], bitrates[4], bitrates[4]},
81 {bitrates[3], bitrates[4], bitrates[4]}
84 /* Sampling frequency table, indexed by version and frequency index */
85 static const long freq_table[3][3] =
87 {44100, 48000, 32000}, /* MPEG Version 1 */
88 {22050, 24000, 16000}, /* MPEG version 2 */
89 {11025, 12000, 8000}, /* MPEG version 2.5 */
92 /* check if 'head' is a valid mp3 frame header */
93 static bool is_mp3frameheader(unsigned long head)
95 if ((head & SYNC_MASK) != (unsigned long)SYNC_MASK) /* bad sync? */
96 return false;
97 if ((head & VERSION_MASK) == (1L << 19)) /* bad version? */
98 return false;
99 if (!(head & LAYER_MASK)) /* no layer? */
100 return false;
101 #if CONFIG_CODEC != SWCODEC
102 /* The MAS can't decode layer 1, so treat layer 1 data as invalid */
103 if ((head & LAYER_MASK) == LAYER_MASK)
104 return false;
105 #endif
106 if ((head & BITRATE_MASK) == BITRATE_MASK) /* bad bitrate? */
107 return false;
108 if (!(head & BITRATE_MASK)) /* no bitrate? */
109 return false;
110 if ((head & SAMPLERATE_MASK) == SAMPLERATE_MASK) /* bad sample rate? */
111 return false;
113 return true;
116 static bool mp3headerinfo(struct mp3info *info, unsigned long header)
118 int bitindex, freqindex;
120 /* MPEG Audio Version */
121 if ((header & VERSION_MASK) >> 19 >= sizeof(version_table))
122 return false;
124 info->version = version_table[(header & VERSION_MASK) >> 19];
125 if (info->version < 0)
126 return false;
128 /* Layer */
129 info->layer = 3 - ((header & LAYER_MASK) >> 17);
130 if (info->layer == 3)
131 return false;
133 info->protection = (header & PROTECTION_MASK) ? true : false;
135 /* Bitrate */
136 bitindex = (header & BITRATE_MASK) >> 12;
137 info->bitrate = bitrate_table[info->version][info->layer][bitindex];
138 if(info->bitrate == 0)
139 return false;
141 /* Sampling frequency */
142 freqindex = (header & SAMPLERATE_MASK) >> 10;
143 if (freqindex == 3)
144 return false;
145 info->frequency = freq_table[info->version][freqindex];
147 info->padding = (header & PADDING_MASK) ? 1 : 0;
149 /* Calculate number of bytes, calculation depends on layer */
150 if (info->layer == 0) {
151 info->frame_samples = 384;
152 info->frame_size = (12000 * info->bitrate / info->frequency
153 + info->padding) * 4;
155 else {
156 if ((info->version > MPEG_VERSION1) && (info->layer == 2))
157 info->frame_samples = 576;
158 else
159 info->frame_samples = 1152;
160 info->frame_size = (1000/8) * info->frame_samples * info->bitrate
161 / info->frequency + info->padding;
164 /* Frametime fraction denominator */
165 if (freqindex != 0) { /* 48/32/24/16/12/8 kHz */
166 info->ft_den = 1; /* integer number of milliseconds */
168 else { /* 44.1/22.05/11.025 kHz */
169 if (info->layer == 0) /* layer 1 */
170 info->ft_den = 147;
171 else /* layer 2+3 */
172 info->ft_den = 49;
174 /* Frametime fraction numerator */
175 info->ft_num = 1000 * info->ft_den * info->frame_samples / info->frequency;
177 info->channel_mode = (header & CHANNELMODE_MASK) >> 6;
178 info->mode_extension = (header & MODE_EXT_MASK) >> 4;
179 info->emphasis = header & EMPHASIS_MASK;
181 #ifdef DEBUG_VERBOSE
182 DEBUGF( "Header: %08x, Ver %d, lay %d, bitr %d, freq %ld, "
183 "chmode %d, mode_ext %d, emph %d, bytes: %d time: %d/%d\n",
184 header, info->version, info->layer+1, info->bitrate,
185 info->frequency, info->channel_mode, info->mode_extension,
186 info->emphasis, info->frame_size, info->ft_num, info->ft_den);
187 #endif
188 return true;
191 static unsigned long __find_next_frame(int fd, long *offset, long max_offset,
192 unsigned long last_header,
193 int(*getfunc)(int fd, unsigned char *c))
195 unsigned long header=0;
196 unsigned char tmp;
197 int i;
199 long pos = 0;
201 /* We remember the last header we found, to use as a template to see if
202 the header we find has the same frequency, layer etc */
203 last_header &= 0xffff0c00;
205 /* Fill up header with first 24 bits */
206 for(i = 0; i < 3; i++) {
207 header <<= 8;
208 if(!getfunc(fd, &tmp))
209 return 0;
210 header |= tmp;
211 pos++;
214 do {
215 header <<= 8;
216 if(!getfunc(fd, &tmp))
217 return 0;
218 header |= tmp;
219 pos++;
220 if(max_offset > 0 && pos > max_offset)
221 return 0;
222 } while(!is_mp3frameheader(header) ||
223 (last_header?((header & 0xffff0c00) != last_header):false));
225 *offset = pos - 4;
227 #if defined(DEBUG) || defined(SIMULATOR)
228 if(*offset)
229 DEBUGF("Warning: skipping %d bytes of garbage\n", *offset);
230 #endif
232 return header;
235 static int fileread(int fd, unsigned char *c)
237 return read(fd, c, 1);
240 unsigned long find_next_frame(int fd, long *offset, long max_offset, unsigned long last_header)
242 return __find_next_frame(fd, offset, max_offset, last_header, fileread);
245 static int fnf_read_index;
246 static int fnf_buf_len;
248 static int buf_getbyte(int fd, unsigned char *c)
250 if(fnf_read_index < fnf_buf_len)
252 *c = audiobuf[fnf_read_index++];
253 return 1;
255 else
257 fnf_buf_len = read(fd, audiobuf, audiobufend - audiobuf);
258 if(fnf_buf_len < 0)
259 return -1;
261 fnf_read_index = 0;
263 if(fnf_buf_len > 0)
265 *c = audiobuf[fnf_read_index++];
266 return 1;
268 else
269 return 0;
271 return 0;
274 static int buf_seek(int fd, int len)
276 fnf_read_index += len;
277 if(fnf_read_index > fnf_buf_len)
279 len = fnf_read_index - fnf_buf_len;
281 fnf_buf_len = read(fd, audiobuf, audiobufend - audiobuf);
282 if(fnf_buf_len < 0)
283 return -1;
285 fnf_read_index = 0;
286 fnf_read_index += len;
289 if(fnf_read_index > fnf_buf_len)
291 return -1;
293 else
294 return 0;
297 static void buf_init(void)
299 fnf_buf_len = 0;
300 fnf_read_index = 0;
303 unsigned long buf_find_next_frame(int fd, long *offset, long max_offset,
304 unsigned long last_header)
306 return __find_next_frame(fd, offset, max_offset, last_header, buf_getbyte);
309 static int audiobuflen;
310 static int mem_pos;
311 static int mem_cnt;
312 static int mem_maxlen;
314 static int mem_getbyte(int dummy, unsigned char *c)
316 dummy = dummy;
318 *c = audiobuf[mem_pos++];
319 if(mem_pos >= audiobuflen)
320 mem_pos = 0;
322 if(mem_cnt++ >= mem_maxlen)
323 return 0;
324 else
325 return 1;
328 unsigned long mem_find_next_frame(int startpos, long *offset, long max_offset,
329 unsigned long last_header)
331 audiobuflen = audiobufend - audiobuf;
332 mem_pos = startpos;
333 mem_cnt = 0;
334 mem_maxlen = max_offset;
336 return __find_next_frame(0, offset, max_offset, last_header, mem_getbyte);
339 int get_mp3file_info(int fd, struct mp3info *info)
341 unsigned char frame[1800];
342 unsigned char *vbrheader;
343 unsigned long header;
344 long bytecount;
345 int num_offsets;
346 int frames_per_entry;
347 int i;
348 long offset;
349 int j;
350 long tmp;
352 header = find_next_frame(fd, &bytecount, 0x20000, 0);
353 /* Quit if we haven't found a valid header within 128K */
354 if(header == 0)
355 return -1;
357 memset(info, 0, sizeof(struct mp3info));
358 /* These two are needed for proper LAME gapless MP3 playback */
359 info->enc_delay = -1;
360 info->enc_padding = -1;
361 if(!mp3headerinfo(info, header))
362 return -2;
364 /* OK, we have found a frame. Let's see if it has a Xing header */
365 if (info->frame_size-4 >= (int)sizeof(frame))
367 #if defined(DEBUG) || defined(SIMULATOR)
368 DEBUGF("Error: Invalid id3 header, frame_size: %d\n", info->frame_size);
369 #endif
370 return -8;
373 if(read(fd, frame, info->frame_size-4) < 0)
374 return -3;
376 /* calculate position of VBR header */
377 if ( info->version == MPEG_VERSION1 ) {
378 if (info->channel_mode == 3) /* mono */
379 vbrheader = frame + 17;
380 else
381 vbrheader = frame + 32;
383 else {
384 if (info->channel_mode == 3) /* mono */
385 vbrheader = frame + 9;
386 else
387 vbrheader = frame + 17;
390 if (!memcmp(vbrheader, "Xing", 4)
391 || !memcmp(vbrheader, "Info", 4))
393 int i = 8; /* Where to start parsing info */
395 DEBUGF("Xing/Info header\n");
397 /* Remember where in the file the Xing header is */
398 info->vbr_header_pos = lseek(fd, 0, SEEK_CUR) - info->frame_size;
400 /* We want to skip the Xing frame when playing the stream */
401 bytecount += info->frame_size;
403 /* Now get the next frame to find out the real info about
404 the mp3 stream */
405 header = find_next_frame(fd, &tmp, 0x20000, 0);
406 if(header == 0)
407 return -4;
409 if(!mp3headerinfo(info, header))
410 return -5;
412 /* Is it a VBR file? */
413 info->is_vbr = info->is_xing_vbr = !memcmp(vbrheader, "Xing", 4);
415 if (vbrheader[7] & VBR_FRAMES_FLAG) /* Is the frame count there? */
417 info->frame_count = BYTES2INT(vbrheader[i], vbrheader[i+1],
418 vbrheader[i+2], vbrheader[i+3]);
419 if (info->frame_count <= ULONG_MAX / info->ft_num)
420 info->file_time = info->frame_count * info->ft_num / info->ft_den;
421 else
422 info->file_time = info->frame_count / info->ft_den * info->ft_num;
423 i += 4;
426 if (vbrheader[7] & VBR_BYTES_FLAG) /* Is byte count there? */
428 info->byte_count = BYTES2INT(vbrheader[i], vbrheader[i+1],
429 vbrheader[i+2], vbrheader[i+3]);
430 i += 4;
433 if (info->file_time && info->byte_count)
435 if (info->byte_count <= (ULONG_MAX/8))
436 info->bitrate = info->byte_count * 8 / info->file_time;
437 else
438 info->bitrate = info->byte_count / (info->file_time >> 3);
440 else
441 info->bitrate = 0;
443 if (vbrheader[7] & VBR_TOC_FLAG) /* Is table-of-contents there? */
445 info->has_toc = true;
446 memcpy( info->toc, vbrheader+i, 100 );
447 i += 100;
449 if (vbrheader[7] & VBR_QUALITY_FLAG)
451 /* We don't care about this, but need to skip it */
452 i += 4;
454 i += 21;
455 info->enc_delay = (vbrheader[i] << 4) | (vbrheader[i + 1] >> 4);
456 info->enc_padding = ((vbrheader[i + 1] & 0x0f) << 8) | vbrheader[i + 2];
457 /* TODO: This sanity checking is rather silly, seeing as how the LAME
458 header contains a CRC field that can be used to verify integrity. */
459 if (!(info->enc_delay >= 0 && info->enc_delay <= 2880 &&
460 info->enc_padding >= 0 && info->enc_padding <= 2*1152))
462 /* Invalid data */
463 info->enc_delay = -1;
464 info->enc_padding = -1;
468 if (!memcmp(vbrheader, "VBRI", 4))
470 DEBUGF("VBRI header\n");
472 /* We want to skip the VBRI frame when playing the stream */
473 bytecount += info->frame_size;
475 /* Now get the next frame to find out the real info about
476 the mp3 stream */
477 header = find_next_frame(fd, &tmp, 0x20000, 0);
478 if(header == 0)
479 return -6;
481 bytecount += tmp;
483 if(!mp3headerinfo(info, header))
484 return -7;
486 DEBUGF("%04x: %04x %04x ", 0, header >> 16, header & 0xffff);
487 for(i = 4;i < (int)sizeof(frame)-4;i+=2) {
488 if(i % 16 == 0) {
489 DEBUGF("\n%04x: ", i-4);
491 DEBUGF("%04x ", (frame[i-4] << 8) | frame[i-4+1]);
494 DEBUGF("\n");
496 /* Yes, it is a FhG VBR file */
497 info->is_vbr = true;
498 info->is_vbri_vbr = true;
499 info->has_toc = false; /* We don't parse the TOC (yet) */
501 info->byte_count = BYTES2INT(vbrheader[10], vbrheader[11],
502 vbrheader[12], vbrheader[13]);
503 info->frame_count = BYTES2INT(vbrheader[14], vbrheader[15],
504 vbrheader[16], vbrheader[17]);
505 if (info->frame_count <= ULONG_MAX / info->ft_num)
506 info->file_time = info->frame_count * info->ft_num / info->ft_den;
507 else
508 info->file_time = info->frame_count / info->ft_den * info->ft_num;
510 if (info->byte_count <= (ULONG_MAX/8))
511 info->bitrate = info->byte_count * 8 / info->file_time;
512 else
513 info->bitrate = info->byte_count / (info->file_time >> 3);
515 /* We don't parse the TOC, since we don't yet know how to (FIXME) */
516 num_offsets = BYTES2INT(0, 0, vbrheader[18], vbrheader[19]);
517 frames_per_entry = BYTES2INT(0, 0, vbrheader[24], vbrheader[25]);
518 DEBUGF("Frame size (%dkpbs): %d bytes (0x%x)\n",
519 info->bitrate, info->frame_size, info->frame_size);
520 DEBUGF("Frame count: %x\n", info->frame_count);
521 DEBUGF("Byte count: %x\n", info->byte_count);
522 DEBUGF("Offsets: %d\n", num_offsets);
523 DEBUGF("Frames/entry: %d\n", frames_per_entry);
525 offset = 0;
527 for(i = 0;i < num_offsets;i++)
529 j = BYTES2INT(0, 0, vbrheader[26+i*2], vbrheader[27+i*2]);
530 offset += j;
531 DEBUGF("%03d: %x (%x)\n", i, offset - bytecount, j);
535 return bytecount;
538 static void long2bytes(unsigned char *buf, long val)
540 buf[0] = (val >> 24) & 0xff;
541 buf[1] = (val >> 16) & 0xff;
542 buf[2] = (val >> 8) & 0xff;
543 buf[3] = val & 0xff;
546 int count_mp3_frames(int fd, int startpos, int filesize,
547 void (*progressfunc)(int))
549 unsigned long header = 0;
550 struct mp3info info;
551 int num_frames;
552 long bytes;
553 int cnt;
554 long progress_chunk = filesize / 50; /* Max is 50%, in 1% increments */
555 int progress_cnt = 0;
556 bool is_vbr = false;
557 int last_bitrate = 0;
558 int header_template = 0;
560 if(lseek(fd, startpos, SEEK_SET) < 0)
561 return -1;
563 buf_init();
565 /* Find out the total number of frames */
566 num_frames = 0;
567 cnt = 0;
569 while((header = buf_find_next_frame(fd, &bytes, -1, header_template))) {
570 mp3headerinfo(&info, header);
572 if(!header_template)
573 header_template = header;
575 /* See if this really is a VBR file */
576 if(last_bitrate && info.bitrate != last_bitrate)
578 is_vbr = true;
580 last_bitrate = info.bitrate;
582 buf_seek(fd, info.frame_size-4);
583 num_frames++;
584 if(progressfunc)
586 cnt += bytes + info.frame_size;
587 if(cnt > progress_chunk)
589 progress_cnt++;
590 progressfunc(progress_cnt);
591 cnt = 0;
595 DEBUGF("Total number of frames: %d\n", num_frames);
597 if(is_vbr)
598 return num_frames;
599 else
601 DEBUGF("Not a VBR file\n");
602 return 0;
606 static const char cooltext[] = "Rockbox - rocks your box";
608 /* buf needs to be the audio buffer with TOC generation enabled,
609 and at least MAX_XING_HEADER_SIZE bytes otherwise */
610 int create_xing_header(int fd, long startpos, long filesize,
611 unsigned char *buf, unsigned long num_frames,
612 unsigned long rec_time, unsigned long header_template,
613 void (*progressfunc)(int), bool generate_toc)
615 struct mp3info info;
616 unsigned char toc[100];
617 unsigned long header = 0;
618 unsigned long xing_header_template = header_template;
619 unsigned long filepos;
620 long pos, last_pos;
621 long j;
622 long bytes;
623 int i;
624 int index;
626 DEBUGF("create_xing_header()\n");
628 if(generate_toc)
630 lseek(fd, startpos, SEEK_SET);
631 buf_init();
633 /* Generate filepos table */
634 last_pos = 0;
635 filepos = 0;
636 header = 0;
637 for(i = 0;i < 100;i++) {
638 /* Calculate the absolute frame number for this seek point */
639 pos = i * num_frames / 100;
641 /* Advance from the last seek point to this one */
642 for(j = 0;j < pos - last_pos;j++)
644 header = buf_find_next_frame(fd, &bytes, -1, header_template);
645 filepos += bytes;
646 mp3headerinfo(&info, header);
647 buf_seek(fd, info.frame_size-4);
648 filepos += info.frame_size;
650 if(!header_template)
651 header_template = header;
654 /* Save a header for later use if header_template is empty.
655 We only save one header, and we want to save one in the
656 middle of the stream, just in case the first and the last
657 headers are corrupt. */
658 if(!xing_header_template && i == 1)
659 xing_header_template = header;
661 if(progressfunc)
663 progressfunc(50 + i/2);
666 /* Fill in the TOC entry */
667 /* each toc is a single byte indicating how many 256ths of the
668 * way through the file, is that percent of the way through the
669 * song. the easy method, filepos*256/filesize, chokes when
670 * the upper 8 bits of the file position are nonzero
671 * (i.e. files over 16mb in size).
673 if (filepos > (ULONG_MAX/256))
675 /* instead of multiplying filepos by 256, we divide
676 * filesize by 256.
678 toc[i] = filepos / (filesize >> 8);
680 else
682 toc[i] = filepos * 256 / filesize;
685 DEBUGF("Pos %d: %d relpos: %d filepos: %x tocentry: %x\n",
686 i, pos, pos-last_pos, filepos, toc[i]);
688 last_pos = pos;
692 /* Use the template header and create a new one.
693 We ignore the Protection bit even if the rest of the stream is
694 protected. */
695 header = xing_header_template & ~(BITRATE_MASK|PROTECTION_MASK|PADDING_MASK);
696 header |= 8 << 12; /* This gives us plenty of space, 192..576 bytes */
698 if (!mp3headerinfo(&info, header))
699 return 0; /* invalid header */
701 if (num_frames == 0 && rec_time) {
702 /* estimate the number of frames based on the recording time */
703 if (rec_time <= ULONG_MAX / info.ft_den)
704 num_frames = rec_time * info.ft_den / info.ft_num;
705 else
706 num_frames = rec_time / info.ft_num * info.ft_den;
709 /* Clear the frame */
710 memset(buf, 0, MAX_XING_HEADER_SIZE);
712 /* Write the header to the buffer */
713 long2bytes(buf, header);
715 /* Calculate position of VBR header */
716 if (info.version == MPEG_VERSION1) {
717 if (info.channel_mode == 3) /* mono */
718 index = 21;
719 else
720 index = 36;
722 else {
723 if (info.channel_mode == 3) /* mono */
724 index = 13;
725 else
726 index = 21;
729 /* Create the Xing data */
730 memcpy(&buf[index], "Xing", 4);
731 long2bytes(&buf[index+4], (num_frames ? VBR_FRAMES_FLAG : 0)
732 | (filesize ? VBR_BYTES_FLAG : 0)
733 | (generate_toc ? VBR_TOC_FLAG : 0));
734 index += 8;
735 if(num_frames)
737 long2bytes(&buf[index], num_frames);
738 index += 4;
741 if(filesize)
743 long2bytes(&buf[index], filesize - startpos);
744 index += 4;
747 /* Copy the TOC */
748 memcpy(buf + index, toc, 100);
750 /* And some extra cool info */
751 memcpy(buf + index + 100, cooltext, sizeof(cooltext));
753 #ifdef DEBUG
754 for(i = 0;i < info.frame_size;i++)
756 if(i && !(i % 16))
757 DEBUGF("\n");
759 DEBUGF("%02x ", buf[i]);
761 #endif
763 return info.frame_size;