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)
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)
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)
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)
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  int ctp_nb = 0;
449 
450  // Calculate the number of entries, so we know the element size
451  for (j = 0; j < num_tracks; j++)
452  tracks[j].has_cue = 0;
453  for (j = 0; j < cues->num_entries - i && entry[j].pts == pts; j++) {
454  int tracknum = entry[j].stream_idx;
455  av_assert0(tracknum>=0 && tracknum<num_tracks);
456  if (tracks[tracknum].has_cue && s->streams[tracknum]->codec->codec_type != AVMEDIA_TYPE_SUBTITLE)
457  continue;
458  tracks[tracknum].has_cue = 1;
459  ctp_nb ++;
460  }
461 
464 
465  // put all the entries from different tracks that have the exact same
466  // timestamp into the same CuePoint
467  for (j = 0; j < num_tracks; j++)
468  tracks[j].has_cue = 0;
469  for (j = 0; j < cues->num_entries - i && entry[j].pts == pts; j++) {
470  int tracknum = entry[j].stream_idx;
471  av_assert0(tracknum>=0 && tracknum<num_tracks);
472  if (tracks[tracknum].has_cue && s->streams[tracknum]->codec->codec_type != AVMEDIA_TYPE_SUBTITLE)
473  continue;
474  tracks[tracknum].has_cue = 1;
476  put_ebml_uint(pb, MATROSKA_ID_CUETRACK , entry[j].tracknum );
477  put_ebml_uint(pb, MATROSKA_ID_CUECLUSTERPOSITION , entry[j].cluster_pos);
478  put_ebml_uint(pb, MATROSKA_ID_CUERELATIVEPOSITION, entry[j].relative_pos);
479  if (entry[j].duration != -1)
481  end_ebml_master(pb, track_positions);
482  }
483  i += j - 1;
484  end_ebml_master(pb, cuepoint);
485  }
486  end_ebml_master(pb, cues_element);
487 
488  return currentpos;
489 }
490 
492 {
493  uint8_t *header_start[3];
494  int header_len[3];
495  int first_header_size;
496  int j;
497 
498  if (codec->codec_id == AV_CODEC_ID_VORBIS)
499  first_header_size = 30;
500  else
501  first_header_size = 42;
502 
504  first_header_size, header_start, header_len) < 0) {
505  av_log(s, AV_LOG_ERROR, "Extradata corrupt.\n");
506  return -1;
507  }
508 
509  avio_w8(pb, 2); // number packets - 1
510  for (j = 0; j < 2; j++) {
511  put_xiph_size(pb, header_len[j]);
512  }
513  for (j = 0; j < 3; j++)
514  avio_write(pb, header_start[j], header_len[j]);
515 
516  return 0;
517 }
518 
520 {
521  if (codec->extradata && codec->extradata_size == 2)
522  avio_write(pb, codec->extradata, 2);
523  else
524  avio_wl16(pb, 0x403); // fallback to the version mentioned in matroska specs
525  return 0;
526 }
527 
529  AVIOContext *pb, AVCodecContext *codec)
530 {
531  int write_comment = (codec->channel_layout &&
532  !(codec->channel_layout & ~0x3ffffULL) &&
534  int ret = ff_flac_write_header(pb, codec->extradata, codec->extradata_size,
535  !write_comment);
536 
537  if (ret < 0)
538  return ret;
539 
540  if (write_comment) {
541  const char *vendor = (s->flags & AVFMT_FLAG_BITEXACT) ?
542  "Lavf" : LIBAVFORMAT_IDENT;
543  AVDictionary *dict = NULL;
544  uint8_t buf[32], *data, *p;
545  int len;
546 
547  snprintf(buf, sizeof(buf), "0x%"PRIx64, codec->channel_layout);
548  av_dict_set(&dict, "WAVEFORMATEXTENSIBLE_CHANNEL_MASK", buf, 0);
549 
550  len = ff_vorbiscomment_length(dict, vendor);
551  data = av_malloc(len + 4);
552  if (!data) {
553  av_dict_free(&dict);
554  return AVERROR(ENOMEM);
555  }
556 
557  data[0] = 0x84;
558  AV_WB24(data + 1, len);
559 
560  p = data + 4;
561  ff_vorbiscomment_write(&p, &dict, vendor);
562 
563  avio_write(pb, data, len + 4);
564 
565  av_freep(&data);
566  av_dict_free(&dict);
567  }
568 
569  return 0;
570 }
571 
573  int *sample_rate, int *output_sample_rate)
574 {
575  MPEG4AudioConfig mp4ac;
576 
577  if (avpriv_mpeg4audio_get_config(&mp4ac, codec->extradata,
578  codec->extradata_size * 8, 1) < 0) {
580  "Error parsing AAC extradata, unable to determine samplerate.\n");
581  return;
582  }
583 
584  *sample_rate = mp4ac.sample_rate;
585  *output_sample_rate = mp4ac.ext_sample_rate;
586 }
587 
589  AVCodecContext *codec,
590  AVIOContext *dyn_cp)
591 {
592  switch (codec->codec_id) {
593  case AV_CODEC_ID_VORBIS:
594  case AV_CODEC_ID_THEORA:
595  return put_xiph_codecpriv(s, dyn_cp, codec);
596  case AV_CODEC_ID_FLAC:
597  return put_flac_codecpriv(s, dyn_cp, codec);
598  case AV_CODEC_ID_WAVPACK:
599  return put_wv_codecpriv(dyn_cp, codec);
600  case AV_CODEC_ID_H264:
601  return ff_isom_write_avcc(dyn_cp, codec->extradata,
602  codec->extradata_size);
603  case AV_CODEC_ID_HEVC:
604  return ff_isom_write_hvcc(dyn_cp, codec->extradata,
605  codec->extradata_size, 0);
606  case AV_CODEC_ID_ALAC:
607  if (codec->extradata_size < 36) {
608  av_log(s, AV_LOG_ERROR,
609  "Invalid extradata found, ALAC expects a 36-byte "
610  "QuickTime atom.");
611  return AVERROR_INVALIDDATA;
612  } else
613  avio_write(dyn_cp, codec->extradata + 12,
614  codec->extradata_size - 12);
615  break;
616  default:
617  if (codec->codec_id == AV_CODEC_ID_PRORES &&
619  avio_wl32(dyn_cp, codec->codec_tag);
620  } else if (codec->extradata_size && codec->codec_id != AV_CODEC_ID_TTA)
621  avio_write(dyn_cp, codec->extradata, codec->extradata_size);
622  }
623 
624  return 0;
625 }
626 
628  AVCodecContext *codec, int native_id,
629  int qt_id)
630 {
631  AVIOContext *dyn_cp;
632  uint8_t *codecpriv;
633  int ret, codecpriv_size;
634 
635  ret = avio_open_dyn_buf(&dyn_cp);
636  if (ret < 0)
637  return ret;
638 
639  if (native_id) {
640  ret = mkv_write_native_codecprivate(s, codec, dyn_cp);
641  } else if (codec->codec_type == AVMEDIA_TYPE_VIDEO) {
642  if (qt_id) {
643  if (!codec->codec_tag)
645  codec->codec_id);
646  if (codec->extradata_size) {
649  ) {
650  int i;
651  avio_wb32(dyn_cp, 0x5a + codec->extradata_size);
652  avio_wl32(dyn_cp, codec->codec_tag);
653  for(i = 0; i < 0x5a - 8; i++)
654  avio_w8(dyn_cp, 0);
655  }
656  avio_write(dyn_cp, codec->extradata, codec->extradata_size);
657  }
658  } else {
660  av_log(s, AV_LOG_WARNING, "codec %s is not supported by this format\n",
661  avcodec_get_name(codec->codec_id));
662 
663  if (!codec->codec_tag)
665  codec->codec_id);
666  if (!codec->codec_tag) {
667  av_log(s, AV_LOG_ERROR, "No bmp codec tag found for codec %s\n",
668  avcodec_get_name(codec->codec_id));
669  ret = AVERROR(EINVAL);
670  }
671 
672  ff_put_bmp_header(dyn_cp, codec, ff_codec_bmp_tags, 0, 0);
673  }
674  } else if (codec->codec_type == AVMEDIA_TYPE_AUDIO) {
675  unsigned int tag;
677  if (!tag) {
678  av_log(s, AV_LOG_ERROR, "No wav codec tag found for codec %s\n",
679  avcodec_get_name(codec->codec_id));
680  ret = AVERROR(EINVAL);
681  }
682  if (!codec->codec_tag)
683  codec->codec_tag = tag;
684 
686  }
687 
688  codecpriv_size = avio_close_dyn_buf(dyn_cp, &codecpriv);
689  if (codecpriv_size)
691  codecpriv_size);
692  av_free(codecpriv);
693  return ret;
694 }
695 
696 static int mkv_write_stereo_mode(AVFormatContext *s, AVIOContext *pb, int st_mode,
697  int mode)
698 {
699  if ((mode == MODE_WEBM && st_mode > 3 && st_mode != 11)
700  || st_mode >= MATROSKA_VIDEO_STEREO_MODE_COUNT) {
701  av_log(s, AV_LOG_ERROR,
702  "The specified stereo mode is not valid.\n");
703  return AVERROR(EINVAL);
704  } else
706 
707  return 0;
708 }
709 
711  int i, AVIOContext *pb, int default_stream_exists)
712 {
713  AVStream *st = s->streams[i];
714  AVCodecContext *codec = st->codec;
715  ebml_master subinfo, track;
716  int native_id = 0;
717  int qt_id = 0;
718  int bit_depth = av_get_bits_per_sample(codec->codec_id);
719  int sample_rate = codec->sample_rate;
720  int output_sample_rate = 0;
721  int display_width_div = 1;
722  int display_height_div = 1;
723  int j, ret;
725 
726  // ms precision is the de-facto standard timescale for mkv files
727  avpriv_set_pts_info(st, 64, 1, 1000);
728 
729  if (codec->codec_type == AVMEDIA_TYPE_ATTACHMENT) {
730  mkv->have_attachments = 1;
731  return 0;
732  }
733 
734  if (!bit_depth && codec->codec_id != AV_CODEC_ID_ADPCM_G726)
735  bit_depth = av_get_bytes_per_sample(codec->sample_fmt) << 3;
736  if (!bit_depth)
737  bit_depth = codec->bits_per_coded_sample;
738 
739  if (codec->codec_id == AV_CODEC_ID_AAC)
740  get_aac_sample_rates(s, codec, &sample_rate, &output_sample_rate);
741 
744  mkv->is_dash ? mkv->dash_track_number : i + 1);
746  mkv->is_dash ? mkv->dash_track_number : i + 1);
747  put_ebml_uint (pb, MATROSKA_ID_TRACKFLAGLACING , 0); // no lacing (yet)
748 
749  if ((tag = av_dict_get(st->metadata, "title", NULL, 0)))
751  tag = av_dict_get(st->metadata, "language", NULL, 0);
752  if (mkv->mode != MODE_WEBM || codec->codec_id != AV_CODEC_ID_WEBVTT) {
753  put_ebml_string(pb, MATROSKA_ID_TRACKLANGUAGE, tag && tag->value ? tag->value:"und");
754  } else if (tag && tag->value) {
756  }
757 
758  // The default value for TRACKFLAGDEFAULT is 1, so add element
759  // if we need to clear it.
760  if (default_stream_exists && !(st->disposition & AV_DISPOSITION_DEFAULT))
762 
765 
766  if (mkv->mode == MODE_WEBM && codec->codec_id == AV_CODEC_ID_WEBVTT) {
767  const char *codec_id;
769  codec_id = "D_WEBVTT/CAPTIONS";
770  native_id = MATROSKA_TRACK_TYPE_SUBTITLE;
771  } else if (st->disposition & AV_DISPOSITION_DESCRIPTIONS) {
772  codec_id = "D_WEBVTT/DESCRIPTIONS";
773  native_id = MATROSKA_TRACK_TYPE_METADATA;
774  } else if (st->disposition & AV_DISPOSITION_METADATA) {
775  codec_id = "D_WEBVTT/METADATA";
776  native_id = MATROSKA_TRACK_TYPE_METADATA;
777  } else {
778  codec_id = "D_WEBVTT/SUBTITLES";
779  native_id = MATROSKA_TRACK_TYPE_SUBTITLE;
780  }
781  put_ebml_string(pb, MATROSKA_ID_CODECID, codec_id);
782  } else {
783  // look for a codec ID string specific to mkv to use,
784  // if none are found, use AVI codes
785  for (j = 0; ff_mkv_codec_tags[j].id != AV_CODEC_ID_NONE; j++) {
786  if (ff_mkv_codec_tags[j].id == codec->codec_id) {
788  native_id = 1;
789  break;
790  }
791  }
792  }
793 
794  if (codec->codec_type == AVMEDIA_TYPE_AUDIO && codec->delay && codec->codec_id == AV_CODEC_ID_OPUS) {
795 // mkv->tracks[i].ts_offset = av_rescale_q(codec->delay,
796 // (AVRational){ 1, codec->sample_rate },
797 // st->time_base);
798 
800  av_rescale_q(codec->delay, (AVRational){ 1, codec->sample_rate },
801  (AVRational){ 1, 1000000000 }));
802  }
803  if (codec->codec_id == AV_CODEC_ID_OPUS) {
805  }
806 
807  if (mkv->mode == MODE_WEBM && !(codec->codec_id == AV_CODEC_ID_VP8 ||
808  codec->codec_id == AV_CODEC_ID_VP9 ||
809  codec->codec_id == AV_CODEC_ID_OPUS ||
810  codec->codec_id == AV_CODEC_ID_VORBIS ||
811  codec->codec_id == AV_CODEC_ID_WEBVTT)) {
813  "Only VP8 or VP9 video and Vorbis or Opus audio and WebVTT subtitles are supported for WebM.\n");
814  return AVERROR(EINVAL);
815  }
816 
817  switch (codec->codec_type) {
818  case AVMEDIA_TYPE_VIDEO:
820 
821  if( st->avg_frame_rate.num > 0 && st->avg_frame_rate.den > 0
822  && 1.0/av_q2d(st->avg_frame_rate) > av_q2d(codec->time_base))
823  put_ebml_uint(pb, MATROSKA_ID_TRACKDEFAULTDURATION, 1E9 / av_q2d(st->avg_frame_rate));
824  else
825  put_ebml_uint(pb, MATROSKA_ID_TRACKDEFAULTDURATION, av_q2d(codec->time_base)*1E9);
826 
827  if (!native_id &&
828  ff_codec_get_tag(ff_codec_movvideo_tags, codec->codec_id) &&
829  (!ff_codec_get_tag(ff_codec_bmp_tags, codec->codec_id) ||
830  codec->codec_id == AV_CODEC_ID_SVQ1 ||
831  codec->codec_id == AV_CODEC_ID_SVQ3 ||
832  codec->codec_id == AV_CODEC_ID_CINEPAK))
833  qt_id = 1;
834 
835  if (qt_id)
836  put_ebml_string(pb, MATROSKA_ID_CODECID, "V_QUICKTIME");
837  else if (!native_id) {
838  // if there is no mkv-specific codec ID, use VFW mode
839  put_ebml_string(pb, MATROSKA_ID_CODECID, "V_MS/VFW/FOURCC");
840  mkv->tracks[i].write_dts = 1;
841  }
842 
843  subinfo = start_ebml_master(pb, MATROSKA_ID_TRACKVIDEO, 0);
844  // XXX: interlace flag?
845  put_ebml_uint (pb, MATROSKA_ID_VIDEOPIXELWIDTH , codec->width);
846  put_ebml_uint (pb, MATROSKA_ID_VIDEOPIXELHEIGHT, codec->height);
847 
848  if ((tag = av_dict_get(st->metadata, "stereo_mode", NULL, 0)) ||
849  (tag = av_dict_get( s->metadata, "stereo_mode", NULL, 0))) {
850  int st_mode = MATROSKA_VIDEO_STEREO_MODE_COUNT;
851 
852  for (j=0; j<MATROSKA_VIDEO_STEREO_MODE_COUNT; j++)
853  if (!strcmp(tag->value, ff_matroska_video_stereo_mode[j])){
854  st_mode = j;
855  break;
856  }
857 
858  if (mkv_write_stereo_mode(s, pb, st_mode, mkv->mode) < 0)
859  return AVERROR(EINVAL);
860 
861  switch (st_mode) {
862  case 1:
863  case 8:
864  case 9:
865  case 11:
866  display_width_div = 2;
867  break;
868  case 2:
869  case 3:
870  case 6:
871  case 7:
872  display_height_div = 2;
873  break;
874  }
875  }
876 
877  if ((tag = av_dict_get(st->metadata, "alpha_mode", NULL, 0)) ||
878  (tag = av_dict_get( s->metadata, "alpha_mode", NULL, 0)) ||
879  (codec->pix_fmt == AV_PIX_FMT_YUVA420P)) {
881  }
882 
883  if (st->sample_aspect_ratio.num) {
884  int64_t d_width = av_rescale(codec->width, st->sample_aspect_ratio.num, st->sample_aspect_ratio.den);
885  if (d_width > INT_MAX) {
886  av_log(s, AV_LOG_ERROR, "Overflow in display width\n");
887  return AVERROR(EINVAL);
888  }
889  put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYWIDTH , d_width / display_width_div);
890  put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYHEIGHT, codec->height / display_height_div);
891  } else if (display_width_div != 1 || display_height_div != 1) {
892  put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYWIDTH , codec->width / display_width_div);
893  put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYHEIGHT, codec->height / display_height_div);
894  }
895 
896  if (codec->codec_id == AV_CODEC_ID_RAWVIDEO) {
897  uint32_t color_space = av_le2ne32(codec->codec_tag);
898  put_ebml_binary(pb, MATROSKA_ID_VIDEOCOLORSPACE, &color_space, sizeof(color_space));
899  }
900  end_ebml_master(pb, subinfo);
901  break;
902 
903  case AVMEDIA_TYPE_AUDIO:
905 
906  if (!native_id)
907  // no mkv-specific ID, use ACM mode
908  put_ebml_string(pb, MATROSKA_ID_CODECID, "A_MS/ACM");
909 
910  subinfo = start_ebml_master(pb, MATROSKA_ID_TRACKAUDIO, 0);
911  put_ebml_uint (pb, MATROSKA_ID_AUDIOCHANNELS , codec->channels);
913  if (output_sample_rate)
914  put_ebml_float(pb, MATROSKA_ID_AUDIOOUTSAMPLINGFREQ, output_sample_rate);
915  if (bit_depth)
917  end_ebml_master(pb, subinfo);
918  break;
919 
921  if (!native_id) {
922  av_log(s, AV_LOG_ERROR, "Subtitle codec %d is not supported.\n", codec->codec_id);
923  return AVERROR(ENOSYS);
924  }
925 
926  if (mkv->mode != MODE_WEBM || codec->codec_id != AV_CODEC_ID_WEBVTT)
927  native_id = MATROSKA_TRACK_TYPE_SUBTITLE;
928 
929  put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, native_id);
930  break;
931  default:
932  av_log(s, AV_LOG_ERROR, "Only audio, video, and subtitles are supported for Matroska.\n");
933  return AVERROR(EINVAL);
934  }
935 
936  if (mkv->mode != MODE_WEBM || codec->codec_id != AV_CODEC_ID_WEBVTT) {
937  ret = mkv_write_codecprivate(s, pb, codec, native_id, qt_id);
938  if (ret < 0)
939  return ret;
940  }
941 
942  end_ebml_master(pb, track);
943 
944  return 0;
945 }
946 
948 {
949  MatroskaMuxContext *mkv = s->priv_data;
950  AVIOContext *pb = s->pb;
951  ebml_master tracks;
952  int i, ret, default_stream_exists = 0;
953 
955  if (ret < 0)
956  return ret;
957 
958  tracks = start_ebml_master(pb, MATROSKA_ID_TRACKS, 0);
959  for (i = 0; i < s->nb_streams; i++) {
960  AVStream *st = s->streams[i];
961  default_stream_exists |= st->disposition & AV_DISPOSITION_DEFAULT;
962  }
963  for (i = 0; i < s->nb_streams; i++) {
964  ret = mkv_write_track(s, mkv, i, pb, default_stream_exists);
965  if (ret < 0)
966  return ret;
967  }
968  end_ebml_master(pb, tracks);
969  return 0;
970 }
971 
973 {
974  MatroskaMuxContext *mkv = s->priv_data;
975  AVIOContext *pb = s->pb;
976  ebml_master chapters, editionentry;
977  AVRational scale = {1, 1E9};
978  int i, ret;
979 
980  if (!s->nb_chapters || mkv->wrote_chapters)
981  return 0;
982 
984  if (ret < 0) return ret;
985 
986  chapters = start_ebml_master(pb, MATROSKA_ID_CHAPTERS , 0);
987  editionentry = start_ebml_master(pb, MATROSKA_ID_EDITIONENTRY, 0);
990  for (i = 0; i < s->nb_chapters; i++) {
991  ebml_master chapteratom, chapterdisplay;
992  AVChapter *c = s->chapters[i];
993  AVDictionaryEntry *t = NULL;
994 
995  chapteratom = start_ebml_master(pb, MATROSKA_ID_CHAPTERATOM, 0);
998  av_rescale_q(c->start, c->time_base, scale));
1000  av_rescale_q(c->end, c->time_base, scale));
1003  if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
1004  chapterdisplay = start_ebml_master(pb, MATROSKA_ID_CHAPTERDISPLAY, 0);
1007  end_ebml_master(pb, chapterdisplay);
1008  }
1009  end_ebml_master(pb, chapteratom);
1010  }
1011  end_ebml_master(pb, editionentry);
1012  end_ebml_master(pb, chapters);
1013 
1014  mkv->wrote_chapters = 1;
1015  return 0;
1016 }
1017 
1019 {
1020  uint8_t *key = av_strdup(t->key);
1021  uint8_t *p = key;
1022  const uint8_t *lang = NULL;
1023  ebml_master tag;
1024 
1025  if ((p = strrchr(p, '-')) &&
1026  (lang = av_convert_lang_to(p + 1, AV_LANG_ISO639_2_BIBL)))
1027  *p = 0;
1028 
1029  p = key;
1030  while (*p) {
1031  if (*p == ' ')
1032  *p = '_';
1033  else if (*p >= 'a' && *p <= 'z')
1034  *p -= 'a' - 'A';
1035  p++;
1036  }
1037 
1040  if (lang)
1043  end_ebml_master(pb, tag);
1044 
1045  av_freep(&key);
1046 }
1047 
1048 static int mkv_write_tag(AVFormatContext *s, AVDictionary *m, unsigned int elementid,
1049  unsigned int uid, ebml_master *tags)
1050 {
1051  MatroskaMuxContext *mkv = s->priv_data;
1052  ebml_master tag, targets;
1053  AVDictionaryEntry *t = NULL;
1054  int ret;
1055 
1056  if (!tags->pos) {
1058  if (ret < 0) return ret;
1059 
1060  *tags = start_ebml_master(s->pb, MATROSKA_ID_TAGS, 0);
1061  }
1062 
1063  tag = start_ebml_master(s->pb, MATROSKA_ID_TAG, 0);
1064  targets = start_ebml_master(s->pb, MATROSKA_ID_TAGTARGETS, 0);
1065  if (elementid)
1066  put_ebml_uint(s->pb, elementid, uid);
1067  end_ebml_master(s->pb, targets);
1068 
1069  while ((t = av_dict_get(m, "", t, AV_DICT_IGNORE_SUFFIX)))
1070  if (av_strcasecmp(t->key, "title") &&
1071  av_strcasecmp(t->key, "stereo_mode") &&
1072  av_strcasecmp(t->key, "encoding_tool"))
1073  mkv_write_simpletag(s->pb, t);
1074 
1075  end_ebml_master(s->pb, tag);
1076  return 0;
1077 }
1078 
1080 {
1081  AVDictionaryEntry *t = NULL;
1082 
1083  while ((t = av_dict_get(m, "", t, AV_DICT_IGNORE_SUFFIX)))
1084  if (av_strcasecmp(t->key, "title") && av_strcasecmp(t->key, "stereo_mode"))
1085  return 1;
1086 
1087  return 0;
1088 }
1089 
1091 {
1092  MatroskaMuxContext *mkv = s->priv_data;
1093  ebml_master tags = {0};
1094  int i, ret;
1095 
1097 
1098  if (mkv_check_tag(s->metadata)) {
1099  ret = mkv_write_tag(s, s->metadata, 0, 0, &tags);
1100  if (ret < 0) return ret;
1101  }
1102 
1103  for (i = 0; i < s->nb_streams; i++) {
1104  AVStream *st = s->streams[i];
1105 
1106  if (!mkv_check_tag(st->metadata))
1107  continue;
1108 
1109  ret = mkv_write_tag(s, st->metadata, MATROSKA_ID_TAGTARGETS_TRACKUID, i + 1, &tags);
1110  if (ret < 0) return ret;
1111  }
1112 
1113  for (i = 0; i < s->nb_chapters; i++) {
1114  AVChapter *ch = s->chapters[i];
1115 
1116  if (!mkv_check_tag(ch->metadata))
1117  continue;
1118 
1120  if (ret < 0) return ret;
1121  }
1122 
1123  if (tags.pos)
1124  end_ebml_master(s->pb, tags);
1125  return 0;
1126 }
1127 
1129 {
1130  MatroskaMuxContext *mkv = s->priv_data;
1131  AVIOContext *pb = s->pb;
1132  ebml_master attachments;
1133  AVLFG c;
1134  int i, ret;
1135 
1136  if (!mkv->have_attachments)
1137  return 0;
1138 
1140 
1142  if (ret < 0) return ret;
1143 
1144  attachments = start_ebml_master(pb, MATROSKA_ID_ATTACHMENTS, 0);
1145 
1146  for (i = 0; i < s->nb_streams; i++) {
1147  AVStream *st = s->streams[i];
1148  ebml_master attached_file;
1149  AVDictionaryEntry *t;
1150  const char *mimetype = NULL;
1151  uint64_t fileuid;
1152 
1154  continue;
1155 
1156  attached_file = start_ebml_master(pb, MATROSKA_ID_ATTACHEDFILE, 0);
1157 
1158  if (t = av_dict_get(st->metadata, "title", NULL, 0))
1160  if (!(t = av_dict_get(st->metadata, "filename", NULL, 0))) {
1161  av_log(s, AV_LOG_ERROR, "Attachment stream %d has no filename tag.\n", i);
1162  return AVERROR(EINVAL);
1163  }
1165  if (t = av_dict_get(st->metadata, "mimetype", NULL, 0))
1166  mimetype = t->value;
1167  else if (st->codec->codec_id != AV_CODEC_ID_NONE ) {
1168  int i;
1169  for (i = 0; ff_mkv_mime_tags[i].id != AV_CODEC_ID_NONE; i++)
1170  if (ff_mkv_mime_tags[i].id == st->codec->codec_id) {
1171  mimetype = ff_mkv_mime_tags[i].str;
1172  break;
1173  }
1174  }
1175  if (!mimetype) {
1176  av_log(s, AV_LOG_ERROR, "Attachment stream %d has no mimetype tag and "
1177  "it cannot be deduced from the codec id.\n", i);
1178  return AVERROR(EINVAL);
1179  }
1180 
1181  if (s->flags & AVFMT_FLAG_BITEXACT) {
1182  struct AVSHA *sha = av_sha_alloc();
1183  uint8_t digest[20];
1184  if (!sha)
1185  return AVERROR(ENOMEM);
1186  av_sha_init(sha, 160);
1188  av_sha_final(sha, digest);
1189  av_free(sha);
1190  fileuid = AV_RL64(digest);
1191  } else {
1192  fileuid = av_lfg_get(&c);
1193  }
1194  av_log(s, AV_LOG_VERBOSE, "Using %.16"PRIx64" for attachment %d\n",
1195  fileuid, i);
1196 
1199  put_ebml_uint(pb, MATROSKA_ID_FILEUID, fileuid);
1200  end_ebml_master(pb, attached_file);
1201  }
1202  end_ebml_master(pb, attachments);
1203 
1204  return 0;
1205 }
1206 
1208 {
1209  MatroskaMuxContext *mkv = s->priv_data;
1210  AVIOContext *pb = s->pb;
1211  ebml_master ebml_header, segment_info;
1213  int ret, i, version = 2;
1214 
1215  if (!strcmp(s->oformat->name, "webm"))
1216  mkv->mode = MODE_WEBM;
1217  else
1218  mkv->mode = MODE_MATROSKAv2;
1219 
1220  if (s->avoid_negative_ts < 0)
1221  s->avoid_negative_ts = 1;
1222 
1223  if (mkv->mode != MODE_WEBM ||
1224  av_dict_get(s->metadata, "stereo_mode", NULL, 0) ||
1225  av_dict_get(s->metadata, "alpha_mode", NULL, 0))
1226  version = 4;
1227 
1228  for (i = 0; i < s->nb_streams; i++) {
1229  if (s->streams[i]->codec->codec_id == AV_CODEC_ID_ATRAC3 ||
1230  s->streams[i]->codec->codec_id == AV_CODEC_ID_COOK ||
1232  s->streams[i]->codec->codec_id == AV_CODEC_ID_SIPR ||
1233  s->streams[i]->codec->codec_id == AV_CODEC_ID_RV10 ||
1234  s->streams[i]->codec->codec_id == AV_CODEC_ID_RV20) {
1235  av_log(s, AV_LOG_ERROR,
1236  "The Matroska muxer does not yet support muxing %s\n",
1238  return AVERROR_PATCHWELCOME;
1239  }
1240  if (s->streams[i]->codec->codec_id == AV_CODEC_ID_OPUS ||
1241  av_dict_get(s->streams[i]->metadata, "stereo_mode", NULL, 0) ||
1242  av_dict_get(s->streams[i]->metadata, "alpha_mode", NULL, 0))
1243  version = 4;
1244  }
1245 
1246  mkv->tracks = av_mallocz_array(s->nb_streams, sizeof(*mkv->tracks));
1247  if (!mkv->tracks)
1248  return AVERROR(ENOMEM);
1249 
1250  ebml_header = start_ebml_master(pb, EBML_ID_HEADER, 0);
1256  put_ebml_uint (pb, EBML_ID_DOCTYPEVERSION , version);
1258  end_ebml_master(pb, ebml_header);
1259 
1261  mkv->segment_offset = avio_tell(pb);
1262 
1263  // we write 2 seek heads - one at the end of the file to point to each
1264  // cluster, and one at the beginning to point to all other level one
1265  // elements (including the seek head at the end of the file), which
1266  // isn't more than 10 elements if we only write one of each other
1267  // currently defined level 1 element
1268  mkv->main_seekhead = mkv_start_seekhead(pb, mkv->segment_offset, 10);
1269  if (!mkv->main_seekhead)
1270  return AVERROR(ENOMEM);
1271 
1273  if (ret < 0) return ret;
1274 
1275  segment_info = start_ebml_master(pb, MATROSKA_ID_INFO, 0);
1277  if ((tag = av_dict_get(s->metadata, "title", NULL, 0)))
1279  if (!(s->flags & AVFMT_FLAG_BITEXACT)) {
1280  uint32_t segment_uid[4];
1281  AVLFG lfg;
1282 
1284 
1285  for (i = 0; i < 4; i++)
1286  segment_uid[i] = av_lfg_get(&lfg);
1287 
1289  if ((tag = av_dict_get(s->metadata, "encoding_tool", NULL, 0)))
1291  else
1293  put_ebml_binary(pb, MATROSKA_ID_SEGMENTUID, segment_uid, 16);
1294  } else {
1295  const char *ident = "Lavf";
1298  }
1299 
1300  if (tag = av_dict_get(s->metadata, "creation_time", NULL, 0)) {
1301  // Adjust time so it's relative to 2001-01-01 and convert to nanoseconds.
1302  int64_t date_utc = (ff_iso8601_to_unix_time(tag->value) - 978307200) * 1000000000;
1303  uint8_t date_utc_buf[8];
1304  AV_WB64(date_utc_buf, date_utc);
1305  put_ebml_binary(pb, MATROSKA_ID_DATEUTC, date_utc_buf, 8);
1306  }
1307 
1308  // reserve space for the duration
1309  mkv->duration = 0;
1310  mkv->duration_offset = avio_tell(pb);
1311  put_ebml_void(pb, 11); // assumes double-precision float to be written
1312  end_ebml_master(pb, segment_info);
1313 
1314  ret = mkv_write_tracks(s);
1315  if (ret < 0)
1316  return ret;
1317 
1318  for (i = 0; i < s->nb_chapters; i++)
1319  mkv->chapter_id_offset = FFMAX(mkv->chapter_id_offset, 1LL - s->chapters[i]->id);
1320 
1321  if (mkv->mode != MODE_WEBM) {
1322  ret = mkv_write_chapters(s);
1323  if (ret < 0)
1324  return ret;
1325 
1326  ret = mkv_write_tags(s);
1327  if (ret < 0)
1328  return ret;
1329 
1330  ret = mkv_write_attachments(s);
1331  if (ret < 0)
1332  return ret;
1333  }
1334 
1335  if (!s->pb->seekable)
1337 
1338  mkv->cues = mkv_start_cues(mkv->segment_offset);
1339  if (!mkv->cues)
1340  return AVERROR(ENOMEM);
1341 
1342  if (pb->seekable && mkv->reserve_cues_space) {
1343  mkv->cues_pos = avio_tell(pb);
1345  }
1346 
1348  mkv->cur_audio_pkt.size = 0;
1349  mkv->cluster_pos = -1;
1350 
1351  avio_flush(pb);
1352 
1353  // start a new cluster every 5 MB or 5 sec, or 32k / 1 sec for streaming or
1354  // after 4k and on a keyframe
1355  if (pb->seekable) {
1356  if (mkv->cluster_time_limit < 0)
1357  mkv->cluster_time_limit = 5000;
1358  if (mkv->cluster_size_limit < 0)
1359  mkv->cluster_size_limit = 5 * 1024 * 1024;
1360  } else {
1361  if (mkv->cluster_time_limit < 0)
1362  mkv->cluster_time_limit = 1000;
1363  if (mkv->cluster_size_limit < 0)
1364  mkv->cluster_size_limit = 32 * 1024;
1365  }
1366 
1367  return 0;
1368 }
1369 
1370 static int mkv_blockgroup_size(int pkt_size)
1371 {
1372  int size = pkt_size + 4;
1373  size += ebml_num_size(size);
1374  size += 2; // EBML ID for block and block duration
1375  size += 8; // max size of block duration
1376  size += ebml_num_size(size);
1377  size += 1; // blockgroup EBML ID
1378  return size;
1379 }
1380 
1381 static int ass_get_duration(const uint8_t *p)
1382 {
1383  int sh, sm, ss, sc, eh, em, es, ec;
1384  uint64_t start, end;
1385 
1386  if (sscanf(p, "%*[^,],%d:%d:%d%*c%d,%d:%d:%d%*c%d",
1387  &sh, &sm, &ss, &sc, &eh, &em, &es, &ec) != 8)
1388  return 0;
1389  start = 3600000LL * sh + 60000LL * sm + 1000LL * ss + 10LL * sc;
1390  end = 3600000LL * eh + 60000LL * em + 1000LL * es + 10LL * ec;
1391  return end - start;
1392 }
1393 
1394 #if FF_API_ASS_SSA
1395 /* Writes the contents of pkt to a block, using the data starting at *datap.
1396  * If pkt corresponds to more than one block, this writes the contents of the first block
1397  * (starting from *datap) and updates *datap so it points to the beginning of the data
1398  * corresponding to the next block.
1399  */
1400 static int mkv_write_ass_block(AVFormatContext *s, AVIOContext *pb,
1401  AVPacket *pkt, uint8_t **datap)
1402 {
1403  MatroskaMuxContext *mkv = s->priv_data;
1404  int i, layer = 0, size, line_size, data_size = pkt->size - (*datap - pkt->data);
1405  uint8_t *start, *end, *data = *datap;
1406  ebml_master blockgroup;
1407  char buffer[2048];
1408 
1409  int duration = ass_get_duration(data);
1410  end = memchr(data, '\n', data_size);
1411  size = line_size = end ? end - data + 1 : data_size;
1412  size -= end ? (end[-1] == '\r') + 1 : 0;
1413  start = data;
1414  for (i = 0; i < 3; i++, start++)
1415  if (!(start = memchr(start, ',', size - (start - data))))
1416  return duration;
1417  size -= start - data;
1418  sscanf(data, "Dialogue: %d,", &layer);
1419  i = snprintf(buffer, sizeof(buffer), "%" PRId64 ",%d,",
1420  s->streams[pkt->stream_index]->nb_frames, layer);
1421  size = FFMIN(i + size, sizeof(buffer));
1422  memcpy(buffer + i, start, size - i);
1423 
1424  av_log(s, AV_LOG_DEBUG,
1425  "Writing block at offset %" PRIu64 ", size %d, "
1426  "pts %" PRId64 ", duration %d\n",
1427  avio_tell(pb), size, pkt->pts, duration);
1428  blockgroup = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP,
1431  put_ebml_num(pb, size + 4, 0);
1432  // this assumes stream_index is less than 126
1433  avio_w8(pb, 0x80 | (pkt->stream_index + 1));
1434  avio_wb16(pb, pkt->pts - mkv->cluster_pts);
1435  avio_w8(pb, 0);
1436  avio_write(pb, buffer, size);
1438  end_ebml_master(pb, blockgroup);
1439 
1440  *datap += line_size;
1441 
1442  return duration;
1443 }
1444 #endif
1445 
1446 static int mkv_strip_wavpack(const uint8_t *src, uint8_t **pdst, int *size)
1447 {
1448  uint8_t *dst;
1449  int srclen = *size;
1450  int offset = 0;
1451  int ret;
1452 
1453  dst = av_malloc(srclen);
1454  if (!dst)
1455  return AVERROR(ENOMEM);
1456 
1457  while (srclen >= WV_HEADER_SIZE) {
1458  WvHeader header;
1459 
1460  ret = ff_wv_parse_header(&header, src);
1461  if (ret < 0)
1462  goto fail;
1463  src += WV_HEADER_SIZE;
1464  srclen -= WV_HEADER_SIZE;
1465 
1466  if (srclen < header.blocksize) {
1467  ret = AVERROR_INVALIDDATA;
1468  goto fail;
1469  }
1470 
1471  if (header.initial) {
1472  AV_WL32(dst + offset, header.samples);
1473  offset += 4;
1474  }
1475  AV_WL32(dst + offset, header.flags);
1476  AV_WL32(dst + offset + 4, header.crc);
1477  offset += 8;
1478 
1479  if (!(header.initial && header.final)) {
1480  AV_WL32(dst + offset, header.blocksize);
1481  offset += 4;
1482  }
1483 
1484  memcpy(dst + offset, src, header.blocksize);
1485  src += header.blocksize;
1486  srclen -= header.blocksize;
1487  offset += header.blocksize;
1488  }
1489 
1490  *pdst = dst;
1491  *size = offset;
1492 
1493  return 0;
1494 fail:
1495  av_freep(&dst);
1496  return ret;
1497 }
1498 
1500  unsigned int blockid, AVPacket *pkt, int flags)
1501 {
1502  MatroskaMuxContext *mkv = s->priv_data;
1503  AVCodecContext *codec = s->streams[pkt->stream_index]->codec;
1504  uint8_t *data = NULL, *side_data = NULL;
1505  int offset = 0, size = pkt->size, side_data_size = 0;
1506  int64_t ts = mkv->tracks[pkt->stream_index].write_dts ? pkt->dts : pkt->pts;
1507  uint64_t additional_id = 0;
1508  int64_t discard_padding = 0;
1509  ebml_master block_group, block_additions, block_more;
1510 
1511  av_log(s, AV_LOG_DEBUG, "Writing block at offset %" PRIu64 ", size %d, "
1512  "pts %" PRId64 ", dts %" PRId64 ", duration %d, flags %d\n",
1513  avio_tell(pb), pkt->size, pkt->pts, pkt->dts, pkt->duration, flags);
1514  if (codec->codec_id == AV_CODEC_ID_H264 && codec->extradata_size > 0 &&
1515  (AV_RB24(codec->extradata) == 1 || AV_RB32(codec->extradata) == 1))
1516  ff_avc_parse_nal_units_buf(pkt->data, &data, &size);
1517  else if (codec->codec_id == AV_CODEC_ID_HEVC && codec->extradata_size > 6 &&
1518  (AV_RB24(codec->extradata) == 1 || AV_RB32(codec->extradata) == 1))
1519  /* extradata is Annex B, assume the bitstream is too and convert it */
1520  ff_hevc_annexb2mp4_buf(pkt->data, &data, &size, 0, NULL);
1521  else if (codec->codec_id == AV_CODEC_ID_WAVPACK) {
1522  int ret = mkv_strip_wavpack(pkt->data, &data, &size);
1523  if (ret < 0) {
1524  av_log(s, AV_LOG_ERROR, "Error stripping a WavPack packet.\n");
1525  return;
1526  }
1527  } else
1528  data = pkt->data;
1529 
1530  if (codec->codec_id == AV_CODEC_ID_PRORES) {
1531  /* Matroska specification requires to remove the first QuickTime atom
1532  */
1533  size -= 8;
1534  offset = 8;
1535  }
1536 
1537  side_data = av_packet_get_side_data(pkt,
1539  &side_data_size);
1540 
1541  if (side_data && side_data_size >= 10) {
1542  discard_padding = av_rescale_q(AV_RL32(side_data + 4),
1543  (AVRational){1, codec->sample_rate},
1544  (AVRational){1, 1000000000});
1545  }
1546 
1547  side_data = av_packet_get_side_data(pkt,
1549  &side_data_size);
1550  if (side_data) {
1551  additional_id = AV_RB64(side_data);
1552  side_data += 8;
1553  side_data_size -= 8;
1554  }
1555 
1556  if ((side_data_size && additional_id == 1) || discard_padding) {
1557  block_group = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP, 0);
1558  blockid = MATROSKA_ID_BLOCK;
1559  }
1560 
1561  put_ebml_id(pb, blockid);
1562  put_ebml_num(pb, size + 4, 0);
1563  // this assumes stream_index is less than 126
1564  avio_w8(pb, 0x80 | (mkv->is_dash ? mkv->dash_track_number : (pkt->stream_index + 1)));
1565  avio_wb16(pb, ts - mkv->cluster_pts);
1566  avio_w8(pb, flags);
1567  avio_write(pb, data + offset, size);
1568  if (data != pkt->data)
1569  av_free(data);
1570 
1571  if (discard_padding) {
1572  put_ebml_sint(pb, MATROSKA_ID_DISCARDPADDING, discard_padding);
1573  }
1574 
1575  if (side_data_size && additional_id == 1) {
1576  block_additions = start_ebml_master(pb, MATROSKA_ID_BLOCKADDITIONS, 0);
1577  block_more = start_ebml_master(pb, MATROSKA_ID_BLOCKMORE, 0);
1580  put_ebml_num(pb, side_data_size, 0);
1581  avio_write(pb, side_data, side_data_size);
1582  end_ebml_master(pb, block_more);
1583  end_ebml_master(pb, block_additions);
1584  }
1585  if ((side_data_size && additional_id == 1) || discard_padding) {
1586  end_ebml_master(pb, block_group);
1587  }
1588 }
1589 
1591 {
1592  int i, duration = 0;
1593 
1594  for (i = 0; i < 2 && !duration; i++) {
1595  int s_hour, s_min, s_sec, s_hsec, e_hour, e_min, e_sec, e_hsec;
1596  if (sscanf(*buf, "%d:%2d:%2d%*1[,.]%3d --> %d:%2d:%2d%*1[,.]%3d",
1597  &s_hour, &s_min, &s_sec, &s_hsec,
1598  &e_hour, &e_min, &e_sec, &e_hsec) == 8) {
1599  s_min += 60 * s_hour;
1600  e_min += 60 * e_hour;
1601  s_sec += 60 * s_min;
1602 
1603  e_sec += 60 * e_min;
1604  s_hsec += 1000 * s_sec;
1605  e_hsec += 1000 * e_sec;
1606 
1607  duration = e_hsec - s_hsec;
1608  }
1609  *buf += ff_subtitles_next_line(*buf);
1610  }
1611  return duration;
1612 }
1613 
1615  AVPacket *pkt)
1616 {
1617  ebml_master blockgroup;
1618  AVPacket pkt2 = *pkt;
1619  int64_t duration = srt_get_duration(&pkt2.data);
1620  pkt2.size -= pkt2.data - pkt->data;
1621 
1622  blockgroup = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP,
1623  mkv_blockgroup_size(pkt2.size));
1624  mkv_write_block(s, pb, MATROSKA_ID_BLOCK, &pkt2, 0);
1626  end_ebml_master(pb, blockgroup);
1627 
1628  return duration;
1629 }
1630 
1632 {
1633  MatroskaMuxContext *mkv = s->priv_data;
1634  ebml_master blockgroup;
1635  int id_size, settings_size, size;
1636  uint8_t *id, *settings;
1637  int64_t ts = mkv->tracks[pkt->stream_index].write_dts ? pkt->dts : pkt->pts;
1638  const int flags = 0;
1639 
1640  id_size = 0;
1642  &id_size);
1643 
1644  settings_size = 0;
1646  &settings_size);
1647 
1648  size = id_size + 1 + settings_size + 1 + pkt->size;
1649 
1650  av_log(s, AV_LOG_DEBUG, "Writing block at offset %" PRIu64 ", size %d, "
1651  "pts %" PRId64 ", dts %" PRId64 ", duration %d, flags %d\n",
1652  avio_tell(pb), size, pkt->pts, pkt->dts, pkt->duration, flags);
1653 
1655 
1657  put_ebml_num(pb, size + 4, 0);
1658  avio_w8(pb, 0x80 | (pkt->stream_index + 1)); // this assumes stream_index is less than 126
1659  avio_wb16(pb, ts - mkv->cluster_pts);
1660  avio_w8(pb, flags);
1661  avio_printf(pb, "%.*s\n%.*s\n%.*s", id_size, id, settings_size, settings, pkt->size, pkt->data);
1662 
1664  end_ebml_master(pb, blockgroup);
1665 
1666  return pkt->duration;
1667 }
1668 
1670 {
1671  MatroskaMuxContext *mkv = s->priv_data;
1672  int bufsize;
1673  uint8_t *dyn_buf;
1674 
1675  if (!mkv->dyn_bc)
1676  return;
1677 
1678  bufsize = avio_close_dyn_buf(mkv->dyn_bc, &dyn_buf);
1679  avio_write(s->pb, dyn_buf, bufsize);
1680  av_free(dyn_buf);
1681  mkv->dyn_bc = NULL;
1682 }
1683 
1685 {
1686  MatroskaMuxContext *mkv = s->priv_data;
1687  AVIOContext *pb;
1688 
1689  if (s->pb->seekable) {
1690  pb = s->pb;
1691  } else {
1692  pb = mkv->dyn_bc;
1693  }
1694 
1695  av_log(s, AV_LOG_DEBUG,
1696  "Starting new cluster at offset %" PRIu64 " bytes, "
1697  "pts %" PRIu64 "dts %" PRIu64 "\n",
1698  avio_tell(pb), pkt->pts, pkt->dts);
1699  end_ebml_master(pb, mkv->cluster);
1700  mkv->cluster_pos = -1;
1701  if (mkv->dyn_bc)
1702  mkv_flush_dynbuf(s);
1703  avio_flush(s->pb);
1704 }
1705 
1706 static int mkv_write_packet_internal(AVFormatContext *s, AVPacket *pkt, int add_cue)
1707 {
1708  MatroskaMuxContext *mkv = s->priv_data;
1709  AVIOContext *pb = s->pb;
1710  AVCodecContext *codec = s->streams[pkt->stream_index]->codec;
1711  int keyframe = !!(pkt->flags & AV_PKT_FLAG_KEY);
1712  int duration = pkt->duration;
1713  int ret;
1714  int64_t ts = mkv->tracks[pkt->stream_index].write_dts ? pkt->dts : pkt->pts;
1715  int64_t relative_packet_pos;
1716  uint8_t *data_offset = pkt->data;
1717  int dash_tracknum = mkv->is_dash ? mkv->dash_track_number : pkt->stream_index + 1;
1718 
1719  if (ts == AV_NOPTS_VALUE) {
1720  av_log(s, AV_LOG_ERROR, "Can't write packet with unknown timestamp\n");
1721  return AVERROR(EINVAL);
1722  }
1723  ts += mkv->tracks[pkt->stream_index].ts_offset;
1724 
1725  if (mkv->cluster_pos != -1) {
1726  int64_t cluster_time = ts - mkv->cluster_pts + mkv->tracks[pkt->stream_index].ts_offset;
1727  if ((int16_t)cluster_time != cluster_time) {
1728  av_log(s, AV_LOG_WARNING, "Starting new cluster due to timestamp\n");
1729  mkv_start_new_cluster(s, pkt);
1730  }
1731  }
1732 
1733  if (!s->pb->seekable) {
1734  if (!mkv->dyn_bc) {
1735  if ((ret = avio_open_dyn_buf(&mkv->dyn_bc)) < 0) {
1736  av_log(s, AV_LOG_ERROR, "Failed to open dynamic buffer\n");
1737  return ret;
1738  }
1739  }
1740  pb = mkv->dyn_bc;
1741  }
1742 
1743  if (mkv->cluster_pos == -1) {
1744  mkv->cluster_pos = avio_tell(s->pb);
1747  mkv->cluster_pts = FFMAX(0, ts);
1748  }
1749 
1750  relative_packet_pos = avio_tell(s->pb) - mkv->cluster.pos;
1751 
1752  if (codec->codec_type != AVMEDIA_TYPE_SUBTITLE) {
1753  mkv_write_block(s, pb, MATROSKA_ID_SIMPLEBLOCK, pkt, keyframe << 7);
1754  if (codec->codec_type == AVMEDIA_TYPE_VIDEO && keyframe || add_cue) {
1755  ret = mkv_add_cuepoint(mkv->cues, pkt->stream_index, dash_tracknum, ts, mkv->cluster_pos, relative_packet_pos, -1);
1756  if (ret < 0) return ret;
1757  }
1758 #if FF_API_ASS_SSA
1759  } else if (codec->codec_id == AV_CODEC_ID_SSA) {
1760  while (data_offset < pkt->data + pkt->size) {
1761  duration = mkv_write_ass_block(s, pb, pkt, &data_offset);
1762  ret = mkv_add_cuepoint(mkv->cues, pkt->stream_index, dash_tracknum, ts, mkv->cluster_pos, relative_packet_pos, duration);
1763  if (ret < 0) return ret;
1764  relative_packet_pos = avio_tell(s->pb) - mkv->cluster.pos;
1765  }
1766 #endif
1767  } else {
1768  if (codec->codec_id == AV_CODEC_ID_SRT) {
1769  duration = mkv_write_srt_blocks(s, pb, pkt);
1770  } else if (codec->codec_id == AV_CODEC_ID_WEBVTT) {
1771  duration = mkv_write_vtt_blocks(s, pb, pkt);
1772  } else {
1774  mkv_blockgroup_size(pkt->size));
1775  /* For backward compatibility, prefer convergence_duration. */
1776  if (pkt->convergence_duration > 0) {
1777  duration = pkt->convergence_duration;
1778  }
1779  mkv_write_block(s, pb, MATROSKA_ID_BLOCK, pkt, 0);
1781  end_ebml_master(pb, blockgroup);
1782  }
1783 
1784  ret = mkv_add_cuepoint(mkv->cues, pkt->stream_index, dash_tracknum, ts,
1785  mkv->cluster_pos, relative_packet_pos, duration);
1786  if (ret < 0)
1787  return ret;
1788  }
1789 
1790  mkv->duration = FFMAX(mkv->duration, ts + duration);
1791  return 0;
1792 }
1793 
1795 {
1796  MatroskaMuxContext *mkv = s->priv_data;
1797  int codec_type = s->streams[pkt->stream_index]->codec->codec_type;
1798  int keyframe = !!(pkt->flags & AV_PKT_FLAG_KEY);
1799  int cluster_size;
1800  int64_t cluster_time;
1801  int ret;
1802  int start_new_cluster;
1803 
1804  if (mkv->tracks[pkt->stream_index].write_dts)
1805  cluster_time = pkt->dts - mkv->cluster_pts;
1806  else
1807  cluster_time = pkt->pts - mkv->cluster_pts;
1808  cluster_time += mkv->tracks[pkt->stream_index].ts_offset;
1809 
1810  // start a new cluster every 5 MB or 5 sec, or 32k / 1 sec for streaming or
1811  // after 4k and on a keyframe
1812  if (s->pb->seekable) {
1813  cluster_size = avio_tell(s->pb) - mkv->cluster_pos;
1814  } else {
1815  cluster_size = avio_tell(mkv->dyn_bc);
1816  }
1817 
1818  if (mkv->is_dash && codec_type == AVMEDIA_TYPE_VIDEO) {
1819  // WebM DASH specification states that the first block of every cluster
1820  // has to be a key frame. So for DASH video, we only create a cluster
1821  // on seeing key frames.
1822  start_new_cluster = keyframe;
1823  } else if (mkv->is_dash && codec_type == AVMEDIA_TYPE_AUDIO &&
1824  cluster_time > mkv->cluster_time_limit) {
1825  // For DASH audio, we create a Cluster based on cluster_time_limit
1826  start_new_cluster = 1;
1827  } else if (!mkv->is_dash &&
1828  (cluster_size > mkv->cluster_size_limit ||
1829  cluster_time > mkv->cluster_time_limit ||
1830  (codec_type == AVMEDIA_TYPE_VIDEO && keyframe &&
1831  cluster_size > 4 * 1024))) {
1832  start_new_cluster = 1;
1833  } else {
1834  start_new_cluster = 0;
1835  }
1836 
1837  if (mkv->cluster_pos != -1 && start_new_cluster) {
1838  mkv_start_new_cluster(s, pkt);
1839  }
1840 
1841  // check if we have an audio packet cached
1842  if (mkv->cur_audio_pkt.size > 0) {
1843  // for DASH audio, a CuePoint has to be added when there is a new cluster.
1845  mkv->is_dash ? start_new_cluster : 0);
1847  if (ret < 0) {
1848  av_log(s, AV_LOG_ERROR,
1849  "Could not write cached audio packet ret:%d\n", ret);
1850  return ret;
1851  }
1852  }
1853 
1854  // buffer an audio packet to ensure the packet containing the video
1855  // keyframe's timecode is contained in the same cluster for WebM
1856  if (codec_type == AVMEDIA_TYPE_AUDIO) {
1857  mkv->cur_audio_pkt = *pkt;
1858  if (pkt->buf) {
1859  mkv->cur_audio_pkt.buf = av_buffer_ref(pkt->buf);
1860  ret = mkv->cur_audio_pkt.buf ? 0 : AVERROR(ENOMEM);
1861  } else
1862  ret = av_dup_packet(&mkv->cur_audio_pkt);
1863  if (mkv->cur_audio_pkt.side_data_elems > 0) {
1865  }
1866  } else
1867  ret = mkv_write_packet_internal(s, pkt, 0);
1868  return ret;
1869 }
1870 
1872 {
1873  MatroskaMuxContext *mkv = s->priv_data;
1874  AVIOContext *pb;
1875  if (s->pb->seekable)
1876  pb = s->pb;
1877  else
1878  pb = mkv->dyn_bc;
1879  if (!pkt) {
1880  if (mkv->cluster_pos != -1) {
1881  av_log(s, AV_LOG_DEBUG,
1882  "Flushing cluster at offset %" PRIu64 " bytes\n",
1883  avio_tell(pb));
1884  end_ebml_master(pb, mkv->cluster);
1885  mkv->cluster_pos = -1;
1886  if (mkv->dyn_bc)
1887  mkv_flush_dynbuf(s);
1888  avio_flush(s->pb);
1889  }
1890  return 0;
1891  }
1892  return mkv_write_packet(s, pkt);
1893 }
1894 
1896 {
1897  MatroskaMuxContext *mkv = s->priv_data;
1898  AVIOContext *pb = s->pb;
1899  int64_t currentpos, cuespos;
1900  int ret;
1901 
1902  // check if we have an audio packet cached
1903  if (mkv->cur_audio_pkt.size > 0) {
1904  ret = mkv_write_packet_internal(s, &mkv->cur_audio_pkt, 0);
1906  if (ret < 0) {
1907  av_log(s, AV_LOG_ERROR,
1908  "Could not write cached audio packet ret:%d\n", ret);
1909  return ret;
1910  }
1911  }
1912 
1913  if (mkv->dyn_bc) {
1914  end_ebml_master(mkv->dyn_bc, mkv->cluster);
1915  mkv_flush_dynbuf(s);
1916  } else if (mkv->cluster_pos != -1) {
1917  end_ebml_master(pb, mkv->cluster);
1918  }
1919 
1920  if (mkv->mode != MODE_WEBM) {
1921  ret = mkv_write_chapters(s);
1922  if (ret < 0)
1923  return ret;
1924  }
1925 
1926  if (pb->seekable) {
1927  if (mkv->cues->num_entries) {
1928  if (mkv->reserve_cues_space) {
1929  int64_t cues_end;
1930 
1931  currentpos = avio_tell(pb);
1932  avio_seek(pb, mkv->cues_pos, SEEK_SET);
1933 
1934  cuespos = mkv_write_cues(s, mkv->cues, mkv->tracks, s->nb_streams);
1935  cues_end = avio_tell(pb);
1936  if (cues_end > cuespos + mkv->reserve_cues_space) {
1937  av_log(s, AV_LOG_ERROR,
1938  "Insufficient space reserved for cues: %d "
1939  "(needed: %" PRId64 ").\n",
1940  mkv->reserve_cues_space, cues_end - cuespos);
1941  return AVERROR(EINVAL);
1942  }
1943 
1944  if (cues_end < cuespos + mkv->reserve_cues_space)
1946  (cues_end - cuespos));
1947 
1948  avio_seek(pb, currentpos, SEEK_SET);
1949  } else {
1950  cuespos = mkv_write_cues(s, mkv->cues, mkv->tracks, s->nb_streams);
1951  }
1952 
1954  cuespos);
1955  if (ret < 0)
1956  return ret;
1957  }
1958 
1960 
1961  // update the duration
1962  av_log(s, AV_LOG_DEBUG, "end duration = %" PRIu64 "\n", mkv->duration);
1963  currentpos = avio_tell(pb);
1964  avio_seek(pb, mkv->duration_offset, SEEK_SET);
1966 
1967  avio_seek(pb, currentpos, SEEK_SET);
1968  }
1969 
1970  end_ebml_master(pb, mkv->segment);
1971  av_freep(&mkv->tracks);
1972  av_freep(&mkv->cues->entries);
1973  av_freep(&mkv->cues);
1974 
1975  return 0;
1976 }
1977 
1978 static int mkv_query_codec(enum AVCodecID codec_id, int std_compliance)
1979 {
1980  int i;
1981  for (i = 0; ff_mkv_codec_tags[i].id != AV_CODEC_ID_NONE; i++)
1982  if (ff_mkv_codec_tags[i].id == codec_id)
1983  return 1;
1984 
1985  if (std_compliance < FF_COMPLIANCE_NORMAL) {
1986  enum AVMediaType type = avcodec_get_type(codec_id);
1987  // mkv theoretically supports any video/audio through VFW/ACM
1988  if (type == AVMEDIA_TYPE_VIDEO || type == AVMEDIA_TYPE_AUDIO)
1989  return 1;
1990  }
1991 
1992  return 0;
1993 }
1994 
1996  { AV_CODEC_ID_ALAC, 0XFFFFFFFF },
1997  { AV_CODEC_ID_EAC3, 0XFFFFFFFF },
1998  { AV_CODEC_ID_MLP, 0xFFFFFFFF },
1999  { AV_CODEC_ID_OPUS, 0xFFFFFFFF },
2000  { AV_CODEC_ID_PCM_S16BE, 0xFFFFFFFF },
2001  { AV_CODEC_ID_PCM_S24BE, 0xFFFFFFFF },
2002  { AV_CODEC_ID_PCM_S32BE, 0xFFFFFFFF },
2003  { AV_CODEC_ID_QDM2, 0xFFFFFFFF },
2004  { AV_CODEC_ID_RA_144, 0xFFFFFFFF },
2005  { AV_CODEC_ID_RA_288, 0xFFFFFFFF },
2006  { AV_CODEC_ID_COOK, 0xFFFFFFFF },
2007  { AV_CODEC_ID_TRUEHD, 0xFFFFFFFF },
2008  { AV_CODEC_ID_NONE, 0xFFFFFFFF }
2009 };
2010 
2012  { AV_CODEC_ID_RV10, 0xFFFFFFFF },
2013  { AV_CODEC_ID_RV20, 0xFFFFFFFF },
2014  { AV_CODEC_ID_RV30, 0xFFFFFFFF },
2015  { AV_CODEC_ID_RV40, 0xFFFFFFFF },
2016  { AV_CODEC_ID_VP9, 0xFFFFFFFF },
2017  { AV_CODEC_ID_NONE, 0xFFFFFFFF }
2018 };
2019 
2020 #define OFFSET(x) offsetof(MatroskaMuxContext, x)
2021 #define FLAGS AV_OPT_FLAG_ENCODING_PARAM
2022 static const AVOption options[] = {
2023  { "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 },
2024  { "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 },
2025  { "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 },
2026  { "dash", "Create a WebM file conforming to WebM DASH specification", OFFSET(is_dash), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, FLAGS },
2027  { "dash_track_number", "Track number for the DASH stream", OFFSET(dash_track_number), AV_OPT_TYPE_INT, { .i64 = 1 }, 0, 127, FLAGS },
2028  { NULL },
2029 };
2030 
2031 #if CONFIG_MATROSKA_MUXER
2032 static const AVClass matroska_class = {
2033  .class_name = "matroska muxer",
2034  .item_name = av_default_item_name,
2035  .option = options,
2036  .version = LIBAVUTIL_VERSION_INT,
2037 };
2038 
2039 AVOutputFormat ff_matroska_muxer = {
2040  .name = "matroska",
2041  .long_name = NULL_IF_CONFIG_SMALL("Matroska"),
2042  .mime_type = "video/x-matroska",
2043  .extensions = "mkv",
2044  .priv_data_size = sizeof(MatroskaMuxContext),
2045  .audio_codec = CONFIG_LIBVORBIS_ENCODER ?
2047  .video_codec = CONFIG_LIBX264_ENCODER ?
2054  .codec_tag = (const AVCodecTag* const []){
2057  },
2058 #if FF_API_ASS_SSA
2059  .subtitle_codec = AV_CODEC_ID_SSA,
2060 #else
2061  .subtitle_codec = AV_CODEC_ID_ASS,
2062 #endif
2063  .query_codec = mkv_query_codec,
2064  .priv_class = &matroska_class,
2065 };
2066 #endif
2067 
2068 #if CONFIG_WEBM_MUXER
2069 static const AVClass webm_class = {
2070  .class_name = "webm muxer",
2071  .item_name = av_default_item_name,
2072  .option = options,
2073  .version = LIBAVUTIL_VERSION_INT,
2074 };
2075 
2076 AVOutputFormat ff_webm_muxer = {
2077  .name = "webm",
2078  .long_name = NULL_IF_CONFIG_SMALL("WebM"),
2079  .mime_type = "video/webm",
2080  .extensions = "webm",
2081  .priv_data_size = sizeof(MatroskaMuxContext),
2082  .audio_codec = AV_CODEC_ID_VORBIS,
2083  .video_codec = AV_CODEC_ID_VP8,
2084  .subtitle_codec = AV_CODEC_ID_WEBVTT,
2090  .priv_class = &webm_class,
2091 };
2092 #endif
2093 
2094 #if CONFIG_MATROSKA_AUDIO_MUXER
2095 static const AVClass mka_class = {
2096  .class_name = "matroska audio muxer",
2097  .item_name = av_default_item_name,
2098  .option = options,
2099  .version = LIBAVUTIL_VERSION_INT,
2100 };
2101 AVOutputFormat ff_matroska_audio_muxer = {
2102  .name = "matroska",
2103  .long_name = NULL_IF_CONFIG_SMALL("Matroska Audio"),
2104  .mime_type = "audio/x-matroska",
2105  .extensions = "mka",
2106  .priv_data_size = sizeof(MatroskaMuxContext),
2107  .audio_codec = CONFIG_LIBVORBIS_ENCODER ?
2108  AV_CODEC_ID_VORBIS : AV_CODEC_ID_AC3,
2109  .video_codec = AV_CODEC_ID_NONE,
2115  .codec_tag = (const AVCodecTag* const []){
2117  },
2118  .priv_class = &mka_class,
2119 };
2120 #endif