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