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