FFmpeg
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
matroskaenc.c
Go to the documentation of this file.
1 /*
2  * Matroska muxer
3  * Copyright (c) 2007 David Conrad
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 #include <stdint.h>
23 
24 #include "avc.h"
25 #include "hevc.h"
26 #include "avformat.h"
27 #include "avio_internal.h"
28 #include "avlanguage.h"
29 #include "flacenc.h"
30 #include "internal.h"
31 #include "isom.h"
32 #include "matroska.h"
33 #include "riff.h"
34 #include "subtitles.h"
35 #include "vorbiscomment.h"
36 #include "wv.h"
37 
38 #include "libavutil/avstring.h"
40 #include "libavutil/dict.h"
41 #include "libavutil/intfloat.h"
42 #include "libavutil/intreadwrite.h"
43 #include "libavutil/lfg.h"
44 #include "libavutil/mathematics.h"
45 #include "libavutil/opt.h"
46 #include "libavutil/random_seed.h"
47 #include "libavutil/samplefmt.h"
48 #include "libavutil/sha.h"
49 #include "libavutil/stereo3d.h"
50 
51 #include "libavcodec/xiph.h"
52 #include "libavcodec/mpeg4audio.h"
53 #include "libavcodec/internal.h"
54 
55 typedef struct ebml_master {
56  int64_t pos; ///< absolute offset in the file where the master's elements start
57  int sizebytes; ///< how many bytes were reserved for the size
58 } ebml_master;
59 
60 typedef struct mkv_seekhead_entry {
61  unsigned int elementid;
62  uint64_t segmentpos;
64 
65 typedef struct mkv_seekhead {
66  int64_t filepos;
67  int64_t segment_offset; ///< the file offset to the beginning of the segment
68  int reserved_size; ///< -1 if appending to file
72 } mkv_seekhead;
73 
74 typedef struct mkv_cuepoint {
75  uint64_t pts;
77  int tracknum;
78  int64_t cluster_pos; ///< file offset of the cluster containing the block
79  int64_t relative_pos; ///< relative offset from the position of the cluster containing the block
80  int64_t duration; ///< duration of the block according to time base
81 } mkv_cuepoint;
82 
83 typedef struct mkv_cues {
84  int64_t segment_offset;
87 } mkv_cues;
88 
89 typedef struct mkv_track {
90  int write_dts;
91  int has_cue;
92  int64_t ts_offset;
93 } mkv_track;
94 
95 #define MODE_MATROSKAv2 0x01
96 #define MODE_WEBM 0x02
97 
98 typedef struct MatroskaMuxContext {
99  const AVClass *class;
100  int mode;
103  int64_t segment_offset;
105  int64_t cluster_pos; ///< file offset of the current cluster
106  int64_t cluster_pts;
108  int64_t duration;
112 
114 
116 
119  int64_t cues_pos;
121  int is_dash;
123 
126 
129 
130 
131 /** 2 bytes * 3 for EBML IDs, 3 1-byte EBML lengths, 8 bytes for 64 bit
132  * offset, 4 bytes for target EBML ID */
133 #define MAX_SEEKENTRY_SIZE 21
134 
135 /** per-cuepoint-track - 5 1-byte EBML IDs, 5 1-byte EBML sizes, 4
136  * 8-byte uint max */
137 #define MAX_CUETRACKPOS_SIZE 42
138 
139 /** per-cuepoint - 2 1-byte EBML IDs, 2 1-byte EBML sizes, 8-byte uint max */
140 #define MAX_CUEPOINT_SIZE(num_tracks) 12 + MAX_CUETRACKPOS_SIZE * num_tracks
141 
142 /** Seek preroll value for opus */
143 #define OPUS_SEEK_PREROLL 80000000
144 
145 static int ebml_id_size(unsigned int id)
146 {
147  return (av_log2(id + 1) - 1) / 7 + 1;
148 }
149 
150 static void put_ebml_id(AVIOContext *pb, unsigned int id)
151 {
152  int i = ebml_id_size(id);
153  while (i--)
154  avio_w8(pb, (uint8_t)(id >> (i * 8)));
155 }
156 
157 /**
158  * Write an EBML size meaning "unknown size".
159  *
160  * @param bytes The number of bytes the size should occupy (maximum: 8).
161  */
162 static void put_ebml_size_unknown(AVIOContext *pb, int bytes)
163 {
164  av_assert0(bytes <= 8);
165  avio_w8(pb, 0x1ff >> bytes);
166  ffio_fill(pb, 0xff, bytes - 1);
167 }
168 
169 /**
170  * Calculate how many bytes are needed to represent a given number in EBML.
171  */
172 static int ebml_num_size(uint64_t num)
173 {
174  int bytes = 1;
175  while ((num + 1) >> bytes * 7)
176  bytes++;
177  return bytes;
178 }
179 
180 /**
181  * Write a number in EBML variable length format.
182  *
183  * @param bytes The number of bytes that need to be used to write the number.
184  * If zero, any number of bytes can be used.
185  */
186 static void put_ebml_num(AVIOContext *pb, uint64_t num, int bytes)
187 {
188  int i, needed_bytes = ebml_num_size(num);
189 
190  // sizes larger than this are currently undefined in EBML
191  av_assert0(num < (1ULL << 56) - 1);
192 
193  if (bytes == 0)
194  // don't care how many bytes are used, so use the min
195  bytes = needed_bytes;
196  // the bytes needed to write the given size would exceed the bytes
197  // that we need to use, so write unknown size. This shouldn't happen.
198  av_assert0(bytes >= needed_bytes);
199 
200  num |= 1ULL << bytes * 7;
201  for (i = bytes - 1; i >= 0; i--)
202  avio_w8(pb, (uint8_t)(num >> i * 8));
203 }
204 
205 static void put_ebml_uint(AVIOContext *pb, unsigned int elementid, uint64_t val)
206 {
207  int i, bytes = 1;
208  uint64_t tmp = val;
209  while (tmp >>= 8)
210  bytes++;
211 
212  put_ebml_id(pb, elementid);
213  put_ebml_num(pb, bytes, 0);
214  for (i = bytes - 1; i >= 0; i--)
215  avio_w8(pb, (uint8_t)(val >> i * 8));
216 }
217 
218 static void put_ebml_sint(AVIOContext *pb, unsigned int elementid, int64_t val)
219 {
220  int i, bytes = 1;
221  uint64_t tmp = 2*(val < 0 ? val^-1 : val);
222 
223  while (tmp>>=8) bytes++;
224 
225  put_ebml_id(pb, elementid);
226  put_ebml_num(pb, bytes, 0);
227  for (i = bytes - 1; i >= 0; i--)
228  avio_w8(pb, (uint8_t)(val >> i * 8));
229 }
230 
231 static void put_ebml_float(AVIOContext *pb, unsigned int elementid, double val)
232 {
233  put_ebml_id(pb, elementid);
234  put_ebml_num(pb, 8, 0);
235  avio_wb64(pb, av_double2int(val));
236 }
237 
238 static void put_ebml_binary(AVIOContext *pb, unsigned int elementid,
239  const void *buf, int size)
240 {
241  put_ebml_id(pb, elementid);
242  put_ebml_num(pb, size, 0);
243  avio_write(pb, buf, size);
244 }
245 
246 static void put_ebml_string(AVIOContext *pb, unsigned int elementid,
247  const char *str)
248 {
249  put_ebml_binary(pb, elementid, str, strlen(str));
250 }
251 
252 /**
253  * Write a void element of a given size. Useful for reserving space in
254  * the file to be written to later.
255  *
256  * @param size The number of bytes to reserve, which must be at least 2.
257  */
258 static void put_ebml_void(AVIOContext *pb, uint64_t size)
259 {
260  int64_t currentpos = avio_tell(pb);
261 
262  av_assert0(size >= 2);
263 
265  // we need to subtract the length needed to store the size from the
266  // size we need to reserve so 2 cases, we use 8 bytes to store the
267  // size if possible, 1 byte otherwise
268  if (size < 10)
269  put_ebml_num(pb, size - 1, 0);
270  else
271  put_ebml_num(pb, size - 9, 8);
272  ffio_fill(pb, 0, currentpos + size - avio_tell(pb));
273 }
274 
275 static ebml_master start_ebml_master(AVIOContext *pb, unsigned int elementid,
276  uint64_t expectedsize)
277 {
278  int bytes = expectedsize ? ebml_num_size(expectedsize) : 8;
279  put_ebml_id(pb, elementid);
280  put_ebml_size_unknown(pb, bytes);
281  return (ebml_master) {avio_tell(pb), bytes };
282 }
283 
285 {
286  int64_t pos = avio_tell(pb);
287 
288  if (avio_seek(pb, master.pos - master.sizebytes, SEEK_SET) < 0)
289  return;
290  put_ebml_num(pb, pos - master.pos, master.sizebytes);
291  avio_seek(pb, pos, SEEK_SET);
292 }
293 
294 static void put_xiph_size(AVIOContext *pb, int size)
295 {
296  ffio_fill(pb, 255, size / 255);
297  avio_w8(pb, size % 255);
298 }
299 
300 /**
301  * Initialize a mkv_seekhead element to be ready to index level 1 Matroska
302  * elements. If a maximum number of elements is specified, enough space
303  * will be reserved at the current file location to write a seek head of
304  * that size.
305  *
306  * @param segment_offset The absolute offset to the position in the file
307  * where the segment begins.
308  * @param numelements The maximum number of elements that will be indexed
309  * by this seek head, 0 if unlimited.
310  */
311 static mkv_seekhead *mkv_start_seekhead(AVIOContext *pb, int64_t segment_offset,
312  int numelements)
313 {
314  mkv_seekhead *new_seekhead = av_mallocz(sizeof(mkv_seekhead));
315  if (!new_seekhead)
316  return NULL;
317 
318  new_seekhead->segment_offset = segment_offset;
319 
320  if (numelements > 0) {
321  new_seekhead->filepos = avio_tell(pb);
322  // 21 bytes max for a seek entry, 10 bytes max for the SeekHead ID
323  // and size, and 3 bytes to guarantee that an EBML void element
324  // will fit afterwards
325  new_seekhead->reserved_size = numelements * MAX_SEEKENTRY_SIZE + 13;
326  new_seekhead->max_entries = numelements;
327  put_ebml_void(pb, new_seekhead->reserved_size);
328  }
329  return new_seekhead;
330 }
331 
332 static int mkv_add_seekhead_entry(mkv_seekhead *seekhead, unsigned int elementid, uint64_t filepos)
333 {
334  mkv_seekhead_entry *entries = seekhead->entries;
335 
336  // don't store more elements than we reserved space for
337  if (seekhead->max_entries > 0 && seekhead->max_entries <= seekhead->num_entries)
338  return -1;
339 
340  entries = av_realloc_array(entries, seekhead->num_entries + 1, sizeof(mkv_seekhead_entry));
341  if (!entries)
342  return AVERROR(ENOMEM);
343  seekhead->entries = entries;
344 
345  seekhead->entries[seekhead->num_entries].elementid = elementid;
346  seekhead->entries[seekhead->num_entries++].segmentpos = filepos - seekhead->segment_offset;
347 
348  return 0;
349 }
350 
351 /**
352  * Write the seek head to the file and free it. If a maximum number of
353  * elements was specified to mkv_start_seekhead(), the seek head will
354  * be written at the location reserved for it. Otherwise, it is written
355  * at the current location in the file.
356  *
357  * @return The file offset where the seekhead was written,
358  * -1 if an error occurred.
359  */
360 static int64_t mkv_write_seekhead(AVIOContext *pb, mkv_seekhead *seekhead)
361 {
362  ebml_master metaseek, seekentry;
363  int64_t currentpos;
364  int i;
365 
366  currentpos = avio_tell(pb);
367 
368  if (seekhead->reserved_size > 0) {
369  if (avio_seek(pb, seekhead->filepos, SEEK_SET) < 0) {
370  currentpos = -1;
371  goto fail;
372  }
373  }
374 
375  metaseek = start_ebml_master(pb, MATROSKA_ID_SEEKHEAD, seekhead->reserved_size);
376  for (i = 0; i < seekhead->num_entries; i++) {
377  mkv_seekhead_entry *entry = &seekhead->entries[i];
378 
380 
382  put_ebml_num(pb, ebml_id_size(entry->elementid), 0);
383  put_ebml_id(pb, entry->elementid);
384 
386  end_ebml_master(pb, seekentry);
387  }
388  end_ebml_master(pb, metaseek);
389 
390  if (seekhead->reserved_size > 0) {
391  uint64_t remaining = seekhead->filepos + seekhead->reserved_size - avio_tell(pb);
392  put_ebml_void(pb, remaining);
393  avio_seek(pb, currentpos, SEEK_SET);
394 
395  currentpos = seekhead->filepos;
396  }
397 fail:
398  av_freep(&seekhead->entries);
399  av_free(seekhead);
400 
401  return currentpos;
402 }
403 
404 static mkv_cues *mkv_start_cues(int64_t segment_offset)
405 {
406  mkv_cues *cues = av_mallocz(sizeof(mkv_cues));
407  if (!cues)
408  return NULL;
409 
410  cues->segment_offset = segment_offset;
411  return cues;
412 }
413 
414 static int mkv_add_cuepoint(mkv_cues *cues, int stream, int tracknum, int64_t ts,
415  int64_t cluster_pos, int64_t relative_pos, int64_t duration)
416 {
417  mkv_cuepoint *entries = cues->entries;
418 
419  if (ts < 0)
420  return 0;
421 
422  entries = av_realloc_array(entries, cues->num_entries + 1, sizeof(mkv_cuepoint));
423  if (!entries)
424  return AVERROR(ENOMEM);
425  cues->entries = entries;
426 
427  cues->entries[cues->num_entries].pts = ts;
428  cues->entries[cues->num_entries].stream_idx = stream;
429  cues->entries[cues->num_entries].tracknum = tracknum;
430  cues->entries[cues->num_entries].cluster_pos = cluster_pos - cues->segment_offset;
431  cues->entries[cues->num_entries].relative_pos = relative_pos;
432  cues->entries[cues->num_entries++].duration = duration;
433 
434  return 0;
435 }
436 
437 static int64_t mkv_write_cues(AVFormatContext *s, mkv_cues *cues, mkv_track *tracks, int num_tracks)
438 {
439  AVIOContext *pb = s->pb;
440  ebml_master cues_element;
441  int64_t currentpos;
442  int i, j;
443 
444  currentpos = avio_tell(pb);
445  cues_element = start_ebml_master(pb, MATROSKA_ID_CUES, 0);
446 
447  for (i = 0; i < cues->num_entries; i++) {
448  ebml_master cuepoint, track_positions;
449  mkv_cuepoint *entry = &cues->entries[i];
450  uint64_t pts = entry->pts;
451  int ctp_nb = 0;
452 
453  // Calculate the number of entries, so we know the element size
454  for (j = 0; j < num_tracks; j++)
455  tracks[j].has_cue = 0;
456  for (j = 0; j < cues->num_entries - i && entry[j].pts == pts; j++) {
457  int tracknum = entry[j].stream_idx;
458  av_assert0(tracknum>=0 && tracknum<num_tracks);
459  if (tracks[tracknum].has_cue && s->streams[tracknum]->codec->codec_type != AVMEDIA_TYPE_SUBTITLE)
460  continue;
461  tracks[tracknum].has_cue = 1;
462  ctp_nb ++;
463  }
464 
467 
468  // put all the entries from different tracks that have the exact same
469  // timestamp into the same CuePoint
470  for (j = 0; j < num_tracks; j++)
471  tracks[j].has_cue = 0;
472  for (j = 0; j < cues->num_entries - i && entry[j].pts == pts; j++) {
473  int tracknum = entry[j].stream_idx;
474  av_assert0(tracknum>=0 && tracknum<num_tracks);
475  if (tracks[tracknum].has_cue && s->streams[tracknum]->codec->codec_type != AVMEDIA_TYPE_SUBTITLE)
476  continue;
477  tracks[tracknum].has_cue = 1;
479  put_ebml_uint(pb, MATROSKA_ID_CUETRACK , entry[j].tracknum );
480  put_ebml_uint(pb, MATROSKA_ID_CUECLUSTERPOSITION , entry[j].cluster_pos);
481  put_ebml_uint(pb, MATROSKA_ID_CUERELATIVEPOSITION, entry[j].relative_pos);
482  if (entry[j].duration != -1)
484  end_ebml_master(pb, track_positions);
485  }
486  i += j - 1;
487  end_ebml_master(pb, cuepoint);
488  }
489  end_ebml_master(pb, cues_element);
490 
491  return currentpos;
492 }
493 
495 {
496  const uint8_t *header_start[3];
497  int header_len[3];
498  int first_header_size;
499  int j;
500 
501  if (codec->codec_id == AV_CODEC_ID_VORBIS)
502  first_header_size = 30;
503  else
504  first_header_size = 42;
505 
507  first_header_size, header_start, header_len) < 0) {
508  av_log(s, AV_LOG_ERROR, "Extradata corrupt.\n");
509  return -1;
510  }
511 
512  avio_w8(pb, 2); // number packets - 1
513  for (j = 0; j < 2; j++) {
514  put_xiph_size(pb, header_len[j]);
515  }
516  for (j = 0; j < 3; j++)
517  avio_write(pb, header_start[j], header_len[j]);
518 
519  return 0;
520 }
521 
523 {
524  if (codec->extradata && codec->extradata_size == 2)
525  avio_write(pb, codec->extradata, 2);
526  else
527  avio_wl16(pb, 0x403); // fallback to the version mentioned in matroska specs
528  return 0;
529 }
530 
532  AVIOContext *pb, AVCodecContext *codec)
533 {
534  int write_comment = (codec->channel_layout &&
535  !(codec->channel_layout & ~0x3ffffULL) &&
537  int ret = ff_flac_write_header(pb, codec->extradata, codec->extradata_size,
538  !write_comment);
539 
540  if (ret < 0)
541  return ret;
542 
543  if (write_comment) {
544  const char *vendor = (s->flags & AVFMT_FLAG_BITEXACT) ?
545  "Lavf" : LIBAVFORMAT_IDENT;
546  AVDictionary *dict = NULL;
547  uint8_t buf[32], *data, *p;
548  int len;
549 
550  snprintf(buf, sizeof(buf), "0x%"PRIx64, codec->channel_layout);
551  av_dict_set(&dict, "WAVEFORMATEXTENSIBLE_CHANNEL_MASK", buf, 0);
552 
553  len = ff_vorbiscomment_length(dict, vendor);
554  data = av_malloc(len + 4);
555  if (!data) {
556  av_dict_free(&dict);
557  return AVERROR(ENOMEM);
558  }
559 
560  data[0] = 0x84;
561  AV_WB24(data + 1, len);
562 
563  p = data + 4;
564  ff_vorbiscomment_write(&p, &dict, vendor);
565 
566  avio_write(pb, data, len + 4);
567 
568  av_freep(&data);
569  av_dict_free(&dict);
570  }
571 
572  return 0;
573 }
574 
576  int *sample_rate, int *output_sample_rate)
577 {
578  MPEG4AudioConfig mp4ac;
579 
580  if (avpriv_mpeg4audio_get_config(&mp4ac, codec->extradata,
581  codec->extradata_size * 8, 1) < 0) {
582  av_log(s, AV_LOG_ERROR,
583  "Error parsing AAC extradata, unable to determine samplerate.\n");
584  return AVERROR(EINVAL);
585  }
586 
587  *sample_rate = mp4ac.sample_rate;
588  *output_sample_rate = mp4ac.ext_sample_rate;
589  return 0;
590 }
591 
593  AVCodecContext *codec,
594  AVIOContext *dyn_cp)
595 {
596  switch (codec->codec_id) {
597  case AV_CODEC_ID_VORBIS:
598  case AV_CODEC_ID_THEORA:
599  return put_xiph_codecpriv(s, dyn_cp, codec);
600  case AV_CODEC_ID_FLAC:
601  return put_flac_codecpriv(s, dyn_cp, codec);
602  case AV_CODEC_ID_WAVPACK:
603  return put_wv_codecpriv(dyn_cp, codec);
604  case AV_CODEC_ID_H264:
605  return ff_isom_write_avcc(dyn_cp, codec->extradata,
606  codec->extradata_size);
607  case AV_CODEC_ID_HEVC:
608  return ff_isom_write_hvcc(dyn_cp, codec->extradata,
609  codec->extradata_size, 0);
610  case AV_CODEC_ID_ALAC:
611  if (codec->extradata_size < 36) {
612  av_log(s, AV_LOG_ERROR,
613  "Invalid extradata found, ALAC expects a 36-byte "
614  "QuickTime atom.");
615  return AVERROR_INVALIDDATA;
616  } else
617  avio_write(dyn_cp, codec->extradata + 12,
618  codec->extradata_size - 12);
619  break;
620  default:
621  if (codec->codec_id == AV_CODEC_ID_PRORES &&
623  avio_wl32(dyn_cp, codec->codec_tag);
624  } else if (codec->extradata_size && codec->codec_id != AV_CODEC_ID_TTA)
625  avio_write(dyn_cp, codec->extradata, codec->extradata_size);
626  }
627 
628  return 0;
629 }
630 
632  AVCodecContext *codec, int native_id,
633  int qt_id)
634 {
635  AVIOContext *dyn_cp;
636  uint8_t *codecpriv;
637  int ret, codecpriv_size;
638 
639  ret = avio_open_dyn_buf(&dyn_cp);
640  if (ret < 0)
641  return ret;
642 
643  if (native_id) {
644  ret = mkv_write_native_codecprivate(s, codec, dyn_cp);
645  } else if (codec->codec_type == AVMEDIA_TYPE_VIDEO) {
646  if (qt_id) {
647  if (!codec->codec_tag)
649  codec->codec_id);
650  if (codec->extradata_size) {
653  ) {
654  int i;
655  avio_wb32(dyn_cp, 0x5a + codec->extradata_size);
656  avio_wl32(dyn_cp, codec->codec_tag);
657  for(i = 0; i < 0x5a - 8; i++)
658  avio_w8(dyn_cp, 0);
659  }
660  avio_write(dyn_cp, codec->extradata, codec->extradata_size);
661  }
662  } else {
664  av_log(s, AV_LOG_WARNING, "codec %s is not supported by this format\n",
665  avcodec_get_name(codec->codec_id));
666 
667  if (!codec->codec_tag)
669  codec->codec_id);
670  if (!codec->codec_tag && codec->codec_id != AV_CODEC_ID_RAWVIDEO) {
671  av_log(s, AV_LOG_ERROR, "No bmp codec tag found for codec %s\n",
672  avcodec_get_name(codec->codec_id));
673  ret = AVERROR(EINVAL);
674  }
675 
676  ff_put_bmp_header(dyn_cp, codec, ff_codec_bmp_tags, 0, 0);
677  }
678  } else if (codec->codec_type == AVMEDIA_TYPE_AUDIO) {
679  unsigned int tag;
681  if (!tag) {
682  av_log(s, AV_LOG_ERROR, "No wav codec tag found for codec %s\n",
683  avcodec_get_name(codec->codec_id));
684  ret = AVERROR(EINVAL);
685  }
686  if (!codec->codec_tag)
687  codec->codec_tag = tag;
688 
690  }
691 
692  codecpriv_size = avio_close_dyn_buf(dyn_cp, &codecpriv);
693  if (codecpriv_size)
695  codecpriv_size);
696  av_free(codecpriv);
697  return ret;
698 }
699 
700 
702  AVStream *st, int mode, int *h_width, int *h_height)
703 {
704  int i;
705  int ret = 0;
708 
709  *h_width = 1;
710  *h_height = 1;
711  // convert metadata into proper side data and add it to the stream
712  if ((tag = av_dict_get(st->metadata, "stereo_mode", NULL, 0)) ||
713  (tag = av_dict_get( s->metadata, "stereo_mode", NULL, 0))) {
714  int stereo_mode = atoi(tag->value);
715 
716  for (i=0; i<MATROSKA_VIDEO_STEREOMODE_TYPE_NB; i++)
717  if (!strcmp(tag->value, ff_matroska_video_stereo_mode[i])){
718  stereo_mode = i;
719  break;
720  }
721 
722  if (stereo_mode < MATROSKA_VIDEO_STEREOMODE_TYPE_NB &&
723  stereo_mode != 10 && stereo_mode != 12) {
724  int ret = ff_mkv_stereo3d_conv(st, stereo_mode);
725  if (ret < 0)
726  return ret;
727  }
728  }
729 
730  // iterate to find the stereo3d side data
731  for (i = 0; i < st->nb_side_data; i++) {
732  AVPacketSideData sd = st->side_data[i];
733  if (sd.type == AV_PKT_DATA_STEREO3D) {
734  AVStereo3D *stereo = (AVStereo3D *)sd.data;
735 
736  switch (stereo->type) {
737  case AV_STEREO3D_2D:
739  break;
741  format = (stereo->flags & AV_STEREO3D_FLAG_INVERT)
744  *h_width = 2;
745  break;
748  if (stereo->flags & AV_STEREO3D_FLAG_INVERT)
749  format--;
750  *h_height = 2;
751  break;
754  if (stereo->flags & AV_STEREO3D_FLAG_INVERT)
755  format--;
756  break;
757  case AV_STEREO3D_LINES:
759  if (stereo->flags & AV_STEREO3D_FLAG_INVERT)
760  format--;
761  *h_height = 2;
762  break;
763  case AV_STEREO3D_COLUMNS:
765  if (stereo->flags & AV_STEREO3D_FLAG_INVERT)
766  format--;
767  *h_width = 2;
768  break;
771  if (stereo->flags & AV_STEREO3D_FLAG_INVERT)
772  format++;
773  break;
774  }
775  break;
776  }
777  }
778 
779  if (format == MATROSKA_VIDEO_STEREOMODE_TYPE_NB)
780  return ret;
781 
782  // if webm, do not write unsupported modes
783  if ((mode == MODE_WEBM &&
786  || format >= MATROSKA_VIDEO_STEREOMODE_TYPE_NB) {
787  av_log(s, AV_LOG_ERROR,
788  "The specified stereo mode is not valid.\n");
790  return AVERROR(EINVAL);
791  }
792 
793  // write StereoMode if format is valid
795 
796  return ret;
797 }
798 
800  int i, AVIOContext *pb, int default_stream_exists)
801 {
802  AVStream *st = s->streams[i];
803  AVCodecContext *codec = st->codec;
804  ebml_master subinfo, track;
805  int native_id = 0;
806  int qt_id = 0;
807  int bit_depth = av_get_bits_per_sample(codec->codec_id);
808  int sample_rate = codec->sample_rate;
809  int output_sample_rate = 0;
810  int display_width_div = 1;
811  int display_height_div = 1;
812  int j, ret;
814 
815  // ms precision is the de-facto standard timescale for mkv files
816  avpriv_set_pts_info(st, 64, 1, 1000);
817 
818  if (codec->codec_type == AVMEDIA_TYPE_ATTACHMENT) {
819  mkv->have_attachments = 1;
820  return 0;
821  }
822 
823  if (!bit_depth && codec->codec_id != AV_CODEC_ID_ADPCM_G726)
824  bit_depth = av_get_bytes_per_sample(codec->sample_fmt) << 3;
825  if (!bit_depth)
826  bit_depth = codec->bits_per_coded_sample;
827 
828  if (codec->codec_id == AV_CODEC_ID_AAC) {
829  ret = get_aac_sample_rates(s, codec, &sample_rate, &output_sample_rate);
830  if (ret < 0)
831  return ret;
832  }
833 
836  mkv->is_dash ? mkv->dash_track_number : i + 1);
838  mkv->is_dash ? mkv->dash_track_number : i + 1);
839  put_ebml_uint (pb, MATROSKA_ID_TRACKFLAGLACING , 0); // no lacing (yet)
840 
841  if ((tag = av_dict_get(st->metadata, "title", NULL, 0)))
843  tag = av_dict_get(st->metadata, "language", NULL, 0);
844  if (mkv->mode != MODE_WEBM || codec->codec_id != AV_CODEC_ID_WEBVTT) {
845  put_ebml_string(pb, MATROSKA_ID_TRACKLANGUAGE, tag && tag->value ? tag->value:"und");
846  } else if (tag && tag->value) {
848  }
849 
850  // The default value for TRACKFLAGDEFAULT is 1, so add element
851  // if we need to clear it.
852  if (default_stream_exists && !(st->disposition & AV_DISPOSITION_DEFAULT))
854 
857 
858  if (mkv->mode == MODE_WEBM && codec->codec_id == AV_CODEC_ID_WEBVTT) {
859  const char *codec_id;
861  codec_id = "D_WEBVTT/CAPTIONS";
862  native_id = MATROSKA_TRACK_TYPE_SUBTITLE;
863  } else if (st->disposition & AV_DISPOSITION_DESCRIPTIONS) {
864  codec_id = "D_WEBVTT/DESCRIPTIONS";
865  native_id = MATROSKA_TRACK_TYPE_METADATA;
866  } else if (st->disposition & AV_DISPOSITION_METADATA) {
867  codec_id = "D_WEBVTT/METADATA";
868  native_id = MATROSKA_TRACK_TYPE_METADATA;
869  } else {
870  codec_id = "D_WEBVTT/SUBTITLES";
871  native_id = MATROSKA_TRACK_TYPE_SUBTITLE;
872  }
873  put_ebml_string(pb, MATROSKA_ID_CODECID, codec_id);
874  } else {
875  // look for a codec ID string specific to mkv to use,
876  // if none are found, use AVI codes
877  for (j = 0; ff_mkv_codec_tags[j].id != AV_CODEC_ID_NONE; j++) {
878  if (ff_mkv_codec_tags[j].id == codec->codec_id) {
880  native_id = 1;
881  break;
882  }
883  }
884  if (codec->codec_id == AV_CODEC_ID_RAWVIDEO && !codec->codec_tag) {
885  if (mkv->allow_raw_vfw) {
886  native_id = 0;
887  } else {
888  av_log(s, AV_LOG_ERROR, "Raw RGB is not supported Natively in Matroska, you can use AVI or NUT or\n"
889  "If you would like to store it anyway using VFW mode, enable allow_raw_vfw (-allow_raw_vfw 1)\n");
890  return AVERROR(EINVAL);
891  }
892  }
893  }
894 
895  if (codec->codec_type == AVMEDIA_TYPE_AUDIO && codec->initial_padding && codec->codec_id == AV_CODEC_ID_OPUS) {
896 // mkv->tracks[i].ts_offset = av_rescale_q(codec->initial_padding,
897 // (AVRational){ 1, codec->sample_rate },
898 // st->time_base);
899 
902  (AVRational){ 1, codec->sample_rate },
903  (AVRational){ 1, 1000000000 }));
904  }
905  if (codec->codec_id == AV_CODEC_ID_OPUS) {
907  }
908 
909  if (mkv->mode == MODE_WEBM && !(codec->codec_id == AV_CODEC_ID_VP8 ||
910  codec->codec_id == AV_CODEC_ID_VP9 ||
911  codec->codec_id == AV_CODEC_ID_OPUS ||
912  codec->codec_id == AV_CODEC_ID_VORBIS ||
913  codec->codec_id == AV_CODEC_ID_WEBVTT)) {
915  "Only VP8 or VP9 video and Vorbis or Opus audio and WebVTT subtitles are supported for WebM.\n");
916  return AVERROR(EINVAL);
917  }
918 
919  switch (codec->codec_type) {
920  case AVMEDIA_TYPE_VIDEO:
922 
923  if( st->avg_frame_rate.num > 0 && st->avg_frame_rate.den > 0
924  && 1.0/av_q2d(st->avg_frame_rate) > av_q2d(codec->time_base))
925  put_ebml_uint(pb, MATROSKA_ID_TRACKDEFAULTDURATION, 1E9 / av_q2d(st->avg_frame_rate));
926  else
927  put_ebml_uint(pb, MATROSKA_ID_TRACKDEFAULTDURATION, av_q2d(codec->time_base)*1E9);
928 
929  if (!native_id &&
930  ff_codec_get_tag(ff_codec_movvideo_tags, codec->codec_id) &&
931  ((!ff_codec_get_tag(ff_codec_bmp_tags, codec->codec_id) && codec->codec_id != AV_CODEC_ID_RAWVIDEO) ||
932  codec->codec_id == AV_CODEC_ID_SVQ1 ||
933  codec->codec_id == AV_CODEC_ID_SVQ3 ||
934  codec->codec_id == AV_CODEC_ID_CINEPAK))
935  qt_id = 1;
936 
937  if (qt_id)
938  put_ebml_string(pb, MATROSKA_ID_CODECID, "V_QUICKTIME");
939  else if (!native_id) {
940  // if there is no mkv-specific codec ID, use VFW mode
941  put_ebml_string(pb, MATROSKA_ID_CODECID, "V_MS/VFW/FOURCC");
942  mkv->tracks[i].write_dts = 1;
943  }
944 
945  subinfo = start_ebml_master(pb, MATROSKA_ID_TRACKVIDEO, 0);
946  // XXX: interlace flag?
947  put_ebml_uint (pb, MATROSKA_ID_VIDEOPIXELWIDTH , codec->width);
948  put_ebml_uint (pb, MATROSKA_ID_VIDEOPIXELHEIGHT, codec->height);
949 
950  // check both side data and metadata for stereo information,
951  // write the result to the bitstream if any is found
952  ret = mkv_write_stereo_mode(s, pb, st, mkv->mode,
953  &display_width_div,
954  &display_height_div);
955  if (ret < 0)
956  return ret;
957 
958  if (((tag = av_dict_get(st->metadata, "alpha_mode", NULL, 0)) && atoi(tag->value)) ||
959  ((tag = av_dict_get( s->metadata, "alpha_mode", NULL, 0)) && atoi(tag->value)) ||
960  (codec->pix_fmt == AV_PIX_FMT_YUVA420P)) {
962  }
963 
964  // write DisplayWidth and DisplayHeight, they contain the size of
965  // a single source view and/or the display aspect ratio
966  if (st->sample_aspect_ratio.num) {
967  int64_t d_width = av_rescale(codec->width, st->sample_aspect_ratio.num, st->sample_aspect_ratio.den);
968  if (d_width > INT_MAX) {
969  av_log(s, AV_LOG_ERROR, "Overflow in display width\n");
970  return AVERROR(EINVAL);
971  }
972  put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYWIDTH , d_width / display_width_div);
973  put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYHEIGHT, codec->height / display_height_div);
974  } else if (display_width_div != 1 || display_height_div != 1) {
975  put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYWIDTH , codec->width / display_width_div);
976  put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYHEIGHT, codec->height / display_height_div);
977  }
978 
979  if (codec->codec_id == AV_CODEC_ID_RAWVIDEO) {
980  uint32_t color_space = av_le2ne32(codec->codec_tag);
981  put_ebml_binary(pb, MATROSKA_ID_VIDEOCOLORSPACE, &color_space, sizeof(color_space));
982  }
983 
984  end_ebml_master(pb, subinfo);
985  break;
986 
987  case AVMEDIA_TYPE_AUDIO:
989 
990  if (!native_id)
991  // no mkv-specific ID, use ACM mode
992  put_ebml_string(pb, MATROSKA_ID_CODECID, "A_MS/ACM");
993 
994  subinfo = start_ebml_master(pb, MATROSKA_ID_TRACKAUDIO, 0);
995  put_ebml_uint (pb, MATROSKA_ID_AUDIOCHANNELS , codec->channels);
997  if (output_sample_rate)
998  put_ebml_float(pb, MATROSKA_ID_AUDIOOUTSAMPLINGFREQ, output_sample_rate);
999  if (bit_depth)
1000  put_ebml_uint(pb, MATROSKA_ID_AUDIOBITDEPTH, bit_depth);
1001  end_ebml_master(pb, subinfo);
1002  break;
1003 
1004  case AVMEDIA_TYPE_SUBTITLE:
1005  if (!native_id) {
1006  av_log(s, AV_LOG_ERROR, "Subtitle codec %d is not supported.\n", codec->codec_id);
1007  return AVERROR(ENOSYS);
1008  }
1009 
1010  if (mkv->mode != MODE_WEBM || codec->codec_id != AV_CODEC_ID_WEBVTT)
1011  native_id = MATROSKA_TRACK_TYPE_SUBTITLE;
1012 
1013  put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, native_id);
1014  break;
1015  default:
1016  av_log(s, AV_LOG_ERROR, "Only audio, video, and subtitles are supported for Matroska.\n");
1017  return AVERROR(EINVAL);
1018  }
1019 
1020  if (mkv->mode != MODE_WEBM || codec->codec_id != AV_CODEC_ID_WEBVTT) {
1021  ret = mkv_write_codecprivate(s, pb, codec, native_id, qt_id);
1022  if (ret < 0)
1023  return ret;
1024  }
1025 
1026  end_ebml_master(pb, track);
1027 
1028  return 0;
1029 }
1030 
1032 {
1033  MatroskaMuxContext *mkv = s->priv_data;
1034  AVIOContext *pb = s->pb;
1035  ebml_master tracks;
1036  int i, ret, default_stream_exists = 0;
1037 
1039  if (ret < 0)
1040  return ret;
1041 
1042  tracks = start_ebml_master(pb, MATROSKA_ID_TRACKS, 0);
1043  for (i = 0; i < s->nb_streams; i++) {
1044  AVStream *st = s->streams[i];
1045  default_stream_exists |= st->disposition & AV_DISPOSITION_DEFAULT;
1046  }
1047  for (i = 0; i < s->nb_streams; i++) {
1048  ret = mkv_write_track(s, mkv, i, pb, default_stream_exists);
1049  if (ret < 0)
1050  return ret;
1051  }
1052  end_ebml_master(pb, tracks);
1053  return 0;
1054 }
1055 
1057 {
1058  MatroskaMuxContext *mkv = s->priv_data;
1059  AVIOContext *pb = s->pb;
1060  ebml_master chapters, editionentry;
1061  AVRational scale = {1, 1E9};
1062  int i, ret;
1063 
1064  if (!s->nb_chapters || mkv->wrote_chapters)
1065  return 0;
1066 
1068  if (ret < 0) return ret;
1069 
1070  chapters = start_ebml_master(pb, MATROSKA_ID_CHAPTERS , 0);
1071  editionentry = start_ebml_master(pb, MATROSKA_ID_EDITIONENTRY, 0);
1074  for (i = 0; i < s->nb_chapters; i++) {
1075  ebml_master chapteratom, chapterdisplay;
1076  AVChapter *c = s->chapters[i];
1077  int64_t chapterstart = av_rescale_q(c->start, c->time_base, scale);
1078  int64_t chapterend = av_rescale_q(c->end, c->time_base, scale);
1079  AVDictionaryEntry *t = NULL;
1080  if (chapterstart < 0 || chapterstart > chapterend)
1081  return AVERROR_INVALIDDATA;
1082 
1083  chapteratom = start_ebml_master(pb, MATROSKA_ID_CHAPTERATOM, 0);
1085  put_ebml_uint(pb, MATROSKA_ID_CHAPTERTIMESTART, chapterstart);
1086  put_ebml_uint(pb, MATROSKA_ID_CHAPTERTIMEEND, chapterend);
1089  if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
1090  chapterdisplay = start_ebml_master(pb, MATROSKA_ID_CHAPTERDISPLAY, 0);
1093  end_ebml_master(pb, chapterdisplay);
1094  }
1095  end_ebml_master(pb, chapteratom);
1096  }
1097  end_ebml_master(pb, editionentry);
1098  end_ebml_master(pb, chapters);
1099 
1100  mkv->wrote_chapters = 1;
1101  return 0;
1102 }
1103 
1105 {
1106  uint8_t *key = av_strdup(t->key);
1107  uint8_t *p = key;
1108  const uint8_t *lang = NULL;
1109  ebml_master tag;
1110 
1111  if (!key)
1112  return AVERROR(ENOMEM);
1113 
1114  if ((p = strrchr(p, '-')) &&
1115  (lang = av_convert_lang_to(p + 1, AV_LANG_ISO639_2_BIBL)))
1116  *p = 0;
1117 
1118  p = key;
1119  while (*p) {
1120  if (*p == ' ')
1121  *p = '_';
1122  else if (*p >= 'a' && *p <= 'z')
1123  *p -= 'a' - 'A';
1124  p++;
1125  }
1126 
1129  if (lang)
1132  end_ebml_master(pb, tag);
1133 
1134  av_freep(&key);
1135  return 0;
1136 }
1137 
1138 static int mkv_write_tag(AVFormatContext *s, AVDictionary *m, unsigned int elementid,
1139  unsigned int uid, ebml_master *tags)
1140 {
1141  MatroskaMuxContext *mkv = s->priv_data;
1142  ebml_master tag, targets;
1143  AVDictionaryEntry *t = NULL;
1144  int ret;
1145 
1146  if (!tags->pos) {
1148  if (ret < 0) return ret;
1149 
1150  *tags = start_ebml_master(s->pb, MATROSKA_ID_TAGS, 0);
1151  }
1152 
1153  tag = start_ebml_master(s->pb, MATROSKA_ID_TAG, 0);
1154  targets = start_ebml_master(s->pb, MATROSKA_ID_TAGTARGETS, 0);
1155  if (elementid)
1156  put_ebml_uint(s->pb, elementid, uid);
1157  end_ebml_master(s->pb, targets);
1158 
1159  while ((t = av_dict_get(m, "", t, AV_DICT_IGNORE_SUFFIX))) {
1160  if (av_strcasecmp(t->key, "title") &&
1161  av_strcasecmp(t->key, "stereo_mode") &&
1162  av_strcasecmp(t->key, "encoding_tool")) {
1163  ret = mkv_write_simpletag(s->pb, t);
1164  if (ret < 0)
1165  return ret;
1166  }
1167  }
1168 
1169  end_ebml_master(s->pb, tag);
1170  return 0;
1171 }
1172 
1174 {
1175  AVDictionaryEntry *t = NULL;
1176 
1177  while ((t = av_dict_get(m, "", t, AV_DICT_IGNORE_SUFFIX)))
1178  if (av_strcasecmp(t->key, "title") && av_strcasecmp(t->key, "stereo_mode"))
1179  return 1;
1180 
1181  return 0;
1182 }
1183 
1185 {
1186  MatroskaMuxContext *mkv = s->priv_data;
1187  ebml_master tags = {0};
1188  int i, ret;
1189 
1191 
1192  if (mkv_check_tag(s->metadata)) {
1193  ret = mkv_write_tag(s, s->metadata, 0, 0, &tags);
1194  if (ret < 0) return ret;
1195  }
1196 
1197  for (i = 0; i < s->nb_streams; i++) {
1198  AVStream *st = s->streams[i];
1199 
1200  if (!mkv_check_tag(st->metadata))
1201  continue;
1202 
1203  ret = mkv_write_tag(s, st->metadata, MATROSKA_ID_TAGTARGETS_TRACKUID, i + 1, &tags);
1204  if (ret < 0) return ret;
1205  }
1206 
1207  for (i = 0; i < s->nb_chapters; i++) {
1208  AVChapter *ch = s->chapters[i];
1209 
1210  if (!mkv_check_tag(ch->metadata))
1211  continue;
1212 
1214  if (ret < 0) return ret;
1215  }
1216 
1217  if (tags.pos)
1218  end_ebml_master(s->pb, tags);
1219  return 0;
1220 }
1221 
1223 {
1224  MatroskaMuxContext *mkv = s->priv_data;
1225  AVIOContext *pb = s->pb;
1226  ebml_master attachments;
1227  AVLFG c;
1228  int i, ret;
1229 
1230  if (!mkv->have_attachments)
1231  return 0;
1232 
1234 
1236  if (ret < 0) return ret;
1237 
1238  attachments = start_ebml_master(pb, MATROSKA_ID_ATTACHMENTS, 0);
1239 
1240  for (i = 0; i < s->nb_streams; i++) {
1241  AVStream *st = s->streams[i];
1242  ebml_master attached_file;
1243  AVDictionaryEntry *t;
1244  const char *mimetype = NULL;
1245  uint64_t fileuid;
1246 
1248  continue;
1249 
1250  attached_file = start_ebml_master(pb, MATROSKA_ID_ATTACHEDFILE, 0);
1251 
1252  if (t = av_dict_get(st->metadata, "title", NULL, 0))
1254  if (!(t = av_dict_get(st->metadata, "filename", NULL, 0))) {
1255  av_log(s, AV_LOG_ERROR, "Attachment stream %d has no filename tag.\n", i);
1256  return AVERROR(EINVAL);
1257  }
1259  if (t = av_dict_get(st->metadata, "mimetype", NULL, 0))
1260  mimetype = t->value;
1261  else if (st->codec->codec_id != AV_CODEC_ID_NONE ) {
1262  int i;
1263  for (i = 0; ff_mkv_mime_tags[i].id != AV_CODEC_ID_NONE; i++)
1264  if (ff_mkv_mime_tags[i].id == st->codec->codec_id) {
1265  mimetype = ff_mkv_mime_tags[i].str;
1266  break;
1267  }
1268  }
1269  if (!mimetype) {
1270  av_log(s, AV_LOG_ERROR, "Attachment stream %d has no mimetype tag and "
1271  "it cannot be deduced from the codec id.\n", i);
1272  return AVERROR(EINVAL);
1273  }
1274 
1275  if (s->flags & AVFMT_FLAG_BITEXACT) {
1276  struct AVSHA *sha = av_sha_alloc();
1277  uint8_t digest[20];
1278  if (!sha)
1279  return AVERROR(ENOMEM);
1280  av_sha_init(sha, 160);
1282  av_sha_final(sha, digest);
1283  av_free(sha);
1284  fileuid = AV_RL64(digest);
1285  } else {
1286  fileuid = av_lfg_get(&c);
1287  }
1288  av_log(s, AV_LOG_VERBOSE, "Using %.16"PRIx64" for attachment %d\n",
1289  fileuid, i);
1290 
1293  put_ebml_uint(pb, MATROSKA_ID_FILEUID, fileuid);
1294  end_ebml_master(pb, attached_file);
1295  }
1296  end_ebml_master(pb, attachments);
1297 
1298  return 0;
1299 }
1300 
1302 {
1303  MatroskaMuxContext *mkv = s->priv_data;
1304  AVIOContext *pb = s->pb;
1305  ebml_master ebml_header, segment_info;
1307  int ret, i, version = 2;
1308 
1309  if (!strcmp(s->oformat->name, "webm"))
1310  mkv->mode = MODE_WEBM;
1311  else
1312  mkv->mode = MODE_MATROSKAv2;
1313 
1314  if (s->avoid_negative_ts < 0)
1315  s->avoid_negative_ts = 1;
1316 
1317  if (mkv->mode != MODE_WEBM ||
1318  av_dict_get(s->metadata, "stereo_mode", NULL, 0) ||
1319  av_dict_get(s->metadata, "alpha_mode", NULL, 0))
1320  version = 4;
1321 
1322  for (i = 0; i < s->nb_streams; i++) {
1323  if (s->streams[i]->codec->codec_id == AV_CODEC_ID_ATRAC3 ||
1324  s->streams[i]->codec->codec_id == AV_CODEC_ID_COOK ||
1326  s->streams[i]->codec->codec_id == AV_CODEC_ID_SIPR ||
1327  s->streams[i]->codec->codec_id == AV_CODEC_ID_RV10 ||
1328  s->streams[i]->codec->codec_id == AV_CODEC_ID_RV20) {
1329  av_log(s, AV_LOG_ERROR,
1330  "The Matroska muxer does not yet support muxing %s\n",
1332  return AVERROR_PATCHWELCOME;
1333  }
1334  if (s->streams[i]->codec->codec_id == AV_CODEC_ID_OPUS ||
1335  av_dict_get(s->streams[i]->metadata, "stereo_mode", NULL, 0) ||
1336  av_dict_get(s->streams[i]->metadata, "alpha_mode", NULL, 0))
1337  version = 4;
1338  }
1339 
1340  mkv->tracks = av_mallocz_array(s->nb_streams, sizeof(*mkv->tracks));
1341  if (!mkv->tracks)
1342  return AVERROR(ENOMEM);
1343 
1344  ebml_header = start_ebml_master(pb, EBML_ID_HEADER, 0);
1350  put_ebml_uint (pb, EBML_ID_DOCTYPEVERSION , version);
1352  end_ebml_master(pb, ebml_header);
1353 
1355  mkv->segment_offset = avio_tell(pb);
1356 
1357  // we write 2 seek heads - one at the end of the file to point to each
1358  // cluster, and one at the beginning to point to all other level one
1359  // elements (including the seek head at the end of the file), which
1360  // isn't more than 10 elements if we only write one of each other
1361  // currently defined level 1 element
1362  mkv->main_seekhead = mkv_start_seekhead(pb, mkv->segment_offset, 10);
1363  if (!mkv->main_seekhead)
1364  return AVERROR(ENOMEM);
1365 
1367  if (ret < 0) return ret;
1368 
1369  segment_info = start_ebml_master(pb, MATROSKA_ID_INFO, 0);
1371  if ((tag = av_dict_get(s->metadata, "title", NULL, 0)))
1373  if (!(s->flags & AVFMT_FLAG_BITEXACT)) {
1374  uint32_t segment_uid[4];
1375  AVLFG lfg;
1376 
1378 
1379  for (i = 0; i < 4; i++)
1380  segment_uid[i] = av_lfg_get(&lfg);
1381 
1383  if ((tag = av_dict_get(s->metadata, "encoding_tool", NULL, 0)))
1385  else
1387  put_ebml_binary(pb, MATROSKA_ID_SEGMENTUID, segment_uid, 16);
1388  } else {
1389  const char *ident = "Lavf";
1392  }
1393 
1394  if (tag = av_dict_get(s->metadata, "creation_time", NULL, 0)) {
1395  // Adjust time so it's relative to 2001-01-01 and convert to nanoseconds.
1396  int64_t date_utc = (ff_iso8601_to_unix_time(tag->value) - 978307200) * 1000000000;
1397  uint8_t date_utc_buf[8];
1398  AV_WB64(date_utc_buf, date_utc);
1399  put_ebml_binary(pb, MATROSKA_ID_DATEUTC, date_utc_buf, 8);
1400  }
1401 
1402  // reserve space for the duration
1403  mkv->duration = 0;
1404  mkv->duration_offset = avio_tell(pb);
1405  put_ebml_void(pb, 11); // assumes double-precision float to be written
1406  end_ebml_master(pb, segment_info);
1407 
1408  ret = mkv_write_tracks(s);
1409  if (ret < 0)
1410  return ret;
1411 
1412  for (i = 0; i < s->nb_chapters; i++)
1413  mkv->chapter_id_offset = FFMAX(mkv->chapter_id_offset, 1LL - s->chapters[i]->id);
1414 
1415  if (mkv->mode != MODE_WEBM) {
1416  ret = mkv_write_chapters(s);
1417  if (ret < 0)
1418  return ret;
1419 
1420  ret = mkv_write_tags(s);
1421  if (ret < 0)
1422  return ret;
1423 
1424  ret = mkv_write_attachments(s);
1425  if (ret < 0)
1426  return ret;
1427  }
1428 
1429  if (!s->pb->seekable)
1431 
1432  mkv->cues = mkv_start_cues(mkv->segment_offset);
1433  if (!mkv->cues)
1434  return AVERROR(ENOMEM);
1435 
1436  if (pb->seekable && mkv->reserve_cues_space) {
1437  mkv->cues_pos = avio_tell(pb);
1439  }
1440 
1442  mkv->cur_audio_pkt.size = 0;
1443  mkv->cluster_pos = -1;
1444 
1445  avio_flush(pb);
1446 
1447  // start a new cluster every 5 MB or 5 sec, or 32k / 1 sec for streaming or
1448  // after 4k and on a keyframe
1449  if (pb->seekable) {
1450  if (mkv->cluster_time_limit < 0)
1451  mkv->cluster_time_limit = 5000;
1452  if (mkv->cluster_size_limit < 0)
1453  mkv->cluster_size_limit = 5 * 1024 * 1024;
1454  } else {
1455  if (mkv->cluster_time_limit < 0)
1456  mkv->cluster_time_limit = 1000;
1457  if (mkv->cluster_size_limit < 0)
1458  mkv->cluster_size_limit = 32 * 1024;
1459  }
1460 
1461  return 0;
1462 }
1463 
1464 static int mkv_blockgroup_size(int pkt_size)
1465 {
1466  int size = pkt_size + 4;
1467  size += ebml_num_size(size);
1468  size += 2; // EBML ID for block and block duration
1469  size += 8; // max size of block duration
1470  size += ebml_num_size(size);
1471  size += 1; // blockgroup EBML ID
1472  return size;
1473 }
1474 
1475 static int mkv_strip_wavpack(const uint8_t *src, uint8_t **pdst, int *size)
1476 {
1477  uint8_t *dst;
1478  int srclen = *size;
1479  int offset = 0;
1480  int ret;
1481 
1482  dst = av_malloc(srclen);
1483  if (!dst)
1484  return AVERROR(ENOMEM);
1485 
1486  while (srclen >= WV_HEADER_SIZE) {
1487  WvHeader header;
1488 
1489  ret = ff_wv_parse_header(&header, src);
1490  if (ret < 0)
1491  goto fail;
1492  src += WV_HEADER_SIZE;
1493  srclen -= WV_HEADER_SIZE;
1494 
1495  if (srclen < header.blocksize) {
1496  ret = AVERROR_INVALIDDATA;
1497  goto fail;
1498  }
1499 
1500  if (header.initial) {
1501  AV_WL32(dst + offset, header.samples);
1502  offset += 4;
1503  }
1504  AV_WL32(dst + offset, header.flags);
1505  AV_WL32(dst + offset + 4, header.crc);
1506  offset += 8;
1507 
1508  if (!(header.initial && header.final)) {
1509  AV_WL32(dst + offset, header.blocksize);
1510  offset += 4;
1511  }
1512 
1513  memcpy(dst + offset, src, header.blocksize);
1514  src += header.blocksize;
1515  srclen -= header.blocksize;
1516  offset += header.blocksize;
1517  }
1518 
1519  *pdst = dst;
1520  *size = offset;
1521 
1522  return 0;
1523 fail:
1524  av_freep(&dst);
1525  return ret;
1526 }
1527 
1529  unsigned int blockid, AVPacket *pkt, int flags)
1530 {
1531  MatroskaMuxContext *mkv = s->priv_data;
1532  AVCodecContext *codec = s->streams[pkt->stream_index]->codec;
1533  uint8_t *data = NULL, *side_data = NULL;
1534  int offset = 0, size = pkt->size, side_data_size = 0;
1535  int64_t ts = mkv->tracks[pkt->stream_index].write_dts ? pkt->dts : pkt->pts;
1536  uint64_t additional_id = 0;
1537  int64_t discard_padding = 0;
1538  ebml_master block_group, block_additions, block_more;
1539 
1540  av_log(s, AV_LOG_DEBUG, "Writing block at offset %" PRIu64 ", size %d, "
1541  "pts %" PRId64 ", dts %" PRId64 ", duration %d, flags %d\n",
1542  avio_tell(pb), pkt->size, pkt->pts, pkt->dts, pkt->duration, flags);
1543  if (codec->codec_id == AV_CODEC_ID_H264 && codec->extradata_size > 0 &&
1544  (AV_RB24(codec->extradata) == 1 || AV_RB32(codec->extradata) == 1))
1545  ff_avc_parse_nal_units_buf(pkt->data, &data, &size);
1546  else if (codec->codec_id == AV_CODEC_ID_HEVC && codec->extradata_size > 6 &&
1547  (AV_RB24(codec->extradata) == 1 || AV_RB32(codec->extradata) == 1))
1548  /* extradata is Annex B, assume the bitstream is too and convert it */
1549  ff_hevc_annexb2mp4_buf(pkt->data, &data, &size, 0, NULL);
1550  else if (codec->codec_id == AV_CODEC_ID_WAVPACK) {
1551  int ret = mkv_strip_wavpack(pkt->data, &data, &size);
1552  if (ret < 0) {
1553  av_log(s, AV_LOG_ERROR, "Error stripping a WavPack packet.\n");
1554  return;
1555  }
1556  } else
1557  data = pkt->data;
1558 
1559  if (codec->codec_id == AV_CODEC_ID_PRORES) {
1560  /* Matroska specification requires to remove the first QuickTime atom
1561  */
1562  size -= 8;
1563  offset = 8;
1564  }
1565 
1566  side_data = av_packet_get_side_data(pkt,
1568  &side_data_size);
1569 
1570  if (side_data && side_data_size >= 10) {
1571  discard_padding = av_rescale_q(AV_RL32(side_data + 4),
1572  (AVRational){1, codec->sample_rate},
1573  (AVRational){1, 1000000000});
1574  }
1575 
1576  side_data = av_packet_get_side_data(pkt,
1578  &side_data_size);
1579  if (side_data) {
1580  additional_id = AV_RB64(side_data);
1581  side_data += 8;
1582  side_data_size -= 8;
1583  }
1584 
1585  if ((side_data_size && additional_id == 1) || discard_padding) {
1586  block_group = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP, 0);
1587  blockid = MATROSKA_ID_BLOCK;
1588  }
1589 
1590  put_ebml_id(pb, blockid);
1591  put_ebml_num(pb, size + 4, 0);
1592  // this assumes stream_index is less than 126
1593  avio_w8(pb, 0x80 | (mkv->is_dash ? mkv->dash_track_number : (pkt->stream_index + 1)));
1594  avio_wb16(pb, ts - mkv->cluster_pts);
1595  avio_w8(pb, flags);
1596  avio_write(pb, data + offset, size);
1597  if (data != pkt->data)
1598  av_free(data);
1599 
1600  if (discard_padding) {
1601  put_ebml_sint(pb, MATROSKA_ID_DISCARDPADDING, discard_padding);
1602  }
1603 
1604  if (side_data_size && additional_id == 1) {
1605  block_additions = start_ebml_master(pb, MATROSKA_ID_BLOCKADDITIONS, 0);
1606  block_more = start_ebml_master(pb, MATROSKA_ID_BLOCKMORE, 0);
1609  put_ebml_num(pb, side_data_size, 0);
1610  avio_write(pb, side_data, side_data_size);
1611  end_ebml_master(pb, block_more);
1612  end_ebml_master(pb, block_additions);
1613  }
1614  if ((side_data_size && additional_id == 1) || discard_padding) {
1615  end_ebml_master(pb, block_group);
1616  }
1617 }
1618 
1620 {
1621  MatroskaMuxContext *mkv = s->priv_data;
1622  ebml_master blockgroup;
1623  int id_size, settings_size, size;
1624  uint8_t *id, *settings;
1625  int64_t ts = mkv->tracks[pkt->stream_index].write_dts ? pkt->dts : pkt->pts;
1626  const int flags = 0;
1627 
1628  id_size = 0;
1630  &id_size);
1631 
1632  settings_size = 0;
1634  &settings_size);
1635 
1636  size = id_size + 1 + settings_size + 1 + pkt->size;
1637 
1638  av_log(s, AV_LOG_DEBUG, "Writing block at offset %" PRIu64 ", size %d, "
1639  "pts %" PRId64 ", dts %" PRId64 ", duration %d, flags %d\n",
1640  avio_tell(pb), size, pkt->pts, pkt->dts, pkt->duration, flags);
1641 
1643 
1645  put_ebml_num(pb, size + 4, 0);
1646  avio_w8(pb, 0x80 | (pkt->stream_index + 1)); // this assumes stream_index is less than 126
1647  avio_wb16(pb, ts - mkv->cluster_pts);
1648  avio_w8(pb, flags);
1649  avio_printf(pb, "%.*s\n%.*s\n%.*s", id_size, id, settings_size, settings, pkt->size, pkt->data);
1650 
1652  end_ebml_master(pb, blockgroup);
1653 
1654  return pkt->duration;
1655 }
1656 
1658 {
1659  MatroskaMuxContext *mkv = s->priv_data;
1660  int bufsize;
1661  uint8_t *dyn_buf;
1662 
1663  if (!mkv->dyn_bc)
1664  return;
1665 
1666  bufsize = avio_close_dyn_buf(mkv->dyn_bc, &dyn_buf);
1667  avio_write(s->pb, dyn_buf, bufsize);
1668  av_free(dyn_buf);
1669  mkv->dyn_bc = NULL;
1670 }
1671 
1673 {
1674  MatroskaMuxContext *mkv = s->priv_data;
1675  AVIOContext *pb;
1676 
1677  if (s->pb->seekable) {
1678  pb = s->pb;
1679  } else {
1680  pb = mkv->dyn_bc;
1681  }
1682 
1683  av_log(s, AV_LOG_DEBUG,
1684  "Starting new cluster at offset %" PRIu64 " bytes, "
1685  "pts %" PRIu64 "dts %" PRIu64 "\n",
1686  avio_tell(pb), pkt->pts, pkt->dts);
1687  end_ebml_master(pb, mkv->cluster);
1688  mkv->cluster_pos = -1;
1689  if (mkv->dyn_bc)
1690  mkv_flush_dynbuf(s);
1691  avio_flush(s->pb);
1692 }
1693 
1695 {
1696  MatroskaMuxContext *mkv = s->priv_data;
1697  AVIOContext *pb = s->pb;
1698  AVCodecContext *codec = s->streams[pkt->stream_index]->codec;
1699  int keyframe = !!(pkt->flags & AV_PKT_FLAG_KEY);
1700  int duration = pkt->duration;
1701  int ret;
1702  int64_t ts = mkv->tracks[pkt->stream_index].write_dts ? pkt->dts : pkt->pts;
1703  int64_t relative_packet_pos;
1704  int dash_tracknum = mkv->is_dash ? mkv->dash_track_number : pkt->stream_index + 1;
1705 
1706  if (ts == AV_NOPTS_VALUE) {
1707  av_log(s, AV_LOG_ERROR, "Can't write packet with unknown timestamp\n");
1708  return AVERROR(EINVAL);
1709  }
1710  ts += mkv->tracks[pkt->stream_index].ts_offset;
1711 
1712  if (mkv->cluster_pos != -1) {
1713  int64_t cluster_time = ts - mkv->cluster_pts + mkv->tracks[pkt->stream_index].ts_offset;
1714  if ((int16_t)cluster_time != cluster_time) {
1715  av_log(s, AV_LOG_WARNING, "Starting new cluster due to timestamp\n");
1716  mkv_start_new_cluster(s, pkt);
1717  }
1718  }
1719 
1720  if (!s->pb->seekable) {
1721  if (!mkv->dyn_bc) {
1722  ret = avio_open_dyn_buf(&mkv->dyn_bc);
1723  if (ret < 0) {
1724  av_log(s, AV_LOG_ERROR, "Failed to open dynamic buffer\n");
1725  return ret;
1726  }
1727  }
1728  pb = mkv->dyn_bc;
1729  }
1730 
1731  if (mkv->cluster_pos == -1) {
1732  mkv->cluster_pos = avio_tell(s->pb);
1735  mkv->cluster_pts = FFMAX(0, ts);
1736  }
1737 
1738  relative_packet_pos = avio_tell(s->pb) - mkv->cluster.pos;
1739 
1740  if (codec->codec_type != AVMEDIA_TYPE_SUBTITLE) {
1741  mkv_write_block(s, pb, MATROSKA_ID_SIMPLEBLOCK, pkt, keyframe << 7);
1742  if (codec->codec_type == AVMEDIA_TYPE_VIDEO && keyframe || add_cue) {
1743  ret = mkv_add_cuepoint(mkv->cues, pkt->stream_index, dash_tracknum, ts, mkv->cluster_pos, relative_packet_pos, -1);
1744  if (ret < 0) return ret;
1745  }
1746  } else {
1747  if (codec->codec_id == AV_CODEC_ID_WEBVTT) {
1748  duration = mkv_write_vtt_blocks(s, pb, pkt);
1749  } else {
1751  mkv_blockgroup_size(pkt->size));
1752  /* For backward compatibility, prefer convergence_duration. */
1753  if (pkt->convergence_duration > 0) {
1754  duration = pkt->convergence_duration;
1755  }
1756  mkv_write_block(s, pb, MATROSKA_ID_BLOCK, pkt, 0);
1758  end_ebml_master(pb, blockgroup);
1759  }
1760 
1761  ret = mkv_add_cuepoint(mkv->cues, pkt->stream_index, dash_tracknum, ts,
1762  mkv->cluster_pos, relative_packet_pos, duration);
1763  if (ret < 0)
1764  return ret;
1765  }
1766 
1767  mkv->duration = FFMAX(mkv->duration, ts + duration);
1768  return 0;
1769 }
1770 
1772 {
1773  MatroskaMuxContext *mkv = s->priv_data;
1774  int codec_type = s->streams[pkt->stream_index]->codec->codec_type;
1775  int keyframe = !!(pkt->flags & AV_PKT_FLAG_KEY);
1776  int cluster_size;
1777  int64_t cluster_time;
1778  int ret;
1779  int start_new_cluster;
1780 
1781  if (mkv->tracks[pkt->stream_index].write_dts)
1782  cluster_time = pkt->dts - mkv->cluster_pts;
1783  else
1784  cluster_time = pkt->pts - mkv->cluster_pts;
1785  cluster_time += mkv->tracks[pkt->stream_index].ts_offset;
1786 
1787  // start a new cluster every 5 MB or 5 sec, or 32k / 1 sec for streaming or
1788  // after 4k and on a keyframe
1789  if (s->pb->seekable) {
1790  cluster_size = avio_tell(s->pb) - mkv->cluster_pos;
1791  } else {
1792  cluster_size = avio_tell(mkv->dyn_bc);
1793  }
1794 
1795  if (mkv->is_dash && codec_type == AVMEDIA_TYPE_VIDEO) {
1796  // WebM DASH specification states that the first block of every cluster
1797  // has to be a key frame. So for DASH video, we only create a cluster
1798  // on seeing key frames.
1799  start_new_cluster = keyframe;
1800  } else if (mkv->is_dash && codec_type == AVMEDIA_TYPE_AUDIO &&
1801  (mkv->cluster_pos == -1 ||
1802  cluster_time > mkv->cluster_time_limit)) {
1803  // For DASH audio, we create a Cluster based on cluster_time_limit
1804  start_new_cluster = 1;
1805  } else if (!mkv->is_dash &&
1806  (cluster_size > mkv->cluster_size_limit ||
1807  cluster_time > mkv->cluster_time_limit ||
1808  (codec_type == AVMEDIA_TYPE_VIDEO && keyframe &&
1809  cluster_size > 4 * 1024))) {
1810  start_new_cluster = 1;
1811  } else {
1812  start_new_cluster = 0;
1813  }
1814 
1815  if (mkv->cluster_pos != -1 && start_new_cluster) {
1816  mkv_start_new_cluster(s, pkt);
1817  }
1818 
1819  // check if we have an audio packet cached
1820  if (mkv->cur_audio_pkt.size > 0) {
1821  // for DASH audio, a CuePoint has to be added when there is a new cluster.
1823  mkv->is_dash ? start_new_cluster : 0);
1825  if (ret < 0) {
1826  av_log(s, AV_LOG_ERROR,
1827  "Could not write cached audio packet ret:%d\n", ret);
1828  return ret;
1829  }
1830  }
1831 
1832  // buffer an audio packet to ensure the packet containing the video
1833  // keyframe's timecode is contained in the same cluster for WebM
1834  if (codec_type == AVMEDIA_TYPE_AUDIO) {
1835  mkv->cur_audio_pkt = *pkt;
1836  if (pkt->buf) {
1837  mkv->cur_audio_pkt.buf = av_buffer_ref(pkt->buf);
1838  ret = mkv->cur_audio_pkt.buf ? 0 : AVERROR(ENOMEM);
1839  } else
1840  ret = av_dup_packet(&mkv->cur_audio_pkt);
1841  if (mkv->cur_audio_pkt.side_data_elems > 0) {
1843  }
1844  } else
1845  ret = mkv_write_packet_internal(s, pkt, 0);
1846  return ret;
1847 }
1848 
1850 {
1851  MatroskaMuxContext *mkv = s->priv_data;
1852  AVIOContext *pb;
1853  if (s->pb->seekable)
1854  pb = s->pb;
1855  else
1856  pb = mkv->dyn_bc;
1857  if (!pkt) {
1858  if (mkv->cluster_pos != -1) {
1859  av_log(s, AV_LOG_DEBUG,
1860  "Flushing cluster at offset %" PRIu64 " bytes\n",
1861  avio_tell(pb));
1862  end_ebml_master(pb, mkv->cluster);
1863  mkv->cluster_pos = -1;
1864  if (mkv->dyn_bc)
1865  mkv_flush_dynbuf(s);
1866  avio_flush(s->pb);
1867  }
1868  return 0;
1869  }
1870  return mkv_write_packet(s, pkt);
1871 }
1872 
1874 {
1875  MatroskaMuxContext *mkv = s->priv_data;
1876  AVIOContext *pb = s->pb;
1877  int64_t currentpos, cuespos;
1878  int ret;
1879 
1880  // check if we have an audio packet cached
1881  if (mkv->cur_audio_pkt.size > 0) {
1882  ret = mkv_write_packet_internal(s, &mkv->cur_audio_pkt, 0);
1884  if (ret < 0) {
1885  av_log(s, AV_LOG_ERROR,
1886  "Could not write cached audio packet ret:%d\n", ret);
1887  return ret;
1888  }
1889  }
1890 
1891  if (mkv->dyn_bc) {
1892  end_ebml_master(mkv->dyn_bc, mkv->cluster);
1893  mkv_flush_dynbuf(s);
1894  } else if (mkv->cluster_pos != -1) {
1895  end_ebml_master(pb, mkv->cluster);
1896  }
1897 
1898  if (mkv->mode != MODE_WEBM) {
1899  ret = mkv_write_chapters(s);
1900  if (ret < 0)
1901  return ret;
1902  }
1903 
1904  if (pb->seekable) {
1905  if (mkv->cues->num_entries) {
1906  if (mkv->reserve_cues_space) {
1907  int64_t cues_end;
1908 
1909  currentpos = avio_tell(pb);
1910  avio_seek(pb, mkv->cues_pos, SEEK_SET);
1911 
1912  cuespos = mkv_write_cues(s, mkv->cues, mkv->tracks, s->nb_streams);
1913  cues_end = avio_tell(pb);
1914  if (cues_end > cuespos + mkv->reserve_cues_space) {
1915  av_log(s, AV_LOG_ERROR,
1916  "Insufficient space reserved for cues: %d "
1917  "(needed: %" PRId64 ").\n",
1918  mkv->reserve_cues_space, cues_end - cuespos);
1919  return AVERROR(EINVAL);
1920  }
1921 
1922  if (cues_end < cuespos + mkv->reserve_cues_space)
1924  (cues_end - cuespos));
1925 
1926  avio_seek(pb, currentpos, SEEK_SET);
1927  } else {
1928  cuespos = mkv_write_cues(s, mkv->cues, mkv->tracks, s->nb_streams);
1929  }
1930 
1932  cuespos);
1933  if (ret < 0)
1934  return ret;
1935  }
1936 
1938 
1939  // update the duration
1940  av_log(s, AV_LOG_DEBUG, "end duration = %" PRIu64 "\n", mkv->duration);
1941  currentpos = avio_tell(pb);
1942  avio_seek(pb, mkv->duration_offset, SEEK_SET);
1944 
1945  avio_seek(pb, currentpos, SEEK_SET);
1946  }
1947 
1948  end_ebml_master(pb, mkv->segment);
1949  av_freep(&mkv->tracks);
1950  av_freep(&mkv->cues->entries);
1951  av_freep(&mkv->cues);
1952 
1953  return 0;
1954 }
1955 
1956 static int mkv_query_codec(enum AVCodecID codec_id, int std_compliance)
1957 {
1958  int i;
1959  for (i = 0; ff_mkv_codec_tags[i].id != AV_CODEC_ID_NONE; i++)
1960  if (ff_mkv_codec_tags[i].id == codec_id)
1961  return 1;
1962 
1963  if (std_compliance < FF_COMPLIANCE_NORMAL) {
1964  enum AVMediaType type = avcodec_get_type(codec_id);
1965  // mkv theoretically supports any video/audio through VFW/ACM
1966  if (type == AVMEDIA_TYPE_VIDEO || type == AVMEDIA_TYPE_AUDIO)
1967  return 1;
1968  }
1969 
1970  return 0;
1971 }
1972 
1974  { AV_CODEC_ID_ALAC, 0XFFFFFFFF },
1975  { AV_CODEC_ID_EAC3, 0XFFFFFFFF },
1976  { AV_CODEC_ID_MLP, 0xFFFFFFFF },
1977  { AV_CODEC_ID_OPUS, 0xFFFFFFFF },
1978  { AV_CODEC_ID_PCM_S16BE, 0xFFFFFFFF },
1979  { AV_CODEC_ID_PCM_S24BE, 0xFFFFFFFF },
1980  { AV_CODEC_ID_PCM_S32BE, 0xFFFFFFFF },
1981  { AV_CODEC_ID_QDM2, 0xFFFFFFFF },
1982  { AV_CODEC_ID_RA_144, 0xFFFFFFFF },
1983  { AV_CODEC_ID_RA_288, 0xFFFFFFFF },
1984  { AV_CODEC_ID_COOK, 0xFFFFFFFF },
1985  { AV_CODEC_ID_TRUEHD, 0xFFFFFFFF },
1986  { AV_CODEC_ID_NONE, 0xFFFFFFFF }
1987 };
1988 
1990  { AV_CODEC_ID_RV10, 0xFFFFFFFF },
1991  { AV_CODEC_ID_RV20, 0xFFFFFFFF },
1992  { AV_CODEC_ID_RV30, 0xFFFFFFFF },
1993  { AV_CODEC_ID_RV40, 0xFFFFFFFF },
1994  { AV_CODEC_ID_VP9, 0xFFFFFFFF },
1995  { AV_CODEC_ID_NONE, 0xFFFFFFFF }
1996 };
1997 
1998 #define OFFSET(x) offsetof(MatroskaMuxContext, x)
1999 #define FLAGS AV_OPT_FLAG_ENCODING_PARAM
2000 static const AVOption options[] = {
2001  { "reserve_index_space", "Reserve a given amount of space (in bytes) at the beginning of the file for the index (cues).", OFFSET(reserve_cues_space), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, FLAGS },
2002  { "cluster_size_limit", "Store at most the provided amount of bytes in a cluster. ", OFFSET(cluster_size_limit), AV_OPT_TYPE_INT , { .i64 = -1 }, -1, INT_MAX, FLAGS },
2003  { "cluster_time_limit", "Store at most the provided number of milliseconds in a cluster.", OFFSET(cluster_time_limit), AV_OPT_TYPE_INT64, { .i64 = -1 }, -1, INT64_MAX, FLAGS },
2004  { "dash", "Create a WebM file conforming to WebM DASH specification", OFFSET(is_dash), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, FLAGS },
2005  { "dash_track_number", "Track number for the DASH stream", OFFSET(dash_track_number), AV_OPT_TYPE_INT, { .i64 = 1 }, 0, 127, FLAGS },
2006  { "allow_raw_vfw", "allow RAW VFW mode", OFFSET(allow_raw_vfw), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, FLAGS },
2007  { NULL },
2008 };
2009 
2010 #if CONFIG_MATROSKA_MUXER
2011 static const AVClass matroska_class = {
2012  .class_name = "matroska muxer",
2013  .item_name = av_default_item_name,
2014  .option = options,
2015  .version = LIBAVUTIL_VERSION_INT,
2016 };
2017 
2018 AVOutputFormat ff_matroska_muxer = {
2019  .name = "matroska",
2020  .long_name = NULL_IF_CONFIG_SMALL("Matroska"),
2021  .mime_type = "video/x-matroska",
2022  .extensions = "mkv",
2023  .priv_data_size = sizeof(MatroskaMuxContext),
2024  .audio_codec = CONFIG_LIBVORBIS_ENCODER ?
2026  .video_codec = CONFIG_LIBX264_ENCODER ?
2033  .codec_tag = (const AVCodecTag* const []){
2036  },
2037  .subtitle_codec = AV_CODEC_ID_ASS,
2038  .query_codec = mkv_query_codec,
2039  .priv_class = &matroska_class,
2040 };
2041 #endif
2042 
2043 #if CONFIG_WEBM_MUXER
2044 static const AVClass webm_class = {
2045  .class_name = "webm muxer",
2046  .item_name = av_default_item_name,
2047  .option = options,
2048  .version = LIBAVUTIL_VERSION_INT,
2049 };
2050 
2051 AVOutputFormat ff_webm_muxer = {
2052  .name = "webm",
2053  .long_name = NULL_IF_CONFIG_SMALL("WebM"),
2054  .mime_type = "video/webm",
2055  .extensions = "webm",
2056  .priv_data_size = sizeof(MatroskaMuxContext),
2057  .audio_codec = AV_CODEC_ID_VORBIS,
2058  .video_codec = AV_CODEC_ID_VP8,
2059  .subtitle_codec = AV_CODEC_ID_WEBVTT,
2065  .priv_class = &webm_class,
2066 };
2067 #endif
2068 
2069 #if CONFIG_MATROSKA_AUDIO_MUXER
2070 static const AVClass mka_class = {
2071  .class_name = "matroska audio muxer",
2072  .item_name = av_default_item_name,
2073  .option = options,
2074  .version = LIBAVUTIL_VERSION_INT,
2075 };
2076 AVOutputFormat ff_matroska_audio_muxer = {
2077  .name = "matroska",
2078  .long_name = NULL_IF_CONFIG_SMALL("Matroska Audio"),
2079  .mime_type = "audio/x-matroska",
2080  .extensions = "mka",
2081  .priv_data_size = sizeof(MatroskaMuxContext),
2082  .audio_codec = CONFIG_LIBVORBIS_ENCODER ?
2083  AV_CODEC_ID_VORBIS : AV_CODEC_ID_AC3,
2084  .video_codec = AV_CODEC_ID_NONE,
2090  .codec_tag = (const AVCodecTag* const []){
2092  },
2093  .priv_class = &mka_class,
2094 };
2095 #endif