simple fix for FS#7274 - selected item might not be shown when a list is drawn in...
[Rockbox.git] / apps / metadata.c
blob357c5e649ef07e346263c77ed8b1b07df13af761
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 16-bit little endian short from buffer. */
187 static unsigned short get_short_le(void* buf)
189 unsigned char* p = (unsigned char*) buf;
191 return p[0] | (p[1] << 8);
194 /* Read an unaligned 32-bit big endian long from buffer. */
195 static unsigned long get_long_be(void* buf)
197 unsigned char* p = (unsigned char*) buf;
199 return (p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3];
202 /* Read an unaligned 32-bit little endian long from buffer. */
203 static long get_slong(void* buf)
205 unsigned char* p = (unsigned char*) buf;
207 return p[0] | (p[1] << 8) | (p[2] << 16) | (p[3] << 24);
210 /* Parse the tag (the name-value pair) and fill id3 and buffer accordingly.
211 * String values to keep are written to buf. Returns number of bytes written
212 * to buf (including end nil).
214 static long parse_tag(const char* name, char* value, struct mp3entry* id3,
215 char* buf, long buf_remaining, enum tagtype type)
217 long len = 0;
218 char** p;
220 if ((((strcasecmp(name, "track") == 0) && (type == TAGTYPE_APE)))
221 || ((strcasecmp(name, "tracknumber") == 0) && (type == TAGTYPE_VORBIS)))
223 id3->tracknum = atoi(value);
224 p = &(id3->track_string);
226 else if (((strcasecmp(name, "year") == 0) && (type == TAGTYPE_APE))
227 || ((strcasecmp(name, "date") == 0) && (type == TAGTYPE_VORBIS)))
229 /* Date's can be in any format in Vorbis. However most of them
230 * are in ISO8601 format so if we try and parse the first part
231 * of the tag as a number, we should get the year. If we get crap,
232 * then act like we never parsed it.
234 id3->year = atoi(value);
235 if (id3->year < 1900)
236 { /* yeah, not likely */
237 id3->year = 0;
239 p = &(id3->year_string);
241 else if (strcasecmp(name, "title") == 0)
243 p = &(id3->title);
245 else if (strcasecmp(name, "artist") == 0)
247 p = &(id3->artist);
249 else if (strcasecmp(name, "album") == 0)
251 p = &(id3->album);
253 else if (strcasecmp(name, "genre") == 0)
255 p = &(id3->genre_string);
257 else if (strcasecmp(name, "composer") == 0)
259 p = &(id3->composer);
261 else if (strcasecmp(name, "comment") == 0)
263 p = &(id3->comment);
265 else if (strcasecmp(name, "albumartist") == 0)
267 p = &(id3->albumartist);
269 else if (strcasecmp(name, "album artist") == 0)
271 p = &(id3->albumartist);
273 else if (strcasecmp(name, "ensemble") == 0)
275 p = &(id3->albumartist);
277 else
279 len = parse_replaygain(name, value, id3, buf, buf_remaining);
280 p = NULL;
283 if (p)
285 len = strlen(value);
286 len = MIN(len, buf_remaining - 1);
288 if (len > 0)
290 strncpy(buf, value, len);
291 buf[len] = 0;
292 *p = buf;
293 len++;
295 else
297 len = 0;
301 return len;
304 /* Read the items in an APEV2 tag. Only looks for a tag at the end of a
305 * file. Returns true if a tag was found and fully read, false otherwise.
307 static bool read_ape_tags(int fd, struct mp3entry* id3)
309 struct apetag_header header;
311 if ((lseek(fd, -APETAG_HEADER_LENGTH, SEEK_END) < 0)
312 || (ecread(fd, &header, 1, APETAG_HEADER_FORMAT, IS_BIG_ENDIAN) != APETAG_HEADER_LENGTH)
313 || (memcmp(header.id, "APETAGEX", sizeof(header.id))))
315 return false;
318 if ((header.version == 2000) && (header.item_count > 0)
319 && (header.length > APETAG_HEADER_LENGTH))
321 char *buf = id3->id3v2buf;
322 unsigned int buf_remaining = sizeof(id3->id3v2buf)
323 + sizeof(id3->id3v1buf);
324 unsigned int tag_remaining = header.length - APETAG_HEADER_LENGTH;
325 int i;
327 if (lseek(fd, -header.length, SEEK_END) < 0)
329 return false;
332 for (i = 0; i < header.item_count; i++)
334 struct apetag_item_header item;
335 char name[TAG_NAME_LENGTH];
336 char value[TAG_VALUE_LENGTH];
337 long r;
339 if (tag_remaining < sizeof(item))
341 break;
344 if (ecread(fd, &item, 1, APETAG_ITEM_HEADER_FORMAT, IS_BIG_ENDIAN) < (long) sizeof(item))
346 return false;
349 tag_remaining -= sizeof(item);
350 r = read_string(fd, name, sizeof(name), 0, tag_remaining);
352 if (r == -1)
354 return false;
357 tag_remaining -= r + item.length;
359 if ((item.flags & APETAG_ITEM_TYPE_MASK) == 0)
361 long len;
363 if (read_string(fd, value, sizeof(value), -1, item.length)
364 != item.length)
366 return false;
369 len = parse_tag(name, value, id3, buf, buf_remaining,
370 TAGTYPE_APE);
371 buf += len;
372 buf_remaining -= len;
374 else
376 if (lseek(fd, item.length, SEEK_CUR) < 0)
378 return false;
384 return true;
387 /* Read the items in a Vorbis comment packet. Returns true the items were
388 * fully read, false otherwise.
390 static bool read_vorbis_tags(int fd, struct mp3entry *id3,
391 long tag_remaining)
393 char *buf = id3->id3v2buf;
394 int32_t comment_count;
395 int32_t len;
396 int buf_remaining = sizeof(id3->id3v2buf) + sizeof(id3->id3v1buf);
397 int i;
399 if (ecread(fd, &len, 1, "l", IS_BIG_ENDIAN) < (long) sizeof(len))
401 return false;
404 if ((lseek(fd, len, SEEK_CUR) < 0)
405 || (ecread(fd, &comment_count, 1, "l", IS_BIG_ENDIAN)
406 < (long) sizeof(comment_count)))
408 return false;
411 tag_remaining -= len + sizeof(len) + sizeof(comment_count);
413 if (tag_remaining <= 0)
415 return true;
418 for (i = 0; i < comment_count; i++)
420 char name[TAG_NAME_LENGTH];
421 char value[TAG_VALUE_LENGTH];
422 int32_t read_len;
424 if (tag_remaining < 4)
426 break;
429 if (ecread(fd, &len, 1, "l", IS_BIG_ENDIAN) < (long) sizeof(len))
431 return false;
434 tag_remaining -= 4;
436 /* Quit if we've passed the end of the page */
437 if (tag_remaining < len)
439 break;
442 tag_remaining -= len;
443 read_len = read_string(fd, name, sizeof(name), '=', len);
445 if (read_len < 0)
447 return false;
450 len -= read_len;
452 if (read_string(fd, value, sizeof(value), -1, len) < 0)
454 return false;
457 len = parse_tag(name, value, id3, buf, buf_remaining,
458 TAGTYPE_VORBIS);
459 buf += len;
460 buf_remaining -= len;
463 /* Skip to the end of the block */
464 if (tag_remaining)
466 if (lseek(fd, tag_remaining, SEEK_CUR) < 0)
468 return false;
472 return true;
475 /* Skip an ID3v2 tag if it can be found. We assume the tag is located at the
476 * start of the file, which should be true in all cases where we need to skip it.
477 * Returns true if successfully skipped or not skipped, and false if
478 * something went wrong while skipping.
480 static bool skip_id3v2(int fd, struct mp3entry *id3)
482 char buf[4];
484 read(fd, buf, 4);
485 if (memcmp(buf, "ID3", 3) == 0)
487 /* We have found an ID3v2 tag at the start of the file - find its
488 length and then skip it. */
489 if ((id3->first_frame_offset = getid3v2len(fd)) == 0)
490 return false;
492 if ((lseek(fd, id3->first_frame_offset, SEEK_SET) < 0))
493 return false;
495 return true;
496 } else {
497 lseek(fd, 0, SEEK_SET);
498 id3->first_frame_offset = 0;
499 return true;
503 /* A simple parser to read vital metadata from an Ogg Speex file. Returns
504 * false if metadata needed by the Speex codec couldn't be read.
507 static bool get_speex_metadata(int fd, struct mp3entry* id3)
509 /* An Ogg File is split into pages, each starting with the string
510 * "OggS". Each page has a timestamp (in PCM samples) referred to as
511 * the "granule position".
513 * An Ogg Speex has the following structure:
514 * 1) Identification header (containing samplerate, numchannels, etc)
515 Described in this page: (http://www.speex.org/manual2/node7.html)
516 * 2) Comment header - containing the Vorbis Comments
517 * 3) Many audio packets...
520 /* Use the path name of the id3 structure as a temporary buffer. */
521 unsigned char* buf = (unsigned char*)id3->path;
522 long comment_size;
523 long remaining = 0;
524 long last_serial = 0;
525 long serial, r;
526 int segments;
527 int i;
528 bool eof = false;
530 if ((lseek(fd, 0, SEEK_SET) < 0) || (read(fd, buf, 58) < 33))
532 return false;
535 if ((memcmp(buf, "OggS", 4) != 0) || (memcmp(&buf[28], "Speex", 5) != 0))
537 return false;
540 /* We need to ensure the serial number from this page is the same as the
541 * one from the last page (since we only support a single bitstream).
543 serial = get_long_le(&buf[14]);
544 if ((lseek(fd, 33, SEEK_SET) < 0)||(read(fd, buf, 58) < 4))
546 return false;
549 id3->frequency = get_slong(&buf[31]);
550 last_serial = get_long_le(&buf[27]);/*temporary, header size*/
551 id3->bitrate = get_long_le(&buf[47]);
552 id3->vbr = get_long_le(&buf[55]);
553 id3->filesize = filesize(fd);
554 /* Comments are in second Ogg page */
555 if (lseek(fd, 28+last_serial/*(temporary for header size)*/, SEEK_SET) < 0)
557 return false;
560 /* Minimum header length for Ogg pages is 27. */
561 if (read(fd, buf, 27) < 27)
563 return false;
566 if (memcmp(buf, "OggS", 4) !=0 )
568 return false;
571 segments = buf[26];
572 /* read in segment table */
573 if (read(fd, buf, segments) < segments)
575 return false;
578 /* The second packet in a vorbis stream is the comment packet. It *may*
579 * extend beyond the second page, but usually does not. Here we find the
580 * length of the comment packet (or the rest of the page if the comment
581 * packet extends to the third page).
583 for (i = 0; i < segments; i++)
585 remaining += buf[i];
586 /* The last segment of a packet is always < 255 bytes */
587 if (buf[i] < 255)
589 break;
593 comment_size = remaining;
595 /* Failure to read the tags isn't fatal. */
596 read_vorbis_tags(fd, id3, remaining);
598 /* We now need to search for the last page in the file - identified by
599 * by ('O','g','g','S',0) and retrieve totalsamples.
602 /* A page is always < 64 kB */
603 if (lseek(fd, -(MIN(64 * 1024, id3->filesize)), SEEK_END) < 0)
605 return false;
608 remaining = 0;
610 while (!eof)
612 r = read(fd, &buf[remaining], MAX_PATH - remaining);
614 if (r <= 0)
616 eof = true;
618 else
620 remaining += r;
623 /* Inefficient (but simple) search */
624 i = 0;
626 while (i < (remaining - 3))
628 if ((buf[i] == 'O') && (memcmp(&buf[i], "OggS", 4) == 0))
630 if (i < (remaining - 17))
632 /* Note that this only reads the low 32 bits of a
633 * 64 bit value.
635 id3->samples = get_long_le(&buf[i + 6]);
636 last_serial = get_long_le(&buf[i + 14]);
638 /* If this page is very small the beginning of the next
639 * header could be in buffer. Jump near end of this header
640 * and continue */
641 i += 27;
643 else
645 break;
648 else
650 i++;
654 if (i < remaining)
656 /* Move the remaining bytes to start of buffer.
657 * Reuse var 'segments' as it is no longer needed */
658 segments = 0;
659 while (i < remaining)
661 buf[segments++] = buf[i++];
663 remaining = segments;
665 else
667 /* Discard the rest of the buffer */
668 remaining = 0;
672 /* This file has mutiple vorbis bitstreams (or is corrupt). */
673 /* FIXME we should display an error here. */
674 if (serial != last_serial)
676 logf("serialno mismatch");
677 logf("%ld", serial);
678 logf("%ld", last_serial);
679 return false;
682 id3->length = (id3->samples / id3->frequency) * 1000;
683 id3->bitrate = (((int64_t) id3->filesize - comment_size) * 8) / id3->length;
684 return true;
688 /* A simple parser to read vital metadata from an Ogg Vorbis file.
689 * Calls get_speex_metadata if a speex file is identified. Returns
690 * false if metadata needed by the Vorbis codec couldn't be read.
692 static bool get_vorbis_metadata(int fd, struct mp3entry* id3)
694 /* An Ogg File is split into pages, each starting with the string
695 * "OggS". Each page has a timestamp (in PCM samples) referred to as
696 * the "granule position".
698 * An Ogg Vorbis has the following structure:
699 * 1) Identification header (containing samplerate, numchannels, etc)
700 * 2) Comment header - containing the Vorbis Comments
701 * 3) Setup header - containing codec setup information
702 * 4) Many audio packets...
705 /* Use the path name of the id3 structure as a temporary buffer. */
706 unsigned char* buf = (unsigned char *)id3->path;
707 long comment_size;
708 long remaining = 0;
709 long last_serial = 0;
710 long serial, r;
711 int segments;
712 int i;
713 bool eof = false;
715 if ((lseek(fd, 0, SEEK_SET) < 0) || (read(fd, buf, 58) < 4))
717 return false;
720 if ((memcmp(buf, "OggS", 4) != 0) || (memcmp(&buf[29], "vorbis", 6) != 0))
722 if ((memcmp(buf, "OggS", 4) != 0) || (memcmp(&buf[28], "Speex", 5) != 0))
724 return false;
726 else
728 id3->codectype = AFMT_SPEEX;
729 return get_speex_metadata(fd, id3);
733 /* We need to ensure the serial number from this page is the same as the
734 * one from the last page (since we only support a single bitstream).
736 serial = get_long_le(&buf[14]);
737 id3->frequency = get_long_le(&buf[40]);
738 id3->filesize = filesize(fd);
740 /* Comments are in second Ogg page */
741 if (lseek(fd, 58, SEEK_SET) < 0)
743 return false;
746 /* Minimum header length for Ogg pages is 27. */
747 if (read(fd, buf, 27) < 27)
749 return false;
752 if (memcmp(buf, "OggS", 4) !=0 )
754 return false;
757 segments = buf[26];
759 /* read in segment table */
760 if (read(fd, buf, segments) < segments)
762 return false;
765 /* The second packet in a vorbis stream is the comment packet. It *may*
766 * extend beyond the second page, but usually does not. Here we find the
767 * length of the comment packet (or the rest of the page if the comment
768 * packet extends to the third page).
770 for (i = 0; i < segments; i++)
772 remaining += buf[i];
774 /* The last segment of a packet is always < 255 bytes */
775 if (buf[i] < 255)
777 break;
781 /* Now read in packet header (type and id string) */
782 if (read(fd, buf, 7) < 7)
784 return false;
787 comment_size = remaining;
788 remaining -= 7;
790 /* The first byte of a packet is the packet type; comment packets are
791 * type 3.
793 if ((buf[0] != 3) || (memcmp(buf + 1, "vorbis", 6) !=0))
795 return false;
798 /* Failure to read the tags isn't fatal. */
799 read_vorbis_tags(fd, id3, remaining);
801 /* We now need to search for the last page in the file - identified by
802 * by ('O','g','g','S',0) and retrieve totalsamples.
805 /* A page is always < 64 kB */
806 if (lseek(fd, -(MIN(64 * 1024, id3->filesize)), SEEK_END) < 0)
808 return false;
811 remaining = 0;
813 while (!eof)
815 r = read(fd, &buf[remaining], MAX_PATH - remaining);
817 if (r <= 0)
819 eof = true;
821 else
823 remaining += r;
826 /* Inefficient (but simple) search */
827 i = 0;
829 while (i < (remaining - 3))
831 if ((buf[i] == 'O') && (memcmp(&buf[i], "OggS", 4) == 0))
833 if (i < (remaining - 17))
835 /* Note that this only reads the low 32 bits of a
836 * 64 bit value.
838 id3->samples = get_long_le(&buf[i + 6]);
839 last_serial = get_long_le(&buf[i + 14]);
841 /* If this page is very small the beginning of the next
842 * header could be in buffer. Jump near end of this header
843 * and continue */
844 i += 27;
846 else
848 break;
851 else
853 i++;
857 if (i < remaining)
859 /* Move the remaining bytes to start of buffer.
860 * Reuse var 'segments' as it is no longer needed */
861 segments = 0;
862 while (i < remaining)
864 buf[segments++] = buf[i++];
866 remaining = segments;
868 else
870 /* Discard the rest of the buffer */
871 remaining = 0;
875 /* This file has mutiple vorbis bitstreams (or is corrupt). */
876 /* FIXME we should display an error here. */
877 if (serial != last_serial)
879 logf("serialno mismatch");
880 logf("%ld", serial);
881 logf("%ld", last_serial);
882 return false;
885 id3->length = ((int64_t) id3->samples * 1000) / id3->frequency;
887 if (id3->length <= 0)
889 logf("ogg length invalid!");
890 return false;
893 id3->bitrate = (((int64_t) id3->filesize - comment_size) * 8) / id3->length;
894 id3->vbr = true;
896 return true;
899 static bool get_flac_metadata(int fd, struct mp3entry* id3)
901 /* A simple parser to read vital metadata from a FLAC file - length,
902 * frequency, bitrate etc. This code should either be moved to a
903 * seperate file, or discarded in favour of the libFLAC code.
904 * The FLAC stream specification can be found at
905 * http://flac.sourceforge.net/format.html#stream
908 /* Use the trackname part of the id3 structure as a temporary buffer */
909 unsigned char* buf = (unsigned char *)id3->path;
910 bool rc = false;
912 if (!skip_id3v2(fd, id3) || (read(fd, buf, 4) < 4))
914 return rc;
917 if (memcmp(buf, "fLaC", 4) != 0)
919 return rc;
922 while (true)
924 long i;
926 if (read(fd, buf, 4) < 0)
928 return rc;
931 /* The length of the block */
932 i = (buf[1] << 16) | (buf[2] << 8) | buf[3];
934 if ((buf[0] & 0x7f) == 0) /* 0 is the STREAMINFO block */
936 unsigned long totalsamples;
938 /* FIXME: Don't trust the value of i */
939 if (read(fd, buf, i) < 0)
941 return rc;
944 id3->vbr = true; /* All FLAC files are VBR */
945 id3->filesize = filesize(fd);
946 id3->frequency = (buf[10] << 12) | (buf[11] << 4)
947 | ((buf[12] & 0xf0) >> 4);
948 rc = true; /* Got vital metadata */
950 /* totalsamples is a 36-bit field, but we assume <= 32 bits are used */
951 totalsamples = get_long_be(&buf[14]);
953 /* Calculate track length (in ms) and estimate the bitrate (in kbit/s) */
954 id3->length = ((int64_t) totalsamples * 1000) / id3->frequency;
956 if (id3->length <= 0)
958 logf("flac length invalid!");
959 return false;
962 id3->bitrate = (id3->filesize * 8) / id3->length;
964 else if ((buf[0] & 0x7f) == 4) /* 4 is the VORBIS_COMMENT block */
966 /* The next i bytes of the file contain the VORBIS COMMENTS. */
967 if (!read_vorbis_tags(fd, id3, i))
969 return rc;
972 else
974 if (buf[0] & 0x80)
976 /* If we have reached the last metadata block, abort. */
977 break;
979 else
981 /* Skip to next metadata block */
982 if (lseek(fd, i, SEEK_CUR) < 0)
984 return rc;
990 return true;
993 static bool get_monkeys_metadata(int fd, struct mp3entry* id3)
995 /* Use the trackname part of the id3 structure as a temporary buffer */
996 unsigned char* buf = (unsigned char *)id3->path;
997 unsigned char* header;
998 bool rc = false;
999 uint32_t descriptorlength;
1000 uint32_t totalsamples;
1001 uint32_t blocksperframe, finalframeblocks, totalframes;
1002 int fileversion;
1004 lseek(fd, 0, SEEK_SET);
1006 if (read(fd, buf, 4) < 4)
1008 return rc;
1011 if (memcmp(buf, "MAC ", 4) != 0)
1013 return rc;
1016 read(fd, buf + 4, MAX_PATH - 4);
1018 fileversion = get_short_le(buf+4);
1019 if (fileversion < 3970)
1021 /* Not supported */
1022 return false;
1025 if (fileversion >= 3980)
1027 descriptorlength = get_long_le(buf+8);
1029 header = buf + descriptorlength;
1031 blocksperframe = get_long_le(header+4);
1032 finalframeblocks = get_long_le(header+8);
1033 totalframes = get_long_le(header+12);
1034 id3->frequency = get_long_le(header+20);
1036 else
1038 /* v3.95 and later files all have a fixed framesize */
1039 blocksperframe = 73728 * 4;
1041 finalframeblocks = get_long_le(buf+28);
1042 totalframes = get_long_le(buf+24);
1043 id3->frequency = get_long_le(buf+12);
1046 id3->vbr = true; /* All FLAC files are VBR */
1047 id3->filesize = filesize(fd);
1049 totalsamples = finalframeblocks;
1050 if (totalframes > 1)
1051 totalsamples += blocksperframe * (totalframes-1);
1053 id3->length = ((int64_t) totalsamples * 1000) / id3->frequency;
1054 id3->bitrate = (id3->filesize * 8) / id3->length;
1055 return true;
1058 static bool get_wave_metadata(int fd, struct mp3entry* id3)
1060 /* Use the trackname part of the id3 structure as a temporary buffer */
1061 unsigned char* buf = (unsigned char *)id3->path;
1062 unsigned long totalsamples = 0;
1063 unsigned long channels = 0;
1064 unsigned long bitspersample = 0;
1065 unsigned long numbytes = 0;
1066 int read_bytes;
1067 int i;
1069 /* get RIFF chunk header */
1070 if ((lseek(fd, 0, SEEK_SET) < 0)
1071 || ((read_bytes = read(fd, buf, 12)) < 12))
1073 return false;
1076 if ((memcmp(buf, "RIFF",4) != 0)
1077 || (memcmp(&buf[8], "WAVE", 4) !=0 ))
1079 return false;
1082 /* iterate over WAVE chunks until 'data' chunk */
1083 while (true)
1085 /* get chunk header */
1086 if ((read_bytes = read(fd, buf, 8)) < 8)
1087 return false;
1089 /* chunkSize */
1090 i = get_long_le(&buf[4]);
1092 if (memcmp(buf, "fmt ", 4) == 0)
1094 /* get rest of chunk */
1095 if ((read_bytes = read(fd, buf, 16)) < 16)
1096 return false;
1098 i -= 16;
1100 /* skipping wFormatTag */
1101 /* wChannels */
1102 channels = buf[2] | (buf[3] << 8);
1103 /* dwSamplesPerSec */
1104 id3->frequency = get_long_le(&buf[4]);
1105 /* dwAvgBytesPerSec */
1106 id3->bitrate = (get_long_le(&buf[8]) * 8) / 1000;
1107 /* skipping wBlockAlign */
1108 /* wBitsPerSample */
1109 bitspersample = buf[14] | (buf[15] << 8);
1111 else if (memcmp(buf, "data", 4) == 0)
1113 numbytes = i;
1114 break;
1116 else if (memcmp(buf, "fact", 4) == 0)
1118 /* dwSampleLength */
1119 if (i >= 4)
1121 /* get rest of chunk */
1122 if ((read_bytes = read(fd, buf, 4)) < 4)
1123 return false;
1125 i -= 4;
1126 totalsamples = get_long_le(buf);
1130 /* seek to next chunk (even chunk sizes must be padded) */
1131 if (i & 0x01)
1132 i++;
1134 if(lseek(fd, i, SEEK_CUR) < 0)
1135 return false;
1138 if ((numbytes == 0) || (channels == 0))
1140 return false;
1143 if (totalsamples == 0)
1145 /* for PCM only */
1146 totalsamples = numbytes
1147 / ((((bitspersample - 1) / 8) + 1) * channels);
1150 id3->vbr = false; /* All WAV files are CBR */
1151 id3->filesize = filesize(fd);
1153 /* Calculate track length (in ms) and estimate the bitrate (in kbit/s) */
1154 id3->length = ((int64_t) totalsamples * 1000) / id3->frequency;
1156 return true;
1159 /* Read the tag data from an MP4 file, storing up to buffer_size bytes in
1160 * buffer.
1162 static unsigned long read_mp4_tag(int fd, unsigned int size_left, char* buffer,
1163 unsigned int buffer_left)
1165 unsigned int bytes_read = 0;
1167 if (buffer_left == 0)
1169 lseek(fd, size_left, SEEK_CUR); /* Skip everything */
1171 else
1173 /* Skip the data tag header - maybe we should parse it properly? */
1174 lseek(fd, 16, SEEK_CUR);
1175 size_left -= 16;
1177 if (size_left > buffer_left)
1179 read(fd, buffer, buffer_left);
1180 lseek(fd, size_left - buffer_left, SEEK_CUR);
1181 bytes_read = buffer_left;
1183 else
1185 read(fd, buffer, size_left);
1186 bytes_read = size_left;
1190 return bytes_read;
1193 /* Read a string tag from an MP4 file */
1194 static unsigned int read_mp4_tag_string(int fd, int size_left, char** buffer,
1195 unsigned int* buffer_left, char** dest)
1197 unsigned int bytes_read = read_mp4_tag(fd, size_left, *buffer,
1198 *buffer_left - 1);
1199 unsigned int length = 0;
1201 if (bytes_read)
1203 (*buffer)[bytes_read] = 0;
1204 *dest = *buffer;
1205 length = strlen(*buffer) + 1;
1206 *buffer_left -= length;
1207 *buffer += length;
1209 else
1211 *dest = NULL;
1214 return length;
1217 static unsigned int read_mp4_atom(int fd, unsigned int* size,
1218 unsigned int* type, unsigned int size_left)
1220 read_uint32be(fd, size);
1221 read_uint32be(fd, type);
1223 if (*size == 1)
1225 /* FAT32 doesn't support files this big, so something seems to
1226 * be wrong. (64-bit sizes should only be used when required.)
1228 errno = EFBIG;
1229 *type = 0;
1230 return 0;
1233 if (*size > 0)
1235 if (*size > size_left)
1237 size_left = 0;
1239 else
1241 size_left -= *size;
1244 *size -= 8;
1246 else
1248 *size = size_left;
1249 size_left = 0;
1252 return size_left;
1255 static unsigned int read_mp4_length(int fd, unsigned int* size)
1257 unsigned int length = 0;
1258 int bytes = 0;
1259 unsigned char c;
1263 read(fd, &c, 1);
1264 bytes++;
1265 (*size)--;
1266 length = (length << 7) | (c & 0x7F);
1268 while ((c & 0x80) && (bytes < 4) && (*size > 0));
1270 return length;
1273 static bool read_mp4_esds(int fd, struct mp3entry* id3,
1274 unsigned int* size)
1276 unsigned char buf[8];
1277 bool sbr = false;
1279 lseek(fd, 4, SEEK_CUR); /* Version and flags. */
1280 read(fd, buf, 1); /* Verify ES_DescrTag. */
1281 *size -= 5;
1283 if (*buf == 3)
1285 /* read length */
1286 if (read_mp4_length(fd, size) < 20)
1288 return sbr;
1291 lseek(fd, 3, SEEK_CUR);
1292 *size -= 3;
1294 else
1296 lseek(fd, 2, SEEK_CUR);
1297 *size -= 2;
1300 read(fd, buf, 1); /* Verify DecoderConfigDescrTab. */
1301 *size -= 1;
1303 if (*buf != 4)
1305 return sbr;
1308 if (read_mp4_length(fd, size) < 13)
1310 return sbr;
1313 lseek(fd, 13, SEEK_CUR); /* Skip audio type, bit rates, etc. */
1314 read(fd, buf, 1);
1315 *size -= 14;
1317 if (*buf != 5) /* Verify DecSpecificInfoTag. */
1319 return sbr;
1323 static const int sample_rates[] =
1325 96000, 88200, 64000, 48000, 44100, 32000,
1326 24000, 22050, 16000, 12000, 11025, 8000
1328 unsigned long bits;
1329 unsigned int length;
1330 unsigned int index;
1331 unsigned int type;
1333 /* Read the (leading part of the) decoder config. */
1334 length = read_mp4_length(fd, size);
1335 length = MIN(length, *size);
1336 length = MIN(length, sizeof(buf));
1337 memset(buf, 0, sizeof(buf));
1338 read(fd, buf, length);
1339 *size -= length;
1341 /* Maybe time to write a simple read_bits function... */
1343 /* Decoder config format:
1344 * Object type - 5 bits
1345 * Frequency index - 4 bits
1346 * Channel configuration - 4 bits
1348 bits = get_long_be(buf);
1349 type = bits >> 27; /* Object type - 5 bits */
1350 index = (bits >> 23) & 0xf; /* Frequency index - 4 bits */
1352 if (index < (sizeof(sample_rates) / sizeof(*sample_rates)))
1354 id3->frequency = sample_rates[index];
1357 if (type == 5)
1359 DEBUGF("MP4: SBR\n");
1360 unsigned int old_index = index;
1362 sbr = true;
1363 index = (bits >> 15) & 0xf; /* Frequency index - 4 bits */
1365 if (index == 15)
1367 /* 17 bits read so far... */
1368 bits = get_long_be(&buf[2]);
1369 id3->frequency = (bits >> 7) & 0x00ffffff;
1371 else if (index < (sizeof(sample_rates) / sizeof(*sample_rates)))
1373 id3->frequency = sample_rates[index];
1376 if (old_index == index)
1378 /* Downsampled SBR */
1379 id3->frequency *= 2;
1382 /* Skip 13 bits from above, plus 3 bits, then read 11 bits */
1383 else if ((length >= 4) && (((bits >> 5) & 0x7ff) == 0x2b7))
1385 /* extensionAudioObjectType */
1386 DEBUGF("MP4: extensionAudioType\n");
1387 type = bits & 0x1f; /* Object type - 5 bits*/
1388 bits = get_long_be(&buf[4]);
1390 if (type == 5)
1392 sbr = bits >> 31;
1394 if (sbr)
1396 unsigned int old_index = index;
1398 /* 1 bit read so far */
1399 index = (bits >> 27) & 0xf; /* Frequency index - 4 bits */
1401 if (index == 15)
1403 /* 5 bits read so far */
1404 id3->frequency = (bits >> 3) & 0x00ffffff;
1406 else if (index < (sizeof(sample_rates) / sizeof(*sample_rates)))
1408 id3->frequency = sample_rates[index];
1411 if (old_index == index)
1413 /* Downsampled SBR */
1414 id3->frequency *= 2;
1420 if (!sbr && (id3->frequency <= 24000) && (length <= 2))
1422 /* Double the frequency for low-frequency files without a "long"
1423 * DecSpecificConfig header. The file may or may not contain SBR,
1424 * but here we guess it does if the header is short. This can
1425 * fail on some files, but it's the best we can do, short of
1426 * decoding (parts of) the file.
1428 id3->frequency *= 2;
1432 return sbr;
1435 static bool read_mp4_tags(int fd, struct mp3entry* id3,
1436 unsigned int size_left)
1438 unsigned int size;
1439 unsigned int type;
1440 unsigned int buffer_left = sizeof(id3->id3v2buf) + sizeof(id3->id3v1buf);
1441 char* buffer = id3->id3v2buf;
1442 bool cwrt = false;
1446 size_left = read_mp4_atom(fd, &size, &type, size_left);
1448 /* DEBUGF("Tag atom: '%c%c%c%c' (%d bytes left)\n", type >> 24 & 0xff,
1449 type >> 16 & 0xff, type >> 8 & 0xff, type & 0xff, size); */
1451 switch (type)
1453 case MP4_cnam:
1454 read_mp4_tag_string(fd, size, &buffer, &buffer_left,
1455 &id3->title);
1456 break;
1458 case MP4_cART:
1459 read_mp4_tag_string(fd, size, &buffer, &buffer_left,
1460 &id3->artist);
1461 break;
1463 case MP4_calb:
1464 read_mp4_tag_string(fd, size, &buffer, &buffer_left,
1465 &id3->album);
1466 break;
1468 case MP4_cwrt:
1469 read_mp4_tag_string(fd, size, &buffer, &buffer_left,
1470 &id3->composer);
1471 cwrt = false;
1472 break;
1474 case MP4_gnre:
1476 unsigned short genre;
1478 read_mp4_tag(fd, size, (char*) &genre, sizeof(genre));
1479 id3->genre_string = id3_get_num_genre(betoh16(genre) - 1);
1481 break;
1483 case MP4_trkn:
1485 unsigned short n[2];
1487 read_mp4_tag(fd, size, (char*) &n, sizeof(n));
1488 id3->tracknum = betoh16(n[1]);
1490 break;
1492 case MP4_extra:
1494 char tag_name[TAG_NAME_LENGTH];
1495 unsigned int sub_size;
1497 /* "mean" atom */
1498 read_uint32be(fd, &sub_size);
1499 size -= sub_size;
1500 lseek(fd, sub_size - 4, SEEK_CUR);
1501 /* "name" atom */
1502 read_uint32be(fd, &sub_size);
1503 size -= sub_size;
1504 lseek(fd, 8, SEEK_CUR);
1505 sub_size -= 12;
1507 if (sub_size > sizeof(tag_name) - 1)
1509 read(fd, tag_name, sizeof(tag_name) - 1);
1510 lseek(fd, sub_size - sizeof(tag_name) - 1, SEEK_CUR);
1511 tag_name[sizeof(tag_name) - 1] = 0;
1513 else
1515 read(fd, tag_name, sub_size);
1516 tag_name[sub_size] = 0;
1519 if ((strcasecmp(tag_name, "composer") == 0) && !cwrt)
1521 read_mp4_tag_string(fd, size, &buffer, &buffer_left,
1522 &id3->composer);
1524 else
1526 char* any;
1527 unsigned int length = read_mp4_tag_string(fd, size,
1528 &buffer, &buffer_left, &any);
1530 if (length > 0)
1532 /* Re-use the read buffer as the dest buffer... */
1533 buffer -= length;
1534 buffer_left += length;
1536 if (parse_replaygain(tag_name, buffer, id3,
1537 buffer, buffer_left) > 0)
1539 /* Data used, keep it. */
1540 buffer += length;
1541 buffer_left -= length;
1546 break;
1548 default:
1549 lseek(fd, size, SEEK_CUR);
1550 break;
1553 while ((size_left > 0) && (errno == 0));
1555 return true;
1558 static bool read_mp4_container(int fd, struct mp3entry* id3,
1559 unsigned int size_left)
1561 unsigned int size;
1562 unsigned int type;
1563 unsigned int handler = 0;
1564 bool rc = true;
1568 size_left = read_mp4_atom(fd, &size, &type, size_left);
1570 /* DEBUGF("Atom: '%c%c%c%c' (0x%08x, %d bytes left)\n",
1571 (type >> 24) & 0xff, (type >> 16) & 0xff, (type >> 8) & 0xff,
1572 type & 0xff, type, size); */
1574 switch (type)
1576 case MP4_ftyp:
1578 unsigned int id;
1580 read_uint32be(fd, &id);
1581 size -= 4;
1583 if ((id != MP4_M4A) && (id != MP4_M4B) && (id != MP4_mp42)
1584 && (id != MP4_qt) && (id != MP4_3gp6))
1586 DEBUGF("Unknown MP4 file type: '%c%c%c%c'\n",
1587 id >> 24 & 0xff, id >> 16 & 0xff, id >> 8 & 0xff,
1588 id & 0xff);
1589 return false;
1592 break;
1594 case MP4_meta:
1595 lseek(fd, 4, SEEK_CUR); /* Skip version */
1596 size -= 4;
1597 /* Fall through */
1599 case MP4_moov:
1600 case MP4_udta:
1601 case MP4_mdia:
1602 case MP4_stbl:
1603 case MP4_trak:
1604 rc = read_mp4_container(fd, id3, size);
1605 size = 0;
1606 break;
1608 case MP4_ilst:
1609 if (handler == MP4_mdir)
1611 rc = read_mp4_tags(fd, id3, size);
1612 size = 0;
1614 break;
1616 case MP4_minf:
1617 if (handler == MP4_soun)
1619 rc = read_mp4_container(fd, id3, size);
1620 size = 0;
1622 break;
1624 case MP4_stsd:
1625 lseek(fd, 8, SEEK_CUR);
1626 size -= 8;
1627 rc = read_mp4_container(fd, id3, size);
1628 size = 0;
1629 break;
1631 case MP4_hdlr:
1632 lseek(fd, 8, SEEK_CUR);
1633 read_uint32be(fd, &handler);
1634 size -= 12;
1635 /* DEBUGF(" Handler '%c%c%c%c'\n", handler >> 24 & 0xff,
1636 handler >> 16 & 0xff, handler >> 8 & 0xff,handler & 0xff); */
1637 break;
1639 case MP4_stts:
1641 unsigned int entries;
1642 unsigned int i;
1644 lseek(fd, 4, SEEK_CUR);
1645 read_uint32be(fd, &entries);
1646 id3->samples = 0;
1648 for (i = 0; i < entries; i++)
1650 unsigned int n;
1651 unsigned int l;
1653 read_uint32be(fd, &n);
1654 read_uint32be(fd, &l);
1655 id3->samples += n * l;
1658 size = 0;
1660 break;
1662 case MP4_mp4a:
1663 case MP4_alac:
1665 unsigned int frequency;
1667 id3->codectype = (type == MP4_mp4a) ? AFMT_AAC : AFMT_ALAC;
1668 lseek(fd, 22, SEEK_CUR);
1669 read_uint32be(fd, &frequency);
1670 size -= 26;
1671 id3->frequency = frequency;
1673 if (type == MP4_mp4a)
1675 unsigned int subsize;
1676 unsigned int subtype;
1678 /* Get frequency from the decoder info tag, if possible. */
1679 lseek(fd, 2, SEEK_CUR);
1680 /* The esds atom is a part of the mp4a atom, so ignore
1681 * the returned size (it's already accounted for).
1683 read_mp4_atom(fd, &subsize, &subtype, size);
1684 size -= 10;
1686 if (subtype == MP4_esds)
1688 read_mp4_esds(fd, id3, &size);
1692 break;
1694 case MP4_mdat:
1695 id3->filesize = size;
1696 break;
1698 default:
1699 break;
1702 lseek(fd, size, SEEK_CUR);
1704 while (rc && (size_left > 0) && (errno == 0) && (id3->filesize == 0));
1705 /* Break on non-zero filesize, since Rockbox currently doesn't support
1706 * metadata after the mdat atom (which sets the filesize field).
1709 return rc;
1712 static bool get_mp4_metadata(int fd, struct mp3entry* id3)
1714 id3->codectype = AFMT_UNKNOWN;
1715 id3->filesize = 0;
1716 errno = 0;
1718 if (read_mp4_container(fd, id3, filesize(fd)) && (errno == 0)
1719 && (id3->samples > 0) && (id3->frequency > 0)
1720 && (id3->filesize > 0))
1722 if (id3->codectype == AFMT_UNKNOWN)
1724 logf("Not an ALAC or AAC file");
1725 return false;
1728 id3->length = ((int64_t) id3->samples * 1000) / id3->frequency;
1730 if (id3->length <= 0)
1732 logf("mp4 length invalid!");
1733 return false;
1736 id3->bitrate = ((int64_t) id3->filesize * 8) / id3->length;
1737 DEBUGF("MP4 bitrate %d, frequency %ld Hz, length %ld ms\n",
1738 id3->bitrate, id3->frequency, id3->length);
1740 else
1742 logf("MP4 metadata error");
1743 DEBUGF("MP4 metadata error. errno %d, length %ld, frequency %ld, filesize %ld\n",
1744 errno, id3->length, id3->frequency, id3->filesize);
1745 return false;
1748 return true;
1751 static bool get_musepack_metadata(int fd, struct mp3entry *id3)
1753 const int32_t sfreqs_sv7[4] = { 44100, 48000, 37800, 32000 };
1754 uint32_t header[8];
1755 uint64_t samples = 0;
1756 int i;
1758 if (!skip_id3v2(fd, id3))
1759 return false;
1760 if (read(fd, header, 4*8) != 4*8) return false;
1761 /* Musepack files are little endian, might need swapping */
1762 for (i = 1; i < 8; i++)
1763 header[i] = letoh32(header[i]);
1764 if (!memcmp(header, "MP+", 3)) { /* Compare to sig "MP+" */
1765 unsigned int streamversion;
1767 header[0] = letoh32(header[0]);
1768 streamversion = (header[0] >> 24) & 15;
1769 if (streamversion >= 8) {
1770 return false; /* SV8 or higher don't exist yet, so no support */
1771 } else if (streamversion == 7) {
1772 unsigned int gapless = (header[5] >> 31) & 0x0001;
1773 unsigned int last_frame_samples = (header[5] >> 20) & 0x07ff;
1774 int track_gain, album_gain;
1775 unsigned int bufused;
1777 id3->frequency = sfreqs_sv7[(header[2] >> 16) & 0x0003];
1778 samples = (uint64_t)header[1]*1152; /* 1152 is mpc frame size */
1779 if (gapless)
1780 samples -= 1152 - last_frame_samples;
1781 else
1782 samples -= 481; /* Musepack subband synth filter delay */
1784 /* Extract ReplayGain data from header */
1785 track_gain = (int16_t)((header[3] >> 16) & 0xffff);
1786 id3->track_gain = get_replaygain_int(track_gain);
1787 id3->track_peak = ((uint16_t)(header[3] & 0xffff)) << 9;
1789 album_gain = (int16_t)((header[4] >> 16) & 0xffff);
1790 id3->album_gain = get_replaygain_int(album_gain);
1791 id3->album_peak = ((uint16_t)(header[4] & 0xffff)) << 9;
1793 /* Write replaygain values to strings for use in id3 screen. We use
1794 the XING header as buffer space since Musepack files shouldn't
1795 need to use it in any other way */
1796 id3->track_gain_string = (char *)id3->toc;
1797 bufused = snprintf(id3->track_gain_string, 45,
1798 "%d.%d dB", track_gain/100, abs(track_gain)%100);
1799 id3->album_gain_string = (char *)id3->toc + bufused + 1;
1800 bufused = snprintf(id3->album_gain_string, 45,
1801 "%d.%d dB", album_gain/100, abs(album_gain)%100);
1803 } else {
1804 header[0] = letoh32(header[0]);
1805 unsigned int streamversion = (header[0] >> 11) & 0x03FF;
1806 if (streamversion != 4 && streamversion != 5 && streamversion != 6)
1807 return false;
1808 id3->frequency = 44100;
1809 id3->track_gain = 0;
1810 id3->track_peak = 0;
1811 id3->album_gain = 0;
1812 id3->album_peak = 0;
1814 if (streamversion >= 5)
1815 samples = (uint64_t)header[1]*1152; // 32 bit
1816 else
1817 samples = (uint64_t)(header[1] >> 16)*1152; // 16 bit
1819 samples -= 576;
1820 if (streamversion < 6)
1821 samples -= 1152;
1824 id3->vbr = true;
1825 /* Estimate bitrate, we should probably subtract the various header sizes
1826 here for super-accurate results */
1827 id3->length = ((int64_t) samples * 1000) / id3->frequency;
1829 if (id3->length <= 0)
1831 logf("mpc length invalid!");
1832 return false;
1835 id3->filesize = filesize(fd);
1836 id3->bitrate = id3->filesize * 8 / id3->length;
1837 return true;
1840 /* PSID metadata info is available here:
1841 http://www.unusedino.de/ec64/technical/formats/sidplay.html */
1842 static bool get_sid_metadata(int fd, struct mp3entry* id3)
1844 /* Use the trackname part of the id3 structure as a temporary buffer */
1845 unsigned char* buf = (unsigned char *)id3->path;
1846 int read_bytes;
1847 char *p;
1850 if ((lseek(fd, 0, SEEK_SET) < 0)
1851 || ((read_bytes = read(fd, buf, 0x80)) < 0x80))
1853 return false;
1856 if ((memcmp(buf, "PSID",4) != 0))
1858 return false;
1861 p = id3->id3v2buf;
1863 /* Copy Title (assumed max 0x1f letters + 1 zero byte) */
1864 id3->title = p;
1865 buf[0x16+0x1f] = 0;
1866 p = iso_decode(&buf[0x16], p, 0, strlen(&buf[0x16])+1);
1868 /* Copy Artist (assumed max 0x1f letters + 1 zero byte) */
1869 id3->artist = p;
1870 buf[0x36+0x1f] = 0;
1871 p = iso_decode(&buf[0x36], p, 0, strlen(&buf[0x36])+1);
1873 /* Copy Year (assumed max 4 letters + 1 zero byte) */
1874 buf[0x56+0x4] = 0;
1875 id3->year = atoi(&buf[0x56]);
1877 /* Copy Album (assumed max 0x1f-0x05 letters + 1 zero byte) */
1878 id3->album = p;
1879 buf[0x56+0x1f] = 0;
1880 p = iso_decode(&buf[0x5b], p, 0, strlen(&buf[0x5b])+1);
1882 id3->bitrate = 706;
1883 id3->frequency = 44100;
1884 /* New idea as posted by Marco Alanen (ravon):
1885 * Set the songlength in seconds to the number of subsongs
1886 * so every second represents a subsong.
1887 * Users can then skip the current subsong by seeking
1889 * Note: the number of songs is a 16bit value at 0xE, so this code only
1890 * uses the lower 8 bits of the counter.
1892 id3->length = (buf[0xf]-1)*1000;
1893 id3->vbr = false;
1894 id3->filesize = filesize(fd);
1896 return true;
1899 static bool get_adx_metadata(int fd, struct mp3entry* id3)
1901 /* Use the trackname part of the id3 structure as a temporary buffer */
1902 unsigned char * buf = (unsigned char *)id3->path;
1903 int chanstart, channels, read_bytes;
1904 int looping = 0, start_adr = 0, end_adr = 0;
1906 /* try to get the basic header */
1907 if ((lseek(fd, 0, SEEK_SET) < 0)
1908 || ((read_bytes = read(fd, buf, 0x38)) < 0x38))
1910 DEBUGF("lseek or read failed\n");
1911 return false;
1914 /* ADX starts with 0x80 */
1915 if (buf[0] != 0x80) {
1916 DEBUGF("get_adx_metadata: wrong first byte %c\n",buf[0]);
1917 return false;
1920 /* check for a reasonable offset */
1921 chanstart = ((buf[2] << 8) | buf[3]) + 4;
1922 if (chanstart > 4096) {
1923 DEBUGF("get_adx_metadata: bad chanstart %i\n", chanstart);
1924 return false;
1927 /* check for a workable number of channels */
1928 channels = buf[7];
1929 if (channels != 1 && channels != 2) {
1930 DEBUGF("get_adx_metadata: bad channel count %i\n",channels);
1931 return false;
1934 id3->frequency = get_long_be(&buf[8]);
1935 /* 32 samples per 18 bytes */
1936 id3->bitrate = id3->frequency * channels * 18 * 8 / 32 / 1000;
1937 id3->length = get_long_be(&buf[12]) / id3->frequency * 1000;
1938 id3->vbr = false;
1939 id3->filesize = filesize(fd);
1941 /* get loop info */
1942 if (!memcmp(buf+0x10,"\x01\xF4\x03\x00",4)) {
1943 /* Soul Calibur 2 style (type 03) */
1944 DEBUGF("get_adx_metadata: type 03 found\n");
1945 /* check if header is too small for loop data */
1946 if (chanstart-6 < 0x2c) looping=0;
1947 else {
1948 looping = get_long_be(&buf[0x18]);
1949 end_adr = get_long_be(&buf[0x28]);
1950 start_adr = get_long_be(&buf[0x1c])/32*channels*18+chanstart;
1952 } else if (!memcmp(buf+0x10,"\x01\xF4\x04\x00",4)) {
1953 /* Standard (type 04) */
1954 DEBUGF("get_adx_metadata: type 04 found\n");
1955 /* check if header is too small for loop data */
1956 if (chanstart-6 < 0x38) looping=0;
1957 else {
1958 looping = get_long_be(&buf[0x24]);
1959 end_adr = get_long_be(&buf[0x34]);
1960 start_adr = get_long_be(&buf[0x28])/32*channels*18+chanstart;
1962 } else {
1963 DEBUGF("get_adx_metadata: error, couldn't determine ADX type\n");
1964 return false;
1967 if (looping) {
1968 /* 2 loops, 10 second fade */
1969 id3->length = (start_adr-chanstart + 2*(end_adr-start_adr))
1970 *8 / id3->bitrate + 10000;
1973 /* try to get the channel header */
1974 if ((lseek(fd, chanstart-6, SEEK_SET) < 0)
1975 || ((read_bytes = read(fd, buf, 6)) < 6))
1977 return false;
1980 /* check channel header */
1981 if (memcmp(buf, "(c)CRI", 6) != 0) return false;
1983 return true;
1986 static bool get_spc_metadata(int fd, struct mp3entry* id3)
1988 /* Use the trackname part of the id3 structure as a temporary buffer */
1989 unsigned char * buf = (unsigned char *)id3->path;
1990 int read_bytes;
1991 char * p;
1993 unsigned long length;
1994 unsigned long fade;
1995 bool isbinary = true;
1996 int i;
1998 /* try to get the ID666 tag */
1999 if ((lseek(fd, 0x2e, SEEK_SET) < 0)
2000 || ((read_bytes = read(fd, buf, 0xD2)) < 0xD2))
2002 DEBUGF("lseek or read failed\n");
2003 return false;
2006 p = id3->id3v2buf;
2008 id3->title = p;
2009 buf[31] = 0;
2010 p = iso_decode(buf, p, 0, 32);
2011 buf += 32;
2013 id3->album = p;
2014 buf[31] = 0;
2015 p = iso_decode(buf, p, 0, 32);
2016 buf += 48;
2018 id3->comment = p;
2019 buf[31] = 0;
2020 p = iso_decode(buf, p, 0, 32);
2021 buf += 32;
2023 /* Date check */
2024 if(buf[2] == '/' && buf[5] == '/')
2025 isbinary = false;
2027 /* Reserved bytes check */
2028 if(buf[0xD2 - 0x2E - 112] >= '0' &&
2029 buf[0xD2 - 0x2E - 112] <= '9' &&
2030 buf[0xD3 - 0x2E - 112] == 0x00)
2031 isbinary = false;
2033 /* is length & fade only digits? */
2034 for (i=0;i<8 && (
2035 (buf[0xA9 - 0x2E - 112+i]>='0'&&buf[0xA9 - 0x2E - 112+i]<='9') ||
2036 buf[0xA9 - 0x2E - 112+i]=='\0');
2037 i++);
2038 if (i==8) isbinary = false;
2040 if(isbinary) {
2041 id3->year = buf[0] | (buf[1]<<8);
2042 buf += 11;
2044 length = (buf[0] | (buf[1]<<8) | (buf[2]<<16)) * 1000;
2045 buf += 3;
2047 fade = (buf[0] | (buf[1]<<8) | (buf[2]<<16) | (buf[3]<<24));
2048 buf += 4;
2049 } else {
2050 char tbuf[6];
2052 buf += 6;
2053 buf[4] = 0;
2054 id3->year = atoi(buf);
2055 buf += 5;
2057 memcpy(tbuf, buf, 3);
2058 tbuf[3] = 0;
2059 length = atoi(tbuf) * 1000;
2060 buf += 3;
2062 memcpy(tbuf, buf, 5);
2063 tbuf[5] = 0;
2064 fade = atoi(tbuf);
2065 buf += 5;
2068 id3->artist = p;
2069 buf[31] = 0;
2070 p = iso_decode(buf, p, 0, 32);
2072 if (length==0) {
2073 length=3*60*1000; /* 3 minutes */
2074 fade=5*1000; /* 5 seconds */
2077 id3->length = length+fade;
2079 return true;
2082 static bool get_aiff_metadata(int fd, struct mp3entry* id3)
2084 /* Use the trackname part of the id3 structure as a temporary buffer */
2085 unsigned char* buf = (unsigned char *)id3->path;
2086 unsigned long numChannels = 0;
2087 unsigned long numSampleFrames = 0;
2088 unsigned long sampleSize = 0;
2089 unsigned long sampleRate = 0;
2090 unsigned long numbytes = 0;
2091 int read_bytes;
2092 int i;
2094 if ((lseek(fd, 0, SEEK_SET) < 0)
2095 || ((read_bytes = read(fd, buf, sizeof(id3->path))) < 54))
2097 return false;
2100 if ((memcmp(buf, "FORM",4) != 0)
2101 || (memcmp(&buf[8], "AIFF", 4) !=0 ))
2103 return false;
2106 buf += 12;
2107 read_bytes -= 12;
2109 while ((numbytes == 0) && (read_bytes >= 8))
2111 /* chunkSize */
2112 i = get_long_be(&buf[4]);
2114 if (memcmp(buf, "COMM", 4) == 0)
2116 /* numChannels */
2117 numChannels = ((buf[8]<<8)|buf[9]);
2118 /* numSampleFrames */
2119 numSampleFrames = get_long_be(&buf[10]);
2120 /* sampleSize */
2121 sampleSize = ((buf[14]<<8)|buf[15]);
2122 /* sampleRate */
2123 sampleRate = get_long_be(&buf[18]);
2124 sampleRate = sampleRate >> (16+14-buf[17]);
2125 /* save format infos */
2126 id3->bitrate = (sampleSize * numChannels * sampleRate) / 1000;
2127 id3->frequency = sampleRate;
2128 id3->length = ((int64_t) numSampleFrames * 1000) / id3->frequency;
2130 id3->vbr = false; /* AIFF files are CBR */
2131 id3->filesize = filesize(fd);
2133 else if (memcmp(buf, "SSND", 4) == 0)
2135 numbytes = i - 8;
2138 if (i & 0x01)
2140 i++; /* odd chunk sizes must be padded */
2142 buf += i + 8;
2143 read_bytes -= i + 8;
2146 if ((numbytes == 0) || (numChannels == 0))
2148 return false;
2150 return true;
2152 #endif /* CONFIG_CODEC == SWCODEC */
2155 /* Simple file type probing by looking at the filename extension. */
2156 unsigned int probe_file_format(const char *filename)
2158 char *suffix;
2159 unsigned int i;
2161 suffix = strrchr(filename, '.');
2163 if (suffix == NULL)
2165 return AFMT_UNKNOWN;
2168 /* skip '.' */
2169 suffix++;
2171 for (i = 1; i < AFMT_NUM_CODECS; i++)
2173 /* search extension list for type */
2174 const char *ext = audio_formats[i].ext_list;
2178 if (strcasecmp(suffix, ext) == 0)
2180 return i;
2183 ext += strlen(ext) + 1;
2185 while (*ext != '\0');
2188 return AFMT_UNKNOWN;
2191 /* Get metadata for track - return false if parsing showed problems with the
2192 * file that would prevent playback.
2194 bool get_metadata(struct track_info* track, int fd, const char* trackname,
2195 bool v1first)
2197 #if CONFIG_CODEC == SWCODEC
2198 unsigned char* buf;
2199 unsigned long totalsamples;
2200 int i;
2201 #endif
2203 /* Take our best guess at the codec type based on file extension */
2204 track->id3.codectype = probe_file_format(trackname);
2206 /* Load codec specific track tag information and confirm the codec type. */
2207 switch (track->id3.codectype)
2209 case AFMT_MPA_L1:
2210 case AFMT_MPA_L2:
2211 case AFMT_MPA_L3:
2212 if (!get_mp3_metadata(fd, &track->id3, trackname, v1first))
2214 return false;
2217 break;
2219 #if CONFIG_CODEC == SWCODEC
2220 case AFMT_FLAC:
2221 if (!get_flac_metadata(fd, &(track->id3)))
2223 return false;
2226 break;
2228 case AFMT_APE:
2229 if (!get_monkeys_metadata(fd, &(track->id3)))
2231 return false;
2233 read_ape_tags(fd, &(track->id3));
2234 break;
2236 case AFMT_MPC:
2237 if (!get_musepack_metadata(fd, &(track->id3)))
2238 return false;
2239 read_ape_tags(fd, &(track->id3));
2240 break;
2242 case AFMT_OGG_VORBIS:
2243 if (!get_vorbis_metadata(fd, &(track->id3)))/*detects and handles Ogg/Speex files*/
2245 return false;
2248 break;
2250 case AFMT_SPEEX:
2251 if (!get_speex_metadata(fd, &(track->id3)))
2253 return false;
2256 break;
2258 case AFMT_PCM_WAV:
2259 if (!get_wave_metadata(fd, &(track->id3)))
2261 return false;
2264 break;
2266 case AFMT_WAVPACK:
2267 /* A simple parser to read basic information from a WavPack file. This
2268 * now works with self-extrating WavPack files. This no longer fails on
2269 * WavPack files containing floating-point audio data because these are
2270 * now converted to standard Rockbox format in the decoder.
2273 /* Use the trackname part of the id3 structure as a temporary buffer */
2274 buf = (unsigned char *)track->id3.path;
2276 for (i = 0; i < 256; ++i) {
2278 /* at every 256 bytes into file, try to read a WavPack header */
2280 if ((lseek(fd, i * 256, SEEK_SET) < 0) || (read(fd, buf, 32) < 32))
2282 return false;
2285 /* if valid WavPack 4 header version & not floating data, break */
2287 if (memcmp (buf, "wvpk", 4) == 0 && buf [9] == 4 &&
2288 (buf [8] >= 2 && buf [8] <= 0x10))
2290 break;
2294 if (i == 256) {
2295 logf ("%s is not a WavPack file\n", trackname);
2296 return false;
2299 track->id3.vbr = true; /* All WavPack files are VBR */
2300 track->id3.filesize = filesize (fd);
2302 if ((buf [20] | buf [21] | buf [22] | buf [23]) &&
2303 (buf [12] & buf [13] & buf [14] & buf [15]) != 0xff)
2305 int srindx = ((buf [26] >> 7) & 1) + ((buf [27] << 1) & 14);
2307 if (srindx == 15)
2309 track->id3.frequency = 44100;
2311 else
2313 track->id3.frequency = wavpack_sample_rates[srindx];
2316 totalsamples = get_long_le(&buf[12]);
2317 track->id3.length = totalsamples / (track->id3.frequency / 100) * 10;
2318 track->id3.bitrate = filesize (fd) / (track->id3.length / 8);
2321 read_ape_tags(fd, &track->id3); /* use any apetag info we find */
2322 break;
2324 case AFMT_A52:
2325 /* Use the trackname part of the id3 structure as a temporary buffer */
2326 buf = (unsigned char *)track->id3.path;
2328 if ((lseek(fd, 0, SEEK_SET) < 0) || (read(fd, buf, 5) < 5))
2330 return false;
2333 if ((buf[0] != 0x0b) || (buf[1] != 0x77))
2335 logf("%s is not an A52/AC3 file\n",trackname);
2336 return false;
2339 i = buf[4] & 0x3e;
2341 if (i > 36)
2343 logf("A52: Invalid frmsizecod: %d\n",i);
2344 return false;
2347 track->id3.bitrate = a52_bitrates[i >> 1];
2348 track->id3.vbr = false;
2349 track->id3.filesize = filesize(fd);
2351 switch (buf[4] & 0xc0)
2353 case 0x00:
2354 track->id3.frequency = 48000;
2355 track->id3.bytesperframe=track->id3.bitrate * 2 * 2;
2356 break;
2358 case 0x40:
2359 track->id3.frequency = 44100;
2360 track->id3.bytesperframe = a52_441framesizes[i];
2361 break;
2363 case 0x80:
2364 track->id3.frequency = 32000;
2365 track->id3.bytesperframe = track->id3.bitrate * 3 * 2;
2366 break;
2368 default:
2369 logf("A52: Invalid samplerate code: 0x%02x\n", buf[4] & 0xc0);
2370 return false;
2371 break;
2374 /* One A52 frame contains 6 blocks, each containing 256 samples */
2375 totalsamples = track->id3.filesize / track->id3.bytesperframe * 6 * 256;
2376 track->id3.length = totalsamples / track->id3.frequency * 1000;
2377 break;
2379 case AFMT_ALAC:
2380 case AFMT_AAC:
2381 if (!get_mp4_metadata(fd, &(track->id3)))
2383 return false;
2386 break;
2388 case AFMT_SHN:
2389 track->id3.vbr = true;
2390 track->id3.filesize = filesize(fd);
2391 if (!skip_id3v2(fd, &(track->id3)))
2393 return false;
2395 /* TODO: read the id3v2 header if it exists */
2396 break;
2398 case AFMT_SID:
2399 if (!get_sid_metadata(fd, &(track->id3)))
2401 return false;
2403 break;
2404 case AFMT_SPC:
2405 if(!get_spc_metadata(fd, &(track->id3)))
2407 DEBUGF("get_spc_metadata error\n");
2410 track->id3.filesize = filesize(fd);
2411 track->id3.genre_string = id3_get_num_genre(36);
2412 break;
2413 case AFMT_ADX:
2414 if (!get_adx_metadata(fd, &(track->id3)))
2416 DEBUGF("get_adx_metadata error\n");
2417 return false;
2420 break;
2421 case AFMT_NSF:
2422 buf = (unsigned char *)track->id3.path;
2423 if ((lseek(fd, 0, SEEK_SET) < 0) || ((read(fd, buf, 8)) < 8))
2425 DEBUGF("lseek or read failed\n");
2426 return false;
2428 track->id3.vbr = false;
2429 track->id3.filesize = filesize(fd);
2430 if (memcmp(buf,"NESM",4) && memcmp(buf,"NSFE",4)) return false;
2431 break;
2433 case AFMT_AIFF:
2434 if (!get_aiff_metadata(fd, &(track->id3)))
2436 return false;
2439 break;
2441 #endif /* CONFIG_CODEC == SWCODEC */
2443 default:
2444 /* If we don't know how to read the metadata, assume we can't play
2445 the file */
2446 return false;
2447 break;
2450 /* We have successfully read the metadata from the file */
2452 #ifndef __PCTOOL__
2453 if (cuesheet_is_enabled() && look_for_cuesheet_file(trackname, NULL))
2455 track->id3.cuesheet_type = 1;
2457 #endif
2459 lseek(fd, 0, SEEK_SET);
2460 strncpy(track->id3.path, trackname, sizeof(track->id3.path));
2461 track->taginfo_ready = true;
2463 return true;