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