LCOV - code coverage report
Current view: top level - libavformat - matroskadec.c (source / functions) Hit Total Coverage
Test: coverage.info Lines: 1153 2007 57.4 %
Date: 2018-05-20 11:54:08 Functions: 50 60 83.3 %

          Line data    Source code
       1             : /*
       2             :  * Matroska file demuxer
       3             :  * Copyright (c) 2003-2008 The FFmpeg Project
       4             :  *
       5             :  * This file is part of FFmpeg.
       6             :  *
       7             :  * FFmpeg is free software; you can redistribute it and/or
       8             :  * modify it under the terms of the GNU Lesser General Public
       9             :  * License as published by the Free Software Foundation; either
      10             :  * version 2.1 of the License, or (at your option) any later version.
      11             :  *
      12             :  * FFmpeg is distributed in the hope that it will be useful,
      13             :  * but WITHOUT ANY WARRANTY; without even the implied warranty of
      14             :  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
      15             :  * Lesser General Public License for more details.
      16             :  *
      17             :  * You should have received a copy of the GNU Lesser General Public
      18             :  * License along with FFmpeg; if not, write to the Free Software
      19             :  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
      20             :  */
      21             : 
      22             : /**
      23             :  * @file
      24             :  * Matroska file demuxer
      25             :  * @author Ronald Bultje <rbultje@ronald.bitfreak.net>
      26             :  * @author with a little help from Moritz Bunkus <moritz@bunkus.org>
      27             :  * @author totally reworked by Aurelien Jacobs <aurel@gnuage.org>
      28             :  * @see specs available on the Matroska project page: http://www.matroska.org/
      29             :  */
      30             : 
      31             : #include "config.h"
      32             : 
      33             : #include <inttypes.h>
      34             : #include <stdio.h>
      35             : 
      36             : #include "libavutil/avstring.h"
      37             : #include "libavutil/base64.h"
      38             : #include "libavutil/dict.h"
      39             : #include "libavutil/intfloat.h"
      40             : #include "libavutil/intreadwrite.h"
      41             : #include "libavutil/lzo.h"
      42             : #include "libavutil/mastering_display_metadata.h"
      43             : #include "libavutil/mathematics.h"
      44             : #include "libavutil/opt.h"
      45             : #include "libavutil/time_internal.h"
      46             : #include "libavutil/spherical.h"
      47             : 
      48             : #include "libavcodec/bytestream.h"
      49             : #include "libavcodec/flac.h"
      50             : #include "libavcodec/mpeg4audio.h"
      51             : 
      52             : #include "avformat.h"
      53             : #include "avio_internal.h"
      54             : #include "internal.h"
      55             : #include "isom.h"
      56             : #include "matroska.h"
      57             : #include "oggdec.h"
      58             : /* For ff_codec_get_id(). */
      59             : #include "riff.h"
      60             : #include "rmsipr.h"
      61             : 
      62             : #if CONFIG_BZLIB
      63             : #include <bzlib.h>
      64             : #endif
      65             : #if CONFIG_ZLIB
      66             : #include <zlib.h>
      67             : #endif
      68             : 
      69             : #include "qtpalette.h"
      70             : 
      71             : typedef enum {
      72             :     EBML_NONE,
      73             :     EBML_UINT,
      74             :     EBML_FLOAT,
      75             :     EBML_STR,
      76             :     EBML_UTF8,
      77             :     EBML_BIN,
      78             :     EBML_NEST,
      79             :     EBML_LEVEL1,
      80             :     EBML_PASS,
      81             :     EBML_STOP,
      82             :     EBML_SINT,
      83             :     EBML_TYPE_COUNT
      84             : } EbmlType;
      85             : 
      86             : typedef const struct EbmlSyntax {
      87             :     uint32_t id;
      88             :     EbmlType type;
      89             :     int list_elem_size;
      90             :     int data_offset;
      91             :     union {
      92             :         int64_t     i;
      93             :         uint64_t    u;
      94             :         double      f;
      95             :         const char *s;
      96             :         const struct EbmlSyntax *n;
      97             :     } def;
      98             : } EbmlSyntax;
      99             : 
     100             : typedef struct EbmlList {
     101             :     int nb_elem;
     102             :     void *elem;
     103             : } EbmlList;
     104             : 
     105             : typedef struct EbmlBin {
     106             :     int      size;
     107             :     AVBufferRef *buf;
     108             :     uint8_t *data;
     109             :     int64_t  pos;
     110             : } EbmlBin;
     111             : 
     112             : typedef struct Ebml {
     113             :     uint64_t version;
     114             :     uint64_t max_size;
     115             :     uint64_t id_length;
     116             :     char    *doctype;
     117             :     uint64_t doctype_version;
     118             : } Ebml;
     119             : 
     120             : typedef struct MatroskaTrackCompression {
     121             :     uint64_t algo;
     122             :     EbmlBin  settings;
     123             : } MatroskaTrackCompression;
     124             : 
     125             : typedef struct MatroskaTrackEncryption {
     126             :     uint64_t algo;
     127             :     EbmlBin  key_id;
     128             : } MatroskaTrackEncryption;
     129             : 
     130             : typedef struct MatroskaTrackEncoding {
     131             :     uint64_t scope;
     132             :     uint64_t type;
     133             :     MatroskaTrackCompression compression;
     134             :     MatroskaTrackEncryption encryption;
     135             : } MatroskaTrackEncoding;
     136             : 
     137             : typedef struct MatroskaMasteringMeta {
     138             :     double r_x;
     139             :     double r_y;
     140             :     double g_x;
     141             :     double g_y;
     142             :     double b_x;
     143             :     double b_y;
     144             :     double white_x;
     145             :     double white_y;
     146             :     double max_luminance;
     147             :     double min_luminance;
     148             : } MatroskaMasteringMeta;
     149             : 
     150             : typedef struct MatroskaTrackVideoColor {
     151             :     uint64_t matrix_coefficients;
     152             :     uint64_t bits_per_channel;
     153             :     uint64_t chroma_sub_horz;
     154             :     uint64_t chroma_sub_vert;
     155             :     uint64_t cb_sub_horz;
     156             :     uint64_t cb_sub_vert;
     157             :     uint64_t chroma_siting_horz;
     158             :     uint64_t chroma_siting_vert;
     159             :     uint64_t range;
     160             :     uint64_t transfer_characteristics;
     161             :     uint64_t primaries;
     162             :     uint64_t max_cll;
     163             :     uint64_t max_fall;
     164             :     MatroskaMasteringMeta mastering_meta;
     165             : } MatroskaTrackVideoColor;
     166             : 
     167             : typedef struct MatroskaTrackVideoProjection {
     168             :     uint64_t type;
     169             :     EbmlBin private;
     170             :     double yaw;
     171             :     double pitch;
     172             :     double roll;
     173             : } MatroskaTrackVideoProjection;
     174             : 
     175             : typedef struct MatroskaTrackVideo {
     176             :     double   frame_rate;
     177             :     uint64_t display_width;
     178             :     uint64_t display_height;
     179             :     uint64_t pixel_width;
     180             :     uint64_t pixel_height;
     181             :     EbmlBin color_space;
     182             :     uint64_t display_unit;
     183             :     uint64_t interlaced;
     184             :     uint64_t field_order;
     185             :     uint64_t stereo_mode;
     186             :     uint64_t alpha_mode;
     187             :     EbmlList color;
     188             :     MatroskaTrackVideoProjection projection;
     189             : } MatroskaTrackVideo;
     190             : 
     191             : typedef struct MatroskaTrackAudio {
     192             :     double   samplerate;
     193             :     double   out_samplerate;
     194             :     uint64_t bitdepth;
     195             :     uint64_t channels;
     196             : 
     197             :     /* real audio header (extracted from extradata) */
     198             :     int      coded_framesize;
     199             :     int      sub_packet_h;
     200             :     int      frame_size;
     201             :     int      sub_packet_size;
     202             :     int      sub_packet_cnt;
     203             :     int      pkt_cnt;
     204             :     uint64_t buf_timecode;
     205             :     uint8_t *buf;
     206             : } MatroskaTrackAudio;
     207             : 
     208             : typedef struct MatroskaTrackPlane {
     209             :     uint64_t uid;
     210             :     uint64_t type;
     211             : } MatroskaTrackPlane;
     212             : 
     213             : typedef struct MatroskaTrackOperation {
     214             :     EbmlList combine_planes;
     215             : } MatroskaTrackOperation;
     216             : 
     217             : typedef struct MatroskaTrack {
     218             :     uint64_t num;
     219             :     uint64_t uid;
     220             :     uint64_t type;
     221             :     char    *name;
     222             :     char    *codec_id;
     223             :     EbmlBin  codec_priv;
     224             :     char    *language;
     225             :     double time_scale;
     226             :     uint64_t default_duration;
     227             :     uint64_t flag_default;
     228             :     uint64_t flag_forced;
     229             :     uint64_t seek_preroll;
     230             :     MatroskaTrackVideo video;
     231             :     MatroskaTrackAudio audio;
     232             :     MatroskaTrackOperation operation;
     233             :     EbmlList encodings;
     234             :     uint64_t codec_delay;
     235             :     uint64_t codec_delay_in_track_tb;
     236             : 
     237             :     AVStream *stream;
     238             :     int64_t end_timecode;
     239             :     int ms_compat;
     240             :     uint64_t max_block_additional_id;
     241             : 
     242             :     uint32_t palette[AVPALETTE_COUNT];
     243             :     int has_palette;
     244             : } MatroskaTrack;
     245             : 
     246             : typedef struct MatroskaAttachment {
     247             :     uint64_t uid;
     248             :     char *filename;
     249             :     char *mime;
     250             :     EbmlBin bin;
     251             : 
     252             :     AVStream *stream;
     253             : } MatroskaAttachment;
     254             : 
     255             : typedef struct MatroskaChapter {
     256             :     uint64_t start;
     257             :     uint64_t end;
     258             :     uint64_t uid;
     259             :     char    *title;
     260             : 
     261             :     AVChapter *chapter;
     262             : } MatroskaChapter;
     263             : 
     264             : typedef struct MatroskaIndexPos {
     265             :     uint64_t track;
     266             :     uint64_t pos;
     267             : } MatroskaIndexPos;
     268             : 
     269             : typedef struct MatroskaIndex {
     270             :     uint64_t time;
     271             :     EbmlList pos;
     272             : } MatroskaIndex;
     273             : 
     274             : typedef struct MatroskaTag {
     275             :     char *name;
     276             :     char *string;
     277             :     char *lang;
     278             :     uint64_t def;
     279             :     EbmlList sub;
     280             : } MatroskaTag;
     281             : 
     282             : typedef struct MatroskaTagTarget {
     283             :     char    *type;
     284             :     uint64_t typevalue;
     285             :     uint64_t trackuid;
     286             :     uint64_t chapteruid;
     287             :     uint64_t attachuid;
     288             : } MatroskaTagTarget;
     289             : 
     290             : typedef struct MatroskaTags {
     291             :     MatroskaTagTarget target;
     292             :     EbmlList tag;
     293             : } MatroskaTags;
     294             : 
     295             : typedef struct MatroskaSeekhead {
     296             :     uint64_t id;
     297             :     uint64_t pos;
     298             : } MatroskaSeekhead;
     299             : 
     300             : typedef struct MatroskaLevel {
     301             :     uint64_t start;
     302             :     uint64_t length;
     303             : } MatroskaLevel;
     304             : 
     305             : typedef struct MatroskaCluster {
     306             :     uint64_t timecode;
     307             :     EbmlList blocks;
     308             : } MatroskaCluster;
     309             : 
     310             : typedef struct MatroskaLevel1Element {
     311             :     uint64_t id;
     312             :     uint64_t pos;
     313             :     int parsed;
     314             : } MatroskaLevel1Element;
     315             : 
     316             : typedef struct MatroskaDemuxContext {
     317             :     const AVClass *class;
     318             :     AVFormatContext *ctx;
     319             : 
     320             :     /* EBML stuff */
     321             :     int num_levels;
     322             :     MatroskaLevel levels[EBML_MAX_DEPTH];
     323             :     int level_up;
     324             :     uint32_t current_id;
     325             : 
     326             :     uint64_t time_scale;
     327             :     double   duration;
     328             :     char    *title;
     329             :     char    *muxingapp;
     330             :     EbmlBin date_utc;
     331             :     EbmlList tracks;
     332             :     EbmlList attachments;
     333             :     EbmlList chapters;
     334             :     EbmlList index;
     335             :     EbmlList tags;
     336             :     EbmlList seekhead;
     337             : 
     338             :     /* byte position of the segment inside the stream */
     339             :     int64_t segment_start;
     340             : 
     341             :     /* the packet queue */
     342             :     AVPacketList *queue;
     343             :     AVPacketList *queue_end;
     344             : 
     345             :     int done;
     346             : 
     347             :     /* What to skip before effectively reading a packet. */
     348             :     int skip_to_keyframe;
     349             :     uint64_t skip_to_timecode;
     350             : 
     351             :     /* File has a CUES element, but we defer parsing until it is needed. */
     352             :     int cues_parsing_deferred;
     353             : 
     354             :     /* Level1 elements and whether they were read yet */
     355             :     MatroskaLevel1Element level1_elems[64];
     356             :     int num_level1_elems;
     357             : 
     358             :     int current_cluster_num_blocks;
     359             :     int64_t current_cluster_pos;
     360             :     MatroskaCluster current_cluster;
     361             : 
     362             :     /* File has SSA subtitles which prevent incremental cluster parsing. */
     363             :     int contains_ssa;
     364             : 
     365             :     /* WebM DASH Manifest live flag */
     366             :     int is_live;
     367             : 
     368             :     /* Bandwidth value for WebM DASH Manifest */
     369             :     int bandwidth;
     370             : } MatroskaDemuxContext;
     371             : 
     372             : typedef struct MatroskaBlock {
     373             :     uint64_t duration;
     374             :     int64_t  reference;
     375             :     uint64_t non_simple;
     376             :     EbmlBin  bin;
     377             :     uint64_t additional_id;
     378             :     EbmlBin  additional;
     379             :     int64_t discard_padding;
     380             : } MatroskaBlock;
     381             : 
     382             : static const EbmlSyntax ebml_header[] = {
     383             :     { EBML_ID_EBMLREADVERSION,    EBML_UINT, 0, offsetof(Ebml, version),         { .u = EBML_VERSION } },
     384             :     { EBML_ID_EBMLMAXSIZELENGTH,  EBML_UINT, 0, offsetof(Ebml, max_size),        { .u = 8 } },
     385             :     { EBML_ID_EBMLMAXIDLENGTH,    EBML_UINT, 0, offsetof(Ebml, id_length),       { .u = 4 } },
     386             :     { EBML_ID_DOCTYPE,            EBML_STR,  0, offsetof(Ebml, doctype),         { .s = "(none)" } },
     387             :     { EBML_ID_DOCTYPEREADVERSION, EBML_UINT, 0, offsetof(Ebml, doctype_version), { .u = 1 } },
     388             :     { EBML_ID_EBMLVERSION,        EBML_NONE },
     389             :     { EBML_ID_DOCTYPEVERSION,     EBML_NONE },
     390             :     { 0 }
     391             : };
     392             : 
     393             : static const EbmlSyntax ebml_syntax[] = {
     394             :     { EBML_ID_HEADER, EBML_NEST, 0, 0, { .n = ebml_header } },
     395             :     { 0 }
     396             : };
     397             : 
     398             : static const EbmlSyntax matroska_info[] = {
     399             :     { MATROSKA_ID_TIMECODESCALE, EBML_UINT,  0, offsetof(MatroskaDemuxContext, time_scale), { .u = 1000000 } },
     400             :     { MATROSKA_ID_DURATION,      EBML_FLOAT, 0, offsetof(MatroskaDemuxContext, duration) },
     401             :     { MATROSKA_ID_TITLE,         EBML_UTF8,  0, offsetof(MatroskaDemuxContext, title) },
     402             :     { MATROSKA_ID_WRITINGAPP,    EBML_NONE },
     403             :     { MATROSKA_ID_MUXINGAPP,     EBML_UTF8, 0, offsetof(MatroskaDemuxContext, muxingapp) },
     404             :     { MATROSKA_ID_DATEUTC,       EBML_BIN,  0, offsetof(MatroskaDemuxContext, date_utc) },
     405             :     { MATROSKA_ID_SEGMENTUID,    EBML_NONE },
     406             :     { 0 }
     407             : };
     408             : 
     409             : static const EbmlSyntax matroska_mastering_meta[] = {
     410             :     { MATROSKA_ID_VIDEOCOLOR_RX, EBML_FLOAT, 0, offsetof(MatroskaMasteringMeta, r_x), { .f=-1 } },
     411             :     { MATROSKA_ID_VIDEOCOLOR_RY, EBML_FLOAT, 0, offsetof(MatroskaMasteringMeta, r_y), { .f=-1 } },
     412             :     { MATROSKA_ID_VIDEOCOLOR_GX, EBML_FLOAT, 0, offsetof(MatroskaMasteringMeta, g_x), { .f=-1 } },
     413             :     { MATROSKA_ID_VIDEOCOLOR_GY, EBML_FLOAT, 0, offsetof(MatroskaMasteringMeta, g_y), { .f=-1 } },
     414             :     { MATROSKA_ID_VIDEOCOLOR_BX, EBML_FLOAT, 0, offsetof(MatroskaMasteringMeta, b_x), { .f=-1 } },
     415             :     { MATROSKA_ID_VIDEOCOLOR_BY, EBML_FLOAT, 0, offsetof(MatroskaMasteringMeta, b_y), { .f=-1 } },
     416             :     { MATROSKA_ID_VIDEOCOLOR_WHITEX, EBML_FLOAT, 0, offsetof(MatroskaMasteringMeta, white_x), { .f=-1 } },
     417             :     { MATROSKA_ID_VIDEOCOLOR_WHITEY, EBML_FLOAT, 0, offsetof(MatroskaMasteringMeta, white_y), { .f=-1 } },
     418             :     { MATROSKA_ID_VIDEOCOLOR_LUMINANCEMIN, EBML_FLOAT, 0, offsetof(MatroskaMasteringMeta, min_luminance), { .f=-1 } },
     419             :     { MATROSKA_ID_VIDEOCOLOR_LUMINANCEMAX, EBML_FLOAT, 0, offsetof(MatroskaMasteringMeta, max_luminance), { .f=-1 } },
     420             :     { 0 }
     421             : };
     422             : 
     423             : static const EbmlSyntax matroska_track_video_color[] = {
     424             :     { MATROSKA_ID_VIDEOCOLORMATRIXCOEFF,      EBML_UINT, 0, offsetof(MatroskaTrackVideoColor, matrix_coefficients), { .u = AVCOL_SPC_UNSPECIFIED } },
     425             :     { MATROSKA_ID_VIDEOCOLORBITSPERCHANNEL,   EBML_UINT, 0, offsetof(MatroskaTrackVideoColor, bits_per_channel), { .u=0 } },
     426             :     { MATROSKA_ID_VIDEOCOLORCHROMASUBHORZ,    EBML_UINT, 0, offsetof(MatroskaTrackVideoColor, chroma_sub_horz), { .u=0 } },
     427             :     { MATROSKA_ID_VIDEOCOLORCHROMASUBVERT,    EBML_UINT, 0, offsetof(MatroskaTrackVideoColor, chroma_sub_vert), { .u=0 } },
     428             :     { MATROSKA_ID_VIDEOCOLORCBSUBHORZ,        EBML_UINT, 0, offsetof(MatroskaTrackVideoColor, cb_sub_horz), { .u=0 } },
     429             :     { MATROSKA_ID_VIDEOCOLORCBSUBVERT,        EBML_UINT, 0, offsetof(MatroskaTrackVideoColor, cb_sub_vert), { .u=0 } },
     430             :     { MATROSKA_ID_VIDEOCOLORCHROMASITINGHORZ, EBML_UINT, 0, offsetof(MatroskaTrackVideoColor, chroma_siting_horz), { .u = MATROSKA_COLOUR_CHROMASITINGHORZ_UNDETERMINED } },
     431             :     { MATROSKA_ID_VIDEOCOLORCHROMASITINGVERT, EBML_UINT, 0, offsetof(MatroskaTrackVideoColor, chroma_siting_vert), { .u = MATROSKA_COLOUR_CHROMASITINGVERT_UNDETERMINED } },
     432             :     { MATROSKA_ID_VIDEOCOLORRANGE,            EBML_UINT, 0, offsetof(MatroskaTrackVideoColor, range), { .u = AVCOL_RANGE_UNSPECIFIED } },
     433             :     { MATROSKA_ID_VIDEOCOLORTRANSFERCHARACTERISTICS, EBML_UINT, 0, offsetof(MatroskaTrackVideoColor, transfer_characteristics), { .u = AVCOL_TRC_UNSPECIFIED } },
     434             :     { MATROSKA_ID_VIDEOCOLORPRIMARIES,        EBML_UINT, 0, offsetof(MatroskaTrackVideoColor, primaries), { .u = AVCOL_PRI_UNSPECIFIED } },
     435             :     { MATROSKA_ID_VIDEOCOLORMAXCLL,           EBML_UINT, 0, offsetof(MatroskaTrackVideoColor, max_cll), { .u=0 } },
     436             :     { MATROSKA_ID_VIDEOCOLORMAXFALL,          EBML_UINT, 0, offsetof(MatroskaTrackVideoColor, max_fall), { .u=0 } },
     437             :     { MATROSKA_ID_VIDEOCOLORMASTERINGMETA,    EBML_NEST, 0, offsetof(MatroskaTrackVideoColor, mastering_meta), { .n = matroska_mastering_meta } },
     438             :     { 0 }
     439             : };
     440             : 
     441             : static const EbmlSyntax matroska_track_video_projection[] = {
     442             :     { MATROSKA_ID_VIDEOPROJECTIONTYPE,        EBML_UINT,  0, offsetof(MatroskaTrackVideoProjection, type), { .u = MATROSKA_VIDEO_PROJECTION_TYPE_RECTANGULAR } },
     443             :     { MATROSKA_ID_VIDEOPROJECTIONPRIVATE,     EBML_BIN,   0, offsetof(MatroskaTrackVideoProjection, private) },
     444             :     { MATROSKA_ID_VIDEOPROJECTIONPOSEYAW,     EBML_FLOAT, 0, offsetof(MatroskaTrackVideoProjection, yaw), { .f=0.0 } },
     445             :     { MATROSKA_ID_VIDEOPROJECTIONPOSEPITCH,   EBML_FLOAT, 0, offsetof(MatroskaTrackVideoProjection, pitch), { .f=0.0 } },
     446             :     { MATROSKA_ID_VIDEOPROJECTIONPOSEROLL,    EBML_FLOAT, 0, offsetof(MatroskaTrackVideoProjection, roll), { .f=0.0 } },
     447             :     { 0 }
     448             : };
     449             : 
     450             : static const EbmlSyntax matroska_track_video[] = {
     451             :     { MATROSKA_ID_VIDEOFRAMERATE,      EBML_FLOAT, 0, offsetof(MatroskaTrackVideo, frame_rate) },
     452             :     { MATROSKA_ID_VIDEODISPLAYWIDTH,   EBML_UINT,  0, offsetof(MatroskaTrackVideo, display_width), { .u=-1 } },
     453             :     { MATROSKA_ID_VIDEODISPLAYHEIGHT,  EBML_UINT,  0, offsetof(MatroskaTrackVideo, display_height), { .u=-1 } },
     454             :     { MATROSKA_ID_VIDEOPIXELWIDTH,     EBML_UINT,  0, offsetof(MatroskaTrackVideo, pixel_width) },
     455             :     { MATROSKA_ID_VIDEOPIXELHEIGHT,    EBML_UINT,  0, offsetof(MatroskaTrackVideo, pixel_height) },
     456             :     { MATROSKA_ID_VIDEOCOLORSPACE,     EBML_BIN,   0, offsetof(MatroskaTrackVideo, color_space) },
     457             :     { MATROSKA_ID_VIDEOALPHAMODE,      EBML_UINT,  0, offsetof(MatroskaTrackVideo, alpha_mode) },
     458             :     { MATROSKA_ID_VIDEOCOLOR,          EBML_NEST,  sizeof(MatroskaTrackVideoColor), offsetof(MatroskaTrackVideo, color), { .n = matroska_track_video_color } },
     459             :     { MATROSKA_ID_VIDEOPROJECTION,     EBML_NEST,  0, offsetof(MatroskaTrackVideo, projection), { .n = matroska_track_video_projection } },
     460             :     { MATROSKA_ID_VIDEOPIXELCROPB,     EBML_NONE },
     461             :     { MATROSKA_ID_VIDEOPIXELCROPT,     EBML_NONE },
     462             :     { MATROSKA_ID_VIDEOPIXELCROPL,     EBML_NONE },
     463             :     { MATROSKA_ID_VIDEOPIXELCROPR,     EBML_NONE },
     464             :     { MATROSKA_ID_VIDEODISPLAYUNIT,    EBML_UINT,  0, offsetof(MatroskaTrackVideo, display_unit), { .u= MATROSKA_VIDEO_DISPLAYUNIT_PIXELS } },
     465             :     { MATROSKA_ID_VIDEOFLAGINTERLACED, EBML_UINT,  0, offsetof(MatroskaTrackVideo, interlaced),  { .u = MATROSKA_VIDEO_INTERLACE_FLAG_UNDETERMINED } },
     466             :     { MATROSKA_ID_VIDEOFIELDORDER,     EBML_UINT,  0, offsetof(MatroskaTrackVideo, field_order), { .u = MATROSKA_VIDEO_FIELDORDER_UNDETERMINED } },
     467             :     { MATROSKA_ID_VIDEOSTEREOMODE,     EBML_UINT,  0, offsetof(MatroskaTrackVideo, stereo_mode), { .u = MATROSKA_VIDEO_STEREOMODE_TYPE_NB } },
     468             :     { MATROSKA_ID_VIDEOASPECTRATIO,    EBML_NONE },
     469             :     { 0 }
     470             : };
     471             : 
     472             : static const EbmlSyntax matroska_track_audio[] = {
     473             :     { MATROSKA_ID_AUDIOSAMPLINGFREQ,    EBML_FLOAT, 0, offsetof(MatroskaTrackAudio, samplerate), { .f = 8000.0 } },
     474             :     { MATROSKA_ID_AUDIOOUTSAMPLINGFREQ, EBML_FLOAT, 0, offsetof(MatroskaTrackAudio, out_samplerate) },
     475             :     { MATROSKA_ID_AUDIOBITDEPTH,        EBML_UINT,  0, offsetof(MatroskaTrackAudio, bitdepth) },
     476             :     { MATROSKA_ID_AUDIOCHANNELS,        EBML_UINT,  0, offsetof(MatroskaTrackAudio, channels),   { .u = 1 } },
     477             :     { 0 }
     478             : };
     479             : 
     480             : static const EbmlSyntax matroska_track_encoding_compression[] = {
     481             :     { MATROSKA_ID_ENCODINGCOMPALGO,     EBML_UINT, 0, offsetof(MatroskaTrackCompression, algo), { .u = 0 } },
     482             :     { MATROSKA_ID_ENCODINGCOMPSETTINGS, EBML_BIN,  0, offsetof(MatroskaTrackCompression, settings) },
     483             :     { 0 }
     484             : };
     485             : 
     486             : static const EbmlSyntax matroska_track_encoding_encryption[] = {
     487             :     { MATROSKA_ID_ENCODINGENCALGO,        EBML_UINT, 0, offsetof(MatroskaTrackEncryption,algo), {.u = 0} },
     488             :     { MATROSKA_ID_ENCODINGENCKEYID,       EBML_BIN, 0, offsetof(MatroskaTrackEncryption,key_id) },
     489             :     { MATROSKA_ID_ENCODINGENCAESSETTINGS, EBML_NONE },
     490             :     { MATROSKA_ID_ENCODINGSIGALGO,        EBML_NONE },
     491             :     { MATROSKA_ID_ENCODINGSIGHASHALGO,    EBML_NONE },
     492             :     { MATROSKA_ID_ENCODINGSIGKEYID,       EBML_NONE },
     493             :     { MATROSKA_ID_ENCODINGSIGNATURE,      EBML_NONE },
     494             :     { 0 }
     495             : };
     496             : static const EbmlSyntax matroska_track_encoding[] = {
     497             :     { MATROSKA_ID_ENCODINGSCOPE,       EBML_UINT, 0, offsetof(MatroskaTrackEncoding, scope),       { .u = 1 } },
     498             :     { MATROSKA_ID_ENCODINGTYPE,        EBML_UINT, 0, offsetof(MatroskaTrackEncoding, type),        { .u = 0 } },
     499             :     { MATROSKA_ID_ENCODINGCOMPRESSION, EBML_NEST, 0, offsetof(MatroskaTrackEncoding, compression), { .n = matroska_track_encoding_compression } },
     500             :     { MATROSKA_ID_ENCODINGENCRYPTION,  EBML_NEST, 0, offsetof(MatroskaTrackEncoding, encryption),  { .n = matroska_track_encoding_encryption } },
     501             :     { MATROSKA_ID_ENCODINGORDER,       EBML_NONE },
     502             :     { 0 }
     503             : };
     504             : 
     505             : static const EbmlSyntax matroska_track_encodings[] = {
     506             :     { MATROSKA_ID_TRACKCONTENTENCODING, EBML_NEST, sizeof(MatroskaTrackEncoding), offsetof(MatroskaTrack, encodings), { .n = matroska_track_encoding } },
     507             :     { 0 }
     508             : };
     509             : 
     510             : static const EbmlSyntax matroska_track_plane[] = {
     511             :     { MATROSKA_ID_TRACKPLANEUID,  EBML_UINT, 0, offsetof(MatroskaTrackPlane,uid) },
     512             :     { MATROSKA_ID_TRACKPLANETYPE, EBML_UINT, 0, offsetof(MatroskaTrackPlane,type) },
     513             :     { 0 }
     514             : };
     515             : 
     516             : static const EbmlSyntax matroska_track_combine_planes[] = {
     517             :     { MATROSKA_ID_TRACKPLANE, EBML_NEST, sizeof(MatroskaTrackPlane), offsetof(MatroskaTrackOperation,combine_planes), {.n = matroska_track_plane} },
     518             :     { 0 }
     519             : };
     520             : 
     521             : static const EbmlSyntax matroska_track_operation[] = {
     522             :     { MATROSKA_ID_TRACKCOMBINEPLANES, EBML_NEST, 0, 0, {.n = matroska_track_combine_planes} },
     523             :     { 0 }
     524             : };
     525             : 
     526             : static const EbmlSyntax matroska_track[] = {
     527             :     { MATROSKA_ID_TRACKNUMBER,           EBML_UINT,  0, offsetof(MatroskaTrack, num) },
     528             :     { MATROSKA_ID_TRACKNAME,             EBML_UTF8,  0, offsetof(MatroskaTrack, name) },
     529             :     { MATROSKA_ID_TRACKUID,              EBML_UINT,  0, offsetof(MatroskaTrack, uid) },
     530             :     { MATROSKA_ID_TRACKTYPE,             EBML_UINT,  0, offsetof(MatroskaTrack, type) },
     531             :     { MATROSKA_ID_CODECID,               EBML_STR,   0, offsetof(MatroskaTrack, codec_id) },
     532             :     { MATROSKA_ID_CODECPRIVATE,          EBML_BIN,   0, offsetof(MatroskaTrack, codec_priv) },
     533             :     { MATROSKA_ID_CODECDELAY,            EBML_UINT,  0, offsetof(MatroskaTrack, codec_delay) },
     534             :     { MATROSKA_ID_TRACKLANGUAGE,         EBML_UTF8,  0, offsetof(MatroskaTrack, language),     { .s = "eng" } },
     535             :     { MATROSKA_ID_TRACKDEFAULTDURATION,  EBML_UINT,  0, offsetof(MatroskaTrack, default_duration) },
     536             :     { MATROSKA_ID_TRACKTIMECODESCALE,    EBML_FLOAT, 0, offsetof(MatroskaTrack, time_scale),   { .f = 1.0 } },
     537             :     { MATROSKA_ID_TRACKFLAGDEFAULT,      EBML_UINT,  0, offsetof(MatroskaTrack, flag_default), { .u = 1 } },
     538             :     { MATROSKA_ID_TRACKFLAGFORCED,       EBML_UINT,  0, offsetof(MatroskaTrack, flag_forced),  { .u = 0 } },
     539             :     { MATROSKA_ID_TRACKVIDEO,            EBML_NEST,  0, offsetof(MatroskaTrack, video),        { .n = matroska_track_video } },
     540             :     { MATROSKA_ID_TRACKAUDIO,            EBML_NEST,  0, offsetof(MatroskaTrack, audio),        { .n = matroska_track_audio } },
     541             :     { MATROSKA_ID_TRACKOPERATION,        EBML_NEST,  0, offsetof(MatroskaTrack, operation),    { .n = matroska_track_operation } },
     542             :     { MATROSKA_ID_TRACKCONTENTENCODINGS, EBML_NEST,  0, 0,                                     { .n = matroska_track_encodings } },
     543             :     { MATROSKA_ID_TRACKMAXBLKADDID,      EBML_UINT,  0, offsetof(MatroskaTrack, max_block_additional_id) },
     544             :     { MATROSKA_ID_SEEKPREROLL,           EBML_UINT,  0, offsetof(MatroskaTrack, seek_preroll) },
     545             :     { MATROSKA_ID_TRACKFLAGENABLED,      EBML_NONE },
     546             :     { MATROSKA_ID_TRACKFLAGLACING,       EBML_NONE },
     547             :     { MATROSKA_ID_CODECNAME,             EBML_NONE },
     548             :     { MATROSKA_ID_CODECDECODEALL,        EBML_NONE },
     549             :     { MATROSKA_ID_CODECINFOURL,          EBML_NONE },
     550             :     { MATROSKA_ID_CODECDOWNLOADURL,      EBML_NONE },
     551             :     { MATROSKA_ID_TRACKMINCACHE,         EBML_NONE },
     552             :     { MATROSKA_ID_TRACKMAXCACHE,         EBML_NONE },
     553             :     { 0 }
     554             : };
     555             : 
     556             : static const EbmlSyntax matroska_tracks[] = {
     557             :     { MATROSKA_ID_TRACKENTRY, EBML_NEST, sizeof(MatroskaTrack), offsetof(MatroskaDemuxContext, tracks), { .n = matroska_track } },
     558             :     { 0 }
     559             : };
     560             : 
     561             : static const EbmlSyntax matroska_attachment[] = {
     562             :     { MATROSKA_ID_FILEUID,      EBML_UINT, 0, offsetof(MatroskaAttachment, uid) },
     563             :     { MATROSKA_ID_FILENAME,     EBML_UTF8, 0, offsetof(MatroskaAttachment, filename) },
     564             :     { MATROSKA_ID_FILEMIMETYPE, EBML_STR,  0, offsetof(MatroskaAttachment, mime) },
     565             :     { MATROSKA_ID_FILEDATA,     EBML_BIN,  0, offsetof(MatroskaAttachment, bin) },
     566             :     { MATROSKA_ID_FILEDESC,     EBML_NONE },
     567             :     { 0 }
     568             : };
     569             : 
     570             : static const EbmlSyntax matroska_attachments[] = {
     571             :     { MATROSKA_ID_ATTACHEDFILE, EBML_NEST, sizeof(MatroskaAttachment), offsetof(MatroskaDemuxContext, attachments), { .n = matroska_attachment } },
     572             :     { 0 }
     573             : };
     574             : 
     575             : static const EbmlSyntax matroska_chapter_display[] = {
     576             :     { MATROSKA_ID_CHAPSTRING,  EBML_UTF8, 0, offsetof(MatroskaChapter, title) },
     577             :     { MATROSKA_ID_CHAPLANG,    EBML_NONE },
     578             :     { MATROSKA_ID_CHAPCOUNTRY, EBML_NONE },
     579             :     { 0 }
     580             : };
     581             : 
     582             : static const EbmlSyntax matroska_chapter_entry[] = {
     583             :     { MATROSKA_ID_CHAPTERTIMESTART,   EBML_UINT, 0, offsetof(MatroskaChapter, start), { .u = AV_NOPTS_VALUE } },
     584             :     { MATROSKA_ID_CHAPTERTIMEEND,     EBML_UINT, 0, offsetof(MatroskaChapter, end),   { .u = AV_NOPTS_VALUE } },
     585             :     { MATROSKA_ID_CHAPTERUID,         EBML_UINT, 0, offsetof(MatroskaChapter, uid) },
     586             :     { MATROSKA_ID_CHAPTERDISPLAY,     EBML_NEST, 0,                        0,         { .n = matroska_chapter_display } },
     587             :     { MATROSKA_ID_CHAPTERFLAGHIDDEN,  EBML_NONE },
     588             :     { MATROSKA_ID_CHAPTERFLAGENABLED, EBML_NONE },
     589             :     { MATROSKA_ID_CHAPTERPHYSEQUIV,   EBML_NONE },
     590             :     { MATROSKA_ID_CHAPTERATOM,        EBML_NONE },
     591             :     { 0 }
     592             : };
     593             : 
     594             : static const EbmlSyntax matroska_chapter[] = {
     595             :     { MATROSKA_ID_CHAPTERATOM,        EBML_NEST, sizeof(MatroskaChapter), offsetof(MatroskaDemuxContext, chapters), { .n = matroska_chapter_entry } },
     596             :     { MATROSKA_ID_EDITIONUID,         EBML_NONE },
     597             :     { MATROSKA_ID_EDITIONFLAGHIDDEN,  EBML_NONE },
     598             :     { MATROSKA_ID_EDITIONFLAGDEFAULT, EBML_NONE },
     599             :     { MATROSKA_ID_EDITIONFLAGORDERED, EBML_NONE },
     600             :     { 0 }
     601             : };
     602             : 
     603             : static const EbmlSyntax matroska_chapters[] = {
     604             :     { MATROSKA_ID_EDITIONENTRY, EBML_NEST, 0, 0, { .n = matroska_chapter } },
     605             :     { 0 }
     606             : };
     607             : 
     608             : static const EbmlSyntax matroska_index_pos[] = {
     609             :     { MATROSKA_ID_CUETRACK,           EBML_UINT, 0, offsetof(MatroskaIndexPos, track) },
     610             :     { MATROSKA_ID_CUECLUSTERPOSITION, EBML_UINT, 0, offsetof(MatroskaIndexPos, pos) },
     611             :     { MATROSKA_ID_CUERELATIVEPOSITION,EBML_NONE },
     612             :     { MATROSKA_ID_CUEDURATION,        EBML_NONE },
     613             :     { MATROSKA_ID_CUEBLOCKNUMBER,     EBML_NONE },
     614             :     { 0 }
     615             : };
     616             : 
     617             : static const EbmlSyntax matroska_index_entry[] = {
     618             :     { MATROSKA_ID_CUETIME,          EBML_UINT, 0,                        offsetof(MatroskaIndex, time) },
     619             :     { MATROSKA_ID_CUETRACKPOSITION, EBML_NEST, sizeof(MatroskaIndexPos), offsetof(MatroskaIndex, pos), { .n = matroska_index_pos } },
     620             :     { 0 }
     621             : };
     622             : 
     623             : static const EbmlSyntax matroska_index[] = {
     624             :     { MATROSKA_ID_POINTENTRY, EBML_NEST, sizeof(MatroskaIndex), offsetof(MatroskaDemuxContext, index), { .n = matroska_index_entry } },
     625             :     { 0 }
     626             : };
     627             : 
     628             : static const EbmlSyntax matroska_simpletag[] = {
     629             :     { MATROSKA_ID_TAGNAME,        EBML_UTF8, 0,                   offsetof(MatroskaTag, name) },
     630             :     { MATROSKA_ID_TAGSTRING,      EBML_UTF8, 0,                   offsetof(MatroskaTag, string) },
     631             :     { MATROSKA_ID_TAGLANG,        EBML_STR,  0,                   offsetof(MatroskaTag, lang), { .s = "und" } },
     632             :     { MATROSKA_ID_TAGDEFAULT,     EBML_UINT, 0,                   offsetof(MatroskaTag, def) },
     633             :     { MATROSKA_ID_TAGDEFAULT_BUG, EBML_UINT, 0,                   offsetof(MatroskaTag, def) },
     634             :     { MATROSKA_ID_SIMPLETAG,      EBML_NEST, sizeof(MatroskaTag), offsetof(MatroskaTag, sub),  { .n = matroska_simpletag } },
     635             :     { 0 }
     636             : };
     637             : 
     638             : static const EbmlSyntax matroska_tagtargets[] = {
     639             :     { MATROSKA_ID_TAGTARGETS_TYPE,       EBML_STR,  0, offsetof(MatroskaTagTarget, type) },
     640             :     { MATROSKA_ID_TAGTARGETS_TYPEVALUE,  EBML_UINT, 0, offsetof(MatroskaTagTarget, typevalue), { .u = 50 } },
     641             :     { MATROSKA_ID_TAGTARGETS_TRACKUID,   EBML_UINT, 0, offsetof(MatroskaTagTarget, trackuid) },
     642             :     { MATROSKA_ID_TAGTARGETS_CHAPTERUID, EBML_UINT, 0, offsetof(MatroskaTagTarget, chapteruid) },
     643             :     { MATROSKA_ID_TAGTARGETS_ATTACHUID,  EBML_UINT, 0, offsetof(MatroskaTagTarget, attachuid) },
     644             :     { 0 }
     645             : };
     646             : 
     647             : static const EbmlSyntax matroska_tag[] = {
     648             :     { MATROSKA_ID_SIMPLETAG,  EBML_NEST, sizeof(MatroskaTag), offsetof(MatroskaTags, tag),    { .n = matroska_simpletag } },
     649             :     { MATROSKA_ID_TAGTARGETS, EBML_NEST, 0,                   offsetof(MatroskaTags, target), { .n = matroska_tagtargets } },
     650             :     { 0 }
     651             : };
     652             : 
     653             : static const EbmlSyntax matroska_tags[] = {
     654             :     { MATROSKA_ID_TAG, EBML_NEST, sizeof(MatroskaTags), offsetof(MatroskaDemuxContext, tags), { .n = matroska_tag } },
     655             :     { 0 }
     656             : };
     657             : 
     658             : static const EbmlSyntax matroska_seekhead_entry[] = {
     659             :     { MATROSKA_ID_SEEKID,       EBML_UINT, 0, offsetof(MatroskaSeekhead, id) },
     660             :     { MATROSKA_ID_SEEKPOSITION, EBML_UINT, 0, offsetof(MatroskaSeekhead, pos), { .u = -1 } },
     661             :     { 0 }
     662             : };
     663             : 
     664             : static const EbmlSyntax matroska_seekhead[] = {
     665             :     { MATROSKA_ID_SEEKENTRY, EBML_NEST, sizeof(MatroskaSeekhead), offsetof(MatroskaDemuxContext, seekhead), { .n = matroska_seekhead_entry } },
     666             :     { 0 }
     667             : };
     668             : 
     669             : static const EbmlSyntax matroska_segment[] = {
     670             :     { MATROSKA_ID_INFO,        EBML_LEVEL1, 0, 0, { .n = matroska_info } },
     671             :     { MATROSKA_ID_TRACKS,      EBML_LEVEL1, 0, 0, { .n = matroska_tracks } },
     672             :     { MATROSKA_ID_ATTACHMENTS, EBML_LEVEL1, 0, 0, { .n = matroska_attachments } },
     673             :     { MATROSKA_ID_CHAPTERS,    EBML_LEVEL1, 0, 0, { .n = matroska_chapters } },
     674             :     { MATROSKA_ID_CUES,        EBML_LEVEL1, 0, 0, { .n = matroska_index } },
     675             :     { MATROSKA_ID_TAGS,        EBML_LEVEL1, 0, 0, { .n = matroska_tags } },
     676             :     { MATROSKA_ID_SEEKHEAD,    EBML_LEVEL1, 0, 0, { .n = matroska_seekhead } },
     677             :     { MATROSKA_ID_CLUSTER,     EBML_STOP },
     678             :     { 0 }
     679             : };
     680             : 
     681             : static const EbmlSyntax matroska_segments[] = {
     682             :     { MATROSKA_ID_SEGMENT, EBML_NEST, 0, 0, { .n = matroska_segment } },
     683             :     { 0 }
     684             : };
     685             : 
     686             : static const EbmlSyntax matroska_blockmore[] = {
     687             :     { MATROSKA_ID_BLOCKADDID,      EBML_UINT, 0, offsetof(MatroskaBlock,additional_id) },
     688             :     { MATROSKA_ID_BLOCKADDITIONAL, EBML_BIN,  0, offsetof(MatroskaBlock,additional) },
     689             :     { 0 }
     690             : };
     691             : 
     692             : static const EbmlSyntax matroska_blockadditions[] = {
     693             :     { MATROSKA_ID_BLOCKMORE, EBML_NEST, 0, 0, {.n = matroska_blockmore} },
     694             :     { 0 }
     695             : };
     696             : 
     697             : static const EbmlSyntax matroska_blockgroup[] = {
     698             :     { MATROSKA_ID_BLOCK,          EBML_BIN,  0, offsetof(MatroskaBlock, bin) },
     699             :     { MATROSKA_ID_BLOCKADDITIONS, EBML_NEST, 0, 0, { .n = matroska_blockadditions} },
     700             :     { MATROSKA_ID_SIMPLEBLOCK,    EBML_BIN,  0, offsetof(MatroskaBlock, bin) },
     701             :     { MATROSKA_ID_BLOCKDURATION,  EBML_UINT, 0, offsetof(MatroskaBlock, duration) },
     702             :     { MATROSKA_ID_DISCARDPADDING, EBML_SINT, 0, offsetof(MatroskaBlock, discard_padding) },
     703             :     { MATROSKA_ID_BLOCKREFERENCE, EBML_SINT, 0, offsetof(MatroskaBlock, reference), { .i = INT64_MIN } },
     704             :     { MATROSKA_ID_CODECSTATE,     EBML_NONE },
     705             :     {                          1, EBML_UINT, 0, offsetof(MatroskaBlock, non_simple), { .u = 1 } },
     706             :     { 0 }
     707             : };
     708             : 
     709             : static const EbmlSyntax matroska_cluster[] = {
     710             :     { MATROSKA_ID_CLUSTERTIMECODE, EBML_UINT, 0,                     offsetof(MatroskaCluster, timecode) },
     711             :     { MATROSKA_ID_BLOCKGROUP,      EBML_NEST, sizeof(MatroskaBlock), offsetof(MatroskaCluster, blocks), { .n = matroska_blockgroup } },
     712             :     { MATROSKA_ID_SIMPLEBLOCK,     EBML_PASS, sizeof(MatroskaBlock), offsetof(MatroskaCluster, blocks), { .n = matroska_blockgroup } },
     713             :     { MATROSKA_ID_CLUSTERPOSITION, EBML_NONE },
     714             :     { MATROSKA_ID_CLUSTERPREVSIZE, EBML_NONE },
     715             :     { 0 }
     716             : };
     717             : 
     718             : static const EbmlSyntax matroska_clusters[] = {
     719             :     { MATROSKA_ID_CLUSTER,  EBML_NEST, 0, 0, { .n = matroska_cluster } },
     720             :     { MATROSKA_ID_INFO,     EBML_NONE },
     721             :     { MATROSKA_ID_CUES,     EBML_NONE },
     722             :     { MATROSKA_ID_TAGS,     EBML_NONE },
     723             :     { MATROSKA_ID_SEEKHEAD, EBML_NONE },
     724             :     { 0 }
     725             : };
     726             : 
     727             : static const EbmlSyntax matroska_cluster_incremental_parsing[] = {
     728             :     { MATROSKA_ID_CLUSTERTIMECODE, EBML_UINT, 0,                     offsetof(MatroskaCluster, timecode) },
     729             :     { MATROSKA_ID_BLOCKGROUP,      EBML_NEST, sizeof(MatroskaBlock), offsetof(MatroskaCluster, blocks), { .n = matroska_blockgroup } },
     730             :     { MATROSKA_ID_SIMPLEBLOCK,     EBML_PASS, sizeof(MatroskaBlock), offsetof(MatroskaCluster, blocks), { .n = matroska_blockgroup } },
     731             :     { MATROSKA_ID_CLUSTERPOSITION, EBML_NONE },
     732             :     { MATROSKA_ID_CLUSTERPREVSIZE, EBML_NONE },
     733             :     { MATROSKA_ID_INFO,            EBML_NONE },
     734             :     { MATROSKA_ID_CUES,            EBML_NONE },
     735             :     { MATROSKA_ID_TAGS,            EBML_NONE },
     736             :     { MATROSKA_ID_SEEKHEAD,        EBML_NONE },
     737             :     { MATROSKA_ID_CLUSTER,         EBML_STOP },
     738             :     { 0 }
     739             : };
     740             : 
     741             : static const EbmlSyntax matroska_cluster_incremental[] = {
     742             :     { MATROSKA_ID_CLUSTERTIMECODE, EBML_UINT, 0, offsetof(MatroskaCluster, timecode) },
     743             :     { MATROSKA_ID_BLOCKGROUP,      EBML_STOP },
     744             :     { MATROSKA_ID_SIMPLEBLOCK,     EBML_STOP },
     745             :     { MATROSKA_ID_CLUSTERPOSITION, EBML_NONE },
     746             :     { MATROSKA_ID_CLUSTERPREVSIZE, EBML_NONE },
     747             :     { 0 }
     748             : };
     749             : 
     750             : static const EbmlSyntax matroska_clusters_incremental[] = {
     751             :     { MATROSKA_ID_CLUSTER,  EBML_NEST, 0, 0, { .n = matroska_cluster_incremental } },
     752             :     { MATROSKA_ID_INFO,     EBML_NONE },
     753             :     { MATROSKA_ID_CUES,     EBML_NONE },
     754             :     { MATROSKA_ID_TAGS,     EBML_NONE },
     755             :     { MATROSKA_ID_SEEKHEAD, EBML_NONE },
     756             :     { 0 }
     757             : };
     758             : 
     759             : static const char *const matroska_doctypes[] = { "matroska", "webm" };
     760             : 
     761             : static int matroska_read_close(AVFormatContext *s);
     762             : 
     763         289 : static int matroska_resync(MatroskaDemuxContext *matroska, int64_t last_pos)
     764             : {
     765         289 :     AVIOContext *pb = matroska->ctx->pb;
     766             :     int64_t ret;
     767             :     uint32_t id;
     768         289 :     matroska->current_id = 0;
     769         289 :     matroska->num_levels = 0;
     770             : 
     771             :     /* seek to next position to resync from */
     772         289 :     if ((ret = avio_seek(pb, last_pos + 1, SEEK_SET)) < 0) {
     773         282 :         matroska->done = 1;
     774         282 :         return ret;
     775             :     }
     776             : 
     777           7 :     id = avio_rb32(pb);
     778             : 
     779             :     // try to find a toplevel element
     780      641950 :     while (!avio_feof(pb)) {
     781      641939 :         if (id == MATROSKA_ID_INFO     || id == MATROSKA_ID_TRACKS      ||
     782      641937 :             id == MATROSKA_ID_CUES     || id == MATROSKA_ID_TAGS        ||
     783      641937 :             id == MATROSKA_ID_SEEKHEAD || id == MATROSKA_ID_ATTACHMENTS ||
     784      641936 :             id == MATROSKA_ID_CLUSTER  || id == MATROSKA_ID_CHAPTERS) {
     785           3 :             matroska->current_id = id;
     786           3 :             return 0;
     787             :         }
     788      641936 :         id = (id << 8) | avio_r8(pb);
     789             :     }
     790             : 
     791           4 :     matroska->done = 1;
     792           4 :     return AVERROR_EOF;
     793             : }
     794             : 
     795             : /*
     796             :  * Return: Whether we reached the end of a level in the hierarchy or not.
     797             :  */
     798       17401 : static int ebml_level_end(MatroskaDemuxContext *matroska)
     799             : {
     800       17401 :     AVIOContext *pb = matroska->ctx->pb;
     801       17401 :     int64_t pos = avio_tell(pb);
     802             : 
     803       17401 :     if (matroska->num_levels > 0) {
     804       17340 :         MatroskaLevel *level = &matroska->levels[matroska->num_levels - 1];
     805       17340 :         if (pos - level->start >= level->length || matroska->current_id) {
     806        3809 :             matroska->num_levels--;
     807        3809 :             return 1;
     808             :         }
     809             :     }
     810       13592 :     return (matroska->is_live && matroska->ctx->pb->eof_reached) ? 1 : 0;
     811             : }
     812             : 
     813             : /*
     814             :  * Read: an "EBML number", which is defined as a variable-length
     815             :  * array of bytes. The first byte indicates the length by giving a
     816             :  * number of 0-bits followed by a one. The position of the first
     817             :  * "one" bit inside the first byte indicates the length of this
     818             :  * number.
     819             :  * Returns: number of bytes read, < 0 on error
     820             :  */
     821      113433 : static int ebml_read_num(MatroskaDemuxContext *matroska, AVIOContext *pb,
     822             :                          int max_size, uint64_t *number)
     823             : {
     824      113433 :     int read = 1, n = 1;
     825      113433 :     uint64_t total = 0;
     826             : 
     827             :     /* The first byte tells us the length in bytes - avio_r8() can normally
     828             :      * return 0, but since that's not a valid first ebmlID byte, we can
     829             :      * use it safely here to catch EOS. */
     830      113433 :     if (!(total = avio_r8(pb))) {
     831             :         /* we might encounter EOS here */
     832         313 :         if (!avio_feof(pb)) {
     833           0 :             int64_t pos = avio_tell(pb);
     834           0 :             av_log(matroska->ctx, AV_LOG_ERROR,
     835             :                    "Read error at pos. %"PRIu64" (0x%"PRIx64")\n",
     836             :                    pos, pos);
     837           0 :             return pb->error ? pb->error : AVERROR(EIO);
     838             :         }
     839         313 :         return AVERROR_EOF;
     840             :     }
     841             : 
     842             :     /* get the length of the EBML number */
     843      113120 :     read = 8 - ff_log2_tab[total];
     844      113120 :     if (read > max_size) {
     845           0 :         int64_t pos = avio_tell(pb) - 1;
     846           0 :         av_log(matroska->ctx, AV_LOG_ERROR,
     847             :                "Invalid EBML number size tag 0x%02x at pos %"PRIu64" (0x%"PRIx64")\n",
     848           0 :                (uint8_t) total, pos, pos);
     849           0 :         return AVERROR_INVALIDDATA;
     850             :     }
     851             : 
     852             :     /* read out length */
     853      113120 :     total ^= 1 << ff_log2_tab[total];
     854      286889 :     while (n++ < read)
     855       60649 :         total = (total << 8) | avio_r8(pb);
     856             : 
     857      113120 :     *number = total;
     858             : 
     859      113120 :     return read;
     860             : }
     861             : 
     862             : /**
     863             :  * Read a EBML length value.
     864             :  * This needs special handling for the "unknown length" case which has multiple
     865             :  * encodings.
     866             :  */
     867       42388 : static int ebml_read_length(MatroskaDemuxContext *matroska, AVIOContext *pb,
     868             :                             uint64_t *number)
     869             : {
     870       42388 :     int res = ebml_read_num(matroska, pb, 8, number);
     871       42388 :     if (res > 0 && *number + 1 == 1ULL << (7 * res))
     872          11 :         *number = 0xffffffffffffffULL;
     873       42388 :     return res;
     874             : }
     875             : 
     876             : /*
     877             :  * Read the next element as an unsigned int.
     878             :  * 0 is success, < 0 is failure.
     879             :  */
     880        6256 : static int ebml_read_uint(AVIOContext *pb, int size, uint64_t *num)
     881             : {
     882        6256 :     int n = 0;
     883             : 
     884        6256 :     if (size > 8)
     885           0 :         return AVERROR_INVALIDDATA;
     886             : 
     887             :     /* big-endian ordering; build up number */
     888        6256 :     *num = 0;
     889       29610 :     while (n++ < size)
     890       17098 :         *num = (*num << 8) | avio_r8(pb);
     891             : 
     892        6256 :     return 0;
     893             : }
     894             : 
     895             : /*
     896             :  * Read the next element as a signed int.
     897             :  * 0 is success, < 0 is failure.
     898             :  */
     899          24 : static int ebml_read_sint(AVIOContext *pb, int size, int64_t *num)
     900             : {
     901          24 :     int n = 1;
     902             : 
     903          24 :     if (size > 8)
     904           0 :         return AVERROR_INVALIDDATA;
     905             : 
     906          24 :     if (size == 0) {
     907           0 :         *num = 0;
     908             :     } else {
     909          24 :         *num = sign_extend(avio_r8(pb), 8);
     910             : 
     911             :         /* big-endian ordering; build up number */
     912         120 :         while (n++ < size)
     913          72 :             *num = ((uint64_t)*num << 8) | avio_r8(pb);
     914             :     }
     915             : 
     916          24 :     return 0;
     917             : }
     918             : 
     919             : /*
     920             :  * Read the next element as a float.
     921             :  * 0 is success, < 0 is failure.
     922             :  */
     923         532 : static int ebml_read_float(AVIOContext *pb, int size, double *num)
     924             : {
     925         532 :     if (size == 0)
     926           0 :         *num = 0;
     927         532 :     else if (size == 4)
     928          34 :         *num = av_int2float(avio_rb32(pb));
     929         498 :     else if (size == 8)
     930         498 :         *num = av_int2double(avio_rb64(pb));
     931             :     else
     932           0 :         return AVERROR_INVALIDDATA;
     933             : 
     934         532 :     return 0;
     935             : }
     936             : 
     937             : /*
     938             :  * Read the next element as an ASCII string.
     939             :  * 0 is success, < 0 is failure.
     940             :  */
     941        1133 : static int ebml_read_ascii(AVIOContext *pb, int size, char **str)
     942             : {
     943             :     char *res;
     944             : 
     945             :     /* EBML strings are usually not 0-terminated, so we allocate one
     946             :      * byte more, read the string and NULL-terminate it ourselves. */
     947        1133 :     if (!(res = av_malloc(size + 1)))
     948           0 :         return AVERROR(ENOMEM);
     949        1133 :     if (avio_read(pb, (uint8_t *) res, size) != size) {
     950           0 :         av_free(res);
     951           0 :         return AVERROR(EIO);
     952             :     }
     953        1133 :     (res)[size] = '\0';
     954        1133 :     av_free(*str);
     955        1133 :     *str = res;
     956             : 
     957        1133 :     return 0;
     958             : }
     959             : 
     960             : /*
     961             :  * Read the next element as binary data.
     962             :  * 0 is success, < 0 is failure.
     963             :  */
     964       28353 : static int ebml_read_binary(AVIOContext *pb, int length, EbmlBin *bin)
     965             : {
     966             :     int ret;
     967             : 
     968       28353 :     ret = av_buffer_realloc(&bin->buf, length + AV_INPUT_BUFFER_PADDING_SIZE);
     969       28353 :     if (ret < 0)
     970           0 :         return ret;
     971       28353 :     memset(bin->buf->data + length, 0, AV_INPUT_BUFFER_PADDING_SIZE);
     972             : 
     973       28353 :     bin->data = bin->buf->data;
     974       28353 :     bin->size = length;
     975       28353 :     bin->pos  = avio_tell(pb);
     976       28353 :     if (avio_read(pb, bin->data, length) != length) {
     977           4 :         av_buffer_unref(&bin->buf);
     978           4 :         bin->data = NULL;
     979           4 :         bin->size = 0;
     980           4 :         return AVERROR(EIO);
     981             :     }
     982             : 
     983       28349 :     return 0;
     984             : }
     985             : 
     986             : /*
     987             :  * Read the next element, but only the header. The contents
     988             :  * are supposed to be sub-elements which can be read separately.
     989             :  * 0 is success, < 0 is failure.
     990             :  */
     991        4458 : static int ebml_read_master(MatroskaDemuxContext *matroska, uint64_t length)
     992             : {
     993        4458 :     AVIOContext *pb = matroska->ctx->pb;
     994             :     MatroskaLevel *level;
     995             : 
     996        4458 :     if (matroska->num_levels >= EBML_MAX_DEPTH) {
     997           0 :         av_log(matroska->ctx, AV_LOG_ERROR,
     998             :                "File moves beyond max. allowed depth (%d)\n", EBML_MAX_DEPTH);
     999           0 :         return AVERROR(ENOSYS);
    1000             :     }
    1001             : 
    1002        4458 :     level         = &matroska->levels[matroska->num_levels++];
    1003        4458 :     level->start  = avio_tell(pb);
    1004        4458 :     level->length = length;
    1005             : 
    1006        4458 :     return 0;
    1007             : }
    1008             : 
    1009             : /*
    1010             :  * Read signed/unsigned "EBML" numbers.
    1011             :  * Return: number of bytes processed, < 0 on error
    1012             :  */
    1013       28337 : static int matroska_ebmlnum_uint(MatroskaDemuxContext *matroska,
    1014             :                                  uint8_t *data, uint32_t size, uint64_t *num)
    1015             : {
    1016             :     AVIOContext pb;
    1017       28337 :     ffio_init_context(&pb, data, size, 0, NULL, NULL, NULL, NULL);
    1018       28337 :     return ebml_read_num(matroska, &pb, FFMIN(size, 8), num);
    1019             : }
    1020             : 
    1021             : /*
    1022             :  * Same as above, but signed.
    1023             :  */
    1024         136 : static int matroska_ebmlnum_sint(MatroskaDemuxContext *matroska,
    1025             :                                  uint8_t *data, uint32_t size, int64_t *num)
    1026             : {
    1027             :     uint64_t unum;
    1028             :     int res;
    1029             : 
    1030             :     /* read as unsigned number first */
    1031         136 :     if ((res = matroska_ebmlnum_uint(matroska, data, size, &unum)) < 0)
    1032           0 :         return res;
    1033             : 
    1034             :     /* make signed (weird way) */
    1035         136 :     *num = unum - ((1LL << (7 * res - 1)) - 1);
    1036             : 
    1037         136 :     return res;
    1038             : }
    1039             : 
    1040             : static int ebml_parse_elem(MatroskaDemuxContext *matroska,
    1041             :                            EbmlSyntax *syntax, void *data);
    1042             : 
    1043       71717 : static int ebml_parse_id(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
    1044             :                          uint32_t id, void *data)
    1045             : {
    1046             :     int i;
    1047      222706 :     for (i = 0; syntax[i].id; i++)
    1048      222512 :         if (id == syntax[i].id)
    1049       71523 :             break;
    1050       71717 :     if (!syntax[i].id && id == MATROSKA_ID_CLUSTER &&
    1051           0 :         matroska->num_levels > 0                   &&
    1052           0 :         matroska->levels[matroska->num_levels - 1].length == 0xffffffffffffff)
    1053           0 :         return 0;  // we reached the end of an unknown size cluster
    1054       71717 :     if (!syntax[i].id && id != EBML_ID_VOID && id != EBML_ID_CRC32) {
    1055          10 :         av_log(matroska->ctx, AV_LOG_DEBUG, "Unknown entry 0x%"PRIX32"\n", id);
    1056             :     }
    1057       71717 :     return ebml_parse_elem(matroska, &syntax[i], data);
    1058             : }
    1059             : 
    1060       44005 : static int ebml_parse(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
    1061             :                       void *data)
    1062             : {
    1063       44005 :     if (!matroska->current_id) {
    1064             :         uint64_t id;
    1065       42610 :         int res = ebml_read_num(matroska, matroska->ctx->pb, 4, &id);
    1066       42610 :         if (res < 0) {
    1067             :             // in live mode, finish parsing if EOF is reached.
    1068         317 :             return (matroska->is_live && matroska->ctx->pb->eof_reached &&
    1069         622 :                     res == AVERROR_EOF) ? 1 : res;
    1070             :         }
    1071       42297 :         matroska->current_id = id | 1 << 7 * res;
    1072             :     }
    1073       43692 :     return ebml_parse_id(matroska, syntax, matroska->current_id, data);
    1074             : }
    1075             : 
    1076        4458 : static int ebml_parse_nest(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
    1077             :                            void *data)
    1078             : {
    1079        4458 :     int i, res = 0;
    1080             : 
    1081       32602 :     for (i = 0; syntax[i].id; i++)
    1082       28144 :         switch (syntax[i].type) {
    1083         294 :         case EBML_SINT:
    1084         294 :             *(int64_t *) ((char *) data + syntax[i].data_offset) = syntax[i].def.i;
    1085         294 :             break;
    1086       10341 :         case EBML_UINT:
    1087       10341 :             *(uint64_t *) ((char *) data + syntax[i].data_offset) = syntax[i].def.u;
    1088       10341 :             break;
    1089         949 :         case EBML_FLOAT:
    1090         949 :             *(double *) ((char *) data + syntax[i].data_offset) = syntax[i].def.f;
    1091         949 :             break;
    1092        2118 :         case EBML_STR:
    1093             :         case EBML_UTF8:
    1094             :             // the default may be NULL
    1095        2118 :             if (syntax[i].def.s) {
    1096         686 :                 uint8_t **dst = (uint8_t **) ((uint8_t *) data + syntax[i].data_offset);
    1097         686 :                 *dst = av_strdup(syntax[i].def.s);
    1098         686 :                 if (!*dst)
    1099           0 :                     return AVERROR(ENOMEM);
    1100             :             }
    1101        2118 :             break;
    1102             :         }
    1103             : 
    1104       22447 :     while (!res && !ebml_level_end(matroska))
    1105       13531 :         res = ebml_parse(matroska, syntax, data);
    1106             : 
    1107        4458 :     return res;
    1108             : }
    1109             : 
    1110        1828 : static int is_ebml_id_valid(uint32_t id)
    1111             : {
    1112             :     // Due to endian nonsense in Matroska, the highest byte with any bits set
    1113             :     // will contain the leading length bit. This bit in turn identifies the
    1114             :     // total byte length of the element by its position within the byte.
    1115        1828 :     unsigned int bits = av_log2(id);
    1116        1828 :     return id && (bits + 7) / 8 ==  (8 - bits % 8);
    1117             : }
    1118             : 
    1119             : /*
    1120             :  * Allocate and return the entry for the level1 element with the given ID. If
    1121             :  * an entry already exists, return the existing entry.
    1122             :  */
    1123        1828 : static MatroskaLevel1Element *matroska_find_level1_elem(MatroskaDemuxContext *matroska,
    1124             :                                                         uint32_t id)
    1125             : {
    1126             :     int i;
    1127             :     MatroskaLevel1Element *elem;
    1128             : 
    1129        1828 :     if (!is_ebml_id_valid(id))
    1130           0 :         return NULL;
    1131             : 
    1132             :     // Some files link to all clusters; useless.
    1133        1828 :     if (id == MATROSKA_ID_CLUSTER)
    1134          24 :         return NULL;
    1135             : 
    1136             :     // There can be multiple seekheads.
    1137        1804 :     if (id != MATROSKA_ID_SEEKHEAD) {
    1138        4315 :         for (i = 0; i < matroska->num_level1_elems; i++) {
    1139        3416 :             if (matroska->level1_elems[i].id == id)
    1140         618 :                 return &matroska->level1_elems[i];
    1141             :         }
    1142             :     }
    1143             : 
    1144             :     // Only a completely broken file would have more elements.
    1145             :     // It also provides a low-effort way to escape from circular seekheads
    1146             :     // (every iteration will add a level1 entry).
    1147        1186 :     if (matroska->num_level1_elems >= FF_ARRAY_ELEMS(matroska->level1_elems)) {
    1148           0 :         av_log(matroska->ctx, AV_LOG_ERROR, "Too many level1 elements or circular seekheads.\n");
    1149           0 :         return NULL;
    1150             :     }
    1151             : 
    1152        1186 :     elem = &matroska->level1_elems[matroska->num_level1_elems++];
    1153        1186 :     *elem = (MatroskaLevel1Element){.id = id};
    1154             : 
    1155        1186 :     return elem;
    1156             : }
    1157             : 
    1158       71717 : static int ebml_parse_elem(MatroskaDemuxContext *matroska,
    1159             :                            EbmlSyntax *syntax, void *data)
    1160             : {
    1161             :     static const uint64_t max_lengths[EBML_TYPE_COUNT] = {
    1162             :         [EBML_UINT]  = 8,
    1163             :         [EBML_FLOAT] = 8,
    1164             :         // max. 16 MB for strings
    1165             :         [EBML_STR]   = 0x1000000,
    1166             :         [EBML_UTF8]  = 0x1000000,
    1167             :         // max. 256 MB for binary data
    1168             :         [EBML_BIN]   = 0x10000000,
    1169             :         // no limits for anything else
    1170             :     };
    1171       71717 :     AVIOContext *pb = matroska->ctx->pb;
    1172       71717 :     uint32_t id = syntax->id;
    1173             :     uint64_t length;
    1174             :     int res;
    1175             :     void *newelem;
    1176             :     MatroskaLevel1Element *level1_elem;
    1177             : 
    1178       71717 :     data = (char *) data + syntax->data_offset;
    1179       71717 :     if (syntax->list_elem_size) {
    1180       29804 :         EbmlList *list = data;
    1181       29804 :         newelem = av_realloc_array(list->elem, list->nb_elem + 1, syntax->list_elem_size);
    1182       29804 :         if (!newelem)
    1183           0 :             return AVERROR(ENOMEM);
    1184       29804 :         list->elem = newelem;
    1185       29804 :         data = (char *) list->elem + list->nb_elem * syntax->list_elem_size;
    1186       29804 :         memset(data, 0, syntax->list_elem_size);
    1187       29804 :         list->nb_elem++;
    1188             :     }
    1189             : 
    1190       71717 :     if (syntax->type != EBML_PASS && syntax->type != EBML_STOP) {
    1191       42290 :         matroska->current_id = 0;
    1192       42290 :         if ((res = ebml_read_length(matroska, pb, &length)) < 0)
    1193           0 :             return res;
    1194       42290 :         if (max_lengths[syntax->type] && length > max_lengths[syntax->type]) {
    1195           0 :             av_log(matroska->ctx, AV_LOG_ERROR,
    1196             :                    "Invalid length 0x%"PRIx64" > 0x%"PRIx64" for syntax element %i\n",
    1197           0 :                    length, max_lengths[syntax->type], syntax->type);
    1198           0 :             return AVERROR_INVALIDDATA;
    1199             :         }
    1200             :     }
    1201             : 
    1202       71717 :     switch (syntax->type) {
    1203        6256 :     case EBML_UINT:
    1204        6256 :         res = ebml_read_uint(pb, length, data);
    1205        6256 :         break;
    1206          24 :     case EBML_SINT:
    1207          24 :         res = ebml_read_sint(pb, length, data);
    1208          24 :         break;
    1209         532 :     case EBML_FLOAT:
    1210         532 :         res = ebml_read_float(pb, length, data);
    1211         532 :         break;
    1212        1133 :     case EBML_STR:
    1213             :     case EBML_UTF8:
    1214        1133 :         res = ebml_read_ascii(pb, length, data);
    1215        1133 :         break;
    1216       28353 :     case EBML_BIN:
    1217       28353 :         res = ebml_read_binary(pb, length, data);
    1218       28353 :         break;
    1219        4458 :     case EBML_LEVEL1:
    1220             :     case EBML_NEST:
    1221        4458 :         if ((res = ebml_read_master(matroska, length)) < 0)
    1222           0 :             return res;
    1223        4458 :         if (id == MATROSKA_ID_SEGMENT)
    1224         296 :             matroska->segment_start = avio_tell(matroska->ctx->pb);
    1225        4458 :         if (id == MATROSKA_ID_CUES)
    1226          12 :             matroska->cues_parsing_deferred = 0;
    1227        5386 :         if (syntax->type == EBML_LEVEL1 &&
    1228         928 :             (level1_elem = matroska_find_level1_elem(matroska, syntax->id))) {
    1229         928 :             if (level1_elem->parsed)
    1230           0 :                 av_log(matroska->ctx, AV_LOG_ERROR, "Duplicate element\n");
    1231         928 :             level1_elem->parsed = 1;
    1232             :         }
    1233        4458 :         return ebml_parse_nest(matroska, syntax->def.n, data);
    1234       28025 :     case EBML_PASS:
    1235       28025 :         return ebml_parse_id(matroska, syntax->def.n, id, data);
    1236        1402 :     case EBML_STOP:
    1237        1402 :         return 1;
    1238        1534 :     default:
    1239        1534 :         if (ffio_limit(pb, length) != length)
    1240           2 :             return AVERROR(EIO);
    1241        1532 :         return avio_skip(pb, length) < 0 ? AVERROR(EIO) : 0;
    1242             :     }
    1243       36298 :     if (res == AVERROR_INVALIDDATA)
    1244           0 :         av_log(matroska->ctx, AV_LOG_ERROR, "Invalid element\n");
    1245       36298 :     else if (res == AVERROR(EIO))
    1246           4 :         av_log(matroska->ctx, AV_LOG_ERROR, "Read error\n");
    1247       36298 :     return res;
    1248             : }
    1249             : 
    1250       92162 : static void ebml_free(EbmlSyntax *syntax, void *data)
    1251             : {
    1252             :     int i, j;
    1253      437335 :     for (i = 0; syntax[i].id; i++) {
    1254      345173 :         void *data_off = (char *) data + syntax[i].data_offset;
    1255      345173 :         switch (syntax[i].type) {
    1256        2118 :         case EBML_STR:
    1257             :         case EBML_UTF8:
    1258        2118 :             av_freep(data_off);
    1259        2118 :             break;
    1260       85737 :         case EBML_BIN:
    1261       85737 :             av_buffer_unref(&((EbmlBin *) data_off)->buf);
    1262       85737 :             break;
    1263       64747 :         case EBML_LEVEL1:
    1264             :         case EBML_NEST:
    1265       64747 :             if (syntax[i].list_elem_size) {
    1266        3832 :                 EbmlList *list = data_off;
    1267        3832 :                 char *ptr = list->elem;
    1268       37468 :                 for (j = 0; j < list->nb_elem;
    1269       29804 :                      j++, ptr += syntax[i].list_elem_size)
    1270       29804 :                     ebml_free(syntax[i].def.n, ptr);
    1271        3832 :                 av_freep(&list->elem);
    1272        3832 :                 list->nb_elem = 0;
    1273             :             } else
    1274       60915 :                 ebml_free(syntax[i].def.n, data_off);
    1275             :         default:
    1276      257318 :             break;
    1277             :         }
    1278             :     }
    1279       92162 : }
    1280             : 
    1281             : /*
    1282             :  * Autodetecting...
    1283             :  */
    1284        6217 : static int matroska_probe(AVProbeData *p)
    1285             : {
    1286        6217 :     uint64_t total = 0;
    1287        6217 :     int len_mask = 0x80, size = 1, n = 1, i;
    1288             : 
    1289             :     /* EBML header? */
    1290        6217 :     if (AV_RB32(p->buf) != EBML_ID_HEADER)
    1291        5935 :         return 0;
    1292             : 
    1293             :     /* length of header */
    1294         282 :     total = p->buf[4];
    1295        2363 :     while (size <= 8 && !(total & len_mask)) {
    1296        1799 :         size++;
    1297        1799 :         len_mask >>= 1;
    1298             :     }
    1299         282 :     if (size > 8)
    1300           0 :         return 0;
    1301         282 :     total &= (len_mask - 1);
    1302        2363 :     while (n < size)
    1303        1799 :         total = (total << 8) | p->buf[4 + n++];
    1304             : 
    1305             :     /* Does the probe data contain the whole header? */
    1306         282 :     if (p->buf_size < 4 + size + total)
    1307           0 :         return 0;
    1308             : 
    1309             :     /* The header should contain a known document type. For now,
    1310             :      * we don't parse the whole header but simply check for the
    1311             :      * availability of that array of characters inside the header.
    1312             :      * Not fully fool-proof, but good enough. */
    1313         524 :     for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++) {
    1314         524 :         size_t probelen = strlen(matroska_doctypes[i]);
    1315         524 :         if (total < probelen)
    1316           0 :             continue;
    1317       11680 :         for (n = 4 + size; n <= 4 + size + total - probelen; n++)
    1318       11438 :             if (!memcmp(p->buf + n, matroska_doctypes[i], probelen))
    1319         282 :                 return AVPROBE_SCORE_MAX;
    1320             :     }
    1321             : 
    1322             :     // probably valid EBML header but no recognized doctype
    1323           0 :     return AVPROBE_SCORE_EXTENSION;
    1324             : }
    1325             : 
    1326       28309 : static MatroskaTrack *matroska_find_track_by_num(MatroskaDemuxContext *matroska,
    1327             :                                                  int num)
    1328             : {
    1329       28309 :     MatroskaTrack *tracks = matroska->tracks.elem;
    1330             :     int i;
    1331             : 
    1332       29867 :     for (i = 0; i < matroska->tracks.nb_elem; i++)
    1333       29866 :         if (tracks[i].num == num)
    1334       28308 :             return &tracks[i];
    1335             : 
    1336           1 :     av_log(matroska->ctx, AV_LOG_ERROR, "Invalid track number %d\n", num);
    1337           1 :     return NULL;
    1338             : }
    1339             : 
    1340           0 : static int matroska_decode_buffer(uint8_t **buf, int *buf_size,
    1341             :                                   MatroskaTrack *track)
    1342             : {
    1343           0 :     MatroskaTrackEncoding *encodings = track->encodings.elem;
    1344           0 :     uint8_t *data = *buf;
    1345           0 :     int isize = *buf_size;
    1346           0 :     uint8_t *pkt_data = NULL;
    1347             :     uint8_t av_unused *newpktdata;
    1348           0 :     int pkt_size = isize;
    1349           0 :     int result = 0;
    1350             :     int olen;
    1351             : 
    1352           0 :     if (pkt_size >= 10000000U)
    1353           0 :         return AVERROR_INVALIDDATA;
    1354             : 
    1355           0 :     switch (encodings[0].compression.algo) {
    1356           0 :     case MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP:
    1357             :     {
    1358           0 :         int header_size = encodings[0].compression.settings.size;
    1359           0 :         uint8_t *header = encodings[0].compression.settings.data;
    1360             : 
    1361           0 :         if (header_size && !header) {
    1362           0 :             av_log(NULL, AV_LOG_ERROR, "Compression size but no data in headerstrip\n");
    1363           0 :             return -1;
    1364             :         }
    1365             : 
    1366           0 :         if (!header_size)
    1367           0 :             return 0;
    1368             : 
    1369           0 :         pkt_size = isize + header_size;
    1370           0 :         pkt_data = av_malloc(pkt_size + AV_INPUT_BUFFER_PADDING_SIZE);
    1371           0 :         if (!pkt_data)
    1372           0 :             return AVERROR(ENOMEM);
    1373             : 
    1374           0 :         memcpy(pkt_data, header, header_size);
    1375           0 :         memcpy(pkt_data + header_size, data, isize);
    1376           0 :         break;
    1377             :     }
    1378             : #if CONFIG_LZO
    1379           0 :     case MATROSKA_TRACK_ENCODING_COMP_LZO:
    1380             :         do {
    1381           0 :             olen       = pkt_size *= 3;
    1382           0 :             newpktdata = av_realloc(pkt_data, pkt_size + AV_LZO_OUTPUT_PADDING
    1383           0 :                                                        + AV_INPUT_BUFFER_PADDING_SIZE);
    1384           0 :             if (!newpktdata) {
    1385           0 :                 result = AVERROR(ENOMEM);
    1386           0 :                 goto failed;
    1387             :             }
    1388           0 :             pkt_data = newpktdata;
    1389           0 :             result   = av_lzo1x_decode(pkt_data, &olen, data, &isize);
    1390           0 :         } while (result == AV_LZO_OUTPUT_FULL && pkt_size < 10000000);
    1391           0 :         if (result) {
    1392           0 :             result = AVERROR_INVALIDDATA;
    1393           0 :             goto failed;
    1394             :         }
    1395           0 :         pkt_size -= olen;
    1396           0 :         break;
    1397             : #endif
    1398             : #if CONFIG_ZLIB
    1399           0 :     case MATROSKA_TRACK_ENCODING_COMP_ZLIB:
    1400             :     {
    1401           0 :         z_stream zstream = { 0 };
    1402           0 :         if (inflateInit(&zstream) != Z_OK)
    1403           0 :             return -1;
    1404           0 :         zstream.next_in  = data;
    1405           0 :         zstream.avail_in = isize;
    1406             :         do {
    1407           0 :             pkt_size  *= 3;
    1408           0 :             newpktdata = av_realloc(pkt_data, pkt_size + AV_INPUT_BUFFER_PADDING_SIZE);
    1409           0 :             if (!newpktdata) {
    1410           0 :                 inflateEnd(&zstream);
    1411           0 :                 result = AVERROR(ENOMEM);
    1412           0 :                 goto failed;
    1413             :             }
    1414           0 :             pkt_data          = newpktdata;
    1415           0 :             zstream.avail_out = pkt_size - zstream.total_out;
    1416           0 :             zstream.next_out  = pkt_data + zstream.total_out;
    1417           0 :             result = inflate(&zstream, Z_NO_FLUSH);
    1418           0 :         } while (result == Z_OK && pkt_size < 10000000);
    1419           0 :         pkt_size = zstream.total_out;
    1420           0 :         inflateEnd(&zstream);
    1421           0 :         if (result != Z_STREAM_END) {
    1422           0 :             if (result == Z_MEM_ERROR)
    1423           0 :                 result = AVERROR(ENOMEM);
    1424             :             else
    1425           0 :                 result = AVERROR_INVALIDDATA;
    1426           0 :             goto failed;
    1427             :         }
    1428           0 :         break;
    1429             :     }
    1430             : #endif
    1431             : #if CONFIG_BZLIB
    1432           0 :     case MATROSKA_TRACK_ENCODING_COMP_BZLIB:
    1433             :     {
    1434           0 :         bz_stream bzstream = { 0 };
    1435           0 :         if (BZ2_bzDecompressInit(&bzstream, 0, 0) != BZ_OK)
    1436           0 :             return -1;
    1437           0 :         bzstream.next_in  = data;
    1438           0 :         bzstream.avail_in = isize;
    1439             :         do {
    1440           0 :             pkt_size  *= 3;
    1441           0 :             newpktdata = av_realloc(pkt_data, pkt_size + AV_INPUT_BUFFER_PADDING_SIZE);
    1442           0 :             if (!newpktdata) {
    1443           0 :                 BZ2_bzDecompressEnd(&bzstream);
    1444           0 :                 result = AVERROR(ENOMEM);
    1445           0 :                 goto failed;
    1446             :             }
    1447           0 :             pkt_data           = newpktdata;
    1448           0 :             bzstream.avail_out = pkt_size - bzstream.total_out_lo32;
    1449           0 :             bzstream.next_out  = pkt_data + bzstream.total_out_lo32;
    1450           0 :             result = BZ2_bzDecompress(&bzstream);
    1451           0 :         } while (result == BZ_OK && pkt_size < 10000000);
    1452           0 :         pkt_size = bzstream.total_out_lo32;
    1453           0 :         BZ2_bzDecompressEnd(&bzstream);
    1454           0 :         if (result != BZ_STREAM_END) {
    1455           0 :             if (result == BZ_MEM_ERROR)
    1456           0 :                 result = AVERROR(ENOMEM);
    1457             :             else
    1458           0 :                 result = AVERROR_INVALIDDATA;
    1459           0 :             goto failed;
    1460             :         }
    1461           0 :         break;
    1462             :     }
    1463             : #endif
    1464           0 :     default:
    1465           0 :         return AVERROR_INVALIDDATA;
    1466             :     }
    1467             : 
    1468           0 :     memset(pkt_data + pkt_size, 0, AV_INPUT_BUFFER_PADDING_SIZE);
    1469             : 
    1470           0 :     *buf      = pkt_data;
    1471           0 :     *buf_size = pkt_size;
    1472           0 :     return 0;
    1473             : 
    1474           0 : failed:
    1475           0 :     av_free(pkt_data);
    1476           0 :     return result;
    1477             : }
    1478             : 
    1479          58 : static void matroska_convert_tag(AVFormatContext *s, EbmlList *list,
    1480             :                                  AVDictionary **metadata, char *prefix)
    1481             : {
    1482          58 :     MatroskaTag *tags = list->elem;
    1483             :     char key[1024];
    1484             :     int i;
    1485             : 
    1486         140 :     for (i = 0; i < list->nb_elem; i++) {
    1487         246 :         const char *lang = tags[i].lang &&
    1488          82 :                            strcmp(tags[i].lang, "und") ? tags[i].lang : NULL;
    1489             : 
    1490          82 :         if (!tags[i].name) {
    1491           0 :             av_log(s, AV_LOG_WARNING, "Skipping invalid tag with no TagName.\n");
    1492           0 :             continue;
    1493             :         }
    1494          82 :         if (prefix)
    1495           0 :             snprintf(key, sizeof(key), "%s/%s", prefix, tags[i].name);
    1496             :         else
    1497          82 :             av_strlcpy(key, tags[i].name, sizeof(key));
    1498          82 :         if (tags[i].def || !lang) {
    1499          82 :             av_dict_set(metadata, key, tags[i].string, 0);
    1500          82 :             if (tags[i].sub.nb_elem)
    1501           0 :                 matroska_convert_tag(s, &tags[i].sub, metadata, key);
    1502             :         }
    1503          82 :         if (lang) {
    1504           0 :             av_strlcat(key, "-", sizeof(key));
    1505           0 :             av_strlcat(key, lang, sizeof(key));
    1506           0 :             av_dict_set(metadata, key, tags[i].string, 0);
    1507           0 :             if (tags[i].sub.nb_elem)
    1508           0 :                 matroska_convert_tag(s, &tags[i].sub, metadata, key);
    1509             :         }
    1510             :     }
    1511          58 :     ff_metadata_conv(metadata, NULL, ff_mkv_metadata_conv);
    1512          58 : }
    1513             : 
    1514         296 : static void matroska_convert_tags(AVFormatContext *s)
    1515             : {
    1516         296 :     MatroskaDemuxContext *matroska = s->priv_data;
    1517         296 :     MatroskaTags *tags = matroska->tags.elem;
    1518             :     int i, j;
    1519             : 
    1520         354 :     for (i = 0; i < matroska->tags.nb_elem; i++) {
    1521          58 :         if (tags[i].target.attachuid) {
    1522           0 :             MatroskaAttachment *attachment = matroska->attachments.elem;
    1523           0 :             int found = 0;
    1524           0 :             for (j = 0; j < matroska->attachments.nb_elem; j++) {
    1525           0 :                 if (attachment[j].uid == tags[i].target.attachuid &&
    1526           0 :                     attachment[j].stream) {
    1527           0 :                     matroska_convert_tag(s, &tags[i].tag,
    1528           0 :                                          &attachment[j].stream->metadata, NULL);
    1529           0 :                     found = 1;
    1530             :                 }
    1531             :             }
    1532           0 :             if (!found) {
    1533           0 :                 av_log(NULL, AV_LOG_WARNING,
    1534             :                        "The tags at index %d refer to a "
    1535             :                        "non-existent attachment %"PRId64".\n",
    1536           0 :                        i, tags[i].target.attachuid);
    1537             :             }
    1538          58 :         } else if (tags[i].target.chapteruid) {
    1539           0 :             MatroskaChapter *chapter = matroska->chapters.elem;
    1540           0 :             int found = 0;
    1541           0 :             for (j = 0; j < matroska->chapters.nb_elem; j++) {
    1542           0 :                 if (chapter[j].uid == tags[i].target.chapteruid &&
    1543           0 :                     chapter[j].chapter) {
    1544           0 :                     matroska_convert_tag(s, &tags[i].tag,
    1545           0 :                                          &chapter[j].chapter->metadata, NULL);
    1546           0 :                     found = 1;
    1547             :                 }
    1548             :             }
    1549           0 :             if (!found) {
    1550           0 :                 av_log(NULL, AV_LOG_WARNING,
    1551             :                        "The tags at index %d refer to a non-existent chapter "
    1552             :                        "%"PRId64".\n",
    1553           0 :                        i, tags[i].target.chapteruid);
    1554             :             }
    1555          58 :         } else if (tags[i].target.trackuid) {
    1556          29 :             MatroskaTrack *track = matroska->tracks.elem;
    1557          29 :             int found = 0;
    1558          82 :             for (j = 0; j < matroska->tracks.nb_elem; j++) {
    1559          82 :                 if (track[j].uid == tags[i].target.trackuid &&
    1560          29 :                     track[j].stream) {
    1561          29 :                     matroska_convert_tag(s, &tags[i].tag,
    1562          29 :                                          &track[j].stream->metadata, NULL);
    1563          29 :                     found = 1;
    1564             :                }
    1565             :             }
    1566          29 :             if (!found) {
    1567           0 :                 av_log(NULL, AV_LOG_WARNING,
    1568             :                        "The tags at index %d refer to a non-existent track "
    1569             :                        "%"PRId64".\n",
    1570           0 :                        i, tags[i].target.trackuid);
    1571             :             }
    1572             :         } else {
    1573          29 :             matroska_convert_tag(s, &tags[i].tag, &s->metadata,
    1574          29 :                                  tags[i].target.type);
    1575             :         }
    1576             :     }
    1577         296 : }
    1578             : 
    1579          12 : static int matroska_parse_seekhead_entry(MatroskaDemuxContext *matroska,
    1580             :                                          uint64_t pos)
    1581             : {
    1582          12 :     uint32_t level_up       = matroska->level_up;
    1583          12 :     uint32_t saved_id       = matroska->current_id;
    1584          12 :     int64_t before_pos = avio_tell(matroska->ctx->pb);
    1585             :     MatroskaLevel level;
    1586             :     int64_t offset;
    1587          12 :     int ret = 0;
    1588             : 
    1589             :     /* seek */
    1590          12 :     offset = pos + matroska->segment_start;
    1591          12 :     if (avio_seek(matroska->ctx->pb, offset, SEEK_SET) == offset) {
    1592             :         /* We don't want to lose our seekhead level, so we add
    1593             :          * a dummy. This is a crude hack. */
    1594          12 :         if (matroska->num_levels == EBML_MAX_DEPTH) {
    1595           0 :             av_log(matroska->ctx, AV_LOG_INFO,
    1596             :                    "Max EBML element depth (%d) reached, "
    1597             :                    "cannot parse further.\n", EBML_MAX_DEPTH);
    1598           0 :             ret = AVERROR_INVALIDDATA;
    1599             :         } else {
    1600          12 :             level.start  = 0;
    1601          12 :             level.length = (uint64_t) -1;
    1602          12 :             matroska->levels[matroska->num_levels] = level;
    1603          12 :             matroska->num_levels++;
    1604          12 :             matroska->current_id                   = 0;
    1605             : 
    1606          12 :             ret = ebml_parse(matroska, matroska_segment, matroska);
    1607             : 
    1608             :             /* remove dummy level */
    1609          12 :             while (matroska->num_levels) {
    1610          12 :                 uint64_t length = matroska->levels[--matroska->num_levels].length;
    1611          12 :                 if (length == (uint64_t) -1)
    1612          12 :                     break;
    1613             :             }
    1614             :         }
    1615             :     }
    1616             :     /* seek back */
    1617          12 :     avio_seek(matroska->ctx->pb, before_pos, SEEK_SET);
    1618          12 :     matroska->level_up   = level_up;
    1619          12 :     matroska->current_id = saved_id;
    1620             : 
    1621          12 :     return ret;
    1622             : }
    1623             : 
    1624         296 : static void matroska_execute_seekhead(MatroskaDemuxContext *matroska)
    1625             : {
    1626         296 :     EbmlList *seekhead_list = &matroska->seekhead;
    1627             :     int i;
    1628             : 
    1629             :     // we should not do any seeking in the streaming case
    1630         296 :     if (!(matroska->ctx->pb->seekable & AVIO_SEEKABLE_NORMAL))
    1631           1 :         return;
    1632             : 
    1633        1194 :     for (i = 0; i < seekhead_list->nb_elem; i++) {
    1634         900 :         MatroskaSeekhead *seekheads = seekhead_list->elem;
    1635         900 :         uint32_t id  = seekheads[i].id;
    1636         900 :         uint64_t pos = seekheads[i].pos;
    1637             : 
    1638         900 :         MatroskaLevel1Element *elem = matroska_find_level1_elem(matroska, id);
    1639         900 :         if (!elem || elem->parsed)
    1640         631 :             continue;
    1641             : 
    1642         269 :         elem->pos = pos;
    1643             : 
    1644             :         // defer cues parsing until we actually need cue data.
    1645         269 :         if (id == MATROSKA_ID_CUES)
    1646         268 :             continue;
    1647             : 
    1648           1 :         if (matroska_parse_seekhead_entry(matroska, pos) < 0) {
    1649             :             // mark index as broken
    1650           1 :             matroska->cues_parsing_deferred = -1;
    1651           1 :             break;
    1652             :         }
    1653             : 
    1654           0 :         elem->parsed = 1;
    1655             :     }
    1656             : }
    1657             : 
    1658         308 : static void matroska_add_index_entries(MatroskaDemuxContext *matroska)
    1659             : {
    1660             :     EbmlList *index_list;
    1661             :     MatroskaIndex *index;
    1662         308 :     uint64_t index_scale = 1;
    1663             :     int i, j;
    1664             : 
    1665         308 :     if (matroska->ctx->flags & AVFMT_FLAG_IGNIDX)
    1666           0 :         return;
    1667             : 
    1668         308 :     index_list = &matroska->index;
    1669         308 :     index      = index_list->elem;
    1670         308 :     if (index_list->nb_elem < 2)
    1671         296 :         return;
    1672          12 :     if (index[1].time > 1E14 / matroska->time_scale) {
    1673           0 :         av_log(matroska->ctx, AV_LOG_WARNING, "Dropping apparently-broken index.\n");
    1674           0 :         return;
    1675             :     }
    1676         153 :     for (i = 0; i < index_list->nb_elem; i++) {
    1677         141 :         EbmlList *pos_list    = &index[i].pos;
    1678         141 :         MatroskaIndexPos *pos = pos_list->elem;
    1679         282 :         for (j = 0; j < pos_list->nb_elem; j++) {
    1680         141 :             MatroskaTrack *track = matroska_find_track_by_num(matroska,
    1681         141 :                                                               pos[j].track);
    1682         141 :             if (track && track->stream)
    1683         282 :                 av_add_index_entry(track->stream,
    1684         141 :                                    pos[j].pos + matroska->segment_start,
    1685         141 :                                    index[i].time / index_scale, 0, 0,
    1686             :                                    AVINDEX_KEYFRAME);
    1687             :         }
    1688             :     }
    1689             : }
    1690             : 
    1691          12 : static void matroska_parse_cues(MatroskaDemuxContext *matroska) {
    1692             :     int i;
    1693             : 
    1694          12 :     if (matroska->ctx->flags & AVFMT_FLAG_IGNIDX)
    1695           0 :         return;
    1696             : 
    1697          50 :     for (i = 0; i < matroska->num_level1_elems; i++) {
    1698          49 :         MatroskaLevel1Element *elem = &matroska->level1_elems[i];
    1699          49 :         if (elem->id == MATROSKA_ID_CUES && !elem->parsed) {
    1700          11 :             if (matroska_parse_seekhead_entry(matroska, elem->pos) < 0)
    1701           0 :                 matroska->cues_parsing_deferred = -1;
    1702          11 :             elem->parsed = 1;
    1703          11 :             break;
    1704             :         }
    1705             :     }
    1706             : 
    1707          12 :     matroska_add_index_entries(matroska);
    1708             : }
    1709             : 
    1710           0 : static int matroska_aac_profile(char *codec_id)
    1711             : {
    1712             :     static const char *const aac_profiles[] = { "MAIN", "LC", "SSR" };
    1713             :     int profile;
    1714             : 
    1715           0 :     for (profile = 0; profile < FF_ARRAY_ELEMS(aac_profiles); profile++)
    1716           0 :         if (strstr(codec_id, aac_profiles[profile]))
    1717           0 :             break;
    1718           0 :     return profile + 1;
    1719             : }
    1720             : 
    1721           0 : static int matroska_aac_sri(int samplerate)
    1722             : {
    1723             :     int sri;
    1724             : 
    1725           0 :     for (sri = 0; sri < FF_ARRAY_ELEMS(avpriv_mpeg4audio_sample_rates); sri++)
    1726           0 :         if (avpriv_mpeg4audio_sample_rates[sri] == samplerate)
    1727           0 :             break;
    1728           0 :     return sri;
    1729             : }
    1730             : 
    1731           5 : static void matroska_metadata_creation_time(AVDictionary **metadata, int64_t date_utc)
    1732             : {
    1733             :     /* Convert to seconds and adjust by number of seconds between 2001-01-01 and Epoch */
    1734           5 :     avpriv_dict_set_timestamp(metadata, "creation_time", date_utc / 1000 + 978307200000000LL);
    1735           5 : }
    1736             : 
    1737           0 : static int matroska_parse_flac(AVFormatContext *s,
    1738             :                                MatroskaTrack *track,
    1739             :                                int *offset)
    1740             : {
    1741           0 :     AVStream *st = track->stream;
    1742           0 :     uint8_t *p = track->codec_priv.data;
    1743           0 :     int size   = track->codec_priv.size;
    1744             : 
    1745           0 :     if (size < 8 + FLAC_STREAMINFO_SIZE || p[4] & 0x7f) {
    1746           0 :         av_log(s, AV_LOG_WARNING, "Invalid FLAC private data\n");
    1747           0 :         track->codec_priv.size = 0;
    1748           0 :         return 0;
    1749             :     }
    1750           0 :     *offset = 8;
    1751           0 :     track->codec_priv.size = 8 + FLAC_STREAMINFO_SIZE;
    1752             : 
    1753           0 :     p    += track->codec_priv.size;
    1754           0 :     size -= track->codec_priv.size;
    1755             : 
    1756             :     /* parse the remaining metadata blocks if present */
    1757           0 :     while (size >= 4) {
    1758             :         int block_last, block_type, block_size;
    1759             : 
    1760           0 :         flac_parse_block_header(p, &block_last, &block_type, &block_size);
    1761             : 
    1762           0 :         p    += 4;
    1763           0 :         size -= 4;
    1764           0 :         if (block_size > size)
    1765           0 :             return 0;
    1766             : 
    1767             :         /* check for the channel mask */
    1768           0 :         if (block_type == FLAC_METADATA_TYPE_VORBIS_COMMENT) {
    1769           0 :             AVDictionary *dict = NULL;
    1770             :             AVDictionaryEntry *chmask;
    1771             : 
    1772           0 :             ff_vorbis_comment(s, &dict, p, block_size, 0);
    1773           0 :             chmask = av_dict_get(dict, "WAVEFORMATEXTENSIBLE_CHANNEL_MASK", NULL, 0);
    1774           0 :             if (chmask) {
    1775           0 :                 uint64_t mask = strtol(chmask->value, NULL, 0);
    1776           0 :                 if (!mask || mask & ~0x3ffffULL) {
    1777           0 :                     av_log(s, AV_LOG_WARNING,
    1778             :                            "Invalid value of WAVEFORMATEXTENSIBLE_CHANNEL_MASK\n");
    1779             :                 } else
    1780           0 :                     st->codecpar->channel_layout = mask;
    1781             :             }
    1782           0 :             av_dict_free(&dict);
    1783             :         }
    1784             : 
    1785           0 :         p    += block_size;
    1786           0 :         size -= block_size;
    1787             :     }
    1788             : 
    1789           0 :     return 0;
    1790             : }
    1791             : 
    1792           0 : static int mkv_field_order(MatroskaDemuxContext *matroska, int64_t field_order)
    1793             : {
    1794           0 :     int major, minor, micro, bttb = 0;
    1795             : 
    1796             :     /* workaround a bug in our Matroska muxer, introduced in version 57.36 alongside
    1797             :      * this function, and fixed in 57.52 */
    1798           0 :     if (matroska->muxingapp && sscanf(matroska->muxingapp, "Lavf%d.%d.%d", &major, &minor, &micro) == 3)
    1799           0 :         bttb = (major == 57 && minor >= 36 && minor <= 51 && micro >= 100);
    1800             : 
    1801           0 :     switch (field_order) {
    1802           0 :     case MATROSKA_VIDEO_FIELDORDER_PROGRESSIVE:
    1803           0 :         return AV_FIELD_PROGRESSIVE;
    1804           0 :     case MATROSKA_VIDEO_FIELDORDER_UNDETERMINED:
    1805           0 :         return AV_FIELD_UNKNOWN;
    1806           0 :     case MATROSKA_VIDEO_FIELDORDER_TT:
    1807           0 :         return AV_FIELD_TT;
    1808           0 :     case MATROSKA_VIDEO_FIELDORDER_BB:
    1809           0 :         return AV_FIELD_BB;
    1810           0 :     case MATROSKA_VIDEO_FIELDORDER_BT:
    1811           0 :         return bttb ? AV_FIELD_TB : AV_FIELD_BT;
    1812           0 :     case MATROSKA_VIDEO_FIELDORDER_TB:
    1813           0 :         return bttb ? AV_FIELD_BT : AV_FIELD_TB;
    1814           0 :     default:
    1815           0 :         return AV_FIELD_UNKNOWN;
    1816             :     }
    1817             : }
    1818             : 
    1819           0 : static void mkv_stereo_mode_display_mul(int stereo_mode,
    1820             :                                         int *h_width, int *h_height)
    1821             : {
    1822           0 :     switch (stereo_mode) {
    1823           0 :         case MATROSKA_VIDEO_STEREOMODE_TYPE_MONO:
    1824             :         case MATROSKA_VIDEO_STEREOMODE_TYPE_CHECKERBOARD_RL:
    1825             :         case MATROSKA_VIDEO_STEREOMODE_TYPE_CHECKERBOARD_LR:
    1826             :         case MATROSKA_VIDEO_STEREOMODE_TYPE_BOTH_EYES_BLOCK_RL:
    1827             :         case MATROSKA_VIDEO_STEREOMODE_TYPE_BOTH_EYES_BLOCK_LR:
    1828           0 :             break;
    1829           0 :         case MATROSKA_VIDEO_STEREOMODE_TYPE_RIGHT_LEFT:
    1830             :         case MATROSKA_VIDEO_STEREOMODE_TYPE_LEFT_RIGHT:
    1831             :         case MATROSKA_VIDEO_STEREOMODE_TYPE_COL_INTERLEAVED_RL:
    1832             :         case MATROSKA_VIDEO_STEREOMODE_TYPE_COL_INTERLEAVED_LR:
    1833           0 :             *h_width = 2;
    1834           0 :             break;
    1835           0 :         case MATROSKA_VIDEO_STEREOMODE_TYPE_BOTTOM_TOP:
    1836             :         case MATROSKA_VIDEO_STEREOMODE_TYPE_TOP_BOTTOM:
    1837             :         case MATROSKA_VIDEO_STEREOMODE_TYPE_ROW_INTERLEAVED_RL:
    1838             :         case MATROSKA_VIDEO_STEREOMODE_TYPE_ROW_INTERLEAVED_LR:
    1839           0 :             *h_height = 2;
    1840           0 :             break;
    1841             :     }
    1842           0 : }
    1843             : 
    1844         268 : static int mkv_parse_video_color(AVStream *st, const MatroskaTrack *track) {
    1845         268 :     const MatroskaTrackVideoColor *color = track->video.color.elem;
    1846             :     const MatroskaMasteringMeta *mastering_meta;
    1847             :     int has_mastering_primaries, has_mastering_luminance;
    1848             : 
    1849         268 :     if (!track->video.color.nb_elem)
    1850         267 :         return 0;
    1851             : 
    1852           1 :     mastering_meta = &color->mastering_meta;
    1853             :     // Mastering primaries are CIE 1931 coords, and must be > 0.
    1854           1 :     has_mastering_primaries =
    1855           1 :         mastering_meta->r_x > 0 && mastering_meta->r_y > 0 &&
    1856           0 :         mastering_meta->g_x > 0 && mastering_meta->g_y > 0 &&
    1857           0 :         mastering_meta->b_x > 0 && mastering_meta->b_y > 0 &&
    1858           1 :         mastering_meta->white_x > 0 && mastering_meta->white_y > 0;
    1859           1 :     has_mastering_luminance = mastering_meta->max_luminance > 0;
    1860             : 
    1861           1 :     if (color->matrix_coefficients != AVCOL_SPC_RESERVED)
    1862           1 :         st->codecpar->color_space = color->matrix_coefficients;
    1863           2 :     if (color->primaries != AVCOL_PRI_RESERVED &&
    1864           1 :         color->primaries != AVCOL_PRI_RESERVED0)
    1865           1 :         st->codecpar->color_primaries = color->primaries;
    1866           2 :     if (color->transfer_characteristics != AVCOL_TRC_RESERVED &&
    1867           1 :         color->transfer_characteristics != AVCOL_TRC_RESERVED0)
    1868           1 :         st->codecpar->color_trc = color->transfer_characteristics;
    1869           1 :     if (color->range != AVCOL_RANGE_UNSPECIFIED &&
    1870           0 :         color->range <= AVCOL_RANGE_JPEG)
    1871           0 :         st->codecpar->color_range = color->range;
    1872           2 :     if (color->chroma_siting_horz != MATROSKA_COLOUR_CHROMASITINGHORZ_UNDETERMINED &&
    1873           2 :         color->chroma_siting_vert != MATROSKA_COLOUR_CHROMASITINGVERT_UNDETERMINED &&
    1874           2 :         color->chroma_siting_horz  < MATROSKA_COLOUR_CHROMASITINGHORZ_NB &&
    1875           1 :         color->chroma_siting_vert  < MATROSKA_COLOUR_CHROMASITINGVERT_NB) {
    1876           2 :         st->codecpar->chroma_location =
    1877           2 :             avcodec_chroma_pos_to_enum((color->chroma_siting_horz - 1) << 7,
    1878           1 :                                        (color->chroma_siting_vert - 1) << 7);
    1879             :     }
    1880           1 :     if (color->max_cll && color->max_fall) {
    1881           0 :         size_t size = 0;
    1882             :         int ret;
    1883           0 :         AVContentLightMetadata *metadata = av_content_light_metadata_alloc(&size);
    1884           0 :         if (!metadata)
    1885           0 :             return AVERROR(ENOMEM);
    1886           0 :         ret = av_stream_add_side_data(st, AV_PKT_DATA_CONTENT_LIGHT_LEVEL,
    1887             :                                       (uint8_t *)metadata, size);
    1888           0 :         if (ret < 0) {
    1889           0 :             av_freep(&metadata);
    1890           0 :             return ret;
    1891             :         }
    1892           0 :         metadata->MaxCLL  = color->max_cll;
    1893           0 :         metadata->MaxFALL = color->max_fall;
    1894             :     }
    1895             : 
    1896           1 :     if (has_mastering_primaries || has_mastering_luminance) {
    1897             :         // Use similar rationals as other standards.
    1898           0 :         const int chroma_den = 50000;
    1899           0 :         const int luma_den = 10000;
    1900           0 :         AVMasteringDisplayMetadata *metadata =
    1901             :             (AVMasteringDisplayMetadata*) av_stream_new_side_data(
    1902             :                 st, AV_PKT_DATA_MASTERING_DISPLAY_METADATA,
    1903             :                 sizeof(AVMasteringDisplayMetadata));
    1904           0 :         if (!metadata) {
    1905           0 :             return AVERROR(ENOMEM);
    1906             :         }
    1907           0 :         memset(metadata, 0, sizeof(AVMasteringDisplayMetadata));
    1908           0 :         if (has_mastering_primaries) {
    1909           0 :             metadata->display_primaries[0][0] = av_make_q(
    1910           0 :                 round(mastering_meta->r_x * chroma_den), chroma_den);
    1911           0 :             metadata->display_primaries[0][1] = av_make_q(
    1912           0 :                 round(mastering_meta->r_y * chroma_den), chroma_den);
    1913           0 :             metadata->display_primaries[1][0] = av_make_q(
    1914           0 :                 round(mastering_meta->g_x * chroma_den), chroma_den);
    1915           0 :             metadata->display_primaries[1][1] = av_make_q(
    1916           0 :                 round(mastering_meta->g_y * chroma_den), chroma_den);
    1917           0 :             metadata->display_primaries[2][0] = av_make_q(
    1918           0 :                 round(mastering_meta->b_x * chroma_den), chroma_den);
    1919           0 :             metadata->display_primaries[2][1] = av_make_q(
    1920           0 :                 round(mastering_meta->b_y * chroma_den), chroma_den);
    1921           0 :             metadata->white_point[0] = av_make_q(
    1922           0 :                 round(mastering_meta->white_x * chroma_den), chroma_den);
    1923           0 :             metadata->white_point[1] = av_make_q(
    1924           0 :                 round(mastering_meta->white_y * chroma_den), chroma_den);
    1925           0 :             metadata->has_primaries = 1;
    1926             :         }
    1927           0 :         if (has_mastering_luminance) {
    1928           0 :             metadata->max_luminance = av_make_q(
    1929           0 :                 round(mastering_meta->max_luminance * luma_den), luma_den);
    1930           0 :             metadata->min_luminance = av_make_q(
    1931           0 :                 round(mastering_meta->min_luminance * luma_den), luma_den);
    1932           0 :             metadata->has_luminance = 1;
    1933             :         }
    1934             :     }
    1935           1 :     return 0;
    1936             : }
    1937             : 
    1938         268 : static int mkv_parse_video_projection(AVStream *st, const MatroskaTrack *track) {
    1939             :     AVSphericalMapping *spherical;
    1940             :     enum AVSphericalProjection projection;
    1941             :     size_t spherical_size;
    1942         268 :     uint32_t l = 0, t = 0, r = 0, b = 0;
    1943         268 :     uint32_t padding = 0;
    1944             :     int ret;
    1945             :     GetByteContext gb;
    1946             : 
    1947         268 :     bytestream2_init(&gb, track->video.projection.private.data,
    1948             :                      track->video.projection.private.size);
    1949             : 
    1950         268 :     if (bytestream2_get_byte(&gb) != 0) {
    1951           0 :         av_log(NULL, AV_LOG_WARNING, "Unknown spherical metadata\n");
    1952           0 :         return 0;
    1953             :     }
    1954             : 
    1955         268 :     bytestream2_skip(&gb, 3); // flags
    1956             : 
    1957         268 :     switch (track->video.projection.type) {
    1958           1 :     case MATROSKA_VIDEO_PROJECTION_TYPE_EQUIRECTANGULAR:
    1959           1 :         if (track->video.projection.private.size == 20) {
    1960           1 :             t = bytestream2_get_be32(&gb);
    1961           1 :             b = bytestream2_get_be32(&gb);
    1962           1 :             l = bytestream2_get_be32(&gb);
    1963           1 :             r = bytestream2_get_be32(&gb);
    1964             : 
    1965           1 :             if (b >= UINT_MAX - t || r >= UINT_MAX - l) {
    1966           0 :                 av_log(NULL, AV_LOG_ERROR,
    1967             :                        "Invalid bounding rectangle coordinates "
    1968             :                        "%"PRIu32",%"PRIu32",%"PRIu32",%"PRIu32"\n",
    1969             :                        l, t, r, b);
    1970           0 :                 return AVERROR_INVALIDDATA;
    1971             :             }
    1972           0 :         } else if (track->video.projection.private.size != 0) {
    1973           0 :             av_log(NULL, AV_LOG_ERROR, "Unknown spherical metadata\n");
    1974           0 :             return AVERROR_INVALIDDATA;
    1975             :         }
    1976             : 
    1977           1 :         if (l || t || r || b)
    1978           1 :             projection = AV_SPHERICAL_EQUIRECTANGULAR_TILE;
    1979             :         else
    1980           0 :             projection = AV_SPHERICAL_EQUIRECTANGULAR;
    1981           1 :         break;
    1982           0 :     case MATROSKA_VIDEO_PROJECTION_TYPE_CUBEMAP:
    1983           0 :         if (track->video.projection.private.size < 4) {
    1984           0 :             av_log(NULL, AV_LOG_ERROR, "Missing projection private properties\n");
    1985           0 :             return AVERROR_INVALIDDATA;
    1986           0 :         } else if (track->video.projection.private.size == 12) {
    1987           0 :             uint32_t layout = bytestream2_get_be32(&gb);
    1988           0 :             if (layout) {
    1989           0 :                 av_log(NULL, AV_LOG_WARNING,
    1990             :                        "Unknown spherical cubemap layout %"PRIu32"\n", layout);
    1991           0 :                 return 0;
    1992             :             }
    1993           0 :             projection = AV_SPHERICAL_CUBEMAP;
    1994           0 :             padding = bytestream2_get_be32(&gb);
    1995             :         } else {
    1996           0 :             av_log(NULL, AV_LOG_ERROR, "Unknown spherical metadata\n");
    1997           0 :             return AVERROR_INVALIDDATA;
    1998             :         }
    1999           0 :         break;
    2000         267 :     case MATROSKA_VIDEO_PROJECTION_TYPE_RECTANGULAR:
    2001             :         /* No Spherical metadata */
    2002         267 :         return 0;
    2003           0 :     default:
    2004           0 :         av_log(NULL, AV_LOG_WARNING,
    2005             :                "Unknown spherical metadata type %"PRIu64"\n",
    2006             :                track->video.projection.type);
    2007           0 :         return 0;
    2008             :     }
    2009             : 
    2010           1 :     spherical = av_spherical_alloc(&spherical_size);
    2011           1 :     if (!spherical)
    2012           0 :         return AVERROR(ENOMEM);
    2013             : 
    2014           1 :     spherical->projection = projection;
    2015             : 
    2016           1 :     spherical->yaw   = (int32_t) (track->video.projection.yaw   * (1 << 16));
    2017           1 :     spherical->pitch = (int32_t) (track->video.projection.pitch * (1 << 16));
    2018           1 :     spherical->roll  = (int32_t) (track->video.projection.roll  * (1 << 16));
    2019             : 
    2020           1 :     spherical->padding = padding;
    2021             : 
    2022           1 :     spherical->bound_left   = l;
    2023           1 :     spherical->bound_top    = t;
    2024           1 :     spherical->bound_right  = r;
    2025           1 :     spherical->bound_bottom = b;
    2026             : 
    2027           1 :     ret = av_stream_add_side_data(st, AV_PKT_DATA_SPHERICAL, (uint8_t *)spherical,
    2028             :                                   spherical_size);
    2029           1 :     if (ret < 0) {
    2030           0 :         av_freep(&spherical);
    2031           0 :         return ret;
    2032             :     }
    2033             : 
    2034           1 :     return 0;
    2035             : }
    2036             : 
    2037           0 : static int get_qt_codec(MatroskaTrack *track, uint32_t *fourcc, enum AVCodecID *codec_id)
    2038             : {
    2039             :     const AVCodecTag *codec_tags;
    2040             : 
    2041           0 :     codec_tags = track->type == MATROSKA_TRACK_TYPE_VIDEO ?
    2042           0 :             ff_codec_movvideo_tags : ff_codec_movaudio_tags;
    2043             : 
    2044             :     /* Normalize noncompliant private data that starts with the fourcc
    2045             :      * by expanding/shifting the data by 4 bytes and storing the data
    2046             :      * size at the start. */
    2047           0 :     if (ff_codec_get_id(codec_tags, AV_RL32(track->codec_priv.data))) {
    2048           0 :         int ret = av_buffer_realloc(&track->codec_priv.buf,
    2049           0 :                                     track->codec_priv.size + 4 + AV_INPUT_BUFFER_PADDING_SIZE);
    2050           0 :         if (ret < 0)
    2051           0 :             return ret;
    2052             : 
    2053           0 :         track->codec_priv.data = track->codec_priv.buf->data;
    2054           0 :         memmove(track->codec_priv.data + 4, track->codec_priv.data, track->codec_priv.size);
    2055           0 :         track->codec_priv.size += 4;
    2056           0 :         AV_WB32(track->codec_priv.data, track->codec_priv.size);
    2057             :     }
    2058             : 
    2059           0 :     *fourcc = AV_RL32(track->codec_priv.data + 4);
    2060           0 :     *codec_id = ff_codec_get_id(codec_tags, *fourcc);
    2061             : 
    2062           0 :     return 0;
    2063             : }
    2064             : 
    2065         296 : static int matroska_parse_tracks(AVFormatContext *s)
    2066             : {
    2067         296 :     MatroskaDemuxContext *matroska = s->priv_data;
    2068         296 :     MatroskaTrack *tracks = matroska->tracks.elem;
    2069             :     AVStream *st;
    2070             :     int i, j, ret;
    2071             :     int k;
    2072             : 
    2073         604 :     for (i = 0; i < matroska->tracks.nb_elem; i++) {
    2074         308 :         MatroskaTrack *track = &tracks[i];
    2075         308 :         enum AVCodecID codec_id = AV_CODEC_ID_NONE;
    2076         308 :         EbmlList *encodings_list = &track->encodings;
    2077         308 :         MatroskaTrackEncoding *encodings = encodings_list->elem;
    2078         308 :         uint8_t *extradata = NULL;
    2079         308 :         int extradata_size = 0;
    2080         308 :         int extradata_offset = 0;
    2081         308 :         uint32_t fourcc = 0;
    2082             :         AVIOContext b;
    2083         308 :         char* key_id_base64 = NULL;
    2084         308 :         int bit_depth = -1;
    2085             : 
    2086             :         /* Apply some sanity checks. */
    2087         348 :         if (track->type != MATROSKA_TRACK_TYPE_VIDEO &&
    2088          43 :             track->type != MATROSKA_TRACK_TYPE_AUDIO &&
    2089           3 :             track->type != MATROSKA_TRACK_TYPE_SUBTITLE &&
    2090           0 :             track->type != MATROSKA_TRACK_TYPE_METADATA) {
    2091           0 :             av_log(matroska->ctx, AV_LOG_INFO,
    2092             :                    "Unknown or unsupported track type %"PRIu64"\n",
    2093             :                    track->type);
    2094           0 :             continue;
    2095             :         }
    2096         308 :         if (!track->codec_id)
    2097           0 :             continue;
    2098             : 
    2099         616 :         if (track->audio.samplerate < 0 || track->audio.samplerate > INT_MAX ||
    2100         308 :             isnan(track->audio.samplerate)) {
    2101           0 :             av_log(matroska->ctx, AV_LOG_WARNING,
    2102             :                    "Invalid sample rate %f, defaulting to 8000 instead.\n",
    2103             :                    track->audio.samplerate);
    2104           0 :             track->audio.samplerate = 8000;
    2105             :         }
    2106             : 
    2107         308 :         if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
    2108         268 :             if (!track->default_duration && track->video.frame_rate > 0) {
    2109         204 :                 double default_duration = 1000000000 / track->video.frame_rate;
    2110         204 :                 if (default_duration > UINT64_MAX || default_duration < 0) {
    2111           0 :                     av_log(matroska->ctx, AV_LOG_WARNING,
    2112             :                          "Invalid frame rate %e. Cannot calculate default duration.\n",
    2113             :                          track->video.frame_rate);
    2114             :                 } else {
    2115         204 :                     track->default_duration = default_duration;
    2116             :                 }
    2117             :             }
    2118         268 :             if (track->video.display_width == -1)
    2119         248 :                 track->video.display_width = track->video.pixel_width;
    2120         268 :             if (track->video.display_height == -1)
    2121         248 :                 track->video.display_height = track->video.pixel_height;
    2122         268 :             if (track->video.color_space.size == 4)
    2123           1 :                 fourcc = AV_RL32(track->video.color_space.data);
    2124          40 :         } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
    2125          37 :             if (!track->audio.out_samplerate)
    2126          36 :                 track->audio.out_samplerate = track->audio.samplerate;
    2127             :         }
    2128         308 :         if (encodings_list->nb_elem > 1) {
    2129           0 :             av_log(matroska->ctx, AV_LOG_ERROR,
    2130             :                    "Multiple combined encodings not supported");
    2131         308 :         } else if (encodings_list->nb_elem == 1) {
    2132           0 :             if (encodings[0].type) {
    2133           0 :                 if (encodings[0].encryption.key_id.size > 0) {
    2134             :                     /* Save the encryption key id to be stored later as a
    2135             :                        metadata tag. */
    2136           0 :                     const int b64_size = AV_BASE64_SIZE(encodings[0].encryption.key_id.size);
    2137           0 :                     key_id_base64 = av_malloc(b64_size);
    2138           0 :                     if (key_id_base64 == NULL)
    2139           0 :                         return AVERROR(ENOMEM);
    2140             : 
    2141           0 :                     av_base64_encode(key_id_base64, b64_size,
    2142           0 :                                      encodings[0].encryption.key_id.data,
    2143             :                                      encodings[0].encryption.key_id.size);
    2144             :                 } else {
    2145           0 :                     encodings[0].scope = 0;
    2146           0 :                     av_log(matroska->ctx, AV_LOG_ERROR,
    2147             :                            "Unsupported encoding type");
    2148             :                 }
    2149           0 :             } else if (
    2150             : #if CONFIG_ZLIB
    2151           0 :                  encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_ZLIB  &&
    2152             : #endif
    2153             : #if CONFIG_BZLIB
    2154           0 :                  encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_BZLIB &&
    2155             : #endif
    2156             : #if CONFIG_LZO
    2157           0 :                  encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_LZO   &&
    2158             : #endif
    2159           0 :                  encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP) {
    2160           0 :                 encodings[0].scope = 0;
    2161           0 :                 av_log(matroska->ctx, AV_LOG_ERROR,
    2162             :                        "Unsupported encoding type");
    2163           0 :             } else if (track->codec_priv.size && encodings[0].scope & 2) {
    2164           0 :                 uint8_t *codec_priv = track->codec_priv.data;
    2165           0 :                 int ret = matroska_decode_buffer(&track->codec_priv.data,
    2166             :                                                  &track->codec_priv.size,
    2167             :                                                  track);
    2168           0 :                 if (ret < 0) {
    2169           0 :                     track->codec_priv.data = NULL;
    2170           0 :                     track->codec_priv.size = 0;
    2171           0 :                     av_log(matroska->ctx, AV_LOG_ERROR,
    2172             :                            "Failed to decode codec private data\n");
    2173             :                 }
    2174             : 
    2175           0 :                 if (codec_priv != track->codec_priv.data) {
    2176           0 :                     av_buffer_unref(&track->codec_priv.buf);
    2177           0 :                     if (track->codec_priv.data) {
    2178           0 :                         track->codec_priv.buf = av_buffer_create(track->codec_priv.data,
    2179           0 :                                                                  track->codec_priv.size + AV_INPUT_BUFFER_PADDING_SIZE,
    2180             :                                                                  NULL, NULL, 0);
    2181           0 :                         if (!track->codec_priv.buf) {
    2182           0 :                             av_freep(&track->codec_priv.data);
    2183           0 :                             track->codec_priv.size = 0;
    2184           0 :                             return AVERROR(ENOMEM);
    2185             :                         }
    2186             :                     }
    2187             :                 }
    2188             :             }
    2189             :         }
    2190             : 
    2191       18921 :         for (j = 0; ff_mkv_codec_tags[j].id != AV_CODEC_ID_NONE; j++) {
    2192       18920 :             if (!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
    2193       18920 :                          strlen(ff_mkv_codec_tags[j].str))) {
    2194         307 :                 codec_id = ff_mkv_codec_tags[j].id;
    2195         307 :                 break;
    2196             :             }
    2197             :         }
    2198             : 
    2199         308 :         st = track->stream = avformat_new_stream(s, NULL);
    2200         308 :         if (!st) {
    2201           0 :             av_free(key_id_base64);
    2202           0 :             return AVERROR(ENOMEM);
    2203             :         }
    2204             : 
    2205         308 :         if (key_id_base64) {
    2206             :             /* export encryption key id as base64 metadata tag */
    2207           0 :             av_dict_set(&st->metadata, "enc_key_id", key_id_base64, 0);
    2208           0 :             av_freep(&key_id_base64);
    2209             :         }
    2210             : 
    2211         309 :         if (!strcmp(track->codec_id, "V_MS/VFW/FOURCC") &&
    2212           2 :              track->codec_priv.size >= 40               &&
    2213           1 :             track->codec_priv.data) {
    2214           1 :             track->ms_compat    = 1;
    2215           1 :             bit_depth           = AV_RL16(track->codec_priv.data + 14);
    2216           1 :             fourcc              = AV_RL32(track->codec_priv.data + 16);
    2217           1 :             codec_id            = ff_codec_get_id(ff_codec_bmp_tags,
    2218             :                                                   fourcc);
    2219           1 :             if (!codec_id)
    2220           0 :                 codec_id        = ff_codec_get_id(ff_codec_movvideo_tags,
    2221             :                                                   fourcc);
    2222           1 :             extradata_offset    = 40;
    2223         307 :         } else if (!strcmp(track->codec_id, "A_MS/ACM") &&
    2224           0 :                    track->codec_priv.size >= 14         &&
    2225           0 :                    track->codec_priv.data) {
    2226             :             int ret;
    2227           0 :             ffio_init_context(&b, track->codec_priv.data,
    2228             :                               track->codec_priv.size,
    2229             :                               0, NULL, NULL, NULL, NULL);
    2230           0 :             ret = ff_get_wav_header(s, &b, st->codecpar, track->codec_priv.size, 0);
    2231           0 :             if (ret < 0)
    2232           0 :                 return ret;
    2233           0 :             codec_id         = st->codecpar->codec_id;
    2234           0 :             fourcc           = st->codecpar->codec_tag;
    2235           0 :             extradata_offset = FFMIN(track->codec_priv.size, 18);
    2236         307 :         } else if (!strcmp(track->codec_id, "A_QUICKTIME")
    2237             :                    /* Normally 36, but allow noncompliant private data */
    2238           0 :                    && (track->codec_priv.size >= 32)
    2239           0 :                    && (track->codec_priv.data)) {
    2240             :             uint16_t sample_size;
    2241           0 :             int ret = get_qt_codec(track, &fourcc, &codec_id);
    2242           0 :             if (ret < 0)
    2243           0 :                 return ret;
    2244           0 :             sample_size = AV_RB16(track->codec_priv.data + 26);
    2245           0 :             if (fourcc == 0) {
    2246           0 :                 if (sample_size == 8) {
    2247           0 :                     fourcc = MKTAG('r','a','w',' ');
    2248           0 :                     codec_id = ff_codec_get_id(ff_codec_movaudio_tags, fourcc);
    2249           0 :                 } else if (sample_size == 16) {
    2250           0 :                     fourcc = MKTAG('t','w','o','s');
    2251           0 :                     codec_id = ff_codec_get_id(ff_codec_movaudio_tags, fourcc);
    2252             :                 }
    2253             :             }
    2254           0 :             if ((fourcc == MKTAG('t','w','o','s') ||
    2255           0 :                     fourcc == MKTAG('s','o','w','t')) &&
    2256             :                     sample_size == 8)
    2257           0 :                 codec_id = AV_CODEC_ID_PCM_S8;
    2258         307 :         } else if (!strcmp(track->codec_id, "V_QUICKTIME") &&
    2259           0 :                    (track->codec_priv.size >= 21)          &&
    2260           0 :                    (track->codec_priv.data)) {
    2261           0 :             int ret = get_qt_codec(track, &fourcc, &codec_id);
    2262           0 :             if (ret < 0)
    2263           0 :                 return ret;
    2264           0 :             if (codec_id == AV_CODEC_ID_NONE && AV_RL32(track->codec_priv.data+4) == AV_RL32("SMI ")) {
    2265           0 :                 fourcc = MKTAG('S','V','Q','3');
    2266           0 :                 codec_id = ff_codec_get_id(ff_codec_movvideo_tags, fourcc);
    2267             :             }
    2268           0 :             if (codec_id == AV_CODEC_ID_NONE)
    2269           0 :                 av_log(matroska->ctx, AV_LOG_ERROR,
    2270           0 :                        "mov FourCC not found %s.\n", av_fourcc2str(fourcc));
    2271           0 :             if (track->codec_priv.size >= 86) {
    2272           0 :                 bit_depth = AV_RB16(track->codec_priv.data + 82);
    2273           0 :                 ffio_init_context(&b, track->codec_priv.data,
    2274             :                                   track->codec_priv.size,
    2275             :                                   0, NULL, NULL, NULL, NULL);
    2276           0 :                 if (ff_get_qtpalette(codec_id, &b, track->palette)) {
    2277           0 :                     bit_depth &= 0x1F;
    2278           0 :                     track->has_palette = 1;
    2279             :                 }
    2280             :             }
    2281         307 :         } else if (codec_id == AV_CODEC_ID_PCM_S16BE) {
    2282           0 :             switch (track->audio.bitdepth) {
    2283           0 :             case  8:
    2284           0 :                 codec_id = AV_CODEC_ID_PCM_U8;
    2285           0 :                 break;
    2286           0 :             case 24:
    2287           0 :                 codec_id = AV_CODEC_ID_PCM_S24BE;
    2288           0 :                 break;
    2289           0 :             case 32:
    2290           0 :                 codec_id = AV_CODEC_ID_PCM_S32BE;
    2291           0 :                 break;
    2292             :             }
    2293         307 :         } else if (codec_id == AV_CODEC_ID_PCM_S16LE) {
    2294           0 :             switch (track->audio.bitdepth) {
    2295           0 :             case  8:
    2296           0 :                 codec_id = AV_CODEC_ID_PCM_U8;
    2297           0 :                 break;
    2298           0 :             case 24:
    2299           0 :                 codec_id = AV_CODEC_ID_PCM_S24LE;
    2300           0 :                 break;
    2301           0 :             case 32:
    2302           0 :                 codec_id = AV_CODEC_ID_PCM_S32LE;
    2303           0 :                 break;
    2304             :             }
    2305         307 :         } else if (codec_id == AV_CODEC_ID_PCM_F32LE &&
    2306           0 :                    track->audio.bitdepth == 64) {
    2307           0 :             codec_id = AV_CODEC_ID_PCM_F64LE;
    2308         307 :         } else if (codec_id == AV_CODEC_ID_AAC && !track->codec_priv.size) {
    2309           0 :             int profile = matroska_aac_profile(track->codec_id);
    2310           0 :             int sri     = matroska_aac_sri(track->audio.samplerate);
    2311           0 :             extradata   = av_mallocz(5 + AV_INPUT_BUFFER_PADDING_SIZE);
    2312           0 :             if (!extradata)
    2313           0 :                 return AVERROR(ENOMEM);
    2314           0 :             extradata[0] = (profile << 3) | ((sri & 0x0E) >> 1);
    2315           0 :             extradata[1] = ((sri & 0x01) << 7) | (track->audio.channels << 3);
    2316           0 :             if (strstr(track->codec_id, "SBR")) {
    2317           0 :                 sri            = matroska_aac_sri(track->audio.out_samplerate);
    2318           0 :                 extradata[2]   = 0x56;
    2319           0 :                 extradata[3]   = 0xE5;
    2320           0 :                 extradata[4]   = 0x80 | (sri << 3);
    2321           0 :                 extradata_size = 5;
    2322             :             } else
    2323           0 :                 extradata_size = 2;
    2324         307 :         } else if (codec_id == AV_CODEC_ID_ALAC && track->codec_priv.size && track->codec_priv.size < INT_MAX - 12 - AV_INPUT_BUFFER_PADDING_SIZE) {
    2325             :             /* Only ALAC's magic cookie is stored in Matroska's track headers.
    2326             :              * Create the "atom size", "tag", and "tag version" fields the
    2327             :              * decoder expects manually. */
    2328           0 :             extradata_size = 12 + track->codec_priv.size;
    2329           0 :             extradata      = av_mallocz(extradata_size +
    2330             :                                         AV_INPUT_BUFFER_PADDING_SIZE);
    2331           0 :             if (!extradata)
    2332           0 :                 return AVERROR(ENOMEM);
    2333           0 :             AV_WB32(extradata, extradata_size);
    2334           0 :             memcpy(&extradata[4], "alac", 4);
    2335           0 :             AV_WB32(&extradata[8], 0);
    2336           0 :             memcpy(&extradata[12], track->codec_priv.data,
    2337           0 :                    track->codec_priv.size);
    2338         307 :         } else if (codec_id == AV_CODEC_ID_TTA) {
    2339           1 :             extradata_size = 30;
    2340           1 :             extradata      = av_mallocz(extradata_size + AV_INPUT_BUFFER_PADDING_SIZE);
    2341           1 :             if (!extradata)
    2342           0 :                 return AVERROR(ENOMEM);
    2343           1 :             ffio_init_context(&b, extradata, extradata_size, 1,
    2344             :                               NULL, NULL, NULL, NULL);
    2345           1 :             avio_write(&b, "TTA1", 4);
    2346           1 :             avio_wl16(&b, 1);
    2347           2 :             if (track->audio.channels > UINT16_MAX ||
    2348           1 :                 track->audio.bitdepth > UINT16_MAX) {
    2349           0 :                 av_log(matroska->ctx, AV_LOG_WARNING,
    2350             :                        "Too large audio channel number %"PRIu64
    2351             :                        " or bitdepth %"PRIu64". Skipping track.\n",
    2352             :                        track->audio.channels, track->audio.bitdepth);
    2353           0 :                 av_freep(&extradata);
    2354           0 :                 if (matroska->ctx->error_recognition & AV_EF_EXPLODE)
    2355           0 :                     return AVERROR_INVALIDDATA;
    2356             :                 else
    2357           0 :                     continue;
    2358             :             }
    2359           1 :             avio_wl16(&b, track->audio.channels);
    2360           1 :             avio_wl16(&b, track->audio.bitdepth);
    2361           1 :             if (track->audio.out_samplerate < 0 || track->audio.out_samplerate > INT_MAX)
    2362           0 :                 return AVERROR_INVALIDDATA;
    2363           1 :             avio_wl32(&b, track->audio.out_samplerate);
    2364           1 :             avio_wl32(&b, av_rescale((matroska->duration * matroska->time_scale),
    2365           1 :                                      track->audio.out_samplerate,
    2366             :                                      AV_TIME_BASE * 1000));
    2367         612 :         } else if (codec_id == AV_CODEC_ID_RV10 ||
    2368         612 :                    codec_id == AV_CODEC_ID_RV20 ||
    2369         612 :                    codec_id == AV_CODEC_ID_RV30 ||
    2370         306 :                    codec_id == AV_CODEC_ID_RV40) {
    2371           0 :             extradata_offset = 26;
    2372         306 :         } else if (codec_id == AV_CODEC_ID_RA_144) {
    2373           0 :             track->audio.out_samplerate = 8000;
    2374           0 :             track->audio.channels       = 1;
    2375         612 :         } else if ((codec_id == AV_CODEC_ID_RA_288 ||
    2376         612 :                     codec_id == AV_CODEC_ID_COOK   ||
    2377         612 :                     codec_id == AV_CODEC_ID_ATRAC3 ||
    2378         306 :                     codec_id == AV_CODEC_ID_SIPR)
    2379           0 :                       && track->codec_priv.data) {
    2380             :             int flavor;
    2381             : 
    2382           0 :             ffio_init_context(&b, track->codec_priv.data,
    2383             :                               track->codec_priv.size,
    2384             :                               0, NULL, NULL, NULL, NULL);
    2385           0 :             avio_skip(&b, 22);
    2386           0 :             flavor                       = avio_rb16(&b);
    2387           0 :             track->audio.coded_framesize = avio_rb32(&b);
    2388           0 :             avio_skip(&b, 12);
    2389           0 :             track->audio.sub_packet_h    = avio_rb16(&b);
    2390           0 :             track->audio.frame_size      = avio_rb16(&b);
    2391           0 :             track->audio.sub_packet_size = avio_rb16(&b);
    2392           0 :             if (flavor                        < 0 ||
    2393           0 :                 track->audio.coded_framesize <= 0 ||
    2394           0 :                 track->audio.sub_packet_h    <= 0 ||
    2395           0 :                 track->audio.frame_size      <= 0 ||
    2396           0 :                 track->audio.sub_packet_size <= 0 && codec_id != AV_CODEC_ID_SIPR)
    2397           0 :                 return AVERROR_INVALIDDATA;
    2398           0 :             track->audio.buf = av_malloc_array(track->audio.sub_packet_h,
    2399           0 :                                                track->audio.frame_size);
    2400           0 :             if (!track->audio.buf)
    2401           0 :                 return AVERROR(ENOMEM);
    2402           0 :             if (codec_id == AV_CODEC_ID_RA_288) {
    2403           0 :                 st->codecpar->block_align = track->audio.coded_framesize;
    2404           0 :                 track->codec_priv.size = 0;
    2405             :             } else {
    2406           0 :                 if (codec_id == AV_CODEC_ID_SIPR && flavor < 4) {
    2407             :                     static const int sipr_bit_rate[4] = { 6504, 8496, 5000, 16000 };
    2408           0 :                     track->audio.sub_packet_size = ff_sipr_subpk_size[flavor];
    2409           0 :                     st->codecpar->bit_rate          = sipr_bit_rate[flavor];
    2410             :                 }
    2411           0 :                 st->codecpar->block_align = track->audio.sub_packet_size;
    2412           0 :                 extradata_offset       = 78;
    2413             :             }
    2414         306 :         } else if (codec_id == AV_CODEC_ID_FLAC && track->codec_priv.size) {
    2415           0 :             ret = matroska_parse_flac(s, track, &extradata_offset);
    2416           0 :             if (ret < 0)
    2417           0 :                 return ret;
    2418         306 :         } else if (codec_id == AV_CODEC_ID_PRORES && track->codec_priv.size == 4) {
    2419           0 :             fourcc = AV_RL32(track->codec_priv.data);
    2420         306 :         } else if (codec_id == AV_CODEC_ID_VP9 && track->codec_priv.size) {
    2421             :             /* we don't need any value stored in CodecPrivate.
    2422             :                make sure that it's not exported as extradata. */
    2423           0 :             track->codec_priv.size = 0;
    2424             :         }
    2425         308 :         track->codec_priv.size -= extradata_offset;
    2426             : 
    2427         308 :         if (codec_id == AV_CODEC_ID_NONE)
    2428           0 :             av_log(matroska->ctx, AV_LOG_INFO,
    2429             :                    "Unknown/unsupported AVCodecID %s.\n", track->codec_id);
    2430             : 
    2431         308 :         if (track->time_scale < 0.01)
    2432           0 :             track->time_scale = 1.0;
    2433         308 :         avpriv_set_pts_info(st, 64, matroska->time_scale * track->time_scale,
    2434             :                             1000 * 1000 * 1000);    /* 64 bit pts in ns */
    2435             : 
    2436             :         /* convert the delay from ns to the track timebase */
    2437         308 :         track->codec_delay_in_track_tb = av_rescale_q(track->codec_delay,
    2438         308 :                                           (AVRational){ 1, 1000000000 },
    2439             :                                           st->time_base);
    2440             : 
    2441         308 :         st->codecpar->codec_id = codec_id;
    2442             : 
    2443         308 :         if (strcmp(track->language, "und"))
    2444         265 :             av_dict_set(&st->metadata, "language", track->language, 0);
    2445         308 :         av_dict_set(&st->metadata, "title", track->name, 0);
    2446             : 
    2447         308 :         if (track->flag_default)
    2448         291 :             st->disposition |= AV_DISPOSITION_DEFAULT;
    2449         308 :         if (track->flag_forced)
    2450           0 :             st->disposition |= AV_DISPOSITION_FORCED;
    2451             : 
    2452         308 :         if (!st->codecpar->extradata) {
    2453         308 :             if (extradata) {
    2454           1 :                 st->codecpar->extradata      = extradata;
    2455           1 :                 st->codecpar->extradata_size = extradata_size;
    2456         307 :             } else if (track->codec_priv.data && track->codec_priv.size > 0) {
    2457          52 :                 if (ff_alloc_extradata(st->codecpar, track->codec_priv.size))
    2458           0 :                     return AVERROR(ENOMEM);
    2459         156 :                 memcpy(st->codecpar->extradata,
    2460         104 :                        track->codec_priv.data + extradata_offset,
    2461          52 :                        track->codec_priv.size);
    2462             :             }
    2463             :         }
    2464             : 
    2465         308 :         if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
    2466         268 :             MatroskaTrackPlane *planes = track->operation.combine_planes.elem;
    2467         268 :             int display_width_mul  = 1;
    2468         268 :             int display_height_mul = 1;
    2469             : 
    2470         268 :             st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
    2471         268 :             st->codecpar->codec_tag  = fourcc;
    2472         268 :             if (bit_depth >= 0)
    2473           1 :                 st->codecpar->bits_per_coded_sample = bit_depth;
    2474         268 :             st->codecpar->width      = track->video.pixel_width;
    2475         268 :             st->codecpar->height     = track->video.pixel_height;
    2476             : 
    2477         268 :             if (track->video.interlaced == MATROSKA_VIDEO_INTERLACE_FLAG_INTERLACED)
    2478           0 :                 st->codecpar->field_order = mkv_field_order(matroska, track->video.field_order);
    2479         268 :             else if (track->video.interlaced == MATROSKA_VIDEO_INTERLACE_FLAG_PROGRESSIVE)
    2480           3 :                 st->codecpar->field_order = AV_FIELD_PROGRESSIVE;
    2481             : 
    2482         268 :             if (track->video.stereo_mode && track->video.stereo_mode < MATROSKA_VIDEO_STEREOMODE_TYPE_NB)
    2483           0 :                 mkv_stereo_mode_display_mul(track->video.stereo_mode, &display_width_mul, &display_height_mul);
    2484             : 
    2485         268 :             if (track->video.display_unit < MATROSKA_VIDEO_DISPLAYUNIT_UNKNOWN) {
    2486         526 :                 av_reduce(&st->sample_aspect_ratio.num,
    2487             :                           &st->sample_aspect_ratio.den,
    2488         263 :                           st->codecpar->height * track->video.display_width  * display_width_mul,
    2489         263 :                           st->codecpar->width  * track->video.display_height * display_height_mul,
    2490             :                           255);
    2491             :             }
    2492         268 :             if (st->codecpar->codec_id != AV_CODEC_ID_HEVC)
    2493         268 :                 st->need_parsing = AVSTREAM_PARSE_HEADERS;
    2494             : 
    2495         268 :             if (track->default_duration) {
    2496         232 :                 av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
    2497         232 :                           1000000000, track->default_duration, 30000);
    2498             : #if FF_API_R_FRAME_RATE
    2499         232 :                 if (   st->avg_frame_rate.num < st->avg_frame_rate.den * 1000LL
    2500         230 :                     && st->avg_frame_rate.num > st->avg_frame_rate.den * 5LL)
    2501         230 :                     st->r_frame_rate = st->avg_frame_rate;
    2502             : #endif
    2503             :             }
    2504             : 
    2505             :             /* export stereo mode flag as metadata tag */
    2506         268 :             if (track->video.stereo_mode && track->video.stereo_mode < MATROSKA_VIDEO_STEREOMODE_TYPE_NB)
    2507           0 :                 av_dict_set(&st->metadata, "stereo_mode", ff_matroska_video_stereo_mode[track->video.stereo_mode], 0);
    2508             : 
    2509             :             /* export alpha mode flag as metadata tag  */
    2510         268 :             if (track->video.alpha_mode)
    2511           1 :                 av_dict_set(&st->metadata, "alpha_mode", "1", 0);
    2512             : 
    2513             :             /* if we have virtual track, mark the real tracks */
    2514         268 :             for (j=0; j < track->operation.combine_planes.nb_elem; j++) {
    2515             :                 char buf[32];
    2516           0 :                 if (planes[j].type >= MATROSKA_VIDEO_STEREO_PLANE_COUNT)
    2517           0 :                     continue;
    2518           0 :                 snprintf(buf, sizeof(buf), "%s_%d",
    2519           0 :                          ff_matroska_video_stereo_plane[planes[j].type], i);
    2520           0 :                 for (k=0; k < matroska->tracks.nb_elem; k++)
    2521           0 :                     if (planes[j].uid == tracks[k].uid && tracks[k].stream) {
    2522           0 :                         av_dict_set(&tracks[k].stream->metadata,
    2523             :                                     "stereo_mode", buf, 0);
    2524           0 :                         break;
    2525             :                     }
    2526             :             }
    2527             :             // add stream level stereo3d side data if it is a supported format
    2528         487 :             if (track->video.stereo_mode < MATROSKA_VIDEO_STEREOMODE_TYPE_NB &&
    2529         438 :                 track->video.stereo_mode != 10 && track->video.stereo_mode != 12) {
    2530         219 :                 int ret = ff_mkv_stereo3d_conv(st, track->video.stereo_mode);
    2531         219 :                 if (ret < 0)
    2532           0 :                     return ret;
    2533             :             }
    2534             : 
    2535         268 :             ret = mkv_parse_video_color(st, track);
    2536         268 :             if (ret < 0)
    2537           0 :                 return ret;
    2538         268 :             ret = mkv_parse_video_projection(st, track);
    2539         268 :             if (ret < 0)
    2540           0 :                 return ret;
    2541          40 :         } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
    2542          37 :             st->codecpar->codec_type  = AVMEDIA_TYPE_AUDIO;
    2543          37 :             st->codecpar->codec_tag   = fourcc;
    2544          37 :             st->codecpar->sample_rate = track->audio.out_samplerate;
    2545          37 :             st->codecpar->channels    = track->audio.channels;
    2546          37 :             if (!st->codecpar->bits_per_coded_sample)
    2547          37 :                 st->codecpar->bits_per_coded_sample = track->audio.bitdepth;
    2548          74 :             if (st->codecpar->codec_id == AV_CODEC_ID_MP3 ||
    2549          74 :                 st->codecpar->codec_id == AV_CODEC_ID_MLP ||
    2550          37 :                 st->codecpar->codec_id == AV_CODEC_ID_TRUEHD)
    2551           0 :                 st->need_parsing = AVSTREAM_PARSE_FULL;
    2552          37 :             else if (st->codecpar->codec_id != AV_CODEC_ID_AAC)
    2553          28 :                 st->need_parsing = AVSTREAM_PARSE_HEADERS;
    2554          37 :             if (track->codec_delay > 0) {
    2555           1 :                 st->codecpar->initial_padding = av_rescale_q(track->codec_delay,
    2556           1 :                                                              (AVRational){1, 1000000000},
    2557           2 :                                                              (AVRational){1, st->codecpar->codec_id == AV_CODEC_ID_OPUS ?
    2558           1 :                                                                              48000 : st->codecpar->sample_rate});
    2559             :             }
    2560          37 :             if (track->seek_preroll > 0) {
    2561           1 :                 st->codecpar->seek_preroll = av_rescale_q(track->seek_preroll,
    2562           1 :                                                           (AVRational){1, 1000000000},
    2563           1 :                                                           (AVRational){1, st->codecpar->sample_rate});
    2564             :             }
    2565           3 :         } else if (codec_id == AV_CODEC_ID_WEBVTT) {
    2566           0 :             st->codecpar->codec_type = AVMEDIA_TYPE_SUBTITLE;
    2567             : 
    2568           0 :             if (!strcmp(track->codec_id, "D_WEBVTT/CAPTIONS")) {
    2569           0 :                 st->disposition |= AV_DISPOSITION_CAPTIONS;
    2570           0 :             } else if (!strcmp(track->codec_id, "D_WEBVTT/DESCRIPTIONS")) {
    2571           0 :                 st->disposition |= AV_DISPOSITION_DESCRIPTIONS;
    2572           0 :             } else if (!strcmp(track->codec_id, "D_WEBVTT/METADATA")) {
    2573           0 :                 st->disposition |= AV_DISPOSITION_METADATA;
    2574             :             }
    2575           3 :         } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
    2576           3 :             st->codecpar->codec_type = AVMEDIA_TYPE_SUBTITLE;
    2577           3 :             if (st->codecpar->codec_id == AV_CODEC_ID_ASS)
    2578           0 :                 matroska->contains_ssa = 1;
    2579             :         }
    2580             :     }
    2581             : 
    2582         296 :     return 0;
    2583             : }
    2584             : 
    2585         296 : static int matroska_read_header(AVFormatContext *s)
    2586             : {
    2587         296 :     MatroskaDemuxContext *matroska = s->priv_data;
    2588         296 :     EbmlList *attachments_list = &matroska->attachments;
    2589         296 :     EbmlList *chapters_list    = &matroska->chapters;
    2590             :     MatroskaAttachment *attachments;
    2591             :     MatroskaChapter *chapters;
    2592         296 :     uint64_t max_start = 0;
    2593             :     int64_t pos;
    2594         296 :     Ebml ebml = { 0 };
    2595             :     int i, j, res;
    2596             : 
    2597         296 :     matroska->ctx = s;
    2598         296 :     matroska->cues_parsing_deferred = 1;
    2599             : 
    2600             :     /* First read the EBML header. */
    2601         296 :     if (ebml_parse(matroska, ebml_syntax, &ebml) || !ebml.doctype) {
    2602           0 :         av_log(matroska->ctx, AV_LOG_ERROR, "EBML header parsing failed\n");
    2603           0 :         ebml_free(ebml_syntax, &ebml);
    2604           0 :         return AVERROR_INVALIDDATA;
    2605             :     }
    2606         592 :     if (ebml.version         > EBML_VERSION      ||
    2607         592 :         ebml.max_size        > sizeof(uint64_t)  ||
    2608         592 :         ebml.id_length       > sizeof(uint32_t)  ||
    2609         296 :         ebml.doctype_version > 3) {
    2610           0 :         avpriv_report_missing_feature(matroska->ctx,
    2611             :                                       "EBML version %"PRIu64", doctype %s, doc version %"PRIu64,
    2612             :                                       ebml.version, ebml.doctype, ebml.doctype_version);
    2613           0 :         ebml_free(ebml_syntax, &ebml);
    2614           0 :         return AVERROR_PATCHWELCOME;
    2615         296 :     } else if (ebml.doctype_version == 3) {
    2616           0 :         av_log(matroska->ctx, AV_LOG_WARNING,
    2617             :                "EBML header using unsupported features\n"
    2618             :                "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
    2619             :                ebml.version, ebml.doctype, ebml.doctype_version);
    2620             :     }
    2621         552 :     for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++)
    2622         552 :         if (!strcmp(ebml.doctype, matroska_doctypes[i]))
    2623         296 :             break;
    2624         296 :     if (i >= FF_ARRAY_ELEMS(matroska_doctypes)) {
    2625           0 :         av_log(s, AV_LOG_WARNING, "Unknown EBML doctype '%s'\n", ebml.doctype);
    2626           0 :         if (matroska->ctx->error_recognition & AV_EF_EXPLODE) {
    2627           0 :             ebml_free(ebml_syntax, &ebml);
    2628           0 :             return AVERROR_INVALIDDATA;
    2629             :         }
    2630             :     }
    2631         296 :     ebml_free(ebml_syntax, &ebml);
    2632             : 
    2633             :     /* The next thing is a segment. */
    2634         296 :     pos = avio_tell(matroska->ctx->pb);
    2635         296 :     res = ebml_parse(matroska, matroska_segments, matroska);
    2636             :     // try resyncing until we find a EBML_STOP type element.
    2637         592 :     while (res != 1) {
    2638           0 :         res = matroska_resync(matroska, pos);
    2639           0 :         if (res < 0)
    2640           0 :             goto fail;
    2641           0 :         pos = avio_tell(matroska->ctx->pb);
    2642           0 :         res = ebml_parse(matroska, matroska_segment, matroska);
    2643             :     }
    2644         296 :     matroska_execute_seekhead(matroska);
    2645             : 
    2646         296 :     if (!matroska->time_scale)
    2647           0 :         matroska->time_scale = 1000000;
    2648         296 :     if (matroska->duration)
    2649         570 :         matroska->ctx->duration = matroska->duration * matroska->time_scale *
    2650         285 :                                   1000 / AV_TIME_BASE;
    2651         296 :     av_dict_set(&s->metadata, "title", matroska->title, 0);
    2652         296 :     av_dict_set(&s->metadata, "encoder", matroska->muxingapp, 0);
    2653             : 
    2654         296 :     if (matroska->date_utc.size == 8)
    2655           5 :         matroska_metadata_creation_time(&s->metadata, AV_RB64(matroska->date_utc.data));
    2656             : 
    2657         296 :     res = matroska_parse_tracks(s);
    2658         296 :     if (res < 0)
    2659           0 :         goto fail;
    2660             : 
    2661         296 :     attachments = attachments_list->elem;
    2662         297 :     for (j = 0; j < attachments_list->nb_elem; j++) {
    2663           3 :         if (!(attachments[j].filename && attachments[j].mime &&
    2664           2 :               attachments[j].bin.data && attachments[j].bin.size > 0)) {
    2665           0 :             av_log(matroska->ctx, AV_LOG_ERROR, "incomplete attachment\n");
    2666             :         } else {
    2667           1 :             AVStream *st = avformat_new_stream(s, NULL);
    2668           1 :             if (!st)
    2669           0 :                 break;
    2670           1 :             av_dict_set(&st->metadata, "filename", attachments[j].filename, 0);
    2671           1 :             av_dict_set(&st->metadata, "mimetype", attachments[j].mime, 0);
    2672           1 :             st->codecpar->codec_id   = AV_CODEC_ID_NONE;
    2673             : 
    2674           5 :             for (i = 0; ff_mkv_image_mime_tags[i].id != AV_CODEC_ID_NONE; i++) {
    2675           4 :                 if (!strncmp(ff_mkv_image_mime_tags[i].str, attachments[j].mime,
    2676           4 :                              strlen(ff_mkv_image_mime_tags[i].str))) {
    2677           0 :                     st->codecpar->codec_id = ff_mkv_image_mime_tags[i].id;
    2678           0 :                     break;
    2679             :                 }
    2680             :             }
    2681             : 
    2682           1 :             attachments[j].stream = st;
    2683             : 
    2684           1 :             if (st->codecpar->codec_id != AV_CODEC_ID_NONE) {
    2685           0 :                 st->disposition         |= AV_DISPOSITION_ATTACHED_PIC;
    2686           0 :                 st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
    2687             : 
    2688           0 :                 av_init_packet(&st->attached_pic);
    2689           0 :                 if ((res = av_new_packet(&st->attached_pic, attachments[j].bin.size)) < 0)
    2690           0 :                     return res;
    2691           0 :                 memcpy(st->attached_pic.data, attachments[j].bin.data, attachments[j].bin.size);
    2692           0 :                 st->attached_pic.stream_index = st->index;
    2693           0 :                 st->attached_pic.flags       |= AV_PKT_FLAG_KEY;
    2694             :             } else {
    2695           1 :                 st->codecpar->codec_type = AVMEDIA_TYPE_ATTACHMENT;
    2696           1 :                 if (ff_alloc_extradata(st->codecpar, attachments[j].bin.size))
    2697           0 :                     break;
    2698           1 :                 memcpy(st->codecpar->extradata, attachments[j].bin.data,
    2699           1 :                        attachments[j].bin.size);
    2700             : 
    2701           6 :                 for (i = 0; ff_mkv_mime_tags[i].id != AV_CODEC_ID_NONE; i++) {
    2702           5 :                     if (!strncmp(ff_mkv_mime_tags[i].str, attachments[j].mime,
    2703           5 :                                 strlen(ff_mkv_mime_tags[i].str))) {
    2704           0 :                         st->codecpar->codec_id = ff_mkv_mime_tags[i].id;
    2705           0 :                         break;
    2706             :                     }
    2707             :                 }
    2708             :             }
    2709             :         }
    2710             :     }
    2711             : 
    2712         296 :     chapters = chapters_list->elem;
    2713         296 :     for (i = 0; i < chapters_list->nb_elem; i++)
    2714           0 :         if (chapters[i].start != AV_NOPTS_VALUE && chapters[i].uid &&
    2715           0 :             (max_start == 0 || chapters[i].start > max_start)) {
    2716           0 :             chapters[i].chapter =
    2717           0 :                 avpriv_new_chapter(s, chapters[i].uid,
    2718           0 :                                    (AVRational) { 1, 1000000000 },
    2719           0 :                                    chapters[i].start, chapters[i].end,
    2720           0 :                                    chapters[i].title);
    2721           0 :             if (chapters[i].chapter) {
    2722           0 :                 av_dict_set(&chapters[i].chapter->metadata,
    2723           0 :                             "title", chapters[i].title, 0);
    2724             :             }
    2725           0 :             max_start = chapters[i].start;
    2726             :         }
    2727             : 
    2728         296 :     matroska_add_index_entries(matroska);
    2729             : 
    2730         296 :     matroska_convert_tags(s);
    2731             : 
    2732         296 :     return 0;
    2733           0 : fail:
    2734           0 :     matroska_read_close(s);
    2735           0 :     return res;
    2736             : }
    2737             : 
    2738             : /*
    2739             :  * Put one packet in an application-supplied AVPacket struct.
    2740             :  * Returns 0 on success or -1 on failure.
    2741             :  */
    2742       55074 : static int matroska_deliver_packet(MatroskaDemuxContext *matroska,
    2743             :                                    AVPacket *pkt)
    2744             : {
    2745       55074 :     if (matroska->queue) {
    2746       26774 :         MatroskaTrack *tracks = matroska->tracks.elem;
    2747             :         MatroskaTrack *track;
    2748             : 
    2749       26774 :         ff_packet_list_get(&matroska->queue, &matroska->queue_end, pkt);
    2750       26774 :         track = &tracks[pkt->stream_index];
    2751       26774 :         if (track->has_palette) {
    2752           0 :             uint8_t *pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
    2753           0 :             if (!pal) {
    2754           0 :                 av_log(matroska->ctx, AV_LOG_ERROR, "Cannot append palette to packet\n");
    2755             :             } else {
    2756           0 :                 memcpy(pal, track->palette, AVPALETTE_SIZE);
    2757             :             }
    2758           0 :             track->has_palette = 0;
    2759             :         }
    2760       26774 :         return 0;
    2761             :     }
    2762             : 
    2763       28300 :     return -1;
    2764             : }
    2765             : 
    2766             : /*
    2767             :  * Free all packets in our internal queue.
    2768             :  */
    2769        1145 : static void matroska_clear_queue(MatroskaDemuxContext *matroska)
    2770             : {
    2771        1145 :     ff_packet_list_free(&matroska->queue, &matroska->queue_end);
    2772        1145 : }
    2773             : 
    2774       27348 : static int matroska_parse_laces(MatroskaDemuxContext *matroska, uint8_t **buf,
    2775             :                                 int *buf_size, int type,
    2776             :                                 uint32_t **lace_buf, int *laces)
    2777             : {
    2778       27348 :     int res = 0, n, size = *buf_size;
    2779       27348 :     uint8_t *data = *buf;
    2780             :     uint32_t *lace_size;
    2781             : 
    2782       27348 :     if (!type) {
    2783       27313 :         *laces    = 1;
    2784       27313 :         *lace_buf = av_mallocz(sizeof(int));
    2785       27313 :         if (!*lace_buf)
    2786           0 :             return AVERROR(ENOMEM);
    2787             : 
    2788       27313 :         *lace_buf[0] = size;
    2789       27313 :         return 0;
    2790             :     }
    2791             : 
    2792          35 :     av_assert0(size > 0);
    2793          35 :     *laces    = *data + 1;
    2794          35 :     data     += 1;
    2795          35 :     size     -= 1;
    2796          35 :     lace_size = av_mallocz(*laces * sizeof(int));
    2797          35 :     if (!lace_size)
    2798           0 :         return AVERROR(ENOMEM);
    2799             : 
    2800          35 :     switch (type) {
    2801           0 :     case 0x1: /* Xiph lacing */
    2802             :     {
    2803             :         uint8_t temp;
    2804           0 :         uint32_t total = 0;
    2805           0 :         for (n = 0; res == 0 && n < *laces - 1; n++) {
    2806             :             while (1) {
    2807           0 :                 if (size <= total) {
    2808           0 :                     res = AVERROR_INVALIDDATA;
    2809           0 :                     break;
    2810             :                 }
    2811           0 :                 temp          = *data;
    2812           0 :                 total        += temp;
    2813           0 :                 lace_size[n] += temp;
    2814           0 :                 data         += 1;
    2815           0 :                 size         -= 1;
    2816           0 :                 if (temp != 0xff)
    2817           0 :                     break;
    2818             :             }
    2819             :         }
    2820           0 :         if (size <= total) {
    2821           0 :             res = AVERROR_INVALIDDATA;
    2822           0 :             break;
    2823             :         }
    2824             : 
    2825           0 :         lace_size[n] = size - total;
    2826           0 :         break;
    2827             :     }
    2828             : 
    2829           2 :     case 0x2: /* fixed-size lacing */
    2830           2 :         if (size % (*laces)) {
    2831           0 :             res = AVERROR_INVALIDDATA;
    2832           0 :             break;
    2833             :         }
    2834           8 :         for (n = 0; n < *laces; n++)
    2835           6 :             lace_size[n] = size / *laces;
    2836           2 :         break;
    2837             : 
    2838          33 :     case 0x3: /* EBML lacing */
    2839             :     {
    2840             :         uint64_t num;
    2841             :         uint64_t total;
    2842          33 :         n = matroska_ebmlnum_uint(matroska, data, size, &num);
    2843          33 :         if (n < 0 || num > INT_MAX) {
    2844           0 :             av_log(matroska->ctx, AV_LOG_INFO,
    2845             :                    "EBML block data error\n");
    2846           0 :             res = n<0 ? n : AVERROR_INVALIDDATA;
    2847           0 :             break;
    2848             :         }
    2849          33 :         data += n;
    2850          33 :         size -= n;
    2851          33 :         total = lace_size[0] = num;
    2852         169 :         for (n = 1; res == 0 && n < *laces - 1; n++) {
    2853             :             int64_t snum;
    2854             :             int r;
    2855         136 :             r = matroska_ebmlnum_sint(matroska, data, size, &snum);
    2856         136 :             if (r < 0 || lace_size[n - 1] + snum > (uint64_t)INT_MAX) {
    2857           0 :                 av_log(matroska->ctx, AV_LOG_INFO,
    2858             :                        "EBML block data error\n");
    2859           0 :                 res = r<0 ? r : AVERROR_INVALIDDATA;
    2860           0 :                 break;
    2861             :             }
    2862         136 :             data        += r;
    2863         136 :             size        -= r;
    2864         136 :             lace_size[n] = lace_size[n - 1] + snum;
    2865         136 :             total       += lace_size[n];
    2866             :         }
    2867          33 :         if (size <= total) {
    2868           0 :             res = AVERROR_INVALIDDATA;
    2869           0 :             break;
    2870             :         }
    2871          33 :         lace_size[*laces - 1] = size - total;
    2872          33 :         break;
    2873             :     }
    2874             :     }
    2875             : 
    2876          35 :     *buf      = data;
    2877          35 :     *lace_buf = lace_size;
    2878          35 :     *buf_size = size;
    2879             : 
    2880          35 :     return res;
    2881             : }
    2882             : 
    2883           0 : static int matroska_parse_rm_audio(MatroskaDemuxContext *matroska,
    2884             :                                    MatroskaTrack *track, AVStream *st,
    2885             :                                    uint8_t *data, int size, uint64_t timecode,
    2886             :                                    int64_t pos)
    2887             : {
    2888           0 :     int a = st->codecpar->block_align;
    2889           0 :     int sps = track->audio.sub_packet_size;
    2890           0 :     int cfs = track->audio.coded_framesize;
    2891           0 :     int h   = track->audio.sub_packet_h;
    2892           0 :     int y   = track->audio.sub_packet_cnt;
    2893           0 :     int w   = track->audio.frame_size;
    2894             :     int x;
    2895             : 
    2896           0 :     if (!track->audio.pkt_cnt) {
    2897           0 :         if (track->audio.sub_packet_cnt == 0)
    2898           0 :             track->audio.buf_timecode = timecode;
    2899           0 :         if (st->codecpar->codec_id == AV_CODEC_ID_RA_288) {
    2900           0 :             if (size < cfs * h / 2) {
    2901           0 :                 av_log(matroska->ctx, AV_LOG_ERROR,
    2902             :                        "Corrupt int4 RM-style audio packet size\n");
    2903           0 :                 return AVERROR_INVALIDDATA;
    2904             :             }
    2905           0 :             for (x = 0; x < h / 2; x++)
    2906           0 :                 memcpy(track->audio.buf + x * 2 * w + y * cfs,
    2907           0 :                        data + x * cfs, cfs);
    2908           0 :         } else if (st->codecpar->codec_id == AV_CODEC_ID_SIPR) {
    2909           0 :             if (size < w) {
    2910           0 :                 av_log(matroska->ctx, AV_LOG_ERROR,
    2911             :                        "Corrupt sipr RM-style audio packet size\n");
    2912           0 :                 return AVERROR_INVALIDDATA;
    2913             :             }
    2914           0 :             memcpy(track->audio.buf + y * w, data, w);
    2915             :         } else {
    2916           0 :             if (size < sps * w / sps || h<=0 || w%sps) {
    2917           0 :                 av_log(matroska->ctx, AV_LOG_ERROR,
    2918             :                        "Corrupt generic RM-style audio packet size\n");
    2919           0 :                 return AVERROR_INVALIDDATA;
    2920             :             }
    2921           0 :             for (x = 0; x < w / sps; x++)
    2922           0 :                 memcpy(track->audio.buf +
    2923           0 :                        sps * (h * x + ((h + 1) / 2) * (y & 1) + (y >> 1)),
    2924           0 :                        data + x * sps, sps);
    2925             :         }
    2926             : 
    2927           0 :         if (++track->audio.sub_packet_cnt >= h) {
    2928           0 :             if (st->codecpar->codec_id == AV_CODEC_ID_SIPR)
    2929           0 :                 ff_rm_reorder_sipr_data(track->audio.buf, h, w);
    2930           0 :             track->audio.sub_packet_cnt = 0;
    2931           0 :             track->audio.pkt_cnt        = h * w / a;
    2932             :         }
    2933             :     }
    2934             : 
    2935           0 :     while (track->audio.pkt_cnt) {
    2936             :         int ret;
    2937           0 :         AVPacket pktl, *pkt = &pktl;
    2938             : 
    2939           0 :         ret = av_new_packet(pkt, a);
    2940           0 :         if (ret < 0) {
    2941           0 :             return ret;
    2942             :         }
    2943           0 :         memcpy(pkt->data,
    2944           0 :                track->audio.buf + a * (h * w / a - track->audio.pkt_cnt--),
    2945             :                a);
    2946           0 :         pkt->pts                  = track->audio.buf_timecode;
    2947           0 :         track->audio.buf_timecode = AV_NOPTS_VALUE;
    2948           0 :         pkt->pos                  = pos;
    2949           0 :         pkt->stream_index         = st->index;
    2950           0 :         ret = ff_packet_list_put(&matroska->queue, &matroska->queue_end, pkt, 0);
    2951           0 :         if (ret < 0) {
    2952           0 :             av_packet_unref(pkt);
    2953           0 :             return AVERROR(ENOMEM);
    2954             :         }
    2955             :     }
    2956             : 
    2957           0 :     return 0;
    2958             : }
    2959             : 
    2960             : /* reconstruct full wavpack blocks from mangled matroska ones */
    2961          22 : static int matroska_parse_wavpack(MatroskaTrack *track, uint8_t *src,
    2962             :                                   uint8_t **pdst, int *size)
    2963             : {
    2964          22 :     uint8_t *dst = NULL;
    2965          22 :     int dstlen   = 0;
    2966          22 :     int srclen   = *size;
    2967             :     uint32_t samples;
    2968             :     uint16_t ver;
    2969          22 :     int ret, offset = 0;
    2970             : 
    2971          22 :     if (srclen < 12 || track->stream->codecpar->extradata_size < 2)
    2972           0 :         return AVERROR_INVALIDDATA;
    2973             : 
    2974          22 :     ver = AV_RL16(track->stream->codecpar->extradata);
    2975             : 
    2976          22 :     samples = AV_RL32(src);
    2977          22 :     src    += 4;
    2978          22 :     srclen -= 4;
    2979             : 
    2980         154 :     while (srclen >= 8) {
    2981             :         int multiblock;
    2982             :         uint32_t blocksize;
    2983             :         uint8_t *tmp;
    2984             : 
    2985         110 :         uint32_t flags = AV_RL32(src);
    2986         110 :         uint32_t crc   = AV_RL32(src + 4);
    2987         110 :         src    += 8;
    2988         110 :         srclen -= 8;
    2989             : 
    2990         110 :         multiblock = (flags & 0x1800) != 0x1800;
    2991         110 :         if (multiblock) {
    2992         110 :             if (srclen < 4) {
    2993           0 :                 ret = AVERROR_INVALIDDATA;
    2994           0 :                 goto fail;
    2995             :             }
    2996         110 :             blocksize = AV_RL32(src);
    2997         110 :             src      += 4;
    2998         110 :             srclen   -= 4;
    2999             :         } else
    3000           0 :             blocksize = srclen;
    3001             : 
    3002         110 :         if (blocksize > srclen) {
    3003           0 :             ret = AVERROR_INVALIDDATA;
    3004           0 :             goto fail;
    3005             :         }
    3006             : 
    3007         110 :         tmp = av_realloc(dst, dstlen + blocksize + 32 + AV_INPUT_BUFFER_PADDING_SIZE);
    3008         110 :         if (!tmp) {
    3009           0 :             ret = AVERROR(ENOMEM);
    3010           0 :             goto fail;
    3011             :         }
    3012         110 :         dst     = tmp;
    3013         110 :         dstlen += blocksize + 32;
    3014             : 
    3015         110 :         AV_WL32(dst + offset, MKTAG('w', 'v', 'p', 'k'));   // tag
    3016         110 :         AV_WL32(dst + offset +  4, blocksize + 24);         // blocksize - 8
    3017         110 :         AV_WL16(dst + offset +  8, ver);                    // version
    3018         110 :         AV_WL16(dst + offset + 10, 0);                      // track/index_no
    3019         110 :         AV_WL32(dst + offset + 12, 0);                      // total samples
    3020         110 :         AV_WL32(dst + offset + 16, 0);                      // block index
    3021         110 :         AV_WL32(dst + offset + 20, samples);                // number of samples
    3022         110 :         AV_WL32(dst + offset + 24, flags);                  // flags
    3023         110 :         AV_WL32(dst + offset + 28, crc);                    // crc
    3024         110 :         memcpy(dst + offset + 32, src, blocksize);          // block data
    3025             : 
    3026         110 :         src    += blocksize;
    3027         110 :         srclen -= blocksize;
    3028         110 :         offset += blocksize + 32;
    3029             :     }
    3030             : 
    3031          22 :     memset(dst + dstlen, 0, AV_INPUT_BUFFER_PADDING_SIZE);
    3032             : 
    3033          22 :     *pdst = dst;
    3034          22 :     *size = dstlen;
    3035             : 
    3036          22 :     return 0;
    3037             : 
    3038           0 : fail:
    3039           0 :     av_freep(&dst);
    3040           0 :     return ret;
    3041             : }
    3042             : 
    3043           0 : static int matroska_parse_prores(MatroskaTrack *track, uint8_t *src,
    3044             :                                  uint8_t **pdst, int *size)
    3045             : {
    3046           0 :     uint8_t *dst = src;
    3047           0 :     int dstlen = *size;
    3048             : 
    3049           0 :     if (AV_RB32(&src[4]) != MKBETAG('i', 'c', 'p', 'f')) {
    3050           0 :         dst = av_malloc(dstlen + 8 + AV_INPUT_BUFFER_PADDING_SIZE);
    3051           0 :         if (!dst)
    3052           0 :             return AVERROR(ENOMEM);
    3053             : 
    3054           0 :         AV_WB32(dst, dstlen);
    3055           0 :         AV_WB32(dst + 4, MKBETAG('i', 'c', 'p', 'f'));
    3056           0 :         memcpy(dst + 8, src, dstlen);
    3057           0 :         memset(dst + 8 + dstlen, 0, AV_INPUT_BUFFER_PADDING_SIZE);
    3058           0 :         dstlen += 8;
    3059             :     }
    3060             : 
    3061           0 :     *pdst = dst;
    3062           0 :     *size = dstlen;
    3063             : 
    3064           0 :     return 0;
    3065             : }
    3066             : 
    3067           0 : static int matroska_parse_webvtt(MatroskaDemuxContext *matroska,
    3068             :                                  MatroskaTrack *track,
    3069             :                                  AVStream *st,
    3070             :                                  uint8_t *data, int data_len,
    3071             :                                  uint64_t timecode,
    3072             :                                  uint64_t duration,
    3073             :                                  int64_t pos)
    3074             : {
    3075           0 :     AVPacket pktl, *pkt = &pktl;
    3076             :     uint8_t *id, *settings, *text, *buf;
    3077             :     int id_len, settings_len, text_len;
    3078             :     uint8_t *p, *q;
    3079             :     int err;
    3080             : 
    3081           0 :     if (data_len <= 0)
    3082           0 :         return AVERROR_INVALIDDATA;
    3083             : 
    3084           0 :     p = data;
    3085           0 :     q = data + data_len;
    3086             : 
    3087           0 :     id = p;
    3088           0 :     id_len = -1;
    3089           0 :     while (p < q) {
    3090           0 :         if (*p == '\r' || *p == '\n') {
    3091           0 :             id_len = p - id;
    3092           0 :             if (*p == '\r')
    3093           0 :                 p++;
    3094           0 :             break;
    3095             :         }
    3096           0 :         p++;
    3097             :     }
    3098             : 
    3099           0 :     if (p >= q || *p != '\n')
    3100           0 :         return AVERROR_INVALIDDATA;
    3101           0 :     p++;
    3102             : 
    3103           0 :     settings = p;
    3104           0 :     settings_len = -1;
    3105           0 :     while (p < q) {
    3106           0 :         if (*p == '\r' || *p == '\n') {
    3107           0 :             settings_len = p - settings;
    3108           0 :             if (*p == '\r')
    3109           0 :                 p++;
    3110           0 :             break;
    3111             :         }
    3112           0 :         p++;
    3113             :     }
    3114             : 
    3115           0 :     if (p >= q || *p != '\n')
    3116           0 :         return AVERROR_INVALIDDATA;
    3117           0 :     p++;
    3118             : 
    3119           0 :     text = p;
    3120           0 :     text_len = q - p;
    3121           0 :     while (text_len > 0) {
    3122           0 :         const int len = text_len - 1;
    3123           0 :         const uint8_t c = p[len];
    3124           0 :         if (c != '\r' && c != '\n')
    3125           0 :             break;
    3126           0 :         text_len = len;
    3127             :     }
    3128             : 
    3129           0 :     if (text_len <= 0)
    3130           0 :         return AVERROR_INVALIDDATA;
    3131             : 
    3132           0 :     err = av_new_packet(pkt, text_len);
    3133           0 :     if (err < 0) {
    3134           0 :         return err;
    3135             :     }
    3136             : 
    3137           0 :     memcpy(pkt->data, text, text_len);
    3138             : 
    3139           0 :     if (id_len > 0) {
    3140           0 :         buf = av_packet_new_side_data(pkt,
    3141             :                                       AV_PKT_DATA_WEBVTT_IDENTIFIER,
    3142             :                                       id_len);
    3143           0 :         if (!buf) {
    3144           0 :             av_packet_unref(pkt);
    3145           0 :             return AVERROR(ENOMEM);
    3146             :         }
    3147           0 :         memcpy(buf, id, id_len);
    3148             :     }
    3149             : 
    3150           0 :     if (settings_len > 0) {
    3151           0 :         buf = av_packet_new_side_data(pkt,
    3152             :                                       AV_PKT_DATA_WEBVTT_SETTINGS,
    3153             :                                       settings_len);
    3154           0 :         if (!buf) {
    3155           0 :             av_packet_unref(pkt);
    3156           0 :             return AVERROR(ENOMEM);
    3157             :         }
    3158           0 :         memcpy(buf, settings, settings_len);
    3159             :     }
    3160             : 
    3161             :     // Do we need this for subtitles?
    3162             :     // pkt->flags = AV_PKT_FLAG_KEY;
    3163             : 
    3164           0 :     pkt->stream_index = st->index;
    3165           0 :     pkt->pts = timecode;
    3166             : 
    3167             :     // Do we need this for subtitles?
    3168             :     // pkt->dts = timecode;
    3169             : 
    3170           0 :     pkt->duration = duration;
    3171           0 :     pkt->pos = pos;
    3172             : 
    3173           0 :     err = ff_packet_list_put(&matroska->queue, &matroska->queue_end, pkt, 0);
    3174           0 :     if (err < 0) {
    3175           0 :         av_packet_unref(pkt);
    3176           0 :         return AVERROR(ENOMEM);
    3177             :     }
    3178             : 
    3179           0 :     return 0;
    3180             : }
    3181             : 
    3182       27521 : static int matroska_parse_frame(MatroskaDemuxContext *matroska,
    3183             :                                 MatroskaTrack *track, AVStream *st,
    3184             :                                 AVBufferRef *buf, uint8_t *data, int pkt_size,
    3185             :                                 uint64_t timecode, uint64_t lace_duration,
    3186             :                                 int64_t pos, int is_keyframe,
    3187             :                                 uint8_t *additional, uint64_t additional_id, int additional_size,
    3188             :                                 int64_t discard_padding)
    3189             : {
    3190       27521 :     MatroskaTrackEncoding *encodings = track->encodings.elem;
    3191       27521 :     uint8_t *pkt_data = data;
    3192             :     int res;
    3193       27521 :     AVPacket pktl, *pkt = &pktl;
    3194             : 
    3195       27521 :     if (encodings && !encodings->type && encodings->scope & 1) {
    3196           0 :         res = matroska_decode_buffer(&pkt_data, &pkt_size, track);
    3197           0 :         if (res < 0)
    3198           0 :             return res;
    3199             :     }
    3200             : 
    3201       27521 :     if (st->codecpar->codec_id == AV_CODEC_ID_WAVPACK) {
    3202             :         uint8_t *wv_data;
    3203          22 :         res = matroska_parse_wavpack(track, pkt_data, &wv_data, &pkt_size);
    3204          22 :         if (res < 0) {
    3205           0 :             av_log(matroska->ctx, AV_LOG_ERROR,
    3206             :                    "Error parsing a wavpack block.\n");
    3207           0 :             goto fail;
    3208             :         }
    3209          22 :         if (pkt_data != data)
    3210           0 :             av_freep(&pkt_data);
    3211          22 :         pkt_data = wv_data;
    3212             :     }
    3213             : 
    3214       27521 :     if (st->codecpar->codec_id == AV_CODEC_ID_PRORES) {
    3215             :         uint8_t *pr_data;
    3216           0 :         res = matroska_parse_prores(track, pkt_data, &pr_data, &pkt_size);
    3217           0 :         if (res < 0) {
    3218           0 :             av_log(matroska->ctx, AV_LOG_ERROR,
    3219             :                    "Error parsing a prores block.\n");
    3220           0 :             goto fail;
    3221             :         }
    3222           0 :         if (pkt_data != data)
    3223           0 :             av_freep(&pkt_data);
    3224           0 :         pkt_data = pr_data;
    3225             :     }
    3226             : 
    3227       27521 :     av_init_packet(pkt);
    3228       27521 :     if (pkt_data != data)
    3229          22 :         pkt->buf = av_buffer_create(pkt_data, pkt_size + AV_INPUT_BUFFER_PADDING_SIZE,
    3230             :                                     NULL, NULL, 0);
    3231             :     else
    3232       27499 :         pkt->buf = av_buffer_ref(buf);
    3233             : 
    3234       27521 :     if (!pkt->buf) {
    3235           0 :         res = AVERROR(ENOMEM);
    3236           0 :         goto fail;
    3237             :     }
    3238             : 
    3239       27521 :     pkt->data         = pkt_data;
    3240       27521 :     pkt->size         = pkt_size;
    3241       27521 :     pkt->flags        = is_keyframe;
    3242       27521 :     pkt->stream_index = st->index;
    3243             : 
    3244       27521 :     if (additional_size > 0) {
    3245         120 :         uint8_t *side_data = av_packet_new_side_data(pkt,
    3246             :                                                      AV_PKT_DATA_MATROSKA_BLOCKADDITIONAL,
    3247             :                                                      additional_size + 8);
    3248         120 :         if (!side_data) {
    3249           0 :             av_packet_unref(pkt);
    3250           0 :             return AVERROR(ENOMEM);
    3251             :         }
    3252         120 :         AV_WB64(side_data, additional_id);
    3253         120 :         memcpy(side_data + 8, additional, additional_size);
    3254             :     }
    3255             : 
    3256       27521 :     if (discard_padding) {
    3257          24 :         uint8_t *side_data = av_packet_new_side_data(pkt,
    3258             :                                                      AV_PKT_DATA_SKIP_SAMPLES,
    3259             :                                                      10);
    3260          24 :         if (!side_data) {
    3261           0 :             av_packet_unref(pkt);
    3262           0 :             return AVERROR(ENOMEM);
    3263             :         }
    3264          24 :         discard_padding = av_rescale_q(discard_padding,
    3265          24 :                                             (AVRational){1, 1000000000},
    3266          24 :                                             (AVRational){1, st->codecpar->sample_rate});
    3267          24 :         if (discard_padding > 0) {
    3268          24 :             AV_WL32(side_data + 4, discard_padding);
    3269             :         } else {
    3270           0 :             AV_WL32(side_data, -discard_padding);
    3271             :         }
    3272             :     }
    3273             : 
    3274       27521 :     if (track->ms_compat)
    3275           1 :         pkt->dts = timecode;
    3276             :     else
    3277       27520 :         pkt->pts = timecode;
    3278       27521 :     pkt->pos = pos;
    3279       27521 :     pkt->duration = lace_duration;
    3280             : 
    3281             : #if FF_API_CONVERGENCE_DURATION
    3282             : FF_DISABLE_DEPRECATION_WARNINGS
    3283       27521 :     if (st->codecpar->codec_id == AV_CODEC_ID_SUBRIP) {
    3284           0 :         pkt->convergence_duration = lace_duration;
    3285             :     }
    3286             : FF_ENABLE_DEPRECATION_WARNINGS
    3287             : #endif
    3288             : 
    3289       27521 :     res = ff_packet_list_put(&matroska->queue, &matroska->queue_end, pkt, 0);
    3290       27521 :     if (res < 0) {
    3291           0 :         av_packet_unref(pkt);
    3292           0 :         return AVERROR(ENOMEM);
    3293             :     }
    3294             : 
    3295       27521 :     return 0;
    3296             : 
    3297           0 : fail:
    3298           0 :     if (pkt_data != data)
    3299           0 :         av_freep(&pkt_data);
    3300           0 :     return res;
    3301             : }
    3302             : 
    3303       28168 : static int matroska_parse_block(MatroskaDemuxContext *matroska, AVBufferRef *buf, uint8_t *data,
    3304             :                                 int size, int64_t pos, uint64_t cluster_time,
    3305             :                                 uint64_t block_duration, int is_keyframe,
    3306             :                                 uint8_t *additional, uint64_t additional_id, int additional_size,
    3307             :                                 int64_t cluster_pos, int64_t discard_padding)
    3308             : {
    3309       28168 :     uint64_t timecode = AV_NOPTS_VALUE;
    3310             :     MatroskaTrack *track;
    3311       28168 :     int res = 0;
    3312             :     AVStream *st;
    3313             :     int16_t block_time;
    3314       28168 :     uint32_t *lace_size = NULL;
    3315       28168 :     int n, flags, laces = 0;
    3316             :     uint64_t num;
    3317       28168 :     int trust_default_duration = 1;
    3318             : 
    3319       28168 :     if ((n = matroska_ebmlnum_uint(matroska, data, size, &num)) < 0) {
    3320           0 :         av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
    3321           0 :         return n;
    3322             :     }
    3323       28168 :     data += n;
    3324       28168 :     size -= n;
    3325             : 
    3326       28168 :     track = matroska_find_track_by_num(matroska, num);
    3327       28168 :     if (!track || !track->stream) {
    3328           1 :         av_log(matroska->ctx, AV_LOG_INFO,
    3329             :                "Invalid stream %"PRIu64" or size %u\n", num, size);
    3330           1 :         return AVERROR_INVALIDDATA;
    3331       28167 :     } else if (size <= 3)
    3332           0 :         return 0;
    3333       28167 :     st = track->stream;
    3334       28167 :     if (st->discard >= AVDISCARD_ALL)
    3335         271 :         return res;
    3336             :     av_assert1(block_duration != AV_NOPTS_VALUE);
    3337             : 
    3338       27896 :     block_time = sign_extend(AV_RB16(data), 16);
    3339       27896 :     data      += 2;
    3340       27896 :     flags      = *data++;
    3341       27896 :     size      -= 3;
    3342       27896 :     if (is_keyframe == -1)
    3343       27751 :         is_keyframe = flags & 0x80 ? AV_PKT_FLAG_KEY : 0;
    3344             : 
    3345       27896 :     if (cluster_time != (uint64_t) -1 &&
    3346          20 :         (block_time >= 0 || cluster_time >= -block_time)) {
    3347       27880 :         timecode = cluster_time + block_time - track->codec_delay_in_track_tb;
    3348       27881 :         if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE &&
    3349           1 :             timecode < track->end_timecode)
    3350           0 :             is_keyframe = 0;  /* overlapping subtitles are not key frame */
    3351       27880 :         if (is_keyframe) {
    3352       24974 :             ff_reduce_index(matroska->ctx, st->index);
    3353       24974 :             av_add_index_entry(st, cluster_pos, timecode, 0, 0,
    3354             :                                AVINDEX_KEYFRAME);
    3355             :         }
    3356             :     }
    3357             : 
    3358       28486 :     if (matroska->skip_to_keyframe &&
    3359         590 :         track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
    3360             :         // Compare signed timecodes. Timecode may be negative due to codec delay
    3361             :         // offset. We don't support timestamps greater than int64_t anyway - see
    3362             :         // AVPacket's pts.
    3363         590 :         if ((int64_t)timecode < (int64_t)matroska->skip_to_timecode)
    3364         548 :             return res;
    3365          42 :         if (is_keyframe)
    3366          42 :             matroska->skip_to_keyframe = 0;
    3367           0 :         else if (!st->skip_to_keyframe) {
    3368           0 :             av_log(matroska->ctx, AV_LOG_ERROR, "File is broken, keyframes not correctly marked!\n");
    3369           0 :             matroska->skip_to_keyframe = 0;
    3370             :         }
    3371             :     }
    3372             : 
    3373       27348 :     res = matroska_parse_laces(matroska, &data, &size, (flags & 0x06) >> 1,
    3374             :                                &lace_size, &laces);
    3375             : 
    3376       27348 :     if (res)
    3377           0 :         goto end;
    3378             : 
    3379       27348 :     if (track->audio.samplerate == 8000) {
    3380             :         // If this is needed for more codecs, then add them here
    3381           0 :         if (st->codecpar->codec_id == AV_CODEC_ID_AC3) {
    3382           0 :             if (track->audio.samplerate != st->codecpar->sample_rate || !st->codecpar->frame_size)
    3383           0 :                 trust_default_duration = 0;
    3384             :         }
    3385             :     }
    3386             : 
    3387       27348 :     if (!block_duration && trust_default_duration)
    3388       27347 :         block_duration = track->default_duration * laces / matroska->time_scale;
    3389             : 
    3390       27348 :     if (cluster_time != (uint64_t)-1 && (block_time >= 0 || cluster_time >= -block_time))
    3391       27332 :         track->end_timecode =
    3392       27332 :             FFMAX(track->end_timecode, timecode + block_duration);
    3393             : 
    3394       54869 :     for (n = 0; n < laces; n++) {
    3395       27521 :         int64_t lace_duration = block_duration*(n+1) / laces - block_duration*n / laces;
    3396             : 
    3397       27521 :         if (lace_size[n] > size) {
    3398           0 :             av_log(matroska->ctx, AV_LOG_ERROR, "Invalid packet size\n");
    3399           0 :             break;
    3400             :         }
    3401             : 
    3402       55042 :         if ((st->codecpar->codec_id == AV_CODEC_ID_RA_288 ||
    3403       55042 :              st->codecpar->codec_id == AV_CODEC_ID_COOK   ||
    3404       55042 :              st->codecpar->codec_id == AV_CODEC_ID_SIPR   ||
    3405       27521 :              st->codecpar->codec_id == AV_CODEC_ID_ATRAC3) &&
    3406           0 :             st->codecpar->block_align && track->audio.sub_packet_size) {
    3407           0 :             res = matroska_parse_rm_audio(matroska, track, st, data,
    3408           0 :                                           lace_size[n],
    3409             :                                           timecode, pos);
    3410           0 :             if (res)
    3411           0 :                 goto end;
    3412             : 
    3413       27521 :         } else if (st->codecpar->codec_id == AV_CODEC_ID_WEBVTT) {
    3414           0 :             res = matroska_parse_webvtt(matroska, track, st,
    3415           0 :                                         data, lace_size[n],
    3416             :                                         timecode, lace_duration,
    3417             :                                         pos);
    3418           0 :             if (res)
    3419           0 :                 goto end;
    3420             :         } else {
    3421       27521 :             res = matroska_parse_frame(matroska, track, st, buf, data, lace_size[n],
    3422             :                                        timecode, lace_duration, pos,
    3423             :                                        !n ? is_keyframe : 0,
    3424             :                                        additional, additional_id, additional_size,
    3425             :                                        discard_padding);
    3426       27521 :             if (res)
    3427           0 :                 goto end;
    3428             :         }
    3429             : 
    3430       27521 :         if (timecode != AV_NOPTS_VALUE)
    3431       27505 :             timecode = lace_duration ? timecode + lace_duration : AV_NOPTS_VALUE;
    3432       27521 :         data += lace_size[n];
    3433       27521 :         size -= lace_size[n];
    3434             :     }
    3435             : 
    3436       27348 : end:
    3437       27348 :     av_free(lace_size);
    3438       27348 :     return res;
    3439             : }
    3440             : 
    3441       28760 : static int matroska_parse_cluster_incremental(MatroskaDemuxContext *matroska)
    3442             : {
    3443             :     EbmlList *blocks_list;
    3444             :     MatroskaBlock *blocks;
    3445             :     int i, res;
    3446       28760 :     res = ebml_parse(matroska,
    3447             :                      matroska_cluster_incremental_parsing,
    3448       28760 :                      &matroska->current_cluster);
    3449       28760 :     if (res == 1) {
    3450             :         /* New Cluster */
    3451         555 :         if (matroska->current_cluster_pos)
    3452         263 :             ebml_level_end(matroska);
    3453         555 :         ebml_free(matroska_cluster, &matroska->current_cluster);
    3454         555 :         memset(&matroska->current_cluster, 0, sizeof(MatroskaCluster));
    3455         555 :         matroska->current_cluster_num_blocks = 0;
    3456         555 :         matroska->current_cluster_pos        = avio_tell(matroska->ctx->pb);
    3457             :         /* sizeof the ID which was already read */
    3458         555 :         if (matroska->current_id)
    3459         555 :             matroska->current_cluster_pos -= 4;
    3460         555 :         res = ebml_parse(matroska,
    3461             :                          matroska_clusters_incremental,
    3462         555 :                          &matroska->current_cluster);
    3463             :         /* Try parsing the block again. */
    3464         555 :         if (res == 1)
    3465         555 :             res = ebml_parse(matroska,
    3466             :                              matroska_cluster_incremental_parsing,
    3467         555 :                              &matroska->current_cluster);
    3468             :     }
    3469             : 
    3470       57206 :     if (!res &&
    3471       28446 :         matroska->current_cluster_num_blocks <
    3472       28446 :         matroska->current_cluster.blocks.nb_elem) {
    3473       28168 :         blocks_list = &matroska->current_cluster.blocks;
    3474       28168 :         blocks      = blocks_list->elem;
    3475             : 
    3476       28168 :         matroska->current_cluster_num_blocks = blocks_list->nb_elem;
    3477       28168 :         i                                    = blocks_list->nb_elem - 1;
    3478       28168 :         if (blocks[i].bin.size > 0 && blocks[i].bin.data) {
    3479       28168 :             int is_keyframe = blocks[i].non_simple ? blocks[i].reference == INT64_MIN : -1;
    3480       56336 :             uint8_t* additional = blocks[i].additional.size > 0 ?
    3481       28168 :                                     blocks[i].additional.data : NULL;
    3482       28168 :             if (!blocks[i].non_simple)
    3483       28021 :                 blocks[i].duration = 0;
    3484      169008 :             res = matroska_parse_block(matroska, blocks[i].bin.buf, blocks[i].bin.data,
    3485       56336 :                                        blocks[i].bin.size, blocks[i].bin.pos,
    3486             :                                        matroska->current_cluster.timecode,
    3487       28168 :                                        blocks[i].duration, is_keyframe,
    3488       28168 :                                        additional, blocks[i].additional_id,
    3489       28168 :                                        blocks[i].additional.size,
    3490             :                                        matroska->current_cluster_pos,
    3491       28168 :                                        blocks[i].discard_padding);
    3492             :         }
    3493             :     }
    3494             : 
    3495       28760 :     return res;
    3496             : }
    3497             : 
    3498       28760 : static int matroska_parse_cluster(MatroskaDemuxContext *matroska)
    3499             : {
    3500       28760 :     MatroskaCluster cluster = { 0 };
    3501             :     EbmlList *blocks_list;
    3502             :     MatroskaBlock *blocks;
    3503             :     int i, res;
    3504             :     int64_t pos;
    3505             : 
    3506       28760 :     if (!matroska->contains_ssa)
    3507       28760 :         return matroska_parse_cluster_incremental(matroska);
    3508           0 :     pos = avio_tell(matroska->ctx->pb);
    3509           0 :     if (matroska->current_id)
    3510           0 :         pos -= 4;  /* sizeof the ID which was already read */
    3511           0 :     res         = ebml_parse(matroska, matroska_clusters, &cluster);
    3512           0 :     blocks_list = &cluster.blocks;
    3513           0 :     blocks      = blocks_list->elem;
    3514           0 :     for (i = 0; i < blocks_list->nb_elem; i++)
    3515           0 :         if (blocks[i].bin.size > 0 && blocks[i].bin.data) {
    3516           0 :             int is_keyframe = blocks[i].non_simple ? blocks[i].reference == INT64_MIN : -1;
    3517           0 :             res = matroska_parse_block(matroska, blocks[i].bin.buf, blocks[i].bin.data,
    3518           0 :                                        blocks[i].bin.size, blocks[i].bin.pos,
    3519           0 :                                        cluster.timecode, blocks[i].duration,
    3520             :                                        is_keyframe, NULL, 0, 0, pos,
    3521           0 :                                        blocks[i].discard_padding);
    3522             :         }
    3523           0 :     ebml_free(matroska_cluster, &cluster);
    3524           0 :     return res;
    3525             : }
    3526             : 
    3527       27101 : static int matroska_read_packet(AVFormatContext *s, AVPacket *pkt)
    3528             : {
    3529       27101 :     MatroskaDemuxContext *matroska = s->priv_data;
    3530       27101 :     int ret = 0;
    3531             : 
    3532       82175 :     while (matroska_deliver_packet(matroska, pkt)) {
    3533       28300 :         int64_t pos = avio_tell(matroska->ctx->pb);
    3534       28300 :         if (matroska->done)
    3535         327 :             return (ret < 0) ? ret : AVERROR_EOF;
    3536       27973 :         if (matroska_parse_cluster(matroska) < 0)
    3537         289 :             ret = matroska_resync(matroska, pos);
    3538             :     }
    3539             : 
    3540       26774 :     return ret;
    3541             : }
    3542             : 
    3543          52 : static int matroska_read_seek(AVFormatContext *s, int stream_index,
    3544             :                               int64_t timestamp, int flags)
    3545             : {
    3546          52 :     MatroskaDemuxContext *matroska = s->priv_data;
    3547          52 :     MatroskaTrack *tracks = NULL;
    3548          52 :     AVStream *st = s->streams[stream_index];
    3549             :     int i, index, index_min;
    3550             : 
    3551             :     /* Parse the CUES now since we need the index data to seek. */
    3552          52 :     if (matroska->cues_parsing_deferred > 0) {
    3553           2 :         matroska->cues_parsing_deferred = 0;
    3554           2 :         matroska_parse_cues(matroska);
    3555             :     }
    3556             : 
    3557          52 :     if (!st->nb_index_entries)
    3558           0 :         goto err;
    3559          52 :     timestamp = FFMAX(timestamp, st->index_entries[0].timestamp);
    3560             : 
    3561          52 :     if ((index = av_index_search_timestamp(st, timestamp, flags)) < 0 || index == st->nb_index_entries - 1) {
    3562          27 :         avio_seek(s->pb, st->index_entries[st->nb_index_entries - 1].pos,
    3563             :                   SEEK_SET);
    3564          27 :         matroska->current_id = 0;
    3565         736 :         while ((index = av_index_search_timestamp(st, timestamp, flags)) < 0 || index == st->nb_index_entries - 1) {
    3566         708 :             matroska_clear_queue(matroska);
    3567         708 :             if (matroska_parse_cluster(matroska) < 0)
    3568          26 :                 break;
    3569             :         }
    3570             :     }
    3571             : 
    3572          52 :     matroska_clear_queue(matroska);
    3573          52 :     if (index < 0 || (matroska->cues_parsing_deferred < 0 && index == st->nb_index_entries - 1))
    3574             :         goto err;
    3575             : 
    3576          42 :     index_min = index;
    3577          42 :     tracks = matroska->tracks.elem;
    3578         105 :     for (i = 0; i < matroska->tracks.nb_elem; i++) {
    3579          63 :         tracks[i].audio.pkt_cnt        = 0;
    3580          63 :         tracks[i].audio.sub_packet_cnt = 0;
    3581          63 :         tracks[i].audio.buf_timecode   = AV_NOPTS_VALUE;
    3582          63 :         tracks[i].end_timecode         = 0;
    3583             :     }
    3584             : 
    3585          42 :     avio_seek(s->pb, st->index_entries[index_min].pos, SEEK_SET);
    3586          42 :     matroska->current_id       = 0;
    3587          42 :     if (flags & AVSEEK_FLAG_ANY) {
    3588           0 :         st->skip_to_keyframe = 0;
    3589           0 :         matroska->skip_to_timecode = timestamp;
    3590             :     } else {
    3591          42 :         st->skip_to_keyframe = 1;
    3592          42 :         matroska->skip_to_timecode = st->index_entries[index].timestamp;
    3593             :     }
    3594          42 :     matroska->skip_to_keyframe = 1;
    3595          42 :     matroska->done             = 0;
    3596          42 :     matroska->num_levels       = 0;
    3597          42 :     ff_update_cur_dts(s, st, st->index_entries[index].timestamp);
    3598          42 :     return 0;
    3599          10 : err:
    3600             :     // slightly hackish but allows proper fallback to
    3601             :     // the generic seeking code.
    3602          10 :     matroska_clear_queue(matroska);
    3603          10 :     matroska->current_id = 0;
    3604          10 :     st->skip_to_keyframe =
    3605          10 :     matroska->skip_to_keyframe = 0;
    3606          10 :     matroska->done = 0;
    3607          10 :     matroska->num_levels = 0;
    3608          10 :     return -1;
    3609             : }
    3610             : 
    3611         296 : static int matroska_read_close(AVFormatContext *s)
    3612             : {
    3613         296 :     MatroskaDemuxContext *matroska = s->priv_data;
    3614         296 :     MatroskaTrack *tracks = matroska->tracks.elem;
    3615             :     int n;
    3616             : 
    3617         296 :     matroska_clear_queue(matroska);
    3618             : 
    3619         604 :     for (n = 0; n < matroska->tracks.nb_elem; n++)
    3620         308 :         if (tracks[n].type == MATROSKA_TRACK_TYPE_AUDIO)
    3621          37 :             av_freep(&tracks[n].audio.buf);
    3622         296 :     ebml_free(matroska_cluster, &matroska->current_cluster);
    3623         296 :     ebml_free(matroska_segment, matroska);
    3624             : 
    3625         296 :     return 0;
    3626             : }
    3627             : 
    3628             : typedef struct {
    3629             :     int64_t start_time_ns;
    3630             :     int64_t end_time_ns;
    3631             :     int64_t start_offset;
    3632             :     int64_t end_offset;
    3633             : } CueDesc;
    3634             : 
    3635             : /* This function searches all the Cues and returns the CueDesc corresponding to
    3636             :  * the timestamp ts. Returned CueDesc will be such that start_time_ns <= ts <
    3637             :  * end_time_ns. All 4 fields will be set to -1 if ts >= file's duration.
    3638             :  */
    3639        4051 : static CueDesc get_cue_desc(AVFormatContext *s, int64_t ts, int64_t cues_start) {
    3640        4051 :     MatroskaDemuxContext *matroska = s->priv_data;
    3641             :     CueDesc cue_desc;
    3642             :     int i;
    3643        4051 :     int nb_index_entries = s->streams[0]->nb_index_entries;
    3644        4051 :     AVIndexEntry *index_entries = s->streams[0]->index_entries;
    3645        4051 :     if (ts >= matroska->duration * matroska->time_scale) return (CueDesc) {-1, -1, -1, -1};
    3646       45391 :     for (i = 1; i < nb_index_entries; i++) {
    3647       90470 :         if (index_entries[i - 1].timestamp * matroska->time_scale <= ts &&
    3648       45235 :             index_entries[i].timestamp * matroska->time_scale > ts) {
    3649        3794 :             break;
    3650             :         }
    3651             :     }
    3652        3950 :     --i;
    3653        3950 :     cue_desc.start_time_ns = index_entries[i].timestamp * matroska->time_scale;
    3654        3950 :     cue_desc.start_offset = index_entries[i].pos - matroska->segment_start;
    3655        3950 :     if (i != nb_index_entries - 1) {
    3656        3794 :         cue_desc.end_time_ns = index_entries[i + 1].timestamp * matroska->time_scale;
    3657        3794 :         cue_desc.end_offset = index_entries[i + 1].pos - matroska->segment_start;
    3658             :     } else {
    3659         156 :         cue_desc.end_time_ns = matroska->duration * matroska->time_scale;
    3660             :         // FIXME: this needs special handling for files where Cues appear
    3661             :         // before Clusters. the current logic assumes Cues appear after
    3662             :         // Clusters.
    3663         156 :         cue_desc.end_offset = cues_start - matroska->segment_start;
    3664             :     }
    3665        3950 :     return cue_desc;
    3666             : }
    3667             : 
    3668          10 : static int webm_clusters_start_with_keyframe(AVFormatContext *s)
    3669             : {
    3670          10 :     MatroskaDemuxContext *matroska = s->priv_data;
    3671             :     int64_t cluster_pos, before_pos;
    3672          10 :     int index, rv = 1;
    3673          10 :     if (s->streams[0]->nb_index_entries <= 0) return 0;
    3674             :     // seek to the first cluster using cues.
    3675          10 :     index = av_index_search_timestamp(s->streams[0], 0, 0);
    3676          10 :     if (index < 0)  return 0;
    3677          10 :     cluster_pos = s->streams[0]->index_entries[index].pos;
    3678          10 :     before_pos = avio_tell(s->pb);
    3679          78 :     while (1) {
    3680          88 :         int64_t cluster_id = 0, cluster_length = 0;
    3681             :         AVPacket *pkt;
    3682          88 :         avio_seek(s->pb, cluster_pos, SEEK_SET);
    3683             :         // read cluster id and length
    3684          88 :         ebml_read_num(matroska, matroska->ctx->pb, 4, &cluster_id);
    3685          88 :         ebml_read_length(matroska, matroska->ctx->pb, &cluster_length);
    3686          88 :         if (cluster_id != 0xF43B675) { // done with all clusters
    3687          19 :             break;
    3688             :         }
    3689          79 :         avio_seek(s->pb, cluster_pos, SEEK_SET);
    3690          79 :         matroska->current_id = 0;
    3691          79 :         matroska_clear_queue(matroska);
    3692         158 :         if (matroska_parse_cluster(matroska) < 0 ||
    3693          79 :             !matroska->queue) {
    3694             :             break;
    3695             :         }
    3696          79 :         pkt = &matroska->queue->pkt;
    3697          79 :         cluster_pos += cluster_length + 12; // 12 is the offset of the cluster id and length.
    3698          79 :         if (!(pkt->flags & AV_PKT_FLAG_KEY)) {
    3699           1 :             rv = 0;
    3700           1 :             break;
    3701             :         }
    3702             :     }
    3703          10 :     avio_seek(s->pb, before_pos, SEEK_SET);
    3704          10 :     return rv;
    3705             : }
    3706             : 
    3707         555 : static int buffer_size_after_time_downloaded(int64_t time_ns, double search_sec, int64_t bps,
    3708             :                                              double min_buffer, double* buffer,
    3709             :                                              double* sec_to_download, AVFormatContext *s,
    3710             :                                              int64_t cues_start)
    3711             : {
    3712         555 :     double nano_seconds_per_second = 1000000000.0;
    3713         555 :     double time_sec = time_ns / nano_seconds_per_second;
    3714         555 :     int rv = 0;
    3715         555 :     int64_t time_to_search_ns = (int64_t)(search_sec * nano_seconds_per_second);
    3716         555 :     int64_t end_time_ns = time_ns + time_to_search_ns;
    3717         555 :     double sec_downloaded = 0.0;
    3718         555 :     CueDesc desc_curr = get_cue_desc(s, time_ns, cues_start);
    3719         555 :     if (desc_curr.start_time_ns == -1)
    3720           0 :       return -1;
    3721         555 :     *sec_to_download = 0.0;
    3722             : 
    3723             :     // Check for non cue start time.
    3724         555 :     if (time_ns > desc_curr.start_time_ns) {
    3725         513 :       int64_t cue_nano = desc_curr.end_time_ns - time_ns;
    3726         513 :       double percent = (double)(cue_nano) / (desc_curr.end_time_ns - desc_curr.start_time_ns);
    3727         513 :       double cueBytes = (desc_curr.end_offset - desc_curr.start_offset) * percent;
    3728         513 :       double timeToDownload = (cueBytes * 8.0) / bps;
    3729             : 
    3730         513 :       sec_downloaded += (cue_nano / nano_seconds_per_second) - timeToDownload;
    3731         513 :       *sec_to_download += timeToDownload;
    3732             : 
    3733             :       // Check if the search ends within the first cue.
    3734         513 :       if (desc_curr.end_time_ns >= end_time_ns) {
    3735           0 :           double desc_end_time_sec = desc_curr.end_time_ns / nano_seconds_per_second;
    3736           0 :           double percent_to_sub = search_sec / (desc_end_time_sec - time_sec);
    3737           0 :           sec_downloaded = percent_to_sub * sec_downloaded;
    3738           0 :           *sec_to_download = percent_to_sub * *sec_to_download;
    3739             :       }
    3740             : 
    3741         513 :       if ((sec_downloaded + *buffer) <= min_buffer) {
    3742           4 :           return 1;
    3743             :       }
    3744             : 
    3745             :       // Get the next Cue.
    3746         509 :       desc_curr = get_cue_desc(s, desc_curr.end_time_ns, cues_start);
    3747             :     }
    3748             : 
    3749        3507 :     while (desc_curr.start_time_ns != -1) {
    3750        2856 :         int64_t desc_bytes = desc_curr.end_offset - desc_curr.start_offset;
    3751        2856 :         int64_t desc_ns = desc_curr.end_time_ns - desc_curr.start_time_ns;
    3752        2856 :         double desc_sec = desc_ns / nano_seconds_per_second;
    3753        2856 :         double bits = (desc_bytes * 8.0);
    3754        2856 :         double time_to_download = bits / bps;
    3755             : 
    3756        2856 :         sec_downloaded += desc_sec - time_to_download;
    3757        2856 :         *sec_to_download += time_to_download;
    3758             : 
    3759        2856 :         if (desc_curr.end_time_ns >= end_time_ns) {
    3760           0 :             double desc_end_time_sec = desc_curr.end_time_ns / nano_seconds_per_second;
    3761           0 :             double percent_to_sub = search_sec / (desc_end_time_sec - time_sec);
    3762           0 :             sec_downloaded = percent_to_sub * sec_downloaded;
    3763           0 :             *sec_to_download = percent_to_sub * *sec_to_download;
    3764             : 
    3765           0 :             if ((sec_downloaded + *buffer) <= min_buffer)
    3766           0 :                 rv = 1;
    3767           0 :             break;
    3768             :         }
    3769             : 
    3770        2856 :         if ((sec_downloaded + *buffer) <= min_buffer) {
    3771         451 :             rv = 1;
    3772         451 :             break;
    3773             :         }
    3774             : 
    3775        2405 :         desc_curr = get_cue_desc(s, desc_curr.end_time_ns, cues_start);
    3776             :     }
    3777         551 :     *buffer = *buffer + sec_downloaded;
    3778         551 :     return rv;
    3779             : }
    3780             : 
    3781             : /* This function computes the bandwidth of the WebM file with the help of
    3782             :  * buffer_size_after_time_downloaded() function. Both of these functions are
    3783             :  * adapted from WebM Tools project and are adapted to work with FFmpeg's
    3784             :  * Matroska parsing mechanism.
    3785             :  *
    3786             :  * Returns the bandwidth of the file on success; -1 on error.
    3787             :  * */
    3788          10 : static int64_t webm_dash_manifest_compute_bandwidth(AVFormatContext *s, int64_t cues_start)
    3789             : {
    3790          10 :     MatroskaDemuxContext *matroska = s->priv_data;
    3791          10 :     AVStream *st = s->streams[0];
    3792          10 :     double bandwidth = 0.0;
    3793             :     int i;
    3794             : 
    3795         222 :     for (i = 0; i < st->nb_index_entries; i++) {
    3796         101 :         int64_t prebuffer_ns = 1000000000;
    3797         101 :         int64_t time_ns = st->index_entries[i].timestamp * matroska->time_scale;
    3798         101 :         double nano_seconds_per_second = 1000000000.0;
    3799         101 :         int64_t prebuffered_ns = time_ns + prebuffer_ns;
    3800         101 :         double prebuffer_bytes = 0.0;
    3801         101 :         int64_t temp_prebuffer_ns = prebuffer_ns;
    3802             :         int64_t pre_bytes, pre_ns;
    3803             :         double pre_sec, prebuffer, bits_per_second;
    3804         101 :         CueDesc desc_beg = get_cue_desc(s, time_ns, cues_start);
    3805             : 
    3806             :         // Start with the first Cue.
    3807         101 :         CueDesc desc_end = desc_beg;
    3808             : 
    3809             :         // Figure out how much data we have downloaded for the prebuffer. This will
    3810             :         // be used later to adjust the bits per sample to try.
    3811         223 :         while (desc_end.start_time_ns != -1 && desc_end.end_time_ns < prebuffered_ns) {
    3812             :             // Prebuffered the entire Cue.
    3813          21 :             prebuffer_bytes += desc_end.end_offset - desc_end.start_offset;
    3814          21 :             temp_prebuffer_ns -= desc_end.end_time_ns - desc_end.start_time_ns;
    3815          21 :             desc_end = get_cue_desc(s, desc_end.end_time_ns, cues_start);
    3816             :         }
    3817         101 :         if (desc_end.start_time_ns == -1) {
    3818             :             // The prebuffer is larger than the duration.
    3819           1 :             if (matroska->duration * matroska->time_scale >= prebuffered_ns)
    3820           0 :               return -1;
    3821           1 :             bits_per_second = 0.0;
    3822             :         } else {
    3823             :             // The prebuffer ends in the last Cue. Estimate how much data was
    3824             :             // prebuffered.
    3825         100 :             pre_bytes = desc_end.end_offset - desc_end.start_offset;
    3826         100 :             pre_ns = desc_end.end_time_ns - desc_end.start_time_ns;
    3827         100 :             pre_sec = pre_ns / nano_seconds_per_second;
    3828         100 :             prebuffer_bytes +=
    3829         100 :                 pre_bytes * ((temp_prebuffer_ns / nano_seconds_per_second) / pre_sec);
    3830             : 
    3831         100 :             prebuffer = prebuffer_ns / nano_seconds_per_second;
    3832             : 
    3833             :             // Set this to 0.0 in case our prebuffer buffers the entire video.
    3834         100 :             bits_per_second = 0.0;
    3835             :             do {
    3836         560 :                 int64_t desc_bytes = desc_end.end_offset - desc_beg.start_offset;
    3837         560 :                 int64_t desc_ns = desc_end.end_time_ns - desc_beg.start_time_ns;
    3838         560 :                 double desc_sec = desc_ns / nano_seconds_per_second;
    3839         560 :                 double calc_bits_per_second = (desc_bytes * 8) / desc_sec;
    3840             : 
    3841             :                 // Drop the bps by the percentage of bytes buffered.
    3842         560 :                 double percent = (desc_bytes - prebuffer_bytes) / desc_bytes;
    3843         560 :                 double mod_bits_per_second = calc_bits_per_second * percent;
    3844             : 
    3845         560 :                 if (prebuffer < desc_sec) {
    3846         555 :                     double search_sec =
    3847         555 :                         (double)(matroska->duration * matroska->time_scale) / nano_seconds_per_second;
    3848             : 
    3849             :                     // Add 1 so the bits per second should be a little bit greater than file
    3850             :                     // datarate.
    3851         555 :                     int64_t bps = (int64_t)(mod_bits_per_second) + 1;
    3852         555 :                     const double min_buffer = 0.0;
    3853         555 :                     double buffer = prebuffer;
    3854         555 :                     double sec_to_download = 0.0;
    3855             : 
    3856         555 :                     int rv = buffer_size_after_time_downloaded(prebuffered_ns, search_sec, bps,
    3857             :                                                                min_buffer, &buffer, &sec_to_download,
    3858             :                                                                s, cues_start);
    3859         555 :                     if (rv < 0) {
    3860           0 :                         return -1;
    3861         555 :                     } else if (rv == 0) {
    3862         100 :                         bits_per_second = (double)(bps);
    3863         100 :                         break;
    3864             :                     }
    3865             :                 }
    3866             : 
    3867         460 :                 desc_end = get_cue_desc(s, desc_end.end_time_ns, cues_start);
    3868         460 :             } while (desc_end.start_time_ns != -1);
    3869             :         }
    3870         101 :         if (bandwidth < bits_per_second) bandwidth = bits_per_second;
    3871             :     }
    3872          10 :     return (int64_t)bandwidth;
    3873             : }
    3874             : 
    3875          10 : static int webm_dash_manifest_cues(AVFormatContext *s, int64_t init_range)
    3876             : {
    3877          10 :     MatroskaDemuxContext *matroska = s->priv_data;
    3878          10 :     EbmlList *seekhead_list = &matroska->seekhead;
    3879          10 :     MatroskaSeekhead *seekhead = seekhead_list->elem;
    3880             :     char *buf;
    3881          10 :     int64_t cues_start = -1, cues_end = -1, before_pos, bandwidth;
    3882             :     int i;
    3883          10 :     int end = 0;
    3884             : 
    3885             :     // determine cues start and end positions
    3886          34 :     for (i = 0; i < seekhead_list->nb_elem; i++)
    3887          34 :         if (seekhead[i].id == MATROSKA_ID_CUES)
    3888          10 :             break;
    3889             : 
    3890          10 :     if (i >= seekhead_list->nb_elem) return -1;
    3891             : 
    3892          10 :     before_pos = avio_tell(matroska->ctx->pb);
    3893          10 :     cues_start = seekhead[i].pos + matroska->segment_start;
    3894          10 :     if (avio_seek(matroska->ctx->pb, cues_start, SEEK_SET) == cues_start) {
    3895             :         // cues_end is computed as cues_start + cues_length + length of the
    3896             :         // Cues element ID + EBML length of the Cues element. cues_end is
    3897             :         // inclusive and the above sum is reduced by 1.
    3898          10 :         uint64_t cues_length = 0, cues_id = 0, bytes_read = 0;
    3899          10 :         bytes_read += ebml_read_num(matroska, matroska->ctx->pb, 4, &cues_id);
    3900          10 :         bytes_read += ebml_read_length(matroska, matroska->ctx->pb, &cues_length);
    3901          10 :         cues_end = cues_start + cues_length + bytes_read - 1;
    3902             :     }
    3903          10 :     avio_seek(matroska->ctx->pb, before_pos, SEEK_SET);
    3904          10 :     if (cues_start == -1 || cues_end == -1) return -1;
    3905             : 
    3906             :     // parse the cues
    3907          10 :     matroska_parse_cues(matroska);
    3908             : 
    3909             :     // cues start
    3910          10 :     av_dict_set_int(&s->streams[0]->metadata, CUES_START, cues_start, 0);
    3911             : 
    3912             :     // cues end
    3913          10 :     av_dict_set_int(&s->streams[0]->metadata, CUES_END, cues_end, 0);
    3914             : 
    3915             :     // if the file has cues at the start, fix up the init range so tht
    3916             :     // it does not include it
    3917          10 :     if (cues_start <= init_range)
    3918           0 :         av_dict_set_int(&s->streams[0]->metadata, INITIALIZATION_RANGE, cues_start - 1, 0);
    3919             : 
    3920             :     // bandwidth
    3921          10 :     bandwidth = webm_dash_manifest_compute_bandwidth(s, cues_start);
    3922          10 :     if (bandwidth < 0) return -1;
    3923          10 :     av_dict_set_int(&s->streams[0]->metadata, BANDWIDTH, bandwidth, 0);
    3924             : 
    3925             :     // check if all clusters start with key frames
    3926          10 :     av_dict_set_int(&s->streams[0]->metadata, CLUSTER_KEYFRAME, webm_clusters_start_with_keyframe(s), 0);
    3927             : 
    3928             :     // store cue point timestamps as a comma separated list for checking subsegment alignment in
    3929             :     // the muxer. assumes that each timestamp cannot be more than 20 characters long.
    3930          10 :     buf = av_malloc_array(s->streams[0]->nb_index_entries, 20 * sizeof(char));
    3931          10 :     if (!buf) return -1;
    3932          10 :     strcpy(buf, "");
    3933         111 :     for (i = 0; i < s->streams[0]->nb_index_entries; i++) {
    3934         101 :         int ret = snprintf(buf + end, 20 * sizeof(char),
    3935         101 :                            "%" PRId64, s->streams[0]->index_entries[i].timestamp);
    3936         101 :         if (ret <= 0 || (ret == 20 && i ==  s->streams[0]->nb_index_entries - 1)) {
    3937           0 :             av_log(s, AV_LOG_ERROR, "timestamp too long.\n");
    3938           0 :             av_free(buf);
    3939           0 :             return AVERROR_INVALIDDATA;
    3940             :         }
    3941         101 :         end += ret;
    3942         101 :         if (i != s->streams[0]->nb_index_entries - 1) {
    3943          91 :             strncat(buf, ",", sizeof(char));
    3944          91 :             end++;
    3945             :         }
    3946             :     }
    3947          10 :     av_dict_set(&s->streams[0]->metadata, CUE_TIMESTAMPS, buf, 0);
    3948          10 :     av_free(buf);
    3949             : 
    3950          10 :     return 0;
    3951             : }
    3952             : 
    3953          14 : static int webm_dash_manifest_read_header(AVFormatContext *s)
    3954             : {
    3955             :     char *buf;
    3956          14 :     int ret = matroska_read_header(s);
    3957             :     int64_t init_range;
    3958             :     MatroskaTrack *tracks;
    3959          14 :     MatroskaDemuxContext *matroska = s->priv_data;
    3960          14 :     if (ret) {
    3961           0 :         av_log(s, AV_LOG_ERROR, "Failed to read file headers\n");
    3962           0 :         return -1;
    3963             :     }
    3964          14 :     if (!s->nb_streams) {
    3965           0 :         matroska_read_close(s);
    3966           0 :         av_log(s, AV_LOG_ERROR, "No streams found\n");
    3967           0 :         return AVERROR_INVALIDDATA;
    3968             :     }
    3969             : 
    3970          14 :     if (!matroska->is_live) {
    3971          10 :         buf = av_asprintf("%g", matroska->duration);
    3972          10 :         if (!buf) return AVERROR(ENOMEM);
    3973          10 :         av_dict_set(&s->streams[0]->metadata, DURATION, buf, 0);
    3974          10 :         av_free(buf);
    3975             : 
    3976             :         // initialization range
    3977             :         // 5 is the offset of Cluster ID.
    3978          10 :         init_range = avio_tell(s->pb) - 5;
    3979          10 :         av_dict_set_int(&s->streams[0]->metadata, INITIALIZATION_RANGE, init_range, 0);
    3980             :     }
    3981             : 
    3982             :     // basename of the file
    3983          14 :     buf = strrchr(s->url, '/');
    3984          14 :     av_dict_set(&s->streams[0]->metadata, FILENAME, buf ? ++buf : s->url, 0);
    3985             : 
    3986             :     // track number
    3987          14 :     tracks = matroska->tracks.elem;
    3988          14 :     av_dict_set_int(&s->streams[0]->metadata, TRACK_NUMBER, tracks[0].num, 0);
    3989             : 
    3990             :     // parse the cues and populate Cue related fields
    3991          14 :     if (!matroska->is_live) {
    3992          10 :         ret = webm_dash_manifest_cues(s, init_range);
    3993          10 :         if (ret < 0) {
    3994           0 :             av_log(s, AV_LOG_ERROR, "Error parsing Cues\n");
    3995           0 :             return ret;
    3996             :         }
    3997             :     }
    3998             : 
    3999             :     // use the bandwidth from the command line if it was provided
    4000          14 :     if (matroska->bandwidth > 0) {
    4001           2 :         av_dict_set_int(&s->streams[0]->metadata, BANDWIDTH,
    4002           2 :                         matroska->bandwidth, 0);
    4003             :     }
    4004          14 :     return 0;
    4005             : }
    4006             : 
    4007          28 : static int webm_dash_manifest_read_packet(AVFormatContext *s, AVPacket *pkt)
    4008             : {
    4009          28 :     return AVERROR_EOF;
    4010             : }
    4011             : 
    4012             : #define OFFSET(x) offsetof(MatroskaDemuxContext, x)
    4013             : static const AVOption options[] = {
    4014             :     { "live", "flag indicating that the input is a live file that only has the headers.", OFFSET(is_live), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, AV_OPT_FLAG_DECODING_PARAM },
    4015             :     { "bandwidth", "bandwidth of this stream to be specified in the DASH manifest.", OFFSET(bandwidth), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_DECODING_PARAM },
    4016             :     { NULL },
    4017             : };
    4018             : 
    4019             : static const AVClass webm_dash_class = {
    4020             :     .class_name = "WebM DASH Manifest demuxer",
    4021             :     .item_name  = av_default_item_name,
    4022             :     .option     = options,
    4023             :     .version    = LIBAVUTIL_VERSION_INT,
    4024             : };
    4025             : 
    4026             : AVInputFormat ff_matroska_demuxer = {
    4027             :     .name           = "matroska,webm",
    4028             :     .long_name      = NULL_IF_CONFIG_SMALL("Matroska / WebM"),
    4029             :     .extensions     = "mkv,mk3d,mka,mks",
    4030             :     .priv_data_size = sizeof(MatroskaDemuxContext),
    4031             :     .read_probe     = matroska_probe,
    4032             :     .read_header    = matroska_read_header,
    4033             :     .read_packet    = matroska_read_packet,
    4034             :     .read_close     = matroska_read_close,
    4035             :     .read_seek      = matroska_read_seek,
    4036             :     .mime_type      = "audio/webm,audio/x-matroska,video/webm,video/x-matroska"
    4037             : };
    4038             : 
    4039             : AVInputFormat ff_webm_dash_manifest_demuxer = {
    4040             :     .name           = "webm_dash_manifest",
    4041             :     .long_name      = NULL_IF_CONFIG_SMALL("WebM DASH Manifest"),
    4042             :     .priv_data_size = sizeof(MatroskaDemuxContext),
    4043             :     .read_header    = webm_dash_manifest_read_header,
    4044             :     .read_packet    = webm_dash_manifest_read_packet,
    4045             :     .read_close     = matroska_read_close,
    4046             :     .priv_class     = &webm_dash_class,
    4047             : };

Generated by: LCOV version 1.13