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