Subversion Repositories Kolibri OS

Rev

Blame | Last modification | View Log | RSS feed

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