Some minor code cleanup.
[Rockbox.git] / apps / metadata.c
blob1f61e984980fae16b2682dce1d2298e549f0fe0e
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 "atoi.h"
30 #include "replaygain.h"
31 #include "debug.h"
32 #include "system.h"
34 enum tagtype { TAGTYPE_APE = 1, TAGTYPE_VORBIS };
36 #define APETAG_HEADER_LENGTH 32
37 #define APETAG_HEADER_FORMAT "8LLLL"
38 #define APETAG_ITEM_HEADER_FORMAT "LL"
39 #define APETAG_ITEM_TYPE_MASK 3
41 #define TAG_NAME_LENGTH 32
42 #define TAG_VALUE_LENGTH 128
44 #define MP4_ID(a, b, c, d) (((a) << 24) | ((b) << 16) | ((c) << 8) | (d))
46 #define MP4_3gp6 MP4_ID('3', 'g', 'p', '6')
47 #define MP4_alac MP4_ID('a', 'l', 'a', 'c')
48 #define MP4_calb MP4_ID(0xa9, 'a', 'l', 'b')
49 #define MP4_cART MP4_ID(0xa9, 'A', 'R', 'T')
50 #define MP4_cnam MP4_ID(0xa9, 'n', 'a', 'm')
51 #define MP4_cwrt MP4_ID(0xa9, 'w', 'r', 't')
52 #define MP4_esds MP4_ID('e', 's', 'd', 's')
53 #define MP4_ftyp MP4_ID('f', 't', 'y', 'p')
54 #define MP4_gnre MP4_ID('g', 'n', 'r', 'e')
55 #define MP4_hdlr MP4_ID('h', 'd', 'l', 'r')
56 #define MP4_ilst MP4_ID('i', 'l', 's', 't')
57 #define MP4_M4A MP4_ID('M', '4', 'A', ' ')
58 #define MP4_M4B MP4_ID('M', '4', 'B', ' ')
59 #define MP4_mdat MP4_ID('m', 'd', 'a', 't')
60 #define MP4_mdia MP4_ID('m', 'd', 'i', 'a')
61 #define MP4_mdir MP4_ID('m', 'd', 'i', 'r')
62 #define MP4_meta MP4_ID('m', 'e', 't', 'a')
63 #define MP4_minf MP4_ID('m', 'i', 'n', 'f')
64 #define MP4_moov MP4_ID('m', 'o', 'o', 'v')
65 #define MP4_mp4a MP4_ID('m', 'p', '4', 'a')
66 #define MP4_mp42 MP4_ID('m', 'p', '4', '2')
67 #define MP4_qt MP4_ID('q', 't', ' ', ' ')
68 #define MP4_soun MP4_ID('s', 'o', 'u', 'n')
69 #define MP4_stbl MP4_ID('s', 't', 'b', 'l')
70 #define MP4_stsd MP4_ID('s', 't', 's', 'd')
71 #define MP4_stts MP4_ID('s', 't', 't', 's')
72 #define MP4_trak MP4_ID('t', 'r', 'a', 'k')
73 #define MP4_trkn MP4_ID('t', 'r', 'k', 'n')
74 #define MP4_udta MP4_ID('u', 'd', 't', 'a')
75 #define MP4_extra MP4_ID('-', '-', '-', '-')
77 struct apetag_header
79 char id[8];
80 long version;
81 long length;
82 long item_count;
83 long flags;
84 char reserved[8];
87 struct apetag_item_header
89 long length;
90 long flags;
93 #if CONFIG_CODEC == SWCODEC
94 static const unsigned short a52_bitrates[] =
96 32, 40, 48, 56, 64, 80, 96, 112, 128, 160,
97 192, 224, 256, 320, 384, 448, 512, 576, 640
100 /* Only store frame sizes for 44.1KHz - others are simply multiples
101 of the bitrate */
102 static const unsigned short a52_441framesizes[] =
104 69 * 2, 70 * 2, 87 * 2, 88 * 2, 104 * 2, 105 * 2, 121 * 2,
105 122 * 2, 139 * 2, 140 * 2, 174 * 2, 175 * 2, 208 * 2, 209 * 2,
106 243 * 2, 244 * 2, 278 * 2, 279 * 2, 348 * 2, 349 * 2, 417 * 2,
107 418 * 2, 487 * 2, 488 * 2, 557 * 2, 558 * 2, 696 * 2, 697 * 2,
108 835 * 2, 836 * 2, 975 * 2, 976 * 2, 1114 * 2, 1115 * 2, 1253 * 2,
109 1254 * 2, 1393 * 2, 1394 * 2
112 static const long wavpack_sample_rates [] =
114 6000, 8000, 9600, 11025, 12000, 16000, 22050, 24000,
115 32000, 44100, 48000, 64000, 88200, 96000, 192000
118 /* Read a string from the file. Read up to size bytes, or, if eos != -1,
119 * until the eos character is found (eos is not stored in buf, unless it is
120 * nil). Writes up to buf_size chars to buf, always terminating with a nil.
121 * Returns number of chars read or -1 on read error.
123 static long read_string(int fd, char* buf, long buf_size, int eos, long size)
125 long read_bytes = 0;
126 char c;
128 while (size != 0)
130 if (read(fd, &c, 1) != 1)
132 read_bytes = -1;
133 break;
136 read_bytes++;
137 size--;
139 if ((eos != -1) && (eos == (unsigned char) c))
141 break;
144 if (buf_size > 1)
146 *buf++ = c;
147 buf_size--;
151 *buf = 0;
152 return read_bytes;
155 /* Convert a little-endian structure to native format using a format string.
156 * Does nothing on a little-endian machine.
158 static void convert_endian(void *data, const char *format)
160 #ifdef ROCKBOX_BIG_ENDIAN
161 while (*format)
163 switch (*format)
165 case 'L':
167 long* d = (long*) data;
169 *d = letoh32(*d);
170 data = d + 1;
173 break;
175 case 'S':
177 short* d = (short*) data;
179 *d = letoh16(*d);
180 data = d + 1;
183 break;
185 default:
186 if (isdigit(*format))
188 data = ((char*) data) + *format - '0';
191 break;
194 format++;
196 #else
197 (void) data;
198 (void) format;
199 #endif
202 #if 0 /* not needed atm */
203 /* Read an unsigned 16-bit integer from a big-endian file. */
204 #ifdef ROCKBOX_BIG_ENDIAN
205 #define read_uint16be(fd, buf) read((fd), (buf), 2)
206 #else
207 static int read_uint16be(int fd, unsigned short* buf)
209 size_t n;
211 n = read(fd, (char*) buf, 2);
212 *buf = betoh16(*buf);
213 return n;
215 #endif
216 #endif /* if 0 */
218 /* Read an unsigned 32-bit integer from a big-endian file. */
219 #ifdef ROCKBOX_BIG_ENDIAN
220 #define read_uint32be(fd,buf) read((fd), (buf), 4)
221 #else
222 static int read_uint32be(int fd, unsigned int* buf)
224 size_t n;
226 n = read(fd, (char*) buf, 4);
227 *buf = betoh32(*buf);
228 return n;
230 #endif
232 /* Read an unaligned 32-bit little endian long from buffer. */
233 static unsigned long get_long_le(void* buf)
235 unsigned char* p = (unsigned char*) buf;
237 return p[0] | (p[1] << 8) | (p[2] << 16) | (p[3] << 24);
240 /* Read an unaligned 32-bit big endian long from buffer. */
241 static unsigned long get_long_be(void* buf)
243 unsigned char* p = (unsigned char*) buf;
245 return (p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3];
248 /* Parse the tag (the name-value pair) and fill id3 and buffer accordingly.
249 * String values to keep are written to buf. Returns number of bytes written
250 * to buf (including end nil).
252 static long parse_tag(const char* name, char* value, struct mp3entry* id3,
253 char* buf, long buf_remaining, enum tagtype type)
255 long len = 0;
256 char** p;
258 if ((((strcasecmp(name, "track") == 0) && (type == TAGTYPE_APE)))
259 || ((strcasecmp(name, "tracknumber") == 0) && (type == TAGTYPE_VORBIS)))
261 id3->tracknum = atoi(value);
262 p = &(id3->track_string);
264 else if (((strcasecmp(name, "year") == 0) && (type == TAGTYPE_APE))
265 || ((strcasecmp(name, "date") == 0) && (type == TAGTYPE_VORBIS)))
267 /* Date can be in more any format in a Vorbis tag, so don't try to
268 * parse it.
270 if (type != TAGTYPE_VORBIS)
272 id3->year = atoi(value);
275 p = &(id3->year_string);
277 else if (strcasecmp(name, "title") == 0)
279 p = &(id3->title);
281 else if (strcasecmp(name, "artist") == 0)
283 p = &(id3->artist);
285 else if (strcasecmp(name, "album") == 0)
287 p = &(id3->album);
289 else if (strcasecmp(name, "genre") == 0)
291 p = &(id3->genre_string);
293 else if (strcasecmp(name, "composer") == 0)
295 p = &(id3->composer);
297 else
299 len = parse_replaygain(name, value, id3, buf, buf_remaining);
300 p = NULL;
303 if (p)
305 len = strlen(value);
306 len = MIN(len, buf_remaining - 1);
308 if (len > 0)
310 strncpy(buf, value, len);
311 buf[len] = 0;
312 *p = buf;
313 len++;
315 else
317 len = 0;
321 return len;
324 /* Read the items in an APEV2 tag. Only looks for a tag at the end of a
325 * file. Returns true if a tag was found and fully read, false otherwise.
327 static bool read_ape_tags(int fd, struct mp3entry* id3)
329 struct apetag_header header;
331 if ((lseek(fd, -APETAG_HEADER_LENGTH, SEEK_END) < 0)
332 || (read(fd, &header, APETAG_HEADER_LENGTH) != APETAG_HEADER_LENGTH)
333 || (memcmp(header.id, "APETAGEX", sizeof(header.id))))
335 return false;
338 convert_endian(&header, APETAG_HEADER_FORMAT);
339 id3->genre = 0xff;
341 if ((header.version == 2000) && (header.item_count > 0)
342 && (header.length > APETAG_HEADER_LENGTH))
344 char *buf = id3->id3v2buf;
345 unsigned int buf_remaining = sizeof(id3->id3v2buf)
346 + sizeof(id3->id3v1buf);
347 unsigned int tag_remaining = header.length - APETAG_HEADER_LENGTH;
348 int i;
350 if (lseek(fd, -header.length, SEEK_END) < 0)
352 return false;
355 for (i = 0; i < header.item_count; i++)
357 struct apetag_item_header item;
358 char name[TAG_NAME_LENGTH];
359 char value[TAG_VALUE_LENGTH];
360 long r;
362 if (tag_remaining < sizeof(item))
364 break;
367 if (read(fd, &item, sizeof(item)) < (long) sizeof(item))
369 return false;
372 convert_endian(&item, APETAG_ITEM_HEADER_FORMAT);
373 tag_remaining -= sizeof(item);
374 r = read_string(fd, name, sizeof(name), 0, tag_remaining);
376 if (r == -1)
378 return false;
381 tag_remaining -= r + item.length;
383 if ((item.flags & APETAG_ITEM_TYPE_MASK) == 0)
385 long len;
387 if (read_string(fd, value, sizeof(value), -1, item.length)
388 != item.length)
390 return false;
393 len = parse_tag(name, value, id3, buf, buf_remaining,
394 TAGTYPE_APE);
395 buf += len;
396 buf_remaining -= len;
398 else
400 if (lseek(fd, item.length, SEEK_CUR) < 0)
402 return false;
408 return true;
411 /* Read the items in a Vorbis comment packet. Returns true the items were
412 * fully read, false otherwise.
414 static bool read_vorbis_tags(int fd, struct mp3entry *id3,
415 long tag_remaining)
417 char *buf = id3->id3v2buf;
418 long comment_count;
419 long len;
420 int buf_remaining = sizeof(id3->id3v2buf) + sizeof(id3->id3v1buf);
421 int i;
423 id3->genre = 255;
425 if (read(fd, &len, sizeof(len)) < (long) sizeof(len))
427 return false;
430 convert_endian(&len, "L");
432 if ((lseek(fd, len, SEEK_CUR) < 0)
433 || (read(fd, &comment_count, sizeof(comment_count))
434 < (long) sizeof(comment_count)))
436 return false;
439 convert_endian(&comment_count, "L");
440 tag_remaining -= len + sizeof(len) + sizeof(comment_count);
442 if (tag_remaining <= 0)
444 return true;
447 for (i = 0; i < comment_count; i++)
449 char name[TAG_NAME_LENGTH];
450 char value[TAG_VALUE_LENGTH];
451 long read_len;
453 if (tag_remaining < 4)
455 break;
458 if (read(fd, &len, sizeof(len)) < (long) sizeof(len))
460 return false;
463 convert_endian(&len, "L");
464 tag_remaining -= 4;
466 /* Quit if we've passed the end of the page */
467 if (tag_remaining < len)
469 break;
472 tag_remaining -= len;
473 read_len = read_string(fd, name, sizeof(name), '=', len);
475 if (read_len < 0)
477 return false;
480 len -= read_len;
482 if (read_string(fd, value, sizeof(value), -1, len) < 0)
484 return false;
487 len = parse_tag(name, value, id3, buf, buf_remaining,
488 TAGTYPE_VORBIS);
489 buf += len;
490 buf_remaining -= len;
493 /* Skip to the end of the block */
494 if (tag_remaining)
496 if (lseek(fd, tag_remaining, SEEK_CUR) < 0)
498 return false;
502 return true;
505 /* Skip an ID3v2 tag if it can be found. We assume the tag is located at the
506 * start of the file, which should be true in all cases where we need to skip it.
507 * Returns true if successfully skipped or not skipped, and false if
508 * something went wrong while skipping.
510 static bool skip_id3v2(int fd, struct mp3entry *id3)
512 char buf[4];
514 read(fd, buf, 4);
515 if (memcmp(buf, "ID3", 3) == 0)
517 /* We have found an ID3v2 tag at the start of the file - find its
518 length and then skip it. */
519 if ((id3->first_frame_offset = getid3v2len(fd)) == 0)
520 return false;
522 if ((lseek(fd, id3->first_frame_offset, SEEK_SET) < 0))
523 return false;
525 return true;
526 } else {
527 lseek(fd, 0, SEEK_SET);
528 id3->first_frame_offset = 0;
529 return true;
533 /* A simple parser to read vital metadata from an Ogg Vorbis file. Returns
534 * false if metadata needed by the Vorbis codec couldn't be read.
536 static bool get_vorbis_metadata(int fd, struct mp3entry* id3)
538 /* An Ogg File is split into pages, each starting with the string
539 * "OggS". Each page has a timestamp (in PCM samples) referred to as
540 * the "granule position".
542 * An Ogg Vorbis has the following structure:
543 * 1) Identification header (containing samplerate, numchannels, etc)
544 * 2) Comment header - containing the Vorbis Comments
545 * 3) Setup header - containing codec setup information
546 * 4) Many audio packets...
549 /* Use the path name of the id3 structure as a temporary buffer. */
550 unsigned char* buf = (unsigned char *)id3->path;
551 long comment_size;
552 long remaining = 0;
553 long last_serial = 0;
554 long serial, r;
555 int segments;
556 int i;
557 bool eof = false;
559 if ((lseek(fd, 0, SEEK_SET) < 0) || (read(fd, buf, 58) < 4))
561 return false;
564 if ((memcmp(buf, "OggS", 4) != 0) || (memcmp(&buf[29], "vorbis", 6) != 0))
566 return false;
569 /* We need to ensure the serial number from this page is the same as the
570 * one from the last page (since we only support a single bitstream).
572 serial = get_long_le(&buf[14]);
573 id3->frequency = get_long_le(&buf[40]);
574 id3->filesize = filesize(fd);
576 /* Comments are in second Ogg page */
577 if (lseek(fd, 58, SEEK_SET) < 0)
579 return false;
582 /* Minimum header length for Ogg pages is 27. */
583 if (read(fd, buf, 27) < 27)
585 return false;
588 if (memcmp(buf, "OggS", 4) !=0 )
590 return false;
593 segments = buf[26];
595 /* read in segment table */
596 if (read(fd, buf, segments) < segments)
598 return false;
601 /* The second packet in a vorbis stream is the comment packet. It *may*
602 * extend beyond the second page, but usually does not. Here we find the
603 * length of the comment packet (or the rest of the page if the comment
604 * packet extends to the third page).
606 for (i = 0; i < segments; i++)
608 remaining += buf[i];
610 /* The last segment of a packet is always < 255 bytes */
611 if (buf[i] < 255)
613 break;
617 /* Now read in packet header (type and id string) */
618 if (read(fd, buf, 7) < 7)
620 return false;
623 comment_size = remaining;
624 remaining -= 7;
626 /* The first byte of a packet is the packet type; comment packets are
627 * type 3.
629 if ((buf[0] != 3) || (memcmp(buf + 1, "vorbis", 6) !=0))
631 return false;
634 /* Failure to read the tags isn't fatal. */
635 read_vorbis_tags(fd, id3, remaining);
637 /* We now need to search for the last page in the file - identified by
638 * by ('O','g','g','S',0) and retrieve totalsamples.
641 /* A page is always < 64 kB */
642 if (lseek(fd, -(MIN(64 * 1024, id3->filesize)), SEEK_END) < 0)
644 return false;
647 remaining = 0;
649 while (!eof)
651 r = read(fd, &buf[remaining], MAX_PATH - remaining);
653 if (r <= 0)
655 eof = true;
657 else
659 remaining += r;
662 /* Inefficient (but simple) search */
663 i = 0;
665 while (i < (remaining - 3))
667 if ((buf[i] == 'O') && (memcmp(&buf[i], "OggS", 4) == 0))
669 if (i < (remaining - 17))
671 /* Note that this only reads the low 32 bits of a
672 * 64 bit value.
674 id3->samples = get_long_le(&buf[i + 6]);
675 last_serial = get_long_le(&buf[i + 14]);
677 /* If this page is very small the beginning of the next
678 * header could be in buffer. Jump near end of this header
679 * and continue */
680 i += 27;
682 else
684 break;
687 else
689 i++;
693 if (i < remaining)
695 /* Move the remaining bytes to start of buffer.
696 * Reuse var 'segments' as it is no longer needed */
697 segments = 0;
698 while (i < remaining)
700 buf[segments++] = buf[i++];
702 remaining = segments;
704 else
706 /* Discard the rest of the buffer */
707 remaining = 0;
711 /* This file has mutiple vorbis bitstreams (or is corrupt). */
712 /* FIXME we should display an error here. */
713 if (serial != last_serial)
715 logf("serialno mismatch");
716 logf("%ld", serial);
717 logf("%ld", last_serial);
718 return false;
721 id3->length = ((int64_t) id3->samples * 1000) / id3->frequency;
723 if (id3->length <= 0)
725 logf("ogg length invalid!");
726 return false;
729 id3->bitrate = (((int64_t) id3->filesize - comment_size) * 8) / id3->length;
730 id3->vbr = true;
732 return true;
735 static bool get_flac_metadata(int fd, struct mp3entry* id3)
737 /* A simple parser to read vital metadata from a FLAC file - length,
738 * frequency, bitrate etc. This code should either be moved to a
739 * seperate file, or discarded in favour of the libFLAC code.
740 * The FLAC stream specification can be found at
741 * http://flac.sourceforge.net/format.html#stream
744 /* Use the trackname part of the id3 structure as a temporary buffer */
745 unsigned char* buf = (unsigned char *)id3->path;
746 bool rc = false;
748 if (!skip_id3v2(fd, id3) || (read(fd, buf, 4) < 4))
750 return rc;
753 if (memcmp(buf, "fLaC", 4) != 0)
755 return rc;
758 while (true)
760 long i;
762 if (read(fd, buf, 4) < 0)
764 return rc;
767 /* The length of the block */
768 i = (buf[1] << 16) | (buf[2] << 8) | buf[3];
770 if ((buf[0] & 0x7f) == 0) /* 0 is the STREAMINFO block */
772 unsigned long totalsamples;
774 /* FIXME: Don't trust the value of i */
775 if (read(fd, buf, i) < 0)
777 return rc;
780 id3->vbr = true; /* All FLAC files are VBR */
781 id3->filesize = filesize(fd);
782 id3->frequency = (buf[10] << 12) | (buf[11] << 4)
783 | ((buf[12] & 0xf0) >> 4);
784 rc = true; /* Got vital metadata */
786 /* totalsamples is a 36-bit field, but we assume <= 32 bits are used */
787 totalsamples = get_long_be(&buf[14]);
789 /* Calculate track length (in ms) and estimate the bitrate (in kbit/s) */
790 id3->length = ((int64_t) totalsamples * 1000) / id3->frequency;
792 if (id3->length <= 0)
794 logf("flac length invalid!");
795 return false;
798 id3->bitrate = (id3->filesize * 8) / id3->length;
800 else if ((buf[0] & 0x7f) == 4) /* 4 is the VORBIS_COMMENT block */
802 /* The next i bytes of the file contain the VORBIS COMMENTS. */
803 if (!read_vorbis_tags(fd, id3, i))
805 return rc;
808 else
810 if (buf[0] & 0x80)
812 /* If we have reached the last metadata block, abort. */
813 break;
815 else
817 /* Skip to next metadata block */
818 if (lseek(fd, i, SEEK_CUR) < 0)
820 return rc;
826 return true;
829 static bool get_wave_metadata(int fd, struct mp3entry* id3)
831 /* Use the trackname part of the id3 structure as a temporary buffer */
832 unsigned char* buf = (unsigned char *)id3->path;
833 unsigned long totalsamples = 0;
834 unsigned long channels = 0;
835 unsigned long bitspersample = 0;
836 unsigned long numbytes = 0;
837 int read_bytes;
838 int i;
840 /* get RIFF chunk header */
841 if ((lseek(fd, 0, SEEK_SET) < 0)
842 || ((read_bytes = read(fd, buf, 12)) < 12))
844 return false;
847 if ((memcmp(buf, "RIFF",4) != 0)
848 || (memcmp(&buf[8], "WAVE", 4) !=0 ))
850 return false;
853 /* iterate over WAVE chunks until 'data' chunk */
854 while (true)
856 /* get chunk header */
857 if ((read_bytes = read(fd, buf, 8)) < 8)
858 return false;
860 /* chunkSize */
861 i = get_long_le(&buf[4]);
863 if (memcmp(buf, "fmt ", 4) == 0)
865 /* get rest of chunk */
866 if ((read_bytes = read(fd, buf, 16)) < 16)
867 return false;
869 i -= 16;
871 /* skipping wFormatTag */
872 /* wChannels */
873 channels = buf[2] | (buf[3] << 8);
874 /* dwSamplesPerSec */
875 id3->frequency = get_long_le(&buf[4]);
876 /* dwAvgBytesPerSec */
877 id3->bitrate = (get_long_le(&buf[8]) * 8) / 1000;
878 /* skipping wBlockAlign */
879 /* wBitsPerSample */
880 bitspersample = buf[14] | (buf[15] << 8);
882 else if (memcmp(buf, "data", 4) == 0)
884 numbytes = i;
885 break;
887 else if (memcmp(buf, "fact", 4) == 0)
889 /* dwSampleLength */
890 if (i >= 4)
892 /* get rest of chunk */
893 if ((read_bytes = read(fd, buf, 2)) < 2)
894 return false;
896 i -= 2;
897 totalsamples = get_long_le(buf);
901 /* seek to next chunk (even chunk sizes must be padded) */
902 if (i & 0x01)
903 i++;
905 if(lseek(fd, i, SEEK_CUR) < 0)
906 return false;
909 if ((numbytes == 0) || (channels == 0))
911 return false;
914 if (totalsamples == 0)
916 /* for PCM only */
917 totalsamples = numbytes
918 / ((((bitspersample - 1) / 8) + 1) * channels);
921 id3->vbr = false; /* All WAV files are CBR */
922 id3->filesize = filesize(fd);
924 /* Calculate track length (in ms) and estimate the bitrate (in kbit/s) */
925 id3->length = ((int64_t) totalsamples * 1000) / id3->frequency;
927 return true;
930 /* Read the tag data from an MP4 file, storing up to buffer_size bytes in
931 * buffer.
933 static unsigned long read_mp4_tag(int fd, unsigned int size_left, char* buffer,
934 unsigned int buffer_left)
936 unsigned int bytes_read = 0;
938 if (buffer_left == 0)
940 lseek(fd, size_left, SEEK_CUR); /* Skip everything */
942 else
944 /* Skip the data tag header - maybe we should parse it properly? */
945 lseek(fd, 16, SEEK_CUR);
946 size_left -= 16;
948 if (size_left > buffer_left)
950 read(fd, buffer, buffer_left);
951 lseek(fd, size_left - buffer_left, SEEK_CUR);
952 bytes_read = buffer_left;
954 else
956 read(fd, buffer, size_left);
957 bytes_read = size_left;
961 return bytes_read;
964 /* Read a string tag from an MP4 file */
965 static unsigned int read_mp4_tag_string(int fd, int size_left, char** buffer,
966 unsigned int* buffer_left, char** dest)
968 unsigned int bytes_read = read_mp4_tag(fd, size_left, *buffer,
969 *buffer_left - 1);
970 unsigned int length = 0;
972 if (bytes_read)
974 (*buffer)[bytes_read] = 0;
975 *dest = *buffer;
976 length = strlen(*buffer) + 1;
977 *buffer_left -= length;
978 *buffer += length;
980 else
982 *dest = NULL;
985 return length;
988 static unsigned int read_mp4_atom(int fd, unsigned int* size,
989 unsigned int* type, unsigned int size_left)
991 read_uint32be(fd, size);
992 read_uint32be(fd, type);
994 if (*size == 1)
996 /* FAT32 doesn't support files this big, so something seems to
997 * be wrong. (64-bit sizes should only be used when required.)
999 errno = EFBIG;
1000 *type = 0;
1001 return 0;
1004 if (*size > 0)
1006 if (*size > size_left)
1008 size_left = 0;
1010 else
1012 size_left -= *size;
1015 *size -= 8;
1017 else
1019 *size = size_left;
1020 size_left = 0;
1023 return size_left;
1026 static unsigned int read_mp4_length(int fd, unsigned int* size)
1028 unsigned int length = 0;
1029 int bytes = 0;
1030 unsigned char c;
1034 read(fd, &c, 1);
1035 bytes++;
1036 (*size)--;
1037 length = (length << 7) | (c & 0x7F);
1039 while ((c & 0x80) && (bytes < 4) && (*size > 0));
1041 return length;
1044 static bool read_mp4_esds(int fd, struct mp3entry* id3,
1045 unsigned int* size)
1047 unsigned char buf[8];
1048 bool sbr = false;
1050 lseek(fd, 4, SEEK_CUR); /* Version and flags. */
1051 read(fd, buf, 1); /* Verify ES_DescrTag. */
1052 *size -= 5;
1054 if (*buf == 3)
1056 /* read length */
1057 if (read_mp4_length(fd, size) < 20)
1059 return sbr;
1062 lseek(fd, 3, SEEK_CUR);
1063 *size -= 3;
1065 else
1067 lseek(fd, 2, SEEK_CUR);
1068 *size -= 2;
1071 read(fd, buf, 1); /* Verify DecoderConfigDescrTab. */
1072 *size -= 1;
1074 if (*buf != 4)
1076 return sbr;
1079 if (read_mp4_length(fd, size) < 13)
1081 return sbr;
1084 lseek(fd, 13, SEEK_CUR); /* Skip audio type, bit rates, etc. */
1085 read(fd, buf, 1);
1086 *size -= 14;
1088 if (*buf != 5) /* Verify DecSpecificInfoTag. */
1090 return sbr;
1094 static const int sample_rates[] =
1096 96000, 88200, 64000, 48000, 44100, 32000,
1097 24000, 22050, 16000, 12000, 11025, 8000
1099 unsigned long bits;
1100 unsigned int length;
1101 unsigned int index;
1102 int type;
1104 /* Read the (leading part of the) decoder config. */
1105 length = read_mp4_length(fd, size);
1106 length = MIN(length, *size);
1107 length = MIN(length, sizeof(buf));
1108 read(fd, buf, length);
1109 *size -= length;
1111 /* Decoder config format:
1112 * Object type - 5 bits
1113 * Frequency index - 4 bits
1114 * Channel configuration - 4 bits
1116 bits = get_long_be(buf);
1117 type = bits >> 27;
1118 index = (bits >> 23) & 0xf;
1120 if (index < (sizeof(sample_rates) / sizeof(*sample_rates)))
1122 id3->frequency = sample_rates[index];
1125 if (type == 5)
1127 sbr = true;
1128 /* Extended frequency index - 4 bits */
1129 index = (bits >> 15) & 0xf;
1131 if (index == 15)
1133 /* 17 bits read so far... */
1134 bits = get_long_be(&buf[2]);
1135 id3->frequency = (bits >> 7) & 0x00FFFFFF;
1137 else if (index < (sizeof(sample_rates) / sizeof(*sample_rates)))
1139 id3->frequency = sample_rates[index];
1142 else if (id3->frequency < 24000)
1144 /* SBR not indicated, but the file might still contain SBR.
1145 * MPEG specification says that one should assume SBR if
1146 * samplerate <= 24000 Hz.
1148 id3->frequency *= 2;
1149 sbr = true;
1153 return sbr;
1156 static bool read_mp4_tags(int fd, struct mp3entry* id3,
1157 unsigned int size_left)
1159 unsigned int size;
1160 unsigned int type;
1161 unsigned int buffer_left = sizeof(id3->id3v2buf) + sizeof(id3->id3v1buf);
1162 char* buffer = id3->id3v2buf;
1163 bool cwrt = false;
1167 size_left = read_mp4_atom(fd, &size, &type, size_left);
1169 /* DEBUGF("Tag atom: '%c%c%c%c' (%d bytes left)\n", type >> 24 & 0xff,
1170 type >> 16 & 0xff, type >> 8 & 0xff, type & 0xff, size); */
1172 switch (type)
1174 case MP4_cnam:
1175 read_mp4_tag_string(fd, size, &buffer, &buffer_left,
1176 &id3->title);
1177 break;
1179 case MP4_cART:
1180 read_mp4_tag_string(fd, size, &buffer, &buffer_left,
1181 &id3->artist);
1182 break;
1184 case MP4_calb:
1185 read_mp4_tag_string(fd, size, &buffer, &buffer_left,
1186 &id3->album);
1187 break;
1189 case MP4_cwrt:
1190 read_mp4_tag_string(fd, size, &buffer, &buffer_left,
1191 &id3->composer);
1192 cwrt = false;
1193 break;
1195 case MP4_gnre:
1197 unsigned short genre;
1199 read_mp4_tag(fd, size, (char*) &genre, sizeof(genre));
1200 id3->genre = betoh16(genre);
1202 break;
1204 case MP4_trkn:
1206 unsigned short n[2];
1208 read_mp4_tag(fd, size, (char*) &n, sizeof(n));
1209 id3->tracknum = betoh16(n[1]);
1211 break;
1213 case MP4_extra:
1215 char tag_name[TAG_NAME_LENGTH];
1216 unsigned int sub_size;
1218 /* "mean" atom */
1219 read_uint32be(fd, &sub_size);
1220 size -= sub_size;
1221 lseek(fd, sub_size - 4, SEEK_CUR);
1222 /* "name" atom */
1223 read_uint32be(fd, &sub_size);
1224 size -= sub_size;
1225 lseek(fd, 8, SEEK_CUR);
1226 sub_size -= 12;
1228 if (sub_size > sizeof(tag_name) - 1)
1230 read(fd, tag_name, sizeof(tag_name) - 1);
1231 lseek(fd, sub_size - sizeof(tag_name) - 1, SEEK_CUR);
1232 tag_name[sizeof(tag_name) - 1] = 0;
1234 else
1236 read(fd, tag_name, sub_size);
1237 tag_name[sub_size] = 0;
1240 if ((strcasecmp(tag_name, "composer") == 0) && !cwrt)
1242 read_mp4_tag_string(fd, size, &buffer, &buffer_left,
1243 &id3->composer);
1245 else
1247 char* any;
1248 unsigned int length = read_mp4_tag_string(fd, size,
1249 &buffer, &buffer_left, &any);
1251 if (length > 0)
1253 /* Re-use the read buffer as the dest buffer... */
1254 buffer -= length;
1255 buffer_left += length;
1257 if (parse_replaygain(tag_name, buffer, id3,
1258 buffer, buffer_left) > 0)
1260 /* Data used, keep it. */
1261 buffer += length;
1262 buffer_left -= length;
1267 break;
1269 default:
1270 lseek(fd, size, SEEK_CUR);
1271 break;
1274 while ((size_left > 0) && (errno == 0));
1276 return true;
1279 static bool read_mp4_container(int fd, struct mp3entry* id3,
1280 unsigned int size_left)
1282 unsigned int size;
1283 unsigned int type;
1284 unsigned int handler = 0;
1285 bool rc = true;
1289 size_left = read_mp4_atom(fd, &size, &type, size_left);
1291 /* DEBUGF("Atom: '%c%c%c%c' (0x%08x, %d bytes left)\n",
1292 (type >> 24) & 0xff, (type >> 16) & 0xff, (type >> 8) & 0xff,
1293 type & 0xff, type, size); */
1295 switch (type)
1297 case MP4_ftyp:
1299 unsigned int id;
1301 read_uint32be(fd, &id);
1302 size -= 4;
1304 if ((id != MP4_M4A) && (id != MP4_M4B) && (id != MP4_mp42)
1305 && (id != MP4_qt) && (id != MP4_3gp6))
1307 DEBUGF("Unknown MP4 file type: '%c%c%c%c'\n",
1308 id >> 24 & 0xff, id >> 16 & 0xff, id >> 8 & 0xff,
1309 id & 0xff);
1310 return false;
1313 break;
1315 case MP4_meta:
1316 lseek(fd, 4, SEEK_CUR); /* Skip version */
1317 size -= 4;
1318 /* Fall through */
1320 case MP4_moov:
1321 case MP4_udta:
1322 case MP4_mdia:
1323 case MP4_stbl:
1324 case MP4_trak:
1325 rc = read_mp4_container(fd, id3, size);
1326 size = 0;
1327 break;
1329 case MP4_ilst:
1330 if (handler == MP4_mdir)
1332 rc = read_mp4_tags(fd, id3, size);
1333 size = 0;
1335 break;
1337 case MP4_minf:
1338 if (handler == MP4_soun)
1340 rc = read_mp4_container(fd, id3, size);
1341 size = 0;
1343 break;
1345 case MP4_stsd:
1346 lseek(fd, 8, SEEK_CUR);
1347 size -= 8;
1348 rc = read_mp4_container(fd, id3, size);
1349 size = 0;
1350 break;
1352 case MP4_hdlr:
1353 lseek(fd, 8, SEEK_CUR);
1354 read_uint32be(fd, &handler);
1355 size -= 12;
1356 /* DEBUGF(" Handler '%c%c%c%c'\n", handler >> 24 & 0xff,
1357 handler >> 16 & 0xff, handler >> 8 & 0xff,handler & 0xff); */
1358 break;
1360 case MP4_stts:
1362 unsigned int entries;
1363 unsigned int i;
1365 lseek(fd, 4, SEEK_CUR);
1366 read_uint32be(fd, &entries);
1367 id3->samples = 0;
1369 for (i = 0; i < entries; i++)
1371 unsigned int n;
1372 unsigned int l;
1374 read_uint32be(fd, &n);
1375 read_uint32be(fd, &l);
1376 id3->samples += n * l;
1379 size = 0;
1381 break;
1383 case MP4_mp4a:
1384 case MP4_alac:
1386 unsigned int frequency;
1388 id3->codectype = (type == MP4_mp4a) ? AFMT_AAC : AFMT_ALAC;
1389 lseek(fd, 22, SEEK_CUR);
1390 read_uint32be(fd, &frequency);
1391 size -= 26;
1392 id3->frequency = frequency;
1394 if (type == MP4_mp4a)
1396 unsigned int subsize;
1397 unsigned int subtype;
1399 /* Get frequency from the decoder info tag, if possible. */
1400 lseek(fd, 2, SEEK_CUR);
1401 /* The esds atom is a part of the mp4a atom, so ignore
1402 * the returned size (it's already accounted for).
1404 read_mp4_atom(fd, &subsize, &subtype, size);
1405 size -= 10;
1407 if (subtype == MP4_esds)
1409 read_mp4_esds(fd, id3, &size);
1413 break;
1415 case MP4_mdat:
1416 id3->filesize = size;
1417 break;
1419 default:
1420 break;
1423 lseek(fd, size, SEEK_CUR);
1425 while (rc && (size_left > 0) && (errno == 0) && (id3->filesize == 0));
1426 /* Break on non-zero filesize, since Rockbox currently doesn't support
1427 * metadata after the mdat atom (which sets the filesize field).
1430 return rc;
1433 static bool get_mp4_metadata(int fd, struct mp3entry* id3)
1435 id3->codectype = AFMT_UNKNOWN;
1436 id3->genre = 255;
1437 id3->filesize = 0;
1438 errno = 0;
1440 if (read_mp4_container(fd, id3, filesize(fd)) && (errno == 0)
1441 && (id3->samples > 0) && (id3->frequency > 0)
1442 && (id3->filesize > 0))
1444 if (id3->codectype == AFMT_UNKNOWN)
1446 logf("Not an ALAC or AAC file");
1447 return false;
1450 id3->length = ((int64_t) id3->samples * 1000) / id3->frequency;
1452 if (id3->length <= 0)
1454 logf("mp4 length invalid!");
1455 return false;
1458 id3->bitrate = ((int64_t) id3->filesize * 8) / id3->length;
1459 DEBUGF("MP4 bitrate %d, frequency %d Hz, length %d ms\n",
1460 id3->bitrate, id3->frequency, id3->length);
1462 else
1464 logf("MP4 metadata error");
1465 DEBUGF("MP4 metadata error. errno %d, length %d, frequency %d, filesize %d\n",
1466 errno, id3->length, id3->frequency, id3->filesize);
1467 return false;
1470 return true;
1473 static bool get_musepack_metadata(int fd, struct mp3entry *id3)
1475 const int32_t sfreqs_sv7[4] = { 44100, 48000, 37800, 32000 };
1476 uint32_t header[8];
1477 uint64_t samples = 0;
1478 int i;
1480 if (!skip_id3v2(fd, id3))
1481 return false;
1482 if (read(fd, header, 4*8) != 4*8) return false;
1483 /* Musepack files are little endian, might need swapping */
1484 for (i = 1; i < 8; i++)
1485 header[i] = letoh32(header[i]);
1486 if (!memcmp(header, "MP+", 3)) { /* Compare to sig "MP+" */
1487 unsigned int streamversion;
1489 header[0] = letoh32(header[0]);
1490 streamversion = (header[0] >> 24) & 15;
1491 if (streamversion >= 8) {
1492 return false; /* SV8 or higher don't exist yet, so no support */
1493 } else if (streamversion == 7) {
1494 unsigned int gapless = (header[5] >> 31) & 0x0001;
1495 unsigned int last_frame_samples = (header[5] >> 20) & 0x07ff;
1496 int track_gain, album_gain;
1497 unsigned int bufused;
1499 id3->frequency = sfreqs_sv7[(header[2] >> 16) & 0x0003];
1500 samples = (uint64_t)header[1]*1152; /* 1152 is mpc frame size */
1501 if (gapless)
1502 samples -= 1152 - last_frame_samples;
1503 else
1504 samples -= 481; /* Musepack subband synth filter delay */
1506 /* Extract ReplayGain data from header */
1507 track_gain = (int16_t)((header[3] >> 16) & 0xffff);
1508 id3->track_gain = get_replaygain_int(track_gain);
1509 id3->track_peak = ((uint16_t)(header[3] & 0xffff)) << 9;
1511 album_gain = (int16_t)((header[4] >> 16) & 0xffff);
1512 id3->album_gain = get_replaygain_int(album_gain);
1513 id3->album_peak = ((uint16_t)(header[4] & 0xffff)) << 9;
1515 /* Write replaygain values to strings for use in id3 screen. We use
1516 the XING header as buffer space since Musepack files shouldn't
1517 need to use it in any other way */
1518 id3->track_gain_string = (char *)id3->toc;
1519 bufused = snprintf(id3->track_gain_string, 45,
1520 "%d.%d dB", track_gain/100, abs(track_gain)%100);
1521 id3->album_gain_string = (char *)id3->toc + bufused + 1;
1522 bufused = snprintf(id3->album_gain_string, 45,
1523 "%d.%d dB", album_gain/100, abs(album_gain)%100);
1525 } else {
1526 header[0] = letoh32(header[0]);
1527 unsigned int streamversion = (header[0] >> 11) & 0x03FF;
1528 if (streamversion != 4 && streamversion != 5 && streamversion != 6)
1529 return false;
1530 id3->frequency = 44100;
1531 id3->track_gain = 0;
1532 id3->track_peak = 0;
1533 id3->album_gain = 0;
1534 id3->album_peak = 0;
1536 if (streamversion >= 5)
1537 samples = (uint64_t)header[1]*1152; // 32 bit
1538 else
1539 samples = (uint64_t)(header[1] >> 16)*1152; // 16 bit
1541 samples -= 576;
1542 if (streamversion < 6)
1543 samples -= 1152;
1546 id3->vbr = true;
1547 /* Estimate bitrate, we should probably subtract the various header sizes
1548 here for super-accurate results */
1549 id3->length = ((int64_t) samples * 1000) / id3->frequency;
1551 if (id3->length <= 0)
1553 logf("mpc length invalid!");
1554 return false;
1557 id3->filesize = filesize(fd);
1558 id3->bitrate = id3->filesize * 8 / id3->length;
1559 return true;
1562 /* PSID metadata info is available here:
1563 http://www.unusedino.de/ec64/technical/formats/sidplay.html */
1564 static bool get_sid_metadata(int fd, struct mp3entry* id3)
1566 /* Use the trackname part of the id3 structure as a temporary buffer */
1567 unsigned char* buf = (unsigned char *)id3->path;
1568 int read_bytes;
1569 char *p;
1572 if ((lseek(fd, 0, SEEK_SET) < 0)
1573 || ((read_bytes = read(fd, buf, sizeof(id3->path))) < 44))
1575 return false;
1578 if ((memcmp(buf, "PSID",4) != 0))
1580 return false;
1583 p = id3->id3v2buf;
1585 /* Copy Title (assumed max 0x1f letters + 1 zero byte) */
1586 strncpy(p, (char *)&buf[0x16], 0x20);
1587 p[0x1f]=0; /* make sure it is zero terminated */
1588 id3->title = p;
1589 p += strlen(p)+1;
1591 /* Copy Artist (assumed max 0x1f letters + 1 zero byte) */
1592 strncpy(p, (char *)&buf[0x36], 0x20);
1593 p[0x1f]=0; /* make sure it is zero terminated */
1594 id3->artist = p;
1596 id3->bitrate = 706;
1597 id3->frequency = 44100;
1598 /* New idea as posted by Marco Alanen (ravon):
1599 * Set the songlength in seconds to the number of subsongs
1600 * so every second represents a subsong.
1601 * Users can then skip the current subsong by seeking
1603 * Note: the number of songs is a 16bit value at 0xE, so this code only
1604 * uses the lower 8 bits of the counter.
1606 id3->length = (buf[0xf]-1)*1000;
1607 id3->vbr = false;
1608 id3->filesize = filesize(fd);
1610 return true;
1613 static bool get_adx_metadata(int fd, struct mp3entry* id3)
1615 /* Use the trackname part of the id3 structure as a temporary buffer */
1616 unsigned char * buf = (unsigned char *)id3->path;
1617 int chanstart, channels, read_bytes;
1618 int looping = 0, start_adr = 0, end_adr = 0;
1620 /* try to get the basic header */
1621 if ((lseek(fd, 0, SEEK_SET) < 0)
1622 || ((read_bytes = read(fd, buf, 0x38)) < 0x38))
1624 DEBUGF("lseek or read failed\n");
1625 return false;
1628 /* ADX starts with 0x80 */
1629 if (buf[0] != 0x80) {
1630 DEBUGF("get_adx_metadata: wrong first byte %c\n",buf[0]);
1631 return false;
1634 /* check for a reasonable offset */
1635 chanstart = ((buf[2] << 8) | buf[3]) + 4;
1636 if (chanstart > 4096) {
1637 DEBUGF("get_adx_metadata: bad chanstart %i\n", chanstart);
1638 return false;
1641 /* check for a workable number of channels */
1642 channels = buf[7];
1643 if (channels != 1 && channels != 2) {
1644 DEBUGF("get_adx_metadata: bad channel count %i\n",channels);
1645 return false;
1648 id3->frequency = get_long_be(&buf[8]);
1649 /* 32 samples per 18 bytes */
1650 id3->bitrate = id3->frequency * channels * 18 * 8 / 32 / 1000;
1651 id3->length = get_long_be(&buf[12]) / id3->frequency * 1000;
1652 id3->vbr = false;
1653 id3->filesize = filesize(fd);
1655 /* get loop info */
1656 if (!memcmp(buf+0x10,"\x01\xF4\x03\x00",4)) {
1657 /* Soul Calibur 2 style (type 03) */
1658 DEBUGF("get_adx_metadata: type 03 found\n");
1659 /* check if header is too small for loop data */
1660 if (chanstart-6 < 0x2c) looping=0;
1661 else {
1662 looping = get_long_be(&buf[0x18]);
1663 end_adr = get_long_be(&buf[0x28]);
1664 start_adr = get_long_be(&buf[0x1c])/32*channels*18+chanstart;
1666 } else if (!memcmp(buf+0x10,"\x01\xF4\x04\x00",4)) {
1667 /* Standard (type 04) */
1668 DEBUGF("get_adx_metadata: type 04 found\n");
1669 /* check if header is too small for loop data */
1670 if (chanstart-6 < 0x38) looping=0;
1671 else {
1672 looping = get_long_be(&buf[0x24]);
1673 end_adr = get_long_be(&buf[0x34]);
1674 start_adr = get_long_be(&buf[0x28])/32*channels*18+chanstart;
1676 } else {
1677 DEBUGF("get_adx_metadata: error, couldn't determine ADX type\n");
1678 return false;
1681 if (looping) {
1682 /* 2 loops, 10 second fade */
1683 id3->length = (start_adr-chanstart + 2*(end_adr-start_adr))
1684 *8 / id3->bitrate + 10000;
1687 /* try to get the channel header */
1688 if ((lseek(fd, chanstart-6, SEEK_SET) < 0)
1689 || ((read_bytes = read(fd, buf, 6)) < 6))
1691 return false;
1694 /* check channel header */
1695 if (memcmp(buf, "(c)CRI", 6) != 0) return false;
1697 return true;
1700 static bool get_aiff_metadata(int fd, struct mp3entry* id3)
1702 /* Use the trackname part of the id3 structure as a temporary buffer */
1703 unsigned char* buf = (unsigned char *)id3->path;
1704 unsigned long numChannels = 0;
1705 unsigned long numSampleFrames = 0;
1706 unsigned long sampleSize = 0;
1707 unsigned long sampleRate = 0;
1708 unsigned long numbytes = 0;
1709 int read_bytes;
1710 int i;
1712 if ((lseek(fd, 0, SEEK_SET) < 0)
1713 || ((read_bytes = read(fd, buf, sizeof(id3->path))) < 54))
1715 return false;
1718 if ((memcmp(buf, "FORM",4) != 0)
1719 || (memcmp(&buf[8], "AIFF", 4) !=0 ))
1721 return false;
1724 buf += 12;
1725 read_bytes -= 12;
1727 while ((numbytes == 0) && (read_bytes >= 8))
1729 /* chunkSize */
1730 i = get_long_be(&buf[4]);
1732 if (memcmp(buf, "COMM", 4) == 0)
1734 /* numChannels */
1735 numChannels = ((buf[8]<<8)|buf[9]);
1736 /* numSampleFrames */
1737 numSampleFrames = get_long_be(&buf[10]);
1738 /* sampleSize */
1739 sampleSize = ((buf[14]<<8)|buf[15]);
1740 /* sampleRate */
1741 sampleRate = get_long_be(&buf[18]);
1742 sampleRate = sampleRate >> (16+14-buf[17]);
1743 /* save format infos */
1744 id3->bitrate = (sampleSize * numChannels * sampleRate) / 1000;
1745 id3->frequency = sampleRate;
1746 id3->length = ((int64_t) numSampleFrames * 1000) / id3->frequency;
1748 id3->vbr = false; /* AIFF files are CBR */
1749 id3->filesize = filesize(fd);
1751 else if (memcmp(buf, "SSND", 4) == 0)
1753 numbytes = i - 8;
1756 if (i & 0x01)
1758 i++; /* odd chunk sizes must be padded */
1760 buf += i + 8;
1761 read_bytes -= i + 8;
1764 if ((numbytes == 0) || (numChannels == 0))
1766 return false;
1768 return true;
1770 #endif /* CONFIG_CODEC == SWCODEC */
1773 /* Simple file type probing by looking at the filename extension. */
1774 unsigned int probe_file_format(const char *filename)
1776 char *suffix;
1777 unsigned int i;
1779 suffix = strrchr(filename, '.');
1781 if (suffix == NULL)
1783 return AFMT_UNKNOWN;
1786 /* skip '.' */
1787 suffix++;
1789 for (i = 1; i < AFMT_NUM_CODECS; i++)
1791 /* search extension list for type */
1792 const char *ext = audio_formats[i].ext_list;
1796 if (strcasecmp(suffix, ext) == 0)
1798 return i;
1801 ext += strlen(ext) + 1;
1803 while (*ext != '\0');
1806 return AFMT_UNKNOWN;
1809 /* Get metadata for track - return false if parsing showed problems with the
1810 * file that would prevent playback.
1812 bool get_metadata(struct track_info* track, int fd, const char* trackname,
1813 bool v1first)
1815 #if CONFIG_CODEC == SWCODEC
1816 unsigned char* buf;
1817 unsigned long totalsamples;
1818 int i;
1819 #endif
1821 /* Take our best guess at the codec type based on file extension */
1822 track->id3.codectype = probe_file_format(trackname);
1824 /* Load codec specific track tag information and confirm the codec type. */
1825 switch (track->id3.codectype)
1827 case AFMT_MPA_L1:
1828 case AFMT_MPA_L2:
1829 case AFMT_MPA_L3:
1830 if (!get_mp3_metadata(fd, &track->id3, trackname, v1first))
1832 return false;
1835 break;
1837 #if CONFIG_CODEC == SWCODEC
1838 case AFMT_FLAC:
1839 if (!get_flac_metadata(fd, &(track->id3)))
1841 return false;
1844 break;
1846 case AFMT_MPC:
1847 if (!get_musepack_metadata(fd, &(track->id3)))
1848 return false;
1849 read_ape_tags(fd, &(track->id3));
1850 break;
1852 case AFMT_OGG_VORBIS:
1853 if (!get_vorbis_metadata(fd, &(track->id3)))
1855 return false;
1858 break;
1860 case AFMT_PCM_WAV:
1861 if (!get_wave_metadata(fd, &(track->id3)))
1863 return false;
1866 break;
1868 case AFMT_WAVPACK:
1869 /* A simple parser to read basic information from a WavPack file. This
1870 * now works with self-extrating WavPack files and also will fail on
1871 * WavPack files containing floating-point audio data (although these
1872 * should be possible to play in theory).
1875 /* Use the trackname part of the id3 structure as a temporary buffer */
1876 buf = (unsigned char *)track->id3.path;
1878 for (i = 0; i < 256; ++i) {
1880 /* at every 256 bytes into file, try to read a WavPack header */
1882 if ((lseek(fd, i * 256, SEEK_SET) < 0) || (read(fd, buf, 32) < 32))
1884 return false;
1887 /* if valid WavPack 4 header version & not floating data, break */
1889 if (memcmp (buf, "wvpk", 4) == 0 && buf [9] == 4 &&
1890 (buf [8] >= 2 && buf [8] <= 0x10) && !(buf [24] & 0x80))
1892 break;
1896 if (i == 256) {
1897 logf ("%s is not a WavPack file\n", trackname);
1898 return false;
1901 track->id3.vbr = true; /* All WavPack files are VBR */
1902 track->id3.filesize = filesize (fd);
1904 if ((buf [20] | buf [21] | buf [22] | buf [23]) &&
1905 (buf [12] & buf [13] & buf [14] & buf [15]) != 0xff)
1907 int srindx = ((buf [26] >> 7) & 1) + ((buf [27] << 1) & 14);
1909 if (srindx == 15)
1911 track->id3.frequency = 44100;
1913 else
1915 track->id3.frequency = wavpack_sample_rates[srindx];
1918 totalsamples = get_long_le(&buf[12]);
1919 track->id3.length = totalsamples / (track->id3.frequency / 100) * 10;
1920 track->id3.bitrate = filesize (fd) / (track->id3.length / 8);
1923 read_ape_tags(fd, &track->id3); /* use any apetag info we find */
1924 break;
1926 case AFMT_A52:
1927 /* Use the trackname part of the id3 structure as a temporary buffer */
1928 buf = (unsigned char *)track->id3.path;
1930 if ((lseek(fd, 0, SEEK_SET) < 0) || (read(fd, buf, 5) < 5))
1932 return false;
1935 if ((buf[0] != 0x0b) || (buf[1] != 0x77))
1937 logf("%s is not an A52/AC3 file\n",trackname);
1938 return false;
1941 i = buf[4] & 0x3e;
1943 if (i > 36)
1945 logf("A52: Invalid frmsizecod: %d\n",i);
1946 return false;
1949 track->id3.bitrate = a52_bitrates[i >> 1];
1950 track->id3.vbr = false;
1951 track->id3.filesize = filesize(fd);
1953 switch (buf[4] & 0xc0)
1955 case 0x00:
1956 track->id3.frequency = 48000;
1957 track->id3.bytesperframe=track->id3.bitrate * 2 * 2;
1958 break;
1960 case 0x40:
1961 track->id3.frequency = 44100;
1962 track->id3.bytesperframe = a52_441framesizes[i];
1963 break;
1965 case 0x80:
1966 track->id3.frequency = 32000;
1967 track->id3.bytesperframe = track->id3.bitrate * 3 * 2;
1968 break;
1970 default:
1971 logf("A52: Invalid samplerate code: 0x%02x\n", buf[4] & 0xc0);
1972 return false;
1973 break;
1976 /* One A52 frame contains 6 blocks, each containing 256 samples */
1977 totalsamples = track->id3.filesize / track->id3.bytesperframe * 6 * 256;
1978 track->id3.length = totalsamples / track->id3.frequency * 1000;
1979 break;
1981 case AFMT_ALAC:
1982 case AFMT_AAC:
1983 if (!get_mp4_metadata(fd, &(track->id3)))
1985 return false;
1988 break;
1990 case AFMT_SHN:
1991 track->id3.vbr = true;
1992 track->id3.filesize = filesize(fd);
1993 if (!skip_id3v2(fd, &(track->id3)))
1995 return false;
1997 /* TODO: read the id3v2 header if it exists */
1998 break;
2000 case AFMT_SID:
2001 if (!get_sid_metadata(fd, &(track->id3)))
2003 return false;
2005 break;
2007 case AFMT_ADX:
2008 if (!get_adx_metadata(fd, &(track->id3)))
2010 DEBUGF("get_adx_metadata error\n");
2011 return false;
2014 break;
2016 case AFMT_AIFF:
2017 if (!get_aiff_metadata(fd, &(track->id3)))
2019 return false;
2022 break;
2024 #endif /* CONFIG_CODEC == SWCODEC */
2026 default:
2027 /* If we don't know how to read the metadata, assume we can't play
2028 the file */
2029 return false;
2030 break;
2033 /* We have successfully read the metadata from the file */
2035 lseek(fd, 0, SEEK_SET);
2036 strncpy(track->id3.path, trackname, sizeof(track->id3.path));
2037 track->taginfo_ready = true;
2039 return true;