]> git.tuebingen.mpg.de Git - paraslash.git/blob - mp4.c
mp4: Merge read_mp4a() into read_stsd().
[paraslash.git] / mp4.c
1 /*
2  * Copyright (C) 2003-2005 M. Bakker, Nero AG, http://www.nero.com
3  * FAAD2 - Freeware Advanced Audio (AAC) Decoder including SBR decoding
4  *
5  * See file COPYING.
6  */
7
8 #include <regex.h>
9
10 #include "para.h"
11 #include "error.h"
12 #include "portable_io.h"
13 #include "string.h"
14 #include "mp4.h"
15
16 struct mp4_track {
17         /* mp4a */
18         uint16_t channel_count;
19         uint16_t sample_rate;
20
21         /* stsz */
22         uint32_t stsz_sample_size;
23         uint32_t stsz_sample_count;
24         uint32_t *stsz_table;
25
26         /* stts */
27         uint32_t stts_entry_count;
28         uint32_t *stts_sample_count;
29
30         /* stsc */
31         uint32_t stsc_entry_count;
32         uint32_t *stsc_first_chunk;
33         uint32_t *stsc_samples_per_chunk;
34
35         /* stsc */
36         uint32_t stco_entry_count;
37         uint32_t *stco_chunk_offset;
38
39         /* mdhd */
40         uint32_t time_scale;
41         uint64_t duration;
42 };
43
44 #define MAX_TRACKS 1024
45
46 struct mp4 {
47         const struct mp4_callback *cb;
48
49         uint64_t moov_offset;
50         uint64_t moov_size;
51         uint64_t meta_offset;
52         uint32_t meta_size;
53         uint64_t ilst_offset;
54         uint32_t ilst_size;
55         uint64_t udta_offset;
56         uint32_t udta_size;
57
58         uint8_t last_atom;
59         /* incremental track index while reading the file */
60         int32_t total_tracks;
61         /* track data */
62         struct mp4_track *track[MAX_TRACKS];
63         /* the first audio track found */
64         struct mp4_track *audio_track;
65
66         /* metadata */
67         struct mp4_metadata meta;
68 };
69
70 /*
71  * Returns -1, 0, or 1 on errors/EOF/success. Partial reads followed by EOF or
72  * read errors are treated as errors.
73  */
74 static int read_data(struct mp4 *f, void *data, size_t size)
75 {
76         while (size > 0) {
77                 ssize_t ret = f->cb->read(f->cb->user_data, data, size);
78                 if (ret < 0 && errno == EINTR)
79                         continue;
80                 /* regard EAGAIN as an error as reads should be blocking. */
81                 if (ret <= 0)
82                         return ret < 0? -1 : 0;
83                 size -= ret;
84         }
85         return 1;
86 }
87
88 static int read_int64(struct mp4 *f, uint64_t *result)
89 {
90         uint8_t data[8];
91         int ret = read_data(f, data, 8);
92
93         if (ret > 0)
94                 *result = read_u64_be(data);
95         return ret;
96 }
97
98 static int read_int32(struct mp4 *f, uint32_t *result)
99 {
100         uint8_t data[4];
101         int ret = read_data(f, data, 4);
102
103         if (ret > 0)
104                 *result = read_u32_be(data);
105         return ret;
106 }
107
108 static int read_int16(struct mp4 *f, uint16_t *result)
109 {
110         uint8_t data[2];
111         int ret = read_data(f, data, 2);
112
113         if (ret > 0)
114                 *result = read_u16_be(data);
115         return ret;
116 }
117
118 #define ATOM_ITEMS \
119         ATOM_ITEM(MOOV, 'm', 'o', 'o', 'v') \
120         ATOM_ITEM(TRAK, 't', 'r', 'a', 'k') \
121         ATOM_ITEM(MDIA, 'm', 'd', 'i', 'a') \
122         ATOM_ITEM(MINF, 'm', 'i', 'n', 'f') \
123         ATOM_ITEM(STBL, 's', 't', 'b', 'l') \
124         ATOM_ITEM(UDTA, 'u', 'd', 't', 'a') \
125         ATOM_ITEM(ILST, 'i', 'l', 's', 't') /* iTunes Metadata list */ \
126         ATOM_ITEM(ARTIST, 0xa9, 'A', 'R', 'T') \
127         ATOM_ITEM(TITLE, 0xa9, 'n', 'a', 'm') \
128         ATOM_ITEM(ALBUM, 0xa9, 'a', 'l', 'b') \
129         ATOM_ITEM(DATE, 0xa9, 'd', 'a', 'y') \
130         ATOM_ITEM(COMMENT, 0xa9, 'c', 'm', 't') \
131         ATOM_ITEM(MDHD, 'm', 'd', 'h', 'd') /* track header */ \
132         ATOM_ITEM(STSD, 's', 't', 's', 'd') /* sample description box */ \
133         ATOM_ITEM(STTS, 's', 't', 't', 's') /* time to sample box */ \
134         ATOM_ITEM(STSZ, 's', 't', 's', 'z') /* sample size box */ \
135         ATOM_ITEM(STCO, 's', 't', 'c', 'o') /* chunk offset box */ \
136         ATOM_ITEM(STSC, 's', 't', 's', 'c') /* sample to chunk box */ \
137         ATOM_ITEM(MP4A, 'm', 'p', '4', 'a') \
138         ATOM_ITEM(META, 'm', 'e', 't', 'a') /* iTunes Metadata box */ \
139         ATOM_ITEM(DATA, 'd', 'a', 't', 'a') /* iTunes Metadata data box */ \
140
141 #define ATOM_ITEM(_name, a, b, c, d) ATOM_ ## _name,
142 enum atom {ATOM_ITEMS};
143 #undef ATOM_ITEM
144
145 static uint8_t atom_name_to_type(uint8_t *p)
146 {
147         #define ATOM_VALUE(a, b, c, d) ((a << 24) + (b << 16) + (c << 8) + d)
148         #define ATOM_ITEM(_name, a, b, c, d) \
149                 {.name = # _name, .val = ATOM_VALUE(a, b, c, d)},
150         static const struct {
151                 const char *name;
152                 uint32_t val;
153         } atom_table[] = {ATOM_ITEMS};
154         #undef ATOM_ITEM
155         uint32_t val = read_u32_be(p);
156
157         for (uint8_t n = 0; n < ARRAY_SIZE(atom_table); n++)
158                 if (val == atom_table[n].val)
159                         return n;
160         return 255;
161 }
162
163 /* read atom header, atom size is returned with header included. */
164 static int atom_read_header(struct mp4 *f, uint8_t *atom_type,
165                 uint8_t *header_size, uint64_t *atom_size)
166 {
167         uint32_t size;
168         int ret;
169         uint8_t atom_header[8];
170
171         ret = read_data(f, atom_header, 8);
172         if (ret <= 0)
173                 return ret;
174         size = read_u32_be(atom_header);
175         if (size == 1) { /* 64 bit atom size */
176                 if (header_size)
177                         *header_size = 16;
178                 ret = read_int64(f, atom_size);
179                 if (ret <= 0)
180                         return ret;
181         } else {
182                 if (header_size)
183                         *header_size = 8;
184                 if (atom_size)
185                         *atom_size = size;
186         }
187         *atom_type = atom_name_to_type(atom_header + 4);
188         return 1;
189 }
190
191 static off_t get_position(const struct mp4 *f)
192 {
193         return f->cb->seek(f->cb->user_data, 0, SEEK_CUR);
194 }
195
196 static void set_position(struct mp4 *f, off_t position)
197 {
198         f->cb->seek(f->cb->user_data, position, SEEK_SET);
199 }
200
201 static void skip_bytes(struct mp4 *f, off_t num_skip)
202 {
203         f->cb->seek(f->cb->user_data, num_skip, SEEK_CUR);
204 }
205
206 static int read_stsz(struct mp4 *f)
207 {
208         int ret;
209         int32_t i;
210         struct mp4_track *t;
211
212         if (f->total_tracks == 0)
213                 return -1;
214         t = f->track[f->total_tracks - 1];
215         skip_bytes(f, 4); /* version (1), flags (3) */
216         ret = read_int32(f, &t->stsz_sample_size);
217         if (ret <= 0)
218                 return ret;
219         ret = read_int32(f, &t->stsz_sample_count);
220         if (ret <= 0)
221                 return ret;
222         if (t->stsz_sample_size != 0)
223                 return 1;
224         t->stsz_table = para_malloc(t->stsz_sample_count * sizeof(int32_t));
225         for (i = 0; i < t->stsz_sample_count; i++) {
226                 ret = read_int32(f, &t->stsz_table[i]);
227                 if (ret <= 0)
228                         return ret;
229         }
230         return 1;
231 }
232
233 static int read_stts(struct mp4 *f)
234 {
235         int ret;
236         int32_t i;
237         struct mp4_track *t;
238
239         if (f->total_tracks == 0)
240                 return -1;
241         t = f->track[f->total_tracks - 1];
242         if (t->stts_entry_count)
243                 return 0;
244         skip_bytes(f, 4); /* version (1), flags (3) */
245         ret = read_int32(f, &t->stts_entry_count);
246         if (ret <= 0)
247                 return ret;
248         t->stts_sample_count = para_malloc(t->stts_entry_count
249                 * sizeof(int32_t));
250         for (i = 0; i < t->stts_entry_count; i++) {
251                 ret = read_int32(f, &t->stts_sample_count[i]);
252                 if (ret <= 0)
253                         return ret;
254                 skip_bytes(f, 4); /* sample delta */
255         }
256         return 1;
257 }
258
259 static int read_stsc(struct mp4 *f)
260 {
261         int ret;
262         int32_t i;
263         struct mp4_track *t;
264
265         if (f->total_tracks == 0)
266                 return -1;
267         t = f->track[f->total_tracks - 1];
268
269         skip_bytes(f, 4); /* version (1), flags (3) */
270         ret = read_int32(f, &t->stsc_entry_count);
271         if (ret <= 0)
272                 return ret;
273         t->stsc_first_chunk = para_malloc(t->stsc_entry_count * sizeof(int32_t));
274         t->stsc_samples_per_chunk = para_malloc(t->stsc_entry_count
275                 * sizeof (int32_t));
276         for (i = 0; i < t->stsc_entry_count; i++) {
277                 ret = read_int32(f, &t->stsc_first_chunk[i]);
278                 if (ret <= 0)
279                         return ret;
280                 ret = read_int32(f, &t->stsc_samples_per_chunk[i]);
281                 if (ret <= 0)
282                         return ret;
283                 skip_bytes(f, 4); /* sample desc index */
284         }
285         return 1;
286 }
287
288 static int read_stco(struct mp4 *f)
289 {
290         int ret;
291         int32_t i;
292         struct mp4_track *t;
293
294         if (f->total_tracks == 0)
295                 return -1;
296         t = f->track[f->total_tracks - 1];
297
298         skip_bytes(f, 4); /* version (1), flags (3) */
299         ret = read_int32(f, &t->stco_entry_count);
300         if (ret <= 0)
301                 return ret;
302         t->stco_chunk_offset = para_malloc(t->stco_entry_count
303                 * sizeof(int32_t));
304         for (i = 0; i < t->stco_entry_count; i++) {
305                 ret = read_int32(f, &t->stco_chunk_offset[i]);
306                 if (ret <= 0)
307                         return ret;
308         }
309         return 1;
310 }
311
312 static int read_stsd(struct mp4 *f)
313 {
314         int ret;
315         uint32_t i, entry_count;
316         struct mp4_track *t;
317
318         if (f->total_tracks == 0)
319                 return -1;
320         t = f->track[f->total_tracks - 1];
321         skip_bytes(f, 4); /* version (1), flags (3) */
322         ret = read_int32(f, &entry_count);
323         if (ret <= 0)
324                 return ret;
325         for (i = 0; i < entry_count; i++) {
326                 uint64_t skip = get_position(f);
327                 uint64_t size;
328                 uint8_t atom_type = 0;
329                 ret = atom_read_header(f, &atom_type, NULL, &size);
330                 if (ret <= 0)
331                         return ret;
332                 skip += size;
333                 if (!f->audio_track && atom_type == ATOM_MP4A) {
334                         f->audio_track = t;
335                         /* reserved (6), data reference index (2), reserved (8) */
336                         skip_bytes(f, 16);
337                         ret = read_int16(f, &t->channel_count);
338                         if (ret <= 0)
339                                 return ret;
340                         skip_bytes(f, 6);
341                         ret = read_int16(f, &t->sample_rate);
342                         if (ret <= 0)
343                                 return ret;
344                 }
345                 set_position(f, skip);
346         }
347         return 1;
348 }
349
350 static const char *get_metadata_name(uint8_t atom_type)
351 {
352         switch (atom_type) {
353         case ATOM_TITLE: return "title";
354         case ATOM_ARTIST: return "artist";
355         case ATOM_ALBUM: return "album";
356         case ATOM_DATE: return "date";
357         case ATOM_COMMENT: return "comment";
358         default: return "unknown";
359         }
360 }
361
362 static int parse_tag(struct mp4 *f, uint8_t parent, int32_t size)
363 {
364         int ret;
365         uint64_t subsize, sumsize;
366         char *value = NULL;
367         uint32_t len = 0;
368         uint64_t destpos;
369         struct mp4_tag *tag;
370
371         for (
372                 sumsize = 0;
373                 sumsize < size;
374                 set_position(f, destpos), sumsize += subsize
375         ) {
376                 uint8_t atom_type;
377                 uint8_t header_size = 0;
378                 ret = atom_read_header(f, &atom_type, &header_size, &subsize);
379                 if (ret <= 0)
380                         goto fail;
381                 destpos = get_position(f) + subsize - header_size;
382                 if (atom_type != ATOM_DATA)
383                         continue;
384                 skip_bytes(f, 8); /* version (1), flags (3), reserved (4) */
385                 ret = -ERRNO_TO_PARA_ERROR(EINVAL);
386                 if (subsize < header_size + 8 || subsize > UINT_MAX)
387                         goto fail;
388                 len = subsize - (header_size + 8);
389                 free(value);
390                 value = para_malloc(len + 1);
391                 ret = read_data(f, value, len);
392                 if (ret <= 0)
393                         goto fail;
394                 value[len] = '\0';
395         }
396         if (!value)
397                 return -ERRNO_TO_PARA_ERROR(EINVAL);
398         f->meta.tags = para_realloc(f->meta.tags, (f->meta.count + 1)
399                 * sizeof(struct mp4_tag));
400         tag = f->meta.tags + f->meta.count;
401         tag->item = para_strdup(get_metadata_name(parent));
402         tag->value = value;
403         tag->len = len;
404         f->meta.count++;
405         return 1;
406 fail:
407         free(value);
408         return ret;
409 }
410
411 static int read_mdhd(struct mp4 *f)
412 {
413         int ret;
414         uint32_t version;
415         struct mp4_track *t;
416
417         if (f->total_tracks == 0)
418                 return -1;
419         t = f->track[f->total_tracks - 1];
420
421         ret = read_int32(f, &version);
422         if (ret <= 0)
423                 return ret;
424         if (version == 1) {
425                 skip_bytes(f, 16); /* creation time (8), modification time (8) */
426                 ret = read_int32(f, &t->time_scale);
427                 if (ret <= 0)
428                         return ret;
429                 ret = read_int64(f, &t->duration);
430                 if (ret <= 0)
431                         return ret;
432         } else { //version == 0
433                 uint32_t temp;
434
435                 skip_bytes(f, 8); /* creation time (4), modification time (4) */
436                 ret = read_int32(f, &t->time_scale);
437                 if (ret <= 0)
438                         return ret;
439                 ret = read_int32(f, &temp);
440                 if (ret <= 0)
441                         return ret;
442                 t->duration = (temp == (uint32_t) (-1))?
443                         (uint64_t) (-1) : (uint64_t) (temp);
444         }
445         skip_bytes(f, 4);
446         return 1;
447 }
448
449 static int32_t read_ilst(struct mp4 *f, int32_t size)
450 {
451         int ret;
452         uint64_t sumsize = 0;
453
454         while (sumsize < size) {
455                 uint8_t atom_type;
456                 uint64_t subsize, destpos;
457                 uint8_t header_size = 0;
458                 ret = atom_read_header(f, &atom_type, &header_size, &subsize);
459                 if (ret <= 0)
460                         return ret;
461                 destpos = get_position(f) + subsize - header_size;
462                 switch (atom_type) {
463                 case ATOM_ARTIST:
464                 case ATOM_TITLE:
465                 case ATOM_ALBUM:
466                 case ATOM_COMMENT:
467                 case ATOM_DATE:
468                         ret = parse_tag(f, atom_type, subsize - header_size);
469                         if (ret <= 0)
470                                 return ret;
471                 }
472                 set_position(f, destpos);
473                 sumsize += subsize;
474         }
475         return 1;
476 }
477
478 static int32_t read_meta(struct mp4 *f, uint64_t size)
479 {
480         int ret;
481         uint64_t subsize, sumsize = 0;
482         uint8_t atom_type;
483         uint8_t header_size = 0;
484
485         skip_bytes(f, 4); /* version (1), flags (3) */
486         while (sumsize < (size - (header_size + 4))) {
487                 ret = atom_read_header(f, &atom_type, &header_size, &subsize);
488                 if (ret <= 0)
489                         return ret;
490                 if (subsize <= header_size + 4)
491                         return 1;
492                 if (atom_type == ATOM_ILST) {
493                         f->ilst_offset = get_position(f) - header_size;
494                         f->ilst_size = subsize;
495                         ret = read_ilst(f, subsize - (header_size + 4));
496                         if (ret <= 0)
497                                 return ret;
498                 } else
499                         set_position(f, get_position(f) + subsize - header_size);
500                 sumsize += subsize;
501         }
502         return 1;
503 }
504
505 static bool need_atom(uint8_t atom_type, bool meta_only)
506 {
507         /* these are needed in any case */
508         switch (atom_type) {
509         case ATOM_STSD:
510         case ATOM_META:
511         case ATOM_TRAK:
512         case ATOM_MDIA:
513         case ATOM_MINF:
514         case ATOM_STBL:
515         case ATOM_UDTA:
516                 return true;
517         }
518         /* meta-only opens don't need anything else */
519         if (meta_only)
520                 return false;
521         /* these are only required for regular opens */
522         switch (atom_type) {
523         case ATOM_STTS:
524         case ATOM_STSZ:
525         case ATOM_STCO:
526         case ATOM_STSC:
527         case ATOM_MDHD:
528                 return true;
529         }
530         return false;
531 }
532
533 /* parse atoms that are sub atoms of other atoms */
534 static int parse_sub_atoms(struct mp4 *f, uint64_t total_size, bool meta_only)
535 {
536         int ret;
537         uint64_t dest, size, end = get_position(f) + total_size;
538
539         for (dest = get_position(f); dest < end; set_position(f, dest)) {
540                 uint8_t header_size, atom_type;
541                 ret = atom_read_header(f, &atom_type, &header_size, &size);
542                 if (ret <= 0)
543                         return ret;
544                 if (size == 0)
545                         return -1;
546                 dest = get_position(f) + size - header_size;
547                 if (atom_type == ATOM_TRAK) {
548                         if (f->total_tracks >= MAX_TRACKS)
549                                 return -1;
550                         f->total_tracks++;
551                         f->track[f->total_tracks - 1] = para_calloc(
552                                 sizeof(struct mp4_track));
553                 } else if (atom_type == ATOM_UDTA) {
554                         f->udta_offset = get_position(f) - header_size;
555                         f->udta_size = size;
556                 }
557                 if (!need_atom(atom_type, meta_only))
558                         continue;
559                 switch (atom_type) {
560                 case ATOM_STSZ: ret = read_stsz(f); break;
561                 case ATOM_STTS: ret = read_stts(f); break;
562                 case ATOM_STSC: ret = read_stsc(f); break;
563                 case ATOM_STCO: ret = read_stco(f); break;
564                 case ATOM_STSD: ret = read_stsd(f); break;
565                 case ATOM_MDHD: ret = read_mdhd(f); break;
566                 case ATOM_META:
567                         f->meta_offset = get_position(f) - header_size;
568                         f->meta_size = size;
569                         ret = read_meta(f, size);
570                         break;
571                 default:
572                         ret = parse_sub_atoms(f, size - header_size, meta_only);
573                 }
574                 if (ret <= 0)
575                         return ret;
576         }
577         return 1;
578 }
579
580 static int open_file(const struct mp4_callback *cb, bool meta_only, struct mp4 **result)
581 {
582         int ret;
583         uint64_t size;
584         uint8_t atom_type, header_size;
585         struct mp4 *f = para_calloc(sizeof(*f));
586
587         f->cb = cb;
588         while ((ret = atom_read_header(f, &atom_type, &header_size, &size)) > 0) {
589                 f->last_atom = atom_type;
590                 if (atom_type != ATOM_MOOV || size <= header_size) { /* skip */
591                         set_position(f, get_position(f) + size - header_size);
592                         continue;
593                 }
594                 f->moov_offset = get_position(f) - header_size;
595                 f->moov_size = size;
596                 ret = parse_sub_atoms(f, size - header_size, meta_only);
597                 if (ret <= 0)
598                         break;
599         }
600         if (ret < 0) {
601                 ret = -E_MP4_OPEN;
602                 goto fail;
603         }
604         ret = -E_MP4_TRACK;
605         if (!f->audio_track)
606                 goto fail;
607         *result = f;
608         return 1;
609 fail:
610         *result = NULL;
611         free(f);
612         return ret;
613 }
614
615 int mp4_open_read(const struct mp4_callback *cb, struct mp4 **result)
616 {
617         return open_file(cb, false, result);
618 }
619
620 void mp4_close(struct mp4 *f)
621 {
622         int32_t i;
623
624         for (i = 0; i < f->total_tracks; i++) {
625                 if (f->track[i]) {
626                         free(f->track[i]->stsz_table);
627                         free(f->track[i]->stts_sample_count);
628                         free(f->track[i]->stsc_first_chunk);
629                         free(f->track[i]->stsc_samples_per_chunk);
630                         free(f->track[i]->stco_chunk_offset);
631                         free(f->track[i]);
632                 }
633         }
634         for (i = 0; i < f->meta.count; i++) {
635                 free(f->meta.tags[i].item);
636                 free(f->meta.tags[i].value);
637         }
638         free(f->meta.tags);
639         free(f);
640 }
641
642 static int32_t chunk_of_sample(const struct mp4 *f, int32_t sample,
643                 int32_t *chunk)
644 {
645         const struct mp4_track *t = f->audio_track;
646         uint32_t *fc = t->stsc_first_chunk, *spc = t->stsc_samples_per_chunk;
647         int32_t chunk1, chunk1samples, n, total, i;
648
649         for (i = 1, total = 0; i < t->stsc_entry_count; i++, total += n) {
650                 n = (fc[i] - fc[i - 1]) * spc[i - 1]; /* number of samples */
651                 if (sample < total + n)
652                         break;
653         }
654         chunk1 = fc[i - 1];
655         chunk1samples = spc[i - 1];
656         if (chunk1samples != 0)
657                 *chunk = (sample - total) / chunk1samples + chunk1;
658         else
659                 *chunk = 1;
660         return total + (*chunk - chunk1) * chunk1samples;
661 }
662
663 /**
664  * Return the number of milliseconds of the audio track.
665  *
666  * \param f As returned by \ref mp4_open_read(), must not be NULL.
667  */
668 uint64_t mp4_get_duration(const struct mp4 *f)
669 {
670         const struct mp4_track *t = f->audio_track;
671
672         if (t->time_scale == 0)
673                 return 0;
674         return t->duration * 1000 / t->time_scale;
675 }
676
677 int mp4_set_sample_position(struct mp4 *f, int32_t sample)
678 {
679         const struct mp4_track *t = f->audio_track;
680         int32_t offset, chunk, chunk_sample;
681         uint32_t n, srs; /* sample range size */
682
683         if (sample >= t->stsz_sample_count)
684                 return -ERRNO_TO_PARA_ERROR(EINVAL);
685         chunk_sample = chunk_of_sample(f, sample, &chunk);
686         if (t->stsz_sample_size > 0)
687                 srs = (sample - chunk_sample) * t->stsz_sample_size;
688         else {
689                 for (srs = 0, n = chunk_sample; n < sample; n++)
690                         srs += t->stsz_table[n];
691         }
692         if (t->stco_entry_count > 0 && chunk > t->stco_entry_count)
693                 offset = t->stco_chunk_offset[t->stco_entry_count - 1];
694         else if (t->stco_entry_count > 0)
695                 offset = t->stco_chunk_offset[chunk - 1];
696         else
697                 offset = 8;
698         set_position(f, offset + srs);
699         return 1;
700 }
701
702 int32_t mp4_get_sample_size(const struct mp4 *f, int sample)
703 {
704         const struct mp4_track *t = f->audio_track;
705
706         if (t->stsz_sample_size != 0)
707                 return t->stsz_sample_size;
708         return t->stsz_table[sample];
709 }
710
711 uint32_t mp4_get_sample_rate(const struct mp4 *f)
712 {
713         return f->audio_track->sample_rate;
714 }
715
716 uint32_t mp4_get_channel_count(const struct mp4 *f)
717 {
718         return f->audio_track->channel_count;
719 }
720
721 int32_t mp4_num_samples(const struct mp4 *f)
722 {
723         const struct mp4_track *t = f->audio_track;
724         int32_t i;
725         int32_t total = 0;
726
727         for (i = 0; i < t->stts_entry_count; i++)
728                 total += t->stts_sample_count[i];
729         return total;
730 }
731
732 int mp4_open_meta(const struct mp4_callback *cb, struct mp4 **result)
733 {
734         struct mp4 *f;
735         int ret = open_file(cb, true, &f);
736
737         if (ret < 0)
738                 return ret;
739         if (f->udta_size == 0 || f->meta_size == 0 || f->ilst_size == 0) {
740                 mp4_close(f);
741                 *result = NULL;
742                 return -E_MP4_MISSING_ATOM;
743         }
744         *result = f;
745         return 1;
746 }
747
748 /**
749  * Return the metadata of an mp4 file.
750  *
751  * \param f As returned by either \ref mp4_open_read() or \ref mp4_open_meta().
752  *
753  * The caller is allowed to add, delete or modify the entries of the returned
754  * structure in order to pass the modified version to \ref mp4_meta_update().
755  */
756 struct mp4_metadata *mp4_get_meta(struct mp4 *f)
757 {
758         return &f->meta;
759 }
760
761 /** Total length of an on-disk metadata tag. */
762 #define TAG_LEN(_len) (24 + (_len))
763 static void create_ilst(const struct mp4_metadata *meta, uint8_t *out)
764 {
765         for (unsigned n = 0; n < meta->count; n++) {
766                 struct mp4_tag *tag = meta->tags + n;
767                 unsigned len = strlen(tag->value);
768                 const char *atom_name;
769
770                 if (!strcasecmp(tag->item, "title"))
771                         atom_name = "\xA9" "nam";
772                 else if (!strcasecmp(tag->item, "artist"))
773                         atom_name = "\xA9" "ART";
774                 else if (!strcasecmp(tag->item, "album"))
775                         atom_name = "\xA9" "alb";
776                 else if (!strcasecmp(tag->item, "date"))
777                         atom_name = "\xA9" "day";
778                 else if (!strcasecmp(tag->item, "comment"))
779                         atom_name = "\xA9" "cmt";
780                 else
781                         assert(false);
782                 write_u32_be(out, TAG_LEN(len));
783                 memcpy(out + 4, atom_name, 4);
784                 write_u32_be(out + 8, 8 /* data atom header */
785                         + 8 /* flags + reserved */
786                         + len);
787                 memcpy(out + 12, "data", 4);
788                 write_u32_be(out + 16, 1); /* flags */
789                 write_u32_be(out + 20, 0); /* reserved */
790                 memcpy(out + 24, tag->value, len);
791                 out += TAG_LEN(len);
792         }
793 }
794
795 static void *modify_moov(struct mp4 *f, uint32_t *out_size)
796 {
797         int ret;
798         uint64_t total_base = f->moov_offset + 8;
799         uint32_t total_size = (uint32_t) (f->moov_size - 8);
800         uint32_t new_ilst_size = 0;
801         void *out_buffer;
802         uint8_t *p_out;
803         int32_t size_delta;
804         uint32_t tmp;
805
806         for (unsigned n = 0; n < f->meta.count; n++)
807                 new_ilst_size += TAG_LEN(strlen(f->meta.tags[n].value));
808         size_delta = new_ilst_size - (f->ilst_size - 8);
809         *out_size = total_size + size_delta;
810         out_buffer = para_malloc(*out_size);
811         p_out = out_buffer;
812         set_position(f, total_base);
813         ret = read_data(f, p_out, f->udta_offset - total_base);
814         if (ret <= 0)
815                 return NULL;
816         p_out += f->udta_offset - total_base;
817         ret = read_int32(f, &tmp);
818         if (ret <= 0)
819                 return NULL;
820         write_u32_be(p_out, tmp + size_delta);
821         p_out += 4;
822         ret = read_data(f, p_out, 4);
823         if (ret <= 0)
824                 return NULL;
825         p_out += 4;
826         ret = read_data(f, p_out, f->meta_offset - f->udta_offset - 8);
827         if (ret <= 0)
828                 return NULL;
829         p_out += f->meta_offset - f->udta_offset - 8;
830         ret = read_int32(f, &tmp);
831         if (ret <= 0)
832                 return NULL;
833         write_u32_be(p_out, tmp + size_delta);
834         p_out += 4;
835         ret = read_data(f, p_out, 4);
836         if (ret <= 0)
837                 return NULL;
838         p_out += 4;
839         ret = read_data(f, p_out, f->ilst_offset - f->meta_offset - 8);
840         if (ret <= 0)
841                 return NULL;
842         p_out += f->ilst_offset - f->meta_offset - 8;
843         ret = read_int32(f, &tmp);
844         if (ret <= 0)
845                 return NULL;
846         write_u32_be(p_out, tmp + size_delta);
847         p_out += 4;
848         ret = read_data(f, p_out, 4);
849         if (ret <= 0)
850                 return NULL;
851         p_out += 4;
852         create_ilst(&f->meta, p_out);
853         p_out += new_ilst_size;
854         set_position(f, f->ilst_offset + f->ilst_size);
855         ret = read_data(f, p_out, total_size - (f->ilst_offset - total_base)
856                 - f->ilst_size);
857         if (ret <= 0)
858                 return NULL;
859         return out_buffer;
860 }
861
862 static int write_data(struct mp4 *f, void *data, size_t size)
863 {
864         while (size > 0) {
865                 ssize_t ret = f->cb->write(f->cb->user_data, data, size);
866                 if (ret < 0) {
867                         if (errno == EINTR)
868                                 continue;
869                         return -ERRNO_TO_PARA_ERROR(errno);
870                 }
871                 size -= ret;
872         }
873         return 1;
874 }
875
876 int mp4_meta_update(struct mp4 *f)
877 {
878         void *new_moov_data;
879         uint32_t new_moov_size;
880         uint8_t buf[8] = "----moov";
881         int ret;
882
883         set_position(f, 0);
884         new_moov_data = modify_moov(f, &new_moov_size);
885         if (!new_moov_data ) {
886                 mp4_close(f);
887                 return 0;
888         }
889         if (f->last_atom != ATOM_MOOV) {
890                 set_position(f, f->moov_offset + 4);
891                 ret = write_data(f, "free", 4); /* rename old moov to free */
892                 if (ret < 0)
893                         goto free_moov;
894                 /* write new moov atom at EOF */
895                 f->cb->seek(f->cb->user_data, 0, SEEK_END);
896         } else /* overwrite old moov atom */
897                 set_position(f, f->moov_offset);
898         write_u32_be(buf, new_moov_size + 8);
899         ret = write_data(f, buf, sizeof(buf));
900         if (ret < 0)
901                 goto free_moov;
902         ret = write_data(f, new_moov_data, new_moov_size);
903         if (ret < 0)
904                 goto free_moov;
905         f->cb->truncate(f->cb->user_data);
906         ret = 1;
907 free_moov:
908         free(new_moov_data);
909         return ret;
910 }
911
912 static char *meta_find_by_name(const struct mp4 *f, const char *item)
913 {
914         uint32_t i;
915
916         for (i = 0; i < f->meta.count; i++)
917                 if (!strcasecmp(f->meta.tags[i].item, item))
918                         return para_strdup(f->meta.tags[i].value);
919         return NULL;
920 }
921
922 /**
923  * Return the value of the artist meta tag of an mp4 file.
924  *
925  * \param f Must not be NULL.
926  *
927  * \return If the file does not contain this metadata tag, the function returns
928  * NULL. Otherwise, a copy of the tag value is returned. The caller should free
929  * this memory when it is no longer needed.
930  */
931 char *mp4_meta_get_artist(const struct mp4 *f)
932 {
933         return meta_find_by_name(f, "artist");
934 }
935
936 /**
937  * Return the value of the title meta tag of an mp4 file.
938  *
939  * \param f See \ref mp4_meta_get_artist().
940  * \return See \ref mp4_meta_get_artist().
941  */
942 char *mp4_meta_get_title(const struct mp4 *f)
943 {
944         return meta_find_by_name(f, "title");
945 }
946
947 /**
948  * Return the value of the date meta tag of an mp4 file.
949  *
950  * \param f See \ref mp4_meta_get_artist().
951  * \return See \ref mp4_meta_get_artist().
952  */
953 char *mp4_meta_get_date(const struct mp4 *f)
954 {
955         return meta_find_by_name(f, "date");
956 }
957
958 /**
959  * Return the value of the album meta tag of an mp4 file.
960  *
961  * \param f See \ref mp4_meta_get_artist().
962  * \return See \ref mp4_meta_get_artist().
963  */
964 char *mp4_meta_get_album(const struct mp4 *f)
965 {
966         return meta_find_by_name(f, "album");
967 }
968
969 /**
970  * Return the value of the comment meta tag of an mp4 file.
971  *
972  * \param f See \ref mp4_meta_get_artist().
973  * \return See \ref mp4_meta_get_artist().
974  */
975 char *mp4_meta_get_comment(const struct mp4 *f)
976 {
977         return meta_find_by_name(f, "comment");
978 }