"Fossies" - the Fresh Open Source Software Archive

Member "libav-12.3/libavformat/matroskadec.c" (12 Feb 2018, 99007 Bytes) of package /linux/misc/libav-12.3.tar.gz:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) C and C++ source code syntax highlighting (style: standard) with prefixed line numbers and code folding option. Alternatively you can here view or download the uninterpreted source code file. For more information about "matroskadec.c" see the Fossies "Dox" file reference documentation and the latest Fossies "Diffs" side-by-side code changes report: 12.2_vs_12.3.

    1 /*
    2  * Matroska file demuxer
    3  * Copyright (c) 2003-2008 The Libav Project
    4  *
    5  * This file is part of Libav.
    6  *
    7  * Libav 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  * Libav 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 Libav; 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 #if CONFIG_BZLIB
   36 #include <bzlib.h>
   37 #endif
   38 #if CONFIG_ZLIB
   39 #include <zlib.h>
   40 #endif
   41 
   42 #include "libavutil/avstring.h"
   43 #include "libavutil/dict.h"
   44 #include "libavutil/intfloat.h"
   45 #include "libavutil/intreadwrite.h"
   46 #include "libavutil/lzo.h"
   47 #include "libavutil/mathematics.h"
   48 
   49 #include "libavcodec/bytestream.h"
   50 #include "libavcodec/flac.h"
   51 #include "libavcodec/mpeg4audio.h"
   52 
   53 #include "avformat.h"
   54 #include "avio_internal.h"
   55 #include "internal.h"
   56 #include "isom.h"
   57 #include "matroska.h"
   58 #include "oggdec.h"
   59 /* For ff_codec_get_id(). */
   60 #include "riff.h"
   61 #include "rmsipr.h"
   62 
   63 typedef enum {
   64     EBML_NONE,
   65     EBML_UINT,
   66     EBML_FLOAT,
   67     EBML_STR,
   68     EBML_UTF8,
   69     EBML_BIN,
   70     EBML_NEST,
   71     EBML_PASS,
   72     EBML_STOP,
   73     EBML_TYPE_COUNT
   74 } EbmlType;
   75 
   76 typedef const struct EbmlSyntax {
   77     uint32_t id;
   78     EbmlType type;
   79     int list_elem_size;
   80     int data_offset;
   81     union {
   82         uint64_t    u;
   83         double      f;
   84         const char *s;
   85         const struct EbmlSyntax *n;
   86     } def;
   87 } EbmlSyntax;
   88 
   89 typedef struct EbmlList {
   90     int nb_elem;
   91     void *elem;
   92 } EbmlList;
   93 
   94 typedef struct EbmlBin {
   95     int      size;
   96     uint8_t *data;
   97     int64_t  pos;
   98 } EbmlBin;
   99 
  100 typedef struct Ebml {
  101     uint64_t version;
  102     uint64_t max_size;
  103     uint64_t id_length;
  104     char    *doctype;
  105     uint64_t doctype_version;
  106 } Ebml;
  107 
  108 typedef struct MatroskaTrackCompression {
  109     uint64_t algo;
  110     EbmlBin  settings;
  111 } MatroskaTrackCompression;
  112 
  113 typedef struct MatroskaTrackEncoding {
  114     uint64_t scope;
  115     uint64_t type;
  116     MatroskaTrackCompression compression;
  117 } MatroskaTrackEncoding;
  118 
  119 typedef struct MatroskaTrackVideo {
  120     double   frame_rate;
  121     uint64_t display_width;
  122     uint64_t display_height;
  123     uint64_t pixel_width;
  124     uint64_t pixel_height;
  125     uint64_t fourcc;
  126     uint64_t interlaced;
  127     uint64_t field_order;
  128     uint64_t stereo_mode;
  129 } MatroskaTrackVideo;
  130 
  131 typedef struct MatroskaTrackAudio {
  132     double   samplerate;
  133     double   out_samplerate;
  134     uint64_t bitdepth;
  135     uint64_t channels;
  136 
  137     /* real audio header (extracted from extradata) */
  138     int      coded_framesize;
  139     int      sub_packet_h;
  140     int      frame_size;
  141     int      sub_packet_size;
  142     int      sub_packet_cnt;
  143     int      pkt_cnt;
  144     uint64_t buf_timecode;
  145     uint8_t *buf;
  146 } MatroskaTrackAudio;
  147 
  148 typedef struct MatroskaTrack {
  149     uint64_t num;
  150     uint64_t uid;
  151     uint64_t type;
  152     char    *name;
  153     char    *codec_id;
  154     EbmlBin  codec_priv;
  155     char    *language;
  156     double time_scale;
  157     uint64_t default_duration;
  158     uint64_t flag_default;
  159     uint64_t flag_forced;
  160     MatroskaTrackVideo video;
  161     MatroskaTrackAudio audio;
  162     EbmlList encodings;
  163     uint64_t codec_delay;
  164 
  165     AVStream *stream;
  166     int64_t end_timecode;
  167     int ms_compat;
  168 } MatroskaTrack;
  169 
  170 typedef struct MatroskaAttachment {
  171     uint64_t uid;
  172     char *filename;
  173     char *mime;
  174     EbmlBin bin;
  175 
  176     AVStream *stream;
  177 } MatroskaAttachment;
  178 
  179 typedef struct MatroskaChapter {
  180     uint64_t start;
  181     uint64_t end;
  182     uint64_t uid;
  183     char    *title;
  184 
  185     AVChapter *chapter;
  186 } MatroskaChapter;
  187 
  188 typedef struct MatroskaIndexPos {
  189     uint64_t track;
  190     uint64_t pos;
  191 } MatroskaIndexPos;
  192 
  193 typedef struct MatroskaIndex {
  194     uint64_t time;
  195     EbmlList pos;
  196 } MatroskaIndex;
  197 
  198 typedef struct MatroskaTag {
  199     char *name;
  200     char *string;
  201     char *lang;
  202     uint64_t def;
  203     EbmlList sub;
  204 } MatroskaTag;
  205 
  206 typedef struct MatroskaTagTarget {
  207     char    *type;
  208     uint64_t typevalue;
  209     uint64_t trackuid;
  210     uint64_t chapteruid;
  211     uint64_t attachuid;
  212 } MatroskaTagTarget;
  213 
  214 typedef struct MatroskaTags {
  215     MatroskaTagTarget target;
  216     EbmlList tag;
  217 } MatroskaTags;
  218 
  219 typedef struct MatroskaSeekhead {
  220     uint64_t id;
  221     uint64_t pos;
  222 } MatroskaSeekhead;
  223 
  224 typedef struct MatroskaLevel {
  225     uint64_t start;
  226     uint64_t length;
  227 } MatroskaLevel;
  228 
  229 typedef struct MatroskaCluster {
  230     uint64_t timecode;
  231     EbmlList blocks;
  232 } MatroskaCluster;
  233 
  234 typedef struct MatroskaDemuxContext {
  235     AVFormatContext *ctx;
  236 
  237     /* EBML stuff */
  238     int num_levels;
  239     MatroskaLevel levels[EBML_MAX_DEPTH];
  240     int level_up;
  241     uint32_t current_id;
  242 
  243     uint64_t time_scale;
  244     double   duration;
  245     char    *title;
  246     EbmlList tracks;
  247     EbmlList attachments;
  248     EbmlList chapters;
  249     EbmlList index;
  250     EbmlList tags;
  251     EbmlList seekhead;
  252 
  253     /* byte position of the segment inside the stream */
  254     int64_t segment_start;
  255 
  256     /* the packet queue */
  257     AVPacket **packets;
  258     int num_packets;
  259     AVPacket *prev_pkt;
  260 
  261     int done;
  262 
  263     /* What to skip before effectively reading a packet. */
  264     int skip_to_keyframe;
  265     uint64_t skip_to_timecode;
  266 
  267     /* File has a CUES element, but we defer parsing until it is needed. */
  268     int cues_parsing_deferred;
  269 
  270     int current_cluster_num_blocks;
  271     int64_t current_cluster_pos;
  272     MatroskaCluster current_cluster;
  273 
  274     /* File has SSA subtitles which prevent incremental cluster parsing. */
  275     int contains_ssa;
  276 } MatroskaDemuxContext;
  277 
  278 typedef struct MatroskaBlock {
  279     uint64_t duration;
  280     int64_t  reference;
  281     uint64_t non_simple;
  282     EbmlBin  bin;
  283 } MatroskaBlock;
  284 
  285 static EbmlSyntax ebml_header[] = {
  286     { EBML_ID_EBMLREADVERSION,    EBML_UINT, 0, offsetof(Ebml, version),         { .u = EBML_VERSION } },
  287     { EBML_ID_EBMLMAXSIZELENGTH,  EBML_UINT, 0, offsetof(Ebml, max_size),        { .u = 8 } },
  288     { EBML_ID_EBMLMAXIDLENGTH,    EBML_UINT, 0, offsetof(Ebml, id_length),       { .u = 4 } },
  289     { EBML_ID_DOCTYPE,            EBML_STR,  0, offsetof(Ebml, doctype),         { .s = "(none)" } },
  290     { EBML_ID_DOCTYPEREADVERSION, EBML_UINT, 0, offsetof(Ebml, doctype_version), { .u = 1 } },
  291     { EBML_ID_EBMLVERSION,        EBML_NONE },
  292     { EBML_ID_DOCTYPEVERSION,     EBML_NONE },
  293     { 0 }
  294 };
  295 
  296 static EbmlSyntax ebml_syntax[] = {
  297     { EBML_ID_HEADER, EBML_NEST, 0, 0, { .n = ebml_header } },
  298     { 0 }
  299 };
  300 
  301 static EbmlSyntax matroska_info[] = {
  302     { MATROSKA_ID_TIMECODESCALE, EBML_UINT,  0, offsetof(MatroskaDemuxContext, time_scale), { .u = 1000000 } },
  303     { MATROSKA_ID_DURATION,      EBML_FLOAT, 0, offsetof(MatroskaDemuxContext, duration) },
  304     { MATROSKA_ID_TITLE,         EBML_UTF8,  0, offsetof(MatroskaDemuxContext, title) },
  305     { MATROSKA_ID_WRITINGAPP,    EBML_NONE },
  306     { MATROSKA_ID_MUXINGAPP,     EBML_NONE },
  307     { MATROSKA_ID_DATEUTC,       EBML_NONE },
  308     { MATROSKA_ID_SEGMENTUID,    EBML_NONE },
  309     { 0 }
  310 };
  311 
  312 static EbmlSyntax matroska_track_video[] = {
  313     { MATROSKA_ID_VIDEOFRAMERATE,      EBML_FLOAT, 0, offsetof(MatroskaTrackVideo, frame_rate) },
  314     { MATROSKA_ID_VIDEODISPLAYWIDTH,   EBML_UINT,  0, offsetof(MatroskaTrackVideo, display_width) },
  315     { MATROSKA_ID_VIDEODISPLAYHEIGHT,  EBML_UINT,  0, offsetof(MatroskaTrackVideo, display_height) },
  316     { MATROSKA_ID_VIDEOPIXELWIDTH,     EBML_UINT,  0, offsetof(MatroskaTrackVideo, pixel_width) },
  317     { MATROSKA_ID_VIDEOPIXELHEIGHT,    EBML_UINT,  0, offsetof(MatroskaTrackVideo, pixel_height) },
  318     { MATROSKA_ID_VIDEOCOLORSPACE,     EBML_UINT,  0, offsetof(MatroskaTrackVideo, fourcc) },
  319     { MATROSKA_ID_VIDEOPIXELCROPB,     EBML_NONE },
  320     { MATROSKA_ID_VIDEOPIXELCROPT,     EBML_NONE },
  321     { MATROSKA_ID_VIDEOPIXELCROPL,     EBML_NONE },
  322     { MATROSKA_ID_VIDEOPIXELCROPR,     EBML_NONE },
  323     { MATROSKA_ID_VIDEODISPLAYUNIT,    EBML_NONE },
  324     { MATROSKA_ID_VIDEOFLAGINTERLACED, EBML_UINT,  0, offsetof(MatroskaTrackVideo, interlaced),  { .u = MATROSKA_VIDEO_INTERLACE_FLAG_UNDETERMINED } },
  325     { MATROSKA_ID_VIDEOFIELDORDER,     EBML_UINT,  0, offsetof(MatroskaTrackVideo, field_order), { .u = MATROSKA_VIDEO_FIELDORDER_UNDETERMINED } },
  326     { MATROSKA_ID_VIDEOSTEREOMODE,     EBML_UINT,  0, offsetof(MatroskaTrackVideo, stereo_mode), { .u = MATROSKA_VIDEO_STEREOMODE_TYPE_NB } },
  327     { MATROSKA_ID_VIDEOASPECTRATIO,    EBML_NONE },
  328     { 0 }
  329 };
  330 
  331 static EbmlSyntax matroska_track_audio[] = {
  332     { MATROSKA_ID_AUDIOSAMPLINGFREQ,    EBML_FLOAT, 0, offsetof(MatroskaTrackAudio, samplerate), { .f = 8000.0 } },
  333     { MATROSKA_ID_AUDIOOUTSAMPLINGFREQ, EBML_FLOAT, 0, offsetof(MatroskaTrackAudio, out_samplerate) },
  334     { MATROSKA_ID_AUDIOBITDEPTH,        EBML_UINT,  0, offsetof(MatroskaTrackAudio, bitdepth) },
  335     { MATROSKA_ID_AUDIOCHANNELS,        EBML_UINT,  0, offsetof(MatroskaTrackAudio, channels),   { .u = 1 } },
  336     { 0 }
  337 };
  338 
  339 static EbmlSyntax matroska_track_encoding_compression[] = {
  340     { MATROSKA_ID_ENCODINGCOMPALGO,     EBML_UINT, 0, offsetof(MatroskaTrackCompression, algo), { .u = 0 } },
  341     { MATROSKA_ID_ENCODINGCOMPSETTINGS, EBML_BIN,  0, offsetof(MatroskaTrackCompression, settings) },
  342     { 0 }
  343 };
  344 
  345 static EbmlSyntax matroska_track_encoding[] = {
  346     { MATROSKA_ID_ENCODINGSCOPE,       EBML_UINT, 0, offsetof(MatroskaTrackEncoding, scope),       { .u = 1 } },
  347     { MATROSKA_ID_ENCODINGTYPE,        EBML_UINT, 0, offsetof(MatroskaTrackEncoding, type),        { .u = 0 } },
  348     { MATROSKA_ID_ENCODINGCOMPRESSION, EBML_NEST, 0, offsetof(MatroskaTrackEncoding, compression), { .n = matroska_track_encoding_compression } },
  349     { MATROSKA_ID_ENCODINGORDER,       EBML_NONE },
  350     { 0 }
  351 };
  352 
  353 static EbmlSyntax matroska_track_encodings[] = {
  354     { MATROSKA_ID_TRACKCONTENTENCODING, EBML_NEST, sizeof(MatroskaTrackEncoding), offsetof(MatroskaTrack, encodings), { .n = matroska_track_encoding } },
  355     { 0 }
  356 };
  357 
  358 static EbmlSyntax matroska_track[] = {
  359     { MATROSKA_ID_TRACKNUMBER,           EBML_UINT,  0, offsetof(MatroskaTrack, num) },
  360     { MATROSKA_ID_TRACKNAME,             EBML_UTF8,  0, offsetof(MatroskaTrack, name) },
  361     { MATROSKA_ID_TRACKUID,              EBML_UINT,  0, offsetof(MatroskaTrack, uid) },
  362     { MATROSKA_ID_TRACKTYPE,             EBML_UINT,  0, offsetof(MatroskaTrack, type) },
  363     { MATROSKA_ID_CODECID,               EBML_STR,   0, offsetof(MatroskaTrack, codec_id) },
  364     { MATROSKA_ID_CODECPRIVATE,          EBML_BIN,   0, offsetof(MatroskaTrack, codec_priv) },
  365     { MATROSKA_ID_CODECDELAY,            EBML_UINT,  0, offsetof(MatroskaTrack, codec_delay) },
  366     { MATROSKA_ID_TRACKLANGUAGE,         EBML_UTF8,  0, offsetof(MatroskaTrack, language),     { .s = "eng"  } },
  367     { MATROSKA_ID_TRACKDEFAULTDURATION,  EBML_UINT,  0, offsetof(MatroskaTrack, default_duration) },
  368     { MATROSKA_ID_TRACKTIMECODESCALE,    EBML_FLOAT, 0, offsetof(MatroskaTrack, time_scale),   { .f = 1.0  } },
  369     { MATROSKA_ID_TRACKFLAGDEFAULT,      EBML_UINT,  0, offsetof(MatroskaTrack, flag_default), { .u = 1  } },
  370     { MATROSKA_ID_TRACKFLAGFORCED,       EBML_UINT,  0, offsetof(MatroskaTrack, flag_forced),  { .u = 0   } },
  371     { MATROSKA_ID_TRACKVIDEO,            EBML_NEST,  0, offsetof(MatroskaTrack, video),        { .n = matroska_track_video } },
  372     { MATROSKA_ID_TRACKAUDIO,            EBML_NEST,  0, offsetof(MatroskaTrack, audio),        { .n = matroska_track_audio } },
  373     { MATROSKA_ID_TRACKCONTENTENCODINGS, EBML_NEST,  0, 0,                                     { .n = matroska_track_encodings } },
  374     { MATROSKA_ID_TRACKFLAGENABLED,      EBML_NONE },
  375     { MATROSKA_ID_TRACKFLAGLACING,       EBML_NONE },
  376     { MATROSKA_ID_CODECNAME,             EBML_NONE },
  377     { MATROSKA_ID_CODECDECODEALL,        EBML_NONE },
  378     { MATROSKA_ID_CODECINFOURL,          EBML_NONE },
  379     { MATROSKA_ID_CODECDOWNLOADURL,      EBML_NONE },
  380     { MATROSKA_ID_TRACKMINCACHE,         EBML_NONE },
  381     { MATROSKA_ID_TRACKMAXCACHE,         EBML_NONE },
  382     { MATROSKA_ID_TRACKMAXBLKADDID,      EBML_NONE },
  383     { 0 }
  384 };
  385 
  386 static EbmlSyntax matroska_tracks[] = {
  387     { MATROSKA_ID_TRACKENTRY, EBML_NEST, sizeof(MatroskaTrack), offsetof(MatroskaDemuxContext, tracks), { .n = matroska_track } },
  388     { 0 }
  389 };
  390 
  391 static EbmlSyntax matroska_attachment[] = {
  392     { MATROSKA_ID_FILEUID,      EBML_UINT, 0, offsetof(MatroskaAttachment, uid) },
  393     { MATROSKA_ID_FILENAME,     EBML_UTF8, 0, offsetof(MatroskaAttachment, filename) },
  394     { MATROSKA_ID_FILEMIMETYPE, EBML_STR,  0, offsetof(MatroskaAttachment, mime) },
  395     { MATROSKA_ID_FILEDATA,     EBML_BIN,  0, offsetof(MatroskaAttachment, bin) },
  396     { MATROSKA_ID_FILEDESC,     EBML_NONE },
  397     { 0 }
  398 };
  399 
  400 static EbmlSyntax matroska_attachments[] = {
  401     { MATROSKA_ID_ATTACHEDFILE, EBML_NEST, sizeof(MatroskaAttachment), offsetof(MatroskaDemuxContext, attachments), { .n = matroska_attachment } },
  402     { 0 }
  403 };
  404 
  405 static EbmlSyntax matroska_chapter_display[] = {
  406     { MATROSKA_ID_CHAPSTRING, EBML_UTF8, 0, offsetof(MatroskaChapter, title) },
  407     { MATROSKA_ID_CHAPLANG,   EBML_NONE },
  408     { 0 }
  409 };
  410 
  411 static EbmlSyntax matroska_chapter_entry[] = {
  412     { MATROSKA_ID_CHAPTERTIMESTART,   EBML_UINT, 0, offsetof(MatroskaChapter, start), { .u = AV_NOPTS_VALUE } },
  413     { MATROSKA_ID_CHAPTERTIMEEND,     EBML_UINT, 0, offsetof(MatroskaChapter, end),   { .u = AV_NOPTS_VALUE } },
  414     { MATROSKA_ID_CHAPTERUID,         EBML_UINT, 0, offsetof(MatroskaChapter, uid) },
  415     { MATROSKA_ID_CHAPTERDISPLAY,     EBML_NEST, 0,                        0,         { .n = matroska_chapter_display } },
  416     { MATROSKA_ID_CHAPTERFLAGHIDDEN,  EBML_NONE },
  417     { MATROSKA_ID_CHAPTERFLAGENABLED, EBML_NONE },
  418     { MATROSKA_ID_CHAPTERPHYSEQUIV,   EBML_NONE },
  419     { MATROSKA_ID_CHAPTERATOM,        EBML_NONE },
  420     { 0 }
  421 };
  422 
  423 static EbmlSyntax matroska_chapter[] = {
  424     { MATROSKA_ID_CHAPTERATOM,        EBML_NEST, sizeof(MatroskaChapter), offsetof(MatroskaDemuxContext, chapters), { .n = matroska_chapter_entry } },
  425     { MATROSKA_ID_EDITIONUID,         EBML_NONE },
  426     { MATROSKA_ID_EDITIONFLAGHIDDEN,  EBML_NONE },
  427     { MATROSKA_ID_EDITIONFLAGDEFAULT, EBML_NONE },
  428     { MATROSKA_ID_EDITIONFLAGORDERED, EBML_NONE },
  429     { 0 }
  430 };
  431 
  432 static EbmlSyntax matroska_chapters[] = {
  433     { MATROSKA_ID_EDITIONENTRY, EBML_NEST, 0, 0, { .n = matroska_chapter } },
  434     { 0 }
  435 };
  436 
  437 static EbmlSyntax matroska_index_pos[] = {
  438     { MATROSKA_ID_CUETRACK,           EBML_UINT, 0, offsetof(MatroskaIndexPos, track) },
  439     { MATROSKA_ID_CUECLUSTERPOSITION, EBML_UINT, 0, offsetof(MatroskaIndexPos, pos) },
  440     { MATROSKA_ID_CUEBLOCKNUMBER,     EBML_NONE },
  441     { 0 }
  442 };
  443 
  444 static EbmlSyntax matroska_index_entry[] = {
  445     { MATROSKA_ID_CUETIME,          EBML_UINT, 0,                        offsetof(MatroskaIndex, time) },
  446     { MATROSKA_ID_CUETRACKPOSITION, EBML_NEST, sizeof(MatroskaIndexPos), offsetof(MatroskaIndex, pos), { .n = matroska_index_pos } },
  447     { 0 }
  448 };
  449 
  450 static EbmlSyntax matroska_index[] = {
  451     { MATROSKA_ID_POINTENTRY, EBML_NEST, sizeof(MatroskaIndex), offsetof(MatroskaDemuxContext, index), { .n = matroska_index_entry } },
  452     { 0 }
  453 };
  454 
  455 static EbmlSyntax matroska_simpletag[] = {
  456     { MATROSKA_ID_TAGNAME,        EBML_UTF8, 0,                   offsetof(MatroskaTag, name) },
  457     { MATROSKA_ID_TAGSTRING,      EBML_UTF8, 0,                   offsetof(MatroskaTag, string) },
  458     { MATROSKA_ID_TAGLANG,        EBML_STR,  0,                   offsetof(MatroskaTag, lang), { .s = "und" } },
  459     { MATROSKA_ID_TAGDEFAULT,     EBML_UINT, 0,                   offsetof(MatroskaTag, def) },
  460     { MATROSKA_ID_TAGDEFAULT_BUG, EBML_UINT, 0,                   offsetof(MatroskaTag, def) },
  461     { MATROSKA_ID_SIMPLETAG,      EBML_NEST, sizeof(MatroskaTag), offsetof(MatroskaTag, sub),  { .n = matroska_simpletag } },
  462     { 0 }
  463 };
  464 
  465 static EbmlSyntax matroska_tagtargets[] = {
  466     { MATROSKA_ID_TAGTARGETS_TYPE,       EBML_STR,  0, offsetof(MatroskaTagTarget, type) },
  467     { MATROSKA_ID_TAGTARGETS_TYPEVALUE,  EBML_UINT, 0, offsetof(MatroskaTagTarget, typevalue), { .u = 50 } },
  468     { MATROSKA_ID_TAGTARGETS_TRACKUID,   EBML_UINT, 0, offsetof(MatroskaTagTarget, trackuid) },
  469     { MATROSKA_ID_TAGTARGETS_CHAPTERUID, EBML_UINT, 0, offsetof(MatroskaTagTarget, chapteruid) },
  470     { MATROSKA_ID_TAGTARGETS_ATTACHUID,  EBML_UINT, 0, offsetof(MatroskaTagTarget, attachuid) },
  471     { 0 }
  472 };
  473 
  474 static EbmlSyntax matroska_tag[] = {
  475     { MATROSKA_ID_SIMPLETAG,  EBML_NEST, sizeof(MatroskaTag), offsetof(MatroskaTags, tag),    { .n = matroska_simpletag } },
  476     { MATROSKA_ID_TAGTARGETS, EBML_NEST, 0,                   offsetof(MatroskaTags, target), { .n = matroska_tagtargets } },
  477     { 0 }
  478 };
  479 
  480 static EbmlSyntax matroska_tags[] = {
  481     { MATROSKA_ID_TAG, EBML_NEST, sizeof(MatroskaTags), offsetof(MatroskaDemuxContext, tags), { .n = matroska_tag } },
  482     { 0 }
  483 };
  484 
  485 static EbmlSyntax matroska_seekhead_entry[] = {
  486     { MATROSKA_ID_SEEKID,       EBML_UINT, 0, offsetof(MatroskaSeekhead, id) },
  487     { MATROSKA_ID_SEEKPOSITION, EBML_UINT, 0, offsetof(MatroskaSeekhead, pos), { .u = -1 } },
  488     { 0 }
  489 };
  490 
  491 static EbmlSyntax matroska_seekhead[] = {
  492     { MATROSKA_ID_SEEKENTRY, EBML_NEST, sizeof(MatroskaSeekhead), offsetof(MatroskaDemuxContext, seekhead), { .n = matroska_seekhead_entry } },
  493     { 0 }
  494 };
  495 
  496 static EbmlSyntax matroska_segment[] = {
  497     { MATROSKA_ID_INFO,        EBML_NEST, 0, 0, { .n = matroska_info } },
  498     { MATROSKA_ID_TRACKS,      EBML_NEST, 0, 0, { .n = matroska_tracks } },
  499     { MATROSKA_ID_ATTACHMENTS, EBML_NEST, 0, 0, { .n = matroska_attachments } },
  500     { MATROSKA_ID_CHAPTERS,    EBML_NEST, 0, 0, { .n = matroska_chapters } },
  501     { MATROSKA_ID_CUES,        EBML_NEST, 0, 0, { .n = matroska_index } },
  502     { MATROSKA_ID_TAGS,        EBML_NEST, 0, 0, { .n = matroska_tags } },
  503     { MATROSKA_ID_SEEKHEAD,    EBML_NEST, 0, 0, { .n = matroska_seekhead } },
  504     { MATROSKA_ID_CLUSTER,     EBML_STOP },
  505     { 0 }
  506 };
  507 
  508 static EbmlSyntax matroska_segments[] = {
  509     { MATROSKA_ID_SEGMENT, EBML_NEST, 0, 0, { .n = matroska_segment } },
  510     { 0 }
  511 };
  512 
  513 static EbmlSyntax matroska_blockgroup[] = {
  514     { MATROSKA_ID_BLOCK,          EBML_BIN,  0, offsetof(MatroskaBlock, bin) },
  515     { MATROSKA_ID_SIMPLEBLOCK,    EBML_BIN,  0, offsetof(MatroskaBlock, bin) },
  516     { MATROSKA_ID_BLOCKDURATION,  EBML_UINT, 0, offsetof(MatroskaBlock, duration), { .u = AV_NOPTS_VALUE } },
  517     { MATROSKA_ID_BLOCKREFERENCE, EBML_UINT, 0, offsetof(MatroskaBlock, reference) },
  518     { MATROSKA_ID_CODECSTATE,     EBML_NONE },
  519     {                          1, EBML_UINT, 0, offsetof(MatroskaBlock, non_simple), { .u = 1 } },
  520     { 0 }
  521 };
  522 
  523 static EbmlSyntax matroska_cluster[] = {
  524     { MATROSKA_ID_CLUSTERTIMECODE, EBML_UINT, 0,                     offsetof(MatroskaCluster, timecode) },
  525     { MATROSKA_ID_BLOCKGROUP,      EBML_NEST, sizeof(MatroskaBlock), offsetof(MatroskaCluster, blocks), { .n = matroska_blockgroup } },
  526     { MATROSKA_ID_SIMPLEBLOCK,     EBML_PASS, sizeof(MatroskaBlock), offsetof(MatroskaCluster, blocks), { .n = matroska_blockgroup } },
  527     { MATROSKA_ID_CLUSTERPOSITION, EBML_NONE },
  528     { MATROSKA_ID_CLUSTERPREVSIZE, EBML_NONE },
  529     { 0 }
  530 };
  531 
  532 static EbmlSyntax matroska_clusters[] = {
  533     { MATROSKA_ID_CLUSTER,  EBML_NEST, 0, 0, { .n = matroska_cluster } },
  534     { MATROSKA_ID_INFO,     EBML_NONE },
  535     { MATROSKA_ID_CUES,     EBML_NONE },
  536     { MATROSKA_ID_TAGS,     EBML_NONE },
  537     { MATROSKA_ID_SEEKHEAD, EBML_NONE },
  538     { 0 }
  539 };
  540 
  541 static EbmlSyntax matroska_cluster_incremental_parsing[] = {
  542     { MATROSKA_ID_CLUSTERTIMECODE, EBML_UINT, 0,                     offsetof(MatroskaCluster, timecode) },
  543     { MATROSKA_ID_BLOCKGROUP,      EBML_NEST, sizeof(MatroskaBlock), offsetof(MatroskaCluster, blocks), { .n = matroska_blockgroup } },
  544     { MATROSKA_ID_SIMPLEBLOCK,     EBML_PASS, sizeof(MatroskaBlock), offsetof(MatroskaCluster, blocks), { .n = matroska_blockgroup } },
  545     { MATROSKA_ID_CLUSTERPOSITION, EBML_NONE },
  546     { MATROSKA_ID_CLUSTERPREVSIZE, EBML_NONE },
  547     { MATROSKA_ID_INFO,            EBML_NONE },
  548     { MATROSKA_ID_CUES,            EBML_NONE },
  549     { MATROSKA_ID_TAGS,            EBML_NONE },
  550     { MATROSKA_ID_SEEKHEAD,        EBML_NONE },
  551     { MATROSKA_ID_CLUSTER,         EBML_STOP },
  552     { 0 }
  553 };
  554 
  555 static EbmlSyntax matroska_cluster_incremental[] = {
  556     { MATROSKA_ID_CLUSTERTIMECODE, EBML_UINT, 0, offsetof(MatroskaCluster, timecode) },
  557     { MATROSKA_ID_BLOCKGROUP,      EBML_STOP },
  558     { MATROSKA_ID_SIMPLEBLOCK,     EBML_STOP },
  559     { MATROSKA_ID_CLUSTERPOSITION, EBML_NONE },
  560     { MATROSKA_ID_CLUSTERPREVSIZE, EBML_NONE },
  561     { 0 }
  562 };
  563 
  564 static EbmlSyntax matroska_clusters_incremental[] = {
  565     { MATROSKA_ID_CLUSTER,  EBML_NEST, 0, 0, { .n = matroska_cluster_incremental } },
  566     { MATROSKA_ID_INFO,     EBML_NONE },
  567     { MATROSKA_ID_CUES,     EBML_NONE },
  568     { MATROSKA_ID_TAGS,     EBML_NONE },
  569     { MATROSKA_ID_SEEKHEAD, EBML_NONE },
  570     { 0 }
  571 };
  572 
  573 static const char *const matroska_doctypes[] = { "matroska", "webm" };
  574 
  575 static int matroska_resync(MatroskaDemuxContext *matroska, int64_t last_pos)
  576 {
  577     AVIOContext *pb = matroska->ctx->pb;
  578     uint32_t id;
  579     matroska->current_id = 0;
  580     matroska->num_levels = 0;
  581 
  582     /* seek to next position to resync from */
  583     if (avio_seek(pb, last_pos + 1, SEEK_SET) < 0)
  584         goto eof;
  585 
  586     id = avio_rb32(pb);
  587 
  588     // try to find a toplevel element
  589     while (!pb->eof_reached) {
  590         if (id == MATROSKA_ID_INFO     || id == MATROSKA_ID_TRACKS      ||
  591             id == MATROSKA_ID_CUES     || id == MATROSKA_ID_TAGS        ||
  592             id == MATROSKA_ID_SEEKHEAD || id == MATROSKA_ID_ATTACHMENTS ||
  593             id == MATROSKA_ID_CLUSTER  || id == MATROSKA_ID_CHAPTERS) {
  594             matroska->current_id = id;
  595             return 0;
  596         }
  597         id = (id << 8) | avio_r8(pb);
  598     }
  599 
  600 eof:
  601     matroska->done = 1;
  602     return AVERROR_EOF;
  603 }
  604 
  605 /*
  606  * Return: Whether we reached the end of a level in the hierarchy or not.
  607  */
  608 static int ebml_level_end(MatroskaDemuxContext *matroska)
  609 {
  610     AVIOContext *pb = matroska->ctx->pb;
  611     int64_t pos = avio_tell(pb);
  612 
  613     if (matroska->num_levels > 0) {
  614         MatroskaLevel *level = &matroska->levels[matroska->num_levels - 1];
  615         if (pos - level->start >= level->length || matroska->current_id) {
  616             matroska->num_levels--;
  617             return 1;
  618         }
  619     }
  620     return 0;
  621 }
  622 
  623 /*
  624  * Read: an "EBML number", which is defined as a variable-length
  625  * array of bytes. The first byte indicates the length by giving a
  626  * number of 0-bits followed by a one. The position of the first
  627  * "one" bit inside the first byte indicates the length of this
  628  * number.
  629  * Returns: number of bytes read, < 0 on error
  630  */
  631 static int ebml_read_num(MatroskaDemuxContext *matroska, AVIOContext *pb,
  632                          int max_size, uint64_t *number)
  633 {
  634     int read = 1, n = 1;
  635     uint64_t total = 0;
  636 
  637     /* The first byte tells us the length in bytes - avio_r8() can normally
  638      * return 0, but since that's not a valid first ebmlID byte, we can
  639      * use it safely here to catch EOS. */
  640     if (!(total = avio_r8(pb))) {
  641         /* we might encounter EOS here */
  642         if (!pb->eof_reached) {
  643             int64_t pos = avio_tell(pb);
  644             av_log(matroska->ctx, AV_LOG_ERROR,
  645                    "Read error at pos. %"PRIu64" (0x%"PRIx64")\n",
  646                    pos, pos);
  647             return pb->error ? pb->error : AVERROR(EIO);
  648         }
  649         return AVERROR_EOF;
  650     }
  651 
  652     /* get the length of the EBML number */
  653     read = 8 - ff_log2_tab[total];
  654     if (read > max_size) {
  655         int64_t pos = avio_tell(pb) - 1;
  656         av_log(matroska->ctx, AV_LOG_ERROR,
  657                "Invalid EBML number size tag 0x%02x at pos %"PRIu64" (0x%"PRIx64")\n",
  658                (uint8_t) total, pos, pos);
  659         return AVERROR_INVALIDDATA;
  660     }
  661 
  662     /* read out length */
  663     total ^= 1 << ff_log2_tab[total];
  664     while (n++ < read)
  665         total = (total << 8) | avio_r8(pb);
  666 
  667     *number = total;
  668 
  669     return read;
  670 }
  671 
  672 /**
  673  * Read a EBML length value.
  674  * This needs special handling for the "unknown length" case which has multiple
  675  * encodings.
  676  */
  677 static int ebml_read_length(MatroskaDemuxContext *matroska, AVIOContext *pb,
  678                             uint64_t *number)
  679 {
  680     int res = ebml_read_num(matroska, pb, 8, number);
  681     if (res > 0 && *number + 1 == 1ULL << (7 * res))
  682         *number = 0xffffffffffffffULL;
  683     return res;
  684 }
  685 
  686 /*
  687  * Read the next element as an unsigned int.
  688  * 0 is success, < 0 is failure.
  689  */
  690 static int ebml_read_uint(AVIOContext *pb, int size, uint64_t *num)
  691 {
  692     int n = 0;
  693 
  694     if (size > 8)
  695         return AVERROR_INVALIDDATA;
  696 
  697     /* big-endian ordering; build up number */
  698     *num = 0;
  699     while (n++ < size)
  700         *num = (*num << 8) | avio_r8(pb);
  701 
  702     return 0;
  703 }
  704 
  705 /*
  706  * Read the next element as a float.
  707  * 0 is success, < 0 is failure.
  708  */
  709 static int ebml_read_float(AVIOContext *pb, int size, double *num)
  710 {
  711     if (size == 0)
  712         *num = 0;
  713     else if (size == 4)
  714         *num = av_int2float(avio_rb32(pb));
  715     else if (size == 8)
  716         *num = av_int2double(avio_rb64(pb));
  717     else
  718         return AVERROR_INVALIDDATA;
  719 
  720     return 0;
  721 }
  722 
  723 /*
  724  * Read the next element as an ASCII string.
  725  * 0 is success, < 0 is failure.
  726  */
  727 static int ebml_read_ascii(AVIOContext *pb, int size, char **str)
  728 {
  729     char *res;
  730 
  731     /* EBML strings are usually not 0-terminated, so we allocate one
  732      * byte more, read the string and NULL-terminate it ourselves. */
  733     if (!(res = av_malloc(size + 1)))
  734         return AVERROR(ENOMEM);
  735     if (avio_read(pb, (uint8_t *) res, size) != size) {
  736         av_free(res);
  737         return AVERROR(EIO);
  738     }
  739     (res)[size] = '\0';
  740     av_free(*str);
  741     *str = res;
  742 
  743     return 0;
  744 }
  745 
  746 /*
  747  * Read the next element as binary data.
  748  * 0 is success, < 0 is failure.
  749  */
  750 static int ebml_read_binary(AVIOContext *pb, int length, EbmlBin *bin)
  751 {
  752     av_free(bin->data);
  753     bin->size = 0;
  754 
  755     if (!(bin->data = av_mallocz(length + AV_INPUT_BUFFER_PADDING_SIZE)))
  756         return AVERROR(ENOMEM);
  757 
  758     bin->pos  = avio_tell(pb);
  759     if (avio_read(pb, bin->data, length) != length) {
  760         av_freep(&bin->data);
  761         return AVERROR(EIO);
  762     }
  763 
  764     bin->size = length;
  765 
  766     return 0;
  767 }
  768 
  769 /*
  770  * Read the next element, but only the header. The contents
  771  * are supposed to be sub-elements which can be read separately.
  772  * 0 is success, < 0 is failure.
  773  */
  774 static int ebml_read_master(MatroskaDemuxContext *matroska, uint64_t length)
  775 {
  776     AVIOContext *pb = matroska->ctx->pb;
  777     MatroskaLevel *level;
  778 
  779     if (matroska->num_levels >= EBML_MAX_DEPTH) {
  780         av_log(matroska->ctx, AV_LOG_ERROR,
  781                "File moves beyond max. allowed depth (%d)\n", EBML_MAX_DEPTH);
  782         return AVERROR(ENOSYS);
  783     }
  784 
  785     level         = &matroska->levels[matroska->num_levels++];
  786     level->start  = avio_tell(pb);
  787     level->length = length;
  788 
  789     return 0;
  790 }
  791 
  792 /*
  793  * Read signed/unsigned "EBML" numbers.
  794  * Return: number of bytes processed, < 0 on error
  795  */
  796 static int matroska_ebmlnum_uint(MatroskaDemuxContext *matroska,
  797                                  uint8_t *data, uint32_t size, uint64_t *num)
  798 {
  799     AVIOContext pb;
  800     ffio_init_context(&pb, data, size, 0, NULL, NULL, NULL, NULL);
  801     return ebml_read_num(matroska, &pb, FFMIN(size, 8), num);
  802 }
  803 
  804 /*
  805  * Same as above, but signed.
  806  */
  807 static int matroska_ebmlnum_sint(MatroskaDemuxContext *matroska,
  808                                  uint8_t *data, uint32_t size, int64_t *num)
  809 {
  810     uint64_t unum;
  811     int res;
  812 
  813     /* read as unsigned number first */
  814     if ((res = matroska_ebmlnum_uint(matroska, data, size, &unum)) < 0)
  815         return res;
  816 
  817     /* make signed (weird way) */
  818     *num = unum - ((1LL << (7 * res - 1)) - 1);
  819 
  820     return res;
  821 }
  822 
  823 static int ebml_parse_elem(MatroskaDemuxContext *matroska,
  824                            EbmlSyntax *syntax, void *data);
  825 
  826 static int ebml_parse_id(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
  827                          uint32_t id, void *data)
  828 {
  829     int i;
  830     for (i = 0; syntax[i].id; i++)
  831         if (id == syntax[i].id)
  832             break;
  833     if (!syntax[i].id && id == MATROSKA_ID_CLUSTER &&
  834         matroska->num_levels > 0                   &&
  835         matroska->levels[matroska->num_levels - 1].length == 0xffffffffffffff)
  836         return 0;  // we reached the end of an unknown size cluster
  837     if (!syntax[i].id && id != EBML_ID_VOID && id != EBML_ID_CRC32) {
  838         av_log(matroska->ctx, AV_LOG_INFO, "Unknown entry 0x%"PRIX32"\n", id);
  839         if (matroska->ctx->error_recognition & AV_EF_EXPLODE)
  840             return AVERROR_INVALIDDATA;
  841     }
  842     return ebml_parse_elem(matroska, &syntax[i], data);
  843 }
  844 
  845 static int ebml_parse(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
  846                       void *data)
  847 {
  848     if (!matroska->current_id) {
  849         uint64_t id;
  850         int res = ebml_read_num(matroska, matroska->ctx->pb, 4, &id);
  851         if (res < 0)
  852             return res;
  853         matroska->current_id = id | 1 << 7 * res;
  854     }
  855     return ebml_parse_id(matroska, syntax, matroska->current_id, data);
  856 }
  857 
  858 static int ebml_parse_nest(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
  859                            void *data)
  860 {
  861     int i, res = 0;
  862 
  863     for (i = 0; syntax[i].id; i++)
  864         switch (syntax[i].type) {
  865         case EBML_UINT:
  866             *(uint64_t *) ((char *) data + syntax[i].data_offset) = syntax[i].def.u;
  867             break;
  868         case EBML_FLOAT:
  869             *(double *) ((char *) data + syntax[i].data_offset) = syntax[i].def.f;
  870             break;
  871         case EBML_STR:
  872         case EBML_UTF8:
  873             // the default may be NULL
  874             if (syntax[i].def.s) {
  875                 uint8_t **dst = (uint8_t **) ((uint8_t *) data + syntax[i].data_offset);
  876                 *dst = av_strdup(syntax[i].def.s);
  877                 if (!*dst)
  878                     return AVERROR(ENOMEM);
  879             }
  880             break;
  881         }
  882 
  883     while (!res && !ebml_level_end(matroska))
  884         res = ebml_parse(matroska, syntax, data);
  885 
  886     return res;
  887 }
  888 
  889 static int ebml_parse_elem(MatroskaDemuxContext *matroska,
  890                            EbmlSyntax *syntax, void *data)
  891 {
  892     static const uint64_t max_lengths[EBML_TYPE_COUNT] = {
  893         [EBML_UINT]  = 8,
  894         [EBML_FLOAT] = 8,
  895         // max. 16 MB for strings
  896         [EBML_STR]   = 0x1000000,
  897         [EBML_UTF8]  = 0x1000000,
  898         // max. 256 MB for binary data
  899         [EBML_BIN]   = 0x10000000,
  900         // no limits for anything else
  901     };
  902     AVIOContext *pb = matroska->ctx->pb;
  903     uint32_t id = syntax->id;
  904     uint64_t length;
  905     int res;
  906 
  907     data = (char *) data + syntax->data_offset;
  908     if (syntax->list_elem_size) {
  909         EbmlList *list = data;
  910         if ((res = av_reallocp_array(&list->elem,
  911                                      list->nb_elem + 1,
  912                                      syntax->list_elem_size)) < 0) {
  913             list->nb_elem = 0;
  914             return res;
  915         }
  916         data = (char *) list->elem + list->nb_elem * syntax->list_elem_size;
  917         memset(data, 0, syntax->list_elem_size);
  918         list->nb_elem++;
  919     }
  920 
  921     if (syntax->type != EBML_PASS && syntax->type != EBML_STOP) {
  922         matroska->current_id = 0;
  923         if ((res = ebml_read_length(matroska, pb, &length)) < 0)
  924             return res;
  925         if (max_lengths[syntax->type] && length > max_lengths[syntax->type]) {
  926             av_log(matroska->ctx, AV_LOG_ERROR,
  927                    "Invalid length 0x%"PRIx64" > 0x%"PRIx64" for syntax element %i\n",
  928                    length, max_lengths[syntax->type], syntax->type);
  929             return AVERROR_INVALIDDATA;
  930         }
  931     }
  932 
  933     switch (syntax->type) {
  934     case EBML_UINT:
  935         res = ebml_read_uint(pb, length, data);
  936         break;
  937     case EBML_FLOAT:
  938         res = ebml_read_float(pb, length, data);
  939         break;
  940     case EBML_STR:
  941     case EBML_UTF8:
  942         res = ebml_read_ascii(pb, length, data);
  943         break;
  944     case EBML_BIN:
  945         res = ebml_read_binary(pb, length, data);
  946         break;
  947     case EBML_NEST:
  948         if ((res = ebml_read_master(matroska, length)) < 0)
  949             return res;
  950         if (id == MATROSKA_ID_SEGMENT)
  951             matroska->segment_start = avio_tell(matroska->ctx->pb);
  952         return ebml_parse_nest(matroska, syntax->def.n, data);
  953     case EBML_PASS:
  954         return ebml_parse_id(matroska, syntax->def.n, id, data);
  955     case EBML_STOP:
  956         return 1;
  957     default:
  958         return avio_skip(pb, length) < 0 ? AVERROR(EIO) : 0;
  959     }
  960     if (res == AVERROR_INVALIDDATA)
  961         av_log(matroska->ctx, AV_LOG_ERROR, "Invalid element\n");
  962     else if (res == AVERROR(EIO))
  963         av_log(matroska->ctx, AV_LOG_ERROR, "Read error\n");
  964     return res;
  965 }
  966 
  967 static void ebml_free(EbmlSyntax *syntax, void *data)
  968 {
  969     int i, j;
  970     for (i = 0; syntax[i].id; i++) {
  971         void *data_off = (char *) data + syntax[i].data_offset;
  972         switch (syntax[i].type) {
  973         case EBML_STR:
  974         case EBML_UTF8:
  975             av_freep(data_off);
  976             break;
  977         case EBML_BIN:
  978             av_freep(&((EbmlBin *) data_off)->data);
  979             break;
  980         case EBML_NEST:
  981             if (syntax[i].list_elem_size) {
  982                 EbmlList *list = data_off;
  983                 char *ptr = list->elem;
  984                 for (j = 0; j < list->nb_elem;
  985                      j++, ptr += syntax[i].list_elem_size)
  986                     ebml_free(syntax[i].def.n, ptr);
  987                 av_free(list->elem);
  988             } else
  989                 ebml_free(syntax[i].def.n, data_off);
  990         default:
  991             break;
  992         }
  993     }
  994 }
  995 
  996 /*
  997  * Autodetecting...
  998  */
  999 static int matroska_probe(AVProbeData *p)
 1000 {
 1001     uint64_t total = 0;
 1002     int len_mask = 0x80, size = 1, n = 1, i;
 1003 
 1004     /* EBML header? */
 1005     if (AV_RB32(p->buf) != EBML_ID_HEADER)
 1006         return 0;
 1007 
 1008     /* length of header */
 1009     total = p->buf[4];
 1010     while (size <= 8 && !(total & len_mask)) {
 1011         size++;
 1012         len_mask >>= 1;
 1013     }
 1014     if (size > 8)
 1015         return 0;
 1016     total &= (len_mask - 1);
 1017     while (n < size)
 1018         total = (total << 8) | p->buf[4 + n++];
 1019 
 1020     /* Does the probe data contain the whole header? */
 1021     if (p->buf_size < 4 + size + total)
 1022         return 0;
 1023 
 1024     /* The header should contain a known document type. For now,
 1025      * we don't parse the whole header but simply check for the
 1026      * availability of that array of characters inside the header.
 1027      * Not fully fool-proof, but good enough. */
 1028     for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++) {
 1029         int probelen = strlen(matroska_doctypes[i]);
 1030         if (total < probelen)
 1031             continue;
 1032         for (n = 4 + size; n <= 4 + size + total - probelen; n++)
 1033             if (!memcmp(p->buf + n, matroska_doctypes[i], probelen))
 1034                 return AVPROBE_SCORE_MAX;
 1035     }
 1036 
 1037     // probably valid EBML header but no recognized doctype
 1038     return AVPROBE_SCORE_EXTENSION;
 1039 }
 1040 
 1041 static MatroskaTrack *matroska_find_track_by_num(MatroskaDemuxContext *matroska,
 1042                                                  int num)
 1043 {
 1044     MatroskaTrack *tracks = matroska->tracks.elem;
 1045     int i;
 1046 
 1047     for (i = 0; i < matroska->tracks.nb_elem; i++)
 1048         if (tracks[i].num == num)
 1049             return &tracks[i];
 1050 
 1051     av_log(matroska->ctx, AV_LOG_ERROR, "Invalid track number %d\n", num);
 1052     return NULL;
 1053 }
 1054 
 1055 static int matroska_decode_buffer(uint8_t **buf, int *buf_size,
 1056                                   MatroskaTrack *track)
 1057 {
 1058     MatroskaTrackEncoding *encodings = track->encodings.elem;
 1059     uint8_t *data = *buf;
 1060     int isize = *buf_size;
 1061     uint8_t *pkt_data = NULL;
 1062     uint8_t av_unused *newpktdata;
 1063     int pkt_size = isize;
 1064     int result = 0;
 1065     int olen;
 1066 
 1067     if (pkt_size >= 10000000)
 1068         return AVERROR_INVALIDDATA;
 1069 
 1070     switch (encodings[0].compression.algo) {
 1071     case MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP:
 1072     {
 1073         int header_size = encodings[0].compression.settings.size;
 1074         uint8_t *header = encodings[0].compression.settings.data;
 1075 
 1076         if (!header_size)
 1077             return 0;
 1078 
 1079         pkt_size = isize + header_size;
 1080         pkt_data = av_malloc(pkt_size);
 1081         if (!pkt_data)
 1082             return AVERROR(ENOMEM);
 1083 
 1084         memcpy(pkt_data, header, header_size);
 1085         memcpy(pkt_data + header_size, data, isize);
 1086         break;
 1087     }
 1088 #if CONFIG_LZO
 1089     case MATROSKA_TRACK_ENCODING_COMP_LZO:
 1090         do {
 1091             olen       = pkt_size *= 3;
 1092             newpktdata = av_realloc(pkt_data, pkt_size + AV_LZO_OUTPUT_PADDING);
 1093             if (!newpktdata) {
 1094                 result = AVERROR(ENOMEM);
 1095                 goto failed;
 1096             }
 1097             pkt_data = newpktdata;
 1098             result   = av_lzo1x_decode(pkt_data, &olen, data, &isize);
 1099         } while (result == AV_LZO_OUTPUT_FULL && pkt_size < 10000000);
 1100         if (result) {
 1101             result = AVERROR_INVALIDDATA;
 1102             goto failed;
 1103         }
 1104         pkt_size -= olen;
 1105         break;
 1106 #endif
 1107 #if CONFIG_ZLIB
 1108     case MATROSKA_TRACK_ENCODING_COMP_ZLIB:
 1109     {
 1110         z_stream zstream = { 0 };
 1111         if (inflateInit(&zstream) != Z_OK)
 1112             return -1;
 1113         zstream.next_in  = data;
 1114         zstream.avail_in = isize;
 1115         do {
 1116             pkt_size  *= 3;
 1117             newpktdata = av_realloc(pkt_data, pkt_size);
 1118             if (!newpktdata) {
 1119                 inflateEnd(&zstream);
 1120                 goto failed;
 1121             }
 1122             pkt_data          = newpktdata;
 1123             zstream.avail_out = pkt_size - zstream.total_out;
 1124             zstream.next_out  = pkt_data + zstream.total_out;
 1125             result            = inflate(&zstream, Z_NO_FLUSH);
 1126         } while (result == Z_OK && pkt_size < 10000000);
 1127         pkt_size = zstream.total_out;
 1128         inflateEnd(&zstream);
 1129         if (result != Z_STREAM_END) {
 1130             if (result == Z_MEM_ERROR)
 1131                 result = AVERROR(ENOMEM);
 1132             else
 1133                 result = AVERROR_INVALIDDATA;
 1134             goto failed;
 1135         }
 1136         break;
 1137     }
 1138 #endif
 1139 #if CONFIG_BZLIB
 1140     case MATROSKA_TRACK_ENCODING_COMP_BZLIB:
 1141     {
 1142         bz_stream bzstream = { 0 };
 1143         if (BZ2_bzDecompressInit(&bzstream, 0, 0) != BZ_OK)
 1144             return -1;
 1145         bzstream.next_in  = data;
 1146         bzstream.avail_in = isize;
 1147         do {
 1148             pkt_size  *= 3;
 1149             newpktdata = av_realloc(pkt_data, pkt_size);
 1150             if (!newpktdata) {
 1151                 BZ2_bzDecompressEnd(&bzstream);
 1152                 goto failed;
 1153             }
 1154             pkt_data           = newpktdata;
 1155             bzstream.avail_out = pkt_size - bzstream.total_out_lo32;
 1156             bzstream.next_out  = pkt_data + bzstream.total_out_lo32;
 1157             result             = BZ2_bzDecompress(&bzstream);
 1158         } while (result == BZ_OK && pkt_size < 10000000);
 1159         pkt_size = bzstream.total_out_lo32;
 1160         BZ2_bzDecompressEnd(&bzstream);
 1161         if (result != BZ_STREAM_END) {
 1162             if (result == BZ_MEM_ERROR)
 1163                 result = AVERROR(ENOMEM);
 1164             else
 1165                 result = AVERROR_INVALIDDATA;
 1166             goto failed;
 1167         }
 1168         break;
 1169     }
 1170 #endif
 1171     default:
 1172         return AVERROR_INVALIDDATA;
 1173     }
 1174 
 1175     *buf      = pkt_data;
 1176     *buf_size = pkt_size;
 1177     return 0;
 1178 
 1179 failed:
 1180     av_free(pkt_data);
 1181     return result;
 1182 }
 1183 
 1184 static void matroska_fix_ass_packet(MatroskaDemuxContext *matroska,
 1185                                     AVPacket *pkt, uint64_t display_duration)
 1186 {
 1187     AVBufferRef *line;
 1188     char *layer, *ptr = pkt->data, *end = ptr + pkt->size;
 1189 
 1190     for (; *ptr != ',' && ptr < end - 1; ptr++)
 1191         ;
 1192     if (*ptr == ',')
 1193         layer = ++ptr;
 1194     for (; *ptr != ',' && ptr < end - 1; ptr++)
 1195         ;
 1196     if (*ptr == ',') {
 1197         int64_t end_pts = pkt->pts + display_duration;
 1198         int sc = matroska->time_scale * pkt->pts / 10000000;
 1199         int ec = matroska->time_scale * end_pts  / 10000000;
 1200         int sh, sm, ss, eh, em, es, len;
 1201         sh     = sc / 360000;
 1202         sc    -= 360000 * sh;
 1203         sm     = sc / 6000;
 1204         sc    -= 6000 * sm;
 1205         ss     = sc / 100;
 1206         sc    -= 100 * ss;
 1207         eh     = ec / 360000;
 1208         ec    -= 360000 * eh;
 1209         em     = ec / 6000;
 1210         ec    -= 6000 * em;
 1211         es     = ec / 100;
 1212         ec    -= 100 * es;
 1213         *ptr++ = '\0';
 1214         len    = 50 + end - ptr + AV_INPUT_BUFFER_PADDING_SIZE;
 1215         if (!(line = av_buffer_alloc(len)))
 1216             return;
 1217         snprintf(line->data, len,
 1218                  "Dialogue: %s,%d:%02d:%02d.%02d,%d:%02d:%02d.%02d,%s\r\n",
 1219                  layer, sh, sm, ss, sc, eh, em, es, ec, ptr);
 1220         av_buffer_unref(&pkt->buf);
 1221         pkt->buf  = line;
 1222         pkt->data = line->data;
 1223         pkt->size = strlen(line->data);
 1224     }
 1225 }
 1226 
 1227 static int matroska_merge_packets(AVPacket *out, AVPacket *in)
 1228 {
 1229     int old_size = out->size;
 1230     int ret = av_grow_packet(out, in->size);
 1231     if (ret < 0)
 1232         return ret;
 1233 
 1234     memcpy(out->data + old_size, in->data, in->size);
 1235 
 1236     av_packet_unref(in);
 1237     av_free(in);
 1238     return 0;
 1239 }
 1240 
 1241 static void matroska_convert_tag(AVFormatContext *s, EbmlList *list,
 1242                                  AVDictionary **metadata, char *prefix)
 1243 {
 1244     MatroskaTag *tags = list->elem;
 1245     char key[1024];
 1246     int i;
 1247 
 1248     for (i = 0; i < list->nb_elem; i++) {
 1249         const char *lang = tags[i].lang &&
 1250                            strcmp(tags[i].lang, "und") ? tags[i].lang : NULL;
 1251 
 1252         if (!tags[i].name) {
 1253             av_log(s, AV_LOG_WARNING, "Skipping invalid tag with no TagName.\n");
 1254             continue;
 1255         }
 1256         if (prefix)
 1257             snprintf(key, sizeof(key), "%s/%s", prefix, tags[i].name);
 1258         else
 1259             av_strlcpy(key, tags[i].name, sizeof(key));
 1260         if (tags[i].def || !lang) {
 1261             av_dict_set(metadata, key, tags[i].string, 0);
 1262             if (tags[i].sub.nb_elem)
 1263                 matroska_convert_tag(s, &tags[i].sub, metadata, key);
 1264         }
 1265         if (lang) {
 1266             av_strlcat(key, "-", sizeof(key));
 1267             av_strlcat(key, lang, sizeof(key));
 1268             av_dict_set(metadata, key, tags[i].string, 0);
 1269             if (tags[i].sub.nb_elem)
 1270                 matroska_convert_tag(s, &tags[i].sub, metadata, key);
 1271         }
 1272     }
 1273     ff_metadata_conv(metadata, NULL, ff_mkv_metadata_conv);
 1274 }
 1275 
 1276 static void matroska_convert_tags(AVFormatContext *s)
 1277 {
 1278     MatroskaDemuxContext *matroska = s->priv_data;
 1279     MatroskaTags *tags = matroska->tags.elem;
 1280     int i, j;
 1281 
 1282     for (i = 0; i < matroska->tags.nb_elem; i++) {
 1283         if (tags[i].target.attachuid) {
 1284             MatroskaAttachment *attachment = matroska->attachments.elem;
 1285             int found = 0;
 1286             for (j = 0; j < matroska->attachments.nb_elem; j++) {
 1287                 if (attachment[j].uid == tags[i].target.attachuid &&
 1288                     attachment[j].stream) {
 1289                     matroska_convert_tag(s, &tags[i].tag,
 1290                                          &attachment[j].stream->metadata, NULL);
 1291                     found = 1;
 1292                 }
 1293             }
 1294             if (!found) {
 1295                 av_log(NULL, AV_LOG_WARNING,
 1296                        "The tags at index %d refer to a "
 1297                        "non-existent attachment %"PRId64".\n",
 1298                        i, tags[i].target.attachuid);
 1299             }
 1300         } else if (tags[i].target.chapteruid) {
 1301             MatroskaChapter *chapter = matroska->chapters.elem;
 1302             int found = 0;
 1303             for (j = 0; j < matroska->chapters.nb_elem; j++) {
 1304                 if (chapter[j].uid == tags[i].target.chapteruid &&
 1305                     chapter[j].chapter) {
 1306                     matroska_convert_tag(s, &tags[i].tag,
 1307                                          &chapter[j].chapter->metadata, NULL);
 1308                     found = 1;
 1309                 }
 1310             }
 1311             if (!found) {
 1312                 av_log(NULL, AV_LOG_WARNING,
 1313                        "The tags at index %d refer to a non-existent chapter "
 1314                        "%"PRId64".\n",
 1315                        i, tags[i].target.chapteruid);
 1316             }
 1317         } else if (tags[i].target.trackuid) {
 1318             MatroskaTrack *track = matroska->tracks.elem;
 1319             int found = 0;
 1320             for (j = 0; j < matroska->tracks.nb_elem; j++) {
 1321                 if (track[j].uid == tags[i].target.trackuid &&
 1322                     track[j].stream) {
 1323                     matroska_convert_tag(s, &tags[i].tag,
 1324                                          &track[j].stream->metadata, NULL);
 1325                     found = 1;
 1326                }
 1327             }
 1328             if (!found) {
 1329                 av_log(NULL, AV_LOG_WARNING,
 1330                        "The tags at index %d refer to a non-existent track "
 1331                        "%"PRId64".\n",
 1332                        i, tags[i].target.trackuid);
 1333             }
 1334         } else {
 1335             matroska_convert_tag(s, &tags[i].tag, &s->metadata,
 1336                                  tags[i].target.type);
 1337         }
 1338     }
 1339 }
 1340 
 1341 static int matroska_parse_seekhead_entry(MatroskaDemuxContext *matroska,
 1342                                          int idx)
 1343 {
 1344     EbmlList *seekhead_list = &matroska->seekhead;
 1345     uint32_t level_up       = matroska->level_up;
 1346     uint32_t saved_id       = matroska->current_id;
 1347     MatroskaSeekhead *seekhead = seekhead_list->elem;
 1348     int64_t before_pos = avio_tell(matroska->ctx->pb);
 1349     MatroskaLevel level;
 1350     int64_t offset;
 1351     int ret = 0;
 1352 
 1353     if (idx >= seekhead_list->nb_elem            ||
 1354         seekhead[idx].id == MATROSKA_ID_SEEKHEAD ||
 1355         seekhead[idx].id == MATROSKA_ID_CLUSTER)
 1356         return 0;
 1357 
 1358     /* seek */
 1359     offset = seekhead[idx].pos + matroska->segment_start;
 1360     if (avio_seek(matroska->ctx->pb, offset, SEEK_SET) == offset) {
 1361         /* We don't want to lose our seekhead level, so we add
 1362          * a dummy. This is a crude hack. */
 1363         if (matroska->num_levels == EBML_MAX_DEPTH) {
 1364             av_log(matroska->ctx, AV_LOG_INFO,
 1365                    "Max EBML element depth (%d) reached, "
 1366                    "cannot parse further.\n", EBML_MAX_DEPTH);
 1367             ret = AVERROR_INVALIDDATA;
 1368         } else {
 1369             level.start  = 0;
 1370             level.length = (uint64_t) -1;
 1371             matroska->levels[matroska->num_levels] = level;
 1372             matroska->num_levels++;
 1373             matroska->current_id                   = 0;
 1374 
 1375             ret = ebml_parse(matroska, matroska_segment, matroska);
 1376 
 1377             /* remove dummy level */
 1378             while (matroska->num_levels) {
 1379                 uint64_t length = matroska->levels[--matroska->num_levels].length;
 1380                 if (length == (uint64_t) -1)
 1381                     break;
 1382             }
 1383         }
 1384     }
 1385     /* seek back */
 1386     avio_seek(matroska->ctx->pb, before_pos, SEEK_SET);
 1387     matroska->level_up   = level_up;
 1388     matroska->current_id = saved_id;
 1389 
 1390     return ret;
 1391 }
 1392 
 1393 static void matroska_execute_seekhead(MatroskaDemuxContext *matroska)
 1394 {
 1395     EbmlList *seekhead_list = &matroska->seekhead;
 1396     int64_t before_pos = avio_tell(matroska->ctx->pb);
 1397     int i;
 1398 
 1399     // we should not do any seeking in the streaming case
 1400     if (!matroska->ctx->pb->seekable ||
 1401         (matroska->ctx->flags & AVFMT_FLAG_IGNIDX))
 1402         return;
 1403 
 1404     for (i = 0; i < seekhead_list->nb_elem; i++) {
 1405         MatroskaSeekhead *seekhead = seekhead_list->elem;
 1406         if (seekhead[i].pos <= before_pos)
 1407             continue;
 1408 
 1409         // defer cues parsing until we actually need cue data.
 1410         if (seekhead[i].id == MATROSKA_ID_CUES) {
 1411             matroska->cues_parsing_deferred = 1;
 1412             continue;
 1413         }
 1414 
 1415         if (matroska_parse_seekhead_entry(matroska, i) < 0)
 1416             break;
 1417     }
 1418 }
 1419 
 1420 static void matroska_parse_cues(MatroskaDemuxContext *matroska)
 1421 {
 1422     EbmlList *seekhead_list = &matroska->seekhead;
 1423     MatroskaSeekhead *seekhead = seekhead_list->elem;
 1424     EbmlList *index_list;
 1425     MatroskaIndex *index;
 1426     int index_scale = 1;
 1427     int i, j;
 1428 
 1429     for (i = 0; i < seekhead_list->nb_elem; i++)
 1430         if (seekhead[i].id == MATROSKA_ID_CUES)
 1431             break;
 1432     assert(i <= seekhead_list->nb_elem);
 1433 
 1434     matroska_parse_seekhead_entry(matroska, i);
 1435 
 1436     index_list = &matroska->index;
 1437     index      = index_list->elem;
 1438     if (index_list->nb_elem &&
 1439         index[0].time > 1E14 / matroska->time_scale) {
 1440         av_log(matroska->ctx, AV_LOG_WARNING, "Working around broken index.\n");
 1441         index_scale = matroska->time_scale;
 1442     }
 1443     for (i = 0; i < index_list->nb_elem; i++) {
 1444         EbmlList *pos_list    = &index[i].pos;
 1445         MatroskaIndexPos *pos = pos_list->elem;
 1446         for (j = 0; j < pos_list->nb_elem; j++) {
 1447             MatroskaTrack *track = matroska_find_track_by_num(matroska,
 1448                                                               pos[j].track);
 1449             if (track && track->stream)
 1450                 av_add_index_entry(track->stream,
 1451                                    pos[j].pos + matroska->segment_start,
 1452                                    index[i].time / index_scale, 0, 0,
 1453                                    AVINDEX_KEYFRAME);
 1454         }
 1455     }
 1456 }
 1457 
 1458 static int matroska_aac_profile(char *codec_id)
 1459 {
 1460     static const char *const aac_profiles[] = { "MAIN", "LC", "SSR" };
 1461     int profile;
 1462 
 1463     for (profile = 0; profile < FF_ARRAY_ELEMS(aac_profiles); profile++)
 1464         if (strstr(codec_id, aac_profiles[profile]))
 1465             break;
 1466     return profile + 1;
 1467 }
 1468 
 1469 static int matroska_aac_sri(int samplerate)
 1470 {
 1471     int sri;
 1472 
 1473     for (sri = 0; sri < FF_ARRAY_ELEMS(avpriv_mpeg4audio_sample_rates); sri++)
 1474         if (avpriv_mpeg4audio_sample_rates[sri] == samplerate)
 1475             break;
 1476     return sri;
 1477 }
 1478 
 1479 static int matroska_parse_flac(AVFormatContext *s,
 1480                                MatroskaTrack *track,
 1481                                int *offset)
 1482 {
 1483     AVStream *st = track->stream;
 1484     uint8_t *p = track->codec_priv.data;
 1485     int size   = track->codec_priv.size;
 1486 
 1487     if (size < 8 + FLAC_STREAMINFO_SIZE || p[4] & 0x7f) {
 1488         av_log(s, AV_LOG_WARNING, "Invalid FLAC private data\n");
 1489         track->codec_priv.size = 0;
 1490         return 0;
 1491     }
 1492     *offset = 8;
 1493     track->codec_priv.size = 8 + FLAC_STREAMINFO_SIZE;
 1494 
 1495     p    += track->codec_priv.size;
 1496     size -= track->codec_priv.size;
 1497 
 1498     /* parse the remaining metadata blocks if present */
 1499     while (size >= 4) {
 1500         int block_last, block_type, block_size;
 1501 
 1502         flac_parse_block_header(p, &block_last, &block_type, &block_size);
 1503 
 1504         p    += 4;
 1505         size -= 4;
 1506         if (block_size > size)
 1507             return 0;
 1508 
 1509         /* check for the channel mask */
 1510         if (block_type == FLAC_METADATA_TYPE_VORBIS_COMMENT) {
 1511             AVDictionary *dict = NULL;
 1512             AVDictionaryEntry *chmask;
 1513 
 1514             ff_vorbis_comment(s, &dict, p, block_size, 0);
 1515             chmask = av_dict_get(dict, "WAVEFORMATEXTENSIBLE_CHANNEL_MASK", NULL, 0);
 1516             if (chmask) {
 1517                 uint64_t mask = strtol(chmask->value, NULL, 0);
 1518                 if (!mask || mask & ~0x3ffffULL) {
 1519                     av_log(s, AV_LOG_WARNING,
 1520                            "Invalid value of WAVEFORMATEXTENSIBLE_CHANNEL_MASK\n");
 1521                 } else
 1522                     st->codecpar->channel_layout = mask;
 1523             }
 1524             av_dict_free(&dict);
 1525         }
 1526 
 1527         p    += block_size;
 1528         size -= block_size;
 1529     }
 1530 
 1531     return 0;
 1532 }
 1533 
 1534 static int mkv_field_order(int64_t field_order)
 1535 {
 1536     switch (field_order) {
 1537     case MATROSKA_VIDEO_FIELDORDER_PROGRESSIVE:
 1538         return AV_FIELD_PROGRESSIVE;
 1539     case MATROSKA_VIDEO_FIELDORDER_UNDETERMINED:
 1540         return AV_FIELD_UNKNOWN;
 1541     case MATROSKA_VIDEO_FIELDORDER_TT:
 1542         return AV_FIELD_TT;
 1543     case MATROSKA_VIDEO_FIELDORDER_BB:
 1544         return AV_FIELD_BB;
 1545     case MATROSKA_VIDEO_FIELDORDER_BT:
 1546         return AV_FIELD_BT;
 1547     case MATROSKA_VIDEO_FIELDORDER_TB:
 1548         return AV_FIELD_TB;
 1549     default:
 1550         return AV_FIELD_UNKNOWN;
 1551     }
 1552 }
 1553 
 1554 static void mkv_stereo_mode_display_mul(int stereo_mode,
 1555                                         int *h_width, int *h_height)
 1556 {
 1557     switch (stereo_mode) {
 1558     case MATROSKA_VIDEO_STEREOMODE_TYPE_MONO:
 1559     case MATROSKA_VIDEO_STEREOMODE_TYPE_CHECKERBOARD_RL:
 1560     case MATROSKA_VIDEO_STEREOMODE_TYPE_CHECKERBOARD_LR:
 1561     case MATROSKA_VIDEO_STEREOMODE_TYPE_BOTH_EYES_BLOCK_RL:
 1562     case MATROSKA_VIDEO_STEREOMODE_TYPE_BOTH_EYES_BLOCK_LR:
 1563         break;
 1564     case MATROSKA_VIDEO_STEREOMODE_TYPE_RIGHT_LEFT:
 1565     case MATROSKA_VIDEO_STEREOMODE_TYPE_LEFT_RIGHT:
 1566     case MATROSKA_VIDEO_STEREOMODE_TYPE_COL_INTERLEAVED_RL:
 1567     case MATROSKA_VIDEO_STEREOMODE_TYPE_COL_INTERLEAVED_LR:
 1568         *h_width = 2;
 1569         break;
 1570     case MATROSKA_VIDEO_STEREOMODE_TYPE_BOTTOM_TOP:
 1571     case MATROSKA_VIDEO_STEREOMODE_TYPE_TOP_BOTTOM:
 1572     case MATROSKA_VIDEO_STEREOMODE_TYPE_ROW_INTERLEAVED_RL:
 1573     case MATROSKA_VIDEO_STEREOMODE_TYPE_ROW_INTERLEAVED_LR:
 1574         *h_height = 2;
 1575         break;
 1576     }
 1577 }
 1578 
 1579 static int matroska_parse_tracks(AVFormatContext *s)
 1580 {
 1581     MatroskaDemuxContext *matroska = s->priv_data;
 1582     MatroskaTrack *tracks = matroska->tracks.elem;
 1583     AVStream *st;
 1584     int i, j, ret;
 1585 
 1586     for (i = 0; i < matroska->tracks.nb_elem; i++) {
 1587         MatroskaTrack *track = &tracks[i];
 1588         enum AVCodecID codec_id = AV_CODEC_ID_NONE;
 1589         EbmlList *encodings_list = &track->encodings;
 1590         MatroskaTrackEncoding *encodings = encodings_list->elem;
 1591         uint8_t *extradata = NULL;
 1592         int extradata_size = 0;
 1593         int extradata_offset = 0;
 1594         AVIOContext b;
 1595 
 1596         /* Apply some sanity checks. */
 1597         if (track->type != MATROSKA_TRACK_TYPE_VIDEO &&
 1598             track->type != MATROSKA_TRACK_TYPE_AUDIO &&
 1599             track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
 1600             av_log(matroska->ctx, AV_LOG_INFO,
 1601                    "Unknown or unsupported track type %"PRIu64"\n",
 1602                    track->type);
 1603             continue;
 1604         }
 1605         if (!track->codec_id)
 1606             continue;
 1607 
 1608         if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
 1609             if (!track->default_duration && track->video.frame_rate > 0)
 1610                 track->default_duration = 1000000000 / track->video.frame_rate;
 1611             if (!track->video.display_width)
 1612                 track->video.display_width = track->video.pixel_width;
 1613             if (!track->video.display_height)
 1614                 track->video.display_height = track->video.pixel_height;
 1615         } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
 1616             if (!track->audio.out_samplerate)
 1617                 track->audio.out_samplerate = track->audio.samplerate;
 1618         }
 1619         if (encodings_list->nb_elem > 1) {
 1620             av_log(matroska->ctx, AV_LOG_ERROR,
 1621                    "Multiple combined encodings not supported");
 1622         } else if (encodings_list->nb_elem == 1) {
 1623             if (encodings[0].type ||
 1624                 (
 1625 #if CONFIG_ZLIB
 1626                  encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_ZLIB  &&
 1627 #endif
 1628 #if CONFIG_BZLIB
 1629                  encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_BZLIB &&
 1630 #endif
 1631 #if CONFIG_LZO
 1632                  encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_LZO   &&
 1633 #endif
 1634                  encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP)) {
 1635                 encodings[0].scope = 0;
 1636                 av_log(matroska->ctx, AV_LOG_ERROR,
 1637                        "Unsupported encoding type");
 1638             } else if (track->codec_priv.size && encodings[0].scope & 2) {
 1639                 uint8_t *codec_priv = track->codec_priv.data;
 1640                 int ret = matroska_decode_buffer(&track->codec_priv.data,
 1641                                                  &track->codec_priv.size,
 1642                                                  track);
 1643                 if (ret < 0) {
 1644                     track->codec_priv.data = NULL;
 1645                     track->codec_priv.size = 0;
 1646                     av_log(matroska->ctx, AV_LOG_ERROR,
 1647                            "Failed to decode codec private data\n");
 1648                 }
 1649 
 1650                 if (codec_priv != track->codec_priv.data)
 1651                     av_free(codec_priv);
 1652             }
 1653         }
 1654 
 1655         for (j = 0; ff_mkv_codec_tags[j].id != AV_CODEC_ID_NONE; j++) {
 1656             if (!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
 1657                          strlen(ff_mkv_codec_tags[j].str))) {
 1658                 codec_id = ff_mkv_codec_tags[j].id;
 1659                 break;
 1660             }
 1661         }
 1662 
 1663         st = track->stream = avformat_new_stream(s, NULL);
 1664         if (!st)
 1665             return AVERROR(ENOMEM);
 1666 
 1667         if (!strcmp(track->codec_id, "V_MS/VFW/FOURCC") &&
 1668             track->codec_priv.size >= 40                &&
 1669             track->codec_priv.data) {
 1670             track->ms_compat    = 1;
 1671             track->video.fourcc = AV_RL32(track->codec_priv.data + 16);
 1672             codec_id            = ff_codec_get_id(ff_codec_bmp_tags,
 1673                                                   track->video.fourcc);
 1674             extradata_offset    = 40;
 1675         } else if (!strcmp(track->codec_id, "A_MS/ACM") &&
 1676                    track->codec_priv.size >= 14         &&
 1677                    track->codec_priv.data) {
 1678             int ret;
 1679             ffio_init_context(&b, track->codec_priv.data,
 1680                               track->codec_priv.size,
 1681                               0, NULL, NULL, NULL, NULL);
 1682             ret = ff_get_wav_header(s, &b, st->codecpar, track->codec_priv.size);
 1683             if (ret < 0)
 1684                 return ret;
 1685             codec_id         = st->codecpar->codec_id;
 1686             extradata_offset = FFMIN(track->codec_priv.size, 18);
 1687         } else if (!strcmp(track->codec_id, "V_QUICKTIME") &&
 1688                    (track->codec_priv.size >= 86)          &&
 1689                    (track->codec_priv.data)) {
 1690             if (track->codec_priv.size == AV_RB32(track->codec_priv.data)) {
 1691                 track->video.fourcc = AV_RL32(track->codec_priv.data + 4);
 1692                 codec_id            = ff_codec_get_id(ff_codec_movvideo_tags,
 1693                                                       track->video.fourcc);
 1694             }
 1695             if (codec_id == AV_CODEC_ID_NONE) {
 1696                 track->video.fourcc = AV_RL32(track->codec_priv.data);
 1697                 codec_id            = ff_codec_get_id(ff_codec_movvideo_tags,
 1698                                                       track->video.fourcc);
 1699             }
 1700             if (codec_id == AV_CODEC_ID_NONE) {
 1701                 char buf[32];
 1702                 av_get_codec_tag_string(buf, sizeof(buf), track->video.fourcc);
 1703                 av_log(matroska->ctx, AV_LOG_ERROR,
 1704                        "mov FourCC not found %s.\n", buf);
 1705             }
 1706         } else if (codec_id == AV_CODEC_ID_PCM_S16BE) {
 1707             switch (track->audio.bitdepth) {
 1708             case  8:
 1709                 codec_id = AV_CODEC_ID_PCM_U8;
 1710                 break;
 1711             case 24:
 1712                 codec_id = AV_CODEC_ID_PCM_S24BE;
 1713                 break;
 1714             case 32:
 1715                 codec_id = AV_CODEC_ID_PCM_S32BE;
 1716                 break;
 1717             }
 1718         } else if (codec_id == AV_CODEC_ID_PCM_S16LE) {
 1719             switch (track->audio.bitdepth) {
 1720             case  8:
 1721                 codec_id = AV_CODEC_ID_PCM_U8;
 1722                 break;
 1723             case 24:
 1724                 codec_id = AV_CODEC_ID_PCM_S24LE;
 1725                 break;
 1726             case 32:
 1727                 codec_id = AV_CODEC_ID_PCM_S32LE;
 1728                 break;
 1729             }
 1730         } else if (codec_id == AV_CODEC_ID_PCM_F32LE &&
 1731                    track->audio.bitdepth == 64) {
 1732             codec_id = AV_CODEC_ID_PCM_F64LE;
 1733         } else if (codec_id == AV_CODEC_ID_AAC && !track->codec_priv.size) {
 1734             int profile = matroska_aac_profile(track->codec_id);
 1735             int sri     = matroska_aac_sri(track->audio.samplerate);
 1736             extradata   = av_mallocz(5 + AV_INPUT_BUFFER_PADDING_SIZE);
 1737             if (!extradata)
 1738                 return AVERROR(ENOMEM);
 1739             extradata[0] = (profile << 3) | ((sri & 0x0E) >> 1);
 1740             extradata[1] = ((sri & 0x01) << 7) | (track->audio.channels << 3);
 1741             if (strstr(track->codec_id, "SBR")) {
 1742                 sri            = matroska_aac_sri(track->audio.out_samplerate);
 1743                 extradata[2]   = 0x56;
 1744                 extradata[3]   = 0xE5;
 1745                 extradata[4]   = 0x80 | (sri << 3);
 1746                 extradata_size = 5;
 1747             } else
 1748                 extradata_size = 2;
 1749         } else if (codec_id == AV_CODEC_ID_ALAC && track->codec_priv.size) {
 1750             /* Only ALAC's magic cookie is stored in Matroska's track headers.
 1751              * Create the "atom size", "tag", and "tag version" fields the
 1752              * decoder expects manually. */
 1753             extradata_size = 12 + track->codec_priv.size;
 1754             extradata      = av_mallocz(extradata_size +
 1755                                         AV_INPUT_BUFFER_PADDING_SIZE);
 1756             if (!extradata)
 1757                 return AVERROR(ENOMEM);
 1758             AV_WB32(extradata, extradata_size);
 1759             memcpy(&extradata[4], "alac", 4);
 1760             AV_WB32(&extradata[8], 0);
 1761             memcpy(&extradata[12], track->codec_priv.data,
 1762                    track->codec_priv.size);
 1763         } else if (codec_id == AV_CODEC_ID_TTA) {
 1764             extradata_size = 30;
 1765             extradata      = av_mallocz(extradata_size);
 1766             if (!extradata)
 1767                 return AVERROR(ENOMEM);
 1768             ffio_init_context(&b, extradata, extradata_size, 1,
 1769                               NULL, NULL, NULL, NULL);
 1770             avio_write(&b, "TTA1", 4);
 1771             avio_wl16(&b, 1);
 1772             avio_wl16(&b, track->audio.channels);
 1773             avio_wl16(&b, track->audio.bitdepth);
 1774             avio_wl32(&b, track->audio.out_samplerate);
 1775             avio_wl32(&b, matroska->ctx->duration *
 1776                       track->audio.out_samplerate);
 1777         } else if (codec_id == AV_CODEC_ID_RV10 ||
 1778                    codec_id == AV_CODEC_ID_RV20 ||
 1779                    codec_id == AV_CODEC_ID_RV30 ||
 1780                    codec_id == AV_CODEC_ID_RV40) {
 1781             extradata_offset = 26;
 1782         } else if (codec_id == AV_CODEC_ID_RA_144) {
 1783             track->audio.out_samplerate = 8000;
 1784             track->audio.channels       = 1;
 1785         } else if (codec_id == AV_CODEC_ID_RA_288 ||
 1786                    codec_id == AV_CODEC_ID_COOK   ||
 1787                    codec_id == AV_CODEC_ID_ATRAC3 ||
 1788                    codec_id == AV_CODEC_ID_SIPR) {
 1789             int flavor;
 1790             ffio_init_context(&b, track->codec_priv.data,
 1791                               track->codec_priv.size,
 1792                               0, NULL, NULL, NULL, NULL);
 1793             avio_skip(&b, 22);
 1794             flavor                       = avio_rb16(&b);
 1795             track->audio.coded_framesize = avio_rb32(&b);
 1796             avio_skip(&b, 12);
 1797             track->audio.sub_packet_h    = avio_rb16(&b);
 1798             track->audio.frame_size      = avio_rb16(&b);
 1799             track->audio.sub_packet_size = avio_rb16(&b);
 1800             if (flavor                        < 0 ||
 1801                 track->audio.coded_framesize <= 0 ||
 1802                 track->audio.sub_packet_h    <= 0 ||
 1803                 track->audio.frame_size      <= 0 ||
 1804                 track->audio.sub_packet_size <= 0)
 1805                 return AVERROR_INVALIDDATA;
 1806             track->audio.buf = av_malloc(track->audio.frame_size *
 1807                                          track->audio.sub_packet_h);
 1808             if (!track->audio.buf)
 1809                 return AVERROR(ENOMEM);
 1810             if (codec_id == AV_CODEC_ID_RA_288) {
 1811                 st->codecpar->block_align = track->audio.coded_framesize;
 1812                 track->codec_priv.size = 0;
 1813             } else {
 1814                 if (codec_id == AV_CODEC_ID_SIPR && flavor < 4) {
 1815                     static const int sipr_bit_rate[4] = { 6504, 8496, 5000, 16000 };
 1816                     track->audio.sub_packet_size = ff_sipr_subpk_size[flavor];
 1817                     st->codecpar->bit_rate          = sipr_bit_rate[flavor];
 1818                 }
 1819                 st->codecpar->block_align = track->audio.sub_packet_size;
 1820                 extradata_offset       = 78;
 1821             }
 1822         } else if (codec_id == AV_CODEC_ID_FLAC && track->codec_priv.size) {
 1823             ret = matroska_parse_flac(s, track, &extradata_offset);
 1824             if (ret < 0)
 1825                 return ret;
 1826         }
 1827         track->codec_priv.size -= extradata_offset;
 1828 
 1829         if (codec_id == AV_CODEC_ID_NONE)
 1830             av_log(matroska->ctx, AV_LOG_INFO,
 1831                    "Unknown/unsupported AVCodecID %s.\n", track->codec_id);
 1832 
 1833         if (track->time_scale < 0.01)
 1834             track->time_scale = 1.0;
 1835         avpriv_set_pts_info(st, 64, matroska->time_scale * track->time_scale,
 1836                             1000 * 1000 * 1000);    /* 64 bit pts in ns */
 1837 
 1838         if (track->type == MATROSKA_TRACK_TYPE_AUDIO &&
 1839             track->audio.out_samplerate) {
 1840             st->codecpar->initial_padding = av_rescale_q(track->codec_delay,
 1841                                                          (AVRational){ 1, 1000000000 },
 1842                                                          (AVRational){ 1, track->audio.out_samplerate });
 1843         }
 1844 
 1845         /* convert the delay from ns to the track timebase */
 1846         track->codec_delay = av_rescale_q(track->codec_delay,
 1847                                           (AVRational){ 1, 1000000000 },
 1848                                           st->time_base);
 1849 
 1850         st->codecpar->codec_id = codec_id;
 1851         st->start_time      = 0;
 1852         if (strcmp(track->language, "und"))
 1853             av_dict_set(&st->metadata, "language", track->language, 0);
 1854         av_dict_set(&st->metadata, "title", track->name, 0);
 1855 
 1856         if (track->flag_default)
 1857             st->disposition |= AV_DISPOSITION_DEFAULT;
 1858         if (track->flag_forced)
 1859             st->disposition |= AV_DISPOSITION_FORCED;
 1860 
 1861         if (!st->codecpar->extradata) {
 1862             if (extradata) {
 1863                 st->codecpar->extradata      = extradata;
 1864                 st->codecpar->extradata_size = extradata_size;
 1865             } else if (track->codec_priv.data && track->codec_priv.size > 0) {
 1866                 st->codecpar->extradata = av_mallocz(track->codec_priv.size +
 1867                                                      AV_INPUT_BUFFER_PADDING_SIZE);
 1868                 if (!st->codecpar->extradata)
 1869                     return AVERROR(ENOMEM);
 1870                 st->codecpar->extradata_size = track->codec_priv.size;
 1871                 memcpy(st->codecpar->extradata,
 1872                        track->codec_priv.data + extradata_offset,
 1873                        track->codec_priv.size);
 1874             }
 1875         }
 1876 
 1877         if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
 1878             int display_width_mul  = 1;
 1879             int display_height_mul = 1;
 1880 
 1881             st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
 1882             st->codecpar->codec_tag  = track->video.fourcc;
 1883             st->codecpar->width      = track->video.pixel_width;
 1884             st->codecpar->height     = track->video.pixel_height;
 1885 
 1886             if (track->video.interlaced == MATROSKA_VIDEO_INTERLACE_FLAG_INTERLACED)
 1887                 st->codecpar->field_order = mkv_field_order(track->video.field_order);
 1888 
 1889             if (track->video.stereo_mode && track->video.stereo_mode < MATROSKA_VIDEO_STEREOMODE_TYPE_NB)
 1890                 mkv_stereo_mode_display_mul(track->video.stereo_mode, &display_width_mul, &display_height_mul);
 1891 
 1892             av_reduce(&st->sample_aspect_ratio.num,
 1893                       &st->sample_aspect_ratio.den,
 1894                       st->codecpar->height * track->video.display_width  * display_width_mul,
 1895                       st->codecpar->width  * track->video.display_height * display_height_mul,
 1896                       255);
 1897             if (st->codecpar->codec_id != AV_CODEC_ID_H264 &&
 1898                 st->codecpar->codec_id != AV_CODEC_ID_HEVC)
 1899                 st->need_parsing = AVSTREAM_PARSE_HEADERS;
 1900             if (track->default_duration) {
 1901                 av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
 1902                           1000000000, track->default_duration, 30000);
 1903             }
 1904             // add stream level stereo3d side data if it is a supported format
 1905             if (track->video.stereo_mode < MATROSKA_VIDEO_STEREOMODE_TYPE_NB &&
 1906                 track->video.stereo_mode != 10 && track->video.stereo_mode != 12) {
 1907                 int ret = ff_mkv_stereo3d_conv(st, track->video.stereo_mode);
 1908                 if (ret < 0)
 1909                     return ret;
 1910             }
 1911         } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
 1912             st->codecpar->codec_type  = AVMEDIA_TYPE_AUDIO;
 1913             st->codecpar->sample_rate = track->audio.out_samplerate;
 1914             st->codecpar->channels    = track->audio.channels;
 1915             if (st->codecpar->codec_id != AV_CODEC_ID_AAC)
 1916                 st->need_parsing = AVSTREAM_PARSE_HEADERS;
 1917             if (st->codecpar->codec_id == AV_CODEC_ID_MP3)
 1918                 st->need_parsing = AVSTREAM_PARSE_FULL;
 1919         } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
 1920             st->codecpar->codec_type = AVMEDIA_TYPE_SUBTITLE;
 1921             if (st->codecpar->codec_id == AV_CODEC_ID_SSA)
 1922                 matroska->contains_ssa = 1;
 1923         }
 1924     }
 1925 
 1926     return 0;
 1927 }
 1928 
 1929 static int matroska_read_header(AVFormatContext *s)
 1930 {
 1931     MatroskaDemuxContext *matroska = s->priv_data;
 1932     EbmlList *attachments_list = &matroska->attachments;
 1933     EbmlList *chapters_list    = &matroska->chapters;
 1934     MatroskaAttachment *attachments;
 1935     MatroskaChapter *chapters;
 1936     uint64_t max_start = 0;
 1937     int64_t pos;
 1938     Ebml ebml = { 0 };
 1939     int i, j, res;
 1940 
 1941     matroska->ctx = s;
 1942 
 1943     /* First read the EBML header. */
 1944     if (ebml_parse(matroska, ebml_syntax, &ebml) || !ebml.doctype) {
 1945         av_log(matroska->ctx, AV_LOG_ERROR, "EBML header parsing failed\n");
 1946         ebml_free(ebml_syntax, &ebml);
 1947         return AVERROR_INVALIDDATA;
 1948     }
 1949     if (ebml.version         > EBML_VERSION      ||
 1950         ebml.max_size        > sizeof(uint64_t)  ||
 1951         ebml.id_length       > sizeof(uint32_t)  ||
 1952         ebml.doctype_version > 3) {
 1953         av_log(matroska->ctx, AV_LOG_ERROR,
 1954                "EBML header using unsupported features\n"
 1955                "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
 1956                ebml.version, ebml.doctype, ebml.doctype_version);
 1957         ebml_free(ebml_syntax, &ebml);
 1958         return AVERROR_PATCHWELCOME;
 1959     }
 1960     for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++)
 1961         if (!strcmp(ebml.doctype, matroska_doctypes[i]))
 1962             break;
 1963     if (i >= FF_ARRAY_ELEMS(matroska_doctypes)) {
 1964         av_log(s, AV_LOG_WARNING, "Unknown EBML doctype '%s'\n", ebml.doctype);
 1965         if (matroska->ctx->error_recognition & AV_EF_EXPLODE) {
 1966             ebml_free(ebml_syntax, &ebml);
 1967             return AVERROR_INVALIDDATA;
 1968         }
 1969     }
 1970     ebml_free(ebml_syntax, &ebml);
 1971 
 1972     /* The next thing is a segment. */
 1973     pos = avio_tell(matroska->ctx->pb);
 1974     res = ebml_parse(matroska, matroska_segments, matroska);
 1975     // try resyncing until we find a EBML_STOP type element.
 1976     while (res != 1) {
 1977         res = matroska_resync(matroska, pos);
 1978         if (res < 0)
 1979             return res;
 1980         pos = avio_tell(matroska->ctx->pb);
 1981         res = ebml_parse(matroska, matroska_segment, matroska);
 1982     }
 1983     matroska_execute_seekhead(matroska);
 1984 
 1985     if (!matroska->time_scale)
 1986         matroska->time_scale = 1000000;
 1987     if (matroska->duration)
 1988         matroska->ctx->duration = matroska->duration * matroska->time_scale *
 1989                                   1000 / AV_TIME_BASE;
 1990     av_dict_set(&s->metadata, "title", matroska->title, 0);
 1991 
 1992     res = matroska_parse_tracks(s);
 1993     if (res < 0)
 1994         return res;
 1995 
 1996     attachments = attachments_list->elem;
 1997     for (j = 0; j < attachments_list->nb_elem; j++) {
 1998         if (!(attachments[j].filename && attachments[j].mime &&
 1999               attachments[j].bin.data && attachments[j].bin.size > 0)) {
 2000             av_log(matroska->ctx, AV_LOG_ERROR, "incomplete attachment\n");
 2001         } else {
 2002             AVStream *st = avformat_new_stream(s, NULL);
 2003             if (!st)
 2004                 break;
 2005             av_dict_set(&st->metadata, "filename", attachments[j].filename, 0);
 2006             av_dict_set(&st->metadata, "mimetype", attachments[j].mime, 0);
 2007             st->codecpar->codec_id   = AV_CODEC_ID_NONE;
 2008 
 2009             for (i = 0; ff_mkv_image_mime_tags[i].id != AV_CODEC_ID_NONE; i++) {
 2010                 if (!strncmp(ff_mkv_image_mime_tags[i].str, attachments[j].mime,
 2011                              strlen(ff_mkv_image_mime_tags[i].str))) {
 2012                     st->codecpar->codec_id = ff_mkv_image_mime_tags[i].id;
 2013                     break;
 2014                 }
 2015             }
 2016 
 2017             attachments[j].stream = st;
 2018 
 2019             if (st->codecpar->codec_id != AV_CODEC_ID_NONE) {
 2020                 st->disposition         |= AV_DISPOSITION_ATTACHED_PIC;
 2021                 st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
 2022 
 2023                 av_init_packet(&st->attached_pic);
 2024                 if ((res = av_new_packet(&st->attached_pic, attachments[j].bin.size)) < 0)
 2025                     return res;
 2026                 memcpy(st->attached_pic.data, attachments[j].bin.data, attachments[j].bin.size);
 2027                 st->attached_pic.stream_index = st->index;
 2028                 st->attached_pic.flags       |= AV_PKT_FLAG_KEY;
 2029             } else {
 2030                 st->codecpar->codec_type = AVMEDIA_TYPE_ATTACHMENT;
 2031                 st->codecpar->extradata  = av_malloc(attachments[j].bin.size);
 2032                 if (!st->codecpar->extradata)
 2033                     break;
 2034 
 2035                 st->codecpar->extradata_size = attachments[j].bin.size;
 2036                 memcpy(st->codecpar->extradata, attachments[j].bin.data,
 2037                        attachments[j].bin.size);
 2038 
 2039                 for (i = 0; ff_mkv_mime_tags[i].id != AV_CODEC_ID_NONE; i++) {
 2040                     if (!strncmp(ff_mkv_mime_tags[i].str, attachments[j].mime,
 2041                                 strlen(ff_mkv_mime_tags[i].str))) {
 2042                         st->codecpar->codec_id = ff_mkv_mime_tags[i].id;
 2043                         break;
 2044                     }
 2045                 }
 2046             }
 2047         }
 2048     }
 2049 
 2050     chapters = chapters_list->elem;
 2051     for (i = 0; i < chapters_list->nb_elem; i++)
 2052         if (chapters[i].start != AV_NOPTS_VALUE && chapters[i].uid &&
 2053             (max_start == 0 || chapters[i].start > max_start)) {
 2054             chapters[i].chapter =
 2055                 avpriv_new_chapter(s, chapters[i].uid,
 2056                                    (AVRational) { 1, 1000000000 },
 2057                                    chapters[i].start, chapters[i].end,
 2058                                    chapters[i].title);
 2059             av_dict_set(&chapters[i].chapter->metadata,
 2060                         "title", chapters[i].title, 0);
 2061             max_start = chapters[i].start;
 2062         }
 2063 
 2064     matroska_convert_tags(s);
 2065 
 2066     return 0;
 2067 }
 2068 
 2069 /*
 2070  * Put one packet in an application-supplied AVPacket struct.
 2071  * Returns 0 on success or -1 on failure.
 2072  */
 2073 static int matroska_deliver_packet(MatroskaDemuxContext *matroska,
 2074                                    AVPacket *pkt)
 2075 {
 2076     if (matroska->num_packets > 0) {
 2077         memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
 2078         av_free(matroska->packets[0]);
 2079         if (matroska->num_packets > 1) {
 2080             void *newpackets;
 2081             memmove(&matroska->packets[0], &matroska->packets[1],
 2082                     (matroska->num_packets - 1) * sizeof(AVPacket *));
 2083             newpackets = av_realloc(matroska->packets,
 2084                                     (matroska->num_packets - 1) *
 2085                                     sizeof(AVPacket *));
 2086             if (newpackets)
 2087                 matroska->packets = newpackets;
 2088         } else {
 2089             av_freep(&matroska->packets);
 2090             matroska->prev_pkt = NULL;
 2091         }
 2092         matroska->num_packets--;
 2093         return 0;
 2094     }
 2095 
 2096     return -1;
 2097 }
 2098 
 2099 /*
 2100  * Free all packets in our internal queue.
 2101  */
 2102 static void matroska_clear_queue(MatroskaDemuxContext *matroska)
 2103 {
 2104     matroska->prev_pkt = NULL;
 2105     if (matroska->packets) {
 2106         int n;
 2107         for (n = 0; n < matroska->num_packets; n++) {
 2108             av_packet_unref(matroska->packets[n]);
 2109             av_free(matroska->packets[n]);
 2110         }
 2111         av_freep(&matroska->packets);
 2112         matroska->num_packets = 0;
 2113     }
 2114 }
 2115 
 2116 static int matroska_parse_laces(MatroskaDemuxContext *matroska, uint8_t **buf,
 2117                                 int *buf_size, int type,
 2118                                 uint32_t **lace_buf, int *laces)
 2119 {
 2120     int res = 0, n, size = *buf_size;
 2121     uint8_t *data = *buf;
 2122     uint32_t *lace_size;
 2123 
 2124     if (!type) {
 2125         *laces    = 1;
 2126         *lace_buf = av_mallocz(sizeof(int));
 2127         if (!*lace_buf)
 2128             return AVERROR(ENOMEM);
 2129 
 2130         *lace_buf[0] = size;
 2131         return 0;
 2132     }
 2133 
 2134     assert(size > 0);
 2135     *laces    = *data + 1;
 2136     data     += 1;
 2137     size     -= 1;
 2138     lace_size = av_mallocz(*laces * sizeof(int));
 2139     if (!lace_size)
 2140         return AVERROR(ENOMEM);
 2141 
 2142     switch (type) {
 2143     case 0x1: /* Xiph lacing */
 2144     {
 2145         uint8_t temp;
 2146         uint32_t total = 0;
 2147         for (n = 0; res == 0 && n < *laces - 1; n++) {
 2148             while (1) {
 2149                 if (size == 0) {
 2150                     res = AVERROR_EOF;
 2151                     break;
 2152                 }
 2153                 temp          = *data;
 2154                 lace_size[n] += temp;
 2155                 data         += 1;
 2156                 size         -= 1;
 2157                 if (temp != 0xff)
 2158                     break;
 2159             }
 2160             total += lace_size[n];
 2161         }
 2162         if (size <= total) {
 2163             res = AVERROR_INVALIDDATA;
 2164             break;
 2165         }
 2166 
 2167         lace_size[n] = size - total;
 2168         break;
 2169     }
 2170 
 2171     case 0x2: /* fixed-size lacing */
 2172         if (size % (*laces)) {
 2173             res = AVERROR_INVALIDDATA;
 2174             break;
 2175         }
 2176         for (n = 0; n < *laces; n++)
 2177             lace_size[n] = size / *laces;
 2178         break;
 2179 
 2180     case 0x3: /* EBML lacing */
 2181     {
 2182         uint64_t num;
 2183         uint64_t total;
 2184         n = matroska_ebmlnum_uint(matroska, data, size, &num);
 2185         if (n < 0) {
 2186             av_log(matroska->ctx, AV_LOG_INFO,
 2187                    "EBML block data error\n");
 2188             res = n;
 2189             break;
 2190         }
 2191         data += n;
 2192         size -= n;
 2193         total = lace_size[0] = num;
 2194         for (n = 1; res == 0 && n < *laces - 1; n++) {
 2195             int64_t snum;
 2196             int r;
 2197             r = matroska_ebmlnum_sint(matroska, data, size, &snum);
 2198             if (r < 0) {
 2199                 av_log(matroska->ctx, AV_LOG_INFO,
 2200                        "EBML block data error\n");
 2201                 res = r;
 2202                 break;
 2203             }
 2204             data        += r;
 2205             size        -= r;
 2206             lace_size[n] = lace_size[n - 1] + snum;
 2207             total       += lace_size[n];
 2208         }
 2209         if (size <= total) {
 2210             res = AVERROR_INVALIDDATA;
 2211             break;
 2212         }
 2213         lace_size[*laces - 1] = size - total;
 2214         break;
 2215     }
 2216     }
 2217 
 2218     *buf      = data;
 2219     *lace_buf = lace_size;
 2220     *buf_size = size;
 2221 
 2222     return res;
 2223 }
 2224 
 2225 static int matroska_parse_rm_audio(MatroskaDemuxContext *matroska,
 2226                                    MatroskaTrack *track, AVStream *st,
 2227                                    uint8_t *data, int size, uint64_t timecode,
 2228                                    uint64_t duration, int64_t pos)
 2229 {
 2230     int a = st->codecpar->block_align;
 2231     int sps = track->audio.sub_packet_size;
 2232     int cfs = track->audio.coded_framesize;
 2233     int h   = track->audio.sub_packet_h;
 2234     int y   = track->audio.sub_packet_cnt;
 2235     int w   = track->audio.frame_size;
 2236     int x;
 2237 
 2238     if (!track->audio.pkt_cnt) {
 2239         if (track->audio.sub_packet_cnt == 0)
 2240             track->audio.buf_timecode = timecode;
 2241         if (st->codecpar->codec_id == AV_CODEC_ID_RA_288) {
 2242             if (size < cfs * h / 2) {
 2243                 av_log(matroska->ctx, AV_LOG_ERROR,
 2244                        "Corrupt int4 RM-style audio packet size\n");
 2245                 return AVERROR_INVALIDDATA;
 2246             }
 2247             for (x = 0; x < h / 2; x++)
 2248                 memcpy(track->audio.buf + x * 2 * w + y * cfs,
 2249                        data + x * cfs, cfs);
 2250         } else if (st->codecpar->codec_id == AV_CODEC_ID_SIPR) {
 2251             if (size < w) {
 2252                 av_log(matroska->ctx, AV_LOG_ERROR,
 2253                        "Corrupt sipr RM-style audio packet size\n");
 2254                 return AVERROR_INVALIDDATA;
 2255             }
 2256             memcpy(track->audio.buf + y * w, data, w);
 2257         } else {
 2258             if (size < sps * w / sps) {
 2259                 av_log(matroska->ctx, AV_LOG_ERROR,
 2260                        "Corrupt generic RM-style audio packet size\n");
 2261                 return AVERROR_INVALIDDATA;
 2262             }
 2263             for (x = 0; x < w / sps; x++)
 2264                 memcpy(track->audio.buf +
 2265                        sps * (h * x + ((h + 1) / 2) * (y & 1) + (y >> 1)),
 2266                        data + x * sps, sps);
 2267         }
 2268 
 2269         if (++track->audio.sub_packet_cnt >= h) {
 2270             if (st->codecpar->codec_id == AV_CODEC_ID_SIPR)
 2271                 ff_rm_reorder_sipr_data(track->audio.buf, h, w);
 2272             track->audio.sub_packet_cnt = 0;
 2273             track->audio.pkt_cnt        = h * w / a;
 2274         }
 2275     }
 2276 
 2277     while (track->audio.pkt_cnt) {
 2278         int ret;
 2279         AVPacket *pkt = av_mallocz(sizeof(AVPacket));
 2280         if (!pkt)
 2281             return AVERROR(ENOMEM);
 2282 
 2283         ret = av_new_packet(pkt, a);
 2284         if (ret < 0) {
 2285             av_free(pkt);
 2286             return ret;
 2287         }
 2288         memcpy(pkt->data,
 2289                track->audio.buf + a * (h * w / a - track->audio.pkt_cnt--),
 2290                a);
 2291         pkt->pts                  = track->audio.buf_timecode;
 2292         track->audio.buf_timecode = AV_NOPTS_VALUE;
 2293         pkt->pos                  = pos;
 2294         pkt->stream_index         = st->index;
 2295         dynarray_add(&matroska->packets, &matroska->num_packets, pkt);
 2296     }
 2297 
 2298     return 0;
 2299 }
 2300 
 2301 /* reconstruct full wavpack blocks from mangled matroska ones */
 2302 static int matroska_parse_wavpack(MatroskaTrack *track, uint8_t *src,
 2303                                   uint8_t **pdst, int *size)
 2304 {
 2305     uint8_t *dst = NULL;
 2306     int dstlen   = 0;
 2307     int srclen   = *size;
 2308     uint32_t samples;
 2309     uint16_t ver;
 2310     int ret, offset = 0;
 2311 
 2312     if (srclen < 12 || track->stream->codecpar->extradata_size < 2)
 2313         return AVERROR_INVALIDDATA;
 2314 
 2315     ver = AV_RL16(track->stream->codecpar->extradata);
 2316 
 2317     samples = AV_RL32(src);
 2318     src    += 4;
 2319     srclen -= 4;
 2320 
 2321     while (srclen >= 8) {
 2322         int multiblock;
 2323         uint32_t blocksize;
 2324         uint8_t *tmp;
 2325 
 2326         uint32_t flags = AV_RL32(src);
 2327         uint32_t crc   = AV_RL32(src + 4);
 2328         src    += 8;
 2329         srclen -= 8;
 2330 
 2331         multiblock = (flags & 0x1800) != 0x1800;
 2332         if (multiblock) {
 2333             if (srclen < 4) {
 2334                 ret = AVERROR_INVALIDDATA;
 2335                 goto fail;
 2336             }
 2337             blocksize = AV_RL32(src);
 2338             src      += 4;
 2339             srclen   -= 4;
 2340         } else
 2341             blocksize = srclen;
 2342 
 2343         if (blocksize > srclen) {
 2344             ret = AVERROR_INVALIDDATA;
 2345             goto fail;
 2346         }
 2347 
 2348         tmp = av_realloc(dst, dstlen + blocksize + 32);
 2349         if (!tmp) {
 2350             ret = AVERROR(ENOMEM);
 2351             goto fail;
 2352         }
 2353         dst     = tmp;
 2354         dstlen += blocksize + 32;
 2355 
 2356         AV_WL32(dst + offset, MKTAG('w', 'v', 'p', 'k'));   // tag
 2357         AV_WL32(dst + offset +  4, blocksize + 24);         // blocksize - 8
 2358         AV_WL16(dst + offset +  8, ver);                    // version
 2359         AV_WL16(dst + offset + 10, 0);                      // track/index_no
 2360         AV_WL32(dst + offset + 12, 0);                      // total samples
 2361         AV_WL32(dst + offset + 16, 0);                      // block index
 2362         AV_WL32(dst + offset + 20, samples);                // number of samples
 2363         AV_WL32(dst + offset + 24, flags);                  // flags
 2364         AV_WL32(dst + offset + 28, crc);                    // crc
 2365         memcpy(dst + offset + 32, src, blocksize);          // block data
 2366 
 2367         src    += blocksize;
 2368         srclen -= blocksize;
 2369         offset += blocksize + 32;
 2370     }
 2371 
 2372     *pdst = dst;
 2373     *size = dstlen;
 2374 
 2375     return 0;
 2376 
 2377 fail:
 2378     av_freep(&dst);
 2379     return ret;
 2380 }
 2381 
 2382 static int matroska_parse_frame(MatroskaDemuxContext *matroska,
 2383                                 MatroskaTrack *track, AVStream *st,
 2384                                 uint8_t *data, int pkt_size,
 2385                                 uint64_t timecode, uint64_t duration,
 2386                                 int64_t pos, int is_keyframe)
 2387 {
 2388     MatroskaTrackEncoding *encodings = track->encodings.elem;
 2389     uint8_t *pkt_data = data;
 2390     int offset = 0, res;
 2391     AVPacket *pkt;
 2392 
 2393     if (encodings && encodings->scope & 1) {
 2394         res = matroska_decode_buffer(&pkt_data, &pkt_size, track);
 2395         if (res < 0)
 2396             return res;
 2397     }
 2398 
 2399     if (st->codecpar->codec_id == AV_CODEC_ID_WAVPACK) {
 2400         uint8_t *wv_data;
 2401         res = matroska_parse_wavpack(track, pkt_data, &wv_data, &pkt_size);
 2402         if (res < 0) {
 2403             av_log(matroska->ctx, AV_LOG_ERROR,
 2404                    "Error parsing a wavpack block.\n");
 2405             goto fail;
 2406         }
 2407         if (pkt_data != data)
 2408             av_freep(&pkt_data);
 2409         pkt_data = wv_data;
 2410     }
 2411 
 2412     if (st->codecpar->codec_id == AV_CODEC_ID_PRORES)
 2413         offset = 8;
 2414 
 2415     pkt = av_mallocz(sizeof(AVPacket));
 2416     if (!pkt) {
 2417         av_freep(&pkt_data);
 2418         return AVERROR(ENOMEM);
 2419     }
 2420     /* XXX: prevent data copy... */
 2421     if (av_new_packet(pkt, pkt_size + offset) < 0) {
 2422         av_free(pkt);
 2423         av_freep(&pkt_data);
 2424         return AVERROR(ENOMEM);
 2425     }
 2426 
 2427     if (st->codecpar->codec_id == AV_CODEC_ID_PRORES) {
 2428         uint8_t *buf = pkt->data;
 2429         bytestream_put_be32(&buf, pkt_size);
 2430         bytestream_put_be32(&buf, MKBETAG('i', 'c', 'p', 'f'));
 2431     }
 2432 
 2433     memcpy(pkt->data + offset, pkt_data, pkt_size);
 2434 
 2435     if (pkt_data != data)
 2436         av_free(pkt_data);
 2437 
 2438     pkt->flags        = is_keyframe;
 2439     pkt->stream_index = st->index;
 2440 
 2441     if (track->ms_compat)
 2442         pkt->dts = timecode;
 2443     else
 2444         pkt->pts = timecode;
 2445     pkt->pos = pos;
 2446     if (track->type != MATROSKA_TRACK_TYPE_SUBTITLE || st->codecpar->codec_id == AV_CODEC_ID_SRT)
 2447         pkt->duration = duration;
 2448 #if FF_API_CONVERGENCE_DURATION
 2449 FF_DISABLE_DEPRECATION_WARNINGS
 2450     if (st->codecpar->codec_id == AV_CODEC_ID_SRT)
 2451         pkt->convergence_duration = duration;
 2452 FF_ENABLE_DEPRECATION_WARNINGS
 2453 #endif
 2454 
 2455     if (st->codecpar->codec_id == AV_CODEC_ID_SSA)
 2456         matroska_fix_ass_packet(matroska, pkt, duration);
 2457 
 2458     if (matroska->prev_pkt                                 &&
 2459         timecode                         != AV_NOPTS_VALUE &&
 2460         matroska->prev_pkt->pts          == timecode       &&
 2461         matroska->prev_pkt->stream_index == st->index      &&
 2462         st->codecpar->codec_id == AV_CODEC_ID_SSA)
 2463         matroska_merge_packets(matroska->prev_pkt, pkt);
 2464     else {
 2465         dynarray_add(&matroska->packets, &matroska->num_packets, pkt);
 2466         matroska->prev_pkt = pkt;
 2467     }
 2468 
 2469     return 0;
 2470 
 2471 fail:
 2472     if (pkt_data != data)
 2473         av_freep(&pkt_data);
 2474     return res;
 2475 }
 2476 
 2477 static int matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data,
 2478                                 int size, int64_t pos, uint64_t cluster_time,
 2479                                 uint64_t block_duration, int is_keyframe,
 2480                                 int64_t cluster_pos)
 2481 {
 2482     uint64_t timecode = AV_NOPTS_VALUE;
 2483     MatroskaTrack *track;
 2484     int res = 0;
 2485     AVStream *st;
 2486     int16_t block_time;
 2487     uint32_t *lace_size = NULL;
 2488     int n, flags, laces = 0;
 2489     uint64_t num, duration;
 2490 
 2491     if ((n = matroska_ebmlnum_uint(matroska, data, size, &num)) < 0) {
 2492         av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
 2493         return n;
 2494     }
 2495     data += n;
 2496     size -= n;
 2497 
 2498     track = matroska_find_track_by_num(matroska, num);
 2499     if (!track || !track->stream) {
 2500         av_log(matroska->ctx, AV_LOG_INFO,
 2501                "Invalid stream %"PRIu64" or size %u\n", num, size);
 2502         return AVERROR_INVALIDDATA;
 2503     } else if (size <= 3)
 2504         return 0;
 2505     st = track->stream;
 2506     if (st->discard >= AVDISCARD_ALL)
 2507         return res;
 2508 
 2509     block_time = AV_RB16(data);
 2510     data      += 2;
 2511     flags      = *data++;
 2512     size      -= 3;
 2513     if (is_keyframe == -1)
 2514         is_keyframe = flags & 0x80 ? AV_PKT_FLAG_KEY : 0;
 2515 
 2516     if (cluster_time != (uint64_t) -1 &&
 2517         (block_time >= 0 || cluster_time >= -block_time)) {
 2518         timecode = cluster_time + block_time - track->codec_delay;
 2519         if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE &&
 2520             timecode < track->end_timecode)
 2521             is_keyframe = 0;  /* overlapping subtitles are not key frame */
 2522         if (is_keyframe)
 2523             av_add_index_entry(st, cluster_pos, timecode, 0, 0,
 2524                                AVINDEX_KEYFRAME);
 2525     }
 2526 
 2527     if (matroska->skip_to_keyframe &&
 2528         track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
 2529         if (!is_keyframe || timecode < matroska->skip_to_timecode)
 2530             return res;
 2531         matroska->skip_to_keyframe = 0;
 2532     }
 2533 
 2534     res = matroska_parse_laces(matroska, &data, &size, (flags & 0x06) >> 1,
 2535                                &lace_size, &laces);
 2536 
 2537     if (res)
 2538         goto end;
 2539 
 2540     if (block_duration != AV_NOPTS_VALUE) {
 2541         duration = block_duration / laces;
 2542         if (block_duration != duration * laces) {
 2543             av_log(matroska->ctx, AV_LOG_WARNING,
 2544                    "Incorrect block_duration, possibly corrupted container");
 2545         }
 2546     } else {
 2547         duration       = track->default_duration / matroska->time_scale;
 2548         block_duration = duration * laces;
 2549     }
 2550 
 2551     if (timecode != AV_NOPTS_VALUE)
 2552         track->end_timecode =
 2553             FFMAX(track->end_timecode, timecode + block_duration);
 2554 
 2555     for (n = 0; n < laces; n++) {
 2556         if ((st->codecpar->codec_id == AV_CODEC_ID_RA_288 ||
 2557              st->codecpar->codec_id == AV_CODEC_ID_COOK   ||
 2558              st->codecpar->codec_id == AV_CODEC_ID_SIPR   ||
 2559              st->codecpar->codec_id == AV_CODEC_ID_ATRAC3) &&
 2560             st->codecpar->block_align && track->audio.sub_packet_size) {
 2561             res = matroska_parse_rm_audio(matroska, track, st, data,
 2562                                           lace_size[n],
 2563                                           timecode, duration, pos);
 2564             if (res)
 2565                 goto end;
 2566         } else {
 2567             res = matroska_parse_frame(matroska, track, st, data, lace_size[n],
 2568                                        timecode, duration, pos,
 2569                                        !n ? is_keyframe : 0);
 2570             if (res)
 2571                 goto end;
 2572         }
 2573 
 2574         if (timecode != AV_NOPTS_VALUE)
 2575             timecode = duration ? timecode + duration : AV_NOPTS_VALUE;
 2576         data += lace_size[n];
 2577     }
 2578 
 2579 end:
 2580     av_free(lace_size);
 2581     return res;
 2582 }
 2583 
 2584 static int matroska_parse_cluster_incremental(MatroskaDemuxContext *matroska)
 2585 {
 2586     EbmlList *blocks_list;
 2587     MatroskaBlock *blocks;
 2588     int i, res;
 2589     res = ebml_parse(matroska,
 2590                      matroska_cluster_incremental_parsing,
 2591                      &matroska->current_cluster);
 2592     if (res == 1) {
 2593         /* New Cluster */
 2594         if (matroska->current_cluster_pos)
 2595             ebml_level_end(matroska);
 2596         ebml_free(matroska_cluster, &matroska->current_cluster);
 2597         memset(&matroska->current_cluster, 0, sizeof(MatroskaCluster));
 2598         matroska->current_cluster_num_blocks = 0;
 2599         matroska->current_cluster_pos        = avio_tell(matroska->ctx->pb);
 2600         matroska->prev_pkt                   = NULL;
 2601         /* sizeof the ID which was already read */
 2602         if (matroska->current_id)
 2603             matroska->current_cluster_pos -= 4;
 2604         res = ebml_parse(matroska,
 2605                          matroska_clusters_incremental,
 2606                          &matroska->current_cluster);
 2607         /* Try parsing the block again. */
 2608         if (res == 1)
 2609             res = ebml_parse(matroska,
 2610                              matroska_cluster_incremental_parsing,
 2611                              &matroska->current_cluster);
 2612     }
 2613 
 2614     if (!res &&
 2615         matroska->current_cluster_num_blocks <
 2616         matroska->current_cluster.blocks.nb_elem) {
 2617         blocks_list = &matroska->current_cluster.blocks;
 2618         blocks      = blocks_list->elem;
 2619 
 2620         matroska->current_cluster_num_blocks = blocks_list->nb_elem;
 2621         i                                    = blocks_list->nb_elem - 1;
 2622         if (blocks[i].bin.size > 0 && blocks[i].bin.data) {
 2623             int is_keyframe = blocks[i].non_simple ? !blocks[i].reference : -1;
 2624             if (!blocks[i].non_simple)
 2625                 blocks[i].duration = AV_NOPTS_VALUE;
 2626             res = matroska_parse_block(matroska, blocks[i].bin.data,
 2627                                        blocks[i].bin.size, blocks[i].bin.pos,
 2628                                        matroska->current_cluster.timecode,
 2629                                        blocks[i].duration, is_keyframe,
 2630                                        matroska->current_cluster_pos);
 2631         }
 2632     }
 2633 
 2634     if (res < 0)
 2635         matroska->done = 1;
 2636     return res;
 2637 }
 2638 
 2639 static int matroska_parse_cluster(MatroskaDemuxContext *matroska)
 2640 {
 2641     MatroskaCluster cluster = { 0 };
 2642     EbmlList *blocks_list;
 2643     MatroskaBlock *blocks;
 2644     int i, res;
 2645     int64_t pos;
 2646 
 2647     if (!matroska->contains_ssa)
 2648         return matroska_parse_cluster_incremental(matroska);
 2649     pos = avio_tell(matroska->ctx->pb);
 2650     matroska->prev_pkt = NULL;
 2651     if (matroska->current_id)
 2652         pos -= 4;  /* sizeof the ID which was already read */
 2653     res         = ebml_parse(matroska, matroska_clusters, &cluster);
 2654     blocks_list = &cluster.blocks;
 2655     blocks      = blocks_list->elem;
 2656     for (i = 0; i < blocks_list->nb_elem && !res; i++)
 2657         if (blocks[i].bin.size > 0 && blocks[i].bin.data) {
 2658             int is_keyframe = blocks[i].non_simple ? !blocks[i].reference : -1;
 2659             if (!blocks[i].non_simple)
 2660                 blocks[i].duration = AV_NOPTS_VALUE;
 2661             res = matroska_parse_block(matroska, blocks[i].bin.data,
 2662                                        blocks[i].bin.size, blocks[i].bin.pos,
 2663                                        cluster.timecode, blocks[i].duration,
 2664                                        is_keyframe, pos);
 2665         }
 2666     ebml_free(matroska_cluster, &cluster);
 2667     return res;
 2668 }
 2669 
 2670 static int matroska_read_packet(AVFormatContext *s, AVPacket *pkt)
 2671 {
 2672     MatroskaDemuxContext *matroska = s->priv_data;
 2673     int ret = 0;
 2674 
 2675     while (!ret && matroska_deliver_packet(matroska, pkt)) {
 2676         int64_t pos = avio_tell(matroska->ctx->pb);
 2677         if (matroska->done)
 2678             return AVERROR_EOF;
 2679         if (matroska_parse_cluster(matroska) < 0)
 2680             ret = matroska_resync(matroska, pos);
 2681     }
 2682 
 2683     if (ret == AVERROR_INVALIDDATA && pkt->data) {
 2684         pkt->flags |= AV_PKT_FLAG_CORRUPT;
 2685         return 0;
 2686     }
 2687 
 2688     return ret;
 2689 }
 2690 
 2691 static int matroska_read_seek(AVFormatContext *s, int stream_index,
 2692                               int64_t timestamp, int flags)
 2693 {
 2694     MatroskaDemuxContext *matroska = s->priv_data;
 2695     MatroskaTrack *tracks = NULL;
 2696     AVStream *st = s->streams[stream_index];
 2697     int i, index, index_sub, index_min;
 2698 
 2699     /* Parse the CUES now since we need the index data to seek. */
 2700     if (matroska->cues_parsing_deferred) {
 2701         matroska_parse_cues(matroska);
 2702         matroska->cues_parsing_deferred = 0;
 2703     }
 2704 
 2705     if (!st->nb_index_entries)
 2706         return 0;
 2707     timestamp = FFMAX(timestamp, st->index_entries[0].timestamp);
 2708 
 2709     if ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
 2710         avio_seek(s->pb, st->index_entries[st->nb_index_entries - 1].pos,
 2711                   SEEK_SET);
 2712         matroska->current_id = 0;
 2713         while ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
 2714             matroska_clear_queue(matroska);
 2715             if (matroska_parse_cluster(matroska) < 0)
 2716                 break;
 2717         }
 2718     }
 2719 
 2720     matroska_clear_queue(matroska);
 2721     if (index < 0)
 2722         return 0;
 2723 
 2724     index_min = index;
 2725     tracks = matroska->tracks.elem;
 2726     for (i = 0; i < matroska->tracks.nb_elem; i++) {
 2727         tracks[i].audio.pkt_cnt        = 0;
 2728         tracks[i].audio.sub_packet_cnt = 0;
 2729         tracks[i].audio.buf_timecode   = AV_NOPTS_VALUE;
 2730         tracks[i].end_timecode         = 0;
 2731         if (tracks[i].type == MATROSKA_TRACK_TYPE_SUBTITLE &&
 2732             tracks[i].stream->discard != AVDISCARD_ALL) {
 2733             index_sub = av_index_search_timestamp(
 2734                 tracks[i].stream, st->index_entries[index].timestamp,
 2735                 AVSEEK_FLAG_BACKWARD);
 2736             if (index_sub >= 0 &&
 2737                 st->index_entries[index_sub].pos < st->index_entries[index_min].pos &&
 2738                 st->index_entries[index].timestamp -
 2739                 st->index_entries[index_sub].timestamp < 30000000000 / matroska->time_scale)
 2740                 index_min = index_sub;
 2741         }
 2742     }
 2743 
 2744     avio_seek(s->pb, st->index_entries[index_min].pos, SEEK_SET);
 2745     matroska->current_id       = 0;
 2746     matroska->skip_to_keyframe = !(flags & AVSEEK_FLAG_ANY);
 2747     matroska->skip_to_timecode = st->index_entries[index].timestamp;
 2748     matroska->done             = 0;
 2749     ff_update_cur_dts(s, st, st->index_entries[index].timestamp);
 2750     return 0;
 2751 }
 2752 
 2753 static int matroska_read_close(AVFormatContext *s)
 2754 {
 2755     MatroskaDemuxContext *matroska = s->priv_data;
 2756     MatroskaTrack *tracks = matroska->tracks.elem;
 2757     int n;
 2758 
 2759     matroska_clear_queue(matroska);
 2760 
 2761     for (n = 0; n < matroska->tracks.nb_elem; n++)
 2762         if (tracks[n].type == MATROSKA_TRACK_TYPE_AUDIO)
 2763             av_free(tracks[n].audio.buf);
 2764     ebml_free(matroska_cluster, &matroska->current_cluster);
 2765     ebml_free(matroska_segment, matroska);
 2766 
 2767     return 0;
 2768 }
 2769 
 2770 AVInputFormat ff_matroska_demuxer = {
 2771     .name           = "matroska,webm",
 2772     .long_name      = NULL_IF_CONFIG_SMALL("Matroska / WebM"),
 2773     .extensions     = "mkv,mk3d,mka,mks",
 2774     .priv_data_size = sizeof(MatroskaDemuxContext),
 2775     .read_probe     = matroska_probe,
 2776     .read_header    = matroska_read_header,
 2777     .read_packet    = matroska_read_packet,
 2778     .read_close     = matroska_read_close,
 2779     .read_seek      = matroska_read_seek,
 2780     .mime_type      = "audio/webm,audio/x-matroska,video/webm,video/x-matroska"
 2781 };