FFmpeg
Loading...
Searching...
No Matches
mov.c
Go to the documentation of this file.
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 "config_components.h"
27
28#include <inttypes.h>
29#include <limits.h>
30#include <stdint.h>
31#include <stdlib.h>
32
34#include "libavutil/bprint.h"
36#include "libavutil/dovi_meta.h"
37#include "libavutil/internal.h"
39#include "libavutil/intfloat.h"
41#include "libavutil/avassert.h"
42#include "libavutil/avstring.h"
43#include "libavutil/dict.h"
44#include "libavutil/display.h"
45#include "libavutil/mem.h"
46#include "libavutil/opt.h"
47#include "libavutil/aes.h"
48#include "libavutil/aes_ctr.h"
49#include "libavutil/gain_map.h"
50#include "libavutil/pixdesc.h"
51#include "libavutil/sha.h"
52#include "libavutil/spherical.h"
53#include "libavutil/stereo3d.h"
54#include "libavutil/timecode.h"
55#include "libavutil/uuid.h"
56#include "libavcodec/ac3tab.h"
57#include "libavcodec/exif.h"
58#include "libavcodec/flac.h"
63#include "avformat.h"
64#include "internal.h"
65#include "avio_internal.h"
66#include "demux.h"
67#include "dvdclut.h"
68#include "iamf_parse.h"
69#include "iamf_reader.h"
70#include "dovi_isom.h"
71#include "riff.h"
72#include "isom.h"
73#include "libavcodec/get_bits.h"
74#include "libavcodec/opus/tab.h"
75#include "id3v1.h"
76#include "mov_chan.h"
77#include "replaygain.h"
78
79#if CONFIG_ZLIB
80#include <zlib.h>
81#endif
82
83#include "qtpalette.h"
84
85/* those functions parse an atom */
86/* links atom IDs to parse functions */
87typedef struct MOVParseTableEntry {
88 uint32_t type;
89 int (*parse)(MOVContext *ctx, AVIOContext *pb, MOVAtom atom);
91
92static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom);
95
97 unsigned len, const char *key)
98{
99 char buf[16];
100
101 short current, total = 0;
102 avio_rb16(pb); // unknown
103 current = avio_rb16(pb);
104 if (len >= 6)
105 total = avio_rb16(pb);
106 if (!total)
107 snprintf(buf, sizeof(buf), "%d", current);
108 else
109 snprintf(buf, sizeof(buf), "%d/%d", current, total);
110 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
111 av_dict_set(&c->fc->metadata, key, buf, 0);
112
113 return 0;
114}
115
117 unsigned len, const char *key)
118{
119 /* bypass padding bytes */
120 avio_r8(pb);
121 avio_r8(pb);
122 avio_r8(pb);
123
124 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
125 av_dict_set_int(&c->fc->metadata, key, avio_r8(pb), 0);
126
127 return 0;
128}
129
131 unsigned len, const char *key)
132{
133 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
134 av_dict_set_int(&c->fc->metadata, key, avio_r8(pb), 0);
135
136 return 0;
137}
138
140 unsigned len, const char *key)
141{
142 short genre;
143
144 avio_r8(pb); // unknown
145
146 genre = avio_r8(pb);
147 if (genre < 1 || genre > ID3v1_GENRE_MAX)
148 return 0;
149 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
150 av_dict_set(&c->fc->metadata, key, ff_id3v1_genre_str[genre-1], 0);
151
152 return 0;
153}
154
155static const uint32_t mac_to_unicode[128] = {
156 0x00C4,0x00C5,0x00C7,0x00C9,0x00D1,0x00D6,0x00DC,0x00E1,
157 0x00E0,0x00E2,0x00E4,0x00E3,0x00E5,0x00E7,0x00E9,0x00E8,
158 0x00EA,0x00EB,0x00ED,0x00EC,0x00EE,0x00EF,0x00F1,0x00F3,
159 0x00F2,0x00F4,0x00F6,0x00F5,0x00FA,0x00F9,0x00FB,0x00FC,
160 0x2020,0x00B0,0x00A2,0x00A3,0x00A7,0x2022,0x00B6,0x00DF,
161 0x00AE,0x00A9,0x2122,0x00B4,0x00A8,0x2260,0x00C6,0x00D8,
162 0x221E,0x00B1,0x2264,0x2265,0x00A5,0x00B5,0x2202,0x2211,
163 0x220F,0x03C0,0x222B,0x00AA,0x00BA,0x03A9,0x00E6,0x00F8,
164 0x00BF,0x00A1,0x00AC,0x221A,0x0192,0x2248,0x2206,0x00AB,
165 0x00BB,0x2026,0x00A0,0x00C0,0x00C3,0x00D5,0x0152,0x0153,
166 0x2013,0x2014,0x201C,0x201D,0x2018,0x2019,0x00F7,0x25CA,
167 0x00FF,0x0178,0x2044,0x20AC,0x2039,0x203A,0xFB01,0xFB02,
168 0x2021,0x00B7,0x201A,0x201E,0x2030,0x00C2,0x00CA,0x00C1,
169 0x00CB,0x00C8,0x00CD,0x00CE,0x00CF,0x00CC,0x00D3,0x00D4,
170 0xF8FF,0x00D2,0x00DA,0x00DB,0x00D9,0x0131,0x02C6,0x02DC,
171 0x00AF,0x02D8,0x02D9,0x02DA,0x00B8,0x02DD,0x02DB,0x02C7,
172};
173
175 char *dst, int dstlen)
176{
177 char *p = dst;
178 char *end = dst+dstlen-1;
179 int i;
180
181 for (i = 0; i < len; i++) {
182 uint8_t t, c = avio_r8(pb);
183
184 if (p >= end)
185 continue;
186
187 if (c < 0x80)
188 *p++ = c;
189 else if (p < end)
190 PUT_UTF8(mac_to_unicode[c-0x80], t, if (p < end) *p++ = t;);
191 }
192 *p = 0;
193 return p - dst;
194}
195
196/**
197 * Get the requested item.
198 */
199static HEIFItem *get_heif_item(MOVContext *c, unsigned id)
200{
201 HEIFItem *item = NULL;
202
203 for (int i = 0; i < c->nb_heif_item; i++) {
204 if (!c->heif_item[i] || c->heif_item[i]->item_id != id)
205 continue;
206
207 item = c->heif_item[i];
208 break;
209 }
210
211 return item;
212}
213
214/**
215 * Get the current stream in the parsing process. This can either be the
216 * stream of the trak being parsed, or the stream referenced by an item.
217 * Returns NULL when neither a trak nor an item is being parsed.
218 */
220{
221 AVStream *st = NULL;
222 HEIFItem *item;
223
224 if (c->fc->nb_streams < 1)
225 return NULL;
226
227 if (c->cur_item_id == -1) {
228 if (c->trak_index < 0) {
229 av_log(c->fc, AV_LOG_WARNING, "Sample description atom outside TRAK\n");
230 return NULL;
231 }
232 return c->fc->streams[c->fc->nb_streams-1];
233 }
234
235 item = get_heif_item(c, c->cur_item_id);
236 if (item)
237 st = item->st;
238
239 return st;
240}
241
242static int mov_read_covr(MOVContext *c, AVIOContext *pb, int type, int len)
243{
244 AVStream *st;
246 enum AVCodecID id;
247 int ret;
248
249 switch (type) {
250 case 0xd: id = AV_CODEC_ID_MJPEG; break;
251 case 0xe: id = AV_CODEC_ID_PNG; break;
252 case 0x1b: id = AV_CODEC_ID_BMP; break;
253 default:
254 av_log(c->fc, AV_LOG_WARNING, "Unknown cover type: 0x%x.\n", type);
255 avio_skip(pb, len);
256 return 0;
257 }
258
259 sc = av_mallocz(sizeof(*sc));
260 if (!sc)
261 return AVERROR(ENOMEM);
262 ret = ff_add_attached_pic(c->fc, NULL, pb, NULL, len);
263 if (ret < 0) {
264 av_free(sc);
265 return ret;
266 }
267 st = c->fc->streams[c->fc->nb_streams - 1];
268 st->priv_data = sc;
269 sc->id = st->id;
270 sc->refcount = 1;
271
272 if (st->attached_pic.size >= 8 && id != AV_CODEC_ID_BMP) {
273 if (AV_RB64(st->attached_pic.data) == 0x89504e470d0a1a0a) {
274 id = AV_CODEC_ID_PNG;
275 } else {
277 }
278 }
279 st->codecpar->codec_id = id;
280
281 return 0;
282}
283
284// 3GPP TS 26.244
285static int mov_metadata_loci(MOVContext *c, AVIOContext *pb, unsigned len)
286{
287 char language[4] = { 0 };
288 char buf[200], place[100];
289 uint16_t langcode = 0;
290 int32_t longitude, latitude, altitude;
291 int64_t lat, lon, alt;
292 const char *key = "location";
293
294 if (len < 4 + 2 + 1 + 1 + 4 + 4 + 4) {
295 av_log(c->fc, AV_LOG_ERROR, "loci too short\n");
296 return AVERROR_INVALIDDATA;
297 }
298
299 avio_skip(pb, 4); // version+flags
300 langcode = avio_rb16(pb);
301 ff_mov_lang_to_iso639(langcode, language);
302 len -= 6;
303
304 len -= avio_get_str(pb, len, place, sizeof(place));
305 if (len < 1) {
306 av_log(c->fc, AV_LOG_ERROR, "place name too long\n");
307 return AVERROR_INVALIDDATA;
308 }
309 avio_skip(pb, 1); // role
310 len -= 1;
311
312 if (len < 12) {
313 av_log(c->fc, AV_LOG_ERROR,
314 "loci too short (%u bytes left, need at least %d)\n", len, 12);
315 return AVERROR_INVALIDDATA;
316 }
317 longitude = avio_rb32(pb);
318 latitude = avio_rb32(pb);
319 altitude = avio_rb32(pb);
320
321 // ISO 6709 string as written by QuickTime, independently of the locale
322 lat = llrint(fabs(latitude * (10000.0 / (1 << 16))));
323 lon = llrint(fabs(longitude * (10000.0 / (1 << 16))));
324 alt = llrint(fabs(altitude * (1000.0 / (1 << 16))));
325 snprintf(buf, sizeof(buf), "%c%02"PRId64".%04"PRId64"%c%03"PRId64".%04"PRId64
326 "%c%03"PRId64".%03"PRId64"/%s",
327 latitude < 0 ? '-' : '+', lat / 10000, lat % 10000,
328 longitude < 0 ? '-' : '+', lon / 10000, lon % 10000,
329 altitude < 0 ? '-' : '+', alt / 1000, alt % 1000, place);
330
331 if (*language && strcmp(language, "und")) {
332 char key2[16];
333 snprintf(key2, sizeof(key2), "%s-%s", key, language);
334 av_dict_set(&c->fc->metadata, key2, buf, 0);
335 }
336 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
337 return av_dict_set(&c->fc->metadata, key, buf, 0);
338}
339
340// 3GPP TS 26.244 user data box or tnam, after its version and flags
342 const char *key, AVDictionary **metadata)
343{
344 char language[4], *str;
345 int size, ch, ret;
346
347 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
348 if (!strcmp(key, "date"))
349 return len < 2 ? 0 : av_dict_set_int(metadata, key, avio_rb16(pb), 0);
350
351 if (len < 3 || len >= INT_MAX / 2)
352 return 0;
353 ff_mov_lang_to_iso639(avio_rb16(pb), language);
354 len -= 2;
355
356 size = 2 * len + 1;
357 str = av_malloc(size);
358 if (!str)
359 return AVERROR(ENOMEM);
360 ch = avio_r8(pb);
361 if (ch == 0xFE || ch == 0xFF) { // UTF-16 byte order mark, never in UTF-8
362 if (len < 2) {
363 av_free(str);
364 return 0;
365 }
366 avio_skip(pb, 1);
367 len -= 2 + (ch == 0xFE ? avio_get_str16be(pb, len - 2, str, size)
368 : avio_get_str16le(pb, len - 2, str, size));
369 } else {
370 str[0] = ch;
371 len -= 1 + (ch ? avio_get_str(pb, len - 1, str + 1, size - 1) : 0);
372 }
373
374 ret = av_dict_set(metadata, key, str, 0);
375 if (ret >= 0 && *language && strcmp(language, "und")) {
376 char key2[32];
377 snprintf(key2, sizeof(key2), "%s-%s", key, language);
378 ret = av_dict_set(metadata, key2, str, 0);
379 }
380 av_free(str);
381
382 if (ret >= 0 && len > 0 && !strcmp(key, "album")) {
383 int track = avio_r8(pb);
384 if (track)
385 ret = av_dict_set_int(metadata, "track", track, 0);
386 }
387 return ret;
388}
389
390static int mov_metadata_hmmt(MOVContext *c, AVIOContext *pb, unsigned len)
391{
392 int i, n_hmmt;
393
394 if (len < 2)
395 return 0;
396 if (c->ignore_chapters)
397 return 0;
398
399 n_hmmt = avio_rb32(pb);
400 if (n_hmmt > len / 4)
401 return AVERROR_INVALIDDATA;
402 for (i = 0; i < n_hmmt && !pb->eof_reached; i++) {
403 int moment_time = avio_rb32(pb);
404 avpriv_new_chapter(c->fc, i, av_make_q(1, 1000), moment_time, AV_NOPTS_VALUE, NULL);
405 }
406 if (avio_feof(pb))
407 return AVERROR_INVALIDDATA;
408 return 0;
409}
410
412{
413 char tmp_key[AV_FOURCC_MAX_STRING_SIZE] = {0};
414 char key2[32], language[4] = {0};
415 char *str = NULL;
416 const char *key = NULL;
417 uint16_t langcode = 0;
418 uint32_t data_type = 0, str_size_alloc;
419 uint64_t str_size;
420 int (*parse)(MOVContext*, AVIOContext*, unsigned, const char*) = NULL;
421 int raw = 0;
422 int num = 0;
423 int tgp = 0;
425
426 if (c->trak_index >= 0 && c->trak_index < c->fc->nb_streams)
427 metadata = &c->fc->streams[c->trak_index]->metadata;
428 else
429 metadata = &c->fc->metadata;
430
431 switch (atom.type) {
432 case MKTAG( '@','P','R','M'): key = "premiere_version"; raw = 1; break;
433 case MKTAG( '@','P','R','Q'): key = "quicktime_version"; raw = 1; break;
434 case MKTAG( 'X','M','P','_'):
435 if (c->export_xmp) { key = "xmp"; raw = 1; } break;
436 case MKTAG( 'a','A','R','T'): key = "album_artist"; break;
437 case MKTAG( 'a','k','I','D'): key = "account_type";
439 case MKTAG( 'a','l','b','m'): key = "album"; tgp = 1; break;
440 case MKTAG( 'a','p','I','D'): key = "account_id"; break;
441 case MKTAG( 'a','u','t','h'): key = "author"; tgp = 1; break;
442 case MKTAG( 'c','a','t','g'): key = "category"; break;
443 case MKTAG( 'c','p','i','l'): key = "compilation";
445 case MKTAG( 'c','p','r','t'): key = "copyright"; tgp = 1; break;
446 case MKTAG( 'd','e','s','c'): key = "description"; break;
447 case MKTAG( 'd','i','s','k'): key = "disc";
449 case MKTAG( 'd','s','c','p'): key = "comment"; tgp = 1; break;
450 case MKTAG( 'e','g','i','d'): key = "episode_uid";
452 case MKTAG( 'F','I','R','M'): key = "firmware"; raw = 1; break;
453 case MKTAG( 'g','n','r','e'): key = "genre"; tgp = 1;
454 parse = mov_metadata_gnre; break;
455 case MKTAG( 'h','d','v','d'): key = "hd_video";
457 case MKTAG( 'H','M','M','T'):
458 return mov_metadata_hmmt(c, pb, atom.size);
459 case MKTAG( 'k','e','y','w'): key = "keywords"; break;
460 case MKTAG( 'l','d','e','s'): key = "synopsis"; break;
461 case MKTAG( 'l','o','c','i'):
462 return mov_metadata_loci(c, pb, atom.size);
463 case MKTAG( 'm','a','n','u'): key = "make"; break;
464 case MKTAG( 'm','o','d','l'): key = "model"; break;
465 case MKTAG( 'n','a','m','e'): key = "name"; break;
466 case MKTAG( 'p','c','s','t'): key = "podcast";
468 case MKTAG( 'p','e','r','f'): key = "artist"; tgp = 1; break;
469 case MKTAG( 'p','g','a','p'): key = "gapless_playback";
471 case MKTAG( 'p','u','r','d'): key = "purchase_date"; break;
472 case MKTAG( 'r','t','n','g'): key = "rating";
474 case MKTAG( 's','o','a','a'): key = "sort_album_artist"; break;
475 case MKTAG( 's','o','a','l'): key = "sort_album"; break;
476 case MKTAG( 's','o','a','r'): key = "sort_artist"; break;
477 case MKTAG( 's','o','c','o'): key = "sort_composer"; break;
478 case MKTAG( 's','o','n','m'): key = "sort_name"; break;
479 case MKTAG( 's','o','s','n'): key = "sort_show"; break;
480 case MKTAG( 's','t','i','k'): key = "media_type";
482 case MKTAG( 't','i','t','l'): key = "title"; tgp = 1; break;
483 case MKTAG( 't','n','a','m'): key = "title"; tgp = 1; break;
484 case MKTAG( 't','r','k','n'): key = "track";
486 case MKTAG( 't','v','e','n'): key = "episode_id"; break;
487 case MKTAG( 't','v','e','s'): key = "episode_sort";
489 case MKTAG( 't','v','n','n'): key = "network"; break;
490 case MKTAG( 't','v','s','h'): key = "show"; break;
491 case MKTAG( 't','v','s','n'): key = "season_number";
493 case MKTAG( 'y','r','r','c'): key = "date"; tgp = 1; break;
494 case MKTAG(0xa9,'A','R','T'): key = "artist"; break;
495 case MKTAG(0xa9,'P','R','D'): key = "producer"; break;
496 case MKTAG(0xa9,'a','l','b'): key = "album"; break;
497 case MKTAG(0xa9,'a','u','t'): key = "artist"; break;
498 case MKTAG(0xa9,'c','h','p'): key = "chapter"; break;
499 case MKTAG(0xa9,'c','m','t'): key = "comment"; break;
500 case MKTAG(0xa9,'c','o','m'): key = "composer"; break;
501 case MKTAG(0xa9,'c','p','y'): key = "copyright"; break;
502 case MKTAG(0xa9,'d','a','y'): key = "date"; break;
503 case MKTAG(0xa9,'d','i','r'): key = "director"; break;
504 case MKTAG(0xa9,'d','i','s'): key = "disclaimer"; break;
505 case MKTAG(0xa9,'e','d','1'): key = "edit_date"; break;
506 case MKTAG(0xa9,'e','n','c'): key = "encoder"; break;
507 case MKTAG(0xa9,'f','m','t'): key = "original_format"; break;
508 case MKTAG(0xa9,'g','e','n'): key = "genre"; break;
509 case MKTAG(0xa9,'g','r','p'): key = "grouping"; break;
510 case MKTAG(0xa9,'h','s','t'): key = "host_computer"; break;
511 case MKTAG(0xa9,'i','n','f'): key = "comment"; break;
512 case MKTAG(0xa9,'l','y','r'): key = "lyrics"; break;
513 case MKTAG(0xa9,'m','a','k'): key = "make"; break;
514 case MKTAG(0xa9,'m','o','d'): key = "model"; break;
515 case MKTAG(0xa9,'n','a','m'): key = "title"; break;
516 case MKTAG(0xa9,'o','p','e'): key = "original_artist"; break;
517 case MKTAG(0xa9,'p','r','d'): key = "producer"; break;
518 case MKTAG(0xa9,'p','r','f'): key = "performers"; break;
519 case MKTAG(0xa9,'r','e','q'): key = "playback_requirements"; break;
520 case MKTAG(0xa9,'s','r','c'): key = "original_source"; break;
521 case MKTAG(0xa9,'s','t','3'): key = "subtitle"; break;
522 case MKTAG(0xa9,'s','w','r'): key = "encoder"; break;
523 case MKTAG(0xa9,'t','o','o'): key = "encoder"; break;
524 case MKTAG(0xa9,'t','r','k'): key = "track"; break;
525 case MKTAG(0xa9,'u','r','l'): key = "URL"; break;
526 case MKTAG(0xa9,'w','r','n'): key = "warning"; break;
527 case MKTAG(0xa9,'w','r','t'): key = "composer"; break;
528 case MKTAG(0xa9,'x','y','z'): key = "location"; break;
529 }
530retry:
531 if (c->itunes_metadata && atom.size > 8) {
532 int data_size = avio_rb32(pb);
533 int tag = avio_rl32(pb);
534 if (tag == MKTAG('d','a','t','a') && data_size <= atom.size && data_size >= 16) {
535 data_type = avio_rb32(pb); // type
536 avio_rb32(pb); // unknown
537 str_size = data_size - 16;
538 atom.size -= 16;
539
540 if (!key && c->found_hdlr_mdta && c->meta_keys) {
541 uint32_t index = av_bswap32(atom.type); // BE number has been read as LE
542 if (index < c->meta_keys_count && index > 0) {
543 key = c->meta_keys[index];
544 } else if (atom.type != MKTAG('c', 'o', 'v', 'r')) {
546 "The index of 'data' is out of range: %"PRId32" < 1 or >= %d.\n",
547 index, c->meta_keys_count);
548 }
549 }
550 if (atom.type == MKTAG('c', 'o', 'v', 'r') ||
551 (key && !strcmp(key, "com.apple.quicktime.artwork"))) {
552 int ret = mov_read_covr(c, pb, data_type, str_size);
553 if (ret < 0) {
554 av_log(c->fc, AV_LOG_ERROR, "Error parsing cover art.\n");
555 return ret;
556 }
557 atom.size -= str_size;
558 if (atom.size > 8)
559 goto retry;
560 return ret;
561 }
562 } else return 0;
563 } else if (atom.size > 4 && (key || c->export_all) && !c->itunes_metadata && !raw) {
564 str_size = avio_rb16(pb); // string length
565 if (str_size > atom.size) {
566 raw = 1;
567 avio_seek(pb, -2, SEEK_CUR);
568 av_log(c->fc, AV_LOG_WARNING, "UDTA parsing failed retrying raw\n");
569 goto retry;
570 }
571 langcode = avio_rb16(pb);
572 ff_mov_lang_to_iso639(langcode, language);
573 atom.size -= 4;
574 if (tgp && !str_size && !langcode) // full box version and flags
575 return mov_metadata_3gp(c, pb, atom.size, key, metadata);
576 } else
577 str_size = atom.size;
578
579 if (c->export_all && !key) {
580 key = av_fourcc_make_string(tmp_key, atom.type);
581 }
582
583 if (!key)
584 return 0;
585 if (atom.size < 0 || str_size >= INT_MAX/2)
586 return AVERROR_INVALIDDATA;
587
588 // Allocates enough space if data_type is an integer or float32 number, otherwise
589 // worst-case requirement for output string in case of utf8 coded input
590 num = (data_type >= 21 && data_type <= 23);
591 str_size_alloc = (num ? 512 : (raw ? str_size : str_size * 2)) + 1;
592 str = av_mallocz(str_size_alloc);
593 if (!str)
594 return AVERROR(ENOMEM);
595
596 if (parse)
597 parse(c, pb, str_size, key);
598 else {
599 if (!raw && (data_type == 3 || (data_type == 0 && (langcode < 0x400 || langcode == 0x7fff)))) { // MAC Encoded
600 mov_read_mac_string(c, pb, str_size, str, str_size_alloc);
601 } else if (data_type == 21) { // BE signed integer, variable size
602 int64_t val = 0;
603 if (str_size == 1)
604 val = (int8_t)avio_r8(pb);
605 else if (str_size == 2)
606 val = (int16_t)avio_rb16(pb);
607 else if (str_size == 3)
608 val = ((int32_t)(avio_rb24(pb)<<8))>>8;
609 else if (str_size == 4)
610 val = (int32_t)avio_rb32(pb);
611 else if (str_size == 8)
612 val = (int64_t)avio_rb64(pb);
613 if (snprintf(str, str_size_alloc, "%"PRId64, val) >= str_size_alloc) {
614 av_log(c->fc, AV_LOG_ERROR,
615 "Failed to store the number (%"PRId64") in string.\n", val);
616 av_free(str);
617 return AVERROR_INVALIDDATA;
618 }
619 } else if (data_type == 22) { // BE unsigned integer, variable size
620 uint64_t val = 0;
621 if (str_size == 1)
622 val = avio_r8(pb);
623 else if (str_size == 2)
624 val = avio_rb16(pb);
625 else if (str_size == 3)
626 val = avio_rb24(pb);
627 else if (str_size == 4)
628 val = avio_rb32(pb);
629 else if (str_size == 8)
630 val = avio_rb64(pb);
631 if (snprintf(str, str_size_alloc, "%"PRIu64, val) >= str_size_alloc) {
632 av_log(c->fc, AV_LOG_ERROR,
633 "Failed to store the number (%"PRIu64") in string.\n", val);
634 av_free(str);
635 return AVERROR_INVALIDDATA;
636 }
637 } else if (data_type == 23 && str_size >= 4) { // BE float32
638 float val = av_int2float(avio_rb32(pb));
639 if (snprintf(str, str_size_alloc, "%f", val) >= str_size_alloc) {
640 av_log(c->fc, AV_LOG_ERROR,
641 "Failed to store the float32 number (%f) in string.\n", val);
642 av_free(str);
643 return AVERROR_INVALIDDATA;
644 }
645 } else if (data_type > 1 && data_type != 4) {
646 // data_type can be 0 if not set at all above. data_type 1 means
647 // UTF8 and 4 means "UTF8 sort". For any other type (UTF16 or e.g.
648 // a picture), don't return it blindly in a string that is supposed
649 // to be UTF8 text.
650 av_log(c->fc, AV_LOG_WARNING, "Skipping unhandled metadata %s of type %"PRIu32"\n", key, data_type);
651 av_free(str);
652 return 0;
653 } else {
654 int ret = ffio_read_size(pb, str, str_size);
655 if (ret < 0) {
656 av_free(str);
657 return ret;
658 }
659 str[str_size] = 0;
660 }
661 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
662 if (c->itunes_metadata && av_dict_get(*metadata, key, NULL, 0))
664 av_dict_set(metadata, key, str, c->itunes_metadata ? AV_DICT_APPEND : 0);
665 if (*language && strcmp(language, "und")) {
666 snprintf(key2, sizeof(key2), "%s-%s", key, language);
667 av_dict_set(metadata, key2, str, 0);
668 }
669 if (!strcmp(key, "encoder")) {
670 int major, minor, micro;
671 if (sscanf(str, "HandBrake %d.%d.%d", &major, &minor, &micro) == 3) {
672 c->handbrake_version = 1000000*major + 1000*minor + micro;
673 }
674 }
675
676 atom.size -= str_size;
677 av_freep(&str);
678
679 // Read remaining data atoms for multi-valued iTunes tags (e.g. multiple
680 // artists stored as multiple data atoms within one tag atom), consistent
681 // with the existing covr path.
682 // Note: multiple sibling tag atoms with the same key (e.g. three separate
683 // ©ART atoms under ilst) are handled by the AV_DICT_APPEND logic above,
684 // since mov_read_udta_string() is called once per tag atom.
685 if (c->itunes_metadata && atom.size > 8)
686 goto retry;
687 }
688
689 av_freep(&str);
690 return 0;
691}
692
694{
695 int64_t start;
696 int i, nb_chapters, str_len, version;
697 char str[256+1];
698 int ret;
699
700 if (c->ignore_chapters)
701 return 0;
702
703 if ((atom.size -= 5) < 0)
704 return 0;
705
706 version = avio_r8(pb);
707 avio_rb24(pb);
708 if (version)
709 avio_rb32(pb); // ???
710 nb_chapters = avio_r8(pb);
711
712 for (i = 0; i < nb_chapters; i++) {
713 if (atom.size < 9)
714 return 0;
715
716 start = avio_rb64(pb);
717 str_len = avio_r8(pb);
718
719 if ((atom.size -= 9+str_len) < 0)
720 return 0;
721
722 ret = ffio_read_size(pb, str, str_len);
723 if (ret < 0)
724 return ret;
725 str[str_len] = 0;
726 avpriv_new_chapter(c->fc, i, (AVRational){1,10000000}, start, AV_NOPTS_VALUE, str);
727 }
728 return 0;
729}
730
731#define MIN_DATA_ENTRY_BOX_SIZE 12
733{
734 AVStream *st;
736 int entries, i, j;
737
738 if (c->fc->nb_streams < 1)
739 return 0;
740 st = c->fc->streams[c->fc->nb_streams-1];
741 sc = st->priv_data;
742
743 avio_rb32(pb); // version + flags
744 entries = avio_rb32(pb);
745 if (!entries ||
746 entries > (atom.size - 1) / MIN_DATA_ENTRY_BOX_SIZE + 1 ||
747 entries >= UINT_MAX / sizeof(*sc->drefs))
748 return AVERROR_INVALIDDATA;
749
750 for (i = 0; i < sc->drefs_count; i++) {
751 MOVDref *dref = &sc->drefs[i];
752 av_freep(&dref->path);
753 av_freep(&dref->dir);
754 }
755 av_free(sc->drefs);
756 sc->drefs_count = 0;
757 sc->drefs = av_mallocz(entries * sizeof(*sc->drefs));
758 if (!sc->drefs)
759 return AVERROR(ENOMEM);
760 sc->drefs_count = entries;
761
762 for (i = 0; i < entries; i++) {
763 MOVDref *dref = &sc->drefs[i];
764 uint32_t size = avio_rb32(pb);
765 int64_t next = avio_tell(pb);
766
767 if (size < 12 || next < 0 || next > INT64_MAX - size)
768 return AVERROR_INVALIDDATA;
769
770 next += size - 4;
771
772 dref->type = avio_rl32(pb);
773 avio_rb32(pb); // version + flags
774
775 if (dref->type == MKTAG('a','l','i','s') && size > 150) {
776 /* macintosh alias record */
777 uint16_t volume_len, len;
778 int16_t type;
779 int ret;
780
781 avio_skip(pb, 10);
782
783 volume_len = avio_r8(pb);
784 volume_len = FFMIN(volume_len, 27);
785 ret = ffio_read_size(pb, dref->volume, 27);
786 if (ret < 0)
787 return ret;
788 dref->volume[volume_len] = 0;
789 av_log(c->fc, AV_LOG_DEBUG, "volume %s, len %d\n", dref->volume, volume_len);
790
791 avio_skip(pb, 12);
792
793 len = avio_r8(pb);
794 len = FFMIN(len, 63);
795 ret = ffio_read_size(pb, dref->filename, 63);
796 if (ret < 0)
797 return ret;
798 dref->filename[len] = 0;
799 av_log(c->fc, AV_LOG_DEBUG, "filename %s, len %d\n", dref->filename, len);
800
801 avio_skip(pb, 16);
802
803 /* read next level up_from_alias/down_to_target */
804 dref->nlvl_from = avio_rb16(pb);
805 dref->nlvl_to = avio_rb16(pb);
806 av_log(c->fc, AV_LOG_DEBUG, "nlvl from %d, nlvl to %d\n",
807 dref->nlvl_from, dref->nlvl_to);
808
809 avio_skip(pb, 16);
810
811 for (type = 0; type != -1 && avio_tell(pb) < next; ) {
812 if (avio_feof(pb))
813 return AVERROR_EOF;
814 type = avio_rb16(pb);
815 len = avio_rb16(pb);
816 av_log(c->fc, AV_LOG_DEBUG, "type %d, len %d\n", type, len);
817 if (len&1)
818 len += 1;
819 if (type == 2) { // absolute path
820 av_free(dref->path);
821 dref->path = av_mallocz(len+1);
822 if (!dref->path)
823 return AVERROR(ENOMEM);
824
825 ret = ffio_read_size(pb, dref->path, len);
826 if (ret < 0) {
827 av_freep(&dref->path);
828 return ret;
829 }
830 if (len > volume_len && !strncmp(dref->path, dref->volume, volume_len)) {
831 len -= volume_len;
832 memmove(dref->path, dref->path+volume_len, len);
833 dref->path[len] = 0;
834 }
835 // trim string of any ending zeros
836 for (j = len - 1; j >= 0; j--) {
837 if (dref->path[j] == 0)
838 len--;
839 else
840 break;
841 }
842 for (j = 0; j < len; j++)
843 if (dref->path[j] == ':' || dref->path[j] == 0)
844 dref->path[j] = '/';
845 av_log(c->fc, AV_LOG_DEBUG, "path %s\n", dref->path);
846 } else if (type == 0) { // directory name
847 av_free(dref->dir);
848 dref->dir = av_malloc(len+1);
849 if (!dref->dir)
850 return AVERROR(ENOMEM);
851
852 ret = ffio_read_size(pb, dref->dir, len);
853 if (ret < 0) {
854 av_freep(&dref->dir);
855 return ret;
856 }
857 dref->dir[len] = 0;
858 for (j = 0; j < len; j++)
859 if (dref->dir[j] == ':')
860 dref->dir[j] = '/';
861 av_log(c->fc, AV_LOG_DEBUG, "dir %s\n", dref->dir);
862 } else
863 avio_skip(pb, len);
864 }
865 } else {
866 av_log(c->fc, AV_LOG_DEBUG, "Unknown dref type 0x%08"PRIx32" size %"PRIu32"\n",
867 dref->type, size);
868 entries--;
869 i--;
870 }
871 avio_seek(pb, next, SEEK_SET);
872 }
873 return 0;
874}
875
877{
878 AVStream *st;
879 uint32_t type;
880 uint32_t ctype;
881 int64_t title_size;
882 char *title_str;
883 int ret;
884
885 avio_r8(pb); /* version */
886 avio_rb24(pb); /* flags */
887
888 /* component type */
889 ctype = avio_rl32(pb);
890 type = avio_rl32(pb); /* component subtype */
891
892 av_log(c->fc, AV_LOG_TRACE, "ctype=%s\n", av_fourcc2str(ctype));
893 av_log(c->fc, AV_LOG_TRACE, "stype=%s\n", av_fourcc2str(type));
894
895 if (c->trak_index < 0) { // meta not inside a trak
896 if (type == MKTAG('m','d','t','a')) {
897 c->found_hdlr_mdta = 1;
898 }
899 return 0;
900 }
901
902 st = c->fc->streams[c->fc->nb_streams-1];
903
904 if (type == MKTAG('v','i','d','e'))
906 else if (type == MKTAG('s','o','u','n'))
908 else if (type == MKTAG('m','1','a',' '))
910 else if ((type == MKTAG('s','u','b','p')) || (type == MKTAG('c','l','c','p')))
912
913 avio_rb32(pb); /* component manufacture */
914 avio_rb32(pb); /* component flags */
915 avio_rb32(pb); /* component flags mask */
916
917 title_size = atom.size - 24;
918 if (title_size > 0) {
919 if (title_size > FFMIN(INT_MAX, SIZE_MAX-1))
920 return AVERROR_INVALIDDATA;
921 title_str = av_malloc(title_size + 1); /* Add null terminator */
922 if (!title_str)
923 return AVERROR(ENOMEM);
924
925 ret = ffio_read_size(pb, title_str, title_size);
926 if (ret < 0) {
927 av_freep(&title_str);
928 return ret;
929 }
930 title_str[title_size] = 0;
931 if (title_str[0]) {
932 int off = (!c->isom && title_str[0] == title_size - 1);
933 // flag added so as to not set stream handler name if already set from mdia->hdlr
934 av_dict_set(&st->metadata, "handler_name", title_str + off, AV_DICT_DONT_OVERWRITE);
935 }
936 av_freep(&title_str);
937 }
938
939 return 0;
940}
941
943{
944 if (!get_curr_st(c))
945 return 0;
946 return ff_mov_read_esds(c->fc, pb);
947}
948
950{
951 AVStream *st;
953 enum AVAudioServiceType *ast;
954 int ac3info, acmod, lfeon, bsmod;
955 uint64_t mask;
956
957 if (c->fc->nb_streams < 1)
958 return 0;
959 st = c->fc->streams[c->fc->nb_streams-1];
960
964 sizeof(*ast), 0);
965 if (!sd)
966 return AVERROR(ENOMEM);
967
968 ast = (enum AVAudioServiceType*)sd->data;
969 ac3info = avio_rb24(pb);
970 bsmod = (ac3info >> 14) & 0x7;
971 acmod = (ac3info >> 11) & 0x7;
972 lfeon = (ac3info >> 10) & 0x1;
973
975 if (lfeon)
979
980 *ast = bsmod;
981 if (st->codecpar->ch_layout.nb_channels > 1 && bsmod == 0x7)
983
984 return 0;
985}
986
987#if CONFIG_IAMFDEC
988static int mov_read_iacb(MOVContext *c, AVIOContext *pb, MOVAtom atom)
989{
990 AVStream *st;
993 AVIOContext *descriptor_pb;
995 IAMFContext *iamf;
997 unsigned descriptors_size;
998 int nb_frames, disposition;
999 int version, ret;
1000
1001 st = get_curr_st(c);
1002 if (!st)
1003 return 0;
1004
1005 if (atom.size < 5)
1006 return AVERROR_INVALIDDATA;
1007
1008 version = avio_r8(pb);
1009 if (version != 1) {
1010 av_log(c->fc, AV_LOG_ERROR, "%s configurationVersion %d",
1011 version < 1 ? "invalid" : "unsupported", version);
1012 return AVERROR_INVALIDDATA;
1013 }
1014
1015 descriptors_size = ffio_read_leb(pb);
1016 if (!descriptors_size || descriptors_size > INT_MAX)
1017 return AVERROR_INVALIDDATA;
1018
1019 sc = st->priv_data;
1020
1021 if (st->codecpar->extradata) {
1022 av_log(c->fc, AV_LOG_WARNING, "ignoring iacb\n");
1023 return 0;
1024 }
1025
1026 sc->iamf = av_mallocz(sizeof(*sc->iamf));
1027 if (!sc->iamf)
1028 return AVERROR(ENOMEM);
1029 iamf = &sc->iamf->iamf;
1030
1031 ret = ff_alloc_extradata(st->codecpar, descriptors_size);
1032 if (ret < 0)
1033 return ret;
1034
1035 ret = avio_read(pb, st->codecpar->extradata, descriptors_size);
1036 if (ret != descriptors_size)
1037 return ret < 0 ? ret : AVERROR_INVALIDDATA;
1038
1039 ffio_init_read_context(&b, st->codecpar->extradata, descriptors_size);
1040 descriptor_pb = &b.pub;
1041
1042 ret = ff_iamfdec_read_descriptors(iamf, descriptor_pb, descriptors_size, c->fc);
1043 if (ret < 0)
1044 return ret;
1045
1046 metadata = st->metadata;
1047 st->metadata = NULL;
1048 start_time = st->start_time;
1049 nb_frames = st->nb_frames;
1050 duration = st->duration;
1051 disposition = st->disposition;
1052
1053 for (int i = 0; i < iamf->nb_audio_elements; i++) {
1054 IAMFAudioElement *audio_element = iamf->audio_elements[i];
1055 const AVIAMFAudioElement *element;
1056 AVStreamGroup *stg =
1058
1059 if (!stg) {
1060 ret = AVERROR(ENOMEM);
1061 goto fail;
1062 }
1063
1065 stg->id = audio_element->audio_element_id;
1066 /* Transfer ownership */
1067 element = stg->params.iamf_audio_element = audio_element->element;
1068 audio_element->element = NULL;
1069
1070 for (int j = 0; j < audio_element->nb_substreams; j++) {
1071 IAMFSubStream *substream = &audio_element->substreams[j];
1072 AVStream *stream;
1073
1074 if (!i && !j) {
1075 if (audio_element->layers[0].substream_count != 1)
1076 disposition &= ~AV_DISPOSITION_DEFAULT;
1077 stream = st;
1078 } else
1079 stream = avformat_new_stream(c->fc, NULL);
1080 if (!stream) {
1081 ret = AVERROR(ENOMEM);
1082 goto fail;
1083 }
1084
1085 stream->start_time = start_time;
1086 stream->nb_frames = nb_frames;
1087 stream->duration = duration;
1088 stream->disposition = disposition;
1089 if (stream != st) {
1090 stream->priv_data = sc;
1091 sc->refcount++;
1092 }
1093
1096 if (i || j) {
1098 if (audio_element->layers[0].substream_count == 1)
1100 }
1101
1102 ret = avcodec_parameters_copy(stream->codecpar, substream->codecpar);
1103 if (ret < 0)
1104 goto fail;
1105
1106 stream->id = substream->audio_substream_id;
1107
1108 avpriv_set_pts_info(st, 64, 1, sc->time_scale);
1109
1111 if (ret < 0)
1112 goto fail;
1113 }
1114
1115 ret = av_dict_copy(&stg->metadata, metadata, 0);
1116 if (ret < 0)
1117 goto fail;
1118 }
1119
1120 for (int i = 0; i < iamf->nb_mix_presentations; i++) {
1121 IAMFMixPresentation *mix_presentation = iamf->mix_presentations[i];
1122 const AVIAMFMixPresentation *mix = mix_presentation->cmix;
1123 AVStreamGroup *stg =
1125
1126 if (!stg) {
1127 ret = AVERROR(ENOMEM);
1128 goto fail;
1129 }
1130
1132 stg->id = mix_presentation->mix_presentation_id;
1133 /* Transfer ownership */
1134 stg->params.iamf_mix_presentation = mix_presentation->mix;
1135 mix_presentation->mix = NULL;
1136
1137 for (int j = 0; j < mix->nb_submixes; j++) {
1138 const AVIAMFSubmix *submix = mix->submixes[j];
1139
1140 for (int k = 0; k < submix->nb_elements; k++) {
1141 const AVIAMFSubmixElement *submix_element = submix->elements[k];
1142 const AVStreamGroup *audio_element = NULL;
1143
1144 for (int l = 0; l < c->fc->nb_stream_groups; l++)
1145 if (c->fc->stream_groups[l]->type == AV_STREAM_GROUP_PARAMS_IAMF_AUDIO_ELEMENT &&
1146 c->fc->stream_groups[l]->id == submix_element->audio_element_id) {
1147 audio_element = c->fc->stream_groups[l];
1148 break;
1149 }
1150 av_assert0(audio_element);
1151
1152 for (int l = 0; l < audio_element->nb_entries; l++) {
1153 ret = avformat_stream_group_add_stream(stg, audio_element->entries[l]->stream);
1154 if (ret < 0 && ret != AVERROR(EEXIST))
1155 goto fail;
1156 }
1157 }
1158 }
1159
1160 ret = av_dict_copy(&stg->metadata, metadata, 0);
1161 if (ret < 0)
1162 goto fail;
1163 }
1164
1165 ret = 0;
1166fail:
1168
1169 return ret;
1170}
1171#endif
1172
1174{
1175 AVStream *st;
1176 int32_t sample_rate;
1177
1178 if (atom.size < 8 || c->fc->nb_streams < 1)
1179 return 0;
1180
1181 st = c->fc->streams[c->fc->nb_streams-1];
1183 av_log(c->fc, AV_LOG_WARNING, "'srat' within non-audio sample entry, skip\n");
1184 return 0;
1185 }
1186
1187 if (!c->isom) {
1188 av_log(c->fc, AV_LOG_WARNING, "'srat' within non-isom, skip\n");
1189 return 0;
1190 }
1191
1192 avio_skip(pb, 4); // version+flags
1193 sample_rate = avio_rb32(pb);
1194 if (sample_rate > 0) {
1195 av_log(c->fc, AV_LOG_DEBUG,
1196 "overwrite sample rate from %d to %d by 'srat'\n",
1197 st->codecpar->sample_rate, sample_rate);
1198 st->codecpar->sample_rate = sample_rate;
1199 } else {
1200 av_log(c->fc, AV_LOG_WARNING,
1201 "ignore invalid sample rate %d in 'srat'\n", sample_rate);
1202 }
1203
1204 return 0;
1205}
1206
1208{
1209 AVStream *st;
1210 AVPacketSideData *sd;
1211 enum AVAudioServiceType *ast;
1212 int eac3info, acmod, lfeon, bsmod;
1213 uint64_t mask;
1214 int ret;
1215
1216 if (c->fc->nb_streams < 1)
1217 return 0;
1218 st = c->fc->streams[c->fc->nb_streams-1];
1219
1220 /* Preserve the complete EC3SpecificBox payload, including optional
1221 * extensions such as E-AC-3 JOC signaling. */
1222 if (atom.size < 5 || (uint64_t)atom.size > (1 << 30))
1223 return AVERROR_INVALIDDATA;
1224 ret = ff_get_extradata(c->fc, st->codecpar, pb, atom.size);
1225 if (ret < 0)
1226 return ret;
1227
1231 sizeof(*ast), 0);
1232 if (!sd)
1233 return AVERROR(ENOMEM);
1234
1235 ast = (enum AVAudioServiceType*)sd->data;
1236
1237 eac3info = AV_RB24(st->codecpar->extradata + 2);
1238 bsmod = (eac3info >> 12) & 0x1f;
1239 acmod = (eac3info >> 9) & 0x7;
1240 lfeon = (eac3info >> 8) & 0x1;
1241
1243 if (lfeon)
1247
1248 *ast = bsmod;
1249 if (st->codecpar->ch_layout.nb_channels > 1 && bsmod == 0x7)
1251
1252 return 0;
1253}
1254
1255/* Maps the DTS `StreamConstruction` field (ETSI TS 102 114 Table E-2) to the
1256 * coarse FFmpeg DTS profile enum. Extension-substream XLL maps to HD_MA;
1257 * extension-substream XXCH, X96, or XBR maps to HD_HRA; core-substream XCH or
1258 * XXCH maps to ES; core-substream X96 maps to 96/24; a core component alone
1259 * maps to DTS; and extension-substream LBR maps to Express. Value 0 (undefined)
1260 * and values outside 1..21 map to AV_PROFILE_UNKNOWN. */
1262{
1263 static const int profile[22] = {
1264 [ 1] = AV_PROFILE_DTS, /* core Core */
1265 [ 2] = AV_PROFILE_DTS_ES, /* core Core + core XCH */
1266 [ 3] = AV_PROFILE_DTS_ES, /* core Core + core XXCH */
1267 [ 4] = AV_PROFILE_DTS_96_24, /* core Core + core X96 */
1268 [ 5] = AV_PROFILE_DTS_HD_HRA, /* core Core + ext XXCH */
1269 [ 6] = AV_PROFILE_DTS_HD_HRA, /* core Core + ext XBR */
1270 [ 7] = AV_PROFILE_DTS_HD_HRA, /* core Core + core XCH + ext XBR */
1271 [ 8] = AV_PROFILE_DTS_HD_HRA, /* core Core + core XXCH + ext XBR */
1272 [ 9] = AV_PROFILE_DTS_HD_HRA, /* core Core + ext XXCH + ext XBR */
1273 [10] = AV_PROFILE_DTS_HD_HRA, /* core Core + ext X96 */
1274 [11] = AV_PROFILE_DTS_HD_HRA, /* core Core + core XCH + ext X96 */
1275 [12] = AV_PROFILE_DTS_HD_HRA, /* core Core + core XXCH + ext X96 */
1276 [13] = AV_PROFILE_DTS_HD_HRA, /* core Core + ext XXCH + ext X96 */
1277 [14] = AV_PROFILE_DTS_HD_MA, /* core Core + ext XLL */
1278 [15] = AV_PROFILE_DTS_HD_MA, /* core Core + core XCH + ext XLL */
1279 [16] = AV_PROFILE_DTS_HD_MA, /* core Core + core X96 + ext XLL */
1280 [17] = AV_PROFILE_DTS_HD_MA, /* ext XLL */
1281 [18] = AV_PROFILE_DTS_EXPRESS, /* ext LBR */
1282 [19] = AV_PROFILE_DTS, /* ext Core */
1283 [20] = AV_PROFILE_DTS_HD_HRA, /* ext Core + ext XXCH */
1284 [21] = AV_PROFILE_DTS_HD_MA, /* ext Core + ext XLL */
1285 };
1286 if (!sc || sc > 21)
1287 return AV_PROFILE_UNKNOWN;
1288 return profile[sc];
1289}
1290
1291/* Maps the 16-bit DTS `ChannelLayout` bitmask (ETSI TS 102 114 Table E-5) to an
1292 * ffmpeg channel mask. Pair bits follow Table 7-10 / DCA_SPEAKER_PAIR_*;
1293 * LwRw (0x0400) and LssRss (0x0800) must not collapse onto SIDE like LsRs. */
1294static uint64_t mov_dts_channel_layout_to_mask(unsigned int code)
1295{
1296 static const struct { unsigned int dts; uint64_t av; } map[] = {
1297 { 0x0001, AV_CH_FRONT_CENTER },
1298 { 0x0002, AV_CH_FRONT_LEFT | AV_CH_FRONT_RIGHT },
1299 { 0x0004, AV_CH_SIDE_LEFT | AV_CH_SIDE_RIGHT },
1300 { 0x0008, AV_CH_LOW_FREQUENCY },
1301 { 0x0010, AV_CH_BACK_CENTER },
1303 { 0x0040, AV_CH_BACK_LEFT | AV_CH_BACK_RIGHT },
1304 { 0x0080, AV_CH_TOP_FRONT_CENTER },
1305 { 0x0100, AV_CH_TOP_CENTER },
1307 { 0x0400, AV_CH_WIDE_LEFT | AV_CH_WIDE_RIGHT },
1309 { 0x1000, AV_CH_LOW_FREQUENCY_2 },
1311 { 0x4000, AV_CH_TOP_BACK_CENTER },
1313 };
1314 uint64_t mask = 0;
1315 int i;
1316 for (i = 0; i < FF_ARRAY_ELEMS(map); i++)
1317 if (code & map[i].dts)
1318 mask |= map[i].av;
1319 return mask;
1320}
1321
1323{
1324#define DDTS_SIZE 20
1326 AVStream *st = NULL;
1327 uint32_t frame_duration_code = 0;
1328 uint32_t channel_layout_code = 0;
1329 uint64_t channel_layout_mask;
1330 unsigned int stream_construction;
1331 unsigned int representation_type;
1332 GetBitContext gb;
1333 int ret;
1334
1335 if ((ret = ffio_read_size(pb, buf, DDTS_SIZE)) < 0)
1336 return ret;
1337
1338 init_get_bits(&gb, buf, 8 * DDTS_SIZE);
1339
1340 if (c->fc->nb_streams < 1) {
1341 return 0;
1342 }
1343 st = c->fc->streams[c->fc->nb_streams-1];
1344
1345 st->codecpar->sample_rate = get_bits_long(&gb, 32);
1346 if (st->codecpar->sample_rate <= 0) {
1347 av_log(c->fc, AV_LOG_ERROR, "Invalid sample rate %d\n", st->codecpar->sample_rate);
1348 return AVERROR_INVALIDDATA;
1349 }
1350 skip_bits_long(&gb, 32); /* max bitrate */
1351 st->codecpar->bit_rate = get_bits_long(&gb, 32);
1353 frame_duration_code = get_bits(&gb, 2);
1354 stream_construction = get_bits(&gb, 5); /* Table E-2 - profile source */
1355 skip_bits(&gb, 1); /* CoreLFEPresent */
1356 skip_bits(&gb, 6); /* CoreLayout */
1357 skip_bits(&gb, 14); /* CoreSize */
1358 skip_bits(&gb, 1); /* StereoDownmix */
1359 representation_type = get_bits(&gb, 3);
1360 channel_layout_code = get_bits(&gb, 16);
1361
1362 st->codecpar->frame_size =
1363 (frame_duration_code == 0) ? 512 :
1364 (frame_duration_code == 1) ? 1024 :
1365 (frame_duration_code == 2) ? 2048 :
1366 (frame_duration_code == 3) ? 4096 : 0;
1367
1368 /* Publish StreamConstruction as codecpar->profile, including for encrypted
1369 * tracks where frame headers cannot be inspected. */
1370 st->codecpar->profile = mov_dts_stream_construction_to_profile(stream_construction);
1371
1372 channel_layout_mask = mov_dts_channel_layout_to_mask(channel_layout_code);
1373 if (channel_layout_mask) {
1375 av_channel_layout_from_mask(&st->codecpar->ch_layout, channel_layout_mask);
1376 } else if (representation_type == 2 || representation_type == 3) {
1379 }
1380
1381 return 0;
1382}
1383
1385{
1386 AVStream *st;
1387
1388 if (c->fc->nb_streams < 1)
1389 return 0;
1390 st = c->fc->streams[c->fc->nb_streams-1];
1391
1392 if (atom.size < 16)
1393 return 0;
1394
1395 /* skip version and flags */
1396 avio_skip(pb, 4);
1397
1398 ff_mov_read_chan(c->fc, pb, st, atom.size - 4);
1399
1400 return 0;
1401}
1402
1404{
1405 int64_t end = av_sat_add64(avio_tell(pb), atom.size);
1406 int version, flags;
1407 int ret;
1408 AVStream *st;
1409
1410 if (c->fc->nb_streams < 1)
1411 return 0;
1412 st = c->fc->streams[c->fc->nb_streams-1];
1413
1414 version = avio_r8(pb);
1415 flags = avio_rb24(pb);
1416 if (version > 1 || flags != 0) {
1417 av_log(c->fc, AV_LOG_WARNING,
1418 "Unsupported 'chnl' box with version %d, flags: %#x\n",
1419 version, flags);
1420 return 0;
1421 }
1422
1423 ret = ff_mov_read_chnl(c->fc, pb, st, version);
1424 if (ret < 0) {
1425 avio_seek(pb, end, SEEK_SET);
1426 return 0;
1427 }
1428
1429 if (avio_tell(pb) != end) {
1430 av_log(c->fc, AV_LOG_WARNING, "skip %" PRId64 " bytes of unknown data inside chnl\n",
1431 end - avio_tell(pb));
1432 avio_seek(pb, end, SEEK_SET);
1433 }
1434 return ret;
1435}
1436
1438{
1439 AVStream *st;
1440 int ret;
1441
1442 st = get_curr_st(c);
1443 if (!st)
1444 return 0;
1445
1446 if ((ret = ff_get_wav_header(c->fc, pb, st->codecpar, atom.size, 0)) < 0)
1447 av_log(c->fc, AV_LOG_WARNING, "get_wav_header failed\n");
1448
1449 return ret;
1450}
1451
1453{
1454 AVStream *st;
1455 HEIFItem *item;
1456 AVPacketSideData *sd;
1457 int width, height, err = 0;
1458 AVRational aperture_width, aperture_height, horiz_off, vert_off;
1459 AVRational pc_x, pc_y;
1460 int64_t top, bottom, left, right;
1461
1462 item = get_heif_item(c, c->cur_item_id);
1463 st = get_curr_st(c);
1464 if (!st)
1465 return 0;
1466
1467 width = st->codecpar->width;
1468 height = st->codecpar->height;
1469 if ((!width || !height) && item) {
1470 width = item->width;
1471 height = item->height;
1472 }
1473 if (!width || !height) {
1474 err = AVERROR_INVALIDDATA;
1475 goto fail;
1476 }
1477
1478 aperture_width.num = avio_rb32(pb);
1479 aperture_width.den = avio_rb32(pb);
1480 aperture_height.num = avio_rb32(pb);
1481 aperture_height.den = avio_rb32(pb);
1482
1483 horiz_off.num = avio_rb32(pb);
1484 horiz_off.den = avio_rb32(pb);
1485 vert_off.num = avio_rb32(pb);
1486 vert_off.den = avio_rb32(pb);
1487
1488 if (aperture_width.num < 0 || aperture_width.den <= 0 ||
1489 aperture_height.num < 0 || aperture_height.den <= 0 ||
1490 horiz_off.den <= 0 || vert_off.den <= 0) {
1491 err = AVERROR_INVALIDDATA;
1492 goto fail;
1493 }
1494 if ((av_cmp_q((AVRational) { width, 1 }, aperture_width) < 0) ||
1495 (av_cmp_q((AVRational) { height, 1 }, aperture_height) < 0)) {
1496 err = AVERROR_INVALIDDATA;
1497 goto fail;
1498 }
1499 av_log(c->fc, AV_LOG_TRACE, "clap: apertureWidth %d/%d, apertureHeight %d/%d "
1500 "horizOff %d/%d vertOff %d/%d\n",
1501 aperture_width.num, aperture_width.den, aperture_height.num, aperture_height.den,
1502 horiz_off.num, horiz_off.den, vert_off.num, vert_off.den);
1503
1504 pc_x = av_mul_q((AVRational) { width - 1, 1 }, (AVRational) { 1, 2 });
1505 pc_x = av_add_q(pc_x, horiz_off);
1506 pc_y = av_mul_q((AVRational) { height - 1, 1 }, (AVRational) { 1, 2 });
1507 pc_y = av_add_q(pc_y, vert_off);
1508
1509 aperture_width = av_sub_q(aperture_width, (AVRational) { 1, 1 });
1510 aperture_width = av_mul_q(aperture_width, (AVRational) { 1, 2 });
1511 aperture_height = av_sub_q(aperture_height, (AVRational) { 1, 1 });
1512 aperture_height = av_mul_q(aperture_height, (AVRational) { 1, 2 });
1513
1514 left = av_q2d(av_sub_q(pc_x, aperture_width));
1515 right = av_q2d(av_add_q(pc_x, aperture_width));
1516 top = av_q2d(av_sub_q(pc_y, aperture_height));
1517 bottom = av_q2d(av_add_q(pc_y, aperture_height));
1518
1519 if (top < 0 || bottom < 0 || bottom > (height - 1) ||
1520 left < 0 || right < 0 || right > (width - 1)) {
1521 err = AVERROR_INVALIDDATA;
1522 goto fail;
1523 }
1524
1525 bottom = height - 1 - bottom;
1526 right = width - 1 - right;
1527
1528 if (!(left | right | top | bottom))
1529 return 0;
1530
1531 if ((left + right) >= width ||
1532 (top + bottom) >= height) {
1533 err = AVERROR_INVALIDDATA;
1534 goto fail;
1535 }
1536
1540 sizeof(uint32_t) * 4, 0);
1541 if (!sd)
1542 return AVERROR(ENOMEM);
1543
1544 AV_WL32A(sd->data, top);
1545 AV_WL32A(sd->data + 4, bottom);
1546 AV_WL32A(sd->data + 8, left);
1547 AV_WL32A(sd->data + 12, right);
1548
1549fail:
1550 if (err < 0) {
1551 int explode = !!(c->fc->error_recognition & AV_EF_EXPLODE);
1552 av_log(c->fc, explode ? AV_LOG_ERROR : AV_LOG_WARNING, "Invalid clap box\n");
1553 if (!explode)
1554 err = 0;
1555 }
1556
1557 return err;
1558}
1559
1560/* This atom overrides any previously set aspect ratio */
1562{
1563 const int num = avio_rb32(pb);
1564 const int den = avio_rb32(pb);
1565 AVStream *st;
1566 MOVStreamContext *sc;
1567
1568 if (c->fc->nb_streams < 1)
1569 return 0;
1570 st = c->fc->streams[c->fc->nb_streams-1];
1571 sc = st->priv_data;
1572
1573 av_log(c->fc, AV_LOG_TRACE, "pasp: hSpacing %d, vSpacing %d\n", num, den);
1574
1575 if (den != 0) {
1576 sc->h_spacing = num;
1577 sc->v_spacing = den;
1578 }
1579 return 0;
1580}
1581
1582/* this atom contains actual media data */
1584{
1585 if (atom.size == 0) /* wrong one (MP4) */
1586 return 0;
1587 c->found_mdat=1;
1588 return 0; /* now go for moov */
1589}
1590
1591#define DRM_BLOB_SIZE 56
1592
1594{
1595 uint8_t intermediate_key[20];
1596 uint8_t intermediate_iv[20];
1597 uint8_t input[64];
1598 uint8_t output[64];
1599 uint8_t file_checksum[20];
1600 uint8_t calculated_checksum[20];
1601 char checksum_string[2 * sizeof(file_checksum) + 1];
1602 struct AVSHA *sha;
1603 int i;
1604 int ret = 0;
1605 uint8_t *activation_bytes = c->activation_bytes;
1606 uint8_t *fixed_key = c->audible_fixed_key;
1607
1608 c->aax_mode = 1;
1609
1610 sha = av_sha_alloc();
1611 if (!sha)
1612 return AVERROR(ENOMEM);
1613 av_free(c->aes_decrypt);
1614 c->aes_decrypt = av_aes_alloc();
1615 if (!c->aes_decrypt) {
1616 ret = AVERROR(ENOMEM);
1617 goto fail;
1618 }
1619
1620 /* drm blob processing */
1621 avio_read(pb, output, 8); // go to offset 8, absolute position 0x251
1622 avio_read(pb, input, DRM_BLOB_SIZE);
1623 avio_read(pb, output, 4); // go to offset 4, absolute position 0x28d
1624 ret = ffio_read_size(pb, file_checksum, 20);
1625 if (ret < 0)
1626 goto fail;
1627
1628 // required by external tools
1629 ff_data_to_hex(checksum_string, file_checksum, sizeof(file_checksum), 1);
1630 av_log(c->fc, AV_LOG_INFO, "[aax] file checksum == %s\n", checksum_string);
1631
1632 /* verify activation data */
1633 if (!activation_bytes) {
1634 av_log(c->fc, AV_LOG_WARNING, "[aax] activation_bytes option is missing!\n");
1635 ret = 0; /* allow ffprobe to continue working on .aax files */
1636 goto fail;
1637 }
1638 if (c->activation_bytes_size != 4) {
1639 av_log(c->fc, AV_LOG_FATAL, "[aax] activation_bytes value needs to be 4 bytes!\n");
1640 ret = AVERROR(EINVAL);
1641 goto fail;
1642 }
1643
1644 /* verify fixed key */
1645 if (c->audible_fixed_key_size != 16) {
1646 av_log(c->fc, AV_LOG_FATAL, "[aax] audible_fixed_key value needs to be 16 bytes!\n");
1647 ret = AVERROR(EINVAL);
1648 goto fail;
1649 }
1650
1651 /* AAX (and AAX+) key derivation */
1652 av_sha_init(sha, 160);
1653 av_sha_update(sha, fixed_key, 16);
1654 av_sha_update(sha, activation_bytes, 4);
1655 av_sha_final(sha, intermediate_key);
1656 av_sha_init(sha, 160);
1657 av_sha_update(sha, fixed_key, 16);
1658 av_sha_update(sha, intermediate_key, 20);
1659 av_sha_update(sha, activation_bytes, 4);
1660 av_sha_final(sha, intermediate_iv);
1661 av_sha_init(sha, 160);
1662 av_sha_update(sha, intermediate_key, 16);
1663 av_sha_update(sha, intermediate_iv, 16);
1664 av_sha_final(sha, calculated_checksum);
1665 if (memcmp(calculated_checksum, file_checksum, 20)) { // critical error
1666 av_log(c->fc, AV_LOG_ERROR, "[aax] mismatch in checksums!\n");
1668 goto fail;
1669 }
1670 av_aes_init(c->aes_decrypt, intermediate_key, 128, 1);
1671 av_aes_crypt(c->aes_decrypt, output, input, DRM_BLOB_SIZE >> 4, intermediate_iv, 1);
1672 for (i = 0; i < 4; i++) {
1673 // file data (in output) is stored in big-endian mode
1674 if (activation_bytes[i] != output[3 - i]) { // critical error
1675 av_log(c->fc, AV_LOG_ERROR, "[aax] error in drm blob decryption!\n");
1677 goto fail;
1678 }
1679 }
1680 memcpy(c->file_key, output + 8, 16);
1681 memcpy(input, output + 26, 16);
1682 av_sha_init(sha, 160);
1683 av_sha_update(sha, input, 16);
1684 av_sha_update(sha, c->file_key, 16);
1685 av_sha_update(sha, fixed_key, 16);
1686 av_sha_final(sha, c->file_iv);
1687
1688fail:
1689 av_free(sha);
1690
1691 return ret;
1692}
1693
1695{
1696 if (c->audible_key_size != 16) {
1697 av_log(c->fc, AV_LOG_FATAL, "[aaxc] audible_key value needs to be 16 bytes!\n");
1698 return AVERROR(EINVAL);
1699 }
1700
1701 if (c->audible_iv_size != 16) {
1702 av_log(c->fc, AV_LOG_FATAL, "[aaxc] audible_iv value needs to be 16 bytes!\n");
1703 return AVERROR(EINVAL);
1704 }
1705
1706 c->aes_decrypt = av_aes_alloc();
1707 if (!c->aes_decrypt) {
1708 return AVERROR(ENOMEM);
1709 }
1710
1711 memcpy(c->file_key, c->audible_key, 16);
1712 memcpy(c->file_iv, c->audible_iv, 16);
1713 c->aax_mode = 1;
1714
1715 return 0;
1716}
1717
1718// Audible AAX (and AAX+) bytestream decryption
1719static int aax_filter(uint8_t *input, int size, MOVContext *c)
1720{
1721 int blocks = 0;
1722 unsigned char iv[16];
1723
1724 memcpy(iv, c->file_iv, 16); // iv is overwritten
1725 blocks = size >> 4; // trailing bytes are not encrypted!
1726 av_aes_init(c->aes_decrypt, c->file_key, 128, 1);
1727 av_aes_crypt(c->aes_decrypt, input, input, blocks, iv, 1);
1728
1729 return 0;
1730}
1731
1732/* read major brand, minor version and compatible brands and store them as metadata */
1734{
1735 uint32_t minor_ver;
1736 int comp_brand_size;
1737 char* comp_brands_str;
1738 uint8_t type[5] = {0};
1739 int ret = ffio_read_size(pb, type, 4);
1740 if (ret < 0)
1741 return ret;
1742 if (c->fc->nb_streams) {
1743 if (c->fc->strict_std_compliance >= FF_COMPLIANCE_STRICT)
1744 return AVERROR_INVALIDDATA;
1745 av_log(c->fc, AV_LOG_DEBUG, "Ignoring duplicate FTYP\n");
1746 return 0;
1747 }
1748
1749 if (strcmp(type, "qt "))
1750 c->isom = 1;
1751 av_log(c->fc, AV_LOG_DEBUG, "ISO: File Type Major Brand: %.4s\n",(char *)&type);
1752 av_dict_set(&c->fc->metadata, "major_brand", type, 0);
1753 minor_ver = avio_rb32(pb); /* minor version */
1754 av_dict_set_int(&c->fc->metadata, "minor_version", minor_ver, 0);
1755
1756 comp_brand_size = atom.size - 8;
1757 if (comp_brand_size < 0 || comp_brand_size == INT_MAX)
1758 return AVERROR_INVALIDDATA;
1759 comp_brands_str = av_malloc(comp_brand_size + 1); /* Add null terminator */
1760 if (!comp_brands_str)
1761 return AVERROR(ENOMEM);
1762
1763 ret = ffio_read_size(pb, comp_brands_str, comp_brand_size);
1764 if (ret < 0) {
1765 av_freep(&comp_brands_str);
1766 return ret;
1767 }
1768 comp_brands_str[comp_brand_size] = 0;
1769 av_dict_set(&c->fc->metadata, "compatible_brands",
1770 comp_brands_str, AV_DICT_DONT_STRDUP_VAL);
1771
1772 // Logic for handling Audible's .aaxc files
1773 if (!strcmp(type, "aaxc")) {
1775 }
1776
1777 return 0;
1778}
1779
1780/* this atom should contain all header atoms */
1782{
1783 int ret;
1784
1785 if (c->found_moov) {
1786 av_log(c->fc, AV_LOG_WARNING, "Found duplicated MOOV Atom. Skipped it\n");
1787 avio_skip(pb, atom.size);
1788 return 0;
1789 }
1790
1791 if ((ret = mov_read_default(c, pb, atom)) < 0)
1792 return ret;
1793 /* we parsed the 'moov' atom, we can terminate the parsing as soon as we find the 'mdat' */
1794 /* so we don't parse the whole file if over a network */
1795 c->found_moov=1;
1796 return 0; /* now go for mdat */
1797}
1798
1800 MOVFragmentIndex *frag_index,
1801 int index,
1802 int id)
1803{
1804 int i;
1805 MOVFragmentIndexItem * item;
1806
1807 if (index < 0 || index >= frag_index->nb_items)
1808 return NULL;
1809 item = &frag_index->item[index];
1810 for (i = 0; i < item->nb_stream_info; i++)
1811 if (item->stream_info[i].id == id)
1812 return &item->stream_info[i];
1813
1814 // This shouldn't happen
1815 return NULL;
1816}
1817
1818static void set_frag_stream(MOVFragmentIndex *frag_index, int id)
1819{
1820 int i;
1821 MOVFragmentIndexItem * item;
1822
1823 if (frag_index->current < 0 ||
1824 frag_index->current >= frag_index->nb_items)
1825 return;
1826
1827 item = &frag_index->item[frag_index->current];
1828 for (i = 0; i < item->nb_stream_info; i++)
1829 if (item->stream_info[i].id == id) {
1830 item->current = i;
1831 return;
1832 }
1833
1834 // id not found. This shouldn't happen.
1835 item->current = -1;
1836}
1837
1839 MOVFragmentIndex *frag_index)
1840{
1842 if (frag_index->current < 0 ||
1843 frag_index->current >= frag_index->nb_items)
1844 return NULL;
1845
1846 item = &frag_index->item[frag_index->current];
1847 if (item->current >= 0 && item->current < item->nb_stream_info)
1848 return &item->stream_info[item->current];
1849
1850 // This shouldn't happen
1851 return NULL;
1852}
1853
1855{
1856 int a, b, m;
1857 int64_t moof_offset;
1858
1859 // Optimize for appending new entries
1860 if (!frag_index->nb_items ||
1861 frag_index->item[frag_index->nb_items - 1].moof_offset < offset)
1862 return frag_index->nb_items;
1863
1864 a = -1;
1865 b = frag_index->nb_items;
1866
1867 while (b - a > 1) {
1868 m = (a + b) >> 1;
1869 moof_offset = frag_index->item[m].moof_offset;
1870 if (moof_offset >= offset)
1871 b = m;
1872 if (moof_offset <= offset)
1873 a = m;
1874 }
1875 return b;
1876}
1877
1879{
1880 av_assert0(frag_stream_info);
1881 if (frag_stream_info->sidx_pts != AV_NOPTS_VALUE)
1882 return frag_stream_info->sidx_pts;
1883 if (frag_stream_info->first_tfra_pts != AV_NOPTS_VALUE)
1884 return frag_stream_info->first_tfra_pts;
1885 return frag_stream_info->tfdt_dts;
1886}
1887
1889 MOVFragmentIndex *frag_index, int index)
1890{
1891 MOVFragmentStreamInfo * frag_stream_info;
1892 MOVStreamContext *sc = dst_st->priv_data;
1893 int64_t timestamp;
1894 int i, j;
1895
1896 // If the stream is referenced by any sidx, limit the search
1897 // to fragments that referenced this stream in the sidx
1898 if (sc->has_sidx) {
1899 frag_stream_info = get_frag_stream_info(frag_index, index, sc->id);
1900 if (!frag_stream_info)
1901 return AV_NOPTS_VALUE;
1902 if (frag_stream_info->sidx_pts != AV_NOPTS_VALUE)
1903 return frag_stream_info->sidx_pts;
1904 if (frag_stream_info->first_tfra_pts != AV_NOPTS_VALUE)
1905 return frag_stream_info->first_tfra_pts;
1906 return frag_stream_info->sidx_pts;
1907 }
1908
1909 for (i = 0; i < frag_index->item[index].nb_stream_info; i++) {
1910 if (dst_st->id != frag_index->item[index].stream_info[i].id)
1911 continue;
1912 AVStream *frag_stream = NULL;
1913 frag_stream_info = &frag_index->item[index].stream_info[i];
1914 for (j = 0; j < s->nb_streams; j++) {
1915 MOVStreamContext *sc2 = s->streams[j]->priv_data;
1916 if (sc2->id == frag_stream_info->id)
1917 frag_stream = s->streams[j];
1918 }
1919 if (!frag_stream) {
1920 av_log(s, AV_LOG_WARNING, "No stream matching sidx ID found.\n");
1921 continue;
1922 }
1923 timestamp = get_stream_info_time(frag_stream_info);
1924 if (timestamp != AV_NOPTS_VALUE)
1925 return av_rescale_q(timestamp, frag_stream->time_base, dst_st->time_base);
1926 }
1927 return AV_NOPTS_VALUE;
1928}
1929
1931 AVStream *st, int64_t timestamp)
1932{
1933 int a, b, m, m0;
1934 int64_t frag_time;
1935
1936 a = -1;
1937 b = frag_index->nb_items;
1938
1939 while (b - a > 1) {
1940 m0 = m = (a + b) >> 1;
1941
1942 while (m < b &&
1943 (frag_time = get_frag_time(s, st, frag_index, m)) == AV_NOPTS_VALUE)
1944 m++;
1945
1946 if (m < b && frag_time <= timestamp)
1947 a = m;
1948 else
1949 b = m0;
1950 }
1951
1952 return a;
1953}
1954
1956{
1957 int index, i;
1958 MOVFragmentIndexItem * item;
1959 MOVFragmentStreamInfo * frag_stream_info;
1960
1961 // If moof_offset already exists in frag_index, return index to it
1962 index = search_frag_moof_offset(&c->frag_index, offset);
1963 if (index < c->frag_index.nb_items &&
1964 c->frag_index.item[index].moof_offset == offset)
1965 return index;
1966
1967 // offset is not yet in frag index.
1968 // Insert new item at index (sorted by moof offset)
1969 item = av_fast_realloc(c->frag_index.item,
1970 &c->frag_index.allocated_size,
1971 (c->frag_index.nb_items + 1) *
1972 sizeof(*c->frag_index.item));
1973 if (!item)
1974 return -1;
1975 c->frag_index.item = item;
1976
1977 frag_stream_info = av_realloc_array(NULL, c->fc->nb_streams,
1978 sizeof(*item->stream_info));
1979 if (!frag_stream_info)
1980 return -1;
1981
1982 for (i = 0; i < c->fc->nb_streams; i++) {
1983 // Avoid building frag index if streams lack track id.
1984 MOVStreamContext *sc = c->fc->streams[i]->priv_data;
1985 if (sc->id < 0) {
1986 av_free(frag_stream_info);
1987 return AVERROR_INVALIDDATA;
1988 }
1989
1990 frag_stream_info[i].id = sc->id;
1991 frag_stream_info[i].sidx_pts = AV_NOPTS_VALUE;
1992 frag_stream_info[i].tfdt_dts = AV_NOPTS_VALUE;
1993 frag_stream_info[i].next_trun_dts = AV_NOPTS_VALUE;
1994 frag_stream_info[i].first_tfra_pts = AV_NOPTS_VALUE;
1995 frag_stream_info[i].index_base = -1;
1996 frag_stream_info[i].index_entry = -1;
1997 frag_stream_info[i].encryption_index = NULL;
1998 frag_stream_info[i].stsd_id = -1;
1999 }
2000
2001 if (index < c->frag_index.nb_items)
2002 memmove(c->frag_index.item + index + 1, c->frag_index.item + index,
2003 (c->frag_index.nb_items - index) * sizeof(*c->frag_index.item));
2004 if (index <= c->frag_index.current)
2005 c->frag_index.current++;
2006
2007 item = &c->frag_index.item[index];
2008 item->headers_read = 0;
2009 item->current = 0;
2010 item->nb_stream_info = c->fc->nb_streams;
2011 item->moof_offset = offset;
2012 item->stream_info = frag_stream_info;
2013 c->frag_index.nb_items++;
2014
2015 return index;
2016}
2017
2018static void fix_frag_index_entries(MOVFragmentIndex *frag_index, int index,
2019 int id, int entries)
2020{
2021 int i;
2022 MOVFragmentStreamInfo * frag_stream_info;
2023
2024 if (index < 0)
2025 return;
2026 for (i = index; i < frag_index->nb_items; i++) {
2027 frag_stream_info = get_frag_stream_info(frag_index, i, id);
2028 if (frag_stream_info && frag_stream_info->index_entry >= 0)
2029 frag_stream_info->index_entry += entries;
2030 }
2031}
2032
2034{
2035 // Set by mov_read_tfhd(). mov_read_trun() will reject files missing tfhd.
2036 c->fragment.found_tfhd = 0;
2037
2038 if (!c->has_looked_for_mfra && c->use_mfra_for > 0) {
2039 c->has_looked_for_mfra = 1;
2040 if (pb->seekable & AVIO_SEEKABLE_NORMAL) {
2041 int ret;
2042 av_log(c->fc, AV_LOG_VERBOSE, "stream has moof boxes, will look "
2043 "for a mfra\n");
2044 if ((ret = mov_read_mfra(c, pb)) < 0) {
2045 av_log(c->fc, AV_LOG_VERBOSE, "found a moof box but failed to "
2046 "read the mfra (may be a live ismv)\n");
2047 }
2048 } else {
2049 av_log(c->fc, AV_LOG_VERBOSE, "found a moof box but stream is not "
2050 "seekable, can not look for mfra\n");
2051 }
2052 }
2053 c->fragment.moof_offset = c->fragment.implicit_offset = avio_tell(pb) - 8;
2054 av_log(c->fc, AV_LOG_TRACE, "moof offset %"PRIx64"\n", c->fragment.moof_offset);
2055 c->frag_index.current = update_frag_index(c, c->fragment.moof_offset);
2056 return mov_read_default(c, pb, atom);
2057}
2058
2060{
2061 int64_t time;
2062 if (version == 1) {
2063 time = avio_rb64(pb);
2064 avio_rb64(pb);
2065 if (time < 0) {
2066 av_log(c->fc, AV_LOG_DEBUG, "creation_time is negative\n");
2067 return;
2068 }
2069 } else {
2070 time = avio_rb32(pb);
2071 avio_rb32(pb); /* modification time */
2072 if (time > 0 && time < 2082844800) {
2073 av_log(c->fc, AV_LOG_WARNING, "Detected creation time before 1970, parsing as unix timestamp.\n");
2074 time += 2082844800;
2075 }
2076 }
2077 if (time) {
2078 time -= 2082844800; /* seconds between 1904-01-01 and Epoch */
2079
2080 if ((int64_t)(time * 1000000ULL) / 1000000 != time) {
2081 av_log(c->fc, AV_LOG_DEBUG, "creation_time is not representable\n");
2082 return;
2083 }
2084
2085 ff_dict_set_timestamp(metadata, "creation_time", time * 1000000);
2086 }
2087}
2088
2090{
2091 AVStream *st;
2092 MOVStreamContext *sc;
2093 int version;
2094 char language[4] = {0};
2095 unsigned lang;
2096
2097 if (c->fc->nb_streams < 1)
2098 return 0;
2099 st = c->fc->streams[c->fc->nb_streams-1];
2100 sc = st->priv_data;
2101
2102 if (sc->time_scale) {
2103 av_log(c->fc, AV_LOG_ERROR, "Multiple mdhd?\n");
2104 return AVERROR_INVALIDDATA;
2105 }
2106
2107 version = avio_r8(pb);
2108 if (version > 1) {
2109 avpriv_request_sample(c->fc, "Version %d", version);
2110 return AVERROR_PATCHWELCOME;
2111 }
2112 avio_rb24(pb); /* flags */
2114
2115 sc->time_scale = avio_rb32(pb);
2116 if (sc->time_scale <= 0) {
2117 av_log(c->fc, AV_LOG_ERROR, "Invalid mdhd time scale %d, defaulting to 1\n", sc->time_scale);
2118 sc->time_scale = 1;
2119 }
2120 st->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
2121
2122 if ((version == 1 && st->duration == UINT64_MAX) ||
2123 (version != 1 && st->duration == UINT32_MAX)) {
2124 st->duration = 0;
2125 }
2126
2127 lang = avio_rb16(pb); /* language */
2128 if (ff_mov_lang_to_iso639(lang, language))
2129 av_dict_set(&st->metadata, "language", language, 0);
2130 avio_rb16(pb); /* quality */
2131
2132 return 0;
2133}
2134
2136{
2137 int i;
2138 int version = avio_r8(pb); /* version */
2139 avio_rb24(pb); /* flags */
2140
2141 mov_metadata_creation_time(c, pb, &c->fc->metadata, version);
2142 c->time_scale = avio_rb32(pb); /* time scale */
2143 if (c->time_scale <= 0) {
2144 av_log(c->fc, AV_LOG_ERROR, "Invalid mvhd time scale %d, defaulting to 1\n", c->time_scale);
2145 c->time_scale = 1;
2146 }
2147 av_log(c->fc, AV_LOG_TRACE, "time scale = %i\n", c->time_scale);
2148
2149 c->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
2150 avio_rb32(pb); /* preferred scale */
2151
2152 avio_rb16(pb); /* preferred volume */
2153
2154 avio_skip(pb, 10); /* reserved */
2155
2156 /* movie display matrix, store it in main context and use it later on */
2157 for (i = 0; i < 3; i++) {
2158 c->movie_display_matrix[i][0] = avio_rb32(pb); // 16.16 fixed point
2159 c->movie_display_matrix[i][1] = avio_rb32(pb); // 16.16 fixed point
2160 c->movie_display_matrix[i][2] = avio_rb32(pb); // 2.30 fixed point
2161 }
2162
2163 avio_rb32(pb); /* preview time */
2164 avio_rb32(pb); /* preview duration */
2165 avio_rb32(pb); /* poster time */
2166 avio_rb32(pb); /* selection time */
2167 avio_rb32(pb); /* selection duration */
2168 avio_rb32(pb); /* current time */
2169 avio_rb32(pb); /* next track ID */
2170
2171 return 0;
2172}
2173
2175{
2176 AVStream *st = get_curr_st(c);
2177
2178 if (!st)
2179 return;
2180
2181 switch (st->codecpar->codec_id) {
2184 break;
2187 break;
2190 break;
2193 break;
2196 break;
2197 default:
2198 break;
2199 }
2200}
2201
2203{
2204 int little_endian = avio_rb16(pb) & 0xFF;
2205 av_log(c->fc, AV_LOG_TRACE, "enda %d\n", little_endian);
2206 if (little_endian == 1)
2208 return 0;
2209}
2210
2212{
2213 int format_flags;
2214 int version, flags;
2215 int pcm_sample_size;
2216 AVFormatContext *fc = c->fc;
2217 AVStream *st;
2218 MOVStreamContext *sc;
2219
2220 if (atom.size < 6) {
2221 av_log(c->fc, AV_LOG_ERROR, "Empty pcmC box\n");
2222 return AVERROR_INVALIDDATA;
2223 }
2224
2225 version = avio_r8(pb);
2226 flags = avio_rb24(pb);
2227
2228 if (version != 0 || flags != 0) {
2229 av_log(c->fc, AV_LOG_ERROR,
2230 "Unsupported 'pcmC' box with version %d, flags: %x",
2231 version, flags);
2232 return AVERROR_INVALIDDATA;
2233 }
2234
2235 format_flags = avio_r8(pb);
2236 pcm_sample_size = avio_r8(pb);
2237
2238 st = get_curr_st(c);
2239 if (!st)
2240 return 0;
2241 sc = st->priv_data;
2242
2243 if (sc->format == MOV_MP4_FPCM_TAG) {
2244 switch (pcm_sample_size) {
2245 case 32:
2247 break;
2248 case 64:
2250 break;
2251 default:
2252 av_log(fc, AV_LOG_ERROR, "invalid pcm_sample_size %d for %s\n",
2253 pcm_sample_size,
2254 av_fourcc2str(sc->format));
2255 return AVERROR_INVALIDDATA;
2256 }
2257 } else if (sc->format == MOV_MP4_IPCM_TAG) {
2258 switch (pcm_sample_size) {
2259 case 16:
2261 break;
2262 case 24:
2264 break;
2265 case 32:
2267 break;
2268 default:
2269 av_log(fc, AV_LOG_ERROR, "invalid pcm_sample_size %d for %s\n",
2270 pcm_sample_size,
2271 av_fourcc2str(sc->format));
2272 return AVERROR_INVALIDDATA;
2273 }
2274 } else {
2275 av_log(fc, AV_LOG_ERROR, "'pcmC' with invalid sample entry '%s'\n",
2276 av_fourcc2str(sc->format));
2277 return AVERROR_INVALIDDATA;
2278 }
2279
2280 if (format_flags & 1) // indicates little-endian format. If not present, big-endian format is used
2283
2284 return 0;
2285}
2286
2288{
2289 AVStream *st;
2290 HEIFItem *item = NULL;
2291 char color_parameter_type[5] = { 0 };
2292 uint16_t color_primaries, color_trc, color_matrix;
2293 int ret;
2294
2295 st = get_curr_st(c);
2296 if (!st) {
2297 item = get_heif_item(c, c->cur_item_id);
2298 if (!item)
2299 return 0;
2300 }
2301
2302 ret = ffio_read_size(pb, color_parameter_type, 4);
2303 if (ret < 0)
2304 return ret;
2305 if (strncmp(color_parameter_type, "nclx", 4) &&
2306 strncmp(color_parameter_type, "nclc", 4) &&
2307 strncmp(color_parameter_type, "prof", 4)) {
2308 av_log(c->fc, AV_LOG_WARNING, "unsupported color_parameter_type %s\n",
2309 color_parameter_type);
2310 return 0;
2311 }
2312
2313 if (!strncmp(color_parameter_type, "prof", 4)) {
2314 AVPacketSideData *sd;
2315 uint8_t *icc_profile;
2316 if (st) {
2320 atom.size - 4, 0);
2321 if (!sd)
2322 return AVERROR(ENOMEM);
2323 icc_profile = sd->data;
2324 } else {
2325 if (c->heif_icc_profile_items >= c->fc->max_streams) {
2326 av_log(c->fc, AV_LOG_WARNING,
2327 "HEIF ICC profile copies exceed cap %d; ignoring further items\n",
2328 c->fc->max_streams);
2329 return 0;
2330 }
2331 av_freep(&item->icc_profile);
2332 icc_profile = item->icc_profile = av_malloc(atom.size - 4);
2333 if (!icc_profile) {
2334 item->icc_profile_size = 0;
2335 return AVERROR(ENOMEM);
2336 }
2337 item->icc_profile_size = atom.size - 4;
2338 c->heif_icc_profile_items++;
2339 }
2340 ret = ffio_read_size(pb, icc_profile, atom.size - 4);
2341 if (ret < 0)
2342 return ret;
2343 if (st)
2344 ((MOVStreamContext *)st->priv_data)->stsd_colr_trc = 1;
2345 } else if (st) {
2347 color_trc = avio_rb16(pb);
2348 color_matrix = avio_rb16(pb);
2349
2350 av_log(c->fc, AV_LOG_TRACE,
2351 "%s: pri %d trc %d matrix %d",
2352 color_parameter_type, color_primaries, color_trc, color_matrix);
2353
2354 if (!strncmp(color_parameter_type, "nclx", 4)) {
2355 uint8_t color_range = avio_r8(pb) >> 7;
2356 av_log(c->fc, AV_LOG_TRACE, " full %"PRIu8"", color_range);
2357 if (color_range)
2359 else
2361 }
2362
2363 // Reserved and unassigned values carry no colour information
2368 if (color_trc == AVCOL_TRC_RESERVED0 ||
2369 color_trc == AVCOL_TRC_RESERVED ||
2370 !av_color_transfer_name(color_trc))
2371 color_trc = AVCOL_TRC_UNSPECIFIED;
2372 if (color_matrix == AVCOL_SPC_RESERVED ||
2373 !av_color_space_name(color_matrix))
2374 color_matrix = AVCOL_SPC_UNSPECIFIED;
2375
2377 st->codecpar->color_trc = color_trc;
2378 ((MOVStreamContext *)st->priv_data)->stsd_colr_trc = color_trc != AVCOL_TRC_UNSPECIFIED;
2379 st->codecpar->color_space = color_matrix;
2380 av_log(c->fc, AV_LOG_TRACE, "\n");
2381 }
2382 return 0;
2383}
2384
2386{
2387 AVStream *st = get_curr_st(c);
2388 MOVStreamContext *sc;
2389 double gamma;
2390
2391 if (!st || atom.size < 4)
2392 return 0;
2393 sc = st->priv_data;
2394
2395 gamma = avio_rb32(pb) / 65536.0;
2396 av_log(c->fc, AV_LOG_TRACE, "gama %f\n", gamma);
2397
2398 if (fabs(gamma - 2.2) < 0.01)
2400 else if (fabs(gamma - 2.8) < 0.01)
2402 return 0;
2403}
2404
2406{
2407 AVStream *st;
2408 unsigned mov_field_order;
2409 enum AVFieldOrder decoded_field_order = AV_FIELD_UNKNOWN;
2410
2411 if (c->fc->nb_streams < 1) // will happen with jp2 files
2412 return 0;
2413 st = c->fc->streams[c->fc->nb_streams-1];
2414 if (atom.size < 2)
2415 return AVERROR_INVALIDDATA;
2416 mov_field_order = avio_rb16(pb);
2417 if ((mov_field_order & 0xFF00) == 0x0100)
2418 decoded_field_order = AV_FIELD_PROGRESSIVE;
2419 else if ((mov_field_order & 0xFF00) == 0x0200) {
2420 switch (mov_field_order & 0xFF) {
2421 case 0x01: decoded_field_order = AV_FIELD_TT;
2422 break;
2423 case 0x06: decoded_field_order = AV_FIELD_BB;
2424 break;
2425 case 0x09: decoded_field_order = AV_FIELD_TB;
2426 break;
2427 case 0x0E: decoded_field_order = AV_FIELD_BT;
2428 break;
2429 }
2430 }
2431 if (decoded_field_order == AV_FIELD_UNKNOWN && mov_field_order) {
2432 av_log(c->fc, AV_LOG_ERROR, "Unknown MOV field order 0x%04x\n", mov_field_order);
2433 }
2434 st->codecpar->field_order = decoded_field_order;
2435
2436 return 0;
2437}
2438
2440{
2441 int err = 0;
2442 uint64_t size = (uint64_t)par->extradata_size + atom.size + 8 + AV_INPUT_BUFFER_PADDING_SIZE;
2443 if (size > INT_MAX || (uint64_t)atom.size > INT_MAX)
2444 return AVERROR_INVALIDDATA;
2445 if ((err = av_reallocp(&par->extradata, size)) < 0) {
2446 par->extradata_size = 0;
2447 return err;
2448 }
2450 return 0;
2451}
2452
2453/* Read a whole atom into the extradata return the size of the atom read, possibly truncated if != atom.size */
2455 AVCodecParameters *par, uint8_t *buf)
2456{
2457 int64_t result = atom.size;
2458 int err;
2459
2460 AV_WB32(buf , atom.size + 8);
2461 AV_WL32(buf + 4, atom.type);
2462 err = ffio_read_size(pb, buf + 8, atom.size);
2463 if (err < 0) {
2464 par->extradata_size -= atom.size;
2465 return err;
2466 } else if (err < atom.size) {
2467 av_log(c->fc, AV_LOG_WARNING, "truncated extradata\n");
2468 par->extradata_size -= atom.size - err;
2469 result = err;
2470 }
2471 memset(buf + 8 + err, 0, AV_INPUT_BUFFER_PADDING_SIZE);
2472 return result;
2473}
2474
2475/* FIXME modify QDM2/SVQ3/H.264 decoders to take full atom as extradata */
2477 enum AVCodecID codec_id)
2478{
2479 AVStream *st;
2480 uint64_t original_size;
2481 int err;
2482
2483 if (c->fc->nb_streams < 1) // will happen with jp2 files
2484 return 0;
2485 st = c->fc->streams[c->fc->nb_streams-1];
2486
2487 if (st->codecpar->codec_id != codec_id)
2488 return 0; /* unexpected codec_id - don't mess with extradata */
2489
2490 original_size = st->codecpar->extradata_size;
2491 err = mov_realloc_extradata(st->codecpar, atom);
2492 if (err)
2493 return err;
2494
2495 err = mov_read_atom_into_extradata(c, pb, atom, st->codecpar, st->codecpar->extradata + original_size);
2496 if (err < 0)
2497 return err;
2498 return 0; // Note: this is the original behavior to ignore truncation.
2499}
2500
2501/* wrapper functions for reading ALAC/AVS/MJPEG/MJPEG2000 extradata atoms only for those codecs */
2503{
2504 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_ALAC);
2505}
2506
2508{
2509 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_CAVS);
2510}
2511
2513{
2514 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_JPEG2000);
2515}
2516
2518{
2519 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_R10K);
2520}
2521
2523{
2524 int ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_AVUI);
2525 if (!ret)
2527 return ret;
2528}
2529
2531{
2533
2534 if (!ret && c->fc->nb_streams >= 1) {
2535 AVCodecParameters *par = c->fc->streams[c->fc->nb_streams-1]->codecpar;
2536 if (par->extradata_size >= 40) {
2537 par->height = AV_RB16(&par->extradata[36]);
2538 par->width = AV_RB16(&par->extradata[38]);
2539 }
2540 }
2541 return ret;
2542}
2543
2545{
2546 if (c->fc->nb_streams >= 1) {
2547 AVStream *const st = c->fc->streams[c->fc->nb_streams - 1];
2548 FFStream *const sti = ffstream(st);
2549 AVCodecParameters *par = st->codecpar;
2550
2551 if (par->codec_tag == MKTAG('A', 'V', 'i', 'n') &&
2552 par->codec_id == AV_CODEC_ID_H264 &&
2553 atom.size > 11) {
2554 int cid;
2555 avio_skip(pb, 10);
2556 cid = avio_rb16(pb);
2557 /* For AVID AVCI50, force width of 1440 to be able to select the correct SPS and PPS */
2558 if (cid == 0xd4d || cid == 0xd4e)
2559 par->width = 1440;
2560 return 0;
2561 } else if ((par->codec_tag == MKTAG('A', 'V', 'd', '1') ||
2562 par->codec_tag == MKTAG('A', 'V', 'j', '2') ||
2563 par->codec_tag == MKTAG('A', 'V', 'd', 'n')) &&
2564 atom.size >= 24) {
2565 int num, den;
2566 avio_skip(pb, 12);
2567 num = avio_rb32(pb);
2568 den = avio_rb32(pb);
2569 if (num <= 0 || den <= 0)
2570 return 0;
2571 switch (avio_rb32(pb)) {
2572 case 2:
2573 if (den >= INT_MAX / 2)
2574 return 0;
2575 den *= 2;
2577 case 1:
2578 sti->display_aspect_ratio = (AVRational){ num, den };
2580 default:
2581 return 0;
2582 }
2583 }
2584 }
2585
2586 return mov_read_avid(c, pb, atom);
2587}
2588
2590{
2591 int ret = 0;
2592 int length = 0;
2593 uint64_t original_size;
2594 if (c->fc->nb_streams >= 1) {
2595 AVCodecParameters *par = c->fc->streams[c->fc->nb_streams-1]->codecpar;
2596 if (par->codec_id == AV_CODEC_ID_H264)
2597 return 0;
2598 if (atom.size == 16) {
2599 original_size = par->extradata_size;
2600 ret = mov_realloc_extradata(par, atom);
2601 if (!ret) {
2602 length = mov_read_atom_into_extradata(c, pb, atom, par, par->extradata + original_size);
2603 if (length == atom.size) {
2604 const uint8_t range_value = par->extradata[original_size + 19];
2605 switch (range_value) {
2606 case 1:
2608 break;
2609 case 2:
2611 break;
2612 default:
2613 av_log(c->fc, AV_LOG_WARNING, "ignored unknown aclr value (%d)\n", range_value);
2614 break;
2615 }
2616 ff_dlog(c->fc, "color_range: %d\n", par->color_range);
2617 } else {
2618 /* For some reason the whole atom was not added to the extradata */
2619 av_log(c->fc, AV_LOG_ERROR, "aclr not decoded - incomplete atom\n");
2620 }
2621 } else {
2622 av_log(c->fc, AV_LOG_ERROR, "aclr not decoded - unable to add atom to extradata\n");
2623 }
2624 } else {
2625 av_log(c->fc, AV_LOG_WARNING, "aclr not decoded - unexpected size %"PRId64"\n", atom.size);
2626 }
2627 }
2628
2629 return ret;
2630}
2631
2633{
2634 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_SVQ3);
2635}
2636
2638{
2639 AVStream *st;
2640 int ret;
2641
2642 if (c->fc->nb_streams < 1)
2643 return 0;
2644 st = c->fc->streams[c->fc->nb_streams-1];
2645
2646 if ((uint64_t)atom.size > (1<<30))
2647 return AVERROR_INVALIDDATA;
2648
2649 if (st->codecpar->codec_id == AV_CODEC_ID_QDM2 ||
2652 // pass all frma atom to codec, needed at least for QDMC and QDM2
2653 ret = ff_get_extradata(c->fc, st->codecpar, pb, atom.size);
2654 if (ret < 0)
2655 return ret;
2656 } else if (atom.size > 8) { /* to read frma, esds atoms */
2657 if (st->codecpar->codec_id == AV_CODEC_ID_ALAC && atom.size >= 24) {
2658 uint64_t buffer;
2659 ret = ffio_ensure_seekback(pb, 8);
2660 if (ret < 0)
2661 return ret;
2662 buffer = avio_rb64(pb);
2663 atom.size -= 8;
2664 if ( (buffer & 0xFFFFFFFF) == MKBETAG('f','r','m','a')
2665 && buffer >> 32 <= atom.size
2666 && buffer >> 32 >= 8) {
2667 avio_skip(pb, -8);
2668 atom.size += 8;
2669 } else if (!st->codecpar->extradata_size) {
2670#define ALAC_EXTRADATA_SIZE 36
2672 if (!st->codecpar->extradata)
2673 return AVERROR(ENOMEM);
2676 AV_WL32(st->codecpar->extradata + 4, MKTAG('a','l','a','c'));
2677 AV_WB64(st->codecpar->extradata + 12, buffer);
2678 avio_read(pb, st->codecpar->extradata + 20, 16);
2679 avio_skip(pb, atom.size - 24);
2680 return 0;
2681 }
2682 }
2683 if ((ret = mov_read_default(c, pb, atom)) < 0)
2684 return ret;
2685 } else
2686 avio_skip(pb, atom.size);
2687 return 0;
2688}
2689
2690/**
2691 * This function reads atom content and puts data in extradata without tag
2692 * nor size unlike mov_read_extradata.
2693 */
2695{
2696 AVStream *st;
2697 int ret;
2698
2699 st = get_curr_st(c);
2700 if (!st)
2701 return 0;
2702
2703 if ((uint64_t)atom.size > (1<<30))
2704 return AVERROR_INVALIDDATA;
2705
2706 if (atom.type == MKTAG('v','v','c','C')) {
2707 avio_skip(pb, 4);
2708 atom.size -= 4;
2709 }
2710
2711 if (atom.size >= 10) {
2712 // Broken files created by legacy versions of libavformat will
2713 // wrap a whole fiel atom inside of a glbl atom.
2714 unsigned size = avio_rb32(pb);
2715 unsigned type = avio_rl32(pb);
2716 if (avio_feof(pb))
2717 return AVERROR_INVALIDDATA;
2718 avio_seek(pb, -8, SEEK_CUR);
2719 if (type == MKTAG('f','i','e','l') && size == atom.size)
2720 return mov_read_default(c, pb, atom);
2721 }
2722 if (st->codecpar->extradata_size > 1 && st->codecpar->extradata) {
2723 av_log(c->fc, AV_LOG_WARNING, "ignoring multiple glbl\n");
2724 return 0;
2725 }
2726 ret = ff_get_extradata(c->fc, st->codecpar, pb, atom.size);
2727 if (ret < 0)
2728 return ret;
2729 if (atom.type == MKTAG('h','v','c','C') && st->codecpar->codec_tag == MKTAG('d','v','h','1'))
2730 /* HEVC-based Dolby Vision derived from hvc1.
2731 Happens to match with an identifier
2732 previously utilized for DV. Thus, if we have
2733 the hvcC extradata box available as specified,
2734 set codec to HEVC */
2736
2737 return 0;
2738}
2739
2741{
2742 AVStream *st;
2743 uint8_t profile_level;
2744 int ret;
2745
2746 if (c->fc->nb_streams < 1)
2747 return 0;
2748 st = c->fc->streams[c->fc->nb_streams-1];
2749
2750 if (atom.size >= (1<<28) || atom.size < 7)
2751 return AVERROR_INVALIDDATA;
2752
2753 profile_level = avio_r8(pb);
2754 if ((profile_level & 0xf0) != 0xc0)
2755 return 0;
2756
2757 avio_seek(pb, 6, SEEK_CUR);
2758 ret = ff_get_extradata(c->fc, st->codecpar, pb, atom.size - 7);
2759 if (ret < 0)
2760 return ret;
2761
2762 return 0;
2763}
2764
2765static int mov_find_tref_id(const MovTref *tag, uint32_t id)
2766{
2767 for (int i = 0; i < tag->nb_id; i++) {
2768 if (tag->id[i] == id)
2769 return 1;
2770 }
2771 return 0;
2772}
2773
2774static int mov_add_tref_id(MovTref *tag, uint32_t id)
2775{
2776 int ret = mov_find_tref_id(tag, id);
2777
2778 if (!ret) {
2779 uint32_t *tmp = av_realloc_array(tag->id, tag->nb_id + 1, sizeof(*tag->id));
2780 if (!tmp)
2781 return AVERROR(ENOMEM);
2782 tag->id = tmp;
2783 tag->id[tag->nb_id++] = id;
2784 }
2785
2786 return 0;
2787}
2788
2790{
2791 for (int i = 0; i < sc->nb_tref_tags; i++) {
2792 MovTref *entry = &sc->tref_tags[i];
2793
2794 if (entry->name == name)
2795 return entry;
2796 }
2797 return NULL;
2798}
2799
2801{
2803
2804 if (!tag) {
2806 sizeof(*sc->tref_tags));
2807 if (!tmp)
2808 return NULL;
2809 sc->tref_tags = tmp;
2810 tag = &sc->tref_tags[sc->nb_tref_tags++];
2811 *tag = (MovTref){ .name = name };
2812 }
2813
2814 return tag;
2815}
2816
2818{
2819 AVStream* st;
2820 MOVStreamContext* sc;
2821
2822 if (c->fc->nb_streams < 1)
2823 return 0;
2824
2825 if (atom.size > 4) {
2826 av_log(c->fc, AV_LOG_ERROR, "Only a single tref of type cdsc/rndr is supported\n");
2827 return AVERROR_PATCHWELCOME;
2828 }
2829 if (atom.size < 4)
2830 return AVERROR_INVALIDDATA;
2831
2832 st = get_curr_st(c);
2833 if (!st)
2834 return 0;
2835 sc = st->priv_data;
2836
2837 MovTref *tag = mov_add_tref_tag(sc, atom.type);
2838 if (!tag)
2839 return AVERROR(ENOMEM);
2840
2841 int ret = mov_add_tref_id(tag, avio_rb32(pb));
2842 if (ret < 0)
2843 return ret;
2844
2845 return 0;
2846}
2847
2849{
2850 AVStream* st;
2851 MOVStreamContext* sc;
2852
2853 if (c->fc->nb_streams < 1)
2854 return 0;
2855
2856 /* For SBAS this should be fine - though beware if someone implements a
2857 * tref atom processor that doesn't drop down to default then this may
2858 * be lost. */
2859 if (atom.size > 4) {
2860 av_log(c->fc, AV_LOG_ERROR, "Only a single tref of type sbas is supported\n");
2861 return AVERROR_PATCHWELCOME;
2862 }
2863 if (atom.size < 4)
2864 return AVERROR_INVALIDDATA;
2865
2866 st = c->fc->streams[c->fc->nb_streams - 1];
2867 sc = st->priv_data;
2868
2869 MovTref *tag = mov_add_tref_tag(sc, atom.type);
2870 if (!tag)
2871 return AVERROR(ENOMEM);
2872
2873 int ret = mov_add_tref_id(tag, avio_rb32(pb));
2874 if (ret < 0)
2875 return ret;
2876
2877 return 0;
2878}
2879
2881{
2882 AVStream* st;
2883 MOVStreamContext* sc;
2884
2885 if (c->fc->nb_streams < 1)
2886 return 0;
2887
2888 if (atom.size > 4)
2889 av_log(c->fc, AV_LOG_WARNING, "More than one vdep reference is not supported.\n");
2890 if (atom.size < 4)
2891 return AVERROR_INVALIDDATA;
2892
2893 st = c->fc->streams[c->fc->nb_streams - 1];
2894 sc = st->priv_data;
2895
2896 MovTref *tag = mov_add_tref_tag(sc, atom.type);
2897 if (!tag)
2898 return AVERROR(ENOMEM);
2899
2900 int ret = mov_add_tref_id(tag, avio_rb32(pb));
2901 if (ret < 0)
2902 return ret;
2903
2904 return 0;
2905}
2906
2907/**
2908 * An strf atom is a BITMAPINFOHEADER struct. This struct is 40 bytes itself,
2909 * but can have extradata appended at the end after the 40 bytes belonging
2910 * to the struct.
2911 */
2913{
2914 AVStream *st;
2915 int ret;
2916
2917 if (c->fc->nb_streams < 1)
2918 return 0;
2919 if (atom.size <= 40)
2920 return 0;
2921 st = c->fc->streams[c->fc->nb_streams-1];
2922
2923 if ((uint64_t)atom.size > (1<<30))
2924 return AVERROR_INVALIDDATA;
2925
2926 avio_skip(pb, 40);
2927 ret = ff_get_extradata(c->fc, st->codecpar, pb, atom.size - 40);
2928 if (ret < 0)
2929 return ret;
2930
2931 return 0;
2932}
2933
2935{
2936 AVStream *st;
2937 MOVStreamContext *sc;
2938 unsigned int i, entries;
2939
2940 if (c->trak_index < 0) {
2941 av_log(c->fc, AV_LOG_WARNING, "STCO outside TRAK\n");
2942 return 0;
2943 }
2944 if (c->fc->nb_streams < 1)
2945 return 0;
2946 st = c->fc->streams[c->fc->nb_streams-1];
2947 sc = st->priv_data;
2948
2949 avio_r8(pb); /* version */
2950 avio_rb24(pb); /* flags */
2951
2952 // Clamp allocation size for `chunk_offsets` -- don't throw an error for an
2953 // invalid count since the EOF path doesn't throw either.
2954 entries = avio_rb32(pb);
2955 entries =
2956 FFMIN(entries,
2957 FFMAX(0, (atom.size - 8) /
2958 (atom.type == MKTAG('s', 't', 'c', 'o') ? 4 : 8)));
2959
2960 if (!entries)
2961 return 0;
2962
2963 if (sc->chunk_offsets) {
2964 av_log(c->fc, AV_LOG_WARNING, "Ignoring duplicated STCO atom\n");
2965 return 0;
2966 }
2967
2969 sc->chunk_count = 0;
2970 sc->chunk_offsets = av_malloc_array(entries, sizeof(*sc->chunk_offsets));
2971 if (!sc->chunk_offsets)
2972 return AVERROR(ENOMEM);
2973 sc->chunk_count = entries;
2974
2975 if (atom.type == MKTAG('s','t','c','o'))
2976 for (i = 0; i < entries && !pb->eof_reached; i++)
2977 sc->chunk_offsets[i] = avio_rb32(pb);
2978 else if (atom.type == MKTAG('c','o','6','4'))
2979 for (i = 0; i < entries && !pb->eof_reached; i++) {
2980 sc->chunk_offsets[i] = avio_rb64(pb);
2981 if (sc->chunk_offsets[i] < 0) {
2982 av_log(c->fc, AV_LOG_WARNING, "Impossible chunk_offset\n");
2983 sc->chunk_offsets[i] = 0;
2984 }
2985 }
2986 else
2987 return AVERROR_INVALIDDATA;
2988
2989 sc->chunk_count = i;
2990
2991 if (pb->eof_reached) {
2992 av_log(c->fc, AV_LOG_WARNING, "reached eof, corrupted STCO atom\n");
2993 return AVERROR_EOF;
2994 }
2995
2996 return 0;
2997}
2998
2999static int mov_codec_id(AVStream *st, uint32_t format)
3000{
3002
3003 if (id <= 0 &&
3004 ((format & 0xFFFF) == 'm' + ('s' << 8) ||
3005 (format & 0xFFFF) == 'T' + ('S' << 8)))
3007
3008 if (st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO && id > 0) {
3010 } else if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO &&
3011 /* skip old ASF MPEG-4 tag */
3012 format && format != MKTAG('m','p','4','s')) {
3014 if (id <= 0)
3016 if (id > 0)
3018 else if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA ||
3022 if (id <= 0) {
3025 }
3026
3027 if (id > 0)
3029 else
3031 }
3032 }
3033
3034 st->codecpar->codec_tag = format;
3035
3036 return id;
3037}
3038
3040 AVStream *st, MOVStreamContext *sc)
3041{
3042 uint8_t codec_name[32] = { 0 };
3043 int64_t stsd_start;
3044 unsigned int len;
3045 uint32_t id = 0;
3046
3047 /* The first 16 bytes of the video sample description are already
3048 * read in ff_mov_read_stsd_entries() */
3049 stsd_start = avio_tell(pb) - 16;
3050
3051 if (c->isom) {
3052 avio_skip(pb, 2); /* pre_defined */
3053 avio_skip(pb, 2); /* reserved */
3054 avio_skip(pb, 12); /* pre_defined */
3055 } else {
3056 avio_rb16(pb); /* version */
3057 avio_rb16(pb); /* revision level */
3058 id = avio_rl32(pb); /* vendor */
3059 av_dict_set(&st->metadata, "vendor_id", av_fourcc2str(id), 0);
3060 avio_rb32(pb); /* temporal quality */
3061 avio_rb32(pb); /* spatial quality */
3062 }
3063
3064 st->codecpar->width = avio_rb16(pb); /* width */
3065 st->codecpar->height = avio_rb16(pb); /* height */
3066
3067 avio_rb32(pb); /* horiz resolution */
3068 avio_rb32(pb); /* vert resolution */
3069 avio_rb32(pb); /* data size, always 0 */
3070 avio_rb16(pb); /* frames per samples */
3071
3072 len = avio_r8(pb); /* codec name, pascal string */
3073 if (len > 31)
3074 len = 31;
3075 mov_read_mac_string(c, pb, len, codec_name, sizeof(codec_name));
3076 if (len < 31)
3077 avio_skip(pb, 31 - len);
3078
3079 if (codec_name[0])
3080 av_dict_set(&st->metadata, "encoder", codec_name, 0);
3081
3082 /* codec_tag YV12 triggers an UV swap in rawdec.c */
3083 if (!strncmp(codec_name, "Planar Y'CbCr 8-bit 4:2:0", 25)) {
3084 st->codecpar->codec_tag = MKTAG('I', '4', '2', '0');
3085 st->codecpar->width &= ~1;
3086 st->codecpar->height &= ~1;
3087 }
3088 /* Flash Media Server uses tag H.263 with Sorenson Spark */
3089 if (st->codecpar->codec_tag == MKTAG('H','2','6','3') &&
3090 !strncmp(codec_name, "Sorenson H263", 13))
3092
3093 st->codecpar->bits_per_coded_sample = avio_rb16(pb); /* depth */
3094
3095 avio_seek(pb, stsd_start, SEEK_SET);
3096
3097 if (ff_get_qtpalette(st->codecpar->codec_id, pb, sc->palette)) {
3098 st->codecpar->bits_per_coded_sample &= 0x1F;
3099 sc->has_palette = 1;
3100 }
3101}
3102
3104 AVStream *st, MOVStreamContext *sc)
3105{
3106 int bits_per_sample, flags;
3107 uint16_t version = avio_rb16(pb);
3108 uint32_t id = 0;
3109 AVDictionaryEntry *compatible_brands = av_dict_get(c->fc->metadata, "compatible_brands", NULL, AV_DICT_MATCH_CASE);
3110 int channel_count;
3111
3112 if (c->isom)
3113 avio_skip(pb, 6); /* reserved */
3114 else {
3115 avio_rb16(pb); /* revision level */
3116 id = avio_rl32(pb); /* vendor */
3117 av_dict_set(&st->metadata, "vendor_id", av_fourcc2str(id), 0);
3118 }
3119
3120 channel_count = avio_rb16(pb);
3121
3123 st->codecpar->ch_layout.nb_channels = channel_count;
3124 st->codecpar->bits_per_coded_sample = avio_rb16(pb); /* sample size */
3125 av_log(c->fc, AV_LOG_TRACE, "audio channels %d\n", channel_count);
3126
3127 sc->audio_cid = avio_rb16(pb);
3128 avio_rb16(pb); /* packet size = 0 */
3129
3130 st->codecpar->sample_rate = ((avio_rb32(pb) >> 16));
3131
3132 // Read QT version 1 fields. In version 0 these do not exist.
3133 av_log(c->fc, AV_LOG_TRACE, "version =%d, isom =%d\n", version, c->isom);
3134 if (!c->isom ||
3135 (compatible_brands && strstr(compatible_brands->value, "qt ")) ||
3136 (sc->stsd_version == 0 && version > 0)) {
3137 if (version == 1) {
3138 sc->samples_per_frame = avio_rb32(pb);
3139 avio_rb32(pb); /* bytes per packet */
3140 sc->bytes_per_frame = avio_rb32(pb);
3141 avio_rb32(pb); /* bytes per sample */
3142 } else if (version == 2) {
3143 double sample_rate;
3144
3145 avio_rb32(pb); /* sizeof struct only */
3146 sample_rate = av_int2double(avio_rb64(pb));
3147
3148 if (sample_rate < 0 || sample_rate > INT_MAX ||
3149 isnan(sample_rate)) {
3150 av_log(c->fc, AV_LOG_ERROR, "Invalid sample rate %g\n",
3151 sample_rate);
3152 return AVERROR_INVALIDDATA;
3153 }
3154 st->codecpar->sample_rate = sample_rate;
3155 channel_count = avio_rb32(pb);
3157 st->codecpar->ch_layout.nb_channels = channel_count;
3158 avio_rb32(pb); /* always 0x7F000000 */
3160
3161 flags = avio_rb32(pb); /* lpcm format specific flag */
3162 sc->bytes_per_frame = avio_rb32(pb);
3163 sc->samples_per_frame = avio_rb32(pb);
3164 if (st->codecpar->codec_tag == MKTAG('l','p','c','m'))
3165 st->codecpar->codec_id =
3167 flags);
3168 }
3169 if (version == 0 || (version == 1 && sc->audio_cid != -2)) {
3170 /* can't correctly handle variable sized packet as audio unit */
3171 switch (st->codecpar->codec_id) {
3172 case AV_CODEC_ID_MP2:
3173 case AV_CODEC_ID_MP3:
3175 break;
3176 }
3177 }
3178 }
3179
3180 if (sc->format == 0) {
3181 if (st->codecpar->bits_per_coded_sample == 8)
3182 st->codecpar->codec_id = mov_codec_id(st, MKTAG('r','a','w',' '));
3183 else if (st->codecpar->bits_per_coded_sample == 16)
3184 st->codecpar->codec_id = mov_codec_id(st, MKTAG('t','w','o','s'));
3185 }
3186
3187 switch (st->codecpar->codec_id) {
3188 case AV_CODEC_ID_PCM_S8:
3189 case AV_CODEC_ID_PCM_U8:
3190 if (st->codecpar->bits_per_coded_sample == 16)
3192 break;
3195 if (st->codecpar->bits_per_coded_sample == 8)
3197 else if (st->codecpar->bits_per_coded_sample == 24)
3198 st->codecpar->codec_id =
3201 else if (st->codecpar->bits_per_coded_sample == 32)
3202 st->codecpar->codec_id =
3205 break;
3206 /* set values for old format before stsd version 1 appeared */
3207 case AV_CODEC_ID_MACE3:
3208 sc->samples_per_frame = 6;
3210 break;
3211 case AV_CODEC_ID_MACE6:
3212 sc->samples_per_frame = 6;
3214 break;
3216 sc->samples_per_frame = 64;
3218 break;
3219 case AV_CODEC_ID_GSM:
3220 sc->samples_per_frame = 160;
3221 sc->bytes_per_frame = 33;
3222 break;
3223 default:
3224 break;
3225 }
3226
3227 bits_per_sample = av_get_bits_per_sample(st->codecpar->codec_id);
3228 if (bits_per_sample && (bits_per_sample >> 3) * (uint64_t)st->codecpar->ch_layout.nb_channels <= INT_MAX) {
3229 st->codecpar->bits_per_coded_sample = bits_per_sample;
3230 sc->sample_size = (bits_per_sample >> 3) * st->codecpar->ch_layout.nb_channels;
3231 }
3232
3233 return 0;
3234}
3235
3237 AVStream *st, MOVStreamContext *sc,
3238 int64_t size)
3239{
3240 // ttxt stsd contains display flags, justification, background
3241 // color, fonts, and default styles, so fake an atom to read it
3242 MOVAtom fake_atom = { .size = size };
3243 // mp4s contains a regular esds atom, dfxp ISMV TTML has no content
3244 // in extradata unlike stpp MP4 TTML.
3245 if (st->codecpar->codec_tag != AV_RL32("mp4s") &&
3247 mov_read_glbl(c, pb, fake_atom);
3248 st->codecpar->width = sc->width;
3249 st->codecpar->height = sc->height;
3250}
3251
3253 AVStream *st, MOVStreamContext *sc,
3254 int64_t size)
3255{
3256 int ret;
3257
3258 if (st->codecpar->codec_tag == MKTAG('t','m','c','d')) {
3259 if ((int)size != size)
3260 return AVERROR(ENOMEM);
3261
3262 ret = ff_get_extradata(c->fc, st->codecpar, pb, size);
3263 if (ret < 0)
3264 return ret;
3265 if (size > 16) {
3266 MOVStreamContext *tmcd_ctx = st->priv_data;
3267 int val;
3268 val = AV_RB32(st->codecpar->extradata + 4);
3269 tmcd_ctx->tmcd_flags = val;
3270 st->avg_frame_rate.num = AV_RB32(st->codecpar->extradata + 8); /* timescale */
3271 st->avg_frame_rate.den = AV_RB32(st->codecpar->extradata + 12); /* frameDuration */
3272 tmcd_ctx->tmcd_nb_frames = st->codecpar->extradata[16]; /* number of frames */
3273 if (size > 30) {
3274 uint32_t len = AV_RB32(st->codecpar->extradata + 18); /* name atom length */
3275 uint32_t format = AV_RB32(st->codecpar->extradata + 22);
3276 if (format == AV_RB32("name") && (int64_t)size >= (int64_t)len + 18) {
3277 uint16_t str_size = AV_RB16(st->codecpar->extradata + 26); /* string length */
3278 if (str_size > 0 && size >= (int)str_size + 30 &&
3279 st->codecpar->extradata[30] /* Don't add empty string */) {
3280 char *reel_name = av_malloc(str_size + 1);
3281 if (!reel_name)
3282 return AVERROR(ENOMEM);
3283 memcpy(reel_name, st->codecpar->extradata + 30, str_size);
3284 reel_name[str_size] = 0; /* Add null terminator */
3285 av_dict_set(&st->metadata, "reel_name", reel_name,
3287 }
3288 }
3289 }
3290 }
3291 } else if (st->codecpar->codec_id == AV_CODEC_ID_ITUT_T35) {
3292 int t35_identifier_length = avio_r8(pb);
3293
3294 if (t35_identifier_length <= 0 || t35_identifier_length >= size)
3295 return AVERROR_INVALIDDATA;
3296
3297 ret = ff_get_extradata(c->fc, st->codecpar, pb, t35_identifier_length);
3298 if (ret < 0)
3299 return ret;
3300
3301 int hrsd_len = size - t35_identifier_length - 1;
3302 if (hrsd_len > 0) {
3303 uint8_t *hrsd_str = av_malloc(hrsd_len + 1);
3304 if (!hrsd_str)
3305 return AVERROR(ENOMEM);
3306
3307 ret = ffio_read_size(pb, hrsd_str, hrsd_len);
3308 if (ret < 0) {
3309 av_free(hrsd_str);
3310 return ret;
3311 }
3312 if (hrsd_str[0]) {
3313 hrsd_str[hrsd_len] = 0;
3314 ret = av_dict_set(&st->metadata, "description", hrsd_str, AV_DICT_DONT_OVERWRITE);
3315 }
3316 av_free(hrsd_str);
3317 }
3318 } else {
3319 /* other codec type, just skip (rtp, mp4s ...) */
3320 avio_skip(pb, size);
3321 }
3322 return 0;
3323}
3324
3326 AVStream *st, MOVStreamContext *sc)
3327{
3328 FFStream *const sti = ffstream(st);
3329
3331 !st->codecpar->sample_rate && sc->time_scale > 1)
3332 st->codecpar->sample_rate = sc->time_scale;
3333
3334 /* special codec parameters handling */
3335 switch (st->codecpar->codec_id) {
3336#if CONFIG_DV_DEMUXER
3338 if (c->dv_fctx) {
3339 avpriv_request_sample(c->fc, "multiple DV audio streams");
3340 return AVERROR(ENOSYS);
3341 }
3342
3343 c->dv_fctx = avformat_alloc_context();
3344 if (!c->dv_fctx) {
3345 av_log(c->fc, AV_LOG_ERROR, "dv demux context alloc error\n");
3346 return AVERROR(ENOMEM);
3347 }
3348 c->dv_demux = avpriv_dv_init_demux(c->dv_fctx);
3349 if (!c->dv_demux) {
3350 av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n");
3351 return AVERROR(ENOMEM);
3352 }
3353 sc->dv_audio_container = 1;
3355 break;
3356#endif
3357 /* no ifdef since parameters are always those */
3358 case AV_CODEC_ID_QCELP:
3361 // force sample rate for qcelp when not stored in mov
3362 if (st->codecpar->codec_tag != MKTAG('Q','c','l','p'))
3363 st->codecpar->sample_rate = 8000;
3364 // Each QCELP frame decodes to 160 samples at every coding rate.
3365 sc->samples_per_frame = 160;
3366 // Assume a full-rate frame when the byte count is unset, as in version 0.
3367 if (!sc->bytes_per_frame)
3368 sc->bytes_per_frame = 35;
3369 break;
3370 case AV_CODEC_ID_AMR_NB:
3373 /* force sample rate for amr, stsd in 3gp does not store sample rate */
3374 st->codecpar->sample_rate = 8000;
3375 break;
3376 case AV_CODEC_ID_AMR_WB:
3379 st->codecpar->sample_rate = 16000;
3380 break;
3381 case AV_CODEC_ID_MP2:
3382 case AV_CODEC_ID_MP3:
3383 /* force type after stsd for m1a hdlr */
3385 break;
3386 case AV_CODEC_ID_GSM:
3389 case AV_CODEC_ID_ILBC:
3390 case AV_CODEC_ID_MACE3:
3391 case AV_CODEC_ID_MACE6:
3392 case AV_CODEC_ID_QDM2:
3394 break;
3395 case AV_CODEC_ID_ALAC:
3396 if (st->codecpar->extradata_size == 36) {
3397 int channel_count = AV_RB8(st->codecpar->extradata + 21);
3398 if (st->codecpar->ch_layout.nb_channels != channel_count) {
3401 st->codecpar->ch_layout.nb_channels = channel_count;
3402 }
3403 st->codecpar->sample_rate = AV_RB32(st->codecpar->extradata + 32);
3404 }
3405 break;
3406 case AV_CODEC_ID_AC3:
3407 case AV_CODEC_ID_EAC3:
3409 case AV_CODEC_ID_VC1:
3410 case AV_CODEC_ID_VP8:
3411 case AV_CODEC_ID_VP9:
3413 break;
3415 case AV_CODEC_ID_PRORES:
3416 case AV_CODEC_ID_APV:
3417 case AV_CODEC_ID_EVC:
3418 case AV_CODEC_ID_LCEVC:
3419 case AV_CODEC_ID_AV1:
3420 /* field_order detection of H264 requires parsing */
3421 case AV_CODEC_ID_H264:
3423 break;
3424 default:
3425 break;
3426 }
3427 return 0;
3428}
3429
3431 int codec_tag, int format,
3432 int64_t size)
3433{
3434 if (codec_tag &&
3435 (codec_tag != format &&
3436 // AVID 1:1 samples with differing data format and codec tag exist
3437 (codec_tag != AV_RL32("AV1x") || format != AV_RL32("AVup")) &&
3438 // prores is allowed to have differing data format and codec tag
3439 codec_tag != AV_RL32("apcn") && codec_tag != AV_RL32("apch") &&
3440 // so is dv (sigh)
3441 codec_tag != AV_RL32("dvpp") && codec_tag != AV_RL32("dvcp") &&
3442 (c->fc->video_codec_id ? ff_codec_get_id(ff_codec_movvideo_tags, format) != c->fc->video_codec_id
3443 : codec_tag != MKTAG('j','p','e','g')))) {
3444 /* Multiple fourcc, we skip JPEG. This is not correct, we should
3445 * export it as a separate AVStream but this needs a few changes
3446 * in the MOV demuxer, patch welcome. */
3447
3448 av_log(c->fc, AV_LOG_WARNING, "multiple fourcc not supported\n");
3449 avio_skip(pb, size);
3450 return 1;
3451 }
3452
3453 return 0;
3454}
3455
3457{
3458 int ret;
3459
3460 /* special codec parameters handling */
3461 switch (st->codecpar->codec_id) {
3462 case AV_CODEC_ID_H264:
3463 // done for ai5q, ai52, ai55, ai1q, ai12 and ai15.
3466 if (ret < 0)
3467 return ret;
3468 }
3469 break;
3470 default:
3471 break;
3472 }
3473
3474 return 0;
3475}
3476
3478{
3479 AVStream *st;
3480 MOVStreamContext *sc;
3481 int pseudo_stream_id;
3482 int gama_trc = -1;
3483
3484 av_assert0 (c->fc->nb_streams >= 1);
3485 st = c->fc->streams[c->fc->nb_streams-1];
3486 sc = st->priv_data;
3487
3488 for (pseudo_stream_id = 0;
3489 pseudo_stream_id < entries && !pb->eof_reached;
3490 pseudo_stream_id++) {
3491 //Parsing Sample description table
3492 enum AVCodecID id;
3493 int ret, dref_id = 1;
3494 MOVAtom a = { AV_RL32("stsd") };
3495 int64_t start_pos = avio_tell(pb);
3496 int64_t size = avio_rb32(pb); /* size */
3497 uint32_t format = avio_rl32(pb); /* data format */
3498
3499 if (size >= 16) {
3500 avio_rb32(pb); /* reserved */
3501 avio_rb16(pb); /* reserved */
3502 dref_id = avio_rb16(pb);
3503 } else if (size <= 7) {
3504 av_log(c->fc, AV_LOG_ERROR,
3505 "invalid size %"PRId64" in stsd\n", size);
3506 return AVERROR_INVALIDDATA;
3507 }
3508
3510 size - (avio_tell(pb) - start_pos))) {
3511 sc->stsd_count++;
3512 continue;
3513 }
3514
3515 sc->pseudo_stream_id = st->codecpar->codec_tag ? -1 : pseudo_stream_id;
3516 sc->dref_id= dref_id;
3517 sc->format = format;
3519 sc->stsd_colr_trc = 0;
3520
3521 id = mov_codec_id(st, format);
3522
3523 av_log(c->fc, AV_LOG_TRACE,
3524 "size=%"PRId64" 4CC=%s codec_type=%d\n", size,
3526
3527 st->codecpar->codec_id = id;
3529 mov_parse_stsd_video(c, pb, st, sc);
3530 } else if (st->codecpar->codec_type==AVMEDIA_TYPE_AUDIO) {
3531 ret = mov_parse_stsd_audio(c, pb, st, sc);
3532 if (ret < 0)
3533 return ret;
3534 if (st->codecpar->sample_rate < 0) {
3535 av_log(c->fc, AV_LOG_ERROR, "Invalid sample rate %d\n", st->codecpar->sample_rate);
3536 return AVERROR_INVALIDDATA;
3537 }
3538 if (st->codecpar->ch_layout.nb_channels < 0) {
3539 av_log(c->fc, AV_LOG_ERROR, "Invalid channels %d\n", st->codecpar->ch_layout.nb_channels);
3540 return AVERROR_INVALIDDATA;
3541 }
3542 } else if (st->codecpar->codec_type==AVMEDIA_TYPE_SUBTITLE){
3543 mov_parse_stsd_subtitle(c, pb, st, sc,
3544 size - (avio_tell(pb) - start_pos));
3545 } else {
3546 ret = mov_parse_stsd_data(c, pb, st, sc,
3547 size - (avio_tell(pb) - start_pos));
3548 if (ret < 0)
3549 return ret;
3550 }
3551 /* this will read extra atoms at the end (wave, alac, damr, avcC, hvcC, SMI ...) */
3552 a.size = size - (avio_tell(pb) - start_pos);
3553 if (a.size > 8) {
3554 if ((ret = mov_read_default(c, pb, a)) < 0)
3555 return ret;
3556 } else if (a.size > 0)
3557 avio_skip(pb, a.size);
3558
3559 // Use gama only when colr does not specify the transfer, like QuickTime does
3560 if (sc->stsd_colr_trc)
3562 if (gama_trc < 0)
3563 gama_trc = sc->stsd_gama_trc;
3564 else if (gama_trc != sc->stsd_gama_trc)
3565 gama_trc = AVCOL_TRC_UNSPECIFIED;
3566
3568 if (ret < 0)
3569 return ret;
3570
3571 if (sc->extradata && st->codecpar->extradata) {
3572 int extra_size = st->codecpar->extradata_size;
3573
3574 /* Move the current stream extradata to the stream context one. */
3575 sc->extradata_size[pseudo_stream_id] = extra_size;
3576 sc->extradata[pseudo_stream_id] = st->codecpar->extradata;
3577 st->codecpar->extradata = NULL;
3578 st->codecpar->extradata_size = 0;
3579 }
3580 sc->stsd_count++;
3581 }
3582
3583 // Only when every sample description has the same gamma,
3584 // and nothing else (e.g. vpcC) set the transfer
3585 if ((gama_trc == AVCOL_TRC_GAMMA22 || gama_trc == AVCOL_TRC_GAMMA28) &&
3587 st->codecpar->color_trc = gama_trc;
3588
3589 if (pb->eof_reached) {
3590 av_log(c->fc, AV_LOG_WARNING, "reached eof, corrupted STSD atom\n");
3591 return AVERROR_EOF;
3592 }
3593
3594 return 0;
3595}
3596
3598{
3599 AVStream *st;
3600 MOVStreamContext *sc;
3601 int ret, entries;
3602
3603 st = get_curr_st(c);
3604 if (!st)
3605 return 0;
3606 sc = st->priv_data;
3607
3608 if (sc->extradata) {
3609 av_log(c->fc, AV_LOG_ERROR,
3610 "Duplicate stsd found in this track.\n");
3611 return AVERROR_INVALIDDATA;
3612 }
3613
3614 sc->stsd_version = avio_r8(pb);
3615 avio_rb24(pb); /* flags */
3616 entries = avio_rb32(pb);
3617
3618 /* Each entry contains a size (4 bytes) and format (4 bytes). */
3619 if (entries <= 0 || entries > atom.size / 8 || entries > 1024) {
3620 av_log(c->fc, AV_LOG_ERROR, "invalid STSD entries %d\n", entries);
3621 return AVERROR_INVALIDDATA;
3622 }
3623
3624 /* Prepare space for hosting multiple extradata. */
3625 sc->extradata = av_calloc(entries, sizeof(*sc->extradata));
3626 if (!sc->extradata)
3627 return AVERROR(ENOMEM);
3628
3629 sc->extradata_size = av_calloc(entries, sizeof(*sc->extradata_size));
3630 if (!sc->extradata_size) {
3631 ret = AVERROR(ENOMEM);
3632 goto fail;
3633 }
3634
3635 ret = ff_mov_read_stsd_entries(c, pb, entries);
3636 if (ret < 0)
3637 goto fail;
3638
3639 /* Restore back the primary extradata. */
3642 if (sc->extradata_size[0]) {
3644 if (!st->codecpar->extradata)
3645 return AVERROR(ENOMEM);
3646 memcpy(st->codecpar->extradata, sc->extradata[0], sc->extradata_size[0]);
3647 }
3648
3649 return mov_finalize_stsd_codec(c, pb, st, sc);
3650fail:
3651 if (sc->extradata) {
3652 int j;
3653 for (j = 0; j < sc->stsd_count; j++)
3654 av_freep(&sc->extradata[j]);
3655 }
3656
3657 sc->stsd_count = 0;
3658 av_freep(&sc->extradata);
3660 return ret;
3661}
3662
3664{
3665 AVStream *st;
3666 MOVStreamContext *sc;
3667 unsigned int i, entries;
3668
3669 if (c->trak_index < 0) {
3670 av_log(c->fc, AV_LOG_WARNING, "STSC outside TRAK\n");
3671 return 0;
3672 }
3673
3674 if (c->fc->nb_streams < 1)
3675 return 0;
3676 st = c->fc->streams[c->fc->nb_streams-1];
3677 sc = st->priv_data;
3678
3679 avio_r8(pb); /* version */
3680 avio_rb24(pb); /* flags */
3681
3682 entries = avio_rb32(pb);
3683 if ((uint64_t)entries * 12 + 4 > atom.size)
3684 return AVERROR_INVALIDDATA;
3685
3686 av_log(c->fc, AV_LOG_TRACE, "track[%u].stsc.entries = %u\n", c->fc->nb_streams - 1, entries);
3687
3688 if (!entries)
3689 return 0;
3690 if (sc->stsc_data) {
3691 av_log(c->fc, AV_LOG_WARNING, "Ignoring duplicated STSC atom\n");
3692 return 0;
3693 }
3694 av_free(sc->stsc_data);
3695 sc->stsc_count = 0;
3696 sc->stsc_data = av_malloc_array(entries, sizeof(*sc->stsc_data));
3697 if (!sc->stsc_data)
3698 return AVERROR(ENOMEM);
3699
3700 for (i = 0; i < entries && !pb->eof_reached; i++) {
3701 sc->stsc_data[i].first = avio_rb32(pb);
3702 sc->stsc_data[i].count = avio_rb32(pb);
3703 sc->stsc_data[i].id = avio_rb32(pb);
3704 }
3705
3706 sc->stsc_count = i;
3707 for (i = sc->stsc_count - 1; i < UINT_MAX; i--) {
3708 int64_t first_min = i + 1;
3709 if ((i+1 < sc->stsc_count && sc->stsc_data[i].first >= sc->stsc_data[i+1].first) ||
3710 (i > 0 && sc->stsc_data[i].first <= sc->stsc_data[i-1].first) ||
3711 sc->stsc_data[i].first < first_min ||
3712 sc->stsc_data[i].count < 1 ||
3713 sc->stsc_data[i].id < 1) {
3714 av_log(c->fc, AV_LOG_WARNING, "STSC entry %d is invalid (first=%d count=%d id=%d)\n", i, sc->stsc_data[i].first, sc->stsc_data[i].count, sc->stsc_data[i].id);
3715 if (i+1 >= sc->stsc_count) {
3716 if (sc->stsc_data[i].count == 0 && i > 0) {
3717 sc->stsc_count --;
3718 continue;
3719 }
3720 sc->stsc_data[i].first = FFMAX(sc->stsc_data[i].first, first_min);
3721 if (i > 0 && sc->stsc_data[i].first <= sc->stsc_data[i-1].first)
3722 sc->stsc_data[i].first = FFMIN(sc->stsc_data[i-1].first + 1LL, INT_MAX);
3723 sc->stsc_data[i].count = FFMAX(sc->stsc_data[i].count, 1);
3724 sc->stsc_data[i].id = FFMAX(sc->stsc_data[i].id, 1);
3725 continue;
3726 }
3727 av_assert0(sc->stsc_data[i+1].first >= 2);
3728 // We replace this entry by the next valid
3729 sc->stsc_data[i].first = sc->stsc_data[i+1].first - 1;
3730 sc->stsc_data[i].count = sc->stsc_data[i+1].count;
3731 sc->stsc_data[i].id = sc->stsc_data[i+1].id;
3732 }
3733 }
3734
3735 if (pb->eof_reached) {
3736 av_log(c->fc, AV_LOG_WARNING, "reached eof, corrupted STSC atom\n");
3737 return AVERROR_EOF;
3738 }
3739
3740 return 0;
3741}
3742
3743static inline int mov_stsc_index_valid(unsigned int index, unsigned int count)
3744{
3745 return index < count - 1;
3746}
3747
3748/* Compute the samples value for the stsc entry at the given index. */
3749static inline int64_t mov_get_stsc_samples(MOVStreamContext *sc, unsigned int index)
3750{
3751 int chunk_count;
3752
3754 chunk_count = sc->stsc_data[index + 1].first - sc->stsc_data[index].first;
3755 else {
3756 // Validation for stsc / stco happens earlier in mov_read_stsc + mov_read_trak.
3758 chunk_count = sc->chunk_count - (sc->stsc_data[index].first - 1);
3759 }
3760
3761 return sc->stsc_data[index].count * (int64_t)chunk_count;
3762}
3763
3765{
3766 AVStream *st;
3767 MOVStreamContext *sc;
3768 unsigned i, entries;
3769
3770 if (c->trak_index < 0) {
3771 av_log(c->fc, AV_LOG_WARNING, "STPS outside TRAK\n");
3772 return 0;
3773 }
3774
3775 if (c->fc->nb_streams < 1)
3776 return 0;
3777 st = c->fc->streams[c->fc->nb_streams-1];
3778 sc = st->priv_data;
3779
3780 avio_rb32(pb); // version + flags
3781
3782 entries = avio_rb32(pb);
3783 if (sc->stps_data)
3784 av_log(c->fc, AV_LOG_WARNING, "Duplicated STPS atom\n");
3785 av_free(sc->stps_data);
3786 sc->stps_count = 0;
3787 sc->stps_data = av_malloc_array(entries, sizeof(*sc->stps_data));
3788 if (!sc->stps_data)
3789 return AVERROR(ENOMEM);
3790
3791 for (i = 0; i < entries && !pb->eof_reached; i++) {
3792 sc->stps_data[i] = avio_rb32(pb);
3793 }
3794
3795 sc->stps_count = i;
3796
3797 if (pb->eof_reached) {
3798 av_log(c->fc, AV_LOG_WARNING, "reached eof, corrupted STPS atom\n");
3799 return AVERROR_EOF;
3800 }
3801
3802 return 0;
3803}
3804
3806{
3807 AVStream *st;
3808 FFStream *sti;
3809 MOVStreamContext *sc;
3810 unsigned int i, entries;
3811
3812 if (c->trak_index < 0) {
3813 av_log(c->fc, AV_LOG_WARNING, "STSS outside TRAK\n");
3814 return 0;
3815 }
3816
3817 if (c->fc->nb_streams < 1)
3818 return 0;
3819 st = c->fc->streams[c->fc->nb_streams-1];
3820 sti = ffstream(st);
3821 sc = st->priv_data;
3822
3823 avio_r8(pb); /* version */
3824 avio_rb24(pb); /* flags */
3825
3826 entries = avio_rb32(pb);
3827
3828 av_log(c->fc, AV_LOG_TRACE, "keyframe_count = %u\n", entries);
3829
3830 if (!entries) {
3831 sc->keyframe_absent = 1;
3834 return 0;
3835 }
3836 if (sc->keyframes)
3837 av_log(c->fc, AV_LOG_WARNING, "Duplicated STSS atom\n");
3838 if (entries >= UINT_MAX / sizeof(int))
3839 return AVERROR_INVALIDDATA;
3840 av_freep(&sc->keyframes);
3841 sc->keyframe_count = 0;
3842 sc->keyframes = av_malloc_array(entries, sizeof(*sc->keyframes));
3843 if (!sc->keyframes)
3844 return AVERROR(ENOMEM);
3845
3846 for (i = 0; i < entries && !pb->eof_reached; i++) {
3847 sc->keyframes[i] = avio_rb32(pb);
3848 }
3849
3850 sc->keyframe_count = i;
3851
3852 if (pb->eof_reached) {
3853 av_log(c->fc, AV_LOG_WARNING, "reached eof, corrupted STSS atom\n");
3854 return AVERROR_EOF;
3855 }
3856
3857 return 0;
3858}
3859
3861{
3862 AVStream *st;
3863 MOVStreamContext *sc;
3864 unsigned int i, entries, sample_size, field_size, num_bytes;
3865 GetBitContext gb;
3866 unsigned char* buf;
3867 int ret;
3868
3869 if (c->trak_index < 0) {
3870 av_log(c->fc, AV_LOG_WARNING, "STSZ outside TRAK\n");
3871 return 0;
3872 }
3873
3874 if (c->fc->nb_streams < 1)
3875 return 0;
3876 st = c->fc->streams[c->fc->nb_streams-1];
3877 sc = st->priv_data;
3878
3879 avio_r8(pb); /* version */
3880 avio_rb24(pb); /* flags */
3881
3882 if (atom.type == MKTAG('s','t','s','z')) {
3883 sample_size = avio_rb32(pb);
3884 if (!sc->sample_size) /* do not overwrite value computed in stsd */
3885 sc->sample_size = sample_size;
3886 sc->stsz_sample_size = sample_size;
3887 field_size = 32;
3888 } else {
3889 sample_size = 0;
3890 avio_rb24(pb); /* reserved */
3891 field_size = avio_r8(pb);
3892 }
3893 entries = avio_rb32(pb);
3894
3895 av_log(c->fc, AV_LOG_TRACE, "sample_size = %u sample_count = %u\n", sc->sample_size, entries);
3896
3897 sc->sample_count = entries;
3898 if (sample_size)
3899 return 0;
3900
3901 if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) {
3902 av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %u\n", field_size);
3903 return AVERROR_INVALIDDATA;
3904 }
3905
3906 if (!entries)
3907 return 0;
3908 if (entries >= (INT_MAX - 4 - 8 * AV_INPUT_BUFFER_PADDING_SIZE) / field_size)
3909 return AVERROR_INVALIDDATA;
3910 if (sc->sample_sizes)
3911 av_log(c->fc, AV_LOG_WARNING, "Duplicated STSZ atom\n");
3912 av_free(sc->sample_sizes);
3913 sc->sample_count = 0;
3914 sc->sample_sizes = av_malloc_array(entries, sizeof(*sc->sample_sizes));
3915 if (!sc->sample_sizes)
3916 return AVERROR(ENOMEM);
3917
3918 num_bytes = (entries*field_size+4)>>3;
3919
3920 buf = av_malloc(num_bytes+AV_INPUT_BUFFER_PADDING_SIZE);
3921 if (!buf) {
3922 av_freep(&sc->sample_sizes);
3923 return AVERROR(ENOMEM);
3924 }
3925
3926 ret = ffio_read_size(pb, buf, num_bytes);
3927 if (ret < 0) {
3928 av_freep(&sc->sample_sizes);
3929 av_free(buf);
3930 av_log(c->fc, AV_LOG_WARNING, "STSZ atom truncated\n");
3931 return 0;
3932 }
3933
3934 init_get_bits(&gb, buf, 8*num_bytes);
3935
3936 for (i = 0; i < entries; i++) {
3937 sc->sample_sizes[i] = get_bits_long(&gb, field_size);
3938 if (sc->sample_sizes[i] > INT64_MAX - sc->data_size) {
3939 av_free(buf);
3940 av_log(c->fc, AV_LOG_ERROR, "Sample size overflow in STSZ\n");
3941 return AVERROR_INVALIDDATA;
3942 }
3943 sc->data_size += sc->sample_sizes[i];
3944 }
3945
3946 sc->sample_count = i;
3947
3948 av_free(buf);
3949
3950 return 0;
3951}
3952
3954{
3955 AVStream *st;
3956 MOVStreamContext *sc;
3957 unsigned int i, entries;
3958 int64_t duration = 0;
3959 int64_t total_sample_count = 0;
3960 int64_t current_dts = 0;
3961 int64_t corrected_dts = 0;
3962
3963 if (c->trak_index < 0) {
3964 av_log(c->fc, AV_LOG_WARNING, "STTS outside TRAK\n");
3965 return 0;
3966 }
3967
3968 if (c->fc->nb_streams < 1)
3969 return 0;
3970 st = c->fc->streams[c->fc->nb_streams-1];
3971 sc = st->priv_data;
3972
3973 avio_r8(pb); /* version */
3974 avio_rb24(pb); /* flags */
3975 entries = avio_rb32(pb);
3976
3977 av_log(c->fc, AV_LOG_TRACE, "track[%u].stts.entries = %u\n",
3978 c->fc->nb_streams-1, entries);
3979
3980 if (sc->stts_data)
3981 av_log(c->fc, AV_LOG_WARNING, "Duplicated STTS atom\n");
3982 av_freep(&sc->stts_data);
3983 sc->stts_count = 0;
3984 if (entries >= INT_MAX / sizeof(*sc->stts_data))
3985 return AVERROR(ENOMEM);
3986
3987 for (i = 0; i < entries && !pb->eof_reached; i++) {
3988 unsigned int sample_duration;
3989 unsigned int sample_count;
3990 unsigned int min_entries = FFMIN(FFMAX(i + 1, 1024 * 1024), entries);
3992 min_entries * sizeof(*sc->stts_data));
3993 if (!stts_data) {
3994 av_freep(&sc->stts_data);
3995 sc->stts_count = 0;
3996 return AVERROR(ENOMEM);
3997 }
3998 sc->stts_count = min_entries;
3999 sc->stts_data = stts_data;
4000
4001 sample_count = avio_rb32(pb);
4002 sample_duration = avio_rb32(pb);
4003
4004 sc->stts_data[i].count= sample_count;
4005 sc->stts_data[i].duration= sample_duration;
4006
4007 av_log(c->fc, AV_LOG_TRACE, "sample_count=%u, sample_duration=%u\n",
4008 sample_count, sample_duration);
4009
4010 /* STTS sample offsets are uint32 but some files store it as int32
4011 * with negative values used to correct DTS delays.
4012 There may be abnormally large values as well. */
4013 if (sample_duration > c->max_stts_delta) {
4014 // assume high delta is a correction if negative when cast as int32
4015 int32_t delta_magnitude = (int32_t)sample_duration;
4016 av_log(c->fc, AV_LOG_WARNING, "Too large sample offset %u in stts entry %u with count %u in st:%d. Clipping to 1.\n",
4017 sample_duration, i, sample_count, st->index);
4018 sc->stts_data[i].duration = 1;
4019 corrected_dts = av_sat_add64(corrected_dts, (delta_magnitude < 0 ? (int64_t)delta_magnitude : 1) * sample_count);
4020 } else {
4021 corrected_dts += sample_duration * (uint64_t)sample_count;
4022 }
4023
4024 current_dts += sc->stts_data[i].duration * (uint64_t)sample_count;
4025
4026 if (current_dts > corrected_dts) {
4027 int64_t drift = av_sat_sub64(current_dts, corrected_dts) / FFMAX(sample_count, 1);
4028 uint32_t correction = (sc->stts_data[i].duration > drift) ? drift : sc->stts_data[i].duration - 1;
4029 current_dts -= correction * (uint64_t)sample_count;
4030 sc->stts_data[i].duration -= correction;
4031 }
4032
4033 duration+=(int64_t)sc->stts_data[i].duration*(uint64_t)sc->stts_data[i].count;
4034 total_sample_count+=sc->stts_data[i].count;
4035 }
4036
4037 sc->stts_count = i;
4038
4039 if (duration > 0 &&
4040 duration <= INT64_MAX - sc->duration_for_fps &&
4041 total_sample_count <= INT_MAX - sc->nb_frames_for_fps) {
4043 sc->nb_frames_for_fps += total_sample_count;
4044 }
4045
4046 if (pb->eof_reached) {
4047 av_log(c->fc, AV_LOG_WARNING, "reached eof, corrupted STTS atom\n");
4048 return AVERROR_EOF;
4049 }
4050
4051 st->nb_frames= total_sample_count;
4052 // The media duration can't be shorter than the sample table, so prefer
4053 // the latter when they differ.
4054 if (duration)
4055 st->duration = duration;
4056
4057 // All samples have zero duration. They have higher chance be chose by
4058 // mov_find_next_sample, which leads to seek again and again.
4059 //
4060 // It's AVERROR_INVALIDDATA actually, but such files exist in the wild.
4061 // So only mark data stream as discarded for safety.
4062 if (!duration && sc->stts_count &&
4064 av_log(c->fc, AV_LOG_WARNING,
4065 "All samples in data stream index:id [%d:%d] have zero "
4066 "duration, stream set to be discarded by default. Override "
4067 "using AVStream->discard or -discard for ffmpeg command.\n",
4068 st->index, sc->id);
4069 st->discard = AVDISCARD_ALL;
4070 }
4071 sc->track_end = duration;
4072 return 0;
4073}
4074
4076{
4077 AVStream *st;
4078 MOVStreamContext *sc;
4079 unsigned int i;
4080 int64_t entries;
4081
4082 if (c->fc->nb_streams < 1)
4083 return 0;
4084 st = c->fc->streams[c->fc->nb_streams - 1];
4085 sc = st->priv_data;
4086
4087 avio_r8(pb); /* version */
4088 avio_rb24(pb); /* flags */
4089 entries = atom.size - 4;
4090
4091 av_log(c->fc, AV_LOG_TRACE, "track[%u].sdtp.entries = %" PRId64 "\n",
4092 c->fc->nb_streams - 1, entries);
4093
4094 if (sc->sdtp_data)
4095 av_log(c->fc, AV_LOG_WARNING, "Duplicated SDTP atom\n");
4096 av_freep(&sc->sdtp_data);
4097 sc->sdtp_count = 0;
4098
4099 if (entries < 0 || entries > UINT_MAX)
4100 return AVERROR(ERANGE);
4101
4102 sc->sdtp_data = av_malloc(entries);
4103 if (!sc->sdtp_data)
4104 return AVERROR(ENOMEM);
4105
4106 for (i = 0; i < entries && !pb->eof_reached; i++)
4107 sc->sdtp_data[i] = avio_r8(pb);
4108 sc->sdtp_count = i;
4109
4110 return 0;
4111}
4112
4113static void mov_update_dts_shift(MOVStreamContext *sc, int duration, void *logctx)
4114{
4115 if (duration < 0) {
4116 if (duration == INT_MIN) {
4117 av_log(logctx, AV_LOG_WARNING, "mov_update_dts_shift(): dts_shift set to %d\n", INT_MAX);
4118 duration++;
4119 }
4120 sc->dts_shift = FFMAX(sc->dts_shift, -duration);
4121 }
4122}
4123
4125{
4126 AVStream *st;
4127 MOVStreamContext *sc;
4128 unsigned int i, entries, ctts_count = 0;
4129
4130 if (c->trak_index < 0) {
4131 av_log(c->fc, AV_LOG_WARNING, "CTTS outside TRAK\n");
4132 return 0;
4133 }
4134
4135 if (c->fc->nb_streams < 1)
4136 return 0;
4137 st = c->fc->streams[c->fc->nb_streams-1];
4138 sc = st->priv_data;
4139
4140 avio_r8(pb); /* version */
4141 avio_rb24(pb); /* flags */
4142 entries = avio_rb32(pb);
4143
4144 av_log(c->fc, AV_LOG_TRACE, "track[%u].ctts.entries = %u\n", c->fc->nb_streams - 1, entries);
4145
4146 if (!entries)
4147 return 0;
4148 if (entries >= UINT_MAX / sizeof(*sc->ctts_data))
4149 return AVERROR_INVALIDDATA;
4150 av_freep(&sc->ctts_data);
4151 sc->ctts_data = av_fast_realloc(NULL, &sc->ctts_allocated_size, entries * sizeof(*sc->ctts_data));
4152 if (!sc->ctts_data)
4153 return AVERROR(ENOMEM);
4154
4155 for (i = 0; i < entries && !pb->eof_reached; i++) {
4156 MOVCtts *ctts_data;
4157 const size_t min_size_needed = (ctts_count + 1) * sizeof(MOVCtts);
4158 const size_t requested_size =
4159 min_size_needed > sc->ctts_allocated_size ?
4160 FFMAX(min_size_needed, 2 * sc->ctts_allocated_size) :
4161 min_size_needed;
4162 int count = avio_rb32(pb);
4163 int duration = avio_rb32(pb);
4164
4165 if (count <= 0) {
4166 av_log(c->fc, AV_LOG_TRACE,
4167 "ignoring CTTS entry with count=%d duration=%d\n",
4168 count, duration);
4169 continue;
4170 }
4171
4172 if (ctts_count >= UINT_MAX / sizeof(MOVCtts) - 1)
4173 return AVERROR(ENOMEM);
4174
4175 ctts_data = av_fast_realloc(sc->ctts_data, &sc->ctts_allocated_size, requested_size);
4176
4177 if (!ctts_data)
4178 return AVERROR(ENOMEM);
4179
4180 sc->ctts_data = ctts_data;
4181
4182 ctts_data[ctts_count].count = count;
4183 ctts_data[ctts_count].offset = duration;
4184 ctts_count++;
4185
4186 av_log(c->fc, AV_LOG_TRACE, "count=%d, duration=%d\n",
4187 count, duration);
4188
4189 if (i+2<entries)
4191 }
4192
4193 sc->ctts_count = ctts_count;
4194
4195 if (pb->eof_reached) {
4196 av_log(c->fc, AV_LOG_WARNING, "reached eof, corrupted CTTS atom\n");
4197 return AVERROR_EOF;
4198 }
4199
4200 av_log(c->fc, AV_LOG_TRACE, "dts shift %d\n", sc->dts_shift);
4201
4202 return 0;
4203}
4204
4206{
4207 AVStream *st;
4208 MOVStreamContext *sc;
4209 uint8_t version;
4210 uint32_t grouping_type;
4211 uint32_t default_length;
4212 av_unused uint32_t default_group_description_index;
4213 uint32_t entry_count;
4214
4215 if (c->fc->nb_streams < 1)
4216 return 0;
4217 st = c->fc->streams[c->fc->nb_streams - 1];
4218 sc = st->priv_data;
4219
4220 version = avio_r8(pb); /* version */
4221 avio_rb24(pb); /* flags */
4222 grouping_type = avio_rl32(pb);
4223
4224 /*
4225 * This function only supports "sync" boxes, but the code is able to parse
4226 * other boxes (such as "tscl", "tsas" and "stsa")
4227 */
4228 if (grouping_type != MKTAG('s','y','n','c'))
4229 return 0;
4230
4231 default_length = version >= 1 ? avio_rb32(pb) : 0;
4232 default_group_description_index = version >= 2 ? avio_rb32(pb) : 0;
4233 entry_count = avio_rb32(pb);
4234
4235 if (entry_count > atom.size)
4236 return AVERROR_INVALIDDATA;
4237
4238 av_freep(&sc->sgpd_sync);
4239 sc->sgpd_sync_count = entry_count;
4240 sc->sgpd_sync = av_calloc(entry_count, sizeof(*sc->sgpd_sync));
4241 if (!sc->sgpd_sync)
4242 return AVERROR(ENOMEM);
4243
4244 for (uint32_t i = 0; i < entry_count && !pb->eof_reached; i++) {
4245 uint32_t description_length = default_length;
4246 if (version >= 1 && default_length == 0)
4247 description_length = avio_rb32(pb);
4248 if (grouping_type == MKTAG('s','y','n','c')) {
4249 const uint8_t nal_unit_type = avio_r8(pb) & 0x3f;
4250 sc->sgpd_sync[i] = nal_unit_type;
4251 description_length -= 1;
4252 }
4253 avio_skip(pb, description_length);
4254 }
4255
4256 if (pb->eof_reached) {
4257 av_log(c->fc, AV_LOG_WARNING, "reached eof, corrupted SGPD atom\n");
4258 return AVERROR_EOF;
4259 }
4260
4261 return 0;
4262}
4263
4265{
4266 AVStream *st;
4267 MOVStreamContext *sc;
4268 unsigned int i, entries;
4269 uint8_t version;
4270 uint32_t grouping_type;
4271 MOVSbgp *table, **tablep;
4272 int *table_count;
4273
4274 if (c->fc->nb_streams < 1)
4275 return 0;
4276 st = c->fc->streams[c->fc->nb_streams-1];
4277 sc = st->priv_data;
4278
4279 version = avio_r8(pb); /* version */
4280 avio_rb24(pb); /* flags */
4281 grouping_type = avio_rl32(pb);
4282
4283 if (grouping_type == MKTAG('r','a','p',' ')) {
4284 tablep = &sc->rap_group;
4285 table_count = &sc->rap_group_count;
4286 } else if (grouping_type == MKTAG('s','y','n','c')) {
4287 tablep = &sc->sync_group;
4288 table_count = &sc->sync_group_count;
4289 } else {
4290 return 0;
4291 }
4292
4293 if (version == 1)
4294 avio_rb32(pb); /* grouping_type_parameter */
4295
4296 entries = avio_rb32(pb);
4297 if (!entries)
4298 return 0;
4299 if (*tablep)
4300 av_log(c->fc, AV_LOG_WARNING, "Duplicated SBGP %s atom\n", av_fourcc2str(grouping_type));
4301 av_freep(tablep);
4302 table = av_malloc_array(entries, sizeof(*table));
4303 if (!table)
4304 return AVERROR(ENOMEM);
4305 *tablep = table;
4306
4307 for (i = 0; i < entries && !pb->eof_reached; i++) {
4308 table[i].count = avio_rb32(pb); /* sample_count */
4309 table[i].index = avio_rb32(pb); /* group_description_index */
4310 }
4311
4312 *table_count = i;
4313
4314 if (pb->eof_reached) {
4315 av_log(c->fc, AV_LOG_WARNING, "reached eof, corrupted SBGP atom\n");
4316 return AVERROR_EOF;
4317 }
4318
4319 return 0;
4320}
4321
4322/**
4323 * Get ith edit list entry (media time, duration).
4324 */
4326 const MOVStreamContext *msc,
4327 unsigned int edit_list_index,
4328 int64_t *edit_list_media_time,
4329 int64_t *edit_list_duration,
4330 int64_t global_timescale)
4331{
4332 if (edit_list_index == msc->elst_count) {
4333 return 0;
4334 }
4335 *edit_list_media_time = msc->elst_data[edit_list_index].time;
4336 *edit_list_duration = msc->elst_data[edit_list_index].duration;
4337
4338 /* duration is in global timescale units;convert to msc timescale */
4339 if (global_timescale == 0) {
4340 avpriv_request_sample(mov->fc, "Support for mvhd.timescale = 0 with editlists");
4341 return 0;
4342 }
4343 *edit_list_duration = av_rescale(*edit_list_duration, msc->time_scale,
4344 global_timescale);
4345
4346 if (*edit_list_duration < 0 ||
4347 *edit_list_media_time > INT64_MAX - *edit_list_duration)
4348 *edit_list_duration = 0;
4349
4350 return 1;
4351}
4352
4353/**
4354 * Find the closest previous frame to the timestamp_pts, in e_old index
4355 * entries. Searching for just any frame / just key frames can be controlled by
4356 * last argument 'flag'.
4357 * Note that if ctts_data is not NULL, we will always search for a key frame
4358 * irrespective of the value of 'flag'. If we don't find any keyframe, we will
4359 * return the first frame of the video.
4360 *
4361 * Here the timestamp_pts is considered to be a presentation timestamp and
4362 * the timestamp of index entries are considered to be decoding timestamps.
4363 *
4364 * Returns 0 if successful in finding a frame, else returns -1.
4365 * Places the found index corresponding output arg.
4366 *
4367 * If ctts_old is not NULL, then refines the searched entry by searching
4368 * backwards from the found timestamp, to find the frame with correct PTS.
4369 *
4370 * Places the found ctts_index and ctts_sample in corresponding output args.
4371 */
4373 AVIndexEntry *e_old,
4374 int nb_old,
4375 MOVTimeToSample *tts_data,
4376 int64_t tts_count,
4377 int64_t timestamp_pts,
4378 int flag,
4379 int64_t* index,
4380 int64_t* tts_index,
4381 int64_t* tts_sample)
4382{
4383 MOVStreamContext *msc = st->priv_data;
4384 FFStream *const sti = ffstream(st);
4385 AVIndexEntry *e_keep = sti->index_entries;
4386 int nb_keep = sti->nb_index_entries;
4387 int64_t i = 0;
4388
4390
4391 // If dts_shift > 0, then all the index timestamps will have to be offset by
4392 // at least dts_shift amount to obtain PTS.
4393 // Hence we decrement the searched timestamp_pts by dts_shift to find the closest index element.
4394 if (msc->dts_shift > 0) {
4395 timestamp_pts -= msc->dts_shift;
4396 }
4397
4398 sti->index_entries = e_old;
4399 sti->nb_index_entries = nb_old;
4401
4402 // Keep going backwards in the index entries until the timestamp is the same.
4403 if (*index >= 0) {
4404 for (i = *index; i > 0 && e_old[i].timestamp == e_old[i - 1].timestamp;
4405 i--) {
4406 if ((flag & AVSEEK_FLAG_ANY) ||
4407 (e_old[i - 1].flags & AVINDEX_KEYFRAME)) {
4408 *index = i - 1;
4409 }
4410 }
4411 }
4412
4413 // If we have CTTS then refine the search, by searching backwards over PTS
4414 // computed by adding corresponding CTTS durations to index timestamps.
4415 if (msc->ctts_count && *index >= 0) {
4416 av_assert0(tts_index);
4417 av_assert0(tts_sample);
4418 // Find out the ctts_index for the found frame.
4419 *tts_index = FFMIN(*index, tts_count);
4420 *tts_sample = 0;
4421
4422 while (*index >= 0 && (*tts_index) >= 0 && (*tts_index) < tts_count) {
4423 // Find a "key frame" with PTS <= timestamp_pts (So that we can decode B-frames correctly).
4424 // No need to add dts_shift to the timestamp here because timestamp_pts has already been
4425 // compensated by dts_shift above.
4426 if ((e_old[*index].timestamp + tts_data[*tts_index].offset) <= timestamp_pts &&
4427 (e_old[*index].flags & AVINDEX_KEYFRAME)) {
4428 break;
4429 }
4430
4431 (*index)--;
4432 if (*tts_sample == 0) {
4433 (*tts_index)--;
4434 if (*tts_index >= 0)
4435 *tts_sample = tts_data[*tts_index].count - 1;
4436 } else {
4437 (*tts_sample)--;
4438 }
4439 }
4440 }
4441
4442 /* restore AVStream state*/
4443 sti->index_entries = e_keep;
4444 sti->nb_index_entries = nb_keep;
4445 return *index >= 0 ? 0 : -1;
4446}
4447
4448/**
4449 * Add index entry with the given values, to the end of ffstream(st)->index_entries.
4450 * Returns the new size ffstream(st)->index_entries if successful, else returns -1.
4451 *
4452 * This function is similar to ff_add_index_entry in libavformat/utils.c
4453 * except that here we are always unconditionally adding an index entry to
4454 * the end, instead of searching the entries list and skipping the add if
4455 * there is an existing entry with the same timestamp.
4456 * This is needed because the mov_fix_index calls this func with the same
4457 * unincremented timestamp for successive discarded frames.
4458 */
4460 int size, int distance, int flags)
4461{
4462 FFStream *const sti = ffstream(st);
4463 AVIndexEntry *entries, *ie;
4464 int64_t index = -1;
4465 const size_t min_size_needed = (sti->nb_index_entries + 1) * sizeof(AVIndexEntry);
4466
4467 // Double the allocation each time, to lower memory fragmentation.
4468 // Another difference from ff_add_index_entry function.
4469 const size_t requested_size =
4470 min_size_needed > sti->index_entries_allocated_size ?
4471 FFMAX(min_size_needed, 2 * sti->index_entries_allocated_size) :
4472 min_size_needed;
4473
4474 if (sti->nb_index_entries + 1U >= UINT_MAX / sizeof(AVIndexEntry))
4475 return -1;
4476
4477 entries = av_fast_realloc(sti->index_entries,
4479 requested_size);
4480 if (!entries)
4481 return -1;
4482
4483 sti->index_entries = entries;
4484
4485 index = sti->nb_index_entries++;
4486 ie= &entries[index];
4487
4488 ie->pos = pos;
4489 ie->timestamp = timestamp;
4491 ie->size= size;
4492 ie->flags = flags;
4493 return index;
4494}
4495
4496/**
4497 * Rewrite timestamps of index entries in the range [end_index - frame_duration_buffer_size, end_index)
4498 * by subtracting end_ts successively by the amounts given in frame_duration_buffer.
4499 */
4500static void fix_index_entry_timestamps(AVStream* st, int end_index, int64_t end_ts,
4501 int64_t* frame_duration_buffer,
4502 int frame_duration_buffer_size) {
4503 FFStream *const sti = ffstream(st);
4504 int i = 0;
4505 av_assert0(end_index >= 0 && end_index <= sti->nb_index_entries);
4506 for (i = 0; i < frame_duration_buffer_size; i++) {
4507 end_ts -= frame_duration_buffer[frame_duration_buffer_size - 1 - i];
4508 sti->index_entries[end_index - 1 - i].timestamp = end_ts;
4509 }
4510}
4511
4512static int add_tts_entry(MOVTimeToSample **tts_data, unsigned int *tts_count, unsigned int *allocated_size,
4513 int count, int offset, unsigned int duration)
4514{
4515 MOVTimeToSample *tts_buf_new;
4516 const size_t min_size_needed = (*tts_count + 1) * sizeof(MOVTimeToSample);
4517 const size_t requested_size =
4518 min_size_needed > *allocated_size ?
4519 FFMAX(min_size_needed, 2 * (*allocated_size)) :
4520 min_size_needed;
4521
4522 if ((unsigned)(*tts_count) >= UINT_MAX / sizeof(MOVTimeToSample) - 1)
4523 return -1;
4524
4525 tts_buf_new = av_fast_realloc(*tts_data, allocated_size, requested_size);
4526
4527 if (!tts_buf_new)
4528 return -1;
4529
4530 *tts_data = tts_buf_new;
4531
4532 tts_buf_new[*tts_count].count = count;
4533 tts_buf_new[*tts_count].offset = offset;
4534 tts_buf_new[*tts_count].duration = duration;
4535
4536 *tts_count = (*tts_count) + 1;
4537 return 0;
4538}
4539
4540#define MAX_REORDER_DELAY 16
4542{
4543 MOVStreamContext *msc = st->priv_data;
4544 FFStream *const sti = ffstream(st);
4545 int ctts_ind = 0;
4546 int ctts_sample = 0;
4547 int64_t pts_buf[MAX_REORDER_DELAY + 1]; // Circular buffer to sort pts.
4548 int buf_start = 0;
4549 int j, r, num_swaps;
4550
4551 for (j = 0; j < MAX_REORDER_DELAY + 1; j++)
4552 pts_buf[j] = INT64_MIN;
4553
4554 if (st->codecpar->video_delay <= 0 && msc->ctts_count &&
4556 st->codecpar->video_delay = 0;
4557 for (int ind = 0; ind < sti->nb_index_entries && ctts_ind < msc->tts_count; ++ind) {
4558 // Point j to the last elem of the buffer and insert the current pts there.
4559 j = buf_start;
4560 buf_start = (buf_start + 1);
4561 if (buf_start == MAX_REORDER_DELAY + 1)
4562 buf_start = 0;
4563
4564 pts_buf[j] = sti->index_entries[ind].timestamp + msc->tts_data[ctts_ind].offset;
4565
4566 // The timestamps that are already in the sorted buffer, and are greater than the
4567 // current pts, are exactly the timestamps that need to be buffered to output PTS
4568 // in correct sorted order.
4569 // Hence the video delay (which is the buffer size used to sort DTS and output PTS),
4570 // can be computed as the maximum no. of swaps any particular timestamp needs to
4571 // go through, to keep this buffer in sorted order.
4572 num_swaps = 0;
4573 while (j != buf_start) {
4574 r = j - 1;
4575 if (r < 0) r = MAX_REORDER_DELAY;
4576 if (pts_buf[j] < pts_buf[r]) {
4577 FFSWAP(int64_t, pts_buf[j], pts_buf[r]);
4578 ++num_swaps;
4579 } else {
4580 break;
4581 }
4582 j = r;
4583 }
4584 st->codecpar->video_delay = FFMAX(st->codecpar->video_delay, num_swaps);
4585
4586 ctts_sample++;
4587 if (ctts_sample == msc->tts_data[ctts_ind].count) {
4588 ctts_ind++;
4589 ctts_sample = 0;
4590 }
4591 }
4592 av_log(c->fc, AV_LOG_DEBUG, "Setting codecpar->delay to %d for stream st: %d\n",
4593 st->codecpar->video_delay, st->index);
4594 }
4595}
4596
4598{
4599 sc->current_sample++;
4600 sc->current_index++;
4601 if (sc->index_ranges &&
4603 sc->current_index_range->end) {
4604 sc->current_index_range++;
4606 }
4607}
4608
4610{
4611 sc->current_sample--;
4612 sc->current_index--;
4613 if (sc->index_ranges &&
4616 sc->current_index_range--;
4617 sc->current_index = sc->current_index_range->end - 1;
4618 }
4619}
4620
4621static void mov_current_sample_set(MOVStreamContext *sc, int current_sample)
4622{
4623 int64_t range_size;
4624
4625 sc->current_sample = current_sample;
4626 sc->current_index = current_sample;
4627 if (!sc->index_ranges) {
4628 return;
4629 }
4630
4631 for (sc->current_index_range = sc->index_ranges;
4633 sc->current_index_range++) {
4634 range_size = sc->current_index_range->end - sc->current_index_range->start;
4635 if (range_size > current_sample) {
4636 sc->current_index = sc->current_index_range->start + current_sample;
4637 break;
4638 }
4639 current_sample -= range_size;
4640 }
4641}
4642
4643/**
4644 * Fix ffstream(st)->index_entries, so that it contains only the entries (and the entries
4645 * which are needed to decode them) that fall in the edit list time ranges.
4646 * Also fixes the timestamps of the index entries to match the timeline
4647 * specified the edit lists.
4648 */
4649static void mov_fix_index(MOVContext *mov, AVStream *st)
4650{
4651 MOVStreamContext *msc = st->priv_data;
4652 FFStream *const sti = ffstream(st);
4653 AVIndexEntry *e_old = sti->index_entries;
4654 int nb_old = sti->nb_index_entries;
4655 const AVIndexEntry *e_old_end = e_old + nb_old;
4656 const AVIndexEntry *current = NULL;
4657 MOVTimeToSample *tts_data_old = msc->tts_data;
4658 int64_t tts_index_old = 0;
4659 int64_t tts_sample_old = 0;
4660 int64_t tts_count_old = msc->tts_count;
4661 int64_t edit_list_media_time = 0;
4662 int64_t edit_list_duration = 0;
4663 int64_t frame_duration = 0;
4664 int64_t edit_list_dts_counter = 0;
4665 int64_t edit_list_dts_entry_end = 0;
4666 int64_t edit_list_start_tts_sample = 0;
4667 int64_t curr_cts;
4668 int64_t curr_ctts = 0;
4669 int64_t empty_edits_sum_duration = 0;
4670 int64_t edit_list_index = 0;
4671 int64_t index;
4672 int flags;
4673 int64_t start_dts = 0;
4674 int64_t edit_list_start_encountered = 0;
4675 int64_t search_timestamp = 0;
4676 int64_t* frame_duration_buffer = NULL;
4677 int num_discarded_begin = 0;
4678 int first_non_zero_audio_edit = -1;
4679 int packet_skip_samples = 0;
4680 MOVIndexRange *current_index_range = NULL;
4681 int found_keyframe_after_edit = 0;
4682 int found_non_empty_edit = 0;
4683
4684 if (!msc->elst_data || msc->elst_count <= 0 || nb_old <= 0) {
4685 return;
4686 }
4687
4688 int64_t max_entries = nb_old * 16LL + (1 << 16);
4689
4690 // allocate the index ranges array
4691 msc->index_ranges = av_malloc_array(msc->elst_count + 1,
4692 sizeof(msc->index_ranges[0]));
4693 if (!msc->index_ranges) {
4694 av_log(mov->fc, AV_LOG_ERROR, "Cannot allocate index ranges buffer\n");
4695 return;
4696 }
4698
4699 // Clean AVStream from traces of old index
4700 sti->index_entries = NULL;
4702 sti->nb_index_entries = 0;
4703
4704 // Clean time to sample fields of MOVStreamContext
4705 msc->tts_data = NULL;
4706 msc->tts_count = 0;
4707 msc->tts_index = 0;
4708 msc->tts_sample = 0;
4709 msc->tts_allocated_size = 0;
4710
4711 // Reinitialize min_corrected_pts so that it can be computed again.
4712 msc->min_corrected_pts = -1;
4713
4714 // If the dts_shift is positive (in case of negative ctts values in mov),
4715 // then negate the DTS by dts_shift
4716 if (msc->dts_shift > 0) {
4717 edit_list_dts_entry_end -= msc->dts_shift;
4718 av_log(mov->fc, AV_LOG_DEBUG, "Shifting DTS by %d because of negative CTTS.\n", msc->dts_shift);
4719 }
4720
4721 start_dts = edit_list_dts_entry_end;
4722
4723 while (get_edit_list_entry(mov, msc, edit_list_index, &edit_list_media_time,
4724 &edit_list_duration, mov->time_scale)) {
4725 av_log(mov->fc, AV_LOG_DEBUG, "Processing st: %d, edit list %"PRId64" - media time: %"PRId64", duration: %"PRId64"\n",
4726 st->index, edit_list_index, edit_list_media_time, edit_list_duration);
4727 edit_list_index++;
4728 edit_list_dts_counter = edit_list_dts_entry_end;
4729 edit_list_dts_entry_end = av_sat_add64(edit_list_dts_entry_end, edit_list_duration);
4730 if (edit_list_dts_entry_end == INT64_MAX) {
4731 av_log(mov->fc, AV_LOG_ERROR, "Cannot calculate dts entry length with duration %"PRId64"\n",
4732 edit_list_duration);
4733 break;
4734 }
4735 num_discarded_begin = 0;
4736 if (edit_list_media_time == -1) {
4737 if (!found_non_empty_edit)
4738 empty_edits_sum_duration += edit_list_duration;
4739 continue;
4740 }
4741 found_non_empty_edit = 1;
4742
4743 // If we encounter a non-negative edit list reset the skip_samples/initial_padding fields and set them
4744 // according to the edit list below.
4746 if (first_non_zero_audio_edit < 0) {
4747 first_non_zero_audio_edit = 1;
4748 } else {
4749 first_non_zero_audio_edit = 0;
4750 }
4751
4752 if (first_non_zero_audio_edit > 0)
4753 sti->skip_samples = st->codecpar->initial_padding = 0;
4754 }
4755
4756 // While reordering frame index according to edit list we must handle properly
4757 // the scenario when edit list entry starts from none key frame.
4758 // We find closest previous key frame and preserve it and consequent frames in index.
4759 // All frames which are outside edit list entry time boundaries will be dropped after decoding.
4760 search_timestamp = edit_list_media_time;
4762 // Audio decoders like AAC need need a decoder delay samples previous to the current sample,
4763 // to correctly decode this frame. Hence for audio we seek to a frame 1 sec. before the
4764 // edit_list_media_time to cover the decoder delay.
4765 search_timestamp = FFMAX(av_sat_sub64(search_timestamp, msc->time_scale), e_old[0].timestamp);
4766 }
4767
4768 if (find_prev_closest_index(st, e_old, nb_old, tts_data_old, tts_count_old, search_timestamp, 0,
4769 &index, &tts_index_old, &tts_sample_old) < 0) {
4770 av_log(mov->fc, AV_LOG_WARNING,
4771 "st: %d edit list: %"PRId64" Missing key frame while searching for timestamp: %"PRId64"\n",
4772 st->index, edit_list_index, search_timestamp);
4773 if (find_prev_closest_index(st, e_old, nb_old, tts_data_old, tts_count_old, search_timestamp, AVSEEK_FLAG_ANY,
4774 &index, &tts_index_old, &tts_sample_old) < 0) {
4775 av_log(mov->fc, AV_LOG_WARNING,
4776 "st: %d edit list %"PRId64" Cannot find an index entry before timestamp: %"PRId64".\n",
4777 st->index, edit_list_index, search_timestamp);
4778 index = 0;
4779 tts_index_old = 0;
4780 tts_sample_old = 0;
4781 }
4782 }
4783 current = e_old + index;
4784 edit_list_start_tts_sample = tts_sample_old;
4785
4786 // Iterate over index and arrange it according to edit list
4787 edit_list_start_encountered = 0;
4788 found_keyframe_after_edit = 0;
4789 for (; current < e_old_end; current++, index++) {
4790 if (sti->nb_index_entries >= max_entries) {
4791 av_log(mov->fc, AV_LOG_ERROR, "Edit list expands the sample index beyond %"PRId64" entries\n",
4792 max_entries);
4793 goto truncated;
4794 }
4795 // check if frame outside edit list mark it for discard
4796 frame_duration = (current + 1 < e_old_end) ?
4797 ((current + 1)->timestamp - current->timestamp) : edit_list_duration;
4798
4799 flags = current->flags;
4800
4801 // frames (pts) before or after edit list
4802 curr_cts = current->timestamp + msc->dts_shift;
4803 curr_ctts = 0;
4804
4805 if (tts_data_old && tts_index_old < tts_count_old) {
4806 curr_ctts = tts_data_old[tts_index_old].offset;
4807 av_log(mov->fc, AV_LOG_TRACE, "stts: %"PRId64" ctts: %"PRId64", tts_index: %"PRId64", tts_count: %"PRId64"\n",
4808 curr_cts, curr_ctts, tts_index_old, tts_count_old);
4809 curr_cts += curr_ctts;
4810 tts_sample_old++;
4811 if (tts_sample_old == tts_data_old[tts_index_old].count) {
4812 if (add_tts_entry(&msc->tts_data, &msc->tts_count,
4813 &msc->tts_allocated_size,
4814 tts_data_old[tts_index_old].count - edit_list_start_tts_sample,
4815 tts_data_old[tts_index_old].offset, tts_data_old[tts_index_old].duration) == -1) {
4816 av_log(mov->fc, AV_LOG_ERROR, "Cannot add Time To Sample entry %"PRId64" - {%"PRId64", %d}\n",
4817 tts_index_old,
4818 tts_data_old[tts_index_old].count - edit_list_start_tts_sample,
4819 tts_data_old[tts_index_old].offset);
4820 break;
4821 }
4822 tts_index_old++;
4823 tts_sample_old = 0;
4824 edit_list_start_tts_sample = 0;
4825 }
4826 }
4827
4828 if (curr_cts < edit_list_media_time || curr_cts >= (edit_list_duration + edit_list_media_time)) {
4830 curr_cts < edit_list_media_time && curr_cts + frame_duration > edit_list_media_time &&
4831 first_non_zero_audio_edit > 0) {
4832 packet_skip_samples = edit_list_media_time - curr_cts;
4833 sti->skip_samples += packet_skip_samples;
4834
4835 // Shift the index entry timestamp by packet_skip_samples to be correct.
4836 edit_list_dts_counter -= packet_skip_samples;
4837 if (edit_list_start_encountered == 0) {
4838 edit_list_start_encountered = 1;
4839 // Make timestamps strictly monotonically increasing for audio, by rewriting timestamps for
4840 // discarded packets.
4841 if (frame_duration_buffer) {
4842 fix_index_entry_timestamps(st, sti->nb_index_entries, edit_list_dts_counter,
4843 frame_duration_buffer, num_discarded_begin);
4844 av_freep(&frame_duration_buffer);
4845 }
4846 }
4847
4848 av_log(mov->fc, AV_LOG_DEBUG, "skip %d audio samples from curr_cts: %"PRId64"\n", packet_skip_samples, curr_cts);
4849 } else {
4851 av_log(mov->fc, AV_LOG_DEBUG, "drop a frame at curr_cts: %"PRId64" @ %"PRId64"\n", curr_cts, index);
4852
4853 if (edit_list_start_encountered == 0) {
4854 if (!av_dynarray2_add((void **)&frame_duration_buffer, &num_discarded_begin,
4855 sizeof(*frame_duration_buffer),
4856 (const uint8_t *)&frame_duration)) {
4857 av_log(mov->fc, AV_LOG_ERROR, "Cannot reallocate frame duration buffer\n");
4858 break;
4859 }
4860
4861 // Increment skip_samples for the first non-zero audio edit list
4863 first_non_zero_audio_edit > 0 && st->codecpar->codec_id != AV_CODEC_ID_VORBIS) {
4864 sti->skip_samples += frame_duration;
4865 }
4866 }
4867 }
4868 } else {
4869 if (msc->min_corrected_pts < 0) {
4870 msc->min_corrected_pts = edit_list_dts_counter + curr_ctts + msc->dts_shift;
4871 } else {
4872 msc->min_corrected_pts = FFMIN(msc->min_corrected_pts, edit_list_dts_counter + curr_ctts + msc->dts_shift);
4873 }
4874 if (edit_list_start_encountered == 0) {
4875 edit_list_start_encountered = 1;
4876 // Make timestamps strictly monotonically increasing by rewriting timestamps for
4877 // discarded packets.
4878 if (frame_duration_buffer) {
4879 fix_index_entry_timestamps(st, sti->nb_index_entries, edit_list_dts_counter,
4880 frame_duration_buffer, num_discarded_begin);
4881 av_freep(&frame_duration_buffer);
4882 }
4883 }
4884 }
4885
4886 if (add_index_entry(st, current->pos, edit_list_dts_counter, current->size,
4887 current->min_distance, flags) == -1) {
4888 av_log(mov->fc, AV_LOG_ERROR, "Cannot add index entry\n");
4889 break;
4890 }
4891
4892 // Update the index ranges array
4893 if (!current_index_range || index != current_index_range->end) {
4894 current_index_range = current_index_range ? current_index_range + 1
4895 : msc->index_ranges;
4896 current_index_range->start = index;
4897 }
4898 current_index_range->end = index + 1;
4899
4900 // Only start incrementing DTS in frame_duration amounts, when we encounter a frame in edit list.
4901 if (edit_list_start_encountered > 0) {
4902 edit_list_dts_counter = edit_list_dts_counter + frame_duration;
4903 }
4904
4905 // Break when found first key frame after edit entry completion
4906 if ((curr_cts + frame_duration >= (edit_list_duration + edit_list_media_time)) &&
4908 if (msc->ctts_count) {
4909 // If we have CTTS and this is the first keyframe after edit elist,
4910 // wait for one more, because there might be trailing B-frames after this I-frame
4911 // that do belong to the edit.
4912 if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO && found_keyframe_after_edit == 0) {
4913 found_keyframe_after_edit = 1;
4914 continue;
4915 }
4916 if (tts_sample_old != 0) {
4917 if (add_tts_entry(&msc->tts_data, &msc->tts_count,
4918 &msc->tts_allocated_size,
4919 tts_sample_old - edit_list_start_tts_sample,
4920 tts_data_old[tts_index_old].offset, tts_data_old[tts_index_old].duration) == -1) {
4921 av_log(mov->fc, AV_LOG_ERROR, "Cannot add Time To Sample entry %"PRId64" - {%"PRId64", %d}\n",
4922 tts_index_old, tts_sample_old - edit_list_start_tts_sample,
4923 tts_data_old[tts_index_old].offset);
4924 break;
4925 }
4926 }
4927 }
4928 break;
4929 }
4930 }
4931 }
4932truncated:
4933 // If there are empty edits, then msc->min_corrected_pts might be positive
4934 // intentionally. So we subtract the sum duration of empty edits here.
4935 msc->min_corrected_pts -= empty_edits_sum_duration;
4936
4937 // If the minimum pts turns out to be greater than zero after fixing the index, then we subtract the
4938 // dts by that amount to make the first pts zero.
4940 if (msc->min_corrected_pts > 0) {
4941 av_log(mov->fc, AV_LOG_DEBUG, "Offset DTS by %"PRId64" to make first pts zero.\n", msc->min_corrected_pts);
4942 for (int i = 0; i < sti->nb_index_entries; ++i)
4944 }
4945 }
4946 // Start time should be equal to zero or the duration of any empty edits.
4947 st->start_time = empty_edits_sum_duration;
4948
4949 // Update av stream length, if it ends up shorter than the track's media duration
4950 st->duration = FFMIN(st->duration, edit_list_dts_entry_end - start_dts);
4951 // The skipped samples are counted in the track's clock. With explicit SBR
4952 // signalling, HE-AAC often keeps it at the core rate, half the output
4953 // rate. A sample rate below the clock may be the core rate of implicit
4954 // SBR. With several sample descriptions, the rate may come from one the
4955 // packets do not use.
4956 if (st->codecpar->codec_id == AV_CODEC_ID_AAC && msc->stsd_count == 1 &&
4957 st->codecpar->sample_rate > msc->time_scale && msc->time_scale > 0)
4959 msc->time_scale), INT_MAX);
4961
4962 // Free the old index and the old CTTS structures
4963 av_free(e_old);
4964 av_free(tts_data_old);
4965 av_freep(&frame_duration_buffer);
4966
4967 // Null terminate the index ranges array
4968 current_index_range = current_index_range ? current_index_range + 1
4969 : msc->index_ranges;
4970 current_index_range->start = 0;
4971 current_index_range->end = 0;
4972 msc->current_index = msc->index_ranges[0].start;
4973}
4974
4975static uint32_t get_sgpd_sync_index(const MOVStreamContext *sc, int nal_unit_type)
4976{
4977 for (uint32_t i = 0; i < sc->sgpd_sync_count; i++)
4978 if (sc->sgpd_sync[i] == nal_unit_type)
4979 return i + 1;
4980 return 0;
4981}
4982
4984{
4985 int k;
4986 int sample_id = 0;
4987 uint32_t cra_index;
4988 MOVStreamContext *sc = st->priv_data;
4989
4991 return 0;
4992
4993 /* Build an unrolled index of the samples */
4994 sc->sample_offsets_count = 0;
4995 for (uint32_t i = 0; i < sc->ctts_count; i++) {
4996 if (sc->ctts_data[i].count > INT_MAX - sc->sample_offsets_count)
4997 return AVERROR(ENOMEM);
4999 }
5002 if (!sc->sample_offsets)
5003 return AVERROR(ENOMEM);
5004 k = 0;
5005 for (uint32_t i = 0; i < sc->ctts_count; i++)
5006 for (int j = 0; j < sc->ctts_data[i].count; j++)
5007 sc->sample_offsets[k++] = sc->ctts_data[i].offset;
5008
5009 /* The following HEVC NAL type reveal the use of open GOP sync points
5010 * (TODO: BLA types may also be concerned) */
5011 cra_index = get_sgpd_sync_index(sc, HEVC_NAL_CRA_NUT); /* Clean Random Access */
5012 if (!cra_index)
5013 return 0;
5014
5015 /* Build a list of open-GOP key samples */
5016 sc->open_key_samples_count = 0;
5017 for (uint32_t i = 0; i < sc->sync_group_count; i++)
5018 if (sc->sync_group[i].index == cra_index) {
5019 if (sc->sync_group[i].count > INT_MAX - sc->open_key_samples_count)
5020 return AVERROR(ENOMEM);
5022 }
5025 if (!sc->open_key_samples)
5026 return AVERROR(ENOMEM);
5027 k = 0;
5028 for (uint32_t i = 0; i < sc->sync_group_count; i++) {
5029 const MOVSbgp *sg = &sc->sync_group[i];
5030 if (sg->index == cra_index)
5031 for (uint32_t j = 0; j < sg->count; j++)
5032 sc->open_key_samples[k++] = sample_id;
5033 if (sg->count > INT_MAX - sample_id)
5034 return AVERROR_PATCHWELCOME;
5035 sample_id += sg->count;
5036 }
5037
5038 /* Identify the minimal time step between samples */
5039 sc->min_sample_duration = UINT_MAX;
5040 for (uint32_t i = 0; i < sc->stts_count; i++)
5042
5043 return 0;
5044}
5045
5046#define MOV_MERGE_CTTS 1
5047#define MOV_MERGE_STTS 2
5048/*
5049 * Merge stts and ctts arrays into a new combined array.
5050 * stts_count and ctts_count may be left untouched as they will be
5051 * used to check for the presence of either of them.
5052 */
5054{
5055 MOVStreamContext *sc = st->priv_data;
5056 int ctts = sc->ctts_data && (flags & MOV_MERGE_CTTS);
5057 int stts = sc->stts_data && (flags & MOV_MERGE_STTS);
5058 int idx = 0;
5059
5060 if (!sc->ctts_data && !sc->stts_data)
5061 return 0;
5062 // Expand time to sample entries such that we have a 1-1 mapping with samples
5063 if (!sc->sample_count || sc->sample_count >= UINT_MAX / sizeof(*sc->tts_data))
5064 return -1;
5065
5066 if (ctts) {
5068 sc->sample_count * sizeof(*sc->tts_data));
5069 if (!sc->tts_data)
5070 return -1;
5071
5072 memset(sc->tts_data, 0, sc->tts_allocated_size);
5073
5074 for (int i = 0; i < sc->ctts_count &&
5075 idx < sc->sample_count; i++)
5076 for (int j = 0; j < sc->ctts_data[i].count &&
5077 idx < sc->sample_count; j++) {
5078 sc->tts_data[idx].offset = sc->ctts_data[i].offset;
5079 sc->tts_data[idx++].count = 1;
5080 }
5081
5082 sc->tts_count = idx;
5083 } else
5084 sc->ctts_count = 0;
5085 av_freep(&sc->ctts_data);
5086 sc->ctts_allocated_size = 0;
5087
5088 idx = 0;
5089 if (stts) {
5091 sc->sample_count * sizeof(*sc->tts_data));
5092 if (!tts_data)
5093 return -1;
5094
5095 if (!sc->tts_data)
5096 memset(tts_data, 0, sc->tts_allocated_size);
5097 sc->tts_data = tts_data;
5098
5099 for (int i = 0; i < sc->stts_count &&
5100 idx < sc->sample_count; i++)
5101 for (int j = 0; j < sc->stts_data[i].count &&
5102 idx < sc->sample_count; j++) {
5103 sc->tts_data[idx].duration = sc->stts_data[i].duration;
5104 sc->tts_data[idx++].count = 1;
5105 }
5106
5107 sc->tts_count = FFMAX(sc->tts_count, idx);
5108 } else
5109 sc->stts_count = 0;
5110 av_freep(&sc->stts_data);
5111 sc->stts_allocated_size = 0;
5112
5113 return 0;
5114}
5115
5117{
5118 MOVStreamContext *sc = st->priv_data;
5119 FFStream *const sti = ffstream(st);
5120 int64_t current_offset;
5121 int64_t current_dts = 0;
5122 unsigned int stts_index = 0;
5123 unsigned int stsc_index = 0;
5124 unsigned int stss_index = 0;
5125 unsigned int stps_index = 0;
5126 unsigned int i, j;
5127 uint64_t stream_size = 0;
5128
5130 if (ret < 0)
5131 return;
5132
5133 if (sc->elst_count) {
5134 int i, edit_start_index = 0, multiple_edits = 0;
5135 int64_t empty_duration = 0; // empty duration of the first edit list entry
5136 int64_t start_time = 0; // start time of the media
5137
5138 for (i = 0; i < sc->elst_count; i++) {
5139 const MOVElst *e = &sc->elst_data[i];
5140 if (i == 0 && e->time == -1) {
5141 /* if empty, the first entry is the start time of the stream
5142 * relative to the presentation itself */
5143 empty_duration = e->duration;
5144 edit_start_index = 1;
5145 } else if (i == edit_start_index && e->time >= 0) {
5146 start_time = e->time;
5147 } else {
5148 multiple_edits = 1;
5149 }
5150 }
5151
5152 if (multiple_edits && !mov->advanced_editlist) {
5154 av_log(mov->fc, AV_LOG_WARNING, "multiple edit list entries, "
5155 "not supported in fragmented MP4 files\n");
5156 else
5157 av_log(mov->fc, AV_LOG_WARNING, "multiple edit list entries, "
5158 "Use -advanced_editlist to correctly decode otherwise "
5159 "a/v desync might occur\n");
5160 }
5161
5162 /* adjust first dts according to edit list */
5163 if ((empty_duration || start_time) && mov->time_scale > 0) {
5164 if (empty_duration)
5165 empty_duration = av_rescale(empty_duration, sc->time_scale, mov->time_scale);
5166
5167 if (av_sat_sub64(start_time, empty_duration) != start_time - (uint64_t)empty_duration)
5168 av_log(mov->fc, AV_LOG_WARNING, "start_time - empty_duration is not representable\n");
5169
5170 sc->time_offset = start_time - (uint64_t)empty_duration;
5172 if (!mov->advanced_editlist)
5173 current_dts = -av_clip64(sc->time_offset, -INT64_MAX, INT64_MAX);
5174 }
5175
5176 if (!multiple_edits && !mov->advanced_editlist &&
5179 (AVRational){1, st->codecpar->sample_rate});
5180 }
5181
5182 /* only use old uncompressed audio chunk demuxing when stts specifies it */
5183 if (!(st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
5184 sc->stts_count == 1 && sc->stts_data && sc->stts_data[0].duration == 1)) {
5185 unsigned int current_sample = 0;
5186 unsigned int stts_sample = 0;
5187 unsigned int sample_size;
5188 unsigned int distance = 0;
5189 unsigned int rap_group_index = 0;
5190 unsigned int rap_group_sample = 0;
5191 int rap_group_present = sc->rap_group_count && sc->rap_group;
5192 int key_off = (sc->keyframe_count && sc->keyframes[0] > 0) || (sc->stps_count && sc->stps_data[0] > 0);
5193
5194 av_assert0(sc->dts_shift >= 0);
5195 if (current_dts < INT64_MIN + sc->dts_shift)
5196 return;
5197 current_dts -= sc->dts_shift;
5198 if (!sc->sample_count || sti->nb_index_entries || sc->tts_count)
5199 return;
5200 if (sc->sample_count >= UINT_MAX / sizeof(*sti->index_entries) - sti->nb_index_entries)
5201 return;
5203 sti->nb_index_entries + sc->sample_count,
5204 sizeof(*sti->index_entries)) < 0) {
5205 sti->nb_index_entries = 0;
5206 return;
5207 }
5208 sti->index_entries_allocated_size = (sti->nb_index_entries + sc->sample_count) * sizeof(*sti->index_entries);
5209
5211 if (ret < 0)
5212 return;
5213
5214 for (i = 0; i < sc->chunk_count; i++) {
5215 int64_t next_offset = i+1 < sc->chunk_count ? sc->chunk_offsets[i+1] : INT64_MAX;
5216 current_offset = sc->chunk_offsets[i];
5217 while (mov_stsc_index_valid(stsc_index, sc->stsc_count) &&
5218 i + 1 == sc->stsc_data[stsc_index + 1].first)
5219 stsc_index++;
5220
5221 if (next_offset > current_offset && sc->sample_size>0 && sc->sample_size < sc->stsz_sample_size &&
5222 sc->stsc_data[stsc_index].count * (int64_t)sc->stsz_sample_size > next_offset - current_offset) {
5223 av_log(mov->fc, AV_LOG_WARNING, "STSZ sample size %d invalid (too large), ignoring\n", sc->stsz_sample_size);
5224 sc->stsz_sample_size = sc->sample_size;
5225 }
5226 if (sc->stsz_sample_size>0 && sc->stsz_sample_size < sc->sample_size) {
5227 av_log(mov->fc, AV_LOG_WARNING, "STSZ sample size %d invalid (too small), ignoring\n", sc->stsz_sample_size);
5228 sc->stsz_sample_size = sc->sample_size;
5229 }
5230
5231 for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
5232 int keyframe = 0;
5233 if (current_sample >= sc->sample_count) {
5234 av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
5235 return;
5236 }
5237
5238 if (!sc->keyframe_absent && (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index])) {
5239 keyframe = 1;
5240 if (stss_index + 1 < sc->keyframe_count)
5241 stss_index++;
5242 } else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) {
5243 keyframe = 1;
5244 if (stps_index + 1 < sc->stps_count)
5245 stps_index++;
5246 }
5247 if (rap_group_present && rap_group_index < sc->rap_group_count) {
5248 if (sc->rap_group[rap_group_index].index > 0)
5249 keyframe = 1;
5250 if (++rap_group_sample == sc->rap_group[rap_group_index].count) {
5251 rap_group_sample = 0;
5252 rap_group_index++;
5253 }
5254 }
5255 if (sc->keyframe_absent
5256 && !sc->stps_count
5257 && !rap_group_present
5258 && (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO || (i==0 && j==0)))
5259 keyframe = 1;
5260 if (keyframe)
5261 distance = 0;
5262 sample_size = sc->stsz_sample_size > 0 ? sc->stsz_sample_size : sc->sample_sizes[current_sample];
5263 if (current_offset > INT64_MAX - sample_size) {
5264 av_log(mov->fc, AV_LOG_ERROR, "Current offset %"PRId64" or sample size %u is too large\n",
5265 current_offset,
5266 sample_size);
5267 return;
5268 }
5269
5270 if (sc->pseudo_stream_id == -1 ||
5271 sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
5272 AVIndexEntry *e;
5273 if (sample_size > 0x3FFFFFFF) {
5274 av_log(mov->fc, AV_LOG_ERROR, "Sample size %u is too large\n", sample_size);
5275 return;
5276 }
5277 e = &sti->index_entries[sti->nb_index_entries++];
5278 e->pos = current_offset;
5279 e->timestamp = current_dts;
5280 e->size = sample_size;
5282 e->flags = keyframe ? AVINDEX_KEYFRAME : 0;
5283 av_log(mov->fc, AV_LOG_TRACE, "AVIndex stream %d, sample %u, offset %"PRIx64", dts %"PRId64", "
5284 "size %u, distance %u, keyframe %d\n", st->index, current_sample,
5285 current_offset, current_dts, sample_size, distance, keyframe);
5286 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && sti->nb_index_entries < 100)
5287 ff_rfps_add_frame(mov->fc, st, current_dts);
5288 }
5289
5290 current_offset += sample_size;
5291 stream_size += sample_size;
5292
5293 if (current_dts > INT64_MAX - sc->tts_data[stts_index].duration)
5294 return;
5295 current_dts += sc->tts_data[stts_index].duration;
5296
5297 distance++;
5298 stts_sample++;
5299 current_sample++;
5300 if (stts_index + 1 < sc->tts_count && stts_sample == sc->tts_data[stts_index].count) {
5301 stts_sample = 0;
5302 stts_index++;
5303 }
5304 }
5305 }
5306 if (st->duration > 0)
5307 st->codecpar->bit_rate = stream_size*8*sc->time_scale/st->duration;
5308 } else {
5309 unsigned chunk_samples, total = 0;
5310
5311 if (!sc->chunk_count || sc->tts_count)
5312 return;
5313
5314 // compute total chunk count
5315 for (i = 0; i < sc->stsc_count; i++) {
5316 unsigned count, chunk_count;
5317
5318 chunk_samples = sc->stsc_data[i].count;
5319 if (i != sc->stsc_count - 1 &&
5320 sc->samples_per_frame && chunk_samples % sc->samples_per_frame) {
5321 av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n");
5322 return;
5323 }
5324
5325 if (sc->samples_per_frame >= 160) { // gsm
5326 count = chunk_samples / sc->samples_per_frame;
5327 } else if (sc->samples_per_frame > 1) {
5328 unsigned samples = (1024/sc->samples_per_frame)*sc->samples_per_frame;
5329 count = (chunk_samples+samples-1) / samples;
5330 } else {
5331 count = (chunk_samples+1023) / 1024;
5332 }
5333
5335 chunk_count = sc->stsc_data[i+1].first - sc->stsc_data[i].first;
5336 else
5337 chunk_count = sc->chunk_count - (sc->stsc_data[i].first - 1);
5338 total += chunk_count * count;
5339 }
5340
5341 av_log(mov->fc, AV_LOG_TRACE, "chunk count %u\n", total);
5342 if (total >= UINT_MAX / sizeof(*sti->index_entries) - sti->nb_index_entries)
5343 return;
5345 sti->nb_index_entries + total,
5346 sizeof(*sti->index_entries)) < 0) {
5347 sti->nb_index_entries = 0;
5348 return;
5349 }
5350 sti->index_entries_allocated_size = (sti->nb_index_entries + total) * sizeof(*sti->index_entries);
5351
5352 // populate index
5353 for (i = 0; i < sc->chunk_count; i++) {
5354 current_offset = sc->chunk_offsets[i];
5355 if (mov_stsc_index_valid(stsc_index, sc->stsc_count) &&
5356 i + 1 == sc->stsc_data[stsc_index + 1].first)
5357 stsc_index++;
5358 chunk_samples = sc->stsc_data[stsc_index].count;
5359
5360 while (chunk_samples > 0) {
5361 AVIndexEntry *e;
5362 unsigned size, samples;
5363
5364 if (sc->samples_per_frame > 1 && !sc->bytes_per_frame) {
5366 "Zero bytes per frame, but %d samples per frame",
5367 sc->samples_per_frame);
5368 return;
5369 }
5370
5371 if (sc->samples_per_frame >= 160) { // gsm
5372 samples = sc->samples_per_frame;
5373 size = sc->bytes_per_frame;
5374 } else {
5375 if (sc->samples_per_frame > 1) {
5376 samples = FFMIN((1024 / sc->samples_per_frame)*
5377 sc->samples_per_frame, chunk_samples);
5378 size = (samples / sc->samples_per_frame) * sc->bytes_per_frame;
5379 } else {
5380 samples = FFMIN(1024, chunk_samples);
5381 size = samples * sc->sample_size;
5382 }
5383 }
5384
5385 if (sti->nb_index_entries >= total) {
5386 av_log(mov->fc, AV_LOG_ERROR, "wrong chunk count %u\n", total);
5387 return;
5388 }
5389 if (size > 0x3FFFFFFF) {
5390 av_log(mov->fc, AV_LOG_ERROR, "Sample size %u is too large\n", size);
5391 return;
5392 }
5393 e = &sti->index_entries[sti->nb_index_entries++];
5394 e->pos = current_offset;
5395 e->timestamp = current_dts;
5396 e->size = size;
5397 e->min_distance = 0;
5399 av_log(mov->fc, AV_LOG_TRACE, "AVIndex stream %d, chunk %u, offset %"PRIx64", dts %"PRId64", "
5400 "size %u, duration %u\n", st->index, i, current_offset, current_dts,
5401 size, samples);
5402
5403 current_offset += size;
5404 if (current_dts > INT64_MAX - samples)
5405 return;
5406 current_dts += samples;
5407 chunk_samples -= samples;
5408 }
5409 }
5410
5412 if (ret < 0)
5413 return;
5414 }
5415
5416 if (!mov->ignore_editlist && mov->advanced_editlist) {
5417 // Fix index according to edit lists.
5418 mov_fix_index(mov, st);
5419 }
5420
5421 // Update start time of the stream.
5424 if (sc->tts_data) {
5426 }
5427 }
5428
5429 mov_estimate_video_delay(mov, st);
5430}
5431
5436
5437static int mov_compare_presentation_samples(const void *a, const void *b)
5438{
5439 const MOVPresentationSample *sa = a;
5440 const MOVPresentationSample *sb = b;
5441
5442 if (sa->pts != sb->pts)
5443 return (sa->pts > sb->pts) - (sa->pts < sb->pts);
5444 return (sa->index > sb->index) - (sa->index < sb->index);
5445}
5446
5447/*
5448 * Set sample durations from adjacent presentation timestamps.
5449 */
5451{
5452 MOVStreamContext *sc = st->priv_data;
5453 FFStream *const sti = ffstream(st);
5454 MOVPresentationSample *samples = NULL;
5455 MOVTimeToSample *tts_data = NULL;
5456 unsigned int tts_index = 0, tts_sample = 0;
5457 int count = sti->nb_index_entries;
5458
5459 /* A single STTS entry describes a fixed sample delta. */
5461 !sc->ctts_count || sc->stts_count < 2 ||
5462 !sc->tts_data || count < 2 ||
5463 count >= UINT_MAX / sizeof(*tts_data))
5464 return;
5465
5466 samples = av_malloc_array(count, sizeof(*samples));
5467 tts_data = av_malloc_array(count, sizeof(*tts_data));
5468 if (!samples || !tts_data)
5469 goto fail;
5470
5471 for (int i = 0; i < count; i++) {
5472 int64_t dts, offset;
5473
5474 if (tts_index >= sc->tts_count || !sc->tts_data[tts_index].count)
5475 goto fail;
5476
5477 tts_data[i] = sc->tts_data[tts_index];
5478 tts_data[i].count = 1;
5479
5480 dts = sti->index_entries[i].timestamp;
5481 offset = (int64_t)sc->dts_shift + tts_data[i].offset;
5482 if (dts == AV_NOPTS_VALUE ||
5483 (offset > 0 && dts > INT64_MAX - offset) ||
5484 (offset < 0 && dts < INT64_MIN - offset))
5485 goto fail;
5486
5487 samples[i].index = i;
5488 samples[i].pts = dts + offset;
5489
5490 if (++tts_sample == sc->tts_data[tts_index].count) {
5491 tts_index++;
5492 tts_sample = 0;
5493 }
5494 }
5495 if (tts_index != sc->tts_count || tts_sample)
5496 goto fail;
5497
5498 qsort(samples, count, sizeof(*samples), mov_compare_presentation_samples);
5499
5500 for (int i = 0; i + 1 < count; i++) {
5501 uint64_t duration;
5502
5503 if (samples[i].pts >= samples[i + 1].pts)
5504 goto fail;
5505
5506 /*
5507 * In VFR streams with reordered frames, STTS deltas follow decode
5508 * order while AVPacket.duration follows presentation order. CTTS
5509 * may produce presentation intervals that cannot be obtained by
5510 * merely permuting the STTS deltas, so derive each known duration
5511 * from adjacent PTS.
5512 */
5513 duration = (uint64_t)samples[i + 1].pts - samples[i].pts;
5514 if (!duration || duration > UINT_MAX)
5515 goto fail;
5516
5517 tts_data[samples[i].index].duration = (unsigned int)duration;
5518 }
5519
5520 av_log(mov->fc, AV_LOG_DEBUG,
5521 "Updated sample durations in presentation order for stream %d\n",
5522 st->index);
5523
5524 av_freep(&sc->tts_data);
5525 sc->tts_data = tts_data;
5526 sc->tts_count = count;
5527 sc->tts_allocated_size = count * sizeof(*tts_data);
5528 tts_data = NULL;
5529
5530fail:
5531 av_free(samples);
5532 av_free(tts_data);
5533}
5534
5535static int test_same_origin(const char *src, const char *ref) {
5536 char src_proto[64];
5537 char ref_proto[64];
5538 char src_auth[256];
5539 char ref_auth[256];
5540 char src_host[256];
5541 char ref_host[256];
5542 int src_port=-1;
5543 int ref_port=-1;
5544
5545 av_url_split(src_proto, sizeof(src_proto), src_auth, sizeof(src_auth), src_host, sizeof(src_host), &src_port, NULL, 0, src);
5546 av_url_split(ref_proto, sizeof(ref_proto), ref_auth, sizeof(ref_auth), ref_host, sizeof(ref_host), &ref_port, NULL, 0, ref);
5547
5548 if (strlen(src) == 0) {
5549 return -1;
5550 } else if (strlen(src_auth) + 1 >= sizeof(src_auth) ||
5551 strlen(ref_auth) + 1 >= sizeof(ref_auth) ||
5552 strlen(src_host) + 1 >= sizeof(src_host) ||
5553 strlen(ref_host) + 1 >= sizeof(ref_host)) {
5554 return 0;
5555 } else if (strcmp(src_proto, ref_proto) ||
5556 strcmp(src_auth, ref_auth) ||
5557 strcmp(src_host, ref_host) ||
5558 src_port != ref_port) {
5559 return 0;
5560 } else
5561 return 1;
5562}
5563
5564static int mov_open_dref(MOVContext *c, AVIOContext **pb, const char *src, MOVDref *ref)
5565{
5566 /* try relative path, we do not try the absolute because it can leak information about our
5567 system to an attacker */
5568 if (ref->nlvl_to > 0 && ref->nlvl_from > 0) {
5569 char filename[1025];
5570 const char *src_path;
5571 int i, l;
5572
5573 /* find a source dir */
5574 src_path = strrchr(src, '/');
5575 if (src_path)
5576 src_path++;
5577 else
5578 src_path = src;
5579
5580 /* find a next level down to target */
5581 for (i = 0, l = strlen(ref->path) - 1; l >= 0; l--)
5582 if (ref->path[l] == '/') {
5583 if (i == ref->nlvl_to - 1)
5584 break;
5585 else
5586 i++;
5587 }
5588
5589 /* compose filename if next level down to target was found */
5590 if (i == ref->nlvl_to - 1 && src_path - src < sizeof(filename)) {
5591 memcpy(filename, src, src_path - src);
5592 filename[src_path - src] = 0;
5593
5594 for (i = 1; i < ref->nlvl_from; i++)
5595 av_strlcat(filename, "../", sizeof(filename));
5596
5597 av_strlcat(filename, ref->path + l + 1, sizeof(filename));
5598 if (!c->use_absolute_path) {
5599 int same_origin = test_same_origin(src, filename);
5600
5601 if (!same_origin) {
5602 av_log(c->fc, AV_LOG_ERROR,
5603 "Reference with mismatching origin, %s not tried for security reasons, "
5604 "set demuxer option use_absolute_path to allow it anyway\n",
5605 ref->path);
5606 return AVERROR(ENOENT);
5607 }
5608
5609 if (strstr(ref->path + l + 1, "..") ||
5610 strstr(ref->path + l + 1, ":") ||
5611 (ref->nlvl_from > 1 && same_origin < 0) ||
5612 (filename[0] == '/' && src_path == src))
5613 return AVERROR(ENOENT);
5614 }
5615
5616 if (strlen(filename) + 1 == sizeof(filename))
5617 return AVERROR(ENOENT);
5618 if (!c->fc->io_open(c->fc, pb, filename, AVIO_FLAG_READ, NULL))
5619 return 0;
5620 }
5621 } else if (c->use_absolute_path) {
5622 av_log(c->fc, AV_LOG_WARNING, "Using absolute path on user request, "
5623 "this is a possible security issue\n");
5624 if (!c->fc->io_open(c->fc, pb, ref->path, AVIO_FLAG_READ, NULL))
5625 return 0;
5626 } else {
5627 av_log(c->fc, AV_LOG_ERROR,
5628 "Absolute path %s not tried for security reasons, "
5629 "set demuxer option use_absolute_path to allow absolute paths\n",
5630 ref->path);
5631 }
5632
5633 return AVERROR(ENOENT);
5634}
5635
5637{
5638 if (sc->time_scale <= 0) {
5639 av_log(c->fc, AV_LOG_WARNING, "stream %d, timescale not set\n", sc->ffindex);
5640 sc->time_scale = c->time_scale;
5641 if (sc->time_scale <= 0)
5642 sc->time_scale = 1;
5643 }
5644}
5645
5646#if CONFIG_IAMFDEC
5647static int mov_update_iamf_streams(MOVContext *c, const AVStream *st)
5648{
5649 const MOVStreamContext *sc = st->priv_data;
5650 const IAMFContext *iamf = &sc->iamf->iamf;
5651
5652 for (int i = 0; i < iamf->nb_audio_elements; i++) {
5653 const AVStreamGroup *stg = NULL;
5654
5655 for (int j = 0; j < c->fc->nb_stream_groups; j++)
5656 if (c->fc->stream_groups[j]->type == AV_STREAM_GROUP_PARAMS_IAMF_AUDIO_ELEMENT &&
5657 c->fc->stream_groups[j]->id == iamf->audio_elements[i]->audio_element_id)
5658 stg = c->fc->stream_groups[j];
5659 av_assert0(stg);
5660
5661 for (int j = 0; j < stg->nb_entries; j++) {
5662 const FFStream *sti = cffstream(st);
5663 AVStream *out = stg->entries[j]->stream;
5664 FFStream *out_sti = ffstream(stg->entries[j]->stream);
5665
5666 out->codecpar->bit_rate = 0;
5667
5668 if (out == st)
5669 continue;
5670
5671 out->time_base = st->time_base;
5672 out->start_time = st->start_time;
5673 out->duration = st->duration;
5674 out->nb_frames = st->nb_frames;
5675 out->discard = st->discard;
5676
5677 av_assert0(!out_sti->index_entries);
5679 if (!out_sti->index_entries)
5680 return AVERROR(ENOMEM);
5681
5683 out_sti->nb_index_entries = sti->nb_index_entries;
5684 out_sti->skip_samples = sti->skip_samples;
5686 memcpy(out_sti->index_entries, sti->index_entries, sti->index_entries_allocated_size);
5687 }
5688 }
5689
5690 return 0;
5691}
5692#endif
5693
5694static int sanity_checks(void *log_obj, MOVStreamContext *sc, int index)
5695{
5696 if ((sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
5697 (!sc->sample_size && !sc->sample_count))) ||
5698 (sc->sample_count && (!sc->chunk_count ||
5699 (!sc->sample_size && !sc->sample_sizes)))) {
5700 av_log(log_obj, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
5701 index);
5702 return 1;
5703 }
5704
5705 if (sc->stsc_count && sc->stsc_data[ sc->stsc_count - 1 ].first > sc->chunk_count) {
5706 av_log(log_obj, AV_LOG_ERROR, "stream %d, contradictionary STSC and STCO\n",
5707 index);
5708 return 2;
5709 }
5710 return 0;
5711}
5712
5714{
5715 AVStream *st;
5716 MOVStreamContext *sc;
5717 int ret;
5718
5719 st = avformat_new_stream(c->fc, NULL);
5720 if (!st) return AVERROR(ENOMEM);
5721 st->id = -1;
5722 sc = av_mallocz(sizeof(MOVStreamContext));
5723 if (!sc) return AVERROR(ENOMEM);
5724
5725 st->priv_data = sc;
5727 sc->ffindex = st->index;
5728 c->trak_index = st->index;
5729 sc->refcount = 1;
5730
5731 if ((ret = mov_read_default(c, pb, atom)) < 0)
5732 return ret;
5733
5734 c->trak_index = -1;
5735
5736 // Here stsc refers to a chunk not described in stco. This is technically invalid,
5737 // but we can overlook it (clearing stsc) whenever stts_count == 0 (indicating no samples).
5738 if (!sc->chunk_count && !sc->stts_count && sc->stsc_count) {
5739 sc->stsc_count = 0;
5740 av_freep(&sc->stsc_data);
5741 }
5742
5743 ret = sanity_checks(c->fc, sc, st->index);
5744 if (ret)
5745 return ret > 1 ? AVERROR_INVALIDDATA : 0;
5746
5747 fix_timescale(c, sc);
5748
5749 avpriv_set_pts_info(st, 64, 1, sc->time_scale);
5750
5751 /*
5752 * Advanced edit list support does not work with fragemented MP4s, which
5753 * have stsc, stsz, stco, and stts with zero entries in the moov atom.
5754 * In these files, trun atoms may be streamed in.
5755 */
5756 if (!sc->stts_count && c->advanced_editlist) {
5757
5758 av_log(c->fc, AV_LOG_VERBOSE, "advanced_editlist does not work with fragmented "
5759 "MP4. disabling.\n");
5760 c->advanced_editlist = 0;
5761 c->advanced_editlist_autodisabled = 1;
5762 }
5763
5764 mov_build_index(c, st);
5765 /*
5766 * Fragment samples are appended later by mov_read_trun() and are not
5767 * covered by this non-fragmented track update.
5768 */
5770
5771#if CONFIG_IAMFDEC
5772 if (sc->iamf) {
5773 ret = mov_update_iamf_streams(c, st);
5774 if (ret < 0)
5775 return ret;
5776 }
5777#endif
5778
5779 if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
5780 MOVDref *dref = &sc->drefs[sc->dref_id - 1];
5781 if (c->enable_drefs) {
5782 if (mov_open_dref(c, &sc->pb, c->fc->url, dref) < 0)
5783 av_log(c->fc, AV_LOG_ERROR,
5784 "stream %d, error opening alias: path='%s', dir='%s', "
5785 "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d\n",
5786 st->index, dref->path, dref->dir, dref->filename,
5787 dref->volume, dref->nlvl_from, dref->nlvl_to);
5788 } else {
5789 av_log(c->fc, AV_LOG_WARNING,
5790 "Skipped opening external track: "
5791 "stream %d, alias: path='%s', dir='%s', "
5792 "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d."
5793 "Set enable_drefs to allow this.\n",
5794 st->index, dref->path, dref->dir, dref->filename,
5795 dref->volume, dref->nlvl_from, dref->nlvl_to);
5796 }
5797 } else {
5798 sc->pb = c->fc->pb;
5799 sc->pb_is_copied = 1;
5800 }
5801
5803 int stts_constant = sc->stts_count && sc->tts_count;
5804 if (sc->h_spacing && sc->v_spacing)
5806 sc->h_spacing, sc->v_spacing, INT_MAX);
5807 if (!st->sample_aspect_ratio.num && st->codecpar->width && st->codecpar->height &&
5808 sc->height && sc->width &&
5809 (st->codecpar->width != sc->width || st->codecpar->height != sc->height)) {
5811 (int64_t)st->codecpar->height * sc->width,
5812 (int64_t)st->codecpar->width * sc->height, INT_MAX);
5813 }
5814
5815#if FF_API_R_FRAME_RATE
5816 for (unsigned int i = 1; sc->stts_count && i + 1 < sc->tts_count; i++) {
5817 if (sc->tts_data[i].duration == sc->tts_data[0].duration)
5818 continue;
5819 stts_constant = 0;
5820 }
5821 if (stts_constant)
5823 sc->time_scale, sc->tts_data[0].duration, INT_MAX);
5824#endif
5825 }
5826
5827#if CONFIG_H261_DECODER || CONFIG_H263_DECODER || CONFIG_MPEG4_DECODER
5828 switch (st->codecpar->codec_id) {
5829#if CONFIG_H261_DECODER
5830 case AV_CODEC_ID_H261:
5831#endif
5832#if CONFIG_H263_DECODER
5833 case AV_CODEC_ID_H263:
5834#endif
5835#if CONFIG_MPEG4_DECODER
5836 case AV_CODEC_ID_MPEG4:
5837#endif
5838 st->codecpar->width = 0; /* let decoder init width/height */
5839 st->codecpar->height= 0;
5840 break;
5841 }
5842#endif
5843
5844 // If the duration of the mp3 packets is not constant, then they could need a parser
5846 && sc->time_scale == st->codecpar->sample_rate) {
5847 int stts_constant = 1;
5848 for (int i = 1; sc->stts_count && i < sc->tts_count; i++) {
5849 if (sc->tts_data[i].duration == sc->tts_data[0].duration)
5850 continue;
5851 stts_constant = 0;
5852 }
5853 if (!stts_constant)
5855 }
5856 /* Do not need those anymore. */
5857 av_freep(&sc->chunk_offsets);
5858 av_freep(&sc->sample_sizes);
5859 av_freep(&sc->keyframes);
5860 av_freep(&sc->stps_data);
5861 av_freep(&sc->elst_data);
5862 av_freep(&sc->rap_group);
5863 av_freep(&sc->sync_group);
5864 av_freep(&sc->sgpd_sync);
5865
5866 return 0;
5867}
5868
5870{
5871 int ret;
5872 c->itunes_metadata = 1;
5873 ret = mov_read_default(c, pb, atom);
5874 c->itunes_metadata = 0;
5875 return ret;
5876}
5877
5879{
5880 uint32_t count;
5881 uint32_t i;
5882
5883 if (atom.size < 8)
5884 return 0;
5885
5886 avio_skip(pb, 4);
5887 count = avio_rb32(pb);
5888 atom.size -= 8;
5889 if (count > atom.size / 8 || count >= UINT_MAX / sizeof(*c->meta_keys)) {
5890 av_log(c->fc, AV_LOG_ERROR,
5891 "The 'keys' atom with the invalid key count: %"PRIu32"\n", count);
5892 return AVERROR_INVALIDDATA;
5893 }
5894
5895 c->meta_keys = av_malloc_array(count + 1, sizeof(*c->meta_keys));
5896 if (!c->meta_keys)
5897 return AVERROR(ENOMEM);
5898
5899 c->meta_keys[0] = NULL;
5900 c->meta_keys_count = 1;
5901 for (i = 1; i <= count; ++i) {
5902 uint32_t key_size = avio_rb32(pb);
5903 uint32_t type = avio_rl32(pb);
5904 c->meta_keys[i] = NULL;
5905 c->meta_keys_count = i + 1;
5906 if (key_size < 8 || key_size > atom.size) {
5907 av_log(c->fc, AV_LOG_ERROR,
5908 "The key# %"PRIu32" in meta has invalid size:"
5909 "%"PRIu32"\n", i, key_size);
5910 return AVERROR_INVALIDDATA;
5911 }
5912 atom.size -= key_size;
5913 key_size -= 8;
5914 if (type != MKTAG('m','d','t','a')) {
5915 avio_skip(pb, key_size);
5916 continue;
5917 }
5918 c->meta_keys[i] = av_malloc(key_size + 1);
5919 if (!c->meta_keys[i])
5920 return AVERROR(ENOMEM);
5921 int ret = ffio_read_size(pb, c->meta_keys[i], key_size);
5922 if (ret < 0)
5923 return ret;
5924 c->meta_keys[i][key_size] = 0;
5925 }
5926
5927 return 0;
5928}
5929
5931{
5932 int64_t end = av_sat_add64(avio_tell(pb), atom.size);
5933 uint8_t *key = NULL, *val = NULL, *mean = NULL;
5934 int i;
5935 int ret = 0;
5936 AVStream *st;
5937
5938 if (c->fc->nb_streams < 1)
5939 return 0;
5940 st = c->fc->streams[c->fc->nb_streams-1];
5941
5942 for (i = 0; i < 3; i++) {
5943 uint8_t **p;
5944 uint32_t len, tag;
5945
5946 if (end - avio_tell(pb) <= 12)
5947 break;
5948
5949 len = avio_rb32(pb);
5950 tag = avio_rl32(pb);
5951 avio_skip(pb, 4); // flags
5952
5953 if (len < 12 || len - 12 > end - avio_tell(pb))
5954 break;
5955 len -= 12;
5956
5957 if (tag == MKTAG('m', 'e', 'a', 'n'))
5958 p = &mean;
5959 else if (tag == MKTAG('n', 'a', 'm', 'e'))
5960 p = &key;
5961 else if (tag == MKTAG('d', 'a', 't', 'a') && len > 4) {
5962 avio_skip(pb, 4);
5963 len -= 4;
5964 p = &val;
5965 } else
5966 break;
5967
5968 if (*p)
5969 break;
5970
5971 *p = av_malloc(len + 1);
5972 if (!*p) {
5973 ret = AVERROR(ENOMEM);
5974 break;
5975 }
5976 ret = ffio_read_size(pb, *p, len);
5977 if (ret < 0) {
5978 av_freep(p);
5979 break;
5980 }
5981 (*p)[len] = 0;
5982 }
5983
5984 if (mean && key && val) {
5985 if (strcmp(key, "iTunSMPB") == 0) {
5986 int64_t priming, remainder, samples;
5987 if (ff_itunes_parse_smpb(val, &priming, &remainder, &samples) >= 0) {
5988 if(priming>0 && priming<16384)
5989 st->codecpar->initial_padding = priming = av_rescale_q(priming, st->time_base,
5990 (AVRational){ 1, st->codecpar->sample_rate });
5991 if (remainder > 0) {
5993 (AVRational){ 1, st->codecpar->sample_rate });
5994 remainder = av_rescale_q(remainder, st->time_base,
5995 (AVRational){ 1, st->codecpar->sample_rate });
5996 samples = av_rescale_q(samples, st->time_base,
5997 (AVRational){ 1, st->codecpar->sample_rate });
5998 if (duration > remainder && duration > samples) {
5999 ffstream(st)->first_discard_sample = duration - remainder;
6001 }
6002 }
6003 av_log(c->fc, AV_LOG_DEBUG, "Parsed iTunSMPB: priming %"PRId64", "
6004 "remainder %"PRId64" samples %"PRId64"\n",
6005 priming, remainder, samples);
6006 }
6007 }
6008 if (strcmp(mean, "com.apple.iTunes") == 0 &&
6009 strcmp(key, "DISCSUBTITLE") == 0) {
6010 av_dict_set(&c->fc->metadata, "disc_subtitle", val,
6012 val = NULL;
6013 }
6014 if (strcmp(key, "cdec") != 0) {
6015 av_dict_set(&c->fc->metadata, key, val,
6017 key = val = NULL;
6018 }
6019 } else {
6020 av_log(c->fc, AV_LOG_VERBOSE,
6021 "Unhandled or malformed custom metadata of size %"PRId64"\n", atom.size);
6022 }
6023
6024 avio_seek(pb, end, SEEK_SET);
6025 av_freep(&key);
6026 av_freep(&val);
6027 av_freep(&mean);
6028 return ret;
6029}
6030
6032{
6033 MOVStreamContext *sc;
6034 AVStream *st;
6035
6036 st = avformat_new_stream(c->fc, NULL);
6037 if (!st)
6038 return AVERROR(ENOMEM);
6039 sc = av_mallocz(sizeof(MOVStreamContext));
6040 if (!sc)
6041 goto fail;
6042
6043 item->st = st;
6044 st->id = item->item_id;
6045 st->priv_data = sc;
6047 st->codecpar->codec_id = mov_codec_id(st, item->type);
6048 sc->id = st->id;
6049 sc->ffindex = st->index;
6050 st->avg_frame_rate.num = st->avg_frame_rate.den = 1;
6051 st->time_base.num = st->time_base.den = 1;
6052 st->nb_frames = 1;
6053 sc->time_scale = 1;
6054 sc->pb = c->fc->pb;
6055 sc->pb_is_copied = 1;
6056 sc->refcount = 1;
6057
6058 if (item->name)
6059 av_dict_set(&st->metadata, "title", item->name, 0);
6060
6061 // Populate the necessary fields used by mov_build_index.
6062 sc->stsc_data = av_malloc_array(1, sizeof(*sc->stsc_data));
6063 if (!sc->stsc_data)
6064 goto fail;
6065 sc->stsc_count = 1;
6066 sc->stsc_data[0].first = 1;
6067 sc->stsc_data[0].count = 1;
6068 sc->stsc_data[0].id = 1;
6069 sc->chunk_offsets = av_malloc_array(1, sizeof(*sc->chunk_offsets));
6070 if (!sc->chunk_offsets)
6071 goto fail;
6072 sc->chunk_count = 1;
6073 sc->stts_data = av_malloc_array(1, sizeof(*sc->stts_data));
6074 if (!sc->stts_data)
6075 goto fail;
6076 sc->stts_count = 1;
6077 sc->stts_data[0].count = 1;
6078 // Not used for still images. But needed by mov_build_index.
6079 sc->stts_data[0].duration = 0;
6080
6081 return 0;
6082fail:
6083 mov_free_stream_context(c->fc, st);
6084 ff_remove_stream(c->fc, st);
6085 item->st = NULL;
6086
6087 return AVERROR(ENOMEM);
6088}
6089
6091{
6092 while (atom.size > 8) {
6093 uint32_t tag;
6094 if (avio_feof(pb))
6095 return AVERROR_EOF;
6096 tag = avio_rl32(pb);
6097 atom.size -= 4;
6098 if (tag == MKTAG('h','d','l','r')) {
6099 avio_seek(pb, -8, SEEK_CUR);
6100 atom.size += 8;
6101 return mov_read_default(c, pb, atom);
6102 }
6103 }
6104 return 0;
6105}
6106
6107// return 1 when matrix is identity, 0 otherwise
6108#define IS_MATRIX_IDENT(matrix) \
6109 ( (matrix)[0][0] == (1 << 16) && \
6110 (matrix)[1][1] == (1 << 16) && \
6111 (matrix)[2][2] == (1 << 30) && \
6112 !(matrix)[0][1] && !(matrix)[0][2] && \
6113 !(matrix)[1][0] && !(matrix)[1][2] && \
6114 !(matrix)[2][0] && !(matrix)[2][1])
6115
6117{
6118 int i, j, e;
6119 int width;
6120 int height;
6121 int display_matrix[3][3];
6122 int res_display_matrix[3][3] = { { 0 } };
6123 AVStream *st;
6124 MOVStreamContext *sc;
6125 int version;
6126 int flags;
6127
6128 if (c->fc->nb_streams < 1)
6129 return 0;
6130 st = c->fc->streams[c->fc->nb_streams-1];
6131 sc = st->priv_data;
6132
6133 // Each stream (trak) should have exactly 1 tkhd. This catches bad files and
6134 // avoids corrupting AVStreams mapped to an earlier tkhd.
6135 if (st->id != -1)
6136 return AVERROR_INVALIDDATA;
6137
6138 version = avio_r8(pb);
6139 flags = avio_rb24(pb);
6141
6142 if (version == 1) {
6143 avio_rb64(pb);
6144 avio_rb64(pb);
6145 } else {
6146 avio_rb32(pb); /* creation time */
6147 avio_rb32(pb); /* modification time */
6148 }
6149 st->id = (int)avio_rb32(pb); /* track id (NOT 0 !)*/
6150 sc->id = st->id;
6151 avio_rb32(pb); /* reserved */
6152
6153 /* highlevel (considering edits) duration in movie timebase */
6154 (version == 1) ? avio_rb64(pb) : avio_rb32(pb);
6155 avio_rb32(pb); /* reserved */
6156 avio_rb32(pb); /* reserved */
6157
6158 avio_rb16(pb); /* layer */
6159 avio_rb16(pb); /* alternate group */
6160 avio_rb16(pb); /* volume */
6161 avio_rb16(pb); /* reserved */
6162
6163 //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
6164 // they're kept in fixed point format through all calculations
6165 // save u,v,z to store the whole matrix in the AV_PKT_DATA_DISPLAYMATRIX
6166 // side data, but the scale factor is not needed to calculate aspect ratio
6167 for (i = 0; i < 3; i++) {
6168 display_matrix[i][0] = avio_rb32(pb); // 16.16 fixed point
6169 display_matrix[i][1] = avio_rb32(pb); // 16.16 fixed point
6170 display_matrix[i][2] = avio_rb32(pb); // 2.30 fixed point
6171 }
6172
6173 width = avio_rb32(pb); // 16.16 fixed point track width
6174 height = avio_rb32(pb); // 16.16 fixed point track height
6175 sc->width = width >> 16;
6176 sc->height = height >> 16;
6177
6178 // apply the moov display matrix (after the tkhd one)
6179 for (i = 0; i < 3; i++) {
6180 const int sh[3] = { 16, 16, 30 };
6181 for (j = 0; j < 3; j++) {
6182 for (e = 0; e < 3; e++) {
6183 res_display_matrix[i][j] +=
6184 ((int64_t) display_matrix[i][e] *
6185 c->movie_display_matrix[e][j]) >> sh[e];
6186 }
6187 }
6188 }
6189
6190 // save the matrix when it is not the default identity
6191 if (!IS_MATRIX_IDENT(res_display_matrix)) {
6193 sc->display_matrix = av_malloc(sizeof(int32_t) * 9);
6194 if (!sc->display_matrix)
6195 return AVERROR(ENOMEM);
6196
6197 for (i = 0; i < 3; i++)
6198 for (j = 0; j < 3; j++)
6199 sc->display_matrix[i * 3 + j] = res_display_matrix[i][j];
6200 }
6201
6202 // transform the display width/height according to the matrix
6203 // to keep the same scale, use [width height 1<<16]
6204 if (width && height && sc->display_matrix) {
6205 double disp_transform[2];
6206
6207 for (i = 0; i < 2; i++)
6208 disp_transform[i] = hypot(sc->display_matrix[0 + i],
6209 sc->display_matrix[3 + i]);
6210
6211 if (disp_transform[0] > 1 && disp_transform[1] > 1 &&
6212 disp_transform[0] < (1<<24) && disp_transform[1] < (1<<24) &&
6213 fabs((disp_transform[0] / disp_transform[1]) - 1.0) > 0.01)
6215 disp_transform[0] / disp_transform[1],
6216 INT_MAX);
6217 }
6218 return 0;
6219}
6220
6222{
6223 MOVFragment *frag = &c->fragment;
6224 MOVTrackExt *trex = NULL;
6225 int flags, track_id, i;
6226 MOVFragmentStreamInfo * frag_stream_info;
6227
6228 avio_r8(pb); /* version */
6229 flags = avio_rb24(pb);
6230
6231 track_id = avio_rb32(pb);
6232 if (!track_id)
6233 return AVERROR_INVALIDDATA;
6234 for (i = 0; i < c->trex_count; i++)
6235 if (c->trex_data[i].track_id == track_id) {
6236 trex = &c->trex_data[i];
6237 break;
6238 }
6239 if (!trex) {
6240 av_log(c->fc, AV_LOG_WARNING, "could not find corresponding trex (id %u)\n", track_id);
6241 return 0;
6242 }
6243 c->fragment.found_tfhd = 1;
6244 frag->track_id = track_id;
6245 set_frag_stream(&c->frag_index, track_id);
6246
6249 frag->moof_offset : frag->implicit_offset;
6250 frag->stsd_id = flags & MOV_TFHD_STSD_ID ? avio_rb32(pb) : trex->stsd_id;
6251
6253 avio_rb32(pb) : trex->duration;
6254 frag->size = flags & MOV_TFHD_DEFAULT_SIZE ?
6255 avio_rb32(pb) : trex->size;
6257 avio_rb32(pb) : trex->flags;
6258 av_log(c->fc, AV_LOG_TRACE, "frag flags 0x%x\n", frag->flags);
6259
6260 frag_stream_info = get_current_frag_stream_info(&c->frag_index);
6261 if (frag_stream_info) {
6262 frag_stream_info->next_trun_dts = AV_NOPTS_VALUE;
6263 frag_stream_info->stsd_id = frag->stsd_id;
6264 }
6265 return 0;
6266}
6267
6269{
6270 unsigned i, num;
6271 void *new_tracks;
6272
6273 num = atom.size / 4;
6274 if (!(new_tracks = av_malloc_array(num, sizeof(int))))
6275 return AVERROR(ENOMEM);
6276
6277 av_free(c->chapter_tracks);
6278 c->chapter_tracks = new_tracks;
6279 c->nb_chapter_tracks = num;
6280
6281 for (i = 0; i < num && !pb->eof_reached; i++)
6282 c->chapter_tracks[i] = avio_rb32(pb);
6283
6284 c->nb_chapter_tracks = i;
6285
6286 return 0;
6287}
6288
6290{
6291 MOVTrackExt *trex;
6292 int err;
6293
6294 if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
6295 return AVERROR_INVALIDDATA;
6296 if ((err = av_reallocp_array(&c->trex_data, c->trex_count + 1,
6297 sizeof(*c->trex_data))) < 0) {
6298 c->trex_count = 0;
6299 return err;
6300 }
6301
6302 c->fc->duration = AV_NOPTS_VALUE; // the duration from mvhd is not representing the whole file when fragments are used.
6303
6304 trex = &c->trex_data[c->trex_count++];
6305 avio_r8(pb); /* version */
6306 avio_rb24(pb); /* flags */
6307 trex->track_id = avio_rb32(pb);
6308 trex->stsd_id = avio_rb32(pb);
6309 trex->duration = avio_rb32(pb);
6310 trex->size = avio_rb32(pb);
6311 trex->flags = avio_rb32(pb);
6312 return 0;
6313}
6314
6316{
6317 MOVFragment *frag = &c->fragment;
6318 AVStream *st = NULL;
6319 MOVStreamContext *sc;
6320 int version, i;
6321 MOVFragmentStreamInfo * frag_stream_info;
6322 int64_t base_media_decode_time;
6323
6324 for (i = 0; i < c->fc->nb_streams; i++) {
6325 sc = c->fc->streams[i]->priv_data;
6326 if (sc->id == frag->track_id) {
6327 st = c->fc->streams[i];
6328 break;
6329 }
6330 }
6331 if (!st) {
6332 av_log(c->fc, AV_LOG_WARNING, "could not find corresponding track id %u\n", frag->track_id);
6333 return 0;
6334 }
6335 sc = st->priv_data;
6336 if (sc->pseudo_stream_id + 1 != frag->stsd_id && sc->pseudo_stream_id != -1)
6337 return 0;
6338 version = avio_r8(pb);
6339 avio_rb24(pb); /* flags */
6340 if (version) {
6341 base_media_decode_time = avio_rb64(pb);
6342 } else {
6343 base_media_decode_time = avio_rb32(pb);
6344 }
6345
6346 frag_stream_info = get_current_frag_stream_info(&c->frag_index);
6347 if (frag_stream_info)
6348 frag_stream_info->tfdt_dts = base_media_decode_time;
6349 sc->track_end = base_media_decode_time;
6350
6351 return 0;
6352}
6353
6355{
6356 MOVFragment *frag = &c->fragment;
6357 AVStream *st = NULL;
6358 FFStream *sti = NULL;
6359 MOVStreamContext *sc;
6360 MOVTimeToSample *tts_data;
6361 uint64_t offset;
6362 int64_t dts, pts = AV_NOPTS_VALUE;
6363 int data_offset = 0;
6364 unsigned entries, first_sample_flags = frag->flags;
6365 int flags, distance, i;
6366 int64_t prev_dts = AV_NOPTS_VALUE;
6367 int next_frag_index = -1, index_entry_pos;
6368 size_t requested_size;
6369 AVIndexEntry *new_entries;
6370 MOVFragmentStreamInfo * frag_stream_info;
6371
6372 if (!frag->found_tfhd) {
6373 av_log(c->fc, AV_LOG_ERROR, "trun track id unknown, no tfhd was found\n");
6374 return AVERROR_INVALIDDATA;
6375 }
6376
6377 for (i = 0; i < c->fc->nb_streams; i++) {
6378 sc = c->fc->streams[i]->priv_data;
6379 if (sc->id == frag->track_id) {
6380 st = c->fc->streams[i];
6381 sti = ffstream(st);
6382 break;
6383 }
6384 }
6385 if (!st) {
6386 av_log(c->fc, AV_LOG_WARNING, "could not find corresponding track id %u\n", frag->track_id);
6387 return 0;
6388 }
6389 sc = st->priv_data;
6390 if (sc->pseudo_stream_id+1 != frag->stsd_id && sc->pseudo_stream_id != -1)
6391 return 0;
6392
6393 // Find the next frag_index index that has a valid index_entry for
6394 // the current track_id.
6395 //
6396 // A valid index_entry means the trun for the fragment was read
6397 // and it's samples are in index_entries at the given position.
6398 // New index entries will be inserted before the index_entry found.
6399 index_entry_pos = sti->nb_index_entries;
6400 for (i = c->frag_index.current + 1; i < c->frag_index.nb_items; i++) {
6401 frag_stream_info = get_frag_stream_info(&c->frag_index, i, frag->track_id);
6402 if (frag_stream_info && frag_stream_info->index_entry >= 0) {
6403 next_frag_index = i;
6404 index_entry_pos = frag_stream_info->index_entry;
6405 break;
6406 }
6407 }
6408 av_assert0(index_entry_pos <= sti->nb_index_entries);
6409
6410 avio_r8(pb); /* version */
6411 flags = avio_rb24(pb);
6412 entries = avio_rb32(pb);
6413 av_log(c->fc, AV_LOG_TRACE, "flags 0x%x entries %u\n", flags, entries);
6414
6415 /* Explicit zero sizes are bounded by the trun payload. Reject a zero
6416 * default size before allocating or updating the sample index. */
6417 if (entries && !frag->size && !(flags & MOV_TRUN_SAMPLE_SIZE))
6418 return AVERROR_INVALIDDATA;
6419
6420 if ((uint64_t)entries+sc->tts_count >= UINT_MAX/sizeof(*sc->tts_data))
6421 return AVERROR_INVALIDDATA;
6422 if (flags & MOV_TRUN_DATA_OFFSET) data_offset = avio_rb32(pb);
6423 if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS) first_sample_flags = avio_rb32(pb);
6424
6425 int entry_size = !!(flags & MOV_TRUN_SAMPLE_DURATION) * 4
6426 + !!(flags & MOV_TRUN_SAMPLE_SIZE) * 4
6427 + !!(flags & MOV_TRUN_SAMPLE_FLAGS) * 4
6428 + !!(flags & MOV_TRUN_SAMPLE_CTS) * 4;
6429 int64_t sample_data_size = avio_size(sc->pb);
6430 int64_t max_entries = INT64_MAX;
6431
6432 if (sample_data_size > 0)
6433 max_entries = sample_data_size - sti->nb_index_entries;
6434 if (entry_size) {
6435 int64_t size = sc->pb == pb ? sample_data_size : avio_size(pb);
6436 int64_t pos = avio_tell(pb);
6437 int64_t left = atom.size - 8 - !!(flags & MOV_TRUN_DATA_OFFSET) * 4
6439
6440 if (pos >= 0 && size >= pos)
6441 left = FFMIN(left, size - pos);
6442 max_entries = FFMIN(max_entries, left / entry_size);
6443 }
6444 if (entries > max_entries) {
6445 av_log(c->fc, AV_LOG_ERROR, "trun sample count %u exceeds the %"PRId64" "
6446 "samples the input can hold\n", entries, max_entries);
6447 return AVERROR_INVALIDDATA;
6448 }
6449
6450 frag_stream_info = get_current_frag_stream_info(&c->frag_index);
6451 if (frag_stream_info) {
6452 if (frag_stream_info->next_trun_dts != AV_NOPTS_VALUE) {
6453 dts = av_sat_sub64(frag_stream_info->next_trun_dts, sc->time_offset);
6454 } else if (frag_stream_info->first_tfra_pts != AV_NOPTS_VALUE &&
6455 c->use_mfra_for == FF_MOV_FLAG_MFRA_PTS) {
6456 pts = frag_stream_info->first_tfra_pts;
6457 av_log(c->fc, AV_LOG_DEBUG, "found mfra time %"PRId64
6458 ", using it for pts\n", pts);
6459 } else if (frag_stream_info->first_tfra_pts != AV_NOPTS_VALUE &&
6460 c->use_mfra_for == FF_MOV_FLAG_MFRA_DTS) {
6461 dts = frag_stream_info->first_tfra_pts;
6462 av_log(c->fc, AV_LOG_DEBUG, "found mfra time %"PRId64
6463 ", using it for dts\n", pts);
6464 } else {
6465 int has_tfdt = frag_stream_info->tfdt_dts != AV_NOPTS_VALUE;
6466 int has_sidx = frag_stream_info->sidx_pts != AV_NOPTS_VALUE;
6467 int fallback_tfdt = !c->use_tfdt && !has_sidx && has_tfdt;
6468 int fallback_sidx = c->use_tfdt && !has_tfdt && has_sidx;
6469
6470 if (fallback_sidx) {
6471 av_log(c->fc, AV_LOG_DEBUG, "use_tfdt set but no tfdt found, using sidx instead\n");
6472 }
6473 if (fallback_tfdt) {
6474 av_log(c->fc, AV_LOG_DEBUG, "use_tfdt not set but no sidx found, using tfdt instead\n");
6475 }
6476
6477 if (has_tfdt && c->use_tfdt || fallback_tfdt) {
6478 dts = av_sat_sub64(frag_stream_info->tfdt_dts, sc->time_offset);
6479 av_log(c->fc, AV_LOG_DEBUG, "found tfdt time %"PRId64
6480 ", using it for dts\n", dts);
6481 } else if (has_sidx && !c->use_tfdt || fallback_sidx) {
6482 // FIXME: sidx earliest_presentation_time is *PTS*, s.b.
6483 // pts = frag_stream_info->sidx_pts;
6484 dts = frag_stream_info->sidx_pts;
6485 av_log(c->fc, AV_LOG_DEBUG, "found sidx time %"PRId64
6486 ", using it for dts\n", frag_stream_info->sidx_pts);
6487 } else {
6488 dts = av_sat_sub64(sc->track_end, sc->time_offset);
6489 av_log(c->fc, AV_LOG_DEBUG, "found track end time %"PRId64
6490 ", using it for dts\n", dts);
6491 }
6492 }
6493 } else {
6494 dts = av_sat_sub64(sc->track_end, sc->time_offset);
6495 av_log(c->fc, AV_LOG_DEBUG, "found track end time %"PRId64
6496 ", using it for dts\n", dts);
6497 }
6498 offset = frag->base_data_offset + data_offset;
6499 distance = 0;
6500 av_log(c->fc, AV_LOG_TRACE, "first sample flags 0x%x\n", first_sample_flags);
6501
6502 // realloc space for new index entries
6503 if ((uint64_t)sti->nb_index_entries + entries >= UINT_MAX / sizeof(AVIndexEntry)) {
6504 entries = UINT_MAX / sizeof(AVIndexEntry) - sti->nb_index_entries;
6505 av_log(c->fc, AV_LOG_ERROR, "Failed to add index entry\n");
6506 }
6507 if (entries == 0)
6508 return 0;
6509
6510 requested_size = (sti->nb_index_entries + entries) * sizeof(AVIndexEntry);
6511 new_entries = av_fast_realloc(sti->index_entries,
6513 requested_size);
6514 if (!new_entries)
6515 return AVERROR(ENOMEM);
6516 sti->index_entries= new_entries;
6517
6518 requested_size = (sti->nb_index_entries + entries) * sizeof(*sc->tts_data);
6519 tts_data = av_fast_realloc(sc->tts_data, &sc->tts_allocated_size,
6520 requested_size);
6521 if (!tts_data)
6522 return AVERROR(ENOMEM);
6523 sc->tts_data = tts_data;
6524
6525 // In case there were samples without time to sample entries, ensure they get
6526 // zero valued entries. This ensures clips which mix boxes with and
6527 // without time to sample entries don't pickup uninitialized data.
6528 if (sc->tts_count < sti->nb_index_entries)
6529 memset(sc->tts_data + sc->tts_count, 0,
6530 sizeof(*sc->tts_data) * (sti->nb_index_entries - sc->tts_count));
6531
6532 if (index_entry_pos < sti->nb_index_entries) {
6533 // Make hole in index_entries and tts_data for new samples
6534 memmove(sti->index_entries + index_entry_pos + entries,
6535 sti->index_entries + index_entry_pos,
6536 sizeof(*sti->index_entries) *
6537 (sti->nb_index_entries - index_entry_pos));
6538 memmove(sc->tts_data + index_entry_pos + entries,
6539 sc->tts_data + index_entry_pos,
6540 sizeof(*sc->tts_data) * (sti->nb_index_entries - index_entry_pos));
6541 if (index_entry_pos <= sc->current_sample) {
6542 sc->current_sample += entries;
6543 }
6544 if (index_entry_pos <= sc->tts_index)
6545 sc->tts_index += entries;
6546 }
6547
6548 sti->nb_index_entries += entries;
6549 sc->tts_count = sti->nb_index_entries;
6550 sc->stts_count = sti->nb_index_entries;
6552 sc->ctts_count = sti->nb_index_entries;
6553
6554 // Record the index_entry position in frag_index of this fragment
6555 if (frag_stream_info) {
6556 frag_stream_info->index_entry = index_entry_pos;
6557 if (frag_stream_info->index_base < 0)
6558 frag_stream_info->index_base = index_entry_pos;
6559 }
6560
6561 if (index_entry_pos > 0)
6562 prev_dts = sti->index_entries[index_entry_pos-1].timestamp;
6563
6564 for (i = 0; i < entries && !pb->eof_reached; i++) {
6565 unsigned sample_size = frag->size;
6566 int sample_flags = i ? frag->flags : first_sample_flags;
6567 unsigned sample_duration = frag->duration;
6568 unsigned ctts_duration = 0;
6569 int keyframe = 0;
6570 int index_entry_flags = 0;
6571
6572 if (flags & MOV_TRUN_SAMPLE_DURATION) sample_duration = avio_rb32(pb);
6573 if (flags & MOV_TRUN_SAMPLE_SIZE) sample_size = avio_rb32(pb);
6574 if (flags & MOV_TRUN_SAMPLE_FLAGS) sample_flags = avio_rb32(pb);
6575 if (flags & MOV_TRUN_SAMPLE_CTS) ctts_duration = avio_rb32(pb);
6576
6577 if (sample_duration > c->max_stts_delta) {
6578 av_log(c->fc, AV_LOG_WARNING,
6579 "Too large sample duration %u in trun entry %u in st:%d. Clipping to 1.\n",
6580 sample_duration, i, st->index);
6581 sample_duration = 1;
6582 }
6583
6584 mov_update_dts_shift(sc, ctts_duration, c->fc);
6585 if (pts != AV_NOPTS_VALUE) {
6586 dts = av_sat_sub64(pts, sc->dts_shift);
6587 if (flags & MOV_TRUN_SAMPLE_CTS) {
6588 dts = av_sat_sub64(dts, ctts_duration);
6589 } else {
6590 dts = av_sat_sub64(dts, sc->time_offset);
6591 }
6592 av_log(c->fc, AV_LOG_DEBUG,
6593 "pts %"PRId64" calculated dts %"PRId64
6594 " sc->dts_shift %d ctts.duration %d"
6595 " sc->time_offset %"PRId64
6596 " flags & MOV_TRUN_SAMPLE_CTS %d\n",
6597 pts, dts,
6598 sc->dts_shift, ctts_duration,
6601 }
6602
6603 keyframe =
6604 !(sample_flags & (MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC |
6606 if (keyframe) {
6607 distance = 0;
6608 index_entry_flags |= AVINDEX_KEYFRAME;
6609 }
6610 // Fragments can overlap in time. Discard overlapping frames after
6611 // decoding.
6612 if (prev_dts >= dts)
6613 index_entry_flags |= AVINDEX_DISCARD_FRAME;
6614
6615 sti->index_entries[index_entry_pos].pos = offset;
6616 sti->index_entries[index_entry_pos].timestamp = dts;
6617 sti->index_entries[index_entry_pos].size = sample_size;
6618 sti->index_entries[index_entry_pos].min_distance = distance;
6619 sti->index_entries[index_entry_pos].flags = index_entry_flags;
6620
6621 sc->tts_data[index_entry_pos].count = 1;
6622 sc->tts_data[index_entry_pos].offset = ctts_duration;
6623 sc->tts_data[index_entry_pos].duration = sample_duration;
6624 index_entry_pos++;
6625
6626 av_log(c->fc, AV_LOG_TRACE, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
6627 "size %u, distance %d, keyframe %d\n", st->index,
6628 index_entry_pos, offset, dts, sample_size, distance, keyframe);
6629 distance++;
6630 if (av_sat_add64(dts, sample_duration) != dts + (uint64_t)sample_duration)
6631 return AVERROR_INVALIDDATA;
6632 dts += sample_duration;
6633 offset += sample_size;
6634 sc->data_size += sample_size;
6635
6636 if (sample_duration <= INT64_MAX - sc->duration_for_fps &&
6637 1 <= INT_MAX - sc->nb_frames_for_fps
6638 ) {
6639 sc->duration_for_fps += sample_duration;
6640 sc->nb_frames_for_fps ++;
6641 }
6642 }
6643 if (frag_stream_info)
6644 frag_stream_info->next_trun_dts = av_sat_add64(dts, sc->time_offset);
6645 if (i < entries) {
6646 // EOF found before reading all entries. Fix the hole this would
6647 // leave in index_entries and tts_data
6648 int gap = entries - i;
6649 memmove(sti->index_entries + index_entry_pos,
6650 sti->index_entries + index_entry_pos + gap,
6651 sizeof(*sti->index_entries) *
6652 (sti->nb_index_entries - (index_entry_pos + gap)));
6653 memmove(sc->tts_data + index_entry_pos,
6654 sc->tts_data + index_entry_pos + gap,
6655 sizeof(*sc->tts_data) *
6656 (sc->tts_count - (index_entry_pos + gap)));
6657
6658 sti->nb_index_entries -= gap;
6659 sc->tts_count -= gap;
6660 if (index_entry_pos < sc->current_sample) {
6661 sc->current_sample -= gap;
6662 }
6663 if (index_entry_pos < sc->tts_index)
6664 sc->tts_index -= gap;
6665 entries = i;
6666 }
6667
6668 // The end of this new fragment may overlap in time with the start
6669 // of the next fragment in index_entries. Mark the samples in the next
6670 // fragment that overlap with AVINDEX_DISCARD_FRAME
6671 prev_dts = AV_NOPTS_VALUE;
6672 if (index_entry_pos > 0)
6673 prev_dts = sti->index_entries[index_entry_pos-1].timestamp;
6674 for (int i = index_entry_pos; i < sti->nb_index_entries; i++) {
6675 if (prev_dts < sti->index_entries[i].timestamp)
6676 break;
6678 }
6679
6680 // If a hole was created to insert the new index_entries into,
6681 // the index_entry recorded for all subsequent moof must
6682 // be incremented by the number of entries inserted.
6683 fix_frag_index_entries(&c->frag_index, next_frag_index,
6684 frag->track_id, entries);
6685
6686 if (pb->eof_reached) {
6687 av_log(c->fc, AV_LOG_WARNING, "reached eof, corrupted TRUN atom\n");
6688 return AVERROR_EOF;
6689 }
6690
6691 frag->implicit_offset = offset;
6692
6693 sc->track_end = av_sat_add64(dts, sc->time_offset);
6694 if (st->duration < sc->track_end)
6695 st->duration = sc->track_end;
6696
6697 return 0;
6698}
6699
6701{
6702 int64_t stream_size = avio_size(pb);
6703 int64_t offset = av_sat_add64(avio_tell(pb), atom.size), pts, timestamp;
6704 uint8_t version, is_complete;
6705 int64_t offadd;
6706 unsigned i, j, track_id, item_count;
6707 AVStream *st = NULL;
6708 AVStream *ref_st = NULL;
6709 MOVStreamContext *sc, *ref_sc = NULL;
6710 AVRational timescale;
6711
6712 version = avio_r8(pb);
6713 if (version > 1) {
6714 avpriv_request_sample(c->fc, "sidx version %u", version);
6715 return 0;
6716 }
6717
6718 avio_rb24(pb); // flags
6719
6720 track_id = avio_rb32(pb); // Reference ID
6721 for (i = 0; i < c->fc->nb_streams; i++) {
6722 sc = c->fc->streams[i]->priv_data;
6723 if (sc->id == track_id) {
6724 st = c->fc->streams[i];
6725 break;
6726 }
6727 }
6728 if (!st) {
6729 av_log(c->fc, AV_LOG_WARNING, "could not find corresponding track id %d\n", track_id);
6730 return 0;
6731 }
6732
6733 sc = st->priv_data;
6734
6735 timescale = av_make_q(1, avio_rb32(pb));
6736
6737 if (timescale.den <= 0) {
6738 av_log(c->fc, AV_LOG_ERROR, "Invalid sidx timescale 1/%d\n", timescale.den);
6739 return AVERROR_INVALIDDATA;
6740 }
6741
6742 if (version == 0) {
6743 pts = avio_rb32(pb);
6744 offadd= avio_rb32(pb);
6745 } else {
6746 pts = avio_rb64(pb);
6747 offadd= avio_rb64(pb);
6748 }
6749 if (av_sat_add64(offset, offadd) != offset + (uint64_t)offadd)
6750 return AVERROR_INVALIDDATA;
6751
6752 offset += (uint64_t)offadd;
6753
6754 avio_rb16(pb); // reserved
6755
6756 item_count = avio_rb16(pb);
6757 if (item_count == 0)
6758 return AVERROR_INVALIDDATA;
6759
6760 for (i = 0; i < item_count; i++) {
6761 int index;
6762 MOVFragmentStreamInfo * frag_stream_info;
6763 uint32_t size = avio_rb32(pb);
6764 uint32_t duration = avio_rb32(pb);
6765 if (size & 0x80000000) {
6766 avpriv_request_sample(c->fc, "sidx reference_type 1");
6767 return AVERROR_PATCHWELCOME;
6768 }
6769 avio_rb32(pb); // sap_flags
6770 timestamp = av_rescale_q(pts, timescale, st->time_base);
6771
6773 frag_stream_info = get_frag_stream_info(&c->frag_index, index, track_id);
6774 if (frag_stream_info)
6775 frag_stream_info->sidx_pts = timestamp;
6776
6777 if (av_sat_add64(offset, size) != offset + (uint64_t)size ||
6778 av_sat_add64(pts, duration) != pts + (uint64_t)duration
6779 )
6780 return AVERROR_INVALIDDATA;
6781 offset += size;
6782 pts += duration;
6783 }
6784
6785 st->duration = sc->track_end = pts;
6786
6787 sc->has_sidx = 1;
6788
6789 // See if the remaining bytes are just an mfra which we can ignore.
6790 is_complete = offset == stream_size;
6791 if (!is_complete && (pb->seekable & AVIO_SEEKABLE_NORMAL) && stream_size > 0 ) {
6792 int64_t ret;
6793 int64_t original_pos = avio_tell(pb);
6794 if (!c->have_read_mfra_size) {
6795 if ((ret = avio_seek(pb, stream_size - 4, SEEK_SET)) < 0)
6796 return ret;
6797 c->mfra_size = avio_rb32(pb);
6798 c->have_read_mfra_size = 1;
6799 if ((ret = avio_seek(pb, original_pos, SEEK_SET)) < 0)
6800 return ret;
6801 }
6802 if (offset == stream_size - c->mfra_size)
6803 is_complete = 1;
6804 }
6805
6806 if (is_complete) {
6807 // Find first entry in fragment index that came from an sidx.
6808 // This will pretty much always be the first entry.
6809 for (i = 0; i < c->frag_index.nb_items; i++) {
6810 MOVFragmentIndexItem * item = &c->frag_index.item[i];
6811 for (j = 0; ref_st == NULL && j < item->nb_stream_info; j++) {
6813 si = &item->stream_info[j];
6814 if (si->sidx_pts != AV_NOPTS_VALUE) {
6815 ref_st = c->fc->streams[j];
6816 ref_sc = ref_st->priv_data;
6817 break;
6818 }
6819 }
6820 }
6821 if (ref_st) for (i = 0; i < c->fc->nb_streams; i++) {
6822 st = c->fc->streams[i];
6823 sc = st->priv_data;
6824 if (!sc->has_sidx) {
6825 st->duration = sc->track_end = av_rescale(ref_st->duration, sc->time_scale, ref_sc->time_scale);
6826 }
6827 }
6828
6829 if (offadd == 0)
6830 c->frag_index.complete = 1;
6831 }
6832
6833 return 0;
6834}
6835
6836/* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
6837/* like the files created with Adobe Premiere 5.0, for samples see */
6838/* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
6840{
6841 int err;
6842
6843 if (atom.size < 8)
6844 return 0; /* continue */
6845 if (avio_rb32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
6846 avio_skip(pb, atom.size - 4);
6847 return 0;
6848 }
6849 atom.type = avio_rl32(pb);
6850 atom.size -= 8;
6851 if (atom.type != MKTAG('m','d','a','t')) {
6852 avio_skip(pb, atom.size);
6853 return 0;
6854 }
6855 err = mov_read_mdat(c, pb, atom);
6856 return err;
6857}
6858
6860{
6861#if CONFIG_ZLIB
6863 uint8_t *cmov_data;
6864 uint8_t *moov_data; /* uncompressed data */
6865 long cmov_len, moov_len;
6866 int ret = -1;
6867
6868 avio_rb32(pb); /* dcom atom */
6869 if (avio_rl32(pb) != MKTAG('d','c','o','m'))
6870 return AVERROR_INVALIDDATA;
6871 if (avio_rl32(pb) != MKTAG('z','l','i','b')) {
6872 av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !\n");
6873 return AVERROR_INVALIDDATA;
6874 }
6875 avio_rb32(pb); /* cmvd atom */
6876 if (avio_rl32(pb) != MKTAG('c','m','v','d'))
6877 return AVERROR_INVALIDDATA;
6878 moov_len = avio_rb32(pb); /* uncompressed size */
6879 cmov_len = atom.size - 6 * 4;
6880
6881 cmov_data = av_malloc(cmov_len);
6882 if (!cmov_data)
6883 return AVERROR(ENOMEM);
6884 moov_data = av_malloc(moov_len);
6885 if (!moov_data) {
6886 av_free(cmov_data);
6887 return AVERROR(ENOMEM);
6888 }
6889 ret = ffio_read_size(pb, cmov_data, cmov_len);
6890 if (ret < 0)
6891 goto free_and_return;
6892
6894 if (uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
6895 goto free_and_return;
6896 ffio_init_read_context(&ctx, moov_data, moov_len);
6897 ctx.pub.seekable = AVIO_SEEKABLE_NORMAL;
6898 atom.type = MKTAG('m','o','o','v');
6899 atom.size = moov_len;
6900 ret = mov_read_default(c, &ctx.pub, atom);
6901free_and_return:
6902 av_free(moov_data);
6903 av_free(cmov_data);
6904 return ret;
6905#else
6906 av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
6907 return AVERROR(ENOSYS);
6908#endif
6909}
6910
6911/* edit list atom */
6913{
6914 MOVStreamContext *sc;
6915 int i, edit_count, version;
6916 int64_t elst_entry_size;
6917
6918 if (c->fc->nb_streams < 1 || c->ignore_editlist)
6919 return 0;
6920 sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
6921
6922 version = avio_r8(pb); /* version */
6923 avio_rb24(pb); /* flags */
6924 edit_count = avio_rb32(pb); /* entries */
6925 atom.size -= 8;
6926
6927 elst_entry_size = version == 1 ? 20 : 12;
6928 if (atom.size != edit_count * elst_entry_size) {
6929 if (c->fc->strict_std_compliance >= FF_COMPLIANCE_STRICT) {
6930 av_log(c->fc, AV_LOG_ERROR, "Invalid edit list entry_count: %d for elst atom of size: %"PRId64" bytes.\n",
6931 edit_count, atom.size + 8);
6932 return AVERROR_INVALIDDATA;
6933 } else {
6934 edit_count = atom.size / elst_entry_size;
6935 if (edit_count * elst_entry_size != atom.size) {
6936 av_log(c->fc, AV_LOG_WARNING, "ELST atom of %"PRId64" bytes, bigger than %d entries.\n", atom.size, edit_count);
6937 }
6938 }
6939 }
6940
6941 if (!edit_count)
6942 return 0;
6943 if (sc->elst_data)
6944 av_log(c->fc, AV_LOG_WARNING, "Duplicated ELST atom\n");
6945 av_free(sc->elst_data);
6946 sc->elst_count = 0;
6947 sc->elst_data = av_malloc_array(edit_count, sizeof(*sc->elst_data));
6948 if (!sc->elst_data)
6949 return AVERROR(ENOMEM);
6950
6951 av_log(c->fc, AV_LOG_TRACE, "track[%u].edit_count = %i\n", c->fc->nb_streams - 1, edit_count);
6952 for (i = 0; i < edit_count && atom.size > 0 && !pb->eof_reached; i++) {
6953 MOVElst *e = &sc->elst_data[i];
6954
6955 if (version == 1) {
6956 e->duration = avio_rb64(pb);
6957 e->time = avio_rb64(pb);
6958 atom.size -= 16;
6959 } else {
6960 e->duration = avio_rb32(pb); /* segment duration */
6961 e->time = (int32_t)avio_rb32(pb); /* media time */
6962 atom.size -= 8;
6963 }
6964 e->rate = avio_rb32(pb) / 65536.0;
6965 atom.size -= 4;
6966 av_log(c->fc, AV_LOG_TRACE, "duration=%"PRId64" time=%"PRId64" rate=%f\n",
6967 e->duration, e->time, e->rate);
6968
6969 if (e->time < 0 && e->time != -1 &&
6970 c->fc->strict_std_compliance >= FF_COMPLIANCE_STRICT) {
6971 av_log(c->fc, AV_LOG_ERROR, "Track %d, edit %d: Invalid edit list media time=%"PRId64"\n",
6972 c->fc->nb_streams-1, i, e->time);
6973 return AVERROR_INVALIDDATA;
6974 }
6975 if (e->duration < 0) {
6976 av_log(c->fc, AV_LOG_ERROR, "Track %d, edit %d: Invalid edit list duration=%"PRId64"\n",
6977 c->fc->nb_streams-1, i, e->duration);
6978 return AVERROR_INVALIDDATA;
6979 }
6980 }
6981 sc->elst_count = i;
6982
6983 return 0;
6984}
6985
6987{
6988 MOVStreamContext *sc;
6989 int err;
6990
6991 if (c->fc->nb_streams < 1)
6992 return AVERROR_INVALIDDATA;
6993 sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
6994
6995 if (atom.size % sizeof(uint32_t))
6996 return AVERROR_INVALIDDATA;
6997
6998 MovTref *tag = mov_add_tref_tag(sc, atom.type);
6999 if (!tag)
7000 return AVERROR(ENOMEM);
7001
7002 int nb_timecode_track = atom.size >> 2;
7003 for (int i = 0; i < nb_timecode_track; i++) {
7004 if (avio_feof(pb))
7005 return AVERROR_INVALIDDATA;
7006 err = mov_add_tref_id(tag, avio_rb32(pb));
7007 if (err < 0)
7008 return err;
7009 }
7010
7011 return 0;
7012}
7013
7015{
7016 AVStream *st;
7017 int version, color_range, color_primaries, color_trc, color_space;
7018
7019 if (c->fc->nb_streams < 1)
7020 return 0;
7021 st = c->fc->streams[c->fc->nb_streams - 1];
7022
7023 if (atom.size < 5) {
7024 av_log(c->fc, AV_LOG_ERROR, "Empty VP Codec Configuration box\n");
7025 return AVERROR_INVALIDDATA;
7026 }
7027
7028 version = avio_r8(pb);
7029 if (version != 1) {
7030 av_log(c->fc, AV_LOG_WARNING, "Unsupported VP Codec Configuration box version %d\n", version);
7031 return 0;
7032 }
7033 avio_skip(pb, 3); /* flags */
7034
7035 avio_skip(pb, 2); /* profile + level */
7036 color_range = avio_r8(pb); /* bitDepth, chromaSubsampling, videoFullRangeFlag */
7038 color_trc = avio_r8(pb);
7039 color_space = avio_r8(pb);
7040 if (avio_rb16(pb)) /* codecIntializationDataSize */
7041 return AVERROR_INVALIDDATA;
7042
7043 // Reserved and unassigned values carry no colour information
7048 if (color_trc == AVCOL_TRC_RESERVED0 ||
7049 color_trc == AVCOL_TRC_RESERVED ||
7050 !av_color_transfer_name(color_trc))
7051 color_trc = AVCOL_TRC_UNSPECIFIED;
7052 if (color_space == AVCOL_SPC_RESERVED ||
7053 !av_color_space_name(color_space))
7054 color_space = AVCOL_SPC_UNSPECIFIED;
7055
7058 st->codecpar->color_trc = color_trc;
7059 st->codecpar->color_space = color_space;
7060
7061 return 0;
7062}
7063
7065{
7066 MOVStreamContext *sc;
7067 int i, version;
7068
7069 if (c->fc->nb_streams < 1)
7070 return AVERROR_INVALIDDATA;
7071
7072 sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
7073
7074 if (atom.size < 5) {
7075 av_log(c->fc, AV_LOG_ERROR, "Empty Mastering Display Metadata box\n");
7076 return AVERROR_INVALIDDATA;
7077 }
7078
7079 version = avio_r8(pb);
7080 if (version) {
7081 av_log(c->fc, AV_LOG_WARNING, "Unsupported Mastering Display Metadata box version %d\n", version);
7082 return 0;
7083 }
7084 if (sc->mastering) {
7085 av_log(c->fc, AV_LOG_WARNING, "Ignoring duplicate Mastering Display Metadata\n");
7086 return 0;
7087 }
7088
7089 avio_skip(pb, 3); /* flags */
7090
7092 if (!sc->mastering)
7093 return AVERROR(ENOMEM);
7094
7095 for (i = 0; i < 3; i++) {
7096 sc->mastering->display_primaries[i][0] = av_make_q(avio_rb16(pb), 1 << 16);
7097 sc->mastering->display_primaries[i][1] = av_make_q(avio_rb16(pb), 1 << 16);
7098 }
7099 sc->mastering->white_point[0] = av_make_q(avio_rb16(pb), 1 << 16);
7100 sc->mastering->white_point[1] = av_make_q(avio_rb16(pb), 1 << 16);
7101
7102 sc->mastering->max_luminance = av_make_q(avio_rb32(pb), 1 << 8);
7103 sc->mastering->min_luminance = av_make_q(avio_rb32(pb), 1 << 14);
7104
7105 sc->mastering->has_primaries = 1;
7106 sc->mastering->has_luminance = 1;
7107
7108 return 0;
7109}
7110
7112{
7113 MOVStreamContext *sc;
7114 const int mapping[3] = {1, 2, 0};
7115 const int chroma_den = 50000;
7116 const int luma_den = 10000;
7117 int i;
7118
7119 if (c->fc->nb_streams < 1)
7120 return AVERROR_INVALIDDATA;
7121
7122 sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
7123
7124 if (atom.size < 24) {
7125 av_log(c->fc, AV_LOG_ERROR, "Invalid Mastering Display Color Volume box\n");
7126 return AVERROR_INVALIDDATA;
7127 }
7128
7129 if (sc->mastering) {
7130 av_log(c->fc, AV_LOG_WARNING, "Ignoring duplicate Mastering Display Color Volume\n");
7131 return 0;
7132 }
7133
7135 if (!sc->mastering)
7136 return AVERROR(ENOMEM);
7137
7138 for (i = 0; i < 3; i++) {
7139 const int j = mapping[i];
7140 sc->mastering->display_primaries[j][0] = av_make_q(avio_rb16(pb), chroma_den);
7141 sc->mastering->display_primaries[j][1] = av_make_q(avio_rb16(pb), chroma_den);
7142 }
7143 sc->mastering->white_point[0] = av_make_q(avio_rb16(pb), chroma_den);
7144 sc->mastering->white_point[1] = av_make_q(avio_rb16(pb), chroma_den);
7145
7146 sc->mastering->max_luminance = av_make_q(avio_rb32(pb), luma_den);
7147 sc->mastering->min_luminance = av_make_q(avio_rb32(pb), luma_den);
7148
7149 sc->mastering->has_luminance = 1;
7150 sc->mastering->has_primaries = 1;
7151
7152 return 0;
7153}
7154
7156{
7157 MOVStreamContext *sc;
7158 int version;
7159
7160 if (c->fc->nb_streams < 1)
7161 return AVERROR_INVALIDDATA;
7162
7163 sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
7164
7165 if (atom.size < 5) {
7166 av_log(c->fc, AV_LOG_ERROR, "Empty Content Light Level box\n");
7167 return AVERROR_INVALIDDATA;
7168 }
7169
7170 version = avio_r8(pb);
7171 if (version) {
7172 av_log(c->fc, AV_LOG_WARNING, "Unsupported Content Light Level box version %d\n", version);
7173 return 0;
7174 }
7175 avio_skip(pb, 3); /* flags */
7176
7177 if (sc->coll){
7178 av_log(c->fc, AV_LOG_WARNING, "Ignoring duplicate COLL\n");
7179 return 0;
7180 }
7181
7183 if (!sc->coll)
7184 return AVERROR(ENOMEM);
7185
7186 sc->coll->MaxCLL = avio_rb16(pb);
7187 sc->coll->MaxFALL = avio_rb16(pb);
7188
7189 return 0;
7190}
7191
7193{
7194 MOVStreamContext *sc;
7195
7196 if (c->fc->nb_streams < 1)
7197 return AVERROR_INVALIDDATA;
7198
7199 sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
7200
7201 if (atom.size < 4) {
7202 av_log(c->fc, AV_LOG_ERROR, "Empty Content Light Level Info box\n");
7203 return AVERROR_INVALIDDATA;
7204 }
7205
7206 if (sc->coll){
7207 av_log(c->fc, AV_LOG_WARNING, "Ignoring duplicate CLLI/COLL\n");
7208 return 0;
7209 }
7210
7212 if (!sc->coll)
7213 return AVERROR(ENOMEM);
7214
7215 sc->coll->MaxCLL = avio_rb16(pb);
7216 sc->coll->MaxFALL = avio_rb16(pb);
7217
7218 return 0;
7219}
7220
7222{
7223 MOVStreamContext *sc;
7224 const int illuminance_den = 10000;
7225 const int ambient_den = 50000;
7226 if (c->fc->nb_streams < 1)
7227 return AVERROR_INVALIDDATA;
7228 sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
7229 if (atom.size < 6) {
7230 av_log(c->fc, AV_LOG_ERROR, "Empty Ambient Viewing Environment Info box\n");
7231 return AVERROR_INVALIDDATA;
7232 }
7233 if (sc->ambient){
7234 av_log(c->fc, AV_LOG_WARNING, "Ignoring duplicate AMVE\n");
7235 return 0;
7236 }
7238 if (!sc->ambient)
7239 return AVERROR(ENOMEM);
7240 sc->ambient->ambient_illuminance = av_make_q(avio_rb32(pb), illuminance_den);
7241 sc->ambient->ambient_light_x = av_make_q(avio_rb16(pb), ambient_den);
7242 sc->ambient->ambient_light_y = av_make_q(avio_rb16(pb), ambient_den);
7243 return 0;
7244}
7245
7247{
7248 AVStream *st;
7249 MOVStreamContext *sc;
7250 enum AVStereo3DType type;
7251 int mode;
7252
7253 if (c->fc->nb_streams < 1)
7254 return 0;
7255
7256 st = c->fc->streams[c->fc->nb_streams - 1];
7257 sc = st->priv_data;
7258
7259 if (atom.size < 5) {
7260 av_log(c->fc, AV_LOG_ERROR, "Empty stereoscopic video box\n");
7261 return AVERROR_INVALIDDATA;
7262 }
7263
7264 if (sc->stereo3d)
7265 return AVERROR_INVALIDDATA;
7266
7267 avio_skip(pb, 4); /* version + flags */
7268
7269 mode = avio_r8(pb);
7270 switch (mode) {
7271 case 0:
7273 break;
7274 case 1:
7276 break;
7277 case 2:
7279 break;
7280 default:
7281 av_log(c->fc, AV_LOG_WARNING, "Unknown st3d mode value %d\n", mode);
7282 return 0;
7283 }
7284
7286 if (!sc->stereo3d)
7287 return AVERROR(ENOMEM);
7288
7289 sc->stereo3d->type = type;
7290 return 0;
7291}
7292
7294{
7295 AVStream *st;
7296 MOVStreamContext *sc;
7297 int size = 0;
7298 int64_t remaining;
7299 uint32_t tag = 0;
7301
7302 if (c->fc->nb_streams < 1)
7303 return 0;
7304
7305 st = c->fc->streams[c->fc->nb_streams - 1];
7306 sc = st->priv_data;
7307
7308 remaining = atom.size;
7309 while (remaining > 0) {
7310 size = avio_rb32(pb);
7311 if (size < 8 || size > remaining ) {
7312 av_log(c->fc, AV_LOG_ERROR, "Invalid child size in pack box\n");
7313 return AVERROR_INVALIDDATA;
7314 }
7315
7316 tag = avio_rl32(pb);
7317 switch (tag) {
7318 case MKTAG('p','k','i','n'): {
7319 if (size != 16) {
7320 av_log(c->fc, AV_LOG_ERROR, "Invalid size of pkin box: %d\n", size);
7321 return AVERROR_INVALIDDATA;
7322 }
7323 avio_skip(pb, 1); // version
7324 avio_skip(pb, 3); // flags
7325
7326 tag = avio_rl32(pb);
7327 switch (tag) {
7328 case MKTAG('s','i','d','e'):
7330 break;
7331 case MKTAG('o','v','e','r'):
7333 break;
7334 case 0:
7335 // This means value will be set in another layer
7336 break;
7337 default:
7338 av_log(c->fc, AV_LOG_WARNING, "Unknown tag in pkin: %s\n",
7340 avio_skip(pb, size - 8);
7341 break;
7342 }
7343
7344 break;
7345 }
7346 default:
7347 av_log(c->fc, AV_LOG_WARNING, "Unknown tag in pack: %s\n",
7349 avio_skip(pb, size - 8);
7350 break;
7351 }
7352 remaining -= size;
7353 }
7354
7355 if (remaining != 0) {
7356 av_log(c->fc, AV_LOG_ERROR, "Broken pack box\n");
7357 return AVERROR_INVALIDDATA;
7358 }
7359
7360 if (type == AV_STEREO3D_2D)
7361 return 0;
7362
7363 if (!sc->stereo3d) {
7365 if (!sc->stereo3d)
7366 return AVERROR(ENOMEM);
7367 }
7368
7369 sc->stereo3d->type = type;
7370
7371 return 0;
7372}
7373
7375{
7376 AVStream *st;
7377 MOVStreamContext *sc;
7378 int size, version, layout;
7379 int32_t yaw, pitch, roll;
7380 uint32_t l = 0, t = 0, r = 0, b = 0;
7381 uint32_t tag, padding = 0;
7382 enum AVSphericalProjection projection;
7383
7384 if (c->fc->nb_streams < 1)
7385 return 0;
7386
7387 st = c->fc->streams[c->fc->nb_streams - 1];
7388 sc = st->priv_data;
7389
7390 if (atom.size < 8) {
7391 av_log(c->fc, AV_LOG_ERROR, "Empty spherical video box\n");
7392 return AVERROR_INVALIDDATA;
7393 }
7394
7395 size = avio_rb32(pb);
7396 if (size <= 12 || size > atom.size)
7397 return AVERROR_INVALIDDATA;
7398
7399 tag = avio_rl32(pb);
7400 if (tag != MKTAG('s','v','h','d')) {
7401 av_log(c->fc, AV_LOG_ERROR, "Missing spherical video header\n");
7402 return 0;
7403 }
7404 version = avio_r8(pb);
7405 if (version != 0) {
7406 av_log(c->fc, AV_LOG_WARNING, "Unknown spherical version %d\n",
7407 version);
7408 return 0;
7409 }
7410 avio_skip(pb, 3); /* flags */
7411 avio_skip(pb, size - 12); /* metadata_source */
7412
7413 size = avio_rb32(pb);
7414 if (size > atom.size)
7415 return AVERROR_INVALIDDATA;
7416
7417 tag = avio_rl32(pb);
7418 if (tag != MKTAG('p','r','o','j')) {
7419 av_log(c->fc, AV_LOG_ERROR, "Missing projection box\n");
7420 return 0;
7421 }
7422
7423 size = avio_rb32(pb);
7424 if (size > atom.size)
7425 return AVERROR_INVALIDDATA;
7426
7427 tag = avio_rl32(pb);
7428 if (tag != MKTAG('p','r','h','d')) {
7429 av_log(c->fc, AV_LOG_ERROR, "Missing projection header box\n");
7430 return 0;
7431 }
7432 version = avio_r8(pb);
7433 if (version != 0) {
7434 av_log(c->fc, AV_LOG_WARNING, "Unknown spherical version %d\n",
7435 version);
7436 return 0;
7437 }
7438 avio_skip(pb, 3); /* flags */
7439
7440 /* 16.16 fixed point */
7441 yaw = avio_rb32(pb);
7442 pitch = avio_rb32(pb);
7443 roll = avio_rb32(pb);
7444
7445 size = avio_rb32(pb);
7446 if (size > atom.size)
7447 return AVERROR_INVALIDDATA;
7448
7449 tag = avio_rl32(pb);
7450 version = avio_r8(pb);
7451 if (version != 0) {
7452 av_log(c->fc, AV_LOG_WARNING, "Unknown spherical version %d\n",
7453 version);
7454 return 0;
7455 }
7456 avio_skip(pb, 3); /* flags */
7457 switch (tag) {
7458 case MKTAG('c','b','m','p'):
7459 layout = avio_rb32(pb);
7460 if (layout) {
7461 av_log(c->fc, AV_LOG_WARNING,
7462 "Unsupported cubemap layout %d\n", layout);
7463 return 0;
7464 }
7465 projection = AV_SPHERICAL_CUBEMAP;
7466 padding = avio_rb32(pb);
7467 break;
7468 case MKTAG('e','q','u','i'):
7469 t = avio_rb32(pb);
7470 b = avio_rb32(pb);
7471 l = avio_rb32(pb);
7472 r = avio_rb32(pb);
7473
7474 if (b >= UINT_MAX - t || r >= UINT_MAX - l) {
7475 av_log(c->fc, AV_LOG_ERROR,
7476 "Invalid bounding rectangle coordinates "
7477 "%"PRIu32",%"PRIu32",%"PRIu32",%"PRIu32"\n", l, t, r, b);
7478 return AVERROR_INVALIDDATA;
7479 }
7480
7481 if (l || t || r || b)
7483 else
7484 projection = AV_SPHERICAL_EQUIRECTANGULAR;
7485 break;
7486 default:
7487 av_log(c->fc, AV_LOG_ERROR, "Unknown projection type: %s\n", av_fourcc2str(tag));
7488 return 0;
7489 }
7490
7491 av_freep(&sc->spherical);
7493 if (!sc->spherical)
7494 return AVERROR(ENOMEM);
7495
7496 sc->spherical->projection = projection;
7497
7498 sc->spherical->yaw = yaw;
7499 sc->spherical->pitch = pitch;
7500 sc->spherical->roll = roll;
7501
7502 sc->spherical->padding = padding;
7503
7504 sc->spherical->bound_left = l;
7505 sc->spherical->bound_top = t;
7506 sc->spherical->bound_right = r;
7507 sc->spherical->bound_bottom = b;
7508
7509 return 0;
7510}
7511
7513{
7514 AVStream *st;
7515 MOVStreamContext *sc;
7516 int size;
7517 uint32_t tag;
7518 enum AVSphericalProjection projection;
7519
7520 if (c->fc->nb_streams < 1)
7521 return 0;
7522
7523 st = c->fc->streams[c->fc->nb_streams - 1];
7524 sc = st->priv_data;
7525
7526 if (atom.size < 16) {
7527 av_log(c->fc, AV_LOG_ERROR, "Invalid size for proj box: %"PRIu64"\n", atom.size);
7528 return AVERROR_INVALIDDATA;
7529 }
7530
7531 size = avio_rb32(pb);
7532 if (size < 16) {
7533 av_log(c->fc, AV_LOG_ERROR, "Invalid size for prji box: %d\n", size);
7534 return AVERROR_INVALIDDATA;
7535 } else if (size > 16) {
7536 av_log(c->fc, AV_LOG_WARNING, "Box has more bytes (%d) than prji box required (16) \n", size);
7537 }
7538
7539 tag = avio_rl32(pb);
7540 if (tag != MKTAG('p','r','j','i')) {
7541 av_log(c->fc, AV_LOG_ERROR, "Invalid child box of proj box: %s\n",
7543 return AVERROR_INVALIDDATA;
7544 }
7545
7546 // version and flags, only support (0, 0)
7547 unsigned n = avio_rl32(pb);
7548 if (n != 0) {
7549 av_log(c->fc, AV_LOG_ERROR, "prji version %u, flag %u are not supported\n",
7550 n & 0xFF, n >> 8);
7551 return AVERROR_PATCHWELCOME;
7552 }
7553
7554 tag = avio_rl32(pb);
7555 switch (tag) {
7556 case MKTAG('r','e','c','t'):
7557 projection = AV_SPHERICAL_RECTILINEAR;
7558 break;
7559 case MKTAG('e','q','u','i'):
7560 projection = AV_SPHERICAL_EQUIRECTANGULAR;
7561 break;
7562 case MKTAG('h','e','q','u'):
7564 break;
7565 case MKTAG('f','i','s','h'):
7566 projection = AV_SPHERICAL_FISHEYE;
7567 break;
7568 case MKTAG('p','r','i','m'):
7570 break;
7571 default:
7572 av_log(c->fc, AV_LOG_ERROR, "Invalid projection type in prji box: %s\n", av_fourcc2str(tag));
7573 return AVERROR_INVALIDDATA;
7574 }
7575
7576 av_freep(&sc->spherical);
7578 if (!sc->spherical)
7579 return AVERROR(ENOMEM);
7580
7581 sc->spherical->projection = projection;
7582
7583 return 0;
7584}
7585
7587{
7588 AVStream *st;
7589 MOVStreamContext *sc;
7590 int size, flags = 0;
7591 int64_t remaining;
7592 uint32_t tag, baseline = 0;
7595 enum AVStereo3DPrimaryEye primary_eye = AV_PRIMARY_EYE_NONE;
7596 AVRational horizontal_disparity_adjustment = { 0, 1 };
7597
7598 if (c->fc->nb_streams < 1)
7599 return 0;
7600
7601 st = c->fc->streams[c->fc->nb_streams - 1];
7602 sc = st->priv_data;
7603
7604 remaining = atom.size;
7605 while (remaining > 0) {
7606 size = avio_rb32(pb);
7607 if (size < 8 || size > remaining ) {
7608 av_log(c->fc, AV_LOG_ERROR, "Invalid child size in eyes box\n");
7609 return AVERROR_INVALIDDATA;
7610 }
7611
7612 tag = avio_rl32(pb);
7613 switch (tag) {
7614 case MKTAG('s','t','r','i'): {
7615 int has_right, has_left;
7616 uint8_t tmp;
7617 if (size != 13) {
7618 av_log(c->fc, AV_LOG_ERROR, "Invalid size of stri box: %d\n", size);
7619 return AVERROR_INVALIDDATA;
7620 }
7621 avio_skip(pb, 1); // version
7622 avio_skip(pb, 3); // flags
7623
7624 tmp = avio_r8(pb);
7625
7626 // eye_views_reversed
7627 if (tmp & 8) {
7629 }
7630 // has_additional_views
7631 if (tmp & 4) {
7632 // skip...
7633 }
7634
7635 has_right = tmp & 2; // has_right_eye_view
7636 has_left = tmp & 1; // has_left_eye_view
7637
7638 if (has_left && has_right)
7640 else if (has_left)
7641 view = AV_STEREO3D_VIEW_LEFT;
7642 else if (has_right)
7644 if (has_left || has_right)
7646
7647 break;
7648 }
7649 case MKTAG('h','e','r','o'): {
7650 int tmp;
7651 if (size != 13) {
7652 av_log(c->fc, AV_LOG_ERROR, "Invalid size of hero box: %d\n", size);
7653 return AVERROR_INVALIDDATA;
7654 }
7655 avio_skip(pb, 1); // version
7656 avio_skip(pb, 3); // flags
7657
7658 tmp = avio_r8(pb);
7659 if (tmp == 0)
7660 primary_eye = AV_PRIMARY_EYE_NONE;
7661 else if (tmp == 1)
7662 primary_eye = AV_PRIMARY_EYE_LEFT;
7663 else if (tmp == 2)
7664 primary_eye = AV_PRIMARY_EYE_RIGHT;
7665 else
7666 av_log(c->fc, AV_LOG_WARNING, "Unknown hero eye type: %d\n", tmp);
7667
7668 break;
7669 }
7670 case MKTAG('c','a','m','s'): {
7671 uint32_t subtag;
7672 int subsize;
7673 if (size != 24) {
7674 av_log(c->fc, AV_LOG_ERROR, "Invalid size of cams box: %d\n", size);
7675 return AVERROR_INVALIDDATA;
7676 }
7677
7678 subsize = avio_rb32(pb);
7679 if (subsize != 16) {
7680 av_log(c->fc, AV_LOG_ERROR, "Invalid size of blin box: %d\n", size);
7681 return AVERROR_INVALIDDATA;
7682 }
7683
7684 subtag = avio_rl32(pb);
7685 if (subtag != MKTAG('b','l','i','n')) {
7686 av_log(c->fc, AV_LOG_ERROR, "Expected blin box, got %s\n",
7687 av_fourcc2str(subtag));
7688 return AVERROR_INVALIDDATA;
7689 }
7690
7691 avio_skip(pb, 1); // version
7692 avio_skip(pb, 3); // flags
7693
7694 baseline = avio_rb32(pb);
7695
7696 break;
7697 }
7698 case MKTAG('c','m','f','y'): {
7699 uint32_t subtag;
7700 int subsize;
7701 int32_t adjustment;
7702 if (size != 24) {
7703 av_log(c->fc, AV_LOG_ERROR, "Invalid size of cmfy box: %d\n", size);
7704 return AVERROR_INVALIDDATA;
7705 }
7706
7707 subsize = avio_rb32(pb);
7708 if (subsize != 16) {
7709 av_log(c->fc, AV_LOG_ERROR, "Invalid size of dadj box: %d\n", size);
7710 return AVERROR_INVALIDDATA;
7711 }
7712
7713 subtag = avio_rl32(pb);
7714 if (subtag != MKTAG('d','a','d','j')) {
7715 av_log(c->fc, AV_LOG_ERROR, "Expected dadj box, got %s\n",
7716 av_fourcc2str(subtag));
7717 return AVERROR_INVALIDDATA;
7718 }
7719
7720 avio_skip(pb, 1); // version
7721 avio_skip(pb, 3); // flags
7722
7723 adjustment = (int32_t) avio_rb32(pb);
7724
7725 horizontal_disparity_adjustment.num = (int) adjustment;
7726 horizontal_disparity_adjustment.den = 10000;
7727
7728 break;
7729 }
7730 default:
7731 av_log(c->fc, AV_LOG_WARNING, "Unknown tag in eyes: %s\n",
7733 avio_skip(pb, size - 8);
7734 break;
7735 }
7736 remaining -= size;
7737 }
7738
7739 if (remaining != 0) {
7740 av_log(c->fc, AV_LOG_ERROR, "Broken eyes box\n");
7741 return AVERROR_INVALIDDATA;
7742 }
7743
7744 if (type == AV_STEREO3D_2D)
7745 return 0;
7746
7747 if (!sc->stereo3d) {
7749 if (!sc->stereo3d)
7750 return AVERROR(ENOMEM);
7751 }
7752
7753 sc->stereo3d->flags = flags;
7754 /* eyes/stri only records packed vs single-eye, not SBS/TB. Keep a more
7755 * specific type already set by st3d. */
7756 if (type != AV_STEREO3D_UNSPEC)
7757 sc->stereo3d->type = type;
7758 else if (sc->stereo3d->type == AV_STEREO3D_2D)
7759 sc->stereo3d->type = type;
7760 sc->stereo3d->view = view;
7761 sc->stereo3d->primary_eye = primary_eye;
7762 sc->stereo3d->baseline = baseline;
7763 sc->stereo3d->horizontal_disparity_adjustment = horizontal_disparity_adjustment;
7764
7765 return 0;
7766}
7767
7769{
7770 int size;
7771 int64_t remaining;
7772 uint32_t tag;
7773
7774 if (c->fc->nb_streams < 1)
7775 return 0;
7776
7777 if (atom.size < 8) {
7778 av_log(c->fc, AV_LOG_ERROR, "Empty video extension usage box\n");
7779 return AVERROR_INVALIDDATA;
7780 }
7781
7782 remaining = atom.size;
7783 while (remaining > 0) {
7784 size = avio_rb32(pb);
7785 if (size < 8 || size > remaining ) {
7786 av_log(c->fc, AV_LOG_ERROR, "Invalid child size in vexu box\n");
7787 return AVERROR_INVALIDDATA;
7788 }
7789
7790 tag = avio_rl32(pb);
7791 switch (tag) {
7792 case MKTAG('p','r','o','j'): {
7793 MOVAtom proj = { tag, size - 8 };
7794 int ret = mov_read_vexu_proj(c, pb, proj);
7795 if (ret < 0)
7796 return ret;
7797 break;
7798 }
7799 case MKTAG('e','y','e','s'): {
7800 MOVAtom eyes = { tag, size - 8 };
7801 int ret = mov_read_eyes(c, pb, eyes);
7802 if (ret < 0)
7803 return ret;
7804 break;
7805 }
7806 case MKTAG('p','a','c','k'): {
7807 MOVAtom pack = { tag, size - 8 };
7808 int ret = mov_read_pack(c, pb, pack);
7809 if (ret < 0)
7810 return ret;
7811 break;
7812 }
7813 default:
7814 av_log(c->fc, AV_LOG_WARNING, "Unknown tag in vexu: %s\n",
7816 avio_skip(pb, size - 8);
7817 break;
7818 }
7819 remaining -= size;
7820 }
7821
7822 if (remaining != 0) {
7823 av_log(c->fc, AV_LOG_ERROR, "Broken vexu box\n");
7824 return AVERROR_INVALIDDATA;
7825 }
7826
7827 return 0;
7828}
7829
7831{
7832 AVStream *st;
7833 MOVStreamContext *sc;
7834
7835 if (c->fc->nb_streams < 1)
7836 return 0;
7837
7838 st = c->fc->streams[c->fc->nb_streams - 1];
7839 sc = st->priv_data;
7840
7841 if (atom.size != 4) {
7842 av_log(c->fc, AV_LOG_ERROR, "Invalid size of hfov box: %"PRIu64"\n", atom.size);
7843 return AVERROR_INVALIDDATA;
7844 }
7845
7846
7847 if (!sc->stereo3d) {
7849 if (!sc->stereo3d)
7850 return AVERROR(ENOMEM);
7851 }
7852
7854 sc->stereo3d->horizontal_field_of_view.den = 1000; // thousands of a degree
7855
7856 return 0;
7857}
7858
7860{
7861 int ret = 0;
7862 uint8_t *buffer = av_malloc(len + 1);
7863 const char *val;
7864
7865 if (!buffer)
7866 return AVERROR(ENOMEM);
7867 buffer[len] = '\0';
7868
7869 ret = ffio_read_size(pb, buffer, len);
7870 if (ret < 0)
7871 goto out;
7872
7873 /* Check for mandatory keys and values, try to support XML as best-effort */
7874 if (!sc->spherical &&
7875 av_stristr(buffer, "<GSpherical:StitchingSoftware>") &&
7876 (val = av_stristr(buffer, "<GSpherical:Spherical>")) &&
7877 av_stristr(val, "true") &&
7878 (val = av_stristr(buffer, "<GSpherical:Stitched>")) &&
7879 av_stristr(val, "true") &&
7880 (val = av_stristr(buffer, "<GSpherical:ProjectionType>")) &&
7881 av_stristr(val, "equirectangular")) {
7883 if (!sc->spherical)
7884 goto out;
7885
7887
7888 if (av_stristr(buffer, "<GSpherical:StereoMode>") && !sc->stereo3d) {
7889 enum AVStereo3DType mode;
7890
7891 if (av_stristr(buffer, "left-right"))
7893 else if (av_stristr(buffer, "top-bottom"))
7895 else
7897
7899 if (!sc->stereo3d)
7900 goto out;
7901
7902 sc->stereo3d->type = mode;
7903 }
7904
7905 /* orientation */
7906 val = av_stristr(buffer, "<GSpherical:InitialViewHeadingDegrees>");
7907 if (val)
7908 sc->spherical->yaw = strtol(val, NULL, 10) * (1 << 16);
7909 val = av_stristr(buffer, "<GSpherical:InitialViewPitchDegrees>");
7910 if (val)
7911 sc->spherical->pitch = strtol(val, NULL, 10) * (1 << 16);
7912 val = av_stristr(buffer, "<GSpherical:InitialViewRollDegrees>");
7913 if (val)
7914 sc->spherical->roll = strtol(val, NULL, 10) * (1 << 16);
7915 }
7916
7917out:
7918 av_free(buffer);
7919 return ret;
7920}
7921
7923{
7924 AVStream *st;
7925 MOVStreamContext *sc;
7926 int64_t ret;
7927 AVUUID uuid;
7928 static const AVUUID uuid_isml_manifest = {
7929 0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd,
7930 0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66
7931 };
7932 static const AVUUID uuid_xmp = {
7933 0xbe, 0x7a, 0xcf, 0xcb, 0x97, 0xa9, 0x42, 0xe8,
7934 0x9c, 0x71, 0x99, 0x94, 0x91, 0xe3, 0xaf, 0xac
7935 };
7936 static const AVUUID uuid_spherical = {
7937 0xff, 0xcc, 0x82, 0x63, 0xf8, 0x55, 0x4a, 0x93,
7938 0x88, 0x14, 0x58, 0x7a, 0x02, 0x52, 0x1f, 0xdd,
7939 };
7940
7941 if (atom.size < AV_UUID_LEN || atom.size >= FFMIN(INT_MAX, SIZE_MAX))
7942 return AVERROR_INVALIDDATA;
7943
7944 if (c->fc->nb_streams < 1)
7945 return 0;
7946 st = c->fc->streams[c->fc->nb_streams - 1];
7947 sc = st->priv_data;
7948
7949 ret = ffio_read_size(pb, uuid, AV_UUID_LEN);
7950 if (ret < 0)
7951 return ret;
7952 if (av_uuid_equal(uuid, uuid_isml_manifest)) {
7953 uint8_t *buffer, *ptr;
7954 char *endptr;
7955 size_t len = atom.size - AV_UUID_LEN;
7956
7957 if (len < 4) {
7958 return AVERROR_INVALIDDATA;
7959 }
7960 ret = avio_skip(pb, 4); // zeroes
7961 len -= 4;
7962
7963 buffer = av_mallocz(len + 1);
7964 if (!buffer) {
7965 return AVERROR(ENOMEM);
7966 }
7967 ret = ffio_read_size(pb, buffer, len);
7968 if (ret < 0) {
7969 av_free(buffer);
7970 return ret;
7971 }
7972
7973 ptr = buffer;
7974 while ((ptr = av_stristr(ptr, "systemBitrate=\""))) {
7975 ptr += sizeof("systemBitrate=\"") - 1;
7976 c->bitrates_count++;
7977 c->bitrates = av_realloc_f(c->bitrates, c->bitrates_count, sizeof(*c->bitrates));
7978 if (!c->bitrates) {
7979 c->bitrates_count = 0;
7980 av_free(buffer);
7981 return AVERROR(ENOMEM);
7982 }
7983 errno = 0;
7984 ret = strtol(ptr, &endptr, 10);
7985 if (ret < 0 || errno || *endptr != '"') {
7986 c->bitrates[c->bitrates_count - 1] = 0;
7987 } else {
7988 c->bitrates[c->bitrates_count - 1] = ret;
7989 }
7990 }
7991
7992 av_free(buffer);
7993 } else if (av_uuid_equal(uuid, uuid_xmp)) {
7994 uint8_t *buffer;
7995 size_t len = atom.size - AV_UUID_LEN;
7996 if (c->export_xmp) {
7997 buffer = av_mallocz(len + 1);
7998 if (!buffer) {
7999 return AVERROR(ENOMEM);
8000 }
8001 ret = ffio_read_size(pb, buffer, len);
8002 if (ret < 0) {
8003 av_free(buffer);
8004 return ret;
8005 }
8006 buffer[len] = '\0';
8007 av_dict_set(&c->fc->metadata, "xmp",
8009 } else {
8010 // skip all uuid atom, which makes it fast for long uuid-xmp file
8011 ret = avio_skip(pb, len);
8012 if (ret < 0)
8013 return ret;
8014 }
8015 } else if (av_uuid_equal(uuid, uuid_spherical)) {
8016 size_t len = atom.size - AV_UUID_LEN;
8017 ret = mov_parse_uuid_spherical(sc, pb, len);
8018 if (ret < 0)
8019 return ret;
8020 if (!sc->spherical)
8021 av_log(c->fc, AV_LOG_WARNING, "Invalid spherical metadata found\n");
8022 }
8023
8024 return 0;
8025}
8026
8028{
8029 int ret;
8030 uint8_t content[16];
8031
8032 if (atom.size < 8)
8033 return 0;
8034
8035 ret = ffio_read_size(pb, content, FFMIN(sizeof(content), atom.size));
8036 if (ret < 0)
8037 return ret;
8038
8039 if ( !c->found_moov
8040 && !c->found_mdat
8041 && !memcmp(content, "Anevia\x1A\x1A", 8)
8042 && c->use_mfra_for == FF_MOV_FLAG_MFRA_AUTO) {
8043 c->use_mfra_for = FF_MOV_FLAG_MFRA_PTS;
8044 }
8045
8046 return 0;
8047}
8048
8050{
8051 uint32_t format = avio_rl32(pb);
8052 MOVStreamContext *sc;
8053 enum AVCodecID id;
8054 AVStream *st;
8055
8056 st = get_curr_st(c);
8057 if (!st)
8058 return 0;
8059 sc = st->priv_data;
8060
8061 switch (sc->format)
8062 {
8063 case MKTAG('e','n','c','v'): // encrypted video
8064 case MKTAG('e','n','c','a'): // encrypted audio
8065 id = mov_codec_id(st, format);
8066 if (st->codecpar->codec_id != AV_CODEC_ID_NONE &&
8067 st->codecpar->codec_id != id) {
8068 av_log(c->fc, AV_LOG_WARNING,
8069 "ignoring 'frma' atom of '%.4s', stream has codec id %d\n",
8070 (char*)&format, st->codecpar->codec_id);
8071 break;
8072 }
8073
8074 st->codecpar->codec_id = id;
8075 sc->format = format;
8076 break;
8077
8078 default:
8079 if (format != sc->format) {
8080 av_log(c->fc, AV_LOG_WARNING,
8081 "ignoring 'frma' atom of '%.4s', stream format is '%.4s'\n",
8082 (char*)&format, (char*)&sc->format);
8083 }
8084 break;
8085 }
8086
8087 return 0;
8088}
8089
8090/**
8091 * Gets the current encryption info and associated current stream context. If
8092 * we are parsing a track fragment, this will return the specific encryption
8093 * info for this fragment; otherwise this will return the global encryption
8094 * info for the current stream.
8095 */
8097{
8098 MOVFragmentStreamInfo *frag_stream_info;
8099 AVStream *st;
8100 int i;
8101
8102 frag_stream_info = get_current_frag_stream_info(&c->frag_index);
8103 if (frag_stream_info) {
8104 for (i = 0; i < c->fc->nb_streams; i++) {
8105 *sc = c->fc->streams[i]->priv_data;
8106 if ((*sc)->id == frag_stream_info->id) {
8107 st = c->fc->streams[i];
8108 break;
8109 }
8110 }
8111 if (i == c->fc->nb_streams)
8112 return 0;
8113 *sc = st->priv_data;
8114
8115 if (!frag_stream_info->encryption_index) {
8116 // If this stream isn't encrypted, don't create the index.
8117 if (!(*sc)->cenc.default_encrypted_sample)
8118 return 0;
8119 frag_stream_info->encryption_index = av_mallocz(sizeof(*frag_stream_info->encryption_index));
8120 if (!frag_stream_info->encryption_index)
8121 return AVERROR(ENOMEM);
8122 }
8123 *encryption_index = frag_stream_info->encryption_index;
8124 return 1;
8125 } else {
8126 // No current track fragment, using stream level encryption info.
8127
8128 if (c->fc->nb_streams < 1)
8129 return 0;
8130 st = c->fc->streams[c->fc->nb_streams - 1];
8131 *sc = st->priv_data;
8132
8133 if (!(*sc)->cenc.encryption_index) {
8134 // If this stream isn't encrypted, don't create the index.
8135 if (!(*sc)->cenc.default_encrypted_sample)
8136 return 0;
8137 (*sc)->cenc.encryption_index = av_mallocz(sizeof(*frag_stream_info->encryption_index));
8138 if (!(*sc)->cenc.encryption_index)
8139 return AVERROR(ENOMEM);
8140 }
8141
8142 *encryption_index = (*sc)->cenc.encryption_index;
8143 return 1;
8144 }
8145}
8146
8148{
8149 int i, ret;
8150 unsigned int subsample_count;
8151 AVSubsampleEncryptionInfo *subsamples;
8152
8153 if (!sc->cenc.default_encrypted_sample) {
8154 av_log(c->fc, AV_LOG_ERROR, "Missing schm or tenc\n");
8155 return AVERROR_INVALIDDATA;
8156 }
8157
8158 if (sc->cenc.per_sample_iv_size || use_subsamples) {
8160 if (!*sample)
8161 return AVERROR(ENOMEM);
8162 } else
8163 *sample = NULL;
8164
8165 if (sc->cenc.per_sample_iv_size != 0) {
8166 if ((ret = ffio_read_size(pb, (*sample)->iv, sc->cenc.per_sample_iv_size)) < 0) {
8167 av_log(c->fc, AV_LOG_ERROR, "failed to read the initialization vector\n");
8169 *sample = NULL;
8170 return ret;
8171 }
8172 }
8173
8174 if (use_subsamples) {
8175 subsample_count = avio_rb16(pb);
8176 av_free((*sample)->subsamples);
8177 (*sample)->subsamples = av_calloc(subsample_count, sizeof(*subsamples));
8178 if (!(*sample)->subsamples) {
8180 *sample = NULL;
8181 return AVERROR(ENOMEM);
8182 }
8183
8184 for (i = 0; i < subsample_count && !pb->eof_reached; i++) {
8185 (*sample)->subsamples[i].bytes_of_clear_data = avio_rb16(pb);
8186 (*sample)->subsamples[i].bytes_of_protected_data = avio_rb32(pb);
8187 }
8188
8189 if (pb->eof_reached) {
8190 av_log(c->fc, AV_LOG_ERROR, "hit EOF while reading sub-sample encryption info\n");
8192 *sample = NULL;
8193 return AVERROR_INVALIDDATA;
8194 }
8195 (*sample)->subsample_count = subsample_count;
8196 }
8197
8198 return 0;
8199}
8200
8202{
8203 AVEncryptionInfo **encrypted_samples;
8204 MOVEncryptionIndex *encryption_index;
8205 MOVStreamContext *sc;
8206 int use_subsamples, ret;
8207 unsigned int sample_count, i, alloc_size = 0;
8208
8209 ret = get_current_encryption_info(c, &encryption_index, &sc);
8210 if (ret != 1)
8211 return ret;
8212
8213 if (encryption_index->nb_encrypted_samples) {
8214 // This can happen if we have both saio/saiz and senc atoms.
8215 av_log(c->fc, AV_LOG_DEBUG, "Ignoring duplicate encryption info in senc\n");
8216 return 0;
8217 }
8218
8219 avio_r8(pb); /* version */
8220 use_subsamples = avio_rb24(pb) & 0x02; /* flags */
8221
8222 sample_count = avio_rb32(pb);
8223 if (sample_count >= INT_MAX / sizeof(*encrypted_samples))
8224 return AVERROR(ENOMEM);
8225
8226 for (i = 0; i < sample_count; i++) {
8227 unsigned int min_samples = FFMIN(FFMAX(i + 1, 1024 * 1024), sample_count);
8228 encrypted_samples = av_fast_realloc(encryption_index->encrypted_samples, &alloc_size,
8229 min_samples * sizeof(*encrypted_samples));
8230 if (encrypted_samples) {
8231 encryption_index->encrypted_samples = encrypted_samples;
8232
8234 c, pb, sc, &encryption_index->encrypted_samples[i], use_subsamples);
8235 } else {
8236 ret = AVERROR(ENOMEM);
8237 }
8238 if (pb->eof_reached) {
8239 av_log(c->fc, AV_LOG_ERROR, "Hit EOF while reading senc\n");
8240 if (ret >= 0)
8241 av_encryption_info_free(encryption_index->encrypted_samples[i]);
8243 }
8244
8245 if (ret < 0) {
8246 for (; i > 0; i--)
8247 av_encryption_info_free(encryption_index->encrypted_samples[i - 1]);
8248 av_freep(&encryption_index->encrypted_samples);
8249 return ret;
8250 }
8251 }
8252 encryption_index->nb_encrypted_samples = sample_count;
8253
8254 return 0;
8255}
8256
8258{
8259 AVEncryptionInfo **sample, **encrypted_samples;
8260 int64_t prev_pos;
8261 size_t sample_count, sample_info_size, i;
8262 int ret = 0;
8263 unsigned int alloc_size = 0;
8264
8265 if (encryption_index->nb_encrypted_samples)
8266 return 0;
8267 sample_count = encryption_index->auxiliary_info_sample_count;
8268 if (encryption_index->auxiliary_offsets_count != 1) {
8269 av_log(c->fc, AV_LOG_ERROR, "Multiple auxiliary info chunks are not supported\n");
8270 return AVERROR_PATCHWELCOME;
8271 }
8272 if (sample_count >= INT_MAX / sizeof(*encrypted_samples))
8273 return AVERROR(ENOMEM);
8274
8275 prev_pos = avio_tell(pb);
8276 if (!(pb->seekable & AVIO_SEEKABLE_NORMAL) ||
8277 avio_seek(pb, encryption_index->auxiliary_offsets[0], SEEK_SET) != encryption_index->auxiliary_offsets[0]) {
8278 av_log(c->fc, AV_LOG_INFO, "Failed to seek for auxiliary info, will only parse senc atoms for encryption info\n");
8279 goto finish;
8280 }
8281
8282 for (i = 0; i < sample_count && !pb->eof_reached; i++) {
8283 unsigned int min_samples = FFMIN(FFMAX(i + 1, 1024 * 1024), sample_count);
8284 encrypted_samples = av_fast_realloc(encryption_index->encrypted_samples, &alloc_size,
8285 min_samples * sizeof(*encrypted_samples));
8286 if (!encrypted_samples) {
8287 ret = AVERROR(ENOMEM);
8288 goto finish;
8289 }
8290 encryption_index->encrypted_samples = encrypted_samples;
8291
8292 sample = &encryption_index->encrypted_samples[i];
8293 sample_info_size = encryption_index->auxiliary_info_default_size
8294 ? encryption_index->auxiliary_info_default_size
8295 : encryption_index->auxiliary_info_sizes[i];
8296
8297 ret = mov_read_sample_encryption_info(c, pb, sc, sample, sample_info_size > sc->cenc.per_sample_iv_size);
8298 if (ret < 0)
8299 goto finish;
8300 }
8301 if (pb->eof_reached) {
8302 av_log(c->fc, AV_LOG_ERROR, "Hit EOF while reading auxiliary info\n");
8304 } else {
8305 encryption_index->nb_encrypted_samples = sample_count;
8306 }
8307
8308finish:
8309 avio_seek(pb, prev_pos, SEEK_SET);
8310 if (ret < 0) {
8311 for (; i > 0; i--) {
8312 av_encryption_info_free(encryption_index->encrypted_samples[i - 1]);
8313 }
8314 av_freep(&encryption_index->encrypted_samples);
8315 }
8316 return ret;
8317}
8318
8320{
8321 MOVEncryptionIndex *encryption_index;
8322 MOVStreamContext *sc;
8323 int ret;
8324 unsigned int sample_count, aux_info_type, aux_info_param;
8325
8326 ret = get_current_encryption_info(c, &encryption_index, &sc);
8327 if (ret != 1)
8328 return ret;
8329
8330 if (encryption_index->nb_encrypted_samples) {
8331 // This can happen if we have both saio/saiz and senc atoms.
8332 av_log(c->fc, AV_LOG_DEBUG, "Ignoring duplicate encryption info in saiz\n");
8333 return 0;
8334 }
8335
8336 if (encryption_index->auxiliary_info_sample_count) {
8337 av_log(c->fc, AV_LOG_ERROR, "Duplicate saiz atom\n");
8338 return AVERROR_INVALIDDATA;
8339 }
8340
8341 avio_r8(pb); /* version */
8342 if (avio_rb24(pb) & 0x01) { /* flags */
8343 aux_info_type = avio_rb32(pb);
8344 aux_info_param = avio_rb32(pb);
8346 if (aux_info_type != sc->cenc.default_encrypted_sample->scheme) {
8347 av_log(c->fc, AV_LOG_DEBUG, "Ignoring saiz box with non-zero aux_info_type\n");
8348 return 0;
8349 }
8350 if (aux_info_param != 0) {
8351 av_log(c->fc, AV_LOG_DEBUG, "Ignoring saiz box with non-zero aux_info_type_parameter\n");
8352 return 0;
8353 }
8354 } else {
8355 // Didn't see 'schm' or 'tenc', so this isn't encrypted.
8356 if ((aux_info_type == MKBETAG('c','e','n','c') ||
8357 aux_info_type == MKBETAG('c','e','n','s') ||
8358 aux_info_type == MKBETAG('c','b','c','1') ||
8359 aux_info_type == MKBETAG('c','b','c','s')) &&
8360 aux_info_param == 0) {
8361 av_log(c->fc, AV_LOG_ERROR, "Saw encrypted saiz without schm/tenc\n");
8362 return AVERROR_INVALIDDATA;
8363 } else {
8364 return 0;
8365 }
8366 }
8367 } else if (!sc->cenc.default_encrypted_sample) {
8368 // Didn't see 'schm' or 'tenc', so this isn't encrypted.
8369 return 0;
8370 }
8371
8372 encryption_index->auxiliary_info_default_size = avio_r8(pb);
8373 sample_count = avio_rb32(pb);
8374
8375 if (encryption_index->auxiliary_info_default_size == 0) {
8376 if (sample_count == 0)
8377 return AVERROR_INVALIDDATA;
8378
8379 encryption_index->auxiliary_info_sizes = av_malloc(sample_count);
8380 if (!encryption_index->auxiliary_info_sizes)
8381 return AVERROR(ENOMEM);
8382
8383 ret = avio_read(pb, encryption_index->auxiliary_info_sizes, sample_count);
8384 if (ret != sample_count) {
8385 av_freep(&encryption_index->auxiliary_info_sizes);
8386
8387 if (ret >= 0)
8389 av_log(c->fc, AV_LOG_ERROR, "Failed to read the auxiliary info, %s\n",
8390 av_err2str(ret));
8391 return ret;
8392 }
8393 }
8394 encryption_index->auxiliary_info_sample_count = sample_count;
8395
8396 if (encryption_index->auxiliary_offsets_count) {
8397 return mov_parse_auxiliary_info(c, sc, pb, encryption_index);
8398 }
8399
8400 return 0;
8401}
8402
8404{
8405 uint64_t *auxiliary_offsets;
8406 MOVEncryptionIndex *encryption_index;
8407 MOVStreamContext *sc;
8408 int i, ret;
8409 unsigned int version, entry_count, aux_info_type, aux_info_param;
8410 unsigned int alloc_size = 0;
8411
8412 ret = get_current_encryption_info(c, &encryption_index, &sc);
8413 if (ret != 1)
8414 return ret;
8415
8416 if (encryption_index->nb_encrypted_samples) {
8417 // This can happen if we have both saio/saiz and senc atoms.
8418 av_log(c->fc, AV_LOG_DEBUG, "Ignoring duplicate encryption info in saio\n");
8419 return 0;
8420 }
8421
8422 if (encryption_index->auxiliary_offsets_count) {
8423 av_log(c->fc, AV_LOG_ERROR, "Duplicate saio atom\n");
8424 return AVERROR_INVALIDDATA;
8425 }
8426
8427 version = avio_r8(pb); /* version */
8428 if (avio_rb24(pb) & 0x01) { /* flags */
8429 aux_info_type = avio_rb32(pb);
8430 aux_info_param = avio_rb32(pb);
8432 if (aux_info_type != sc->cenc.default_encrypted_sample->scheme) {
8433 av_log(c->fc, AV_LOG_DEBUG, "Ignoring saio box with non-zero aux_info_type\n");
8434 return 0;
8435 }
8436 if (aux_info_param != 0) {
8437 av_log(c->fc, AV_LOG_DEBUG, "Ignoring saio box with non-zero aux_info_type_parameter\n");
8438 return 0;
8439 }
8440 } else {
8441 // Didn't see 'schm' or 'tenc', so this isn't encrypted.
8442 if ((aux_info_type == MKBETAG('c','e','n','c') ||
8443 aux_info_type == MKBETAG('c','e','n','s') ||
8444 aux_info_type == MKBETAG('c','b','c','1') ||
8445 aux_info_type == MKBETAG('c','b','c','s')) &&
8446 aux_info_param == 0) {
8447 av_log(c->fc, AV_LOG_ERROR, "Saw encrypted saio without schm/tenc\n");
8448 return AVERROR_INVALIDDATA;
8449 } else {
8450 return 0;
8451 }
8452 }
8453 } else if (!sc->cenc.default_encrypted_sample) {
8454 // Didn't see 'schm' or 'tenc', so this isn't encrypted.
8455 return 0;
8456 }
8457
8458 entry_count = avio_rb32(pb);
8459 if (entry_count >= INT_MAX / sizeof(*auxiliary_offsets))
8460 return AVERROR(ENOMEM);
8461
8462 for (i = 0; i < entry_count && !pb->eof_reached; i++) {
8463 unsigned int min_offsets = FFMIN(FFMAX(i + 1, 1024), entry_count);
8464 auxiliary_offsets = av_fast_realloc(
8465 encryption_index->auxiliary_offsets, &alloc_size,
8466 min_offsets * sizeof(*auxiliary_offsets));
8467 if (!auxiliary_offsets) {
8468 av_freep(&encryption_index->auxiliary_offsets);
8469 return AVERROR(ENOMEM);
8470 }
8471 encryption_index->auxiliary_offsets = auxiliary_offsets;
8472
8473 if (version == 0) {
8474 encryption_index->auxiliary_offsets[i] = avio_rb32(pb);
8475 } else {
8476 encryption_index->auxiliary_offsets[i] = avio_rb64(pb);
8477 }
8478 if (c->frag_index.current >= 0) {
8479 encryption_index->auxiliary_offsets[i] += c->fragment.base_data_offset;
8480 }
8481 }
8482
8483 if (pb->eof_reached) {
8484 av_log(c->fc, AV_LOG_ERROR, "Hit EOF while reading saio\n");
8485 av_freep(&encryption_index->auxiliary_offsets);
8486 return AVERROR_INVALIDDATA;
8487 }
8488
8489 encryption_index->auxiliary_offsets_count = entry_count;
8490
8491 if (encryption_index->auxiliary_info_sample_count) {
8492 return mov_parse_auxiliary_info(c, sc, pb, encryption_index);
8493 }
8494
8495 return 0;
8496}
8497
8499{
8501 uint8_t **key_ids;
8502 AVStream *st;
8503 AVPacketSideData *old_side_data = NULL;
8504 uint8_t *side_data = NULL, *extra_data;
8505 size_t side_data_size = 0;
8506 int ret = 0;
8507 unsigned int version, kid_count, extra_data_size, alloc_size = 0;
8508
8509 if (c->fc->nb_streams < 1)
8510 return 0;
8511 st = c->fc->streams[c->fc->nb_streams-1];
8512
8513 version = avio_r8(pb); /* version */
8514 avio_rb24(pb); /* flags */
8515
8516 info = av_encryption_init_info_alloc(/* system_id_size */ 16, /* num_key_ids */ 0,
8517 /* key_id_size */ 16, /* data_size */ 0);
8518 if (!info)
8519 return AVERROR(ENOMEM);
8520
8521 if ((ret = ffio_read_size(pb, info->system_id, 16)) < 0) {
8522 av_log(c->fc, AV_LOG_ERROR, "Failed to read the system id\n");
8523 goto finish;
8524 }
8525
8526 if (version > 0) {
8527 kid_count = avio_rb32(pb);
8528 if (kid_count >= INT_MAX / sizeof(*key_ids)) {
8529 ret = AVERROR(ENOMEM);
8530 goto finish;
8531 }
8532
8533 for (unsigned int i = 0; i < kid_count && !pb->eof_reached; i++) {
8534 unsigned int min_kid_count = FFMIN(FFMAX(i + 1, 1024), kid_count);
8535 key_ids = av_fast_realloc(info->key_ids, &alloc_size,
8536 min_kid_count * sizeof(*key_ids));
8537 if (!key_ids) {
8538 ret = AVERROR(ENOMEM);
8539 goto finish;
8540 }
8541 info->key_ids = key_ids;
8542
8543 info->key_ids[i] = av_mallocz(16);
8544 if (!info->key_ids[i]) {
8545 ret = AVERROR(ENOMEM);
8546 goto finish;
8547 }
8548 info->num_key_ids = i + 1;
8549
8550 if ((ret = ffio_read_size(pb, info->key_ids[i], 16)) < 0) {
8551 av_log(c->fc, AV_LOG_ERROR, "Failed to read the key id\n");
8552 goto finish;
8553 }
8554 }
8555
8556 if (pb->eof_reached) {
8557 av_log(c->fc, AV_LOG_ERROR, "Hit EOF while reading pssh\n");
8559 goto finish;
8560 }
8561 }
8562
8563 extra_data_size = avio_rb32(pb);
8564 extra_data = av_malloc(extra_data_size);
8565 if (!extra_data) {
8566 ret = AVERROR(ENOMEM);
8567 goto finish;
8568 }
8569 ret = avio_read(pb, extra_data, extra_data_size);
8570 if (ret != extra_data_size) {
8571 av_free(extra_data);
8572
8573 if (ret >= 0)
8575 goto finish;
8576 }
8577
8578 av_freep(&info->data); // malloc(0) may still allocate something.
8579 info->data = extra_data;
8580 info->data_size = extra_data_size;
8581
8582 for (int i = 0; i < st->codecpar->nb_coded_side_data; i++)
8584 old_side_data = &st->codecpar->coded_side_data[i];
8585
8586 // If there is existing initialization data, append the new record to it.
8587 if (old_side_data) {
8588 side_data = old_side_data->data;
8589 side_data_size = old_side_data->size;
8590 }
8591 if (!old_side_data || side_data != c->pssh_side_data)
8592 c->pssh_side_data_allocated = 0;
8593
8594 ret = av_encryption_init_info_append_side_data(&side_data, &side_data_size,
8595 &c->pssh_side_data_allocated, info);
8596 if (ret < 0)
8597 goto finish;
8598
8599 if (old_side_data) {
8600 old_side_data->data = side_data;
8601 old_side_data->size = side_data_size;
8605 side_data, side_data_size, 0)) {
8606 av_free(side_data);
8607 ret = AVERROR(ENOMEM);
8608 goto finish;
8609 }
8610 c->pssh_side_data = side_data;
8611
8612finish:
8614 return ret;
8615}
8616
8618{
8619 AVStream *st;
8620 MOVStreamContext *sc;
8621
8622 if (c->fc->nb_streams < 1)
8623 return 0;
8624 st = c->fc->streams[c->fc->nb_streams-1];
8625 sc = st->priv_data;
8626
8627 if (sc->pseudo_stream_id != 0) {
8628 av_log(c->fc, AV_LOG_ERROR, "schm boxes are only supported in first sample descriptor\n");
8629 return AVERROR_PATCHWELCOME;
8630 }
8631
8632 if (atom.size < 8)
8633 return AVERROR_INVALIDDATA;
8634
8635 avio_rb32(pb); /* version and flags */
8636
8637 if (!sc->cenc.default_encrypted_sample) {
8639 if (!sc->cenc.default_encrypted_sample) {
8640 return AVERROR(ENOMEM);
8641 }
8642 }
8643
8645 return 0;
8646}
8647
8649{
8650 AVStream *st;
8651 MOVStreamContext *sc;
8652 unsigned int version, pattern, is_protected, iv_size;
8653
8654 if (c->fc->nb_streams < 1)
8655 return 0;
8656 st = c->fc->streams[c->fc->nb_streams-1];
8657 sc = st->priv_data;
8658
8659 if (sc->pseudo_stream_id != 0) {
8660 av_log(c->fc, AV_LOG_ERROR, "tenc atom are only supported in first sample descriptor\n");
8661 return AVERROR_PATCHWELCOME;
8662 }
8663
8664 if (!sc->cenc.default_encrypted_sample) {
8666 if (!sc->cenc.default_encrypted_sample) {
8667 return AVERROR(ENOMEM);
8668 }
8669 }
8670
8671 if (atom.size < 20)
8672 return AVERROR_INVALIDDATA;
8673
8674 version = avio_r8(pb); /* version */
8675 avio_rb24(pb); /* flags */
8676
8677 avio_r8(pb); /* reserved */
8678 pattern = avio_r8(pb);
8679
8680 if (version > 0) {
8682 sc->cenc.default_encrypted_sample->skip_byte_block = pattern & 0xf;
8683 }
8684
8685 is_protected = avio_r8(pb);
8686 if (is_protected && !sc->cenc.encryption_index) {
8687 // The whole stream should be by-default encrypted.
8689 if (!sc->cenc.encryption_index)
8690 return AVERROR(ENOMEM);
8691 }
8692 iv_size = avio_r8(pb);
8693 if (iv_size != 0 && iv_size != 8 && iv_size != 16) {
8694 av_log(c->fc, AV_LOG_ERROR, "invalid per-sample IV size value\n");
8695 return AVERROR_INVALIDDATA;
8696 }
8697 sc->cenc.per_sample_iv_size = iv_size;
8698 if (avio_read(pb, sc->cenc.default_encrypted_sample->key_id, 16) != 16) {
8699 av_log(c->fc, AV_LOG_ERROR, "failed to read the default key ID\n");
8700 return AVERROR_INVALIDDATA;
8701 }
8702
8703 if (is_protected && !sc->cenc.per_sample_iv_size) {
8704 iv_size = avio_r8(pb);
8705 if (iv_size != 8 && iv_size != 16) {
8706 av_log(c->fc, AV_LOG_ERROR, "invalid default_constant_IV_size in tenc atom\n");
8707 return AVERROR_INVALIDDATA;
8708 }
8709
8710 if (avio_read(pb, sc->cenc.default_encrypted_sample->iv, iv_size) != iv_size) {
8711 av_log(c->fc, AV_LOG_ERROR, "failed to read the default IV\n");
8712 return AVERROR_INVALIDDATA;
8713 }
8714 }
8715
8716 return 0;
8717}
8718
8720{
8721 AVStream *st;
8722 int last, type, size, ret;
8723 uint8_t buf[4];
8724
8725 if (c->fc->nb_streams < 1)
8726 return 0;
8727 st = c->fc->streams[c->fc->nb_streams-1];
8728
8729 if ((uint64_t)atom.size > (1<<30) || atom.size < 42)
8730 return AVERROR_INVALIDDATA;
8731
8732 /* Check FlacSpecificBox version. */
8733 if (avio_r8(pb) != 0)
8734 return AVERROR_INVALIDDATA;
8735
8736 avio_rb24(pb); /* Flags */
8737
8738 if (avio_read(pb, buf, sizeof(buf)) != sizeof(buf)) {
8739 av_log(c->fc, AV_LOG_ERROR, "failed to read FLAC metadata block header\n");
8740 return pb->error < 0 ? pb->error : AVERROR_INVALIDDATA;
8741 }
8742 flac_parse_block_header(buf, &last, &type, &size);
8743
8745 av_log(c->fc, AV_LOG_ERROR, "STREAMINFO must be first FLACMetadataBlock\n");
8746 return AVERROR_INVALIDDATA;
8747 }
8748
8749 ret = ff_get_extradata(c->fc, st->codecpar, pb, size);
8750 if (ret < 0)
8751 return ret;
8752
8753 if (!last)
8754 av_log(c->fc, AV_LOG_WARNING, "non-STREAMINFO FLACMetadataBlock(s) ignored\n");
8755
8756 return 0;
8757}
8758
8760 AVDictionaryEntry *key_entry_hex;
8761 char kid_hex[16*2+1];
8762
8763 if (c->decryption_default_key && c->decryption_default_key_len != len) {
8764 av_log(c->fc, AV_LOG_ERROR, "invalid default decryption key length: got %d, expected %d\n", c->decryption_default_key_len, len);
8765 return -1;
8766 }
8767
8768 if (!c->decryption_keys) {
8769 av_assert0(c->decryption_default_key);
8770 memcpy(out, c->decryption_default_key, len);
8771 return 0;
8772 }
8773
8774 if (sample->key_id_size != 16) {
8775 av_log(c->fc, AV_LOG_ERROR, "invalid key ID size: got %u, expected 16\n", sample->key_id_size);
8776 return -1;
8777 }
8778
8779 ff_data_to_hex(kid_hex, sample->key_id, 16, 1);
8780 key_entry_hex = av_dict_get(c->decryption_keys, kid_hex, NULL, AV_DICT_DONT_STRDUP_KEY|AV_DICT_DONT_STRDUP_VAL);
8781 if (!key_entry_hex) {
8782 if (!c->decryption_default_key) {
8783 av_log(c->fc, AV_LOG_ERROR, "unable to find KID %s\n", kid_hex);
8784 return -1;
8785 }
8786 memcpy(out, c->decryption_default_key, len);
8787 return 0;
8788 }
8789 if (strlen(key_entry_hex->value) != len*2) {
8790 return -1;
8791 }
8792 ff_hex_to_data(out, key_entry_hex->value);
8793 return 0;
8794}
8795
8797{
8798 int i, ret;
8799 int bytes_of_protected_data;
8800 uint8_t decryption_key[AES_CTR_KEY_SIZE];
8801
8802 if (!sc->cenc.aes_ctr) {
8803 ret = get_key_from_kid(decryption_key, sizeof(decryption_key), c, sample);
8804 if (ret < 0) {
8805 return ret;
8806 }
8807
8808 /* initialize the cipher */
8810 if (!sc->cenc.aes_ctr) {
8811 return AVERROR(ENOMEM);
8812 }
8813
8814 ret = av_aes_ctr_init(sc->cenc.aes_ctr, decryption_key);
8815 if (ret < 0) {
8816 return ret;
8817 }
8818 }
8819
8821
8822 if (!sample->subsample_count) {
8823 /* decrypt the whole packet */
8824 av_aes_ctr_crypt(sc->cenc.aes_ctr, input, input, size);
8825 return 0;
8826 }
8827
8828 for (i = 0; i < sample->subsample_count; i++) {
8829 if (sample->subsamples[i].bytes_of_clear_data + (int64_t)sample->subsamples[i].bytes_of_protected_data > size) {
8830 av_log(c->fc, AV_LOG_ERROR, "subsample size exceeds the packet size left\n");
8831 return AVERROR_INVALIDDATA;
8832 }
8833
8834 /* skip the clear bytes */
8835 input += sample->subsamples[i].bytes_of_clear_data;
8836 size -= sample->subsamples[i].bytes_of_clear_data;
8837
8838 /* decrypt the encrypted bytes */
8839
8840 bytes_of_protected_data = sample->subsamples[i].bytes_of_protected_data;
8841 av_aes_ctr_crypt(sc->cenc.aes_ctr, input, input, bytes_of_protected_data);
8842
8843 input += bytes_of_protected_data;
8844 size -= bytes_of_protected_data;
8845 }
8846
8847 if (size > 0) {
8848 av_log(c->fc, AV_LOG_ERROR, "leftover packet bytes after subsample processing\n");
8849 return AVERROR_INVALIDDATA;
8850 }
8851
8852 return 0;
8853}
8854
8856{
8857 int i, ret;
8858 int num_of_encrypted_blocks;
8859 uint8_t iv[16];
8860 uint8_t decryption_key[16];
8861
8862 if (!sc->cenc.aes_ctx) {
8863 ret = get_key_from_kid(decryption_key, sizeof(decryption_key), c, sample);
8864 if (ret < 0) {
8865 return ret;
8866 }
8867
8868 /* initialize the cipher */
8869 sc->cenc.aes_ctx = av_aes_alloc();
8870 if (!sc->cenc.aes_ctx) {
8871 return AVERROR(ENOMEM);
8872 }
8873
8874 ret = av_aes_init(sc->cenc.aes_ctx, decryption_key, 16 * 8, 1);
8875 if (ret < 0) {
8876 return ret;
8877 }
8878 }
8879
8880 memcpy(iv, sample->iv, 16);
8881
8882 /* whole-block full sample encryption */
8883 if (!sample->subsample_count) {
8884 /* decrypt the whole packet */
8885 av_aes_crypt(sc->cenc.aes_ctx, input, input, size/16, iv, 1);
8886 return 0;
8887 }
8888
8889 for (i = 0; i < sample->subsample_count; i++) {
8890 if (sample->subsamples[i].bytes_of_clear_data + (int64_t)sample->subsamples[i].bytes_of_protected_data > size) {
8891 av_log(c->fc, AV_LOG_ERROR, "subsample size exceeds the packet size left\n");
8892 return AVERROR_INVALIDDATA;
8893 }
8894
8895 if (sample->subsamples[i].bytes_of_protected_data % 16) {
8896 av_log(c->fc, AV_LOG_ERROR, "subsample BytesOfProtectedData is not a multiple of 16\n");
8897 return AVERROR_INVALIDDATA;
8898 }
8899
8900 /* skip the clear bytes */
8901 input += sample->subsamples[i].bytes_of_clear_data;
8902 size -= sample->subsamples[i].bytes_of_clear_data;
8903
8904 /* decrypt the encrypted bytes */
8905 num_of_encrypted_blocks = sample->subsamples[i].bytes_of_protected_data/16;
8906 if (num_of_encrypted_blocks > 0) {
8907 av_aes_crypt(sc->cenc.aes_ctx, input, input, num_of_encrypted_blocks, iv, 1);
8908 }
8909 input += sample->subsamples[i].bytes_of_protected_data;
8910 size -= sample->subsamples[i].bytes_of_protected_data;
8911 }
8912
8913 if (size > 0) {
8914 av_log(c->fc, AV_LOG_ERROR, "leftover packet bytes after subsample processing\n");
8915 return AVERROR_INVALIDDATA;
8916 }
8917
8918 return 0;
8919}
8920
8922{
8923 int i, ret, rem_bytes;
8924 uint8_t *data;
8925 uint8_t decryption_key[AES_CTR_KEY_SIZE];
8926
8927 if (!sc->cenc.aes_ctr) {
8928 ret = get_key_from_kid(decryption_key, sizeof(decryption_key), c, sample);
8929 if (ret < 0) {
8930 return ret;
8931 }
8932
8933 /* initialize the cipher */
8935 if (!sc->cenc.aes_ctr) {
8936 return AVERROR(ENOMEM);
8937 }
8938
8939 ret = av_aes_ctr_init(sc->cenc.aes_ctr, decryption_key);
8940 if (ret < 0) {
8941 return ret;
8942 }
8943 }
8944
8946
8947 /* whole-block full sample encryption */
8948 if (!sample->subsample_count) {
8949 /* decrypt the whole packet */
8950 av_aes_ctr_crypt(sc->cenc.aes_ctr, input, input, size);
8951 return 0;
8952 } else if (!sample->crypt_byte_block && !sample->skip_byte_block) {
8953 av_log(c->fc, AV_LOG_ERROR, "pattern encryption is not present in 'cens' scheme\n");
8954 return AVERROR_INVALIDDATA;
8955 }
8956
8957 for (i = 0; i < sample->subsample_count; i++) {
8958 if (sample->subsamples[i].bytes_of_clear_data + (int64_t)sample->subsamples[i].bytes_of_protected_data > size) {
8959 av_log(c->fc, AV_LOG_ERROR, "subsample size exceeds the packet size left\n");
8960 return AVERROR_INVALIDDATA;
8961 }
8962
8963 /* skip the clear bytes */
8964 input += sample->subsamples[i].bytes_of_clear_data;
8965 size -= sample->subsamples[i].bytes_of_clear_data;
8966
8967 /* decrypt the encrypted bytes */
8968 data = input;
8969 rem_bytes = sample->subsamples[i].bytes_of_protected_data;
8970 while (rem_bytes > 0) {
8971 if (rem_bytes < 16*sample->crypt_byte_block) {
8972 break;
8973 }
8974 av_aes_ctr_crypt(sc->cenc.aes_ctr, data, data, 16*sample->crypt_byte_block);
8975 data += 16*sample->crypt_byte_block;
8976 rem_bytes -= 16*sample->crypt_byte_block;
8977 data += FFMIN(16*sample->skip_byte_block, rem_bytes);
8978 rem_bytes -= FFMIN(16*sample->skip_byte_block, rem_bytes);
8979 }
8980 input += sample->subsamples[i].bytes_of_protected_data;
8981 size -= sample->subsamples[i].bytes_of_protected_data;
8982 }
8983
8984 if (size > 0) {
8985 av_log(c->fc, AV_LOG_ERROR, "leftover packet bytes after subsample processing\n");
8986 return AVERROR_INVALIDDATA;
8987 }
8988
8989 return 0;
8990}
8991
8993{
8994 int i, ret, rem_bytes;
8995 uint8_t iv[16];
8996 uint8_t *data;
8997 uint8_t decryption_key[16];
8998
8999 if (!sc->cenc.aes_ctx) {
9000 ret = get_key_from_kid(decryption_key, sizeof(decryption_key), c, sample);
9001 if (ret < 0) {
9002 return ret;
9003 }
9004
9005 /* initialize the cipher */
9006 sc->cenc.aes_ctx = av_aes_alloc();
9007 if (!sc->cenc.aes_ctx) {
9008 return AVERROR(ENOMEM);
9009 }
9010
9011 ret = av_aes_init(sc->cenc.aes_ctx, decryption_key, 16 * 8, 1);
9012 if (ret < 0) {
9013 return ret;
9014 }
9015 }
9016
9017 /* whole-block full sample encryption */
9018 if (!sample->subsample_count) {
9019 /* decrypt the whole packet */
9020 memcpy(iv, sample->iv, 16);
9021 av_aes_crypt(sc->cenc.aes_ctx, input, input, size/16, iv, 1);
9022 return 0;
9023 } else if (!sample->crypt_byte_block && !sample->skip_byte_block) {
9024 av_log(c->fc, AV_LOG_ERROR, "pattern encryption is not present in 'cbcs' scheme\n");
9025 return AVERROR_INVALIDDATA;
9026 }
9027
9028 for (i = 0; i < sample->subsample_count; i++) {
9029 if (sample->subsamples[i].bytes_of_clear_data + (int64_t)sample->subsamples[i].bytes_of_protected_data > size) {
9030 av_log(c->fc, AV_LOG_ERROR, "subsample size exceeds the packet size left\n");
9031 return AVERROR_INVALIDDATA;
9032 }
9033
9034 /* skip the clear bytes */
9035 input += sample->subsamples[i].bytes_of_clear_data;
9036 size -= sample->subsamples[i].bytes_of_clear_data;
9037
9038 /* decrypt the encrypted bytes */
9039 memcpy(iv, sample->iv, 16);
9040 data = input;
9041 rem_bytes = sample->subsamples[i].bytes_of_protected_data;
9042 while (rem_bytes > 0) {
9043 if (rem_bytes < 16*sample->crypt_byte_block) {
9044 break;
9045 }
9046 av_aes_crypt(sc->cenc.aes_ctx, data, data, sample->crypt_byte_block, iv, 1);
9047 data += 16*sample->crypt_byte_block;
9048 rem_bytes -= 16*sample->crypt_byte_block;
9049 data += FFMIN(16*sample->skip_byte_block, rem_bytes);
9050 rem_bytes -= FFMIN(16*sample->skip_byte_block, rem_bytes);
9051 }
9052 input += sample->subsamples[i].bytes_of_protected_data;
9053 size -= sample->subsamples[i].bytes_of_protected_data;
9054 }
9055
9056 if (size > 0) {
9057 av_log(c->fc, AV_LOG_ERROR, "leftover packet bytes after subsample processing\n");
9058 return AVERROR_INVALIDDATA;
9059 }
9060
9061 return 0;
9062}
9063
9064static int cenc_decrypt(MOVContext *c, MOVStreamContext *sc, AVEncryptionInfo *sample, uint8_t *input, int size)
9065{
9066 if (sample->scheme == MKBETAG('c','e','n','c') && !sample->crypt_byte_block && !sample->skip_byte_block) {
9067 return cenc_scheme_decrypt(c, sc, sample, input, size);
9068 } else if (sample->scheme == MKBETAG('c','b','c','1') && !sample->crypt_byte_block && !sample->skip_byte_block) {
9069 return cbc1_scheme_decrypt(c, sc, sample, input, size);
9070 } else if (sample->scheme == MKBETAG('c','e','n','s')) {
9071 return cens_scheme_decrypt(c, sc, sample, input, size);
9072 } else if (sample->scheme == MKBETAG('c','b','c','s')) {
9073 return cbcs_scheme_decrypt(c, sc, sample, input, size);
9074 } else {
9075 av_log(c->fc, AV_LOG_ERROR, "invalid encryption scheme\n");
9076 return AVERROR_INVALIDDATA;
9077 }
9078}
9079
9081{
9082 int current = frag_index->current;
9083
9084 if (!frag_index->nb_items)
9085 return NULL;
9086
9087 // Check frag_index->current is the right one for pkt. It can out of sync.
9088 if (current >= 0 && current < frag_index->nb_items) {
9089 if (frag_index->item[current].moof_offset < pkt->pos &&
9090 (current + 1 == frag_index->nb_items ||
9091 frag_index->item[current + 1].moof_offset > pkt->pos))
9092 return get_frag_stream_info(frag_index, current, id);
9093 }
9094
9095
9096 for (int i = 0; i < frag_index->nb_items; i++) {
9097 if (frag_index->item[i].moof_offset > pkt->pos)
9098 break;
9099 current = i;
9100 }
9101 frag_index->current = current;
9102 return get_frag_stream_info(frag_index, current, id);
9103}
9104
9105static int cenc_filter(MOVContext *mov, AVStream* st, MOVStreamContext *sc, AVPacket *pkt, int current_index)
9106{
9107 MOVFragmentStreamInfo *frag_stream_info;
9108 MOVEncryptionIndex *encryption_index;
9109 AVEncryptionInfo *encrypted_sample;
9110 int encrypted_index, ret;
9111
9112 frag_stream_info = get_frag_stream_info_from_pkt(&mov->frag_index, pkt, sc->id);
9113 encrypted_index = current_index;
9114 encryption_index = NULL;
9115 if (frag_stream_info) {
9116 // Note this only supports encryption info in the first sample descriptor.
9117 if (frag_stream_info->stsd_id == 1) {
9118 if (frag_stream_info->encryption_index) {
9119 encrypted_index = current_index - frag_stream_info->index_base;
9120 encryption_index = frag_stream_info->encryption_index;
9121 } else {
9122 encryption_index = sc->cenc.encryption_index;
9123 }
9124 }
9125 } else {
9126 encryption_index = sc->cenc.encryption_index;
9127 }
9128
9129 if (encryption_index) {
9130 if (encryption_index->auxiliary_info_sample_count &&
9131 !encryption_index->nb_encrypted_samples) {
9132 av_log(mov->fc, AV_LOG_ERROR, "saiz atom found without saio\n");
9133 return AVERROR_INVALIDDATA;
9134 }
9135 if (encryption_index->auxiliary_offsets_count &&
9136 !encryption_index->nb_encrypted_samples) {
9137 av_log(mov->fc, AV_LOG_ERROR, "saio atom found without saiz\n");
9138 return AVERROR_INVALIDDATA;
9139 }
9140
9141 encrypted_sample = NULL;
9142 if (!encryption_index->nb_encrypted_samples) {
9143 // Full-sample encryption with default settings.
9144 encrypted_sample = sc->cenc.default_encrypted_sample;
9145 } else if (encrypted_index >= 0 && encrypted_index < encryption_index->nb_encrypted_samples) {
9146 // Per-sample setting override.
9147 encrypted_sample = encryption_index->encrypted_samples[encrypted_index];
9148 if (!encrypted_sample) {
9149 encrypted_sample = sc->cenc.default_encrypted_sample;
9150 }
9151 }
9152
9153 if (!encrypted_sample) {
9154 av_log(mov->fc, AV_LOG_ERROR, "Incorrect number of samples in encryption info\n");
9155 return AVERROR_INVALIDDATA;
9156 }
9157
9158 if (mov->decryption_keys || mov->decryption_default_key) {
9159 return cenc_decrypt(mov, sc, encrypted_sample, pkt->data, pkt->size);
9160 } else {
9161 size_t size;
9162 uint8_t *side_data = av_encryption_info_add_side_data(encrypted_sample, &size);
9163 if (!side_data)
9164 return AVERROR(ENOMEM);
9166 if (ret < 0)
9167 av_free(side_data);
9168 return ret;
9169 }
9170 }
9171
9172 return 0;
9173}
9174
9176{
9177 const int OPUS_SEEK_PREROLL_MS = 80;
9178 int ret;
9179 AVStream *st;
9180 size_t size;
9181 uint16_t pre_skip;
9182
9183 if (c->fc->nb_streams < 1)
9184 return 0;
9185 st = c->fc->streams[c->fc->nb_streams-1];
9186
9187 if ((uint64_t)atom.size > (1<<30) || atom.size < 11 || st->codecpar->extradata)
9188 return AVERROR_INVALIDDATA;
9189
9190 /* Check OpusSpecificBox version. */
9191 if (avio_r8(pb) != 0) {
9192 av_log(c->fc, AV_LOG_ERROR, "unsupported OpusSpecificBox version\n");
9193 return AVERROR_INVALIDDATA;
9194 }
9195
9196 /* OpusSpecificBox size plus magic for Ogg OpusHead header. */
9197 size = atom.size + 8;
9198
9199 if ((ret = ff_alloc_extradata(st->codecpar, size)) < 0)
9200 return ret;
9201
9202 AV_WL32A(st->codecpar->extradata, MKTAG('O','p','u','s'));
9203 AV_WL32A(st->codecpar->extradata + 4, MKTAG('H','e','a','d'));
9204 AV_WB8(st->codecpar->extradata + 8, 1); /* OpusHead version */
9205 if ((ret = ffio_read_size(pb, st->codecpar->extradata + 9, size - 9)) < 0) {
9207 st->codecpar->extradata_size = 0;
9208 return ret;
9209 }
9210
9211 /* OpusSpecificBox is stored in big-endian, but OpusHead is
9212 little-endian; aside from the preceding magic and version they're
9213 otherwise currently identical. Data after output gain at offset 16
9214 doesn't need to be bytewapped. */
9215 pre_skip = AV_RB16A(st->codecpar->extradata + 10);
9216 AV_WL16A(st->codecpar->extradata + 10, pre_skip);
9217 AV_WL32A(st->codecpar->extradata + 12, AV_RB32A(st->codecpar->extradata + 12));
9218 AV_WL16A(st->codecpar->extradata + 16, AV_RB16A(st->codecpar->extradata + 16));
9219
9220 st->codecpar->initial_padding = pre_skip;
9221 st->codecpar->seek_preroll =
9224
9225 return 0;
9226}
9227
9229{
9230 AVStream *st;
9231 unsigned format_info;
9232 int channel_assignment, channel_assignment1, channel_assignment2;
9233 int ratebits;
9234 uint64_t chmask;
9235
9236 if (c->fc->nb_streams < 1)
9237 return 0;
9238 st = c->fc->streams[c->fc->nb_streams-1];
9239
9240 if (atom.size < 10)
9241 return AVERROR_INVALIDDATA;
9242
9243 format_info = avio_rb32(pb);
9244
9245 ratebits = (format_info >> 28) & 0xF;
9246 channel_assignment1 = (format_info >> 15) & 0x1F;
9247 channel_assignment2 = format_info & 0x1FFF;
9248 if (channel_assignment2)
9249 channel_assignment = channel_assignment2;
9250 else
9251 channel_assignment = channel_assignment1;
9252
9253 st->codecpar->frame_size = 40 << (ratebits & 0x7);
9254 st->codecpar->sample_rate = mlp_samplerate(ratebits);
9255
9257 chmask = truehd_layout(channel_assignment);
9259
9260 return 0;
9261}
9262
9264{
9265 AVStream *st;
9266 uint8_t buf[ISOM_DVCC_DVVC_SIZE];
9267 int ret;
9268 int64_t read_size = atom.size;
9269
9270 if (c->fc->nb_streams < 1)
9271 return 0;
9272 st = c->fc->streams[c->fc->nb_streams-1];
9273
9274 // At most 24 bytes
9275 read_size = FFMIN(read_size, ISOM_DVCC_DVVC_SIZE);
9276
9277 if ((ret = ffio_read_size(pb, buf, read_size)) < 0)
9278 return ret;
9279
9280 return ff_isom_parse_dvcc_dvvc(c->fc, st, buf, read_size);
9281}
9282
9284{
9285 AVStream *st;
9286 AVPacketSideData *sd;
9287 int ret;
9288
9289 if (c->fc->nb_streams < 1)
9290 return 0;
9291 st = c->fc->streams[c->fc->nb_streams - 1];
9292
9293 if (atom.size < 23 || atom.size > INT_MAX - AV_INPUT_BUFFER_PADDING_SIZE)
9294 return AVERROR_INVALIDDATA;
9295
9299 atom.size, 0);
9300 if (!sd)
9301 return AVERROR(ENOMEM);
9302
9303 ret = ffio_read_size(pb, sd->data, atom.size);
9304 if (ret < 0)
9305 return ret;
9306
9307 return 0;
9308}
9309
9311{
9312 AVStream *st;
9313 uint8_t *buf;
9314 int ret, old_size, num_arrays;
9315
9316 if (c->fc->nb_streams < 1)
9317 return 0;
9318 st = c->fc->streams[c->fc->nb_streams-1];
9319
9320 if (!st->codecpar->extradata_size)
9321 // TODO: handle lhvC when present before hvcC
9322 return 0;
9323
9324 if (atom.size < 6 || st->codecpar->extradata_size < 23 ||
9325 atom.size > INT_MAX - AV_INPUT_BUFFER_PADDING_SIZE) {
9326 return AVERROR_INVALIDDATA;
9327 }
9328
9330 if (!buf)
9331 return AVERROR(ENOMEM);
9332 memset(buf + atom.size, 0, AV_INPUT_BUFFER_PADDING_SIZE);
9333
9334 ret = ffio_read_size(pb, buf, atom.size);
9335 if (ret < 0) {
9336 av_free(buf);
9337 av_log(c->fc, AV_LOG_WARNING, "lhvC atom truncated\n");
9338 return 0;
9339 }
9340
9341 num_arrays = buf[5];
9342 old_size = st->codecpar->extradata_size;
9343 atom.size -= 8 /* account for mov_realloc_extradata offsetting */
9344 + 6 /* lhvC bytes before the arrays*/;
9345
9346 ret = mov_realloc_extradata(st->codecpar, atom);
9347 if (ret < 0) {
9348 av_free(buf);
9349 return ret;
9350 }
9351
9352 st->codecpar->extradata[22] += num_arrays;
9353 memcpy(st->codecpar->extradata + old_size, buf + 6, atom.size + 8);
9354
9356
9357 av_free(buf);
9358 return 0;
9359}
9360
9362{
9363 AVFormatContext *ctx = c->fc;
9364 AVStream *st = NULL;
9365 AVBPrint scheme_buf, value_buf;
9366 int64_t scheme_str_len = 0, value_str_len = 0;
9367 int version, flags, ret = AVERROR_BUG;
9368 int64_t size = atom.size;
9369
9370 if (atom.size < 6)
9371 // 4 bytes for version + flags, 2x 1 byte for null
9372 return AVERROR_INVALIDDATA;
9373
9374 if (c->fc->nb_streams < 1)
9375 return 0;
9376 st = c->fc->streams[c->fc->nb_streams-1];
9377
9378 version = avio_r8(pb);
9379 flags = avio_rb24(pb);
9380 size -= 4;
9381
9382 if (version != 0 || flags != 0) {
9384 "Unsupported 'kind' box with version %d, flags: %x",
9385 version, flags);
9386 return AVERROR_INVALIDDATA;
9387 }
9388
9391
9392 if ((scheme_str_len = ff_read_string_to_bprint_overwrite(pb, &scheme_buf,
9393 size)) < 0) {
9394 ret = scheme_str_len;
9395 goto cleanup;
9396 }
9397
9398 if (scheme_str_len + 1 >= size) {
9399 // we need to have another string, even if nullptr.
9400 // we check with + 1 since we expect that if size was not hit,
9401 // an additional null was read.
9403 goto cleanup;
9404 }
9405
9406 size -= scheme_str_len + 1;
9407
9408 if ((value_str_len = ff_read_string_to_bprint_overwrite(pb, &value_buf,
9409 size)) < 0) {
9410 ret = value_str_len;
9411 goto cleanup;
9412 }
9413
9414 if (value_str_len == size) {
9415 // in case of no trailing null, box is not valid.
9417 goto cleanup;
9418 }
9419
9421 "%s stream %d KindBox(scheme: %s, value: %s)\n",
9423 st->index,
9424 scheme_buf.str, value_buf.str);
9425
9426 for (int i = 0; ff_mov_track_kind_table[i].scheme_uri; i++) {
9428 if (!av_strstart(scheme_buf.str, map.scheme_uri, NULL))
9429 continue;
9430
9431 for (int j = 0; map.value_maps[j].disposition; j++) {
9432 const struct MP4TrackKindValueMapping value_map = map.value_maps[j];
9433 if (!av_strstart(value_buf.str, value_map.value, NULL))
9434 continue;
9435
9436 st->disposition |= value_map.disposition;
9437 }
9438 }
9439
9440 ret = 0;
9441
9442cleanup:
9443
9444 av_bprint_finalize(&scheme_buf, NULL);
9445 av_bprint_finalize(&value_buf, NULL);
9446
9447 return ret;
9448}
9449
9451{
9452 AVStream *st;
9453 AVChannelLayout ch_layout = { 0 };
9454 int ret, i, version, type;
9455 int ambisonic_order, channel_order, normalization, channel_count;
9456 int ambi_channels, non_diegetic_channels;
9457
9458 if (c->fc->nb_streams < 1)
9459 return 0;
9460
9461 st = c->fc->streams[c->fc->nb_streams - 1];
9462
9463 if (atom.size < 16) {
9464 av_log(c->fc, AV_LOG_ERROR, "SA3D audio box too small\n");
9465 return AVERROR_INVALIDDATA;
9466 }
9467
9468 version = avio_r8(pb);
9469 if (version) {
9470 av_log(c->fc, AV_LOG_WARNING, "Unsupported SA3D box version %d\n", version);
9471 return 0;
9472 }
9473
9474 type = avio_r8(pb);
9475 if (type & 0x7f) {
9476 av_log(c->fc, AV_LOG_WARNING,
9477 "Unsupported ambisonic type %d\n", type & 0x7f);
9478 return 0;
9479 }
9480 non_diegetic_channels = (type >> 7) * 2; // head_locked_stereo
9481
9482 ambisonic_order = avio_rb32(pb);
9483
9484 channel_order = avio_r8(pb);
9485 if (channel_order) {
9486 av_log(c->fc, AV_LOG_WARNING,
9487 "Unsupported channel_order %d\n", channel_order);
9488 return 0;
9489 }
9490
9491 normalization = avio_r8(pb);
9492 if (normalization) {
9493 av_log(c->fc, AV_LOG_WARNING,
9494 "Unsupported normalization %d\n", normalization);
9495 return 0;
9496 }
9497
9498 channel_count = avio_rb32(pb);
9499 if (ambisonic_order < 0 || ambisonic_order > 31 ||
9500 channel_count != ((ambisonic_order + 1LL) * (ambisonic_order + 1LL) +
9501 non_diegetic_channels)) {
9502 av_log(c->fc, AV_LOG_ERROR,
9503 "Invalid number of channels (%d / %d)\n",
9504 channel_count, ambisonic_order);
9505 return 0;
9506 }
9507 ambi_channels = channel_count - non_diegetic_channels;
9508
9509 ret = av_channel_layout_custom_init(&ch_layout, channel_count);
9510 if (ret < 0)
9511 return 0;
9512
9513 for (i = 0; i < channel_count; i++) {
9514 unsigned channel = avio_rb32(pb);
9515
9516 if (channel >= channel_count) {
9517 av_log(c->fc, AV_LOG_ERROR, "Invalid channel index (%d / %d)\n",
9518 channel, ambisonic_order);
9519 av_channel_layout_uninit(&ch_layout);
9520 return 0;
9521 }
9522 if (channel >= ambi_channels)
9523 ch_layout.u.map[i].id = channel - ambi_channels;
9524 else
9525 ch_layout.u.map[i].id = AV_CHAN_AMBISONIC_BASE + channel;
9526 }
9527
9529 if (ret < 0) {
9530 av_channel_layout_uninit(&ch_layout);
9531 return 0;
9532 }
9533
9535 st->codecpar->ch_layout = ch_layout;
9536
9537 return 0;
9538}
9539
9541{
9542 AVStream *st;
9543 int version;
9544
9545 if (c->fc->nb_streams < 1)
9546 return 0;
9547
9548 st = c->fc->streams[c->fc->nb_streams - 1];
9549
9550 if (atom.size < 5) {
9551 av_log(c->fc, AV_LOG_ERROR, "Empty SAND audio box\n");
9552 return AVERROR_INVALIDDATA;
9553 }
9554
9555 version = avio_r8(pb);
9556 if (version) {
9557 av_log(c->fc, AV_LOG_WARNING, "Unsupported SAND box version %d\n", version);
9558 return 0;
9559 }
9560
9562
9563 return 0;
9564}
9565
9566static int rb_size(AVIOContext *pb, int64_t *value, int size)
9567{
9568 if (size == 0)
9569 *value = 0;
9570 else if (size == 1)
9571 *value = avio_r8(pb);
9572 else if (size == 2)
9573 *value = avio_rb16(pb);
9574 else if (size == 4)
9575 *value = avio_rb32(pb);
9576 else if (size == 8) {
9577 *value = avio_rb64(pb);
9578 if (*value < 0)
9579 return -1;
9580 } else
9581 return -1;
9582 return size;
9583}
9584
9586{
9587 AVBPrint aux_type;
9588 HEIFItem *item;
9589
9590 avio_r8(pb); /* version */
9591 avio_rb24(pb); /* flags */
9592
9594 ff_read_string_to_bprint_overwrite(pb, &aux_type, atom.size - 4);
9595
9596 av_log(c->fc, AV_LOG_TRACE, "auxC: item_id %d, aux_type %s\n",
9597 c->cur_item_id, aux_type.str);
9598
9599 item = get_heif_item(c, c->cur_item_id);
9600 if (item) {
9601 if ((av_stristr(aux_type.str, "hdrgainmap")))
9602 item->is_gainmap = 1;
9603 else if (strstr(aux_type.str, "urn:mpeg:hevc:2015:auxid:1") ||
9604 strstr(aux_type.str, "urn:mpeg:mpegB:cicp:systems:auxiliary:alpha"))
9605 item->is_alpha = 1;
9606 }
9607 return 0;
9608}
9609
9611{
9612 avio_rb32(pb); // version & flags.
9613 c->primary_item_id = avio_rb16(pb);
9614 av_log(c->fc, AV_LOG_TRACE, "pitm: primary_item_id %d\n", c->primary_item_id);
9615 return atom.size;
9616}
9617
9619{
9620 c->idat_offset = avio_tell(pb);
9621 return 0;
9622}
9623
9625{
9626 HEIFItem **heif_item;
9627 int version, offset_size, length_size, base_offset_size, index_size;
9628 int item_count, extent_count;
9629 int64_t base_offset, extent_offset, extent_length;
9630 uint8_t value;
9631
9632 if (c->found_iloc) {
9633 av_log(c->fc, AV_LOG_INFO, "Duplicate iloc box found\n");
9634 return 0;
9635 }
9636
9637 version = avio_r8(pb);
9638 avio_rb24(pb); // flags.
9639
9640 value = avio_r8(pb);
9641 offset_size = (value >> 4) & 0xF;
9642 length_size = value & 0xF;
9643 value = avio_r8(pb);
9644 base_offset_size = (value >> 4) & 0xF;
9645 index_size = !version ? 0 : (value & 0xF);
9646 if (index_size) {
9647 avpriv_report_missing_feature(c->fc, "iloc: index_size != 0");
9648 return AVERROR_PATCHWELCOME;
9649 }
9650 item_count = (version < 2) ? avio_rb16(pb) : avio_rb32(pb);
9651
9652 if (item_count > atom.size)
9653 return AVERROR_INVALIDDATA;
9654
9655 heif_item = av_realloc_array(c->heif_item, FFMAX(item_count, c->nb_heif_item), sizeof(*c->heif_item));
9656 if (!heif_item)
9657 return AVERROR(ENOMEM);
9658 c->heif_item = heif_item;
9659 if (item_count > c->nb_heif_item)
9660 memset(&c->heif_item[c->nb_heif_item], 0,
9661 sizeof(*c->heif_item) * (item_count - c->nb_heif_item));
9662 c->nb_heif_item = FFMAX(c->nb_heif_item, item_count);
9663
9664 av_log(c->fc, AV_LOG_TRACE, "iloc: item_count %d\n", item_count);
9665 for (int i = 0; i < item_count; i++) {
9666 HEIFItem *item = NULL;
9667 int item_id = (version < 2) ? avio_rb16(pb) : avio_rb32(pb);
9668 int offset_type = (version > 0) ? avio_rb16(pb) & 0xf : 0;
9669 int j;
9670
9671 if (avio_feof(pb))
9672 return AVERROR_INVALIDDATA;
9673 if (offset_type > 1) {
9674 avpriv_report_missing_feature(c->fc, "iloc offset type %d", offset_type);
9675 return AVERROR_PATCHWELCOME;
9676 }
9677
9678 avio_rb16(pb); // data_reference_index.
9679 if (rb_size(pb, &base_offset, base_offset_size) < 0)
9680 return AVERROR_INVALIDDATA;
9681 extent_count = avio_rb16(pb);
9682 if (extent_count > 1) {
9683 // For still AVIF images, we only support one extent item.
9684 avpriv_report_missing_feature(c->fc, "iloc: extent_count > 1");
9685 return AVERROR_PATCHWELCOME;
9686 }
9687
9688 if (rb_size(pb, &extent_offset, offset_size) < 0 ||
9689 rb_size(pb, &extent_length, length_size) < 0 ||
9690 base_offset > INT64_MAX - extent_offset)
9691 return AVERROR_INVALIDDATA;
9692
9693 for (j = 0; j < c->nb_heif_item; j++) {
9694 item = c->heif_item[j];
9695 if (!item)
9696 item = c->heif_item[j] = av_mallocz(sizeof(*item));
9697 else if (item->item_id != item_id)
9698 continue;
9699 break;
9700 }
9701 if (!item)
9702 return AVERROR(ENOMEM);
9703 if (j == c->nb_heif_item)
9704 return AVERROR_INVALIDDATA;
9705
9706 item->item_id = item_id;
9707
9708 if (offset_type == 1)
9709 item->is_idat_relative = 1;
9710 item->extent_length = extent_length;
9711 item->extent_offset = base_offset + extent_offset;
9712 av_log(c->fc, AV_LOG_TRACE, "iloc: item_idx %d, item->item_id %d, offset_type %d, "
9713 "extent_offset %"PRId64", extent_length %"PRId64"\n",
9714 i, item->item_id, offset_type, item->extent_offset, item->extent_length);
9715 }
9716
9717 c->found_iloc = 1;
9718 return atom.size;
9719}
9720
9722{
9723 HEIFItem *item = NULL;
9724 AVBPrint item_name;
9725 int64_t size = atom.size;
9726 uint32_t item_type;
9727 int item_id;
9728 int i, version, flags, ret;
9729
9730 version = avio_r8(pb);
9731 flags = avio_rb24(pb);
9732 size -= 4;
9733 if (size < 0)
9734 return AVERROR_INVALIDDATA;
9735
9736 if (version < 2) {
9737 avpriv_report_missing_feature(c->fc, "infe version < 2");
9738 avio_skip(pb, size);
9739 return 1;
9740 }
9741
9742 item_id = version > 2 ? avio_rb32(pb) : avio_rb16(pb);
9743 avio_rb16(pb); // item_protection_index
9744 item_type = avio_rl32(pb);
9745 size -= 8;
9746 if (size < 1)
9747 return AVERROR_INVALIDDATA;
9748
9751 if (ret < 0) {
9753 return ret;
9754 }
9755
9756 av_log(c->fc, AV_LOG_TRACE, "infe: item_id %d, item_type %s, item_name %s\n",
9757 item_id, av_fourcc2str(item_type), item_name.str);
9758
9759 size -= ret + 1;
9760 if (size > 0)
9761 avio_skip(pb, size);
9762
9763 for (i = 0; i < c->nb_heif_item; i++) {
9764 item = c->heif_item[i];
9765 if (!item)
9766 item = c->heif_item[i] = av_mallocz(sizeof(*item));
9767 else if (item->item_id != item_id)
9768 continue;
9769 break;
9770 }
9771 if (!item) {
9773 return AVERROR(ENOMEM);
9774 }
9775 if (i == c->nb_heif_item) {
9777 return AVERROR_INVALIDDATA;
9778 }
9779
9780 av_freep(&item->name);
9782 item->item_id = item_id;
9783 item->type = item_type;
9784 item->flags = flags;
9785
9786 switch (item_type) {
9787 case MKTAG('a','v','0','1'):
9788 case MKTAG('j','p','e','g'):
9789 case MKTAG('h','v','c','1'):
9790 ret = heif_add_stream(c, item);
9791 if (ret < 0)
9792 return ret;
9793 break;
9794 }
9795
9796 return 0;
9797}
9798
9800{
9801 HEIFItem **heif_item;
9802 int entry_count;
9803 int version, got_stream = 0, ret, i;
9804
9805 if (c->found_iinf) {
9806 av_log(c->fc, AV_LOG_WARNING, "Duplicate iinf box found\n");
9807 return 0;
9808 }
9809
9810 version = avio_r8(pb);
9811 avio_rb24(pb); // flags.
9812 entry_count = version ? avio_rb32(pb) : avio_rb16(pb);
9813
9814 if (entry_count > atom.size)
9815 return AVERROR_INVALIDDATA;
9816
9817 /* account for the version/flags/entry_count fields already consumed,
9818 * so the per-entry loop below can bound each infe box by what is
9819 * actually left in this iinf box, the same way mov_read_iprp() bounds
9820 * ipco/ipma entries by the remaining iprp size. */
9821 atom.size -= version ? 8 : 6;
9822 if (atom.size < 0)
9823 return AVERROR_INVALIDDATA;
9824
9825 heif_item = av_realloc_array(c->heif_item, FFMAX(entry_count, c->nb_heif_item), sizeof(*c->heif_item));
9826 if (!heif_item)
9827 return AVERROR(ENOMEM);
9828 c->heif_item = heif_item;
9829 if (entry_count > c->nb_heif_item)
9830 memset(&c->heif_item[c->nb_heif_item], 0,
9831 sizeof(*c->heif_item) * (entry_count - c->nb_heif_item));
9832 c->nb_heif_item = FFMAX(c->nb_heif_item, entry_count);
9833
9834 for (i = 0; i < entry_count; i++) {
9835 MOVAtom infe;
9836
9837 infe.size = avio_rb32(pb);
9838 infe.type = avio_rl32(pb);
9839 if (avio_feof(pb) || infe.size < 8 || infe.size > atom.size ||
9840 infe.type != MKTAG('i','n','f','e')) {
9842 goto fail;
9843 }
9844
9845 atom.size -= infe.size;
9846 infe.size -= 8;
9847
9848 ret = mov_read_infe(c, pb, infe);
9849 if (ret < 0)
9850 goto fail;
9851 if (!ret)
9852 got_stream = 1;
9853 }
9854
9855 c->found_iinf = got_stream;
9856 return 0;
9857fail:
9858 for (; i >= 0; i--) {
9859 HEIFItem *item = c->heif_item[i];
9860
9861 if (!item)
9862 continue;
9863
9864 av_freep(&item->name);
9865 }
9866 return ret;
9867}
9868
9870 HEIFItem *item, int version, int entries)
9871{
9872 HEIFGroup *tmap = av_realloc_array(c->heif_group, c->nb_heif_group + 1U,
9873 sizeof(*c->heif_group));
9874 int ret;
9875
9876 if (!tmap)
9877 return AVERROR(ENOMEM);
9878 c->heif_group = tmap;
9879
9880 if (entries != 2) {
9881 avpriv_report_missing_feature(c->fc, "Derived image item of type %s with an "
9882 "item reference count other than 2",
9883 av_fourcc2str(item->type));
9884 return 0;
9885 }
9886
9887 tmap = &tmap[c->nb_heif_group];
9888
9889 tmap->item_idx_list = NULL; // Not needed
9890 tmap->item_id_list = av_malloc_array(entries, sizeof(*tmap->item_id_list));
9891 tmap->item_list = av_calloc(entries, sizeof(*tmap->item_list));
9892 if (!tmap->item_id_list || !tmap->item_list) {
9893 ret = AVERROR(ENOMEM);
9894 goto fail;
9895 }
9896
9897 /* 'to' item ids */
9898 for (int i = 0; i < entries; i++) {
9899 tmap->item_id_list[i] = version ? avio_rb32(pb) : avio_rb16(pb);
9900
9901 if (avio_feof(pb)) {
9903 goto fail;
9904 }
9905 }
9906
9907 tmap->nb_items = entries;
9908 tmap->item = item;
9909 ++c->nb_heif_group;
9910
9911 return 0;
9912fail:
9913 av_freep(&tmap->item_id_list);
9914 av_freep(&tmap->item_list);
9915
9916 return ret;
9917}
9918
9920 HEIFItem *item, int version, int entries)
9921{
9922 HEIFGroup *grid = av_realloc_array(c->heif_group, c->nb_heif_group + 1U,
9923 sizeof(*c->heif_group));
9924 int ret;
9925
9926 if (!grid)
9927 return AVERROR(ENOMEM);
9928 c->heif_group = grid;
9929 grid = &grid[c->nb_heif_group];
9930
9931 grid->item_id_list = av_malloc_array(entries, sizeof(*grid->item_id_list));
9932 grid->item_idx_list = av_calloc(entries, sizeof(*grid->item_idx_list));
9933 grid->item_list = av_calloc(entries, sizeof(*grid->item_list));
9934 if (!grid->item_id_list || !grid->item_list || !grid->item_idx_list) {
9935 ret = AVERROR(ENOMEM);
9936 goto fail;
9937 }
9938 /* 'to' item ids */
9939 for (int i = 0; i < entries; i++) {
9940 grid->item_id_list[i] = version ? avio_rb32(pb) : avio_rb16(pb);
9941
9942 if (avio_feof(pb)) {
9944 goto fail;
9945 }
9946 }
9947
9948 grid->nb_items = entries;
9949 grid->item = item;
9950 ++c->nb_heif_group;
9951
9952 return 0;
9953fail:
9954 av_freep(&grid->item_id_list);
9955 av_freep(&grid->item_idx_list);
9956 av_freep(&grid->item_list);
9957
9958 return ret;
9959}
9960
9962 uint32_t size)
9963{
9964 HEIFItem *item = NULL;
9965 int entries;
9966 int item_id_size = version ? 4 : 2;
9967 int from_item_id = version ? avio_rb32(pb) : avio_rb16(pb);
9968 int ret;
9969
9970 for (int i = 0; i < c->nb_heif_group; i++) {
9971 if (c->heif_group[i].item->item_id == from_item_id) {
9972 av_log(c->fc, AV_LOG_ERROR, "More than one 'dimg' box "
9973 "referencing the same Derived Image item\n");
9974 return AVERROR_INVALIDDATA;
9975 }
9976 }
9977 for (int i = 0; i < c->nb_heif_item; i++) {
9978 if (!c->heif_item[i] || c->heif_item[i]->item_id != from_item_id)
9979 continue;
9980 item = c->heif_item[i];
9981
9982 switch (item->type) {
9983 case MKTAG('g','r','i','d'):
9984 case MKTAG('i','o','v','l'):
9985 case MKTAG('t','m','a','p'):
9986 break;
9987 default:
9988 avpriv_report_missing_feature(c->fc, "Derived Image item of type %s",
9989 av_fourcc2str(item->type));
9990 return 0;
9991 }
9992 break;
9993 }
9994 if (!item) {
9995 av_log(c->fc, AV_LOG_ERROR, "Missing derived image information\n");
9996 return AVERROR_INVALIDDATA;
9997 }
9998
9999 entries = avio_rb16(pb);
10000 if (!entries) {
10001 av_log(c->fc, AV_LOG_ERROR,
10002 "Derived image item references no input images\n");
10003 return AVERROR_INVALIDDATA;
10004 }
10005 if ((int64_t)entries * item_id_size > (int64_t)size - item_id_size - 2) {
10006 av_log(c->fc, AV_LOG_ERROR, "iref dimg entry count %d exceeds the sub-box size\n",
10007 entries);
10008 return AVERROR_INVALIDDATA;
10009 }
10010
10011 av_log(c->fc, AV_LOG_TRACE, "dimg: from_item_id %d, entries %d\n",
10012 from_item_id, entries);
10013
10014 switch (item->type) {
10015 case MKTAG('g','r','i','d'):
10016 case MKTAG('i','o','v','l'):
10017 ret = mov_read_iref_dimg_grid(c, pb, item, version, entries);
10018 break;
10019 case MKTAG('t','m','a','p'):
10020 ret = mov_read_iref_dimg_tmap(c, pb, item, version, entries);
10021 break;
10022 default:
10023 av_unreachable("item->type should have been checked above");
10024 }
10025
10026 return ret;
10027}
10028
10030 int version, uint32_t size)
10031{
10032 HEIFItem *from_item = NULL;
10033 int entries;
10034 int item_id_size = version ? 4 : 2;
10035 int from_item_id = version ? avio_rb32(pb) : avio_rb16(pb);
10036 const HEIFItemRef ref = { type, from_item_id };
10037
10038 from_item = get_heif_item(c, from_item_id);
10039 if (!from_item) {
10040 av_log(c->fc, AV_LOG_ERROR, "Missing stream referenced by %s iref\n",
10042 return AVERROR_INVALIDDATA;
10043 }
10044
10045 entries = avio_rb16(pb);
10046 if ((int64_t)entries * item_id_size > (int64_t)size - item_id_size - 2) {
10047 av_log(c->fc, AV_LOG_ERROR, "iref %s entry count %d exceeds the sub-box size\n",
10048 av_fourcc2str(type), entries);
10049 return AVERROR_INVALIDDATA;
10050 }
10051 /* 'to' item ids */
10052 for (int i = 0; i < entries; i++) {
10053 HEIFItem *item = get_heif_item(c, version ? avio_rb32(pb) : avio_rb16(pb));
10054
10055 if (avio_feof(pb))
10056 return AVERROR_INVALIDDATA;
10057
10058 if (!item) {
10059 av_log(c->fc, AV_LOG_WARNING, "Missing stream referenced by %s item\n",
10061 continue;
10062 }
10063
10064 if (!av_dynarray2_add((void **)&item->iref_from_list, &item->nb_iref_from_list,
10065 sizeof(*item->iref_from_list), (const uint8_t *)&ref))
10066 return AVERROR(ENOMEM);
10067 }
10068
10069 av_log(c->fc, AV_LOG_TRACE, "%s: from_item_id %d, entries %d\n",
10070 av_fourcc2str(type), from_item_id, entries);
10071
10072 return 0;
10073}
10074
10076 int version, uint32_t size)
10077{
10078 HEIFItem *from_item = NULL;
10079 int entries;
10080 unsigned from_item_id = version ? avio_rb32(pb) : avio_rb16(pb);
10081
10082 from_item = get_heif_item(c, from_item_id);
10083 if (!from_item) {
10084 av_log(c->fc, AV_LOG_ERROR, "Missing item referenced by %s iref\n",
10086 return AVERROR_INVALIDDATA;
10087 }
10088
10089 entries = avio_rb16(pb);
10090 if (entries != 1) {
10091 avpriv_report_missing_feature(c->fc, "%s iref with an item reference "
10092 "count other than 1",
10094 return 0;
10095 }
10096
10097 /* 'to' item ids */
10098 for (int i = 0; i < entries; i++) {
10099 unsigned to_item_id = version ? avio_rb32(pb) : avio_rb16(pb);
10100 const HEIFItemRef ref = { type, to_item_id };
10101 HEIFItem *item = get_heif_item(c, to_item_id);
10102
10103 if (avio_feof(pb))
10104 return AVERROR_INVALIDDATA;
10105
10106 if (!item) {
10107 av_log(c->fc, AV_LOG_WARNING, "Missing item referenced by %s iref\n",
10109 continue;
10110 }
10111
10112 if (!av_dynarray2_add((void **)&from_item->iref_to_list, &from_item->nb_iref_to_list,
10113 sizeof(*from_item->iref_to_list), (const uint8_t *)&ref))
10114 return AVERROR(ENOMEM);
10115 }
10116
10117 av_log(c->fc, AV_LOG_TRACE, "%s: from_item_id %d, entries %d\n",
10118 av_fourcc2str(type), from_item_id, entries);
10119
10120 return 0;
10121}
10122
10124{
10125 int version = avio_r8(pb);
10126 int ret;
10127
10128 avio_rb24(pb); // flags
10129 atom.size -= 4;
10130
10131 if (version > 1) {
10132 av_log(c->fc, AV_LOG_WARNING, "Unknown iref box version %d\n", version);
10133 return 0;
10134 }
10135
10136 while (atom.size) {
10137 int64_t next = avio_tell(pb);
10138 uint32_t type, size = avio_rb32(pb);
10139
10140 if (size < 14 || size > atom.size || next > INT64_MAX - size)
10141 return AVERROR_INVALIDDATA;
10142
10143 next += size;
10144 type = avio_rl32(pb);
10145 switch (type) {
10146 case MKTAG('d','i','m','g'):
10147 ret = mov_read_iref_dimg(c, pb, version, size - 8);
10148 if (ret < 0)
10149 return ret;
10150 break;
10151 case MKTAG('c','d','s','c'):
10152 ret = mov_read_iref_cdsc(c, pb, type, version, size - 8);
10153 if (ret < 0)
10154 return ret;
10155 break;
10156 case MKTAG('a','u','x','l'):
10157 case MKTAG('t','h','m','b'):
10158 ret = mov_read_iref_auxl(c, pb, type, version, size - 8);
10159 if (ret < 0)
10160 return ret;
10161 break;
10162 default:
10163 av_log(c->fc, AV_LOG_DEBUG, "Unknown iref type %s size %"PRIu32"\n",
10165 }
10166
10167 atom.size -= size;
10168 avio_seek(pb, next, SEEK_SET);
10169 }
10170 return 0;
10171}
10172
10174{
10175 HEIFItem *item;
10176 uint32_t width, height;
10177
10178 avio_r8(pb); /* version */
10179 avio_rb24(pb); /* flags */
10180 width = avio_rb32(pb);
10181 height = avio_rb32(pb);
10182
10183 av_log(c->fc, AV_LOG_TRACE, "ispe: item_id %d, width %"PRIu32", height %"PRIu32"\n",
10184 c->cur_item_id, width, height);
10185
10186 if (!width || !height || width > INT_MAX || height > INT_MAX) {
10187 av_log(c->fc, AV_LOG_ERROR, "Invalid ispe dimensions %"PRIu32"x%"PRIu32"\n",
10188 width, height);
10189 return AVERROR_INVALIDDATA;
10190 }
10191
10192 item = get_heif_item(c, c->cur_item_id);
10193 if (item) {
10194 item->width = width;
10195 item->height = height;
10196 }
10197
10198 return 0;
10199}
10200
10202{
10203 HEIFItem *item;
10204 int angle;
10205
10206 angle = avio_r8(pb) & 0x3;
10207
10208 av_log(c->fc, AV_LOG_TRACE, "irot: item_id %d, angle %u\n",
10209 c->cur_item_id, angle);
10210
10211 item = get_heif_item(c, c->cur_item_id);
10212 if (item) {
10213 // angle * 90 specifies the angle (in anti-clockwise direction)
10214 // in units of degrees.
10215 item->rotation = angle * 90;
10216 }
10217
10218 return 0;
10219}
10220
10222{
10223 HEIFItem *item;
10224 int axis;
10225
10226 axis = avio_r8(pb) & 0x1;
10227
10228 av_log(c->fc, AV_LOG_TRACE, "imir: item_id %d, axis %u\n",
10229 c->cur_item_id, axis);
10230
10231 item = get_heif_item(c, c->cur_item_id);
10232 if (item) {
10233 item->hflip = axis;
10234 item->vflip = !axis;
10235 }
10236
10237 return 0;
10238}
10239
10240typedef struct MOVAtomExt {
10241 uint32_t type;
10243 uint8_t *data;
10244} MOVAtomExt;
10245
10247 MOVAtomExt **atoms, int *nb_atoms)
10248{
10249 while (atom.size >= 8) {
10250 MOVAtomExt *ref = av_dynarray2_add((void**)atoms, nb_atoms, sizeof(MOVAtomExt), NULL);
10251 if (!ref)
10252 return AVERROR(ENOMEM);
10253
10254 ref->data = NULL;
10255 ref->size = avio_rb32(pb);
10256 ref->type = avio_rl32(pb);
10257 if (ref->size > atom.size || ref->size < 8)
10258 break;
10259 ref->data = av_malloc(ref->size);
10260 if (!ref->data)
10261 return AVERROR_INVALIDDATA;
10262
10263 av_log(c->fc, AV_LOG_TRACE, "ipco: index %d, box type %s\n", *nb_atoms,
10264 av_fourcc2str(ref->type));
10265 AV_WB32(ref->data, ref->size);
10266 AV_WL32(ref->data + 4, ref->type);
10267 if (avio_read(pb, ref->data + 8, ref->size - 8) != ref->size - 8) {
10268 return AVERROR_INVALIDDATA;
10269 }
10270 atom.size -= ref->size;
10271 }
10272
10273 if (atom.size)
10274 return AVERROR_INVALIDDATA;
10275
10276 return 0;
10277}
10278
10280 MOVAtomExt *atoms, int nb_atoms)
10281{
10282 unsigned count;
10283 int version, flags;
10284 int ret;
10285
10286 version = avio_r8(pb);
10287 flags = avio_rb24(pb);
10288 count = avio_rb32(pb);
10289 atom.size -= 8;
10290
10291 for (int i = 0; i < count; i++) {
10292 int item_id = version ? avio_rb32(pb) : avio_rb16(pb);
10293 int assoc_count = avio_r8(pb);
10294
10295 atom.size -= (version ? 5 : 3) + assoc_count * (1 + (flags & 1));
10296 if (avio_feof(pb) || atom.size < 0)
10297 return AVERROR_INVALIDDATA;
10298
10299 for (int j = 0; j < assoc_count; j++) {
10300 FFIOContext b;
10301 MOVAtomExt *ref;
10302 int index = avio_r8(pb) & 0x7f;
10303 if (flags & 1) {
10304 index <<= 8;
10305 index |= avio_r8(pb);
10306 }
10307 if (!index)
10308 continue;
10309 if (index > nb_atoms) {
10310 return AVERROR_INVALIDDATA;
10311 }
10312 ref = &atoms[--index];
10313
10314 av_log(c->fc, AV_LOG_TRACE, "ipma: property_index %d, item_id %d, item_type %s\n",
10315 index + 1, item_id, av_fourcc2str(ref->type));
10316
10317 c->cur_item_id = item_id;
10318
10319 ffio_init_read_context(&b, ref->data, ref->size);
10320 ret = mov_read_default(c, &b.pub,
10321 (MOVAtom) { .size = ref->size,
10322 .type = MKTAG('i','p','c','o') });
10323 if (ret < 0)
10324 return ret;
10325 }
10326 }
10327
10328 if (atom.size)
10329 return AVERROR_INVALIDDATA;
10330
10331 return 0;
10332}
10333
10335{
10336 MOVAtomExt *atoms = NULL;
10337 MOVAtom a;
10338 int nb_atoms = 0;
10339 int ret;
10340
10341 a.size = avio_rb32(pb);
10342 a.type = avio_rl32(pb);
10343
10344 if (a.size <= 8 || a.size > atom.size || a.type != MKTAG('i','p','c','o'))
10345 return AVERROR_INVALIDDATA;
10346
10347 atom.size -= a.size;
10348 a.size -= 8;
10349
10350 ret = mov_read_ipco(c, pb, a, &atoms, &nb_atoms);
10351 if (ret < 0)
10352 goto fail;
10353
10354 a.size = avio_rb32(pb);
10355 a.type = avio_rl32(pb);
10356
10357 if (a.size <= 8 || a.size > atom.size || a.type != MKTAG('i','p','m','a')) {
10359 goto fail;
10360 }
10361
10362 a.size -= 8;
10363
10364 ret = mov_read_ipma(c, pb, a, atoms, nb_atoms);
10365 if (ret < 0)
10366 goto fail;
10367
10368 ret = 0;
10369fail:
10370 c->cur_item_id = -1;
10371 for (int i = 0; i < nb_atoms; i++)
10372 av_free(atoms[i].data);
10373 av_free(atoms);
10374
10375 return ret;
10376}
10377
10379{
10380 avio_rb32(pb); // version & flags
10381 uint16_t graphics_mode = avio_rb16(pb);
10382 // ignored: opcolor[3]
10383
10384 if (c->fc->nb_streams < 1)
10385 return 0;
10386 AVStream *st = c->fc->streams[c->fc->nb_streams - 1];
10388 return 0;
10389
10390 switch (graphics_mode) {
10394 break;
10397 break;
10400 break;
10401 default:
10403 av_log(c->fc, AV_LOG_WARNING, "Unhandled graphics mode: 0x%x\n",
10404 graphics_mode);
10405 break;
10406 }
10407
10408 return 0;
10409}
10410
10412{
10413 AVFormatContext *ctx = c->fc;
10414 AVStream *st;
10415 int profile_level_indication, reference_ch_layout, config_length;
10416 int ret = 0;
10417
10418 if (ctx->nb_streams < 1)
10419 return 0;
10420
10421 st = ctx->streams[ctx->nb_streams - 1];
10423 return 0;
10424
10425 if (avio_r8(pb) != 1) // ConfigurationVersion
10426 return 0;
10427
10428 profile_level_indication = avio_r8(pb);
10429 st->codecpar->profile = (profile_level_indication - 1) / 5;
10430 st->codecpar->level = ((profile_level_indication - 1) % 5) + 1;
10431
10432 reference_ch_layout = avio_r8(pb);
10433 config_length = avio_rb16(pb);
10434 if (config_length)
10435 ret = ff_get_extradata(ctx, st->codecpar, pb, config_length);
10436
10437 if (!reference_ch_layout ||
10438 reference_ch_layout >= FF_ARRAY_ELEMS(ff_mpa_cicp_channel_layout_masks)) {
10439 av_log(ctx, AV_LOG_WARNING, "Unknown referenceChannelLayout value: %d\n", reference_ch_layout);
10440 return ret;
10441 }
10442
10444 ff_mpa_cicp_channel_layout_masks[reference_ch_layout]);
10445
10446 return ret;
10447}
10448
10450{
10451 AVStream *st;
10452 int version;
10453 uint32_t profile;
10454
10455 if (c->fc->nb_streams < 1)
10456 return 0;
10457 st = c->fc->streams[c->fc->nb_streams - 1];
10458
10459 if (atom.size < 8)
10460 return AVERROR_INVALIDDATA;
10461
10462 version = avio_r8(pb);
10463 avio_rb24(pb); /* flags */
10464 profile = avio_rl32(pb);
10465
10466 if (version == 1) {
10467 switch (profile) {
10468 case MKTAG('r','g','b','3'):
10470 break;
10471 case MKTAG('r','g','b','a'):
10473 break;
10474 default:
10475 avpriv_request_sample(c->fc, "Unknown uncC profile %s", av_fourcc2str(profile));
10476 return AVERROR_INVALIDDATA;
10477 }
10478 } else if (version == 0) {
10479 avpriv_request_sample(c->fc, "uncC version 0 not yet implemented");
10480 return AVERROR_PATCHWELCOME;
10481 } else {
10482 av_log(c->fc, AV_LOG_WARNING, "Unknown uncC version %d\n", version);
10483 return AVERROR_INVALIDDATA;
10484 }
10485
10486 return 0;
10487}
10488
10490{ MKTAG('A','C','L','R'), mov_read_aclr },
10491{ MKTAG('A','P','R','G'), mov_read_avid },
10492{ MKTAG('A','A','L','P'), mov_read_avid },
10493{ MKTAG('A','R','E','S'), mov_read_ares },
10494{ MKTAG('a','v','s','s'), mov_read_avss },
10495{ MKTAG('a','v','1','C'), mov_read_glbl },
10496{ MKTAG('c','h','p','l'), mov_read_chpl },
10497{ MKTAG('c','o','6','4'), mov_read_stco },
10498{ MKTAG('c','o','l','r'), mov_read_colr },
10499{ MKTAG('g','a','m','a'), mov_read_gama },
10500{ MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
10501{ MKTAG('d','i','n','f'), mov_read_default },
10502{ MKTAG('D','p','x','E'), mov_read_dpxe },
10503{ MKTAG('d','r','e','f'), mov_read_dref },
10504{ MKTAG('e','d','t','s'), mov_read_default },
10505{ MKTAG('e','l','s','t'), mov_read_elst },
10506{ MKTAG('e','n','d','a'), mov_read_enda },
10507{ MKTAG('f','i','e','l'), mov_read_fiel },
10508{ MKTAG('a','d','r','m'), mov_read_adrm },
10509{ MKTAG('f','t','y','p'), mov_read_ftyp },
10510{ MKTAG('g','l','b','l'), mov_read_glbl },
10511{ MKTAG('h','d','l','r'), mov_read_hdlr },
10512{ MKTAG('i','l','s','t'), mov_read_ilst },
10513{ MKTAG('j','p','2','h'), mov_read_jp2h },
10514{ MKTAG('m','d','a','t'), mov_read_mdat },
10515{ MKTAG('m','d','h','d'), mov_read_mdhd },
10516{ MKTAG('m','d','i','a'), mov_read_default },
10517{ MKTAG('m','e','t','a'), mov_read_meta },
10518{ MKTAG('m','i','n','f'), mov_read_default },
10519{ MKTAG('m','o','o','f'), mov_read_moof },
10520{ MKTAG('m','o','o','v'), mov_read_moov },
10521{ MKTAG('m','v','e','x'), mov_read_default },
10522{ MKTAG('m','v','h','d'), mov_read_mvhd },
10523{ MKTAG('S','M','I',' '), mov_read_svq3 },
10524{ MKTAG('a','l','a','c'), mov_read_alac }, /* alac specific atom */
10525{ MKTAG('a','v','c','C'), mov_read_glbl },
10526{ MKTAG('u','n','c','C'), mov_read_uncc },
10527{ MKTAG('p','a','s','p'), mov_read_pasp },
10528{ MKTAG('c','l','a','p'), mov_read_clap },
10529{ MKTAG('c','d','s','c'), mov_read_cdsc_rndr },
10530{ MKTAG('r','n','d','r'), mov_read_cdsc_rndr },
10531{ MKTAG('s','b','a','s'), mov_read_sbas },
10532{ MKTAG('v','d','e','p'), mov_read_vdep },
10533{ MKTAG('s','i','d','x'), mov_read_sidx },
10534{ MKTAG('s','t','b','l'), mov_read_default },
10535{ MKTAG('s','t','c','o'), mov_read_stco },
10536{ MKTAG('s','t','p','s'), mov_read_stps },
10537{ MKTAG('s','t','r','f'), mov_read_strf },
10538{ MKTAG('s','t','s','c'), mov_read_stsc },
10539{ MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
10540{ MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
10541{ MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
10542{ MKTAG('s','t','t','s'), mov_read_stts },
10543{ MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */
10544{ MKTAG('s','d','t','p'), mov_read_sdtp }, /* independent and disposable samples */
10545{ MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
10546{ MKTAG('t','f','d','t'), mov_read_tfdt },
10547{ MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
10548{ MKTAG('t','r','a','k'), mov_read_trak },
10549{ MKTAG('t','r','a','f'), mov_read_default },
10550{ MKTAG('t','r','e','f'), mov_read_default },
10551{ MKTAG('t','m','c','d'), mov_read_tmcd },
10552{ MKTAG('c','h','a','p'), mov_read_chap },
10553{ MKTAG('t','r','e','x'), mov_read_trex },
10554{ MKTAG('t','r','u','n'), mov_read_trun },
10555{ MKTAG('u','d','t','a'), mov_read_default },
10556{ MKTAG('w','a','v','e'), mov_read_wave },
10557{ MKTAG('e','s','d','s'), mov_read_esds },
10558{ MKTAG('d','a','c','3'), mov_read_dac3 }, /* AC-3 info */
10559{ MKTAG('d','e','c','3'), mov_read_dec3 }, /* EAC-3 info */
10560{ MKTAG('d','d','t','s'), mov_read_ddts }, /* DTS audio descriptor */
10561{ MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
10562{ MKTAG('w','f','e','x'), mov_read_wfex },
10563{ MKTAG('c','m','o','v'), mov_read_cmov },
10564{ MKTAG('c','h','a','n'), mov_read_chan }, /* channel layout from quicktime */
10565{ MKTAG('c','h','n','l'), mov_read_chnl }, /* channel layout from ISO-14496-12 */
10566{ MKTAG('d','v','c','1'), mov_read_dvc1 },
10567{ MKTAG('s','g','p','d'), mov_read_sgpd },
10568{ MKTAG('s','b','g','p'), mov_read_sbgp },
10569{ MKTAG('h','v','c','C'), mov_read_glbl },
10570{ MKTAG('v','v','c','C'), mov_read_glbl },
10571{ MKTAG('u','u','i','d'), mov_read_uuid },
10572{ MKTAG('C','i','n', 0x8e), mov_read_targa_y216 },
10573{ MKTAG('f','r','e','e'), mov_read_free },
10574{ MKTAG('-','-','-','-'), mov_read_custom },
10575{ MKTAG('s','i','n','f'), mov_read_default },
10576{ MKTAG('f','r','m','a'), mov_read_frma },
10577{ MKTAG('s','e','n','c'), mov_read_senc },
10578{ MKTAG('s','a','i','z'), mov_read_saiz },
10579{ MKTAG('s','a','i','o'), mov_read_saio },
10580{ MKTAG('p','s','s','h'), mov_read_pssh },
10581{ MKTAG('s','c','h','m'), mov_read_schm },
10582{ MKTAG('s','c','h','i'), mov_read_default },
10583{ MKTAG('t','e','n','c'), mov_read_tenc },
10584{ MKTAG('d','f','L','a'), mov_read_dfla },
10585{ MKTAG('s','t','3','d'), mov_read_st3d }, /* stereoscopic 3D video box */
10586{ MKTAG('s','v','3','d'), mov_read_sv3d }, /* spherical video box */
10587{ MKTAG('v','e','x','u'), mov_read_vexu }, /* video extension usage */
10588{ MKTAG('h','f','o','v'), mov_read_hfov },
10589{ MKTAG('d','O','p','s'), mov_read_dops },
10590{ MKTAG('d','m','l','p'), mov_read_dmlp },
10591{ MKTAG('S','m','D','m'), mov_read_smdm },
10592{ MKTAG('C','o','L','L'), mov_read_coll },
10593{ MKTAG('v','p','c','C'), mov_read_vpcc },
10594{ MKTAG('m','d','c','v'), mov_read_mdcv },
10595{ MKTAG('c','l','l','i'), mov_read_clli },
10596{ MKTAG('d','v','c','C'), mov_read_dvcc_dvvc },
10597{ MKTAG('d','v','v','C'), mov_read_dvcc_dvvc },
10598{ MKTAG('d','v','w','C'), mov_read_dvcc_dvvc },
10599{ MKTAG('h','v','c','E'), mov_read_hvce },
10600{ MKTAG('k','i','n','d'), mov_read_kind },
10601{ MKTAG('S','A','3','D'), mov_read_SA3D }, /* ambisonic audio box */
10602{ MKTAG('S','A','N','D'), mov_read_SAND }, /* non diegetic audio box */
10603{ MKTAG('i','l','o','c'), mov_read_iloc },
10604{ MKTAG('p','c','m','C'), mov_read_pcmc }, /* PCM configuration box */
10605{ MKTAG('p','i','t','m'), mov_read_pitm },
10606{ MKTAG('e','v','c','C'), mov_read_glbl },
10607{ MKTAG('a','u','x','C'), mov_read_auxc },
10608{ MKTAG('i','d','a','t'), mov_read_idat },
10609{ MKTAG('i','m','i','r'), mov_read_imir },
10610{ MKTAG('i','r','e','f'), mov_read_iref },
10611{ MKTAG('i','s','p','e'), mov_read_ispe },
10612{ MKTAG('i','r','o','t'), mov_read_irot },
10613{ MKTAG('i','p','r','p'), mov_read_iprp },
10614{ MKTAG('i','i','n','f'), mov_read_iinf },
10615{ MKTAG('a','m','v','e'), mov_read_amve }, /* ambient viewing environment box */
10616{ MKTAG('l','h','v','C'), mov_read_lhvc },
10617{ MKTAG('l','v','c','C'), mov_read_glbl },
10618{ MKTAG('a','p','v','C'), mov_read_glbl },
10619#if CONFIG_IAMFDEC
10620{ MKTAG('i','a','c','b'), mov_read_iacb },
10621#endif
10622{ MKTAG('s','r','a','t'), mov_read_srat },
10623{ MKTAG('v','m','h','d'), mov_read_vmhd },
10624{ MKTAG('m','h','a','C'), mov_read_mhac },
10625{ 0, NULL }
10626};
10627
10629{
10630 int64_t total_size = 0;
10631 MOVAtom a;
10632 int i;
10633
10634 if (c->atom_depth > 10) {
10635 av_log(c->fc, AV_LOG_ERROR, "Atoms too deeply nested\n");
10636 return AVERROR_INVALIDDATA;
10637 }
10638 c->atom_depth ++;
10639
10640 if (atom.size < 0)
10641 atom.size = INT64_MAX;
10642 while (total_size <= atom.size - 8) {
10643 int (*parse)(MOVContext*, AVIOContext*, MOVAtom) = NULL;
10644 a.size = avio_rb32(pb);
10645 a.type = avio_rl32(pb);
10646 if (avio_feof(pb))
10647 break;
10648 if (((a.type == MKTAG('f','r','e','e') && c->moov_retry) ||
10649 a.type == MKTAG('h','o','o','v')) &&
10650 a.size >= 8 &&
10651 c->fc->strict_std_compliance < FF_COMPLIANCE_STRICT) {
10652 uint32_t type;
10653 avio_skip(pb, 4);
10654 type = avio_rl32(pb);
10655 if (avio_feof(pb))
10656 break;
10657 avio_seek(pb, -8, SEEK_CUR);
10658 if (type == MKTAG('m','v','h','d') ||
10659 type == MKTAG('c','m','o','v')) {
10660 av_log(c->fc, AV_LOG_ERROR, "Detected moov in a free or hoov atom.\n");
10661 a.type = MKTAG('m','o','o','v');
10662 }
10663 }
10664 if (atom.type != MKTAG('r','o','o','t') &&
10665 atom.type != MKTAG('m','o','o','v')) {
10666 if (a.type == MKTAG('t','r','a','k') ||
10667 a.type == MKTAG('m','d','a','t')) {
10668 av_log(c->fc, AV_LOG_ERROR, "Broken file, trak/mdat not at top-level\n");
10669 avio_skip(pb, -8);
10670 c->atom_depth --;
10671 return 0;
10672 }
10673 }
10674 total_size += 8;
10675 if (a.size == 1 && total_size + 8 <= atom.size) { /* 64 bit extended size */
10676 a.size = avio_rb64(pb) - 8;
10677 total_size += 8;
10678 }
10679 av_log(c->fc, AV_LOG_TRACE, "type:'%s' parent:'%s' sz: %"PRId64" %"PRId64" %"PRId64"\n",
10680 av_fourcc2str(a.type), av_fourcc2str(atom.type), a.size, total_size, atom.size);
10681 if (a.size == 0) {
10682 a.size = atom.size - total_size + 8;
10683 }
10684 if (a.size < 0)
10685 break;
10686 a.size -= 8;
10687 if (a.size < 0)
10688 break;
10689 a.size = FFMIN(a.size, atom.size - total_size);
10690
10691 for (i = 0; mov_default_parse_table[i].type; i++)
10692 if (mov_default_parse_table[i].type == a.type) {
10694 break;
10695 }
10696
10697 // container is user data
10698 if (!parse && (atom.type == MKTAG('u','d','t','a') ||
10699 atom.type == MKTAG('i','l','s','t')))
10701
10702 // Supports parsing the QuickTime Metadata Keys.
10703 // https://developer.apple.com/library/mac/documentation/QuickTime/QTFF/Metadata/Metadata.html
10704 if (!parse && c->found_hdlr_mdta &&
10705 atom.type == MKTAG('m','e','t','a') &&
10706 a.type == MKTAG('k','e','y','s') &&
10707 c->meta_keys_count == 0) {
10709 }
10710
10711 if (!parse) { /* skip leaf atoms data */
10712 avio_skip(pb, a.size);
10713 } else {
10714 int64_t start_pos = avio_tell(pb);
10715 int64_t left;
10716 int err = parse(c, pb, a);
10717 if (err < 0) {
10718 c->atom_depth --;
10719 return err;
10720 }
10721 if (c->found_moov && c->found_mdat && a.size <= INT64_MAX - start_pos &&
10722 ((!(pb->seekable & AVIO_SEEKABLE_NORMAL) || c->fc->flags & AVFMT_FLAG_IGNIDX || c->frag_index.complete) ||
10723 start_pos + a.size == avio_size(pb))) {
10724 if (!(pb->seekable & AVIO_SEEKABLE_NORMAL) || c->fc->flags & AVFMT_FLAG_IGNIDX || c->frag_index.complete)
10725 c->next_root_atom = start_pos + a.size;
10726 c->atom_depth --;
10727 return 0;
10728 }
10729 left = a.size - avio_tell(pb) + start_pos;
10730 if (left > 0) /* skip garbage at atom end */
10731 avio_skip(pb, left);
10732 else if (left < 0) {
10733 av_log(c->fc, AV_LOG_WARNING,
10734 "overread end of atom '%s' by %"PRId64" bytes\n",
10735 av_fourcc2str(a.type), -left);
10736 avio_seek(pb, left, SEEK_CUR);
10737 }
10738 }
10739
10740 total_size += a.size;
10741 }
10742
10743 if (total_size < atom.size && atom.size < 0x7ffff)
10744 avio_skip(pb, atom.size - total_size);
10745
10746 c->atom_depth --;
10747 return 0;
10748}
10749
10750static int mov_probe(const AVProbeData *p)
10751{
10753 uint32_t tag;
10754 int score = 0;
10755 int moov_offset = -1;
10756
10757 /* check file header */
10758 offset = 0;
10759 for (;;) {
10760 int64_t size;
10761 int minsize = 8;
10762 /* ignore invalid offset */
10763 if ((offset + 8ULL) > (unsigned int)p->buf_size)
10764 break;
10765 size = AV_RB32(p->buf + offset);
10766 if (size == 1 && offset + 16 <= (unsigned int)p->buf_size) {
10767 size = AV_RB64(p->buf+offset + 8);
10768 minsize = 16;
10769 } else if (size == 0) {
10770 size = p->buf_size - offset;
10771 }
10772 if (size < minsize) {
10773 offset += 4;
10774 continue;
10775 }
10776 tag = AV_RL32(p->buf + offset + 4);
10777 switch(tag) {
10778 /* check for obvious tags */
10779 case MKTAG('m','o','o','v'):
10780 moov_offset = offset + 4;
10782 case MKTAG('m','d','a','t'):
10783 case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
10784 case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
10785 case MKTAG('f','t','y','p'):
10786 if (tag == MKTAG('f','t','y','p') &&
10787 ( AV_RL32(p->buf + offset + 8) == MKTAG('j','p','2',' ')
10788 || AV_RL32(p->buf + offset + 8) == MKTAG('j','p','x',' ')
10789 || AV_RL32(p->buf + offset + 8) == MKTAG('j','x','l',' ')
10790 )) {
10791 score = FFMAX(score, 5);
10792 } else {
10793 score = AVPROBE_SCORE_MAX;
10794 }
10795 break;
10796 /* those are more common words, so rate then a bit less */
10797 case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
10798 case MKTAG('w','i','d','e'):
10799 case MKTAG('f','r','e','e'):
10800 case MKTAG('j','u','n','k'):
10801 case MKTAG('p','i','c','t'):
10802 score = FFMAX(score, AVPROBE_SCORE_MAX - 5);
10803 break;
10804 case MKTAG(0x82,0x82,0x7f,0x7d):
10805 score = FFMAX(score, AVPROBE_SCORE_EXTENSION - 5);
10806 break;
10807 case MKTAG('s','k','i','p'):
10808 case MKTAG('u','u','i','d'):
10809 case MKTAG('p','r','f','l'):
10810 /* if we only find those cause probedata is too small at least rate them */
10811 score = FFMAX(score, AVPROBE_SCORE_EXTENSION);
10812 break;
10813 }
10814 if (size > INT64_MAX - offset)
10815 break;
10816 offset += size;
10817 }
10818 if (score > AVPROBE_SCORE_MAX - 50 && moov_offset != -1) {
10819 /* moov atom in the header - we should make sure that this is not a
10820 * MOV-packed MPEG-PS */
10821 offset = moov_offset;
10822
10823 while (offset < (p->buf_size - 16)) { /* Sufficient space */
10824 /* We found an actual hdlr atom */
10825 if (AV_RL32(p->buf + offset ) == MKTAG('h','d','l','r') &&
10826 AV_RL32(p->buf + offset + 8) == MKTAG('m','h','l','r') &&
10827 AV_RL32(p->buf + offset + 12) == MKTAG('M','P','E','G')) {
10828 av_log(NULL, AV_LOG_WARNING, "Found media data tag MPEG indicating this is a MOV-packed MPEG-PS.\n");
10829 /* We found a media handler reference atom describing an
10830 * MPEG-PS-in-MOV, return a
10831 * low score to force expanding the probe window until
10832 * mpegps_probe finds what it needs */
10833 return 5;
10834 } else {
10835 /* Keep looking */
10836 offset += 2;
10837 }
10838 }
10839 }
10840
10841 return score;
10842}
10843
10844// must be done after parsing all trak because there's no order requirement
10846{
10847 MOVContext *mov = s->priv_data;
10848 MOVStreamContext *sc;
10849 int64_t cur_pos;
10850 int i, j;
10851 int chapter_track;
10852
10853 for (j = 0; j < mov->nb_chapter_tracks; j++) {
10854 AVStream *st = NULL;
10855 FFStream *sti = NULL;
10856 chapter_track = mov->chapter_tracks[j];
10857 for (i = 0; i < s->nb_streams; i++) {
10858 sc = mov->fc->streams[i]->priv_data;
10859 if (sc->id == chapter_track) {
10860 st = s->streams[i];
10861 break;
10862 }
10863 }
10864 if (!st) {
10865 av_log(s, AV_LOG_ERROR, "Referenced QT chapter track not found\n");
10866 continue;
10867 }
10868 sti = ffstream(st);
10869
10870 sc = st->priv_data;
10871 cur_pos = avio_tell(sc->pb);
10872
10875 if (!st->attached_pic.data && sti->nb_index_entries) {
10876 // Retrieve the first frame, if possible
10877 AVIndexEntry *sample = &sti->index_entries[0];
10878 if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
10879 av_log(s, AV_LOG_ERROR, "Failed to retrieve first frame\n");
10880 goto finish;
10881 }
10882
10883 if (ff_add_attached_pic(s, st, sc->pb, NULL, sample->size) < 0)
10884 goto finish;
10885 }
10886 } else {
10889 st->discard = AVDISCARD_ALL;
10890 for (int i = 0; i < sti->nb_index_entries; i++) {
10892 int64_t end = i+1 < sti->nb_index_entries ? sti->index_entries[i+1].timestamp : st->duration;
10893 uint8_t *title;
10894 uint16_t ch;
10895 int len, title_len;
10896
10897 if (end < sample->timestamp) {
10898 av_log(s, AV_LOG_WARNING, "ignoring stream duration which is shorter than chapters\n");
10899 end = AV_NOPTS_VALUE;
10900 }
10901
10902 if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
10903 av_log(s, AV_LOG_ERROR, "Chapter %d not found in file\n", i);
10904 goto finish;
10905 }
10906
10907 // the first two bytes are the length of the title
10908 len = avio_rb16(sc->pb);
10909 if (len > sample->size-2)
10910 continue;
10911 title_len = 2*len + 1;
10912 if (!(title = av_mallocz(title_len)))
10913 goto finish;
10914
10915 // The samples could theoretically be in any encoding if there's an encd
10916 // atom following, but in practice are only utf-8 or utf-16, distinguished
10917 // instead by the presence of a BOM
10918 if (!len) {
10919 title[0] = 0;
10920 } else {
10921 ch = avio_rb16(sc->pb);
10922 if (ch == 0xfeff)
10923 avio_get_str16be(sc->pb, len, title, title_len);
10924 else if (ch == 0xfffe)
10925 avio_get_str16le(sc->pb, len, title, title_len);
10926 else {
10927 AV_WB16(title, ch);
10928 if (len == 1 || len == 2)
10929 title[len] = 0;
10930 else
10931 avio_get_str(sc->pb, INT_MAX, title + 2, len - 1);
10932 }
10933 }
10934
10935 avpriv_new_chapter(s, i, st->time_base, sample->timestamp, end, title);
10936 av_freep(&title);
10937 }
10938 }
10939finish:
10940 avio_seek(sc->pb, cur_pos, SEEK_SET);
10941 }
10942}
10943
10945 int64_t value, int flags)
10946{
10947 AVTimecode tc;
10948 char buf[AV_TIMECODE_STR_SIZE];
10949 AVRational rate = st->avg_frame_rate;
10950 int ret = av_timecode_init(&tc, rate, flags, 0, s);
10951 if (ret < 0)
10952 return ret;
10953 av_dict_set(&st->metadata, "timecode",
10954 av_timecode_make_string(&tc, buf, value), 0);
10955 return 0;
10956}
10957
10959{
10960 MOVStreamContext *sc = st->priv_data;
10961 FFStream *const sti = ffstream(st);
10962 char buf[AV_TIMECODE_STR_SIZE];
10963 int64_t cur_pos = avio_tell(sc->pb);
10964 int hh, mm, ss, ff, drop;
10965
10966 if (!sti->nb_index_entries)
10967 return -1;
10968
10969 avio_seek(sc->pb, sti->index_entries->pos, SEEK_SET);
10970 avio_skip(s->pb, 13);
10971 hh = avio_r8(s->pb);
10972 mm = avio_r8(s->pb);
10973 ss = avio_r8(s->pb);
10974 drop = avio_r8(s->pb);
10975 ff = avio_r8(s->pb);
10976 snprintf(buf, AV_TIMECODE_STR_SIZE, "%02d:%02d:%02d%c%02d",
10977 hh, mm, ss, drop ? ';' : ':', ff);
10978 av_dict_set(&st->metadata, "timecode", buf, 0);
10979
10980 avio_seek(sc->pb, cur_pos, SEEK_SET);
10981 return 0;
10982}
10983
10985{
10986 MOVStreamContext *sc = st->priv_data;
10987 FFStream *const sti = ffstream(st);
10988 int flags = 0;
10989 int64_t cur_pos = avio_tell(sc->pb);
10990 int64_t value;
10991 AVRational tc_rate = st->avg_frame_rate;
10992 int tmcd_nb_frames = sc->tmcd_nb_frames;
10993 int rounded_tc_rate;
10994
10995 if (!sti->nb_index_entries)
10996 return -1;
10997
10998 if (!tc_rate.num || !tc_rate.den || !tmcd_nb_frames)
10999 return -1;
11000
11001 avio_seek(sc->pb, sti->index_entries->pos, SEEK_SET);
11002 value = avio_rb32(s->pb);
11003
11004 if (sc->tmcd_flags & 0x0001) flags |= AV_TIMECODE_FLAG_DROPFRAME;
11005 if (sc->tmcd_flags & 0x0002) flags |= AV_TIMECODE_FLAG_24HOURSMAX;
11006 if (sc->tmcd_flags & 0x0004) flags |= AV_TIMECODE_FLAG_ALLOWNEGATIVE;
11007
11008 /* Assume Counter flag is set to 1 in tmcd track (even though it is likely
11009 * not the case) and thus assume "frame number format" instead of QT one.
11010 * No sample with tmcd track can be found with a QT timecode at the moment,
11011 * despite what the tmcd track "suggests" (Counter flag set to 0 means QT
11012 * format). */
11013
11014 /* 60 fps content have tmcd_nb_frames set to 30 but tc_rate set to 60, so
11015 * we multiply the frame number with the quotient.
11016 * See tickets #9492, #9710. */
11017 rounded_tc_rate = (tc_rate.num + tc_rate.den / 2LL) / tc_rate.den;
11018 /* Work around files where tmcd_nb_frames is rounded down from frame rate
11019 * instead of up. See ticket #5978. */
11020 if (tmcd_nb_frames == tc_rate.num / tc_rate.den &&
11021 s->strict_std_compliance < FF_COMPLIANCE_STRICT)
11022 tmcd_nb_frames = rounded_tc_rate;
11023 value = av_rescale(value, rounded_tc_rate, tmcd_nb_frames);
11024
11026
11027 avio_seek(sc->pb, cur_pos, SEEK_SET);
11028 return 0;
11029}
11030
11032 int i;
11033 if (!index || !*index) return;
11034 for (i = 0; i < (*index)->nb_encrypted_samples; i++) {
11035 av_encryption_info_free((*index)->encrypted_samples[i]);
11036 }
11037 av_freep(&(*index)->encrypted_samples);
11038 av_freep(&(*index)->auxiliary_info_sizes);
11039 av_freep(&(*index)->auxiliary_offsets);
11040 av_freep(index);
11041}
11042
11044{
11045 MOVStreamContext *sc = st->priv_data;
11046
11047 if (!sc || --sc->refcount) {
11048 st->priv_data = NULL;
11049 return;
11050 }
11051
11052 av_freep(&sc->tts_data);
11053 for (int i = 0; i < sc->drefs_count; i++) {
11054 av_freep(&sc->drefs[i].path);
11055 av_freep(&sc->drefs[i].dir);
11056 }
11057 av_freep(&sc->drefs);
11058
11059 sc->drefs_count = 0;
11060
11061 if (!sc->pb_is_copied)
11062 ff_format_io_close(s, &sc->pb);
11063
11064 sc->pb = NULL;
11065 av_freep(&sc->chunk_offsets);
11066 av_freep(&sc->stsc_data);
11067 av_freep(&sc->sample_sizes);
11068 av_freep(&sc->keyframes);
11069 av_freep(&sc->ctts_data);
11070 av_freep(&sc->stts_data);
11071 av_freep(&sc->sdtp_data);
11072 av_freep(&sc->stps_data);
11073 av_freep(&sc->elst_data);
11074 av_freep(&sc->rap_group);
11075 av_freep(&sc->sync_group);
11076 av_freep(&sc->sgpd_sync);
11080 av_freep(&sc->index_ranges);
11081 for (int i = 0; i < sc->nb_tref_tags; i++)
11082 av_freep(&sc->tref_tags[i].id);
11083 av_freep(&sc->tref_tags);
11084
11085 if (sc->extradata)
11086 for (int i = 0; i < sc->stsd_count; i++)
11087 av_free(sc->extradata[i]);
11088 av_freep(&sc->extradata);
11090
11094 av_freep(&sc->cenc.aes_ctx);
11095
11096 av_freep(&sc->stereo3d);
11097 av_freep(&sc->spherical);
11098 av_freep(&sc->mastering);
11099 av_freep(&sc->coll);
11100 av_freep(&sc->ambient);
11101
11102#if CONFIG_IAMFDEC
11103 if (sc->iamf)
11105#endif
11106 av_freep(&sc->iamf);
11107}
11108
11110{
11111 MOVContext *mov = s->priv_data;
11112 int i, j;
11113
11114 for (i = 0; i < s->nb_streams; i++) {
11115 AVStream *st = s->streams[i];
11116
11118 }
11119
11120 av_freep(&mov->dv_demux);
11122 mov->dv_fctx = NULL;
11123
11124 if (mov->meta_keys) {
11125 for (i = 1; i < mov->meta_keys_count; i++) {
11126 av_freep(&mov->meta_keys[i]);
11127 }
11128 av_freep(&mov->meta_keys);
11129 }
11130
11131 av_freep(&mov->trex_data);
11132 av_freep(&mov->bitrates);
11133
11134 for (i = 0; i < mov->frag_index.nb_items; i++) {
11136 for (j = 0; j < mov->frag_index.item[i].nb_stream_info; j++) {
11137 mov_free_encryption_index(&frag[j].encryption_index);
11138 }
11140 }
11141 av_freep(&mov->frag_index.item);
11142
11143 av_freep(&mov->aes_decrypt);
11144 av_freep(&mov->chapter_tracks);
11145 for (i = 0; i < mov->nb_heif_item; i++) {
11146 if (!mov->heif_item[i])
11147 continue;
11148 av_freep(&mov->heif_item[i]->name);
11152 av_exif_free(&mov->heif_item[i]->ifd);
11153 av_freep(&mov->heif_item[i]);
11154 }
11155 av_freep(&mov->heif_item);
11156 for (i = 0; i < mov->nb_heif_group; i++) {
11160 }
11161 av_freep(&mov->heif_group);
11162
11163 return 0;
11164}
11165
11166static int tmcd_is_referenced(AVFormatContext *s, int tmcd_id)
11167{
11168 int i;
11169
11170 for (i = 0; i < s->nb_streams; i++) {
11171 AVStream *st = s->streams[i];
11172 MOVStreamContext *sc = st->priv_data;
11173 MovTref *tag = mov_find_tref_tag(sc, MKTAG('t','m','c','d'));
11174
11175 if (!tag)
11176 continue;
11177 if (mov_find_tref_id(tag, tmcd_id))
11178 return 1;
11179 }
11180 return 0;
11181}
11182
11183/* look for a tmcd track not referenced by any video track, and export it globally */
11185{
11186 int i;
11187
11188 for (i = 0; i < s->nb_streams; i++) {
11189 AVStream *st = s->streams[i];
11190
11191 if (st->codecpar->codec_tag == MKTAG('t','m','c','d') &&
11192 !tmcd_is_referenced(s, st->id)) {
11193 AVDictionaryEntry *tcr = av_dict_get(st->metadata, "timecode", NULL, 0);
11194 if (tcr) {
11195 av_dict_set(&s->metadata, "timecode", tcr->value, 0);
11196 break;
11197 }
11198 }
11199 }
11200}
11201
11203{
11204 int version, fieldlength, i, j;
11206 uint32_t size = avio_rb32(f);
11207 unsigned track_id, item_count;
11208
11209 if (avio_rb32(f) != MKBETAG('t', 'f', 'r', 'a')) {
11210 return 1;
11211 }
11212 /* A tfra box can not be smaller than its 24-byte header. A size of 0
11213 * would make mov_read_mfra() re-read the same box forever. */
11214 if (size < 24) {
11215 av_log(mov->fc, AV_LOG_ERROR, "Invalid tfra size %"PRIu32"\n", size);
11216 return AVERROR_INVALIDDATA;
11217 }
11218 av_log(mov->fc, AV_LOG_VERBOSE, "found tfra\n");
11219
11220 version = avio_r8(f);
11221 avio_rb24(f);
11222 track_id = avio_rb32(f);
11223 fieldlength = avio_rb32(f);
11224 item_count = avio_rb32(f);
11225 for (i = 0; i < item_count; i++) {
11226 int64_t time, offset;
11227 int index;
11228 MOVFragmentStreamInfo * frag_stream_info;
11229
11230 if (avio_feof(f)) {
11231 return AVERROR_INVALIDDATA;
11232 }
11233
11234 if (version == 1) {
11235 time = avio_rb64(f);
11236 offset = avio_rb64(f);
11237 } else {
11238 time = avio_rb32(f);
11239 offset = avio_rb32(f);
11240 }
11241
11242 // The first sample of each stream in a fragment is always a random
11243 // access sample. So it's entry in the tfra can be used as the
11244 // initial PTS of the fragment.
11246 frag_stream_info = get_frag_stream_info(&mov->frag_index, index, track_id);
11247 if (frag_stream_info &&
11248 frag_stream_info->first_tfra_pts == AV_NOPTS_VALUE)
11249 frag_stream_info->first_tfra_pts = time;
11250
11251 for (j = 0; j < ((fieldlength >> 4) & 3) + 1; j++)
11252 avio_r8(f);
11253 for (j = 0; j < ((fieldlength >> 2) & 3) + 1; j++)
11254 avio_r8(f);
11255 for (j = 0; j < ((fieldlength >> 0) & 3) + 1; j++)
11256 avio_r8(f);
11257 }
11258
11259 avio_seek(f, pos + size, SEEK_SET);
11260 return 0;
11261}
11262
11264{
11265 int64_t stream_size = avio_size(f);
11266 int64_t original_pos = avio_tell(f);
11267 int64_t seek_ret;
11268 int ret = -1;
11269 if ((seek_ret = avio_seek(f, stream_size - 4, SEEK_SET)) < 0) {
11270 ret = seek_ret;
11271 goto fail;
11272 }
11273 c->mfra_size = avio_rb32(f);
11274 c->have_read_mfra_size = 1;
11275 if (!c->mfra_size || c->mfra_size > stream_size) {
11276 av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (unreasonable size)\n");
11277 goto fail;
11278 }
11279 if ((seek_ret = avio_seek(f, -((int64_t) c->mfra_size), SEEK_CUR)) < 0) {
11280 ret = seek_ret;
11281 goto fail;
11282 }
11283 if (avio_rb32(f) != c->mfra_size) {
11284 av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (size mismatch)\n");
11285 goto fail;
11286 }
11287 if (avio_rb32(f) != MKBETAG('m', 'f', 'r', 'a')) {
11288 av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (tag mismatch)\n");
11289 goto fail;
11290 }
11291 av_log(c->fc, AV_LOG_VERBOSE, "stream has mfra\n");
11292 do {
11293 ret = read_tfra(c, f);
11294 if (ret < 0)
11295 goto fail;
11296 } while (!ret);
11297 ret = 0;
11298 c->frag_index.complete = 1;
11299fail:
11300 seek_ret = avio_seek(f, original_pos, SEEK_SET);
11301 if (seek_ret < 0) {
11302 av_log(c->fc, AV_LOG_ERROR,
11303 "failed to seek back after looking for mfra\n");
11304 ret = seek_ret;
11305 }
11306 return ret;
11307}
11308
11310 AVPacketSideData **coded_side_data, int *nb_coded_side_data,
11311 const HEIFItem *item)
11312{
11313 AVPacketSideData *sd =
11314 (AVPacketSideData *)av_packet_side_data_get(*coded_side_data,
11315 *nb_coded_side_data,
11317 const AVExifMetadata *ifd = &item->ifd;
11318 AVBufferRef *buf = NULL;
11319 int err;
11320
11321 if (sd)
11322 return 0;
11323
11324 err = av_exif_write(s, ifd, &buf, AV_EXIF_TIFF_HEADER);
11325 if (err < 0)
11326 return err;
11327
11328 sd = av_packet_side_data_new(coded_side_data, nb_coded_side_data,
11329 AV_PKT_DATA_EXIF, buf->size, 0);
11330 if (!sd) {
11331 av_buffer_unref(&buf);
11332 return AVERROR(ENOMEM);
11333 }
11334 memcpy(sd->data, buf->data, buf->size);
11335
11336 av_buffer_unref(&buf);
11337
11338 return 0;
11339}
11340
11341static int set_icc_profile_from_item(AVPacketSideData **coded_side_data, int *nb_coded_side_data,
11342 const HEIFItem *item)
11343{
11344 AVPacketSideData *sd =
11345 (AVPacketSideData *)av_packet_side_data_get(*coded_side_data,
11346 *nb_coded_side_data,
11348
11349 if (sd)
11350 return 0;
11351
11352 sd = av_packet_side_data_new(coded_side_data, nb_coded_side_data,
11354 item->icc_profile_size, 0);
11355 if (!sd)
11356 return AVERROR(ENOMEM);
11357
11358 memcpy(sd->data, item->icc_profile, item->icc_profile_size);
11359
11360 return 0;
11361}
11362
11363static int set_display_matrix_from_item(AVPacketSideData **coded_side_data, int *nb_coded_side_data,
11364 const HEIFItem *item)
11365{
11366 int32_t *matrix;
11367 AVPacketSideData *sd =
11368 (AVPacketSideData *)av_packet_side_data_get(*coded_side_data,
11369 *nb_coded_side_data,
11371
11372 if (sd)
11373 return 0;
11374
11375 sd = av_packet_side_data_new(coded_side_data, nb_coded_side_data,
11377 9 * sizeof(*matrix), 0);
11378 if (!sd)
11379 return AVERROR(ENOMEM);
11380
11381 matrix = (int32_t*)sd->data;
11382 /* rotation is in the counter-clockwise direction whereas
11383 * av_display_rotation_set() expects its argument to be
11384 * oriented clockwise, so we need to negate it. */
11387
11388 return 0;
11389}
11390
11392 AVStreamGroupTileGrid *tile_grid)
11393{
11394 MOVContext *c = s->priv_data;
11395 const HEIFItem *item = grid->item;
11396 int64_t coded_width = 0, coded_height = 0;
11397 int64_t offset = 0, pos = avio_tell(s->pb);
11398 int64_t x = 0, y = 0;
11399 int i = 0;
11400 int tile_rows, tile_cols;
11401 int flags, size;
11402
11403 if (!(s->pb->seekable & AVIO_SEEKABLE_NORMAL)) {
11404 av_log(c->fc, AV_LOG_INFO, "grid box with non seekable input\n");
11405 return AVERROR_PATCHWELCOME;
11406 }
11407 if (item->is_idat_relative) {
11408 if (!c->idat_offset) {
11409 av_log(c->fc, AV_LOG_ERROR, "missing idat box required by the image grid\n");
11410 return AVERROR_INVALIDDATA;
11411 }
11412 offset = c->idat_offset;
11413 }
11414
11415 if (offset > INT64_MAX - item->extent_offset)
11416 return AVERROR_INVALIDDATA;
11417
11418 avio_seek(s->pb, item->extent_offset + offset, SEEK_SET);
11419
11420 avio_r8(s->pb); /* version */
11421 flags = avio_r8(s->pb);
11422
11423 tile_rows = avio_r8(s->pb) + 1;
11424 tile_cols = avio_r8(s->pb) + 1;
11425 /* actual width and height of output image */
11426 tile_grid->width = (flags & 1) ? avio_rb32(s->pb) : avio_rb16(s->pb);
11427 tile_grid->height = (flags & 1) ? avio_rb32(s->pb) : avio_rb16(s->pb);
11428
11429 av_log(c->fc, AV_LOG_TRACE, "grid: grid_rows %d grid_cols %d output_width %d output_height %d\n",
11430 tile_rows, tile_cols, tile_grid->width, tile_grid->height);
11431
11432 avio_seek(s->pb, pos, SEEK_SET);
11433
11435 tile_grid->nb_tiles = grid->nb_items;
11436
11437 if (tile_grid->nb_tiles != size)
11438 return AVERROR_INVALIDDATA;
11439
11440 for (int i = 0; i < tile_cols; i++)
11441 coded_width += grid->item_list[i]->width;
11442 for (int i = 0; i < size; i += tile_cols)
11443 coded_height += grid->item_list[i]->height;
11444
11445 if (coded_width > INT_MAX || coded_height > INT_MAX)
11446 return AVERROR_INVALIDDATA;
11447 if (coded_width == 0 || coded_height == 0)
11448 return AVERROR_INVALIDDATA;
11449
11450 tile_grid->coded_width = coded_width;
11451 tile_grid->coded_height = coded_height;
11452
11453 tile_grid->offsets = av_calloc(tile_grid->nb_tiles, sizeof(*tile_grid->offsets));
11454 if (!tile_grid->offsets)
11455 return AVERROR(ENOMEM);
11456
11457 while (y < tile_grid->coded_height) {
11458 int left_col = i;
11459
11460 while (x < tile_grid->coded_width) {
11461 if (i == tile_grid->nb_tiles)
11462 return AVERROR_INVALIDDATA;
11463
11464 tile_grid->offsets[i].idx = grid->item_idx_list[i];
11465 tile_grid->offsets[i].horizontal = x;
11466 tile_grid->offsets[i].vertical = y;
11467
11468 x += grid->item_list[i++]->width;
11469 }
11470
11471 if (x > tile_grid->coded_width) {
11472 av_log(c->fc, AV_LOG_ERROR, "Non uniform HEIF tiles\n");
11473 return AVERROR_INVALIDDATA;
11474 }
11475
11476 x = 0;
11477 y += grid->item_list[left_col]->height;
11478 }
11479
11480 if (y > tile_grid->coded_height || i != tile_grid->nb_tiles) {
11481 av_log(c->fc, AV_LOG_ERROR, "Non uniform HEIF tiles\n");
11482 return AVERROR_INVALIDDATA;
11483 }
11484
11485 return 0;
11486}
11487
11489 AVStreamGroupTileGrid *tile_grid)
11490{
11491 MOVContext *c = s->priv_data;
11492 const HEIFItem *item = grid->item;
11493 uint16_t canvas_fill_value[4];
11494 int64_t offset = 0, pos = avio_tell(s->pb);
11495 int ret = 0, flags;
11496
11497 if (!(s->pb->seekable & AVIO_SEEKABLE_NORMAL)) {
11498 av_log(c->fc, AV_LOG_INFO, "iovl box with non seekable input\n");
11499 return AVERROR_PATCHWELCOME;
11500 }
11501 if (item->is_idat_relative) {
11502 if (!c->idat_offset) {
11503 av_log(c->fc, AV_LOG_ERROR, "missing idat box required by the image overlay\n");
11504 return AVERROR_INVALIDDATA;
11505 }
11506 offset = c->idat_offset;
11507 }
11508
11509 if (offset > INT64_MAX - item->extent_offset)
11510 return AVERROR_INVALIDDATA;
11511
11512 avio_seek(s->pb, item->extent_offset + offset, SEEK_SET);
11513
11514 avio_r8(s->pb); /* version */
11515 flags = avio_r8(s->pb);
11516
11517 for (int i = 0; i < 4; i++)
11518 canvas_fill_value[i] = avio_rb16(s->pb);
11519 av_log(c->fc, AV_LOG_TRACE, "iovl: canvas_fill_value { %u, %u, %u, %u }\n",
11520 canvas_fill_value[0], canvas_fill_value[1],
11521 canvas_fill_value[2], canvas_fill_value[3]);
11522 for (int i = 0; i < 4; i++)
11523 tile_grid->background[i] = canvas_fill_value[i];
11524
11525 /* actual width and height of output image */
11526 tile_grid->width =
11527 tile_grid->coded_width = (flags & 1) ? avio_rb32(s->pb) : avio_rb16(s->pb);
11528 tile_grid->height =
11529 tile_grid->coded_height = (flags & 1) ? avio_rb32(s->pb) : avio_rb16(s->pb);
11530
11531 av_log(c->fc, AV_LOG_TRACE, "iovl: output_width %d, output_height %d\n",
11532 tile_grid->width, tile_grid->height);
11533
11534 tile_grid->nb_tiles = grid->nb_items;
11535 tile_grid->offsets = av_malloc_array(tile_grid->nb_tiles, sizeof(*tile_grid->offsets));
11536 if (!tile_grid->offsets) {
11537 ret = AVERROR(ENOMEM);
11538 goto fail;
11539 }
11540
11541 for (int i = 0; i < tile_grid->nb_tiles; i++) {
11542 tile_grid->offsets[i].idx = grid->item_idx_list[i];
11543 tile_grid->offsets[i].horizontal = (flags & 1) ? avio_rb32(s->pb) : avio_rb16(s->pb);
11544 tile_grid->offsets[i].vertical = (flags & 1) ? avio_rb32(s->pb) : avio_rb16(s->pb);
11545 av_log(c->fc, AV_LOG_TRACE, "iovl: stream_idx[%d] %u, "
11546 "horizontal_offset[%d] %d, vertical_offset[%d] %d\n",
11547 i, tile_grid->offsets[i].idx,
11548 i, tile_grid->offsets[i].horizontal, i, tile_grid->offsets[i].vertical);
11549 }
11550
11551fail:
11552 avio_seek(s->pb, pos, SEEK_SET);
11553
11554 return ret;
11555}
11556
11558{
11559 MOVContext *c = s->priv_data;
11560 AVExifMetadata *ifd = &item->ifd;
11561 uint8_t *buf;
11562 int64_t offset = 0, pos = avio_tell(s->pb);
11563 unsigned orientation_id = av_exif_get_tag_id("Orientation");
11564 int err;
11565
11566 if (!(s->pb->seekable & AVIO_SEEKABLE_NORMAL)) {
11567 av_log(c->fc, AV_LOG_WARNING, "Exif metadata with non seekable input\n");
11568 return AVERROR_PATCHWELCOME;
11569 }
11570 if (ref->is_idat_relative) {
11571 if (!c->idat_offset) {
11572 av_log(c->fc, AV_LOG_ERROR, "missing idat box required by the Exif metadata\n");
11573 return AVERROR_INVALIDDATA;
11574 }
11575 offset = c->idat_offset;
11576 }
11577
11578 buf = av_malloc(ref->extent_length);
11579 if (!buf)
11580 return AVERROR(ENOMEM);
11581
11582 if (offset > INT64_MAX - ref->extent_offset) {
11583 err = AVERROR(ENOMEM);
11584 goto fail;
11585 }
11586
11587 avio_seek(s->pb, ref->extent_offset + offset, SEEK_SET);
11588 err = avio_read(s->pb, buf, ref->extent_length);
11589 if (err != ref->extent_length) {
11590 if (err > 0)
11591 err = AVERROR_INVALIDDATA;
11592 goto fail;
11593 }
11594
11595 // HEIF spec states that Exif metadata is informative. The irot item property is
11596 // the normative source of rotation information. So we remove any Orientation tag
11597 // present in the Exif buffer.
11598 err = av_exif_parse_buffer(s, buf, ref->extent_length, ifd, AV_EXIF_T_OFF);
11599 if (err < 0) {
11600 av_log(s, AV_LOG_ERROR, "Unable to parse Exif metadata\n");
11601 goto fail;
11602 }
11603
11604 err = av_exif_remove_entry(s, ifd, orientation_id, 0);
11605 if (err < 0)
11606 goto fail;
11607
11608 err = 0;
11609fail:
11610 av_free(buf);
11611 if (err < 0)
11612 av_exif_free(ifd);
11613 avio_seek(s->pb, pos, SEEK_SET);
11614
11615 return err;
11616}
11617
11619 AVPacketSideData **coded_side_data,
11620 int *nb_coded_side_data)
11621{
11622 int err;
11623
11624 /* exif */
11625 if (item->ifd.count) {
11626 err = set_exif_from_item(s, coded_side_data, nb_coded_side_data, item);
11627 if (err < 0)
11628 return err;
11629 }
11630
11631 /* rotation */
11632 if (item->rotation || item->hflip || item->vflip) {
11633 err = set_display_matrix_from_item(coded_side_data, nb_coded_side_data, item);
11634 if (err < 0)
11635 return err;
11636 }
11637
11638 /* ICC profile */
11639 if (item->icc_profile_size) {
11640 err = set_icc_profile_from_item(coded_side_data, nb_coded_side_data, item);
11641 if (err < 0)
11642 return err;
11643 }
11644
11645 return 0;
11646}
11647
11649 AVPacketSideData **coded_side_data,
11650 int *nb_coded_side_data)
11651{
11652 MOVContext *mov = s->priv_data;
11653 int err;
11654
11655 for (int j = 0; j < item->nb_iref_from_list; j++) {
11657
11658 av_assert0(ref);
11659 switch(ref->type) {
11660 case MKTAG('E','x','i','f'):
11661 err = mov_parse_exif_item(s, item, ref);
11662 if (err < 0 && (s->error_recognition & AV_EF_EXPLODE))
11663 return err;
11664 break;
11665 default:
11666 break;
11667 }
11668 }
11669
11670 err = mov_apply_heif_item_references(s, item, coded_side_data, nb_coded_side_data);
11671 if (err < 0)
11672 return err;
11673
11674 return 0;
11675}
11676
11678{
11679 MOVContext *mov = s->priv_data;
11680
11681 for (int i = 0; i < mov->nb_heif_group; i++) {
11682 AVStreamGroup *stg;
11683 AVStreamGroupTileGrid *tile_grid;
11684 const HEIFGroup *grid = &mov->heif_group[i];
11685 int err;
11686
11687 if (!grid->item || (grid->item->type != MKTAG('g','r','i','d') &&
11688 grid->item->type != MKTAG('i','o','v','l')))
11689 continue;
11690
11692 if (!stg)
11693 return AVERROR(ENOMEM);
11694
11695 stg->id = grid->item->item_id;
11696 tile_grid = stg->params.tile_grid;
11697
11698 for (int j = 0; j < grid->nb_items; j++) {
11699 int tile_id = grid->item_id_list[j];
11700 HEIFItem *item = get_heif_item(mov, tile_id);
11701 AVStream *st;
11702
11703 if (!item) {
11704 av_log(s, AV_LOG_WARNING, "HEIF item id %d referenced by grid id %d doesn't "
11705 "exist\n",
11706 tile_id, grid->item->item_id);
11708 stg = NULL;
11709 break;
11710 }
11711
11712 st = item->st;
11713 if (!st) {
11714 av_log(s, AV_LOG_WARNING, "HEIF item id %d from grid id %d doesn't "
11715 "reference a stream\n",
11716 tile_id, grid->item->item_id);
11718 stg = NULL;
11719 break;
11720 }
11721
11722 grid->item_list[j] = item;
11723 grid->item_idx_list[j] = stg->nb_entries;
11724
11725 err = avformat_stream_group_add_stream(stg, st);
11726 if (err < 0) {
11727 int l;
11728 if (err != AVERROR(EEXIST))
11729 return err;
11730
11731 for (l = 0; l < stg->nb_entries; l++)
11732 if (stg->entries[l]->stream->index == st->index)
11733 break;
11734 av_assert0(l < stg->nb_entries);
11735 grid->item_idx_list[j] = l;
11736 }
11737
11738 if (item->item_id != mov->primary_item_id)
11740 }
11741 if (!stg)
11742 continue;
11743
11744 switch (grid->item->type) {
11745 case MKTAG('g','r','i','d'):
11746 err = read_image_grid(s, grid, tile_grid);
11747 break;
11748 case MKTAG('i','o','v','l'):
11749 err = read_image_iovl(s, grid, tile_grid);
11750 break;
11751 default:
11752 av_assert0(0);
11753 }
11754 if (err < 0)
11755 return err;
11756
11758 &stg->nb_coded_side_data);
11759 if (err < 0)
11760 return err;
11761
11762 if (grid->item->name)
11763 av_dict_set(&stg->metadata, "title", grid->item->name, 0);
11764 if (grid->item->item_id == mov->primary_item_id)
11766
11767 grid->item->stg = stg;
11768 }
11769
11770 return 0;
11771}
11772
11774{
11775 MOVContext *mov = s->priv_data;
11776 AVStreamGroup *stg;
11777 AVStreamGroupLayeredVideo *layered_video;
11778 AVGainMapParams *gain = NULL;
11779 uint8_t *payload = NULL;
11780 int64_t pos, offset = 0;
11781 size_t gain_size;
11782 int64_t err64;
11783 int err;
11784
11785 if (!(s->pb->seekable & AVIO_SEEKABLE_NORMAL)) {
11786 av_log(s, AV_LOG_WARNING, "tmap box with non seekable input\n");
11787 return 0;
11788 }
11789
11791 if (!stg)
11792 return AVERROR(ENOMEM);
11793
11794 stg->id = tmap->item->item_id;
11795 layered_video = stg->params.layered_video;
11796
11797 for (int j = 0; j < tmap->nb_items; j++) {
11798 int item_id = tmap->item_id_list[j];
11799 HEIFItem *item = get_heif_item(mov, item_id);
11800 AVStreamGroup *child_stg;
11801 AVStream *st;
11802
11803 if (!item) {
11804 av_log(s, AV_LOG_WARNING, "HEIF item id %d referenced by tmap id %d doesn't "
11805 "exist\n",
11806 item_id, tmap->item->item_id);
11808 return 0;
11809 }
11810
11811 st = item->st;
11812 child_stg = item->stg;
11813 if (!st && !child_stg) {
11814 av_log(s, AV_LOG_WARNING, "HEIF item id %d from tmap id %d doesn't "
11815 "reference a stream or tmap\n",
11816 item_id, tmap->item->item_id);
11818 return 0;
11819 }
11820 av_assert0(!st != !child_stg);
11821
11822 tmap->item_list[j] = item;
11823
11824 if (st)
11825 err = avformat_stream_group_add_stream(stg, st);
11826 else
11827 err = avformat_stream_group_add_stream_group(stg, child_stg);
11828 if (err < 0) {
11829 if (err == AVERROR(EEXIST))
11830 err = AVERROR_INVALIDDATA;
11831
11832 return err;
11833 }
11834
11835 if ((item->flags & MOV_INFE_FLAG_HIDDEN)) {
11836 if (st)
11838 else
11840 }
11841 }
11842
11843 layered_video->width = tmap->item->width;
11844 layered_video->height = tmap->item->height;
11845
11846 if (tmap->item->is_idat_relative) {
11847 if (!mov->idat_offset) {
11848 av_log(s, AV_LOG_ERROR, "Missing idat box required by the tmap\n");
11849 return AVERROR_INVALIDDATA;
11850 }
11851 offset = mov->idat_offset;
11852 }
11853
11854 if (offset > INT64_MAX - tmap->item->extent_offset)
11855 return AVERROR_INVALIDDATA;
11856
11857 gain = av_gain_map_params_alloc(&gain_size);
11858 if (!gain)
11859 return AVERROR(ENOMEM);
11860
11861 payload = av_malloc(tmap->item->extent_length);
11862 if (!payload) {
11863 err = AVERROR(ENOMEM);
11864 goto fail;
11865 }
11866
11867 pos = avio_tell(s->pb);
11868 err64 = avio_seek(s->pb, tmap->item->extent_offset + offset, SEEK_SET);
11869 if (err64 != tmap->item->extent_offset + offset) {
11870 err64 = err64 < 0 ? err64 : AVERROR_INVALIDDATA;
11871 goto fail;
11872 }
11873 avio_r8(s->pb); /* version */
11874
11875 err = avio_read(s->pb, payload, tmap->item->extent_length - 1);
11876 if (err == (tmap->item->extent_length - 1))
11877 err64 = avio_seek(s->pb, pos, SEEK_SET);
11878 else {
11879 err = err < 0 ? err : AVERROR_INVALIDDATA;
11880 goto fail;
11881 }
11882 if (err64 != pos) {
11883 err = err64 < 0 ? err64 : AVERROR_INVALIDDATA;
11884 goto fail;
11885 }
11886
11887 err = av_gain_map_params_from_iso21496(gain, payload, tmap->item->extent_length - 1);
11888 av_freep(&payload);
11889 if (err < 0) {
11890 av_log(s, AV_LOG_ERROR, "Invalid ISO 21496-1 gain map payload\n");
11892 err = (s->error_recognition & (AV_EF_COMPLIANT|AV_EF_EXPLODE)) ? AVERROR_INVALIDDATA : 0;
11893 goto fail;
11894 }
11895 for (int j = 0; j < tmap->nb_items; j++) {
11896 HEIFItem *item = tmap->item_list[j];
11897 AVPacketSideData *sd;
11898 AVPacketSideData **coded_side_data;
11899 int *nb_coded_side_data;
11900
11901 if (!(item->flags & MOV_INFE_FLAG_HIDDEN))
11902 continue;
11903
11904 layered_video->el_index = j;
11905
11906 if (item->st) {
11907 coded_side_data = &item->st->codecpar->coded_side_data;
11908 nb_coded_side_data = &item->st->codecpar->nb_coded_side_data;
11909 } else {
11910 av_assert0(item->stg);
11911 coded_side_data = &item->stg->coded_side_data;
11912 nb_coded_side_data = &item->stg->nb_coded_side_data;
11913 }
11914
11915 sd = av_packet_side_data_add(coded_side_data, nb_coded_side_data,
11917 (uint8_t *)gain, gain_size, 0);
11918 if (!sd) {
11919 av_free(gain);
11920 return AVERROR(ENOMEM);
11921 }
11922 gain = NULL;
11923
11924 for (int k = 0; k < item->nb_iref_to_list; k++) {
11925 HEIFItem *ref = get_heif_item(mov, item->iref_to_list[k].item_id);
11926
11927 av_assert0(ref);
11928 // Remove auxl reference so we don't create the same group we made with
11929 // this tmap using it. Strictly speaking, the chances for Apple style
11930 // Exif values being present on a base item referenced by a tmap item
11931 // are very low, but better safe than sorry.
11932 if (item->iref_to_list[k].type == MKTAG('a','u','x','l') &&
11933 (ref == tmap->item_list[!j])) {
11934 if (k != (item->nb_iref_to_list - 1))
11935 item->iref_to_list[k] = item->iref_to_list[item->nb_iref_to_list - 1];
11936 --item->nb_iref_to_list;
11937 break;
11938 }
11939 }
11940 break;
11941 }
11942 av_free(gain);
11943
11945 &stg->nb_coded_side_data);
11946 if (err < 0)
11947 return err;
11948
11949 if (tmap->item->name)
11950 av_dict_set(&stg->metadata, "title", tmap->item->name, 0);
11951 if (tmap->item->item_id == mov->primary_item_id)
11953
11954 tmap->item->stg = stg;
11955
11956 return 0;
11957fail:
11958 av_free(gain);
11959 av_free(payload);
11960
11961 return err;
11962}
11963
11966{
11967 AVStreamGroupLayeredVideo *layered_video;
11968 AVStreamGroup *stg;
11969 int err;
11970
11971 if ((!alpha->st && !alpha->stg) ||
11972 (!base->st && !base->stg)) {
11973 av_log(s, AV_LOG_WARNING, "HEIF alpha id %d or its base doesn't reference "
11974 "a stream or group\n",
11975 alpha->item_id);
11976 return 0;
11977 }
11978
11980 if (!stg)
11981 return AVERROR(ENOMEM);
11982
11983 stg->id = alpha->item_id;
11984 layered_video = stg->params.layered_video;
11985
11986 layered_video->width = base->width;
11987 layered_video->height = base->height;
11988 layered_video->el_index = 1;
11989
11990 av_assert0(!base->st != !base->stg);
11991 if (base->st)
11992 err = avformat_stream_group_add_stream(stg, base->st);
11993 else
11995 if (err < 0) {
11996 if (err == AVERROR(EEXIST))
11997 err = AVERROR_INVALIDDATA;
11998 return err;
11999 }
12000
12001 av_assert0(!alpha->st != !alpha->stg);
12002 if (alpha->st)
12004 else
12006 if (err < 0) {
12007 if (err == AVERROR(EEXIST))
12008 err = AVERROR_INVALIDDATA;
12009 return err;
12010 }
12011
12012 // Apply all references from the base image to the Alpha group
12014 &stg->nb_coded_side_data);
12015 if (err < 0)
12016 return err;
12017
12018 return 0;
12019}
12020
12021// Parse Apple style Gain Map metadata from Exif values
12022// See https://developer.apple.com/documentation/appkit/applying-apple-hdr-effect-to-your-photos
12024 HEIFItem *base, HEIFItem *gain_map)
12025{
12026 AVStreamGroupLayeredVideo *layered_video;
12027 AVStreamGroup *stg;
12028 AVGainMapParams *gain;
12029 AVPacketSideData **coded_side_data;
12030 int *nb_coded_side_data;
12031 AVExifEntry *entry, *maker33 = NULL, *maker48 = NULL;
12032 double maker_33 = 0.0, maker_48 = 0.0, headroom;
12033 size_t gain_size;
12034 int err;
12035
12036 if ((!gain_map->st && !gain_map->stg) ||
12037 (!base->st && !base->stg)) {
12038 av_log(s, AV_LOG_WARNING, "HEIF gain_map id %d or its base doesn't reference "
12039 "a stream or group\n",
12040 gain_map->item_id);
12041 return 0;
12042 }
12043
12044 if (!base->ifd.count)
12045 return 0;
12046
12047 err = av_exif_get_entry(s, &base->ifd, 0x8769, 0, &entry);
12048 if (err > 0)
12049 err = av_exif_get_entry(s, &entry->value.ifd, 0x927c, 0, &entry);
12050 if (err > 0) {
12051 av_exif_get_entry(s, &entry->value.ifd, 0x21, 0, &maker33);
12052 av_exif_get_entry(s, &entry->value.ifd, 0x30, 0, &maker48);
12053 }
12054 if ((!maker33 && !maker48) ||
12055 (maker33 && maker33->type != AV_TIFF_SRATIONAL) ||
12056 (maker48 && maker48->type != AV_TIFF_SRATIONAL))
12057 return 0;
12058
12059 if (maker33)
12060 maker_33 = av_q2d(*maker33->value.rat);
12061 if (maker48)
12062 maker_48 = av_q2d(*maker48->value.rat);
12063
12064 if (maker_33 < 1.0) {
12065 if (maker_48 <= 0.01) {
12066 headroom = -20.0 * maker_48 + 1.8;
12067 } else {
12068 headroom = -0.101 * maker_48 + 1.601;
12069 }
12070 } else {
12071 if (maker_48 <= 0.01) {
12072 headroom = -70.0 * maker_48 + 3.0;
12073 } else {
12074 headroom = -0.303 * maker_48 + 2.303;
12075 }
12076 }
12077 if (headroom <= 0.0)
12078 return 0;
12079
12081 if (!stg)
12082 return AVERROR(ENOMEM);
12083
12084 stg->id = gain_map->item_id;
12085 layered_video = stg->params.layered_video;
12086
12087 layered_video->width = base->width;
12088 layered_video->height = base->height;
12089 layered_video->el_index = 1;
12090
12091 av_assert0(!base->st != !base->stg);
12092 if (base->st)
12093 err = avformat_stream_group_add_stream(stg, base->st);
12094 else
12096 if (err < 0) {
12097 if (err == AVERROR(EEXIST))
12098 err = AVERROR_INVALIDDATA;
12099 return err;
12100 }
12101
12102 av_assert0(!gain_map->st != !gain_map->stg);
12103 if (gain_map->st) {
12104 coded_side_data = &gain_map->st->codecpar->coded_side_data;
12105 nb_coded_side_data = &gain_map->st->codecpar->nb_coded_side_data;
12106 err = avformat_stream_group_add_stream(stg, gain_map->st);
12107 } else {
12108 coded_side_data = &gain_map->stg->coded_side_data;
12109 nb_coded_side_data = &gain_map->stg->nb_coded_side_data;
12110 err = avformat_stream_group_add_stream_group(stg, gain_map->stg);
12111 }
12112 if (err < 0) {
12113 if (err == AVERROR(EEXIST))
12114 err = AVERROR_INVALIDDATA;
12115 return err;
12116 }
12117
12118 gain = av_gain_map_params_alloc(&gain_size);
12119 if (!gain)
12120 return AVERROR(ENOMEM);
12121
12122 gain->use_base_color_space = 1;
12123 gain->alternate_hdr_headroom = av_d2q(headroom, INT_MAX);
12124 gain->nb_channels = 1;
12125 gain->channels[0].base_offset = (AVRational) { 0, 1 };
12126 gain->channels[0].alternate_offset = (AVRational) { 0, 1 };
12128
12129 AVPacketSideData *sd = av_packet_side_data_add(coded_side_data, nb_coded_side_data,
12131 (uint8_t *)gain, gain_size, 0);
12132 if (!sd) {
12133 av_free(gain);
12134 return AVERROR(ENOMEM);
12135 }
12136
12137 // Apply all references from the base image except Exif to the Gain Map group
12138 int count = base->ifd.count;
12139 base->ifd.count = 0;
12141 &stg->nb_coded_side_data);
12142 base->ifd.count = count;
12143 if (err < 0)
12144 return err;
12145
12146 return 0;
12147}
12148
12150{
12151 MOVContext *mov = s->priv_data;
12152 int err;
12153
12154 for (int i = 0; i < mov->nb_heif_group; i++) {
12155 const HEIFGroup *tmap = &mov->heif_group[i];
12156
12157 if (!tmap->item)
12158 continue;
12159
12160 switch (tmap->item->type) {
12161 case MKTAG('t','m','a','p'):
12163 if (err < 0)
12164 return err;
12165 break;
12166 default:
12167 break;
12168 }
12169 }
12170
12171 for (int i = 0; i < mov->nb_heif_item; i++) {
12172 HEIFItem *item = mov->heif_item[i];
12173 int err;
12174
12175 if (!item)
12176 continue;
12177
12178 for (int j = 0; j < item->nb_iref_to_list; j++) {
12179 HEIFItem *ref = get_heif_item(mov, item->iref_to_list[j].item_id);
12180
12181 av_assert0(ref);
12182 switch(item->iref_to_list[j].type) {
12183 case MKTAG('a','u','x','l'):
12184 if (item->is_alpha) {
12186 if (err < 0)
12187 return err;
12188 break;
12189 }
12190 if (item->is_gainmap) {
12192 if (err < 0)
12193 return err;
12194 break;
12195 }
12196 }
12197 }
12198 }
12199
12200 return 0;
12201}
12202
12204{
12205 MOVContext *mov = s->priv_data;
12206 int err;
12207
12208 for (int i = 0; i < mov->nb_heif_item; i++) {
12209 HEIFItem *item = mov->heif_item[i];
12210 MOVStreamContext *sc;
12211 AVStream *st;
12212 int64_t offset = 0;
12213
12214 if (!item)
12215 continue;
12216 if (!item->st) {
12217 continue;
12218 }
12219 if (item->is_idat_relative) {
12220 if (!mov->idat_offset) {
12221 av_log(s, AV_LOG_ERROR, "Missing idat box for item %d\n", item->item_id);
12222 return AVERROR_INVALIDDATA;
12223 }
12224 offset = mov->idat_offset;
12225 }
12226
12227 st = item->st;
12228 sc = st->priv_data;
12229 st->codecpar->width = item->width;
12230 st->codecpar->height = item->height;
12231
12232 sc->sample_size = sc->stsz_sample_size = item->extent_length;
12233 sc->sample_count = 1;
12234
12235 err = sanity_checks(s, sc, st->index);
12236 if (err)
12237 return AVERROR_INVALIDDATA;
12238
12239 if (offset > INT64_MAX - item->extent_offset)
12240 return AVERROR_INVALIDDATA;
12241
12242 sc->chunk_offsets[0] = item->extent_offset + offset;
12243
12246 if (err < 0)
12247 return err;
12248
12249 if (item->name)
12250 av_dict_set(&st->metadata, "title", item->name, 0);
12251 if (item->item_id == mov->primary_item_id)
12253
12254 mov_build_index(mov, st);
12255 }
12256
12257 err = mov_parse_tiles(s);
12258 if (err < 0)
12259 return err;
12260
12262 if (err < 0)
12263 return err;
12264
12265 return 0;
12266}
12267
12269{
12270 int err;
12271
12272 for (int i = 0; i < s->nb_streams; i++) {
12273 AVStreamGroup *stg;
12274 const AVDictionaryEntry *tcr;
12275 AVStream *st = s->streams[i];
12276
12277 if (st->codecpar->codec_tag != MKTAG('t','m','c','d'))
12278 continue;
12279
12281 if (!stg)
12282 return AVERROR(ENOMEM);
12283
12284 stg->id = st->id;
12285 tcr = av_dict_get(st->metadata, "timecode", NULL, 0);
12286
12287 for (int j = 0; j < s->nb_streams; j++) {
12288 AVStream *st2 = s->streams[j];
12289 MOVStreamContext *sc2 = st2->priv_data;
12290 MovTref *tag = mov_find_tref_tag(sc2, MKTAG('t','m','c','d'));
12291
12292 if (!tag)
12293 continue;
12294
12295 for (int k = 0; k < tag->nb_id; k++) {
12296 if (tag->id[k] != st->id)
12297 continue;
12298
12299 err = avformat_stream_group_add_stream(stg, st2);
12300 if (err < 0)
12301 return err;
12302
12303 if (tcr)
12304 av_dict_set(&st2->metadata, "timecode", tcr->value, AV_DICT_DONT_OVERWRITE);
12305 }
12306 }
12307
12308 if (!stg->nb_entries) {
12310 continue;
12311 }
12312
12313 err = avformat_stream_group_add_stream(stg, st);
12314 if (err < 0)
12315 return err;
12316
12317 stg->params.tref->metadata_index = stg->nb_entries - 1;
12318 }
12320
12321 return 0;
12322}
12323
12325 uint32_t *tref_id, int nb_tref_id, int first_index)
12326{
12327 if (!nb_tref_id)
12328 return NULL;
12329
12330 for (int i = first_index; i < s->nb_streams; i++)
12331 for (int j = 0; j < nb_tref_id; j++)
12332 if (s->streams[i]->index != st->index &&
12333 s->streams[i]->id == tref_id[j])
12334 return s->streams[i];
12335
12336 return NULL;
12337}
12338
12340{
12341 static const uint32_t tref_tags[] = {
12342 MKTAG('c','d','s','c'),
12343 MKTAG('r','n','d','r'),
12344 };
12345
12346 int err;
12347
12348 // Don't try to add a group if there's only one track
12349 if (s->nb_streams <= 1)
12350 return 0;
12351
12352 for (int i = 0; i < s->nb_streams; i++) {
12353 AVStream *st = s->streams[i];
12354 MOVStreamContext *sc = st->priv_data;
12355
12356 for (int c = 0; c < FF_ARRAY_ELEMS(tref_tags); c++) {
12357 AVStreamGroup *stg;
12358 AVStream *st_ref;
12359 MovTref *tag = mov_find_tref_tag(sc, tref_tags[c]);
12360
12361 if (!tag)
12362 continue;
12363
12364 st_ref = mov_find_reference_track(s, st, tag->id, tag->nb_id, 0);
12365 if (!st_ref) {
12366 av_log(s, AV_LOG_WARNING, "Failed to find referenced stream\n");
12367 continue;
12368 }
12369
12371 if (!stg)
12372 return AVERROR(ENOMEM);
12373
12374 stg->id = st_ref->id;
12375
12376 err = avformat_stream_group_add_stream(stg, st_ref);
12377 if (err < 0)
12378 return err;
12379
12380 err = avformat_stream_group_add_stream(stg, st);
12381 if (err < 0)
12382 return err;
12383
12384 stg->params.tref->metadata_index = stg->nb_entries - 1;
12385 }
12386 }
12387
12388 return 0;
12389}
12390
12392{
12393 int err;
12394
12395 // Don't try to add a group if there's only one track
12396 if (s->nb_streams <= 1)
12397 return 0;
12398
12399 for (int i = 0; i < s->nb_streams; i++) {
12400 AVStreamGroup *stg;
12401 AVStream *st = s->streams[i];
12402 AVStream *st_base;
12403 MOVStreamContext *sc = st->priv_data;
12404 MovTref *tag = mov_find_tref_tag(sc, MKTAG('s','b','a','s'));
12405 int j = 0;
12406
12407 /* Find an enhancement stream. */
12408 if (st->codecpar->codec_id != AV_CODEC_ID_LCEVC || !tag)
12409 continue;
12410
12412 if (!stg)
12413 return AVERROR(ENOMEM);
12414
12415 stg->id = st->id;
12418
12419 while (st_base = mov_find_reference_track(s, st, tag->id, tag->nb_id, j)) {
12420 err = avformat_stream_group_add_stream(stg, st_base);
12421 if (err < 0)
12422 return err;
12423
12424 j = st_base->index + 1;
12425 }
12426 if (!j) {
12427 int loglevel = (s->error_recognition & AV_EF_EXPLODE) ? AV_LOG_ERROR : AV_LOG_WARNING;
12428 av_log(s, loglevel, "Failed to find base stream for LCEVC stream\n");
12430 if (s->error_recognition & AV_EF_EXPLODE)
12431 return AVERROR_INVALIDDATA;
12432 continue;
12433 }
12434
12435 err = avformat_stream_group_add_stream(stg, st);
12436 if (err < 0)
12437 return err;
12438
12439 stg->params.layered_video->el_index = stg->nb_entries - 1;
12440 }
12441
12442 return 0;
12443}
12444
12446{
12447 int err;
12448
12449 if (s->nb_streams <= 1)
12450 return 0;
12451
12452 /* Identify legacy dual-track Dolby Vision profile 7 carriage per Annex
12453 * C of "Dolby Vision Streams Within the ISO Base Media File Format",
12454 * v2.7.1. The 'vdep' track reference type is shared with depth video
12455 * and multi-view dependencies. The spec-mandated DV-specific sample
12456 * entry combined with the dvcC configuration record disambiguates
12457 * those uses. */
12458 for (int i = 0; i < s->nb_streams; i++) {
12459 AVStreamGroup *stg;
12460 AVStream *st = s->streams[i];
12461 AVStream *st_base;
12462 MOVStreamContext *sc = st->priv_data;
12463 MovTref *tag = mov_find_tref_tag(sc, MKTAG('v','d','e','p'));
12464 const AVPacketSideData *sd;
12466
12467 if (st->codecpar->codec_id != AV_CODEC_ID_HEVC || !tag)
12468 continue;
12469
12470 if (st->codecpar->codec_tag != MKTAG('d','v','h','e') &&
12471 st->codecpar->codec_tag != MKTAG('d','v','h','1'))
12472 continue;
12473
12477 if (!sd)
12478 continue;
12479 dovi = (const AVDOVIDecoderConfigurationRecord *)sd->data;
12480
12481 /* EL track of a dual-track stream: rpu_present_flag = 1,
12482 * el_present_flag = 1, bl_present_flag = 0, dv_profile = 7. */
12483 if (dovi->dv_profile != 7 || !dovi->rpu_present_flag ||
12484 !dovi->el_present_flag || dovi->bl_present_flag)
12485 continue;
12486
12487 st_base = mov_find_reference_track(s, st, tag->id, tag->nb_id, 0);
12488 if (!st_base) {
12489 int loglevel = (s->error_recognition & AV_EF_EXPLODE) ? AV_LOG_ERROR : AV_LOG_WARNING;
12490 av_log(s, loglevel, "Failed to find base layer for Dolby Vision EL stream\n");
12491 if (s->error_recognition & AV_EF_EXPLODE)
12492 return AVERROR_INVALIDDATA;
12493 continue;
12494 }
12495
12497 if (!stg)
12498 return AVERROR(ENOMEM);
12499
12500 stg->id = st->id;
12501
12502 err = avformat_stream_group_add_stream(stg, st_base);
12503 if (err < 0)
12504 return err;
12505
12506 err = avformat_stream_group_add_stream(stg, st);
12507 if (err < 0)
12508 return err;
12509
12510 stg->params.layered_video->el_index = stg->nb_entries - 1;
12511 stg->params.layered_video->width = st_base->codecpar->width;
12512 stg->params.layered_video->height = st_base->codecpar->height;
12513 }
12514
12515 return 0;
12516}
12517
12519{
12520 int highest_id = 0, lowest_iamf_id = INT_MAX;
12521
12522 for (int i = 0; i < s->nb_streams; i++) {
12523 const AVStream *st = s->streams[i];
12524 const MOVStreamContext *sc = st->priv_data;
12525 if (!sc->iamf)
12526 highest_id = FFMAX(highest_id, st->id);
12527 }
12528
12529 for (int i = 0; i < s->nb_stream_groups; i++) {
12530 AVStreamGroup *stg = s->stream_groups[i];
12532 continue;
12533 for (int j = 0; j < stg->nb_entries; j++) {
12534 AVStream *st = stg->entries[j]->stream;
12535 lowest_iamf_id = FFMIN(lowest_iamf_id, st->id);
12536 }
12537 }
12538
12539 if (highest_id < lowest_iamf_id)
12540 return;
12541
12542 highest_id += !lowest_iamf_id;
12543 for (int i = 0; highest_id > 1 && i < s->nb_stream_groups; i++) {
12544 AVStreamGroup *stg = s->stream_groups[i];
12546 continue;
12547 for (int j = 0; j < stg->nb_entries; j++) {
12548 AVStream *st = stg->entries[j]->stream;
12549 MOVStreamContext *sc = st->priv_data;
12550 st->id += highest_id;
12551 sc->iamf_stream_offset = highest_id;
12552 }
12553 }
12554}
12555
12557{
12558 MOVContext *mov = s->priv_data;
12559 AVIOContext *pb = s->pb;
12560 int j, err;
12561 MOVAtom atom = { AV_RL32("root") };
12562 int i;
12563
12564 mov->fc = s;
12565 mov->trak_index = -1;
12566 mov->primary_item_id = -1;
12567 mov->cur_item_id = -1;
12568 /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
12570 atom.size = avio_size(pb);
12571 else
12572 atom.size = INT64_MAX;
12573
12574 /* check MOV header */
12575 do {
12576 if (mov->moov_retry)
12577 avio_seek(pb, 0, SEEK_SET);
12578 if ((err = mov_read_default(mov, pb, atom)) < 0) {
12579 av_log(s, AV_LOG_ERROR, "error reading header\n");
12580 return err;
12581 }
12582 } while ((pb->seekable & AVIO_SEEKABLE_NORMAL) &&
12583 !mov->found_moov && (!mov->found_iloc || !mov->found_iinf) && !mov->moov_retry++);
12584 if (!mov->found_moov && !mov->found_iloc && !mov->found_iinf) {
12585 av_log(s, AV_LOG_ERROR, "moov atom not found\n");
12586 return AVERROR_INVALIDDATA;
12587 }
12588 av_log(mov->fc, AV_LOG_TRACE, "on_parse_exit_offset=%"PRId64"\n", avio_tell(pb));
12589
12590 if (mov->found_iloc && mov->found_iinf) {
12591 err = mov_parse_heif_items(s);
12592 if (err < 0)
12593 return err;
12594 }
12595 // prevent iloc and iinf boxes from being parsed while reading packets.
12596 // this is needed because an iinf box may have been parsed but ignored
12597 // for having old infe boxes which create no streams.
12598 mov->found_iloc = mov->found_iinf = 1;
12599
12600 if (pb->seekable & AVIO_SEEKABLE_NORMAL) {
12601 if (mov->nb_chapter_tracks > 0 && !mov->ignore_chapters)
12603 for (i = 0; i < s->nb_streams; i++)
12604 if (s->streams[i]->codecpar->codec_tag == AV_RL32("tmcd")) {
12605 mov_read_timecode_track(s, s->streams[i]);
12606 } else if (s->streams[i]->codecpar->codec_tag == AV_RL32("rtmd")) {
12607 mov_read_rtmd_track(s, s->streams[i]);
12608 }
12609 }
12610
12611 /* Create metadata stream groups. */
12613 if (err < 0)
12614 return err;
12615
12616 /* copy timecode metadata from tmcd tracks to the related video streams */
12618 if (err < 0)
12619 return err;
12620
12621 /* Create LCEVC stream groups. */
12623 if (err < 0)
12624 return err;
12625
12626 /* Create Dolby Vision Profile 7 stream groups. */
12628 if (err < 0)
12629 return err;
12630
12631 for (i = 0; i < s->nb_streams; i++) {
12632 AVStream *st = s->streams[i];
12633 FFStream *const sti = ffstream(st);
12634 MOVStreamContext *sc = st->priv_data;
12635 uint32_t dvdsub_clut[FF_DVDCLUT_CLUT_LEN] = {0};
12636 fix_timescale(mov, sc);
12637
12638 /* Set the primary extradata based on the first Sample if it doesn't reference the first stsd entry. */
12639 if (sc->stsc_count && sc->extradata_size && !sc->iamf &&
12640 sc->stsc_data[0].id > 1 && sc->stsc_data[0].id <= sc->stsd_count) {
12641 sc->last_stsd_index = sc->stsc_data[0].id - 1;
12644 if (sc->extradata_size[sc->last_stsd_index]) {
12646 if (!st->codecpar->extradata)
12647 return AVERROR(ENOMEM);
12649 }
12650 }
12651
12655 }
12658 sc->time_scale*(int64_t)sc->nb_frames_for_fps, sc->duration_for_fps, INT_MAX);
12660 if (st->codecpar->width <= 0 || st->codecpar->height <= 0) {
12661 st->codecpar->width = sc->width;
12662 st->codecpar->height = sc->height;
12663 }
12666
12667 for (j = 0; j < FF_DVDCLUT_CLUT_LEN; j++)
12668 dvdsub_clut[j] = AV_RB32(st->codecpar->extradata + j * 4);
12669
12670 err = ff_dvdclut_yuv_to_rgb(dvdsub_clut, FF_DVDCLUT_CLUT_SIZE);
12671 if (err < 0)
12672 return err;
12673
12675 st->codecpar->extradata_size = 0;
12676
12678 st->codecpar);
12679 if (err < 0)
12680 return err;
12681 }
12682 }
12683 if (mov->handbrake_version &&
12684 mov->handbrake_version <= 1000000*0 + 1000*10 + 2 && // 0.10.2
12686 av_log(s, AV_LOG_VERBOSE, "Forcing full parsing for mp3 stream\n");
12688 }
12689 }
12690
12691 if (mov->trex_data || mov->use_mfra_for > 0) {
12692 for (i = 0; i < s->nb_streams; i++) {
12693 AVStream *st = s->streams[i];
12694 MOVStreamContext *sc = st->priv_data;
12695 if (sc->duration_for_fps > 0) {
12696 /* Akin to sc->data_size * 8 * sc->time_scale / sc->duration_for_fps but accounting for overflows. */
12698 if (st->codecpar->bit_rate == INT64_MIN) {
12699 av_log(s, AV_LOG_WARNING, "Overflow during bit rate calculation %"PRId64" * 8 * %d\n",
12700 sc->data_size, sc->time_scale);
12701 st->codecpar->bit_rate = 0;
12702 if (s->error_recognition & AV_EF_EXPLODE)
12703 return AVERROR_INVALIDDATA;
12704 }
12705 }
12706 }
12707 }
12708
12709 for (i = 0; i < mov->bitrates_count && i < s->nb_streams; i++) {
12710 if (mov->bitrates[i]) {
12711 s->streams[i]->codecpar->bit_rate = mov->bitrates[i];
12712 }
12713 }
12714
12716
12717 for (i = 0; i < s->nb_streams; i++) {
12718 AVStream *st = s->streams[i];
12719 MOVStreamContext *sc = st->priv_data;
12720
12721 switch (st->codecpar->codec_type) {
12722 case AVMEDIA_TYPE_AUDIO:
12723 err = ff_replaygain_export(st, s->metadata);
12724 if (err < 0)
12725 return err;
12726 break;
12727 case AVMEDIA_TYPE_VIDEO:
12728 if (sc->display_matrix) {
12731 (uint8_t*)sc->display_matrix, sizeof(int32_t) * 9, 0))
12732 return AVERROR(ENOMEM);
12733
12734 sc->display_matrix = NULL;
12735 }
12736 if (sc->stereo3d) {
12739 (uint8_t *)sc->stereo3d, sc->stereo3d_size, 0))
12740 return AVERROR(ENOMEM);
12741
12742 sc->stereo3d = NULL;
12743 }
12744 if (sc->spherical) {
12747 (uint8_t *)sc->spherical, sc->spherical_size, 0))
12748 return AVERROR(ENOMEM);
12749
12750 sc->spherical = NULL;
12751 }
12752 if (sc->mastering) {
12755 (uint8_t *)sc->mastering, sc->mastering_size, 0))
12756 return AVERROR(ENOMEM);
12757
12758 sc->mastering = NULL;
12759 }
12760 if (sc->coll) {
12763 (uint8_t *)sc->coll, sc->coll_size, 0))
12764 return AVERROR(ENOMEM);
12765
12766 sc->coll = NULL;
12767 }
12768 if (sc->ambient) {
12771 (uint8_t *) sc->ambient, sc->ambient_size, 0))
12772 return AVERROR(ENOMEM);
12773
12774 sc->ambient = NULL;
12775 }
12776 break;
12777 }
12778 }
12779
12781
12783
12784 for (i = 0; i < mov->frag_index.nb_items; i++)
12785 if (mov->frag_index.item[i].moof_offset <= mov->fragment.moof_offset)
12786 mov->frag_index.item[i].headers_read = 1;
12787
12788 return 0;
12789}
12790
12792{
12794 int64_t best_dts = INT64_MAX;
12795 int i;
12796 MOVContext *mov = s->priv_data;
12797 int no_interleave = !mov->interleaved_read || !(s->pb->seekable & AVIO_SEEKABLE_NORMAL);
12798 for (i = 0; i < s->nb_streams; i++) {
12799 AVStream *avst = s->streams[i];
12800 FFStream *const avsti = ffstream(avst);
12801 MOVStreamContext *msc = avst->priv_data;
12802 if (msc->pb && msc->current_sample < avsti->nb_index_entries) {
12803 AVIndexEntry *current_sample = &avsti->index_entries[msc->current_sample];
12804 int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale);
12805 uint64_t dtsdiff = best_dts > dts ? best_dts - (uint64_t)dts : ((uint64_t)dts - best_dts);
12806 av_log(s, AV_LOG_TRACE, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
12807 if (!sample || (no_interleave && current_sample->pos < sample->pos) ||
12808 ((s->pb->seekable & AVIO_SEEKABLE_NORMAL) &&
12809 ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb && dts != AV_NOPTS_VALUE &&
12810 ((dtsdiff <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
12811 (dtsdiff > AV_TIME_BASE && dts < best_dts && mov->interleaved_read)))))) {
12812 sample = current_sample;
12813 best_dts = dts;
12814 *st = avst;
12815 }
12816 }
12817 }
12818 return sample;
12819}
12820
12821static int should_retry(AVIOContext *pb, int error_code) {
12822 if (error_code == AVERROR_EOF || avio_feof(pb))
12823 return 0;
12824
12825 return 1;
12826}
12827
12829{
12830 int ret;
12831 MOVContext *mov = s->priv_data;
12832
12833 if (index >= 0 && index < mov->frag_index.nb_items)
12834 target = mov->frag_index.item[index].moof_offset;
12835 if (target >= 0 && avio_seek(s->pb, target, SEEK_SET) != target) {
12836 av_log(mov->fc, AV_LOG_ERROR, "root atom offset 0x%"PRIx64": partial file\n", target);
12837 return AVERROR_INVALIDDATA;
12838 }
12839
12840 mov->next_root_atom = 0;
12841 if ((index < 0 && target >= 0) || index >= mov->frag_index.nb_items)
12842 index = search_frag_moof_offset(&mov->frag_index, target);
12843 if (index >= 0 && index < mov->frag_index.nb_items &&
12844 mov->frag_index.item[index].moof_offset == target) {
12845 if (index + 1 < mov->frag_index.nb_items)
12848 return 0;
12850 }
12851
12852 mov->found_mdat = 0;
12853 mov->pssh_side_data = NULL;
12854
12855 ret = mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX });
12856 if (ret < 0)
12857 return ret;
12858 if (avio_feof(s->pb))
12859 return AVERROR_EOF;
12860 av_log(s, AV_LOG_TRACE, "read fragments, offset 0x%"PRIx64"\n", avio_tell(s->pb));
12861
12862 return 1;
12863}
12864
12866{
12867 MOVStreamContext *sc = st->priv_data;
12868 uint8_t *side, *extradata;
12869 int extradata_size;
12870
12871 /* Save the current index. */
12872 sc->last_stsd_index = sc->stsc_data[sc->stsc_index].id - 1;
12873
12874 /* Notify the decoder that extradata changed. */
12875 extradata_size = sc->extradata_size[sc->last_stsd_index];
12876 extradata = sc->extradata[sc->last_stsd_index];
12877 if (st->discard != AVDISCARD_ALL && extradata_size > 0 && extradata) {
12880 extradata_size);
12881 if (!side)
12882 return AVERROR(ENOMEM);
12883 memcpy(side, extradata, extradata_size);
12884 }
12885
12886 return 0;
12887}
12888
12889static int get_eia608_packet(AVIOContext *pb, AVPacket *pkt, int src_size)
12890{
12891 /* We can't make assumptions about the structure of the payload,
12892 because it may include multiple cdat and cdt2 samples. */
12893 const uint32_t cdat = AV_RB32("cdat");
12894 const uint32_t cdt2 = AV_RB32("cdt2");
12895 int ret, out_size = 0;
12896
12897 /* a valid payload must have size, 4cc, and at least 1 byte pair: */
12898 if (src_size < 10)
12899 return AVERROR_INVALIDDATA;
12900
12901 /* avoid an int overflow: */
12902 if ((src_size - 8) / 2 >= INT_MAX / 3)
12903 return AVERROR_INVALIDDATA;
12904
12905 ret = av_new_packet(pkt, ((src_size - 8) / 2) * 3);
12906 if (ret < 0)
12907 return ret;
12908
12909 /* parse and re-format the c608 payload in one pass. */
12910 while (src_size >= 10) {
12911 const uint32_t atom_size = avio_rb32(pb);
12912 const uint32_t atom_type = avio_rb32(pb);
12913 const uint32_t data_size = atom_size - 8;
12914 const uint8_t cc_field =
12915 atom_type == cdat ? 1 :
12916 atom_type == cdt2 ? 2 :
12917 0;
12918
12919 /* account for bytes consumed for atom size and type. */
12920 src_size -= 8;
12921
12922 /* make sure the data size stays within the buffer boundaries. */
12923 if (data_size < 2 || data_size > src_size) {
12925 break;
12926 }
12927
12928 /* make sure the data size is consistent with N byte pairs. */
12929 if (data_size % 2 != 0) {
12931 break;
12932 }
12933
12934 if (!cc_field) {
12935 /* neither cdat or cdt2 ... skip it */
12936 avio_skip(pb, data_size);
12937 src_size -= data_size;
12938 continue;
12939 }
12940
12941 for (uint32_t i = 0; i < data_size; i += 2) {
12942 pkt->data[out_size] = (0x1F << 3) | (1 << 2) | (cc_field - 1);
12943 pkt->data[out_size + 1] = avio_r8(pb);
12944 pkt->data[out_size + 2] = avio_r8(pb);
12945 out_size += 3;
12946 src_size -= 2;
12947 }
12948 }
12949
12950 if (src_size > 0)
12951 /* skip any remaining unread portion of the input payload */
12952 avio_skip(pb, src_size);
12953
12955 return ret;
12956}
12957
12959 int64_t current_index, AVPacket *pkt)
12960{
12961 MOVContext *mov = s->priv_data;
12962 MOVStreamContext *sc = st->priv_data;
12963
12964 pkt->stream_index = sc->ffindex;
12965 pkt->dts = sample->timestamp;
12966 if (sample->flags & AVINDEX_DISCARD_FRAME) {
12967 pkt->flags |= AV_PKT_FLAG_DISCARD;
12968 }
12969 if (sc->stts_count && sc->tts_index < sc->tts_count)
12970 pkt->duration = sc->tts_data[sc->tts_index].duration;
12971 if (sc->ctts_count && sc->tts_index < sc->tts_count) {
12972 pkt->pts = av_sat_add64(pkt->dts, av_sat_add64(sc->dts_shift, sc->tts_data[sc->tts_index].offset));
12973 } else {
12974 if (pkt->duration == 0) {
12975 int64_t next_dts = (sc->current_sample < ffstream(st)->nb_index_entries) ?
12977 if (next_dts >= pkt->dts)
12978 pkt->duration = next_dts - pkt->dts;
12979 }
12980 pkt->pts = pkt->dts;
12981 }
12982
12984 sc->current_sample >= ffstream(st)->nb_index_entries) {
12985 int64_t pts = av_rescale_q(pkt->pts, st->time_base, (AVRational){ 1, st->codecpar->sample_rate });
12986 int64_t total = av_rescale_q(st->duration, st->time_base, (AVRational){ 1, st->codecpar->sample_rate });
12987 int64_t duration = pkt->duration;
12988
12989 if (st->duration < pkt->pts) {
12990 duration = 0;
12991 } else
12992 duration = FFMIN(duration, (uint64_t)st->duration - pkt->pts);
12993
12994 duration = av_rescale_q(duration, st->time_base, (AVRational){ 1, st->codecpar->sample_rate });
12995
12996 if (!ffstream(st)->first_discard_sample)
12998 if (!ffstream(st)->last_discard_sample)
12999 ffstream(st)->last_discard_sample = total;
13000 }
13001
13002 if (sc->tts_data && sc->tts_index < sc->tts_count) {
13003 /* update tts context */
13004 sc->tts_sample++;
13005 if (sc->tts_index < sc->tts_count &&
13006 sc->tts_data[sc->tts_index].count == sc->tts_sample) {
13007 sc->tts_index++;
13008 sc->tts_sample = 0;
13009 }
13010 }
13011
13012 if (sc->sdtp_data && sc->current_sample <= sc->sdtp_count) {
13013 uint8_t sample_flags = sc->sdtp_data[sc->current_sample - 1];
13014 uint8_t sample_is_depended_on = (sample_flags >> 2) & 0x3;
13015 pkt->flags |= sample_is_depended_on == MOV_SAMPLE_DEPENDENCY_NO ? AV_PKT_FLAG_DISPOSABLE : 0;
13016 }
13017 pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? AV_PKT_FLAG_KEY : 0;
13018 pkt->pos = sample->pos;
13019
13020 /* Multiple stsd handling. */
13021 if (sc->stsc_data) {
13022 if (sc->stsc_data[sc->stsc_index].id > 0 &&
13023 sc->stsc_data[sc->stsc_index].id - 1 < sc->stsd_count &&
13024 sc->stsc_data[sc->stsc_index].id - 1 != sc->last_stsd_index) {
13025 int ret = mov_change_extradata(st, pkt);
13026 if (ret < 0)
13027 return ret;
13028 }
13029
13030 /* Update the stsc index for the next sample */
13031 sc->stsc_sample++;
13034 sc->stsc_index++;
13035 sc->stsc_sample = 0;
13036 }
13037 }
13038
13039 return 0;
13040}
13041
13043{
13044 MOVContext *mov = s->priv_data;
13045 MOVStreamContext *sc;
13047 AVStream *st = NULL;
13048 FFStream *avsti = NULL;
13049 int64_t current_index;
13050 int ret;
13051 int i;
13052 mov->fc = s;
13053 retry:
13054 if (s->pb->pos == 0) {
13055
13056 // Discard current fragment index
13057 if (mov->frag_index.allocated_size > 0) {
13058 for(int i = 0; i < mov->frag_index.nb_items; i++) {
13060 }
13061 av_freep(&mov->frag_index.item);
13062 mov->frag_index.nb_items = 0;
13063 mov->frag_index.allocated_size = 0;
13064 mov->frag_index.current = -1;
13065 mov->frag_index.complete = 0;
13066 }
13067
13068 for (i = 0; i < s->nb_streams; i++) {
13069 AVStream *avst = s->streams[i];
13070 MOVStreamContext *msc = avst->priv_data;
13071
13072 // Clear current sample
13073 mov_current_sample_set(msc, 0);
13074 msc->tts_index = 0;
13075
13076 // Discard current index entries
13077 avsti = ffstream(avst);
13078 if (avsti->index_entries_allocated_size > 0) {
13079 av_freep(&avsti->index_entries);
13081 avsti->nb_index_entries = 0;
13082 }
13083 }
13084
13085 if ((ret = mov_switch_root(s, -1, -1)) < 0)
13086 return ret;
13087 }
13089 if (!sample || (mov->next_root_atom && sample->pos > mov->next_root_atom)) {
13090 if (!mov->next_root_atom)
13091 return AVERROR_EOF;
13092 if ((ret = mov_switch_root(s, mov->next_root_atom, -1)) < 0)
13093 return ret;
13094 goto retry;
13095 }
13096 sc = st->priv_data;
13097 /* must be done just before reading, to avoid infinite loop on sample */
13098 current_index = sc->current_index;
13100
13101 if (mov->next_root_atom) {
13102 sample->pos = FFMIN(sample->pos, mov->next_root_atom);
13103 sample->size = FFMIN(sample->size, (mov->next_root_atom - sample->pos));
13104 }
13105
13106 if (st->discard != AVDISCARD_ALL || sc->iamf) {
13107 int64_t ret64 = avio_seek(sc->pb, sample->pos, SEEK_SET);
13108 if (ret64 != sample->pos) {
13109 av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
13110 sc->ffindex, sample->pos);
13111 if (should_retry(sc->pb, ret64)) {
13113 } else if (ret64 < 0) {
13114 return (int)ret64;
13115 }
13116 return AVERROR_INVALIDDATA;
13117 }
13118
13119 if (st->discard == AVDISCARD_NONKEY && !(sample->flags & AVINDEX_KEYFRAME)) {
13120 av_log(mov->fc, AV_LOG_DEBUG, "Nonkey frame from stream %d discarded due to AVDISCARD_NONKEY\n", sc->ffindex);
13121 goto retry;
13122 }
13123
13124 if (st->codecpar->codec_id == AV_CODEC_ID_EIA_608 && sample->size > 8)
13125 ret = get_eia608_packet(sc->pb, pkt, sample->size);
13126#if CONFIG_IAMFDEC
13127 else if (sc->iamf) {
13128 int64_t pts, dts, pos, duration;
13129 int flags, size = sample->size;
13130 ret = mov_finalize_packet(s, st, sample, current_index, pkt);
13131 pts = pkt->pts; dts = pkt->dts;
13132 pos = pkt->pos; flags = pkt->flags;
13133 duration = pkt->duration;
13134 while (!ret && size > 0) {
13136 if (ret < 0) {
13137 if (should_retry(sc->pb, ret))
13139 return ret;
13140 }
13141 size -= ret;
13142
13143 if (pkt->flags & AV_PKT_FLAG_DISCARD) {
13145 ret = 0;
13146 continue;
13147 }
13148 pkt->pts = pts; pkt->dts = dts;
13149 pkt->pos = pos; pkt->flags |= flags;
13150 pkt->duration = duration;
13152 }
13153 if (!ret)
13154 return FFERROR_REDO;
13155 }
13156#endif
13157 else if (st->codecpar->codec_id == AV_CODEC_ID_APV && sample->size > 4) {
13158 uint32_t au_size = avio_rb32(sc->pb);
13159 int explode = !!(mov->fc->error_recognition & AV_EF_EXPLODE);
13160 if (au_size > sample->size - 4) {
13161 av_log(s, explode ? AV_LOG_ERROR : AV_LOG_WARNING,
13162 "APV au_size %u exceeds sample body %d\n",
13163 au_size, sample->size - 4);
13164 if (explode)
13165 return AVERROR_INVALIDDATA;
13166 au_size = sample->size - 4;
13167 }
13168 ret = av_get_packet(sc->pb, pkt, au_size);
13169 } else
13170 ret = av_get_packet(sc->pb, pkt, sample->size);
13171 if (ret < 0) {
13172 if (should_retry(sc->pb, ret)) {
13174 }
13175 return ret;
13176 }
13177#if CONFIG_DV_DEMUXER
13178 if (mov->dv_demux && sc->dv_audio_container) {
13179 ret = avpriv_dv_produce_packet(mov->dv_demux, NULL, pkt->data, pkt->size, pkt->pos);
13181 if (ret < 0)
13182 return ret;
13184 if (ret < 0)
13185 return ret;
13186 }
13187#endif
13188 if (sc->has_palette) {
13189 uint8_t *pal;
13190
13192 if (!pal) {
13193 av_log(mov->fc, AV_LOG_ERROR, "Cannot append palette to packet\n");
13194 } else {
13195 memcpy(pal, sc->palette, AVPALETTE_SIZE);
13196 sc->has_palette = 0;
13197 }
13198 }
13199 if (st->codecpar->codec_id == AV_CODEC_ID_MP3 && !ffstream(st)->need_parsing && pkt->size > 4) {
13200 if (ff_mpa_check_header(AV_RB32(pkt->data)) < 0)
13202 }
13203 }
13204
13205 ret = mov_finalize_packet(s, st, sample, current_index, pkt);
13206 if (ret < 0)
13207 return ret;
13208
13209 if (st->discard == AVDISCARD_ALL)
13210 goto retry;
13211
13212 if (mov->aax_mode)
13213 aax_filter(pkt->data, pkt->size, mov);
13214
13215 ret = cenc_filter(mov, st, sc, pkt, current_index);
13216 if (ret < 0) {
13217 return ret;
13218 }
13219
13220 return 0;
13221}
13222
13224{
13225 MOVContext *mov = s->priv_data;
13226 int index;
13227
13228 if (!mov->frag_index.complete)
13229 return 0;
13230
13231 index = search_frag_timestamp(s, &mov->frag_index, st, timestamp);
13232 if (index < 0)
13233 index = 0;
13234 if (!mov->frag_index.item[index].headers_read)
13235 return mov_switch_root(s, -1, index);
13236 if (index + 1 < mov->frag_index.nb_items)
13238
13239 return 0;
13240}
13241
13243{
13244 // TODO: a bisect search would scale much better
13245 for (int i = 0; i < sc->open_key_samples_count; i++) {
13246 const int oks = sc->open_key_samples[i];
13247 if (oks == sample)
13248 return 1;
13249 if (oks > sample) /* list is monotically increasing so we can stop early */
13250 break;
13251 }
13252 return 0;
13253}
13254
13255/*
13256 * Some key sample may be key frames but not IDR frames, so a random access to
13257 * them may not be allowed.
13258 */
13259static int can_seek_to_key_sample(AVStream *st, int sample, int64_t requested_pts)
13260{
13261 MOVStreamContext *sc = st->priv_data;
13262 FFStream *const sti = ffstream(st);
13263 int64_t key_sample_dts, key_sample_pts;
13264
13266 return 1;
13267
13268 if (sample >= sc->sample_offsets_count)
13269 return 1;
13270
13271 av_assert0(sample >= 0);
13272 key_sample_dts = sti->index_entries[sample].timestamp;
13273 key_sample_pts = key_sample_dts + sc->sample_offsets[sample] + sc->dts_shift;
13274
13275 /*
13276 * If the sample needs to be presented before an open key sample, they may
13277 * not be decodable properly, even though they come after in decoding
13278 * order.
13279 */
13280 if (is_open_key_sample(sc, sample) && key_sample_pts > requested_pts)
13281 return 0;
13282
13283 return 1;
13284}
13285
13286static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp, int flags)
13287{
13288 MOVStreamContext *sc = st->priv_data;
13289 FFStream *const sti = ffstream(st);
13290 int sample, time_sample, ret, requested_sample;
13291 int64_t next_ts;
13292 unsigned int i;
13293
13294 // Here we consider timestamp to be PTS, hence try to offset it so that we
13295 // can search over the DTS timeline.
13296 timestamp -= (sc->min_corrected_pts + sc->dts_shift);
13297
13298 ret = mov_seek_fragment(s, st, timestamp);
13299 if (ret < 0)
13300 return ret;
13301
13302 for (;;) {
13303 sample = av_index_search_timestamp(st, timestamp, flags);
13304 av_log(s, AV_LOG_TRACE, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
13305 if (sample < 0 && sti->nb_index_entries && timestamp < sti->index_entries[0].timestamp)
13306 sample = 0;
13307 if (sample < 0) /* not sure what to do */
13308 return AVERROR_INVALIDDATA;
13309
13310 if (!sample || can_seek_to_key_sample(st, sample, timestamp))
13311 break;
13312
13313 next_ts = timestamp - FFMAX(sc->min_sample_duration, 1);
13314 requested_sample = av_index_search_timestamp(st, next_ts, flags);
13315 if (requested_sample < 0)
13316 return AVERROR_INVALIDDATA;
13317
13318 // If we've reached a different sample trying to find a good pts to
13319 // seek to, give up searching because we'll end up seeking back to
13320 // sample 0 on every seek.
13321 if (sample != requested_sample && !can_seek_to_key_sample(st, requested_sample, next_ts))
13322 break;
13323
13324 timestamp = next_ts;
13325 }
13326
13328 av_log(s, AV_LOG_TRACE, "stream %d, found sample %d\n", st->index, sc->current_sample);
13329 /* adjust time to sample index */
13330 if (sc->tts_data) {
13331 time_sample = 0;
13332 for (i = 0; i < sc->tts_count; i++) {
13333 int next = time_sample + sc->tts_data[i].count;
13334 if (next > sc->current_sample) {
13335 sc->tts_index = i;
13336 sc->tts_sample = sc->current_sample - time_sample;
13337 break;
13338 }
13339 time_sample = next;
13340 }
13341 }
13342
13343 /* adjust stsd index */
13344 if (sc->chunk_count) {
13345 time_sample = 0;
13346 for (i = 0; i < sc->stsc_count; i++) {
13347 int64_t next = time_sample + mov_get_stsc_samples(sc, i);
13348 if (next > sc->current_sample) {
13349 sc->stsc_index = i;
13350 sc->stsc_sample = sc->current_sample - time_sample;
13351 break;
13352 }
13353 av_assert0(next == (int)next);
13354 time_sample = next;
13355 }
13356 }
13357
13358 return sample;
13359}
13360
13362{
13363 FFStream *const sti = ffstream(st);
13364 int64_t first_ts = sti->index_entries[0].timestamp;
13366 int64_t off;
13367
13369 return 0;
13370
13371 /* compute skip samples according to stream initial_padding, seek ts and first ts */
13372 off = av_rescale_q(ts - first_ts, st->time_base,
13373 (AVRational){1, st->codecpar->sample_rate});
13374 return FFMAX(st->codecpar->initial_padding - off, 0);
13375}
13376
13377static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
13378{
13379 MOVContext *mc = s->priv_data;
13380 AVStream *st;
13381 FFStream *sti;
13382 int sample;
13383 int i;
13384
13385 if (stream_index >= s->nb_streams)
13386 return AVERROR_INVALIDDATA;
13387
13388 st = s->streams[stream_index];
13389 sti = ffstream(st);
13390 sample = mov_seek_stream(s, st, sample_time, flags);
13391 if (sample < 0)
13392 return sample;
13393
13394 if (mc->seek_individually) {
13395 /* adjust seek timestamp to found sample timestamp */
13396 int64_t seek_timestamp = sti->index_entries[sample].timestamp;
13397 int64_t next_root_atom = mc->next_root_atom;
13399
13400 for (i = 0; i < s->nb_streams; i++) {
13401 AVStream *const st = s->streams[i];
13402 FFStream *const sti = ffstream(st);
13403 const MOVStreamContext *sc = st->priv_data;
13404 int64_t timestamp;
13405
13406 if (stream_index == i)
13407 continue;
13408
13409 mc->next_root_atom = 0;
13410 timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
13411 sample = mov_seek_stream(s, st, timestamp, flags);
13412 if (sample >= 0)
13414
13415 /* Reading resumes from the earliest fragment a read stream landed
13416 * in; a discarded chapter track would send it back to the start. */
13417 if ((st->discard != AVDISCARD_ALL || sc->iamf) && mc->next_root_atom &&
13418 (!next_root_atom || mc->next_root_atom < next_root_atom))
13419 next_root_atom = mc->next_root_atom;
13420 }
13421 mc->next_root_atom = next_root_atom;
13422 } else {
13423 for (i = 0; i < s->nb_streams; i++) {
13424 MOVStreamContext *sc;
13425 st = s->streams[i];
13426 sc = st->priv_data;
13428 }
13429 while (1) {
13430 MOVStreamContext *sc;
13432 if (!entry)
13433 return AVERROR_INVALIDDATA;
13434 sc = st->priv_data;
13435 if (sc->ffindex == stream_index && sc->current_sample == sample)
13436 break;
13438 }
13439 }
13440 return 0;
13441}
13442
13443#define OFFSET(x) offsetof(MOVContext, x)
13444#define FLAGS AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
13445static const AVOption mov_options[] = {
13446 {"use_absolute_path",
13447 "allow using absolute path when opening alias, this is a possible security issue",
13448 OFFSET(use_absolute_path), AV_OPT_TYPE_BOOL, {.i64 = 0},
13449 0, 1, FLAGS},
13450 {"seek_streams_individually",
13451 "Seek each stream individually to the closest point",
13452 OFFSET(seek_individually), AV_OPT_TYPE_BOOL, { .i64 = 1 },
13453 0, 1, FLAGS},
13454 {"ignore_editlist", "Ignore the edit list atom.", OFFSET(ignore_editlist), AV_OPT_TYPE_BOOL, {.i64 = 0},
13455 0, 1, FLAGS},
13456 {"advanced_editlist",
13457 "Modify the AVIndex according to the editlists. Use this option to decode in the order specified by the edits.",
13458 OFFSET(advanced_editlist), AV_OPT_TYPE_BOOL, {.i64 = 1},
13459 0, 1, FLAGS},
13460 {"ignore_chapters", "", OFFSET(ignore_chapters), AV_OPT_TYPE_BOOL, {.i64 = 0},
13461 0, 1, FLAGS},
13462 {"use_mfra_for",
13463 "use mfra for fragment timestamps",
13464 OFFSET(use_mfra_for), AV_OPT_TYPE_INT, {.i64 = FF_MOV_FLAG_MFRA_AUTO},
13466 .unit = "use_mfra_for"},
13467 {"auto", "auto", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_AUTO}, 0, 0,
13468 FLAGS, .unit = "use_mfra_for" },
13469 {"dts", "dts", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_DTS}, 0, 0,
13470 FLAGS, .unit = "use_mfra_for" },
13471 {"pts", "pts", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_PTS}, 0, 0,
13472 FLAGS, .unit = "use_mfra_for" },
13473 {"use_tfdt", "use tfdt for fragment timestamps", OFFSET(use_tfdt), AV_OPT_TYPE_BOOL, {.i64 = 1},
13474 0, 1, FLAGS},
13475 { "export_all", "Export unrecognized metadata entries", OFFSET(export_all),
13476 AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, .flags = FLAGS },
13477 { "export_xmp", "Export full XMP metadata", OFFSET(export_xmp),
13478 AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, .flags = FLAGS },
13479 { "activation_bytes", "Secret bytes for Audible AAX files", OFFSET(activation_bytes),
13481 { "audible_key", "AES-128 Key for Audible AAXC files", OFFSET(audible_key),
13483 { "audible_iv", "AES-128 IV for Audible AAXC files", OFFSET(audible_iv),
13485 { "audible_fixed_key", // extracted from libAAX_SDK.so and AAXSDKWin.dll files!
13486 "Fixed key used for handling Audible AAX files", OFFSET(audible_fixed_key),
13487 AV_OPT_TYPE_BINARY, {.str="77214d4b196a87cd520045fd20a51d67"},
13488 .flags = AV_OPT_FLAG_DECODING_PARAM },
13489 { "decryption_key", "The default media decryption key (hex)", OFFSET(decryption_default_key), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_DECODING_PARAM },
13490 { "decryption_keys", "The media decryption keys by KID (hex)", OFFSET(decryption_keys), AV_OPT_TYPE_DICT, .flags = AV_OPT_FLAG_DECODING_PARAM },
13491 { "enable_drefs", "Enable external track support.", OFFSET(enable_drefs), AV_OPT_TYPE_BOOL,
13492 {.i64 = 0}, 0, 1, FLAGS },
13493 { "max_stts_delta", "treat offsets above this value as invalid", OFFSET(max_stts_delta), AV_OPT_TYPE_INT, {.i64 = UINT_MAX-48000*10 }, 0, UINT_MAX, .flags = AV_OPT_FLAG_DECODING_PARAM },
13494 { "interleaved_read", "Interleave packets from multiple tracks at demuxer level", OFFSET(interleaved_read), AV_OPT_TYPE_BOOL, {.i64 = 1 }, 0, 1, .flags = AV_OPT_FLAG_DECODING_PARAM },
13495
13496 { NULL },
13497};
13498
13499static const AVClass mov_class = {
13500 .class_name = "mov,mp4,m4a,3gp,3g2,mj2",
13501 .item_name = av_default_item_name,
13502 .option = mov_options,
13503 .version = LIBAVUTIL_VERSION_INT,
13504};
13505
13507 .p.name = "mov,mp4,m4a,3gp,3g2,mj2",
13508 .p.long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
13509 .p.priv_class = &mov_class,
13510 .p.extensions = "mov,mp4,m4a,3gp,3g2,mj2,psp,m4v,m4b,ism,ismv,isma,f4v,avif,heic,heif",
13512 .priv_data_size = sizeof(MOVContext),
13513 .flags_internal = FF_INFMT_FLAG_INIT_CLEANUP,
13519};
uint8_t ptrdiff_t const uint8_t ptrdiff_t int intptr_t intptr_t int int16_t * dst
Definition dsp.h:97
const uint16_t ff_ac3_channel_layout_tab[8]
Map audio coding mode (acmod) to channel layout mask.
static double val(void *priv, double ch)
Definition aeval.c:77
static const char *const format[]
Definition af_aiir.c:445
#define ctype
#define ALAC_EXTRADATA_SIZE
Definition alac.c:63
const FFInputFormat ff_mov_demuxer
Definition mov.c:13506
AVAmbientViewingEnvironment * av_ambient_viewing_environment_alloc(size_t *size)
Allocate an AVAmbientViewingEnvironment structure.
#define entry
static FILE * out
static int out_size
static AVFormatContext * ctx
static void finish(void)
static int parse(AVCodecParserContext *s, AVCodecContext *avctx, const uint8_t **poutbuf, int *poutbuf_size, const uint8_t *buf, int buf_size)
Definition apv_parser.c:92
int32_t
simple assert() macros that are a bit more flexible than ISO C assert().
#define av_unreachable(msg)
Asserts that are used as compiler optimization hints depending upon ASSERT_LEVEL and NBDEBUG.
Definition avassert.h:109
#define av_assert0(cond)
assert() equivalent, that is always enabled.
Definition avassert.h:42
int ff_format_io_close(AVFormatContext *s, AVIOContext **pb)
Definition avformat.c:992
void avpriv_set_pts_info(AVStream *st, int pts_wrap_bits, unsigned int pts_num, unsigned int pts_den)
Set the time base and wrapping info for a given stream.
Definition avformat.c:865
void ff_remove_stream(AVFormatContext *s, AVStream *st)
Remove a stream from its AVFormatContext and free it.
Definition avformat.c:137
void ff_remove_stream_group(AVFormatContext *s, AVStreamGroup *stg)
Remove a stream group from its AVFormatContext and free it.
Definition avformat.c:145
Main libavformat public API header.
#define AVFMT_EVENT_FLAG_METADATA_UPDATED
Definition avformat.h:1796
#define AVINDEX_KEYFRAME
Definition avformat.h:630
#define AVPROBE_SCORE_MAX
maximum score
Definition avformat.h:485
#define AVFMT_FLAG_IGNIDX
Ignore index.
Definition avformat.h:1555
@ AV_STREAM_GROUP_PARAMS_DOLBY_VISION
Definition avformat.h:1164
@ AV_STREAM_GROUP_PARAMS_TREF
Definition avformat.h:1163
@ AV_STREAM_GROUP_PARAMS_ALPHA
Definition avformat.h:1166
@ AV_STREAM_GROUP_PARAMS_IAMF_MIX_PRESENTATION
Definition avformat.h:1160
@ AV_STREAM_GROUP_PARAMS_TILE_GRID
Definition avformat.h:1161
@ AV_STREAM_GROUP_PARAMS_IAMF_AUDIO_ELEMENT
Definition avformat.h:1159
@ AV_STREAM_GROUP_PARAMS_LCEVC
Definition avformat.h:1162
@ AV_STREAM_GROUP_PARAMS_GAIN_MAP
Definition avformat.h:1165
#define AVFMT_NO_BYTE_SEEK
Format does not allow seeking by bytes.
Definition avformat.h:508
#define AV_DISPOSITION_MULTILAYER
The video stream contains multiple layers, e.g.
Definition avformat.h:738
#define AV_DISPOSITION_DEPENDENT
The stream is intended to be mixed with another stream before presentation.
Definition avformat.h:729
#define AV_DISPOSITION_NON_DIEGETIC
The stream is intended to be mixed with a spatial audio track.
Definition avformat.h:706
#define AVPROBE_SCORE_EXTENSION
score for file extension
Definition avformat.h:483
#define AVFMT_SHOW_IDS
Show format stream IDs numbers.
Definition avformat.h:498
#define AVSEEK_FLAG_ANY
seek to any frame, even non-keyframes
Definition avformat.h:2749
int av_get_packet(AVIOContext *s, AVPacket *pkt, int size)
Allocate and read the payload of a packet and initialize its fields with default values.
Definition utils.c:98
#define AV_DISPOSITION_ATTACHED_PIC
The stream is stored in the file as an attached picture/"cover art" (e.g.
Definition avformat.h:694
#define AVFMT_SEEK_TO_PTS
Seeking is based on PTS.
Definition avformat.h:522
#define AVINDEX_DISCARD_FRAME
Definition avformat.h:631
#define AVSEEK_FLAG_BACKWARD
seek backward
Definition avformat.h:2747
#define AV_DISPOSITION_DEFAULT
The stream should be chosen by default among other streams of the same type, unless the user has expl...
Definition avformat.h:641
#define AV_DISPOSITION_TIMED_THUMBNAILS
The stream is sparse, and contains thumbnail images, often corresponding to chapter markers.
Definition avformat.h:699
@ AVSTREAM_PARSE_HEADERS
Only parse headers, do not repack.
Definition avformat.h:614
@ AVSTREAM_PARSE_FULL
full parsing and repack
Definition avformat.h:613
int avio_get_str16be(AVIOContext *pb, int maxlen, char *buf, int buflen)
int64_t avio_seek(AVIOContext *s, int64_t offset, int whence)
fseek() equivalent for AVIOContext.
Definition aviobuf.c:236
#define AVIO_SEEKABLE_NORMAL
Seeking works like for a local file.
Definition avio.h:41
uint64_t avio_rb64(AVIOContext *s)
#define AVIO_FLAG_READ
read-only
Definition avio.h:630
int64_t avio_size(AVIOContext *s)
Get the filesize.
Definition aviobuf.c:326
unsigned int avio_rb16(AVIOContext *s)
int avio_get_str16le(AVIOContext *pb, int maxlen, char *buf, int buflen)
Read a UTF-16 string from pb and convert it to UTF-8.
int avio_feof(AVIOContext *s)
Similar to feof() but also returns nonzero on read errors.
Definition aviobuf.c:349
static av_always_inline int64_t avio_tell(AVIOContext *s)
ftell() equivalent for AVIOContext.
Definition avio.h:507
int64_t avio_skip(AVIOContext *s, int64_t offset)
Skip given number of bytes forward.
Definition aviobuf.c:321
int avio_read(AVIOContext *s, unsigned char *buf, int size)
Read size bytes from AVIOContext into buf.
Definition aviobuf.c:620
unsigned int avio_rl32(AVIOContext *s)
int avio_get_str(AVIOContext *pb, int maxlen, char *buf, int buflen)
Read a string from pb into buf.
Definition aviobuf.c:845
unsigned int avio_rb24(AVIOContext *s)
unsigned int avio_rb32(AVIOContext *s)
int avio_r8(AVIOContext *s)
Definition aviobuf.c:611
int ffio_ensure_seekback(AVIOContext *s, int64_t buf_size)
Ensures that the requested seekback buffer size will be available.
Definition aviobuf.c:994
int64_t ff_read_string_to_bprint_overwrite(AVIOContext *s, struct AVBPrint *bp, int64_t max_len)
Read a whole null-terminated string of text from AVIOContext to an AVBPrint buffer overwriting its co...
Definition aviobuf.c:839
void ffio_init_read_context(FFIOContext *s, const uint8_t *buffer, int buffer_size)
Wrap a buffer in an AVIOContext for reading.
Definition aviobuf.c:99
int ffio_read_size(AVIOContext *s, unsigned char *buf, int size)
Read size bytes from AVIOContext into buf.
Definition aviobuf.c:674
unsigned int ffio_read_leb(AVIOContext *s)
Read a unsigned integer coded as a variable number of up to eight little-endian bytes,...
Definition aviobuf.c:898
static int read_packet(void *opaque, uint8_t *buf, int buf_size)
static int BS_FUNC left(const BSCTX *bc)
Return the number of the bits left in a buffer.
void av_bprint_init(AVBPrint *buf, unsigned size_init, unsigned size_max)
Definition bprint.c:68
AVBPrint public header.
#define AV_BPRINT_SIZE_UNLIMITED
#define AV_BPRINT_SIZE_AUTOMATIC
static int FUNC metadata(CodedBitstreamContext *ctx, RWContext *rw, APVRawMetadata *current)
#define flag(name)
Definition cbs_h264.c:60
#define flags(name, subs,...)
Definition cbs_h264.c:74
#define i(width, name, range_min, range_max)
Definition cbs_h264.c:63
#define f(width, name)
Definition cbs_vp8.c:236
#define ss(width, name, subs,...)
Definition cbs_vp9.c:202
#define s(width, name)
Definition cbs_vp9.c:198
static int read_probe(const AVProbeData *p)
Definition cdg.c:30
Public libavutil channel layout APIs header.
#define FLAGS
Definition cmdutils.c:596
int avcodec_parameters_copy(AVCodecParameters *dst, const AVCodecParameters *src)
Definition codec_par.c:107
#define av_sat_sub64
Definition common.h:142
#define av_sat_add64
Definition common.h:139
#define PUT_UTF8(val, tmp, PUT_BYTE)
Convert a 32-bit Unicode character to its UTF-8 encoded form (up to 4 bytes long).
Definition common.h:530
#define av_clip64
Definition common.h:103
#define NULL
Definition coverity.c:32
long long int64_t
Definition coverity.c:34
static const AVColorPrimariesDesc color_primaries[AVCOL_PRI_NB]
Definition csp.c:76
static __device__ float fabs(float a)
static const uint16_t fc[]
Definition dcaenc.h:43
#define AV_PROFILE_DTS_EXPRESS
Definition defs.h:101
#define AV_PROFILE_DTS_HD_MA
Definition defs.h:100
#define AV_PROFILE_DTS
Definition defs.h:96
#define AV_PROFILE_UNKNOWN
Definition defs.h:65
#define AV_PROFILE_DTS_HD_HRA
Definition defs.h:99
#define AV_EF_COMPLIANT
consider all spec non compliances as errors
Definition defs.h:55
#define FF_COMPLIANCE_STRICT
Strictly conform to all the things in the spec no matter what consequences.
Definition defs.h:59
#define AV_EF_EXPLODE
abort decoding on minor error detection
Definition defs.h:51
AVFieldOrder
Definition defs.h:227
@ AV_FIELD_TT
Top coded_first, top displayed first.
Definition defs.h:230
@ AV_FIELD_BB
Bottom coded first, bottom displayed first.
Definition defs.h:231
@ AV_FIELD_UNKNOWN
Definition defs.h:228
@ AV_FIELD_PROGRESSIVE
Definition defs.h:229
@ AV_FIELD_BT
Bottom coded first, top displayed first.
Definition defs.h:233
@ AV_FIELD_TB
Top coded first, bottom displayed first.
Definition defs.h:232
#define AV_PROFILE_DTS_96_24
Definition defs.h:98
AVAudioServiceType
Definition defs.h:251
@ AV_AUDIO_SERVICE_TYPE_KARAOKE
Definition defs.h:260
#define AV_PROFILE_DTS_ES
Definition defs.h:97
int ff_buffer_packet(AVFormatContext *s, AVPacket *pkt)
Definition demux.c:645
void ff_rfps_calculate(AVFormatContext *ic)
Definition demux.c:2471
int ff_rfps_add_frame(AVFormatContext *ic, AVStream *st, int64_t ts)
add frame for rfps calculation.
Definition demux.c:2410
AVChapter * avpriv_new_chapter(AVFormatContext *s, int64_t id, AVRational time_base, int64_t start, int64_t end, const char *title)
Add a new chapter.
Definition demux_utils.c:46
#define FF_INFMT_FLAG_INIT_CLEANUP
For an FFInputFormat with this flag set read_close() needs to be called by the caller upon read_heade...
Definition demux.h:35
int ff_itunes_parse_smpb(const char *value, int64_t *priming, int64_t *remainder, int64_t *samples)
Parse the gapless playback information Apple encoders store in an iTunSMPB tag.
void ff_configure_buffers_for_index(AVFormatContext *s, int64_t time_tolerance)
Definition seek.c:175
int ff_generate_avci_extradata(AVStream *st)
Generate standard extradata for AVC-Intra based on width/height and field order.
#define FFERROR_REDO
Returned by demuxers to indicate that data was consumed but discarded (ignored streams or junk data).
Definition demux.h:234
int ff_get_extradata(void *logctx, AVCodecParameters *par, AVIOContext *pb, int size)
Allocate extradata with additional AV_INPUT_BUFFER_PADDING_SIZE at end which is always set to 0 and f...
int ff_add_attached_pic(AVFormatContext *s, AVStream *st, AVIOContext *pb, AVBufferRef **buf, int size)
Add an attached pic to an AVStream.
static AVPacket * pkt
#define OPUS_SEEK_PREROLL_MS
Definition opus.c:38
Public dictionary API.
Display matrix.
int ff_isom_parse_dvcc_dvvc(void *logctx, AVStream *st, const uint8_t *buf_ptr, uint64_t size)
Definition dovi_isom.c:32
#define ISOM_DVCC_DVVC_SIZE
Definition dovi_isom.h:29
DOVI configuration.
enum AVCodecID id
Definition dts2pts.c:612
int ff_dvdclut_yuv_to_rgb(uint32_t *clut, const size_t clut_size)
Definition dvdclut.c:50
int ff_dvdclut_palette_extradata_cat(const uint32_t *clut, const size_t clut_size, AVCodecParameters *par)
Definition dvdclut.c:28
#define FF_DVDCLUT_CLUT_SIZE
Definition dvdclut.h:29
#define FF_DVDCLUT_CLUT_LEN
Definition dvdclut.h:28
channel
Use these values when setting the channel map with ebur128_set_channel().
Definition ebur128.h:39
AVEncryptionInfo * av_encryption_info_alloc(uint32_t subsample_count, uint32_t key_id_size, uint32_t iv_size)
Allocates an AVEncryptionInfo structure and sub-pointers to hold the given number of subsamples.
AVEncryptionInfo * av_encryption_info_clone(const AVEncryptionInfo *info)
Allocates an AVEncryptionInfo structure with a copy of the given data.
int av_encryption_init_info_append_side_data(uint8_t **side_data, size_t *side_data_size, unsigned int *allocated_size, const AVEncryptionInitInfo *info)
Appends a copy of the given encryption init info list to encryption init info side data,...
uint8_t * av_encryption_info_add_side_data(const AVEncryptionInfo *info, size_t *size)
Allocates and initializes side data that holds a copy of the given encryption info.
AVEncryptionInitInfo * av_encryption_init_info_alloc(uint32_t system_id_size, uint32_t num_key_ids, uint32_t key_id_size, uint32_t data_size)
Allocates an AVEncryptionInitInfo structure and sub-pointers to hold the given sizes.
void av_encryption_init_info_free(AVEncryptionInitInfo *info)
Frees the given encryption init info object.
void av_encryption_info_free(AVEncryptionInfo *info)
Frees the given encryption info object.
double value
Definition eval.c:102
int av_exif_get_entry(void *logctx, AVExifMetadata *ifd, uint16_t id, int flags, AVExifEntry **value)
Get an entry with the tagged ID from the EXIF metadata struct.
Definition exif.c:1204
int av_exif_parse_buffer(void *logctx, const uint8_t *buf, size_t size, AVExifMetadata *ifd, enum AVExifHeaderMode header_mode)
Decodes the EXIF data provided in the buffer and writes it into the struct *ifd.
Definition exif.c:902
void av_exif_free(AVExifMetadata *ifd)
Frees all resources associated with the given EXIF metadata struct.
Definition exif.c:679
int av_exif_write(void *logctx, const AVExifMetadata *ifd, AVBufferRef **buffer, enum AVExifHeaderMode header_mode)
Allocates a buffer using av_malloc of an appropriate size and writes the EXIF data represented by ifd...
Definition exif.c:773
int32_t av_exif_get_tag_id(const char *name)
Retrieves the tag ID associated with the provided tag string name.
Definition exif.c:245
int av_exif_remove_entry(void *logctx, AVExifMetadata *ifd, uint16_t id, int flags)
Remove an entry from the provided EXIF metadata struct.
Definition exif.c:1303
EXIF metadata parser.
@ AV_TIFF_SRATIONAL
Definition exif.h:51
@ AV_EXIF_TIFF_HEADER
The TIFF header starts with 0x49492a00, or 0x4d4d002a.
Definition exif.h:62
@ AV_EXIF_T_OFF
The first four bytes point to the actual start, then it's AV_EXIF_TIFF_HEADER.
Definition exif.h:68
static struct @111144215057303131116103221376075045141373005341 current
const char * key
static int64_t duration
Definition ffplay.c:359
int ret
Definition ffplay.c:391
static int64_t start_time
Definition ffplay.c:358
static int read_header(FFV1Context *f, RangeCoder *c)
Definition ffv1dec.c:580
FLAC (Free Lossless Audio Codec) common stuff.
@ FLAC_METADATA_TYPE_STREAMINFO
Definition flac.h:46
static av_always_inline void flac_parse_block_header(const uint8_t *block_header, int *last, int *type, int *size)
Parse the metadata block parameters from the header.
Definition flac.h:63
#define FLAC_STREAMINFO_SIZE
Definition flac.h:32
#define sample
static av_cold void cleanup(FlashSV2Context *s)
bitstream reader API header.
static unsigned int get_bits_long(GetBitContext *s, int n)
Read 0-32 bits.
Definition get_bits.h:424
static void skip_bits_long(GetBitContext *s, int n)
Skips the specified number of bits.
Definition get_bits.h:280
static void skip_bits(GetBitContext *s, int n)
Definition get_bits.h:383
static unsigned int get_bits(GetBitContext *s, int n)
Read 1-25 bits.
Definition get_bits.h:337
static int init_get_bits(GetBitContext *s, const uint8_t *buffer, int bit_size)
Initialize GetBitContext.
Definition get_bits.h:517
#define fail
Definition test.h:479
#define AV_OPT_FLAG_DECODING_PARAM
A generic parameter which can be set by the user for demuxing or decoding.
Definition opt.h:355
@ AV_OPT_TYPE_CONST
Special option type for declaring named constants.
Definition opt.h:298
@ AV_OPT_TYPE_BINARY
Underlying C type is a uint8_t* that is either NULL or points to an array allocated with the av_mallo...
Definition opt.h:285
@ AV_OPT_TYPE_INT
Underlying C type is int.
Definition opt.h:258
@ AV_OPT_TYPE_DICT
Underlying C type is AVDictionary*.
Definition opt.h:289
@ AV_OPT_TYPE_BOOL
Underlying C type is int.
Definition opt.h:326
#define AV_CH_SIDE_LEFT
#define AV_CH_SIDE_SURROUND_RIGHT
#define AV_CH_WIDE_LEFT
#define AV_CH_WIDE_RIGHT
#define AV_CH_TOP_FRONT_LEFT
#define AV_CH_FRONT_RIGHT
#define AV_CH_SIDE_SURROUND_LEFT
#define AV_CH_TOP_BACK_CENTER
#define AV_CH_FRONT_RIGHT_OF_CENTER
#define AV_CH_BACK_CENTER
#define AV_CH_TOP_FRONT_CENTER
#define AV_CH_FRONT_LEFT_OF_CENTER
#define AV_CH_LOW_FREQUENCY_2
#define AV_CH_BACK_RIGHT
#define AV_CH_TOP_SIDE_RIGHT
#define AV_CH_FRONT_CENTER
#define AV_CH_TOP_BACK_RIGHT
#define AV_CH_TOP_CENTER
#define AV_CH_SIDE_RIGHT
#define AV_CH_BACK_LEFT
#define AV_CH_TOP_SIDE_LEFT
#define AV_CH_TOP_BACK_LEFT
#define AV_CH_LOW_FREQUENCY
#define AV_CH_TOP_FRONT_RIGHT
#define AV_CH_FRONT_LEFT
int av_get_bits_per_sample(enum AVCodecID codec_id)
Return codec bits per sample.
Definition utils.c:557
AVCodecID
Identify the syntax and semantics of the bitstream.
Definition codec_id.h:47
@ AV_CODEC_ID_PCM_F32LE
Definition codec_id.h:354
@ AV_CODEC_ID_PCM_S24BE
Definition codec_id.h:346
@ AV_CODEC_ID_VORBIS
Definition codec_id.h:464
@ AV_CODEC_ID_H261
Definition codec_id.h:53
@ AV_CODEC_ID_FLV1
Definition codec_id.h:71
@ AV_CODEC_ID_PNG
Definition codec_id.h:111
@ AV_CODEC_ID_EAC3
Definition codec_id.h:499
@ AV_CODEC_ID_PCM_U8
Definition codec_id.h:338
@ AV_CODEC_ID_APV
Definition codec_id.h:323
@ AV_CODEC_ID_LCEVC
Definition codec_id.h:615
@ AV_CODEC_ID_PCM_S16LE
Definition codec_id.h:333
@ AV_CODEC_ID_GSM
as in Berlin toast format
Definition codec_id.h:477
@ AV_CODEC_ID_DVD_SUBTITLE
Definition codec_id.h:572
@ AV_CODEC_ID_TTML
Definition codec_id.h:596
@ AV_CODEC_ID_PCM_F32BE
Definition codec_id.h:353
@ AV_CODEC_ID_SVQ3
Definition codec_id.h:73
@ AV_CODEC_ID_H264
Definition codec_id.h:77
@ AV_CODEC_ID_NONE
Definition codec_id.h:48
@ AV_CODEC_ID_JPEG2000
Definition codec_id.h:138
@ AV_CODEC_ID_PCM_S16BE
Definition codec_id.h:334
@ AV_CODEC_ID_PCM_S24LE
Definition codec_id.h:345
@ AV_CODEC_ID_PCM_S32LE
Definition codec_id.h:341
@ AV_CODEC_ID_PCM_S8
Definition codec_id.h:337
@ AV_CODEC_ID_AV1
Definition codec_id.h:275
@ AV_CODEC_ID_ADPCM_MS
Definition codec_id.h:380
@ AV_CODEC_ID_VC1
Definition codec_id.h:120
@ AV_CODEC_ID_VP8
Definition codec_id.h:190
@ AV_CODEC_ID_PCM_F64LE
Definition codec_id.h:356
@ AV_CODEC_ID_ALAC
Definition codec_id.h:475
@ AV_CODEC_ID_EIA_608
Definition codec_id.h:582
@ AV_CODEC_ID_AMR_NB
Definition codec_id.h:440
@ AV_CODEC_ID_CAVS
Definition codec_id.h:137
@ AV_CODEC_ID_PRORES_RAW
Definition codec_id.h:324
@ AV_CODEC_ID_MP2
Definition codec_id.h:459
@ AV_CODEC_ID_DVAUDIO
Definition codec_id.h:465
@ AV_CODEC_ID_ADPCM_IMA_QT
Definition codec_id.h:374
@ AV_CODEC_ID_HEVC
Definition codec_id.h:223
@ AV_CODEC_ID_BIN_DATA
Definition codec_id.h:613
@ AV_CODEC_ID_AAC
Definition codec_id.h:461
@ AV_CODEC_ID_PRORES
Definition codec_id.h:198
@ AV_CODEC_ID_BMP
Definition codec_id.h:128
@ AV_CODEC_ID_PCM_F64BE
Definition codec_id.h:355
@ AV_CODEC_ID_H263
Definition codec_id.h:54
@ AV_CODEC_ID_QCELP
Definition codec_id.h:483
@ AV_CODEC_ID_AMR_WB
Definition codec_id.h:441
@ AV_CODEC_ID_AC3
Definition codec_id.h:462
@ AV_CODEC_ID_MACE3
Definition codec_id.h:468
@ AV_CODEC_ID_MACE6
Definition codec_id.h:469
@ AV_CODEC_ID_QDM2
Definition codec_id.h:478
@ AV_CODEC_ID_PCM_S32BE
Definition codec_id.h:342
@ AV_CODEC_ID_DNXHD
Definition codec_id.h:149
@ AV_CODEC_ID_MPEG4
Definition codec_id.h:62
@ AV_CODEC_ID_MJPEG
Definition codec_id.h:57
@ AV_CODEC_ID_ADPCM_IMA_WAV
Definition codec_id.h:375
@ AV_CODEC_ID_R10K
Definition codec_id.h:195
@ AV_CODEC_ID_EVC
Definition codec_id.h:316
@ AV_CODEC_ID_SPEEX
Definition codec_id.h:494
@ AV_CODEC_ID_AVUI
Definition codec_id.h:252
@ AV_CODEC_ID_ILBC
Definition codec_id.h:518
@ AV_CODEC_ID_MP3
preferred ID for decoding MPEG audio layer 1, 2 or 3
Definition codec_id.h:460
@ AV_CODEC_ID_VP9
Definition codec_id.h:217
@ AV_CODEC_ID_MPEG1VIDEO
Definition codec_id.h:51
@ AV_CODEC_ID_QDMC
Definition codec_id.h:509
@ AV_CODEC_ID_ITUT_T35
Definition codec_id.h:617
@ AV_CODEC_ID_TARGA_Y216
Definition codec_id.h:253
#define AV_INPUT_BUFFER_PADDING_SIZE
Required number of additionally allocated bytes at the end of the input bitstream for decoding.
Definition defs.h:40
@ AVDISCARD_ALL
discard all
Definition defs.h:248
@ AVDISCARD_NONKEY
discard all frames except keyframes
Definition defs.h:247
AVPacketSideData * av_packet_side_data_new(AVPacketSideData **psd, int *pnb_sd, enum AVPacketSideDataType type, size_t size, int flags)
Allocate a new packet side data.
Definition packet.c:621
AVPacketSideData * av_packet_side_data_add(AVPacketSideData **psd, int *pnb_sd, enum AVPacketSideDataType type, void *data, size_t size, int flags)
Wrap existing data as packet side data.
Definition packet.c:614
const AVPacketSideData * av_packet_side_data_get(const AVPacketSideData *sd, int nb_sd, enum AVPacketSideDataType type)
Get side information from a side data array.
Definition packet.c:571
@ AV_PKT_DATA_HEVC_CONF
Dolby Vision enhancement-layer HEVC decoder configuration.
Definition packet.h:384
@ AV_PKT_DATA_AMBIENT_VIEWING_ENVIRONMENT
Ambient viewing environment metadata, as defined by H.274.
Definition packet.h:327
@ AV_PKT_DATA_GAIN_MAP_PARAMS
Parameters describing how to combine this gain map with its base image to form an alternate rendition...
Definition packet.h:391
@ AV_PKT_DATA_ICC_PROFILE
ICC profile data consisting of an opaque octet buffer following the format described by ISO 15076-1.
Definition packet.h:271
@ AV_PKT_DATA_MASTERING_DISPLAY_METADATA
Mastering display metadata (based on SMPTE-2086:2014).
Definition packet.h:219
@ AV_PKT_DATA_AUDIO_SERVICE_TYPE
This side data should be associated with an audio stream and corresponds to enum AVAudioServiceType.
Definition packet.h:117
@ AV_PKT_DATA_SPHERICAL
This side data should be associated with a video stream and corresponds to the AVSphericalMapping str...
Definition packet.h:225
@ AV_PKT_DATA_PALETTE
An AV_PKT_DATA_PALETTE side data packet contains exactly AVPALETTE_SIZE bytes worth of palette.
Definition packet.h:47
@ AV_PKT_DATA_ENCRYPTION_INFO
This side data contains encryption info for how to decrypt the packet.
Definition packet.h:252
@ AV_PKT_DATA_DISPLAYMATRIX
This side data contains a 3x3 transformation matrix describing an affine transformation that needs to...
Definition packet.h:105
@ AV_PKT_DATA_EXIF
Extensible image file format metadata.
Definition packet.h:369
@ AV_PKT_DATA_ENCRYPTION_INIT_INFO
This side data is encryption initialization data.
Definition packet.h:246
@ AV_PKT_DATA_NEW_EXTRADATA
The AV_PKT_DATA_NEW_EXTRADATA is used to notify the codec or the format that the extradata buffer was...
Definition packet.h:56
@ AV_PKT_DATA_STEREO3D
This side data should be associated with a video stream and contains Stereoscopic 3D information in f...
Definition packet.h:111
@ AV_PKT_DATA_FRAME_CROPPING
The number of pixels to discard from the top/bottom/left/right border of the decoded frame to obtain ...
Definition packet.h:340
@ AV_PKT_DATA_CONTENT_LIGHT_LEVEL
Content light level (based on CTA-861.3).
Definition packet.h:232
@ AV_PKT_DATA_DOVI_CONF
DOVI configuration ref: dolby-vision-bitstreams-within-the-iso-base-media-file-format-v2....
Definition packet.h:280
#define AV_PKT_FLAG_DISCARD
Flag is used to discard packets which are required to maintain valid decoder state but are not requir...
Definition packet.h:664
void av_packet_unref(AVPacket *pkt)
Wipe the packet.
Definition packet.c:435
uint8_t * av_packet_new_side_data(AVPacket *pkt, enum AVPacketSideDataType type, size_t size)
Allocate new information of a packet.
Definition packet.c:231
#define AV_PKT_FLAG_KEY
The packet contains a keyframe.
Definition packet.h:657
#define AV_PKT_FLAG_DISPOSABLE
Flag is used to indicate packets that contain frames that can be discarded by the decoder.
Definition packet.h:676
int av_packet_add_side_data(AVPacket *pkt, enum AVPacketSideDataType type, uint8_t *data, size_t size)
Wrap an existing array as a packet side data.
Definition packet.c:197
void av_shrink_packet(AVPacket *pkt, int size)
Reduce packet size, correctly zeroing padding.
Definition packet.c:113
int av_new_packet(AVPacket *pkt, int size)
Allocate the payload of a packet and initialize its fields with default values.
Definition packet.c:98
AVStreamGroup * avformat_stream_group_create(AVFormatContext *s, enum AVStreamGroupParamsType type, AVDictionary **options)
Add a new empty stream group to a media file.
Definition options.c:474
AVStream * avformat_new_stream(AVFormatContext *s, const struct AVCodec *c)
Add a new stream to a media file.
int avformat_stream_group_add_stream(AVStreamGroup *stg, AVStream *st)
Add an already allocated stream to a stream group.
Definition options.c:589
AVFormatContext * avformat_alloc_context(void)
Allocate an AVFormatContext.
Definition options.c:165
void avformat_free_context(AVFormatContext *s)
Free an AVFormatContext and all its streams.
Definition avformat.c:165
int avformat_stream_group_add_stream_group(AVStreamGroup *stg, AVStreamGroup *group)
Add an already allocated stream group to another stream group.
Definition options.c:631
void av_url_split(char *proto, int proto_size, char *authorization, int authorization_size, char *hostname, int hostname_size, int *port_ptr, char *path, int path_size, const char *url)
Split a URL string into components.
Definition utils.c:361
int av_index_search_timestamp(AVStream *st, int64_t timestamp, int flags)
Get the index for a specific timestamp.
Definition seek.c:245
struct AVAESCTR * av_aes_ctr_alloc(void)
Allocate an AVAESCTR context.
Definition aes_ctr.c:41
int av_aes_ctr_init(struct AVAESCTR *a, const uint8_t *key)
Initialize an AVAESCTR context.
Definition aes_ctr.c:74
void av_aes_ctr_set_full_iv(struct AVAESCTR *a, const uint8_t *iv)
Forcefully change the "full" 16-byte iv, including the counter.
Definition aes_ctr.c:53
void av_aes_ctr_crypt(struct AVAESCTR *a, uint8_t *dst, const uint8_t *src, int count)
Process a buffer using a previously initialized context.
Definition aes_ctr.c:102
void av_aes_ctr_free(struct AVAESCTR *a)
Release an AVAESCTR context.
Definition aes_ctr.c:84
#define AES_CTR_KEY_SIZE
Definition aes_ctr.h:35
struct AVAES * av_aes_alloc(void)
Allocate an AVAES context.
Definition aes.c:37
int av_aes_init(AVAES *a, const uint8_t *key, int key_bits, int decrypt)
Initialize an AVAES context.
Definition aes.c:231
void av_aes_crypt(AVAES *a, uint8_t *dst, const uint8_t *src, int count, uint8_t *iv, int decrypt)
Encrypt or decrypt a buffer using a previously initialized context.
Definition aes.c:171
int av_channel_layout_retype(AVChannelLayout *channel_layout, enum AVChannelOrder order, int flags)
Change the AVChannelOrder of a channel layout.
#define AV_CHANNEL_LAYOUT_RETYPE_FLAG_CANONICAL
The specified retype target order is ignored and the simplest possible (canonical) order is used for ...
#define AV_CHANNEL_LAYOUT_STEREO
#define AV_CHANNEL_LAYOUT_MONO
int av_channel_layout_custom_init(AVChannelLayout *channel_layout, int nb_channels)
Initialize a custom channel layout with the specified number of channels.
void av_channel_layout_uninit(AVChannelLayout *channel_layout)
Free any allocated data in the channel layout and reset the channel count to 0.
int av_channel_layout_from_mask(AVChannelLayout *channel_layout, uint64_t mask)
Initialize a native channel layout from a bitmask indicating which channels are present.
@ AV_CHANNEL_ORDER_UNSPEC
Only the channel count is specified, without any further information about the channel order.
@ AV_CHAN_AMBISONIC_BASE
Range of channels between AV_CHAN_AMBISONIC_BASE and AV_CHAN_AMBISONIC_END represent Ambisonic compon...
int av_bprint_finalize(AVBPrint *buf, char **ret_str)
Finalize a print buffer.
Definition bprint.c:234
void av_buffer_unref(AVBufferRef **buf)
Free a given reference and automatically free the buffer if there are no more references to it.
Definition buffer.c:140
void av_dict_free(AVDictionary **pm)
Free all the memory allocated for an AVDictionary struct and all keys and values.
Definition dict.c:236
AVDictionaryEntry * av_dict_get(const AVDictionary *m, const char *key, const AVDictionaryEntry *prev, int flags)
Get a dictionary entry with matching key.
Definition dict.c:61
int av_dict_copy(AVDictionary **dst, const AVDictionary *src, int flags)
Copy entries from one AVDictionary struct into another.
Definition dict.c:250
#define AV_DICT_APPEND
If the entry already exists, append to it.
Definition dict.h:82
#define AV_DICT_DONT_STRDUP_VAL
Take ownership of a value that's been allocated with av_malloc() or another memory allocation functio...
Definition dict.h:79
int av_dict_set(AVDictionary **pm, const char *key, const char *value, int flags)
Set the given entry in *pm, overwriting an existing entry.
Definition dict.c:87
#define AV_DICT_DONT_OVERWRITE
Don't overwrite existing entries.
Definition dict.h:81
#define AV_DICT_DONT_STRDUP_KEY
Take ownership of a key that's been allocated with av_malloc() or another memory allocation function.
Definition dict.h:77
#define AV_DICT_MATCH_CASE
Only get an entry with exact-case key match.
Definition dict.h:74
int av_dict_set_int(AVDictionary **pm, const char *key, int64_t value, int flags)
Convenience wrapper for av_dict_set() that converts the value to a string and stores it.
Definition dict.c:180
#define AVERROR_PATCHWELCOME
Not yet implemented in FFmpeg, patches welcome.
Definition error.h:64
#define AVERROR_BUG
Internal bug, also see AVERROR_BUG2.
Definition error.h:52
#define AVERROR_INVALIDDATA
Invalid data found when processing input.
Definition error.h:61
#define AVERROR_EOF
End of file.
Definition error.h:57
#define av_err2str(errnum)
Convenience macro, the return value should be used only directly in function arguments but never stan...
Definition error.h:122
#define AVERROR(e)
Definition error.h:45
void av_iamf_audio_element_free(AVIAMFAudioElement **paudio_element)
Free an AVIAMFAudioElement and all its contents.
Definition iamf.c:338
@ AV_IAMF_AUDIO_ELEMENT_TYPE_SCENE
Definition iamf.h:349
void av_iamf_mix_presentation_free(AVIAMFMixPresentation **pmix_presentation)
Free an AVIAMFMixPresentation and all its contents.
Definition iamf.c:536
#define AV_LOG_TRACE
Extremely verbose debugging, useful for libav* development.
Definition log.h:236
#define AV_LOG_DEBUG
Stuff which is only useful for libav* developers.
Definition log.h:231
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition log.h:216
#define AV_LOG_FATAL
Something went wrong and recovery is not possible.
Definition log.h:204
#define AV_LOG_VERBOSE
Detailed information.
Definition log.h:226
#define AV_LOG_INFO
Standard information.
Definition log.h:221
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition log.h:210
const char * av_default_item_name(void *ptr)
Return the context name.
Definition log.c:247
AVRational av_add_q(AVRational b, AVRational c)
Add two rationals.
Definition rational.c:93
AVRational av_mul_q(AVRational b, AVRational c)
Multiply two rationals.
Definition rational.c:80
int av_reduce(int *dst_num, int *dst_den, int64_t num, int64_t den, int64_t max)
Reduce a fraction.
Definition rational.c:35
static AVRational av_make_q(int num, int den)
Create an AVRational.
Definition rational.h:71
AVRational av_d2q(double d, int max)
Convert a double precision floating point number to a rational.
Definition rational.c:110
static double av_q2d(AVRational a)
Convert an AVRational to a double.
Definition rational.h:104
static int av_cmp_q(AVRational a, AVRational b)
Compare two rationals.
Definition rational.h:89
AVRational av_sub_q(AVRational b, AVRational c)
Subtract one rational from another.
Definition rational.c:101
int64_t av_rescale(int64_t a, int64_t b, int64_t c)
Rescale a 64-bit integer with rounding to nearest.
int64_t av_rescale_q(int64_t a, AVRational bq, AVRational cq)
Rescale a 64-bit integer by 2 rational numbers.
void * av_dynarray2_add(void **tab_ptr, int *nb_ptr, size_t elem_size, const uint8_t *elem_data)
Add an element of size elem_size to a dynamic array.
Definition mem.c:447
void * av_fast_realloc(void *ptr, unsigned int *size, size_t min_size)
Reallocate the given buffer if it is not large enough, otherwise do nothing.
Definition mem.c:601
void * av_realloc_array(void *ptr, size_t nmemb, size_t size)
Definition mem.c:318
int av_reallocp(void *ptr, size_t size)
Allocate, reallocate, or free a block of memory through a pointer to a pointer.
Definition mem.c:289
int av_reallocp_array(void *ptr, size_t nmemb, size_t size)
Allocate, reallocate an array through a pointer to a pointer.
Definition mem.c:326
const char * av_get_media_type_string(enum AVMediaType media_type)
Return a string describing the media_type enum, NULL if media_type is unknown.
Definition utils.c:28
char * av_fourcc_make_string(char *buf, uint32_t fourcc)
Fill the provided buffer with a string containing a FourCC (four-character code) representation.
Definition utils.c:54
#define av_fourcc2str(fourcc)
Definition avutil.h:323
#define AV_FOURCC_MAX_STRING_SIZE
Definition avutil.h:321
@ AVMEDIA_TYPE_AUDIO
Definition avutil.h:201
@ AVMEDIA_TYPE_SUBTITLE
Definition avutil.h:203
@ AVMEDIA_TYPE_VIDEO
Definition avutil.h:200
@ AVMEDIA_TYPE_DATA
Opaque data information usually continuous.
Definition avutil.h:202
void av_sha_update(struct AVSHA *ctx, const uint8_t *data, size_t len)
Update hash value.
Definition sha.c:315
struct AVSHA * av_sha_alloc(void)
Allocate an AVSHA context.
Definition sha.c:46
void av_sha_final(AVSHA *ctx, uint8_t *digest)
Finish hashing and output digest value.
Definition sha.c:347
av_cold int av_sha_init(AVSHA *ctx, int bits)
Initialize SHA-1 or SHA-2 hashing.
Definition sha.c:274
size_t av_strlcat(char *dst, const char *src, size_t size)
Append the string src to the string dst, but to a total length of no more than size - 1 bytes,...
Definition avstring.c:95
char * av_stristr(const char *s1, const char *s2)
Locate the first case-independent occurrence in the string haystack of the string needle.
Definition avstring.c:58
int av_strstart(const char *str, const char *pfx, const char **ptr)
Return non-zero if pfx is a prefix of str.
Definition avstring.c:36
#define AV_NOPTS_VALUE
Undefined timestamp value.
Definition avutil.h:247
#define AV_TIME_BASE
Internal time base represented as integer.
Definition avutil.h:253
#define LIBAVUTIL_VERSION_INT
Definition version.h:85
void av_display_rotation_set(int32_t matrix[9], double angle)
Initialize a transformation matrix describing a pure clockwise rotation by the specified angle (in de...
Definition display.c:50
void av_display_matrix_flip(int32_t matrix[9], int hflip, int vflip)
Flip the input matrix horizontally and/or vertically.
Definition display.c:65
AVSphericalMapping * av_spherical_alloc(size_t *size)
Allocate a AVSphericalVideo structure and initialize its fields to default values.
Definition spherical.c:26
AVSphericalProjection
Projection of the video surface(s) on a sphere.
Definition spherical.h:47
@ AV_SPHERICAL_RECTILINEAR
Video frame displays on a flat, rectangular 2D surface.
Definition spherical.h:78
@ AV_SPHERICAL_EQUIRECTANGULAR
Video represents a sphere mapped on a flat surface using equirectangular projection.
Definition spherical.h:52
@ AV_SPHERICAL_EQUIRECTANGULAR_TILE
Video represents a portion of a sphere mapped on a flat surface using equirectangular projection.
Definition spherical.h:68
@ AV_SPHERICAL_CUBEMAP
Video frame is split into 6 faces of a cube, and arranged on a 3x2 layout.
Definition spherical.h:61
@ AV_SPHERICAL_HALF_EQUIRECTANGULAR
Video frame displays as a 180 degree equirectangular projection.
Definition spherical.h:73
@ AV_SPHERICAL_PARAMETRIC_IMMERSIVE
Parametric Immersive projection (Apple).
Definition spherical.h:90
@ AV_SPHERICAL_FISHEYE
Fisheye projection (Apple).
Definition spherical.h:84
AVStereo3DType
List of possible 3D Types.
Definition stereo3d.h:48
AVStereo3D * av_stereo3d_alloc_size(size_t *size)
Allocate an AVStereo3D structure and set its fields to default values.
Definition stereo3d.c:39
#define AV_STEREO3D_FLAG_INVERT
Inverted views, Right/Bottom represents the left view.
Definition stereo3d.h:194
AVStereo3DPrimaryEye
List of possible primary eyes.
Definition stereo3d.h:174
AVStereo3DView
List of possible view types.
Definition stereo3d.h:149
@ AV_STEREO3D_2D
Video is not stereoscopic (and metadata has to be there).
Definition stereo3d.h:52
@ AV_STEREO3D_TOPBOTTOM
Views are on top of each other.
Definition stereo3d.h:76
@ AV_STEREO3D_UNSPEC
Video is stereoscopic but the packing is unspecified.
Definition stereo3d.h:143
@ AV_STEREO3D_SIDEBYSIDE
Views are next to each other.
Definition stereo3d.h:64
@ AV_PRIMARY_EYE_NONE
Neither eye.
Definition stereo3d.h:178
@ AV_PRIMARY_EYE_LEFT
Left eye.
Definition stereo3d.h:183
@ AV_PRIMARY_EYE_RIGHT
Right eye.
Definition stereo3d.h:188
@ AV_STEREO3D_VIEW_RIGHT
Frame contains only the right view.
Definition stereo3d.h:163
@ AV_STEREO3D_VIEW_PACKED
Frame contains two packed views.
Definition stereo3d.h:153
@ AV_STEREO3D_VIEW_LEFT
Frame contains only the left view.
Definition stereo3d.h:158
@ AV_STEREO3D_VIEW_UNSPEC
Content is unspecified.
Definition stereo3d.h:168
int index
Definition gxfenc.c:90
int a
int tile_rows
#define MAX_REORDER_DELAY
const VDPAUPixFmtMap * map
int ff_iamfdec_read_descriptors(IAMFContext *c, AVIOContext *pb, int max_size, void *log_ctx)
int ff_iamf_read_packet(AVFormatContext *s, IAMFDemuxContext *c, AVIOContext *pb, int max_size, int stream_id_offset, AVPacket *pkt)
void ff_iamf_read_deinit(IAMFDemuxContext *c)
const char *const ff_id3v1_genre_str[ID3v1_GENRE_MAX+1]
ID3v1 genres.
Definition id3v1.c:26
#define ID3v1_GENRE_MAX
Definition id3v1.h:29
static const int16_t alpha[]
Definition ilbcdata.h:55
#define r
Definition input.c:42
#define b
Definition input.c:43
static av_always_inline float av_int2float(uint32_t i)
Reinterpret a 32-bit integer as a float.
Definition intfloat.h:40
static av_always_inline double av_int2double(uint64_t i)
Reinterpret a 64-bit integer as a double.
Definition intfloat.h:60
#define AV_WB32(p, v)
#define AV_RB8(x)
#define AV_WL32(p, v)
#define AV_RL32(p)
#define AV_RB32(p)
#define AV_RB16A(p)
#define AV_WB64(p, v)
#define AV_WL32A(p, v)
#define AV_WB8(p, d)
#define AV_RB64(p)
#define AV_WB16(p, v)
#define AV_WL16A(p, v)
#define AV_RB24(x)
#define AV_RB16(p)
#define AV_RB32A(p)
int ff_mov_lang_to_iso639(unsigned code, char to[4])
Definition isom.c:263
const AVCodecTag ff_codec_movdata_tags[]
Definition isom.c:82
const struct MP4TrackKindMapping ff_mov_track_kind_table[]
Definition isom.c:467
const AVCodecTag ff_codec_movsubtitle_tags[]
Definition isom.c:75
#define MOV_TRUN_SAMPLE_DURATION
Definition isom.h:430
#define MOV_GRAPHICS_MODE_COPY
Definition isom.h:457
int ff_mov_read_esds(AVFormatContext *fc, AVIOContext *pb)
Definition mov_esds.c:23
#define FF_MOV_FLAG_MFRA_PTS
Definition isom.h:491
#define MOV_TRUN_SAMPLE_CTS
Definition isom.h:433
#define MOV_TKHD_FLAG_ENABLED
Definition isom.h:445
#define MOV_TFHD_DEFAULT_BASE_IS_MOOF
Definition isom.h:426
#define MOV_INFE_FLAG_HIDDEN
Definition isom.h:450
#define FF_MOV_FLAG_MFRA_DTS
Definition isom.h:490
const AVCodecTag ff_codec_movaudio_tags[]
Definition isom_tags.c:308
#define MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES
Definition isom.h:443
const AVCodecTag ff_codec_movvideo_tags[]
Definition isom_tags.c:29
#define MOV_TFHD_DEFAULT_SIZE
Definition isom.h:423
#define MOV_ISMV_TTML_TAG
Definition isom.h:507
#define TAG_IS_AVCI(tag)
Definition isom.h:467
#define MOV_TRUN_FIRST_SAMPLE_FLAGS
Definition isom.h:429
#define MOV_GRAPHICS_MODE_PREMUL_BLACK_ALPHA
Definition isom.h:463
#define MOV_MP4_FPCM_TAG
Definition isom.h:509
#define MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC
Definition isom.h:436
#define MOV_TFHD_STSD_ID
Definition isom.h:421
#define MOV_GRAPHICS_MODE_DITHER_COPY
Definition isom.h:458
#define MOV_TRUN_SAMPLE_FLAGS
Definition isom.h:432
#define MOV_MP4_TTML_TAG
Definition isom.h:508
#define MOV_TFHD_DEFAULT_FLAGS
Definition isom.h:424
#define MOV_TRUN_DATA_OFFSET
Definition isom.h:428
#define MOV_TFHD_BASE_DATA_OFFSET
Definition isom.h:420
#define MOV_MP4_IPCM_TAG
Definition isom.h:510
static enum AVCodecID ff_mov_get_lpcm_codec_id(int bps, int flags)
Compute codec id for 'lpcm' tag.
Definition isom.h:497
#define MOV_TRUN_SAMPLE_SIZE
Definition isom.h:431
#define MOV_SAMPLE_DEPENDENCY_NO
Definition isom.h:454
#define MOV_GRAPHICS_MODE_STRAIGHT_ALPHA
Definition isom.h:461
#define FF_MOV_FLAG_MFRA_AUTO
Definition isom.h:489
#define MOV_TFHD_DEFAULT_DURATION
Definition isom.h:422
enum MPFType type
Definition jpegmpfenc.c:55
unsigned offset
Definition libaomenc.c:812
static int mix(int c0, int c1)
Definition 4xm.c:718
enum TrimAxis axis
Definition trim.c:49
@ HEVC_NAL_CRA_NUT
Definition hevc.h:52
int avpriv_dv_produce_packet(DVDemuxContext *c, AVPacket *pkt, uint8_t *buf, int buf_size, int64_t pos)
Definition dv.c:738
int avpriv_dv_get_packet(DVDemuxContext *c, AVPacket *pkt)
Definition dv.c:733
DVDemuxContext * avpriv_dv_init_demux(AVFormatContext *s)
Definition dv.c:728
int ff_dict_set_timestamp(AVDictionary **dict, const char *key, int64_t timestamp)
Set a dictionary value to an ISO-8601 compliant timestamp string.
Definition utils.c:626
int ff_hex_to_data(uint8_t *data, const char *p)
Parse a string of hexadecimal strings.
Definition utils.c:495
static av_always_inline FFStream * ffstream(AVStream *st)
Definition internal.h:392
static av_always_inline const FFStream * cffstream(const AVStream *st)
Definition internal.h:397
char * ff_data_to_hex(char *buf, const uint8_t *src, int size, int lowercase)
Write hexadecimal string corresponding to given binary data.
Definition utils.c:473
int ff_alloc_extradata(AVCodecParameters *par, int size)
Allocate extradata with additional AV_INPUT_BUFFER_PADDING_SIZE at end which is always set to 0.
Definition utils.c:237
enum AVCodecID ff_codec_get_id(const AVCodecTag *tags, unsigned int tag)
Definition utils.c:143
Macro definitions for various function/variable attributes.
#define av_fallthrough
Definition attributes.h:67
#define av_unused
Definition attributes.h:164
AVGainMapParams * av_gain_map_params_alloc(size_t *size)
Allocate an AVGainMapParams structure and initialize it to default values.
Definition gain_map.c:224
int av_gain_map_params_from_iso21496(AVGainMapParams *restrict p, const uint8_t *data, size_t size)
Definition gain_map.c:111
common internal API header
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification.
Definition internal.h:97
void avpriv_report_missing_feature(void *avc, const char *msg,...) av_printf_format(2
Log a generic warning message about a missing feature.
Stereoscopic video.
static av_cold int read_close(AVFormatContext *ctx)
Definition libcdio.c:143
static int read_seek(AVFormatContext *ctx, int stream_index, int64_t timestamp, int flags)
Definition libcdio.c:151
version
Definition libkvazaar.c:313
item_name
Definition libkvazaar.c:311
static const uint16_t mask[17]
Definition lzw.c:38
#define FFSWAP(type, a, b)
Definition macros.h:52
#define FFMIN(a, b)
Definition macros.h:49
#define MKTAG(a, b, c, d)
Definition macros.h:55
#define MKBETAG(a, b, c, d)
Definition macros.h:56
#define FFMAX(a, b)
Definition macros.h:47
AVContentLightMetadata * av_content_light_metadata_alloc(size_t *size)
Allocate an AVContentLightMetadata structure and set its fields to default values.
AVMasteringDisplayMetadata * av_mastering_display_metadata_alloc_size(size_t *size)
Allocate an AVMasteringDisplayMetadata structure and set its fields to default values.
uint64_t layout
void * av_calloc(size_t nmemb, size_t size)
Definition mem.c:370
Memory handling functions.
static int mlp_samplerate(int in)
Definition mlp_parse.h:87
static uint64_t truehd_layout(int chanmap)
Definition mlp_parse.h:105
static int mov_read_ilst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:5869
static int64_t mov_get_skip_samples(AVStream *st, int sample)
Definition mov.c:13361
static int search_frag_moof_offset(MOVFragmentIndex *frag_index, int64_t offset)
Definition mov.c:1854
static int mov_read_sbas(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:2848
static int update_frag_index(MOVContext *c, int64_t offset)
Definition mov.c:1955
static int get_eia608_packet(AVIOContext *pb, AVPacket *pkt, int src_size)
Definition mov.c:12889
static int mov_read_iloc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:9624
static int mov_read_pack(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:7293
static int read_image_grid(AVFormatContext *s, const HEIFGroup *grid, AVStreamGroupTileGrid *tile_grid)
Definition mov.c:11391
static int mov_apply_heif_item_references(AVFormatContext *s, HEIFItem *item, AVPacketSideData **coded_side_data, int *nb_coded_side_data)
Definition mov.c:11618
static int find_prev_closest_index(AVStream *st, AVIndexEntry *e_old, int nb_old, MOVTimeToSample *tts_data, int64_t tts_count, int64_t timestamp_pts, int flag, int64_t *index, int64_t *tts_index, int64_t *tts_sample)
Find the closest previous frame to the timestamp_pts, in e_old index entries.
Definition mov.c:4372
static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
Definition mov.c:13377
static HEIFItem * get_heif_item(MOVContext *c, unsigned id)
Get the requested item.
Definition mov.c:199
static void mov_free_stream_context(AVFormatContext *s, AVStream *st)
Definition mov.c:11043
static int mov_read_stsd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:3597
static void mov_parse_stsd_video(MOVContext *c, AVIOContext *pb, AVStream *st, MOVStreamContext *sc)
Definition mov.c:3039
static int heif_add_stream(MOVContext *c, HEIFItem *item)
Definition mov.c:6031
static int mov_read_dops(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:9175
static int set_display_matrix_from_item(AVPacketSideData **coded_side_data, int *nb_coded_side_data, const HEIFItem *item)
Definition mov.c:11363
static int mov_compare_presentation_samples(const void *a, const void *b)
Definition mov.c:5437
static int mov_switch_root(AVFormatContext *s, int64_t target, int index)
Definition mov.c:12828
static int mov_read_vexu_proj(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:7512
static int mov_read_srat(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:1173
static int get_key_from_kid(uint8_t *out, int len, MOVContext *c, AVEncryptionInfo *sample)
Definition mov.c:8759
static int mov_read_aclr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:2589
static int mov_read_idat(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:9618
static int mov_parse_tmcd_streams(AVFormatContext *s)
Definition mov.c:12268
static int mov_read_lhvc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:9310
static int aax_filter(uint8_t *input, int size, MOVContext *c)
Definition mov.c:1719
static void mov_current_sample_dec(MOVStreamContext *sc)
Definition mov.c:4609
static int mov_finalize_stsd_entry(MOVContext *c, AVStream *st)
Definition mov.c:3456
static int mov_read_pitm(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:9610
static void set_curr_stream_little_endian(MOVContext *c)
Definition mov.c:2174
static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp, int flags)
Definition mov.c:13286
static int mov_read_uncc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:10449
static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
Definition mov.c:13042
static int mov_parse_lcevc_streams(AVFormatContext *s)
Definition mov.c:12391
static int mov_read_hvce(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:9283
static int cbcs_scheme_decrypt(MOVContext *c, MOVStreamContext *sc, AVEncryptionInfo *sample, uint8_t *input, int size)
Definition mov.c:8992
static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:10628
static int mov_finalize_packet(AVFormatContext *s, AVStream *st, AVIndexEntry *sample, int64_t current_index, AVPacket *pkt)
Definition mov.c:12958
static int mov_read_stss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:3805
static uint64_t mov_dts_channel_layout_to_mask(unsigned int code)
Definition mov.c:1294
static int64_t get_stream_info_time(MOVFragmentStreamInfo *frag_stream_info)
Definition mov.c:1878
static int mov_read_saio(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:8403
static int mov_skip_multiple_stsd(MOVContext *c, AVIOContext *pb, int codec_tag, int format, int64_t size)
Definition mov.c:3430
static int mov_read_iref_auxl(MOVContext *c, AVIOContext *pb, uint32_t type, int version, uint32_t size)
Definition mov.c:10075
#define DRM_BLOB_SIZE
Definition mov.c:1591
static int mov_add_tref_id(MovTref *tag, uint32_t id)
Definition mov.c:2774
static int mov_read_mdhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:2089
static int mov_read_tmcd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:6986
int ff_mov_read_stsd_entries(MOVContext *c, AVIOContext *pb, int entries)
Definition mov.c:3477
static int mov_metadata_gnre(MOVContext *c, AVIOContext *pb, unsigned len, const char *key)
Definition mov.c:139
static int mov_read_dref(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:732
static int mov_read_dpxe(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:2517
static MovTref * mov_find_tref_tag(const MOVStreamContext *sc, uint32_t name)
Definition mov.c:2789
static int mov_parse_heif_layered_video_auxl_alpha(AVFormatContext *s, HEIFItem *base, HEIFItem *alpha)
Definition mov.c:11964
static int mov_read_eyes(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:7586
static int cenc_scheme_decrypt(MOVContext *c, MOVStreamContext *sc, AVEncryptionInfo *sample, uint8_t *input, int size)
Definition mov.c:8796
static int mov_read_wave(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:2637
static int mov_metadata_hmmt(MOVContext *c, AVIOContext *pb, unsigned len)
Definition mov.c:390
static int mov_read_stsz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:3860
static int mov_dts_stream_construction_to_profile(unsigned int sc)
Definition mov.c:1261
static int mov_read_gama(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:2385
static int rb_size(AVIOContext *pb, int64_t *value, int size)
Definition mov.c:9566
static int mov_read_chpl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:693
static int mov_read_header(AVFormatContext *s)
Definition mov.c:12556
static int mov_read_dfla(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:8719
static int mov_read_stco(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:2934
static int mov_read_st3d(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:7246
static int mov_read_elst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:6912
static int mov_metadata_3gp(MOVContext *c, AVIOContext *pb, int64_t len, const char *key, AVDictionary **metadata)
Definition mov.c:341
static int test_same_origin(const char *src, const char *ref)
Definition mov.c:5535
static int sanity_checks(void *log_obj, MOVStreamContext *sc, int index)
Definition mov.c:5694
static void mov_current_sample_set(MOVStreamContext *sc, int current_sample)
Definition mov.c:4621
static int mov_merge_tts_data(MOVContext *mov, AVStream *st, int flags)
Definition mov.c:5053
static int mov_aaxc_crypto(MOVContext *c)
Definition mov.c:1694
static int mov_read_sv3d(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:7374
static int mov_read_ddts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:1322
static int mov_read_ipco(MOVContext *c, AVIOContext *pb, MOVAtom atom, MOVAtomExt **atoms, int *nb_atoms)
Definition mov.c:10246
static int mov_read_sdtp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:4075
static int mov_read_stts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:3953
static int cenc_filter(MOVContext *mov, AVStream *st, MOVStreamContext *sc, AVPacket *pkt, int current_index)
Definition mov.c:9105
static const AVClass mov_class
Definition mov.c:13499
static int mov_read_sample_encryption_info(MOVContext *c, AVIOContext *pb, MOVStreamContext *sc, AVEncryptionInfo **sample, int use_subsamples)
Definition mov.c:8147
static int mov_read_meta(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:6090
static int mov_read_smdm(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:7064
static const uint32_t mac_to_unicode[128]
Definition mov.c:155
static int mov_parse_heif_layered_video_auxl_gmap(AVFormatContext *s, HEIFItem *base, HEIFItem *gain_map)
Definition mov.c:12023
static int mov_read_sidx(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:6700
static int mov_read_strf(MOVContext *c, AVIOContext *pb, MOVAtom atom)
An strf atom is a BITMAPINFOHEADER struct.
Definition mov.c:2912
static uint32_t get_sgpd_sync_index(const MOVStreamContext *sc, int nal_unit_type)
Definition mov.c:4975
static void fix_frag_index_entries(MOVFragmentIndex *frag_index, int index, int id, int entries)
Definition mov.c:2018
static int mov_read_rtmd_track(AVFormatContext *s, AVStream *st)
Definition mov.c:10958
static int mov_read_dec3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:1207
static int mov_read_dmlp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:9228
static int mov_metadata_int8_bypass_padding(MOVContext *c, AVIOContext *pb, unsigned len, const char *key)
Definition mov.c:116
static int mov_read_schm(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:8617
static int mov_metadata_loci(MOVContext *c, AVIOContext *pb, unsigned len)
Definition mov.c:285
static int read_tfra(MOVContext *mov, AVIOContext *f)
Definition mov.c:11202
static int mov_seek_fragment(AVFormatContext *s, AVStream *st, int64_t timestamp)
Definition mov.c:13223
static int mov_read_extradata(MOVContext *c, AVIOContext *pb, MOVAtom atom, enum AVCodecID codec_id)
Definition mov.c:2476
static int mov_read_enda(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:2202
static int mov_read_covr(MOVContext *c, AVIOContext *pb, int type, int len)
Definition mov.c:242
static int mov_read_adrm(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:1593
static int mov_parse_heif_layered_video_tmap(AVFormatContext *s, const HEIFGroup *tmap)
Definition mov.c:11773
static int mov_parse_dovi_streams(AVFormatContext *s)
Definition mov.c:12445
static int mov_read_chnl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:1403
static void mov_metadata_creation_time(MOVContext *c, AVIOContext *pb, AVDictionary **metadata, int version)
Definition mov.c:2059
static int mov_stsc_index_valid(unsigned int index, unsigned int count)
Definition mov.c:3743
static int mov_read_hdlr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:876
#define MOV_MERGE_STTS
Definition mov.c:5047
static int mov_read_dvcc_dvvc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:9263
static int should_retry(AVIOContext *pb, int error_code)
Definition mov.c:12821
static int mov_read_mvhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:2135
static int mov_read_tfdt(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:6315
static int mov_read_moov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:1781
static int mov_read_clli(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:7192
static int mov_read_trun(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:6354
static void mov_update_dts_shift(MOVStreamContext *sc, int duration, void *logctx)
Definition mov.c:4113
static int mov_read_kind(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:9361
static int mov_read_sbgp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:4264
static int mov_metadata_track_or_disc_number(MOVContext *c, AVIOContext *pb, unsigned len, const char *key)
Definition mov.c:96
static int mov_read_ares(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:2544
static int mov_read_pssh(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:8498
static int mov_finalize_stsd_codec(MOVContext *c, AVIOContext *pb, AVStream *st, MOVStreamContext *sc)
Definition mov.c:3325
static int mov_read_tkhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:6116
static int mov_read_iprp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:10334
static int mov_read_cdsc_rndr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:2817
static int cens_scheme_decrypt(MOVContext *c, MOVStreamContext *sc, AVEncryptionInfo *sample, uint8_t *input, int size)
Definition mov.c:8921
static int read_image_iovl(AVFormatContext *s, const HEIFGroup *grid, AVStreamGroupTileGrid *tile_grid)
Definition mov.c:11488
static int mov_read_alac(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:2502
static int mov_read_mfra(MOVContext *c, AVIOContext *f)
Definition mov.c:11263
static int mov_read_iref_dimg_grid(MOVContext *c, AVIOContext *pb, HEIFItem *item, int version, int entries)
Definition mov.c:9919
#define MIN_DATA_ENTRY_BOX_SIZE
Definition mov.c:731
static int mov_change_extradata(AVStream *st, AVPacket *pkt)
Definition mov.c:12865
static int mov_read_mdcv(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:7111
static int mov_parse_stsd_audio(MOVContext *c, AVIOContext *pb, AVStream *st, MOVStreamContext *sc)
Definition mov.c:3103
static int mov_read_timecode_track(AVFormatContext *s, AVStream *st)
Definition mov.c:10984
static int mov_read_imir(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:10221
static int mov_read_stps(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:3764
static int mov_read_svq3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:2632
static int mov_read_pcmc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:2211
static int mov_read_auxc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:9585
static int mov_parse_cdsc_and_rndr_streams(AVFormatContext *s)
Definition mov.c:12339
static const MOVParseTableEntry mov_default_parse_table[]
Definition mov.c:10489
static int mov_read_jp2h(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:2512
static int mov_read_iref(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:10123
static int mov_read_trex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:6289
static int mov_read_saiz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:8319
static int mov_read_hfov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:7830
static int mov_read_free(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:8027
static int set_icc_profile_from_item(AVPacketSideData **coded_side_data, int *nb_coded_side_data, const HEIFItem *item)
Definition mov.c:11341
static int mov_read_infe(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:9721
static int mov_parse_heif_item_references(AVFormatContext *s, HEIFItem *item, AVPacketSideData **coded_side_data, int *nb_coded_side_data)
Definition mov.c:11648
static int mov_read_stsc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:3663
static AVStream * get_curr_st(MOVContext *c)
Get the current stream in the parsing process.
Definition mov.c:219
static int mov_parse_stsd_data(MOVContext *c, AVIOContext *pb, AVStream *st, MOVStreamContext *sc, int64_t size)
Definition mov.c:3252
static int mov_read_mdat(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:1583
static int cbc1_scheme_decrypt(MOVContext *c, MOVStreamContext *sc, AVEncryptionInfo *sample, uint8_t *input, int size)
Definition mov.c:8855
static int mov_metadata_int8_no_padding(MOVContext *c, AVIOContext *pb, unsigned len, const char *key)
Definition mov.c:130
static int search_frag_timestamp(AVFormatContext *s, MOVFragmentIndex *frag_index, AVStream *st, int64_t timestamp)
Definition mov.c:1930
static int mov_read_avid(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:2522
static int set_exif_from_item(AVFormatContext *s, AVPacketSideData **coded_side_data, int *nb_coded_side_data, const HEIFItem *item)
Definition mov.c:11309
static void fix_timescale(MOVContext *c, MOVStreamContext *sc)
Definition mov.c:5636
static int mov_read_custom(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:5930
static int mov_read_dac3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:949
static int get_current_encryption_info(MOVContext *c, MOVEncryptionIndex **encryption_index, MOVStreamContext **sc)
Gets the current encryption info and associated current stream context.
Definition mov.c:8096
static int mov_read_close(AVFormatContext *s)
Definition mov.c:11109
static int mov_read_pasp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:1561
static int mov_open_dref(MOVContext *c, AVIOContext **pb, const char *src, MOVDref *ref)
Definition mov.c:5564
static MOVFragmentStreamInfo * get_frag_stream_info_from_pkt(MOVFragmentIndex *frag_index, AVPacket *pkt, int id)
Definition mov.c:9080
static int mov_read_avss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:2507
static int mov_read_tenc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:8648
static int mov_read_ipma(MOVContext *c, AVIOContext *pb, MOVAtom atom, MOVAtomExt *atoms, int nb_atoms)
Definition mov.c:10279
static int mov_read_uuid(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:7922
static int mov_read_chan(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:1384
static int build_open_gop_key_points(AVStream *st)
Definition mov.c:4983
static void mov_build_index(MOVContext *mov, AVStream *st)
Definition mov.c:5116
static void mov_update_sample_durations(MOVContext *mov, AVStream *st)
Definition mov.c:5450
static int mov_read_ctts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:4124
static int mov_find_tref_id(const MovTref *tag, uint32_t id)
Definition mov.c:2765
static int mov_parse_heif_layered_video(AVFormatContext *s)
Definition mov.c:12149
static int mov_read_amve(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:7221
static int mov_read_keys(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:5878
static int mov_read_wfex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:1437
static int mov_read_glbl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
This function reads atom content and puts data in extradata without tag nor size unlike mov_read_extr...
Definition mov.c:2694
static int mov_read_ftyp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:1733
#define IS_MATRIX_IDENT(matrix)
Definition mov.c:6108
static int can_seek_to_key_sample(AVStream *st, int sample, int64_t requested_pts)
Definition mov.c:13259
static int mov_parse_auxiliary_info(MOVContext *c, MOVStreamContext *sc, AVIOContext *pb, MOVEncryptionIndex *encryption_index)
Definition mov.c:8257
static int64_t mov_get_stsc_samples(MOVStreamContext *sc, unsigned int index)
Definition mov.c:3749
static int mov_read_vpcc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:7014
static int64_t add_index_entry(AVStream *st, int64_t pos, int64_t timestamp, int size, int distance, int flags)
Add index entry with the given values, to the end of ffstream(st)->index_entries.
Definition mov.c:4459
static int mov_parse_tiles(AVFormatContext *s)
Definition mov.c:11677
static void mov_fix_index(MOVContext *mov, AVStream *st)
Fix ffstream(st)->index_entries, so that it contains only the entries (and the entries which are need...
Definition mov.c:4649
#define DDTS_SIZE
static int mov_read_iref_cdsc(MOVContext *c, AVIOContext *pb, uint32_t type, int version, uint32_t size)
Definition mov.c:10029
static int cenc_decrypt(MOVContext *c, MOVStreamContext *sc, AVEncryptionInfo *sample, uint8_t *input, int size)
Definition mov.c:9064
static int mov_read_senc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:8201
static int mov_read_sgpd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:4205
static AVStream * mov_find_reference_track(AVFormatContext *s, AVStream *st, uint32_t *tref_id, int nb_tref_id, int first_index)
Definition mov.c:12324
static void fix_index_entry_timestamps(AVStream *st, int end_index, int64_t end_ts, int64_t *frame_duration_buffer, int frame_duration_buffer_size)
Rewrite timestamps of index entries in the range [end_index - frame_duration_buffer_size,...
Definition mov.c:4500
static int mov_read_trak(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:5713
static int mov_read_colr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:2287
static int add_tts_entry(MOVTimeToSample **tts_data, unsigned int *tts_count, unsigned int *allocated_size, int count, int offset, unsigned int duration)
Definition mov.c:4512
static void mov_parse_stsd_subtitle(MOVContext *c, AVIOContext *pb, AVStream *st, MOVStreamContext *sc, int64_t size)
Definition mov.c:3236
static int mov_read_clap(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:1452
static int mov_read_dvc1(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:2740
static int mov_read_vdep(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:2880
static int mov_read_SAND(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:9540
static int64_t mov_read_atom_into_extradata(MOVContext *c, AVIOContext *pb, MOVAtom atom, AVCodecParameters *par, uint8_t *buf)
Definition mov.c:2454
static void mov_free_encryption_index(MOVEncryptionIndex **index)
Definition mov.c:11031
static int mov_read_mac_string(MOVContext *c, AVIOContext *pb, int len, char *dst, int dstlen)
Definition mov.c:174
static void fix_stream_ids(AVFormatContext *s)
Definition mov.c:12518
#define OFFSET(x)
Definition mov.c:13443
static AVIndexEntry * mov_find_next_sample(AVFormatContext *s, AVStream **st)
Definition mov.c:12791
static int mov_read_chap(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:6268
#define MOV_MERGE_CTTS
Definition mov.c:5046
static int is_open_key_sample(const MOVStreamContext *sc, int sample)
Definition mov.c:13242
static int mov_read_moof(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:2033
static int mov_read_SA3D(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:9450
static int mov_realloc_extradata(AVCodecParameters *par, MOVAtom atom)
Definition mov.c:2439
static int mov_read_udta_string(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:411
static int mov_read_coll(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:7155
static int mov_read_frma(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:8049
static int mov_read_ispe(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:10173
static int mov_codec_id(AVStream *st, uint32_t format)
Definition mov.c:2999
static void export_orphan_timecode(AVFormatContext *s)
Definition mov.c:11184
static int mov_parse_heif_items(AVFormatContext *s)
Definition mov.c:12203
static void mov_estimate_video_delay(MOVContext *c, AVStream *st)
Definition mov.c:4541
static int mov_read_vmhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:10378
static int mov_read_tfhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:6221
static MOVFragmentStreamInfo * get_frag_stream_info(MOVFragmentIndex *frag_index, int index, int id)
Definition mov.c:1799
static int mov_read_irot(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:10201
static int mov_probe(const AVProbeData *p)
Definition mov.c:10750
static int parse_timecode_in_framenum_format(AVFormatContext *s, AVStream *st, int64_t value, int flags)
Definition mov.c:10944
static int mov_parse_uuid_spherical(MOVStreamContext *sc, AVIOContext *pb, size_t len)
Definition mov.c:7859
static void mov_current_sample_inc(MOVStreamContext *sc)
Definition mov.c:4597
static int mov_read_fiel(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:2405
static int mov_read_iref_dimg_tmap(MOVContext *c, AVIOContext *pb, HEIFItem *item, int version, int entries)
Definition mov.c:9869
static int mov_read_targa_y216(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:2530
static int get_edit_list_entry(MOVContext *mov, const MOVStreamContext *msc, unsigned int edit_list_index, int64_t *edit_list_media_time, int64_t *edit_list_duration, int64_t global_timescale)
Get ith edit list entry (media time, duration).
Definition mov.c:4325
static int mov_read_wide(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:6839
static int64_t get_frag_time(AVFormatContext *s, AVStream *dst_st, MOVFragmentIndex *frag_index, int index)
Definition mov.c:1888
static MOVFragmentStreamInfo * get_current_frag_stream_info(MOVFragmentIndex *frag_index)
Definition mov.c:1838
static int mov_read_esds(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:942
static int mov_read_iref_dimg(MOVContext *c, AVIOContext *pb, int version, uint32_t size)
Definition mov.c:9961
static int mov_read_iinf(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:9799
static int mov_parse_exif_item(AVFormatContext *s, HEIFItem *item, const HEIFItem *ref)
Definition mov.c:11557
static int tmcd_is_referenced(AVFormatContext *s, int tmcd_id)
Definition mov.c:11166
static void mov_read_chapters(AVFormatContext *s)
Definition mov.c:10845
static int mov_read_mhac(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:10411
static int mov_read_cmov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:6859
static void set_frag_stream(MOVFragmentIndex *frag_index, int id)
Definition mov.c:1818
static const AVOption mov_options[]
Definition mov.c:13445
static MovTref * mov_add_tref_tag(MOVStreamContext *sc, uint32_t name)
Definition mov.c:2800
static int mov_read_vexu(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition mov.c:7768
int ff_mov_read_chan(AVFormatContext *s, AVIOContext *pb, AVStream *st, int64_t size)
Read 'chan' tag from the input stream.
Definition mov_chan.c:550
int ff_mov_read_chnl(AVFormatContext *s, AVIOContext *pb, AVStream *st, int version)
Read 'chnl' tag from the input stream.
Definition mov_chan.c:776
uint32_t tag
Definition movenc.c:2157
mpeg audio layer common tables.
const uint64_t ff_mpa_cicp_channel_layout_masks[20]
MPEG Audio header decoder.
static int ff_mpa_check_header(uint32_t header)
const char data[16]
Definition mxf.c:155
int profile
Definition mxfenc.c:2404
uint16_t cid
Definition mxfenc.c:2455
static int headroom(int *la)
Definition nellymoser.c:106
static float distance(float x, float y, int band)
#define av_malloc(s)
Definition ops_static.c:52
AVOptions.
const char * av_color_space_name(enum AVColorSpace space)
Definition pixdesc.c:3884
const char * av_color_transfer_name(enum AVColorTransferCharacteristic transfer)
Definition pixdesc.c:3851
const char * av_color_primaries_name(enum AVColorPrimaries primaries)
Definition pixdesc.c:3818
@ AVCOL_RANGE_MPEG
Narrow or limited range content.
Definition pixfmt.h:775
@ AVCOL_RANGE_JPEG
Full range content.
Definition pixfmt.h:792
@ AVALPHA_MODE_STRAIGHT
Alpha channel is independent of color values.
Definition pixfmt.h:828
@ AVALPHA_MODE_UNSPECIFIED
Unknown alpha handling, or no alpha channel.
Definition pixfmt.h:826
@ AVALPHA_MODE_PREMULTIPLIED
Alpha channel is multiplied into color values.
Definition pixfmt.h:827
@ AV_PIX_FMT_RGB24
packed RGB 8:8:8, 24bpp, RGBRGB...
Definition pixfmt.h:75
@ AV_PIX_FMT_RGBA
packed RGBA 8:8:8:8, 32bpp, RGBARGBA...
Definition pixfmt.h:100
#define AVPALETTE_SIZE
Definition pixfmt.h:32
@ AVCOL_PRI_RESERVED
Definition pixfmt.h:651
@ AVCOL_PRI_UNSPECIFIED
Definition pixfmt.h:650
@ AVCOL_PRI_RESERVED0
Definition pixfmt.h:648
@ AVCOL_TRC_GAMMA22
also ITU-R BT470M / ITU-R BT1700 625 PAL & SECAM
Definition pixfmt.h:682
@ AVCOL_TRC_RESERVED
Definition pixfmt.h:681
@ AVCOL_TRC_GAMMA28
also ITU-R BT470BG
Definition pixfmt.h:683
@ AVCOL_TRC_UNSPECIFIED
Definition pixfmt.h:680
@ AVCOL_TRC_RESERVED0
Definition pixfmt.h:678
@ AVCOL_SPC_UNSPECIFIED
Definition pixfmt.h:714
@ AVCOL_SPC_RESERVED
reserved for future use by ITU-T and ISO/IEC just like 15-255 are
Definition pixfmt.h:715
static const uint16_t table[]
Definition prosumer.c:203
const char * name
Definition qsvenc.c:142
int ff_get_qtpalette(int codec_id, AVIOContext *pb, uint32_t *palette)
Retrieve the palette (or "color table" in QuickTime terms), either from the video sample description,...
Definition qtpalette.c:323
int ff_replaygain_export(AVStream *st, AVDictionary *metadata)
Parse replaygain tags and export them as per-stream side data.
Definition replaygain.c:94
const AVCodecTag ff_codec_bmp_tags[]
Definition riff.c:36
const AVCodecTag ff_codec_wav_tags[]
Definition riff.c:526
internal header for RIFF based (de)muxers do NOT include this in end user applications
int ff_get_wav_header(AVFormatContext *s, AVIOContext *pb, AVCodecParameters *par, int size, int big_endian)
Definition riffdec.c:141
#define av_bswap32
Definition bswap.h:47
Public header for SHA-1 & SHA-256 hash function implementations.
#define FF_ARRAY_ELEMS(a)
const uint8_t * code
Definition spdifenc.c:433
unsigned int pos
Definition spdifenc.c:431
Spherical video.
AVRational ambient_illuminance
Environmental illuminance of the ambient viewing environment in lux.
AVRational ambient_light_x
Normalized x chromaticity coordinate of the environmental ambient light in the nominal viewing enviro...
AVRational ambient_light_y
Normalized y chromaticity coordinate of the environmental ambient light in the nominal viewing enviro...
A reference to a data buffer.
Definition buffer.h:82
uint8_t * data
The data buffer.
Definition buffer.h:90
size_t size
Size of data in bytes.
Definition buffer.h:94
enum AVChannel id
An AVChannelLayout holds information about the channel layout of audio data.
enum AVChannelOrder order
Channel order used in this layout.
union AVChannelLayout::@162063043056170047076125117143030261346263330336 u
Details about which channels are present in this layout.
int nb_channels
Number of channels in this layout.
AVChannelCustom * map
This member must be used when the channel order is AV_CHANNEL_ORDER_CUSTOM.
Describe the class of an AVClass context structure.
Definition log.h:76
This struct describes the properties of an encoded stream.
Definition codec_par.h:49
enum AVColorSpace color_space
Definition codec_par.h:192
int extradata_size
Size of the extradata content in bytes.
Definition codec_par.h:75
int frame_size
Audio frame size, if known.
Definition codec_par.h:227
enum AVFieldOrder field_order
The order of the fields in interlaced video.
Definition codec_par.h:182
int height
The height of the video frame in pixels.
Definition codec_par.h:150
int nb_coded_side_data
Amount of entries in coded_side_data.
Definition codec_par.h:88
int bits_per_coded_sample
The number of bits per sample in the codedwords.
Definition codec_par.h:113
AVChannelLayout ch_layout
The channel layout and number of channels.
Definition codec_par.h:207
int width
The width of the video frame in pixels.
Definition codec_par.h:143
int64_t bit_rate
The average bitrate of the encoded data (in bits per second).
Definition codec_par.h:99
int seek_preroll
Number of audio samples to skip after a discontinuity.
Definition codec_par.h:256
enum AVMediaType codec_type
General type of the encoded data.
Definition codec_par.h:53
int profile
Codec-specific bitstream restrictions that the stream conforms to.
Definition codec_par.h:135
int block_align
The number of bytes per coded audio frame, required by some formats.
Definition codec_par.h:221
int video_delay
Number of delayed frames.
Definition codec_par.h:200
uint32_t codec_tag
Additional information about the codec (corresponds to the AVI FOURCC).
Definition codec_par.h:61
uint8_t * extradata
Extra binary data needed for initializing the decoder, codec-dependent.
Definition codec_par.h:71
enum AVCodecID codec_id
Specific type of the encoded data (the codec used).
Definition codec_par.h:57
enum AVColorPrimaries color_primaries
Definition codec_par.h:190
int sample_rate
The number of audio samples per second.
Definition codec_par.h:213
enum AVColorTransferCharacteristic color_trc
Definition codec_par.h:191
enum AVAlphaMode alpha_mode
Video with alpha channel only.
Definition codec_par.h:261
int initial_padding
Number of padding audio samples at the start.
Definition codec_par.h:239
AVPacketSideData * coded_side_data
Additional data associated with the entire stream.
Definition codec_par.h:83
enum AVColorRange color_range
Additional colorspace characteristics.
Definition codec_par.h:189
unsigned MaxFALL
Max average light level per frame (cd/m^2).
unsigned MaxCLL
Max content light level (cd/m^2).
char * value
Definition dict.h:92
This describes encryption info for a packet.
uint32_t skip_byte_block
Only used for pattern encryption.
uint8_t * iv
The initialization vector.
uint32_t crypt_byte_block
Only used for pattern encryption.
uint8_t * key_id
The ID of the key used to encrypt the packet.
uint32_t scheme
The fourcc encryption scheme, in big-endian byte order.
This describes info used to initialize an encryption key system.
uint8_t * data
Key-system specific initialization data.
uint8_t ** key_ids
An array of key IDs this initialization data is for.
uint8_t * system_id
A unique identifier for the key system this is for, can be NULL if it is not known.
uint32_t num_key_ids
The number of key IDs.
enum AVTiffDataType type
Definition exif.h:86
union AVExifEntry::@325220332140161067313112036135003363017341144014 value
AVRational * rat
Definition exif.h:113
unsigned int count
Definition exif.h:79
Format I/O context.
Definition avformat.h:1401
AVStream ** streams
A list of all streams in the file.
Definition avformat.h:1469
int error_recognition
Error recognition; higher values will detect more errors but may misdetect some more or less valid pa...
Definition avformat.h:1676
AVRational base_offset
Small constants added before the log-domain math to avoid a singularity at zero.
Definition gain_map.h:76
Parameters describing how to combine a gain map rendition with its base rendition to recover the alte...
Definition gain_map.h:39
AVRational alternate_hdr_headroom
Definition gain_map.h:57
struct AVGainMapParams::AVGainMapChannel channels[3]
int nb_channels
Must be 1 or 3.
Definition gain_map.h:83
int use_base_color_space
If non-zero, the gain map is applied in the colour space of the base rendition; otherwise in that of ...
Definition gain_map.h:50
Information on how to combine one or more audio streams, as defined in section 3.6 of IAMF.
Definition iamf.h:359
enum AVIAMFAudioElementType audio_element_type
Audio element type as defined in section 3.6 of IAMF.
Definition iamf.h:391
Information on how to render and mix one or more AVIAMFAudioElement to generate the final audio outpu...
Definition iamf.h:616
Submix element as defined in section 3.7 of IAMF.
Definition iamf.h:449
unsigned int audio_element_id
The id of the Audio Element this submix element references.
Definition iamf.h:455
Submix layout as defined in section 3.7 of IAMF.
Definition iamf.h:559
unsigned int nb_elements
Number of elements in the submix.
Definition iamf.h:575
AVIAMFSubmixElement ** elements
Array of submix elements.
Definition iamf.h:568
Bytestream IO Context.
Definition avio.h:160
int seekable
A combination of AVIO_SEEKABLE_ flags or 0 when the stream is not seekable.
Definition avio.h:261
int eof_reached
true if was unable to read due to error or eof
Definition avio.h:238
int error
contains the error code or 0 if no error happened
Definition avio.h:239
int64_t pos
Definition avformat.h:623
int min_distance
Minimum distance between this and the previous keyframe, used to avoid unneeded searching.
Definition avformat.h:634
int64_t timestamp
Timestamp in AVStream.time_base units, preferably the time from which on correctly decoded frames are...
Definition avformat.h:624
int has_primaries
Flag indicating whether the display primaries (and white point) are set.
AVRational max_luminance
Max luminance of mastering display (cd/m^2).
AVRational min_luminance
Min luminance of mastering display (cd/m^2).
AVRational display_primaries[3][2]
CIE 1931 xy chromaticity coords of color primaries (r, g, b order).
AVRational white_point[2]
CIE 1931 xy chromaticity coords of white point.
int has_luminance
Flag indicating whether the luminance (min_ and max_) have been set.
AVOption.
Definition opt.h:428
This structure stores auxiliary information for decoding, presenting, or otherwise processing the cod...
Definition packet.h:431
uint8_t * data
Definition packet.h:432
enum AVPacketSideDataType type
Definition packet.h:434
This structure stores compressed data.
Definition packet.h:587
int size
Definition packet.h:611
uint8_t * data
Definition packet.h:610
This structure contains the data a format has to probe a file.
Definition avformat.h:473
Rational number (pair of numerator and denominator).
Definition rational.h:58
int num
Numerator.
Definition rational.h:59
int den
Denominator.
Definition rational.h:60
hash context
Definition sha.c:35
uint64_t count
number of bytes in buffer
Definition sha.c:37
uint32_t bound_left
Distance from the left edge.
Definition spherical.h:185
enum AVSphericalProjection projection
Projection type.
Definition spherical.h:104
uint32_t bound_top
Distance from the top edge.
Definition spherical.h:186
uint32_t bound_bottom
Distance from the bottom edge.
Definition spherical.h:188
uint32_t bound_right
Distance from the right edge.
Definition spherical.h:187
int32_t pitch
Rotation around the right vector [-90, 90].
Definition spherical.h:145
int32_t roll
Rotation around the forward vector [-180, 180].
Definition spherical.h:146
int32_t yaw
Rotation around the up vector [-180, 180].
Definition spherical.h:144
uint32_t padding
Number of pixels to pad from the edge of each cube face.
Definition spherical.h:200
enum AVStereo3DType type
How views are packed within the video.
Definition stereo3d.h:207
uint32_t baseline
The distance between the centres of the lenses of the camera system, in micrometers.
Definition stereo3d.h:228
AVRational horizontal_disparity_adjustment
Relative shift of the left and right images, which changes the zero parallax plane.
Definition stereo3d.h:234
enum AVStereo3DPrimaryEye primary_eye
Which eye is the primary eye when rendering in 2D.
Definition stereo3d.h:222
int flags
Additional information about the frame packing.
Definition stereo3d.h:212
AVRational horizontal_field_of_view
Horizontal field of view, in degrees.
Definition stereo3d.h:239
enum AVStereo3DView view
Determines which views are packed.
Definition stereo3d.h:217
AVStream * stream
Definition avformat.h:1180
AVStreamGroupLayeredVideo is meant to define the relation between a base layer video stream and a sep...
Definition avformat.h:1104
int height
Height of the final image for presentation.
Definition avformat.h:1129
unsigned int el_index
Index of the enhancement layer stream in AVStreamGroup.
Definition avformat.h:1113
int width
Width of the final stream for presentation.
Definition avformat.h:1125
unsigned int metadata_index
Index of the metadata stream in the AVStreamGroup.
Definition avformat.h:1154
AVStreamGroupTileGrid holds information on how to combine several independent images on a single canv...
Definition avformat.h:975
int width
Width of the final image for presentation.
Definition avformat.h:1060
int height
Height of the final image for presentation.
Definition avformat.h:1070
int coded_width
Width of the canvas.
Definition avformat.h:990
struct AVStreamGroupTileGrid::@036353327352337314037001273105074056331305251354 * offsets
An nb_tiles sized array of offsets in pixels from the topleft edge of the canvas, indicating where ea...
unsigned int nb_tiles
Amount of tiles in the grid.
Definition avformat.h:983
uint8_t background[4]
The pixel value per channel in RGBA format used if no pixel of any tile is located at a particular pi...
Definition avformat.h:1034
int horizontal
Offset in pixels from the left edge of the canvas where the tile should be placed.
Definition avformat.h:1019
unsigned int idx
Index of the stream in the group this tile references.
Definition avformat.h:1014
int coded_height
Width of the canvas.
Definition avformat.h:996
int vertical
Offset in pixels from the top edge of the canvas where the tile should be placed.
Definition avformat.h:1024
unsigned int nb_entries
Number of elements in AVStreamGroup.entries.
Definition avformat.h:1286
enum AVStreamGroupParamsType type
Group type.
Definition avformat.h:1212
struct AVIAMFMixPresentation * iamf_mix_presentation
Definition avformat.h:1219
AVStreamGroupEntry ** entries
A list of streams or child groups in the group.
Definition avformat.h:1299
struct AVStreamGroupTileGrid * tile_grid
Definition avformat.h:1220
struct AVStreamGroupTREF * tref
Definition avformat.h:1229
int nb_coded_side_data
Amount of entries in coded_side_data.
Definition avformat.h:1312
AVDictionary * metadata
Metadata that applies to the whole group.
Definition avformat.h:1240
union AVStreamGroup::@313244315204024013007202273061153315146016101155 params
Group type-specific parameters.
struct AVIAMFAudioElement * iamf_audio_element
Definition avformat.h:1218
int disposition
Stream group disposition - a combination of AV_DISPOSITION_* flags.
Definition avformat.h:1278
int64_t id
Group type-specific group ID.
Definition avformat.h:1204
AVPacketSideData * coded_side_data
Additional data associated with the group.
Definition avformat.h:1307
struct AVStreamGroupLayeredVideo * layered_video
Definition avformat.h:1221
Stream structure.
Definition avformat.h:768
AVCodecParameters * codecpar
Codec parameters associated with this stream.
Definition avformat.h:791
AVRational sample_aspect_ratio
sample aspect ratio (0 if unknown)
Definition avformat.h:846
int64_t nb_frames
number of frames in this stream if known or 0
Definition avformat.h:829
enum AVDiscard discard
Selects which packets can be discarded at will and do not need to be demuxed.
Definition avformat.h:839
int64_t duration
Decoding: duration of the stream, in stream time base.
Definition avformat.h:827
AVDictionary * metadata
Definition avformat.h:848
void * priv_data
Definition avformat.h:793
int id
Format-specific stream ID.
Definition avformat.h:780
int index
stream index in AVFormatContext
Definition avformat.h:774
int64_t start_time
Decoding: pts of the first frame of the stream in presentation order, in stream time base.
Definition avformat.h:817
AVPacket attached_pic
For streams with AV_DISPOSITION_ATTACHED_PIC disposition, this packet will contain the attached pictu...
Definition avformat.h:866
AVRational avg_frame_rate
Average framerate.
Definition avformat.h:857
AVRational time_base
This is the fundamental unit of time (in seconds) in terms of which frame timestamps are represented.
Definition avformat.h:807
AVRational r_frame_rate
Real base framerate of the stream.
Definition avformat.h:902
int disposition
Stream disposition - a combination of AV_DISPOSITION_* flags.
Definition avformat.h:837
This file is part of FFmpeg.
int64_t last_discard_sample
The sample after last sample that is intended to be discarded after first_discard_sample.
Definition internal.h:244
int64_t first_discard_sample
If not 0, the first audio sample that should be discarded from the stream.
Definition internal.h:237
int skip_samples
Number of samples to skip at the start of the frame decoded from the next packet.
Definition internal.h:220
int nb_index_entries
Definition internal.h:198
AVRational display_aspect_ratio
display aspect ratio (0 if unknown)
Definition internal.h:328
AVIndexEntry * index_entries
Only used if the format does not support seeking natively.
Definition internal.h:196
enum AVStreamParseType need_parsing
Definition internal.h:346
unsigned int index_entries_allocated_size
Definition internal.h:199
int16_t * item_id_list
Definition isom.h:330
HEIFItem ** item_list
Definition isom.h:329
int nb_items
Definition isom.h:332
unsigned * item_idx_list
Definition isom.h:331
HEIFItem * item
Definition isom.h:328
int item_id
Definition isom.h:298
uint32_t type
Definition isom.h:297
int is_idat_relative
Definition isom.h:321
int type
Definition isom.h:318
int nb_iref_from_list
Definition isom.h:305
AVStreamGroup * stg
Definition isom.h:303
char * name
Definition isom.h:309
int nb_iref_to_list
Definition isom.h:307
uint8_t * icc_profile
Definition isom.h:323
HEIFItemRef * iref_from_list
Definition isom.h:304
int rotation
Definition isom.h:315
int is_alpha
Definition isom.h:320
int hflip
Definition isom.h:316
AVExifMetadata ifd
Definition isom.h:322
int64_t extent_length
Definition isom.h:311
int flags
Definition isom.h:308
AVStream * st
Definition isom.h:302
int is_gainmap
Definition isom.h:319
size_t icc_profile_size
Definition isom.h:324
int vflip
Definition isom.h:317
int64_t extent_offset
Definition isom.h:312
int width
Definition isom.h:313
int height
Definition isom.h:314
int item_id
Definition isom.h:310
HEIFItemRef * iref_to_list
Definition isom.h:306
IAMFLayer * layers
Definition iamf.h:103
unsigned int audio_element_id
Definition iamf.h:96
AVIAMFAudioElement * element
element backs celement iff the AVIAMFAudioElement is owned by this structure.
Definition iamf.h:95
unsigned int nb_substreams
Definition iamf.h:99
IAMFSubStream * substreams
Definition iamf.h:98
int nb_mix_presentations
Definition iamf.h:134
IAMFMixPresentation ** mix_presentations
Definition iamf.h:133
IAMFAudioElement ** audio_elements
Definition iamf.h:131
int nb_audio_elements
Definition iamf.h:132
IAMFContext iamf
Definition iamf_reader.h:33
unsigned int substream_count
Definition iamf.h:78
AVIAMFMixPresentation * mix
mix backs cmix iff the AVIAMFMixPresentation is owned by this structure.
Definition iamf.h:113
const AVIAMFMixPresentation * cmix
Definition iamf.h:108
unsigned int mix_presentation_id
Definition iamf.h:114
AVCodecParameters * codecpar
Definition iamf.h:86
unsigned int audio_substream_id
Definition iamf.h:83
int64_t size
Definition mov.c:10242
uint32_t type
Definition mov.c:10241
uint8_t * data
Definition mov.c:10243
uint32_t type
Definition isom.h:102
int64_t size
Definition isom.h:103
int handbrake_version
Definition isom.h:355
AVDictionary * decryption_keys
Definition isom.h:404
int * bitrates
bitrates read before streams creation
Definition isom.h:367
int cur_item_id
Definition isom.h:397
int ignore_editlist
Definition isom.h:359
HEIFGroup * heif_group
Definition isom.h:400
uint8_t * decryption_default_key
Definition isom.h:389
unsigned meta_keys_count
Definition isom.h:347
char ** meta_keys
Definition isom.h:346
AVFormatContext * fc
Definition isom.h:337
unsigned int aax_mode
'aax' file has been detected
Definition isom.h:377
int found_mdat
'mdat' atom has been found
Definition isom.h:343
int found_iinf
'iinf' atom has been found
Definition isom.h:342
int bitrates_count
Definition isom.h:368
int * chapter_tracks
Definition isom.h:356
int interleaved_read
Definition isom.h:403
int64_t next_root_atom
offset of the next root atom
Definition isom.h:364
int ignore_chapters
Definition isom.h:362
DVDemuxContext * dv_demux
Definition isom.h:348
int nb_heif_item
Definition isom.h:399
unsigned int nb_chapter_tracks
Definition isom.h:357
int64_t idat_offset
Definition isom.h:402
MOVFragmentIndex frag_index
Definition isom.h:373
int nb_heif_group
Definition isom.h:401
MOVTrackExt * trex_data
Definition isom.h:352
uint8_t * pssh_side_data
Definition isom.h:374
struct AVAES * aes_decrypt
Definition isom.h:388
MOVFragment fragment
current fragment in moof atom
Definition isom.h:351
AVFormatContext * dv_fctx
Definition isom.h:349
int moov_retry
Definition isom.h:369
int time_scale
Definition isom.h:338
int advanced_editlist_autodisabled
Definition isom.h:361
int found_moov
'moov' atom has been found
Definition isom.h:340
int primary_item_id
Definition isom.h:396
int advanced_editlist
Definition isom.h:360
int found_iloc
'iloc' atom has been found
Definition isom.h:341
HEIFItem ** heif_item
Definition isom.h:398
int trak_index
Index of the current 'trak'.
Definition isom.h:345
int use_mfra_for
Definition isom.h:370
Definition isom.h:69
unsigned int count
Definition isom.h:70
int offset
Definition isom.h:71
Definition isom.h:86
char volume[28]
Definition isom.h:90
char * dir
Definition isom.h:89
int16_t nlvl_to
Definition isom.h:92
char * path
Definition isom.h:88
uint32_t type
Definition isom.h:87
int16_t nlvl_from
Definition isom.h:92
char filename[64]
Definition isom.h:91
Definition isom.h:80
float rate
Definition isom.h:83
int64_t duration
Definition isom.h:81
int64_t time
Definition isom.h:82
uint64_t * auxiliary_offsets
Absolute seek position.
Definition isom.h:142
unsigned int nb_encrypted_samples
Definition isom.h:136
size_t auxiliary_offsets_count
Definition isom.h:143
size_t auxiliary_info_sample_count
Definition isom.h:140
uint8_t auxiliary_info_default_size
Definition isom.h:141
uint8_t * auxiliary_info_sizes
Definition isom.h:139
AVEncryptionInfo ** encrypted_samples
Definition isom.h:137
MOVFragmentStreamInfo * stream_info
Definition isom.h:164
int64_t moof_offset
Definition isom.h:160
int allocated_size
Definition isom.h:168
MOVFragmentIndexItem * item
Definition isom.h:172
MOVEncryptionIndex * encryption_index
Definition isom.h:155
int64_t next_trun_dts
Definition isom.h:151
int64_t first_tfra_pts
Definition isom.h:149
unsigned track_id
Definition isom.h:110
unsigned flags
Definition isom.h:117
unsigned duration
Definition isom.h:115
int found_tfhd
Definition isom.h:109
unsigned size
Definition isom.h:116
unsigned stsd_id
Definition isom.h:114
uint64_t base_data_offset
Definition isom.h:111
uint64_t moof_offset
Definition isom.h:112
uint64_t implicit_offset
Definition isom.h:113
int64_t start
Definition isom.h:176
int64_t end
Definition isom.h:177
int(* parse)(MOVContext *ctx, AVIOContext *pb, MOVAtom atom)
Definition mov.c:89
uint32_t type
Definition mov.c:88
unsigned int index
Definition isom.h:130
unsigned int count
Definition isom.h:129
int64_t time_offset
time offset of the edit list entries
Definition isom.h:218
int64_t duration_for_fps
Definition isom.h:258
AVIOContext * pb
Definition isom.h:181
size_t spherical_size
Definition isom.h:273
uint32_t min_sample_duration
Definition isom.h:255
uint8_t ** extradata
extradata array (and size) for multiple stsd
Definition isom.h:261
MOVSbgp * rap_group
Definition isom.h:246
int iamf_stream_offset
Definition isom.h:293
MOVEncryptionIndex * encryption_index
Definition isom.h:289
int64_t track_end
used for dts generation in fragmented movie files
Definition isom.h:244
int pseudo_stream_id
-1 means demux all ids
Definition isom.h:227
unsigned int rap_group_count
Definition isom.h:245
int height
tkhd height
Definition isom.h:235
int stsc_sample
Definition isom.h:203
MOVDref * drefs
Definition isom.h:230
int sample_offsets_count
Definition isom.h:252
unsigned int ctts_allocated_size
Definition isom.h:198
unsigned int per_sample_iv_size
Definition isom.h:287
int * extradata_size
Definition isom.h:262
size_t coll_size
Definition isom.h:277
int dv_audio_container
Definition isom.h:226
AVContentLightMetadata * coll
Definition isom.h:276
int64_t * chunk_offsets
Definition isom.h:188
size_t ambient_size
Definition isom.h:279
int stsd_colr_trc
the colr atom of the sample description being read sets the transfer
Definition isom.h:266
MOVStsc * stsc_data
Definition isom.h:201
uint8_t * sgpd_sync
Definition isom.h:249
size_t stereo3d_size
Definition isom.h:271
MOVTimeToSample * tts_data
Definition isom.h:191
AVStereo3D * stereo3d
Definition isom.h:270
int32_t * display_matrix
Definition isom.h:269
int current_sample
Definition isom.h:220
uint32_t sgpd_sync_count
Definition isom.h:250
unsigned int samples_per_frame
Definition isom.h:225
int nb_frames_for_fps
Definition isom.h:257
uint32_t format
Definition isom.h:281
int keyframe_absent
Definition isom.h:214
int open_key_samples_count
Definition isom.h:254
MOVElst * elst_data
Definition isom.h:206
int64_t current_index
Definition isom.h:221
int * open_key_samples
Definition isom.h:253
unsigned int stts_count
Definition isom.h:192
uint8_t * sdtp_data
Definition isom.h:196
unsigned int sample_size
may contain value calculated from stsd or value from stsz atom
Definition isom.h:210
AVEncryptionInfo * default_encrypted_sample
Definition isom.h:288
int nb_tref_tags
Definition isom.h:232
int16_t audio_cid
stsd audio compression id
Definition isom.h:228
struct AVAESCTR * aes_ctr
Definition isom.h:285
MOVStts * stts_data
Definition isom.h:194
int last_stsd_index
Definition isom.h:263
unsigned int chunk_count
Definition isom.h:187
size_t mastering_size
Definition isom.h:275
AVAmbientViewingEnvironment * ambient
Definition isom.h:278
int64_t data_size
Definition isom.h:241
int pb_is_copied
Definition isom.h:183
int * keyframes
Definition isom.h:216
struct MOVStreamContext::@212112112267365060330232277203165117121340225276 cenc
unsigned drefs_count
Definition isom.h:229
MOVIndexRange * current_index_range
Definition isom.h:223
unsigned int * sample_sizes
Definition isom.h:213
MOVCtts * ctts_data
Definition isom.h:199
AVMasteringDisplayMetadata * mastering
Definition isom.h:274
int width
tkhd width
Definition isom.h:234
int id
AVStream id.
Definition isom.h:184
uint8_t tmcd_nb_frames
tmcd number of frames per tick / second
Definition isom.h:243
unsigned int sdtp_count
Definition isom.h:195
int v_spacing
pasp vSpacing
Definition isom.h:237
unsigned int sample_count
Definition isom.h:212
MOVSbgp * sync_group
Definition isom.h:248
int dts_shift
dts shift when ctts is negative
Definition isom.h:238
unsigned int tts_count
Definition isom.h:189
int stsd_version
Definition isom.h:267
unsigned int stsc_index
Definition isom.h:202
int64_t min_corrected_pts
minimum Composition time shown by the edits excluding empty edits.
Definition isom.h:219
struct AVAES * aes_ctx
Definition isom.h:286
int32_t * sample_offsets
Definition isom.h:251
int has_palette
Definition isom.h:240
int stsd_gama_trc
transfer from the gama atom of the sample description being read
Definition isom.h:265
MovTref * tref_tags
Definition isom.h:233
uint32_t palette[256]
Definition isom.h:239
int ffindex
AVStream index.
Definition isom.h:185
AVSphericalMapping * spherical
Definition isom.h:272
unsigned int keyframe_count
Definition isom.h:215
unsigned int bytes_per_frame
Definition isom.h:224
uint32_t tmcd_flags
tmcd track flags
Definition isom.h:242
unsigned * stps_data
partial sync sample for mpeg-2 open gop
Definition isom.h:205
unsigned int stts_allocated_size
Definition isom.h:193
unsigned int sync_group_count
Definition isom.h:247
MOVIndexRange * index_ranges
Definition isom.h:222
struct IAMFDemuxContext * iamf
Definition isom.h:292
unsigned int stsc_count
Definition isom.h:200
unsigned int stsz_sample_size
always contains sample size from stsz atom
Definition isom.h:211
int h_spacing
pasp hSpacing
Definition isom.h:236
unsigned int elst_count
Definition isom.h:207
unsigned int ctts_count
Definition isom.h:197
unsigned int stps_count
Definition isom.h:204
unsigned int tts_allocated_size
Definition isom.h:190
int first
Definition isom.h:75
int count
Definition isom.h:76
int id
Definition isom.h:77
Definition isom.h:64
unsigned int count
Definition isom.h:65
unsigned int duration
Definition isom.h:66
unsigned int count
Definition isom.h:59
unsigned int duration
Definition isom.h:60
unsigned flags
Definition isom.h:125
unsigned duration
Definition isom.h:123
unsigned size
Definition isom.h:124
unsigned track_id
Definition isom.h:121
unsigned stsd_id
Definition isom.h:122
const char * value
Definition isom.h:517
Definition isom.h:95
uint32_t * id
trackID of the referenced track
Definition isom.h:98
Definition swscale.c:85
#define OPUS_TIMESTAMP_RATE
The clock of Opus: packet lengths, pre-skip and trimming count samples at 48 kHz whatever the sample ...
Definition tab.h:35
#define llrint
Definition tablegen.h:47
#define av_free(p)
#define av_malloc_array(a, b)
#define av_mallocz(s)
#define ff_dlog(a,...)
#define av_realloc_f(p, o, n)
#define avpriv_request_sample(...)
#define av_freep(p)
#define av_log(a,...)
static uint8_t tmp[40]
Definition aes_ctr.c:52
static const uint8_t fixed_key[]
Definition aes_ctr.c:45
int tile_cols
Definition av1_levels.c:73
#define alt(var)
#define src
Definition vp8dsp.c:248
int num
Definition error.c:23
static int ref[MAX_W *MAX_W]
static char buffer[20]
Definition seek.c:33
#define height
Definition dsp.h:99
#define width
Definition dsp.h:99
int av_timecode_init(AVTimecode *tc, AVRational rate, int flags, int frame_start, void *log_ctx)
Init a timecode struct with the passed parameters.
Definition timecode.c:201
char * av_timecode_make_string(const AVTimecode *tc, char *buf, int framenum_arg)
Load timecode string in buf.
Definition timecode.c:104
Timecode helpers header.
#define AV_TIMECODE_STR_SIZE
Definition timecode.h:33
@ AV_TIMECODE_FLAG_ALLOWNEGATIVE
negative time values are allowed
Definition timecode.h:38
@ AV_TIMECODE_FLAG_DROPFRAME
timecode is drop frame
Definition timecode.h:36
@ AV_TIMECODE_FLAG_24HOURSMAX
timecode wraps after 24 hours
Definition timecode.h:37
static int64_t pts
static const int16_t cdt2[8]
int size
UUID parsing and serialization utilities.
static int av_uuid_equal(const AVUUID uu1, const AVUUID uu2)
Compares two UUIDs for equality.
Definition uuid.h:119
#define AV_UUID_LEN
Definition uuid.h:57
uint8_t AVUUID[AV_UUID_LEN]
Definition uuid.h:60
enum AVCodecID codec_id
#define mc
static float mean(const float *input, int size)
Definition vf_nnedi.c:792
color_range
int len
uint8_t base
Definition vp3data.h:128
static double c[64]