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