HAVE_ADJUSTABLE_CPU_FREQ isn't defined for simulators, so we don't have to check...
[Rockbox.git] / apps / metadata.c
blob09ccb3928d4210c046013f14250ebdb4d09d4d81
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 "metadata.h"
26 #include "mp3_playback.h"
27 #include "logf.h"
28 #include "atoi.h"
29 #include "replaygain.h"
30 #include "debug.h"
31 #include "system.h"
33 enum tagtype { TAGTYPE_APE = 1, TAGTYPE_VORBIS };
35 #define APETAG_HEADER_LENGTH 32
36 #define APETAG_HEADER_FORMAT "8LLLL"
37 #define APETAG_ITEM_HEADER_FORMAT "LL"
38 #define APETAG_ITEM_TYPE_MASK 3
40 #define TAG_NAME_LENGTH 32
41 #define TAG_VALUE_LENGTH 128
43 struct apetag_header
45 char id[8];
46 long version;
47 long length;
48 long item_count;
49 long flags;
50 char reserved[8];
53 struct apetag_item_header
55 long length;
56 long flags;
59 struct format_list
61 char format;
62 char extension[5];
65 static const struct format_list formats[] =
67 { AFMT_MPA_L1, "mp1" },
68 { AFMT_MPA_L2, "mp2" },
69 { AFMT_MPA_L2, "mpa" },
70 { AFMT_MPA_L3, "mp3" },
71 #if CONFIG_CODEC == SWCODEC
72 { AFMT_OGG_VORBIS, "ogg" },
73 { AFMT_PCM_WAV, "wav" },
74 { AFMT_FLAC, "flac" },
75 { AFMT_MPC, "mpc" },
76 { AFMT_A52, "a52" },
77 { AFMT_A52, "ac3" },
78 { AFMT_WAVPACK, "wv" },
79 { AFMT_ALAC, "m4a" },
80 { AFMT_AAC, "mp4" },
81 { AFMT_SHN, "shn" },
82 { AFMT_AIFF, "aif" },
83 { AFMT_AIFF, "aiff" },
84 #endif
87 #if CONFIG_CODEC == SWCODEC
88 static const unsigned short a52_bitrates[] =
90 32, 40, 48, 56, 64, 80, 96, 112, 128, 160,
91 192, 224, 256, 320, 384, 448, 512, 576, 640
94 /* Only store frame sizes for 44.1KHz - others are simply multiples
95 of the bitrate */
96 static const unsigned short a52_441framesizes[] =
98 69 * 2, 70 * 2, 87 * 2, 88 * 2, 104 * 2, 105 * 2, 121 * 2,
99 122 * 2, 139 * 2, 140 * 2, 174 * 2, 175 * 2, 208 * 2, 209 * 2,
100 243 * 2, 244 * 2, 278 * 2, 279 * 2, 348 * 2, 349 * 2, 417 * 2,
101 418 * 2, 487 * 2, 488 * 2, 557 * 2, 558 * 2, 696 * 2, 697 * 2,
102 835 * 2, 836 * 2, 975 * 2, 976 * 2, 1114 * 2, 1115 * 2, 1253 * 2,
103 1254 * 2, 1393 * 2, 1394 * 2
106 static const long wavpack_sample_rates [] =
108 6000, 8000, 9600, 11025, 12000, 16000, 22050, 24000,
109 32000, 44100, 48000, 64000, 88200, 96000, 192000
112 /* Read a string from the file. Read up to size bytes, or, if eos != -1,
113 * until the eos character is found (eos is not stored in buf, unless it is
114 * nil). Writes up to buf_size chars to buf, always terminating with a nil.
115 * Returns number of chars read or -1 on read error.
117 static long read_string(int fd, char* buf, long buf_size, int eos, long size)
119 long read_bytes = 0;
120 char c;
122 while (size != 0)
124 if (read(fd, &c, 1) != 1)
126 read_bytes = -1;
127 break;
130 read_bytes++;
131 size--;
133 if ((eos != -1) && (eos == (unsigned char) c))
135 break;
138 if (buf_size > 1)
140 *buf++ = c;
141 buf_size--;
145 *buf = 0;
146 return read_bytes;
149 /* Convert a little-endian structure to native format using a format string.
150 * Does nothing on a little-endian machine.
152 static void convert_endian(void *data, const char *format)
154 while (*format)
156 switch (*format)
158 case 'L':
160 long* d = (long*) data;
162 *d = letoh32(*d);
163 data = d + 1;
166 break;
168 case 'S':
170 short* d = (short*) data;
172 *d = letoh16(*d);
173 data = d + 1;
176 break;
178 default:
179 if (isdigit(*format))
181 data = ((char*) data) + *format - '0';
184 break;
187 format++;
191 /* read_uint32be() - read an unsigned integer from a big-endian
192 (e.g. Quicktime) file. This is used by the .m4a parser
194 #ifdef ROCKBOX_BIG_ENDIAN
195 #define read_uint32be(fd,buf) read((fd),(buf),4)
196 #else
197 int read_uint32be(int fd, unsigned int* buf) {
198 char tmp;
199 char* p=(char*)buf;
200 size_t n;
202 n=read(fd,p,4);
203 if (n==4) {
204 tmp=p[0];
205 p[0]=p[3];
206 p[3]=tmp;
207 tmp=p[2];
208 p[2]=p[1];
209 p[1]=tmp;
212 return(n);
214 #endif
216 /* Read an unaligned 32-bit little endian long from buffer. */
217 static unsigned long get_long(void* buf)
219 unsigned char* p = (unsigned char*) buf;
221 return p[0] | (p[1] << 8) | (p[2] << 16) | (p[3] << 24);
224 /* Read a string tag from an M4A file */
225 void read_m4a_tag_string(int fd, int len,char** bufptr,size_t* bytes_remaining, char** dest)
227 int data_length;
229 if (bytes_remaining==0) {
230 lseek(fd,len,SEEK_CUR); /* Skip everything */
231 } else {
232 /* Skip the data tag header - maybe we should parse it properly? */
233 lseek(fd,16,SEEK_CUR);
234 len-=16;
236 *dest=*bufptr;
237 if ((size_t)len+1 > *bytes_remaining) {
238 read(fd,*bufptr,*bytes_remaining-1);
239 lseek(fd,len-(*bytes_remaining-1),SEEK_CUR);
240 *bufptr+=(*bytes_remaining-1);
241 } else {
242 read(fd,*bufptr,len);
243 *bufptr+=len;
245 **bufptr=(char)0;
247 data_length = strlen(*dest)+1;
248 *bufptr=(*dest)+data_length;
249 *bytes_remaining-=data_length;
253 /* Parse the tag (the name-value pair) and fill id3 and buffer accordingly.
254 * String values to keep are written to buf. Returns number of bytes written
255 * to buf (including end nil).
257 static long parse_tag(const char* name, char* value, struct mp3entry* id3,
258 char* buf, long buf_remaining, enum tagtype type)
260 long len = 0;
261 char** p;
263 if ((((strcasecmp(name, "track") == 0) && (type == TAGTYPE_APE)))
264 || ((strcasecmp(name, "tracknumber") == 0) && (type == TAGTYPE_VORBIS)))
266 id3->tracknum = atoi(value);
267 p = &(id3->track_string);
269 else if (((strcasecmp(name, "year") == 0) && (type == TAGTYPE_APE))
270 || ((strcasecmp(name, "date") == 0) && (type == TAGTYPE_VORBIS)))
272 /* Date can be in more any format in a Vorbis tag, so don't try to
273 * parse it.
275 if (type != TAGTYPE_VORBIS)
277 id3->year = atoi(value);
280 p = &(id3->year_string);
282 else if (strcasecmp(name, "title") == 0)
284 p = &(id3->title);
286 else if (strcasecmp(name, "artist") == 0)
288 p = &(id3->artist);
290 else if (strcasecmp(name, "album") == 0)
292 p = &(id3->album);
294 else if (strcasecmp(name, "genre") == 0)
296 p = &(id3->genre_string);
298 else if (strcasecmp(name, "composer") == 0)
300 p = &(id3->composer);
302 else
304 len = parse_replaygain(name, value, id3, buf, buf_remaining);
305 p = NULL;
308 if (p)
310 len = strlen(value);
311 len = MIN(len, buf_remaining - 1);
313 if (len > 0)
315 strncpy(buf, value, len);
316 buf[len] = 0;
317 *p = buf;
318 len++;
320 else
322 len = 0;
326 return len;
329 /* Read the items in an APEV2 tag. Only looks for a tag at the end of a
330 * file. Returns true if a tag was found and fully read, false otherwise.
332 static bool read_ape_tags(int fd, struct mp3entry* id3)
334 struct apetag_header header;
336 if ((lseek(fd, -APETAG_HEADER_LENGTH, SEEK_END) < 0)
337 || (read(fd, &header, APETAG_HEADER_LENGTH) != APETAG_HEADER_LENGTH)
338 || (memcmp(header.id, "APETAGEX", sizeof(header.id))))
340 return false;
343 convert_endian(&header, APETAG_HEADER_FORMAT);
344 id3->genre = 0xff;
346 if ((header.version == 2000) && (header.item_count > 0)
347 && (header.length > APETAG_HEADER_LENGTH))
349 char *buf = id3->id3v2buf;
350 unsigned int buf_remaining = sizeof(id3->id3v2buf)
351 + sizeof(id3->id3v1buf);
352 unsigned int tag_remaining = header.length - APETAG_HEADER_LENGTH;
353 int i;
355 if (lseek(fd, -header.length, SEEK_END) < 0)
357 return false;
360 for (i = 0; i < header.item_count; i++)
362 struct apetag_item_header item;
363 char name[TAG_NAME_LENGTH];
364 char value[TAG_VALUE_LENGTH];
365 long r;
367 if (tag_remaining < sizeof(item))
369 break;
372 if (read(fd, &item, sizeof(item)) < (long) sizeof(item))
374 return false;
377 convert_endian(&item, APETAG_ITEM_HEADER_FORMAT);
378 tag_remaining -= sizeof(item);
379 r = read_string(fd, name, sizeof(name), 0, tag_remaining);
381 if (r == -1)
383 return false;
386 tag_remaining -= r + item.length;
388 if ((item.flags & APETAG_ITEM_TYPE_MASK) == 0)
390 long len;
392 if (read_string(fd, value, sizeof(value), -1, item.length)
393 != item.length)
395 return false;
398 len = parse_tag(name, value, id3, buf, buf_remaining,
399 TAGTYPE_APE);
400 buf += len;
401 buf_remaining -= len;
403 else
405 if (lseek(fd, item.length, SEEK_CUR) < 0)
407 return false;
413 return true;
416 /* Read the items in a Vorbis comment packet. Returns true the items were
417 * fully read, false otherwise.
419 static bool read_vorbis_tags(int fd, struct mp3entry *id3,
420 long tag_remaining)
422 char *buf = id3->id3v2buf;
423 long comment_count;
424 long len;
425 int buf_remaining = sizeof(id3->id3v2buf) + sizeof(id3->id3v1buf);
426 int i;
428 id3->genre = 255;
430 if (read(fd, &len, sizeof(len)) < (long) sizeof(len))
432 return false;
435 convert_endian(&len, "L");
437 if ((lseek(fd, len, SEEK_CUR) < 0)
438 || (read(fd, &comment_count, sizeof(comment_count))
439 < (long) sizeof(comment_count)))
441 return false;
444 convert_endian(&comment_count, "L");
445 tag_remaining -= len + sizeof(len) + sizeof(comment_count);
447 if (tag_remaining <= 0)
449 return true;
452 for (i = 0; i < comment_count; i++)
454 char name[TAG_NAME_LENGTH];
455 char value[TAG_VALUE_LENGTH];
456 long read_len;
458 if (tag_remaining < 4)
460 break;
463 if (read(fd, &len, sizeof(len)) < (long) sizeof(len))
465 return false;
468 convert_endian(&len, "L");
469 tag_remaining -= 4;
471 /* Quit if we've passed the end of the page */
472 if (tag_remaining < len)
474 break;
477 tag_remaining -= len;
478 read_len = read_string(fd, name, sizeof(name), '=', len);
480 if (read_len < 0)
482 return false;
485 len -= read_len;
487 if (read_string(fd, value, sizeof(value), -1, len) < 0)
489 return false;
492 len = parse_tag(name, value, id3, buf, buf_remaining,
493 TAGTYPE_VORBIS);
494 buf += len;
495 buf_remaining -= len;
498 /* Skip to the end of the block */
499 if (tag_remaining)
501 if (lseek(fd, tag_remaining, SEEK_CUR) < 0)
503 return false;
507 return true;
510 /* Skip an ID3v2 tag if it can be found. We assume the tag is located at the
511 * start of the file, which should be true in all cases where we need to skip it.
512 * Returns true if successfully skipped or not skipped, and false if
513 * something went wrong while skipping.
515 static bool skip_id3v2(int fd, struct mp3entry *id3)
517 char buf[4];
519 read(fd, buf, 4);
520 if (memcmp(buf, "ID3", 3) == 0)
522 /* We have found an ID3v2 tag at the start of the file - find its
523 length and then skip it. */
524 if ((id3->first_frame_offset = getid3v2len(fd)) == 0)
525 return false;
527 if ((lseek(fd, id3->first_frame_offset, SEEK_SET) < 0))
528 return false;
530 return true;
531 } else {
532 lseek(fd, 0, SEEK_SET);
533 id3->first_frame_offset = 0;
534 return true;
538 /* A simple parser to read vital metadata from an Ogg Vorbis file. Returns
539 * false if metadata needed by the Vorbis codec couldn't be read.
541 static bool get_vorbis_metadata(int fd, struct mp3entry* id3)
543 /* An Ogg File is split into pages, each starting with the string
544 * "OggS". Each page has a timestamp (in PCM samples) referred to as
545 * the "granule position".
547 * An Ogg Vorbis has the following structure:
548 * 1) Identification header (containing samplerate, numchannels, etc)
549 * 2) Comment header - containing the Vorbis Comments
550 * 3) Setup header - containing codec setup information
551 * 4) Many audio packets...
554 /* Use the path name of the id3 structure as a temporary buffer. */
555 unsigned char* buf = id3->path;
556 long comment_size;
557 long remaining = 0;
558 long last_serial = 0;
559 long serial;
560 int segments;
561 int i;
562 bool eof = false;
564 if ((lseek(fd, 0, SEEK_SET) < 0) || (read(fd, buf, 58) < 4))
566 return false;
569 if ((memcmp(buf, "OggS", 4) != 0) || (memcmp(&buf[29], "vorbis", 6) != 0))
571 return false;
574 /* We need to ensure the serial number from this page is the same as the
575 * one from the last page (since we only support a single bitstream).
577 serial = get_long(&buf[14]);
578 id3->frequency = get_long(&buf[40]);
579 id3->filesize = filesize(fd);
581 /* Comments are in second Ogg page */
582 if (lseek(fd, 58, SEEK_SET) < 0)
584 return false;
587 /* Minimum header length for Ogg pages is 27. */
588 if (read(fd, buf, 27) < 27)
590 return false;
593 if (memcmp(buf, "OggS", 4) !=0 )
595 return false;
598 segments = buf[26];
600 /* read in segment table */
601 if (read(fd, buf, segments) < segments)
603 return false;
606 /* The second packet in a vorbis stream is the comment packet. It *may*
607 * extend beyond the second page, but usually does not. Here we find the
608 * length of the comment packet (or the rest of the page if the comment
609 * packet extends to the third page).
611 for (i = 0; i < segments; i++)
613 remaining += buf[i];
615 /* The last segment of a packet is always < 255 bytes */
616 if (buf[i] < 255)
618 break;
622 /* Now read in packet header (type and id string) */
623 if (read(fd, buf, 7) < 7)
625 return false;
628 comment_size = remaining;
629 remaining -= 7;
631 /* The first byte of a packet is the packet type; comment packets are
632 * type 3.
634 if ((buf[0] != 3) || (memcmp(buf + 1, "vorbis", 6) !=0))
636 return false;
639 /* Failure to read the tags isn't fatal. */
640 read_vorbis_tags(fd, id3, remaining);
642 /* We now need to search for the last page in the file - identified by
643 * by ('O','g','g','S',0) and retrieve totalsamples.
646 if (lseek(fd, -64 * 1024, SEEK_END) < 0) /* A page is always < 64 kB */
648 return false;
651 remaining = 0;
653 while (!eof)
655 long r = read(fd, &buf[remaining], MAX_PATH - remaining);
657 if (r <= 0)
659 eof = true;
661 else
663 remaining += r;
666 /* Inefficient (but simple) search */
667 i = 0;
669 while (i < (remaining - 5))
671 if ((buf[i] == 'O') && (memcmp(&buf[i], "OggS", 4) == 0))
673 if (i < (remaining - 17))
675 /* Note that this only reads the low 32 bits of a
676 * 64 bit value.
678 id3->samples = get_long(&buf[i + 6]);
679 last_serial = get_long(&buf[i + 14]);
680 /* We can discard the rest of the buffer */
681 remaining = 0;
683 else
685 break;
688 else
690 i++;
694 if (i < (remaining - 5))
696 /* Move OggS to start of buffer. */
697 while (i >0)
699 buf[i--] = buf[remaining--];
702 else
704 remaining = 0;
708 /* This file has mutiple vorbis bitstreams (or is corrupt). */
709 /* FIXME we should display an error here. */
710 if (serial != last_serial)
712 logf("serialno mismatch");
713 logf("%ld", serial);
714 logf("%ld", last_serial);
715 return false;
718 id3->length = (id3->samples / id3->frequency) * 1000;
719 id3->bitrate = (((int64_t) id3->filesize - comment_size) * 8) / id3->length;
720 id3->vbr = true;
722 return true;
725 static bool get_flac_metadata(int fd, struct mp3entry* id3)
727 /* A simple parser to read vital metadata from a FLAC file - length,
728 * frequency, bitrate etc. This code should either be moved to a
729 * seperate file, or discarded in favour of the libFLAC code.
730 * The FLAC stream specification can be found at
731 * http://flac.sourceforge.net/format.html#stream
734 /* Use the trackname part of the id3 structure as a temporary buffer */
735 unsigned char* buf = id3->path;
736 bool rc = false;
738 if (!skip_id3v2(fd, id3) || (read(fd, buf, 4) < 4))
740 return rc;
743 if (memcmp(buf, "fLaC", 4) != 0)
745 return rc;
748 while (true)
750 long i;
752 if (read(fd, buf, 4) < 0)
754 return rc;
757 /* The length of the block */
758 i = (buf[1] << 16) | (buf[2] << 8) | buf[3];
760 if ((buf[0] & 0x7f) == 0) /* 0 is the STREAMINFO block */
762 unsigned long totalsamples;
764 /* FIXME: Don't trust the value of i */
765 if (read(fd, buf, i) < 0)
767 return rc;
770 id3->vbr = true; /* All FLAC files are VBR */
771 id3->filesize = filesize(fd);
772 id3->frequency = (buf[10] << 12) | (buf[11] << 4)
773 | ((buf[12] & 0xf0) >> 4);
774 rc = true; /* Got vital metadata */
776 /* totalsamples is a 36-bit field, but we assume <= 32 bits are used */
777 totalsamples = (buf[14] << 24) | (buf[15] << 16)
778 | (buf[16] << 8) | buf[17];
780 /* Calculate track length (in ms) and estimate the bitrate (in kbit/s) */
781 id3->length = (totalsamples / id3->frequency) * 1000;
782 id3->bitrate = (id3->filesize * 8) / id3->length;
784 else if ((buf[0] & 0x7f) == 4) /* 4 is the VORBIS_COMMENT block */
786 /* The next i bytes of the file contain the VORBIS COMMENTS. */
787 if (!read_vorbis_tags(fd, id3, i))
789 return rc;
792 else
794 if (buf[0] & 0x80)
796 /* If we have reached the last metadata block, abort. */
797 break;
799 else
801 /* Skip to next metadata block */
802 if (lseek(fd, i, SEEK_CUR) < 0)
804 return rc;
810 return true;
813 static bool get_wave_metadata(int fd, struct mp3entry* id3)
815 /* Use the trackname part of the id3 structure as a temporary buffer */
816 unsigned char* buf = id3->path;
817 unsigned long totalsamples = 0;
818 unsigned long channels = 0;
819 unsigned long bitspersample = 0;
820 unsigned long numbytes = 0;
821 int read_bytes;
822 int i;
824 if ((lseek(fd, 0, SEEK_SET) < 0)
825 || ((read_bytes = read(fd, buf, sizeof(id3->path))) < 44))
827 return false;
830 if ((memcmp(buf, "RIFF",4) != 0)
831 || (memcmp(&buf[8], "WAVE", 4) !=0 ))
833 return false;
836 buf += 12;
837 read_bytes -= 12;
839 while ((numbytes == 0) && (read_bytes >= 8))
841 /* chunkSize */
842 i = get_long(&buf[4]);
844 if (memcmp(buf, "fmt ", 4) == 0)
846 /* skipping wFormatTag */
847 /* wChannels */
848 channels = buf[10] | (buf[11] << 8);
849 /* dwSamplesPerSec */
850 id3->frequency = get_long(&buf[12]);
851 /* dwAvgBytesPerSec */
852 id3->bitrate = (get_long(&buf[16]) * 8) / 1000;
853 /* skipping wBlockAlign */
854 /* wBitsPerSample */
855 bitspersample = buf[22] | (buf[23] << 8);
857 else if (memcmp(buf, "data", 4) == 0)
859 numbytes = i;
861 else if (memcmp(buf, "fact", 4) == 0)
863 /* dwSampleLength */
864 if (i >= 4)
866 totalsamples = get_long(&buf[8]);
870 /* go to next chunk (even chunk sizes must be padded) */
871 if (i & 0x01)
873 i++;
876 buf += i + 8;
877 read_bytes -= i + 8;
880 if ((numbytes == 0) || (channels == 0))
882 return false;
885 if (totalsamples == 0)
887 /* for PCM only */
888 totalsamples = numbytes
889 / ((((bitspersample - 1) / 8) + 1) * channels);
892 id3->vbr = false; /* All WAV files are CBR */
893 id3->filesize = filesize(fd);
895 /* Calculate track length (in ms) and estimate the bitrate (in kbit/s) */
896 id3->length = (totalsamples / id3->frequency) * 1000;
898 return true;
902 static bool get_m4a_metadata(int fd, struct mp3entry* id3)
904 unsigned char* buf;
905 unsigned long totalsamples;
906 int i,j,k;
907 size_t n;
908 size_t bytes_remaining;
909 char* id3buf;
910 unsigned int compressedsize;
911 unsigned int sample_count;
912 unsigned int sample_duration;
913 int numentries;
914 int entry_size;
915 int size_remaining;
916 int chunk_len;
917 unsigned char chunk_id[4];
918 int sub_chunk_len;
919 unsigned char sub_chunk_id[4];
921 /* A simple parser to read vital metadata from an ALAC file.
922 This parser also works for AAC files - they are both stored in
923 a Quicktime M4A container. */
925 /* Use the trackname part of the id3 structure as a temporary buffer */
926 buf=id3->path;
928 lseek(fd, 0, SEEK_SET);
930 totalsamples=0;
931 compressedsize=0;
932 /* read the chunks - we stop when we find the mdat chunk and set compressedsize */
933 while (compressedsize==0) {
934 n=read_uint32be(fd,&chunk_len);
936 // This means it was a 64-bit file, so we have problems.
937 if (chunk_len == 1) {
938 logf("need 64bit support\n");
939 return false;
942 n=read(fd,&chunk_id,4);
943 if (memcmp(&chunk_id,"ftyp",4)==0) {
944 /* Check for M4A type */
945 n=read(fd,&chunk_id,4);
946 if ((memcmp(&chunk_id,"M4A ",4)!=0) &&
947 (memcmp(&chunk_id,"mp42",4)!=0)) {
948 logf("Not an M4A file, aborting\n");
949 return false;
951 /* Skip rest of chunk */
952 lseek(fd, chunk_len - 8 - 4, SEEK_CUR); /* FIXME not 8 */
953 } else if (memcmp(&chunk_id,"moov",4)==0) {
954 size_remaining=chunk_len - 8; /* FIXME not 8 */
956 while (size_remaining > 0) {
957 n=read_uint32be(fd,&sub_chunk_len);
958 if ((sub_chunk_len < 1) || (sub_chunk_len > size_remaining)) {
959 logf("Strange sub_chunk_len value inside moov: %d (remaining: %d)\n",sub_chunk_len,size_remaining);
960 return false;
962 n=read(fd,&sub_chunk_id,4);
963 size_remaining-=8;
965 if (memcmp(&sub_chunk_id,"mvhd",4)==0) {
966 /* We don't need anything from here - skip */
967 lseek(fd, sub_chunk_len - 8, SEEK_CUR); /* FIXME not 8 */
968 size_remaining-=(sub_chunk_len-8);
969 } else if (memcmp(&sub_chunk_id,"udta",4)==0) {
970 /* The udta chunk contains the metadata - track, artist, album etc.
971 The format appears to be:
972 udta
973 meta
974 hdlr
975 ilst
976 .nam
977 [rest of tags]
978 free
980 NOTE: This code was written by examination of some .m4a files
981 produced by iTunes v4.9 - it may not therefore be 100%
982 compliant with all streams. But it should fail gracefully.
984 j=(sub_chunk_len-8);
985 size_remaining-=j;
986 n=read_uint32be(fd,&sub_chunk_len);
987 n=read(fd,&sub_chunk_id,4);
988 j-=8;
989 if (memcmp(&sub_chunk_id,"meta",4)==0) {
990 lseek(fd, 4, SEEK_CUR);
991 j-=4;
992 n=read_uint32be(fd,&sub_chunk_len);
993 n=read(fd,&sub_chunk_id,4);
994 j-=8;
995 if (memcmp(&sub_chunk_id,"hdlr",4)==0) {
996 lseek(fd, sub_chunk_len - 8, SEEK_CUR);
997 j-=(sub_chunk_len - 8);
998 n=read_uint32be(fd,&sub_chunk_len);
999 n=read(fd,&sub_chunk_id,4);
1000 j-=8;
1001 if (memcmp(&sub_chunk_id,"ilst",4)==0) {
1002 /* Here are the actual tags. We use the id3v2 300-byte buffer
1003 to store the string data */
1004 bytes_remaining=sizeof(id3->id3v2buf);
1005 id3->genre=255; /* Not every track is the Blues */
1006 id3buf=id3->id3v2buf;
1007 k=sub_chunk_len-8;
1008 j-=k;
1009 while (k > 0) {
1010 n=read_uint32be(fd,&sub_chunk_len);
1011 n=read(fd,&sub_chunk_id,4);
1012 k-=8;
1013 if (memcmp(sub_chunk_id,"\251nam",4)==0) {
1014 read_m4a_tag_string(fd,sub_chunk_len-8,&id3buf,&bytes_remaining,&id3->title);
1015 } else if (memcmp(sub_chunk_id,"\251ART",4)==0) {
1016 read_m4a_tag_string(fd,sub_chunk_len-8,&id3buf,&bytes_remaining,&id3->artist);
1017 } else if (memcmp(sub_chunk_id,"\251alb",4)==0) {
1018 read_m4a_tag_string(fd,sub_chunk_len-8,&id3buf,&bytes_remaining,&id3->album);
1019 } else if (memcmp(sub_chunk_id,"\251gen",4)==0) {
1020 read_m4a_tag_string(fd,sub_chunk_len-8,&id3buf,&bytes_remaining,&id3->genre_string);
1021 } else if (memcmp(sub_chunk_id,"\251day",4)==0) {
1022 read_m4a_tag_string(fd,sub_chunk_len-8,&id3buf,&bytes_remaining,&id3->year_string);
1023 } else if (memcmp(sub_chunk_id,"trkn",4)==0) {
1024 if (sub_chunk_len==0x20) {
1025 read(fd,buf,sub_chunk_len-8);
1026 id3->tracknum=buf[19];
1027 } else {
1028 lseek(fd, sub_chunk_len-8,SEEK_CUR);
1030 } else {
1031 lseek(fd, sub_chunk_len-8,SEEK_CUR);
1033 k-=(sub_chunk_len-8);
1038 /* Skip any remaining data in udta chunk */
1039 lseek(fd, j, SEEK_CUR);
1040 } else if (memcmp(&sub_chunk_id,"trak",4)==0) {
1041 /* Format of trak chunk:
1042 tkhd
1043 mdia
1044 mdhd
1045 hdlr
1046 minf
1047 smhd
1048 dinf
1049 stbl
1050 stsd - Samplerate, Samplesize, Numchannels
1051 stts - time_to_sample array - RLE'd table containing duration of each block
1052 stsz - sample_byte_size array - ?Size in bytes of each compressed block
1053 stsc - Seek table related?
1054 stco - Seek table related?
1057 /* Skip tkhd - not needed */
1058 n=read_uint32be(fd,&sub_chunk_len);
1059 n=read(fd,&sub_chunk_id,4);
1060 if (memcmp(&sub_chunk_id,"tkhd",4)!=0) {
1061 logf("Expecting tkhd\n");
1062 return false;
1064 lseek(fd, sub_chunk_len - 8, SEEK_CUR); /* FIXME not 8 */
1065 size_remaining-=sub_chunk_len;
1067 /* Process mdia - skipping possible edts */
1068 n=read_uint32be(fd,&sub_chunk_len);
1069 n=read(fd,&sub_chunk_id,4);
1070 if (memcmp(&sub_chunk_id,"edts",4)==0) {
1071 lseek(fd, sub_chunk_len - 8, SEEK_CUR); /* FIXME not 8 */
1072 size_remaining-=sub_chunk_len;
1073 n=read_uint32be(fd,&sub_chunk_len);
1074 n=read(fd,&sub_chunk_id,4);
1077 if (memcmp(&sub_chunk_id,"mdia",4)!=0) {
1078 logf("Expecting mdia\n");
1079 return false;
1081 size_remaining-=sub_chunk_len;
1082 j=sub_chunk_len-8;
1084 while (j > 0) {
1085 n=read_uint32be(fd,&sub_chunk_len);
1086 n=read(fd,&sub_chunk_id,4);
1087 j-=4;
1088 if (memcmp(&sub_chunk_id,"minf",4)==0) {
1089 j=sub_chunk_len-8;
1090 } else if (memcmp(&sub_chunk_id,"stbl",4)==0) {
1091 j=sub_chunk_len-8;
1092 } else if (memcmp(&sub_chunk_id,"stsd",4)==0) {
1093 n=read(fd,buf,sub_chunk_len-8);
1094 j-=sub_chunk_len;
1095 i=0;
1096 /* Skip version and flags */
1097 i+=4;
1099 numentries=(buf[i]<<24)|(buf[i+1]<<16)|(buf[i+2]<<8)|buf[i+3];
1100 i+=4;
1101 if (numentries!=1) {
1102 logf("ERROR: Expecting only one entry in stsd\n");
1105 entry_size=(buf[i]<<24)|(buf[i+1]<<16)|(buf[i+2]<<8)|buf[i+3];
1106 i+=4;
1108 if (memcmp(&buf[i],"alac",4)==0) {
1109 id3->codectype=AFMT_ALAC;
1110 } else if (memcmp(&buf[i],"mp4a",4)==0) {
1111 id3->codectype=AFMT_AAC;
1112 } else {
1113 logf("Not an ALAC or AAC file\n");
1114 return false;
1117 //numchannels=(buf[i+20]<<8)|buf[i+21]; /* Not used - assume Stereo */
1118 //samplesize=(buf[i+22]<<8)|buf[i+23]; /* Not used - assume 16-bit */
1120 /* Samplerate is 32-bit fixed point, but this works for < 65536 Hz */
1121 id3->frequency=(buf[i+28]<<8)|buf[i+29];
1122 } else if (memcmp(&sub_chunk_id,"stts",4)==0) {
1123 j-=sub_chunk_len;
1124 i=8;
1125 n=read(fd,buf,8);
1126 i+=8;
1127 numentries=(buf[4]<<24)|(buf[5]<<16)|(buf[6]<<8)|buf[7];
1128 for (k=0;k<numentries;k++) {
1129 n=read_uint32be(fd,&sample_count);
1130 n=read_uint32be(fd,&sample_duration);
1131 totalsamples+=sample_count*sample_duration;
1132 i+=8;
1134 if (i > 0) lseek(fd, sub_chunk_len - i, SEEK_CUR);
1135 } else if (memcmp(&sub_chunk_id,"stsz",4)==0) {
1136 j-=sub_chunk_len;
1137 i=8;
1138 n=read(fd,buf,8);
1139 i+=8;
1140 numentries=(buf[4]<<24)|(buf[5]<<16)|(buf[6]<<8)|buf[7];
1141 for (k=0;k<numentries;k++) {
1142 n=read_uint32be(fd,&sample_count);
1143 n=read_uint32be(fd,&sample_duration);
1144 totalsamples+=sample_count*sample_duration;
1145 i+=8;
1147 if (i > 0) lseek(fd, sub_chunk_len - i, SEEK_CUR);
1148 } else {
1149 lseek(fd, sub_chunk_len - 8, SEEK_CUR); /* FIXME not 8 */
1150 j-=sub_chunk_len;
1153 } else {
1154 logf("Unexpected sub_chunk_id inside moov: %c%c%c%c\n",
1155 sub_chunk_id[0],sub_chunk_id[1],sub_chunk_id[2],sub_chunk_id[3]);
1156 return false;
1159 } else if (memcmp(&chunk_id,"mdat",4)==0) {
1160 /* once we hit mdat we stop reading and return.
1161 * this is on the assumption that there is no furhter interesting
1162 * stuff in the stream. if there is stuff will fail (:()).
1163 * But we need the read pointer to be at the mdat stuff
1164 * for the decoder. And we don't want to rely on fseek/ftell,
1165 * as they may not always be avilable */
1166 lseek(fd, chunk_len - 8, SEEK_CUR); /* FIXME not 8 */
1167 compressedsize=chunk_len-8;
1168 } else if (memcmp(&chunk_id,"free",4)==0) {
1169 /* these following atoms can be skipped !!!! */
1170 lseek(fd, chunk_len - 8, SEEK_CUR); /* FIXME not 8 */
1171 } else {
1172 logf("(top) unknown chunk id: %c%c%c%c\n", chunk_id[0],chunk_id[1],chunk_id[2],chunk_id[3]);
1173 return false;
1177 id3->vbr=true; /* All ALAC files are VBR */
1178 id3->filesize=filesize(fd);
1179 id3->samples=totalsamples;
1180 id3->length=(10*totalsamples)/(id3->frequency/100);
1181 id3->bitrate=(compressedsize*8)/id3->length;;
1183 return true;
1186 static bool get_musepack_metadata(int fd, struct mp3entry *id3)
1188 const int32_t sfreqs_sv7[4] = { 44100, 48000, 37800, 32000 };
1189 uint32_t header[8];
1190 uint64_t samples = 0;
1191 int i;
1193 if (!skip_id3v2(fd, id3))
1194 return false;
1195 if (read(fd, header, 4*8) != 4*8) return false;
1196 /* Musepack files are little endian, might need swapping */
1197 for (i = 1; i < 8; i++)
1198 header[i] = letoh32(header[i]);
1199 if (!memcmp(header, "MP+", 3)) { /* Compare to sig "MP+" */
1200 unsigned int streamversion;
1202 header[0] = letoh32(header[0]);
1203 streamversion = (header[0] >> 24) & 15;
1204 if (streamversion >= 8) {
1205 return false; /* SV8 or higher don't exist yet, so no support */
1206 } else if (streamversion == 7) {
1207 unsigned int gapless = (header[5] >> 31) & 0x0001;
1208 unsigned int last_frame_samples = (header[5] >> 20) & 0x07ff;
1209 int track_gain, album_gain;
1210 unsigned int bufused;
1212 id3->frequency = sfreqs_sv7[(header[2] >> 16) & 0x0003];
1213 samples = (uint64_t)header[1]*1152; /* 1152 is mpc frame size */
1214 if (gapless)
1215 samples -= 1152 - last_frame_samples;
1216 else
1217 samples -= 481; /* Musepack subband synth filter delay */
1219 /* Extract ReplayGain data from header */
1220 track_gain = (int16_t)((header[3] >> 16) & 0xffff);
1221 id3->track_gain = get_replaygain_int(track_gain);
1222 id3->track_peak = ((uint16_t)(header[3] & 0xffff)) << 9;
1224 album_gain = (int16_t)((header[4] >> 16) & 0xffff);
1225 id3->album_gain = get_replaygain_int(album_gain);
1226 id3->album_peak = ((uint16_t)(header[4] & 0xffff)) << 9;
1228 /* Write replaygain values to strings for use in id3 screen. We use
1229 the XING header as buffer space since Musepack files shouldn't
1230 need to use it in any other way */
1231 id3->track_gain_string = id3->toc;
1232 bufused = snprintf(id3->track_gain_string, 45,
1233 "%d.%d dB", track_gain/100, abs(track_gain)%100);
1234 id3->album_gain_string = id3->toc + bufused + 1;
1235 bufused = snprintf(id3->album_gain_string, 45,
1236 "%d.%d dB", album_gain/100, abs(album_gain)%100);
1238 } else {
1239 /* There's no certain way to detect these pre-sv7 streams, apparently */
1240 /* TODO: add sv6 parsing here */
1241 return false;
1244 id3->vbr = true;
1245 /* Estimate bitrate, we should probably subtract the various header sizes
1246 here for super-accurate results */
1247 id3->length = samples/id3->frequency*1000;
1248 id3->filesize = filesize(fd);
1249 id3->bitrate = id3->filesize*8/id3->length;
1250 return true;
1252 #endif /* CONFIG_CODEC == SWCODEC */
1254 static bool get_aiff_metadata(int fd, struct mp3entry* id3)
1256 /* Use the trackname part of the id3 structure as a temporary buffer */
1257 unsigned char* buf = id3->path;
1258 unsigned long numChannels = 0;
1259 unsigned long numSampleFrames = 0;
1260 unsigned long sampleSize = 0;
1261 unsigned long sampleRate = 0;
1262 unsigned long numbytes = 0;
1263 int read_bytes;
1264 int i;
1266 if ((lseek(fd, 0, SEEK_SET) < 0)
1267 || ((read_bytes = read(fd, buf, sizeof(id3->path))) < 44))
1269 return false;
1272 if ((memcmp(buf, "FORM",4) != 0)
1273 || (memcmp(&buf[8], "AIFF", 4) !=0 ))
1275 return false;
1278 buf += 12;
1279 read_bytes -= 12;
1281 while ((numbytes == 0) && (read_bytes >= 8))
1283 /* chunkSize */
1284 i = ((buf[4]<<24)|(buf[5]<<16)|(buf[6]<<8)|buf[7]);
1286 if (memcmp(buf, "COMM", 4) == 0)
1288 /* numChannels */
1289 numChannels = ((buf[8]<<8)|buf[9]);
1290 /* numSampleFrames */
1291 numSampleFrames =((buf[10]<<24)|(buf[11]<<16)|(buf[12]<<8)|buf[13]);
1292 /* sampleSize */
1293 sampleSize = ((buf[14]<<8)|buf[15]);
1294 /* sampleRate */
1295 sampleRate = ((buf[18]<<24)|(buf[19]<<16)|(buf[20]<<8)|buf[21]);
1296 sampleRate = sampleRate >> (16+14-buf[17]);
1297 /* save format infos */
1298 id3->bitrate = (sampleSize * numChannels * sampleRate) / 1000;
1299 id3->frequency = sampleRate;
1300 id3->length = (numSampleFrames / id3->frequency) * 1000;
1301 id3->vbr = false; /* AIFF files are CBR */
1302 id3->filesize = filesize(fd);
1304 else if (memcmp(buf, "SSND", 4) == 0)
1306 numbytes = i - 8;
1309 if (i & 0x01)
1311 i++; /* odd chunk sizes must be padded */
1313 buf += i + 8;
1314 read_bytes -= i + 8;
1317 if ((numbytes == 0) || (numChannels == 0))
1319 return false;
1321 return true;
1324 /* Simple file type probing by looking at the filename extension. */
1325 unsigned int probe_file_format(const char *filename)
1327 char *suffix;
1328 unsigned int i;
1330 suffix = strrchr(filename, '.');
1332 if (suffix == NULL)
1334 return AFMT_UNKNOWN;
1337 suffix += 1;
1339 for (i = 0; i < sizeof(formats) / sizeof(formats[0]); i++)
1341 if (strcasecmp(suffix, formats[i].extension) == 0)
1343 return formats[i].format;
1347 return AFMT_UNKNOWN;
1350 /* Get metadata for track - return false if parsing showed problems with the
1351 * file that would prevent playback.
1353 bool get_metadata(struct track_info* track, int fd, const char* trackname,
1354 bool v1first)
1356 #if CONFIG_CODEC == SWCODEC
1357 unsigned char* buf;
1358 unsigned long totalsamples;
1359 int i;
1360 #endif
1362 /* Take our best guess at the codec type based on file extension */
1363 track->id3.codectype = probe_file_format(trackname);
1365 /* Load codec specific track tag information and confirm the codec type. */
1366 switch (track->id3.codectype)
1368 case AFMT_MPA_L1:
1369 case AFMT_MPA_L2:
1370 case AFMT_MPA_L3:
1371 if (mp3info(&track->id3, trackname, v1first))
1373 return false;
1376 break;
1378 #if CONFIG_CODEC == SWCODEC
1379 case AFMT_FLAC:
1380 if (!get_flac_metadata(fd, &(track->id3)))
1382 return false;
1385 break;
1387 case AFMT_MPC:
1388 if (!get_musepack_metadata(fd, &(track->id3)))
1389 return false;
1390 read_ape_tags(fd, &(track->id3));
1391 break;
1393 case AFMT_OGG_VORBIS:
1394 if (!get_vorbis_metadata(fd, &(track->id3)))
1396 return false;
1399 break;
1401 case AFMT_PCM_WAV:
1402 if (!get_wave_metadata(fd, &(track->id3)))
1404 return false;
1407 break;
1409 case AFMT_WAVPACK:
1410 /* A simple parser to read basic information from a WavPack file.
1411 * This will fail on WavPack files that don't have the WavPack header
1412 * as the first thing (i.e. self-extracting WavPack files) or WavPack
1413 * files that have so much extra RIFF data stored in the first block
1414 * that they don't have samples (very rare, I would think).
1417 /* Use the trackname part of the id3 structure as a temporary buffer */
1418 buf = track->id3.path;
1420 if ((lseek(fd, 0, SEEK_SET) < 0) || (read(fd, buf, 32) < 32))
1422 return false;
1425 if (memcmp (buf, "wvpk", 4) != 0 || buf [9] != 4 || buf [8] < 2)
1427 logf ("%s is not a WavPack file\n", trackname);
1428 return false;
1431 track->id3.vbr = true; /* All WavPack files are VBR */
1432 track->id3.filesize = filesize (fd);
1434 if ((buf [20] | buf [21] | buf [22] | buf [23]) &&
1435 (buf [12] & buf [13] & buf [14] & buf [15]) != 0xff)
1437 int srindx = ((buf [26] >> 7) & 1) + ((buf [27] << 1) & 14);
1439 if (srindx == 15)
1441 track->id3.frequency = 44100;
1443 else
1445 track->id3.frequency = wavpack_sample_rates[srindx];
1448 totalsamples = get_long(&buf[12]);
1449 track->id3.length = totalsamples / (track->id3.frequency / 100) * 10;
1450 track->id3.bitrate = filesize (fd) / (track->id3.length / 8);
1453 read_ape_tags(fd, &track->id3); /* use any apetag info we find */
1454 break;
1456 case AFMT_A52:
1457 /* Use the trackname part of the id3 structure as a temporary buffer */
1458 buf = track->id3.path;
1460 if ((lseek(fd, 0, SEEK_SET) < 0) || (read(fd, buf, 5) < 5))
1462 return false;
1465 if ((buf[0] != 0x0b) || (buf[1] != 0x77))
1467 logf("%s is not an A52/AC3 file\n",trackname);
1468 return false;
1471 i = buf[4] & 0x3e;
1473 if (i > 36)
1475 logf("A52: Invalid frmsizecod: %d\n",i);
1476 return false;
1479 track->id3.bitrate = a52_bitrates[i >> 1];
1480 track->id3.vbr = false;
1481 track->id3.filesize = filesize(fd);
1483 switch (buf[4] & 0xc0)
1485 case 0x00:
1486 track->id3.frequency = 48000;
1487 track->id3.bytesperframe=track->id3.bitrate * 2 * 2;
1488 break;
1490 case 0x40:
1491 track->id3.frequency = 44100;
1492 track->id3.bytesperframe = a52_441framesizes[i];
1493 break;
1495 case 0x80:
1496 track->id3.frequency = 32000;
1497 track->id3.bytesperframe = track->id3.bitrate * 3 * 2;
1498 break;
1500 default:
1501 logf("A52: Invalid samplerate code: 0x%02x\n", buf[4] & 0xc0);
1502 return false;
1503 break;
1506 /* One A52 frame contains 6 blocks, each containing 256 samples */
1507 totalsamples = (track->filesize / track->id3.bytesperframe) * 6 * 256;
1508 track->id3.length = (totalsamples / track->id3.frequency) * 1000;
1509 break;
1511 case AFMT_ALAC:
1512 case AFMT_AAC:
1513 if (!get_m4a_metadata(fd, &(track->id3)))
1515 return false;
1518 break;
1520 case AFMT_SHN:
1521 track->id3.vbr = true;
1522 track->id3.filesize = filesize(fd);
1523 if (!skip_id3v2(fd, &(track->id3)))
1525 return false;
1527 /* TODO: read the id3v2 header if it exists */
1528 break;
1529 #endif /* CONFIG_CODEC == SWCODEC */
1531 case AFMT_AIFF:
1532 if (!get_aiff_metadata(fd, &(track->id3)))
1534 return false;
1537 break;
1539 default:
1540 /* If we don't know how to read the metadata, assume we can't play
1541 the file */
1542 return false;
1543 break;
1546 /* We have successfully read the metadata from the file */
1548 lseek(fd, 0, SEEK_SET);
1549 strncpy(track->id3.path, trackname, sizeof(track->id3.path));
1550 track->taginfo_ready = true;
1552 return true;