FFmpeg
 All Data Structures 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/intfloat.h"
43 #include "libavutil/intreadwrite.h"
44 #include "libavutil/avstring.h"
45 #include "libavutil/lzo.h"
46 #include "libavutil/dict.h"
47 #if CONFIG_ZLIB
48 #include <zlib.h>
49 #endif
50 #if CONFIG_BZLIB
51 #include <bzlib.h>
52 #endif
53 
54 typedef enum {
65 } EbmlType;
66 
67 typedef const struct EbmlSyntax {
68  uint32_t id;
72  union {
73  uint64_t u;
74  double f;
75  const char *s;
76  const struct EbmlSyntax *n;
77  } def;
78 } EbmlSyntax;
79 
80 typedef struct {
81  int nb_elem;
82  void *elem;
83 } EbmlList;
84 
85 typedef struct {
86  int size;
88  int64_t pos;
89 } EbmlBin;
90 
91 typedef struct {
92  uint64_t version;
93  uint64_t max_size;
94  uint64_t id_length;
95  char *doctype;
96  uint64_t doctype_version;
97 } Ebml;
98 
99 typedef struct {
100  uint64_t algo;
103 
104 typedef struct {
105  uint64_t scope;
106  uint64_t type;
109 
110 typedef struct {
111  double frame_rate;
112  uint64_t display_width;
113  uint64_t display_height;
114  uint64_t pixel_width;
115  uint64_t pixel_height;
117  uint64_t stereo_mode;
118  uint64_t alpha_mode;
120 
121 typedef struct {
122  double samplerate;
124  uint64_t bitdepth;
125  uint64_t channels;
126 
127  /* real audio header (extracted from extradata) */
133  int pkt_cnt;
134  uint64_t buf_timecode;
137 
138 typedef struct {
139  uint64_t uid;
140  uint64_t type;
142 
143 typedef struct {
146 
147 typedef struct {
148  uint64_t num;
149  uint64_t uid;
150  uint64_t type;
151  char *name;
152  char *codec_id;
154  char *language;
155  double time_scale;
157  uint64_t flag_default;
158  uint64_t flag_forced;
163 
165  int64_t end_timecode;
168 } MatroskaTrack;
169 
170 typedef struct {
171  uint64_t uid;
172  char *filename;
173  char *mime;
175 
178 
179 typedef struct {
180  uint64_t start;
181  uint64_t end;
182  uint64_t uid;
183  char *title;
184 
187 
188 typedef struct {
189  uint64_t track;
190  uint64_t pos;
192 
193 typedef struct {
194  uint64_t time;
196 } MatroskaIndex;
197 
198 typedef struct {
199  char *name;
200  char *string;
201  char *lang;
202  uint64_t def;
204 } MatroskaTag;
205 
206 typedef struct {
207  char *type;
208  uint64_t typevalue;
209  uint64_t trackuid;
210  uint64_t chapteruid;
211  uint64_t attachuid;
213 
214 typedef struct {
217 } MatroskaTags;
218 
219 typedef struct {
220  uint64_t id;
221  uint64_t pos;
223 
224 typedef struct {
225  uint64_t start;
226  uint64_t length;
227 } MatroskaLevel;
228 
229 typedef struct {
230  uint64_t timecode;
233 
234 typedef struct {
236 
237  /* EBML stuff */
240  int level_up;
241  uint32_t current_id;
242 
243  uint64_t time_scale;
244  double duration;
245  char *title;
253 
254  /* byte position of the segment inside the stream */
255  int64_t segment_start;
256 
257  /* the packet queue */
261 
262  int done;
263 
264  /* What to skip before effectively reading a packet. */
267 
268  /* File has a CUES element, but we defer parsing until it is needed. */
270 
274 
275  /* File has SSA subtitles which prevent incremental cluster parsing. */
278 
279 typedef struct {
280  uint64_t duration;
281  int64_t reference;
282  uint64_t non_simple;
284  uint64_t additional_id;
286 } MatroskaBlock;
287 
289  { EBML_ID_EBMLREADVERSION, EBML_UINT, 0, offsetof(Ebml,version), {.u=EBML_VERSION} },
290  { EBML_ID_EBMLMAXSIZELENGTH, EBML_UINT, 0, offsetof(Ebml,max_size), {.u=8} },
291  { EBML_ID_EBMLMAXIDLENGTH, EBML_UINT, 0, offsetof(Ebml,id_length), {.u=4} },
292  { EBML_ID_DOCTYPE, EBML_STR, 0, offsetof(Ebml,doctype), {.s="(none)"} },
293  { EBML_ID_DOCTYPEREADVERSION, EBML_UINT, 0, offsetof(Ebml,doctype_version), {.u=1} },
296  { 0 }
297 };
298 
300  { EBML_ID_HEADER, EBML_NEST, 0, 0, {.n=ebml_header} },
301  { 0 }
302 };
303 
305  { MATROSKA_ID_TIMECODESCALE, EBML_UINT, 0, offsetof(MatroskaDemuxContext,time_scale), {.u=1000000} },
307  { MATROSKA_ID_TITLE, EBML_UTF8, 0, offsetof(MatroskaDemuxContext,title) },
310  { MATROSKA_ID_DATEUTC, EBML_BIN, 0, offsetof(MatroskaDemuxContext,date_utc) },
312  { 0 }
313 };
314 
316  { MATROSKA_ID_VIDEOFRAMERATE, EBML_FLOAT,0, offsetof(MatroskaTrackVideo,frame_rate) },
317  { MATROSKA_ID_VIDEODISPLAYWIDTH, EBML_UINT, 0, offsetof(MatroskaTrackVideo,display_width) },
318  { MATROSKA_ID_VIDEODISPLAYHEIGHT, EBML_UINT, 0, offsetof(MatroskaTrackVideo,display_height) },
319  { MATROSKA_ID_VIDEOPIXELWIDTH, EBML_UINT, 0, offsetof(MatroskaTrackVideo,pixel_width) },
320  { MATROSKA_ID_VIDEOPIXELHEIGHT, EBML_UINT, 0, offsetof(MatroskaTrackVideo,pixel_height) },
321  { MATROSKA_ID_VIDEOCOLORSPACE, EBML_BIN, 0, offsetof(MatroskaTrackVideo,color_space) },
322  { MATROSKA_ID_VIDEOSTEREOMODE, EBML_UINT, 0, offsetof(MatroskaTrackVideo,stereo_mode) },
323  { MATROSKA_ID_VIDEOALPHAMODE, EBML_UINT, 0, offsetof(MatroskaTrackVideo,alpha_mode) },
331  { 0 }
332 };
333 
335  { MATROSKA_ID_AUDIOSAMPLINGFREQ, EBML_FLOAT,0, offsetof(MatroskaTrackAudio,samplerate), {.f=8000.0} },
336  { MATROSKA_ID_AUDIOOUTSAMPLINGFREQ,EBML_FLOAT,0,offsetof(MatroskaTrackAudio,out_samplerate) },
338  { MATROSKA_ID_AUDIOCHANNELS, EBML_UINT, 0, offsetof(MatroskaTrackAudio,channels), {.u=1} },
339  { 0 }
340 };
341 
345  { 0 }
346 };
347 
349  { MATROSKA_ID_ENCODINGSCOPE, EBML_UINT, 0, offsetof(MatroskaTrackEncoding,scope), {.u=1} },
350  { MATROSKA_ID_ENCODINGTYPE, EBML_UINT, 0, offsetof(MatroskaTrackEncoding,type), {.u=0} },
351  { MATROSKA_ID_ENCODINGCOMPRESSION,EBML_NEST, 0, offsetof(MatroskaTrackEncoding,compression), {.n=matroska_track_encoding_compression} },
353  { 0 }
354 };
355 
357  { MATROSKA_ID_TRACKCONTENTENCODING, EBML_NEST, sizeof(MatroskaTrackEncoding), offsetof(MatroskaTrack,encodings), {.n=matroska_track_encoding} },
358  { 0 }
359 };
360 
364  { 0 }
365 };
366 
368  { MATROSKA_ID_TRACKPLANE, EBML_NEST, sizeof(MatroskaTrackPlane), offsetof(MatroskaTrackOperation,combine_planes), {.n=matroska_track_plane} },
369  { 0 }
370 };
371 
373  { MATROSKA_ID_TRACKCOMBINEPLANES, EBML_NEST, 0, 0, {.n=matroska_track_combine_planes} },
374  { 0 }
375 };
376 
378  { MATROSKA_ID_TRACKNUMBER, EBML_UINT, 0, offsetof(MatroskaTrack,num) },
380  { MATROSKA_ID_TRACKUID, EBML_UINT, 0, offsetof(MatroskaTrack,uid) },
381  { MATROSKA_ID_TRACKTYPE, EBML_UINT, 0, offsetof(MatroskaTrack,type) },
383  { MATROSKA_ID_CODECPRIVATE, EBML_BIN, 0, offsetof(MatroskaTrack,codec_priv) },
384  { MATROSKA_ID_TRACKLANGUAGE, EBML_UTF8, 0, offsetof(MatroskaTrack,language), {.s="eng"} },
385  { MATROSKA_ID_TRACKDEFAULTDURATION, EBML_UINT, 0, offsetof(MatroskaTrack,default_duration) },
386  { MATROSKA_ID_TRACKTIMECODESCALE, EBML_FLOAT,0, offsetof(MatroskaTrack,time_scale), {.f=1.0} },
387  { MATROSKA_ID_TRACKFLAGDEFAULT, EBML_UINT, 0, offsetof(MatroskaTrack,flag_default), {.u=1} },
388  { MATROSKA_ID_TRACKFLAGFORCED, EBML_UINT, 0, offsetof(MatroskaTrack,flag_forced), {.u=0} },
389  { MATROSKA_ID_TRACKVIDEO, EBML_NEST, 0, offsetof(MatroskaTrack,video), {.n=matroska_track_video} },
390  { MATROSKA_ID_TRACKAUDIO, EBML_NEST, 0, offsetof(MatroskaTrack,audio), {.n=matroska_track_audio} },
391  { MATROSKA_ID_TRACKOPERATION, EBML_NEST, 0, offsetof(MatroskaTrack,operation), {.n=matroska_track_operation} },
392  { MATROSKA_ID_TRACKCONTENTENCODINGS,EBML_NEST, 0, 0, {.n=matroska_track_encodings} },
393  { MATROSKA_ID_TRACKMAXBLKADDID, EBML_UINT, 0, offsetof(MatroskaTrack,max_block_additional_id) },
402  { 0 }
403 };
404 
406  { MATROSKA_ID_TRACKENTRY, EBML_NEST, sizeof(MatroskaTrack), offsetof(MatroskaDemuxContext,tracks), {.n=matroska_track} },
407  { 0 }
408 };
409 
411  { MATROSKA_ID_FILEUID, EBML_UINT, 0, offsetof(MatroskaAttachement,uid) },
412  { MATROSKA_ID_FILENAME, EBML_UTF8, 0, offsetof(MatroskaAttachement,filename) },
413  { MATROSKA_ID_FILEMIMETYPE, EBML_STR, 0, offsetof(MatroskaAttachement,mime) },
414  { MATROSKA_ID_FILEDATA, EBML_BIN, 0, offsetof(MatroskaAttachement,bin) },
416  { 0 }
417 };
418 
420  { MATROSKA_ID_ATTACHEDFILE, EBML_NEST, sizeof(MatroskaAttachement), offsetof(MatroskaDemuxContext,attachments), {.n=matroska_attachment} },
421  { 0 }
422 };
423 
425  { MATROSKA_ID_CHAPSTRING, EBML_UTF8, 0, offsetof(MatroskaChapter,title) },
427  { 0 }
428 };
429 
433  { MATROSKA_ID_CHAPTERUID, EBML_UINT, 0, offsetof(MatroskaChapter,uid) },
434  { MATROSKA_ID_CHAPTERDISPLAY, EBML_NEST, 0, 0, {.n=matroska_chapter_display} },
439  { 0 }
440 };
441 
443  { MATROSKA_ID_CHAPTERATOM, EBML_NEST, sizeof(MatroskaChapter), offsetof(MatroskaDemuxContext,chapters), {.n=matroska_chapter_entry} },
448  { 0 }
449 };
450 
452  { MATROSKA_ID_EDITIONENTRY, EBML_NEST, 0, 0, {.n=matroska_chapter} },
453  { 0 }
454 };
455 
457  { MATROSKA_ID_CUETRACK, EBML_UINT, 0, offsetof(MatroskaIndexPos,track) },
460  { 0 }
461 };
462 
464  { MATROSKA_ID_CUETIME, EBML_UINT, 0, offsetof(MatroskaIndex,time) },
465  { MATROSKA_ID_CUETRACKPOSITION, EBML_NEST, sizeof(MatroskaIndexPos), offsetof(MatroskaIndex,pos), {.n=matroska_index_pos} },
466  { 0 }
467 };
468 
470  { MATROSKA_ID_POINTENTRY, EBML_NEST, sizeof(MatroskaIndex), offsetof(MatroskaDemuxContext,index), {.n=matroska_index_entry} },
471  { 0 }
472 };
473 
475  { MATROSKA_ID_TAGNAME, EBML_UTF8, 0, offsetof(MatroskaTag,name) },
476  { MATROSKA_ID_TAGSTRING, EBML_UTF8, 0, offsetof(MatroskaTag,string) },
477  { MATROSKA_ID_TAGLANG, EBML_STR, 0, offsetof(MatroskaTag,lang), {.s="und"} },
478  { MATROSKA_ID_TAGDEFAULT, EBML_UINT, 0, offsetof(MatroskaTag,def) },
479  { MATROSKA_ID_TAGDEFAULT_BUG, EBML_UINT, 0, offsetof(MatroskaTag,def) },
480  { MATROSKA_ID_SIMPLETAG, EBML_NEST, sizeof(MatroskaTag), offsetof(MatroskaTag,sub), {.n=matroska_simpletag} },
481  { 0 }
482 };
483 
486  { MATROSKA_ID_TAGTARGETS_TYPEVALUE, EBML_UINT, 0, offsetof(MatroskaTagTarget,typevalue), {.u=50} },
487  { MATROSKA_ID_TAGTARGETS_TRACKUID, EBML_UINT, 0, offsetof(MatroskaTagTarget,trackuid) },
489  { MATROSKA_ID_TAGTARGETS_ATTACHUID, EBML_UINT, 0, offsetof(MatroskaTagTarget,attachuid) },
490  { 0 }
491 };
492 
494  { MATROSKA_ID_SIMPLETAG, EBML_NEST, sizeof(MatroskaTag), offsetof(MatroskaTags,tag), {.n=matroska_simpletag} },
495  { MATROSKA_ID_TAGTARGETS, EBML_NEST, 0, offsetof(MatroskaTags,target), {.n=matroska_tagtargets} },
496  { 0 }
497 };
498 
500  { MATROSKA_ID_TAG, EBML_NEST, sizeof(MatroskaTags), offsetof(MatroskaDemuxContext,tags), {.n=matroska_tag} },
501  { 0 }
502 };
503 
505  { MATROSKA_ID_SEEKID, EBML_UINT, 0, offsetof(MatroskaSeekhead,id) },
506  { MATROSKA_ID_SEEKPOSITION, EBML_UINT, 0, offsetof(MatroskaSeekhead,pos), {.u=-1} },
507  { 0 }
508 };
509 
511  { MATROSKA_ID_SEEKENTRY, EBML_NEST, sizeof(MatroskaSeekhead), offsetof(MatroskaDemuxContext,seekhead), {.n=matroska_seekhead_entry} },
512  { 0 }
513 };
514 
516  { MATROSKA_ID_INFO, EBML_NEST, 0, 0, {.n=matroska_info } },
517  { MATROSKA_ID_TRACKS, EBML_NEST, 0, 0, {.n=matroska_tracks } },
518  { MATROSKA_ID_ATTACHMENTS, EBML_NEST, 0, 0, {.n=matroska_attachments} },
519  { MATROSKA_ID_CHAPTERS, EBML_NEST, 0, 0, {.n=matroska_chapters } },
520  { MATROSKA_ID_CUES, EBML_NEST, 0, 0, {.n=matroska_index } },
521  { MATROSKA_ID_TAGS, EBML_NEST, 0, 0, {.n=matroska_tags } },
522  { MATROSKA_ID_SEEKHEAD, EBML_NEST, 0, 0, {.n=matroska_seekhead } },
524  { 0 }
525 };
526 
528  { MATROSKA_ID_SEGMENT, EBML_NEST, 0, 0, {.n=matroska_segment } },
529  { 0 }
530 };
531 
533  { MATROSKA_ID_BLOCKADDID, EBML_UINT, 0, offsetof(MatroskaBlock,additional_id) },
534  { MATROSKA_ID_BLOCKADDITIONAL, EBML_BIN, 0, offsetof(MatroskaBlock,additional) },
535  { 0 }
536 };
537 
539  { MATROSKA_ID_BLOCKMORE, EBML_NEST, 0, 0, {.n=matroska_blockmore} },
540  { 0 }
541 };
542 
544  { MATROSKA_ID_BLOCK, EBML_BIN, 0, offsetof(MatroskaBlock,bin) },
545  { MATROSKA_ID_BLOCKADDITIONS, EBML_NEST, 0, 0, {.n=matroska_blockadditions} },
546  { MATROSKA_ID_SIMPLEBLOCK, EBML_BIN, 0, offsetof(MatroskaBlock,bin) },
548  { MATROSKA_ID_BLOCKREFERENCE, EBML_UINT, 0, offsetof(MatroskaBlock,reference) },
549  { 1, EBML_UINT, 0, offsetof(MatroskaBlock,non_simple), {.u=1} },
550  { 0 }
551 };
552 
554  { MATROSKA_ID_CLUSTERTIMECODE,EBML_UINT,0, offsetof(MatroskaCluster,timecode) },
555  { MATROSKA_ID_BLOCKGROUP, EBML_NEST, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
556  { MATROSKA_ID_SIMPLEBLOCK, EBML_PASS, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
559  { 0 }
560 };
561 
563  { MATROSKA_ID_CLUSTER, EBML_NEST, 0, 0, {.n=matroska_cluster} },
568  { 0 }
569 };
570 
572  { MATROSKA_ID_CLUSTERTIMECODE,EBML_UINT,0, offsetof(MatroskaCluster,timecode) },
573  { MATROSKA_ID_BLOCKGROUP, EBML_NEST, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
574  { MATROSKA_ID_SIMPLEBLOCK, EBML_PASS, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
582  { 0 }
583 };
584 
586  { MATROSKA_ID_CLUSTERTIMECODE,EBML_UINT,0, offsetof(MatroskaCluster,timecode) },
591  { 0 }
592 };
593 
595  { MATROSKA_ID_CLUSTER, EBML_NEST, 0, 0, {.n=matroska_cluster_incremental} },
600  { 0 }
601 };
602 
603 static const char *const matroska_doctypes[] = { "matroska", "webm" };
604 
605 static int matroska_resync(MatroskaDemuxContext *matroska, int64_t last_pos)
606 {
607  AVIOContext *pb = matroska->ctx->pb;
608  uint32_t id;
609  matroska->current_id = 0;
610  matroska->num_levels = 0;
611 
612  // seek to next position to resync from
613  if (avio_seek(pb, last_pos + 1, SEEK_SET) < 0 || avio_tell(pb) <= last_pos)
614  goto eof;
615 
616  id = avio_rb32(pb);
617 
618  // try to find a toplevel element
619  while (!url_feof(pb)) {
620  if (id == MATROSKA_ID_INFO || id == MATROSKA_ID_TRACKS ||
621  id == MATROSKA_ID_CUES || id == MATROSKA_ID_TAGS ||
624  {
625  matroska->current_id = id;
626  return 0;
627  }
628  id = (id << 8) | avio_r8(pb);
629  }
630 eof:
631  matroska->done = 1;
632  return AVERROR_EOF;
633 }
634 
635 /*
636  * Return: Whether we reached the end of a level in the hierarchy or not.
637  */
639 {
640  AVIOContext *pb = matroska->ctx->pb;
641  int64_t pos = avio_tell(pb);
642 
643  if (matroska->num_levels > 0) {
644  MatroskaLevel *level = &matroska->levels[matroska->num_levels - 1];
645  if (pos - level->start >= level->length || matroska->current_id) {
646  matroska->num_levels--;
647  return 1;
648  }
649  }
650  return 0;
651 }
652 
653 /*
654  * Read: an "EBML number", which is defined as a variable-length
655  * array of bytes. The first byte indicates the length by giving a
656  * number of 0-bits followed by a one. The position of the first
657  * "one" bit inside the first byte indicates the length of this
658  * number.
659  * Returns: number of bytes read, < 0 on error
660  */
662  int max_size, uint64_t *number)
663 {
664  int read = 1, n = 1;
665  uint64_t total = 0;
666 
667  /* The first byte tells us the length in bytes - avio_r8() can normally
668  * return 0, but since that's not a valid first ebmlID byte, we can
669  * use it safely here to catch EOS. */
670  if (!(total = avio_r8(pb))) {
671  /* we might encounter EOS here */
672  if (!url_feof(pb)) {
673  int64_t pos = avio_tell(pb);
674  av_log(matroska->ctx, AV_LOG_ERROR,
675  "Read error at pos. %"PRIu64" (0x%"PRIx64")\n",
676  pos, pos);
677  return pb->error ? pb->error : AVERROR(EIO);
678  }
679  return AVERROR_EOF;
680  }
681 
682  /* get the length of the EBML number */
683  read = 8 - ff_log2_tab[total];
684  if (read > max_size) {
685  int64_t pos = avio_tell(pb) - 1;
686  av_log(matroska->ctx, AV_LOG_ERROR,
687  "Invalid EBML number size tag 0x%02x at pos %"PRIu64" (0x%"PRIx64")\n",
688  (uint8_t) total, pos, pos);
689  return AVERROR_INVALIDDATA;
690  }
691 
692  /* read out length */
693  total ^= 1 << ff_log2_tab[total];
694  while (n++ < read)
695  total = (total << 8) | avio_r8(pb);
696 
697  *number = total;
698 
699  return read;
700 }
701 
702 /**
703  * Read a EBML length value.
704  * This needs special handling for the "unknown length" case which has multiple
705  * encodings.
706  */
708  uint64_t *number)
709 {
710  int res = ebml_read_num(matroska, pb, 8, number);
711  if (res > 0 && *number + 1 == 1ULL << (7 * res))
712  *number = 0xffffffffffffffULL;
713  return res;
714 }
715 
716 /*
717  * Read the next element as an unsigned int.
718  * 0 is success, < 0 is failure.
719  */
720 static int ebml_read_uint(AVIOContext *pb, int size, uint64_t *num)
721 {
722  int n = 0;
723 
724  if (size > 8)
725  return AVERROR_INVALIDDATA;
726 
727  /* big-endian ordering; build up number */
728  *num = 0;
729  while (n++ < size)
730  *num = (*num << 8) | avio_r8(pb);
731 
732  return 0;
733 }
734 
735 /*
736  * Read the next element as a float.
737  * 0 is success, < 0 is failure.
738  */
739 static int ebml_read_float(AVIOContext *pb, int size, double *num)
740 {
741  if (size == 0) {
742  *num = 0;
743  } else if (size == 4) {
744  *num = av_int2float(avio_rb32(pb));
745  } else if (size == 8){
746  *num = av_int2double(avio_rb64(pb));
747  } else
748  return AVERROR_INVALIDDATA;
749 
750  return 0;
751 }
752 
753 /*
754  * Read the next element as an ASCII string.
755  * 0 is success, < 0 is failure.
756  */
757 static int ebml_read_ascii(AVIOContext *pb, int size, char **str)
758 {
759  char *res;
760 
761  /* EBML strings are usually not 0-terminated, so we allocate one
762  * byte more, read the string and NULL-terminate it ourselves. */
763  if (!(res = av_malloc(size + 1)))
764  return AVERROR(ENOMEM);
765  if (avio_read(pb, (uint8_t *) res, size) != size) {
766  av_free(res);
767  return AVERROR(EIO);
768  }
769  (res)[size] = '\0';
770  av_free(*str);
771  *str = res;
772 
773  return 0;
774 }
775 
776 /*
777  * Read the next element as binary data.
778  * 0 is success, < 0 is failure.
779  */
780 static int ebml_read_binary(AVIOContext *pb, int length, EbmlBin *bin)
781 {
782  av_fast_padded_malloc(&bin->data, &bin->size, length);
783  if (!bin->data)
784  return AVERROR(ENOMEM);
785 
786  bin->size = length;
787  bin->pos = avio_tell(pb);
788  if (avio_read(pb, bin->data, length) != length) {
789  av_freep(&bin->data);
790  bin->size = 0;
791  return AVERROR(EIO);
792  }
793 
794  return 0;
795 }
796 
797 /*
798  * Read the next element, but only the header. The contents
799  * are supposed to be sub-elements which can be read separately.
800  * 0 is success, < 0 is failure.
801  */
802 static int ebml_read_master(MatroskaDemuxContext *matroska, uint64_t length)
803 {
804  AVIOContext *pb = matroska->ctx->pb;
806 
807  if (matroska->num_levels >= EBML_MAX_DEPTH) {
808  av_log(matroska->ctx, AV_LOG_ERROR,
809  "File moves beyond max. allowed depth (%d)\n", EBML_MAX_DEPTH);
810  return AVERROR(ENOSYS);
811  }
812 
813  level = &matroska->levels[matroska->num_levels++];
814  level->start = avio_tell(pb);
815  level->length = length;
816 
817  return 0;
818 }
819 
820 /*
821  * Read signed/unsigned "EBML" numbers.
822  * Return: number of bytes processed, < 0 on error
823  */
825  uint8_t *data, uint32_t size, uint64_t *num)
826 {
827  AVIOContext pb;
828  ffio_init_context(&pb, data, size, 0, NULL, NULL, NULL, NULL);
829  return ebml_read_num(matroska, &pb, FFMIN(size, 8), num);
830 }
831 
832 /*
833  * Same as above, but signed.
834  */
836  uint8_t *data, uint32_t size, int64_t *num)
837 {
838  uint64_t unum;
839  int res;
840 
841  /* read as unsigned number first */
842  if ((res = matroska_ebmlnum_uint(matroska, data, size, &unum)) < 0)
843  return res;
844 
845  /* make signed (weird way) */
846  *num = unum - ((1LL << (7*res - 1)) - 1);
847 
848  return res;
849 }
850 
851 static int ebml_parse_elem(MatroskaDemuxContext *matroska,
852  EbmlSyntax *syntax, void *data);
853 
854 static int ebml_parse_id(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
855  uint32_t id, void *data)
856 {
857  int i;
858  for (i=0; syntax[i].id; i++)
859  if (id == syntax[i].id)
860  break;
861  if (!syntax[i].id && id == MATROSKA_ID_CLUSTER &&
862  matroska->num_levels > 0 &&
863  matroska->levels[matroska->num_levels-1].length == 0xffffffffffffff)
864  return 0; // we reached the end of an unknown size cluster
865  if (!syntax[i].id && id != EBML_ID_VOID && id != EBML_ID_CRC32) {
866  av_log(matroska->ctx, AV_LOG_INFO, "Unknown entry 0x%X\n", id);
867  if (matroska->ctx->error_recognition & AV_EF_EXPLODE)
868  return AVERROR_INVALIDDATA;
869  }
870  return ebml_parse_elem(matroska, &syntax[i], data);
871 }
872 
873 static int ebml_parse(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
874  void *data)
875 {
876  if (!matroska->current_id) {
877  uint64_t id;
878  int res = ebml_read_num(matroska, matroska->ctx->pb, 4, &id);
879  if (res < 0)
880  return res;
881  matroska->current_id = id | 1 << 7*res;
882  }
883  return ebml_parse_id(matroska, syntax, matroska->current_id, data);
884 }
885 
886 static int ebml_parse_nest(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
887  void *data)
888 {
889  int i, res = 0;
890 
891  for (i=0; syntax[i].id; i++)
892  switch (syntax[i].type) {
893  case EBML_UINT:
894  *(uint64_t *)((char *)data+syntax[i].data_offset) = syntax[i].def.u;
895  break;
896  case EBML_FLOAT:
897  *(double *)((char *)data+syntax[i].data_offset) = syntax[i].def.f;
898  break;
899  case EBML_STR:
900  case EBML_UTF8:
901  *(char **)((char *)data+syntax[i].data_offset) = av_strdup(syntax[i].def.s);
902  break;
903  }
904 
905  while (!res && !ebml_level_end(matroska))
906  res = ebml_parse(matroska, syntax, data);
907 
908  return res;
909 }
910 
912  EbmlSyntax *syntax, void *data)
913 {
914  static const uint64_t max_lengths[EBML_TYPE_COUNT] = {
915  [EBML_UINT] = 8,
916  [EBML_FLOAT] = 8,
917  // max. 16 MB for strings
918  [EBML_STR] = 0x1000000,
919  [EBML_UTF8] = 0x1000000,
920  // max. 256 MB for binary data
921  [EBML_BIN] = 0x10000000,
922  // no limits for anything else
923  };
924  AVIOContext *pb = matroska->ctx->pb;
925  uint32_t id = syntax->id;
926  uint64_t length;
927  int res;
928  void *newelem;
929 
930  data = (char *)data + syntax->data_offset;
931  if (syntax->list_elem_size) {
932  EbmlList *list = data;
933  newelem = av_realloc(list->elem, (list->nb_elem+1)*syntax->list_elem_size);
934  if (!newelem)
935  return AVERROR(ENOMEM);
936  list->elem = newelem;
937  data = (char*)list->elem + list->nb_elem*syntax->list_elem_size;
938  memset(data, 0, syntax->list_elem_size);
939  list->nb_elem++;
940  }
941 
942  if (syntax->type != EBML_PASS && syntax->type != EBML_STOP) {
943  matroska->current_id = 0;
944  if ((res = ebml_read_length(matroska, pb, &length)) < 0)
945  return res;
946  if (max_lengths[syntax->type] && length > max_lengths[syntax->type]) {
947  av_log(matroska->ctx, AV_LOG_ERROR,
948  "Invalid length 0x%"PRIx64" > 0x%"PRIx64" for syntax element %i\n",
949  length, max_lengths[syntax->type], syntax->type);
950  return AVERROR_INVALIDDATA;
951  }
952  }
953 
954  switch (syntax->type) {
955  case EBML_UINT: res = ebml_read_uint (pb, length, data); break;
956  case EBML_FLOAT: res = ebml_read_float (pb, length, data); break;
957  case EBML_STR:
958  case EBML_UTF8: res = ebml_read_ascii (pb, length, data); break;
959  case EBML_BIN: res = ebml_read_binary(pb, length, data); break;
960  case EBML_NEST: if ((res=ebml_read_master(matroska, length)) < 0)
961  return res;
962  if (id == MATROSKA_ID_SEGMENT)
963  matroska->segment_start = avio_tell(matroska->ctx->pb);
964  return ebml_parse_nest(matroska, syntax->def.n, data);
965  case EBML_PASS: return ebml_parse_id(matroska, syntax->def.n, id, data);
966  case EBML_STOP: return 1;
967  default:
968  if(ffio_limit(pb, length) != length)
969  return AVERROR(EIO);
970  return avio_skip(pb,length)<0 ? AVERROR(EIO) : 0;
971  }
972  if (res == AVERROR_INVALIDDATA)
973  av_log(matroska->ctx, AV_LOG_ERROR, "Invalid element\n");
974  else if (res == AVERROR(EIO))
975  av_log(matroska->ctx, AV_LOG_ERROR, "Read error\n");
976  return res;
977 }
978 
979 static void ebml_free(EbmlSyntax *syntax, void *data)
980 {
981  int i, j;
982  for (i=0; syntax[i].id; i++) {
983  void *data_off = (char *)data + syntax[i].data_offset;
984  switch (syntax[i].type) {
985  case EBML_STR:
986  case EBML_UTF8: av_freep(data_off); break;
987  case EBML_BIN: av_freep(&((EbmlBin *)data_off)->data); break;
988  case EBML_NEST:
989  if (syntax[i].list_elem_size) {
990  EbmlList *list = data_off;
991  char *ptr = list->elem;
992  for (j=0; j<list->nb_elem; j++, ptr+=syntax[i].list_elem_size)
993  ebml_free(syntax[i].def.n, ptr);
994  av_free(list->elem);
995  } else
996  ebml_free(syntax[i].def.n, data_off);
997  default: break;
998  }
999  }
1000 }
1001 
1002 
1003 /*
1004  * Autodetecting...
1005  */
1007 {
1008  uint64_t total = 0;
1009  int len_mask = 0x80, size = 1, n = 1, i;
1010 
1011  /* EBML header? */
1012  if (AV_RB32(p->buf) != EBML_ID_HEADER)
1013  return 0;
1014 
1015  /* length of header */
1016  total = p->buf[4];
1017  while (size <= 8 && !(total & len_mask)) {
1018  size++;
1019  len_mask >>= 1;
1020  }
1021  if (size > 8)
1022  return 0;
1023  total &= (len_mask - 1);
1024  while (n < size)
1025  total = (total << 8) | p->buf[4 + n++];
1026 
1027  /* Does the probe data contain the whole header? */
1028  if (p->buf_size < 4 + size + total)
1029  return 0;
1030 
1031  /* The header should contain a known document type. For now,
1032  * we don't parse the whole header but simply check for the
1033  * availability of that array of characters inside the header.
1034  * Not fully fool-proof, but good enough. */
1035  for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++) {
1036  int probelen = strlen(matroska_doctypes[i]);
1037  if (total < probelen)
1038  continue;
1039  for (n = 4+size; n <= 4+size+total-probelen; n++)
1040  if (!memcmp(p->buf+n, matroska_doctypes[i], probelen))
1041  return AVPROBE_SCORE_MAX;
1042  }
1043 
1044  // probably valid EBML header but no recognized doctype
1045  return AVPROBE_SCORE_MAX/2;
1046 }
1047 
1049  int num)
1050 {
1051  MatroskaTrack *tracks = matroska->tracks.elem;
1052  int i;
1053 
1054  for (i=0; i < matroska->tracks.nb_elem; i++)
1055  if (tracks[i].num == num)
1056  return &tracks[i];
1057 
1058  av_log(matroska->ctx, AV_LOG_ERROR, "Invalid track number %d\n", num);
1059  return NULL;
1060 }
1061 
1062 static int matroska_decode_buffer(uint8_t** buf, int* buf_size,
1063  MatroskaTrack *track)
1064 {
1065  MatroskaTrackEncoding *encodings = track->encodings.elem;
1066  uint8_t* data = *buf;
1067  int isize = *buf_size;
1068  uint8_t* pkt_data = NULL;
1069  uint8_t av_unused *newpktdata;
1070  int pkt_size = isize;
1071  int result = 0;
1072  int olen;
1073 
1074  if (pkt_size >= 10000000U)
1075  return AVERROR_INVALIDDATA;
1076 
1077  switch (encodings[0].compression.algo) {
1079  int header_size = encodings[0].compression.settings.size;
1080  uint8_t *header = encodings[0].compression.settings.data;
1081 
1082  if (header_size && !header) {
1083  av_log(NULL, AV_LOG_ERROR, "Compression size but no data in headerstrip\n");
1084  return -1;
1085  }
1086 
1087  if (!header_size)
1088  return 0;
1089 
1090  pkt_size = isize + header_size;
1091  pkt_data = av_malloc(pkt_size);
1092  if (!pkt_data)
1093  return AVERROR(ENOMEM);
1094 
1095  memcpy(pkt_data, header, header_size);
1096  memcpy(pkt_data + header_size, data, isize);
1097  break;
1098  }
1099 #if CONFIG_LZO
1101  do {
1102  olen = pkt_size *= 3;
1103  newpktdata = av_realloc(pkt_data, pkt_size + AV_LZO_OUTPUT_PADDING);
1104  if (!newpktdata) {
1105  result = AVERROR(ENOMEM);
1106  goto failed;
1107  }
1108  pkt_data = newpktdata;
1109  result = av_lzo1x_decode(pkt_data, &olen, data, &isize);
1110  } while (result==AV_LZO_OUTPUT_FULL && pkt_size<10000000);
1111  if (result) {
1112  result = AVERROR_INVALIDDATA;
1113  goto failed;
1114  }
1115  pkt_size -= olen;
1116  break;
1117 #endif
1118 #if CONFIG_ZLIB
1120  z_stream zstream = {0};
1121  if (inflateInit(&zstream) != Z_OK)
1122  return -1;
1123  zstream.next_in = data;
1124  zstream.avail_in = isize;
1125  do {
1126  pkt_size *= 3;
1127  newpktdata = av_realloc(pkt_data, pkt_size);
1128  if (!newpktdata) {
1129  inflateEnd(&zstream);
1130  goto failed;
1131  }
1132  pkt_data = newpktdata;
1133  zstream.avail_out = pkt_size - zstream.total_out;
1134  zstream.next_out = pkt_data + zstream.total_out;
1135  if (pkt_data) {
1136  result = inflate(&zstream, Z_NO_FLUSH);
1137  } else
1138  result = Z_MEM_ERROR;
1139  } while (result==Z_OK && pkt_size<10000000);
1140  pkt_size = zstream.total_out;
1141  inflateEnd(&zstream);
1142  if (result != Z_STREAM_END) {
1143  if (result == Z_MEM_ERROR)
1144  result = AVERROR(ENOMEM);
1145  else
1146  result = AVERROR_INVALIDDATA;
1147  goto failed;
1148  }
1149  break;
1150  }
1151 #endif
1152 #if CONFIG_BZLIB
1154  bz_stream bzstream = {0};
1155  if (BZ2_bzDecompressInit(&bzstream, 0, 0) != BZ_OK)
1156  return -1;
1157  bzstream.next_in = data;
1158  bzstream.avail_in = isize;
1159  do {
1160  pkt_size *= 3;
1161  newpktdata = av_realloc(pkt_data, pkt_size);
1162  if (!newpktdata) {
1163  BZ2_bzDecompressEnd(&bzstream);
1164  goto failed;
1165  }
1166  pkt_data = newpktdata;
1167  bzstream.avail_out = pkt_size - bzstream.total_out_lo32;
1168  bzstream.next_out = pkt_data + bzstream.total_out_lo32;
1169  if (pkt_data) {
1170  result = BZ2_bzDecompress(&bzstream);
1171  } else
1172  result = BZ_MEM_ERROR;
1173  } while (result==BZ_OK && pkt_size<10000000);
1174  pkt_size = bzstream.total_out_lo32;
1175  BZ2_bzDecompressEnd(&bzstream);
1176  if (result != BZ_STREAM_END) {
1177  if (result == BZ_MEM_ERROR)
1178  result = AVERROR(ENOMEM);
1179  else
1180  result = AVERROR_INVALIDDATA;
1181  goto failed;
1182  }
1183  break;
1184  }
1185 #endif
1186  default:
1187  return AVERROR_INVALIDDATA;
1188  }
1189 
1190  *buf = pkt_data;
1191  *buf_size = pkt_size;
1192  return 0;
1193  failed:
1194  av_free(pkt_data);
1195  return result;
1196 }
1197 
1199  AVPacket *pkt, uint64_t display_duration)
1200 {
1201  char *line, *layer, *ptr = pkt->data, *end = ptr+pkt->size;
1202  for (; *ptr!=',' && ptr<end-1; ptr++);
1203  if (*ptr == ',')
1204  ptr++;
1205  layer = ptr;
1206  for (; *ptr!=',' && ptr<end-1; ptr++);
1207  if (*ptr == ',') {
1208  int64_t end_pts = pkt->pts + display_duration;
1209  int sc = matroska->time_scale * pkt->pts / 10000000;
1210  int ec = matroska->time_scale * end_pts / 10000000;
1211  int sh, sm, ss, eh, em, es, len;
1212  sh = sc/360000; sc -= 360000*sh;
1213  sm = sc/ 6000; sc -= 6000*sm;
1214  ss = sc/ 100; sc -= 100*ss;
1215  eh = ec/360000; ec -= 360000*eh;
1216  em = ec/ 6000; ec -= 6000*em;
1217  es = ec/ 100; ec -= 100*es;
1218  *ptr++ = '\0';
1219  len = 50 + end-ptr + FF_INPUT_BUFFER_PADDING_SIZE;
1220  if (!(line = av_malloc(len)))
1221  return;
1222  snprintf(line,len,"Dialogue: %s,%d:%02d:%02d.%02d,%d:%02d:%02d.%02d,%s\r\n",
1223  layer, sh, sm, ss, sc, eh, em, es, ec, ptr);
1224  av_free(pkt->data);
1225  pkt->data = line;
1226  pkt->size = strlen(line);
1227  }
1228 }
1229 
1231 {
1232  int ret = av_grow_packet(out, in->size);
1233  if (ret < 0)
1234  return ret;
1235 
1236  memcpy(out->data + out->size - in->size, in->data, in->size);
1237 
1238  av_free_packet(in);
1239  av_free(in);
1240  return 0;
1241 }
1242 
1244  AVDictionary **metadata, char *prefix)
1245 {
1246  MatroskaTag *tags = list->elem;
1247  char key[1024];
1248  int i;
1249 
1250  for (i=0; i < list->nb_elem; i++) {
1251  const char *lang= (tags[i].lang && strcmp(tags[i].lang, "und")) ? tags[i].lang : NULL;
1252 
1253  if (!tags[i].name) {
1254  av_log(s, AV_LOG_WARNING, "Skipping invalid tag with no TagName.\n");
1255  continue;
1256  }
1257  if (prefix) snprintf(key, sizeof(key), "%s/%s", prefix, tags[i].name);
1258  else av_strlcpy(key, tags[i].name, sizeof(key));
1259  if (tags[i].def || !lang) {
1260  av_dict_set(metadata, key, tags[i].string, 0);
1261  if (tags[i].sub.nb_elem)
1262  matroska_convert_tag(s, &tags[i].sub, metadata, key);
1263  }
1264  if (lang) {
1265  av_strlcat(key, "-", sizeof(key));
1266  av_strlcat(key, lang, sizeof(key));
1267  av_dict_set(metadata, key, tags[i].string, 0);
1268  if (tags[i].sub.nb_elem)
1269  matroska_convert_tag(s, &tags[i].sub, metadata, key);
1270  }
1271  }
1273 }
1274 
1276 {
1277  MatroskaDemuxContext *matroska = s->priv_data;
1278  MatroskaTags *tags = matroska->tags.elem;
1279  int i, j;
1280 
1281  for (i=0; i < matroska->tags.nb_elem; i++) {
1282  if (tags[i].target.attachuid) {
1283  MatroskaAttachement *attachment = matroska->attachments.elem;
1284  for (j=0; j<matroska->attachments.nb_elem; j++)
1285  if (attachment[j].uid == tags[i].target.attachuid
1286  && attachment[j].stream)
1287  matroska_convert_tag(s, &tags[i].tag,
1288  &attachment[j].stream->metadata, NULL);
1289  } else if (tags[i].target.chapteruid) {
1290  MatroskaChapter *chapter = matroska->chapters.elem;
1291  for (j=0; j<matroska->chapters.nb_elem; j++)
1292  if (chapter[j].uid == tags[i].target.chapteruid
1293  && chapter[j].chapter)
1294  matroska_convert_tag(s, &tags[i].tag,
1295  &chapter[j].chapter->metadata, NULL);
1296  } else if (tags[i].target.trackuid) {
1297  MatroskaTrack *track = matroska->tracks.elem;
1298  for (j=0; j<matroska->tracks.nb_elem; j++)
1299  if (track[j].uid == tags[i].target.trackuid && track[j].stream)
1300  matroska_convert_tag(s, &tags[i].tag,
1301  &track[j].stream->metadata, NULL);
1302  } else {
1303  matroska_convert_tag(s, &tags[i].tag, &s->metadata,
1304  tags[i].target.type);
1305  }
1306  }
1307 }
1308 
1310 {
1311  EbmlList *seekhead_list = &matroska->seekhead;
1312  MatroskaSeekhead *seekhead = seekhead_list->elem;
1313  uint32_t level_up = matroska->level_up;
1314  int64_t before_pos = avio_tell(matroska->ctx->pb);
1315  uint32_t saved_id = matroska->current_id;
1317  int64_t offset;
1318  int ret = 0;
1319 
1320  if (idx >= seekhead_list->nb_elem
1321  || seekhead[idx].id == MATROSKA_ID_SEEKHEAD
1322  || seekhead[idx].id == MATROSKA_ID_CLUSTER)
1323  return 0;
1324 
1325  /* seek */
1326  offset = seekhead[idx].pos + matroska->segment_start;
1327  if (avio_seek(matroska->ctx->pb, offset, SEEK_SET) == offset) {
1328  /* We don't want to lose our seekhead level, so we add
1329  * a dummy. This is a crude hack. */
1330  if (matroska->num_levels == EBML_MAX_DEPTH) {
1331  av_log(matroska->ctx, AV_LOG_INFO,
1332  "Max EBML element depth (%d) reached, "
1333  "cannot parse further.\n", EBML_MAX_DEPTH);
1334  ret = AVERROR_INVALIDDATA;
1335  } else {
1336  level.start = 0;
1337  level.length = (uint64_t)-1;
1338  matroska->levels[matroska->num_levels] = level;
1339  matroska->num_levels++;
1340  matroska->current_id = 0;
1341 
1342  ret = ebml_parse(matroska, matroska_segment, matroska);
1343 
1344  /* remove dummy level */
1345  while (matroska->num_levels) {
1346  uint64_t length = matroska->levels[--matroska->num_levels].length;
1347  if (length == (uint64_t)-1)
1348  break;
1349  }
1350  }
1351  }
1352  /* seek back */
1353  avio_seek(matroska->ctx->pb, before_pos, SEEK_SET);
1354  matroska->level_up = level_up;
1355  matroska->current_id = saved_id;
1356 
1357  return ret;
1358 }
1359 
1361 {
1362  EbmlList *seekhead_list = &matroska->seekhead;
1363  int64_t before_pos = avio_tell(matroska->ctx->pb);
1364  int i;
1365 
1366  // we should not do any seeking in the streaming case
1367  if (!matroska->ctx->pb->seekable ||
1368  (matroska->ctx->flags & AVFMT_FLAG_IGNIDX))
1369  return;
1370 
1371  for (i = 0; i < seekhead_list->nb_elem; i++) {
1372  MatroskaSeekhead *seekhead = seekhead_list->elem;
1373  if (seekhead[i].pos <= before_pos)
1374  continue;
1375 
1376  // defer cues parsing until we actually need cue data.
1377  if (seekhead[i].id == MATROSKA_ID_CUES) {
1378  matroska->cues_parsing_deferred = 1;
1379  continue;
1380  }
1381 
1382  if (matroska_parse_seekhead_entry(matroska, i) < 0) {
1383  // mark index as broken
1384  matroska->cues_parsing_deferred = -1;
1385  break;
1386  }
1387  }
1388 }
1389 
1391  EbmlList *index_list;
1393  int index_scale = 1;
1394  int i, j;
1395 
1396  index_list = &matroska->index;
1397  index = index_list->elem;
1398  if (index_list->nb_elem
1399  && index[0].time > 1E14/matroska->time_scale) {
1400  av_log(matroska->ctx, AV_LOG_WARNING, "Working around broken index.\n");
1401  index_scale = matroska->time_scale;
1402  }
1403  for (i = 0; i < index_list->nb_elem; i++) {
1404  EbmlList *pos_list = &index[i].pos;
1405  MatroskaIndexPos *pos = pos_list->elem;
1406  for (j = 0; j < pos_list->nb_elem; j++) {
1407  MatroskaTrack *track = matroska_find_track_by_num(matroska, pos[j].track);
1408  if (track && track->stream)
1409  av_add_index_entry(track->stream,
1410  pos[j].pos + matroska->segment_start,
1411  index[i].time/index_scale, 0, 0,
1413  }
1414  }
1415 }
1416 
1418  EbmlList *seekhead_list = &matroska->seekhead;
1419  MatroskaSeekhead *seekhead = seekhead_list->elem;
1420  int i;
1421 
1422  for (i = 0; i < seekhead_list->nb_elem; i++)
1423  if (seekhead[i].id == MATROSKA_ID_CUES)
1424  break;
1425  assert(i <= seekhead_list->nb_elem);
1426 
1427  if (matroska_parse_seekhead_entry(matroska, i) < 0)
1428  matroska->cues_parsing_deferred = -1;
1429  matroska_add_index_entries(matroska);
1430 }
1431 
1433 {
1434  static const char * const aac_profiles[] = { "MAIN", "LC", "SSR" };
1435  int profile;
1436 
1437  for (profile=0; profile<FF_ARRAY_ELEMS(aac_profiles); profile++)
1438  if (strstr(codec_id, aac_profiles[profile]))
1439  break;
1440  return profile + 1;
1441 }
1442 
1443 static int matroska_aac_sri(int samplerate)
1444 {
1445  int sri;
1446 
1447  for (sri=0; sri<FF_ARRAY_ELEMS(avpriv_mpeg4audio_sample_rates); sri++)
1448  if (avpriv_mpeg4audio_sample_rates[sri] == samplerate)
1449  break;
1450  return sri;
1451 }
1452 
1453 static void matroska_metadata_creation_time(AVDictionary **metadata, int64_t date_utc)
1454 {
1455  char buffer[32];
1456  /* Convert to seconds and adjust by number of seconds between 2001-01-01 and Epoch */
1457  time_t creation_time = date_utc / 1000000000 + 978307200;
1458  struct tm *ptm = gmtime(&creation_time);
1459  if (!ptm) return;
1460  strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", ptm);
1461  av_dict_set(metadata, "creation_time", buffer, 0);
1462 }
1463 
1465 {
1466  MatroskaDemuxContext *matroska = s->priv_data;
1467  EbmlList *attachements_list = &matroska->attachments;
1468  MatroskaAttachement *attachements;
1469  EbmlList *chapters_list = &matroska->chapters;
1470  MatroskaChapter *chapters;
1471  MatroskaTrack *tracks;
1472  uint64_t max_start = 0;
1473  int64_t pos;
1474  Ebml ebml = { 0 };
1475  AVStream *st;
1476  int i, j, k, res;
1477 
1478  matroska->ctx = s;
1479 
1480  /* First read the EBML header. */
1481  if (ebml_parse(matroska, ebml_syntax, &ebml)
1482  || ebml.version > EBML_VERSION || ebml.max_size > sizeof(uint64_t)
1483  || ebml.id_length > sizeof(uint32_t) || ebml.doctype_version > 3 || !ebml.doctype) {
1484  av_log(matroska->ctx, AV_LOG_ERROR,
1485  "EBML header using unsupported features\n"
1486  "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
1487  ebml.version, ebml.doctype, ebml.doctype_version);
1488  ebml_free(ebml_syntax, &ebml);
1489  return AVERROR_PATCHWELCOME;
1490  } else if (ebml.doctype_version == 3) {
1491  av_log(matroska->ctx, AV_LOG_WARNING,
1492  "EBML header using unsupported features\n"
1493  "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
1494  ebml.version, ebml.doctype, ebml.doctype_version);
1495  }
1496  for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++)
1497  if (!strcmp(ebml.doctype, matroska_doctypes[i]))
1498  break;
1499  if (i >= FF_ARRAY_ELEMS(matroska_doctypes)) {
1500  av_log(s, AV_LOG_WARNING, "Unknown EBML doctype '%s'\n", ebml.doctype);
1501  if (matroska->ctx->error_recognition & AV_EF_EXPLODE) {
1502  ebml_free(ebml_syntax, &ebml);
1503  return AVERROR_INVALIDDATA;
1504  }
1505  }
1506  ebml_free(ebml_syntax, &ebml);
1507 
1508  /* The next thing is a segment. */
1509  pos = avio_tell(matroska->ctx->pb);
1510  res = ebml_parse(matroska, matroska_segments, matroska);
1511  // try resyncing until we find a EBML_STOP type element.
1512  while (res != 1) {
1513  res = matroska_resync(matroska, pos);
1514  if (res < 0)
1515  return res;
1516  pos = avio_tell(matroska->ctx->pb);
1517  res = ebml_parse(matroska, matroska_segment, matroska);
1518  }
1519  matroska_execute_seekhead(matroska);
1520 
1521  if (!matroska->time_scale)
1522  matroska->time_scale = 1000000;
1523  if (matroska->duration)
1524  matroska->ctx->duration = matroska->duration * matroska->time_scale
1525  * 1000 / AV_TIME_BASE;
1526  av_dict_set(&s->metadata, "title", matroska->title, 0);
1527 
1528  if (matroska->date_utc.size == 8)
1530 
1531  tracks = matroska->tracks.elem;
1532  for (i=0; i < matroska->tracks.nb_elem; i++) {
1533  MatroskaTrack *track = &tracks[i];
1535  EbmlList *encodings_list = &track->encodings;
1536  MatroskaTrackEncoding *encodings = encodings_list->elem;
1537  uint8_t *extradata = NULL;
1538  int extradata_size = 0;
1539  int extradata_offset = 0;
1540  uint32_t fourcc = 0;
1541  AVIOContext b;
1542 
1543  /* Apply some sanity checks. */
1544  if (track->type != MATROSKA_TRACK_TYPE_VIDEO &&
1545  track->type != MATROSKA_TRACK_TYPE_AUDIO &&
1546  track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
1547  av_log(matroska->ctx, AV_LOG_INFO,
1548  "Unknown or unsupported track type %"PRIu64"\n",
1549  track->type);
1550  continue;
1551  }
1552  if (track->codec_id == NULL)
1553  continue;
1554 
1555  if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1556  if (!track->default_duration && track->video.frame_rate > 0)
1557  track->default_duration = 1000000000/track->video.frame_rate;
1558  if (!track->video.display_width)
1559  track->video.display_width = track->video.pixel_width;
1560  if (!track->video.display_height)
1561  track->video.display_height = track->video.pixel_height;
1562  if (track->video.color_space.size == 4)
1563  fourcc = AV_RL32(track->video.color_space.data);
1564  } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
1565  if (!track->audio.out_samplerate)
1566  track->audio.out_samplerate = track->audio.samplerate;
1567  }
1568  if (encodings_list->nb_elem > 1) {
1569  av_log(matroska->ctx, AV_LOG_ERROR,
1570  "Multiple combined encodings not supported");
1571  } else if (encodings_list->nb_elem == 1) {
1572  if (encodings[0].type ||
1573  (
1574 #if CONFIG_ZLIB
1575  encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_ZLIB &&
1576 #endif
1577 #if CONFIG_BZLIB
1579 #endif
1580 #if CONFIG_LZO
1582 #endif
1584  encodings[0].scope = 0;
1585  av_log(matroska->ctx, AV_LOG_ERROR,
1586  "Unsupported encoding type");
1587  } else if (track->codec_priv.size && encodings[0].scope&2) {
1588  uint8_t *codec_priv = track->codec_priv.data;
1589  int ret = matroska_decode_buffer(&track->codec_priv.data,
1590  &track->codec_priv.size,
1591  track);
1592  if (ret < 0) {
1593  track->codec_priv.data = NULL;
1594  track->codec_priv.size = 0;
1595  av_log(matroska->ctx, AV_LOG_ERROR,
1596  "Failed to decode codec private data\n");
1597  }
1598 
1599  if (codec_priv != track->codec_priv.data)
1600  av_free(codec_priv);
1601  }
1602  }
1603 
1604  for(j=0; ff_mkv_codec_tags[j].id != AV_CODEC_ID_NONE; j++){
1605  if(!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
1606  strlen(ff_mkv_codec_tags[j].str))){
1607  codec_id= ff_mkv_codec_tags[j].id;
1608  break;
1609  }
1610  }
1611 
1612  st = track->stream = avformat_new_stream(s, NULL);
1613  if (st == NULL)
1614  return AVERROR(ENOMEM);
1615 
1616  if (!strcmp(track->codec_id, "V_MS/VFW/FOURCC")
1617  && track->codec_priv.size >= 40
1618  && track->codec_priv.data != NULL) {
1619  track->ms_compat = 1;
1620  fourcc = AV_RL32(track->codec_priv.data + 16);
1621  codec_id = ff_codec_get_id(ff_codec_bmp_tags, fourcc);
1622  extradata_offset = 40;
1623  } else if (!strcmp(track->codec_id, "A_MS/ACM")
1624  && track->codec_priv.size >= 14
1625  && track->codec_priv.data != NULL) {
1626  int ret;
1627  ffio_init_context(&b, track->codec_priv.data, track->codec_priv.size,
1628  0, NULL, NULL, NULL, NULL);
1629  ret = ff_get_wav_header(&b, st->codec, track->codec_priv.size);
1630  if (ret < 0)
1631  return ret;
1632  codec_id = st->codec->codec_id;
1633  extradata_offset = FFMIN(track->codec_priv.size, 18);
1634  } else if (!strcmp(track->codec_id, "V_QUICKTIME")
1635  && (track->codec_priv.size >= 86)
1636  && (track->codec_priv.data != NULL)) {
1637  fourcc = AV_RL32(track->codec_priv.data);
1638  codec_id = ff_codec_get_id(ff_codec_movvideo_tags, fourcc);
1639  } else if (codec_id == AV_CODEC_ID_ALAC && track->codec_priv.size && track->codec_priv.size < INT_MAX-12) {
1640  /* Only ALAC's magic cookie is stored in Matroska's track headers.
1641  Create the "atom size", "tag", and "tag version" fields the
1642  decoder expects manually. */
1643  extradata_size = 12 + track->codec_priv.size;
1644  extradata = av_mallocz(extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
1645  if (extradata == NULL)
1646  return AVERROR(ENOMEM);
1647  AV_WB32(extradata, extradata_size);
1648  memcpy(&extradata[4], "alac", 4);
1649  AV_WB32(&extradata[8], 0);
1650  memcpy(&extradata[12], track->codec_priv.data, track->codec_priv.size);
1651  } else if (codec_id == AV_CODEC_ID_PCM_S16BE) {
1652  switch (track->audio.bitdepth) {
1653  case 8: codec_id = AV_CODEC_ID_PCM_U8; break;
1654  case 24: codec_id = AV_CODEC_ID_PCM_S24BE; break;
1655  case 32: codec_id = AV_CODEC_ID_PCM_S32BE; break;
1656  }
1657  } else if (codec_id == AV_CODEC_ID_PCM_S16LE) {
1658  switch (track->audio.bitdepth) {
1659  case 8: codec_id = AV_CODEC_ID_PCM_U8; break;
1660  case 24: codec_id = AV_CODEC_ID_PCM_S24LE; break;
1661  case 32: codec_id = AV_CODEC_ID_PCM_S32LE; break;
1662  }
1663  } else if (codec_id==AV_CODEC_ID_PCM_F32LE && track->audio.bitdepth==64) {
1664  codec_id = AV_CODEC_ID_PCM_F64LE;
1665  } else if (codec_id == AV_CODEC_ID_AAC && !track->codec_priv.size) {
1666  int profile = matroska_aac_profile(track->codec_id);
1667  int sri = matroska_aac_sri(track->audio.samplerate);
1668  extradata = av_mallocz(5 + FF_INPUT_BUFFER_PADDING_SIZE);
1669  if (extradata == NULL)
1670  return AVERROR(ENOMEM);
1671  extradata[0] = (profile << 3) | ((sri&0x0E) >> 1);
1672  extradata[1] = ((sri&0x01) << 7) | (track->audio.channels<<3);
1673  if (strstr(track->codec_id, "SBR")) {
1674  sri = matroska_aac_sri(track->audio.out_samplerate);
1675  extradata[2] = 0x56;
1676  extradata[3] = 0xE5;
1677  extradata[4] = 0x80 | (sri<<3);
1678  extradata_size = 5;
1679  } else
1680  extradata_size = 2;
1681  } else if (codec_id == AV_CODEC_ID_TTA) {
1682  extradata_size = 30;
1683  extradata = av_mallocz(extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
1684  if (extradata == NULL)
1685  return AVERROR(ENOMEM);
1686  ffio_init_context(&b, extradata, extradata_size, 1,
1687  NULL, NULL, NULL, NULL);
1688  avio_write(&b, "TTA1", 4);
1689  avio_wl16(&b, 1);
1690  avio_wl16(&b, track->audio.channels);
1691  avio_wl16(&b, track->audio.bitdepth);
1692  avio_wl32(&b, track->audio.out_samplerate);
1693  avio_wl32(&b, matroska->ctx->duration * track->audio.out_samplerate);
1694  } else if (codec_id == AV_CODEC_ID_RV10 || codec_id == AV_CODEC_ID_RV20 ||
1695  codec_id == AV_CODEC_ID_RV30 || codec_id == AV_CODEC_ID_RV40) {
1696  extradata_offset = 26;
1697  } else if (codec_id == AV_CODEC_ID_RA_144) {
1698  track->audio.out_samplerate = 8000;
1699  track->audio.channels = 1;
1700  } else if ((codec_id == AV_CODEC_ID_RA_288 || codec_id == AV_CODEC_ID_COOK ||
1701  codec_id == AV_CODEC_ID_ATRAC3 || codec_id == AV_CODEC_ID_SIPR)
1702  && track->codec_priv.data) {
1703  int flavor;
1704 
1705  ffio_init_context(&b, track->codec_priv.data,track->codec_priv.size,
1706  0, NULL, NULL, NULL, NULL);
1707  avio_skip(&b, 22);
1708  flavor = avio_rb16(&b);
1709  track->audio.coded_framesize = avio_rb32(&b);
1710  avio_skip(&b, 12);
1711  track->audio.sub_packet_h = avio_rb16(&b);
1712  track->audio.frame_size = avio_rb16(&b);
1713  track->audio.sub_packet_size = avio_rb16(&b);
1714  track->audio.buf = av_malloc(track->audio.frame_size * track->audio.sub_packet_h);
1715  if (codec_id == AV_CODEC_ID_RA_288) {
1716  st->codec->block_align = track->audio.coded_framesize;
1717  track->codec_priv.size = 0;
1718  } else {
1719  if (codec_id == AV_CODEC_ID_SIPR && flavor < 4) {
1720  const int sipr_bit_rate[4] = { 6504, 8496, 5000, 16000 };
1721  track->audio.sub_packet_size = ff_sipr_subpk_size[flavor];
1722  st->codec->bit_rate = sipr_bit_rate[flavor];
1723  }
1724  st->codec->block_align = track->audio.sub_packet_size;
1725  extradata_offset = 78;
1726  }
1727  }
1728  track->codec_priv.size -= extradata_offset;
1729 
1730  if (codec_id == AV_CODEC_ID_NONE)
1731  av_log(matroska->ctx, AV_LOG_INFO,
1732  "Unknown/unsupported AVCodecID %s.\n", track->codec_id);
1733 
1734  if (track->time_scale < 0.01)
1735  track->time_scale = 1.0;
1736  avpriv_set_pts_info(st, 64, matroska->time_scale*track->time_scale, 1000*1000*1000); /* 64 bit pts in ns */
1737 
1738  st->codec->codec_id = codec_id;
1739  st->start_time = 0;
1740  if (strcmp(track->language, "und"))
1741  av_dict_set(&st->metadata, "language", track->language, 0);
1742  av_dict_set(&st->metadata, "title", track->name, 0);
1743 
1744  if (track->flag_default)
1746  if (track->flag_forced)
1748 
1749  if (!st->codec->extradata) {
1750  if(extradata){
1751  st->codec->extradata = extradata;
1752  st->codec->extradata_size = extradata_size;
1753  } else if(track->codec_priv.data && track->codec_priv.size > 0){
1754  st->codec->extradata = av_mallocz(track->codec_priv.size +
1756  if(st->codec->extradata == NULL)
1757  return AVERROR(ENOMEM);
1758  st->codec->extradata_size = track->codec_priv.size;
1759  memcpy(st->codec->extradata,
1760  track->codec_priv.data + extradata_offset,
1761  track->codec_priv.size);
1762  }
1763  }
1764 
1765  if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1767 
1769  st->codec->codec_tag = fourcc;
1770  st->codec->width = track->video.pixel_width;
1771  st->codec->height = track->video.pixel_height;
1773  &st->sample_aspect_ratio.den,
1774  st->codec->height * track->video.display_width,
1775  st->codec-> width * track->video.display_height,
1776  255);
1778  if (track->default_duration) {
1780  1000000000, track->default_duration, 30000);
1781 #if FF_API_R_FRAME_RATE
1782  st->r_frame_rate = st->avg_frame_rate;
1783 #endif
1784  }
1785 
1786  /* export stereo mode flag as metadata tag */
1788  av_dict_set(&st->metadata, "stereo_mode", ff_matroska_video_stereo_mode[track->video.stereo_mode], 0);
1789 
1790  /* export alpha mode flag as metadata tag */
1791  if (track->video.alpha_mode)
1792  av_dict_set(&st->metadata, "alpha_mode", "1", 0);
1793 
1794  /* if we have virtual track, mark the real tracks */
1795  for (j=0; j < track->operation.combine_planes.nb_elem; j++) {
1796  char buf[32];
1797  if (planes[j].type >= MATROSKA_VIDEO_STEREO_PLANE_COUNT)
1798  continue;
1799  snprintf(buf, sizeof(buf), "%s_%d",
1800  ff_matroska_video_stereo_plane[planes[j].type], i);
1801  for (k=0; k < matroska->tracks.nb_elem; k++)
1802  if (planes[j].uid == tracks[k].uid) {
1803  av_dict_set(&s->streams[k]->metadata,
1804  "stereo_mode", buf, 0);
1805  break;
1806  }
1807  }
1808  } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
1810  st->codec->sample_rate = track->audio.out_samplerate;
1811  st->codec->channels = track->audio.channels;
1812  st->codec->bits_per_coded_sample = track->audio.bitdepth;
1813  if (st->codec->codec_id != AV_CODEC_ID_AAC)
1815  } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
1817  if (st->codec->codec_id == AV_CODEC_ID_SSA)
1818  matroska->contains_ssa = 1;
1819  }
1820  }
1821 
1822  attachements = attachements_list->elem;
1823  for (j=0; j<attachements_list->nb_elem; j++) {
1824  if (!(attachements[j].filename && attachements[j].mime &&
1825  attachements[j].bin.data && attachements[j].bin.size > 0)) {
1826  av_log(matroska->ctx, AV_LOG_ERROR, "incomplete attachment\n");
1827  } else {
1828  AVStream *st = avformat_new_stream(s, NULL);
1829  if (st == NULL)
1830  break;
1831  av_dict_set(&st->metadata, "filename",attachements[j].filename, 0);
1832  av_dict_set(&st->metadata, "mimetype", attachements[j].mime, 0);
1835  st->codec->extradata = av_malloc(attachements[j].bin.size + FF_INPUT_BUFFER_PADDING_SIZE);
1836  if(st->codec->extradata == NULL)
1837  break;
1838  st->codec->extradata_size = attachements[j].bin.size;
1839  memcpy(st->codec->extradata, attachements[j].bin.data, attachements[j].bin.size);
1840 
1841  for (i=0; ff_mkv_mime_tags[i].id != AV_CODEC_ID_NONE; i++) {
1842  if (!strncmp(ff_mkv_mime_tags[i].str, attachements[j].mime,
1843  strlen(ff_mkv_mime_tags[i].str))) {
1844  st->codec->codec_id = ff_mkv_mime_tags[i].id;
1845  break;
1846  }
1847  }
1848  attachements[j].stream = st;
1849  }
1850  }
1851 
1852  chapters = chapters_list->elem;
1853  for (i=0; i<chapters_list->nb_elem; i++)
1854  if (chapters[i].start != AV_NOPTS_VALUE && chapters[i].uid
1855  && (max_start==0 || chapters[i].start > max_start)) {
1856  chapters[i].chapter =
1857  avpriv_new_chapter(s, chapters[i].uid, (AVRational){1, 1000000000},
1858  chapters[i].start, chapters[i].end,
1859  chapters[i].title);
1860  av_dict_set(&chapters[i].chapter->metadata,
1861  "title", chapters[i].title, 0);
1862  max_start = chapters[i].start;
1863  }
1864 
1865  matroska_add_index_entries(matroska);
1866 
1868 
1869  return 0;
1870 }
1871 
1872 /*
1873  * Put one packet in an application-supplied AVPacket struct.
1874  * Returns 0 on success or -1 on failure.
1875  */
1877  AVPacket *pkt)
1878 {
1879  if (matroska->num_packets > 0) {
1880  memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
1881  av_free(matroska->packets[0]);
1882  if (matroska->num_packets > 1) {
1883  void *newpackets;
1884  memmove(&matroska->packets[0], &matroska->packets[1],
1885  (matroska->num_packets - 1) * sizeof(AVPacket *));
1886  newpackets = av_realloc(matroska->packets,
1887  (matroska->num_packets - 1) * sizeof(AVPacket *));
1888  if (newpackets)
1889  matroska->packets = newpackets;
1890  } else {
1891  av_freep(&matroska->packets);
1892  matroska->prev_pkt = NULL;
1893  }
1894  matroska->num_packets--;
1895  return 0;
1896  }
1897 
1898  return -1;
1899 }
1900 
1901 /*
1902  * Free all packets in our internal queue.
1903  */
1905 {
1906  matroska->prev_pkt = NULL;
1907  if (matroska->packets) {
1908  int n;
1909  for (n = 0; n < matroska->num_packets; n++) {
1910  av_free_packet(matroska->packets[n]);
1911  av_free(matroska->packets[n]);
1912  }
1913  av_freep(&matroska->packets);
1914  matroska->num_packets = 0;
1915  }
1916 }
1917 
1919  int* buf_size, int type,
1920  uint32_t **lace_buf, int *laces)
1921 {
1922  int res = 0, n, size = *buf_size;
1923  uint8_t *data = *buf;
1924  uint32_t *lace_size;
1925 
1926  if (!type) {
1927  *laces = 1;
1928  *lace_buf = av_mallocz(sizeof(int));
1929  if (!*lace_buf)
1930  return AVERROR(ENOMEM);
1931 
1932  *lace_buf[0] = size;
1933  return 0;
1934  }
1935 
1936  av_assert0(size > 0);
1937  *laces = *data + 1;
1938  data += 1;
1939  size -= 1;
1940  lace_size = av_mallocz(*laces * sizeof(int));
1941  if (!lace_size)
1942  return AVERROR(ENOMEM);
1943 
1944  switch (type) {
1945  case 0x1: /* Xiph lacing */ {
1946  uint8_t temp;
1947  uint32_t total = 0;
1948  for (n = 0; res == 0 && n < *laces - 1; n++) {
1949  while (1) {
1950  if (size == 0) {
1951  res = AVERROR_EOF;
1952  break;
1953  }
1954  temp = *data;
1955  lace_size[n] += temp;
1956  data += 1;
1957  size -= 1;
1958  if (temp != 0xff)
1959  break;
1960  }
1961  total += lace_size[n];
1962  }
1963  if (size <= total) {
1964  res = AVERROR_INVALIDDATA;
1965  break;
1966  }
1967 
1968  lace_size[n] = size - total;
1969  break;
1970  }
1971 
1972  case 0x2: /* fixed-size lacing */
1973  if (size % (*laces)) {
1974  res = AVERROR_INVALIDDATA;
1975  break;
1976  }
1977  for (n = 0; n < *laces; n++)
1978  lace_size[n] = size / *laces;
1979  break;
1980 
1981  case 0x3: /* EBML lacing */ {
1982  uint64_t num;
1983  uint32_t total;
1984  n = matroska_ebmlnum_uint(matroska, data, size, &num);
1985  if (n < 0) {
1986  av_log(matroska->ctx, AV_LOG_INFO,
1987  "EBML block data error\n");
1988  res = n;
1989  break;
1990  }
1991  data += n;
1992  size -= n;
1993  total = lace_size[0] = num;
1994  for (n = 1; res == 0 && n < *laces - 1; n++) {
1995  int64_t snum;
1996  int r;
1997  r = matroska_ebmlnum_sint(matroska, data, size, &snum);
1998  if (r < 0) {
1999  av_log(matroska->ctx, AV_LOG_INFO,
2000  "EBML block data error\n");
2001  res = r;
2002  break;
2003  }
2004  data += r;
2005  size -= r;
2006  lace_size[n] = lace_size[n - 1] + snum;
2007  total += lace_size[n];
2008  }
2009  if (size <= total) {
2010  res = AVERROR_INVALIDDATA;
2011  break;
2012  }
2013  lace_size[*laces - 1] = size - total;
2014  break;
2015  }
2016  }
2017 
2018  *buf = data;
2019  *lace_buf = lace_size;
2020  *buf_size = size;
2021 
2022  return res;
2023 }
2024 
2026  MatroskaTrack *track,
2027  AVStream *st,
2028  uint8_t *data, int size,
2029  uint64_t timecode,
2030  int64_t pos)
2031 {
2032  int a = st->codec->block_align;
2033  int sps = track->audio.sub_packet_size;
2034  int cfs = track->audio.coded_framesize;
2035  int h = track->audio.sub_packet_h;
2036  int y = track->audio.sub_packet_cnt;
2037  int w = track->audio.frame_size;
2038  int x;
2039 
2040  if (!track->audio.pkt_cnt) {
2041  if (track->audio.sub_packet_cnt == 0)
2042  track->audio.buf_timecode = timecode;
2043  if (st->codec->codec_id == AV_CODEC_ID_RA_288) {
2044  if (size < cfs * h / 2) {
2045  av_log(matroska->ctx, AV_LOG_ERROR,
2046  "Corrupt int4 RM-style audio packet size\n");
2047  return AVERROR_INVALIDDATA;
2048  }
2049  for (x=0; x<h/2; x++)
2050  memcpy(track->audio.buf+x*2*w+y*cfs,
2051  data+x*cfs, cfs);
2052  } else if (st->codec->codec_id == AV_CODEC_ID_SIPR) {
2053  if (size < w) {
2054  av_log(matroska->ctx, AV_LOG_ERROR,
2055  "Corrupt sipr RM-style audio packet size\n");
2056  return AVERROR_INVALIDDATA;
2057  }
2058  memcpy(track->audio.buf + y*w, data, w);
2059  } else {
2060  if (size < sps * w / sps || h<=0) {
2061  av_log(matroska->ctx, AV_LOG_ERROR,
2062  "Corrupt generic RM-style audio packet size\n");
2063  return AVERROR_INVALIDDATA;
2064  }
2065  for (x=0; x<w/sps; x++)
2066  memcpy(track->audio.buf+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), data+x*sps, sps);
2067  }
2068 
2069  if (++track->audio.sub_packet_cnt >= h) {
2070  if (st->codec->codec_id == AV_CODEC_ID_SIPR)
2071  ff_rm_reorder_sipr_data(track->audio.buf, h, w);
2072  track->audio.sub_packet_cnt = 0;
2073  track->audio.pkt_cnt = h*w / a;
2074  }
2075  }
2076 
2077  while (track->audio.pkt_cnt) {
2078  AVPacket *pkt = NULL;
2079  if (!(pkt = av_mallocz(sizeof(AVPacket))) || av_new_packet(pkt, a) < 0){
2080  av_free(pkt);
2081  return AVERROR(ENOMEM);
2082  }
2083  memcpy(pkt->data, track->audio.buf
2084  + a * (h*w / a - track->audio.pkt_cnt--), a);
2085  pkt->pts = track->audio.buf_timecode;
2087  pkt->pos = pos;
2088  pkt->stream_index = st->index;
2089  dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
2090  }
2091 
2092  return 0;
2093 }
2095  MatroskaTrack *track,
2096  AVStream *st,
2097  uint8_t *data, int pkt_size,
2098  uint64_t timecode, uint64_t lace_duration,
2099  int64_t pos, int is_keyframe,
2100  uint8_t *additional, uint64_t additional_id, int additional_size)
2101 {
2102  MatroskaTrackEncoding *encodings = track->encodings.elem;
2103  uint8_t *pkt_data = data;
2104  int offset = 0, res;
2105  AVPacket *pkt;
2106 
2107  if (encodings && encodings->scope & 1) {
2108  res = matroska_decode_buffer(&pkt_data, &pkt_size, track);
2109  if (res < 0)
2110  return res;
2111  }
2112 
2113  if (st->codec->codec_id == AV_CODEC_ID_PRORES)
2114  offset = 8;
2115 
2116  pkt = av_mallocz(sizeof(AVPacket));
2117  /* XXX: prevent data copy... */
2118  if (av_new_packet(pkt, pkt_size + offset) < 0) {
2119  av_free(pkt);
2120  return AVERROR(ENOMEM);
2121  }
2122 
2123  if (st->codec->codec_id == AV_CODEC_ID_PRORES) {
2124  uint8_t *buf = pkt->data;
2125  bytestream_put_be32(&buf, pkt_size);
2126  bytestream_put_be32(&buf, MKBETAG('i', 'c', 'p', 'f'));
2127  }
2128 
2129  memcpy(pkt->data + offset, pkt_data, pkt_size);
2130 
2131  if (pkt_data != data)
2132  av_free(pkt_data);
2133 
2134  pkt->flags = is_keyframe;
2135  pkt->stream_index = st->index;
2136 
2137  if (additional_size > 0) {
2138  uint8_t *side_data = av_packet_new_side_data(pkt,
2140  additional_size + 8);
2141  if(side_data == NULL) {
2142  return AVERROR(ENOMEM);
2143  }
2144  AV_WB64(side_data, additional_id);
2145  memcpy(side_data + 8, additional, additional_size);
2146  }
2147 
2148  if (track->ms_compat)
2149  pkt->dts = timecode;
2150  else
2151  pkt->pts = timecode;
2152  pkt->pos = pos;
2153  if (st->codec->codec_id == AV_CODEC_ID_SUBRIP) {
2154  /*
2155  * For backward compatibility.
2156  * Historically, we have put subtitle duration
2157  * in convergence_duration, on the off chance
2158  * that the time_scale is less than 1us, which
2159  * could result in a 32bit overflow on the
2160  * normal duration field.
2161  */
2162  pkt->convergence_duration = lace_duration;
2163  }
2164 
2165  if (track->type != MATROSKA_TRACK_TYPE_SUBTITLE ||
2166  lace_duration <= INT_MAX) {
2167  /*
2168  * For non subtitle tracks, just store the duration
2169  * as normal.
2170  *
2171  * If it's a subtitle track and duration value does
2172  * not overflow a uint32, then also store it normally.
2173  */
2174  pkt->duration = lace_duration;
2175  }
2176 
2177  if (st->codec->codec_id == AV_CODEC_ID_SSA)
2178  matroska_fix_ass_packet(matroska, pkt, lace_duration);
2179 
2180  if (matroska->prev_pkt &&
2181  timecode != AV_NOPTS_VALUE &&
2182  matroska->prev_pkt->pts == timecode &&
2183  matroska->prev_pkt->stream_index == st->index &&
2184  st->codec->codec_id == AV_CODEC_ID_SSA)
2185  matroska_merge_packets(matroska->prev_pkt, pkt);
2186  else {
2187  dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
2188  matroska->prev_pkt = pkt;
2189  }
2190 
2191  return 0;
2192 }
2193 
2195  int size, int64_t pos, uint64_t cluster_time,
2196  uint64_t block_duration, int is_keyframe,
2197  uint8_t *additional, uint64_t additional_id, int additional_size,
2198  int64_t cluster_pos)
2199 {
2200  uint64_t timecode = AV_NOPTS_VALUE;
2201  MatroskaTrack *track;
2202  int res = 0;
2203  AVStream *st;
2204  int16_t block_time;
2205  uint32_t *lace_size = NULL;
2206  int n, flags, laces = 0;
2207  uint64_t num;
2208 
2209  if ((n = matroska_ebmlnum_uint(matroska, data, size, &num)) < 0) {
2210  av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
2211  return n;
2212  }
2213  data += n;
2214  size -= n;
2215 
2216  track = matroska_find_track_by_num(matroska, num);
2217  if (!track || !track->stream) {
2218  av_log(matroska->ctx, AV_LOG_INFO,
2219  "Invalid stream %"PRIu64" or size %u\n", num, size);
2220  return AVERROR_INVALIDDATA;
2221  } else if (size <= 3)
2222  return 0;
2223  st = track->stream;
2224  if (st->discard >= AVDISCARD_ALL)
2225  return res;
2226  av_assert1(block_duration != AV_NOPTS_VALUE);
2227 
2228  block_time = AV_RB16(data);
2229  data += 2;
2230  flags = *data++;
2231  size -= 3;
2232  if (is_keyframe == -1)
2233  is_keyframe = flags & 0x80 ? AV_PKT_FLAG_KEY : 0;
2234 
2235  if (cluster_time != (uint64_t)-1
2236  && (block_time >= 0 || cluster_time >= -block_time)) {
2237  timecode = cluster_time + block_time;
2238  if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE
2239  && timecode < track->end_timecode)
2240  is_keyframe = 0; /* overlapping subtitles are not key frame */
2241  if (is_keyframe)
2242  av_add_index_entry(st, cluster_pos, timecode, 0,0,AVINDEX_KEYFRAME);
2243  }
2244 
2245  if (matroska->skip_to_keyframe && track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
2246  if (timecode < matroska->skip_to_timecode)
2247  return res;
2248  if (!st->skip_to_keyframe) {
2249  av_log(matroska->ctx, AV_LOG_ERROR, "File is broken, keyframes not correctly marked!\n");
2250  matroska->skip_to_keyframe = 0;
2251  }
2252  if (is_keyframe)
2253  matroska->skip_to_keyframe = 0;
2254  }
2255 
2256  res = matroska_parse_laces(matroska, &data, &size, (flags & 0x06) >> 1,
2257  &lace_size, &laces);
2258 
2259  if (res)
2260  goto end;
2261 
2262  if (!block_duration)
2263  block_duration = track->default_duration * laces / matroska->time_scale;
2264 
2265  if (cluster_time != (uint64_t)-1 && (block_time >= 0 || cluster_time >= -block_time))
2266  track->end_timecode =
2267  FFMAX(track->end_timecode, timecode + block_duration);
2268 
2269  for (n = 0; n < laces; n++) {
2270  int64_t lace_duration = block_duration*(n+1) / laces - block_duration*n / laces;
2271 
2272  if (lace_size[n] > size) {
2273  av_log(matroska->ctx, AV_LOG_ERROR, "Invalid packet size\n");
2274  break;
2275  }
2276 
2277  if ((st->codec->codec_id == AV_CODEC_ID_RA_288 ||
2278  st->codec->codec_id == AV_CODEC_ID_COOK ||
2279  st->codec->codec_id == AV_CODEC_ID_SIPR ||
2280  st->codec->codec_id == AV_CODEC_ID_ATRAC3) &&
2281  st->codec->block_align && track->audio.sub_packet_size) {
2282 
2283  res = matroska_parse_rm_audio(matroska, track, st, data, size,
2284  timecode, pos);
2285  if (res)
2286  goto end;
2287 
2288  } else {
2289  res = matroska_parse_frame(matroska, track, st, data, lace_size[n],
2290  timecode, lace_duration,
2291  pos, !n? is_keyframe : 0,
2292  additional, additional_id, additional_size);
2293  if (res)
2294  goto end;
2295  }
2296 
2297  if (timecode != AV_NOPTS_VALUE)
2298  timecode = lace_duration ? timecode + lace_duration : AV_NOPTS_VALUE;
2299  data += lace_size[n];
2300  size -= lace_size[n];
2301  }
2302 
2303 end:
2304  av_free(lace_size);
2305  return res;
2306 }
2307 
2309 {
2310  EbmlList *blocks_list;
2311  MatroskaBlock *blocks;
2312  int i, res;
2313  res = ebml_parse(matroska,
2314  matroska_cluster_incremental_parsing,
2315  &matroska->current_cluster);
2316  if (res == 1) {
2317  /* New Cluster */
2318  if (matroska->current_cluster_pos)
2319  ebml_level_end(matroska);
2320  ebml_free(matroska_cluster, &matroska->current_cluster);
2321  memset(&matroska->current_cluster, 0, sizeof(MatroskaCluster));
2322  matroska->current_cluster_num_blocks = 0;
2323  matroska->current_cluster_pos = avio_tell(matroska->ctx->pb);
2324  matroska->prev_pkt = NULL;
2325  /* sizeof the ID which was already read */
2326  if (matroska->current_id)
2327  matroska->current_cluster_pos -= 4;
2328  res = ebml_parse(matroska,
2329  matroska_clusters_incremental,
2330  &matroska->current_cluster);
2331  /* Try parsing the block again. */
2332  if (res == 1)
2333  res = ebml_parse(matroska,
2334  matroska_cluster_incremental_parsing,
2335  &matroska->current_cluster);
2336  }
2337 
2338  if (!res &&
2339  matroska->current_cluster_num_blocks <
2340  matroska->current_cluster.blocks.nb_elem) {
2341  blocks_list = &matroska->current_cluster.blocks;
2342  blocks = blocks_list->elem;
2343 
2344  matroska->current_cluster_num_blocks = blocks_list->nb_elem;
2345  i = blocks_list->nb_elem - 1;
2346  if (blocks[i].bin.size > 0 && blocks[i].bin.data) {
2347  int is_keyframe = blocks[i].non_simple ? !blocks[i].reference : -1;
2348  uint8_t* additional = blocks[i].additional.size > 0 ?
2349  blocks[i].additional.data : NULL;
2350  if (!blocks[i].non_simple)
2351  blocks[i].duration = 0;
2352  res = matroska_parse_block(matroska,
2353  blocks[i].bin.data, blocks[i].bin.size,
2354  blocks[i].bin.pos,
2355  matroska->current_cluster.timecode,
2356  blocks[i].duration, is_keyframe,
2357  additional, blocks[i].additional_id,
2358  blocks[i].additional.size,
2359  matroska->current_cluster_pos);
2360  }
2361  }
2362 
2363  return res;
2364 }
2365 
2367 {
2368  MatroskaCluster cluster = { 0 };
2369  EbmlList *blocks_list;
2370  MatroskaBlock *blocks;
2371  int i, res;
2372  int64_t pos;
2373  if (!matroska->contains_ssa)
2374  return matroska_parse_cluster_incremental(matroska);
2375  pos = avio_tell(matroska->ctx->pb);
2376  matroska->prev_pkt = NULL;
2377  if (matroska->current_id)
2378  pos -= 4; /* sizeof the ID which was already read */
2379  res = ebml_parse(matroska, matroska_clusters, &cluster);
2380  blocks_list = &cluster.blocks;
2381  blocks = blocks_list->elem;
2382  for (i=0; i<blocks_list->nb_elem; i++)
2383  if (blocks[i].bin.size > 0 && blocks[i].bin.data) {
2384  int is_keyframe = blocks[i].non_simple ? !blocks[i].reference : -1;
2385  res=matroska_parse_block(matroska,
2386  blocks[i].bin.data, blocks[i].bin.size,
2387  blocks[i].bin.pos, cluster.timecode,
2388  blocks[i].duration, is_keyframe, NULL, 0, 0,
2389  pos);
2390  }
2391  ebml_free(matroska_cluster, &cluster);
2392  return res;
2393 }
2394 
2396 {
2397  MatroskaDemuxContext *matroska = s->priv_data;
2398 
2399  while (matroska_deliver_packet(matroska, pkt)) {
2400  int64_t pos = avio_tell(matroska->ctx->pb);
2401  if (matroska->done)
2402  return AVERROR_EOF;
2403  if (matroska_parse_cluster(matroska) < 0)
2404  matroska_resync(matroska, pos);
2405  }
2406 
2407  return 0;
2408 }
2409 
2410 static int matroska_read_seek(AVFormatContext *s, int stream_index,
2411  int64_t timestamp, int flags)
2412 {
2413  MatroskaDemuxContext *matroska = s->priv_data;
2414  MatroskaTrack *tracks = matroska->tracks.elem;
2415  AVStream *st = s->streams[stream_index];
2416  int i, index, index_sub, index_min;
2417 
2418  /* Parse the CUES now since we need the index data to seek. */
2419  if (matroska->cues_parsing_deferred > 0) {
2420  matroska->cues_parsing_deferred = 0;
2421  matroska_parse_cues(matroska);
2422  }
2423 
2424  if (!st->nb_index_entries)
2425  goto err;
2426  timestamp = FFMAX(timestamp, st->index_entries[0].timestamp);
2427 
2428  if ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
2429  avio_seek(s->pb, st->index_entries[st->nb_index_entries-1].pos, SEEK_SET);
2430  matroska->current_id = 0;
2431  while ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
2432  matroska_clear_queue(matroska);
2433  if (matroska_parse_cluster(matroska) < 0)
2434  break;
2435  }
2436  }
2437 
2438  matroska_clear_queue(matroska);
2439  if (index < 0 || (matroska->cues_parsing_deferred < 0 && index == st->nb_index_entries - 1))
2440  goto err;
2441 
2442  index_min = index;
2443  for (i=0; i < matroska->tracks.nb_elem; i++) {
2444  tracks[i].audio.pkt_cnt = 0;
2445  tracks[i].audio.sub_packet_cnt = 0;
2446  tracks[i].audio.buf_timecode = AV_NOPTS_VALUE;
2447  tracks[i].end_timecode = 0;
2448  if (tracks[i].type == MATROSKA_TRACK_TYPE_SUBTITLE
2449  && tracks[i].stream->discard != AVDISCARD_ALL) {
2450  index_sub = av_index_search_timestamp(tracks[i].stream, st->index_entries[index].timestamp, AVSEEK_FLAG_BACKWARD);
2451  if (index_sub >= 0
2452  && st->index_entries[index_sub].pos < st->index_entries[index_min].pos
2453  && st->index_entries[index].timestamp - st->index_entries[index_sub].timestamp < 30000000000/matroska->time_scale)
2454  index_min = index_sub;
2455  }
2456  }
2457 
2458  avio_seek(s->pb, st->index_entries[index_min].pos, SEEK_SET);
2459  matroska->current_id = 0;
2460  if (flags & AVSEEK_FLAG_ANY) {
2461  st->skip_to_keyframe = 0;
2462  matroska->skip_to_timecode = timestamp;
2463  } else {
2464  st->skip_to_keyframe = 1;
2465  matroska->skip_to_timecode = st->index_entries[index].timestamp;
2466  }
2467  matroska->skip_to_keyframe = 1;
2468  matroska->done = 0;
2469  matroska->num_levels = 0;
2470  ff_update_cur_dts(s, st, st->index_entries[index].timestamp);
2471  return 0;
2472 err:
2473  // slightly hackish but allows proper fallback to
2474  // the generic seeking code.
2475  matroska_clear_queue(matroska);
2476  matroska->current_id = 0;
2477  st->skip_to_keyframe =
2478  matroska->skip_to_keyframe = 0;
2479  matroska->done = 0;
2480  matroska->num_levels = 0;
2481  return -1;
2482 }
2483 
2485 {
2486  MatroskaDemuxContext *matroska = s->priv_data;
2487  MatroskaTrack *tracks = matroska->tracks.elem;
2488  int n;
2489 
2490  matroska_clear_queue(matroska);
2491 
2492  for (n=0; n < matroska->tracks.nb_elem; n++)
2493  if (tracks[n].type == MATROSKA_TRACK_TYPE_AUDIO)
2494  av_free(tracks[n].audio.buf);
2495  ebml_free(matroska_cluster, &matroska->current_cluster);
2496  ebml_free(matroska_segment, matroska);
2497 
2498  return 0;
2499 }
2500 
2502  .name = "matroska,webm",
2503  .long_name = NULL_IF_CONFIG_SMALL("Matroska / WebM"),
2504  .priv_data_size = sizeof(MatroskaDemuxContext),
2510 };