]> git.tuebingen.mpg.de Git - paraslash.git/blob - mp4.c
mp4: Provide return value for 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 "error.h"
12 #include "portable_io.h"
13 #include "string.h"
14 #include "mp4.h"
15
16 struct mp4_track {
17         bool is_audio;
18         uint16_t channelCount;
19         uint16_t sampleRate;
20
21         /* stsz */
22         uint32_t stsz_sample_size;
23         uint32_t stsz_sample_count;
24         uint32_t *stsz_table;
25
26         /* stts */
27         uint32_t stts_entry_count;
28         uint32_t *stts_sample_count;
29         uint32_t *stts_sample_delta;
30
31         /* stsc */
32         uint32_t stsc_entry_count;
33         uint32_t *stsc_first_chunk;
34         uint32_t *stsc_samples_per_chunk;
35         uint32_t *stsc_sample_desc_index;
36
37         /* stsc */
38         uint32_t stco_entry_count;
39         uint32_t *stco_chunk_offset;
40
41         uint32_t timeScale;
42         uint64_t duration;
43 };
44
45 #define MAX_TRACKS 1024
46
47 struct mp4 {
48         const struct mp4_callback *cb;
49         int64_t current_position;
50
51         uint64_t moov_offset;
52         uint64_t moov_size;
53         uint8_t last_atom;
54         uint64_t file_size;
55
56         /* incremental track index while reading the file */
57         int32_t total_tracks;
58         /* track data */
59         struct mp4_track *track[MAX_TRACKS];
60
61         /* metadata */
62         struct mp4_metadata meta;
63 };
64
65 /*
66  * Returns -1, 0, or 1 on errors/EOF/success. Partial reads followed by EOF or
67  * read errors are treated as errors.
68  */
69 static int read_data(struct mp4 *f, void *data, size_t size)
70 {
71         while (size > 0) {
72                 ssize_t ret = f->cb->read(f->cb->user_data, data, size);
73                 if (ret < 0 && errno == EINTR)
74                         continue;
75                 /* regard EAGAIN as an error as reads should be blocking. */
76                 if (ret <= 0)
77                         return ret < 0? -1 : 0;
78                 f->current_position += ret;
79                 size -= ret;
80         }
81         return 1;
82 }
83
84 static int read_int64(struct mp4 *f, uint64_t *result)
85 {
86         uint8_t data[8];
87         int ret = read_data(f, data, 8);
88
89         if (ret > 0 && result)
90                 *result = read_u64_be(data);
91         return ret;
92 }
93
94 static int read_int32(struct mp4 *f, uint32_t *result)
95 {
96         uint8_t data[4];
97         int ret = read_data(f, data, 4);
98
99         if (ret > 0 && result)
100                 *result = read_u32_be(data);
101         return ret;
102 }
103
104 static int read_int24(struct mp4 *f, uint32_t *result)
105 {
106         uint8_t data[3];
107         int ret = read_data(f, data, 3);
108
109         if (ret > 0 && result)
110                 *result = read_u24_be(data);
111         return ret;
112 }
113
114 static int read_int16(struct mp4 *f, uint16_t *result)
115 {
116         uint8_t data[2];
117         int ret = read_data(f, data, 2);
118
119         if (ret > 0 && result)
120                 *result = read_u16_be(data);
121         return ret;
122 }
123
124 static uint8_t read_int8(struct mp4 *f, uint8_t *result)
125 {
126         uint8_t data[1];
127         int ret = read_data(f, data, 1);
128
129         if (ret > 0 && result)
130                 *result = data[0];
131         return ret;
132 }
133
134 static bool atom_compare(int8_t a1, int8_t b1, int8_t c1, int8_t d1,
135                 int8_t a2, int8_t b2, int8_t c2, int8_t d2)
136 {
137         return a1 == a2 && b1 == b2 && c1 == c2 && d1 == d2;
138 }
139
140 enum atoms {
141         /* atoms with subatoms */
142         ATOM_MOOV = 1,
143         ATOM_TRAK = 2,
144         ATOM_EDTS = 3,
145         ATOM_MDIA = 4,
146         ATOM_MINF = 5,
147         ATOM_STBL = 6,
148         ATOM_UDTA = 7,
149         ATOM_ILST = 8, /* iTunes Metadata list */
150         ATOM_TITLE = 9,
151         ATOM_ARTIST = 10,
152         ATOM_WRITER = 11,
153         ATOM_ALBUM = 12,
154         ATOM_DATE = 13,
155         ATOM_TOOL = 14,
156         ATOM_COMMENT = 15,
157         ATOM_GENRE1 = 16,
158         ATOM_TRACK = 17,
159         ATOM_DISC = 18,
160         ATOM_COMPILATION = 19,
161         ATOM_GENRE2 = 20,
162         ATOM_TEMPO = 21,
163         ATOM_COVER = 22,
164         ATOM_DRMS = 23,
165         ATOM_SINF = 24,
166         ATOM_SCHI = 25,
167
168         SUBATOMIC = 128,
169
170         /* atoms without subatoms */
171         ATOM_FTYP = 129,
172         ATOM_MDAT = 130,
173         ATOM_MVHD = 131,
174         ATOM_TKHD = 132,
175         ATOM_TREF = 133,
176         ATOM_MDHD = 134, /* track header */
177         ATOM_VMHD = 135,
178         ATOM_SMHD = 136,
179         ATOM_HMHD = 137,
180         ATOM_STSD = 138, /* sample description box */
181         ATOM_STTS = 139, /* time to sample box */
182         ATOM_STSZ = 140, /* sample size box */
183         ATOM_STZ2 = 141,
184         ATOM_STCO = 142, /* chunk offset box */
185         ATOM_STSC = 143, /* sample to chunk box */
186         ATOM_MP4A = 144,
187         ATOM_MP4V = 145,
188         ATOM_MP4S = 146,
189         ATOM_ESDS = 147,
190         ATOM_META = 148, /* iTunes Metadata box */
191         ATOM_NAME = 149, /* iTunes Metadata name box */
192         ATOM_DATA = 150, /* iTunes Metadata data box */
193         ATOM_CTTS = 151,
194         ATOM_FRMA = 152,
195         ATOM_IVIV = 153,
196         ATOM_PRIV = 154,
197         ATOM_USER = 155,
198         ATOM_KEY = 156,
199         ATOM_ALBUM_ARTIST = 157,
200         ATOM_CONTENTGROUP = 158,
201         ATOM_LYRICS = 159,
202         ATOM_DESCRIPTION = 160,
203         ATOM_NETWORK = 161,
204         ATOM_SHOW = 162,
205         ATOM_EPISODENAME = 163,
206         ATOM_SORTTITLE = 164,
207         ATOM_SORTALBUM = 165,
208         ATOM_SORTARTIST = 166,
209         ATOM_SORTALBUMARTIST = 167,
210         ATOM_SORTWRITER = 168,
211         ATOM_SORTSHOW = 169,
212         ATOM_SEASON = 170,
213         ATOM_EPISODE = 171,
214         ATOM_PODCAST = 172,
215
216         ATOM_UNKNOWN = 255
217 };
218
219 #define ATOM_FREE ATOM_UNKNOWN
220 #define ATOM_SKIP ATOM_UNKNOWN
221
222 #define COPYRIGHT_SYMBOL ((int8_t)0xA9)
223
224 static uint8_t atom_name_to_type(int8_t a, int8_t b, int8_t c, int8_t d)
225 {
226         if (a == 'm') {
227                 if (atom_compare(a, b, c, d, 'm', 'o', 'o', 'v'))
228                         return ATOM_MOOV;
229                 else if (atom_compare(a, b, c, d, 'm', 'i', 'n', 'f'))
230                         return ATOM_MINF;
231                 else if (atom_compare(a, b, c, d, 'm', 'd', 'i', 'a'))
232                         return ATOM_MDIA;
233                 else if (atom_compare(a, b, c, d, 'm', 'd', 'a', 't'))
234                         return ATOM_MDAT;
235                 else if (atom_compare(a, b, c, d, 'm', 'd', 'h', 'd'))
236                         return ATOM_MDHD;
237                 else if (atom_compare(a, b, c, d, 'm', 'v', 'h', 'd'))
238                         return ATOM_MVHD;
239                 else if (atom_compare(a, b, c, d, 'm', 'p', '4', 'a'))
240                         return ATOM_MP4A;
241                 else if (atom_compare(a, b, c, d, 'm', 'p', '4', 'v'))
242                         return ATOM_MP4V;
243                 else if (atom_compare(a, b, c, d, 'm', 'p', '4', 's'))
244                         return ATOM_MP4S;
245                 else if (atom_compare(a, b, c, d, 'm', 'e', 't', 'a'))
246                         return ATOM_META;
247         } else if (a == 't') {
248                 if (atom_compare(a, b, c, d, 't', 'r', 'a', 'k'))
249                         return ATOM_TRAK;
250                 else if (atom_compare(a, b, c, d, 't', 'k', 'h', 'd'))
251                         return ATOM_TKHD;
252                 else if (atom_compare(a, b, c, d, 't', 'r', 'e', 'f'))
253                         return ATOM_TREF;
254                 else if (atom_compare(a, b, c, d, 't', 'r', 'k', 'n'))
255                         return ATOM_TRACK;
256                 else if (atom_compare(a, b, c, d, 't', 'm', 'p', 'o'))
257                         return ATOM_TEMPO;
258                 else if (atom_compare(a, b, c, d, 't', 'v', 'n', 'n'))
259                         return ATOM_NETWORK;
260                 else if (atom_compare(a, b, c, d, 't', 'v', 's', 'h'))
261                         return ATOM_SHOW;
262                 else if (atom_compare(a, b, c, d, 't', 'v', 'e', 'n'))
263                         return ATOM_EPISODENAME;
264                 else if (atom_compare(a, b, c, d, 't', 'v', 's', 'n'))
265                         return ATOM_SEASON;
266                 else if (atom_compare(a, b, c, d, 't', 'v', 'e', 's'))
267                         return ATOM_EPISODE;
268         } else if (a == 's') {
269                 if (atom_compare(a, b, c, d, 's', 't', 'b', 'l'))
270                         return ATOM_STBL;
271                 else if (atom_compare(a, b, c, d, 's', 'm', 'h', 'd'))
272                         return ATOM_SMHD;
273                 else if (atom_compare(a, b, c, d, 's', 't', 's', 'd'))
274                         return ATOM_STSD;
275                 else if (atom_compare(a, b, c, d, 's', 't', 't', 's'))
276                         return ATOM_STTS;
277                 else if (atom_compare(a, b, c, d, 's', 't', 'c', 'o'))
278                         return ATOM_STCO;
279                 else if (atom_compare(a, b, c, d, 's', 't', 's', 'c'))
280                         return ATOM_STSC;
281                 else if (atom_compare(a, b, c, d, 's', 't', 's', 'z'))
282                         return ATOM_STSZ;
283                 else if (atom_compare(a, b, c, d, 's', 't', 'z', '2'))
284                         return ATOM_STZ2;
285                 else if (atom_compare(a, b, c, d, 's', 'k', 'i', 'p'))
286                         return ATOM_SKIP;
287                 else if (atom_compare(a, b, c, d, 's', 'i', 'n', 'f'))
288                         return ATOM_SINF;
289                 else if (atom_compare(a, b, c, d, 's', 'c', 'h', 'i'))
290                         return ATOM_SCHI;
291                 else if (atom_compare(a, b, c, d, 's', 'o', 'n', 'm'))
292                         return ATOM_SORTTITLE;
293                 else if (atom_compare(a, b, c, d, 's', 'o', 'a', 'l'))
294                         return ATOM_SORTALBUM;
295                 else if (atom_compare(a, b, c, d, 's', 'o', 'a', 'r'))
296                         return ATOM_SORTARTIST;
297                 else if (atom_compare(a, b, c, d, 's', 'o', 'a', 'a'))
298                         return ATOM_SORTALBUMARTIST;
299                 else if (atom_compare(a, b, c, d, 's', 'o', 'c', 'o'))
300                         return ATOM_SORTWRITER;
301                 else if (atom_compare(a, b, c, d, 's', 'o', 's', 'n'))
302                         return ATOM_SORTSHOW;
303         } else if (a == COPYRIGHT_SYMBOL) {
304                 if (atom_compare(a, b, c, d, COPYRIGHT_SYMBOL, 'n', 'a', 'm'))
305                         return ATOM_TITLE;
306                 else if (atom_compare(a, b, c, d, COPYRIGHT_SYMBOL, 'A', 'R', 'T'))
307                         return ATOM_ARTIST;
308                 else if (atom_compare(a, b, c, d, COPYRIGHT_SYMBOL, 'w', 'r', 't'))
309                         return ATOM_WRITER;
310                 else if (atom_compare(a, b, c, d, COPYRIGHT_SYMBOL, 'a', 'l', 'b'))
311                         return ATOM_ALBUM;
312                 else if (atom_compare(a, b, c, d, COPYRIGHT_SYMBOL, 'd', 'a', 'y'))
313                         return ATOM_DATE;
314                 else if (atom_compare(a, b, c, d, COPYRIGHT_SYMBOL, 't', 'o', 'o'))
315                         return ATOM_TOOL;
316                 else if (atom_compare(a, b, c, d, COPYRIGHT_SYMBOL, 'c', 'm', 't'))
317                         return ATOM_COMMENT;
318                 else if (atom_compare(a, b, c, d, COPYRIGHT_SYMBOL, 'g', 'e', 'n'))
319                         return ATOM_GENRE1;
320                 else if (atom_compare(a, b, c, d, COPYRIGHT_SYMBOL, 'g', 'r', 'p'))
321                         return ATOM_CONTENTGROUP;
322                 else if (atom_compare(a, b, c, d, COPYRIGHT_SYMBOL, 'l', 'y', 'r'))
323                         return ATOM_LYRICS;
324         }
325
326         if (atom_compare(a, b, c, d, 'e', 'd', 't', 's'))
327                 return ATOM_EDTS;
328         else if (atom_compare(a, b, c, d, 'e', 's', 'd', 's'))
329                 return ATOM_ESDS;
330         else if (atom_compare(a, b, c, d, 'f', 't', 'y', 'p'))
331                 return ATOM_FTYP;
332         else if (atom_compare(a, b, c, d, 'f', 'r', 'e', 'e'))
333                 return ATOM_FREE;
334         else if (atom_compare(a, b, c, d, 'h', 'm', 'h', 'd'))
335                 return ATOM_HMHD;
336         else if (atom_compare(a, b, c, d, 'v', 'm', 'h', 'd'))
337                 return ATOM_VMHD;
338         else if (atom_compare(a, b, c, d, 'u', 'd', 't', 'a'))
339                 return ATOM_UDTA;
340         else if (atom_compare(a, b, c, d, 'i', 'l', 's', 't'))
341                 return ATOM_ILST;
342         else if (atom_compare(a, b, c, d, 'n', 'a', 'm', 'e'))
343                 return ATOM_NAME;
344         else if (atom_compare(a, b, c, d, 'd', 'a', 't', 'a'))
345                 return ATOM_DATA;
346         else if (atom_compare(a, b, c, d, 'd', 'i', 's', 'k'))
347                 return ATOM_DISC;
348         else if (atom_compare(a, b, c, d, 'g', 'n', 'r', 'e'))
349                 return ATOM_GENRE2;
350         else if (atom_compare(a, b, c, d, 'c', 'o', 'v', 'r'))
351                 return ATOM_COVER;
352         else if (atom_compare(a, b, c, d, 'c', 'p', 'i', 'l'))
353                 return ATOM_COMPILATION;
354         else if (atom_compare(a, b, c, d, 'c', 't', 't', 's'))
355                 return ATOM_CTTS;
356         else if (atom_compare(a, b, c, d, 'd', 'r', 'm', 's'))
357                 return ATOM_DRMS;
358         else if (atom_compare(a, b, c, d, 'f', 'r', 'm', 'a'))
359                 return ATOM_FRMA;
360         else if (atom_compare(a, b, c, d, 'p', 'r', 'i', 'v'))
361                 return ATOM_PRIV;
362         else if (atom_compare(a, b, c, d, 'i', 'v', 'i', 'v'))
363                 return ATOM_IVIV;
364         else if (atom_compare(a, b, c, d, 'u', 's', 'e', 'r'))
365                 return ATOM_USER;
366         else if (atom_compare(a, b, c, d, 'k', 'e', 'y', ' '))
367                 return ATOM_KEY;
368         else if (atom_compare(a, b, c, d, 'a', 'A', 'R', 'T'))
369                 return ATOM_ALBUM_ARTIST;
370         else if (atom_compare(a, b, c, d, 'd', 'e', 's', 'c'))
371                 return ATOM_DESCRIPTION;
372         else if (atom_compare(a, b, c, d, 'p', 'c', 's', 't'))
373                 return ATOM_PODCAST;
374         else
375                 return ATOM_UNKNOWN;
376 }
377
378 /* read atom header, atom size is returned with header included. */
379 static int atom_read_header(struct mp4 *f, uint8_t *atom_type,
380                 uint8_t *header_size, uint64_t *atom_size)
381 {
382         uint32_t size;
383         int ret;
384         int8_t atom_header[8];
385
386         ret = read_data(f, atom_header, 8);
387         if (ret <= 0)
388                 return ret;
389         size = read_u32_be(atom_header);
390         if (size == 1) { /* 64 bit atom size */
391                 if (header_size)
392                         *header_size = 16;
393                 ret = read_int64(f, atom_size);
394                 if (ret <= 0)
395                         return ret;
396         } else {
397                 if (header_size)
398                         *header_size = 8;
399                 if (atom_size)
400                         *atom_size = size;
401         }
402         *atom_type = atom_name_to_type(atom_header[4], atom_header[5],
403                 atom_header[6], atom_header[7]);
404         return 1;
405 }
406
407 static int64_t get_position(const struct mp4 *f)
408 {
409         return f->current_position;
410 }
411
412 static int need_parse_when_meta_only(uint8_t atom_type)
413 {
414         switch (atom_type) {
415         case ATOM_EDTS:
416         case ATOM_DRMS:
417         case ATOM_SINF:
418         case ATOM_SCHI:
419         case ATOM_STTS:
420         case ATOM_STSZ:
421         case ATOM_STZ2:
422         case ATOM_STCO:
423         case ATOM_STSC:
424         case ATOM_FRMA:
425         case ATOM_IVIV:
426         case ATOM_PRIV:
427                 return 0;
428         default:
429                 return 1;
430         }
431 }
432
433 static int32_t set_position(struct mp4 *f, int64_t position)
434 {
435         f->cb->seek(f->cb->user_data, position);
436         f->current_position = position;
437
438         return 0;
439 }
440
441 static int read_stsz(struct mp4 *f)
442 {
443         int ret;
444         int32_t i;
445         struct mp4_track *t;
446
447         if (f->total_tracks == 0)
448                 return -1;
449         t = f->track[f->total_tracks - 1];
450         ret = read_int8(f, NULL); /* version */
451         if (ret <= 0)
452                 return ret;
453         ret = read_int24(f, NULL); /* flags */
454         if (ret <= 0)
455                 return ret;
456         ret = read_int32(f, &t->stsz_sample_size);
457         if (ret <= 0)
458                 return ret;
459         ret = read_int32(f, &t->stsz_sample_count);
460         if (ret <= 0)
461                 return ret;
462         if (t->stsz_sample_size != 0)
463                 return 1;
464         t->stsz_table = para_malloc(t->stsz_sample_count * sizeof(int32_t));
465         for (i = 0; i < t->stsz_sample_count; i++) {
466                 ret = read_int32(f, &t->stsz_table[i]);
467                 if (ret <= 0)
468                         return ret;
469         }
470         return 1;
471 }
472
473 static int read_stts(struct mp4 *f)
474 {
475         int ret;
476         int32_t i;
477         struct mp4_track *t;
478
479         if (f->total_tracks == 0)
480                 return -1;
481         t = f->track[f->total_tracks - 1];
482         if (t->stts_entry_count)
483                 return 0;
484         ret = read_int8(f, NULL); /* version */
485         if (ret <= 0)
486                 return ret;
487         ret = read_int24(f, NULL); /* flags */
488         if (ret <= 0)
489                 return ret;
490         ret = read_int32(f, &t->stts_entry_count);
491         if (ret <= 0)
492                 return ret;
493         t->stts_sample_count = para_malloc(t->stts_entry_count
494                 * sizeof(int32_t));
495         t->stts_sample_delta = para_malloc(t->stts_entry_count
496                 * sizeof (int32_t));
497         for (i = 0; i < t->stts_entry_count; i++) {
498                 ret = read_int32(f, &t->stts_sample_count[i]);
499                 if (ret <= 0)
500                         return ret;
501                 ret = read_int32(f, &t->stts_sample_delta[i]);
502                 if (ret <= 0)
503                         return ret;
504         }
505         return 1;
506 }
507
508 static int read_stsc(struct mp4 *f)
509 {
510         int ret;
511         int32_t i;
512         struct mp4_track *t;
513
514         if (f->total_tracks == 0)
515                 return -1;
516         t = f->track[f->total_tracks - 1];
517
518         ret = read_int8(f, NULL); /* version */
519         if (ret <= 0)
520                 return ret;
521         ret = read_int24(f, NULL); /* flags */
522         if (ret <= 0)
523                 return ret;
524         ret = read_int32(f, &t->stsc_entry_count);
525         if (ret <= 0)
526                 return ret;
527         t->stsc_first_chunk = para_malloc(t->stsc_entry_count * sizeof(int32_t));
528         t->stsc_samples_per_chunk = para_malloc(t->stsc_entry_count
529                 * sizeof (int32_t));
530         t->stsc_sample_desc_index = para_malloc(t->stsc_entry_count *
531                 sizeof (int32_t));
532
533         for (i = 0; i < t->stsc_entry_count; i++) {
534                 ret = read_int32(f, &t->stsc_first_chunk[i]);
535                 if (ret <= 0)
536                         return ret;
537                 ret = read_int32(f, &t->stsc_samples_per_chunk[i]);
538                 if (ret <= 0)
539                         return ret;
540                 ret = read_int32(f, &t->stsc_sample_desc_index[i]);
541                 if (ret <= 0)
542                         return ret;
543         }
544         return 1;
545 }
546
547 static int read_stco(struct mp4 *f)
548 {
549         int ret;
550         int32_t i;
551         struct mp4_track *t;
552
553         if (f->total_tracks == 0)
554                 return -1;
555         t = f->track[f->total_tracks - 1];
556
557         ret = read_int8(f, NULL); /* version */
558         if (ret <= 0)
559                 return ret;
560         ret = read_int24(f, NULL); /* flags */
561         if (ret <= 0)
562                 return ret;
563         ret = read_int32(f, &t->stco_entry_count);
564         if (ret <= 0)
565                 return ret;
566         t->stco_chunk_offset = para_malloc(t->stco_entry_count
567                 * sizeof(int32_t));
568         for (i = 0; i < t->stco_entry_count; i++) {
569                 ret = read_int32(f, &t->stco_chunk_offset[i]);
570                 if (ret <= 0)
571                         return ret;
572         }
573         return 1;
574 }
575
576 static int read_mp4a(struct mp4 *f)
577 {
578         int ret;
579         int32_t i;
580         uint8_t atom_type = 0;
581         uint8_t header_size = 0;
582         struct mp4_track *t;
583
584         if (f->total_tracks == 0)
585                 return -1;
586         t = f->track[f->total_tracks - 1];
587
588         for (i = 0; i < 6; i++) {
589                 ret = read_int8(f, NULL); /* reserved */
590                 if (ret <= 0)
591                         return ret;
592         }
593         ret = read_int16(f, NULL); /* data_reference_index */
594         if (ret <= 0)
595                 return ret;
596         ret = read_int32(f, NULL); /* reserved */
597         if (ret <= 0)
598                 return ret;
599         ret = read_int32(f, NULL); /* reserved */
600         if (ret <= 0)
601                 return ret;
602         ret = read_int16(f, &t->channelCount);
603         if (ret <= 0)
604                 return ret;
605         ret = read_int16(f, NULL);
606         if (ret <= 0)
607                 return ret;
608         ret = read_int16(f, NULL);
609         if (ret <= 0)
610                 return ret;
611         ret = read_int16(f, NULL);
612         if (ret <= 0)
613                 return ret;
614         ret = read_int16(f, &t->sampleRate);
615         if (ret <= 0)
616                 return ret;
617         ret = read_int16(f, NULL);
618         if (ret <= 0)
619                 return ret;
620         return atom_read_header(f, &atom_type, &header_size, NULL);
621 }
622
623 static int read_stsd(struct mp4 *f)
624 {
625         int ret;
626         uint32_t i, entry_count;
627         uint8_t header_size = 0;
628         struct mp4_track *t;
629
630         if (f->total_tracks == 0)
631                 return -1;
632         t = f->track[f->total_tracks - 1];
633         ret = read_int8(f, NULL); /* version */
634         if (ret <= 0)
635                 return ret;
636         ret = read_int24(f, NULL); /* flags */
637         if (ret <= 0)
638                 return ret;
639         ret = read_int32(f, &entry_count);
640         if (ret <= 0)
641                 return ret;
642         for (i = 0; i < entry_count; i++) {
643                 uint64_t skip = get_position(f);
644                 uint64_t size;
645                 uint8_t atom_type = 0;
646                 ret = atom_read_header(f, &atom_type, &header_size, &size);
647                 if (ret <= 0)
648                         return ret;
649                 skip += size;
650                 t->is_audio = atom_type == ATOM_MP4A;
651                 if (t->is_audio)
652                         read_mp4a(f);
653                 set_position(f, skip);
654         }
655         return 1;
656 }
657
658 static int32_t tag_add_field(struct mp4_metadata *meta, const char *item,
659                 const char *value, int32_t len)
660 {
661         meta->tags = para_realloc(meta->tags,
662                 (meta->count + 1) * sizeof(struct mp4_tag));
663         meta->tags[meta->count].item = para_strdup(item);
664         meta->tags[meta->count].len = len;
665         if (len >= 0) {
666                 meta->tags[meta->count].value = para_malloc(len + 1);
667                 memcpy(meta->tags[meta->count].value, value, len);
668                 meta->tags[meta->count].value[len] = 0;
669         } else {
670                 meta->tags[meta->count].value = para_strdup(value);
671         }
672         meta->count++;
673         return 1;
674 }
675
676 static int read_string(struct mp4 *f, uint32_t length, char **result)
677 {
678         char *str = para_malloc(length + 1);
679         int ret = read_data(f, str, length);
680
681         if (ret <= 0) {
682                 free(str);
683                 *result = NULL;
684         } else {
685                 str[length] = '\0';
686                 *result = str;
687         }
688         return ret;
689 }
690
691 static const char *get_metadata_name(uint8_t atom_type)
692 {
693         switch (atom_type) {
694         case ATOM_TITLE: return "title";
695         case ATOM_ARTIST: return "artist";
696         case ATOM_ALBUM: return "album";
697         case ATOM_DATE: return "date";
698         case ATOM_COMMENT: return "comment";
699         default: return "unknown";
700         }
701 }
702
703 static int parse_tag(struct mp4 *f, uint8_t parent, int32_t size)
704 {
705         int ret;
706         uint64_t subsize, sumsize;
707         char *data = NULL;
708         uint32_t len = 0;
709         uint64_t destpos;
710
711         for (
712                 sumsize = 0;
713                 sumsize < size;
714                 set_position(f, destpos), sumsize += subsize
715         ) {
716                 uint8_t atom_type;
717                 uint8_t header_size = 0;
718                 ret = atom_read_header(f, &atom_type, &header_size, &subsize);
719                 if (ret <= 0)
720                         return ret;
721                 destpos = get_position(f) + subsize - header_size;
722                 if (atom_type != ATOM_DATA)
723                         continue;
724                 ret = read_int8(f, NULL); /* version */
725                 if (ret <= 0)
726                         return ret;
727                 ret = read_int24(f, NULL); /* flags */
728                 if (ret <= 0)
729                         return ret;
730                 ret = read_int32(f, NULL); /* reserved */
731                 if (ret <= 0)
732                         return ret;
733                 free(data);
734                 ret = read_string(f, subsize - (header_size + 8), &data);
735                 if (ret <= 0)
736                         return ret;
737                 len = subsize - (header_size + 8);
738         }
739         if (!data)
740                 return -1;
741         tag_add_field(&f->meta, get_metadata_name(parent), data, len);
742         free(data);
743         return 1;
744 }
745
746 static int read_mdhd(struct mp4 *f)
747 {
748         int ret;
749         uint32_t version;
750         struct mp4_track *t;
751
752         if (f->total_tracks == 0)
753                 return -1;
754         t = f->track[f->total_tracks - 1];
755
756         ret = read_int32(f, &version);
757         if (ret <= 0)
758                 return ret;
759         if (version == 1) {
760                 ret = read_int64(f, NULL); /* creation-time */
761                 if (ret <= 0)
762                         return ret;
763                 ret = read_int64(f, NULL); /* modification-time */
764                 if (ret <= 0)
765                         return ret;
766                 ret = read_int32(f, &t->timeScale);
767                 if (ret <= 0)
768                         return ret;
769                 ret = read_int64(f, &t->duration);
770                 if (ret <= 0)
771                         return ret;
772         } else { //version == 0
773                 uint32_t temp;
774
775                 ret = read_int32(f, NULL); /* creation-time */
776                 if (ret <= 0)
777                         return ret;
778                 ret = read_int32(f, NULL); /* modification-time */
779                 if (ret <= 0)
780                         return ret;
781                 ret = read_int32(f, &t->timeScale);
782                 if (ret <= 0)
783                         return ret;
784                 ret = read_int32(f, &temp);
785                 if (ret <= 0)
786                         return ret;
787                 t->duration = (temp == (uint32_t) (-1))?
788                         (uint64_t) (-1) : (uint64_t) (temp);
789         }
790         ret = read_int16(f, NULL);
791         if (ret <= 0)
792                 return ret;
793         ret = read_int16(f, NULL);
794         if (ret <= 0)
795                 return ret;
796         return 1;
797 }
798
799 static int32_t read_ilst(struct mp4 *f, int32_t size)
800 {
801         int ret;
802         uint64_t sumsize = 0;
803
804         while (sumsize < size) {
805                 uint8_t atom_type;
806                 uint64_t subsize, destpos;
807                 uint8_t header_size = 0;
808                 ret = atom_read_header(f, &atom_type, &header_size, &subsize);
809                 if (ret <= 0)
810                         return ret;
811                 destpos = get_position(f) + subsize - header_size;
812                 switch (atom_type) {
813                 case ATOM_ARTIST:
814                 case ATOM_TITLE:
815                 case ATOM_ALBUM:
816                 case ATOM_COMMENT:
817                 case ATOM_DATE:
818                         parse_tag(f, atom_type, subsize - header_size);
819                 }
820                 set_position(f, destpos);
821                 sumsize += subsize;
822         }
823         return 1;
824 }
825
826 static int32_t read_meta(struct mp4 *f, uint64_t size)
827 {
828         int ret;
829         uint64_t subsize, sumsize = 0;
830         uint8_t atom_type;
831         uint8_t header_size = 0;
832
833         ret = read_int8(f, NULL); /* version */
834         if (ret <= 0)
835                 return ret;
836         ret = read_int24(f, NULL); /* flags */
837         if (ret <= 0)
838                 return ret;
839         while (sumsize < (size - (header_size + 4))) {
840                 ret = atom_read_header(f, &atom_type, &header_size, &subsize);
841                 if (ret <= 0)
842                         return ret;
843                 if (subsize <= header_size + 4)
844                         return 1;
845                 if (atom_type == ATOM_ILST)
846                         read_ilst(f, subsize - (header_size + 4));
847                 else
848                         set_position(f, get_position(f) + subsize - header_size);
849                 sumsize += subsize;
850         }
851         return 1;
852 }
853
854 static int atom_read(struct mp4 *f, uint64_t size, uint8_t atom_type)
855 {
856         uint64_t dest_position = get_position(f) + size - 8;
857         int ret = 1; /* return success for atoms we don't care about */
858
859         switch (atom_type) {
860         case ATOM_STSZ: ret = read_stsz(f); break;
861         case ATOM_STTS: ret = read_stts(f); break;
862         case ATOM_STSC: ret = read_stsc(f); break;
863         case ATOM_STCO: ret = read_stco(f); break;
864         case ATOM_STSD: ret = read_stsd(f); break;
865         case ATOM_MDHD: ret = read_mdhd(f); break;
866         case ATOM_META: ret = read_meta(f, size); break;
867         }
868         set_position(f, dest_position);
869         return ret;
870 }
871
872 /* parse atoms that are sub atoms of other atoms */
873 static int parse_sub_atoms(struct mp4 *f, uint64_t total_size, int meta_only)
874 {
875         int ret;
876         uint64_t size;
877         uint8_t atom_type = 0;
878         uint64_t counted_size = 0;
879         uint8_t header_size = 0;
880
881         while (counted_size < total_size) {
882                 ret = atom_read_header(f, &atom_type, &header_size, &size);
883                 if (ret <= 0)
884                         return ret;
885                 if (size == 0)
886                         return -1;
887                 counted_size += size;
888                 if (atom_type == ATOM_TRAK) {
889                         if (f->total_tracks >= MAX_TRACKS)
890                                 return -1;
891                         f->total_tracks++;
892                         f->track[f->total_tracks - 1] = para_calloc(
893                                 sizeof(struct mp4_track));
894                 }
895                 /* parse subatoms */
896                 if (meta_only && !need_parse_when_meta_only(atom_type)) {
897                         set_position(f, get_position(f) + size - header_size);
898                 } else if (atom_type < SUBATOMIC) {
899                         ret = parse_sub_atoms(f, size - header_size, meta_only);
900                         if (ret <= 0)
901                                 return ret;
902                 } else {
903                         ret = atom_read(f, size, atom_type);
904                         if (ret <= 0)
905                                 return ret;
906                 }
907         }
908         return 1;
909 }
910
911 /* parse root atoms */
912 static int parse_atoms(struct mp4 *f, int meta_only)
913 {
914         int ret;
915         uint64_t size;
916         uint8_t atom_type = 0;
917         uint8_t header_size = 0;
918
919         f->file_size = 0;
920
921         while ((ret = atom_read_header(f, &atom_type, &header_size, &size)) > 0) {
922                 f->file_size += size;
923                 f->last_atom = atom_type;
924
925                 if (atom_type == ATOM_MOOV && size > header_size) {
926                         f->moov_offset = get_position(f) - header_size;
927                         f->moov_size = size;
928                 }
929
930                 /* parse subatoms */
931                 if (meta_only && !need_parse_when_meta_only(atom_type)) {
932                         set_position(f, get_position(f) + size - header_size);
933                 } else if (atom_type < SUBATOMIC) {
934                         ret = parse_sub_atoms(f, size - header_size, meta_only);
935                         if (ret <= 0)
936                                 return ret;
937                 } else {
938                         /* skip this atom */
939                         set_position(f, get_position(f) + size - header_size);
940                 }
941         }
942         return ret;
943 }
944
945 struct mp4 *mp4_open_read(const struct mp4_callback *cb)
946 {
947         int ret;
948         struct mp4 *f = para_calloc(sizeof(struct mp4));
949
950         f->cb = cb;
951         ret = parse_atoms(f, 0);
952         if (ret < 0) {
953                 free(f);
954                 return NULL;
955         }
956         return f;
957 }
958
959 void mp4_close(struct mp4 *f)
960 {
961         int32_t i;
962
963         for (i = 0; i < f->total_tracks; i++) {
964                 if (f->track[i]) {
965                         free(f->track[i]->stsz_table);
966                         free(f->track[i]->stts_sample_count);
967                         free(f->track[i]->stts_sample_delta);
968                         free(f->track[i]->stsc_first_chunk);
969                         free(f->track[i]->stsc_samples_per_chunk);
970                         free(f->track[i]->stsc_sample_desc_index);
971                         free(f->track[i]->stco_chunk_offset);
972                         free(f->track[i]);
973                 }
974         }
975         for (i = 0; i < f->meta.count; i++) {
976                 free(f->meta.tags[i].item);
977                 free(f->meta.tags[i].value);
978         }
979         free(f->meta.tags);
980         free(f);
981 }
982
983 static int32_t chunk_of_sample(const struct mp4 *f, int32_t track,
984                 int32_t sample, int32_t *chunk_sample, int32_t *chunk)
985 {
986         int32_t total_entries = 0;
987         int32_t chunk2entry;
988         int32_t chunk1, chunk2, chunk1samples, range_samples, total = 0;
989
990         *chunk_sample = 0;
991         *chunk = 1;
992
993         total_entries = f->track[track]->stsc_entry_count;
994
995         chunk1 = 1;
996         chunk1samples = 0;
997         chunk2entry = 0;
998
999         do {
1000                 chunk2 = f->track[track]->stsc_first_chunk[chunk2entry];
1001                 *chunk = chunk2 - chunk1;
1002                 range_samples = *chunk * chunk1samples;
1003
1004                 if (sample < total + range_samples)
1005                         break;
1006
1007                 chunk1samples = f->track[track]->stsc_samples_per_chunk[chunk2entry];
1008                 chunk1 = chunk2;
1009
1010                 if (chunk2entry < total_entries) {
1011                         chunk2entry++;
1012                         total += range_samples;
1013                 }
1014         } while (chunk2entry < total_entries);
1015
1016         if (chunk1samples)
1017                 *chunk = (sample - total) / chunk1samples + chunk1;
1018         else
1019                 *chunk = 1;
1020
1021         *chunk_sample = total + (*chunk - chunk1) * chunk1samples;
1022
1023         return 0;
1024 }
1025
1026 static int32_t chunk_to_offset(const struct mp4 *f, int32_t track,
1027                 int32_t chunk)
1028 {
1029         const struct mp4_track *p_track = f->track[track];
1030
1031         if (p_track->stco_entry_count && (chunk > p_track->stco_entry_count)) {
1032                 return p_track->stco_chunk_offset[p_track->stco_entry_count -
1033                                                   1];
1034         } else if (p_track->stco_entry_count) {
1035                 return p_track->stco_chunk_offset[chunk - 1];
1036         } else {
1037                 return 8;
1038         }
1039
1040         return 0;
1041 }
1042
1043 static int32_t sample_range_size(const struct mp4 *f, int32_t track,
1044                 int32_t chunk_sample, int32_t sample)
1045 {
1046         int32_t i, total;
1047         const struct mp4_track *t = f->track[track];
1048
1049         if (t->stsz_sample_size)
1050                 return (sample - chunk_sample) * t->stsz_sample_size;
1051         for (i = chunk_sample, total = 0; i < sample; i++)
1052                 total += t->stsz_table[i];
1053         return total;
1054 }
1055
1056 /**
1057  * Return the number of milliseconds of the given track.
1058  *
1059  * \param f As returned by \ref mp4_open_read(), must not be NULL.
1060  * \param track Between zero and the value returned by \ref mp4_get_total_tracks().
1061  *
1062  * The function returns zero if the audio file is of zero length or contains a
1063  * corrupt track header.
1064  */
1065 uint64_t mp4_get_duration(const struct mp4 *f, int32_t track)
1066 {
1067         const struct mp4_track *t = f->track[track];
1068
1069         if (t->timeScale == 0)
1070                 return 0;
1071         return t->duration * 1000 / t->timeScale;
1072 }
1073
1074 int32_t mp4_get_total_tracks(const struct mp4 *f)
1075 {
1076         return f->total_tracks;
1077 }
1078
1079 /**
1080  * Check whether the given track number corresponds to an audio track.
1081  *
1082  * \param f See \ref mp4_get_duration().
1083  * \param track See \ref mp4_get_duration().
1084  *
1085  * Besides audio tracks, an mp4 file may contain video and system tracks. For
1086  * those the function returns false.
1087  */
1088 bool mp4_is_audio_track(const struct mp4 *f, int32_t track)
1089 {
1090         return f->track[track]->is_audio;
1091 }
1092
1093 int mp4_set_sample_position(struct mp4 *f, uint32_t track, int32_t sample)
1094 {
1095         const struct mp4_track *t = f->track[track];
1096         int32_t offset, chunk, chunk_sample;
1097
1098         if (sample >= t->stsz_sample_count || track >= f->total_tracks)
1099                 return -ERRNO_TO_PARA_ERROR(EINVAL);
1100         chunk_of_sample(f, track, sample, &chunk_sample, &chunk);
1101         offset = chunk_to_offset(f, track, chunk)
1102                 + sample_range_size(f, track, chunk_sample, sample);
1103         set_position(f, offset);
1104         return 1;
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 }