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