FFmpeg  2.1.1
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/base64.h"
43 #include "libavutil/intfloat.h"
44 #include "libavutil/intreadwrite.h"
45 #include "libavutil/avstring.h"
46 #include "libavutil/lzo.h"
47 #include "libavutil/dict.h"
48 #if CONFIG_ZLIB
49 #include <zlib.h>
50 #endif
51 #if CONFIG_BZLIB
52 #include <bzlib.h>
53 #endif
54 
55 typedef enum {
66 } EbmlType;
67 
68 typedef const struct EbmlSyntax {
69  uint32_t id;
73  union {
74  uint64_t u;
75  double f;
76  const char *s;
77  const struct EbmlSyntax *n;
78  } def;
79 } EbmlSyntax;
80 
81 typedef struct {
82  int nb_elem;
83  void *elem;
84 } EbmlList;
85 
86 typedef struct {
87  int size;
89  int64_t pos;
90 } EbmlBin;
91 
92 typedef struct {
93  uint64_t version;
94  uint64_t max_size;
95  uint64_t id_length;
96  char *doctype;
97  uint64_t doctype_version;
98 } Ebml;
99 
100 typedef struct {
101  uint64_t algo;
104 
105 typedef struct {
106  uint64_t algo;
109 
110 typedef struct {
111  uint64_t scope;
112  uint64_t type;
116 
117 typedef struct {
118  double frame_rate;
119  uint64_t display_width;
120  uint64_t display_height;
121  uint64_t pixel_width;
122  uint64_t pixel_height;
124  uint64_t stereo_mode;
125  uint64_t alpha_mode;
127 
128 typedef struct {
129  double samplerate;
131  uint64_t bitdepth;
132  uint64_t channels;
133 
134  /* real audio header (extracted from extradata) */
140  int pkt_cnt;
141  uint64_t buf_timecode;
144 
145 typedef struct {
146  uint64_t uid;
147  uint64_t type;
149 
150 typedef struct {
153 
154 typedef struct {
155  uint64_t num;
156  uint64_t uid;
157  uint64_t type;
158  char *name;
159  char *codec_id;
161  char *language;
162  double time_scale;
164  uint64_t flag_default;
165  uint64_t flag_forced;
166  uint64_t codec_delay;
167  uint64_t seek_preroll;
172 
174  int64_t end_timecode;
177 } MatroskaTrack;
178 
179 typedef struct {
180  uint64_t uid;
181  char *filename;
182  char *mime;
184 
187 
188 typedef struct {
189  uint64_t start;
190  uint64_t end;
191  uint64_t uid;
192  char *title;
193 
196 
197 typedef struct {
198  uint64_t track;
199  uint64_t pos;
201 
202 typedef struct {
203  uint64_t time;
205 } MatroskaIndex;
206 
207 typedef struct {
208  char *name;
209  char *string;
210  char *lang;
211  uint64_t def;
213 } MatroskaTag;
214 
215 typedef struct {
216  char *type;
217  uint64_t typevalue;
218  uint64_t trackuid;
219  uint64_t chapteruid;
220  uint64_t attachuid;
222 
223 typedef struct {
226 } MatroskaTags;
227 
228 typedef struct {
229  uint64_t id;
230  uint64_t pos;
232 
233 typedef struct {
234  uint64_t start;
235  uint64_t length;
236 } MatroskaLevel;
237 
238 typedef struct {
239  uint64_t timecode;
242 
243 typedef struct {
245 
246  /* EBML stuff */
249  int level_up;
250  uint32_t current_id;
251 
252  uint64_t time_scale;
253  double duration;
254  char *title;
262 
263  /* byte position of the segment inside the stream */
264  int64_t segment_start;
265 
266  /* the packet queue */
270 
271  int done;
272 
273  /* What to skip before effectively reading a packet. */
276 
277  /* File has a CUES element, but we defer parsing until it is needed. */
279 
283 
284  /* File has SSA subtitles which prevent incremental cluster parsing. */
287 
288 typedef struct {
289  uint64_t duration;
290  int64_t reference;
291  uint64_t non_simple;
293  uint64_t additional_id;
295  uint64_t discard_padding;
296 } MatroskaBlock;
297 
299  { EBML_ID_EBMLREADVERSION, EBML_UINT, 0, offsetof(Ebml,version), {.u=EBML_VERSION} },
300  { EBML_ID_EBMLMAXSIZELENGTH, EBML_UINT, 0, offsetof(Ebml,max_size), {.u=8} },
301  { EBML_ID_EBMLMAXIDLENGTH, EBML_UINT, 0, offsetof(Ebml,id_length), {.u=4} },
302  { EBML_ID_DOCTYPE, EBML_STR, 0, offsetof(Ebml,doctype), {.s="(none)"} },
303  { EBML_ID_DOCTYPEREADVERSION, EBML_UINT, 0, offsetof(Ebml,doctype_version), {.u=1} },
306  { 0 }
307 };
308 
310  { EBML_ID_HEADER, EBML_NEST, 0, 0, {.n=ebml_header} },
311  { 0 }
312 };
313 
315  { MATROSKA_ID_TIMECODESCALE, EBML_UINT, 0, offsetof(MatroskaDemuxContext,time_scale), {.u=1000000} },
317  { MATROSKA_ID_TITLE, EBML_UTF8, 0, offsetof(MatroskaDemuxContext,title) },
320  { MATROSKA_ID_DATEUTC, EBML_BIN, 0, offsetof(MatroskaDemuxContext,date_utc) },
322  { 0 }
323 };
324 
326  { MATROSKA_ID_VIDEOFRAMERATE, EBML_FLOAT,0, offsetof(MatroskaTrackVideo,frame_rate) },
327  { MATROSKA_ID_VIDEODISPLAYWIDTH, EBML_UINT, 0, offsetof(MatroskaTrackVideo,display_width), {.u=-1} },
328  { MATROSKA_ID_VIDEODISPLAYHEIGHT, EBML_UINT, 0, offsetof(MatroskaTrackVideo,display_height), {.u=-1} },
329  { MATROSKA_ID_VIDEOPIXELWIDTH, EBML_UINT, 0, offsetof(MatroskaTrackVideo,pixel_width) },
330  { MATROSKA_ID_VIDEOPIXELHEIGHT, EBML_UINT, 0, offsetof(MatroskaTrackVideo,pixel_height) },
331  { MATROSKA_ID_VIDEOCOLORSPACE, EBML_BIN, 0, offsetof(MatroskaTrackVideo,color_space) },
332  { MATROSKA_ID_VIDEOSTEREOMODE, EBML_UINT, 0, offsetof(MatroskaTrackVideo,stereo_mode) },
333  { MATROSKA_ID_VIDEOALPHAMODE, EBML_UINT, 0, offsetof(MatroskaTrackVideo,alpha_mode) },
341  { 0 }
342 };
343 
345  { MATROSKA_ID_AUDIOSAMPLINGFREQ, EBML_FLOAT,0, offsetof(MatroskaTrackAudio,samplerate), {.f=8000.0} },
346  { MATROSKA_ID_AUDIOOUTSAMPLINGFREQ,EBML_FLOAT,0,offsetof(MatroskaTrackAudio,out_samplerate) },
348  { MATROSKA_ID_AUDIOCHANNELS, EBML_UINT, 0, offsetof(MatroskaTrackAudio,channels), {.u=1} },
349  { 0 }
350 };
351 
355  { 0 }
356 };
357 
366  { 0 }
367 };
369  { MATROSKA_ID_ENCODINGSCOPE, EBML_UINT, 0, offsetof(MatroskaTrackEncoding,scope), {.u=1} },
371  { MATROSKA_ID_ENCODINGCOMPRESSION,EBML_NEST, 0, offsetof(MatroskaTrackEncoding,compression), {.n=matroska_track_encoding_compression} },
372  { MATROSKA_ID_ENCODINGENCRYPTION, EBML_NEST, 0, offsetof(MatroskaTrackEncoding,encryption), {.n=matroska_track_encoding_encryption} },
374  { 0 }
375 };
376 
378  { MATROSKA_ID_TRACKCONTENTENCODING, EBML_NEST, sizeof(MatroskaTrackEncoding), offsetof(MatroskaTrack,encodings), {.n=matroska_track_encoding} },
379  { 0 }
380 };
381 
385  { 0 }
386 };
387 
389  { MATROSKA_ID_TRACKPLANE, EBML_NEST, sizeof(MatroskaTrackPlane), offsetof(MatroskaTrackOperation,combine_planes), {.n=matroska_track_plane} },
390  { 0 }
391 };
392 
394  { MATROSKA_ID_TRACKCOMBINEPLANES, EBML_NEST, 0, 0, {.n=matroska_track_combine_planes} },
395  { 0 }
396 };
397 
399  { MATROSKA_ID_TRACKNUMBER, EBML_UINT, 0, offsetof(MatroskaTrack,num) },
401  { MATROSKA_ID_TRACKUID, EBML_UINT, 0, offsetof(MatroskaTrack,uid) },
404  { MATROSKA_ID_CODECPRIVATE, EBML_BIN, 0, offsetof(MatroskaTrack,codec_priv) },
405  { MATROSKA_ID_TRACKLANGUAGE, EBML_UTF8, 0, offsetof(MatroskaTrack,language), {.s="eng"} },
406  { MATROSKA_ID_TRACKDEFAULTDURATION, EBML_UINT, 0, offsetof(MatroskaTrack,default_duration) },
407  { MATROSKA_ID_TRACKTIMECODESCALE, EBML_FLOAT,0, offsetof(MatroskaTrack,time_scale), {.f=1.0} },
408  { MATROSKA_ID_TRACKFLAGDEFAULT, EBML_UINT, 0, offsetof(MatroskaTrack,flag_default), {.u=1} },
409  { MATROSKA_ID_TRACKFLAGFORCED, EBML_UINT, 0, offsetof(MatroskaTrack,flag_forced), {.u=0} },
410  { MATROSKA_ID_TRACKVIDEO, EBML_NEST, 0, offsetof(MatroskaTrack,video), {.n=matroska_track_video} },
411  { MATROSKA_ID_TRACKAUDIO, EBML_NEST, 0, offsetof(MatroskaTrack,audio), {.n=matroska_track_audio} },
412  { MATROSKA_ID_TRACKOPERATION, EBML_NEST, 0, offsetof(MatroskaTrack,operation), {.n=matroska_track_operation} },
413  { MATROSKA_ID_TRACKCONTENTENCODINGS,EBML_NEST, 0, 0, {.n=matroska_track_encodings} },
414  { MATROSKA_ID_TRACKMAXBLKADDID, EBML_UINT, 0, offsetof(MatroskaTrack,max_block_additional_id) },
415  { MATROSKA_ID_CODECDELAY, EBML_UINT, 0, offsetof(MatroskaTrack,codec_delay) },
416  { MATROSKA_ID_SEEKPREROLL, EBML_UINT, 0, offsetof(MatroskaTrack,seek_preroll) },
425  { 0 }
426 };
427 
429  { MATROSKA_ID_TRACKENTRY, EBML_NEST, sizeof(MatroskaTrack), offsetof(MatroskaDemuxContext,tracks), {.n=matroska_track} },
430  { 0 }
431 };
432 
434  { MATROSKA_ID_FILEUID, EBML_UINT, 0, offsetof(MatroskaAttachement,uid) },
435  { MATROSKA_ID_FILENAME, EBML_UTF8, 0, offsetof(MatroskaAttachement,filename) },
436  { MATROSKA_ID_FILEMIMETYPE, EBML_STR, 0, offsetof(MatroskaAttachement,mime) },
437  { MATROSKA_ID_FILEDATA, EBML_BIN, 0, offsetof(MatroskaAttachement,bin) },
439  { 0 }
440 };
441 
443  { MATROSKA_ID_ATTACHEDFILE, EBML_NEST, sizeof(MatroskaAttachement), offsetof(MatroskaDemuxContext,attachments), {.n=matroska_attachment} },
444  { 0 }
445 };
446 
448  { MATROSKA_ID_CHAPSTRING, EBML_UTF8, 0, offsetof(MatroskaChapter,title) },
450  { 0 }
451 };
452 
456  { MATROSKA_ID_CHAPTERUID, EBML_UINT, 0, offsetof(MatroskaChapter,uid) },
457  { MATROSKA_ID_CHAPTERDISPLAY, EBML_NEST, 0, 0, {.n=matroska_chapter_display} },
462  { 0 }
463 };
464 
466  { MATROSKA_ID_CHAPTERATOM, EBML_NEST, sizeof(MatroskaChapter), offsetof(MatroskaDemuxContext,chapters), {.n=matroska_chapter_entry} },
471  { 0 }
472 };
473 
475  { MATROSKA_ID_EDITIONENTRY, EBML_NEST, 0, 0, {.n=matroska_chapter} },
476  { 0 }
477 };
478 
480  { MATROSKA_ID_CUETRACK, EBML_UINT, 0, offsetof(MatroskaIndexPos,track) },
485  { 0 }
486 };
487 
489  { MATROSKA_ID_CUETIME, EBML_UINT, 0, offsetof(MatroskaIndex,time) },
490  { MATROSKA_ID_CUETRACKPOSITION, EBML_NEST, sizeof(MatroskaIndexPos), offsetof(MatroskaIndex,pos), {.n=matroska_index_pos} },
491  { 0 }
492 };
493 
495  { MATROSKA_ID_POINTENTRY, EBML_NEST, sizeof(MatroskaIndex), offsetof(MatroskaDemuxContext,index), {.n=matroska_index_entry} },
496  { 0 }
497 };
498 
500  { MATROSKA_ID_TAGNAME, EBML_UTF8, 0, offsetof(MatroskaTag,name) },
501  { MATROSKA_ID_TAGSTRING, EBML_UTF8, 0, offsetof(MatroskaTag,string) },
502  { MATROSKA_ID_TAGLANG, EBML_STR, 0, offsetof(MatroskaTag,lang), {.s="und"} },
503  { MATROSKA_ID_TAGDEFAULT, EBML_UINT, 0, offsetof(MatroskaTag,def) },
504  { MATROSKA_ID_TAGDEFAULT_BUG, EBML_UINT, 0, offsetof(MatroskaTag,def) },
505  { MATROSKA_ID_SIMPLETAG, EBML_NEST, sizeof(MatroskaTag), offsetof(MatroskaTag,sub), {.n=matroska_simpletag} },
506  { 0 }
507 };
508 
511  { MATROSKA_ID_TAGTARGETS_TYPEVALUE, EBML_UINT, 0, offsetof(MatroskaTagTarget,typevalue), {.u=50} },
512  { MATROSKA_ID_TAGTARGETS_TRACKUID, EBML_UINT, 0, offsetof(MatroskaTagTarget,trackuid) },
514  { MATROSKA_ID_TAGTARGETS_ATTACHUID, EBML_UINT, 0, offsetof(MatroskaTagTarget,attachuid) },
515  { 0 }
516 };
517 
519  { MATROSKA_ID_SIMPLETAG, EBML_NEST, sizeof(MatroskaTag), offsetof(MatroskaTags,tag), {.n=matroska_simpletag} },
520  { MATROSKA_ID_TAGTARGETS, EBML_NEST, 0, offsetof(MatroskaTags,target), {.n=matroska_tagtargets} },
521  { 0 }
522 };
523 
525  { MATROSKA_ID_TAG, EBML_NEST, sizeof(MatroskaTags), offsetof(MatroskaDemuxContext,tags), {.n=matroska_tag} },
526  { 0 }
527 };
528 
530  { MATROSKA_ID_SEEKID, EBML_UINT, 0, offsetof(MatroskaSeekhead,id) },
531  { MATROSKA_ID_SEEKPOSITION, EBML_UINT, 0, offsetof(MatroskaSeekhead,pos), {.u=-1} },
532  { 0 }
533 };
534 
536  { MATROSKA_ID_SEEKENTRY, EBML_NEST, sizeof(MatroskaSeekhead), offsetof(MatroskaDemuxContext,seekhead), {.n=matroska_seekhead_entry} },
537  { 0 }
538 };
539 
541  { MATROSKA_ID_INFO, EBML_NEST, 0, 0, {.n=matroska_info } },
542  { MATROSKA_ID_TRACKS, EBML_NEST, 0, 0, {.n=matroska_tracks } },
543  { MATROSKA_ID_ATTACHMENTS, EBML_NEST, 0, 0, {.n=matroska_attachments} },
544  { MATROSKA_ID_CHAPTERS, EBML_NEST, 0, 0, {.n=matroska_chapters } },
545  { MATROSKA_ID_CUES, EBML_NEST, 0, 0, {.n=matroska_index } },
546  { MATROSKA_ID_TAGS, EBML_NEST, 0, 0, {.n=matroska_tags } },
547  { MATROSKA_ID_SEEKHEAD, EBML_NEST, 0, 0, {.n=matroska_seekhead } },
549  { 0 }
550 };
551 
553  { MATROSKA_ID_SEGMENT, EBML_NEST, 0, 0, {.n=matroska_segment } },
554  { 0 }
555 };
556 
558  { MATROSKA_ID_BLOCKADDID, EBML_UINT, 0, offsetof(MatroskaBlock,additional_id) },
559  { MATROSKA_ID_BLOCKADDITIONAL, EBML_BIN, 0, offsetof(MatroskaBlock,additional) },
560  { 0 }
561 };
562 
564  { MATROSKA_ID_BLOCKMORE, EBML_NEST, 0, 0, {.n=matroska_blockmore} },
565  { 0 }
566 };
567 
569  { MATROSKA_ID_BLOCK, EBML_BIN, 0, offsetof(MatroskaBlock,bin) },
570  { MATROSKA_ID_BLOCKADDITIONS, EBML_NEST, 0, 0, {.n=matroska_blockadditions} },
571  { MATROSKA_ID_SIMPLEBLOCK, EBML_BIN, 0, offsetof(MatroskaBlock,bin) },
573  { MATROSKA_ID_DISCARDPADDING, EBML_UINT, 0, offsetof(MatroskaBlock,discard_padding) },
574  { MATROSKA_ID_BLOCKREFERENCE, EBML_UINT, 0, offsetof(MatroskaBlock,reference) },
576  { 1, EBML_UINT, 0, offsetof(MatroskaBlock,non_simple), {.u=1} },
577  { 0 }
578 };
579 
581  { MATROSKA_ID_CLUSTERTIMECODE,EBML_UINT,0, offsetof(MatroskaCluster,timecode) },
582  { MATROSKA_ID_BLOCKGROUP, EBML_NEST, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
583  { MATROSKA_ID_SIMPLEBLOCK, EBML_PASS, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
586  { 0 }
587 };
588 
590  { MATROSKA_ID_CLUSTER, EBML_NEST, 0, 0, {.n=matroska_cluster} },
595  { 0 }
596 };
597 
599  { MATROSKA_ID_CLUSTERTIMECODE,EBML_UINT,0, offsetof(MatroskaCluster,timecode) },
600  { MATROSKA_ID_BLOCKGROUP, EBML_NEST, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
601  { MATROSKA_ID_SIMPLEBLOCK, EBML_PASS, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
609  { 0 }
610 };
611 
613  { MATROSKA_ID_CLUSTERTIMECODE,EBML_UINT,0, offsetof(MatroskaCluster,timecode) },
618  { 0 }
619 };
620 
622  { MATROSKA_ID_CLUSTER, EBML_NEST, 0, 0, {.n=matroska_cluster_incremental} },
627  { 0 }
628 };
629 
630 static const char *const matroska_doctypes[] = { "matroska", "webm" };
631 
632 static int matroska_resync(MatroskaDemuxContext *matroska, int64_t last_pos)
633 {
634  AVIOContext *pb = matroska->ctx->pb;
635  uint32_t id;
636  matroska->current_id = 0;
637  matroska->num_levels = 0;
638 
639  /* seek to next position to resync from */
640  if (avio_seek(pb, last_pos + 1, SEEK_SET) < 0)
641  goto eof;
642 
643  id = avio_rb32(pb);
644 
645  // try to find a toplevel element
646  while (!url_feof(pb)) {
647  if (id == MATROSKA_ID_INFO || id == MATROSKA_ID_TRACKS ||
648  id == MATROSKA_ID_CUES || id == MATROSKA_ID_TAGS ||
650  id == MATROSKA_ID_CLUSTER || id == MATROSKA_ID_CHAPTERS) {
651  matroska->current_id = id;
652  return 0;
653  }
654  id = (id << 8) | avio_r8(pb);
655  }
656 eof:
657  matroska->done = 1;
658  return AVERROR_EOF;
659 }
660 
661 /*
662  * Return: Whether we reached the end of a level in the hierarchy or not.
663  */
665 {
666  AVIOContext *pb = matroska->ctx->pb;
667  int64_t pos = avio_tell(pb);
668 
669  if (matroska->num_levels > 0) {
670  MatroskaLevel *level = &matroska->levels[matroska->num_levels - 1];
671  if (pos - level->start >= level->length || matroska->current_id) {
672  matroska->num_levels--;
673  return 1;
674  }
675  }
676  return 0;
677 }
678 
679 /*
680  * Read: an "EBML number", which is defined as a variable-length
681  * array of bytes. The first byte indicates the length by giving a
682  * number of 0-bits followed by a one. The position of the first
683  * "one" bit inside the first byte indicates the length of this
684  * number.
685  * Returns: number of bytes read, < 0 on error
686  */
688  int max_size, uint64_t *number)
689 {
690  int read = 1, n = 1;
691  uint64_t total = 0;
692 
693  /* The first byte tells us the length in bytes - avio_r8() can normally
694  * return 0, but since that's not a valid first ebmlID byte, we can
695  * use it safely here to catch EOS. */
696  if (!(total = avio_r8(pb))) {
697  /* we might encounter EOS here */
698  if (!url_feof(pb)) {
699  int64_t pos = avio_tell(pb);
700  av_log(matroska->ctx, AV_LOG_ERROR,
701  "Read error at pos. %"PRIu64" (0x%"PRIx64")\n",
702  pos, pos);
703  return pb->error ? pb->error : AVERROR(EIO);
704  }
705  return AVERROR_EOF;
706  }
707 
708  /* get the length of the EBML number */
709  read = 8 - ff_log2_tab[total];
710  if (read > max_size) {
711  int64_t pos = avio_tell(pb) - 1;
712  av_log(matroska->ctx, AV_LOG_ERROR,
713  "Invalid EBML number size tag 0x%02x at pos %"PRIu64" (0x%"PRIx64")\n",
714  (uint8_t) total, pos, pos);
715  return AVERROR_INVALIDDATA;
716  }
717 
718  /* read out length */
719  total ^= 1 << ff_log2_tab[total];
720  while (n++ < read)
721  total = (total << 8) | avio_r8(pb);
722 
723  *number = total;
724 
725  return read;
726 }
727 
728 /**
729  * Read a EBML length value.
730  * This needs special handling for the "unknown length" case which has multiple
731  * encodings.
732  */
734  uint64_t *number)
735 {
736  int res = ebml_read_num(matroska, pb, 8, number);
737  if (res > 0 && *number + 1 == 1ULL << (7 * res))
738  *number = 0xffffffffffffffULL;
739  return res;
740 }
741 
742 /*
743  * Read the next element as an unsigned int.
744  * 0 is success, < 0 is failure.
745  */
746 static int ebml_read_uint(AVIOContext *pb, int size, uint64_t *num)
747 {
748  int n = 0;
749 
750  if (size > 8)
751  return AVERROR_INVALIDDATA;
752 
753  /* big-endian ordering; build up number */
754  *num = 0;
755  while (n++ < size)
756  *num = (*num << 8) | avio_r8(pb);
757 
758  return 0;
759 }
760 
761 /*
762  * Read the next element as a float.
763  * 0 is success, < 0 is failure.
764  */
765 static int ebml_read_float(AVIOContext *pb, int size, double *num)
766 {
767  if (size == 0) {
768  *num = 0;
769  } else if (size == 4) {
770  *num = av_int2float(avio_rb32(pb));
771  } else if (size == 8){
772  *num = av_int2double(avio_rb64(pb));
773  } else
774  return AVERROR_INVALIDDATA;
775 
776  return 0;
777 }
778 
779 /*
780  * Read the next element as an ASCII string.
781  * 0 is success, < 0 is failure.
782  */
783 static int ebml_read_ascii(AVIOContext *pb, int size, char **str)
784 {
785  char *res;
786 
787  /* EBML strings are usually not 0-terminated, so we allocate one
788  * byte more, read the string and NULL-terminate it ourselves. */
789  if (!(res = av_malloc(size + 1)))
790  return AVERROR(ENOMEM);
791  if (avio_read(pb, (uint8_t *) res, size) != size) {
792  av_free(res);
793  return AVERROR(EIO);
794  }
795  (res)[size] = '\0';
796  av_free(*str);
797  *str = res;
798 
799  return 0;
800 }
801 
802 /*
803  * Read the next element as binary data.
804  * 0 is success, < 0 is failure.
805  */
806 static int ebml_read_binary(AVIOContext *pb, int length, EbmlBin *bin)
807 {
808  av_fast_padded_malloc(&bin->data, &bin->size, length);
809  if (!bin->data)
810  return AVERROR(ENOMEM);
811 
812  bin->size = length;
813  bin->pos = avio_tell(pb);
814  if (avio_read(pb, bin->data, length) != length) {
815  av_freep(&bin->data);
816  bin->size = 0;
817  return AVERROR(EIO);
818  }
819 
820  return 0;
821 }
822 
823 /*
824  * Read the next element, but only the header. The contents
825  * are supposed to be sub-elements which can be read separately.
826  * 0 is success, < 0 is failure.
827  */
828 static int ebml_read_master(MatroskaDemuxContext *matroska, uint64_t length)
829 {
830  AVIOContext *pb = matroska->ctx->pb;
832 
833  if (matroska->num_levels >= EBML_MAX_DEPTH) {
834  av_log(matroska->ctx, AV_LOG_ERROR,
835  "File moves beyond max. allowed depth (%d)\n", EBML_MAX_DEPTH);
836  return AVERROR(ENOSYS);
837  }
838 
839  level = &matroska->levels[matroska->num_levels++];
840  level->start = avio_tell(pb);
841  level->length = length;
842 
843  return 0;
844 }
845 
846 /*
847  * Read signed/unsigned "EBML" numbers.
848  * Return: number of bytes processed, < 0 on error
849  */
851  uint8_t *data, uint32_t size, uint64_t *num)
852 {
853  AVIOContext pb;
854  ffio_init_context(&pb, data, size, 0, NULL, NULL, NULL, NULL);
855  return ebml_read_num(matroska, &pb, FFMIN(size, 8), num);
856 }
857 
858 /*
859  * Same as above, but signed.
860  */
862  uint8_t *data, uint32_t size, int64_t *num)
863 {
864  uint64_t unum;
865  int res;
866 
867  /* read as unsigned number first */
868  if ((res = matroska_ebmlnum_uint(matroska, data, size, &unum)) < 0)
869  return res;
870 
871  /* make signed (weird way) */
872  *num = unum - ((1LL << (7*res - 1)) - 1);
873 
874  return res;
875 }
876 
877 static int ebml_parse_elem(MatroskaDemuxContext *matroska,
878  EbmlSyntax *syntax, void *data);
879 
880 static int ebml_parse_id(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
881  uint32_t id, void *data)
882 {
883  int i;
884  for (i=0; syntax[i].id; i++)
885  if (id == syntax[i].id)
886  break;
887  if (!syntax[i].id && id == MATROSKA_ID_CLUSTER &&
888  matroska->num_levels > 0 &&
889  matroska->levels[matroska->num_levels-1].length == 0xffffffffffffff)
890  return 0; // we reached the end of an unknown size cluster
891  if (!syntax[i].id && id != EBML_ID_VOID && id != EBML_ID_CRC32) {
892  av_log(matroska->ctx, AV_LOG_INFO, "Unknown entry 0x%X\n", id);
893  if (matroska->ctx->error_recognition & AV_EF_EXPLODE)
894  return AVERROR_INVALIDDATA;
895  }
896  return ebml_parse_elem(matroska, &syntax[i], data);
897 }
898 
899 static int ebml_parse(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
900  void *data)
901 {
902  if (!matroska->current_id) {
903  uint64_t id;
904  int res = ebml_read_num(matroska, matroska->ctx->pb, 4, &id);
905  if (res < 0)
906  return res;
907  matroska->current_id = id | 1 << 7*res;
908  }
909  return ebml_parse_id(matroska, syntax, matroska->current_id, data);
910 }
911 
912 static int ebml_parse_nest(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
913  void *data)
914 {
915  int i, res = 0;
916 
917  for (i=0; syntax[i].id; i++)
918  switch (syntax[i].type) {
919  case EBML_UINT:
920  *(uint64_t *)((char *)data+syntax[i].data_offset) = syntax[i].def.u;
921  break;
922  case EBML_FLOAT:
923  *(double *)((char *)data+syntax[i].data_offset) = syntax[i].def.f;
924  break;
925  case EBML_STR:
926  case EBML_UTF8:
927  // the default may be NULL
928  if (syntax[i].def.s) {
929  uint8_t **dst = (uint8_t**)((uint8_t*)data + syntax[i].data_offset);
930  *dst = av_strdup(syntax[i].def.s);
931  if (!*dst)
932  return AVERROR(ENOMEM);
933  }
934  break;
935  }
936 
937  while (!res && !ebml_level_end(matroska))
938  res = ebml_parse(matroska, syntax, data);
939 
940  return res;
941 }
942 
944  EbmlSyntax *syntax, void *data)
945 {
946  static const uint64_t max_lengths[EBML_TYPE_COUNT] = {
947  [EBML_UINT] = 8,
948  [EBML_FLOAT] = 8,
949  // max. 16 MB for strings
950  [EBML_STR] = 0x1000000,
951  [EBML_UTF8] = 0x1000000,
952  // max. 256 MB for binary data
953  [EBML_BIN] = 0x10000000,
954  // no limits for anything else
955  };
956  AVIOContext *pb = matroska->ctx->pb;
957  uint32_t id = syntax->id;
958  uint64_t length;
959  int res;
960  void *newelem;
961 
962  data = (char *)data + syntax->data_offset;
963  if (syntax->list_elem_size) {
964  EbmlList *list = data;
965  newelem = av_realloc_array(list->elem, list->nb_elem+1, syntax->list_elem_size);
966  if (!newelem)
967  return AVERROR(ENOMEM);
968  list->elem = newelem;
969  data = (char*)list->elem + list->nb_elem*syntax->list_elem_size;
970  memset(data, 0, syntax->list_elem_size);
971  list->nb_elem++;
972  }
973 
974  if (syntax->type != EBML_PASS && syntax->type != EBML_STOP) {
975  matroska->current_id = 0;
976  if ((res = ebml_read_length(matroska, pb, &length)) < 0)
977  return res;
978  if (max_lengths[syntax->type] && length > max_lengths[syntax->type]) {
979  av_log(matroska->ctx, AV_LOG_ERROR,
980  "Invalid length 0x%"PRIx64" > 0x%"PRIx64" for syntax element %i\n",
981  length, max_lengths[syntax->type], syntax->type);
982  return AVERROR_INVALIDDATA;
983  }
984  }
985 
986  switch (syntax->type) {
987  case EBML_UINT: res = ebml_read_uint (pb, length, data); break;
988  case EBML_FLOAT: res = ebml_read_float (pb, length, data); break;
989  case EBML_STR:
990  case EBML_UTF8: res = ebml_read_ascii (pb, length, data); break;
991  case EBML_BIN: res = ebml_read_binary(pb, length, data); break;
992  case EBML_NEST: if ((res=ebml_read_master(matroska, length)) < 0)
993  return res;
994  if (id == MATROSKA_ID_SEGMENT)
995  matroska->segment_start = avio_tell(matroska->ctx->pb);
996  return ebml_parse_nest(matroska, syntax->def.n, data);
997  case EBML_PASS: return ebml_parse_id(matroska, syntax->def.n, id, data);
998  case EBML_STOP: return 1;
999  default:
1000  if(ffio_limit(pb, length) != length)
1001  return AVERROR(EIO);
1002  return avio_skip(pb,length)<0 ? AVERROR(EIO) : 0;
1003  }
1004  if (res == AVERROR_INVALIDDATA)
1005  av_log(matroska->ctx, AV_LOG_ERROR, "Invalid element\n");
1006  else if (res == AVERROR(EIO))
1007  av_log(matroska->ctx, AV_LOG_ERROR, "Read error\n");
1008  return res;
1009 }
1010 
1011 static void ebml_free(EbmlSyntax *syntax, void *data)
1012 {
1013  int i, j;
1014  for (i=0; syntax[i].id; i++) {
1015  void *data_off = (char *)data + syntax[i].data_offset;
1016  switch (syntax[i].type) {
1017  case EBML_STR:
1018  case EBML_UTF8: av_freep(data_off); break;
1019  case EBML_BIN: av_freep(&((EbmlBin *)data_off)->data); break;
1020  case EBML_NEST:
1021  if (syntax[i].list_elem_size) {
1022  EbmlList *list = data_off;
1023  char *ptr = list->elem;
1024  for (j=0; j<list->nb_elem; j++, ptr+=syntax[i].list_elem_size)
1025  ebml_free(syntax[i].def.n, ptr);
1026  av_free(list->elem);
1027  } else
1028  ebml_free(syntax[i].def.n, data_off);
1029  default: break;
1030  }
1031  }
1032 }
1033 
1034 
1035 /*
1036  * Autodetecting...
1037  */
1039 {
1040  uint64_t total = 0;
1041  int len_mask = 0x80, size = 1, n = 1, i;
1042 
1043  /* EBML header? */
1044  if (AV_RB32(p->buf) != EBML_ID_HEADER)
1045  return 0;
1046 
1047  /* length of header */
1048  total = p->buf[4];
1049  while (size <= 8 && !(total & len_mask)) {
1050  size++;
1051  len_mask >>= 1;
1052  }
1053  if (size > 8)
1054  return 0;
1055  total &= (len_mask - 1);
1056  while (n < size)
1057  total = (total << 8) | p->buf[4 + n++];
1058 
1059  /* Does the probe data contain the whole header? */
1060  if (p->buf_size < 4 + size + total)
1061  return 0;
1062 
1063  /* The header should contain a known document type. For now,
1064  * we don't parse the whole header but simply check for the
1065  * availability of that array of characters inside the header.
1066  * Not fully fool-proof, but good enough. */
1067  for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++) {
1068  int probelen = strlen(matroska_doctypes[i]);
1069  if (total < probelen)
1070  continue;
1071  for (n = 4+size; n <= 4+size+total-probelen; n++)
1072  if (!memcmp(p->buf+n, matroska_doctypes[i], probelen))
1073  return AVPROBE_SCORE_MAX;
1074  }
1075 
1076  // probably valid EBML header but no recognized doctype
1077  return AVPROBE_SCORE_EXTENSION;
1078 }
1079 
1081  int num)
1082 {
1083  MatroskaTrack *tracks = matroska->tracks.elem;
1084  int i;
1085 
1086  for (i=0; i < matroska->tracks.nb_elem; i++)
1087  if (tracks[i].num == num)
1088  return &tracks[i];
1089 
1090  av_log(matroska->ctx, AV_LOG_ERROR, "Invalid track number %d\n", num);
1091  return NULL;
1092 }
1093 
1094 static int matroska_decode_buffer(uint8_t** buf, int* buf_size,
1095  MatroskaTrack *track)
1096 {
1097  MatroskaTrackEncoding *encodings = track->encodings.elem;
1098  uint8_t* data = *buf;
1099  int isize = *buf_size;
1100  uint8_t* pkt_data = NULL;
1101  uint8_t av_unused *newpktdata;
1102  int pkt_size = isize;
1103  int result = 0;
1104  int olen;
1105 
1106  if (pkt_size >= 10000000U)
1107  return AVERROR_INVALIDDATA;
1108 
1109  switch (encodings[0].compression.algo) {
1111  int header_size = encodings[0].compression.settings.size;
1112  uint8_t *header = encodings[0].compression.settings.data;
1113 
1114  if (header_size && !header) {
1115  av_log(NULL, AV_LOG_ERROR, "Compression size but no data in headerstrip\n");
1116  return -1;
1117  }
1118 
1119  if (!header_size)
1120  return 0;
1121 
1122  pkt_size = isize + header_size;
1123  pkt_data = av_malloc(pkt_size);
1124  if (!pkt_data)
1125  return AVERROR(ENOMEM);
1126 
1127  memcpy(pkt_data, header, header_size);
1128  memcpy(pkt_data + header_size, data, isize);
1129  break;
1130  }
1131 #if CONFIG_LZO
1133  do {
1134  olen = pkt_size *= 3;
1135  newpktdata = av_realloc(pkt_data, pkt_size + AV_LZO_OUTPUT_PADDING);
1136  if (!newpktdata) {
1137  result = AVERROR(ENOMEM);
1138  goto failed;
1139  }
1140  pkt_data = newpktdata;
1141  result = av_lzo1x_decode(pkt_data, &olen, data, &isize);
1142  } while (result==AV_LZO_OUTPUT_FULL && pkt_size<10000000);
1143  if (result) {
1144  result = AVERROR_INVALIDDATA;
1145  goto failed;
1146  }
1147  pkt_size -= olen;
1148  break;
1149 #endif
1150 #if CONFIG_ZLIB
1152  z_stream zstream = {0};
1153  if (inflateInit(&zstream) != Z_OK)
1154  return -1;
1155  zstream.next_in = data;
1156  zstream.avail_in = isize;
1157  do {
1158  pkt_size *= 3;
1159  newpktdata = av_realloc(pkt_data, pkt_size);
1160  if (!newpktdata) {
1161  inflateEnd(&zstream);
1162  goto failed;
1163  }
1164  pkt_data = newpktdata;
1165  zstream.avail_out = pkt_size - zstream.total_out;
1166  zstream.next_out = pkt_data + zstream.total_out;
1167  if (pkt_data) {
1168  result = inflate(&zstream, Z_NO_FLUSH);
1169  } else
1170  result = Z_MEM_ERROR;
1171  } while (result==Z_OK && pkt_size<10000000);
1172  pkt_size = zstream.total_out;
1173  inflateEnd(&zstream);
1174  if (result != Z_STREAM_END) {
1175  if (result == Z_MEM_ERROR)
1176  result = AVERROR(ENOMEM);
1177  else
1178  result = AVERROR_INVALIDDATA;
1179  goto failed;
1180  }
1181  break;
1182  }
1183 #endif
1184 #if CONFIG_BZLIB
1186  bz_stream bzstream = {0};
1187  if (BZ2_bzDecompressInit(&bzstream, 0, 0) != BZ_OK)
1188  return -1;
1189  bzstream.next_in = data;
1190  bzstream.avail_in = isize;
1191  do {
1192  pkt_size *= 3;
1193  newpktdata = av_realloc(pkt_data, pkt_size);
1194  if (!newpktdata) {
1195  BZ2_bzDecompressEnd(&bzstream);
1196  goto failed;
1197  }
1198  pkt_data = newpktdata;
1199  bzstream.avail_out = pkt_size - bzstream.total_out_lo32;
1200  bzstream.next_out = pkt_data + bzstream.total_out_lo32;
1201  if (pkt_data) {
1202  result = BZ2_bzDecompress(&bzstream);
1203  } else
1204  result = BZ_MEM_ERROR;
1205  } while (result==BZ_OK && pkt_size<10000000);
1206  pkt_size = bzstream.total_out_lo32;
1207  BZ2_bzDecompressEnd(&bzstream);
1208  if (result != BZ_STREAM_END) {
1209  if (result == BZ_MEM_ERROR)
1210  result = AVERROR(ENOMEM);
1211  else
1212  result = AVERROR_INVALIDDATA;
1213  goto failed;
1214  }
1215  break;
1216  }
1217 #endif
1218  default:
1219  return AVERROR_INVALIDDATA;
1220  }
1221 
1222  *buf = pkt_data;
1223  *buf_size = pkt_size;
1224  return 0;
1225  failed:
1226  av_free(pkt_data);
1227  return result;
1228 }
1229 
1230 #if FF_API_ASS_SSA
1231 static void matroska_fix_ass_packet(MatroskaDemuxContext *matroska,
1232  AVPacket *pkt, uint64_t display_duration)
1233 {
1234  AVBufferRef *line;
1235  char *layer, *ptr = pkt->data, *end = ptr+pkt->size;
1236  for (; *ptr!=',' && ptr<end-1; ptr++);
1237  if (*ptr == ',')
1238  ptr++;
1239  layer = ptr;
1240  for (; *ptr!=',' && ptr<end-1; ptr++);
1241  if (*ptr == ',') {
1242  int64_t end_pts = pkt->pts + display_duration;
1243  int sc = matroska->time_scale * pkt->pts / 10000000;
1244  int ec = matroska->time_scale * end_pts / 10000000;
1245  int sh, sm, ss, eh, em, es, len;
1246  sh = sc/360000; sc -= 360000*sh;
1247  sm = sc/ 6000; sc -= 6000*sm;
1248  ss = sc/ 100; sc -= 100*ss;
1249  eh = ec/360000; ec -= 360000*eh;
1250  em = ec/ 6000; ec -= 6000*em;
1251  es = ec/ 100; ec -= 100*es;
1252  *ptr++ = '\0';
1253  len = 50 + end-ptr + FF_INPUT_BUFFER_PADDING_SIZE;
1254  if (!(line = av_buffer_alloc(len)))
1255  return;
1256  snprintf(line->data, len,"Dialogue: %s,%d:%02d:%02d.%02d,%d:%02d:%02d.%02d,%s\r\n",
1257  layer, sh, sm, ss, sc, eh, em, es, ec, ptr);
1258  av_buffer_unref(&pkt->buf);
1259  pkt->buf = line;
1260  pkt->data = line->data;
1261  pkt->size = strlen(line->data);
1262  }
1263 }
1264 
1265 static int matroska_merge_packets(AVPacket *out, AVPacket *in)
1266 {
1267  int ret = av_grow_packet(out, in->size);
1268  if (ret < 0)
1269  return ret;
1270 
1271  memcpy(out->data + out->size - in->size, in->data, in->size);
1272 
1273  av_free_packet(in);
1274  av_free(in);
1275  return 0;
1276 }
1277 #endif
1278 
1280  AVDictionary **metadata, char *prefix)
1281 {
1282  MatroskaTag *tags = list->elem;
1283  char key[1024];
1284  int i;
1285 
1286  for (i=0; i < list->nb_elem; i++) {
1287  const char *lang = tags[i].lang && strcmp(tags[i].lang, "und") ?
1288  tags[i].lang : NULL;
1289 
1290  if (!tags[i].name) {
1291  av_log(s, AV_LOG_WARNING, "Skipping invalid tag with no TagName.\n");
1292  continue;
1293  }
1294  if (prefix) snprintf(key, sizeof(key), "%s/%s", prefix, tags[i].name);
1295  else av_strlcpy(key, tags[i].name, sizeof(key));
1296  if (tags[i].def || !lang) {
1297  av_dict_set(metadata, key, tags[i].string, 0);
1298  if (tags[i].sub.nb_elem)
1299  matroska_convert_tag(s, &tags[i].sub, metadata, key);
1300  }
1301  if (lang) {
1302  av_strlcat(key, "-", sizeof(key));
1303  av_strlcat(key, lang, sizeof(key));
1304  av_dict_set(metadata, key, tags[i].string, 0);
1305  if (tags[i].sub.nb_elem)
1306  matroska_convert_tag(s, &tags[i].sub, metadata, key);
1307  }
1308  }
1309  ff_metadata_conv(metadata, NULL, ff_mkv_metadata_conv);
1310 }
1311 
1313 {
1314  MatroskaDemuxContext *matroska = s->priv_data;
1315  MatroskaTags *tags = matroska->tags.elem;
1316  int i, j;
1317 
1318  for (i=0; i < matroska->tags.nb_elem; i++) {
1319  if (tags[i].target.attachuid) {
1320  MatroskaAttachement *attachment = matroska->attachments.elem;
1321  for (j=0; j<matroska->attachments.nb_elem; j++)
1322  if (attachment[j].uid == tags[i].target.attachuid
1323  && attachment[j].stream)
1324  matroska_convert_tag(s, &tags[i].tag,
1325  &attachment[j].stream->metadata, NULL);
1326  } else if (tags[i].target.chapteruid) {
1327  MatroskaChapter *chapter = matroska->chapters.elem;
1328  for (j=0; j<matroska->chapters.nb_elem; j++)
1329  if (chapter[j].uid == tags[i].target.chapteruid
1330  && chapter[j].chapter)
1331  matroska_convert_tag(s, &tags[i].tag,
1332  &chapter[j].chapter->metadata, NULL);
1333  } else if (tags[i].target.trackuid) {
1334  MatroskaTrack *track = matroska->tracks.elem;
1335  for (j=0; j<matroska->tracks.nb_elem; j++)
1336  if (track[j].uid == tags[i].target.trackuid && track[j].stream)
1337  matroska_convert_tag(s, &tags[i].tag,
1338  &track[j].stream->metadata, NULL);
1339  } else {
1340  matroska_convert_tag(s, &tags[i].tag, &s->metadata,
1341  tags[i].target.type);
1342  }
1343  }
1344 }
1345 
1347 {
1348  EbmlList *seekhead_list = &matroska->seekhead;
1349  MatroskaSeekhead *seekhead = seekhead_list->elem;
1350  uint32_t level_up = matroska->level_up;
1351  int64_t before_pos = avio_tell(matroska->ctx->pb);
1352  uint32_t saved_id = matroska->current_id;
1354  int64_t offset;
1355  int ret = 0;
1356 
1357  if (idx >= seekhead_list->nb_elem
1358  || seekhead[idx].id == MATROSKA_ID_SEEKHEAD
1359  || seekhead[idx].id == MATROSKA_ID_CLUSTER)
1360  return 0;
1361 
1362  /* seek */
1363  offset = seekhead[idx].pos + matroska->segment_start;
1364  if (avio_seek(matroska->ctx->pb, offset, SEEK_SET) == offset) {
1365  /* We don't want to lose our seekhead level, so we add
1366  * a dummy. This is a crude hack. */
1367  if (matroska->num_levels == EBML_MAX_DEPTH) {
1368  av_log(matroska->ctx, AV_LOG_INFO,
1369  "Max EBML element depth (%d) reached, "
1370  "cannot parse further.\n", EBML_MAX_DEPTH);
1371  ret = AVERROR_INVALIDDATA;
1372  } else {
1373  level.start = 0;
1374  level.length = (uint64_t)-1;
1375  matroska->levels[matroska->num_levels] = level;
1376  matroska->num_levels++;
1377  matroska->current_id = 0;
1378 
1379  ret = ebml_parse(matroska, matroska_segment, matroska);
1380 
1381  /* remove dummy level */
1382  while (matroska->num_levels) {
1383  uint64_t length = matroska->levels[--matroska->num_levels].length;
1384  if (length == (uint64_t)-1)
1385  break;
1386  }
1387  }
1388  }
1389  /* seek back */
1390  avio_seek(matroska->ctx->pb, before_pos, SEEK_SET);
1391  matroska->level_up = level_up;
1392  matroska->current_id = saved_id;
1393 
1394  return ret;
1395 }
1396 
1398 {
1399  EbmlList *seekhead_list = &matroska->seekhead;
1400  int64_t before_pos = avio_tell(matroska->ctx->pb);
1401  int i;
1402 
1403  // we should not do any seeking in the streaming case
1404  if (!matroska->ctx->pb->seekable ||
1405  (matroska->ctx->flags & AVFMT_FLAG_IGNIDX))
1406  return;
1407 
1408  for (i = 0; i < seekhead_list->nb_elem; i++) {
1409  MatroskaSeekhead *seekhead = seekhead_list->elem;
1410  if (seekhead[i].pos <= before_pos)
1411  continue;
1412 
1413  // defer cues parsing until we actually need cue data.
1414  if (seekhead[i].id == MATROSKA_ID_CUES) {
1415  matroska->cues_parsing_deferred = 1;
1416  continue;
1417  }
1418 
1419  if (matroska_parse_seekhead_entry(matroska, i) < 0) {
1420  // mark index as broken
1421  matroska->cues_parsing_deferred = -1;
1422  break;
1423  }
1424  }
1425 }
1426 
1428  EbmlList *index_list;
1430  int index_scale = 1;
1431  int i, j;
1432 
1433  index_list = &matroska->index;
1434  index = index_list->elem;
1435  if (index_list->nb_elem
1436  && index[0].time > 1E14/matroska->time_scale) {
1437  av_log(matroska->ctx, AV_LOG_WARNING, "Working around broken index.\n");
1438  index_scale = matroska->time_scale;
1439  }
1440  for (i = 0; i < index_list->nb_elem; i++) {
1441  EbmlList *pos_list = &index[i].pos;
1442  MatroskaIndexPos *pos = pos_list->elem;
1443  for (j = 0; j < pos_list->nb_elem; j++) {
1444  MatroskaTrack *track = matroska_find_track_by_num(matroska, pos[j].track);
1445  if (track && track->stream)
1446  av_add_index_entry(track->stream,
1447  pos[j].pos + matroska->segment_start,
1448  index[i].time/index_scale, 0, 0,
1450  }
1451  }
1452 }
1453 
1455  EbmlList *seekhead_list = &matroska->seekhead;
1456  MatroskaSeekhead *seekhead = seekhead_list->elem;
1457  int i;
1458 
1459  for (i = 0; i < seekhead_list->nb_elem; i++)
1460  if (seekhead[i].id == MATROSKA_ID_CUES)
1461  break;
1462  av_assert1(i <= seekhead_list->nb_elem);
1463 
1464  if (matroska_parse_seekhead_entry(matroska, i) < 0)
1465  matroska->cues_parsing_deferred = -1;
1466  matroska_add_index_entries(matroska);
1467 }
1468 
1470 {
1471  static const char * const aac_profiles[] = { "MAIN", "LC", "SSR" };
1472  int profile;
1473 
1474  for (profile=0; profile<FF_ARRAY_ELEMS(aac_profiles); profile++)
1475  if (strstr(codec_id, aac_profiles[profile]))
1476  break;
1477  return profile + 1;
1478 }
1479 
1480 static int matroska_aac_sri(int samplerate)
1481 {
1482  int sri;
1483 
1484  for (sri=0; sri<FF_ARRAY_ELEMS(avpriv_mpeg4audio_sample_rates); sri++)
1485  if (avpriv_mpeg4audio_sample_rates[sri] == samplerate)
1486  break;
1487  return sri;
1488 }
1489 
1490 static void matroska_metadata_creation_time(AVDictionary **metadata, int64_t date_utc)
1491 {
1492  char buffer[32];
1493  /* Convert to seconds and adjust by number of seconds between 2001-01-01 and Epoch */
1494  time_t creation_time = date_utc / 1000000000 + 978307200;
1495  struct tm *ptm = gmtime(&creation_time);
1496  if (!ptm) return;
1497  strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", ptm);
1498  av_dict_set(metadata, "creation_time", buffer, 0);
1499 }
1500 
1502 {
1503  MatroskaDemuxContext *matroska = s->priv_data;
1504  EbmlList *attachements_list = &matroska->attachments;
1505  MatroskaAttachement *attachements;
1506  EbmlList *chapters_list = &matroska->chapters;
1507  MatroskaChapter *chapters;
1508  MatroskaTrack *tracks;
1509  uint64_t max_start = 0;
1510  int64_t pos;
1511  Ebml ebml = { 0 };
1512  AVStream *st;
1513  int i, j, k, res;
1514 
1515  matroska->ctx = s;
1516 
1517  /* First read the EBML header. */
1518  if (ebml_parse(matroska, ebml_syntax, &ebml)
1519  || ebml.version > EBML_VERSION || ebml.max_size > sizeof(uint64_t)
1520  || ebml.id_length > sizeof(uint32_t) || ebml.doctype_version > 3 || !ebml.doctype) {
1521  av_log(matroska->ctx, AV_LOG_ERROR,
1522  "EBML header using unsupported features\n"
1523  "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
1524  ebml.version, ebml.doctype, ebml.doctype_version);
1525  ebml_free(ebml_syntax, &ebml);
1526  return AVERROR_PATCHWELCOME;
1527  } else if (ebml.doctype_version == 3) {
1528  av_log(matroska->ctx, AV_LOG_WARNING,
1529  "EBML header using unsupported features\n"
1530  "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
1531  ebml.version, ebml.doctype, ebml.doctype_version);
1532  }
1533  for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++)
1534  if (!strcmp(ebml.doctype, matroska_doctypes[i]))
1535  break;
1536  if (i >= FF_ARRAY_ELEMS(matroska_doctypes)) {
1537  av_log(s, AV_LOG_WARNING, "Unknown EBML doctype '%s'\n", ebml.doctype);
1538  if (matroska->ctx->error_recognition & AV_EF_EXPLODE) {
1539  ebml_free(ebml_syntax, &ebml);
1540  return AVERROR_INVALIDDATA;
1541  }
1542  }
1543  ebml_free(ebml_syntax, &ebml);
1544 
1545  /* The next thing is a segment. */
1546  pos = avio_tell(matroska->ctx->pb);
1547  res = ebml_parse(matroska, matroska_segments, matroska);
1548  // try resyncing until we find a EBML_STOP type element.
1549  while (res != 1) {
1550  res = matroska_resync(matroska, pos);
1551  if (res < 0)
1552  return res;
1553  pos = avio_tell(matroska->ctx->pb);
1554  res = ebml_parse(matroska, matroska_segment, matroska);
1555  }
1556  matroska_execute_seekhead(matroska);
1557 
1558  if (!matroska->time_scale)
1559  matroska->time_scale = 1000000;
1560  if (matroska->duration)
1561  matroska->ctx->duration = matroska->duration * matroska->time_scale
1562  * 1000 / AV_TIME_BASE;
1563  av_dict_set(&s->metadata, "title", matroska->title, 0);
1564 
1565  if (matroska->date_utc.size == 8)
1567 
1568  tracks = matroska->tracks.elem;
1569  for (i=0; i < matroska->tracks.nb_elem; i++) {
1570  MatroskaTrack *track = &tracks[i];
1572  EbmlList *encodings_list = &track->encodings;
1573  MatroskaTrackEncoding *encodings = encodings_list->elem;
1574  uint8_t *extradata = NULL;
1575  int extradata_size = 0;
1576  int extradata_offset = 0;
1577  uint32_t fourcc = 0;
1578  AVIOContext b;
1579  char* key_id_base64 = NULL;
1580 
1581  /* Apply some sanity checks. */
1582  if (track->type != MATROSKA_TRACK_TYPE_VIDEO &&
1583  track->type != MATROSKA_TRACK_TYPE_AUDIO &&
1584  track->type != MATROSKA_TRACK_TYPE_SUBTITLE &&
1585  track->type != MATROSKA_TRACK_TYPE_METADATA) {
1586  av_log(matroska->ctx, AV_LOG_INFO,
1587  "Unknown or unsupported track type %"PRIu64"\n",
1588  track->type);
1589  continue;
1590  }
1591  if (track->codec_id == NULL)
1592  continue;
1593 
1594  if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1595  if (!track->default_duration && track->video.frame_rate > 0)
1596  track->default_duration = 1000000000/track->video.frame_rate;
1597  if (track->video.display_width == -1)
1598  track->video.display_width = track->video.pixel_width;
1599  if (track->video.display_height == -1)
1600  track->video.display_height = track->video.pixel_height;
1601  if (track->video.color_space.size == 4)
1602  fourcc = AV_RL32(track->video.color_space.data);
1603  } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
1604  if (!track->audio.out_samplerate)
1605  track->audio.out_samplerate = track->audio.samplerate;
1606  }
1607  if (encodings_list->nb_elem > 1) {
1608  av_log(matroska->ctx, AV_LOG_ERROR,
1609  "Multiple combined encodings not supported");
1610  } else if (encodings_list->nb_elem == 1) {
1611  if (encodings[0].type) {
1612  if (encodings[0].encryption.key_id.size > 0) {
1613  /* Save the encryption key id to be stored later as a
1614  metadata tag. */
1615  const int b64_size = AV_BASE64_SIZE(encodings[0].encryption.key_id.size);
1616  key_id_base64 = av_malloc(b64_size);
1617  if (key_id_base64 == NULL)
1618  return AVERROR(ENOMEM);
1619 
1620  av_base64_encode(key_id_base64, b64_size,
1621  encodings[0].encryption.key_id.data,
1622  encodings[0].encryption.key_id.size);
1623  } else {
1624  encodings[0].scope = 0;
1625  av_log(matroska->ctx, AV_LOG_ERROR,
1626  "Unsupported encoding type");
1627  }
1628  } else if (
1629 #if CONFIG_ZLIB
1630  encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_ZLIB &&
1631 #endif
1632 #if CONFIG_BZLIB
1634 #endif
1635 #if CONFIG_LZO
1637 #endif
1639  encodings[0].scope = 0;
1640  av_log(matroska->ctx, AV_LOG_ERROR,
1641  "Unsupported encoding type");
1642  } else if (track->codec_priv.size && encodings[0].scope&2) {
1643  uint8_t *codec_priv = track->codec_priv.data;
1644  int ret = matroska_decode_buffer(&track->codec_priv.data,
1645  &track->codec_priv.size,
1646  track);
1647  if (ret < 0) {
1648  track->codec_priv.data = NULL;
1649  track->codec_priv.size = 0;
1650  av_log(matroska->ctx, AV_LOG_ERROR,
1651  "Failed to decode codec private data\n");
1652  }
1653 
1654  if (codec_priv != track->codec_priv.data)
1655  av_free(codec_priv);
1656  }
1657  }
1658 
1659  for(j=0; ff_mkv_codec_tags[j].id != AV_CODEC_ID_NONE; j++){
1660  if(!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
1661  strlen(ff_mkv_codec_tags[j].str))){
1662  codec_id= ff_mkv_codec_tags[j].id;
1663  break;
1664  }
1665  }
1666 
1667  st = track->stream = avformat_new_stream(s, NULL);
1668  if (st == NULL) {
1669  av_free(key_id_base64);
1670  return AVERROR(ENOMEM);
1671  }
1672 
1673  if (key_id_base64) {
1674  /* export encryption key id as base64 metadata tag */
1675  av_dict_set(&st->metadata, "enc_key_id", key_id_base64, 0);
1676  av_freep(&key_id_base64);
1677  }
1678 
1679  if (!strcmp(track->codec_id, "V_MS/VFW/FOURCC")
1680  && track->codec_priv.size >= 40
1681  && track->codec_priv.data != NULL) {
1682  track->ms_compat = 1;
1683  fourcc = AV_RL32(track->codec_priv.data + 16);
1684  codec_id = ff_codec_get_id(ff_codec_bmp_tags, fourcc);
1685  extradata_offset = 40;
1686  } else if (!strcmp(track->codec_id, "A_MS/ACM")
1687  && track->codec_priv.size >= 14
1688  && track->codec_priv.data != NULL) {
1689  int ret;
1690  ffio_init_context(&b, track->codec_priv.data, track->codec_priv.size,
1691  0, NULL, NULL, NULL, NULL);
1692  ret = ff_get_wav_header(&b, st->codec, track->codec_priv.size);
1693  if (ret < 0)
1694  return ret;
1695  codec_id = st->codec->codec_id;
1696  extradata_offset = FFMIN(track->codec_priv.size, 18);
1697  } else if (!strcmp(track->codec_id, "V_QUICKTIME")
1698  && (track->codec_priv.size >= 86)
1699  && (track->codec_priv.data != NULL)) {
1700  fourcc = AV_RL32(track->codec_priv.data);
1701  codec_id = ff_codec_get_id(ff_codec_movvideo_tags, fourcc);
1702  } else if (codec_id == AV_CODEC_ID_PCM_S16BE) {
1703  switch (track->audio.bitdepth) {
1704  case 8: codec_id = AV_CODEC_ID_PCM_U8; break;
1705  case 24: codec_id = AV_CODEC_ID_PCM_S24BE; break;
1706  case 32: codec_id = AV_CODEC_ID_PCM_S32BE; break;
1707  }
1708  } else if (codec_id == AV_CODEC_ID_PCM_S16LE) {
1709  switch (track->audio.bitdepth) {
1710  case 8: codec_id = AV_CODEC_ID_PCM_U8; break;
1711  case 24: codec_id = AV_CODEC_ID_PCM_S24LE; break;
1712  case 32: codec_id = AV_CODEC_ID_PCM_S32LE; break;
1713  }
1714  } else if (codec_id==AV_CODEC_ID_PCM_F32LE && track->audio.bitdepth==64) {
1715  codec_id = AV_CODEC_ID_PCM_F64LE;
1716  } else if (codec_id == AV_CODEC_ID_AAC && !track->codec_priv.size) {
1717  int profile = matroska_aac_profile(track->codec_id);
1718  int sri = matroska_aac_sri(track->audio.samplerate);
1719  extradata = av_mallocz(5 + FF_INPUT_BUFFER_PADDING_SIZE);
1720  if (extradata == NULL)
1721  return AVERROR(ENOMEM);
1722  extradata[0] = (profile << 3) | ((sri&0x0E) >> 1);
1723  extradata[1] = ((sri&0x01) << 7) | (track->audio.channels<<3);
1724  if (strstr(track->codec_id, "SBR")) {
1725  sri = matroska_aac_sri(track->audio.out_samplerate);
1726  extradata[2] = 0x56;
1727  extradata[3] = 0xE5;
1728  extradata[4] = 0x80 | (sri<<3);
1729  extradata_size = 5;
1730  } else
1731  extradata_size = 2;
1732  } else if (codec_id == AV_CODEC_ID_ALAC && track->codec_priv.size && track->codec_priv.size < INT_MAX - 12 - FF_INPUT_BUFFER_PADDING_SIZE) {
1733  /* Only ALAC's magic cookie is stored in Matroska's track headers.
1734  Create the "atom size", "tag", and "tag version" fields the
1735  decoder expects manually. */
1736  extradata_size = 12 + track->codec_priv.size;
1737  extradata = av_mallocz(extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
1738  if (extradata == NULL)
1739  return AVERROR(ENOMEM);
1740  AV_WB32(extradata, extradata_size);
1741  memcpy(&extradata[4], "alac", 4);
1742  AV_WB32(&extradata[8], 0);
1743  memcpy(&extradata[12], track->codec_priv.data,
1744  track->codec_priv.size);
1745  } else if (codec_id == AV_CODEC_ID_TTA) {
1746  extradata_size = 30;
1747  extradata = av_mallocz(extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
1748  if (extradata == NULL)
1749  return AVERROR(ENOMEM);
1750  ffio_init_context(&b, extradata, extradata_size, 1,
1751  NULL, NULL, NULL, NULL);
1752  avio_write(&b, "TTA1", 4);
1753  avio_wl16(&b, 1);
1754  avio_wl16(&b, track->audio.channels);
1755  avio_wl16(&b, track->audio.bitdepth);
1756  if (track->audio.out_samplerate < 0 || track->audio.out_samplerate > INT_MAX)
1757  return AVERROR_INVALIDDATA;
1758  avio_wl32(&b, track->audio.out_samplerate);
1759  avio_wl32(&b, av_rescale((matroska->duration * matroska->time_scale), track->audio.out_samplerate, AV_TIME_BASE * 1000));
1760  } else if (codec_id == AV_CODEC_ID_RV10 || codec_id == AV_CODEC_ID_RV20 ||
1761  codec_id == AV_CODEC_ID_RV30 || codec_id == AV_CODEC_ID_RV40) {
1762  extradata_offset = 26;
1763  } else if (codec_id == AV_CODEC_ID_RA_144) {
1764  track->audio.out_samplerate = 8000;
1765  track->audio.channels = 1;
1766  } else if ((codec_id == AV_CODEC_ID_RA_288 || codec_id == AV_CODEC_ID_COOK ||
1767  codec_id == AV_CODEC_ID_ATRAC3 || codec_id == AV_CODEC_ID_SIPR)
1768  && track->codec_priv.data) {
1769  int flavor;
1770 
1771  ffio_init_context(&b, track->codec_priv.data,track->codec_priv.size,
1772  0, NULL, NULL, NULL, NULL);
1773  avio_skip(&b, 22);
1774  flavor = avio_rb16(&b);
1775  track->audio.coded_framesize = avio_rb32(&b);
1776  avio_skip(&b, 12);
1777  track->audio.sub_packet_h = avio_rb16(&b);
1778  track->audio.frame_size = avio_rb16(&b);
1779  track->audio.sub_packet_size = avio_rb16(&b);
1780  if (flavor <= 0 || track->audio.coded_framesize <= 0 ||
1781  track->audio.sub_packet_h <= 0 || track->audio.frame_size <= 0 ||
1782  track->audio.sub_packet_size <= 0)
1783  return AVERROR_INVALIDDATA;
1784  track->audio.buf = av_malloc_array(track->audio.sub_packet_h, track->audio.frame_size);
1785  if (!track->audio.buf)
1786  return AVERROR(ENOMEM);
1787  if (codec_id == AV_CODEC_ID_RA_288) {
1788  st->codec->block_align = track->audio.coded_framesize;
1789  track->codec_priv.size = 0;
1790  } else {
1791  if (codec_id == AV_CODEC_ID_SIPR && flavor < 4) {
1792  static const int sipr_bit_rate[4] = { 6504, 8496, 5000, 16000 };
1793  track->audio.sub_packet_size = ff_sipr_subpk_size[flavor];
1794  st->codec->bit_rate = sipr_bit_rate[flavor];
1795  }
1796  st->codec->block_align = track->audio.sub_packet_size;
1797  extradata_offset = 78;
1798  }
1799  }
1800  track->codec_priv.size -= extradata_offset;
1801 
1802  if (codec_id == AV_CODEC_ID_NONE)
1803  av_log(matroska->ctx, AV_LOG_INFO,
1804  "Unknown/unsupported AVCodecID %s.\n", track->codec_id);
1805 
1806  if (track->time_scale < 0.01)
1807  track->time_scale = 1.0;
1808  avpriv_set_pts_info(st, 64, matroska->time_scale*track->time_scale, 1000*1000*1000); /* 64 bit pts in ns */
1809 
1810  st->codec->codec_id = codec_id;
1811  st->start_time = 0;
1812  if (strcmp(track->language, "und"))
1813  av_dict_set(&st->metadata, "language", track->language, 0);
1814  av_dict_set(&st->metadata, "title", track->name, 0);
1815 
1816  if (track->flag_default)
1818  if (track->flag_forced)
1820 
1821  if (!st->codec->extradata) {
1822  if(extradata){
1823  st->codec->extradata = extradata;
1824  st->codec->extradata_size = extradata_size;
1825  } else if(track->codec_priv.data && track->codec_priv.size > 0){
1826  if (ff_alloc_extradata(st->codec, track->codec_priv.size))
1827  return AVERROR(ENOMEM);
1828  memcpy(st->codec->extradata,
1829  track->codec_priv.data + extradata_offset,
1830  track->codec_priv.size);
1831  }
1832  }
1833 
1834  if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1836 
1838  st->codec->codec_tag = fourcc;
1839  st->codec->width = track->video.pixel_width;
1840  st->codec->height = track->video.pixel_height;
1842  &st->sample_aspect_ratio.den,
1843  st->codec->height * track->video.display_width,
1844  st->codec-> width * track->video.display_height,
1845  255);
1846  if (st->codec->codec_id != AV_CODEC_ID_HEVC)
1848  if (track->default_duration) {
1850  1000000000, track->default_duration, 30000);
1851 #if FF_API_R_FRAME_RATE
1852  if (st->avg_frame_rate.num < st->avg_frame_rate.den * 1000L)
1853  st->r_frame_rate = st->avg_frame_rate;
1854 #endif
1855  }
1856 
1857  /* export stereo mode flag as metadata tag */
1859  av_dict_set(&st->metadata, "stereo_mode", ff_matroska_video_stereo_mode[track->video.stereo_mode], 0);
1860 
1861  /* export alpha mode flag as metadata tag */
1862  if (track->video.alpha_mode)
1863  av_dict_set(&st->metadata, "alpha_mode", "1", 0);
1864 
1865  /* if we have virtual track, mark the real tracks */
1866  for (j=0; j < track->operation.combine_planes.nb_elem; j++) {
1867  char buf[32];
1868  if (planes[j].type >= MATROSKA_VIDEO_STEREO_PLANE_COUNT)
1869  continue;
1870  snprintf(buf, sizeof(buf), "%s_%d",
1871  ff_matroska_video_stereo_plane[planes[j].type], i);
1872  for (k=0; k < matroska->tracks.nb_elem; k++)
1873  if (planes[j].uid == tracks[k].uid) {
1874  av_dict_set(&s->streams[k]->metadata,
1875  "stereo_mode", buf, 0);
1876  break;
1877  }
1878  }
1879  } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
1881  st->codec->sample_rate = track->audio.out_samplerate;
1882  st->codec->channels = track->audio.channels;
1883  st->codec->bits_per_coded_sample = track->audio.bitdepth;
1884  if (st->codec->codec_id != AV_CODEC_ID_AAC)
1886  if (track->codec_delay > 0) {
1887  st->codec->delay = av_rescale_q(track->codec_delay,
1888  (AVRational){1, 1000000000},
1889  (AVRational){1, st->codec->sample_rate});
1890  }
1891  if (track->seek_preroll > 0) {
1893  av_rescale_q(track->seek_preroll,
1894  (AVRational){1, 1000000000},
1895  (AVRational){1, st->codec->sample_rate}));
1896  }
1897  } else if (codec_id == AV_CODEC_ID_WEBVTT) {
1898  st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
1899 
1900  if (!strcmp(track->codec_id, "D_WEBVTT/CAPTIONS")) {
1901  st->disposition |= AV_DISPOSITION_CAPTIONS;
1902  } else if (!strcmp(track->codec_id, "D_WEBVTT/DESCRIPTIONS")) {
1903  st->disposition |= AV_DISPOSITION_DESCRIPTIONS;
1904  } else if (!strcmp(track->codec_id, "D_WEBVTT/METADATA")) {
1905  st->disposition |= AV_DISPOSITION_METADATA;
1906  }
1907  } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
1908  st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
1909 #if FF_API_ASS_SSA
1910  if (st->codec->codec_id == AV_CODEC_ID_SSA ||
1911  st->codec->codec_id == AV_CODEC_ID_ASS)
1912 #else
1913  if (st->codec->codec_id == AV_CODEC_ID_ASS)
1914 #endif
1915  matroska->contains_ssa = 1;
1916  }
1917  }
1918 
1919  attachements = attachements_list->elem;
1920  for (j=0; j<attachements_list->nb_elem; j++) {
1921  if (!(attachements[j].filename && attachements[j].mime &&
1922  attachements[j].bin.data && attachements[j].bin.size > 0)) {
1923  av_log(matroska->ctx, AV_LOG_ERROR, "incomplete attachment\n");
1924  } else {
1925  AVStream *st = avformat_new_stream(s, NULL);
1926  if (st == NULL)
1927  break;
1928  av_dict_set(&st->metadata, "filename",attachements[j].filename, 0);
1929  av_dict_set(&st->metadata, "mimetype", attachements[j].mime, 0);
1932  if (ff_alloc_extradata(st->codec, attachements[j].bin.size))
1933  break;
1934  memcpy(st->codec->extradata, attachements[j].bin.data, attachements[j].bin.size);
1935 
1936  for (i=0; ff_mkv_mime_tags[i].id != AV_CODEC_ID_NONE; i++) {
1937  if (!strncmp(ff_mkv_mime_tags[i].str, attachements[j].mime,
1938  strlen(ff_mkv_mime_tags[i].str))) {
1939  st->codec->codec_id = ff_mkv_mime_tags[i].id;
1940  break;
1941  }
1942  }
1943  attachements[j].stream = st;
1944  }
1945  }
1946 
1947  chapters = chapters_list->elem;
1948  for (i=0; i<chapters_list->nb_elem; i++)
1949  if (chapters[i].start != AV_NOPTS_VALUE && chapters[i].uid
1950  && (max_start==0 || chapters[i].start > max_start)) {
1951  chapters[i].chapter =
1952  avpriv_new_chapter(s, chapters[i].uid, (AVRational){1, 1000000000},
1953  chapters[i].start, chapters[i].end,
1954  chapters[i].title);
1955  av_dict_set(&chapters[i].chapter->metadata,
1956  "title", chapters[i].title, 0);
1957  max_start = chapters[i].start;
1958  }
1959 
1960  matroska_add_index_entries(matroska);
1961 
1963 
1964  return 0;
1965 }
1966 
1967 /*
1968  * Put one packet in an application-supplied AVPacket struct.
1969  * Returns 0 on success or -1 on failure.
1970  */
1972  AVPacket *pkt)
1973 {
1974  if (matroska->num_packets > 0) {
1975  memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
1976  av_free(matroska->packets[0]);
1977  if (matroska->num_packets > 1) {
1978  void *newpackets;
1979  memmove(&matroska->packets[0], &matroska->packets[1],
1980  (matroska->num_packets - 1) * sizeof(AVPacket *));
1981  newpackets = av_realloc(matroska->packets,
1982  (matroska->num_packets - 1) * sizeof(AVPacket *));
1983  if (newpackets)
1984  matroska->packets = newpackets;
1985  } else {
1986  av_freep(&matroska->packets);
1987  matroska->prev_pkt = NULL;
1988  }
1989  matroska->num_packets--;
1990  return 0;
1991  }
1992 
1993  return -1;
1994 }
1995 
1996 /*
1997  * Free all packets in our internal queue.
1998  */
2000 {
2001  matroska->prev_pkt = NULL;
2002  if (matroska->packets) {
2003  int n;
2004  for (n = 0; n < matroska->num_packets; n++) {
2005  av_free_packet(matroska->packets[n]);
2006  av_free(matroska->packets[n]);
2007  }
2008  av_freep(&matroska->packets);
2009  matroska->num_packets = 0;
2010  }
2011 }
2012 
2014  int* buf_size, int type,
2015  uint32_t **lace_buf, int *laces)
2016 {
2017  int res = 0, n, size = *buf_size;
2018  uint8_t *data = *buf;
2019  uint32_t *lace_size;
2020 
2021  if (!type) {
2022  *laces = 1;
2023  *lace_buf = av_mallocz(sizeof(int));
2024  if (!*lace_buf)
2025  return AVERROR(ENOMEM);
2026 
2027  *lace_buf[0] = size;
2028  return 0;
2029  }
2030 
2031  av_assert0(size > 0);
2032  *laces = *data + 1;
2033  data += 1;
2034  size -= 1;
2035  lace_size = av_mallocz(*laces * sizeof(int));
2036  if (!lace_size)
2037  return AVERROR(ENOMEM);
2038 
2039  switch (type) {
2040  case 0x1: /* Xiph lacing */ {
2041  uint8_t temp;
2042  uint32_t total = 0;
2043  for (n = 0; res == 0 && n < *laces - 1; n++) {
2044  while (1) {
2045  if (size <= total) {
2046  res = AVERROR_INVALIDDATA;
2047  break;
2048  }
2049  temp = *data;
2050  total += temp;
2051  lace_size[n] += temp;
2052  data += 1;
2053  size -= 1;
2054  if (temp != 0xff)
2055  break;
2056  }
2057  }
2058  if (size <= total) {
2059  res = AVERROR_INVALIDDATA;
2060  break;
2061  }
2062 
2063  lace_size[n] = size - total;
2064  break;
2065  }
2066 
2067  case 0x2: /* fixed-size lacing */
2068  if (size % (*laces)) {
2069  res = AVERROR_INVALIDDATA;
2070  break;
2071  }
2072  for (n = 0; n < *laces; n++)
2073  lace_size[n] = size / *laces;
2074  break;
2075 
2076  case 0x3: /* EBML lacing */ {
2077  uint64_t num;
2078  uint64_t total;
2079  n = matroska_ebmlnum_uint(matroska, data, size, &num);
2080  if (n < 0 || num > INT_MAX) {
2081  av_log(matroska->ctx, AV_LOG_INFO,
2082  "EBML block data error\n");
2083  res = n<0 ? n : AVERROR_INVALIDDATA;
2084  break;
2085  }
2086  data += n;
2087  size -= n;
2088  total = lace_size[0] = num;
2089  for (n = 1; res == 0 && n < *laces - 1; n++) {
2090  int64_t snum;
2091  int r;
2092  r = matroska_ebmlnum_sint(matroska, data, size, &snum);
2093  if (r < 0 || lace_size[n - 1] + snum > (uint64_t)INT_MAX) {
2094  av_log(matroska->ctx, AV_LOG_INFO,
2095  "EBML block data error\n");
2096  res = r<0 ? r : AVERROR_INVALIDDATA;
2097  break;
2098  }
2099  data += r;
2100  size -= r;
2101  lace_size[n] = lace_size[n - 1] + snum;
2102  total += lace_size[n];
2103  }
2104  if (size <= total) {
2105  res = AVERROR_INVALIDDATA;
2106  break;
2107  }
2108  lace_size[*laces - 1] = size - total;
2109  break;
2110  }
2111  }
2112 
2113  *buf = data;
2114  *lace_buf = lace_size;
2115  *buf_size = size;
2116 
2117  return res;
2118 }
2119 
2121  MatroskaTrack *track,
2122  AVStream *st,
2123  uint8_t *data, int size,
2124  uint64_t timecode,
2125  int64_t pos)
2126 {
2127  int a = st->codec->block_align;
2128  int sps = track->audio.sub_packet_size;
2129  int cfs = track->audio.coded_framesize;
2130  int h = track->audio.sub_packet_h;
2131  int y = track->audio.sub_packet_cnt;
2132  int w = track->audio.frame_size;
2133  int x;
2134 
2135  if (!track->audio.pkt_cnt) {
2136  if (track->audio.sub_packet_cnt == 0)
2137  track->audio.buf_timecode = timecode;
2138  if (st->codec->codec_id == AV_CODEC_ID_RA_288) {
2139  if (size < cfs * h / 2) {
2140  av_log(matroska->ctx, AV_LOG_ERROR,
2141  "Corrupt int4 RM-style audio packet size\n");
2142  return AVERROR_INVALIDDATA;
2143  }
2144  for (x=0; x<h/2; x++)
2145  memcpy(track->audio.buf+x*2*w+y*cfs,
2146  data+x*cfs, cfs);
2147  } else if (st->codec->codec_id == AV_CODEC_ID_SIPR) {
2148  if (size < w) {
2149  av_log(matroska->ctx, AV_LOG_ERROR,
2150  "Corrupt sipr RM-style audio packet size\n");
2151  return AVERROR_INVALIDDATA;
2152  }
2153  memcpy(track->audio.buf + y*w, data, w);
2154  } else {
2155  if (size < sps * w / sps || h<=0) {
2156  av_log(matroska->ctx, AV_LOG_ERROR,
2157  "Corrupt generic RM-style audio packet size\n");
2158  return AVERROR_INVALIDDATA;
2159  }
2160  for (x=0; x<w/sps; x++)
2161  memcpy(track->audio.buf+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), data+x*sps, sps);
2162  }
2163 
2164  if (++track->audio.sub_packet_cnt >= h) {
2165  if (st->codec->codec_id == AV_CODEC_ID_SIPR)
2166  ff_rm_reorder_sipr_data(track->audio.buf, h, w);
2167  track->audio.sub_packet_cnt = 0;
2168  track->audio.pkt_cnt = h*w / a;
2169  }
2170  }
2171 
2172  while (track->audio.pkt_cnt) {
2173  AVPacket *pkt = NULL;
2174  if (!(pkt = av_mallocz(sizeof(AVPacket))) || av_new_packet(pkt, a) < 0){
2175  av_free(pkt);
2176  return AVERROR(ENOMEM);
2177  }
2178  memcpy(pkt->data, track->audio.buf
2179  + a * (h*w / a - track->audio.pkt_cnt--), a);
2180  pkt->pts = track->audio.buf_timecode;
2182  pkt->pos = pos;
2183  pkt->stream_index = st->index;
2184  dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
2185  }
2186 
2187  return 0;
2188 }
2189 
2190 /* reconstruct full wavpack blocks from mangled matroska ones */
2192  uint8_t **pdst, int *size)
2193 {
2194  uint8_t *dst = NULL;
2195  int dstlen = 0;
2196  int srclen = *size;
2197  uint32_t samples;
2198  uint16_t ver;
2199  int ret, offset = 0;
2200 
2201  if (srclen < 12 || track->stream->codec->extradata_size < 2)
2202  return AVERROR_INVALIDDATA;
2203 
2204  ver = AV_RL16(track->stream->codec->extradata);
2205 
2206  samples = AV_RL32(src);
2207  src += 4;
2208  srclen -= 4;
2209 
2210  while (srclen >= 8) {
2211  int multiblock;
2212  uint32_t blocksize;
2213  uint8_t *tmp;
2214 
2215  uint32_t flags = AV_RL32(src);
2216  uint32_t crc = AV_RL32(src + 4);
2217  src += 8;
2218  srclen -= 8;
2219 
2220  multiblock = (flags & 0x1800) != 0x1800;
2221  if (multiblock) {
2222  if (srclen < 4) {
2223  ret = AVERROR_INVALIDDATA;
2224  goto fail;
2225  }
2226  blocksize = AV_RL32(src);
2227  src += 4;
2228  srclen -= 4;
2229  } else
2230  blocksize = srclen;
2231 
2232  if (blocksize > srclen) {
2233  ret = AVERROR_INVALIDDATA;
2234  goto fail;
2235  }
2236 
2237  tmp = av_realloc(dst, dstlen + blocksize + 32);
2238  if (!tmp) {
2239  ret = AVERROR(ENOMEM);
2240  goto fail;
2241  }
2242  dst = tmp;
2243  dstlen += blocksize + 32;
2244 
2245  AV_WL32(dst + offset, MKTAG('w', 'v', 'p', 'k')); // tag
2246  AV_WL32(dst + offset + 4, blocksize + 24); // blocksize - 8
2247  AV_WL16(dst + offset + 8, ver); // version
2248  AV_WL16(dst + offset + 10, 0); // track/index_no
2249  AV_WL32(dst + offset + 12, 0); // total samples
2250  AV_WL32(dst + offset + 16, 0); // block index
2251  AV_WL32(dst + offset + 20, samples); // number of samples
2252  AV_WL32(dst + offset + 24, flags); // flags
2253  AV_WL32(dst + offset + 28, crc); // crc
2254  memcpy (dst + offset + 32, src, blocksize); // block data
2255 
2256  src += blocksize;
2257  srclen -= blocksize;
2258  offset += blocksize + 32;
2259  }
2260 
2261  *pdst = dst;
2262  *size = dstlen;
2263 
2264  return 0;
2265 
2266 fail:
2267  av_freep(&dst);
2268  return ret;
2269 }
2270 
2272  MatroskaTrack *track,
2273  AVStream *st,
2274  uint8_t *data, int data_len,
2275  uint64_t timecode,
2276  uint64_t duration,
2277  int64_t pos)
2278 {
2279  AVPacket *pkt;
2280  uint8_t *id, *settings, *text, *buf;
2281  int id_len, settings_len, text_len;
2282  uint8_t *p, *q;
2283  int err;
2284 
2285  if (data_len <= 0)
2286  return AVERROR_INVALIDDATA;
2287 
2288  p = data;
2289  q = data + data_len;
2290 
2291  id = p;
2292  id_len = -1;
2293  while (p < q) {
2294  if (*p == '\r' || *p == '\n') {
2295  id_len = p - id;
2296  if (*p == '\r')
2297  p++;
2298  break;
2299  }
2300  p++;
2301  }
2302 
2303  if (p >= q || *p != '\n')
2304  return AVERROR_INVALIDDATA;
2305  p++;
2306 
2307  settings = p;
2308  settings_len = -1;
2309  while (p < q) {
2310  if (*p == '\r' || *p == '\n') {
2311  settings_len = p - settings;
2312  if (*p == '\r')
2313  p++;
2314  break;
2315  }
2316  p++;
2317  }
2318 
2319  if (p >= q || *p != '\n')
2320  return AVERROR_INVALIDDATA;
2321  p++;
2322 
2323  text = p;
2324  text_len = q - p;
2325  while (text_len > 0) {
2326  const int len = text_len - 1;
2327  const uint8_t c = p[len];
2328  if (c != '\r' && c != '\n')
2329  break;
2330  text_len = len;
2331  }
2332 
2333  if (text_len <= 0)
2334  return AVERROR_INVALIDDATA;
2335 
2336  pkt = av_mallocz(sizeof(*pkt));
2337  err = av_new_packet(pkt, text_len);
2338  if (err < 0) {
2339  av_free(pkt);
2340  return AVERROR(err);
2341  }
2342 
2343  memcpy(pkt->data, text, text_len);
2344 
2345  if (id_len > 0) {
2346  buf = av_packet_new_side_data(pkt,
2348  id_len);
2349  if (buf == NULL) {
2350  av_free(pkt);
2351  return AVERROR(ENOMEM);
2352  }
2353  memcpy(buf, id, id_len);
2354  }
2355 
2356  if (settings_len > 0) {
2357  buf = av_packet_new_side_data(pkt,
2359  settings_len);
2360  if (buf == NULL) {
2361  av_free(pkt);
2362  return AVERROR(ENOMEM);
2363  }
2364  memcpy(buf, settings, settings_len);
2365  }
2366 
2367  // Do we need this for subtitles?
2368  // pkt->flags = AV_PKT_FLAG_KEY;
2369 
2370  pkt->stream_index = st->index;
2371  pkt->pts = timecode;
2372 
2373  // Do we need this for subtitles?
2374  // pkt->dts = timecode;
2375 
2376  pkt->duration = duration;
2377  pkt->pos = pos;
2378 
2379  dynarray_add(&matroska->packets, &matroska->num_packets, pkt);
2380  matroska->prev_pkt = pkt;
2381 
2382  return 0;
2383 }
2384 
2386  MatroskaTrack *track,
2387  AVStream *st,
2388  uint8_t *data, int pkt_size,
2389  uint64_t timecode, uint64_t lace_duration,
2390  int64_t pos, int is_keyframe,
2391  uint8_t *additional, uint64_t additional_id, int additional_size,
2392  uint64_t discard_padding)
2393 {
2394  MatroskaTrackEncoding *encodings = track->encodings.elem;
2395  uint8_t *pkt_data = data;
2396  int offset = 0, res;
2397  AVPacket *pkt;
2398 
2399  if (encodings && !encodings->type && encodings->scope & 1) {
2400  res = matroska_decode_buffer(&pkt_data, &pkt_size, track);
2401  if (res < 0)
2402  return res;
2403  }
2404 
2405  if (st->codec->codec_id == AV_CODEC_ID_WAVPACK) {
2406  uint8_t *wv_data;
2407  res = matroska_parse_wavpack(track, pkt_data, &wv_data, &pkt_size);
2408  if (res < 0) {
2409  av_log(matroska->ctx, AV_LOG_ERROR, "Error parsing a wavpack block.\n");
2410  goto fail;
2411  }
2412  if (pkt_data != data)
2413  av_freep(&pkt_data);
2414  pkt_data = wv_data;
2415  }
2416 
2417  if (st->codec->codec_id == AV_CODEC_ID_PRORES)
2418  offset = 8;
2419 
2420  pkt = av_mallocz(sizeof(AVPacket));
2421  /* XXX: prevent data copy... */
2422  if (av_new_packet(pkt, pkt_size + offset) < 0) {
2423  av_free(pkt);
2424  res = AVERROR(ENOMEM);
2425  goto fail;
2426  }
2427 
2428  if (st->codec->codec_id == AV_CODEC_ID_PRORES) {
2429  uint8_t *buf = pkt->data;
2430  bytestream_put_be32(&buf, pkt_size);
2431  bytestream_put_be32(&buf, MKBETAG('i', 'c', 'p', 'f'));
2432  }
2433 
2434  memcpy(pkt->data + offset, pkt_data, pkt_size);
2435 
2436  if (pkt_data != data)
2437  av_freep(&pkt_data);
2438 
2439  pkt->flags = is_keyframe;
2440  pkt->stream_index = st->index;
2441 
2442  if (additional_size > 0) {
2443  uint8_t *side_data = av_packet_new_side_data(pkt,
2445  additional_size + 8);
2446  if(side_data == NULL) {
2447  av_free_packet(pkt);
2448  av_free(pkt);
2449  return AVERROR(ENOMEM);
2450  }
2451  AV_WB64(side_data, additional_id);
2452  memcpy(side_data + 8, additional, additional_size);
2453  }
2454 
2455  if (discard_padding) {
2456  uint8_t *side_data = av_packet_new_side_data(pkt,
2458  10);
2459  if(side_data == NULL) {
2460  av_free_packet(pkt);
2461  av_free(pkt);
2462  return AVERROR(ENOMEM);
2463  }
2464  AV_WL32(side_data, 0);
2465  AV_WL32(side_data + 4, av_rescale_q(discard_padding,
2466  (AVRational){1, 1000000000},
2467  (AVRational){1, st->codec->sample_rate}));
2468  }
2469 
2470  if (track->ms_compat)
2471  pkt->dts = timecode;
2472  else
2473  pkt->pts = timecode;
2474  pkt->pos = pos;
2475  if (st->codec->codec_id == AV_CODEC_ID_SUBRIP) {
2476  /*
2477  * For backward compatibility.
2478  * Historically, we have put subtitle duration
2479  * in convergence_duration, on the off chance
2480  * that the time_scale is less than 1us, which
2481  * could result in a 32bit overflow on the
2482  * normal duration field.
2483  */
2484  pkt->convergence_duration = lace_duration;
2485  }
2486 
2487  if (track->type != MATROSKA_TRACK_TYPE_SUBTITLE ||
2488  lace_duration <= INT_MAX) {
2489  /*
2490  * For non subtitle tracks, just store the duration
2491  * as normal.
2492  *
2493  * If it's a subtitle track and duration value does
2494  * not overflow a uint32, then also store it normally.
2495  */
2496  pkt->duration = lace_duration;
2497  }
2498 
2499 #if FF_API_ASS_SSA
2500  if (st->codec->codec_id == AV_CODEC_ID_SSA)
2501  matroska_fix_ass_packet(matroska, pkt, lace_duration);
2502 
2503  if (matroska->prev_pkt &&
2504  timecode != AV_NOPTS_VALUE &&
2505  matroska->prev_pkt->pts == timecode &&
2506  matroska->prev_pkt->stream_index == st->index &&
2507  st->codec->codec_id == AV_CODEC_ID_SSA)
2508  matroska_merge_packets(matroska->prev_pkt, pkt);
2509  else {
2510  dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
2511  matroska->prev_pkt = pkt;
2512  }
2513 #else
2514  dynarray_add(&matroska->packets, &matroska->num_packets, pkt);
2515  matroska->prev_pkt = pkt;
2516 #endif
2517 
2518  return 0;
2519 fail:
2520  if (pkt_data != data)
2521  av_freep(&pkt_data);
2522  return res;
2523 }
2524 
2526  int size, int64_t pos, uint64_t cluster_time,
2527  uint64_t block_duration, int is_keyframe,
2528  uint8_t *additional, uint64_t additional_id, int additional_size,
2529  int64_t cluster_pos, uint64_t discard_padding)
2530 {
2531  uint64_t timecode = AV_NOPTS_VALUE;
2532  MatroskaTrack *track;
2533  int res = 0;
2534  AVStream *st;
2535  int16_t block_time;
2536  uint32_t *lace_size = NULL;
2537  int n, flags, laces = 0;
2538  uint64_t num;
2539  int trust_default_duration = 1;
2540 
2541  if ((n = matroska_ebmlnum_uint(matroska, data, size, &num)) < 0) {
2542  av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
2543  return n;
2544  }
2545  data += n;
2546  size -= n;
2547 
2548  track = matroska_find_track_by_num(matroska, num);
2549  if (!track || !track->stream) {
2550  av_log(matroska->ctx, AV_LOG_INFO,
2551  "Invalid stream %"PRIu64" or size %u\n", num, size);
2552  return AVERROR_INVALIDDATA;
2553  } else if (size <= 3)
2554  return 0;
2555  st = track->stream;
2556  if (st->discard >= AVDISCARD_ALL)
2557  return res;
2558  av_assert1(block_duration != AV_NOPTS_VALUE);
2559 
2560  block_time = sign_extend(AV_RB16(data), 16);
2561  data += 2;
2562  flags = *data++;
2563  size -= 3;
2564  if (is_keyframe == -1)
2565  is_keyframe = flags & 0x80 ? AV_PKT_FLAG_KEY : 0;
2566 
2567  if (cluster_time != (uint64_t)-1
2568  && (block_time >= 0 || cluster_time >= -block_time)) {
2569  timecode = cluster_time + block_time;
2570  if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE
2571  && timecode < track->end_timecode)
2572  is_keyframe = 0; /* overlapping subtitles are not key frame */
2573  if (is_keyframe)
2574  av_add_index_entry(st, cluster_pos, timecode, 0,0,AVINDEX_KEYFRAME);
2575  }
2576 
2577  if (matroska->skip_to_keyframe && track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
2578  if (timecode < matroska->skip_to_timecode)
2579  return res;
2580  if (is_keyframe)
2581  matroska->skip_to_keyframe = 0;
2582  else if (!st->skip_to_keyframe) {
2583  av_log(matroska->ctx, AV_LOG_ERROR, "File is broken, keyframes not correctly marked!\n");
2584  matroska->skip_to_keyframe = 0;
2585  }
2586  }
2587 
2588  res = matroska_parse_laces(matroska, &data, &size, (flags & 0x06) >> 1,
2589  &lace_size, &laces);
2590 
2591  if (res)
2592  goto end;
2593 
2594  if (track->audio.samplerate == 8000) {
2595  // If this is needed for more codecs, then add them here
2596  if (st->codec->codec_id == AV_CODEC_ID_AC3) {
2597  if(track->audio.samplerate != st->codec->sample_rate || !st->codec->frame_size)
2598  trust_default_duration = 0;
2599  }
2600  }
2601 
2602  if (!block_duration && trust_default_duration)
2603  block_duration = track->default_duration * laces / matroska->time_scale;
2604 
2605  if (cluster_time != (uint64_t)-1 && (block_time >= 0 || cluster_time >= -block_time))
2606  track->end_timecode =
2607  FFMAX(track->end_timecode, timecode + block_duration);
2608 
2609  for (n = 0; n < laces; n++) {
2610  int64_t lace_duration = block_duration*(n+1) / laces - block_duration*n / laces;
2611 
2612  if (lace_size[n] > size) {
2613  av_log(matroska->ctx, AV_LOG_ERROR, "Invalid packet size\n");
2614  break;
2615  }
2616 
2617  if ((st->codec->codec_id == AV_CODEC_ID_RA_288 ||
2618  st->codec->codec_id == AV_CODEC_ID_COOK ||
2619  st->codec->codec_id == AV_CODEC_ID_SIPR ||
2620  st->codec->codec_id == AV_CODEC_ID_ATRAC3) &&
2621  st->codec->block_align && track->audio.sub_packet_size) {
2622 
2623  res = matroska_parse_rm_audio(matroska, track, st, data,
2624  lace_size[n],
2625  timecode, pos);
2626  if (res)
2627  goto end;
2628 
2629  } else if (st->codec->codec_id == AV_CODEC_ID_WEBVTT) {
2630  res = matroska_parse_webvtt(matroska, track, st,
2631  data, lace_size[n],
2632  timecode, lace_duration,
2633  pos);
2634  if (res)
2635  goto end;
2636 
2637  } else {
2638  res = matroska_parse_frame(matroska, track, st, data, lace_size[n],
2639  timecode, lace_duration,
2640  pos, !n? is_keyframe : 0,
2641  additional, additional_id, additional_size,
2642  discard_padding);
2643  if (res)
2644  goto end;
2645  }
2646 
2647  if (timecode != AV_NOPTS_VALUE)
2648  timecode = lace_duration ? timecode + lace_duration : AV_NOPTS_VALUE;
2649  data += lace_size[n];
2650  size -= lace_size[n];
2651  }
2652 
2653 end:
2654  av_free(lace_size);
2655  return res;
2656 }
2657 
2659 {
2660  EbmlList *blocks_list;
2661  MatroskaBlock *blocks;
2662  int i, res;
2663  res = ebml_parse(matroska,
2664  matroska_cluster_incremental_parsing,
2665  &matroska->current_cluster);
2666  if (res == 1) {
2667  /* New Cluster */
2668  if (matroska->current_cluster_pos)
2669  ebml_level_end(matroska);
2670  ebml_free(matroska_cluster, &matroska->current_cluster);
2671  memset(&matroska->current_cluster, 0, sizeof(MatroskaCluster));
2672  matroska->current_cluster_num_blocks = 0;
2673  matroska->current_cluster_pos = avio_tell(matroska->ctx->pb);
2674  matroska->prev_pkt = NULL;
2675  /* sizeof the ID which was already read */
2676  if (matroska->current_id)
2677  matroska->current_cluster_pos -= 4;
2678  res = ebml_parse(matroska,
2679  matroska_clusters_incremental,
2680  &matroska->current_cluster);
2681  /* Try parsing the block again. */
2682  if (res == 1)
2683  res = ebml_parse(matroska,
2684  matroska_cluster_incremental_parsing,
2685  &matroska->current_cluster);
2686  }
2687 
2688  if (!res &&
2689  matroska->current_cluster_num_blocks <
2690  matroska->current_cluster.blocks.nb_elem) {
2691  blocks_list = &matroska->current_cluster.blocks;
2692  blocks = blocks_list->elem;
2693 
2694  matroska->current_cluster_num_blocks = blocks_list->nb_elem;
2695  i = blocks_list->nb_elem - 1;
2696  if (blocks[i].bin.size > 0 && blocks[i].bin.data) {
2697  int is_keyframe = blocks[i].non_simple ? !blocks[i].reference : -1;
2698  uint8_t* additional = blocks[i].additional.size > 0 ?
2699  blocks[i].additional.data : NULL;
2700  if (!blocks[i].non_simple)
2701  blocks[i].duration = 0;
2702  res = matroska_parse_block(matroska,
2703  blocks[i].bin.data, blocks[i].bin.size,
2704  blocks[i].bin.pos,
2705  matroska->current_cluster.timecode,
2706  blocks[i].duration, is_keyframe,
2707  additional, blocks[i].additional_id,
2708  blocks[i].additional.size,
2709  matroska->current_cluster_pos,
2710  blocks[i].discard_padding);
2711  }
2712  }
2713 
2714  return res;
2715 }
2716 
2718 {
2719  MatroskaCluster cluster = { 0 };
2720  EbmlList *blocks_list;
2721  MatroskaBlock *blocks;
2722  int i, res;
2723  int64_t pos;
2724  if (!matroska->contains_ssa)
2725  return matroska_parse_cluster_incremental(matroska);
2726  pos = avio_tell(matroska->ctx->pb);
2727  matroska->prev_pkt = NULL;
2728  if (matroska->current_id)
2729  pos -= 4; /* sizeof the ID which was already read */
2730  res = ebml_parse(matroska, matroska_clusters, &cluster);
2731  blocks_list = &cluster.blocks;
2732  blocks = blocks_list->elem;
2733  for (i=0; i<blocks_list->nb_elem; i++)
2734  if (blocks[i].bin.size > 0 && blocks[i].bin.data) {
2735  int is_keyframe = blocks[i].non_simple ? !blocks[i].reference : -1;
2736  res=matroska_parse_block(matroska,
2737  blocks[i].bin.data, blocks[i].bin.size,
2738  blocks[i].bin.pos, cluster.timecode,
2739  blocks[i].duration, is_keyframe, NULL, 0, 0,
2740  pos, blocks[i].discard_padding);
2741  }
2742  ebml_free(matroska_cluster, &cluster);
2743  return res;
2744 }
2745 
2747 {
2748  MatroskaDemuxContext *matroska = s->priv_data;
2749 
2750  while (matroska_deliver_packet(matroska, pkt)) {
2751  int64_t pos = avio_tell(matroska->ctx->pb);
2752  if (matroska->done)
2753  return AVERROR_EOF;
2754  if (matroska_parse_cluster(matroska) < 0)
2755  matroska_resync(matroska, pos);
2756  }
2757 
2758  return 0;
2759 }
2760 
2761 static int matroska_read_seek(AVFormatContext *s, int stream_index,
2762  int64_t timestamp, int flags)
2763 {
2764  MatroskaDemuxContext *matroska = s->priv_data;
2765  MatroskaTrack *tracks = matroska->tracks.elem;
2766  AVStream *st = s->streams[stream_index];
2767  int i, index, index_sub, index_min;
2768 
2769  /* Parse the CUES now since we need the index data to seek. */
2770  if (matroska->cues_parsing_deferred > 0) {
2771  matroska->cues_parsing_deferred = 0;
2772  matroska_parse_cues(matroska);
2773  }
2774 
2775  if (!st->nb_index_entries)
2776  goto err;
2777  timestamp = FFMAX(timestamp, st->index_entries[0].timestamp);
2778 
2779  if ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
2780  avio_seek(s->pb, st->index_entries[st->nb_index_entries-1].pos, SEEK_SET);
2781  matroska->current_id = 0;
2782  while ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
2783  matroska_clear_queue(matroska);
2784  if (matroska_parse_cluster(matroska) < 0)
2785  break;
2786  }
2787  }
2788 
2789  matroska_clear_queue(matroska);
2790  if (index < 0 || (matroska->cues_parsing_deferred < 0 && index == st->nb_index_entries - 1))
2791  goto err;
2792 
2793  index_min = index;
2794  for (i=0; i < matroska->tracks.nb_elem; i++) {
2795  tracks[i].audio.pkt_cnt = 0;
2796  tracks[i].audio.sub_packet_cnt = 0;
2797  tracks[i].audio.buf_timecode = AV_NOPTS_VALUE;
2798  tracks[i].end_timecode = 0;
2799  if (tracks[i].type == MATROSKA_TRACK_TYPE_SUBTITLE
2800  && tracks[i].stream->discard != AVDISCARD_ALL) {
2801  index_sub = av_index_search_timestamp(tracks[i].stream, st->index_entries[index].timestamp, AVSEEK_FLAG_BACKWARD);
2802  while(index_sub >= 0
2803  && index_min >= 0
2804  && tracks[i].stream->index_entries[index_sub].pos < st->index_entries[index_min].pos
2805  && st->index_entries[index].timestamp - tracks[i].stream->index_entries[index_sub].timestamp < 30000000000/matroska->time_scale)
2806  index_min--;
2807  }
2808  }
2809 
2810  avio_seek(s->pb, st->index_entries[index_min].pos, SEEK_SET);
2811  matroska->current_id = 0;
2812  if (flags & AVSEEK_FLAG_ANY) {
2813  st->skip_to_keyframe = 0;
2814  matroska->skip_to_timecode = timestamp;
2815  } else {
2816  st->skip_to_keyframe = 1;
2817  matroska->skip_to_timecode = st->index_entries[index].timestamp;
2818  }
2819  matroska->skip_to_keyframe = 1;
2820  matroska->done = 0;
2821  matroska->num_levels = 0;
2822  ff_update_cur_dts(s, st, st->index_entries[index].timestamp);
2823  return 0;
2824 err:
2825  // slightly hackish but allows proper fallback to
2826  // the generic seeking code.
2827  matroska_clear_queue(matroska);
2828  matroska->current_id = 0;
2829  st->skip_to_keyframe =
2830  matroska->skip_to_keyframe = 0;
2831  matroska->done = 0;
2832  matroska->num_levels = 0;
2833  return -1;
2834 }
2835 
2837 {
2838  MatroskaDemuxContext *matroska = s->priv_data;
2839  MatroskaTrack *tracks = matroska->tracks.elem;
2840  int n;
2841 
2842  matroska_clear_queue(matroska);
2843 
2844  for (n=0; n < matroska->tracks.nb_elem; n++)
2845  if (tracks[n].type == MATROSKA_TRACK_TYPE_AUDIO)
2846  av_free(tracks[n].audio.buf);
2847  ebml_free(matroska_cluster, &matroska->current_cluster);
2848  ebml_free(matroska_segment, matroska);
2849 
2850  return 0;
2851 }
2852 
2854  .name = "matroska,webm",
2855  .long_name = NULL_IF_CONFIG_SMALL("Matroska / WebM"),
2856  .priv_data_size = sizeof(MatroskaDemuxContext),
2862 };
const char * name
Definition: avisynth_c.h:675
#define MATROSKA_ID_SEEKPREROLL
Definition: matroska.h:95
const char * s
Definition: matroskadec.c:76
static EbmlSyntax matroska_simpletag[]
Definition: matroskadec.c:499
#define MATROSKA_ID_BLOCKADDID
Definition: matroska.h:194
#define MATROSKA_ID_TRACKDEFAULTDURATION
Definition: matroska.h:104
static int matroska_parse_rm_audio(MatroskaDemuxContext *matroska, MatroskaTrack *track, AVStream *st, uint8_t *data, int size, uint64_t timecode, int64_t pos)
Definition: matroskadec.c:2120
const char * s
Definition: avisynth_c.h:668
static int matroska_parse_seekhead_entry(MatroskaDemuxContext *matroska, int idx)
Definition: matroskadec.c:1346
Bytestream IO Context.
Definition: avio.h:68
#define MATROSKA_ID_VIDEOFLAGINTERLACED
Definition: matroska.h:121
uint64_t seek_preroll
Definition: matroskadec.c:167
#define AVERROR_PATCHWELCOME
const char *const ff_matroska_video_stereo_plane[MATROSKA_VIDEO_STEREO_PLANE_COUNT]
Definition: matroska.c:144
static void matroska_convert_tags(AVFormatContext *s)
Definition: matroskadec.c:1312
#define MATROSKA_ID_DATEUTC
Definition: matroska.h:71
void av_buffer_unref(AVBufferRef **buf)
Free a given reference and automatically free the buffer if there are no more references to it...
Definition: buffer.c:105
int size
void av_free_packet(AVPacket *pkt)
Free a packet.
Definition: avpacket.c:279
The optional first identifier line of a WebVTT cue.
Definition: avcodec.h:1009
uint64_t type
Definition: matroskadec.c:157
#define MATROSKA_ID_TRACKFLAGLACING
Definition: matroska.h:101
#define MATROSKA_ID_TRACKENTRY
Definition: matroska.h:75
static int matroska_deliver_packet(MatroskaDemuxContext *matroska, AVPacket *pkt)
Definition: matroskadec.c:1971
#define MATROSKA_ID_VIDEODISPLAYHEIGHT
Definition: matroska.h:113
uint64_t version
Definition: matroskadec.c:93
static EbmlSyntax matroska_blockmore[]
Definition: matroskadec.c:557
AVInputFormat ff_matroska_demuxer
Definition: matroskadec.c:2853
int av_add_index_entry(AVStream *st, int64_t pos, int64_t timestamp, int size, int distance, int flags)
Add an index entry into a sorted list.
Definition: utils.c:1675
enum AVCodecID id
Definition: mxfenc.c:90
#define MATROSKA_ID_CUETRACKPOSITION
Definition: matroska.h:156
enum AVCodecID ff_codec_get_id(const AVCodecTag *tags, unsigned int tag)
Definition: utils.c:2556
#define MATROSKA_ID_CODECPRIVATE
Definition: matroska.h:89
const char * name
A comma separated list of short names for the format.
Definition: avformat.h:478
const unsigned char ff_sipr_subpk_size[4]
Definition: rmsipr.c:25
#define MATROSKA_ID_TAGTARGETS_TYPE
Definition: matroska.h:174
#define AV_DISPOSITION_METADATA
Definition: avformat.h:651
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition: avcodec.h:4153
static int ebml_level_end(MatroskaDemuxContext *matroska)
Definition: matroskadec.c:664
int64_t pos
byte position in stream, -1 if unknown
Definition: avcodec.h:1092
static int matroska_ebmlnum_sint(MatroskaDemuxContext *matroska, uint8_t *data, uint32_t size, int64_t *num)
Definition: matroskadec.c:861
else temp
Definition: vf_mcdeint.c:258
char * av_strdup(const char *s) av_malloc_attrib
Duplicate the string s.
Definition: mem.c:256
void avpriv_set_pts_info(AVStream *s, int pts_wrap_bits, unsigned int pts_num, unsigned int pts_den)
Set the time base and wrapping info for a given stream.
Definition: utils.c:3922
int64_t pos
Definition: avformat.h:609
#define MATROSKA_ID_ENCODINGTYPE
Definition: matroska.h:137
#define MATROSKA_ID_AUDIOBITDEPTH
Definition: matroska.h:131
uint64_t chapteruid
Definition: matroskadec.c:219
#define MATROSKA_ID_TRACKFLAGDEFAULT
Definition: matroska.h:99
uint64_t additional_id
Definition: matroskadec.c:293
EbmlList tag
Definition: matroskadec.c:225
uint64_t uid
Definition: matroskadec.c:156
#define AV_RL16(x)
Definition: intreadwrite.h:245
static EbmlSyntax matroska_segments[]
Definition: matroskadec.c:552
static int read_seek(AVFormatContext *ctx, int stream_index, int64_t timestamp, int flags)
Definition: libcdio.c:153
#define AV_WL32(p, darg)
Definition: intreadwrite.h:282
MatroskaCluster current_cluster
Definition: matroskadec.c:282
AVCodecContext * codec
Codec context associated with this stream.
Definition: avformat.h:686
AVRational sample_aspect_ratio
sample aspect ratio (0 if unknown)
Definition: avformat.h:733
#define MATROSKA_ID_TAGTARGETS_ATTACHUID
Definition: matroska.h:178
int num
numerator
Definition: rational.h:44
int index
stream index in AVFormatContext
Definition: avformat.h:668
int size
Definition: avcodec.h:1064
#define MATROSKA_ID_CLUSTERPOSITION
Definition: matroska.h:189
const char * b
Definition: vf_curves.c:105
#define MATROSKA_ID_FILEDATA
Definition: matroska.h:210
#define EBML_ID_DOCTYPEREADVERSION
Definition: matroska.h:42
#define MATROSKA_ID_BLOCKREFERENCE
Definition: matroska.h:201
uint64_t flag_forced
Definition: matroskadec.c:165
uint64_t max_size
Definition: matroskadec.c:94
#define MATROSKA_ID_TRACKTYPE
Definition: matroska.h:80
#define MATROSKA_ID_TAGTARGETS_CHAPTERUID
Definition: matroska.h:177
void av_log(void *avcl, int level, const char *fmt,...) av_printf_format(3
Send the specified message to the log if the level is less than or equal to the current av_log_level...
char * av_base64_encode(char *out, int out_size, const uint8_t *in, int in_size)
Encode data to base64 and null-terminate.
Definition: base64.c:137
static int matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data, int size, int64_t pos, uint64_t cluster_time, uint64_t block_duration, int is_keyframe, uint8_t *additional, uint64_t additional_id, int additional_size, int64_t cluster_pos, uint64_t discard_padding)
Definition: matroskadec.c:2525
uint64_t flag_default
Definition: matroskadec.c:164
void av_fast_padded_malloc(void *ptr, unsigned int *size, size_t min_size)
Same behaviour av_fast_malloc but the buffer has additional FF_INPUT_BUFFER_PADDING_SIZE at the end w...
Definition: utils.c:158
#define MATROSKA_ID_VIDEOASPECTRATIO
Definition: matroska.h:124
#define MATROSKA_ID_MUXINGAPP
Definition: matroska.h:70
#define MATROSKA_ID_AUDIOCHANNELS
Definition: matroska.h:132
char * name
Definition: matroskadec.c:208
int version
Definition: avisynth_c.h:666
void avio_write(AVIOContext *s, const unsigned char *buf, int size)
Definition: aviobuf.c:173
unsigned int avio_rb32(AVIOContext *s)
Definition: aviobuf.c:624
discard all
Definition: avcodec.h:618
MatroskaLevel levels[EBML_MAX_DEPTH]
Definition: matroskadec.c:248
static EbmlSyntax matroska_track_audio[]
Definition: matroskadec.c:344
#define MATROSKA_ID_CUECLUSTERPOSITION
Definition: matroska.h:160
MatroskaTrackAudio audio
Definition: matroskadec.c:169
uint64_t duration
Definition: matroskadec.c:289
#define MATROSKA_ID_EDITIONFLAGDEFAULT
Definition: matroska.h:223
#define MATROSKA_ID_CLUSTERTIMECODE
Definition: matroska.h:188
#define EBML_ID_DOCTYPE
Definition: matroska.h:40
int block_align
number of bytes per packet if constant and known or 0 Used by some WAV based audio codecs...
Definition: avcodec.h:1910
static EbmlSyntax matroska_tag[]
Definition: matroskadec.c:518
#define MATROSKA_ID_ENCODINGENCALGO
Definition: matroska.h:144
static EbmlSyntax matroska_attachment[]
Definition: matroskadec.c:433
int avio_r8(AVIOContext *s)
Definition: aviobuf.c:471
#define MATROSKA_ID_CHAPTERTIMEEND
Definition: matroska.h:217
uint8_t * extradata
some codecs need / can use extradata like Huffman tables.
Definition: avcodec.h:1254
static EbmlSyntax matroska_track[]
Definition: matroskadec.c:398
#define MATROSKA_ID_TRACKCONTENTENCODINGS
Definition: matroska.h:105
AVBufferRef * buf
A reference to the reference-counted buffer where the packet data is stored.
Definition: avcodec.h:1046
void av_freep(void *ptr)
Free a memory block which has been allocated with av_malloc(z)() or av_realloc() and set the pointer ...
Definition: mem.c:234
#define AV_LZO_OUTPUT_FULL
decoded data did not fit into output buffer
Definition: lzo.h:39
AVChapter * avpriv_new_chapter(AVFormatContext *s, int id, AVRational time_base, int64_t start, int64_t end, const char *title)
Add a new chapter.
Definition: utils.c:3435
if((e=av_dict_get(options,"", NULL, AV_DICT_IGNORE_SUFFIX)))
Definition: avfilter.c:965
#define EBML_VERSION
Definition: matroska.h:30
AVDictionary * metadata
Definition: avformat.h:735
#define MATROSKA_ID_FILEDESC
Definition: matroska.h:207
Format I/O context.
Definition: avformat.h:968
#define EBML_ID_CRC32
Definition: matroska.h:46
uint64_t def
Definition: matroskadec.c:211
void ff_update_cur_dts(AVFormatContext *s, AVStream *ref_st, int64_t timestamp)
Update cur_dts of all streams based on the given timestamp and AVStream.
Definition: utils.c:1594
#define MATROSKA_ID_TRACKCONTENTENCODING
Definition: matroska.h:106
#define MATROSKA_ID_CODECDOWNLOADURL
Definition: matroska.h:92
int64_t end_timecode
Definition: matroskadec.c:174
static EbmlSyntax matroska_track_operation[]
Definition: matroskadec.c:393
static uint8_t * res
Definition: ffhash.c:43
int ffio_limit(AVIOContext *s, int size)
Definition: utils.c:133
#define AV_DISPOSITION_CAPTIONS
To specify text track kind (different from subtitles default).
Definition: avformat.h:649
#define AV_RB16(x)
Definition: intreadwrite.h:232
uint64_t pixel_height
Definition: matroskadec.c:122
uint8_t
#define MATROSKA_ID_CHAPLANG
Definition: matroska.h:220
uint64_t stereo_mode
Definition: matroskadec.c:124
MatroskaTrackOperation operation
Definition: matroskadec.c:170
MatroskaTrackVideo video
Definition: matroskadec.c:168
#define MATROSKA_ID_EDITIONFLAGORDERED
Definition: matroska.h:224
void * elem
Definition: matroskadec.c:83
#define MATROSKA_ID_TRACKLANGUAGE
Definition: matroska.h:97
MatroskaTrackCompression compression
Definition: matroskadec.c:113
uint8_t * data
Definition: matroskadec.c:88
const AVCodecTag ff_codec_movvideo_tags[]
Definition: isom.c:66
uint64_t time
Definition: matroskadec.c:203
static const uint8_t offset[511][2]
Definition: vf_uspp.c:58
static av_cold int end(AVCodecContext *avctx)
Definition: avrndec.c:67
#define MATROSKA_ID_VIDEOPIXELCROPT
Definition: matroska.h:117
#define MATROSKA_ID_TIMECODESCALE
Definition: matroska.h:66
static int matroska_aac_sri(int samplerate)
Definition: matroskadec.c:1480
unsigned char * buf
Buffer must have AVPROBE_PADDING_SIZE of extra allocated bytes filled with zero.
Definition: avformat.h:336
enum AVStreamParseType need_parsing
Definition: avformat.h:812
#define MATROSKA_ID_SIMPLEBLOCK
Definition: matroska.h:196
#define MATROSKA_ID_TAGTARGETS_TYPEVALUE
Definition: matroska.h:175
uint64_t avio_rb64(AVIOContext *s)
Definition: aviobuf.c:689
#define MATROSKA_ID_EDITIONFLAGHIDDEN
Definition: matroska.h:222
#define AV_LZO_OUTPUT_PADDING
Definition: lzo.h:47
static EbmlSyntax matroska_cluster[]
Definition: matroskadec.c:580
void avio_wl32(AVIOContext *s, unsigned int val)
Definition: aviobuf.c:291
#define MATROSKA_ID_CODECNAME
Definition: matroska.h:90
char * language
Definition: matroskadec.c:161
#define MATROSKA_ID_BLOCKMORE
Definition: matroska.h:193
#define MATROSKA_ID_CUERELATIVEPOSITION
Definition: matroska.h:161
#define MATROSKA_ID_AUDIOOUTSAMPLINGFREQ
Definition: matroska.h:129
static av_always_inline int64_t avio_tell(AVIOContext *s)
ftell() equivalent for AVIOContext.
Definition: avio.h:248
const char data[16]
Definition: mxf.c:68
#define AVFMT_FLAG_IGNIDX
Ignore index.
Definition: avformat.h:1047
#define AV_DISPOSITION_FORCED
Track should be used during playback by default.
Definition: avformat.h:634
#define AV_DISPOSITION_DEFAULT
Definition: avformat.h:622
uint64_t typevalue
Definition: matroskadec.c:217
uint64_t codec_delay
Definition: matroskadec.c:166
static int matroska_parse_cluster_incremental(MatroskaDemuxContext *matroska)
Definition: matroskadec.c:2658
#define MATROSKA_ID_VIDEODISPLAYWIDTH
Definition: matroska.h:112
#define MATROSKA_ID_EDITIONUID
Definition: matroska.h:221
#define MATROSKA_ID_BLOCKADDITIONS
Definition: matroska.h:192
uint32_t tag
Definition: movenc.c:961
#define AV_WB32(p, darg)
Definition: intreadwrite.h:265
AVIndexEntry * index_entries
Only used if the format does not support seeking natively.
Definition: avformat.h:823
static EbmlSyntax ebml_header[]
Definition: matroskadec.c:298
#define MATROSKA_ID_CODECDECODEALL
Definition: matroska.h:93
#define MATROSKA_ID_ENCODINGENCRYPTION
Definition: matroska.h:142
enum AVCodecID id
Definition: internal.h:46
static av_cold int read_close(AVFormatContext *ctx)
Definition: libcdio.c:145
const uint8_t ff_log2_tab[256]
Definition: log2_tab.c:23
#define MATROSKA_ID_CUES
Definition: matroska.h:58
#define EBML_MAX_DEPTH
Definition: matroska.h:276
int bits_per_coded_sample
bits per sample/pixel from the demuxer (needed for huffyuv).
Definition: avcodec.h:2563
#define MATROSKA_ID_TRACKNUMBER
Definition: matroska.h:78
static int64_t duration
Definition: ffplay.c:306
AVStream * avformat_new_stream(AVFormatContext *s, const AVCodec *c)
Add a new stream to a media file.
Definition: utils.c:3348
int duration
Duration of this packet in AVStream-&gt;time_base units, 0 if unknown.
Definition: avcodec.h:1085
#define MATROSKA_ID_SEGMENTUID
Definition: matroska.h:72
static EbmlSyntax matroska_tracks[]
Definition: matroskadec.c:428
EbmlList sub
Definition: matroskadec.c:212
#define AV_PKT_FLAG_KEY
The packet contains a keyframe.
Definition: avcodec.h:1113
static int matroska_parse_cluster(MatroskaDemuxContext *matroska)
Definition: matroskadec.c:2717
static int ebml_parse_nest(MatroskaDemuxContext *matroska, EbmlSyntax *syntax, void *data)
Definition: matroskadec.c:912
#define MATROSKA_ID_CUEBLOCKNUMBER
Definition: matroska.h:163
#define MATROSKA_ID_TRACKUID
Definition: matroska.h:79
int64_t av_rescale_q(int64_t a, AVRational bq, AVRational cq) av_const
Rescale a 64-bit integer by 2 rational numbers.
Definition: mathematics.c:130
uint64_t display_height
Definition: matroskadec.c:120
#define U(x)
Definition: vp56_arith.h:37
static EbmlSyntax matroska_info[]
Definition: matroskadec.c:314
#define MATROSKA_ID_ENCODINGORDER
Definition: matroska.h:135
#define MATROSKA_ID_VIDEOSTEREOMODE
Definition: matroska.h:122
int av_new_packet(AVPacket *pkt, int size)
Allocate the payload of a packet and initialize its fields with default values.
Definition: avpacket.c:83
static EbmlSyntax matroska_blockadditions[]
Definition: matroskadec.c:563
EbmlType type
Definition: matroskadec.c:70
AVCodecID
Identify the syntax and semantics of the bitstream.
Definition: avcodec.h:102
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition: avcodec.h:4147
void av_free(void *ptr)
Free a memory block which has been allocated with av_malloc(z)() or av_realloc(). ...
Definition: mem.c:219
uint8_t pi<< 24) CONV_FUNC_GROUP(AV_SAMPLE_FMT_FLT, float, AV_SAMPLE_FMT_U8, uint8_t,(*(constuint8_t *) pi-0x80)*(1.0f/(1<< 7))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_DBL, double, AV_SAMPLE_FMT_U8, uint8_t,(*(constuint8_t *) pi-0x80)*(1.0/(1<< 7))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_U8, uint8_t, AV_SAMPLE_FMT_S16, int16_t,(*(constint16_t *) pi >>8)+0x80) CONV_FUNC_GROUP(AV_SAMPLE_FMT_FLT, float, AV_SAMPLE_FMT_S16, int16_t,*(constint16_t *) pi *(1.0f/(1<< 15))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_DBL, double, AV_SAMPLE_FMT_S16, int16_t,*(constint16_t *) pi *(1.0/(1<< 15))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_U8, uint8_t, AV_SAMPLE_FMT_S32, int32_t,(*(constint32_t *) pi >>24)+0x80) CONV_FUNC_GROUP(AV_SAMPLE_FMT_FLT, float, AV_SAMPLE_FMT_S32, int32_t,*(constint32_t *) pi *(1.0f/(1U<< 31))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_DBL, double, AV_SAMPLE_FMT_S32, int32_t,*(constint32_t *) pi *(1.0/(1U<< 31))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_U8, uint8_t, AV_SAMPLE_FMT_FLT, float, av_clip_uint8(lrintf(*(constfloat *) pi *(1<< 7))+0x80)) CONV_FUNC_GROUP(AV_SAMPLE_FMT_S16, int16_t, AV_SAMPLE_FMT_FLT, float, av_clip_int16(lrintf(*(constfloat *) pi *(1<< 15)))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_S32, int32_t, AV_SAMPLE_FMT_FLT, float, av_clipl_int32(llrintf(*(constfloat *) pi *(1U<< 31)))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_U8, uint8_t, AV_SAMPLE_FMT_DBL, double, av_clip_uint8(lrint(*(constdouble *) pi *(1<< 7))+0x80)) CONV_FUNC_GROUP(AV_SAMPLE_FMT_S16, int16_t, AV_SAMPLE_FMT_DBL, double, av_clip_int16(lrint(*(constdouble *) pi *(1<< 15)))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_S32, int32_t, AV_SAMPLE_FMT_DBL, double, av_clipl_int32(llrint(*(constdouble *) pi *(1U<< 31))))#defineSET_CONV_FUNC_GROUP(ofmt, ifmt) staticvoidset_generic_function(AudioConvert *ac){}voidff_audio_convert_free(AudioConvert **ac){return;ff_dither_free(&(*ac) ->dc);av_freep(ac);}AudioConvert *ff_audio_convert_alloc(AVAudioResampleContext *avr, enumAVSampleFormatout_fmt, enumAVSampleFormatin_fmt, intchannels, intsample_rate, intapply_map){AudioConvert *ac;intin_planar, out_planar;ac=av_mallocz(sizeof(*ac));returnNULL;ac->avr=avr;ac->out_fmt=out_fmt;ac->in_fmt=in_fmt;ac->channels=channels;ac->apply_map=apply_map;if(avr->dither_method!=AV_RESAMPLE_DITHER_NONE &&av_get_packed_sample_fmt(out_fmt)==AV_SAMPLE_FMT_S16 &&av_get_bytes_per_sample(in_fmt)>2){ac->dc=ff_dither_alloc(avr, out_fmt, in_fmt, channels, sample_rate, apply_map);if(!ac->dc){av_free(ac);returnNULL;}returnac;}in_planar=av_sample_fmt_is_planar(in_fmt);out_planar=av_sample_fmt_is_planar(out_fmt);if(in_planar==out_planar){ac->func_type=CONV_FUNC_TYPE_FLAT;ac->planes=in_planar?ac->channels:1;}elseif(in_planar) ac->func_type=CONV_FUNC_TYPE_INTERLEAVE;elseac->func_type=CONV_FUNC_TYPE_DEINTERLEAVE;set_generic_function(ac);ff_audio_convert_init_arm(ac);ff_audio_convert_init_x86(ac);returnac;}intff_audio_convert(AudioConvert *ac, AudioData *out, AudioData *in){intuse_generic=1;intlen=in->nb_samples;intp;if(ac->dc){av_dlog(ac->avr,"%dsamples-audio_convert:%sto%s(dithered)\n", len, av_get_sample_fmt_name(ac->in_fmt), av_get_sample_fmt_name(ac->out_fmt));returnff_convert_dither(ac-> in
#define AV_DISPOSITION_DESCRIPTIONS
Definition: avformat.h:650
#define MATROSKA_ID_BLOCKDURATION
Definition: matroska.h:200
#define EBML_ID_EBMLREADVERSION
Definition: matroska.h:37
int av_index_search_timestamp(AVStream *st, int64_t timestamp, int flags)
Get the index for a specific timestamp.
Definition: utils.c:1718
static int ebml_read_length(MatroskaDemuxContext *matroska, AVIOContext *pb, uint64_t *number)
Read a EBML length value.
Definition: matroskadec.c:733
void * priv_data
Format private data.
Definition: avformat.h:988
AVChapter * chapter
Definition: matroskadec.c:194
static EbmlSyntax matroska_index[]
Definition: matroskadec.c:494
int ff_get_wav_header(AVIOContext *pb, AVCodecContext *codec, int size)
Definition: riffdec.c:88
int64_t timestamp
Timestamp in AVStream.time_base units, preferably the time from which on correctly decoded frames are...
Definition: avformat.h:610
#define MATROSKA_ID_CLUSTER
Definition: matroska.h:62
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification. ...
Definition: internal.h:151
#define MATROSKA_ID_FILEMIMETYPE
Definition: matroska.h:209
static int matroska_ebmlnum_uint(MatroskaDemuxContext *matroska, uint8_t *data, uint32_t size, uint64_t *num)
Definition: matroskadec.c:850
const char * r
Definition: vf_curves.c:103
int64_t convergence_duration
Time difference in AVStream-&gt;time_base units from the pts of this packet to the point at which the ou...
Definition: avcodec.h:1111
uint64_t display_width
Definition: matroskadec.c:119
#define MATROSKA_ID_WRITINGAPP
Definition: matroska.h:69
EbmlBin additional
Definition: matroskadec.c:294
static av_always_inline float av_int2float(uint32_t i)
Reinterpret a 32-bit integer as a float.
Definition: intfloat.h:40
#define MATROSKA_ID_TAGDEFAULT_BUG
Definition: matroska.h:172
Definition: graph2dot.c:48
static EbmlSyntax matroska_clusters[]
Definition: matroskadec.c:589
static EbmlSyntax matroska_chapter[]
Definition: matroskadec.c:465
enum AVCodecID id
Definition: matroska.h:272
#define MATROSKA_ID_VIDEOPIXELCROPR
Definition: matroska.h:119
#define MATROSKA_ID_TRACKPLANEUID
Definition: matroska.h:86
#define MATROSKA_ID_ENCODINGCOMPSETTINGS
Definition: matroska.h:140
#define EBML_ID_EBMLMAXIDLENGTH
Definition: matroska.h:38
#define MATROSKA_ID_CHAPTERFLAGHIDDEN
Definition: matroska.h:226
enum AVCodecID codec_id
Definition: mov_chan.c:433
AVRational avg_frame_rate
Average framerate.
Definition: avformat.h:740
uint64_t timecode
Definition: matroskadec.c:239
#define CONFIG_ZLIB
Definition: config.h:370
size_t av_strlcpy(char *dst, const char *src, size_t size)
Copy the string src to dst, but no more than size - 1 bytes, and null-terminate dst.
Definition: avstring.c:82
#define av_unused
Disable warnings about deprecated features This is useful for sections of code kept for backward comp...
Definition: avcodec.h:697
uint8_t * av_packet_new_side_data(AVPacket *pkt, enum AVPacketSideDataType type, int size)
Allocate new information of a packet.
Definition: avpacket.c:298
static EbmlSyntax matroska_attachments[]
Definition: matroskadec.c:442
int flags
A combination of AV_PKT_FLAG values.
Definition: avcodec.h:1069
static EbmlSyntax matroska_cluster_incremental_parsing[]
Definition: matroskadec.c:598
static void ebml_free(EbmlSyntax *syntax, void *data)
Definition: matroskadec.c:1011
const CodecMime ff_mkv_mime_tags[]
Definition: matroska.c:107
int nb_elem
Definition: matroskadec.c:82
#define MATROSKA_ID_TAG
Definition: matroska.h:166
int av_reduce(int *dst_num, int *dst_den, int64_t num, int64_t den, int64_t max)
Reduce a fraction.
Definition: rational.c:35
int buf_size
Size of buf except extra allocated bytes.
Definition: avformat.h:337
char * lang
Definition: matroskadec.c:210
goto fail
Definition: avfilter.c:963
#define FF_INPUT_BUFFER_PADDING_SIZE
Required number of additionally allocated bytes at the end of the input bitstream for decoding...
Definition: avcodec.h:580
static EbmlSyntax matroska_chapters[]
Definition: matroskadec.c:474
#define FF_ARRAY_ELEMS(a)
Definition: avcodec.h:929
#define MATROSKA_ID_ENCODINGSIGHASHALGO
Definition: matroska.h:147
uint64_t skip_to_timecode
Definition: matroskadec.c:275
Definition: dct-test.c:68
static int matroska_read_header(AVFormatContext *s)
Definition: matroskadec.c:1501
static void matroska_parse_cues(MatroskaDemuxContext *matroska)
Definition: matroskadec.c:1454
int seekable
A combination of AVIO_SEEKABLE_ flags or 0 when the stream is not seekable.
Definition: avio.h:117
int bit_rate
the average bitrate
Definition: avcodec.h:1204
static void matroska_execute_seekhead(MatroskaDemuxContext *matroska)
Definition: matroskadec.c:1397
#define dynarray_add(tab, nb_ptr, elem)
Definition: internal.h:58
uint64_t start
Definition: matroskadec.c:189
#define EBML_ID_EBMLVERSION
Definition: matroska.h:36
uint8_t * data
The data buffer.
Definition: buffer.h:89
int64_t av_rescale(int64_t a, int64_t b, int64_t c) av_const
Rescale a 64-bit integer with rounding to nearest.
Definition: mathematics.c:118
#define AV_BASE64_SIZE(x)
Calculate the output size needed to base64-encode x bytes to a null-terminated string.
Definition: base64.h:61
#define AV_TIME_BASE
Internal time base represented as integer.
Definition: avcodec.h:2284
void * av_realloc(void *ptr, size_t size) 1(2)
Allocate or reallocate a block of memory.
Definition: mem.c:141
#define MATROSKA_ID_TAGTARGETS
Definition: matroska.h:173
float y
const AVCodecTag ff_codec_bmp_tags[]
Definition: riff.c:32
AVPacket ** packets
Definition: matroskadec.c:267
#define MATROSKA_VIDEO_STEREO_PLANE_COUNT
Definition: matroska.h:279
#define MATROSKA_ID_TAGNAME
Definition: matroska.h:168
#define MATROSKA_ID_TRACKTIMECODESCALE
Definition: matroska.h:107
static int read_probe(AVProbeData *pd)
Definition: jvdec.c:54
static int ebml_parse_elem(MatroskaDemuxContext *matroska, EbmlSyntax *syntax, void *data)
Definition: matroskadec.c:943
static int ebml_read_num(MatroskaDemuxContext *matroska, AVIOContext *pb, int max_size, uint64_t *number)
Definition: matroskadec.c:687
ret
Definition: avfilter.c:961
int width
picture width / height.
Definition: avcodec.h:1314
const char *const ff_matroska_video_stereo_mode[MATROSKA_VIDEO_STEREO_MODE_COUNT]
Definition: matroska.c:126
#define MATROSKA_ID_CHAPTERFLAGENABLED
Definition: matroska.h:227
uint64_t id_length
Definition: matroskadec.c:95
static EbmlSyntax matroska_track_encodings[]
Definition: matroskadec.c:377
static MatroskaTrack * matroska_find_track_by_num(MatroskaDemuxContext *matroska, int num)
Definition: matroskadec.c:1080
#define AVSEEK_FLAG_ANY
seek to any frame, even non-keyframes
Definition: avformat.h:1840
AVStream ** streams
Definition: avformat.h:1016
#define AVPROBE_SCORE_EXTENSION
score for file extension
Definition: avformat.h:341
void * av_malloc(size_t size) av_malloc_attrib 1(1)
Allocate a block of size bytes with alignment suitable for all memory accesses (including vectors if ...
Definition: mem.c:73
#define MATROSKA_ID_SIMPLETAG
Definition: matroska.h:167
uint64_t doctype_version
Definition: matroskadec.c:97
internal header for RIFF based (de)muxers do NOT include this in end user applications ...
static EbmlSyntax matroska_track_encoding[]
Definition: matroskadec.c:368
#define FFMIN(a, b)
Definition: avcodec.h:925
#define MATROSKA_ID_TRACKMAXCACHE
Definition: matroska.h:103
int data_offset
Definition: matroskadec.c:72
#define MATROSKA_ID_CHAPTERPHYSEQUIV
Definition: matroska.h:228
static int matroska_read_close(AVFormatContext *s)
Definition: matroskadec.c:2836
EbmlBin codec_priv
Definition: matroskadec.c:160
static int ebml_read_ascii(AVIOContext *pb, int size, char **str)
Definition: matroskadec.c:783
static char buffer[20]
Definition: seek-test.c:31
static int matroska_decode_buffer(uint8_t **buf, int *buf_size, MatroskaTrack *track)
Definition: matroskadec.c:1094
#define MATROSKA_ID_CHAPTERATOM
Definition: matroska.h:215
int av_lzo1x_decode(void *out, int *outlen, const void *in, int *inlen)
Decodes LZO 1x compressed data.
Definition: lzo.c:126
int64_t avio_seek(AVIOContext *s, int64_t offset, int whence)
fseek() equivalent for AVIOContext.
Definition: aviobuf.c:199
int n
Definition: avisynth_c.h:588
#define MATROSKA_ID_VIDEOCOLORSPACE
Definition: matroska.h:125
static EbmlSyntax matroska_segment[]
Definition: matroskadec.c:540
#define MATROSKA_ID_CHAPTERS
Definition: matroska.h:63
static int matroska_probe(AVProbeData *p)
Definition: matroskadec.c:1038
#define EBML_ID_VOID
Definition: matroska.h:45
#define L(x)
Definition: vp56_arith.h:36
void * av_realloc_array(void *ptr, size_t nmemb, size_t size)
Definition: mem.c:203
static void matroska_convert_tag(AVFormatContext *s, EbmlList *list, AVDictionary **metadata, char *prefix)
Definition: matroskadec.c:1279
uint64_t max_block_additional_id
Definition: matroskadec.c:176
static int matroska_parse_frame(MatroskaDemuxContext *matroska, MatroskaTrack *track, AVStream *st, uint8_t *data, int pkt_size, uint64_t timecode, uint64_t lace_duration, int64_t pos, int is_keyframe, uint8_t *additional, uint64_t additional_id, int additional_size, uint64_t discard_padding)
Definition: matroskadec.c:2385
#define MATROSKA_ID_AUDIOSAMPLINGFREQ
Definition: matroska.h:128
double f
Definition: matroskadec.c:75
#define MATROSKA_ID_TRACKMINCACHE
Definition: matroska.h:102
static void matroska_metadata_creation_time(AVDictionary **metadata, int64_t date_utc)
Definition: matroskadec.c:1490
static int read_header(FFV1Context *f)
Definition: ffv1dec.c:592
struct EbmlSyntax * n
Definition: matroskadec.c:77
static int matroska_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
Definition: matroskadec.c:2761
static EbmlSyntax matroska_seekhead[]
Definition: matroskadec.c:535
Stream structure.
Definition: avformat.h:667
static int matroska_parse_wavpack(MatroskaTrack *track, uint8_t *src, uint8_t **pdst, int *size)
Definition: matroskadec.c:2191
#define MATROSKA_ID_TRACKPLANETYPE
Definition: matroska.h:87
#define AV_WL16(p, darg)
Definition: intreadwrite.h:250
int frame_size
Number of samples per channel in an audio frame.
Definition: avcodec.h:1893
#define AV_RB64(x)
Definition: intreadwrite.h:292
EbmlList encodings
Definition: matroskadec.c:171
char * codec_id
Definition: matroskadec.c:159
static int width
Definition: utils.c:158
int64_t current_cluster_pos
Definition: matroskadec.c:281
#define MATROSKA_ID_VIDEOPIXELCROPB
Definition: matroska.h:116
#define AV_LOG_INFO
Standard information.
Definition: avcodec.h:4158
AVBufferRef * av_buffer_alloc(int size)
Allocate an AVBuffer of the given size using av_malloc().
Definition: buffer.c:65
AVS_Value src
Definition: avisynth_c.h:523
#define MATROSKA_ID_TRACKFLAGFORCED
Definition: matroska.h:100
#define MATROSKA_ID_TAGS
Definition: matroska.h:59
enum AVMediaType codec_type
Definition: avcodec.h:1154
static EbmlSyntax matroska_track_plane[]
Definition: matroskadec.c:382
#define FFMAX(a, b)
Definition: avcodec.h:923
static int ebml_read_master(MatroskaDemuxContext *matroska, uint64_t length)
Definition: matroskadec.c:828
enum AVCodecID codec_id
Definition: avcodec.h:1157
#define MATROSKA_ID_TAGDEFAULT
Definition: matroska.h:171
#define MATROSKA_ID_SEEKID
Definition: matroska.h:184
int sample_rate
samples per second
Definition: avcodec.h:1873
#define MATROSKA_ID_ENCODINGCOMPALGO
Definition: matroska.h:139
#define MATROSKA_ID_BLOCK
Definition: matroska.h:199
#define MATROSKA_ID_INFO
Definition: matroska.h:56
#define MATROSKA_ID_TAGTARGETS_TRACKUID
Definition: matroska.h:176
#define AV_EF_EXPLODE
abort decoding on minor error detection
Definition: avcodec.h:2480
#define MATROSKA_ID_TAGLANG
Definition: matroska.h:170
static EbmlSyntax matroska_tags[]
Definition: matroskadec.c:524
uint64_t pixel_width
Definition: matroskadec.c:121
#define MATROSKA_ID_TRACKCOMBINEPLANES
Definition: matroska.h:84
unsigned int codec_tag
fourcc (LSB first, so &quot;ABCD&quot; -&gt; (&#39;D&#39;&lt;&lt;24) + (&#39;C&#39;&lt;&lt;16) + (&#39;B&#39;&lt;&lt;8) + &#39;A&#39;).
Definition: avcodec.h:1172
#define MATROSKA_ID_TRACKFLAGENABLED
Definition: matroska.h:98
int ff_alloc_extradata(AVCodecContext *avctx, int size)
Allocate extradata with additional FF_INPUT_BUFFER_PADDING_SIZE at end which is always set to 0...
Definition: utils.c:2690
#define MATROSKA_ID_TRACKS
Definition: matroska.h:57
AVIOContext * pb
I/O context.
Definition: avformat.h:1001
void * buf
Definition: avisynth_c.h:594
#define MATROSKA_ID_TRACKPLANE
Definition: matroska.h:85
Data found in BlockAdditional element of matroska container.
Definition: avcodec.h:1004
int extradata_size
Definition: avcodec.h:1255
#define MATROSKA_ID_TRACKNAME
Definition: matroska.h:96
static int read_packet(AVFormatContext *ctx, AVPacket *pkt)
Definition: libcdio.c:114
uint64_t start
Definition: matroskadec.c:234
int av_dict_set(AVDictionary **pm, const char *key, const char *value, int flags)
Set the given entry in *pm, overwriting an existing entry.
Definition: dict.c:62
static EbmlSyntax matroska_cluster_incremental[]
Definition: matroskadec.c:612
int nb_index_entries
Definition: avformat.h:825
#define MATROSKA_ID_SEEKENTRY
Definition: matroska.h:181
EbmlList pos
Definition: matroskadec.c:204
#define MKTAG(a, b, c, d)
#define AVSEEK_FLAG_BACKWARD
Definition: avformat.h:1838
uint64_t u
Definition: matroskadec.c:74
#define MATROSKA_ID_EDITIONENTRY
Definition: matroska.h:214
int index
Definition: gxfenc.c:89
#define MATROSKA_ID_BLOCKGROUP
Definition: matroska.h:191
#define MATROSKA_ID_VIDEOPIXELHEIGHT
Definition: matroska.h:115
rational number numerator/denominator
Definition: rational.h:43
#define MATROSKA_ID_CUEDURATION
Definition: matroska.h:162
AVStream * stream
Definition: matroskadec.c:173
uint8_t * data
Definition: avcodec.h:1063
static int matroska_parse_laces(MatroskaDemuxContext *matroska, uint8_t **buf, int *buf_size, int type, uint32_t **lace_buf, int *laces)
Definition: matroskadec.c:2013
#define MATROSKA_ID_CUETIME
Definition: matroska.h:155
#define MATROSKA_ID_ENCODINGSIGALGO
Definition: matroska.h:146
static int matroska_read_packet(AVFormatContext *s, AVPacket *pkt)
Definition: matroskadec.c:2746
static EbmlSyntax matroska_blockgroup[]
Definition: matroskadec.c:568
static EbmlSyntax matroska_track_encoding_encryption[]
Definition: matroskadec.c:358
Recommmends skipping the specified number of samples.
Definition: avcodec.h:969
AVDictionary * metadata
Definition: avformat.h:1128
static int ebml_parse(MatroskaDemuxContext *matroska, EbmlSyntax *syntax, void *data)
Definition: matroskadec.c:899
#define MATROSKA_ID_ENCODINGSIGKEYID
Definition: matroska.h:148
#define MATROSKA_ID_TITLE
Definition: matroska.h:68
#define snprintf
Definition: snprintf.h:34
AVFormatContext * ctx
Definition: matroskadec.c:244
#define AV_WB64(p, darg)
Definition: intreadwrite.h:303
#define MATROSKA_ID_TRACKVIDEO
Definition: matroska.h:81
static EbmlSyntax matroska_track_combine_planes[]
Definition: matroskadec.c:388
#define AVINDEX_KEYFRAME
Definition: avformat.h:616
int size
Definition: matroskadec.c:87
int error
contains the error code or 0 if no error happened
Definition: avio.h:102
This structure contains the data a format has to probe a file.
Definition: avformat.h:334
#define MKBETAG(a, b, c, d)
static int ebml_parse_id(MatroskaDemuxContext *matroska, EbmlSyntax *syntax, uint32_t id, void *data)
Definition: matroskadec.c:880
int64_t avio_skip(AVIOContext *s, int64_t offset)
Skip given number of bytes forward.
Definition: aviobuf.c:256
#define type
int list_elem_size
Definition: matroskadec.c:71
static EbmlSyntax ebml_syntax[]
Definition: matroskadec.c:309
size_t av_strlcat(char *dst, const char *src, size_t size)
Append the string src to the string dst, but to a total length of no more than size - 1 bytes...
Definition: avstring.c:92
#define MATROSKA_ID_VIDEOFRAMERATE
Definition: matroska.h:111
#define av_assert1(cond)
assert() equivalent, that does not lie in speed critical code.
Definition: avassert.h:53
static av_const int sign_extend(int val, unsigned bits)
Definition: mathops.h:123
#define MATROSKA_ID_ATTACHMENTS
Definition: matroska.h:61
#define MATROSKA_ID_TRACKOPERATION
Definition: matroska.h:83
int64_t pos
Definition: matroskadec.c:89
#define MATROSKA_ID_CHAPTERDISPLAY
Definition: matroska.h:218
static int flags
Definition: cpu.c:45
#define AVERROR_EOF
static void * av_malloc_array(size_t nmemb, size_t size)
Definition: mem.h:93
#define AVPROBE_SCORE_MAX
maximum score
Definition: avformat.h:342
uint8_t level
Definition: svq3.c:146
#define MATROSKA_ID_FILENAME
Definition: matroska.h:208
#define MATROSKA_ID_BLOCKADDITIONAL
Definition: matroska.h:195
const int avpriv_mpeg4audio_sample_rates[16]
Definition: mpeg4audio.c:57
const AVMetadataConv ff_mkv_metadata_conv[]
Definition: matroska.c:120
#define CONFIG_LZO
Definition: config.h:400
#define MATROSKA_ID_CODECID
Definition: matroska.h:88
static EbmlSyntax matroska_clusters_incremental[]
Definition: matroskadec.c:621
int avio_read(AVIOContext *s, unsigned char *buf, int size)
Read size bytes from AVIOContext into buf.
Definition: aviobuf.c:480
#define MATROSKA_ID_VIDEOALPHAMODE
Definition: matroska.h:123
int url_feof(AVIOContext *s)
feof() equivalent for AVIOContext.
Definition: aviobuf.c:280
A reference to a data buffer.
Definition: buffer.h:81
int64_t reference
Definition: matroskadec.c:290
void ff_rm_reorder_sipr_data(uint8_t *buf, int sub_packet_h, int framesize)
Perform 4-bit block reordering for SIPR data.
Definition: rmsipr.c:41
uint64_t buf_timecode
Definition: matroskadec.c:141
#define MATROSKA_ID_ENCODINGENCAESSETTINGS
Definition: matroska.h:143
uint64_t num
Definition: matroskadec.c:155
#define MATROSKA_ID_CUETRACK
Definition: matroska.h:159
static EbmlSyntax matroska_track_encoding_compression[]
Definition: matroskadec.c:352
EbmlType
Definition: matroskadec.c:55
#define MATROSKA_ID_SEEKPOSITION
Definition: matroska.h:185
static int matroska_resync(MatroskaDemuxContext *matroska, int64_t last_pos)
Definition: matroskadec.c:632
#define MATROSKA_ID_CODECDELAY
Definition: matroska.h:94
#define MATROSKA_ID_CHAPTERTIMESTART
Definition: matroska.h:216
double time_scale
Definition: matroskadec.c:162
static av_always_inline double av_int2double(uint64_t i)
Reinterpret a 64-bit integer as a double.
Definition: intfloat.h:60
int ffio_init_context(AVIOContext *s, unsigned char *buffer, int buffer_size, int write_flag, void *opaque, int(*read_packet)(void *opaque, uint8_t *buf, int buf_size), int(*write_packet)(void *opaque, uint8_t *buf, int buf_size), int64_t(*seek)(void *opaque, int64_t offset, int whence))
Definition: aviobuf.c:71
union EbmlSyntax::@149 def
char * string
Definition: matroskadec.c:209
int64_t start_time
Decoding: pts of the first frame of the stream in presentation order, in stream time base...
Definition: avformat.h:713
static double c[64]
int error_recognition
Error recognition; higher values will detect more errors but may misdetect some more or less valid pa...
Definition: avformat.h:1150
Main libavformat public API header.
int disposition
AV_DISPOSITION_* bit field.
Definition: avformat.h:724
char * doctype
Definition: matroskadec.c:96
static EbmlSyntax matroska_seekhead_entry[]
Definition: matroskadec.c:529
int av_grow_packet(AVPacket *pkt, int grow_by)
Increase packet size, correctly zeroing padding.
Definition: avpacket.c:111
int den
denominator
Definition: rational.h:45
#define MATROSKA_ID_ENCODINGSIGNATURE
Definition: matroska.h:149
#define MATROSKA_ID_SEGMENT
Definition: matroska.h:53
uint32_t id
Definition: matroskadec.c:69
static EbmlSyntax matroska_tagtargets[]
Definition: matroskadec.c:509
MatroskaTagTarget target
Definition: matroskadec.c:224
void ff_metadata_conv(AVDictionary **pm, const AVMetadataConv *d_conv, const AVMetadataConv *s_conv)
Definition: metadata.c:26
The optional settings (rendering instructions) that immediately follow the timestamp specifier of a W...
Definition: avcodec.h:1015
#define MATROSKA_ID_SEEKHEAD
Definition: matroska.h:60
ASS as defined in Matroska.
Definition: avcodec.h:496
static int matroska_parse_webvtt(MatroskaDemuxContext *matroska, MatroskaTrack *track, AVStream *st, uint8_t *data, int data_len, uint64_t timecode, uint64_t duration, int64_t pos)
Definition: matroskadec.c:2271
#define EBML_ID_HEADER
Definition: matroska.h:33
#define AV_RB32(x)
Definition: intreadwrite.h:258
void av_codec_set_seek_preroll(AVCodecContext *avctx, int val)
int skip_to_keyframe
Indicates that everything up to the next keyframe should be discarded.
Definition: avformat.h:863
#define MATROSKA_ID_ENCODINGCOMPRESSION
Definition: matroska.h:138
#define MATROSKA_ID_CLUSTERPREVSIZE
Definition: matroska.h:190
#define AVERROR_INVALIDDATA
#define MATROSKA_ID_POINTENTRY
Definition: matroska.h:152
#define AV_RL32(x)
Definition: intreadwrite.h:275
int len
uint8_t pi<< 24) CONV_FUNC_GROUP(AV_SAMPLE_FMT_FLT, float, AV_SAMPLE_FMT_U8, uint8_t,(*(constuint8_t *) pi-0x80)*(1.0f/(1<< 7))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_DBL, double, AV_SAMPLE_FMT_U8, uint8_t,(*(constuint8_t *) pi-0x80)*(1.0/(1<< 7))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_U8, uint8_t, AV_SAMPLE_FMT_S16, int16_t,(*(constint16_t *) pi >>8)+0x80) CONV_FUNC_GROUP(AV_SAMPLE_FMT_FLT, float, AV_SAMPLE_FMT_S16, int16_t,*(constint16_t *) pi *(1.0f/(1<< 15))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_DBL, double, AV_SAMPLE_FMT_S16, int16_t,*(constint16_t *) pi *(1.0/(1<< 15))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_U8, uint8_t, AV_SAMPLE_FMT_S32, int32_t,(*(constint32_t *) pi >>24)+0x80) CONV_FUNC_GROUP(AV_SAMPLE_FMT_FLT, float, AV_SAMPLE_FMT_S32, int32_t,*(constint32_t *) pi *(1.0f/(1U<< 31))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_DBL, double, AV_SAMPLE_FMT_S32, int32_t,*(constint32_t *) pi *(1.0/(1U<< 31))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_U8, uint8_t, AV_SAMPLE_FMT_FLT, float, av_clip_uint8(lrintf(*(constfloat *) pi *(1<< 7))+0x80)) CONV_FUNC_GROUP(AV_SAMPLE_FMT_S16, int16_t, AV_SAMPLE_FMT_FLT, float, av_clip_int16(lrintf(*(constfloat *) pi *(1<< 15)))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_S32, int32_t, AV_SAMPLE_FMT_FLT, float, av_clipl_int32(llrintf(*(constfloat *) pi *(1U<< 31)))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_U8, uint8_t, AV_SAMPLE_FMT_DBL, double, av_clip_uint8(lrint(*(constdouble *) pi *(1<< 7))+0x80)) CONV_FUNC_GROUP(AV_SAMPLE_FMT_S16, int16_t, AV_SAMPLE_FMT_DBL, double, av_clip_int16(lrint(*(constdouble *) pi *(1<< 15)))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_S32, int32_t, AV_SAMPLE_FMT_DBL, double, av_clipl_int32(llrint(*(constdouble *) pi *(1U<< 31))))#defineSET_CONV_FUNC_GROUP(ofmt, ifmt) staticvoidset_generic_function(AudioConvert *ac){}voidff_audio_convert_free(AudioConvert **ac){return;ff_dither_free(&(*ac) ->dc);av_freep(ac);}AudioConvert *ff_audio_convert_alloc(AVAudioResampleContext *avr, enumAVSampleFormatout_fmt, enumAVSampleFormatin_fmt, intchannels, intsample_rate, intapply_map){AudioConvert *ac;intin_planar, out_planar;ac=av_mallocz(sizeof(*ac));returnNULL;ac->avr=avr;ac->out_fmt=out_fmt;ac->in_fmt=in_fmt;ac->channels=channels;ac->apply_map=apply_map;if(avr->dither_method!=AV_RESAMPLE_DITHER_NONE &&av_get_packed_sample_fmt(out_fmt)==AV_SAMPLE_FMT_S16 &&av_get_bytes_per_sample(in_fmt)>2){ac->dc=ff_dither_alloc(avr, out_fmt, in_fmt, channels, sample_rate, apply_map);if(!ac->dc){av_free(ac);returnNULL;}returnac;}in_planar=av_sample_fmt_is_planar(in_fmt);out_planar=av_sample_fmt_is_planar(out_fmt);if(in_planar==out_planar){ac->func_type=CONV_FUNC_TYPE_FLAT;ac->planes=in_planar?ac->channels:1;}elseif(in_planar) ac->func_type=CONV_FUNC_TYPE_INTERLEAVE;elseac->func_type=CONV_FUNC_TYPE_DEINTERLEAVE;set_generic_function(ac);ff_audio_convert_init_arm(ac);ff_audio_convert_init_x86(ac);returnac;}intff_audio_convert(AudioConvert *ac, AudioData *out, AudioData *in){intuse_generic=1;intlen=in->nb_samples;intp;if(ac->dc){av_dlog(ac->avr,"%dsamples-audio_convert:%sto%s(dithered)\n", len, av_get_sample_fmt_name(ac->in_fmt), av_get_sample_fmt_name(ac->out_fmt));returnff_convert_dither(ac-> out
int channels
number of audio channels
Definition: avcodec.h:1874
#define MATROSKA_VIDEO_STEREO_MODE_COUNT
Definition: matroska.h:278
#define MATROSKA_ID_FILEUID
Definition: matroska.h:211
#define MATROSKA_ID_VIDEOPIXELCROPL
Definition: matroska.h:118
uint64_t non_simple
Definition: matroskadec.c:291
#define MATROSKA_ID_CHAPTERUID
Definition: matroska.h:225
Opaque data information usually sparse.
Definition: avcodec.h:2235
static EbmlSyntax matroska_index_entry[]
Definition: matroskadec.c:488
uint64_t discard_padding
Definition: matroskadec.c:295
#define AVERROR(e)
static int ebml_read_binary(AVIOContext *pb, int length, EbmlBin *bin)
Definition: matroskadec.c:806
unsigned int avio_rb16(AVIOContext *s)
Definition: aviobuf.c:609
#define MATROSKA_ID_VIDEODISPLAYUNIT
Definition: matroska.h:120
static int ebml_read_uint(AVIOContext *pb, int size, uint64_t *num)
Definition: matroskadec.c:746
#define MATROSKA_ID_TRACKMAXBLKADDID
Definition: matroska.h:108
int64_t dts
Decompression timestamp in AVStream-&gt;time_base units; the time at which the packet is decompressed...
Definition: avcodec.h:1062
#define EBML_ID_EBMLMAXSIZELENGTH
Definition: matroska.h:39
int64_t duration
Decoding: duration of the stream, in AV_TIME_BASE fractional seconds.
Definition: avformat.h:1033
MatroskaTrackEncryption encryption
Definition: matroskadec.c:114
#define MATROSKA_ID_CHAPSTRING
Definition: matroska.h:219
void INT64 start
Definition: avisynth_c.h:594
#define MATROSKA_ID_TAGSTRING
Definition: matroska.h:169
#define av_assert0(cond)
assert() equivalent, that is always enabled.
Definition: avassert.h:37
static EbmlSyntax matroska_index_pos[]
Definition: matroskadec.c:479
static AVPacket pkt
Definition: demuxing.c:52
const char int length
Definition: avisynth_c.h:668
static int ebml_read_float(AVIOContext *pb, int size, double *num)
Definition: matroskadec.c:765
#define MATROSKA_ID_DURATION
Definition: matroska.h:67
uint64_t length
Definition: matroskadec.c:235
static int matroska_aac_profile(char *codec_id)
Definition: matroskadec.c:1469
int stream_index
Definition: avcodec.h:1065
#define EBML_ID_DOCTYPEVERSION
Definition: matroska.h:41
static void matroska_clear_queue(MatroskaDemuxContext *matroska)
Definition: matroskadec.c:1999
static EbmlSyntax matroska_chapter_entry[]
Definition: matroskadec.c:453
uint8_t bitdepth
Definition: dirac.c:81
#define CONFIG_BZLIB
Definition: config.h:312
enum AVDiscard discard
Selects which packets can be discarded at will and do not need to be demuxed.
Definition: avformat.h:726
AVRational r_frame_rate
Real base framerate of the stream.
Definition: avformat.h:839
#define MATROSKA_ID_ATTACHEDFILE
Definition: matroska.h:206
EbmlList blocks
Definition: matroskadec.c:240
This structure stores compressed data.
Definition: avcodec.h:1040
static EbmlSyntax matroska_chapter_display[]
Definition: matroskadec.c:447
#define MATROSKA_ID_CODECSTATE
Definition: matroska.h:202
uint64_t default_duration
Definition: matroskadec.c:163
int delay
Codec delay.
Definition: avcodec.h:1302
#define MATROSKA_ID_CODECINFOURL
Definition: matroska.h:91
int64_t pts
Presentation timestamp in AVStream-&gt;time_base units; the time at which the decompressed packet will b...
Definition: avcodec.h:1056
#define MATROSKA_ID_VIDEOPIXELWIDTH
Definition: matroska.h:114
static void matroska_add_index_entries(MatroskaDemuxContext *matroska)
Definition: matroskadec.c:1427
#define MATROSKA_ID_TRACKAUDIO
Definition: matroska.h:82
#define AV_NOPTS_VALUE
Undefined timestamp value.
Definition: avcodec.h:2278
#define MATROSKA_ID_ENCODINGSCOPE
Definition: matroska.h:136
void avio_wl16(AVIOContext *s, unsigned int val)
Definition: aviobuf.c:367
const CodecTags ff_mkv_codec_tags[]
Definition: matroska.c:27
void * av_mallocz(size_t size) av_malloc_attrib 1(1)
Allocate a block of size bytes with alignment suitable for all memory accesses (including vectors if ...
Definition: mem.c:241
#define MATROSKA_ID_ENCODINGENCKEYID
Definition: matroska.h:145
#define MATROSKA_ID_DISCARDPADDING
Definition: matroska.h:203
static const char *const matroska_doctypes[]
Definition: matroskadec.c:630
static EbmlSyntax matroska_track_video[]
Definition: matroskadec.c:325
Only parse headers, do not repack.
Definition: avformat.h:600
uint64_t attachuid
Definition: matroskadec.c:220