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