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