Add platform file for Iaudio M5.
[Rockbox.git] / apps / metadata.c
blob869e4b9b8165ebe9cc0ce28a8fe388a4699dabf4
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"
36 #include "settings.h"
38 enum tagtype { TAGTYPE_APE = 1, TAGTYPE_VORBIS };
40 #ifdef ROCKBOX_BIG_ENDIAN
41 #define IS_BIG_ENDIAN 1
42 #else
43 #define IS_BIG_ENDIAN 0
44 #endif
46 #define APETAG_HEADER_LENGTH 32
47 #define APETAG_HEADER_FORMAT "8llll8"
48 #define APETAG_ITEM_HEADER_FORMAT "ll"
49 #define APETAG_ITEM_TYPE_MASK 3
51 #define TAG_NAME_LENGTH 32
52 #define TAG_VALUE_LENGTH 128
54 #define MP4_ID(a, b, c, d) (((a) << 24) | ((b) << 16) | ((c) << 8) | (d))
56 #define MP4_3gp6 MP4_ID('3', 'g', 'p', '6')
57 #define MP4_alac MP4_ID('a', 'l', 'a', 'c')
58 #define MP4_calb MP4_ID(0xa9, 'a', 'l', 'b')
59 #define MP4_cART MP4_ID(0xa9, 'A', 'R', 'T')
60 #define MP4_cnam MP4_ID(0xa9, 'n', 'a', 'm')
61 #define MP4_cwrt MP4_ID(0xa9, 'w', 'r', 't')
62 #define MP4_esds MP4_ID('e', 's', 'd', 's')
63 #define MP4_ftyp MP4_ID('f', 't', 'y', 'p')
64 #define MP4_gnre MP4_ID('g', 'n', 'r', 'e')
65 #define MP4_hdlr MP4_ID('h', 'd', 'l', 'r')
66 #define MP4_ilst MP4_ID('i', 'l', 's', 't')
67 #define MP4_M4A MP4_ID('M', '4', 'A', ' ')
68 #define MP4_M4B MP4_ID('M', '4', 'B', ' ')
69 #define MP4_mdat MP4_ID('m', 'd', 'a', 't')
70 #define MP4_mdia MP4_ID('m', 'd', 'i', 'a')
71 #define MP4_mdir MP4_ID('m', 'd', 'i', 'r')
72 #define MP4_meta MP4_ID('m', 'e', 't', 'a')
73 #define MP4_minf MP4_ID('m', 'i', 'n', 'f')
74 #define MP4_moov MP4_ID('m', 'o', 'o', 'v')
75 #define MP4_mp4a MP4_ID('m', 'p', '4', 'a')
76 #define MP4_mp42 MP4_ID('m', 'p', '4', '2')
77 #define MP4_qt MP4_ID('q', 't', ' ', ' ')
78 #define MP4_soun MP4_ID('s', 'o', 'u', 'n')
79 #define MP4_stbl MP4_ID('s', 't', 'b', 'l')
80 #define MP4_stsd MP4_ID('s', 't', 's', 'd')
81 #define MP4_stts MP4_ID('s', 't', 't', 's')
82 #define MP4_trak MP4_ID('t', 'r', 'a', 'k')
83 #define MP4_trkn MP4_ID('t', 'r', 'k', 'n')
84 #define MP4_udta MP4_ID('u', 'd', 't', 'a')
85 #define MP4_extra MP4_ID('-', '-', '-', '-')
87 struct apetag_header
89 char id[8];
90 long version;
91 long length;
92 long item_count;
93 long flags;
94 char reserved[8];
97 struct apetag_item_header
99 long length;
100 long flags;
103 #if CONFIG_CODEC == SWCODEC
104 static const unsigned short a52_bitrates[] =
106 32, 40, 48, 56, 64, 80, 96, 112, 128, 160,
107 192, 224, 256, 320, 384, 448, 512, 576, 640
110 /* Only store frame sizes for 44.1KHz - others are simply multiples
111 of the bitrate */
112 static const unsigned short a52_441framesizes[] =
114 69 * 2, 70 * 2, 87 * 2, 88 * 2, 104 * 2, 105 * 2, 121 * 2,
115 122 * 2, 139 * 2, 140 * 2, 174 * 2, 175 * 2, 208 * 2, 209 * 2,
116 243 * 2, 244 * 2, 278 * 2, 279 * 2, 348 * 2, 349 * 2, 417 * 2,
117 418 * 2, 487 * 2, 488 * 2, 557 * 2, 558 * 2, 696 * 2, 697 * 2,
118 835 * 2, 836 * 2, 975 * 2, 976 * 2, 1114 * 2, 1115 * 2, 1253 * 2,
119 1254 * 2, 1393 * 2, 1394 * 2
122 static const long wavpack_sample_rates [] =
124 6000, 8000, 9600, 11025, 12000, 16000, 22050, 24000,
125 32000, 44100, 48000, 64000, 88200, 96000, 192000
128 /* Read a string from the file. Read up to size bytes, or, if eos != -1,
129 * until the eos character is found (eos is not stored in buf, unless it is
130 * nil). Writes up to buf_size chars to buf, always terminating with a nil.
131 * Returns number of chars read or -1 on read error.
133 static long read_string(int fd, char* buf, long buf_size, int eos, long size)
135 long read_bytes = 0;
136 char c;
138 while (size != 0)
140 if (read(fd, &c, 1) != 1)
142 read_bytes = -1;
143 break;
146 read_bytes++;
147 size--;
149 if ((eos != -1) && (eos == (unsigned char) c))
151 break;
154 if (buf_size > 1)
156 *buf++ = c;
157 buf_size--;
161 *buf = 0;
162 return read_bytes;
165 /* Read an unsigned 32-bit integer from a big-endian file. */
166 #ifdef ROCKBOX_BIG_ENDIAN
167 #define read_uint32be(fd,buf) read((fd), (buf), 4)
168 #else
169 static int read_uint32be(int fd, unsigned int* buf)
171 size_t n;
173 n = read(fd, (char*) buf, 4);
174 *buf = betoh32(*buf);
175 return n;
177 #endif
179 /* Read an unaligned 32-bit little endian long from buffer. */
180 static unsigned long get_long_le(void* buf)
182 unsigned char* p = (unsigned char*) buf;
184 return p[0] | (p[1] << 8) | (p[2] << 16) | (p[3] << 24);
187 /* Read an unaligned 32-bit big endian long from buffer. */
188 static unsigned long get_long_be(void* buf)
190 unsigned char* p = (unsigned char*) buf;
192 return (p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3];
195 /* Read an unaligned 32-bit little endian long from buffer. */
196 static long get_slong(void* buf)
198 unsigned char* p = (unsigned char*) buf;
200 return p[0] | (p[1] << 8) | (p[2] << 16) | (p[3] << 24);
203 /* Parse the tag (the name-value pair) and fill id3 and buffer accordingly.
204 * String values to keep are written to buf. Returns number of bytes written
205 * to buf (including end nil).
207 static long parse_tag(const char* name, char* value, struct mp3entry* id3,
208 char* buf, long buf_remaining, enum tagtype type)
210 long len = 0;
211 char** p;
213 if ((((strcasecmp(name, "track") == 0) && (type == TAGTYPE_APE)))
214 || ((strcasecmp(name, "tracknumber") == 0) && (type == TAGTYPE_VORBIS)))
216 id3->tracknum = atoi(value);
217 p = &(id3->track_string);
219 else if (((strcasecmp(name, "year") == 0) && (type == TAGTYPE_APE))
220 || ((strcasecmp(name, "date") == 0) && (type == TAGTYPE_VORBIS)))
222 /* Date's can be in any format in Vorbis. However most of them
223 * are in ISO8601 format so if we try and parse the first part
224 * of the tag as a number, we should get the year. If we get crap,
225 * then act like we never parsed it.
227 id3->year = atoi(value);
228 if (id3->year < 1900)
229 { /* yeah, not likely */
230 id3->year = 0;
232 p = &(id3->year_string);
234 else if (strcasecmp(name, "title") == 0)
236 p = &(id3->title);
238 else if (strcasecmp(name, "artist") == 0)
240 p = &(id3->artist);
242 else if (strcasecmp(name, "album") == 0)
244 p = &(id3->album);
246 else if (strcasecmp(name, "genre") == 0)
248 p = &(id3->genre_string);
250 else if (strcasecmp(name, "composer") == 0)
252 p = &(id3->composer);
254 else if (strcasecmp(name, "comment") == 0)
256 p = &(id3->comment);
258 else if (strcasecmp(name, "albumartist") == 0)
260 p = &(id3->albumartist);
262 else if (strcasecmp(name, "album artist") == 0)
264 p = &(id3->albumartist);
266 else if (strcasecmp(name, "ensemble") == 0)
268 p = &(id3->albumartist);
270 else
272 len = parse_replaygain(name, value, id3, buf, buf_remaining);
273 p = NULL;
276 if (p)
278 len = strlen(value);
279 len = MIN(len, buf_remaining - 1);
281 if (len > 0)
283 strncpy(buf, value, len);
284 buf[len] = 0;
285 *p = buf;
286 len++;
288 else
290 len = 0;
294 return len;
297 /* Read the items in an APEV2 tag. Only looks for a tag at the end of a
298 * file. Returns true if a tag was found and fully read, false otherwise.
300 static bool read_ape_tags(int fd, struct mp3entry* id3)
302 struct apetag_header header;
304 if ((lseek(fd, -APETAG_HEADER_LENGTH, SEEK_END) < 0)
305 || (ecread(fd, &header, 1, APETAG_HEADER_FORMAT, IS_BIG_ENDIAN) != APETAG_HEADER_LENGTH)
306 || (memcmp(header.id, "APETAGEX", sizeof(header.id))))
308 return false;
311 if ((header.version == 2000) && (header.item_count > 0)
312 && (header.length > APETAG_HEADER_LENGTH))
314 char *buf = id3->id3v2buf;
315 unsigned int buf_remaining = sizeof(id3->id3v2buf)
316 + sizeof(id3->id3v1buf);
317 unsigned int tag_remaining = header.length - APETAG_HEADER_LENGTH;
318 int i;
320 if (lseek(fd, -header.length, SEEK_END) < 0)
322 return false;
325 for (i = 0; i < header.item_count; i++)
327 struct apetag_item_header item;
328 char name[TAG_NAME_LENGTH];
329 char value[TAG_VALUE_LENGTH];
330 long r;
332 if (tag_remaining < sizeof(item))
334 break;
337 if (ecread(fd, &item, 1, APETAG_ITEM_HEADER_FORMAT, IS_BIG_ENDIAN) < (long) sizeof(item))
339 return false;
342 tag_remaining -= sizeof(item);
343 r = read_string(fd, name, sizeof(name), 0, tag_remaining);
345 if (r == -1)
347 return false;
350 tag_remaining -= r + item.length;
352 if ((item.flags & APETAG_ITEM_TYPE_MASK) == 0)
354 long len;
356 if (read_string(fd, value, sizeof(value), -1, item.length)
357 != item.length)
359 return false;
362 len = parse_tag(name, value, id3, buf, buf_remaining,
363 TAGTYPE_APE);
364 buf += len;
365 buf_remaining -= len;
367 else
369 if (lseek(fd, item.length, SEEK_CUR) < 0)
371 return false;
377 return true;
380 /* Read the items in a Vorbis comment packet. Returns true the items were
381 * fully read, false otherwise.
383 static bool read_vorbis_tags(int fd, struct mp3entry *id3,
384 long tag_remaining)
386 char *buf = id3->id3v2buf;
387 long comment_count;
388 long len;
389 int buf_remaining = sizeof(id3->id3v2buf) + sizeof(id3->id3v1buf);
390 int i;
392 if (ecread(fd, &len, 1, "l", IS_BIG_ENDIAN) < (long) sizeof(len))
394 return false;
397 if ((lseek(fd, len, SEEK_CUR) < 0)
398 || (ecread(fd, &comment_count, 1, "l", IS_BIG_ENDIAN)
399 < (long) sizeof(comment_count)))
401 return false;
404 tag_remaining -= len + sizeof(len) + sizeof(comment_count);
406 if (tag_remaining <= 0)
408 return true;
411 for (i = 0; i < comment_count; i++)
413 char name[TAG_NAME_LENGTH];
414 char value[TAG_VALUE_LENGTH];
415 long read_len;
417 if (tag_remaining < 4)
419 break;
422 if (ecread(fd, &len, 1, "l", IS_BIG_ENDIAN) < (long) sizeof(len))
424 return false;
427 tag_remaining -= 4;
429 /* Quit if we've passed the end of the page */
430 if (tag_remaining < len)
432 break;
435 tag_remaining -= len;
436 read_len = read_string(fd, name, sizeof(name), '=', len);
438 if (read_len < 0)
440 return false;
443 len -= read_len;
445 if (read_string(fd, value, sizeof(value), -1, len) < 0)
447 return false;
450 len = parse_tag(name, value, id3, buf, buf_remaining,
451 TAGTYPE_VORBIS);
452 buf += len;
453 buf_remaining -= len;
456 /* Skip to the end of the block */
457 if (tag_remaining)
459 if (lseek(fd, tag_remaining, SEEK_CUR) < 0)
461 return false;
465 return true;
468 /* Skip an ID3v2 tag if it can be found. We assume the tag is located at the
469 * start of the file, which should be true in all cases where we need to skip it.
470 * Returns true if successfully skipped or not skipped, and false if
471 * something went wrong while skipping.
473 static bool skip_id3v2(int fd, struct mp3entry *id3)
475 char buf[4];
477 read(fd, buf, 4);
478 if (memcmp(buf, "ID3", 3) == 0)
480 /* We have found an ID3v2 tag at the start of the file - find its
481 length and then skip it. */
482 if ((id3->first_frame_offset = getid3v2len(fd)) == 0)
483 return false;
485 if ((lseek(fd, id3->first_frame_offset, SEEK_SET) < 0))
486 return false;
488 return true;
489 } else {
490 lseek(fd, 0, SEEK_SET);
491 id3->first_frame_offset = 0;
492 return true;
496 /* A simple parser to read vital metadata from an Ogg Speex file. Returns
497 * false if metadata needed by the Speex codec couldn't be read.
500 static bool get_speex_metadata(int fd, struct mp3entry* id3)
502 /* An Ogg File is split into pages, each starting with the string
503 * "OggS". Each page has a timestamp (in PCM samples) referred to as
504 * the "granule position".
506 * An Ogg Speex has the following structure:
507 * 1) Identification header (containing samplerate, numchannels, etc)
508 Described in this page: (http://www.speex.org/manual2/node7.html)
509 * 2) Comment header - containing the Vorbis Comments
510 * 3) Many audio packets...
513 /* Use the path name of the id3 structure as a temporary buffer. */
514 unsigned char* buf = (unsigned char*)id3->path;
515 long comment_size;
516 long remaining = 0;
517 long last_serial = 0;
518 long serial, r;
519 int segments;
520 int i;
521 bool eof = false;
523 if ((lseek(fd, 0, SEEK_SET) < 0) || (read(fd, buf, 58) < 33))
525 return false;
528 if ((memcmp(buf, "OggS", 4) != 0) || (memcmp(&buf[28], "Speex", 5) != 0))
530 return false;
533 /* We need to ensure the serial number from this page is the same as the
534 * one from the last page (since we only support a single bitstream).
536 serial = get_long_le(&buf[14]);
537 if ((lseek(fd, 33, SEEK_SET) < 0)||(read(fd, buf, 58) < 4))
539 return false;
542 id3->frequency = get_slong(&buf[31]);
543 last_serial = get_long_le(&buf[27]);/*temporary, header size*/
544 id3->bitrate = get_long_le(&buf[47]);
545 id3->vbr = get_long_le(&buf[55]);
546 id3->filesize = filesize(fd);
547 /* Comments are in second Ogg page */
548 if (lseek(fd, 28+last_serial/*(temporary for header size)*/, SEEK_SET) < 0)
550 return false;
553 /* Minimum header length for Ogg pages is 27. */
554 if (read(fd, buf, 27) < 27)
556 return false;
559 if (memcmp(buf, "OggS", 4) !=0 )
561 return false;
564 segments = buf[26];
565 /* read in segment table */
566 if (read(fd, buf, segments) < segments)
568 return false;
571 /* The second packet in a vorbis stream is the comment packet. It *may*
572 * extend beyond the second page, but usually does not. Here we find the
573 * length of the comment packet (or the rest of the page if the comment
574 * packet extends to the third page).
576 for (i = 0; i < segments; i++)
578 remaining += buf[i];
579 /* The last segment of a packet is always < 255 bytes */
580 if (buf[i] < 255)
582 break;
586 comment_size = remaining;
588 /* Failure to read the tags isn't fatal. */
589 read_vorbis_tags(fd, id3, remaining);
591 /* We now need to search for the last page in the file - identified by
592 * by ('O','g','g','S',0) and retrieve totalsamples.
595 /* A page is always < 64 kB */
596 if (lseek(fd, -(MIN(64 * 1024, id3->filesize)), SEEK_END) < 0)
598 return false;
601 remaining = 0;
603 while (!eof)
605 r = read(fd, &buf[remaining], MAX_PATH - remaining);
607 if (r <= 0)
609 eof = true;
611 else
613 remaining += r;
616 /* Inefficient (but simple) search */
617 i = 0;
619 while (i < (remaining - 3))
621 if ((buf[i] == 'O') && (memcmp(&buf[i], "OggS", 4) == 0))
623 if (i < (remaining - 17))
625 /* Note that this only reads the low 32 bits of a
626 * 64 bit value.
628 id3->samples = get_long_le(&buf[i + 6]);
629 last_serial = get_long_le(&buf[i + 14]);
631 /* If this page is very small the beginning of the next
632 * header could be in buffer. Jump near end of this header
633 * and continue */
634 i += 27;
636 else
638 break;
641 else
643 i++;
647 if (i < remaining)
649 /* Move the remaining bytes to start of buffer.
650 * Reuse var 'segments' as it is no longer needed */
651 segments = 0;
652 while (i < remaining)
654 buf[segments++] = buf[i++];
656 remaining = segments;
658 else
660 /* Discard the rest of the buffer */
661 remaining = 0;
665 /* This file has mutiple vorbis bitstreams (or is corrupt). */
666 /* FIXME we should display an error here. */
667 if (serial != last_serial)
669 logf("serialno mismatch");
670 logf("%ld", serial);
671 logf("%ld", last_serial);
672 return false;
675 id3->length = (id3->samples / id3->frequency) * 1000;
676 id3->bitrate = (((int64_t) id3->filesize - comment_size) * 8) / id3->length;
677 return true;
681 /* A simple parser to read vital metadata from an Ogg Vorbis file.
682 * Calls get_speex_metadata if a speex file is identified. Returns
683 * false if metadata needed by the Vorbis codec couldn't be read.
685 static bool get_vorbis_metadata(int fd, struct mp3entry* id3)
687 /* An Ogg File is split into pages, each starting with the string
688 * "OggS". Each page has a timestamp (in PCM samples) referred to as
689 * the "granule position".
691 * An Ogg Vorbis has the following structure:
692 * 1) Identification header (containing samplerate, numchannels, etc)
693 * 2) Comment header - containing the Vorbis Comments
694 * 3) Setup header - containing codec setup information
695 * 4) Many audio packets...
698 /* Use the path name of the id3 structure as a temporary buffer. */
699 unsigned char* buf = (unsigned char *)id3->path;
700 long comment_size;
701 long remaining = 0;
702 long last_serial = 0;
703 long serial, r;
704 int segments;
705 int i;
706 bool eof = false;
708 if ((lseek(fd, 0, SEEK_SET) < 0) || (read(fd, buf, 58) < 4))
710 return false;
713 if ((memcmp(buf, "OggS", 4) != 0) || (memcmp(&buf[29], "vorbis", 6) != 0))
715 if ((memcmp(buf, "OggS", 4) != 0) || (memcmp(&buf[28], "Speex", 5) != 0))
717 return false;
719 else
721 id3->codectype = AFMT_SPEEX;
722 return get_speex_metadata(fd, id3);
726 /* We need to ensure the serial number from this page is the same as the
727 * one from the last page (since we only support a single bitstream).
729 serial = get_long_le(&buf[14]);
730 id3->frequency = get_long_le(&buf[40]);
731 id3->filesize = filesize(fd);
733 /* Comments are in second Ogg page */
734 if (lseek(fd, 58, SEEK_SET) < 0)
736 return false;
739 /* Minimum header length for Ogg pages is 27. */
740 if (read(fd, buf, 27) < 27)
742 return false;
745 if (memcmp(buf, "OggS", 4) !=0 )
747 return false;
750 segments = buf[26];
752 /* read in segment table */
753 if (read(fd, buf, segments) < segments)
755 return false;
758 /* The second packet in a vorbis stream is the comment packet. It *may*
759 * extend beyond the second page, but usually does not. Here we find the
760 * length of the comment packet (or the rest of the page if the comment
761 * packet extends to the third page).
763 for (i = 0; i < segments; i++)
765 remaining += buf[i];
767 /* The last segment of a packet is always < 255 bytes */
768 if (buf[i] < 255)
770 break;
774 /* Now read in packet header (type and id string) */
775 if (read(fd, buf, 7) < 7)
777 return false;
780 comment_size = remaining;
781 remaining -= 7;
783 /* The first byte of a packet is the packet type; comment packets are
784 * type 3.
786 if ((buf[0] != 3) || (memcmp(buf + 1, "vorbis", 6) !=0))
788 return false;
791 /* Failure to read the tags isn't fatal. */
792 read_vorbis_tags(fd, id3, remaining);
794 /* We now need to search for the last page in the file - identified by
795 * by ('O','g','g','S',0) and retrieve totalsamples.
798 /* A page is always < 64 kB */
799 if (lseek(fd, -(MIN(64 * 1024, id3->filesize)), SEEK_END) < 0)
801 return false;
804 remaining = 0;
806 while (!eof)
808 r = read(fd, &buf[remaining], MAX_PATH - remaining);
810 if (r <= 0)
812 eof = true;
814 else
816 remaining += r;
819 /* Inefficient (but simple) search */
820 i = 0;
822 while (i < (remaining - 3))
824 if ((buf[i] == 'O') && (memcmp(&buf[i], "OggS", 4) == 0))
826 if (i < (remaining - 17))
828 /* Note that this only reads the low 32 bits of a
829 * 64 bit value.
831 id3->samples = get_long_le(&buf[i + 6]);
832 last_serial = get_long_le(&buf[i + 14]);
834 /* If this page is very small the beginning of the next
835 * header could be in buffer. Jump near end of this header
836 * and continue */
837 i += 27;
839 else
841 break;
844 else
846 i++;
850 if (i < remaining)
852 /* Move the remaining bytes to start of buffer.
853 * Reuse var 'segments' as it is no longer needed */
854 segments = 0;
855 while (i < remaining)
857 buf[segments++] = buf[i++];
859 remaining = segments;
861 else
863 /* Discard the rest of the buffer */
864 remaining = 0;
868 /* This file has mutiple vorbis bitstreams (or is corrupt). */
869 /* FIXME we should display an error here. */
870 if (serial != last_serial)
872 logf("serialno mismatch");
873 logf("%ld", serial);
874 logf("%ld", last_serial);
875 return false;
878 id3->length = ((int64_t) id3->samples * 1000) / id3->frequency;
880 if (id3->length <= 0)
882 logf("ogg length invalid!");
883 return false;
886 id3->bitrate = (((int64_t) id3->filesize - comment_size) * 8) / id3->length;
887 id3->vbr = true;
889 return true;
892 static bool get_flac_metadata(int fd, struct mp3entry* id3)
894 /* A simple parser to read vital metadata from a FLAC file - length,
895 * frequency, bitrate etc. This code should either be moved to a
896 * seperate file, or discarded in favour of the libFLAC code.
897 * The FLAC stream specification can be found at
898 * http://flac.sourceforge.net/format.html#stream
901 /* Use the trackname part of the id3 structure as a temporary buffer */
902 unsigned char* buf = (unsigned char *)id3->path;
903 bool rc = false;
905 if (!skip_id3v2(fd, id3) || (read(fd, buf, 4) < 4))
907 return rc;
910 if (memcmp(buf, "fLaC", 4) != 0)
912 return rc;
915 while (true)
917 long i;
919 if (read(fd, buf, 4) < 0)
921 return rc;
924 /* The length of the block */
925 i = (buf[1] << 16) | (buf[2] << 8) | buf[3];
927 if ((buf[0] & 0x7f) == 0) /* 0 is the STREAMINFO block */
929 unsigned long totalsamples;
931 /* FIXME: Don't trust the value of i */
932 if (read(fd, buf, i) < 0)
934 return rc;
937 id3->vbr = true; /* All FLAC files are VBR */
938 id3->filesize = filesize(fd);
939 id3->frequency = (buf[10] << 12) | (buf[11] << 4)
940 | ((buf[12] & 0xf0) >> 4);
941 rc = true; /* Got vital metadata */
943 /* totalsamples is a 36-bit field, but we assume <= 32 bits are used */
944 totalsamples = get_long_be(&buf[14]);
946 /* Calculate track length (in ms) and estimate the bitrate (in kbit/s) */
947 id3->length = ((int64_t) totalsamples * 1000) / id3->frequency;
949 if (id3->length <= 0)
951 logf("flac length invalid!");
952 return false;
955 id3->bitrate = (id3->filesize * 8) / id3->length;
957 else if ((buf[0] & 0x7f) == 4) /* 4 is the VORBIS_COMMENT block */
959 /* The next i bytes of the file contain the VORBIS COMMENTS. */
960 if (!read_vorbis_tags(fd, id3, i))
962 return rc;
965 else
967 if (buf[0] & 0x80)
969 /* If we have reached the last metadata block, abort. */
970 break;
972 else
974 /* Skip to next metadata block */
975 if (lseek(fd, i, SEEK_CUR) < 0)
977 return rc;
983 return true;
986 static bool get_wave_metadata(int fd, struct mp3entry* id3)
988 /* Use the trackname part of the id3 structure as a temporary buffer */
989 unsigned char* buf = (unsigned char *)id3->path;
990 unsigned long totalsamples = 0;
991 unsigned long channels = 0;
992 unsigned long bitspersample = 0;
993 unsigned long numbytes = 0;
994 int read_bytes;
995 int i;
997 /* get RIFF chunk header */
998 if ((lseek(fd, 0, SEEK_SET) < 0)
999 || ((read_bytes = read(fd, buf, 12)) < 12))
1001 return false;
1004 if ((memcmp(buf, "RIFF",4) != 0)
1005 || (memcmp(&buf[8], "WAVE", 4) !=0 ))
1007 return false;
1010 /* iterate over WAVE chunks until 'data' chunk */
1011 while (true)
1013 /* get chunk header */
1014 if ((read_bytes = read(fd, buf, 8)) < 8)
1015 return false;
1017 /* chunkSize */
1018 i = get_long_le(&buf[4]);
1020 if (memcmp(buf, "fmt ", 4) == 0)
1022 /* get rest of chunk */
1023 if ((read_bytes = read(fd, buf, 16)) < 16)
1024 return false;
1026 i -= 16;
1028 /* skipping wFormatTag */
1029 /* wChannels */
1030 channels = buf[2] | (buf[3] << 8);
1031 /* dwSamplesPerSec */
1032 id3->frequency = get_long_le(&buf[4]);
1033 /* dwAvgBytesPerSec */
1034 id3->bitrate = (get_long_le(&buf[8]) * 8) / 1000;
1035 /* skipping wBlockAlign */
1036 /* wBitsPerSample */
1037 bitspersample = buf[14] | (buf[15] << 8);
1039 else if (memcmp(buf, "data", 4) == 0)
1041 numbytes = i;
1042 break;
1044 else if (memcmp(buf, "fact", 4) == 0)
1046 /* dwSampleLength */
1047 if (i >= 4)
1049 /* get rest of chunk */
1050 if ((read_bytes = read(fd, buf, 2)) < 2)
1051 return false;
1053 i -= 2;
1054 totalsamples = get_long_le(buf);
1058 /* seek to next chunk (even chunk sizes must be padded) */
1059 if (i & 0x01)
1060 i++;
1062 if(lseek(fd, i, SEEK_CUR) < 0)
1063 return false;
1066 if ((numbytes == 0) || (channels == 0))
1068 return false;
1071 if (totalsamples == 0)
1073 /* for PCM only */
1074 totalsamples = numbytes
1075 / ((((bitspersample - 1) / 8) + 1) * channels);
1078 id3->vbr = false; /* All WAV files are CBR */
1079 id3->filesize = filesize(fd);
1081 /* Calculate track length (in ms) and estimate the bitrate (in kbit/s) */
1082 id3->length = ((int64_t) totalsamples * 1000) / id3->frequency;
1084 return true;
1087 /* Read the tag data from an MP4 file, storing up to buffer_size bytes in
1088 * buffer.
1090 static unsigned long read_mp4_tag(int fd, unsigned int size_left, char* buffer,
1091 unsigned int buffer_left)
1093 unsigned int bytes_read = 0;
1095 if (buffer_left == 0)
1097 lseek(fd, size_left, SEEK_CUR); /* Skip everything */
1099 else
1101 /* Skip the data tag header - maybe we should parse it properly? */
1102 lseek(fd, 16, SEEK_CUR);
1103 size_left -= 16;
1105 if (size_left > buffer_left)
1107 read(fd, buffer, buffer_left);
1108 lseek(fd, size_left - buffer_left, SEEK_CUR);
1109 bytes_read = buffer_left;
1111 else
1113 read(fd, buffer, size_left);
1114 bytes_read = size_left;
1118 return bytes_read;
1121 /* Read a string tag from an MP4 file */
1122 static unsigned int read_mp4_tag_string(int fd, int size_left, char** buffer,
1123 unsigned int* buffer_left, char** dest)
1125 unsigned int bytes_read = read_mp4_tag(fd, size_left, *buffer,
1126 *buffer_left - 1);
1127 unsigned int length = 0;
1129 if (bytes_read)
1131 (*buffer)[bytes_read] = 0;
1132 *dest = *buffer;
1133 length = strlen(*buffer) + 1;
1134 *buffer_left -= length;
1135 *buffer += length;
1137 else
1139 *dest = NULL;
1142 return length;
1145 static unsigned int read_mp4_atom(int fd, unsigned int* size,
1146 unsigned int* type, unsigned int size_left)
1148 read_uint32be(fd, size);
1149 read_uint32be(fd, type);
1151 if (*size == 1)
1153 /* FAT32 doesn't support files this big, so something seems to
1154 * be wrong. (64-bit sizes should only be used when required.)
1156 errno = EFBIG;
1157 *type = 0;
1158 return 0;
1161 if (*size > 0)
1163 if (*size > size_left)
1165 size_left = 0;
1167 else
1169 size_left -= *size;
1172 *size -= 8;
1174 else
1176 *size = size_left;
1177 size_left = 0;
1180 return size_left;
1183 static unsigned int read_mp4_length(int fd, unsigned int* size)
1185 unsigned int length = 0;
1186 int bytes = 0;
1187 unsigned char c;
1191 read(fd, &c, 1);
1192 bytes++;
1193 (*size)--;
1194 length = (length << 7) | (c & 0x7F);
1196 while ((c & 0x80) && (bytes < 4) && (*size > 0));
1198 return length;
1201 static bool read_mp4_esds(int fd, struct mp3entry* id3,
1202 unsigned int* size)
1204 unsigned char buf[8];
1205 bool sbr = false;
1207 lseek(fd, 4, SEEK_CUR); /* Version and flags. */
1208 read(fd, buf, 1); /* Verify ES_DescrTag. */
1209 *size -= 5;
1211 if (*buf == 3)
1213 /* read length */
1214 if (read_mp4_length(fd, size) < 20)
1216 return sbr;
1219 lseek(fd, 3, SEEK_CUR);
1220 *size -= 3;
1222 else
1224 lseek(fd, 2, SEEK_CUR);
1225 *size -= 2;
1228 read(fd, buf, 1); /* Verify DecoderConfigDescrTab. */
1229 *size -= 1;
1231 if (*buf != 4)
1233 return sbr;
1236 if (read_mp4_length(fd, size) < 13)
1238 return sbr;
1241 lseek(fd, 13, SEEK_CUR); /* Skip audio type, bit rates, etc. */
1242 read(fd, buf, 1);
1243 *size -= 14;
1245 if (*buf != 5) /* Verify DecSpecificInfoTag. */
1247 return sbr;
1251 static const int sample_rates[] =
1253 96000, 88200, 64000, 48000, 44100, 32000,
1254 24000, 22050, 16000, 12000, 11025, 8000
1256 unsigned long bits;
1257 unsigned int length;
1258 unsigned int index;
1259 int type;
1261 /* Read the (leading part of the) decoder config. */
1262 length = read_mp4_length(fd, size);
1263 length = MIN(length, *size);
1264 length = MIN(length, sizeof(buf));
1265 read(fd, buf, length);
1266 *size -= length;
1268 /* Decoder config format:
1269 * Object type - 5 bits
1270 * Frequency index - 4 bits
1271 * Channel configuration - 4 bits
1273 bits = get_long_be(buf);
1274 type = bits >> 27;
1275 index = (bits >> 23) & 0xf;
1277 if (index < (sizeof(sample_rates) / sizeof(*sample_rates)))
1279 id3->frequency = sample_rates[index];
1282 if (type == 5)
1284 sbr = true;
1285 /* Extended frequency index - 4 bits */
1286 index = (bits >> 15) & 0xf;
1288 if (index == 15)
1290 /* 17 bits read so far... */
1291 bits = get_long_be(&buf[2]);
1292 id3->frequency = (bits >> 7) & 0x00FFFFFF;
1294 else if (index < (sizeof(sample_rates) / sizeof(*sample_rates)))
1296 id3->frequency = sample_rates[index];
1299 else if (id3->frequency < 24000)
1301 /* SBR not indicated, but the file might still contain SBR.
1302 * MPEG specification says that one should assume SBR if
1303 * samplerate <= 24000 Hz.
1305 id3->frequency *= 2;
1306 sbr = true;
1310 return sbr;
1313 static bool read_mp4_tags(int fd, struct mp3entry* id3,
1314 unsigned int size_left)
1316 unsigned int size;
1317 unsigned int type;
1318 unsigned int buffer_left = sizeof(id3->id3v2buf) + sizeof(id3->id3v1buf);
1319 char* buffer = id3->id3v2buf;
1320 bool cwrt = false;
1324 size_left = read_mp4_atom(fd, &size, &type, size_left);
1326 /* DEBUGF("Tag atom: '%c%c%c%c' (%d bytes left)\n", type >> 24 & 0xff,
1327 type >> 16 & 0xff, type >> 8 & 0xff, type & 0xff, size); */
1329 switch (type)
1331 case MP4_cnam:
1332 read_mp4_tag_string(fd, size, &buffer, &buffer_left,
1333 &id3->title);
1334 break;
1336 case MP4_cART:
1337 read_mp4_tag_string(fd, size, &buffer, &buffer_left,
1338 &id3->artist);
1339 break;
1341 case MP4_calb:
1342 read_mp4_tag_string(fd, size, &buffer, &buffer_left,
1343 &id3->album);
1344 break;
1346 case MP4_cwrt:
1347 read_mp4_tag_string(fd, size, &buffer, &buffer_left,
1348 &id3->composer);
1349 cwrt = false;
1350 break;
1352 case MP4_gnre:
1354 unsigned short genre;
1356 read_mp4_tag(fd, size, (char*) &genre, sizeof(genre));
1357 id3->genre_string = id3_get_num_genre(betoh16(genre));
1359 break;
1361 case MP4_trkn:
1363 unsigned short n[2];
1365 read_mp4_tag(fd, size, (char*) &n, sizeof(n));
1366 id3->tracknum = betoh16(n[1]);
1368 break;
1370 case MP4_extra:
1372 char tag_name[TAG_NAME_LENGTH];
1373 unsigned int sub_size;
1375 /* "mean" atom */
1376 read_uint32be(fd, &sub_size);
1377 size -= sub_size;
1378 lseek(fd, sub_size - 4, SEEK_CUR);
1379 /* "name" atom */
1380 read_uint32be(fd, &sub_size);
1381 size -= sub_size;
1382 lseek(fd, 8, SEEK_CUR);
1383 sub_size -= 12;
1385 if (sub_size > sizeof(tag_name) - 1)
1387 read(fd, tag_name, sizeof(tag_name) - 1);
1388 lseek(fd, sub_size - sizeof(tag_name) - 1, SEEK_CUR);
1389 tag_name[sizeof(tag_name) - 1] = 0;
1391 else
1393 read(fd, tag_name, sub_size);
1394 tag_name[sub_size] = 0;
1397 if ((strcasecmp(tag_name, "composer") == 0) && !cwrt)
1399 read_mp4_tag_string(fd, size, &buffer, &buffer_left,
1400 &id3->composer);
1402 else
1404 char* any;
1405 unsigned int length = read_mp4_tag_string(fd, size,
1406 &buffer, &buffer_left, &any);
1408 if (length > 0)
1410 /* Re-use the read buffer as the dest buffer... */
1411 buffer -= length;
1412 buffer_left += length;
1414 if (parse_replaygain(tag_name, buffer, id3,
1415 buffer, buffer_left) > 0)
1417 /* Data used, keep it. */
1418 buffer += length;
1419 buffer_left -= length;
1424 break;
1426 default:
1427 lseek(fd, size, SEEK_CUR);
1428 break;
1431 while ((size_left > 0) && (errno == 0));
1433 return true;
1436 static bool read_mp4_container(int fd, struct mp3entry* id3,
1437 unsigned int size_left)
1439 unsigned int size;
1440 unsigned int type;
1441 unsigned int handler = 0;
1442 bool rc = true;
1446 size_left = read_mp4_atom(fd, &size, &type, size_left);
1448 /* DEBUGF("Atom: '%c%c%c%c' (0x%08x, %d bytes left)\n",
1449 (type >> 24) & 0xff, (type >> 16) & 0xff, (type >> 8) & 0xff,
1450 type & 0xff, type, size); */
1452 switch (type)
1454 case MP4_ftyp:
1456 unsigned int id;
1458 read_uint32be(fd, &id);
1459 size -= 4;
1461 if ((id != MP4_M4A) && (id != MP4_M4B) && (id != MP4_mp42)
1462 && (id != MP4_qt) && (id != MP4_3gp6))
1464 DEBUGF("Unknown MP4 file type: '%c%c%c%c'\n",
1465 id >> 24 & 0xff, id >> 16 & 0xff, id >> 8 & 0xff,
1466 id & 0xff);
1467 return false;
1470 break;
1472 case MP4_meta:
1473 lseek(fd, 4, SEEK_CUR); /* Skip version */
1474 size -= 4;
1475 /* Fall through */
1477 case MP4_moov:
1478 case MP4_udta:
1479 case MP4_mdia:
1480 case MP4_stbl:
1481 case MP4_trak:
1482 rc = read_mp4_container(fd, id3, size);
1483 size = 0;
1484 break;
1486 case MP4_ilst:
1487 if (handler == MP4_mdir)
1489 rc = read_mp4_tags(fd, id3, size);
1490 size = 0;
1492 break;
1494 case MP4_minf:
1495 if (handler == MP4_soun)
1497 rc = read_mp4_container(fd, id3, size);
1498 size = 0;
1500 break;
1502 case MP4_stsd:
1503 lseek(fd, 8, SEEK_CUR);
1504 size -= 8;
1505 rc = read_mp4_container(fd, id3, size);
1506 size = 0;
1507 break;
1509 case MP4_hdlr:
1510 lseek(fd, 8, SEEK_CUR);
1511 read_uint32be(fd, &handler);
1512 size -= 12;
1513 /* DEBUGF(" Handler '%c%c%c%c'\n", handler >> 24 & 0xff,
1514 handler >> 16 & 0xff, handler >> 8 & 0xff,handler & 0xff); */
1515 break;
1517 case MP4_stts:
1519 unsigned int entries;
1520 unsigned int i;
1522 lseek(fd, 4, SEEK_CUR);
1523 read_uint32be(fd, &entries);
1524 id3->samples = 0;
1526 for (i = 0; i < entries; i++)
1528 unsigned int n;
1529 unsigned int l;
1531 read_uint32be(fd, &n);
1532 read_uint32be(fd, &l);
1533 id3->samples += n * l;
1536 size = 0;
1538 break;
1540 case MP4_mp4a:
1541 case MP4_alac:
1543 unsigned int frequency;
1545 id3->codectype = (type == MP4_mp4a) ? AFMT_AAC : AFMT_ALAC;
1546 lseek(fd, 22, SEEK_CUR);
1547 read_uint32be(fd, &frequency);
1548 size -= 26;
1549 id3->frequency = frequency;
1551 if (type == MP4_mp4a)
1553 unsigned int subsize;
1554 unsigned int subtype;
1556 /* Get frequency from the decoder info tag, if possible. */
1557 lseek(fd, 2, SEEK_CUR);
1558 /* The esds atom is a part of the mp4a atom, so ignore
1559 * the returned size (it's already accounted for).
1561 read_mp4_atom(fd, &subsize, &subtype, size);
1562 size -= 10;
1564 if (subtype == MP4_esds)
1566 read_mp4_esds(fd, id3, &size);
1570 break;
1572 case MP4_mdat:
1573 id3->filesize = size;
1574 break;
1576 default:
1577 break;
1580 lseek(fd, size, SEEK_CUR);
1582 while (rc && (size_left > 0) && (errno == 0) && (id3->filesize == 0));
1583 /* Break on non-zero filesize, since Rockbox currently doesn't support
1584 * metadata after the mdat atom (which sets the filesize field).
1587 return rc;
1590 static bool get_mp4_metadata(int fd, struct mp3entry* id3)
1592 id3->codectype = AFMT_UNKNOWN;
1593 id3->filesize = 0;
1594 errno = 0;
1596 if (read_mp4_container(fd, id3, filesize(fd)) && (errno == 0)
1597 && (id3->samples > 0) && (id3->frequency > 0)
1598 && (id3->filesize > 0))
1600 if (id3->codectype == AFMT_UNKNOWN)
1602 logf("Not an ALAC or AAC file");
1603 return false;
1606 id3->length = ((int64_t) id3->samples * 1000) / id3->frequency;
1608 if (id3->length <= 0)
1610 logf("mp4 length invalid!");
1611 return false;
1614 id3->bitrate = ((int64_t) id3->filesize * 8) / id3->length;
1615 DEBUGF("MP4 bitrate %d, frequency %d Hz, length %d ms\n",
1616 id3->bitrate, id3->frequency, id3->length);
1618 else
1620 logf("MP4 metadata error");
1621 DEBUGF("MP4 metadata error. errno %d, length %d, frequency %d, filesize %d\n",
1622 errno, id3->length, id3->frequency, id3->filesize);
1623 return false;
1626 return true;
1629 static bool get_musepack_metadata(int fd, struct mp3entry *id3)
1631 const int32_t sfreqs_sv7[4] = { 44100, 48000, 37800, 32000 };
1632 uint32_t header[8];
1633 uint64_t samples = 0;
1634 int i;
1636 if (!skip_id3v2(fd, id3))
1637 return false;
1638 if (read(fd, header, 4*8) != 4*8) return false;
1639 /* Musepack files are little endian, might need swapping */
1640 for (i = 1; i < 8; i++)
1641 header[i] = letoh32(header[i]);
1642 if (!memcmp(header, "MP+", 3)) { /* Compare to sig "MP+" */
1643 unsigned int streamversion;
1645 header[0] = letoh32(header[0]);
1646 streamversion = (header[0] >> 24) & 15;
1647 if (streamversion >= 8) {
1648 return false; /* SV8 or higher don't exist yet, so no support */
1649 } else if (streamversion == 7) {
1650 unsigned int gapless = (header[5] >> 31) & 0x0001;
1651 unsigned int last_frame_samples = (header[5] >> 20) & 0x07ff;
1652 int track_gain, album_gain;
1653 unsigned int bufused;
1655 id3->frequency = sfreqs_sv7[(header[2] >> 16) & 0x0003];
1656 samples = (uint64_t)header[1]*1152; /* 1152 is mpc frame size */
1657 if (gapless)
1658 samples -= 1152 - last_frame_samples;
1659 else
1660 samples -= 481; /* Musepack subband synth filter delay */
1662 /* Extract ReplayGain data from header */
1663 track_gain = (int16_t)((header[3] >> 16) & 0xffff);
1664 id3->track_gain = get_replaygain_int(track_gain);
1665 id3->track_peak = ((uint16_t)(header[3] & 0xffff)) << 9;
1667 album_gain = (int16_t)((header[4] >> 16) & 0xffff);
1668 id3->album_gain = get_replaygain_int(album_gain);
1669 id3->album_peak = ((uint16_t)(header[4] & 0xffff)) << 9;
1671 /* Write replaygain values to strings for use in id3 screen. We use
1672 the XING header as buffer space since Musepack files shouldn't
1673 need to use it in any other way */
1674 id3->track_gain_string = (char *)id3->toc;
1675 bufused = snprintf(id3->track_gain_string, 45,
1676 "%d.%d dB", track_gain/100, abs(track_gain)%100);
1677 id3->album_gain_string = (char *)id3->toc + bufused + 1;
1678 bufused = snprintf(id3->album_gain_string, 45,
1679 "%d.%d dB", album_gain/100, abs(album_gain)%100);
1681 } else {
1682 header[0] = letoh32(header[0]);
1683 unsigned int streamversion = (header[0] >> 11) & 0x03FF;
1684 if (streamversion != 4 && streamversion != 5 && streamversion != 6)
1685 return false;
1686 id3->frequency = 44100;
1687 id3->track_gain = 0;
1688 id3->track_peak = 0;
1689 id3->album_gain = 0;
1690 id3->album_peak = 0;
1692 if (streamversion >= 5)
1693 samples = (uint64_t)header[1]*1152; // 32 bit
1694 else
1695 samples = (uint64_t)(header[1] >> 16)*1152; // 16 bit
1697 samples -= 576;
1698 if (streamversion < 6)
1699 samples -= 1152;
1702 id3->vbr = true;
1703 /* Estimate bitrate, we should probably subtract the various header sizes
1704 here for super-accurate results */
1705 id3->length = ((int64_t) samples * 1000) / id3->frequency;
1707 if (id3->length <= 0)
1709 logf("mpc length invalid!");
1710 return false;
1713 id3->filesize = filesize(fd);
1714 id3->bitrate = id3->filesize * 8 / id3->length;
1715 return true;
1718 /* PSID metadata info is available here:
1719 http://www.unusedino.de/ec64/technical/formats/sidplay.html */
1720 static bool get_sid_metadata(int fd, struct mp3entry* id3)
1722 /* Use the trackname part of the id3 structure as a temporary buffer */
1723 unsigned char* buf = (unsigned char *)id3->path;
1724 int read_bytes;
1725 char *p;
1728 if ((lseek(fd, 0, SEEK_SET) < 0)
1729 || ((read_bytes = read(fd, buf, 0x80)) < 0x80))
1731 return false;
1734 if ((memcmp(buf, "PSID",4) != 0))
1736 return false;
1739 p = id3->id3v2buf;
1741 /* Copy Title (assumed max 0x1f letters + 1 zero byte) */
1742 id3->title = p;
1743 buf[0x16+0x1f] = 0;
1744 p = iso_decode(&buf[0x16], p, 0, strlen(&buf[0x16])+1);
1746 /* Copy Artist (assumed max 0x1f letters + 1 zero byte) */
1747 id3->artist = p;
1748 buf[0x36+0x1f] = 0;
1749 p = iso_decode(&buf[0x36], p, 0, strlen(&buf[0x36])+1);
1751 /* Copy Year (assumed max 4 letters + 1 zero byte) */
1752 buf[0x56+0x4] = 0;
1753 id3->year = atoi(&buf[0x56]);
1755 /* Copy Album (assumed max 0x1f-0x05 letters + 1 zero byte) */
1756 id3->album = p;
1757 buf[0x56+0x1f] = 0;
1758 p = iso_decode(&buf[0x5b], p, 0, strlen(&buf[0x5b])+1);
1760 id3->bitrate = 706;
1761 id3->frequency = 44100;
1762 /* New idea as posted by Marco Alanen (ravon):
1763 * Set the songlength in seconds to the number of subsongs
1764 * so every second represents a subsong.
1765 * Users can then skip the current subsong by seeking
1767 * Note: the number of songs is a 16bit value at 0xE, so this code only
1768 * uses the lower 8 bits of the counter.
1770 id3->length = (buf[0xf]-1)*1000;
1771 id3->vbr = false;
1772 id3->filesize = filesize(fd);
1774 return true;
1777 static bool get_adx_metadata(int fd, struct mp3entry* id3)
1779 /* Use the trackname part of the id3 structure as a temporary buffer */
1780 unsigned char * buf = (unsigned char *)id3->path;
1781 int chanstart, channels, read_bytes;
1782 int looping = 0, start_adr = 0, end_adr = 0;
1784 /* try to get the basic header */
1785 if ((lseek(fd, 0, SEEK_SET) < 0)
1786 || ((read_bytes = read(fd, buf, 0x38)) < 0x38))
1788 DEBUGF("lseek or read failed\n");
1789 return false;
1792 /* ADX starts with 0x80 */
1793 if (buf[0] != 0x80) {
1794 DEBUGF("get_adx_metadata: wrong first byte %c\n",buf[0]);
1795 return false;
1798 /* check for a reasonable offset */
1799 chanstart = ((buf[2] << 8) | buf[3]) + 4;
1800 if (chanstart > 4096) {
1801 DEBUGF("get_adx_metadata: bad chanstart %i\n", chanstart);
1802 return false;
1805 /* check for a workable number of channels */
1806 channels = buf[7];
1807 if (channels != 1 && channels != 2) {
1808 DEBUGF("get_adx_metadata: bad channel count %i\n",channels);
1809 return false;
1812 id3->frequency = get_long_be(&buf[8]);
1813 /* 32 samples per 18 bytes */
1814 id3->bitrate = id3->frequency * channels * 18 * 8 / 32 / 1000;
1815 id3->length = get_long_be(&buf[12]) / id3->frequency * 1000;
1816 id3->vbr = false;
1817 id3->filesize = filesize(fd);
1819 /* get loop info */
1820 if (!memcmp(buf+0x10,"\x01\xF4\x03\x00",4)) {
1821 /* Soul Calibur 2 style (type 03) */
1822 DEBUGF("get_adx_metadata: type 03 found\n");
1823 /* check if header is too small for loop data */
1824 if (chanstart-6 < 0x2c) looping=0;
1825 else {
1826 looping = get_long_be(&buf[0x18]);
1827 end_adr = get_long_be(&buf[0x28]);
1828 start_adr = get_long_be(&buf[0x1c])/32*channels*18+chanstart;
1830 } else if (!memcmp(buf+0x10,"\x01\xF4\x04\x00",4)) {
1831 /* Standard (type 04) */
1832 DEBUGF("get_adx_metadata: type 04 found\n");
1833 /* check if header is too small for loop data */
1834 if (chanstart-6 < 0x38) looping=0;
1835 else {
1836 looping = get_long_be(&buf[0x24]);
1837 end_adr = get_long_be(&buf[0x34]);
1838 start_adr = get_long_be(&buf[0x28])/32*channels*18+chanstart;
1840 } else {
1841 DEBUGF("get_adx_metadata: error, couldn't determine ADX type\n");
1842 return false;
1845 if (looping) {
1846 /* 2 loops, 10 second fade */
1847 id3->length = (start_adr-chanstart + 2*(end_adr-start_adr))
1848 *8 / id3->bitrate + 10000;
1851 /* try to get the channel header */
1852 if ((lseek(fd, chanstart-6, SEEK_SET) < 0)
1853 || ((read_bytes = read(fd, buf, 6)) < 6))
1855 return false;
1858 /* check channel header */
1859 if (memcmp(buf, "(c)CRI", 6) != 0) return false;
1861 return true;
1864 static bool get_spc_metadata(int fd, struct mp3entry* id3)
1866 /* Use the trackname part of the id3 structure as a temporary buffer */
1867 unsigned char * buf = (unsigned char *)id3->path;
1868 int read_bytes;
1869 char * p;
1871 unsigned long length;
1872 unsigned long fade;
1873 bool isbinary = true;
1874 int i;
1876 /* try to get the ID666 tag */
1877 if ((lseek(fd, 0x2e, SEEK_SET) < 0)
1878 || ((read_bytes = read(fd, buf, 0xD2)) < 0xD2))
1880 DEBUGF("lseek or read failed\n");
1881 return false;
1884 p = id3->id3v2buf;
1886 id3->title = p;
1887 buf[31] = 0;
1888 p = iso_decode(buf, p, 0, 32);
1889 buf += 32;
1891 id3->album = p;
1892 buf[31] = 0;
1893 p = iso_decode(buf, p, 0, 32);
1894 buf += 48;
1896 id3->comment = p;
1897 buf[31] = 0;
1898 p = iso_decode(buf, p, 0, 32);
1899 buf += 32;
1901 /* Date check */
1902 if(buf[2] == '/' && buf[5] == '/')
1903 isbinary = false;
1905 /* Reserved bytes check */
1906 if(buf[0xD2 - 0x2E - 112] >= '0' &&
1907 buf[0xD2 - 0x2E - 112] <= '9' &&
1908 buf[0xD3 - 0x2E - 112] == 0x00)
1909 isbinary = false;
1911 /* is length & fade only digits? */
1912 for (i=0;i<8 && (
1913 (buf[0xA9 - 0x2E - 112+i]>='0'&&buf[0xA9 - 0x2E - 112+i]<='9') ||
1914 buf[0xA9 - 0x2E - 112+i]=='\0');
1915 i++);
1916 if (i==8) isbinary = false;
1918 if(isbinary) {
1919 id3->year = buf[0] | (buf[1]<<8);
1920 buf += 11;
1922 length = (buf[0] | (buf[1]<<8) | (buf[2]<<16)) * 1000;
1923 buf += 3;
1925 fade = (buf[0] | (buf[1]<<8) | (buf[2]<<16) | (buf[3]<<24));
1926 buf += 4;
1927 } else {
1928 char tbuf[6];
1930 buf += 6;
1931 buf[4] = 0;
1932 id3->year = atoi(buf);
1933 buf += 5;
1935 memcpy(tbuf, buf, 3);
1936 tbuf[3] = 0;
1937 length = atoi(tbuf) * 1000;
1938 buf += 3;
1940 memcpy(tbuf, buf, 5);
1941 tbuf[5] = 0;
1942 fade = atoi(tbuf);
1943 buf += 5;
1946 id3->artist = p;
1947 buf[31] = 0;
1948 p = iso_decode(buf, p, 0, 32);
1950 #ifndef __PCTOOL__
1951 if (global_settings.repeat_mode!=REPEAT_ONE && length==0) {
1952 length=3*60*1000; /* 3 minutes */
1953 fade=5*1000; /* 5 seconds */
1955 #endif
1957 id3->length = length+fade;
1959 return true;
1962 static bool get_aiff_metadata(int fd, struct mp3entry* id3)
1964 /* Use the trackname part of the id3 structure as a temporary buffer */
1965 unsigned char* buf = (unsigned char *)id3->path;
1966 unsigned long numChannels = 0;
1967 unsigned long numSampleFrames = 0;
1968 unsigned long sampleSize = 0;
1969 unsigned long sampleRate = 0;
1970 unsigned long numbytes = 0;
1971 int read_bytes;
1972 int i;
1974 if ((lseek(fd, 0, SEEK_SET) < 0)
1975 || ((read_bytes = read(fd, buf, sizeof(id3->path))) < 54))
1977 return false;
1980 if ((memcmp(buf, "FORM",4) != 0)
1981 || (memcmp(&buf[8], "AIFF", 4) !=0 ))
1983 return false;
1986 buf += 12;
1987 read_bytes -= 12;
1989 while ((numbytes == 0) && (read_bytes >= 8))
1991 /* chunkSize */
1992 i = get_long_be(&buf[4]);
1994 if (memcmp(buf, "COMM", 4) == 0)
1996 /* numChannels */
1997 numChannels = ((buf[8]<<8)|buf[9]);
1998 /* numSampleFrames */
1999 numSampleFrames = get_long_be(&buf[10]);
2000 /* sampleSize */
2001 sampleSize = ((buf[14]<<8)|buf[15]);
2002 /* sampleRate */
2003 sampleRate = get_long_be(&buf[18]);
2004 sampleRate = sampleRate >> (16+14-buf[17]);
2005 /* save format infos */
2006 id3->bitrate = (sampleSize * numChannels * sampleRate) / 1000;
2007 id3->frequency = sampleRate;
2008 id3->length = ((int64_t) numSampleFrames * 1000) / id3->frequency;
2010 id3->vbr = false; /* AIFF files are CBR */
2011 id3->filesize = filesize(fd);
2013 else if (memcmp(buf, "SSND", 4) == 0)
2015 numbytes = i - 8;
2018 if (i & 0x01)
2020 i++; /* odd chunk sizes must be padded */
2022 buf += i + 8;
2023 read_bytes -= i + 8;
2026 if ((numbytes == 0) || (numChannels == 0))
2028 return false;
2030 return true;
2032 #endif /* CONFIG_CODEC == SWCODEC */
2035 /* Simple file type probing by looking at the filename extension. */
2036 unsigned int probe_file_format(const char *filename)
2038 char *suffix;
2039 unsigned int i;
2041 suffix = strrchr(filename, '.');
2043 if (suffix == NULL)
2045 return AFMT_UNKNOWN;
2048 /* skip '.' */
2049 suffix++;
2051 for (i = 1; i < AFMT_NUM_CODECS; i++)
2053 /* search extension list for type */
2054 const char *ext = audio_formats[i].ext_list;
2058 if (strcasecmp(suffix, ext) == 0)
2060 return i;
2063 ext += strlen(ext) + 1;
2065 while (*ext != '\0');
2068 return AFMT_UNKNOWN;
2071 /* Get metadata for track - return false if parsing showed problems with the
2072 * file that would prevent playback.
2074 bool get_metadata(struct track_info* track, int fd, const char* trackname,
2075 bool v1first)
2077 #if CONFIG_CODEC == SWCODEC
2078 unsigned char* buf;
2079 unsigned long totalsamples;
2080 int i;
2081 #endif
2083 /* Take our best guess at the codec type based on file extension */
2084 track->id3.codectype = probe_file_format(trackname);
2086 /* Load codec specific track tag information and confirm the codec type. */
2087 switch (track->id3.codectype)
2089 case AFMT_MPA_L1:
2090 case AFMT_MPA_L2:
2091 case AFMT_MPA_L3:
2092 if (!get_mp3_metadata(fd, &track->id3, trackname, v1first))
2094 return false;
2097 break;
2099 #if CONFIG_CODEC == SWCODEC
2100 case AFMT_FLAC:
2101 if (!get_flac_metadata(fd, &(track->id3)))
2103 return false;
2106 break;
2108 case AFMT_MPC:
2109 if (!get_musepack_metadata(fd, &(track->id3)))
2110 return false;
2111 read_ape_tags(fd, &(track->id3));
2112 break;
2114 case AFMT_OGG_VORBIS:
2115 if (!get_vorbis_metadata(fd, &(track->id3)))/*detects and handles Ogg/Speex files*/
2117 return false;
2120 break;
2122 case AFMT_SPEEX:
2123 if (!get_speex_metadata(fd, &(track->id3)))
2125 return false;
2128 break;
2130 case AFMT_PCM_WAV:
2131 if (!get_wave_metadata(fd, &(track->id3)))
2133 return false;
2136 break;
2138 case AFMT_WAVPACK:
2139 /* A simple parser to read basic information from a WavPack file. This
2140 * now works with self-extrating WavPack files. This no longer fails on
2141 * WavPack files containing floating-point audio data because these are
2142 * now converted to standard Rockbox format in the decoder.
2145 /* Use the trackname part of the id3 structure as a temporary buffer */
2146 buf = (unsigned char *)track->id3.path;
2148 for (i = 0; i < 256; ++i) {
2150 /* at every 256 bytes into file, try to read a WavPack header */
2152 if ((lseek(fd, i * 256, SEEK_SET) < 0) || (read(fd, buf, 32) < 32))
2154 return false;
2157 /* if valid WavPack 4 header version & not floating data, break */
2159 if (memcmp (buf, "wvpk", 4) == 0 && buf [9] == 4 &&
2160 (buf [8] >= 2 && buf [8] <= 0x10))
2162 break;
2166 if (i == 256) {
2167 logf ("%s is not a WavPack file\n", trackname);
2168 return false;
2171 track->id3.vbr = true; /* All WavPack files are VBR */
2172 track->id3.filesize = filesize (fd);
2174 if ((buf [20] | buf [21] | buf [22] | buf [23]) &&
2175 (buf [12] & buf [13] & buf [14] & buf [15]) != 0xff)
2177 int srindx = ((buf [26] >> 7) & 1) + ((buf [27] << 1) & 14);
2179 if (srindx == 15)
2181 track->id3.frequency = 44100;
2183 else
2185 track->id3.frequency = wavpack_sample_rates[srindx];
2188 totalsamples = get_long_le(&buf[12]);
2189 track->id3.length = totalsamples / (track->id3.frequency / 100) * 10;
2190 track->id3.bitrate = filesize (fd) / (track->id3.length / 8);
2193 read_ape_tags(fd, &track->id3); /* use any apetag info we find */
2194 break;
2196 case AFMT_A52:
2197 /* Use the trackname part of the id3 structure as a temporary buffer */
2198 buf = (unsigned char *)track->id3.path;
2200 if ((lseek(fd, 0, SEEK_SET) < 0) || (read(fd, buf, 5) < 5))
2202 return false;
2205 if ((buf[0] != 0x0b) || (buf[1] != 0x77))
2207 logf("%s is not an A52/AC3 file\n",trackname);
2208 return false;
2211 i = buf[4] & 0x3e;
2213 if (i > 36)
2215 logf("A52: Invalid frmsizecod: %d\n",i);
2216 return false;
2219 track->id3.bitrate = a52_bitrates[i >> 1];
2220 track->id3.vbr = false;
2221 track->id3.filesize = filesize(fd);
2223 switch (buf[4] & 0xc0)
2225 case 0x00:
2226 track->id3.frequency = 48000;
2227 track->id3.bytesperframe=track->id3.bitrate * 2 * 2;
2228 break;
2230 case 0x40:
2231 track->id3.frequency = 44100;
2232 track->id3.bytesperframe = a52_441framesizes[i];
2233 break;
2235 case 0x80:
2236 track->id3.frequency = 32000;
2237 track->id3.bytesperframe = track->id3.bitrate * 3 * 2;
2238 break;
2240 default:
2241 logf("A52: Invalid samplerate code: 0x%02x\n", buf[4] & 0xc0);
2242 return false;
2243 break;
2246 /* One A52 frame contains 6 blocks, each containing 256 samples */
2247 totalsamples = track->id3.filesize / track->id3.bytesperframe * 6 * 256;
2248 track->id3.length = totalsamples / track->id3.frequency * 1000;
2249 break;
2251 case AFMT_ALAC:
2252 case AFMT_AAC:
2253 if (!get_mp4_metadata(fd, &(track->id3)))
2255 return false;
2258 break;
2260 case AFMT_SHN:
2261 track->id3.vbr = true;
2262 track->id3.filesize = filesize(fd);
2263 if (!skip_id3v2(fd, &(track->id3)))
2265 return false;
2267 /* TODO: read the id3v2 header if it exists */
2268 break;
2270 case AFMT_SID:
2271 if (!get_sid_metadata(fd, &(track->id3)))
2273 return false;
2275 break;
2276 case AFMT_SPC:
2277 if(!get_spc_metadata(fd, &(track->id3)))
2279 DEBUGF("get_spc_metadata error\n");
2282 track->id3.filesize = filesize(fd);
2283 track->id3.genre_string = id3_get_num_genre(36);
2284 break;
2285 case AFMT_ADX:
2286 if (!get_adx_metadata(fd, &(track->id3)))
2288 DEBUGF("get_adx_metadata error\n");
2289 return false;
2292 break;
2293 case AFMT_NSF:
2294 buf = (unsigned char *)track->id3.path;
2295 if ((lseek(fd, 0, SEEK_SET) < 0) || ((read(fd, buf, 8)) < 8))
2297 DEBUGF("lseek or read failed\n");
2298 return false;
2300 track->id3.vbr = false;
2301 track->id3.filesize = filesize(fd);
2302 if (memcmp(buf,"NESM",4) && memcmp(buf,"NSFE",4)) return false;
2303 break;
2305 case AFMT_AIFF:
2306 if (!get_aiff_metadata(fd, &(track->id3)))
2308 return false;
2311 break;
2313 #endif /* CONFIG_CODEC == SWCODEC */
2315 default:
2316 /* If we don't know how to read the metadata, assume we can't play
2317 the file */
2318 return false;
2319 break;
2322 /* We have successfully read the metadata from the file */
2324 #ifndef __PCTOOL__
2325 if (cuesheet_is_enabled() && look_for_cuesheet_file(trackname))
2327 track->id3.cuesheet_type = 1;
2329 #endif
2331 lseek(fd, 0, SEEK_SET);
2332 strncpy(track->id3.path, trackname, sizeof(track->id3.path));
2333 track->taginfo_ready = true;
2335 return true;