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