summaryrefslogtreecommitdiff
path: root/libavformat/mov.c (plain)
blob: ff0d0be74b82aa823f724d7be24306a5530ea8d4
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 FFmpeg.
10 *
11 * FFmpeg 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 * FFmpeg 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 FFmpeg; if not, write to the Free Software
23 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
24 */
25
26#include <limits.h>
27
28//#define MOV_EXPORT_ALL_METADATA
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/avstring.h"
36#include "libavutil/dict.h"
37#include "libavutil/opt.h"
38#include "libavutil/timecode.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 "seek.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#include "id3v2.h"
61/* those functions parse an atom */
62/* links atom IDs to parse functions */
63typedef struct MOVParseTableEntry {
64 uint32_t type;
65 int (*parse)(MOVContext *ctx, AVIOContext *pb, MOVAtom atom);
66} MOVParseTableEntry;
67
68static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom);
69
70static int mov_metadata_track_or_disc_number(MOVContext *c, AVIOContext *pb,
71 unsigned len, const char *key)
72{
73 char buf[16];
74
75 short current, total = 0;
76 avio_rb16(pb); // unknown
77 current = avio_rb16(pb);
78 if (len >= 6)
79 total = avio_rb16(pb);
80 if (!total)
81 snprintf(buf, sizeof(buf), "%d", current);
82 else
83 snprintf(buf, sizeof(buf), "%d/%d", current, total);
84 av_dict_set(&c->fc->metadata, key, buf, 0);
85
86 return 0;
87}
88
89static 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 av_dict_set(&c->fc->metadata, key, buf, 0);
101
102 return 0;
103}
104
105static int mov_metadata_int8_no_padding(MOVContext *c, AVIOContext *pb,
106 unsigned len, const char *key)
107{
108 char buf[16];
109
110 snprintf(buf, sizeof(buf), "%d", avio_r8(pb));
111 av_dict_set(&c->fc->metadata, key, buf, 0);
112
113 return 0;
114}
115
116static int mov_metadata_gnre(MOVContext *c, AVIOContext *pb,
117 unsigned len, const char *key)
118{
119 short genre;
120 char buf[20];
121
122 avio_r8(pb); // unknown
123
124 genre = avio_r8(pb);
125 if (genre < 1 || genre > ID3v1_GENRE_MAX)
126 return 0;
127 snprintf(buf, sizeof(buf), "%s", ff_id3v1_genre_str[genre-1]);
128 av_dict_set(&c->fc->metadata, key, buf, 0);
129
130 return 0;
131}
132
133static int mov_read_custom_metadata(MOVContext *c, AVIOContext *pb, MOVAtom atom)
134{
135 char key[1024]={0}, data[1024]={0};
136 int i;
137 AVStream *st;
138 MOVStreamContext *sc;
139
140 if (c->fc->nb_streams < 1)
141 return 0;
142 st = c->fc->streams[c->fc->nb_streams-1];
143 sc = st->priv_data;
144
145 if (atom.size <= 8) return 0;
146
147 for (i = 0; i < 3; i++) { // Parse up to three sub-atoms looking for name and data.
148 int data_size = avio_rb32(pb);
149 int tag = avio_rl32(pb);
150 int str_size = 0, skip_size = 0;
151 char *target = NULL;
152
153 switch (tag) {
154 case MKTAG('n','a','m','e'):
155 avio_rb32(pb); // version/flags
156 str_size = skip_size = data_size - 12;
157 atom.size -= 12;
158 target = key;
159 break;
160 case MKTAG('d','a','t','a'):
161 avio_rb32(pb); // version/flags
162 avio_rb32(pb); // reserved (zero)
163 str_size = skip_size = data_size - 16;
164 atom.size -= 16;
165 target = data;
166 break;
167 default:
168 skip_size = data_size - 8;
169 str_size = 0;
170 break;
171 }
172
173 if (target) {
174 str_size = FFMIN3(sizeof(data)-1, str_size, atom.size);
175 avio_read(pb, target, str_size);
176 target[str_size] = 0;
177 }
178 atom.size -= skip_size;
179
180 // If we didn't read the full data chunk for the sub-atom, skip to the end of it.
181 if (skip_size > str_size) avio_skip(pb, skip_size - str_size);
182 }
183
184 if (*key && *data) {
185 if (strcmp(key, "iTunSMPB") == 0) {
186 int priming, remainder, samples;
187 if(sscanf(data, "%*X %X %X %X", &priming, &remainder, &samples) == 3){
188 if(priming>0 && priming<16384)
189 sc->start_pad = priming;
190 return 1;
191 }
192 }
193 if (strcmp(key, "cdec") == 0) {
194// av_dict_set(&st->metadata, key, data, 0);
195 return 1;
196 }
197 }
198 return 0;
199}
200
201static const uint32_t mac_to_unicode[128] = {
202 0x00C4,0x00C5,0x00C7,0x00C9,0x00D1,0x00D6,0x00DC,0x00E1,
203 0x00E0,0x00E2,0x00E4,0x00E3,0x00E5,0x00E7,0x00E9,0x00E8,
204 0x00EA,0x00EB,0x00ED,0x00EC,0x00EE,0x00EF,0x00F1,0x00F3,
205 0x00F2,0x00F4,0x00F6,0x00F5,0x00FA,0x00F9,0x00FB,0x00FC,
206 0x2020,0x00B0,0x00A2,0x00A3,0x00A7,0x2022,0x00B6,0x00DF,
207 0x00AE,0x00A9,0x2122,0x00B4,0x00A8,0x2260,0x00C6,0x00D8,
208 0x221E,0x00B1,0x2264,0x2265,0x00A5,0x00B5,0x2202,0x2211,
209 0x220F,0x03C0,0x222B,0x00AA,0x00BA,0x03A9,0x00E6,0x00F8,
210 0x00BF,0x00A1,0x00AC,0x221A,0x0192,0x2248,0x2206,0x00AB,
211 0x00BB,0x2026,0x00A0,0x00C0,0x00C3,0x00D5,0x0152,0x0153,
212 0x2013,0x2014,0x201C,0x201D,0x2018,0x2019,0x00F7,0x25CA,
213 0x00FF,0x0178,0x2044,0x20AC,0x2039,0x203A,0xFB01,0xFB02,
214 0x2021,0x00B7,0x201A,0x201E,0x2030,0x00C2,0x00CA,0x00C1,
215 0x00CB,0x00C8,0x00CD,0x00CE,0x00CF,0x00CC,0x00D3,0x00D4,
216 0xF8FF,0x00D2,0x00DA,0x00DB,0x00D9,0x0131,0x02C6,0x02DC,
217 0x00AF,0x02D8,0x02D9,0x02DA,0x00B8,0x02DD,0x02DB,0x02C7,
218};
219
220static int mov_read_mac_string(MOVContext *c, AVIOContext *pb, int len,
221 char *dst, int dstlen)
222{
223 char *p = dst;
224 char *end = dst+dstlen-1;
225 int i;
226
227 for (i = 0; i < len; i++) {
228 uint8_t t, c = avio_r8(pb);
229 if (c < 0x80 && p < end)
230 *p++ = c;
231 else if (p < end)
232 PUT_UTF8(mac_to_unicode[c-0x80], t, if (p < end) *p++ = t;);
233 }
234 *p = 0;
235 return p - dst;
236}
237
238static int mov_extract_cover_pic(AVFormatContext *s, AVIOContext *pb, int type, int size, char *value)
239{
240 if(s->cover_data){
241 av_log(s, AV_LOG_INFO, "Extract cover picture in other atom!\n");
242 return 0;
243 }
244
245 s->cover_data = av_malloc(size);
246 if(!s->cover_data){
247 av_log(s, AV_LOG_INFO, "no memery, av_alloc failed!\n");
248 return -1;
249 }
250 s->cover_data_len = size;
251 avio_read(pb, s->cover_data, size);
252
253 if (type == 13)
254 strcpy(value, "image/jpeg"); // jpeg
255 else if (type == 14)
256 strcpy(value, "image/png"); // png
257
258 return 0;
259}
260
261static int mov_read_covr(MOVContext *c, AVIOContext *pb, int type, int len)
262{
263 AVPacket pkt;
264 AVStream *st;
265 MOVStreamContext *sc;
266 enum AVCodecID id;
267 int ret;
268
269 switch (type) {
270 case 0xd: id = AV_CODEC_ID_MJPEG; break;
271 case 0xe: id = AV_CODEC_ID_PNG; break;
272 case 0x1b: id = AV_CODEC_ID_BMP; break;
273 default:
274 av_log(c->fc, AV_LOG_WARNING, "Unknown cover type: 0x%x.\n", type);
275 avio_skip(pb, len);
276 return 0;
277 }
278
279 st = avformat_new_stream(c->fc, NULL);
280 if (!st)
281 return AVERROR(ENOMEM);
282 sc = av_mallocz(sizeof(*sc));
283 if (!sc)
284 return AVERROR(ENOMEM);
285 st->priv_data = sc;
286
287 ret = av_get_packet(pb, &pkt, len);
288 if (ret < 0)
289 return ret;
290
291 st->disposition |= AV_DISPOSITION_ATTACHED_PIC;
292
293 st->attached_pic = pkt;
294 st->attached_pic.stream_index = st->index;
295 st->attached_pic.flags |= AV_PKT_FLAG_KEY;
296
297 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
298 st->codec->codec_id = id;
299
300 return 0;
301}
302
303static int mov_metadata_raw(MOVContext *c, AVIOContext *pb,
304 unsigned len, const char *key)
305{
306 char *value = av_malloc(len + 1);
307 if (!value)
308 return AVERROR(ENOMEM);
309 avio_read(pb, value, len);
310 value[len] = 0;
311 return av_dict_set(&c->fc->metadata, key, value, AV_DICT_DONT_STRDUP_VAL);
312}
313
314static int mov_metadata_3gpp_general(MOVContext *c, AVIOContext *pb,
315 unsigned len, const char *key)
316{
317 char key2[16];
318 uint8_t version;
319 uint32_t flags;
320 uint8_t pad;
321 uint16_t langcode;
322 uint16_t shortbytes;
323 char language[4] = {0};
324 char byte = 0;
325 char str[128] = {0};
326 int offset = 0;
327 uint16_t byteOrderMark = 0;
328
329 version = avio_r8(pb); // version
330 flags = avio_rb24(pb); //flags
331 shortbytes = avio_rb16(pb);
332 pad = (shortbytes & 0x8000) >> 15;
333 langcode = shortbytes & 0x7ffff;
334 ff_mov_lang_to_iso639(langcode, language);
335 len -= 6;
336
337 //read BYTE ORDER MARK
338 byteOrderMark = avio_rb16(pb);
339 if (byteOrderMark == 0xFEFF) {//UTF-16BE
340 len -= 2;
341 offset += 2;
342 avio_get_str16be(pb, len, str, 128);
343 av_dict_set(&c->fc->metadata, key, str, 0);
344 } else if (byteOrderMark == 0xFFFE) {//UTF-16LE
345 len -= 2;
346 offset += 2;
347 avio_get_str16le(pb, len, str, 128);
348 av_dict_set(&c->fc->metadata, key, str, 0);
349 } else { //not BYTE ORDER MARK,UTF-8 format
350 avio_seek(pb, -2, SEEK_CUR);
351 avio_read(pb, str+offset, len);
352 str[len] = 0;
353 av_dict_set(&c->fc->metadata, key, str, 0);
354 if (*language && strcmp(language, "und")) {
355 snprintf(key2, sizeof(key2), "%s-%s", key, language);
356 av_dict_set(&c->fc->metadata, key2, str, 0);
357 }
358 }
359 return 0;
360}
361
362static int mov_metadata_3gpp_yrrc(MOVContext *c, AVIOContext *pb,
363 unsigned len, const char *key)
364{
365 uint8_t version;
366 uint32_t flags;
367 char byte = 0;
368 char str[128] = {0};
369 char year[32] = {0};
370 uint16_t yearCode = 0;
371
372 version = avio_r8(pb); // version
373 flags = avio_rb24(pb); //flags
374 len -= 4;
375
376 //get the year when the media was recorded
377 yearCode = avio_rb16(pb);
378 snprintf(year, sizeof(year), "%d", yearCode);
379 av_dict_set(&c->fc->metadata, key, year, 0);
380
381 return 0;
382}
383
384static int mov_metadata_3gpp_album(MOVContext *c, AVIOContext *pb,
385 unsigned len, const char *key)
386{
387 char key2[16];
388 uint8_t version;
389 uint32_t flags;
390 uint8_t pad;
391 uint16_t langcode;
392 uint16_t shortbytes;
393 char language[4] = {0};
394 char byte = 0;
395 int read_byte = 0;
396 char str[128] = {0};
397 int offset = 0;
398 uint16_t byteOrderMark = 0;
399 uint8_t trackNum[16] ={0};
400
401 version = avio_r8(pb); // version
402 flags = avio_rb24(pb); //flags
403 shortbytes = avio_rb16(pb);
404 pad = (shortbytes & 0x8000) >> 15; //pad
405 langcode = shortbytes & 0x7ffff; //language
406 ff_mov_lang_to_iso639(langcode, language);
407 len -= 6;
408
409 //get track num
410 do {
411 byte = avio_r8(pb);
412 read_byte++;
413 } while(byte != '\0');
414 byte = avio_r8(pb);
415 read_byte++;
416 snprintf(trackNum, sizeof(trackNum), "%d", byte);
417 av_dict_set(&c->fc->metadata, "track", trackNum, 0);
418
419 //seek back to get Text of album title
420 avio_seek(pb, -read_byte, SEEK_CUR);
421
422 //read BYTE ORDER MARK
423 byteOrderMark = avio_rb16(pb);
424 if (byteOrderMark == 0xFEFF) {//UTF-16BE
425 len -= 2;
426 offset += 2;
427 avio_get_str16be(pb, len, str, 128);
428 av_dict_set(&c->fc->metadata, key, str, 0);
429 } else if (byteOrderMark == 0xFFFE) {//UTF-16LE
430 len -= 2;
431 offset += 2;
432 avio_get_str16le(pb, len, str, 128);
433 av_dict_set(&c->fc->metadata, key, str, 0);
434 } else { //not BYTE ORDER MARK,UTF-8 format
435 avio_seek(pb, -2, SEEK_CUR);
436 avio_read(pb, str+offset, len);
437 str[len] = 0;
438 av_dict_set(&c->fc->metadata, key, str, 0);
439 if (*language && strcmp(language, "und")) {
440 snprintf(key2, sizeof(key2), "%s-%s", key, language);
441 av_dict_set(&c->fc->metadata, key2, str, 0);
442 }
443 }
444
445 return 0;
446}
447
448static int mov_read_udta_string(MOVContext *c, AVIOContext *pb, MOVAtom atom)
449{
450#ifdef MOV_EXPORT_ALL_METADATA
451 char tmp_key[5];
452#endif
453 char str[1024], key2[16], language[4] = {0};
454 const char *key = NULL;
455 uint16_t langcode = 0;
456 uint32_t data_type = 0, str_size;
457 uint32_t cover_size = 0;
458 int skip_read = 0;
459 int (*parse)(MOVContext*, AVIOContext*, unsigned, const char*) = NULL;
460
461 if (c->itunes_metadata && atom.type == MKTAG('-','-','-','-'))
462 return mov_read_custom_metadata(c, pb, atom);
463
464 switch (atom.type) {
465 case MKTAG('t', 'i', 't', 'l'):
466 key = "title";
467 skip_read = 1;
468 parse = mov_metadata_3gpp_general;
469 break;
470 case MKTAG('a', 'l', 'b', 'm'):
471 key = "album";
472 skip_read = 1;
473 parse = mov_metadata_3gpp_album;
474 break;
475 case MKTAG('d', 's', 'c', 'p'):
476 key = "description";
477 skip_read = 1;
478 parse = mov_metadata_3gpp_general;
479 break;
480 case MKTAG('p', 'e', 'r', 'f'):
481 key = "artist";
482 skip_read = 1;
483 parse = mov_metadata_3gpp_general;
484 break;
485 case MKTAG('y', 'r', 'r', 'c'):
486 key = "year";
487 skip_read = 1;
488 parse = mov_metadata_3gpp_yrrc;
489 break;
490
491 case MKTAG(0xa9,'n','a','m'): key = "title"; break;
492 case MKTAG(0xa9,'a','u','t'):
493 case MKTAG(0xa9,'A','R','T'): key = "artist"; break;
494 case MKTAG( 'a','A','R','T'): key = "album_artist"; break;
495 case MKTAG(0xa9,'w','r','t'): key = "composer"; break;
496 case MKTAG( 'c','p','r','t'):
497 case MKTAG(0xa9,'c','p','y'): key = "copyright"; break;
498 case MKTAG(0xa9,'g','r','p'): key = "grouping"; break;
499 case MKTAG(0xa9,'l','y','r'): key = "lyrics"; break;
500 case MKTAG(0xa9,'c','m','t'):
501 case MKTAG(0xa9,'i','n','f'): key = "comment"; break;
502 case MKTAG(0xa9,'a','l','b'): key = "album"; break;
503 case MKTAG(0xa9,'d','a','y'): key = "date"; break;
504 case MKTAG(0xa9,'g','e','n'): key = "genre"; break;
505 case MKTAG( 'g','n','r','e'): key = "genre";
506 parse = mov_metadata_gnre; break;
507 case MKTAG(0xa9,'t','o','o'):
508 case MKTAG(0xa9,'s','w','r'): key = "encoder"; break;
509 case MKTAG(0xa9,'e','n','c'): key = "encoder"; break;
510 case MKTAG(0xa9,'m','a','k'): key = "make"; break;
511 case MKTAG(0xa9,'m','o','d'): key = "model"; break;
512 case MKTAG(0xa9,'x','y','z'): key = "location"; break;
513 case MKTAG( 'd','e','s','c'): key = "description";break;
514 case MKTAG( 'l','d','e','s'): key = "synopsis"; break;
515 case MKTAG( 't','v','s','h'): key = "show"; break;
516 case MKTAG( 't','v','e','n'): key = "episode_id";break;
517 case MKTAG( 't','v','n','n'): key = "network"; break;
518 case MKTAG( 't','r','k','n'): key = "track";
519 parse = mov_metadata_track_or_disc_number; break;
520 case MKTAG( 'd','i','s','k'): key = "disc";
521 parse = mov_metadata_track_or_disc_number; break;
522 case MKTAG( 't','v','e','s'): key = "episode_sort";
523 parse = mov_metadata_int8_bypass_padding; break;
524 case MKTAG( 't','v','s','n'): key = "season_number";
525 parse = mov_metadata_int8_bypass_padding; break;
526 case MKTAG( 's','t','i','k'): key = "media_type";
527 parse = mov_metadata_int8_no_padding; break;
528 case MKTAG( 'h','d','v','d'): key = "hd_video";
529 parse = mov_metadata_int8_no_padding; break;
530 case MKTAG( 'p','g','a','p'): key = "gapless_playback";
531 parse = mov_metadata_int8_no_padding; break;
532 case MKTAG( '@','P','R','M'):
533 return mov_metadata_raw(c, pb, atom.size, "premiere_version");
534 case MKTAG( '@','P','R','Q'):
535 return mov_metadata_raw(c, pb, atom.size, "quicktime_version");
536 }
537
538 if (c->itunes_metadata && atom.size > 8) {
539 int data_size = avio_rb32(pb);
540 int tag = avio_rl32(pb);
541 if (tag == MKTAG('d','a','t','a')) {
542 data_type = avio_rb32(pb); // type
543 avio_rb32(pb); // unknown
544 str_size = data_size - 16;
545 cover_size = data_size -16;
546 atom.size -= 16;
547
548 if (atom.type == MKTAG('c', 'o', 'v', 'r')) {
549 int ret = mov_read_covr(c, pb, data_type, str_size);
550 if (ret < 0) {
551 av_log(c->fc, AV_LOG_ERROR, "Error parsing cover art.\n");
552 return ret;
553 }
554 } else if (!key && c->found_hdlr_mdta && c->meta_keys) {
555 uint32_t index = AV_RB32(&atom.type);
556 if (index < c->meta_keys_count) {
557 key = c->meta_keys[index];
558 } else {
559 av_log(c->fc, AV_LOG_WARNING,
560 "The index of 'data' is out of range: %d >= %d.\n",
561 index, c->meta_keys_count);
562 }
563
564 }
565 } else return 0;
566 } else if (atom.size > 4 && key && !c->itunes_metadata) {
567 if (skip_read) {
568 str_size = atom.size;
569 }
570 else{
571 str_size = avio_rb16(pb); // string length
572 langcode = avio_rb16(pb);
573 ff_mov_lang_to_iso639(langcode, language);
574 atom.size -= 4;
575 }
576 } else
577 str_size = atom.size;
578
579#ifdef MOV_EXPORT_ALL_METADATA
580 if (!key) {
581 snprintf(tmp_key, 5, "%.4s", (char*)&atom.type);
582 key = tmp_key;
583 }
584#endif
585
586 if (!key)
587 return 0;
588 if (atom.size < 0)
589 return AVERROR_INVALIDDATA;
590
591 str_size = FFMIN3(sizeof(str)-1, str_size, atom.size);
592
593 if (parse)
594 parse(c, pb, str_size, key);
595 else {
596 if (data_type == 3 || (data_type == 0 && (langcode < 0x400 || langcode == 0x7fff))) { // MAC Encoded
597 mov_read_mac_string(c, pb, str_size, str, sizeof(str));
598 } else if (data_type == 13 || data_type == 14){
599 mov_extract_cover_pic(c->fc, pb, data_type, cover_size, str);
600 } else if (data_type == 23 && str_size >= 4) { // BE float32
601 // Allocates enough space if data_type is a float32 number
602 int str_size_alloc = 512 + 1;
603 float val = av_int2float(avio_rb32(pb));
604 if (snprintf(str, str_size_alloc, "%f", val) >= str_size_alloc) {
605 av_log(c->fc, AV_LOG_ERROR,
606 "Failed to store the float32 number (%f) in string.\n", val);
607 av_free(str);
608 return AVERROR_INVALIDDATA;
609 }
610
611 } else {
612 avio_read(pb, str, str_size);
613 str[str_size] = 0;
614 }
615 // Android MP4 writer put an additional '/' at the end, discard it.
616 // The CTS test seems the added '/' is not needed.
617 if ((atom.type == MKTAG(0xa9,'x','y','z')) && (str[str_size-1] == 0x2f)) {
618 str[str_size-1] = 0;
619 }
620 av_dict_set(&c->fc->metadata, key, str, 0);
621 if (*language && strcmp(language, "und")) {
622 snprintf(key2, sizeof(key2), "%s-%s", key, language);
623 av_dict_set(&c->fc->metadata, key2, str, 0);
624 }
625 }
626 av_dlog(c->fc, "lang \"%3s\" ", language);
627 av_dlog(c->fc, "tag \"%s\" value \"%s\" atom \"%.4s\" %d %"PRId64"\n",
628 key, str, (char*)&atom.type, str_size, atom.size);
629
630 return 0;
631}
632
633static int mov_read_chpl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
634{
635 int64_t start;
636 int i, nb_chapters, str_len, version;
637 char str[256+1];
638
639 if ((atom.size -= 5) < 0)
640 return 0;
641
642 version = avio_r8(pb);
643 avio_rb24(pb);
644 if (version)
645 avio_rb32(pb); // ???
646 nb_chapters = avio_r8(pb);
647
648 for (i = 0; i < nb_chapters; i++) {
649 if (atom.size < 9)
650 return 0;
651
652 start = avio_rb64(pb);
653 str_len = avio_r8(pb);
654
655 if ((atom.size -= 9+str_len) < 0)
656 return 0;
657
658 avio_read(pb, str, str_len);
659 str[str_len] = 0;
660 avpriv_new_chapter(c->fc, i, (AVRational){1,10000000}, start, AV_NOPTS_VALUE, str);
661 }
662 return 0;
663}
664
665#define MIN_DATA_ENTRY_BOX_SIZE 12
666static int mov_read_dref(MOVContext *c, AVIOContext *pb, MOVAtom atom)
667{
668 AVStream *st;
669 MOVStreamContext *sc;
670 int entries, i, j;
671
672 if (c->fc->nb_streams < 1)
673 return 0;
674 st = c->fc->streams[c->fc->nb_streams-1];
675 sc = st->priv_data;
676
677 avio_rb32(pb); // version + flags
678 entries = avio_rb32(pb);
679 if (entries > (atom.size - 1) / MIN_DATA_ENTRY_BOX_SIZE + 1 ||
680 entries >= UINT_MAX / sizeof(*sc->drefs))
681 return AVERROR_INVALIDDATA;
682 av_free(sc->drefs);
683 sc->drefs_count = 0;
684 sc->drefs = av_mallocz(entries * sizeof(*sc->drefs));
685 if (!sc->drefs)
686 return AVERROR(ENOMEM);
687 sc->drefs_count = entries;
688
689 for (i = 0; i < sc->drefs_count; i++) {
690 MOVDref *dref = &sc->drefs[i];
691 uint32_t size = avio_rb32(pb);
692 int64_t next = avio_tell(pb) + size - 4;
693
694 if (size < 12)
695 return AVERROR_INVALIDDATA;
696
697 dref->type = avio_rl32(pb);
698 avio_rb32(pb); // version + flags
699 av_dlog(c->fc, "type %.4s size %d\n", (char*)&dref->type, size);
700
701 if (dref->type == MKTAG('a','l','i','s') && size > 150) {
702 /* macintosh alias record */
703 uint16_t volume_len, len;
704 int16_t type;
705
706 avio_skip(pb, 10);
707
708 volume_len = avio_r8(pb);
709 volume_len = FFMIN(volume_len, 27);
710 avio_read(pb, dref->volume, 27);
711 dref->volume[volume_len] = 0;
712 av_log(c->fc, AV_LOG_DEBUG, "volume %s, len %d\n", dref->volume, volume_len);
713
714 avio_skip(pb, 12);
715
716 len = avio_r8(pb);
717 len = FFMIN(len, 63);
718 avio_read(pb, dref->filename, 63);
719 dref->filename[len] = 0;
720 av_log(c->fc, AV_LOG_DEBUG, "filename %s, len %d\n", dref->filename, len);
721
722 avio_skip(pb, 16);
723
724 /* read next level up_from_alias/down_to_target */
725 dref->nlvl_from = avio_rb16(pb);
726 dref->nlvl_to = avio_rb16(pb);
727 av_log(c->fc, AV_LOG_DEBUG, "nlvl from %d, nlvl to %d\n",
728 dref->nlvl_from, dref->nlvl_to);
729
730 avio_skip(pb, 16);
731
732 for (type = 0; type != -1 && avio_tell(pb) < next; ) {
733 if(url_feof(pb))
734 return AVERROR_EOF;
735 type = avio_rb16(pb);
736 len = avio_rb16(pb);
737 av_log(c->fc, AV_LOG_DEBUG, "type %d, len %d\n", type, len);
738 if (len&1)
739 len += 1;
740 if (type == 2) { // absolute path
741 av_free(dref->path);
742 dref->path = av_mallocz(len+1);
743 if (!dref->path)
744 return AVERROR(ENOMEM);
745 avio_read(pb, dref->path, len);
746 if (len > volume_len && !strncmp(dref->path, dref->volume, volume_len)) {
747 len -= volume_len;
748 memmove(dref->path, dref->path+volume_len, len);
749 dref->path[len] = 0;
750 }
751 for (j = 0; j < len; j++)
752 if (dref->path[j] == ':')
753 dref->path[j] = '/';
754 av_log(c->fc, AV_LOG_DEBUG, "path %s\n", dref->path);
755 } else if (type == 0) { // directory name
756 av_free(dref->dir);
757 dref->dir = av_malloc(len+1);
758 if (!dref->dir)
759 return AVERROR(ENOMEM);
760 avio_read(pb, dref->dir, len);
761 dref->dir[len] = 0;
762 for (j = 0; j < len; j++)
763 if (dref->dir[j] == ':')
764 dref->dir[j] = '/';
765 av_log(c->fc, AV_LOG_DEBUG, "dir %s\n", dref->dir);
766 } else
767 avio_skip(pb, len);
768 }
769 }
770 avio_seek(pb, next, SEEK_SET);
771 }
772 return 0;
773}
774
775static int mov_read_hdlr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
776{
777 AVStream *st;
778 uint32_t type;
779 uint32_t av_unused ctype;
780 int title_size;
781 char *title_str;
782
783 avio_r8(pb); /* version */
784 avio_rb24(pb); /* flags */
785
786 /* component type */
787 ctype = avio_rl32(pb);
788 type = avio_rl32(pb); /* component subtype */
789
790 av_dlog(c->fc, "ctype= %.4s (0x%08x)\n", (char*)&ctype, ctype);
791 av_dlog(c->fc, "stype= %.4s\n", (char*)&type);
792
793 if (c->trak_index < 0) { // meta not inside a trak
794 if (type == MKTAG('m','d','t','a')) {
795 c->found_hdlr_mdta = 1;
796 }
797 return 0;
798 }
799
800 st = c->fc->streams[c->fc->nb_streams-1];
801
802 if (type == MKTAG('v','i','d','e'))
803 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
804 else if (type == MKTAG('s','o','u','n'))
805 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
806 else if (type == MKTAG('m','1','a',' '))
807 st->codec->codec_id = AV_CODEC_ID_MP2;
808 else if ((type == MKTAG('s','u','b','p')) || (type == MKTAG('c','l','c','p')))
809 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
810
811 avio_rb32(pb); /* component manufacture */
812 avio_rb32(pb); /* component flags */
813 avio_rb32(pb); /* component flags mask */
814
815 title_size = atom.size - 24;
816 if (title_size > 0) {
817 title_str = av_malloc(title_size + 1); /* Add null terminator */
818 if (!title_str)
819 return AVERROR(ENOMEM);
820 avio_read(pb, title_str, title_size);
821 title_str[title_size] = 0;
822 if (title_str[0])
823 av_dict_set(&st->metadata, "handler_name", title_str +
824 (!c->isom && title_str[0] == title_size - 1), 0);
825 av_freep(&title_str);
826 }
827
828 return 0;
829}
830
831int ff_mov_read_esds(AVFormatContext *fc, AVIOContext *pb, MOVAtom atom)
832{
833 AVStream *st;
834 int tag;
835
836 if (fc->nb_streams < 1)
837 return 0;
838 st = fc->streams[fc->nb_streams-1];
839
840 avio_rb32(pb); /* version + flags */
841 ff_mp4_read_descr(fc, pb, &tag);
842 if (tag == MP4ESDescrTag) {
843 ff_mp4_parse_es_descr(pb, NULL);
844 } else
845 avio_rb16(pb); /* ID */
846
847 ff_mp4_read_descr(fc, pb, &tag);
848 if (tag == MP4DecConfigDescrTag)
849 ff_mp4_read_dec_config_descr(fc, st, pb);
850 return 0;
851}
852
853static int mov_read_esds(MOVContext *c, AVIOContext *pb, MOVAtom atom)
854{
855 return ff_mov_read_esds(c->fc, pb, atom);
856}
857
858static int mov_read_dac3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
859{
860 AVStream *st;
861 int ac3info, acmod, lfeon, bsmod;
862
863 if (c->fc->nb_streams < 1)
864 return 0;
865 st = c->fc->streams[c->fc->nb_streams-1];
866
867 ac3info = avio_rb24(pb);
868 bsmod = (ac3info >> 14) & 0x7;
869 acmod = (ac3info >> 11) & 0x7;
870 lfeon = (ac3info >> 10) & 0x1;
871 st->codec->channels = ((int[]){2,1,2,3,3,4,4,5})[acmod] + lfeon;
872 st->codec->channel_layout = avpriv_ac3_channel_layout_tab[acmod];
873 if (lfeon)
874 st->codec->channel_layout |= AV_CH_LOW_FREQUENCY;
875 st->codec->audio_service_type = bsmod;
876 if (st->codec->channels > 1 && bsmod == 0x7)
877 st->codec->audio_service_type = AV_AUDIO_SERVICE_TYPE_KARAOKE;
878
879 return 0;
880}
881
882static int mov_read_dec3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
883{
884 AVStream *st;
885 int eac3info, acmod, lfeon, bsmod;
886
887 if (c->fc->nb_streams < 1)
888 return 0;
889 st = c->fc->streams[c->fc->nb_streams-1];
890
891 /* No need to parse fields for additional independent substreams and its
892 * associated dependent substreams since libavcodec's E-AC-3 decoder
893 * does not support them yet. */
894 avio_rb16(pb); /* data_rate and num_ind_sub */
895 eac3info = avio_rb24(pb);
896 bsmod = (eac3info >> 12) & 0x1f;
897 acmod = (eac3info >> 9) & 0x7;
898 lfeon = (eac3info >> 8) & 0x1;
899 st->codec->channel_layout = avpriv_ac3_channel_layout_tab[acmod];
900 if (lfeon)
901 st->codec->channel_layout |= AV_CH_LOW_FREQUENCY;
902 st->codec->channels = av_get_channel_layout_nb_channels(st->codec->channel_layout);
903 st->codec->audio_service_type = bsmod;
904 if (st->codec->channels > 1 && bsmod == 0x7)
905 st->codec->audio_service_type = AV_AUDIO_SERVICE_TYPE_KARAOKE;
906
907 return 0;
908}
909
910static int mov_read_chan(MOVContext *c, AVIOContext *pb, MOVAtom atom)
911{
912 AVStream *st;
913
914 if (c->fc->nb_streams < 1)
915 return 0;
916 st = c->fc->streams[c->fc->nb_streams-1];
917
918 if (atom.size < 16)
919 return 0;
920
921 /* skip version and flags */
922 avio_skip(pb, 4);
923
924 ff_mov_read_chan(c->fc, pb, st, atom.size - 4);
925
926 return 0;
927}
928
929static int mov_read_wfex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
930{
931 AVStream *st;
932
933 if (c->fc->nb_streams < 1)
934 return 0;
935 st = c->fc->streams[c->fc->nb_streams-1];
936
937 if (ff_get_wav_header(pb, st->codec, atom.size) < 0) {
938 av_log(c->fc, AV_LOG_WARNING, "get_wav_header failed\n");
939 }
940
941 return 0;
942}
943
944static int mov_read_pasp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
945{
946 const int num = avio_rb32(pb);
947 const int den = avio_rb32(pb);
948 AVStream *st;
949
950 if (c->fc->nb_streams < 1)
951 return 0;
952 st = c->fc->streams[c->fc->nb_streams-1];
953
954 if ((st->sample_aspect_ratio.den != 1 || st->sample_aspect_ratio.num) && // default
955 (den != st->sample_aspect_ratio.den || num != st->sample_aspect_ratio.num)) {
956 av_log(c->fc, AV_LOG_WARNING,
957 "sample aspect ratio already set to %d:%d, ignoring 'pasp' atom (%d:%d)\n",
958 st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
959 num, den);
960 } else if (den != 0) {
961 st->sample_aspect_ratio.num = num;
962 st->sample_aspect_ratio.den = den;
963 }
964 return 0;
965}
966
967/* this atom contains actual media data */
968static int mov_read_mdat(MOVContext *c, AVIOContext *pb, MOVAtom atom)
969{
970 if (atom.size == 0) /* wrong one (MP4) */
971 return 0;
972 c->found_mdat=1;
973 return 0; /* now go for moov */
974}
975
976/* read major brand, minor version and compatible brands and store them as metadata */
977static int mov_read_ftyp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
978{
979 uint32_t minor_ver;
980 int comp_brand_size;
981 char minor_ver_str[11]; /* 32 bit integer -> 10 digits + null */
982 char* comp_brands_str;
983 uint8_t type[5] = {0};
984
985 avio_read(pb, type, 4);
986 if (strcmp(type, "qt "))
987 c->isom = 1;
988 av_log(c->fc, AV_LOG_DEBUG, "ISO: File Type Major Brand: %.4s\n",(char *)&type);
989 av_dict_set(&c->fc->metadata, "major_brand", type, 0);
990 minor_ver = avio_rb32(pb); /* minor version */
991 snprintf(minor_ver_str, sizeof(minor_ver_str), "%d", minor_ver);
992 av_dict_set(&c->fc->metadata, "minor_version", minor_ver_str, 0);
993
994 comp_brand_size = atom.size - 8;
995 if (comp_brand_size < 0)
996 return AVERROR_INVALIDDATA;
997 comp_brands_str = av_malloc(comp_brand_size + 1); /* Add null terminator */
998 if (!comp_brands_str)
999 return AVERROR(ENOMEM);
1000 avio_read(pb, comp_brands_str, comp_brand_size);
1001 comp_brands_str[comp_brand_size] = 0;
1002 av_dict_set(&c->fc->metadata, "compatible_brands", comp_brands_str, 0);
1003 av_freep(&comp_brands_str);
1004
1005 return 0;
1006}
1007
1008/* this atom should contain all header atoms */
1009static int mov_read_moov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1010{
1011 int ret;
1012
1013 if (c->found_moov) {
1014 av_log(c->fc, AV_LOG_WARNING, "Found duplicated MOOV Atom. Skipped it\n");
1015 avio_skip(pb, atom.size);
1016 return 0;
1017 }
1018
1019 if ((ret = mov_read_default(c, pb, atom)) < 0)
1020 return ret;
1021 /* we parsed the 'moov' atom, we can terminate the parsing as soon as we find the 'mdat' */
1022 /* so we don't parse the whole file if over a network */
1023 c->found_moov=1;
1024 return 0; /* now go for mdat */
1025}
1026
1027static int mov_read_moof(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1028{
1029 c->fragment.moof_offset = avio_tell(pb) - 8;
1030 av_dlog(c->fc, "moof offset %"PRIx64"\n", c->fragment.moof_offset);
1031 return mov_read_default(c, pb, atom);
1032}
1033
1034static void mov_metadata_creation_time(AVDictionary **metadata, int64_t time)
1035{
1036 char buffer[32];
1037 if (time) {
1038 struct tm *ptm;
1039 time_t timet;
1040 if(time >= 2082844800)
1041 time -= 2082844800; /* seconds between 1904-01-01 and Epoch */
1042 timet = time;
1043 ptm = gmtime(&timet);
1044 if (!ptm) return;
1045 strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", ptm);
1046 av_dict_set(metadata, "creation_time", buffer, 0);
1047 }
1048}
1049
1050static int mov_read_mdhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1051{
1052 AVStream *st;
1053 MOVStreamContext *sc;
1054 int version;
1055 char language[4] = {0};
1056 unsigned lang;
1057 int64_t creation_time;
1058
1059 if (c->fc->nb_streams < 1)
1060 return 0;
1061 st = c->fc->streams[c->fc->nb_streams-1];
1062 sc = st->priv_data;
1063
1064 if (sc->time_scale) {
1065 av_log(c->fc, AV_LOG_ERROR, "Multiple mdhd?\n");
1066 return AVERROR_INVALIDDATA;
1067 }
1068
1069 version = avio_r8(pb);
1070 if (version > 1) {
1071 avpriv_request_sample(c->fc, "Version %d", version);
1072 return AVERROR_PATCHWELCOME;
1073 }
1074 avio_rb24(pb); /* flags */
1075 if (version == 1) {
1076 creation_time = avio_rb64(pb);
1077 avio_rb64(pb);
1078 } else {
1079 creation_time = avio_rb32(pb);
1080 avio_rb32(pb); /* modification time */
1081 }
1082 mov_metadata_creation_time(&st->metadata, creation_time);
1083
1084 sc->time_scale = avio_rb32(pb);
1085 st->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
1086
1087 lang = avio_rb16(pb); /* language */
1088 if (ff_mov_lang_to_iso639(lang, language))
1089 av_dict_set(&st->metadata, "language", language, 0);
1090 avio_rb16(pb); /* quality */
1091
1092 return 0;
1093}
1094
1095static int mov_read_mvhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1096{
1097 int64_t creation_time;
1098 int version = avio_r8(pb); /* version */
1099 avio_rb24(pb); /* flags */
1100
1101 if (version == 1) {
1102 creation_time = avio_rb64(pb);
1103 avio_rb64(pb);
1104 } else {
1105 creation_time = avio_rb32(pb);
1106 avio_rb32(pb); /* modification time */
1107 }
1108 mov_metadata_creation_time(&c->fc->metadata, creation_time);
1109 c->time_scale = avio_rb32(pb); /* time scale */
1110
1111 av_dlog(c->fc, "time scale = %i\n", c->time_scale);
1112
1113 c->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
1114 // set the AVCodecContext duration because the duration of individual tracks
1115 // may be inaccurate
1116 if (c->time_scale > 0 && !c->trex_data)
1117 c->fc->duration = av_rescale(c->duration, AV_TIME_BASE, c->time_scale);
1118 avio_rb32(pb); /* preferred scale */
1119
1120 avio_rb16(pb); /* preferred volume */
1121
1122 avio_skip(pb, 10); /* reserved */
1123
1124 avio_skip(pb, 36); /* display matrix */
1125
1126 avio_rb32(pb); /* preview time */
1127 avio_rb32(pb); /* preview duration */
1128 avio_rb32(pb); /* poster time */
1129 avio_rb32(pb); /* selection time */
1130 avio_rb32(pb); /* selection duration */
1131 avio_rb32(pb); /* current time */
1132 avio_rb32(pb); /* next track ID */
1133 return 0;
1134}
1135
1136static int mov_read_enda(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1137{
1138 AVStream *st;
1139 int little_endian;
1140
1141 if (c->fc->nb_streams < 1)
1142 return 0;
1143 st = c->fc->streams[c->fc->nb_streams-1];
1144
1145 little_endian = avio_rb16(pb) & 0xFF;
1146 av_dlog(c->fc, "enda %d\n", little_endian);
1147 if (little_endian == 1) {
1148 switch (st->codec->codec_id) {
1149 case AV_CODEC_ID_PCM_S24BE:
1150 st->codec->codec_id = AV_CODEC_ID_PCM_S24LE;
1151 break;
1152 case AV_CODEC_ID_PCM_S32BE:
1153 st->codec->codec_id = AV_CODEC_ID_PCM_S32LE;
1154 break;
1155 case AV_CODEC_ID_PCM_F32BE:
1156 st->codec->codec_id = AV_CODEC_ID_PCM_F32LE;
1157 break;
1158 case AV_CODEC_ID_PCM_F64BE:
1159 st->codec->codec_id = AV_CODEC_ID_PCM_F64LE;
1160 break;
1161 default:
1162 break;
1163 }
1164 }
1165 return 0;
1166}
1167
1168static int mov_read_fiel(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1169{
1170 AVStream *st;
1171 unsigned mov_field_order;
1172 enum AVFieldOrder decoded_field_order = AV_FIELD_UNKNOWN;
1173
1174 if (c->fc->nb_streams < 1) // will happen with jp2 files
1175 return 0;
1176 st = c->fc->streams[c->fc->nb_streams-1];
1177 if (atom.size < 2)
1178 return AVERROR_INVALIDDATA;
1179 mov_field_order = avio_rb16(pb);
1180 if ((mov_field_order & 0xFF00) == 0x0100)
1181 decoded_field_order = AV_FIELD_PROGRESSIVE;
1182 else if ((mov_field_order & 0xFF00) == 0x0200) {
1183 switch (mov_field_order & 0xFF) {
1184 case 0x01: decoded_field_order = AV_FIELD_TT;
1185 break;
1186 case 0x06: decoded_field_order = AV_FIELD_BB;
1187 break;
1188 case 0x09: decoded_field_order = AV_FIELD_TB;
1189 break;
1190 case 0x0E: decoded_field_order = AV_FIELD_BT;
1191 break;
1192 }
1193 }
1194 if (decoded_field_order == AV_FIELD_UNKNOWN && mov_field_order) {
1195 av_log(NULL, AV_LOG_ERROR, "Unknown MOV field order 0x%04x\n", mov_field_order);
1196 }
1197 st->codec->field_order = decoded_field_order;
1198
1199 return 0;
1200}
1201
1202/* FIXME modify qdm2/svq3/h264 decoders to take full atom as extradata */
1203static int mov_read_extradata(MOVContext *c, AVIOContext *pb, MOVAtom atom,
1204 enum AVCodecID codec_id)
1205{
1206 AVStream *st;
1207 uint64_t size;
1208 uint8_t *buf;
1209 int err;
1210
1211 if (c->fc->nb_streams < 1) // will happen with jp2 files
1212 return 0;
1213 st= c->fc->streams[c->fc->nb_streams-1];
1214
1215 if (st->codec->codec_id != codec_id)
1216 return 0; /* unexpected codec_id - don't mess with extradata */
1217
1218 size= (uint64_t)st->codec->extradata_size + atom.size + 8 + FF_INPUT_BUFFER_PADDING_SIZE;
1219 if (size > INT_MAX || (uint64_t)atom.size > INT_MAX)
1220 return AVERROR_INVALIDDATA;
1221 if ((err = av_reallocp(&st->codec->extradata, size)) < 0) {
1222 st->codec->extradata_size = 0;
1223 return err;
1224 }
1225 buf = st->codec->extradata + st->codec->extradata_size;
1226 st->codec->extradata_size= size - FF_INPUT_BUFFER_PADDING_SIZE;
1227 AV_WB32( buf , atom.size + 8);
1228 AV_WL32( buf + 4, atom.type);
1229 avio_read(pb, buf + 8, atom.size);
1230 return 0;
1231}
1232
1233/* wrapper functions for reading ALAC/AVS/MJPEG/MJPEG2000 extradata atoms only for those codecs */
1234static int mov_read_alac(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1235{
1236 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_ALAC);
1237}
1238
1239static int mov_read_avss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1240{
1241 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_AVS);
1242}
1243
1244static int mov_read_jp2h(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1245{
1246 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_JPEG2000);
1247}
1248
1249static int mov_read_avid(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1250{
1251 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_AVUI);
1252}
1253
1254static int mov_read_targa_y216(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1255{
1256 int ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_TARGA_Y216);
1257
1258 if (!ret && c->fc->nb_streams >= 1) {
1259 AVCodecContext *avctx = c->fc->streams[c->fc->nb_streams-1]->codec;
1260 if (avctx->extradata_size >= 40) {
1261 avctx->height = AV_RB16(&avctx->extradata[36]);
1262 avctx->width = AV_RB16(&avctx->extradata[38]);
1263 }
1264 }
1265 return ret;
1266}
1267
1268static int mov_read_ares(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1269{
1270 AVCodecContext *codec = c->fc->streams[c->fc->nb_streams-1]->codec;
1271 if (codec->codec_tag == MKTAG('A', 'V', 'i', 'n') &&
1272 codec->codec_id == AV_CODEC_ID_H264 &&
1273 atom.size > 11) {
1274 avio_skip(pb, 10);
1275 /* For AVID AVCI50, force width of 1440 to be able to select the correct SPS and PPS */
1276 if (avio_rb16(pb) == 0xd4d)
1277 codec->width = 1440;
1278 return 0;
1279 }
1280
1281 return mov_read_avid(c, pb, atom);
1282}
1283
1284static int mov_read_svq3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1285{
1286 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_SVQ3);
1287}
1288
1289static int mov_read_wave(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1290{
1291 AVStream *st;
1292
1293 if (c->fc->nb_streams < 1)
1294 return 0;
1295 st = c->fc->streams[c->fc->nb_streams-1];
1296
1297 if ((uint64_t)atom.size > (1<<30))
1298 return AVERROR_INVALIDDATA;
1299
1300 if (st->codec->codec_id == AV_CODEC_ID_QDM2 ||
1301 st->codec->codec_id == AV_CODEC_ID_QDMC ||
1302 st->codec->codec_id == AV_CODEC_ID_SPEEX) {
1303 // pass all frma atom to codec, needed at least for QDMC and QDM2
1304 av_free(st->codec->extradata);
1305 if (ff_alloc_extradata(st->codec, atom.size))
1306 return AVERROR(ENOMEM);
1307 avio_read(pb, st->codec->extradata, atom.size);
1308 } else if (atom.size > 8) { /* to read frma, esds atoms */
1309 int ret;
1310 if ((ret = mov_read_default(c, pb, atom)) < 0)
1311 return ret;
1312 } else
1313 avio_skip(pb, atom.size);
1314 return 0;
1315}
1316
1317/**
1318 * This function reads atom content and puts data in extradata without tag
1319 * nor size unlike mov_read_extradata.
1320 */
1321static int mov_read_glbl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1322{
1323 AVStream *st;
1324
1325 if (c->fc->nb_streams < 1)
1326 return 0;
1327 st = c->fc->streams[c->fc->nb_streams-1];
1328
1329 if ((uint64_t)atom.size > (1<<30))
1330 return AVERROR_INVALIDDATA;
1331
1332 if (atom.size >= 10) {
1333 // Broken files created by legacy versions of libavformat will
1334 // wrap a whole fiel atom inside of a glbl atom.
1335 unsigned size = avio_rb32(pb);
1336 unsigned type = avio_rl32(pb);
1337 avio_seek(pb, -8, SEEK_CUR);
1338 if (type == MKTAG('f','i','e','l') && size == atom.size)
1339 return mov_read_default(c, pb, atom);
1340 }
1341 av_free(st->codec->extradata);
1342 if (ff_alloc_extradata(st->codec, atom.size))
1343 return AVERROR(ENOMEM);
1344 avio_read(pb, st->codec->extradata, atom.size);
1345 return 0;
1346}
1347
1348static int mov_read_dvc1(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1349{
1350 AVStream *st;
1351 uint8_t profile_level;
1352
1353 if (c->fc->nb_streams < 1)
1354 return 0;
1355 st = c->fc->streams[c->fc->nb_streams-1];
1356
1357 if (atom.size >= (1<<28) || atom.size < 7)
1358 return AVERROR_INVALIDDATA;
1359
1360 profile_level = avio_r8(pb);
1361 if ((profile_level & 0xf0) != 0xc0)
1362 return 0;
1363
1364 av_free(st->codec->extradata);
1365 if (ff_alloc_extradata(st->codec, atom.size - 7))
1366 return AVERROR(ENOMEM);
1367 avio_seek(pb, 6, SEEK_CUR);
1368 avio_read(pb, st->codec->extradata, st->codec->extradata_size);
1369 return 0;
1370}
1371
1372/**
1373 * An strf atom is a BITMAPINFOHEADER struct. This struct is 40 bytes itself,
1374 * but can have extradata appended at the end after the 40 bytes belonging
1375 * to the struct.
1376 */
1377static int mov_read_strf(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1378{
1379 AVStream *st;
1380
1381 if (c->fc->nb_streams < 1)
1382 return 0;
1383 if (atom.size <= 40)
1384 return 0;
1385 st = c->fc->streams[c->fc->nb_streams-1];
1386
1387 if ((uint64_t)atom.size > (1<<30))
1388 return AVERROR_INVALIDDATA;
1389
1390 av_free(st->codec->extradata);
1391 if (ff_alloc_extradata(st->codec, atom.size - 40))
1392 return AVERROR(ENOMEM);
1393 avio_skip(pb, 40);
1394 avio_read(pb, st->codec->extradata, atom.size - 40);
1395 return 0;
1396}
1397
1398static int mov_read_stco(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1399{
1400 AVStream *st;
1401 MOVStreamContext *sc;
1402 unsigned int i, entries;
1403
1404 if (c->fc->nb_streams < 1)
1405 return 0;
1406 st = c->fc->streams[c->fc->nb_streams-1];
1407 sc = st->priv_data;
1408
1409 avio_r8(pb); /* version */
1410 avio_rb24(pb); /* flags */
1411
1412 entries = avio_rb32(pb);
1413
1414 if (!entries)
1415 return 0;
1416 if (entries >= UINT_MAX/sizeof(int64_t))
1417 return AVERROR_INVALIDDATA;
1418
1419 sc->chunk_offsets = av_malloc(entries * sizeof(int64_t));
1420 if (!sc->chunk_offsets)
1421 return AVERROR(ENOMEM);
1422 sc->chunk_count = entries;
1423
1424 if (atom.type == MKTAG('s','t','c','o'))
1425 for (i = 0; i < entries && !pb->eof_reached; i++)
1426 sc->chunk_offsets[i] = avio_rb32(pb);
1427 else if (atom.type == MKTAG('c','o','6','4'))
1428 for (i = 0; i < entries && !pb->eof_reached; i++)
1429 sc->chunk_offsets[i] = avio_rb64(pb);
1430 else
1431 return AVERROR_INVALIDDATA;
1432
1433 sc->chunk_count = i;
1434
1435 if (pb->eof_reached)
1436 return AVERROR_EOF;
1437
1438 return 0;
1439}
1440
1441/**
1442 * Compute codec id for 'lpcm' tag.
1443 * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
1444 */
1445enum AVCodecID ff_mov_get_lpcm_codec_id(int bps, int flags)
1446{
1447 /* lpcm flags:
1448 * 0x1 = float
1449 * 0x2 = big-endian
1450 * 0x4 = signed
1451 */
1452 return ff_get_pcm_codec_id(bps, flags & 1, flags & 2, flags & 4 ? -1 : 0);
1453}
1454
1455static int mov_codec_id(AVStream *st, uint32_t format)
1456{
1457 int id = ff_codec_get_id(ff_codec_movaudio_tags, format);
1458
1459 if (id <= 0 &&
1460 ((format & 0xFFFF) == 'm' + ('s' << 8) ||
1461 (format & 0xFFFF) == 'T' + ('S' << 8)))
1462 id = ff_codec_get_id(ff_codec_wav_tags, av_bswap32(format) & 0xFFFF);
1463
1464 if (st->codec->codec_type != AVMEDIA_TYPE_VIDEO && id > 0) {
1465 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
1466 } else if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO &&
1467 /* skip old asf mpeg4 tag */
1468 format && format != MKTAG('m','p','4','s')) {
1469 id = ff_codec_get_id(ff_codec_movvideo_tags, format);
1470 if (id <= 0)
1471 id = ff_codec_get_id(ff_codec_bmp_tags, format);
1472 if (id > 0)
1473 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
1474 else if (st->codec->codec_type == AVMEDIA_TYPE_DATA ||
1475 (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE &&
1476 st->codec->codec_id == AV_CODEC_ID_NONE)) {
1477 id = ff_codec_get_id(ff_codec_movsubtitle_tags, format);
1478 if (id > 0)
1479 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
1480 }
1481 }
1482
1483 st->codec->codec_tag = format;
1484
1485 return id;
1486}
1487
1488static void mov_parse_stsd_video(MOVContext *c, AVIOContext *pb,
1489 AVStream *st, MOVStreamContext *sc)
1490{
1491 unsigned int color_depth, len, j;
1492 int color_greyscale;
1493 int color_table_id;
1494
1495 avio_rb16(pb); /* version */
1496 avio_rb16(pb); /* revision level */
1497 avio_rb32(pb); /* vendor */
1498 avio_rb32(pb); /* temporal quality */
1499 avio_rb32(pb); /* spatial quality */
1500
1501 st->codec->width = avio_rb16(pb); /* width */
1502 st->codec->height = avio_rb16(pb); /* height */
1503
1504 avio_rb32(pb); /* horiz resolution */
1505 avio_rb32(pb); /* vert resolution */
1506 avio_rb32(pb); /* data size, always 0 */
1507 avio_rb16(pb); /* frames per samples */
1508
1509 len = avio_r8(pb); /* codec name, pascal string */
1510 if (len > 31)
1511 len = 31;
1512 mov_read_mac_string(c, pb, len, st->codec->codec_name, 32);
1513 if (len < 31)
1514 avio_skip(pb, 31 - len);
1515 /* codec_tag YV12 triggers an UV swap in rawdec.c */
1516 if (!memcmp(st->codec->codec_name, "Planar Y'CbCr 8-bit 4:2:0", 25)) {
1517 st->codec->codec_tag = MKTAG('I', '4', '2', '0');
1518 st->codec->width &= ~1;
1519 st->codec->height &= ~1;
1520 }
1521 /* Flash Media Server uses tag H263 with Sorenson Spark */
1522 if (st->codec->codec_tag == MKTAG('H','2','6','3') &&
1523 !memcmp(st->codec->codec_name, "Sorenson H263", 13))
1524 st->codec->codec_id = AV_CODEC_ID_FLV1;
1525
1526 st->codec->bits_per_coded_sample = avio_rb16(pb); /* depth */
1527 color_table_id = avio_rb16(pb); /* colortable id */
1528 av_dlog(c->fc, "depth %d, ctab id %d\n",
1529 st->codec->bits_per_coded_sample, color_table_id);
1530 /* figure out the palette situation */
1531 color_depth = st->codec->bits_per_coded_sample & 0x1F;
1532 color_greyscale = st->codec->bits_per_coded_sample & 0x20;
1533
1534 /* if the depth is 2, 4, or 8 bpp, file is palettized */
1535 if ((color_depth == 2) || (color_depth == 4) || (color_depth == 8)) {
1536 /* for palette traversal */
1537 unsigned int color_start, color_count, color_end;
1538 unsigned char a, r, g, b;
1539
1540 if (color_greyscale) {
1541 int color_index, color_dec;
1542 /* compute the greyscale palette */
1543 st->codec->bits_per_coded_sample = color_depth;
1544 color_count = 1 << color_depth;
1545 color_index = 255;
1546 color_dec = 256 / (color_count - 1);
1547 for (j = 0; j < color_count; j++) {
1548 if (st->codec->codec_id == AV_CODEC_ID_CINEPAK){
1549 r = g = b = color_count - 1 - color_index;
1550 } else
1551 r = g = b = color_index;
1552 sc->palette[j] = (0xFFU << 24) | (r << 16) | (g << 8) | (b);
1553 color_index -= color_dec;
1554 if (color_index < 0)
1555 color_index = 0;
1556 }
1557 } else if (color_table_id) {
1558 const uint8_t *color_table;
1559 /* if flag bit 3 is set, use the default palette */
1560 color_count = 1 << color_depth;
1561 if (color_depth == 2)
1562 color_table = ff_qt_default_palette_4;
1563 else if (color_depth == 4)
1564 color_table = ff_qt_default_palette_16;
1565 else
1566 color_table = ff_qt_default_palette_256;
1567
1568 for (j = 0; j < color_count; j++) {
1569 r = color_table[j * 3 + 0];
1570 g = color_table[j * 3 + 1];
1571 b = color_table[j * 3 + 2];
1572 sc->palette[j] = (0xFFU << 24) | (r << 16) | (g << 8) | (b);
1573 }
1574 } else {
1575 /* load the palette from the file */
1576 color_start = avio_rb32(pb);
1577 color_count = avio_rb16(pb);
1578 color_end = avio_rb16(pb);
1579 if ((color_start <= 255) && (color_end <= 255)) {
1580 for (j = color_start; j <= color_end; j++) {
1581 /* each A, R, G, or B component is 16 bits;
1582 * only use the top 8 bits */
1583 a = avio_r8(pb);
1584 avio_r8(pb);
1585 r = avio_r8(pb);
1586 avio_r8(pb);
1587 g = avio_r8(pb);
1588 avio_r8(pb);
1589 b = avio_r8(pb);
1590 avio_r8(pb);
1591 sc->palette[j] = (a << 24 ) | (r << 16) | (g << 8) | (b);
1592 }
1593 }
1594 }
1595 sc->has_palette = 1;
1596 }
1597}
1598
1599static void mov_parse_stsd_audio(MOVContext *c, AVIOContext *pb,
1600 AVStream *st, MOVStreamContext *sc)
1601{
1602 int bits_per_sample, flags;
1603 uint16_t version = avio_rb16(pb);
1604 AVDictionaryEntry *compatible_brands = av_dict_get(c->fc->metadata, "compatible_brands", NULL, AV_DICT_MATCH_CASE);
1605
1606 avio_rb16(pb); /* revision level */
1607 avio_rb32(pb); /* vendor */
1608
1609 st->codec->channels = avio_rb16(pb); /* channel count */
1610 st->codec->bits_per_coded_sample = avio_rb16(pb); /* sample size */
1611 av_dlog(c->fc, "audio channels %d\n", st->codec->channels);
1612
1613 sc->audio_cid = avio_rb16(pb);
1614 avio_rb16(pb); /* packet size = 0 */
1615
1616 st->codec->sample_rate = ((avio_rb32(pb) >> 16));
1617
1618 // Read QT version 1 fields. In version 0 these do not exist.
1619 av_dlog(c->fc, "version =%d, isom =%d\n", version, c->isom);
1620 if (!c->isom ||
1621 (compatible_brands && strstr(compatible_brands->value, "qt "))) {
1622
1623 if (version == 1) {
1624 sc->samples_per_frame = avio_rb32(pb);
1625 avio_rb32(pb); /* bytes per packet */
1626 sc->bytes_per_frame = avio_rb32(pb);
1627 avio_rb32(pb); /* bytes per sample */
1628 } else if (version == 2) {
1629 avio_rb32(pb); /* sizeof struct only */
1630 st->codec->sample_rate = av_int2double(avio_rb64(pb));
1631 st->codec->channels = avio_rb32(pb);
1632 avio_rb32(pb); /* always 0x7F000000 */
1633 st->codec->bits_per_coded_sample = avio_rb32(pb);
1634
1635 flags = avio_rb32(pb); /* lpcm format specific flag */
1636 sc->bytes_per_frame = avio_rb32(pb);
1637 sc->samples_per_frame = avio_rb32(pb);
1638 if (st->codec->codec_tag == MKTAG('l','p','c','m'))
1639 st->codec->codec_id =
1640 ff_mov_get_lpcm_codec_id(st->codec->bits_per_coded_sample,
1641 flags);
1642 }
1643 }
1644
1645 switch (st->codec->codec_id) {
1646 case AV_CODEC_ID_PCM_S8:
1647 case AV_CODEC_ID_PCM_U8:
1648 if (st->codec->bits_per_coded_sample == 16)
1649 st->codec->codec_id = AV_CODEC_ID_PCM_S16BE;
1650 break;
1651 case AV_CODEC_ID_PCM_S16LE:
1652 case AV_CODEC_ID_PCM_S16BE:
1653 if (st->codec->bits_per_coded_sample == 8)
1654 st->codec->codec_id = AV_CODEC_ID_PCM_S8;
1655 else if (st->codec->bits_per_coded_sample == 24)
1656 st->codec->codec_id =
1657 st->codec->codec_id == AV_CODEC_ID_PCM_S16BE ?
1658 AV_CODEC_ID_PCM_S24BE : AV_CODEC_ID_PCM_S24LE;
1659 break;
1660 /* set values for old format before stsd version 1 appeared */
1661 case AV_CODEC_ID_MACE3:
1662 sc->samples_per_frame = 6;
1663 sc->bytes_per_frame = 2 * st->codec->channels;
1664 break;
1665 case AV_CODEC_ID_MACE6:
1666 sc->samples_per_frame = 6;
1667 sc->bytes_per_frame = 1 * st->codec->channels;
1668 break;
1669 case AV_CODEC_ID_ADPCM_IMA_QT:
1670 sc->samples_per_frame = 64;
1671 sc->bytes_per_frame = 34 * st->codec->channels;
1672 break;
1673 case AV_CODEC_ID_GSM:
1674 sc->samples_per_frame = 160;
1675 sc->bytes_per_frame = 33;
1676 break;
1677 default:
1678 break;
1679 }
1680
1681 bits_per_sample = av_get_bits_per_sample(st->codec->codec_id);
1682 if (bits_per_sample) {
1683 st->codec->bits_per_coded_sample = bits_per_sample;
1684 sc->sample_size = (bits_per_sample >> 3) * st->codec->channels;
1685 }
1686}
1687
1688static void mov_parse_stsd_subtitle(MOVContext *c, AVIOContext *pb,
1689 AVStream *st, MOVStreamContext *sc,
1690 int size)
1691{
1692 // ttxt stsd contains display flags, justification, background
1693 // color, fonts, and default styles, so fake an atom to read it
1694 MOVAtom fake_atom = { .size = size };
1695 // mp4s contains a regular esds atom
1696 if (st->codec->codec_tag != AV_RL32("mp4s"))
1697 mov_read_glbl(c, pb, fake_atom);
1698 st->codec->width = sc->width;
1699 st->codec->height = sc->height;
1700}
1701
1702static int mov_parse_stsd_data(MOVContext *c, AVIOContext *pb,
1703 AVStream *st, MOVStreamContext *sc,
1704 int size)
1705{
1706 if (st->codec->codec_tag == MKTAG('t','m','c','d')) {
1707 if (ff_alloc_extradata(st->codec, size))
1708 return AVERROR(ENOMEM);
1709 avio_read(pb, st->codec->extradata, size);
1710 if (size > 16) {
1711 MOVStreamContext *tmcd_ctx = st->priv_data;
1712 int val;
1713 val = AV_RB32(st->codec->extradata + 4);
1714 tmcd_ctx->tmcd_flags = val;
1715 if (val & 1)
1716 st->codec->flags2 |= CODEC_FLAG2_DROP_FRAME_TIMECODE;
1717 st->codec->time_base.den = st->codec->extradata[16]; /* number of frame */
1718 st->codec->time_base.num = 1;
1719 }
1720 } else {
1721 /* other codec type, just skip (rtp, mp4s ...) */
1722 avio_skip(pb, size);
1723 }
1724 return 0;
1725}
1726
1727static int mov_finalize_stsd_codec(MOVContext *c, AVIOContext *pb,
1728 AVStream *st, MOVStreamContext *sc)
1729{
1730 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
1731 !st->codec->sample_rate && sc->time_scale > 1)
1732 st->codec->sample_rate = sc->time_scale;
1733
1734 /* special codec parameters handling */
1735 switch (st->codec->codec_id) {
1736#if CONFIG_DV_DEMUXER
1737 case AV_CODEC_ID_DVAUDIO:
1738 c->dv_fctx = avformat_alloc_context();
1739 c->dv_demux = avpriv_dv_init_demux(c->dv_fctx);
1740 if (!c->dv_demux) {
1741 av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n");
1742 return AVERROR(ENOMEM);
1743 }
1744 sc->dv_audio_container = 1;
1745 st->codec->codec_id = AV_CODEC_ID_PCM_S16LE;
1746 break;
1747#endif
1748 /* no ifdef since parameters are always those */
1749 case AV_CODEC_ID_QCELP:
1750 st->codec->channels = 1;
1751 // force sample rate for qcelp when not stored in mov
1752 if (st->codec->codec_tag != MKTAG('Q','c','l','p'))
1753 st->codec->sample_rate = 8000;
1754 break;
1755 case AV_CODEC_ID_AMR_NB:
1756 st->codec->channels = 1;
1757 /* force sample rate for amr, stsd in 3gp does not store sample rate */
1758 st->codec->sample_rate = 8000;
1759 break;
1760 case AV_CODEC_ID_AMR_WB:
1761 st->codec->channels = 1;
1762 st->codec->sample_rate = 16000;
1763 break;
1764 case AV_CODEC_ID_MP2:
1765 case AV_CODEC_ID_MP3:
1766 /* force type after stsd for m1a hdlr */
1767 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
1768 st->need_parsing = AVSTREAM_PARSE_FULL;
1769 break;
1770 case AV_CODEC_ID_GSM:
1771 case AV_CODEC_ID_ADPCM_MS:
1772 case AV_CODEC_ID_ADPCM_IMA_WAV:
1773 case AV_CODEC_ID_ILBC:
1774 case AV_CODEC_ID_MACE3:
1775 case AV_CODEC_ID_MACE6:
1776 case AV_CODEC_ID_QDM2:
1777 st->codec->block_align = sc->bytes_per_frame;
1778 break;
1779 case AV_CODEC_ID_ALAC:
1780 if (st->codec->extradata_size == 36) {
1781 st->codec->channels = AV_RB8 (st->codec->extradata + 21);
1782 st->codec->sample_rate = AV_RB32(st->codec->extradata + 32);
1783 }
1784 break;
1785 case AV_CODEC_ID_AC3:
1786 st->need_parsing = AVSTREAM_PARSE_FULL;
1787 break;
1788 case AV_CODEC_ID_MPEG1VIDEO:
1789 st->need_parsing = AVSTREAM_PARSE_FULL;
1790 break;
1791 case AV_CODEC_ID_VC1:
1792 st->need_parsing = AVSTREAM_PARSE_FULL;
1793 break;
1794 case AV_CODEC_ID_HEVC:
1795 st->need_parsing = AVSTREAM_PARSE_HEADERS;
1796 break;
1797 default:
1798 break;
1799 }
1800 return 0;
1801}
1802
1803static int mov_skip_multiple_stsd(MOVContext *c, AVIOContext *pb,
1804 int codec_tag, int format,
1805 int size)
1806{
1807 int video_codec_id = ff_codec_get_id(ff_codec_movvideo_tags, format);
1808
1809 if (codec_tag &&
1810 (codec_tag != format &&
1811 (c->fc->video_codec_id ? video_codec_id != c->fc->video_codec_id
1812 : codec_tag != MKTAG('j','p','e','g')))) {
1813 /* Multiple fourcc, we skip JPEG. This is not correct, we should
1814 * export it as a separate AVStream but this needs a few changes
1815 * in the MOV demuxer, patch welcome. */
1816
1817 av_log(c->fc, AV_LOG_WARNING, "multiple fourcc not supported\n");
1818 avio_skip(pb, size);
1819 return 1;
1820 }
1821 if ( codec_tag == AV_RL32("avc1") ||
1822 codec_tag == AV_RL32("hvc1") ||
1823 codec_tag == AV_RL32("hev1")
1824 )
1825 av_log(c->fc, AV_LOG_WARNING, "Concatenated H.264 or H.265 might not play correctly.\n");
1826
1827 return 0;
1828}
1829
1830int ff_mov_read_stsd_entries(MOVContext *c, AVIOContext *pb, int entries)
1831{
1832 AVStream *st;
1833 MOVStreamContext *sc;
1834 int pseudo_stream_id;
1835
1836 if (c->fc->nb_streams < 1)
1837 return 0;
1838 st = c->fc->streams[c->fc->nb_streams-1];
1839 sc = st->priv_data;
1840
1841 for (pseudo_stream_id = 0;
1842 pseudo_stream_id < entries && !pb->eof_reached;
1843 pseudo_stream_id++) {
1844 //Parsing Sample description table
1845 enum AVCodecID id;
1846 int ret, dref_id = 1;
1847 MOVAtom a = { AV_RL32("stsd") };
1848 int64_t start_pos = avio_tell(pb);
1849 int64_t size = avio_rb32(pb); /* size */
1850 uint32_t format = avio_rl32(pb); /* data format */
1851
1852 if (size >= 16) {
1853 avio_rb32(pb); /* reserved */
1854 avio_rb16(pb); /* reserved */
1855 dref_id = avio_rb16(pb);
1856 }else if (size <= 7){
1857 av_log(c->fc, AV_LOG_ERROR, "invalid size %"PRId64" in stsd\n", size);
1858 return AVERROR_INVALIDDATA;
1859 }
1860
1861 if (mov_skip_multiple_stsd(c, pb, st->codec->codec_tag, format,
1862 size - (avio_tell(pb) - start_pos)))
1863 continue;
1864
1865 sc->pseudo_stream_id = st->codec->codec_tag ? -1 : pseudo_stream_id;
1866 sc->dref_id= dref_id;
1867
1868 id = mov_codec_id(st, format);
1869
1870 av_dlog(c->fc, "size=%"PRId64" 4CC= %c%c%c%c codec_type=%d\n", size,
1871 (format >> 0) & 0xff, (format >> 8) & 0xff, (format >> 16) & 0xff,
1872 (format >> 24) & 0xff, st->codec->codec_type);
1873
1874 if (st->codec->codec_type==AVMEDIA_TYPE_VIDEO) {
1875 st->codec->codec_id = id;
1876 mov_parse_stsd_video(c, pb, st, sc);
1877 } else if (st->codec->codec_type==AVMEDIA_TYPE_AUDIO) {
1878 st->codec->codec_id = id;
1879 mov_parse_stsd_audio(c, pb, st, sc);
1880 } else if (st->codec->codec_type==AVMEDIA_TYPE_SUBTITLE){
1881 st->codec->codec_id = id;
1882 mov_parse_stsd_subtitle(c, pb, st, sc,
1883 size - (avio_tell(pb) - start_pos));
1884 } else {
1885 ret = mov_parse_stsd_data(c, pb, st, sc,
1886 size - (avio_tell(pb) - start_pos));
1887 if (ret < 0)
1888 return ret;
1889 }
1890 /* this will read extra atoms at the end (wave, alac, damr, avcC, hvcC, SMI ...) */
1891 a.size = size - (avio_tell(pb) - start_pos);
1892 if (a.size > 8) {
1893 if ((ret = mov_read_default(c, pb, a)) < 0)
1894 return ret;
1895 } else if (a.size > 0)
1896 avio_skip(pb, a.size);
1897 }
1898
1899 if (pb->eof_reached)
1900 return AVERROR_EOF;
1901
1902 return mov_finalize_stsd_codec(c, pb, st, sc);
1903}
1904
1905static int mov_read_stsd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1906{
1907 int entries;
1908
1909 avio_r8(pb); /* version */
1910 avio_rb24(pb); /* flags */
1911 entries = avio_rb32(pb);
1912
1913 return ff_mov_read_stsd_entries(c, pb, entries);
1914}
1915
1916static int mov_read_stsc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1917{
1918 AVStream *st;
1919 MOVStreamContext *sc;
1920 unsigned int i, entries;
1921
1922 if (c->fc->nb_streams < 1)
1923 return 0;
1924 st = c->fc->streams[c->fc->nb_streams-1];
1925 sc = st->priv_data;
1926
1927 avio_r8(pb); /* version */
1928 avio_rb24(pb); /* flags */
1929
1930 entries = avio_rb32(pb);
1931
1932 av_dlog(c->fc, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);
1933
1934 if (!entries)
1935 return 0;
1936 if (entries >= UINT_MAX / sizeof(*sc->stsc_data))
1937 return AVERROR_INVALIDDATA;
1938 sc->stsc_data = av_malloc(entries * sizeof(*sc->stsc_data));
1939 if (!sc->stsc_data)
1940 return AVERROR(ENOMEM);
1941
1942 for (i = 0; i < entries && !pb->eof_reached; i++) {
1943 sc->stsc_data[i].first = avio_rb32(pb);
1944 sc->stsc_data[i].count = avio_rb32(pb);
1945 sc->stsc_data[i].id = avio_rb32(pb);
1946 }
1947
1948 sc->stsc_count = i;
1949
1950 if (pb->eof_reached)
1951 return AVERROR_EOF;
1952
1953 return 0;
1954}
1955
1956static int mov_read_stps(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1957{
1958 AVStream *st;
1959 MOVStreamContext *sc;
1960 unsigned i, entries;
1961
1962 if (c->fc->nb_streams < 1)
1963 return 0;
1964 st = c->fc->streams[c->fc->nb_streams-1];
1965 sc = st->priv_data;
1966
1967 avio_rb32(pb); // version + flags
1968
1969 entries = avio_rb32(pb);
1970 if (entries >= UINT_MAX / sizeof(*sc->stps_data))
1971 return AVERROR_INVALIDDATA;
1972 sc->stps_data = av_malloc(entries * sizeof(*sc->stps_data));
1973 if (!sc->stps_data)
1974 return AVERROR(ENOMEM);
1975
1976 for (i = 0; i < entries && !pb->eof_reached; i++) {
1977 sc->stps_data[i] = avio_rb32(pb);
1978 //av_dlog(c->fc, "stps %d\n", sc->stps_data[i]);
1979 }
1980
1981 sc->stps_count = i;
1982
1983 if (pb->eof_reached)
1984 return AVERROR_EOF;
1985
1986 return 0;
1987}
1988
1989static int mov_read_stss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1990{
1991 AVStream *st;
1992 MOVStreamContext *sc;
1993 unsigned int i, entries;
1994
1995 if (c->fc->nb_streams < 1)
1996 return 0;
1997 st = c->fc->streams[c->fc->nb_streams-1];
1998 sc = st->priv_data;
1999
2000 avio_r8(pb); /* version */
2001 avio_rb24(pb); /* flags */
2002
2003 entries = avio_rb32(pb);
2004
2005 av_dlog(c->fc, "keyframe_count = %d\n", entries);
2006
2007 if (!entries)
2008 {
2009 sc->keyframe_absent = 1;
2010 if (!st->need_parsing)
2011 st->need_parsing = AVSTREAM_PARSE_HEADERS;
2012 return 0;
2013 }
2014 if (entries >= UINT_MAX / sizeof(int))
2015 return AVERROR_INVALIDDATA;
2016 sc->keyframes = av_malloc(entries * sizeof(int));
2017 if (!sc->keyframes)
2018 return AVERROR(ENOMEM);
2019
2020 for (i = 0; i < entries && !pb->eof_reached; i++) {
2021 sc->keyframes[i] = avio_rb32(pb);
2022 //av_dlog(c->fc, "keyframes[]=%d\n", sc->keyframes[i]);
2023 }
2024
2025 sc->keyframe_count = i;
2026
2027 if (pb->eof_reached)
2028 return AVERROR_EOF;
2029
2030 return 0;
2031}
2032
2033static int mov_read_stsz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2034{
2035 AVStream *st;
2036 MOVStreamContext *sc;
2037 unsigned int i, entries, sample_size, field_size, num_bytes;
2038 GetBitContext gb;
2039 unsigned char* buf;
2040
2041 if (c->fc->nb_streams < 1)
2042 return 0;
2043 st = c->fc->streams[c->fc->nb_streams-1];
2044 sc = st->priv_data;
2045
2046 avio_r8(pb); /* version */
2047 avio_rb24(pb); /* flags */
2048
2049 if (atom.type == MKTAG('s','t','s','z')) {
2050 sample_size = avio_rb32(pb);
2051 if (!sc->sample_size) /* do not overwrite value computed in stsd */
2052 sc->sample_size = sample_size;
2053 sc->stsz_sample_size = sample_size;
2054 field_size = 32;
2055 } else {
2056 sample_size = 0;
2057 avio_rb24(pb); /* reserved */
2058 field_size = avio_r8(pb);
2059 }
2060 entries = avio_rb32(pb);
2061
2062 av_dlog(c->fc, "sample_size = %d sample_count = %d\n", sc->sample_size, entries);
2063
2064 sc->sample_count = entries;
2065 if (sample_size)
2066 return 0;
2067
2068 if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) {
2069 av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %d\n", field_size);
2070 return AVERROR_INVALIDDATA;
2071 }
2072
2073 if (!entries)
2074 return 0;
2075 if (entries >= UINT_MAX / sizeof(int) || entries >= (UINT_MAX - 4) / field_size)
2076 return AVERROR_INVALIDDATA;
2077 sc->sample_sizes = av_malloc(entries * sizeof(int));
2078 if (!sc->sample_sizes)
2079 return AVERROR(ENOMEM);
2080
2081 num_bytes = (entries*field_size+4)>>3;
2082
2083 buf = av_malloc(num_bytes+FF_INPUT_BUFFER_PADDING_SIZE);
2084 if (!buf) {
2085 av_freep(&sc->sample_sizes);
2086 return AVERROR(ENOMEM);
2087 }
2088
2089 if (avio_read(pb, buf, num_bytes) < num_bytes) {
2090 av_freep(&sc->sample_sizes);
2091 av_free(buf);
2092 return AVERROR_INVALIDDATA;
2093 }
2094
2095 init_get_bits(&gb, buf, 8*num_bytes);
2096
2097 for (i = 0; i < entries && !pb->eof_reached; i++) {
2098 sc->sample_sizes[i] = get_bits_long(&gb, field_size);
2099 sc->data_size += sc->sample_sizes[i];
2100 }
2101
2102 sc->sample_count = i;
2103
2104 if (pb->eof_reached)
2105 return AVERROR_EOF;
2106
2107 av_free(buf);
2108 return 0;
2109}
2110
2111static int mov_read_stts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2112{
2113 AVStream *st;
2114 MOVStreamContext *sc;
2115 unsigned int i, entries;
2116 int64_t duration=0;
2117 int64_t total_sample_count=0;
2118
2119 if (c->fc->nb_streams < 1)
2120 return 0;
2121 st = c->fc->streams[c->fc->nb_streams-1];
2122 sc = st->priv_data;
2123
2124 avio_r8(pb); /* version */
2125 avio_rb24(pb); /* flags */
2126 entries = avio_rb32(pb);
2127
2128 av_dlog(c->fc, "track[%i].stts.entries = %i\n",
2129 c->fc->nb_streams-1, entries);
2130
2131 if (entries >= UINT_MAX / sizeof(*sc->stts_data))
2132 return -1;
2133
2134 sc->stts_data = av_malloc(entries * sizeof(*sc->stts_data));
2135 if (!sc->stts_data)
2136 return AVERROR(ENOMEM);
2137
2138 for (i = 0; i < entries && !pb->eof_reached; i++) {
2139 int sample_duration;
2140 int sample_count;
2141
2142 sample_count=avio_rb32(pb);
2143 sample_duration = avio_rb32(pb);
2144
2145 /* sample_duration < 0 is invalid based on the spec */
2146 if (sample_duration < 0) {
2147 av_log(c->fc, AV_LOG_ERROR, "Invalid SampleDelta in STTS %d\n", sample_duration);
2148 sample_duration = 1;
2149 }
2150 if (sample_count < 0) {
2151 av_log(c->fc, AV_LOG_ERROR, "Invalid sample_count=%d\n", sample_count);
2152 return AVERROR_INVALIDDATA;
2153 }
2154 sc->stts_data[i].count= sample_count;
2155 sc->stts_data[i].duration= sample_duration;
2156
2157 av_dlog(c->fc, "sample_count=%d, sample_duration=%d\n",
2158 sample_count, sample_duration);
2159
2160 duration+=(int64_t)sample_duration*sample_count;
2161 total_sample_count+=sample_count;
2162 }
2163
2164 sc->stts_count = i;
2165
2166 if (pb->eof_reached)
2167 return AVERROR_EOF;
2168
2169 st->nb_frames= total_sample_count;
2170 if (duration)
2171 st->duration= duration;
2172 sc->track_end = duration;
2173 return 0;
2174}
2175
2176static void mov_update_dts_shift(MOVStreamContext *sc, int duration)
2177{
2178 if (duration < 0) {
2179 sc->dts_shift = FFMAX(sc->dts_shift, -duration);
2180 }
2181}
2182
2183static int mov_read_ctts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2184{
2185 AVStream *st;
2186 MOVStreamContext *sc;
2187 unsigned int i, entries;
2188
2189 if (c->fc->nb_streams < 1)
2190 return 0;
2191 st = c->fc->streams[c->fc->nb_streams-1];
2192 sc = st->priv_data;
2193
2194 avio_r8(pb); /* version */
2195 avio_rb24(pb); /* flags */
2196 entries = avio_rb32(pb);
2197
2198 av_dlog(c->fc, "track[%i].ctts.entries = %i\n", c->fc->nb_streams-1, entries);
2199
2200 if (!entries)
2201 return 0;
2202 if (entries >= UINT_MAX / sizeof(*sc->ctts_data))
2203 return AVERROR_INVALIDDATA;
2204 sc->ctts_data = av_malloc(entries * sizeof(*sc->ctts_data));
2205 if (!sc->ctts_data)
2206 return AVERROR(ENOMEM);
2207
2208 for (i = 0; i < entries && !pb->eof_reached; i++) {
2209 int count =avio_rb32(pb);
2210 int duration =avio_rb32(pb);
2211
2212 sc->ctts_data[i].count = count;
2213 sc->ctts_data[i].duration= duration;
2214
2215 av_dlog(c->fc, "count=%d, duration=%d\n",
2216 count, duration);
2217
2218 if (FFABS(duration) > (1<<28) && i+2<entries) {
2219 av_log(c->fc, AV_LOG_WARNING, "CTTS invalid\n");
2220 av_freep(&sc->ctts_data);
2221 sc->ctts_count = 0;
2222 return 0;
2223 }
2224
2225 if (i+2<entries)
2226 mov_update_dts_shift(sc, duration);
2227 }
2228
2229 sc->ctts_count = i;
2230
2231 if (pb->eof_reached)
2232 return AVERROR_EOF;
2233
2234 av_dlog(c->fc, "dts shift %d\n", sc->dts_shift);
2235
2236 return 0;
2237}
2238
2239static int mov_read_sbgp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2240{
2241 AVStream *st;
2242 MOVStreamContext *sc;
2243 unsigned int i, entries;
2244 uint8_t version;
2245 uint32_t grouping_type;
2246
2247 if (c->fc->nb_streams < 1)
2248 return 0;
2249 st = c->fc->streams[c->fc->nb_streams-1];
2250 sc = st->priv_data;
2251
2252 version = avio_r8(pb); /* version */
2253 avio_rb24(pb); /* flags */
2254 grouping_type = avio_rl32(pb);
2255 if (grouping_type != MKTAG( 'r','a','p',' '))
2256 return 0; /* only support 'rap ' grouping */
2257 if (version == 1)
2258 avio_rb32(pb); /* grouping_type_parameter */
2259
2260 entries = avio_rb32(pb);
2261 if (!entries)
2262 return 0;
2263 if (entries >= UINT_MAX / sizeof(*sc->rap_group))
2264 return AVERROR_INVALIDDATA;
2265 sc->rap_group = av_malloc(entries * sizeof(*sc->rap_group));
2266 if (!sc->rap_group)
2267 return AVERROR(ENOMEM);
2268
2269 for (i = 0; i < entries && !pb->eof_reached; i++) {
2270 sc->rap_group[i].count = avio_rb32(pb); /* sample_count */
2271 sc->rap_group[i].index = avio_rb32(pb); /* group_description_index */
2272 }
2273
2274 sc->rap_group_count = i;
2275
2276 return pb->eof_reached ? AVERROR_EOF : 0;
2277}
2278
2279static void mov_build_index(MOVContext *mov, AVStream *st)
2280{
2281 MOVStreamContext *sc = st->priv_data;
2282 int64_t current_offset;
2283 int64_t current_dts = 0;
2284 unsigned int stts_index = 0;
2285 unsigned int stsc_index = 0;
2286 unsigned int stss_index = 0;
2287 unsigned int stps_index = 0;
2288 unsigned int i, j;
2289 uint64_t stream_size = 0;
2290
2291 /* adjust first dts according to edit list */
2292 if ((sc->empty_duration || sc->start_time) && mov->time_scale > 0) {
2293 if (sc->empty_duration)
2294 sc->empty_duration = av_rescale(sc->empty_duration, sc->time_scale, mov->time_scale);
2295 sc->time_offset = sc->start_time - sc->empty_duration;
2296 current_dts = -sc->time_offset;
2297 if (sc->ctts_count>0 && sc->stts_count>0 &&
2298 sc->ctts_data[0].duration / FFMAX(sc->stts_data[0].duration, 1) > 16) {
2299 /* more than 16 frames delay, dts are likely wrong
2300 this happens with files created by iMovie */
2301 sc->wrong_dts = 1;
2302 st->codec->has_b_frames = 1;
2303 }
2304 }
2305
2306 /* only use old uncompressed audio chunk demuxing when stts specifies it */
2307 if (!(st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
2308 sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
2309 unsigned int current_sample = 0;
2310 unsigned int stts_sample = 0;
2311 unsigned int sample_size;
2312 unsigned int distance = 0;
2313 unsigned int rap_group_index = 0;
2314 unsigned int rap_group_sample = 0;
2315 int rap_group_present = sc->rap_group_count && sc->rap_group;
2316 int key_off = (sc->keyframe_count && sc->keyframes[0] > 0) || (sc->stps_count && sc->stps_data[0] > 0);
2317
2318 current_dts -= sc->dts_shift;
2319
2320 if (!sc->sample_count || st->nb_index_entries)
2321 return;
2322 if (sc->sample_count >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
2323 return;
2324 if (av_reallocp_array(&st->index_entries,
2325 st->nb_index_entries + sc->sample_count,
2326 sizeof(*st->index_entries)) < 0) {
2327 st->nb_index_entries = 0;
2328 return;
2329 }
2330 st->index_entries_allocated_size = (st->nb_index_entries + sc->sample_count) * sizeof(*st->index_entries);
2331
2332 for (i = 0; i < sc->chunk_count; i++) {
2333 int64_t next_offset = i+1 < sc->chunk_count ? sc->chunk_offsets[i+1] : INT64_MAX;
2334 current_offset = sc->chunk_offsets[i];
2335 while (stsc_index + 1 < sc->stsc_count &&
2336 i + 1 == sc->stsc_data[stsc_index + 1].first)
2337 stsc_index++;
2338
2339 if (next_offset > current_offset && sc->sample_size>0 && sc->sample_size < sc->stsz_sample_size &&
2340 sc->stsc_data[stsc_index].count * (int64_t)sc->stsz_sample_size > next_offset - current_offset) {
2341 av_log(mov->fc, AV_LOG_WARNING, "STSZ sample size %d invalid (too large), ignoring\n", sc->stsz_sample_size);
2342 sc->stsz_sample_size = sc->sample_size;
2343 }
2344 if (sc->stsz_sample_size>0 && sc->stsz_sample_size < sc->sample_size) {
2345 av_log(mov->fc, AV_LOG_WARNING, "STSZ sample size %d invalid (too small), ignoring\n", sc->stsz_sample_size);
2346 sc->stsz_sample_size = sc->sample_size;
2347 }
2348
2349 for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
2350 int keyframe = 0;
2351 if (current_sample >= sc->sample_count) {
2352 av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
2353 return;
2354 }
2355
2356 if (!sc->keyframe_absent && (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index])) {
2357 keyframe = 1;
2358 if (stss_index + 1 < sc->keyframe_count)
2359 stss_index++;
2360 } else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) {
2361 keyframe = 1;
2362 if (stps_index + 1 < sc->stps_count)
2363 stps_index++;
2364 }
2365 if (rap_group_present && rap_group_index < sc->rap_group_count) {
2366 if (sc->rap_group[rap_group_index].index > 0)
2367 keyframe = 1;
2368 if (++rap_group_sample == sc->rap_group[rap_group_index].count) {
2369 rap_group_sample = 0;
2370 rap_group_index++;
2371 }
2372 }
2373 if (keyframe)
2374 distance = 0;
2375 sample_size = sc->stsz_sample_size > 0 ? sc->stsz_sample_size : sc->sample_sizes[current_sample];
2376 if (sc->pseudo_stream_id == -1 ||
2377 sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
2378 AVIndexEntry *e = &st->index_entries[st->nb_index_entries++];
2379 e->pos = current_offset;
2380 e->timestamp = current_dts;
2381 e->size = sample_size;
2382 e->min_distance = distance;
2383 e->flags = keyframe ? AVINDEX_KEYFRAME : 0;
2384 av_dlog(mov->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
2385 "size %d, distance %d, keyframe %d\n", st->index, current_sample,
2386 current_offset, current_dts, sample_size, distance, keyframe);
2387 }
2388
2389 current_offset += sample_size;
2390 stream_size += sample_size;
2391 current_dts += sc->stts_data[stts_index].duration;
2392 distance++;
2393 stts_sample++;
2394 current_sample++;
2395 if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
2396 stts_sample = 0;
2397 stts_index++;
2398 }
2399 }
2400 }
2401 if (st->duration > 0)
2402 st->codec->bit_rate = stream_size*8*sc->time_scale/st->duration;
2403 } else {
2404 unsigned chunk_samples, total = 0;
2405
2406 // compute total chunk count
2407 for (i = 0; i < sc->stsc_count; i++) {
2408 unsigned count, chunk_count;
2409
2410 chunk_samples = sc->stsc_data[i].count;
2411 if (i != sc->stsc_count - 1 &&
2412 sc->samples_per_frame && chunk_samples % sc->samples_per_frame) {
2413 av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n");
2414 return;
2415 }
2416
2417 if (sc->samples_per_frame >= 160) { // gsm
2418 count = chunk_samples / sc->samples_per_frame;
2419 } else if (sc->samples_per_frame > 1) {
2420 unsigned samples = (1024/sc->samples_per_frame)*sc->samples_per_frame;
2421 count = (chunk_samples+samples-1) / samples;
2422 } else {
2423 count = (chunk_samples+1023) / 1024;
2424 }
2425
2426 if (i < sc->stsc_count - 1)
2427 chunk_count = sc->stsc_data[i+1].first - sc->stsc_data[i].first;
2428 else
2429 chunk_count = sc->chunk_count - (sc->stsc_data[i].first - 1);
2430 total += chunk_count * count;
2431 }
2432
2433 av_dlog(mov->fc, "chunk count %d\n", total);
2434 if (total >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
2435 return;
2436 if (av_reallocp_array(&st->index_entries,
2437 st->nb_index_entries + total,
2438 sizeof(*st->index_entries)) < 0) {
2439 st->nb_index_entries = 0;
2440 return;
2441 }
2442 st->index_entries_allocated_size = (st->nb_index_entries + total) * sizeof(*st->index_entries);
2443
2444 // populate index
2445 for (i = 0; i < sc->chunk_count; i++) {
2446 current_offset = sc->chunk_offsets[i];
2447 if (stsc_index + 1 < sc->stsc_count &&
2448 i + 1 == sc->stsc_data[stsc_index + 1].first)
2449 stsc_index++;
2450 chunk_samples = sc->stsc_data[stsc_index].count;
2451
2452 while (chunk_samples > 0) {
2453 AVIndexEntry *e;
2454 unsigned size, samples;
2455
2456 if (sc->samples_per_frame >= 160) { // gsm
2457 samples = sc->samples_per_frame;
2458 size = sc->bytes_per_frame;
2459 } else {
2460 if (sc->samples_per_frame > 1) {
2461 samples = FFMIN((1024 / sc->samples_per_frame)*
2462 sc->samples_per_frame, chunk_samples);
2463 size = (samples / sc->samples_per_frame) * sc->bytes_per_frame;
2464 } else {
2465 samples = FFMIN(1024, chunk_samples);
2466 size = samples * sc->sample_size;
2467 }
2468 }
2469
2470 if (st->nb_index_entries >= total) {
2471 av_log(mov->fc, AV_LOG_ERROR, "wrong chunk count %d\n", total);
2472 return;
2473 }
2474 e = &st->index_entries[st->nb_index_entries++];
2475 e->pos = current_offset;
2476 e->timestamp = current_dts;
2477 e->size = size;
2478 e->min_distance = 0;
2479 e->flags = AVINDEX_KEYFRAME;
2480 av_dlog(mov->fc, "AVIndex stream %d, chunk %d, offset %"PRIx64", dts %"PRId64", "
2481 "size %d, duration %d\n", st->index, i, current_offset, current_dts,
2482 size, samples);
2483
2484 current_offset += size;
2485 current_dts += samples;
2486 chunk_samples -= samples;
2487 }
2488 }
2489 }
2490}
2491
2492static int mov_open_dref(AVIOContext **pb, const char *src, MOVDref *ref,
2493 AVIOInterruptCB *int_cb, int use_absolute_path, AVFormatContext *fc)
2494{
2495 /* try relative path, we do not try the absolute because it can leak information about our
2496 system to an attacker */
2497 if (ref->nlvl_to > 0 && ref->nlvl_from > 0) {
2498 char filename[1024];
2499 const char *src_path;
2500 int i, l;
2501
2502 /* find a source dir */
2503 src_path = strrchr(src, '/');
2504 if (src_path)
2505 src_path++;
2506 else
2507 src_path = src;
2508
2509 /* find a next level down to target */
2510 for (i = 0, l = strlen(ref->path) - 1; l >= 0; l--)
2511 if (ref->path[l] == '/') {
2512 if (i == ref->nlvl_to - 1)
2513 break;
2514 else
2515 i++;
2516 }
2517
2518 /* compose filename if next level down to target was found */
2519 if (i == ref->nlvl_to - 1 && src_path - src < sizeof(filename)) {
2520 memcpy(filename, src, src_path - src);
2521 filename[src_path - src] = 0;
2522
2523 for (i = 1; i < ref->nlvl_from; i++)
2524 av_strlcat(filename, "../", 1024);
2525
2526 av_strlcat(filename, ref->path + l + 1, 1024);
2527
2528 if (!avio_open2(pb, filename, AVIO_FLAG_READ, int_cb, NULL))
2529 return 0;
2530 }
2531 } else if (use_absolute_path) {
2532 av_log(fc, AV_LOG_WARNING, "Using absolute path on user request, "
2533 "this is a possible security issue\n");
2534 if (!avio_open2(pb, ref->path, AVIO_FLAG_READ, int_cb, NULL))
2535 return 0;
2536 }
2537
2538 return AVERROR(ENOENT);
2539}
2540
2541static void fix_timescale(MOVContext *c, MOVStreamContext *sc)
2542{
2543 if (sc->time_scale <= 0) {
2544 av_log(c->fc, AV_LOG_WARNING, "stream %d, timescale not set\n", sc->ffindex);
2545 sc->time_scale = c->time_scale;
2546 if (sc->time_scale <= 0)
2547 sc->time_scale = 1;
2548 }
2549}
2550
2551static int mov_read_trak(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2552{
2553 AVStream *st;
2554 MOVStreamContext *sc;
2555 int ret;
2556
2557 st = avformat_new_stream(c->fc, NULL);
2558 if (!st) return AVERROR(ENOMEM);
2559 st->id = c->fc->nb_streams;
2560 sc = av_mallocz(sizeof(MOVStreamContext));
2561 if (!sc) return AVERROR(ENOMEM);
2562
2563 st->priv_data = sc;
2564 st->codec->codec_type = AVMEDIA_TYPE_DATA;
2565 sc->ffindex = st->index;
2566 c->trak_index = st->index;
2567
2568 if ((ret = mov_read_default(c, pb, atom)) < 0)
2569 return ret;
2570
2571 c->trak_index = -1;
2572
2573 /* sanity checks */
2574 if (sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
2575 (!sc->sample_size && !sc->sample_count))) {
2576 av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
2577 st->index);
2578 return 0;
2579 }
2580
2581 fix_timescale(c, sc);
2582
2583 avpriv_set_pts_info(st, 64, 1, sc->time_scale);
2584
2585 mov_build_index(c, st);
2586
2587 if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
2588 MOVDref *dref = &sc->drefs[sc->dref_id - 1];
2589 if (mov_open_dref(&sc->pb, c->fc->filename, dref, &c->fc->interrupt_callback,
2590 c->use_absolute_path, c->fc) < 0)
2591 av_log(c->fc, AV_LOG_ERROR,
2592 "stream %d, error opening alias: path='%s', dir='%s', "
2593 "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d\n",
2594 st->index, dref->path, dref->dir, dref->filename,
2595 dref->volume, dref->nlvl_from, dref->nlvl_to);
2596 } else {
2597 sc->pb = c->fc->pb;
2598 sc->pb_is_copied = 1;
2599 }
2600
2601 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
2602 if (!st->sample_aspect_ratio.num &&
2603 (st->codec->width != sc->width || st->codec->height != sc->height)) {
2604 st->sample_aspect_ratio = av_d2q(((double)st->codec->height * sc->width) /
2605 ((double)st->codec->width * sc->height), INT_MAX);
2606 }
2607
2608 if (st->duration > 0)
2609 av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
2610 sc->time_scale*st->nb_frames, st->duration, INT_MAX);
2611
2612#if FF_API_R_FRAME_RATE
2613 if (sc->stts_count == 1 || (sc->stts_count == 2 && sc->stts_data[1].count == 1))
2614 av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den,
2615 sc->time_scale, sc->stts_data[0].duration, INT_MAX);
2616#endif
2617 }
2618
2619 // done for ai5q, ai52, ai55, ai1q, ai12 and ai15.
2620 if (!st->codec->extradata_size && st->codec->codec_id == AV_CODEC_ID_H264 &&
2621 st->codec->codec_tag != MKTAG('a', 'v', 'c', '1')) {
2622 ff_generate_avci_extradata(st);
2623 }
2624
2625 switch (st->codec->codec_id) {
2626#if CONFIG_H261_DECODER
2627 case AV_CODEC_ID_H261:
2628#endif
2629#if CONFIG_H263_DECODER
2630 case AV_CODEC_ID_H263:
2631#endif
2632#if CONFIG_MPEG4_DECODER
2633 case AV_CODEC_ID_MPEG4:
2634#endif
2635 st->codec->width = 0; /* let decoder init width/height */
2636 st->codec->height= 0;
2637 break;
2638 }
2639
2640 /* Do not need those anymore. */
2641 av_freep(&sc->chunk_offsets);
2642 av_freep(&sc->stsc_data);
2643 av_freep(&sc->sample_sizes);
2644 av_freep(&sc->keyframes);
2645 av_freep(&sc->stts_data);
2646 av_freep(&sc->stps_data);
2647 av_freep(&sc->rap_group);
2648
2649 return 0;
2650}
2651
2652static int mov_read_ilst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2653{
2654 int ret;
2655 c->itunes_metadata = 1;
2656 ret = mov_read_default(c, pb, atom);
2657 c->itunes_metadata = 0;
2658 return ret;
2659}
2660
2661static int mov_read_keys(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2662{
2663 uint32_t count;
2664 uint32_t i;
2665
2666 if (atom.size < 8)
2667 return 0;
2668
2669 avio_skip(pb, 4);
2670 count = avio_rb32(pb);
2671 if (count > UINT_MAX / sizeof(*c->meta_keys)) {
2672 av_log(c->fc, AV_LOG_ERROR,
2673 "The 'keys' atom with the invalid key count: %d\n", count);
2674 return AVERROR_INVALIDDATA;
2675 }
2676
2677 c->meta_keys_count = count + 1;
2678 c->meta_keys = av_mallocz(c->meta_keys_count * sizeof(*c->meta_keys));
2679 if (!c->meta_keys)
2680 return AVERROR(ENOMEM);
2681
2682 for (i = 1; i <= count; ++i) {
2683 uint32_t key_size = avio_rb32(pb);
2684 uint32_t type = avio_rl32(pb);
2685 if (key_size < 8) {
2686 av_log(c->fc, AV_LOG_ERROR,
2687 "The key# %d in meta has invalid size: %d\n", i, key_size);
2688 return AVERROR_INVALIDDATA;
2689 }
2690 key_size -= 8;
2691 if (type != MKTAG('m','d','t','a')) {
2692 avio_skip(pb, key_size);
2693 }
2694 c->meta_keys[i] = av_mallocz(key_size + 1);
2695 if (!c->meta_keys[i])
2696 return AVERROR(ENOMEM);
2697 avio_read(pb, c->meta_keys[i], key_size);
2698 }
2699
2700 return 0;
2701}
2702
2703static int mov_read_meta(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2704{
2705 while (atom.size > 8) {
2706 uint32_t tag = avio_rl32(pb);
2707 atom.size -= 4;
2708 if (tag == MKTAG('h','d','l','r')) {
2709 avio_seek(pb, -8, SEEK_CUR);
2710 atom.size += 8;
2711 return mov_read_default(c, pb, atom);
2712 }
2713 }
2714 return 0;
2715}
2716
2717static int mov_read_tkhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2718{
2719 int i;
2720 int width;
2721 int height;
2722 int64_t disp_transform[2];
2723 int display_matrix[3][2];
2724 AVStream *st;
2725 MOVStreamContext *sc;
2726 int version;
2727 int flags;
2728
2729 if (c->fc->nb_streams < 1)
2730 return 0;
2731 st = c->fc->streams[c->fc->nb_streams-1];
2732 sc = st->priv_data;
2733
2734 version = avio_r8(pb);
2735 flags = avio_rb24(pb);
2736 st->disposition |= (flags & MOV_TKHD_FLAG_ENABLED) ? AV_DISPOSITION_DEFAULT : 0;
2737
2738 if (version == 1) {
2739 avio_rb64(pb);
2740 avio_rb64(pb);
2741 } else {
2742 avio_rb32(pb); /* creation time */
2743 avio_rb32(pb); /* modification time */
2744 }
2745 st->id = (int)avio_rb32(pb); /* track id (NOT 0 !)*/
2746 avio_rb32(pb); /* reserved */
2747
2748 /* highlevel (considering edits) duration in movie timebase */
2749 (version == 1) ? avio_rb64(pb) : avio_rb32(pb);
2750 avio_rb32(pb); /* reserved */
2751 avio_rb32(pb); /* reserved */
2752
2753 avio_rb16(pb); /* layer */
2754 avio_rb16(pb); /* alternate group */
2755 avio_rb16(pb); /* volume */
2756 avio_rb16(pb); /* reserved */
2757
2758 //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
2759 // they're kept in fixed point format through all calculations
2760 // ignore u,v,z b/c we don't need the scale factor to calc aspect ratio
2761 for (i = 0; i < 3; i++) {
2762 display_matrix[i][0] = avio_rb32(pb); // 16.16 fixed point
2763 display_matrix[i][1] = avio_rb32(pb); // 16.16 fixed point
2764 avio_rb32(pb); // 2.30 fixed point (not used)
2765 }
2766
2767 width = avio_rb32(pb); // 16.16 fixed point track width
2768 height = avio_rb32(pb); // 16.16 fixed point track height
2769 sc->width = width >> 16;
2770 sc->height = height >> 16;
2771
2772 //Assign clockwise rotate values based on transform matrix so that
2773 //we can compensate for iPhone orientation during capture.
2774
2775 if (display_matrix[0][0] == 65536 && display_matrix[1][1] == 65536) {
2776 av_dict_set(&st->metadata, "rotate", "0", 0);
2777 st->rotation_degree = 0;
2778 }
2779
2780 if (display_matrix[1][0] == -65536 && display_matrix[0][1] == 65536) {
2781 av_dict_set(&st->metadata, "rotate", "90", 0);
2782 st->rotation_degree = 1;
2783 }
2784
2785 if (display_matrix[0][0] == -65536 && display_matrix[1][1] == -65536) {
2786 av_dict_set(&st->metadata, "rotate", "180", 0);
2787 st->rotation_degree = 2;
2788 }
2789
2790 if (display_matrix[1][0] == 65536 && display_matrix[0][1] == -65536) {
2791 av_dict_set(&st->metadata, "rotate", "270", 0);
2792 st->rotation_degree = 3;
2793 }
2794
2795 // transform the display width/height according to the matrix
2796 // skip this if the display matrix is the default identity matrix
2797 // or if it is rotating the picture, ex iPhone 3GS
2798 // to keep the same scale, use [width height 1<<16]
2799 if (width && height &&
2800 ((display_matrix[0][0] != 65536 ||
2801 display_matrix[1][1] != 65536) &&
2802 !display_matrix[0][1] &&
2803 !display_matrix[1][0] &&
2804 !display_matrix[2][0] && !display_matrix[2][1])) {
2805 for (i = 0; i < 2; i++)
2806 disp_transform[i] =
2807 (int64_t) width * display_matrix[0][i] +
2808 (int64_t) height * display_matrix[1][i] +
2809 ((int64_t) display_matrix[2][i] << 16);
2810
2811 //sample aspect ratio is new width/height divided by old width/height
2812 st->sample_aspect_ratio = av_d2q(
2813 ((double) disp_transform[0] * height) /
2814 ((double) disp_transform[1] * width), INT_MAX);
2815 }
2816 return 0;
2817}
2818
2819static int mov_read_tfhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2820{
2821 MOVFragment *frag = &c->fragment;
2822 MOVTrackExt *trex = NULL;
2823 int flags, track_id, i;
2824
2825 avio_r8(pb); /* version */
2826 flags = avio_rb24(pb);
2827
2828 track_id = avio_rb32(pb);
2829 if (!track_id)
2830 return AVERROR_INVALIDDATA;
2831 frag->track_id = track_id;
2832 for (i = 0; i < c->trex_count; i++)
2833 if (c->trex_data[i].track_id == frag->track_id) {
2834 trex = &c->trex_data[i];
2835 break;
2836 }
2837 if (!trex) {
2838 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
2839 return AVERROR_INVALIDDATA;
2840 }
2841
2842 frag->base_data_offset = flags & MOV_TFHD_BASE_DATA_OFFSET ?
2843 avio_rb64(pb) : frag->moof_offset;
2844 frag->stsd_id = flags & MOV_TFHD_STSD_ID ? avio_rb32(pb) : trex->stsd_id;
2845
2846 frag->duration = flags & MOV_TFHD_DEFAULT_DURATION ?
2847 avio_rb32(pb) : trex->duration;
2848 frag->size = flags & MOV_TFHD_DEFAULT_SIZE ?
2849 avio_rb32(pb) : trex->size;
2850 frag->flags = flags & MOV_TFHD_DEFAULT_FLAGS ?
2851 avio_rb32(pb) : trex->flags;
2852 av_dlog(c->fc, "frag flags 0x%x\n", frag->flags);
2853 return 0;
2854}
2855
2856static int mov_read_chap(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2857{
2858 c->chapter_track = avio_rb32(pb);
2859 return 0;
2860}
2861
2862static int mov_read_trex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2863{
2864 MOVTrackExt *trex;
2865 int err;
2866
2867 if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
2868 return AVERROR_INVALIDDATA;
2869 if ((err = av_reallocp_array(&c->trex_data, c->trex_count + 1,
2870 sizeof(*c->trex_data))) < 0) {
2871 c->trex_count = 0;
2872 return err;
2873 }
2874
2875 c->fc->duration = AV_NOPTS_VALUE; // the duration from mvhd is not representing the whole file when fragments are used.
2876
2877 trex = &c->trex_data[c->trex_count++];
2878 avio_r8(pb); /* version */
2879 avio_rb24(pb); /* flags */
2880 trex->track_id = avio_rb32(pb);
2881 trex->stsd_id = avio_rb32(pb);
2882 trex->duration = avio_rb32(pb);
2883 trex->size = avio_rb32(pb);
2884 trex->flags = avio_rb32(pb);
2885 return 0;
2886}
2887
2888static int mov_read_trun(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2889{
2890 MOVFragment *frag = &c->fragment;
2891 AVStream *st = NULL;
2892 MOVStreamContext *sc;
2893 MOVStts *ctts_data;
2894 uint64_t offset;
2895 int64_t dts;
2896 int data_offset = 0;
2897 unsigned entries, first_sample_flags = frag->flags;
2898 int flags, distance, i, found_keyframe = 0, err;
2899
2900 for (i = 0; i < c->fc->nb_streams; i++) {
2901 if (c->fc->streams[i]->id == frag->track_id) {
2902 st = c->fc->streams[i];
2903 break;
2904 }
2905 }
2906 if (!st) {
2907 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
2908 return AVERROR_INVALIDDATA;
2909 }
2910 sc = st->priv_data;
2911 if (sc->pseudo_stream_id+1 != frag->stsd_id && sc->pseudo_stream_id != -1)
2912 return 0;
2913 avio_r8(pb); /* version */
2914 flags = avio_rb24(pb);
2915 entries = avio_rb32(pb);
2916 av_dlog(c->fc, "flags 0x%x entries %d\n", flags, entries);
2917
2918 /* Always assume the presence of composition time offsets.
2919 * Without this assumption, for instance, we cannot deal with a track in fragmented movies that meet the following.
2920 * 1) in the initial movie, there are no samples.
2921 * 2) in the first movie fragment, there is only one sample without composition time offset.
2922 * 3) in the subsequent movie fragments, there are samples with composition time offset. */
2923 if (!sc->ctts_count && sc->sample_count)
2924 {
2925 /* Complement ctts table if moov atom doesn't have ctts atom. */
2926 ctts_data = av_realloc(NULL, sizeof(*sc->ctts_data));
2927 if (!ctts_data)
2928 return AVERROR(ENOMEM);
2929 sc->ctts_data = ctts_data;
2930 sc->ctts_data[sc->ctts_count].count = sc->sample_count;
2931 sc->ctts_data[sc->ctts_count].duration = 0;
2932 sc->ctts_count++;
2933 }
2934 if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
2935 return AVERROR_INVALIDDATA;
2936 if ((err = av_reallocp_array(&sc->ctts_data, entries + sc->ctts_count,
2937 sizeof(*sc->ctts_data))) < 0) {
2938 sc->ctts_count = 0;
2939 return err;
2940 }
2941 if (flags & MOV_TRUN_DATA_OFFSET) data_offset = avio_rb32(pb);
2942 if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS) first_sample_flags = avio_rb32(pb);
2943 dts = sc->track_end - sc->time_offset;
2944 offset = frag->base_data_offset + data_offset;
2945 distance = 0;
2946 av_dlog(c->fc, "first sample flags 0x%x\n", first_sample_flags);
2947 for (i = 0; i < entries && !pb->eof_reached; i++) {
2948 unsigned sample_size = frag->size;
2949 int sample_flags = i ? frag->flags : first_sample_flags;
2950 unsigned sample_duration = frag->duration;
2951 int keyframe = 0;
2952
2953 if (flags & MOV_TRUN_SAMPLE_DURATION) sample_duration = avio_rb32(pb);
2954 if (flags & MOV_TRUN_SAMPLE_SIZE) sample_size = avio_rb32(pb);
2955 if (flags & MOV_TRUN_SAMPLE_FLAGS) sample_flags = avio_rb32(pb);
2956 sc->ctts_data[sc->ctts_count].count = 1;
2957 sc->ctts_data[sc->ctts_count].duration = (flags & MOV_TRUN_SAMPLE_CTS) ?
2958 avio_rb32(pb) : 0;
2959 mov_update_dts_shift(sc, sc->ctts_data[sc->ctts_count].duration);
2960 sc->ctts_count++;
2961 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
2962 keyframe = 1;
2963 else if (!found_keyframe)
2964 keyframe = found_keyframe =
2965 !(sample_flags & (MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC |
2966 MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES));
2967 if (keyframe)
2968 distance = 0;
2969 av_add_index_entry(st, offset, dts, sample_size, distance,
2970 keyframe ? AVINDEX_KEYFRAME : 0);
2971 av_dlog(c->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
2972 "size %d, distance %d, keyframe %d\n", st->index, sc->sample_count+i,
2973 offset, dts, sample_size, distance, keyframe);
2974 distance++;
2975 dts += sample_duration;
2976 offset += sample_size;
2977 sc->data_size += sample_size;
2978 }
2979
2980 if (pb->eof_reached)
2981 return AVERROR_EOF;
2982
2983 frag->moof_offset = offset;
2984 st->duration = sc->track_end = dts + sc->time_offset;
2985 return 0;
2986}
2987
2988/* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
2989/* like the files created with Adobe Premiere 5.0, for samples see */
2990/* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
2991static int mov_read_wide(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2992{
2993 int err;
2994
2995 if (atom.size < 8)
2996 return 0; /* continue */
2997 if (avio_rb32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
2998 avio_skip(pb, atom.size - 4);
2999 return 0;
3000 }
3001 atom.type = avio_rl32(pb);
3002 atom.size -= 8;
3003 if (atom.type != MKTAG('m','d','a','t')) {
3004 avio_skip(pb, atom.size);
3005 return 0;
3006 }
3007 err = mov_read_mdat(c, pb, atom);
3008 return err;
3009}
3010
3011static int mov_read_cmov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3012{
3013#if CONFIG_ZLIB
3014 AVIOContext ctx;
3015 uint8_t *cmov_data;
3016 uint8_t *moov_data; /* uncompressed data */
3017 long cmov_len, moov_len;
3018 int ret = -1;
3019
3020 avio_rb32(pb); /* dcom atom */
3021 if (avio_rl32(pb) != MKTAG('d','c','o','m'))
3022 return AVERROR_INVALIDDATA;
3023 if (avio_rl32(pb) != MKTAG('z','l','i','b')) {
3024 av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !\n");
3025 return AVERROR_INVALIDDATA;
3026 }
3027 avio_rb32(pb); /* cmvd atom */
3028 if (avio_rl32(pb) != MKTAG('c','m','v','d'))
3029 return AVERROR_INVALIDDATA;
3030 moov_len = avio_rb32(pb); /* uncompressed size */
3031 cmov_len = atom.size - 6 * 4;
3032
3033 cmov_data = av_malloc(cmov_len);
3034 if (!cmov_data)
3035 return AVERROR(ENOMEM);
3036 moov_data = av_malloc(moov_len);
3037 if (!moov_data) {
3038 av_free(cmov_data);
3039 return AVERROR(ENOMEM);
3040 }
3041 avio_read(pb, cmov_data, cmov_len);
3042 if (uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
3043 goto free_and_return;
3044 if (ffio_init_context(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
3045 goto free_and_return;
3046 atom.type = MKTAG('m','o','o','v');
3047 atom.size = moov_len;
3048 ret = mov_read_default(c, &ctx, atom);
3049free_and_return:
3050 av_free(moov_data);
3051 av_free(cmov_data);
3052 return ret;
3053#else
3054 av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
3055 return AVERROR(ENOSYS);
3056#endif
3057}
3058
3059/* edit list atom */
3060static int mov_read_elst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3061{
3062 MOVStreamContext *sc;
3063 int i, edit_count, version, edit_start_index = 0;
3064 int unsupported = 0;
3065
3066 if (c->fc->nb_streams < 1 || c->ignore_editlist)
3067 return 0;
3068 sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
3069
3070 version = avio_r8(pb); /* version */
3071 avio_rb24(pb); /* flags */
3072 edit_count = avio_rb32(pb); /* entries */
3073
3074 if ((uint64_t)edit_count*12+8 > atom.size)
3075 return AVERROR_INVALIDDATA;
3076
3077 av_dlog(c->fc, "track[%i].edit_count = %i\n", c->fc->nb_streams-1, edit_count);
3078 for (i=0; i<edit_count; i++){
3079 int64_t time;
3080 int64_t duration;
3081 int rate;
3082 if (version == 1) {
3083 duration = avio_rb64(pb);
3084 time = avio_rb64(pb);
3085 } else {
3086 duration = avio_rb32(pb); /* segment duration */
3087 time = (int32_t)avio_rb32(pb); /* media time */
3088 }
3089 rate = avio_rb32(pb);
3090 if (i == 0 && time == -1) {
3091 sc->empty_duration = duration;
3092 edit_start_index = 1;
3093 } else if (i == edit_start_index && time >= 0)
3094 sc->start_time = time;
3095 else
3096 unsupported = 1;
3097
3098 av_dlog(c->fc, "duration=%"PRId64" time=%"PRId64" rate=%f\n",
3099 duration, time, rate / 65536.0);
3100 }
3101
3102 if (unsupported)
3103 av_log(c->fc, AV_LOG_WARNING, "multiple edit list entries, "
3104 "a/v desync might occur, patch welcome\n");
3105
3106 return 0;
3107}
3108
3109static int mov_read_tmcd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3110{
3111 MOVStreamContext *sc;
3112
3113 if (c->fc->nb_streams < 1)
3114 return AVERROR_INVALIDDATA;
3115 sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
3116 sc->timecode_track = avio_rb32(pb);
3117 return 0;
3118}
3119
3120static int mov_read_uuid(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3121{
3122 int ret;
3123 uint8_t uuid[16];
3124 static const uint8_t uuid_isml_manifest[] = {
3125 0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd,
3126 0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66
3127 };
3128
3129 if (atom.size < sizeof(uuid) || atom.size == INT64_MAX)
3130 return AVERROR_INVALIDDATA;
3131
3132 ret = avio_read(pb, uuid, sizeof(uuid));
3133 if (ret < 0) {
3134 return ret;
3135 } else if (ret != sizeof(uuid)) {
3136 return AVERROR_INVALIDDATA;
3137 }
3138 if (!memcmp(uuid, uuid_isml_manifest, sizeof(uuid))) {
3139 uint8_t *buffer, *ptr;
3140 char *endptr;
3141 size_t len = atom.size - sizeof(uuid);
3142
3143 if (len < 4) {
3144 return AVERROR_INVALIDDATA;
3145 }
3146 ret = avio_skip(pb, 4); // zeroes
3147 len -= 4;
3148
3149 buffer = av_mallocz(len + 1);
3150 if (!buffer) {
3151 return AVERROR(ENOMEM);
3152 }
3153 ret = avio_read(pb, buffer, len);
3154 if (ret < 0) {
3155 av_free(buffer);
3156 return ret;
3157 } else if (ret != len) {
3158 av_free(buffer);
3159 return AVERROR_INVALIDDATA;
3160 }
3161
3162 ptr = buffer;
3163 while ((ptr = av_stristr(ptr, "systemBitrate=\"")) != NULL) {
3164 ptr += sizeof("systemBitrate=\"") - 1;
3165 c->bitrates_count++;
3166 c->bitrates = av_realloc_f(c->bitrates, c->bitrates_count, sizeof(*c->bitrates));
3167 if (!c->bitrates) {
3168 c->bitrates_count = 0;
3169 av_free(buffer);
3170 return AVERROR(ENOMEM);
3171 }
3172 errno = 0;
3173 ret = strtol(ptr, &endptr, 10);
3174 if (ret < 0 || errno || *endptr != '"') {
3175 c->bitrates[c->bitrates_count - 1] = 0;
3176 } else {
3177 c->bitrates[c->bitrates_count - 1] = ret;
3178 }
3179 }
3180
3181 av_free(buffer);
3182 }
3183 return 0;
3184}
3185
3186static void mov_id32_date2year(AVDictionary **m)
3187{
3188 AVDictionaryEntry *t;
3189 if (t = av_dict_get(*m, "date", t, AV_DICT_MATCH_CASE)) {
3190 av_dict_set(m, "year", t->value, 0);
3191 av_log(NULL, AV_LOG_INFO, "[%s:%d]========date:%s\n", __FUNCTION__, __LINE__, t->value);
3192 }
3193}
3194
3195static int mov_read_id32(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3196{
3197 uint8_t version;
3198 uint32_t flags;
3199 uint8_t pad;
3200 uint16_t langcode;
3201 uint16_t shortbytes;
3202 char language[4] = {0};
3203 uint32_t str_size;
3204 AVFormatContext *s = c->fc;
3205 ID3v2ExtraMeta *id3v2_extra_meta = NULL;
3206
3207 str_size = atom.size;
3208 version = avio_r8(pb); // version
3209 flags = avio_rb24(pb); //flags
3210 shortbytes = avio_rb16(pb);
3211 pad = (shortbytes & 0x8000) >> 15; //pad
3212 langcode = shortbytes & 0x7ffff; //language
3213 ff_mov_lang_to_iso639(langcode, language);
3214 str_size -= 6;
3215 ff_id3v2_read(s, ID3v2_DEFAULT_MAGIC, &id3v2_extra_meta);
3216 if (id3v2_extra_meta) {
3217 int err = ff_id3v2_parse_apic(s, &id3v2_extra_meta);
3218 if (err < 0) {
3219 av_log(NULL, AV_LOG_INFO, "[%s:%d]ff_id3v2_parse_apic err:%d\n", __FUNCTION__, __LINE__, err);
3220 return err;
3221 }
3222 }
3223 ff_id3v2_free_extra_meta(&id3v2_extra_meta);
3224 mov_id32_date2year(&s->metadata);
3225
3226 return 0;
3227}
3228
3229static const MOVParseTableEntry mov_default_parse_table[] = {
3230{ MKTAG('A','C','L','R'), mov_read_avid },
3231{ MKTAG('A','P','R','G'), mov_read_avid },
3232{ MKTAG('A','A','L','P'), mov_read_avid },
3233{ MKTAG('A','R','E','S'), mov_read_ares },
3234{ MKTAG('a','v','s','s'), mov_read_avss },
3235{ MKTAG('c','h','p','l'), mov_read_chpl },
3236{ MKTAG('c','o','6','4'), mov_read_stco },
3237{ MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
3238{ MKTAG('d','i','n','f'), mov_read_default },
3239{ MKTAG('d','r','e','f'), mov_read_dref },
3240{ MKTAG('e','d','t','s'), mov_read_default },
3241{ MKTAG('e','l','s','t'), mov_read_elst },
3242{ MKTAG('e','n','d','a'), mov_read_enda },
3243{ MKTAG('f','i','e','l'), mov_read_fiel },
3244{ MKTAG('f','t','y','p'), mov_read_ftyp },
3245{ MKTAG('g','l','b','l'), mov_read_glbl },
3246{ MKTAG('h','d','l','r'), mov_read_hdlr },
3247{ MKTAG('i','l','s','t'), mov_read_ilst },
3248{ MKTAG('j','p','2','h'), mov_read_jp2h },
3249{ MKTAG('m','d','a','t'), mov_read_mdat },
3250{ MKTAG('m','d','h','d'), mov_read_mdhd },
3251{ MKTAG('m','d','i','a'), mov_read_default },
3252{ MKTAG('m','e','t','a'), mov_read_meta },
3253{ MKTAG('m','i','n','f'), mov_read_default },
3254{ MKTAG('m','o','o','f'), mov_read_moof },
3255{ MKTAG('m','o','o','v'), mov_read_moov },
3256{ MKTAG('m','v','e','x'), mov_read_default },
3257{ MKTAG('m','v','h','d'), mov_read_mvhd },
3258{ MKTAG('S','M','I',' '), mov_read_svq3 },
3259{ MKTAG('a','l','a','c'), mov_read_alac }, /* alac specific atom */
3260{ MKTAG('a','v','c','C'), mov_read_glbl },
3261{ MKTAG('p','a','s','p'), mov_read_pasp },
3262{ MKTAG('s','t','b','l'), mov_read_default },
3263{ MKTAG('s','t','c','o'), mov_read_stco },
3264{ MKTAG('s','t','p','s'), mov_read_stps },
3265{ MKTAG('s','t','r','f'), mov_read_strf },
3266{ MKTAG('s','t','s','c'), mov_read_stsc },
3267{ MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
3268{ MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
3269{ MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
3270{ MKTAG('s','t','t','s'), mov_read_stts },
3271{ MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */
3272{ MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
3273{ MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
3274{ MKTAG('t','r','a','k'), mov_read_trak },
3275{ MKTAG('t','r','a','f'), mov_read_default },
3276{ MKTAG('t','r','e','f'), mov_read_default },
3277{ MKTAG('t','m','c','d'), mov_read_tmcd },
3278{ MKTAG('c','h','a','p'), mov_read_chap },
3279{ MKTAG('t','r','e','x'), mov_read_trex },
3280{ MKTAG('t','r','u','n'), mov_read_trun },
3281{ MKTAG('u','d','t','a'), mov_read_default },
3282{ MKTAG('w','a','v','e'), mov_read_wave },
3283{ MKTAG('e','s','d','s'), mov_read_esds },
3284{ MKTAG('d','a','c','3'), mov_read_dac3 }, /* AC-3 info */
3285{ MKTAG('d','e','c','3'), mov_read_dec3 }, /* EAC-3 info */
3286{ MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
3287{ MKTAG('w','f','e','x'), mov_read_wfex },
3288{ MKTAG('c','m','o','v'), mov_read_cmov },
3289{ MKTAG('c','h','a','n'), mov_read_chan }, /* channel layout */
3290{ MKTAG('d','v','c','1'), mov_read_dvc1 },
3291{ MKTAG('s','b','g','p'), mov_read_sbgp },
3292{ MKTAG('h','v','c','C'), mov_read_glbl },
3293{ MKTAG('u','u','i','d'), mov_read_uuid },
3294{ MKTAG('C','i','n', 0x8e), mov_read_targa_y216 },
3295{ MKTAG('I','D','3','2'), mov_read_id32 },
3296
3297{ 0, NULL }
3298};
3299
3300static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3301{
3302 int64_t total_size = 0;
3303 MOVAtom a;
3304 int i;
3305
3306 if (atom.size < 0)
3307 atom.size = INT64_MAX;
3308 while (total_size + 8 <= atom.size && !url_feof(pb)) {
3309 int (*parse)(MOVContext*, AVIOContext*, MOVAtom) = NULL;
3310 a.size = atom.size;
3311 a.type=0;
3312 if (atom.size >= 8) {
3313 a.size = avio_rb32(pb);
3314 a.type = avio_rl32(pb);
3315 if (atom.type != MKTAG('r','o','o','t') &&
3316 atom.type != MKTAG('m','o','o','v'))
3317 {
3318 if (a.type == MKTAG('t','r','a','k') || a.type == MKTAG('m','d','a','t'))
3319 {
3320 av_log(c->fc, AV_LOG_ERROR, "Broken file, trak/mdat not at top-level\n");
3321 avio_skip(pb, -8);
3322 return 0;
3323 }
3324 }
3325 total_size += 8;
3326 if (a.size == 1) { /* 64 bit extended size */
3327 a.size = avio_rb64(pb) - 8;
3328 total_size += 8;
3329 }
3330 }
3331 av_dlog(c->fc, "type: %08x '%.4s' parent:'%.4s' sz: %"PRId64" %"PRId64" %"PRId64"\n",
3332 a.type, (char*)&a.type, (char*)&atom.type, a.size, total_size, atom.size);
3333 if (a.size == 0) {
3334 a.size = atom.size - total_size + 8;
3335 }
3336 a.size -= 8;
3337 if (a.size < 0)
3338 break;
3339 a.size = FFMIN(a.size, atom.size - total_size);
3340
3341 for (i = 0; mov_default_parse_table[i].type; i++)
3342 if (mov_default_parse_table[i].type == a.type) {
3343 parse = mov_default_parse_table[i].parse;
3344 break;
3345 }
3346
3347 // container is user data
3348 if (!parse && (atom.type == MKTAG('u','d','t','a') ||
3349 atom.type == MKTAG('i','l','s','t')))
3350 parse = mov_read_udta_string;
3351
3352 // Supports parsing the QuickTime Metadata Keys.
3353 // https://developer.apple.com/library/mac/documentation/QuickTime/QTFF/Metadata/Metadata.html
3354 if (!parse && c->found_hdlr_mdta &&
3355 atom.type == MKTAG('m','e','t','a') &&
3356 a.type == MKTAG('k','e','y','s')) {
3357 parse = mov_read_keys;
3358 }
3359
3360 if (!parse) { /* skip leaf atoms data */
3361 avio_skip(pb, a.size);
3362 } else {
3363 int64_t start_pos = avio_tell(pb);
3364 int64_t left;
3365 int err = parse(c, pb, a);
3366 if (err < 0)
3367 return err;
3368 if (c->found_moov && c->found_mdat &&
3369 ((!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX) ||
3370 start_pos + a.size == avio_size(pb))) {
3371 if (!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX)
3372 c->next_root_atom = start_pos + a.size;
3373 return 0;
3374 }
3375 left = a.size - avio_tell(pb) + start_pos;
3376 if (left > 0) /* skip garbage at atom end */
3377 avio_skip(pb, left);
3378 else if (left < 0) {
3379 av_log(c->fc, AV_LOG_WARNING,
3380 "overread end of atom '%.4s' by %"PRId64" bytes\n",
3381 (char*)&a.type, -left);
3382 avio_seek(pb, left, SEEK_CUR);
3383 }
3384 }
3385
3386 total_size += a.size;
3387 }
3388
3389 if (total_size < atom.size && atom.size < 0x7ffff)
3390 avio_skip(pb, atom.size - total_size);
3391
3392 return 0;
3393}
3394
3395static int mov_probe(AVProbeData *p)
3396{
3397 int64_t offset;
3398 uint32_t tag;
3399 int score = 0;
3400 int moov_offset = -1;
3401
3402 /* check file header */
3403 offset = 0;
3404 for (;;) {
3405 /* ignore invalid offset */
3406 if ((offset + 8) > p->buf_size)
3407 break;
3408 tag = AV_RL32(p->buf + offset + 4);
3409 switch(tag) {
3410 /* check for obvious tags */
3411 case MKTAG('m','o','o','v'):
3412 moov_offset = offset + 4;
3413 case MKTAG('j','P',' ',' '): /* jpeg 2000 signature */
3414 case MKTAG('m','d','a','t'):
3415 case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
3416 case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
3417 case MKTAG('f','t','y','p'):
3418 if (AV_RB32(p->buf+offset) < 8 &&
3419 (AV_RB32(p->buf+offset) != 1 ||
3420 offset + 12 > (unsigned int)p->buf_size ||
3421 AV_RB64(p->buf+offset + 8) == 0)) {
3422 score = FFMAX(score, AVPROBE_SCORE_EXTENSION);
3423 } else {
3424 score = AVPROBE_SCORE_MAX;
3425 }
3426 offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
3427 break;
3428 /* those are more common words, so rate then a bit less */
3429 case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
3430 case MKTAG('w','i','d','e'):
3431 case MKTAG('f','r','e','e'):
3432 case MKTAG('j','u','n','k'):
3433 case MKTAG('p','i','c','t'):
3434 score = FFMAX(score, AVPROBE_SCORE_MAX - 5);
3435 offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
3436 break;
3437 case MKTAG(0x82,0x82,0x7f,0x7d):
3438 case MKTAG('s','k','i','p'):
3439 case MKTAG('u','u','i','d'):
3440 case MKTAG('p','r','f','l'):
3441 /* if we only find those cause probedata is too small at least rate them */
3442 score = FFMAX(score, AVPROBE_SCORE_EXTENSION);
3443 offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
3444 break;
3445 default:
3446 offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
3447 }
3448 }
3449 if(score > AVPROBE_SCORE_MAX - 50 && moov_offset != -1) {
3450 /* moov atom in the header - we should make sure that this is not a
3451 * MOV-packed MPEG-PS */
3452 offset = moov_offset;
3453
3454 while(offset < (p->buf_size - 16)){ /* Sufficient space */
3455 /* We found an actual hdlr atom */
3456 if(AV_RL32(p->buf + offset ) == MKTAG('h','d','l','r') &&
3457 AV_RL32(p->buf + offset + 8) == MKTAG('m','h','l','r') &&
3458 AV_RL32(p->buf + offset + 12) == MKTAG('M','P','E','G')){
3459 av_log(NULL, AV_LOG_WARNING, "Found media data tag MPEG indicating this is a MOV-packed MPEG-PS.\n");
3460 /* We found a media handler reference atom describing an
3461 * MPEG-PS-in-MOV, return a
3462 * low score to force expanding the probe window until
3463 * mpegps_probe finds what it needs */
3464 return 5;
3465 }else
3466 /* Keep looking */
3467 offset+=2;
3468 }
3469 }
3470
3471 return score;
3472}
3473
3474// must be done after parsing all trak because there's no order requirement
3475static void mov_read_chapters(AVFormatContext *s)
3476{
3477 MOVContext *mov = s->priv_data;
3478 AVStream *st = NULL;
3479 MOVStreamContext *sc;
3480 int64_t cur_pos;
3481 int i;
3482
3483 for (i = 0; i < s->nb_streams; i++)
3484 if (s->streams[i]->id == mov->chapter_track) {
3485 st = s->streams[i];
3486 break;
3487 }
3488 if (!st) {
3489 av_log(s, AV_LOG_ERROR, "Referenced QT chapter track not found\n");
3490 return;
3491 }
3492
3493 st->discard = AVDISCARD_ALL;
3494 sc = st->priv_data;
3495 cur_pos = avio_tell(sc->pb);
3496
3497 for (i = 0; i < st->nb_index_entries; i++) {
3498 AVIndexEntry *sample = &st->index_entries[i];
3499 int64_t end = i+1 < st->nb_index_entries ? st->index_entries[i+1].timestamp : st->duration;
3500 uint8_t *title;
3501 uint16_t ch;
3502 int len, title_len;
3503
3504 if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
3505 av_log(s, AV_LOG_ERROR, "Chapter %d not found in file\n", i);
3506 goto finish;
3507 }
3508
3509 // the first two bytes are the length of the title
3510 len = avio_rb16(sc->pb);
3511 if (len > sample->size-2)
3512 continue;
3513 title_len = 2*len + 1;
3514 if (!(title = av_mallocz(title_len)))
3515 goto finish;
3516
3517 // The samples could theoretically be in any encoding if there's an encd
3518 // atom following, but in practice are only utf-8 or utf-16, distinguished
3519 // instead by the presence of a BOM
3520 if (!len) {
3521 title[0] = 0;
3522 } else {
3523 ch = avio_rb16(sc->pb);
3524 if (ch == 0xfeff)
3525 avio_get_str16be(sc->pb, len, title, title_len);
3526 else if (ch == 0xfffe)
3527 avio_get_str16le(sc->pb, len, title, title_len);
3528 else {
3529 AV_WB16(title, ch);
3530 if (len == 1 || len == 2)
3531 title[len] = 0;
3532 else
3533 avio_get_str(sc->pb, INT_MAX, title + 2, len - 1);
3534 }
3535 }
3536
3537 avpriv_new_chapter(s, i, st->time_base, sample->timestamp, end, title);
3538 av_freep(&title);
3539 }
3540finish:
3541 avio_seek(sc->pb, cur_pos, SEEK_SET);
3542}
3543
3544static int parse_timecode_in_framenum_format(AVFormatContext *s, AVStream *st,
3545 uint32_t value, int flags)
3546{
3547 AVTimecode tc;
3548 char buf[AV_TIMECODE_STR_SIZE];
3549 AVRational rate = {st->codec->time_base.den,
3550 st->codec->time_base.num};
3551 int ret = av_timecode_init(&tc, rate, flags, 0, s);
3552 if (ret < 0)
3553 return ret;
3554 av_dict_set(&st->metadata, "timecode",
3555 av_timecode_make_string(&tc, buf, value), 0);
3556 return 0;
3557}
3558
3559static int mov_read_timecode_track(AVFormatContext *s, AVStream *st)
3560{
3561 MOVStreamContext *sc = st->priv_data;
3562 int flags = 0;
3563 int64_t cur_pos = avio_tell(sc->pb);
3564 uint32_t value;
3565
3566 if (!st->nb_index_entries)
3567 return -1;
3568
3569 avio_seek(sc->pb, st->index_entries->pos, SEEK_SET);
3570 value = avio_rb32(s->pb);
3571
3572 if (sc->tmcd_flags & 0x0001) flags |= AV_TIMECODE_FLAG_DROPFRAME;
3573 if (sc->tmcd_flags & 0x0002) flags |= AV_TIMECODE_FLAG_24HOURSMAX;
3574 if (sc->tmcd_flags & 0x0004) flags |= AV_TIMECODE_FLAG_ALLOWNEGATIVE;
3575
3576 /* Assume Counter flag is set to 1 in tmcd track (even though it is likely
3577 * not the case) and thus assume "frame number format" instead of QT one.
3578 * No sample with tmcd track can be found with a QT timecode at the moment,
3579 * despite what the tmcd track "suggests" (Counter flag set to 0 means QT
3580 * format). */
3581 parse_timecode_in_framenum_format(s, st, value, flags);
3582
3583 avio_seek(sc->pb, cur_pos, SEEK_SET);
3584 return 0;
3585}
3586
3587static int mov_read_close(AVFormatContext *s)
3588{
3589 MOVContext *mov = s->priv_data;
3590 int i, j;
3591
3592 for (i = 0; i < s->nb_streams; i++) {
3593 AVStream *st = s->streams[i];
3594 MOVStreamContext *sc = st->priv_data;
3595
3596 av_freep(&sc->ctts_data);
3597 for (j = 0; j < sc->drefs_count; j++) {
3598 av_freep(&sc->drefs[j].path);
3599 av_freep(&sc->drefs[j].dir);
3600 }
3601 av_freep(&sc->drefs);
3602 if (!sc->pb_is_copied)
3603 avio_close(sc->pb);
3604 sc->pb = NULL;
3605 av_freep(&sc->chunk_offsets);
3606 av_freep(&sc->keyframes);
3607 av_freep(&sc->sample_sizes);
3608 av_freep(&sc->stps_data);
3609 av_freep(&sc->stsc_data);
3610 av_freep(&sc->stts_data);
3611 }
3612
3613 if (mov->dv_demux) {
3614 for (i = 0; i < mov->dv_fctx->nb_streams; i++) {
3615 av_freep(&mov->dv_fctx->streams[i]->codec);
3616 av_freep(&mov->dv_fctx->streams[i]);
3617 }
3618 av_freep(&mov->dv_fctx);
3619 av_freep(&mov->dv_demux);
3620 }
3621
3622 if (mov->meta_keys) {
3623 for (i = 1; i < mov->meta_keys_count; i++) {
3624 av_freep(&mov->meta_keys[i]);
3625 }
3626 av_freep(&mov->meta_keys);
3627 }
3628
3629 av_freep(&mov->trex_data);
3630 av_freep(&mov->bitrates);
3631
3632 return 0;
3633}
3634
3635static int tmcd_is_referenced(AVFormatContext *s, int tmcd_id)
3636{
3637 int i;
3638
3639 for (i = 0; i < s->nb_streams; i++) {
3640 AVStream *st = s->streams[i];
3641 MOVStreamContext *sc = st->priv_data;
3642
3643 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
3644 sc->timecode_track == tmcd_id)
3645 return 1;
3646 }
3647 return 0;
3648}
3649
3650/* look for a tmcd track not referenced by any video track, and export it globally */
3651static void export_orphan_timecode(AVFormatContext *s)
3652{
3653 int i;
3654
3655 for (i = 0; i < s->nb_streams; i++) {
3656 AVStream *st = s->streams[i];
3657
3658 if (st->codec->codec_tag == MKTAG('t','m','c','d') &&
3659 !tmcd_is_referenced(s, i + 1)) {
3660 AVDictionaryEntry *tcr = av_dict_get(st->metadata, "timecode", NULL, 0);
3661 if (tcr) {
3662 av_dict_set(&s->metadata, "timecode", tcr->value, 0);
3663 break;
3664 }
3665 }
3666 }
3667}
3668
3669static int mov_read_header(AVFormatContext *s)
3670{
3671 MOVContext *mov = s->priv_data;
3672 AVIOContext *pb = s->pb;
3673 int i, j, err;
3674 MOVAtom atom = { AV_RL32("root") };
3675
3676 mov->fc = s;
3677 mov->trak_index = -1;
3678 /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
3679 if (pb->seekable)
3680 atom.size = avio_size(pb);
3681 else
3682 atom.size = INT64_MAX;
3683
3684 /* check MOV header */
3685 if ((err = mov_read_default(mov, pb, atom)) < 0) {
3686 av_log(s, AV_LOG_ERROR, "error reading header: %d\n", err);
3687 mov_read_close(s);
3688 return err;
3689 }
3690 if (!mov->found_moov) {
3691 av_log(s, AV_LOG_ERROR, "moov atom not found\n");
3692 mov_read_close(s);
3693 return AVERROR_INVALIDDATA;
3694 }
3695 av_dlog(mov->fc, "on_parse_exit_offset=%"PRId64"\n", avio_tell(pb));
3696
3697 if (pb->seekable) {
3698 if (mov->chapter_track > 0)
3699 mov_read_chapters(s);
3700 for (i = 0; i < s->nb_streams; i++)
3701 if (s->streams[i]->codec->codec_tag == AV_RL32("tmcd"))
3702 mov_read_timecode_track(s, s->streams[i]);
3703 }
3704
3705 /* copy timecode metadata from tmcd tracks to the related video streams */
3706 for (i = 0; i < s->nb_streams; i++) {
3707 AVStream *st = s->streams[i];
3708 MOVStreamContext *sc = st->priv_data;
3709 if (sc->timecode_track > 0) {
3710 AVDictionaryEntry *tcr;
3711 int tmcd_st_id = -1;
3712
3713 for (j = 0; j < s->nb_streams; j++)
3714 if (s->streams[j]->id == sc->timecode_track)
3715 tmcd_st_id = j;
3716
3717 if (tmcd_st_id < 0 || tmcd_st_id == i)
3718 continue;
3719 tcr = av_dict_get(s->streams[tmcd_st_id]->metadata, "timecode", NULL, 0);
3720 if (tcr)
3721 av_dict_set(&st->metadata, "timecode", tcr->value, 0);
3722 }
3723 }
3724 export_orphan_timecode(s);
3725
3726 for (i = 0; i < s->nb_streams; i++) {
3727 AVStream *st = s->streams[i];
3728 MOVStreamContext *sc = st->priv_data;
3729 fix_timescale(mov, sc);
3730 if(st->codec->codec_type == AVMEDIA_TYPE_AUDIO && st->codec->codec_id == AV_CODEC_ID_AAC) {
3731 st->skip_samples = sc->start_pad;
3732 }
3733 }
3734
3735 if (mov->trex_data) {
3736 for (i = 0; i < s->nb_streams; i++) {
3737 AVStream *st = s->streams[i];
3738 MOVStreamContext *sc = st->priv_data;
3739 if (st->duration > 0)
3740 st->codec->bit_rate = sc->data_size * 8 * sc->time_scale / st->duration;
3741 }
3742 }
3743
3744 for (i = 0; i < mov->bitrates_count && i < s->nb_streams; i++) {
3745 if (mov->bitrates[i]) {
3746 s->streams[i]->codec->bit_rate = mov->bitrates[i];
3747 }
3748 }
3749
3750 return 0;
3751}
3752
3753static AVIndexEntry *mov_find_next_sample(AVFormatContext *s, AVStream **st)
3754{
3755 AVIndexEntry *sample = NULL;
3756 int64_t best_dts = INT64_MAX;
3757 int i;
3758 for (i = 0; i < s->nb_streams; i++) {
3759 AVStream *avst = s->streams[i];
3760 MOVStreamContext *msc = avst->priv_data;
3761 if (msc->pb && msc->current_sample < avst->nb_index_entries) {
3762 AVIndexEntry *current_sample = &avst->index_entries[msc->current_sample];
3763 int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale);
3764 av_dlog(s, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
3765 if (!sample || (!s->pb->seekable && current_sample->pos < sample->pos) ||
3766 (s->pb->seekable &&
3767 ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb &&
3768 ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
3769 (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
3770 sample = current_sample;
3771 best_dts = dts;
3772 *st = avst;
3773 }
3774 }
3775 }
3776 return sample;
3777}
3778
3779static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
3780{
3781 MOVContext *mov = s->priv_data;
3782 MOVStreamContext *sc;
3783 AVIndexEntry *sample;
3784 AVStream *st = NULL;
3785 int ret;
3786 mov->fc = s;
3787 retry:
3788 sample = mov_find_next_sample(s, &st);
3789 if (!sample) {
3790 mov->found_mdat = 0;
3791 if (!mov->next_root_atom)
3792 return AVERROR_EOF;
3793 avio_seek(s->pb, mov->next_root_atom, SEEK_SET);
3794 mov->next_root_atom = 0;
3795 if (mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX }) < 0 ||
3796 url_feof(s->pb))
3797 return AVERROR_EOF;
3798 av_dlog(s, "read fragments, offset 0x%"PRIx64"\n", avio_tell(s->pb));
3799 goto retry;
3800 }
3801 sc = st->priv_data;
3802 /* must be done just before reading, to avoid infinite loop on sample */
3803 sc->current_sample++;
3804
3805 if (mov->next_root_atom) {
3806 sample->pos = FFMIN(sample->pos, mov->next_root_atom);
3807 sample->size = FFMIN(sample->size, (mov->next_root_atom - sample->pos));
3808 }
3809
3810 if (st->discard != AVDISCARD_ALL) {
3811 if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
3812 av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
3813 sc->ffindex, sample->pos);
3814 return AVERROR_INVALIDDATA;
3815 }
3816 ret = av_get_packet(sc->pb, pkt, sample->size);
3817 if (ret < 0)
3818 return ret;
3819 if (sc->has_palette) {
3820 uint8_t *pal;
3821
3822 pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
3823 if (!pal) {
3824 av_log(mov->fc, AV_LOG_ERROR, "Cannot append palette to packet\n");
3825 } else {
3826 memcpy(pal, sc->palette, AVPALETTE_SIZE);
3827 sc->has_palette = 0;
3828 }
3829 }
3830#if CONFIG_DV_DEMUXER
3831 if (mov->dv_demux && sc->dv_audio_container) {
3832 avpriv_dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size, pkt->pos);
3833 av_free(pkt->data);
3834 pkt->size = 0;
3835 ret = avpriv_dv_get_packet(mov->dv_demux, pkt);
3836 if (ret < 0)
3837 return ret;
3838 }
3839#endif
3840 }
3841
3842 pkt->stream_index = sc->ffindex;
3843 pkt->dts = sample->timestamp;
3844 if (sc->ctts_data && sc->ctts_index < sc->ctts_count) {
3845 pkt->pts = pkt->dts + sc->dts_shift + sc->ctts_data[sc->ctts_index].duration;
3846 /* update ctts context */
3847 sc->ctts_sample++;
3848 if (sc->ctts_index < sc->ctts_count &&
3849 sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
3850 sc->ctts_index++;
3851 sc->ctts_sample = 0;
3852 }
3853 if (sc->wrong_dts)
3854 pkt->dts = AV_NOPTS_VALUE;
3855 } else {
3856 int64_t next_dts = (sc->current_sample < st->nb_index_entries) ?
3857 st->index_entries[sc->current_sample].timestamp : st->duration;
3858 pkt->duration = next_dts - pkt->dts;
3859 pkt->pts = pkt->dts;
3860 }
3861 if (st->discard == AVDISCARD_ALL)
3862 goto retry;
3863 pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? AV_PKT_FLAG_KEY : 0;
3864 pkt->pos = sample->pos;
3865 av_dlog(s, "stream %d, pts %"PRId64", dts %"PRId64", pos 0x%"PRIx64", duration %d\n",
3866 pkt->stream_index, pkt->pts, pkt->dts, pkt->pos, pkt->duration);
3867 return 0;
3868}
3869
3870
3871static int64_t mov_read_seek_sync(AVFormatContext *s,
3872 int stream_index,
3873 int64_t min_ts,
3874 int64_t target_ts,
3875 int64_t max_ts,
3876 int flags)
3877{
3878 int64_t pos, t_pos;
3879
3880 int64_t ts_ret, ts_adj;
3881 int stream_index_gen_search = stream_index;
3882 int sample, i;
3883 AVStream *st;
3884 AVParserState *backup;
3885
3886 backup = ff_store_parser_state(s);
3887
3888 // detect direction of seeking for search purposes
3889 flags |= (target_ts - min_ts > (uint64_t)(max_ts - target_ts)) ?
3890 AVSEEK_FLAG_BACKWARD : 0;
3891
3892 st = s->streams[stream_index_gen_search];
3893 sample = av_index_search_timestamp(st, target_ts, AVSEEK_FLAG_ANY);
3894 pos = st->index_entries[sample].pos;
3895 target_ts = st->index_entries[sample].timestamp;
3896 for (i = 0; i < s->nb_streams; i++) {
3897 MOVStreamContext *sc = s->streams[i]->priv_data;
3898 sc->current_sample = (sample - 500) > 0 ? (sample - 500) : 0; // hard code for mov, repos the sample.
3899 }
3900
3901 // search for actual matching keyframe/starting position for all streams
3902 if ((t_pos = ff_gen_syncpoint_search(s, stream_index, pos,
3903 min_ts, target_ts, max_ts,
3904 flags)) < 0) {
3905 ff_restore_parser_state(s, backup);
3906 return -1;
3907 }
3908
3909 ff_free_parser_state(s, backup);
3910 return t_pos;
3911}
3912
3913static int64_t mov_read_seek2(AVFormatContext *s, int stream_index, int64_t target_ts, int flags){
3914 int ret;
3915 if (flags & AVSEEK_FLAG_BACKWARD) {
3916 flags &= ~AVSEEK_FLAG_BACKWARD;
3917 ret = mov_read_seek_sync(s, stream_index, INT64_MIN, target_ts, target_ts, flags);
3918 if (ret < 0) {
3919 // for compatibility reasons, seek to the best-fitting timestamp
3920 ret = mov_read_seek_sync(s, stream_index, INT64_MIN, target_ts, INT64_MAX, flags);
3921 }
3922 } else {
3923 ret = mov_read_seek_sync(s, stream_index, target_ts, target_ts, INT64_MAX, flags);
3924 if (ret < 0)
3925 // for compatibility reasons, seek to the best-fitting timestamp
3926 ret = mov_read_seek_sync(s, stream_index, INT64_MIN, target_ts, INT64_MAX, flags);
3927 }
3928 return ret;
3929}
3930
3931static int mov_index_search_pos(const AVIndexEntry *entries, int nb_entries,
3932 int64_t pos, int flags)
3933{
3934 int a, b, m;
3935 int64_t ppos;
3936
3937 a = - 1;
3938 b = nb_entries;
3939
3940 //optimize appending index entries at the end
3941 if(b && entries[b-1].pos < pos)
3942 a= b-1;
3943
3944 while (b - a > 1) {
3945 m = (a + b) >> 1;
3946 ppos = entries[m].pos;
3947 if(ppos >= pos)
3948 b = m;
3949 if(ppos <= pos)
3950 a = m;
3951 }
3952
3953 m= (flags & AVSEEK_FLAG_BACKWARD) ? a : b;
3954 return m;
3955}
3956
3957static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp, int flags)
3958{
3959 MOVStreamContext *sc = st->priv_data;
3960 int sample, time_sample;
3961 int i;
3962
3963 sample = av_index_search_timestamp(st, timestamp, flags);
3964
3965 // mov's stss is wrong sometimes, need to read seek
3966 // added by senbai.tao
3967 if(st->codec->codec_type == AVMEDIA_TYPE_VIDEO && sample <=0 && st->nb_index_entries && sc->keyframe_count <= 1) {
3968 int64_t sync_point = mov_read_seek2(s, st->index, timestamp, flags);
3969 sample = mov_index_search_pos(st->index_entries, st->nb_index_entries, sync_point, AVSEEK_FLAG_ANY);
3970 }
3971
3972 av_dlog(s, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
3973 if (sample < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
3974 sample = 0;
3975 if (sample < 0) /* not sure what to do */
3976 return AVERROR_INVALIDDATA;
3977 sc->current_sample = sample;
3978 av_dlog(s, "stream %d, found sample %d\n", st->index, sc->current_sample);
3979 /* adjust ctts index */
3980 if (sc->ctts_data) {
3981 time_sample = 0;
3982 for (i = 0; i < sc->ctts_count; i++) {
3983 int next = time_sample + sc->ctts_data[i].count;
3984 if (next > sc->current_sample) {
3985 sc->ctts_index = i;
3986 sc->ctts_sample = sc->current_sample - time_sample;
3987 break;
3988 }
3989 time_sample = next;
3990 }
3991 }
3992 return sample;
3993}
3994
3995static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
3996{
3997 AVStream *st;
3998 int64_t seek_timestamp, timestamp;
3999 int sample;
4000 int i;
4001
4002 if (stream_index >= s->nb_streams)
4003 return AVERROR_INVALIDDATA;
4004
4005 st = s->streams[stream_index];
4006 sample = mov_seek_stream(s, st, sample_time, flags);
4007 if (sample < 0)
4008 return sample;
4009
4010 /* adjust seek timestamp to found sample timestamp */
4011 seek_timestamp = st->index_entries[sample].timestamp;
4012
4013 for (i = 0; i < s->nb_streams; i++) {
4014 MOVStreamContext *sc = s->streams[i]->priv_data;
4015 st = s->streams[i];
4016 st->skip_samples = (sample_time <= 0) ? sc->start_pad : 0;
4017
4018 if (stream_index == i)
4019 continue;
4020
4021 timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
4022 mov_seek_stream(s, st, timestamp, flags);
4023 }
4024 return 0;
4025}
4026
4027static const AVOption options[] = {
4028 {"use_absolute_path",
4029 "allow using absolute path when opening alias, this is a possible security issue",
4030 offsetof(MOVContext, use_absolute_path), FF_OPT_TYPE_INT, {.i64 = 0},
4031 0, 1, AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_DECODING_PARAM},
4032 {"ignore_editlist", "", offsetof(MOVContext, ignore_editlist), FF_OPT_TYPE_INT, {.i64 = 0},
4033 0, 1, AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_DECODING_PARAM},
4034 {NULL}
4035};
4036
4037static const AVClass mov_class = {
4038 .class_name = "mov,mp4,m4a,3gp,3g2,mj2",
4039 .item_name = av_default_item_name,
4040 .option = options,
4041 .version = LIBAVUTIL_VERSION_INT,
4042};
4043
4044AVInputFormat ff_mov_demuxer = {
4045 .name = "mov,mp4,m4a,3gp,3g2,mj2",
4046 .long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
4047 .priv_data_size = sizeof(MOVContext),
4048 .read_probe = mov_probe,
4049 .read_header = mov_read_header,
4050 .read_packet = mov_read_packet,
4051 .read_close = mov_read_close,
4052 .read_seek = mov_read_seek,
4053 .priv_class = &mov_class,
4054 .flags = AVFMT_NO_BYTE_SEEK,
4055};
4056