Change i2c config on e200. Seems to speed things up somewhat.
[kugel-rb.git] / apps / metadata.c
blob54bb40413e7c39fbc066842ad0cbee92c5cfe6c6
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 ****************************************************************************/
19 #include <stdio.h>
20 #include <string.h>
21 #include <stdlib.h>
22 #include <ctype.h>
23 #include <inttypes.h>
25 #include "errno.h"
26 #include "metadata.h"
27 #include "mp3_playback.h"
28 #include "logf.h"
29 #include "rbunicode.h"
30 #include "atoi.h"
31 #include "replaygain.h"
32 #include "debug.h"
33 #include "system.h"
34 #include "cuesheet.h"
35 #include "structec.h"
37 enum tagtype { TAGTYPE_APE = 1, TAGTYPE_VORBIS };
39 #ifdef ROCKBOX_BIG_ENDIAN
40 #define IS_BIG_ENDIAN 1
41 #else
42 #define IS_BIG_ENDIAN 0
43 #endif
45 #define APETAG_HEADER_LENGTH 32
46 #define APETAG_HEADER_FORMAT "8llll8"
47 #define APETAG_ITEM_HEADER_FORMAT "ll"
48 #define APETAG_ITEM_TYPE_MASK 3
50 #define TAG_NAME_LENGTH 32
51 #define TAG_VALUE_LENGTH 128
53 #define MP4_ID(a, b, c, d) (((a) << 24) | ((b) << 16) | ((c) << 8) | (d))
55 #define MP4_3gp6 MP4_ID('3', 'g', 'p', '6')
56 #define MP4_alac MP4_ID('a', 'l', 'a', 'c')
57 #define MP4_calb MP4_ID(0xa9, 'a', 'l', 'b')
58 #define MP4_cART MP4_ID(0xa9, 'A', 'R', 'T')
59 #define MP4_cnam MP4_ID(0xa9, 'n', 'a', 'm')
60 #define MP4_cwrt MP4_ID(0xa9, 'w', 'r', 't')
61 #define MP4_esds MP4_ID('e', 's', 'd', 's')
62 #define MP4_ftyp MP4_ID('f', 't', 'y', 'p')
63 #define MP4_gnre MP4_ID('g', 'n', 'r', 'e')
64 #define MP4_hdlr MP4_ID('h', 'd', 'l', 'r')
65 #define MP4_ilst MP4_ID('i', 'l', 's', 't')
66 #define MP4_M4A MP4_ID('M', '4', 'A', ' ')
67 #define MP4_M4B MP4_ID('M', '4', 'B', ' ')
68 #define MP4_mdat MP4_ID('m', 'd', 'a', 't')
69 #define MP4_mdia MP4_ID('m', 'd', 'i', 'a')
70 #define MP4_mdir MP4_ID('m', 'd', 'i', 'r')
71 #define MP4_meta MP4_ID('m', 'e', 't', 'a')
72 #define MP4_minf MP4_ID('m', 'i', 'n', 'f')
73 #define MP4_moov MP4_ID('m', 'o', 'o', 'v')
74 #define MP4_mp4a MP4_ID('m', 'p', '4', 'a')
75 #define MP4_mp42 MP4_ID('m', 'p', '4', '2')
76 #define MP4_qt MP4_ID('q', 't', ' ', ' ')
77 #define MP4_soun MP4_ID('s', 'o', 'u', 'n')
78 #define MP4_stbl MP4_ID('s', 't', 'b', 'l')
79 #define MP4_stsd MP4_ID('s', 't', 's', 'd')
80 #define MP4_stts MP4_ID('s', 't', 't', 's')
81 #define MP4_trak MP4_ID('t', 'r', 'a', 'k')
82 #define MP4_trkn MP4_ID('t', 'r', 'k', 'n')
83 #define MP4_udta MP4_ID('u', 'd', 't', 'a')
84 #define MP4_extra MP4_ID('-', '-', '-', '-')
86 struct apetag_header
88 char id[8];
89 long version;
90 long length;
91 long item_count;
92 long flags;
93 char reserved[8];
96 struct apetag_item_header
98 long length;
99 long flags;
102 #if CONFIG_CODEC == SWCODEC
103 static const unsigned short a52_bitrates[] =
105 32, 40, 48, 56, 64, 80, 96, 112, 128, 160,
106 192, 224, 256, 320, 384, 448, 512, 576, 640
109 /* Only store frame sizes for 44.1KHz - others are simply multiples
110 of the bitrate */
111 static const unsigned short a52_441framesizes[] =
113 69 * 2, 70 * 2, 87 * 2, 88 * 2, 104 * 2, 105 * 2, 121 * 2,
114 122 * 2, 139 * 2, 140 * 2, 174 * 2, 175 * 2, 208 * 2, 209 * 2,
115 243 * 2, 244 * 2, 278 * 2, 279 * 2, 348 * 2, 349 * 2, 417 * 2,
116 418 * 2, 487 * 2, 488 * 2, 557 * 2, 558 * 2, 696 * 2, 697 * 2,
117 835 * 2, 836 * 2, 975 * 2, 976 * 2, 1114 * 2, 1115 * 2, 1253 * 2,
118 1254 * 2, 1393 * 2, 1394 * 2
121 static const long wavpack_sample_rates [] =
123 6000, 8000, 9600, 11025, 12000, 16000, 22050, 24000,
124 32000, 44100, 48000, 64000, 88200, 96000, 192000
127 /* Read a string from the file. Read up to size bytes, or, if eos != -1,
128 * until the eos character is found (eos is not stored in buf, unless it is
129 * nil). Writes up to buf_size chars to buf, always terminating with a nil.
130 * Returns number of chars read or -1 on read error.
132 static long read_string(int fd, char* buf, long buf_size, int eos, long size)
134 long read_bytes = 0;
135 char c;
137 while (size != 0)
139 if (read(fd, &c, 1) != 1)
141 read_bytes = -1;
142 break;
145 read_bytes++;
146 size--;
148 if ((eos != -1) && (eos == (unsigned char) c))
150 break;
153 if (buf_size > 1)
155 *buf++ = c;
156 buf_size--;
160 *buf = 0;
161 return read_bytes;
164 /* Read an unsigned 32-bit integer from a big-endian file. */
165 #ifdef ROCKBOX_BIG_ENDIAN
166 #define read_uint32be(fd,buf) read((fd), (buf), 4)
167 #else
168 static int read_uint32be(int fd, unsigned int* buf)
170 size_t n;
172 n = read(fd, (char*) buf, 4);
173 *buf = betoh32(*buf);
174 return n;
176 #endif
178 /* Read an unaligned 32-bit little endian long from buffer. */
179 static unsigned long get_long_le(void* buf)
181 unsigned char* p = (unsigned char*) buf;
183 return p[0] | (p[1] << 8) | (p[2] << 16) | (p[3] << 24);
186 /* Read an unaligned 32-bit big endian long from buffer. */
187 static unsigned long get_long_be(void* buf)
189 unsigned char* p = (unsigned char*) buf;
191 return (p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3];
194 /* Read an unaligned 32-bit little endian long from buffer. */
195 static long get_slong(void* buf)
197 unsigned char* p = (unsigned char*) buf;
199 return p[0] | (p[1] << 8) | (p[2] << 16) | (p[3] << 24);
202 /* Parse the tag (the name-value pair) and fill id3 and buffer accordingly.
203 * String values to keep are written to buf. Returns number of bytes written
204 * to buf (including end nil).
206 static long parse_tag(const char* name, char* value, struct mp3entry* id3,
207 char* buf, long buf_remaining, enum tagtype type)
209 long len = 0;
210 char** p;
212 if ((((strcasecmp(name, "track") == 0) && (type == TAGTYPE_APE)))
213 || ((strcasecmp(name, "tracknumber") == 0) && (type == TAGTYPE_VORBIS)))
215 id3->tracknum = atoi(value);
216 p = &(id3->track_string);
218 else if (((strcasecmp(name, "year") == 0) && (type == TAGTYPE_APE))
219 || ((strcasecmp(name, "date") == 0) && (type == TAGTYPE_VORBIS)))
221 /* Date's can be in any format in Vorbis. However most of them
222 * are in ISO8601 format so if we try and parse the first part
223 * of the tag as a number, we should get the year. If we get crap,
224 * then act like we never parsed it.
226 id3->year = atoi(value);
227 if (id3->year < 1900)
228 { /* yeah, not likely */
229 id3->year = 0;
231 p = &(id3->year_string);
233 else if (strcasecmp(name, "title") == 0)
235 p = &(id3->title);
237 else if (strcasecmp(name, "artist") == 0)
239 p = &(id3->artist);
241 else if (strcasecmp(name, "album") == 0)
243 p = &(id3->album);
245 else if (strcasecmp(name, "genre") == 0)
247 p = &(id3->genre_string);
249 else if (strcasecmp(name, "composer") == 0)
251 p = &(id3->composer);
253 else if (strcasecmp(name, "comment") == 0)
255 p = &(id3->comment);
257 else if (strcasecmp(name, "albumartist") == 0)
259 p = &(id3->albumartist);
261 else if (strcasecmp(name, "album artist") == 0)
263 p = &(id3->albumartist);
265 else if (strcasecmp(name, "ensemble") == 0)
267 p = &(id3->albumartist);
269 else
271 len = parse_replaygain(name, value, id3, buf, buf_remaining);
272 p = NULL;
275 if (p)
277 len = strlen(value);
278 len = MIN(len, buf_remaining - 1);
280 if (len > 0)
282 strncpy(buf, value, len);
283 buf[len] = 0;
284 *p = buf;
285 len++;
287 else
289 len = 0;
293 return len;
296 /* Read the items in an APEV2 tag. Only looks for a tag at the end of a
297 * file. Returns true if a tag was found and fully read, false otherwise.
299 static bool read_ape_tags(int fd, struct mp3entry* id3)
301 struct apetag_header header;
303 if ((lseek(fd, -APETAG_HEADER_LENGTH, SEEK_END) < 0)
304 || (ecread(fd, &header, 1, APETAG_HEADER_FORMAT, IS_BIG_ENDIAN) != APETAG_HEADER_LENGTH)
305 || (memcmp(header.id, "APETAGEX", sizeof(header.id))))
307 return false;
310 if ((header.version == 2000) && (header.item_count > 0)
311 && (header.length > APETAG_HEADER_LENGTH))
313 char *buf = id3->id3v2buf;
314 unsigned int buf_remaining = sizeof(id3->id3v2buf)
315 + sizeof(id3->id3v1buf);
316 unsigned int tag_remaining = header.length - APETAG_HEADER_LENGTH;
317 int i;
319 if (lseek(fd, -header.length, SEEK_END) < 0)
321 return false;
324 for (i = 0; i < header.item_count; i++)
326 struct apetag_item_header item;
327 char name[TAG_NAME_LENGTH];
328 char value[TAG_VALUE_LENGTH];
329 long r;
331 if (tag_remaining < sizeof(item))
333 break;
336 if (ecread(fd, &item, 1, APETAG_ITEM_HEADER_FORMAT, IS_BIG_ENDIAN) < (long) sizeof(item))
338 return false;
341 tag_remaining -= sizeof(item);
342 r = read_string(fd, name, sizeof(name), 0, tag_remaining);
344 if (r == -1)
346 return false;
349 tag_remaining -= r + item.length;
351 if ((item.flags & APETAG_ITEM_TYPE_MASK) == 0)
353 long len;
355 if (read_string(fd, value, sizeof(value), -1, item.length)
356 != item.length)
358 return false;
361 len = parse_tag(name, value, id3, buf, buf_remaining,
362 TAGTYPE_APE);
363 buf += len;
364 buf_remaining -= len;
366 else
368 if (lseek(fd, item.length, SEEK_CUR) < 0)
370 return false;
376 return true;
379 /* Read the items in a Vorbis comment packet. Returns true the items were
380 * fully read, false otherwise.
382 static bool read_vorbis_tags(int fd, struct mp3entry *id3,
383 long tag_remaining)
385 char *buf = id3->id3v2buf;
386 int32_t comment_count;
387 int32_t len;
388 int buf_remaining = sizeof(id3->id3v2buf) + sizeof(id3->id3v1buf);
389 int i;
391 if (ecread(fd, &len, 1, "l", IS_BIG_ENDIAN) < (long) sizeof(len))
393 return false;
396 if ((lseek(fd, len, SEEK_CUR) < 0)
397 || (ecread(fd, &comment_count, 1, "l", IS_BIG_ENDIAN)
398 < (long) sizeof(comment_count)))
400 return false;
403 tag_remaining -= len + sizeof(len) + sizeof(comment_count);
405 if (tag_remaining <= 0)
407 return true;
410 for (i = 0; i < comment_count; i++)
412 char name[TAG_NAME_LENGTH];
413 char value[TAG_VALUE_LENGTH];
414 int32_t read_len;
416 if (tag_remaining < 4)
418 break;
421 if (ecread(fd, &len, 1, "l", IS_BIG_ENDIAN) < (long) sizeof(len))
423 return false;
426 tag_remaining -= 4;
428 /* Quit if we've passed the end of the page */
429 if (tag_remaining < len)
431 break;
434 tag_remaining -= len;
435 read_len = read_string(fd, name, sizeof(name), '=', len);
437 if (read_len < 0)
439 return false;
442 len -= read_len;
444 if (read_string(fd, value, sizeof(value), -1, len) < 0)
446 return false;
449 len = parse_tag(name, value, id3, buf, buf_remaining,
450 TAGTYPE_VORBIS);
451 buf += len;
452 buf_remaining -= len;
455 /* Skip to the end of the block */
456 if (tag_remaining)
458 if (lseek(fd, tag_remaining, SEEK_CUR) < 0)
460 return false;
464 return true;
467 /* Skip an ID3v2 tag if it can be found. We assume the tag is located at the
468 * start of the file, which should be true in all cases where we need to skip it.
469 * Returns true if successfully skipped or not skipped, and false if
470 * something went wrong while skipping.
472 static bool skip_id3v2(int fd, struct mp3entry *id3)
474 char buf[4];
476 read(fd, buf, 4);
477 if (memcmp(buf, "ID3", 3) == 0)
479 /* We have found an ID3v2 tag at the start of the file - find its
480 length and then skip it. */
481 if ((id3->first_frame_offset = getid3v2len(fd)) == 0)
482 return false;
484 if ((lseek(fd, id3->first_frame_offset, SEEK_SET) < 0))
485 return false;
487 return true;
488 } else {
489 lseek(fd, 0, SEEK_SET);
490 id3->first_frame_offset = 0;
491 return true;
495 /* A simple parser to read vital metadata from an Ogg Speex file. Returns
496 * false if metadata needed by the Speex codec couldn't be read.
499 static bool get_speex_metadata(int fd, struct mp3entry* id3)
501 /* An Ogg File is split into pages, each starting with the string
502 * "OggS". Each page has a timestamp (in PCM samples) referred to as
503 * the "granule position".
505 * An Ogg Speex has the following structure:
506 * 1) Identification header (containing samplerate, numchannels, etc)
507 Described in this page: (http://www.speex.org/manual2/node7.html)
508 * 2) Comment header - containing the Vorbis Comments
509 * 3) Many audio packets...
512 /* Use the path name of the id3 structure as a temporary buffer. */
513 unsigned char* buf = (unsigned char*)id3->path;
514 long comment_size;
515 long remaining = 0;
516 long last_serial = 0;
517 long serial, r;
518 int segments;
519 int i;
520 bool eof = false;
522 if ((lseek(fd, 0, SEEK_SET) < 0) || (read(fd, buf, 58) < 33))
524 return false;
527 if ((memcmp(buf, "OggS", 4) != 0) || (memcmp(&buf[28], "Speex", 5) != 0))
529 return false;
532 /* We need to ensure the serial number from this page is the same as the
533 * one from the last page (since we only support a single bitstream).
535 serial = get_long_le(&buf[14]);
536 if ((lseek(fd, 33, SEEK_SET) < 0)||(read(fd, buf, 58) < 4))
538 return false;
541 id3->frequency = get_slong(&buf[31]);
542 last_serial = get_long_le(&buf[27]);/*temporary, header size*/
543 id3->bitrate = get_long_le(&buf[47]);
544 id3->vbr = get_long_le(&buf[55]);
545 id3->filesize = filesize(fd);
546 /* Comments are in second Ogg page */
547 if (lseek(fd, 28+last_serial/*(temporary for header size)*/, SEEK_SET) < 0)
549 return false;
552 /* Minimum header length for Ogg pages is 27. */
553 if (read(fd, buf, 27) < 27)
555 return false;
558 if (memcmp(buf, "OggS", 4) !=0 )
560 return false;
563 segments = buf[26];
564 /* read in segment table */
565 if (read(fd, buf, segments) < segments)
567 return false;
570 /* The second packet in a vorbis stream is the comment packet. It *may*
571 * extend beyond the second page, but usually does not. Here we find the
572 * length of the comment packet (or the rest of the page if the comment
573 * packet extends to the third page).
575 for (i = 0; i < segments; i++)
577 remaining += buf[i];
578 /* The last segment of a packet is always < 255 bytes */
579 if (buf[i] < 255)
581 break;
585 comment_size = remaining;
587 /* Failure to read the tags isn't fatal. */
588 read_vorbis_tags(fd, id3, remaining);
590 /* We now need to search for the last page in the file - identified by
591 * by ('O','g','g','S',0) and retrieve totalsamples.
594 /* A page is always < 64 kB */
595 if (lseek(fd, -(MIN(64 * 1024, id3->filesize)), SEEK_END) < 0)
597 return false;
600 remaining = 0;
602 while (!eof)
604 r = read(fd, &buf[remaining], MAX_PATH - remaining);
606 if (r <= 0)
608 eof = true;
610 else
612 remaining += r;
615 /* Inefficient (but simple) search */
616 i = 0;
618 while (i < (remaining - 3))
620 if ((buf[i] == 'O') && (memcmp(&buf[i], "OggS", 4) == 0))
622 if (i < (remaining - 17))
624 /* Note that this only reads the low 32 bits of a
625 * 64 bit value.
627 id3->samples = get_long_le(&buf[i + 6]);
628 last_serial = get_long_le(&buf[i + 14]);
630 /* If this page is very small the beginning of the next
631 * header could be in buffer. Jump near end of this header
632 * and continue */
633 i += 27;
635 else
637 break;
640 else
642 i++;
646 if (i < remaining)
648 /* Move the remaining bytes to start of buffer.
649 * Reuse var 'segments' as it is no longer needed */
650 segments = 0;
651 while (i < remaining)
653 buf[segments++] = buf[i++];
655 remaining = segments;
657 else
659 /* Discard the rest of the buffer */
660 remaining = 0;
664 /* This file has mutiple vorbis bitstreams (or is corrupt). */
665 /* FIXME we should display an error here. */
666 if (serial != last_serial)
668 logf("serialno mismatch");
669 logf("%ld", serial);
670 logf("%ld", last_serial);
671 return false;
674 id3->length = (id3->samples / id3->frequency) * 1000;
675 id3->bitrate = (((int64_t) id3->filesize - comment_size) * 8) / id3->length;
676 return true;
680 /* A simple parser to read vital metadata from an Ogg Vorbis file.
681 * Calls get_speex_metadata if a speex file is identified. Returns
682 * false if metadata needed by the Vorbis codec couldn't be read.
684 static bool get_vorbis_metadata(int fd, struct mp3entry* id3)
686 /* An Ogg File is split into pages, each starting with the string
687 * "OggS". Each page has a timestamp (in PCM samples) referred to as
688 * the "granule position".
690 * An Ogg Vorbis has the following structure:
691 * 1) Identification header (containing samplerate, numchannels, etc)
692 * 2) Comment header - containing the Vorbis Comments
693 * 3) Setup header - containing codec setup information
694 * 4) Many audio packets...
697 /* Use the path name of the id3 structure as a temporary buffer. */
698 unsigned char* buf = (unsigned char *)id3->path;
699 long comment_size;
700 long remaining = 0;
701 long last_serial = 0;
702 long serial, r;
703 int segments;
704 int i;
705 bool eof = false;
707 if ((lseek(fd, 0, SEEK_SET) < 0) || (read(fd, buf, 58) < 4))
709 return false;
712 if ((memcmp(buf, "OggS", 4) != 0) || (memcmp(&buf[29], "vorbis", 6) != 0))
714 if ((memcmp(buf, "OggS", 4) != 0) || (memcmp(&buf[28], "Speex", 5) != 0))
716 return false;
718 else
720 id3->codectype = AFMT_SPEEX;
721 return get_speex_metadata(fd, id3);
725 /* We need to ensure the serial number from this page is the same as the
726 * one from the last page (since we only support a single bitstream).
728 serial = get_long_le(&buf[14]);
729 id3->frequency = get_long_le(&buf[40]);
730 id3->filesize = filesize(fd);
732 /* Comments are in second Ogg page */
733 if (lseek(fd, 58, SEEK_SET) < 0)
735 return false;
738 /* Minimum header length for Ogg pages is 27. */
739 if (read(fd, buf, 27) < 27)
741 return false;
744 if (memcmp(buf, "OggS", 4) !=0 )
746 return false;
749 segments = buf[26];
751 /* read in segment table */
752 if (read(fd, buf, segments) < segments)
754 return false;
757 /* The second packet in a vorbis stream is the comment packet. It *may*
758 * extend beyond the second page, but usually does not. Here we find the
759 * length of the comment packet (or the rest of the page if the comment
760 * packet extends to the third page).
762 for (i = 0; i < segments; i++)
764 remaining += buf[i];
766 /* The last segment of a packet is always < 255 bytes */
767 if (buf[i] < 255)
769 break;
773 /* Now read in packet header (type and id string) */
774 if (read(fd, buf, 7) < 7)
776 return false;
779 comment_size = remaining;
780 remaining -= 7;
782 /* The first byte of a packet is the packet type; comment packets are
783 * type 3.
785 if ((buf[0] != 3) || (memcmp(buf + 1, "vorbis", 6) !=0))
787 return false;
790 /* Failure to read the tags isn't fatal. */
791 read_vorbis_tags(fd, id3, remaining);
793 /* We now need to search for the last page in the file - identified by
794 * by ('O','g','g','S',0) and retrieve totalsamples.
797 /* A page is always < 64 kB */
798 if (lseek(fd, -(MIN(64 * 1024, id3->filesize)), SEEK_END) < 0)
800 return false;
803 remaining = 0;
805 while (!eof)
807 r = read(fd, &buf[remaining], MAX_PATH - remaining);
809 if (r <= 0)
811 eof = true;
813 else
815 remaining += r;
818 /* Inefficient (but simple) search */
819 i = 0;
821 while (i < (remaining - 3))
823 if ((buf[i] == 'O') && (memcmp(&buf[i], "OggS", 4) == 0))
825 if (i < (remaining - 17))
827 /* Note that this only reads the low 32 bits of a
828 * 64 bit value.
830 id3->samples = get_long_le(&buf[i + 6]);
831 last_serial = get_long_le(&buf[i + 14]);
833 /* If this page is very small the beginning of the next
834 * header could be in buffer. Jump near end of this header
835 * and continue */
836 i += 27;
838 else
840 break;
843 else
845 i++;
849 if (i < remaining)
851 /* Move the remaining bytes to start of buffer.
852 * Reuse var 'segments' as it is no longer needed */
853 segments = 0;
854 while (i < remaining)
856 buf[segments++] = buf[i++];
858 remaining = segments;
860 else
862 /* Discard the rest of the buffer */
863 remaining = 0;
867 /* This file has mutiple vorbis bitstreams (or is corrupt). */
868 /* FIXME we should display an error here. */
869 if (serial != last_serial)
871 logf("serialno mismatch");
872 logf("%ld", serial);
873 logf("%ld", last_serial);
874 return false;
877 id3->length = ((int64_t) id3->samples * 1000) / id3->frequency;
879 if (id3->length <= 0)
881 logf("ogg length invalid!");
882 return false;
885 id3->bitrate = (((int64_t) id3->filesize - comment_size) * 8) / id3->length;
886 id3->vbr = true;
888 return true;
891 static bool get_flac_metadata(int fd, struct mp3entry* id3)
893 /* A simple parser to read vital metadata from a FLAC file - length,
894 * frequency, bitrate etc. This code should either be moved to a
895 * seperate file, or discarded in favour of the libFLAC code.
896 * The FLAC stream specification can be found at
897 * http://flac.sourceforge.net/format.html#stream
900 /* Use the trackname part of the id3 structure as a temporary buffer */
901 unsigned char* buf = (unsigned char *)id3->path;
902 bool rc = false;
904 if (!skip_id3v2(fd, id3) || (read(fd, buf, 4) < 4))
906 return rc;
909 if (memcmp(buf, "fLaC", 4) != 0)
911 return rc;
914 while (true)
916 long i;
918 if (read(fd, buf, 4) < 0)
920 return rc;
923 /* The length of the block */
924 i = (buf[1] << 16) | (buf[2] << 8) | buf[3];
926 if ((buf[0] & 0x7f) == 0) /* 0 is the STREAMINFO block */
928 unsigned long totalsamples;
930 /* FIXME: Don't trust the value of i */
931 if (read(fd, buf, i) < 0)
933 return rc;
936 id3->vbr = true; /* All FLAC files are VBR */
937 id3->filesize = filesize(fd);
938 id3->frequency = (buf[10] << 12) | (buf[11] << 4)
939 | ((buf[12] & 0xf0) >> 4);
940 rc = true; /* Got vital metadata */
942 /* totalsamples is a 36-bit field, but we assume <= 32 bits are used */
943 totalsamples = get_long_be(&buf[14]);
945 /* Calculate track length (in ms) and estimate the bitrate (in kbit/s) */
946 id3->length = ((int64_t) totalsamples * 1000) / id3->frequency;
948 if (id3->length <= 0)
950 logf("flac length invalid!");
951 return false;
954 id3->bitrate = (id3->filesize * 8) / id3->length;
956 else if ((buf[0] & 0x7f) == 4) /* 4 is the VORBIS_COMMENT block */
958 /* The next i bytes of the file contain the VORBIS COMMENTS. */
959 if (!read_vorbis_tags(fd, id3, i))
961 return rc;
964 else
966 if (buf[0] & 0x80)
968 /* If we have reached the last metadata block, abort. */
969 break;
971 else
973 /* Skip to next metadata block */
974 if (lseek(fd, i, SEEK_CUR) < 0)
976 return rc;
982 return true;
985 static bool get_wave_metadata(int fd, struct mp3entry* id3)
987 /* Use the trackname part of the id3 structure as a temporary buffer */
988 unsigned char* buf = (unsigned char *)id3->path;
989 unsigned long totalsamples = 0;
990 unsigned long channels = 0;
991 unsigned long bitspersample = 0;
992 unsigned long numbytes = 0;
993 int read_bytes;
994 int i;
996 /* get RIFF chunk header */
997 if ((lseek(fd, 0, SEEK_SET) < 0)
998 || ((read_bytes = read(fd, buf, 12)) < 12))
1000 return false;
1003 if ((memcmp(buf, "RIFF",4) != 0)
1004 || (memcmp(&buf[8], "WAVE", 4) !=0 ))
1006 return false;
1009 /* iterate over WAVE chunks until 'data' chunk */
1010 while (true)
1012 /* get chunk header */
1013 if ((read_bytes = read(fd, buf, 8)) < 8)
1014 return false;
1016 /* chunkSize */
1017 i = get_long_le(&buf[4]);
1019 if (memcmp(buf, "fmt ", 4) == 0)
1021 /* get rest of chunk */
1022 if ((read_bytes = read(fd, buf, 16)) < 16)
1023 return false;
1025 i -= 16;
1027 /* skipping wFormatTag */
1028 /* wChannels */
1029 channels = buf[2] | (buf[3] << 8);
1030 /* dwSamplesPerSec */
1031 id3->frequency = get_long_le(&buf[4]);
1032 /* dwAvgBytesPerSec */
1033 id3->bitrate = (get_long_le(&buf[8]) * 8) / 1000;
1034 /* skipping wBlockAlign */
1035 /* wBitsPerSample */
1036 bitspersample = buf[14] | (buf[15] << 8);
1038 else if (memcmp(buf, "data", 4) == 0)
1040 numbytes = i;
1041 break;
1043 else if (memcmp(buf, "fact", 4) == 0)
1045 /* dwSampleLength */
1046 if (i >= 4)
1048 /* get rest of chunk */
1049 if ((read_bytes = read(fd, buf, 2)) < 2)
1050 return false;
1052 i -= 2;
1053 totalsamples = get_long_le(buf);
1057 /* seek to next chunk (even chunk sizes must be padded) */
1058 if (i & 0x01)
1059 i++;
1061 if(lseek(fd, i, SEEK_CUR) < 0)
1062 return false;
1065 if ((numbytes == 0) || (channels == 0))
1067 return false;
1070 if (totalsamples == 0)
1072 /* for PCM only */
1073 totalsamples = numbytes
1074 / ((((bitspersample - 1) / 8) + 1) * channels);
1077 id3->vbr = false; /* All WAV files are CBR */
1078 id3->filesize = filesize(fd);
1080 /* Calculate track length (in ms) and estimate the bitrate (in kbit/s) */
1081 id3->length = ((int64_t) totalsamples * 1000) / id3->frequency;
1083 return true;
1086 /* Read the tag data from an MP4 file, storing up to buffer_size bytes in
1087 * buffer.
1089 static unsigned long read_mp4_tag(int fd, unsigned int size_left, char* buffer,
1090 unsigned int buffer_left)
1092 unsigned int bytes_read = 0;
1094 if (buffer_left == 0)
1096 lseek(fd, size_left, SEEK_CUR); /* Skip everything */
1098 else
1100 /* Skip the data tag header - maybe we should parse it properly? */
1101 lseek(fd, 16, SEEK_CUR);
1102 size_left -= 16;
1104 if (size_left > buffer_left)
1106 read(fd, buffer, buffer_left);
1107 lseek(fd, size_left - buffer_left, SEEK_CUR);
1108 bytes_read = buffer_left;
1110 else
1112 read(fd, buffer, size_left);
1113 bytes_read = size_left;
1117 return bytes_read;
1120 /* Read a string tag from an MP4 file */
1121 static unsigned int read_mp4_tag_string(int fd, int size_left, char** buffer,
1122 unsigned int* buffer_left, char** dest)
1124 unsigned int bytes_read = read_mp4_tag(fd, size_left, *buffer,
1125 *buffer_left - 1);
1126 unsigned int length = 0;
1128 if (bytes_read)
1130 (*buffer)[bytes_read] = 0;
1131 *dest = *buffer;
1132 length = strlen(*buffer) + 1;
1133 *buffer_left -= length;
1134 *buffer += length;
1136 else
1138 *dest = NULL;
1141 return length;
1144 static unsigned int read_mp4_atom(int fd, unsigned int* size,
1145 unsigned int* type, unsigned int size_left)
1147 read_uint32be(fd, size);
1148 read_uint32be(fd, type);
1150 if (*size == 1)
1152 /* FAT32 doesn't support files this big, so something seems to
1153 * be wrong. (64-bit sizes should only be used when required.)
1155 errno = EFBIG;
1156 *type = 0;
1157 return 0;
1160 if (*size > 0)
1162 if (*size > size_left)
1164 size_left = 0;
1166 else
1168 size_left -= *size;
1171 *size -= 8;
1173 else
1175 *size = size_left;
1176 size_left = 0;
1179 return size_left;
1182 static unsigned int read_mp4_length(int fd, unsigned int* size)
1184 unsigned int length = 0;
1185 int bytes = 0;
1186 unsigned char c;
1190 read(fd, &c, 1);
1191 bytes++;
1192 (*size)--;
1193 length = (length << 7) | (c & 0x7F);
1195 while ((c & 0x80) && (bytes < 4) && (*size > 0));
1197 return length;
1200 static bool read_mp4_esds(int fd, struct mp3entry* id3,
1201 unsigned int* size)
1203 unsigned char buf[8];
1204 bool sbr = false;
1206 lseek(fd, 4, SEEK_CUR); /* Version and flags. */
1207 read(fd, buf, 1); /* Verify ES_DescrTag. */
1208 *size -= 5;
1210 if (*buf == 3)
1212 /* read length */
1213 if (read_mp4_length(fd, size) < 20)
1215 return sbr;
1218 lseek(fd, 3, SEEK_CUR);
1219 *size -= 3;
1221 else
1223 lseek(fd, 2, SEEK_CUR);
1224 *size -= 2;
1227 read(fd, buf, 1); /* Verify DecoderConfigDescrTab. */
1228 *size -= 1;
1230 if (*buf != 4)
1232 return sbr;
1235 if (read_mp4_length(fd, size) < 13)
1237 return sbr;
1240 lseek(fd, 13, SEEK_CUR); /* Skip audio type, bit rates, etc. */
1241 read(fd, buf, 1);
1242 *size -= 14;
1244 if (*buf != 5) /* Verify DecSpecificInfoTag. */
1246 return sbr;
1250 static const int sample_rates[] =
1252 96000, 88200, 64000, 48000, 44100, 32000,
1253 24000, 22050, 16000, 12000, 11025, 8000
1255 unsigned long bits;
1256 unsigned int length;
1257 unsigned int index;
1258 unsigned int type;
1260 /* Read the (leading part of the) decoder config. */
1261 length = read_mp4_length(fd, size);
1262 length = MIN(length, *size);
1263 length = MIN(length, sizeof(buf));
1264 memset(buf, 0, sizeof(buf));
1265 read(fd, buf, length);
1266 *size -= length;
1268 /* Maybe time to write a simple read_bits function... */
1270 /* Decoder config format:
1271 * Object type - 5 bits
1272 * Frequency index - 4 bits
1273 * Channel configuration - 4 bits
1275 bits = get_long_be(buf);
1276 type = bits >> 27; /* Object type - 5 bits */
1277 index = (bits >> 23) & 0xf; /* Frequency index - 4 bits */
1279 if (index < (sizeof(sample_rates) / sizeof(*sample_rates)))
1281 id3->frequency = sample_rates[index];
1284 if (type == 5)
1286 DEBUGF("MP4: SBR\n");
1287 unsigned int old_index = index;
1289 sbr = true;
1290 index = (bits >> 15) & 0xf; /* Frequency index - 4 bits */
1292 if (index == 15)
1294 /* 17 bits read so far... */
1295 bits = get_long_be(&buf[2]);
1296 id3->frequency = (bits >> 7) & 0x00ffffff;
1298 else if (index < (sizeof(sample_rates) / sizeof(*sample_rates)))
1300 id3->frequency = sample_rates[index];
1303 if (old_index == index)
1305 /* Downsampled SBR */
1306 id3->frequency *= 2;
1309 /* Skip 13 bits from above, plus 3 bits, then read 11 bits */
1310 else if ((length >= 4) && (((bits >> 5) & 0x7ff) == 0x2b7))
1312 /* extensionAudioObjectType */
1313 DEBUGF("MP4: extensionAudioType\n");
1314 type = bits & 0x1f; /* Object type - 5 bits*/
1315 bits = get_long_be(&buf[4]);
1317 if (type == 5)
1319 sbr = bits >> 31;
1321 if (sbr)
1323 unsigned int old_index = index;
1325 /* 1 bit read so far */
1326 index = (bits >> 27) & 0xf; /* Frequency index - 4 bits */
1328 if (index == 15)
1330 /* 5 bits read so far */
1331 id3->frequency = (bits >> 3) & 0x00ffffff;
1333 else if (index < (sizeof(sample_rates) / sizeof(*sample_rates)))
1335 id3->frequency = sample_rates[index];
1338 if (old_index == index)
1340 /* Downsampled SBR */
1341 id3->frequency *= 2;
1347 if (!sbr && (id3->frequency <= 24000) && (length <= 2))
1349 /* Double the frequency for low-frequency files without a "long"
1350 * DecSpecificConfig header. The file may or may not contain SBR,
1351 * but here we guess it does if the header is short. This can
1352 * fail on some files, but it's the best we can do, short of
1353 * decoding (parts of) the file.
1355 id3->frequency *= 2;
1359 return sbr;
1362 static bool read_mp4_tags(int fd, struct mp3entry* id3,
1363 unsigned int size_left)
1365 unsigned int size;
1366 unsigned int type;
1367 unsigned int buffer_left = sizeof(id3->id3v2buf) + sizeof(id3->id3v1buf);
1368 char* buffer = id3->id3v2buf;
1369 bool cwrt = false;
1373 size_left = read_mp4_atom(fd, &size, &type, size_left);
1375 /* DEBUGF("Tag atom: '%c%c%c%c' (%d bytes left)\n", type >> 24 & 0xff,
1376 type >> 16 & 0xff, type >> 8 & 0xff, type & 0xff, size); */
1378 switch (type)
1380 case MP4_cnam:
1381 read_mp4_tag_string(fd, size, &buffer, &buffer_left,
1382 &id3->title);
1383 break;
1385 case MP4_cART:
1386 read_mp4_tag_string(fd, size, &buffer, &buffer_left,
1387 &id3->artist);
1388 break;
1390 case MP4_calb:
1391 read_mp4_tag_string(fd, size, &buffer, &buffer_left,
1392 &id3->album);
1393 break;
1395 case MP4_cwrt:
1396 read_mp4_tag_string(fd, size, &buffer, &buffer_left,
1397 &id3->composer);
1398 cwrt = false;
1399 break;
1401 case MP4_gnre:
1403 unsigned short genre;
1405 read_mp4_tag(fd, size, (char*) &genre, sizeof(genre));
1406 id3->genre_string = id3_get_num_genre(betoh16(genre) - 1);
1408 break;
1410 case MP4_trkn:
1412 unsigned short n[2];
1414 read_mp4_tag(fd, size, (char*) &n, sizeof(n));
1415 id3->tracknum = betoh16(n[1]);
1417 break;
1419 case MP4_extra:
1421 char tag_name[TAG_NAME_LENGTH];
1422 unsigned int sub_size;
1424 /* "mean" atom */
1425 read_uint32be(fd, &sub_size);
1426 size -= sub_size;
1427 lseek(fd, sub_size - 4, SEEK_CUR);
1428 /* "name" atom */
1429 read_uint32be(fd, &sub_size);
1430 size -= sub_size;
1431 lseek(fd, 8, SEEK_CUR);
1432 sub_size -= 12;
1434 if (sub_size > sizeof(tag_name) - 1)
1436 read(fd, tag_name, sizeof(tag_name) - 1);
1437 lseek(fd, sub_size - sizeof(tag_name) - 1, SEEK_CUR);
1438 tag_name[sizeof(tag_name) - 1] = 0;
1440 else
1442 read(fd, tag_name, sub_size);
1443 tag_name[sub_size] = 0;
1446 if ((strcasecmp(tag_name, "composer") == 0) && !cwrt)
1448 read_mp4_tag_string(fd, size, &buffer, &buffer_left,
1449 &id3->composer);
1451 else
1453 char* any;
1454 unsigned int length = read_mp4_tag_string(fd, size,
1455 &buffer, &buffer_left, &any);
1457 if (length > 0)
1459 /* Re-use the read buffer as the dest buffer... */
1460 buffer -= length;
1461 buffer_left += length;
1463 if (parse_replaygain(tag_name, buffer, id3,
1464 buffer, buffer_left) > 0)
1466 /* Data used, keep it. */
1467 buffer += length;
1468 buffer_left -= length;
1473 break;
1475 default:
1476 lseek(fd, size, SEEK_CUR);
1477 break;
1480 while ((size_left > 0) && (errno == 0));
1482 return true;
1485 static bool read_mp4_container(int fd, struct mp3entry* id3,
1486 unsigned int size_left)
1488 unsigned int size;
1489 unsigned int type;
1490 unsigned int handler = 0;
1491 bool rc = true;
1495 size_left = read_mp4_atom(fd, &size, &type, size_left);
1497 /* DEBUGF("Atom: '%c%c%c%c' (0x%08x, %d bytes left)\n",
1498 (type >> 24) & 0xff, (type >> 16) & 0xff, (type >> 8) & 0xff,
1499 type & 0xff, type, size); */
1501 switch (type)
1503 case MP4_ftyp:
1505 unsigned int id;
1507 read_uint32be(fd, &id);
1508 size -= 4;
1510 if ((id != MP4_M4A) && (id != MP4_M4B) && (id != MP4_mp42)
1511 && (id != MP4_qt) && (id != MP4_3gp6))
1513 DEBUGF("Unknown MP4 file type: '%c%c%c%c'\n",
1514 id >> 24 & 0xff, id >> 16 & 0xff, id >> 8 & 0xff,
1515 id & 0xff);
1516 return false;
1519 break;
1521 case MP4_meta:
1522 lseek(fd, 4, SEEK_CUR); /* Skip version */
1523 size -= 4;
1524 /* Fall through */
1526 case MP4_moov:
1527 case MP4_udta:
1528 case MP4_mdia:
1529 case MP4_stbl:
1530 case MP4_trak:
1531 rc = read_mp4_container(fd, id3, size);
1532 size = 0;
1533 break;
1535 case MP4_ilst:
1536 if (handler == MP4_mdir)
1538 rc = read_mp4_tags(fd, id3, size);
1539 size = 0;
1541 break;
1543 case MP4_minf:
1544 if (handler == MP4_soun)
1546 rc = read_mp4_container(fd, id3, size);
1547 size = 0;
1549 break;
1551 case MP4_stsd:
1552 lseek(fd, 8, SEEK_CUR);
1553 size -= 8;
1554 rc = read_mp4_container(fd, id3, size);
1555 size = 0;
1556 break;
1558 case MP4_hdlr:
1559 lseek(fd, 8, SEEK_CUR);
1560 read_uint32be(fd, &handler);
1561 size -= 12;
1562 /* DEBUGF(" Handler '%c%c%c%c'\n", handler >> 24 & 0xff,
1563 handler >> 16 & 0xff, handler >> 8 & 0xff,handler & 0xff); */
1564 break;
1566 case MP4_stts:
1568 unsigned int entries;
1569 unsigned int i;
1571 lseek(fd, 4, SEEK_CUR);
1572 read_uint32be(fd, &entries);
1573 id3->samples = 0;
1575 for (i = 0; i < entries; i++)
1577 unsigned int n;
1578 unsigned int l;
1580 read_uint32be(fd, &n);
1581 read_uint32be(fd, &l);
1582 id3->samples += n * l;
1585 size = 0;
1587 break;
1589 case MP4_mp4a:
1590 case MP4_alac:
1592 unsigned int frequency;
1594 id3->codectype = (type == MP4_mp4a) ? AFMT_AAC : AFMT_ALAC;
1595 lseek(fd, 22, SEEK_CUR);
1596 read_uint32be(fd, &frequency);
1597 size -= 26;
1598 id3->frequency = frequency;
1600 if (type == MP4_mp4a)
1602 unsigned int subsize;
1603 unsigned int subtype;
1605 /* Get frequency from the decoder info tag, if possible. */
1606 lseek(fd, 2, SEEK_CUR);
1607 /* The esds atom is a part of the mp4a atom, so ignore
1608 * the returned size (it's already accounted for).
1610 read_mp4_atom(fd, &subsize, &subtype, size);
1611 size -= 10;
1613 if (subtype == MP4_esds)
1615 read_mp4_esds(fd, id3, &size);
1619 break;
1621 case MP4_mdat:
1622 id3->filesize = size;
1623 break;
1625 default:
1626 break;
1629 lseek(fd, size, SEEK_CUR);
1631 while (rc && (size_left > 0) && (errno == 0) && (id3->filesize == 0));
1632 /* Break on non-zero filesize, since Rockbox currently doesn't support
1633 * metadata after the mdat atom (which sets the filesize field).
1636 return rc;
1639 static bool get_mp4_metadata(int fd, struct mp3entry* id3)
1641 id3->codectype = AFMT_UNKNOWN;
1642 id3->filesize = 0;
1643 errno = 0;
1645 if (read_mp4_container(fd, id3, filesize(fd)) && (errno == 0)
1646 && (id3->samples > 0) && (id3->frequency > 0)
1647 && (id3->filesize > 0))
1649 if (id3->codectype == AFMT_UNKNOWN)
1651 logf("Not an ALAC or AAC file");
1652 return false;
1655 id3->length = ((int64_t) id3->samples * 1000) / id3->frequency;
1657 if (id3->length <= 0)
1659 logf("mp4 length invalid!");
1660 return false;
1663 id3->bitrate = ((int64_t) id3->filesize * 8) / id3->length;
1664 DEBUGF("MP4 bitrate %d, frequency %ld Hz, length %ld ms\n",
1665 id3->bitrate, id3->frequency, id3->length);
1667 else
1669 logf("MP4 metadata error");
1670 DEBUGF("MP4 metadata error. errno %d, length %ld, frequency %ld, filesize %ld\n",
1671 errno, id3->length, id3->frequency, id3->filesize);
1672 return false;
1675 return true;
1678 static bool get_musepack_metadata(int fd, struct mp3entry *id3)
1680 const int32_t sfreqs_sv7[4] = { 44100, 48000, 37800, 32000 };
1681 uint32_t header[8];
1682 uint64_t samples = 0;
1683 int i;
1685 if (!skip_id3v2(fd, id3))
1686 return false;
1687 if (read(fd, header, 4*8) != 4*8) return false;
1688 /* Musepack files are little endian, might need swapping */
1689 for (i = 1; i < 8; i++)
1690 header[i] = letoh32(header[i]);
1691 if (!memcmp(header, "MP+", 3)) { /* Compare to sig "MP+" */
1692 unsigned int streamversion;
1694 header[0] = letoh32(header[0]);
1695 streamversion = (header[0] >> 24) & 15;
1696 if (streamversion >= 8) {
1697 return false; /* SV8 or higher don't exist yet, so no support */
1698 } else if (streamversion == 7) {
1699 unsigned int gapless = (header[5] >> 31) & 0x0001;
1700 unsigned int last_frame_samples = (header[5] >> 20) & 0x07ff;
1701 int track_gain, album_gain;
1702 unsigned int bufused;
1704 id3->frequency = sfreqs_sv7[(header[2] >> 16) & 0x0003];
1705 samples = (uint64_t)header[1]*1152; /* 1152 is mpc frame size */
1706 if (gapless)
1707 samples -= 1152 - last_frame_samples;
1708 else
1709 samples -= 481; /* Musepack subband synth filter delay */
1711 /* Extract ReplayGain data from header */
1712 track_gain = (int16_t)((header[3] >> 16) & 0xffff);
1713 id3->track_gain = get_replaygain_int(track_gain);
1714 id3->track_peak = ((uint16_t)(header[3] & 0xffff)) << 9;
1716 album_gain = (int16_t)((header[4] >> 16) & 0xffff);
1717 id3->album_gain = get_replaygain_int(album_gain);
1718 id3->album_peak = ((uint16_t)(header[4] & 0xffff)) << 9;
1720 /* Write replaygain values to strings for use in id3 screen. We use
1721 the XING header as buffer space since Musepack files shouldn't
1722 need to use it in any other way */
1723 id3->track_gain_string = (char *)id3->toc;
1724 bufused = snprintf(id3->track_gain_string, 45,
1725 "%d.%d dB", track_gain/100, abs(track_gain)%100);
1726 id3->album_gain_string = (char *)id3->toc + bufused + 1;
1727 bufused = snprintf(id3->album_gain_string, 45,
1728 "%d.%d dB", album_gain/100, abs(album_gain)%100);
1730 } else {
1731 header[0] = letoh32(header[0]);
1732 unsigned int streamversion = (header[0] >> 11) & 0x03FF;
1733 if (streamversion != 4 && streamversion != 5 && streamversion != 6)
1734 return false;
1735 id3->frequency = 44100;
1736 id3->track_gain = 0;
1737 id3->track_peak = 0;
1738 id3->album_gain = 0;
1739 id3->album_peak = 0;
1741 if (streamversion >= 5)
1742 samples = (uint64_t)header[1]*1152; // 32 bit
1743 else
1744 samples = (uint64_t)(header[1] >> 16)*1152; // 16 bit
1746 samples -= 576;
1747 if (streamversion < 6)
1748 samples -= 1152;
1751 id3->vbr = true;
1752 /* Estimate bitrate, we should probably subtract the various header sizes
1753 here for super-accurate results */
1754 id3->length = ((int64_t) samples * 1000) / id3->frequency;
1756 if (id3->length <= 0)
1758 logf("mpc length invalid!");
1759 return false;
1762 id3->filesize = filesize(fd);
1763 id3->bitrate = id3->filesize * 8 / id3->length;
1764 return true;
1767 /* PSID metadata info is available here:
1768 http://www.unusedino.de/ec64/technical/formats/sidplay.html */
1769 static bool get_sid_metadata(int fd, struct mp3entry* id3)
1771 /* Use the trackname part of the id3 structure as a temporary buffer */
1772 unsigned char* buf = (unsigned char *)id3->path;
1773 int read_bytes;
1774 char *p;
1777 if ((lseek(fd, 0, SEEK_SET) < 0)
1778 || ((read_bytes = read(fd, buf, 0x80)) < 0x80))
1780 return false;
1783 if ((memcmp(buf, "PSID",4) != 0))
1785 return false;
1788 p = id3->id3v2buf;
1790 /* Copy Title (assumed max 0x1f letters + 1 zero byte) */
1791 id3->title = p;
1792 buf[0x16+0x1f] = 0;
1793 p = iso_decode(&buf[0x16], p, 0, strlen(&buf[0x16])+1);
1795 /* Copy Artist (assumed max 0x1f letters + 1 zero byte) */
1796 id3->artist = p;
1797 buf[0x36+0x1f] = 0;
1798 p = iso_decode(&buf[0x36], p, 0, strlen(&buf[0x36])+1);
1800 /* Copy Year (assumed max 4 letters + 1 zero byte) */
1801 buf[0x56+0x4] = 0;
1802 id3->year = atoi(&buf[0x56]);
1804 /* Copy Album (assumed max 0x1f-0x05 letters + 1 zero byte) */
1805 id3->album = p;
1806 buf[0x56+0x1f] = 0;
1807 p = iso_decode(&buf[0x5b], p, 0, strlen(&buf[0x5b])+1);
1809 id3->bitrate = 706;
1810 id3->frequency = 44100;
1811 /* New idea as posted by Marco Alanen (ravon):
1812 * Set the songlength in seconds to the number of subsongs
1813 * so every second represents a subsong.
1814 * Users can then skip the current subsong by seeking
1816 * Note: the number of songs is a 16bit value at 0xE, so this code only
1817 * uses the lower 8 bits of the counter.
1819 id3->length = (buf[0xf]-1)*1000;
1820 id3->vbr = false;
1821 id3->filesize = filesize(fd);
1823 return true;
1826 static bool get_adx_metadata(int fd, struct mp3entry* id3)
1828 /* Use the trackname part of the id3 structure as a temporary buffer */
1829 unsigned char * buf = (unsigned char *)id3->path;
1830 int chanstart, channels, read_bytes;
1831 int looping = 0, start_adr = 0, end_adr = 0;
1833 /* try to get the basic header */
1834 if ((lseek(fd, 0, SEEK_SET) < 0)
1835 || ((read_bytes = read(fd, buf, 0x38)) < 0x38))
1837 DEBUGF("lseek or read failed\n");
1838 return false;
1841 /* ADX starts with 0x80 */
1842 if (buf[0] != 0x80) {
1843 DEBUGF("get_adx_metadata: wrong first byte %c\n",buf[0]);
1844 return false;
1847 /* check for a reasonable offset */
1848 chanstart = ((buf[2] << 8) | buf[3]) + 4;
1849 if (chanstart > 4096) {
1850 DEBUGF("get_adx_metadata: bad chanstart %i\n", chanstart);
1851 return false;
1854 /* check for a workable number of channels */
1855 channels = buf[7];
1856 if (channels != 1 && channels != 2) {
1857 DEBUGF("get_adx_metadata: bad channel count %i\n",channels);
1858 return false;
1861 id3->frequency = get_long_be(&buf[8]);
1862 /* 32 samples per 18 bytes */
1863 id3->bitrate = id3->frequency * channels * 18 * 8 / 32 / 1000;
1864 id3->length = get_long_be(&buf[12]) / id3->frequency * 1000;
1865 id3->vbr = false;
1866 id3->filesize = filesize(fd);
1868 /* get loop info */
1869 if (!memcmp(buf+0x10,"\x01\xF4\x03\x00",4)) {
1870 /* Soul Calibur 2 style (type 03) */
1871 DEBUGF("get_adx_metadata: type 03 found\n");
1872 /* check if header is too small for loop data */
1873 if (chanstart-6 < 0x2c) looping=0;
1874 else {
1875 looping = get_long_be(&buf[0x18]);
1876 end_adr = get_long_be(&buf[0x28]);
1877 start_adr = get_long_be(&buf[0x1c])/32*channels*18+chanstart;
1879 } else if (!memcmp(buf+0x10,"\x01\xF4\x04\x00",4)) {
1880 /* Standard (type 04) */
1881 DEBUGF("get_adx_metadata: type 04 found\n");
1882 /* check if header is too small for loop data */
1883 if (chanstart-6 < 0x38) looping=0;
1884 else {
1885 looping = get_long_be(&buf[0x24]);
1886 end_adr = get_long_be(&buf[0x34]);
1887 start_adr = get_long_be(&buf[0x28])/32*channels*18+chanstart;
1889 } else {
1890 DEBUGF("get_adx_metadata: error, couldn't determine ADX type\n");
1891 return false;
1894 if (looping) {
1895 /* 2 loops, 10 second fade */
1896 id3->length = (start_adr-chanstart + 2*(end_adr-start_adr))
1897 *8 / id3->bitrate + 10000;
1900 /* try to get the channel header */
1901 if ((lseek(fd, chanstart-6, SEEK_SET) < 0)
1902 || ((read_bytes = read(fd, buf, 6)) < 6))
1904 return false;
1907 /* check channel header */
1908 if (memcmp(buf, "(c)CRI", 6) != 0) return false;
1910 return true;
1913 static bool get_spc_metadata(int fd, struct mp3entry* id3)
1915 /* Use the trackname part of the id3 structure as a temporary buffer */
1916 unsigned char * buf = (unsigned char *)id3->path;
1917 int read_bytes;
1918 char * p;
1920 unsigned long length;
1921 unsigned long fade;
1922 bool isbinary = true;
1923 int i;
1925 /* try to get the ID666 tag */
1926 if ((lseek(fd, 0x2e, SEEK_SET) < 0)
1927 || ((read_bytes = read(fd, buf, 0xD2)) < 0xD2))
1929 DEBUGF("lseek or read failed\n");
1930 return false;
1933 p = id3->id3v2buf;
1935 id3->title = p;
1936 buf[31] = 0;
1937 p = iso_decode(buf, p, 0, 32);
1938 buf += 32;
1940 id3->album = p;
1941 buf[31] = 0;
1942 p = iso_decode(buf, p, 0, 32);
1943 buf += 48;
1945 id3->comment = p;
1946 buf[31] = 0;
1947 p = iso_decode(buf, p, 0, 32);
1948 buf += 32;
1950 /* Date check */
1951 if(buf[2] == '/' && buf[5] == '/')
1952 isbinary = false;
1954 /* Reserved bytes check */
1955 if(buf[0xD2 - 0x2E - 112] >= '0' &&
1956 buf[0xD2 - 0x2E - 112] <= '9' &&
1957 buf[0xD3 - 0x2E - 112] == 0x00)
1958 isbinary = false;
1960 /* is length & fade only digits? */
1961 for (i=0;i<8 && (
1962 (buf[0xA9 - 0x2E - 112+i]>='0'&&buf[0xA9 - 0x2E - 112+i]<='9') ||
1963 buf[0xA9 - 0x2E - 112+i]=='\0');
1964 i++);
1965 if (i==8) isbinary = false;
1967 if(isbinary) {
1968 id3->year = buf[0] | (buf[1]<<8);
1969 buf += 11;
1971 length = (buf[0] | (buf[1]<<8) | (buf[2]<<16)) * 1000;
1972 buf += 3;
1974 fade = (buf[0] | (buf[1]<<8) | (buf[2]<<16) | (buf[3]<<24));
1975 buf += 4;
1976 } else {
1977 char tbuf[6];
1979 buf += 6;
1980 buf[4] = 0;
1981 id3->year = atoi(buf);
1982 buf += 5;
1984 memcpy(tbuf, buf, 3);
1985 tbuf[3] = 0;
1986 length = atoi(tbuf) * 1000;
1987 buf += 3;
1989 memcpy(tbuf, buf, 5);
1990 tbuf[5] = 0;
1991 fade = atoi(tbuf);
1992 buf += 5;
1995 id3->artist = p;
1996 buf[31] = 0;
1997 p = iso_decode(buf, p, 0, 32);
1999 if (length==0) {
2000 length=3*60*1000; /* 3 minutes */
2001 fade=5*1000; /* 5 seconds */
2004 id3->length = length+fade;
2006 return true;
2009 static bool get_aiff_metadata(int fd, struct mp3entry* id3)
2011 /* Use the trackname part of the id3 structure as a temporary buffer */
2012 unsigned char* buf = (unsigned char *)id3->path;
2013 unsigned long numChannels = 0;
2014 unsigned long numSampleFrames = 0;
2015 unsigned long sampleSize = 0;
2016 unsigned long sampleRate = 0;
2017 unsigned long numbytes = 0;
2018 int read_bytes;
2019 int i;
2021 if ((lseek(fd, 0, SEEK_SET) < 0)
2022 || ((read_bytes = read(fd, buf, sizeof(id3->path))) < 54))
2024 return false;
2027 if ((memcmp(buf, "FORM",4) != 0)
2028 || (memcmp(&buf[8], "AIFF", 4) !=0 ))
2030 return false;
2033 buf += 12;
2034 read_bytes -= 12;
2036 while ((numbytes == 0) && (read_bytes >= 8))
2038 /* chunkSize */
2039 i = get_long_be(&buf[4]);
2041 if (memcmp(buf, "COMM", 4) == 0)
2043 /* numChannels */
2044 numChannels = ((buf[8]<<8)|buf[9]);
2045 /* numSampleFrames */
2046 numSampleFrames = get_long_be(&buf[10]);
2047 /* sampleSize */
2048 sampleSize = ((buf[14]<<8)|buf[15]);
2049 /* sampleRate */
2050 sampleRate = get_long_be(&buf[18]);
2051 sampleRate = sampleRate >> (16+14-buf[17]);
2052 /* save format infos */
2053 id3->bitrate = (sampleSize * numChannels * sampleRate) / 1000;
2054 id3->frequency = sampleRate;
2055 id3->length = ((int64_t) numSampleFrames * 1000) / id3->frequency;
2057 id3->vbr = false; /* AIFF files are CBR */
2058 id3->filesize = filesize(fd);
2060 else if (memcmp(buf, "SSND", 4) == 0)
2062 numbytes = i - 8;
2065 if (i & 0x01)
2067 i++; /* odd chunk sizes must be padded */
2069 buf += i + 8;
2070 read_bytes -= i + 8;
2073 if ((numbytes == 0) || (numChannels == 0))
2075 return false;
2077 return true;
2079 #endif /* CONFIG_CODEC == SWCODEC */
2082 /* Simple file type probing by looking at the filename extension. */
2083 unsigned int probe_file_format(const char *filename)
2085 char *suffix;
2086 unsigned int i;
2088 suffix = strrchr(filename, '.');
2090 if (suffix == NULL)
2092 return AFMT_UNKNOWN;
2095 /* skip '.' */
2096 suffix++;
2098 for (i = 1; i < AFMT_NUM_CODECS; i++)
2100 /* search extension list for type */
2101 const char *ext = audio_formats[i].ext_list;
2105 if (strcasecmp(suffix, ext) == 0)
2107 return i;
2110 ext += strlen(ext) + 1;
2112 while (*ext != '\0');
2115 return AFMT_UNKNOWN;
2118 /* Get metadata for track - return false if parsing showed problems with the
2119 * file that would prevent playback.
2121 bool get_metadata(struct track_info* track, int fd, const char* trackname,
2122 bool v1first)
2124 #if CONFIG_CODEC == SWCODEC
2125 unsigned char* buf;
2126 unsigned long totalsamples;
2127 int i;
2128 #endif
2130 /* Take our best guess at the codec type based on file extension */
2131 track->id3.codectype = probe_file_format(trackname);
2133 /* Load codec specific track tag information and confirm the codec type. */
2134 switch (track->id3.codectype)
2136 case AFMT_MPA_L1:
2137 case AFMT_MPA_L2:
2138 case AFMT_MPA_L3:
2139 if (!get_mp3_metadata(fd, &track->id3, trackname, v1first))
2141 return false;
2144 break;
2146 #if CONFIG_CODEC == SWCODEC
2147 case AFMT_FLAC:
2148 if (!get_flac_metadata(fd, &(track->id3)))
2150 return false;
2153 break;
2155 case AFMT_MPC:
2156 if (!get_musepack_metadata(fd, &(track->id3)))
2157 return false;
2158 read_ape_tags(fd, &(track->id3));
2159 break;
2161 case AFMT_OGG_VORBIS:
2162 if (!get_vorbis_metadata(fd, &(track->id3)))/*detects and handles Ogg/Speex files*/
2164 return false;
2167 break;
2169 case AFMT_SPEEX:
2170 if (!get_speex_metadata(fd, &(track->id3)))
2172 return false;
2175 break;
2177 case AFMT_PCM_WAV:
2178 if (!get_wave_metadata(fd, &(track->id3)))
2180 return false;
2183 break;
2185 case AFMT_WAVPACK:
2186 /* A simple parser to read basic information from a WavPack file. This
2187 * now works with self-extrating WavPack files. This no longer fails on
2188 * WavPack files containing floating-point audio data because these are
2189 * now converted to standard Rockbox format in the decoder.
2192 /* Use the trackname part of the id3 structure as a temporary buffer */
2193 buf = (unsigned char *)track->id3.path;
2195 for (i = 0; i < 256; ++i) {
2197 /* at every 256 bytes into file, try to read a WavPack header */
2199 if ((lseek(fd, i * 256, SEEK_SET) < 0) || (read(fd, buf, 32) < 32))
2201 return false;
2204 /* if valid WavPack 4 header version & not floating data, break */
2206 if (memcmp (buf, "wvpk", 4) == 0 && buf [9] == 4 &&
2207 (buf [8] >= 2 && buf [8] <= 0x10))
2209 break;
2213 if (i == 256) {
2214 logf ("%s is not a WavPack file\n", trackname);
2215 return false;
2218 track->id3.vbr = true; /* All WavPack files are VBR */
2219 track->id3.filesize = filesize (fd);
2221 if ((buf [20] | buf [21] | buf [22] | buf [23]) &&
2222 (buf [12] & buf [13] & buf [14] & buf [15]) != 0xff)
2224 int srindx = ((buf [26] >> 7) & 1) + ((buf [27] << 1) & 14);
2226 if (srindx == 15)
2228 track->id3.frequency = 44100;
2230 else
2232 track->id3.frequency = wavpack_sample_rates[srindx];
2235 totalsamples = get_long_le(&buf[12]);
2236 track->id3.length = totalsamples / (track->id3.frequency / 100) * 10;
2237 track->id3.bitrate = filesize (fd) / (track->id3.length / 8);
2240 read_ape_tags(fd, &track->id3); /* use any apetag info we find */
2241 break;
2243 case AFMT_A52:
2244 /* Use the trackname part of the id3 structure as a temporary buffer */
2245 buf = (unsigned char *)track->id3.path;
2247 if ((lseek(fd, 0, SEEK_SET) < 0) || (read(fd, buf, 5) < 5))
2249 return false;
2252 if ((buf[0] != 0x0b) || (buf[1] != 0x77))
2254 logf("%s is not an A52/AC3 file\n",trackname);
2255 return false;
2258 i = buf[4] & 0x3e;
2260 if (i > 36)
2262 logf("A52: Invalid frmsizecod: %d\n",i);
2263 return false;
2266 track->id3.bitrate = a52_bitrates[i >> 1];
2267 track->id3.vbr = false;
2268 track->id3.filesize = filesize(fd);
2270 switch (buf[4] & 0xc0)
2272 case 0x00:
2273 track->id3.frequency = 48000;
2274 track->id3.bytesperframe=track->id3.bitrate * 2 * 2;
2275 break;
2277 case 0x40:
2278 track->id3.frequency = 44100;
2279 track->id3.bytesperframe = a52_441framesizes[i];
2280 break;
2282 case 0x80:
2283 track->id3.frequency = 32000;
2284 track->id3.bytesperframe = track->id3.bitrate * 3 * 2;
2285 break;
2287 default:
2288 logf("A52: Invalid samplerate code: 0x%02x\n", buf[4] & 0xc0);
2289 return false;
2290 break;
2293 /* One A52 frame contains 6 blocks, each containing 256 samples */
2294 totalsamples = track->id3.filesize / track->id3.bytesperframe * 6 * 256;
2295 track->id3.length = totalsamples / track->id3.frequency * 1000;
2296 break;
2298 case AFMT_ALAC:
2299 case AFMT_AAC:
2300 if (!get_mp4_metadata(fd, &(track->id3)))
2302 return false;
2305 break;
2307 case AFMT_SHN:
2308 track->id3.vbr = true;
2309 track->id3.filesize = filesize(fd);
2310 if (!skip_id3v2(fd, &(track->id3)))
2312 return false;
2314 /* TODO: read the id3v2 header if it exists */
2315 break;
2317 case AFMT_SID:
2318 if (!get_sid_metadata(fd, &(track->id3)))
2320 return false;
2322 break;
2323 case AFMT_SPC:
2324 if(!get_spc_metadata(fd, &(track->id3)))
2326 DEBUGF("get_spc_metadata error\n");
2329 track->id3.filesize = filesize(fd);
2330 track->id3.genre_string = id3_get_num_genre(36);
2331 break;
2332 case AFMT_ADX:
2333 if (!get_adx_metadata(fd, &(track->id3)))
2335 DEBUGF("get_adx_metadata error\n");
2336 return false;
2339 break;
2340 case AFMT_NSF:
2341 buf = (unsigned char *)track->id3.path;
2342 if ((lseek(fd, 0, SEEK_SET) < 0) || ((read(fd, buf, 8)) < 8))
2344 DEBUGF("lseek or read failed\n");
2345 return false;
2347 track->id3.vbr = false;
2348 track->id3.filesize = filesize(fd);
2349 if (memcmp(buf,"NESM",4) && memcmp(buf,"NSFE",4)) return false;
2350 break;
2352 case AFMT_AIFF:
2353 if (!get_aiff_metadata(fd, &(track->id3)))
2355 return false;
2358 break;
2360 #endif /* CONFIG_CODEC == SWCODEC */
2362 default:
2363 /* If we don't know how to read the metadata, assume we can't play
2364 the file */
2365 return false;
2366 break;
2369 /* We have successfully read the metadata from the file */
2371 #ifndef __PCTOOL__
2372 if (cuesheet_is_enabled() && look_for_cuesheet_file(trackname))
2374 track->id3.cuesheet_type = 1;
2376 #endif
2378 lseek(fd, 0, SEEK_SET);
2379 strncpy(track->id3.path, trackname, sizeof(track->id3.path));
2380 track->taginfo_ready = true;
2382 return true;