LCOV - code coverage report
Current view: top level - libavformat - mov.c (source / functions) Hit Total Coverage
Test: coverage.info Lines: 2620 4295 61.0 %
Date: 2017-12-11 04:34:20 Functions: 112 144 77.8 %

          Line data    Source code
       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 <inttypes.h>
      27             : #include <limits.h>
      28             : #include <stdint.h>
      29             : 
      30             : #include "libavutil/attributes.h"
      31             : #include "libavutil/channel_layout.h"
      32             : #include "libavutil/internal.h"
      33             : #include "libavutil/intreadwrite.h"
      34             : #include "libavutil/intfloat.h"
      35             : #include "libavutil/mathematics.h"
      36             : #include "libavutil/time_internal.h"
      37             : #include "libavutil/avassert.h"
      38             : #include "libavutil/avstring.h"
      39             : #include "libavutil/dict.h"
      40             : #include "libavutil/display.h"
      41             : #include "libavutil/opt.h"
      42             : #include "libavutil/aes.h"
      43             : #include "libavutil/aes_ctr.h"
      44             : #include "libavutil/pixdesc.h"
      45             : #include "libavutil/sha.h"
      46             : #include "libavutil/spherical.h"
      47             : #include "libavutil/stereo3d.h"
      48             : #include "libavutil/timecode.h"
      49             : #include "libavcodec/ac3tab.h"
      50             : #include "libavcodec/flac.h"
      51             : #include "libavcodec/mpegaudiodecheader.h"
      52             : #include "avformat.h"
      53             : #include "internal.h"
      54             : #include "avio_internal.h"
      55             : #include "riff.h"
      56             : #include "isom.h"
      57             : #include "libavcodec/get_bits.h"
      58             : #include "id3v1.h"
      59             : #include "mov_chan.h"
      60             : #include "replaygain.h"
      61             : 
      62             : #if CONFIG_ZLIB
      63             : #include <zlib.h>
      64             : #endif
      65             : 
      66             : #include "qtpalette.h"
      67             : 
      68             : /* those functions parse an atom */
      69             : /* links atom IDs to parse functions */
      70             : typedef struct MOVParseTableEntry {
      71             :     uint32_t type;
      72             :     int (*parse)(MOVContext *ctx, AVIOContext *pb, MOVAtom atom);
      73             : } MOVParseTableEntry;
      74             : 
      75             : static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom);
      76             : static int mov_read_mfra(MOVContext *c, AVIOContext *f);
      77             : static int64_t add_ctts_entry(MOVStts** ctts_data, unsigned int* ctts_count, unsigned int* allocated_size,
      78             :                               int count, int duration);
      79             : 
      80          12 : static int mov_metadata_track_or_disc_number(MOVContext *c, AVIOContext *pb,
      81             :                                              unsigned len, const char *key)
      82             : {
      83             :     char buf[16];
      84             : 
      85          12 :     short current, total = 0;
      86          12 :     avio_rb16(pb); // unknown
      87          12 :     current = avio_rb16(pb);
      88          12 :     if (len >= 6)
      89          12 :         total = avio_rb16(pb);
      90          12 :     if (!total)
      91           2 :         snprintf(buf, sizeof(buf), "%d", current);
      92             :     else
      93          10 :         snprintf(buf, sizeof(buf), "%d/%d", current, total);
      94          12 :     c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
      95          12 :     av_dict_set(&c->fc->metadata, key, buf, 0);
      96             : 
      97          12 :     return 0;
      98             : }
      99             : 
     100           0 : static int mov_metadata_int8_bypass_padding(MOVContext *c, AVIOContext *pb,
     101             :                                             unsigned len, const char *key)
     102             : {
     103             :     /* bypass padding bytes */
     104           0 :     avio_r8(pb);
     105           0 :     avio_r8(pb);
     106           0 :     avio_r8(pb);
     107             : 
     108           0 :     c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
     109           0 :     av_dict_set_int(&c->fc->metadata, key, avio_r8(pb), 0);
     110             : 
     111           0 :     return 0;
     112             : }
     113             : 
     114          14 : static int mov_metadata_int8_no_padding(MOVContext *c, AVIOContext *pb,
     115             :                                         unsigned len, const char *key)
     116             : {
     117          14 :     c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
     118          14 :     av_dict_set_int(&c->fc->metadata, key, avio_r8(pb), 0);
     119             : 
     120          14 :     return 0;
     121             : }
     122             : 
     123           6 : static int mov_metadata_gnre(MOVContext *c, AVIOContext *pb,
     124             :                              unsigned len, const char *key)
     125             : {
     126             :     short genre;
     127             : 
     128           6 :     avio_r8(pb); // unknown
     129             : 
     130           6 :     genre = avio_r8(pb);
     131           6 :     if (genre < 1 || genre > ID3v1_GENRE_MAX)
     132           0 :         return 0;
     133           6 :     c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
     134           6 :     av_dict_set(&c->fc->metadata, key, ff_id3v1_genre_str[genre-1], 0);
     135             : 
     136           6 :     return 0;
     137             : }
     138             : 
     139             : static const uint32_t mac_to_unicode[128] = {
     140             :     0x00C4,0x00C5,0x00C7,0x00C9,0x00D1,0x00D6,0x00DC,0x00E1,
     141             :     0x00E0,0x00E2,0x00E4,0x00E3,0x00E5,0x00E7,0x00E9,0x00E8,
     142             :     0x00EA,0x00EB,0x00ED,0x00EC,0x00EE,0x00EF,0x00F1,0x00F3,
     143             :     0x00F2,0x00F4,0x00F6,0x00F5,0x00FA,0x00F9,0x00FB,0x00FC,
     144             :     0x2020,0x00B0,0x00A2,0x00A3,0x00A7,0x2022,0x00B6,0x00DF,
     145             :     0x00AE,0x00A9,0x2122,0x00B4,0x00A8,0x2260,0x00C6,0x00D8,
     146             :     0x221E,0x00B1,0x2264,0x2265,0x00A5,0x00B5,0x2202,0x2211,
     147             :     0x220F,0x03C0,0x222B,0x00AA,0x00BA,0x03A9,0x00E6,0x00F8,
     148             :     0x00BF,0x00A1,0x00AC,0x221A,0x0192,0x2248,0x2206,0x00AB,
     149             :     0x00BB,0x2026,0x00A0,0x00C0,0x00C3,0x00D5,0x0152,0x0153,
     150             :     0x2013,0x2014,0x201C,0x201D,0x2018,0x2019,0x00F7,0x25CA,
     151             :     0x00FF,0x0178,0x2044,0x20AC,0x2039,0x203A,0xFB01,0xFB02,
     152             :     0x2021,0x00B7,0x201A,0x201E,0x2030,0x00C2,0x00CA,0x00C1,
     153             :     0x00CB,0x00C8,0x00CD,0x00CE,0x00CF,0x00CC,0x00D3,0x00D4,
     154             :     0xF8FF,0x00D2,0x00DA,0x00DB,0x00D9,0x0131,0x02C6,0x02DC,
     155             :     0x00AF,0x02D8,0x02D9,0x02DA,0x00B8,0x02DD,0x02DB,0x02C7,
     156             : };
     157             : 
     158         218 : static int mov_read_mac_string(MOVContext *c, AVIOContext *pb, int len,
     159             :                                char *dst, int dstlen)
     160             : {
     161         218 :     char *p = dst;
     162         218 :     char *end = dst+dstlen-1;
     163             :     int i;
     164             : 
     165        2105 :     for (i = 0; i < len; i++) {
     166        1887 :         uint8_t t, c = avio_r8(pb);
     167             : 
     168        1887 :         if (p >= end)
     169           0 :             continue;
     170             : 
     171        1887 :         if (c < 0x80)
     172        1885 :             *p++ = c;
     173           2 :         else if (p < end)
     174           2 :             PUT_UTF8(mac_to_unicode[c-0x80], t, if (p < end) *p++ = t;);
     175             :     }
     176         218 :     *p = 0;
     177         218 :     return p - dst;
     178             : }
     179             : 
     180           6 : static int mov_read_covr(MOVContext *c, AVIOContext *pb, int type, int len)
     181             : {
     182             :     AVPacket pkt;
     183             :     AVStream *st;
     184             :     MOVStreamContext *sc;
     185             :     enum AVCodecID id;
     186             :     int ret;
     187             : 
     188           6 :     switch (type) {
     189           4 :     case 0xd:  id = AV_CODEC_ID_MJPEG; break;
     190           2 :     case 0xe:  id = AV_CODEC_ID_PNG;   break;
     191           0 :     case 0x1b: id = AV_CODEC_ID_BMP;   break;
     192           0 :     default:
     193           0 :         av_log(c->fc, AV_LOG_WARNING, "Unknown cover type: 0x%x.\n", type);
     194           0 :         avio_skip(pb, len);
     195           0 :         return 0;
     196             :     }
     197             : 
     198           6 :     st = avformat_new_stream(c->fc, NULL);
     199           6 :     if (!st)
     200           0 :         return AVERROR(ENOMEM);
     201           6 :     sc = av_mallocz(sizeof(*sc));
     202           6 :     if (!sc)
     203           0 :         return AVERROR(ENOMEM);
     204           6 :     st->priv_data = sc;
     205             : 
     206           6 :     ret = av_get_packet(pb, &pkt, len);
     207           6 :     if (ret < 0)
     208           0 :         return ret;
     209             : 
     210           6 :     if (pkt.size >= 8 && id != AV_CODEC_ID_BMP) {
     211           6 :         if (AV_RB64(pkt.data) == 0x89504e470d0a1a0a) {
     212           2 :             id = AV_CODEC_ID_PNG;
     213             :         } else {
     214           4 :             id = AV_CODEC_ID_MJPEG;
     215             :         }
     216             :     }
     217             : 
     218           6 :     st->disposition              |= AV_DISPOSITION_ATTACHED_PIC;
     219             : 
     220           6 :     st->attached_pic              = pkt;
     221           6 :     st->attached_pic.stream_index = st->index;
     222           6 :     st->attached_pic.flags       |= AV_PKT_FLAG_KEY;
     223             : 
     224           6 :     st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
     225           6 :     st->codecpar->codec_id   = id;
     226             : 
     227           6 :     return 0;
     228             : }
     229             : 
     230             : // 3GPP TS 26.244
     231           0 : static int mov_metadata_loci(MOVContext *c, AVIOContext *pb, unsigned len)
     232             : {
     233           0 :     char language[4] = { 0 };
     234             :     char buf[200], place[100];
     235           0 :     uint16_t langcode = 0;
     236             :     double longitude, latitude, altitude;
     237           0 :     const char *key = "location";
     238             : 
     239           0 :     if (len < 4 + 2 + 1 + 1 + 4 + 4 + 4) {
     240           0 :         av_log(c->fc, AV_LOG_ERROR, "loci too short\n");
     241           0 :         return AVERROR_INVALIDDATA;
     242             :     }
     243             : 
     244           0 :     avio_skip(pb, 4); // version+flags
     245           0 :     langcode = avio_rb16(pb);
     246           0 :     ff_mov_lang_to_iso639(langcode, language);
     247           0 :     len -= 6;
     248             : 
     249           0 :     len -= avio_get_str(pb, len, place, sizeof(place));
     250           0 :     if (len < 1) {
     251           0 :         av_log(c->fc, AV_LOG_ERROR, "place name too long\n");
     252           0 :         return AVERROR_INVALIDDATA;
     253             :     }
     254           0 :     avio_skip(pb, 1); // role
     255           0 :     len -= 1;
     256             : 
     257           0 :     if (len < 12) {
     258           0 :         av_log(c->fc, AV_LOG_ERROR,
     259             :                "loci too short (%u bytes left, need at least %d)\n", len, 12);
     260           0 :         return AVERROR_INVALIDDATA;
     261             :     }
     262           0 :     longitude = ((int32_t) avio_rb32(pb)) / (float) (1 << 16);
     263           0 :     latitude  = ((int32_t) avio_rb32(pb)) / (float) (1 << 16);
     264           0 :     altitude  = ((int32_t) avio_rb32(pb)) / (float) (1 << 16);
     265             : 
     266             :     // Try to output in the same format as the ?xyz field
     267           0 :     snprintf(buf, sizeof(buf), "%+08.4f%+09.4f",  latitude, longitude);
     268           0 :     if (altitude)
     269           0 :         av_strlcatf(buf, sizeof(buf), "%+f", altitude);
     270           0 :     av_strlcatf(buf, sizeof(buf), "/%s", place);
     271             : 
     272           0 :     if (*language && strcmp(language, "und")) {
     273             :         char key2[16];
     274           0 :         snprintf(key2, sizeof(key2), "%s-%s", key, language);
     275           0 :         av_dict_set(&c->fc->metadata, key2, buf, 0);
     276             :     }
     277           0 :     c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
     278           0 :     return av_dict_set(&c->fc->metadata, key, buf, 0);
     279             : }
     280             : 
     281           0 : static int mov_metadata_hmmt(MOVContext *c, AVIOContext *pb, unsigned len)
     282             : {
     283             :     int i, n_hmmt;
     284             : 
     285           0 :     if (len < 2)
     286           0 :         return 0;
     287           0 :     if (c->ignore_chapters)
     288           0 :         return 0;
     289             : 
     290           0 :     n_hmmt = avio_rb32(pb);
     291           0 :     for (i = 0; i < n_hmmt && !pb->eof_reached; i++) {
     292           0 :         int moment_time = avio_rb32(pb);
     293           0 :         avpriv_new_chapter(c->fc, i, av_make_q(1, 1000), moment_time, AV_NOPTS_VALUE, NULL);
     294             :     }
     295           0 :     return 0;
     296             : }
     297             : 
     298         301 : static int mov_read_udta_string(MOVContext *c, AVIOContext *pb, MOVAtom atom)
     299             : {
     300             :     char tmp_key[5];
     301         301 :     char key2[32], language[4] = {0};
     302         301 :     char *str = NULL;
     303         301 :     const char *key = NULL;
     304         301 :     uint16_t langcode = 0;
     305         301 :     uint32_t data_type = 0, str_size, str_size_alloc;
     306         301 :     int (*parse)(MOVContext*, AVIOContext*, unsigned, const char*) = NULL;
     307         301 :     int raw = 0;
     308         301 :     int num = 0;
     309             : 
     310         301 :     switch (atom.type) {
     311           3 :     case MKTAG( '@','P','R','M'): key = "premiere_version"; raw = 1; break;
     312           3 :     case MKTAG( '@','P','R','Q'): key = "quicktime_version"; raw = 1; break;
     313           1 :     case MKTAG( 'X','M','P','_'):
     314           1 :         if (c->export_xmp) { key = "xmp"; raw = 1; } break;
     315           6 :     case MKTAG( 'a','A','R','T'): key = "album_artist";    break;
     316           0 :     case MKTAG( 'a','k','I','D'): key = "account_type";
     317           0 :         parse = mov_metadata_int8_no_padding; break;
     318           0 :     case MKTAG( 'a','p','I','D'): key = "account_id"; break;
     319           0 :     case MKTAG( 'c','a','t','g'): key = "category"; break;
     320           7 :     case MKTAG( 'c','p','i','l'): key = "compilation";
     321           7 :         parse = mov_metadata_int8_no_padding; break;
     322           0 :     case MKTAG( 'c','p','r','t'): key = "copyright"; break;
     323           0 :     case MKTAG( 'd','e','s','c'): key = "description"; break;
     324           6 :     case MKTAG( 'd','i','s','k'): key = "disc";
     325           6 :         parse = mov_metadata_track_or_disc_number; break;
     326           0 :     case MKTAG( 'e','g','i','d'): key = "episode_uid";
     327           0 :         parse = mov_metadata_int8_no_padding; break;
     328           0 :     case MKTAG( 'F','I','R','M'): key = "firmware"; raw = 1; break;
     329           6 :     case MKTAG( 'g','n','r','e'): key = "genre";
     330           6 :         parse = mov_metadata_gnre; break;
     331           0 :     case MKTAG( 'h','d','v','d'): key = "hd_video";
     332           0 :         parse = mov_metadata_int8_no_padding; break;
     333           0 :     case MKTAG( 'H','M','M','T'):
     334           0 :         return mov_metadata_hmmt(c, pb, atom.size);
     335           0 :     case MKTAG( 'k','e','y','w'): key = "keywords";  break;
     336           0 :     case MKTAG( 'l','d','e','s'): key = "synopsis";  break;
     337           0 :     case MKTAG( 'l','o','c','i'):
     338           0 :         return mov_metadata_loci(c, pb, atom.size);
     339           0 :     case MKTAG( 'p','c','s','t'): key = "podcast";
     340           0 :         parse = mov_metadata_int8_no_padding; break;
     341           7 :     case MKTAG( 'p','g','a','p'): key = "gapless_playback";
     342           7 :         parse = mov_metadata_int8_no_padding; break;
     343           0 :     case MKTAG( 'p','u','r','d'): key = "purchase_date"; break;
     344           0 :     case MKTAG( 'r','t','n','g'): key = "rating";
     345           0 :         parse = mov_metadata_int8_no_padding; break;
     346           0 :     case MKTAG( 's','o','a','a'): key = "sort_album_artist"; break;
     347           0 :     case MKTAG( 's','o','a','l'): key = "sort_album";   break;
     348           0 :     case MKTAG( 's','o','a','r'): key = "sort_artist";  break;
     349           0 :     case MKTAG( 's','o','c','o'): key = "sort_composer"; break;
     350           0 :     case MKTAG( 's','o','n','m'): key = "sort_name";    break;
     351           0 :     case MKTAG( 's','o','s','n'): key = "sort_show";    break;
     352           0 :     case MKTAG( 's','t','i','k'): key = "media_type";
     353           0 :         parse = mov_metadata_int8_no_padding; break;
     354           6 :     case MKTAG( 't','r','k','n'): key = "track";
     355           6 :         parse = mov_metadata_track_or_disc_number; break;
     356           0 :     case MKTAG( 't','v','e','n'): key = "episode_id"; break;
     357           0 :     case MKTAG( 't','v','e','s'): key = "episode_sort";
     358           0 :         parse = mov_metadata_int8_bypass_padding; break;
     359           0 :     case MKTAG( 't','v','n','n'): key = "network";   break;
     360           0 :     case MKTAG( 't','v','s','h'): key = "show";      break;
     361           0 :     case MKTAG( 't','v','s','n'): key = "season_number";
     362           0 :         parse = mov_metadata_int8_bypass_padding; break;
     363          10 :     case MKTAG(0xa9,'A','R','T'): key = "artist";    break;
     364           0 :     case MKTAG(0xa9,'P','R','D'): key = "producer";  break;
     365          10 :     case MKTAG(0xa9,'a','l','b'): key = "album";     break;
     366           2 :     case MKTAG(0xa9,'a','u','t'): key = "artist";    break;
     367           0 :     case MKTAG(0xa9,'c','h','p'): key = "chapter";   break;
     368           4 :     case MKTAG(0xa9,'c','m','t'): key = "comment";   break;
     369           0 :     case MKTAG(0xa9,'c','o','m'): key = "composer";  break;
     370           3 :     case MKTAG(0xa9,'c','p','y'): key = "copyright"; break;
     371          10 :     case MKTAG(0xa9,'d','a','y'): key = "date";      break;
     372           0 :     case MKTAG(0xa9,'d','i','r'): key = "director";  break;
     373           0 :     case MKTAG(0xa9,'d','i','s'): key = "disclaimer"; break;
     374           0 :     case MKTAG(0xa9,'e','d','1'): key = "edit_date"; break;
     375           2 :     case MKTAG(0xa9,'e','n','c'): key = "encoder";   break;
     376           0 :     case MKTAG(0xa9,'f','m','t'): key = "original_format"; break;
     377           0 :     case MKTAG(0xa9,'g','e','n'): key = "genre";     break;
     378           0 :     case MKTAG(0xa9,'g','r','p'): key = "grouping";  break;
     379           0 :     case MKTAG(0xa9,'h','s','t'): key = "host_computer"; break;
     380           0 :     case MKTAG(0xa9,'i','n','f'): key = "comment";   break;
     381           0 :     case MKTAG(0xa9,'l','y','r'): key = "lyrics";    break;
     382           2 :     case MKTAG(0xa9,'m','a','k'): key = "make";      break;
     383           2 :     case MKTAG(0xa9,'m','o','d'): key = "model";     break;
     384          26 :     case MKTAG(0xa9,'n','a','m'): key = "title";     break;
     385           0 :     case MKTAG(0xa9,'o','p','e'): key = "original_artist"; break;
     386           0 :     case MKTAG(0xa9,'p','r','d'): key = "producer";  break;
     387           0 :     case MKTAG(0xa9,'p','r','f'): key = "performers"; break;
     388           0 :     case MKTAG(0xa9,'r','e','q'): key = "playback_requirements"; break;
     389           0 :     case MKTAG(0xa9,'s','r','c'): key = "original_source"; break;
     390           0 :     case MKTAG(0xa9,'s','t','3'): key = "subtitle";  break;
     391          44 :     case MKTAG(0xa9,'s','w','r'): key = "encoder";   break;
     392          34 :     case MKTAG(0xa9,'t','o','o'): key = "encoder";   break;
     393           0 :     case MKTAG(0xa9,'t','r','k'): key = "track";     break;
     394           0 :     case MKTAG(0xa9,'u','r','l'): key = "URL";       break;
     395           0 :     case MKTAG(0xa9,'w','r','n'): key = "warning";   break;
     396           0 :     case MKTAG(0xa9,'w','r','t'): key = "composer";  break;
     397           2 :     case MKTAG(0xa9,'x','y','z'): key = "location";  break;
     398             :     }
     399         301 : retry:
     400         464 :     if (c->itunes_metadata && atom.size > 8) {
     401         169 :         int data_size = avio_rb32(pb);
     402         169 :         int tag = avio_rl32(pb);
     403         169 :         if (tag == MKTAG('d','a','t','a') && data_size <= atom.size) {
     404         169 :             data_type = avio_rb32(pb); // type
     405         169 :             avio_rb32(pb); // unknown
     406         169 :             str_size = data_size - 16;
     407         169 :             atom.size -= 16;
     408             : 
     409         332 :             if (atom.type == MKTAG('c', 'o', 'v', 'r')) {
     410           6 :                 int ret = mov_read_covr(c, pb, data_type, str_size);
     411           6 :                 if (ret < 0) {
     412           0 :                     av_log(c->fc, AV_LOG_ERROR, "Error parsing cover art.\n");
     413             :                 }
     414           6 :                 return ret;
     415         163 :             } else if (!key && c->found_hdlr_mdta && c->meta_keys) {
     416          28 :                 uint32_t index = AV_RB32(&atom.type);
     417          28 :                 if (index < c->meta_keys_count && index > 0) {
     418          28 :                     key = c->meta_keys[index];
     419             :                 } else {
     420           0 :                     av_log(c->fc, AV_LOG_WARNING,
     421             :                            "The index of 'data' is out of range: %"PRId32" < 1 or >= %d.\n",
     422             :                            index, c->meta_keys_count);
     423             :                 }
     424             :             }
     425           0 :         } else return 0;
     426         132 :     } else if (atom.size > 4 && key && !c->itunes_metadata && !raw) {
     427          68 :         str_size = avio_rb16(pb); // string length
     428          68 :         if (str_size > atom.size) {
     429           0 :             raw = 1;
     430           0 :             avio_seek(pb, -2, SEEK_CUR);
     431           0 :             av_log(c->fc, AV_LOG_WARNING, "UDTA parsing failed retrying raw\n");
     432           0 :             goto retry;
     433             :         }
     434          68 :         langcode = avio_rb16(pb);
     435          68 :         ff_mov_lang_to_iso639(langcode, language);
     436          68 :         atom.size -= 4;
     437             :     } else
     438          64 :         str_size = atom.size;
     439             : 
     440         295 :     if (c->export_all && !key) {
     441           0 :         snprintf(tmp_key, 5, "%.4s", (char*)&atom.type);
     442           0 :         key = tmp_key;
     443             :     }
     444             : 
     445         295 :     if (!key)
     446          72 :         return 0;
     447         223 :     if (atom.size < 0 || str_size >= INT_MAX/2)
     448           0 :         return AVERROR_INVALIDDATA;
     449             : 
     450             :     // Allocates enough space if data_type is a int32 or float32 number, otherwise
     451             :     // worst-case requirement for output string in case of utf8 coded input
     452         223 :     num = (data_type >= 21 && data_type <= 23);
     453         223 :     str_size_alloc = (num ? 512 : (raw ? str_size : str_size * 2)) + 1;
     454         223 :     str = av_mallocz(str_size_alloc);
     455         223 :     if (!str)
     456           0 :         return AVERROR(ENOMEM);
     457             : 
     458         223 :     if (parse)
     459          32 :         parse(c, pb, str_size, key);
     460             :     else {
     461         191 :         if (!raw && (data_type == 3 || (data_type == 0 && (langcode < 0x400 || langcode == 0x7fff)))) { // MAC Encoded
     462          10 :             mov_read_mac_string(c, pb, str_size, str, str_size_alloc);
     463         181 :         } else if (data_type == 21) { // BE signed integer, variable size
     464           0 :             int val = 0;
     465           0 :             if (str_size == 1)
     466           0 :                 val = (int8_t)avio_r8(pb);
     467           0 :             else if (str_size == 2)
     468           0 :                 val = (int16_t)avio_rb16(pb);
     469           0 :             else if (str_size == 3)
     470           0 :                 val = ((int32_t)(avio_rb24(pb)<<8))>>8;
     471           0 :             else if (str_size == 4)
     472           0 :                 val = (int32_t)avio_rb32(pb);
     473           0 :             if (snprintf(str, str_size_alloc, "%d", val) >= str_size_alloc) {
     474           0 :                 av_log(c->fc, AV_LOG_ERROR,
     475             :                        "Failed to store the number (%d) in string.\n", val);
     476           0 :                 av_free(str);
     477           0 :                 return AVERROR_INVALIDDATA;
     478             :             }
     479         181 :         } else if (data_type == 22) { // BE unsigned integer, variable size
     480           0 :             unsigned int val = 0;
     481           0 :             if (str_size == 1)
     482           0 :                 val = avio_r8(pb);
     483           0 :             else if (str_size == 2)
     484           0 :                 val = avio_rb16(pb);
     485           0 :             else if (str_size == 3)
     486           0 :                 val = avio_rb24(pb);
     487           0 :             else if (str_size == 4)
     488           0 :                 val = avio_rb32(pb);
     489           0 :             if (snprintf(str, str_size_alloc, "%u", val) >= str_size_alloc) {
     490           0 :                 av_log(c->fc, AV_LOG_ERROR,
     491             :                        "Failed to store the number (%u) in string.\n", val);
     492           0 :                 av_free(str);
     493           0 :                 return AVERROR_INVALIDDATA;
     494             :             }
     495         194 :         } else if (data_type == 23 && str_size >= 4) {  // BE float32
     496          13 :             float val = av_int2float(avio_rb32(pb));
     497          13 :             if (snprintf(str, str_size_alloc, "%f", val) >= str_size_alloc) {
     498           0 :                 av_log(c->fc, AV_LOG_ERROR,
     499             :                        "Failed to store the float32 number (%f) in string.\n", val);
     500           0 :                 av_free(str);
     501           0 :                 return AVERROR_INVALIDDATA;
     502             :             }
     503             :         } else {
     504         168 :             int ret = ffio_read_size(pb, str, str_size);
     505         168 :             if (ret < 0) {
     506           0 :                 av_free(str);
     507           0 :                 return ret;
     508             :             }
     509         168 :             str[str_size] = 0;
     510             :         }
     511         191 :         c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
     512         191 :         av_dict_set(&c->fc->metadata, key, str, 0);
     513         191 :         if (*language && strcmp(language, "und")) {
     514          20 :             snprintf(key2, sizeof(key2), "%s-%s", key, language);
     515          20 :             av_dict_set(&c->fc->metadata, key2, str, 0);
     516             :         }
     517         191 :         if (!strcmp(key, "encoder")) {
     518             :             int major, minor, micro;
     519          80 :             if (sscanf(str, "HandBrake %d.%d.%d", &major, &minor, &micro) == 3) {
     520           0 :                 c->handbrake_version = 1000000*major + 1000*minor + micro;
     521             :             }
     522             :         }
     523             :     }
     524             : 
     525         223 :     av_freep(&str);
     526         223 :     return 0;
     527             : }
     528             : 
     529          10 : static int mov_read_chpl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
     530             : {
     531             :     int64_t start;
     532             :     int i, nb_chapters, str_len, version;
     533             :     char str[256+1];
     534             :     int ret;
     535             : 
     536          10 :     if (c->ignore_chapters)
     537           0 :         return 0;
     538             : 
     539          10 :     if ((atom.size -= 5) < 0)
     540           0 :         return 0;
     541             : 
     542          10 :     version = avio_r8(pb);
     543          10 :     avio_rb24(pb);
     544          10 :     if (version)
     545          10 :         avio_rb32(pb); // ???
     546          10 :     nb_chapters = avio_r8(pb);
     547             : 
     548          20 :     for (i = 0; i < nb_chapters; i++) {
     549          10 :         if (atom.size < 9)
     550           0 :             return 0;
     551             : 
     552          10 :         start = avio_rb64(pb);
     553          10 :         str_len = avio_r8(pb);
     554             : 
     555          10 :         if ((atom.size -= 9+str_len) < 0)
     556           0 :             return 0;
     557             : 
     558          10 :         ret = ffio_read_size(pb, str, str_len);
     559          10 :         if (ret < 0)
     560           0 :             return ret;
     561          10 :         str[str_len] = 0;
     562          10 :         avpriv_new_chapter(c->fc, i, (AVRational){1,10000000}, start, AV_NOPTS_VALUE, str);
     563             :     }
     564          10 :     return 0;
     565             : }
     566             : 
     567             : #define MIN_DATA_ENTRY_BOX_SIZE 12
     568         418 : static int mov_read_dref(MOVContext *c, AVIOContext *pb, MOVAtom atom)
     569             : {
     570             :     AVStream *st;
     571             :     MOVStreamContext *sc;
     572             :     int entries, i, j;
     573             : 
     574         418 :     if (c->fc->nb_streams < 1)
     575           0 :         return 0;
     576         418 :     st = c->fc->streams[c->fc->nb_streams-1];
     577         418 :     sc = st->priv_data;
     578             : 
     579         418 :     avio_rb32(pb); // version + flags
     580         418 :     entries = avio_rb32(pb);
     581         836 :     if (!entries ||
     582         836 :         entries >  (atom.size - 1) / MIN_DATA_ENTRY_BOX_SIZE + 1 ||
     583         418 :         entries >= UINT_MAX / sizeof(*sc->drefs))
     584           0 :         return AVERROR_INVALIDDATA;
     585         418 :     sc->drefs_count = 0;
     586         418 :     av_free(sc->drefs);
     587         418 :     sc->drefs_count = 0;
     588         418 :     sc->drefs = av_mallocz(entries * sizeof(*sc->drefs));
     589         418 :     if (!sc->drefs)
     590           0 :         return AVERROR(ENOMEM);
     591         418 :     sc->drefs_count = entries;
     592             : 
     593         836 :     for (i = 0; i < entries; i++) {
     594         418 :         MOVDref *dref = &sc->drefs[i];
     595         418 :         uint32_t size = avio_rb32(pb);
     596         418 :         int64_t next = avio_tell(pb) + size - 4;
     597             : 
     598         418 :         if (size < 12)
     599           0 :             return AVERROR_INVALIDDATA;
     600             : 
     601         418 :         dref->type = avio_rl32(pb);
     602         418 :         avio_rb32(pb); // version + flags
     603             : 
     604         418 :         if (dref->type == MKTAG('a','l','i','s') && size > 150) {
     605             :             /* macintosh alias record */
     606             :             uint16_t volume_len, len;
     607             :             int16_t type;
     608             :             int ret;
     609             : 
     610           0 :             avio_skip(pb, 10);
     611             : 
     612           0 :             volume_len = avio_r8(pb);
     613           0 :             volume_len = FFMIN(volume_len, 27);
     614           0 :             ret = ffio_read_size(pb, dref->volume, 27);
     615           0 :             if (ret < 0)
     616           0 :                 return ret;
     617           0 :             dref->volume[volume_len] = 0;
     618           0 :             av_log(c->fc, AV_LOG_DEBUG, "volume %s, len %d\n", dref->volume, volume_len);
     619             : 
     620           0 :             avio_skip(pb, 12);
     621             : 
     622           0 :             len = avio_r8(pb);
     623           0 :             len = FFMIN(len, 63);
     624           0 :             ret = ffio_read_size(pb, dref->filename, 63);
     625           0 :             if (ret < 0)
     626           0 :                 return ret;
     627           0 :             dref->filename[len] = 0;
     628           0 :             av_log(c->fc, AV_LOG_DEBUG, "filename %s, len %d\n", dref->filename, len);
     629             : 
     630           0 :             avio_skip(pb, 16);
     631             : 
     632             :             /* read next level up_from_alias/down_to_target */
     633           0 :             dref->nlvl_from = avio_rb16(pb);
     634           0 :             dref->nlvl_to   = avio_rb16(pb);
     635           0 :             av_log(c->fc, AV_LOG_DEBUG, "nlvl from %d, nlvl to %d\n",
     636           0 :                    dref->nlvl_from, dref->nlvl_to);
     637             : 
     638           0 :             avio_skip(pb, 16);
     639             : 
     640           0 :             for (type = 0; type != -1 && avio_tell(pb) < next; ) {
     641           0 :                 if(avio_feof(pb))
     642           0 :                     return AVERROR_EOF;
     643           0 :                 type = avio_rb16(pb);
     644           0 :                 len = avio_rb16(pb);
     645           0 :                 av_log(c->fc, AV_LOG_DEBUG, "type %d, len %d\n", type, len);
     646           0 :                 if (len&1)
     647           0 :                     len += 1;
     648           0 :                 if (type == 2) { // absolute path
     649           0 :                     av_free(dref->path);
     650           0 :                     dref->path = av_mallocz(len+1);
     651           0 :                     if (!dref->path)
     652           0 :                         return AVERROR(ENOMEM);
     653             : 
     654           0 :                     ret = ffio_read_size(pb, dref->path, len);
     655           0 :                     if (ret < 0) {
     656           0 :                         av_freep(&dref->path);
     657           0 :                         return ret;
     658             :                     }
     659           0 :                     if (len > volume_len && !strncmp(dref->path, dref->volume, volume_len)) {
     660           0 :                         len -= volume_len;
     661           0 :                         memmove(dref->path, dref->path+volume_len, len);
     662           0 :                         dref->path[len] = 0;
     663             :                     }
     664             :                     // trim string of any ending zeros
     665           0 :                     for (j = len - 1; j >= 0; j--) {
     666           0 :                         if (dref->path[j] == 0)
     667           0 :                             len--;
     668             :                         else
     669           0 :                             break;
     670             :                     }
     671           0 :                     for (j = 0; j < len; j++)
     672           0 :                         if (dref->path[j] == ':' || dref->path[j] == 0)
     673           0 :                             dref->path[j] = '/';
     674           0 :                     av_log(c->fc, AV_LOG_DEBUG, "path %s\n", dref->path);
     675           0 :                 } else if (type == 0) { // directory name
     676           0 :                     av_free(dref->dir);
     677           0 :                     dref->dir = av_malloc(len+1);
     678           0 :                     if (!dref->dir)
     679           0 :                         return AVERROR(ENOMEM);
     680             : 
     681           0 :                     ret = ffio_read_size(pb, dref->dir, len);
     682           0 :                     if (ret < 0) {
     683           0 :                         av_freep(&dref->dir);
     684           0 :                         return ret;
     685             :                     }
     686           0 :                     dref->dir[len] = 0;
     687           0 :                     for (j = 0; j < len; j++)
     688           0 :                         if (dref->dir[j] == ':')
     689           0 :                             dref->dir[j] = '/';
     690           0 :                     av_log(c->fc, AV_LOG_DEBUG, "dir %s\n", dref->dir);
     691             :                 } else
     692           0 :                     avio_skip(pb, len);
     693             :             }
     694             :         } else {
     695         418 :             av_log(c->fc, AV_LOG_DEBUG, "Unknown dref type 0x%08"PRIx32" size %"PRIu32"\n",
     696             :                    dref->type, size);
     697         418 :             entries--;
     698         418 :             i--;
     699             :         }
     700         418 :         avio_seek(pb, next, SEEK_SET);
     701             :     }
     702         418 :     return 0;
     703             : }
     704             : 
     705         744 : static int mov_read_hdlr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
     706             : {
     707             :     AVStream *st;
     708             :     uint32_t type;
     709             :     uint32_t ctype;
     710             :     int64_t title_size;
     711             :     char *title_str;
     712             :     int ret;
     713             : 
     714         744 :     avio_r8(pb); /* version */
     715         744 :     avio_rb24(pb); /* flags */
     716             : 
     717             :     /* component type */
     718         744 :     ctype = avio_rl32(pb);
     719         744 :     type = avio_rl32(pb); /* component subtype */
     720             : 
     721         744 :     av_log(c->fc, AV_LOG_TRACE, "ctype=%s\n", av_fourcc2str(ctype));
     722         744 :     av_log(c->fc, AV_LOG_TRACE, "stype=%s\n", av_fourcc2str(type));
     723             : 
     724         744 :     if (c->trak_index < 0) {  // meta not inside a trak
     725          71 :         if (type == MKTAG('m','d','t','a')) {
     726           5 :             c->found_hdlr_mdta = 1;
     727             :         }
     728          71 :         return 0;
     729             :     }
     730             : 
     731         673 :     st = c->fc->streams[c->fc->nb_streams-1];
     732             : 
     733         673 :     if     (type == MKTAG('v','i','d','e'))
     734         203 :         st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
     735         470 :     else if (type == MKTAG('s','o','u','n'))
     736         185 :         st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
     737         285 :     else if (type == MKTAG('m','1','a',' '))
     738           0 :         st->codecpar->codec_id = AV_CODEC_ID_MP2;
     739         285 :     else if ((type == MKTAG('s','u','b','p')) || (type == MKTAG('c','l','c','p')))
     740           0 :         st->codecpar->codec_type = AVMEDIA_TYPE_SUBTITLE;
     741             : 
     742         673 :     avio_rb32(pb); /* component  manufacture */
     743         673 :     avio_rb32(pb); /* component flags */
     744         673 :     avio_rb32(pb); /* component flags mask */
     745             : 
     746         673 :     title_size = atom.size - 24;
     747         673 :     if (title_size > 0) {
     748         670 :         if (title_size > FFMIN(INT_MAX, SIZE_MAX-1))
     749           0 :             return AVERROR_INVALIDDATA;
     750         670 :         title_str = av_malloc(title_size + 1); /* Add null terminator */
     751         670 :         if (!title_str)
     752           0 :             return AVERROR(ENOMEM);
     753             : 
     754         670 :         ret = ffio_read_size(pb, title_str, title_size);
     755         670 :         if (ret < 0) {
     756           0 :             av_freep(&title_str);
     757           0 :             return ret;
     758             :         }
     759         670 :         title_str[title_size] = 0;
     760         670 :         if (title_str[0]) {
     761         629 :             int off = (!c->isom && title_str[0] == title_size - 1);
     762         629 :             av_dict_set(&st->metadata, "handler_name", title_str + off, 0);
     763             :         }
     764         670 :         av_freep(&title_str);
     765             :     }
     766             : 
     767         673 :     return 0;
     768             : }
     769             : 
     770         126 : static int mov_read_esds(MOVContext *c, AVIOContext *pb, MOVAtom atom)
     771             : {
     772         126 :     return ff_mov_read_esds(c->fc, pb);
     773             : }
     774             : 
     775           0 : static int mov_read_dac3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
     776             : {
     777             :     AVStream *st;
     778             :     enum AVAudioServiceType *ast;
     779             :     int ac3info, acmod, lfeon, bsmod;
     780             : 
     781           0 :     if (c->fc->nb_streams < 1)
     782           0 :         return 0;
     783           0 :     st = c->fc->streams[c->fc->nb_streams-1];
     784             : 
     785           0 :     ast = (enum AVAudioServiceType*)av_stream_new_side_data(st, AV_PKT_DATA_AUDIO_SERVICE_TYPE,
     786             :                                                             sizeof(*ast));
     787           0 :     if (!ast)
     788           0 :         return AVERROR(ENOMEM);
     789             : 
     790           0 :     ac3info = avio_rb24(pb);
     791           0 :     bsmod = (ac3info >> 14) & 0x7;
     792           0 :     acmod = (ac3info >> 11) & 0x7;
     793           0 :     lfeon = (ac3info >> 10) & 0x1;
     794           0 :     st->codecpar->channels = ((int[]){2,1,2,3,3,4,4,5})[acmod] + lfeon;
     795           0 :     st->codecpar->channel_layout = avpriv_ac3_channel_layout_tab[acmod];
     796           0 :     if (lfeon)
     797           0 :         st->codecpar->channel_layout |= AV_CH_LOW_FREQUENCY;
     798           0 :     *ast = bsmod;
     799           0 :     if (st->codecpar->channels > 1 && bsmod == 0x7)
     800           0 :         *ast = AV_AUDIO_SERVICE_TYPE_KARAOKE;
     801             : 
     802             : #if FF_API_LAVF_AVCTX
     803             :     FF_DISABLE_DEPRECATION_WARNINGS
     804           0 :     st->codec->audio_service_type = *ast;
     805             :     FF_ENABLE_DEPRECATION_WARNINGS
     806             : #endif
     807             : 
     808           0 :     return 0;
     809             : }
     810             : 
     811           1 : static int mov_read_dec3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
     812             : {
     813             :     AVStream *st;
     814             :     enum AVAudioServiceType *ast;
     815             :     int eac3info, acmod, lfeon, bsmod;
     816             : 
     817           1 :     if (c->fc->nb_streams < 1)
     818           0 :         return 0;
     819           1 :     st = c->fc->streams[c->fc->nb_streams-1];
     820             : 
     821           1 :     ast = (enum AVAudioServiceType*)av_stream_new_side_data(st, AV_PKT_DATA_AUDIO_SERVICE_TYPE,
     822             :                                                             sizeof(*ast));
     823           1 :     if (!ast)
     824           0 :         return AVERROR(ENOMEM);
     825             : 
     826             :     /* No need to parse fields for additional independent substreams and its
     827             :      * associated dependent substreams since libavcodec's E-AC-3 decoder
     828             :      * does not support them yet. */
     829           1 :     avio_rb16(pb); /* data_rate and num_ind_sub */
     830           1 :     eac3info = avio_rb24(pb);
     831           1 :     bsmod = (eac3info >> 12) & 0x1f;
     832           1 :     acmod = (eac3info >>  9) & 0x7;
     833           1 :     lfeon = (eac3info >>  8) & 0x1;
     834           1 :     st->codecpar->channel_layout = avpriv_ac3_channel_layout_tab[acmod];
     835           1 :     if (lfeon)
     836           0 :         st->codecpar->channel_layout |= AV_CH_LOW_FREQUENCY;
     837           1 :     st->codecpar->channels = av_get_channel_layout_nb_channels(st->codecpar->channel_layout);
     838           1 :     *ast = bsmod;
     839           1 :     if (st->codecpar->channels > 1 && bsmod == 0x7)
     840           0 :         *ast = AV_AUDIO_SERVICE_TYPE_KARAOKE;
     841             : 
     842             : #if FF_API_LAVF_AVCTX
     843             :     FF_DISABLE_DEPRECATION_WARNINGS
     844           1 :     st->codec->audio_service_type = *ast;
     845             :     FF_ENABLE_DEPRECATION_WARNINGS
     846             : #endif
     847             : 
     848           1 :     return 0;
     849             : }
     850             : 
     851           0 : static int mov_read_ddts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
     852             : {
     853           0 :     const uint32_t ddts_size = 20;
     854           0 :     AVStream *st = NULL;
     855           0 :     uint8_t *buf = NULL;
     856           0 :     uint32_t frame_duration_code = 0;
     857           0 :     uint32_t channel_layout_code = 0;
     858             :     GetBitContext gb;
     859             : 
     860           0 :     buf = av_malloc(ddts_size + AV_INPUT_BUFFER_PADDING_SIZE);
     861           0 :     if (!buf) {
     862           0 :         return AVERROR(ENOMEM);
     863             :     }
     864           0 :     if (avio_read(pb, buf, ddts_size) < ddts_size) {
     865           0 :         av_free(buf);
     866           0 :         return AVERROR_INVALIDDATA;
     867             :     }
     868             : 
     869           0 :     init_get_bits(&gb, buf, 8*ddts_size);
     870             : 
     871           0 :     if (c->fc->nb_streams < 1) {
     872           0 :         av_free(buf);
     873           0 :         return 0;
     874             :     }
     875           0 :     st = c->fc->streams[c->fc->nb_streams-1];
     876             : 
     877           0 :     st->codecpar->sample_rate = get_bits_long(&gb, 32);
     878           0 :     if (st->codecpar->sample_rate <= 0) {
     879           0 :         av_log(c->fc, AV_LOG_ERROR, "Invalid sample rate %d\n", st->codecpar->sample_rate);
     880           0 :         av_free(buf);
     881           0 :         return AVERROR_INVALIDDATA;
     882             :     }
     883           0 :     skip_bits_long(&gb, 32); /* max bitrate */
     884           0 :     st->codecpar->bit_rate = get_bits_long(&gb, 32);
     885           0 :     st->codecpar->bits_per_coded_sample = get_bits(&gb, 8);
     886           0 :     frame_duration_code = get_bits(&gb, 2);
     887           0 :     skip_bits(&gb, 30); /* various fields */
     888           0 :     channel_layout_code = get_bits(&gb, 16);
     889             : 
     890           0 :     st->codecpar->frame_size =
     891           0 :             (frame_duration_code == 0) ? 512 :
     892           0 :             (frame_duration_code == 1) ? 1024 :
     893           0 :             (frame_duration_code == 2) ? 2048 :
     894           0 :             (frame_duration_code == 3) ? 4096 : 0;
     895             : 
     896           0 :     if (channel_layout_code > 0xff) {
     897           0 :         av_log(c->fc, AV_LOG_WARNING, "Unsupported DTS audio channel layout");
     898             :     }
     899           0 :     st->codecpar->channel_layout =
     900           0 :             ((channel_layout_code & 0x1) ? AV_CH_FRONT_CENTER : 0) |
     901           0 :             ((channel_layout_code & 0x2) ? AV_CH_FRONT_LEFT : 0) |
     902           0 :             ((channel_layout_code & 0x2) ? AV_CH_FRONT_RIGHT : 0) |
     903           0 :             ((channel_layout_code & 0x4) ? AV_CH_SIDE_LEFT : 0) |
     904           0 :             ((channel_layout_code & 0x4) ? AV_CH_SIDE_RIGHT : 0) |
     905           0 :             ((channel_layout_code & 0x8) ? AV_CH_LOW_FREQUENCY : 0);
     906             : 
     907           0 :     st->codecpar->channels = av_get_channel_layout_nb_channels(st->codecpar->channel_layout);
     908           0 :     av_free(buf);
     909             : 
     910           0 :     return 0;
     911             : }
     912             : 
     913          34 : static int mov_read_chan(MOVContext *c, AVIOContext *pb, MOVAtom atom)
     914             : {
     915             :     AVStream *st;
     916             : 
     917          34 :     if (c->fc->nb_streams < 1)
     918           0 :         return 0;
     919          34 :     st = c->fc->streams[c->fc->nb_streams-1];
     920             : 
     921          34 :     if (atom.size < 16)
     922           0 :         return 0;
     923             : 
     924             :     /* skip version and flags */
     925          34 :     avio_skip(pb, 4);
     926             : 
     927          34 :     ff_mov_read_chan(c->fc, pb, st, atom.size - 4);
     928             : 
     929          34 :     return 0;
     930             : }
     931             : 
     932           2 : static int mov_read_wfex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
     933             : {
     934             :     AVStream *st;
     935             :     int ret;
     936             : 
     937           2 :     if (c->fc->nb_streams < 1)
     938           0 :         return 0;
     939           2 :     st = c->fc->streams[c->fc->nb_streams-1];
     940             : 
     941           2 :     if ((ret = ff_get_wav_header(c->fc, pb, st->codecpar, atom.size, 0)) < 0)
     942           0 :         av_log(c->fc, AV_LOG_WARNING, "get_wav_header failed\n");
     943             : 
     944           2 :     return ret;
     945             : }
     946             : 
     947          32 : static int mov_read_pasp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
     948             : {
     949          32 :     const int num = avio_rb32(pb);
     950          32 :     const int den = avio_rb32(pb);
     951             :     AVStream *st;
     952             : 
     953          32 :     if (c->fc->nb_streams < 1)
     954           0 :         return 0;
     955          32 :     st = c->fc->streams[c->fc->nb_streams-1];
     956             : 
     957          34 :     if ((st->sample_aspect_ratio.den != 1 || st->sample_aspect_ratio.num) && // default
     958           4 :         (den != st->sample_aspect_ratio.den || num != st->sample_aspect_ratio.num)) {
     959           0 :         av_log(c->fc, AV_LOG_WARNING,
     960             :                "sample aspect ratio already set to %d:%d, ignoring 'pasp' atom (%d:%d)\n",
     961             :                st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
     962             :                num, den);
     963          32 :     } else if (den != 0) {
     964          30 :         av_reduce(&st->sample_aspect_ratio.num, &st->sample_aspect_ratio.den,
     965             :                   num, den, 32767);
     966             :     }
     967          32 :     return 0;
     968             : }
     969             : 
     970             : /* this atom contains actual media data */
     971         731 : static int mov_read_mdat(MOVContext *c, AVIOContext *pb, MOVAtom atom)
     972             : {
     973         731 :     if (atom.size == 0) /* wrong one (MP4) */
     974           0 :         return 0;
     975         731 :     c->found_mdat=1;
     976         731 :     return 0; /* now go for moov */
     977             : }
     978             : 
     979             : #define DRM_BLOB_SIZE 56
     980             : 
     981           0 : static int mov_read_adrm(MOVContext *c, AVIOContext *pb, MOVAtom atom)
     982             : {
     983             :     uint8_t intermediate_key[20];
     984             :     uint8_t intermediate_iv[20];
     985             :     uint8_t input[64];
     986             :     uint8_t output[64];
     987             :     uint8_t file_checksum[20];
     988             :     uint8_t calculated_checksum[20];
     989             :     struct AVSHA *sha;
     990             :     int i;
     991           0 :     int ret = 0;
     992           0 :     uint8_t *activation_bytes = c->activation_bytes;
     993           0 :     uint8_t *fixed_key = c->audible_fixed_key;
     994             : 
     995           0 :     c->aax_mode = 1;
     996             : 
     997           0 :     sha = av_sha_alloc();
     998           0 :     if (!sha)
     999           0 :         return AVERROR(ENOMEM);
    1000           0 :     c->aes_decrypt = av_aes_alloc();
    1001           0 :     if (!c->aes_decrypt) {
    1002           0 :         ret = AVERROR(ENOMEM);
    1003           0 :         goto fail;
    1004             :     }
    1005             : 
    1006             :     /* drm blob processing */
    1007           0 :     avio_read(pb, output, 8); // go to offset 8, absolute position 0x251
    1008           0 :     avio_read(pb, input, DRM_BLOB_SIZE);
    1009           0 :     avio_read(pb, output, 4); // go to offset 4, absolute position 0x28d
    1010           0 :     avio_read(pb, file_checksum, 20);
    1011             : 
    1012           0 :     av_log(c->fc, AV_LOG_INFO, "[aax] file checksum == "); // required by external tools
    1013           0 :     for (i = 0; i < 20; i++)
    1014           0 :         av_log(c->fc, AV_LOG_INFO, "%02x", file_checksum[i]);
    1015           0 :     av_log(c->fc, AV_LOG_INFO, "\n");
    1016             : 
    1017             :     /* verify activation data */
    1018           0 :     if (!activation_bytes) {
    1019           0 :         av_log(c->fc, AV_LOG_WARNING, "[aax] activation_bytes option is missing!\n");
    1020           0 :         ret = 0;  /* allow ffprobe to continue working on .aax files */
    1021           0 :         goto fail;
    1022             :     }
    1023           0 :     if (c->activation_bytes_size != 4) {
    1024           0 :         av_log(c->fc, AV_LOG_FATAL, "[aax] activation_bytes value needs to be 4 bytes!\n");
    1025           0 :         ret = AVERROR(EINVAL);
    1026           0 :         goto fail;
    1027             :     }
    1028             : 
    1029             :     /* verify fixed key */
    1030           0 :     if (c->audible_fixed_key_size != 16) {
    1031           0 :         av_log(c->fc, AV_LOG_FATAL, "[aax] audible_fixed_key value needs to be 16 bytes!\n");
    1032           0 :         ret = AVERROR(EINVAL);
    1033           0 :         goto fail;
    1034             :     }
    1035             : 
    1036             :     /* AAX (and AAX+) key derivation */
    1037           0 :     av_sha_init(sha, 160);
    1038           0 :     av_sha_update(sha, fixed_key, 16);
    1039           0 :     av_sha_update(sha, activation_bytes, 4);
    1040           0 :     av_sha_final(sha, intermediate_key);
    1041           0 :     av_sha_init(sha, 160);
    1042           0 :     av_sha_update(sha, fixed_key, 16);
    1043           0 :     av_sha_update(sha, intermediate_key, 20);
    1044           0 :     av_sha_update(sha, activation_bytes, 4);
    1045           0 :     av_sha_final(sha, intermediate_iv);
    1046           0 :     av_sha_init(sha, 160);
    1047           0 :     av_sha_update(sha, intermediate_key, 16);
    1048           0 :     av_sha_update(sha, intermediate_iv, 16);
    1049           0 :     av_sha_final(sha, calculated_checksum);
    1050           0 :     if (memcmp(calculated_checksum, file_checksum, 20)) { // critical error
    1051           0 :         av_log(c->fc, AV_LOG_ERROR, "[aax] mismatch in checksums!\n");
    1052           0 :         ret = AVERROR_INVALIDDATA;
    1053           0 :         goto fail;
    1054             :     }
    1055           0 :     av_aes_init(c->aes_decrypt, intermediate_key, 128, 1);
    1056           0 :     av_aes_crypt(c->aes_decrypt, output, input, DRM_BLOB_SIZE >> 4, intermediate_iv, 1);
    1057           0 :     for (i = 0; i < 4; i++) {
    1058             :         // file data (in output) is stored in big-endian mode
    1059           0 :         if (activation_bytes[i] != output[3 - i]) { // critical error
    1060           0 :             av_log(c->fc, AV_LOG_ERROR, "[aax] error in drm blob decryption!\n");
    1061           0 :             ret = AVERROR_INVALIDDATA;
    1062           0 :             goto fail;
    1063             :         }
    1064             :     }
    1065           0 :     memcpy(c->file_key, output + 8, 16);
    1066           0 :     memcpy(input, output + 26, 16);
    1067           0 :     av_sha_init(sha, 160);
    1068           0 :     av_sha_update(sha, input, 16);
    1069           0 :     av_sha_update(sha, c->file_key, 16);
    1070           0 :     av_sha_update(sha, fixed_key, 16);
    1071           0 :     av_sha_final(sha, c->file_iv);
    1072             : 
    1073           0 : fail:
    1074           0 :     av_free(sha);
    1075             : 
    1076           0 :     return ret;
    1077             : }
    1078             : 
    1079             : // Audible AAX (and AAX+) bytestream decryption
    1080           0 : static int aax_filter(uint8_t *input, int size, MOVContext *c)
    1081             : {
    1082           0 :     int blocks = 0;
    1083             :     unsigned char iv[16];
    1084             : 
    1085           0 :     memcpy(iv, c->file_iv, 16); // iv is overwritten
    1086           0 :     blocks = size >> 4; // trailing bytes are not encrypted!
    1087           0 :     av_aes_init(c->aes_decrypt, c->file_key, 128, 1);
    1088           0 :     av_aes_crypt(c->aes_decrypt, input, input, blocks, iv, 1);
    1089             : 
    1090           0 :     return 0;
    1091             : }
    1092             : 
    1093             : /* read major brand, minor version and compatible brands and store them as metadata */
    1094         318 : static int mov_read_ftyp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
    1095             : {
    1096             :     uint32_t minor_ver;
    1097             :     int comp_brand_size;
    1098             :     char* comp_brands_str;
    1099         318 :     uint8_t type[5] = {0};
    1100         318 :     int ret = ffio_read_size(pb, type, 4);
    1101         318 :     if (ret < 0)
    1102           0 :         return ret;
    1103             : 
    1104         318 :     if (strcmp(type, "qt  "))
    1105         147 :         c->isom = 1;
    1106         318 :     av_log(c->fc, AV_LOG_DEBUG, "ISO: File Type Major Brand: %.4s\n",(char *)&type);
    1107         318 :     av_dict_set(&c->fc->metadata, "major_brand", type, 0);
    1108         318 :     minor_ver = avio_rb32(pb); /* minor version */
    1109         318 :     av_dict_set_int(&c->fc->metadata, "minor_version", minor_ver, 0);
    1110             : 
    1111         318 :     comp_brand_size = atom.size - 8;
    1112         318 :     if (comp_brand_size < 0)
    1113           0 :         return AVERROR_INVALIDDATA;
    1114         318 :     comp_brands_str = av_malloc(comp_brand_size + 1); /* Add null terminator */
    1115         318 :     if (!comp_brands_str)
    1116           0 :         return AVERROR(ENOMEM);
    1117             : 
    1118         318 :     ret = ffio_read_size(pb, comp_brands_str, comp_brand_size);
    1119         318 :     if (ret < 0) {
    1120           0 :         av_freep(&comp_brands_str);
    1121           0 :         return ret;
    1122             :     }
    1123         318 :     comp_brands_str[comp_brand_size] = 0;
    1124         318 :     av_dict_set(&c->fc->metadata, "compatible_brands", comp_brands_str, 0);
    1125         318 :     av_freep(&comp_brands_str);
    1126             : 
    1127         318 :     return 0;
    1128             : }
    1129             : 
    1130             : /* this atom should contain all header atoms */
    1131         356 : static int mov_read_moov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
    1132             : {
    1133             :     int ret;
    1134             : 
    1135         356 :     if (c->found_moov) {
    1136           0 :         av_log(c->fc, AV_LOG_WARNING, "Found duplicated MOOV Atom. Skipped it\n");
    1137           0 :         avio_skip(pb, atom.size);
    1138           0 :         return 0;
    1139             :     }
    1140             : 
    1141         356 :     if ((ret = mov_read_default(c, pb, atom)) < 0)
    1142           0 :         return ret;
    1143             :     /* we parsed the 'moov' atom, we can terminate the parsing as soon as we find the 'mdat' */
    1144             :     /* so we don't parse the whole file if over a network */
    1145         356 :     c->found_moov=1;
    1146         356 :     return 0; /* now go for mdat */
    1147             : }
    1148             : 
    1149        2202 : static MOVFragmentStreamInfo * get_frag_stream_info(
    1150             :     MOVFragmentIndex *frag_index,
    1151             :     int index,
    1152             :     int id)
    1153             : {
    1154             :     int i;
    1155             :     MOVFragmentIndexItem * item;
    1156             : 
    1157        2202 :     if (index < 0 || index >= frag_index->nb_items)
    1158           0 :         return NULL;
    1159        2202 :     item = &frag_index->item[index];
    1160        2202 :     for (i = 0; i < item->nb_stream_info; i++)
    1161        2202 :         if (item->stream_info[i].id == id)
    1162        2202 :             return &item->stream_info[i];
    1163             : 
    1164             :     // This shouldn't happen
    1165           0 :     return NULL;
    1166             : }
    1167             : 
    1168         381 : static void set_frag_stream(MOVFragmentIndex *frag_index, int id)
    1169             : {
    1170             :     int i;
    1171             :     MOVFragmentIndexItem * item;
    1172             : 
    1173         762 :     if (frag_index->current < 0 ||
    1174         381 :         frag_index->current >= frag_index->nb_items)
    1175           0 :         return;
    1176             : 
    1177         381 :     item = &frag_index->item[frag_index->current];
    1178         385 :     for (i = 0; i < item->nb_stream_info; i++)
    1179         385 :         if (item->stream_info[i].id == id) {
    1180         381 :             item->current = i;
    1181         381 :             return;
    1182             :         }
    1183             : 
    1184             :     // id not found.  This shouldn't happen.
    1185           0 :     item->current = -1;
    1186             : }
    1187             : 
    1188         743 : static MOVFragmentStreamInfo * get_current_frag_stream_info(
    1189             :     MOVFragmentIndex *frag_index)
    1190             : {
    1191             :     MOVFragmentIndexItem *item;
    1192        1486 :     if (frag_index->current < 0 ||
    1193         743 :         frag_index->current >= frag_index->nb_items)
    1194           0 :         return NULL;
    1195             : 
    1196         743 :     item = &frag_index->item[frag_index->current];
    1197         743 :     if (item->current >= 0 && item->current < item->nb_stream_info)
    1198         743 :         return &item->stream_info[item->current];
    1199             : 
    1200             :     // This shouldn't happen
    1201           0 :     return NULL;
    1202             : }
    1203             : 
    1204         781 : static int search_frag_moof_offset(MOVFragmentIndex *frag_index, int64_t offset)
    1205             : {
    1206             :     int a, b, m;
    1207             :     int64_t moof_offset;
    1208             : 
    1209             :     // Optimize for appending new entries
    1210        1555 :     if (!frag_index->nb_items ||
    1211         774 :         frag_index->item[frag_index->nb_items - 1].moof_offset < offset)
    1212         383 :         return frag_index->nb_items;
    1213             : 
    1214         398 :     a = -1;
    1215         398 :     b = frag_index->nb_items;
    1216             : 
    1217        3440 :     while (b - a > 1) {
    1218        2644 :         m = (a + b) >> 1;
    1219        2644 :         moof_offset = frag_index->item[m].moof_offset;
    1220        2644 :         if (moof_offset >= offset)
    1221         725 :             b = m;
    1222        2644 :         if (moof_offset <= offset)
    1223        2317 :             a = m;
    1224             :     }
    1225         398 :     return b;
    1226             : }
    1227             : 
    1228           0 : static int64_t get_stream_info_time(MOVFragmentStreamInfo * frag_stream_info)
    1229             : {
    1230             : 
    1231           0 :     if (frag_stream_info) {
    1232           0 :         if (frag_stream_info->sidx_pts != AV_NOPTS_VALUE)
    1233           0 :             return frag_stream_info->sidx_pts;
    1234           0 :         if (frag_stream_info->first_tfra_pts != AV_NOPTS_VALUE)
    1235           0 :             return frag_stream_info->first_tfra_pts;
    1236           0 :         if (frag_stream_info->tfdt_dts != AV_NOPTS_VALUE)
    1237           0 :             return frag_stream_info->tfdt_dts;
    1238             :     }
    1239           0 :     return AV_NOPTS_VALUE;
    1240             : }
    1241             : 
    1242         219 : static int64_t get_frag_time(MOVFragmentIndex *frag_index,
    1243             :                              int index, int track_id)
    1244             : {
    1245             :     MOVFragmentStreamInfo * frag_stream_info;
    1246             :     int64_t timestamp;
    1247             :     int i;
    1248             : 
    1249         219 :     if (track_id >= 0) {
    1250         219 :         frag_stream_info = get_frag_stream_info(frag_index, index, track_id);
    1251         219 :         return frag_stream_info->sidx_pts;
    1252             :     }
    1253             : 
    1254           0 :     for (i = 0; i < frag_index->item[index].nb_stream_info; i++) {
    1255           0 :         frag_stream_info = &frag_index->item[index].stream_info[i];
    1256           0 :         timestamp = get_stream_info_time(frag_stream_info);
    1257           0 :         if (timestamp != AV_NOPTS_VALUE)
    1258           0 :             return timestamp;
    1259             :     }
    1260           0 :     return AV_NOPTS_VALUE;
    1261             : }
    1262             : 
    1263          26 : static int search_frag_timestamp(MOVFragmentIndex *frag_index,
    1264             :                                  AVStream *st, int64_t timestamp)
    1265             : {
    1266             :     int a, b, m;
    1267             :     int64_t frag_time;
    1268          26 :     int id = -1;
    1269             : 
    1270          26 :     if (st) {
    1271             :         // If the stream is referenced by any sidx, limit the search
    1272             :         // to fragments that referenced this stream in the sidx
    1273          26 :         MOVStreamContext *sc = st->priv_data;
    1274          26 :         if (sc->has_sidx)
    1275          26 :             id = st->id;
    1276             :     }
    1277             : 
    1278          26 :     a = -1;
    1279          26 :     b = frag_index->nb_items;
    1280             : 
    1281         271 :     while (b - a > 1) {
    1282         219 :         m = (a + b) >> 1;
    1283         219 :         frag_time = get_frag_time(frag_index, m, id);
    1284         219 :         if (frag_time != AV_NOPTS_VALUE) {
    1285         219 :             if (frag_time >= timestamp)
    1286         126 :                 b = m;
    1287         219 :             if (frag_time <= timestamp)
    1288          93 :                 a = m;
    1289             :         }
    1290             :     }
    1291          26 :     return a;
    1292             : }
    1293             : 
    1294         744 : static int update_frag_index(MOVContext *c, int64_t offset)
    1295             : {
    1296             :     int index, i;
    1297             :     MOVFragmentIndexItem * item;
    1298             :     MOVFragmentStreamInfo * frag_stream_info;
    1299             : 
    1300             :     // If moof_offset already exists in frag_index, return index to it
    1301         744 :     index = search_frag_moof_offset(&c->frag_index, offset);
    1302        1106 :     if (index < c->frag_index.nb_items &&
    1303         362 :         c->frag_index.item[index].moof_offset == offset)
    1304         362 :         return index;
    1305             : 
    1306             :     // offset is not yet in frag index.
    1307             :     // Insert new item at index (sorted by moof offset)
    1308         764 :     item = av_fast_realloc(c->frag_index.item,
    1309         382 :                            &c->frag_index.allocated_size,
    1310         382 :                            (c->frag_index.nb_items + 1) *
    1311             :                            sizeof(*c->frag_index.item));
    1312         382 :     if(!item)
    1313           0 :         return -1;
    1314         382 :     c->frag_index.item = item;
    1315             : 
    1316         382 :     frag_stream_info = av_realloc_array(NULL, c->fc->nb_streams,
    1317             :                                         sizeof(*item->stream_info));
    1318         382 :     if (!frag_stream_info)
    1319           0 :         return -1;
    1320             : 
    1321         774 :     for (i = 0; i < c->fc->nb_streams; i++) {
    1322         392 :         frag_stream_info[i].id = c->fc->streams[i]->id;
    1323         392 :         frag_stream_info[i].sidx_pts = AV_NOPTS_VALUE;
    1324         392 :         frag_stream_info[i].tfdt_dts = AV_NOPTS_VALUE;
    1325         392 :         frag_stream_info[i].first_tfra_pts = AV_NOPTS_VALUE;
    1326         392 :         frag_stream_info[i].index_entry = -1;
    1327             :     }
    1328             : 
    1329         382 :     if (index < c->frag_index.nb_items)
    1330           0 :         memmove(c->frag_index.item + index + 1, c->frag_index.item + index,
    1331           0 :                 (c->frag_index.nb_items - index) * sizeof(*c->frag_index.item));
    1332             : 
    1333         382 :     item = &c->frag_index.item[index];
    1334         382 :     item->headers_read = 0;
    1335         382 :     item->current = 0;
    1336         382 :     item->nb_stream_info = c->fc->nb_streams;
    1337         382 :     item->moof_offset = offset;
    1338         382 :     item->stream_info = frag_stream_info;
    1339         382 :     c->frag_index.nb_items++;
    1340             : 
    1341         382 :     return index;
    1342             : }
    1343             : 
    1344         381 : static void fix_frag_index_entries(MOVFragmentIndex *frag_index, int index,
    1345             :                                    int id, int entries)
    1346             : {
    1347             :     int i;
    1348             :     MOVFragmentStreamInfo * frag_stream_info;
    1349             : 
    1350         381 :     if (index < 0)
    1351         381 :         return;
    1352           0 :     for (i = index; i < frag_index->nb_items; i++) {
    1353           0 :         frag_stream_info = get_frag_stream_info(frag_index, i, id);
    1354           0 :         if (frag_stream_info && frag_stream_info->index_entry >= 0)
    1355           0 :             frag_stream_info->index_entry += entries;
    1356             :     }
    1357             : }
    1358             : 
    1359         381 : static int mov_read_moof(MOVContext *c, AVIOContext *pb, MOVAtom atom)
    1360             : {
    1361         381 :     if (!c->has_looked_for_mfra && c->use_mfra_for > 0) {
    1362           0 :         c->has_looked_for_mfra = 1;
    1363           0 :         if (pb->seekable & AVIO_SEEKABLE_NORMAL) {
    1364             :             int ret;
    1365           0 :             av_log(c->fc, AV_LOG_VERBOSE, "stream has moof boxes, will look "
    1366             :                     "for a mfra\n");
    1367           0 :             if ((ret = mov_read_mfra(c, pb)) < 0) {
    1368           0 :                 av_log(c->fc, AV_LOG_VERBOSE, "found a moof box but failed to "
    1369             :                         "read the mfra (may be a live ismv)\n");
    1370             :             }
    1371             :         } else {
    1372           0 :             av_log(c->fc, AV_LOG_VERBOSE, "found a moof box but stream is not "
    1373             :                     "seekable, can not look for mfra\n");
    1374             :         }
    1375             :     }
    1376         381 :     c->fragment.moof_offset = c->fragment.implicit_offset = avio_tell(pb) - 8;
    1377         381 :     av_log(c->fc, AV_LOG_TRACE, "moof offset %"PRIx64"\n", c->fragment.moof_offset);
    1378         381 :     c->frag_index.current = update_frag_index(c, c->fragment.moof_offset);
    1379         381 :     return mov_read_default(c, pb, atom);
    1380             : }
    1381             : 
    1382         772 : static void mov_metadata_creation_time(AVDictionary **metadata, int64_t time)
    1383             : {
    1384         772 :     if (time) {
    1385         429 :         if(time >= 2082844800)
    1386         393 :             time -= 2082844800;  /* seconds between 1904-01-01 and Epoch */
    1387             : 
    1388         429 :         if ((int64_t)(time * 1000000ULL) / 1000000 != time) {
    1389           0 :             av_log(NULL, AV_LOG_DEBUG, "creation_time is not representable\n");
    1390           0 :             return;
    1391             :         }
    1392             : 
    1393         429 :         avpriv_dict_set_timestamp(metadata, "creation_time", time * 1000000);
    1394             :     }
    1395             : }
    1396             : 
    1397         418 : static int mov_read_mdhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
    1398             : {
    1399             :     AVStream *st;
    1400             :     MOVStreamContext *sc;
    1401             :     int version;
    1402         418 :     char language[4] = {0};
    1403             :     unsigned lang;
    1404             :     int64_t creation_time;
    1405             : 
    1406         418 :     if (c->fc->nb_streams < 1)
    1407           0 :         return 0;
    1408         418 :     st = c->fc->streams[c->fc->nb_streams-1];
    1409         418 :     sc = st->priv_data;
    1410             : 
    1411         418 :     if (sc->time_scale) {
    1412           0 :         av_log(c->fc, AV_LOG_ERROR, "Multiple mdhd?\n");
    1413           0 :         return AVERROR_INVALIDDATA;
    1414             :     }
    1415             : 
    1416         418 :     version = avio_r8(pb);
    1417         418 :     if (version > 1) {
    1418           0 :         avpriv_request_sample(c->fc, "Version %d", version);
    1419           0 :         return AVERROR_PATCHWELCOME;
    1420             :     }
    1421         418 :     avio_rb24(pb); /* flags */
    1422         418 :     if (version == 1) {
    1423           7 :         creation_time = avio_rb64(pb);
    1424           7 :         avio_rb64(pb);
    1425             :     } else {
    1426         411 :         creation_time = avio_rb32(pb);
    1427         411 :         avio_rb32(pb); /* modification time */
    1428             :     }
    1429         418 :     mov_metadata_creation_time(&st->metadata, creation_time);
    1430             : 
    1431         418 :     sc->time_scale = avio_rb32(pb);
    1432         418 :     if (sc->time_scale <= 0) {
    1433           0 :         av_log(c->fc, AV_LOG_ERROR, "Invalid mdhd time scale %d, defaulting to 1\n", sc->time_scale);
    1434           0 :         sc->time_scale = 1;
    1435             :     }
    1436         418 :     st->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
    1437             : 
    1438         418 :     lang = avio_rb16(pb); /* language */
    1439         418 :     if (ff_mov_lang_to_iso639(lang, language))
    1440         418 :         av_dict_set(&st->metadata, "language", language, 0);
    1441         418 :     avio_rb16(pb); /* quality */
    1442             : 
    1443         418 :     return 0;
    1444             : }
    1445             : 
    1446         354 : static int mov_read_mvhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
    1447             : {
    1448             :     int i;
    1449             :     int64_t creation_time;
    1450         354 :     int version = avio_r8(pb); /* version */
    1451         354 :     avio_rb24(pb); /* flags */
    1452             : 
    1453         354 :     if (version == 1) {
    1454           2 :         creation_time = avio_rb64(pb);
    1455           2 :         avio_rb64(pb);
    1456             :     } else {
    1457         352 :         creation_time = avio_rb32(pb);
    1458         352 :         avio_rb32(pb); /* modification time */
    1459             :     }
    1460         354 :     mov_metadata_creation_time(&c->fc->metadata, creation_time);
    1461         354 :     c->time_scale = avio_rb32(pb); /* time scale */
    1462         354 :     if (c->time_scale <= 0) {
    1463           0 :         av_log(c->fc, AV_LOG_ERROR, "Invalid mvhd time scale %d, defaulting to 1\n", c->time_scale);
    1464           0 :         c->time_scale = 1;
    1465             :     }
    1466         354 :     av_log(c->fc, AV_LOG_TRACE, "time scale = %i\n", c->time_scale);
    1467             : 
    1468         354 :     c->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
    1469             :     // set the AVCodecContext duration because the duration of individual tracks
    1470             :     // may be inaccurate
    1471         354 :     if (c->time_scale > 0 && !c->trex_data)
    1472         354 :         c->fc->duration = av_rescale(c->duration, AV_TIME_BASE, c->time_scale);
    1473         354 :     avio_rb32(pb); /* preferred scale */
    1474             : 
    1475         354 :     avio_rb16(pb); /* preferred volume */
    1476             : 
    1477         354 :     avio_skip(pb, 10); /* reserved */
    1478             : 
    1479             :     /* movie display matrix, store it in main context and use it later on */
    1480        1416 :     for (i = 0; i < 3; i++) {
    1481        1062 :         c->movie_display_matrix[i][0] = avio_rb32(pb); // 16.16 fixed point
    1482        1062 :         c->movie_display_matrix[i][1] = avio_rb32(pb); // 16.16 fixed point
    1483        1062 :         c->movie_display_matrix[i][2] = avio_rb32(pb); //  2.30 fixed point
    1484             :     }
    1485             : 
    1486         354 :     avio_rb32(pb); /* preview time */
    1487         354 :     avio_rb32(pb); /* preview duration */
    1488         354 :     avio_rb32(pb); /* poster time */
    1489         354 :     avio_rb32(pb); /* selection time */
    1490         354 :     avio_rb32(pb); /* selection duration */
    1491         354 :     avio_rb32(pb); /* current time */
    1492         354 :     avio_rb32(pb); /* next track ID */
    1493             : 
    1494         354 :     return 0;
    1495             : }
    1496             : 
    1497           4 : static int mov_read_enda(MOVContext *c, AVIOContext *pb, MOVAtom atom)
    1498             : {
    1499             :     AVStream *st;
    1500             :     int little_endian;
    1501             : 
    1502           4 :     if (c->fc->nb_streams < 1)
    1503           0 :         return 0;
    1504           4 :     st = c->fc->streams[c->fc->nb_streams-1];
    1505             : 
    1506           4 :     little_endian = avio_rb16(pb) & 0xFF;
    1507           4 :     av_log(c->fc, AV_LOG_TRACE, "enda %d\n", little_endian);
    1508           4 :     if (little_endian == 1) {
    1509           0 :         switch (st->codecpar->codec_id) {
    1510           0 :         case AV_CODEC_ID_PCM_S24BE:
    1511           0 :             st->codecpar->codec_id = AV_CODEC_ID_PCM_S24LE;
    1512           0 :             break;
    1513           0 :         case AV_CODEC_ID_PCM_S32BE:
    1514           0 :             st->codecpar->codec_id = AV_CODEC_ID_PCM_S32LE;
    1515           0 :             break;
    1516           0 :         case AV_CODEC_ID_PCM_F32BE:
    1517           0 :             st->codecpar->codec_id = AV_CODEC_ID_PCM_F32LE;
    1518           0 :             break;
    1519           0 :         case AV_CODEC_ID_PCM_F64BE:
    1520           0 :             st->codecpar->codec_id = AV_CODEC_ID_PCM_F64LE;
    1521           0 :             break;
    1522           0 :         default:
    1523           0 :             break;
    1524             :         }
    1525           4 :     }
    1526           4 :     return 0;
    1527             : }
    1528             : 
    1529          18 : static int mov_read_colr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
    1530             : {
    1531             :     AVStream *st;
    1532          18 :     char color_parameter_type[5] = { 0 };
    1533             :     uint16_t color_primaries, color_trc, color_matrix;
    1534             :     int ret;
    1535             : 
    1536          18 :     if (c->fc->nb_streams < 1)
    1537           0 :         return 0;
    1538          18 :     st = c->fc->streams[c->fc->nb_streams - 1];
    1539             : 
    1540          18 :     ret = ffio_read_size(pb, color_parameter_type, 4);
    1541          18 :     if (ret < 0)
    1542           0 :         return ret;
    1543          35 :     if (strncmp(color_parameter_type, "nclx", 4) &&
    1544          17 :         strncmp(color_parameter_type, "nclc", 4)) {
    1545           0 :         av_log(c->fc, AV_LOG_WARNING, "unsupported color_parameter_type %s\n",
    1546             :                color_parameter_type);
    1547           0 :         return 0;
    1548             :     }
    1549             : 
    1550          18 :     color_primaries = avio_rb16(pb);
    1551          18 :     color_trc = avio_rb16(pb);
    1552          18 :     color_matrix = avio_rb16(pb);
    1553             : 
    1554          18 :     av_log(c->fc, AV_LOG_TRACE,
    1555             :            "%s: pri %d trc %d matrix %d",
    1556             :            color_parameter_type, color_primaries, color_trc, color_matrix);
    1557             : 
    1558          18 :     if (!strncmp(color_parameter_type, "nclx", 4)) {
    1559           1 :         uint8_t color_range = avio_r8(pb) >> 7;
    1560           1 :         av_log(c->fc, AV_LOG_TRACE, " full %"PRIu8"", color_range);
    1561           1 :         if (color_range)
    1562           0 :             st->codecpar->color_range = AVCOL_RANGE_JPEG;
    1563             :         else
    1564           1 :             st->codecpar->color_range = AVCOL_RANGE_MPEG;
    1565             :     }
    1566             : 
    1567          18 :     if (!av_color_primaries_name(color_primaries))
    1568           0 :         color_primaries = AVCOL_PRI_UNSPECIFIED;
    1569          18 :     if (!av_color_transfer_name(color_trc))
    1570           0 :         color_trc = AVCOL_TRC_UNSPECIFIED;
    1571          18 :     if (!av_color_space_name(color_matrix))
    1572           0 :         color_matrix = AVCOL_SPC_UNSPECIFIED;
    1573             : 
    1574          18 :     st->codecpar->color_primaries = color_primaries;
    1575          18 :     st->codecpar->color_trc       = color_trc;
    1576          18 :     st->codecpar->color_space     = color_matrix;
    1577          18 :     av_log(c->fc, AV_LOG_TRACE, "\n");
    1578             : 
    1579          18 :     return 0;
    1580             : }
    1581             : 
    1582          77 : static int mov_read_fiel(MOVContext *c, AVIOContext *pb, MOVAtom atom)
    1583             : {
    1584             :     AVStream *st;
    1585             :     unsigned mov_field_order;
    1586          77 :     enum AVFieldOrder decoded_field_order = AV_FIELD_UNKNOWN;
    1587             : 
    1588          77 :     if (c->fc->nb_streams < 1) // will happen with jp2 files
    1589           0 :         return 0;
    1590          77 :     st = c->fc->streams[c->fc->nb_streams-1];
    1591          77 :     if (atom.size < 2)
    1592           0 :         return AVERROR_INVALIDDATA;
    1593          77 :     mov_field_order = avio_rb16(pb);
    1594          77 :     if ((mov_field_order & 0xFF00) == 0x0100)
    1595          66 :         decoded_field_order = AV_FIELD_PROGRESSIVE;
    1596          11 :     else if ((mov_field_order & 0xFF00) == 0x0200) {
    1597          11 :         switch (mov_field_order & 0xFF) {
    1598           1 :         case 0x01: decoded_field_order = AV_FIELD_TT;
    1599           1 :                    break;
    1600           0 :         case 0x06: decoded_field_order = AV_FIELD_BB;
    1601           0 :                    break;
    1602           1 :         case 0x09: decoded_field_order = AV_FIELD_TB;
    1603           1 :                    break;
    1604           9 :         case 0x0E: decoded_field_order = AV_FIELD_BT;
    1605           9 :                    break;
    1606             :         }
    1607             :     }
    1608          77 :     if (decoded_field_order == AV_FIELD_UNKNOWN && mov_field_order) {
    1609           0 :         av_log(NULL, AV_LOG_ERROR, "Unknown MOV field order 0x%04x\n", mov_field_order);
    1610             :     }
    1611          77 :     st->codecpar->field_order = decoded_field_order;
    1612             : 
    1613          77 :     return 0;
    1614             : }
    1615             : 
    1616          61 : static int mov_realloc_extradata(AVCodecParameters *par, MOVAtom atom)
    1617             : {
    1618          61 :     int err = 0;
    1619          61 :     uint64_t size = (uint64_t)par->extradata_size + atom.size + 8 + AV_INPUT_BUFFER_PADDING_SIZE;
    1620          61 :     if (size > INT_MAX || (uint64_t)atom.size > INT_MAX)
    1621           0 :         return AVERROR_INVALIDDATA;
    1622          61 :     if ((err = av_reallocp(&par->extradata, size)) < 0) {
    1623           0 :         par->extradata_size = 0;
    1624           0 :         return err;
    1625             :     }
    1626          61 :     par->extradata_size = size - AV_INPUT_BUFFER_PADDING_SIZE;
    1627          61 :     return 0;
    1628             : }
    1629             : 
    1630             : /* Read a whole atom into the extradata return the size of the atom read, possibly truncated if != atom.size */
    1631          61 : static int64_t mov_read_atom_into_extradata(MOVContext *c, AVIOContext *pb, MOVAtom atom,
    1632             :                                         AVCodecParameters *par, uint8_t *buf)
    1633             : {
    1634          61 :     int64_t result = atom.size;
    1635             :     int err;
    1636             : 
    1637          61 :     AV_WB32(buf    , atom.size + 8);
    1638          61 :     AV_WL32(buf + 4, atom.type);
    1639          61 :     err = ffio_read_size(pb, buf + 8, atom.size);
    1640          61 :     if (err < 0) {
    1641           0 :         par->extradata_size -= atom.size;
    1642           0 :         return err;
    1643          61 :     } else if (err < atom.size) {
    1644           0 :         av_log(c->fc, AV_LOG_WARNING, "truncated extradata\n");
    1645           0 :         par->extradata_size -= atom.size - err;
    1646           0 :         result = err;
    1647             :     }
    1648          61 :     memset(buf + 8 + err, 0, AV_INPUT_BUFFER_PADDING_SIZE);
    1649          61 :     return result;
    1650             : }
    1651             : 
    1652             : /* FIXME modify QDM2/SVQ3/H.264 decoders to take full atom as extradata */
    1653          54 : static int mov_read_extradata(MOVContext *c, AVIOContext *pb, MOVAtom atom,
    1654             :                               enum AVCodecID codec_id)
    1655             : {
    1656             :     AVStream *st;
    1657             :     uint64_t original_size;
    1658             :     int err;
    1659             : 
    1660          54 :     if (c->fc->nb_streams < 1) // will happen with jp2 files
    1661           0 :         return 0;
    1662          54 :     st = c->fc->streams[c->fc->nb_streams-1];
    1663             : 
    1664          54 :     if (st->codecpar->codec_id != codec_id)
    1665          19 :         return 0; /* unexpected codec_id - don't mess with extradata */
    1666             : 
    1667          35 :     original_size = st->codecpar->extradata_size;
    1668          35 :     err = mov_realloc_extradata(st->codecpar, atom);
    1669          35 :     if (err)
    1670           0 :         return err;
    1671             : 
    1672          35 :     err =  mov_read_atom_into_extradata(c, pb, atom, st->codecpar,  st->codecpar->extradata + original_size);
    1673          35 :     if (err < 0)
    1674           0 :         return err;
    1675          35 :     return 0; // Note: this is the original behavior to ignore truncation.
    1676             : }
    1677             : 
    1678             : /* wrapper functions for reading ALAC/AVS/MJPEG/MJPEG2000 extradata atoms only for those codecs */
    1679          13 : static int mov_read_alac(MOVContext *c, AVIOContext *pb, MOVAtom atom)
    1680             : {
    1681          13 :     return mov_read_extradata(c, pb, atom, AV_CODEC_ID_ALAC);
    1682             : }
    1683             : 
    1684           0 : static int mov_read_avss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
    1685             : {
    1686           0 :     return mov_read_extradata(c, pb, atom, AV_CODEC_ID_AVS);
    1687             : }
    1688             : 
    1689           0 : static int mov_read_jp2h(MOVContext *c, AVIOContext *pb, MOVAtom atom)
    1690             : {
    1691           0 :     return mov_read_extradata(c, pb, atom, AV_CODEC_ID_JPEG2000);
    1692             : }
    1693             : 
    1694           0 : static int mov_read_dpxe(MOVContext *c, AVIOContext *pb, MOVAtom atom)
    1695             : {
    1696           0 :     return mov_read_extradata(c, pb, atom, AV_CODEC_ID_R10K);
    1697             : }
    1698             : 
    1699          19 : static int mov_read_avid(MOVContext *c, AVIOContext *pb, MOVAtom atom)
    1700             : {
    1701          19 :     int ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_AVUI);
    1702          19 :     if(ret == 0)
    1703          19 :         ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_DNXHD);
    1704          19 :     return ret;
    1705             : }
    1706             : 
    1707           0 : static int mov_read_targa_y216(MOVContext *c, AVIOContext *pb, MOVAtom atom)
    1708             : {
    1709           0 :     int ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_TARGA_Y216);
    1710             : 
    1711           0 :     if (!ret && c->fc->nb_streams >= 1) {
    1712           0 :         AVCodecParameters *par = c->fc->streams[c->fc->nb_streams-1]->codecpar;
    1713           0 :         if (par->extradata_size >= 40) {
    1714           0 :             par->height = AV_RB16(&par->extradata[36]);
    1715           0 :             par->width  = AV_RB16(&par->extradata[38]);
    1716             :         }
    1717             :     }
    1718           0 :     return ret;
    1719             : }
    1720             : 
    1721          16 : static int mov_read_ares(MOVContext *c, AVIOContext *pb, MOVAtom atom)
    1722             : {
    1723          16 :     if (c->fc->nb_streams >= 1) {
    1724          16 :         AVCodecParameters *par = c->fc->streams[c->fc->nb_streams-1]->codecpar;
    1725          16 :         if (par->codec_tag == MKTAG('A', 'V', 'i', 'n') &&
    1726           0 :             par->codec_id == AV_CODEC_ID_H264 &&
    1727           0 :             atom.size > 11) {
    1728             :             int cid;
    1729           0 :             avio_skip(pb, 10);
    1730           0 :             cid = avio_rb16(pb);
    1731             :             /* For AVID AVCI50, force width of 1440 to be able to select the correct SPS and PPS */
    1732           0 :             if (cid == 0xd4d || cid == 0xd4e)
    1733           0 :                 par->width = 1440;
    1734           0 :             return 0;
    1735          32 :         } else if ((par->codec_tag == MKTAG('A', 'V', 'd', '1') ||
    1736          32 :                     par->codec_tag == MKTAG('A', 'V', 'j', '2') ||
    1737          29 :                     par->codec_tag == MKTAG('A', 'V', 'd', 'n')) &&
    1738          13 :                    atom.size >= 24) {
    1739             :             int num, den;
    1740          13 :             avio_skip(pb, 12);
    1741          13 :             num = avio_rb32(pb);
    1742          13 :             den = avio_rb32(pb);
    1743          13 :             if (num <= 0 || den <= 0)
    1744           0 :                 return 0;
    1745          13 :             switch (avio_rb32(pb)) {
    1746          12 :             case 2:
    1747          12 :                 if (den >= INT_MAX / 2)
    1748           0 :                     return 0;
    1749          12 :                 den *= 2;
    1750          13 :             case 1:
    1751          13 :                 c->fc->streams[c->fc->nb_streams-1]->display_aspect_ratio.num = num;
    1752          13 :                 c->fc->streams[c->fc->nb_streams-1]->display_aspect_ratio.den = den;
    1753          13 :             default:
    1754          13 :                 return 0;
    1755             :             }
    1756             :         }
    1757             :     }
    1758             : 
    1759           3 :     return mov_read_avid(c, pb, atom);
    1760             : }
    1761             : 
    1762          26 : static int mov_read_aclr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
    1763             : {
    1764          26 :     int ret = 0;
    1765          26 :     int length = 0;
    1766             :     uint64_t original_size;
    1767          26 :     if (c->fc->nb_streams >= 1) {
    1768          26 :         AVCodecParameters *par = c->fc->streams[c->fc->nb_streams-1]->codecpar;
    1769          26 :         if (par->codec_id == AV_CODEC_ID_H264)
    1770           0 :             return 0;
    1771          26 :         if (atom.size == 16) {
    1772          26 :             original_size = par->extradata_size;
    1773          26 :             ret = mov_realloc_extradata(par, atom);
    1774          26 :             if (!ret) {
    1775          26 :                 length =  mov_read_atom_into_extradata(c, pb, atom, par, par->extradata + original_size);
    1776          26 :                 if (length == atom.size) {
    1777          26 :                     const uint8_t range_value = par->extradata[original_size + 19];
    1778          26 :                     switch (range_value) {
    1779          26 :                     case 1:
    1780          26 :                         par->color_range = AVCOL_RANGE_MPEG;
    1781          26 :                         break;
    1782           0 :                     case 2:
    1783           0 :                         par->color_range = AVCOL_RANGE_JPEG;
    1784           0 :                         break;
    1785           0 :                     default:
    1786           0 :                         av_log(c, AV_LOG_WARNING, "ignored unknown aclr value (%d)\n", range_value);
    1787           0 :                         break;
    1788             :                     }
    1789             :                     ff_dlog(c, "color_range: %d\n", par->color_range);
    1790             :                 } else {
    1791             :                   /* For some reason the whole atom was not added to the extradata */
    1792           0 :                   av_log(c, AV_LOG_ERROR, "aclr not decoded - incomplete atom\n");
    1793             :                 }
    1794             :             } else {
    1795           0 :                 av_log(c, AV_LOG_ERROR, "aclr not decoded - unable to add atom to extradata\n");
    1796             :             }
    1797             :         } else {
    1798           0 :             av_log(c, AV_LOG_WARNING, "aclr not decoded - unexpected size %"PRId64"\n", atom.size);
    1799             :         }
    1800             :     }
    1801             : 
    1802          26 :     return ret;
    1803             : }
    1804             : 
    1805           3 : static int mov_read_svq3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
    1806             : {
    1807           3 :     return mov_read_extradata(c, pb, atom, AV_CODEC_ID_SVQ3);
    1808             : }
    1809             : 
    1810          25 : static int mov_read_wave(MOVContext *c, AVIOContext *pb, MOVAtom atom)
    1811             : {
    1812             :     AVStream *st;
    1813             :     int ret;
    1814             : 
    1815          25 :     if (c->fc->nb_streams < 1)
    1816           0 :         return 0;
    1817          25 :     st = c->fc->streams[c->fc->nb_streams-1];
    1818             : 
    1819          25 :     if ((uint64_t)atom.size > (1<<30))
    1820           0 :         return AVERROR_INVALIDDATA;
    1821             : 
    1822          49 :     if (st->codecpar->codec_id == AV_CODEC_ID_QDM2 ||
    1823          48 :         st->codecpar->codec_id == AV_CODEC_ID_QDMC ||
    1824          24 :         st->codecpar->codec_id == AV_CODEC_ID_SPEEX) {
    1825             :         // pass all frma atom to codec, needed at least for QDMC and QDM2
    1826           1 :         av_freep(&st->codecpar->extradata);
    1827           1 :         ret = ff_get_extradata(c->fc, st->codecpar, pb, atom.size);
    1828           2 :         if (ret < 0)
    1829           0 :             return ret;
    1830          24 :     } else if (atom.size > 8) { /* to read frma, esds atoms */
    1831          24 :         if (st->codecpar->codec_id == AV_CODEC_ID_ALAC && atom.size >= 24) {
    1832             :             uint64_t buffer;
    1833          10 :             ret = ffio_ensure_seekback(pb, 8);
    1834          10 :             if (ret < 0)
    1835           0 :                 return ret;
    1836          10 :             buffer = avio_rb64(pb);
    1837          10 :             atom.size -= 8;
    1838          10 :             if (  (buffer & 0xFFFFFFFF) == MKBETAG('f','r','m','a')
    1839          10 :                 && buffer >> 32 <= atom.size
    1840          10 :                 && buffer >> 32 >= 8) {
    1841          10 :                 avio_skip(pb, -8);
    1842          10 :                 atom.size += 8;
    1843           0 :             } else if (!st->codecpar->extradata_size) {
    1844             : #define ALAC_EXTRADATA_SIZE 36
    1845           0 :                 st->codecpar->extradata = av_mallocz(ALAC_EXTRADATA_SIZE + AV_INPUT_BUFFER_PADDING_SIZE);
    1846           0 :                 if (!st->codecpar->extradata)
    1847           0 :                     return AVERROR(ENOMEM);
    1848           0 :                 st->codecpar->extradata_size = ALAC_EXTRADATA_SIZE;
    1849           0 :                 AV_WB32(st->codecpar->extradata    , ALAC_EXTRADATA_SIZE);
    1850           0 :                 AV_WB32(st->codecpar->extradata + 4, MKTAG('a','l','a','c'));
    1851           0 :                 AV_WB64(st->codecpar->extradata + 12, buffer);
    1852           0 :                 avio_read(pb, st->codecpar->extradata + 20, 16);
    1853           0 :                 avio_skip(pb, atom.size - 24);
    1854           0 :                 return 0;
    1855             :             }
    1856             :         }
    1857          24 :         if ((ret = mov_read_default(c, pb, atom)) < 0)
    1858           0 :             return ret;
    1859             :     } else
    1860           0 :         avio_skip(pb, atom.size);
    1861          25 :     return 0;
    1862             : }
    1863             : 
    1864             : /**
    1865             :  * This function reads atom content and puts data in extradata without tag
    1866             :  * nor size unlike mov_read_extradata.
    1867             :  */
    1868          54 : static int mov_read_glbl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
    1869             : {
    1870             :     AVStream *st;
    1871             :     int ret;
    1872             : 
    1873          54 :     if (c->fc->nb_streams < 1)
    1874           0 :         return 0;
    1875          54 :     st = c->fc->streams[c->fc->nb_streams-1];
    1876             : 
    1877          54 :     if ((uint64_t)atom.size > (1<<30))
    1878           0 :         return AVERROR_INVALIDDATA;
    1879             : 
    1880          54 :     if (atom.size >= 10) {
    1881             :         // Broken files created by legacy versions of libavformat will
    1882             :         // wrap a whole fiel atom inside of a glbl atom.
    1883          53 :         unsigned size = avio_rb32(pb);
    1884          53 :         unsigned type = avio_rl32(pb);
    1885          53 :         avio_seek(pb, -8, SEEK_CUR);
    1886          53 :         if (type == MKTAG('f','i','e','l') && size == atom.size)
    1887           7 :             return mov_read_default(c, pb, atom);
    1888             :     }
    1889          47 :     if (st->codecpar->extradata_size > 1 && st->codecpar->extradata) {
    1890           0 :         av_log(c, AV_LOG_WARNING, "ignoring multiple glbl\n");
    1891           0 :         return 0;
    1892             :     }
    1893          47 :     av_freep(&st->codecpar->extradata);
    1894          47 :     ret = ff_get_extradata(c->fc, st->codecpar, pb, atom.size);
    1895          47 :     if (ret < 0)
    1896           0 :         return ret;
    1897             : 
    1898          47 :     return 0;
    1899             : }
    1900             : 
    1901           2 : static int mov_read_dvc1(MOVContext *c, AVIOContext *pb, MOVAtom atom)
    1902             : {
    1903             :     AVStream *st;
    1904             :     uint8_t profile_level;
    1905             :     int ret;
    1906             : 
    1907           2 :     if (c->fc->nb_streams < 1)
    1908           0 :         return 0;
    1909           2 :     st = c->fc->streams[c->fc->nb_streams-1];
    1910             : 
    1911           2 :     if (atom.size >= (1<<28) || atom.size < 7)
    1912           0 :         return AVERROR_INVALIDDATA;
    1913             : 
    1914           2 :     profile_level = avio_r8(pb);
    1915           2 :     if ((profile_level & 0xf0) != 0xc0)
    1916           0 :         return 0;
    1917             : 
    1918           2 :     avio_seek(pb, 6, SEEK_CUR);
    1919           2 :     av_freep(&st->codecpar->extradata);
    1920           2 :     ret = ff_get_extradata(c->fc, st->codecpar, pb, atom.size - 7);
    1921           2 :     if (ret < 0)
    1922           0 :         return ret;
    1923             : 
    1924           2 :     return 0;
    1925             : }
    1926             : 
    1927             : /**
    1928             :  * An strf atom is a BITMAPINFOHEADER struct. This struct is 40 bytes itself,
    1929             :  * but can have extradata appended at the end after the 40 bytes belonging
    1930             :  * to the struct.
    1931             :  */
    1932           0 : static int mov_read_strf(MOVContext *c, AVIOContext *pb, MOVAtom atom)
    1933             : {
    1934             :     AVStream *st;
    1935             :     int ret;
    1936             : 
    1937           0 :     if (c->fc->nb_streams < 1)
    1938           0 :         return 0;
    1939           0 :     if (atom.size <= 40)
    1940           0 :         return 0;
    1941           0 :     st = c->fc->streams[c->fc->nb_streams-1];
    1942             : 
    1943           0 :     if ((uint64_t)atom.size > (1<<30))
    1944           0 :         return AVERROR_INVALIDDATA;
    1945             : 
    1946           0 :     avio_skip(pb, 40);
    1947           0 :     av_freep(&st->codecpar->extradata);
    1948           0 :     ret = ff_get_extradata(c->fc, st->codecpar, pb, atom.size - 40);
    1949           0 :     if (ret < 0)
    1950           0 :         return ret;
    1951             : 
    1952           0 :     return 0;
    1953             : }
    1954             : 
    1955         418 : static int mov_read_stco(MOVContext *c, AVIOContext *pb, MOVAtom atom)
    1956             : {
    1957             :     AVStream *st;
    1958             :     MOVStreamContext *sc;
    1959             :     unsigned int i, entries;
    1960             : 
    1961         418 :     if (c->fc->nb_streams < 1)
    1962           0 :         return 0;
    1963         418 :     st = c->fc->streams[c->fc->nb_streams-1];
    1964         418 :     sc = st->priv_data;
    1965             : 
    1966         418 :     avio_r8(pb); /* version */
    1967         418 :     avio_rb24(pb); /* flags */
    1968             : 
    1969         418 :     entries = avio_rb32(pb);
    1970             : 
    1971         418 :     if (!entries)
    1972           9 :         return 0;
    1973             : 
    1974         409 :     if (sc->chunk_offsets)
    1975           0 :         av_log(c->fc, AV_LOG_WARNING, "Duplicated STCO atom\n");
    1976         409 :     av_free(sc->chunk_offsets);
    1977         409 :     sc->chunk_count = 0;
    1978         409 :     sc->chunk_offsets = av_malloc_array(entries, sizeof(*sc->chunk_offsets));
    1979         409 :     if (!sc->chunk_offsets)
    1980           0 :         return AVERROR(ENOMEM);
    1981         409 :     sc->chunk_count = entries;
    1982             : 
    1983         409 :     if      (atom.type == MKTAG('s','t','c','o'))
    1984       40903 :         for (i = 0; i < entries && !pb->eof_reached; i++)
    1985       40494 :             sc->chunk_offsets[i] = avio_rb32(pb);
    1986           0 :     else if (atom.type == MKTAG('c','o','6','4'))
    1987           0 :         for (i = 0; i < entries && !pb->eof_reached; i++)
    1988           0 :             sc->chunk_offsets[i] = avio_rb64(pb);
    1989             :     else
    1990           0 :         return AVERROR_INVALIDDATA;
    1991             : 
    1992         409 :     sc->chunk_count = i;
    1993             : 
    1994         409 :     if (pb->eof_reached) {
    1995           0 :         av_log(c->fc, AV_LOG_WARNING, "reached eof, corrupted STCO atom\n");
    1996           0 :         return AVERROR_EOF;
    1997             :     }
    1998             : 
    1999         409 :     return 0;
    2000             : }
    2001             : 
    2002         425 : static int mov_codec_id(AVStream *st, uint32_t format)
    2003             : {
    2004         425 :     int id = ff_codec_get_id(ff_codec_movaudio_tags, format);
    2005             : 
    2006         669 :     if (id <= 0 &&
    2007         486 :         ((format & 0xFFFF) == 'm' + ('s' << 8) ||
    2008         242 :          (format & 0xFFFF) == 'T' + ('S' << 8)))
    2009           2 :         id = ff_codec_get_id(ff_codec_wav_tags, av_bswap32(format) & 0xFFFF);
    2010             : 
    2011         425 :     if (st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO && id > 0) {
    2012         183 :         st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
    2013         242 :     } else if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO &&
    2014             :                /* skip old ASF MPEG-4 tag */
    2015         240 :                format && format != MKTAG('m','p','4','s')) {
    2016         236 :         id = ff_codec_get_id(ff_codec_movvideo_tags, format);
    2017         236 :         if (id <= 0)
    2018          33 :             id = ff_codec_get_id(ff_codec_bmp_tags, format);
    2019         236 :         if (id > 0)
    2020         208 :             st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
    2021          30 :         else if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA ||
    2022           3 :                     (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE &&
    2023           1 :                     st->codecpar->codec_id == AV_CODEC_ID_NONE)) {
    2024          26 :             id = ff_codec_get_id(ff_codec_movsubtitle_tags, format);
    2025          26 :             if (id > 0)
    2026           4 :                 st->codecpar->codec_type = AVMEDIA_TYPE_SUBTITLE;
    2027             :         }
    2028             :     }
    2029             : 
    2030         425 :     st->codecpar->codec_tag = format;
    2031             : 
    2032         425 :     return id;
    2033             : }
    2034             : 
    2035         208 : static void mov_parse_stsd_video(MOVContext *c, AVIOContext *pb,
    2036             :                                  AVStream *st, MOVStreamContext *sc)
    2037             : {
    2038         208 :     uint8_t codec_name[32] = { 0 };
    2039             :     int64_t stsd_start;
    2040             :     unsigned int len;
    2041             : 
    2042             :     /* The first 16 bytes of the video sample description are already
    2043             :      * read in ff_mov_read_stsd_entries() */
    2044         208 :     stsd_start = avio_tell(pb) - 16;
    2045             : 
    2046         208 :     avio_rb16(pb); /* version */
    2047         208 :     avio_rb16(pb); /* revision level */
    2048         208 :     avio_rb32(pb); /* vendor */
    2049         208 :     avio_rb32(pb); /* temporal quality */
    2050         208 :     avio_rb32(pb); /* spatial quality */
    2051             : 
    2052         208 :     st->codecpar->width  = avio_rb16(pb); /* width */
    2053         208 :     st->codecpar->height = avio_rb16(pb); /* height */
    2054             : 
    2055         208 :     avio_rb32(pb); /* horiz resolution */
    2056         208 :     avio_rb32(pb); /* vert resolution */
    2057         208 :     avio_rb32(pb); /* data size, always 0 */
    2058         208 :     avio_rb16(pb); /* frames per samples */
    2059             : 
    2060         208 :     len = avio_r8(pb); /* codec name, pascal string */
    2061         208 :     if (len > 31)
    2062           1 :         len = 31;
    2063         208 :     mov_read_mac_string(c, pb, len, codec_name, sizeof(codec_name));
    2064         208 :     if (len < 31)
    2065         206 :         avio_skip(pb, 31 - len);
    2066             : 
    2067         208 :     if (codec_name[0])
    2068         165 :         av_dict_set(&st->metadata, "encoder", codec_name, 0);
    2069             : 
    2070             :     /* codec_tag YV12 triggers an UV swap in rawdec.c */
    2071         208 :     if (!strncmp(codec_name, "Planar Y'CbCr 8-bit 4:2:0", 25)) {
    2072           0 :         st->codecpar->codec_tag = MKTAG('I', '4', '2', '0');
    2073           0 :         st->codecpar->width &= ~1;
    2074           0 :         st->codecpar->height &= ~1;
    2075             :     }
    2076             :     /* Flash Media Server uses tag H.263 with Sorenson Spark */
    2077         208 :     if (st->codecpar->codec_tag == MKTAG('H','2','6','3') &&
    2078           0 :         !strncmp(codec_name, "Sorenson H263", 13))
    2079           0 :         st->codecpar->codec_id = AV_CODEC_ID_FLV1;
    2080             : 
    2081         208 :     st->codecpar->bits_per_coded_sample = avio_rb16(pb); /* depth */
    2082             : 
    2083         208 :     avio_seek(pb, stsd_start, SEEK_SET);
    2084             : 
    2085         208 :     if (ff_get_qtpalette(st->codecpar->codec_id, pb, sc->palette)) {
    2086          13 :         st->codecpar->bits_per_coded_sample &= 0x1F;
    2087          13 :         sc->has_palette = 1;
    2088             :     }
    2089         208 : }
    2090             : 
    2091         185 : static void mov_parse_stsd_audio(MOVContext *c, AVIOContext *pb,
    2092             :                                  AVStream *st, MOVStreamContext *sc)
    2093             : {
    2094             :     int bits_per_sample, flags;
    2095         185 :     uint16_t version = avio_rb16(pb);
    2096         185 :     AVDictionaryEntry *compatible_brands = av_dict_get(c->fc->metadata, "compatible_brands", NULL, AV_DICT_MATCH_CASE);
    2097             : 
    2098         185 :     avio_rb16(pb); /* revision level */
    2099         185 :     avio_rb32(pb); /* vendor */
    2100             : 
    2101         185 :     st->codecpar->channels              = avio_rb16(pb); /* channel count */
    2102         185 :     st->codecpar->bits_per_coded_sample = avio_rb16(pb); /* sample size */
    2103         185 :     av_log(c->fc, AV_LOG_TRACE, "audio channels %d\n", st->codecpar->channels);
    2104             : 
    2105         185 :     sc->audio_cid = avio_rb16(pb);
    2106         185 :     avio_rb16(pb); /* packet size = 0 */
    2107             : 
    2108         185 :     st->codecpar->sample_rate = ((avio_rb32(pb) >> 16));
    2109             : 
    2110             :     // Read QT version 1 fields. In version 0 these do not exist.
    2111         185 :     av_log(c->fc, AV_LOG_TRACE, "version =%d, isom =%d\n", version, c->isom);
    2112         185 :     if (!c->isom ||
    2113         120 :         (compatible_brands && strstr(compatible_brands->value, "qt  "))) {
    2114             : 
    2115          65 :         if (version == 1) {
    2116          34 :             sc->samples_per_frame = avio_rb32(pb);
    2117          34 :             avio_rb32(pb); /* bytes per packet */
    2118          34 :             sc->bytes_per_frame = avio_rb32(pb);
    2119          34 :             avio_rb32(pb); /* bytes per sample */
    2120          31 :         } else if (version == 2) {
    2121           4 :             avio_rb32(pb); /* sizeof struct only */
    2122           4 :             st->codecpar->sample_rate = av_int2double(avio_rb64(pb));
    2123           4 :             st->codecpar->channels    = avio_rb32(pb);
    2124           4 :             avio_rb32(pb); /* always 0x7F000000 */
    2125           4 :             st->codecpar->bits_per_coded_sample = avio_rb32(pb);
    2126             : 
    2127           4 :             flags = avio_rb32(pb); /* lpcm format specific flag */
    2128           4 :             sc->bytes_per_frame   = avio_rb32(pb);
    2129           4 :             sc->samples_per_frame = avio_rb32(pb);
    2130           4 :             if (st->codecpar->codec_tag == MKTAG('l','p','c','m'))
    2131           0 :                 st->codecpar->codec_id =
    2132           0 :                     ff_mov_get_lpcm_codec_id(st->codecpar->bits_per_coded_sample,
    2133             :                                              flags);
    2134             :         }
    2135          65 :         if (version == 0 || (version == 1 && sc->audio_cid != -2)) {
    2136             :             /* can't correctly handle variable sized packet as audio unit */
    2137          46 :             switch (st->codecpar->codec_id) {
    2138           0 :             case AV_CODEC_ID_MP2:
    2139             :             case AV_CODEC_ID_MP3:
    2140           0 :                 st->need_parsing = AVSTREAM_PARSE_FULL;
    2141           0 :                 break;
    2142             :             }
    2143             :         }
    2144             :     }
    2145             : 
    2146         185 :     if (sc->format == 0) {
    2147           0 :         if (st->codecpar->bits_per_coded_sample == 8)
    2148           0 :             st->codecpar->codec_id = mov_codec_id(st, MKTAG('r','a','w',' '));
    2149           0 :         else if (st->codecpar->bits_per_coded_sample == 16)
    2150           0 :             st->codecpar->codec_id = mov_codec_id(st, MKTAG('t','w','o','s'));
    2151             :     }
    2152             : 
    2153         185 :     switch (st->codecpar->codec_id) {
    2154           6 :     case AV_CODEC_ID_PCM_S8:
    2155             :     case AV_CODEC_ID_PCM_U8:
    2156           6 :         if (st->codecpar->bits_per_coded_sample == 16)
    2157           0 :             st->codecpar->codec_id = AV_CODEC_ID_PCM_S16BE;
    2158           6 :         break;
    2159          11 :     case AV_CODEC_ID_PCM_S16LE:
    2160             :     case AV_CODEC_ID_PCM_S16BE:
    2161          11 :         if (st->codecpar->bits_per_coded_sample == 8)
    2162           2 :             st->codecpar->codec_id = AV_CODEC_ID_PCM_S8;
    2163           9 :         else if (st->codecpar->bits_per_coded_sample == 24)
    2164           0 :             st->codecpar->codec_id =
    2165           0 :                 st->codecpar->codec_id == AV_CODEC_ID_PCM_S16BE ?
    2166           0 :                 AV_CODEC_ID_PCM_S24BE : AV_CODEC_ID_PCM_S24LE;
    2167           9 :         else if (st->codecpar->bits_per_coded_sample == 32)
    2168           0 :              st->codecpar->codec_id =
    2169           0 :                 st->codecpar->codec_id == AV_CODEC_ID_PCM_S16BE ?
    2170           0 :                 AV_CODEC_ID_PCM_S32BE : AV_CODEC_ID_PCM_S32LE;
    2171          11 :         break;
    2172             :     /* set values for old format before stsd version 1 appeared */
    2173           2 :     case AV_CODEC_ID_MACE3:
    2174           2 :         sc->samples_per_frame = 6;
    2175           2 :         sc->bytes_per_frame   = 2 * st->codecpar->channels;
    2176           2 :         break;
    2177           7 :     case AV_CODEC_ID_MACE6:
    2178           7 :         sc->samples_per_frame = 6;
    2179           7 :         sc->bytes_per_frame   = 1 * st->codecpar->channels;
    2180           7 :         break;
    2181           4 :     case AV_CODEC_ID_ADPCM_IMA_QT:
    2182           4 :         sc->samples_per_frame = 64;
    2183           4 :         sc->bytes_per_frame   = 34 * st->codecpar->channels;
    2184           4 :         break;
    2185           1 :     case AV_CODEC_ID_GSM:
    2186           1 :         sc->samples_per_frame = 160;
    2187           1 :         sc->bytes_per_frame   = 33;
    2188           1 :         break;
    2189         154 :     default:
    2190         154 :         break;
    2191             :     }
    2192             : 
    2193         185 :     bits_per_sample = av_get_bits_per_sample(st->codecpar->codec_id);
    2194         185 :     if (bits_per_sample) {
    2195          36 :         st->codecpar->bits_per_coded_sample = bits_per_sample;
    2196          36 :         sc->sample_size = (bits_per_sample >> 3) * st->codecpar->channels;
    2197             :     }
    2198         185 : }
    2199             : 
    2200           5 : static void mov_parse_stsd_subtitle(MOVContext *c, AVIOContext *pb,
    2201             :                                     AVStream *st, MOVStreamContext *sc,
    2202             :                                     int64_t size)
    2203             : {
    2204             :     // ttxt stsd contains display flags, justification, background
    2205             :     // color, fonts, and default styles, so fake an atom to read it
    2206           5 :     MOVAtom fake_atom = { .size = size };
    2207             :     // mp4s contains a regular esds atom
    2208           5 :     if (st->codecpar->codec_tag != AV_RL32("mp4s"))
    2209           5 :         mov_read_glbl(c, pb, fake_atom);
    2210           5 :     st->codecpar->width  = sc->width;
    2211           5 :     st->codecpar->height = sc->height;
    2212           5 : }
    2213             : 
    2214           0 : static uint32_t yuv_to_rgba(uint32_t ycbcr)
    2215             : {
    2216             :     uint8_t r, g, b;
    2217             :     int y, cb, cr;
    2218             : 
    2219           0 :     y  = (ycbcr >> 16) & 0xFF;
    2220           0 :     cr = (ycbcr >> 8)  & 0xFF;
    2221           0 :     cb =  ycbcr        & 0xFF;
    2222             : 
    2223           0 :     b = av_clip_uint8((1164 * (y - 16)                     + 2018 * (cb - 128)) / 1000);
    2224           0 :     g = av_clip_uint8((1164 * (y - 16) -  813 * (cr - 128) -  391 * (cb - 128)) / 1000);
    2225           0 :     r = av_clip_uint8((1164 * (y - 16) + 1596 * (cr - 128)                    ) / 1000);
    2226             : 
    2227           0 :     return (r << 16) | (g << 8) | b;
    2228             : }
    2229             : 
    2230           0 : static int mov_rewrite_dvd_sub_extradata(AVStream *st)
    2231             : {
    2232           0 :     char buf[256] = {0};
    2233           0 :     uint8_t *src = st->codecpar->extradata;
    2234             :     int i;
    2235             : 
    2236           0 :     if (st->codecpar->extradata_size != 64)
    2237           0 :         return 0;
    2238             : 
    2239           0 :     if (st->codecpar->width > 0 &&  st->codecpar->height > 0)
    2240           0 :         snprintf(buf, sizeof(buf), "size: %dx%d\n",
    2241           0 :                  st->codecpar->width, st->codecpar->height);
    2242           0 :     av_strlcat(buf, "palette: ", sizeof(buf));
    2243             : 
    2244           0 :     for (i = 0; i < 16; i++) {
    2245           0 :         uint32_t yuv = AV_RB32(src + i * 4);
    2246           0 :         uint32_t rgba = yuv_to_rgba(yuv);
    2247             : 
    2248           0 :         av_strlcatf(buf, sizeof(buf), "%06"PRIx32"%s", rgba, i != 15 ? ", " : "");
    2249             :     }
    2250             : 
    2251           0 :     if (av_strlcat(buf, "\n", sizeof(buf)) >= sizeof(buf))
    2252           0 :         return 0;
    2253             : 
    2254           0 :     av_freep(&st->codecpar->extradata);
    2255           0 :     st->codecpar->extradata_size = 0;
    2256           0 :     st->codecpar->extradata = av_mallocz(strlen(buf) + AV_INPUT_BUFFER_PADDING_SIZE);
    2257           0 :     if (!st->codecpar->extradata)
    2258           0 :         return AVERROR(ENOMEM);
    2259           0 :     st->codecpar->extradata_size = strlen(buf);
    2260           0 :     memcpy(st->codecpar->extradata, buf, st->codecpar->extradata_size);
    2261             : 
    2262           0 :     return 0;
    2263             : }
    2264             : 
    2265          26 : static int mov_parse_stsd_data(MOVContext *c, AVIOContext *pb,
    2266             :                                 AVStream *st, MOVStreamContext *sc,
    2267             :                                 int64_t size)
    2268             : {
    2269             :     int ret;
    2270             : 
    2271          26 :     if (st->codecpar->codec_tag == MKTAG('t','m','c','d')) {
    2272          15 :         if ((int)size != size)
    2273           0 :             return AVERROR(ENOMEM);
    2274             : 
    2275          15 :         ret = ff_get_extradata(c->fc, st->codecpar, pb, size);
    2276          15 :         if (ret < 0)
    2277           0 :             return ret;
    2278          15 :         if (size > 16) {
    2279          15 :             MOVStreamContext *tmcd_ctx = st->priv_data;
    2280             :             int val;
    2281          15 :             val = AV_RB32(st->codecpar->extradata + 4);
    2282          15 :             tmcd_ctx->tmcd_flags = val;
    2283          15 :             st->avg_frame_rate.num = st->codecpar->extradata[16]; /* number of frame */
    2284          15 :             st->avg_frame_rate.den = 1;
    2285             : #if FF_API_LAVF_AVCTX
    2286             : FF_DISABLE_DEPRECATION_WARNINGS
    2287          15 :             st->codec->time_base = av_inv_q(st->avg_frame_rate);
    2288             : FF_ENABLE_DEPRECATION_WARNINGS
    2289             : #endif
    2290             :             /* adjust for per frame dur in counter mode */
    2291          15 :             if (tmcd_ctx->tmcd_flags & 0x0008) {
    2292           0 :                 int timescale = AV_RB32(st->codecpar->extradata + 8);
    2293           0 :                 int framedur = AV_RB32(st->codecpar->extradata + 12);
    2294           0 :                 st->avg_frame_rate.num *= timescale;
    2295           0 :                 st->avg_frame_rate.den *= framedur;
    2296             : #if FF_API_LAVF_AVCTX
    2297             : FF_DISABLE_DEPRECATION_WARNINGS
    2298           0 :                 st->codec->time_base.den *= timescale;
    2299           0 :                 st->codec->time_base.num *= framedur;
    2300             : FF_ENABLE_DEPRECATION_WARNINGS
    2301             : #endif
    2302             :             }
    2303          15 :             if (size > 30) {
    2304           4 :                 uint32_t len = AV_RB32(st->codecpar->extradata + 18); /* name atom length */
    2305           4 :                 uint32_t format = AV_RB32(st->codecpar->extradata + 22);
    2306           4 :                 if (format == AV_RB32("name") && (int64_t)size >= (int64_t)len + 18) {
    2307           4 :                     uint16_t str_size = AV_RB16(st->codecpar->extradata + 26); /* string length */
    2308           4 :                     if (str_size > 0 && size >= (int)str_size + 26) {
    2309           4 :                         char *reel_name = av_malloc(str_size + 1);
    2310           4 :                         if (!reel_name)
    2311           0 :                             return AVERROR(ENOMEM);
    2312           4 :                         memcpy(reel_name, st->codecpar->extradata + 30, str_size);
    2313           4 :                         reel_name[str_size] = 0; /* Add null terminator */
    2314             :                         /* don't add reel_name if emtpy string */
    2315           4 :                         if (*reel_name == 0) {
    2316           0 :                             av_free(reel_name);
    2317             :                         } else {
    2318           4 :                             av_dict_set(&st->metadata, "reel_name", reel_name,  AV_DICT_DONT_STRDUP_VAL);
    2319             :                         }
    2320             :                     }
    2321             :                 }
    2322             :             }
    2323             :         }
    2324             :     } else {
    2325             :         /* other codec type, just skip (rtp, mp4s ...) */
    2326          11 :         avio_skip(pb, size);
    2327             :     }
    2328          26 :     return 0;
    2329             : }
    2330             : 
    2331         418 : static int mov_finalize_stsd_codec(MOVContext *c, AVIOContext *pb,
    2332             :                                    AVStream *st, MOVStreamContext *sc)
    2333             : {
    2334         603 :     if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
    2335         185 :         !st->codecpar->sample_rate && sc->time_scale > 1)
    2336           0 :         st->codecpar->sample_rate = sc->time_scale;
    2337             : 
    2338             :     /* special codec parameters handling */
    2339         418 :     switch (st->codecpar->codec_id) {
    2340             : #if CONFIG_DV_DEMUXER
    2341           0 :     case AV_CODEC_ID_DVAUDIO:
    2342           0 :         c->dv_fctx = avformat_alloc_context();
    2343           0 :         if (!c->dv_fctx) {
    2344           0 :             av_log(c->fc, AV_LOG_ERROR, "dv demux context alloc error\n");
    2345           0 :             return AVERROR(ENOMEM);
    2346             :         }
    2347           0 :         c->dv_demux = avpriv_dv_init_demux(c->dv_fctx);
    2348           0 :         if (!c->dv_demux) {
    2349           0 :             av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n");
    2350           0 :             return AVERROR(ENOMEM);
    2351             :         }
    2352           0 :         sc->dv_audio_container = 1;
    2353           0 :         st->codecpar->codec_id    = AV_CODEC_ID_PCM_S16LE;
    2354           0 :         break;
    2355             : #endif
    2356             :     /* no ifdef since parameters are always those */
    2357           0 :     case AV_CODEC_ID_QCELP:
    2358           0 :         st->codecpar->channels = 1;
    2359             :         // force sample rate for qcelp when not stored in mov
    2360           0 :         if (st->codecpar->codec_tag != MKTAG('Q','c','l','p'))
    2361           0 :             st->codecpar->sample_rate = 8000;
    2362             :         // FIXME: Why is the following needed for some files?
    2363           0 :         sc->samples_per_frame = 160;
    2364           0 :         if (!sc->bytes_per_frame)
    2365           0 :             sc->bytes_per_frame = 35;
    2366           0 :         break;
    2367           0 :     case AV_CODEC_ID_AMR_NB:
    2368           0 :         st->codecpar->channels    = 1;
    2369             :         /* force sample rate for amr, stsd in 3gp does not store sample rate */
    2370           0 :         st->codecpar->sample_rate = 8000;
    2371           0 :         break;
    2372          11 :     case AV_CODEC_ID_AMR_WB:
    2373          11 :         st->codecpar->channels    = 1;
    2374          11 :         st->codecpar->sample_rate = 16000;
    2375          11 :         break;
    2376           1 :     case AV_CODEC_ID_MP2:
    2377             :     case AV_CODEC_ID_MP3:
    2378             :         /* force type after stsd for m1a hdlr */
    2379           1 :         st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
    2380           1 :         break;
    2381          13 :     case AV_CODEC_ID_GSM:
    2382             :     case AV_CODEC_ID_ADPCM_MS:
    2383             :     case AV_CODEC_ID_ADPCM_IMA_WAV:
    2384             :     case AV_CODEC_ID_ILBC:
    2385             :     case AV_CODEC_ID_MACE3:
    2386             :     case AV_CODEC_ID_MACE6:
    2387             :     case AV_CODEC_ID_QDM2:
    2388          13 :         st->codecpar->block_align = sc->bytes_per_frame;
    2389          13 :         break;
    2390          13 :     case AV_CODEC_ID_ALAC:
    2391          13 :         if (st->codecpar->extradata_size == 36) {
    2392          13 :             st->codecpar->channels    = AV_RB8 (st->codecpar->extradata + 21);
    2393          13 :             st->codecpar->sample_rate = AV_RB32(st->codecpar->extradata + 32);
    2394             :         }
    2395          13 :         break;
    2396           3 :     case AV_CODEC_ID_AC3:
    2397             :     case AV_CODEC_ID_EAC3:
    2398             :     case AV_CODEC_ID_MPEG1VIDEO:
    2399             :     case AV_CODEC_ID_VC1:
    2400             :     case AV_CODEC_ID_VP9:
    2401           3 :         st->need_parsing = AVSTREAM_PARSE_FULL;
    2402           3 :         break;
    2403         377 :     default:
    2404         377 :         break;
    2405             :     }
    2406         418 :     return 0;
    2407             : }
    2408             : 
    2409         424 : static int mov_skip_multiple_stsd(MOVContext *c, AVIOContext *pb,
    2410             :                                   int codec_tag, int format,
    2411             :                                   int64_t size)
    2412             : {
    2413         424 :     int video_codec_id = ff_codec_get_id(ff_codec_movvideo_tags, format);
    2414             : 
    2415         424 :     if (codec_tag &&
    2416           0 :          (codec_tag != format &&
    2417             :           // AVID 1:1 samples with differing data format and codec tag exist
    2418           0 :           (codec_tag != AV_RL32("AV1x") || format != AV_RL32("AVup")) &&
    2419             :           // prores is allowed to have differing data format and codec tag
    2420           0 :           codec_tag != AV_RL32("apcn") && codec_tag != AV_RL32("apch") &&
    2421             :           // so is dv (sigh)
    2422           0 :           codec_tag != AV_RL32("dvpp") && codec_tag != AV_RL32("dvcp") &&
    2423           0 :           (c->fc->video_codec_id ? video_codec_id != c->fc->video_codec_id
    2424             :                                  : codec_tag != MKTAG('j','p','e','g')))) {
    2425             :         /* Multiple fourcc, we skip JPEG. This is not correct, we should
    2426             :          * export it as a separate AVStream but this needs a few changes
    2427             :          * in the MOV demuxer, patch welcome. */
    2428             : 
    2429           0 :         av_log(c->fc, AV_LOG_WARNING, "multiple fourcc not supported\n");
    2430           0 :         avio_skip(pb, size);
    2431           0 :         return 1;
    2432             :     }
    2433             : 
    2434         424 :     return 0;
    2435             : }
    2436             : 
    2437         418 : int ff_mov_read_stsd_entries(MOVContext *c, AVIOContext *pb, int entries)
    2438             : {
    2439             :     AVStream *st;
    2440             :     MOVStreamContext *sc;
    2441             :     int pseudo_stream_id;
    2442             : 
    2443         418 :     av_assert0 (c->fc->nb_streams >= 1);
    2444         418 :     st = c->fc->streams[c->fc->nb_streams-1];
    2445         418 :     sc = st->priv_data;
    2446             : 
    2447        1260 :     for (pseudo_stream_id = 0;
    2448         424 :          pseudo_stream_id < entries && !pb->eof_reached;
    2449         424 :          pseudo_stream_id++) {
    2450             :         //Parsing Sample description table
    2451             :         enum AVCodecID id;
    2452         424 :         int ret, dref_id = 1;
    2453         424 :         MOVAtom a = { AV_RL32("stsd") };
    2454         424 :         int64_t start_pos = avio_tell(pb);
    2455         424 :         int64_t size    = avio_rb32(pb); /* size */
    2456         424 :         uint32_t format = avio_rl32(pb); /* data format */
    2457             : 
    2458         424 :         if (size >= 16) {
    2459         424 :             avio_rb32(pb); /* reserved */
    2460         424 :             avio_rb16(pb); /* reserved */
    2461         424 :             dref_id = avio_rb16(pb);
    2462           0 :         } else if (size <= 7) {
    2463           0 :             av_log(c->fc, AV_LOG_ERROR,
    2464             :                    "invalid size %"PRId64" in stsd\n", size);
    2465           0 :             return AVERROR_INVALIDDATA;
    2466             :         }
    2467             : 
    2468         424 :         if (mov_skip_multiple_stsd(c, pb, st->codecpar->codec_tag, format,
    2469         424 :                                    size - (avio_tell(pb) - start_pos))) {
    2470           0 :             sc->stsd_count++;
    2471           0 :             continue;
    2472             :         }
    2473             : 
    2474         424 :         sc->pseudo_stream_id = st->codecpar->codec_tag ? -1 : pseudo_stream_id;
    2475         424 :         sc->dref_id= dref_id;
    2476         424 :         sc->format = format;
    2477             : 
    2478         424 :         id = mov_codec_id(st, format);
    2479             : 
    2480         424 :         av_log(c->fc, AV_LOG_TRACE,
    2481             :                "size=%"PRId64" 4CC=%s codec_type=%d\n", size,
    2482         424 :                av_fourcc2str(format), st->codecpar->codec_type);
    2483             : 
    2484         424 :         if (st->codecpar->codec_type==AVMEDIA_TYPE_VIDEO) {
    2485         208 :             st->codecpar->codec_id = id;
    2486         208 :             mov_parse_stsd_video(c, pb, st, sc);
    2487         216 :         } else if (st->codecpar->codec_type==AVMEDIA_TYPE_AUDIO) {
    2488         185 :             st->codecpar->codec_id = id;
    2489         185 :             mov_parse_stsd_audio(c, pb, st, sc);
    2490         185 :             if (st->codecpar->sample_rate < 0) {
    2491           0 :                 av_log(c->fc, AV_LOG_ERROR, "Invalid sample rate %d\n", st->codecpar->sample_rate);
    2492           0 :                 return AVERROR_INVALIDDATA;
    2493             :             }
    2494          31 :         } else if (st->codecpar->codec_type==AVMEDIA_TYPE_SUBTITLE){
    2495           5 :             st->codecpar->codec_id = id;
    2496           5 :             mov_parse_stsd_subtitle(c, pb, st, sc,
    2497           5 :                                     size - (avio_tell(pb) - start_pos));
    2498             :         } else {
    2499          26 :             ret = mov_parse_stsd_data(c, pb, st, sc,
    2500          26 :                                       size - (avio_tell(pb) - start_pos));
    2501          26 :             if (ret < 0)
    2502           0 :                 return ret;
    2503             :         }
    2504             :         /* this will read extra atoms at the end (wave, alac, damr, avcC, hvcC, SMI ...) */
    2505         424 :         a.size = size - (avio_tell(pb) - start_pos);
    2506         424 :         if (a.size > 8) {
    2507         321 :             if ((ret = mov_read_default(c, pb, a)) < 0)
    2508           0 :                 return ret;
    2509         103 :         } else if (a.size > 0)
    2510           1 :             avio_skip(pb, a.size);
    2511             : 
    2512         424 :         if (sc->extradata && st->codecpar->extradata) {
    2513         237 :             int extra_size = st->codecpar->extradata_size;
    2514             : 
    2515             :             /* Move the current stream extradata to the stream context one. */
    2516         237 :             sc->extradata_size[pseudo_stream_id] = extra_size;
    2517         237 :             sc->extradata[pseudo_stream_id] = av_malloc(extra_size + AV_INPUT_BUFFER_PADDING_SIZE);
    2518         237 :             if (!sc->extradata[pseudo_stream_id])
    2519           0 :                 return AVERROR(ENOMEM);
    2520         237 :             memcpy(sc->extradata[pseudo_stream_id], st->codecpar->extradata, extra_size);
    2521         237 :             av_freep(&st->codecpar->extradata);
    2522         237 :             st->codecpar->extradata_size = 0;
    2523             :         }
    2524         424 :         sc->stsd_count++;
    2525             :     }
    2526             : 
    2527         418 :     if (pb->eof_reached) {
    2528           0 :         av_log(c->fc, AV_LOG_WARNING, "reached eof, corrupted STSD atom\n");
    2529           0 :         return AVERROR_EOF;
    2530             :     }
    2531             : 
    2532         418 :     return 0;
    2533             : }
    2534             : 
    2535         418 : static int mov_read_stsd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
    2536             : {
    2537             :     AVStream *st;
    2538             :     MOVStreamContext *sc;
    2539             :     int ret, entries;
    2540             : 
    2541         418 :     if (c->fc->nb_streams < 1)
    2542           0 :         return 0;
    2543         418 :     st = c->fc->streams[c->fc->nb_streams - 1];
    2544         418 :     sc = st->priv_data;
    2545             : 
    2546         418 :     avio_r8(pb); /* version */
    2547         418 :     avio_rb24(pb); /* flags */
    2548         418 :     entries = avio_rb32(pb);
    2549             : 
    2550         418 :     if (entries <= 0) {
    2551           0 :         av_log(c->fc, AV_LOG_ERROR, "invalid STSD entries %d\n", entries);
    2552           0 :         return AVERROR_INVALIDDATA;
    2553             :     }
    2554             : 
    2555         418 :     if (sc->extradata) {
    2556           0 :         av_log(c->fc, AV_LOG_ERROR,
    2557             :                "Duplicate stsd found in this track.\n");
    2558           0 :         return AVERROR_INVALIDDATA;
    2559             :     }
    2560             : 
    2561             :     /* Prepare space for hosting multiple extradata. */
    2562         418 :     sc->extradata = av_mallocz_array(entries, sizeof(*sc->extradata));
    2563         418 :     if (!sc->extradata)
    2564           0 :         return AVERROR(ENOMEM);
    2565             : 
    2566         418 :     sc->extradata_size = av_mallocz_array(entries, sizeof(*sc->extradata_size));
    2567         418 :     if (!sc->extradata_size) {
    2568           0 :         ret = AVERROR(ENOMEM);
    2569           0 :         goto fail;
    2570             :     }
    2571             : 
    2572         418 :     ret = ff_mov_read_stsd_entries(c, pb, entries);
    2573         418 :     if (ret < 0)
    2574           0 :         goto fail;
    2575             : 
    2576             :     /* Restore back the primary extradata. */
    2577         418 :     av_freep(&st->codecpar->extradata);
    2578         418 :     st->codecpar->extradata_size = sc->extradata_size[0];
    2579         418 :     if (sc->extradata_size[0]) {
    2580         232 :         st->codecpar->extradata = av_mallocz(sc->extradata_size[0] + AV_INPUT_BUFFER_PADDING_SIZE);
    2581         232 :         if (!st->codecpar->extradata)
    2582           0 :             return AVERROR(ENOMEM);
    2583         232 :         memcpy(st->codecpar->extradata, sc->extradata[0], sc->extradata_size[0]);
    2584             :     }
    2585             : 
    2586         418 :     return mov_finalize_stsd_codec(c, pb, st, sc);
    2587           0 : fail:
    2588           0 :     av_freep(&sc->extradata);
    2589           0 :     av_freep(&sc->extradata_size);
    2590           0 :     return ret;
    2591             : }
    2592             : 
    2593         418 : static int mov_read_stsc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
    2594             : {
    2595             :     AVStream *st;
    2596             :     MOVStreamContext *sc;
    2597             :     unsigned int i, entries;
    2598             : 
    2599         418 :     if (c->fc->nb_streams < 1)
    2600           0 :         return 0;
    2601         418 :     st = c->fc->streams[c->fc->nb_streams-1];
    2602         418 :     sc = st->priv_data;
    2603             : 
    2604         418 :     avio_r8(pb); /* version */
    2605         418 :     avio_rb24(pb); /* flags */
    2606             : 
    2607         418 :     entries = avio_rb32(pb);
    2608         418 :     if ((uint64_t)entries * 12 + 4 > atom.size)
    2609           0 :         return AVERROR_INVALIDDATA;
    2610             : 
    2611         418 :     av_log(c->fc, AV_LOG_TRACE, "track[%u].stsc.entries = %u\n", c->fc->nb_streams - 1, entries);
    2612             : 
    2613         418 :     if (!entries)
    2614           9 :         return 0;
    2615         409 :     if (sc->stsc_data)
    2616           0 :         av_log(c->fc, AV_LOG_WARNING, "Duplicated STSC atom\n");
    2617         409 :     av_free(sc->stsc_data);
    2618         409 :     sc->stsc_count = 0;
    2619         409 :     sc->stsc_data = av_malloc_array(entries, sizeof(*sc->stsc_data));
    2620         409 :     if (!sc->stsc_data)
    2621           0 :         return AVERROR(ENOMEM);
    2622             : 
    2623        3487 :     for (i = 0; i < entries && !pb->eof_reached; i++) {
    2624        3078 :         sc->stsc_data[i].first = avio_rb32(pb);
    2625        3078 :         sc->stsc_data[i].count = avio_rb32(pb);
    2626        3078 :         sc->stsc_data[i].id = avio_rb32(pb);
    2627             :     }
    2628             : 
    2629         409 :     sc->stsc_count = i;
    2630             : 
    2631         409 :     if (pb->eof_reached) {
    2632           0 :         av_log(c->fc, AV_LOG_WARNING, "reached eof, corrupted STSC atom\n");
    2633           0 :         return AVERROR_EOF;
    2634             :     }
    2635             : 
    2636         409 :     return 0;
    2637             : }
    2638             : 
    2639      168098 : static inline int mov_stsc_index_valid(unsigned int index, unsigned int count)
    2640             : {
    2641      168098 :     return index < count - 1;
    2642             : }
    2643             : 
    2644             : /* Compute the samples value for the stsc entry at the given index. */
    2645       43139 : static inline int mov_get_stsc_samples(MOVStreamContext *sc, unsigned int index)
    2646             : {
    2647             :     int chunk_count;
    2648             : 
    2649       43139 :     if (mov_stsc_index_valid(index, sc->stsc_count))
    2650       43003 :         chunk_count = sc->stsc_data[index + 1].first - sc->stsc_data[index].first;
    2651             :     else
    2652         136 :         chunk_count = sc->chunk_count - (sc->stsc_data[index].first - 1);
    2653             : 
    2654       43139 :     return sc->stsc_data[index].count * chunk_count;
    2655             : }
    2656             : 
    2657           0 : static int mov_read_stps(MOVContext *c, AVIOContext *pb, MOVAtom atom)
    2658             : {
    2659             :     AVStream *st;
    2660             :     MOVStreamContext *sc;
    2661             :     unsigned i, entries;
    2662             : 
    2663           0 :     if (c->fc->nb_streams < 1)
    2664           0 :         return 0;
    2665           0 :     st = c->fc->streams[c->fc->nb_streams-1];
    2666           0 :     sc = st->priv_data;
    2667             : 
    2668           0 :     avio_rb32(pb); // version + flags
    2669             : 
    2670           0 :     entries = avio_rb32(pb);
    2671           0 :     if (sc->stps_data)
    2672           0 :         av_log(c->fc, AV_LOG_WARNING, "Duplicated STPS atom\n");
    2673           0 :     av_free(sc->stps_data);
    2674           0 :     sc->stps_count = 0;
    2675           0 :     sc->stps_data = av_malloc_array(entries, sizeof(*sc->stps_data));
    2676           0 :     if (!sc->stps_data)
    2677           0 :         return AVERROR(ENOMEM);
    2678             : 
    2679           0 :     for (i = 0; i < entries && !pb->eof_reached; i++) {
    2680           0 :         sc->stps_data[i] = avio_rb32(pb);
    2681             :     }
    2682             : 
    2683           0 :     sc->stps_count = i;
    2684             : 
    2685           0 :     if (pb->eof_reached) {
    2686           0 :         av_log(c->fc, AV_LOG_WARNING, "reached eof, corrupted STPS atom\n");
    2687           0 :         return AVERROR_EOF;
    2688             :     }
    2689             : 
    2690           0 :     return 0;
    2691             : }
    2692             : 
    2693          85 : static int mov_read_stss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
    2694             : {
    2695             :     AVStream *st;
    2696             :     MOVStreamContext *sc;
    2697             :     unsigned int i, entries;
    2698             : 
    2699          85 :     if (c->fc->nb_streams < 1)
    2700           0 :         return 0;
    2701          85 :     st = c->fc->streams[c->fc->nb_streams-1];
    2702          85 :     sc = st->priv_data;
    2703             : 
    2704          85 :     avio_r8(pb); /* version */
    2705          85 :     avio_rb24(pb); /* flags */
    2706             : 
    2707          85 :     entries = avio_rb32(pb);
    2708             : 
    2709          85 :     av_log(c->fc, AV_LOG_TRACE, "keyframe_count = %u\n", entries);
    2710             : 
    2711          85 :     if (!entries)
    2712             :     {
    2713           3 :         sc->keyframe_absent = 1;
    2714           3 :         if (!st->need_parsing && st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
    2715           3 :             st->need_parsing = AVSTREAM_PARSE_HEADERS;
    2716           3 :         return 0;
    2717             :     }
    2718          82 :     if (sc->keyframes)
    2719           0 :         av_log(c->fc, AV_LOG_WARNING, "Duplicated STSS atom\n");
    2720          82 :     if (entries >= UINT_MAX / sizeof(int))
    2721           0 :         return AVERROR_INVALIDDATA;
    2722          82 :     av_freep(&sc->keyframes);
    2723          82 :     sc->keyframe_count = 0;
    2724          82 :     sc->keyframes = av_malloc_array(entries, sizeof(*sc->keyframes));
    2725          82 :     if (!sc->keyframes)
    2726           0 :         return AVERROR(ENOMEM);
    2727             : 
    2728        2830 :     for (i = 0; i < entries && !pb->eof_reached; i++) {
    2729        2748 :         sc->keyframes[i] = avio_rb32(pb);
    2730             :     }
    2731             : 
    2732          82 :     sc->keyframe_count = i;
    2733             : 
    2734          82 :     if (pb->eof_reached) {
    2735           0 :         av_log(c->fc, AV_LOG_WARNING, "reached eof, corrupted STSS atom\n");
    2736           0 :         return AVERROR_EOF;
    2737             :     }
    2738             : 
    2739          82 :     return 0;
    2740             : }
    2741             : 
    2742         418 : static int mov_read_stsz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
    2743             : {
    2744             :     AVStream *st;
    2745             :     MOVStreamContext *sc;
    2746             :     unsigned int i, entries, sample_size, field_size, num_bytes;
    2747             :     GetBitContext gb;
    2748             :     unsigned char* buf;
    2749             :     int ret;
    2750             : 
    2751         418 :     if (c->fc->nb_streams < 1)
    2752           0 :         return 0;
    2753         418 :     st = c->fc->streams[c->fc->nb_streams-1];
    2754         418 :     sc = st->priv_data;
    2755             : 
    2756         418 :     avio_r8(pb); /* version */
    2757         418 :     avio_rb24(pb); /* flags */
    2758             : 
    2759         418 :     if (atom.type == MKTAG('s','t','s','z')) {
    2760         418 :         sample_size = avio_rb32(pb);
    2761         418 :         if (!sc->sample_size) /* do not overwrite value computed in stsd */
    2762         388 :             sc->sample_size = sample_size;
    2763         418 :         sc->stsz_sample_size = sample_size;
    2764         418 :         field_size = 32;
    2765             :     } else {
    2766           0 :         sample_size = 0;
    2767           0 :         avio_rb24(pb); /* reserved */
    2768           0 :         field_size = avio_r8(pb);
    2769             :     }
    2770         418 :     entries = avio_rb32(pb);
    2771             : 
    2772         418 :     av_log(c->fc, AV_LOG_TRACE, "sample_size = %u sample_count = %u\n", sc->sample_size, entries);
    2773             : 
    2774         418 :     sc->sample_count = entries;
    2775         418 :     if (sample_size)
    2776         147 :         return 0;
    2777             : 
    2778         271 :     if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) {
    2779           0 :         av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %u\n", field_size);
    2780           0 :         return AVERROR_INVALIDDATA;
    2781             :     }
    2782             : 
    2783         271 :     if (!entries)
    2784           9 :         return 0;
    2785         262 :     if (entries >= (UINT_MAX - 4) / field_size)
    2786           0 :         return AVERROR_INVALIDDATA;
    2787         262 :     if (sc->sample_sizes)
    2788           0 :         av_log(c->fc, AV_LOG_WARNING, "Duplicated STSZ atom\n");
    2789         262 :     av_free(sc->sample_sizes);
    2790         262 :     sc->sample_count = 0;
    2791         262 :     sc->sample_sizes = av_malloc_array(entries, sizeof(*sc->sample_sizes));
    2792         262 :     if (!sc->sample_sizes)
    2793           0 :         return AVERROR(ENOMEM);
    2794             : 
    2795         262 :     num_bytes = (entries*field_size+4)>>3;
    2796             : 
    2797         262 :     buf = av_malloc(num_bytes+AV_INPUT_BUFFER_PADDING_SIZE);
    2798         262 :     if (!buf) {
    2799           0 :         av_freep(&sc->sample_sizes);
    2800           0 :         return AVERROR(ENOMEM);
    2801             :     }
    2802             : 
    2803         262 :     ret = ffio_read_size(pb, buf, num_bytes);
    2804         262 :     if (ret < 0) {
    2805           0 :         av_freep(&sc->sample_sizes);
    2806           0 :         av_free(buf);
    2807           0 :         return ret;
    2808             :     }
    2809             : 
    2810         262 :     init_get_bits(&gb, buf, 8*num_bytes);
    2811             : 
    2812       76478 :     for (i = 0; i < entries && !pb->eof_reached; i++) {
    2813       76216 :         sc->sample_sizes[i] = get_bits_long(&gb, field_size);
    2814       76216 :         sc->data_size += sc->sample_sizes[i];
    2815             :     }
    2816             : 
    2817         262 :     sc->sample_count = i;
    2818             : 
    2819         262 :     av_free(buf);
    2820             : 
    2821         262 :     if (pb->eof_reached) {
    2822           0 :         av_log(c->fc, AV_LOG_WARNING, "reached eof, corrupted STSZ atom\n");
    2823           0 :         return AVERROR_EOF;
    2824             :     }
    2825             : 
    2826         262 :     return 0;
    2827             : }
    2828             : 
    2829         418 : static int mov_read_stts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
    2830             : {
    2831             :     AVStream *st;
    2832             :     MOVStreamContext *sc;
    2833             :     unsigned int i, entries;
    2834         418 :     int64_t duration=0;
    2835         418 :     int64_t total_sample_count=0;
    2836             : 
    2837         418 :     if (c->fc->nb_streams < 1)
    2838           0 :         return 0;
    2839         418 :     st = c->fc->streams[c->fc->nb_streams-1];
    2840         418 :     sc = st->priv_data;
    2841             : 
    2842         418 :     avio_r8(pb); /* version */
    2843         418 :     avio_rb24(pb); /* flags */
    2844         418 :     entries = avio_rb32(pb);
    2845             : 
    2846         418 :     av_log(c->fc, AV_LOG_TRACE, "track[%u].stts.entries = %u\n",
    2847         418 :             c->fc->nb_streams-1, entries);
    2848             : 
    2849         418 :     if (sc->stts_data)
    2850           0 :         av_log(c->fc, AV_LOG_WARNING, "Duplicated STTS atom\n");
    2851         418 :     av_free(sc->stts_data);
    2852         418 :     sc->stts_count = 0;
    2853         418 :     sc->stts_data = av_malloc_array(entries, sizeof(*sc->stts_data));
    2854         418 :     if (!sc->stts_data)
    2855           0 :         return AVERROR(ENOMEM);
    2856             : 
    2857        2596 :     for (i = 0; i < entries && !pb->eof_reached; i++) {
    2858             :         int sample_duration;
    2859             :         unsigned int sample_count;
    2860             : 
    2861        2178 :         sample_count=avio_rb32(pb);
    2862        2178 :         sample_duration = avio_rb32(pb);
    2863             : 
    2864        2178 :         sc->stts_data[i].count= sample_count;
    2865        2178 :         sc->stts_data[i].duration= sample_duration;
    2866             : 
    2867        2178 :         av_log(c->fc, AV_LOG_TRACE, "sample_count=%d, sample_duration=%d\n",
    2868             :                 sample_count, sample_duration);
    2869             : 
    2870        2178 :         if (   i+1 == entries
    2871         409 :             && i
    2872          59 :             && sample_count == 1
    2873          51 :             && total_sample_count > 100
    2874          27 :             && sample_duration/10 > duration / total_sample_count)
    2875           0 :             sample_duration = duration / total_sample_count;
    2876        2178 :         duration+=(int64_t)sample_duration*sample_count;
    2877        2178 :         total_sample_count+=sample_count;
    2878             :     }
    2879             : 
    2880         418 :     sc->stts_count = i;
    2881             : 
    2882         418 :     sc->duration_for_fps  += duration;
    2883         418 :     sc->nb_frames_for_fps += total_sample_count;
    2884             : 
    2885         418 :     if (pb->eof_reached) {
    2886           0 :         av_log(c->fc, AV_LOG_WARNING, "reached eof, corrupted STTS atom\n");
    2887           0 :         return AVERROR_EOF;
    2888             :     }
    2889             : 
    2890         418 :     st->nb_frames= total_sample_count;
    2891         418 :     if (duration)
    2892         409 :         st->duration= duration;
    2893         418 :     sc->track_end = duration;
    2894         418 :     return 0;
    2895             : }
    2896             : 
    2897        8862 : static void mov_update_dts_shift(MOVStreamContext *sc, int duration)
    2898             : {
    2899        8862 :     if (duration < 0) {
    2900         654 :         if (duration == INT_MIN) {
    2901           0 :             av_log(NULL, AV_LOG_WARNING, "mov_update_dts_shift(): dts_shift set to %d\n", INT_MAX);
    2902           0 :             duration++;
    2903             :         }
    2904         654 :         sc->dts_shift = FFMAX(sc->dts_shift, -duration);
    2905             :     }
    2906        8862 : }
    2907             : 
    2908          32 : static int mov_read_ctts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
    2909             : {
    2910             :     AVStream *st;
    2911             :     MOVStreamContext *sc;
    2912          32 :     unsigned int i, entries, ctts_count = 0;
    2913             : 
    2914          32 :     if (c->fc->nb_streams < 1)
    2915           0 :         return 0;
    2916          32 :     st = c->fc->streams[c->fc->nb_streams-1];
    2917          32 :     sc = st->priv_data;
    2918             : 
    2919          32 :     avio_r8(pb); /* version */
    2920          32 :     avio_rb24(pb); /* flags */
    2921          32 :     entries = avio_rb32(pb);
    2922             : 
    2923          32 :     av_log(c->fc, AV_LOG_TRACE, "track[%u].ctts.entries = %u\n", c->fc->nb_streams - 1, entries);
    2924             : 
    2925          32 :     if (!entries)
    2926           4 :         return 0;
    2927          28 :     if (entries >= UINT_MAX / sizeof(*sc->ctts_data))
    2928           0 :         return AVERROR_INVALIDDATA;
    2929          28 :     av_freep(&sc->ctts_data);
    2930          28 :     sc->ctts_data = av_fast_realloc(NULL, &sc->ctts_allocated_size, entries * sizeof(*sc->ctts_data));
    2931          28 :     if (!sc->ctts_data)
    2932           0 :         return AVERROR(ENOMEM);
    2933             : 
    2934        3084 :     for (i = 0; i < entries && !pb->eof_reached; i++) {
    2935        3056 :         int count    =avio_rb32(pb);
    2936        3056 :         int duration =avio_rb32(pb);
    2937             : 
    2938        3056 :         if (count <= 0) {
    2939           0 :             av_log(c->fc, AV_LOG_TRACE,
    2940             :                    "ignoring CTTS entry with count=%d duration=%d\n",
    2941             :                    count, duration);
    2942           0 :             continue;
    2943             :         }
    2944             : 
    2945        3056 :         add_ctts_entry(&sc->ctts_data, &ctts_count, &sc->ctts_allocated_size,
    2946             :                        count, duration);
    2947             : 
    2948        3056 :         av_log(c->fc, AV_LOG_TRACE, "count=%d, duration=%d\n",
    2949             :                 count, duration);
    2950             : 
    2951        3056 :         if (FFNABS(duration) < -(1<<28) && i+2<entries) {
    2952           0 :             av_log(c->fc, AV_LOG_WARNING, "CTTS invalid\n");
    2953           0 :             av_freep(&sc->ctts_data);
    2954           0 :             sc->ctts_count = 0;
    2955           0 :             return 0;
    2956             :         }
    2957             : 
    2958        3056 :         if (i+2<entries)
    2959        3002 :             mov_update_dts_shift(sc, duration);
    2960             :     }
    2961             : 
    2962          28 :     sc->ctts_count = ctts_count;
    2963             : 
    2964          28 :     if (pb->eof_reached) {
    2965           0 :         av_log(c->fc, AV_LOG_WARNING, "reached eof, corrupted CTTS atom\n");
    2966           0 :         return AVERROR_EOF;
    2967             :     }
    2968             : 
    2969          28 :     av_log(c->fc, AV_LOG_TRACE, "dts shift %d\n", sc->dts_shift);
    2970             : 
    2971          28 :     return 0;
    2972             : }
    2973             : 
    2974          13 : static int mov_read_sbgp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
    2975             : {
    2976             :     AVStream *st;
    2977             :     MOVStreamContext *sc;
    2978             :     unsigned int i, entries;
    2979             :     uint8_t version;
    2980             :     uint32_t grouping_type;
    2981             : 
    2982          13 :     if (c->fc->nb_streams < 1)
    2983           0 :         return 0;
    2984          13 :     st = c->fc->streams[c->fc->nb_streams-1];
    2985          13 :     sc = st->priv_data;
    2986             : 
    2987          13 :     version = avio_r8(pb); /* version */
    2988          13 :     avio_rb24(pb); /* flags */
    2989          13 :     grouping_type = avio_rl32(pb);
    2990          13 :     if (grouping_type != MKTAG( 'r','a','p',' '))
    2991          12 :         return 0; /* only support 'rap ' grouping */
    2992           1 :     if (version == 1)
    2993           0 :         avio_rb32(pb); /* grouping_type_parameter */
    2994             : 
    2995           1 :     entries = avio_rb32(pb);
    2996           1 :     if (!entries)
    2997           0 :         return 0;
    2998           1 :     if (sc->rap_group)
    2999           0 :         av_log(c->fc, AV_LOG_WARNING, "Duplicated SBGP atom\n");
    3000           1 :     av_free(sc->rap_group);
    3001           1 :     sc->rap_group_count = 0;
    3002           1 :     sc->rap_group = av_malloc_array(entries, sizeof(*sc->rap_group));
    3003           1 :     if (!sc->rap_group)
    3004           0 :         return AVERROR(ENOMEM);
    3005             : 
    3006           5 :     for (i = 0; i < entries && !pb->eof_reached; i++) {
    3007           4 :         sc->rap_group[i].count = avio_rb32(pb); /* sample_count */
    3008           4 :         sc->rap_group[i].index = avio_rb32(pb); /* group_description_index */
    3009             :     }
    3010             : 
    3011           1 :     sc->rap_group_count = i;
    3012             : 
    3013           1 :     if (pb->eof_reached) {
    3014           0 :         av_log(c->fc, AV_LOG_WARNING, "reached eof, corrupted SBGP atom\n");
    3015           0 :         return AVERROR_EOF;
    3016             :     }
    3017             : 
    3018           1 :     return 0;
    3019             : }
    3020             : 
    3021             : /**
    3022             :  * Get ith edit list entry (media time, duration).
    3023             :  */
    3024         582 : static int get_edit_list_entry(MOVContext *mov,
    3025             :                                const MOVStreamContext *msc,
    3026             :                                unsigned int edit_list_index,
    3027             :                                int64_t *edit_list_media_time,
    3028             :                                int64_t *edit_list_duration,
    3029             :                                int64_t global_timescale)
    3030             : {
    3031         582 :     if (edit_list_index == msc->elst_count) {
    3032         279 :         return 0;
    3033             :     }
    3034         303 :     *edit_list_media_time = msc->elst_data[edit_list_index].time;
    3035         303 :     *edit_list_duration = msc->elst_data[edit_list_index].duration;
    3036             : 
    3037             :     /* duration is in global timescale units;convert to msc timescale */
    3038         303 :     if (global_timescale == 0) {
    3039           0 :       avpriv_request_sample(mov->fc, "Support for mvhd.timescale = 0 with editlists");
    3040           0 :       return 0;
    3041             :     }
    3042         303 :     *edit_list_duration = av_rescale(*edit_list_duration, msc->time_scale,
    3043             :                                      global_timescale);
    3044         303 :     return 1;
    3045             : }
    3046             : 
    3047             : /**
    3048             :  * Find the closest previous frame to the timestamp_pts, in e_old index
    3049             :  * entries. Searching for just any frame / just key frames can be controlled by
    3050             :  * last argument 'flag'.
    3051             :  * Note that if ctts_data is not NULL, we will always search for a key frame
    3052             :  * irrespective of the value of 'flag'. If we don't find any keyframe, we will
    3053             :  * return the first frame of the video.
    3054             :  *
    3055             :  * Here the timestamp_pts is considered to be a presentation timestamp and
    3056             :  * the timestamp of index entries are considered to be decoding timestamps.
    3057             :  *
    3058             :  * Returns 0 if successful in finding a frame, else returns -1.
    3059             :  * Places the found index corresponding output arg.
    3060             :  *
    3061             :  * If ctts_old is not NULL, then refines the searched entry by searching
    3062             :  * backwards from the found timestamp, to find the frame with correct PTS.
    3063             :  *
    3064             :  * Places the found ctts_index and ctts_sample in corresponding output args.
    3065             :  */
    3066         305 : static int find_prev_closest_index(AVStream *st,
    3067             :                                    AVIndexEntry *e_old,
    3068             :                                    int nb_old,
    3069             :                                    MOVStts* ctts_data,
    3070             :                                    int64_t ctts_count,
    3071             :                                    int64_t timestamp_pts,
    3072             :                                    int flag,
    3073             :                                    int64_t* index,
    3074             :                                    int64_t* ctts_index,
    3075             :                                    int64_t* ctts_sample)
    3076             : {
    3077         305 :     MOVStreamContext *msc = st->priv_data;
    3078         305 :     AVIndexEntry *e_keep = st->index_entries;
    3079         305 :     int nb_keep = st->nb_index_entries;
    3080         305 :     int64_t i = 0;
    3081             :     int64_t index_ctts_count;
    3082             : 
    3083         305 :     av_assert0(index);
    3084             : 
    3085             :     // If dts_shift > 0, then all the index timestamps will have to be offset by
    3086             :     // at least dts_shift amount to obtain PTS.
    3087             :     // Hence we decrement the searched timestamp_pts by dts_shift to find the closest index element.
    3088         305 :     if (msc->dts_shift > 0) {
    3089           2 :         timestamp_pts -= msc->dts_shift;
    3090             :     }
    3091             : 
    3092         305 :     st->index_entries = e_old;
    3093         305 :     st->nb_index_entries = nb_old;
    3094         305 :     *index = av_index_search_timestamp(st, timestamp_pts, flag | AVSEEK_FLAG_BACKWARD);
    3095             : 
    3096             :     // Keep going backwards in the index entries until the timestamp is the same.
    3097         305 :     if (*index >= 0) {
    3098         608 :         for (i = *index; i > 0 && e_old[i].timestamp == e_old[i - 1].timestamp;
    3099           0 :              i--) {
    3100           0 :             if ((flag & AVSEEK_FLAG_ANY) ||
    3101           0 :                 (e_old[i - 1].flags & AVINDEX_KEYFRAME)) {
    3102           0 :                 *index = i - 1;
    3103             :             }
    3104             :         }
    3105             :     }
    3106             : 
    3107             :     // If we have CTTS then refine the search, by searching backwards over PTS
    3108             :     // computed by adding corresponding CTTS durations to index timestamps.
    3109         305 :     if (ctts_data && *index >= 0) {
    3110          33 :         av_assert0(ctts_index);
    3111          33 :         av_assert0(ctts_sample);
    3112             :         // Find out the ctts_index for the found frame.
    3113          33 :         *ctts_index = 0;
    3114          33 :         *ctts_sample = 0;
    3115         207 :         for (index_ctts_count = 0; index_ctts_count < *index; index_ctts_count++) {
    3116         174 :             if (*ctts_index < ctts_count) {
    3117         174 :                 (*ctts_sample)++;
    3118         174 :                 if (ctts_data[*ctts_index].count == *ctts_sample) {
    3119         174 :                     (*ctts_index)++;
    3120         174 :                     *ctts_sample = 0;
    3121             :                 }
    3122             :             }
    3123             :         }
    3124             : 
    3125          77 :         while (*index >= 0 && (*ctts_index) >= 0) {
    3126             :             // Find a "key frame" with PTS <= timestamp_pts (So that we can decode B-frames correctly).
    3127             :             // No need to add dts_shift to the timestamp here becase timestamp_pts has already been
    3128             :             // compensated by dts_shift above.
    3129          71 :             if ((e_old[*index].timestamp + ctts_data[*ctts_index].duration) <= timestamp_pts &&
    3130          32 :                 (e_old[*index].flags & AVINDEX_KEYFRAME)) {
    3131          28 :                 break;
    3132             :             }
    3133             : 
    3134          11 :             (*index)--;
    3135          11 :             if (*ctts_sample == 0) {
    3136          11 :                 (*ctts_index)--;
    3137          11 :                 if (*ctts_index >= 0)
    3138           6 :                   *ctts_sample = ctts_data[*ctts_index].count - 1;
    3139             :             } else {
    3140           0 :                 (*ctts_sample)--;
    3141             :             }
    3142             :         }
    3143             :     }
    3144             : 
    3145             :     /* restore AVStream state*/
    3146         305 :     st->index_entries = e_keep;
    3147         305 :     st->nb_index_entries = nb_keep;
    3148         305 :     return *index >= 0 ? 0 : -1;
    3149             : }
    3150             : 
    3151             : /**
    3152             :  * Add index entry with the given values, to the end of st->index_entries.
    3153             :  * Returns the new size st->index_entries if successful, else returns -1.
    3154             :  *
    3155             :  * This function is similar to ff_add_index_entry in libavformat/utils.c
    3156             :  * except that here we are always unconditionally adding an index entry to
    3157             :  * the end, instead of searching the entries list and skipping the add if
    3158             :  * there is an existing entry with the same timestamp.
    3159             :  * This is needed because the mov_fix_index calls this func with the same
    3160             :  * unincremented timestamp for successive discarded frames.
    3161             :  */
    3162       67402 : static int64_t add_index_entry(AVStream *st, int64_t pos, int64_t timestamp,
    3163             :                                int size, int distance, int flags)
    3164             : {
    3165             :     AVIndexEntry *entries, *ie;
    3166       67402 :     int64_t index = -1;
    3167       67402 :     const size_t min_size_needed = (st->nb_index_entries + 1) * sizeof(AVIndexEntry);
    3168             : 
    3169             :     // Double the allocation each time, to lower memory fragmentation.
    3170             :     // Another difference from ff_add_index_entry function.
    3171       67402 :     const size_t requested_size =
    3172       67402 :         min_size_needed > st->index_entries_allocated_size ?
    3173       67402 :         FFMAX(min_size_needed, 2 * st->index_entries_allocated_size) :
    3174             :         min_size_needed;
    3175             : 
    3176       67402 :     if((unsigned)st->nb_index_entries + 1 >= UINT_MAX / sizeof(AVIndexEntry))
    3177           0 :         return -1;
    3178             : 
    3179       67402 :     entries = av_fast_realloc(st->index_entries,
    3180             :                               &st->index_entries_allocated_size,
    3181             :                               requested_size);
    3182       67402 :     if(!entries)
    3183           0 :         return -1;
    3184             : 
    3185       67402 :     st->index_entries= entries;
    3186             : 
    3187       67402 :     index= st->nb_index_entries++;
    3188       67402 :     ie= &entries[index];
    3189             : 
    3190       67402 :     ie->pos = pos;
    3191       67402 :     ie->timestamp = timestamp;
    3192       67402 :     ie->min_distance= distance;
    3193       67402 :     ie->size= size;
    3194       67402 :     ie->flags = flags;
    3195       67402 :     return index;
    3196             : }
    3197             : 
    3198             : /**
    3199             :  * Rewrite timestamps of index entries in the range [end_index - frame_duration_buffer_size, end_index)
    3200             :  * by subtracting end_ts successively by the amounts given in frame_duration_buffer.
    3201             :  */
    3202           9 : static void fix_index_entry_timestamps(AVStream* st, int end_index, int64_t end_ts,
    3203             :                                        int64_t* frame_duration_buffer,
    3204             :                                        int frame_duration_buffer_size) {
    3205           9 :     int i = 0;
    3206           9 :     av_assert0(end_index >= 0 && end_index <= st->nb_index_entries);
    3207          20 :     for (i = 0; i < frame_duration_buffer_size; i++) {
    3208          11 :         end_ts -= frame_duration_buffer[frame_duration_buffer_size - 1 - i];
    3209          11 :         st->index_entries[end_index - 1 - i].timestamp = end_ts;
    3210             :     }
    3211           9 : }
    3212             : 
    3213             : /**
    3214             :  * Append a new ctts entry to ctts_data.
    3215             :  * Returns the new ctts_count if successful, else returns -1.
    3216             :  */
    3217        9819 : static int64_t add_ctts_entry(MOVStts** ctts_data, unsigned int* ctts_count, unsigned int* allocated_size,
    3218             :                               int count, int duration)
    3219             : {
    3220             :     MOVStts *ctts_buf_new;
    3221        9819 :     const size_t min_size_needed = (*ctts_count + 1) * sizeof(MOVStts);
    3222        9819 :     const size_t requested_size =
    3223        9819 :         min_size_needed > *allocated_size ?
    3224        9819 :         FFMAX(min_size_needed, 2 * (*allocated_size)) :
    3225             :         min_size_needed;
    3226             : 
    3227        9819 :     if((unsigned)(*ctts_count) + 1 >= UINT_MAX / sizeof(MOVStts))
    3228           0 :         return -1;
    3229             : 
    3230        9819 :     ctts_buf_new = av_fast_realloc(*ctts_data, allocated_size, requested_size);
    3231             : 
    3232        9819 :     if(!ctts_buf_new)
    3233           0 :         return -1;
    3234             : 
    3235        9819 :     *ctts_data = ctts_buf_new;
    3236             : 
    3237        9819 :     ctts_buf_new[*ctts_count].count = count;
    3238        9819 :     ctts_buf_new[*ctts_count].duration = duration;
    3239             : 
    3240        9819 :     *ctts_count = (*ctts_count) + 1;
    3241        9819 :     return *ctts_count;
    3242             : }
    3243             : 
    3244       86912 : static void mov_current_sample_inc(MOVStreamContext *sc)
    3245             : {
    3246       86912 :     sc->current_sample++;
    3247       86912 :     sc->current_index++;
    3248      133879 :     if (sc->index_ranges &&
    3249       47264 :         sc->current_index >= sc->current_index_range->end &&
    3250         297 :         sc->current_index_range->end) {
    3251         297 :         sc->current_index_range++;
    3252         297 :         sc->current_index = sc->current_index_range->start;
    3253             :     }
    3254       86912 : }
    3255             : 
    3256           0 : static void mov_current_sample_dec(MOVStreamContext *sc)
    3257             : {
    3258           0 :     sc->current_sample--;
    3259           0 :     sc->current_index--;
    3260           0 :     if (sc->index_ranges &&
    3261           0 :         sc->current_index < sc->current_index_range->start &&
    3262           0 :         sc->current_index_range > sc->index_ranges) {
    3263           0 :         sc->current_index_range--;
    3264           0 :         sc->current_index = sc->current_index_range->end - 1;
    3265             :     }
    3266           0 : }
    3267             : 
    3268         261 : static void mov_current_sample_set(MOVStreamContext *sc, int current_sample)
    3269             : {
    3270             :     int64_t range_size;
    3271             : 
    3272         261 :     sc->current_sample = current_sample;
    3273         261 :     sc->current_index = current_sample;
    3274         261 :     if (!sc->index_ranges) {
    3275          26 :         return;
    3276             :     }
    3277             : 
    3278         470 :     for (sc->current_index_range = sc->index_ranges;
    3279         235 :         sc->current_index_range->end;
    3280           0 :         sc->current_index_range++) {
    3281         235 :         range_size = sc->current_index_range->end - sc->current_index_range->start;
    3282         235 :         if (range_size > current_sample) {
    3283         235 :             sc->current_index = sc->current_index_range->start + current_sample;
    3284         235 :             break;
    3285             :         }
    3286           0 :         current_sample -= range_size;
    3287             :     }
    3288             : }
    3289             : 
    3290             : /**
    3291             :  * Fix st->index_entries, so that it contains only the entries (and the entries
    3292             :  * which are needed to decode them) that fall in the edit list time ranges.
    3293             :  * Also fixes the timestamps of the index entries to match the timeline
    3294             :  * specified the edit lists.
    3295             :  */
    3296         409 : static void mov_fix_index(MOVContext *mov, AVStream *st)
    3297             : {
    3298         409 :     MOVStreamContext *msc = st->priv_data;
    3299         409 :     AVIndexEntry *e_old = st->index_entries;
    3300         409 :     int nb_old = st->nb_index_entries;
    3301         409 :     const AVIndexEntry *e_old_end = e_old + nb_old;
    3302         409 :     const AVIndexEntry *current = NULL;
    3303         409 :     MOVStts *ctts_data_old = msc->ctts_data;
    3304         409 :     int64_t ctts_index_old = 0;
    3305         409 :     int64_t ctts_sample_old = 0;
    3306         409 :     int64_t ctts_count_old = msc->ctts_count;
    3307         409 :     int64_t edit_list_media_time = 0;
    3308         409 :     int64_t edit_list_duration = 0;
    3309         409 :     int64_t frame_duration = 0;
    3310         409 :     int64_t edit_list_dts_counter = 0;
    3311         409 :     int64_t edit_list_dts_entry_end = 0;
    3312         409 :     int64_t edit_list_start_ctts_sample = 0;
    3313             :     int64_t curr_cts;
    3314         409 :     int64_t curr_ctts = 0;
    3315         409 :     int64_t min_corrected_pts = -1;
    3316         409 :     int64_t empty_edits_sum_duration = 0;
    3317         409 :     int64_t edit_list_index = 0;
    3318             :     int64_t index;
    3319             :     int flags;
    3320         409 :     int64_t start_dts = 0;
    3321         409 :     int64_t edit_list_start_encountered = 0;
    3322         409 :     int64_t search_timestamp = 0;
    3323         409 :     int64_t* frame_duration_buffer = NULL;
    3324         409 :     int num_discarded_begin = 0;
    3325         409 :     int first_non_zero_audio_edit = -1;
    3326         409 :     int packet_skip_samples = 0;
    3327             :     MOVIndexRange *current_index_range;
    3328             :     int i;
    3329         409 :     int found_keyframe_after_edit = 0;
    3330             : 
    3331         409 :     if (!msc->elst_data || msc->elst_count <= 0 || nb_old <= 0) {
    3332         260 :         return;
    3333             :     }
    3334             : 
    3335             :     // allocate the index ranges array
    3336         279 :     msc->index_ranges = av_malloc((msc->elst_count + 1) * sizeof(msc->index_ranges[0]));
    3337         279 :     if (!msc->index_ranges) {
    3338           0 :         av_log(mov->fc, AV_LOG_ERROR, "Cannot allocate index ranges buffer\n");
    3339           0 :         return;
    3340             :     }
    3341         279 :     msc->current_index_range = msc->index_ranges;
    3342         279 :     current_index_range = msc->index_ranges - 1;
    3343             : 
    3344             :     // Clean AVStream from traces of old index
    3345         279 :     st->index_entries = NULL;
    3346         279 :     st->index_entries_allocated_size = 0;
    3347         279 :     st->nb_index_entries = 0;
    3348             : 
    3349             :     // Clean ctts fields of MOVStreamContext
    3350         279 :     msc->ctts_data = NULL;
    3351         279 :     msc->ctts_count = 0;
    3352         279 :     msc->ctts_index = 0;
    3353         279 :     msc->ctts_sample = 0;
    3354         279 :     msc->ctts_allocated_size = 0;
    3355             : 
    3356             :     // If the dts_shift is positive (in case of negative ctts values in mov),
    3357             :     // then negate the DTS by dts_shift
    3358         279 :     if (msc->dts_shift > 0) {
    3359           2 :         edit_list_dts_entry_end -= msc->dts_shift;
    3360           2 :         av_log(mov->fc, AV_LOG_DEBUG, "Shifting DTS by %d because of negative CTTS.\n", msc->dts_shift);
    3361             :     }
    3362             : 
    3363         279 :     start_dts = edit_list_dts_entry_end;
    3364             : 
    3365         861 :     while (get_edit_list_entry(mov, msc, edit_list_index, &edit_list_media_time,
    3366         582 :                                &edit_list_duration, mov->time_scale)) {
    3367         303 :         av_log(mov->fc, AV_LOG_DEBUG, "Processing st: %d, edit list %"PRId64" - media time: %"PRId64", duration: %"PRId64"\n",
    3368             :                st->index, edit_list_index, edit_list_media_time, edit_list_duration);
    3369         303 :         edit_list_index++;
    3370         303 :         edit_list_dts_counter = edit_list_dts_entry_end;
    3371         303 :         edit_list_dts_entry_end += edit_list_duration;
    3372         303 :         num_discarded_begin = 0;
    3373         303 :         if (edit_list_media_time == -1) {
    3374           1 :             empty_edits_sum_duration += edit_list_duration;
    3375           1 :             continue;
    3376             :         }
    3377             : 
    3378             :         // If we encounter a non-negative edit list reset the skip_samples/start_pad fields and set them
    3379             :         // according to the edit list below.
    3380         302 :         if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
    3381          80 :             if (first_non_zero_audio_edit < 0) {
    3382          80 :                 first_non_zero_audio_edit = 1;
    3383             :             } else {
    3384           0 :                 first_non_zero_audio_edit = 0;
    3385             :             }
    3386             : 
    3387          80 :             if (first_non_zero_audio_edit > 0)
    3388          80 :                 st->skip_samples = msc->start_pad = 0;
    3389             :         }
    3390             : 
    3391             :         // While reordering frame index according to edit list we must handle properly
    3392             :         // the scenario when edit list entry starts from none key frame.
    3393             :         // We find closest previous key frame and preserve it and consequent frames in index.
    3394             :         // All frames which are outside edit list entry time boundaries will be dropped after decoding.
    3395         302 :         search_timestamp = edit_list_media_time;
    3396         302 :         if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
    3397             :             // Audio decoders like AAC need need a decoder delay samples previous to the current sample,
    3398             :             // to correctly decode this frame. Hence for audio we seek to a frame 1 sec. before the
    3399             :             // edit_list_media_time to cover the decoder delay.
    3400          80 :             search_timestamp = FFMAX(search_timestamp - msc->time_scale, e_old[0].timestamp);
    3401             :         }
    3402             : 
    3403         302 :         if (find_prev_closest_index(st, e_old, nb_old, ctts_data_old, ctts_count_old, search_timestamp, 0,
    3404             :                                     &index, &ctts_index_old, &ctts_sample_old) < 0) {
    3405           3 :             av_log(mov->fc, AV_LOG_WARNING,
    3406             :                    "st: %d edit list: %"PRId64" Missing key frame while searching for timestamp: %"PRId64"\n",
    3407             :                    st->index, edit_list_index, search_timestamp);
    3408           3 :             if (find_prev_closest_index(st, e_old, nb_old, ctts_data_old, ctts_count_old, search_timestamp, AVSEEK_FLAG_ANY,
    3409             :                                         &index, &ctts_index_old, &ctts_sample_old) < 0) {
    3410           3 :                 av_log(mov->fc, AV_LOG_WARNING,
    3411             :                        "st: %d edit list %"PRId64" Cannot find an index entry before timestamp: %"PRId64".\n",
    3412             :                        st->index, edit_list_index, search_timestamp);
    3413           3 :                 index = 0;
    3414           3 :                 ctts_index_old = 0;
    3415           3 :                 ctts_sample_old = 0;
    3416             :             }
    3417             :         }
    3418         302 :         current = e_old + index;
    3419         302 :         edit_list_start_ctts_sample = ctts_sample_old;
    3420             : 
    3421             :         // Iterate over index and arrange it according to edit list
    3422         302 :         edit_list_start_encountered = 0;
    3423         302 :         found_keyframe_after_edit = 0;
    3424       67466 :         for (; current < e_old_end; current++, index++) {
    3425             :             // check  if frame outside edit list mark it for discard
    3426      134804 :             frame_duration = (current + 1 <  e_old_end) ?
    3427       67402 :                              ((current + 1)->timestamp - current->timestamp) : edit_list_duration;
    3428             : 
    3429       67402 :             flags = current->flags;
    3430             : 
    3431             :             // frames (pts) before or after edit list
    3432       67402 :             curr_cts = current->timestamp + msc->dts_shift;
    3433       67402 :             curr_ctts = 0;
    3434             : 
    3435       67402 :             if (ctts_data_old && ctts_index_old < ctts_count_old) {
    3436        3306 :                 curr_ctts = ctts_data_old[ctts_index_old].duration;
    3437        3306 :                 av_log(mov->fc, AV_LOG_DEBUG, "stts: %"PRId64" ctts: %"PRId64", ctts_index: %"PRId64", ctts_count: %"PRId64"\n",
    3438             :                        curr_cts, curr_ctts, ctts_index_old, ctts_count_old);
    3439        3306 :                 curr_cts += curr_ctts;
    3440        3306 :                 ctts_sample_old++;
    3441        3306 :                 if (ctts_sample_old == ctts_data_old[ctts_index_old].count) {
    3442        6612 :                     if (add_ctts_entry(&msc->ctts_data, &msc->ctts_count,
    3443             :                                        &msc->ctts_allocated_size,
    3444        3306 :                                        ctts_data_old[ctts_index_old].count - edit_list_start_ctts_sample,
    3445        3306 :                                        ctts_data_old[ctts_index_old].duration) == -1) {
    3446           0 :                         av_log(mov->fc, AV_LOG_ERROR, "Cannot add CTTS entry %"PRId64" - {%"PRId64", %d}\n",
    3447             :                                ctts_index_old,
    3448           0 :                                ctts_data_old[ctts_index_old].count - edit_list_start_ctts_sample,
    3449           0 :                                ctts_data_old[ctts_index_old].duration);
    3450           0 :                         break;
    3451             :                     }
    3452        3306 :                     ctts_index_old++;
    3453        3306 :                     ctts_sample_old = 0;
    3454        3306 :                     edit_list_start_ctts_sample = 0;
    3455             :                 }
    3456             :             }
    3457             : 
    3458       67402 :             if (curr_cts < edit_list_media_time || curr_cts >= (edit_list_duration + edit_list_media_time)) {
    3459         339 :                 if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && st->codecpar->codec_id != AV_CODEC_ID_VORBIS &&
    3460          30 :                     curr_cts < edit_list_media_time && curr_cts + frame_duration > edit_list_media_time &&
    3461             :                     first_non_zero_audio_edit > 0) {
    3462           4 :                     packet_skip_samples = edit_list_media_time - curr_cts;
    3463           4 :                     st->skip_samples += packet_skip_samples;
    3464             : 
    3465             :                     // Shift the index entry timestamp by packet_skip_samples to be correct.
    3466           4 :                     edit_list_dts_counter -= packet_skip_samples;
    3467           4 :                     if (edit_list_start_encountered == 0)  {
    3468           4 :                         edit_list_start_encountered = 1;
    3469             :                         // Make timestamps strictly monotonically increasing for audio, by rewriting timestamps for
    3470             :                         // discarded packets.
    3471           4 :                         if (frame_duration_buffer) {
    3472           1 :                             fix_index_entry_timestamps(st, st->nb_index_entries, edit_list_dts_counter,
    3473             :                                                        frame_duration_buffer, num_discarded_begin);
    3474           1 :                             av_freep(&frame_duration_buffer);
    3475             :                         }
    3476             :                     }
    3477             : 
    3478           4 :                     av_log(mov->fc, AV_LOG_DEBUG, "skip %d audio samples from curr_cts: %"PRId64"\n", packet_skip_samples, curr_cts);
    3479             :                 } else {
    3480         158 :                     flags |= AVINDEX_DISCARD_FRAME;
    3481         158 :                     av_log(mov->fc, AV_LOG_DEBUG, "drop a frame at curr_cts: %"PRId64" @ %"PRId64"\n", curr_cts, index);
    3482             : 
    3483         158 :                     if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && edit_list_start_encountered == 0) {
    3484          11 :                         num_discarded_begin++;
    3485          11 :                         frame_duration_buffer = av_realloc(frame_duration_buffer,
    3486             :                                                            num_discarded_begin * sizeof(int64_t));
    3487          11 :                         if (!frame_duration_buffer) {
    3488           0 :                             av_log(mov->fc, AV_LOG_ERROR, "Cannot reallocate frame duration buffer\n");
    3489           0 :                             break;
    3490             :                         }
    3491          11 :                         frame_duration_buffer[num_discarded_begin - 1] = frame_duration;
    3492             : 
    3493             :                         // Increment skip_samples for the first non-zero audio edit list
    3494          11 :                         if (first_non_zero_audio_edit > 0 && st->codecpar->codec_id != AV_CODEC_ID_VORBIS) {
    3495          11 :                             st->skip_samples += frame_duration;
    3496             :                         }
    3497             :                     }
    3498             :                 }
    3499             :             } else {
    3500       67240 :                 if (min_corrected_pts < 0) {
    3501         278 :                     min_corrected_pts = edit_list_dts_counter + curr_ctts + msc->dts_shift;
    3502             :                 } else {
    3503       66962 :                     min_corrected_pts = FFMIN(min_corrected_pts, edit_list_dts_counter + curr_ctts + msc->dts_shift);
    3504             :                 }
    3505       67240 :                 if (edit_list_start_encountered == 0) {
    3506         296 :                     edit_list_start_encountered = 1;
    3507             :                     // Make timestamps strictly monotonically increasing for audio, by rewriting timestamps for
    3508             :                     // discarded packets.
    3509         296 :                     if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && frame_duration_buffer) {
    3510           8 :                         fix_index_entry_timestamps(st, st->nb_index_entries, edit_list_dts_counter,
    3511             :                                                    frame_duration_buffer, num_discarded_begin);
    3512           8 :                         av_freep(&frame_duration_buffer);
    3513             :                     }
    3514             :                 }
    3515             :             }
    3516             : 
    3517       67402 :             if (add_index_entry(st, current->pos, edit_list_dts_counter, current->size,
    3518             :                                 current->min_distance, flags) == -1) {
    3519           0 :                 av_log(mov->fc, AV_LOG_ERROR, "Cannot add index entry\n");
    3520           0 :                 break;
    3521             :             }
    3522             : 
    3523             :             // Update the index ranges array
    3524       67402 :             if (current_index_range < msc->index_ranges || index != current_index_range->end) {
    3525         300 :                 current_index_range++;
    3526         300 :                 current_index_range->start = index;
    3527             :             }
    3528       67402 :             current_index_range->end = index + 1;
    3529             : 
    3530             :             // Only start incrementing DTS in frame_duration amounts, when we encounter a frame in edit list.
    3531       67402 :             if (edit_list_start_encountered > 0) {
    3532       67373 :                 edit_list_dts_counter = edit_list_dts_counter + frame_duration;
    3533             :             }
    3534             : 
    3535             :             // Break when found first key frame after edit entry completion
    3536       67841 :             if ((curr_cts + frame_duration >= (edit_list_duration + edit_list_media_time)) &&
    3537         630 :                 ((flags & AVINDEX_KEYFRAME) || ((st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)))) {
    3538         248 :                 if (ctts_data_old) {
    3539             :                     // If we have CTTS and this is the the first keyframe after edit elist,
    3540             :                     // wait for one more, because there might be trailing B-frames after this I-frame
    3541             :                     // that do belong to the edit.
    3542          19 :                     if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO && found_keyframe_after_edit == 0) {
    3543          10 :                         found_keyframe_after_edit = 1;
    3544          10 :                         continue;
    3545             :                     }
    3546           9 :                     if (ctts_sample_old != 0) {
    3547           0 :                         if (add_ctts_entry(&msc->ctts_data, &msc->ctts_count,
    3548             :                                            &msc->ctts_allocated_size,
    3549           0 :                                            ctts_sample_old - edit_list_start_ctts_sample,
    3550           0 :                                            ctts_data_old[ctts_index_old].duration) == -1) {
    3551           0 :                             av_log(mov->fc, AV_LOG_ERROR, "Cannot add CTTS entry %"PRId64" - {%"PRId64", %d}\n",
    3552             :                                    ctts_index_old, ctts_sample_old - edit_list_start_ctts_sample,
    3553           0 :                                    ctts_data_old[ctts_index_old].duration);
    3554           0 :                             break;
    3555             :                         }
    3556             :                     }
    3557             :                 }
    3558         238 :                 break;
    3559             :             }
    3560             :         }
    3561             :     }
    3562             :     // If there are empty edits, then min_corrected_pts might be positive intentionally. So we subtract the
    3563             :     // sum duration of emtpy edits here.
    3564         279 :     min_corrected_pts -= empty_edits_sum_duration;
    3565             : 
    3566             :     // If the minimum pts turns out to be greater than zero after fixing the index, then we subtract the
    3567             :     // dts by that amount to make the first pts zero.
    3568         279 :     if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && min_corrected_pts > 0) {
    3569          19 :         av_log(mov->fc, AV_LOG_DEBUG, "Offset DTS by %"PRId64" to make first pts zero.\n", min_corrected_pts);
    3570        1789 :         for (i = 0; i < st->nb_index_entries; ++i) {
    3571        1770 :             st->index_entries[i].timestamp -= min_corrected_pts;
    3572             :         }
    3573             :     }
    3574             : 
    3575             :     // Update av stream length
    3576         279 :     st->duration = edit_list_dts_entry_end - start_dts;
    3577         279 :     msc->start_pad = st->skip_samples;
    3578             : 
    3579             :     // Free the old index and the old CTTS structures
    3580         279 :     av_free(e_old);
    3581         279 :     av_free(ctts_data_old);
    3582         279 :     av_freep(&frame_duration_buffer);
    3583             : 
    3584             :     // Null terminate the index ranges array
    3585         279 :     current_index_range++;
    3586         279 :     current_index_range->start = 0;
    3587         279 :     current_index_range->end = 0;
    3588         279 :     msc->current_index = msc->index_ranges[0].start;
    3589             : }
    3590             : 
    3591         418 : static void mov_build_index(MOVContext *mov, AVStream *st)
    3592             : {
    3593         418 :     MOVStreamContext *sc = st->priv_data;
    3594             :     int64_t current_offset;
    3595         418 :     int64_t current_dts = 0;
    3596         418 :     unsigned int stts_index = 0;
    3597         418 :     unsigned int stsc_index = 0;
    3598         418 :     unsigned int stss_index = 0;
    3599         418 :     unsigned int stps_index = 0;
    3600             :     unsigned int i, j;
    3601         418 :     uint64_t stream_size = 0;
    3602         418 :     MOVStts *ctts_data_old = sc->ctts_data;
    3603         418 :     unsigned int ctts_count_old = sc->ctts_count;
    3604             : 
    3605         418 :     if (sc->elst_count) {
    3606         280 :         int i, edit_start_index = 0, multiple_edits = 0;
    3607         280 :         int64_t empty_duration = 0; // empty duration of the first edit list entry
    3608         280 :         int64_t start_time = 0; // start time of the media
    3609             : 
    3610         584 :         for (i = 0; i < sc->elst_count; i++) {
    3611         304 :             const MOVElst *e = &sc->elst_data[i];
    3612         304 :             if (i == 0 && e->time == -1) {
    3613             :                 /* if empty, the first entry is the start time of the stream
    3614             :                  * relative to the presentation itself */
    3615           1 :                 empty_duration = e->duration;
    3616           1 :                 edit_start_index = 1;
    3617         303 :             } else if (i == edit_start_index && e->time >= 0) {
    3618         280 :                 start_time = e->time;
    3619             :             } else {
    3620          23 :                 multiple_edits = 1;
    3621             :             }
    3622             :         }
    3623             : 
    3624         280 :         if (multiple_edits && !mov->advanced_editlist)
    3625           0 :             av_log(mov->fc, AV_LOG_WARNING, "multiple edit list entries, "
    3626             :                    "Use -advanced_editlist to correctly decode otherwise "
    3627             :                    "a/v desync might occur\n");
    3628             : 
    3629             :         /* adjust first dts according to edit list */
    3630         280 :         if ((empty_duration || start_time) && mov->time_scale > 0) {
    3631          35 :             if (empty_duration)
    3632           1 :                 empty_duration = av_rescale(empty_duration, sc->time_scale, mov->time_scale);
    3633          35 :             sc->time_offset = start_time - empty_duration;
    3634          35 :             if (!mov->advanced_editlist)
    3635           0 :                 current_dts = -sc->time_offset;
    3636             :         }
    3637             : 
    3638         280 :         if (!multiple_edits && !mov->advanced_editlist &&
    3639           0 :             st->codecpar->codec_id == AV_CODEC_ID_AAC && start_time > 0)
    3640           0 :             sc->start_pad = start_time;
    3641             :     }
    3642             : 
    3643             :     /* only use old uncompressed audio chunk demuxing when stts specifies it */
    3644         756 :     if (!(st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
    3645         701 :           sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
    3646         372 :         unsigned int current_sample = 0;
    3647         372 :         unsigned int stts_sample = 0;
    3648             :         unsigned int sample_size;
    3649         372 :         unsigned int distance = 0;
    3650         372 :         unsigned int rap_group_index = 0;
    3651         372 :         unsigned int rap_group_sample = 0;
    3652         372 :         int64_t last_dts = 0;
    3653         372 :         int64_t dts_correction = 0;
    3654         372 :         int rap_group_present = sc->rap_group_count && sc->rap_group;
    3655         372 :         int key_off = (sc->keyframe_count && sc->keyframes[0] > 0) || (sc->stps_count && sc->stps_data[0] > 0);
    3656             : 
    3657         372 :         current_dts -= sc->dts_shift;
    3658         372 :         last_dts     = current_dts;
    3659             : 
    3660         372 :         if (!sc->sample_count || st->nb_index_entries)
    3661           9 :             return;
    3662         363 :         if (sc->sample_count >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
    3663           0 :             return;
    3664         363 :         if (av_reallocp_array(&st->index_entries,
    3665         363 :                               st->nb_index_entries + sc->sample_count,
    3666             :                               sizeof(*st->index_entries)) < 0) {
    3667           0 :             st->nb_index_entries = 0;
    3668           0 :             return;
    3669             :         }
    3670         363 :         st->index_entries_allocated_size = (st->nb_index_entries + sc->sample_count) * sizeof(*st->index_entries);
    3671             : 
    3672         363 :         if (ctts_data_old) {
    3673             :             // Expand ctts entries such that we have a 1-1 mapping with samples
    3674          28 :             if (sc->sample_count >= UINT_MAX / sizeof(*sc->ctts_data))
    3675           0 :                 return;
    3676          28 :             sc->ctts_count = 0;
    3677          28 :             sc->ctts_allocated_size = 0;
    3678          28 :             sc->ctts_data = av_fast_realloc(NULL, &sc->ctts_allocated_size,
    3679          28 :                                     sc->sample_count * sizeof(*sc->ctts_data));
    3680          28 :             if (!sc->ctts_data) {
    3681           0 :                 av_free(ctts_data_old);
    3682           0 :                 return;
    3683             :             }
    3684        6168 :             for (i = 0; i < ctts_count_old &&
    3685        6112 :                         sc->ctts_count < sc->sample_count; i++)
    3686       13026 :                 for (j = 0; j < ctts_data_old[i].count &&
    3687        6914 :                             sc->ctts_count < sc->sample_count; j++)
    3688        3457 :                     add_ctts_entry(&sc->ctts_data, &sc->ctts_count,
    3689             :                                    &sc->ctts_allocated_size, 1,
    3690        3457 :                                    ctts_data_old[i].duration);
    3691          28 :             av_free(ctts_data_old);
    3692             :         }
    3693             : 
    3694       39066 :         for (i = 0; i < sc->chunk_count; i++) {
    3695       38703 :             int64_t next_offset = i+1 < sc->chunk_count ? sc->chunk_offsets[i+1] : INT64_MAX;
    3696       38703 :             current_offset = sc->chunk_offsets[i];
    3697       86663 :             while (mov_stsc_index_valid(stsc_index, sc->stsc_count) &&
    3698        7174 :                 i + 1 == sc->stsc_data[stsc_index + 1].first)
    3699        2083 :                 stsc_index++;
    3700             : 
    3701       38703 :             if (next_offset > current_offset && sc->sample_size>0 && sc->sample_size < sc->stsz_sample_size &&
    3702           0 :                 sc->stsc_data[stsc_index].count * (int64_t)sc->stsz_sample_size > next_offset - current_offset) {
    3703           0 :                 av_log(mov->fc, AV_LOG_WARNING, "STSZ sample size %d invalid (too large), ignoring\n", sc->stsz_sample_size);
    3704           0 :                 sc->stsz_sample_size = sc->sample_size;
    3705             :             }
    3706       38703 :             if (sc->stsz_sample_size>0 && sc->stsz_sample_size < sc->sample_size) {
    3707           0 :                 av_log(mov->fc, AV_LOG_WARNING, "STSZ sample size %d invalid (too small), ignoring\n", sc->stsz_sample_size);
    3708           0 :                 sc->stsz_sample_size = sc->sample_size;
    3709             :             }
    3710             : 
    3711      123315 :             for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
    3712       84612 :                 int keyframe = 0;
    3713       84612 :                 if (current_sample >= sc->sample_count) {
    3714           0 :                     av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
    3715           0 :                     return;
    3716             :                 }
    3717             : 
    3718       84612 :                 if (!sc->keyframe_absent && (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index])) {
    3719       72938 :                     keyframe = 1;
    3720      145876 :                     if (stss_index + 1 < sc->keyframe_count)
    3721        2666 :                         stss_index++;
    3722       11674 :                 } else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) {
    3723           0 :                     keyframe = 1;
    3724           0 :                     if (stps_index + 1 < sc->stps_count)
    3725           0 :                         stps_index++;
    3726             :                 }
    3727       84612 :                 if (rap_group_present && rap_group_index < sc->rap_group_count) {
    3728         188 :                     if (sc->rap_group[rap_group_index].index > 0)
    3729           2 :                         keyframe = 1;
    3730         188 :                     if (++rap_group_sample == sc->rap_group[rap_group_index].count) {
    3731           4 :                         rap_group_sample = 0;
    3732           4 :                         rap_group_index++;
    3733             :                     }
    3734             :                 }
    3735       84612 :                 if (sc->keyframe_absent
    3736         874 :                     && !sc->stps_count
    3737         874 :                     && !rap_group_present
    3738         874 :                     && (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO || (i==0 && j==0)))
    3739           2 :                      keyframe = 1;
    3740       84612 :                 if (keyframe)
    3741       72940 :                     distance = 0;
    3742       84612 :                 sample_size = sc->stsz_sample_size > 0 ? sc->stsz_sample_size : sc->sample_sizes[current_sample];
    3743      169168 :                 if (sc->pseudo_stream_id == -1 ||
    3744       84556 :                    sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
    3745             :                     AVIndexEntry *e;
    3746       84612 :                     if (sample_size > 0x3FFFFFFF) {
    3747           0 :                         av_log(mov->fc, AV_LOG_ERROR, "Sample size %u is too large\n", sample_size);
    3748           0 :                         return;
    3749             :                     }
    3750       84612 :                     e = &st->index_entries[st->nb_index_entries++];
    3751       84612 :                     e->pos = current_offset;
    3752       84612 :                     e->timestamp = current_dts;
    3753       84612 :                     e->size = sample_size;
    3754       84612 :                     e->min_distance = distance;
    3755       84612 :                     e->flags = keyframe ? AVINDEX_KEYFRAME : 0;
    3756       84612 :                     av_log(mov->fc, AV_LOG_TRACE, "AVIndex stream %d, sample %u, offset %"PRIx64", dts %"PRId64", "
    3757             :                             "size %u, distance %u, keyframe %d\n", st->index, current_sample,
    3758             :                             current_offset, current_dts, sample_size, distance, keyframe);
    3759       84612 :                     if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && st->nb_index_entries < 100)
    3760        6519 :                         ff_rfps_add_frame(mov->fc, st, current_dts);
    3761             :                 }
    3762             : 
    3763       84612 :                 current_offset += sample_size;
    3764       84612 :                 stream_size += sample_size;
    3765             : 
    3766             :                 /* A negative sample duration is invalid based on the spec,
    3767             :                  * but some samples need it to correct the DTS. */
    3768       84612 :                 if (sc->stts_data[stts_index].duration < 0) {
    3769           0 :                     av_log(mov->fc, AV_LOG_WARNING,
    3770             :                            "Invalid SampleDelta %d in STTS, at %d st:%d\n",
    3771           0 :                            sc->stts_data[stts_index].duration, stts_index,
    3772             :                            st->index);
    3773           0 :                     dts_correction += sc->stts_data[stts_index].duration - 1;
    3774           0 :                     sc->stts_data[stts_index].duration = 1;
    3775             :                 }
    3776       84612 :                 current_dts += sc->stts_data[stts_index].duration;
    3777       84612 :                 if (!dts_correction || current_dts + dts_correction > last_dts) {
    3778       84612 :                     current_dts += dts_correction;
    3779       84612 :                     dts_correction = 0;
    3780             :                 } else {
    3781             :                     /* Avoid creating non-monotonous DTS */
    3782           0 :                     dts_correction += current_dts - last_dts - 1;
    3783           0 :                     current_dts = last_dts + 1;
    3784             :                 }
    3785       84612 :                 last_dts = current_dts;
    3786       84612 :                 distance++;
    3787       84612 :                 stts_sample++;
    3788       84612 :                 current_sample++;
    3789       84612 :                 if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
    3790        1769 :                     stts_sample = 0;
    3791        1769 :                     stts_index++;
    3792             :                 }
    3793             :             }
    3794             :         }
    3795         363 :         if (st->duration > 0)
    3796         363 :             st->codecpar->bit_rate = stream_size*8*sc->time_scale/st->duration;
    3797             :     } else {
    3798          46 :         unsigned chunk_samples, total = 0;
    3799             : 
    3800             :         // compute total chunk count
    3801         678 :         for (i = 0; i < sc->stsc_count; i++) {
    3802             :             unsigned count, chunk_count;
    3803             : 
    3804         632 :             chunk_samples = sc->stsc_data[i].count;
    3805        1218 :             if (i != sc->stsc_count - 1 &&
    3806        1063 :                 sc->samples_per_frame && chunk_samples % sc->samples_per_frame) {
    3807           0 :                 av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n");
    3808           0 :                 return;
    3809             :             }
    3810             : 
    3811         632 :             if (sc->samples_per_frame >= 160) { // gsm
    3812          41 :                 count = chunk_samples / sc->samples_per_frame;
    3813         591 :             } else if (sc->samples_per_frame > 1) {
    3814         446 :                 unsigned samples = (1024/sc->samples_per_frame)*sc->samples_per_frame;
    3815         446 :                 count = (chunk_samples+samples-1) / samples;
    3816             :             } else {
    3817         145 :                 count = (chunk_samples+1023) / 1024;
    3818             :             }
    3819             : 
    3820         632 :             if (mov_stsc_index_valid(i, sc->stsc_count))
    3821         586 :                 chunk_count = sc->stsc_data[i+1].first - sc->stsc_data[i].first;
    3822             :             else
    3823          46 :                 chunk_count = sc->chunk_count - (sc->stsc_data[i].first - 1);
    3824         632 :             total += chunk_count * count;
    3825             :         }
    3826             : 
    3827          46 :         av_log(mov->fc, AV_LOG_TRACE, "chunk count %u\n", total);
    3828          46 :         if (total >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
    3829           0 :             return;
    3830          46 :         if (av_reallocp_array(&st->index_entries,
    3831          46 :                               st->nb_index_entries + total,
    3832             :                               sizeof(*st->index_entries)) < 0) {
    3833           0 :             st->nb_index_entries = 0;
    3834           0 :             return;
    3835             :         }
    3836          46 :         st->index_entries_allocated_size = (st->nb_index_entries + total) * sizeof(*st->index_entries);
    3837             : 
    3838             :         // populate index
    3839        1837 :         for (i = 0; i < sc->chunk_count; i++) {
    3840        1791 :             current_offset = sc->chunk_offsets[i];
    3841        3503 :             if (mov_stsc_index_valid(stsc_index, sc->stsc_count) &&
    3842        1712 :                 i + 1 == sc->stsc_data[stsc_index + 1].first)
    3843         586 :                 stsc_index++;
    3844        1791 :             chunk_samples = sc->stsc_data[stsc_index].count;
    3845             : 
    3846       34198 :             while (chunk_samples > 0) {
    3847             :                 AVIndexEntry *e;
    3848             :                 unsigned size, samples;
    3849             : 
    3850       30616 :                 if (sc->samples_per_frame > 1 && !sc->bytes_per_frame) {
    3851           0 :                     avpriv_request_sample(mov->fc,
    3852             :                            "Zero bytes per frame, but %d samples per frame",
    3853             :                            sc->samples_per_frame);
    3854           0 :                     return;
    3855             :                 }
    3856             : 
    3857       30616 :                 if (sc->samples_per_frame >= 160) { // gsm
    3858       14220 :                     samples = sc->samples_per_frame;
    3859       14220 :                     size = sc->bytes_per_frame;
    3860             :                 } else {
    3861       16396 :                     if (sc->samples_per_frame > 1) {
    3862        7576 :                         samples = FFMIN((1024 / sc->samples_per_frame)*
    3863             :                                         sc->samples_per_frame, chunk_samples);
    3864        7576 :                         size = (samples / sc->samples_per_frame) * sc->bytes_per_frame;
    3865             :                     } else {
    3866        8820 :                         samples = FFMIN(1024, chunk_samples);
    3867        8820 :                         size = samples * sc->sample_size;
    3868             :                     }
    3869             :                 }
    3870             : 
    3871       30616 :                 if (st->nb_index_entries >= total) {
    3872           0 :                     av_log(mov->fc, AV_LOG_ERROR, "wrong chunk count %u\n", total);
    3873           0 :                     return;
    3874             :                 }
    3875       30616 :                 if (size > 0x3FFFFFFF) {
    3876           0 :                     av_log(mov->fc, AV_LOG_ERROR, "Sample size %u is too large\n", size);
    3877           0 :                     return;
    3878             :                 }
    3879       30616 :                 e = &st->index_entries[st->nb_index_entries++];
    3880       30616 :                 e->pos = current_offset;
    3881       30616 :                 e->timestamp = current_dts;
    3882       30616 :                 e->size = size;
    3883       30616 :                 e->min_distance = 0;
    3884       30616 :                 e->flags = AVINDEX_KEYFRAME;
    3885       30616 :                 av_log(mov->fc, AV_LOG_TRACE, "AVIndex stream %d, chunk %u, offset %"PRIx64", dts %"PRId64", "
    3886             :                        "size %u, duration %u\n", st->index, i, current_offset, current_dts,
    3887             :                        size, samples);
    3888             : 
    3889       30616 :                 current_offset += size;
    3890       30616 :                 current_dts += samples;
    3891       30616 :                 chunk_samples -= samples;
    3892             :             }
    3893             :         }
    3894             :     }
    3895             : 
    3896         409 :     if (!mov->ignore_editlist && mov->advanced_editlist) {
    3897             :         // Fix index according to edit lists.
    3898         409 :         mov_fix_index(mov, st);
    3899             :     }
    3900             : }
    3901             : 
    3902           0 : static int test_same_origin(const char *src, const char *ref) {
    3903             :     char src_proto[64];
    3904             :     char ref_proto[64];
    3905             :     char src_auth[256];
    3906             :     char ref_auth[256];
    3907             :     char src_host[256];
    3908             :     char ref_host[256];
    3909           0 :     int src_port=-1;
    3910           0 :     int ref_port=-1;
    3911             : 
    3912           0 :     av_url_split(src_proto, sizeof(src_proto), src_auth, sizeof(src_auth), src_host, sizeof(src_host), &src_port, NULL, 0, src);
    3913           0 :     av_url_split(ref_proto, sizeof(ref_proto), ref_auth, sizeof(ref_auth), ref_host, sizeof(ref_host), &ref_port, NULL, 0, ref);
    3914             : 
    3915           0 :     if (strlen(src) == 0) {
    3916           0 :         return -1;
    3917           0 :     } else if (strlen(src_auth) + 1 >= sizeof(src_auth) ||
    3918           0 :         strlen(ref_auth) + 1 >= sizeof(ref_auth) ||
    3919           0 :         strlen(src_host) + 1 >= sizeof(src_host) ||
    3920           0 :         strlen(ref_host) + 1 >= sizeof(ref_host)) {
    3921           0 :         return 0;
    3922           0 :     } else if (strcmp(src_proto, ref_proto) ||
    3923           0 :                strcmp(src_auth, ref_auth) ||
    3924           0 :                strcmp(src_host, ref_host) ||
    3925           0 :                src_port != ref_port) {
    3926           0 :         return 0;
    3927             :     } else
    3928           0 :         return 1;
    3929             : }
    3930             : 
    3931           0 : static int mov_open_dref(MOVContext *c, AVIOContext **pb, const char *src, MOVDref *ref)
    3932             : {
    3933             :     /* try relative path, we do not try the absolute because it can leak information about our
    3934             :        system to an attacker */
    3935           0 :     if (ref->nlvl_to > 0 && ref->nlvl_from > 0) {
    3936             :         char filename[1025];
    3937             :         const char *src_path;
    3938             :         int i, l;
    3939             : 
    3940             :         /* find a source dir */
    3941           0 :         src_path = strrchr(src, '/');
    3942           0 :         if (src_path)
    3943           0 :             src_path++;
    3944             :         else
    3945           0 :             src_path = src;
    3946             : 
    3947             :         /* find a next level down to target */
    3948           0 :         for (i = 0, l = strlen(ref->path) - 1; l >= 0; l--)
    3949           0 :             if (ref->path[l] == '/') {
    3950           0 :                 if (i == ref->nlvl_to - 1)
    3951           0 :                     break;
    3952             :                 else
    3953           0 :                     i++;
    3954             :             }
    3955             : 
    3956             :         /* compose filename if next level down to target was found */
    3957           0 :         if (i == ref->nlvl_to - 1 && src_path - src  < sizeof(filename)) {
    3958           0 :             memcpy(filename, src, src_path - src);
    3959           0 :             filename[src_path - src] = 0;
    3960             : 
    3961           0 :             for (i = 1; i < ref->nlvl_from; i++)
    3962           0 :                 av_strlcat(filename, "../", sizeof(filename));
    3963             : 
    3964           0 :             av_strlcat(filename, ref->path + l + 1, sizeof(filename));
    3965           0 :             if (!c->use_absolute_path) {
    3966           0 :                 int same_origin = test_same_origin(src, filename);
    3967             : 
    3968           0 :                 if (!same_origin) {
    3969           0 :                     av_log(c->fc, AV_LOG_ERROR,
    3970             :                         "Reference with mismatching origin, %s not tried for security reasons, "
    3971             :                         "set demuxer option use_absolute_path to allow it anyway\n",
    3972             :                         ref->path);
    3973           0 :                     return AVERROR(ENOENT);
    3974             :                 }
    3975             : 
    3976           0 :                 if(strstr(ref->path + l + 1, "..") ||
    3977           0 :                    strstr(ref->path + l + 1, ":") ||
    3978           0 :                    (ref->nlvl_from > 1 && same_origin < 0) ||
    3979           0 :                    (filename[0] == '/' && src_path == src))
    3980           0 :                     return AVERROR(ENOENT);
    3981             :             }
    3982             : 
    3983           0 :             if (strlen(filename) + 1 == sizeof(filename))
    3984           0 :                 return AVERROR(ENOENT);
    3985           0 :             if (!c->fc->io_open(c->fc, pb, filename, AVIO_FLAG_READ, NULL))
    3986           0 :                 return 0;
    3987             :         }
    3988           0 :     } else if (c->use_absolute_path) {
    3989           0 :         av_log(c->fc, AV_LOG_WARNING, "Using absolute path on user request, "
    3990             :                "this is a possible security issue\n");
    3991           0 :         if (!c->fc->io_open(c->fc, pb, ref->path, AVIO_FLAG_READ, NULL))
    3992           0 :             return 0;
    3993             :     } else {
    3994           0 :         av_log(c->fc, AV_LOG_ERROR,
    3995             :                "Absolute path %s not tried for security reasons, "
    3996             :                "set demuxer option use_absolute_path to allow absolute paths\n",
    3997             :                ref->path);
    3998             :     }
    3999             : 
    4000           0 :     return AVERROR(ENOENT);
    4001             : }
    4002             : 
    4003         842 : static void fix_timescale(MOVContext *c, MOVStreamContext *sc)
    4004             : {
    4005         842 :     if (sc->time_scale <= 0) {
    4006           6 :         av_log(c->fc, AV_LOG_WARNING, "stream %d, timescale not set\n", sc->ffindex);
    4007           6 :         sc->time_scale = c->time_scale;
    4008           6 :         if (sc->time_scale <= 0)
    4009           0 :             sc->time_scale = 1;
    4010             :     }
    4011         842 : }
    4012             : 
    4013         418 : static int mov_read_trak(MOVContext *c, AVIOContext *pb, MOVAtom atom)
    4014             : {
    4015             :     AVStream *st;
    4016             :     MOVStreamContext *sc;
    4017             :     int ret;
    4018             : 
    4019         418 :     st = avformat_new_stream(c->fc, NULL);
    4020         418 :     if (!st) return AVERROR(ENOMEM);
    4021         418 :     st->id = c->fc->nb_streams;
    4022         418 :     sc = av_mallocz(sizeof(MOVStreamContext));
    4023         418 :     if (!sc) return AVERROR(ENOMEM);
    4024             : 
    4025         418 :     st->priv_data = sc;
    4026         418 :     st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
    4027         418 :     sc->ffindex = st->index;
    4028         418 :     c->trak_index = st->index;
    4029             : 
    4030         418 :     if ((ret = mov_read_default(c, pb, atom)) < 0)
    4031           0 :         return ret;
    4032             : 
    4033         418 :     c->trak_index = -1;
    4034             : 
    4035             :     /* sanity checks */
    4036         827 :     if ((sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
    4037        1089 :                             (!sc->sample_size && !sc->sample_count))) ||
    4038         427 :         (!sc->chunk_count && sc->sample_count)) {
    4039           0 :         av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
    4040             :                st->index);
    4041           0 :         return 0;
    4042             :     }
    4043             : 
    4044         418 :     fix_timescale(c, sc);
    4045             : 
    4046         418 :     avpriv_set_pts_info(st, 64, 1, sc->time_scale);
    4047             : 
    4048         418 :     mov_build_index(c, st);
    4049             : 
    4050         418 :     if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
    4051           0 :         MOVDref *dref = &sc->drefs[sc->dref_id - 1];
    4052           0 :         if (c->enable_drefs) {
    4053           0 :             if (mov_open_dref(c, &sc->pb, c->fc->filename, dref) < 0)
    4054           0 :                 av_log(c->fc, AV_LOG_ERROR,
    4055             :                        "stream %d, error opening alias: path='%s', dir='%s', "
    4056             :                        "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d\n",
    4057           0 :                        st->index, dref->path, dref->dir, dref->filename,
    4058           0 :                        dref->volume, dref->nlvl_from, dref->nlvl_to);
    4059             :         } else {
    4060           0 :             av_log(c->fc, AV_LOG_WARNING,
    4061             :                    "Skipped opening external track: "
    4062             :                    "stream %d, alias: path='%s', dir='%s', "
    4063             :                    "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d."
    4064             :                    "Set enable_drefs to allow this.\n",
    4065           0 :                    st->index, dref->path, dref->dir, dref->filename,
    4066           0 :                    dref->volume, dref->nlvl_from, dref->nlvl_to);
    4067             :         }
    4068             :     } else {
    4069         418 :         sc->pb = c->fc->pb;
    4070         418 :         sc->pb_is_copied = 1;
    4071             :     }
    4072             : 
    4073         418 :     if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
    4074         376 :         if (!st->sample_aspect_ratio.num && st->codecpar->width && st->codecpar->height &&
    4075         519 :             sc->height && sc->width &&
    4076         346 :             (st->codecpar->width != sc->width || st->codecpar->height != sc->height)) {
    4077           0 :             st->sample_aspect_ratio = av_d2q(((double)st->codecpar->height * sc->width) /
    4078           0 :                                              ((double)st->codecpar->width * sc->height), INT_MAX);
    4079             :         }
    4080             : 
    4081             : #if FF_API_R_FRAME_RATE
    4082         203 :         if (sc->stts_count == 1 || (sc->stts_count == 2 && sc->stts_data[1].count == 1))
    4083         372 :             av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den,
    4084         372 :                       sc->time_scale, sc->stts_data[0].duration, INT_MAX);
    4085             : #endif
    4086             :     }
    4087             : 
    4088             :     // done for ai5q, ai52, ai55, ai1q, ai12 and ai15.
    4089         418 :     if (!st->codecpar->extradata_size && st->codecpar->codec_id == AV_CODEC_ID_H264 &&
    4090           0 :         TAG_IS_AVCI(st->codecpar->codec_tag)) {
    4091           0 :         ret = ff_generate_avci_extradata(st);
    4092           0 :         if (ret < 0)
    4093           0 :             return ret;
    4094             :     }
    4095             : 
    4096         418 :     switch (st->codecpar->codec_id) {
    4097             : #if CONFIG_H261_DECODER
    4098          17 :     case AV_CODEC_ID_H261:
    4099             : #endif
    4100             : #if CONFIG_H263_DECODER
    4101             :     case AV_CODEC_ID_H263:
    4102             : #endif
    4103             : #if CONFIG_MPEG4_DECODER
    4104             :     case AV_CODEC_ID_MPEG4:
    4105             : #endif
    4106          17 :         st->codecpar->width = 0; /* let decoder init width/height */
    4107          17 :         st->codecpar->height= 0;
    4108          17 :         break;
    4109             :     }
    4110             : 
    4111             :     // If the duration of the mp3 packets is not constant, then they could need a parser
    4112         418 :     if (st->codecpar->codec_id == AV_CODEC_ID_MP3
    4113           1 :         && sc->stts_count > 3
    4114           0 :         && sc->stts_count*10 > st->nb_frames
    4115           0 :         && sc->time_scale == st->codecpar->sample_rate) {
    4116           0 :             st->need_parsing = AVSTREAM_PARSE_FULL;
    4117             :     }
    4118             :     /* Do not need those anymore. */
    4119         418 :     av_freep(&sc->chunk_offsets);
    4120         418 :     av_freep(&sc->sample_sizes);
    4121         418 :     av_freep(&sc->keyframes);
    4122         418 :     av_freep(&sc->stts_data);
    4123         418 :     av_freep(&sc->stps_data);
    4124         418 :     av_freep(&sc->elst_data);
    4125         418 :     av_freep(&sc->rap_group);
    4126             : 
    4127         418 :     return 0;
    4128             : }
    4129             : 
    4130          73 : static int mov_read_ilst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
    4131             : {
    4132             :     int ret;
    4133          73 :     c->itunes_metadata = 1;
    4134          73 :     ret = mov_read_default(c, pb, atom);
    4135          73 :     c->itunes_metadata = 0;
    4136          73 :     return ret;
    4137             : }
    4138             : 
    4139           5 : static int mov_read_keys(MOVContext *c, AVIOContext *pb, MOVAtom atom)
    4140             : {
    4141             :     uint32_t count;
    4142             :     uint32_t i;
    4143             : 
    4144           5 :     if (atom.size < 8)
    4145           0 :         return 0;
    4146             : 
    4147           5 :     avio_skip(pb, 4);
    4148           5 :     count = avio_rb32(pb);
    4149           5 :     if (count > UINT_MAX / sizeof(*c->meta_keys) - 1) {
    4150           0 :         av_log(c->fc, AV_LOG_ERROR,
    4151             :                "The 'keys' atom with the invalid key count: %"PRIu32"\n", count);
    4152           0 :         return AVERROR_INVALIDDATA;
    4153             :     }
    4154             : 
    4155           5 :     c->meta_keys_count = count + 1;
    4156           5 :     c->meta_keys = av_mallocz(c->meta_keys_count * sizeof(*c->meta_keys));
    4157           5 :     if (!c->meta_keys)
    4158           0 :         return AVERROR(ENOMEM);
    4159             : 
    4160          32 :     for (i = 1; i <= count; ++i) {
    4161          27 :         uint32_t key_size = avio_rb32(pb);
    4162          27 :         uint32_t type = avio_rl32(pb);
    4163          27 :         if (key_size < 8) {
    4164           0 :             av_log(c->fc, AV_LOG_ERROR,
    4165             :                    "The key# %"PRIu32" in meta has invalid size:"
    4166             :                    "%"PRIu32"\n", i, key_size);
    4167           0 :             return AVERROR_INVALIDDATA;
    4168             :         }
    4169          27 :         key_size -= 8;
    4170          27 :         if (type != MKTAG('m','d','t','a')) {
    4171           0 :             avio_skip(pb, key_size);
    4172             :         }
    4173          27 :         c->meta_keys[i] = av_mallocz(key_size + 1);
    4174          27 :         if (!c->meta_keys[i])
    4175           0 :             return AVERROR(ENOMEM);
    4176          27 :         avio_read(pb, c->meta_keys[i], key_size);
    4177             :     }
    4178             : 
    4179           5 :     return 0;
    4180             : }
    4181             : 
    4182          56 : static int mov_read_custom(MOVContext *c, AVIOContext *pb, MOVAtom atom)
    4183             : {
    4184          56 :     int64_t end = avio_tell(pb) + atom.size;
    4185          56 :     uint8_t *key = NULL, *val = NULL, *mean = NULL;
    4186             :     int i;
    4187          56 :     int ret = 0;
    4188             :     AVStream *st;
    4189             :     MOVStreamContext *sc;
    4190             : 
    4191          56 :     if (c->fc->nb_streams < 1)
    4192           0 :         return 0;
    4193          56 :     st = c->fc->streams[c->fc->nb_streams-1];
    4194          56 :     sc = st->priv_data;
    4195             : 
    4196         224 :     for (i = 0; i < 3; i++) {
    4197             :         uint8_t **p;
    4198             :         uint32_t len, tag;
    4199             : 
    4200         168 :         if (end - avio_tell(pb) <= 12)
    4201           0 :             break;
    4202             : 
    4203         168 :         len = avio_rb32(pb);
    4204         168 :         tag = avio_rl32(pb);
    4205         168 :         avio_skip(pb, 4); // flags
    4206             : 
    4207         168 :         if (len < 12 || len - 12 > end - avio_tell(pb))
    4208             :             break;
    4209         168 :         len -= 12;
    4210             : 
    4211         168 :         if (tag == MKTAG('m', 'e', 'a', 'n'))
    4212          56 :             p = &mean;
    4213         112 :         else if (tag == MKTAG('n', 'a', 'm', 'e'))
    4214          56 :             p = &key;
    4215          56 :         else if (tag == MKTAG('d', 'a', 't', 'a') && len > 4) {
    4216          56 :             avio_skip(pb, 4);
    4217          56 :             len -= 4;
    4218          56 :             p = &val;
    4219             :         } else
    4220             :             break;
    4221             : 
    4222         168 :         *p = av_malloc(len + 1);
    4223         168 :         if (!*p) {
    4224           0 :             ret = AVERROR(ENOMEM);
    4225           0 :             break;
    4226             :         }
    4227         168 :         ret = ffio_read_size(pb, *p, len);
    4228         168 :         if (ret < 0) {
    4229           0 :             av_freep(p);
    4230           0 :             break;
    4231             :         }
    4232         168 :         (*p)[len] = 0;
    4233             :     }
    4234             : 
    4235          56 :     if (mean && key && val) {
    4236          56 :         if (strcmp(key, "iTunSMPB") == 0) {
    4237             :             int priming, remainder, samples;
    4238          32 :             if(sscanf(val, "%*X %X %X %X", &priming, &remainder, &samples) == 3){
    4239          32 :                 if(priming>0 && priming<16384)
    4240          32 :                     sc->start_pad = priming;
    4241             :             }
    4242             :         }
    4243         112 :         if (strcmp(key, "cdec") != 0) {
    4244          46 :             av_dict_set(&c->fc->metadata, key, val,
    4245             :                         AV_DICT_DONT_STRDUP_KEY | AV_DICT_DONT_STRDUP_VAL);
    4246          46 :             key = val = NULL;
    4247             :         }
    4248             :     } else {
    4249           0 :         av_log(c->fc, AV_LOG_VERBOSE,
    4250             :                "Unhandled or malformed custom metadata of size %"PRId64"\n", atom.size);
    4251             :     }
    4252             : 
    4253          56 :     avio_seek(pb, end, SEEK_SET);
    4254          56 :     av_freep(&key);
    4255          56 :     av_freep(&val);
    4256          56 :     av_freep(&mean);
    4257          56 :     return ret;
    4258             : }
    4259             : 
    4260          73 : static int mov_read_meta(MOVContext *c, AVIOContext *pb, MOVAtom atom)
    4261             : {
    4262         285 :     while (atom.size > 8) {
    4263         212 :         uint32_t tag = avio_rl32(pb);
    4264         212 :         atom.size -= 4;
    4265         212 :         if (tag == MKTAG('h','d','l','r')) {
    4266          73 :             avio_seek(pb, -8, SEEK_CUR);
    4267          73 :             atom.size += 8;
    4268          73 :             return mov_read_default(c, pb, atom);
    4269             :         }
    4270             :     }
    4271           0 :     return 0;
    4272             : }
    4273             : 
    4274             : // return 1 when matrix is identity, 0 otherwise
    4275             : #define IS_MATRIX_IDENT(matrix)            \
    4276             :     ( (matrix)[0][0] == (1 << 16) &&       \
    4277             :       (matrix)[1][1] == (1 << 16) &&       \
    4278             :       (matrix)[2][2] == (1 << 30) &&       \
    4279             :      !(matrix)[0][1] && !(matrix)[0][2] && \
    4280             :      !(matrix)[1][0] && !(matrix)[1][2] && \
    4281             :      !(matrix)[2][0] && !(matrix)[2][1])
    4282             : 
    4283         418 : static int mov_read_tkhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
    4284             : {
    4285             :     int i, j, e;
    4286             :     int width;
    4287             :     int height;
    4288             :     int display_matrix[3][3];
    4289         418 :     int res_display_matrix[3][3] = { { 0 } };
    4290             :     AVStream *st;
    4291             :     MOVStreamContext *sc;
    4292             :     int version;
    4293             :     int flags;
    4294             : 
    4295         418 :     if (c->fc->nb_streams < 1)
    4296           0 :         return 0;
    4297         418 :     st = c->fc->streams[c->fc->nb_streams-1];
    4298         418 :     sc = st->priv_data;
    4299             : 
    4300         418 :     version = avio_r8(pb);
    4301         418 :     flags = avio_rb24(pb);
    4302         418 :     st->disposition |= (flags & MOV_TKHD_FLAG_ENABLED) ? AV_DISPOSITION_DEFAULT : 0;
    4303             : 
    4304         418 :     if (version == 1) {
    4305           7 :         avio_rb64(pb);
    4306           7 :         avio_rb64(pb);
    4307             :     } else {
    4308         411 :         avio_rb32(pb); /* creation time */
    4309         411 :         avio_rb32(pb); /* modification time */
    4310             :     }
    4311         418 :     st->id = (int)avio_rb32(pb); /* track id (NOT 0 !)*/
    4312         418 :     avio_rb32(pb); /* reserved */
    4313             : 
    4314             :     /* highlevel (considering edits) duration in movie timebase */
    4315         418 :     (version == 1) ? avio_rb64(pb) : avio_rb32(pb);
    4316         418 :     avio_rb32(pb); /* reserved */
    4317         418 :     avio_rb32(pb); /* reserved */
    4318             : 
    4319         418 :     avio_rb16(pb); /* layer */
    4320         418 :     avio_rb16(pb); /* alternate group */
    4321         418 :     avio_rb16(pb); /* volume */
    4322         418 :     avio_rb16(pb); /* reserved */
    4323             : 
    4324             :     //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
    4325             :     // they're kept in fixed point format through all calculations
    4326             :     // save u,v,z to store the whole matrix in the AV_PKT_DATA_DISPLAYMATRIX
    4327             :     // side data, but the scale factor is not needed to calculate aspect ratio
    4328        1672 :     for (i = 0; i < 3; i++) {
    4329        1254 :         display_matrix[i][0] = avio_rb32(pb);   // 16.16 fixed point
    4330        1254 :         display_matrix[i][1] = avio_rb32(pb);   // 16.16 fixed point
    4331        1254 :         display_matrix[i][2] = avio_rb32(pb);   //  2.30 fixed point
    4332             :     }
    4333             : 
    4334         418 :     width = avio_rb32(pb);       // 16.16 fixed point track width
    4335         418 :     height = avio_rb32(pb);      // 16.16 fixed point track height
    4336         418 :     sc->width = width >> 16;
    4337         418 :     sc->height = height >> 16;
    4338             : 
    4339             :     // apply the moov display matrix (after the tkhd one)
    4340        1672 :     for (i = 0; i < 3; i++) {
    4341        1254 :         const int sh[3] = { 16, 16, 30 };
    4342        5016 :         for (j = 0; j < 3; j++) {
    4343       15048 :             for (e = 0; e < 3; e++) {
    4344       22572 :                 res_display_matrix[i][j] +=
    4345       22572 :                     ((int64_t) display_matrix[i][e] *
    4346       22572 :                      c->movie_display_matrix[e][j]) >> sh[e];
    4347             :             }
    4348             :         }
    4349             :     }
    4350             : 
    4351             :     // save the matrix when it is not the default identity
    4352         418 :     if (!IS_MATRIX_IDENT(res_display_matrix)) {
    4353             :         double rotate;
    4354             : 
    4355           4 :         av_freep(&sc->display_matrix);
    4356           4 :         sc->display_matrix = av_malloc(sizeof(int32_t) * 9);
    4357           4 :         if (!sc->display_matrix)
    4358           0 :             return AVERROR(ENOMEM);
    4359             : 
    4360          16 :         for (i = 0; i < 3; i++)
    4361          48 :             for (j = 0; j < 3; j++)
    4362          36 :                 sc->display_matrix[i * 3 + j] = res_display_matrix[i][j];
    4363             : 
    4364             : #if FF_API_OLD_ROTATE_API
    4365           4 :         rotate = av_display_rotation_get(sc->display_matrix);
    4366           4 :         if (!isnan(rotate)) {
    4367             :             char rotate_buf[64];
    4368           3 :             rotate = -rotate;
    4369           3 :             if (rotate < 0) // for backward compatibility
    4370           0 :                 rotate += 360;
    4371           3 :             snprintf(rotate_buf, sizeof(rotate_buf), "%g", rotate);
    4372           3 :             av_dict_set(&st->metadata, "rotate", rotate_buf, 0);
    4373             :         }
    4374             : #endif
    4375             :     }
    4376             : 
    4377             :     // transform the display width/height according to the matrix
    4378             :     // to keep the same scale, use [width height 1<<16]
    4379         418 :     if (width && height && sc->display_matrix) {
    4380             :         double disp_transform[2];
    4381             : 
    4382           9 :         for (i = 0; i < 2; i++)
    4383           6 :             disp_transform[i] = hypot(sc->display_matrix[0 + i],
    4384           6 :                                       sc->display_matrix[3 + i]);
    4385             : 
    4386           6 :         if (disp_transform[0] > 0       && disp_transform[1] > 0 &&
    4387           9 :             disp_transform[0] < (1<<24) && disp_transform[1] < (1<<24) &&
    4388           3 :             fabs((disp_transform[0] / disp_transform[1]) - 1.0) > 0.01)
    4389           2 :             st->sample_aspect_ratio = av_d2q(
    4390           2 :                 disp_transform[0] / disp_transform[1],
    4391             :                 INT_MAX);
    4392             :     }
    4393         418 :     return 0;
    4394             : }
    4395             : 
    4396         381 : static int mov_read_tfhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
    4397             : {
    4398         381 :     MOVFragment *frag = &c->fragment;
    4399         381 :     MOVTrackExt *trex = NULL;
    4400             :     int flags, track_id, i;
    4401             : 
    4402         381 :     avio_r8(pb); /* version */
    4403         381 :     flags = avio_rb24(pb);
    4404             : 
    4405         381 :     track_id = avio_rb32(pb);
    4406         381 :     if (!track_id)
    4407           0 :         return AVERROR_INVALIDDATA;
    4408         381 :     frag->track_id = track_id;
    4409         381 :     set_frag_stream(&c->frag_index, track_id);
    4410         385 :     for (i = 0; i < c->trex_count; i++)
    4411         385 :         if (c->trex_data[i].track_id == frag->track_id) {
    4412         381 :             trex = &c->trex_data[i];
    4413         381 :             break;
    4414             :         }
    4415         381 :     if (!trex) {
    4416           0 :         av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
    4417           0 :         return AVERROR_INVALIDDATA;
    4418             :     }
    4419             : 
    4420         762 :     frag->base_data_offset = flags & MOV_TFHD_BASE_DATA_OFFSET ?
    4421         762 :                              avio_rb64(pb) : flags & MOV_TFHD_DEFAULT_BASE_IS_MOOF ?
    4422         381 :                              frag->moof_offset : frag->implicit_offset;
    4423         381 :     frag->stsd_id  = flags & MOV_TFHD_STSD_ID ? avio_rb32(pb) : trex->stsd_id;
    4424             : 
    4425         762 :     frag->duration = flags & MOV_TFHD_DEFAULT_DURATION ?
    4426         381 :                      avio_rb32(pb) : trex->duration;
    4427         762 :     frag->size     = flags & MOV_TFHD_DEFAULT_SIZE ?
    4428         381 :                      avio_rb32(pb) : trex->size;
    4429         762 :     frag->flags    = flags & MOV_TFHD_DEFAULT_FLAGS ?
    4430         381 :                      avio_rb32(pb) : trex->flags;
    4431         381 :     av_log(c->fc, AV_LOG_TRACE, "frag flags 0x%x\n", frag->flags);
    4432             : 
    4433         381 :     return 0;
    4434             : }
    4435             : 
    4436           0 : static int mov_read_chap(MOVContext *c, AVIOContext *pb, MOVAtom atom)
    4437             : {
    4438             :     unsigned i, num;
    4439             :     void *new_tracks;
    4440             : 
    4441           0 :     num = atom.size / 4;
    4442           0 :     if (!(new_tracks = av_malloc_array(num, sizeof(int))))
    4443           0 :         return AVERROR(ENOMEM);
    4444             : 
    4445           0 :     av_free(c->chapter_tracks);
    4446           0 :     c->chapter_tracks = new_tracks;
    4447           0 :     c->nb_chapter_tracks = num;
    4448             : 
    4449           0 :     for (i = 0; i < num && !pb->eof_reached; i++)
    4450           0 :         c->chapter_tracks[i] = avio_rb32(pb);
    4451             : 
    4452           0 :     return 0;
    4453             : }
    4454             : 
    4455           9 : static int mov_read_trex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
    4456             : {
    4457             :     MOVTrackExt *trex;
    4458             :     int err;
    4459             : 
    4460           9 :     if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
    4461           0 :         return AVERROR_INVALIDDATA;
    4462           9 :     if ((err = av_reallocp_array(&c->trex_data, c->trex_count + 1,
    4463             :                                  sizeof(*c->trex_data))) < 0) {
    4464           0 :         c->trex_count = 0;
    4465           0 :         return err;
    4466             :     }
    4467             : 
    4468           9 :     c->fc->duration = AV_NOPTS_VALUE; // the duration from mvhd is not representing the whole file when fragments are used.
    4469             : 
    4470           9 :     trex = &c->trex_data[c->trex_count++];
    4471           9 :     avio_r8(pb); /* version */
    4472           9 :     avio_rb24(pb); /* flags */
    4473           9 :     trex->track_id = avio_rb32(pb);
    4474           9 :     trex->stsd_id  = avio_rb32(pb);
    4475           9 :     trex->duration = avio_rb32(pb);
    4476           9 :     trex->size     = avio_rb32(pb);
    4477           9 :     trex->flags    = avio_rb32(pb);
    4478           9 :     return 0;
    4479             : }
    4480             : 
    4481         362 : static int mov_read_tfdt(MOVContext *c, AVIOContext *pb, MOVAtom atom)
    4482             : {
    4483         362 :     MOVFragment *frag = &c->fragment;
    4484         362 :     AVStream *st = NULL;
    4485             :     MOVStreamContext *sc;
    4486             :     int version, i;
    4487             :     MOVFragmentStreamInfo * frag_stream_info;
    4488             :     int64_t base_media_decode_time;
    4489             : 
    4490         362 :     for (i = 0; i < c->fc->nb_streams; i++) {
    4491         362 :         if (c->fc->streams[i]->id == frag->track_id) {
    4492         362 :             st = c->fc->streams[i];
    4493         362 :             break;
    4494             :         }
    4495             :     }
    4496         362 :     if (!st) {
    4497           0 :         av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %u\n", frag->track_id);
    4498           0 :         return AVERROR_INVALIDDATA;
    4499             :     }
    4500         362 :     sc = st->priv_data;
    4501         362 :     if (sc->pseudo_stream_id + 1 != frag->stsd_id)
    4502           0 :         return 0;
    4503         362 :     version = avio_r8(pb);
    4504         362 :     avio_rb24(pb); /* flags */
    4505         362 :     if (version) {
    4506           0 :         base_media_decode_time = avio_rb64(pb);
    4507             :     } else {
    4508         362 :         base_media_decode_time = avio_rb32(pb);
    4509             :     }
    4510             : 
    4511         362 :     frag_stream_info = get_current_frag_stream_info(&c->frag_index);
    4512         362 :     if (frag_stream_info)
    4513         362 :         frag_stream_info->tfdt_dts = base_media_decode_time;
    4514         362 :     sc->track_end = base_media_decode_time;
    4515             : 
    4516         362 :     return 0;
    4517             : }
    4518             : 
    4519         381 : static int mov_read_trun(MOVContext *c, AVIOContext *pb, MOVAtom atom)
    4520             : {
    4521         381 :     MOVFragment *frag = &c->fragment;
    4522         381 :     AVStream *st = NULL;
    4523             :     MOVStreamContext *sc;
    4524             :     MOVStts *ctts_data;
    4525             :     uint64_t offset;
    4526         381 :     int64_t dts, pts = AV_NOPTS_VALUE;
    4527         381 :     int data_offset = 0;
    4528         381 :     unsigned entries, first_sample_flags = frag->flags;
    4529             :     int flags, distance, i;
    4530         381 :     int64_t prev_dts = AV_NOPTS_VALUE;
    4531         381 :     int next_frag_index = -1, index_entry_pos;
    4532             :     size_t requested_size;
    4533             :     AVIndexEntry *new_entries;
    4534             :     MOVFragmentStreamInfo * frag_stream_info;
    4535             : 
    4536         385 :     for (i = 0; i < c->fc->nb_streams; i++) {
    4537         385 :         if (c->fc->streams[i]->id == frag->track_id) {
    4538         381 :             st = c->fc->streams[i];
    4539         381 :             break;
    4540             :         }
    4541             :     }
    4542         381 :     if (!st) {
    4543           0 :         av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %u\n", frag->track_id);
    4544           0 :         return AVERROR_INVALIDDATA;
    4545             :     }
    4546         381 :     sc = st->priv_data;
    4547         381 :     if (sc->pseudo_stream_id+1 != frag->stsd_id && sc->pseudo_stream_id != -1)
    4548           0 :         return 0;
    4549             : 
    4550             :     // Find the next frag_index index that has a valid index_entry for
    4551             :     // the current track_id.
    4552             :     //
    4553             :     // A valid index_entry means the trun for the fragment was read
    4554             :     // and it's samples are in index_entries at the given position.
    4555             :     // New index entries will be inserted before the index_entry found.
    4556         381 :     index_entry_pos = st->nb_index_entries;
    4557        2001 :     for (i = c->frag_index.current + 1; i < c->frag_index.nb_items; i++) {
    4558        1620 :         frag_stream_info = get_frag_stream_info(&c->frag_index, i, frag->track_id);
    4559        1620 :         if (frag_stream_info && frag_stream_info->index_entry >= 0) {
    4560           0 :             next_frag_index = i;
    4561           0 :             index_entry_pos = frag_stream_info->index_entry;
    4562           0 :             break;
    4563             :         }
    4564             :     }
    4565             : 
    4566         381 :     avio_r8(pb); /* version */
    4567         381 :     flags = avio_rb24(pb);
    4568         381 :     entries = avio_rb32(pb);
    4569         381 :     av_log(c->fc, AV_LOG_TRACE, "flags 0x%x entries %u\n", flags, entries);
    4570             : 
    4571         381 :     if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
    4572           0 :         return AVERROR_INVALIDDATA;
    4573         381 :     if (flags & MOV_TRUN_DATA_OFFSET)        data_offset        = avio_rb32(pb);
    4574         381 :     if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS) first_sample_flags = avio_rb32(pb);
    4575             : 
    4576         381 :     frag_stream_info = get_current_frag_stream_info(&c->frag_index);
    4577         381 :     if (frag_stream_info)
    4578             :     {
    4579         381 :         if (frag_stream_info->first_tfra_pts != AV_NOPTS_VALUE &&
    4580           0 :             c->use_mfra_for == FF_MOV_FLAG_MFRA_PTS) {
    4581           0 :             pts = frag_stream_info->first_tfra_pts;
    4582           0 :             av_log(c->fc, AV_LOG_DEBUG, "found mfra time %"PRId64
    4583             :                     ", using it for pts\n", pts);
    4584         381 :         } else if (frag_stream_info->sidx_pts != AV_NOPTS_VALUE) {
    4585             :             // FIXME: sidx earliest_presentation_time is *PTS*, s.b.
    4586             :             // pts = frag_stream_info->sidx_pts;
    4587         362 :             dts = frag_stream_info->sidx_pts - sc->time_offset;
    4588         362 :             av_log(c->fc, AV_LOG_DEBUG, "found sidx time %"PRId64
    4589             :                     ", using it for pts\n", pts);
    4590          19 :         } else if (frag_stream_info->tfdt_dts != AV_NOPTS_VALUE) {
    4591           0 :             dts = frag_stream_info->tfdt_dts - sc->time_offset;
    4592           0 :             av_log(c->fc, AV_LOG_DEBUG, "found tfdt time %"PRId64
    4593             :                     ", using it for dts\n", dts);
    4594             :         } else {
    4595          19 :             dts = sc->track_end - sc->time_offset;
    4596          19 :             av_log(c->fc, AV_LOG_DEBUG, "found track end time %"PRId64
    4597             :                     ", using it for dts\n", dts);
    4598             :         }
    4599             :     } else {
    4600           0 :         dts = sc->track_end - sc->time_offset;
    4601           0 :         av_log(c->fc, AV_LOG_DEBUG, "found track end time %"PRId64
    4602             :                 ", using it for dts\n", dts);
    4603             :     }
    4604         381 :     offset   = frag->base_data_offset + data_offset;
    4605         381 :     distance = 0;
    4606         381 :     av_log(c->fc, AV_LOG_TRACE, "first sample flags 0x%x\n", first_sample_flags);
    4607             : 
    4608             :     // realloc space for new index entries
    4609         381 :     if((unsigned)st->nb_index_entries + entries >= UINT_MAX / sizeof(AVIndexEntry)) {
    4610           0 :         entries = UINT_MAX / sizeof(AVIndexEntry) - st->nb_index_entries;
    4611           0 :         av_log(c->fc, AV_LOG_ERROR, "Failed to add index entry\n");
    4612             :     }
    4613         381 :     if (entries <= 0)
    4614           0 :         return -1;
    4615             : 
    4616         381 :     requested_size = (st->nb_index_entries + entries) * sizeof(AVIndexEntry);
    4617         381 :     new_entries = av_fast_realloc(st->index_entries,
    4618             :                                   &st->index_entries_allocated_size,
    4619             :                                   requested_size);
    4620         381 :     if(!new_entries)
    4621           0 :         return AVERROR(ENOMEM);
    4622         381 :     st->index_entries= new_entries;
    4623             : 
    4624         381 :     requested_size = (st->nb_index_entries + entries) * sizeof(*sc->ctts_data);
    4625         381 :     ctts_data = av_fast_realloc(sc->ctts_data, &sc->ctts_allocated_size,
    4626             :                                 requested_size);
    4627         381 :     if (!ctts_data)
    4628           0 :         return AVERROR(ENOMEM);
    4629         381 :     sc->ctts_data = ctts_data;
    4630             : 
    4631             :     // In case there were samples without ctts entries, ensure they get
    4632             :     // zero valued entries. This ensures clips which mix boxes with and
    4633             :     // without ctts entries don't pickup uninitialized data.
    4634         381 :     memset(sc->ctts_data + sc->ctts_count, 0,
    4635         381 :            (st->nb_index_entries - sc->ctts_count) * sizeof(*sc->ctts_data));
    4636             : 
    4637         381 :     if (index_entry_pos < st->nb_index_entries) {
    4638             :         // Make hole in index_entries and ctts_data for new samples
    4639           0 :         memmove(st->index_entries + index_entry_pos + entries,
    4640           0 :                 st->index_entries + index_entry_pos,
    4641             :                 sizeof(*st->index_entries) *
    4642           0 :                 (st->nb_index_entries - index_entry_pos));
    4643           0 :         memmove(sc->ctts_data + index_entry_pos + entries,
    4644           0 :                 sc->ctts_data + index_entry_pos,
    4645           0 :                 sizeof(*sc->ctts_data) * (sc->ctts_count - index_entry_pos));
    4646           0 :         if (index_entry_pos < sc->current_sample) {
    4647           0 :             sc->current_sample += entries;
    4648             :         }
    4649             :     }
    4650             : 
    4651         381 :     st->nb_index_entries += entries;
    4652         381 :     sc->ctts_count = st->nb_index_entries;
    4653             : 
    4654             :     // Record the index_entry position in frag_index of this fragment
    4655         381 :     if (frag_stream_info)
    4656         381 :         frag_stream_info->index_entry = index_entry_pos;
    4657             : 
    4658         381 :     if (index_entry_pos > 0)
    4659         372 :         prev_dts = st->index_entries[index_entry_pos-1].timestamp;
    4660             : 
    4661        6241 :     for (i = 0; i < entries && !pb->eof_reached; i++) {
    4662        5860 :         unsigned sample_size = frag->size;
    4663        5860 :         int sample_flags = i ? frag->flags : first_sample_flags;
    4664        5860 :         unsigned sample_duration = frag->duration;
    4665        5860 :         unsigned ctts_duration = 0;
    4666        5860 :         int keyframe = 0;
    4667        5860 :         int index_entry_flags = 0;
    4668             : 
    4669        5860 :         if (flags & MOV_TRUN_SAMPLE_DURATION) sample_duration = avio_rb32(pb);
    4670        5860 :         if (flags & MOV_TRUN_SAMPLE_SIZE)     sample_size     = avio_rb32(pb);
    4671        5860 :         if (flags & MOV_TRUN_SAMPLE_FLAGS)    sample_flags    = avio_rb32(pb);
    4672        5860 :         if (flags & MOV_TRUN_SAMPLE_CTS)      ctts_duration   = avio_rb32(pb);
    4673             : 
    4674        5860 :         mov_update_dts_shift(sc, ctts_duration);
    4675        5860 :         if (pts != AV_NOPTS_VALUE) {
    4676           0 :             dts = pts - sc->dts_shift;
    4677           0 :             if (flags & MOV_TRUN_SAMPLE_CTS) {
    4678           0 :                 dts -= ctts_duration;
    4679             :             } else {
    4680           0 :                 dts -= sc->time_offset;
    4681             :             }
    4682           0 :             av_log(c->fc, AV_LOG_DEBUG,
    4683             :                    "pts %"PRId64" calculated dts %"PRId64
    4684             :                    " sc->dts_shift %d ctts.duration %d"
    4685             :                    " sc->time_offset %"PRId64
    4686             :                    " flags & MOV_TRUN_SAMPLE_CTS %d\n",
    4687             :                    pts, dts,
    4688             :                    sc->dts_shift, ctts_duration,
    4689             :                    sc->time_offset, flags & MOV_TRUN_SAMPLE_CTS);
    4690           0 :             pts = AV_NOPTS_VALUE;
    4691             :         }
    4692             : 
    4693        5860 :         if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
    4694          32 :             keyframe = 1;
    4695             :         else
    4696        5828 :             keyframe =
    4697        5828 :                 !(sample_flags & (MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC |
    4698             :                                   MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES));
    4699        5860 :         if (keyframe) {
    4700         347 :             distance = 0;
    4701         347 :             index_entry_flags |= AVINDEX_KEYFRAME;
    4702             :         }
    4703             :         // Fragments can overlap in time.  Discard overlapping frames after
    4704             :         // decoding.
    4705        5860 :         if (prev_dts >= dts)
    4706          64 :             index_entry_flags |= AVINDEX_DISCARD_FRAME;
    4707             : 
    4708        5860 :         st->index_entries[index_entry_pos].pos = offset;
    4709        5860 :         st->index_entries[index_entry_pos].timestamp = dts;
    4710        5860 :         st->index_entries[index_entry_pos].size= sample_size;
    4711        5860 :         st->index_entries[index_entry_pos].min_distance= distance;
    4712        5860 :         st->index_entries[index_entry_pos].flags = index_entry_flags;
    4713             : 
    4714        5860 :         sc->ctts_data[index_entry_pos].count = 1;
    4715        5860 :         sc->ctts_data[index_entry_pos].duration = ctts_duration;
    4716        5860 :         index_entry_pos++;
    4717             : 
    4718        5860 :         av_log(c->fc, AV_LOG_TRACE, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
    4719             :                 "size %u, distance %d, keyframe %d\n", st->index,
    4720             :                 index_entry_pos, offset, dts, sample_size, distance, keyframe);
    4721        5860 :         distance++;
    4722        5860 :         dts += sample_duration;
    4723        5860 :         offset += sample_size;
    4724        5860 :         sc->data_size += sample_size;
    4725        5860 :         sc->duration_for_fps += sample_duration;
    4726        5860 :         sc->nb_frames_for_fps ++;
    4727             :     }
    4728         381 :     if (i < entries) {
    4729             :         // EOF found before reading all entries.  Fix the hole this would
    4730             :         // leave in index_entries and ctts_data
    4731           0 :         int gap = entries - i;
    4732           0 :         memmove(st->index_entries + index_entry_pos,
    4733           0 :                 st->index_entries + index_entry_pos + gap,
    4734             :                 sizeof(*st->index_entries) *
    4735           0 :                 (st->nb_index_entries - (index_entry_pos + gap)));
    4736           0 :         memmove(sc->ctts_data + index_entry_pos,
    4737           0 :                 sc->ctts_data + index_entry_pos + gap,
    4738             :                 sizeof(*sc->ctts_data) *
    4739           0 :                 (sc->ctts_count - (index_entry_pos + gap)));
    4740             : 
    4741           0 :         st->nb_index_entries -= gap;
    4742           0 :         sc->ctts_count -= gap;
    4743           0 :         if (index_entry_pos < sc->current_sample) {
    4744           0 :             sc->current_sample -= gap;
    4745             :         }
    4746           0 :         entries = i;
    4747             :     }
    4748             : 
    4749             :     // The end of this new fragment may overlap in time with the start
    4750             :     // of the next fragment in index_entries. Mark the samples in the next
    4751             :     // fragment that overlap with AVINDEX_DISCARD_FRAME
    4752         381 :     prev_dts = AV_NOPTS_VALUE;
    4753         381 :     if (index_entry_pos > 0)
    4754         381 :         prev_dts = st->index_entries[index_entry_pos-1].timestamp;
    4755         381 :     for (i = index_entry_pos; i < st->nb_index_entries; i++) {
    4756           0 :         if (prev_dts < st->index_entries[i].timestamp)
    4757           0 :             break;
    4758           0 :         st->index_entries[i].flags |= AVINDEX_DISCARD_FRAME;
    4759             :     }
    4760             : 
    4761             :     // If a hole was created to insert the new index_entries into,
    4762             :     // the index_entry recorded for all subsequent moof must
    4763             :     // be incremented by the number of entries inserted.
    4764         762 :     fix_frag_index_entries(&c->frag_index, next_frag_index,
    4765         381 :                            frag->track_id, entries);
    4766             : 
    4767         381 :     if (pb->eof_reached) {
    4768           0 :         av_log(c->fc, AV_LOG_WARNING, "reached eof, corrupted TRUN atom\n");
    4769           0 :         return AVERROR_EOF;
    4770             :     }
    4771             : 
    4772         381 :     frag->implicit_offset = offset;
    4773             : 
    4774         381 :     sc->track_end = dts + sc->time_offset;
    4775         381 :     if (st->duration < sc->track_end)
    4776           9 :         st->duration = sc->track_end;
    4777             : 
    4778         381 :     return 0;
    4779             : }
    4780             : 
    4781          39 : static int mov_read_sidx(MOVContext *c, AVIOContext *pb, MOVAtom atom)
    4782             : {
    4783          39 :     int64_t offset = avio_tell(pb) + atom.size, pts, timestamp;
    4784             :     uint8_t version;
    4785             :     unsigned i, j, track_id, item_count;
    4786          39 :     AVStream *st = NULL;
    4787          39 :     AVStream *ref_st = NULL;
    4788          39 :     MOVStreamContext *sc, *ref_sc = NULL;
    4789             :     AVRational timescale;
    4790             : 
    4791          39 :     version = avio_r8(pb);
    4792          39 :     if (version > 1) {
    4793           0 :         avpriv_request_sample(c->fc, "sidx version %u", version);
    4794           0 :         return 0;
    4795             :     }
    4796             : 
    4797          39 :     avio_rb24(pb); // flags
    4798             : 
    4799          39 :     track_id = avio_rb32(pb); // Reference ID
    4800          39 :     for (i = 0; i < c->fc->nb_streams; i++) {
    4801          39 :         if (c->fc->streams[i]->id == track_id) {
    4802          39 :             st = c->fc->streams[i];
    4803          39 :             break;
    4804             :         }
    4805             :     }
    4806          39 :     if (!st) {
    4807           0 :         av_log(c->fc, AV_LOG_WARNING, "could not find corresponding track id %d\n", track_id);
    4808           0 :         return 0;
    4809             :     }
    4810             : 
    4811          39 :     sc = st->priv_data;
    4812             : 
    4813          39 :     timescale = av_make_q(1, avio_rb32(pb));
    4814             : 
    4815          39 :     if (timescale.den <= 0) {
    4816           0 :         av_log(c->fc, AV_LOG_ERROR, "Invalid sidx timescale 1/%d\n", timescale.den);
    4817           0 :         return AVERROR_INVALIDDATA;
    4818             :     }
    4819             : 
    4820          39 :     if (version == 0) {
    4821          39 :         pts = avio_rb32(pb);
    4822          39 :         offset += avio_rb32(pb);
    4823             :     } else {
    4824           0 :         pts = avio_rb64(pb);
    4825           0 :         offset += avio_rb64(pb);
    4826             :     }
    4827             : 
    4828          39 :     avio_rb16(pb); // reserved
    4829             : 
    4830          39 :     item_count = avio_rb16(pb);
    4831             : 
    4832         402 :     for (i = 0; i < item_count; i++) {
    4833             :         int index;
    4834             :         MOVFragmentStreamInfo * frag_stream_info;
    4835         363 :         uint32_t size = avio_rb32(pb);
    4836         363 :         uint32_t duration = avio_rb32(pb);
    4837         363 :         if (size & 0x80000000) {
    4838           0 :             avpriv_request_sample(c->fc, "sidx reference_type 1");
    4839           0 :             return AVERROR_PATCHWELCOME;
    4840             :         }
    4841         363 :         avio_rb32(pb); // sap_flags
    4842         363 :         timestamp = av_rescale_q(pts, st->time_base, timescale);
    4843             : 
    4844         363 :         index = update_frag_index(c, offset);
    4845         363 :         frag_stream_info = get_frag_stream_info(&c->frag_index, index, track_id);
    4846         363 :         if (frag_stream_info)
    4847         363 :             frag_stream_info->sidx_pts = timestamp;
    4848             : 
    4849         363 :         offset += size;
    4850         363 :         pts += duration;
    4851             :     }
    4852             : 
    4853          39 :     st->duration = sc->track_end = pts;
    4854             : 
    4855          39 :     sc->has_sidx = 1;
    4856             : 
    4857          39 :     if (offset == avio_size(pb)) {
    4858             :         // Find first entry in fragment index that came from an sidx.
    4859             :         // This will pretty much always be the first entry.
    4860         365 :         for (i = 0; i < c->frag_index.nb_items; i++) {
    4861         363 :             MOVFragmentIndexItem * item = &c->frag_index.item[i];
    4862         363 :             for (j = 0; ref_st == NULL && j < item->nb_stream_info; j++) {
    4863             :                 MOVFragmentStreamInfo * si;
    4864           2 :                 si = &item->stream_info[j];
    4865           2 :                 if (si->sidx_pts != AV_NOPTS_VALUE) {
    4866           2 :                     ref_st = c->fc->streams[j];
    4867           2 :                     ref_sc = ref_st->priv_data;
    4868           2 :                     break;
    4869             :                 }
    4870             :             }
    4871             :         }
    4872           4 :         for (i = 0; i < c->fc->nb_streams; i++) {
    4873           2 :             st = c->fc->streams[i];
    4874           2 :             sc = st->priv_data;
    4875           2 :             if (!sc->has_sidx) {
    4876           0 :                 st->duration = sc->track_end = av_rescale(ref_st->duration, sc->time_scale, ref_sc->time_scale);
    4877             :             }
    4878             :         }
    4879             : 
    4880           2 :         c->frag_index.complete = 1;
    4881             :     }
    4882             : 
    4883          39 :     return 0;
    4884             : }
    4885             : 
    4886             : /* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
    4887             : /* like the files created with Adobe Premiere 5.0, for samples see */
    4888             : /* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
    4889         207 : static int mov_read_wide(MOVContext *c, AVIOContext *pb, MOVAtom atom)
    4890             : {
    4891             :     int err;
    4892             : 
    4893         207 :     if (atom.size < 8)
    4894         207 :         return 0; /* continue */
    4895           0 :     if (avio_rb32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
    4896           0 :         avio_skip(pb, atom.size - 4);
    4897           0 :         return 0;
    4898             :     }
    4899           0 :     atom.type = avio_rl32(pb);
    4900           0 :     atom.size -= 8;
    4901           0 :     if (atom.type != MKTAG('m','d','a','t')) {
    4902           0 :         avio_skip(pb, atom.size);
    4903           0 :         return 0;
    4904             :     }
    4905           0 :     err = mov_read_mdat(c, pb, atom);
    4906           0 :     return err;
    4907             : }
    4908             : 
    4909           2 : static int mov_read_cmov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
    4910             : {
    4911             : #if CONFIG_ZLIB
    4912             :     AVIOContext ctx;
    4913             :     uint8_t *cmov_data;
    4914             :     uint8_t *moov_data; /* uncompressed data */
    4915             :     long cmov_len, moov_len;
    4916           2 :     int ret = -1;
    4917             : 
    4918           2 :     avio_rb32(pb); /* dcom atom */
    4919           2 :     if (avio_rl32(pb) != MKTAG('d','c','o','m'))
    4920           0 :         return AVERROR_INVALIDDATA;
    4921           2 :     if (avio_rl32(pb) != MKTAG('z','l','i','b')) {
    4922           0 :         av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !\n");
    4923           0 :         return AVERROR_INVALIDDATA;
    4924             :     }
    4925           2 :     avio_rb32(pb); /* cmvd atom */
    4926           2 :     if (avio_rl32(pb) != MKTAG('c','m','v','d'))
    4927           0 :         return AVERROR_INVALIDDATA;
    4928           2 :     moov_len = avio_rb32(pb); /* uncompressed size */
    4929           2 :     cmov_len = atom.size - 6 * 4;
    4930             : 
    4931           2 :     cmov_data = av_malloc(cmov_len);
    4932           2 :     if (!cmov_data)
    4933           0 :         return AVERROR(ENOMEM);
    4934           2 :     moov_data = av_malloc(moov_len);
    4935           2 :     if (!moov_data) {
    4936           0 :         av_free(cmov_data);
    4937           0 :         return AVERROR(ENOMEM);
    4938             :     }
    4939           2 :     ret = ffio_read_size(pb, cmov_data, cmov_len);
    4940           2 :     if (ret < 0)
    4941           0 :         goto free_and_return;
    4942             : 
    4943           2 :     ret = AVERROR_INVALIDDATA;
    4944           2 :     if (uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
    4945           0 :         goto free_and_return;
    4946           2 :     if (ffio_init_context(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
    4947           0 :         goto free_and_return;
    4948           2 :     ctx.seekable = AVIO_SEEKABLE_NORMAL;
    4949           2 :     atom.type = MKTAG('m','o','o','v');
    4950           2 :     atom.size = moov_len;
    4951           2 :     ret = mov_read_default(c, &ctx, atom);
    4952           2 : free_and_return:
    4953           2 :     av_free(moov_data);
    4954           2 :     av_free(cmov_data);
    4955           2 :     return ret;
    4956             : #else
    4957             :     av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
    4958             :     return AVERROR(ENOSYS);
    4959             : #endif
    4960             : }
    4961             : 
    4962             : /* edit list atom */
    4963         280 : static int mov_read_elst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
    4964             : {
    4965             :     MOVStreamContext *sc;
    4966             :     int i, edit_count, version;
    4967             :     int64_t elst_entry_size;
    4968             : 
    4969         280 :     if (c->fc->nb_streams < 1 || c->ignore_editlist)
    4970           0 :         return 0;
    4971         280 :     sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
    4972             : 
    4973         280 :     version = avio_r8(pb); /* version */
    4974         280 :     avio_rb24(pb); /* flags */
    4975         280 :     edit_count = avio_rb32(pb); /* entries */
    4976         280 :     atom.size -= 8;
    4977             : 
    4978         280 :     elst_entry_size = version == 1 ? 20 : 12;
    4979         280 :     if (atom.size != edit_count * elst_entry_size) {
    4980           1 :         if (c->fc->strict_std_compliance >= FF_COMPLIANCE_STRICT) {
    4981           0 :             av_log(c->fc, AV_LOG_ERROR, "Invalid edit list entry_count: %d for elst atom of size: %"PRId64" bytes.\n",
    4982           0 :                    edit_count, atom.size + 8);
    4983           0 :             return AVERROR_INVALIDDATA;
    4984             :         } else {
    4985           1 :             edit_count = atom.size / elst_entry_size;
    4986           1 :             if (edit_count * elst_entry_size != atom.size) {
    4987           0 :                 av_log(c->fc, AV_LOG_WARNING, "ELST atom of %"PRId64" bytes, bigger than %d entries.", atom.size, edit_count);
    4988             :             }
    4989             :         }
    4990             :     }
    4991             : 
    4992         280 :     if (!edit_count)
    4993           0 :         return 0;
    4994         280 :     if (sc->elst_data)
    4995           0 :         av_log(c->fc, AV_LOG_WARNING, "Duplicated ELST atom\n");
    4996         280 :     av_free(sc->elst_data);
    4997         280 :     sc->elst_count = 0;
    4998         280 :     sc->elst_data = av_malloc_array(edit_count, sizeof(*sc->elst_data));
    4999         280 :     if (!sc->elst_data)
    5000           0 :         return AVERROR(ENOMEM);
    5001             : 
    5002         280 :     av_log(c->fc, AV_LOG_TRACE, "track[%u].edit_count = %i\n", c->fc->nb_streams - 1, edit_count);
    5003         584 :     for (i = 0; i < edit_count && atom.size > 0 && !pb->eof_reached; i++) {
    5004         304 :         MOVElst *e = &sc->elst_data[i];
    5005             : 
    5006         304 :         if (version == 1) {
    5007           0 :             e->duration = avio_rb64(pb);
    5008           0 :             e->time     = avio_rb64(pb);
    5009           0 :             atom.size -= 16;
    5010             :         } else {
    5011         304 :             e->duration = avio_rb32(pb); /* segment duration */
    5012         304 :             e->time     = (int32_t)avio_rb32(pb); /* media time */
    5013         304 :             atom.size -= 8;
    5014             :         }
    5015         304 :         e->rate = avio_rb32(pb) / 65536.0;
    5016         304 :         atom.size -= 4;
    5017         304 :         av_log(c->fc, AV_LOG_TRACE, "duration=%"PRId64" time=%"PRId64" rate=%f\n",
    5018         304 :                e->duration, e->time, e->rate);
    5019             : 
    5020         304 :         if (e->time < 0 && e->time != -1 &&
    5021           0 :             c->fc->strict_std_compliance >= FF_COMPLIANCE_STRICT) {
    5022           0 :             av_log(c->fc, AV_LOG_ERROR, "Track %d, edit %d: Invalid edit list media time=%"PRId64"\n",
    5023           0 :                    c->fc->nb_streams-1, i, e->time);
    5024           0 :             return AVERROR_INVALIDDATA;
    5025             :         }
    5026             :     }
    5027         280 :     sc->elst_count = i;
    5028             : 
    5029         280 :     return 0;
    5030             : }
    5031             : 
    5032          13 : static int mov_read_tmcd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
    5033             : {
    5034             :     MOVStreamContext *sc;
    5035             : 
    5036          13 :     if (c->fc->nb_streams < 1)
    5037           0 :         return AVERROR_INVALIDDATA;
    5038          13 :     sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
    5039          13 :     sc->timecode_track = avio_rb32(pb);
    5040          13 :     return 0;
    5041             : }
    5042             : 
    5043           0 : static int mov_read_vpcc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
    5044             : {
    5045             :     AVStream *st;
    5046             :     int version, color_range, color_primaries, color_trc, color_space;
    5047             : 
    5048           0 :     if (c->fc->nb_streams < 1)
    5049           0 :         return 0;
    5050           0 :     st = c->fc->streams[c->fc->nb_streams - 1];
    5051             : 
    5052           0 :     if (atom.size < 5) {
    5053           0 :         av_log(c->fc, AV_LOG_ERROR, "Empty VP Codec Configuration box\n");
    5054           0 :         return AVERROR_INVALIDDATA;
    5055             :     }
    5056             : 
    5057           0 :     version = avio_r8(pb);
    5058           0 :     if (version != 1) {
    5059           0 :         av_log(c->fc, AV_LOG_WARNING, "Unsupported VP Codec Configuration box version %d\n", version);
    5060           0 :         return 0;
    5061             :     }
    5062           0 :     avio_skip(pb, 3); /* flags */
    5063             : 
    5064           0 :     avio_skip(pb, 2); /* profile + level */
    5065           0 :     color_range     = avio_r8(pb); /* bitDepth, chromaSubsampling, videoFullRangeFlag */
    5066           0 :     color_primaries = avio_r8(pb);
    5067           0 :     color_trc       = avio_r8(pb);
    5068           0 :     color_space     = avio_r8(pb);
    5069           0 :     if (avio_rb16(pb)) /* codecIntializationDataSize */
    5070           0 :         return AVERROR_INVALIDDATA;
    5071             : 
    5072           0 :     if (!av_color_primaries_name(color_primaries))
    5073           0 :         color_primaries = AVCOL_PRI_UNSPECIFIED;
    5074           0 :     if (!av_color_transfer_name(color_trc))
    5075           0 :         color_trc = AVCOL_TRC_UNSPECIFIED;
    5076           0 :     if (!av_color_space_name(color_space))
    5077           0 :         color_space = AVCOL_SPC_UNSPECIFIED;
    5078             : 
    5079           0 :     st->codecpar->color_range     = (color_range & 1) ? AVCOL_RANGE_JPEG : AVCOL_RANGE_MPEG;
    5080           0 :     st->codecpar->color_primaries = color_primaries;
    5081           0 :     st->codecpar->color_trc       = color_trc;
    5082           0 :     st->codecpar->color_space     = color_space;
    5083             : 
    5084           0 :     return 0;
    5085             : }
    5086             : 
    5087           0 : static int mov_read_smdm(MOVContext *c, AVIOContext *pb, MOVAtom atom)
    5088             : {
    5089             :     MOVStreamContext *sc;
    5090           0 :     const int chroma_den = 50000;
    5091           0 :     const int luma_den = 10000;
    5092             :     int i, j, version;
    5093             : 
    5094           0 :     if (c->fc->nb_streams < 1)
    5095           0 :         return AVERROR_INVALIDDATA;
    5096             : 
    5097           0 :     sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
    5098             : 
    5099           0 :     if (atom.size < 5) {
    5100           0 :         av_log(c->fc, AV_LOG_ERROR, "Empty Mastering Display Metadata box\n");
    5101           0 :         return AVERROR_INVALIDDATA;
    5102             :     }
    5103             : 
    5104           0 :     version = avio_r8(pb);
    5105           0 :     if (version) {
    5106           0 :         av_log(c->fc, AV_LOG_WARNING, "Unsupported Mastering Display Metadata box version %d\n", version);
    5107           0 :         return 0;
    5108             :     }
    5109           0 :     avio_skip(pb, 3); /* flags */
    5110             : 
    5111           0 :     sc->mastering = av_mastering_display_metadata_alloc();
    5112           0 :     if (!sc->mastering)
    5113           0 :         return AVERROR(ENOMEM);
    5114             : 
    5115           0 :     for (i = 0; i < 3; i++)
    5116           0 :         for (j = 0; j < 2; j++)
    5117           0 :             sc->mastering->display_primaries[i][j] =
    5118           0 :                 av_make_q(lrint(((double)avio_rb16(pb) / (1 << 16)) * chroma_den), chroma_den);
    5119           0 :     for (i = 0; i < 2; i++)
    5120           0 :         sc->mastering->white_point[i] =
    5121           0 :             av_make_q(lrint(((double)avio_rb16(pb) / (1 << 16)) * chroma_den), chroma_den);
    5122           0 :     sc->mastering->max_luminance =
    5123           0 :         av_make_q(lrint(((double)avio_rb32(pb) / (1 <<  8)) * luma_den), luma_den);
    5124           0 :     sc->mastering->min_luminance =
    5125           0 :         av_make_q(lrint(((double)avio_rb32(pb) / (1 << 14)) * luma_den), luma_den);
    5126             : 
    5127           0 :     sc->mastering->has_primaries = 1;
    5128           0 :     sc->mastering->has_luminance = 1;
    5129             : 
    5130           0 :     return 0;
    5131             : }
    5132             : 
    5133           0 : static int mov_read_mdcv(MOVContext *c, AVIOContext *pb, MOVAtom atom)
    5134             : {
    5135             :     MOVStreamContext *sc;
    5136           0 :     const int mapping[3] = {1, 2, 0};
    5137           0 :     const int chroma_den = 50000;
    5138           0 :     const int luma_den = 10000;
    5139             :     int i;
    5140             : 
    5141           0 :     if (c->fc->nb_streams < 1)
    5142           0 :         return AVERROR_INVALIDDATA;
    5143             : 
    5144           0 :     sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
    5145             : 
    5146           0 :     if (atom.size < 24) {
    5147           0 :         av_log(c->fc, AV_LOG_ERROR, "Invalid Mastering Display Color Volume box\n");
    5148           0 :         return AVERROR_INVALIDDATA;
    5149             :     }
    5150             : 
    5151           0 :     sc->mastering = av_mastering_display_metadata_alloc();
    5152           0 :     if (!sc->mastering)
    5153           0 :         return AVERROR(ENOMEM);
    5154             : 
    5155           0 :     for (i = 0; i < 3; i++) {
    5156           0 :         const int j = mapping[i];
    5157           0 :         sc->mastering->display_primaries[j][0].num = avio_rb16(pb);
    5158           0 :         sc->mastering->display_primaries[j][0].den = chroma_den;
    5159           0 :         sc->mastering->display_primaries[j][1].num = avio_rb16(pb);
    5160           0 :         sc->mastering->display_primaries[j][1].den = chroma_den;
    5161             :     }
    5162           0 :     sc->mastering->white_point[0].num = avio_rb16(pb);
    5163           0 :     sc->mastering->white_point[0].den = chroma_den;
    5164           0 :     sc->mastering->white_point[1].num = avio_rb16(pb);
    5165           0 :     sc->mastering->white_point[1].den = chroma_den;
    5166             : 
    5167           0 :     sc->mastering->max_luminance.num = avio_rb32(pb);
    5168           0 :     sc->mastering->max_luminance.den = luma_den;
    5169           0 :     sc->mastering->min_luminance.num = avio_rb32(pb);
    5170           0 :     sc->mastering->min_luminance.den = luma_den;
    5171             : 
    5172           0 :     sc->mastering->has_luminance = 1;
    5173           0 :     sc->mastering->has_primaries = 1;
    5174             : 
    5175           0 :     return 0;
    5176             : }
    5177             : 
    5178           0 : static int mov_read_coll(MOVContext *c, AVIOContext *pb, MOVAtom atom)
    5179             : {
    5180             :     MOVStreamContext *sc;
    5181             :     int version;
    5182             : 
    5183           0 :     if (c->fc->nb_streams < 1)
    5184           0 :         return AVERROR_INVALIDDATA;
    5185             : 
    5186           0 :     sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
    5187             : 
    5188           0 :     if (atom.size < 5) {
    5189           0 :         av_log(c->fc, AV_LOG_ERROR, "Empty Content Light Level box\n");
    5190           0 :         return AVERROR_INVALIDDATA;
    5191             :     }
    5192             : 
    5193           0 :     version = avio_r8(pb);
    5194           0 :     if (version) {
    5195           0 :         av_log(c->fc, AV_LOG_WARNING, "Unsupported Content Light Level box version %d\n", version);
    5196           0 :         return 0;
    5197             :     }
    5198           0 :     avio_skip(pb, 3); /* flags */
    5199             : 
    5200           0 :     sc->coll = av_content_light_metadata_alloc(&sc->coll_size);
    5201           0 :     if (!sc->coll)
    5202           0 :         return AVERROR(ENOMEM);
    5203             : 
    5204           0 :     sc->coll->MaxCLL  = avio_rb16(pb);
    5205           0 :     sc->coll->MaxFALL = avio_rb16(pb);
    5206             : 
    5207           0 :     return 0;
    5208             : }
    5209             : 
    5210           0 : static int mov_read_clli(MOVContext *c, AVIOContext *pb, MOVAtom atom)
    5211             : {
    5212             :     MOVStreamContext *sc;
    5213             : 
    5214           0 :     if (c->fc->nb_streams < 1)
    5215           0 :         return AVERROR_INVALIDDATA;
    5216             : 
    5217           0 :     sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
    5218             : 
    5219           0 :     if (atom.size < 4) {
    5220           0 :         av_log(c->fc, AV_LOG_ERROR, "Empty Content Light Level Info box\n");
    5221           0 :         return AVERROR_INVALIDDATA;
    5222             :     }
    5223             : 
    5224           0 :     sc->coll = av_content_light_metadata_alloc(&sc->coll_size);
    5225           0 :     if (!sc->coll)
    5226           0 :         return AVERROR(ENOMEM);
    5227             : 
    5228           0 :     sc->coll->MaxCLL  = avio_rb16(pb);
    5229           0 :     sc->coll->MaxFALL = avio_rb16(pb);
    5230             : 
    5231           0 :     return 0;
    5232             : }
    5233             : 
    5234           1 : static int mov_read_st3d(MOVContext *c, AVIOContext *pb, MOVAtom atom)
    5235             : {
    5236             :     AVStream *st;
    5237             :     MOVStreamContext *sc;
    5238             :     enum AVStereo3DType type;
    5239             :     int mode;
    5240             : 
    5241           1 :     if (c->fc->nb_streams < 1)
    5242           0 :         return 0;
    5243             : 
    5244           1 :     st = c->fc->streams[c->fc->nb_streams - 1];
    5245           1 :     sc = st->priv_data;
    5246             : 
    5247           1 :     if (atom.size < 5) {
    5248           0 :         av_log(c->fc, AV_LOG_ERROR, "Empty stereoscopic video box\n");
    5249           0 :         return AVERROR_INVALIDDATA;
    5250             :     }
    5251           1 :     avio_skip(pb, 4); /* version + flags */
    5252             : 
    5253           1 :     mode = avio_r8(pb);
    5254           1 :     switch (mode) {
    5255           1 :     case 0:
    5256           1 :         type = AV_STEREO3D_2D;
    5257           1 :         break;
    5258           0 :     case 1:
    5259           0 :         type = AV_STEREO3D_TOPBOTTOM;
    5260           0 :         break;
    5261           0 :     case 2:
    5262           0 :         type = AV_STEREO3D_SIDEBYSIDE;
    5263           0 :         break;
    5264           0 :     default:
    5265           0 :         av_log(c->fc, AV_LOG_WARNING, "Unknown st3d mode value %d\n", mode);
    5266           0 :         return 0;
    5267             :     }
    5268             : 
    5269           1 :     sc->stereo3d = av_stereo3d_alloc();
    5270           1 :     if (!sc->stereo3d)
    5271           0 :         return AVERROR(ENOMEM);
    5272             : 
    5273           1 :     sc->stereo3d->type = type;
    5274           1 :     return 0;
    5275             : }
    5276             : 
    5277           1 : static int mov_read_sv3d(MOVContext *c, AVIOContext *pb, MOVAtom atom)
    5278             : {
    5279             :     AVStream *st;
    5280             :     MOVStreamContext *sc;
    5281             :     int size, version, layout;
    5282             :     int32_t yaw, pitch, roll;
    5283           1 :     uint32_t l = 0, t = 0, r = 0, b = 0;
    5284           1 :     uint32_t tag, padding = 0;
    5285             :     enum AVSphericalProjection projection;
    5286             : 
    5287           1 :     if (c->fc->nb_streams < 1)
    5288           0 :         return 0;
    5289             : 
    5290           1 :     st = c->fc->streams[c->fc->nb_streams - 1];
    5291           1 :     sc = st->priv_data;
    5292             : 
    5293           1 :     if (atom.size < 8) {
    5294           0 :         av_log(c->fc, AV_LOG_ERROR, "Empty spherical video box\n");
    5295           0 :         return AVERROR_INVALIDDATA;
    5296             :     }
    5297             : 
    5298           1 :     size = avio_rb32(pb);
    5299           1 :     if (size <= 12 || size > atom.size)
    5300           0 :         return AVERROR_INVALIDDATA;
    5301             : 
    5302           1 :     tag = avio_rl32(pb);
    5303           1 :     if (tag != MKTAG('s','v','h','d')) {
    5304           0 :         av_log(c->fc, AV_LOG_ERROR, "Missing spherical video header\n");
    5305           0 :         return 0;
    5306             :     }
    5307           1 :     version = avio_r8(pb);
    5308           1 :     if (version != 0) {
    5309           0 :         av_log(c->fc, AV_LOG_WARNING, "Unknown spherical version %d\n",
    5310             :                version);
    5311           0 :         return 0;
    5312             :     }
    5313           1 :     avio_skip(pb, 3); /* flags */
    5314           1 :     avio_skip(pb, size - 12); /* metadata_source */
    5315             : 
    5316           1 :     size = avio_rb32(pb);
    5317           1 :     if (size > atom.size)
    5318           0 :         return AVERROR_INVALIDDATA;
    5319             : 
    5320           1 :     tag = avio_rl32(pb);
    5321           1 :     if (tag != MKTAG('p','r','o','j')) {
    5322           0 :         av_log(c->fc, AV_LOG_ERROR, "Missing projection box\n");
    5323           0 :         return 0;
    5324             :     }
    5325             : 
    5326           1 :     size = avio_rb32(pb);
    5327           1 :     if (size > atom.size)
    5328           0 :         return AVERROR_INVALIDDATA;
    5329             : 
    5330           1 :     tag = avio_rl32(pb);
    5331           1 :     if (tag != MKTAG('p','r','h','d')) {
    5332           0 :         av_log(c->fc, AV_LOG_ERROR, "Missing projection header box\n");
    5333           0 :         return 0;
    5334             :     }
    5335           1 :     version = avio_r8(pb);
    5336           1 :     if (version != 0) {
    5337           0 :         av_log(c->fc, AV_LOG_WARNING, "Unknown spherical version %d\n",
    5338             :                version);
    5339           0 :         return 0;
    5340             :     }
    5341           1 :     avio_skip(pb, 3); /* flags */
    5342             : 
    5343             :     /* 16.16 fixed point */
    5344           1 :     yaw   = avio_rb32(pb);
    5345           1 :     pitch = avio_rb32(pb);
    5346           1 :     roll  = avio_rb32(pb);
    5347             : 
    5348           1 :     size = avio_rb32(pb);
    5349           1 :     if (size > atom.size)
    5350           0 :         return AVERROR_INVALIDDATA;
    5351             : 
    5352           1 :     tag = avio_rl32(pb);
    5353           1 :     version = avio_r8(pb);
    5354           1 :     if (version != 0) {
    5355           0 :         av_log(c->fc, AV_LOG_WARNING, "Unknown spherical version %d\n",
    5356             :                version);
    5357           0 :         return 0;
    5358             :     }
    5359           1 :     avio_skip(pb, 3); /* flags */
    5360           1 :     switch (tag) {
    5361           0 :     case MKTAG('c','b','m','p'):
    5362           0 :         layout = avio_rb32(pb);
    5363           0 :         if (layout) {
    5364           0 :             av_log(c->fc, AV_LOG_WARNING,
    5365             :                    "Unsupported cubemap layout %d\n", layout);
    5366           0 :             return 0;
    5367             :         }
    5368           0 :         projection = AV_SPHERICAL_CUBEMAP;
    5369           0 :         padding = avio_rb32(pb);
    5370           0 :         break;
    5371           1 :     case MKTAG('e','q','u','i'):
    5372           1 :         t = avio_rb32(pb);
    5373           1 :         b = avio_rb32(pb);
    5374           1 :         l = avio_rb32(pb);
    5375           1 :         r = avio_rb32(pb);
    5376             : 
    5377           1 :         if (b >= UINT_MAX - t || r >= UINT_MAX - l) {
    5378           0 :             av_log(c->fc, AV_LOG_ERROR,
    5379             :                    "Invalid bounding rectangle coordinates "
    5380             :                    "%"PRIu32",%"PRIu32",%"PRIu32",%"PRIu32"\n", l, t, r, b);
    5381           0 :             return AVERROR_INVALIDDATA;
    5382             :         }
    5383             : 
    5384           1 :         if (l || t || r || b)
    5385           1 :             projection = AV_SPHERICAL_EQUIRECTANGULAR_TILE;
    5386             :         else
    5387           0 :             projection = AV_SPHERICAL_EQUIRECTANGULAR;
    5388           1 :         break;
    5389           0 :     default:
    5390           0 :         av_log(c->fc, AV_LOG_ERROR, "Unknown projection type\n");
    5391           0 :         return 0;
    5392             :     }
    5393             : 
    5394           1 :     sc->spherical = av_spherical_alloc(&sc->spherical_size);
    5395           1 :     if (!sc->spherical)
    5396           0 :         return AVERROR(ENOMEM);
    5397             : 
    5398           1 :     sc->spherical->projection = projection;
    5399             : 
    5400           1 :     sc->spherical->yaw   = yaw;
    5401           1 :     sc->spherical->pitch = pitch;
    5402           1 :     sc->spherical->roll  = roll;
    5403             : 
    5404           1 :     sc->spherical->padding = padding;
    5405             : 
    5406           1 :     sc->spherical->bound_left   = l;
    5407           1 :     sc->spherical->bound_top    = t;
    5408           1 :     sc->spherical->bound_right  = r;
    5409           1 :     sc->spherical->bound_bottom = b;
    5410             : 
    5411           1 :     return 0;
    5412             : }
    5413             : 
    5414           0 : static int mov_parse_uuid_spherical(MOVStreamContext *sc, AVIOContext *pb, size_t len)
    5415             : {
    5416           0 :     int ret = 0;
    5417           0 :     uint8_t *buffer = av_malloc(len + 1);
    5418             :     const char *val;
    5419             : 
    5420           0 :     if (!buffer)
    5421           0 :         return AVERROR(ENOMEM);
    5422           0 :     buffer[len] = '\0';
    5423             : 
    5424           0 :     ret = ffio_read_size(pb, buffer, len);
    5425           0 :     if (ret < 0)
    5426           0 :         goto out;
    5427             : 
    5428             :     /* Check for mandatory keys and values, try to support XML as best-effort */
    5429           0 :     if (!sc->spherical &&
    5430           0 :         av_stristr(buffer, "<GSpherical:StitchingSoftware>") &&
    5431           0 :         (val = av_stristr(buffer, "<GSpherical:Spherical>")) &&
    5432           0 :         av_stristr(val, "true") &&
    5433           0 :         (val = av_stristr(buffer, "<GSpherical:Stitched>")) &&
    5434           0 :         av_stristr(val, "true") &&
    5435           0 :         (val = av_stristr(buffer, "<GSpherical:ProjectionType>")) &&
    5436           0 :         av_stristr(val, "equirectangular")) {
    5437           0 :         sc->spherical = av_spherical_alloc(&sc->spherical_size);
    5438           0 :         if (!sc->spherical)
    5439           0 :             goto out;
    5440             : 
    5441           0 :         sc->spherical->projection = AV_SPHERICAL_EQUIRECTANGULAR;
    5442             : 
    5443           0 :         if (av_stristr(buffer, "<GSpherical:StereoMode>") && !sc->stereo3d) {
    5444             :             enum AVStereo3DType mode;
    5445             : 
    5446           0 :             if (av_stristr(buffer, "left-right"))
    5447           0 :                 mode = AV_STEREO3D_SIDEBYSIDE;
    5448           0 :             else if (av_stristr(buffer, "top-bottom"))
    5449           0 :                 mode = AV_STEREO3D_TOPBOTTOM;
    5450             :             else
    5451           0 :                 mode = AV_STEREO3D_2D;
    5452             : 
    5453           0 :             sc->stereo3d = av_stereo3d_alloc();
    5454           0 :             if (!sc->stereo3d)
    5455           0 :                 goto out;
    5456             : 
    5457           0 :             sc->stereo3d->type = mode;
    5458             :         }
    5459             : 
    5460             :         /* orientation */
    5461           0 :         val = av_stristr(buffer, "<GSpherical:InitialViewHeadingDegrees>");
    5462           0 :         if (val)
    5463           0 :             sc->spherical->yaw = strtol(val, NULL, 10) * (1 << 16);
    5464           0 :         val = av_stristr(buffer, "<GSpherical:InitialViewPitchDegrees>");
    5465           0 :         if (val)
    5466           0 :             sc->spherical->pitch = strtol(val, NULL, 10) * (1 << 16);
    5467           0 :         val = av_stristr(buffer, "<GSpherical:InitialViewRollDegrees>");
    5468           0 :         if (val)
    5469           0 :             sc->spherical->roll = strtol(val, NULL, 10) * (1 << 16);
    5470             :     }
    5471             : 
    5472           0 : out:
    5473           0 :     av_free(buffer);
    5474           0 :     return ret;
    5475             : }
    5476             : 
    5477          12 : static int mov_read_uuid(MOVContext *c, AVIOContext *pb, MOVAtom atom)
    5478             : {
    5479             :     AVStream *st;
    5480             :     MOVStreamContext *sc;
    5481             :     int64_t ret;
    5482             :     uint8_t uuid[16];
    5483             :     static const uint8_t uuid_isml_manifest[] = {
    5484             :         0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd,
    5485             :         0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66
    5486             :     };
    5487             :     static const uint8_t uuid_xmp[] = {
    5488             :         0xbe, 0x7a, 0xcf, 0xcb, 0x97, 0xa9, 0x42, 0xe8,
    5489             :         0x9c, 0x71, 0x99, 0x94, 0x91, 0xe3, 0xaf, 0xac
    5490             :     };
    5491             :     static const uint8_t uuid_spherical[] = {
    5492             :         0xff, 0xcc, 0x82, 0x63, 0xf8, 0x55, 0x4a, 0x93,
    5493             :         0x88, 0x14, 0x58, 0x7a, 0x02, 0x52, 0x1f, 0xdd,
    5494             :     };
    5495             : 
    5496          12 :     if (atom.size < sizeof(uuid) || atom.size >= FFMIN(INT_MAX, SIZE_MAX))
    5497           0 :         return AVERROR_INVALIDDATA;
    5498             : 
    5499          12 :     if (c->fc->nb_streams < 1)
    5500           1 :         return 0;
    5501          11 :     st = c->fc->streams[c->fc->nb_streams - 1];
    5502          11 :     sc = st->priv_data;
    5503             : 
    5504          11 :     ret = avio_read(pb, uuid, sizeof(uuid));
    5505          11 :     if (ret < 0) {
    5506           0 :         return ret;
    5507          11 :     } else if (ret != sizeof(uuid)) {
    5508           0 :         return AVERROR_INVALIDDATA;
    5509             :     }
    5510          11 :     if (!memcmp(uuid, uuid_isml_manifest, sizeof(uuid))) {
    5511             :         uint8_t *buffer, *ptr;
    5512             :         char *endptr;
    5513           0 :         size_t len = atom.size - sizeof(uuid);
    5514             : 
    5515           0 :         if (len < 4) {
    5516           0 :             return AVERROR_INVALIDDATA;
    5517             :         }
    5518           0 :         ret = avio_skip(pb, 4); // zeroes
    5519           0 :         len -= 4;
    5520             : 
    5521           0 :         buffer = av_mallocz(len + 1);
    5522           0 :         if (!buffer) {
    5523           0 :             return AVERROR(ENOMEM);
    5524             :         }
    5525           0 :         ret = avio_read(pb, buffer, len);
    5526           0 :         if (ret < 0) {
    5527           0 :             av_free(buffer);
    5528           0 :             return ret;
    5529           0 :         } else if (ret != len) {
    5530           0 :             av_free(buffer);
    5531           0 :             return AVERROR_INVALIDDATA;
    5532             :         }
    5533             : 
    5534           0 :         ptr = buffer;
    5535           0 :         while ((ptr = av_stristr(ptr, "systemBitrate=\""))) {
    5536           0 :             ptr += sizeof("systemBitrate=\"") - 1;
    5537           0 :             c->bitrates_count++;
    5538           0 :             c->bitrates = av_realloc_f(c->bitrates, c->bitrates_count, sizeof(*c->bitrates));
    5539           0 :             if (!c->bitrates) {
    5540           0 :                 c->bitrates_count = 0;
    5541           0 :                 av_free(buffer);
    5542           0 :                 return AVERROR(ENOMEM);
    5543             :             }
    5544           0 :             errno = 0;
    5545           0 :             ret = strtol(ptr, &endptr, 10);
    5546           0 :             if (ret < 0 || errno || *endptr != '"') {
    5547           0 :                 c->bitrates[c->bitrates_count - 1] = 0;
    5548             :             } else {
    5549           0 :                 c->bitrates[c->bitrates_count - 1] = ret;
    5550             :             }
    5551             :         }
    5552             : 
    5553           0 :         av_free(buffer);
    5554          11 :     } else if (!memcmp(uuid, uuid_xmp, sizeof(uuid))) {
    5555             :         uint8_t *buffer;
    5556           0 :         size_t len = atom.size - sizeof(uuid);
    5557           0 :         if (c->export_xmp) {
    5558           0 :             buffer = av_mallocz(len + 1);
    5559           0 :             if (!buffer) {
    5560           0 :                 return AVERROR(ENOMEM);
    5561             :             }
    5562           0 :             ret = avio_read(pb, buffer, len);
    5563           0 :             if (ret < 0) {
    5564           0 :                 av_free(buffer);
    5565           0 :                 return ret;
    5566           0 :             } else if (ret != len) {
    5567           0 :                 av_free(buffer);
    5568           0 :                 return AVERROR_INVALIDDATA;
    5569             :             }
    5570           0 :             buffer[len] = '\0';
    5571           0 :             av_dict_set(&c->fc->metadata, "xmp", buffer, 0);
    5572           0 :             av_free(buffer);
    5573             :         } else {
    5574             :             // skip all uuid atom, which makes it fast for long uuid-xmp file
    5575           0 :             ret = avio_skip(pb, len);
    5576           0 :             if (ret < 0)
    5577           0 :                 return ret;
    5578             :         }
    5579          11 :     } else if (!memcmp(uuid, uuid_spherical, sizeof(uuid))) {
    5580           0 :         size_t len = atom.size - sizeof(uuid);
    5581           0 :         ret = mov_parse_uuid_spherical(sc, pb, len);
    5582           0 :         if (ret < 0)
    5583           0 :             return ret;
    5584           0 :         if (!sc->spherical)
    5585           0 :             av_log(c->fc, AV_LOG_WARNING, "Invalid spherical metadata found\n");
    5586             :     }
    5587             : 
    5588          11 :     return 0;
    5589             : }
    5590             : 
    5591         114 : static int mov_read_free(MOVContext *c, AVIOContext *pb, MOVAtom atom)
    5592             : {
    5593             :     int ret;
    5594             :     uint8_t content[16];
    5595             : 
    5596         114 :     if (atom.size < 8)
    5597          48 :         return 0;
    5598             : 
    5599          66 :     ret = avio_read(pb, content, FFMIN(sizeof(content), atom.size));
    5600          66 :     if (ret < 0)
    5601           0 :         return ret;
    5602             : 
    5603          66 :     if (   !c->found_moov
    5604          21 :         && !c->found_mdat
    5605          13 :         && !memcmp(content, "Anevia\x1A\x1A", 8)
    5606           0 :         && c->use_mfra_for == FF_MOV_FLAG_MFRA_AUTO) {
    5607           0 :         c->use_mfra_for = FF_MOV_FLAG_MFRA_PTS;
    5608             :     }
    5609             : 
    5610          66 :     return 0;
    5611             : }
    5612             : 
    5613          25 : static int mov_read_frma(MOVContext *c, AVIOContext *pb, MOVAtom atom)
    5614             : {
    5615          25 :     uint32_t format = avio_rl32(pb);
    5616             :     MOVStreamContext *sc;
    5617             :     enum AVCodecID id;
    5618             :     AVStream *st;
    5619             : 
    5620          25 :     if (c->fc->nb_streams < 1)
    5621           0 :         return 0;
    5622          25 :     st = c->fc->streams[c->fc->nb_streams - 1];
    5623          25 :     sc = st->priv_data;
    5624             : 
    5625          25 :     switch (sc->format)
    5626             :     {
    5627           1 :     case MKTAG('e','n','c','v'):        // encrypted video
    5628             :     case MKTAG('e','n','c','a'):        // encrypted audio
    5629           1 :         id = mov_codec_id(st, format);
    5630           1 :         if (st->codecpar->codec_id != AV_CODEC_ID_NONE &&
    5631           0 :             st->codecpar->codec_id != id) {
    5632           0 :             av_log(c->fc, AV_LOG_WARNING,
    5633             :                    "ignoring 'frma' atom of '%.4s', stream has codec id %d\n",
    5634           0 :                    (char*)&format, st->codecpar->codec_id);
    5635           0 :             break;
    5636             :         }
    5637             : 
    5638           1 :         st->codecpar->codec_id = id;
    5639           1 :         sc->format = format;
    5640           1 :         break;
    5641             : 
    5642          24 :     default:
    5643          24 :         if (format != sc->format) {
    5644           0 :             av_log(c->fc, AV_LOG_WARNING,
    5645             :                    "ignoring 'frma' atom of '%.4s', stream format is '%.4s'\n",
    5646           0 :                    (char*)&format, (char*)&sc->format);
    5647             :         }
    5648          24 :         break;
    5649             :     }
    5650             : 
    5651          25 :     return 0;
    5652             : }
    5653             : 
    5654           1 : static int mov_read_senc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
    5655             : {
    5656             :     AVStream *st;
    5657             :     MOVStreamContext *sc;
    5658             :     size_t auxiliary_info_size;
    5659             : 
    5660           1 :     if (c->decryption_key_len == 0 || c->fc->nb_streams < 1)
    5661           0 :         return 0;
    5662             : 
    5663           1 :     st = c->fc->streams[c->fc->nb_streams - 1];
    5664           1 :     sc = st->priv_data;
    5665             : 
    5666           1 :     if (sc->cenc.aes_ctr) {
    5667           0 :         av_log(c->fc, AV_LOG_ERROR, "duplicate senc atom\n");
    5668           0 :         return AVERROR_INVALIDDATA;
    5669             :     }
    5670             : 
    5671           1 :     avio_r8(pb); /* version */
    5672           1 :     sc->cenc.use_subsamples = avio_rb24(pb) & 0x02; /* flags */
    5673             : 
    5674           1 :     avio_rb32(pb);        /* entries */
    5675             : 
    5676           1 :     if (atom.size < 8 || atom.size > FFMIN(INT_MAX, SIZE_MAX)) {
    5677           0 :         av_log(c->fc, AV_LOG_ERROR, "senc atom size %"PRId64" invalid\n", atom.size);
    5678           0 :         return AVERROR_INVALIDDATA;
    5679             :     }
    5680             : 
    5681             :     /* save the auxiliary info as is */
    5682           1 :     auxiliary_info_size = atom.size - 8;
    5683             : 
    5684           1 :     sc->cenc.auxiliary_info = av_malloc(auxiliary_info_size);
    5685           1 :     if (!sc->cenc.auxiliary_info) {
    5686           0 :         return AVERROR(ENOMEM);
    5687             :     }
    5688             : 
    5689           1 :     sc->cenc.auxiliary_info_end = sc->cenc.auxiliary_info + auxiliary_info_size;
    5690           1 :     sc->cenc.auxiliary_info_pos = sc->cenc.auxiliary_info;
    5691           1 :     sc->cenc.auxiliary_info_index = 0;
    5692             : 
    5693           1 :     if (avio_read(pb, sc->cenc.auxiliary_info, auxiliary_info_size) != auxiliary_info_size) {
    5694           0 :         av_log(c->fc, AV_LOG_ERROR, "failed to read the auxiliary info");
    5695           0 :         return AVERROR_INVALIDDATA;
    5696             :     }
    5697             : 
    5698             :     /* initialize the cipher */
    5699           1 :     sc->cenc.aes_ctr = av_aes_ctr_alloc();
    5700           1 :     if (!sc->cenc.aes_ctr) {
    5701           0 :         return AVERROR(ENOMEM);
    5702             :     }
    5703             : 
    5704           1 :     return av_aes_ctr_init(sc->cenc.aes_ctr, c->decryption_key);
    5705             : }
    5706             : 
    5707           1 : static int mov_read_saiz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
    5708             : {
    5709             :     AVStream *st;
    5710             :     MOVStreamContext *sc;
    5711             :     size_t data_size;
    5712             :     int atom_header_size;
    5713             :     int flags;
    5714             : 
    5715           1 :     if (c->decryption_key_len == 0 || c->fc->nb_streams < 1)
    5716           0 :         return 0;
    5717             : 
    5718           1 :     st = c->fc->streams[c->fc->nb_streams - 1];
    5719           1 :     sc = st->priv_data;
    5720             : 
    5721           1 :     if (sc->cenc.auxiliary_info_sizes || sc->cenc.auxiliary_info_default_size) {
    5722           0 :         av_log(c->fc, AV_LOG_ERROR, "duplicate saiz atom\n");
    5723           0 :         return AVERROR_INVALIDDATA;
    5724             :     }
    5725             : 
    5726           1 :     atom_header_size = 9;
    5727             : 
    5728           1 :     avio_r8(pb); /* version */
    5729           1 :     flags = avio_rb24(pb);
    5730             : 
    5731           1 :     if ((flags & 0x01) != 0) {
    5732           0 :         atom_header_size += 8;
    5733             : 
    5734           0 :         avio_rb32(pb);    /* info type */
    5735           0 :         avio_rb32(pb);    /* info type param */
    5736             :     }
    5737             : 
    5738           1 :     sc->cenc.auxiliary_info_default_size = avio_r8(pb);
    5739           1 :     avio_rb32(pb);    /* entries */
    5740             : 
    5741           1 :     if (atom.size <= atom_header_size) {
    5742           0 :         return 0;
    5743             :     }
    5744             : 
    5745           1 :     if (atom.size > FFMIN(INT_MAX, SIZE_MAX)) {
    5746           0 :         av_log(c->fc, AV_LOG_ERROR, "saiz atom auxiliary_info_sizes size %"PRId64" invalid\n", atom.size);
    5747           0 :         return AVERROR_INVALIDDATA;
    5748             :     }
    5749             : 
    5750             :     /* save the auxiliary info sizes as is */
    5751           1 :     data_size = atom.size - atom_header_size;
    5752             : 
    5753           1 :     sc->cenc.auxiliary_info_sizes = av_malloc(data_size);
    5754           1 :     if (!sc->cenc.auxiliary_info_sizes) {
    5755           0 :         return AVERROR(ENOMEM);
    5756             :     }
    5757             : 
    5758           1 :     sc->cenc.auxiliary_info_sizes_count = data_size;
    5759             : 
    5760           1 :     if (avio_read(pb, sc->cenc.auxiliary_info_sizes, data_size) != data_size) {
    5761           0 :         av_log(c->fc, AV_LOG_ERROR, "failed to read the auxiliary info sizes");
    5762           0 :         return AVERROR_INVALIDDATA;
    5763             :     }
    5764             : 
    5765           1 :     return 0;
    5766             : }
    5767             : 
    5768           0 : static int mov_read_dfla(MOVContext *c, AVIOContext *pb, MOVAtom atom)
    5769             : {
    5770             :     AVStream *st;
    5771             :     int last, type, size, ret;
    5772             :     uint8_t buf[4];
    5773             : 
    5774           0 :     if (c->fc->nb_streams < 1)
    5775           0 :         return 0;
    5776           0 :     st = c->fc->streams[c->fc->nb_streams-1];
    5777             : 
    5778           0 :     if ((uint64_t)atom.size > (1<<30) || atom.size < 42)
    5779           0 :         return AVERROR_INVALIDDATA;
    5780             : 
    5781             :     /* Check FlacSpecificBox version. */
    5782           0 :     if (avio_r8(pb) != 0)
    5783           0 :         return AVERROR_INVALIDDATA;
    5784             : 
    5785           0 :     avio_rb24(pb); /* Flags */
    5786             : 
    5787           0 :     avio_read(pb, buf, sizeof(buf));
    5788           0 :     flac_parse_block_header(buf, &last, &type, &size);
    5789             : 
    5790           0 :     if (type != FLAC_METADATA_TYPE_STREAMINFO || size != FLAC_STREAMINFO_SIZE) {
    5791           0 :         av_log(c->fc, AV_LOG_ERROR, "STREAMINFO must be first FLACMetadataBlock\n");
    5792           0 :         return AVERROR_INVALIDDATA;
    5793             :     }
    5794             : 
    5795           0 :     ret = ff_get_extradata(c->fc, st->codecpar, pb, size);
    5796           0 :     if (ret < 0)
    5797           0 :         return ret;
    5798             : 
    5799           0 :     if (!last)
    5800           0 :         av_log(c->fc, AV_LOG_WARNING, "non-STREAMINFO FLACMetadataBlock(s) ignored\n");
    5801             : 
    5802           0 :     return 0;
    5803             : }
    5804             : 
    5805           2 : static int mov_seek_auxiliary_info(MOVContext *c, MOVStreamContext *sc, int64_t index)
    5806             : {
    5807           2 :     size_t auxiliary_info_seek_offset = 0;
    5808             :     int i;
    5809             : 
    5810           2 :     if (sc->cenc.auxiliary_info_default_size) {
    5811           0 :         auxiliary_info_seek_offset = (size_t)sc->cenc.auxiliary_info_default_size * index;
    5812           2 :     } else if (sc->cenc.auxiliary_info_sizes) {
    5813           2 :         if (index > sc->cenc.auxiliary_info_sizes_count) {
    5814           0 :             av_log(c, AV_LOG_ERROR, "current sample %"PRId64" greater than the number of auxiliary info sample sizes %"SIZE_SPECIFIER"\n",
    5815             :                 index, sc->cenc.auxiliary_info_sizes_count);
    5816           0 :             return AVERROR_INVALIDDATA;
    5817             :         }
    5818             : 
    5819          38 :         for (i = 0; i < index; i++) {
    5820          36 :             auxiliary_info_seek_offset += sc->cenc.auxiliary_info_sizes[i];
    5821             :         }
    5822             :     }
    5823             : 
    5824           2 :     if (auxiliary_info_seek_offset > sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info) {
    5825           0 :         av_log(c, AV_LOG_ERROR, "auxiliary info offset %"SIZE_SPECIFIER" greater than auxiliary info size %"SIZE_SPECIFIER"\n",
    5826           0 :             auxiliary_info_seek_offset, (size_t)(sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info));
    5827           0 :         return AVERROR_INVALIDDATA;
    5828             :     }
    5829             : 
    5830           2 :     sc->cenc.auxiliary_info_pos = sc->cenc.auxiliary_info + auxiliary_info_seek_offset;
    5831           2 :     sc->cenc.auxiliary_info_index = index;
    5832           2 :     return 0;
    5833             : }
    5834             : 
    5835          74 : static int cenc_filter(MOVContext *c, MOVStreamContext *sc, int64_t index, uint8_t *input, int size)
    5836             : {
    5837             :     uint32_t encrypted_bytes;
    5838             :     uint16_t subsample_count;
    5839             :     uint16_t clear_bytes;
    5840          74 :     uint8_t* input_end = input + size;
    5841             :     int ret;
    5842             : 
    5843          74 :     if (index != sc->cenc.auxiliary_info_index) {
    5844           2 :         ret = mov_seek_auxiliary_info(c, sc, index);
    5845           2 :         if (ret < 0) {
    5846           0 :             return ret;
    5847             :         }
    5848             :     }
    5849             : 
    5850             :     /* read the iv */
    5851          74 :     if (AES_CTR_IV_SIZE > sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info_pos) {
    5852           0 :         av_log(c->fc, AV_LOG_ERROR, "failed to read iv from the auxiliary info\n");
    5853           0 :         return AVERROR_INVALIDDATA;
    5854             :     }
    5855             : 
    5856          74 :     av_aes_ctr_set_iv(sc->cenc.aes_ctr, sc->cenc.auxiliary_info_pos);
    5857          74 :     sc->cenc.auxiliary_info_pos += AES_CTR_IV_SIZE;
    5858             : 
    5859          74 :     if (!sc->cenc.use_subsamples)
    5860             :     {
    5861             :         /* decrypt the whole packet */
    5862           0 :         av_aes_ctr_crypt(sc->cenc.aes_ctr, input, input, size);
    5863           0 :         return 0;
    5864             :     }
    5865             : 
    5866             :     /* read the subsample count */
    5867          74 :     if (sizeof(uint16_t) > sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info_pos) {
    5868           0 :         av_log(c->fc, AV_LOG_ERROR, "failed to read subsample count from the auxiliary info\n");
    5869           0 :         return AVERROR_INVALIDDATA;
    5870             :     }
    5871             : 
    5872          74 :     subsample_count = AV_RB16(sc->cenc.auxiliary_info_pos);
    5873          74 :     sc->cenc.auxiliary_info_pos += sizeof(uint16_t);
    5874             : 
    5875         148 :     for (; subsample_count > 0; subsample_count--)
    5876             :     {
    5877          74 :         if (6 > sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info_pos) {
    5878           0 :             av_log(c->fc, AV_LOG_ERROR, "failed to read subsample from the auxiliary info\n");
    5879           0 :             return AVERROR_INVALIDDATA;
    5880             :         }
    5881             : 
    5882             :         /* read the number of clear / encrypted bytes */
    5883          74 :         clear_bytes = AV_RB16(sc->cenc.auxiliary_info_pos);
    5884          74 :         sc->cenc.auxiliary_info_pos += sizeof(uint16_t);
    5885          74 :         encrypted_bytes = AV_RB32(sc->cenc.auxiliary_info_pos);
    5886          74 :         sc->cenc.auxiliary_info_pos += sizeof(uint32_t);
    5887             : 
    5888          74 :         if ((uint64_t)clear_bytes + encrypted_bytes > input_end - input) {
    5889           0 :             av_log(c->fc, AV_LOG_ERROR, "subsample size exceeds the packet size left\n");
    5890           0 :             return AVERROR_INVALIDDATA;
    5891             :         }
    5892             : 
    5893             :         /* skip the clear bytes */
    5894          74 :         input += clear_bytes;
    5895             : 
    5896             :         /* decrypt the encrypted bytes */
    5897          74 :         av_aes_ctr_crypt(sc->cenc.aes_ctr, input, input, encrypted_bytes);
    5898          74 :         input += encrypted_bytes;
    5899             :     }
    5900             : 
    5901          74 :     if (input < input_end) {
    5902           0 :         av_log(c->fc, AV_LOG_ERROR, "leftover packet bytes after subsample processing\n");
    5903           0 :         return AVERROR_INVALIDDATA;
    5904             :     }
    5905             : 
    5906          74 :     sc->cenc.auxiliary_info_index++;
    5907          74 :     return 0;
    5908             : }
    5909             : 
    5910           0 : static int mov_read_dops(MOVContext *c, AVIOContext *pb, MOVAtom atom)
    5911             : {
    5912           0 :     const int OPUS_SEEK_PREROLL_MS = 80;
    5913             :     AVStream *st;
    5914             :     size_t size;
    5915             :     int16_t pre_skip;
    5916             : 
    5917           0 :     if (c->fc->nb_streams < 1)
    5918           0 :         return 0;
    5919           0 :     st = c->fc->streams[c->fc->nb_streams-1];
    5920             : 
    5921           0 :     if ((uint64_t)atom.size > (1<<30) || atom.size < 11)
    5922           0 :         return AVERROR_INVALIDDATA;
    5923             : 
    5924             :     /* Check OpusSpecificBox version. */
    5925           0 :     if (avio_r8(pb) != 0) {
    5926           0 :         av_log(c->fc, AV_LOG_ERROR, "unsupported OpusSpecificBox version\n");
    5927           0 :         return AVERROR_INVALIDDATA;
    5928             :     }
    5929             : 
    5930             :     /* OpusSpecificBox size plus magic for Ogg OpusHead header. */
    5931           0 :     size = atom.size + 8;
    5932             : 
    5933           0 :     if (ff_alloc_extradata(st->codecpar, size))
    5934           0 :         return AVERROR(ENOMEM);
    5935             : 
    5936           0 :     AV_WL32(st->codecpar->extradata, MKTAG('O','p','u','s'));
    5937           0 :     AV_WL32(st->codecpar->extradata + 4, MKTAG('H','e','a','d'));
    5938           0 :     AV_WB8(st->codecpar->extradata + 8, 1); /* OpusHead version */
    5939           0 :     avio_read(pb, st->codecpar->extradata + 9, size - 9);
    5940             : 
    5941             :     /* OpusSpecificBox is stored in big-endian, but OpusHead is
    5942             :        little-endian; aside from the preceeding magic and version they're
    5943             :        otherwise currently identical.  Data after output gain at offset 16
    5944             :        doesn't need to be bytewapped. */
    5945           0 :     pre_skip = AV_RB16(st->codecpar->extradata + 10);
    5946           0 :     AV_WL16(st->codecpar->extradata + 10, pre_skip);
    5947           0 :     AV_WL32(st->codecpar->extradata + 12, AV_RB32(st->codecpar->extradata + 12));
    5948           0 :     AV_WL16(st->codecpar->extradata + 16, AV_RB16(st->codecpar->extradata + 16));
    5949             : 
    5950           0 :     st->codecpar->initial_padding = pre_skip;
    5951           0 :     st->codecpar->seek_preroll = av_rescale_q(OPUS_SEEK_PREROLL_MS,
    5952           0 :                                               (AVRational){1, 1000},
    5953           0 :                                               (AVRational){1, 48000});
    5954             : 
    5955           0 :     return 0;
    5956             : }
    5957             : 
    5958             : static const MOVParseTableEntry mov_default_parse_table[] = {
    5959             : { MKTAG('A','C','L','R'), mov_read_aclr },
    5960             : { MKTAG('A','P','R','G'), mov_read_avid },
    5961             : { MKTAG('A','A','L','P'), mov_read_avid },
    5962             : { MKTAG('A','R','E','S'), mov_read_ares },
    5963             : { MKTAG('a','v','s','s'), mov_read_avss },
    5964             : { MKTAG('c','h','p','l'), mov_read_chpl },
    5965             : { MKTAG('c','o','6','4'), mov_read_stco },
    5966             : { MKTAG('c','o','l','r'), mov_read_colr },
    5967             : { MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
    5968             : { MKTAG('d','i','n','f'), mov_read_default },
    5969             : { MKTAG('D','p','x','E'), mov_read_dpxe },
    5970             : { MKTAG('d','r','e','f'), mov_read_dref },
    5971             : { MKTAG('e','d','t','s'), mov_read_default },
    5972             : { MKTAG('e','l','s','t'), mov_read_elst },
    5973             : { MKTAG('e','n','d','a'), mov_read_enda },
    5974             : { MKTAG('f','i','e','l'), mov_read_fiel },
    5975             : { MKTAG('a','d','r','m'), mov_read_adrm },
    5976             : { MKTAG('f','t','y','p'), mov_read_ftyp },
    5977             : { MKTAG('g','l','b','l'), mov_read_glbl },
    5978             : { MKTAG('h','d','l','r'), mov_read_hdlr },
    5979             : { MKTAG('i','l','s','t'), mov_read_ilst },
    5980             : { MKTAG('j','p','2','h'), mov_read_jp2h },
    5981             : { MKTAG('m','d','a','t'), mov_read_mdat },
    5982             : { MKTAG('m','d','h','d'), mov_read_mdhd },
    5983             : { MKTAG('m','d','i','a'), mov_read_default },
    5984             : { MKTAG('m','e','t','a'), mov_read_meta },
    5985             : { MKTAG('m','i','n','f'), mov_read_default },
    5986             : { MKTAG('m','o','o','f'), mov_read_moof },
    5987             : { MKTAG('m','o','o','v'), mov_read_moov },
    5988             : { MKTAG('m','v','e','x'), mov_read_default },
    5989             : { MKTAG('m','v','h','d'), mov_read_mvhd },
    5990             : { MKTAG('S','M','I',' '), mov_read_svq3 },
    5991             : { MKTAG('a','l','a','c'), mov_read_alac }, /* alac specific atom */
    5992             : { MKTAG('a','v','c','C'), mov_read_glbl },
    5993             : { MKTAG('p','a','s','p'), mov_read_pasp },
    5994             : { MKTAG('s','i','d','x'), mov_read_sidx },
    5995             : { MKTAG('s','t','b','l'), mov_read_default },
    5996             : { MKTAG('s','t','c','o'), mov_read_stco },
    5997             : { MKTAG('s','t','p','s'), mov_read_stps },
    5998             : { MKTAG('s','t','r','f'), mov_read_strf },
    5999             : { MKTAG('s','t','s','c'), mov_read_stsc },
    6000             : { MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
    6001             : { MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
    6002             : { MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
    6003             : { MKTAG('s','t','t','s'), mov_read_stts },
    6004             : { MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */
    6005             : { MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
    6006             : { MKTAG('t','f','d','t'), mov_read_tfdt },
    6007             : { MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
    6008             : { MKTAG('t','r','a','k'), mov_read_trak },
    6009             : { MKTAG('t','r','a','f'), mov_read_default },
    6010             : { MKTAG('t','r','e','f'), mov_read_default },
    6011             : { MKTAG('t','m','c','d'), mov_read_tmcd },
    6012             : { MKTAG('c','h','a','p'), mov_read_chap },
    6013             : { MKTAG('t','r','e','x'), mov_read_trex },
    6014             : { MKTAG('t','r','u','n'), mov_read_trun },
    6015             : { MKTAG('u','d','t','a'), mov_read_default },
    6016             : { MKTAG('w','a','v','e'), mov_read_wave },
    6017             : { MKTAG('e','s','d','s'), mov_read_esds },
    6018             : { MKTAG('d','a','c','3'), mov_read_dac3 }, /* AC-3 info */
    6019             : { MKTAG('d','e','c','3'), mov_read_dec3 }, /* EAC-3 info */
    6020             : { MKTAG('d','d','t','s'), mov_read_ddts }, /* DTS audio descriptor */
    6021             : { MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
    6022             : { MKTAG('w','f','e','x'), mov_read_wfex },
    6023             : { MKTAG('c','m','o','v'), mov_read_cmov },
    6024             : { MKTAG('c','h','a','n'), mov_read_chan }, /* channel layout */
    6025             : { MKTAG('d','v','c','1'), mov_read_dvc1 },
    6026             : { MKTAG('s','b','g','p'), mov_read_sbgp },
    6027             : { MKTAG('h','v','c','C'), mov_read_glbl },
    6028             : { MKTAG('u','u','i','d'), mov_read_uuid },
    6029             : { MKTAG('C','i','n', 0x8e), mov_read_targa_y216 },
    6030             : { MKTAG('f','r','e','e'), mov_read_free },
    6031             : { MKTAG('-','-','-','-'), mov_read_custom },
    6032             : { MKTAG('s','i','n','f'), mov_read_default },
    6033             : { MKTAG('f','r','m','a'), mov_read_frma },
    6034             : { MKTAG('s','e','n','c'), mov_read_senc },
    6035             : { MKTAG('s','a','i','z'), mov_read_saiz },
    6036             : { MKTAG('d','f','L','a'), mov_read_dfla },
    6037             : { MKTAG('s','t','3','d'), mov_read_st3d }, /* stereoscopic 3D video box */
    6038             : { MKTAG('s','v','3','d'), mov_read_sv3d }, /* spherical video box */
    6039             : { MKTAG('d','O','p','s'), mov_read_dops },
    6040             : { MKTAG('S','m','D','m'), mov_read_smdm },
    6041             : { MKTAG('C','o','L','L'), mov_read_coll },
    6042             : { MKTAG('v','p','c','C'), mov_read_vpcc },
    6043             : { MKTAG('m','d','c','v'), mov_read_mdcv },
    6044             : { MKTAG('c','l','l','i'), mov_read_clli },
    6045             : { 0, NULL }
    6046             : };
    6047             : 
    6048        4536 : static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom)
    6049             : {
    6050        4536 :     int64_t total_size = 0;
    6051             :     MOVAtom a;
    6052             :     int i;
    6053             : 
    6054        4536 :     if (c->atom_depth > 10) {
    6055           0 :         av_log(c->fc, AV_LOG_ERROR, "Atoms too deeply nested\n");
    6056           0 :         return AVERROR_INVALIDDATA;
    6057             :     }
    6058        4536 :     c->atom_depth ++;
    6059             : 
    6060        4536 :     if (atom.size < 0)
    6061           0 :         atom.size = INT64_MAX;
    6062       21885 :     while (total_size <= atom.size - 8 && !avio_feof(pb)) {
    6063       13163 :         int (*parse)(MOVContext*, AVIOContext*, MOVAtom) = NULL;
    6064       13163 :         a.size = atom.size;
    6065       13163 :         a.type=0;
    6066       13163 :         if (atom.size >= 8) {
    6067       13163 :             a.size = avio_rb32(pb);
    6068       13163 :             a.type = avio_rl32(pb);
    6069       13277 :             if (a.type == MKTAG('f','r','e','e') &&
    6070         228 :                 a.size >= 8 &&
    6071         228 :                 c->fc->strict_std_compliance < FF_COMPLIANCE_STRICT &&
    6072         114 :                 c->moov_retry) {
    6073             :                 uint8_t buf[8];
    6074           0 :                 uint32_t *type = (uint32_t *)buf + 1;
    6075           0 :                 if (avio_read(pb, buf, 8) != 8)
    6076           0 :                     return AVERROR_INVALIDDATA;
    6077           0 :                 avio_seek(pb, -8, SEEK_CUR);
    6078           0 :                 if (*type == MKTAG('m','v','h','d') ||
    6079           0 :                     *type == MKTAG('c','m','o','v')) {
    6080           0 :                     av_log(c->fc, AV_LOG_ERROR, "Detected moov in a free atom.\n");
    6081           0 :                     a.type = MKTAG('m','o','o','v');
    6082             :                 }
    6083             :             }
    6084       24184 :             if (atom.type != MKTAG('r','o','o','t') &&
    6085       11021 :                 atom.type != MKTAG('m','o','o','v'))
    6086             :             {
    6087       10026 :                 if (a.type == MKTAG('t','r','a','k') || a.type == MKTAG('m','d','a','t'))
    6088             :                 {
    6089           0 :                     av_log(c->fc, AV_LOG_ERROR, "Broken file, trak/mdat not at top-level\n");
    6090           0 :                     avio_skip(pb, -8);
    6091           0 :                     c->atom_depth --;
    6092           0 :                     return 0;
    6093             :                 }
    6094             :             }
    6095       13163 :             total_size += 8;
    6096       13163 :             if (a.size == 1 && total_size + 8 <= atom.size) { /* 64 bit extended size */
    6097           6 :                 a.size = avio_rb64(pb) - 8;
    6098           6 :                 total_size += 8;
    6099             :             }
    6100             :         }
    6101       39489 :         av_log(c->fc, AV_LOG_TRACE, "type:'%s' parent:'%s' sz: %"PRId64" %"PRId64" %"PRId64"\n",
    6102       26326 :                av_fourcc2str(a.type), av_fourcc2str(atom.type), a.size, total_size, atom.size);
    6103       13163 :         if (a.size == 0) {
    6104           6 :             a.size = atom.size - total_size + 8;
    6105             :         }
    6106       13163 :         a.size -= 8;
    6107       13163 :         if (a.size < 0)
    6108           0 :             break;
    6109       13163 :         a.size = FFMIN(a.size, atom.size - total_size);
    6110             : 
    6111      524777 :         for (i = 0; mov_default_parse_table[i].type; i++)
    6112      523400 :             if (mov_default_parse_table[i].type == a.type) {
    6113       11786 :                 parse = mov_default_parse_table[i].parse;
    6114       11786 :                 break;
    6115             :             }
    6116             : 
    6117             :         // container is user data
    6118       14408 :         if (!parse && (atom.type == MKTAG('u','d','t','a') ||
    6119        1245 :                        atom.type == MKTAG('i','l','s','t')))
    6120         301 :             parse = mov_read_udta_string;
    6121             : 
    6122             :         // Supports parsing the QuickTime Metadata Keys.
    6123             :         // https://developer.apple.com/library/mac/documentation/QuickTime/QTFF/Metadata/Metadata.html
    6124       13168 :         if (!parse && c->found_hdlr_mdta &&
    6125          10 :             atom.type == MKTAG('m','e','t','a') &&
    6126           5 :             a.type == MKTAG('k','e','y','s')) {
    6127           5 :             parse = mov_read_keys;
    6128             :         }
    6129             : 
    6130       13163 :         if (!parse) { /* skip leaf atoms data */
    6131        1071 :             avio_skip(pb, a.size);
    6132             :         } else {
    6133       12092 :             int64_t start_pos = avio_tell(pb);
    6134             :             int64_t left;
    6135       12092 :             int err = parse(c, pb, a);
    6136       12092 :             if (err < 0) {
    6137           0 :                 c->atom_depth --;
    6138           0 :                 return err;
    6139             :             }
    6140       14721 :             if (c->found_moov && c->found_mdat &&
    6141        7884 :                 ((!(pb->seekable & AVIO_SEEKABLE_NORMAL) || c->fc->flags & AVFMT_FLAG_IGNIDX || c->frag_index.complete) ||
    6142        2626 :                  start_pos + a.size == avio_size(pb))) {
    6143         350 :                 if (!(pb->seekable & AVIO_SEEKABLE_NORMAL) || c->fc->flags & AVFMT_FLAG_IGNIDX || c->frag_index.complete)
    6144           3 :                     c->next_root_atom = start_pos + a.size;
    6145         350 :                 c->atom_depth --;
    6146         350 :                 return 0;
    6147             :             }
    6148       11742 :             left = a.size - avio_tell(pb) + start_pos;
    6149       11742 :             if (left > 0) /* skip garbage at atom end */
    6150         992 :                 avio_skip(pb, left);
    6151       10750 :             else if (left < 0) {
    6152           2 :                 av_log(c->fc, AV_LOG_WARNING,
    6153             :                        "overread end of atom '%.4s' by %"PRId64" bytes\n",
    6154             :                        (char*)&a.type, -left);
    6155           2 :                 avio_seek(pb, left, SEEK_CUR);
    6156             :             }
    6157             :         }
    6158             : 
    6159       12813 :         total_size += a.size;
    6160             :     }
    6161             : 
    6162        4186 :     if (total_size < atom.size && atom.size < 0x7ffff)
    6163          83 :         avio_skip(pb, atom.size - total_size);
    6164             : 
    6165        4186 :     c->atom_depth --;
    6166        4186 :     return 0;
    6167             : }
    6168             : 
    6169        6130 : static int mov_probe(AVProbeData *p)
    6170             : {
    6171             :     int64_t offset;
    6172             :     uint32_t tag;
    6173        6130 :     int score = 0;
    6174        6130 :     int moov_offset = -1;
    6175             : 
    6176             :     /* check file header */
    6177        6130 :     offset = 0;
    6178             :     for (;;) {
    6179             :         /* ignore invalid offset */
    6180       51652 :         if ((offset + 8) > (unsigned int)p->buf_size)
    6181        6130 :             break;
    6182       22761 :         tag = AV_RL32(p->buf + offset + 4);
    6183       22761 :         switch(tag) {
    6184             :         /* check for obvious tags */
    6185         114 :         case MKTAG('m','o','o','v'):
    6186         114 :             moov_offset = offset + 4;
    6187         714 :         case MKTAG('m','d','a','t'):
    6188             :         case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
    6189             :         case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
    6190             :         case MKTAG('f','t','y','p'):
    6191         720 :             if (AV_RB32(p->buf+offset) < 8 &&
    6192          12 :                 (AV_RB32(p->buf+offset) != 1 ||
    6193          12 :                  offset + 12 > (unsigned int)p->buf_size ||
    6194           6 :                  AV_RB64(p->buf+offset + 8) == 0)) {
    6195           0 :                 score = FFMAX(score, AVPROBE_SCORE_EXTENSION);
    6196        1027 :             } else if (tag == MKTAG('f','t','y','p') &&
    6197         313 :                        (   AV_RL32(p->buf + offset + 8) == MKTAG('j','p','2',' ')
    6198         313 :                         || AV_RL32(p->buf + offset + 8) == MKTAG('j','p','x',' ')
    6199             :                     )) {
    6200           0 :                 score = FFMAX(score, 5);
    6201             :             } else {
    6202         714 :                 score = AVPROBE_SCORE_MAX;
    6203             :             }
    6204         714 :             offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
    6205         714 :             break;
    6206             :         /* those are more common words, so rate then a bit less */
    6207         265 :         case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
    6208             :         case MKTAG('w','i','d','e'):
    6209             :         case MKTAG('f','r','e','e'):
    6210             :         case MKTAG('j','u','n','k'):
    6211             :         case MKTAG('p','i','c','t'):
    6212         265 :             score  = FFMAX(score, AVPROBE_SCORE_MAX - 5);
    6213         265 :             offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
    6214         265 :             break;
    6215           1 :         case MKTAG(0x82,0x82,0x7f,0x7d):
    6216             :         case MKTAG('s','k','i','p'):
    6217             :         case MKTAG('u','u','i','d'):
    6218             :         case MKTAG('p','r','f','l'):
    6219             :             /* if we only find those cause probedata is too small at least rate them */
    6220           1 :             score  = FFMAX(score, AVPROBE_SCORE_EXTENSION);
    6221           1 :             offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
    6222           1 :             break;
    6223       21781 :         default:
    6224       21781 :             offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
    6225             :         }
    6226             :     }
    6227        6130 :     if(score > AVPROBE_SCORE_MAX - 50 && moov_offset != -1) {
    6228             :         /* moov atom in the header - we should make sure that this is not a
    6229             :          * MOV-packed MPEG-PS */
    6230         114 :         offset = moov_offset;
    6231             : 
    6232      112497 :         while(offset < (p->buf_size - 16)){ /* Sufficient space */
    6233             :                /* We found an actual hdlr atom */
    6234      112390 :             if(AV_RL32(p->buf + offset     ) == MKTAG('h','d','l','r') &&
    6235         141 :                AV_RL32(p->buf + offset +  8) == MKTAG('m','h','l','r') &&
    6236          20 :                AV_RL32(p->buf + offset + 12) == MKTAG('M','P','E','G')){
    6237           0 :                 av_log(NULL, AV_LOG_WARNING, "Found media data tag MPEG indicating this is a MOV-packed MPEG-PS.\n");
    6238             :                 /* We found a media handler reference atom describing an
    6239             :                  * MPEG-PS-in-MOV, return a
    6240             :                  * low score to force expanding the probe window until
    6241             :                  * mpegps_probe finds what it needs */
    6242           0 :                 return 5;
    6243             :             }else
    6244             :                 /* Keep looking */
    6245      112269 :                 offset+=2;
    6246             :         }
    6247             :     }
    6248             : 
    6249        6130 :     return score;
    6250             : }
    6251             : 
    6252             : // must be done after parsing all trak because there's no order requirement
    6253           0 : static void mov_read_chapters(AVFormatContext *s)
    6254             : {
    6255           0 :     MOVContext *mov = s->priv_data;
    6256             :     AVStream *st;
    6257             :     MOVStreamContext *sc;
    6258             :     int64_t cur_pos;
    6259             :     int i, j;
    6260             :     int chapter_track;
    6261             : 
    6262           0 :     for (j = 0; j < mov->nb_chapter_tracks; j++) {
    6263           0 :         chapter_track = mov->chapter_tracks[j];
    6264           0 :         st = NULL;
    6265           0 :         for (i = 0; i < s->nb_streams; i++)
    6266           0 :             if (s->streams[i]->id == chapter_track) {
    6267           0 :                 st = s->streams[i];
    6268           0 :                 break;
    6269             :             }
    6270           0 :         if (!st) {
    6271           0 :             av_log(s, AV_LOG_ERROR, "Referenced QT chapter track not found\n");
    6272           0 :             continue;
    6273             :         }
    6274             : 
    6275           0 :         sc = st->priv_data;
    6276           0 :         cur_pos = avio_tell(sc->pb);
    6277             : 
    6278           0 :         if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
    6279           0 :             st->disposition |= AV_DISPOSITION_ATTACHED_PIC | AV_DISPOSITION_TIMED_THUMBNAILS;
    6280           0 :             if (st->nb_index_entries) {
    6281             :                 // Retrieve the first frame, if possible
    6282             :                 AVPacket pkt;
    6283           0 :                 AVIndexEntry *sample = &st->index_entries[0];
    6284           0 :                 if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
    6285           0 :                     av_log(s, AV_LOG_ERROR, "Failed to retrieve first frame\n");
    6286           0 :                     goto finish;
    6287             :                 }
    6288             : 
    6289           0 :                 if (av_get_packet(sc->pb, &pkt, sample->size) < 0)
    6290           0 :                     goto finish;
    6291             : 
    6292           0 :                 st->attached_pic              = pkt;
    6293           0 :                 st->attached_pic.stream_index = st->index;
    6294           0 :                 st->attached_pic.flags       |= AV_PKT_FLAG_KEY;
    6295             :             }
    6296             :         } else {
    6297           0 :             st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
    6298           0 :             st->codecpar->codec_id = AV_CODEC_ID_BIN_DATA;
    6299           0 :             st->discard = AVDISCARD_ALL;
    6300           0 :             for (i = 0; i < st->nb_index_entries; i++) {
    6301           0 :                 AVIndexEntry *sample = &st->index_entries[i];
    6302           0 :                 int64_t end = i+1 < st->nb_index_entries ? st->index_entries[i+1].timestamp : st->duration;
    6303             :                 uint8_t *title;
    6304             :                 uint16_t ch;
    6305             :                 int len, title_len;
    6306             : 
    6307           0 :                 if (end < sample->timestamp) {
    6308           0 :                     av_log(s, AV_LOG_WARNING, "ignoring stream duration which is shorter than chapters\n");
    6309           0 :                     end = AV_NOPTS_VALUE;
    6310             :                 }
    6311             : 
    6312           0 :                 if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
    6313           0 :                     av_log(s, AV_LOG_ERROR, "Chapter %d not found in file\n", i);
    6314           0 :                     goto finish;
    6315             :                 }
    6316             : 
    6317             :                 // the first two bytes are the length of the title
    6318           0 :                 len = avio_rb16(sc->pb);
    6319           0 :                 if (len > sample->size-2)
    6320           0 :                     continue;
    6321           0 :                 title_len = 2*len + 1;
    6322           0 :                 if (!(title = av_mallocz(title_len)))
    6323           0 :                     goto finish;
    6324             : 
    6325             :                 // The samples could theoretically be in any encoding if there's an encd
    6326             :                 // atom following, but in practice are only utf-8 or utf-16, distinguished
    6327             :                 // instead by the presence of a BOM
    6328           0 :                 if (!len) {
    6329           0 :                     title[0] = 0;
    6330             :                 } else {
    6331           0 :                     ch = avio_rb16(sc->pb);
    6332           0 :                     if (ch == 0xfeff)
    6333           0 :                         avio_get_str16be(sc->pb, len, title, title_len);
    6334           0 :                     else if (ch == 0xfffe)
    6335           0 :                         avio_get_str16le(sc->pb, len, title, title_len);
    6336             :                     else {
    6337           0 :                         AV_WB16(title, ch);
    6338           0 :                         if (len == 1 || len == 2)
    6339           0 :                             title[len] = 0;
    6340             :                         else
    6341           0 :                             avio_get_str(sc->pb, INT_MAX, title + 2, len - 1);
    6342             :                     }
    6343             :                 }
    6344             : 
    6345           0 :                 avpriv_new_chapter(s, i, st->time_base, sample->timestamp, end, title);
    6346           0 :                 av_freep(&title);
    6347             :             }
    6348             :         }
    6349           0 : finish:
    6350           0 :         avio_seek(sc->pb, cur_pos, SEEK_SET);
    6351             :     }
    6352           0 : }
    6353             : 
    6354          15 : static int parse_timecode_in_framenum_format(AVFormatContext *s, AVStream *st,
    6355             :                                              uint32_t value, int flags)
    6356             : {
    6357             :     AVTimecode tc;
    6358             :     char buf[AV_TIMECODE_STR_SIZE];
    6359          15 :     AVRational rate = st->avg_frame_rate;
    6360          15 :     int ret = av_timecode_init(&tc, rate, flags, 0, s);
    6361          15 :     if (ret < 0)
    6362           0 :         return ret;
    6363          15 :     av_dict_set(&st->metadata, "timecode",
    6364          15 :                 av_timecode_make_string(&tc, buf, value), 0);
    6365          15 :     return 0;
    6366             : }
    6367             : 
    6368           0 : static int mov_read_rtmd_track(AVFormatContext *s, AVStream *st)
    6369             : {
    6370           0 :     MOVStreamContext *sc = st->priv_data;
    6371             :     char buf[AV_TIMECODE_STR_SIZE];
    6372           0 :     int64_t cur_pos = avio_tell(sc->pb);
    6373             :     int hh, mm, ss, ff, drop;
    6374             : 
    6375           0 :     if (!st->nb_index_entries)
    6376           0 :         return -1;
    6377             : 
    6378           0 :     avio_seek(sc->pb, st->index_entries->pos, SEEK_SET);
    6379           0 :     avio_skip(s->pb, 13);
    6380           0 :     hh = avio_r8(s->pb);
    6381           0 :     mm = avio_r8(s->pb);
    6382           0 :     ss = avio_r8(s->pb);
    6383           0 :     drop = avio_r8(s->pb);
    6384           0 :     ff = avio_r8(s->pb);
    6385           0 :     snprintf(buf, AV_TIMECODE_STR_SIZE, "%02d:%02d:%02d%c%02d",
    6386             :              hh, mm, ss, drop ? ';' : ':', ff);
    6387           0 :     av_dict_set(&st->metadata, "timecode", buf, 0);
    6388             : 
    6389           0 :     avio_seek(sc->pb, cur_pos, SEEK_SET);
    6390           0 :     return 0;
    6391             : }
    6392             : 
    6393          15 : static int mov_read_timecode_track(AVFormatContext *s, AVStream *st)
    6394             : {
    6395          15 :     MOVStreamContext *sc = st->priv_data;
    6396          15 :     int flags = 0;
    6397          15 :     int64_t cur_pos = avio_tell(sc->pb);
    6398             :     uint32_t value;
    6399             : 
    6400          15 :     if (!st->nb_index_entries)
    6401           0 :         return -1;
    6402             : 
    6403          15 :     avio_seek(sc->pb, st->index_entries->pos, SEEK_SET);
    6404          15 :     value = avio_rb32(s->pb);
    6405             : 
    6406          15 :     if (sc->tmcd_flags & 0x0001) flags |= AV_TIMECODE_FLAG_DROPFRAME;
    6407          15 :     if (sc->tmcd_flags & 0x0002) flags |= AV_TIMECODE_FLAG_24HOURSMAX;
    6408          15 :     if (sc->tmcd_flags & 0x0004) flags |= AV_TIMECODE_FLAG_ALLOWNEGATIVE;
    6409             : 
    6410             :     /* Assume Counter flag is set to 1 in tmcd track (even though it is likely
    6411             :      * not the case) and thus assume "frame number format" instead of QT one.
    6412             :      * No sample with tmcd track can be found with a QT timecode at the moment,
    6413             :      * despite what the tmcd track "suggests" (Counter flag set to 0 means QT
    6414             :      * format). */
    6415          15 :     parse_timecode_in_framenum_format(s, st, value, flags);
    6416             : 
    6417          15 :     avio_seek(sc->pb, cur_pos, SEEK_SET);
    6418          15 :     return 0;
    6419             : }
    6420             : 
    6421         354 : static int mov_read_close(AVFormatContext *s)
    6422             : {
    6423         354 :     MOVContext *mov = s->priv_data;
    6424             :     int i, j;
    6425             : 
    6426         778 :     for (i = 0; i < s->nb_streams; i++) {
    6427         424 :         AVStream *st = s->streams[i];
    6428         424 :         MOVStreamContext *sc = st->priv_data;
    6429             : 
    6430         424 :         if (!sc)
    6431           0 :             continue;
    6432             : 
    6433         424 :         av_freep(&sc->ctts_data);
    6434         842 :         for (j = 0; j < sc->drefs_count; j++) {
    6435         418 :             av_freep(&sc->drefs[j].path);
    6436         418 :             av_freep(&sc->drefs[j].dir);
    6437             :         }
    6438         424 :         av_freep(&sc->drefs);
    6439             : 
    6440         424 :         sc->drefs_count = 0;
    6441             : 
    6442         424 :         if (!sc->pb_is_copied)
    6443           6 :             ff_format_io_close(s, &sc->pb);
    6444             : 
    6445         424 :         sc->pb = NULL;
    6446         424 :         av_freep(&sc->chunk_offsets);
    6447         424 :         av_freep(&sc->stsc_data);
    6448         424 :         av_freep(&sc->sample_sizes);
    6449         424 :         av_freep(&sc->keyframes);
    6450         424 :         av_freep(&sc->stts_data);
    6451         424 :         av_freep(&sc->stps_data);
    6452         424 :         av_freep(&sc->elst_data);
    6453         424 :         av_freep(&sc->rap_group);
    6454         424 :         av_freep(&sc->display_matrix);
    6455         424 :         av_freep(&sc->index_ranges);
    6456             : 
    6457         424 :         if (sc->extradata)
    6458         842 :             for (j = 0; j < sc->stsd_count; j++)
    6459         424 :                 av_free(sc->extradata[j]);
    6460         424 :         av_freep(&sc->extradata);
    6461         424 :         av_freep(&sc->extradata_size);
    6462             : 
    6463         424 :         av_freep(&sc->cenc.auxiliary_info);
    6464         424 :         av_freep(&sc->cenc.auxiliary_info_sizes);
    6465         424 :         av_aes_ctr_free(sc->cenc.aes_ctr);
    6466             : 
    6467         424 :         av_freep(&sc->stereo3d);
    6468         424 :         av_freep(&sc->spherical);
    6469         424 :         av_freep(&sc->mastering);
    6470         424 :         av_freep(&sc->coll);
    6471             :     }
    6472             : 
    6473         354 :     if (mov->dv_demux) {
    6474           0 :         avformat_free_context(mov->dv_fctx);
    6475           0 :         mov->dv_fctx = NULL;
    6476             :     }
    6477             : 
    6478         354 :     if (mov->meta_keys) {
    6479          32 :         for (i = 1; i < mov->meta_keys_count; i++) {
    6480          27 :             av_freep(&mov->meta_keys[i]);
    6481             :         }
    6482           5 :         av_freep(&mov->meta_keys);
    6483             :     }
    6484             : 
    6485         354 :     av_freep(&mov->trex_data);
    6486         354 :     av_freep(&mov->bitrates);
    6487             : 
    6488         736 :     for (i = 0; i < mov->frag_index.nb_items; i++) {
    6489         382 :         av_freep(&mov->frag_index.item[i].stream_info);
    6490             :     }
    6491         354 :     av_freep(&mov->frag_index.item);
    6492             : 
    6493         354 :     av_freep(&mov->aes_decrypt);
    6494         354 :     av_freep(&mov->chapter_tracks);
    6495             : 
    6496         354 :     return 0;
    6497             : }
    6498             : 
    6499          12 : static int tmcd_is_referenced(AVFormatContext *s, int tmcd_id)
    6500             : {
    6501             :     int i;
    6502             : 
    6503          22 :     for (i = 0; i < s->nb_streams; i++) {
    6504          20 :         AVStream *st = s->streams[i];
    6505          20 :         MOVStreamContext *sc = st->priv_data;
    6506             : 
    6507          32 :         if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
    6508          12 :             sc->timecode_track == tmcd_id)
    6509          10 :             return 1;
    6510             :     }
    6511           2 :     return 0;
    6512             : }
    6513             : 
    6514             : /* look for a tmcd track not referenced by any video track, and export it globally */
    6515         354 : static void export_orphan_timecode(AVFormatContext *s)
    6516             : {
    6517             :     int i;
    6518             : 
    6519         773 :     for (i = 0; i < s->nb_streams; i++) {
    6520         421 :         AVStream *st = s->streams[i];
    6521             : 
    6522         433 :         if (st->codecpar->codec_tag  == MKTAG('t','m','c','d') &&
    6523          12 :             !tmcd_is_referenced(s, i + 1)) {
    6524           2 :             AVDictionaryEntry *tcr = av_dict_get(st->metadata, "timecode", NULL, 0);
    6525           2 :             if (tcr) {
    6526           2 :                 av_dict_set(&s->metadata, "timecode", tcr->value, 0);
    6527           2 :                 break;
    6528             :             }
    6529             :         }
    6530             :     }
    6531         354 : }
    6532             : 
    6533           0 : static int read_tfra(MOVContext *mov, AVIOContext *f)
    6534             : {
    6535             :     int version, fieldlength, i, j;
    6536           0 :     int64_t pos = avio_tell(f);
    6537           0 :     uint32_t size = avio_rb32(f);
    6538             :     unsigned track_id, item_count;
    6539             : 
    6540           0 :     if (avio_rb32(f) != MKBETAG('t', 'f', 'r', 'a')) {
    6541           0 :         return 1;
    6542             :     }
    6543           0 :     av_log(mov->fc, AV_LOG_VERBOSE, "found tfra\n");
    6544             : 
    6545           0 :     version = avio_r8(f);
    6546           0 :     avio_rb24(f);
    6547           0 :     track_id = avio_rb32(f);
    6548           0 :     fieldlength = avio_rb32(f);
    6549           0 :     item_count = avio_rb32(f);
    6550           0 :     for (i = 0; i < item_count; i++) {
    6551             :         int64_t time, offset;
    6552             :         int index;
    6553             :         MOVFragmentStreamInfo * frag_stream_info;
    6554             : 
    6555           0 :         if (avio_feof(f)) {
    6556           0 :             return AVERROR_INVALIDDATA;
    6557             :         }
    6558             : 
    6559           0 :         if (version == 1) {
    6560           0 :             time   = avio_rb64(f);
    6561           0 :             offset = avio_rb64(f);
    6562             :         } else {
    6563           0 :             time   = avio_rb32(f);
    6564           0 :             offset = avio_rb32(f);
    6565             :         }
    6566             : 
    6567             :         // The first sample of each stream in a fragment is always a random
    6568             :         // access sample.  So it's entry in the tfra can be used as the
    6569             :         // initial PTS of the fragment.
    6570           0 :         index = update_frag_index(mov, offset);
    6571           0 :         frag_stream_info = get_frag_stream_info(&mov->frag_index, index, track_id);
    6572           0 :         if (frag_stream_info &&
    6573           0 :             frag_stream_info->first_tfra_pts == AV_NOPTS_VALUE)
    6574           0 :             frag_stream_info->first_tfra_pts = time;
    6575             : 
    6576           0 :         for (j = 0; j < ((fieldlength >> 4) & 3) + 1; j++)
    6577           0 :             avio_r8(f);
    6578           0 :         for (j = 0; j < ((fieldlength >> 2) & 3) + 1; j++)
    6579           0 :             avio_r8(f);
    6580           0 :         for (j = 0; j < ((fieldlength >> 0) & 3) + 1; j++)
    6581           0 :             avio_r8(f);
    6582             :     }
    6583             : 
    6584           0 :     avio_seek(f, pos + size, SEEK_SET);
    6585           0 :     return 0;
    6586             : }
    6587             : 
    6588           0 : static int mov_read_mfra(MOVContext *c, AVIOContext *f)
    6589             : {
    6590           0 :     int64_t stream_size = avio_size(f);
    6591           0 :     int64_t original_pos = avio_tell(f);
    6592             :     int64_t seek_ret;
    6593             :     int32_t mfra_size;
    6594           0 :     int ret = -1;
    6595           0 :     if ((seek_ret = avio_seek(f, stream_size - 4, SEEK_SET)) < 0) {
    6596           0 :         ret = seek_ret;
    6597           0 :         goto fail;
    6598             :     }
    6599           0 :     mfra_size = avio_rb32(f);
    6600           0 :     if (mfra_size < 0 || mfra_size > stream_size) {
    6601           0 :         av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (unreasonable size)\n");
    6602           0 :         goto fail;
    6603             :     }
    6604           0 :     if ((seek_ret = avio_seek(f, -mfra_size, SEEK_CUR)) < 0) {
    6605           0 :         ret = seek_ret;
    6606           0 :         goto fail;
    6607             :     }
    6608           0 :     if (avio_rb32(f) != mfra_size) {
    6609           0 :         av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (size mismatch)\n");
    6610           0 :         goto fail;
    6611             :     }
    6612           0 :     if (avio_rb32(f) != MKBETAG('m', 'f', 'r', 'a')) {
    6613           0 :         av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (tag mismatch)\n");
    6614           0 :         goto fail;
    6615             :     }
    6616           0 :     av_log(c->fc, AV_LOG_VERBOSE, "stream has mfra\n");
    6617             :     do {
    6618           0 :         ret = read_tfra(c, f);
    6619           0 :         if (ret < 0)
    6620           0 :             goto fail;
    6621           0 :     } while (!ret);
    6622           0 :     ret = 0;
    6623           0 : fail:
    6624           0 :     seek_ret = avio_seek(f, original_pos, SEEK_SET);
    6625           0 :     if (seek_ret < 0) {
    6626           0 :         av_log(c->fc, AV_LOG_ERROR,
    6627             :                "failed to seek back after looking for mfra\n");
    6628           0 :         ret = seek_ret;
    6629             :     }
    6630           0 :     return ret;
    6631             : }
    6632             : 
    6633         354 : static int mov_read_header(AVFormatContext *s)
    6634             : {
    6635         354 :     MOVContext *mov = s->priv_data;
    6636         354 :     AVIOContext *pb = s->pb;
    6637             :     int j, err;
    6638         354 :     MOVAtom atom = { AV_RL32("root") };
    6639             :     int i;
    6640             : 
    6641         354 :     if (mov->decryption_key_len != 0 && mov->decryption_key_len != AES_CTR_KEY_SIZE) {
    6642           0 :         av_log(s, AV_LOG_ERROR, "Invalid decryption key len %d expected %d\n",
    6643             :             mov->decryption_key_len, AES_CTR_KEY_SIZE);
    6644           0 :         return AVERROR(EINVAL);
    6645             :     }
    6646             : 
    6647         354 :     mov->fc = s;
    6648         354 :     mov->trak_index = -1;
    6649             :     /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
    6650         354 :     if (pb->seekable & AVIO_SEEKABLE_NORMAL)
    6651         354 :         atom.size = avio_size(pb);
    6652             :     else
    6653           0 :         atom.size = INT64_MAX;
    6654             : 
    6655             :     /* check MOV header */
    6656             :     do {
    6657         354 :         if (mov->moov_retry)
    6658           0 :             avio_seek(pb, 0, SEEK_SET);
    6659         354 :         if ((err = mov_read_default(mov, pb, atom)) < 0) {
    6660           0 :             av_log(s, AV_LOG_ERROR, "error reading header\n");
    6661           0 :             mov_read_close(s);
    6662           0 :             return err;
    6663             :         }
    6664         354 :     } while ((pb->seekable & AVIO_SEEKABLE_NORMAL) && !mov->found_moov && !mov->moov_retry++);
    6665         354 :     if (!mov->found_moov) {
    6666           0 :         av_log(s, AV_LOG_ERROR, "moov atom not found\n");
    6667           0 :         mov_read_close(s);
    6668           0 :         return AVERROR_INVALIDDATA;
    6669             :     }
    6670         354 :     av_log(mov->fc, AV_LOG_TRACE, "on_parse_exit_offset=%"PRId64"\n", avio_tell(pb));
    6671             : 
    6672         354 :     if (pb->seekable & AVIO_SEEKABLE_NORMAL) {
    6673         354 :         if (mov->nb_chapter_tracks > 0 && !mov->ignore_chapters)
    6674           0 :             mov_read_chapters(s);
    6675         778 :         for (i = 0; i < s->nb_streams; i++)
    6676         424 :             if (s->streams[i]->codecpar->codec_tag == AV_RL32("tmcd")) {
    6677          15 :                 mov_read_timecode_track(s, s->streams[i]);
    6678         409 :             } else if (s->streams[i]->codecpar->codec_tag == AV_RL32("rtmd")) {
    6679           0 :                 mov_read_rtmd_track(s, s->streams[i]);
    6680             :             }
    6681             :     }
    6682             : 
    6683             :     /* copy timecode metadata from tmcd tracks to the related video streams */
    6684         778 :     for (i = 0; i < s->nb_streams; i++) {
    6685         424 :         AVStream *st = s->streams[i];
    6686         424 :         MOVStreamContext *sc = st->priv_data;
    6687         424 :         if (sc->timecode_track > 0) {
    6688             :             AVDictionaryEntry *tcr;
    6689          13 :             int tmcd_st_id = -1;
    6690             : 
    6691          49 :             for (j = 0; j < s->nb_streams; j++)
    6692          36 :                 if (s->streams[j]->id == sc->timecode_track)
    6693          13 :                     tmcd_st_id = j;
    6694             : 
    6695          13 :             if (tmcd_st_id < 0 || tmcd_st_id == i)
    6696           0 :                 continue;
    6697          13 :             tcr = av_dict_get(s->streams[tmcd_st_id]->metadata, "timecode", NULL, 0);
    6698          13 :             if (tcr)
    6699          11 :                 av_dict_set(&st->metadata, "timecode", tcr->value, 0);
    6700             :         }
    6701             :     }
    6702         354 :     export_orphan_timecode(s);
    6703             : 
    6704         778 :     for (i = 0; i < s->nb_streams; i++) {
    6705         424 :         AVStream *st = s->streams[i];
    6706         424 :         MOVStreamContext *sc = st->priv_data;
    6707         424 :         fix_timescale(mov, sc);
    6708         424 :         if(st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && st->codecpar->codec_id == AV_CODEC_ID_AAC) {
    6709         104 :             st->skip_samples = sc->start_pad;
    6710             :         }
    6711         424 :         if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && sc->nb_frames_for_fps > 0 && sc->duration_for_fps > 0)
    6712         406 :             av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
    6713         203 :                       sc->time_scale*(int64_t)sc->nb_frames_for_fps, sc->duration_for_fps, INT_MAX);
    6714         424 :         if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) {
    6715           4 :             if (st->codecpar->width <= 0 || st->codecpar->height <= 0) {
    6716           0 :                 st->codecpar->width  = sc->width;
    6717           0 :                 st->codecpar->height = sc->height;
    6718             :             }
    6719           4 :             if (st->codecpar->codec_id == AV_CODEC_ID_DVD_SUBTITLE) {
    6720           0 :                 if ((err = mov_rewrite_dvd_sub_extradata(st)) < 0)
    6721           0 :                     return err;
    6722             :             }
    6723             :         }
    6724         424 :         if (mov->handbrake_version &&
    6725           0 :             mov->handbrake_version <= 1000000*0 + 1000*10 + 2 &&  // 0.10.2
    6726           0 :             st->codecpar->codec_id == AV_CODEC_ID_MP3
    6727             :         ) {
    6728           0 :             av_log(s, AV_LOG_VERBOSE, "Forcing full parsing for mp3 stream\n");
    6729           0 :             st->need_parsing = AVSTREAM_PARSE_FULL;
    6730             :         }
    6731             :     }
    6732             : 
    6733         354 :     if (mov->trex_data) {
    6734          16 :         for (i = 0; i < s->nb_streams; i++) {
    6735           9 :             AVStream *st = s->streams[i];
    6736           9 :             MOVStreamContext *sc = st->priv_data;
    6737           9 :             if (st->duration > 0) {
    6738           9 :                 if (sc->data_size > INT64_MAX / sc->time_scale / 8) {
    6739           0 :                     av_log(s, AV_LOG_ERROR, "Overflow during bit rate calculation %"PRId64" * 8 * %d\n",
    6740             :                            sc->data_size, sc->time_scale);
    6741           0 :                     mov_read_close(s);
    6742           0 :                     return AVERROR_INVALIDDATA;
    6743             :                 }
    6744           9 :                 st->codecpar->bit_rate = sc->data_size * 8 * sc->time_scale / st->duration;
    6745             :             }
    6746             :         }
    6747             :     }
    6748             : 
    6749         354 :     if (mov->use_mfra_for > 0) {
    6750           0 :         for (i = 0; i < s->nb_streams; i++) {
    6751           0 :             AVStream *st = s->streams[i];
    6752           0 :             MOVStreamContext *sc = st->priv_data;
    6753           0 :             if (sc->duration_for_fps > 0) {
    6754           0 :                 if (sc->data_size > INT64_MAX / sc->time_scale / 8) {
    6755           0 :                     av_log(s, AV_LOG_ERROR, "Overflow during bit rate calculation %"PRId64" * 8 * %d\n",
    6756             :                            sc->data_size, sc->time_scale);
    6757           0 :                     mov_read_close(s);
    6758           0 :                     return AVERROR_INVALIDDATA;
    6759             :                 }
    6760           0 :                 st->codecpar->bit_rate = sc->data_size * 8 * sc->time_scale /
    6761           0 :                     sc->duration_for_fps;
    6762             :             }
    6763             :         }
    6764             :     }
    6765             : 
    6766         354 :     for (i = 0; i < mov->bitrates_count && i < s->nb_streams; i++) {
    6767           0 :         if (mov->bitrates[i]) {
    6768           0 :             s->streams[i]->codecpar->bit_rate = mov->bitrates[i];
    6769             :         }
    6770             :     }
    6771             : 
    6772         354 :     ff_rfps_calculate(s);
    6773             : 
    6774         778 :     for (i = 0; i < s->nb_streams; i++) {
    6775         424 :         AVStream *st = s->streams[i];
    6776         424 :         MOVStreamContext *sc = st->priv_data;
    6777             : 
    6778         424 :         switch (st->codecpar->codec_type) {
    6779         185 :         case AVMEDIA_TYPE_AUDIO:
    6780         185 :             err = ff_replaygain_export(st, s->metadata);
    6781         185 :             if (err < 0) {
    6782           0 :                 mov_read_close(s);
    6783           0 :                 return err;
    6784             :             }
    6785         185 :             break;
    6786         209 :         case AVMEDIA_TYPE_VIDEO:
    6787         209 :             if (sc->display_matrix) {
    6788           3 :                 err = av_stream_add_side_data(st, AV_PKT_DATA_DISPLAYMATRIX, (uint8_t*)sc->display_matrix,
    6789             :                                               sizeof(int32_t) * 9);
    6790           3 :                 if (err < 0)
    6791           0 :                     return err;
    6792             : 
    6793           3 :                 sc->display_matrix = NULL;
    6794             :             }
    6795         209 :             if (sc->stereo3d) {
    6796           1 :                 err = av_stream_add_side_data(st, AV_PKT_DATA_STEREO3D,
    6797           1 :                                               (uint8_t *)sc->stereo3d,
    6798             :                                               sizeof(*sc->stereo3d));
    6799           1 :                 if (err < 0)
    6800           0 :                     return err;
    6801             : 
    6802           1 :                 sc->stereo3d = NULL;
    6803             :             }
    6804         209 :             if (sc->spherical) {
    6805           2 :                 err = av_stream_add_side_data(st, AV_PKT_DATA_SPHERICAL,
    6806           1 :                                               (uint8_t *)sc->spherical,
    6807             :                                               sc->spherical_size);
    6808           1 :                 if (err < 0)
    6809           0 :                     return err;
    6810             : 
    6811           1 :                 sc->spherical = NULL;
    6812             :             }
    6813         209 :             if (sc->mastering) {
    6814           0 :                 err = av_stream_add_side_data(st, AV_PKT_DATA_MASTERING_DISPLAY_METADATA,
    6815           0 :                                               (uint8_t *)sc->mastering,
    6816             :                                               sizeof(*sc->mastering));
    6817           0 :                 if (err < 0)
    6818           0 :                     return err;
    6819             : 
    6820           0 :                 sc->mastering = NULL;
    6821             :             }
    6822         209 :             if (sc->coll) {
    6823           0 :                 err = av_stream_add_side_data(st, AV_PKT_DATA_CONTENT_LIGHT_LEVEL,
    6824           0 :                                               (uint8_t *)sc->coll,
    6825             :                                               sc->coll_size);
    6826           0 :                 if (err < 0)
    6827           0 :                     return err;
    6828             : 
    6829           0 :                 sc->coll = NULL;
    6830             :             }
    6831         209 :             break;
    6832             :         }
    6833             :     }
    6834         354 :     ff_configure_buffers_for_index(s, AV_TIME_BASE);
    6835             : 
    6836         736 :     for (i = 0; i < mov->frag_index.nb_items; i++)
    6837         382 :         if (mov->frag_index.item[i].moof_offset <= mov->fragment.moof_offset)
    6838         380 :             mov->frag_index.item[i].headers_read = 1;
    6839             : 
    6840         354 :     return 0;
    6841             : }
    6842             : 
    6843       87319 : static AVIndexEntry *mov_find_next_sample(AVFormatContext *s, AVStream **st)
    6844             : {
    6845       87319 :     AVIndexEntry *sample = NULL;
    6846       87319 :     int64_t best_dts = INT64_MAX;
    6847             :     int i;
    6848      190967 :     for (i = 0; i < s->nb_streams; i++) {
    6849      103648 :         AVStream *avst = s->streams[i];
    6850      103648 :         MOVStreamContext *msc = avst->priv_data;
    6851      103648 :         if (msc->pb && msc->current_sample < avst->nb_index_entries) {
    6852       97879 :             AVIndexEntry *current_sample = &avst->index_entries[msc->current_sample];
    6853       97879 :             int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale);
    6854       97879 :             av_log(s, AV_LOG_TRACE, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
    6855      108811 :             if (!sample || (!(s->pb->seekable & AVIO_SEEKABLE_NORMAL) && current_sample->pos < sample->pos) ||
    6856       21864 :                 ((s->pb->seekable & AVIO_SEEKABLE_NORMAL) &&
    6857       21864 :                  ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb &&
    6858       27065 :                  ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
    6859        7856 :                   (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
    6860       92060 :                 sample = current_sample;
    6861       92060 :                 best_dts = dts;
    6862       92060 :                 *st = avst;
    6863             :             }
    6864             :         }
    6865             :     }
    6866       87319 :     return sample;
    6867             : }
    6868             : 
    6869           5 : static int should_retry(AVIOContext *pb, int error_code) {
    6870           5 :     if (error_code == AVERROR_EOF || avio_feof(pb))
    6871           5 :         return 0;
    6872             : 
    6873           0 :     return 1;
    6874             : }
    6875             : 
    6876          37 : static int mov_switch_root(AVFormatContext *s, int64_t target, int index)
    6877             : {
    6878             :     int ret;
    6879          37 :     MOVContext *mov = s->priv_data;
    6880             : 
    6881          37 :     if (index >= 0 && index < mov->frag_index.nb_items)
    6882           0 :         target = mov->frag_index.item[index].moof_offset;
    6883          37 :     if (avio_seek(s->pb, target, SEEK_SET) != target) {
    6884           0 :         av_log(mov->fc, AV_LOG_ERROR, "root atom offset 0x%"PRIx64": partial file\n", target);
    6885           0 :         return AVERROR_INVALIDDATA;
    6886             :     }
    6887             : 
    6888          37 :     mov->next_root_atom = 0;
    6889          37 :     if (index < 0 || index >= mov->frag_index.nb_items)
    6890          37 :         index = search_frag_moof_offset(&mov->frag_index, target);
    6891          37 :     if (index < mov->frag_index.nb_items) {
    6892          36 :         if (index + 1 < mov->frag_index.nb_items)
    6893          35 :             mov->next_root_atom = mov->frag_index.item[index + 1].moof_offset;
    6894          36 :         if (mov->frag_index.item[index].headers_read)
    6895          35 :             return 0;
    6896           1 :         mov->frag_index.item[index].headers_read = 1;
    6897             :     }
    6898             : 
    6899           2 :     mov->found_mdat = 0;
    6900             : 
    6901           2 :     ret = mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX });
    6902           2 :     if (ret < 0)
    6903           0 :         return ret;
    6904           2 :     if (avio_feof(s->pb))
    6905           1 :         return AVERROR_EOF;
    6906           1 :     av_log(s, AV_LOG_TRACE, "read fragments, offset 0x%"PRIx64"\n", avio_tell(s->pb));
    6907             : 
    6908           1 :     return 1;
    6909             : }
    6910             : 
    6911           6 : static int mov_change_extradata(MOVStreamContext *sc, AVPacket *pkt)
    6912             : {
    6913             :     uint8_t *side, *extradata;
    6914             :     int extradata_size;
    6915             : 
    6916             :     /* Save the current index. */
    6917           6 :     sc->last_stsd_index = sc->stsc_data[sc->stsc_index].id - 1;
    6918             : 
    6919             :     /* Notify the decoder that extradata changed. */
    6920           6 :     extradata_size = sc->extradata_size[sc->last_stsd_index];
    6921           6 :     extradata = sc->extradata[sc->last_stsd_index];
    6922           6 :     if (extradata_size > 0 && extradata) {
    6923           5 :         side = av_packet_new_side_data(pkt,
    6924             :                                        AV_PKT_DATA_NEW_EXTRADATA,
    6925             :                                        extradata_size);
    6926           5 :         if (!side)
    6927           0 :             return AVERROR(ENOMEM);
    6928           5 :         memcpy(side, extradata, extradata_size);
    6929             :     }
    6930             : 
    6931           6 :     return 0;
    6932             : }
    6933             : 
    6934       82582 : static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
    6935             : {
    6936       82582 :     MOVContext *mov = s->priv_data;
    6937             :     MOVStreamContext *sc;
    6938             :     AVIndexEntry *sample;
    6939       82582 :     AVStream *st = NULL;
    6940             :     int64_t current_index;
    6941             :     int ret;
    6942       82582 :     mov->fc = s;
    6943       87319 :  retry:
    6944       87319 :     sample = mov_find_next_sample(s, &st);
    6945       87319 :     if (!sample || (mov->next_root_atom && sample->pos > mov->next_root_atom)) {
    6946         407 :         if (!mov->next_root_atom)
    6947         370 :             return AVERROR_EOF;
    6948          37 :         if ((ret = mov_switch_root(s, mov->next_root_atom, -1)) < 0)
    6949           1 :             return ret;
    6950          36 :         goto retry;
    6951             :     }
    6952       86912 :     sc = st->priv_data;
    6953             :     /* must be done just before reading, to avoid infinite loop on sample */
    6954       86912 :     current_index = sc->current_index;
    6955       86912 :     mov_current_sample_inc(sc);
    6956             : 
    6957       86912 :     if (mov->next_root_atom) {
    6958         234 :         sample->pos = FFMIN(sample->pos, mov->next_root_atom);
    6959         234 :         sample->size = FFMIN(sample->size, (mov->next_root_atom - sample->pos));
    6960             :     }
    6961             : 
    6962       86912 :     if (st->discard != AVDISCARD_ALL) {
    6963       82211 :         int64_t ret64 = avio_seek(sc->pb, sample->pos, SEEK_SET);
    6964       82211 :         if (ret64 != sample->pos) {
    6965           2 :             av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
    6966             :                    sc->ffindex, sample->pos);
    6967           2 :             if (should_retry(sc->pb, ret64)) {
    6968           0 :                 mov_current_sample_dec(sc);
    6969             :             }
    6970           2 :             return AVERROR_INVALIDDATA;
    6971             :         }
    6972             : 
    6973       82209 :         if( st->discard == AVDISCARD_NONKEY && 0==(sample->flags & AVINDEX_KEYFRAME) ) {
    6974           0 :             av_log(mov->fc, AV_LOG_DEBUG, "Nonkey frame from stream %d discarded due to AVDISCARD_NONKEY\n", sc->ffindex);
    6975           0 :             goto retry;
    6976             :         }
    6977             : 
    6978       82209 :         ret = av_get_packet(sc->pb, pkt, sample->size);
    6979       82209 :         if (ret < 0) {
    6980           3 :             if (should_retry(sc->pb, ret)) {
    6981           0 :                 mov_current_sample_dec(sc);
    6982             :             }
    6983           3 :             return ret;
    6984             :         }
    6985       82206 :         if (sc->has_palette) {
    6986             :             uint8_t *pal;
    6987             : 
    6988          13 :             pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
    6989          13 :             if (!pal) {
    6990           0 :                 av_log(mov->fc, AV_LOG_ERROR, "Cannot append palette to packet\n");
    6991             :             } else {
    6992          13 :                 memcpy(pal, sc->palette, AVPALETTE_SIZE);
    6993          13 :                 sc->has_palette = 0;
    6994             :             }
    6995             :         }
    6996             : #if CONFIG_DV_DEMUXER
    6997       82206 :         if (mov->dv_demux && sc->dv_audio_container) {
    6998           0 :             avpriv_dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size, pkt->pos);
    6999           0 :             av_freep(&pkt->data);
    7000           0 :             pkt->size = 0;
    7001           0 :             ret = avpriv_dv_get_packet(mov->dv_demux, pkt);
    7002           0 :             if (ret < 0)
    7003           0 :                 return ret;
    7004             :         }
    7005             : #endif
    7006       82206 :         if (st->codecpar->codec_id == AV_CODEC_ID_MP3 && !st->need_parsing && pkt->size > 4) {
    7007         288 :             if (ff_mpa_check_header(AV_RB32(pkt->data)) < 0)
    7008           0 :                 st->need_parsing = AVSTREAM_PARSE_FULL;
    7009             :         }
    7010             :     }
    7011             : 
    7012       86907 :     pkt->stream_index = sc->ffindex;
    7013       86907 :     pkt->dts = sample->timestamp;
    7014       86907 :     if (sample->flags & AVINDEX_DISCARD_FRAME) {
    7015         171 :         pkt->flags |= AV_PKT_FLAG_DISCARD;
    7016             :     }
    7017       86907 :     if (sc->ctts_data && sc->ctts_index < sc->ctts_count) {
    7018        2280 :         pkt->pts = pkt->dts + sc->dts_shift + sc->ctts_data[sc->ctts_index].duration;
    7019             :         /* update ctts context */
    7020        2280 :         sc->ctts_sample++;
    7021        6840 :         if (sc->ctts_index < sc->ctts_count &&
    7022        2280 :             sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
    7023        2280 :             sc->ctts_index++;
    7024        2280 :             sc->ctts_sample = 0;
    7025             :         }
    7026             :     } else {
    7027      169254 :         int64_t next_dts = (sc->current_sample < st->nb_index_entries) ?
    7028       84627 :             st->index_entries[sc->current_sample].timestamp : st->duration;
    7029       84627 :         pkt->duration = next_dts - pkt->dts;
    7030       84627 :         pkt->pts = pkt->dts;
    7031             :     }
    7032       86907 :     if (st->discard == AVDISCARD_ALL)
    7033        4701 :         goto retry;
    7034       82206 :     pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? AV_PKT_FLAG_KEY : 0;
    7035       82206 :     pkt->pos = sample->pos;
    7036             : 
    7037             :     /* Multiple stsd handling. */
    7038       82206 :     if (sc->stsc_data) {
    7039             :         /* Keep track of the stsc index for the given sample, then check
    7040             :         * if the stsd index is different from the last used one. */
    7041       81750 :         sc->stsc_sample++;
    7042      124654 :         if (mov_stsc_index_valid(sc->stsc_index, sc->stsc_count) &&
    7043       42904 :             mov_get_stsc_samples(sc, sc->stsc_index) == sc->stsc_sample) {
    7044         658 :             sc->stsc_index++;
    7045         658 :             sc->stsc_sample = 0;
    7046             :         /* Do not check indexes after a switch. */
    7047      162184 :         } else if (sc->stsc_data[sc->stsc_index].id > 0 &&
    7048      243276 :                    sc->stsc_data[sc->stsc_index].id - 1 < sc->stsd_count &&
    7049       81092 :                    sc->stsc_data[sc->stsc_index].id - 1 != sc->last_stsd_index) {
    7050           6 :             ret = mov_change_extradata(sc, pkt);
    7051           6 :             if (ret < 0)
    7052           0 :                 return ret;
    7053             :         }
    7054             :     }
    7055             : 
    7056       82206 :     if (mov->aax_mode)
    7057           0 :         aax_filter(pkt->data, pkt->size, mov);
    7058             : 
    7059       82206 :     if (sc->cenc.aes_ctr) {
    7060          74 :         ret = cenc_filter(mov, sc, current_index, pkt->data, pkt->size);
    7061          74 :         if (ret) {
    7062           0 :             return ret;
    7063             :         }
    7064             :     }
    7065             : 
    7066       82206 :     return 0;
    7067             : }
    7068             : 
    7069         281 : static int mov_seek_fragment(AVFormatContext *s, AVStream *st, int64_t timestamp)
    7070             : {
    7071         281 :     MOVContext *mov = s->priv_data;
    7072             :     int index;
    7073             : 
    7074         281 :     if (!mov->frag_index.complete)
    7075         255 :         return 0;
    7076             : 
    7077          26 :     index = search_frag_timestamp(&mov->frag_index, st, timestamp);
    7078          26 :     if (index < 0)
    7079           4 :         index = 0;
    7080          26 :     if (!mov->frag_index.item[index].headers_read)
    7081           0 :         return mov_switch_root(s, -1, index);
    7082          26 :     if (index + 1 < mov->frag_index.nb_items)
    7083          26 :         mov->next_root_atom = mov->frag_index.item[index + 1].moof_offset;
    7084             : 
    7085          26 :     return 0;
    7086             : }
    7087             : 
    7088         281 : static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp, int flags)
    7089             : {
    7090         281 :     MOVStreamContext *sc = st->priv_data;
    7091             :     int sample, time_sample, ret;
    7092             :     unsigned int i;
    7093             : 
    7094         281 :     timestamp -= sc->time_offset;
    7095             : 
    7096         281 :     ret = mov_seek_fragment(s, st, timestamp);
    7097         281 :     if (ret < 0)
    7098           0 :         return ret;
    7099             : 
    7100         281 :     sample = av_index_search_timestamp(st, timestamp, flags);
    7101         281 :     av_log(s, AV_LOG_TRACE, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
    7102         281 :     if (sample < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
    7103          38 :         sample = 0;
    7104         281 :     if (sample < 0) /* not sure what to do */
    7105          20 :         return AVERROR_INVALIDDATA;
    7106         261 :     mov_current_sample_set(sc, sample);
    7107         261 :     av_log(s, AV_LOG_TRACE, "stream %d, found sample %d\n", st->index, sc->current_sample);
    7108             :     /* adjust ctts index */
    7109         261 :     if (sc->ctts_data) {
    7110          26 :         time_sample = 0;
    7111       57706 :         for (i = 0; i < sc->ctts_count; i++) {
    7112       57706 :             int next = time_sample + sc->ctts_data[i].count;
    7113       57706 :             if (next > sc->current_sample) {
    7114          26 :                 sc->ctts_index = i;
    7115          26 :                 sc->ctts_sample = sc->current_sample - time_sample;
    7116          26 :                 break;
    7117             :             }
    7118       57680 :             time_sample = next;
    7119             :         }
    7120             :     }
    7121             : 
    7122             :     /* adjust stsd index */
    7123         261 :     time_sample = 0;
    7124         261 :     for (i = 0; i < sc->stsc_count; i++) {
    7125         235 :         int next = time_sample + mov_get_stsc_samples(sc, i);
    7126         235 :         if (next > sc->current_sample) {
    7127         235 :             sc->stsc_index = i;
    7128         235 :             sc->stsc_sample = sc->current_sample - time_sample;
    7129         235 :             break;
    7130             :         }
    7131           0 :         time_sample = next;
    7132             :     }
    7133             : 
    7134         261 :     return sample;
    7135             : }
    7136             : 
    7137         260 : static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
    7138             : {
    7139         260 :     MOVContext *mc = s->priv_data;
    7140             :     AVStream *st;
    7141             :     int sample;
    7142             :     int i;
    7143             : 
    7144         260 :     if (stream_index >= s->nb_streams)
    7145           0 :         return AVERROR_INVALIDDATA;
    7146             : 
    7147         260 :     st = s->streams[stream_index];
    7148         260 :     sample = mov_seek_stream(s, st, sample_time, flags);
    7149         260 :     if (sample < 0)
    7150          20 :         return sample;
    7151             : 
    7152         240 :     if (mc->seek_individually) {
    7153             :         /* adjust seek timestamp to found sample timestamp */
    7154         240 :         int64_t seek_timestamp = st->index_entries[sample].timestamp;
    7155             : 
    7156         501 :         for (i = 0; i < s->nb_streams; i++) {
    7157             :             int64_t timestamp;
    7158         261 :             MOVStreamContext *sc = s->streams[i]->priv_data;
    7159         261 :             st = s->streams[i];
    7160         261 :             st->skip_samples = (sample_time <= 0) ? sc->start_pad : 0;
    7161             : 
    7162         261 :             if (stream_index == i)
    7163         240 :                 continue;
    7164             : 
    7165          21 :             timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
    7166          21 :             mov_seek_stream(s, st, timestamp, flags);
    7167             :         }
    7168             :     } else {
    7169           0 :         for (i = 0; i < s->nb_streams; i++) {
    7170             :             MOVStreamContext *sc;
    7171           0 :             st = s->streams[i];
    7172           0 :             sc = st->priv_data;
    7173           0 :             mov_current_sample_set(sc, 0);
    7174             :         }
    7175           0 :         while (1) {
    7176             :             MOVStreamContext *sc;
    7177           0 :             AVIndexEntry *entry = mov_find_next_sample(s, &st);
    7178           0 :             if (!entry)
    7179           0 :                 return AVERROR_INVALIDDATA;
    7180           0 :             sc = st->priv_data;
    7181           0 :             if (sc->ffindex == stream_index && sc->current_sample == sample)
    7182           0 :                 break;
    7183           0 :             mov_current_sample_inc(sc);
    7184             :         }
    7185             :     }
    7186         240 :     return 0;
    7187             : }
    7188             : 
    7189             : #define OFFSET(x) offsetof(MOVContext, x)
    7190             : #define FLAGS AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
    7191             : static const AVOption mov_options[] = {
    7192             :     {"use_absolute_path",
    7193             :         "allow using absolute path when opening alias, this is a possible security issue",
    7194             :         OFFSET(use_absolute_path), AV_OPT_TYPE_BOOL, {.i64 = 0},
    7195             :         0, 1, FLAGS},
    7196             :     {"seek_streams_individually",
    7197             :         "Seek each stream individually to the to the closest point",
    7198             :         OFFSET(seek_individually), AV_OPT_TYPE_BOOL, { .i64 = 1 },
    7199             :         0, 1, FLAGS},
    7200             :     {"ignore_editlist", "Ignore the edit list atom.", OFFSET(ignore_editlist), AV_OPT_TYPE_BOOL, {.i64 = 0},
    7201             :         0, 1, FLAGS},
    7202             :     {"advanced_editlist",
    7203             :         "Modify the AVIndex according to the editlists. Use this option to decode in the order specified by the edits.",
    7204             :         OFFSET(advanced_editlist), AV_OPT_TYPE_BOOL, {.i64 = 1},
    7205             :         0, 1, FLAGS},
    7206             :     {"ignore_chapters", "", OFFSET(ignore_chapters), AV_OPT_TYPE_BOOL, {.i64 = 0},
    7207             :         0, 1, FLAGS},
    7208             :     {"use_mfra_for",
    7209             :         "use mfra for fragment timestamps",
    7210             :         OFFSET(use_mfra_for), AV_OPT_TYPE_INT, {.i64 = FF_MOV_FLAG_MFRA_AUTO},
    7211             :         -1, FF_MOV_FLAG_MFRA_PTS, FLAGS,
    7212             :         "use_mfra_for"},
    7213             :     {"auto", "auto", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_AUTO}, 0, 0,
    7214             :         FLAGS, "use_mfra_for" },
    7215             :     {"dts", "dts", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_DTS}, 0, 0,
    7216             :         FLAGS, "use_mfra_for" },
    7217             :     {"pts", "pts", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_PTS}, 0, 0,
    7218             :         FLAGS, "use_mfra_for" },
    7219             :     { "export_all", "Export unrecognized metadata entries", OFFSET(export_all),
    7220             :         AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, .flags = FLAGS },
    7221             :     { "export_xmp", "Export full XMP metadata", OFFSET(export_xmp),
    7222             :         AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, .flags = FLAGS },
    7223             :     { "activation_bytes", "Secret bytes for Audible AAX files", OFFSET(activation_bytes),
    7224             :         AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_DECODING_PARAM },
    7225             :     { "audible_fixed_key", // extracted from libAAX_SDK.so and AAXSDKWin.dll files!
    7226             :         "Fixed key used for handling Audible AAX files", OFFSET(audible_fixed_key),
    7227             :         AV_OPT_TYPE_BINARY, {.str="77214d4b196a87cd520045fd20a51d67"},
    7228             :         .flags = AV_OPT_FLAG_DECODING_PARAM },
    7229             :     { "decryption_key", "The media decryption key (hex)", OFFSET(decryption_key), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_DECODING_PARAM },
    7230             :     { "enable_drefs", "Enable external track support.", OFFSET(enable_drefs), AV_OPT_TYPE_BOOL,
    7231             :         {.i64 = 0}, 0, 1, FLAGS },
    7232             : 
    7233             :     { NULL },
    7234             : };
    7235             : 
    7236             : static const AVClass mov_class = {
    7237             :     .class_name = "mov,mp4,m4a,3gp,3g2,mj2",
    7238             :     .item_name  = av_default_item_name,
    7239             :     .option     = mov_options,
    7240             :     .version    = LIBAVUTIL_VERSION_INT,
    7241             : };
    7242             : 
    7243             : AVInputFormat ff_mov_demuxer = {
    7244             :     .name           = "mov,mp4,m4a,3gp,3g2,mj2",
    7245             :     .long_name      = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
    7246             :     .priv_class     = &mov_class,
    7247             :     .priv_data_size = sizeof(MOVContext),
    7248             :     .extensions     = "mov,mp4,m4a,3gp,3g2,mj2",
    7249             :     .read_probe     = mov_probe,
    7250             :     .read_header    = mov_read_header,
    7251             :     .read_packet    = mov_read_packet,
    7252             :     .read_close     = mov_read_close,
    7253             :     .read_seek      = mov_read_seek,
    7254             :     .flags          = AVFMT_NO_BYTE_SEEK,
    7255             : };

Generated by: LCOV version 1.13