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