2 * Copyright (C) 2003-2005 M. Bakker, Nero AG, http://www.nero.com
3 * FAAD2 - Freeware Advanced Audio (AAC) Decoder including SBR decoding
12 #include "portable_io.h"
17 * The three states of the mp4 parser. The parser only loads the audio specific
18 * values and tables when it is in the second state.
20 enum audio_track_state {
21 /** We haven't encountered an mp4a atom so far. */
23 /** We have seen an mp4a atom but no subsequent trak atom yet. */
25 /** A trak atom was seen *after* the mp4a atom. */
30 /* determines which atoms we still need to parse. */
31 enum audio_track_state state;
34 uint16_t channel_count;
38 uint32_t stsz_sample_size;
39 uint32_t stsz_sample_count;
43 uint32_t stts_entry_count;
44 uint32_t *stts_sample_count;
47 uint32_t stsc_entry_count;
48 uint32_t *stsc_first_chunk;
49 uint32_t *stsc_samples_per_chunk;
52 uint32_t stco_entry_count;
53 uint32_t *stco_chunk_offset;
61 const struct mp4_callback *cb;
73 struct mp4_track track;
74 struct mp4_metadata meta;
78 * Returns -1, 0, or 1 on errors/EOF/success. Partial reads followed by EOF or
79 * read errors are treated as errors.
81 static int read_data(struct mp4 *f, void *data, size_t size)
84 ssize_t ret = f->cb->read(f->cb->user_data, data, size);
85 if (ret < 0 && errno == EINTR)
87 /* regard EAGAIN as an error as reads should be blocking. */
89 return ret < 0? -1 : 0;
95 static int read_int64(struct mp4 *f, uint64_t *result)
98 int ret = read_data(f, data, 8);
101 *result = read_u64_be(data);
105 static int read_int32(struct mp4 *f, uint32_t *result)
108 int ret = read_data(f, data, 4);
111 *result = read_u32_be(data);
115 static int read_int16(struct mp4 *f, uint16_t *result)
118 int ret = read_data(f, data, 2);
121 *result = read_u16_be(data);
126 ATOM_ITEM(MOOV, 'm', 'o', 'o', 'v') \
127 ATOM_ITEM(TRAK, 't', 'r', 'a', 'k') \
128 ATOM_ITEM(MDIA, 'm', 'd', 'i', 'a') \
129 ATOM_ITEM(MINF, 'm', 'i', 'n', 'f') \
130 ATOM_ITEM(STBL, 's', 't', 'b', 'l') \
131 ATOM_ITEM(UDTA, 'u', 'd', 't', 'a') \
132 ATOM_ITEM(ILST, 'i', 'l', 's', 't') /* iTunes Metadata list */ \
133 ATOM_ITEM(ARTIST, 0xa9, 'A', 'R', 'T') \
134 ATOM_ITEM(TITLE, 0xa9, 'n', 'a', 'm') \
135 ATOM_ITEM(ALBUM, 0xa9, 'a', 'l', 'b') \
136 ATOM_ITEM(DATE, 0xa9, 'd', 'a', 'y') \
137 ATOM_ITEM(COMMENT, 0xa9, 'c', 'm', 't') \
138 ATOM_ITEM(MDHD, 'm', 'd', 'h', 'd') /* track header */ \
139 ATOM_ITEM(STSD, 's', 't', 's', 'd') /* sample description box */ \
140 ATOM_ITEM(STTS, 's', 't', 't', 's') /* time to sample box */ \
141 ATOM_ITEM(STSZ, 's', 't', 's', 'z') /* sample size box */ \
142 ATOM_ITEM(STCO, 's', 't', 'c', 'o') /* chunk offset box */ \
143 ATOM_ITEM(STSC, 's', 't', 's', 'c') /* sample to chunk box */ \
144 ATOM_ITEM(MP4A, 'm', 'p', '4', 'a') \
145 ATOM_ITEM(META, 'm', 'e', 't', 'a') /* iTunes Metadata box */ \
146 ATOM_ITEM(DATA, 'd', 'a', 't', 'a') /* iTunes Metadata data box */ \
148 #define ATOM_ITEM(_name, a, b, c, d) ATOM_ ## _name,
149 enum atom {ATOM_ITEMS};
152 static uint8_t atom_name_to_type(uint8_t *p)
154 #define ATOM_VALUE(a, b, c, d) ((a << 24) + (b << 16) + (c << 8) + d)
155 #define ATOM_ITEM(_name, a, b, c, d) \
156 {.name = # _name, .val = ATOM_VALUE(a, b, c, d)},
157 static const struct {
160 } atom_table[] = {ATOM_ITEMS};
162 uint32_t val = read_u32_be(p);
164 for (uint8_t n = 0; n < ARRAY_SIZE(atom_table); n++)
165 if (val == atom_table[n].val)
170 /* read atom header, atom size is returned with header included. */
171 static int atom_read_header(struct mp4 *f, uint8_t *atom_type,
172 uint8_t *header_size, uint64_t *atom_size)
176 uint8_t atom_header[8];
178 ret = read_data(f, atom_header, 8);
181 size = read_u32_be(atom_header);
182 if (size == 1) { /* 64 bit atom size */
185 ret = read_int64(f, atom_size);
193 *atom_type = atom_name_to_type(atom_header + 4);
197 static off_t get_position(const struct mp4 *f)
199 return f->cb->seek(f->cb->user_data, 0, SEEK_CUR);
202 static void set_position(struct mp4 *f, off_t position)
204 f->cb->seek(f->cb->user_data, position, SEEK_SET);
207 static void skip_bytes(struct mp4 *f, off_t num_skip)
209 f->cb->seek(f->cb->user_data, num_skip, SEEK_CUR);
212 static int read_stsz(struct mp4 *f)
216 struct mp4_track *t = &f->track;
218 if (t->state != ATS_SEEN_MP4A || t->stsz_table)
220 skip_bytes(f, 4); /* version (1), flags (3) */
221 ret = read_int32(f, &t->stsz_sample_size);
224 ret = read_int32(f, &t->stsz_sample_count);
227 if (t->stsz_sample_size != 0)
229 t->stsz_table = para_malloc(t->stsz_sample_count * sizeof(int32_t));
230 for (i = 0; i < t->stsz_sample_count; i++) {
231 ret = read_int32(f, &t->stsz_table[i]);
238 static int read_stts(struct mp4 *f)
242 struct mp4_track *t = &f->track;
244 if (t->state != ATS_SEEN_MP4A || t->stts_sample_count)
246 skip_bytes(f, 4); /* version (1), flags (3) */
247 ret = read_int32(f, &t->stts_entry_count);
250 t->stts_sample_count = para_malloc(t->stts_entry_count
252 for (i = 0; i < t->stts_entry_count; i++) {
253 ret = read_int32(f, &t->stts_sample_count[i]);
256 skip_bytes(f, 4); /* sample delta */
261 static int read_stsc(struct mp4 *f)
265 struct mp4_track *t = &f->track;
267 if (t->state != ATS_SEEN_MP4A)
269 if (t->stsc_first_chunk || t->stsc_samples_per_chunk)
271 skip_bytes(f, 4); /* version (1), flags (3) */
272 ret = read_int32(f, &t->stsc_entry_count);
275 t->stsc_first_chunk = para_malloc(t->stsc_entry_count * sizeof(int32_t));
276 t->stsc_samples_per_chunk = para_malloc(t->stsc_entry_count
278 for (i = 0; i < t->stsc_entry_count; i++) {
279 ret = read_int32(f, &t->stsc_first_chunk[i]);
282 ret = read_int32(f, &t->stsc_samples_per_chunk[i]);
285 skip_bytes(f, 4); /* sample desc index */
290 static int read_stco(struct mp4 *f)
294 struct mp4_track *t = &f->track;
296 if (t->state != ATS_SEEN_MP4A || t->stco_chunk_offset)
298 skip_bytes(f, 4); /* version (1), flags (3) */
299 ret = read_int32(f, &t->stco_entry_count);
302 t->stco_chunk_offset = para_malloc(t->stco_entry_count
304 for (i = 0; i < t->stco_entry_count; i++) {
305 ret = read_int32(f, &t->stco_chunk_offset[i]);
312 static int read_stsd(struct mp4 *f)
315 uint32_t i, entry_count;
317 if (f->track.state != ATS_INITIAL)
319 skip_bytes(f, 4); /* version (1), flags (3) */
320 ret = read_int32(f, &entry_count);
323 for (i = 0; i < entry_count; i++) {
324 uint64_t skip = get_position(f);
326 uint8_t atom_type = 0;
327 ret = atom_read_header(f, &atom_type, NULL, &size);
331 if (atom_type == ATOM_MP4A) {
332 f->track.state = ATS_SEEN_MP4A;
333 /* reserved (6), data reference index (2), reserved (8) */
335 ret = read_int16(f, &f->track.channel_count);
339 ret = read_int16(f, &f->track.sample_rate);
343 set_position(f, skip);
348 static const char *get_metadata_name(uint8_t atom_type)
351 case ATOM_TITLE: return "title";
352 case ATOM_ARTIST: return "artist";
353 case ATOM_ALBUM: return "album";
354 case ATOM_DATE: return "date";
355 case ATOM_COMMENT: return "comment";
356 default: return "unknown";
360 static int parse_tag(struct mp4 *f, uint8_t parent, int32_t size)
363 uint64_t subsize, sumsize;
372 set_position(f, destpos), sumsize += subsize
375 uint8_t header_size = 0;
376 ret = atom_read_header(f, &atom_type, &header_size, &subsize);
379 destpos = get_position(f) + subsize - header_size;
380 if (atom_type != ATOM_DATA)
382 skip_bytes(f, 8); /* version (1), flags (3), reserved (4) */
383 ret = -ERRNO_TO_PARA_ERROR(EINVAL);
384 if (subsize < header_size + 8 || subsize > UINT_MAX)
386 len = subsize - (header_size + 8);
388 value = para_malloc(len + 1);
389 ret = read_data(f, value, len);
395 return -ERRNO_TO_PARA_ERROR(EINVAL);
396 f->meta.tags = para_realloc(f->meta.tags, (f->meta.count + 1)
397 * sizeof(struct mp4_tag));
398 tag = f->meta.tags + f->meta.count;
399 tag->item = para_strdup(get_metadata_name(parent));
409 static int read_mdhd(struct mp4 *f)
413 struct mp4_track *t = &f->track;
415 if (t->state != ATS_INITIAL)
417 ret = read_int32(f, &version);
421 skip_bytes(f, 16); /* creation time (8), modification time (8) */
422 ret = read_int32(f, &t->time_scale);
425 ret = read_int64(f, &t->duration);
428 } else { //version == 0
431 skip_bytes(f, 8); /* creation time (4), modification time (4) */
432 ret = read_int32(f, &t->time_scale);
435 ret = read_int32(f, &temp);
438 t->duration = (temp == (uint32_t) (-1))?
439 (uint64_t) (-1) : (uint64_t) (temp);
445 static int32_t read_ilst(struct mp4 *f, int32_t size)
448 uint64_t sumsize = 0;
450 while (sumsize < size) {
452 uint64_t subsize, destpos;
453 uint8_t header_size = 0;
454 ret = atom_read_header(f, &atom_type, &header_size, &subsize);
457 destpos = get_position(f) + subsize - header_size;
464 ret = parse_tag(f, atom_type, subsize - header_size);
468 set_position(f, destpos);
474 static int32_t read_meta(struct mp4 *f, uint64_t size)
477 uint64_t subsize, sumsize = 0;
479 uint8_t header_size = 0;
481 skip_bytes(f, 4); /* version (1), flags (3) */
482 while (sumsize < (size - (header_size + 4))) {
483 ret = atom_read_header(f, &atom_type, &header_size, &subsize);
486 if (subsize <= header_size + 4)
488 if (atom_type == ATOM_ILST) {
489 f->ilst_offset = get_position(f) - header_size;
490 f->ilst_size = subsize;
491 ret = read_ilst(f, subsize - (header_size + 4));
495 set_position(f, get_position(f) + subsize - header_size);
501 static bool need_atom(uint8_t atom_type, bool meta_only)
503 /* these are needed in any case */
514 /* meta-only opens don't need anything else */
517 /* these are only required for regular opens */
529 /* parse atoms that are sub atoms of other atoms */
530 static int parse_sub_atoms(struct mp4 *f, uint64_t total_size, bool meta_only)
533 uint64_t dest, size, end = get_position(f) + total_size;
535 for (dest = get_position(f); dest < end; set_position(f, dest)) {
536 uint8_t header_size, atom_type;
537 ret = atom_read_header(f, &atom_type, &header_size, &size);
542 dest = get_position(f) + size - header_size;
543 if (atom_type == ATOM_TRAK && f->track.state == ATS_SEEN_MP4A) {
544 f->track.state = ATS_TRACK_CHANGE;
547 if (atom_type == ATOM_UDTA) {
548 f->udta_offset = get_position(f) - header_size;
551 if (!need_atom(atom_type, meta_only))
554 case ATOM_STSZ: ret = read_stsz(f); break;
555 case ATOM_STTS: ret = read_stts(f); break;
556 case ATOM_STSC: ret = read_stsc(f); break;
557 case ATOM_STCO: ret = read_stco(f); break;
558 case ATOM_STSD: ret = read_stsd(f); break;
559 case ATOM_MDHD: ret = read_mdhd(f); break;
561 f->meta_offset = get_position(f) - header_size;
563 ret = read_meta(f, size);
566 ret = parse_sub_atoms(f, size - header_size, meta_only);
574 static int open_file(const struct mp4_callback *cb, bool meta_only, struct mp4 **result)
578 uint8_t atom_type, header_size;
579 struct mp4 *f = para_calloc(sizeof(*f));
582 while ((ret = atom_read_header(f, &atom_type, &header_size, &size)) > 0) {
583 f->last_atom = atom_type;
584 if (atom_type != ATOM_MOOV || size <= header_size) { /* skip */
585 set_position(f, get_position(f) + size - header_size);
588 f->moov_offset = get_position(f) - header_size;
590 ret = parse_sub_atoms(f, size - header_size, meta_only);
599 if (f->track.channel_count == 0)
609 int mp4_open_read(const struct mp4_callback *cb, struct mp4 **result)
611 return open_file(cb, false, result);
614 void mp4_close(struct mp4 *f)
618 free(f->track.stsz_table);
619 free(f->track.stts_sample_count);
620 free(f->track.stsc_first_chunk);
621 free(f->track.stsc_samples_per_chunk);
622 free(f->track.stco_chunk_offset);
623 for (i = 0; i < f->meta.count; i++) {
624 free(f->meta.tags[i].item);
625 free(f->meta.tags[i].value);
631 static int32_t chunk_of_sample(const struct mp4 *f, int32_t sample,
634 const struct mp4_track *t = &f->track;
635 uint32_t *fc = t->stsc_first_chunk, *spc = t->stsc_samples_per_chunk;
636 int32_t chunk1, chunk1samples, n, total, i;
638 for (i = 1, total = 0; i < t->stsc_entry_count; i++, total += n) {
639 n = (fc[i] - fc[i - 1]) * spc[i - 1]; /* number of samples */
640 if (sample < total + n)
644 chunk1samples = spc[i - 1];
645 if (chunk1samples != 0)
646 *chunk = (sample - total) / chunk1samples + chunk1;
649 return total + (*chunk - chunk1) * chunk1samples;
653 * Return the number of milliseconds of the audio track.
655 * \param f As returned by \ref mp4_open_read(), must not be NULL.
657 uint64_t mp4_get_duration(const struct mp4 *f)
659 const struct mp4_track *t = &f->track;
661 if (t->time_scale == 0)
663 return t->duration * 1000 / t->time_scale;
666 int mp4_set_sample_position(struct mp4 *f, int32_t sample)
668 const struct mp4_track *t = &f->track;
669 int32_t offset, chunk, chunk_sample;
670 uint32_t n, srs; /* sample range size */
672 if (sample >= t->stsz_sample_count)
673 return -ERRNO_TO_PARA_ERROR(EINVAL);
674 chunk_sample = chunk_of_sample(f, sample, &chunk);
675 if (t->stsz_sample_size > 0)
676 srs = (sample - chunk_sample) * t->stsz_sample_size;
678 for (srs = 0, n = chunk_sample; n < sample; n++)
679 srs += t->stsz_table[n];
681 if (t->stco_entry_count > 0 && chunk > t->stco_entry_count)
682 offset = t->stco_chunk_offset[t->stco_entry_count - 1];
683 else if (t->stco_entry_count > 0)
684 offset = t->stco_chunk_offset[chunk - 1];
687 set_position(f, offset + srs);
691 int32_t mp4_get_sample_size(const struct mp4 *f, int sample)
693 const struct mp4_track *t = &f->track;
695 if (t->stsz_sample_size != 0)
696 return t->stsz_sample_size;
697 return t->stsz_table[sample];
700 uint32_t mp4_get_sample_rate(const struct mp4 *f)
702 return f->track.sample_rate;
705 uint32_t mp4_get_channel_count(const struct mp4 *f)
707 return f->track.channel_count;
710 int32_t mp4_num_samples(const struct mp4 *f)
712 const struct mp4_track *t = &f->track;
716 for (i = 0; i < t->stts_entry_count; i++)
717 total += t->stts_sample_count[i];
721 int mp4_open_meta(const struct mp4_callback *cb, struct mp4 **result)
724 int ret = open_file(cb, true, &f);
728 if (f->udta_size == 0 || f->meta_size == 0 || f->ilst_size == 0) {
731 return -E_MP4_MISSING_ATOM;
738 * Return the metadata of an mp4 file.
740 * \param f As returned by either \ref mp4_open_read() or \ref mp4_open_meta().
742 * The caller is allowed to add, delete or modify the entries of the returned
743 * structure in order to pass the modified version to \ref mp4_meta_update().
745 struct mp4_metadata *mp4_get_meta(struct mp4 *f)
750 /** Total length of an on-disk metadata tag. */
751 #define TAG_LEN(_len) (24 + (_len))
752 static void create_ilst(const struct mp4_metadata *meta, uint8_t *out)
754 for (unsigned n = 0; n < meta->count; n++) {
755 struct mp4_tag *tag = meta->tags + n;
756 unsigned len = strlen(tag->value);
757 const char *atom_name;
759 if (!strcasecmp(tag->item, "title"))
760 atom_name = "\xA9" "nam";
761 else if (!strcasecmp(tag->item, "artist"))
762 atom_name = "\xA9" "ART";
763 else if (!strcasecmp(tag->item, "album"))
764 atom_name = "\xA9" "alb";
765 else if (!strcasecmp(tag->item, "date"))
766 atom_name = "\xA9" "day";
767 else if (!strcasecmp(tag->item, "comment"))
768 atom_name = "\xA9" "cmt";
771 write_u32_be(out, TAG_LEN(len));
772 memcpy(out + 4, atom_name, 4);
773 write_u32_be(out + 8, 8 /* data atom header */
774 + 8 /* flags + reserved */
776 memcpy(out + 12, "data", 4);
777 write_u32_be(out + 16, 1); /* flags */
778 write_u32_be(out + 20, 0); /* reserved */
779 memcpy(out + 24, tag->value, len);
784 static void *modify_moov(struct mp4 *f, uint32_t *out_size)
787 uint64_t total_base = f->moov_offset + 8;
788 uint32_t total_size = (uint32_t) (f->moov_size - 8);
789 uint32_t new_ilst_size = 0;
795 for (unsigned n = 0; n < f->meta.count; n++)
796 new_ilst_size += TAG_LEN(strlen(f->meta.tags[n].value));
797 size_delta = new_ilst_size - (f->ilst_size - 8);
798 *out_size = total_size + size_delta;
799 out_buffer = para_malloc(*out_size);
801 set_position(f, total_base);
802 ret = read_data(f, p_out, f->udta_offset - total_base);
805 p_out += f->udta_offset - total_base;
806 ret = read_int32(f, &tmp);
809 write_u32_be(p_out, tmp + size_delta);
811 ret = read_data(f, p_out, 4);
815 ret = read_data(f, p_out, f->meta_offset - f->udta_offset - 8);
818 p_out += f->meta_offset - f->udta_offset - 8;
819 ret = read_int32(f, &tmp);
822 write_u32_be(p_out, tmp + size_delta);
824 ret = read_data(f, p_out, 4);
828 ret = read_data(f, p_out, f->ilst_offset - f->meta_offset - 8);
831 p_out += f->ilst_offset - f->meta_offset - 8;
832 ret = read_int32(f, &tmp);
835 write_u32_be(p_out, tmp + size_delta);
837 ret = read_data(f, p_out, 4);
841 create_ilst(&f->meta, p_out);
842 p_out += new_ilst_size;
843 set_position(f, f->ilst_offset + f->ilst_size);
844 ret = read_data(f, p_out, total_size - (f->ilst_offset - total_base)
851 static int write_data(struct mp4 *f, void *data, size_t size)
854 ssize_t ret = f->cb->write(f->cb->user_data, data, size);
858 return -ERRNO_TO_PARA_ERROR(errno);
865 int mp4_meta_update(struct mp4 *f)
868 uint32_t new_moov_size;
869 uint8_t buf[8] = "----moov";
873 new_moov_data = modify_moov(f, &new_moov_size);
874 if (!new_moov_data ) {
878 if (f->last_atom != ATOM_MOOV) {
879 set_position(f, f->moov_offset + 4);
880 ret = write_data(f, "free", 4); /* rename old moov to free */
883 /* write new moov atom at EOF */
884 f->cb->seek(f->cb->user_data, 0, SEEK_END);
885 } else /* overwrite old moov atom */
886 set_position(f, f->moov_offset);
887 write_u32_be(buf, new_moov_size + 8);
888 ret = write_data(f, buf, sizeof(buf));
891 ret = write_data(f, new_moov_data, new_moov_size);
894 f->cb->truncate(f->cb->user_data);
901 static char *meta_find_by_name(const struct mp4 *f, const char *item)
905 for (i = 0; i < f->meta.count; i++)
906 if (!strcasecmp(f->meta.tags[i].item, item))
907 return para_strdup(f->meta.tags[i].value);
912 * Return the value of the artist meta tag of an mp4 file.
914 * \param f Must not be NULL.
916 * \return If the file does not contain this metadata tag, the function returns
917 * NULL. Otherwise, a copy of the tag value is returned. The caller should free
918 * this memory when it is no longer needed.
920 char *mp4_meta_get_artist(const struct mp4 *f)
922 return meta_find_by_name(f, "artist");
926 * Return the value of the title meta tag of an mp4 file.
928 * \param f See \ref mp4_meta_get_artist().
929 * \return See \ref mp4_meta_get_artist().
931 char *mp4_meta_get_title(const struct mp4 *f)
933 return meta_find_by_name(f, "title");
937 * Return the value of the date meta tag of an mp4 file.
939 * \param f See \ref mp4_meta_get_artist().
940 * \return See \ref mp4_meta_get_artist().
942 char *mp4_meta_get_date(const struct mp4 *f)
944 return meta_find_by_name(f, "date");
948 * Return the value of the album meta tag of an mp4 file.
950 * \param f See \ref mp4_meta_get_artist().
951 * \return See \ref mp4_meta_get_artist().
953 char *mp4_meta_get_album(const struct mp4 *f)
955 return meta_find_by_name(f, "album");
959 * Return the value of the comment meta tag of an mp4 file.
961 * \param f See \ref mp4_meta_get_artist().
962 * \return See \ref mp4_meta_get_artist().
964 char *mp4_meta_get_comment(const struct mp4 *f)
966 return meta_find_by_name(f, "comment");