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