]> git.tuebingen.mpg.de Git - paraslash.git/blob - mp4.c
mp4: Add error checking to parse_atoms() and friends.
[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 "portable_io.h"
12 #include "string.h"
13 #include "mp4.h"
14
15 struct mp4_track {
16         bool is_audio;
17         uint16_t channelCount;
18         uint16_t sampleRate;
19
20         /* stsz */
21         uint32_t stsz_sample_size;
22         uint32_t stsz_sample_count;
23         uint32_t *stsz_table;
24
25         /* stts */
26         uint32_t stts_entry_count;
27         uint32_t *stts_sample_count;
28         uint32_t *stts_sample_delta;
29
30         /* stsc */
31         uint32_t stsc_entry_count;
32         uint32_t *stsc_first_chunk;
33         uint32_t *stsc_samples_per_chunk;
34         uint32_t *stsc_sample_desc_index;
35
36         /* stsc */
37         uint32_t stco_entry_count;
38         uint32_t *stco_chunk_offset;
39
40         uint32_t timeScale;
41         uint64_t duration;
42 };
43
44 #define MAX_TRACKS 1024
45
46 struct mp4 {
47         const struct mp4_callback *cb;
48         int64_t current_position;
49
50         uint64_t moov_offset;
51         uint64_t moov_size;
52         uint8_t last_atom;
53         uint64_t file_size;
54
55         uint32_t error;
56
57         /* incremental track index while reading the file */
58         int32_t total_tracks;
59
60         /* track data */
61         struct mp4_track *track[MAX_TRACKS];
62
63         /* metadata */
64         struct mp4_metadata meta;
65 };
66
67 int32_t mp4_total_tracks(const struct mp4 *f)
68 {
69         return f->total_tracks;
70 }
71
72 /*
73  * Returns -1, 0, or 1 on errors/EOF/success. Partial reads followed by EOF or
74  * read errors are treated as errors.
75  */
76 static int read_data(struct mp4 *f, void *data, size_t size)
77 {
78         while (size > 0) {
79                 ssize_t ret = f->cb->read(f->cb->user_data, data, size);
80                 if (ret < 0 && errno == EINTR)
81                         continue;
82                 /* regard EAGAIN as an error as reads should be blocking. */
83                 if (ret <= 0)
84                         return ret < 0? -1 : 0;
85                 f->current_position += ret;
86                 size -= ret;
87         }
88         return 1;
89 }
90
91 static int read_int64(struct mp4 *f, uint64_t *result)
92 {
93         uint8_t data[8];
94         int ret = read_data(f, data, 8);
95
96         if (ret > 0 && result)
97                 *result = read_u64_be(data);
98         return ret;
99 }
100
101 static int read_int32(struct mp4 *f, uint32_t *result)
102 {
103         uint8_t data[4];
104         int ret = read_data(f, data, 4);
105
106         if (ret > 0 && result)
107                 *result = read_u32_be(data);
108         return ret;
109 }
110
111 static int read_int24(struct mp4 *f, uint32_t *result)
112 {
113         uint8_t data[3];
114         int ret = read_data(f, data, 3);
115
116         if (ret > 0 && result)
117                 *result = read_u24_be(data);
118         return ret;
119 }
120
121 static int read_int16(struct mp4 *f, uint16_t *result)
122 {
123         uint8_t data[2];
124         int ret = read_data(f, data, 2);
125
126         if (ret > 0 && result)
127                 *result = read_u16_be(data);
128         return ret;
129 }
130
131 static uint8_t read_int8(struct mp4 *f, uint8_t *result)
132 {
133         uint8_t data[1];
134         int ret = read_data(f, data, 1);
135
136         if (ret > 0 && result)
137                 *result = data[0];
138         return ret;
139 }
140
141 static bool atom_compare(int8_t a1, int8_t b1, int8_t c1, int8_t d1,
142                 int8_t a2, int8_t b2, int8_t c2, int8_t d2)
143 {
144         return a1 == a2 && b1 == b2 && c1 == c2 && d1 == d2;
145 }
146
147 enum atoms {
148         /* atoms with subatoms */
149         ATOM_MOOV = 1,
150         ATOM_TRAK = 2,
151         ATOM_EDTS = 3,
152         ATOM_MDIA = 4,
153         ATOM_MINF = 5,
154         ATOM_STBL = 6,
155         ATOM_UDTA = 7,
156         ATOM_ILST = 8, /* iTunes Metadata list */
157         ATOM_TITLE = 9,
158         ATOM_ARTIST = 10,
159         ATOM_WRITER = 11,
160         ATOM_ALBUM = 12,
161         ATOM_DATE = 13,
162         ATOM_TOOL = 14,
163         ATOM_COMMENT = 15,
164         ATOM_GENRE1 = 16,
165         ATOM_TRACK = 17,
166         ATOM_DISC = 18,
167         ATOM_COMPILATION = 19,
168         ATOM_GENRE2 = 20,
169         ATOM_TEMPO = 21,
170         ATOM_COVER = 22,
171         ATOM_DRMS = 23,
172         ATOM_SINF = 24,
173         ATOM_SCHI = 25,
174
175         SUBATOMIC = 128,
176
177         /* atoms without subatoms */
178         ATOM_FTYP = 129,
179         ATOM_MDAT = 130,
180         ATOM_MVHD = 131,
181         ATOM_TKHD = 132,
182         ATOM_TREF = 133,
183         ATOM_MDHD = 134, /* track header */
184         ATOM_VMHD = 135,
185         ATOM_SMHD = 136,
186         ATOM_HMHD = 137,
187         ATOM_STSD = 138, /* sample description box */
188         ATOM_STTS = 139, /* time to sample box */
189         ATOM_STSZ = 140, /* sample size box */
190         ATOM_STZ2 = 141,
191         ATOM_STCO = 142, /* chunk offset box */
192         ATOM_STSC = 143, /* sample to chunk box */
193         ATOM_MP4A = 144,
194         ATOM_MP4V = 145,
195         ATOM_MP4S = 146,
196         ATOM_ESDS = 147,
197         ATOM_META = 148, /* iTunes Metadata box */
198         ATOM_NAME = 149, /* iTunes Metadata name box */
199         ATOM_DATA = 150, /* iTunes Metadata data box */
200         ATOM_CTTS = 151,
201         ATOM_FRMA = 152,
202         ATOM_IVIV = 153,
203         ATOM_PRIV = 154,
204         ATOM_USER = 155,
205         ATOM_KEY = 156,
206         ATOM_ALBUM_ARTIST = 157,
207         ATOM_CONTENTGROUP = 158,
208         ATOM_LYRICS = 159,
209         ATOM_DESCRIPTION = 160,
210         ATOM_NETWORK = 161,
211         ATOM_SHOW = 162,
212         ATOM_EPISODENAME = 163,
213         ATOM_SORTTITLE = 164,
214         ATOM_SORTALBUM = 165,
215         ATOM_SORTARTIST = 166,
216         ATOM_SORTALBUMARTIST = 167,
217         ATOM_SORTWRITER = 168,
218         ATOM_SORTSHOW = 169,
219         ATOM_SEASON = 170,
220         ATOM_EPISODE = 171,
221         ATOM_PODCAST = 172,
222
223         ATOM_UNKNOWN = 255
224 };
225
226 #define ATOM_FREE ATOM_UNKNOWN
227 #define ATOM_SKIP ATOM_UNKNOWN
228
229 #define COPYRIGHT_SYMBOL ((int8_t)0xA9)
230
231 static uint8_t atom_name_to_type(int8_t a, int8_t b, int8_t c, int8_t d)
232 {
233         if (a == 'm') {
234                 if (atom_compare(a, b, c, d, 'm', 'o', 'o', 'v'))
235                         return ATOM_MOOV;
236                 else if (atom_compare(a, b, c, d, 'm', 'i', 'n', 'f'))
237                         return ATOM_MINF;
238                 else if (atom_compare(a, b, c, d, 'm', 'd', 'i', 'a'))
239                         return ATOM_MDIA;
240                 else if (atom_compare(a, b, c, d, 'm', 'd', 'a', 't'))
241                         return ATOM_MDAT;
242                 else if (atom_compare(a, b, c, d, 'm', 'd', 'h', 'd'))
243                         return ATOM_MDHD;
244                 else if (atom_compare(a, b, c, d, 'm', 'v', 'h', 'd'))
245                         return ATOM_MVHD;
246                 else if (atom_compare(a, b, c, d, 'm', 'p', '4', 'a'))
247                         return ATOM_MP4A;
248                 else if (atom_compare(a, b, c, d, 'm', 'p', '4', 'v'))
249                         return ATOM_MP4V;
250                 else if (atom_compare(a, b, c, d, 'm', 'p', '4', 's'))
251                         return ATOM_MP4S;
252                 else if (atom_compare(a, b, c, d, 'm', 'e', 't', 'a'))
253                         return ATOM_META;
254         } else if (a == 't') {
255                 if (atom_compare(a, b, c, d, 't', 'r', 'a', 'k'))
256                         return ATOM_TRAK;
257                 else if (atom_compare(a, b, c, d, 't', 'k', 'h', 'd'))
258                         return ATOM_TKHD;
259                 else if (atom_compare(a, b, c, d, 't', 'r', 'e', 'f'))
260                         return ATOM_TREF;
261                 else if (atom_compare(a, b, c, d, 't', 'r', 'k', 'n'))
262                         return ATOM_TRACK;
263                 else if (atom_compare(a, b, c, d, 't', 'm', 'p', 'o'))
264                         return ATOM_TEMPO;
265                 else if (atom_compare(a, b, c, d, 't', 'v', 'n', 'n'))
266                         return ATOM_NETWORK;
267                 else if (atom_compare(a, b, c, d, 't', 'v', 's', 'h'))
268                         return ATOM_SHOW;
269                 else if (atom_compare(a, b, c, d, 't', 'v', 'e', 'n'))
270                         return ATOM_EPISODENAME;
271                 else if (atom_compare(a, b, c, d, 't', 'v', 's', 'n'))
272                         return ATOM_SEASON;
273                 else if (atom_compare(a, b, c, d, 't', 'v', 'e', 's'))
274                         return ATOM_EPISODE;
275         } else if (a == 's') {
276                 if (atom_compare(a, b, c, d, 's', 't', 'b', 'l'))
277                         return ATOM_STBL;
278                 else if (atom_compare(a, b, c, d, 's', 'm', 'h', 'd'))
279                         return ATOM_SMHD;
280                 else if (atom_compare(a, b, c, d, 's', 't', 's', 'd'))
281                         return ATOM_STSD;
282                 else if (atom_compare(a, b, c, d, 's', 't', 't', 's'))
283                         return ATOM_STTS;
284                 else if (atom_compare(a, b, c, d, 's', 't', 'c', 'o'))
285                         return ATOM_STCO;
286                 else if (atom_compare(a, b, c, d, 's', 't', 's', 'c'))
287                         return ATOM_STSC;
288                 else if (atom_compare(a, b, c, d, 's', 't', 's', 'z'))
289                         return ATOM_STSZ;
290                 else if (atom_compare(a, b, c, d, 's', 't', 'z', '2'))
291                         return ATOM_STZ2;
292                 else if (atom_compare(a, b, c, d, 's', 'k', 'i', 'p'))
293                         return ATOM_SKIP;
294                 else if (atom_compare(a, b, c, d, 's', 'i', 'n', 'f'))
295                         return ATOM_SINF;
296                 else if (atom_compare(a, b, c, d, 's', 'c', 'h', 'i'))
297                         return ATOM_SCHI;
298                 else if (atom_compare(a, b, c, d, 's', 'o', 'n', 'm'))
299                         return ATOM_SORTTITLE;
300                 else if (atom_compare(a, b, c, d, 's', 'o', 'a', 'l'))
301                         return ATOM_SORTALBUM;
302                 else if (atom_compare(a, b, c, d, 's', 'o', 'a', 'r'))
303                         return ATOM_SORTARTIST;
304                 else if (atom_compare(a, b, c, d, 's', 'o', 'a', 'a'))
305                         return ATOM_SORTALBUMARTIST;
306                 else if (atom_compare(a, b, c, d, 's', 'o', 'c', 'o'))
307                         return ATOM_SORTWRITER;
308                 else if (atom_compare(a, b, c, d, 's', 'o', 's', 'n'))
309                         return ATOM_SORTSHOW;
310         } else if (a == COPYRIGHT_SYMBOL) {
311                 if (atom_compare(a, b, c, d, COPYRIGHT_SYMBOL, 'n', 'a', 'm'))
312                         return ATOM_TITLE;
313                 else if (atom_compare(a, b, c, d, COPYRIGHT_SYMBOL, 'A', 'R', 'T'))
314                         return ATOM_ARTIST;
315                 else if (atom_compare(a, b, c, d, COPYRIGHT_SYMBOL, 'w', 'r', 't'))
316                         return ATOM_WRITER;
317                 else if (atom_compare(a, b, c, d, COPYRIGHT_SYMBOL, 'a', 'l', 'b'))
318                         return ATOM_ALBUM;
319                 else if (atom_compare(a, b, c, d, COPYRIGHT_SYMBOL, 'd', 'a', 'y'))
320                         return ATOM_DATE;
321                 else if (atom_compare(a, b, c, d, COPYRIGHT_SYMBOL, 't', 'o', 'o'))
322                         return ATOM_TOOL;
323                 else if (atom_compare(a, b, c, d, COPYRIGHT_SYMBOL, 'c', 'm', 't'))
324                         return ATOM_COMMENT;
325                 else if (atom_compare(a, b, c, d, COPYRIGHT_SYMBOL, 'g', 'e', 'n'))
326                         return ATOM_GENRE1;
327                 else if (atom_compare(a, b, c, d, COPYRIGHT_SYMBOL, 'g', 'r', 'p'))
328                         return ATOM_CONTENTGROUP;
329                 else if (atom_compare(a, b, c, d, COPYRIGHT_SYMBOL, 'l', 'y', 'r'))
330                         return ATOM_LYRICS;
331         }
332
333         if (atom_compare(a, b, c, d, 'e', 'd', 't', 's'))
334                 return ATOM_EDTS;
335         else if (atom_compare(a, b, c, d, 'e', 's', 'd', 's'))
336                 return ATOM_ESDS;
337         else if (atom_compare(a, b, c, d, 'f', 't', 'y', 'p'))
338                 return ATOM_FTYP;
339         else if (atom_compare(a, b, c, d, 'f', 'r', 'e', 'e'))
340                 return ATOM_FREE;
341         else if (atom_compare(a, b, c, d, 'h', 'm', 'h', 'd'))
342                 return ATOM_HMHD;
343         else if (atom_compare(a, b, c, d, 'v', 'm', 'h', 'd'))
344                 return ATOM_VMHD;
345         else if (atom_compare(a, b, c, d, 'u', 'd', 't', 'a'))
346                 return ATOM_UDTA;
347         else if (atom_compare(a, b, c, d, 'i', 'l', 's', 't'))
348                 return ATOM_ILST;
349         else if (atom_compare(a, b, c, d, 'n', 'a', 'm', 'e'))
350                 return ATOM_NAME;
351         else if (atom_compare(a, b, c, d, 'd', 'a', 't', 'a'))
352                 return ATOM_DATA;
353         else if (atom_compare(a, b, c, d, 'd', 'i', 's', 'k'))
354                 return ATOM_DISC;
355         else if (atom_compare(a, b, c, d, 'g', 'n', 'r', 'e'))
356                 return ATOM_GENRE2;
357         else if (atom_compare(a, b, c, d, 'c', 'o', 'v', 'r'))
358                 return ATOM_COVER;
359         else if (atom_compare(a, b, c, d, 'c', 'p', 'i', 'l'))
360                 return ATOM_COMPILATION;
361         else if (atom_compare(a, b, c, d, 'c', 't', 't', 's'))
362                 return ATOM_CTTS;
363         else if (atom_compare(a, b, c, d, 'd', 'r', 'm', 's'))
364                 return ATOM_DRMS;
365         else if (atom_compare(a, b, c, d, 'f', 'r', 'm', 'a'))
366                 return ATOM_FRMA;
367         else if (atom_compare(a, b, c, d, 'p', 'r', 'i', 'v'))
368                 return ATOM_PRIV;
369         else if (atom_compare(a, b, c, d, 'i', 'v', 'i', 'v'))
370                 return ATOM_IVIV;
371         else if (atom_compare(a, b, c, d, 'u', 's', 'e', 'r'))
372                 return ATOM_USER;
373         else if (atom_compare(a, b, c, d, 'k', 'e', 'y', ' '))
374                 return ATOM_KEY;
375         else if (atom_compare(a, b, c, d, 'a', 'A', 'R', 'T'))
376                 return ATOM_ALBUM_ARTIST;
377         else if (atom_compare(a, b, c, d, 'd', 'e', 's', 'c'))
378                 return ATOM_DESCRIPTION;
379         else if (atom_compare(a, b, c, d, 'p', 'c', 's', 't'))
380                 return ATOM_PODCAST;
381         else
382                 return ATOM_UNKNOWN;
383 }
384
385 /* read atom header, atom size is returned with header included. */
386 static int atom_read_header(struct mp4 *f, uint8_t *atom_type,
387                 uint8_t *header_size, uint64_t *atom_size)
388 {
389         uint32_t size;
390         int ret;
391         int8_t atom_header[8];
392
393         ret = read_data(f, atom_header, 8);
394         if (ret <= 0)
395                 return ret;
396         size = read_u32_be(atom_header);
397         if (size == 1) { /* 64 bit atom size */
398                 if (header_size)
399                         *header_size = 16;
400                 ret = read_int64(f, atom_size);
401                 if (ret <= 0)
402                         return ret;
403         } else {
404                 if (header_size)
405                         *header_size = 8;
406                 if (atom_size)
407                         *atom_size = size;
408         }
409         *atom_type = atom_name_to_type(atom_header[4], atom_header[5],
410                 atom_header[6], atom_header[7]);
411         return 1;
412 }
413
414 static int64_t get_position(const struct mp4 *f)
415 {
416         return f->current_position;
417 }
418
419 static int need_parse_when_meta_only(uint8_t atom_type)
420 {
421         switch (atom_type) {
422         case ATOM_EDTS:
423         case ATOM_DRMS:
424         case ATOM_SINF:
425         case ATOM_SCHI:
426         case ATOM_STTS:
427         case ATOM_STSZ:
428         case ATOM_STZ2:
429         case ATOM_STCO:
430         case ATOM_STSC:
431         case ATOM_FRMA:
432         case ATOM_IVIV:
433         case ATOM_PRIV:
434                 return 0;
435         default:
436                 return 1;
437         }
438 }
439
440 static int32_t set_position(struct mp4 *f, int64_t position)
441 {
442         f->cb->seek(f->cb->user_data, position);
443         f->current_position = position;
444
445         return 0;
446 }
447
448 static void track_add(struct mp4 *f)
449 {
450         f->total_tracks++;
451
452         if (f->total_tracks > MAX_TRACKS) {
453                 f->total_tracks = 0;
454                 f->error++;
455                 return;
456         }
457         f->track[f->total_tracks - 1] = para_calloc(sizeof(struct mp4_track));
458 }
459
460 static int read_stsz(struct mp4 *f)
461 {
462         int ret;
463         int32_t i;
464         struct mp4_track *t;
465
466         if (f->total_tracks == 0)
467                 return -1;
468         t = f->track[f->total_tracks - 1];
469         ret = read_int8(f, NULL); /* version */
470         if (ret <= 0)
471                 return ret;
472         ret = read_int24(f, NULL); /* flags */
473         if (ret <= 0)
474                 return ret;
475         ret = read_int32(f, &t->stsz_sample_size);
476         if (ret <= 0)
477                 return ret;
478         ret = read_int32(f, &t->stsz_sample_count);
479         if (ret <= 0)
480                 return ret;
481         if (t->stsz_sample_size != 0)
482                 return 1;
483         t->stsz_table = para_malloc(t->stsz_sample_count * sizeof(int32_t));
484         for (i = 0; i < t->stsz_sample_count; i++) {
485                 ret = read_int32(f, &t->stsz_table[i]);
486                 if (ret <= 0)
487                         return ret;
488         }
489         return 1;
490 }
491
492 static int read_stts(struct mp4 *f)
493 {
494         int ret;
495         int32_t i;
496         struct mp4_track *t;
497
498         if (f->total_tracks == 0)
499                 return -1;
500         t = f->track[f->total_tracks - 1];
501         if (t->stts_entry_count)
502                 return 0;
503         ret = read_int8(f, NULL); /* version */
504         if (ret <= 0)
505                 return ret;
506         ret = read_int24(f, NULL); /* flags */
507         if (ret <= 0)
508                 return ret;
509         ret = read_int32(f, &t->stts_entry_count);
510         if (ret <= 0)
511                 return ret;
512         t->stts_sample_count = para_malloc(t->stts_entry_count
513                 * sizeof(int32_t));
514         t->stts_sample_delta = para_malloc(t->stts_entry_count
515                 * sizeof (int32_t));
516         for (i = 0; i < t->stts_entry_count; i++) {
517                 ret = read_int32(f, &t->stts_sample_count[i]);
518                 if (ret <= 0)
519                         return ret;
520                 ret = read_int32(f, &t->stts_sample_delta[i]);
521                 if (ret <= 0)
522                         return ret;
523         }
524         return 1;
525 }
526
527 static int read_stsc(struct mp4 *f)
528 {
529         int ret;
530         int32_t i;
531         struct mp4_track *t;
532
533         if (f->total_tracks == 0)
534                 return -1;
535         t = f->track[f->total_tracks - 1];
536
537         ret = read_int8(f, NULL); /* version */
538         if (ret <= 0)
539                 return ret;
540         ret = read_int24(f, NULL); /* flags */
541         if (ret <= 0)
542                 return ret;
543         ret = read_int32(f, &t->stsc_entry_count);
544         if (ret <= 0)
545                 return ret;
546         t->stsc_first_chunk = para_malloc(t->stsc_entry_count * sizeof(int32_t));
547         t->stsc_samples_per_chunk = para_malloc(t->stsc_entry_count
548                 * sizeof (int32_t));
549         t->stsc_sample_desc_index = para_malloc(t->stsc_entry_count *
550                 sizeof (int32_t));
551
552         for (i = 0; i < t->stsc_entry_count; i++) {
553                 ret = read_int32(f, &t->stsc_first_chunk[i]);
554                 if (ret <= 0)
555                         return ret;
556                 ret = read_int32(f, &t->stsc_samples_per_chunk[i]);
557                 if (ret <= 0)
558                         return ret;
559                 ret = read_int32(f, &t->stsc_sample_desc_index[i]);
560                 if (ret <= 0)
561                         return ret;
562         }
563         return 1;
564 }
565
566 static int read_stco(struct mp4 *f)
567 {
568         int ret;
569         int32_t i;
570         struct mp4_track *t;
571
572         if (f->total_tracks == 0)
573                 return -1;
574         t = f->track[f->total_tracks - 1];
575
576         ret = read_int8(f, NULL); /* version */
577         if (ret <= 0)
578                 return ret;
579         ret = read_int24(f, NULL); /* flags */
580         if (ret <= 0)
581                 return ret;
582         ret = read_int32(f, &t->stco_entry_count);
583         if (ret <= 0)
584                 return ret;
585         t->stco_chunk_offset = para_malloc(t->stco_entry_count
586                 * sizeof(int32_t));
587         for (i = 0; i < t->stco_entry_count; i++) {
588                 ret = read_int32(f, &t->stco_chunk_offset[i]);
589                 if (ret <= 0)
590                         return ret;
591         }
592         return 1;
593 }
594
595 static int read_mp4a(struct mp4 *f)
596 {
597         int ret;
598         int32_t i;
599         uint8_t atom_type = 0;
600         uint8_t header_size = 0;
601         struct mp4_track *t;
602
603         if (f->total_tracks == 0)
604                 return -1;
605         t = f->track[f->total_tracks - 1];
606
607         for (i = 0; i < 6; i++) {
608                 ret = read_int8(f, NULL); /* reserved */
609                 if (ret <= 0)
610                         return ret;
611         }
612         ret = read_int16(f, NULL); /* data_reference_index */
613         if (ret <= 0)
614                 return ret;
615         ret = read_int32(f, NULL); /* reserved */
616         if (ret <= 0)
617                 return ret;
618         ret = read_int32(f, NULL); /* reserved */
619         if (ret <= 0)
620                 return ret;
621         ret = read_int16(f, &t->channelCount);
622         if (ret <= 0)
623                 return ret;
624         ret = read_int16(f, NULL);
625         if (ret <= 0)
626                 return ret;
627         ret = read_int16(f, NULL);
628         if (ret <= 0)
629                 return ret;
630         ret = read_int16(f, NULL);
631         if (ret <= 0)
632                 return ret;
633         ret = read_int16(f, &t->sampleRate);
634         if (ret <= 0)
635                 return ret;
636         ret = read_int16(f, NULL);
637         if (ret <= 0)
638                 return ret;
639         return atom_read_header(f, &atom_type, &header_size, NULL);
640 }
641
642 static int read_stsd(struct mp4 *f)
643 {
644         int ret;
645         uint32_t i, entry_count;
646         uint8_t header_size = 0;
647         struct mp4_track *t;
648
649         if (f->total_tracks == 0)
650                 return -1;
651         t = f->track[f->total_tracks - 1];
652         ret = read_int8(f, NULL); /* version */
653         if (ret <= 0)
654                 return ret;
655         ret = read_int24(f, NULL); /* flags */
656         if (ret <= 0)
657                 return ret;
658         ret = read_int32(f, &entry_count);
659         if (ret <= 0)
660                 return ret;
661         for (i = 0; i < entry_count; i++) {
662                 uint64_t skip = get_position(f);
663                 uint64_t size;
664                 uint8_t atom_type = 0;
665                 ret = atom_read_header(f, &atom_type, &header_size, &size);
666                 if (ret <= 0)
667                         return ret;
668                 skip += size;
669                 t->is_audio = atom_type == ATOM_MP4A;
670                 if (t->is_audio)
671                         read_mp4a(f);
672                 set_position(f, skip);
673         }
674         return 1;
675 }
676
677 static int32_t tag_add_field(struct mp4_metadata *meta, const char *item,
678                 const char *value, int32_t len)
679 {
680         meta->tags = para_realloc(meta->tags,
681                 (meta->count + 1) * sizeof(struct mp4_tag));
682         meta->tags[meta->count].item = para_strdup(item);
683         meta->tags[meta->count].len = len;
684         if (len >= 0) {
685                 meta->tags[meta->count].value = para_malloc(len + 1);
686                 memcpy(meta->tags[meta->count].value, value, len);
687                 meta->tags[meta->count].value[len] = 0;
688         } else {
689                 meta->tags[meta->count].value = para_strdup(value);
690         }
691         meta->count++;
692         return 1;
693 }
694
695 static int read_string(struct mp4 *f, uint32_t length, char **result)
696 {
697         char *str = para_malloc(length + 1);
698         int ret = read_data(f, str, length);
699
700         if (ret <= 0) {
701                 free(str);
702                 *result = NULL;
703         } else {
704                 str[length] = '\0';
705                 *result = str;
706         }
707         return ret;
708 }
709
710 static const char *get_metadata_name(uint8_t atom_type)
711 {
712         switch (atom_type) {
713         case ATOM_TITLE: return "title";
714         case ATOM_ARTIST: return "artist";
715         case ATOM_ALBUM: return "album";
716         case ATOM_DATE: return "date";
717         case ATOM_COMMENT: return "comment";
718         default: return "unknown";
719         }
720 }
721
722 static int parse_tag(struct mp4 *f, uint8_t parent, int32_t size)
723 {
724         int ret;
725         uint64_t subsize, sumsize;
726         char *data = NULL;
727         uint32_t len = 0;
728         uint64_t destpos;
729
730         for (
731                 sumsize = 0;
732                 sumsize < size;
733                 set_position(f, destpos), sumsize += subsize
734         ) {
735                 uint8_t atom_type;
736                 uint8_t header_size = 0;
737                 ret = atom_read_header(f, &atom_type, &header_size, &subsize);
738                 if (ret <= 0)
739                         return ret;
740                 destpos = get_position(f) + subsize - header_size;
741                 if (atom_type != ATOM_DATA)
742                         continue;
743                 ret = read_int8(f, NULL); /* version */
744                 if (ret <= 0)
745                         return ret;
746                 ret = read_int24(f, NULL); /* flags */
747                 if (ret <= 0)
748                         return ret;
749                 ret = read_int32(f, NULL); /* reserved */
750                 if (ret <= 0)
751                         return ret;
752                 free(data);
753                 ret = read_string(f, subsize - (header_size + 8), &data);
754                 if (ret <= 0)
755                         return ret;
756                 len = subsize - (header_size + 8);
757         }
758         if (!data)
759                 return -1;
760         tag_add_field(&f->meta, get_metadata_name(parent), data, len);
761         free(data);
762         return 1;
763 }
764
765 static int read_mdhd(struct mp4 *f)
766 {
767         int ret;
768         uint32_t version;
769         struct mp4_track *t;
770
771         if (f->total_tracks == 0)
772                 return -1;
773         t = f->track[f->total_tracks - 1];
774
775         ret = read_int32(f, &version);
776         if (ret <= 0)
777                 return ret;
778         if (version == 1) {
779                 ret = read_int64(f, NULL); /* creation-time */
780                 if (ret <= 0)
781                         return ret;
782                 ret = read_int64(f, NULL); /* modification-time */
783                 if (ret <= 0)
784                         return ret;
785                 ret = read_int32(f, &t->timeScale);
786                 if (ret <= 0)
787                         return ret;
788                 ret = read_int64(f, &t->duration);
789                 if (ret <= 0)
790                         return ret;
791         } else { //version == 0
792                 uint32_t temp;
793
794                 ret = read_int32(f, NULL); /* creation-time */
795                 if (ret <= 0)
796                         return ret;
797                 ret = read_int32(f, NULL); /* modification-time */
798                 if (ret <= 0)
799                         return ret;
800                 ret = read_int32(f, &t->timeScale);
801                 if (ret <= 0)
802                         return ret;
803                 ret = read_int32(f, &temp);
804                 if (ret <= 0)
805                         return ret;
806                 t->duration = (temp == (uint32_t) (-1))?
807                         (uint64_t) (-1) : (uint64_t) (temp);
808         }
809         ret = read_int16(f, NULL);
810         if (ret <= 0)
811                 return ret;
812         ret = read_int16(f, NULL);
813         if (ret <= 0)
814                 return ret;
815         return 1;
816 }
817
818 static int32_t read_ilst(struct mp4 *f, int32_t size)
819 {
820         int ret;
821         uint64_t sumsize = 0;
822
823         while (sumsize < size) {
824                 uint8_t atom_type;
825                 uint64_t subsize, destpos;
826                 uint8_t header_size = 0;
827                 ret = atom_read_header(f, &atom_type, &header_size, &subsize);
828                 if (ret <= 0)
829                         return ret;
830                 destpos = get_position(f) + subsize - header_size;
831                 switch (atom_type) {
832                 case ATOM_ARTIST:
833                 case ATOM_TITLE:
834                 case ATOM_ALBUM:
835                 case ATOM_COMMENT:
836                 case ATOM_DATE:
837                         parse_tag(f, atom_type, subsize - header_size);
838                 }
839                 set_position(f, destpos);
840                 sumsize += subsize;
841         }
842         return 1;
843 }
844
845 static int32_t read_meta(struct mp4 *f, uint64_t size)
846 {
847         int ret;
848         uint64_t subsize, sumsize = 0;
849         uint8_t atom_type;
850         uint8_t header_size = 0;
851
852         ret = read_int8(f, NULL); /* version */
853         if (ret <= 0)
854                 return ret;
855         ret = read_int24(f, NULL); /* flags */
856         if (ret <= 0)
857                 return ret;
858         while (sumsize < (size - (header_size + 4))) {
859                 ret = atom_read_header(f, &atom_type, &header_size, &subsize);
860                 if (ret <= 0)
861                         return ret;
862                 if (subsize <= header_size + 4)
863                         return 1;
864                 if (atom_type == ATOM_ILST)
865                         read_ilst(f, subsize - (header_size + 4));
866                 else
867                         set_position(f, get_position(f) + subsize - header_size);
868                 sumsize += subsize;
869         }
870         return 1;
871 }
872
873 static int atom_read(struct mp4 *f, uint64_t size, uint8_t atom_type)
874 {
875         uint64_t dest_position = get_position(f) + size - 8;
876         int ret = 1; /* return success for atoms we don't care about */
877
878         switch (atom_type) {
879         case ATOM_STSZ: ret = read_stsz(f); break;
880         case ATOM_STTS: ret = read_stts(f); break;
881         case ATOM_STSC: ret = read_stsc(f); break;
882         case ATOM_STCO: ret = read_stco(f); break;
883         case ATOM_STSD: ret = read_stsd(f); break;
884         case ATOM_MDHD: ret = read_mdhd(f); break;
885         case ATOM_META: ret = read_meta(f, size); break;
886         }
887         set_position(f, dest_position);
888         return ret;
889 }
890
891 /* parse atoms that are sub atoms of other atoms */
892 static int parse_sub_atoms(struct mp4 *f, uint64_t total_size, int meta_only)
893 {
894         int ret;
895         uint64_t size;
896         uint8_t atom_type = 0;
897         uint64_t counted_size = 0;
898         uint8_t header_size = 0;
899
900         while (counted_size < total_size) {
901                 ret = atom_read_header(f, &atom_type, &header_size, &size);
902                 if (ret <= 0)
903                         return ret;
904                 if (size == 0)
905                         return -1;
906                 counted_size += size;
907                 /* we're starting to read a new track, update index,
908                  * so that all data and tables get written in the right place
909                  */
910                 if (atom_type == ATOM_TRAK)
911                         track_add(f);
912                 /* parse subatoms */
913                 if (meta_only && !need_parse_when_meta_only(atom_type)) {
914                         set_position(f, get_position(f) + size - header_size);
915                 } else if (atom_type < SUBATOMIC) {
916                         ret = parse_sub_atoms(f, size - header_size, meta_only);
917                         if (ret <= 0)
918                                 return ret;
919                 } else {
920                         ret = atom_read(f, size, atom_type);
921                         if (ret <= 0)
922                                 return ret;
923                 }
924         }
925         return 1;
926 }
927
928 /* parse root atoms */
929 static int parse_atoms(struct mp4 *f, int meta_only)
930 {
931         int ret;
932         uint64_t size;
933         uint8_t atom_type = 0;
934         uint8_t header_size = 0;
935
936         f->file_size = 0;
937
938         while ((ret = atom_read_header(f, &atom_type, &header_size, &size)) > 0) {
939                 f->file_size += size;
940                 f->last_atom = atom_type;
941
942                 if (atom_type == ATOM_MOOV && size > header_size) {
943                         f->moov_offset = get_position(f) - header_size;
944                         f->moov_size = size;
945                 }
946
947                 /* parse subatoms */
948                 if (meta_only && !need_parse_when_meta_only(atom_type)) {
949                         set_position(f, get_position(f) + size - header_size);
950                 } else if (atom_type < SUBATOMIC) {
951                         ret = parse_sub_atoms(f, size - header_size, meta_only);
952                         if (ret <= 0)
953                                 return ret;
954                 } else {
955                         /* skip this atom */
956                         set_position(f, get_position(f) + size - header_size);
957                 }
958         }
959         return ret;
960 }
961
962 struct mp4 *mp4_open_read(const struct mp4_callback *cb)
963 {
964         int ret;
965         struct mp4 *f = para_calloc(sizeof(struct mp4));
966
967         f->cb = cb;
968         ret = parse_atoms(f, 0);
969         if (ret < 0 || f->error) {
970                 free(f);
971                 return NULL;
972         }
973         return f;
974 }
975
976 void mp4_close(struct mp4 *f)
977 {
978         int32_t i;
979
980         for (i = 0; i < f->total_tracks; i++) {
981                 if (f->track[i]) {
982                         free(f->track[i]->stsz_table);
983                         free(f->track[i]->stts_sample_count);
984                         free(f->track[i]->stts_sample_delta);
985                         free(f->track[i]->stsc_first_chunk);
986                         free(f->track[i]->stsc_samples_per_chunk);
987                         free(f->track[i]->stsc_sample_desc_index);
988                         free(f->track[i]->stco_chunk_offset);
989                         free(f->track[i]);
990                 }
991         }
992         for (i = 0; i < f->meta.count; i++) {
993                 free(f->meta.tags[i].item);
994                 free(f->meta.tags[i].value);
995         }
996         free(f->meta.tags);
997         free(f);
998 }
999
1000 static int32_t chunk_of_sample(const struct mp4 *f, int32_t track,
1001                 int32_t sample, int32_t *chunk_sample, int32_t *chunk)
1002 {
1003         int32_t total_entries = 0;
1004         int32_t chunk2entry;
1005         int32_t chunk1, chunk2, chunk1samples, range_samples, total = 0;
1006
1007         *chunk_sample = 0;
1008         *chunk = 1;
1009         if (f->track[track] == NULL) {
1010                 return -1;
1011         }
1012
1013         total_entries = f->track[track]->stsc_entry_count;
1014
1015         chunk1 = 1;
1016         chunk1samples = 0;
1017         chunk2entry = 0;
1018
1019         do {
1020                 chunk2 = f->track[track]->stsc_first_chunk[chunk2entry];
1021                 *chunk = chunk2 - chunk1;
1022                 range_samples = *chunk * chunk1samples;
1023
1024                 if (sample < total + range_samples)
1025                         break;
1026
1027                 chunk1samples = f->track[track]->stsc_samples_per_chunk[chunk2entry];
1028                 chunk1 = chunk2;
1029
1030                 if (chunk2entry < total_entries) {
1031                         chunk2entry++;
1032                         total += range_samples;
1033                 }
1034         } while (chunk2entry < total_entries);
1035
1036         if (chunk1samples)
1037                 *chunk = (sample - total) / chunk1samples + chunk1;
1038         else
1039                 *chunk = 1;
1040
1041         *chunk_sample = total + (*chunk - chunk1) * chunk1samples;
1042
1043         return 0;
1044 }
1045
1046 static int32_t chunk_to_offset(const struct mp4 *f, int32_t track,
1047                 int32_t chunk)
1048 {
1049         const struct mp4_track *p_track = f->track[track];
1050
1051         if (p_track->stco_entry_count && (chunk > p_track->stco_entry_count)) {
1052                 return p_track->stco_chunk_offset[p_track->stco_entry_count -
1053                                                   1];
1054         } else if (p_track->stco_entry_count) {
1055                 return p_track->stco_chunk_offset[chunk - 1];
1056         } else {
1057                 return 8;
1058         }
1059
1060         return 0;
1061 }
1062
1063 static int32_t sample_range_size(const struct mp4 *f, int32_t track,
1064                 int32_t chunk_sample, int32_t sample)
1065 {
1066         int32_t i, total;
1067         const struct mp4_track *p_track = f->track[track];
1068
1069         if (p_track->stsz_sample_size) {
1070                 return (sample - chunk_sample) * p_track->stsz_sample_size;
1071         } else {
1072                 if (sample >= p_track->stsz_sample_count)
1073                         return 0;       //error
1074
1075                 for (i = chunk_sample, total = 0; i < sample; i++) {
1076                         total += p_track->stsz_table[i];
1077                 }
1078         }
1079
1080         return total;
1081 }
1082
1083 static int32_t sample_to_offset(const struct mp4 *f, int32_t track,
1084                 int32_t sample)
1085 {
1086         int32_t chunk, chunk_sample, chunk_offset1, chunk_offset2;
1087
1088         chunk_of_sample(f, track, sample, &chunk_sample, &chunk);
1089
1090         chunk_offset1 = chunk_to_offset(f, track, chunk);
1091         chunk_offset2 = chunk_offset1 + sample_range_size(f,
1092                 track, chunk_sample, sample);
1093         return chunk_offset2;
1094 }
1095
1096 /**
1097  * Return the number of milliseconds of the given track.
1098  *
1099  * \param f As returned by \ref mp4_open_read(), must not be NULL.
1100  * \param track Between zero and the value returned by \ref mp4_total_tracks().
1101  *
1102  * The function returns zero if the audio file is of zero length or contains a
1103  * corrupt track header.
1104  */
1105 uint64_t mp4_get_duration(const struct mp4 *f, int32_t track)
1106 {
1107         const struct mp4_track *t = f->track[track];
1108
1109         if (t->timeScale == 0)
1110                 return 0;
1111         return t->duration * 1000 / t->timeScale;
1112 }
1113
1114 /**
1115  * Check whether the given track number corresponds to an audio track.
1116  *
1117  * \param f See \ref mp4_get_duration().
1118  * \param track See \ref mp4_get_duration().
1119  *
1120  * Besides audio tracks, an mp4 file may contain video and system tracks. For
1121  * those the function returns false.
1122  */
1123 bool mp4_is_audio_track(const struct mp4 *f, int32_t track)
1124 {
1125         return f->track[track]->is_audio;
1126 }
1127
1128 void mp4_set_sample_position(struct mp4 *f, int32_t track, int32_t sample)
1129 {
1130         int32_t offset = sample_to_offset(f, track, sample);
1131         set_position(f, offset);
1132 }
1133
1134 int32_t mp4_get_sample_size(const struct mp4 *f, int track, int sample)
1135 {
1136         const struct mp4_track *t = f->track[track];
1137
1138         if (t->stsz_sample_size != 0)
1139                 return t->stsz_sample_size;
1140         return t->stsz_table[sample];
1141 }
1142
1143 uint32_t mp4_get_sample_rate(const struct mp4 *f, int32_t track)
1144 {
1145         return f->track[track]->sampleRate;
1146 }
1147
1148 uint32_t mp4_get_channel_count(const struct mp4 *f, int32_t track)
1149 {
1150         return f->track[track]->channelCount;
1151 }
1152
1153 int32_t mp4_num_samples(const struct mp4 *f, int32_t track)
1154 {
1155         int32_t i;
1156         int32_t total = 0;
1157
1158         for (i = 0; i < f->track[track]->stts_entry_count; i++) {
1159                 total += f->track[track]->stts_sample_count[i];
1160         }
1161         return total;
1162 }
1163
1164 struct mp4 *mp4_open_meta(const struct mp4_callback *cb)
1165 {
1166         int ret;
1167         struct mp4 *f = para_calloc(sizeof(struct mp4));
1168
1169         f->cb = cb;
1170         ret = parse_atoms(f, 1);
1171         if (ret < 0 || f->error) {
1172                 free(f);
1173                 return NULL;
1174         }
1175         return f;
1176 }
1177
1178 /**
1179  * Return the metadata of an mp4 file.
1180  *
1181  * \param f As returned by either \ref mp4_open_read() or \ref mp4_open_meta().
1182  *
1183  * The caller is allowed to add, delete or modify the entries of the returned
1184  * structure in order to pass the modified version to \ref mp4_meta_update().
1185  */
1186 struct mp4_metadata *mp4_get_meta(struct mp4 *f)
1187 {
1188         return &f->meta;
1189 }
1190
1191 static int find_atom(struct mp4 *f, uint64_t base, uint32_t size,
1192         const char *name)
1193 {
1194         uint32_t remaining = size;
1195         uint64_t atom_offset = base;
1196
1197         for (;;) {
1198                 int ret;
1199                 char atom_name[4];
1200                 uint32_t atom_size;
1201
1202                 set_position(f, atom_offset);
1203
1204                 if (remaining < 8)
1205                         return -1;
1206                 ret = read_int32(f, &atom_size);
1207                 if (ret <= 0)
1208                         return ret;
1209                 if (atom_size > remaining || atom_size < 8)
1210                         return -1;
1211                 ret = read_data(f, atom_name, 4);
1212                 if (ret <= 0)
1213                         return ret;
1214                 if (!memcmp(atom_name, name, 4)) {
1215                         set_position(f, atom_offset);
1216                         return 1;
1217                 }
1218                 remaining -= atom_size;
1219                 atom_offset += atom_size;
1220         }
1221 }
1222
1223 /*
1224  * Try to find atom <name> with atom <name_inside> in it. Besides -1/0/1 for
1225  * error, EOF and success, this function may return 2 to indicate that the
1226  * desired atoms were not found.
1227  */
1228 static int find_atom_v2(struct mp4 *f, uint64_t base, uint32_t size,
1229                 const char *name, uint32_t extraheaders, const char *name_inside)
1230 {
1231         uint64_t first_base = (uint64_t) (-1);
1232
1233         for (;;) {
1234                 uint64_t mybase;
1235                 uint32_t mysize;
1236                 int ret = find_atom(f, base, size, name);
1237
1238                 if (ret <= 0)
1239                         return ret;
1240                 mybase = get_position(f);
1241                 ret = read_int32(f, &mysize);
1242                 if (ret <= 0)
1243                         return ret;
1244                 if (first_base == (uint64_t) (-1))
1245                         first_base = mybase;
1246
1247                 if (mysize < 8 + extraheaders)
1248                         break;
1249
1250                 if (find_atom (f, mybase + (8 + extraheaders),
1251                                 mysize - (8 + extraheaders), name_inside)) {
1252                         set_position(f, mybase);
1253                         return 1;
1254                 }
1255                 base += mysize;
1256                 if (size <= mysize)
1257                         break;
1258                 size -= mysize;
1259         }
1260         if (first_base != (uint64_t)(-1)) {
1261                 set_position(f, first_base);
1262                 return 1;
1263         }
1264         /* wanted atom inside not found */
1265         return 2;
1266 }
1267
1268 struct membuffer {
1269         void *data;
1270         unsigned written;
1271         unsigned allocated;
1272 };
1273
1274 static struct membuffer *membuffer_create(void)
1275 {
1276         struct membuffer *buf = para_calloc(sizeof(*buf));
1277
1278         buf->allocated = 256;
1279         buf->data = para_malloc(buf->allocated);
1280         return buf;
1281 }
1282
1283 static void membuffer_write(struct membuffer *buf, const void *ptr,
1284                 unsigned bytes)
1285 {
1286         unsigned dest_size = buf->written + bytes;
1287
1288         if (dest_size > buf->allocated) {
1289                 do {
1290                         buf->allocated <<= 1;
1291                 } while (dest_size > buf->allocated);
1292                 buf->data = para_realloc(buf->data, buf->allocated);
1293         }
1294
1295         if (ptr)
1296                 memcpy((char *) buf->data + buf->written, ptr, bytes);
1297         buf->written += bytes;
1298 }
1299
1300 static void membuffer_write_atom_name(struct membuffer *buf, const char *data)
1301 {
1302         membuffer_write(buf, data, 4);
1303 }
1304
1305 static void membuffer_write_int32(struct membuffer *buf, uint32_t data)
1306 {
1307         uint8_t temp[4];
1308         write_u32_be(temp, data);
1309         membuffer_write(buf, temp, 4);
1310 }
1311
1312 static void membuffer_write_std_tag(struct membuffer *buf, const char *name,
1313                 const char *value)
1314 {
1315         uint32_t len = strlen(value);
1316         membuffer_write_int32(buf, 8 /* atom header */
1317                 + 8 /* data atom header */
1318                 + 8 /* flags + reserved */
1319                 + len);
1320         membuffer_write_atom_name(buf, name);
1321         membuffer_write_int32(buf, 8 /* data atom header */
1322                 + 8 /* flags + reserved */
1323                 + len);
1324         membuffer_write_atom_name(buf, "data");
1325         membuffer_write_int32(buf, 1);  /* flags */
1326         membuffer_write_int32(buf, 0);  /* reserved */
1327         membuffer_write(buf, value, len);
1328 }
1329
1330 static unsigned membuffer_get_size(const struct membuffer *buf)
1331 {
1332         return buf->written;
1333 }
1334
1335 static void *membuffer_detach(struct membuffer *buf)
1336 {
1337         void *ret = para_realloc(buf->data, buf->written);
1338         free(buf);
1339         return ret;
1340 }
1341
1342 struct stdmeta_entry {
1343         const char *atom;
1344         const char *name;
1345 };
1346
1347 static const char *find_standard_meta(const char *name)
1348 {
1349         const struct stdmeta_entry stdmetas[] = {
1350                 {"\xA9" "nam", "title"},
1351                 {"\xA9" "ART", "artist"},
1352                 {"\xA9" "alb", "album"},
1353                 {"\xA9" "day", "date"},
1354                 {"\xA9" "cmt", "comment"},
1355         };
1356
1357         for (unsigned n = 0; n < ARRAY_SIZE(stdmetas); n++)
1358                 if (!strcasecmp(name, stdmetas[n].name))
1359                         return stdmetas[n].atom;
1360         return NULL;
1361 }
1362
1363 static uint32_t create_ilst(const struct mp4_metadata *meta, void **out_buffer,
1364                 uint32_t * out_size)
1365 {
1366         struct membuffer *buf = membuffer_create();
1367         unsigned metaptr;
1368
1369         for (metaptr = 0; metaptr < meta->count; metaptr++) {
1370                 struct mp4_tag *tag = meta->tags + metaptr;
1371                 const char *std_meta_atom = find_standard_meta(tag->item);
1372                 if (std_meta_atom)
1373                         membuffer_write_std_tag(buf, std_meta_atom, tag->value);
1374                 else
1375                         PARA_ERROR_LOG("invalid tag item: %s\n", tag->item);
1376         }
1377         *out_size = membuffer_get_size(buf);
1378         *out_buffer = membuffer_detach(buf);
1379         return 1;
1380 }
1381
1382 static void membuffer_write_atom(struct membuffer *buf, const char *name, unsigned size,
1383                           const void *data)
1384 {
1385         membuffer_write_int32(buf, size + 8);
1386         membuffer_write_atom_name(buf, name);
1387         membuffer_write(buf, data, size);
1388 }
1389
1390 static void *membuffer_get_ptr(const struct membuffer *buf)
1391 {
1392         return buf->data;
1393 }
1394
1395 static bool membuffer_transfer_from_file(struct membuffer *buf, struct mp4 *src,
1396                 unsigned bytes)
1397 {
1398         unsigned oldsize = membuffer_get_size(buf);
1399         char *bufptr;
1400
1401         membuffer_write(buf, 0, bytes);
1402         bufptr = membuffer_get_ptr(buf);
1403         if (read_data(src, bufptr + oldsize, bytes) != 1) {
1404                 free(buf->data);
1405                 free(buf);
1406                 return false;
1407         }
1408         return true;
1409 }
1410
1411 static uint32_t create_meta(const struct mp4_metadata *meta, void **out_buffer,
1412                 uint32_t * out_size)
1413 {
1414         struct membuffer *buf;
1415         uint32_t ilst_size;
1416         void *ilst_buffer;
1417
1418         if (!create_ilst(meta, &ilst_buffer, &ilst_size))
1419                 return 0;
1420
1421         buf = membuffer_create();
1422
1423         membuffer_write_int32(buf, 0);
1424         membuffer_write_atom(buf, "ilst", ilst_size, ilst_buffer);
1425         free(ilst_buffer);
1426
1427         *out_size = membuffer_get_size(buf);
1428         *out_buffer = membuffer_detach(buf);
1429         return 1;
1430 }
1431
1432 static uint32_t create_udta(const struct mp4_metadata *meta, void **out_buffer,
1433 uint32_t * out_size)
1434 {
1435         struct membuffer *buf;
1436         uint32_t meta_size;
1437         void *meta_buffer;
1438
1439         if (!create_meta(meta, &meta_buffer, &meta_size))
1440                 return 0;
1441
1442         buf = membuffer_create();
1443
1444         membuffer_write_atom(buf, "meta", meta_size, meta_buffer);
1445
1446         free(meta_buffer);
1447
1448         *out_size = membuffer_get_size(buf);
1449         *out_buffer = membuffer_detach(buf);
1450         return 1;
1451 }
1452
1453 static uint32_t fix_byte_order_32(uint32_t src)
1454 {
1455         return read_u32_be(&src);
1456 }
1457
1458 static void *modify_moov(struct mp4 *f, uint32_t *out_size)
1459 {
1460         int ret;
1461         uint64_t total_base = f->moov_offset + 8;
1462         uint32_t total_size = (uint32_t) (f->moov_size - 8);
1463         uint64_t udta_offset, meta_offset, ilst_offset;
1464         uint32_t udta_size, meta_size, ilst_size;
1465         uint32_t new_ilst_size;
1466         void *new_ilst_buffer, *out_buffer;
1467         uint8_t *p_out;
1468         int32_t size_delta;
1469         uint32_t tmp;
1470
1471         ret = find_atom_v2(f, total_base, total_size, "udta", 0, "meta");
1472         if (ret <= 0)
1473                 return NULL;
1474         if (ret == 2) {
1475                 struct membuffer *buf;
1476                 void *new_udta_buffer;
1477                 uint32_t new_udta_size;
1478                 if (!create_udta(&f->meta, &new_udta_buffer, &new_udta_size))
1479                         return NULL;
1480
1481                 buf = membuffer_create();
1482                 set_position(f, total_base);
1483                 if (!membuffer_transfer_from_file(buf, f, total_size)) {
1484                         free(new_udta_buffer);
1485                         return NULL;
1486                 }
1487                 membuffer_write_atom(buf, "udta", new_udta_size,
1488                         new_udta_buffer);
1489
1490                 free(new_udta_buffer);
1491
1492                 *out_size = membuffer_get_size(buf);
1493                 return membuffer_detach(buf);
1494         }
1495         udta_offset = get_position(f);
1496         ret = read_int32(f, &udta_size);
1497         if (ret <= 0)
1498                 return NULL;
1499         ret = find_atom_v2(f, udta_offset + 8, udta_size - 8, "meta", 4, "ilst");
1500         if (ret <= 0)
1501                 return NULL;
1502         if (ret == 2) {
1503                 struct membuffer *buf;
1504                 void *new_meta_buffer;
1505                 uint32_t new_meta_size;
1506
1507                 if (!create_meta(&f->meta, &new_meta_buffer, &new_meta_size))
1508                         return NULL;
1509
1510                 buf = membuffer_create();
1511                 set_position(f, total_base);
1512                 if (!membuffer_transfer_from_file(buf, f,
1513                                 udta_offset - total_base)) {
1514                         free(new_meta_buffer);
1515                         return NULL;
1516                 }
1517
1518                 membuffer_write_int32(buf, udta_size + 8 + new_meta_size);
1519                 membuffer_write_atom_name(buf, "udta");
1520                 if (!membuffer_transfer_from_file(buf, f, udta_size)) {
1521                         free(new_meta_buffer);
1522                         return NULL;
1523                 }
1524                 membuffer_write_atom(buf, "meta", new_meta_size,
1525                         new_meta_buffer);
1526                 free(new_meta_buffer);
1527
1528                 *out_size = membuffer_get_size(buf);
1529                 return membuffer_detach(buf);
1530         }
1531         meta_offset = get_position(f);
1532         ret = read_int32(f, &meta_size);
1533         if (ret <= 0)
1534                 return NULL;
1535         /* shouldn't happen, find_atom_v2 above takes care of it */
1536         if (!find_atom(f, meta_offset + 12, meta_size - 12, "ilst"))
1537                 return NULL;
1538         ilst_offset = get_position(f);
1539         ret = read_int32(f, &ilst_size);
1540         if (ret <= 0)
1541                 return NULL;
1542         if (!create_ilst(&f->meta, &new_ilst_buffer, &new_ilst_size))
1543                 return NULL;
1544         size_delta = new_ilst_size - (ilst_size - 8);
1545         *out_size = total_size + size_delta;
1546         out_buffer = para_malloc(*out_size);
1547         p_out = out_buffer;
1548         set_position(f, total_base);
1549         ret = read_data(f, p_out, udta_offset - total_base);
1550         if (ret <= 0)
1551                 return NULL;
1552         p_out += (uint32_t) (udta_offset - total_base);
1553         ret = read_int32(f, &tmp);
1554         if (ret <= 0)
1555                 return NULL;
1556         *(uint32_t *)p_out = fix_byte_order_32(tmp + size_delta);
1557         p_out += 4;
1558         ret = read_data(f, p_out, 4);
1559         if (ret <= 0)
1560                 return NULL;
1561         p_out += 4;
1562         ret = read_data(f, p_out, meta_offset - udta_offset - 8);
1563         if (ret <= 0)
1564                 return NULL;
1565         p_out += (uint32_t) (meta_offset - udta_offset - 8);
1566         ret = read_int32(f, &tmp);
1567         if (ret <= 0)
1568                 return NULL;
1569         *(uint32_t *)p_out = fix_byte_order_32(tmp + size_delta);
1570         p_out += 4;
1571         ret = read_data(f, p_out, 4);
1572         if (ret <= 0)
1573                 return NULL;
1574         p_out += 4;
1575         ret = read_data(f, p_out, ilst_offset - meta_offset - 8);
1576         if (ret <= 0)
1577                 return NULL;
1578         p_out += (uint32_t) (ilst_offset - meta_offset - 8);
1579         ret = read_int32(f, &tmp);
1580         if (ret <= 0)
1581                 return NULL;
1582         *(uint32_t *)p_out = fix_byte_order_32(tmp + size_delta);
1583         p_out += 4;
1584         ret = read_data(f, p_out, 4);
1585         if (ret <= 0)
1586                 return NULL;
1587         p_out += 4;
1588         memcpy(p_out, new_ilst_buffer, new_ilst_size);
1589         p_out += new_ilst_size;
1590         set_position(f, ilst_offset + ilst_size);
1591         ret = read_data(f, p_out, total_size
1592                 - (ilst_offset - total_base) - ilst_size);
1593         if (ret <= 0)
1594                 return NULL;
1595         free(new_ilst_buffer);
1596         return out_buffer;
1597 }
1598
1599 static int32_t write_data(struct mp4 *f, void *data, uint32_t size)
1600 {
1601         int32_t result = 1;
1602
1603         result = f->cb->write(f->cb->user_data, data, size);
1604
1605         f->current_position += size;
1606
1607         return result;
1608 }
1609
1610 static int32_t write_int32(struct mp4 *f, uint32_t data)
1611 {
1612         int8_t temp[4];
1613         write_u32_be(temp, data);
1614         return write_data(f, temp, sizeof(temp));
1615 }
1616
1617 int32_t mp4_meta_update(struct mp4 *f)
1618 {
1619         void *new_moov_data;
1620         uint32_t new_moov_size;
1621
1622         set_position(f, 0);
1623         new_moov_data = modify_moov(f, &new_moov_size);
1624         if (!new_moov_data ) {
1625                 mp4_close(f);
1626                 return 0;
1627         }
1628         /* copy moov atom to end of the file */
1629         if (f->last_atom != ATOM_MOOV) {
1630                 char *free_data = "free";
1631
1632                 /* rename old moov to free */
1633                 set_position(f, f->moov_offset + 4);
1634                 write_data(f, free_data, 4);
1635
1636                 set_position(f, f->file_size);
1637                 write_int32(f, new_moov_size + 8);
1638                 write_data(f, "moov", 4);
1639                 write_data(f, new_moov_data, new_moov_size);
1640         } else {
1641                 set_position(f, f->moov_offset);
1642                 write_int32(f, new_moov_size + 8);
1643                 write_data(f, "moov", 4);
1644                 write_data(f, new_moov_data, new_moov_size);
1645         }
1646         free(new_moov_data);
1647         f->cb->truncate(f->cb->user_data);
1648         return 1;
1649 }
1650
1651 static char *meta_find_by_name(const struct mp4 *f, const char *item)
1652 {
1653         uint32_t i;
1654
1655         for (i = 0; i < f->meta.count; i++)
1656                 if (!strcasecmp(f->meta.tags[i].item, item))
1657                         return para_strdup(f->meta.tags[i].value);
1658         return NULL;
1659 }
1660
1661 /**
1662  * Return the value of the artist meta tag of an mp4 file.
1663  *
1664  * \param f Must not be NULL.
1665  *
1666  * \return If the file does not contain this metadata tag, the function returns
1667  * NULL. Otherwise, a copy of the tag value is returned. The caller should free
1668  * this memory when it is no longer needed.
1669  */
1670 char *mp4_meta_get_artist(const struct mp4 *f)
1671 {
1672         return meta_find_by_name(f, "artist");
1673 }
1674
1675 /**
1676  * Return the value of the title meta tag of an mp4 file.
1677  *
1678  * \param f See \ref mp4_meta_get_artist().
1679  * \return See \ref mp4_meta_get_artist().
1680  */
1681 char *mp4_meta_get_title(const struct mp4 *f)
1682 {
1683         return meta_find_by_name(f, "title");
1684 }
1685
1686 /**
1687  * Return the value of the date meta tag of an mp4 file.
1688  *
1689  * \param f See \ref mp4_meta_get_artist().
1690  * \return See \ref mp4_meta_get_artist().
1691  */
1692 char *mp4_meta_get_date(const struct mp4 *f)
1693 {
1694         return meta_find_by_name(f, "date");
1695 }
1696
1697 /**
1698  * Return the value of the album meta tag of an mp4 file.
1699  *
1700  * \param f See \ref mp4_meta_get_artist().
1701  * \return See \ref mp4_meta_get_artist().
1702  */
1703 char *mp4_meta_get_album(const struct mp4 *f)
1704 {
1705         return meta_find_by_name(f, "album");
1706 }
1707
1708 /**
1709  * Return the value of the comment meta tag of an mp4 file.
1710  *
1711  * \param f See \ref mp4_meta_get_artist().
1712  * \return See \ref mp4_meta_get_artist().
1713  */
1714 char *mp4_meta_get_comment(const struct mp4 *f)
1715 {
1716         return meta_find_by_name(f, "comment");
1717 }