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