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 "rm.h"
39 #include "matroska.h"
40 #include "libavcodec/mpeg4audio.h"
41 #include "libavutil/intfloat.h"
42 #include "libavutil/intreadwrite.h"
43 #include "libavutil/avstring.h"
44 #include "libavutil/lzo.h"
45 #include "libavutil/dict.h"
46 #if CONFIG_ZLIB
47 #include <zlib.h>
48 #endif
49 #if CONFIG_BZLIB
50 #include <bzlib.h>
51 #endif
52 
53 typedef enum {
64 } EbmlType;
65 
66 typedef const struct EbmlSyntax {
67  uint32_t id;
71  union {
72  uint64_t u;
73  double f;
74  const char *s;
75  const struct EbmlSyntax *n;
76  } def;
77 } EbmlSyntax;
78 
79 typedef struct {
80  int nb_elem;
81  void *elem;
82 } EbmlList;
83 
84 typedef struct {
85  int size;
86  uint8_t *data;
87  int64_t pos;
88 } EbmlBin;
89 
90 typedef struct {
91  uint64_t version;
92  uint64_t max_size;
93  uint64_t id_length;
94  char *doctype;
95  uint64_t doctype_version;
96 } Ebml;
97 
98 typedef struct {
99  uint64_t algo;
102 
103 typedef struct {
104  uint64_t scope;
105  uint64_t type;
108 
109 typedef struct {
110  double frame_rate;
111  uint64_t display_width;
112  uint64_t display_height;
113  uint64_t pixel_width;
114  uint64_t pixel_height;
115  uint64_t fourcc;
117 
118 typedef struct {
119  double samplerate;
121  uint64_t bitdepth;
122  uint64_t channels;
123 
124  /* real audio header (extracted from extradata) */
130  int pkt_cnt;
131  uint64_t buf_timecode;
132  uint8_t *buf;
134 
135 typedef struct {
136  uint64_t num;
137  uint64_t uid;
138  uint64_t type;
139  char *name;
140  char *codec_id;
142  char *language;
143  double time_scale;
145  uint64_t flag_default;
146  uint64_t flag_forced;
150 
152  int64_t end_timecode;
154 } MatroskaTrack;
155 
156 typedef struct {
157  uint64_t uid;
158  char *filename;
159  char *mime;
161 
164 
165 typedef struct {
166  uint64_t start;
167  uint64_t end;
168  uint64_t uid;
169  char *title;
170 
173 
174 typedef struct {
175  uint64_t track;
176  uint64_t pos;
178 
179 typedef struct {
180  uint64_t time;
182 } MatroskaIndex;
183 
184 typedef struct {
185  char *name;
186  char *string;
187  char *lang;
188  uint64_t def;
190 } MatroskaTag;
191 
192 typedef struct {
193  char *type;
194  uint64_t typevalue;
195  uint64_t trackuid;
196  uint64_t chapteruid;
197  uint64_t attachuid;
199 
200 typedef struct {
203 } MatroskaTags;
204 
205 typedef struct {
206  uint64_t id;
207  uint64_t pos;
209 
210 typedef struct {
211  uint64_t start;
212  uint64_t length;
213 } MatroskaLevel;
214 
215 typedef struct {
217 
218  /* EBML stuff */
221  int level_up;
222  uint32_t current_id;
223 
224  uint64_t time_scale;
225  double duration;
226  char *title;
233 
234  /* byte position of the segment inside the stream */
235  int64_t segment_start;
236 
237  /* the packet queue */
241 
242  int done;
243 
244  /* What to skip before effectively reading a packet. */
247 
248  /* File has a CUES element, but we defer parsing until it is needed. */
251 
252 typedef struct {
253  uint64_t duration;
254  int64_t reference;
255  uint64_t non_simple;
257 } MatroskaBlock;
258 
259 typedef struct {
260  uint64_t timecode;
263 
265  { EBML_ID_EBMLREADVERSION, EBML_UINT, 0, offsetof(Ebml,version), {.u=EBML_VERSION} },
266  { EBML_ID_EBMLMAXSIZELENGTH, EBML_UINT, 0, offsetof(Ebml,max_size), {.u=8} },
267  { EBML_ID_EBMLMAXIDLENGTH, EBML_UINT, 0, offsetof(Ebml,id_length), {.u=4} },
268  { EBML_ID_DOCTYPE, EBML_STR, 0, offsetof(Ebml,doctype), {.s="(none)"} },
269  { EBML_ID_DOCTYPEREADVERSION, EBML_UINT, 0, offsetof(Ebml,doctype_version), {.u=1} },
272  { 0 }
273 };
274 
276  { EBML_ID_HEADER, EBML_NEST, 0, 0, {.n=ebml_header} },
277  { 0 }
278 };
279 
281  { MATROSKA_ID_TIMECODESCALE, EBML_UINT, 0, offsetof(MatroskaDemuxContext,time_scale), {.u=1000000} },
283  { MATROSKA_ID_TITLE, EBML_UTF8, 0, offsetof(MatroskaDemuxContext,title) },
288  { 0 }
289 };
290 
293  { MATROSKA_ID_VIDEODISPLAYWIDTH, EBML_UINT, 0, offsetof(MatroskaTrackVideo,display_width) },
294  { MATROSKA_ID_VIDEODISPLAYHEIGHT, EBML_UINT, 0, offsetof(MatroskaTrackVideo,display_height) },
295  { MATROSKA_ID_VIDEOPIXELWIDTH, EBML_UINT, 0, offsetof(MatroskaTrackVideo,pixel_width) },
296  { MATROSKA_ID_VIDEOPIXELHEIGHT, EBML_UINT, 0, offsetof(MatroskaTrackVideo,pixel_height) },
297  { MATROSKA_ID_VIDEOCOLORSPACE, EBML_UINT, 0, offsetof(MatroskaTrackVideo,fourcc) },
306  { 0 }
307 };
308 
310  { MATROSKA_ID_AUDIOSAMPLINGFREQ, EBML_FLOAT,0, offsetof(MatroskaTrackAudio,samplerate), {.f=8000.0} },
311  { MATROSKA_ID_AUDIOOUTSAMPLINGFREQ,EBML_FLOAT,0,offsetof(MatroskaTrackAudio,out_samplerate) },
313  { MATROSKA_ID_AUDIOCHANNELS, EBML_UINT, 0, offsetof(MatroskaTrackAudio,channels), {.u=1} },
314  { 0 }
315 };
316 
320  { 0 }
321 };
322 
324  { MATROSKA_ID_ENCODINGSCOPE, EBML_UINT, 0, offsetof(MatroskaTrackEncoding,scope), {.u=1} },
325  { MATROSKA_ID_ENCODINGTYPE, EBML_UINT, 0, offsetof(MatroskaTrackEncoding,type), {.u=0} },
326  { MATROSKA_ID_ENCODINGCOMPRESSION,EBML_NEST, 0, offsetof(MatroskaTrackEncoding,compression), {.n=matroska_track_encoding_compression} },
328  { 0 }
329 };
330 
332  { MATROSKA_ID_TRACKCONTENTENCODING, EBML_NEST, sizeof(MatroskaTrackEncoding), offsetof(MatroskaTrack,encodings), {.n=matroska_track_encoding} },
333  { 0 }
334 };
335 
337  { MATROSKA_ID_TRACKNUMBER, EBML_UINT, 0, offsetof(MatroskaTrack,num) },
339  { MATROSKA_ID_TRACKUID, EBML_UINT, 0, offsetof(MatroskaTrack,uid) },
340  { MATROSKA_ID_TRACKTYPE, EBML_UINT, 0, offsetof(MatroskaTrack,type) },
342  { MATROSKA_ID_CODECPRIVATE, EBML_BIN, 0, offsetof(MatroskaTrack,codec_priv) },
343  { MATROSKA_ID_TRACKLANGUAGE, EBML_UTF8, 0, offsetof(MatroskaTrack,language), {.s="eng"} },
344  { MATROSKA_ID_TRACKDEFAULTDURATION, EBML_UINT, 0, offsetof(MatroskaTrack,default_duration) },
345  { MATROSKA_ID_TRACKTIMECODESCALE, EBML_FLOAT,0, offsetof(MatroskaTrack,time_scale), {.f=1.0} },
346  { MATROSKA_ID_TRACKFLAGDEFAULT, EBML_UINT, 0, offsetof(MatroskaTrack,flag_default), {.u=1} },
347  { MATROSKA_ID_TRACKFLAGFORCED, EBML_UINT, 0, offsetof(MatroskaTrack,flag_forced), {.u=0} },
348  { MATROSKA_ID_TRACKVIDEO, EBML_NEST, 0, offsetof(MatroskaTrack,video), {.n=matroska_track_video} },
349  { MATROSKA_ID_TRACKAUDIO, EBML_NEST, 0, offsetof(MatroskaTrack,audio), {.n=matroska_track_audio} },
350  { MATROSKA_ID_TRACKCONTENTENCODINGS,EBML_NEST, 0, 0, {.n=matroska_track_encodings} },
360  { 0 }
361 };
362 
364  { MATROSKA_ID_TRACKENTRY, EBML_NEST, sizeof(MatroskaTrack), offsetof(MatroskaDemuxContext,tracks), {.n=matroska_track} },
365  { 0 }
366 };
367 
369  { MATROSKA_ID_FILEUID, EBML_UINT, 0, offsetof(MatroskaAttachement,uid) },
370  { MATROSKA_ID_FILENAME, EBML_UTF8, 0, offsetof(MatroskaAttachement,filename) },
371  { MATROSKA_ID_FILEMIMETYPE, EBML_STR, 0, offsetof(MatroskaAttachement,mime) },
372  { MATROSKA_ID_FILEDATA, EBML_BIN, 0, offsetof(MatroskaAttachement,bin) },
374  { 0 }
375 };
376 
378  { MATROSKA_ID_ATTACHEDFILE, EBML_NEST, sizeof(MatroskaAttachement), offsetof(MatroskaDemuxContext,attachments), {.n=matroska_attachment} },
379  { 0 }
380 };
381 
383  { MATROSKA_ID_CHAPSTRING, EBML_UTF8, 0, offsetof(MatroskaChapter,title) },
385  { 0 }
386 };
387 
391  { MATROSKA_ID_CHAPTERUID, EBML_UINT, 0, offsetof(MatroskaChapter,uid) },
392  { MATROSKA_ID_CHAPTERDISPLAY, EBML_NEST, 0, 0, {.n=matroska_chapter_display} },
397  { 0 }
398 };
399 
401  { MATROSKA_ID_CHAPTERATOM, EBML_NEST, sizeof(MatroskaChapter), offsetof(MatroskaDemuxContext,chapters), {.n=matroska_chapter_entry} },
406  { 0 }
407 };
408 
410  { MATROSKA_ID_EDITIONENTRY, EBML_NEST, 0, 0, {.n=matroska_chapter} },
411  { 0 }
412 };
413 
415  { MATROSKA_ID_CUETRACK, EBML_UINT, 0, offsetof(MatroskaIndexPos,track) },
418  { 0 }
419 };
420 
422  { MATROSKA_ID_CUETIME, EBML_UINT, 0, offsetof(MatroskaIndex,time) },
423  { MATROSKA_ID_CUETRACKPOSITION, EBML_NEST, sizeof(MatroskaIndexPos), offsetof(MatroskaIndex,pos), {.n=matroska_index_pos} },
424  { 0 }
425 };
426 
428  { MATROSKA_ID_POINTENTRY, EBML_NEST, sizeof(MatroskaIndex), offsetof(MatroskaDemuxContext,index), {.n=matroska_index_entry} },
429  { 0 }
430 };
431 
433  { MATROSKA_ID_TAGNAME, EBML_UTF8, 0, offsetof(MatroskaTag,name) },
434  { MATROSKA_ID_TAGSTRING, EBML_UTF8, 0, offsetof(MatroskaTag,string) },
435  { MATROSKA_ID_TAGLANG, EBML_STR, 0, offsetof(MatroskaTag,lang), {.s="und"} },
436  { MATROSKA_ID_TAGDEFAULT, EBML_UINT, 0, offsetof(MatroskaTag,def) },
437  { MATROSKA_ID_TAGDEFAULT_BUG, EBML_UINT, 0, offsetof(MatroskaTag,def) },
438  { MATROSKA_ID_SIMPLETAG, EBML_NEST, sizeof(MatroskaTag), offsetof(MatroskaTag,sub), {.n=matroska_simpletag} },
439  { 0 }
440 };
441 
444  { MATROSKA_ID_TAGTARGETS_TYPEVALUE, EBML_UINT, 0, offsetof(MatroskaTagTarget,typevalue), {.u=50} },
445  { MATROSKA_ID_TAGTARGETS_TRACKUID, EBML_UINT, 0, offsetof(MatroskaTagTarget,trackuid) },
447  { MATROSKA_ID_TAGTARGETS_ATTACHUID, EBML_UINT, 0, offsetof(MatroskaTagTarget,attachuid) },
448  { 0 }
449 };
450 
452  { MATROSKA_ID_SIMPLETAG, EBML_NEST, sizeof(MatroskaTag), offsetof(MatroskaTags,tag), {.n=matroska_simpletag} },
453  { MATROSKA_ID_TAGTARGETS, EBML_NEST, 0, offsetof(MatroskaTags,target), {.n=matroska_tagtargets} },
454  { 0 }
455 };
456 
458  { MATROSKA_ID_TAG, EBML_NEST, sizeof(MatroskaTags), offsetof(MatroskaDemuxContext,tags), {.n=matroska_tag} },
459  { 0 }
460 };
461 
463  { MATROSKA_ID_SEEKID, EBML_UINT, 0, offsetof(MatroskaSeekhead,id) },
464  { MATROSKA_ID_SEEKPOSITION, EBML_UINT, 0, offsetof(MatroskaSeekhead,pos), {.u=-1} },
465  { 0 }
466 };
467 
469  { MATROSKA_ID_SEEKENTRY, EBML_NEST, sizeof(MatroskaSeekhead), offsetof(MatroskaDemuxContext,seekhead), {.n=matroska_seekhead_entry} },
470  { 0 }
471 };
472 
474  { MATROSKA_ID_INFO, EBML_NEST, 0, 0, {.n=matroska_info } },
475  { MATROSKA_ID_TRACKS, EBML_NEST, 0, 0, {.n=matroska_tracks } },
476  { MATROSKA_ID_ATTACHMENTS, EBML_NEST, 0, 0, {.n=matroska_attachments} },
477  { MATROSKA_ID_CHAPTERS, EBML_NEST, 0, 0, {.n=matroska_chapters } },
478  { MATROSKA_ID_CUES, EBML_NEST, 0, 0, {.n=matroska_index } },
479  { MATROSKA_ID_TAGS, EBML_NEST, 0, 0, {.n=matroska_tags } },
480  { MATROSKA_ID_SEEKHEAD, EBML_NEST, 0, 0, {.n=matroska_seekhead } },
482  { 0 }
483 };
484 
486  { MATROSKA_ID_SEGMENT, EBML_NEST, 0, 0, {.n=matroska_segment } },
487  { 0 }
488 };
489 
491  { MATROSKA_ID_BLOCK, EBML_BIN, 0, offsetof(MatroskaBlock,bin) },
492  { MATROSKA_ID_SIMPLEBLOCK, EBML_BIN, 0, offsetof(MatroskaBlock,bin) },
494  { MATROSKA_ID_BLOCKREFERENCE, EBML_UINT, 0, offsetof(MatroskaBlock,reference) },
495  { 1, EBML_UINT, 0, offsetof(MatroskaBlock,non_simple), {.u=1} },
496  { 0 }
497 };
498 
500  { MATROSKA_ID_CLUSTERTIMECODE,EBML_UINT,0, offsetof(MatroskaCluster,timecode) },
501  { MATROSKA_ID_BLOCKGROUP, EBML_NEST, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
502  { MATROSKA_ID_SIMPLEBLOCK, EBML_PASS, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
505  { 0 }
506 };
507 
509  { MATROSKA_ID_CLUSTER, EBML_NEST, 0, 0, {.n=matroska_cluster} },
514  { 0 }
515 };
516 
517 static const char *matroska_doctypes[] = { "matroska", "webm" };
518 
519 /*
520  * Return: Whether we reached the end of a level in the hierarchy or not.
521  */
523 {
524  AVIOContext *pb = matroska->ctx->pb;
525  int64_t pos = avio_tell(pb);
526 
527  if (matroska->num_levels > 0) {
528  MatroskaLevel *level = &matroska->levels[matroska->num_levels - 1];
529  if (pos - level->start >= level->length || matroska->current_id) {
530  matroska->num_levels--;
531  return 1;
532  }
533  }
534  return 0;
535 }
536 
537 /*
538  * Read: an "EBML number", which is defined as a variable-length
539  * array of bytes. The first byte indicates the length by giving a
540  * number of 0-bits followed by a one. The position of the first
541  * "one" bit inside the first byte indicates the length of this
542  * number.
543  * Returns: number of bytes read, < 0 on error
544  */
546  int max_size, uint64_t *number)
547 {
548  int read = 1, n = 1;
549  uint64_t total = 0;
550 
551  /* The first byte tells us the length in bytes - avio_r8() can normally
552  * return 0, but since that's not a valid first ebmlID byte, we can
553  * use it safely here to catch EOS. */
554  if (!(total = avio_r8(pb))) {
555  /* we might encounter EOS here */
556  if (!pb->eof_reached) {
557  int64_t pos = avio_tell(pb);
558  av_log(matroska->ctx, AV_LOG_ERROR,
559  "Read error at pos. %"PRIu64" (0x%"PRIx64")\n",
560  pos, pos);
561  }
562  return AVERROR(EIO); /* EOS or actual I/O error */
563  }
564 
565  /* get the length of the EBML number */
566  read = 8 - ff_log2_tab[total];
567  if (read > max_size) {
568  int64_t pos = avio_tell(pb) - 1;
569  av_log(matroska->ctx, AV_LOG_ERROR,
570  "Invalid EBML number size tag 0x%02x at pos %"PRIu64" (0x%"PRIx64")\n",
571  (uint8_t) total, pos, pos);
572  return AVERROR_INVALIDDATA;
573  }
574 
575  /* read out length */
576  total ^= 1 << ff_log2_tab[total];
577  while (n++ < read)
578  total = (total << 8) | avio_r8(pb);
579 
580  *number = total;
581 
582  return read;
583 }
584 
591  uint64_t *number)
592 {
593  int res = ebml_read_num(matroska, pb, 8, number);
594  if (res > 0 && *number + 1 == 1ULL << (7 * res))
595  *number = 0xffffffffffffffULL;
596  return res;
597 }
598 
599 /*
600  * Read the next element as an unsigned int.
601  * 0 is success, < 0 is failure.
602  */
603 static int ebml_read_uint(AVIOContext *pb, int size, uint64_t *num)
604 {
605  int n = 0;
606 
607  if (size > 8)
608  return AVERROR_INVALIDDATA;
609 
610  /* big-endian ordering; build up number */
611  *num = 0;
612  while (n++ < size)
613  *num = (*num << 8) | avio_r8(pb);
614 
615  return 0;
616 }
617 
618 /*
619  * Read the next element as a float.
620  * 0 is success, < 0 is failure.
621  */
622 static int ebml_read_float(AVIOContext *pb, int size, double *num)
623 {
624  if (size == 0) {
625  *num = 0;
626  } else if (size == 4) {
627  *num = av_int2float(avio_rb32(pb));
628  } else if (size == 8){
629  *num = av_int2double(avio_rb64(pb));
630  } else
631  return AVERROR_INVALIDDATA;
632 
633  return 0;
634 }
635 
636 /*
637  * Read the next element as an ASCII string.
638  * 0 is success, < 0 is failure.
639  */
640 static int ebml_read_ascii(AVIOContext *pb, int size, char **str)
641 {
642  char *res;
643 
644  /* EBML strings are usually not 0-terminated, so we allocate one
645  * byte more, read the string and NULL-terminate it ourselves. */
646  if (!(res = av_malloc(size + 1)))
647  return AVERROR(ENOMEM);
648  if (avio_read(pb, (uint8_t *) res, size) != size) {
649  av_free(res);
650  return AVERROR(EIO);
651  }
652  (res)[size] = '\0';
653  av_free(*str);
654  *str = res;
655 
656  return 0;
657 }
658 
659 /*
660  * Read the next element as binary data.
661  * 0 is success, < 0 is failure.
662  */
663 static int ebml_read_binary(AVIOContext *pb, int length, EbmlBin *bin)
664 {
665  av_free(bin->data);
666  if (!(bin->data = av_malloc(length)))
667  return AVERROR(ENOMEM);
668 
669  bin->size = length;
670  bin->pos = avio_tell(pb);
671  if (avio_read(pb, bin->data, length) != length) {
672  av_freep(&bin->data);
673  return AVERROR(EIO);
674  }
675 
676  return 0;
677 }
678 
679 /*
680  * Read the next element, but only the header. The contents
681  * are supposed to be sub-elements which can be read separately.
682  * 0 is success, < 0 is failure.
683  */
684 static int ebml_read_master(MatroskaDemuxContext *matroska, uint64_t length)
685 {
686  AVIOContext *pb = matroska->ctx->pb;
688 
689  if (matroska->num_levels >= EBML_MAX_DEPTH) {
690  av_log(matroska->ctx, AV_LOG_ERROR,
691  "File moves beyond max. allowed depth (%d)\n", EBML_MAX_DEPTH);
692  return AVERROR(ENOSYS);
693  }
694 
695  level = &matroska->levels[matroska->num_levels++];
696  level->start = avio_tell(pb);
697  level->length = length;
698 
699  return 0;
700 }
701 
702 /*
703  * Read signed/unsigned "EBML" numbers.
704  * Return: number of bytes processed, < 0 on error
705  */
707  uint8_t *data, uint32_t size, uint64_t *num)
708 {
709  AVIOContext pb;
710  ffio_init_context(&pb, data, size, 0, NULL, NULL, NULL, NULL);
711  return ebml_read_num(matroska, &pb, FFMIN(size, 8), num);
712 }
713 
714 /*
715  * Same as above, but signed.
716  */
718  uint8_t *data, uint32_t size, int64_t *num)
719 {
720  uint64_t unum;
721  int res;
722 
723  /* read as unsigned number first */
724  if ((res = matroska_ebmlnum_uint(matroska, data, size, &unum)) < 0)
725  return res;
726 
727  /* make signed (weird way) */
728  *num = unum - ((1LL << (7*res - 1)) - 1);
729 
730  return res;
731 }
732 
733 static int ebml_parse_elem(MatroskaDemuxContext *matroska,
734  EbmlSyntax *syntax, void *data);
735 
736 static int ebml_parse_id(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
737  uint32_t id, void *data)
738 {
739  int i;
740  for (i=0; syntax[i].id; i++)
741  if (id == syntax[i].id)
742  break;
743  if (!syntax[i].id && id == MATROSKA_ID_CLUSTER &&
744  matroska->num_levels > 0 &&
745  matroska->levels[matroska->num_levels-1].length == 0xffffffffffffff)
746  return 0; // we reached the end of an unknown size cluster
747  if (!syntax[i].id && id != EBML_ID_VOID && id != EBML_ID_CRC32)
748  av_log(matroska->ctx, AV_LOG_INFO, "Unknown entry 0x%X\n", id);
749  return ebml_parse_elem(matroska, &syntax[i], data);
750 }
751 
752 static int ebml_parse(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
753  void *data)
754 {
755  if (!matroska->current_id) {
756  uint64_t id;
757  int res = ebml_read_num(matroska, matroska->ctx->pb, 4, &id);
758  if (res < 0)
759  return res;
760  matroska->current_id = id | 1 << 7*res;
761  }
762  return ebml_parse_id(matroska, syntax, matroska->current_id, data);
763 }
764 
765 static int ebml_parse_nest(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
766  void *data)
767 {
768  int i, res = 0;
769 
770  for (i=0; syntax[i].id; i++)
771  switch (syntax[i].type) {
772  case EBML_UINT:
773  *(uint64_t *)((char *)data+syntax[i].data_offset) = syntax[i].def.u;
774  break;
775  case EBML_FLOAT:
776  *(double *)((char *)data+syntax[i].data_offset) = syntax[i].def.f;
777  break;
778  case EBML_STR:
779  case EBML_UTF8:
780  *(char **)((char *)data+syntax[i].data_offset) = av_strdup(syntax[i].def.s);
781  break;
782  }
783 
784  while (!res && !ebml_level_end(matroska))
785  res = ebml_parse(matroska, syntax, data);
786 
787  return res;
788 }
789 
791  EbmlSyntax *syntax, void *data)
792 {
793  static const uint64_t max_lengths[EBML_TYPE_COUNT] = {
794  [EBML_UINT] = 8,
795  [EBML_FLOAT] = 8,
796  // max. 16 MB for strings
797  [EBML_STR] = 0x1000000,
798  [EBML_UTF8] = 0x1000000,
799  // max. 256 MB for binary data
800  [EBML_BIN] = 0x10000000,
801  // no limits for anything else
802  };
803  AVIOContext *pb = matroska->ctx->pb;
804  uint32_t id = syntax->id;
805  uint64_t length;
806  int res;
807  void *newelem;
808 
809  data = (char *)data + syntax->data_offset;
810  if (syntax->list_elem_size) {
811  EbmlList *list = data;
812  newelem = av_realloc(list->elem, (list->nb_elem+1)*syntax->list_elem_size);
813  if (!newelem)
814  return AVERROR(ENOMEM);
815  list->elem = newelem;
816  data = (char*)list->elem + list->nb_elem*syntax->list_elem_size;
817  memset(data, 0, syntax->list_elem_size);
818  list->nb_elem++;
819  }
820 
821  if (syntax->type != EBML_PASS && syntax->type != EBML_STOP) {
822  matroska->current_id = 0;
823  if ((res = ebml_read_length(matroska, pb, &length)) < 0)
824  return res;
825  if (max_lengths[syntax->type] && length > max_lengths[syntax->type]) {
826  av_log(matroska->ctx, AV_LOG_ERROR,
827  "Invalid length 0x%"PRIx64" > 0x%"PRIx64" for syntax element %i\n",
828  length, max_lengths[syntax->type], syntax->type);
829  return AVERROR_INVALIDDATA;
830  }
831  }
832 
833  switch (syntax->type) {
834  case EBML_UINT: res = ebml_read_uint (pb, length, data); break;
835  case EBML_FLOAT: res = ebml_read_float (pb, length, data); break;
836  case EBML_STR:
837  case EBML_UTF8: res = ebml_read_ascii (pb, length, data); break;
838  case EBML_BIN: res = ebml_read_binary(pb, length, data); break;
839  case EBML_NEST: if ((res=ebml_read_master(matroska, length)) < 0)
840  return res;
841  if (id == MATROSKA_ID_SEGMENT)
842  matroska->segment_start = avio_tell(matroska->ctx->pb);
843  return ebml_parse_nest(matroska, syntax->def.n, data);
844  case EBML_PASS: return ebml_parse_id(matroska, syntax->def.n, id, data);
845  case EBML_STOP: return 1;
846  default: return avio_skip(pb,length)<0 ? AVERROR(EIO) : 0;
847  }
848  if (res == AVERROR_INVALIDDATA)
849  av_log(matroska->ctx, AV_LOG_ERROR, "Invalid element\n");
850  else if (res == AVERROR(EIO))
851  av_log(matroska->ctx, AV_LOG_ERROR, "Read error\n");
852  return res;
853 }
854 
855 static void ebml_free(EbmlSyntax *syntax, void *data)
856 {
857  int i, j;
858  for (i=0; syntax[i].id; i++) {
859  void *data_off = (char *)data + syntax[i].data_offset;
860  switch (syntax[i].type) {
861  case EBML_STR:
862  case EBML_UTF8: av_freep(data_off); break;
863  case EBML_BIN: av_freep(&((EbmlBin *)data_off)->data); break;
864  case EBML_NEST:
865  if (syntax[i].list_elem_size) {
866  EbmlList *list = data_off;
867  char *ptr = list->elem;
868  for (j=0; j<list->nb_elem; j++, ptr+=syntax[i].list_elem_size)
869  ebml_free(syntax[i].def.n, ptr);
870  av_free(list->elem);
871  } else
872  ebml_free(syntax[i].def.n, data_off);
873  default: break;
874  }
875  }
876 }
877 
878 
879 /*
880  * Autodetecting...
881  */
883 {
884  uint64_t total = 0;
885  int len_mask = 0x80, size = 1, n = 1, i;
886 
887  /* EBML header? */
888  if (AV_RB32(p->buf) != EBML_ID_HEADER)
889  return 0;
890 
891  /* length of header */
892  total = p->buf[4];
893  while (size <= 8 && !(total & len_mask)) {
894  size++;
895  len_mask >>= 1;
896  }
897  if (size > 8)
898  return 0;
899  total &= (len_mask - 1);
900  while (n < size)
901  total = (total << 8) | p->buf[4 + n++];
902 
903  /* Does the probe data contain the whole header? */
904  if (p->buf_size < 4 + size + total)
905  return 0;
906 
907  /* The header should contain a known document type. For now,
908  * we don't parse the whole header but simply check for the
909  * availability of that array of characters inside the header.
910  * Not fully fool-proof, but good enough. */
911  for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++) {
912  int probelen = strlen(matroska_doctypes[i]);
913  if (total < probelen)
914  continue;
915  for (n = 4+size; n <= 4+size+total-probelen; n++)
916  if (!memcmp(p->buf+n, matroska_doctypes[i], probelen))
917  return AVPROBE_SCORE_MAX;
918  }
919 
920  // probably valid EBML header but no recognized doctype
921  return AVPROBE_SCORE_MAX/2;
922 }
923 
925  int num)
926 {
927  MatroskaTrack *tracks = matroska->tracks.elem;
928  int i;
929 
930  for (i=0; i < matroska->tracks.nb_elem; i++)
931  if (tracks[i].num == num)
932  return &tracks[i];
933 
934  av_log(matroska->ctx, AV_LOG_ERROR, "Invalid track number %d\n", num);
935  return NULL;
936 }
937 
938 static int matroska_decode_buffer(uint8_t** buf, int* buf_size,
939  MatroskaTrack *track)
940 {
941  MatroskaTrackEncoding *encodings = track->encodings.elem;
942  uint8_t* data = *buf;
943  int isize = *buf_size;
944  uint8_t* pkt_data = NULL;
945  uint8_t* newpktdata;
946  int pkt_size = isize;
947  int result = 0;
948  int olen;
949 
950  if (pkt_size >= 10000000)
951  return -1;
952 
953  switch (encodings[0].compression.algo) {
955  return encodings[0].compression.settings.size;
957  do {
958  olen = pkt_size *= 3;
959  pkt_data = av_realloc(pkt_data, pkt_size+AV_LZO_OUTPUT_PADDING);
960  result = av_lzo1x_decode(pkt_data, &olen, data, &isize);
961  } while (result==AV_LZO_OUTPUT_FULL && pkt_size<10000000);
962  if (result)
963  goto failed;
964  pkt_size -= olen;
965  break;
966 #if CONFIG_ZLIB
968  z_stream zstream = {0};
969  if (inflateInit(&zstream) != Z_OK)
970  return -1;
971  zstream.next_in = data;
972  zstream.avail_in = isize;
973  do {
974  pkt_size *= 3;
975  newpktdata = av_realloc(pkt_data, pkt_size);
976  if (!newpktdata) {
977  inflateEnd(&zstream);
978  goto failed;
979  }
980  pkt_data = newpktdata;
981  zstream.avail_out = pkt_size - zstream.total_out;
982  zstream.next_out = pkt_data + zstream.total_out;
983  result = inflate(&zstream, Z_NO_FLUSH);
984  } while (result==Z_OK && pkt_size<10000000);
985  pkt_size = zstream.total_out;
986  inflateEnd(&zstream);
987  if (result != Z_STREAM_END)
988  goto failed;
989  break;
990  }
991 #endif
992 #if CONFIG_BZLIB
994  bz_stream bzstream = {0};
995  if (BZ2_bzDecompressInit(&bzstream, 0, 0) != BZ_OK)
996  return -1;
997  bzstream.next_in = data;
998  bzstream.avail_in = isize;
999  do {
1000  pkt_size *= 3;
1001  newpktdata = av_realloc(pkt_data, pkt_size);
1002  if (!newpktdata) {
1003  BZ2_bzDecompressEnd(&bzstream);
1004  goto failed;
1005  }
1006  pkt_data = newpktdata;
1007  bzstream.avail_out = pkt_size - bzstream.total_out_lo32;
1008  bzstream.next_out = pkt_data + bzstream.total_out_lo32;
1009  result = BZ2_bzDecompress(&bzstream);
1010  } while (result==BZ_OK && pkt_size<10000000);
1011  pkt_size = bzstream.total_out_lo32;
1012  BZ2_bzDecompressEnd(&bzstream);
1013  if (result != BZ_STREAM_END)
1014  goto failed;
1015  break;
1016  }
1017 #endif
1018  default:
1019  return -1;
1020  }
1021 
1022  *buf = pkt_data;
1023  *buf_size = pkt_size;
1024  return 0;
1025  failed:
1026  av_free(pkt_data);
1027  return -1;
1028 }
1029 
1031  AVPacket *pkt, uint64_t display_duration)
1032 {
1033  char *line, *layer, *ptr = pkt->data, *end = ptr+pkt->size;
1034  for (; *ptr!=',' && ptr<end-1; ptr++);
1035  if (*ptr == ',')
1036  layer = ++ptr;
1037  for (; *ptr!=',' && ptr<end-1; ptr++);
1038  if (*ptr == ',') {
1039  int64_t end_pts = pkt->pts + display_duration;
1040  int sc = matroska->time_scale * pkt->pts / 10000000;
1041  int ec = matroska->time_scale * end_pts / 10000000;
1042  int sh, sm, ss, eh, em, es, len;
1043  sh = sc/360000; sc -= 360000*sh;
1044  sm = sc/ 6000; sc -= 6000*sm;
1045  ss = sc/ 100; sc -= 100*ss;
1046  eh = ec/360000; ec -= 360000*eh;
1047  em = ec/ 6000; ec -= 6000*em;
1048  es = ec/ 100; ec -= 100*es;
1049  *ptr++ = '\0';
1050  len = 50 + end-ptr + FF_INPUT_BUFFER_PADDING_SIZE;
1051  if (!(line = av_malloc(len)))
1052  return;
1053  snprintf(line,len,"Dialogue: %s,%d:%02d:%02d.%02d,%d:%02d:%02d.%02d,%s\r\n",
1054  layer, sh, sm, ss, sc, eh, em, es, ec, ptr);
1055  av_free(pkt->data);
1056  pkt->data = line;
1057  pkt->size = strlen(line);
1058  }
1059 }
1060 
1062 {
1063  void *newdata = av_realloc(out->data, out->size+in->size);
1064  if (!newdata)
1065  return AVERROR(ENOMEM);
1066  out->data = newdata;
1067  memcpy(out->data+out->size, in->data, in->size);
1068  out->size += in->size;
1069  av_destruct_packet(in);
1070  av_free(in);
1071  return 0;
1072 }
1073 
1075  AVDictionary **metadata, char *prefix)
1076 {
1077  MatroskaTag *tags = list->elem;
1078  char key[1024];
1079  int i;
1080 
1081  for (i=0; i < list->nb_elem; i++) {
1082  const char *lang = strcmp(tags[i].lang, "und") ? tags[i].lang : NULL;
1083 
1084  if (!tags[i].name) {
1085  av_log(s, AV_LOG_WARNING, "Skipping invalid tag with no TagName.\n");
1086  continue;
1087  }
1088  if (prefix) snprintf(key, sizeof(key), "%s/%s", prefix, tags[i].name);
1089  else av_strlcpy(key, tags[i].name, sizeof(key));
1090  if (tags[i].def || !lang) {
1091  av_dict_set(metadata, key, tags[i].string, 0);
1092  if (tags[i].sub.nb_elem)
1093  matroska_convert_tag(s, &tags[i].sub, metadata, key);
1094  }
1095  if (lang) {
1096  av_strlcat(key, "-", sizeof(key));
1097  av_strlcat(key, lang, sizeof(key));
1098  av_dict_set(metadata, key, tags[i].string, 0);
1099  if (tags[i].sub.nb_elem)
1100  matroska_convert_tag(s, &tags[i].sub, metadata, key);
1101  }
1102  }
1104 }
1105 
1107 {
1108  MatroskaDemuxContext *matroska = s->priv_data;
1109  MatroskaTags *tags = matroska->tags.elem;
1110  int i, j;
1111 
1112  for (i=0; i < matroska->tags.nb_elem; i++) {
1113  if (tags[i].target.attachuid) {
1114  MatroskaAttachement *attachment = matroska->attachments.elem;
1115  for (j=0; j<matroska->attachments.nb_elem; j++)
1116  if (attachment[j].uid == tags[i].target.attachuid
1117  && attachment[j].stream)
1118  matroska_convert_tag(s, &tags[i].tag,
1119  &attachment[j].stream->metadata, NULL);
1120  } else if (tags[i].target.chapteruid) {
1121  MatroskaChapter *chapter = matroska->chapters.elem;
1122  for (j=0; j<matroska->chapters.nb_elem; j++)
1123  if (chapter[j].uid == tags[i].target.chapteruid
1124  && chapter[j].chapter)
1125  matroska_convert_tag(s, &tags[i].tag,
1126  &chapter[j].chapter->metadata, NULL);
1127  } else if (tags[i].target.trackuid) {
1128  MatroskaTrack *track = matroska->tracks.elem;
1129  for (j=0; j<matroska->tracks.nb_elem; j++)
1130  if (track[j].uid == tags[i].target.trackuid && track[j].stream)
1131  matroska_convert_tag(s, &tags[i].tag,
1132  &track[j].stream->metadata, NULL);
1133  } else {
1134  matroska_convert_tag(s, &tags[i].tag, &s->metadata,
1135  tags[i].target.type);
1136  }
1137  }
1138 }
1139 
1141 {
1142  EbmlList *seekhead_list = &matroska->seekhead;
1143  MatroskaSeekhead *seekhead = seekhead_list->elem;
1144  uint32_t level_up = matroska->level_up;
1145  int64_t before_pos = avio_tell(matroska->ctx->pb);
1146  uint32_t saved_id = matroska->current_id;
1148  int64_t offset;
1149  int ret = 0;
1150 
1151  if (idx >= seekhead_list->nb_elem
1152  || seekhead[idx].id == MATROSKA_ID_SEEKHEAD
1153  || seekhead[idx].id == MATROSKA_ID_CLUSTER)
1154  return 0;
1155 
1156  /* seek */
1157  offset = seekhead[idx].pos + matroska->segment_start;
1158  if (avio_seek(matroska->ctx->pb, offset, SEEK_SET) == offset) {
1159  /* We don't want to lose our seekhead level, so we add
1160  * a dummy. This is a crude hack. */
1161  if (matroska->num_levels == EBML_MAX_DEPTH) {
1162  av_log(matroska->ctx, AV_LOG_INFO,
1163  "Max EBML element depth (%d) reached, "
1164  "cannot parse further.\n", EBML_MAX_DEPTH);
1165  ret = AVERROR_INVALIDDATA;
1166  } else {
1167  level.start = 0;
1168  level.length = (uint64_t)-1;
1169  matroska->levels[matroska->num_levels] = level;
1170  matroska->num_levels++;
1171  matroska->current_id = 0;
1172 
1173  ret = ebml_parse(matroska, matroska_segment, matroska);
1174 
1175  /* remove dummy level */
1176  while (matroska->num_levels) {
1177  uint64_t length = matroska->levels[--matroska->num_levels].length;
1178  if (length == (uint64_t)-1)
1179  break;
1180  }
1181  }
1182  }
1183  /* seek back */
1184  avio_seek(matroska->ctx->pb, before_pos, SEEK_SET);
1185  matroska->level_up = level_up;
1186  matroska->current_id = saved_id;
1187 
1188  return ret;
1189 }
1190 
1192 {
1193  EbmlList *seekhead_list = &matroska->seekhead;
1194  int64_t before_pos = avio_tell(matroska->ctx->pb);
1195  int i;
1196 
1197  // we should not do any seeking in the streaming case
1198  if (!matroska->ctx->pb->seekable ||
1199  (matroska->ctx->flags & AVFMT_FLAG_IGNIDX))
1200  return;
1201 
1202  for (i = 0; i < seekhead_list->nb_elem; i++) {
1203  MatroskaSeekhead *seekhead = seekhead_list->elem;
1204  if (seekhead[i].pos <= before_pos)
1205  continue;
1206 
1207  // defer cues parsing until we actually need cue data.
1208  if (seekhead[i].id == MATROSKA_ID_CUES) {
1209  matroska->cues_parsing_deferred = 1;
1210  continue;
1211  }
1212 
1213  if (matroska_parse_seekhead_entry(matroska, i) < 0)
1214  break;
1215  }
1216 }
1217 
1219  EbmlList *seekhead_list = &matroska->seekhead;
1220  MatroskaSeekhead *seekhead = seekhead_list->elem;
1221  EbmlList *index_list;
1223  int index_scale = 1;
1224  int i, j;
1225 
1226  for (i = 0; i < seekhead_list->nb_elem; i++)
1227  if (seekhead[i].id == MATROSKA_ID_CUES)
1228  break;
1229  assert(i <= seekhead_list->nb_elem);
1230 
1231  matroska_parse_seekhead_entry(matroska, i);
1232 
1233  index_list = &matroska->index;
1234  index = index_list->elem;
1235  if (index_list->nb_elem
1236  && index[0].time > 1E14/matroska->time_scale) {
1237  av_log(matroska->ctx, AV_LOG_WARNING, "Working around broken index.\n");
1238  index_scale = matroska->time_scale;
1239  }
1240  for (i = 0; i < index_list->nb_elem; i++) {
1241  EbmlList *pos_list = &index[i].pos;
1242  MatroskaIndexPos *pos = pos_list->elem;
1243  for (j = 0; j < pos_list->nb_elem; j++) {
1244  MatroskaTrack *track = matroska_find_track_by_num(matroska, pos[j].track);
1245  if (track && track->stream)
1246  av_add_index_entry(track->stream,
1247  pos[j].pos + matroska->segment_start,
1248  index[i].time/index_scale, 0, 0,
1250  }
1251  }
1252 }
1253 
1255 {
1256  static const char * const aac_profiles[] = { "MAIN", "LC", "SSR" };
1257  int profile;
1258 
1259  for (profile=0; profile<FF_ARRAY_ELEMS(aac_profiles); profile++)
1260  if (strstr(codec_id, aac_profiles[profile]))
1261  break;
1262  return profile + 1;
1263 }
1264 
1265 static int matroska_aac_sri(int samplerate)
1266 {
1267  int sri;
1268 
1269  for (sri=0; sri<FF_ARRAY_ELEMS(avpriv_mpeg4audio_sample_rates); sri++)
1270  if (avpriv_mpeg4audio_sample_rates[sri] == samplerate)
1271  break;
1272  return sri;
1273 }
1274 
1276 {
1277  MatroskaDemuxContext *matroska = s->priv_data;
1278  EbmlList *attachements_list = &matroska->attachments;
1279  MatroskaAttachement *attachements;
1280  EbmlList *chapters_list = &matroska->chapters;
1281  MatroskaChapter *chapters;
1282  MatroskaTrack *tracks;
1283  uint64_t max_start = 0;
1284  Ebml ebml = { 0 };
1285  AVStream *st;
1286  int i, j, res;
1287 
1288  matroska->ctx = s;
1289 
1290  /* First read the EBML header. */
1291  if (ebml_parse(matroska, ebml_syntax, &ebml)
1292  || ebml.version > EBML_VERSION || ebml.max_size > sizeof(uint64_t)
1293  || ebml.id_length > sizeof(uint32_t) || ebml.doctype_version > 2) {
1294  av_log(matroska->ctx, AV_LOG_ERROR,
1295  "EBML header using unsupported features\n"
1296  "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
1297  ebml.version, ebml.doctype, ebml.doctype_version);
1298  ebml_free(ebml_syntax, &ebml);
1299  return AVERROR_PATCHWELCOME;
1300  }
1301  for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++)
1302  if (!strcmp(ebml.doctype, matroska_doctypes[i]))
1303  break;
1304  if (i >= FF_ARRAY_ELEMS(matroska_doctypes)) {
1305  av_log(s, AV_LOG_WARNING, "Unknown EBML doctype '%s'\n", ebml.doctype);
1306  }
1307  ebml_free(ebml_syntax, &ebml);
1308 
1309  /* The next thing is a segment. */
1310  if ((res = ebml_parse(matroska, matroska_segments, matroska)) < 0)
1311  return res;
1312  matroska_execute_seekhead(matroska);
1313 
1314  if (!matroska->time_scale)
1315  matroska->time_scale = 1000000;
1316  if (matroska->duration)
1317  matroska->ctx->duration = matroska->duration * matroska->time_scale
1318  * 1000 / AV_TIME_BASE;
1319  av_dict_set(&s->metadata, "title", matroska->title, 0);
1320 
1321  tracks = matroska->tracks.elem;
1322  for (i=0; i < matroska->tracks.nb_elem; i++) {
1323  MatroskaTrack *track = &tracks[i];
1325  EbmlList *encodings_list = &tracks->encodings;
1326  MatroskaTrackEncoding *encodings = encodings_list->elem;
1327  uint8_t *extradata = NULL;
1328  int extradata_size = 0;
1329  int extradata_offset = 0;
1330  AVIOContext b;
1331 
1332  /* Apply some sanity checks. */
1333  if (track->type != MATROSKA_TRACK_TYPE_VIDEO &&
1334  track->type != MATROSKA_TRACK_TYPE_AUDIO &&
1335  track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
1336  av_log(matroska->ctx, AV_LOG_INFO,
1337  "Unknown or unsupported track type %"PRIu64"\n",
1338  track->type);
1339  continue;
1340  }
1341  if (track->codec_id == NULL)
1342  continue;
1343 
1344  if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1345  if (!track->default_duration)
1346  track->default_duration = 1000000000/track->video.frame_rate;
1347  if (!track->video.display_width)
1348  track->video.display_width = track->video.pixel_width;
1349  if (!track->video.display_height)
1350  track->video.display_height = track->video.pixel_height;
1351  } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
1352  if (!track->audio.out_samplerate)
1353  track->audio.out_samplerate = track->audio.samplerate;
1354  }
1355  if (encodings_list->nb_elem > 1) {
1356  av_log(matroska->ctx, AV_LOG_ERROR,
1357  "Multiple combined encodings not supported");
1358  } else if (encodings_list->nb_elem == 1) {
1359  if (encodings[0].type ||
1360  (encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP &&
1361 #if CONFIG_ZLIB
1363 #endif
1364 #if CONFIG_BZLIB
1366 #endif
1368  encodings[0].scope = 0;
1369  av_log(matroska->ctx, AV_LOG_ERROR,
1370  "Unsupported encoding type");
1371  } else if (track->codec_priv.size && encodings[0].scope&2) {
1372  uint8_t *codec_priv = track->codec_priv.data;
1373  int offset = matroska_decode_buffer(&track->codec_priv.data,
1374  &track->codec_priv.size,
1375  track);
1376  if (offset < 0) {
1377  track->codec_priv.data = NULL;
1378  track->codec_priv.size = 0;
1379  av_log(matroska->ctx, AV_LOG_ERROR,
1380  "Failed to decode codec private data\n");
1381  } else if (offset > 0) {
1382  track->codec_priv.data = av_malloc(track->codec_priv.size + offset);
1383  memcpy(track->codec_priv.data,
1384  encodings[0].compression.settings.data, offset);
1385  memcpy(track->codec_priv.data+offset, codec_priv,
1386  track->codec_priv.size);
1387  track->codec_priv.size += offset;
1388  }
1389  if (codec_priv != track->codec_priv.data)
1390  av_free(codec_priv);
1391  }
1392  }
1393 
1394  for(j=0; ff_mkv_codec_tags[j].id != CODEC_ID_NONE; j++){
1395  if(!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
1396  strlen(ff_mkv_codec_tags[j].str))){
1397  codec_id= ff_mkv_codec_tags[j].id;
1398  break;
1399  }
1400  }
1401 
1402  st = track->stream = avformat_new_stream(s, NULL);
1403  if (st == NULL)
1404  return AVERROR(ENOMEM);
1405 
1406  if (!strcmp(track->codec_id, "V_MS/VFW/FOURCC")
1407  && track->codec_priv.size >= 40
1408  && track->codec_priv.data != NULL) {
1409  track->ms_compat = 1;
1410  track->video.fourcc = AV_RL32(track->codec_priv.data + 16);
1411  codec_id = ff_codec_get_id(ff_codec_bmp_tags, track->video.fourcc);
1412  extradata_offset = 40;
1413  } else if (!strcmp(track->codec_id, "A_MS/ACM")
1414  && track->codec_priv.size >= 14
1415  && track->codec_priv.data != NULL) {
1416  int ret;
1417  ffio_init_context(&b, track->codec_priv.data, track->codec_priv.size,
1418  0, NULL, NULL, NULL, NULL);
1419  ret = ff_get_wav_header(&b, st->codec, track->codec_priv.size);
1420  if (ret < 0)
1421  return ret;
1422  codec_id = st->codec->codec_id;
1423  extradata_offset = FFMIN(track->codec_priv.size, 18);
1424  } else if (!strcmp(track->codec_id, "V_QUICKTIME")
1425  && (track->codec_priv.size >= 86)
1426  && (track->codec_priv.data != NULL)) {
1427  track->video.fourcc = AV_RL32(track->codec_priv.data);
1428  codec_id=ff_codec_get_id(codec_movvideo_tags, track->video.fourcc);
1429  } else if (codec_id == CODEC_ID_PCM_S16BE) {
1430  switch (track->audio.bitdepth) {
1431  case 8: codec_id = CODEC_ID_PCM_U8; break;
1432  case 24: codec_id = CODEC_ID_PCM_S24BE; break;
1433  case 32: codec_id = CODEC_ID_PCM_S32BE; break;
1434  }
1435  } else if (codec_id == CODEC_ID_PCM_S16LE) {
1436  switch (track->audio.bitdepth) {
1437  case 8: codec_id = CODEC_ID_PCM_U8; break;
1438  case 24: codec_id = CODEC_ID_PCM_S24LE; break;
1439  case 32: codec_id = CODEC_ID_PCM_S32LE; break;
1440  }
1441  } else if (codec_id==CODEC_ID_PCM_F32LE && track->audio.bitdepth==64) {
1442  codec_id = CODEC_ID_PCM_F64LE;
1443  } else if (codec_id == CODEC_ID_AAC && !track->codec_priv.size) {
1444  int profile = matroska_aac_profile(track->codec_id);
1445  int sri = matroska_aac_sri(track->audio.samplerate);
1446  extradata = av_mallocz(5 + FF_INPUT_BUFFER_PADDING_SIZE);
1447  if (extradata == NULL)
1448  return AVERROR(ENOMEM);
1449  extradata[0] = (profile << 3) | ((sri&0x0E) >> 1);
1450  extradata[1] = ((sri&0x01) << 7) | (track->audio.channels<<3);
1451  if (strstr(track->codec_id, "SBR")) {
1452  sri = matroska_aac_sri(track->audio.out_samplerate);
1453  extradata[2] = 0x56;
1454  extradata[3] = 0xE5;
1455  extradata[4] = 0x80 | (sri<<3);
1456  extradata_size = 5;
1457  } else
1458  extradata_size = 2;
1459  } else if (codec_id == CODEC_ID_TTA) {
1460  extradata_size = 30;
1461  extradata = av_mallocz(extradata_size);
1462  if (extradata == NULL)
1463  return AVERROR(ENOMEM);
1464  ffio_init_context(&b, extradata, extradata_size, 1,
1465  NULL, NULL, NULL, NULL);
1466  avio_write(&b, "TTA1", 4);
1467  avio_wl16(&b, 1);
1468  avio_wl16(&b, track->audio.channels);
1469  avio_wl16(&b, track->audio.bitdepth);
1470  avio_wl32(&b, track->audio.out_samplerate);
1471  avio_wl32(&b, matroska->ctx->duration * track->audio.out_samplerate);
1472  } else if (codec_id == CODEC_ID_RV10 || codec_id == CODEC_ID_RV20 ||
1473  codec_id == CODEC_ID_RV30 || codec_id == CODEC_ID_RV40) {
1474  extradata_offset = 26;
1475  } else if (codec_id == CODEC_ID_RA_144) {
1476  track->audio.out_samplerate = 8000;
1477  track->audio.channels = 1;
1478  } else if (codec_id == CODEC_ID_RA_288 || codec_id == CODEC_ID_COOK ||
1479  codec_id == CODEC_ID_ATRAC3 || codec_id == CODEC_ID_SIPR) {
1480  int flavor;
1481  ffio_init_context(&b, track->codec_priv.data,track->codec_priv.size,
1482  0, NULL, NULL, NULL, NULL);
1483  avio_skip(&b, 22);
1484  flavor = avio_rb16(&b);
1485  track->audio.coded_framesize = avio_rb32(&b);
1486  avio_skip(&b, 12);
1487  track->audio.sub_packet_h = avio_rb16(&b);
1488  track->audio.frame_size = avio_rb16(&b);
1489  track->audio.sub_packet_size = avio_rb16(&b);
1490  track->audio.buf = av_malloc(track->audio.frame_size * track->audio.sub_packet_h);
1491  if (codec_id == CODEC_ID_RA_288) {
1492  st->codec->block_align = track->audio.coded_framesize;
1493  track->codec_priv.size = 0;
1494  } else {
1495  if (codec_id == CODEC_ID_SIPR && flavor < 4) {
1496  const int sipr_bit_rate[4] = { 6504, 8496, 5000, 16000 };
1497  track->audio.sub_packet_size = ff_sipr_subpk_size[flavor];
1498  st->codec->bit_rate = sipr_bit_rate[flavor];
1499  }
1500  st->codec->block_align = track->audio.sub_packet_size;
1501  extradata_offset = 78;
1502  }
1503  }
1504  track->codec_priv.size -= extradata_offset;
1505 
1506  if (codec_id == CODEC_ID_NONE)
1507  av_log(matroska->ctx, AV_LOG_INFO,
1508  "Unknown/unsupported CodecID %s.\n", track->codec_id);
1509 
1510  if (track->time_scale < 0.01)
1511  track->time_scale = 1.0;
1512  avpriv_set_pts_info(st, 64, matroska->time_scale*track->time_scale, 1000*1000*1000); /* 64 bit pts in ns */
1513 
1514  st->codec->codec_id = codec_id;
1515  st->start_time = 0;
1516  if (strcmp(track->language, "und"))
1517  av_dict_set(&st->metadata, "language", track->language, 0);
1518  av_dict_set(&st->metadata, "title", track->name, 0);
1519 
1520  if (track->flag_default)
1522  if (track->flag_forced)
1524 
1525  if (!st->codec->extradata) {
1526  if(extradata){
1527  st->codec->extradata = extradata;
1528  st->codec->extradata_size = extradata_size;
1529  } else if(track->codec_priv.data && track->codec_priv.size > 0){
1530  st->codec->extradata = av_mallocz(track->codec_priv.size +
1532  if(st->codec->extradata == NULL)
1533  return AVERROR(ENOMEM);
1534  st->codec->extradata_size = track->codec_priv.size;
1535  memcpy(st->codec->extradata,
1536  track->codec_priv.data + extradata_offset,
1537  track->codec_priv.size);
1538  }
1539  }
1540 
1541  if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1543  st->codec->codec_tag = track->video.fourcc;
1544  st->codec->width = track->video.pixel_width;
1545  st->codec->height = track->video.pixel_height;
1547  &st->sample_aspect_ratio.den,
1548  st->codec->height * track->video.display_width,
1549  st->codec-> width * track->video.display_height,
1550  255);
1551  if (st->codec->codec_id != CODEC_ID_H264)
1553  if (track->default_duration)
1554  st->avg_frame_rate = av_d2q(1000000000.0/track->default_duration, INT_MAX);
1555  } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
1557  st->codec->sample_rate = track->audio.out_samplerate;
1558  st->codec->channels = track->audio.channels;
1559  if (st->codec->codec_id != CODEC_ID_AAC)
1561  } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
1563  }
1564  }
1565 
1566  attachements = attachements_list->elem;
1567  for (j=0; j<attachements_list->nb_elem; j++) {
1568  if (!(attachements[j].filename && attachements[j].mime &&
1569  attachements[j].bin.data && attachements[j].bin.size > 0)) {
1570  av_log(matroska->ctx, AV_LOG_ERROR, "incomplete attachment\n");
1571  } else {
1572  AVStream *st = avformat_new_stream(s, NULL);
1573  if (st == NULL)
1574  break;
1575  av_dict_set(&st->metadata, "filename",attachements[j].filename, 0);
1576  av_dict_set(&st->metadata, "mimetype", attachements[j].mime, 0);
1577  st->codec->codec_id = CODEC_ID_NONE;
1579  st->codec->extradata = av_malloc(attachements[j].bin.size);
1580  if(st->codec->extradata == NULL)
1581  break;
1582  st->codec->extradata_size = attachements[j].bin.size;
1583  memcpy(st->codec->extradata, attachements[j].bin.data, attachements[j].bin.size);
1584 
1585  for (i=0; ff_mkv_mime_tags[i].id != CODEC_ID_NONE; i++) {
1586  if (!strncmp(ff_mkv_mime_tags[i].str, attachements[j].mime,
1587  strlen(ff_mkv_mime_tags[i].str))) {
1588  st->codec->codec_id = ff_mkv_mime_tags[i].id;
1589  break;
1590  }
1591  }
1592  attachements[j].stream = st;
1593  }
1594  }
1595 
1596  chapters = chapters_list->elem;
1597  for (i=0; i<chapters_list->nb_elem; i++)
1598  if (chapters[i].start != AV_NOPTS_VALUE && chapters[i].uid
1599  && (max_start==0 || chapters[i].start > max_start)) {
1600  chapters[i].chapter =
1601  avpriv_new_chapter(s, chapters[i].uid, (AVRational){1, 1000000000},
1602  chapters[i].start, chapters[i].end,
1603  chapters[i].title);
1604  av_dict_set(&chapters[i].chapter->metadata,
1605  "title", chapters[i].title, 0);
1606  max_start = chapters[i].start;
1607  }
1608 
1610 
1611  return 0;
1612 }
1613 
1614 /*
1615  * Put one packet in an application-supplied AVPacket struct.
1616  * Returns 0 on success or -1 on failure.
1617  */
1619  AVPacket *pkt)
1620 {
1621  if (matroska->num_packets > 0) {
1622  memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
1623  av_free(matroska->packets[0]);
1624  if (matroska->num_packets > 1) {
1625  void *newpackets;
1626  memmove(&matroska->packets[0], &matroska->packets[1],
1627  (matroska->num_packets - 1) * sizeof(AVPacket *));
1628  newpackets = av_realloc(matroska->packets,
1629  (matroska->num_packets - 1) * sizeof(AVPacket *));
1630  if (newpackets)
1631  matroska->packets = newpackets;
1632  } else {
1633  av_freep(&matroska->packets);
1634  }
1635  matroska->num_packets--;
1636  return 0;
1637  }
1638 
1639  return -1;
1640 }
1641 
1642 /*
1643  * Free all packets in our internal queue.
1644  */
1646 {
1647  if (matroska->packets) {
1648  int n;
1649  for (n = 0; n < matroska->num_packets; n++) {
1650  av_free_packet(matroska->packets[n]);
1651  av_free(matroska->packets[n]);
1652  }
1653  av_freep(&matroska->packets);
1654  matroska->num_packets = 0;
1655  }
1656 }
1657 
1658 static int matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data,
1659  int size, int64_t pos, uint64_t cluster_time,
1660  uint64_t duration, int is_keyframe,
1661  int64_t cluster_pos)
1662 {
1663  uint64_t timecode = AV_NOPTS_VALUE;
1664  MatroskaTrack *track;
1665  int res = 0;
1666  AVStream *st;
1667  AVPacket *pkt;
1668  int16_t block_time;
1669  uint32_t *lace_size = NULL;
1670  int n, flags, laces = 0;
1671  uint64_t num;
1672 
1673  if ((n = matroska_ebmlnum_uint(matroska, data, size, &num)) < 0) {
1674  av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
1675  return res;
1676  }
1677  data += n;
1678  size -= n;
1679 
1680  track = matroska_find_track_by_num(matroska, num);
1681  if (!track || !track->stream) {
1682  av_log(matroska->ctx, AV_LOG_INFO,
1683  "Invalid stream %"PRIu64" or size %u\n", num, size);
1684  return AVERROR_INVALIDDATA;
1685  } else if (size <= 3)
1686  return 0;
1687  st = track->stream;
1688  if (st->discard >= AVDISCARD_ALL)
1689  return res;
1690  if (duration == AV_NOPTS_VALUE)
1691  duration = track->default_duration / matroska->time_scale;
1692 
1693  block_time = AV_RB16(data);
1694  data += 2;
1695  flags = *data++;
1696  size -= 3;
1697  if (is_keyframe == -1)
1698  is_keyframe = flags & 0x80 ? AV_PKT_FLAG_KEY : 0;
1699 
1700  if (cluster_time != (uint64_t)-1
1701  && (block_time >= 0 || cluster_time >= -block_time)) {
1702  timecode = cluster_time + block_time;
1703  if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE
1704  && timecode < track->end_timecode)
1705  is_keyframe = 0; /* overlapping subtitles are not key frame */
1706  if (is_keyframe)
1707  av_add_index_entry(st, cluster_pos, timecode, 0,0,AVINDEX_KEYFRAME);
1708  track->end_timecode = FFMAX(track->end_timecode, timecode+duration);
1709  }
1710 
1711  if (matroska->skip_to_keyframe && track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
1712  if (!is_keyframe || timecode < matroska->skip_to_timecode)
1713  return res;
1714  matroska->skip_to_keyframe = 0;
1715  }
1716 
1717  switch ((flags & 0x06) >> 1) {
1718  case 0x0: /* no lacing */
1719  laces = 1;
1720  lace_size = av_mallocz(sizeof(int));
1721  lace_size[0] = size;
1722  break;
1723 
1724  case 0x1: /* Xiph lacing */
1725  case 0x2: /* fixed-size lacing */
1726  case 0x3: /* EBML lacing */
1727  assert(size>0); // size <=3 is checked before size-=3 above
1728  laces = (*data) + 1;
1729  data += 1;
1730  size -= 1;
1731  lace_size = av_mallocz(laces * sizeof(int));
1732 
1733  switch ((flags & 0x06) >> 1) {
1734  case 0x1: /* Xiph lacing */ {
1735  uint8_t temp;
1736  uint32_t total = 0;
1737  for (n = 0; res == 0 && n < laces - 1; n++) {
1738  while (1) {
1739  if (size == 0) {
1740  res = -1;
1741  break;
1742  }
1743  temp = *data;
1744  lace_size[n] += temp;
1745  data += 1;
1746  size -= 1;
1747  if (temp != 0xff)
1748  break;
1749  }
1750  total += lace_size[n];
1751  }
1752  lace_size[n] = size - total;
1753  break;
1754  }
1755 
1756  case 0x2: /* fixed-size lacing */
1757  for (n = 0; n < laces; n++)
1758  lace_size[n] = size / laces;
1759  break;
1760 
1761  case 0x3: /* EBML lacing */ {
1762  uint32_t total;
1763  n = matroska_ebmlnum_uint(matroska, data, size, &num);
1764  if (n < 0) {
1765  av_log(matroska->ctx, AV_LOG_INFO,
1766  "EBML block data error\n");
1767  break;
1768  }
1769  data += n;
1770  size -= n;
1771  total = lace_size[0] = num;
1772  for (n = 1; res == 0 && n < laces - 1; n++) {
1773  int64_t snum;
1774  int r;
1775  r = matroska_ebmlnum_sint(matroska, data, size, &snum);
1776  if (r < 0) {
1777  av_log(matroska->ctx, AV_LOG_INFO,
1778  "EBML block data error\n");
1779  break;
1780  }
1781  data += r;
1782  size -= r;
1783  lace_size[n] = lace_size[n - 1] + snum;
1784  total += lace_size[n];
1785  }
1786  lace_size[laces - 1] = size - total;
1787  break;
1788  }
1789  }
1790  break;
1791  }
1792 
1793  if (res == 0) {
1794  for (n = 0; n < laces; n++) {
1795  if ((st->codec->codec_id == CODEC_ID_RA_288 ||
1796  st->codec->codec_id == CODEC_ID_COOK ||
1797  st->codec->codec_id == CODEC_ID_SIPR ||
1798  st->codec->codec_id == CODEC_ID_ATRAC3) &&
1799  st->codec->block_align && track->audio.sub_packet_size) {
1800  int a = st->codec->block_align;
1801  int sps = track->audio.sub_packet_size;
1802  int cfs = track->audio.coded_framesize;
1803  int h = track->audio.sub_packet_h;
1804  int y = track->audio.sub_packet_cnt;
1805  int w = track->audio.frame_size;
1806  int x;
1807 
1808  if (!track->audio.pkt_cnt) {
1809  if (track->audio.sub_packet_cnt == 0)
1810  track->audio.buf_timecode = timecode;
1811  if (st->codec->codec_id == CODEC_ID_RA_288) {
1812  if (size < cfs * h / 2) {
1813  av_log(matroska->ctx, AV_LOG_ERROR,
1814  "Corrupt int4 RM-style audio packet size\n");
1815  return AVERROR_INVALIDDATA;
1816  }
1817  for (x=0; x<h/2; x++)
1818  memcpy(track->audio.buf+x*2*w+y*cfs,
1819  data+x*cfs, cfs);
1820  } else if (st->codec->codec_id == CODEC_ID_SIPR) {
1821  if (size < w) {
1822  av_log(matroska->ctx, AV_LOG_ERROR,
1823  "Corrupt sipr RM-style audio packet size\n");
1824  return AVERROR_INVALIDDATA;
1825  }
1826  memcpy(track->audio.buf + y*w, data, w);
1827  } else {
1828  if (size < sps * w / sps) {
1829  av_log(matroska->ctx, AV_LOG_ERROR,
1830  "Corrupt generic RM-style audio packet size\n");
1831  return AVERROR_INVALIDDATA;
1832  }
1833  for (x=0; x<w/sps; x++)
1834  memcpy(track->audio.buf+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), data+x*sps, sps);
1835  }
1836 
1837  if (++track->audio.sub_packet_cnt >= h) {
1838  if (st->codec->codec_id == CODEC_ID_SIPR)
1839  ff_rm_reorder_sipr_data(track->audio.buf, h, w);
1840  track->audio.sub_packet_cnt = 0;
1841  track->audio.pkt_cnt = h*w / a;
1842  }
1843  }
1844  while (track->audio.pkt_cnt) {
1845  pkt = av_mallocz(sizeof(AVPacket));
1846  av_new_packet(pkt, a);
1847  memcpy(pkt->data, track->audio.buf
1848  + a * (h*w / a - track->audio.pkt_cnt--), a);
1849  pkt->pts = track->audio.buf_timecode;
1851  pkt->pos = pos;
1852  pkt->stream_index = st->index;
1853  dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
1854  }
1855  } else {
1856  MatroskaTrackEncoding *encodings = track->encodings.elem;
1857  int offset = 0, pkt_size = lace_size[n];
1858  uint8_t *pkt_data = data;
1859 
1860  if (pkt_size > size) {
1861  av_log(matroska->ctx, AV_LOG_ERROR, "Invalid packet size\n");
1862  break;
1863  }
1864 
1865  if (encodings && encodings->scope & 1) {
1866  offset = matroska_decode_buffer(&pkt_data,&pkt_size, track);
1867  if (offset < 0)
1868  continue;
1869  }
1870 
1871  pkt = av_mallocz(sizeof(AVPacket));
1872  /* XXX: prevent data copy... */
1873  if (av_new_packet(pkt, pkt_size+offset) < 0) {
1874  av_free(pkt);
1875  res = AVERROR(ENOMEM);
1876  break;
1877  }
1878  if (offset)
1879  memcpy (pkt->data, encodings->compression.settings.data, offset);
1880  memcpy (pkt->data+offset, pkt_data, pkt_size);
1881 
1882  if (pkt_data != data)
1883  av_free(pkt_data);
1884 
1885  if (n == 0)
1886  pkt->flags = is_keyframe;
1887  pkt->stream_index = st->index;
1888 
1889  if (track->ms_compat)
1890  pkt->dts = timecode;
1891  else
1892  pkt->pts = timecode;
1893  pkt->pos = pos;
1894  if (st->codec->codec_id == CODEC_ID_TEXT)
1896  else if (track->type != MATROSKA_TRACK_TYPE_SUBTITLE)
1897  pkt->duration = duration;
1898 
1899  if (st->codec->codec_id == CODEC_ID_SSA)
1900  matroska_fix_ass_packet(matroska, pkt, duration);
1901 
1902  if (matroska->prev_pkt &&
1903  timecode != AV_NOPTS_VALUE &&
1904  matroska->prev_pkt->pts == timecode &&
1905  matroska->prev_pkt->stream_index == st->index &&
1906  st->codec->codec_id == CODEC_ID_SSA)
1907  matroska_merge_packets(matroska->prev_pkt, pkt);
1908  else {
1909  dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
1910  matroska->prev_pkt = pkt;
1911  }
1912  }
1913 
1914  if (timecode != AV_NOPTS_VALUE)
1915  timecode = duration ? timecode + duration : AV_NOPTS_VALUE;
1916  data += lace_size[n];
1917  size -= lace_size[n];
1918  }
1919  }
1920 
1921  av_free(lace_size);
1922  return res;
1923 }
1924 
1926 {
1927  MatroskaCluster cluster = { 0 };
1928  EbmlList *blocks_list;
1929  MatroskaBlock *blocks;
1930  int i, res;
1931  int64_t pos = avio_tell(matroska->ctx->pb);
1932  matroska->prev_pkt = NULL;
1933  if (matroska->current_id)
1934  pos -= 4; /* sizeof the ID which was already read */
1935  res = ebml_parse(matroska, matroska_clusters, &cluster);
1936  blocks_list = &cluster.blocks;
1937  blocks = blocks_list->elem;
1938  for (i=0; i<blocks_list->nb_elem && !res; i++)
1939  if (blocks[i].bin.size > 0 && blocks[i].bin.data) {
1940  int is_keyframe = blocks[i].non_simple ? !blocks[i].reference : -1;
1941  if (!blocks[i].non_simple)
1942  blocks[i].duration = AV_NOPTS_VALUE;
1943  res=matroska_parse_block(matroska,
1944  blocks[i].bin.data, blocks[i].bin.size,
1945  blocks[i].bin.pos, cluster.timecode,
1946  blocks[i].duration, is_keyframe,
1947  pos);
1948  }
1949  ebml_free(matroska_cluster, &cluster);
1950  if (res < 0) matroska->done = 1;
1951  return res;
1952 }
1953 
1955 {
1956  MatroskaDemuxContext *matroska = s->priv_data;
1957  int ret = 0;
1958 
1959  while (!ret && matroska_deliver_packet(matroska, pkt)) {
1960  if (matroska->done)
1961  return AVERROR_EOF;
1962  ret = matroska_parse_cluster(matroska);
1963  }
1964 
1965  return ret;
1966 }
1967 
1968 static int matroska_read_seek(AVFormatContext *s, int stream_index,
1969  int64_t timestamp, int flags)
1970 {
1971  MatroskaDemuxContext *matroska = s->priv_data;
1972  MatroskaTrack *tracks = matroska->tracks.elem;
1973  AVStream *st = s->streams[stream_index];
1974  int i, index, index_sub, index_min;
1975 
1976  /* Parse the CUES now since we need the index data to seek. */
1977  if (matroska->cues_parsing_deferred) {
1978  matroska_parse_cues(matroska);
1979  matroska->cues_parsing_deferred = 0;
1980  }
1981 
1982  if (!st->nb_index_entries)
1983  return 0;
1984  timestamp = FFMAX(timestamp, st->index_entries[0].timestamp);
1985 
1986  if ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
1987  avio_seek(s->pb, st->index_entries[st->nb_index_entries-1].pos, SEEK_SET);
1988  matroska->current_id = 0;
1989  while ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
1990  matroska_clear_queue(matroska);
1991  if (matroska_parse_cluster(matroska) < 0)
1992  break;
1993  }
1994  }
1995 
1996  matroska_clear_queue(matroska);
1997  if (index < 0)
1998  return 0;
1999 
2000  index_min = index;
2001  for (i=0; i < matroska->tracks.nb_elem; i++) {
2002  tracks[i].audio.pkt_cnt = 0;
2003  tracks[i].audio.sub_packet_cnt = 0;
2004  tracks[i].audio.buf_timecode = AV_NOPTS_VALUE;
2005  tracks[i].end_timecode = 0;
2006  if (tracks[i].type == MATROSKA_TRACK_TYPE_SUBTITLE
2007  && !tracks[i].stream->discard != AVDISCARD_ALL) {
2008  index_sub = av_index_search_timestamp(tracks[i].stream, st->index_entries[index].timestamp, AVSEEK_FLAG_BACKWARD);
2009  if (index_sub >= 0
2010  && st->index_entries[index_sub].pos < st->index_entries[index_min].pos
2011  && st->index_entries[index].timestamp - st->index_entries[index_sub].timestamp < 30000000000/matroska->time_scale)
2012  index_min = index_sub;
2013  }
2014  }
2015 
2016  avio_seek(s->pb, st->index_entries[index_min].pos, SEEK_SET);
2017  matroska->current_id = 0;
2018  matroska->skip_to_keyframe = !(flags & AVSEEK_FLAG_ANY);
2019  matroska->skip_to_timecode = st->index_entries[index].timestamp;
2020  matroska->done = 0;
2021  ff_update_cur_dts(s, st, st->index_entries[index].timestamp);
2022  return 0;
2023 }
2024 
2026 {
2027  MatroskaDemuxContext *matroska = s->priv_data;
2028  MatroskaTrack *tracks = matroska->tracks.elem;
2029  int n;
2030 
2031  matroska_clear_queue(matroska);
2032 
2033  for (n=0; n < matroska->tracks.nb_elem; n++)
2034  if (tracks[n].type == MATROSKA_TRACK_TYPE_AUDIO)
2035  av_free(tracks[n].audio.buf);
2036  ebml_free(matroska_segment, matroska);
2037 
2038  return 0;
2039 }
2040 
2042  .name = "matroska,webm",
2043  .long_name = NULL_IF_CONFIG_SMALL("Matroska/WebM file format"),
2044  .priv_data_size = sizeof(MatroskaDemuxContext),
2050 };