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