matroskadec.c
Go to the documentation of this file.
1 /*
2  * Matroska file demuxer
3  * Copyright (c) 2003-2008 The Libav Project
4  *
5  * This file is part of Libav.
6  *
7  * Libav is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * Libav is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with Libav; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21 
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;
116  uint64_t fourcc;
118 
119 typedef struct {
120  double samplerate;
122  uint64_t bitdepth;
123  uint64_t channels;
124 
125  /* real audio header (extracted from extradata) */
131  int pkt_cnt;
132  uint64_t buf_timecode;
135 
136 typedef struct {
137  uint64_t num;
138  uint64_t uid;
139  uint64_t type;
140  char *name;
141  char *codec_id;
143  char *language;
144  double time_scale;
146  uint64_t flag_default;
147  uint64_t flag_forced;
151 
153  int64_t end_timecode;
155 } MatroskaTrack;
156 
157 typedef struct {
158  uint64_t uid;
159  char *filename;
160  char *mime;
162 
165 
166 typedef struct {
167  uint64_t start;
168  uint64_t end;
169  uint64_t uid;
170  char *title;
171 
174 
175 typedef struct {
176  uint64_t track;
177  uint64_t pos;
179 
180 typedef struct {
181  uint64_t time;
183 } MatroskaIndex;
184 
185 typedef struct {
186  char *name;
187  char *string;
188  char *lang;
189  uint64_t def;
191 } MatroskaTag;
192 
193 typedef struct {
194  char *type;
195  uint64_t typevalue;
196  uint64_t trackuid;
197  uint64_t chapteruid;
198  uint64_t attachuid;
200 
201 typedef struct {
204 } MatroskaTags;
205 
206 typedef struct {
207  uint64_t id;
208  uint64_t pos;
210 
211 typedef struct {
212  uint64_t start;
213  uint64_t length;
214 } MatroskaLevel;
215 
216 typedef struct {
217  uint64_t timecode;
220 
221 typedef struct {
223 
224  /* EBML stuff */
227  int level_up;
228  uint32_t current_id;
229 
230  uint64_t time_scale;
231  double duration;
232  char *title;
239 
240  /* byte position of the segment inside the stream */
241  int64_t segment_start;
242 
243  /* the packet queue */
247 
248  int done;
249 
250  /* What to skip before effectively reading a packet. */
253 
254  /* File has a CUES element, but we defer parsing until it is needed. */
256 
260 
261  /* File has SSA subtitles which prevent incremental cluster parsing. */
264 
265 typedef struct {
266  uint64_t duration;
267  int64_t reference;
268  uint64_t non_simple;
270 } MatroskaBlock;
271 
273  { EBML_ID_EBMLREADVERSION, EBML_UINT, 0, offsetof(Ebml,version), {.u=EBML_VERSION} },
274  { EBML_ID_EBMLMAXSIZELENGTH, EBML_UINT, 0, offsetof(Ebml,max_size), {.u=8} },
275  { EBML_ID_EBMLMAXIDLENGTH, EBML_UINT, 0, offsetof(Ebml,id_length), {.u=4} },
276  { EBML_ID_DOCTYPE, EBML_STR, 0, offsetof(Ebml,doctype), {.s="(none)"} },
277  { EBML_ID_DOCTYPEREADVERSION, EBML_UINT, 0, offsetof(Ebml,doctype_version), {.u=1} },
280  { 0 }
281 };
282 
284  { EBML_ID_HEADER, EBML_NEST, 0, 0, {.n=ebml_header} },
285  { 0 }
286 };
287 
289  { MATROSKA_ID_TIMECODESCALE, EBML_UINT, 0, offsetof(MatroskaDemuxContext,time_scale), {.u=1000000} },
291  { MATROSKA_ID_TITLE, EBML_UTF8, 0, offsetof(MatroskaDemuxContext,title) },
296  { 0 }
297 };
298 
300  { MATROSKA_ID_VIDEOFRAMERATE, EBML_FLOAT,0, offsetof(MatroskaTrackVideo,frame_rate) },
301  { MATROSKA_ID_VIDEODISPLAYWIDTH, EBML_UINT, 0, offsetof(MatroskaTrackVideo,display_width) },
302  { MATROSKA_ID_VIDEODISPLAYHEIGHT, EBML_UINT, 0, offsetof(MatroskaTrackVideo,display_height) },
303  { MATROSKA_ID_VIDEOPIXELWIDTH, EBML_UINT, 0, offsetof(MatroskaTrackVideo,pixel_width) },
304  { MATROSKA_ID_VIDEOPIXELHEIGHT, EBML_UINT, 0, offsetof(MatroskaTrackVideo,pixel_height) },
305  { MATROSKA_ID_VIDEOCOLORSPACE, EBML_UINT, 0, offsetof(MatroskaTrackVideo,fourcc) },
314  { 0 }
315 };
316 
318  { MATROSKA_ID_AUDIOSAMPLINGFREQ, EBML_FLOAT,0, offsetof(MatroskaTrackAudio,samplerate), {.f=8000.0} },
319  { MATROSKA_ID_AUDIOOUTSAMPLINGFREQ,EBML_FLOAT,0,offsetof(MatroskaTrackAudio,out_samplerate) },
321  { MATROSKA_ID_AUDIOCHANNELS, EBML_UINT, 0, offsetof(MatroskaTrackAudio,channels), {.u=1} },
322  { 0 }
323 };
324 
328  { 0 }
329 };
330 
332  { MATROSKA_ID_ENCODINGSCOPE, EBML_UINT, 0, offsetof(MatroskaTrackEncoding,scope), {.u=1} },
333  { MATROSKA_ID_ENCODINGTYPE, EBML_UINT, 0, offsetof(MatroskaTrackEncoding,type), {.u=0} },
334  { MATROSKA_ID_ENCODINGCOMPRESSION,EBML_NEST, 0, offsetof(MatroskaTrackEncoding,compression), {.n=matroska_track_encoding_compression} },
336  { 0 }
337 };
338 
340  { MATROSKA_ID_TRACKCONTENTENCODING, EBML_NEST, sizeof(MatroskaTrackEncoding), offsetof(MatroskaTrack,encodings), {.n=matroska_track_encoding} },
341  { 0 }
342 };
343 
345  { MATROSKA_ID_TRACKNUMBER, EBML_UINT, 0, offsetof(MatroskaTrack,num) },
347  { MATROSKA_ID_TRACKUID, EBML_UINT, 0, offsetof(MatroskaTrack,uid) },
348  { MATROSKA_ID_TRACKTYPE, EBML_UINT, 0, offsetof(MatroskaTrack,type) },
350  { MATROSKA_ID_CODECPRIVATE, EBML_BIN, 0, offsetof(MatroskaTrack,codec_priv) },
351  { MATROSKA_ID_TRACKLANGUAGE, EBML_UTF8, 0, offsetof(MatroskaTrack,language), {.s="eng"} },
352  { MATROSKA_ID_TRACKDEFAULTDURATION, EBML_UINT, 0, offsetof(MatroskaTrack,default_duration) },
353  { MATROSKA_ID_TRACKTIMECODESCALE, EBML_FLOAT,0, offsetof(MatroskaTrack,time_scale), {.f=1.0} },
354  { MATROSKA_ID_TRACKFLAGDEFAULT, EBML_UINT, 0, offsetof(MatroskaTrack,flag_default), {.u=1} },
355  { MATROSKA_ID_TRACKFLAGFORCED, EBML_UINT, 0, offsetof(MatroskaTrack,flag_forced), {.u=0} },
356  { MATROSKA_ID_TRACKVIDEO, EBML_NEST, 0, offsetof(MatroskaTrack,video), {.n=matroska_track_video} },
357  { MATROSKA_ID_TRACKAUDIO, EBML_NEST, 0, offsetof(MatroskaTrack,audio), {.n=matroska_track_audio} },
358  { MATROSKA_ID_TRACKCONTENTENCODINGS,EBML_NEST, 0, 0, {.n=matroska_track_encodings} },
368  { 0 }
369 };
370 
372  { MATROSKA_ID_TRACKENTRY, EBML_NEST, sizeof(MatroskaTrack), offsetof(MatroskaDemuxContext,tracks), {.n=matroska_track} },
373  { 0 }
374 };
375 
377  { MATROSKA_ID_FILEUID, EBML_UINT, 0, offsetof(MatroskaAttachement,uid) },
378  { MATROSKA_ID_FILENAME, EBML_UTF8, 0, offsetof(MatroskaAttachement,filename) },
379  { MATROSKA_ID_FILEMIMETYPE, EBML_STR, 0, offsetof(MatroskaAttachement,mime) },
380  { MATROSKA_ID_FILEDATA, EBML_BIN, 0, offsetof(MatroskaAttachement,bin) },
382  { 0 }
383 };
384 
386  { MATROSKA_ID_ATTACHEDFILE, EBML_NEST, sizeof(MatroskaAttachement), offsetof(MatroskaDemuxContext,attachments), {.n=matroska_attachment} },
387  { 0 }
388 };
389 
391  { MATROSKA_ID_CHAPSTRING, EBML_UTF8, 0, offsetof(MatroskaChapter,title) },
393  { 0 }
394 };
395 
399  { MATROSKA_ID_CHAPTERUID, EBML_UINT, 0, offsetof(MatroskaChapter,uid) },
400  { MATROSKA_ID_CHAPTERDISPLAY, EBML_NEST, 0, 0, {.n=matroska_chapter_display} },
405  { 0 }
406 };
407 
409  { MATROSKA_ID_CHAPTERATOM, EBML_NEST, sizeof(MatroskaChapter), offsetof(MatroskaDemuxContext,chapters), {.n=matroska_chapter_entry} },
414  { 0 }
415 };
416 
418  { MATROSKA_ID_EDITIONENTRY, EBML_NEST, 0, 0, {.n=matroska_chapter} },
419  { 0 }
420 };
421 
423  { MATROSKA_ID_CUETRACK, EBML_UINT, 0, offsetof(MatroskaIndexPos,track) },
426  { 0 }
427 };
428 
430  { MATROSKA_ID_CUETIME, EBML_UINT, 0, offsetof(MatroskaIndex,time) },
431  { MATROSKA_ID_CUETRACKPOSITION, EBML_NEST, sizeof(MatroskaIndexPos), offsetof(MatroskaIndex,pos), {.n=matroska_index_pos} },
432  { 0 }
433 };
434 
436  { MATROSKA_ID_POINTENTRY, EBML_NEST, sizeof(MatroskaIndex), offsetof(MatroskaDemuxContext,index), {.n=matroska_index_entry} },
437  { 0 }
438 };
439 
441  { MATROSKA_ID_TAGNAME, EBML_UTF8, 0, offsetof(MatroskaTag,name) },
442  { MATROSKA_ID_TAGSTRING, EBML_UTF8, 0, offsetof(MatroskaTag,string) },
443  { MATROSKA_ID_TAGLANG, EBML_STR, 0, offsetof(MatroskaTag,lang), {.s="und"} },
444  { MATROSKA_ID_TAGDEFAULT, EBML_UINT, 0, offsetof(MatroskaTag,def) },
445  { MATROSKA_ID_TAGDEFAULT_BUG, EBML_UINT, 0, offsetof(MatroskaTag,def) },
446  { MATROSKA_ID_SIMPLETAG, EBML_NEST, sizeof(MatroskaTag), offsetof(MatroskaTag,sub), {.n=matroska_simpletag} },
447  { 0 }
448 };
449 
452  { MATROSKA_ID_TAGTARGETS_TYPEVALUE, EBML_UINT, 0, offsetof(MatroskaTagTarget,typevalue), {.u=50} },
453  { MATROSKA_ID_TAGTARGETS_TRACKUID, EBML_UINT, 0, offsetof(MatroskaTagTarget,trackuid) },
455  { MATROSKA_ID_TAGTARGETS_ATTACHUID, EBML_UINT, 0, offsetof(MatroskaTagTarget,attachuid) },
456  { 0 }
457 };
458 
460  { MATROSKA_ID_SIMPLETAG, EBML_NEST, sizeof(MatroskaTag), offsetof(MatroskaTags,tag), {.n=matroska_simpletag} },
461  { MATROSKA_ID_TAGTARGETS, EBML_NEST, 0, offsetof(MatroskaTags,target), {.n=matroska_tagtargets} },
462  { 0 }
463 };
464 
466  { MATROSKA_ID_TAG, EBML_NEST, sizeof(MatroskaTags), offsetof(MatroskaDemuxContext,tags), {.n=matroska_tag} },
467  { 0 }
468 };
469 
471  { MATROSKA_ID_SEEKID, EBML_UINT, 0, offsetof(MatroskaSeekhead,id) },
472  { MATROSKA_ID_SEEKPOSITION, EBML_UINT, 0, offsetof(MatroskaSeekhead,pos), {.u=-1} },
473  { 0 }
474 };
475 
477  { MATROSKA_ID_SEEKENTRY, EBML_NEST, sizeof(MatroskaSeekhead), offsetof(MatroskaDemuxContext,seekhead), {.n=matroska_seekhead_entry} },
478  { 0 }
479 };
480 
482  { MATROSKA_ID_INFO, EBML_NEST, 0, 0, {.n=matroska_info } },
483  { MATROSKA_ID_TRACKS, EBML_NEST, 0, 0, {.n=matroska_tracks } },
484  { MATROSKA_ID_ATTACHMENTS, EBML_NEST, 0, 0, {.n=matroska_attachments} },
485  { MATROSKA_ID_CHAPTERS, EBML_NEST, 0, 0, {.n=matroska_chapters } },
486  { MATROSKA_ID_CUES, EBML_NEST, 0, 0, {.n=matroska_index } },
487  { MATROSKA_ID_TAGS, EBML_NEST, 0, 0, {.n=matroska_tags } },
488  { MATROSKA_ID_SEEKHEAD, EBML_NEST, 0, 0, {.n=matroska_seekhead } },
490  { 0 }
491 };
492 
494  { MATROSKA_ID_SEGMENT, EBML_NEST, 0, 0, {.n=matroska_segment } },
495  { 0 }
496 };
497 
499  { MATROSKA_ID_BLOCK, EBML_BIN, 0, offsetof(MatroskaBlock,bin) },
500  { MATROSKA_ID_SIMPLEBLOCK, EBML_BIN, 0, offsetof(MatroskaBlock,bin) },
502  { MATROSKA_ID_BLOCKREFERENCE, EBML_UINT, 0, offsetof(MatroskaBlock,reference) },
503  { 1, EBML_UINT, 0, offsetof(MatroskaBlock,non_simple), {.u=1} },
504  { 0 }
505 };
506 
508  { MATROSKA_ID_CLUSTERTIMECODE,EBML_UINT,0, offsetof(MatroskaCluster,timecode) },
509  { MATROSKA_ID_BLOCKGROUP, EBML_NEST, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
510  { MATROSKA_ID_SIMPLEBLOCK, EBML_PASS, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
513  { 0 }
514 };
515 
517  { MATROSKA_ID_CLUSTER, EBML_NEST, 0, 0, {.n=matroska_cluster} },
522  { 0 }
523 };
524 
526  { MATROSKA_ID_CLUSTERTIMECODE,EBML_UINT,0, offsetof(MatroskaCluster,timecode) },
527  { MATROSKA_ID_BLOCKGROUP, EBML_NEST, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
528  { MATROSKA_ID_SIMPLEBLOCK, EBML_PASS, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
536  { 0 }
537 };
538 
540  { MATROSKA_ID_CLUSTERTIMECODE,EBML_UINT,0, offsetof(MatroskaCluster,timecode) },
545  { 0 }
546 };
547 
549  { MATROSKA_ID_CLUSTER, EBML_NEST, 0, 0, {.n=matroska_cluster_incremental} },
554  { 0 }
555 };
556 
557 static const char *const matroska_doctypes[] = { "matroska", "webm" };
558 
559 /*
560  * Return: Whether we reached the end of a level in the hierarchy or not.
561  */
563 {
564  AVIOContext *pb = matroska->ctx->pb;
565  int64_t pos = avio_tell(pb);
566 
567  if (matroska->num_levels > 0) {
568  MatroskaLevel *level = &matroska->levels[matroska->num_levels - 1];
569  if (pos - level->start >= level->length || matroska->current_id) {
570  matroska->num_levels--;
571  return 1;
572  }
573  }
574  return 0;
575 }
576 
577 /*
578  * Read: an "EBML number", which is defined as a variable-length
579  * array of bytes. The first byte indicates the length by giving a
580  * number of 0-bits followed by a one. The position of the first
581  * "one" bit inside the first byte indicates the length of this
582  * number.
583  * Returns: number of bytes read, < 0 on error
584  */
586  int max_size, uint64_t *number)
587 {
588  int read = 1, n = 1;
589  uint64_t total = 0;
590 
591  /* The first byte tells us the length in bytes - avio_r8() can normally
592  * return 0, but since that's not a valid first ebmlID byte, we can
593  * use it safely here to catch EOS. */
594  if (!(total = avio_r8(pb))) {
595  /* we might encounter EOS here */
596  if (!pb->eof_reached) {
597  int64_t pos = avio_tell(pb);
598  av_log(matroska->ctx, AV_LOG_ERROR,
599  "Read error at pos. %"PRIu64" (0x%"PRIx64")\n",
600  pos, pos);
601  return pb->error ? pb->error : AVERROR(EIO);
602  }
603  return AVERROR_EOF;
604  }
605 
606  /* get the length of the EBML number */
607  read = 8 - ff_log2_tab[total];
608  if (read > max_size) {
609  int64_t pos = avio_tell(pb) - 1;
610  av_log(matroska->ctx, AV_LOG_ERROR,
611  "Invalid EBML number size tag 0x%02x at pos %"PRIu64" (0x%"PRIx64")\n",
612  (uint8_t) total, pos, pos);
613  return AVERROR_INVALIDDATA;
614  }
615 
616  /* read out length */
617  total ^= 1 << ff_log2_tab[total];
618  while (n++ < read)
619  total = (total << 8) | avio_r8(pb);
620 
621  *number = total;
622 
623  return read;
624 }
625 
632  uint64_t *number)
633 {
634  int res = ebml_read_num(matroska, pb, 8, number);
635  if (res > 0 && *number + 1 == 1ULL << (7 * res))
636  *number = 0xffffffffffffffULL;
637  return res;
638 }
639 
640 /*
641  * Read the next element as an unsigned int.
642  * 0 is success, < 0 is failure.
643  */
644 static int ebml_read_uint(AVIOContext *pb, int size, uint64_t *num)
645 {
646  int n = 0;
647 
648  if (size > 8)
649  return AVERROR_INVALIDDATA;
650 
651  /* big-endian ordering; build up number */
652  *num = 0;
653  while (n++ < size)
654  *num = (*num << 8) | avio_r8(pb);
655 
656  return 0;
657 }
658 
659 /*
660  * Read the next element as a float.
661  * 0 is success, < 0 is failure.
662  */
663 static int ebml_read_float(AVIOContext *pb, int size, double *num)
664 {
665  if (size == 0) {
666  *num = 0;
667  } else if (size == 4) {
668  *num = av_int2float(avio_rb32(pb));
669  } else if (size == 8){
670  *num = av_int2double(avio_rb64(pb));
671  } else
672  return AVERROR_INVALIDDATA;
673 
674  return 0;
675 }
676 
677 /*
678  * Read the next element as an ASCII string.
679  * 0 is success, < 0 is failure.
680  */
681 static int ebml_read_ascii(AVIOContext *pb, int size, char **str)
682 {
683  char *res;
684 
685  /* EBML strings are usually not 0-terminated, so we allocate one
686  * byte more, read the string and NULL-terminate it ourselves. */
687  if (!(res = av_malloc(size + 1)))
688  return AVERROR(ENOMEM);
689  if (avio_read(pb, (uint8_t *) res, size) != size) {
690  av_free(res);
691  return AVERROR(EIO);
692  }
693  (res)[size] = '\0';
694  av_free(*str);
695  *str = res;
696 
697  return 0;
698 }
699 
700 /*
701  * Read the next element as binary data.
702  * 0 is success, < 0 is failure.
703  */
704 static int ebml_read_binary(AVIOContext *pb, int length, EbmlBin *bin)
705 {
706  av_free(bin->data);
707  if (!(bin->data = av_malloc(length)))
708  return AVERROR(ENOMEM);
709 
710  bin->size = length;
711  bin->pos = avio_tell(pb);
712  if (avio_read(pb, bin->data, length) != length) {
713  av_freep(&bin->data);
714  return AVERROR(EIO);
715  }
716 
717  return 0;
718 }
719 
720 /*
721  * Read the next element, but only the header. The contents
722  * are supposed to be sub-elements which can be read separately.
723  * 0 is success, < 0 is failure.
724  */
725 static int ebml_read_master(MatroskaDemuxContext *matroska, uint64_t length)
726 {
727  AVIOContext *pb = matroska->ctx->pb;
729 
730  if (matroska->num_levels >= EBML_MAX_DEPTH) {
731  av_log(matroska->ctx, AV_LOG_ERROR,
732  "File moves beyond max. allowed depth (%d)\n", EBML_MAX_DEPTH);
733  return AVERROR(ENOSYS);
734  }
735 
736  level = &matroska->levels[matroska->num_levels++];
737  level->start = avio_tell(pb);
738  level->length = length;
739 
740  return 0;
741 }
742 
743 /*
744  * Read signed/unsigned "EBML" numbers.
745  * Return: number of bytes processed, < 0 on error
746  */
748  uint8_t *data, uint32_t size, uint64_t *num)
749 {
750  AVIOContext pb;
751  ffio_init_context(&pb, data, size, 0, NULL, NULL, NULL, NULL);
752  return ebml_read_num(matroska, &pb, FFMIN(size, 8), num);
753 }
754 
755 /*
756  * Same as above, but signed.
757  */
759  uint8_t *data, uint32_t size, int64_t *num)
760 {
761  uint64_t unum;
762  int res;
763 
764  /* read as unsigned number first */
765  if ((res = matroska_ebmlnum_uint(matroska, data, size, &unum)) < 0)
766  return res;
767 
768  /* make signed (weird way) */
769  *num = unum - ((1LL << (7*res - 1)) - 1);
770 
771  return res;
772 }
773 
774 static int ebml_parse_elem(MatroskaDemuxContext *matroska,
775  EbmlSyntax *syntax, void *data);
776 
777 static int ebml_parse_id(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
778  uint32_t id, void *data)
779 {
780  int i;
781  for (i=0; syntax[i].id; i++)
782  if (id == syntax[i].id)
783  break;
784  if (!syntax[i].id && id == MATROSKA_ID_CLUSTER &&
785  matroska->num_levels > 0 &&
786  matroska->levels[matroska->num_levels-1].length == 0xffffffffffffff)
787  return 0; // we reached the end of an unknown size cluster
788  if (!syntax[i].id && id != EBML_ID_VOID && id != EBML_ID_CRC32) {
789  av_log(matroska->ctx, AV_LOG_INFO, "Unknown entry 0x%X\n", id);
790  if (matroska->ctx->error_recognition & AV_EF_EXPLODE)
791  return AVERROR_INVALIDDATA;
792  }
793  return ebml_parse_elem(matroska, &syntax[i], data);
794 }
795 
796 static int ebml_parse(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
797  void *data)
798 {
799  if (!matroska->current_id) {
800  uint64_t id;
801  int res = ebml_read_num(matroska, matroska->ctx->pb, 4, &id);
802  if (res < 0)
803  return res;
804  matroska->current_id = id | 1 << 7*res;
805  }
806  return ebml_parse_id(matroska, syntax, matroska->current_id, data);
807 }
808 
809 static int ebml_parse_nest(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
810  void *data)
811 {
812  int i, res = 0;
813 
814  for (i=0; syntax[i].id; i++)
815  switch (syntax[i].type) {
816  case EBML_UINT:
817  *(uint64_t *)((char *)data+syntax[i].data_offset) = syntax[i].def.u;
818  break;
819  case EBML_FLOAT:
820  *(double *)((char *)data+syntax[i].data_offset) = syntax[i].def.f;
821  break;
822  case EBML_STR:
823  case EBML_UTF8:
824  *(char **)((char *)data+syntax[i].data_offset) = av_strdup(syntax[i].def.s);
825  break;
826  }
827 
828  while (!res && !ebml_level_end(matroska))
829  res = ebml_parse(matroska, syntax, data);
830 
831  return res;
832 }
833 
835  EbmlSyntax *syntax, void *data)
836 {
837  static const uint64_t max_lengths[EBML_TYPE_COUNT] = {
838  [EBML_UINT] = 8,
839  [EBML_FLOAT] = 8,
840  // max. 16 MB for strings
841  [EBML_STR] = 0x1000000,
842  [EBML_UTF8] = 0x1000000,
843  // max. 256 MB for binary data
844  [EBML_BIN] = 0x10000000,
845  // no limits for anything else
846  };
847  AVIOContext *pb = matroska->ctx->pb;
848  uint32_t id = syntax->id;
849  uint64_t length;
850  int res;
851  void *newelem;
852 
853  data = (char *)data + syntax->data_offset;
854  if (syntax->list_elem_size) {
855  EbmlList *list = data;
856  newelem = av_realloc(list->elem, (list->nb_elem+1)*syntax->list_elem_size);
857  if (!newelem)
858  return AVERROR(ENOMEM);
859  list->elem = newelem;
860  data = (char*)list->elem + list->nb_elem*syntax->list_elem_size;
861  memset(data, 0, syntax->list_elem_size);
862  list->nb_elem++;
863  }
864 
865  if (syntax->type != EBML_PASS && syntax->type != EBML_STOP) {
866  matroska->current_id = 0;
867  if ((res = ebml_read_length(matroska, pb, &length)) < 0)
868  return res;
869  if (max_lengths[syntax->type] && length > max_lengths[syntax->type]) {
870  av_log(matroska->ctx, AV_LOG_ERROR,
871  "Invalid length 0x%"PRIx64" > 0x%"PRIx64" for syntax element %i\n",
872  length, max_lengths[syntax->type], syntax->type);
873  return AVERROR_INVALIDDATA;
874  }
875  }
876 
877  switch (syntax->type) {
878  case EBML_UINT: res = ebml_read_uint (pb, length, data); break;
879  case EBML_FLOAT: res = ebml_read_float (pb, length, data); break;
880  case EBML_STR:
881  case EBML_UTF8: res = ebml_read_ascii (pb, length, data); break;
882  case EBML_BIN: res = ebml_read_binary(pb, length, data); break;
883  case EBML_NEST: if ((res=ebml_read_master(matroska, length)) < 0)
884  return res;
885  if (id == MATROSKA_ID_SEGMENT)
886  matroska->segment_start = avio_tell(matroska->ctx->pb);
887  return ebml_parse_nest(matroska, syntax->def.n, data);
888  case EBML_PASS: return ebml_parse_id(matroska, syntax->def.n, id, data);
889  case EBML_STOP: return 1;
890  default: return avio_skip(pb,length)<0 ? AVERROR(EIO) : 0;
891  }
892  if (res == AVERROR_INVALIDDATA)
893  av_log(matroska->ctx, AV_LOG_ERROR, "Invalid element\n");
894  else if (res == AVERROR(EIO))
895  av_log(matroska->ctx, AV_LOG_ERROR, "Read error\n");
896  return res;
897 }
898 
899 static void ebml_free(EbmlSyntax *syntax, void *data)
900 {
901  int i, j;
902  for (i=0; syntax[i].id; i++) {
903  void *data_off = (char *)data + syntax[i].data_offset;
904  switch (syntax[i].type) {
905  case EBML_STR:
906  case EBML_UTF8: av_freep(data_off); break;
907  case EBML_BIN: av_freep(&((EbmlBin *)data_off)->data); break;
908  case EBML_NEST:
909  if (syntax[i].list_elem_size) {
910  EbmlList *list = data_off;
911  char *ptr = list->elem;
912  for (j=0; j<list->nb_elem; j++, ptr+=syntax[i].list_elem_size)
913  ebml_free(syntax[i].def.n, ptr);
914  av_free(list->elem);
915  } else
916  ebml_free(syntax[i].def.n, data_off);
917  default: break;
918  }
919  }
920 }
921 
922 
923 /*
924  * Autodetecting...
925  */
927 {
928  uint64_t total = 0;
929  int len_mask = 0x80, size = 1, n = 1, i;
930 
931  /* EBML header? */
932  if (AV_RB32(p->buf) != EBML_ID_HEADER)
933  return 0;
934 
935  /* length of header */
936  total = p->buf[4];
937  while (size <= 8 && !(total & len_mask)) {
938  size++;
939  len_mask >>= 1;
940  }
941  if (size > 8)
942  return 0;
943  total &= (len_mask - 1);
944  while (n < size)
945  total = (total << 8) | p->buf[4 + n++];
946 
947  /* Does the probe data contain the whole header? */
948  if (p->buf_size < 4 + size + total)
949  return 0;
950 
951  /* The header should contain a known document type. For now,
952  * we don't parse the whole header but simply check for the
953  * availability of that array of characters inside the header.
954  * Not fully fool-proof, but good enough. */
955  for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++) {
956  int probelen = strlen(matroska_doctypes[i]);
957  if (total < probelen)
958  continue;
959  for (n = 4+size; n <= 4+size+total-probelen; n++)
960  if (!memcmp(p->buf+n, matroska_doctypes[i], probelen))
961  return AVPROBE_SCORE_MAX;
962  }
963 
964  // probably valid EBML header but no recognized doctype
965  return AVPROBE_SCORE_MAX/2;
966 }
967 
969  int num)
970 {
971  MatroskaTrack *tracks = matroska->tracks.elem;
972  int i;
973 
974  for (i=0; i < matroska->tracks.nb_elem; i++)
975  if (tracks[i].num == num)
976  return &tracks[i];
977 
978  av_log(matroska->ctx, AV_LOG_ERROR, "Invalid track number %d\n", num);
979  return NULL;
980 }
981 
982 static int matroska_decode_buffer(uint8_t** buf, int* buf_size,
983  MatroskaTrack *track)
984 {
985  MatroskaTrackEncoding *encodings = track->encodings.elem;
986  uint8_t* data = *buf;
987  int isize = *buf_size;
988  uint8_t* pkt_data = NULL;
989  uint8_t av_unused *newpktdata;
990  int pkt_size = isize;
991  int result = 0;
992  int olen;
993 
994  if (pkt_size >= 10000000)
995  return AVERROR_INVALIDDATA;
996 
997  switch (encodings[0].compression.algo) {
999  int header_size = encodings[0].compression.settings.size;
1000  uint8_t *header = encodings[0].compression.settings.data;
1001 
1002  if (!header_size)
1003  return 0;
1004 
1005  pkt_size = isize + header_size;
1006  pkt_data = av_malloc(pkt_size);
1007  if (!pkt_data)
1008  return AVERROR(ENOMEM);
1009 
1010  memcpy(pkt_data, header, header_size);
1011  memcpy(pkt_data + header_size, data, isize);
1012  break;
1013  }
1014 #if CONFIG_LZO
1016  do {
1017  olen = pkt_size *= 3;
1018  newpktdata = av_realloc(pkt_data, pkt_size + AV_LZO_OUTPUT_PADDING);
1019  if (!newpktdata) {
1020  result = AVERROR(ENOMEM);
1021  goto failed;
1022  }
1023  pkt_data = newpktdata;
1024  result = av_lzo1x_decode(pkt_data, &olen, data, &isize);
1025  } while (result==AV_LZO_OUTPUT_FULL && pkt_size<10000000);
1026  if (result) {
1027  result = AVERROR_INVALIDDATA;
1028  goto failed;
1029  }
1030  pkt_size -= olen;
1031  break;
1032 #endif
1033 #if CONFIG_ZLIB
1035  z_stream zstream = {0};
1036  if (inflateInit(&zstream) != Z_OK)
1037  return -1;
1038  zstream.next_in = data;
1039  zstream.avail_in = isize;
1040  do {
1041  pkt_size *= 3;
1042  newpktdata = av_realloc(pkt_data, pkt_size);
1043  if (!newpktdata) {
1044  inflateEnd(&zstream);
1045  goto failed;
1046  }
1047  pkt_data = newpktdata;
1048  zstream.avail_out = pkt_size - zstream.total_out;
1049  zstream.next_out = pkt_data + zstream.total_out;
1050  result = inflate(&zstream, Z_NO_FLUSH);
1051  } while (result==Z_OK && pkt_size<10000000);
1052  pkt_size = zstream.total_out;
1053  inflateEnd(&zstream);
1054  if (result != Z_STREAM_END) {
1055  if (result == Z_MEM_ERROR)
1056  result = AVERROR(ENOMEM);
1057  else
1058  result = AVERROR_INVALIDDATA;
1059  goto failed;
1060  }
1061  break;
1062  }
1063 #endif
1064 #if CONFIG_BZLIB
1066  bz_stream bzstream = {0};
1067  if (BZ2_bzDecompressInit(&bzstream, 0, 0) != BZ_OK)
1068  return -1;
1069  bzstream.next_in = data;
1070  bzstream.avail_in = isize;
1071  do {
1072  pkt_size *= 3;
1073  newpktdata = av_realloc(pkt_data, pkt_size);
1074  if (!newpktdata) {
1075  BZ2_bzDecompressEnd(&bzstream);
1076  goto failed;
1077  }
1078  pkt_data = newpktdata;
1079  bzstream.avail_out = pkt_size - bzstream.total_out_lo32;
1080  bzstream.next_out = pkt_data + bzstream.total_out_lo32;
1081  result = BZ2_bzDecompress(&bzstream);
1082  } while (result==BZ_OK && pkt_size<10000000);
1083  pkt_size = bzstream.total_out_lo32;
1084  BZ2_bzDecompressEnd(&bzstream);
1085  if (result != BZ_STREAM_END) {
1086  if (result == BZ_MEM_ERROR)
1087  result = AVERROR(ENOMEM);
1088  else
1089  result = AVERROR_INVALIDDATA;
1090  goto failed;
1091  }
1092  break;
1093  }
1094 #endif
1095  default:
1096  return AVERROR_INVALIDDATA;
1097  }
1098 
1099  *buf = pkt_data;
1100  *buf_size = pkt_size;
1101  return 0;
1102  failed:
1103  av_free(pkt_data);
1104  return result;
1105 }
1106 
1108  AVPacket *pkt, uint64_t display_duration)
1109 {
1110  char *line, *layer, *ptr = pkt->data, *end = ptr+pkt->size;
1111  for (; *ptr!=',' && ptr<end-1; ptr++);
1112  if (*ptr == ',')
1113  layer = ++ptr;
1114  for (; *ptr!=',' && ptr<end-1; ptr++);
1115  if (*ptr == ',') {
1116  int64_t end_pts = pkt->pts + display_duration;
1117  int sc = matroska->time_scale * pkt->pts / 10000000;
1118  int ec = matroska->time_scale * end_pts / 10000000;
1119  int sh, sm, ss, eh, em, es, len;
1120  sh = sc/360000; sc -= 360000*sh;
1121  sm = sc/ 6000; sc -= 6000*sm;
1122  ss = sc/ 100; sc -= 100*ss;
1123  eh = ec/360000; ec -= 360000*eh;
1124  em = ec/ 6000; ec -= 6000*em;
1125  es = ec/ 100; ec -= 100*es;
1126  *ptr++ = '\0';
1127  len = 50 + end-ptr + FF_INPUT_BUFFER_PADDING_SIZE;
1128  if (!(line = av_malloc(len)))
1129  return;
1130  snprintf(line,len,"Dialogue: %s,%d:%02d:%02d.%02d,%d:%02d:%02d.%02d,%s\r\n",
1131  layer, sh, sm, ss, sc, eh, em, es, ec, ptr);
1132  av_free(pkt->data);
1133  pkt->data = line;
1134  pkt->size = strlen(line);
1135  }
1136 }
1137 
1139 {
1140  int old_size = out->size;
1141  int ret = av_grow_packet(out, in->size);
1142  if (ret < 0)
1143  return ret;
1144 
1145  memcpy(out->data + old_size, in->data, in->size);
1146 
1147  av_free_packet(in);
1148  av_free(in);
1149  return 0;
1150 }
1151 
1153  AVDictionary **metadata, char *prefix)
1154 {
1155  MatroskaTag *tags = list->elem;
1156  char key[1024];
1157  int i;
1158 
1159  for (i=0; i < list->nb_elem; i++) {
1160  const char *lang = tags[i].lang && strcmp(tags[i].lang, "und") ?
1161  tags[i].lang : NULL;
1162 
1163  if (!tags[i].name) {
1164  av_log(s, AV_LOG_WARNING, "Skipping invalid tag with no TagName.\n");
1165  continue;
1166  }
1167  if (prefix) snprintf(key, sizeof(key), "%s/%s", prefix, tags[i].name);
1168  else av_strlcpy(key, tags[i].name, sizeof(key));
1169  if (tags[i].def || !lang) {
1170  av_dict_set(metadata, key, tags[i].string, 0);
1171  if (tags[i].sub.nb_elem)
1172  matroska_convert_tag(s, &tags[i].sub, metadata, key);
1173  }
1174  if (lang) {
1175  av_strlcat(key, "-", sizeof(key));
1176  av_strlcat(key, lang, sizeof(key));
1177  av_dict_set(metadata, key, tags[i].string, 0);
1178  if (tags[i].sub.nb_elem)
1179  matroska_convert_tag(s, &tags[i].sub, metadata, key);
1180  }
1181  }
1183 }
1184 
1186 {
1187  MatroskaDemuxContext *matroska = s->priv_data;
1188  MatroskaTags *tags = matroska->tags.elem;
1189  int i, j;
1190 
1191  for (i=0; i < matroska->tags.nb_elem; i++) {
1192  if (tags[i].target.attachuid) {
1193  MatroskaAttachement *attachment = matroska->attachments.elem;
1194  for (j=0; j<matroska->attachments.nb_elem; j++)
1195  if (attachment[j].uid == tags[i].target.attachuid
1196  && attachment[j].stream)
1197  matroska_convert_tag(s, &tags[i].tag,
1198  &attachment[j].stream->metadata, NULL);
1199  } else if (tags[i].target.chapteruid) {
1200  MatroskaChapter *chapter = matroska->chapters.elem;
1201  for (j=0; j<matroska->chapters.nb_elem; j++)
1202  if (chapter[j].uid == tags[i].target.chapteruid
1203  && chapter[j].chapter)
1204  matroska_convert_tag(s, &tags[i].tag,
1205  &chapter[j].chapter->metadata, NULL);
1206  } else if (tags[i].target.trackuid) {
1207  MatroskaTrack *track = matroska->tracks.elem;
1208  for (j=0; j<matroska->tracks.nb_elem; j++)
1209  if (track[j].uid == tags[i].target.trackuid && track[j].stream)
1210  matroska_convert_tag(s, &tags[i].tag,
1211  &track[j].stream->metadata, NULL);
1212  } else {
1213  matroska_convert_tag(s, &tags[i].tag, &s->metadata,
1214  tags[i].target.type);
1215  }
1216  }
1217 }
1218 
1220 {
1221  EbmlList *seekhead_list = &matroska->seekhead;
1222  MatroskaSeekhead *seekhead = seekhead_list->elem;
1223  uint32_t level_up = matroska->level_up;
1224  int64_t before_pos = avio_tell(matroska->ctx->pb);
1225  uint32_t saved_id = matroska->current_id;
1227  int64_t offset;
1228  int ret = 0;
1229 
1230  if (idx >= seekhead_list->nb_elem
1231  || seekhead[idx].id == MATROSKA_ID_SEEKHEAD
1232  || seekhead[idx].id == MATROSKA_ID_CLUSTER)
1233  return 0;
1234 
1235  /* seek */
1236  offset = seekhead[idx].pos + matroska->segment_start;
1237  if (avio_seek(matroska->ctx->pb, offset, SEEK_SET) == offset) {
1238  /* We don't want to lose our seekhead level, so we add
1239  * a dummy. This is a crude hack. */
1240  if (matroska->num_levels == EBML_MAX_DEPTH) {
1241  av_log(matroska->ctx, AV_LOG_INFO,
1242  "Max EBML element depth (%d) reached, "
1243  "cannot parse further.\n", EBML_MAX_DEPTH);
1244  ret = AVERROR_INVALIDDATA;
1245  } else {
1246  level.start = 0;
1247  level.length = (uint64_t)-1;
1248  matroska->levels[matroska->num_levels] = level;
1249  matroska->num_levels++;
1250  matroska->current_id = 0;
1251 
1252  ret = ebml_parse(matroska, matroska_segment, matroska);
1253 
1254  /* remove dummy level */
1255  while (matroska->num_levels) {
1256  uint64_t length = matroska->levels[--matroska->num_levels].length;
1257  if (length == (uint64_t)-1)
1258  break;
1259  }
1260  }
1261  }
1262  /* seek back */
1263  avio_seek(matroska->ctx->pb, before_pos, SEEK_SET);
1264  matroska->level_up = level_up;
1265  matroska->current_id = saved_id;
1266 
1267  return ret;
1268 }
1269 
1271 {
1272  EbmlList *seekhead_list = &matroska->seekhead;
1273  int64_t before_pos = avio_tell(matroska->ctx->pb);
1274  int i;
1275 
1276  // we should not do any seeking in the streaming case
1277  if (!matroska->ctx->pb->seekable ||
1278  (matroska->ctx->flags & AVFMT_FLAG_IGNIDX))
1279  return;
1280 
1281  for (i = 0; i < seekhead_list->nb_elem; i++) {
1282  MatroskaSeekhead *seekhead = seekhead_list->elem;
1283  if (seekhead[i].pos <= before_pos)
1284  continue;
1285 
1286  // defer cues parsing until we actually need cue data.
1287  if (seekhead[i].id == MATROSKA_ID_CUES) {
1288  matroska->cues_parsing_deferred = 1;
1289  continue;
1290  }
1291 
1292  if (matroska_parse_seekhead_entry(matroska, i) < 0)
1293  break;
1294  }
1295 }
1296 
1298  EbmlList *seekhead_list = &matroska->seekhead;
1299  MatroskaSeekhead *seekhead = seekhead_list->elem;
1300  EbmlList *index_list;
1302  int index_scale = 1;
1303  int i, j;
1304 
1305  for (i = 0; i < seekhead_list->nb_elem; i++)
1306  if (seekhead[i].id == MATROSKA_ID_CUES)
1307  break;
1308  assert(i <= seekhead_list->nb_elem);
1309 
1310  matroska_parse_seekhead_entry(matroska, i);
1311 
1312  index_list = &matroska->index;
1313  index = index_list->elem;
1314  if (index_list->nb_elem
1315  && index[0].time > 1E14/matroska->time_scale) {
1316  av_log(matroska->ctx, AV_LOG_WARNING, "Working around broken index.\n");
1317  index_scale = matroska->time_scale;
1318  }
1319  for (i = 0; i < index_list->nb_elem; i++) {
1320  EbmlList *pos_list = &index[i].pos;
1321  MatroskaIndexPos *pos = pos_list->elem;
1322  for (j = 0; j < pos_list->nb_elem; j++) {
1323  MatroskaTrack *track = matroska_find_track_by_num(matroska, pos[j].track);
1324  if (track && track->stream)
1325  av_add_index_entry(track->stream,
1326  pos[j].pos + matroska->segment_start,
1327  index[i].time/index_scale, 0, 0,
1329  }
1330  }
1331 }
1332 
1334 {
1335  static const char * const aac_profiles[] = { "MAIN", "LC", "SSR" };
1336  int profile;
1337 
1338  for (profile=0; profile<FF_ARRAY_ELEMS(aac_profiles); profile++)
1339  if (strstr(codec_id, aac_profiles[profile]))
1340  break;
1341  return profile + 1;
1342 }
1343 
1344 static int matroska_aac_sri(int samplerate)
1345 {
1346  int sri;
1347 
1348  for (sri=0; sri<FF_ARRAY_ELEMS(avpriv_mpeg4audio_sample_rates); sri++)
1349  if (avpriv_mpeg4audio_sample_rates[sri] == samplerate)
1350  break;
1351  return sri;
1352 }
1353 
1355 {
1356  MatroskaDemuxContext *matroska = s->priv_data;
1357  EbmlList *attachements_list = &matroska->attachments;
1358  MatroskaAttachement *attachements;
1359  EbmlList *chapters_list = &matroska->chapters;
1360  MatroskaChapter *chapters;
1361  MatroskaTrack *tracks;
1362  uint64_t max_start = 0;
1363  Ebml ebml = { 0 };
1364  AVStream *st;
1365  int i, j, res;
1366 
1367  matroska->ctx = s;
1368 
1369  /* First read the EBML header. */
1370  if (ebml_parse(matroska, ebml_syntax, &ebml)
1371  || ebml.version > EBML_VERSION || ebml.max_size > sizeof(uint64_t)
1372  || ebml.id_length > sizeof(uint32_t) || ebml.doctype_version > 2) {
1373  av_log(matroska->ctx, AV_LOG_ERROR,
1374  "EBML header using unsupported features\n"
1375  "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
1376  ebml.version, ebml.doctype, ebml.doctype_version);
1377  ebml_free(ebml_syntax, &ebml);
1378  return AVERROR_PATCHWELCOME;
1379  }
1380  for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++)
1381  if (!strcmp(ebml.doctype, matroska_doctypes[i]))
1382  break;
1383  if (i >= FF_ARRAY_ELEMS(matroska_doctypes)) {
1384  av_log(s, AV_LOG_WARNING, "Unknown EBML doctype '%s'\n", ebml.doctype);
1385  if (matroska->ctx->error_recognition & AV_EF_EXPLODE) {
1386  ebml_free(ebml_syntax, &ebml);
1387  return AVERROR_INVALIDDATA;
1388  }
1389  }
1390  ebml_free(ebml_syntax, &ebml);
1391 
1392  /* The next thing is a segment. */
1393  if ((res = ebml_parse(matroska, matroska_segments, matroska)) < 0)
1394  return res;
1395  matroska_execute_seekhead(matroska);
1396 
1397  if (!matroska->time_scale)
1398  matroska->time_scale = 1000000;
1399  if (matroska->duration)
1400  matroska->ctx->duration = matroska->duration * matroska->time_scale
1401  * 1000 / AV_TIME_BASE;
1402  av_dict_set(&s->metadata, "title", matroska->title, 0);
1403 
1404  tracks = matroska->tracks.elem;
1405  for (i=0; i < matroska->tracks.nb_elem; i++) {
1406  MatroskaTrack *track = &tracks[i];
1408  EbmlList *encodings_list = &tracks->encodings;
1409  MatroskaTrackEncoding *encodings = encodings_list->elem;
1410  uint8_t *extradata = NULL;
1411  int extradata_size = 0;
1412  int extradata_offset = 0;
1413  AVIOContext b;
1414 
1415  /* Apply some sanity checks. */
1416  if (track->type != MATROSKA_TRACK_TYPE_VIDEO &&
1417  track->type != MATROSKA_TRACK_TYPE_AUDIO &&
1418  track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
1419  av_log(matroska->ctx, AV_LOG_INFO,
1420  "Unknown or unsupported track type %"PRIu64"\n",
1421  track->type);
1422  continue;
1423  }
1424  if (track->codec_id == NULL)
1425  continue;
1426 
1427  if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1428  if (!track->default_duration && track->video.frame_rate > 0)
1429  track->default_duration = 1000000000/track->video.frame_rate;
1430  if (!track->video.display_width)
1431  track->video.display_width = track->video.pixel_width;
1432  if (!track->video.display_height)
1433  track->video.display_height = track->video.pixel_height;
1434  } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
1435  if (!track->audio.out_samplerate)
1436  track->audio.out_samplerate = track->audio.samplerate;
1437  }
1438  if (encodings_list->nb_elem > 1) {
1439  av_log(matroska->ctx, AV_LOG_ERROR,
1440  "Multiple combined encodings not supported");
1441  } else if (encodings_list->nb_elem == 1) {
1442  if (encodings[0].type ||
1443  (
1444 #if CONFIG_ZLIB
1445  encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_ZLIB &&
1446 #endif
1447 #if CONFIG_BZLIB
1449 #endif
1450 #if CONFIG_LZO
1452 #endif
1454  encodings[0].scope = 0;
1455  av_log(matroska->ctx, AV_LOG_ERROR,
1456  "Unsupported encoding type");
1457  } else if (track->codec_priv.size && encodings[0].scope&2) {
1458  uint8_t *codec_priv = track->codec_priv.data;
1459  int ret = matroska_decode_buffer(&track->codec_priv.data,
1460  &track->codec_priv.size,
1461  track);
1462  if (ret < 0) {
1463  track->codec_priv.data = NULL;
1464  track->codec_priv.size = 0;
1465  av_log(matroska->ctx, AV_LOG_ERROR,
1466  "Failed to decode codec private data\n");
1467  }
1468 
1469  if (codec_priv != track->codec_priv.data)
1470  av_free(codec_priv);
1471  }
1472  }
1473 
1474  for(j=0; ff_mkv_codec_tags[j].id != AV_CODEC_ID_NONE; j++){
1475  if(!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
1476  strlen(ff_mkv_codec_tags[j].str))){
1477  codec_id= ff_mkv_codec_tags[j].id;
1478  break;
1479  }
1480  }
1481 
1482  st = track->stream = avformat_new_stream(s, NULL);
1483  if (st == NULL)
1484  return AVERROR(ENOMEM);
1485 
1486  if (!strcmp(track->codec_id, "V_MS/VFW/FOURCC")
1487  && track->codec_priv.size >= 40
1488  && track->codec_priv.data != NULL) {
1489  track->ms_compat = 1;
1490  track->video.fourcc = AV_RL32(track->codec_priv.data + 16);
1491  codec_id = ff_codec_get_id(ff_codec_bmp_tags, track->video.fourcc);
1492  extradata_offset = 40;
1493  } else if (!strcmp(track->codec_id, "A_MS/ACM")
1494  && track->codec_priv.size >= 14
1495  && track->codec_priv.data != NULL) {
1496  int ret;
1497  ffio_init_context(&b, track->codec_priv.data, track->codec_priv.size,
1499  ret = ff_get_wav_header(&b, st->codec, track->codec_priv.size);
1500  if (ret < 0)
1501  return ret;
1502  codec_id = st->codec->codec_id;
1503  extradata_offset = FFMIN(track->codec_priv.size, 18);
1504  } else if (!strcmp(track->codec_id, "V_QUICKTIME")
1505  && (track->codec_priv.size >= 86)
1506  && (track->codec_priv.data != NULL)) {
1507  track->video.fourcc = AV_RL32(track->codec_priv.data);
1509  } else if (codec_id == AV_CODEC_ID_PCM_S16BE) {
1510  switch (track->audio.bitdepth) {
1511  case 8: codec_id = AV_CODEC_ID_PCM_U8; break;
1512  case 24: codec_id = AV_CODEC_ID_PCM_S24BE; break;
1513  case 32: codec_id = AV_CODEC_ID_PCM_S32BE; break;
1514  }
1515  } else if (codec_id == AV_CODEC_ID_PCM_S16LE) {
1516  switch (track->audio.bitdepth) {
1517  case 8: codec_id = AV_CODEC_ID_PCM_U8; break;
1518  case 24: codec_id = AV_CODEC_ID_PCM_S24LE; break;
1519  case 32: codec_id = AV_CODEC_ID_PCM_S32LE; break;
1520  }
1521  } else if (codec_id==AV_CODEC_ID_PCM_F32LE && track->audio.bitdepth==64) {
1522  codec_id = AV_CODEC_ID_PCM_F64LE;
1523  } else if (codec_id == AV_CODEC_ID_AAC && !track->codec_priv.size) {
1524  int profile = matroska_aac_profile(track->codec_id);
1525  int sri = matroska_aac_sri(track->audio.samplerate);
1526  extradata = av_mallocz(5 + FF_INPUT_BUFFER_PADDING_SIZE);
1527  if (extradata == NULL)
1528  return AVERROR(ENOMEM);
1529  extradata[0] = (profile << 3) | ((sri&0x0E) >> 1);
1530  extradata[1] = ((sri&0x01) << 7) | (track->audio.channels<<3);
1531  if (strstr(track->codec_id, "SBR")) {
1532  sri = matroska_aac_sri(track->audio.out_samplerate);
1533  extradata[2] = 0x56;
1534  extradata[3] = 0xE5;
1535  extradata[4] = 0x80 | (sri<<3);
1536  extradata_size = 5;
1537  } else
1538  extradata_size = 2;
1539  } else if (codec_id == AV_CODEC_ID_ALAC && track->codec_priv.size) {
1540  /* Only ALAC's magic cookie is stored in Matroska's track headers.
1541  Create the "atom size", "tag", and "tag version" fields the
1542  decoder expects manually. */
1543  extradata_size = 12 + track->codec_priv.size;
1544  extradata = av_mallocz(extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
1545  if (extradata == NULL)
1546  return AVERROR(ENOMEM);
1547  AV_WB32(extradata, extradata_size);
1548  memcpy(&extradata[4], "alac", 4);
1549  AV_WB32(&extradata[8], 0);
1550  memcpy(&extradata[12], track->codec_priv.data,
1551  track->codec_priv.size);
1552  } else if (codec_id == AV_CODEC_ID_TTA) {
1553  extradata_size = 30;
1554  extradata = av_mallocz(extradata_size);
1555  if (extradata == NULL)
1556  return AVERROR(ENOMEM);
1557  ffio_init_context(&b, extradata, extradata_size, 1,
1558  NULL, NULL, NULL, NULL);
1559  avio_write(&b, "TTA1", 4);
1560  avio_wl16(&b, 1);
1561  avio_wl16(&b, track->audio.channels);
1562  avio_wl16(&b, track->audio.bitdepth);
1563  avio_wl32(&b, track->audio.out_samplerate);
1564  avio_wl32(&b, matroska->ctx->duration * track->audio.out_samplerate);
1565  } else if (codec_id == AV_CODEC_ID_RV10 || codec_id == AV_CODEC_ID_RV20 ||
1566  codec_id == AV_CODEC_ID_RV30 || codec_id == AV_CODEC_ID_RV40) {
1567  extradata_offset = 26;
1568  } else if (codec_id == AV_CODEC_ID_RA_144) {
1569  track->audio.out_samplerate = 8000;
1570  track->audio.channels = 1;
1571  } else if (codec_id == AV_CODEC_ID_RA_288 || codec_id == AV_CODEC_ID_COOK ||
1572  codec_id == AV_CODEC_ID_ATRAC3 || codec_id == AV_CODEC_ID_SIPR) {
1573  int flavor;
1574  ffio_init_context(&b, track->codec_priv.data,track->codec_priv.size,
1575  0, NULL, NULL, NULL, NULL);
1576  avio_skip(&b, 22);
1577  flavor = avio_rb16(&b);
1578  track->audio.coded_framesize = avio_rb32(&b);
1579  avio_skip(&b, 12);
1580  track->audio.sub_packet_h = avio_rb16(&b);
1581  track->audio.frame_size = avio_rb16(&b);
1582  track->audio.sub_packet_size = avio_rb16(&b);
1583  if (flavor <= 0 || track->audio.coded_framesize <= 0 ||
1584  track->audio.sub_packet_h <= 0 || track->audio.frame_size <= 0 ||
1585  track->audio.sub_packet_size <= 0)
1586  return AVERROR_INVALIDDATA;
1587  track->audio.buf = av_malloc(track->audio.frame_size * track->audio.sub_packet_h);
1588  if (codec_id == AV_CODEC_ID_RA_288) {
1589  st->codec->block_align = track->audio.coded_framesize;
1590  track->codec_priv.size = 0;
1591  } else {
1592  if (codec_id == AV_CODEC_ID_SIPR && flavor < 4) {
1593  const int sipr_bit_rate[4] = { 6504, 8496, 5000, 16000 };
1594  track->audio.sub_packet_size = ff_sipr_subpk_size[flavor];
1595  st->codec->bit_rate = sipr_bit_rate[flavor];
1596  }
1597  st->codec->block_align = track->audio.sub_packet_size;
1598  extradata_offset = 78;
1599  }
1600  }
1601  track->codec_priv.size -= extradata_offset;
1602 
1603  if (codec_id == AV_CODEC_ID_NONE)
1604  av_log(matroska->ctx, AV_LOG_INFO,
1605  "Unknown/unsupported AVCodecID %s.\n", track->codec_id);
1606 
1607  if (track->time_scale < 0.01)
1608  track->time_scale = 1.0;
1609  avpriv_set_pts_info(st, 64, matroska->time_scale*track->time_scale, 1000*1000*1000); /* 64 bit pts in ns */
1610 
1611  st->codec->codec_id = codec_id;
1612  st->start_time = 0;
1613  if (strcmp(track->language, "und"))
1614  av_dict_set(&st->metadata, "language", track->language, 0);
1615  av_dict_set(&st->metadata, "title", track->name, 0);
1616 
1617  if (track->flag_default)
1619  if (track->flag_forced)
1621 
1622  if (!st->codec->extradata) {
1623  if(extradata){
1624  st->codec->extradata = extradata;
1625  st->codec->extradata_size = extradata_size;
1626  } else if(track->codec_priv.data && track->codec_priv.size > 0){
1627  st->codec->extradata = av_mallocz(track->codec_priv.size +
1629  if(st->codec->extradata == NULL)
1630  return AVERROR(ENOMEM);
1631  st->codec->extradata_size = track->codec_priv.size;
1632  memcpy(st->codec->extradata,
1633  track->codec_priv.data + extradata_offset,
1634  track->codec_priv.size);
1635  }
1636  }
1637 
1638  if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1640  st->codec->codec_tag = track->video.fourcc;
1641  st->codec->width = track->video.pixel_width;
1642  st->codec->height = track->video.pixel_height;
1644  &st->sample_aspect_ratio.den,
1645  st->codec->height * track->video.display_width,
1646  st->codec-> width * track->video.display_height,
1647  255);
1648  if (st->codec->codec_id != AV_CODEC_ID_H264)
1650  if (track->default_duration) {
1652  1000000000, track->default_duration, 30000);
1653 #if FF_API_R_FRAME_RATE
1654  st->r_frame_rate = st->avg_frame_rate;
1655 #endif
1656  }
1657  } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
1659  st->codec->sample_rate = track->audio.out_samplerate;
1660  st->codec->channels = track->audio.channels;
1661  if (st->codec->codec_id != AV_CODEC_ID_AAC)
1663  } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
1665  if (st->codec->codec_id == AV_CODEC_ID_SSA)
1666  matroska->contains_ssa = 1;
1667  }
1668  }
1669 
1670  attachements = attachements_list->elem;
1671  for (j=0; j<attachements_list->nb_elem; j++) {
1672  if (!(attachements[j].filename && attachements[j].mime &&
1673  attachements[j].bin.data && attachements[j].bin.size > 0)) {
1674  av_log(matroska->ctx, AV_LOG_ERROR, "incomplete attachment\n");
1675  } else {
1676  AVStream *st = avformat_new_stream(s, NULL);
1677  if (st == NULL)
1678  break;
1679  av_dict_set(&st->metadata, "filename",attachements[j].filename, 0);
1680  av_dict_set(&st->metadata, "mimetype", attachements[j].mime, 0);
1683  st->codec->extradata = av_malloc(attachements[j].bin.size);
1684  if(st->codec->extradata == NULL)
1685  break;
1686  st->codec->extradata_size = attachements[j].bin.size;
1687  memcpy(st->codec->extradata, attachements[j].bin.data, attachements[j].bin.size);
1688 
1689  for (i=0; ff_mkv_mime_tags[i].id != AV_CODEC_ID_NONE; i++) {
1690  if (!strncmp(ff_mkv_mime_tags[i].str, attachements[j].mime,
1691  strlen(ff_mkv_mime_tags[i].str))) {
1692  st->codec->codec_id = ff_mkv_mime_tags[i].id;
1693  break;
1694  }
1695  }
1696  attachements[j].stream = st;
1697  }
1698  }
1699 
1700  chapters = chapters_list->elem;
1701  for (i=0; i<chapters_list->nb_elem; i++)
1702  if (chapters[i].start != AV_NOPTS_VALUE && chapters[i].uid
1703  && (max_start==0 || chapters[i].start > max_start)) {
1704  chapters[i].chapter =
1705  avpriv_new_chapter(s, chapters[i].uid, (AVRational){1, 1000000000},
1706  chapters[i].start, chapters[i].end,
1707  chapters[i].title);
1708  av_dict_set(&chapters[i].chapter->metadata,
1709  "title", chapters[i].title, 0);
1710  max_start = chapters[i].start;
1711  }
1712 
1714 
1715  return 0;
1716 }
1717 
1718 /*
1719  * Put one packet in an application-supplied AVPacket struct.
1720  * Returns 0 on success or -1 on failure.
1721  */
1723  AVPacket *pkt)
1724 {
1725  if (matroska->num_packets > 0) {
1726  memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
1727  av_free(matroska->packets[0]);
1728  if (matroska->num_packets > 1) {
1729  void *newpackets;
1730  memmove(&matroska->packets[0], &matroska->packets[1],
1731  (matroska->num_packets - 1) * sizeof(AVPacket *));
1732  newpackets = av_realloc(matroska->packets,
1733  (matroska->num_packets - 1) * sizeof(AVPacket *));
1734  if (newpackets)
1735  matroska->packets = newpackets;
1736  } else {
1737  av_freep(&matroska->packets);
1738  matroska->prev_pkt = NULL;
1739  }
1740  matroska->num_packets--;
1741  return 0;
1742  }
1743 
1744  return -1;
1745 }
1746 
1747 /*
1748  * Free all packets in our internal queue.
1749  */
1751 {
1752  matroska->prev_pkt = NULL;
1753  if (matroska->packets) {
1754  int n;
1755  for (n = 0; n < matroska->num_packets; n++) {
1756  av_free_packet(matroska->packets[n]);
1757  av_free(matroska->packets[n]);
1758  }
1759  av_freep(&matroska->packets);
1760  matroska->num_packets = 0;
1761  }
1762 }
1763 
1765  int* buf_size, int type,
1766  uint32_t **lace_buf, int *laces)
1767 {
1768  int res = 0, n, size = *buf_size;
1769  uint8_t *data = *buf;
1770  uint32_t *lace_size;
1771 
1772  if (!type) {
1773  *laces = 1;
1774  *lace_buf = av_mallocz(sizeof(int));
1775  if (!*lace_buf)
1776  return AVERROR(ENOMEM);
1777 
1778  *lace_buf[0] = size;
1779  return 0;
1780  }
1781 
1782  assert(size > 0);
1783  *laces = *data + 1;
1784  data += 1;
1785  size -= 1;
1786  lace_size = av_mallocz(*laces * sizeof(int));
1787  if (!lace_size)
1788  return AVERROR(ENOMEM);
1789 
1790  switch (type) {
1791  case 0x1: /* Xiph lacing */ {
1792  uint8_t temp;
1793  uint32_t total = 0;
1794  for (n = 0; res == 0 && n < *laces - 1; n++) {
1795  while (1) {
1796  if (size == 0) {
1797  res = AVERROR_EOF;
1798  break;
1799  }
1800  temp = *data;
1801  lace_size[n] += temp;
1802  data += 1;
1803  size -= 1;
1804  if (temp != 0xff)
1805  break;
1806  }
1807  total += lace_size[n];
1808  }
1809  if (size <= total) {
1810  res = AVERROR_INVALIDDATA;
1811  break;
1812  }
1813 
1814  lace_size[n] = size - total;
1815  break;
1816  }
1817 
1818  case 0x2: /* fixed-size lacing */
1819  if (size % (*laces)) {
1820  res = AVERROR_INVALIDDATA;
1821  break;
1822  }
1823  for (n = 0; n < *laces; n++)
1824  lace_size[n] = size / *laces;
1825  break;
1826 
1827  case 0x3: /* EBML lacing */ {
1828  uint64_t num;
1829  uint64_t total;
1830  n = matroska_ebmlnum_uint(matroska, data, size, &num);
1831  if (n < 0) {
1832  av_log(matroska->ctx, AV_LOG_INFO,
1833  "EBML block data error\n");
1834  res = n;
1835  break;
1836  }
1837  data += n;
1838  size -= n;
1839  total = lace_size[0] = num;
1840  for (n = 1; res == 0 && n < *laces - 1; n++) {
1841  int64_t snum;
1842  int r;
1843  r = matroska_ebmlnum_sint(matroska, data, size, &snum);
1844  if (r < 0) {
1845  av_log(matroska->ctx, AV_LOG_INFO,
1846  "EBML block data error\n");
1847  res = r;
1848  break;
1849  }
1850  data += r;
1851  size -= r;
1852  lace_size[n] = lace_size[n - 1] + snum;
1853  total += lace_size[n];
1854  }
1855  if (size <= total) {
1856  res = AVERROR_INVALIDDATA;
1857  break;
1858  }
1859  lace_size[*laces - 1] = size - total;
1860  break;
1861  }
1862  }
1863 
1864  *buf = data;
1865  *lace_buf = lace_size;
1866  *buf_size = size;
1867 
1868  return res;
1869 }
1870 
1872  MatroskaTrack *track,
1873  AVStream *st,
1874  uint8_t *data, int size,
1875  uint64_t timecode, uint64_t duration,
1876  int64_t pos)
1877 {
1878  int a = st->codec->block_align;
1879  int sps = track->audio.sub_packet_size;
1880  int cfs = track->audio.coded_framesize;
1881  int h = track->audio.sub_packet_h;
1882  int y = track->audio.sub_packet_cnt;
1883  int w = track->audio.frame_size;
1884  int x;
1885 
1886  if (!track->audio.pkt_cnt) {
1887  if (track->audio.sub_packet_cnt == 0)
1888  track->audio.buf_timecode = timecode;
1889  if (st->codec->codec_id == AV_CODEC_ID_RA_288) {
1890  if (size < cfs * h / 2) {
1891  av_log(matroska->ctx, AV_LOG_ERROR,
1892  "Corrupt int4 RM-style audio packet size\n");
1893  return AVERROR_INVALIDDATA;
1894  }
1895  for (x=0; x<h/2; x++)
1896  memcpy(track->audio.buf+x*2*w+y*cfs,
1897  data+x*cfs, cfs);
1898  } else if (st->codec->codec_id == AV_CODEC_ID_SIPR) {
1899  if (size < w) {
1900  av_log(matroska->ctx, AV_LOG_ERROR,
1901  "Corrupt sipr RM-style audio packet size\n");
1902  return AVERROR_INVALIDDATA;
1903  }
1904  memcpy(track->audio.buf + y*w, data, w);
1905  } else {
1906  if (size < sps * w / sps) {
1907  av_log(matroska->ctx, AV_LOG_ERROR,
1908  "Corrupt generic RM-style audio packet size\n");
1909  return AVERROR_INVALIDDATA;
1910  }
1911  for (x=0; x<w/sps; x++)
1912  memcpy(track->audio.buf+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), data+x*sps, sps);
1913  }
1914 
1915  if (++track->audio.sub_packet_cnt >= h) {
1916  if (st->codec->codec_id == AV_CODEC_ID_SIPR)
1917  ff_rm_reorder_sipr_data(track->audio.buf, h, w);
1918  track->audio.sub_packet_cnt = 0;
1919  track->audio.pkt_cnt = h*w / a;
1920  }
1921  }
1922 
1923  while (track->audio.pkt_cnt) {
1924  AVPacket *pkt = av_mallocz(sizeof(AVPacket));
1925  av_new_packet(pkt, a);
1926  memcpy(pkt->data, track->audio.buf
1927  + a * (h*w / a - track->audio.pkt_cnt--), a);
1928  pkt->pts = track->audio.buf_timecode;
1930  pkt->pos = pos;
1931  pkt->stream_index = st->index;
1932  dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
1933  }
1934 
1935  return 0;
1936 }
1938  MatroskaTrack *track,
1939  AVStream *st,
1940  uint8_t *data, int pkt_size,
1941  uint64_t timecode, uint64_t duration,
1942  int64_t pos, int is_keyframe)
1943 {
1944  MatroskaTrackEncoding *encodings = track->encodings.elem;
1945  uint8_t *pkt_data = data;
1946  int offset = 0, res;
1947  AVPacket *pkt;
1948 
1949  if (encodings && encodings->scope & 1) {
1950  res = matroska_decode_buffer(&pkt_data, &pkt_size, track);
1951  if (res < 0)
1952  return res;
1953  }
1954 
1955  if (st->codec->codec_id == AV_CODEC_ID_PRORES)
1956  offset = 8;
1957 
1958  pkt = av_mallocz(sizeof(AVPacket));
1959  /* XXX: prevent data copy... */
1960  if (av_new_packet(pkt, pkt_size + offset) < 0) {
1961  av_free(pkt);
1962  return AVERROR(ENOMEM);
1963  }
1964 
1965  if (st->codec->codec_id == AV_CODEC_ID_PRORES) {
1966  uint8_t *buf = pkt->data;
1967  bytestream_put_be32(&buf, pkt_size);
1968  bytestream_put_be32(&buf, MKBETAG('i', 'c', 'p', 'f'));
1969  }
1970 
1971  memcpy(pkt->data + offset, pkt_data, pkt_size);
1972 
1973  if (pkt_data != data)
1974  av_free(pkt_data);
1975 
1976  pkt->flags = is_keyframe;
1977  pkt->stream_index = st->index;
1978 
1979  if (track->ms_compat)
1980  pkt->dts = timecode;
1981  else
1982  pkt->pts = timecode;
1983  pkt->pos = pos;
1984  if (st->codec->codec_id == AV_CODEC_ID_TEXT)
1986  else if (track->type != MATROSKA_TRACK_TYPE_SUBTITLE)
1987  pkt->duration = duration;
1988 
1989  if (st->codec->codec_id == AV_CODEC_ID_SSA)
1990  matroska_fix_ass_packet(matroska, pkt, duration);
1991 
1992  if (matroska->prev_pkt &&
1993  timecode != AV_NOPTS_VALUE &&
1994  matroska->prev_pkt->pts == timecode &&
1995  matroska->prev_pkt->stream_index == st->index &&
1996  st->codec->codec_id == AV_CODEC_ID_SSA)
1997  matroska_merge_packets(matroska->prev_pkt, pkt);
1998  else {
1999  dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
2000  matroska->prev_pkt = pkt;
2001  }
2002 
2003  return 0;
2004 }
2005 
2007  int size, int64_t pos, uint64_t cluster_time,
2008  uint64_t block_duration, int is_keyframe,
2009  int64_t cluster_pos)
2010 {
2011  uint64_t timecode = AV_NOPTS_VALUE;
2012  MatroskaTrack *track;
2013  int res = 0;
2014  AVStream *st;
2015  int16_t block_time;
2016  uint32_t *lace_size = NULL;
2017  int n, flags, laces = 0;
2018  uint64_t num, duration;
2019 
2020  if ((n = matroska_ebmlnum_uint(matroska, data, size, &num)) < 0) {
2021  av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
2022  return n;
2023  }
2024  data += n;
2025  size -= n;
2026 
2027  track = matroska_find_track_by_num(matroska, num);
2028  if (!track || !track->stream) {
2029  av_log(matroska->ctx, AV_LOG_INFO,
2030  "Invalid stream %"PRIu64" or size %u\n", num, size);
2031  return AVERROR_INVALIDDATA;
2032  } else if (size <= 3)
2033  return 0;
2034  st = track->stream;
2035  if (st->discard >= AVDISCARD_ALL)
2036  return res;
2037 
2038  block_time = AV_RB16(data);
2039  data += 2;
2040  flags = *data++;
2041  size -= 3;
2042  if (is_keyframe == -1)
2043  is_keyframe = flags & 0x80 ? AV_PKT_FLAG_KEY : 0;
2044 
2045  if (cluster_time != (uint64_t)-1
2046  && (block_time >= 0 || cluster_time >= -block_time)) {
2047  timecode = cluster_time + block_time;
2048  if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE
2049  && timecode < track->end_timecode)
2050  is_keyframe = 0; /* overlapping subtitles are not key frame */
2051  if (is_keyframe)
2052  av_add_index_entry(st, cluster_pos, timecode, 0,0,AVINDEX_KEYFRAME);
2053  }
2054 
2055  if (matroska->skip_to_keyframe && track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
2056  if (!is_keyframe || timecode < matroska->skip_to_timecode)
2057  return res;
2058  matroska->skip_to_keyframe = 0;
2059  }
2060 
2061  res = matroska_parse_laces(matroska, &data, &size, (flags & 0x06) >> 1,
2062  &lace_size, &laces);
2063 
2064  if (res)
2065  goto end;
2066 
2067  if (block_duration != AV_NOPTS_VALUE) {
2068  duration = block_duration / laces;
2069  if (block_duration != duration * laces) {
2070  av_log(matroska->ctx, AV_LOG_WARNING,
2071  "Incorrect block_duration, possibly corrupted container");
2072  }
2073  } else {
2074  duration = track->default_duration / matroska->time_scale;
2075  block_duration = duration * laces;
2076  }
2077 
2078  if (timecode != AV_NOPTS_VALUE)
2079  track->end_timecode =
2080  FFMAX(track->end_timecode, timecode + block_duration);
2081 
2082  for (n = 0; n < laces; n++) {
2083  if ((st->codec->codec_id == AV_CODEC_ID_RA_288 ||
2084  st->codec->codec_id == AV_CODEC_ID_COOK ||
2085  st->codec->codec_id == AV_CODEC_ID_SIPR ||
2086  st->codec->codec_id == AV_CODEC_ID_ATRAC3) &&
2087  st->codec->block_align && track->audio.sub_packet_size) {
2088 
2089  res = matroska_parse_rm_audio(matroska, track, st, data,
2090  lace_size[n],
2091  timecode, duration, pos);
2092  if (res)
2093  goto end;
2094 
2095  } else {
2096  res = matroska_parse_frame(matroska, track, st, data, lace_size[n],
2097  timecode, duration,
2098  pos, !n? is_keyframe : 0);
2099  if (res)
2100  goto end;
2101  }
2102 
2103  if (timecode != AV_NOPTS_VALUE)
2104  timecode = duration ? timecode + duration : AV_NOPTS_VALUE;
2105  data += lace_size[n];
2106  }
2107 
2108 end:
2109  av_free(lace_size);
2110  return res;
2111 }
2112 
2114 {
2115  EbmlList *blocks_list;
2116  MatroskaBlock *blocks;
2117  int i, res;
2118  res = ebml_parse(matroska,
2119  matroska_cluster_incremental_parsing,
2120  &matroska->current_cluster);
2121  if (res == 1) {
2122  /* New Cluster */
2123  if (matroska->current_cluster_pos)
2124  ebml_level_end(matroska);
2125  ebml_free(matroska_cluster, &matroska->current_cluster);
2126  memset(&matroska->current_cluster, 0, sizeof(MatroskaCluster));
2127  matroska->current_cluster_num_blocks = 0;
2128  matroska->current_cluster_pos = avio_tell(matroska->ctx->pb);
2129  matroska->prev_pkt = NULL;
2130  /* sizeof the ID which was already read */
2131  if (matroska->current_id)
2132  matroska->current_cluster_pos -= 4;
2133  res = ebml_parse(matroska,
2134  matroska_clusters_incremental,
2135  &matroska->current_cluster);
2136  /* Try parsing the block again. */
2137  if (res == 1)
2138  res = ebml_parse(matroska,
2139  matroska_cluster_incremental_parsing,
2140  &matroska->current_cluster);
2141  }
2142 
2143  if (!res &&
2144  matroska->current_cluster_num_blocks <
2145  matroska->current_cluster.blocks.nb_elem) {
2146  blocks_list = &matroska->current_cluster.blocks;
2147  blocks = blocks_list->elem;
2148 
2149  matroska->current_cluster_num_blocks = blocks_list->nb_elem;
2150  i = blocks_list->nb_elem - 1;
2151  if (blocks[i].bin.size > 0 && blocks[i].bin.data) {
2152  int is_keyframe = blocks[i].non_simple ? !blocks[i].reference : -1;
2153  if (!blocks[i].non_simple)
2154  blocks[i].duration = AV_NOPTS_VALUE;
2155  res = matroska_parse_block(matroska,
2156  blocks[i].bin.data, blocks[i].bin.size,
2157  blocks[i].bin.pos,
2158  matroska->current_cluster.timecode,
2159  blocks[i].duration, is_keyframe,
2160  matroska->current_cluster_pos);
2161  }
2162  }
2163 
2164  if (res < 0) matroska->done = 1;
2165  return res;
2166 }
2167 
2169 {
2170  MatroskaCluster cluster = { 0 };
2171  EbmlList *blocks_list;
2172  MatroskaBlock *blocks;
2173  int i, res;
2174  int64_t pos;
2175  if (!matroska->contains_ssa)
2176  return matroska_parse_cluster_incremental(matroska);
2177  pos = avio_tell(matroska->ctx->pb);
2178  matroska->prev_pkt = NULL;
2179  if (matroska->current_id)
2180  pos -= 4; /* sizeof the ID which was already read */
2181  res = ebml_parse(matroska, matroska_clusters, &cluster);
2182  blocks_list = &cluster.blocks;
2183  blocks = blocks_list->elem;
2184  for (i=0; i<blocks_list->nb_elem && !res; i++)
2185  if (blocks[i].bin.size > 0 && blocks[i].bin.data) {
2186  int is_keyframe = blocks[i].non_simple ? !blocks[i].reference : -1;
2187  if (!blocks[i].non_simple)
2188  blocks[i].duration = AV_NOPTS_VALUE;
2189  res=matroska_parse_block(matroska,
2190  blocks[i].bin.data, blocks[i].bin.size,
2191  blocks[i].bin.pos, cluster.timecode,
2192  blocks[i].duration, is_keyframe,
2193  pos);
2194  }
2195  ebml_free(matroska_cluster, &cluster);
2196  if (res < 0) matroska->done = 1;
2197  return res;
2198 }
2199 
2201 {
2202  MatroskaDemuxContext *matroska = s->priv_data;
2203  int ret = 0;
2204 
2205  while (!ret && matroska_deliver_packet(matroska, pkt)) {
2206  if (matroska->done)
2207  return AVERROR_EOF;
2208  ret = matroska_parse_cluster(matroska);
2209  }
2210 
2211  if (ret == AVERROR_INVALIDDATA && pkt->data) {
2212  pkt->flags |= AV_PKT_FLAG_CORRUPT;
2213  return 0;
2214  }
2215 
2216  return ret;
2217 }
2218 
2219 static int matroska_read_seek(AVFormatContext *s, int stream_index,
2220  int64_t timestamp, int flags)
2221 {
2222  MatroskaDemuxContext *matroska = s->priv_data;
2223  MatroskaTrack *tracks = matroska->tracks.elem;
2224  AVStream *st = s->streams[stream_index];
2225  int i, index, index_sub, index_min;
2226 
2227  /* Parse the CUES now since we need the index data to seek. */
2228  if (matroska->cues_parsing_deferred) {
2229  matroska_parse_cues(matroska);
2230  matroska->cues_parsing_deferred = 0;
2231  }
2232 
2233  if (!st->nb_index_entries)
2234  return 0;
2235  timestamp = FFMAX(timestamp, st->index_entries[0].timestamp);
2236 
2237  if ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
2238  avio_seek(s->pb, st->index_entries[st->nb_index_entries-1].pos, SEEK_SET);
2239  matroska->current_id = 0;
2240  while ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
2241  matroska_clear_queue(matroska);
2242  if (matroska_parse_cluster(matroska) < 0)
2243  break;
2244  }
2245  }
2246 
2247  matroska_clear_queue(matroska);
2248  if (index < 0)
2249  return 0;
2250 
2251  index_min = index;
2252  for (i=0; i < matroska->tracks.nb_elem; i++) {
2253  tracks[i].audio.pkt_cnt = 0;
2254  tracks[i].audio.sub_packet_cnt = 0;
2255  tracks[i].audio.buf_timecode = AV_NOPTS_VALUE;
2256  tracks[i].end_timecode = 0;
2257  if (tracks[i].type == MATROSKA_TRACK_TYPE_SUBTITLE
2258  && !tracks[i].stream->discard != AVDISCARD_ALL) {
2259  index_sub = av_index_search_timestamp(tracks[i].stream, st->index_entries[index].timestamp, AVSEEK_FLAG_BACKWARD);
2260  if (index_sub >= 0
2261  && st->index_entries[index_sub].pos < st->index_entries[index_min].pos
2262  && st->index_entries[index].timestamp - st->index_entries[index_sub].timestamp < 30000000000/matroska->time_scale)
2263  index_min = index_sub;
2264  }
2265  }
2266 
2267  avio_seek(s->pb, st->index_entries[index_min].pos, SEEK_SET);
2268  matroska->current_id = 0;
2269  matroska->skip_to_keyframe = !(flags & AVSEEK_FLAG_ANY);
2270  matroska->skip_to_timecode = st->index_entries[index].timestamp;
2271  matroska->done = 0;
2272  ff_update_cur_dts(s, st, st->index_entries[index].timestamp);
2273  return 0;
2274 }
2275 
2277 {
2278  MatroskaDemuxContext *matroska = s->priv_data;
2279  MatroskaTrack *tracks = matroska->tracks.elem;
2280  int n;
2281 
2282  matroska_clear_queue(matroska);
2283 
2284  for (n=0; n < matroska->tracks.nb_elem; n++)
2285  if (tracks[n].type == MATROSKA_TRACK_TYPE_AUDIO)
2286  av_free(tracks[n].audio.buf);
2287  ebml_free(matroska_cluster, &matroska->current_cluster);
2288  ebml_free(matroska_segment, matroska);
2289 
2290  return 0;
2291 }
2292 
2294  .name = "matroska,webm",
2295  .long_name = NULL_IF_CONFIG_SMALL("Matroska / WebM"),
2296  .priv_data_size = sizeof(MatroskaDemuxContext),
2302 };
const char * s
Definition: matroskadec.c:75
static EbmlSyntax matroska_simpletag[]
Definition: matroskadec.c:440
void * av_malloc(size_t size)
Allocate a block of size bytes with alignment suitable for all memory accesses (including vectors if ...
Definition: mem.c:61
#define MATROSKA_ID_TRACKDEFAULTDURATION
Definition: matroska.h:97
void avio_wl16(AVIOContext *s, unsigned int val)
Definition: aviobuf.c:336
static int matroska_parse_seekhead_entry(MatroskaDemuxContext *matroska, int idx)
Definition: matroskadec.c:1219
Bytestream IO Context.
Definition: avio.h:68
#define MATROSKA_ID_VIDEOFLAGINTERLACED
Definition: matroska.h:114
static void matroska_convert_tags(AVFormatContext *s)
Definition: matroskadec.c:1185
#define MATROSKA_ID_DATEUTC
Definition: matroska.h:71
int size
void av_free_packet(AVPacket *pkt)
Free a packet.
Definition: avpacket.c:153
uint64_t type
Definition: matroskadec.c:139
#define MATROSKA_ID_TRACKFLAGLACING
Definition: matroska.h:94
#define MATROSKA_ID_TRACKENTRY
Definition: matroska.h:75
static int matroska_deliver_packet(MatroskaDemuxContext *matroska, AVPacket *pkt)
Definition: matroskadec.c:1722
#define MATROSKA_ID_VIDEODISPLAYHEIGHT
Definition: matroska.h:106
uint64_t version
Definition: matroskadec.c:92
AVInputFormat ff_matroska_demuxer
Definition: matroskadec.c:2293
int av_add_index_entry(AVStream *st, int64_t pos, int64_t timestamp, int size, int distance, int flags)
Add an index entry into a sorted list.
Definition: utils.c:1396
enum AVCodecID id
Definition: mxfenc.c:85
#define MATROSKA_ID_CUETRACKPOSITION
Definition: matroska.h:139
enum AVCodecID ff_codec_get_id(const AVCodecTag *tags, unsigned int tag)
Definition: utils.c:2129
#define MATROSKA_ID_CODECPRIVATE
Definition: matroska.h:84
const unsigned char ff_sipr_subpk_size[4]
Definition: rmsipr.c:25
#define MATROSKA_ID_TAGTARGETS_TYPE
Definition: matroska.h:155
static int ebml_level_end(MatroskaDemuxContext *matroska)
Definition: matroskadec.c:562
int64_t pos
byte position in stream, -1 if unknown
Definition: avcodec.h:940
static int matroska_ebmlnum_sint(MatroskaDemuxContext *matroska, uint8_t *data, uint32_t size, int64_t *num)
Definition: matroskadec.c:758
void avpriv_set_pts_info(AVStream *s, int pts_wrap_bits, unsigned int pts_num, unsigned int pts_den)
Set the time base and wrapping info for a given stream.
Definition: utils.c:3286
int64_t pos
Definition: avformat.h:583
#define MATROSKA_ID_ENCODINGTYPE
Definition: matroska.h:129
#define MATROSKA_ID_AUDIOBITDEPTH
Definition: matroska.h:123
uint64_t chapteruid
Definition: matroskadec.c:197
static av_always_inline float av_int2float(uint32_t i)
Reinterpret a 32-bit integer as a float.
Definition: intfloat.h:40
#define MATROSKA_ID_TRACKFLAGDEFAULT
Definition: matroska.h:92
EbmlList tag
Definition: matroskadec.c:203
#define CONFIG_ZLIB
Definition: config.h:326
uint64_t uid
Definition: matroskadec.c:138
static EbmlSyntax matroska_segments[]
Definition: matroskadec.c:493
static int read_seek(AVFormatContext *ctx, int stream_index, int64_t timestamp, int flags)
Definition: libcdio.c:153
MatroskaCluster current_cluster
Definition: matroskadec.c:259
AVRational sample_aspect_ratio
sample aspect ratio (0 if unknown)
Definition: avformat.h:697
#define MATROSKA_ID_TAGTARGETS_ATTACHUID
Definition: matroska.h:159
int num
numerator
Definition: rational.h:44
int index
stream index in AVFormatContext
Definition: avformat.h:623
int size
Definition: avcodec.h:916
#define MATROSKA_ID_CLUSTERPOSITION
Definition: matroska.h:170
int64_t avio_seek(AVIOContext *s, int64_t offset, int whence)
fseek() equivalent for AVIOContext.
Definition: aviobuf.c:186
#define MATROSKA_ID_FILEDATA
Definition: matroska.h:185
AVIndexEntry * index_entries
Only used if the format does not support seeking natively.
Definition: avformat.h:786
#define EBML_ID_DOCTYPEREADVERSION
Definition: matroska.h:42
#define MATROSKA_ID_BLOCKREFERENCE
Definition: matroska.h:178
uint64_t flag_forced
Definition: matroskadec.c:147
uint64_t max_size
Definition: matroskadec.c:93
#define MATROSKA_ID_TRACKTYPE
Definition: matroska.h:80
#define MATROSKA_ID_TAGTARGETS_CHAPTERUID
Definition: matroska.h:158
uint64_t flag_default
Definition: matroskadec.c:146
#define MATROSKA_ID_VIDEOASPECTRATIO
Definition: matroska.h:116
#define MATROSKA_ID_MUXINGAPP
Definition: matroska.h:70
#define MATROSKA_ID_AUDIOCHANNELS
Definition: matroska.h:124
char * name
Definition: matroskadec.c:186
discard all
Definition: avcodec.h:536
MatroskaLevel levels[EBML_MAX_DEPTH]
Definition: matroskadec.c:226
static EbmlSyntax matroska_track_audio[]
Definition: matroskadec.c:317
#define MATROSKA_ID_CUECLUSTERPOSITION
Definition: matroska.h:143
unsigned int avio_rb16(AVIOContext *s)
Definition: aviobuf.c:562
MatroskaTrackAudio audio
Definition: matroskadec.c:149
uint64_t duration
Definition: matroskadec.c:266
const struct EbmlSyntax * n
Definition: matroskadec.c:76
#define CONFIG_LZO
Definition: config.h:304
#define MATROSKA_ID_EDITIONFLAGDEFAULT
Definition: matroska.h:198
#define MATROSKA_ID_CLUSTERTIMECODE
Definition: matroska.h:169
#define EBML_ID_DOCTYPE
Definition: matroska.h:40
int block_align
number of bytes per packet if constant and known or 0 Used by some WAV based audio codecs...
Definition: avcodec.h:2141
static EbmlSyntax matroska_tag[]
Definition: matroskadec.c:459
static EbmlSyntax matroska_attachment[]
Definition: matroskadec.c:376
#define MATROSKA_ID_CHAPTERTIMEEND
Definition: matroska.h:192
static int64_t duration
Definition: avplay.c:249
static EbmlSyntax matroska_track[]
Definition: matroskadec.c:344
#define MATROSKA_ID_TRACKCONTENTENCODINGS
Definition: matroska.h:98
void av_freep(void *arg)
Free a memory block which has been allocated with av_malloc(z)() or av_realloc() and set the pointer ...
Definition: mem.c:151
#define AV_LZO_OUTPUT_FULL
decoded data did not fit into output buffer
Definition: lzo.h:39
AVChapter * avpriv_new_chapter(AVFormatContext *s, int id, AVRational time_base, int64_t start, int64_t end, const char *title)
Add a new chapter.
Definition: utils.c:2818
#define EBML_VERSION
Definition: matroska.h:30
#define MATROSKA_ID_FILEDESC
Definition: matroska.h:182
Format I/O context.
Definition: avformat.h:828
#define EBML_ID_CRC32
Definition: matroska.h:46
uint64_t def
Definition: matroskadec.c:189
void ff_update_cur_dts(AVFormatContext *s, AVStream *ref_st, int64_t timestamp)
Update cur_dts of all streams based on the given timestamp and AVStream.
Definition: utils.c:1324
#define MATROSKA_ID_TRACKCONTENTENCODING
Definition: matroska.h:99
#define MATROSKA_ID_CODECDOWNLOADURL
Definition: matroska.h:87
int64_t end_timecode
Definition: matroskadec.c:153
Public dictionary API.
uint64_t pixel_height
Definition: matroskadec.c:115
void avio_wl32(AVIOContext *s, unsigned int val)
Definition: aviobuf.c:260
static av_always_inline double av_int2double(uint64_t i)
Reinterpret a 64-bit integer as a double.
Definition: intfloat.h:60
uint8_t
#define MATROSKA_ID_CHAPLANG
Definition: matroska.h:195
MatroskaTrackVideo video
Definition: matroskadec.c:148
#define MATROSKA_ID_EDITIONFLAGORDERED
Definition: matroska.h:199
void * elem
Definition: matroskadec.c:82
#define MATROSKA_ID_TRACKLANGUAGE
Definition: matroska.h:90
#define AV_WB32(p, d)
Definition: intreadwrite.h:239
MatroskaTrackCompression compression
Definition: matroskadec.c:107
uint8_t * data
Definition: matroskadec.c:87
const AVCodecTag ff_codec_movvideo_tags[]
Definition: isom.c:68
unsigned int avio_rb32(AVIOContext *s)
Definition: aviobuf.c:577
uint64_t time
Definition: matroskadec.c:181
#define AV_RB32
Definition: intreadwrite.h:130
#define MATROSKA_ID_VIDEOPIXELCROPT
Definition: matroska.h:110
#define MATROSKA_ID_TIMECODESCALE
Definition: matroska.h:66
static int matroska_aac_sri(int samplerate)
Definition: matroskadec.c:1344
enum AVStreamParseType need_parsing
Definition: avformat.h:775
#define b
Definition: input.c:52
union EbmlSyntax::@92 def
#define MATROSKA_ID_SIMPLEBLOCK
Definition: matroska.h:173
#define MATROSKA_ID_TAGTARGETS_TYPEVALUE
Definition: matroska.h:156
#define MATROSKA_ID_EDITIONFLAGHIDDEN
Definition: matroska.h:197
#define AV_LZO_OUTPUT_PADDING
Definition: lzo.h:47
static EbmlSyntax matroska_cluster[]
Definition: matroskadec.c:507
uint8_t * extradata
some codecs need / can use extradata like Huffman tables.
Definition: avcodec.h:1454
const char * name
#define MATROSKA_ID_CODECNAME
Definition: matroska.h:85
char * language
Definition: matroskadec.c:143
AVStream ** streams
Definition: avformat.h:876
static int matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data, int size, int64_t pos, uint64_t cluster_time, uint64_t block_duration, int is_keyframe, int64_t cluster_pos)
Definition: matroskadec.c:2006
#define MATROSKA_ID_AUDIOOUTSAMPLINGFREQ
Definition: matroska.h:121
const char data[16]
Definition: mxf.c:66
uint8_t * data
Definition: avcodec.h:915
uint64_t typevalue
Definition: matroskadec.c:195
static int matroska_parse_cluster_incremental(MatroskaDemuxContext *matroska)
Definition: matroskadec.c:2113
#define MATROSKA_ID_VIDEODISPLAYWIDTH
Definition: matroska.h:105
#define MATROSKA_ID_EDITIONUID
Definition: matroska.h:196
static int flags
Definition: log.c:42
uint32_t tag
Definition: movenc.c:802
static EbmlSyntax ebml_header[]
Definition: matroskadec.c:272
#define MATROSKA_ID_CODECDECODEALL
Definition: matroska.h:88
enum AVCodecID id
Definition: internal.h:42
static av_cold int read_close(AVFormatContext *ctx)
Definition: libcdio.c:145
const uint8_t ff_log2_tab[256]
Definition: log2_tab.c:21
static void matroska_fix_ass_packet(MatroskaDemuxContext *matroska, AVPacket *pkt, uint64_t display_duration)
Definition: matroskadec.c:1107
#define MATROSKA_ID_CUES
Definition: matroska.h:58
#define EBML_MAX_DEPTH
Definition: matroska.h:250
uint64_t avio_rb64(AVIOContext *s)
Definition: aviobuf.c:642
static av_always_inline int64_t avio_tell(AVIOContext *s)
ftell() equivalent for AVIOContext.
Definition: avio.h:219
#define MATROSKA_ID_TRACKNUMBER
Definition: matroska.h:78
void avio_write(AVIOContext *s, const unsigned char *buf, int size)
Definition: aviobuf.c:165
int duration
Duration of this packet in AVStream->time_base units, 0 if unknown.
Definition: avcodec.h:937
#define MATROSKA_ID_SEGMENTUID
Definition: matroska.h:72
int avio_read(AVIOContext *s, unsigned char *buf, int size)
Read size bytes from AVIOContext into buf.
Definition: aviobuf.c:446
static EbmlSyntax matroska_tracks[]
Definition: matroskadec.c:371
EbmlList sub
Definition: matroskadec.c:190
#define r
Definition: input.c:51
static int matroska_parse_cluster(MatroskaDemuxContext *matroska)
Definition: matroskadec.c:2168
static int ebml_parse_nest(MatroskaDemuxContext *matroska, EbmlSyntax *syntax, void *data)
Definition: matroskadec.c:809
#define MATROSKA_ID_CUEBLOCKNUMBER
Definition: matroska.h:144
#define MATROSKA_ID_TRACKUID
Definition: matroska.h:79
uint64_t display_height
Definition: matroskadec.c:113
static EbmlSyntax matroska_info[]
Definition: matroskadec.c:288
#define MATROSKA_ID_ENCODINGORDER
Definition: matroska.h:127
#define MATROSKA_ID_VIDEOSTEREOMODE
Definition: matroska.h:115
int av_new_packet(AVPacket *pkt, int size)
Allocate the payload of a packet and initialize its fields with default values.
Definition: avpacket.c:56
void ff_metadata_conv(AVDictionary **pm, const AVMetadataConv *d_conv, const AVMetadataConv *s_conv)
Definition: metadata.c:26
EbmlType type
Definition: matroskadec.c:69
AVCodecID
Identify the syntax and semantics of the bitstream.
Definition: avcodec.h:95
AVDictionary * metadata
Definition: avformat.h:972
void av_free(void *ptr)
Free a memory block which has been allocated with av_malloc(z)() or av_realloc(). ...
Definition: mem.c:139
#define MATROSKA_ID_BLOCKDURATION
Definition: matroska.h:177
#define EBML_ID_EBMLREADVERSION
Definition: matroska.h:37
int av_index_search_timestamp(AVStream *st, int64_t timestamp, int flags)
Get the index for a specific timestamp.
Definition: utils.c:1438
static int ebml_read_length(MatroskaDemuxContext *matroska, AVIOContext *pb, uint64_t *number)
Read a EBML length value.
Definition: matroskadec.c:631
#define AV_RB16
Definition: intreadwrite.h:53
AVChapter * chapter
Definition: matroskadec.c:172
static EbmlSyntax matroska_index[]
Definition: matroskadec.c:435
int ff_get_wav_header(AVIOContext *pb, AVCodecContext *codec, int size)
int64_t timestamp
Definition: avformat.h:584
#define MATROSKA_ID_CLUSTER
Definition: matroska.h:62
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification. ...
Definition: internal.h:88
#define MATROSKA_ID_FILEMIMETYPE
Definition: matroska.h:184
static int matroska_ebmlnum_uint(MatroskaDemuxContext *matroska, uint8_t *data, uint32_t size, uint64_t *num)
Definition: matroskadec.c:747
int64_t convergence_duration
Time difference in AVStream->time_base units from the pts of this packet to the point at which the ou...
Definition: avcodec.h:959
uint64_t display_width
Definition: matroskadec.c:112
#define MATROSKA_ID_WRITINGAPP
Definition: matroska.h:69
static int matroska_parse_rm_audio(MatroskaDemuxContext *matroska, MatroskaTrack *track, AVStream *st, uint8_t *data, int size, uint64_t timecode, uint64_t duration, int64_t pos)
Definition: matroskadec.c:1871
#define MATROSKA_ID_TAGDEFAULT_BUG
Definition: matroska.h:153
Definition: graph2dot.c:48
static EbmlSyntax matroska_clusters[]
Definition: matroskadec.c:516
static EbmlSyntax matroska_chapter[]
Definition: matroskadec.c:408
enum AVCodecID id
Definition: matroska.h:246
#define MATROSKA_ID_VIDEOPIXELCROPR
Definition: matroska.h:112
void av_log(void *avcl, int level, const char *fmt,...)
Definition: log.c:146
AVStream * avformat_new_stream(AVFormatContext *s, AVCodec *c)
Add a new stream to a media file.
Definition: utils.c:2739
#define MATROSKA_ID_ENCODINGCOMPSETTINGS
Definition: matroska.h:132
#define EBML_ID_EBMLMAXIDLENGTH
Definition: matroska.h:38
#define MATROSKA_ID_CHAPTERFLAGHIDDEN
Definition: matroska.h:201
enum AVCodecID codec_id
Definition: mov_chan.c:432
AVRational avg_frame_rate
Average framerate.
Definition: avformat.h:704
uint64_t timecode
Definition: matroskadec.c:217
size_t av_strlcpy(char *dst, const char *src, size_t size)
Copy the string src to dst, but no more than size - 1 bytes, and null-terminate dst.
Definition: avstring.c:67
static EbmlSyntax matroska_attachments[]
Definition: matroskadec.c:385
int flags
A combination of AV_PKT_FLAG values.
Definition: avcodec.h:921
static EbmlSyntax matroska_cluster_incremental_parsing[]
Definition: matroskadec.c:525
Only parse headers, do not repack.
Definition: avformat.h:577
int avio_r8(AVIOContext *s)
Definition: aviobuf.c:437
AVCodecContext * codec
Codec context associated with this stream.
Definition: avformat.h:641
static void ebml_free(EbmlSyntax *syntax, void *data)
Definition: matroskadec.c:899
const CodecMime ff_mkv_mime_tags[]
Definition: matroska.c:87
int nb_elem
Definition: matroskadec.c:81
#define MATROSKA_ID_TAG
Definition: matroska.h:147
int av_reduce(int *dst_num, int *dst_den, int64_t num, int64_t den, int64_t max)
Reduce a fraction.
Definition: rational.c:36
int buf_size
Size of buf except extra allocated bytes.
Definition: avformat.h:341
unsigned char * buf
Buffer must have AVPROBE_PADDING_SIZE of extra allocated bytes filled with zero.
Definition: avformat.h:340
char * lang
Definition: matroskadec.c:188
static EbmlSyntax matroska_chapters[]
Definition: matroskadec.c:417
uint64_t skip_to_timecode
Definition: matroskadec.c:252
Definition: dct-test.c:67
static int matroska_read_header(AVFormatContext *s)
Definition: matroskadec.c:1354
static void matroska_parse_cues(MatroskaDemuxContext *matroska)
Definition: matroskadec.c:1297
int seekable
A combination of AVIO_SEEKABLE_ flags or 0 when the stream is not seekable.
Definition: avio.h:117
int bit_rate
the average bitrate
Definition: avcodec.h:1404
static void matroska_execute_seekhead(MatroskaDemuxContext *matroska)
Definition: matroskadec.c:1270
#define dynarray_add(tab, nb_ptr, elem)
Definition: internal.h:56
uint64_t start
Definition: matroskadec.c:167
#define EBML_ID_EBMLVERSION
Definition: matroska.h:36
#define MATROSKA_ID_TAGTARGETS
Definition: matroska.h:154
const AVCodecTag ff_codec_bmp_tags[]
Definition: riff.c:31
AVPacket ** packets
Definition: matroskadec.c:244
#define MATROSKA_ID_TAGNAME
Definition: matroska.h:149
#define MATROSKA_ID_TRACKTIMECODESCALE
Definition: matroska.h:100
static int read_probe(AVProbeData *pd)
Definition: jvdec.c:54
#define CONFIG_BZLIB
Definition: config.h:267
static int ebml_parse_elem(MatroskaDemuxContext *matroska, EbmlSyntax *syntax, void *data)
Definition: matroskadec.c:834
static int ebml_read_num(MatroskaDemuxContext *matroska, AVIOContext *pb, int max_size, uint64_t *number)
Definition: matroskadec.c:585
int width
picture width / height.
Definition: avcodec.h:1508
#define MATROSKA_ID_CHAPTERFLAGENABLED
Definition: matroska.h:202
uint64_t id_length
Definition: matroskadec.c:94
static EbmlSyntax matroska_track_encodings[]
Definition: matroskadec.c:339
static MatroskaTrack * matroska_find_track_by_num(MatroskaDemuxContext *matroska, int num)
Definition: matroskadec.c:968
static av_always_inline int64_t avio_skip(AVIOContext *s, int64_t offset)
Skip given number of bytes forward.
Definition: avio.h:210
#define MATROSKA_ID_SIMPLETAG
Definition: matroska.h:148
uint64_t doctype_version
Definition: matroskadec.c:96
internal header for RIFF based (de)muxers do NOT include this in end user applications ...
static EbmlSyntax matroska_track_encoding[]
Definition: matroskadec.c:331
#define MATROSKA_ID_TRACKMAXCACHE
Definition: matroska.h:96
int data_offset
Definition: matroskadec.c:71
#define MATROSKA_ID_CHAPTERPHYSEQUIV
Definition: matroska.h:203
static int matroska_read_close(AVFormatContext *s)
Definition: matroskadec.c:2276
EbmlBin codec_priv
Definition: matroskadec.c:142
static int ebml_read_ascii(AVIOContext *pb, int size, char **str)
Definition: matroskadec.c:681
static int matroska_decode_buffer(uint8_t **buf, int *buf_size, MatroskaTrack *track)
Definition: matroskadec.c:982
#define MATROSKA_ID_CHAPTERATOM
Definition: matroska.h:190
#define AV_RL32
Definition: intreadwrite.h:146
int av_lzo1x_decode(void *out, int *outlen, const void *in, int *inlen)
Decodes LZO 1x compressed data.
Definition: lzo.c:126
AVDictionary * metadata
Definition: avformat.h:699
Opaque data information usually sparse.
Definition: avutil.h:183
#define MATROSKA_ID_VIDEOCOLORSPACE
Definition: matroska.h:117
static EbmlSyntax matroska_segment[]
Definition: matroskadec.c:481
#define MATROSKA_ID_CHAPTERS
Definition: matroska.h:63
static int matroska_probe(AVProbeData *p)
Definition: matroskadec.c:926
#define EBML_ID_VOID
Definition: matroska.h:45
static void matroska_convert_tag(AVFormatContext *s, EbmlList *list, AVDictionary **metadata, char *prefix)
Definition: matroskadec.c:1152
#define MATROSKA_ID_AUDIOSAMPLINGFREQ
Definition: matroska.h:120
double f
Definition: matroskadec.c:74
#define MATROSKA_ID_TRACKMINCACHE
Definition: matroska.h:95
static int read_header(FFV1Context *f)
Definition: ffv1dec.c:536
static int matroska_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
Definition: matroskadec.c:2219
static EbmlSyntax matroska_seekhead[]
Definition: matroskadec.c:476
Stream structure.
Definition: avformat.h:622
NULL
Definition: eval.c:52
EbmlList encodings
Definition: matroskadec.c:150
char * codec_id
Definition: matroskadec.c:141
static int width
Definition: utils.c:156
int64_t current_cluster_pos
Definition: matroskadec.c:258
#define MATROSKA_ID_VIDEOPIXELCROPB
Definition: matroska.h:109
#define MATROSKA_ID_TRACKFLAGFORCED
Definition: matroska.h:93
#define MATROSKA_ID_TAGS
Definition: matroska.h:59
enum AVMediaType codec_type
Definition: avcodec.h:1347
version
Definition: ffv1enc.c:1069
static int ebml_read_master(MatroskaDemuxContext *matroska, uint64_t length)
Definition: matroskadec.c:725
enum AVCodecID codec_id
Definition: avcodec.h:1350
#define MATROSKA_ID_TAGDEFAULT
Definition: matroska.h:152
#define MATROSKA_ID_SEEKID
Definition: matroska.h:165
char * av_strdup(const char *s)
Duplicate the string s.
Definition: mem.c:166
int sample_rate
samples per second
Definition: avcodec.h:2104
AVIOContext * pb
I/O context.
Definition: avformat.h:861
#define MATROSKA_ID_ENCODINGCOMPALGO
Definition: matroska.h:131
#define MATROSKA_ID_BLOCK
Definition: matroska.h:176
#define MATROSKA_ID_INFO
Definition: matroska.h:56
#define MATROSKA_ID_TAGTARGETS_TRACKUID
Definition: matroska.h:157
#define MATROSKA_ID_TAGLANG
Definition: matroska.h:151
static EbmlSyntax matroska_tags[]
Definition: matroskadec.c:465
uint64_t pixel_width
Definition: matroskadec.c:114
unsigned int codec_tag
fourcc (LSB first, so "ABCD" -> ('D'<<24) + ('C'<<16) + ('B'<<8) + 'A').
Definition: avcodec.h:1365
#define MATROSKA_ID_TRACKFLAGENABLED
Definition: matroska.h:91
#define MATROSKA_ID_TRACKS
Definition: matroska.h:57
int extradata_size
Definition: avcodec.h:1455
#define MATROSKA_ID_TRACKNAME
Definition: matroska.h:89
static int read_packet(AVFormatContext *ctx, AVPacket *pkt)
Definition: libcdio.c:114
uint64_t start
Definition: matroskadec.c:212
int av_dict_set(AVDictionary **pm, const char *key, const char *value, int flags)
Set the given entry in *pm, overwriting an existing entry.
Definition: dict.c:63
static EbmlSyntax matroska_cluster_incremental[]
Definition: matroskadec.c:539
int nb_index_entries
Definition: avformat.h:788
#define MATROSKA_ID_SEEKENTRY
Definition: matroska.h:162
EbmlList pos
Definition: matroskadec.c:182
uint64_t u
Definition: matroskadec.c:73
#define MATROSKA_ID_EDITIONENTRY
Definition: matroska.h:189
int index
Definition: gxfenc.c:72
#define MATROSKA_ID_BLOCKGROUP
Definition: matroska.h:172
#define MATROSKA_ID_VIDEOPIXELHEIGHT
Definition: matroska.h:108
rational number numerator/denominator
Definition: rational.h:43
AVStream * stream
Definition: matroskadec.c:152
static int matroska_parse_laces(MatroskaDemuxContext *matroska, uint8_t **buf, int *buf_size, int type, uint32_t **lace_buf, int *laces)
Definition: matroskadec.c:1764
#define MATROSKA_ID_CUETIME
Definition: matroska.h:138
static int matroska_read_packet(AVFormatContext *s, AVPacket *pkt)
Definition: matroskadec.c:2200
static EbmlSyntax matroska_blockgroup[]
Definition: matroskadec.c:498
static int ebml_parse(MatroskaDemuxContext *matroska, EbmlSyntax *syntax, void *data)
Definition: matroskadec.c:796
#define MATROSKA_ID_TITLE
Definition: matroska.h:68
AVFormatContext * ctx
Definition: matroskadec.c:222
#define MATROSKA_ID_TRACKVIDEO
Definition: matroska.h:82
int size
Definition: matroskadec.c:86
int error
contains the error code or 0 if no error happened
Definition: avio.h:102
This structure contains the data a format has to probe a file.
Definition: avformat.h:338
static int ebml_parse_id(MatroskaDemuxContext *matroska, EbmlSyntax *syntax, uint32_t id, void *data)
Definition: matroskadec.c:777
int list_elem_size
Definition: matroskadec.c:70
static EbmlSyntax ebml_syntax[]
Definition: matroskadec.c:283
size_t av_strlcat(char *dst, const char *src, size_t size)
Append the string src to the string dst, but to a total length of no more than size - 1 bytes...
Definition: avstring.c:77
#define MATROSKA_ID_VIDEOFRAMERATE
Definition: matroska.h:104
#define MATROSKA_ID_ATTACHMENTS
Definition: matroska.h:61
int64_t pos
Definition: matroskadec.c:88
#define MATROSKA_ID_CHAPTERDISPLAY
Definition: matroska.h:193
uint8_t level
Definition: svq3.c:125
#define MATROSKA_ID_FILENAME
Definition: matroska.h:183
const int avpriv_mpeg4audio_sample_rates[16]
Definition: mpeg4audio.c:55
const AVMetadataConv ff_mkv_metadata_conv[]
Definition: matroska.c:99
#define MATROSKA_ID_CODECID
Definition: matroska.h:83
static EbmlSyntax matroska_clusters_incremental[]
Definition: matroskadec.c:548
int64_t reference
Definition: matroskadec.c:267
void ff_rm_reorder_sipr_data(uint8_t *buf, int sub_packet_h, int framesize)
Perform 4-bit block reordering for SIPR data.
Definition: rmsipr.c:41
Main libavformat public API header.
uint64_t buf_timecode
Definition: matroskadec.c:132
uint64_t num
Definition: matroskadec.c:137
const struct EbmlSyntax EbmlSyntax
#define MATROSKA_ID_CUETRACK
Definition: matroska.h:142
static EbmlSyntax matroska_track_encoding_compression[]
Definition: matroskadec.c:325
EbmlType
Definition: matroskadec.c:54
#define MATROSKA_ID_SEEKPOSITION
Definition: matroska.h:166
#define MATROSKA_ID_CHAPTERTIMESTART
Definition: matroska.h:191
double time_scale
Definition: matroskadec.c:144
int ffio_init_context(AVIOContext *s, unsigned char *buffer, int buffer_size, int write_flag, void *opaque, int(*read_packet)(void *opaque, uint8_t *buf, int buf_size), int(*write_packet)(void *opaque, uint8_t *buf, int buf_size), int64_t(*seek)(void *opaque, int64_t offset, int whence))
Definition: aviobuf.c:70
void * av_realloc(void *ptr, size_t size)
Allocate or reallocate a block of memory.
Definition: mem.c:116
raw UTF-8 text
Definition: avcodec.h:416
char * string
Definition: matroskadec.c:187
int64_t start_time
Decoding: pts of the first frame of the stream, in stream time base.
Definition: avformat.h:677
int error_recognition
Error recognition; higher values will detect more errors but may misdetect some more or less valid pa...
Definition: avformat.h:994
int disposition
AV_DISPOSITION_* bit field.
Definition: avformat.h:688
char * doctype
Definition: matroskadec.c:95
static EbmlSyntax matroska_seekhead_entry[]
Definition: matroskadec.c:470
int av_grow_packet(AVPacket *pkt, int grow_by)
Increase packet size, correctly zeroing padding.
Definition: avpacket.c:83
int den
denominator
Definition: rational.h:45
#define MATROSKA_ID_SEGMENT
Definition: matroska.h:53
uint32_t id
Definition: matroskadec.c:68
static EbmlSyntax matroska_tagtargets[]
Definition: matroskadec.c:450
MatroskaTagTarget target
Definition: matroskadec.c:202
#define MATROSKA_ID_SEEKHEAD
Definition: matroska.h:60
#define EBML_ID_HEADER
Definition: matroska.h:33
#define MATROSKA_ID_ENCODINGCOMPRESSION
Definition: matroska.h:130
#define MATROSKA_ID_CLUSTERPREVSIZE
Definition: matroska.h:171
int eof_reached
true if eof reached
Definition: avio.h:96
#define MATROSKA_ID_POINTENTRY
Definition: matroska.h:135
int len
int channels
number of audio channels
Definition: avcodec.h:2105
#define MATROSKA_ID_FILEUID
Definition: matroska.h:186
#define MATROSKA_ID_VIDEOPIXELCROPL
Definition: matroska.h:111
void * priv_data
Format private data.
Definition: avformat.h:848
uint64_t non_simple
Definition: matroskadec.c:268
#define MATROSKA_ID_CHAPTERUID
Definition: matroska.h:200
static EbmlSyntax matroska_index_entry[]
Definition: matroskadec.c:429
static int ebml_read_binary(AVIOContext *pb, int length, EbmlBin *bin)
Definition: matroskadec.c:704
#define MATROSKA_ID_VIDEODISPLAYUNIT
Definition: matroska.h:113
static int ebml_read_uint(AVIOContext *pb, int size, uint64_t *num)
Definition: matroskadec.c:644
#define MATROSKA_ID_TRACKMAXBLKADDID
Definition: matroska.h:101
int64_t dts
Decompression timestamp in AVStream->time_base units; the time at which the packet is decompressed...
Definition: avcodec.h:914
#define EBML_ID_EBMLMAXSIZELENGTH
Definition: matroska.h:39
int64_t duration
Decoding: duration of the stream, in AV_TIME_BASE fractional seconds.
Definition: avformat.h:893
#define MATROSKA_ID_CHAPSTRING
Definition: matroska.h:194
static int matroska_merge_packets(AVPacket *out, AVPacket *in)
Definition: matroskadec.c:1138
const char * name
A comma separated list of short names for the format.
Definition: avformat.h:455
#define MATROSKA_ID_TAGSTRING
Definition: matroska.h:150
static EbmlSyntax matroska_index_pos[]
Definition: matroskadec.c:422
static int ebml_read_float(AVIOContext *pb, int size, double *num)
Definition: matroskadec.c:663
#define MATROSKA_ID_DURATION
Definition: matroska.h:67
uint64_t length
Definition: matroskadec.c:213
static int matroska_aac_profile(char *codec_id)
Definition: matroskadec.c:1333
int stream_index
Definition: avcodec.h:917
#define EBML_ID_DOCTYPEVERSION
Definition: matroska.h:41
static void matroska_clear_queue(MatroskaDemuxContext *matroska)
Definition: matroskadec.c:1750
static EbmlSyntax matroska_chapter_entry[]
Definition: matroskadec.c:396
uint8_t bitdepth
Definition: dirac.c:82
enum AVDiscard discard
Selects which packets can be discarded at will and do not need to be demuxed.
Definition: avformat.h:690
#define MATROSKA_ID_ATTACHEDFILE
Definition: matroska.h:181
EbmlList blocks
Definition: matroskadec.c:218
This structure stores compressed data.
Definition: avcodec.h:898
static EbmlSyntax matroska_chapter_display[]
Definition: matroskadec.c:390
uint64_t default_duration
Definition: matroskadec.c:145
static int matroska_parse_frame(MatroskaDemuxContext *matroska, MatroskaTrack *track, AVStream *st, uint8_t *data, int pkt_size, uint64_t timecode, uint64_t duration, int64_t pos, int is_keyframe)
Definition: matroskadec.c:1937
void * av_mallocz(size_t size)
Allocate a block of size bytes with alignment suitable for all memory accesses (including vectors if ...
Definition: mem.c:158
#define MATROSKA_ID_CODECINFOURL
Definition: matroska.h:86
int64_t pts
Presentation timestamp in AVStream->time_base units; the time at which the decompressed packet will b...
Definition: avcodec.h:908
#define MATROSKA_ID_VIDEOPIXELWIDTH
Definition: matroska.h:107
#define MATROSKA_ID_TRACKAUDIO
Definition: matroska.h:81
#define MATROSKA_ID_ENCODINGSCOPE
Definition: matroska.h:128
const CodecTags ff_mkv_codec_tags[]
Definition: matroska.c:24
static const char *const matroska_doctypes[]
Definition: matroskadec.c:557
static EbmlSyntax matroska_track_video[]
Definition: matroskadec.c:299
if(!(ptr_align%ac->ptr_align)&&samples_align >=aligned_len)
uint64_t attachuid
Definition: matroskadec.c:198