]> git.tuebingen.mpg.de Git - paraslash.git/blob - mp4.c
mp4: Provide proper error codes for all errors.
[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         int32_t i;
216         struct mp4_track *t = &f->track;
217
218         if (t->state != ATS_SEEN_MP4A || t->stsz_table)
219                 return 1;
220         skip_bytes(f, 4); /* version (1), flags (3) */
221         ret = read_int32(f, &t->stsz_sample_size);
222         if (ret <= 0)
223                 return ret;
224         ret = read_int32(f, &t->stsz_sample_count);
225         if (ret <= 0)
226                 return ret;
227         if (t->stsz_sample_size != 0)
228                 return 1;
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]);
232                 if (ret <= 0)
233                         return ret;
234         }
235         return 1;
236 }
237
238 static int read_stts(struct mp4 *f)
239 {
240         int ret;
241         int32_t i;
242         struct mp4_track *t = &f->track;
243
244         if (t->state != ATS_SEEN_MP4A || t->stts_sample_count)
245                 return 1;
246         skip_bytes(f, 4); /* version (1), flags (3) */
247         ret = read_int32(f, &t->stts_entry_count);
248         if (ret <= 0)
249                 return ret;
250         t->stts_sample_count = para_malloc(t->stts_entry_count
251                 * sizeof(int32_t));
252         for (i = 0; i < t->stts_entry_count; i++) {
253                 ret = read_int32(f, &t->stts_sample_count[i]);
254                 if (ret <= 0)
255                         return ret;
256                 skip_bytes(f, 4); /* sample delta */
257         }
258         return 1;
259 }
260
261 static int read_stsc(struct mp4 *f)
262 {
263         int ret;
264         int32_t i;
265         struct mp4_track *t = &f->track;
266
267         if (t->state != ATS_SEEN_MP4A)
268                 return 1;
269         if (t->stsc_first_chunk || t->stsc_samples_per_chunk)
270                 return 1;
271         skip_bytes(f, 4); /* version (1), flags (3) */
272         ret = read_int32(f, &t->stsc_entry_count);
273         if (ret <= 0)
274                 return ret;
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
277                 * sizeof (int32_t));
278         for (i = 0; i < t->stsc_entry_count; i++) {
279                 ret = read_int32(f, &t->stsc_first_chunk[i]);
280                 if (ret <= 0)
281                         return ret;
282                 ret = read_int32(f, &t->stsc_samples_per_chunk[i]);
283                 if (ret <= 0)
284                         return ret;
285                 skip_bytes(f, 4); /* sample desc index */
286         }
287         return 1;
288 }
289
290 static int read_stco(struct mp4 *f)
291 {
292         int ret;
293         int32_t i;
294         struct mp4_track *t = &f->track;
295
296         if (t->state != ATS_SEEN_MP4A || t->stco_chunk_offset)
297                 return 1;
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
317         if (f->track.state != ATS_INITIAL)
318                 return 1;
319         skip_bytes(f, 4); /* version (1), flags (3) */
320         ret = read_int32(f, &entry_count);
321         if (ret <= 0)
322                 return ret;
323         for (i = 0; i < entry_count; i++) {
324                 uint64_t skip = get_position(f);
325                 uint64_t size;
326                 uint8_t atom_type = 0;
327                 ret = atom_read_header(f, &atom_type, NULL, &size);
328                 if (ret <= 0)
329                         return ret;
330                 skip += size;
331                 if (atom_type == ATOM_MP4A) {
332                         f->track.state = ATS_SEEN_MP4A;
333                         /* reserved (6), data reference index (2), reserved (8) */
334                         skip_bytes(f, 16);
335                         ret = read_int16(f, &f->track.channel_count);
336                         if (ret <= 0)
337                                 return ret;
338                         skip_bytes(f, 6);
339                         ret = read_int16(f, &f->track.sample_rate);
340                         if (ret <= 0)
341                                 return ret;
342                 }
343                 set_position(f, skip);
344         }
345         return 1;
346 }
347
348 static const char *get_metadata_name(uint8_t atom_type)
349 {
350         switch (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";
357         }
358 }
359
360 static int parse_tag(struct mp4 *f, uint8_t parent, int32_t size)
361 {
362         int ret;
363         uint64_t subsize, sumsize;
364         char *value = NULL;
365         uint32_t len = 0;
366         uint64_t destpos;
367         struct mp4_tag *tag;
368
369         for (
370                 sumsize = 0;
371                 sumsize < size;
372                 set_position(f, destpos), sumsize += subsize
373         ) {
374                 uint8_t atom_type;
375                 uint8_t header_size = 0;
376                 ret = atom_read_header(f, &atom_type, &header_size, &subsize);
377                 if (ret <= 0)
378                         goto fail;
379                 destpos = get_position(f) + subsize - header_size;
380                 if (atom_type != ATOM_DATA)
381                         continue;
382                 skip_bytes(f, 8); /* version (1), flags (3), reserved (4) */
383                 ret = -E_MP4_CORRUPT;
384                 if (subsize < header_size + 8 || subsize > UINT_MAX)
385                         goto fail;
386                 len = subsize - (header_size + 8);
387                 free(value);
388                 value = para_malloc(len + 1);
389                 ret = read_data(f, value, len);
390                 if (ret <= 0)
391                         goto fail;
392                 value[len] = '\0';
393         }
394         if (!value)
395                 return -E_MP4_CORRUPT;
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));
400         tag->value = value;
401         tag->len = len;
402         f->meta.count++;
403         return 1;
404 fail:
405         free(value);
406         return ret;
407 }
408
409 static int read_mdhd(struct mp4 *f)
410 {
411         int ret;
412         uint32_t version;
413         struct mp4_track *t = &f->track;
414
415         if (t->state != ATS_INITIAL)
416                 return 1;
417         ret = read_int32(f, &version);
418         if (ret <= 0)
419                 return ret;
420         if (version == 1) {
421                 skip_bytes(f, 16); /* creation time (8), modification time (8) */
422                 ret = read_int32(f, &t->time_scale);
423                 if (ret <= 0)
424                         return ret;
425                 ret = read_int64(f, &t->duration);
426                 if (ret <= 0)
427                         return ret;
428         } else { //version == 0
429                 uint32_t temp;
430
431                 skip_bytes(f, 8); /* creation time (4), modification time (4) */
432                 ret = read_int32(f, &t->time_scale);
433                 if (ret <= 0)
434                         return ret;
435                 ret = read_int32(f, &temp);
436                 if (ret <= 0)
437                         return ret;
438                 t->duration = (temp == (uint32_t) (-1))?
439                         (uint64_t) (-1) : (uint64_t) (temp);
440         }
441         skip_bytes(f, 4);
442         return 1;
443 }
444
445 static int32_t read_ilst(struct mp4 *f, int32_t size)
446 {
447         int ret;
448         uint64_t sumsize = 0;
449
450         while (sumsize < size) {
451                 uint8_t atom_type;
452                 uint64_t subsize, destpos;
453                 uint8_t header_size = 0;
454                 ret = atom_read_header(f, &atom_type, &header_size, &subsize);
455                 if (ret <= 0)
456                         return ret;
457                 destpos = get_position(f) + subsize - header_size;
458                 switch (atom_type) {
459                 case ATOM_ARTIST:
460                 case ATOM_TITLE:
461                 case ATOM_ALBUM:
462                 case ATOM_COMMENT:
463                 case ATOM_DATE:
464                         ret = parse_tag(f, atom_type, subsize - header_size);
465                         if (ret <= 0)
466                                 return ret;
467                 }
468                 set_position(f, destpos);
469                 sumsize += subsize;
470         }
471         return 1;
472 }
473
474 static int32_t read_meta(struct mp4 *f, uint64_t size)
475 {
476         int ret;
477         uint64_t subsize, sumsize = 0;
478         uint8_t atom_type;
479         uint8_t header_size = 0;
480
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);
484                 if (ret <= 0)
485                         return ret;
486                 if (subsize <= header_size + 4)
487                         return 1;
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));
492                         if (ret <= 0)
493                                 return ret;
494                 } else
495                         set_position(f, get_position(f) + subsize - header_size);
496                 sumsize += subsize;
497         }
498         return 1;
499 }
500
501 static bool need_atom(uint8_t atom_type, bool meta_only)
502 {
503         /* these are needed in any case */
504         switch (atom_type) {
505         case ATOM_STSD:
506         case ATOM_META:
507         case ATOM_TRAK:
508         case ATOM_MDIA:
509         case ATOM_MINF:
510         case ATOM_STBL:
511         case ATOM_UDTA:
512                 return true;
513         }
514         /* meta-only opens don't need anything else */
515         if (meta_only)
516                 return false;
517         /* these are only required for regular opens */
518         switch (atom_type) {
519         case ATOM_STTS:
520         case ATOM_STSZ:
521         case ATOM_STCO:
522         case ATOM_STSC:
523         case ATOM_MDHD:
524                 return true;
525         }
526         return false;
527 }
528
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)
531 {
532         int ret;
533         uint64_t dest, size, end = get_position(f) + total_size;
534
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);
538                 if (ret <= 0)
539                         return ret;
540                 if (size == 0)
541                         return -E_MP4_CORRUPT;
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;
545                         continue;
546                 }
547                 if (atom_type == ATOM_UDTA) {
548                         f->udta_offset = get_position(f) - header_size;
549                         f->udta_size = size;
550                 }
551                 if (!need_atom(atom_type, meta_only))
552                         continue;
553                 switch (atom_type) {
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;
560                 case ATOM_META:
561                         f->meta_offset = get_position(f) - header_size;
562                         f->meta_size = size;
563                         ret = read_meta(f, size);
564                         break;
565                 default:
566                         ret = parse_sub_atoms(f, size - header_size, meta_only);
567                 }
568                 if (ret <= 0)
569                         return ret;
570         }
571         return 1;
572 }
573
574 static int open_file(const struct mp4_callback *cb, bool meta_only, struct mp4 **result)
575 {
576         int ret;
577         uint64_t size;
578         uint8_t atom_type, header_size;
579         struct mp4 *f = para_calloc(sizeof(*f));
580
581         f->cb = cb;
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);
586                         continue;
587                 }
588                 f->moov_offset = get_position(f) - header_size;
589                 f->moov_size = size;
590                 ret = parse_sub_atoms(f, size - header_size, meta_only);
591                 if (ret <= 0)
592                         break;
593         }
594         if (ret < 0)
595                 goto fail;
596         ret = -E_MP4_TRACK;
597         if (f->track.channel_count == 0)
598                 goto fail;
599         *result = f;
600         return 1;
601 fail:
602         *result = NULL;
603         free(f);
604         return ret;
605 }
606
607 int mp4_open_read(const struct mp4_callback *cb, struct mp4 **result)
608 {
609         return open_file(cb, false, result);
610 }
611
612 void mp4_close(struct mp4 *f)
613 {
614         int32_t i;
615
616         free(f->track.stsz_table);
617         free(f->track.stts_sample_count);
618         free(f->track.stsc_first_chunk);
619         free(f->track.stsc_samples_per_chunk);
620         free(f->track.stco_chunk_offset);
621         for (i = 0; i < f->meta.count; i++) {
622                 free(f->meta.tags[i].item);
623                 free(f->meta.tags[i].value);
624         }
625         free(f->meta.tags);
626         free(f);
627 }
628
629 static int32_t chunk_of_sample(const struct mp4 *f, int32_t sample,
630                 int32_t *chunk)
631 {
632         const struct mp4_track *t = &f->track;
633         uint32_t *fc = t->stsc_first_chunk, *spc = t->stsc_samples_per_chunk;
634         int32_t chunk1, chunk1samples, n, total, i;
635
636         for (i = 1, total = 0; i < t->stsc_entry_count; i++, total += n) {
637                 n = (fc[i] - fc[i - 1]) * spc[i - 1]; /* number of samples */
638                 if (sample < total + n)
639                         break;
640         }
641         chunk1 = fc[i - 1];
642         chunk1samples = spc[i - 1];
643         if (chunk1samples != 0)
644                 *chunk = (sample - total) / chunk1samples + chunk1;
645         else
646                 *chunk = 1;
647         return total + (*chunk - chunk1) * chunk1samples;
648 }
649
650 /**
651  * Return the number of milliseconds of the audio track.
652  *
653  * \param f As returned by \ref mp4_open_read(), must not be NULL.
654  */
655 uint64_t mp4_get_duration(const struct mp4 *f)
656 {
657         const struct mp4_track *t = &f->track;
658
659         if (t->time_scale == 0)
660                 return 0;
661         return t->duration * 1000 / t->time_scale;
662 }
663
664 int mp4_set_sample_position(struct mp4 *f, int32_t sample)
665 {
666         const struct mp4_track *t = &f->track;
667         int32_t offset, chunk, chunk_sample;
668         uint32_t n, srs; /* sample range size */
669
670         if (sample >= t->stsz_sample_count)
671                 return -ERRNO_TO_PARA_ERROR(EINVAL);
672         chunk_sample = chunk_of_sample(f, sample, &chunk);
673         if (t->stsz_sample_size > 0)
674                 srs = (sample - chunk_sample) * t->stsz_sample_size;
675         else {
676                 for (srs = 0, n = chunk_sample; n < sample; n++)
677                         srs += t->stsz_table[n];
678         }
679         if (t->stco_entry_count > 0 && chunk > t->stco_entry_count)
680                 offset = t->stco_chunk_offset[t->stco_entry_count - 1];
681         else if (t->stco_entry_count > 0)
682                 offset = t->stco_chunk_offset[chunk - 1];
683         else
684                 offset = 8;
685         set_position(f, offset + srs);
686         return 1;
687 }
688
689 int32_t mp4_get_sample_size(const struct mp4 *f, int sample)
690 {
691         const struct mp4_track *t = &f->track;
692
693         if (t->stsz_sample_size != 0)
694                 return t->stsz_sample_size;
695         return t->stsz_table[sample];
696 }
697
698 uint32_t mp4_get_sample_rate(const struct mp4 *f)
699 {
700         return f->track.sample_rate;
701 }
702
703 uint32_t mp4_get_channel_count(const struct mp4 *f)
704 {
705         return f->track.channel_count;
706 }
707
708 int32_t mp4_num_samples(const struct mp4 *f)
709 {
710         const struct mp4_track *t = &f->track;
711         int32_t i;
712         int32_t total = 0;
713
714         for (i = 0; i < t->stts_entry_count; i++)
715                 total += t->stts_sample_count[i];
716         return total;
717 }
718
719 int mp4_open_meta(const struct mp4_callback *cb, struct mp4 **result)
720 {
721         struct mp4 *f;
722         int ret = open_file(cb, true, &f);
723
724         if (ret < 0)
725                 return ret;
726         if (f->udta_size == 0 || f->meta_size == 0 || f->ilst_size == 0) {
727                 mp4_close(f);
728                 *result = NULL;
729                 return -E_MP4_MISSING_ATOM;
730         }
731         *result = f;
732         return 1;
733 }
734
735 /**
736  * Return the metadata of an mp4 file.
737  *
738  * \param f As returned by either \ref mp4_open_read() or \ref mp4_open_meta().
739  *
740  * The caller is allowed to add, delete or modify the entries of the returned
741  * structure in order to pass the modified version to \ref mp4_meta_update().
742  */
743 struct mp4_metadata *mp4_get_meta(struct mp4 *f)
744 {
745         return &f->meta;
746 }
747
748 /** Total length of an on-disk metadata tag. */
749 #define TAG_LEN(_len) (24 + (_len))
750 static void create_ilst(const struct mp4_metadata *meta, uint8_t *out)
751 {
752         for (unsigned n = 0; n < meta->count; n++) {
753                 struct mp4_tag *tag = meta->tags + n;
754                 unsigned len = strlen(tag->value);
755                 const char *atom_name;
756
757                 if (!strcasecmp(tag->item, "title"))
758                         atom_name = "\xA9" "nam";
759                 else if (!strcasecmp(tag->item, "artist"))
760                         atom_name = "\xA9" "ART";
761                 else if (!strcasecmp(tag->item, "album"))
762                         atom_name = "\xA9" "alb";
763                 else if (!strcasecmp(tag->item, "date"))
764                         atom_name = "\xA9" "day";
765                 else if (!strcasecmp(tag->item, "comment"))
766                         atom_name = "\xA9" "cmt";
767                 else
768                         assert(false);
769                 write_u32_be(out, TAG_LEN(len));
770                 memcpy(out + 4, atom_name, 4);
771                 write_u32_be(out + 8, 8 /* data atom header */
772                         + 8 /* flags + reserved */
773                         + len);
774                 memcpy(out + 12, "data", 4);
775                 write_u32_be(out + 16, 1); /* flags */
776                 write_u32_be(out + 20, 0); /* reserved */
777                 memcpy(out + 24, tag->value, len);
778                 out += TAG_LEN(len);
779         }
780 }
781
782 static void *modify_moov(struct mp4 *f, uint32_t *out_size)
783 {
784         int ret;
785         uint64_t total_base = f->moov_offset + 8;
786         uint32_t total_size = (uint32_t) (f->moov_size - 8);
787         uint32_t new_ilst_size = 0;
788         void *out_buffer;
789         uint8_t *p_out;
790         int32_t size_delta;
791         uint32_t tmp;
792
793         for (unsigned n = 0; n < f->meta.count; n++)
794                 new_ilst_size += TAG_LEN(strlen(f->meta.tags[n].value));
795         size_delta = new_ilst_size - (f->ilst_size - 8);
796         *out_size = total_size + size_delta;
797         out_buffer = para_malloc(*out_size);
798         p_out = out_buffer;
799         set_position(f, total_base);
800         ret = read_data(f, p_out, f->udta_offset - total_base);
801         if (ret <= 0)
802                 return NULL;
803         p_out += f->udta_offset - total_base;
804         ret = read_int32(f, &tmp);
805         if (ret <= 0)
806                 return NULL;
807         write_u32_be(p_out, tmp + size_delta);
808         p_out += 4;
809         ret = read_data(f, p_out, 4);
810         if (ret <= 0)
811                 return NULL;
812         p_out += 4;
813         ret = read_data(f, p_out, f->meta_offset - f->udta_offset - 8);
814         if (ret <= 0)
815                 return NULL;
816         p_out += f->meta_offset - f->udta_offset - 8;
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->ilst_offset - f->meta_offset - 8);
827         if (ret <= 0)
828                 return NULL;
829         p_out += f->ilst_offset - f->meta_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         create_ilst(&f->meta, p_out);
840         p_out += new_ilst_size;
841         set_position(f, f->ilst_offset + f->ilst_size);
842         ret = read_data(f, p_out, total_size - (f->ilst_offset - total_base)
843                 - f->ilst_size);
844         if (ret <= 0)
845                 return NULL;
846         return out_buffer;
847 }
848
849 static int write_data(struct mp4 *f, void *data, size_t size)
850 {
851         while (size > 0) {
852                 ssize_t ret = f->cb->write(f->cb->user_data, data, size);
853                 if (ret < 0) {
854                         if (errno == EINTR)
855                                 continue;
856                         return -ERRNO_TO_PARA_ERROR(errno);
857                 }
858                 size -= ret;
859         }
860         return 1;
861 }
862
863 int mp4_meta_update(struct mp4 *f)
864 {
865         void *new_moov_data;
866         uint32_t new_moov_size;
867         uint8_t buf[8] = "----moov";
868         int ret;
869
870         set_position(f, 0);
871         new_moov_data = modify_moov(f, &new_moov_size);
872         if (!new_moov_data ) {
873                 mp4_close(f);
874                 return 0;
875         }
876         if (f->last_atom != ATOM_MOOV) {
877                 set_position(f, f->moov_offset + 4);
878                 ret = write_data(f, "free", 4); /* rename old moov to free */
879                 if (ret < 0)
880                         goto free_moov;
881                 /* write new moov atom at EOF */
882                 f->cb->seek(f->cb->user_data, 0, SEEK_END);
883         } else /* overwrite old moov atom */
884                 set_position(f, f->moov_offset);
885         write_u32_be(buf, new_moov_size + 8);
886         ret = write_data(f, buf, sizeof(buf));
887         if (ret < 0)
888                 goto free_moov;
889         ret = write_data(f, new_moov_data, new_moov_size);
890         if (ret < 0)
891                 goto free_moov;
892         f->cb->truncate(f->cb->user_data);
893         ret = 1;
894 free_moov:
895         free(new_moov_data);
896         return ret;
897 }
898
899 static char *meta_find_by_name(const struct mp4 *f, const char *item)
900 {
901         uint32_t i;
902
903         for (i = 0; i < f->meta.count; i++)
904                 if (!strcasecmp(f->meta.tags[i].item, item))
905                         return para_strdup(f->meta.tags[i].value);
906         return NULL;
907 }
908
909 /**
910  * Return the value of the artist meta tag of an mp4 file.
911  *
912  * \param f Must not be NULL.
913  *
914  * \return If the file does not contain this metadata tag, the function returns
915  * NULL. Otherwise, a copy of the tag value is returned. The caller should free
916  * this memory when it is no longer needed.
917  */
918 char *mp4_meta_get_artist(const struct mp4 *f)
919 {
920         return meta_find_by_name(f, "artist");
921 }
922
923 /**
924  * Return the value of the title meta tag of an mp4 file.
925  *
926  * \param f See \ref mp4_meta_get_artist().
927  * \return See \ref mp4_meta_get_artist().
928  */
929 char *mp4_meta_get_title(const struct mp4 *f)
930 {
931         return meta_find_by_name(f, "title");
932 }
933
934 /**
935  * Return the value of the date meta tag of an mp4 file.
936  *
937  * \param f See \ref mp4_meta_get_artist().
938  * \return See \ref mp4_meta_get_artist().
939  */
940 char *mp4_meta_get_date(const struct mp4 *f)
941 {
942         return meta_find_by_name(f, "date");
943 }
944
945 /**
946  * Return the value of the album meta tag of an mp4 file.
947  *
948  * \param f See \ref mp4_meta_get_artist().
949  * \return See \ref mp4_meta_get_artist().
950  */
951 char *mp4_meta_get_album(const struct mp4 *f)
952 {
953         return meta_find_by_name(f, "album");
954 }
955
956 /**
957  * Return the value of the comment meta tag of an mp4 file.
958  *
959  * \param f See \ref mp4_meta_get_artist().
960  * \return See \ref mp4_meta_get_artist().
961  */
962 char *mp4_meta_get_comment(const struct mp4 *f)
963 {
964         return meta_find_by_name(f, "comment");
965 }