mov: read hydrogenaudio replaygain information
[libav.git] / libavformat / mov.c
1 /*
2 * MOV demuxer
3 * Copyright (c) 2001 Fabrice Bellard
4 * Copyright (c) 2009 Baptiste Coudurier <baptiste dot coudurier at gmail dot com>
5 *
6 * first version by Francois Revol <revol@free.fr>
7 * seek function by Gael Chardon <gael.dev@4now.net>
8 *
9 * This file is part of Libav.
10 *
11 * Libav is free software; you can redistribute it and/or
12 * modify it under the terms of the GNU Lesser General Public
13 * License as published by the Free Software Foundation; either
14 * version 2.1 of the License, or (at your option) any later version.
15 *
16 * Libav is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 * Lesser General Public License for more details.
20 *
21 * You should have received a copy of the GNU Lesser General Public
22 * License along with Libav; if not, write to the Free Software
23 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
24 */
25
26 #include <inttypes.h>
27 #include <limits.h>
28 #include <stdint.h>
29
30 //#define MOV_EXPORT_ALL_METADATA
31
32 #include "libavutil/attributes.h"
33 #include "libavutil/channel_layout.h"
34 #include "libavutil/intreadwrite.h"
35 #include "libavutil/intfloat.h"
36 #include "libavutil/mathematics.h"
37 #include "libavutil/avstring.h"
38 #include "libavutil/dict.h"
39 #include "libavcodec/ac3tab.h"
40 #include "avformat.h"
41 #include "internal.h"
42 #include "avio_internal.h"
43 #include "riff.h"
44 #include "isom.h"
45 #include "libavcodec/get_bits.h"
46 #include "id3v1.h"
47 #include "mov_chan.h"
48 #include "replaygain.h"
49
50 #if CONFIG_ZLIB
51 #include <zlib.h>
52 #endif
53
54 #include "qtpalette.h"
55
56
57 #undef NDEBUG
58 #include <assert.h>
59
60 /* those functions parse an atom */
61 /* links atom IDs to parse functions */
62 typedef struct MOVParseTableEntry {
63 uint32_t type;
64 int (*parse)(MOVContext *ctx, AVIOContext *pb, MOVAtom atom);
65 } MOVParseTableEntry;
66
67 static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom);
68
69 static int mov_metadata_track_or_disc_number(MOVContext *c, AVIOContext *pb,
70 unsigned len, const char *key)
71 {
72 char buf[16];
73
74 short current, total = 0;
75 avio_rb16(pb); // unknown
76 current = avio_rb16(pb);
77 if (len >= 6)
78 total = avio_rb16(pb);
79 if (!total)
80 snprintf(buf, sizeof(buf), "%d", current);
81 else
82 snprintf(buf, sizeof(buf), "%d/%d", current, total);
83 av_dict_set(&c->fc->metadata, key, buf, 0);
84
85 return 0;
86 }
87
88 static int mov_metadata_int8_bypass_padding(MOVContext *c, AVIOContext *pb,
89 unsigned len, const char *key)
90 {
91 char buf[16];
92
93 /* bypass padding bytes */
94 avio_r8(pb);
95 avio_r8(pb);
96 avio_r8(pb);
97
98 snprintf(buf, sizeof(buf), "%d", avio_r8(pb));
99 av_dict_set(&c->fc->metadata, key, buf, 0);
100
101 return 0;
102 }
103
104 static int mov_metadata_int8_no_padding(MOVContext *c, AVIOContext *pb,
105 unsigned len, const char *key)
106 {
107 char buf[16];
108
109 snprintf(buf, sizeof(buf), "%d", avio_r8(pb));
110 av_dict_set(&c->fc->metadata, key, buf, 0);
111
112 return 0;
113 }
114
115 static int mov_metadata_gnre(MOVContext *c, AVIOContext *pb,
116 unsigned len, const char *key)
117 {
118 short genre;
119 char buf[20];
120
121 avio_r8(pb); // unknown
122
123 genre = avio_r8(pb);
124 if (genre < 1 || genre > ID3v1_GENRE_MAX)
125 return 0;
126 snprintf(buf, sizeof(buf), "%s", ff_id3v1_genre_str[genre-1]);
127 av_dict_set(&c->fc->metadata, key, buf, 0);
128
129 return 0;
130 }
131
132 static const uint32_t mac_to_unicode[128] = {
133 0x00C4,0x00C5,0x00C7,0x00C9,0x00D1,0x00D6,0x00DC,0x00E1,
134 0x00E0,0x00E2,0x00E4,0x00E3,0x00E5,0x00E7,0x00E9,0x00E8,
135 0x00EA,0x00EB,0x00ED,0x00EC,0x00EE,0x00EF,0x00F1,0x00F3,
136 0x00F2,0x00F4,0x00F6,0x00F5,0x00FA,0x00F9,0x00FB,0x00FC,
137 0x2020,0x00B0,0x00A2,0x00A3,0x00A7,0x2022,0x00B6,0x00DF,
138 0x00AE,0x00A9,0x2122,0x00B4,0x00A8,0x2260,0x00C6,0x00D8,
139 0x221E,0x00B1,0x2264,0x2265,0x00A5,0x00B5,0x2202,0x2211,
140 0x220F,0x03C0,0x222B,0x00AA,0x00BA,0x03A9,0x00E6,0x00F8,
141 0x00BF,0x00A1,0x00AC,0x221A,0x0192,0x2248,0x2206,0x00AB,
142 0x00BB,0x2026,0x00A0,0x00C0,0x00C3,0x00D5,0x0152,0x0153,
143 0x2013,0x2014,0x201C,0x201D,0x2018,0x2019,0x00F7,0x25CA,
144 0x00FF,0x0178,0x2044,0x20AC,0x2039,0x203A,0xFB01,0xFB02,
145 0x2021,0x00B7,0x201A,0x201E,0x2030,0x00C2,0x00CA,0x00C1,
146 0x00CB,0x00C8,0x00CD,0x00CE,0x00CF,0x00CC,0x00D3,0x00D4,
147 0xF8FF,0x00D2,0x00DA,0x00DB,0x00D9,0x0131,0x02C6,0x02DC,
148 0x00AF,0x02D8,0x02D9,0x02DA,0x00B8,0x02DD,0x02DB,0x02C7,
149 };
150
151 static int mov_read_mac_string(MOVContext *c, AVIOContext *pb, int len,
152 char *dst, int dstlen)
153 {
154 char *p = dst;
155 char *end = dst+dstlen-1;
156 int i;
157
158 for (i = 0; i < len; i++) {
159 uint8_t t, c = avio_r8(pb);
160 if (c < 0x80 && p < end)
161 *p++ = c;
162 else
163 PUT_UTF8(mac_to_unicode[c-0x80], t, if (p < end) *p++ = t;);
164 }
165 *p = 0;
166 return p - dst;
167 }
168
169 static int mov_read_covr(MOVContext *c, AVIOContext *pb, int type, int len)
170 {
171 AVPacket pkt;
172 AVStream *st;
173 MOVStreamContext *sc;
174 enum AVCodecID id;
175 int ret;
176
177 switch (type) {
178 case 0xd: id = AV_CODEC_ID_MJPEG; break;
179 case 0xe: id = AV_CODEC_ID_PNG; break;
180 case 0x1b: id = AV_CODEC_ID_BMP; break;
181 default:
182 av_log(c->fc, AV_LOG_WARNING, "Unknown cover type: 0x%x.\n", type);
183 avio_skip(pb, len);
184 return 0;
185 }
186
187 st = avformat_new_stream(c->fc, NULL);
188 if (!st)
189 return AVERROR(ENOMEM);
190 sc = av_mallocz(sizeof(*sc));
191 if (!sc)
192 return AVERROR(ENOMEM);
193 st->priv_data = sc;
194
195 ret = av_get_packet(pb, &pkt, len);
196 if (ret < 0)
197 return ret;
198
199 st->disposition |= AV_DISPOSITION_ATTACHED_PIC;
200
201 st->attached_pic = pkt;
202 st->attached_pic.stream_index = st->index;
203 st->attached_pic.flags |= AV_PKT_FLAG_KEY;
204
205 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
206 st->codec->codec_id = id;
207
208 return 0;
209 }
210
211 static int mov_read_udta_string(MOVContext *c, AVIOContext *pb, MOVAtom atom)
212 {
213 #ifdef MOV_EXPORT_ALL_METADATA
214 char tmp_key[5];
215 #endif
216 char str[1024], key2[16], language[4] = {0};
217 const char *key = NULL;
218 uint16_t langcode = 0;
219 uint32_t data_type = 0, str_size;
220 int (*parse)(MOVContext*, AVIOContext*, unsigned, const char*) = NULL;
221
222 switch (atom.type) {
223 case MKTAG(0xa9,'n','a','m'): key = "title"; break;
224 case MKTAG(0xa9,'a','u','t'):
225 case MKTAG(0xa9,'A','R','T'): key = "artist"; break;
226 case MKTAG( 'a','A','R','T'): key = "album_artist"; break;
227 case MKTAG(0xa9,'w','r','t'): key = "composer"; break;
228 case MKTAG( 'c','p','r','t'):
229 case MKTAG(0xa9,'c','p','y'): key = "copyright"; break;
230 case MKTAG(0xa9,'c','m','t'):
231 case MKTAG(0xa9,'i','n','f'): key = "comment"; break;
232 case MKTAG(0xa9,'a','l','b'): key = "album"; break;
233 case MKTAG(0xa9,'d','a','y'): key = "date"; break;
234 case MKTAG(0xa9,'g','e','n'): key = "genre"; break;
235 case MKTAG( 'g','n','r','e'): key = "genre";
236 parse = mov_metadata_gnre; break;
237 case MKTAG(0xa9,'t','o','o'):
238 case MKTAG(0xa9,'s','w','r'): key = "encoder"; break;
239 case MKTAG(0xa9,'e','n','c'): key = "encoder"; break;
240 case MKTAG( 'd','e','s','c'): key = "description";break;
241 case MKTAG( 'l','d','e','s'): key = "synopsis"; break;
242 case MKTAG( 't','v','s','h'): key = "show"; break;
243 case MKTAG( 't','v','e','n'): key = "episode_id";break;
244 case MKTAG( 't','v','n','n'): key = "network"; break;
245 case MKTAG( 't','r','k','n'): key = "track";
246 parse = mov_metadata_track_or_disc_number; break;
247 case MKTAG( 'd','i','s','k'): key = "disc";
248 parse = mov_metadata_track_or_disc_number; break;
249 case MKTAG( 't','v','e','s'): key = "episode_sort";
250 parse = mov_metadata_int8_bypass_padding; break;
251 case MKTAG( 't','v','s','n'): key = "season_number";
252 parse = mov_metadata_int8_bypass_padding; break;
253 case MKTAG( 's','t','i','k'): key = "media_type";
254 parse = mov_metadata_int8_no_padding; break;
255 case MKTAG( 'h','d','v','d'): key = "hd_video";
256 parse = mov_metadata_int8_no_padding; break;
257 case MKTAG( 'p','g','a','p'): key = "gapless_playback";
258 parse = mov_metadata_int8_no_padding; break;
259 }
260
261 if (c->itunes_metadata && atom.size > 8) {
262 int data_size = avio_rb32(pb);
263 int tag = avio_rl32(pb);
264 if (tag == MKTAG('d','a','t','a')) {
265 data_type = avio_rb32(pb); // type
266 avio_rb32(pb); // unknown
267 str_size = data_size - 16;
268 atom.size -= 16;
269
270 if (atom.type == MKTAG('c', 'o', 'v', 'r')) {
271 int ret = mov_read_covr(c, pb, data_type, str_size);
272 if (ret < 0) {
273 av_log(c->fc, AV_LOG_ERROR, "Error parsing cover art.\n");
274 return ret;
275 }
276 }
277 } else return 0;
278 } else if (atom.size > 4 && key && !c->itunes_metadata) {
279 str_size = avio_rb16(pb); // string length
280 langcode = avio_rb16(pb);
281 ff_mov_lang_to_iso639(langcode, language);
282 atom.size -= 4;
283 } else
284 str_size = atom.size;
285
286 #ifdef MOV_EXPORT_ALL_METADATA
287 if (!key) {
288 snprintf(tmp_key, 5, "%.4s", (char*)&atom.type);
289 key = tmp_key;
290 }
291 #endif
292
293 if (!key)
294 return 0;
295 if (atom.size < 0)
296 return AVERROR_INVALIDDATA;
297
298 str_size = FFMIN3(sizeof(str)-1, str_size, atom.size);
299
300 if (parse)
301 parse(c, pb, str_size, key);
302 else {
303 if (data_type == 3 || (data_type == 0 && (langcode < 0x400 || langcode == 0x7fff))) { // MAC Encoded
304 mov_read_mac_string(c, pb, str_size, str, sizeof(str));
305 } else {
306 avio_read(pb, str, str_size);
307 str[str_size] = 0;
308 }
309 av_dict_set(&c->fc->metadata, key, str, 0);
310 if (*language && strcmp(language, "und")) {
311 snprintf(key2, sizeof(key2), "%s-%s", key, language);
312 av_dict_set(&c->fc->metadata, key2, str, 0);
313 }
314 }
315 av_dlog(c->fc, "lang \"%3s\" ", language);
316 av_dlog(c->fc, "tag \"%s\" value \"%s\" atom \"%.4s\" %d %"PRId64"\n",
317 key, str, (char*)&atom.type, str_size, atom.size);
318
319 return 0;
320 }
321
322 static int mov_read_chpl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
323 {
324 int64_t start;
325 int i, nb_chapters, str_len, version;
326 char str[256+1];
327
328 if ((atom.size -= 5) < 0)
329 return 0;
330
331 version = avio_r8(pb);
332 avio_rb24(pb);
333 if (version)
334 avio_rb32(pb); // ???
335 nb_chapters = avio_r8(pb);
336
337 for (i = 0; i < nb_chapters; i++) {
338 if (atom.size < 9)
339 return 0;
340
341 start = avio_rb64(pb);
342 str_len = avio_r8(pb);
343
344 if ((atom.size -= 9+str_len) < 0)
345 return 0;
346
347 avio_read(pb, str, str_len);
348 str[str_len] = 0;
349 avpriv_new_chapter(c->fc, i, (AVRational){1,10000000}, start, AV_NOPTS_VALUE, str);
350 }
351 return 0;
352 }
353
354 #define MIN_DATA_ENTRY_BOX_SIZE 12
355 static int mov_read_dref(MOVContext *c, AVIOContext *pb, MOVAtom atom)
356 {
357 AVStream *st;
358 MOVStreamContext *sc;
359 int entries, i, j;
360
361 if (c->fc->nb_streams < 1)
362 return 0;
363 st = c->fc->streams[c->fc->nb_streams-1];
364 sc = st->priv_data;
365
366 avio_rb32(pb); // version + flags
367 entries = avio_rb32(pb);
368 if (entries > (atom.size - 1) / MIN_DATA_ENTRY_BOX_SIZE + 1 ||
369 entries >= UINT_MAX / sizeof(*sc->drefs))
370 return AVERROR_INVALIDDATA;
371 av_free(sc->drefs);
372 sc->drefs = av_mallocz(entries * sizeof(*sc->drefs));
373 if (!sc->drefs)
374 return AVERROR(ENOMEM);
375 sc->drefs_count = entries;
376
377 for (i = 0; i < sc->drefs_count; i++) {
378 MOVDref *dref = &sc->drefs[i];
379 uint32_t size = avio_rb32(pb);
380 int64_t next = avio_tell(pb) + size - 4;
381
382 if (size < 12)
383 return AVERROR_INVALIDDATA;
384
385 dref->type = avio_rl32(pb);
386 avio_rb32(pb); // version + flags
387 av_dlog(c->fc, "type %.4s size %d\n", (char*)&dref->type, size);
388
389 if (dref->type == MKTAG('a','l','i','s') && size > 150) {
390 /* macintosh alias record */
391 uint16_t volume_len, len;
392 int16_t type;
393
394 avio_skip(pb, 10);
395
396 volume_len = avio_r8(pb);
397 volume_len = FFMIN(volume_len, 27);
398 avio_read(pb, dref->volume, 27);
399 dref->volume[volume_len] = 0;
400 av_log(c->fc, AV_LOG_DEBUG, "volume %s, len %d\n", dref->volume, volume_len);
401
402 avio_skip(pb, 12);
403
404 len = avio_r8(pb);
405 len = FFMIN(len, 63);
406 avio_read(pb, dref->filename, 63);
407 dref->filename[len] = 0;
408 av_log(c->fc, AV_LOG_DEBUG, "filename %s, len %d\n", dref->filename, len);
409
410 avio_skip(pb, 16);
411
412 /* read next level up_from_alias/down_to_target */
413 dref->nlvl_from = avio_rb16(pb);
414 dref->nlvl_to = avio_rb16(pb);
415 av_log(c->fc, AV_LOG_DEBUG, "nlvl from %d, nlvl to %d\n",
416 dref->nlvl_from, dref->nlvl_to);
417
418 avio_skip(pb, 16);
419
420 for (type = 0; type != -1 && avio_tell(pb) < next; ) {
421 if (pb->eof_reached)
422 return AVERROR_EOF;
423 type = avio_rb16(pb);
424 len = avio_rb16(pb);
425 av_log(c->fc, AV_LOG_DEBUG, "type %d, len %d\n", type, len);
426 if (len&1)
427 len += 1;
428 if (type == 2) { // absolute path
429 av_free(dref->path);
430 dref->path = av_mallocz(len+1);
431 if (!dref->path)
432 return AVERROR(ENOMEM);
433 avio_read(pb, dref->path, len);
434 if (len > volume_len && !strncmp(dref->path, dref->volume, volume_len)) {
435 len -= volume_len;
436 memmove(dref->path, dref->path+volume_len, len);
437 dref->path[len] = 0;
438 }
439 for (j = 0; j < len; j++)
440 if (dref->path[j] == ':')
441 dref->path[j] = '/';
442 av_log(c->fc, AV_LOG_DEBUG, "path %s\n", dref->path);
443 } else if (type == 0) { // directory name
444 av_free(dref->dir);
445 dref->dir = av_malloc(len+1);
446 if (!dref->dir)
447 return AVERROR(ENOMEM);
448 avio_read(pb, dref->dir, len);
449 dref->dir[len] = 0;
450 for (j = 0; j < len; j++)
451 if (dref->dir[j] == ':')
452 dref->dir[j] = '/';
453 av_log(c->fc, AV_LOG_DEBUG, "dir %s\n", dref->dir);
454 } else
455 avio_skip(pb, len);
456 }
457 }
458 avio_seek(pb, next, SEEK_SET);
459 }
460 return 0;
461 }
462
463 static int mov_read_hdlr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
464 {
465 AVStream *st;
466 uint32_t type;
467 uint32_t av_unused ctype;
468
469 if (c->fc->nb_streams < 1) // meta before first trak
470 return 0;
471
472 st = c->fc->streams[c->fc->nb_streams-1];
473
474 avio_r8(pb); /* version */
475 avio_rb24(pb); /* flags */
476
477 /* component type */
478 ctype = avio_rl32(pb);
479 type = avio_rl32(pb); /* component subtype */
480
481 av_dlog(c->fc, "ctype= %.4s (0x%08x)\n", (char*)&ctype, ctype);
482 av_dlog(c->fc, "stype= %.4s\n", (char*)&type);
483
484 if (type == MKTAG('v','i','d','e'))
485 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
486 else if (type == MKTAG('s','o','u','n'))
487 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
488 else if (type == MKTAG('m','1','a',' '))
489 st->codec->codec_id = AV_CODEC_ID_MP2;
490 else if ((type == MKTAG('s','u','b','p')) || (type == MKTAG('c','l','c','p')))
491 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
492
493 avio_rb32(pb); /* component manufacture */
494 avio_rb32(pb); /* component flags */
495 avio_rb32(pb); /* component flags mask */
496
497 return 0;
498 }
499
500 int ff_mov_read_esds(AVFormatContext *fc, AVIOContext *pb, MOVAtom atom)
501 {
502 AVStream *st;
503 int tag;
504
505 if (fc->nb_streams < 1)
506 return 0;
507 st = fc->streams[fc->nb_streams-1];
508
509 avio_rb32(pb); /* version + flags */
510 ff_mp4_read_descr(fc, pb, &tag);
511 if (tag == MP4ESDescrTag) {
512 ff_mp4_parse_es_descr(pb, NULL);
513 } else
514 avio_rb16(pb); /* ID */
515
516 ff_mp4_read_descr(fc, pb, &tag);
517 if (tag == MP4DecConfigDescrTag)
518 ff_mp4_read_dec_config_descr(fc, st, pb);
519 return 0;
520 }
521
522 static int mov_read_esds(MOVContext *c, AVIOContext *pb, MOVAtom atom)
523 {
524 return ff_mov_read_esds(c->fc, pb, atom);
525 }
526
527 static int mov_read_dac3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
528 {
529 AVStream *st;
530 int ac3info, acmod, lfeon, bsmod;
531
532 if (c->fc->nb_streams < 1)
533 return 0;
534 st = c->fc->streams[c->fc->nb_streams-1];
535
536 ac3info = avio_rb24(pb);
537 bsmod = (ac3info >> 14) & 0x7;
538 acmod = (ac3info >> 11) & 0x7;
539 lfeon = (ac3info >> 10) & 0x1;
540 st->codec->channels = ((int[]){2,1,2,3,3,4,4,5})[acmod] + lfeon;
541 st->codec->channel_layout = avpriv_ac3_channel_layout_tab[acmod];
542 if (lfeon)
543 st->codec->channel_layout |= AV_CH_LOW_FREQUENCY;
544 st->codec->audio_service_type = bsmod;
545 if (st->codec->channels > 1 && bsmod == 0x7)
546 st->codec->audio_service_type = AV_AUDIO_SERVICE_TYPE_KARAOKE;
547
548 return 0;
549 }
550
551 static int mov_read_dec3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
552 {
553 AVStream *st;
554 int eac3info, acmod, lfeon, bsmod;
555
556 if (c->fc->nb_streams < 1)
557 return 0;
558 st = c->fc->streams[c->fc->nb_streams-1];
559
560 /* No need to parse fields for additional independent substreams and its
561 * associated dependent substreams since libavcodec's E-AC-3 decoder
562 * does not support them yet. */
563 avio_rb16(pb); /* data_rate and num_ind_sub */
564 eac3info = avio_rb24(pb);
565 bsmod = (eac3info >> 12) & 0x1f;
566 acmod = (eac3info >> 9) & 0x7;
567 lfeon = (eac3info >> 8) & 0x1;
568 st->codec->channel_layout = avpriv_ac3_channel_layout_tab[acmod];
569 if (lfeon)
570 st->codec->channel_layout |= AV_CH_LOW_FREQUENCY;
571 st->codec->channels = av_get_channel_layout_nb_channels(st->codec->channel_layout);
572 st->codec->audio_service_type = bsmod;
573 if (st->codec->channels > 1 && bsmod == 0x7)
574 st->codec->audio_service_type = AV_AUDIO_SERVICE_TYPE_KARAOKE;
575
576 return 0;
577 }
578
579 static int mov_read_chan(MOVContext *c, AVIOContext *pb, MOVAtom atom)
580 {
581 AVStream *st;
582
583 if (c->fc->nb_streams < 1)
584 return 0;
585 st = c->fc->streams[c->fc->nb_streams-1];
586
587 if (atom.size < 16)
588 return 0;
589
590 ff_mov_read_chan(c->fc, pb, st, atom.size - 4);
591
592 return 0;
593 }
594
595 static int mov_read_wfex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
596 {
597 AVStream *st;
598
599 if (c->fc->nb_streams < 1)
600 return 0;
601 st = c->fc->streams[c->fc->nb_streams-1];
602
603 ff_get_wav_header(pb, st->codec, atom.size);
604
605 return 0;
606 }
607
608 static int mov_read_pasp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
609 {
610 const int num = avio_rb32(pb);
611 const int den = avio_rb32(pb);
612 AVStream *st;
613
614 if (c->fc->nb_streams < 1)
615 return 0;
616 st = c->fc->streams[c->fc->nb_streams-1];
617
618 if ((st->sample_aspect_ratio.den != 1 || st->sample_aspect_ratio.num) && // default
619 (den != st->sample_aspect_ratio.den || num != st->sample_aspect_ratio.num)) {
620 av_log(c->fc, AV_LOG_WARNING,
621 "sample aspect ratio already set to %d:%d, ignoring 'pasp' atom (%d:%d)\n",
622 st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
623 num, den);
624 } else if (den != 0) {
625 st->sample_aspect_ratio.num = num;
626 st->sample_aspect_ratio.den = den;
627 }
628 return 0;
629 }
630
631 /* this atom contains actual media data */
632 static int mov_read_mdat(MOVContext *c, AVIOContext *pb, MOVAtom atom)
633 {
634 if (atom.size == 0) /* wrong one (MP4) */
635 return 0;
636 c->found_mdat=1;
637 return 0; /* now go for moov */
638 }
639
640 /* read major brand, minor version and compatible brands and store them as metadata */
641 static int mov_read_ftyp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
642 {
643 uint32_t minor_ver;
644 int comp_brand_size;
645 char minor_ver_str[11]; /* 32 bit integer -> 10 digits + null */
646 char* comp_brands_str;
647 uint8_t type[5] = {0};
648
649 avio_read(pb, type, 4);
650 if (strcmp(type, "qt "))
651 c->isom = 1;
652 av_log(c->fc, AV_LOG_DEBUG, "ISO: File Type Major Brand: %.4s\n",(char *)&type);
653 av_dict_set(&c->fc->metadata, "major_brand", type, 0);
654 minor_ver = avio_rb32(pb); /* minor version */
655 snprintf(minor_ver_str, sizeof(minor_ver_str), "%"PRIu32"", minor_ver);
656 av_dict_set(&c->fc->metadata, "minor_version", minor_ver_str, 0);
657
658 comp_brand_size = atom.size - 8;
659 if (comp_brand_size < 0)
660 return AVERROR_INVALIDDATA;
661 comp_brands_str = av_malloc(comp_brand_size + 1); /* Add null terminator */
662 if (!comp_brands_str)
663 return AVERROR(ENOMEM);
664 avio_read(pb, comp_brands_str, comp_brand_size);
665 comp_brands_str[comp_brand_size] = 0;
666 av_dict_set(&c->fc->metadata, "compatible_brands", comp_brands_str, 0);
667 av_freep(&comp_brands_str);
668
669 return 0;
670 }
671
672 /* this atom should contain all header atoms */
673 static int mov_read_moov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
674 {
675 int ret;
676
677 if ((ret = mov_read_default(c, pb, atom)) < 0)
678 return ret;
679 /* we parsed the 'moov' atom, we can terminate the parsing as soon as we find the 'mdat' */
680 /* so we don't parse the whole file if over a network */
681 c->found_moov=1;
682 return 0; /* now go for mdat */
683 }
684
685 static int mov_read_moof(MOVContext *c, AVIOContext *pb, MOVAtom atom)
686 {
687 c->fragment.moof_offset = avio_tell(pb) - 8;
688 av_dlog(c->fc, "moof offset %"PRIx64"\n", c->fragment.moof_offset);
689 return mov_read_default(c, pb, atom);
690 }
691
692 static void mov_metadata_creation_time(AVDictionary **metadata, time_t time)
693 {
694 char buffer[32];
695 if (time) {
696 struct tm *ptm;
697 time -= 2082844800; /* seconds between 1904-01-01 and Epoch */
698 ptm = gmtime(&time);
699 if (!ptm) return;
700 strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", ptm);
701 av_dict_set(metadata, "creation_time", buffer, 0);
702 }
703 }
704
705 static int mov_read_mdhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
706 {
707 AVStream *st;
708 MOVStreamContext *sc;
709 int version;
710 char language[4] = {0};
711 unsigned lang;
712 time_t creation_time;
713
714 if (c->fc->nb_streams < 1)
715 return 0;
716 st = c->fc->streams[c->fc->nb_streams-1];
717 sc = st->priv_data;
718
719 if (sc->time_scale) {
720 av_log(c->fc, AV_LOG_ERROR, "Multiple mdhd?\n");
721 return AVERROR_INVALIDDATA;
722 }
723
724 version = avio_r8(pb);
725 if (version > 1) {
726 avpriv_request_sample(c->fc, "Version %d", version);
727 return AVERROR_PATCHWELCOME;
728 }
729 avio_rb24(pb); /* flags */
730 if (version == 1) {
731 creation_time = avio_rb64(pb);
732 avio_rb64(pb);
733 } else {
734 creation_time = avio_rb32(pb);
735 avio_rb32(pb); /* modification time */
736 }
737 mov_metadata_creation_time(&st->metadata, creation_time);
738
739 sc->time_scale = avio_rb32(pb);
740 st->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
741
742 lang = avio_rb16(pb); /* language */
743 if (ff_mov_lang_to_iso639(lang, language))
744 av_dict_set(&st->metadata, "language", language, 0);
745 avio_rb16(pb); /* quality */
746
747 return 0;
748 }
749
750 static int mov_read_mvhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
751 {
752 time_t creation_time;
753 int version = avio_r8(pb); /* version */
754 avio_rb24(pb); /* flags */
755
756 if (version == 1) {
757 creation_time = avio_rb64(pb);
758 avio_rb64(pb);
759 } else {
760 creation_time = avio_rb32(pb);
761 avio_rb32(pb); /* modification time */
762 }
763 mov_metadata_creation_time(&c->fc->metadata, creation_time);
764 c->time_scale = avio_rb32(pb); /* time scale */
765
766 av_dlog(c->fc, "time scale = %i\n", c->time_scale);
767
768 c->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
769 avio_rb32(pb); /* preferred scale */
770
771 avio_rb16(pb); /* preferred volume */
772
773 avio_skip(pb, 10); /* reserved */
774
775 avio_skip(pb, 36); /* display matrix */
776
777 avio_rb32(pb); /* preview time */
778 avio_rb32(pb); /* preview duration */
779 avio_rb32(pb); /* poster time */
780 avio_rb32(pb); /* selection time */
781 avio_rb32(pb); /* selection duration */
782 avio_rb32(pb); /* current time */
783 avio_rb32(pb); /* next track ID */
784
785 return 0;
786 }
787
788 static int mov_read_smi(MOVContext *c, AVIOContext *pb, MOVAtom atom)
789 {
790 AVStream *st;
791
792 if (c->fc->nb_streams < 1)
793 return 0;
794 st = c->fc->streams[c->fc->nb_streams-1];
795
796 if ((uint64_t)atom.size > (1<<30))
797 return AVERROR_INVALIDDATA;
798
799 // currently SVQ3 decoder expect full STSD header - so let's fake it
800 // this should be fixed and just SMI header should be passed
801 av_free(st->codec->extradata);
802 st->codec->extradata = av_mallocz(atom.size + 0x5a + FF_INPUT_BUFFER_PADDING_SIZE);
803 if (!st->codec->extradata)
804 return AVERROR(ENOMEM);
805 st->codec->extradata_size = 0x5a + atom.size;
806 memcpy(st->codec->extradata, "SVQ3", 4); // fake
807 avio_read(pb, st->codec->extradata + 0x5a, atom.size);
808 av_dlog(c->fc, "Reading SMI %"PRId64" %s\n", atom.size, st->codec->extradata + 0x5a);
809 return 0;
810 }
811
812 static int mov_read_enda(MOVContext *c, AVIOContext *pb, MOVAtom atom)
813 {
814 AVStream *st;
815 int little_endian;
816
817 if (c->fc->nb_streams < 1)
818 return 0;
819 st = c->fc->streams[c->fc->nb_streams-1];
820
821 little_endian = avio_rb16(pb);
822 av_dlog(c->fc, "enda %d\n", little_endian);
823 if (little_endian == 1) {
824 switch (st->codec->codec_id) {
825 case AV_CODEC_ID_PCM_S24BE:
826 st->codec->codec_id = AV_CODEC_ID_PCM_S24LE;
827 break;
828 case AV_CODEC_ID_PCM_S32BE:
829 st->codec->codec_id = AV_CODEC_ID_PCM_S32LE;
830 break;
831 case AV_CODEC_ID_PCM_F32BE:
832 st->codec->codec_id = AV_CODEC_ID_PCM_F32LE;
833 break;
834 case AV_CODEC_ID_PCM_F64BE:
835 st->codec->codec_id = AV_CODEC_ID_PCM_F64LE;
836 break;
837 default:
838 break;
839 }
840 }
841 return 0;
842 }
843
844 static int mov_read_fiel(MOVContext *c, AVIOContext *pb, MOVAtom atom)
845 {
846 AVStream *st;
847 unsigned mov_field_order;
848 enum AVFieldOrder decoded_field_order = AV_FIELD_UNKNOWN;
849
850 if (c->fc->nb_streams < 1) // will happen with jp2 files
851 return 0;
852 st = c->fc->streams[c->fc->nb_streams-1];
853 if (atom.size < 2)
854 return AVERROR_INVALIDDATA;
855 mov_field_order = avio_rb16(pb);
856 if ((mov_field_order & 0xFF00) == 0x0100)
857 decoded_field_order = AV_FIELD_PROGRESSIVE;
858 else if ((mov_field_order & 0xFF00) == 0x0200) {
859 switch (mov_field_order & 0xFF) {
860 case 0x01: decoded_field_order = AV_FIELD_TT;
861 break;
862 case 0x06: decoded_field_order = AV_FIELD_BB;
863 break;
864 case 0x09: decoded_field_order = AV_FIELD_TB;
865 break;
866 case 0x0E: decoded_field_order = AV_FIELD_BT;
867 break;
868 }
869 }
870 if (decoded_field_order == AV_FIELD_UNKNOWN && mov_field_order) {
871 av_log(NULL, AV_LOG_ERROR, "Unknown MOV field order 0x%04x\n", mov_field_order);
872 }
873 st->codec->field_order = decoded_field_order;
874
875 return 0;
876 }
877
878 /* FIXME modify qdm2/svq3/h264 decoders to take full atom as extradata */
879 static int mov_read_extradata(MOVContext *c, AVIOContext *pb, MOVAtom atom)
880 {
881 AVStream *st;
882 uint64_t size;
883 uint8_t *buf;
884 int err;
885
886 if (c->fc->nb_streams < 1) // will happen with jp2 files
887 return 0;
888 st= c->fc->streams[c->fc->nb_streams-1];
889 size= (uint64_t)st->codec->extradata_size + atom.size + 8 + FF_INPUT_BUFFER_PADDING_SIZE;
890 if (size > INT_MAX || (uint64_t)atom.size > INT_MAX)
891 return AVERROR_INVALIDDATA;
892 if ((err = av_reallocp(&st->codec->extradata, size)) < 0) {
893 st->codec->extradata_size = 0;
894 return err;
895 }
896 buf = st->codec->extradata + st->codec->extradata_size;
897 st->codec->extradata_size= size - FF_INPUT_BUFFER_PADDING_SIZE;
898 AV_WB32( buf , atom.size + 8);
899 AV_WL32( buf + 4, atom.type);
900 avio_read(pb, buf + 8, atom.size);
901 return 0;
902 }
903
904 static int mov_read_wave(MOVContext *c, AVIOContext *pb, MOVAtom atom)
905 {
906 AVStream *st;
907
908 if (c->fc->nb_streams < 1)
909 return 0;
910 st = c->fc->streams[c->fc->nb_streams-1];
911
912 if ((uint64_t)atom.size > (1<<30))
913 return AVERROR_INVALIDDATA;
914
915 if (st->codec->codec_id == AV_CODEC_ID_QDM2 || st->codec->codec_id == AV_CODEC_ID_QDMC) {
916 // pass all frma atom to codec, needed at least for QDMC and QDM2
917 av_free(st->codec->extradata);
918 st->codec->extradata = av_mallocz(atom.size + FF_INPUT_BUFFER_PADDING_SIZE);
919 if (!st->codec->extradata)
920 return AVERROR(ENOMEM);
921 st->codec->extradata_size = atom.size;
922 avio_read(pb, st->codec->extradata, atom.size);
923 } else if (atom.size > 8) { /* to read frma, esds atoms */
924 int ret;
925 if ((ret = mov_read_default(c, pb, atom)) < 0)
926 return ret;
927 } else
928 avio_skip(pb, atom.size);
929 return 0;
930 }
931
932 /**
933 * This function reads atom content and puts data in extradata without tag
934 * nor size unlike mov_read_extradata.
935 */
936 static int mov_read_glbl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
937 {
938 AVStream *st;
939
940 if (c->fc->nb_streams < 1)
941 return 0;
942 st = c->fc->streams[c->fc->nb_streams-1];
943
944 if ((uint64_t)atom.size > (1<<30))
945 return AVERROR_INVALIDDATA;
946
947 if (atom.size >= 10) {
948 // Broken files created by legacy versions of libavformat will
949 // wrap a whole fiel atom inside of a glbl atom.
950 unsigned size = avio_rb32(pb);
951 unsigned type = avio_rl32(pb);
952 avio_seek(pb, -8, SEEK_CUR);
953 if (type == MKTAG('f','i','e','l') && size == atom.size)
954 return mov_read_default(c, pb, atom);
955 }
956 av_free(st->codec->extradata);
957 st->codec->extradata = av_mallocz(atom.size + FF_INPUT_BUFFER_PADDING_SIZE);
958 if (!st->codec->extradata)
959 return AVERROR(ENOMEM);
960 st->codec->extradata_size = atom.size;
961 avio_read(pb, st->codec->extradata, atom.size);
962 return 0;
963 }
964
965 static int mov_read_dvc1(MOVContext *c, AVIOContext *pb, MOVAtom atom)
966 {
967 AVStream *st;
968 uint8_t profile_level;
969
970 if (c->fc->nb_streams < 1)
971 return 0;
972 st = c->fc->streams[c->fc->nb_streams-1];
973
974 if (atom.size >= (1<<28) || atom.size < 7)
975 return AVERROR_INVALIDDATA;
976
977 profile_level = avio_r8(pb);
978 if ((profile_level & 0xf0) != 0xc0)
979 return 0;
980
981 av_free(st->codec->extradata);
982 st->codec->extradata = av_mallocz(atom.size - 7 + FF_INPUT_BUFFER_PADDING_SIZE);
983 if (!st->codec->extradata)
984 return AVERROR(ENOMEM);
985 st->codec->extradata_size = atom.size - 7;
986 avio_seek(pb, 6, SEEK_CUR);
987 avio_read(pb, st->codec->extradata, st->codec->extradata_size);
988 return 0;
989 }
990
991 /**
992 * An strf atom is a BITMAPINFOHEADER struct. This struct is 40 bytes itself,
993 * but can have extradata appended at the end after the 40 bytes belonging
994 * to the struct.
995 */
996 static int mov_read_strf(MOVContext *c, AVIOContext *pb, MOVAtom atom)
997 {
998 AVStream *st;
999
1000 if (c->fc->nb_streams < 1)
1001 return 0;
1002 if (atom.size <= 40)
1003 return 0;
1004 st = c->fc->streams[c->fc->nb_streams-1];
1005
1006 if ((uint64_t)atom.size > (1<<30))
1007 return AVERROR_INVALIDDATA;
1008
1009 av_free(st->codec->extradata);
1010 st->codec->extradata = av_mallocz(atom.size - 40 + FF_INPUT_BUFFER_PADDING_SIZE);
1011 if (!st->codec->extradata)
1012 return AVERROR(ENOMEM);
1013 st->codec->extradata_size = atom.size - 40;
1014 avio_skip(pb, 40);
1015 avio_read(pb, st->codec->extradata, atom.size - 40);
1016 return 0;
1017 }
1018
1019 static int mov_read_stco(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1020 {
1021 AVStream *st;
1022 MOVStreamContext *sc;
1023 unsigned int i, entries;
1024
1025 if (c->fc->nb_streams < 1)
1026 return 0;
1027 st = c->fc->streams[c->fc->nb_streams-1];
1028 sc = st->priv_data;
1029
1030 avio_r8(pb); /* version */
1031 avio_rb24(pb); /* flags */
1032
1033 entries = avio_rb32(pb);
1034
1035 if (!entries)
1036 return 0;
1037 if (entries >= UINT_MAX/sizeof(int64_t))
1038 return AVERROR_INVALIDDATA;
1039
1040 sc->chunk_offsets = av_malloc(entries * sizeof(int64_t));
1041 if (!sc->chunk_offsets)
1042 return AVERROR(ENOMEM);
1043 sc->chunk_count = entries;
1044
1045 if (atom.type == MKTAG('s','t','c','o'))
1046 for (i = 0; i < entries && !pb->eof_reached; i++)
1047 sc->chunk_offsets[i] = avio_rb32(pb);
1048 else if (atom.type == MKTAG('c','o','6','4'))
1049 for (i = 0; i < entries && !pb->eof_reached; i++)
1050 sc->chunk_offsets[i] = avio_rb64(pb);
1051 else
1052 return AVERROR_INVALIDDATA;
1053
1054 sc->chunk_count = i;
1055
1056 if (pb->eof_reached)
1057 return AVERROR_EOF;
1058
1059 return 0;
1060 }
1061
1062 /**
1063 * Compute codec id for 'lpcm' tag.
1064 * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
1065 */
1066 enum AVCodecID ff_mov_get_lpcm_codec_id(int bps, int flags)
1067 {
1068 /* lpcm flags:
1069 * 0x1 = float
1070 * 0x2 = big-endian
1071 * 0x4 = signed
1072 */
1073 return ff_get_pcm_codec_id(bps, flags & 1, flags & 2, flags & 4 ? -1 : 0);
1074 }
1075
1076 static int mov_codec_id(AVStream *st, uint32_t format)
1077 {
1078 int id = ff_codec_get_id(ff_codec_movaudio_tags, format);
1079
1080 if (id <= 0 &&
1081 ((format & 0xFFFF) == 'm' + ('s' << 8) ||
1082 (format & 0xFFFF) == 'T' + ('S' << 8)))
1083 id = ff_codec_get_id(ff_codec_wav_tags, av_bswap32(format) & 0xFFFF);
1084
1085 if (st->codec->codec_type != AVMEDIA_TYPE_VIDEO && id > 0) {
1086 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
1087 } else if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO &&
1088 /* skip old asf mpeg4 tag */
1089 format && format != MKTAG('m','p','4','s')) {
1090 id = ff_codec_get_id(ff_codec_movvideo_tags, format);
1091 if (id <= 0)
1092 id = ff_codec_get_id(ff_codec_bmp_tags, format);
1093 if (id > 0)
1094 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
1095 else if (st->codec->codec_type == AVMEDIA_TYPE_DATA) {
1096 id = ff_codec_get_id(ff_codec_movsubtitle_tags, format);
1097 if (id > 0)
1098 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
1099 }
1100 }
1101
1102 st->codec->codec_tag = format;
1103
1104 return id;
1105 }
1106
1107 static void mov_parse_stsd_video(MOVContext *c, AVIOContext *pb,
1108 AVStream *st, MOVStreamContext *sc)
1109 {
1110 unsigned int color_depth, len, j;
1111 int color_greyscale;
1112 int color_table_id;
1113
1114 avio_rb16(pb); /* version */
1115 avio_rb16(pb); /* revision level */
1116 avio_rb32(pb); /* vendor */
1117 avio_rb32(pb); /* temporal quality */
1118 avio_rb32(pb); /* spatial quality */
1119
1120 st->codec->width = avio_rb16(pb); /* width */
1121 st->codec->height = avio_rb16(pb); /* height */
1122
1123 avio_rb32(pb); /* horiz resolution */
1124 avio_rb32(pb); /* vert resolution */
1125 avio_rb32(pb); /* data size, always 0 */
1126 avio_rb16(pb); /* frames per samples */
1127
1128 len = avio_r8(pb); /* codec name, pascal string */
1129 if (len > 31)
1130 len = 31;
1131 mov_read_mac_string(c, pb, len, st->codec->codec_name, 32);
1132 if (len < 31)
1133 avio_skip(pb, 31 - len);
1134 /* codec_tag YV12 triggers an UV swap in rawdec.c */
1135 if (!memcmp(st->codec->codec_name, "Planar Y'CbCr 8-bit 4:2:0", 25))
1136 st->codec->codec_tag = MKTAG('I', '4', '2', '0');
1137 /* Flash Media Server uses tag H263 with Sorenson Spark */
1138 if (st->codec->codec_tag == MKTAG('H','2','6','3') &&
1139 !memcmp(st->codec->codec_name, "Sorenson H263", 13))
1140 st->codec->codec_id = AV_CODEC_ID_FLV1;
1141
1142 st->codec->bits_per_coded_sample = avio_rb16(pb); /* depth */
1143 color_table_id = avio_rb16(pb); /* colortable id */
1144 av_dlog(c->fc, "depth %d, ctab id %d\n",
1145 st->codec->bits_per_coded_sample, color_table_id);
1146 /* figure out the palette situation */
1147 color_depth = st->codec->bits_per_coded_sample & 0x1F;
1148 color_greyscale = st->codec->bits_per_coded_sample & 0x20;
1149
1150 /* if the depth is 2, 4, or 8 bpp, file is palettized */
1151 if ((color_depth == 2) || (color_depth == 4) || (color_depth == 8)) {
1152 /* for palette traversal */
1153 unsigned int color_start, color_count, color_end;
1154 unsigned char r, g, b;
1155
1156 if (color_greyscale) {
1157 int color_index, color_dec;
1158 /* compute the greyscale palette */
1159 st->codec->bits_per_coded_sample = color_depth;
1160 color_count = 1 << color_depth;
1161 color_index = 255;
1162 color_dec = 256 / (color_count - 1);
1163 for (j = 0; j < color_count; j++) {
1164 r = g = b = color_index;
1165 sc->palette[j] = (r << 16) | (g << 8) | (b);
1166 color_index -= color_dec;
1167 if (color_index < 0)
1168 color_index = 0;
1169 }
1170 } else if (color_table_id) {
1171 const uint8_t *color_table;
1172 /* if flag bit 3 is set, use the default palette */
1173 color_count = 1 << color_depth;
1174 if (color_depth == 2)
1175 color_table = ff_qt_default_palette_4;
1176 else if (color_depth == 4)
1177 color_table = ff_qt_default_palette_16;
1178 else
1179 color_table = ff_qt_default_palette_256;
1180
1181 for (j = 0; j < color_count; j++) {
1182 r = color_table[j * 3 + 0];
1183 g = color_table[j * 3 + 1];
1184 b = color_table[j * 3 + 2];
1185 sc->palette[j] = (r << 16) | (g << 8) | (b);
1186 }
1187 } else {
1188 /* load the palette from the file */
1189 color_start = avio_rb32(pb);
1190 color_count = avio_rb16(pb);
1191 color_end = avio_rb16(pb);
1192 if ((color_start <= 255) && (color_end <= 255)) {
1193 for (j = color_start; j <= color_end; j++) {
1194 /* each R, G, or B component is 16 bits;
1195 * only use the top 8 bits; skip alpha bytes
1196 * up front */
1197 avio_r8(pb);
1198 avio_r8(pb);
1199 r = avio_r8(pb);
1200 avio_r8(pb);
1201 g = avio_r8(pb);
1202 avio_r8(pb);
1203 b = avio_r8(pb);
1204 avio_r8(pb);
1205 sc->palette[j] = (r << 16) | (g << 8) | (b);
1206 }
1207 }
1208 }
1209 sc->has_palette = 1;
1210 }
1211 }
1212
1213 static void mov_parse_stsd_audio(MOVContext *c, AVIOContext *pb,
1214 AVStream *st, MOVStreamContext *sc)
1215 {
1216 int bits_per_sample, flags;
1217 uint16_t version = avio_rb16(pb);
1218
1219 avio_rb16(pb); /* revision level */
1220 avio_rb32(pb); /* vendor */
1221
1222 st->codec->channels = avio_rb16(pb); /* channel count */
1223 st->codec->bits_per_coded_sample = avio_rb16(pb); /* sample size */
1224 av_dlog(c->fc, "audio channels %d\n", st->codec->channels);
1225
1226 sc->audio_cid = avio_rb16(pb);
1227 avio_rb16(pb); /* packet size = 0 */
1228
1229 st->codec->sample_rate = ((avio_rb32(pb) >> 16));
1230
1231 // Read QT version 1 fields. In version 0 these do not exist.
1232 av_dlog(c->fc, "version =%d, isom =%d\n", version, c->isom);
1233 if (!c->isom) {
1234 if (version == 1) {
1235 sc->samples_per_frame = avio_rb32(pb);
1236 avio_rb32(pb); /* bytes per packet */
1237 sc->bytes_per_frame = avio_rb32(pb);
1238 avio_rb32(pb); /* bytes per sample */
1239 } else if (version == 2) {
1240 avio_rb32(pb); /* sizeof struct only */
1241 st->codec->sample_rate = av_int2double(avio_rb64(pb));
1242 st->codec->channels = avio_rb32(pb);
1243 avio_rb32(pb); /* always 0x7F000000 */
1244 st->codec->bits_per_coded_sample = avio_rb32(pb);
1245
1246 flags = avio_rb32(pb); /* lpcm format specific flag */
1247 sc->bytes_per_frame = avio_rb32(pb);
1248 sc->samples_per_frame = avio_rb32(pb);
1249 if (st->codec->codec_tag == MKTAG('l','p','c','m'))
1250 st->codec->codec_id =
1251 ff_mov_get_lpcm_codec_id(st->codec->bits_per_coded_sample,
1252 flags);
1253 }
1254 }
1255
1256 switch (st->codec->codec_id) {
1257 case AV_CODEC_ID_PCM_S8:
1258 case AV_CODEC_ID_PCM_U8:
1259 if (st->codec->bits_per_coded_sample == 16)
1260 st->codec->codec_id = AV_CODEC_ID_PCM_S16BE;
1261 break;
1262 case AV_CODEC_ID_PCM_S16LE:
1263 case AV_CODEC_ID_PCM_S16BE:
1264 if (st->codec->bits_per_coded_sample == 8)
1265 st->codec->codec_id = AV_CODEC_ID_PCM_S8;
1266 else if (st->codec->bits_per_coded_sample == 24)
1267 st->codec->codec_id =
1268 st->codec->codec_id == AV_CODEC_ID_PCM_S16BE ?
1269 AV_CODEC_ID_PCM_S24BE : AV_CODEC_ID_PCM_S24LE;
1270 break;
1271 /* set values for old format before stsd version 1 appeared */
1272 case AV_CODEC_ID_MACE3:
1273 sc->samples_per_frame = 6;
1274 sc->bytes_per_frame = 2 * st->codec->channels;
1275 break;
1276 case AV_CODEC_ID_MACE6:
1277 sc->samples_per_frame = 6;
1278 sc->bytes_per_frame = 1 * st->codec->channels;
1279 break;
1280 case AV_CODEC_ID_ADPCM_IMA_QT:
1281 sc->samples_per_frame = 64;
1282 sc->bytes_per_frame = 34 * st->codec->channels;
1283 break;
1284 case AV_CODEC_ID_GSM:
1285 sc->samples_per_frame = 160;
1286 sc->bytes_per_frame = 33;
1287 break;
1288 default:
1289 break;
1290 }
1291
1292 bits_per_sample = av_get_bits_per_sample(st->codec->codec_id);
1293 if (bits_per_sample) {
1294 st->codec->bits_per_coded_sample = bits_per_sample;
1295 sc->sample_size = (bits_per_sample >> 3) * st->codec->channels;
1296 }
1297 }
1298
1299 static void mov_parse_stsd_subtitle(MOVContext *c, AVIOContext *pb,
1300 AVStream *st, MOVStreamContext *sc,
1301 int size)
1302 {
1303 // ttxt stsd contains display flags, justification, background
1304 // color, fonts, and default styles, so fake an atom to read it
1305 MOVAtom fake_atom = { .size = size };
1306 // mp4s contains a regular esds atom
1307 if (st->codec->codec_tag != AV_RL32("mp4s"))
1308 mov_read_glbl(c, pb, fake_atom);
1309 st->codec->width = sc->width;
1310 st->codec->height = sc->height;
1311 }
1312
1313 static uint32_t yuv_to_rgba(uint32_t ycbcr)
1314 {
1315 uint8_t r, g, b;
1316 int y, cb, cr;
1317
1318 y = (ycbcr >> 16) & 0xFF;
1319 cr = (ycbcr >> 8) & 0xFF;
1320 cb = ycbcr & 0xFF;
1321
1322 b = av_clip_uint8(1.164 * (y - 16) + 2.018 * (cb - 128));
1323 g = av_clip_uint8(1.164 * (y - 16) - 0.813 * (cr - 128) - 0.391 * (cb - 128));
1324 r = av_clip_uint8(1.164 * (y - 16) + 1.596 * (cr - 128));
1325
1326 return (r << 16) | (g << 8) | b;
1327 }
1328
1329 static int mov_rewrite_dvd_sub_extradata(AVStream *st)
1330 {
1331 char buf[256] = {0};
1332 uint8_t *src = st->codec->extradata;
1333 int i;
1334
1335 if (st->codec->extradata_size != 64)
1336 return 0;
1337
1338 if (st->codec->width > 0 && st->codec->height > 0)
1339 snprintf(buf, sizeof(buf), "size: %dx%d\n",
1340 st->codec->width, st->codec->height);
1341 av_strlcat(buf, "palette: ", sizeof(buf));
1342
1343 for (i = 0; i < 16; i++) {
1344 uint32_t yuv = AV_RB32(src + i * 4);
1345 uint32_t rgba = yuv_to_rgba(yuv);
1346
1347 av_strlcatf(buf, sizeof(buf), "%06"PRIx32"%s", rgba, i != 15 ? ", " : "");
1348 }
1349
1350 if (av_strlcat(buf, "\n", sizeof(buf)) >= sizeof(buf))
1351 return 0;
1352
1353 av_freep(&st->codec->extradata);
1354 st->codec->extradata_size = 0;
1355 st->codec->extradata = av_mallocz(strlen(buf) + FF_INPUT_BUFFER_PADDING_SIZE);
1356 if (!st->codec->extradata)
1357 return AVERROR(ENOMEM);
1358 st->codec->extradata_size = strlen(buf);
1359 memcpy(st->codec->extradata, buf, st->codec->extradata_size);
1360
1361 return 0;
1362 }
1363
1364 static int mov_parse_stsd_data(MOVContext *c, AVIOContext *pb,
1365 AVStream *st, MOVStreamContext *sc,
1366 int size)
1367 {
1368 if (st->codec->codec_tag == MKTAG('t','m','c','d')) {
1369 st->codec->extradata_size = size;
1370 st->codec->extradata = av_malloc(size + FF_INPUT_BUFFER_PADDING_SIZE);
1371 if (!st->codec->extradata)
1372 return AVERROR(ENOMEM);
1373 avio_read(pb, st->codec->extradata, size);
1374 } else {
1375 /* other codec type, just skip (rtp, mp4s ...) */
1376 avio_skip(pb, size);
1377 }
1378 return 0;
1379 }
1380
1381 static int mov_finalize_stsd_codec(MOVContext *c, AVIOContext *pb,
1382 AVStream *st, MOVStreamContext *sc)
1383 {
1384 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
1385 !st->codec->sample_rate && sc->time_scale > 1)
1386 st->codec->sample_rate = sc->time_scale;
1387
1388 /* special codec parameters handling */
1389 switch (st->codec->codec_id) {
1390 #if CONFIG_DV_DEMUXER
1391 case AV_CODEC_ID_DVAUDIO:
1392 c->dv_fctx = avformat_alloc_context();
1393 c->dv_demux = avpriv_dv_init_demux(c->dv_fctx);
1394 if (!c->dv_demux) {
1395 av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n");
1396 return AVERROR(ENOMEM);
1397 }
1398 sc->dv_audio_container = 1;
1399 st->codec->codec_id = AV_CODEC_ID_PCM_S16LE;
1400 break;
1401 #endif
1402 /* no ifdef since parameters are always those */
1403 case AV_CODEC_ID_QCELP:
1404 st->codec->channels = 1;
1405 // force sample rate for qcelp when not stored in mov
1406 if (st->codec->codec_tag != MKTAG('Q','c','l','p'))
1407 st->codec->sample_rate = 8000;
1408 break;
1409 case AV_CODEC_ID_AMR_NB:
1410 st->codec->channels = 1;
1411 /* force sample rate for amr, stsd in 3gp does not store sample rate */
1412 st->codec->sample_rate = 8000;
1413 break;
1414 case AV_CODEC_ID_AMR_WB:
1415 st->codec->channels = 1;
1416 st->codec->sample_rate = 16000;
1417 break;
1418 case AV_CODEC_ID_MP2:
1419 case AV_CODEC_ID_MP3:
1420 /* force type after stsd for m1a hdlr */
1421 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
1422 st->need_parsing = AVSTREAM_PARSE_FULL;
1423 break;
1424 case AV_CODEC_ID_GSM:
1425 case AV_CODEC_ID_ADPCM_MS:
1426 case AV_CODEC_ID_ADPCM_IMA_WAV:
1427 case AV_CODEC_ID_ILBC:
1428 st->codec->block_align = sc->bytes_per_frame;
1429 break;
1430 case AV_CODEC_ID_ALAC:
1431 if (st->codec->extradata_size == 36) {
1432 st->codec->channels = AV_RB8 (st->codec->extradata + 21);
1433 st->codec->sample_rate = AV_RB32(st->codec->extradata + 32);
1434 }
1435 break;
1436 case AV_CODEC_ID_VC1:
1437 st->need_parsing = AVSTREAM_PARSE_FULL;
1438 break;
1439 default:
1440 break;
1441 }
1442 return 0;
1443 }
1444
1445 static int mov_skip_multiple_stsd(MOVContext *c, AVIOContext *pb,
1446 int codec_tag, int format,
1447 int size)
1448 {
1449 int video_codec_id = ff_codec_get_id(ff_codec_movvideo_tags, format);
1450
1451 if (codec_tag &&
1452 (codec_tag == AV_RL32("avc1") ||
1453 codec_tag == AV_RL32("hvc1") ||
1454 codec_tag == AV_RL32("hev1") ||
1455 (codec_tag != format &&
1456 (c->fc->video_codec_id ? video_codec_id != c->fc->video_codec_id
1457 : codec_tag != MKTAG('j','p','e','g'))))) {
1458 /* Multiple fourcc, we skip JPEG. This is not correct, we should
1459 * export it as a separate AVStream but this needs a few changes
1460 * in the MOV demuxer, patch welcome. */
1461
1462 av_log(c->fc, AV_LOG_WARNING, "multiple fourcc not supported\n");
1463 avio_skip(pb, size);
1464 return 1;
1465 }
1466
1467 return 0;
1468 }
1469
1470 int ff_mov_read_stsd_entries(MOVContext *c, AVIOContext *pb, int entries)
1471 {
1472 AVStream *st;
1473 MOVStreamContext *sc;
1474 int pseudo_stream_id;
1475
1476 if (c->fc->nb_streams < 1)
1477 return 0;
1478 st = c->fc->streams[c->fc->nb_streams-1];
1479 sc = st->priv_data;
1480
1481 for (pseudo_stream_id = 0;
1482 pseudo_stream_id < entries && !pb->eof_reached;
1483 pseudo_stream_id++) {
1484 //Parsing Sample description table
1485 enum AVCodecID id;
1486 int ret, dref_id = 1;
1487 MOVAtom a = { AV_RL32("stsd") };
1488 int64_t start_pos = avio_tell(pb);
1489 uint32_t size = avio_rb32(pb); /* size */
1490 uint32_t format = avio_rl32(pb); /* data format */
1491
1492 if (size >= 16) {
1493 avio_rb32(pb); /* reserved */
1494 avio_rb16(pb); /* reserved */
1495 dref_id = avio_rb16(pb);
1496 } else {
1497 av_log(c->fc, AV_LOG_ERROR, "invalid size %"PRIu32" in stsd\n", size);
1498 return AVERROR_INVALIDDATA;
1499 }
1500
1501 if (mov_skip_multiple_stsd(c, pb, st->codec->codec_tag, format,
1502 size - (avio_tell(pb) - start_pos)))
1503 continue;
1504
1505 sc->pseudo_stream_id = st->codec->codec_tag ? -1 : pseudo_stream_id;
1506 sc->dref_id= dref_id;
1507
1508 id = mov_codec_id(st, format);
1509
1510 av_dlog(c->fc, "size=%"PRIu32" 4CC= %"PRIu8"%"PRIu8"%"PRIu8"%"PRIu8" codec_type=%d\n", size,
1511 (format >> 0) & 0xff, (format >> 8) & 0xff, (format >> 16) & 0xff,
1512 (format >> 24) & 0xff, st->codec->codec_type);
1513
1514 if (st->codec->codec_type==AVMEDIA_TYPE_VIDEO) {
1515 st->codec->codec_id = id;
1516 mov_parse_stsd_video(c, pb, st, sc);
1517 } else if (st->codec->codec_type==AVMEDIA_TYPE_AUDIO) {
1518 st->codec->codec_id = id;
1519 mov_parse_stsd_audio(c, pb, st, sc);
1520 } else if (st->codec->codec_type==AVMEDIA_TYPE_SUBTITLE){
1521 st->codec->codec_id = id;
1522 mov_parse_stsd_subtitle(c, pb, st, sc,
1523 size - (avio_tell(pb) - start_pos));
1524 } else {
1525 ret = mov_parse_stsd_data(c, pb, st, sc,
1526 size - (avio_tell(pb) - start_pos));
1527 if (ret < 0)
1528 return ret;
1529 }
1530 /* this will read extra atoms at the end (wave, alac, damr, avcC, hvcC, SMI ...) */
1531 a.size = size - (avio_tell(pb) - start_pos);
1532 if (a.size > 8) {
1533 if ((ret = mov_read_default(c, pb, a)) < 0)
1534 return ret;
1535 } else if (a.size > 0)
1536 avio_skip(pb, a.size);
1537 }
1538
1539 if (pb->eof_reached)
1540 return AVERROR_EOF;
1541
1542 return mov_finalize_stsd_codec(c, pb, st, sc);
1543 }
1544
1545 static int mov_read_stsd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1546 {
1547 int entries;
1548
1549 avio_r8(pb); /* version */
1550 avio_rb24(pb); /* flags */
1551 entries = avio_rb32(pb);
1552
1553 return ff_mov_read_stsd_entries(c, pb, entries);
1554 }
1555
1556 static int mov_read_stsc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1557 {
1558 AVStream *st;
1559 MOVStreamContext *sc;
1560 unsigned int i, entries;
1561
1562 if (c->fc->nb_streams < 1)
1563 return 0;
1564 st = c->fc->streams[c->fc->nb_streams-1];
1565 sc = st->priv_data;
1566
1567 avio_r8(pb); /* version */
1568 avio_rb24(pb); /* flags */
1569
1570 entries = avio_rb32(pb);
1571
1572 av_dlog(c->fc, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);
1573
1574 if (!entries)
1575 return 0;
1576 if (entries >= UINT_MAX / sizeof(*sc->stsc_data))
1577 return AVERROR_INVALIDDATA;
1578 sc->stsc_data = av_malloc(entries * sizeof(*sc->stsc_data));
1579 if (!sc->stsc_data)
1580 return AVERROR(ENOMEM);
1581
1582 for (i = 0; i < entries && !pb->eof_reached; i++) {
1583 sc->stsc_data[i].first = avio_rb32(pb);
1584 sc->stsc_data[i].count = avio_rb32(pb);
1585 sc->stsc_data[i].id = avio_rb32(pb);
1586 }
1587
1588 sc->stsc_count = i;
1589
1590 if (pb->eof_reached)
1591 return AVERROR_EOF;
1592
1593 return 0;
1594 }
1595
1596 static int mov_read_stps(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1597 {
1598 AVStream *st;
1599 MOVStreamContext *sc;
1600 unsigned i, entries;
1601
1602 if (c->fc->nb_streams < 1)
1603 return 0;
1604 st = c->fc->streams[c->fc->nb_streams-1];
1605 sc = st->priv_data;
1606
1607 avio_rb32(pb); // version + flags
1608
1609 entries = avio_rb32(pb);
1610 if (entries >= UINT_MAX / sizeof(*sc->stps_data))
1611 return AVERROR_INVALIDDATA;
1612 sc->stps_data = av_malloc(entries * sizeof(*sc->stps_data));
1613 if (!sc->stps_data)
1614 return AVERROR(ENOMEM);
1615
1616 for (i = 0; i < entries && !pb->eof_reached; i++) {
1617 sc->stps_data[i] = avio_rb32(pb);
1618 //av_dlog(c->fc, "stps %d\n", sc->stps_data[i]);
1619 }
1620
1621 sc->stps_count = i;
1622
1623 if (pb->eof_reached)
1624 return AVERROR_EOF;
1625
1626 return 0;
1627 }
1628
1629 static int mov_read_stss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1630 {
1631 AVStream *st;
1632 MOVStreamContext *sc;
1633 unsigned int i, entries;
1634
1635 if (c->fc->nb_streams < 1)
1636 return 0;
1637 st = c->fc->streams[c->fc->nb_streams-1];
1638 sc = st->priv_data;
1639
1640 avio_r8(pb); /* version */
1641 avio_rb24(pb); /* flags */
1642
1643 entries = avio_rb32(pb);
1644
1645 av_dlog(c->fc, "keyframe_count = %d\n", entries);
1646
1647 if (!entries)
1648 {
1649 sc->keyframe_absent = 1;
1650 return 0;
1651 }
1652 if (entries >= UINT_MAX / sizeof(int))
1653 return AVERROR_INVALIDDATA;
1654 sc->keyframes = av_malloc(entries * sizeof(int));
1655 if (!sc->keyframes)
1656 return AVERROR(ENOMEM);
1657
1658 for (i = 0; i < entries && !pb->eof_reached; i++) {
1659 sc->keyframes[i] = avio_rb32(pb);
1660 //av_dlog(c->fc, "keyframes[]=%d\n", sc->keyframes[i]);
1661 }
1662
1663 sc->keyframe_count = i;
1664
1665 if (pb->eof_reached)
1666 return AVERROR_EOF;
1667
1668 return 0;
1669 }
1670
1671 static int mov_read_stsz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1672 {
1673 AVStream *st;
1674 MOVStreamContext *sc;
1675 unsigned int i, entries, sample_size, field_size, num_bytes;
1676 GetBitContext gb;
1677 unsigned char* buf;
1678
1679 if (c->fc->nb_streams < 1)
1680 return 0;
1681 st = c->fc->streams[c->fc->nb_streams-1];
1682 sc = st->priv_data;
1683
1684 avio_r8(pb); /* version */
1685 avio_rb24(pb); /* flags */
1686
1687 if (atom.type == MKTAG('s','t','s','z')) {
1688 sample_size = avio_rb32(pb);
1689 if (!sc->sample_size) /* do not overwrite value computed in stsd */
1690 sc->sample_size = sample_size;
1691 field_size = 32;
1692 } else {
1693 sample_size = 0;
1694 avio_rb24(pb); /* reserved */
1695 field_size = avio_r8(pb);
1696 }
1697 entries = avio_rb32(pb);
1698
1699 av_dlog(c->fc, "sample_size = %d sample_count = %d\n", sc->sample_size, entries);
1700
1701 sc->sample_count = entries;
1702 if (sample_size)
1703 return 0;
1704
1705 if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) {
1706 av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %d\n", field_size);
1707 return AVERROR_INVALIDDATA;
1708 }
1709
1710 if (!entries)
1711 return 0;
1712 if (entries >= UINT_MAX / sizeof(int) || entries >= (UINT_MAX - 4) / field_size)
1713 return AVERROR_INVALIDDATA;
1714 sc->sample_sizes = av_malloc(entries * sizeof(int));
1715 if (!sc->sample_sizes)
1716 return AVERROR(ENOMEM);
1717
1718 num_bytes = (entries*field_size+4)>>3;
1719
1720 buf = av_malloc(num_bytes+FF_INPUT_BUFFER_PADDING_SIZE);
1721 if (!buf) {
1722 av_freep(&sc->sample_sizes);
1723 return AVERROR(ENOMEM);
1724 }
1725
1726 if (avio_read(pb, buf, num_bytes) < num_bytes) {
1727 av_freep(&sc->sample_sizes);
1728 av_free(buf);
1729 return AVERROR_INVALIDDATA;
1730 }
1731
1732 init_get_bits(&gb, buf, 8*num_bytes);
1733
1734 for (i = 0; i < entries && !pb->eof_reached; i++) {
1735 sc->sample_sizes[i] = get_bits_long(&gb, field_size);
1736 sc->data_size += sc->sample_sizes[i];
1737 }
1738
1739 sc->sample_count = i;
1740
1741 if (pb->eof_reached)
1742 return AVERROR_EOF;
1743
1744 av_free(buf);
1745 return 0;
1746 }
1747
1748 static int mov_read_stts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1749 {
1750 AVStream *st;
1751 MOVStreamContext *sc;
1752 unsigned int i, entries;
1753 int64_t duration=0;
1754 int64_t total_sample_count=0;
1755
1756 if (c->fc->nb_streams < 1)
1757 return 0;
1758 st = c->fc->streams[c->fc->nb_streams-1];
1759 sc = st->priv_data;
1760
1761 avio_r8(pb); /* version */
1762 avio_rb24(pb); /* flags */
1763 entries = avio_rb32(pb);
1764
1765 av_dlog(c->fc, "track[%i].stts.entries = %i\n",
1766 c->fc->nb_streams-1, entries);
1767
1768 if (!entries)
1769 return 0;
1770 if (entries >= UINT_MAX / sizeof(*sc->stts_data))
1771 return AVERROR(EINVAL);
1772
1773 av_free(sc->stts_data);
1774 sc->stts_data = av_malloc(entries * sizeof(*sc->stts_data));
1775 if (!sc->stts_data)
1776 return AVERROR(ENOMEM);
1777
1778 for (i = 0; i < entries && !pb->eof_reached; i++) {
1779 int sample_duration;
1780 int sample_count;
1781
1782 sample_count=avio_rb32(pb);
1783 sample_duration = avio_rb32(pb);
1784 if (sample_count < 0) {
1785 av_log(c->fc, AV_LOG_ERROR, "Invalid sample_count=%d\n", sample_count);
1786 return AVERROR_INVALIDDATA;
1787 }
1788 sc->stts_data[i].count= sample_count;
1789 sc->stts_data[i].duration= sample_duration;
1790
1791 av_dlog(c->fc, "sample_count=%d, sample_duration=%d\n",
1792 sample_count, sample_duration);
1793
1794 duration+=(int64_t)sample_duration*sample_count;
1795 total_sample_count+=sample_count;
1796 }
1797
1798 sc->stts_count = i;
1799
1800 if (pb->eof_reached)
1801 return AVERROR_EOF;
1802
1803 st->nb_frames= total_sample_count;
1804 if (duration)
1805 st->duration= duration;
1806 sc->track_end = duration;
1807 return 0;
1808 }
1809
1810 static int mov_read_ctts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1811 {
1812 AVStream *st;
1813 MOVStreamContext *sc;
1814 unsigned int i, entries;
1815
1816 if (c->fc->nb_streams < 1)
1817 return 0;
1818 st = c->fc->streams[c->fc->nb_streams-1];
1819 sc = st->priv_data;
1820
1821 avio_r8(pb); /* version */
1822 avio_rb24(pb); /* flags */
1823 entries = avio_rb32(pb);
1824
1825 av_dlog(c->fc, "track[%i].ctts.entries = %i\n", c->fc->nb_streams-1, entries);
1826
1827 if (!entries)
1828 return 0;
1829 if (entries >= UINT_MAX / sizeof(*sc->ctts_data))
1830 return AVERROR_INVALIDDATA;
1831 sc->ctts_data = av_malloc(entries * sizeof(*sc->ctts_data));
1832 if (!sc->ctts_data)
1833 return AVERROR(ENOMEM);
1834
1835 for (i = 0; i < entries && !pb->eof_reached; i++) {
1836 int count =avio_rb32(pb);
1837 int duration =avio_rb32(pb);
1838
1839 sc->ctts_data[i].count = count;
1840 sc->ctts_data[i].duration= duration;
1841 if (duration < 0)
1842 sc->dts_shift = FFMAX(sc->dts_shift, -duration);
1843 }
1844
1845 sc->ctts_count = i;
1846
1847 if (pb->eof_reached)
1848 return AVERROR_EOF;
1849
1850 av_dlog(c->fc, "dts shift %d\n", sc->dts_shift);
1851
1852 return 0;
1853 }
1854
1855 static int mov_read_sbgp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1856 {
1857 AVStream *st;
1858 MOVStreamContext *sc;
1859 unsigned int i, entries;
1860 uint8_t version;
1861 uint32_t grouping_type;
1862
1863 if (c->fc->nb_streams < 1)
1864 return 0;
1865 st = c->fc->streams[c->fc->nb_streams-1];
1866 sc = st->priv_data;
1867
1868 version = avio_r8(pb); /* version */
1869 avio_rb24(pb); /* flags */
1870 grouping_type = avio_rl32(pb);
1871 if (grouping_type != MKTAG( 'r','a','p',' '))
1872 return 0; /* only support 'rap ' grouping */
1873 if (version == 1)
1874 avio_rb32(pb); /* grouping_type_parameter */
1875
1876 entries = avio_rb32(pb);
1877 if (!entries)
1878 return 0;
1879 if (entries >= UINT_MAX / sizeof(*sc->rap_group))
1880 return AVERROR_INVALIDDATA;
1881 sc->rap_group = av_malloc(entries * sizeof(*sc->rap_group));
1882 if (!sc->rap_group)
1883 return AVERROR(ENOMEM);
1884
1885 for (i = 0; i < entries && !pb->eof_reached; i++) {
1886 sc->rap_group[i].count = avio_rb32(pb); /* sample_count */
1887 sc->rap_group[i].index = avio_rb32(pb); /* group_description_index */
1888 }
1889
1890 sc->rap_group_count = i;
1891
1892 return pb->eof_reached ? AVERROR_EOF : 0;
1893 }
1894
1895 static void mov_build_index(MOVContext *mov, AVStream *st)
1896 {
1897 MOVStreamContext *sc = st->priv_data;
1898 int64_t current_offset;
1899 int64_t current_dts = 0;
1900 unsigned int stts_index = 0;
1901 unsigned int stsc_index = 0;
1902 unsigned int stss_index = 0;
1903 unsigned int stps_index = 0;
1904 unsigned int i, j;
1905 uint64_t stream_size = 0;
1906
1907 /* adjust first dts according to edit list */
1908 if (sc->time_offset && mov->time_scale > 0) {
1909 if (sc->time_offset < 0)
1910 sc->time_offset = av_rescale(sc->time_offset, sc->time_scale, mov->time_scale);
1911 current_dts = -sc->time_offset;
1912 if (sc->ctts_data && sc->stts_data && sc->stts_data[0].duration &&
1913 sc->ctts_data[0].duration / sc->stts_data[0].duration > 16) {
1914 /* more than 16 frames delay, dts are likely wrong
1915 this happens with files created by iMovie */
1916 sc->wrong_dts = 1;
1917 st->codec->has_b_frames = 1;
1918 }
1919 }
1920
1921 /* only use old uncompressed audio chunk demuxing when stts specifies it */
1922 if (!(st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
1923 sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
1924 unsigned int current_sample = 0;
1925 unsigned int stts_sample = 0;
1926 unsigned int sample_size;
1927 unsigned int distance = 0;
1928 unsigned int rap_group_index = 0;
1929 unsigned int rap_group_sample = 0;
1930 int rap_group_present = sc->rap_group_count && sc->rap_group;
1931 int key_off = (sc->keyframes && sc->keyframes[0] > 0) || (sc->stps_data && sc->stps_data[0] > 0);
1932
1933 current_dts -= sc->dts_shift;
1934
1935 if (!sc->sample_count)
1936 return;
1937 if (sc->sample_count >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
1938 return;
1939 if (av_reallocp_array(&st->index_entries,
1940 st->nb_index_entries + sc->sample_count,
1941 sizeof(*st->index_entries)) < 0) {
1942 st->nb_index_entries = 0;
1943 return;
1944 }
1945 st->index_entries_allocated_size = (st->nb_index_entries + sc->sample_count) * sizeof(*st->index_entries);
1946
1947 for (i = 0; i < sc->chunk_count; i++) {
1948 current_offset = sc->chunk_offsets[i];
1949 while (stsc_index + 1 < sc->stsc_count &&
1950 i + 1 == sc->stsc_data[stsc_index + 1].first)
1951 stsc_index++;
1952 for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
1953 int keyframe = 0;
1954 if (current_sample >= sc->sample_count) {
1955 av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
1956 return;
1957 }
1958
1959 if (!sc->keyframe_absent && (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index])) {
1960 keyframe = 1;
1961 if (stss_index + 1 < sc->keyframe_count)
1962 stss_index++;
1963 } else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) {
1964 keyframe = 1;
1965 if (stps_index + 1 < sc->stps_count)
1966 stps_index++;
1967 }
1968 if (rap_group_present && rap_group_index < sc->rap_group_count) {
1969 if (sc->rap_group[rap_group_index].index > 0)
1970 keyframe = 1;
1971 if (++rap_group_sample == sc->rap_group[rap_group_index].count) {
1972 rap_group_sample = 0;
1973 rap_group_index++;
1974 }
1975 }
1976 if (keyframe)
1977 distance = 0;
1978 sample_size = sc->sample_size > 0 ? sc->sample_size : sc->sample_sizes[current_sample];
1979 if (sc->pseudo_stream_id == -1 ||
1980 sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
1981 AVIndexEntry *e = &st->index_entries[st->nb_index_entries++];
1982 e->pos = current_offset;
1983 e->timestamp = current_dts;
1984 e->size = sample_size;
1985 e->min_distance = distance;
1986 e->flags = keyframe ? AVINDEX_KEYFRAME : 0;
1987 av_dlog(mov->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
1988 "size %d, distance %d, keyframe %d\n", st->index, current_sample,
1989 current_offset, current_dts, sample_size, distance, keyframe);
1990 }
1991
1992 current_offset += sample_size;
1993 stream_size += sample_size;
1994 current_dts += sc->stts_data[stts_index].duration;
1995 distance++;
1996 stts_sample++;
1997 current_sample++;
1998 if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
1999 stts_sample = 0;
2000 stts_index++;
2001 }
2002 }
2003 }
2004 if (st->duration > 0)
2005 st->codec->bit_rate = stream_size*8*sc->time_scale/st->duration;
2006 } else {
2007 unsigned chunk_samples, total = 0;
2008
2009 // compute total chunk count
2010 for (i = 0; i < sc->stsc_count; i++) {
2011 unsigned count, chunk_count;
2012
2013 chunk_samples = sc->stsc_data[i].count;
2014 if (i != sc->stsc_count - 1 &&
2015 sc->samples_per_frame && chunk_samples % sc->samples_per_frame) {
2016 av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n");
2017 return;
2018 }
2019
2020 if (sc->samples_per_frame >= 160) { // gsm
2021 count = chunk_samples / sc->samples_per_frame;
2022 } else if (sc->samples_per_frame > 1) {
2023 unsigned samples = (1024/sc->samples_per_frame)*sc->samples_per_frame;
2024 count = (chunk_samples+samples-1) / samples;
2025 } else {
2026 count = (chunk_samples+1023) / 1024;
2027 }
2028
2029 if (i < sc->stsc_count - 1)
2030 chunk_count = sc->stsc_data[i+1].first - sc->stsc_data[i].first;
2031 else
2032 chunk_count = sc->chunk_count - (sc->stsc_data[i].first - 1);
2033 total += chunk_count * count;
2034 }
2035
2036 av_dlog(mov->fc, "chunk count %d\n", total);
2037 if (total >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
2038 return;
2039 if (av_reallocp_array(&st->index_entries,
2040 st->nb_index_entries + total,
2041 sizeof(*st->index_entries)) < 0) {
2042 st->nb_index_entries = 0;
2043 return;
2044 }
2045 st->index_entries_allocated_size = (st->nb_index_entries + total) * sizeof(*st->index_entries);
2046
2047 // populate index
2048 for (i = 0; i < sc->chunk_count; i++) {
2049 current_offset = sc->chunk_offsets[i];
2050 if (stsc_index + 1 < sc->stsc_count &&
2051 i + 1 == sc->stsc_data[stsc_index + 1].first)
2052 stsc_index++;
2053 chunk_samples = sc->stsc_data[stsc_index].count;
2054
2055 while (chunk_samples > 0) {
2056 AVIndexEntry *e;
2057 unsigned size, samples;
2058
2059 if (sc->samples_per_frame >= 160) { // gsm
2060 samples = sc->samples_per_frame;
2061 size = sc->bytes_per_frame;
2062 } else {
2063 if (sc->samples_per_frame > 1) {
2064 samples = FFMIN((1024 / sc->samples_per_frame)*
2065 sc->samples_per_frame, chunk_samples);
2066 size = (samples / sc->samples_per_frame) * sc->bytes_per_frame;
2067 } else {
2068 samples = FFMIN(1024, chunk_samples);
2069 size = samples * sc->sample_size;
2070 }
2071 }
2072
2073 if (st->nb_index_entries >= total) {
2074 av_log(mov->fc, AV_LOG_ERROR, "wrong chunk count %d\n", total);
2075 return;
2076 }
2077 e = &st->index_entries[st->nb_index_entries++];
2078 e->pos = current_offset;
2079 e->timestamp = current_dts;
2080 e->size = size;
2081 e->min_distance = 0;
2082 e->flags = AVINDEX_KEYFRAME;
2083 av_dlog(mov->fc, "AVIndex stream %d, chunk %d, offset %"PRIx64", dts %"PRId64", "
2084 "size %d, duration %d\n", st->index, i, current_offset, current_dts,
2085 size, samples);
2086
2087 current_offset += size;
2088 current_dts += samples;
2089 chunk_samples -= samples;
2090 }
2091 }
2092 }
2093 }
2094
2095 static int mov_open_dref(AVIOContext **pb, char *src, MOVDref *ref,
2096 AVIOInterruptCB *int_cb)
2097 {
2098 /* try relative path, we do not try the absolute because it can leak information about our
2099 system to an attacker */
2100 if (ref->nlvl_to > 0 && ref->nlvl_from > 0) {
2101 char filename[1024];
2102 char *src_path;
2103 int i, l;
2104
2105 /* find a source dir */
2106 src_path = strrchr(src, '/');
2107 if (src_path)
2108 src_path++;
2109 else
2110 src_path = src;
2111
2112 /* find a next level down to target */
2113 for (i = 0, l = strlen(ref->path) - 1; l >= 0; l--)
2114 if (ref->path[l] == '/') {
2115 if (i == ref->nlvl_to - 1)
2116 break;
2117 else
2118 i++;
2119 }
2120
2121 /* compose filename if next level down to target was found */
2122 if (i == ref->nlvl_to - 1 && src_path - src < sizeof(filename)) {
2123 memcpy(filename, src, src_path - src);
2124 filename[src_path - src] = 0;
2125
2126 for (i = 1; i < ref->nlvl_from; i++)
2127 av_strlcat(filename, "../", 1024);
2128
2129 av_strlcat(filename, ref->path + l + 1, 1024);
2130
2131 if (!avio_open2(pb, filename, AVIO_FLAG_READ, int_cb, NULL))
2132 return 0;
2133 }
2134 }
2135
2136 return AVERROR(ENOENT);
2137 }
2138
2139 static int mov_read_trak(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2140 {
2141 AVStream *st;
2142 MOVStreamContext *sc;
2143 int ret;
2144
2145 st = avformat_new_stream(c->fc, NULL);
2146 if (!st) return AVERROR(ENOMEM);
2147 st->id = c->fc->nb_streams;
2148 sc = av_mallocz(sizeof(MOVStreamContext));
2149 if (!sc) return AVERROR(ENOMEM);
2150
2151 st->priv_data = sc;
2152 st->codec->codec_type = AVMEDIA_TYPE_DATA;
2153 sc->ffindex = st->index;
2154
2155 if ((ret = mov_read_default(c, pb, atom)) < 0)
2156 return ret;
2157
2158 /* sanity checks */
2159 if (sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
2160 (!sc->sample_size && !sc->sample_count))) {
2161 av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
2162 st->index);
2163 return 0;
2164 }
2165
2166 if (sc->time_scale <= 0) {
2167 av_log(c->fc, AV_LOG_WARNING, "stream %d, timescale not set\n", st->index);
2168 sc->time_scale = c->time_scale;
2169 if (sc->time_scale <= 0)
2170 sc->time_scale = 1;
2171 }
2172
2173 avpriv_set_pts_info(st, 64, 1, sc->time_scale);
2174
2175 mov_build_index(c, st);
2176
2177 if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
2178 MOVDref *dref = &sc->drefs[sc->dref_id - 1];
2179 if (mov_open_dref(&sc->pb, c->fc->filename, dref, &c->fc->interrupt_callback) < 0)
2180 av_log(c->fc, AV_LOG_ERROR,
2181 "stream %d, error opening alias: path='%s', dir='%s', "
2182 "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d\n",
2183 st->index, dref->path, dref->dir, dref->filename,
2184 dref->volume, dref->nlvl_from, dref->nlvl_to);
2185 } else
2186 sc->pb = c->fc->pb;
2187
2188 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
2189 if (!st->sample_aspect_ratio.num &&
2190 (st->codec->width != sc->width || st->codec->height != sc->height)) {
2191 st->sample_aspect_ratio = av_d2q(((double)st->codec->height * sc->width) /
2192 ((double)st->codec->width * sc->height), INT_MAX);
2193 }
2194 }
2195
2196 // done for ai5q, ai52, ai55, ai1q, ai12 and ai15.
2197 if (!st->codec->extradata_size && st->codec->codec_id == AV_CODEC_ID_H264 &&
2198 TAG_IS_AVCI(st->codec->codec_tag)) {
2199 ret = ff_generate_avci_extradata(st);
2200 if (ret < 0)
2201 return ret;
2202 }
2203
2204 switch (st->codec->codec_id) {
2205 #if CONFIG_H261_DECODER
2206 case AV_CODEC_ID_H261:
2207 #endif
2208 #if CONFIG_H263_DECODER
2209 case AV_CODEC_ID_H263:
2210 #endif
2211 #if CONFIG_MPEG4_DECODER
2212 case AV_CODEC_ID_MPEG4:
2213 #endif
2214 st->codec->width = 0; /* let decoder init width/height */
2215 st->codec->height= 0;
2216 break;
2217 }
2218
2219 /* Do not need those anymore. */
2220 av_freep(&sc->chunk_offsets);
2221 av_freep(&sc->stsc_data);
2222 av_freep(&sc->sample_sizes);
2223 av_freep(&sc->keyframes);
2224 av_freep(&sc->stts_data);
2225 av_freep(&sc->stps_data);
2226 av_freep(&sc->rap_group);
2227
2228 return 0;
2229 }
2230
2231 static int mov_read_ilst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2232 {
2233 int ret;
2234 c->itunes_metadata = 1;
2235 ret = mov_read_default(c, pb, atom);
2236 c->itunes_metadata = 0;
2237 return ret;
2238 }
2239
2240 static int mov_read_replaygain(MOVContext *c, AVIOContext *pb, int size)
2241 {
2242 int64_t end = avio_tell(pb) + size;
2243 uint8_t *key = NULL, *val = NULL;
2244 int i;
2245
2246 for (i = 0; i < 2; i++) {
2247 uint8_t **p;
2248 uint32_t len, tag;
2249
2250 if (end - avio_tell(pb) <= 12)
2251 break;
2252
2253 len = avio_rb32(pb);
2254 tag = avio_rl32(pb);
2255 avio_skip(pb, 4); // flags
2256
2257 if (len < 12 || len - 12 > end - avio_tell(pb))
2258 break;
2259 len -= 12;
2260
2261 if (tag == MKTAG('n', 'a', 'm', 'e'))
2262 p = &key;
2263 else if (tag == MKTAG('d', 'a', 't', 'a') && len > 4) {
2264 avio_skip(pb, 4);
2265 len -= 4;
2266 p = &val;
2267 } else
2268 break;
2269
2270 *p = av_malloc(len + 1);
2271 if (!*p)
2272 break;
2273 avio_read(pb, *p, len);
2274 (*p)[len] = 0;
2275 }
2276
2277 if (key && val) {
2278 av_dict_set(&c->fc->metadata, key, val,
2279 AV_DICT_DONT_STRDUP_KEY | AV_DICT_DONT_STRDUP_VAL);
2280 key = val = NULL;
2281 }
2282
2283 avio_seek(pb, end, SEEK_SET);
2284 av_freep(&key);
2285 av_freep(&val);
2286 return 0;
2287 }
2288
2289 static int mov_read_custom(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2290 {
2291 int64_t end = avio_tell(pb) + atom.size;
2292 uint32_t tag, len;
2293
2294 if (atom.size < 8)
2295 goto fail;
2296
2297 len = avio_rb32(pb);
2298 tag = avio_rl32(pb);
2299
2300 if (len > atom.size)
2301 goto fail;
2302
2303 if (tag == MKTAG('m', 'e', 'a', 'n') && len > 12) {
2304 uint8_t domain[128];
2305 int domain_len;
2306
2307 avio_skip(pb, 4); // flags
2308 len -= 12;
2309
2310 domain_len = avio_get_str(pb, len, domain, sizeof(domain));
2311 avio_skip(pb, len - domain_len);
2312 if (!strcmp(domain, "org.hydrogenaudio.replaygain"))
2313 return mov_read_replaygain(c, pb, end - avio_tell(pb));
2314 }
2315
2316 fail:
2317 av_log(c->fc, AV_LOG_VERBOSE,
2318 "Unhandled or malformed custom metadata of size %"PRId64"\n", atom.size);
2319 return 0;
2320 }
2321
2322 static int mov_read_meta(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2323 {
2324 while (atom.size > 8) {
2325 uint32_t tag = avio_rl32(pb);
2326 atom.size -= 4;
2327 if (tag == MKTAG('h','d','l','r')) {
2328 avio_seek(pb, -8, SEEK_CUR);
2329 atom.size += 8;
2330 return mov_read_default(c, pb, atom);
2331 }
2332 }
2333 return 0;
2334 }
2335
2336 static int mov_read_tkhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2337 {
2338 int i;
2339 int width;
2340 int height;
2341 int64_t disp_transform[2];
2342 int display_matrix[3][2];
2343 AVStream *st;
2344 MOVStreamContext *sc;
2345 int version;
2346 int flags;
2347
2348 if (c->fc->nb_streams < 1)
2349 return 0;
2350 st = c->fc->streams[c->fc->nb_streams-1];
2351 sc = st->priv_data;
2352
2353 version = avio_r8(pb);
2354 flags = avio_rb24(pb);
2355 st->disposition |= (flags & MOV_TKHD_FLAG_ENABLED) ? AV_DISPOSITION_DEFAULT : 0;
2356
2357 if (version == 1) {
2358 avio_rb64(pb);
2359 avio_rb64(pb);
2360 } else {
2361 avio_rb32(pb); /* creation time */
2362 avio_rb32(pb); /* modification time */
2363 }
2364 st->id = (int)avio_rb32(pb); /* track id (NOT 0 !)*/
2365 avio_rb32(pb); /* reserved */
2366
2367 /* highlevel (considering edits) duration in movie timebase */
2368 (version == 1) ? avio_rb64(pb) : avio_rb32(pb);
2369 avio_rb32(pb); /* reserved */
2370 avio_rb32(pb); /* reserved */
2371
2372 avio_rb16(pb); /* layer */
2373 avio_rb16(pb); /* alternate group */
2374 avio_rb16(pb); /* volume */
2375 avio_rb16(pb); /* reserved */
2376
2377 //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
2378 // they're kept in fixed point format through all calculations
2379 // ignore u,v,z b/c we don't need the scale factor to calc aspect ratio
2380 for (i = 0; i < 3; i++) {
2381 display_matrix[i][0] = avio_rb32(pb); // 16.16 fixed point
2382 display_matrix[i][1] = avio_rb32(pb); // 16.16 fixed point
2383 avio_rb32(pb); // 2.30 fixed point (not used)
2384 }
2385
2386 width = avio_rb32(pb); // 16.16 fixed point track width
2387 height = avio_rb32(pb); // 16.16 fixed point track height
2388 sc->width = width >> 16;
2389 sc->height = height >> 16;
2390
2391 // transform the display width/height according to the matrix
2392 // skip this if the display matrix is the default identity matrix
2393 // or if it is rotating the picture, ex iPhone 3GS
2394 // to keep the same scale, use [width height 1<<16]
2395 if (width && height &&
2396 ((display_matrix[0][0] != 65536 ||
2397 display_matrix[1][1] != 65536) &&
2398 !display_matrix[0][1] &&
2399 !display_matrix[1][0] &&
2400 !display_matrix[2][0] && !display_matrix[2][1])) {
2401 for (i = 0; i < 2; i++)
2402 disp_transform[i] =
2403 (int64_t) width * display_matrix[0][i] +
2404 (int64_t) height * display_matrix[1][i] +
2405 ((int64_t) display_matrix[2][i] << 16);
2406
2407 //sample aspect ratio is new width/height divided by old width/height
2408 st->sample_aspect_ratio = av_d2q(
2409 ((double) disp_transform[0] * height) /
2410 ((double) disp_transform[1] * width), INT_MAX);
2411 }
2412 return 0;
2413 }
2414
2415 static int mov_read_tfhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2416 {
2417 MOVFragment *frag = &c->fragment;
2418 MOVTrackExt *trex = NULL;
2419 int flags, track_id, i;
2420
2421 avio_r8(pb); /* version */
2422 flags = avio_rb24(pb);
2423
2424 track_id = avio_rb32(pb);
2425 if (!track_id)
2426 return AVERROR_INVALIDDATA;
2427 frag->track_id = track_id;
2428 for (i = 0; i < c->trex_count; i++)
2429 if (c->trex_data[i].track_id == frag->track_id) {
2430 trex = &c->trex_data[i];
2431 break;
2432 }
2433 if (!trex) {
2434 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
2435 return AVERROR_INVALIDDATA;
2436 }
2437
2438 frag->base_data_offset = flags & MOV_TFHD_BASE_DATA_OFFSET ?
2439 avio_rb64(pb) : frag->moof_offset;
2440 frag->stsd_id = flags & MOV_TFHD_STSD_ID ? avio_rb32(pb) : trex->stsd_id;
2441
2442 frag->duration = flags & MOV_TFHD_DEFAULT_DURATION ?
2443 avio_rb32(pb) : trex->duration;
2444 frag->size = flags & MOV_TFHD_DEFAULT_SIZE ?
2445 avio_rb32(pb) : trex->size;
2446 frag->flags = flags & MOV_TFHD_DEFAULT_FLAGS ?
2447 avio_rb32(pb) : trex->flags;
2448 av_dlog(c->fc, "frag flags 0x%x\n", frag->flags);
2449 return 0;
2450 }
2451
2452 static int mov_read_chap(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2453 {
2454 c->chapter_track = avio_rb32(pb);
2455 return 0;
2456 }
2457
2458 static int mov_read_trex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2459 {
2460 MOVTrackExt *trex;
2461 int err;
2462
2463 if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
2464 return AVERROR_INVALIDDATA;
2465 if ((err = av_reallocp_array(&c->trex_data, c->trex_count + 1,
2466 sizeof(*c->trex_data))) < 0) {
2467 c->trex_count = 0;
2468 return err;
2469 }
2470 trex = &c->trex_data[c->trex_count++];
2471 avio_r8(pb); /* version */
2472 avio_rb24(pb); /* flags */
2473 trex->track_id = avio_rb32(pb);
2474 trex->stsd_id = avio_rb32(pb);
2475 trex->duration = avio_rb32(pb);
2476 trex->size = avio_rb32(pb);
2477 trex->flags = avio_rb32(pb);
2478 return 0;
2479 }
2480
2481 static int mov_read_trun(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2482 {
2483 MOVFragment *frag = &c->fragment;
2484 AVStream *st = NULL;
2485 MOVStreamContext *sc;
2486 MOVStts *ctts_data;
2487 uint64_t offset;
2488 int64_t dts;
2489 int data_offset = 0;
2490 unsigned entries, first_sample_flags = frag->flags;
2491 int flags, distance, i, found_keyframe = 0, err;
2492
2493 for (i = 0; i < c->fc->nb_streams; i++) {
2494 if (c->fc->streams[i]->id == frag->track_id) {
2495 st = c->fc->streams[i];
2496 break;
2497 }
2498 }
2499 if (!st) {
2500 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
2501 return AVERROR_INVALIDDATA;
2502 }
2503 sc = st->priv_data;
2504 if (sc->pseudo_stream_id+1 != frag->stsd_id)
2505 return 0;
2506 avio_r8(pb); /* version */
2507 flags = avio_rb24(pb);
2508 entries = avio_rb32(pb);
2509 av_dlog(c->fc, "flags 0x%x entries %d\n", flags, entries);
2510
2511 /* Always assume the presence of composition time offsets.
2512 * Without this assumption, for instance, we cannot deal with a track in fragmented movies that meet the following.
2513 * 1) in the initial movie, there are no samples.
2514 * 2) in the first movie fragment, there is only one sample without composition time offset.
2515 * 3) in the subsequent movie fragments, there are samples with composition time offset. */
2516 if (!sc->ctts_count && sc->sample_count)
2517 {
2518 /* Complement ctts table if moov atom doesn't have ctts atom. */
2519 ctts_data = av_realloc(NULL, sizeof(*sc->ctts_data));
2520 if (!ctts_data)
2521 return AVERROR(ENOMEM);
2522 sc->ctts_data = ctts_data;
2523 sc->ctts_data[sc->ctts_count].count = sc->sample_count;
2524 sc->ctts_data[sc->ctts_count].duration = 0;
2525 sc->ctts_count++;
2526 }
2527 if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
2528 return AVERROR_INVALIDDATA;
2529 if ((err = av_reallocp_array(&sc->ctts_data, entries + sc->ctts_count,
2530 sizeof(*sc->ctts_data))) < 0) {
2531 sc->ctts_count = 0;
2532 return err;
2533 }
2534 if (flags & MOV_TRUN_DATA_OFFSET) data_offset = avio_rb32(pb);
2535 if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS) first_sample_flags = avio_rb32(pb);
2536 dts = sc->track_end - sc->time_offset;
2537 offset = frag->base_data_offset + data_offset;
2538 distance = 0;
2539 av_dlog(c->fc, "first sample flags 0x%x\n", first_sample_flags);
2540 for (i = 0; i < entries && !pb->eof_reached; i++) {
2541 unsigned sample_size = frag->size;
2542 int sample_flags = i ? frag->flags : first_sample_flags;
2543 unsigned sample_duration = frag->duration;
2544 int keyframe = 0;
2545
2546 if (flags & MOV_TRUN_SAMPLE_DURATION) sample_duration = avio_rb32(pb);
2547 if (flags & MOV_TRUN_SAMPLE_SIZE) sample_size = avio_rb32(pb);
2548 if (flags & MOV_TRUN_SAMPLE_FLAGS) sample_flags = avio_rb32(pb);
2549 sc->ctts_data[sc->ctts_count].count = 1;
2550 sc->ctts_data[sc->ctts_count].duration = (flags & MOV_TRUN_SAMPLE_CTS) ?
2551 avio_rb32(pb) : 0;
2552 sc->ctts_count++;
2553 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
2554 keyframe = 1;
2555 else if (!found_keyframe)
2556 keyframe = found_keyframe =
2557 !(sample_flags & (MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC |
2558 MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES));
2559 if (keyframe)
2560 distance = 0;
2561 av_add_index_entry(st, offset, dts, sample_size, distance,
2562 keyframe ? AVINDEX_KEYFRAME : 0);
2563 av_dlog(c->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
2564 "size %d, distance %d, keyframe %d\n", st->index, sc->sample_count+i,
2565 offset, dts, sample_size, distance, keyframe);
2566 distance++;
2567 dts += sample_duration;
2568 offset += sample_size;
2569 sc->data_size += sample_size;
2570 }
2571
2572 if (pb->eof_reached)
2573 return AVERROR_EOF;
2574
2575 frag->moof_offset = offset;
2576 st->duration = sc->track_end = dts + sc->time_offset;
2577 return 0;
2578 }
2579
2580 /* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
2581 /* like the files created with Adobe Premiere 5.0, for samples see */
2582 /* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
2583 static int mov_read_wide(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2584 {
2585 int err;
2586
2587 if (atom.size < 8)
2588 return 0; /* continue */
2589 if (avio_rb32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
2590 avio_skip(pb, atom.size - 4);
2591 return 0;
2592 }
2593 atom.type = avio_rl32(pb);
2594 atom.size -= 8;
2595 if (atom.type != MKTAG('m','d','a','t')) {
2596 avio_skip(pb, atom.size);
2597 return 0;
2598 }
2599 err = mov_read_mdat(c, pb, atom);
2600 return err;
2601 }
2602
2603 static int mov_read_cmov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2604 {
2605 #if CONFIG_ZLIB
2606 AVIOContext ctx;
2607 uint8_t *cmov_data;
2608 uint8_t *moov_data; /* uncompressed data */
2609 long cmov_len, moov_len;
2610 int ret = -1;
2611
2612 avio_rb32(pb); /* dcom atom */
2613 if (avio_rl32(pb) != MKTAG('d','c','o','m'))
2614 return AVERROR_INVALIDDATA;
2615 if (avio_rl32(pb) != MKTAG('z','l','i','b')) {
2616 av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !");
2617 return AVERROR_INVALIDDATA;
2618 }
2619 avio_rb32(pb); /* cmvd atom */
2620 if (avio_rl32(pb) != MKTAG('c','m','v','d'))
2621 return AVERROR_INVALIDDATA;
2622 moov_len = avio_rb32(pb); /* uncompressed size */
2623 cmov_len = atom.size - 6 * 4;
2624
2625 cmov_data = av_malloc(cmov_len);
2626 if (!cmov_data)
2627 return AVERROR(ENOMEM);
2628 moov_data = av_malloc(moov_len);
2629 if (!moov_data) {
2630 av_free(cmov_data);
2631 return AVERROR(ENOMEM);
2632 }
2633 avio_read(pb, cmov_data, cmov_len);
2634 if (uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
2635 goto free_and_return;
2636 if (ffio_init_context(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
2637 goto free_and_return;
2638 atom.type = MKTAG('m','o','o','v');
2639 atom.size = moov_len;
2640 ret = mov_read_default(c, &ctx, atom);
2641 free_and_return:
2642 av_free(moov_data);
2643 av_free(cmov_data);
2644 return ret;
2645 #else
2646 av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
2647 return AVERROR(ENOSYS);
2648 #endif
2649 }
2650
2651 /* edit list atom */
2652 static int mov_read_elst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2653 {
2654 MOVStreamContext *sc;
2655 int i, edit_count, version;
2656
2657 if (c->fc->nb_streams < 1)
2658 return 0;
2659 sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
2660
2661 version = avio_r8(pb); /* version */
2662 avio_rb24(pb); /* flags */
2663 edit_count = avio_rb32(pb); /* entries */
2664
2665 if ((uint64_t)edit_count*12+8 > atom.size)
2666 return AVERROR_INVALIDDATA;
2667
2668 for (i=0; i<edit_count; i++){
2669 int64_t time;
2670 int64_t duration;
2671 if (version == 1) {
2672 duration = avio_rb64(pb);
2673 time = avio_rb64(pb);
2674 } else {
2675 duration = avio_rb32(pb); /* segment duration */
2676 time = (int32_t)avio_rb32(pb); /* media time */
2677 }
2678 avio_rb32(pb); /* Media rate */
2679 if (i == 0 && time >= -1) {
2680 sc->time_offset = time != -1 ? time : -duration;
2681 }
2682 }
2683
2684 if (edit_count > 1)
2685 av_log(c->fc, AV_LOG_WARNING, "multiple edit list entries, "
2686 "a/v desync might occur, patch welcome\n");
2687
2688 av_dlog(c->fc, "track[%i].edit_count = %i\n", c->fc->nb_streams-1, edit_count);
2689 return 0;
2690 }
2691
2692 static const MOVParseTableEntry mov_default_parse_table[] = {
2693 { MKTAG('a','v','s','s'), mov_read_extradata },
2694 { MKTAG('c','h','p','l'), mov_read_chpl },
2695 { MKTAG('c','o','6','4'), mov_read_stco },
2696 { MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
2697 { MKTAG('d','i','n','f'), mov_read_default },
2698 { MKTAG('d','r','e','f'), mov_read_dref },
2699 { MKTAG('e','d','t','s'), mov_read_default },
2700 { MKTAG('e','l','s','t'), mov_read_elst },
2701 { MKTAG('e','n','d','a'), mov_read_enda },
2702 { MKTAG('f','i','e','l'), mov_read_fiel },
2703 { MKTAG('f','t','y','p'), mov_read_ftyp },
2704 { MKTAG('g','l','b','l'), mov_read_glbl },
2705 { MKTAG('h','d','l','r'), mov_read_hdlr },
2706 { MKTAG('i','l','s','t'), mov_read_ilst },
2707 { MKTAG('j','p','2','h'), mov_read_extradata },
2708 { MKTAG('m','d','a','t'), mov_read_mdat },
2709 { MKTAG('m','d','h','d'), mov_read_mdhd },
2710 { MKTAG('m','d','i','a'), mov_read_default },
2711 { MKTAG('m','e','t','a'), mov_read_meta },
2712 { MKTAG('m','i','n','f'), mov_read_default },
2713 { MKTAG('m','o','o','f'), mov_read_moof },
2714 { MKTAG('m','o','o','v'), mov_read_moov },
2715 { MKTAG('m','v','e','x'), mov_read_default },
2716 { MKTAG('m','v','h','d'), mov_read_mvhd },
2717 { MKTAG('S','M','I',' '), mov_read_smi }, /* Sorenson extension ??? */
2718 { MKTAG('a','l','a','c'), mov_read_extradata }, /* alac specific atom */
2719 { MKTAG('a','v','c','C'), mov_read_glbl },
2720 { MKTAG('p','a','s','p'), mov_read_pasp },
2721 { MKTAG('s','t','b','l'), mov_read_default },
2722 { MKTAG('s','t','c','o'), mov_read_stco },
2723 { MKTAG('s','t','p','s'), mov_read_stps },
2724 { MKTAG('s','t','r','f'), mov_read_strf },
2725 { MKTAG('s','t','s','c'), mov_read_stsc },
2726 { MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
2727 { MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
2728 { MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
2729 { MKTAG('s','t','t','s'), mov_read_stts },
2730 { MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */
2731 { MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
2732 { MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
2733 { MKTAG('t','r','a','k'), mov_read_trak },
2734 { MKTAG('t','r','a','f'), mov_read_default },
2735 { MKTAG('t','r','e','f'), mov_read_default },
2736 { MKTAG('c','h','a','p'), mov_read_chap },
2737 { MKTAG('t','r','e','x'), mov_read_trex },
2738 { MKTAG('t','r','u','n'), mov_read_trun },
2739 { MKTAG('u','d','t','a'), mov_read_default },
2740 { MKTAG('w','a','v','e'), mov_read_wave },
2741 { MKTAG('e','s','d','s'), mov_read_esds },
2742 { MKTAG('d','a','c','3'), mov_read_dac3 }, /* AC-3 info */
2743 { MKTAG('d','e','c','3'), mov_read_dec3 }, /* EAC-3 info */
2744 { MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
2745 { MKTAG('w','f','e','x'), mov_read_wfex },
2746 { MKTAG('c','m','o','v'), mov_read_cmov },
2747 { MKTAG('c','h','a','n'), mov_read_chan }, /* channel layout */
2748 { MKTAG('d','v','c','1'), mov_read_dvc1 },
2749 { MKTAG('s','b','g','p'), mov_read_sbgp },
2750 { MKTAG('h','v','c','C'), mov_read_glbl },
2751 { MKTAG('-','-','-','-'), mov_read_custom },
2752 { 0, NULL }
2753 };
2754
2755 static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2756 {
2757 int64_t total_size = 0;
2758 MOVAtom a;
2759 int i;
2760
2761 if (atom.size < 0)
2762 atom.size = INT64_MAX;
2763 while (total_size + 8 < atom.size && !pb->eof_reached) {
2764 int (*parse)(MOVContext*, AVIOContext*, MOVAtom) = NULL;
2765 a.size = atom.size;
2766 a.type=0;
2767 if (atom.size >= 8) {
2768 a.size = avio_rb32(pb);
2769 a.type = avio_rl32(pb);
2770 }
2771 av_dlog(c->fc, "type: %08x '%.4s' parent:'%.4s' sz: %"PRId64" %"PRId64" %"PRId64"\n",
2772 a.type, (char*)&a.type, (char*)&atom.type, a.size, total_size, atom.size);
2773 total_size += 8;
2774 if (a.size == 1) { /* 64 bit extended size */
2775 a.size = avio_rb64(pb) - 8;
2776 total_size += 8;
2777 }
2778 if (a.size == 0) {
2779 a.size = atom.size - total_size;
2780 if (a.size <= 8)
2781 break;
2782 }
2783 a.size -= 8;
2784 if (a.size < 0)
2785 break;
2786 a.size = FFMIN(a.size, atom.size - total_size);
2787
2788 for (i = 0; mov_default_parse_table[i].type; i++)
2789 if (mov_default_parse_table[i].type == a.type) {
2790 parse = mov_default_parse_table[i].parse;
2791 break;
2792 }
2793
2794 // container is user data
2795 if (!parse && (atom.type == MKTAG('u','d','t','a') ||
2796 atom.type == MKTAG('i','l','s','t')))
2797 parse = mov_read_udta_string;
2798
2799 if (!parse) { /* skip leaf atoms data */
2800 avio_skip(pb, a.size);
2801 } else {
2802 int64_t start_pos = avio_tell(pb);
2803 int64_t left;
2804 int err = parse(c, pb, a);
2805 if (err < 0)
2806 return err;
2807 if (c->found_moov && c->found_mdat &&
2808 ((!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX) ||
2809 start_pos + a.size == avio_size(pb))) {
2810 if (!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX)
2811 c->next_root_atom = start_pos + a.size;
2812 return 0;
2813 }
2814 left = a.size - avio_tell(pb) + start_pos;
2815 if (left > 0) /* skip garbage at atom end */
2816 avio_skip(pb, left);
2817 else if (left < 0) {
2818 av_log(c->fc, AV_LOG_WARNING,
2819 "overread end of atom '%.4s' by %"PRId64" bytes\n",
2820 (char*)&a.type, -left);
2821 avio_seek(pb, left, SEEK_CUR);
2822 }
2823 }
2824
2825 total_size += a.size;
2826 }
2827
2828 if (total_size < atom.size && atom.size < 0x7ffff)
2829 avio_skip(pb, atom.size - total_size);
2830
2831 return 0;
2832 }
2833
2834 static int mov_probe(AVProbeData *p)
2835 {
2836 unsigned int offset;
2837 uint32_t tag;
2838 int score = 0;
2839
2840 /* check file header */
2841 offset = 0;
2842 for (;;) {
2843 /* ignore invalid offset */
2844 if ((offset + 8) > (unsigned int)p->buf_size)
2845 return score;
2846 tag = AV_RL32(p->buf + offset + 4);
2847 switch(tag) {
2848 /* check for obvious tags */
2849 case MKTAG('j','P',' ',' '): /* jpeg 2000 signature */
2850 case MKTAG('m','o','o','v'):
2851 case MKTAG('m','d','a','t'):
2852 case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
2853 case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
2854 case MKTAG('f','t','y','p'):
2855 return AVPROBE_SCORE_MAX;
2856 /* those are more common words, so rate then a bit less */
2857 case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
2858 case MKTAG('w','i','d','e'):
2859 case MKTAG('f','r','e','e'):
2860 case MKTAG('j','u','n','k'):
2861 case MKTAG('p','i','c','t'):
2862 return AVPROBE_SCORE_MAX - 5;
2863 case MKTAG(0x82,0x82,0x7f,0x7d):
2864 case MKTAG('s','k','i','p'):
2865 case MKTAG('u','u','i','d'):
2866 case MKTAG('p','r','f','l'):
2867 offset = AV_RB32(p->buf+offset) + offset;
2868 /* if we only find those cause probedata is too small at least rate them */
2869 score = AVPROBE_SCORE_EXTENSION;
2870 break;
2871 default:
2872 /* unrecognized tag */
2873 return score;
2874 }
2875 }
2876 }
2877
2878 // must be done after parsing all trak because there's no order requirement
2879 static void mov_read_chapters(AVFormatContext *s)
2880 {
2881 MOVContext *mov = s->priv_data;
2882 AVStream *st = NULL;
2883 MOVStreamContext *sc;
2884 int64_t cur_pos;
2885 int i;
2886
2887 for (i = 0; i < s->nb_streams; i++)
2888 if (s->streams[i]->id == mov->chapter_track) {
2889 st = s->streams[i];
2890 break;
2891 }
2892 if (!st) {
2893 av_log(s, AV_LOG_ERROR, "Referenced QT chapter track not found\n");
2894 return;
2895 }
2896
2897 st->discard = AVDISCARD_ALL;
2898 sc = st->priv_data;
2899 cur_pos = avio_tell(sc->pb);
2900
2901 for (i = 0; i < st->nb_index_entries; i++) {
2902 AVIndexEntry *sample = &st->index_entries[i];
2903 int64_t end = i+1 < st->nb_index_entries ? st->index_entries[i+1].timestamp : st->duration;
2904 uint8_t *title;
2905 uint16_t ch;
2906 int len, title_len;
2907
2908 if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
2909 av_log(s, AV_LOG_ERROR, "Chapter %d not found in file\n", i);
2910 goto finish;
2911 }
2912
2913 // the first two bytes are the length of the title
2914 len = avio_rb16(sc->pb);
2915 if (len > sample->size-2)
2916 continue;
2917 title_len = 2*len + 1;
2918 if (!(title = av_mallocz(title_len)))
2919 goto finish;
2920
2921 // The samples could theoretically be in any encoding if there's an encd
2922 // atom following, but in practice are only utf-8 or utf-16, distinguished
2923 // instead by the presence of a BOM
2924 if (!len) {
2925 title[0] = 0;
2926 } else {
2927 ch = avio_rb16(sc->pb);
2928 if (ch == 0xfeff)
2929 avio_get_str16be(sc->pb, len, title, title_len);
2930 else if (ch == 0xfffe)
2931 avio_get_str16le(sc->pb, len, title, title_len);
2932 else {
2933 AV_WB16(title, ch);
2934 if (len == 1 || len == 2)
2935 title[len] = 0;
2936 else
2937 avio_get_str(sc->pb, len - 2, title + 2, title_len - 2);
2938 }
2939 }
2940
2941 avpriv_new_chapter(s, i, st->time_base, sample->timestamp, end, title);
2942 av_freep(&title);
2943 }
2944 finish:
2945 avio_seek(sc->pb, cur_pos, SEEK_SET);
2946 }
2947
2948 static int mov_read_close(AVFormatContext *s)
2949 {
2950 MOVContext *mov = s->priv_data;
2951 int i, j;
2952
2953 for (i = 0; i