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