FFmpeg  2.6.9
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Modules Pages
matroskaenc.c
Go to the documentation of this file.
1 /*
2  * Matroska muxer
3  * Copyright (c) 2007 David Conrad
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21 
22 #include <stdint.h>
23 
24 #include "avc.h"
25 #include "hevc.h"
26 #include "avformat.h"
27 #include "avio_internal.h"
28 #include "avlanguage.h"
29 #include "flacenc.h"
30 #include "internal.h"
31 #include "isom.h"
32 #include "matroska.h"
33 #include "riff.h"
34 #include "subtitles.h"
35 #include "vorbiscomment.h"
36 #include "wv.h"
37 
38 #include "libavutil/avstring.h"
40 #include "libavutil/dict.h"
41 #include "libavutil/intfloat.h"
42 #include "libavutil/intreadwrite.h"
43 #include "libavutil/lfg.h"
44 #include "libavutil/mathematics.h"
45 #include "libavutil/opt.h"
46 #include "libavutil/random_seed.h"
47 #include "libavutil/samplefmt.h"
48 #include "libavutil/sha.h"
49 #include "libavutil/stereo3d.h"
50 
51 #include "libavcodec/xiph.h"
52 #include "libavcodec/mpeg4audio.h"
53 #include "libavcodec/internal.h"
54 
55 typedef struct ebml_master {
56  int64_t pos; ///< absolute offset in the file where the master's elements start
57  int sizebytes; ///< how many bytes were reserved for the size
58 } ebml_master;
59 
60 typedef struct mkv_seekhead_entry {
61  unsigned int elementid;
62  uint64_t segmentpos;
64 
65 typedef struct mkv_seekhead {
66  int64_t filepos;
67  int64_t segment_offset; ///< the file offset to the beginning of the segment
68  int reserved_size; ///< -1 if appending to file
72 } mkv_seekhead;
73 
74 typedef struct mkv_cuepoint {
75  uint64_t pts;
77  int tracknum;
78  int64_t cluster_pos; ///< file offset of the cluster containing the block
79  int64_t relative_pos; ///< relative offset from the position of the cluster containing the block
80  int64_t duration; ///< duration of the block according to time base
81 } mkv_cuepoint;
82 
83 typedef struct mkv_cues {
84  int64_t segment_offset;
87 } mkv_cues;
88 
89 typedef struct mkv_track {
90  int write_dts;
91  int has_cue;
92  int64_t ts_offset;
93 } mkv_track;
94 
95 #define MODE_MATROSKAv2 0x01
96 #define MODE_WEBM 0x02
97 
98 typedef struct MatroskaMuxContext {
99  const AVClass *class;
100  int mode;
103  int64_t segment_offset;
105  int64_t cluster_pos; ///< file offset of the current cluster
106  int64_t cluster_pts;
108  int64_t duration;
112 
114 
116 
119  int64_t cues_pos;
121  int is_dash;
123 
126 
129 
130 
131 /** 2 bytes * 3 for EBML IDs, 3 1-byte EBML lengths, 8 bytes for 64 bit
132  * offset, 4 bytes for target EBML ID */
133 #define MAX_SEEKENTRY_SIZE 21
134 
135 /** per-cuepoint-track - 5 1-byte EBML IDs, 5 1-byte EBML sizes, 4
136  * 8-byte uint max */
137 #define MAX_CUETRACKPOS_SIZE 42
138 
139 /** per-cuepoint - 2 1-byte EBML IDs, 2 1-byte EBML sizes, 8-byte uint max */
140 #define MAX_CUEPOINT_SIZE(num_tracks) 12 + MAX_CUETRACKPOS_SIZE * num_tracks
141 
142 /** Seek preroll value for opus */
143 #define OPUS_SEEK_PREROLL 80000000
144 
145 static int ebml_id_size(unsigned int id)
146 {
147  return (av_log2(id + 1) - 1) / 7 + 1;
148 }
149 
150 static void put_ebml_id(AVIOContext *pb, unsigned int id)
151 {
152  int i = ebml_id_size(id);
153  while (i--)
154  avio_w8(pb, (uint8_t)(id >> (i * 8)));
155 }
156 
157 /**
158  * Write an EBML size meaning "unknown size".
159  *
160  * @param bytes The number of bytes the size should occupy (maximum: 8).
161  */
162 static void put_ebml_size_unknown(AVIOContext *pb, int bytes)
163 {
164  av_assert0(bytes <= 8);
165  avio_w8(pb, 0x1ff >> bytes);
166  ffio_fill(pb, 0xff, bytes - 1);
167 }
168 
169 /**
170  * Calculate how many bytes are needed to represent a given number in EBML.
171  */
172 static int ebml_num_size(uint64_t num)
173 {
174  int bytes = 1;
175  while ((num + 1) >> bytes * 7)
176  bytes++;
177  return bytes;
178 }
179 
180 /**
181  * Write a number in EBML variable length format.
182  *
183  * @param bytes The number of bytes that need to be used to write the number.
184  * If zero, any number of bytes can be used.
185  */
186 static void put_ebml_num(AVIOContext *pb, uint64_t num, int bytes)
187 {
188  int i, needed_bytes = ebml_num_size(num);
189 
190  // sizes larger than this are currently undefined in EBML
191  av_assert0(num < (1ULL << 56) - 1);
192 
193  if (bytes == 0)
194  // don't care how many bytes are used, so use the min
195  bytes = needed_bytes;
196  // the bytes needed to write the given size would exceed the bytes
197  // that we need to use, so write unknown size. This shouldn't happen.
198  av_assert0(bytes >= needed_bytes);
199 
200  num |= 1ULL << bytes * 7;
201  for (i = bytes - 1; i >= 0; i--)
202  avio_w8(pb, (uint8_t)(num >> i * 8));
203 }
204 
205 static void put_ebml_uint(AVIOContext *pb, unsigned int elementid, uint64_t val)
206 {
207  int i, bytes = 1;
208  uint64_t tmp = val;
209  while (tmp >>= 8)
210  bytes++;
211 
212  put_ebml_id(pb, elementid);
213  put_ebml_num(pb, bytes, 0);
214  for (i = bytes - 1; i >= 0; i--)
215  avio_w8(pb, (uint8_t)(val >> i * 8));
216 }
217 
218 static void put_ebml_sint(AVIOContext *pb, unsigned int elementid, int64_t val)
219 {
220  int i, bytes = 1;
221  uint64_t tmp = 2*(val < 0 ? val^-1 : val);
222 
223  while (tmp>>=8) bytes++;
224 
225  put_ebml_id(pb, elementid);
226  put_ebml_num(pb, bytes, 0);
227  for (i = bytes - 1; i >= 0; i--)
228  avio_w8(pb, (uint8_t)(val >> i * 8));
229 }
230 
231 static void put_ebml_float(AVIOContext *pb, unsigned int elementid, double val)
232 {
233  put_ebml_id(pb, elementid);
234  put_ebml_num(pb, 8, 0);
235  avio_wb64(pb, av_double2int(val));
236 }
237 
238 static void put_ebml_binary(AVIOContext *pb, unsigned int elementid,
239  const void *buf, int size)
240 {
241  put_ebml_id(pb, elementid);
242  put_ebml_num(pb, size, 0);
243  avio_write(pb, buf, size);
244 }
245 
246 static void put_ebml_string(AVIOContext *pb, unsigned int elementid,
247  const char *str)
248 {
249  put_ebml_binary(pb, elementid, str, strlen(str));
250 }
251 
252 /**
253  * Write a void element of a given size. Useful for reserving space in
254  * the file to be written to later.
255  *
256  * @param size The number of bytes to reserve, which must be at least 2.
257  */
258 static void put_ebml_void(AVIOContext *pb, uint64_t size)
259 {
260  int64_t currentpos = avio_tell(pb);
261 
262  av_assert0(size >= 2);
263 
265  // we need to subtract the length needed to store the size from the
266  // size we need to reserve so 2 cases, we use 8 bytes to store the
267  // size if possible, 1 byte otherwise
268  if (size < 10)
269  put_ebml_num(pb, size - 1, 0);
270  else
271  put_ebml_num(pb, size - 9, 8);
272  ffio_fill(pb, 0, currentpos + size - avio_tell(pb));
273 }
274 
275 static ebml_master start_ebml_master(AVIOContext *pb, unsigned int elementid,
276  uint64_t expectedsize)
277 {
278  int bytes = expectedsize ? ebml_num_size(expectedsize) : 8;
279  put_ebml_id(pb, elementid);
280  put_ebml_size_unknown(pb, bytes);
281  return (ebml_master) {avio_tell(pb), bytes };
282 }
283 
285 {
286  int64_t pos = avio_tell(pb);
287 
288  if (avio_seek(pb, master.pos - master.sizebytes, SEEK_SET) < 0)
289  return;
290  put_ebml_num(pb, pos - master.pos, master.sizebytes);
291  avio_seek(pb, pos, SEEK_SET);
292 }
293 
294 static void put_xiph_size(AVIOContext *pb, int size)
295 {
296  ffio_fill(pb, 255, size / 255);
297  avio_w8(pb, size % 255);
298 }
299 
300 /**
301  * Initialize a mkv_seekhead element to be ready to index level 1 Matroska
302  * elements. If a maximum number of elements is specified, enough space
303  * will be reserved at the current file location to write a seek head of
304  * that size.
305  *
306  * @param segment_offset The absolute offset to the position in the file
307  * where the segment begins.
308  * @param numelements The maximum number of elements that will be indexed
309  * by this seek head, 0 if unlimited.
310  */
311 static mkv_seekhead *mkv_start_seekhead(AVIOContext *pb, int64_t segment_offset,
312  int numelements)
313 {
314  mkv_seekhead *new_seekhead = av_mallocz(sizeof(mkv_seekhead));
315  if (!new_seekhead)
316  return NULL;
317 
318  new_seekhead->segment_offset = segment_offset;
319 
320  if (numelements > 0) {
321  new_seekhead->filepos = avio_tell(pb);
322  // 21 bytes max for a seek entry, 10 bytes max for the SeekHead ID
323  // and size, and 3 bytes to guarantee that an EBML void element
324  // will fit afterwards
325  new_seekhead->reserved_size = numelements * MAX_SEEKENTRY_SIZE + 13;
326  new_seekhead->max_entries = numelements;
327  put_ebml_void(pb, new_seekhead->reserved_size);
328  }
329  return new_seekhead;
330 }
331 
332 static int mkv_add_seekhead_entry(mkv_seekhead *seekhead, unsigned int elementid, uint64_t filepos)
333 {
334  mkv_seekhead_entry *entries = seekhead->entries;
335 
336  // don't store more elements than we reserved space for
337  if (seekhead->max_entries > 0 && seekhead->max_entries <= seekhead->num_entries)
338  return -1;
339 
340  entries = av_realloc_array(entries, seekhead->num_entries + 1, sizeof(mkv_seekhead_entry));
341  if (!entries)
342  return AVERROR(ENOMEM);
343  seekhead->entries = entries;
344 
345  seekhead->entries[seekhead->num_entries].elementid = elementid;
346  seekhead->entries[seekhead->num_entries++].segmentpos = filepos - seekhead->segment_offset;
347 
348  return 0;
349 }
350 
351 /**
352  * Write the seek head to the file and free it. If a maximum number of
353  * elements was specified to mkv_start_seekhead(), the seek head will
354  * be written at the location reserved for it. Otherwise, it is written
355  * at the current location in the file.
356  *
357  * @return The file offset where the seekhead was written,
358  * -1 if an error occurred.
359  */
360 static int64_t mkv_write_seekhead(AVIOContext *pb, mkv_seekhead *seekhead)
361 {
362  ebml_master metaseek, seekentry;
363  int64_t currentpos;
364  int i;
365 
366  currentpos = avio_tell(pb);
367 
368  if (seekhead->reserved_size > 0) {
369  if (avio_seek(pb, seekhead->filepos, SEEK_SET) < 0) {
370  currentpos = -1;
371  goto fail;
372  }
373  }
374 
375  metaseek = start_ebml_master(pb, MATROSKA_ID_SEEKHEAD, seekhead->reserved_size);
376  for (i = 0; i < seekhead->num_entries; i++) {
377  mkv_seekhead_entry *entry = &seekhead->entries[i];
378 
380 
382  put_ebml_num(pb, ebml_id_size(entry->elementid), 0);
383  put_ebml_id(pb, entry->elementid);
384 
386  end_ebml_master(pb, seekentry);
387  }
388  end_ebml_master(pb, metaseek);
389 
390  if (seekhead->reserved_size > 0) {
391  uint64_t remaining = seekhead->filepos + seekhead->reserved_size - avio_tell(pb);
392  put_ebml_void(pb, remaining);
393  avio_seek(pb, currentpos, SEEK_SET);
394 
395  currentpos = seekhead->filepos;
396  }
397 fail:
398  av_freep(&seekhead->entries);
399  av_free(seekhead);
400 
401  return currentpos;
402 }
403 
404 static mkv_cues *mkv_start_cues(int64_t segment_offset)
405 {
406  mkv_cues *cues = av_mallocz(sizeof(mkv_cues));
407  if (!cues)
408  return NULL;
409 
410  cues->segment_offset = segment_offset;
411  return cues;
412 }
413 
414 static int mkv_add_cuepoint(mkv_cues *cues, int stream, int tracknum, int64_t ts,
415  int64_t cluster_pos, int64_t relative_pos, int64_t duration)
416 {
417  mkv_cuepoint *entries = cues->entries;
418 
419  if (ts < 0)
420  return 0;
421 
422  entries = av_realloc_array(entries, cues->num_entries + 1, sizeof(mkv_cuepoint));
423  if (!entries)
424  return AVERROR(ENOMEM);
425  cues->entries = entries;
426 
427  cues->entries[cues->num_entries].pts = ts;
428  cues->entries[cues->num_entries].stream_idx = stream;
429  cues->entries[cues->num_entries].tracknum = tracknum;
430  cues->entries[cues->num_entries].cluster_pos = cluster_pos - cues->segment_offset;
431  cues->entries[cues->num_entries].relative_pos = relative_pos;
432  cues->entries[cues->num_entries++].duration = duration;
433 
434  return 0;
435 }
436 
437 static int64_t mkv_write_cues(AVFormatContext *s, mkv_cues *cues, mkv_track *tracks, int num_tracks)
438 {
439  AVIOContext *pb = s->pb;
440  ebml_master cues_element;
441  int64_t currentpos;
442  int i, j;
443 
444  currentpos = avio_tell(pb);
445  cues_element = start_ebml_master(pb, MATROSKA_ID_CUES, 0);
446 
447  for (i = 0; i < cues->num_entries; i++) {
448  ebml_master cuepoint, track_positions;
449  mkv_cuepoint *entry = &cues->entries[i];
450  uint64_t pts = entry->pts;
451  int ctp_nb = 0;
452 
453  // Calculate the number of entries, so we know the element size
454  for (j = 0; j < num_tracks; j++)
455  tracks[j].has_cue = 0;
456  for (j = 0; j < cues->num_entries - i && entry[j].pts == pts; j++) {
457  int tracknum = entry[j].stream_idx;
458  av_assert0(tracknum>=0 && tracknum<num_tracks);
459  if (tracks[tracknum].has_cue && s->streams[tracknum]->codec->codec_type != AVMEDIA_TYPE_SUBTITLE)
460  continue;
461  tracks[tracknum].has_cue = 1;
462  ctp_nb ++;
463  }
464 
467 
468  // put all the entries from different tracks that have the exact same
469  // timestamp into the same CuePoint
470  for (j = 0; j < num_tracks; j++)
471  tracks[j].has_cue = 0;
472  for (j = 0; j < cues->num_entries - i && entry[j].pts == pts; j++) {
473  int tracknum = entry[j].stream_idx;
474  av_assert0(tracknum>=0 && tracknum<num_tracks);
475  if (tracks[tracknum].has_cue && s->streams[tracknum]->codec->codec_type != AVMEDIA_TYPE_SUBTITLE)
476  continue;
477  tracks[tracknum].has_cue = 1;
479  put_ebml_uint(pb, MATROSKA_ID_CUETRACK , entry[j].tracknum );
480  put_ebml_uint(pb, MATROSKA_ID_CUECLUSTERPOSITION , entry[j].cluster_pos);
481  put_ebml_uint(pb, MATROSKA_ID_CUERELATIVEPOSITION, entry[j].relative_pos);
482  if (entry[j].duration != -1)
484  end_ebml_master(pb, track_positions);
485  }
486  i += j - 1;
487  end_ebml_master(pb, cuepoint);
488  }
489  end_ebml_master(pb, cues_element);
490 
491  return currentpos;
492 }
493 
495 {
496  const uint8_t *header_start[3];
497  int header_len[3];
498  int first_header_size;
499  int j;
500 
501  if (codec->codec_id == AV_CODEC_ID_VORBIS)
502  first_header_size = 30;
503  else
504  first_header_size = 42;
505 
507  first_header_size, header_start, header_len) < 0) {
508  av_log(s, AV_LOG_ERROR, "Extradata corrupt.\n");
509  return -1;
510  }
511 
512  avio_w8(pb, 2); // number packets - 1
513  for (j = 0; j < 2; j++) {
514  put_xiph_size(pb, header_len[j]);
515  }
516  for (j = 0; j < 3; j++)
517  avio_write(pb, header_start[j], header_len[j]);
518 
519  return 0;
520 }
521 
523 {
524  if (codec->extradata && codec->extradata_size == 2)
525  avio_write(pb, codec->extradata, 2);
526  else
527  avio_wl16(pb, 0x403); // fallback to the version mentioned in matroska specs
528  return 0;
529 }
530 
532  AVIOContext *pb, AVCodecContext *codec)
533 {
534  int write_comment = (codec->channel_layout &&
535  !(codec->channel_layout & ~0x3ffffULL) &&
537  int ret = ff_flac_write_header(pb, codec->extradata, codec->extradata_size,
538  !write_comment);
539 
540  if (ret < 0)
541  return ret;
542 
543  if (write_comment) {
544  const char *vendor = (s->flags & AVFMT_FLAG_BITEXACT) ?
545  "Lavf" : LIBAVFORMAT_IDENT;
546  AVDictionary *dict = NULL;
547  uint8_t buf[32], *data, *p;
548  int64_t len;
549 
550  snprintf(buf, sizeof(buf), "0x%"PRIx64, codec->channel_layout);
551  av_dict_set(&dict, "WAVEFORMATEXTENSIBLE_CHANNEL_MASK", buf, 0);
552 
553  len = ff_vorbiscomment_length(dict, vendor);
554  if (len >= ((1<<24) - 4))
555  return AVERROR(EINVAL);
556 
557  data = av_malloc(len + 4);
558  if (!data) {
559  av_dict_free(&dict);
560  return AVERROR(ENOMEM);
561  }
562 
563  data[0] = 0x84;
564  AV_WB24(data + 1, len);
565 
566  p = data + 4;
567  ff_vorbiscomment_write(&p, &dict, vendor);
568 
569  avio_write(pb, data, len + 4);
570 
571  av_freep(&data);
572  av_dict_free(&dict);
573  }
574 
575  return 0;
576 }
577 
579  int *sample_rate, int *output_sample_rate)
580 {
581  MPEG4AudioConfig mp4ac;
582 
583  if (avpriv_mpeg4audio_get_config(&mp4ac, codec->extradata,
584  codec->extradata_size * 8, 1) < 0) {
585  av_log(s, AV_LOG_ERROR,
586  "Error parsing AAC extradata, unable to determine samplerate.\n");
587  return AVERROR(EINVAL);
588  }
589 
590  *sample_rate = mp4ac.sample_rate;
591  *output_sample_rate = mp4ac.ext_sample_rate;
592  return 0;
593 }
594 
596  AVCodecContext *codec,
597  AVIOContext *dyn_cp)
598 {
599  switch (codec->codec_id) {
600  case AV_CODEC_ID_VORBIS:
601  case AV_CODEC_ID_THEORA:
602  return put_xiph_codecpriv(s, dyn_cp, codec);
603  case AV_CODEC_ID_FLAC:
604  return put_flac_codecpriv(s, dyn_cp, codec);
605  case AV_CODEC_ID_WAVPACK:
606  return put_wv_codecpriv(dyn_cp, codec);
607  case AV_CODEC_ID_H264:
608  return ff_isom_write_avcc(dyn_cp, codec->extradata,
609  codec->extradata_size);
610  case AV_CODEC_ID_HEVC:
611  return ff_isom_write_hvcc(dyn_cp, codec->extradata,
612  codec->extradata_size, 0);
613  case AV_CODEC_ID_ALAC:
614  if (codec->extradata_size < 36) {
615  av_log(s, AV_LOG_ERROR,
616  "Invalid extradata found, ALAC expects a 36-byte "
617  "QuickTime atom.");
618  return AVERROR_INVALIDDATA;
619  } else
620  avio_write(dyn_cp, codec->extradata + 12,
621  codec->extradata_size - 12);
622  break;
623  default:
624  if (codec->codec_id == AV_CODEC_ID_PRORES &&
626  avio_wl32(dyn_cp, codec->codec_tag);
627  } else if (codec->extradata_size && codec->codec_id != AV_CODEC_ID_TTA)
628  avio_write(dyn_cp, codec->extradata, codec->extradata_size);
629  }
630 
631  return 0;
632 }
633 
635  AVCodecContext *codec, int native_id,
636  int qt_id)
637 {
638  AVIOContext *dyn_cp;
639  uint8_t *codecpriv;
640  int ret, codecpriv_size;
641 
642  ret = avio_open_dyn_buf(&dyn_cp);
643  if (ret < 0)
644  return ret;
645 
646  if (native_id) {
647  ret = mkv_write_native_codecprivate(s, codec, dyn_cp);
648  } else if (codec->codec_type == AVMEDIA_TYPE_VIDEO) {
649  if (qt_id) {
650  if (!codec->codec_tag)
652  codec->codec_id);
653  if (codec->extradata_size) {
656  ) {
657  int i;
658  avio_wb32(dyn_cp, 0x5a + codec->extradata_size);
659  avio_wl32(dyn_cp, codec->codec_tag);
660  for(i = 0; i < 0x5a - 8; i++)
661  avio_w8(dyn_cp, 0);
662  }
663  avio_write(dyn_cp, codec->extradata, codec->extradata_size);
664  }
665  } else {
667  av_log(s, AV_LOG_WARNING, "codec %s is not supported by this format\n",
668  avcodec_get_name(codec->codec_id));
669 
670  if (!codec->codec_tag)
672  codec->codec_id);
673  if (!codec->codec_tag && codec->codec_id != AV_CODEC_ID_RAWVIDEO) {
674  av_log(s, AV_LOG_ERROR, "No bmp codec tag found for codec %s\n",
675  avcodec_get_name(codec->codec_id));
676  ret = AVERROR(EINVAL);
677  }
678 
679  ff_put_bmp_header(dyn_cp, codec, ff_codec_bmp_tags, 0, 0);
680  }
681  } else if (codec->codec_type == AVMEDIA_TYPE_AUDIO) {
682  unsigned int tag;
684  if (!tag) {
685  av_log(s, AV_LOG_ERROR, "No wav codec tag found for codec %s\n",
686  avcodec_get_name(codec->codec_id));
687  ret = AVERROR(EINVAL);
688  }
689  if (!codec->codec_tag)
690  codec->codec_tag = tag;
691 
693  }
694 
695  codecpriv_size = avio_close_dyn_buf(dyn_cp, &codecpriv);
696  if (codecpriv_size)
698  codecpriv_size);
699  av_free(codecpriv);
700  return ret;
701 }
702 
703 
705  AVStream *st, int mode, int *h_width, int *h_height)
706 {
707  int i;
708  int ret = 0;
711 
712  *h_width = 1;
713  *h_height = 1;
714  // convert metadata into proper side data and add it to the stream
715  if ((tag = av_dict_get(st->metadata, "stereo_mode", NULL, 0)) ||
716  (tag = av_dict_get( s->metadata, "stereo_mode", NULL, 0))) {
717  int stereo_mode = atoi(tag->value);
718 
719  for (i=0; i<MATROSKA_VIDEO_STEREOMODE_TYPE_NB; i++)
720  if (!strcmp(tag->value, ff_matroska_video_stereo_mode[i])){
721  stereo_mode = i;
722  break;
723  }
724 
725  if (stereo_mode < MATROSKA_VIDEO_STEREOMODE_TYPE_NB &&
726  stereo_mode != 10 && stereo_mode != 12) {
727  int ret = ff_mkv_stereo3d_conv(st, stereo_mode);
728  if (ret < 0)
729  return ret;
730  }
731  }
732 
733  // iterate to find the stereo3d side data
734  for (i = 0; i < st->nb_side_data; i++) {
735  AVPacketSideData sd = st->side_data[i];
736  if (sd.type == AV_PKT_DATA_STEREO3D) {
737  AVStereo3D *stereo = (AVStereo3D *)sd.data;
738 
739  switch (stereo->type) {
740  case AV_STEREO3D_2D:
742  break;
744  format = (stereo->flags & AV_STEREO3D_FLAG_INVERT)
747  *h_width = 2;
748  break;
751  if (stereo->flags & AV_STEREO3D_FLAG_INVERT)
752  format--;
753  *h_height = 2;
754  break;
757  if (stereo->flags & AV_STEREO3D_FLAG_INVERT)
758  format--;
759  break;
760  case AV_STEREO3D_LINES:
762  if (stereo->flags & AV_STEREO3D_FLAG_INVERT)
763  format--;
764  *h_height = 2;
765  break;
766  case AV_STEREO3D_COLUMNS:
768  if (stereo->flags & AV_STEREO3D_FLAG_INVERT)
769  format--;
770  *h_width = 2;
771  break;
774  if (stereo->flags & AV_STEREO3D_FLAG_INVERT)
775  format++;
776  break;
777  }
778  break;
779  }
780  }
781 
782  if (format == MATROSKA_VIDEO_STEREOMODE_TYPE_NB)
783  return ret;
784 
785  // if webm, do not write unsupported modes
786  if ((mode == MODE_WEBM &&
789  || format >= MATROSKA_VIDEO_STEREOMODE_TYPE_NB) {
790  av_log(s, AV_LOG_ERROR,
791  "The specified stereo mode is not valid.\n");
793  return AVERROR(EINVAL);
794  }
795 
796  // write StereoMode if format is valid
798 
799  return ret;
800 }
801 
803  int i, AVIOContext *pb, int default_stream_exists)
804 {
805  AVStream *st = s->streams[i];
806  AVCodecContext *codec = st->codec;
807  ebml_master subinfo, track;
808  int native_id = 0;
809  int qt_id = 0;
810  int bit_depth = av_get_bits_per_sample(codec->codec_id);
811  int sample_rate = codec->sample_rate;
812  int output_sample_rate = 0;
813  int display_width_div = 1;
814  int display_height_div = 1;
815  int j, ret;
817 
818  // ms precision is the de-facto standard timescale for mkv files
819  avpriv_set_pts_info(st, 64, 1, 1000);
820 
821  if (codec->codec_type == AVMEDIA_TYPE_ATTACHMENT) {
822  mkv->have_attachments = 1;
823  return 0;
824  }
825 
826  if (!bit_depth && codec->codec_id != AV_CODEC_ID_ADPCM_G726)
827  bit_depth = av_get_bytes_per_sample(codec->sample_fmt) << 3;
828  if (!bit_depth)
829  bit_depth = codec->bits_per_coded_sample;
830 
831  if (codec->codec_id == AV_CODEC_ID_AAC) {
832  ret = get_aac_sample_rates(s, codec, &sample_rate, &output_sample_rate);
833  if (ret < 0)
834  return ret;
835  }
836 
839  mkv->is_dash ? mkv->dash_track_number : i + 1);
841  mkv->is_dash ? mkv->dash_track_number : i + 1);
842  put_ebml_uint (pb, MATROSKA_ID_TRACKFLAGLACING , 0); // no lacing (yet)
843 
844  if ((tag = av_dict_get(st->metadata, "title", NULL, 0)))
846  tag = av_dict_get(st->metadata, "language", NULL, 0);
847  if (mkv->mode != MODE_WEBM || codec->codec_id != AV_CODEC_ID_WEBVTT) {
848  put_ebml_string(pb, MATROSKA_ID_TRACKLANGUAGE, tag && tag->value ? tag->value:"und");
849  } else if (tag && tag->value) {
851  }
852 
853  // The default value for TRACKFLAGDEFAULT is 1, so add element
854  // if we need to clear it.
855  if (default_stream_exists && !(st->disposition & AV_DISPOSITION_DEFAULT))
857 
860 
861  if (mkv->mode == MODE_WEBM && codec->codec_id == AV_CODEC_ID_WEBVTT) {
862  const char *codec_id;
864  codec_id = "D_WEBVTT/CAPTIONS";
865  native_id = MATROSKA_TRACK_TYPE_SUBTITLE;
866  } else if (st->disposition & AV_DISPOSITION_DESCRIPTIONS) {
867  codec_id = "D_WEBVTT/DESCRIPTIONS";
868  native_id = MATROSKA_TRACK_TYPE_METADATA;
869  } else if (st->disposition & AV_DISPOSITION_METADATA) {
870  codec_id = "D_WEBVTT/METADATA";
871  native_id = MATROSKA_TRACK_TYPE_METADATA;
872  } else {
873  codec_id = "D_WEBVTT/SUBTITLES";
874  native_id = MATROSKA_TRACK_TYPE_SUBTITLE;
875  }
876  put_ebml_string(pb, MATROSKA_ID_CODECID, codec_id);
877  } else {
878  // look for a codec ID string specific to mkv to use,
879  // if none are found, use AVI codes
880  for (j = 0; ff_mkv_codec_tags[j].id != AV_CODEC_ID_NONE; j++) {
881  if (ff_mkv_codec_tags[j].id == codec->codec_id) {
883  native_id = 1;
884  break;
885  }
886  }
887  if (codec->codec_id == AV_CODEC_ID_RAWVIDEO && !codec->codec_tag) {
888  if (mkv->allow_raw_vfw) {
889  native_id = 0;
890  } else {
891  av_log(s, AV_LOG_ERROR, "Raw RGB is not supported Natively in Matroska, you can use AVI or NUT or\n"
892  "If you would like to store it anyway using VFW mode, enable allow_raw_vfw (-allow_raw_vfw 1)\n");
893  return AVERROR(EINVAL);
894  }
895  }
896  }
897 
898  if (codec->codec_type == AVMEDIA_TYPE_AUDIO && codec->initial_padding && codec->codec_id == AV_CODEC_ID_OPUS) {
899  int64_t codecdelay = av_rescale_q(codec->initial_padding,
900  (AVRational){ 1, codec->sample_rate },
901  (AVRational){ 1, 1000000000 });
902  if (codecdelay < 0) {
903  av_log(s, AV_LOG_ERROR, "Initial padding is invalid\n");
904  return AVERROR(EINVAL);
905  }
906 // mkv->tracks[i].ts_offset = av_rescale_q(codec->initial_padding,
907 // (AVRational){ 1, codec->sample_rate },
908 // st->time_base);
909 
910  put_ebml_uint(pb, MATROSKA_ID_CODECDELAY, codecdelay);
911  }
912  if (codec->codec_id == AV_CODEC_ID_OPUS) {
914  }
915 
916  if (mkv->mode == MODE_WEBM && !(codec->codec_id == AV_CODEC_ID_VP8 ||
917  codec->codec_id == AV_CODEC_ID_VP9 ||
918  codec->codec_id == AV_CODEC_ID_OPUS ||
919  codec->codec_id == AV_CODEC_ID_VORBIS ||
920  codec->codec_id == AV_CODEC_ID_WEBVTT)) {
921  av_log(s, AV_LOG_ERROR,
922  "Only VP8 or VP9 video and Vorbis or Opus audio and WebVTT subtitles are supported for WebM.\n");
923  return AVERROR(EINVAL);
924  }
925 
926  switch (codec->codec_type) {
927  case AVMEDIA_TYPE_VIDEO:
929 
930  if( st->avg_frame_rate.num > 0 && st->avg_frame_rate.den > 0
931  && 1.0/av_q2d(st->avg_frame_rate) > av_q2d(codec->time_base))
933  else
935 
936  if (!native_id &&
939  codec->codec_id == AV_CODEC_ID_SVQ1 ||
940  codec->codec_id == AV_CODEC_ID_SVQ3 ||
941  codec->codec_id == AV_CODEC_ID_CINEPAK))
942  qt_id = 1;
943 
944  if (qt_id)
945  put_ebml_string(pb, MATROSKA_ID_CODECID, "V_QUICKTIME");
946  else if (!native_id) {
947  // if there is no mkv-specific codec ID, use VFW mode
948  put_ebml_string(pb, MATROSKA_ID_CODECID, "V_MS/VFW/FOURCC");
949  mkv->tracks[i].write_dts = 1;
951  }
952 
953  subinfo = start_ebml_master(pb, MATROSKA_ID_TRACKVIDEO, 0);
954  // XXX: interlace flag?
957 
958  // check both side data and metadata for stereo information,
959  // write the result to the bitstream if any is found
960  ret = mkv_write_stereo_mode(s, pb, st, mkv->mode,
961  &display_width_div,
962  &display_height_div);
963  if (ret < 0)
964  return ret;
965 
966  if (((tag = av_dict_get(st->metadata, "alpha_mode", NULL, 0)) && atoi(tag->value)) ||
967  ((tag = av_dict_get( s->metadata, "alpha_mode", NULL, 0)) && atoi(tag->value)) ||
968  (codec->pix_fmt == AV_PIX_FMT_YUVA420P)) {
970  }
971 
972  // write DisplayWidth and DisplayHeight, they contain the size of
973  // a single source view and/or the display aspect ratio
974  if (st->sample_aspect_ratio.num) {
975  int64_t d_width = av_rescale(codec->width, st->sample_aspect_ratio.num, st->sample_aspect_ratio.den);
976  if (d_width > INT_MAX) {
977  av_log(s, AV_LOG_ERROR, "Overflow in display width\n");
978  return AVERROR(EINVAL);
979  }
980  put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYWIDTH , d_width / display_width_div);
981  put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYHEIGHT, codec->height / display_height_div);
982  } else if (display_width_div != 1 || display_height_div != 1) {
983  put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYWIDTH , codec->width / display_width_div);
984  put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYHEIGHT, codec->height / display_height_div);
985  }
986 
987  if (codec->codec_id == AV_CODEC_ID_RAWVIDEO) {
988  uint32_t color_space = av_le2ne32(codec->codec_tag);
989  put_ebml_binary(pb, MATROSKA_ID_VIDEOCOLORSPACE, &color_space, sizeof(color_space));
990  }
991 
992  end_ebml_master(pb, subinfo);
993  break;
994 
995  case AVMEDIA_TYPE_AUDIO:
997 
998  if (!native_id)
999  // no mkv-specific ID, use ACM mode
1000  put_ebml_string(pb, MATROSKA_ID_CODECID, "A_MS/ACM");
1001 
1002  subinfo = start_ebml_master(pb, MATROSKA_ID_TRACKAUDIO, 0);
1004  put_ebml_float (pb, MATROSKA_ID_AUDIOSAMPLINGFREQ, sample_rate);
1005  if (output_sample_rate)
1006  put_ebml_float(pb, MATROSKA_ID_AUDIOOUTSAMPLINGFREQ, output_sample_rate);
1007  if (bit_depth)
1008  put_ebml_uint(pb, MATROSKA_ID_AUDIOBITDEPTH, bit_depth);
1009  end_ebml_master(pb, subinfo);
1010  break;
1011 
1012  case AVMEDIA_TYPE_SUBTITLE:
1013  if (!native_id) {
1014  av_log(s, AV_LOG_ERROR, "Subtitle codec %d is not supported.\n", codec->codec_id);
1015  return AVERROR(ENOSYS);
1016  }
1017 
1018  if (mkv->mode != MODE_WEBM || codec->codec_id != AV_CODEC_ID_WEBVTT)
1019  native_id = MATROSKA_TRACK_TYPE_SUBTITLE;
1020 
1021  put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, native_id);
1022  break;
1023  default:
1024  av_log(s, AV_LOG_ERROR, "Only audio, video, and subtitles are supported for Matroska.\n");
1025  return AVERROR(EINVAL);
1026  }
1027 
1028  if (mkv->mode != MODE_WEBM || codec->codec_id != AV_CODEC_ID_WEBVTT) {
1029  ret = mkv_write_codecprivate(s, pb, codec, native_id, qt_id);
1030  if (ret < 0)
1031  return ret;
1032  }
1033 
1034  end_ebml_master(pb, track);
1035 
1036  return 0;
1037 }
1038 
1040 {
1041  MatroskaMuxContext *mkv = s->priv_data;
1042  AVIOContext *pb = s->pb;
1043  ebml_master tracks;
1044  int i, ret, default_stream_exists = 0;
1045 
1047  if (ret < 0)
1048  return ret;
1049 
1050  tracks = start_ebml_master(pb, MATROSKA_ID_TRACKS, 0);
1051  for (i = 0; i < s->nb_streams; i++) {
1052  AVStream *st = s->streams[i];
1053  default_stream_exists |= st->disposition & AV_DISPOSITION_DEFAULT;
1054  }
1055  for (i = 0; i < s->nb_streams; i++) {
1056  ret = mkv_write_track(s, mkv, i, pb, default_stream_exists);
1057  if (ret < 0)
1058  return ret;
1059  }
1060  end_ebml_master(pb, tracks);
1061  return 0;
1062 }
1063 
1065 {
1066  MatroskaMuxContext *mkv = s->priv_data;
1067  AVIOContext *pb = s->pb;
1068  ebml_master chapters, editionentry;
1069  AVRational scale = {1, 1E9};
1070  int i, ret;
1071 
1072  if (!s->nb_chapters || mkv->wrote_chapters)
1073  return 0;
1074 
1076  if (ret < 0) return ret;
1077 
1078  chapters = start_ebml_master(pb, MATROSKA_ID_CHAPTERS , 0);
1079  editionentry = start_ebml_master(pb, MATROSKA_ID_EDITIONENTRY, 0);
1082  for (i = 0; i < s->nb_chapters; i++) {
1083  ebml_master chapteratom, chapterdisplay;
1084  AVChapter *c = s->chapters[i];
1085  int64_t chapterstart = av_rescale_q(c->start, c->time_base, scale);
1086  int64_t chapterend = av_rescale_q(c->end, c->time_base, scale);
1087  AVDictionaryEntry *t = NULL;
1088  if (chapterstart < 0 || chapterstart > chapterend)
1089  return AVERROR_INVALIDDATA;
1090 
1091  chapteratom = start_ebml_master(pb, MATROSKA_ID_CHAPTERATOM, 0);
1093  put_ebml_uint(pb, MATROSKA_ID_CHAPTERTIMESTART, chapterstart);
1094  put_ebml_uint(pb, MATROSKA_ID_CHAPTERTIMEEND, chapterend);
1097  if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
1098  chapterdisplay = start_ebml_master(pb, MATROSKA_ID_CHAPTERDISPLAY, 0);
1101  end_ebml_master(pb, chapterdisplay);
1102  }
1103  end_ebml_master(pb, chapteratom);
1104  }
1105  end_ebml_master(pb, editionentry);
1106  end_ebml_master(pb, chapters);
1107 
1108  mkv->wrote_chapters = 1;
1109  return 0;
1110 }
1111 
1113 {
1114  uint8_t *key = av_strdup(t->key);
1115  uint8_t *p = key;
1116  const uint8_t *lang = NULL;
1117  ebml_master tag;
1118 
1119  if (!key)
1120  return AVERROR(ENOMEM);
1121 
1122  if ((p = strrchr(p, '-')) &&
1123  (lang = av_convert_lang_to(p + 1, AV_LANG_ISO639_2_BIBL)))
1124  *p = 0;
1125 
1126  p = key;
1127  while (*p) {
1128  if (*p == ' ')
1129  *p = '_';
1130  else if (*p >= 'a' && *p <= 'z')
1131  *p -= 'a' - 'A';
1132  p++;
1133  }
1134 
1137  if (lang)
1140  end_ebml_master(pb, tag);
1141 
1142  av_freep(&key);
1143  return 0;
1144 }
1145 
1146 static int mkv_write_tag(AVFormatContext *s, AVDictionary *m, unsigned int elementid,
1147  unsigned int uid, ebml_master *tags)
1148 {
1149  MatroskaMuxContext *mkv = s->priv_data;
1150  ebml_master tag, targets;
1151  AVDictionaryEntry *t = NULL;
1152  int ret;
1153 
1154  if (!tags->pos) {
1156  if (ret < 0) return ret;
1157 
1158  *tags = start_ebml_master(s->pb, MATROSKA_ID_TAGS, 0);
1159  }
1160 
1161  tag = start_ebml_master(s->pb, MATROSKA_ID_TAG, 0);
1162  targets = start_ebml_master(s->pb, MATROSKA_ID_TAGTARGETS, 0);
1163  if (elementid)
1164  put_ebml_uint(s->pb, elementid, uid);
1165  end_ebml_master(s->pb, targets);
1166 
1167  while ((t = av_dict_get(m, "", t, AV_DICT_IGNORE_SUFFIX))) {
1168  if (av_strcasecmp(t->key, "title") &&
1169  av_strcasecmp(t->key, "stereo_mode") &&
1170  av_strcasecmp(t->key, "encoding_tool")) {
1171  ret = mkv_write_simpletag(s->pb, t);
1172  if (ret < 0)
1173  return ret;
1174  }
1175  }
1176 
1177  end_ebml_master(s->pb, tag);
1178  return 0;
1179 }
1180 
1182 {
1183  AVDictionaryEntry *t = NULL;
1184 
1185  while ((t = av_dict_get(m, "", t, AV_DICT_IGNORE_SUFFIX)))
1186  if (av_strcasecmp(t->key, "title") && av_strcasecmp(t->key, "stereo_mode"))
1187  return 1;
1188 
1189  return 0;
1190 }
1191 
1193 {
1194  MatroskaMuxContext *mkv = s->priv_data;
1195  ebml_master tags = {0};
1196  int i, ret;
1197 
1199 
1200  if (mkv_check_tag(s->metadata)) {
1201  ret = mkv_write_tag(s, s->metadata, 0, 0, &tags);
1202  if (ret < 0) return ret;
1203  }
1204 
1205  for (i = 0; i < s->nb_streams; i++) {
1206  AVStream *st = s->streams[i];
1207 
1208  if (!mkv_check_tag(st->metadata))
1209  continue;
1210 
1211  ret = mkv_write_tag(s, st->metadata, MATROSKA_ID_TAGTARGETS_TRACKUID, i + 1, &tags);
1212  if (ret < 0) return ret;
1213  }
1214 
1215  for (i = 0; i < s->nb_chapters; i++) {
1216  AVChapter *ch = s->chapters[i];
1217 
1218  if (!mkv_check_tag(ch->metadata))
1219  continue;
1220 
1222  if (ret < 0) return ret;
1223  }
1224 
1225  if (tags.pos)
1226  end_ebml_master(s->pb, tags);
1227  return 0;
1228 }
1229 
1231 {
1232  MatroskaMuxContext *mkv = s->priv_data;
1233  AVIOContext *pb = s->pb;
1234  ebml_master attachments;
1235  AVLFG c;
1236  int i, ret;
1237 
1238  if (!mkv->have_attachments)
1239  return 0;
1240 
1242 
1244  if (ret < 0) return ret;
1245 
1246  attachments = start_ebml_master(pb, MATROSKA_ID_ATTACHMENTS, 0);
1247 
1248  for (i = 0; i < s->nb_streams; i++) {
1249  AVStream *st = s->streams[i];
1250  ebml_master attached_file;
1251  AVDictionaryEntry *t;
1252  const char *mimetype = NULL;
1253  uint64_t fileuid;
1254 
1256  continue;
1257 
1258  attached_file = start_ebml_master(pb, MATROSKA_ID_ATTACHEDFILE, 0);
1259 
1260  if (t = av_dict_get(st->metadata, "title", NULL, 0))
1262  if (!(t = av_dict_get(st->metadata, "filename", NULL, 0))) {
1263  av_log(s, AV_LOG_ERROR, "Attachment stream %d has no filename tag.\n", i);
1264  return AVERROR(EINVAL);
1265  }
1267  if (t = av_dict_get(st->metadata, "mimetype", NULL, 0))
1268  mimetype = t->value;
1269  else if (st->codec->codec_id != AV_CODEC_ID_NONE ) {
1270  int i;
1271  for (i = 0; ff_mkv_mime_tags[i].id != AV_CODEC_ID_NONE; i++)
1272  if (ff_mkv_mime_tags[i].id == st->codec->codec_id) {
1273  mimetype = ff_mkv_mime_tags[i].str;
1274  break;
1275  }
1276  for (i = 0; ff_mkv_image_mime_tags[i].id != AV_CODEC_ID_NONE; i++)
1277  if (ff_mkv_image_mime_tags[i].id == st->codec->codec_id) {
1278  mimetype = ff_mkv_image_mime_tags[i].str;
1279  break;
1280  }
1281  }
1282  if (!mimetype) {
1283  av_log(s, AV_LOG_ERROR, "Attachment stream %d has no mimetype tag and "
1284  "it cannot be deduced from the codec id.\n", i);
1285  return AVERROR(EINVAL);
1286  }
1287 
1288  if (s->flags & AVFMT_FLAG_BITEXACT) {
1289  struct AVSHA *sha = av_sha_alloc();
1290  uint8_t digest[20];
1291  if (!sha)
1292  return AVERROR(ENOMEM);
1293  av_sha_init(sha, 160);
1295  av_sha_final(sha, digest);
1296  av_free(sha);
1297  fileuid = AV_RL64(digest);
1298  } else {
1299  fileuid = av_lfg_get(&c);
1300  }
1301  av_log(s, AV_LOG_VERBOSE, "Using %.16"PRIx64" for attachment %d\n",
1302  fileuid, i);
1303 
1306  put_ebml_uint(pb, MATROSKA_ID_FILEUID, fileuid);
1307  end_ebml_master(pb, attached_file);
1308  }
1309  end_ebml_master(pb, attachments);
1310 
1311  return 0;
1312 }
1313 
1315 {
1316  MatroskaMuxContext *mkv = s->priv_data;
1317  AVIOContext *pb = s->pb;
1318  ebml_master ebml_header, segment_info;
1320  int ret, i, version = 2;
1321 
1322  if (!strcmp(s->oformat->name, "webm"))
1323  mkv->mode = MODE_WEBM;
1324  else
1325  mkv->mode = MODE_MATROSKAv2;
1326 
1327  if (s->avoid_negative_ts < 0) {
1328  s->avoid_negative_ts = 1;
1330  }
1331 
1332  if (mkv->mode != MODE_WEBM ||
1333  av_dict_get(s->metadata, "stereo_mode", NULL, 0) ||
1334  av_dict_get(s->metadata, "alpha_mode", NULL, 0))
1335  version = 4;
1336 
1337  for (i = 0; i < s->nb_streams; i++) {
1338  if (s->streams[i]->codec->codec_id == AV_CODEC_ID_ATRAC3 ||
1339  s->streams[i]->codec->codec_id == AV_CODEC_ID_COOK ||
1341  s->streams[i]->codec->codec_id == AV_CODEC_ID_SIPR ||
1342  s->streams[i]->codec->codec_id == AV_CODEC_ID_RV10 ||
1343  s->streams[i]->codec->codec_id == AV_CODEC_ID_RV20) {
1344  av_log(s, AV_LOG_ERROR,
1345  "The Matroska muxer does not yet support muxing %s\n",
1347  return AVERROR_PATCHWELCOME;
1348  }
1349  if (s->streams[i]->codec->codec_id == AV_CODEC_ID_OPUS ||
1350  av_dict_get(s->streams[i]->metadata, "stereo_mode", NULL, 0) ||
1351  av_dict_get(s->streams[i]->metadata, "alpha_mode", NULL, 0))
1352  version = 4;
1353  }
1354 
1355  mkv->tracks = av_mallocz_array(s->nb_streams, sizeof(*mkv->tracks));
1356  if (!mkv->tracks)
1357  return AVERROR(ENOMEM);
1358 
1359  ebml_header = start_ebml_master(pb, EBML_ID_HEADER, 0);
1365  put_ebml_uint (pb, EBML_ID_DOCTYPEVERSION , version);
1367  end_ebml_master(pb, ebml_header);
1368 
1370  mkv->segment_offset = avio_tell(pb);
1371 
1372  // we write 2 seek heads - one at the end of the file to point to each
1373  // cluster, and one at the beginning to point to all other level one
1374  // elements (including the seek head at the end of the file), which
1375  // isn't more than 10 elements if we only write one of each other
1376  // currently defined level 1 element
1377  mkv->main_seekhead = mkv_start_seekhead(pb, mkv->segment_offset, 10);
1378  if (!mkv->main_seekhead)
1379  return AVERROR(ENOMEM);
1380 
1382  if (ret < 0) return ret;
1383 
1384  segment_info = start_ebml_master(pb, MATROSKA_ID_INFO, 0);
1386  if ((tag = av_dict_get(s->metadata, "title", NULL, 0)))
1388  if (!(s->flags & AVFMT_FLAG_BITEXACT)) {
1389  uint32_t segment_uid[4];
1390  AVLFG lfg;
1391 
1393 
1394  for (i = 0; i < 4; i++)
1395  segment_uid[i] = av_lfg_get(&lfg);
1396 
1398  if ((tag = av_dict_get(s->metadata, "encoding_tool", NULL, 0)))
1400  else
1402  put_ebml_binary(pb, MATROSKA_ID_SEGMENTUID, segment_uid, 16);
1403  } else {
1404  const char *ident = "Lavf";
1407  }
1408 
1409  if (tag = av_dict_get(s->metadata, "creation_time", NULL, 0)) {
1410  // Adjust time so it's relative to 2001-01-01 and convert to nanoseconds.
1411  int64_t date_utc = (ff_iso8601_to_unix_time(tag->value) - 978307200) * 1000000000;
1412  uint8_t date_utc_buf[8];
1413  AV_WB64(date_utc_buf, date_utc);
1414  put_ebml_binary(pb, MATROSKA_ID_DATEUTC, date_utc_buf, 8);
1415  }
1416 
1417  // reserve space for the duration
1418  mkv->duration = 0;
1419  mkv->duration_offset = avio_tell(pb);
1420  put_ebml_void(pb, 11); // assumes double-precision float to be written
1421  end_ebml_master(pb, segment_info);
1422 
1423  ret = mkv_write_tracks(s);
1424  if (ret < 0)
1425  return ret;
1426 
1427  for (i = 0; i < s->nb_chapters; i++)
1428  mkv->chapter_id_offset = FFMAX(mkv->chapter_id_offset, 1LL - s->chapters[i]->id);
1429 
1430  if (mkv->mode != MODE_WEBM) {
1431  ret = mkv_write_chapters(s);
1432  if (ret < 0)
1433  return ret;
1434 
1435  ret = mkv_write_tags(s);
1436  if (ret < 0)
1437  return ret;
1438 
1439  ret = mkv_write_attachments(s);
1440  if (ret < 0)
1441  return ret;
1442  }
1443 
1444  if (!s->pb->seekable)
1446 
1447  mkv->cues = mkv_start_cues(mkv->segment_offset);
1448  if (!mkv->cues)
1449  return AVERROR(ENOMEM);
1450 
1451  if (pb->seekable && mkv->reserve_cues_space) {
1452  mkv->cues_pos = avio_tell(pb);
1454  }
1455 
1457  mkv->cur_audio_pkt.size = 0;
1458  mkv->cluster_pos = -1;
1459 
1460  avio_flush(pb);
1461 
1462  // start a new cluster every 5 MB or 5 sec, or 32k / 1 sec for streaming or
1463  // after 4k and on a keyframe
1464  if (pb->seekable) {
1465  if (mkv->cluster_time_limit < 0)
1466  mkv->cluster_time_limit = 5000;
1467  if (mkv->cluster_size_limit < 0)
1468  mkv->cluster_size_limit = 5 * 1024 * 1024;
1469  } else {
1470  if (mkv->cluster_time_limit < 0)
1471  mkv->cluster_time_limit = 1000;
1472  if (mkv->cluster_size_limit < 0)
1473  mkv->cluster_size_limit = 32 * 1024;
1474  }
1475 
1476  return 0;
1477 }
1478 
1479 static int mkv_blockgroup_size(int pkt_size)
1480 {
1481  int size = pkt_size + 4;
1482  size += ebml_num_size(size);
1483  size += 2; // EBML ID for block and block duration
1484  size += 8; // max size of block duration
1485  size += ebml_num_size(size);
1486  size += 1; // blockgroup EBML ID
1487  return size;
1488 }
1489 
1490 static int mkv_strip_wavpack(const uint8_t *src, uint8_t **pdst, int *size)
1491 {
1492  uint8_t *dst;
1493  int srclen = *size;
1494  int offset = 0;
1495  int ret;
1496 
1497  dst = av_malloc(srclen);
1498  if (!dst)
1499  return AVERROR(ENOMEM);
1500 
1501  while (srclen >= WV_HEADER_SIZE) {
1502  WvHeader header;
1503 
1504  ret = ff_wv_parse_header(&header, src);
1505  if (ret < 0)
1506  goto fail;
1507  src += WV_HEADER_SIZE;
1508  srclen -= WV_HEADER_SIZE;
1509 
1510  if (srclen < header.blocksize) {
1511  ret = AVERROR_INVALIDDATA;
1512  goto fail;
1513  }
1514 
1515  if (header.initial) {
1516  AV_WL32(dst + offset, header.samples);
1517  offset += 4;
1518  }
1519  AV_WL32(dst + offset, header.flags);
1520  AV_WL32(dst + offset + 4, header.crc);
1521  offset += 8;
1522 
1523  if (!(header.initial && header.final)) {
1524  AV_WL32(dst + offset, header.blocksize);
1525  offset += 4;
1526  }
1527 
1528  memcpy(dst + offset, src, header.blocksize);
1529  src += header.blocksize;
1530  srclen -= header.blocksize;
1531  offset += header.blocksize;
1532  }
1533 
1534  *pdst = dst;
1535  *size = offset;
1536 
1537  return 0;
1538 fail:
1539  av_freep(&dst);
1540  return ret;
1541 }
1542 
1544  unsigned int blockid, AVPacket *pkt, int flags)
1545 {
1546  MatroskaMuxContext *mkv = s->priv_data;
1547  AVCodecContext *codec = s->streams[pkt->stream_index]->codec;
1548  uint8_t *data = NULL, *side_data = NULL;
1549  int offset = 0, size = pkt->size, side_data_size = 0;
1550  int64_t ts = mkv->tracks[pkt->stream_index].write_dts ? pkt->dts : pkt->pts;
1551  uint64_t additional_id = 0;
1552  int64_t discard_padding = 0;
1553  ebml_master block_group, block_additions, block_more;
1554 
1555  av_log(s, AV_LOG_DEBUG, "Writing block at offset %" PRIu64 ", size %d, "
1556  "pts %" PRId64 ", dts %" PRId64 ", duration %d, flags %d\n",
1557  avio_tell(pb), pkt->size, pkt->pts, pkt->dts, pkt->duration, flags);
1558  if (codec->codec_id == AV_CODEC_ID_H264 && codec->extradata_size > 0 &&
1559  (AV_RB24(codec->extradata) == 1 || AV_RB32(codec->extradata) == 1))
1560  ff_avc_parse_nal_units_buf(pkt->data, &data, &size);
1561  else if (codec->codec_id == AV_CODEC_ID_HEVC && codec->extradata_size > 6 &&
1562  (AV_RB24(codec->extradata) == 1 || AV_RB32(codec->extradata) == 1))
1563  /* extradata is Annex B, assume the bitstream is too and convert it */
1564  ff_hevc_annexb2mp4_buf(pkt->data, &data, &size, 0, NULL);
1565  else if (codec->codec_id == AV_CODEC_ID_WAVPACK) {
1566  int ret = mkv_strip_wavpack(pkt->data, &data, &size);
1567  if (ret < 0) {
1568  av_log(s, AV_LOG_ERROR, "Error stripping a WavPack packet.\n");
1569  return;
1570  }
1571  } else
1572  data = pkt->data;
1573 
1574  if (codec->codec_id == AV_CODEC_ID_PRORES) {
1575  /* Matroska specification requires to remove the first QuickTime atom
1576  */
1577  size -= 8;
1578  offset = 8;
1579  }
1580 
1581  side_data = av_packet_get_side_data(pkt,
1583  &side_data_size);
1584 
1585  if (side_data && side_data_size >= 10) {
1586  discard_padding = av_rescale_q(AV_RL32(side_data + 4),
1587  (AVRational){1, codec->sample_rate},
1588  (AVRational){1, 1000000000});
1589  }
1590 
1591  side_data = av_packet_get_side_data(pkt,
1593  &side_data_size);
1594  if (side_data) {
1595  additional_id = AV_RB64(side_data);
1596  side_data += 8;
1597  side_data_size -= 8;
1598  }
1599 
1600  if ((side_data_size && additional_id == 1) || discard_padding) {
1601  block_group = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP, 0);
1602  blockid = MATROSKA_ID_BLOCK;
1603  }
1604 
1605  put_ebml_id(pb, blockid);
1606  put_ebml_num(pb, size + 4, 0);
1607  // this assumes stream_index is less than 126
1608  avio_w8(pb, 0x80 | (mkv->is_dash ? mkv->dash_track_number : (pkt->stream_index + 1)));
1609  avio_wb16(pb, ts - mkv->cluster_pts);
1610  avio_w8(pb, flags);
1611  avio_write(pb, data + offset, size);
1612  if (data != pkt->data)
1613  av_free(data);
1614 
1615  if (discard_padding) {
1616  put_ebml_sint(pb, MATROSKA_ID_DISCARDPADDING, discard_padding);
1617  }
1618 
1619  if (side_data_size && additional_id == 1) {
1620  block_additions = start_ebml_master(pb, MATROSKA_ID_BLOCKADDITIONS, 0);
1621  block_more = start_ebml_master(pb, MATROSKA_ID_BLOCKMORE, 0);
1624  put_ebml_num(pb, side_data_size, 0);
1625  avio_write(pb, side_data, side_data_size);
1626  end_ebml_master(pb, block_more);
1627  end_ebml_master(pb, block_additions);
1628  }
1629  if ((side_data_size && additional_id == 1) || discard_padding) {
1630  end_ebml_master(pb, block_group);
1631  }
1632 }
1633 
1635 {
1636  MatroskaMuxContext *mkv = s->priv_data;
1637  ebml_master blockgroup;
1638  int id_size, settings_size, size;
1639  uint8_t *id, *settings;
1640  int64_t ts = mkv->tracks[pkt->stream_index].write_dts ? pkt->dts : pkt->pts;
1641  const int flags = 0;
1642 
1643  id_size = 0;
1645  &id_size);
1646 
1647  settings_size = 0;
1649  &settings_size);
1650 
1651  size = id_size + 1 + settings_size + 1 + pkt->size;
1652 
1653  av_log(s, AV_LOG_DEBUG, "Writing block at offset %" PRIu64 ", size %d, "
1654  "pts %" PRId64 ", dts %" PRId64 ", duration %d, flags %d\n",
1655  avio_tell(pb), size, pkt->pts, pkt->dts, pkt->duration, flags);
1656 
1658 
1660  put_ebml_num(pb, size + 4, 0);
1661  avio_w8(pb, 0x80 | (pkt->stream_index + 1)); // this assumes stream_index is less than 126
1662  avio_wb16(pb, ts - mkv->cluster_pts);
1663  avio_w8(pb, flags);
1664  avio_printf(pb, "%.*s\n%.*s\n%.*s", id_size, id, settings_size, settings, pkt->size, pkt->data);
1665 
1667  end_ebml_master(pb, blockgroup);
1668 
1669  return pkt->duration;
1670 }
1671 
1673 {
1674  MatroskaMuxContext *mkv = s->priv_data;
1675  int bufsize;
1676  uint8_t *dyn_buf;
1677 
1678  if (!mkv->dyn_bc)
1679  return;
1680 
1681  bufsize = avio_close_dyn_buf(mkv->dyn_bc, &dyn_buf);
1682  avio_write(s->pb, dyn_buf, bufsize);
1683  av_free(dyn_buf);
1684  mkv->dyn_bc = NULL;
1685 }
1686 
1688 {
1689  MatroskaMuxContext *mkv = s->priv_data;
1690  AVIOContext *pb;
1691 
1692  if (s->pb->seekable) {
1693  pb = s->pb;
1694  } else {
1695  pb = mkv->dyn_bc;
1696  }
1697 
1698  av_log(s, AV_LOG_DEBUG,
1699  "Starting new cluster at offset %" PRIu64 " bytes, "
1700  "pts %" PRIu64 "dts %" PRIu64 "\n",
1701  avio_tell(pb), pkt->pts, pkt->dts);
1702  end_ebml_master(pb, mkv->cluster);
1703  mkv->cluster_pos = -1;
1704  if (mkv->dyn_bc)
1705  mkv_flush_dynbuf(s);
1706  avio_flush(s->pb);
1707 }
1708 
1710 {
1711  MatroskaMuxContext *mkv = s->priv_data;
1712  AVIOContext *pb = s->pb;
1713  AVCodecContext *codec = s->streams[pkt->stream_index]->codec;
1714  int keyframe = !!(pkt->flags & AV_PKT_FLAG_KEY);
1715  int duration = pkt->duration;
1716  int ret;
1717  int64_t ts = mkv->tracks[pkt->stream_index].write_dts ? pkt->dts : pkt->pts;
1718  int64_t relative_packet_pos;
1719  int dash_tracknum = mkv->is_dash ? mkv->dash_track_number : pkt->stream_index + 1;
1720 
1721  if (ts == AV_NOPTS_VALUE) {
1722  av_log(s, AV_LOG_ERROR, "Can't write packet with unknown timestamp\n");
1723  return AVERROR(EINVAL);
1724  }
1725  ts += mkv->tracks[pkt->stream_index].ts_offset;
1726 
1727  if (mkv->cluster_pos != -1) {
1728  int64_t cluster_time = ts - mkv->cluster_pts + mkv->tracks[pkt->stream_index].ts_offset;
1729  if ((int16_t)cluster_time != cluster_time) {
1730  av_log(s, AV_LOG_WARNING, "Starting new cluster due to timestamp\n");
1731  mkv_start_new_cluster(s, pkt);
1732  }
1733  }
1734 
1735  if (!s->pb->seekable) {
1736  if (!mkv->dyn_bc) {
1737  ret = avio_open_dyn_buf(&mkv->dyn_bc);
1738  if (ret < 0) {
1739  av_log(s, AV_LOG_ERROR, "Failed to open dynamic buffer\n");
1740  return ret;
1741  }
1742  }
1743  pb = mkv->dyn_bc;
1744  }
1745 
1746  if (mkv->cluster_pos == -1) {
1747  mkv->cluster_pos = avio_tell(s->pb);
1750  mkv->cluster_pts = FFMAX(0, ts);
1751  }
1752 
1753  relative_packet_pos = avio_tell(s->pb) - mkv->cluster.pos;
1754 
1755  if (codec->codec_type != AVMEDIA_TYPE_SUBTITLE) {
1756  mkv_write_block(s, pb, MATROSKA_ID_SIMPLEBLOCK, pkt, keyframe << 7);
1757  if (codec->codec_type == AVMEDIA_TYPE_VIDEO && keyframe || add_cue) {
1758  ret = mkv_add_cuepoint(mkv->cues, pkt->stream_index, dash_tracknum, ts, mkv->cluster_pos, relative_packet_pos, -1);
1759  if (ret < 0) return ret;
1760  }
1761  } else {
1762  if (codec->codec_id == AV_CODEC_ID_WEBVTT) {
1763  duration = mkv_write_vtt_blocks(s, pb, pkt);
1764  } else {
1766  mkv_blockgroup_size(pkt->size));
1767  /* For backward compatibility, prefer convergence_duration. */
1768  if (pkt->convergence_duration > 0) {
1769  duration = pkt->convergence_duration;
1770  }
1771  mkv_write_block(s, pb, MATROSKA_ID_BLOCK, pkt, 0);
1773  end_ebml_master(pb, blockgroup);
1774  }
1775 
1776  ret = mkv_add_cuepoint(mkv->cues, pkt->stream_index, dash_tracknum, ts,
1777  mkv->cluster_pos, relative_packet_pos, duration);
1778  if (ret < 0)
1779  return ret;
1780  }
1781 
1782  mkv->duration = FFMAX(mkv->duration, ts + duration);
1783  return 0;
1784 }
1785 
1787 {
1788  MatroskaMuxContext *mkv = s->priv_data;
1789  int codec_type = s->streams[pkt->stream_index]->codec->codec_type;
1790  int keyframe = !!(pkt->flags & AV_PKT_FLAG_KEY);
1791  int cluster_size;
1792  int64_t cluster_time;
1793  int ret;
1794  int start_new_cluster;
1795 
1796  if (mkv->tracks[pkt->stream_index].write_dts)
1797  cluster_time = pkt->dts - mkv->cluster_pts;
1798  else
1799  cluster_time = pkt->pts - mkv->cluster_pts;
1800  cluster_time += mkv->tracks[pkt->stream_index].ts_offset;
1801 
1802  // start a new cluster every 5 MB or 5 sec, or 32k / 1 sec for streaming or
1803  // after 4k and on a keyframe
1804  if (s->pb->seekable) {
1805  cluster_size = avio_tell(s->pb) - mkv->cluster_pos;
1806  } else {
1807  cluster_size = avio_tell(mkv->dyn_bc);
1808  }
1809 
1810  if (mkv->is_dash && codec_type == AVMEDIA_TYPE_VIDEO) {
1811  // WebM DASH specification states that the first block of every cluster
1812  // has to be a key frame. So for DASH video, we only create a cluster
1813  // on seeing key frames.
1814  start_new_cluster = keyframe;
1815  } else if (mkv->is_dash && codec_type == AVMEDIA_TYPE_AUDIO &&
1816  (mkv->cluster_pos == -1 ||
1817  cluster_time > mkv->cluster_time_limit)) {
1818  // For DASH audio, we create a Cluster based on cluster_time_limit
1819  start_new_cluster = 1;
1820  } else if (!mkv->is_dash &&
1821  (cluster_size > mkv->cluster_size_limit ||
1822  cluster_time > mkv->cluster_time_limit ||
1823  (codec_type == AVMEDIA_TYPE_VIDEO && keyframe &&
1824  cluster_size > 4 * 1024))) {
1825  start_new_cluster = 1;
1826  } else {
1827  start_new_cluster = 0;
1828  }
1829 
1830  if (mkv->cluster_pos != -1 && start_new_cluster) {
1831  mkv_start_new_cluster(s, pkt);
1832  }
1833 
1834  // check if we have an audio packet cached
1835  if (mkv->cur_audio_pkt.size > 0) {
1836  // for DASH audio, a CuePoint has to be added when there is a new cluster.
1838  mkv->is_dash ? start_new_cluster : 0);
1840  if (ret < 0) {
1841  av_log(s, AV_LOG_ERROR,
1842  "Could not write cached audio packet ret:%d\n", ret);
1843  return ret;
1844  }
1845  }
1846 
1847  // buffer an audio packet to ensure the packet containing the video
1848  // keyframe's timecode is contained in the same cluster for WebM
1849  if (codec_type == AVMEDIA_TYPE_AUDIO) {
1850  mkv->cur_audio_pkt = *pkt;
1851  if (pkt->buf) {
1852  mkv->cur_audio_pkt.buf = av_buffer_ref(pkt->buf);
1853  ret = mkv->cur_audio_pkt.buf ? 0 : AVERROR(ENOMEM);
1854  } else
1855  ret = av_dup_packet(&mkv->cur_audio_pkt);
1856  if (mkv->cur_audio_pkt.side_data_elems > 0) {
1858  }
1859  } else
1860  ret = mkv_write_packet_internal(s, pkt, 0);
1861  return ret;
1862 }
1863 
1865 {
1866  MatroskaMuxContext *mkv = s->priv_data;
1867  AVIOContext *pb;
1868  if (s->pb->seekable)
1869  pb = s->pb;
1870  else
1871  pb = mkv->dyn_bc;
1872  if (!pkt) {
1873  if (mkv->cluster_pos != -1) {
1874  av_log(s, AV_LOG_DEBUG,
1875  "Flushing cluster at offset %" PRIu64 " bytes\n",
1876  avio_tell(pb));
1877  end_ebml_master(pb, mkv->cluster);
1878  mkv->cluster_pos = -1;
1879  if (mkv->dyn_bc)
1880  mkv_flush_dynbuf(s);
1881  avio_flush(s->pb);
1882  }
1883  return 0;
1884  }
1885  return mkv_write_packet(s, pkt);
1886 }
1887 
1889 {
1890  MatroskaMuxContext *mkv = s->priv_data;
1891  AVIOContext *pb = s->pb;
1892  int64_t currentpos, cuespos;
1893  int ret;
1894 
1895  // check if we have an audio packet cached
1896  if (mkv->cur_audio_pkt.size > 0) {
1897  ret = mkv_write_packet_internal(s, &mkv->cur_audio_pkt, 0);
1899  if (ret < 0) {
1900  av_log(s, AV_LOG_ERROR,
1901  "Could not write cached audio packet ret:%d\n", ret);
1902  return ret;
1903  }
1904  }
1905 
1906  if (mkv->dyn_bc) {
1907  end_ebml_master(mkv->dyn_bc, mkv->cluster);
1908  mkv_flush_dynbuf(s);
1909  } else if (mkv->cluster_pos != -1) {
1910  end_ebml_master(pb, mkv->cluster);
1911  }
1912 
1913  if (mkv->mode != MODE_WEBM) {
1914  ret = mkv_write_chapters(s);
1915  if (ret < 0)
1916  return ret;
1917  }
1918 
1919  if (pb->seekable) {
1920  if (mkv->cues->num_entries) {
1921  if (mkv->reserve_cues_space) {
1922  int64_t cues_end;
1923 
1924  currentpos = avio_tell(pb);
1925  avio_seek(pb, mkv->cues_pos, SEEK_SET);
1926 
1927  cuespos = mkv_write_cues(s, mkv->cues, mkv->tracks, s->nb_streams);
1928  cues_end = avio_tell(pb);
1929  if (cues_end > cuespos + mkv->reserve_cues_space) {
1930  av_log(s, AV_LOG_ERROR,
1931  "Insufficient space reserved for cues: %d "
1932  "(needed: %" PRId64 ").\n",
1933  mkv->reserve_cues_space, cues_end - cuespos);
1934  return AVERROR(EINVAL);
1935  }
1936 
1937  if (cues_end < cuespos + mkv->reserve_cues_space)
1939  (cues_end - cuespos));
1940 
1941  avio_seek(pb, currentpos, SEEK_SET);
1942  } else {
1943  cuespos = mkv_write_cues(s, mkv->cues, mkv->tracks, s->nb_streams);
1944  }
1945 
1947  cuespos);
1948  if (ret < 0)
1949  return ret;
1950  }
1951 
1953 
1954  // update the duration
1955  av_log(s, AV_LOG_DEBUG, "end duration = %" PRIu64 "\n", mkv->duration);
1956  currentpos = avio_tell(pb);
1957  avio_seek(pb, mkv->duration_offset, SEEK_SET);
1959 
1960  avio_seek(pb, currentpos, SEEK_SET);
1961  }
1962 
1963  end_ebml_master(pb, mkv->segment);
1964  av_freep(&mkv->tracks);
1965  av_freep(&mkv->cues->entries);
1966  av_freep(&mkv->cues);
1967 
1968  return 0;
1969 }
1970 
1971 static int mkv_query_codec(enum AVCodecID codec_id, int std_compliance)
1972 {
1973  int i;
1974  for (i = 0; ff_mkv_codec_tags[i].id != AV_CODEC_ID_NONE; i++)
1975  if (ff_mkv_codec_tags[i].id == codec_id)
1976  return 1;
1977 
1978  if (std_compliance < FF_COMPLIANCE_NORMAL) {
1979  enum AVMediaType type = avcodec_get_type(codec_id);
1980  // mkv theoretically supports any video/audio through VFW/ACM
1981  if (type == AVMEDIA_TYPE_VIDEO || type == AVMEDIA_TYPE_AUDIO)
1982  return 1;
1983  }
1984 
1985  return 0;
1986 }
1987 
1989  { AV_CODEC_ID_ALAC, 0XFFFFFFFF },
1990  { AV_CODEC_ID_EAC3, 0XFFFFFFFF },
1991  { AV_CODEC_ID_MLP, 0xFFFFFFFF },
1992  { AV_CODEC_ID_OPUS, 0xFFFFFFFF },
1993  { AV_CODEC_ID_PCM_S16BE, 0xFFFFFFFF },
1994  { AV_CODEC_ID_PCM_S24BE, 0xFFFFFFFF },
1995  { AV_CODEC_ID_PCM_S32BE, 0xFFFFFFFF },
1996  { AV_CODEC_ID_QDM2, 0xFFFFFFFF },
1997  { AV_CODEC_ID_RA_144, 0xFFFFFFFF },
1998  { AV_CODEC_ID_RA_288, 0xFFFFFFFF },
1999  { AV_CODEC_ID_COOK, 0xFFFFFFFF },
2000  { AV_CODEC_ID_TRUEHD, 0xFFFFFFFF },
2001  { AV_CODEC_ID_NONE, 0xFFFFFFFF }
2002 };
2003 
2005  { AV_CODEC_ID_RV10, 0xFFFFFFFF },
2006  { AV_CODEC_ID_RV20, 0xFFFFFFFF },
2007  { AV_CODEC_ID_RV30, 0xFFFFFFFF },
2008  { AV_CODEC_ID_RV40, 0xFFFFFFFF },
2009  { AV_CODEC_ID_VP9, 0xFFFFFFFF },
2010  { AV_CODEC_ID_NONE, 0xFFFFFFFF }
2011 };
2012 
2014  { AV_CODEC_ID_DVB_SUBTITLE, 0xFFFFFFFF },
2015  { AV_CODEC_ID_HDMV_PGS_SUBTITLE, 0xFFFFFFFF },
2016  { AV_CODEC_ID_NONE, 0xFFFFFFFF }
2017 };
2018 
2019 #define OFFSET(x) offsetof(MatroskaMuxContext, x)
2020 #define FLAGS AV_OPT_FLAG_ENCODING_PARAM
2021 static const AVOption options[] = {
2022  { "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 },
2023  { "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 },
2024  { "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 },
2025  { "dash", "Create a WebM file conforming to WebM DASH specification", OFFSET(is_dash), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, FLAGS },
2026  { "dash_track_number", "Track number for the DASH stream", OFFSET(dash_track_number), AV_OPT_TYPE_INT, { .i64 = 1 }, 0, 127, FLAGS },
2027  { "allow_raw_vfw", "allow RAW VFW mode", OFFSET(allow_raw_vfw), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, FLAGS },
2028  { NULL },
2029 };
2030 
2031 #if CONFIG_MATROSKA_MUXER
2032 static const AVClass matroska_class = {
2033  .class_name = "matroska muxer",
2034  .item_name = av_default_item_name,
2035  .option = options,
2036  .version = LIBAVUTIL_VERSION_INT,
2037 };
2038 
2039 AVOutputFormat ff_matroska_muxer = {
2040  .name = "matroska",
2041  .long_name = NULL_IF_CONFIG_SMALL("Matroska"),
2042  .mime_type = "video/x-matroska",
2043  .extensions = "mkv",
2044  .priv_data_size = sizeof(MatroskaMuxContext),
2045  .audio_codec = CONFIG_LIBVORBIS_ENCODER ?
2047  .video_codec = CONFIG_LIBX264_ENCODER ?
2054  .codec_tag = (const AVCodecTag* const []){
2057  },
2058  .subtitle_codec = AV_CODEC_ID_ASS,
2059  .query_codec = mkv_query_codec,
2060  .priv_class = &matroska_class,
2061 };
2062 #endif
2063 
2064 #if CONFIG_WEBM_MUXER
2065 static const AVClass webm_class = {
2066  .class_name = "webm muxer",
2067  .item_name = av_default_item_name,
2068  .option = options,
2069  .version = LIBAVUTIL_VERSION_INT,
2070 };
2071 
2072 AVOutputFormat ff_webm_muxer = {
2073  .name = "webm",
2074  .long_name = NULL_IF_CONFIG_SMALL("WebM"),
2075  .mime_type = "video/webm",
2076  .extensions = "webm",
2077  .priv_data_size = sizeof(MatroskaMuxContext),
2078  .audio_codec = AV_CODEC_ID_VORBIS,
2079  .video_codec = AV_CODEC_ID_VP8,
2080  .subtitle_codec = AV_CODEC_ID_WEBVTT,
2086  .priv_class = &webm_class,
2087 };
2088 #endif
2089 
2090 #if CONFIG_MATROSKA_AUDIO_MUXER
2091 static const AVClass mka_class = {
2092  .class_name = "matroska audio muxer",
2093  .item_name = av_default_item_name,
2094  .option = options,
2095  .version = LIBAVUTIL_VERSION_INT,
2096 };
2097 AVOutputFormat ff_matroska_audio_muxer = {
2098  .name = "matroska",
2099  .long_name = NULL_IF_CONFIG_SMALL("Matroska Audio"),
2100  .mime_type = "audio/x-matroska",
2101  .extensions = "mka",
2102  .priv_data_size = sizeof(MatroskaMuxContext),
2103  .audio_codec = CONFIG_LIBVORBIS_ENCODER ?
2104  AV_CODEC_ID_VORBIS : AV_CODEC_ID_AC3,
2105  .video_codec = AV_CODEC_ID_NONE,
2111  .codec_tag = (const AVCodecTag* const []){
2113  },
2114  .priv_class = &mka_class,
2115 };
2116 #endif
unsigned int nb_chapters
Number of chapters in AVChapter array.
Definition: avformat.h:1424
static int mkv_write_packet_internal(AVFormatContext *s, AVPacket *pkt, int add_cue)
Definition: matroskaenc.c:1709
Definition: lfg.h:25
#define MATROSKA_ID_SEEKPREROLL
Definition: matroska.h:95
void av_sha_final(AVSHA *ctx, uint8_t *digest)
Finish hashing and output digest value.
Definition: sha.c:341
internal header for HEVC (de)muxer utilities
#define AV_DISPOSITION_METADATA
Definition: avformat.h:791
void avio_wb64(AVIOContext *s, uint64_t val)
Definition: aviobuf.c:412
#define NULL
Definition: coverity.c:32
static int mkv_write_vtt_blocks(AVFormatContext *s, AVIOContext *pb, AVPacket *pkt)
Definition: matroskaenc.c:1634
const char const char void * val
Definition: avisynth_c.h:672
#define MATROSKA_ID_BLOCKADDID
Definition: matroska.h:194
#define MATROSKA_ID_TRACKDEFAULTDURATION
Definition: matroska.h:104
void avio_wl16(AVIOContext *s, unsigned int val)
Definition: aviobuf.c:418
static void put_ebml_size_unknown(AVIOContext *pb, int bytes)
Write an EBML size meaning "unknown size".
Definition: matroskaenc.c:162
const char * s
Definition: avisynth_c.h:669
Bytestream IO Context.
Definition: avio.h:68
#define AVERROR_INVALIDDATA
Invalid data found when processing input.
Definition: error.h:59
static int mkv_check_tag(AVDictionary *m)
Definition: matroskaenc.c:1181
void ff_metadata_conv_ctx(AVFormatContext *ctx, const AVMetadataConv *d_conv, const AVMetadataConv *s_conv)
Definition: metadata.c:59
Views are packed per line, as if interlaced.
Definition: stereo3d.h:97
#define MATROSKA_ID_DATEUTC
Definition: matroska.h:71
void av_free_packet(AVPacket *pkt)
Free a packet.
Definition: avpacket.c:281
int sizebytes
how many bytes were reserved for the size
Definition: matroskaenc.c:57
The optional first identifier line of a WebVTT cue.
Definition: avcodec.h:1093
uint32_t samples
Definition: wv.h:39
int initial
Definition: wv.h:43
void av_sha_update(AVSHA *ctx, const uint8_t *data, unsigned int len)
Update hash value.
Definition: sha.c:314
#define MATROSKA_ID_TRACKFLAGLACING
Definition: matroska.h:101
#define MATROSKA_ID_TRACKENTRY
Definition: matroska.h:75
#define MATROSKA_ID_VIDEODISPLAYHEIGHT
Definition: matroska.h:113
static void mkv_start_new_cluster(AVFormatContext *s, AVPacket *pkt)
Definition: matroskaenc.c:1687
int avio_close_dyn_buf(AVIOContext *s, uint8_t **pbuffer)
Return the written size and a pointer to the buffer.
Definition: aviobuf.c:1112
AVOption.
Definition: opt.h:255
hash context
Definition: sha.c:34
int64_t cluster_pos
file offset of the cluster containing the block
Definition: matroskaenc.c:78
ptrdiff_t const GLvoid * data
Definition: opengl_enc.c:101
Views are alternated temporally.
Definition: stereo3d.h:66
enum AVCodecID id
Definition: mxfenc.c:95
#define MATROSKA_ID_CUETRACKPOSITION
Definition: matroska.h:156
enum AVCodecID ff_codec_get_id(const AVCodecTag *tags, unsigned int tag)
Definition: utils.c:2705
#define MATROSKA_ID_CODECPRIVATE
Definition: matroska.h:89
av_cold int av_sha_init(AVSHA *ctx, int bits)
Initialize SHA-1 or SHA-2 hashing.
Definition: sha.c:273
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition: log.h:181
#define LIBAVUTIL_VERSION_INT
Definition: version.h:62
#define AV_RB64
Definition: intreadwrite.h:164
void avpriv_set_pts_info(AVStream *s, int pts_wrap_bits, unsigned int pts_num, unsigned int pts_den)
Set the time base and wrapping info for a given stream.
Definition: utils.c:3997
#define MATROSKA_ID_AUDIOBITDEPTH
Definition: matroska.h:131
#define MATROSKA_ID_TRACKFLAGDEFAULT
Definition: matroska.h:99
static const AVCodecTag additional_subtitle_tags[]
Definition: matroskaenc.c:2013
This side data should be associated with a video stream and contains Stereoscopic 3D information in f...
Definition: avcodec.h:1036
static int mkv_write_attachments(AVFormatContext *s)
Definition: matroskaenc.c:1230
uint64_t pts
Definition: matroskaenc.c:75
AVRational sample_aspect_ratio
sample aspect ratio (0 if unknown)
Definition: avformat.h:879
int num
numerator
Definition: rational.h:44
int size
Definition: avcodec.h:1161
int64_t avio_seek(AVIOContext *s, int64_t offset, int whence)
fseek() equivalent for AVIOContext.
Definition: aviobuf.c:203
#define MATROSKA_ID_FILEDATA
Definition: matroska.h:210
AVFormatInternal * internal
An opaque field for libavformat internal usage.
Definition: avformat.h:1648
#define EBML_ID_DOCTYPEREADVERSION
Definition: matroska.h:42
#define AV_RB24
Definition: intreadwrite.h:64
static int mkv_write_header(AVFormatContext *s)
Definition: matroskaenc.c:1314
#define MATROSKA_ID_TRACKTYPE
Definition: matroska.h:80
enum AVMediaType codec_type
Definition: rtp.c:37
#define MATROSKA_ID_TAGTARGETS_CHAPTERUID
Definition: matroska.h:177
int ff_flac_is_native_layout(uint64_t channel_layout)
enum AVPixelFormat pix_fmt
Pixel format, see AV_PIX_FMT_xxx.
Definition: avcodec.h:1442
int64_t duration
duration of the block according to time base
Definition: matroskaenc.c:80
static av_always_inline uint64_t av_double2int(double f)
Reinterpret a double as a 64-bit integer.
Definition: intfloat.h:70
#define MATROSKA_ID_MUXINGAPP
Definition: matroska.h:70
int64_t cluster_time_limit
Definition: matroskaenc.c:120
#define MATROSKA_ID_AUDIOCHANNELS
Definition: matroska.h:132
unsigned int ff_codec_get_tag(const AVCodecTag *tags, enum AVCodecID id)
Definition: utils.c:2695
int64_t segment_offset
Definition: matroskaenc.c:84
int version
Definition: avisynth_c.h:667
int avoid_negative_ts_use_pts
Definition: internal.h:101
const char * master
Definition: vf_curves.c:110
AVPacketSideData * side_data
An array of side data that applies to the whole stream (i.e.
Definition: avformat.h:919
static AVPacket pkt
#define av_le2ne32(x)
Definition: bswap.h:96
#define MATROSKA_ID_CUECLUSTERPOSITION
Definition: matroska.h:160
Definition: matroskaenc.c:60
AVDictionary * metadata
Definition: avformat.h:1195
int av_dup_packet(AVPacket *pkt)
Definition: avpacket.c:249
mkv_track * tracks
Definition: matroskaenc.c:111
#define AVFMT_ALLOW_FLUSH
Format allows flushing.
Definition: avformat.h:446
#define MATROSKA_ID_EDITIONFLAGDEFAULT
Definition: matroska.h:223
#define MATROSKA_ID_CLUSTERTIMECODE
Definition: matroska.h:188
int avio_open_dyn_buf(AVIOContext **s)
Open a write only memory stream.
Definition: aviobuf.c:1100
#define EBML_ID_DOCTYPE
Definition: matroska.h:40
#define AVFMT_TS_NONSTRICT
Format does not require strictly increasing timestamps, but they must still be monotonic.
Definition: avformat.h:448
#define MATROSKA_ID_CHAPTERTIMEEND
Definition: matroska.h:217
int64_t pos
absolute offset in the file where the master's elements start
Definition: matroskaenc.c:56
MatroskaVideoStereoModeType
Definition: matroska.h:248
int ff_vorbiscomment_write(uint8_t **p, AVDictionary **m, const char *vendor_string)
Write a VorbisComment into a buffer.
Definition: vorbiscomment.c:54
AVRational time_base
This is the fundamental unit of time (in seconds) in terms of which frame timestamps are represented...
Definition: avcodec.h:1367
#define FLAGS
Definition: matroskaenc.c:2020
#define MATROSKA_ID_FILEDESC
Definition: matroska.h:207
Format I/O context.
Definition: avformat.h:1226
UID uid
Definition: mxfenc.c:1617
#define AV_RL64
Definition: intreadwrite.h:173
char str[32]
Definition: internal.h:46
int64_t cluster_pos
file offset of the current cluster
Definition: matroskaenc.c:105
const char * class_name
The name of the class; usually it is the same name as the context structure type to which the AVClass...
Definition: log.h:71
#define AV_WB64(p, v)
Definition: intreadwrite.h:433
#define av_assert0(cond)
assert() equivalent, that is always enabled.
Definition: avassert.h:37
static const AVCodecTag additional_audio_tags[]
Definition: matroskaenc.c:1988
Public dictionary API.
static int mkv_write_native_codecprivate(AVFormatContext *s, AVCodecContext *codec, AVIOContext *dyn_cp)
Definition: matroskaenc.c:595
planar YUV 4:2:0, 20bpp, (1 Cr & Cb sample per 2x2 Y & A samples)
Definition: pixfmt.h:108
void avio_wl32(AVIOContext *s, unsigned int val)
Definition: aviobuf.c:318
enum AVSampleFormat sample_fmt
audio sample format
Definition: avcodec.h:1991
uint8_t
#define MATROSKA_ID_CHAPLANG
Definition: matroska.h:220
#define av_malloc(s)
static int mkv_write_tag(AVFormatContext *s, AVDictionary *m, unsigned int elementid, unsigned int uid, ebml_master *tags)
Definition: matroskaenc.c:1146
mode
Definition: f_perms.c:27
AVOptions.
#define MATROSKA_ID_TRACKLANGUAGE
Definition: matroska.h:97
Stereo 3D type: this structure describes how two videos are packed within a single video surface...
Definition: stereo3d.h:123
const AVCodecTag ff_codec_movvideo_tags[]
Definition: isom.c:70
static int ebml_id_size(unsigned int id)
Definition: matroskaenc.c:145
#define OPUS_SEEK_PREROLL
Seek preroll value for opus.
Definition: matroskaenc.c:143
uint32_t flags
Definition: wv.h:40
#define AV_RB32
Definition: intreadwrite.h:130
int ff_mkv_stereo3d_conv(AVStream *st, MatroskaVideoStereoModeType stereo_mode)
Definition: matroska.c:151
uint64_t segmentpos
Definition: matroskaenc.c:62
int id
unique ID to identify the chapter
Definition: avformat.h:1192
#define MATROSKA_ID_TIMECODESCALE
Definition: matroska.h:66
#define MATROSKA_ID_SIMPLEBLOCK
Definition: matroska.h:196
#define MATROSKA_ID_EDITIONFLAGHIDDEN
Definition: matroska.h:222
int nb_side_data
The number of elements in the AVStream.side_data array.
Definition: avformat.h:923
uint8_t * extradata
some codecs need / can use extradata like Huffman tables.
Definition: avcodec.h:1353
#define MATROSKA_ID_BLOCKMORE
Definition: matroska.h:193
AVStream ** streams
A list of all streams in the file.
Definition: avformat.h:1294
#define MATROSKA_ID_CUERELATIVEPOSITION
Definition: matroska.h:161
#define MATROSKA_ID_AUDIOOUTSAMPLINGFREQ
Definition: matroska.h:129
static double av_q2d(AVRational a)
Convert rational to double.
Definition: rational.h:80
AVDictionaryEntry * av_dict_get(const AVDictionary *m, const char *key, const AVDictionaryEntry *prev, int flags)
Get a dictionary entry with matching key.
Definition: dict.c:39
int flags
Flags modifying the (de)muxer behaviour.
Definition: avformat.h:1337
uint8_t * data
Definition: avcodec.h:1160
static int64_t mkv_write_cues(AVFormatContext *s, mkv_cues *cues, mkv_track *tracks, int num_tracks)
Definition: matroskaenc.c:437
#define MATROSKA_ID_VIDEODISPLAYWIDTH
Definition: matroska.h:112
#define MATROSKA_ID_BLOCKADDITIONS
Definition: matroska.h:192
uint32_t tag
Definition: movenc.c:1332
static EbmlSyntax ebml_header[]
Definition: matroskadec.c:322
#define WV_HEADER_SIZE
Definition: wavpack.h:30
enum AVCodecID id
Definition: internal.h:47
static int put_flac_codecpriv(AVFormatContext *s, AVIOContext *pb, AVCodecContext *codec)
Definition: matroskaenc.c:531
#define AV_LOG_VERBOSE
Detailed information.
Definition: log.h:191
uint8_t * data
Definition: avcodec.h:1110
#define MATROSKA_ID_CUES
Definition: matroska.h:58
int ff_vorbiscomment_length(AVDictionary *m, const char *vendor_string)
Calculate the length in bytes of a VorbisComment.
Definition: vorbiscomment.c:41
int64_t ts_offset
Definition: matroskaenc.c:92
ptrdiff_t size
Definition: opengl_enc.c:101
static av_always_inline int64_t avio_tell(AVIOContext *s)
ftell() equivalent for AVIOContext.
Definition: avio.h:273
static const uint8_t header[24]
Definition: sdr2.c:67
int bits_per_coded_sample
bits per sample/pixel from the demuxer (needed for huffyuv).
Definition: avcodec.h:2718
#define MATROSKA_ID_TRACKNUMBER
Definition: matroska.h:78
static int64_t duration
Definition: ffplay.c:320
void avio_write(AVIOContext *s, const unsigned char *buf, int size)
Definition: aviobuf.c:177
static int get_aac_sample_rates(AVFormatContext *s, AVCodecContext *codec, int *sample_rate, int *output_sample_rate)
Definition: matroskaenc.c:578
Definition: wv.h:34
#define AVFMT_FLAG_BITEXACT
When muxing, try to avoid writing any random/volatile data to the output.
Definition: avformat.h:1354
int duration
Duration of this packet in AVStream->time_base units, 0 if unknown.
Definition: avcodec.h:1178
#define MATROSKA_ID_SEGMENTUID
Definition: matroska.h:72
static void put_ebml_num(AVIOContext *pb, uint64_t num, int bytes)
Write a number in EBML variable length format.
Definition: matroskaenc.c:186
#define av_log(a,...)
int has_cue
Definition: matroskaenc.c:91
#define AV_DISPOSITION_CAPTIONS
To specify text track kind (different from subtitles default).
Definition: avformat.h:789
unsigned m
Definition: audioconvert.c:187
static int mkv_add_seekhead_entry(mkv_seekhead *seekhead, unsigned int elementid, uint64_t filepos)
Definition: matroskaenc.c:332
int64_t segment_offset
the file offset to the beginning of the segment
Definition: matroskaenc.c:67
struct AVOutputFormat * oformat
The output container format.
Definition: avformat.h:1245
#define AV_PKT_FLAG_KEY
The packet contains a keyframe.
Definition: avcodec.h:1206
#define MATROSKA_ID_TRACKUID
Definition: matroska.h:79
int64_t av_rescale_q(int64_t a, AVRational bq, AVRational cq)
Rescale a 64-bit integer by 2 rational numbers.
Definition: mathematics.c:147
ebml_master segment
Definition: matroskaenc.c:102
static int mkv_write_simpletag(AVIOContext *pb, AVDictionaryEntry *t)
Definition: matroskaenc.c:1112
#define MATROSKA_ID_VIDEOSTEREOMODE
Definition: matroska.h:122
uint32_t chapter_id_offset
Definition: matroskaenc.c:124
AVPacket cur_audio_pkt
Definition: matroskaenc.c:113
AVCodecID
Identify the syntax and semantics of the bitstream.
Definition: avcodec.h:102
static int mkv_write_tags(AVFormatContext *s)
Definition: matroskaenc.c:1192
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition: log.h:175
int av_get_bits_per_sample(enum AVCodecID codec_id)
Return codec bits per sample.
Definition: utils.c:3299
AVDictionary * metadata
Metadata that applies to the whole file.
Definition: avformat.h:1435
int flags
Additional information about the frame packing.
Definition: stereo3d.h:132
#define MATROSKA_ID_BLOCKDURATION
Definition: matroska.h:200
#define EBML_ID_EBMLREADVERSION
Definition: matroska.h:37
#define MAX_CUETRACKPOS_SIZE
per-cuepoint-track - 5 1-byte EBML IDs, 5 1-byte EBML sizes, 4 8-byte uint max
Definition: matroskaenc.c:137
av_default_item_name
#define AVERROR(e)
Definition: error.h:43
unsigned int elementid
Definition: matroskaenc.c:61
int reserved_size
-1 if appending to file
Definition: matroskaenc.c:68
#define MATROSKA_ID_CLUSTER
Definition: matroska.h:62
const char * av_convert_lang_to(const char *lang, enum AVLangCodespace target_codespace)
Convert a language code to a target codespace.
Definition: avlanguage.c:736
static int put_xiph_codecpriv(AVFormatContext *s, AVIOContext *pb, AVCodecContext *codec)
Definition: matroskaenc.c:494
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification. ...
Definition: internal.h:180
#define MATROSKA_ID_FILEMIMETYPE
Definition: matroska.h:209
int64_t convergence_duration
Time difference in AVStream->time_base units from the pts of this packet to the point at which the ou...
Definition: avcodec.h:1204
#define MATROSKA_ID_WRITINGAPP
Definition: matroska.h:69
int initial_padding
Audio only.
Definition: avcodec.h:3007
#define AV_LOG_DEBUG
Stuff which is only useful for libav* developers.
Definition: log.h:196
#define FF_COMPLIANCE_NORMAL
Definition: avcodec.h:2544
const char *const ff_matroska_video_stereo_mode[MATROSKA_VIDEO_STEREOMODE_TYPE_NB]
Definition: matroska.c:127
void av_dict_free(AVDictionary **pm)
Free all the memory allocated for an AVDictionary struct and all keys and values. ...
Definition: dict.c:194
static int mkv_blockgroup_size(int pkt_size)
Definition: matroskaenc.c:1479
AVBufferRef * buf
A reference to the reference-counted buffer where the packet data is stored.
Definition: avcodec.h:1143
static int ebml_num_size(uint64_t num)
Calculate how many bytes are needed to represent a given number in EBML.
Definition: matroskaenc.c:172
int write_dts
Definition: matroskaenc.c:90
int final
Definition: wv.h:43
AVChapter ** chapters
Definition: avformat.h:1425
enum AVCodecID id
Definition: matroska.h:273
enum AVPacketSideDataType type
Definition: avcodec.h:1112
enum AVMediaType avcodec_get_type(enum AVCodecID codec_id)
Get the type of the given codec.
Definition: utils.c:3736
static int mkv_write_chapters(AVFormatContext *s)
Definition: matroskaenc.c:1064
int side_data_elems
Definition: avcodec.h:1172
#define EBML_ID_EBMLMAXIDLENGTH
Definition: matroska.h:38
#define MATROSKA_ID_CHAPTERFLAGHIDDEN
Definition: matroska.h:226
enum AVCodecID codec_id
Definition: mov_chan.c:433
Video is not stereoscopic (and metadata has to be there).
Definition: stereo3d.h:35
static const uint8_t offset[127][2]
Definition: vf_spp.c:92
uint32_t crc
Definition: wv.h:41
AVRational avg_frame_rate
Average framerate.
Definition: avformat.h:890
const AVCodecTag ff_codec_wav_tags[]
Definition: riff.c:369
#define FFMAX(a, b)
Definition: common.h:79
static mkv_seekhead * mkv_start_seekhead(AVIOContext *pb, int64_t segment_offset, int numelements)
Initialize a mkv_seekhead element to be ready to index level 1 Matroska elements. ...
Definition: matroskaenc.c:311
int ff_avc_parse_nal_units_buf(const uint8_t *buf_in, uint8_t **buf, int *size)
Definition: avc.c:92
int64_t filepos
Definition: matroskaenc.c:66
int flags
A combination of AV_PKT_FLAG values.
Definition: avcodec.h:1166
uint64_t channel_layout
Audio channel layout.
Definition: avcodec.h:2044
static void mkv_write_block(AVFormatContext *s, AVIOContext *pb, unsigned int blockid, AVPacket *pkt, int flags)
Definition: matroskaenc.c:1543
AVCodecContext * codec
Codec context associated with this stream.
Definition: avformat.h:826
const CodecMime ff_mkv_mime_tags[]
Definition: matroska.c:111
#define MATROSKA_ID_TAG
Definition: matroska.h:166
#define AV_DISPOSITION_FORCED
Track should be used during playback by default.
Definition: avformat.h:774
unsigned int nb_streams
Number of elements in AVFormatContext.streams.
Definition: avformat.h:1282
#define LIBAVFORMAT_IDENT
Definition: version.h:44
int seekable
A combination of AVIO_SEEKABLE_ flags or 0 when the stream is not seekable.
Definition: avio.h:117
int void avio_flush(AVIOContext *s)
Force flushing of buffered data.
Definition: aviobuf.c:197
audio channel layout utility functions
#define EBML_ID_EBMLVERSION
Definition: matroska.h:36
int64_t av_rescale(int64_t a, int64_t b, int64_t c)
Rescale a 64-bit integer with rounding to nearest.
Definition: mathematics.c:134
mkv_cuepoint * entries
Definition: matroskaenc.c:85
void ffio_fill(AVIOContext *s, int b, int count)
Definition: aviobuf.c:163
#define MATROSKA_ID_TAGTARGETS
Definition: matroska.h:173
const AVCodecTag ff_codec_bmp_tags[]
Definition: riff.c:32
int av_strcasecmp(const char *a, const char *b)
Locale-independent case-insensitive compare.
Definition: avstring.c:213
#define MATROSKA_ID_TAGNAME
Definition: matroska.h:168
ret
Definition: avfilter.c:974
int width
picture width / height.
Definition: avcodec.h:1412
#define MATROSKA_ID_CHAPTERFLAGENABLED
Definition: matroska.h:227
static int write_trailer(AVFormatContext *s1)
Definition: v4l2enc.c:94
int64_t ff_iso8601_to_unix_time(const char *datestr)
Convert a date string in ISO8601 format to Unix timestamp.
Definition: utils.c:4085
#define AVFMT_GLOBALHEADER
Format wants global header.
Definition: avformat.h:436
int ff_wv_parse_header(WvHeader *wv, const uint8_t *data)
Parse a WavPack block header.
Definition: wv.c:29
int ff_hevc_annexb2mp4_buf(const uint8_t *buf_in, uint8_t **buf_out, int *size, int filter_ps, int *ps_count)
Writes Annex B formatted HEVC NAL units to a data buffer.
Definition: hevc.c:1077
#define MATROSKA_ID_SIMPLETAG
Definition: matroska.h:167
const char * name
Definition: avformat.h:478
internal header for RIFF based (de)muxers do NOT include this in end user applications ...
#define AV_STEREO3D_FLAG_INVERT
Inverted views, Right/Bottom represents the left view.
Definition: stereo3d.h:114
#define AV_WB24(p, d)
Definition: intreadwrite.h:450
int ff_flac_write_header(AVIOContext *pb, uint8_t *extradata, int extradata_size, int last_block)
int avoid_negative_ts
Avoid negative timestamps during muxing.
Definition: avformat.h:1526
#define MATROSKA_ID_CHAPTERATOM
Definition: matroska.h:215
int avpriv_split_xiph_headers(const uint8_t *extradata, int extradata_size, int first_header_size, const uint8_t *header_start[3], int header_len[3])
Split a single extradata buffer into the three headers that most Xiph codecs use. ...
Definition: xiph.c:24
#define CONFIG_LIBVORBIS_ENCODER
Definition: config.h:1372
#define AV_RL32
Definition: intreadwrite.h:146
AVDictionary * metadata
Definition: avformat.h:881
Opaque data information usually sparse.
Definition: avutil.h:198
#define MATROSKA_ID_VIDEOCOLORSPACE
Definition: matroska.h:125
#define MATROSKA_ID_CHAPTERS
Definition: matroska.h:63
#define EBML_ID_VOID
Definition: matroska.h:45
#define OFFSET(x)
Definition: matroskaenc.c:2019
#define MATROSKA_ID_AUDIOSAMPLINGFREQ
Definition: matroska.h:128
const char * avcodec_get_name(enum AVCodecID id)
Get the name of a codec.
Definition: utils.c:2957
static int mkv_add_cuepoint(mkv_cues *cues, int stream, int tracknum, int64_t ts, int64_t cluster_pos, int64_t relative_pos, int64_t duration)
Definition: matroskaenc.c:414
static void put_ebml_float(AVIOContext *pb, unsigned int elementid, double val)
Definition: matroskaenc.c:231
Stream structure.
Definition: avformat.h:807
#define AVERROR_PATCHWELCOME
Not yet implemented in FFmpeg, patches welcome.
Definition: error.h:62
static void put_ebml_string(AVIOContext *pb, unsigned int elementid, const char *str)
Definition: matroskaenc.c:246
int64_t end
chapter start/end time in time_base units
Definition: avformat.h:1194
static int mkv_write_track(AVFormatContext *s, MatroskaMuxContext *mkv, int i, AVIOContext *pb, int default_stream_exists)
Definition: matroskaenc.c:802
#define AV_DISPOSITION_DEFAULT
Definition: avformat.h:762
sample_rate
enum AVStereo3DType type
How views are packed within the video.
Definition: stereo3d.h:127
#define AV_DISPOSITION_DESCRIPTIONS
Definition: avformat.h:790
AVS_Value src
Definition: avisynth_c.h:524
#define MATROSKA_ID_TRACKFLAGFORCED
Definition: matroska.h:100
#define MATROSKA_ID_TAGS
Definition: matroska.h:59
enum AVMediaType codec_type
Definition: avcodec.h:1247
enum AVCodecID codec_id
Definition: avcodec.h:1256
#define MATROSKA_ID_SEEKID
Definition: matroska.h:184
char * av_strdup(const char *s)
Duplicate the string s.
Definition: mem.c:265
int sample_rate
samples per second
Definition: avcodec.h:1983
AVIOContext * pb
I/O context.
Definition: avformat.h:1268
void avio_w8(AVIOContext *s, int b)
Definition: aviobuf.c:155
main external API structure.
Definition: avcodec.h:1239
#define MATROSKA_ID_BLOCK
Definition: matroska.h:199
#define MATROSKA_ID_INFO
Definition: matroska.h:56
#define MATROSKA_ID_TAGTARGETS_TRACKUID
Definition: matroska.h:176
#define MATROSKA_ID_TAGLANG
Definition: matroska.h:170
unsigned int codec_tag
fourcc (LSB first, so "ABCD" -> ('D'<<24) + ('C'<<16) + ('B'<<8) + 'A').
Definition: avcodec.h:1271
struct AVSHA * av_sha_alloc(void)
Allocate an AVSHA context.
Definition: sha.c:45
static unsigned int av_lfg_get(AVLFG *c)
Get the next random unsigned 32-bit number using an ALFG.
Definition: lfg.h:38
#define MATROSKA_ID_TRACKS
Definition: matroska.h:57
void * buf
Definition: avisynth_c.h:595
Data found in BlockAdditional element of matroska container.
Definition: avcodec.h:1088
GLint GLenum type
Definition: opengl_enc.c:105
int extradata_size
Definition: avcodec.h:1354
#define MATROSKA_ID_TRACKNAME
Definition: matroska.h:96
int av_dict_set(AVDictionary **pm, const char *key, const char *value, int flags)
Set the given entry in *pm, overwriting an existing entry.
Definition: dict.c:69
#define MATROSKA_ID_SEEKENTRY
Definition: matroska.h:181
Describe the class of an AVClass context structure.
Definition: log.h:66
#define MATROSKA_ID_EDITIONENTRY
Definition: matroska.h:214
#define MAX_CUEPOINT_SIZE(num_tracks)
per-cuepoint - 2 1-byte EBML IDs, 2 1-byte EBML sizes, 8-byte uint max
Definition: matroskaenc.c:140
#define MATROSKA_ID_BLOCKGROUP
Definition: matroska.h:191
#define MATROSKA_ID_VIDEOPIXELHEIGHT
Definition: matroska.h:115
static int mkv_write_tracks(AVFormatContext *s)
Definition: matroskaenc.c:1039
rational number numerator/denominator
Definition: rational.h:43
static void put_ebml_uint(AVIOContext *pb, unsigned int elementid, uint64_t val)
Definition: matroskaenc.c:205
#define MATROSKA_ID_CUEDURATION
Definition: matroska.h:162
void ff_put_bmp_header(AVIOContext *pb, AVCodecContext *enc, const AVCodecTag *tags, int for_asf, int ignore_extradata)
Definition: riffenc.c:205
#define MATROSKA_ID_CUETIME
Definition: matroska.h:155
static int64_t mkv_write_seekhead(AVIOContext *pb, mkv_seekhead *seekhead)
Write the seek head to the file and free it.
Definition: matroskaenc.c:360
Recommmends skipping the specified number of samples.
Definition: avcodec.h:1053
AVIOContext * dyn_bc
Definition: matroskaenc.c:101
AVMediaType
Definition: avutil.h:192
av_cold void av_lfg_init(AVLFG *c, unsigned int seed)
Definition: lfg.c:30
int64_t duration_offset
Definition: matroskaenc.c:107
#define MATROSKA_ID_TITLE
Definition: matroska.h:68
#define snprintf
Definition: snprintf.h:34
#define MATROSKA_ID_TRACKVIDEO
Definition: matroska.h:81
static int mkv_strip_wavpack(const uint8_t *src, uint8_t **pdst, int *size)
Definition: matroskaenc.c:1490
static void put_ebml_id(AVIOContext *pb, unsigned int id)
Definition: matroskaenc.c:150
static void put_ebml_sint(AVIOContext *pb, unsigned int elementid, int64_t val)
Definition: matroskaenc.c:218
static int put_wv_codecpriv(AVIOContext *pb, AVCodecContext *codec)
Definition: matroskaenc.c:522
Views are on top of each other.
Definition: stereo3d.h:55
#define MATROSKA_ID_ATTACHMENTS
Definition: matroska.h:61
static int64_t pts
Global timestamp for the audio frames.
void avio_wb16(AVIOContext *s, unsigned int val)
Definition: aviobuf.c:424
#define MATROSKA_ID_CHAPTERDISPLAY
Definition: matroska.h:218
static int flags
Definition: cpu.c:47
#define MATROSKA_ID_FILENAME
Definition: matroska.h:208
int av_get_bytes_per_sample(enum AVSampleFormat sample_fmt)
Return number of bytes per sample.
Definition: samplefmt.c:104
#define MATROSKA_ID_BLOCKADDITIONAL
Definition: matroska.h:195
const AVMetadataConv ff_mkv_metadata_conv[]
Definition: matroska.c:121
#define MATROSKA_ID_CODECID
Definition: matroska.h:88
static const AVCodecTag additional_video_tags[]
Definition: matroskaenc.c:2004
int64_t start
Definition: avformat.h:1194
Views are next to each other.
Definition: stereo3d.h:45
#define MATROSKA_ID_VIDEOALPHAMODE
Definition: matroska.h:123
static int mkv_write_trailer(AVFormatContext *s)
Definition: matroskaenc.c:1888
Main libavformat public API header.
#define MATROSKA_ID_CUETRACK
Definition: matroska.h:159
#define MATROSKA_ID_SEEKPOSITION
Definition: matroska.h:185
#define MATROSKA_ID_CODECDELAY
Definition: matroska.h:94
#define MATROSKA_ID_CHAPTERTIMESTART
Definition: matroska.h:216
common internal api header.
static void put_ebml_binary(AVIOContext *pb, unsigned int elementid, const void *buf, int size)
Definition: matroskaenc.c:238
static int mkv_write_codecprivate(AVFormatContext *s, AVIOContext *pb, AVCodecContext *codec, int native_id, int qt_id)
Definition: matroskaenc.c:634
static double c[64]
static int mkv_write_flush_packet(AVFormatContext *s, AVPacket *pkt)
Definition: matroskaenc.c:1864
int disposition
AV_DISPOSITION_* bit field.
Definition: avformat.h:870
AVBufferRef * av_buffer_ref(AVBufferRef *buf)
Create a new reference to an AVBuffer.
Definition: buffer.c:92
static void put_ebml_void(AVIOContext *pb, uint64_t size)
Write a void element of a given size.
Definition: matroskaenc.c:258
AVRational time_base
time base in which the start/end timestamps are specified
Definition: avformat.h:1193
void * av_realloc_array(void *ptr, size_t nmemb, size_t size)
Definition: mem.c:206
void av_init_packet(AVPacket *pkt)
Initialize optional fields of a packet with default values.
Definition: avpacket.c:49
char * key
Definition: dict.h:87
int den
denominator
Definition: rational.h:45
#define MATROSKA_ID_SEGMENT
Definition: matroska.h:53
int avpriv_mpeg4audio_get_config(MPEG4AudioConfig *c, const uint8_t *buf, int bit_size, int sync_extension)
Parse MPEG-4 systems extradata to retrieve audio configuration.
Definition: mpeg4audio.c:81
The optional settings (rendering instructions) that immediately follow the timestamp specifier of a W...
Definition: avcodec.h:1099
#define MATROSKA_ID_SEEKHEAD
Definition: matroska.h:60
ASS as defined in Matroska.
Definition: avcodec.h:525
#define EBML_ID_HEADER
Definition: matroska.h:33
#define AVFMT_VARIABLE_FPS
Format allows variable fps.
Definition: avformat.h:440
ebml_master cluster
Definition: matroskaenc.c:104
#define av_free(p)
char * value
Definition: dict.h:88
#define MATROSKA_ID_POINTENTRY
Definition: matroska.h:152
mkv_seekhead_entry * entries
Definition: matroskaenc.c:70
int len
int channels
number of audio channels
Definition: avcodec.h:1984
#define av_log2
Definition: intmath.h:105
static int mkv_write_stereo_mode(AVFormatContext *s, AVIOContext *pb, AVStream *st, int mode, int *h_width, int *h_height)
Definition: matroskaenc.c:704
#define MATROSKA_ID_FILEUID
Definition: matroska.h:211
int ff_put_wav_header(AVIOContext *pb, AVCodecContext *enc, int flags)
Write WAVEFORMAT header structure.
Definition: riffenc.c:54
Views are packed in a checkerboard-like structure per pixel.
Definition: stereo3d.h:76
void * priv_data
Format private data.
Definition: avformat.h:1254
#define MATROSKA_ID_CHAPTERUID
Definition: matroska.h:225
Views are packed per column.
Definition: stereo3d.h:107
static void write_header(FFV1Context *f)
Definition: ffv1enc.c:493
int64_t relative_pos
relative offset from the position of the cluster containing the block
Definition: matroskaenc.c:79
int64_t dts
Decompression timestamp in AVStream->time_base units; the time at which the packet is decompressed...
Definition: avcodec.h:1159
static void mkv_flush_dynbuf(AVFormatContext *s)
Definition: matroskaenc.c:1672
static const AVOption options[]
Definition: matroskaenc.c:2021
static void * av_mallocz_array(size_t nmemb, size_t size)
Definition: mem.h:228
#define EBML_ID_EBMLMAXSIZELENGTH
Definition: matroska.h:39
void avio_wb32(AVIOContext *s, unsigned int val)
Definition: aviobuf.c:326
#define MATROSKA_ID_CHAPSTRING
Definition: matroska.h:219
#define av_freep(p)
#define MATROSKA_ID_TAGSTRING
Definition: matroska.h:169
#define AV_DICT_IGNORE_SUFFIX
Return first entry in a dictionary whose first part corresponds to the search key, ignoring the suffix of the found key string.
Definition: dict.h:72
uint8_t * av_packet_get_side_data(AVPacket *pkt, enum AVPacketSideDataType type, int *size)
Get side information from packet.
Definition: avpacket.c:325
#define MODE_MATROSKAv2
Definition: matroskaenc.c:95
uint32_t av_get_random_seed(void)
Get a seed to use in conjunction with random functions.
Definition: random_seed.c:114
int ff_isom_write_hvcc(AVIOContext *pb, const uint8_t *data, int size, int ps_array_completeness)
Writes HEVC extradata (parameter sets, declarative SEI NAL units) to the provided AVIOContext...
Definition: hevc.c:1093
const CodecMime ff_mkv_image_mime_tags[]
Definition: matroska.c:102
#define MODE_WEBM
Definition: matroskaenc.c:96
static int mkv_write_packet(AVFormatContext *s, AVPacket *pkt)
Definition: matroskaenc.c:1786
#define MATROSKA_ID_DURATION
Definition: matroska.h:67
#define MAX_SEEKENTRY_SIZE
2 bytes * 3 for EBML IDs, 3 1-byte EBML lengths, 8 bytes for 64 bit offset, 4 bytes for target EBML I...
Definition: matroskaenc.c:133
static mkv_cues * mkv_start_cues(int64_t segment_offset)
Definition: matroskaenc.c:404
int stream_index
Definition: avcodec.h:1162
int num_entries
Definition: matroskaenc.c:86
#define EBML_ID_DOCTYPEVERSION
Definition: matroska.h:41
static void end_ebml_master(AVIOContext *pb, ebml_master master)
Definition: matroskaenc.c:284
int64_t segment_offset
Definition: matroskaenc.c:103
#define CONFIG_LIBX264_ENCODER
Definition: config.h:1377
int av_copy_packet_side_data(AVPacket *dst, const AVPacket *src)
Copy packet side data.
Definition: avpacket.c:224
#define MATROSKA_ID_ATTACHEDFILE
Definition: matroska.h:206
static ebml_master start_ebml_master(AVIOContext *pb, unsigned int elementid, uint64_t expectedsize)
Definition: matroskaenc.c:275
mkv_seekhead * main_seekhead
Definition: matroskaenc.c:109
This structure stores compressed data.
Definition: avcodec.h:1137
static int write_packet(AVFormatContext *s1, AVPacket *pkt)
Definition: v4l2enc.c:86
void * av_mallocz(size_t size)
Allocate a block of size bytes with alignment suitable for all memory accesses (including vectors if ...
Definition: mem.c:250
uint32_t blocksize
Definition: wv.h:35
static int mkv_query_codec(enum AVCodecID codec_id, int std_compliance)
Definition: matroskaenc.c:1971
static void put_xiph_size(AVIOContext *pb, int size)
Definition: matroskaenc.c:294
int64_t pts
Presentation timestamp in AVStream->time_base units; the time at which the decompressed packet will b...
Definition: avcodec.h:1153
#define MATROSKA_ID_VIDEOPIXELWIDTH
Definition: matroska.h:114
int ff_isom_write_avcc(AVIOContext *pb, const uint8_t *data, int len)
Definition: avc.c:106
#define MATROSKA_ID_TRACKAUDIO
Definition: matroska.h:82
#define AV_NOPTS_VALUE
Undefined timestamp value.
Definition: avutil.h:241
const CodecTags ff_mkv_codec_tags[]
Definition: matroska.c:29
int avio_printf(AVIOContext *s, const char *fmt,...) av_printf_format(2
#define AV_WL32(p, v)
Definition: intreadwrite.h:426
#define MATROSKA_ID_DISCARDPADDING
Definition: matroska.h:203
#define FF_PUT_WAV_HEADER_FORCE_WAVEFORMATEX
Tell ff_put_wav_header() to use WAVEFORMATEX even for PCM codecs.
Definition: riff.h:53