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