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