3 * Copyright (c) 2001 Fabrice Bellard
4 * Copyright (c) 2009 Baptiste Coudurier <baptiste dot coudurier at gmail dot com>
6 * first version by Francois Revol <revol@free.fr>
7 * seek function by Gael Chardon <gael.dev@4now.net>
9 * This file is part of Libav.
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.
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.
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
30 #include "libavutil/attributes.h"
31 #include "libavutil/channel_layout.h"
32 #include "libavutil/intreadwrite.h"
33 #include "libavutil/intfloat.h"
34 #include "libavutil/mathematics.h"
35 #include "libavutil/time_internal.h"
36 #include "libavutil/avstring.h"
37 #include "libavutil/dict.h"
38 #include "libavutil/opt.h"
39 #include "libavcodec/ac3tab.h"
42 #include "avio_internal.h"
45 #include "libavcodec/get_bits.h"
48 #include "replaygain.h"
54 #include "qtpalette.h"
57 /* those functions parse an atom */
58 /* links atom IDs to parse functions */
59 typedef struct MOVParseTableEntry {
61 int (*parse)(MOVContext *ctx, AVIOContext *pb, MOVAtom atom);
64 static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom);
66 static int mov_metadata_track_or_disc_number(MOVContext *c, AVIOContext *pb,
67 unsigned len, const char *key)
71 short current, total = 0;
72 avio_rb16(pb); // unknown
73 current = avio_rb16(pb);
75 total = avio_rb16(pb);
77 snprintf(buf, sizeof(buf), "%d", current);
79 snprintf(buf, sizeof(buf), "%d/%d", current, total);
80 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
81 av_dict_set(&c->fc->metadata, key, buf, 0);
86 static int mov_metadata_int8_bypass_padding(MOVContext *c, AVIOContext *pb,
87 unsigned len, const char *key)
91 /* bypass padding bytes */
96 snprintf(buf, sizeof(buf), "%d", avio_r8(pb));
97 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
98 av_dict_set(&c->fc->metadata, key, buf, 0);
103 static int mov_metadata_int8_no_padding(MOVContext *c, AVIOContext *pb,
104 unsigned len, const char *key)
108 snprintf(buf, sizeof(buf), "%d", avio_r8(pb));
109 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
110 av_dict_set(&c->fc->metadata, key, buf, 0);
115 static int mov_metadata_gnre(MOVContext *c, AVIOContext *pb,
116 unsigned len, const char *key)
121 avio_r8(pb); // unknown
124 if (genre < 1 || genre > ID3v1_GENRE_MAX)
126 snprintf(buf, sizeof(buf), "%s", ff_id3v1_genre_str[genre-1]);
127 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
128 av_dict_set(&c->fc->metadata, key, buf, 0);
133 static const uint32_t mac_to_unicode[128] = {
134 0x00C4,0x00C5,0x00C7,0x00C9,0x00D1,0x00D6,0x00DC,0x00E1,
135 0x00E0,0x00E2,0x00E4,0x00E3,0x00E5,0x00E7,0x00E9,0x00E8,
136 0x00EA,0x00EB,0x00ED,0x00EC,0x00EE,0x00EF,0x00F1,0x00F3,
137 0x00F2,0x00F4,0x00F6,0x00F5,0x00FA,0x00F9,0x00FB,0x00FC,
138 0x2020,0x00B0,0x00A2,0x00A3,0x00A7,0x2022,0x00B6,0x00DF,
139 0x00AE,0x00A9,0x2122,0x00B4,0x00A8,0x2260,0x00C6,0x00D8,
140 0x221E,0x00B1,0x2264,0x2265,0x00A5,0x00B5,0x2202,0x2211,
141 0x220F,0x03C0,0x222B,0x00AA,0x00BA,0x03A9,0x00E6,0x00F8,
142 0x00BF,0x00A1,0x00AC,0x221A,0x0192,0x2248,0x2206,0x00AB,
143 0x00BB,0x2026,0x00A0,0x00C0,0x00C3,0x00D5,0x0152,0x0153,
144 0x2013,0x2014,0x201C,0x201D,0x2018,0x2019,0x00F7,0x25CA,
145 0x00FF,0x0178,0x2044,0x20AC,0x2039,0x203A,0xFB01,0xFB02,
146 0x2021,0x00B7,0x201A,0x201E,0x2030,0x00C2,0x00CA,0x00C1,
147 0x00CB,0x00C8,0x00CD,0x00CE,0x00CF,0x00CC,0x00D3,0x00D4,
148 0xF8FF,0x00D2,0x00DA,0x00DB,0x00D9,0x0131,0x02C6,0x02DC,
149 0x00AF,0x02D8,0x02D9,0x02DA,0x00B8,0x02DD,0x02DB,0x02C7,
152 static int mov_read_mac_string(MOVContext *c, AVIOContext *pb, int len,
153 char *dst, int dstlen)
156 char *end = dst+dstlen-1;
159 for (i = 0; i < len; i++) {
160 uint8_t t, c = avio_r8(pb);
161 if (c < 0x80 && p < end)
164 PUT_UTF8(mac_to_unicode[c-0x80], t, if (p < end) *p++ = t;);
170 static int mov_read_covr(MOVContext *c, AVIOContext *pb, int type, int len)
174 MOVStreamContext *sc;
179 case 0xd: id = AV_CODEC_ID_MJPEG; break;
180 case 0xe: id = AV_CODEC_ID_PNG; break;
181 case 0x1b: id = AV_CODEC_ID_BMP; break;
183 av_log(c->fc, AV_LOG_WARNING, "Unknown cover type: 0x%x.\n", type);
188 st = avformat_new_stream(c->fc, NULL);
190 return AVERROR(ENOMEM);
191 sc = av_mallocz(sizeof(*sc));
193 return AVERROR(ENOMEM);
196 ret = av_get_packet(pb, &pkt, len);
200 if (pkt.size >= 8 && id != AV_CODEC_ID_BMP) {
201 if (AV_RB64(pkt.data) == 0x89504e470d0a1a0a) {
202 id = AV_CODEC_ID_PNG;
204 id = AV_CODEC_ID_MJPEG;
208 st->disposition |= AV_DISPOSITION_ATTACHED_PIC;
210 st->attached_pic = pkt;
211 st->attached_pic.stream_index = st->index;
212 st->attached_pic.flags |= AV_PKT_FLAG_KEY;
214 st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
215 st->codecpar->codec_id = id;
220 static int mov_metadata_loci(MOVContext *c, AVIOContext *pb, unsigned len)
222 char language[4] = { 0 };
224 uint16_t langcode = 0;
225 double longitude, latitude;
226 const char *key = "location";
228 if (len < 4 + 2 + 1 + 1 + 4 + 4 + 4)
229 return AVERROR_INVALIDDATA;
231 avio_skip(pb, 4); // version+flags
232 langcode = avio_rb16(pb);
233 ff_mov_lang_to_iso639(langcode, language);
236 len -= avio_get_str(pb, len, buf, sizeof(buf)); // place name
238 return AVERROR_INVALIDDATA;
239 avio_skip(pb, 1); // role
243 return AVERROR_INVALIDDATA;
244 longitude = ((int32_t) avio_rb32(pb)) / (float) (1 << 16);
245 latitude = ((int32_t) avio_rb32(pb)) / (float) (1 << 16);
247 // Try to output in the same format as the ?xyz field
248 snprintf(buf, sizeof(buf), "%+08.4f%+09.4f/", latitude, longitude);
249 if (*language && strcmp(language, "und")) {
251 snprintf(key2, sizeof(key2), "%s-%s", key, language);
252 av_dict_set(&c->fc->metadata, key2, buf, 0);
254 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
255 return av_dict_set(&c->fc->metadata, key, buf, 0);
258 static int mov_read_udta_string(MOVContext *c, AVIOContext *pb, MOVAtom atom)
261 char *str, key2[32], language[4] = {0};
262 const char *key = NULL;
263 uint16_t langcode = 0;
264 uint32_t data_type = 0, str_size, str_size_alloc;
265 int (*parse)(MOVContext*, AVIOContext*, unsigned, const char*) = NULL;
269 case MKTAG( '@','P','R','M'): key = "premiere_version"; raw = 1; break;
270 case MKTAG( '@','P','R','Q'): key = "quicktime_version"; raw = 1; break;
271 case MKTAG( 'X','M','P','_'):
272 if (c->export_xmp) { key = "xmp"; raw = 1; } break;
273 case MKTAG( 'a','A','R','T'): key = "album_artist"; break;
274 case MKTAG( 'a','k','I','D'): key = "account_type";
275 parse = mov_metadata_int8_no_padding; break;
276 case MKTAG( 'a','p','I','D'): key = "account_id"; break;
277 case MKTAG( 'c','a','t','g'): key = "category"; break;
278 case MKTAG( 'c','p','i','l'): key = "compilation";
279 parse = mov_metadata_int8_no_padding; break;
280 case MKTAG( 'c','p','r','t'): key = "copyright"; break;
281 case MKTAG( 'd','e','s','c'): key = "description"; break;
282 case MKTAG( 'd','i','s','k'): key = "disc";
283 parse = mov_metadata_track_or_disc_number; break;
284 case MKTAG( 'e','g','i','d'): key = "episode_uid";
285 parse = mov_metadata_int8_no_padding; break;
286 case MKTAG( 'g','n','r','e'): key = "genre";
287 parse = mov_metadata_gnre; break;
288 case MKTAG( 'h','d','v','d'): key = "hd_video";
289 parse = mov_metadata_int8_no_padding; break;
290 case MKTAG( 'k','e','y','w'): key = "keywords"; break;
291 case MKTAG( 'l','d','e','s'): key = "synopsis"; break;
292 case MKTAG( 'l','o','c','i'):
293 return mov_metadata_loci(c, pb, atom.size);
294 case MKTAG( 'p','c','s','t'): key = "podcast";
295 parse = mov_metadata_int8_no_padding; break;
296 case MKTAG( 'p','g','a','p'): key = "gapless_playback";
297 parse = mov_metadata_int8_no_padding; break;
298 case MKTAG( 'p','u','r','d'): key = "purchase_date"; break;
299 case MKTAG( 'r','t','n','g'): key = "rating";
300 parse = mov_metadata_int8_no_padding; break;
301 case MKTAG( 's','o','a','a'): key = "sort_album_artist"; break;
302 case MKTAG( 's','o','a','l'): key = "sort_album"; break;
303 case MKTAG( 's','o','a','r'): key = "sort_artist"; break;
304 case MKTAG( 's','o','c','o'): key = "sort_composer"; break;
305 case MKTAG( 's','o','n','m'): key = "sort_name"; break;
306 case MKTAG( 's','o','s','n'): key = "sort_show"; break;
307 case MKTAG( 's','t','i','k'): key = "media_type";
308 parse = mov_metadata_int8_no_padding; break;
309 case MKTAG( 't','r','k','n'): key = "track";
310 parse = mov_metadata_track_or_disc_number; break;
311 case MKTAG( 't','v','e','n'): key = "episode_id"; break;
312 case MKTAG( 't','v','e','s'): key = "episode_sort";
313 parse = mov_metadata_int8_bypass_padding; break;
314 case MKTAG( 't','v','n','n'): key = "network"; break;
315 case MKTAG( 't','v','s','h'): key = "show"; break;
316 case MKTAG( 't','v','s','n'): key = "season_number";
317 parse = mov_metadata_int8_bypass_padding; break;
318 case MKTAG(0xa9,'A','R','T'): key = "artist"; break;
319 case MKTAG(0xa9,'P','R','D'): key = "producer"; break;
320 case MKTAG(0xa9,'a','l','b'): key = "album"; break;
321 case MKTAG(0xa9,'a','u','t'): key = "artist"; break;
322 case MKTAG(0xa9,'c','h','p'): key = "chapter"; break;
323 case MKTAG(0xa9,'c','m','t'): key = "comment"; break;
324 case MKTAG(0xa9,'c','o','m'): key = "composer"; break;
325 case MKTAG(0xa9,'c','p','y'): key = "copyright"; break;
326 case MKTAG(0xa9,'d','a','y'): key = "date"; break;
327 case MKTAG(0xa9,'d','i','r'): key = "director"; break;
328 case MKTAG(0xa9,'d','i','s'): key = "disclaimer"; break;
329 case MKTAG(0xa9,'e','d','1'): key = "edit_date"; break;
330 case MKTAG(0xa9,'e','n','c'): key = "encoder"; break;
331 case MKTAG(0xa9,'f','m','t'): key = "original_format"; break;
332 case MKTAG(0xa9,'g','e','n'): key = "genre"; break;
333 case MKTAG(0xa9,'g','r','p'): key = "grouping"; break;
334 case MKTAG(0xa9,'h','s','t'): key = "host_computer"; break;
335 case MKTAG(0xa9,'i','n','f'): key = "comment"; break;
336 case MKTAG(0xa9,'l','y','r'): key = "lyrics"; break;
337 case MKTAG(0xa9,'m','a','k'): key = "make"; break;
338 case MKTAG(0xa9,'m','o','d'): key = "model"; break;
339 case MKTAG(0xa9,'n','a','m'): key = "title"; break;
340 case MKTAG(0xa9,'o','p','e'): key = "original_artist"; break;
341 case MKTAG(0xa9,'p','r','d'): key = "producer"; break;
342 case MKTAG(0xa9,'p','r','f'): key = "performers"; break;
343 case MKTAG(0xa9,'r','e','q'): key = "playback_requirements"; break;
344 case MKTAG(0xa9,'s','r','c'): key = "original_source"; break;
345 case MKTAG(0xa9,'s','t','3'): key = "subtitle"; break;
346 case MKTAG(0xa9,'s','w','r'): key = "encoder"; break;
347 case MKTAG(0xa9,'t','o','o'): key = "encoder"; break;
348 case MKTAG(0xa9,'t','r','k'): key = "track"; break;
349 case MKTAG(0xa9,'u','r','l'): key = "URL"; break;
350 case MKTAG(0xa9,'w','r','n'): key = "warning"; break;
351 case MKTAG(0xa9,'w','r','t'): key = "composer"; break;
352 case MKTAG(0xa9,'x','y','z'): key = "location"; break;
355 if (c->itunes_metadata && atom.size > 8) {
356 int data_size = avio_rb32(pb);
357 int tag = avio_rl32(pb);
358 if (tag == MKTAG('d','a','t','a')) {
359 data_type = avio_rb32(pb); // type
360 avio_rb32(pb); // unknown
361 str_size = data_size - 16;
364 if (atom.type == MKTAG('c', 'o', 'v', 'r')) {
365 int ret = mov_read_covr(c, pb, data_type, str_size);
367 av_log(c->fc, AV_LOG_ERROR, "Error parsing cover art.\n");
372 } else if (atom.size > 4 && key && !c->itunes_metadata && !raw) {
373 str_size = avio_rb16(pb); // string length
374 langcode = avio_rb16(pb);
375 ff_mov_lang_to_iso639(langcode, language);
378 str_size = atom.size;
380 if (c->export_all && !key) {
381 snprintf(tmp_key, 5, "%.4s", (char*)&atom.type);
388 return AVERROR_INVALIDDATA;
390 // allocate twice as much as worst-case
391 str_size_alloc = (raw ? str_size : str_size * 2) + 1;
392 str = av_malloc(str_size_alloc);
394 return AVERROR(ENOMEM);
397 parse(c, pb, str_size, key);
399 if (!raw && (data_type == 3 || (data_type == 0 && (langcode < 0x400 || langcode == 0x7fff)))) { // MAC Encoded
400 mov_read_mac_string(c, pb, str_size, str, str_size_alloc);
402 int ret = ffio_read_size(pb, str, str_size);
409 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
410 av_dict_set(&c->fc->metadata, key, str, 0);
411 if (*language && strcmp(language, "und")) {
412 snprintf(key2, sizeof(key2), "%s-%s", key, language);
413 av_dict_set(&c->fc->metadata, key2, str, 0);
416 av_log(c->fc, AV_LOG_TRACE, "lang \"%3s\" ", language);
417 av_log(c->fc, AV_LOG_TRACE, "tag \"%s\" value \"%s\" atom \"%.4s\" %d %"PRId64"\n",
418 key, str, (char*)&atom.type, str_size_alloc, atom.size);
424 static int mov_read_chpl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
427 int i, nb_chapters, str_len, version;
431 if ((atom.size -= 5) < 0)
434 version = avio_r8(pb);
437 avio_rb32(pb); // ???
438 nb_chapters = avio_r8(pb);
440 for (i = 0; i < nb_chapters; i++) {
444 start = avio_rb64(pb);
445 str_len = avio_r8(pb);
447 if ((atom.size -= 9+str_len) < 0)
450 ret = ffio_read_size(pb, str, str_len);
454 avpriv_new_chapter(c->fc, i, (AVRational){1,10000000}, start, AV_NOPTS_VALUE, str);
459 #define MIN_DATA_ENTRY_BOX_SIZE 12
460 static int mov_read_dref(MOVContext *c, AVIOContext *pb, MOVAtom atom)
463 MOVStreamContext *sc;
466 if (c->fc->nb_streams < 1)
468 st = c->fc->streams[c->fc->nb_streams-1];
471 avio_rb32(pb); // version + flags
472 entries = avio_rb32(pb);
474 entries > (atom.size - 1) / MIN_DATA_ENTRY_BOX_SIZE + 1 ||
475 entries >= UINT_MAX / sizeof(*sc->drefs))
476 return AVERROR_INVALIDDATA;
479 sc->drefs = av_mallocz(entries * sizeof(*sc->drefs));
481 return AVERROR(ENOMEM);
482 sc->drefs_count = entries;
484 for (i = 0; i < entries; i++) {
485 MOVDref *dref = &sc->drefs[i];
486 uint32_t size = avio_rb32(pb);
487 int64_t next = avio_tell(pb) + size - 4;
490 return AVERROR_INVALIDDATA;
492 dref->type = avio_rl32(pb);
493 avio_rb32(pb); // version + flags
494 av_log(c->fc, AV_LOG_TRACE, "type %.4s size %d\n", (char*)&dref->type, size);
496 if (dref->type == MKTAG('a','l','i','s') && size > 150) {
497 /* macintosh alias record */
498 uint16_t volume_len, len;
504 volume_len = avio_r8(pb);
505 volume_len = FFMIN(volume_len, 27);
506 ret = ffio_read_size(pb, dref->volume, 27);
509 dref->volume[volume_len] = 0;
510 av_log(c->fc, AV_LOG_DEBUG, "volume %s, len %d\n", dref->volume, volume_len);
515 len = FFMIN(len, 63);
516 ret = ffio_read_size(pb, dref->filename, 63);
519 dref->filename[len] = 0;
520 av_log(c->fc, AV_LOG_DEBUG, "filename %s, len %d\n", dref->filename, len);
524 /* read next level up_from_alias/down_to_target */
525 dref->nlvl_from = avio_rb16(pb);
526 dref->nlvl_to = avio_rb16(pb);
527 av_log(c->fc, AV_LOG_DEBUG, "nlvl from %d, nlvl to %d\n",
528 dref->nlvl_from, dref->nlvl_to);
532 for (type = 0; type != -1 && avio_tell(pb) < next; ) {
535 type = avio_rb16(pb);
537 av_log(c->fc, AV_LOG_DEBUG, "type %d, len %d\n", type, len);
540 if (type == 2) { // absolute path
542 dref->path = av_mallocz(len+1);
544 return AVERROR(ENOMEM);
546 ret = ffio_read_size(pb, dref->path, len);
548 av_freep(&dref->path);
551 if (len > volume_len && !strncmp(dref->path, dref->volume, volume_len)) {
553 memmove(dref->path, dref->path+volume_len, len);
556 // trim string of any ending zeros
557 for (j = len - 1; j >= 0; j--) {
558 if (dref->path[j] == 0)
563 for (j = 0; j < len; j++)
564 if (dref->path[j] == ':' || dref->path[j] == 0)
566 av_log(c->fc, AV_LOG_DEBUG, "path %s\n", dref->path);
567 } else if (type == 0) { // directory name
569 dref->dir = av_malloc(len+1);
571 return AVERROR(ENOMEM);
573 ret = ffio_read_size(pb, dref->dir, len);
575 av_freep(&dref->dir);
579 for (j = 0; j < len; j++)
580 if (dref->dir[j] == ':')
582 av_log(c->fc, AV_LOG_DEBUG, "dir %s\n", dref->dir);
587 av_log(c->fc, AV_LOG_DEBUG, "Unknown dref type 0x08%x size %d\n",
592 avio_seek(pb, next, SEEK_SET);
597 static int mov_read_hdlr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
601 uint32_t av_unused ctype;
606 if (c->fc->nb_streams < 1) // meta before first trak
609 st = c->fc->streams[c->fc->nb_streams-1];
611 avio_r8(pb); /* version */
612 avio_rb24(pb); /* flags */
615 ctype = avio_rl32(pb);
616 type = avio_rl32(pb); /* component subtype */
618 av_log(c->fc, AV_LOG_TRACE, "ctype= %.4s (0x%08x)\n", (char*)&ctype, ctype);
619 av_log(c->fc, AV_LOG_TRACE, "stype= %.4s\n", (char*)&type);
621 if (type == MKTAG('v','i','d','e'))
622 st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
623 else if (type == MKTAG('s','o','u','n'))
624 st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
625 else if (type == MKTAG('m','1','a',' '))
626 st->codecpar->codec_id = AV_CODEC_ID_MP2;
627 else if ((type == MKTAG('s','u','b','p')) || (type == MKTAG('c','l','c','p')))
628 st->codecpar->codec_type = AVMEDIA_TYPE_SUBTITLE;
630 avio_rb32(pb); /* component manufacture */
631 avio_rb32(pb); /* component flags */
632 avio_rb32(pb); /* component flags mask */
634 title_size = atom.size - 24;
635 if (title_size > 0) {
636 title_str = av_malloc(title_size + 1); /* Add null terminator */
638 return AVERROR(ENOMEM);
640 ret = ffio_read_size(pb, title_str, title_size);
642 av_freep(&title_str);
645 title_str[title_size] = 0;
647 int off = (!c->isom && title_str[0] == title_size - 1);
648 av_dict_set(&st->metadata, "handler_name", title_str + off, 0);
650 av_freep(&title_str);
656 int ff_mov_read_esds(AVFormatContext *fc, AVIOContext *pb)
661 if (fc->nb_streams < 1)
663 st = fc->streams[fc->nb_streams-1];
665 avio_rb32(pb); /* version + flags */
666 ff_mp4_read_descr(fc, pb, &tag);
667 if (tag == MP4ESDescrTag) {
668 ff_mp4_parse_es_descr(pb, NULL);
670 avio_rb16(pb); /* ID */
672 ff_mp4_read_descr(fc, pb, &tag);
673 if (tag == MP4DecConfigDescrTag)
674 ff_mp4_read_dec_config_descr(fc, st, pb);
678 static int mov_read_esds(MOVContext *c, AVIOContext *pb, MOVAtom atom)
680 return ff_mov_read_esds(c->fc, pb);
683 static int mov_read_dac3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
686 enum AVAudioServiceType *ast;
687 int ac3info, acmod, lfeon, bsmod;
689 if (c->fc->nb_streams < 1)
691 st = c->fc->streams[c->fc->nb_streams-1];
693 ast = (enum AVAudioServiceType*)av_stream_new_side_data(st, AV_PKT_DATA_AUDIO_SERVICE_TYPE,
696 return AVERROR(ENOMEM);
698 ac3info = avio_rb24(pb);
699 bsmod = (ac3info >> 14) & 0x7;
700 acmod = (ac3info >> 11) & 0x7;
701 lfeon = (ac3info >> 10) & 0x1;
702 st->codecpar->channels = ((int[]){2,1,2,3,3,4,4,5})[acmod] + lfeon;
703 st->codecpar->channel_layout = avpriv_ac3_channel_layout_tab[acmod];
705 st->codecpar->channel_layout |= AV_CH_LOW_FREQUENCY;
707 if (st->codecpar->channels > 1 && bsmod == 0x7)
708 *ast = AV_AUDIO_SERVICE_TYPE_KARAOKE;
710 #if FF_API_LAVF_AVCTX
711 FF_DISABLE_DEPRECATION_WARNINGS
712 st->codec->audio_service_type = *ast;
713 FF_ENABLE_DEPRECATION_WARNINGS
719 static int mov_read_dec3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
722 enum AVAudioServiceType *ast;
723 int eac3info, acmod, lfeon, bsmod;
725 if (c->fc->nb_streams < 1)
727 st = c->fc->streams[c->fc->nb_streams-1];
729 ast = (enum AVAudioServiceType*)av_stream_new_side_data(st, AV_PKT_DATA_AUDIO_SERVICE_TYPE,
732 return AVERROR(ENOMEM);
734 /* No need to parse fields for additional independent substreams and its
735 * associated dependent substreams since libavcodec's E-AC-3 decoder
736 * does not support them yet. */
737 avio_rb16(pb); /* data_rate and num_ind_sub */
738 eac3info = avio_rb24(pb);
739 bsmod = (eac3info >> 12) & 0x1f;
740 acmod = (eac3info >> 9) & 0x7;
741 lfeon = (eac3info >> 8) & 0x1;
742 st->codecpar->channel_layout = avpriv_ac3_channel_layout_tab[acmod];
744 st->codecpar->channel_layout |= AV_CH_LOW_FREQUENCY;
745 st->codecpar->channels = av_get_channel_layout_nb_channels(st->codecpar->channel_layout);
747 if (st->codecpar->channels > 1 && bsmod == 0x7)
748 *ast = AV_AUDIO_SERVICE_TYPE_KARAOKE;
750 #if FF_API_LAVF_AVCTX
751 FF_DISABLE_DEPRECATION_WARNINGS
752 st->codec->audio_service_type = *ast;
753 FF_ENABLE_DEPRECATION_WARNINGS
759 static int mov_read_chan(MOVContext *c, AVIOContext *pb, MOVAtom atom)
763 if (c->fc->nb_streams < 1)
765 st = c->fc->streams[c->fc->nb_streams-1];
770 /* skip version and flags */
773 ff_mov_read_chan(c->fc, pb, st, atom.size - 4);
778 static int mov_read_wfex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
782 if (c->fc->nb_streams < 1)
784 st = c->fc->streams[c->fc->nb_streams-1];
786 return ff_get_wav_header(c->fc, pb, st->codecpar, atom.size);
789 static int mov_read_pasp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
791 const int num = avio_rb32(pb);
792 const int den = avio_rb32(pb);
795 if (c->fc->nb_streams < 1)
797 st = c->fc->streams[c->fc->nb_streams-1];
799 if ((st->sample_aspect_ratio.den != 1 || st->sample_aspect_ratio.num) && // default
800 (den != st->sample_aspect_ratio.den || num != st->sample_aspect_ratio.num)) {
801 av_log(c->fc, AV_LOG_WARNING,
802 "sample aspect ratio already set to %d:%d, ignoring 'pasp' atom (%d:%d)\n",
803 st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
805 } else if (den != 0) {
806 st->sample_aspect_ratio.num = num;
807 st->sample_aspect_ratio.den = den;
812 /* this atom contains actual media data */
813 static int mov_read_mdat(MOVContext *c, AVIOContext *pb, MOVAtom atom)
815 if (atom.size == 0) /* wrong one (MP4) */
818 return 0; /* now go for moov */
821 /* read major brand, minor version and compatible brands and store them as metadata */
822 static int mov_read_ftyp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
826 char minor_ver_str[11]; /* 32 bit integer -> 10 digits + null */
827 char* comp_brands_str;
828 uint8_t type[5] = {0};
829 int ret = ffio_read_size(pb, type, 4);
833 if (strcmp(type, "qt "))
835 av_log(c->fc, AV_LOG_DEBUG, "ISO: File Type Major Brand: %.4s\n",(char *)&type);
836 av_dict_set(&c->fc->metadata, "major_brand", type, 0);
837 minor_ver = avio_rb32(pb); /* minor version */
838 snprintf(minor_ver_str, sizeof(minor_ver_str), "%"PRIu32"", minor_ver);
839 av_dict_set(&c->fc->metadata, "minor_version", minor_ver_str, 0);
841 comp_brand_size = atom.size - 8;
842 if (comp_brand_size < 0)
843 return AVERROR_INVALIDDATA;
844 comp_brands_str = av_malloc(comp_brand_size + 1); /* Add null terminator */
845 if (!comp_brands_str)
846 return AVERROR(ENOMEM);
848 ret = ffio_read_size(pb, comp_brands_str, comp_brand_size);
850 av_freep(&comp_brands_str);
853 comp_brands_str[comp_brand_size] = 0;
854 av_dict_set(&c->fc->metadata, "compatible_brands", comp_brands_str, 0);
855 av_freep(&comp_brands_str);
860 /* this atom should contain all header atoms */
861 static int mov_read_moov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
865 if ((ret = mov_read_default(c, pb, atom)) < 0)
867 /* we parsed the 'moov' atom, we can terminate the parsing as soon as we find the 'mdat' */
868 /* so we don't parse the whole file if over a network */
870 return 0; /* now go for mdat */
873 static int mov_read_moof(MOVContext *c, AVIOContext *pb, MOVAtom atom)
875 c->fragment.moof_offset = c->fragment.implicit_offset = avio_tell(pb) - 8;
876 av_log(c->fc, AV_LOG_TRACE, "moof offset %"PRIx64"\n", c->fragment.moof_offset);
877 return mov_read_default(c, pb, atom);
880 static void mov_metadata_creation_time(AVDictionary **metadata, time_t time)
884 struct tm *ptm, tmbuf;
885 time -= 2082844800; /* seconds between 1904-01-01 and Epoch */
886 ptm = gmtime_r(&time, &tmbuf);
888 if (strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", ptm))
889 av_dict_set(metadata, "creation_time", buffer, 0);
893 static int mov_read_mdhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
896 MOVStreamContext *sc;
898 char language[4] = {0};
900 time_t creation_time;
902 if (c->fc->nb_streams < 1)
904 st = c->fc->streams[c->fc->nb_streams-1];
907 if (sc->time_scale) {
908 av_log(c->fc, AV_LOG_ERROR, "Multiple mdhd?\n");
909 return AVERROR_INVALIDDATA;
912 version = avio_r8(pb);
914 avpriv_request_sample(c->fc, "Version %d", version);
915 return AVERROR_PATCHWELCOME;
917 avio_rb24(pb); /* flags */
919 creation_time = avio_rb64(pb);
922 creation_time = avio_rb32(pb);
923 avio_rb32(pb); /* modification time */
925 mov_metadata_creation_time(&st->metadata, creation_time);
927 sc->time_scale = avio_rb32(pb);
928 st->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
930 lang = avio_rb16(pb); /* language */
931 if (ff_mov_lang_to_iso639(lang, language))
932 av_dict_set(&st->metadata, "language", language, 0);
933 avio_rb16(pb); /* quality */
938 static int mov_read_mvhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
940 time_t creation_time;
941 int version = avio_r8(pb); /* version */
942 avio_rb24(pb); /* flags */
945 creation_time = avio_rb64(pb);
948 creation_time = avio_rb32(pb);
949 avio_rb32(pb); /* modification time */
951 mov_metadata_creation_time(&c->fc->metadata, creation_time);
952 c->time_scale = avio_rb32(pb); /* time scale */
954 av_log(c->fc, AV_LOG_TRACE, "time scale = %i\n", c->time_scale);
956 c->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
957 avio_rb32(pb); /* preferred scale */
959 avio_rb16(pb); /* preferred volume */
961 avio_skip(pb, 10); /* reserved */
963 avio_skip(pb, 36); /* display matrix */
965 avio_rb32(pb); /* preview time */
966 avio_rb32(pb); /* preview duration */
967 avio_rb32(pb); /* poster time */
968 avio_rb32(pb); /* selection time */
969 avio_rb32(pb); /* selection duration */
970 avio_rb32(pb); /* current time */
971 avio_rb32(pb); /* next track ID */
976 static int mov_read_smi(MOVContext *c, AVIOContext *pb, MOVAtom atom)
981 if (c->fc->nb_streams < 1)
983 st = c->fc->streams[c->fc->nb_streams-1];
985 if ((uint64_t)atom.size > (1<<30))
986 return AVERROR_INVALIDDATA;
988 // currently SVQ3 decoder expect full STSD header - so let's fake it
989 // this should be fixed and just SMI header should be passed
990 av_free(st->codecpar->extradata);
991 st->codecpar->extradata = av_mallocz(atom.size + 0x5a + AV_INPUT_BUFFER_PADDING_SIZE);
992 if (!st->codecpar->extradata)
993 return AVERROR(ENOMEM);
994 st->codecpar->extradata_size = 0x5a + atom.size;
995 memcpy(st->codecpar->extradata, "SVQ3", 4); // fake
997 ret = ffio_read_size(pb, st->codecpar->extradata + 0x5a, atom.size);
1001 av_log(c->fc, AV_LOG_TRACE, "Reading SMI %"PRId64" %s\n", atom.size, st->codecpar->extradata + 0x5a);
1005 static int mov_read_enda(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1010 if (c->fc->nb_streams < 1)
1012 st = c->fc->streams[c->fc->nb_streams-1];
1014 little_endian = !!avio_rb16(pb);
1015 av_log(c->fc, AV_LOG_TRACE, "enda %d\n", little_endian);
1016 if (little_endian == 1) {
1017 switch (st->codecpar->codec_id) {
1018 case AV_CODEC_ID_PCM_S24BE:
1019 st->codecpar->codec_id = AV_CODEC_ID_PCM_S24LE;
1021 case AV_CODEC_ID_PCM_S32BE:
1022 st->codecpar->codec_id = AV_CODEC_ID_PCM_S32LE;
1024 case AV_CODEC_ID_PCM_F32BE:
1025 st->codecpar->codec_id = AV_CODEC_ID_PCM_F32LE;
1027 case AV_CODEC_ID_PCM_F64BE:
1028 st->codecpar->codec_id = AV_CODEC_ID_PCM_F64LE;
1037 static int mov_read_colr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1040 char color_parameter_type[5] = { 0 };
1041 uint16_t color_primaries, color_trc, color_matrix;
1044 if (c->fc->nb_streams < 1)
1046 st = c->fc->streams[c->fc->nb_streams - 1];
1048 ret = ffio_read_size(pb, color_parameter_type, 4);
1051 if (strncmp(color_parameter_type, "nclx", 4) &&
1052 strncmp(color_parameter_type, "nclc", 4)) {
1053 av_log(c->fc, AV_LOG_WARNING, "unsupported color_parameter_type %s\n",
1054 color_parameter_type);
1058 color_primaries = avio_rb16(pb);
1059 color_trc = avio_rb16(pb);
1060 color_matrix = avio_rb16(pb);
1062 av_log(c->fc, AV_LOG_TRACE,
1063 "%s: pri %"PRIu16" trc %"PRIu16" matrix %"PRIu16"",
1064 color_parameter_type, color_primaries, color_trc, color_matrix);
1066 if (!strncmp(color_parameter_type, "nclx", 4)) {
1067 uint8_t color_range = avio_r8(pb) >> 7;
1068 av_log(c->fc, AV_LOG_TRACE, " full %"PRIu8"", color_range);
1070 st->codecpar->color_range = AVCOL_RANGE_JPEG;
1072 st->codecpar->color_range = AVCOL_RANGE_MPEG;
1073 /* 14496-12 references JPEG XR specs (rather than the more complete
1074 * 23001-8) so some adjusting is required */
1075 if (color_primaries >= AVCOL_PRI_FILM)
1076 color_primaries = AVCOL_PRI_UNSPECIFIED;
1077 if ((color_trc >= AVCOL_TRC_LINEAR &&
1078 color_trc <= AVCOL_TRC_LOG_SQRT) ||
1079 color_trc >= AVCOL_TRC_BT2020_10)
1080 color_trc = AVCOL_TRC_UNSPECIFIED;
1081 if (color_matrix >= AVCOL_SPC_BT2020_NCL)
1082 color_matrix = AVCOL_SPC_UNSPECIFIED;
1083 st->codecpar->color_primaries = color_primaries;
1084 st->codecpar->color_trc = color_trc;
1085 st->codecpar->color_space = color_matrix;
1086 } else if (!strncmp(color_parameter_type, "nclc", 4)) {
1087 /* color primaries, Table 4-4 */
1088 switch (color_primaries) {
1089 case 1: st->codecpar->color_primaries = AVCOL_PRI_BT709; break;
1090 case 5: st->codecpar->color_primaries = AVCOL_PRI_SMPTE170M; break;
1091 case 6: st->codecpar->color_primaries = AVCOL_PRI_SMPTE240M; break;
1093 /* color transfer, Table 4-5 */
1094 switch (color_trc) {
1095 case 1: st->codecpar->color_trc = AVCOL_TRC_BT709; break;
1096 case 7: st->codecpar->color_trc = AVCOL_TRC_SMPTE240M; break;
1098 /* color matrix, Table 4-6 */
1099 switch (color_matrix) {
1100 case 1: st->codecpar->color_space = AVCOL_SPC_BT709; break;
1101 case 6: st->codecpar->color_space = AVCOL_SPC_BT470BG; break;
1102 case 7: st->codecpar->color_space = AVCOL_SPC_SMPTE240M; break;
1105 av_log(c->fc, AV_LOG_TRACE, "\n");
1110 static int mov_read_fiel(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1113 unsigned mov_field_order;
1114 enum AVFieldOrder decoded_field_order = AV_FIELD_UNKNOWN;
1116 if (c->fc->nb_streams < 1) // will happen with jp2 files
1118 st = c->fc->streams[c->fc->nb_streams-1];
1120 return AVERROR_INVALIDDATA;
1121 mov_field_order = avio_rb16(pb);
1122 if ((mov_field_order & 0xFF00) == 0x0100)
1123 decoded_field_order = AV_FIELD_PROGRESSIVE;
1124 else if ((mov_field_order & 0xFF00) == 0x0200) {
1125 switch (mov_field_order & 0xFF) {
1126 case 0x01: decoded_field_order = AV_FIELD_TT;
1128 case 0x06: decoded_field_order = AV_FIELD_BB;
1130 case 0x09: decoded_field_order = AV_FIELD_TB;
1132 case 0x0E: decoded_field_order = AV_FIELD_BT;
1136 if (decoded_field_order == AV_FIELD_UNKNOWN && mov_field_order) {
1137 av_log(NULL, AV_LOG_ERROR, "Unknown MOV field order 0x%04x\n", mov_field_order);
1139 st->codecpar->field_order = decoded_field_order;
1144 /* FIXME modify QDM2/SVQ3/H.264 decoders to take full atom as extradata */
1145 static int mov_read_extradata(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1152 if (c->fc->nb_streams < 1) // will happen with jp2 files
1154 st= c->fc->streams[c->fc->nb_streams-1];
1155 size= (uint64_t)st->codecpar->extradata_size + atom.size + 8 + AV_INPUT_BUFFER_PADDING_SIZE;
1156 if (size > INT_MAX || (uint64_t)atom.size > INT_MAX)
1157 return AVERROR_INVALIDDATA;
1158 if ((err = av_reallocp(&st->codecpar->extradata, size)) < 0) {
1159 st->codecpar->extradata_size = 0;
1162 buf = st->codecpar->extradata + st->codecpar->extradata_size;
1163 st->codecpar->extradata_size= size - AV_INPUT_BUFFER_PADDING_SIZE;
1164 AV_WB32( buf , atom.size + 8);
1165 AV_WL32( buf + 4, atom.type);
1167 err = ffio_read_size(pb, buf + 8, atom.size);
1174 static int mov_read_wave(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1179 if (c->fc->nb_streams < 1)
1181 st = c->fc->streams[c->fc->nb_streams-1];
1183 if ((uint64_t)atom.size > (1<<30))
1184 return AVERROR_INVALIDDATA;
1186 if (st->codecpar->codec_id == AV_CODEC_ID_QDM2 || st->codecpar->codec_id == AV_CODEC_ID_QDMC) {
1187 // pass all frma atom to codec, needed at least for QDMC and QDM2
1188 av_free(st->codecpar->extradata);
1189 st->codecpar->extradata = av_mallocz(atom.size + AV_INPUT_BUFFER_PADDING_SIZE);
1190 if (!st->codecpar->extradata)
1191 return AVERROR(ENOMEM);
1192 st->codecpar->extradata_size = atom.size;
1194 ret = ffio_read_size(pb, st->codecpar->extradata, atom.size);
1197 } else if (atom.size > 8) { /* to read frma, esds atoms */
1198 if ((ret = mov_read_default(c, pb, atom)) < 0)
1201 avio_skip(pb, atom.size);
1206 * This function reads atom content and puts data in extradata without tag
1207 * nor size unlike mov_read_extradata.
1209 static int mov_read_glbl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1214 if (c->fc->nb_streams < 1)
1216 st = c->fc->streams[c->fc->nb_streams-1];
1218 if ((uint64_t)atom.size > (1<<30))
1219 return AVERROR_INVALIDDATA;
1221 if (atom.size >= 10) {
1222 // Broken files created by legacy versions of libavformat will
1223 // wrap a whole fiel atom inside of a glbl atom.
1224 unsigned size = avio_rb32(pb);
1225 unsigned type = avio_rl32(pb);
1226 avio_seek(pb, -8, SEEK_CUR);
1227 if (type == MKTAG('f','i','e','l') && size == atom.size)
1228 return mov_read_default(c, pb, atom);
1230 av_free(st->codecpar->extradata);
1231 st->codecpar->extradata = av_mallocz(atom.size + AV_INPUT_BUFFER_PADDING_SIZE);
1232 if (!st->codecpar->extradata)
1233 return AVERROR(ENOMEM);
1234 st->codecpar->extradata_size = atom.size;
1236 ret = ffio_read_size(pb, st->codecpar->extradata, atom.size);
1243 static int mov_read_dvc1(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1246 uint8_t profile_level;
1249 if (c->fc->nb_streams < 1)
1251 st = c->fc->streams[c->fc->nb_streams-1];
1253 if (atom.size >= (1<<28) || atom.size < 7)
1254 return AVERROR_INVALIDDATA;
1256 profile_level = avio_r8(pb);
1257 if ((profile_level & 0xf0) != 0xc0)
1260 av_free(st->codecpar->extradata);
1261 st->codecpar->extradata = av_mallocz(atom.size - 7 + AV_INPUT_BUFFER_PADDING_SIZE);
1262 if (!st->codecpar->extradata)
1263 return AVERROR(ENOMEM);
1264 st->codecpar->extradata_size = atom.size - 7;
1265 avio_seek(pb, 6, SEEK_CUR);
1267 ret = ffio_read_size(pb, st->codecpar->extradata, st->codecpar->extradata_size);
1275 * An strf atom is a BITMAPINFOHEADER struct. This struct is 40 bytes itself,
1276 * but can have extradata appended at the end after the 40 bytes belonging
1279 static int mov_read_strf(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1284 if (c->fc->nb_streams < 1)
1286 if (atom.size <= 40)
1288 st = c->fc->streams[c->fc->nb_streams-1];
1290 if ((uint64_t)atom.size > (1<<30))
1291 return AVERROR_INVALIDDATA;
1293 av_free(st->codecpar->extradata);
1294 st->codecpar->extradata = av_mallocz(atom.size - 40 + AV_INPUT_BUFFER_PADDING_SIZE);
1295 if (!st->codecpar->extradata)
1296 return AVERROR(ENOMEM);
1297 st->codecpar->extradata_size = atom.size - 40;
1300 ret = ffio_read_size(pb, st->codecpar->extradata, atom.size - 40);
1307 static int mov_read_stco(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1310 MOVStreamContext *sc;
1311 unsigned int i, entries;
1313 if (c->fc->nb_streams < 1)
1315 st = c->fc->streams[c->fc->nb_streams-1];
1318 avio_r8(pb); /* version */
1319 avio_rb24(pb); /* flags */
1321 entries = avio_rb32(pb);
1325 if (entries >= UINT_MAX/sizeof(int64_t))
1326 return AVERROR_INVALIDDATA;
1328 sc->chunk_offsets = av_malloc(entries * sizeof(int64_t));
1329 if (!sc->chunk_offsets)
1330 return AVERROR(ENOMEM);
1331 sc->chunk_count = entries;
1333 if (atom.type == MKTAG('s','t','c','o'))
1334 for (i = 0; i < entries && !pb->eof_reached; i++)
1335 sc->chunk_offsets[i] = avio_rb32(pb);
1336 else if (atom.type == MKTAG('c','o','6','4'))
1337 for (i = 0; i < entries && !pb->eof_reached; i++)
1338 sc->chunk_offsets[i] = avio_rb64(pb);
1340 return AVERROR_INVALIDDATA;
1342 sc->chunk_count = i;
1344 if (pb->eof_reached)
1351 * Compute codec id for 'lpcm' tag.
1352 * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
1354 enum AVCodecID ff_mov_get_lpcm_codec_id(int bps, int flags)
1361 return ff_get_pcm_codec_id(bps, flags & 1, flags & 2, flags & 4 ? -1 : 0);
1364 static int mov_codec_id(AVStream *st, uint32_t format)
1366 int id = ff_codec_get_id(ff_codec_movaudio_tags, format);
1369 ((format & 0xFFFF) == 'm' + ('s' << 8) ||
1370 (format & 0xFFFF) == 'T' + ('S' << 8)))
1371 id = ff_codec_get_id(ff_codec_wav_tags, av_bswap32(format) & 0xFFFF);
1373 if (st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO && id > 0) {
1374 st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
1375 } else if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO &&
1376 /* skip old ASF MPEG-4 tag */
1377 format && format != MKTAG('m','p','4','s')) {
1378 id = ff_codec_get_id(ff_codec_movvideo_tags, format);
1380 id = ff_codec_get_id(ff_codec_bmp_tags, format);
1382 st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
1383 else if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA) {
1384 id = ff_codec_get_id(ff_codec_movsubtitle_tags, format);
1386 st->codecpar->codec_type = AVMEDIA_TYPE_SUBTITLE;
1390 st->codecpar->codec_tag = format;
1395 static void mov_parse_stsd_video(MOVContext *c, AVIOContext *pb,
1396 AVStream *st, MOVStreamContext *sc)
1398 uint8_t codec_name[32];
1399 unsigned int color_depth, len, j;
1400 int color_greyscale;
1403 avio_rb16(pb); /* version */
1404 avio_rb16(pb); /* revision level */
1405 avio_rb32(pb); /* vendor */
1406 avio_rb32(pb); /* temporal quality */
1407 avio_rb32(pb); /* spatial quality */
1409 st->codecpar->width = avio_rb16(pb); /* width */
1410 st->codecpar->height = avio_rb16(pb); /* height */
1412 avio_rb32(pb); /* horiz resolution */
1413 avio_rb32(pb); /* vert resolution */
1414 avio_rb32(pb); /* data size, always 0 */
1415 avio_rb16(pb); /* frames per samples */
1417 len = avio_r8(pb); /* codec name, pascal string */
1420 mov_read_mac_string(c, pb, len, codec_name, sizeof(codec_name));
1422 avio_skip(pb, 31 - len);
1425 av_dict_set(&st->metadata, "encoder", codec_name, 0);
1427 /* codec_tag YV12 triggers an UV swap in rawdec.c */
1428 if (!memcmp(codec_name, "Planar Y'CbCr 8-bit 4:2:0", 25))
1429 st->codecpar->codec_tag = MKTAG('I', '4', '2', '0');
1430 /* Flash Media Server uses tag H.263 with Sorenson Spark */
1431 if (st->codecpar->codec_tag == MKTAG('H','2','6','3') &&
1432 !memcmp(codec_name, "Sorenson H263", 13))
1433 st->codecpar->codec_id = AV_CODEC_ID_FLV1;
1435 st->codecpar->bits_per_coded_sample = avio_rb16(pb); /* depth */
1436 color_table_id = avio_rb16(pb); /* colortable id */
1437 av_log(c->fc, AV_LOG_TRACE, "depth %d, ctab id %d\n",
1438 st->codecpar->bits_per_coded_sample, color_table_id);
1439 /* figure out the palette situation */
1440 color_depth = st->codecpar->bits_per_coded_sample & 0x1F;
1441 color_greyscale = st->codecpar->bits_per_coded_sample & 0x20;
1443 /* if the depth is 2, 4, or 8 bpp, file is palettized */
1444 if ((color_depth == 2) || (color_depth == 4) || (color_depth == 8)) {
1445 /* for palette traversal */
1446 unsigned int color_start, color_count, color_end;
1447 unsigned char r, g, b;
1449 if (color_greyscale) {
1450 int color_index, color_dec;
1451 /* compute the greyscale palette */
1452 st->codecpar->bits_per_coded_sample = color_depth;
1453 color_count = 1 << color_depth;
1455 color_dec = 256 / (color_count - 1);
1456 for (j = 0; j < color_count; j++) {
1457 r = g = b = color_index;
1458 sc->palette[j] = (r << 16) | (g << 8) | (b);
1459 color_index -= color_dec;
1460 if (color_index < 0)
1463 } else if (color_table_id) {
1464 const uint8_t *color_table;
1465 /* if flag bit 3 is set, use the default palette */
1466 color_count = 1 << color_depth;
1467 if (color_depth == 2)
1468 color_table = ff_qt_default_palette_4;
1469 else if (color_depth == 4)
1470 color_table = ff_qt_default_palette_16;
1472 color_table = ff_qt_default_palette_256;
1474 for (j = 0; j < color_count; j++) {
1475 r = color_table[j * 3 + 0];
1476 g = color_table[j * 3 + 1];
1477 b = color_table[j * 3 + 2];
1478 sc->palette[j] = (r << 16) | (g << 8) | (b);
1481 /* load the palette from the file */
1482 color_start = avio_rb32(pb);
1483 color_count = avio_rb16(pb);
1484 color_end = avio_rb16(pb);
1485 if ((color_start <= 255) && (color_end <= 255)) {
1486 for (j = color_start; j <= color_end; j++) {
1487 /* each R, G, or B component is 16 bits;
1488 * only use the top 8 bits; skip alpha bytes
1498 sc->palette[j] = (r << 16) | (g << 8) | (b);
1502 sc->has_palette = 1;
1506 static void mov_parse_stsd_audio(MOVContext *c, AVIOContext *pb,
1507 AVStream *st, MOVStreamContext *sc)
1509 int bits_per_sample, flags;
1510 uint16_t version = avio_rb16(pb);
1512 avio_rb16(pb); /* revision level */
1513 avio_rb32(pb); /* vendor */
1515 st->codecpar->channels = avio_rb16(pb); /* channel count */
1516 st->codecpar->bits_per_coded_sample = avio_rb16(pb); /* sample size */
1517 av_log(c->fc, AV_LOG_TRACE, "audio channels %d\n", st->codecpar->channels);
1519 sc->audio_cid = avio_rb16(pb);
1520 avio_rb16(pb); /* packet size = 0 */
1522 st->codecpar->sample_rate = ((avio_rb32(pb) >> 16));
1524 // Read QT version 1 fields. In version 0 these do not exist.
1525 av_log(c->fc, AV_LOG_TRACE, "version =%d, isom =%d\n", version, c->isom);
1528 sc->samples_per_frame = avio_rb32(pb);
1529 avio_rb32(pb); /* bytes per packet */
1530 sc->bytes_per_frame = avio_rb32(pb);
1531 avio_rb32(pb); /* bytes per sample */
1532 } else if (version == 2) {
1533 avio_rb32(pb); /* sizeof struct only */
1534 st->codecpar->sample_rate = av_int2double(avio_rb64(pb));
1535 st->codecpar->channels = avio_rb32(pb);
1536 avio_rb32(pb); /* always 0x7F000000 */
1537 st->codecpar->bits_per_coded_sample = avio_rb32(pb);
1539 flags = avio_rb32(pb); /* lpcm format specific flag */
1540 sc->bytes_per_frame = avio_rb32(pb);
1541 sc->samples_per_frame = avio_rb32(pb);
1542 if (st->codecpar->codec_tag == MKTAG('l','p','c','m'))
1543 st->codecpar->codec_id =
1544 ff_mov_get_lpcm_codec_id(st->codecpar->bits_per_coded_sample,
1547 if (version == 0 || (version == 1 && sc->audio_cid != -2)) {
1548 /* can't correctly handle variable sized packet as audio unit */
1549 switch (st->codecpar->codec_id) {
1550 case AV_CODEC_ID_MP2:
1551 case AV_CODEC_ID_MP3:
1552 st->need_parsing = AVSTREAM_PARSE_FULL;
1558 switch (st->codecpar->codec_id) {
1559 case AV_CODEC_ID_PCM_S8:
1560 case AV_CODEC_ID_PCM_U8:
1561 if (st->codecpar->bits_per_coded_sample == 16)
1562 st->codecpar->codec_id = AV_CODEC_ID_PCM_S16BE;
1564 case AV_CODEC_ID_PCM_S16LE:
1565 case AV_CODEC_ID_PCM_S16BE:
1566 if (st->codecpar->bits_per_coded_sample == 8)
1567 st->codecpar->codec_id = AV_CODEC_ID_PCM_S8;
1568 else if (st->codecpar->bits_per_coded_sample == 24)
1569 st->codecpar->codec_id =
1570 st->codecpar->codec_id == AV_CODEC_ID_PCM_S16BE ?
1571 AV_CODEC_ID_PCM_S24BE : AV_CODEC_ID_PCM_S24LE;
1573 /* set values for old format before stsd version 1 appeared */
1574 case AV_CODEC_ID_MACE3:
1575 sc->samples_per_frame = 6;
1576 sc->bytes_per_frame = 2 * st->codecpar->channels;
1578 case AV_CODEC_ID_MACE6:
1579 sc->samples_per_frame = 6;
1580 sc->bytes_per_frame = 1 * st->codecpar->channels;
1582 case AV_CODEC_ID_ADPCM_IMA_QT:
1583 sc->samples_per_frame = 64;
1584 sc->bytes_per_frame = 34 * st->codecpar->channels;
1586 case AV_CODEC_ID_GSM:
1587 sc->samples_per_frame = 160;
1588 sc->bytes_per_frame = 33;
1594 bits_per_sample = av_get_bits_per_sample(st->codecpar->codec_id);
1595 if (bits_per_sample) {
1596 st->codecpar->bits_per_coded_sample = bits_per_sample;
1597 sc->sample_size = (bits_per_sample >> 3) * st->codecpar->channels;
1601 static void mov_parse_stsd_subtitle(MOVContext *c, AVIOContext *pb,
1602 AVStream *st, MOVStreamContext *sc,
1605 // ttxt stsd contains display flags, justification, background
1606 // color, fonts, and default styles, so fake an atom to read it
1607 MOVAtom fake_atom = { .size = size };
1608 // mp4s contains a regular esds atom
1609 if (st->codecpar->codec_tag != AV_RL32("mp4s"))
1610 mov_read_glbl(c, pb, fake_atom);
1611 st->codecpar->width = sc->width;
1612 st->codecpar->height = sc->height;
1615 static uint32_t yuv_to_rgba(uint32_t ycbcr)
1620 y = (ycbcr >> 16) & 0xFF;
1621 cr = (ycbcr >> 8) & 0xFF;
1624 b = av_clip_uint8(1.164 * (y - 16) + 2.018 * (cb - 128));
1625 g = av_clip_uint8(1.164 * (y - 16) - 0.813 * (cr - 128) - 0.391 * (cb - 128));
1626 r = av_clip_uint8(1.164 * (y - 16) + 1.596 * (cr - 128));
1628 return (r << 16) | (g << 8) | b;
1631 static int mov_rewrite_dvd_sub_extradata(AVStream *st)
1633 char buf[256] = {0};
1634 uint8_t *src = st->codecpar->extradata;
1637 if (st->codecpar->extradata_size != 64)
1640 if (st->codecpar->width > 0 && st->codecpar->height > 0)
1641 snprintf(buf, sizeof(buf), "size: %dx%d\n",
1642 st->codecpar->width, st->codecpar->height);
1643 av_strlcat(buf, "palette: ", sizeof(buf));
1645 for (i = 0; i < 16; i++) {
1646 uint32_t yuv = AV_RB32(src + i * 4);
1647 uint32_t rgba = yuv_to_rgba(yuv);
1649 av_strlcatf(buf, sizeof(buf), "%06"PRIx32"%s", rgba, i != 15 ? ", " : "");
1652 if (av_strlcat(buf, "\n", sizeof(buf)) >= sizeof(buf))
1655 av_freep(&st->codecpar->extradata);
1656 st->codecpar->extradata_size = 0;
1657 st->codecpar->extradata = av_mallocz(strlen(buf) + AV_INPUT_BUFFER_PADDING_SIZE);
1658 if (!st->codecpar->extradata)
1659 return AVERROR(ENOMEM);
1660 st->codecpar->extradata_size = strlen(buf);
1661 memcpy(st->codecpar->extradata, buf, st->codecpar->extradata_size);
1666 static int mov_parse_stsd_data(MOVContext *c, AVIOContext *pb,
1667 AVStream *st, MOVStreamContext *sc,
1672 if (st->codecpar->codec_tag == MKTAG('t','m','c','d')) {
1673 st->codecpar->extradata_size = size;
1674 st->codecpar->extradata = av_malloc(size + AV_INPUT_BUFFER_PADDING_SIZE);
1675 if (!st->codecpar->extradata)
1676 return AVERROR(ENOMEM);
1677 ret = ffio_read_size(pb, st->codecpar->extradata, size);
1681 /* other codec type, just skip (rtp, mp4s ...) */
1682 avio_skip(pb, size);
1687 static int mov_finalize_stsd_codec(MOVContext *c, AVIOContext *pb,
1688 AVStream *st, MOVStreamContext *sc)
1690 if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
1691 !st->codecpar->sample_rate && sc->time_scale > 1)
1692 st->codecpar->sample_rate = sc->time_scale;
1694 /* special codec parameters handling */
1695 switch (st->codecpar->codec_id) {
1696 #if CONFIG_DV_DEMUXER
1697 case AV_CODEC_ID_DVAUDIO:
1698 c->dv_fctx = avformat_alloc_context();
1700 av_log(c->fc, AV_LOG_ERROR, "dv demux context alloc error\n");
1701 return AVERROR(ENOMEM);
1703 c->dv_demux = avpriv_dv_init_demux(c->dv_fctx);
1705 av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n");
1706 return AVERROR(ENOMEM);
1708 sc->dv_audio_container = 1;
1709 st->codecpar->codec_id = AV_CODEC_ID_PCM_S16LE;
1712 /* no ifdef since parameters are always those */
1713 case AV_CODEC_ID_QCELP:
1714 st->codecpar->channels = 1;
1715 // force sample rate for qcelp when not stored in mov
1716 if (st->codecpar->codec_tag != MKTAG('Q','c','l','p'))
1717 st->codecpar->sample_rate = 8000;
1719 case AV_CODEC_ID_AMR_NB:
1720 st->codecpar->channels = 1;
1721 /* force sample rate for amr, stsd in 3gp does not store sample rate */
1722 st->codecpar->sample_rate = 8000;
1724 case AV_CODEC_ID_AMR_WB:
1725 st->codecpar->channels = 1;
1726 st->codecpar->sample_rate = 16000;
1728 case AV_CODEC_ID_MP2:
1729 case AV_CODEC_ID_MP3:
1730 /* force type after stsd for m1a hdlr */
1731 st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
1733 case AV_CODEC_ID_GSM:
1734 case AV_CODEC_ID_ADPCM_MS:
1735 case AV_CODEC_ID_ADPCM_IMA_WAV:
1736 case AV_CODEC_ID_ILBC:
1737 st->codecpar->block_align = sc->bytes_per_frame;
1739 case AV_CODEC_ID_ALAC:
1740 if (st->codecpar->extradata_size == 36) {
1741 st->codecpar->channels = AV_RB8 (st->codecpar->extradata + 21);
1742 st->codecpar->sample_rate = AV_RB32(st->codecpar->extradata + 32);
1745 case AV_CODEC_ID_VC1:
1746 st->need_parsing = AVSTREAM_PARSE_FULL;
1754 static int mov_skip_multiple_stsd(MOVContext *c, AVIOContext *pb,
1755 int codec_tag, int format,
1758 int video_codec_id = ff_codec_get_id(ff_codec_movvideo_tags, format);
1761 (codec_tag == AV_RL32("avc1") ||
1762 codec_tag == AV_RL32("hvc1") ||
1763 codec_tag == AV_RL32("hev1") ||
1764 (codec_tag != format &&
1765 (c->fc->video_codec_id ? video_codec_id != c->fc->video_codec_id
1766 : codec_tag != MKTAG('j','p','e','g'))))) {
1767 /* Multiple fourcc, we skip JPEG. This is not correct, we should
1768 * export it as a separate AVStream but this needs a few changes
1769 * in the MOV demuxer, patch welcome. */
1771 av_log(c->fc, AV_LOG_WARNING, "multiple fourcc not supported\n");
1772 avio_skip(pb, size);
1779 int ff_mov_read_stsd_entries(MOVContext *c, AVIOContext *pb, int entries)
1782 MOVStreamContext *sc;
1783 int pseudo_stream_id;
1785 if (c->fc->nb_streams < 1)
1787 st = c->fc->streams[c->fc->nb_streams-1];
1790 for (pseudo_stream_id = 0;
1791 pseudo_stream_id < entries && !pb->eof_reached;
1792 pseudo_stream_id++) {
1793 //Parsing Sample description table
1795 int ret, dref_id = 1;
1796 MOVAtom a = { AV_RL32("stsd") };
1797 int64_t start_pos = avio_tell(pb);
1798 int64_t size = avio_rb32(pb); /* size */
1799 uint32_t format = avio_rl32(pb); /* data format */
1802 avio_rb32(pb); /* reserved */
1803 avio_rb16(pb); /* reserved */
1804 dref_id = avio_rb16(pb);
1806 av_log(c->fc, AV_LOG_ERROR,
1807 "invalid size %"PRId64" in stsd\n", size);
1808 return AVERROR_INVALIDDATA;
1811 if (mov_skip_multiple_stsd(c, pb, st->codecpar->codec_tag, format,
1812 size - (avio_tell(pb) - start_pos)))
1815 sc->pseudo_stream_id = st->codecpar->codec_tag ? -1 : pseudo_stream_id;
1816 sc->dref_id= dref_id;
1818 id = mov_codec_id(st, format);
1820 av_log(c->fc, AV_LOG_TRACE,
1821 "size=%"PRId64" format=0x%08x codec_type=%d\n",
1822 size, format, st->codecpar->codec_type);
1824 if (st->codecpar->codec_type==AVMEDIA_TYPE_VIDEO) {
1825 st->codecpar->codec_id = id;
1826 mov_parse_stsd_video(c, pb, st, sc);
1827 } else if (st->codecpar->codec_type==AVMEDIA_TYPE_AUDIO) {
1828 st->codecpar->codec_id = id;
1829 mov_parse_stsd_audio(c, pb, st, sc);
1830 } else if (st->codecpar->codec_type==AVMEDIA_TYPE_SUBTITLE){
1831 st->codecpar->codec_id = id;
1832 mov_parse_stsd_subtitle(c, pb, st, sc,
1833 size - (avio_tell(pb) - start_pos));
1835 ret = mov_parse_stsd_data(c, pb, st, sc,
1836 size - (avio_tell(pb) - start_pos));
1840 /* this will read extra atoms at the end (wave, alac, damr, avcC, hvcC, SMI ...) */
1841 a.size = size - (avio_tell(pb) - start_pos);
1843 if ((ret = mov_read_default(c, pb, a)) < 0)
1845 } else if (a.size > 0)
1846 avio_skip(pb, a.size);
1849 if (pb->eof_reached)
1852 return mov_finalize_stsd_codec(c, pb, st, sc);
1855 static int mov_read_stsd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1859 avio_r8(pb); /* version */
1860 avio_rb24(pb); /* flags */
1861 entries = avio_rb32(pb);
1863 return ff_mov_read_stsd_entries(c, pb, entries);
1866 static int mov_read_stsc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1869 MOVStreamContext *sc;
1870 unsigned int i, entries;
1872 if (c->fc->nb_streams < 1)
1874 st = c->fc->streams[c->fc->nb_streams-1];
1877 avio_r8(pb); /* version */
1878 avio_rb24(pb); /* flags */
1880 entries = avio_rb32(pb);
1882 av_log(c->fc, AV_LOG_TRACE, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);
1886 if (entries >= UINT_MAX / sizeof(*sc->stsc_data))
1887 return AVERROR_INVALIDDATA;
1888 sc->stsc_data = av_malloc(entries * sizeof(*sc->stsc_data));
1890 return AVERROR(ENOMEM);
1892 for (i = 0; i < entries && !pb->eof_reached; i++) {
1893 sc->stsc_data[i].first = avio_rb32(pb);
1894 sc->stsc_data[i].count = avio_rb32(pb);
1895 sc->stsc_data[i].id = avio_rb32(pb);
1900 if (pb->eof_reached)
1906 static int mov_read_stps(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1909 MOVStreamContext *sc;
1910 unsigned i, entries;
1912 if (c->fc->nb_streams < 1)
1914 st = c->fc->streams[c->fc->nb_streams-1];
1917 avio_rb32(pb); // version + flags
1919 entries = avio_rb32(pb);
1920 if (entries >= UINT_MAX / sizeof(*sc->stps_data))
1921 return AVERROR_INVALIDDATA;
1922 sc->stps_data = av_malloc(entries * sizeof(*sc->stps_data));
1924 return AVERROR(ENOMEM);
1926 for (i = 0; i < entries && !pb->eof_reached; i++) {
1927 sc->stps_data[i] = avio_rb32(pb);
1928 //av_log(c->fc, AV_LOG_TRACE, "stps %d\n", sc->stps_data[i]);
1933 if (pb->eof_reached)
1939 static int mov_read_stss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1942 MOVStreamContext *sc;
1943 unsigned int i, entries;
1945 if (c->fc->nb_streams < 1)
1947 st = c->fc->streams[c->fc->nb_streams-1];
1950 avio_r8(pb); /* version */
1951 avio_rb24(pb); /* flags */
1953 entries = avio_rb32(pb);
1955 av_log(c->fc, AV_LOG_TRACE, "keyframe_count = %d\n", entries);
1959 sc->keyframe_absent = 1;
1962 if (entries >= UINT_MAX / sizeof(int))
1963 return AVERROR_INVALIDDATA;
1964 av_freep(&sc->keyframes);
1965 sc->keyframes = av_malloc(entries * sizeof(int));
1967 return AVERROR(ENOMEM);
1969 for (i = 0; i < entries && !pb->eof_reached; i++) {
1970 sc->keyframes[i] = avio_rb32(pb);
1971 //av_log(c->fc, AV_LOG_TRACE, "keyframes[]=%d\n", sc->keyframes[i]);
1974 sc->keyframe_count = i;
1976 if (pb->eof_reached)
1982 static int mov_read_stsz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1985 MOVStreamContext *sc;
1986 unsigned int i, entries, sample_size, field_size, num_bytes;
1991 if (c->fc->nb_streams < 1)
1993 st = c->fc->streams[c->fc->nb_streams-1];
1996 avio_r8(pb); /* version */
1997 avio_rb24(pb); /* flags */
1999 if (atom.type == MKTAG('s','t','s','z')) {
2000 sample_size = avio_rb32(pb);
2001 if (!sc->sample_size) /* do not overwrite value computed in stsd */
2002 sc->sample_size = sample_size;
2006 avio_rb24(pb); /* reserved */
2007 field_size = avio_r8(pb);
2009 entries = avio_rb32(pb);
2011 av_log(c->fc, AV_LOG_TRACE, "sample_size = %d sample_count = %d\n", sc->sample_size, entries);
2013 sc->sample_count = entries;
2017 if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) {
2018 av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %d\n", field_size);
2019 return AVERROR_INVALIDDATA;
2024 if (entries >= UINT_MAX / sizeof(int) || entries >= (UINT_MAX - 4) / field_size)
2025 return AVERROR_INVALIDDATA;
2026 sc->sample_sizes = av_malloc(entries * sizeof(int));
2027 if (!sc->sample_sizes)
2028 return AVERROR(ENOMEM);
2030 num_bytes = (entries*field_size+4)>>3;
2032 buf = av_malloc(num_bytes+AV_INPUT_BUFFER_PADDING_SIZE);
2034 av_freep(&sc->sample_sizes);
2035 return AVERROR(ENOMEM);
2038 ret = ffio_read_size(pb, buf, num_bytes);
2040 av_freep(&sc->sample_sizes);
2045 init_get_bits(&gb, buf, 8*num_bytes);
2047 for (i = 0; i < entries && !pb->eof_reached; i++) {
2048 sc->sample_sizes[i] = get_bits_long(&gb, field_size);
2049 sc->data_size += sc->sample_sizes[i];
2052 sc->sample_count = i;
2056 if (pb->eof_reached)
2062 static int mov_read_stts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2065 MOVStreamContext *sc;
2066 unsigned int i, entries;
2068 int64_t total_sample_count=0;
2070 if (c->fc->nb_streams < 1)
2072 st = c->fc->streams[c->fc->nb_streams-1];
2075 avio_r8(pb); /* version */
2076 avio_rb24(pb); /* flags */
2077 entries = avio_rb32(pb);
2079 av_log(c->fc, AV_LOG_TRACE, "track[%i].stts.entries = %i\n",
2080 c->fc->nb_streams-1, entries);
2084 if (entries >= UINT_MAX / sizeof(*sc->stts_data))
2085 return AVERROR(EINVAL);
2087 av_free(sc->stts_data);
2088 sc->stts_data = av_malloc(entries * sizeof(*sc->stts_data));
2090 return AVERROR(ENOMEM);
2092 for (i = 0; i < entries && !pb->eof_reached; i++) {
2093 int sample_duration;
2096 sample_count=avio_rb32(pb);
2097 sample_duration = avio_rb32(pb);
2098 if (sample_count < 0) {
2099 av_log(c->fc, AV_LOG_ERROR, "Invalid sample_count=%d\n", sample_count);
2100 return AVERROR_INVALIDDATA;
2102 sc->stts_data[i].count= sample_count;
2103 sc->stts_data[i].duration= sample_duration;
2105 av_log(c->fc, AV_LOG_TRACE, "sample_count=%d, sample_duration=%d\n",
2106 sample_count, sample_duration);
2108 duration+=(int64_t)sample_duration*sample_count;
2109 total_sample_count+=sample_count;
2114 if (pb->eof_reached)
2117 st->nb_frames= total_sample_count;
2119 st->duration= duration;
2120 sc->track_end = duration;
2124 static int mov_read_ctts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2127 MOVStreamContext *sc;
2128 unsigned int i, entries;
2130 if (c->fc->nb_streams < 1)
2132 st = c->fc->streams[c->fc->nb_streams-1];
2135 avio_r8(pb); /* version */
2136 avio_rb24(pb); /* flags */
2137 entries = avio_rb32(pb);
2139 av_log(c->fc, AV_LOG_TRACE, "track[%i].ctts.entries = %i\n", c->fc->nb_streams-1, entries);
2141 av_freep(&sc->ctts_data);
2145 if (entries >= UINT_MAX / sizeof(*sc->ctts_data))
2146 return AVERROR_INVALIDDATA;
2147 sc->ctts_data = av_realloc(NULL, entries * sizeof(*sc->ctts_data));
2149 return AVERROR(ENOMEM);
2151 for (i = 0; i < entries && !pb->eof_reached; i++) {
2152 int count =avio_rb32(pb);
2153 int duration =avio_rb32(pb);
2155 sc->ctts_data[i].count = count;
2156 sc->ctts_data[i].duration= duration;
2158 sc->dts_shift = FFMAX(sc->dts_shift, -duration);
2163 if (pb->eof_reached)
2166 av_log(c->fc, AV_LOG_TRACE, "dts shift %d\n", sc->dts_shift);
2171 static int mov_read_sbgp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2174 MOVStreamContext *sc;
2175 unsigned int i, entries;
2177 uint32_t grouping_type;
2179 if (c->fc->nb_streams < 1)
2181 st = c->fc->streams[c->fc->nb_streams-1];
2184 version = avio_r8(pb); /* version */
2185 avio_rb24(pb); /* flags */
2186 grouping_type = avio_rl32(pb);
2187 if (grouping_type != MKTAG( 'r','a','p',' '))
2188 return 0; /* only support 'rap ' grouping */
2190 avio_rb32(pb); /* grouping_type_parameter */
2192 entries = avio_rb32(pb);
2195 if (entries >= UINT_MAX / sizeof(*sc->rap_group))
2196 return AVERROR_INVALIDDATA;
2197 sc->rap_group = av_malloc(entries * sizeof(*sc->rap_group));
2199 return AVERROR(ENOMEM);
2201 for (i = 0; i < entries && !pb->eof_reached; i++) {
2202 sc->rap_group[i].count = avio_rb32(pb); /* sample_count */
2203 sc->rap_group[i].index = avio_rb32(pb); /* group_description_index */
2206 sc->rap_group_count = i;
2208 return pb->eof_reached ? AVERROR_EOF : 0;
2211 static void mov_build_index(MOVContext *mov, AVStream *st)
2213 MOVStreamContext *sc = st->priv_data;
2214 int64_t current_offset;
2215 int64_t current_dts = 0;
2216 unsigned int stts_index = 0;
2217 unsigned int stsc_index = 0;
2218 unsigned int stss_index = 0;
2219 unsigned int stps_index = 0;
2221 uint64_t stream_size = 0;
2223 /* adjust first dts according to edit list */
2224 if (sc->time_offset && mov->time_scale > 0) {
2225 if (sc->time_offset < 0)
2226 sc->time_offset = av_rescale(sc->time_offset, sc->time_scale, mov->time_scale);
2227 current_dts = -sc->time_offset;
2228 if (sc->ctts_data && sc->stts_data && sc->stts_data[0].duration &&
2229 sc->ctts_data[0].duration / sc->stts_data[0].duration > 16) {
2230 /* more than 16 frames delay, dts are likely wrong
2231 this happens with files created by iMovie */
2233 st->internal->avctx->has_b_frames = 1;
2237 /* only use old uncompressed audio chunk demuxing when stts specifies it */
2238 if (!(st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
2239 sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
2240 unsigned int current_sample = 0;
2241 unsigned int stts_sample = 0;
2242 unsigned int sample_size;
2243 unsigned int distance = 0;
2244 unsigned int rap_group_index = 0;
2245 unsigned int rap_group_sample = 0;
2246 int rap_group_present = sc->rap_group_count && sc->rap_group;
2247 int key_off = (sc->keyframes && sc->keyframes[0] > 0) || (sc->stps_data && sc->stps_data[0] > 0);
2249 current_dts -= sc->dts_shift;
2251 if (!sc->sample_count)
2253 if (sc->sample_count >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
2255 if (av_reallocp_array(&st->index_entries,
2256 st->nb_index_entries + sc->sample_count,
2257 sizeof(*st->index_entries)) < 0) {
2258 st->nb_index_entries = 0;
2261 st->index_entries_allocated_size = (st->nb_index_entries + sc->sample_count) * sizeof(*st->index_entries);
2263 for (i = 0; i < sc->chunk_count; i++) {
2264 current_offset = sc->chunk_offsets[i];
2265 while (stsc_index + 1 < sc->stsc_count &&
2266 i + 1 == sc->stsc_data[stsc_index + 1].first)
2268 for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
2270 if (current_sample >= sc->sample_count) {
2271 av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
2275 if (!sc->keyframe_absent && (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index])) {
2277 if (stss_index + 1 < sc->keyframe_count)
2279 } else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) {
2281 if (stps_index + 1 < sc->stps_count)
2284 if (rap_group_present && rap_group_index < sc->rap_group_count) {
2285 if (sc->rap_group[rap_group_index].index > 0)
2287 if (++rap_group_sample == sc->rap_group[rap_group_index].count) {
2288 rap_group_sample = 0;
2294 sample_size = sc->sample_size > 0 ? sc->sample_size : sc->sample_sizes[current_sample];
2295 if (sc->pseudo_stream_id == -1 ||
2296 sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
2297 AVIndexEntry *e = &st->index_entries[st->nb_index_entries++];
2298 e->pos = current_offset;
2299 e->timestamp = current_dts;
2300 e->size = sample_size;
2301 e->min_distance = distance;
2302 e->flags = keyframe ? AVINDEX_KEYFRAME : 0;
2303 av_log(mov->fc, AV_LOG_TRACE, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
2304 "size %d, distance %d, keyframe %d\n", st->index, current_sample,
2305 current_offset, current_dts, sample_size, distance, keyframe);
2308 current_offset += sample_size;
2309 stream_size += sample_size;
2310 current_dts += sc->stts_data[stts_index].duration;
2314 if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
2320 if (st->duration > 0)
2321 st->codecpar->bit_rate = stream_size*8*sc->time_scale/st->duration;
2323 unsigned chunk_samples, total = 0;
2325 // compute total chunk count
2326 for (i = 0; i < sc->stsc_count; i++) {
2327 unsigned count, chunk_count;
2329 chunk_samples = sc->stsc_data[i].count;
2330 if (i != sc->stsc_count - 1 &&
2331 sc->samples_per_frame && chunk_samples % sc->samples_per_frame) {
2332 av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n");
2336 if (sc->samples_per_frame >= 160) { // gsm
2337 count = chunk_samples / sc->samples_per_frame;
2338 } else if (sc->samples_per_frame > 1) {
2339 unsigned samples = (1024/sc->samples_per_frame)*sc->samples_per_frame;
2340 count = (chunk_samples+samples-1) / samples;
2342 count = (chunk_samples+1023) / 1024;
2345 if (i < sc->stsc_count - 1)
2346 chunk_count = sc->stsc_data[i+1].first - sc->stsc_data[i].first;
2348 chunk_count = sc->chunk_count - (sc->stsc_data[i].first - 1);
2349 total += chunk_count * count;
2352 av_log(mov->fc, AV_LOG_TRACE, "chunk count %d\n", total);
2353 if (total >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
2355 if (av_reallocp_array(&st->index_entries,
2356 st->nb_index_entries + total,
2357 sizeof(*st->index_entries)) < 0) {
2358 st->nb_index_entries = 0;
2361 st->index_entries_allocated_size = (st->nb_index_entries + total) * sizeof(*st->index_entries);
2364 for (i = 0; i < sc->chunk_count; i++) {
2365 current_offset = sc->chunk_offsets[i];
2366 if (stsc_index + 1 < sc->stsc_count &&
2367 i + 1 == sc->stsc_data[stsc_index + 1].first)
2369 chunk_samples = sc->stsc_data[stsc_index].count;
2371 while (chunk_samples > 0) {
2373 unsigned size, samples;
2375 if (sc->samples_per_frame > 1 && !sc->bytes_per_frame) {
2376 avpriv_request_sample(mov->fc,
2377 "Zero bytes per frame, but %d samples per frame",
2378 sc->samples_per_frame);
2382 if (sc->samples_per_frame >= 160) { // gsm
2383 samples = sc->samples_per_frame;
2384 size = sc->bytes_per_frame;
2386 if (sc->samples_per_frame > 1) {
2387 samples = FFMIN((1024 / sc->samples_per_frame)*
2388 sc->samples_per_frame, chunk_samples);
2389 size = (samples / sc->samples_per_frame) * sc->bytes_per_frame;
2391 samples = FFMIN(1024, chunk_samples);
2392 size = samples * sc->sample_size;
2396 if (st->nb_index_entries >= total) {
2397 av_log(mov->fc, AV_LOG_ERROR, "wrong chunk count %d\n", total);
2400 e = &st->index_entries[st->nb_index_entries++];
2401 e->pos = current_offset;
2402 e->timestamp = current_dts;
2404 e->min_distance = 0;
2405 e->flags = AVINDEX_KEYFRAME;
2406 av_log(mov->fc, AV_LOG_TRACE, "AVIndex stream %d, chunk %d, offset %"PRIx64", dts %"PRId64", "
2407 "size %d, duration %d\n", st->index, i, current_offset, current_dts,
2410 current_offset += size;
2411 current_dts += samples;
2412 chunk_samples -= samples;
2418 static int mov_open_dref(AVFormatContext *s, AVIOContext **pb, char *src,
2421 /* try relative path, we do not try the absolute because it can leak information about our
2422 system to an attacker */
2423 if (ref->nlvl_to > 0 && ref->nlvl_from > 0) {
2424 char filename[1024];
2428 /* find a source dir */
2429 src_path = strrchr(src, '/');
2435 /* find a next level down to target */
2436 for (i = 0, l = strlen(ref->path) - 1; l >= 0; l--)
2437 if (ref->path[l] == '/') {
2438 if (i == ref->nlvl_to - 1)
2444 /* compose filename if next level down to target was found */
2445 if (i == ref->nlvl_to - 1 && src_path - src < sizeof(filename)) {
2446 memcpy(filename, src, src_path - src);
2447 filename[src_path - src] = 0;
2449 for (i = 1; i < ref->nlvl_from; i++)
2450 av_strlcat(filename, "../", 1024);
2452 av_strlcat(filename, ref->path + l + 1, 1024);
2454 if (!s->io_open(s, pb, filename, AVIO_FLAG_READ, NULL))
2459 return AVERROR(ENOENT);
2462 static int mov_read_trak(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2465 MOVStreamContext *sc;
2468 st = avformat_new_stream(c->fc, NULL);
2469 if (!st) return AVERROR(ENOMEM);
2470 st->id = c->fc->nb_streams;
2471 sc = av_mallocz(sizeof(MOVStreamContext));
2472 if (!sc) return AVERROR(ENOMEM);
2475 st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
2476 sc->ffindex = st->index;
2478 if ((ret = mov_read_default(c, pb, atom)) < 0)
2482 if (sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
2483 (!sc->sample_size && !sc->sample_count))) {
2484 av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
2489 if (sc->time_scale <= 0) {
2490 av_log(c->fc, AV_LOG_WARNING, "stream %d, timescale not set\n", st->index);
2491 sc->time_scale = c->time_scale;
2492 if (sc->time_scale <= 0)
2496 avpriv_set_pts_info(st, 64, 1, sc->time_scale);
2498 mov_build_index(c, st);
2500 if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
2501 MOVDref *dref = &sc->drefs[sc->dref_id - 1];
2502 if (c->enable_drefs) {
2503 if (mov_open_dref(c->fc, &sc->pb, c->fc->filename, dref) < 0)
2504 av_log(c->fc, AV_LOG_ERROR,
2505 "stream %d, error opening alias: path='%s', dir='%s', "
2506 "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d\n",
2507 st->index, dref->path, dref->dir, dref->filename,
2508 dref->volume, dref->nlvl_from, dref->nlvl_to);
2510 av_log(c->fc, AV_LOG_WARNING,
2511 "Skipped opening external track: "
2512 "stream %d, alias: path='%s', dir='%s', "
2513 "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d."
2514 "Set enable_drefs to allow this.\n",
2515 st->index, dref->path, dref->dir, dref->filename,
2516 dref->volume, dref->nlvl_from, dref->nlvl_to);
2521 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
2522 if (!st->sample_aspect_ratio.num &&
2523 (st->codecpar->width != sc->width || st->codecpar->height != sc->height)) {
2524 st->sample_aspect_ratio = av_d2q(((double)st->codecpar->height * sc->width) /
2525 ((double)st->codecpar->width * sc->height), INT_MAX);
2529 // done for ai5q, ai52, ai55, ai1q, ai12 and ai15.
2530 if (!st->codecpar->extradata_size && st->codecpar->codec_id == AV_CODEC_ID_H264 &&
2531 TAG_IS_AVCI(st->codecpar->codec_tag)) {
2532 ret = ff_generate_avci_extradata(st);
2537 switch (st->codecpar->codec_id) {
2538 #if CONFIG_H261_DECODER
2539 case AV_CODEC_ID_H261:
2541 #if CONFIG_H263_DECODER
2542 case AV_CODEC_ID_H263:
2544 #if CONFIG_MPEG4_DECODER
2545 case AV_CODEC_ID_MPEG4:
2547 st->codecpar->width = 0; /* let decoder init width/height */
2548 st->codecpar->height= 0;
2550 case AV_CODEC_ID_MP3:
2551 st->need_parsing = AVSTREAM_PARSE_FULL;
2555 /* Do not need those anymore. */
2556 av_freep(&sc->chunk_offsets);
2557 av_freep(&sc->stsc_data);
2558 av_freep(&sc->sample_sizes);
2559 av_freep(&sc->keyframes);
2560 av_freep(&sc->stts_data);
2561 av_freep(&sc->stps_data);
2562 av_freep(&sc->rap_group);
2567 static int mov_read_ilst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2570 c->itunes_metadata = 1;
2571 ret = mov_read_default(c, pb, atom);
2572 c->itunes_metadata = 0;
2576 static int mov_read_replaygain(MOVContext *c, AVIOContext *pb, int64_t size)
2578 int64_t end = avio_tell(pb) + size;
2579 uint8_t *key = NULL, *val = NULL;
2582 for (i = 0; i < 2; i++) {
2587 if (end - avio_tell(pb) <= 12)
2590 len = avio_rb32(pb);
2591 tag = avio_rl32(pb);
2592 avio_skip(pb, 4); // flags
2594 if (len < 12 || len - 12 > end - avio_tell(pb))
2598 if (tag == MKTAG('n', 'a', 'm', 'e'))
2600 else if (tag == MKTAG('d', 'a', 't', 'a') && len > 4) {
2607 *p = av_malloc(len + 1);
2610 ret = ffio_read_size(pb, *p, len);
2619 av_dict_set(&c->fc->metadata, key, val,
2620 AV_DICT_DONT_STRDUP_KEY | AV_DICT_DONT_STRDUP_VAL);
2624 avio_seek(pb, end, SEEK_SET);
2630 static int mov_read_custom(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2632 int64_t end = avio_tell(pb) + atom.size;
2638 len = avio_rb32(pb);
2639 tag = avio_rl32(pb);
2641 if (len > atom.size)
2644 if (tag == MKTAG('m', 'e', 'a', 'n') && len > 12) {
2645 uint8_t domain[128];
2648 avio_skip(pb, 4); // flags
2651 domain_len = avio_get_str(pb, len, domain, sizeof(domain));
2652 avio_skip(pb, len - domain_len);
2653 if (!strcmp(domain, "org.hydrogenaudio.replaygain"))
2654 return mov_read_replaygain(c, pb, end - avio_tell(pb));
2658 av_log(c->fc, AV_LOG_VERBOSE,
2659 "Unhandled or malformed custom metadata of size %"PRId64"\n", atom.size);
2663 static int mov_read_meta(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2665 while (atom.size > 8) {
2666 uint32_t tag = avio_rl32(pb);
2668 if (tag == MKTAG('h','d','l','r')) {
2669 avio_seek(pb, -8, SEEK_CUR);
2671 return mov_read_default(c, pb, atom);
2677 static int mov_read_tkhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2682 int64_t disp_transform[2];
2683 int display_matrix[3][3];
2685 MOVStreamContext *sc;
2689 if (c->fc->nb_streams < 1)
2691 st = c->fc->streams[c->fc->nb_streams-1];
2694 version = avio_r8(pb);
2695 flags = avio_rb24(pb);
2696 st->disposition |= (flags & MOV_TKHD_FLAG_ENABLED) ? AV_DISPOSITION_DEFAULT : 0;
2702 avio_rb32(pb); /* creation time */
2703 avio_rb32(pb); /* modification time */
2705 st->id = (int)avio_rb32(pb); /* track id (NOT 0 !)*/
2706 avio_rb32(pb); /* reserved */
2708 /* highlevel (considering edits) duration in movie timebase */
2709 (version == 1) ? avio_rb64(pb) : avio_rb32(pb);
2710 avio_rb32(pb); /* reserved */
2711 avio_rb32(pb); /* reserved */
2713 avio_rb16(pb); /* layer */
2714 avio_rb16(pb); /* alternate group */
2715 avio_rb16(pb); /* volume */
2716 avio_rb16(pb); /* reserved */
2718 //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
2719 // they're kept in fixed point format through all calculations
2720 // save u,v,z to store the whole matrix in the AV_PKT_DATA_DISPLAYMATRIX
2721 // side data, but the scale factor is not needed to calculate aspect ratio
2722 for (i = 0; i < 3; i++) {
2723 display_matrix[i][0] = avio_rb32(pb); // 16.16 fixed point
2724 display_matrix[i][1] = avio_rb32(pb); // 16.16 fixed point
2725 display_matrix[i][2] = avio_rb32(pb); // 2.30 fixed point
2728 width = avio_rb32(pb); // 16.16 fixed point track width
2729 height = avio_rb32(pb); // 16.16 fixed point track height
2730 sc->width = width >> 16;
2731 sc->height = height >> 16;
2733 // save the matrix when it is not the default identity
2734 if (display_matrix[0][0] != (1 << 16) ||
2735 display_matrix[1][1] != (1 << 16) ||
2736 display_matrix[2][2] != (1 << 30) ||
2737 display_matrix[0][1] || display_matrix[0][2] ||
2738 display_matrix[1][0] || display_matrix[1][2] ||
2739 display_matrix[2][0] || display_matrix[2][1]) {
2742 av_freep(&sc->display_matrix);
2743 sc->display_matrix = av_malloc(sizeof(int32_t) * 9);
2744 if (!sc->display_matrix)
2745 return AVERROR(ENOMEM);
2747 for (i = 0; i < 3; i++)
2748 for (j = 0; j < 3; j++)
2749 sc->display_matrix[i * 3 + j] = display_matrix[i][j];
2752 // transform the display width/height according to the matrix
2753 // skip this when the display matrix is the identity one
2754 // to keep the same scale, use [width height 1<<16]
2755 if (width && height && sc->display_matrix) {
2756 for (i = 0; i < 2; i++)
2758 (int64_t) width * display_matrix[0][i] +
2759 (int64_t) height * display_matrix[1][i] +
2760 ((int64_t) display_matrix[2][i] << 16);
2762 //sample aspect ratio is new width/height divided by old width/height
2763 if (disp_transform[0] > 0 && disp_transform[1] > 0)
2764 st->sample_aspect_ratio = av_d2q(
2765 ((double) disp_transform[0] * height) /
2766 ((double) disp_transform[1] * width), INT_MAX);
2771 static int mov_read_tfhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2773 MOVFragment *frag = &c->fragment;
2774 MOVTrackExt *trex = NULL;
2775 int flags, track_id, i;
2777 avio_r8(pb); /* version */
2778 flags = avio_rb24(pb);
2780 track_id = avio_rb32(pb);
2782 return AVERROR_INVALIDDATA;
2783 frag->track_id = track_id;
2784 for (i = 0; i < c->trex_count; i++)
2785 if (c->trex_data[i].track_id == frag->track_id) {
2786 trex = &c->trex_data[i];
2790 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
2791 return AVERROR_INVALIDDATA;
2794 frag->base_data_offset = flags & MOV_TFHD_BASE_DATA_OFFSET ?
2795 avio_rb64(pb) : flags & MOV_TFHD_DEFAULT_BASE_IS_MOOF ?
2796 frag->moof_offset : frag->implicit_offset;
2797 frag->stsd_id = flags & MOV_TFHD_STSD_ID ? avio_rb32(pb) : trex->stsd_id;
2799 frag->duration = flags & MOV_TFHD_DEFAULT_DURATION ?
2800 avio_rb32(pb) : trex->duration;
2801 frag->size = flags & MOV_TFHD_DEFAULT_SIZE ?
2802 avio_rb32(pb) : trex->size;
2803 frag->flags = flags & MOV_TFHD_DEFAULT_FLAGS ?
2804 avio_rb32(pb) : trex->flags;
2805 av_log(c->fc, AV_LOG_TRACE, "frag flags 0x%x\n", frag->flags);
2809 static int mov_read_chap(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2811 c->chapter_track = avio_rb32(pb);
2815 static int mov_read_trex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2820 if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
2821 return AVERROR_INVALIDDATA;
2822 if ((err = av_reallocp_array(&c->trex_data, c->trex_count + 1,
2823 sizeof(*c->trex_data))) < 0) {
2827 trex = &c->trex_data[c->trex_count++];
2828 avio_r8(pb); /* version */
2829 avio_rb24(pb); /* flags */
2830 trex->track_id = avio_rb32(pb);
2831 trex->stsd_id = avio_rb32(pb);
2832 trex->duration = avio_rb32(pb);
2833 trex->size = avio_rb32(pb);
2834 trex->flags = avio_rb32(pb);
2838 static int mov_read_tfdt(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2840 MOVFragment *frag = &c->fragment;
2841 AVStream *st = NULL;
2842 MOVStreamContext *sc;
2845 for (i = 0; i < c->fc->nb_streams; i++) {
2846 if (c->fc->streams[i]->id == frag->track_id) {
2847 st = c->fc->streams[i];
2852 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
2853 return AVERROR_INVALIDDATA;
2856 if (sc->pseudo_stream_id + 1 != frag->stsd_id)
2858 version = avio_r8(pb);
2859 avio_rb24(pb); /* flags */
2861 sc->track_end = avio_rb64(pb);
2863 sc->track_end = avio_rb32(pb);
2868 static int mov_read_trun(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2870 MOVFragment *frag = &c->fragment;
2871 AVStream *st = NULL;
2872 MOVStreamContext *sc;
2876 int data_offset = 0;
2877 unsigned entries, first_sample_flags = frag->flags;
2878 int flags, distance, i, err;
2880 for (i = 0; i < c->fc->nb_streams; i++) {
2881 if (c->fc->streams[i]->id == frag->track_id) {
2882 st = c->fc->streams[i];
2887 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
2888 return AVERROR_INVALIDDATA;
2891 if (sc->pseudo_stream_id+1 != frag->stsd_id)
2893 avio_r8(pb); /* version */
2894 flags = avio_rb24(pb);
2895 entries = avio_rb32(pb);
2896 av_log(c->fc, AV_LOG_TRACE, "flags 0x%x entries %d\n", flags, entries);
2898 /* Always assume the presence of composition time offsets.
2899 * Without this assumption, for instance, we cannot deal with a track in fragmented movies that meet the following.
2900 * 1) in the initial movie, there are no samples.
2901 * 2) in the first movie fragment, there is only one sample without composition time offset.
2902 * 3) in the subsequent movie fragments, there are samples with composition time offset. */
2903 if (!sc->ctts_count && sc->sample_count)
2905 /* Complement ctts table if moov atom doesn't have ctts atom. */
2906 ctts_data = av_realloc(NULL, sizeof(*sc->ctts_data));
2908 return AVERROR(ENOMEM);
2909 sc->ctts_data = ctts_data;
2910 sc->ctts_data[sc->ctts_count].count = sc->sample_count;
2911 sc->ctts_data[sc->ctts_count].duration = 0;
2914 if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
2915 return AVERROR_INVALIDDATA;
2916 if ((err = av_reallocp_array(&sc->ctts_data, entries + sc->ctts_count,
2917 sizeof(*sc->ctts_data))) < 0) {
2921 if (flags & MOV_TRUN_DATA_OFFSET) data_offset = avio_rb32(pb);
2922 if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS) first_sample_flags = avio_rb32(pb);
2923 dts = sc->track_end - sc->time_offset;
2924 offset = frag->base_data_offset + data_offset;
2926 av_log(c->fc, AV_LOG_TRACE, "first sample flags 0x%x\n", first_sample_flags);
2927 for (i = 0; i < entries && !pb->eof_reached; i++) {
2928 unsigned sample_size = frag->size;
2929 int sample_flags = i ? frag->flags : first_sample_flags;
2930 unsigned sample_duration = frag->duration;
2933 if (flags & MOV_TRUN_SAMPLE_DURATION) sample_duration = avio_rb32(pb);
2934 if (flags & MOV_TRUN_SAMPLE_SIZE) sample_size = avio_rb32(pb);
2935 if (flags & MOV_TRUN_SAMPLE_FLAGS) sample_flags = avio_rb32(pb);
2936 sc->ctts_data[sc->ctts_count].count = 1;
2937 sc->ctts_data[sc->ctts_count].duration = (flags & MOV_TRUN_SAMPLE_CTS) ?
2940 if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
2944 !(sample_flags & (MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC |
2945 MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES));
2948 av_add_index_entry(st, offset, dts, sample_size, distance,
2949 keyframe ? AVINDEX_KEYFRAME : 0);
2950 av_log(c->fc, AV_LOG_TRACE, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
2951 "size %d, distance %d, keyframe %d\n", st->index, sc->sample_count+i,
2952 offset, dts, sample_size, distance, keyframe);
2954 dts += sample_duration;
2955 offset += sample_size;
2956 sc->data_size += sample_size;
2959 if (pb->eof_reached)
2962 frag->implicit_offset = offset;
2963 st->duration = sc->track_end = dts + sc->time_offset;
2967 /* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
2968 /* like the files created with Adobe Premiere 5.0, for samples see */
2969 /* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
2970 static int mov_read_wide(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2975 return 0; /* continue */
2976 if (avio_rb32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
2977 avio_skip(pb, atom.size - 4);
2980 atom.type = avio_rl32(pb);
2982 if (atom.type != MKTAG('m','d','a','t')) {
2983 avio_skip(pb, atom.size);
2986 err = mov_read_mdat(c, pb, atom);
2990 static int mov_read_cmov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2995 uint8_t *moov_data; /* uncompressed data */
2996 long cmov_len, moov_len;
2999 avio_rb32(pb); /* dcom atom */
3000 if (avio_rl32(pb) != MKTAG('d','c','o','m'))
3001 return AVERROR_INVALIDDATA;
3002 if (avio_rl32(pb) != MKTAG('z','l','i','b')) {
3003 av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !");
3004 return AVERROR_INVALIDDATA;
3006 avio_rb32(pb); /* cmvd atom */
3007 if (avio_rl32(pb) != MKTAG('c','m','v','d'))
3008 return AVERROR_INVALIDDATA;
3009 moov_len = avio_rb32(pb); /* uncompressed size */
3010 cmov_len = atom.size - 6 * 4;
3012 cmov_data = av_malloc(cmov_len);
3014 return AVERROR(ENOMEM);
3015 moov_data = av_malloc(moov_len);
3018 return AVERROR(ENOMEM);
3020 ret = ffio_read_size(pb, cmov_data, cmov_len);
3022 goto free_and_return;
3024 if (uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
3025 goto free_and_return;
3026 if (ffio_init_context(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
3027 goto free_and_return;
3028 atom.type = MKTAG('m','o','o','v');
3029 atom.size = moov_len;
3030 ret = mov_read_default(c, &ctx, atom);
3036 av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
3037 return AVERROR(ENOSYS);
3041 /* edit list atom */
3042 static int mov_read_elst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3044 MOVStreamContext *sc;
3045 int i, edit_count, version;
3047 if (c->fc->nb_streams < 1)
3049 sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
3051 version = avio_r8(pb); /* version */
3052 avio_rb24(pb); /* flags */
3053 edit_count = avio_rb32(pb); /* entries */
3055 if ((uint64_t)edit_count*12+8 > atom.size)
3056 return AVERROR_INVALIDDATA;
3058 for (i=0; i<edit_count; i++){
3062 duration = avio_rb64(pb);
3063 time = avio_rb64(pb);
3065 duration = avio_rb32(pb); /* segment duration */
3066 time = (int32_t)avio_rb32(pb); /* media time */
3068 avio_rb32(pb); /* Media rate */
3069 if (i == 0 && time >= -1) {
3070 sc->time_offset = time != -1 ? time : -duration;
3075 av_log(c->fc, AV_LOG_WARNING, "multiple edit list entries, "
3076 "a/v desync might occur, patch welcome\n");
3078 av_log(c->fc, AV_LOG_TRACE, "track[%i].edit_count = %i\n", c->fc->nb_streams-1, edit_count);
3082 static const MOVParseTableEntry mov_default_parse_table[] = {
3083 { MKTAG('a','v','s','s'), mov_read_extradata },
3084 { MKTAG('c','h','p','l'), mov_read_chpl },
3085 { MKTAG('c','o','6','4'), mov_read_stco },
3086 { MKTAG('c','o','l','r'), mov_read_colr },
3087 { MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
3088 { MKTAG('d','i','n','f'), mov_read_default },
3089 { MKTAG('d','r','e','f'), mov_read_dref },
3090 { MKTAG('e','d','t','s'), mov_read_default },
3091 { MKTAG('e','l','s','t'), mov_read_elst },
3092 { MKTAG('e','n','d','a'), mov_read_enda },
3093 { MKTAG('f','i','e','l'), mov_read_fiel },
3094 { MKTAG('f','t','y','p'), mov_read_ftyp },
3095 { MKTAG('g','l','b','l'), mov_read_glbl },
3096 { MKTAG('h','d','l','r'), mov_read_hdlr },
3097 { MKTAG('i','l','s','t'), mov_read_ilst },
3098 { MKTAG('j','p','2','h'), mov_read_extradata },
3099 { MKTAG('m','d','a','t'), mov_read_mdat },
3100 { MKTAG('m','d','h','d'), mov_read_mdhd },
3101 { MKTAG('m','d','i','a'), mov_read_default },
3102 { MKTAG('m','e','t','a'), mov_read_meta },
3103 { MKTAG('m','i','n','f'), mov_read_default },
3104 { MKTAG('m','o','o','f'), mov_read_moof },
3105 { MKTAG('m','o','o','v'), mov_read_moov },
3106 { MKTAG('m','v','e','x'), mov_read_default },
3107 { MKTAG('m','v','h','d'), mov_read_mvhd },
3108 { MKTAG('S','M','I',' '), mov_read_smi }, /* Sorenson extension ??? */
3109 { MKTAG('a','l','a','c'), mov_read_extradata }, /* alac specific atom */
3110 { MKTAG('a','v','c','C'), mov_read_glbl },
3111 { MKTAG('p','a','s','p'), mov_read_pasp },
3112 { MKTAG('s','t','b','l'), mov_read_default },
3113 { MKTAG('s','t','c','o'), mov_read_stco },
3114 { MKTAG('s','t','p','s'), mov_read_stps },
3115 { MKTAG('s','t','r','f'), mov_read_strf },
3116 { MKTAG('s','t','s','c'), mov_read_stsc },
3117 { MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
3118 { MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
3119 { MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
3120 { MKTAG('s','t','t','s'), mov_read_stts },
3121 { MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */
3122 { MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
3123 { MKTAG('t','f','d','t'), mov_read_tfdt },
3124 { MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
3125 { MKTAG('t','r','a','k'), mov_read_trak },
3126 { MKTAG('t','r','a','f'), mov_read_default },
3127 { MKTAG('t','r','e','f'), mov_read_default },
3128 { MKTAG('c','h','a','p'), mov_read_chap },
3129 { MKTAG('t','r','e','x'), mov_read_trex },
3130 { MKTAG('t','r','u','n'), mov_read_trun },
3131 { MKTAG('u','d','t','a'), mov_read_default },
3132 { MKTAG('w','a','v','e'), mov_read_wave },
3133 { MKTAG('e','s','d','s'), mov_read_esds },
3134 { MKTAG('d','a','c','3'), mov_read_dac3 }, /* AC-3 info */
3135 { MKTAG('d','e','c','3'), mov_read_dec3 }, /* EAC-3 info */
3136 { MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
3137 { MKTAG('w','f','e','x'), mov_read_wfex },
3138 { MKTAG('c','m','o','v'), mov_read_cmov },
3139 { MKTAG('c','h','a','n'), mov_read_chan }, /* channel layout */
3140 { MKTAG('d','v','c','1'), mov_read_dvc1 },
3141 { MKTAG('s','b','g','p'), mov_read_sbgp },
3142 { MKTAG('h','v','c','C'), mov_read_glbl },
3143 { MKTAG('-','-','-','-'), mov_read_custom },
3147 static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3149 int64_t total_size = 0;
3154 atom.size = INT64_MAX;
3155 while (total_size + 8 < atom.size && !pb->eof_reached) {
3156 int (*parse)(MOVContext*, AVIOContext*, MOVAtom) = NULL;
3159 if (atom.size >= 8) {
3160 a.size = avio_rb32(pb);
3161 a.type = avio_rl32(pb);
3163 av_log(c->fc, AV_LOG_TRACE, "type: %08x '%.4s' parent:'%.4s' sz: %"PRId64" %"PRId64" %"PRId64"\n",
3164 a.type, (char*)&a.type, (char*)&atom.type, a.size, total_size, atom.size);
3166 if (a.size == 1) { /* 64 bit extended size */
3167 a.size = avio_rb64(pb) - 8;
3171 a.size = atom.size - total_size;
3178 a.size = FFMIN(a.size, atom.size - total_size);
3180 for (i = 0; mov_default_parse_table[i].type; i++)
3181 if (mov_default_parse_table[i].type == a.type) {
3182 parse = mov_default_parse_table[i].parse;
3186 // container is user data
3187 if (!parse && (atom.type == MKTAG('u','d','t','a') ||
3188 atom.type == MKTAG('i','l','s','t')))
3189 parse = mov_read_udta_string;
3191 if (!parse) { /* skip leaf atoms data */
3192 avio_skip(pb, a.size);
3194 int64_t start_pos = avio_tell(pb);
3196 int err = parse(c, pb, a);
3199 if (c->found_moov && c->found_mdat &&
3200 ((!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX) ||
3201 start_pos + a.size == avio_size(pb))) {
3202 if (!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX)
3203 c->next_root_atom = start_pos + a.size;
3206 left = a.size - avio_tell(pb) + start_pos;
3207 if (left > 0) /* skip garbage at atom end */
3208 avio_skip(pb, left);
3209 else if (left < 0) {
3210 av_log(c->fc, AV_LOG_WARNING,
3211 "overread end of atom '%.4s' by %"PRId64" bytes\n",
3212 (char*)&a.type, -left);
3213 avio_seek(pb, left, SEEK_CUR);
3217 total_size += a.size;
3220 if (total_size < atom.size && atom.size < 0x7ffff)
3221 avio_skip(pb, atom.size - total_size);
3226 static int mov_probe(AVProbeData *p)
3228 unsigned int offset;
3232 /* check file header */
3235 /* ignore invalid offset */
3236 if ((offset + 8) > (unsigned int)p->buf_size)
3238 tag = AV_RL32(p->buf + offset + 4);
3240 /* check for obvious tags */
3241 case MKTAG('j','P',' ',' '): /* jpeg 2000 signature */
3242 case MKTAG('m','o','o','v'):
3243 case MKTAG('m','d','a','t'):
3244 case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
3245 case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
3246 case MKTAG('f','t','y','p'):
3247 return AVPROBE_SCORE_MAX;
3248 /* those are more common words, so rate then a bit less */
3249 case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
3250 case MKTAG('w','i','d','e'):
3251 case MKTAG('f','r','e','e'):
3252 case MKTAG('j','u','n','k'):
3253 case MKTAG('p','i','c','t'):
3254 return AVPROBE_SCORE_MAX - 5;
3255 case MKTAG(0x82,0x82,0x7f,0x7d):
3256 case MKTAG('s','k','i','p'):
3257 case MKTAG('u','u','i','d'):
3258 case MKTAG('p','r','f','l'):
3259 offset = AV_RB32(p->buf+offset) + offset;
3260 /* if we only find those cause probedata is too small at least rate them */
3261 score = AVPROBE_SCORE_EXTENSION;
3264 /* unrecognized tag */
3270 // must be done after parsing all trak because there's no order requirement
3271 static void mov_read_chapters(AVFormatContext *s)
3273 MOVContext *mov = s->priv_data;
3274 AVStream *st = NULL;
3275 MOVStreamContext *sc;
3279 for (i = 0; i < s->nb_streams; i++)
3280 if (s->streams[i]->id == mov->chapter_track) {
3285 av_log(s, AV_LOG_ERROR, "Referenced QT chapter track not found\n");
3289 st->discard = AVDISCARD_ALL;
3291 cur_pos = avio_tell(sc->pb);
3293 for (i = 0; i < st->nb_index_entries; i++) {
3294 AVIndexEntry *sample = &st->index_entries[i];
3295 int64_t end = i+1 < st->nb_index_entries ? st->index_entries[i+1].timestamp : st->duration;
3300 if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
3301 av_log(s, AV_LOG_ERROR, "Chapter %d not found in file\n", i);
3305 // the first two bytes are the length of the title
3306 len = avio_rb16(sc->pb);
3307 if (len > sample->size-2)
3309 title_len = 2*len + 1;
3310 if (!(title = av_mallocz(title_len)))
3313 // The samples could theoretically be in any encoding if there's an encd
3314 // atom following, but in practice are only utf-8 or utf-16, distinguished
3315 // instead by the presence of a BOM
3319 ch = avio_rb16(sc->pb);
3321 avio_get_str16be(sc->pb, len, title, title_len);
3322 else if (ch == 0xfffe)
3323 avio_get_str16le(sc->pb, len, title, title_len);
3326 if (len == 1 || len == 2)
3329 avio_get_str(sc->pb, len - 2, title + 2, title_len - 2);
3333 avpriv_new_chapter(s, i, st->time_base, sample->timestamp, end, title);
3337 avio_seek(sc->pb, cur_pos, SEEK_SET);
3340 static int mov_read_close(AVFormatContext *s)
3342 MOVContext *mov = s->priv_data;
3345 for (i = 0; i < s->nb_streams; i++) {
3346 AVStream *st = s->streams[i];
3347 MOVStreamContext *sc = st->priv_data;
3349 av_freep(&sc->ctts_data);
3350 for (j = 0; j < sc->drefs_count; j++) {
3351 av_freep(&sc->drefs[j].path);
3352 av_freep(&sc->drefs[j].dir);
3354 av_freep(&sc->drefs);
3355 if (sc->pb && sc->pb != s->pb)
3356 ff_format_io_close(s, &sc->pb);
3358 av_freep(&sc->chunk_offsets);
3359 av_freep(&sc->stsc_data);
3360 av_freep(&sc->sample_sizes);
3361 av_freep(&sc->keyframes);
3362 av_freep(&sc->stts_data);
3363 av_freep(&sc->stps_data);
3364 av_freep(&sc->rap_group);
3365 av_freep(&sc->display_matrix);
3368 if (mov->dv_demux) {
3369 avformat_free_context(mov->dv_fctx);
3370 mov->dv_fctx = NULL;
3373 av_freep(&mov->trex_data);
3378 static int mov_read_header(AVFormatContext *s)
3380 MOVContext *mov = s->priv_data;
3381 AVIOContext *pb = s->pb;
3383 MOVAtom atom = { AV_RL32("root") };
3387 /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
3389 atom.size = avio_size(pb);
3391 atom.size = INT64_MAX;
3393 /* check MOV header */
3394 if ((err = mov_read_default(mov, pb, atom)) < 0) {
3395 av_log(s, AV_LOG_ERROR, "error reading header: %d\n", err);
3399 if (!mov->found_moov) {
3400 av_log(s, AV_LOG_ERROR, "moov atom not found\n");
3402 return AVERROR_INVALIDDATA;
3404 av_log(mov->fc, AV_LOG_TRACE, "on_parse_exit_offset=%"PRId64"\n", avio_tell(pb));
3406 if (pb->seekable && mov->chapter_track > 0)
3407 mov_read_chapters(s);
3409 for (i = 0; i < s->nb_streams; i++) {
3410 AVStream *st = s->streams[i];
3411 MOVStreamContext *sc = st->priv_data;
3413 if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) {
3414 if (st->codecpar->width <= 0 || st->codecpar->height <= 0) {
3415 st->codecpar->width = sc->width;
3416 st->codecpar->height = sc->height;
3418 if (st->codecpar->codec_id == AV_CODEC_ID_DVD_SUBTITLE) {
3419 if ((err = mov_rewrite_dvd_sub_extradata(st)) < 0)
3425 if (mov->trex_data) {
3426 for (i = 0; i < s->nb_streams; i++) {
3427 AVStream *st = s->streams[i];
3428 MOVStreamContext *sc = st->priv_data;
3429 if (st->duration > 0)
3430 st->codecpar->bit_rate = sc->data_size * 8 * sc->time_scale / st->duration;
3434 for (i = 0; i < s->nb_streams; i++) {
3435 AVStream *st = s->streams[i];
3436 MOVStreamContext *sc = st->priv_data;
3438 switch (st->codecpar->codec_type) {
3439 case AVMEDIA_TYPE_AUDIO:
3440 err = ff_replaygain_export(st, s->metadata);
3446 case AVMEDIA_TYPE_VIDEO:
3447 if (sc->display_matrix) {
3448 AVPacketSideData *sd, *tmp;
3450 tmp = av_realloc_array(st->side_data,
3451 st->nb_side_data + 1, sizeof(*tmp));
3453 return AVERROR(ENOMEM);
3455 st->side_data = tmp;
3458 sd = &st->side_data[st->nb_side_data - 1];
3459 sd->type = AV_PKT_DATA_DISPLAYMATRIX;
3460 sd->size = sizeof(int32_t) * 9;
3461 sd->data = (uint8_t*)sc->display_matrix;
3462 sc->display_matrix = NULL;
3471 static AVIndexEntry *mov_find_next_sample(AVFormatContext *s, AVStream **st)
3473 AVIndexEntry *sample = NULL;
3474 int64_t best_dts = INT64_MAX;
3476 for (i = 0; i < s->nb_streams; i++) {
3477 AVStream *avst = s->streams[i];
3478 MOVStreamContext *msc = avst->priv_data;
3479 if (msc->pb && msc->current_sample < avst->nb_index_entries) {
3480 AVIndexEntry *current_sample = &avst->index_entries[msc->current_sample];
3481 int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale);
3482 av_log(s, AV_LOG_TRACE, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
3483 if (!sample || (!s->pb->seekable && current_sample->pos < sample->pos) ||
3485 ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb &&
3486 ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
3487 (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
3488 sample = current_sample;
3497 static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
3499 MOVContext *mov = s->priv_data;
3500 MOVStreamContext *sc;
3501 AVIndexEntry *sample;
3502 AVStream *st = NULL;
3505 sample = mov_find_next_sample(s, &st);
3507 mov->found_mdat = 0;
3508 if (!mov->next_root_atom)
3510 avio_seek(s->pb, mov->next_root_atom, SEEK_SET);
3511 mov->next_root_atom = 0;
3512 if (mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX }) < 0 ||
3515 av_log(s, AV_LOG_TRACE, "read fragments, offset 0x%"PRIx64"\n", avio_tell(s->pb));
3519 /* must be done just before reading, to avoid infinite loop on sample */
3520 sc->current_sample++;
3522 if (st->discard != AVDISCARD_ALL) {
3523 if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
3524 av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
3525 sc->ffindex, sample->pos);
3526 return AVERROR_INVALIDDATA;
3528 ret = av_get_packet(sc->pb, pkt, sample->size);
3531 if (sc->has_palette) {
3534 pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
3536 av_log(mov->fc, AV_LOG_ERROR, "Cannot append palette to packet\n");
3538 memcpy(pal, sc->palette, AVPALETTE_SIZE);
3539 sc->has_palette = 0;
3542 #if CONFIG_DV_DEMUXER
3543 if (mov->dv_demux && sc->dv_audio_container) {
3544 avpriv_dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size);
3547 ret = avpriv_dv_get_packet(mov->dv_demux, pkt);
3554 pkt->stream_index = sc->ffindex;
3555 pkt->dts = sample->timestamp;
3556 if (sc->ctts_data && sc->ctts_index < sc->ctts_count) {
3557 pkt->pts = pkt->dts + sc->dts_shift + sc->ctts_data[sc->ctts_index].duration;
3558 /* update ctts context */
3560 if (sc->ctts_index < sc->ctts_count &&
3561 sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
3563 sc->ctts_sample = 0;
3566 pkt->dts = AV_NOPTS_VALUE;
3568 int64_t next_dts = (sc->current_sample < st->nb_index_entries) ?
3569 st->index_entries[sc->current_sample].timestamp : st->duration;
3570 pkt->duration = next_dts - pkt->dts;
3571 pkt->pts = pkt->dts;
3573 if (st->discard == AVDISCARD_ALL)
3575 pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? AV_PKT_FLAG_KEY : 0;
3576 pkt->pos = sample->pos;
3577 av_log(s, AV_LOG_TRACE, "stream %d, pts %"PRId64", dts %"PRId64", pos 0x%"PRIx64", duration %"PRId64"\n",
3578 pkt->stream_index, pkt->pts, pkt->dts, pkt->pos, pkt->duration);
3582 static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp, int flags)
3584 MOVStreamContext *sc = st->priv_data;
3585 int sample, time_sample;
3588 sample = av_index_search_timestamp(st, timestamp, flags);
3589 av_log(s, AV_LOG_TRACE, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
3590 if (sample < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
3592 if (sample < 0) /* not sure what to do */
3593 return AVERROR_INVALIDDATA;
3594 sc->current_sample = sample;
3595 av_log(s, AV_LOG_TRACE, "stream %d, found sample %d\n", st->index, sc->current_sample);
3596 /* adjust ctts index */
3597 if (sc->ctts_data) {
3599 for (i = 0; i < sc->ctts_count; i++) {
3600 int next = time_sample + sc->ctts_data[i].count;
3601 if (next > sc->current_sample) {
3603 sc->ctts_sample = sc->current_sample - time_sample;
3612 static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
3614 MOVContext *mc = s->priv_data;
3619 if (stream_index >= s->nb_streams)
3620 return AVERROR_INVALIDDATA;
3621 if (sample_time < 0)
3624 st = s->streams[stream_index];
3625 sample = mov_seek_stream(s, st, sample_time, flags);
3629 if (mc->seek_individually) {
3630 /* adjust seek timestamp to found sample timestamp */
3631 int64_t seek_timestamp = st->index_entries[sample].timestamp;
3633 for (i = 0; i < s->nb_streams; i++) {
3636 if (stream_index == i)
3639 timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
3640 mov_seek_stream(s, st, timestamp, flags);
3643 for (i = 0; i < s->nb_streams; i++) {
3644 MOVStreamContext *sc;
3647 sc->current_sample = 0;
3650 MOVStreamContext *sc;
3651 AVIndexEntry *entry = mov_find_next_sample(s, &st);
3653 return AVERROR_INVALIDDATA;
3655 if (sc->ffindex == stream_index && sc->current_sample == sample)
3657 sc->current_sample++;
3663 #define OFFSET(x) offsetof(MOVContext, x)
3664 #define FLAGS AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
3665 static const AVOption mov_options[] = {
3666 {"seek_streams_individually",
3667 "Seek each stream individually to the to the closest point",
3668 OFFSET(seek_individually), AV_OPT_TYPE_INT, { .i64 = 1 },
3670 { "export_all", "Export unrecognized metadata entries", OFFSET(export_all),
3671 AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, .flags = FLAGS },
3672 { "export_xmp", "Export full XMP metadata", OFFSET(export_xmp),
3673 AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, .flags = FLAGS },
3674 { "enable_drefs", "Enable external track support.", OFFSET(enable_drefs),
3675 AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, .flags = FLAGS },
3679 static const AVClass mov_class = {
3680 .class_name = "mov,mp4,m4a,3gp,3g2,mj2",
3681 .item_name = av_default_item_name,
3682 .option = mov_options,
3683 .version = LIBAVUTIL_VERSION_INT,
3686 AVInputFormat ff_mov_demuxer = {
3687 .name = "mov,mp4,m4a,3gp,3g2,mj2",
3688 .long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
3689 .priv_class = &mov_class,
3690 .priv_data_size = sizeof(MOVContext),
3691 .extensions = "mov,mp4,m4a,3gp,3g2,mj2",
3692 .read_probe = mov_probe,
3693 .read_header = mov_read_header,
3694 .read_packet = mov_read_packet,
3695 .read_close = mov_read_close,
3696 .read_seek = mov_read_seek,