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 + FF_INPUT_BUFFER_PADDING_SIZE)))
708  return AVERROR(ENOMEM);
709 
710  memset(bin->data + length, 0, FF_INPUT_BUFFER_PADDING_SIZE);
711 
712  bin->size = length;
713  bin->pos = avio_tell(pb);
714  if (avio_read(pb, bin->data, length) != length) {
715  av_freep(&bin->data);
716  return AVERROR(EIO);
717  }
718 
719  return 0;
720 }
721 
722 /*
723  * Read the next element, but only the header. The contents
724  * are supposed to be sub-elements which can be read separately.
725  * 0 is success, < 0 is failure.
726  */
727 static int ebml_read_master(MatroskaDemuxContext *matroska, uint64_t length)
728 {
729  AVIOContext *pb = matroska->ctx->pb;
731 
732  if (matroska->num_levels >= EBML_MAX_DEPTH) {
733  av_log(matroska->ctx, AV_LOG_ERROR,
734  "File moves beyond max. allowed depth (%d)\n", EBML_MAX_DEPTH);
735  return AVERROR(ENOSYS);
736  }
737 
738  level = &matroska->levels[matroska->num_levels++];
739  level->start = avio_tell(pb);
740  level->length = length;
741 
742  return 0;
743 }
744 
745 /*
746  * Read signed/unsigned "EBML" numbers.
747  * Return: number of bytes processed, < 0 on error
748  */
750  uint8_t *data, uint32_t size, uint64_t *num)
751 {
752  AVIOContext pb;
753  ffio_init_context(&pb, data, size, 0, NULL, NULL, NULL, NULL);
754  return ebml_read_num(matroska, &pb, FFMIN(size, 8), num);
755 }
756 
757 /*
758  * Same as above, but signed.
759  */
761  uint8_t *data, uint32_t size, int64_t *num)
762 {
763  uint64_t unum;
764  int res;
765 
766  /* read as unsigned number first */
767  if ((res = matroska_ebmlnum_uint(matroska, data, size, &unum)) < 0)
768  return res;
769 
770  /* make signed (weird way) */
771  *num = unum - ((1LL << (7*res - 1)) - 1);
772 
773  return res;
774 }
775 
776 static int ebml_parse_elem(MatroskaDemuxContext *matroska,
777  EbmlSyntax *syntax, void *data);
778 
779 static int ebml_parse_id(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
780  uint32_t id, void *data)
781 {
782  int i;
783  for (i=0; syntax[i].id; i++)
784  if (id == syntax[i].id)
785  break;
786  if (!syntax[i].id && id == MATROSKA_ID_CLUSTER &&
787  matroska->num_levels > 0 &&
788  matroska->levels[matroska->num_levels-1].length == 0xffffffffffffff)
789  return 0; // we reached the end of an unknown size cluster
790  if (!syntax[i].id && id != EBML_ID_VOID && id != EBML_ID_CRC32) {
791  av_log(matroska->ctx, AV_LOG_INFO, "Unknown entry 0x%X\n", id);
792  if (matroska->ctx->error_recognition & AV_EF_EXPLODE)
793  return AVERROR_INVALIDDATA;
794  }
795  return ebml_parse_elem(matroska, &syntax[i], data);
796 }
797 
798 static int ebml_parse(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
799  void *data)
800 {
801  if (!matroska->current_id) {
802  uint64_t id;
803  int res = ebml_read_num(matroska, matroska->ctx->pb, 4, &id);
804  if (res < 0)
805  return res;
806  matroska->current_id = id | 1 << 7*res;
807  }
808  return ebml_parse_id(matroska, syntax, matroska->current_id, data);
809 }
810 
811 static int ebml_parse_nest(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
812  void *data)
813 {
814  int i, res = 0;
815 
816  for (i=0; syntax[i].id; i++)
817  switch (syntax[i].type) {
818  case EBML_UINT:
819  *(uint64_t *)((char *)data+syntax[i].data_offset) = syntax[i].def.u;
820  break;
821  case EBML_FLOAT:
822  *(double *)((char *)data+syntax[i].data_offset) = syntax[i].def.f;
823  break;
824  case EBML_STR:
825  case EBML_UTF8:
826  *(char **)((char *)data+syntax[i].data_offset) = av_strdup(syntax[i].def.s);
827  break;
828  }
829 
830  while (!res && !ebml_level_end(matroska))
831  res = ebml_parse(matroska, syntax, data);
832 
833  return res;
834 }
835 
837  EbmlSyntax *syntax, void *data)
838 {
839  static const uint64_t max_lengths[EBML_TYPE_COUNT] = {
840  [EBML_UINT] = 8,
841  [EBML_FLOAT] = 8,
842  // max. 16 MB for strings
843  [EBML_STR] = 0x1000000,
844  [EBML_UTF8] = 0x1000000,
845  // max. 256 MB for binary data
846  [EBML_BIN] = 0x10000000,
847  // no limits for anything else
848  };
849  AVIOContext *pb = matroska->ctx->pb;
850  uint32_t id = syntax->id;
851  uint64_t length;
852  int res;
853  void *newelem;
854 
855  data = (char *)data + syntax->data_offset;
856  if (syntax->list_elem_size) {
857  EbmlList *list = data;
858  newelem = av_realloc(list->elem, (list->nb_elem+1)*syntax->list_elem_size);
859  if (!newelem)
860  return AVERROR(ENOMEM);
861  list->elem = newelem;
862  data = (char*)list->elem + list->nb_elem*syntax->list_elem_size;
863  memset(data, 0, syntax->list_elem_size);
864  list->nb_elem++;
865  }
866 
867  if (syntax->type != EBML_PASS && syntax->type != EBML_STOP) {
868  matroska->current_id = 0;
869  if ((res = ebml_read_length(matroska, pb, &length)) < 0)
870  return res;
871  if (max_lengths[syntax->type] && length > max_lengths[syntax->type]) {
872  av_log(matroska->ctx, AV_LOG_ERROR,
873  "Invalid length 0x%"PRIx64" > 0x%"PRIx64" for syntax element %i\n",
874  length, max_lengths[syntax->type], syntax->type);
875  return AVERROR_INVALIDDATA;
876  }
877  }
878 
879  switch (syntax->type) {
880  case EBML_UINT: res = ebml_read_uint (pb, length, data); break;
881  case EBML_FLOAT: res = ebml_read_float (pb, length, data); break;
882  case EBML_STR:
883  case EBML_UTF8: res = ebml_read_ascii (pb, length, data); break;
884  case EBML_BIN: res = ebml_read_binary(pb, length, data); break;
885  case EBML_NEST: if ((res=ebml_read_master(matroska, length)) < 0)
886  return res;
887  if (id == MATROSKA_ID_SEGMENT)
888  matroska->segment_start = avio_tell(matroska->ctx->pb);
889  return ebml_parse_nest(matroska, syntax->def.n, data);
890  case EBML_PASS: return ebml_parse_id(matroska, syntax->def.n, id, data);
891  case EBML_STOP: return 1;
892  default: return avio_skip(pb,length)<0 ? AVERROR(EIO) : 0;
893  }
894  if (res == AVERROR_INVALIDDATA)
895  av_log(matroska->ctx, AV_LOG_ERROR, "Invalid element\n");
896  else if (res == AVERROR(EIO))
897  av_log(matroska->ctx, AV_LOG_ERROR, "Read error\n");
898  return res;
899 }
900 
901 static void ebml_free(EbmlSyntax *syntax, void *data)
902 {
903  int i, j;
904  for (i=0; syntax[i].id; i++) {
905  void *data_off = (char *)data + syntax[i].data_offset;
906  switch (syntax[i].type) {
907  case EBML_STR:
908  case EBML_UTF8: av_freep(data_off); break;
909  case EBML_BIN: av_freep(&((EbmlBin *)data_off)->data); break;
910  case EBML_NEST:
911  if (syntax[i].list_elem_size) {
912  EbmlList *list = data_off;
913  char *ptr = list->elem;
914  for (j=0; j<list->nb_elem; j++, ptr+=syntax[i].list_elem_size)
915  ebml_free(syntax[i].def.n, ptr);
916  av_free(list->elem);
917  } else
918  ebml_free(syntax[i].def.n, data_off);
919  default: break;
920  }
921  }
922 }
923 
924 
925 /*
926  * Autodetecting...
927  */
929 {
930  uint64_t total = 0;
931  int len_mask = 0x80, size = 1, n = 1, i;
932 
933  /* EBML header? */
934  if (AV_RB32(p->buf) != EBML_ID_HEADER)
935  return 0;
936 
937  /* length of header */
938  total = p->buf[4];
939  while (size <= 8 && !(total & len_mask)) {
940  size++;
941  len_mask >>= 1;
942  }
943  if (size > 8)
944  return 0;
945  total &= (len_mask - 1);
946  while (n < size)
947  total = (total << 8) | p->buf[4 + n++];
948 
949  /* Does the probe data contain the whole header? */
950  if (p->buf_size < 4 + size + total)
951  return 0;
952 
953  /* The header should contain a known document type. For now,
954  * we don't parse the whole header but simply check for the
955  * availability of that array of characters inside the header.
956  * Not fully fool-proof, but good enough. */
957  for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++) {
958  int probelen = strlen(matroska_doctypes[i]);
959  if (total < probelen)
960  continue;
961  for (n = 4+size; n <= 4+size+total-probelen; n++)
962  if (!memcmp(p->buf+n, matroska_doctypes[i], probelen))
963  return AVPROBE_SCORE_MAX;
964  }
965 
966  // probably valid EBML header but no recognized doctype
967  return AVPROBE_SCORE_MAX/2;
968 }
969 
971  int num)
972 {
973  MatroskaTrack *tracks = matroska->tracks.elem;
974  int i;
975 
976  for (i=0; i < matroska->tracks.nb_elem; i++)
977  if (tracks[i].num == num)
978  return &tracks[i];
979 
980  av_log(matroska->ctx, AV_LOG_ERROR, "Invalid track number %d\n", num);
981  return NULL;
982 }
983 
984 static int matroska_decode_buffer(uint8_t** buf, int* buf_size,
985  MatroskaTrack *track)
986 {
987  MatroskaTrackEncoding *encodings = track->encodings.elem;
988  uint8_t* data = *buf;
989  int isize = *buf_size;
990  uint8_t* pkt_data = NULL;
991  uint8_t av_unused *newpktdata;
992  int pkt_size = isize;
993  int result = 0;
994  int olen;
995 
996  if (pkt_size >= 10000000)
997  return AVERROR_INVALIDDATA;
998 
999  switch (encodings[0].compression.algo) {
1001  int header_size = encodings[0].compression.settings.size;
1002  uint8_t *header = encodings[0].compression.settings.data;
1003 
1004  if (!header_size)
1005  return 0;
1006 
1007  pkt_size = isize + header_size;
1008  pkt_data = av_malloc(pkt_size);
1009  if (!pkt_data)
1010  return AVERROR(ENOMEM);
1011 
1012  memcpy(pkt_data, header, header_size);
1013  memcpy(pkt_data + header_size, data, isize);
1014  break;
1015  }
1016 #if CONFIG_LZO
1018  do {
1019  olen = pkt_size *= 3;
1020  newpktdata = av_realloc(pkt_data, pkt_size + AV_LZO_OUTPUT_PADDING);
1021  if (!newpktdata) {
1022  result = AVERROR(ENOMEM);
1023  goto failed;
1024  }
1025  pkt_data = newpktdata;
1026  result = av_lzo1x_decode(pkt_data, &olen, data, &isize);
1027  } while (result==AV_LZO_OUTPUT_FULL && pkt_size<10000000);
1028  if (result) {
1029  result = AVERROR_INVALIDDATA;
1030  goto failed;
1031  }
1032  pkt_size -= olen;
1033  break;
1034 #endif
1035 #if CONFIG_ZLIB
1037  z_stream zstream = {0};
1038  if (inflateInit(&zstream) != Z_OK)
1039  return -1;
1040  zstream.next_in = data;
1041  zstream.avail_in = isize;
1042  do {
1043  pkt_size *= 3;
1044  newpktdata = av_realloc(pkt_data, pkt_size);
1045  if (!newpktdata) {
1046  inflateEnd(&zstream);
1047  goto failed;
1048  }
1049  pkt_data = newpktdata;
1050  zstream.avail_out = pkt_size - zstream.total_out;
1051  zstream.next_out = pkt_data + zstream.total_out;
1052  result = inflate(&zstream, Z_NO_FLUSH);
1053  } while (result==Z_OK && pkt_size<10000000);
1054  pkt_size = zstream.total_out;
1055  inflateEnd(&zstream);
1056  if (result != Z_STREAM_END) {
1057  if (result == Z_MEM_ERROR)
1058  result = AVERROR(ENOMEM);
1059  else
1060  result = AVERROR_INVALIDDATA;
1061  goto failed;
1062  }
1063  break;
1064  }
1065 #endif
1066 #if CONFIG_BZLIB
1068  bz_stream bzstream = {0};
1069  if (BZ2_bzDecompressInit(&bzstream, 0, 0) != BZ_OK)
1070  return -1;
1071  bzstream.next_in = data;
1072  bzstream.avail_in = isize;
1073  do {
1074  pkt_size *= 3;
1075  newpktdata = av_realloc(pkt_data, pkt_size);
1076  if (!newpktdata) {
1077  BZ2_bzDecompressEnd(&bzstream);
1078  goto failed;
1079  }
1080  pkt_data = newpktdata;
1081  bzstream.avail_out = pkt_size - bzstream.total_out_lo32;
1082  bzstream.next_out = pkt_data + bzstream.total_out_lo32;
1083  result = BZ2_bzDecompress(&bzstream);
1084  } while (result==BZ_OK && pkt_size<10000000);
1085  pkt_size = bzstream.total_out_lo32;
1086  BZ2_bzDecompressEnd(&bzstream);
1087  if (result != BZ_STREAM_END) {
1088  if (result == BZ_MEM_ERROR)
1089  result = AVERROR(ENOMEM);
1090  else
1091  result = AVERROR_INVALIDDATA;
1092  goto failed;
1093  }
1094  break;
1095  }
1096 #endif
1097  default:
1098  return AVERROR_INVALIDDATA;
1099  }
1100 
1101  *buf = pkt_data;
1102  *buf_size = pkt_size;
1103  return 0;
1104  failed:
1105  av_free(pkt_data);
1106  return result;
1107 }
1108 
1110  AVPacket *pkt, uint64_t display_duration)
1111 {
1112  char *line, *layer, *ptr = pkt->data, *end = ptr+pkt->size;
1113  for (; *ptr!=',' && ptr<end-1; ptr++);
1114  if (*ptr == ',')
1115  layer = ++ptr;
1116  for (; *ptr!=',' && ptr<end-1; ptr++);
1117  if (*ptr == ',') {
1118  int64_t end_pts = pkt->pts + display_duration;
1119  int sc = matroska->time_scale * pkt->pts / 10000000;
1120  int ec = matroska->time_scale * end_pts / 10000000;
1121  int sh, sm, ss, eh, em, es, len;
1122  sh = sc/360000; sc -= 360000*sh;
1123  sm = sc/ 6000; sc -= 6000*sm;
1124  ss = sc/ 100; sc -= 100*ss;
1125  eh = ec/360000; ec -= 360000*eh;
1126  em = ec/ 6000; ec -= 6000*em;
1127  es = ec/ 100; ec -= 100*es;
1128  *ptr++ = '\0';
1129  len = 50 + end-ptr + FF_INPUT_BUFFER_PADDING_SIZE;
1130  if (!(line = av_malloc(len)))
1131  return;
1132  snprintf(line,len,"Dialogue: %s,%d:%02d:%02d.%02d,%d:%02d:%02d.%02d,%s\r\n",
1133  layer, sh, sm, ss, sc, eh, em, es, ec, ptr);
1134  av_free(pkt->data);
1135  pkt->data = line;
1136  pkt->size = strlen(line);
1137  }
1138 }
1139 
1141 {
1142  int old_size = out->size;
1143  int ret = av_grow_packet(out, in->size);
1144  if (ret < 0)
1145  return ret;
1146 
1147  memcpy(out->data + old_size, in->data, in->size);
1148 
1149  av_free_packet(in);
1150  av_free(in);
1151  return 0;
1152 }
1153 
1155  AVDictionary **metadata, char *prefix)
1156 {
1157  MatroskaTag *tags = list->elem;
1158  char key[1024];
1159  int i;
1160 
1161  for (i=0; i < list->nb_elem; i++) {
1162  const char *lang = tags[i].lang && strcmp(tags[i].lang, "und") ?
1163  tags[i].lang : NULL;
1164 
1165  if (!tags[i].name) {
1166  av_log(s, AV_LOG_WARNING, "Skipping invalid tag with no TagName.\n");
1167  continue;
1168  }
1169  if (prefix) snprintf(key, sizeof(key), "%s/%s", prefix, tags[i].name);
1170  else av_strlcpy(key, tags[i].name, sizeof(key));
1171  if (tags[i].def || !lang) {
1172  av_dict_set(metadata, key, tags[i].string, 0);
1173  if (tags[i].sub.nb_elem)
1174  matroska_convert_tag(s, &tags[i].sub, metadata, key);
1175  }
1176  if (lang) {
1177  av_strlcat(key, "-", sizeof(key));
1178  av_strlcat(key, lang, sizeof(key));
1179  av_dict_set(metadata, key, tags[i].string, 0);
1180  if (tags[i].sub.nb_elem)
1181  matroska_convert_tag(s, &tags[i].sub, metadata, key);
1182  }
1183  }
1185 }
1186 
1188 {
1189  MatroskaDemuxContext *matroska = s->priv_data;
1190  MatroskaTags *tags = matroska->tags.elem;
1191  int i, j;
1192 
1193  for (i=0; i < matroska->tags.nb_elem; i++) {
1194  if (tags[i].target.attachuid) {
1195  MatroskaAttachement *attachment = matroska->attachments.elem;
1196  for (j=0; j<matroska->attachments.nb_elem; j++)
1197  if (attachment[j].uid == tags[i].target.attachuid
1198  && attachment[j].stream)
1199  matroska_convert_tag(s, &tags[i].tag,
1200  &attachment[j].stream->metadata, NULL);
1201  } else if (tags[i].target.chapteruid) {
1202  MatroskaChapter *chapter = matroska->chapters.elem;
1203  for (j=0; j<matroska->chapters.nb_elem; j++)
1204  if (chapter[j].uid == tags[i].target.chapteruid
1205  && chapter[j].chapter)
1206  matroska_convert_tag(s, &tags[i].tag,
1207  &chapter[j].chapter->metadata, NULL);
1208  } else if (tags[i].target.trackuid) {
1209  MatroskaTrack *track = matroska->tracks.elem;
1210  for (j=0; j<matroska->tracks.nb_elem; j++)
1211  if (track[j].uid == tags[i].target.trackuid && track[j].stream)
1212  matroska_convert_tag(s, &tags[i].tag,
1213  &track[j].stream->metadata, NULL);
1214  } else {
1215  matroska_convert_tag(s, &tags[i].tag, &s->metadata,
1216  tags[i].target.type);
1217  }
1218  }
1219 }
1220 
1222 {
1223  EbmlList *seekhead_list = &matroska->seekhead;
1224  MatroskaSeekhead *seekhead = seekhead_list->elem;
1225  uint32_t level_up = matroska->level_up;
1226  int64_t before_pos = avio_tell(matroska->ctx->pb);
1227  uint32_t saved_id = matroska->current_id;
1229  int64_t offset;
1230  int ret = 0;
1231 
1232  if (idx >= seekhead_list->nb_elem
1233  || seekhead[idx].id == MATROSKA_ID_SEEKHEAD
1234  || seekhead[idx].id == MATROSKA_ID_CLUSTER)
1235  return 0;
1236 
1237  /* seek */
1238  offset = seekhead[idx].pos + matroska->segment_start;
1239  if (avio_seek(matroska->ctx->pb, offset, SEEK_SET) == offset) {
1240  /* We don't want to lose our seekhead level, so we add
1241  * a dummy. This is a crude hack. */
1242  if (matroska->num_levels == EBML_MAX_DEPTH) {
1243  av_log(matroska->ctx, AV_LOG_INFO,
1244  "Max EBML element depth (%d) reached, "
1245  "cannot parse further.\n", EBML_MAX_DEPTH);
1246  ret = AVERROR_INVALIDDATA;
1247  } else {
1248  level.start = 0;
1249  level.length = (uint64_t)-1;
1250  matroska->levels[matroska->num_levels] = level;
1251  matroska->num_levels++;
1252  matroska->current_id = 0;
1253 
1254  ret = ebml_parse(matroska, matroska_segment, matroska);
1255 
1256  /* remove dummy level */
1257  while (matroska->num_levels) {
1258  uint64_t length = matroska->levels[--matroska->num_levels].length;
1259  if (length == (uint64_t)-1)
1260  break;
1261  }
1262  }
1263  }
1264  /* seek back */
1265  avio_seek(matroska->ctx->pb, before_pos, SEEK_SET);
1266  matroska->level_up = level_up;
1267  matroska->current_id = saved_id;
1268 
1269  return ret;
1270 }
1271 
1273 {
1274  EbmlList *seekhead_list = &matroska->seekhead;
1275  int64_t before_pos = avio_tell(matroska->ctx->pb);
1276  int i;
1277 
1278  // we should not do any seeking in the streaming case
1279  if (!matroska->ctx->pb->seekable ||
1280  (matroska->ctx->flags & AVFMT_FLAG_IGNIDX))
1281  return;
1282 
1283  for (i = 0; i < seekhead_list->nb_elem; i++) {
1284  MatroskaSeekhead *seekhead = seekhead_list->elem;
1285  if (seekhead[i].pos <= before_pos)
1286  continue;
1287 
1288  // defer cues parsing until we actually need cue data.
1289  if (seekhead[i].id == MATROSKA_ID_CUES) {
1290  matroska->cues_parsing_deferred = 1;
1291  continue;
1292  }
1293 
1294  if (matroska_parse_seekhead_entry(matroska, i) < 0)
1295  break;
1296  }
1297 }
1298 
1300  EbmlList *seekhead_list = &matroska->seekhead;
1301  MatroskaSeekhead *seekhead = seekhead_list->elem;
1302  EbmlList *index_list;
1304  int index_scale = 1;
1305  int i, j;
1306 
1307  for (i = 0; i < seekhead_list->nb_elem; i++)
1308  if (seekhead[i].id == MATROSKA_ID_CUES)
1309  break;
1310  assert(i <= seekhead_list->nb_elem);
1311 
1312  matroska_parse_seekhead_entry(matroska, i);
1313 
1314  index_list = &matroska->index;
1315  index = index_list->elem;
1316  if (index_list->nb_elem
1317  && index[0].time > 1E14/matroska->time_scale) {
1318  av_log(matroska->ctx, AV_LOG_WARNING, "Working around broken index.\n");
1319  index_scale = matroska->time_scale;
1320  }
1321  for (i = 0; i < index_list->nb_elem; i++) {
1322  EbmlList *pos_list = &index[i].pos;
1323  MatroskaIndexPos *pos = pos_list->elem;
1324  for (j = 0; j < pos_list->nb_elem; j++) {
1325  MatroskaTrack *track = matroska_find_track_by_num(matroska, pos[j].track);
1326  if (track && track->stream)
1327  av_add_index_entry(track->stream,
1328  pos[j].pos + matroska->segment_start,
1329  index[i].time/index_scale, 0, 0,
1331  }
1332  }
1333 }
1334 
1336 {
1337  static const char * const aac_profiles[] = { "MAIN", "LC", "SSR" };
1338  int profile;
1339 
1340  for (profile=0; profile<FF_ARRAY_ELEMS(aac_profiles); profile++)
1341  if (strstr(codec_id, aac_profiles[profile]))
1342  break;
1343  return profile + 1;
1344 }
1345 
1346 static int matroska_aac_sri(int samplerate)
1347 {
1348  int sri;
1349 
1350  for (sri=0; sri<FF_ARRAY_ELEMS(avpriv_mpeg4audio_sample_rates); sri++)
1351  if (avpriv_mpeg4audio_sample_rates[sri] == samplerate)
1352  break;
1353  return sri;
1354 }
1355 
1357 {
1358  MatroskaDemuxContext *matroska = s->priv_data;
1359  EbmlList *attachements_list = &matroska->attachments;
1360  MatroskaAttachement *attachements;
1361  EbmlList *chapters_list = &matroska->chapters;
1362  MatroskaChapter *chapters;
1363  MatroskaTrack *tracks;
1364  uint64_t max_start = 0;
1365  Ebml ebml = { 0 };
1366  AVStream *st;
1367  int i, j, res;
1368 
1369  matroska->ctx = s;
1370 
1371  /* First read the EBML header. */
1372  if (ebml_parse(matroska, ebml_syntax, &ebml)
1373  || ebml.version > EBML_VERSION || ebml.max_size > sizeof(uint64_t)
1374  || ebml.id_length > sizeof(uint32_t) || ebml.doctype_version > 2) {
1375  av_log(matroska->ctx, AV_LOG_ERROR,
1376  "EBML header using unsupported features\n"
1377  "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
1378  ebml.version, ebml.doctype, ebml.doctype_version);
1379  ebml_free(ebml_syntax, &ebml);
1380  return AVERROR_PATCHWELCOME;
1381  }
1382  for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++)
1383  if (!strcmp(ebml.doctype, matroska_doctypes[i]))
1384  break;
1385  if (i >= FF_ARRAY_ELEMS(matroska_doctypes)) {
1386  av_log(s, AV_LOG_WARNING, "Unknown EBML doctype '%s'\n", ebml.doctype);
1387  if (matroska->ctx->error_recognition & AV_EF_EXPLODE) {
1388  ebml_free(ebml_syntax, &ebml);
1389  return AVERROR_INVALIDDATA;
1390  }
1391  }
1392  ebml_free(ebml_syntax, &ebml);
1393 
1394  /* The next thing is a segment. */
1395  if ((res = ebml_parse(matroska, matroska_segments, matroska)) < 0)
1396  return res;
1397  matroska_execute_seekhead(matroska);
1398 
1399  if (!matroska->time_scale)
1400  matroska->time_scale = 1000000;
1401  if (matroska->duration)
1402  matroska->ctx->duration = matroska->duration * matroska->time_scale
1403  * 1000 / AV_TIME_BASE;
1404  av_dict_set(&s->metadata, "title", matroska->title, 0);
1405 
1406  tracks = matroska->tracks.elem;
1407  for (i=0; i < matroska->tracks.nb_elem; i++) {
1408  MatroskaTrack *track = &tracks[i];
1410  EbmlList *encodings_list = &track->encodings;
1411  MatroskaTrackEncoding *encodings = encodings_list->elem;
1412  uint8_t *extradata = NULL;
1413  int extradata_size = 0;
1414  int extradata_offset = 0;
1415  AVIOContext b;
1416 
1417  /* Apply some sanity checks. */
1418  if (track->type != MATROSKA_TRACK_TYPE_VIDEO &&
1419  track->type != MATROSKA_TRACK_TYPE_AUDIO &&
1420  track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
1421  av_log(matroska->ctx, AV_LOG_INFO,
1422  "Unknown or unsupported track type %"PRIu64"\n",
1423  track->type);
1424  continue;
1425  }
1426  if (track->codec_id == NULL)
1427  continue;
1428 
1429  if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1430  if (!track->default_duration && track->video.frame_rate > 0)
1431  track->default_duration = 1000000000/track->video.frame_rate;
1432  if (!track->video.display_width)
1433  track->video.display_width = track->video.pixel_width;
1434  if (!track->video.display_height)
1435  track->video.display_height = track->video.pixel_height;
1436  } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
1437  if (!track->audio.out_samplerate)
1438  track->audio.out_samplerate = track->audio.samplerate;
1439  }
1440  if (encodings_list->nb_elem > 1) {
1441  av_log(matroska->ctx, AV_LOG_ERROR,
1442  "Multiple combined encodings not supported");
1443  } else if (encodings_list->nb_elem == 1) {
1444  if (encodings[0].type ||
1445  (
1446 #if CONFIG_ZLIB
1447  encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_ZLIB &&
1448 #endif
1449 #if CONFIG_BZLIB
1451 #endif
1452 #if CONFIG_LZO
1454 #endif
1456  encodings[0].scope = 0;
1457  av_log(matroska->ctx, AV_LOG_ERROR,
1458  "Unsupported encoding type");
1459  } else if (track->codec_priv.size && encodings[0].scope&2) {
1460  uint8_t *codec_priv = track->codec_priv.data;
1461  int ret = matroska_decode_buffer(&track->codec_priv.data,
1462  &track->codec_priv.size,
1463  track);
1464  if (ret < 0) {
1465  track->codec_priv.data = NULL;
1466  track->codec_priv.size = 0;
1467  av_log(matroska->ctx, AV_LOG_ERROR,
1468  "Failed to decode codec private data\n");
1469  }
1470 
1471  if (codec_priv != track->codec_priv.data)
1472  av_free(codec_priv);
1473  }
1474  }
1475 
1476  for(j=0; ff_mkv_codec_tags[j].id != AV_CODEC_ID_NONE; j++){
1477  if(!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
1478  strlen(ff_mkv_codec_tags[j].str))){
1479  codec_id= ff_mkv_codec_tags[j].id;
1480  break;
1481  }
1482  }
1483 
1484  st = track->stream = avformat_new_stream(s, NULL);
1485  if (st == NULL)
1486  return AVERROR(ENOMEM);
1487 
1488  if (!strcmp(track->codec_id, "V_MS/VFW/FOURCC")
1489  && track->codec_priv.size >= 40
1490  && track->codec_priv.data != NULL) {
1491  track->ms_compat = 1;
1492  track->video.fourcc = AV_RL32(track->codec_priv.data + 16);
1493  codec_id = ff_codec_get_id(ff_codec_bmp_tags, track->video.fourcc);
1494  extradata_offset = 40;
1495  } else if (!strcmp(track->codec_id, "A_MS/ACM")
1496  && track->codec_priv.size >= 14
1497  && track->codec_priv.data != NULL) {
1498  int ret;
1499  ffio_init_context(&b, track->codec_priv.data, track->codec_priv.size,
1501  ret = ff_get_wav_header(&b, st->codec, track->codec_priv.size);
1502  if (ret < 0)
1503  return ret;
1504  codec_id = st->codec->codec_id;
1505  extradata_offset = FFMIN(track->codec_priv.size, 18);
1506  } else if (!strcmp(track->codec_id, "V_QUICKTIME")
1507  && (track->codec_priv.size >= 86)
1508  && (track->codec_priv.data != NULL)) {
1509  track->video.fourcc = AV_RL32(track->codec_priv.data);
1511  } else if (codec_id == AV_CODEC_ID_PCM_S16BE) {
1512  switch (track->audio.bitdepth) {
1513  case 8: codec_id = AV_CODEC_ID_PCM_U8; break;
1514  case 24: codec_id = AV_CODEC_ID_PCM_S24BE; break;
1515  case 32: codec_id = AV_CODEC_ID_PCM_S32BE; break;
1516  }
1517  } else if (codec_id == AV_CODEC_ID_PCM_S16LE) {
1518  switch (track->audio.bitdepth) {
1519  case 8: codec_id = AV_CODEC_ID_PCM_U8; break;
1520  case 24: codec_id = AV_CODEC_ID_PCM_S24LE; break;
1521  case 32: codec_id = AV_CODEC_ID_PCM_S32LE; break;
1522  }
1523  } else if (codec_id==AV_CODEC_ID_PCM_F32LE && track->audio.bitdepth==64) {
1524  codec_id = AV_CODEC_ID_PCM_F64LE;
1525  } else if (codec_id == AV_CODEC_ID_AAC && !track->codec_priv.size) {
1526  int profile = matroska_aac_profile(track->codec_id);
1527  int sri = matroska_aac_sri(track->audio.samplerate);
1528  extradata = av_mallocz(5 + FF_INPUT_BUFFER_PADDING_SIZE);
1529  if (extradata == NULL)
1530  return AVERROR(ENOMEM);
1531  extradata[0] = (profile << 3) | ((sri&0x0E) >> 1);
1532  extradata[1] = ((sri&0x01) << 7) | (track->audio.channels<<3);
1533  if (strstr(track->codec_id, "SBR")) {
1534  sri = matroska_aac_sri(track->audio.out_samplerate);
1535  extradata[2] = 0x56;
1536  extradata[3] = 0xE5;
1537  extradata[4] = 0x80 | (sri<<3);
1538  extradata_size = 5;
1539  } else
1540  extradata_size = 2;
1541  } else if (codec_id == AV_CODEC_ID_ALAC && track->codec_priv.size) {
1542  /* Only ALAC's magic cookie is stored in Matroska's track headers.
1543  Create the "atom size", "tag", and "tag version" fields the
1544  decoder expects manually. */
1545  extradata_size = 12 + track->codec_priv.size;
1546  extradata = av_mallocz(extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
1547  if (extradata == NULL)
1548  return AVERROR(ENOMEM);
1549  AV_WB32(extradata, extradata_size);
1550  memcpy(&extradata[4], "alac", 4);
1551  AV_WB32(&extradata[8], 0);
1552  memcpy(&extradata[12], track->codec_priv.data,
1553  track->codec_priv.size);
1554  } else if (codec_id == AV_CODEC_ID_TTA) {
1555  extradata_size = 30;
1556  extradata = av_mallocz(extradata_size);
1557  if (extradata == NULL)
1558  return AVERROR(ENOMEM);
1559  ffio_init_context(&b, extradata, extradata_size, 1,
1560  NULL, NULL, NULL, NULL);
1561  avio_write(&b, "TTA1", 4);
1562  avio_wl16(&b, 1);
1563  avio_wl16(&b, track->audio.channels);
1564  avio_wl16(&b, track->audio.bitdepth);
1565  avio_wl32(&b, track->audio.out_samplerate);
1566  avio_wl32(&b, matroska->ctx->duration * track->audio.out_samplerate);
1567  } else if (codec_id == AV_CODEC_ID_RV10 || codec_id == AV_CODEC_ID_RV20 ||
1568  codec_id == AV_CODEC_ID_RV30 || codec_id == AV_CODEC_ID_RV40) {
1569  extradata_offset = 26;
1570  } else if (codec_id == AV_CODEC_ID_RA_144) {
1571  track->audio.out_samplerate = 8000;
1572  track->audio.channels = 1;
1573  } else if (codec_id == AV_CODEC_ID_RA_288 || codec_id == AV_CODEC_ID_COOK ||
1574  codec_id == AV_CODEC_ID_ATRAC3 || codec_id == AV_CODEC_ID_SIPR) {
1575  int flavor;
1576  ffio_init_context(&b, track->codec_priv.data,track->codec_priv.size,
1577  0, NULL, NULL, NULL, NULL);
1578  avio_skip(&b, 22);
1579  flavor = avio_rb16(&b);
1580  track->audio.coded_framesize = avio_rb32(&b);
1581  avio_skip(&b, 12);
1582  track->audio.sub_packet_h = avio_rb16(&b);
1583  track->audio.frame_size = avio_rb16(&b);
1584  track->audio.sub_packet_size = avio_rb16(&b);
1585  if (flavor <= 0 || track->audio.coded_framesize <= 0 ||
1586  track->audio.sub_packet_h <= 0 || track->audio.frame_size <= 0 ||
1587  track->audio.sub_packet_size <= 0)
1588  return AVERROR_INVALIDDATA;
1589  track->audio.buf = av_malloc(track->audio.frame_size * track->audio.sub_packet_h);
1590  if (codec_id == AV_CODEC_ID_RA_288) {
1591  st->codec->block_align = track->audio.coded_framesize;
1592  track->codec_priv.size = 0;
1593  } else {
1594  if (codec_id == AV_CODEC_ID_SIPR && flavor < 4) {
1595  const int sipr_bit_rate[4] = { 6504, 8496, 5000, 16000 };
1596  track->audio.sub_packet_size = ff_sipr_subpk_size[flavor];
1597  st->codec->bit_rate = sipr_bit_rate[flavor];
1598  }
1599  st->codec->block_align = track->audio.sub_packet_size;
1600  extradata_offset = 78;
1601  }
1602  }
1603  track->codec_priv.size -= extradata_offset;
1604 
1605  if (codec_id == AV_CODEC_ID_NONE)
1606  av_log(matroska->ctx, AV_LOG_INFO,
1607  "Unknown/unsupported AVCodecID %s.\n", track->codec_id);
1608 
1609  if (track->time_scale < 0.01)
1610  track->time_scale = 1.0;
1611  avpriv_set_pts_info(st, 64, matroska->time_scale*track->time_scale, 1000*1000*1000); /* 64 bit pts in ns */
1612 
1613  st->codec->codec_id = codec_id;
1614  st->start_time = 0;
1615  if (strcmp(track->language, "und"))
1616  av_dict_set(&st->metadata, "language", track->language, 0);
1617  av_dict_set(&st->metadata, "title", track->name, 0);
1618 
1619  if (track->flag_default)
1621  if (track->flag_forced)
1623 
1624  if (!st->codec->extradata) {
1625  if(extradata){
1626  st->codec->extradata = extradata;
1627  st->codec->extradata_size = extradata_size;
1628  } else if(track->codec_priv.data && track->codec_priv.size > 0){
1629  st->codec->extradata = av_mallocz(track->codec_priv.size +
1631  if(st->codec->extradata == NULL)
1632  return AVERROR(ENOMEM);
1633  st->codec->extradata_size = track->codec_priv.size;
1634  memcpy(st->codec->extradata,
1635  track->codec_priv.data + extradata_offset,
1636  track->codec_priv.size);
1637  }
1638  }
1639 
1640  if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1642  st->codec->codec_tag = track->video.fourcc;
1643  st->codec->width = track->video.pixel_width;
1644  st->codec->height = track->video.pixel_height;
1646  &st->sample_aspect_ratio.den,
1647  st->codec->height * track->video.display_width,
1648  st->codec-> width * track->video.display_height,
1649  255);
1650  if (st->codec->codec_id != AV_CODEC_ID_H264)
1652  if (track->default_duration) {
1654  1000000000, track->default_duration, 30000);
1655 #if FF_API_R_FRAME_RATE
1656  st->r_frame_rate = st->avg_frame_rate;
1657 #endif
1658  }
1659  } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
1661  st->codec->sample_rate = track->audio.out_samplerate;
1662  st->codec->channels = track->audio.channels;
1663  if (st->codec->codec_id != AV_CODEC_ID_AAC)
1665  } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
1667  if (st->codec->codec_id == AV_CODEC_ID_SSA)
1668  matroska->contains_ssa = 1;
1669  }
1670  }
1671 
1672  attachements = attachements_list->elem;
1673  for (j=0; j<attachements_list->nb_elem; j++) {
1674  if (!(attachements[j].filename && attachements[j].mime &&
1675  attachements[j].bin.data && attachements[j].bin.size > 0)) {
1676  av_log(matroska->ctx, AV_LOG_ERROR, "incomplete attachment\n");
1677  } else {
1678  AVStream *st = avformat_new_stream(s, NULL);
1679  if (st == NULL)
1680  break;
1681  av_dict_set(&st->metadata, "filename",attachements[j].filename, 0);
1682  av_dict_set(&st->metadata, "mimetype", attachements[j].mime, 0);
1685  st->codec->extradata = av_malloc(attachements[j].bin.size);
1686  if(st->codec->extradata == NULL)
1687  break;
1688  st->codec->extradata_size = attachements[j].bin.size;
1689  memcpy(st->codec->extradata, attachements[j].bin.data, attachements[j].bin.size);
1690 
1691  for (i=0; ff_mkv_mime_tags[i].id != AV_CODEC_ID_NONE; i++) {
1692  if (!strncmp(ff_mkv_mime_tags[i].str, attachements[j].mime,
1693  strlen(ff_mkv_mime_tags[i].str))) {
1694  st->codec->codec_id = ff_mkv_mime_tags[i].id;
1695  break;
1696  }
1697  }
1698  attachements[j].stream = st;
1699  }
1700  }
1701 
1702  chapters = chapters_list->elem;
1703  for (i=0; i<chapters_list->nb_elem; i++)
1704  if (chapters[i].start != AV_NOPTS_VALUE && chapters[i].uid
1705  && (max_start==0 || chapters[i].start > max_start)) {
1706  chapters[i].chapter =
1707  avpriv_new_chapter(s, chapters[i].uid, (AVRational){1, 1000000000},
1708  chapters[i].start, chapters[i].end,
1709  chapters[i].title);
1710  av_dict_set(&chapters[i].chapter->metadata,
1711  "title", chapters[i].title, 0);
1712  max_start = chapters[i].start;
1713  }
1714 
1716 
1717  return 0;
1718 }
1719 
1720 /*
1721  * Put one packet in an application-supplied AVPacket struct.
1722  * Returns 0 on success or -1 on failure.
1723  */
1725  AVPacket *pkt)
1726 {
1727  if (matroska->num_packets > 0) {
1728  memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
1729  av_free(matroska->packets[0]);
1730  if (matroska->num_packets > 1) {
1731  void *newpackets;
1732  memmove(&matroska->packets[0], &matroska->packets[1],
1733  (matroska->num_packets - 1) * sizeof(AVPacket *));
1734  newpackets = av_realloc(matroska->packets,
1735  (matroska->num_packets - 1) * sizeof(AVPacket *));
1736  if (newpackets)
1737  matroska->packets = newpackets;
1738  } else {
1739  av_freep(&matroska->packets);
1740  matroska->prev_pkt = NULL;
1741  }
1742  matroska->num_packets--;
1743  return 0;
1744  }
1745 
1746  return -1;
1747 }
1748 
1749 /*
1750  * Free all packets in our internal queue.
1751  */
1753 {
1754  matroska->prev_pkt = NULL;
1755  if (matroska->packets) {
1756  int n;
1757  for (n = 0; n < matroska->num_packets; n++) {
1758  av_free_packet(matroska->packets[n]);
1759  av_free(matroska->packets[n]);
1760  }
1761  av_freep(&matroska->packets);
1762  matroska->num_packets = 0;
1763  }
1764 }
1765 
1767  int* buf_size, int type,
1768  uint32_t **lace_buf, int *laces)
1769 {
1770  int res = 0, n, size = *buf_size;
1771  uint8_t *data = *buf;
1772  uint32_t *lace_size;
1773 
1774  if (!type) {
1775  *laces = 1;
1776  *lace_buf = av_mallocz(sizeof(int));
1777  if (!*lace_buf)
1778  return AVERROR(ENOMEM);
1779 
1780  *lace_buf[0] = size;
1781  return 0;
1782  }
1783 
1784  assert(size > 0);
1785  *laces = *data + 1;
1786  data += 1;
1787  size -= 1;
1788  lace_size = av_mallocz(*laces * sizeof(int));
1789  if (!lace_size)
1790  return AVERROR(ENOMEM);
1791 
1792  switch (type) {
1793  case 0x1: /* Xiph lacing */ {
1794  uint8_t temp;
1795  uint32_t total = 0;
1796  for (n = 0; res == 0 && n < *laces - 1; n++) {
1797  while (1) {
1798  if (size == 0) {
1799  res = AVERROR_EOF;
1800  break;
1801  }
1802  temp = *data;
1803  lace_size[n] += temp;
1804  data += 1;
1805  size -= 1;
1806  if (temp != 0xff)
1807  break;
1808  }
1809  total += lace_size[n];
1810  }
1811  if (size <= total) {
1812  res = AVERROR_INVALIDDATA;
1813  break;
1814  }
1815 
1816  lace_size[n] = size - total;
1817  break;
1818  }
1819 
1820  case 0x2: /* fixed-size lacing */
1821  if (size % (*laces)) {
1822  res = AVERROR_INVALIDDATA;
1823  break;
1824  }
1825  for (n = 0; n < *laces; n++)
1826  lace_size[n] = size / *laces;
1827  break;
1828 
1829  case 0x3: /* EBML lacing */ {
1830  uint64_t num;
1831  uint64_t total;
1832  n = matroska_ebmlnum_uint(matroska, data, size, &num);
1833  if (n < 0) {
1834  av_log(matroska->ctx, AV_LOG_INFO,
1835  "EBML block data error\n");
1836  res = n;
1837  break;
1838  }
1839  data += n;
1840  size -= n;
1841  total = lace_size[0] = num;
1842  for (n = 1; res == 0 && n < *laces - 1; n++) {
1843  int64_t snum;
1844  int r;
1845  r = matroska_ebmlnum_sint(matroska, data, size, &snum);
1846  if (r < 0) {
1847  av_log(matroska->ctx, AV_LOG_INFO,
1848  "EBML block data error\n");
1849  res = r;
1850  break;
1851  }
1852  data += r;
1853  size -= r;
1854  lace_size[n] = lace_size[n - 1] + snum;
1855  total += lace_size[n];
1856  }
1857  if (size <= total) {
1858  res = AVERROR_INVALIDDATA;
1859  break;
1860  }
1861  lace_size[*laces - 1] = size - total;
1862  break;
1863  }
1864  }
1865 
1866  *buf = data;
1867  *lace_buf = lace_size;
1868  *buf_size = size;
1869 
1870  return res;
1871 }
1872 
1874  MatroskaTrack *track,
1875  AVStream *st,
1876  uint8_t *data, int size,
1877  uint64_t timecode, uint64_t duration,
1878  int64_t pos)
1879 {
1880  int a = st->codec->block_align;
1881  int sps = track->audio.sub_packet_size;
1882  int cfs = track->audio.coded_framesize;
1883  int h = track->audio.sub_packet_h;
1884  int y = track->audio.sub_packet_cnt;
1885  int w = track->audio.frame_size;
1886  int x;
1887 
1888  if (!track->audio.pkt_cnt) {
1889  if (track->audio.sub_packet_cnt == 0)
1890  track->audio.buf_timecode = timecode;
1891  if (st->codec->codec_id == AV_CODEC_ID_RA_288) {
1892  if (size < cfs * h / 2) {
1893  av_log(matroska->ctx, AV_LOG_ERROR,
1894  "Corrupt int4 RM-style audio packet size\n");
1895  return AVERROR_INVALIDDATA;
1896  }
1897  for (x=0; x<h/2; x++)
1898  memcpy(track->audio.buf+x*2*w+y*cfs,
1899  data+x*cfs, cfs);
1900  } else if (st->codec->codec_id == AV_CODEC_ID_SIPR) {
1901  if (size < w) {
1902  av_log(matroska->ctx, AV_LOG_ERROR,
1903  "Corrupt sipr RM-style audio packet size\n");
1904  return AVERROR_INVALIDDATA;
1905  }
1906  memcpy(track->audio.buf + y*w, data, w);
1907  } else {
1908  if (size < sps * w / sps) {
1909  av_log(matroska->ctx, AV_LOG_ERROR,
1910  "Corrupt generic RM-style audio packet size\n");
1911  return AVERROR_INVALIDDATA;
1912  }
1913  for (x=0; x<w/sps; x++)
1914  memcpy(track->audio.buf+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), data+x*sps, sps);
1915  }
1916 
1917  if (++track->audio.sub_packet_cnt >= h) {
1918  if (st->codec->codec_id == AV_CODEC_ID_SIPR)
1919  ff_rm_reorder_sipr_data(track->audio.buf, h, w);
1920  track->audio.sub_packet_cnt = 0;
1921  track->audio.pkt_cnt = h*w / a;
1922  }
1923  }
1924 
1925  while (track->audio.pkt_cnt) {
1926  AVPacket *pkt = av_mallocz(sizeof(AVPacket));
1927  av_new_packet(pkt, a);
1928  memcpy(pkt->data, track->audio.buf
1929  + a * (h*w / a - track->audio.pkt_cnt--), a);
1930  pkt->pts = track->audio.buf_timecode;
1932  pkt->pos = pos;
1933  pkt->stream_index = st->index;
1934  dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
1935  }
1936 
1937  return 0;
1938 }
1940  MatroskaTrack *track,
1941  AVStream *st,
1942  uint8_t *data, int pkt_size,
1943  uint64_t timecode, uint64_t duration,
1944  int64_t pos, int is_keyframe)
1945 {
1946  MatroskaTrackEncoding *encodings = track->encodings.elem;
1947  uint8_t *pkt_data = data;
1948  int offset = 0, res;
1949  AVPacket *pkt;
1950 
1951  if (encodings && encodings->scope & 1) {
1952  res = matroska_decode_buffer(&pkt_data, &pkt_size, track);
1953  if (res < 0)
1954  return res;
1955  }
1956 
1957  if (st->codec->codec_id == AV_CODEC_ID_PRORES)
1958  offset = 8;
1959 
1960  pkt = av_mallocz(sizeof(AVPacket));
1961  /* XXX: prevent data copy... */
1962  if (av_new_packet(pkt, pkt_size + offset) < 0) {
1963  av_free(pkt);
1964  return AVERROR(ENOMEM);
1965  }
1966 
1967  if (st->codec->codec_id == AV_CODEC_ID_PRORES) {
1968  uint8_t *buf = pkt->data;
1969  bytestream_put_be32(&buf, pkt_size);
1970  bytestream_put_be32(&buf, MKBETAG('i', 'c', 'p', 'f'));
1971  }
1972 
1973  memcpy(pkt->data + offset, pkt_data, pkt_size);
1974 
1975  if (pkt_data != data)
1976  av_free(pkt_data);
1977 
1978  pkt->flags = is_keyframe;
1979  pkt->stream_index = st->index;
1980 
1981  if (track->ms_compat)
1982  pkt->dts = timecode;
1983  else
1984  pkt->pts = timecode;
1985  pkt->pos = pos;
1986  if (st->codec->codec_id == AV_CODEC_ID_TEXT)
1988  else if (track->type != MATROSKA_TRACK_TYPE_SUBTITLE)
1989  pkt->duration = duration;
1990 
1991  if (st->codec->codec_id == AV_CODEC_ID_SSA)
1992  matroska_fix_ass_packet(matroska, pkt, duration);
1993 
1994  if (matroska->prev_pkt &&
1995  timecode != AV_NOPTS_VALUE &&
1996  matroska->prev_pkt->pts == timecode &&
1997  matroska->prev_pkt->stream_index == st->index &&
1998  st->codec->codec_id == AV_CODEC_ID_SSA)
1999  matroska_merge_packets(matroska->prev_pkt, pkt);
2000  else {
2001  dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
2002  matroska->prev_pkt = pkt;
2003  }
2004 
2005  return 0;
2006 }
2007 
2009  int size, int64_t pos, uint64_t cluster_time,
2010  uint64_t block_duration, int is_keyframe,
2011  int64_t cluster_pos)
2012 {
2013  uint64_t timecode = AV_NOPTS_VALUE;
2014  MatroskaTrack *track;
2015  int res = 0;
2016  AVStream *st;
2017  int16_t block_time;
2018  uint32_t *lace_size = NULL;
2019  int n, flags, laces = 0;
2020  uint64_t num, duration;
2021 
2022  if ((n = matroska_ebmlnum_uint(matroska, data, size, &num)) < 0) {
2023  av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
2024  return n;
2025  }
2026  data += n;
2027  size -= n;
2028 
2029  track = matroska_find_track_by_num(matroska, num);
2030  if (!track || !track->stream) {
2031  av_log(matroska->ctx, AV_LOG_INFO,
2032  "Invalid stream %"PRIu64" or size %u\n", num, size);
2033  return AVERROR_INVALIDDATA;
2034  } else if (size <= 3)
2035  return 0;
2036  st = track->stream;
2037  if (st->discard >= AVDISCARD_ALL)
2038  return res;
2039 
2040  block_time = AV_RB16(data);
2041  data += 2;
2042  flags = *data++;
2043  size -= 3;
2044  if (is_keyframe == -1)
2045  is_keyframe = flags & 0x80 ? AV_PKT_FLAG_KEY : 0;
2046 
2047  if (cluster_time != (uint64_t)-1
2048  && (block_time >= 0 || cluster_time >= -block_time)) {
2049  timecode = cluster_time + block_time;
2050  if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE
2051  && timecode < track->end_timecode)
2052  is_keyframe = 0; /* overlapping subtitles are not key frame */
2053  if (is_keyframe)
2054  av_add_index_entry(st, cluster_pos, timecode, 0,0,AVINDEX_KEYFRAME);
2055  }
2056 
2057  if (matroska->skip_to_keyframe && track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
2058  if (!is_keyframe || timecode < matroska->skip_to_timecode)
2059  return res;
2060  matroska->skip_to_keyframe = 0;
2061  }
2062 
2063  res = matroska_parse_laces(matroska, &data, &size, (flags & 0x06) >> 1,
2064  &lace_size, &laces);
2065 
2066  if (res)
2067  goto end;
2068 
2069  if (block_duration != AV_NOPTS_VALUE) {
2070  duration = block_duration / laces;
2071  if (block_duration != duration * laces) {
2072  av_log(matroska->ctx, AV_LOG_WARNING,
2073  "Incorrect block_duration, possibly corrupted container");
2074  }
2075  } else {
2076  duration = track->default_duration / matroska->time_scale;
2077  block_duration = duration * laces;
2078  }
2079 
2080  if (timecode != AV_NOPTS_VALUE)
2081  track->end_timecode =
2082  FFMAX(track->end_timecode, timecode + block_duration);
2083 
2084  for (n = 0; n < laces; n++) {
2085  if ((st->codec->codec_id == AV_CODEC_ID_RA_288 ||
2086  st->codec->codec_id == AV_CODEC_ID_COOK ||
2087  st->codec->codec_id == AV_CODEC_ID_SIPR ||
2088  st->codec->codec_id == AV_CODEC_ID_ATRAC3) &&
2089  st->codec->block_align && track->audio.sub_packet_size) {
2090 
2091  res = matroska_parse_rm_audio(matroska, track, st, data,
2092  lace_size[n],
2093  timecode, duration, pos);
2094  if (res)
2095  goto end;
2096 
2097  } else {
2098  res = matroska_parse_frame(matroska, track, st, data, lace_size[n],
2099  timecode, duration,
2100  pos, !n? is_keyframe : 0);
2101  if (res)
2102  goto end;
2103  }
2104 
2105  if (timecode != AV_NOPTS_VALUE)
2106  timecode = duration ? timecode + duration : AV_NOPTS_VALUE;
2107  data += lace_size[n];
2108  }
2109 
2110 end:
2111  av_free(lace_size);
2112  return res;
2113 }
2114 
2116 {
2117  EbmlList *blocks_list;
2118  MatroskaBlock *blocks;
2119  int i, res;
2120  res = ebml_parse(matroska,
2121  matroska_cluster_incremental_parsing,
2122  &matroska->current_cluster);
2123  if (res == 1) {
2124  /* New Cluster */
2125  if (matroska->current_cluster_pos)
2126  ebml_level_end(matroska);
2127  ebml_free(matroska_cluster, &matroska->current_cluster);
2128  memset(&matroska->current_cluster, 0, sizeof(MatroskaCluster));
2129  matroska->current_cluster_num_blocks = 0;
2130  matroska->current_cluster_pos = avio_tell(matroska->ctx->pb);
2131  matroska->prev_pkt = NULL;
2132  /* sizeof the ID which was already read */
2133  if (matroska->current_id)
2134  matroska->current_cluster_pos -= 4;
2135  res = ebml_parse(matroska,
2136  matroska_clusters_incremental,
2137  &matroska->current_cluster);
2138  /* Try parsing the block again. */
2139  if (res == 1)
2140  res = ebml_parse(matroska,
2141  matroska_cluster_incremental_parsing,
2142  &matroska->current_cluster);
2143  }
2144 
2145  if (!res &&
2146  matroska->current_cluster_num_blocks <
2147  matroska->current_cluster.blocks.nb_elem) {
2148  blocks_list = &matroska->current_cluster.blocks;
2149  blocks = blocks_list->elem;
2150 
2151  matroska->current_cluster_num_blocks = blocks_list->nb_elem;
2152  i = blocks_list->nb_elem - 1;
2153  if (blocks[i].bin.size > 0 && blocks[i].bin.data) {
2154  int is_keyframe = blocks[i].non_simple ? !blocks[i].reference : -1;
2155  if (!blocks[i].non_simple)
2156  blocks[i].duration = AV_NOPTS_VALUE;
2157  res = matroska_parse_block(matroska,
2158  blocks[i].bin.data, blocks[i].bin.size,
2159  blocks[i].bin.pos,
2160  matroska->current_cluster.timecode,
2161  blocks[i].duration, is_keyframe,
2162  matroska->current_cluster_pos);
2163  }
2164  }
2165 
2166  if (res < 0) matroska->done = 1;
2167  return res;
2168 }
2169 
2171 {
2172  MatroskaCluster cluster = { 0 };
2173  EbmlList *blocks_list;
2174  MatroskaBlock *blocks;
2175  int i, res;
2176  int64_t pos;
2177  if (!matroska->contains_ssa)
2178  return matroska_parse_cluster_incremental(matroska);
2179  pos = avio_tell(matroska->ctx->pb);
2180  matroska->prev_pkt = NULL;
2181  if (matroska->current_id)
2182  pos -= 4; /* sizeof the ID which was already read */
2183  res = ebml_parse(matroska, matroska_clusters, &cluster);
2184  blocks_list = &cluster.blocks;
2185  blocks = blocks_list->elem;
2186  for (i=0; i<blocks_list->nb_elem && !res; i++)
2187  if (blocks[i].bin.size > 0 && blocks[i].bin.data) {
2188  int is_keyframe = blocks[i].non_simple ? !blocks[i].reference : -1;
2189  if (!blocks[i].non_simple)
2190  blocks[i].duration = AV_NOPTS_VALUE;
2191  res=matroska_parse_block(matroska,
2192  blocks[i].bin.data, blocks[i].bin.size,
2193  blocks[i].bin.pos, cluster.timecode,
2194  blocks[i].duration, is_keyframe,
2195  pos);
2196  }
2197  ebml_free(matroska_cluster, &cluster);
2198  if (res < 0) matroska->done = 1;
2199  return res;
2200 }
2201 
2203 {
2204  MatroskaDemuxContext *matroska = s->priv_data;
2205  int ret = 0;
2206 
2207  while (!ret && matroska_deliver_packet(matroska, pkt)) {
2208  if (matroska->done)
2209  return AVERROR_EOF;
2210  ret = matroska_parse_cluster(matroska);
2211  }
2212 
2213  if (ret == AVERROR_INVALIDDATA && pkt->data) {
2214  pkt->flags |= AV_PKT_FLAG_CORRUPT;
2215  return 0;
2216  }
2217 
2218  return ret;
2219 }
2220 
2221 static int matroska_read_seek(AVFormatContext *s, int stream_index,
2222  int64_t timestamp, int flags)
2223 {
2224  MatroskaDemuxContext *matroska = s->priv_data;
2225  MatroskaTrack *tracks = matroska->tracks.elem;
2226  AVStream *st = s->streams[stream_index];
2227  int i, index, index_sub, index_min;
2228 
2229  /* Parse the CUES now since we need the index data to seek. */
2230  if (matroska->cues_parsing_deferred) {
2231  matroska_parse_cues(matroska);
2232  matroska->cues_parsing_deferred = 0;
2233  }
2234 
2235  if (!st->nb_index_entries)
2236  return 0;
2237  timestamp = FFMAX(timestamp, st->index_entries[0].timestamp);
2238 
2239  if ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
2240  avio_seek(s->pb, st->index_entries[st->nb_index_entries-1].pos, SEEK_SET);
2241  matroska->current_id = 0;
2242  while ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
2243  matroska_clear_queue(matroska);
2244  if (matroska_parse_cluster(matroska) < 0)
2245  break;
2246  }
2247  }
2248 
2249  matroska_clear_queue(matroska);
2250  if (index < 0)
2251  return 0;
2252 
2253  index_min = index;
2254  for (i=0; i < matroska->tracks.nb_elem; i++) {
2255  tracks[i].audio.pkt_cnt = 0;
2256  tracks[i].audio.sub_packet_cnt = 0;
2257  tracks[i].audio.buf_timecode = AV_NOPTS_VALUE;
2258  tracks[i].end_timecode = 0;
2259  if (tracks[i].type == MATROSKA_TRACK_TYPE_SUBTITLE
2260  && !tracks[i].stream->discard != AVDISCARD_ALL) {
2261  index_sub = av_index_search_timestamp(tracks[i].stream, st->index_entries[index].timestamp, AVSEEK_FLAG_BACKWARD);
2262  if (index_sub >= 0
2263  && st->index_entries[index_sub].pos < st->index_entries[index_min].pos
2264  && st->index_entries[index].timestamp - st->index_entries[index_sub].timestamp < 30000000000/matroska->time_scale)
2265  index_min = index_sub;
2266  }
2267  }
2268 
2269  avio_seek(s->pb, st->index_entries[index_min].pos, SEEK_SET);
2270  matroska->current_id = 0;
2271  matroska->skip_to_keyframe = !(flags & AVSEEK_FLAG_ANY);
2272  matroska->skip_to_timecode = st->index_entries[index].timestamp;
2273  matroska->done = 0;
2274  ff_update_cur_dts(s, st, st->index_entries[index].timestamp);
2275  return 0;
2276 }
2277 
2279 {
2280  MatroskaDemuxContext *matroska = s->priv_data;
2281  MatroskaTrack *tracks = matroska->tracks.elem;
2282  int n;
2283 
2284  matroska_clear_queue(matroska);
2285 
2286  for (n=0; n < matroska->tracks.nb_elem; n++)
2287  if (tracks[n].type == MATROSKA_TRACK_TYPE_AUDIO)
2288  av_free(tracks[n].audio.buf);
2289  ebml_free(matroska_cluster, &matroska->current_cluster);
2290  ebml_free(matroska_segment, matroska);
2291 
2292  return 0;
2293 }
2294 
2296  .name = "matroska,webm",
2297  .long_name = NULL_IF_CONFIG_SMALL("Matroska / WebM"),
2298  .priv_data_size = sizeof(MatroskaDemuxContext),
2304 };
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:1221
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:1187
#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:1724
#define MATROSKA_ID_VIDEODISPLAYHEIGHT
Definition: matroska.h:106
uint64_t version
Definition: matroskadec.c:92
AVInputFormat ff_matroska_demuxer
Definition: matroskadec.c:2295
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:1393
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:2126
#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:760
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:3283
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
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 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:2815
#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:1321
#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:1346
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:2008
#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:2115
#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:1109
#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:2170
static int ebml_parse_nest(MatroskaDemuxContext *matroska, EbmlSyntax *syntax, void *data)
Definition: matroskadec.c:811
#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:1435
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:749
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:1873
#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:2736
#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:901
const CodecMime ff_mkv_mime_tags[]
Definition: matroska.c:88
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:1356
static void matroska_parse_cues(MatroskaDemuxContext *matroska)
Definition: matroskadec.c:1299
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:1272
#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
static int ebml_parse_elem(MatroskaDemuxContext *matroska, EbmlSyntax *syntax, void *data)
Definition: matroskadec.c:836
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:970
#define CONFIG_ZLIB
Definition: config.h:326
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:2278
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:984
#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:928
#define EBML_ID_VOID
Definition: matroska.h:45
static void matroska_convert_tag(AVFormatContext *s, EbmlList *list, AVDictionary **metadata, char *prefix)
Definition: matroskadec.c:1154
#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:2221
static EbmlSyntax matroska_seekhead[]
Definition: matroskadec.c:476
Stream structure.
Definition: avformat.h:622
#define CONFIG_BZLIB
Definition: config.h:267
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:727
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:1766
#define MATROSKA_ID_CUETIME
Definition: matroska.h:138
static int matroska_read_packet(AVFormatContext *s, AVPacket *pkt)
Definition: matroskadec.c:2202
static EbmlSyntax matroska_blockgroup[]
Definition: matroskadec.c:498
static int ebml_parse(MatroskaDemuxContext *matroska, EbmlSyntax *syntax, void *data)
Definition: matroskadec.c:798
#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:779
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:100
#define MATROSKA_ID_CODECID
Definition: matroska.h:83
static EbmlSyntax matroska_clusters_incremental[]
Definition: matroskadec.c:548
#define CONFIG_LZO
Definition: config.h:304
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:1140
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:1335
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:1752
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:1939
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