]> git.tuebingen.mpg.de Git - paraslash.git/blob - mp4.c
mp4: Merge sample_to_offset() into mp4_set_sample_position().
[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 *p_track = f->track[track];
1050
1051         if (p_track->stsz_sample_size) {
1052                 return (sample - chunk_sample) * p_track->stsz_sample_size;
1053         } else {
1054                 if (sample >= p_track->stsz_sample_count)
1055                         return 0;       //error
1056
1057                 for (i = chunk_sample, total = 0; i < sample; i++) {
1058                         total += p_track->stsz_table[i];
1059                 }
1060         }
1061
1062         return total;
1063 }
1064
1065 /**
1066  * Return the number of milliseconds of the given track.
1067  *
1068  * \param f As returned by \ref mp4_open_read(), must not be NULL.
1069  * \param track Between zero and the value returned by \ref mp4_get_total_tracks().
1070  *
1071  * The function returns zero if the audio file is of zero length or contains a
1072  * corrupt track header.
1073  */
1074 uint64_t mp4_get_duration(const struct mp4 *f, int32_t track)
1075 {
1076         const struct mp4_track *t = f->track[track];
1077
1078         if (t->timeScale == 0)
1079                 return 0;
1080         return t->duration * 1000 / t->timeScale;
1081 }
1082
1083 int32_t mp4_get_total_tracks(const struct mp4 *f)
1084 {
1085         return f->total_tracks;
1086 }
1087
1088 /**
1089  * Check whether the given track number corresponds to an audio track.
1090  *
1091  * \param f See \ref mp4_get_duration().
1092  * \param track See \ref mp4_get_duration().
1093  *
1094  * Besides audio tracks, an mp4 file may contain video and system tracks. For
1095  * those the function returns false.
1096  */
1097 bool mp4_is_audio_track(const struct mp4 *f, int32_t track)
1098 {
1099         return f->track[track]->is_audio;
1100 }
1101
1102 void mp4_set_sample_position(struct mp4 *f, int32_t track, int32_t sample)
1103 {
1104         int32_t offset, chunk, chunk_sample;
1105
1106         chunk_of_sample(f, track, sample, &chunk_sample, &chunk);
1107         offset = chunk_to_offset(f, track, chunk)
1108                 + sample_range_size(f, track, chunk_sample, sample);
1109         set_position(f, offset);
1110 }
1111
1112 int32_t mp4_get_sample_size(const struct mp4 *f, int track, int sample)
1113 {
1114         const struct mp4_track *t = f->track[track];
1115
1116         if (t->stsz_sample_size != 0)
1117                 return t->stsz_sample_size;
1118         return t->stsz_table[sample];
1119 }
1120
1121 uint32_t mp4_get_sample_rate(const struct mp4 *f, int32_t track)
1122 {
1123         return f->track[track]->sampleRate;
1124 }
1125
1126 uint32_t mp4_get_channel_count(const struct mp4 *f, int32_t track)
1127 {
1128         return f->track[track]->channelCount;
1129 }
1130
1131 int32_t mp4_num_samples(const struct mp4 *f, int32_t track)
1132 {
1133         int32_t i;
1134         int32_t total = 0;
1135
1136         for (i = 0; i < f->track[track]->stts_entry_count; i++) {
1137                 total += f->track[track]->stts_sample_count[i];
1138         }
1139         return total;
1140 }
1141
1142 struct mp4 *mp4_open_meta(const struct mp4_callback *cb)
1143 {
1144         int ret;
1145         struct mp4 *f = para_calloc(sizeof(struct mp4));
1146
1147         f->cb = cb;
1148         ret = parse_atoms(f, 1);
1149         if (ret < 0) {
1150                 free(f);
1151                 return NULL;
1152         }
1153         return f;
1154 }
1155
1156 /**
1157  * Return the metadata of an mp4 file.
1158  *
1159  * \param f As returned by either \ref mp4_open_read() or \ref mp4_open_meta().
1160  *
1161  * The caller is allowed to add, delete or modify the entries of the returned
1162  * structure in order to pass the modified version to \ref mp4_meta_update().
1163  */
1164 struct mp4_metadata *mp4_get_meta(struct mp4 *f)
1165 {
1166         return &f->meta;
1167 }
1168
1169 static int find_atom(struct mp4 *f, uint64_t base, uint32_t size,
1170         const char *name)
1171 {
1172         uint32_t remaining = size;
1173         uint64_t atom_offset = base;
1174
1175         for (;;) {
1176                 int ret;
1177                 char atom_name[4];
1178                 uint32_t atom_size;
1179
1180                 set_position(f, atom_offset);
1181
1182                 if (remaining < 8)
1183                         return -1;
1184                 ret = read_int32(f, &atom_size);
1185                 if (ret <= 0)
1186                         return ret;
1187                 if (atom_size > remaining || atom_size < 8)
1188                         return -1;
1189                 ret = read_data(f, atom_name, 4);
1190                 if (ret <= 0)
1191                         return ret;
1192                 if (!memcmp(atom_name, name, 4)) {
1193                         set_position(f, atom_offset);
1194                         return 1;
1195                 }
1196                 remaining -= atom_size;
1197                 atom_offset += atom_size;
1198         }
1199 }
1200
1201 /*
1202  * Try to find atom <name> with atom <name_inside> in it. Besides -1/0/1 for
1203  * error, EOF and success, this function may return 2 to indicate that the
1204  * desired atoms were not found.
1205  */
1206 static int find_atom_v2(struct mp4 *f, uint64_t base, uint32_t size,
1207                 const char *name, uint32_t extraheaders, const char *name_inside)
1208 {
1209         uint64_t first_base = (uint64_t) (-1);
1210
1211         for (;;) {
1212                 uint64_t mybase;
1213                 uint32_t mysize;
1214                 int ret = find_atom(f, base, size, name);
1215
1216                 if (ret <= 0)
1217                         return ret;
1218                 mybase = get_position(f);
1219                 ret = read_int32(f, &mysize);
1220                 if (ret <= 0)
1221                         return ret;
1222                 if (first_base == (uint64_t) (-1))
1223                         first_base = mybase;
1224
1225                 if (mysize < 8 + extraheaders)
1226                         break;
1227
1228                 if (find_atom (f, mybase + (8 + extraheaders),
1229                                 mysize - (8 + extraheaders), name_inside)) {
1230                         set_position(f, mybase);
1231                         return 1;
1232                 }
1233                 base += mysize;
1234                 if (size <= mysize)
1235                         break;
1236                 size -= mysize;
1237         }
1238         if (first_base != (uint64_t)(-1)) {
1239                 set_position(f, first_base);
1240                 return 1;
1241         }
1242         /* wanted atom inside not found */
1243         return 2;
1244 }
1245
1246 struct membuffer {
1247         void *data;
1248         unsigned written;
1249         unsigned allocated;
1250 };
1251
1252 static struct membuffer *membuffer_create(void)
1253 {
1254         struct membuffer *buf = para_calloc(sizeof(*buf));
1255
1256         buf->allocated = 256;
1257         buf->data = para_malloc(buf->allocated);
1258         return buf;
1259 }
1260
1261 static void membuffer_write(struct membuffer *buf, const void *ptr,
1262                 unsigned bytes)
1263 {
1264         unsigned dest_size = buf->written + bytes;
1265
1266         if (dest_size > buf->allocated) {
1267                 do {
1268                         buf->allocated <<= 1;
1269                 } while (dest_size > buf->allocated);
1270                 buf->data = para_realloc(buf->data, buf->allocated);
1271         }
1272
1273         if (ptr)
1274                 memcpy((char *) buf->data + buf->written, ptr, bytes);
1275         buf->written += bytes;
1276 }
1277
1278 static void membuffer_write_atom_name(struct membuffer *buf, const char *data)
1279 {
1280         membuffer_write(buf, data, 4);
1281 }
1282
1283 static void membuffer_write_int32(struct membuffer *buf, uint32_t data)
1284 {
1285         uint8_t temp[4];
1286         write_u32_be(temp, data);
1287         membuffer_write(buf, temp, 4);
1288 }
1289
1290 static void membuffer_write_std_tag(struct membuffer *buf, const char *name,
1291                 const char *value)
1292 {
1293         uint32_t len = strlen(value);
1294         membuffer_write_int32(buf, 8 /* atom header */
1295                 + 8 /* data atom header */
1296                 + 8 /* flags + reserved */
1297                 + len);
1298         membuffer_write_atom_name(buf, name);
1299         membuffer_write_int32(buf, 8 /* data atom header */
1300                 + 8 /* flags + reserved */
1301                 + len);
1302         membuffer_write_atom_name(buf, "data");
1303         membuffer_write_int32(buf, 1);  /* flags */
1304         membuffer_write_int32(buf, 0);  /* reserved */
1305         membuffer_write(buf, value, len);
1306 }
1307
1308 static unsigned membuffer_get_size(const struct membuffer *buf)
1309 {
1310         return buf->written;
1311 }
1312
1313 static void *membuffer_detach(struct membuffer *buf)
1314 {
1315         void *ret = para_realloc(buf->data, buf->written);
1316         free(buf);
1317         return ret;
1318 }
1319
1320 struct stdmeta_entry {
1321         const char *atom;
1322         const char *name;
1323 };
1324
1325 static const char *find_standard_meta(const char *name)
1326 {
1327         const struct stdmeta_entry stdmetas[] = {
1328                 {"\xA9" "nam", "title"},
1329                 {"\xA9" "ART", "artist"},
1330                 {"\xA9" "alb", "album"},
1331                 {"\xA9" "day", "date"},
1332                 {"\xA9" "cmt", "comment"},
1333         };
1334
1335         for (unsigned n = 0; n < ARRAY_SIZE(stdmetas); n++)
1336                 if (!strcasecmp(name, stdmetas[n].name))
1337                         return stdmetas[n].atom;
1338         return NULL;
1339 }
1340
1341 static uint32_t create_ilst(const struct mp4_metadata *meta, void **out_buffer,
1342                 uint32_t * out_size)
1343 {
1344         struct membuffer *buf = membuffer_create();
1345         unsigned metaptr;
1346
1347         for (metaptr = 0; metaptr < meta->count; metaptr++) {
1348                 struct mp4_tag *tag = meta->tags + metaptr;
1349                 const char *std_meta_atom = find_standard_meta(tag->item);
1350                 if (std_meta_atom)
1351                         membuffer_write_std_tag(buf, std_meta_atom, tag->value);
1352                 else
1353                         PARA_ERROR_LOG("invalid tag item: %s\n", tag->item);
1354         }
1355         *out_size = membuffer_get_size(buf);
1356         *out_buffer = membuffer_detach(buf);
1357         return 1;
1358 }
1359
1360 static void membuffer_write_atom(struct membuffer *buf, const char *name, unsigned size,
1361                           const void *data)
1362 {
1363         membuffer_write_int32(buf, size + 8);
1364         membuffer_write_atom_name(buf, name);
1365         membuffer_write(buf, data, size);
1366 }
1367
1368 static void *membuffer_get_ptr(const struct membuffer *buf)
1369 {
1370         return buf->data;
1371 }
1372
1373 static bool membuffer_transfer_from_file(struct membuffer *buf, struct mp4 *src,
1374                 unsigned bytes)
1375 {
1376         unsigned oldsize = membuffer_get_size(buf);
1377         char *bufptr;
1378
1379         membuffer_write(buf, 0, bytes);
1380         bufptr = membuffer_get_ptr(buf);
1381         if (read_data(src, bufptr + oldsize, bytes) != 1) {
1382                 free(buf->data);
1383                 free(buf);
1384                 return false;
1385         }
1386         return true;
1387 }
1388
1389 static uint32_t create_meta(const struct mp4_metadata *meta, void **out_buffer,
1390                 uint32_t * out_size)
1391 {
1392         struct membuffer *buf;
1393         uint32_t ilst_size;
1394         void *ilst_buffer;
1395
1396         if (!create_ilst(meta, &ilst_buffer, &ilst_size))
1397                 return 0;
1398
1399         buf = membuffer_create();
1400
1401         membuffer_write_int32(buf, 0);
1402         membuffer_write_atom(buf, "ilst", ilst_size, ilst_buffer);
1403         free(ilst_buffer);
1404
1405         *out_size = membuffer_get_size(buf);
1406         *out_buffer = membuffer_detach(buf);
1407         return 1;
1408 }
1409
1410 static uint32_t create_udta(const struct mp4_metadata *meta, void **out_buffer,
1411 uint32_t * out_size)
1412 {
1413         struct membuffer *buf;
1414         uint32_t meta_size;
1415         void *meta_buffer;
1416
1417         if (!create_meta(meta, &meta_buffer, &meta_size))
1418                 return 0;
1419
1420         buf = membuffer_create();
1421
1422         membuffer_write_atom(buf, "meta", meta_size, meta_buffer);
1423
1424         free(meta_buffer);
1425
1426         *out_size = membuffer_get_size(buf);
1427         *out_buffer = membuffer_detach(buf);
1428         return 1;
1429 }
1430
1431 static uint32_t fix_byte_order_32(uint32_t src)
1432 {
1433         return read_u32_be(&src);
1434 }
1435
1436 static void *modify_moov(struct mp4 *f, uint32_t *out_size)
1437 {
1438         int ret;
1439         uint64_t total_base = f->moov_offset + 8;
1440         uint32_t total_size = (uint32_t) (f->moov_size - 8);
1441         uint64_t udta_offset, meta_offset, ilst_offset;
1442         uint32_t udta_size, meta_size, ilst_size;
1443         uint32_t new_ilst_size;
1444         void *new_ilst_buffer, *out_buffer;
1445         uint8_t *p_out;
1446         int32_t size_delta;
1447         uint32_t tmp;
1448
1449         ret = find_atom_v2(f, total_base, total_size, "udta", 0, "meta");
1450         if (ret <= 0)
1451                 return NULL;
1452         if (ret == 2) {
1453                 struct membuffer *buf;
1454                 void *new_udta_buffer;
1455                 uint32_t new_udta_size;
1456                 if (!create_udta(&f->meta, &new_udta_buffer, &new_udta_size))
1457                         return NULL;
1458
1459                 buf = membuffer_create();
1460                 set_position(f, total_base);
1461                 if (!membuffer_transfer_from_file(buf, f, total_size)) {
1462                         free(new_udta_buffer);
1463                         return NULL;
1464                 }
1465                 membuffer_write_atom(buf, "udta", new_udta_size,
1466                         new_udta_buffer);
1467
1468                 free(new_udta_buffer);
1469
1470                 *out_size = membuffer_get_size(buf);
1471                 return membuffer_detach(buf);
1472         }
1473         udta_offset = get_position(f);
1474         ret = read_int32(f, &udta_size);
1475         if (ret <= 0)
1476                 return NULL;
1477         ret = find_atom_v2(f, udta_offset + 8, udta_size - 8, "meta", 4, "ilst");
1478         if (ret <= 0)
1479                 return NULL;
1480         if (ret == 2) {
1481                 struct membuffer *buf;
1482                 void *new_meta_buffer;
1483                 uint32_t new_meta_size;
1484
1485                 if (!create_meta(&f->meta, &new_meta_buffer, &new_meta_size))
1486                         return NULL;
1487
1488                 buf = membuffer_create();
1489                 set_position(f, total_base);
1490                 if (!membuffer_transfer_from_file(buf, f,
1491                                 udta_offset - total_base)) {
1492                         free(new_meta_buffer);
1493                         return NULL;
1494                 }
1495
1496                 membuffer_write_int32(buf, udta_size + 8 + new_meta_size);
1497                 membuffer_write_atom_name(buf, "udta");
1498                 if (!membuffer_transfer_from_file(buf, f, udta_size)) {
1499                         free(new_meta_buffer);
1500                         return NULL;
1501                 }
1502                 membuffer_write_atom(buf, "meta", new_meta_size,
1503                         new_meta_buffer);
1504                 free(new_meta_buffer);
1505
1506                 *out_size = membuffer_get_size(buf);
1507                 return membuffer_detach(buf);
1508         }
1509         meta_offset = get_position(f);
1510         ret = read_int32(f, &meta_size);
1511         if (ret <= 0)
1512                 return NULL;
1513         /* shouldn't happen, find_atom_v2 above takes care of it */
1514         if (!find_atom(f, meta_offset + 12, meta_size - 12, "ilst"))
1515                 return NULL;
1516         ilst_offset = get_position(f);
1517         ret = read_int32(f, &ilst_size);
1518         if (ret <= 0)
1519                 return NULL;
1520         if (!create_ilst(&f->meta, &new_ilst_buffer, &new_ilst_size))
1521                 return NULL;
1522         size_delta = new_ilst_size - (ilst_size - 8);
1523         *out_size = total_size + size_delta;
1524         out_buffer = para_malloc(*out_size);
1525         p_out = out_buffer;
1526         set_position(f, total_base);
1527         ret = read_data(f, p_out, udta_offset - total_base);
1528         if (ret <= 0)
1529                 return NULL;
1530         p_out += (uint32_t) (udta_offset - total_base);
1531         ret = read_int32(f, &tmp);
1532         if (ret <= 0)
1533                 return NULL;
1534         *(uint32_t *)p_out = fix_byte_order_32(tmp + size_delta);
1535         p_out += 4;
1536         ret = read_data(f, p_out, 4);
1537         if (ret <= 0)
1538                 return NULL;
1539         p_out += 4;
1540         ret = read_data(f, p_out, meta_offset - udta_offset - 8);
1541         if (ret <= 0)
1542                 return NULL;
1543         p_out += (uint32_t) (meta_offset - udta_offset - 8);
1544         ret = read_int32(f, &tmp);
1545         if (ret <= 0)
1546                 return NULL;
1547         *(uint32_t *)p_out = fix_byte_order_32(tmp + size_delta);
1548         p_out += 4;
1549         ret = read_data(f, p_out, 4);
1550         if (ret <= 0)
1551                 return NULL;
1552         p_out += 4;
1553         ret = read_data(f, p_out, ilst_offset - meta_offset - 8);
1554         if (ret <= 0)
1555                 return NULL;
1556         p_out += (uint32_t) (ilst_offset - meta_offset - 8);
1557         ret = read_int32(f, &tmp);
1558         if (ret <= 0)
1559                 return NULL;
1560         *(uint32_t *)p_out = fix_byte_order_32(tmp + size_delta);
1561         p_out += 4;
1562         ret = read_data(f, p_out, 4);
1563         if (ret <= 0)
1564                 return NULL;
1565         p_out += 4;
1566         memcpy(p_out, new_ilst_buffer, new_ilst_size);
1567         p_out += new_ilst_size;
1568         set_position(f, ilst_offset + ilst_size);
1569         ret = read_data(f, p_out, total_size
1570                 - (ilst_offset - total_base) - ilst_size);
1571         if (ret <= 0)
1572                 return NULL;
1573         free(new_ilst_buffer);
1574         return out_buffer;
1575 }
1576
1577 static int32_t write_data(struct mp4 *f, void *data, uint32_t size)
1578 {
1579         int32_t result = 1;
1580
1581         result = f->cb->write(f->cb->user_data, data, size);
1582
1583         f->current_position += size;
1584
1585         return result;
1586 }
1587
1588 static int32_t write_int32(struct mp4 *f, uint32_t data)
1589 {
1590         int8_t temp[4];
1591         write_u32_be(temp, data);
1592         return write_data(f, temp, sizeof(temp));
1593 }
1594
1595 int32_t mp4_meta_update(struct mp4 *f)
1596 {
1597         void *new_moov_data;
1598         uint32_t new_moov_size;
1599
1600         set_position(f, 0);
1601         new_moov_data = modify_moov(f, &new_moov_size);
1602         if (!new_moov_data ) {
1603                 mp4_close(f);
1604                 return 0;
1605         }
1606         /* copy moov atom to end of the file */
1607         if (f->last_atom != ATOM_MOOV) {
1608                 char *free_data = "free";
1609
1610                 /* rename old moov to free */
1611                 set_position(f, f->moov_offset + 4);
1612                 write_data(f, free_data, 4);
1613
1614                 set_position(f, f->file_size);
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         } else {
1619                 set_position(f, f->moov_offset);
1620                 write_int32(f, new_moov_size + 8);
1621                 write_data(f, "moov", 4);
1622                 write_data(f, new_moov_data, new_moov_size);
1623         }
1624         free(new_moov_data);
1625         f->cb->truncate(f->cb->user_data);
1626         return 1;
1627 }
1628
1629 static char *meta_find_by_name(const struct mp4 *f, const char *item)
1630 {
1631         uint32_t i;
1632
1633         for (i = 0; i < f->meta.count; i++)
1634                 if (!strcasecmp(f->meta.tags[i].item, item))
1635                         return para_strdup(f->meta.tags[i].value);
1636         return NULL;
1637 }
1638
1639 /**
1640  * Return the value of the artist meta tag of an mp4 file.
1641  *
1642  * \param f Must not be NULL.
1643  *
1644  * \return If the file does not contain this metadata tag, the function returns
1645  * NULL. Otherwise, a copy of the tag value is returned. The caller should free
1646  * this memory when it is no longer needed.
1647  */
1648 char *mp4_meta_get_artist(const struct mp4 *f)
1649 {
1650         return meta_find_by_name(f, "artist");
1651 }
1652
1653 /**
1654  * Return the value of the title meta tag of an mp4 file.
1655  *
1656  * \param f See \ref mp4_meta_get_artist().
1657  * \return See \ref mp4_meta_get_artist().
1658  */
1659 char *mp4_meta_get_title(const struct mp4 *f)
1660 {
1661         return meta_find_by_name(f, "title");
1662 }
1663
1664 /**
1665  * Return the value of the date meta tag of an mp4 file.
1666  *
1667  * \param f See \ref mp4_meta_get_artist().
1668  * \return See \ref mp4_meta_get_artist().
1669  */
1670 char *mp4_meta_get_date(const struct mp4 *f)
1671 {
1672         return meta_find_by_name(f, "date");
1673 }
1674
1675 /**
1676  * Return the value of the album meta tag of an mp4 file.
1677  *
1678  * \param f See \ref mp4_meta_get_artist().
1679  * \return See \ref mp4_meta_get_artist().
1680  */
1681 char *mp4_meta_get_album(const struct mp4 *f)
1682 {
1683         return meta_find_by_name(f, "album");
1684 }
1685
1686 /**
1687  * Return the value of the comment meta tag of an mp4 file.
1688  *
1689  * \param f See \ref mp4_meta_get_artist().
1690  * \return See \ref mp4_meta_get_artist().
1691  */
1692 char *mp4_meta_get_comment(const struct mp4 *f)
1693 {
1694         return meta_find_by_name(f, "comment");
1695 }