FFmpeg
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 "config_components.h"
25 
26 #include "av1.h"
27 #include "avc.h"
28 #include "hevc.h"
29 #include "avformat.h"
30 #include "avio_internal.h"
31 #include "avlanguage.h"
32 #include "dovi_isom.h"
33 #include "flacenc.h"
34 #include "internal.h"
35 #include "isom.h"
36 #include "nal.h"
37 #include "matroska.h"
38 #include "mux.h"
39 #include "riff.h"
40 #include "version.h"
41 #include "vorbiscomment.h"
42 #include "wv.h"
43 
44 #include "libavutil/avstring.h"
46 #include "libavutil/crc.h"
47 #include "libavutil/dict.h"
49 #include "libavutil/intfloat.h"
50 #include "libavutil/intreadwrite.h"
51 #include "libavutil/lfg.h"
53 #include "libavutil/mathematics.h"
54 #include "libavutil/mem.h"
55 #include "libavutil/opt.h"
56 #include "libavutil/parseutils.h"
57 #include "libavutil/pixdesc.h"
58 #include "libavutil/random_seed.h"
59 #include "libavutil/rational.h"
60 #include "libavutil/samplefmt.h"
61 #include "libavutil/stereo3d.h"
62 
63 #include "libavcodec/av1.h"
64 #include "libavcodec/bytestream.h"
65 #include "libavcodec/codec_desc.h"
66 #include "libavcodec/codec_par.h"
67 #include "libavcodec/defs.h"
68 #include "libavcodec/itut35.h"
69 #include "libavcodec/xiph.h"
70 #include "libavcodec/mpeg4audio.h"
71 
72 /* Level 1 elements we create a SeekHead entry for:
73  * Info, Tracks, Chapters, Attachments, Tags (potentially twice) and Cues */
74 #define MAX_SEEKHEAD_ENTRIES 7
75 
76 /* Largest known-length EBML length */
77 #define MAX_EBML_LENGTH ((1ULL << 56) - 2)
78 /* The dynamic buffer API we rely upon has a limit of INT_MAX;
79  * and so has avio_write(). */
80 #define MAX_SUPPORTED_EBML_LENGTH FFMIN(MAX_EBML_LENGTH, INT_MAX)
81 
82 #define MODE_MATROSKAv2 0x01
83 #define MODE_WEBM 0x02
84 
85 #define IS_WEBM(mkv) (CONFIG_WEBM_MUXER && CONFIG_MATROSKA_MUXER ? \
86  ((mkv)->mode == MODE_WEBM) : CONFIG_WEBM_MUXER)
87 #define IS_SEEKABLE(pb, mkv) (((pb)->seekable & AVIO_SEEKABLE_NORMAL) && \
88  !(mkv)->is_live)
89 
90 enum {
94 };
95 
96 typedef struct ebml_master {
97  int64_t pos; ///< absolute offset in the containing AVIOContext where the master's elements start
98  int sizebytes; ///< how many bytes were reserved for the size
99 } ebml_master;
100 
101 typedef struct ebml_stored_master {
105 
106 typedef enum EbmlType {
114  EBML_BLOCK, ///< pseudo-type for writing (Simple)Blocks
116 } EbmlType;
117 
118 typedef struct BlockContext {
119  struct mkv_track *track;
120  const AVPacket *pkt;
121  int16_t rel_ts;
122  uint8_t flags;
124 } BlockContext;
125 
126 typedef struct EbmlMaster {
127  int nb_elements; ///< -1 if not finished
128  int containing_master; ///< -1 if no parent exists
129 } EbmlMaster;
130 
131 typedef struct EbmlElement {
132  uint32_t id;
134  unsigned length_size;
135  uint64_t size; ///< excluding id and length field
136  union {
137  uint64_t uint;
139  double f;
140  const char *str;
141  const uint8_t *bin;
142  struct MatroskaMuxContext *mkv; ///< used by EBML_BLOCK
144  } priv;
145 } EbmlElement;
146 
147 typedef struct EbmlWriter {
148  unsigned nb_elements;
151 } EbmlWriter;
152 
153 #define EBML_WRITER(max_nb_elems) \
154  EbmlElement elements[max_nb_elems]; \
155  EbmlWriter writer = (EbmlWriter){ .elements = elements, \
156  .current_master_element = -1 }
157 
158 typedef struct mkv_seekhead_entry {
159  uint32_t elementid;
160  uint64_t segmentpos;
162 
163 typedef struct mkv_seekhead {
168 } mkv_seekhead;
169 
170 typedef struct mkv_cuepoint {
171  uint64_t pts;
173  int64_t cluster_pos; ///< offset of the cluster containing the block relative to the segment
174  int64_t relative_pos; ///< relative offset from the position of the cluster containing the block
175  int64_t duration; ///< duration of the block according to time base
176 } mkv_cuepoint;
177 
178 typedef struct mkv_cues {
181 } mkv_cues;
182 
183 struct MatroskaMuxContext;
184 
185 typedef struct mkv_track {
187  int has_cue;
188  uint64_t uid;
189  unsigned track_num;
192  unsigned offset;
197  uint64_t max_blockaddid;
200  unsigned codecpriv_size; ///< size reserved for CodecPrivate excluding header+length field
204  /* This callback will be called twice: First with a NULL AVIOContext
205  * to return the size of the (Simple)Block's data via size
206  * and a second time with the AVIOContext set when the data
207  * shall be written.
208  * The callback shall not return an error on the second call. */
210  const AVPacket *, int *size);
211 } mkv_track;
212 
213 typedef struct MatroskaMuxContext {
214  const AVClass *class;
216 
217  int mode;
223  int64_t cluster_pos; ///< file offset of the current Cluster
231 
233 
234  /* Used as temporary buffer to use the minimal amount of bytes
235  * to write the length field of EBML Masters.
236  * Every user has to reset the buffer after using it and
237  * different uses may not overlap. It is currently used in
238  * mkv_write_tag(), in mkv_assemble_cues() as well as in
239  * mkv_update_codecprivate() and mkv_write_track(). */
241 
243 
244  unsigned nb_attachments;
246 
249 
254  int is_live;
255 
256  int is_dash;
262 
263  uint32_t segment_uid[4];
265 
266 /** 2 bytes * 3 for EBML IDs, 3 1-byte EBML lengths, 8 bytes for 64 bit
267  * offset, 4 bytes for target EBML ID */
268 #define MAX_SEEKENTRY_SIZE 21
269 
270 /** 4 * (1-byte EBML ID, 1-byte EBML size, 8-byte uint max) */
271 #define MAX_CUETRACKPOS_SIZE 40
272 
273 /** DURATION_STRING_LENGTH must be <= 112 or the containing
274  * simpletag will need more than one byte for its length field. */
275 #define DURATION_STRING_LENGTH 19
276 
277 /** 2 + 1 Simpletag header, 2 + 1 + 8 Name "DURATION", rest for TagString */
278 #define DURATION_SIMPLETAG_SIZE (2 + 1 + (2 + 1 + 8) + (2 + 1 + DURATION_STRING_LENGTH))
279 
280 /** Seek preroll value for opus */
281 #define OPUS_SEEK_PREROLL 80000000
282 
283 static int ebml_id_size(uint32_t id)
284 {
285  return (av_log2(id) + 7U) / 8;
286 }
287 
288 static void put_ebml_id(AVIOContext *pb, uint32_t id)
289 {
290  int i = ebml_id_size(id);
291  while (i--)
292  avio_w8(pb, (uint8_t)(id >> (i * 8)));
293 }
294 
295 /**
296  * Write an EBML size meaning "unknown size".
297  *
298  * @param bytes The number of bytes the size should occupy (maximum: 8).
299  */
300 static void put_ebml_size_unknown(AVIOContext *pb, int bytes)
301 {
302  av_assert0(bytes <= 8);
303  avio_w8(pb, 0x1ff >> bytes);
304  if (av_builtin_constant_p(bytes) && bytes == 1)
305  return;
306  ffio_fill(pb, 0xff, bytes - 1);
307 }
308 
309 /**
310  * Returns how many bytes are needed to represent a number
311  * as EBML variable length integer.
312  */
313 static int ebml_num_size(uint64_t num)
314 {
315  int bytes = 0;
316  do {
317  bytes++;
318  } while (num >>= 7);
319  return bytes;
320 }
321 
322 /**
323  * Calculate how many bytes are needed to represent the length field
324  * of an EBML element whose payload has a given length.
325  */
326 static int ebml_length_size(uint64_t length)
327 {
328  return ebml_num_size(length + 1);
329 }
330 
331 /**
332  * Write a number as EBML variable length integer on `bytes` bytes.
333  * `bytes` is taken literally without checking.
334  */
335 static void put_ebml_num(AVIOContext *pb, uint64_t num, int bytes)
336 {
337  num |= 1ULL << bytes * 7;
338  for (int i = bytes - 1; i >= 0; i--)
339  avio_w8(pb, (uint8_t)(num >> i * 8));
340 }
341 
342 /**
343  * Write a length as EBML variable length integer.
344  *
345  * @param bytes The number of bytes that need to be used to write the number.
346  * If zero, the minimal number of bytes will be used.
347  */
348 static void put_ebml_length(AVIOContext *pb, uint64_t length, int bytes)
349 {
350  int needed_bytes = ebml_length_size(length);
351 
352  // sizes larger than this are currently undefined in EBML
353  av_assert0(length < (1ULL << 56) - 1);
354 
355  if (bytes == 0)
356  bytes = needed_bytes;
357  // The bytes needed to write the given size must not exceed
358  // the bytes that we ought to use.
359  av_assert0(bytes >= needed_bytes);
360  put_ebml_num(pb, length, bytes);
361 }
362 
363 /**
364  * Write a (random) UID with fixed size to make the output more deterministic
365  */
366 static void put_ebml_uid(AVIOContext *pb, uint32_t elementid, uint64_t uid)
367 {
368  put_ebml_id(pb, elementid);
369  put_ebml_length(pb, 8, 0);
370  avio_wb64(pb, uid);
371 }
372 
373 static void put_ebml_uint(AVIOContext *pb, uint32_t elementid, uint64_t val)
374 {
375  int i, bytes = 1;
376  uint64_t tmp = val;
377  while (tmp >>= 8)
378  bytes++;
379 
380  put_ebml_id(pb, elementid);
381  put_ebml_length(pb, bytes, 0);
382  for (i = bytes - 1; i >= 0; i--)
383  avio_w8(pb, (uint8_t)(val >> i * 8));
384 }
385 
386 static void put_ebml_float(AVIOContext *pb, uint32_t elementid, double val)
387 {
388  put_ebml_id(pb, elementid);
389  put_ebml_length(pb, 8, 0);
391 }
392 
393 static void put_ebml_binary(AVIOContext *pb, uint32_t elementid,
394  const void *buf, int size)
395 {
396  put_ebml_id(pb, elementid);
397  put_ebml_length(pb, size, 0);
398  avio_write(pb, buf, size);
399 }
400 
401 static void put_ebml_string(AVIOContext *pb, uint32_t elementid,
402  const char *str)
403 {
404  put_ebml_binary(pb, elementid, str, strlen(str));
405 }
406 
407 /**
408  * Write a void element of a given size. Useful for reserving space in
409  * the file to be written to later.
410  *
411  * @param size The number of bytes to reserve, which must be at least 2.
412  */
413 static void put_ebml_void(AVIOContext *pb, int size)
414 {
415  av_assert0(size >= 2);
416 
418  // we need to subtract the length needed to store the size from the
419  // size we need to reserve so 2 cases, we use 8 bytes to store the
420  // size if possible, 1 byte otherwise
421  if (size < 10) {
422  size -= 2;
423  put_ebml_length(pb, size, 0);
424  } else {
425  size -= 9;
426  put_ebml_length(pb, size, 8);
427  }
428  ffio_fill(pb, 0, size);
429 }
430 
431 static ebml_master start_ebml_master(AVIOContext *pb, uint32_t elementid,
432  uint64_t expectedsize)
433 {
434  int bytes = expectedsize ? ebml_length_size(expectedsize) : 8;
435 
436  put_ebml_id(pb, elementid);
437  put_ebml_size_unknown(pb, bytes);
438  return (ebml_master) { avio_tell(pb), bytes };
439 }
440 
442 {
443  int64_t pos = avio_tell(pb);
444 
445  if (avio_seek(pb, master.pos - master.sizebytes, SEEK_SET) < 0)
446  return;
447  put_ebml_length(pb, pos - master.pos, master.sizebytes);
448  avio_seek(pb, pos, SEEK_SET);
449 }
450 
452  uint32_t id, EbmlType type)
453 {
454  writer->elements[writer->nb_elements].id = id;
455  writer->elements[writer->nb_elements].type = type;
456  return &writer->elements[writer->nb_elements++];
457 }
458 
459 static void ebml_writer_open_master(EbmlWriter *writer, uint32_t id)
460 {
461  EbmlElement *const elem = ebml_writer_add(writer, id, EBML_MASTER);
462  EbmlMaster *const master = &elem->priv.master;
463 
464  master->containing_master = writer->current_master_element;
465  master->nb_elements = -1;
466 
467  writer->current_master_element = writer->nb_elements - 1;
468 }
469 
471 {
472  EbmlElement *elem;
473  av_assert2(writer->current_master_element >= 0);
474  av_assert2(writer->current_master_element < writer->nb_elements);
475  elem = &writer->elements[writer->current_master_element];
476  av_assert2(elem->type == EBML_MASTER);
477  av_assert2(elem->priv.master.nb_elements < 0); /* means unset */
478  elem->priv.master.nb_elements = writer->nb_elements - writer->current_master_element - 1;
482 }
483 
485 {
486  av_assert2(writer->nb_elements > 0);
487  av_assert2(0 <= writer->current_master_element);
488  av_assert2(writer->current_master_element < writer->nb_elements);
489  if (writer->current_master_element == writer->nb_elements - 1) {
490  const EbmlElement *const elem = &writer->elements[writer->nb_elements - 1];
491  /* The master element has no children. Discard it. */
492  av_assert2(elem->type == EBML_MASTER);
496  writer->nb_elements--;
497  return;
498  }
499  ebml_writer_close_master(writer);
500 }
501 
502 static void ebml_writer_add_string(EbmlWriter *writer, uint32_t id,
503  const char *str)
504 {
505  EbmlElement *const elem = ebml_writer_add(writer, id, EBML_STR);
506 
507  elem->priv.str = str;
508 }
509 
510 static void ebml_writer_add_bin(EbmlWriter *writer, uint32_t id,
511  const uint8_t *data, size_t size)
512 {
513  EbmlElement *const elem = ebml_writer_add(writer, id, EBML_BIN);
514 
515 #if SIZE_MAX > UINT64_MAX
516  size = FFMIN(size, UINT64_MAX);
517 #endif
518  elem->size = size;
519  elem->priv.bin = data;
520 }
521 
522 static void ebml_writer_add_float(EbmlWriter *writer, uint32_t id,
523  double val)
524 {
525  EbmlElement *const elem = ebml_writer_add(writer, id, EBML_FLOAT);
526 
527  elem->priv.f = val;
528 }
529 
530 static void ebml_writer_add_uid(EbmlWriter *writer, uint32_t id,
531  uint64_t val)
532 {
533  EbmlElement *const elem = ebml_writer_add(writer, id, EBML_UID);
534  elem->priv.uint = val;
535 }
536 
537 static void ebml_writer_add_uint(EbmlWriter *writer, uint32_t id,
538  uint64_t val)
539 {
540  EbmlElement *elem = ebml_writer_add(writer, id, EBML_UINT);
541  elem->priv.uint = val;
542 }
543 
544 static void ebml_writer_add_sint(EbmlWriter *writer, uint32_t id,
545  int64_t val)
546 {
547  EbmlElement *elem = ebml_writer_add(writer, id, EBML_SINT);
548  elem->priv.sint = val;
549 }
550 
552 {
554  elem->priv.mkv = mkv;
555 }
556 
558 {
559  size_t len = strlen(elem->priv.str);
560 #if SIZE_MAX > UINT64_MAX
561  len = FF_MIN(len, UINT64_MAX);
562 #endif
563  elem->size = len;
564  return 0;
565 }
566 
567 static av_const int uint_size(uint64_t val)
568 {
569  int bytes = 0;
570  do {
571  bytes++;
572  } while (val >>= 8);
573  return bytes;
574 }
575 
577 {
578  elem->size = uint_size(elem->priv.uint);
579  return 0;
580 }
581 
583 {
584  uint64_t tmp = 2 * (uint64_t)(val < 0 ? val^-1 : val);
585  return uint_size(tmp);
586 }
587 
589 {
590  elem->size = sint_size(elem->priv.sint);
591  return 0;
592 }
593 
594 static int ebml_writer_elem_len(EbmlWriter *writer, EbmlElement *elem,
595  int remaining_elems);
596 
598  int remaining_elems)
599 {
600  int nb_elems = elem->priv.master.nb_elements >= 0 ? elem->priv.master.nb_elements : remaining_elems - 1;
601  EbmlElement *const master = elem;
602  uint64_t total_size = 0;
603 
604  master->priv.master.nb_elements = nb_elems;
605  for (; elem++, nb_elems > 0;) {
606  int ret = ebml_writer_elem_len(writer, elem, nb_elems);
607  if (ret < 0)
608  return ret;
609  av_assert2(ret < nb_elems);
610  /* No overflow is possible here, as both total_size and elem->size
611  * are bounded by MAX_SUPPORTED_EBML_LENGTH. */
612  total_size += ebml_id_size(elem->id) + elem->length_size + elem->size;
613  if (total_size > MAX_SUPPORTED_EBML_LENGTH)
614  return AVERROR(ERANGE);
615  nb_elems--; /* consume elem */
616  elem += ret, nb_elems -= ret; /* and elem's children */
617  }
618  master->size = total_size;
619 
620  return master->priv.master.nb_elements;
621 }
622 
624 {
625  MatroskaMuxContext *const mkv = elem->priv.mkv;
626  BlockContext *const block = &mkv->cur_block;
627  mkv_track *const track = block->track;
628  const AVPacket *const pkt = block->pkt;
629  int err, size;
630 
631  if (track->reformat) {
632  err = track->reformat(mkv, NULL, pkt, &size);
633  if (err < 0) {
634  av_log(mkv->ctx, AV_LOG_ERROR, "Error when reformatting data of "
635  "a packet from stream %d.\n", pkt->stream_index);
636  return err;
637  }
638  } else {
639  size = pkt->size;
640  if (track->offset <= size)
641  size -= track->offset;
642  }
643  elem->size = track->track_num_size + 3U + size;
644 
645  return 0;
646 }
647 
648 static void ebml_writer_write_block(const EbmlElement *elem, AVIOContext *pb)
649 {
650  MatroskaMuxContext *const mkv = elem->priv.mkv;
651  BlockContext *const block = &mkv->cur_block;
652  mkv_track *const track = block->track;
653  const AVPacket *const pkt = block->pkt;
654 
655  put_ebml_num(pb, track->track_num, track->track_num_size);
656  avio_wb16(pb, block->rel_ts);
657  avio_w8(pb, block->flags);
658 
659  if (track->reformat) {
660  int size;
661  track->reformat(mkv, pb, pkt, &size);
662  } else {
663  const uint8_t *data = pkt->data;
664  unsigned offset = track->offset <= pkt->size ? track->offset : 0;
665  avio_write(pb, data + offset, pkt->size - offset);
666  }
667 }
668 
669 static int ebml_writer_elem_len(EbmlWriter *writer, EbmlElement *elem,
670  int remaining_elems)
671 {
672  int ret = 0;
673 
674  switch (elem->type) {
675  case EBML_FLOAT:
676  case EBML_UID:
677  elem->size = 8;
678  break;
679  case EBML_STR:
680  ret = ebml_writer_str_len(elem);
681  break;
682  case EBML_UINT:
683  ret = ebml_writer_uint_len(elem);
684  break;
685  case EBML_SINT:
686  ret = ebml_writer_sint_len(elem);
687  break;
688  case EBML_BLOCK:
689  ret = ebml_writer_block_len(elem);
690  break;
691  case EBML_MASTER:
692  ret = ebml_writer_master_len(writer, elem, remaining_elems);
693  break;
694  }
695  if (ret < 0)
696  return ret;
697  if (elem->size > MAX_SUPPORTED_EBML_LENGTH)
698  return AVERROR(ERANGE);
699  elem->length_size = ebml_length_size(elem->size);
700  return ret; /* number of elements consumed excluding elem itself */
701 }
702 
703 static int ebml_writer_elem_write(const EbmlElement *elem, AVIOContext *pb)
704 {
705  put_ebml_id(pb, elem->id);
706  put_ebml_num(pb, elem->size, elem->length_size);
707  switch (elem->type) {
708  case EBML_UID:
709  case EBML_FLOAT: {
710  uint64_t val = elem->type == EBML_UID ? elem->priv.uint
711  : av_double2int(elem->priv.f);
712  avio_wb64(pb, val);
713  break;
714  }
715  case EBML_UINT:
716  case EBML_SINT: {
717  uint64_t val = elem->type == EBML_UINT ? elem->priv.uint
718  : elem->priv.sint;
719  for (int i = elem->size; --i >= 0; )
720  avio_w8(pb, (uint8_t)(val >> i * 8));
721  break;
722  }
723  case EBML_STR:
724  case EBML_BIN: {
725  const uint8_t *data = elem->type == EBML_BIN ? elem->priv.bin
726  : (const uint8_t*)elem->priv.str;
727  avio_write(pb, data, elem->size);
728  break;
729  }
730  case EBML_BLOCK:
731  ebml_writer_write_block(elem, pb);
732  break;
733  case EBML_MASTER: {
734  int nb_elems = elem->priv.master.nb_elements;
735 
736  elem++;
737  for (int i = 0; i < nb_elems; i++)
738  i += ebml_writer_elem_write(elem + i, pb);
739 
740  return nb_elems;
741  }
742  }
743  return 0;
744 }
745 
746 static int ebml_writer_write(EbmlWriter *writer, AVIOContext *pb)
747 {
748  int ret = ebml_writer_elem_len(writer, writer->elements,
749  writer->nb_elements);
750  if (ret < 0)
751  return ret;
752  ebml_writer_elem_write(writer->elements, pb);
753  return 0;
754 }
755 
756 static void mkv_add_seekhead_entry(MatroskaMuxContext *mkv, uint32_t elementid,
757  uint64_t filepos)
758 {
759  mkv_seekhead *seekhead = &mkv->seekhead;
760 
762 
763  seekhead->entries[seekhead->num_entries].elementid = elementid;
764  seekhead->entries[seekhead->num_entries++].segmentpos = filepos - mkv->segment_offset;
765 }
766 
768 {
769  int ret;
770 
771  if (!*dyn_cp && (ret = avio_open_dyn_buf(dyn_cp)) < 0)
772  return ret;
773 
774  if (mkv->write_crc)
775  put_ebml_void(*dyn_cp, 6); /* Reserve space for CRC32 so position/size calculations using avio_tell() take it into account */
776 
777  return 0;
778 }
779 
781  MatroskaMuxContext *mkv, uint32_t id,
782  int length_size, int keep_buffer,
783  int add_seekentry)
784 {
785  uint8_t *buf, crc[4];
786  int ret, size, skip = 0;
787 
788  size = avio_get_dyn_buf(*dyn_cp, &buf);
789  if ((ret = (*dyn_cp)->error) < 0)
790  goto fail;
791 
792  if (add_seekentry)
793  mkv_add_seekhead_entry(mkv, id, avio_tell(pb));
794 
795  put_ebml_id(pb, id);
796  put_ebml_length(pb, size, length_size);
797  if (mkv->write_crc) {
798  skip = 6; /* Skip reserved 6-byte long void element from the dynamic buffer. */
799  AV_WL32(crc, av_crc(av_crc_get_table(AV_CRC_32_IEEE_LE), UINT32_MAX, buf + skip, size - skip) ^ UINT32_MAX);
800  put_ebml_binary(pb, EBML_ID_CRC32, crc, sizeof(crc));
801  }
802  avio_write(pb, buf + skip, size - skip);
803 
804 fail:
805  if (keep_buffer) {
806  ffio_reset_dyn_buf(*dyn_cp);
807  } else {
808  ffio_free_dyn_buf(dyn_cp);
809  }
810  return ret;
811 }
812 
813 /**
814  * Output EBML master. Keep the buffer if seekable, allowing for later updates.
815  * Furthermore always add a SeekHead Entry for this element.
816  */
818  ebml_stored_master *elem,
819  MatroskaMuxContext *mkv, uint32_t id)
820 {
821  if (IS_SEEKABLE(pb, mkv)) {
822  uint8_t *buf;
823  int size = avio_get_dyn_buf(elem->bc, &buf);
824 
825  if (elem->bc->error < 0)
826  return elem->bc->error;
827 
828  elem->pos = avio_tell(pb);
829  mkv_add_seekhead_entry(mkv, id, elem->pos);
830 
831  put_ebml_id(pb, id);
832  put_ebml_length(pb, size, 0);
833  avio_write(pb, buf, size);
834 
835  return 0;
836  } else
837  return end_ebml_master_crc32(pb, &elem->bc, mkv, id, 0, 0, 1);
838 }
839 
840 static void put_xiph_size(AVIOContext *pb, int size)
841 {
842  ffio_fill(pb, 255, size / 255);
843  avio_w8(pb, size % 255);
844 }
845 
846 /**
847  * Free the members allocated in the mux context.
848  */
850 {
851  MatroskaMuxContext *mkv = s->priv_data;
852 
854  ffio_free_dyn_buf(&mkv->info.bc);
855  ffio_free_dyn_buf(&mkv->track.bc);
856  ffio_free_dyn_buf(&mkv->tags.bc);
857  ffio_free_dyn_buf(&mkv->tmp_bc);
858 
860  av_freep(&mkv->cues.entries);
861  av_freep(&mkv->tracks);
862 }
863 
864 /**
865  * Initialize the SeekHead element to be ready to index level 1 Matroska
866  * elements. Enough space to write MAX_SEEKHEAD_ENTRIES SeekHead entries
867  * will be reserved at the current file location.
868  */
870 {
871  mkv->seekhead.filepos = avio_tell(pb);
872  // 21 bytes max for a Seek entry, 6 bytes max for the SeekHead ID
873  // and size, 6 bytes for a CRC32 element, and 2 bytes to guarantee
874  // that an EBML void element will fit afterwards
877 }
878 
879 /**
880  * Write the SeekHead to the file at the location reserved for it
881  * and seek to destpos afterwards. When error_on_seek_failure
882  * is not set, failure to seek to the position designated for the
883  * SeekHead is not considered an error and it is presumed that
884  * destpos is the current position; failure to seek to destpos
885  * afterwards is always an error.
886  *
887  * @return 0 on success, < 0 on error.
888  */
890  int error_on_seek_failure, int64_t destpos)
891 {
892  AVIOContext *dyn_cp = NULL;
893  mkv_seekhead *seekhead = &mkv->seekhead;
894  int64_t remaining, ret64;
895  int i, ret;
896 
897  if ((ret64 = avio_seek(pb, seekhead->filepos, SEEK_SET)) < 0)
898  return error_on_seek_failure ? ret64 : 0;
899 
900  ret = start_ebml_master_crc32(&dyn_cp, mkv);
901  if (ret < 0)
902  return ret;
903 
904  for (i = 0; i < seekhead->num_entries; i++) {
905  mkv_seekhead_entry *entry = &seekhead->entries[i];
908 
910  put_ebml_length(dyn_cp, ebml_id_size(entry->elementid), 0);
911  put_ebml_id(dyn_cp, entry->elementid);
912 
913  put_ebml_uint(dyn_cp, MATROSKA_ID_SEEKPOSITION, entry->segmentpos);
914  end_ebml_master(dyn_cp, seekentry);
915  }
916  ret = end_ebml_master_crc32(pb, &dyn_cp, mkv,
917  MATROSKA_ID_SEEKHEAD, 0, 0, 0);
918  if (ret < 0)
919  return ret;
920 
921  remaining = seekhead->filepos + seekhead->reserved_size - avio_tell(pb);
922  put_ebml_void(pb, remaining);
923 
924  if ((ret64 = avio_seek(pb, destpos, SEEK_SET)) < 0)
925  return ret64;
926 
927  return 0;
928 }
929 
930 static int mkv_add_cuepoint(MatroskaMuxContext *mkv, int stream, int64_t ts,
931  int64_t cluster_pos, int64_t relative_pos, int64_t duration)
932 {
933  mkv_cues *cues = &mkv->cues;
934  mkv_cuepoint *entries = cues->entries;
935  unsigned idx = cues->num_entries;
936 
937  if (ts < 0)
938  return 0;
939 
940  entries = av_realloc_array(entries, cues->num_entries + 1, sizeof(mkv_cuepoint));
941  if (!entries)
942  return AVERROR(ENOMEM);
943  cues->entries = entries;
944 
945  /* Make sure the cues entries are sorted by pts. */
946  while (idx > 0 && entries[idx - 1].pts > ts)
947  idx--;
948  memmove(&entries[idx + 1], &entries[idx],
949  (cues->num_entries - idx) * sizeof(entries[0]));
950 
951  entries[idx].pts = ts;
952  entries[idx].stream_idx = stream;
953  entries[idx].cluster_pos = cluster_pos - mkv->segment_offset;
954  entries[idx].relative_pos = relative_pos;
955  entries[idx].duration = duration;
956 
957  cues->num_entries++;
958 
959  return 0;
960 }
961 
962 static int mkv_assemble_cues(AVStream **streams, AVIOContext *dyn_cp, AVIOContext *cuepoint,
963  const mkv_cues *cues, mkv_track *tracks, int num_tracks,
964  uint64_t offset)
965 {
966  for (mkv_cuepoint *entry = cues->entries, *end = entry + cues->num_entries;
967  entry < end;) {
968  uint64_t pts = entry->pts;
969  uint8_t *buf;
970  int size;
971 
973 
974  // put all the entries from different tracks that have the exact same
975  // timestamp into the same CuePoint
976  for (int j = 0; j < num_tracks; j++)
977  tracks[j].has_cue = 0;
978  do {
979  ebml_master track_positions;
980  int idx = entry->stream_idx;
981 
982  av_assert0(idx >= 0 && idx < num_tracks);
983  if (tracks[idx].has_cue && streams[idx]->codecpar->codec_type != AVMEDIA_TYPE_SUBTITLE)
984  continue;
985  tracks[idx].has_cue = 1;
987  put_ebml_uint(cuepoint, MATROSKA_ID_CUETRACK , tracks[idx].track_num);
988  put_ebml_uint(cuepoint, MATROSKA_ID_CUECLUSTERPOSITION , entry->cluster_pos + offset);
989  put_ebml_uint(cuepoint, MATROSKA_ID_CUERELATIVEPOSITION, entry->relative_pos);
990  if (entry->duration > 0)
991  put_ebml_uint(cuepoint, MATROSKA_ID_CUEDURATION , entry->duration);
992  end_ebml_master(cuepoint, track_positions);
993  } while (++entry < end && entry->pts == pts);
994  size = avio_get_dyn_buf(cuepoint, &buf);
995  if (cuepoint->error < 0)
996  return cuepoint->error;
998  ffio_reset_dyn_buf(cuepoint);
999  }
1000 
1001  return 0;
1002 }
1003 
1005  const AVCodecParameters *par,
1006  const uint8_t *extradata, int extradata_size)
1007 {
1008  const uint8_t *header_start[3];
1009  int header_len[3];
1010  int first_header_size;
1011  int err, j;
1012 
1013  if (par->codec_id == AV_CODEC_ID_VORBIS)
1014  first_header_size = 30;
1015  else
1016  first_header_size = 42;
1017 
1018  err = avpriv_split_xiph_headers(extradata, extradata_size,
1019  first_header_size, header_start, header_len);
1020  if (err < 0) {
1021  av_log(s, AV_LOG_ERROR, "Extradata corrupt.\n");
1022  return err;
1023  }
1024 
1025  avio_w8(pb, 2); // number packets - 1
1026  for (j = 0; j < 2; j++) {
1027  put_xiph_size(pb, header_len[j]);
1028  }
1029  for (j = 0; j < 3; j++)
1030  avio_write(pb, header_start[j], header_len[j]);
1031 
1032  return 0;
1033 }
1034 
1035 #if CONFIG_MATROSKA_MUXER
1036 static int put_wv_codecpriv(AVIOContext *pb, const uint8_t *extradata, int extradata_size)
1037 {
1038  if (extradata && extradata_size == 2)
1039  avio_write(pb, extradata, 2);
1040  else
1041  avio_wl16(pb, 0x410); // fallback to the most recent version
1042  return 0;
1043 }
1044 
1045 static int put_flac_codecpriv(AVFormatContext *s, AVIOContext *pb,
1046  const AVCodecParameters *par,
1047  const uint8_t *extradata, int extradata_size)
1048 {
1049  int write_comment = (par->ch_layout.order == AV_CHANNEL_ORDER_NATIVE &&
1050  !(par->ch_layout.u.mask & ~0x3ffffULL) &&
1052  int ret = ff_flac_write_header(pb, extradata, extradata_size,
1053  !write_comment);
1054 
1055  if (ret < 0)
1056  return ret;
1057 
1058  if (write_comment) {
1059  const char *vendor = (s->flags & AVFMT_FLAG_BITEXACT) ?
1060  "Lavf" : LIBAVFORMAT_IDENT;
1061  AVDictionary *dict = NULL;
1062  uint8_t buf[32];
1063  int64_t len;
1064 
1065  snprintf(buf, sizeof(buf), "0x%"PRIx64, par->ch_layout.u.mask);
1066  av_dict_set(&dict, "WAVEFORMATEXTENSIBLE_CHANNEL_MASK", buf, 0);
1067 
1068  len = ff_vorbiscomment_length(dict, vendor, NULL, 0);
1069  av_assert1(len < (1 << 24) - 4);
1070 
1071  avio_w8(pb, 0x84);
1072  avio_wb24(pb, len);
1073 
1074  ff_vorbiscomment_write(pb, dict, vendor, NULL, 0);
1075 
1076  av_dict_free(&dict);
1077  }
1078 
1079  return 0;
1080 }
1081 
1082 static int get_aac_sample_rates(AVFormatContext *s, MatroskaMuxContext *mkv,
1083  const uint8_t *extradata, int extradata_size,
1084  int *sample_rate, int *output_sample_rate)
1085 {
1086  MPEG4AudioConfig mp4ac;
1087  int ret;
1088 
1089  ret = avpriv_mpeg4audio_get_config2(&mp4ac, extradata, extradata_size, 1, s);
1090  /* Don't abort if the failure is because of missing extradata. Assume in that
1091  * case a bitstream filter will provide the muxer with the extradata in the
1092  * first packet.
1093  * Abort however if s->pb is not seekable, as we would not be able to seek back
1094  * to write the sample rate elements once the extradata shows up, anyway. */
1095  if (ret < 0 && (extradata_size || !IS_SEEKABLE(s->pb, mkv))) {
1097  "Error parsing AAC extradata, unable to determine samplerate.\n");
1098  return AVERROR(EINVAL);
1099  }
1100 
1101  if (ret < 0) {
1102  /* This will only happen when this function is called while writing the
1103  * header and no extradata is available. The space for this element has
1104  * to be reserved for when this function is called again after the
1105  * extradata shows up in the first packet, as there's no way to know if
1106  * output_sample_rate will be different than sample_rate or not. */
1107  *output_sample_rate = *sample_rate;
1108  } else {
1109  *sample_rate = mp4ac.sample_rate;
1110  *output_sample_rate = mp4ac.ext_sample_rate;
1111  }
1112  return 0;
1113 }
1114 #endif
1115 
1117  const AVCodecParameters *par,
1118  const uint8_t *extradata,
1119  int extradata_size,
1120  unsigned *size_to_reserve)
1121 {
1122  switch (par->codec_id) {
1123  case AV_CODEC_ID_VORBIS:
1124  case AV_CODEC_ID_THEORA:
1125  return put_xiph_codecpriv(s, dyn_cp, par, extradata, extradata_size);
1126  case AV_CODEC_ID_AV1:
1127  if (extradata_size)
1128  return ff_isom_write_av1c(dyn_cp, extradata,
1129  extradata_size, 1);
1130  else
1131  *size_to_reserve = (AV1_SANE_SEQUENCE_HEADER_MAX_BITS + 7) / 8 + 100;
1132  break;
1133 #if CONFIG_MATROSKA_MUXER
1134  case AV_CODEC_ID_FLAC:
1135  return put_flac_codecpriv(s, dyn_cp, par, extradata, extradata_size);
1136  case AV_CODEC_ID_WAVPACK:
1137  return put_wv_codecpriv(dyn_cp, extradata, extradata_size);
1138  case AV_CODEC_ID_H264:
1139  return ff_isom_write_avcc(dyn_cp, extradata,
1140  extradata_size);
1141  case AV_CODEC_ID_HEVC:
1142  return ff_isom_write_hvcc(dyn_cp, extradata,
1143  extradata_size, 0);
1144  case AV_CODEC_ID_ALAC:
1145  if (extradata_size < 36) {
1147  "Invalid extradata found, ALAC expects a 36-byte "
1148  "QuickTime atom.");
1149  return AVERROR_INVALIDDATA;
1150  } else
1151  avio_write(dyn_cp, extradata + 12,
1152  extradata_size - 12);
1153  break;
1154  case AV_CODEC_ID_AAC:
1155  if (extradata_size)
1156  avio_write(dyn_cp, extradata, extradata_size);
1157  else
1158  *size_to_reserve = MAX_PCE_SIZE;
1159  break;
1160  case AV_CODEC_ID_ARIB_CAPTION: {
1161  unsigned stream_identifier, data_component_id;
1162  switch (par->profile) {
1164  stream_identifier = 0x30;
1165  data_component_id = 0x0008;
1166  break;
1168  stream_identifier = 0x87;
1169  data_component_id = 0x0012;
1170  break;
1171  default:
1173  "Unset/unknown ARIB caption profile %d utilized!\n",
1174  par->profile);
1175  return AVERROR_INVALIDDATA;
1176  }
1177  avio_w8(dyn_cp, stream_identifier);
1178  avio_wb16(dyn_cp, data_component_id);
1179  break;
1180  }
1181 #endif
1182  default:
1183  if (CONFIG_MATROSKA_MUXER && par->codec_id == AV_CODEC_ID_PRORES &&
1185  avio_wl32(dyn_cp, par->codec_tag);
1186  } else if (extradata_size && par->codec_id != AV_CODEC_ID_TTA)
1187  avio_write(dyn_cp, extradata, extradata_size);
1188  }
1189 
1190  return 0;
1191 }
1192 
1194  AVCodecParameters *par,
1195  const uint8_t *extradata, int extradata_size,
1196  int native_id, int qt_id,
1197  uint8_t **codecpriv, int *codecpriv_size,
1198  unsigned *max_payload_size)
1199 {
1200  MatroskaMuxContext av_unused *const mkv = s->priv_data;
1201  unsigned size_to_reserve = 0;
1202  int ret;
1203 
1204  if (native_id) {
1205  ret = mkv_assemble_native_codecprivate(s, dyn_cp, par,
1206  extradata, extradata_size,
1207  &size_to_reserve);
1208  if (ret < 0)
1209  return ret;
1210 #if CONFIG_MATROSKA_MUXER
1211  } else if (par->codec_type == AVMEDIA_TYPE_VIDEO) {
1212  if (qt_id) {
1213  if (!par->codec_tag)
1215  par->codec_id);
1217  && (!extradata_size || ff_codec_get_id(ff_codec_movvideo_tags, AV_RL32(extradata + 4)) != par->codec_id)
1218  ) {
1219  avio_wb32(dyn_cp, 0x5a + extradata_size);
1220  avio_wl32(dyn_cp, par->codec_tag);
1221  ffio_fill(dyn_cp, 0, 0x5a - 8);
1222  }
1223  avio_write(dyn_cp, extradata, extradata_size);
1224  } else {
1226  av_log(s, AV_LOG_WARNING, "codec %s is not supported by this format\n",
1227  avcodec_get_name(par->codec_id));
1228 
1229  if (!par->codec_tag)
1231  par->codec_id);
1232  if (!par->codec_tag && par->codec_id != AV_CODEC_ID_RAWVIDEO) {
1233  av_log(s, AV_LOG_ERROR, "No bmp codec tag found for codec %s\n",
1234  avcodec_get_name(par->codec_id));
1235  return AVERROR(EINVAL);
1236  }
1237 
1238  /* If vfw extradata updates are supported, this will have
1239  * to be updated to pass extradata(_size) explicitly. */
1240  ff_put_bmp_header(dyn_cp, par, 0, 0, mkv->flipped_raw_rgb);
1241  }
1242  } else if (par->codec_type == AVMEDIA_TYPE_AUDIO) {
1243  unsigned int tag;
1245  if (!tag) {
1246  av_log(s, AV_LOG_ERROR, "No wav codec tag found for codec %s\n",
1247  avcodec_get_name(par->codec_id));
1248  return AVERROR(EINVAL);
1249  }
1250  if (!par->codec_tag)
1251  par->codec_tag = tag;
1252 
1253  /* Same comment as for ff_put_bmp_header applies here. */
1255  if (ret < 0)
1256  return ret;
1257 #endif
1258  }
1259 
1260  *codecpriv_size = avio_get_dyn_buf(dyn_cp, codecpriv);
1261  if (dyn_cp->error < 0)
1262  return dyn_cp->error;
1263  *max_payload_size = *codecpriv_size + size_to_reserve;
1264 
1265  return 0;
1266 }
1267 
1268 static void mkv_put_codecprivate(AVIOContext *pb, unsigned max_payload_size,
1269  const uint8_t *codecpriv, unsigned codecpriv_size)
1270 {
1271  unsigned total_codecpriv_size = 0, total_size;
1272 
1273  av_assert1(codecpriv_size <= max_payload_size);
1274 
1275  if (!max_payload_size)
1276  return;
1277 
1278  total_size = 2 + ebml_length_size(max_payload_size) + max_payload_size;
1279 
1280  if (codecpriv_size) {
1281  unsigned length_size = ebml_length_size(codecpriv_size);
1282 
1283  total_codecpriv_size = 2U + length_size + codecpriv_size;
1284  if (total_codecpriv_size + 1 == total_size) {
1285  /* It is impossible to add one byte of padding via an EBML Void. */
1286  length_size++;
1287  total_codecpriv_size++;
1288  }
1290  put_ebml_length(pb, codecpriv_size, length_size);
1291  avio_write(pb, codecpriv, codecpriv_size);
1292  }
1293  if (total_codecpriv_size < total_size)
1294  put_ebml_void(pb, total_size - total_codecpriv_size);
1295 }
1296 
1298  uint8_t *side_data, int side_data_size,
1299  AVCodecParameters *par, AVIOContext *pb,
1300  mkv_track *track, unsigned alternative_size)
1301 {
1302  AVIOContext *const dyn_bc = mkv->tmp_bc;
1303  uint8_t *codecpriv;
1304  unsigned max_payload_size;
1305  int ret, codecpriv_size;
1306 
1307  ret = mkv_assemble_codecprivate(s, dyn_bc, par,
1308  side_data, side_data_size, 1, 0,
1309  &codecpriv, &codecpriv_size, &max_payload_size);
1310  if (ret < 0)
1311  goto fail;
1312  if (codecpriv_size > track->codecpriv_size && !alternative_size) {
1313  ret = AVERROR(ENOSPC);
1314  goto fail;
1315  } else if (codecpriv_size > track->codecpriv_size) {
1316  av_assert1(alternative_size < track->codecpriv_size);
1317  codecpriv_size = alternative_size;
1318  }
1319  avio_seek(pb, track->codecpriv_offset, SEEK_SET);
1321  codecpriv, codecpriv_size);
1322 
1323  if (!par->extradata_size) {
1324  ret = ff_alloc_extradata(par, side_data_size);
1325  if (ret < 0)
1326  goto fail;
1327  memcpy(par->extradata, side_data, side_data_size);
1328  }
1329 fail:
1330  ffio_reset_dyn_buf(dyn_bc);
1331  return ret;
1332 }
1333 
1334 #define MAX_VIDEO_COLOR_ELEMS 20
1335 static void mkv_write_video_color(EbmlWriter *writer, const AVStream *st,
1336  const AVCodecParameters *par)
1337 {
1338  const AVPacketSideData *side_data;
1339 
1341 
1342  if (par->color_trc != AVCOL_TRC_UNSPECIFIED &&
1343  par->color_trc < AVCOL_TRC_NB) {
1345  par->color_trc);
1346  }
1347  if (par->color_space != AVCOL_SPC_UNSPECIFIED &&
1348  par->color_space < AVCOL_SPC_NB) {
1350  par->color_space);
1351  }
1352  if (par->color_primaries != AVCOL_PRI_UNSPECIFIED &&
1353  par->color_primaries < AVCOL_PRI_NB) {
1355  par->color_primaries);
1356  }
1357  if (par->color_range != AVCOL_RANGE_UNSPECIFIED &&
1358  par->color_range < AVCOL_RANGE_NB) {
1360  }
1363  int xpos, ypos;
1364 
1365  av_chroma_location_enum_to_pos(&xpos, &ypos, par->chroma_location);
1367  (xpos >> 7) + 1);
1369  (ypos >> 7) + 1);
1370  }
1371 
1374  if (side_data) {
1375  const AVContentLightMetadata *metadata = (AVContentLightMetadata *)side_data->data;
1377  metadata->MaxCLL);
1379  metadata->MaxFALL);
1380  }
1381 
1384  if (side_data) {
1385  const AVMasteringDisplayMetadata *metadata = (AVMasteringDisplayMetadata *)side_data->data;
1387  if (metadata->has_primaries) {
1389  av_q2d(metadata->display_primaries[0][0]));
1391  av_q2d(metadata->display_primaries[0][1]));
1393  av_q2d(metadata->display_primaries[1][0]));
1395  av_q2d(metadata->display_primaries[1][1]));
1397  av_q2d(metadata->display_primaries[2][0]));
1399  av_q2d(metadata->display_primaries[2][1]));
1401  av_q2d(metadata->white_point[0]));
1403  av_q2d(metadata->white_point[1]));
1404  }
1405  if (metadata->has_luminance) {
1407  av_q2d(metadata->max_luminance));
1409  av_q2d(metadata->min_luminance));
1410  }
1412  }
1413 
1415 }
1416 
1417 #define MAX_VIDEO_PROJECTION_ELEMS 6
1418 static void mkv_handle_rotation(void *logctx, const AVCodecParameters *par,
1419  double *yaw, double *roll)
1420 {
1421  const int32_t *matrix;
1422  const AVPacketSideData *side_data =
1425 
1426  if (!side_data)
1427  return;
1428 
1429  matrix = (int32_t *)side_data->data;
1430 
1431  /* Check whether this is an affine transformation */
1432  if (matrix[2] || matrix[5])
1433  goto ignore;
1434 
1435  /* This together with the checks below test whether
1436  * the upper-left 2x2 matrix is nonsingular. */
1437  if (!matrix[0] && !matrix[1])
1438  goto ignore;
1439 
1440  /* We ignore the translation part of the matrix (matrix[6] and matrix[7])
1441  * as well as any scaling, i.e. we only look at the upper left 2x2 matrix.
1442  * We only accept matrices that are an exact multiple of an orthogonal one.
1443  * Apart from the multiple, every such matrix can be obtained by
1444  * potentially flipping in the x-direction (corresponding to yaw = 180)
1445  * followed by a rotation of (say) an angle phi in the counterclockwise
1446  * direction. The upper-left 2x2 matrix then looks like this:
1447  * | (+/-)cos(phi) (-/+)sin(phi) |
1448  * scale * | |
1449  * | sin(phi) cos(phi) |
1450  * The first set of signs in the first row apply in case of no flipping,
1451  * the second set applies in case of flipping. */
1452 
1453  /* The casts to int64_t are needed because -INT32_MIN doesn't fit
1454  * in an int32_t. */
1455  if (matrix[0] == matrix[4] && -(int64_t)matrix[1] == matrix[3]) {
1456  /* No flipping case */
1457  *yaw = 0;
1458  } else if (-(int64_t)matrix[0] == matrix[4] && matrix[1] == matrix[3]) {
1459  /* Horizontal flip */
1460  *yaw = 180;
1461  } else {
1462 ignore:
1463  av_log(logctx, AV_LOG_INFO, "Ignoring display matrix indicating "
1464  "non-orthogonal transformation.\n");
1465  return;
1466  }
1467  *roll = 180 / M_PI * atan2(matrix[3], matrix[4]);
1468 
1469  /* We do not write a ProjectionType element indicating "rectangular",
1470  * because this is the default value. */
1471 }
1472 
1473 static int mkv_handle_spherical(void *logctx, EbmlWriter *writer,
1474  const AVCodecParameters *par, uint8_t private[],
1475  double *yaw, double *pitch, double *roll)
1476 {
1478  par->nb_coded_side_data,
1480  const AVSphericalMapping *spherical;
1481 
1482  if (!sd)
1483  return 0;
1484 
1485  spherical = (const AVSphericalMapping *)sd->data;
1486  if (spherical->projection != AV_SPHERICAL_EQUIRECTANGULAR &&
1488  spherical->projection != AV_SPHERICAL_CUBEMAP) {
1489  av_log(logctx, AV_LOG_WARNING, "Unknown projection type\n");
1490  return 0;
1491  }
1492 
1493  switch (spherical->projection) {
1498  AV_WB32(private, 0); // version + flags
1499  if (spherical->projection == AV_SPHERICAL_EQUIRECTANGULAR) {
1500  AV_WB32(private + 4, 0);
1501  AV_WB32(private + 8, 0);
1502  AV_WB32(private + 12, 0);
1503  AV_WB32(private + 16, 0);
1504  } else {
1505  AV_WB32(private + 4, spherical->bound_top);
1506  AV_WB32(private + 8, spherical->bound_bottom);
1507  AV_WB32(private + 12, spherical->bound_left);
1508  AV_WB32(private + 16, spherical->bound_right);
1509  }
1511  private, 20);
1512  break;
1513  case AV_SPHERICAL_CUBEMAP:
1516  AV_WB32(private, 0); // version + flags
1517  AV_WB32(private + 4, 0); // layout
1518  AV_WB32(private + 8, spherical->padding);
1520  private, 12);
1521  break;
1522  default:
1523  av_assert0(0);
1524  }
1525 
1526  *yaw = (double) spherical->yaw / (1 << 16);
1527  *pitch = (double) spherical->pitch / (1 << 16);
1528  *roll = (double) spherical->roll / (1 << 16);
1529 
1530  return 1; /* Projection included */
1531 }
1532 
1533 static void mkv_write_video_projection(void *logctx, EbmlWriter *wr,
1534  const AVCodecParameters *par,
1535  uint8_t private[])
1536 {
1537  double yaw = 0, pitch = 0, roll = 0;
1538  int ret;
1539 
1541 
1542  ret = mkv_handle_spherical(logctx, wr, par, private, &yaw, &pitch, &roll);
1543  if (!ret)
1544  mkv_handle_rotation(logctx, par, &yaw, &roll);
1545 
1546  if (yaw)
1548  if (pitch)
1550  if (roll)
1552 
1554 }
1555 
1556 #define MAX_FIELD_ORDER_ELEMS 2
1557 static void mkv_write_field_order(EbmlWriter *writer, int is_webm,
1558  enum AVFieldOrder field_order)
1559 {
1560  switch (field_order) {
1561  case AV_FIELD_UNKNOWN:
1562  break;
1563  case AV_FIELD_PROGRESSIVE:
1566  break;
1567  case AV_FIELD_TT:
1568  case AV_FIELD_BB:
1569  case AV_FIELD_TB:
1570  case AV_FIELD_BT:
1573  if (!is_webm) {
1574  switch (field_order) {
1575  case AV_FIELD_TT:
1578  break;
1579  case AV_FIELD_BB:
1582  break;
1583  case AV_FIELD_TB:
1586  break;
1587  case AV_FIELD_BT:
1590  break;
1591  }
1592  }
1593  }
1594 }
1595 
1596 #define MAX_STEREO_MODE_ELEMS 1
1598  const AVCodecParameters *par,
1599  const AVStream *st, int is_webm,
1600  int *h_width, int *h_height)
1601 {
1602  const char *error_message_addendum = "";
1603  const AVDictionaryEntry *tag;
1605 
1606  /* The following macros create bitfields where the ith bit
1607  * indicates whether the MatroskaVideoStereoModeType with that value
1608  * uses double width/height or is WebM compatible. */
1609 #define FLAG(STEREOMODETYPE, BOOL) | (BOOL) << (STEREOMODETYPE)
1610 #define WDIV1(STEREOMODETYPE, STEREO3DTYPE, FLAGS, WDIV, HDIV, WEBM) \
1611  FLAG(STEREOMODETYPE, WDIV)
1612 #define WDIV2(STEREOMODETYPE, WDIV, HDIV, WEBM) \
1613  FLAG(STEREOMODETYPE, WDIV)
1614  // The zero in the following line consumes the first '|'.
1615  const unsigned width_bitfield = 0 STEREOMODE_STEREO3D_MAPPING(WDIV1, WDIV2);
1616 
1617 #define HDIV1(STEREOMODETYPE, STEREO3DTYPE, FLAGS, WDIV, HDIV, WEBM) \
1618  FLAG(STEREOMODETYPE, HDIV)
1619 #define HDIV2(STEREOMODETYPE, WDIV, HDIV, WEBM) \
1620  FLAG(STEREOMODETYPE, HDIV)
1621  const unsigned height_bitfield = 0 STEREOMODE_STEREO3D_MAPPING(HDIV1, HDIV2);
1622 
1623 #define WEBM1(STEREOMODETYPE, STEREO3DTYPE, FLAGS, WDIV, HDIV, WEBM) \
1624  FLAG(STEREOMODETYPE, WEBM)
1625 #define WEBM2(STEREOMODETYPE, WDIV, HDIV, WEBM) \
1626  FLAG(STEREOMODETYPE, WEBM)
1627  const unsigned webm_bitfield = 0 STEREOMODE_STEREO3D_MAPPING(WEBM1, WEBM2);
1628 
1629  *h_width = 1;
1630  *h_height = 1;
1631 
1632  if ((tag = av_dict_get(st->metadata, "stereo_mode", NULL, 0)) ||
1633  (tag = av_dict_get( s->metadata, "stereo_mode", NULL, 0))) {
1634 
1635  for (int i = 0; i < MATROSKA_VIDEO_STEREOMODE_TYPE_NB; i++)
1636  if (!strcmp(tag->value, ff_matroska_video_stereo_mode[i])){
1637  format = i;
1638  break;
1639  }
1641  long stereo_mode = strtol(tag->value, NULL, 0);
1642  if ((unsigned long)stereo_mode >= MATROSKA_VIDEO_STEREOMODE_TYPE_NB)
1643  goto fail;
1644  format = stereo_mode;
1645  }
1646  } else {
1647  const AVPacketSideData *sd;
1648  const AVStereo3D *stereo;
1649  /* The following macro presumes all MATROSKA_VIDEO_STEREOMODE_TYPE_*
1650  * values to be in the range 0..254. */
1651 #define STEREOMODE(STEREOMODETYPE, STEREO3DTYPE, FLAGS, WDIV, HDIV, WEBM) \
1652  [(STEREO3DTYPE)][!!((FLAGS) & AV_STEREO3D_FLAG_INVERT)] = (STEREOMODETYPE) + 1,
1653 #define NOTHING(STEREOMODETYPE, WDIV, HDIV, WEBM)
1654  static const unsigned char conversion_table[][2] = {
1656  };
1657  int fmt;
1658 
1661  if (!sd)
1662  return 0;
1663 
1664  stereo = (const AVStereo3D*)sd->data;
1665 
1666  /* A garbage AVStereo3D or something with no Matroska analogon. */
1667  if ((unsigned)stereo->type >= FF_ARRAY_ELEMS(conversion_table))
1668  return 0;
1669 
1670  fmt = conversion_table[stereo->type][!!(stereo->flags & AV_STEREO3D_FLAG_INVERT)];
1671  /* Format with no Matroska analogon; ignore it */
1672  if (!fmt)
1673  return 0;
1674  format = fmt - 1;
1675  }
1676 
1677  // if webm, do not write unsupported modes
1678  if (is_webm && !(webm_bitfield >> format)) {
1679  error_message_addendum = " for WebM";
1680  goto fail;
1681  }
1682 
1683  *h_width = 1 << ((width_bitfield >> format) & 1);
1684  *h_height = 1 << ((height_bitfield >> format) & 1);
1685 
1686  // write StereoMode if format is valid
1688 
1689  return 0;
1690 fail:
1692  "The specified stereo mode is not valid%s.\n",
1693  error_message_addendum);
1694  return AVERROR(EINVAL);
1695 }
1696 
1698  const AVCodecParameters *par, AVIOContext *pb,
1699  mkv_track *track, const AVStream *st)
1700 {
1701 #if CONFIG_MATROSKA_MUXER
1703  const AVPacketSideData *sd;
1704 
1705  if (IS_SEEKABLE(s->pb, mkv)) {
1707  // We can't know at this point if there will be a block with BlockAdditions, so
1708  // we either write the default value here, or a void element. Either of them will
1709  // be overwritten when finishing the track.
1711  if (par->codec_type == AVMEDIA_TYPE_VIDEO) {
1712  // Similarly, reserve space for an eventual
1713  // HDR10+ ITU T.35 metadata BlockAdditionMapping.
1714  put_ebml_void(pb, 3 /* BlockAdditionMapping */
1715  + 4 /* BlockAddIDValue */
1716  + 4 /* BlockAddIDType */);
1717  }
1718  }
1719 
1722 
1723  if (!sd)
1724  return;
1725 
1726  dovi = (const AVDOVIDecoderConfigurationRecord *)sd->data;
1727  if (dovi->dv_profile <= 10) {
1728  ebml_master mapping;
1729  uint8_t buf[ISOM_DVCC_DVVC_SIZE];
1730  uint32_t type;
1731 
1732  uint64_t expected_size = (2 + 1 + (sizeof(DVCC_DVVC_BLOCK_TYPE_NAME) - 1))
1733  + (2 + 1 + 4) + (2 + 1 + ISOM_DVCC_DVVC_SIZE);
1734 
1735  if (dovi->dv_profile > 7) {
1737  } else {
1739  }
1740 
1741  ff_isom_put_dvcc_dvvc(s, buf, dovi);
1742 
1743  mapping = start_ebml_master(pb, MATROSKA_ID_TRACKBLKADDMAPPING, expected_size);
1744 
1747  put_ebml_binary(pb, MATROSKA_ID_BLKADDIDEXTRADATA, buf, sizeof(buf));
1748 
1749  end_ebml_master(pb, mapping);
1750  }
1751 #endif
1752 }
1753 
1755  const AVStream *st, const AVCodecParameters *par,
1756  AVIOContext *pb)
1757 {
1758  const AVDictionaryEntry *tag;
1759  int display_width_div = 1, display_height_div = 1;
1760  uint8_t color_space[4], projection_private[20];
1761  const AVPacketSideData *sd;
1764  int cropped_width = par->width, cropped_height = par->height;
1765  int ret;
1766 
1768 
1771 
1772  mkv_write_field_order(&writer, IS_WEBM(mkv), par->field_order);
1773 
1774  // check both side data and metadata for stereo information,
1775  // write the result to the bitstream if any is found
1776  ret = mkv_write_stereo_mode(s, &writer, par, st, IS_WEBM(mkv),
1777  &display_width_div,
1778  &display_height_div);
1779  if (ret < 0)
1780  return ret;
1781 
1782  if (par->format == AV_PIX_FMT_YUVA420P ||
1783  ((tag = av_dict_get(st->metadata, "alpha_mode", NULL, 0)) ||
1784  (tag = av_dict_get( s->metadata, "alpha_mode", NULL, 0))) && strtol(tag->value, NULL, 0))
1786 
1788  par->nb_coded_side_data,
1790  if (sd && sd->size == sizeof(uint32_t) * 4) {
1791  uint64_t top, bottom, left, right;
1792 
1793  top = AV_RL32(sd->data + 0);
1794  bottom = AV_RL32(sd->data + 4);
1795  left = AV_RL32(sd->data + 8);
1796  right = AV_RL32(sd->data + 12);
1797 
1798  if ((left + right) >= par->width ||
1799  (top + bottom) >= par->height) {
1800  av_log(s, AV_LOG_ERROR, "Invalid cropping dimensions in stream side data\n");
1801  return AVERROR(EINVAL);
1802  }
1803 
1804  if (bottom)
1806  if (top)
1808  if (left)
1810  if (right)
1812 
1813  cropped_width -= left + right;
1814  cropped_height -= top + bottom;
1815  }
1816 
1817  // write DisplayWidth and DisplayHeight, they contain the size of
1818  // a single source view and/or the display aspect ratio
1819  if (st->sample_aspect_ratio.num) {
1820  int64_t d_width = av_rescale(cropped_width, st->sample_aspect_ratio.num, st->sample_aspect_ratio.den);
1821  if (d_width > INT_MAX) {
1822  av_log(s, AV_LOG_ERROR, "Overflow in display width\n");
1823  return AVERROR(EINVAL);
1824  }
1825  if (d_width != cropped_width || display_width_div != 1 || display_height_div != 1) {
1826  if (IS_WEBM(mkv) || display_width_div != 1 || display_height_div != 1) {
1828  d_width / display_width_div);
1830  cropped_height / display_height_div);
1831  } else {
1832  AVRational display_aspect_ratio;
1833  av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den,
1834  cropped_width * (int64_t)st->sample_aspect_ratio.num,
1835  cropped_height * (int64_t)st->sample_aspect_ratio.den,
1836  1024 * 1024);
1838  display_aspect_ratio.num);
1840  display_aspect_ratio.den);
1843  }
1844  }
1845  } else if (display_width_div != 1 || display_height_div != 1) {
1847  cropped_width / display_width_div);
1849  cropped_height / display_height_div);
1850  } else if (!IS_WEBM(mkv))
1853 
1854  if (par->codec_id == AV_CODEC_ID_RAWVIDEO) {
1855  AV_WL32(color_space, par->codec_tag);
1857  color_space, sizeof(color_space));
1858  }
1859  mkv_write_video_color(&writer, st, par);
1860  mkv_write_video_projection(s, &writer, par, projection_private);
1861 
1862  return ebml_writer_write(&writer, pb);
1863 }
1864 
1867 {
1869  1000000000LL * duration.num / duration.den);
1870  track->default_duration_low = 1000LL * duration.num / duration.den;
1872  !!(1000LL * duration.num % duration.den);
1873 }
1874 
1876  AVStream *st, mkv_track *track, AVIOContext *pb,
1877  int is_default)
1878 {
1879  AVCodecParameters *par = st->codecpar;
1880  ebml_master subinfo, track_master;
1881  int native_id = 0;
1882  int qt_id = 0;
1883  int bit_depth;
1884  int sample_rate = par->sample_rate;
1885  int output_sample_rate = 0;
1886  int j, ret;
1887  const AVDictionaryEntry *tag;
1888 
1889  if (par->codec_type == AVMEDIA_TYPE_ATTACHMENT)
1890  return 0;
1891 
1892  track_master = start_ebml_master(pb, MATROSKA_ID_TRACKENTRY, 0);
1894  put_ebml_uid (pb, MATROSKA_ID_TRACKUID, track->uid);
1895  put_ebml_uint(pb, MATROSKA_ID_TRACKFLAGLACING, 0); // no lacing (yet)
1896 
1897  if ((tag = av_dict_get(st->metadata, "title", NULL, 0)))
1899  tag = av_dict_get(st->metadata, "language", NULL, 0);
1901  tag && tag->value[0] ? tag->value : "und");
1902 
1903  // The default value for TRACKFLAGDEFAULT is 1, so add element
1904  // if we need to clear it.
1905  if (!is_default)
1907 
1910 
1911  if (IS_WEBM(mkv)) {
1912  const char *codec_id;
1913  if (par->codec_id != AV_CODEC_ID_WEBVTT) {
1914  for (j = 0; ff_webm_codec_tags[j].id != AV_CODEC_ID_NONE; j++) {
1915  if (ff_webm_codec_tags[j].id == par->codec_id) {
1917  native_id = 1;
1918  break;
1919  }
1920  }
1921  } else {
1923  codec_id = "D_WEBVTT/CAPTIONS";
1924  native_id = MATROSKA_TRACK_TYPE_SUBTITLE;
1925  } else if (st->disposition & AV_DISPOSITION_DESCRIPTIONS) {
1926  codec_id = "D_WEBVTT/DESCRIPTIONS";
1927  native_id = MATROSKA_TRACK_TYPE_METADATA;
1928  } else if (st->disposition & AV_DISPOSITION_METADATA) {
1929  codec_id = "D_WEBVTT/METADATA";
1930  native_id = MATROSKA_TRACK_TYPE_METADATA;
1931  } else {
1932  codec_id = "D_WEBVTT/SUBTITLES";
1933  native_id = MATROSKA_TRACK_TYPE_SUBTITLE;
1934  }
1935  }
1936 
1937  if (!native_id) {
1939  "Only VP8 or VP9 or AV1 video and Vorbis or Opus audio and WebVTT subtitles are supported for WebM.\n");
1940  return AVERROR(EINVAL);
1941  }
1942 
1944  } else {
1956 
1957  // look for a codec ID string specific to mkv to use,
1958  // if none are found, use AVI codes
1959  if (par->codec_id == AV_CODEC_ID_FFV1) {
1960  /* FFV1 is actually supported natively in Matroska,
1961  * yet we use the VfW way to mux it for compatibility
1962  * with old demuxers. (FIXME: Are they really important?) */
1963  } else if (par->codec_id != AV_CODEC_ID_RAWVIDEO || par->codec_tag) {
1964  for (j = 0; ff_mkv_codec_tags[j].id != AV_CODEC_ID_NONE; j++) {
1965  if (ff_mkv_codec_tags[j].id == par->codec_id) {
1967  native_id = 1;
1968  break;
1969  }
1970  }
1971  } else {
1972  if (mkv->allow_raw_vfw) {
1973  native_id = 0;
1974  } else {
1975  av_log(s, AV_LOG_ERROR, "Raw RGB is not supported Natively in Matroska, you can use AVI or NUT or\n"
1976  "If you would like to store it anyway using VFW mode, enable allow_raw_vfw (-allow_raw_vfw 1)\n");
1977  return AVERROR(EINVAL);
1978  }
1979  }
1980  }
1981 
1982  switch (par->codec_type) {
1983  AVRational frame_rate;
1984  int audio_frame_samples;
1985 
1986  case AVMEDIA_TYPE_VIDEO:
1987  mkv->have_video = 1;
1989 
1990  frame_rate = (AVRational){ 0, 1 };
1991  if (st->avg_frame_rate.num > 0 && st->avg_frame_rate.den > 0)
1992  frame_rate = st->avg_frame_rate;
1993  else if (st->r_frame_rate.num > 0 && st->r_frame_rate.den > 0)
1994  frame_rate = st->r_frame_rate;
1995 
1996  if (frame_rate.num > 0)
1997  mkv_write_default_duration(track, pb, av_inv_q(frame_rate));
1998 
1999  if (CONFIG_MATROSKA_MUXER && !native_id &&
2002  par->codec_id == AV_CODEC_ID_SVQ1 ||
2003  par->codec_id == AV_CODEC_ID_SVQ3 ||
2004  par->codec_id == AV_CODEC_ID_CINEPAK))
2005  qt_id = 1;
2006 
2007  if (qt_id)
2008  put_ebml_string(pb, MATROSKA_ID_CODECID, "V_QUICKTIME");
2009  else if (!native_id) {
2010  // if there is no mkv-specific codec ID, use VFW mode
2011  put_ebml_string(pb, MATROSKA_ID_CODECID, "V_MS/VFW/FOURCC");
2012  track->write_dts = 1;
2014  }
2015 
2016  ret = mkv_write_track_video(s, mkv, st, par, pb);
2017  if (ret < 0)
2018  return ret;
2019 
2020  break;
2021 
2022  case AVMEDIA_TYPE_AUDIO:
2023  if (par->initial_padding) {
2024  int64_t codecdelay = av_rescale_q(par->initial_padding,
2025  (AVRational){ 1, par->sample_rate },
2026  (AVRational){ 1, 1000000000 });
2027  if (codecdelay < 0) {
2028  av_log(s, AV_LOG_ERROR, "Initial padding is invalid\n");
2029  return AVERROR(EINVAL);
2030  }
2031  put_ebml_uint(pb, MATROSKA_ID_CODECDELAY, codecdelay);
2032 
2033  track->ts_offset = av_rescale_q(par->initial_padding,
2034  (AVRational){ 1, par->sample_rate },
2035  st->time_base);
2036  ffstream(st)->lowest_ts_allowed = -track->ts_offset;
2037  }
2038  if (par->codec_id == AV_CODEC_ID_OPUS)
2040 #if CONFIG_MATROSKA_MUXER
2041  else if (par->codec_id == AV_CODEC_ID_AAC) {
2042  ret = get_aac_sample_rates(s, mkv, par->extradata, par->extradata_size,
2043  &sample_rate, &output_sample_rate);
2044  if (ret < 0)
2045  return ret;
2046  }
2047 #endif
2048 
2050 
2051  audio_frame_samples = av_get_audio_frame_duration2(par, 0);
2052  if (audio_frame_samples)
2053  mkv_write_default_duration(track, pb, (AVRational){ audio_frame_samples,
2054  par->sample_rate });
2055  if (!native_id)
2056  // no mkv-specific ID, use ACM mode
2057  put_ebml_string(pb, MATROSKA_ID_CODECID, "A_MS/ACM");
2058 
2059  subinfo = start_ebml_master(pb, MATROSKA_ID_TRACKAUDIO, 6 + 4 * 9);
2061 
2062  track->sample_rate_offset = avio_tell(pb);
2063  put_ebml_float (pb, MATROSKA_ID_AUDIOSAMPLINGFREQ, sample_rate);
2064  if (output_sample_rate)
2065  put_ebml_float(pb, MATROSKA_ID_AUDIOOUTSAMPLINGFREQ, output_sample_rate);
2066 
2068  if (!bit_depth && par->codec_id != AV_CODEC_ID_ADPCM_G726) {
2069  if (par->bits_per_raw_sample)
2071  else
2073  }
2074  if (!bit_depth)
2076  if (bit_depth)
2078  end_ebml_master(pb, subinfo);
2079  break;
2080 
2081  case AVMEDIA_TYPE_SUBTITLE:
2082  if (!native_id) {
2083  av_log(s, AV_LOG_ERROR, "Subtitle codec %d is not supported.\n", par->codec_id);
2084  return AVERROR(ENOSYS);
2085  }
2086  if (!IS_WEBM(mkv) && st->disposition & AV_DISPOSITION_DESCRIPTIONS)
2088 
2089  if (!IS_WEBM(mkv) || par->codec_id != AV_CODEC_ID_WEBVTT)
2090  native_id = MATROSKA_TRACK_TYPE_SUBTITLE;
2091 
2092  put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, native_id);
2093  break;
2094  default:
2095  av_log(s, AV_LOG_ERROR, "Only audio, video, and subtitles are supported for Matroska.\n");
2096  return AVERROR(EINVAL);
2097  }
2098 
2099  if (!IS_WEBM(mkv))
2100  mkv_write_blockadditionmapping(s, mkv, par, pb, track, st);
2101 
2102  if (!IS_WEBM(mkv) || par->codec_id != AV_CODEC_ID_WEBVTT) {
2103  uint8_t *codecpriv;
2104  int codecpriv_size, max_payload_size;
2105  track->codecpriv_offset = avio_tell(pb);
2106  ret = mkv_assemble_codecprivate(s, mkv->tmp_bc, par,
2107  par->extradata, par->extradata_size,
2108  native_id, qt_id,
2109  &codecpriv, &codecpriv_size, &max_payload_size);
2110  if (ret < 0)
2111  goto fail;
2112  mkv_put_codecprivate(pb, max_payload_size, codecpriv, codecpriv_size);
2113  track->codecpriv_size = max_payload_size;
2114  }
2115 
2116  end_ebml_master(pb, track_master);
2117  ret = 0;
2118 fail:
2119  ffio_reset_dyn_buf(mkv->tmp_bc);
2120 
2121  return ret;
2122 }
2123 
2125 {
2126  MatroskaMuxContext *mkv = s->priv_data;
2127  AVIOContext *pb = s->pb;
2128  int video_default_idx = -1, audio_default_idx = -1, subtitle_default_idx = -1;
2129  int i, ret;
2130 
2131  if (mkv->nb_attachments == s->nb_streams)
2132  return 0;
2133 
2134  ret = start_ebml_master_crc32(&mkv->track.bc, mkv);
2135  if (ret < 0)
2136  return ret;
2137 
2138  if (mkv->default_mode != DEFAULT_MODE_PASSTHROUGH) {
2139  int video_idx = -1, audio_idx = -1, subtitle_idx = -1;
2140 
2141  for (i = s->nb_streams - 1; i >= 0; i--) {
2142  AVStream *st = s->streams[i];
2143 
2144  switch (st->codecpar->codec_type) {
2145 #define CASE(type, variable) \
2146  case AVMEDIA_TYPE_ ## type: \
2147  variable ## _idx = i; \
2148  if (st->disposition & AV_DISPOSITION_DEFAULT) \
2149  variable ## _default_idx = i; \
2150  break;
2151  CASE(VIDEO, video)
2152  CASE(AUDIO, audio)
2153  CASE(SUBTITLE, subtitle)
2154 #undef CASE
2155  }
2156  }
2157 
2158  video_default_idx = FFMAX(video_default_idx, video_idx);
2159  audio_default_idx = FFMAX(audio_default_idx, audio_idx);
2161  subtitle_default_idx = FFMAX(subtitle_default_idx, subtitle_idx);
2162  }
2163  for (i = 0; i < s->nb_streams; i++) {
2164  AVStream *st = s->streams[i];
2165  int is_default = st->disposition & AV_DISPOSITION_DEFAULT ||
2166  i == video_default_idx || i == audio_default_idx ||
2167  i == subtitle_default_idx;
2168  ret = mkv_write_track(s, mkv, st, &mkv->tracks[i],
2169  mkv->track.bc, is_default);
2170  if (ret < 0)
2171  return ret;
2172  }
2173 
2174  return end_ebml_master_crc32_tentatively(pb, &mkv->track, mkv,
2176 }
2177 
2179 {
2180  EBML_WRITER(4);
2181  uint8_t *key = av_strdup(t->key);
2182  uint8_t *p = key;
2183  const uint8_t *lang = NULL;
2184  int ret;
2185 
2186  if (!key)
2187  return AVERROR(ENOMEM);
2188 
2189  if ((p = strrchr(p, '-')) &&
2190  (lang = ff_convert_lang_to(p + 1, AV_LANG_ISO639_2_BIBL)))
2191  *p = 0;
2192 
2193  p = key;
2194  while (*p) {
2195  if (*p == ' ')
2196  *p = '_';
2197  else if (*p >= 'a' && *p <= 'z')
2198  *p -= 'a' - 'A';
2199  p++;
2200  }
2201 
2204  if (lang)
2207  ret = ebml_writer_write(&writer, pb);
2208 
2209  av_freep(&key);
2210  return ret;
2211 }
2212 
2214  uint32_t elementid, uint64_t uid)
2215 {
2217  4 + 1 + 8);
2218  if (elementid)
2219  put_ebml_uid(pb, elementid, uid);
2220  end_ebml_master(pb, targets);
2221 }
2222 
2223 static int mkv_check_tag_name(const char *name, uint32_t elementid)
2224 {
2225  return av_strcasecmp(name, "title") &&
2226  av_strcasecmp(name, "stereo_mode") &&
2227  av_strcasecmp(name, "creation_time") &&
2228  av_strcasecmp(name, "encoding_tool") &&
2229  av_strcasecmp(name, "duration") &&
2230  (elementid != MATROSKA_ID_TAGTARGETS_TRACKUID ||
2231  av_strcasecmp(name, "language")) &&
2232  (elementid != MATROSKA_ID_TAGTARGETS_ATTACHUID ||
2233  (av_strcasecmp(name, "filename") &&
2234  av_strcasecmp(name, "mimetype")));
2235 }
2236 
2238  AVIOContext **pb, unsigned reserved_size,
2239  uint32_t elementid, uint64_t uid)
2240 {
2241  const AVDictionaryEntry *t = NULL;
2242  AVIOContext *const tmp_bc = mkv->tmp_bc;
2243  uint8_t *buf;
2244  int ret = 0, size, tag_written = 0;
2245 
2246  mkv_write_tag_targets(mkv, tmp_bc, elementid, uid);
2247 
2248  while ((t = av_dict_iterate(m, t))) {
2249  if (mkv_check_tag_name(t->key, elementid)) {
2250  ret = mkv_write_simpletag(tmp_bc, t);
2251  if (ret < 0)
2252  goto end;
2253  tag_written = 1;
2254  }
2255  }
2256  if (reserved_size)
2257  put_ebml_void(tmp_bc, reserved_size);
2258  else if (!tag_written)
2259  goto end;
2260 
2261  size = avio_get_dyn_buf(tmp_bc, &buf);
2262  if (tmp_bc->error) {
2263  ret = tmp_bc->error;
2264  goto end;
2265  }
2266  if (!*pb) {
2267  ret = start_ebml_master_crc32(pb, mkv);
2268  if (ret < 0)
2269  goto end;
2270  }
2271  put_ebml_binary(*pb, MATROSKA_ID_TAG, buf, size);
2272 
2273 end:
2274  ffio_reset_dyn_buf(tmp_bc);
2275  return ret;
2276 }
2277 
2279 {
2280  MatroskaMuxContext *mkv = s->priv_data;
2281  int i, ret, seekable = IS_SEEKABLE(s->pb, mkv);
2282 
2283  mkv->wrote_tags = 1;
2284 
2286 
2287  ret = mkv_write_tag(mkv, s->metadata, &mkv->tags.bc, 0, 0, 0);
2288  if (ret < 0)
2289  return ret;
2290 
2291  for (i = 0; i < s->nb_streams; i++) {
2292  const AVStream *st = s->streams[i];
2293  mkv_track *track = &mkv->tracks[i];
2294 
2296  continue;
2297 
2298  ret = mkv_write_tag(mkv, st->metadata, &mkv->tags.bc,
2299  seekable ? DURATION_SIMPLETAG_SIZE : 0,
2301  if (ret < 0)
2302  return ret;
2303  if (seekable)
2305  }
2306 
2307  if (mkv->nb_attachments && !IS_WEBM(mkv)) {
2308  for (i = 0; i < s->nb_streams; i++) {
2309  const mkv_track *track = &mkv->tracks[i];
2310  const AVStream *st = s->streams[i];
2311 
2313  continue;
2314 
2315  ret = mkv_write_tag(mkv, st->metadata, &mkv->tags.bc, 0,
2317  if (ret < 0)
2318  return ret;
2319  }
2320  }
2321 
2322  if (mkv->tags.bc) {
2323  return end_ebml_master_crc32_tentatively(s->pb, &mkv->tags, mkv,
2325  }
2326  return 0;
2327 }
2328 
2330 {
2331  for (unsigned i = 0; i < s->nb_chapters; i++) {
2332  if (!s->chapters[i]->id)
2333  return 1;
2334  for (unsigned j = 0; j < i; j++)
2335  if (s->chapters[j]->id == s->chapters[i]->id)
2336  return 1;
2337  }
2338  return 0;
2339 }
2340 
2342 {
2343  MatroskaMuxContext *mkv = s->priv_data;
2344  AVIOContext *dyn_cp = NULL, *dyn_tags = NULL, **tags, *pb = s->pb;
2345  ebml_master editionentry;
2346  AVRational scale = {1, 1E9};
2347  int ret, create_new_ids;
2348 
2349  if (!s->nb_chapters || mkv->wrote_chapters)
2350  return 0;
2351 
2352  ret = start_ebml_master_crc32(&dyn_cp, mkv);
2353  if (ret < 0)
2354  return ret;
2355 
2356  editionentry = start_ebml_master(dyn_cp, MATROSKA_ID_EDITIONENTRY, 0);
2357  if (!IS_WEBM(mkv)) {
2359  /* If mkv_write_tags() has already been called, then any tags
2360  * corresponding to chapters will be put into a new Tags element. */
2361  tags = mkv->wrote_tags ? &dyn_tags : &mkv->tags.bc;
2362  } else
2363  tags = NULL;
2364 
2365  create_new_ids = mkv_new_chapter_ids_needed(s);
2366 
2367  for (unsigned i = 0; i < s->nb_chapters; i++) {
2368  AVChapter *const c = s->chapters[i];
2369  int64_t chapterstart = av_rescale_q(c->start, c->time_base, scale);
2370  int64_t chapterend = av_rescale_q(c->end, c->time_base, scale);
2371  const AVDictionaryEntry *t;
2372  uint64_t uid = create_new_ids ? i + 1ULL : c->id;
2373  EBML_WRITER(7);
2374 
2375  if (chapterstart < 0 || chapterstart > chapterend || chapterend < 0) {
2377  "Invalid chapter start (%"PRId64") or end (%"PRId64").\n",
2378  chapterstart, chapterend);
2380  goto fail;
2381  }
2382 
2385  ebml_writer_add_uint(&writer, MATROSKA_ID_CHAPTERTIMESTART, chapterstart);
2386  ebml_writer_add_uint(&writer, MATROSKA_ID_CHAPTERTIMEEND, chapterend);
2387  if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
2390  ebml_writer_add_string(&writer, MATROSKA_ID_CHAPLANG , "und");
2391  }
2392  ret = ebml_writer_write(&writer, dyn_cp);
2393  if (ret < 0)
2394  goto fail;
2395 
2396  if (tags) {
2398 
2399  ret = mkv_write_tag(mkv, c->metadata, tags, 0,
2401  if (ret < 0)
2402  goto fail;
2403  }
2404  }
2405  end_ebml_master(dyn_cp, editionentry);
2406  mkv->wrote_chapters = 1;
2407 
2408  ret = end_ebml_master_crc32(pb, &dyn_cp, mkv, MATROSKA_ID_CHAPTERS, 0, 0, 1);
2409  if (ret < 0)
2410  goto fail;
2411  if (dyn_tags)
2412  return end_ebml_master_crc32(pb, &dyn_tags, mkv,
2413  MATROSKA_ID_TAGS, 0, 0, 1);
2414  return 0;
2415 
2416 fail:
2417  if (tags) {
2418  /* tags == &mkv->tags.bc can only happen if mkv->tags.bc was
2419  * initially NULL, so we never free older tags. */
2420  ffio_free_dyn_buf(tags);
2421  }
2422  ffio_free_dyn_buf(&dyn_cp);
2423  return ret;
2424 }
2425 
2426 static const char *get_mimetype(const AVStream *st)
2427 {
2428  const AVDictionaryEntry *t;
2429 
2430  if (t = av_dict_get(st->metadata, "mimetype", NULL, 0))
2431  return t->value;
2432  if (st->codecpar->codec_id != AV_CODEC_ID_NONE) {
2434  if (desc && desc->mime_types) {
2435  return desc->mime_types[0];
2436  } else if (st->codecpar->codec_id == AV_CODEC_ID_TEXT)
2437  return "text/plain";
2438  }
2439 
2440  return NULL;
2441 }
2442 
2444 {
2445  MatroskaMuxContext *mkv = s->priv_data;
2446  AVIOContext *dyn_cp = NULL, *pb = s->pb;
2447  int i, ret;
2448 
2449  if (!mkv->nb_attachments)
2450  return 0;
2451 
2452  ret = start_ebml_master_crc32(&dyn_cp, mkv);
2453  if (ret < 0)
2454  return ret;
2455 
2456  for (i = 0; i < s->nb_streams; i++) {
2457  const AVStream *st = s->streams[i];
2458  mkv_track *track = &mkv->tracks[i];
2459  EBML_WRITER(6);
2460  const AVDictionaryEntry *t;
2461  const char *mimetype;
2462 
2464  continue;
2465 
2467 
2468  if (t = av_dict_get(st->metadata, "title", NULL, 0))
2470  if (!(t = av_dict_get(st->metadata, "filename", NULL, 0))) {
2471  av_log(s, AV_LOG_ERROR, "Attachment stream %d has no filename tag.\n", i);
2472  ffio_free_dyn_buf(&dyn_cp);
2473  return AVERROR(EINVAL);
2474  }
2476 
2477  mimetype = get_mimetype(st);
2478  av_assert0(mimetype);
2482  ebml_writer_add_uid(&writer, MATROSKA_ID_FILEUID, track->uid);
2483  ret = ebml_writer_write(&writer, dyn_cp);
2484  if (ret < 0) {
2485  ffio_free_dyn_buf(&dyn_cp);
2486  return ret;
2487  }
2488  }
2489  return end_ebml_master_crc32(pb, &dyn_cp, mkv,
2490  MATROSKA_ID_ATTACHMENTS, 0, 0, 1);
2491 }
2492 
2494 {
2495  const AVDictionaryEntry *duration = av_dict_get(s->metadata, "DURATION",
2496  NULL, 0);
2497  int64_t max = 0;
2498  int64_t us;
2499 
2500  if (duration && (av_parse_time(&us, duration->value, 1) == 0) && us > 0) {
2501  av_log(s, AV_LOG_DEBUG, "get_metadata_duration found duration in context metadata: %" PRId64 "\n", us);
2502  return us;
2503  }
2504 
2505  for (unsigned i = 0; i < s->nb_streams; i++) {
2506  int64_t us;
2507  duration = av_dict_get(s->streams[i]->metadata, "DURATION", NULL, 0);
2508 
2509  if (duration && (av_parse_time(&us, duration->value, 1) == 0))
2510  max = FFMAX(max, us);
2511  }
2512 
2513  av_log(s, AV_LOG_DEBUG, "get_metadata_duration returned: %" PRId64 "\n", max);
2514  return max;
2515 }
2516 
2518  const char *doctype, int version)
2519 {
2520  EBML_WRITER(8);
2526  ebml_writer_add_string(&writer, EBML_ID_DOCTYPE, doctype);
2529  /* The size is bounded, so no need to check this. */
2530  ebml_writer_write(&writer, pb);
2531 }
2532 
2534 {
2535  MatroskaMuxContext *mkv = s->priv_data;
2536  const AVDictionaryEntry *tag;
2537  int64_t creation_time;
2538  AVIOContext *pb;
2539  int ret = start_ebml_master_crc32(&mkv->info.bc, mkv);
2540  if (ret < 0)
2541  return ret;
2542  pb = mkv->info.bc;
2543 
2545  if ((tag = av_dict_get(s->metadata, "title", NULL, 0)))
2546  put_ebml_string(pb, MATROSKA_ID_TITLE, tag->value);
2547  if (!(s->flags & AVFMT_FLAG_BITEXACT)) {
2549  if ((tag = av_dict_get(s->metadata, "encoding_tool", NULL, 0)))
2551  else
2553 
2554  if (!IS_WEBM(mkv))
2556  } else {
2557  const char *ident = "Lavf";
2560  }
2561 
2562  if (ff_parse_creation_time_metadata(s, &creation_time, 0) > 0) {
2563  // Adjust time so it's relative to 2001-01-01 and convert to nanoseconds.
2564  int64_t date_utc = (creation_time - 978307200000000LL) * 1000;
2565  uint8_t date_utc_buf[8];
2566  AV_WB64(date_utc_buf, date_utc);
2567  put_ebml_binary(pb, MATROSKA_ID_DATEUTC, date_utc_buf, 8);
2568  }
2569 
2570  // reserve space for the duration
2571  mkv->duration = 0;
2572  mkv->duration_offset = avio_tell(pb);
2573  if (!mkv->is_live) {
2574  int64_t metadata_duration = get_metadata_duration(s);
2575 
2576  if (s->duration > 0) {
2577  int64_t scaledDuration = av_rescale(s->duration, 1000, AV_TIME_BASE);
2578  put_ebml_float(pb, MATROSKA_ID_DURATION, scaledDuration);
2579  av_log(s, AV_LOG_DEBUG, "Write early duration from recording time = %" PRIu64 "\n", scaledDuration);
2580  } else if (metadata_duration > 0) {
2581  int64_t scaledDuration = av_rescale(metadata_duration, 1000, AV_TIME_BASE);
2582  put_ebml_float(pb, MATROSKA_ID_DURATION, scaledDuration);
2583  av_log(s, AV_LOG_DEBUG, "Write early duration from metadata = %" PRIu64 "\n", scaledDuration);
2584  } else if (s->pb->seekable & AVIO_SEEKABLE_NORMAL) {
2585  put_ebml_void(pb, 11); // assumes double-precision float to be written
2586  }
2587  }
2588  return end_ebml_master_crc32_tentatively(s->pb, &mkv->info,
2589  mkv, MATROSKA_ID_INFO);
2590 }
2591 
2593 {
2594  MatroskaMuxContext *mkv = s->priv_data;
2595  AVIOContext *pb = s->pb;
2596  int ret, version = 2;
2597 
2598  ret = avio_open_dyn_buf(&mkv->tmp_bc);
2599  if (ret < 0)
2600  return ret;
2601 
2602  if (!IS_WEBM(mkv) ||
2603  av_dict_get(s->metadata, "stereo_mode", NULL, 0) ||
2604  av_dict_get(s->metadata, "alpha_mode", NULL, 0))
2605  version = 4;
2606 
2607  for (unsigned i = 0; i < s->nb_streams; i++) {
2608  if (s->streams[i]->codecpar->codec_id == AV_CODEC_ID_OPUS ||
2609  av_dict_get(s->streams[i]->metadata, "stereo_mode", NULL, 0) ||
2610  av_dict_get(s->streams[i]->metadata, "alpha_mode", NULL, 0))
2611  version = 4;
2612  }
2613 
2614  ebml_write_header(pb, s->oformat->name, version);
2616  put_ebml_size_unknown(pb, 8);
2617  mkv->segment_offset = avio_tell(pb);
2618 
2619  // We write a SeekHead at the beginning to point to all other level
2620  // one elements (except Clusters).
2621  mkv_start_seekhead(mkv, pb);
2622 
2623  ret = mkv_write_info(s);
2624  if (ret < 0)
2625  return ret;
2626 
2627  ret = mkv_write_tracks(s);
2628  if (ret < 0)
2629  return ret;
2630 
2632  if (ret < 0)
2633  return ret;
2634 
2635  if (!IS_WEBM(mkv)) {
2637  if (ret < 0)
2638  return ret;
2639  }
2640 
2641  /* Must come after mkv_write_chapters() to write chapter tags
2642  * into the same Tags element as the other tags. */
2643  ret = mkv_write_tags(s);
2644  if (ret < 0)
2645  return ret;
2646 
2647  if (!IS_SEEKABLE(pb, mkv)) {
2648  ret = mkv_write_seekhead(pb, mkv, 0, avio_tell(pb));
2649  if (ret < 0)
2650  return ret;
2651  }
2652 
2653  if (s->metadata_header_padding > 0) {
2654  if (s->metadata_header_padding == 1)
2655  s->metadata_header_padding++;
2656  put_ebml_void(pb, s->metadata_header_padding);
2657  }
2658 
2659  if (mkv->reserve_cues_space || mkv->move_cues_to_front) {
2660  if (IS_SEEKABLE(pb, mkv)) {
2661  mkv->cues_pos = avio_tell(pb);
2662  if (mkv->reserve_cues_space >= 1) {
2663  if (mkv->reserve_cues_space == 1)
2664  mkv->reserve_cues_space++;
2666  }
2667  } else
2668  mkv->reserve_cues_space = -1;
2669  }
2670 
2671  mkv->cluster_pos = -1;
2672 
2673  // start a new cluster every 5 MB or 5 sec, or 32k / 1 sec for streaming or
2674  // after 4k and on a keyframe
2675  if (IS_SEEKABLE(pb, mkv)) {
2676  if (mkv->cluster_time_limit < 0)
2677  mkv->cluster_time_limit = 5000;
2678  if (mkv->cluster_size_limit < 0)
2679  mkv->cluster_size_limit = 5 * 1024 * 1024;
2680  } else {
2681  if (mkv->cluster_time_limit < 0)
2682  mkv->cluster_time_limit = 1000;
2683  if (mkv->cluster_size_limit < 0)
2684  mkv->cluster_size_limit = 32 * 1024;
2685  }
2686 
2687  return 0;
2688 }
2689 
2690 #if CONFIG_MATROSKA_MUXER
2691 static int mkv_reformat_h2645(MatroskaMuxContext *mkv, AVIOContext *pb,
2692  const AVPacket *pkt, int *size)
2693 {
2694  int ret;
2695  if (pb) {
2697  } else {
2699  if (ret < 0)
2700  return ret;
2701  *size = ret;
2702  }
2703  return 0;
2704 }
2705 
2706 static int mkv_reformat_wavpack(MatroskaMuxContext *mkv, AVIOContext *pb,
2707  const AVPacket *pkt, int *size)
2708 {
2709  const uint8_t *src = pkt->data;
2710  int srclen = pkt->size;
2711  int offset = 0;
2712  int ret;
2713 
2714  while (srclen >= WV_HEADER_SIZE) {
2715  WvHeader header;
2716 
2718  if (ret < 0)
2719  return ret;
2720  src += WV_HEADER_SIZE;
2721  srclen -= WV_HEADER_SIZE;
2722 
2723  if (srclen < header.blocksize)
2724  return AVERROR_INVALIDDATA;
2725 
2726  offset += 4 * !!header.initial + 8 + 4 * !(header.initial && header.final);
2727  if (pb) {
2728  if (header.initial)
2729  avio_wl32(pb, header.samples);
2730  avio_wl32(pb, header.flags);
2731  avio_wl32(pb, header.crc);
2732 
2733  if (!(header.initial && header.final))
2734  avio_wl32(pb, header.blocksize);
2735 
2736  avio_write(pb, src, header.blocksize);
2737  }
2738  src += header.blocksize;
2739  srclen -= header.blocksize;
2740  offset += header.blocksize;
2741  }
2742  *size = offset;
2743 
2744  return 0;
2745 }
2746 #endif
2747 
2749  const AVPacket *pkt, int *size)
2750 {
2751  int ret = ff_av1_filter_obus(pb, pkt->data, pkt->size);
2752  if (ret < 0)
2753  return ret;
2754  *size = ret;
2755  return 0;
2756 }
2757 
2759  const AVPacket *pkt, int *size)
2760 {
2761  const uint8_t *id, *settings;
2762  size_t id_size, settings_size;
2763  unsigned total = pkt->size + 2U;
2764 
2765  if (total > INT_MAX)
2766  return AVERROR(ERANGE);
2767 
2769  &id_size);
2771  &settings_size);
2772  if (id_size > INT_MAX - total || settings_size > INT_MAX - (total += id_size))
2773  return AVERROR(ERANGE);
2774  *size = total += settings_size;
2775  if (pb) {
2776  avio_write(pb, id, id_size);
2777  avio_w8(pb, '\n');
2778  avio_write(pb, settings, settings_size);
2779  avio_w8(pb, '\n');
2780  avio_write(pb, pkt->data, pkt->size);
2781  }
2782  return 0;
2783 }
2784 
2785 static void mkv_write_blockadditional(EbmlWriter *writer, const uint8_t *buf,
2786  size_t size, uint64_t additional_id)
2787 {
2789  ebml_writer_add_uint(writer, MATROSKA_ID_BLOCKADDID, additional_id);
2791  ebml_writer_close_master(writer);
2792 }
2793 
2794 static int mkv_write_block(void *logctx, MatroskaMuxContext *mkv,
2795  AVIOContext *pb, const AVCodecParameters *par,
2796  mkv_track *track, const AVPacket *pkt,
2797  int keyframe, int64_t ts, uint64_t duration,
2798  int force_blockgroup, int64_t relative_packet_pos)
2799 {
2800  uint8_t t35_buf[6 + AV_HDR_PLUS_MAX_PAYLOAD_SIZE];
2801  uint8_t *side_data;
2802  size_t side_data_size;
2803  uint64_t additional_id;
2804  unsigned track_number = track->track_num;
2805  EBML_WRITER(12);
2806  int ret;
2807 
2808  mkv->cur_block.track = track;
2809  mkv->cur_block.pkt = pkt;
2810  mkv->cur_block.rel_ts = ts - mkv->cluster_pts;
2811  mkv->cur_block.flags = 0;
2812 
2813  /* Open a BlockGroup with a Block now; it will later be converted
2814  * to a SimpleBlock if possible. */
2816  ebml_writer_add_block(&writer, mkv);
2817 
2818  if (duration > 0 && (par->codec_type == AVMEDIA_TYPE_SUBTITLE ||
2819  /* If the packet's duration is inconsistent with the default duration,
2820  * add an explicit duration element. */
2821  track->default_duration_high > 0 &&
2822  duration != track->default_duration_high &&
2823  duration != track->default_duration_low))
2825 
2826  av_log(logctx, AV_LOG_DEBUG,
2827  "Writing block of size %d with pts %" PRId64 ", dts %" PRId64 ", "
2828  "duration %" PRId64 " at relative offset %" PRId64 " in cluster "
2829  "at offset %" PRId64 ". TrackNumber %u, keyframe %d\n",
2830  pkt->size, pkt->pts, pkt->dts, pkt->duration, relative_packet_pos,
2831  mkv->cluster_pos, track_number, keyframe != 0);
2832 
2833  side_data = av_packet_get_side_data(pkt,
2835  &side_data_size);
2836  if (side_data && side_data_size >= 10) {
2837  int64_t discard_padding = AV_RL32(side_data + 4);
2838  if (discard_padding) {
2839  discard_padding = av_rescale_q(discard_padding,
2840  (AVRational){1, par->sample_rate},
2841  (AVRational){1, 1000000000});
2842  ebml_writer_add_sint(&writer, MATROSKA_ID_DISCARDPADDING, discard_padding);
2843  }
2844  }
2845 
2847  side_data = av_packet_get_side_data(pkt,
2849  &side_data_size);
2850  if (side_data && side_data_size >= 8 &&
2851  // Only the Codec-specific BlockMore (id == 1) is currently supported.
2852  (additional_id = AV_RB64(side_data)) == MATROSKA_BLOCK_ADD_ID_TYPE_OPAQUE) {
2853  mkv_write_blockadditional(&writer, side_data + 8, side_data_size - 8,
2854  additional_id);
2855  track->max_blockaddid = FFMAX(track->max_blockaddid, additional_id);
2856  }
2857 
2858  if (par->codec_type == AVMEDIA_TYPE_VIDEO) {
2859  side_data = av_packet_get_side_data(pkt,
2861  &side_data_size);
2862  if (side_data && side_data_size) {
2863  uint8_t *payload = t35_buf;
2864  size_t payload_size = sizeof(t35_buf) - 6;
2865 
2866  bytestream_put_byte(&payload, ITU_T_T35_COUNTRY_CODE_US);
2867  bytestream_put_be16(&payload, ITU_T_T35_PROVIDER_CODE_SMTPE);
2868  bytestream_put_be16(&payload, 0x01); // provider_oriented_code
2869  bytestream_put_byte(&payload, 0x04); // application_identifier
2870 
2871  ret = av_dynamic_hdr_plus_to_t35((AVDynamicHDRPlus *)side_data, &payload,
2872  &payload_size);
2873  if (ret < 0)
2874  return ret;
2875 
2876  mkv_write_blockadditional(&writer, t35_buf, payload_size + 6,
2878  track->max_blockaddid = FFMAX(track->max_blockaddid,
2880  }
2881  }
2882 
2884 
2885  if (!force_blockgroup && writer.nb_elements == 2) {
2886  /* Nothing except the BlockGroup + Block. Can use a SimpleBlock. */
2887  writer.elements++; // Skip the BlockGroup.
2888  writer.nb_elements--;
2889  av_assert2(writer.elements[0].id == MATROSKA_ID_BLOCK);
2890  writer.elements[0].id = MATROSKA_ID_SIMPLEBLOCK;
2891  if (keyframe)
2892  mkv->cur_block.flags |= 1 << 7;
2893  } else if (!keyframe)
2895  track->last_timestamp - ts);
2896 
2897  return ebml_writer_write(&writer, pb);
2898 }
2899 
2901 {
2902  MatroskaMuxContext *mkv = s->priv_data;
2903  int ret;
2904 
2905  if (!mkv->have_video) {
2906  for (unsigned i = 0; i < s->nb_streams; i++)
2907  mkv->tracks[i].has_cue = 0;
2908  }
2909  mkv->cluster_pos = -1;
2910  ret = end_ebml_master_crc32(s->pb, &mkv->cluster_bc, mkv,
2911  MATROSKA_ID_CLUSTER, 0, 1, 0);
2912  if (ret < 0)
2913  return ret;
2914 
2916  return 0;
2917 }
2918 
2920 {
2921  MatroskaMuxContext *mkv = s->priv_data;
2922  mkv_track *track = &mkv->tracks[pkt->stream_index];
2923  AVCodecParameters *par = s->streams[pkt->stream_index]->codecpar;
2924  uint8_t *side_data;
2925  size_t side_data_size;
2926  int ret;
2927 
2929  &side_data_size);
2930 
2931  switch (par->codec_id) {
2932 #if CONFIG_MATROSKA_MUXER
2933  case AV_CODEC_ID_AAC:
2934  if (side_data_size && mkv->track.bc) {
2935  int output_sample_rate = 0;
2936  ret = get_aac_sample_rates(s, mkv, side_data, side_data_size,
2937  &track->sample_rate, &output_sample_rate);
2938  if (ret < 0)
2939  return ret;
2940  if (!output_sample_rate)
2941  output_sample_rate = track->sample_rate; // Space is already reserved, so it's this or a void element.
2942  ret = mkv_update_codecprivate(s, mkv, side_data, side_data_size,
2943  par, mkv->track.bc, track, 0);
2944  if (ret < 0)
2945  return ret;
2946  avio_seek(mkv->track.bc, track->sample_rate_offset, SEEK_SET);
2948  put_ebml_float(mkv->track.bc, MATROSKA_ID_AUDIOOUTSAMPLINGFREQ, output_sample_rate);
2949  } else if (!par->extradata_size && !track->sample_rate) {
2950  // No extradata (codecpar or packet side data).
2951  av_log(s, AV_LOG_ERROR, "Error parsing AAC extradata, unable to determine samplerate.\n");
2952  return AVERROR(EINVAL);
2953  }
2954  break;
2955  case AV_CODEC_ID_FLAC:
2956  if (side_data_size && mkv->track.bc) {
2957  if (side_data_size != par->extradata_size) {
2958  av_log(s, AV_LOG_ERROR, "Invalid FLAC STREAMINFO metadata for output stream %d\n",
2959  pkt->stream_index);
2960  return AVERROR(EINVAL);
2961  }
2962  ret = mkv_update_codecprivate(s, mkv, side_data, side_data_size,
2963  par, mkv->track.bc, track, 0);
2964  if (ret < 0)
2965  return ret;
2966  }
2967  break;
2968 #endif
2969  // FIXME: Remove the following once libaom starts propagating proper extradata during init()
2970  // See https://bugs.chromium.org/p/aomedia/issues/detail?id=2208
2971  case AV_CODEC_ID_AV1:
2972  if (side_data_size && mkv->track.bc && !par->extradata_size) {
2973  // If the reserved space doesn't suffice, only write
2974  // the first four bytes of the av1C.
2975  ret = mkv_update_codecprivate(s, mkv, side_data, side_data_size,
2976  par, mkv->track.bc, track, 4);
2977  if (ret < 0)
2978  return ret;
2979  } else if (!par->extradata_size)
2980  return AVERROR_INVALIDDATA;
2981  break;
2982  default:
2983  if (side_data_size)
2984  av_log(s, AV_LOG_DEBUG, "Ignoring new extradata in a packet for stream %d.\n", pkt->stream_index);
2985  break;
2986  }
2987 
2988  return 0;
2989 }
2990 
2992 {
2993  MatroskaMuxContext *mkv = s->priv_data;
2994  AVIOContext *pb;
2995  AVCodecParameters *par = s->streams[pkt->stream_index]->codecpar;
2996  mkv_track *track = &mkv->tracks[pkt->stream_index];
2997  int is_sub = par->codec_type == AVMEDIA_TYPE_SUBTITLE;
2998  /* All subtitle blocks are considered to be keyframes. */
2999  int keyframe = is_sub || !!(pkt->flags & AV_PKT_FLAG_KEY);
3001  int64_t cue_duration = is_sub ? duration : 0;
3002  int ret;
3003  int64_t ts = track->write_dts ? pkt->dts : pkt->pts;
3004  int64_t relative_packet_pos;
3005 
3006  if (ts == AV_NOPTS_VALUE) {
3007  av_log(s, AV_LOG_ERROR, "Can't write packet with unknown timestamp\n");
3008  return AVERROR(EINVAL);
3009  }
3010  ts += track->ts_offset;
3011 
3012  if (mkv->cluster_pos != -1) {
3013  int64_t cluster_time = ts - mkv->cluster_pts;
3014  if ((int16_t)cluster_time != cluster_time) {
3015  ret = mkv_end_cluster(s);
3016  if (ret < 0)
3017  return ret;
3018  av_log(s, AV_LOG_WARNING, "Starting new cluster due to timestamp\n");
3019  }
3020  }
3021 
3022  if (mkv->cluster_pos == -1) {
3023  ret = start_ebml_master_crc32(&mkv->cluster_bc, mkv);
3024  if (ret < 0)
3025  return ret;
3026  mkv->cluster_bc->direct = 1;
3027  mkv->cluster_pos = avio_tell(s->pb);
3029  mkv->cluster_pts = FFMAX(0, ts);
3031  "Starting new cluster with timestamp "
3032  "%" PRId64 " at offset %" PRId64 " bytes\n",
3033  mkv->cluster_pts, mkv->cluster_pos);
3034  }
3035  pb = mkv->cluster_bc;
3036 
3037  relative_packet_pos = avio_tell(pb);
3038 
3039  /* The WebM spec requires WebVTT to be muxed in BlockGroups;
3040  * so we force it even for packets without duration. */
3041  ret = mkv_write_block(s, mkv, pb, par, track, pkt,
3042  keyframe, ts, duration,
3043  par->codec_id == AV_CODEC_ID_WEBVTT,
3044  relative_packet_pos);
3045  if (ret < 0)
3046  return ret;
3047  if (keyframe && IS_SEEKABLE(s->pb, mkv) &&
3048  (par->codec_type == AVMEDIA_TYPE_VIDEO ||
3050  !mkv->have_video && !track->has_cue)) {
3051  ret = mkv_add_cuepoint(mkv, pkt->stream_index, ts,
3052  mkv->cluster_pos, relative_packet_pos,
3053  cue_duration);
3054  if (ret < 0)
3055  return ret;
3056  track->has_cue = 1;
3057  }
3058 
3059  track->last_timestamp = ts;
3060  mkv->duration = FFMAX(mkv->duration, ts + duration);
3061  track->duration = FFMAX(track->duration, ts + duration);
3062 
3063  return 0;
3064 }
3065 
3067 {
3068  MatroskaMuxContext *mkv = s->priv_data;
3069  int codec_type = s->streams[pkt->stream_index]->codecpar->codec_type;
3070  int keyframe = !!(pkt->flags & AV_PKT_FLAG_KEY);
3071  int cluster_size;
3072  int64_t cluster_time;
3073  int ret;
3074  int start_new_cluster;
3075 
3077  if (ret < 0)
3078  return ret;
3079 
3080  if (mkv->cluster_pos != -1) {
3081  if (mkv->tracks[pkt->stream_index].write_dts)
3082  cluster_time = pkt->dts - mkv->cluster_pts;
3083  else
3084  cluster_time = pkt->pts - mkv->cluster_pts;
3085  cluster_time += mkv->tracks[pkt->stream_index].ts_offset;
3086 
3087  cluster_size = avio_tell(mkv->cluster_bc);
3088 
3089  if (mkv->is_dash && codec_type == AVMEDIA_TYPE_VIDEO) {
3090  // WebM DASH specification states that the first block of
3091  // every Cluster has to be a key frame. So for DASH video,
3092  // we only create a Cluster on seeing key frames.
3093  start_new_cluster = keyframe;
3094  } else if (mkv->is_dash && codec_type == AVMEDIA_TYPE_AUDIO &&
3095  cluster_time > mkv->cluster_time_limit) {
3096  // For DASH audio, we create a Cluster based on cluster_time_limit.
3097  start_new_cluster = 1;
3098  } else if (!mkv->is_dash &&
3099  (cluster_size > mkv->cluster_size_limit ||
3100  cluster_time > mkv->cluster_time_limit ||
3101  (codec_type == AVMEDIA_TYPE_VIDEO && keyframe &&
3102  cluster_size > 4 * 1024))) {
3103  start_new_cluster = 1;
3104  } else
3105  start_new_cluster = 0;
3106 
3107  if (start_new_cluster) {
3108  ret = mkv_end_cluster(s);
3109  if (ret < 0)
3110  return ret;
3111  }
3112  }
3113 
3114  if (mkv->cluster_pos == -1)
3115  avio_write_marker(s->pb,
3116  av_rescale_q(pkt->dts, s->streams[pkt->stream_index]->time_base, AV_TIME_BASE_Q),
3118 
3119  // check if we have an audio packet cached
3120  if (mkv->cur_audio_pkt->size > 0) {
3123  if (ret < 0) {
3125  "Could not write cached audio packet ret:%d\n", ret);
3126  return ret;
3127  }
3128  }
3129 
3130  // buffer an audio packet to ensure the packet containing the video
3131  // keyframe's timecode is contained in the same cluster for WebM
3132  if (codec_type == AVMEDIA_TYPE_AUDIO) {
3133  if (pkt->size > 0)
3135  } else
3137  return ret;
3138 }
3139 
3141 {
3142  MatroskaMuxContext *mkv = s->priv_data;
3143 
3144  if (!pkt) {
3145  if (mkv->cluster_pos != -1) {
3146  int ret = mkv_end_cluster(s);
3147  if (ret < 0)
3148  return ret;
3150  "Flushing cluster at offset %" PRIu64 " bytes\n",
3151  avio_tell(s->pb));
3152  }
3153  return 1;
3154  }
3155  return mkv_write_packet(s, pkt);
3156 }
3157 
3159 {
3160  MatroskaMuxContext *mkv = s->priv_data;
3161  AVIOContext *pb = s->pb;
3162  int64_t endpos, ret64;
3163  int ret, ret2 = 0;
3164 
3165  // check if we have an audio packet cached
3166  if (mkv->cur_audio_pkt->size > 0) {
3168  if (ret < 0) {
3170  "Could not write cached audio packet ret:%d\n", ret);
3171  return ret;
3172  }
3173  }
3174 
3175  if (mkv->cluster_pos != -1) {
3176  ret = end_ebml_master_crc32(pb, &mkv->cluster_bc, mkv,
3177  MATROSKA_ID_CLUSTER, 0, 0, 0);
3178  if (ret < 0)
3179  return ret;
3180  }
3181 
3183  if (ret < 0)
3184  return ret;
3185 
3186  if (!IS_SEEKABLE(pb, mkv))
3187  return 0;
3188 
3189  endpos = avio_tell(pb);
3190 
3191  if (mkv->cues.num_entries && mkv->reserve_cues_space >= 0) {
3192  AVIOContext *cues = NULL;
3193  uint64_t size, offset = 0;
3194  int length_size = 0;
3195 
3196 redo_cues:
3197  ret = start_ebml_master_crc32(&cues, mkv);
3198  if (ret < 0)
3199  return ret;
3200 
3201  ret = mkv_assemble_cues(s->streams, cues, mkv->tmp_bc, &mkv->cues,
3202  mkv->tracks, s->nb_streams, offset);
3203  if (ret < 0) {
3204  ffio_free_dyn_buf(&cues);
3205  return ret;
3206  }
3207 
3208  if (mkv->reserve_cues_space || mkv->move_cues_to_front) {
3209  size = avio_tell(cues);
3210  length_size = ebml_length_size(size);
3211  size += 4 + length_size;
3212  if (offset + mkv->reserve_cues_space < size) {
3213  if (mkv->move_cues_to_front) {
3214  offset = size - mkv->reserve_cues_space;
3215  ffio_reset_dyn_buf(cues);
3216  goto redo_cues;
3217  }
3219  "Insufficient space reserved for Cues: "
3220  "%d < %"PRIu64". No Cues will be output.\n",
3221  mkv->reserve_cues_space, size);
3222  ret2 = AVERROR(EINVAL);
3223  goto after_cues;
3224  } else {
3225  if (offset) {
3227  offset);
3228  if (ret < 0) {
3229  ffio_free_dyn_buf(&cues);
3230  return ret;
3231  }
3232  endpos += offset;
3233  }
3234  if ((ret64 = avio_seek(pb, mkv->cues_pos, SEEK_SET)) < 0) {
3235  ffio_free_dyn_buf(&cues);
3236  return ret64;
3237  }
3238  if (mkv->reserve_cues_space == size + 1) {
3239  /* There is no way to reserve a single byte because
3240  * the minimal size of an EBML Void element is 2
3241  * (1 byte ID, 1 byte length field). This problem
3242  * is solved by writing the Cues' length field on
3243  * one byte more than necessary. */
3244  length_size++;
3245  size++;
3246  }
3247  }
3248  }
3249  ret = end_ebml_master_crc32(pb, &cues, mkv, MATROSKA_ID_CUES,
3250  length_size, 0, 1);
3251  if (ret < 0)
3252  return ret;
3253  if (mkv->reserve_cues_space) {
3254  if (size < mkv->reserve_cues_space)
3256  } else if (!mkv->move_cues_to_front)
3257  endpos = avio_tell(pb);
3258  }
3259 
3260 after_cues:
3261  /* Lengths greater than (1ULL << 56) - 1 can't be represented
3262  * via an EBML number, so leave the unknown length field. */
3263  if (endpos - mkv->segment_offset < (1ULL << 56) - 1) {
3264  if ((ret64 = avio_seek(pb, mkv->segment_offset - 8, SEEK_SET)) < 0)
3265  return ret64;
3266  put_ebml_length(pb, endpos - mkv->segment_offset, 8);
3267  }
3268 
3269  ret = mkv_write_seekhead(pb, mkv, 1, mkv->info.pos);
3270  if (ret < 0)
3271  return ret;
3272 
3273  if (mkv->info.bc) {
3274  // update the duration
3275  av_log(s, AV_LOG_DEBUG, "end duration = %" PRIu64 "\n", mkv->duration);
3276  avio_seek(mkv->info.bc, mkv->duration_offset, SEEK_SET);
3278  ret = end_ebml_master_crc32(pb, &mkv->info.bc, mkv,
3279  MATROSKA_ID_INFO, 0, 0, 0);
3280  if (ret < 0)
3281  return ret;
3282  }
3283 
3284  if (mkv->track.bc) {
3285  // write Tracks master
3286  if (!IS_WEBM(mkv)) {
3287  AVIOContext *track_bc = mkv->track.bc;
3288 
3289  for (unsigned i = 0; i < s->nb_streams; i++) {
3290  const mkv_track *track = &mkv->tracks[i];
3291 
3292  if (!track->max_blockaddid)
3293  continue;
3294 
3295  // We reserved a single byte to write this value.
3296  av_assert0(track->max_blockaddid <= 0xFF);
3297 
3298  avio_seek(track_bc, track->blockadditionmapping_offset, SEEK_SET);
3299 
3301  track->max_blockaddid);
3303  ebml_master mapping_master = start_ebml_master(track_bc, MATROSKA_ID_TRACKBLKADDMAPPING, 8);
3308  end_ebml_master(track_bc, mapping_master);
3309  }
3310  }
3311  }
3312 
3313  avio_seek(pb, mkv->track.pos, SEEK_SET);
3314  ret = end_ebml_master_crc32(pb, &mkv->track.bc, mkv,
3315  MATROSKA_ID_TRACKS, 0, 0, 0);
3316  if (ret < 0)
3317  return ret;
3318  }
3319 
3320  // update stream durations
3321  if (mkv->tags.bc) {
3322  AVIOContext *tags_bc = mkv->tags.bc;
3323  int i;
3324  for (i = 0; i < s->nb_streams; ++i) {
3325  const AVStream *st = s->streams[i];
3326  const mkv_track *track = &mkv->tracks[i];
3327 
3328  if (track->duration_offset > 0) {
3329  double duration_sec = track->duration * av_q2d(st->time_base);
3330  char duration_string[DURATION_STRING_LENGTH + 1] = "";
3331  ebml_master simpletag;
3332 
3333  av_log(s, AV_LOG_DEBUG, "stream %d end duration = %" PRIu64 "\n", i,
3334  track->duration);
3335 
3336  avio_seek(tags_bc, track->duration_offset, SEEK_SET);
3337  simpletag = start_ebml_master(tags_bc, MATROSKA_ID_SIMPLETAG,
3338  2 + 1 + 8 + 23);
3339  put_ebml_string(tags_bc, MATROSKA_ID_TAGNAME, "DURATION");
3340 
3341  snprintf(duration_string, sizeof(duration_string), "%02d:%02d:%012.9f",
3342  (int) duration_sec / 3600, ((int) duration_sec / 60) % 60,
3343  fmod(duration_sec, 60));
3344 
3346  duration_string, DURATION_STRING_LENGTH);
3347  end_ebml_master(tags_bc, simpletag);
3348  }
3349  }
3350 
3351  avio_seek(pb, mkv->tags.pos, SEEK_SET);
3352  ret = end_ebml_master_crc32(pb, &mkv->tags.bc, mkv,
3353  MATROSKA_ID_TAGS, 0, 0, 0);
3354  if (ret < 0)
3355  return ret;
3356  }
3357 
3358  avio_seek(pb, endpos, SEEK_SET);
3359 
3360  return ret2;
3361 }
3362 
3363 static uint64_t mkv_get_uid(const mkv_track *tracks, int i, AVLFG *c)
3364 {
3365  while (1) {
3366  uint64_t uid;
3367  int k;
3368  uid = (uint64_t)av_lfg_get(c) << 32;
3369  uid |= av_lfg_get(c);
3370  if (!uid)
3371  continue;
3372  for (k = 0; k < i; k++) {
3373  if (tracks[k].uid == uid)
3374  break;
3375  }
3376  if (k == i)
3377  return uid;
3378  }
3379 }
3380 
3381 static int mkv_init(struct AVFormatContext *s)
3382 {
3383  FFFormatContext *const si = ffformatcontext(s);
3384  MatroskaMuxContext *mkv = s->priv_data;
3385  AVLFG c;
3386  unsigned nb_tracks = 0;
3387  int i;
3388 
3389  mkv->ctx = s;
3390 
3391  for (i = 0; i < s->nb_streams; i++) {
3392  if (s->streams[i]->codecpar->codec_id == AV_CODEC_ID_ATRAC3 ||
3393  s->streams[i]->codecpar->codec_id == AV_CODEC_ID_COOK ||
3394  s->streams[i]->codecpar->codec_id == AV_CODEC_ID_RA_288 ||
3395  s->streams[i]->codecpar->codec_id == AV_CODEC_ID_SIPR ||
3396  s->streams[i]->codecpar->codec_id == AV_CODEC_ID_RV10 ||
3397  s->streams[i]->codecpar->codec_id == AV_CODEC_ID_RV20 ||
3398  s->streams[i]->codecpar->codec_id == AV_CODEC_ID_RV30) {
3400  "The Matroska muxer does not yet support muxing %s\n",
3401  avcodec_get_name(s->streams[i]->codecpar->codec_id));
3402  return AVERROR_PATCHWELCOME;
3403  }
3404  }
3405 
3406  if (s->avoid_negative_ts < 0) {
3407  s->avoid_negative_ts = 1;
3408  si->avoid_negative_ts_use_pts = 1;
3409  }
3410 
3411  if (!CONFIG_MATROSKA_MUXER ||
3412  (CONFIG_WEBM_MUXER && !strcmp(s->oformat->name, "webm"))) {
3413  mkv->mode = MODE_WEBM;
3414  mkv->write_crc = 0;
3415  } else
3416  mkv->mode = MODE_MATROSKAv2;
3417 
3419 
3420  mkv->tracks = av_calloc(s->nb_streams, sizeof(*mkv->tracks));
3421  if (!mkv->tracks)
3422  return AVERROR(ENOMEM);
3423 
3424  if (!(s->flags & AVFMT_FLAG_BITEXACT)) {
3426 
3427  // Calculate the SegmentUID now in order not to waste our random seed.
3428  for (i = 0; i < 4; i++)
3429  mkv->segment_uid[i] = av_lfg_get(&c);
3430  }
3431 
3432  for (i = 0; i < s->nb_streams; i++) {
3433  AVStream *st = s->streams[i];
3434  const AVCodecParameters *const par = st->codecpar;
3435  mkv_track *track = &mkv->tracks[i];
3436 
3437  switch (par->codec_id) {
3438 #if CONFIG_MATROSKA_MUXER
3439  case AV_CODEC_ID_WAVPACK:
3440  track->reformat = mkv_reformat_wavpack;
3441  break;
3442  case AV_CODEC_ID_H264:
3443  case AV_CODEC_ID_HEVC:
3444  if ((par->codec_id == AV_CODEC_ID_H264 && par->extradata_size > 0 ||
3445  par->codec_id == AV_CODEC_ID_HEVC && par->extradata_size > 6) &&
3446  (AV_RB24(par->extradata) == 1 || AV_RB32(par->extradata) == 1))
3447  track->reformat = mkv_reformat_h2645;
3448  break;
3449  case AV_CODEC_ID_PRORES:
3450  /* Matroska specification requires to remove
3451  * the first QuickTime atom. */
3452  track->offset = 8;
3453  break;
3454 #endif
3455  case AV_CODEC_ID_AV1:
3456  track->reformat = mkv_reformat_av1;
3457  break;
3458  case AV_CODEC_ID_WEBVTT:
3459  track->reformat = webm_reformat_vtt;
3460  break;
3461  }
3462 
3463  if (s->flags & AVFMT_FLAG_BITEXACT) {
3464  track->uid = i + 1;
3465  } else {
3466  track->uid = mkv_get_uid(mkv->tracks, i, &c);
3467  }
3468 
3469  // ms precision is the de-facto standard timescale for mkv files
3470  avpriv_set_pts_info(st, 64, 1, 1000);
3471 
3473  if (IS_WEBM(mkv)) {
3474  av_log(s, AV_LOG_WARNING, "Stream %d will be ignored "
3475  "as WebM doesn't support attachments.\n", i);
3476  } else if (!get_mimetype(st)) {
3477  av_log(s, AV_LOG_ERROR, "Attachment stream %d has no mimetype "
3478  "tag and it cannot be deduced from the codec id.\n", i);
3479  return AVERROR(EINVAL);
3480  }
3481  mkv->nb_attachments++;
3482  continue;
3483  }
3484 
3485  nb_tracks++;
3486  track->track_num = mkv->is_dash ? mkv->dash_track_number : nb_tracks;
3487  track->track_num_size = ebml_num_size(track->track_num);
3488  }
3489 
3490  if (mkv->is_dash && nb_tracks != 1)
3491  return AVERROR(EINVAL);
3492 
3493  return 0;
3494 }
3495 
3497  const AVPacket *pkt)
3498 {
3499  int ret = 1;
3500 
3501  if (CONFIG_MATROSKA_MUXER && st->codecpar->codec_id == AV_CODEC_ID_AAC) {
3502  if (pkt->size > 2 && (AV_RB16(pkt->data) & 0xfff0) == 0xfff0)
3503  ret = ff_stream_add_bitstream_filter(st, "aac_adtstoasc", NULL);
3504  } else if (st->codecpar->codec_id == AV_CODEC_ID_VP9) {
3505  ret = ff_stream_add_bitstream_filter(st, "vp9_superframe", NULL);
3506  } else if (CONFIG_MATROSKA_MUXER &&
3508  ret = ff_stream_add_bitstream_filter(st, "pgs_frame_merge", NULL);
3509  }
3510 
3511  return ret;
3512 }
3513 
3515  { AV_CODEC_ID_ALAC, 0XFFFFFFFF },
3516  { AV_CODEC_ID_ATRAC1, 0xFFFFFFFF },
3517  { AV_CODEC_ID_MLP, 0xFFFFFFFF },
3518  { AV_CODEC_ID_OPUS, 0xFFFFFFFF },
3519  { AV_CODEC_ID_PCM_S16BE, 0xFFFFFFFF },
3520  { AV_CODEC_ID_PCM_S24BE, 0xFFFFFFFF },
3521  { AV_CODEC_ID_PCM_S32BE, 0xFFFFFFFF },
3522  { AV_CODEC_ID_QDMC, 0xFFFFFFFF },
3523  { AV_CODEC_ID_QDM2, 0xFFFFFFFF },
3524  { AV_CODEC_ID_RA_144, 0xFFFFFFFF },
3525  { AV_CODEC_ID_TRUEHD, 0xFFFFFFFF },
3526  { AV_CODEC_ID_NONE, 0xFFFFFFFF }
3527 };
3528 
3530  { AV_CODEC_ID_DVB_SUBTITLE, 0xFFFFFFFF },
3531  { AV_CODEC_ID_DVD_SUBTITLE, 0xFFFFFFFF },
3532  { AV_CODEC_ID_HDMV_PGS_SUBTITLE, 0xFFFFFFFF },
3533  { AV_CODEC_ID_ARIB_CAPTION, 0xFFFFFFFF },
3534  { AV_CODEC_ID_NONE, 0xFFFFFFFF }
3535 };
3536 
3537 #define OFFSET(x) offsetof(MatroskaMuxContext, x)
3538 #define FLAGS AV_OPT_FLAG_ENCODING_PARAM
3539 static const AVOption options[] = {
3540  { "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 },
3541  { "cues_to_front", "move Cues (the index) to the front by shifting data if necessary", OFFSET(move_cues_to_front), AV_OPT_TYPE_BOOL, { .i64 = 0}, 0, 1, FLAGS },
3542  { "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 },
3543  { "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 },
3544  { "dash", "create a WebM file conforming to WebM DASH specification", OFFSET(is_dash), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, FLAGS },
3545  { "dash_track_number", "track number for the DASH stream", OFFSET(dash_track_number), AV_OPT_TYPE_INT, { .i64 = 1 }, 1, INT_MAX, FLAGS },
3546  { "live", "write files assuming it is a live stream", OFFSET(is_live), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, FLAGS },
3547  { "allow_raw_vfw", "allow raw VFW mode", OFFSET(allow_raw_vfw), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, FLAGS },
3548  { "flipped_raw_rgb", "store raw RGB bitmaps in VFW mode in bottom-up mode", OFFSET(flipped_raw_rgb), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, FLAGS },
3549  { "write_crc32", "write a CRC32 element inside every Level 1 element", OFFSET(write_crc), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, FLAGS },
3550  { "default_mode", "control how a track's FlagDefault is inferred", OFFSET(default_mode), AV_OPT_TYPE_INT, { .i64 = DEFAULT_MODE_PASSTHROUGH }, DEFAULT_MODE_INFER, DEFAULT_MODE_PASSTHROUGH, FLAGS, .unit = "default_mode" },
3551  { "infer", "for each track type, mark each track of disposition default as default; if none exists, mark the first track as default", 0, AV_OPT_TYPE_CONST, { .i64 = DEFAULT_MODE_INFER }, 0, 0, FLAGS, .unit = "default_mode" },
3552  { "infer_no_subs", "for each track type, mark each track of disposition default as default; for audio and video: if none exists, mark the first track as default", 0, AV_OPT_TYPE_CONST, { .i64 = DEFAULT_MODE_INFER_NO_SUBS }, 0, 0, FLAGS, .unit = "default_mode" },
3553  { "passthrough", "use the disposition flag as-is", 0, AV_OPT_TYPE_CONST, { .i64 = DEFAULT_MODE_PASSTHROUGH }, 0, 0, FLAGS, .unit = "default_mode" },
3554  { NULL },
3555 };
3556 
3558  .class_name = "matroska/webm muxer",
3559  .item_name = av_default_item_name,
3560  .option = options,
3561  .version = LIBAVUTIL_VERSION_INT,
3562 };
3563 
3564 #if CONFIG_MATROSKA_MUXER
3565 static int mkv_query_codec(enum AVCodecID codec_id, int std_compliance)
3566 {
3567  for (int i = 0; ff_mkv_codec_tags[i].id != AV_CODEC_ID_NONE; i++)
3568  if (ff_mkv_codec_tags[i].id == codec_id)
3569  return 1;
3570 
3571  if (std_compliance < FF_COMPLIANCE_NORMAL) {
3573  // mkv theoretically supports any video/audio through VFW/ACM
3575  return 1;
3576  }
3577 
3578  return 0;
3579 }
3580 
3582  .p.name = "matroska",
3583  .p.long_name = NULL_IF_CONFIG_SMALL("Matroska"),
3584  .p.mime_type = "video/x-matroska",
3585  .p.extensions = "mkv",
3586  .priv_data_size = sizeof(MatroskaMuxContext),
3587  .p.audio_codec = CONFIG_LIBVORBIS_ENCODER ?
3589  .p.video_codec = CONFIG_LIBX264_ENCODER ?
3591  .init = mkv_init,
3592  .deinit = mkv_deinit,
3593  .write_header = mkv_write_header,
3594  .write_packet = mkv_write_flush_packet,
3595  .write_trailer = mkv_write_trailer,
3596  .p.flags = AVFMT_GLOBALHEADER | AVFMT_VARIABLE_FPS |
3598  AVFMT_TS_NONSTRICT | AVFMT_ALLOW_FLUSH,
3599 #else
3601 #endif
3602  .p.codec_tag = (const AVCodecTag* const []){
3605  },
3606  .p.subtitle_codec = AV_CODEC_ID_ASS,
3607  .query_codec = mkv_query_codec,
3608  .check_bitstream = mkv_check_bitstream,
3609  .p.priv_class = &matroska_webm_class,
3610  .flags_internal = FF_OFMT_FLAG_ALLOW_FLUSH,
3611 };
3612 #endif
3613 
3614 #if CONFIG_WEBM_MUXER
3615 static int webm_query_codec(enum AVCodecID codec_id, int std_compliance)
3616 {
3617  for (int i = 0; ff_webm_codec_tags[i].id != AV_CODEC_ID_NONE; i++)
3618  if (ff_webm_codec_tags[i].id == codec_id)
3619  return 1;
3620 
3621  return 0;
3622 }
3623 
3624 const FFOutputFormat ff_webm_muxer = {
3625  .p.name = "webm",
3626  .p.long_name = NULL_IF_CONFIG_SMALL("WebM"),
3627  .p.mime_type = "video/webm",
3628  .p.extensions = "webm",
3629  .priv_data_size = sizeof(MatroskaMuxContext),
3630  .p.audio_codec = CONFIG_LIBOPUS_ENCODER ? AV_CODEC_ID_OPUS : AV_CODEC_ID_VORBIS,
3631  .p.video_codec = CONFIG_LIBVPX_VP9_ENCODER? AV_CODEC_ID_VP9 : AV_CODEC_ID_VP8,
3632  .p.subtitle_codec = AV_CODEC_ID_WEBVTT,
3633  .init = mkv_init,
3634  .deinit = mkv_deinit,
3635  .write_header = mkv_write_header,
3636  .write_packet = mkv_write_flush_packet,
3637  .write_trailer = mkv_write_trailer,
3638  .query_codec = webm_query_codec,
3639  .check_bitstream = mkv_check_bitstream,
3640  .p.flags = AVFMT_GLOBALHEADER | AVFMT_VARIABLE_FPS |
3642  AVFMT_TS_NONSTRICT | AVFMT_ALLOW_FLUSH,
3643 #else
3645 #endif
3646  .p.priv_class = &matroska_webm_class,
3647  .flags_internal = FF_OFMT_FLAG_ALLOW_FLUSH,
3648 };
3649 #endif
3650 
3651 #if CONFIG_MATROSKA_AUDIO_MUXER
3653  .p.name = "matroska",
3654  .p.long_name = NULL_IF_CONFIG_SMALL("Matroska Audio"),
3655  .p.mime_type = "audio/x-matroska",
3656  .p.extensions = "mka",
3657  .priv_data_size = sizeof(MatroskaMuxContext),
3658  .p.audio_codec = CONFIG_LIBVORBIS_ENCODER ?
3660  .p.video_codec = AV_CODEC_ID_NONE,
3661  .init = mkv_init,
3662  .deinit = mkv_deinit,
3663  .write_header = mkv_write_header,
3664  .write_packet = mkv_write_flush_packet,
3665  .write_trailer = mkv_write_trailer,
3666  .check_bitstream = mkv_check_bitstream,
3668  .p.flags = AVFMT_GLOBALHEADER | AVFMT_TS_NONSTRICT |
3669  AVFMT_ALLOW_FLUSH,
3670 #else
3672 #endif
3673  .p.codec_tag = (const AVCodecTag* const []){
3675  },
3676  .p.priv_class = &matroska_webm_class,
3677  .flags_internal = FF_OFMT_FLAG_ALLOW_FLUSH,
3678 };
3679 #endif
MatroskaMuxContext::reserve_cues_space
int reserve_cues_space
Definition: matroskaenc.c:250
MATROSKA_ID_TAGTARGETS_ATTACHUID
#define MATROSKA_ID_TAGTARGETS_ATTACHUID
Definition: matroska.h:225
AVMasteringDisplayMetadata::has_primaries
int has_primaries
Flag indicating whether the display primaries (and white point) are set.
Definition: mastering_display_metadata.h:62
AV_PKT_DATA_DISPLAYMATRIX
@ AV_PKT_DATA_DISPLAYMATRIX
This side data contains a 3x3 transformation matrix describing an affine transformation that needs to...
Definition: packet.h:105
av_packet_unref
void av_packet_unref(AVPacket *pkt)
Wipe the packet.
Definition: packet.c:429
MATROSKA_ID_VIDEODISPLAYUNIT
#define MATROSKA_ID_VIDEODISPLAYUNIT
Definition: matroska.h:125
MATROSKA_ID_CODECPRIVATE
#define MATROSKA_ID_CODECPRIVATE
Definition: matroska.h:88
MATROSKA_ID_TRACKNUMBER
#define MATROSKA_ID_TRACKNUMBER
Definition: matroska.h:77
AVMEDIA_TYPE_SUBTITLE
@ AVMEDIA_TYPE_SUBTITLE
Definition: avutil.h:204
EBML_BIN
@ EBML_BIN
Definition: matroskaenc.c:113
MATROSKA_ID_TRACKFLAGVISUALIMPAIRED
#define MATROSKA_ID_TRACKFLAGVISUALIMPAIRED
Definition: matroska.h:101
AV_LOG_WARNING
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition: log.h:215
MatroskaMuxContext::is_dash
int is_dash
Definition: matroskaenc.c:256
MATROSKA_ID_CHAPSTRING
#define MATROSKA_ID_CHAPSTRING
Definition: matroska.h:266
IS_SEEKABLE
#define IS_SEEKABLE(pb, mkv)
Definition: matroskaenc.c:87
mkv_init
static int mkv_init(struct AVFormatContext *s)
Definition: matroskaenc.c:3381
MATROSKA_ID_TAGTARGETS
#define MATROSKA_ID_TAGTARGETS
Definition: matroska.h:220
AVMasteringDisplayMetadata::max_luminance
AVRational max_luminance
Max luminance of mastering display (cd/m^2).
Definition: mastering_display_metadata.h:57
AVCodecParameters::extradata
uint8_t * extradata
Extra binary data needed for initializing the decoder, codec-dependent.
Definition: codec_par.h:69
name
it s the only field you need to keep assuming you have a context There is some magic you don t need to care about around this just let it vf default minimum maximum flags name is the option name
Definition: writing_filters.txt:88
MATROSKA_ID_CLUSTERTIMECODE
#define MATROSKA_ID_CLUSTERTIMECODE
Definition: matroska.h:235
LIBAVFORMAT_IDENT
#define LIBAVFORMAT_IDENT
Definition: version.h:45
entry
#define entry
Definition: aom_film_grain_template.c:66
ebml_num_size
static int ebml_num_size(uint64_t num)
Returns how many bytes are needed to represent a number as EBML variable length integer.
Definition: matroskaenc.c:313
AV_CODEC_ID_AC3
@ AV_CODEC_ID_AC3
Definition: codec_id.h:449
AVIO_DATA_MARKER_BOUNDARY_POINT
@ AVIO_DATA_MARKER_BOUNDARY_POINT
A point in the output bytestream where a demuxer can start parsing (for non self synchronizing bytest...
Definition: avio.h:127
mkv_write_packet
static int mkv_write_packet(AVFormatContext *s, const AVPacket *pkt)
Definition: matroskaenc.c:3066
AVOutputFormat::name
const char * name
Definition: avformat.h:510
MATROSKA_ID_TITLE
#define MATROSKA_ID_TITLE
Definition: matroska.h:67
AVERROR
Filter the word “frame” indicates either a video frame or a group of audio as stored in an AVFrame structure Format for each input and each output the list of supported formats For video that means pixel format For audio that means channel sample they are references to shared objects When the negotiation mechanism computes the intersection of the formats supported at each end of a all references to both lists are replaced with a reference to the intersection And when a single format is eventually chosen for a link amongst the remaining all references to the list are updated That means that if a filter requires that its input and output have the same format amongst a supported all it has to do is use a reference to the same list of formats query_formats can leave some formats unset and return AVERROR(EAGAIN) to cause the negotiation mechanism toagain later. That can be used by filters with complex requirements to use the format negotiated on one link to set the formats supported on another. Frame references ownership and permissions
uid
UID uid
Definition: mxfenc.c:2428
opt.h
put_ebml_size_unknown
static void put_ebml_size_unknown(AVIOContext *pb, int bytes)
Write an EBML size meaning "unknown size".
Definition: matroskaenc.c:300
ebml_writer_add_string
static void ebml_writer_add_string(EbmlWriter *writer, uint32_t id, const char *str)
Definition: matroskaenc.c:502
mkv_write_packet_internal
static int mkv_write_packet_internal(AVFormatContext *s, const AVPacket *pkt)
Definition: matroskaenc.c:2991
MatroskaMuxContext::allow_raw_vfw
int allow_raw_vfw
Definition: matroskaenc.c:258
ebml_writer_add_float
static void ebml_writer_add_float(EbmlWriter *writer, uint32_t id, double val)
Definition: matroskaenc.c:522
AVCodecParameters::codec_type
enum AVMediaType codec_type
General type of the encoded data.
Definition: codec_par.h:51
AVSphericalMapping::projection
enum AVSphericalProjection projection
Projection type.
Definition: spherical.h:98
AV1_SANE_SEQUENCE_HEADER_MAX_BITS
#define AV1_SANE_SEQUENCE_HEADER_MAX_BITS
Definition: av1.h:190
AV_WL32
#define AV_WL32(p, v)
Definition: intreadwrite.h:422
hevc.h
AVSphericalMapping::bound_bottom
uint32_t bound_bottom
Distance from the bottom edge.
Definition: spherical.h:182
MATROSKA_ID_VIDEOCOLORMASTERINGMETA
#define MATROSKA_ID_VIDEOCOLORMASTERINGMETA
Definition: matroska.h:149
ebml_writer_master_len
static int ebml_writer_master_len(EbmlWriter *writer, EbmlElement *elem, int remaining_elems)
Definition: matroskaenc.c:597
AVFieldOrder
AVFieldOrder
Definition: defs.h:200
MatroskaMuxContext::segment_offset
int64_t segment_offset
Definition: matroskaenc.c:221
av_lfg_init
av_cold void av_lfg_init(AVLFG *c, unsigned int seed)
Definition: lfg.c:32
MatroskaMuxContext::tracks
mkv_track * tracks
Definition: matroskaenc.c:227
AV_PKT_DATA_FRAME_CROPPING
@ AV_PKT_DATA_FRAME_CROPPING
The number of pixels to discard from the top/bottom/left/right border of the decoded frame to obtain ...
Definition: packet.h:340
AVCodecParameters
This struct describes the properties of an encoded stream.
Definition: codec_par.h:47
EBML_ID_EBMLMAXSIZELENGTH
#define EBML_ID_EBMLMAXSIZELENGTH
Definition: matroska.h:38
ffformatcontext
static av_always_inline FFFormatContext * ffformatcontext(AVFormatContext *s)
Definition: internal.h:127
mkv_new_chapter_ids_needed
static int mkv_new_chapter_ids_needed(const AVFormatContext *s)
Definition: matroskaenc.c:2329
AVCodecParameters::color_space
enum AVColorSpace color_space
Definition: codec_par.h:169
end_ebml_master_crc32
static int end_ebml_master_crc32(AVIOContext *pb, AVIOContext **dyn_cp, MatroskaMuxContext *mkv, uint32_t id, int length_size, int keep_buffer, int add_seekentry)
Definition: matroskaenc.c:780
MATROSKA_ID_TRACKFLAGTEXTDESCRIPTIONS
#define MATROSKA_ID_TRACKFLAGTEXTDESCRIPTIONS
Definition: matroska.h:102
AV_PKT_DATA_NEW_EXTRADATA
@ AV_PKT_DATA_NEW_EXTRADATA
The AV_PKT_DATA_NEW_EXTRADATA is used to notify the codec or the format that the extradata buffer was...
Definition: packet.h:56
AVFMT_VARIABLE_FPS
#define AVFMT_VARIABLE_FPS
Format allows variable fps.
Definition: avformat.h:482
avcodec_get_type
enum AVMediaType avcodec_get_type(enum AVCodecID codec_id)
Get the type of the given codec.
Definition: codec_desc.c:3784
AV_FIELD_PROGRESSIVE
@ AV_FIELD_PROGRESSIVE
Definition: defs.h:202
MATROSKA_ID_VIDEOPIXELWIDTH
#define MATROSKA_ID_VIDEOPIXELWIDTH
Definition: matroska.h:119
EbmlMaster::containing_master
int containing_master
-1 if no parent exists
Definition: matroskaenc.c:128
mkv_track::duration
int64_t duration
Definition: matroskaenc.c:195
MATROSKA_ID_AUDIOSAMPLINGFREQ
#define MATROSKA_ID_AUDIOSAMPLINGFREQ
Definition: matroska.h:169
AV_PKT_DATA_MASTERING_DISPLAY_METADATA
@ AV_PKT_DATA_MASTERING_DISPLAY_METADATA
Mastering display metadata (based on SMPTE-2086:2014).
Definition: packet.h:219
MatroskaMuxContext::cluster_bc
AVIOContext * cluster_bc
Definition: matroskaenc.c:222
OPUS_SEEK_PREROLL
#define OPUS_SEEK_PREROLL
Seek preroll value for opus.
Definition: matroskaenc.c:281
matrix
Definition: vc1dsp.c:43
AVMasteringDisplayMetadata::display_primaries
AVRational display_primaries[3][2]
CIE 1931 xy chromaticity coords of color primaries (r, g, b order).
Definition: mastering_display_metadata.h:42
EbmlElement
Definition: matroskaenc.c:131
MODE_MATROSKAv2
#define MODE_MATROSKAv2
Definition: matroskaenc.c:82
AVMasteringDisplayMetadata::has_luminance
int has_luminance
Flag indicating whether the luminance (min_ and max_) have been set.
Definition: mastering_display_metadata.h:67
ff_put_bmp_header
void ff_put_bmp_header(AVIOContext *pb, AVCodecParameters *par, int for_asf, int ignore_extradata, int rgb_frame_is_flipped)
Definition: riffenc.c:215
rational.h
MATROSKA_ID_DISCARDPADDING
#define MATROSKA_ID_DISCARDPADDING
Definition: matroska.h:250
AV_TIME_BASE_Q
#define AV_TIME_BASE_Q
Internal time base represented as fractional value.
Definition: avutil.h:264
MATROSKA_VIDEO_FIELDORDER_BB
@ MATROSKA_VIDEO_FIELDORDER_BB
Definition: matroska.h:307
int64_t
long long int64_t
Definition: coverity.c:34
ebml_writer_add_uint
static void ebml_writer_add_uint(EbmlWriter *writer, uint32_t id, uint64_t val)
Definition: matroskaenc.c:537
MATROSKA_ID_DURATION
#define MATROSKA_ID_DURATION
Definition: matroska.h:66
MATROSKA_ID_VIDEOCOLORCHROMASITINGVERT
#define MATROSKA_ID_VIDEOCOLORCHROMASITINGVERT
Definition: matroska.h:141
BlockContext::pkt
const AVPacket * pkt
Definition: matroskaenc.c:120
avlanguage.h
av_strcasecmp
int av_strcasecmp(const char *a, const char *b)
Locale-independent case-insensitive compare.
Definition: avstring.c:207
MATROSKA_ID_VIDEOCOLORPRIMARIES
#define MATROSKA_ID_VIDEOCOLORPRIMARIES
Definition: matroska.h:145
AV_CODEC_ID_RAWVIDEO
@ AV_CODEC_ID_RAWVIDEO
Definition: codec_id.h:65
av_unused
#define av_unused
Definition: attributes.h:131
MATROSKA_ID_SEGMENT
#define MATROSKA_ID_SEGMENT
Definition: matroska.h:52
AV_DISPOSITION_DEFAULT
#define AV_DISPOSITION_DEFAULT
The stream should be chosen by default among other streams of the same type, unless the user has expl...
Definition: avformat.h:621
AV_CODEC_ID_MPEG4
@ AV_CODEC_ID_MPEG4
Definition: codec_id.h:64
MATROSKA_ID_BLKADDIDTYPE
#define MATROSKA_ID_BLKADDIDTYPE
Definition: matroska.h:195
AVContentLightMetadata::MaxCLL
unsigned MaxCLL
Max content light level (cd/m^2).
Definition: mastering_display_metadata.h:111
MatroskaMuxContext::dash_track_number
int dash_track_number
Definition: matroskaenc.c:257
AV_CODEC_ID_RA_144
@ AV_CODEC_ID_RA_144
Definition: codec_id.h:431
ff_metadata_conv
void ff_metadata_conv(AVDictionary **pm, const AVMetadataConv *d_conv, const AVMetadataConv *s_conv)
Definition: metadata.c:26
ebml_writer_write
static int ebml_writer_write(EbmlWriter *writer, AVIOContext *pb)
Definition: matroskaenc.c:746
MATROSKA_ID_CHAPTERS
#define MATROSKA_ID_CHAPTERS
Definition: matroska.h:62
AVCOL_TRC_NB
@ AVCOL_TRC_NB
Not part of ABI.
Definition: pixfmt.h:633
tmp
static uint8_t tmp[11]
Definition: aes_ctr.c:28
ebml_writer_elem_write
static int ebml_writer_elem_write(const EbmlElement *elem, AVIOContext *pb)
Definition: matroskaenc.c:703
MATROSKA_ID_VIDEOCOLOR_BY
#define MATROSKA_ID_VIDEOCOLOR_BY
Definition: matroska.h:155
pixdesc.h
EbmlElement::priv
union EbmlElement::@399 priv
AVPacketSideData
This structure stores auxiliary information for decoding, presenting, or otherwise processing the cod...
Definition: packet.h:390
MATROSKA_ID_BLOCKDURATION
#define MATROSKA_ID_BLOCKDURATION
Definition: matroska.h:247
MATROSKA_ID_VIDEOCOLORRANGE
#define MATROSKA_ID_VIDEOCOLORRANGE
Definition: matroska.h:142
MATROSKA_ID_BLOCK
#define MATROSKA_ID_BLOCK
Definition: matroska.h:246
av_dynamic_hdr_plus_to_t35
int av_dynamic_hdr_plus_to_t35(const AVDynamicHDRPlus *s, uint8_t **data, size_t *size)
Serialize dynamic HDR10+ metadata to a user data registered ITU-T T.35 buffer, excluding the first 48...
Definition: hdr_dynamic_metadata.c:239
AVPacket::data
uint8_t * data
Definition: packet.h:539
MATROSKA_ID_TRACKDEFAULTDURATION
#define MATROSKA_ID_TRACKDEFAULTDURATION
Definition: matroska.h:108
vorbiscomment.h
targets
FFmpeg currently uses a custom build this text attempts to document some of its obscure features and options Makefile the full command issued by make and its output will be shown on the screen DBG Preprocess x86 external assembler files to a dbg asm file in the object which then gets compiled Helps in developing those assembler files DESTDIR Destination directory for the install targets
Definition: build_system.txt:16
av_const
#define av_const
Definition: attributes.h:84
put_xiph_size
static void put_xiph_size(AVIOContext *pb, int size)
Definition: matroskaenc.c:840
AVOption
AVOption.
Definition: opt.h:429
AVCOL_SPC_NB
@ AVCOL_SPC_NB
Not part of ABI.
Definition: pixfmt.h:660
AVCOL_TRC_UNSPECIFIED
@ AVCOL_TRC_UNSPECIFIED
Definition: pixfmt.h:614
MatroskaMuxContext::mode
int mode
Definition: matroskaenc.c:217
AVStream::avg_frame_rate
AVRational avg_frame_rate
Average framerate.
Definition: avformat.h:837
mkv_track::duration_offset
int64_t duration_offset
Definition: matroskaenc.c:196
data
const char data[16]
Definition: mxf.c:149
MATROSKA_VIDEO_INTERLACE_FLAG_INTERLACED
@ MATROSKA_VIDEO_INTERLACE_FLAG_INTERLACED
Definition: matroska.h:299
MatroskaMuxContext::cluster_pts
int64_t cluster_pts
Definition: matroskaenc.c:224
mkv_write_attachments
static int mkv_write_attachments(AVFormatContext *s)
Definition: matroskaenc.c:2443
AV_CODEC_ID_ALAC
@ AV_CODEC_ID_ALAC
Definition: codec_id.h:462
MATROSKA_ID_DATEUTC
#define MATROSKA_ID_DATEUTC
Definition: matroska.h:70
ebml_id_size
static int ebml_id_size(uint32_t id)
Definition: matroskaenc.c:283
flacenc.h
AVIOContext::error
int error
contains the error code or 0 if no error happened
Definition: avio.h:239
MatroskaMuxContext::tags
ebml_stored_master tags
Definition: matroskaenc.c:220
EBML_UID
@ EBML_UID
Definition: matroskaenc.c:110
matroska.h
ff_parse_creation_time_metadata
int ff_parse_creation_time_metadata(AVFormatContext *s, int64_t *timestamp, int return_seconds)
Parse creation_time in AVFormatContext metadata if exists and warn if the parsing fails.
Definition: mux_utils.c:138
ff_codec_wav_tags
const AVCodecTag ff_codec_wav_tags[]
Definition: riff.c:530
MATROSKA_ID_VIDEOPIXELCROPT
#define MATROSKA_ID_VIDEOPIXELCROPT
Definition: matroska.h:122
mkv_track::ts_offset
int64_t ts_offset
Definition: matroskaenc.c:201
MATROSKA_ID_VIDEOPIXELCROPB
#define MATROSKA_ID_VIDEOPIXELCROPB
Definition: matroska.h:121
put_ebml_binary
static void put_ebml_binary(AVIOContext *pb, uint32_t elementid, const void *buf, int size)
Definition: matroskaenc.c:393
AVPacket::duration
int64_t duration
Duration of this packet in AVStream->time_base units, 0 if unknown.
Definition: packet.h:557
AVCodecParameters::codec_tag
uint32_t codec_tag
Additional information about the codec (corresponds to the AVI FOURCC).
Definition: codec_par.h:59
AV_SPHERICAL_EQUIRECTANGULAR_TILE
@ AV_SPHERICAL_EQUIRECTANGULAR_TILE
Video represents a portion of a sphere mapped on a flat surface using equirectangular projection.
Definition: spherical.h:68
MAX_VIDEO_COLOR_ELEMS
#define MAX_VIDEO_COLOR_ELEMS
Definition: matroskaenc.c:1334
max
#define max(a, b)
Definition: cuda_runtime.h:33
BlockContext
Definition: matroskaenc.c:118
mathematics.h
MATROSKA_ID_CUES
#define MATROSKA_ID_CUES
Definition: matroska.h:57
AVDictionary
Definition: dict.c:34
AV_CODEC_ID_FLAC
@ AV_CODEC_ID_FLAC
Definition: codec_id.h:458
AVChannelLayout::order
enum AVChannelOrder order
Channel order used in this layout.
Definition: channel_layout.h:322
FFMAX
#define FFMAX(a, b)
Definition: macros.h:47
MATROSKA_ID_CUETIME
#define MATROSKA_ID_CUETIME
Definition: matroska.h:202
IS_WEBM
#define IS_WEBM(mkv)
Definition: matroskaenc.c:85
AV_PROFILE_ARIB_PROFILE_C
#define AV_PROFILE_ARIB_PROFILE_C
Definition: defs.h:189
AVChannelLayout::mask
uint64_t mask
This member must be used for AV_CHANNEL_ORDER_NATIVE, and may be used for AV_CHANNEL_ORDER_AMBISONIC ...
Definition: channel_layout.h:349
WvHeader
Definition: wv.h:34
MATROSKA_ID_CUERELATIVEPOSITION
#define MATROSKA_ID_CUERELATIVEPOSITION
Definition: matroska.h:208
AVChannelLayout::nb_channels
int nb_channels
Number of channels in this layout.
Definition: channel_layout.h:327
MAX_PCE_SIZE
#define MAX_PCE_SIZE
Maximum size of a PCE including the 3-bit ID_PCE.
Definition: mpeg4audio.h:118
ff_flac_is_native_layout
int ff_flac_is_native_layout(uint64_t channel_layout)
Definition: flacenc_header.c:50
AV_CODEC_ID_HDMV_PGS_SUBTITLE
@ AV_CODEC_ID_HDMV_PGS_SUBTITLE
Definition: codec_id.h:562
bit_depth
static void bit_depth(AudioStatsContext *s, const uint64_t *const mask, uint8_t *depth)
Definition: af_astats.c:246
AV_SPHERICAL_EQUIRECTANGULAR
@ AV_SPHERICAL_EQUIRECTANGULAR
Video represents a sphere mapped on a flat surface using equirectangular projection.
Definition: spherical.h:52
intfloat.h
codec_type
enum AVMediaType codec_type
Definition: rtp.c:37
MatroskaMuxContext::flipped_raw_rgb
int flipped_raw_rgb
Definition: matroskaenc.c:259
MATROSKA_ID_CHAPLANG
#define MATROSKA_ID_CHAPLANG
Definition: matroska.h:267
AV_CODEC_ID_TRUEHD
@ AV_CODEC_ID_TRUEHD
Definition: codec_id.h:490
MATROSKA_ID_CUEDURATION
#define MATROSKA_ID_CUEDURATION
Definition: matroska.h:209
avio_get_dyn_buf
int avio_get_dyn_buf(AVIOContext *s, uint8_t **pbuffer)
Return the written size and a pointer to the buffer.
Definition: aviobuf.c:1374
AV_PKT_FLAG_KEY
#define AV_PKT_FLAG_KEY
The packet contains a keyframe.
Definition: packet.h:594
AV_WB64
#define AV_WB64(p, v)
Definition: intreadwrite.h:429
FFOutputFormat::p
AVOutputFormat p
The public AVOutputFormat.
Definition: mux.h:65
MatroskaMuxContext::cues_pos
int64_t cues_pos
Definition: matroskaenc.c:230
AV_FIELD_BT
@ AV_FIELD_BT
Bottom coded first, top displayed first.
Definition: defs.h:206
av_get_random_seed
uint32_t av_get_random_seed(void)
Get a seed to use in conjunction with random functions.
Definition: random_seed.c:167
xiph.h
MatroskaMuxContext::cluster_size_limit
int cluster_size_limit
Definition: matroskaenc.c:251
MATROSKA_VIDEO_DISPLAYUNIT_UNKNOWN
@ MATROSKA_VIDEO_DISPLAYUNIT_UNKNOWN
Definition: matroska.h:336
mkv_track::codecpriv_offset
int codecpriv_offset
Definition: matroskaenc.c:199
AVContentLightMetadata
Content light level needed by to transmit HDR over HDMI (CTA-861.3).
Definition: mastering_display_metadata.h:107
MATROSKA_ID_VIDEOCOLOR_LUMINANCEMAX
#define MATROSKA_ID_VIDEOCOLOR_LUMINANCEMAX
Definition: matroska.h:158
AV_PKT_DATA_DOVI_CONF
@ AV_PKT_DATA_DOVI_CONF
DOVI configuration ref: dolby-vision-bitstreams-within-the-iso-base-media-file-format-v2....
Definition: packet.h:280
MPEG4AudioConfig
Definition: mpeg4audio.h:29
crc.h
avio_wl16
void avio_wl16(AVIOContext *s, unsigned int val)
Definition: aviobuf.c:437
AVCodecParameters::color_primaries
enum AVColorPrimaries color_primaries
Definition: codec_par.h:167
avio_write_marker
void avio_write_marker(AVIOContext *s, int64_t time, enum AVIODataMarkerType type)
Mark the written bytestream as a specific type.
Definition: aviobuf.c:461
MATROSKA_ID_VIDEOCOLOR_WHITEY
#define MATROSKA_ID_VIDEOCOLOR_WHITEY
Definition: matroska.h:157
NOTHING
#define NOTHING(STEREOMODETYPE, WDIV, HDIV, WEBM)
AVPacketSideData::size
size_t size
Definition: packet.h:392
AV_PROFILE_ARIB_PROFILE_A
#define AV_PROFILE_ARIB_PROFILE_A
Definition: defs.h:188
HDIV1
#define HDIV1(STEREOMODETYPE, STEREO3DTYPE, FLAGS, WDIV, HDIV, WEBM)
start_ebml_master
static ebml_master start_ebml_master(AVIOContext *pb, uint32_t elementid, uint64_t expectedsize)
Definition: matroskaenc.c:431
AV_FIELD_TT
@ AV_FIELD_TT
Top coded_first, top displayed first.
Definition: defs.h:203
DVCC_DVVC_BLOCK_TYPE_NAME
#define DVCC_DVVC_BLOCK_TYPE_NAME
Definition: matroska.h:439
AV_CODEC_ID_ASS
@ AV_CODEC_ID_ASS
Definition: codec_id.h:578
MATROSKA_ID_AUDIOOUTSAMPLINGFREQ
#define MATROSKA_ID_AUDIOOUTSAMPLINGFREQ
Definition: matroska.h:170
MAX_SUPPORTED_EBML_LENGTH
#define MAX_SUPPORTED_EBML_LENGTH
Definition: matroskaenc.c:80
avpriv_set_pts_info
void avpriv_set_pts_info(AVStream *st, int pts_wrap_bits, unsigned int pts_num, unsigned int pts_den)
Set the time base and wrapping info for a given stream.
Definition: avformat.c:867
mpeg4audio.h
MATROSKA_ID_VIDEOPROJECTIONPRIVATE
#define MATROSKA_ID_VIDEOPROJECTIONPRIVATE
Definition: matroska.h:163
ffstream
static av_always_inline FFStream * ffstream(AVStream *st)
Definition: internal.h:358
AV_CODEC_ID_PCM_S16BE
@ AV_CODEC_ID_PCM_S16BE
Definition: codec_id.h:335
mkv_cues
Definition: matroskaenc.c:178
MatroskaMuxContext::move_cues_to_front
int move_cues_to_front
Definition: matroskaenc.c:261
fail
#define fail()
Definition: checkasm.h:193
AVCodecParameters::bits_per_raw_sample
int bits_per_raw_sample
This is the number of valid bits in each output sample.
Definition: codec_par.h:123
ebml_writer_sint_len
static int ebml_writer_sint_len(EbmlElement *elem)
Definition: matroskaenc.c:588
EbmlElement::sint
int64_t sint
Definition: matroskaenc.c:138
MATROSKA_ID_CHAPTERDISPLAY
#define MATROSKA_ID_CHAPTERDISPLAY
Definition: matroska.h:265
MATROSKA_ID_TRACKUID
#define MATROSKA_ID_TRACKUID
Definition: matroska.h:78
samplefmt.h
EBML_ID_DOCTYPEVERSION
#define EBML_ID_DOCTYPEVERSION
Definition: matroska.h:40
AVCOL_RANGE_NB
@ AVCOL_RANGE_NB
Not part of ABI.
Definition: pixfmt.h:718
ff_vorbiscomment_write
int ff_vorbiscomment_write(AVIOContext *pb, const AVDictionary *m, const char *vendor_string, AVChapter **chapters, unsigned int nb_chapters)
Write a VorbisComment into an AVIOContext.
Definition: vorbiscomment.c:65
put_ebml_uint
static void put_ebml_uint(AVIOContext *pb, uint32_t elementid, uint64_t val)
Definition: matroskaenc.c:373
avio_tell
static av_always_inline int64_t avio_tell(AVIOContext *s)
ftell() equivalent for AVIOContext.
Definition: avio.h:494
ff_matroska_video_stereo_mode
const char *const ff_matroska_video_stereo_mode[MATROSKA_VIDEO_STEREOMODE_TYPE_NB]
Definition: matroska.c:130
AVChapter
Definition: avformat.h:1259
AV_DISPOSITION_FORCED
#define AV_DISPOSITION_FORCED
Track should be used during playback by default.
Definition: avformat.h:654
val
static double val(void *priv, double ch)
Definition: aeval.c:77
MATROSKA_BLOCK_ADD_ID_TYPE_ITU_T_T35
@ MATROSKA_BLOCK_ADD_ID_TYPE_ITU_T_T35
Definition: matroska.h:363
type
it s the only field you need to keep assuming you have a context There is some magic you don t need to care about around this just let it vf type
Definition: writing_filters.txt:86
MATROSKA_ID_VIDEOALPHAMODE
#define MATROSKA_ID_VIDEOALPHAMODE
Definition: matroska.h:129
pts
static int64_t pts
Definition: transcode_aac.c:644
us
#define us(width, name, range_min, range_max, subs,...)
Definition: cbs_h2645.c:263
EBML_ID_DOCTYPE
#define EBML_ID_DOCTYPE
Definition: matroska.h:39
av_reduce
int av_reduce(int *dst_num, int *dst_den, int64_t num, int64_t den, int64_t max)
Reduce a fraction.
Definition: rational.c:35
MATROSKA_ID_VIDEOCOLOR_WHITEX
#define MATROSKA_ID_VIDEOCOLOR_WHITEX
Definition: matroska.h:156
AVRational::num
int num
Numerator.
Definition: rational.h:59
AV_FIELD_TB
@ AV_FIELD_TB
Top coded first, bottom displayed first.
Definition: defs.h:205
MATROSKA_TRACK_TYPE_METADATA
@ MATROSKA_TRACK_TYPE_METADATA
Definition: matroska.h:287
AV_CODEC_ID_ATRAC3
@ AV_CODEC_ID_ATRAC3
Definition: codec_id.h:477
mkv_track::max_blockaddid
uint64_t max_blockaddid
Definition: matroskaenc.c:197
MATROSKA_VIDEO_FIELDORDER_TT
@ MATROSKA_VIDEO_FIELDORDER_TT
Definition: matroska.h:305
AV_PKT_DATA_WEBVTT_SETTINGS
@ AV_PKT_DATA_WEBVTT_SETTINGS
The optional settings (rendering instructions) that immediately follow the timestamp specifier of a W...
Definition: packet.h:199
AV_CODEC_ID_DVB_SUBTITLE
@ AV_CODEC_ID_DVB_SUBTITLE
Definition: codec_id.h:557
MatroskaVideoStereoModeType
MatroskaVideoStereoModeType
Definition: matroska.h:312
av_get_bits_per_sample
int av_get_bits_per_sample(enum AVCodecID codec_id)
Return codec bits per sample.
Definition: utils.c:550
AV_CODEC_ID_SIPR
@ AV_CODEC_ID_SIPR
Definition: codec_id.h:487
AVCodecParameters::color_trc
enum AVColorTransferCharacteristic color_trc
Definition: codec_par.h:168
MATROSKA_ID_BLKADDIDNAME
#define MATROSKA_ID_BLKADDIDNAME
Definition: matroska.h:194
mkv_write_tracks
static int mkv_write_tracks(AVFormatContext *s)
Definition: matroskaenc.c:2124
MatroskaMuxContext::ctx
AVFormatContext * ctx
Definition: matroskaenc.c:215
mkv_seekhead_entry
Definition: matroskaenc.c:158
MATROSKA_ID_BLOCKADDITIONAL
#define MATROSKA_ID_BLOCKADDITIONAL
Definition: matroska.h:242
pkt
AVPacket * pkt
Definition: movenc.c:60
AV_LOG_ERROR
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition: log.h:209
FF_ARRAY_ELEMS
#define FF_ARRAY_ELEMS(a)
Definition: sinewin_tablegen.c:29
EBML_ID_VOID
#define EBML_ID_VOID
Definition: matroska.h:44
MATROSKA_ID_VIDEOFIELDORDER
#define MATROSKA_ID_VIDEOFIELDORDER
Definition: matroska.h:127
AVCodecTag
Definition: internal.h:42
MATROSKA_ID_VIDEOPIXELCROPR
#define MATROSKA_ID_VIDEOPIXELCROPR
Definition: matroska.h:124
MATROSKA_ID_TAGS
#define MATROSKA_ID_TAGS
Definition: matroska.h:58
AV_CODEC_ID_TTA
@ AV_CODEC_ID_TTA
Definition: codec_id.h:468
options
static const AVOption options[]
Definition: matroskaenc.c:3539
duration
int64_t duration
Definition: movenc.c:65
put_ebml_id
static void put_ebml_id(AVIOContext *pb, uint32_t id)
Definition: matroskaenc.c:288
AV_FIELD_UNKNOWN
@ AV_FIELD_UNKNOWN
Definition: defs.h:201
EBML_ID_EBMLMAXIDLENGTH
#define EBML_ID_EBMLMAXIDLENGTH
Definition: matroska.h:37
av_dict_get
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:62
avio_open_dyn_buf
int avio_open_dyn_buf(AVIOContext **s)
Open a write only memory stream.
Definition: aviobuf.c:1362
mkv_cuepoint::relative_pos
int64_t relative_pos
relative offset from the position of the cluster containing the block
Definition: matroskaenc.c:174
mkv_update_codecprivate
static int mkv_update_codecprivate(AVFormatContext *s, MatroskaMuxContext *mkv, uint8_t *side_data, int side_data_size, AVCodecParameters *par, AVIOContext *pb, mkv_track *track, unsigned alternative_size)
Definition: matroskaenc.c:1297
AV_CODEC_ID_ADPCM_G726
@ AV_CODEC_ID_ADPCM_G726
Definition: codec_id.h:384
avpriv_mpeg4audio_get_config2
int avpriv_mpeg4audio_get_config2(MPEG4AudioConfig *c, const uint8_t *buf, int size, int sync_extension, void *logctx)
Parse MPEG-4 systems extradata from a raw buffer to retrieve audio configuration.
Definition: mpeg4audio.c:165
ebml_writer_block_len
static int ebml_writer_block_len(EbmlElement *elem)
Definition: matroskaenc.c:623
AVCodecDescriptor
This struct describes the properties of a single codec described by an AVCodecID.
Definition: codec_desc.h:38
stereo3d.h
AVMasteringDisplayMetadata::white_point
AVRational white_point[2]
CIE 1931 xy chromaticity coords of white point.
Definition: mastering_display_metadata.h:47
intreadwrite.h
end_ebml_master
static void end_ebml_master(AVIOContext *pb, ebml_master master)
Definition: matroskaenc.c:441
MATROSKA_ID_FILEUID
#define MATROSKA_ID_FILEUID
Definition: matroska.h:258
s
#define s(width, name)
Definition: cbs_vp9.c:198
AVCHROMA_LOC_TOP
@ AVCHROMA_LOC_TOP
Definition: pixfmt.h:741
MATROSKA_VIDEO_INTERLACE_FLAG_PROGRESSIVE
@ MATROSKA_VIDEO_INTERLACE_FLAG_PROGRESSIVE
Definition: matroska.h:300
EbmlElement::bin
const uint8_t * bin
Definition: matroskaenc.c:141
av_chroma_location_enum_to_pos
int av_chroma_location_enum_to_pos(int *xpos, int *ypos, enum AVChromaLocation pos)
Converts AVChromaLocation to swscale x/y chroma position.
Definition: pixdesc.c:3588
NALUList::nalus
NALU * nalus
Definition: evc.c:74
AVCOL_PRI_NB
@ AVCOL_PRI_NB
Not part of ABI.
Definition: pixfmt.h:604
AV_PIX_FMT_YUVA420P
@ AV_PIX_FMT_YUVA420P
planar YUV 4:2:0, 20bpp, (1 Cr & Cb sample per 2x2 Y & A samples)
Definition: pixfmt.h:108
mkv_track::write_dts
int write_dts
Definition: matroskaenc.c:186
CodecTags::str
char str[22]
Definition: matroska.h:376
av_lfg_get
static unsigned int av_lfg_get(AVLFG *c)
Get the next random unsigned 32-bit number using an ALFG.
Definition: lfg.h:53
MATROSKA_ID_VIDEODISPLAYWIDTH
#define MATROSKA_ID_VIDEODISPLAYWIDTH
Definition: matroska.h:117
av_realloc_array
void * av_realloc_array(void *ptr, size_t nmemb, size_t size)
Definition: mem.c:217
format
Filter the word “frame” indicates either a video frame or a group of audio as stored in an AVFrame structure Format for each input and each output the list of supported formats For video that means pixel format For audio that means channel sample format(the sample packing is implied by the sample format) and sample rate. The lists are not just lists
mkv_write_flush_packet
static int mkv_write_flush_packet(AVFormatContext *s, AVPacket *pkt)
Definition: matroskaenc.c:3140
ebml_writer_add_block
static void ebml_writer_add_block(EbmlWriter *writer, MatroskaMuxContext *mkv)
Definition: matroskaenc.c:551
MATROSKA_VIDEO_FIELDORDER_BT
@ MATROSKA_VIDEO_FIELDORDER_BT
Definition: matroska.h:309
MatroskaMuxContext::cluster_pos
int64_t cluster_pos
file offset of the current Cluster
Definition: matroskaenc.c:223
AVDictionaryEntry::key
char * key
Definition: dict.h:90
MATROSKA_ID_TAGNAME
#define MATROSKA_ID_TAGNAME
Definition: matroska.h:215
AVSphericalMapping::bound_top
uint32_t bound_top
Distance from the top edge.
Definition: spherical.h:180
AVMEDIA_TYPE_AUDIO
@ AVMEDIA_TYPE_AUDIO
Definition: avutil.h:202
AV_CODEC_ID_VP9
@ AV_CODEC_ID_VP9
Definition: codec_id.h:222
AVCodecParameters::width
int width
Video only.
Definition: codec_par.h:134
ebml_writer_open_master
static void ebml_writer_open_master(EbmlWriter *writer, uint32_t id)
Definition: matroskaenc.c:459
AVChannelLayout::u
union AVChannelLayout::@428 u
Details about which channels are present in this layout.
MATROSKA_ID_TAG
#define MATROSKA_ID_TAG
Definition: matroska.h:213
av_q2d
static double av_q2d(AVRational a)
Convert an AVRational to a double.
Definition: rational.h:104
ebml_writer_add_uid
static void ebml_writer_add_uid(EbmlWriter *writer, uint32_t id, uint64_t val)
Definition: matroskaenc.c:530
MATROSKA_ID_TIMECODESCALE
#define MATROSKA_ID_TIMECODESCALE
Definition: matroska.h:65
lfg.h
MatroskaMuxContext::tmp_bc
AVIOContext * tmp_bc
Definition: matroskaenc.c:240
get_mimetype
static const char * get_mimetype(const AVStream *st)
Definition: matroskaenc.c:2426
ebml_writer_add_sint
static void ebml_writer_add_sint(EbmlWriter *writer, uint32_t id, int64_t val)
Definition: matroskaenc.c:544
MatroskaMuxContext::write_crc
int write_crc
Definition: matroskaenc.c:253
matroska_webm_class
static const AVClass matroska_webm_class
Definition: matroskaenc.c:3557
AV_OPT_TYPE_INT64
@ AV_OPT_TYPE_INT64
Underlying C type is int64_t.
Definition: opt.h:263
av_assert0
#define av_assert0(cond)
assert() equivalent, that is always enabled.
Definition: avassert.h:40
MATROSKA_ID_CUETRACKPOSITION
#define MATROSKA_ID_CUETRACKPOSITION
Definition: matroska.h:203
additional_audio_tags
static const AVCodecTag additional_audio_tags[]
Definition: matroskaenc.c:3514
MATROSKA_ID_SEEKENTRY
#define MATROSKA_ID_SEEKENTRY
Definition: matroska.h:228
ff_isom_put_dvcc_dvvc
void ff_isom_put_dvcc_dvvc(void *logctx, uint8_t out[ISOM_DVCC_DVVC_SIZE], const AVDOVIDecoderConfigurationRecord *dovi)
Definition: dovi_isom.c:89
mkv_track::track_num
unsigned track_num
Definition: matroskaenc.c:189
AV_LOG_DEBUG
#define AV_LOG_DEBUG
Stuff which is only useful for libav* developers.
Definition: log.h:230
MATROSKA_ID_TRACKTYPE
#define MATROSKA_ID_TRACKTYPE
Definition: matroska.h:79
AVPacketSideData::data
uint8_t * data
Definition: packet.h:391
ebml_writer_close_master
static void ebml_writer_close_master(EbmlWriter *writer)
Definition: matroskaenc.c:470
AVDOVIDecoderConfigurationRecord::dv_profile
uint8_t dv_profile
Definition: dovi_meta.h:58
MATROSKA_ID_SEGMENTUID
#define MATROSKA_ID_SEGMENTUID
Definition: matroska.h:71
EbmlType
EbmlType
Definition: matroskadec.c:89
MATROSKA_ID_TRACKBLKADDMAPPING
#define MATROSKA_ID_TRACKBLKADDMAPPING
Definition: matroska.h:113
AV_PKT_DATA_STEREO3D
@ AV_PKT_DATA_STEREO3D
This side data should be associated with a video stream and contains Stereoscopic 3D information in f...
Definition: packet.h:111
av_rescale_q
int64_t av_rescale_q(int64_t a, AVRational bq, AVRational cq)
Rescale a 64-bit integer by 2 rational numbers.
Definition: mathematics.c:142
sint_size
static av_const int sint_size(int64_t val)
Definition: matroskaenc.c:582
DEFAULT_MODE_PASSTHROUGH
@ DEFAULT_MODE_PASSTHROUGH
Definition: matroskaenc.c:93
MatroskaMuxContext::cluster_time_limit
int64_t cluster_time_limit
Definition: matroskaenc.c:252
EbmlElement::type
EbmlType type
Definition: matroskaenc.c:133
EbmlElement::f
double f
Definition: matroskaenc.c:139
MATROSKA_ID_INFO
#define MATROSKA_ID_INFO
Definition: matroska.h:55
MatroskaMuxContext::have_video
int have_video
Definition: matroskaenc.c:245
MATROSKA_ID_AUDIOCHANNELS
#define MATROSKA_ID_AUDIOCHANNELS
Definition: matroska.h:173
codec_id
enum AVCodecID codec_id
Definition: vaapi_decode.c:410
MATROSKA_ID_BLKADDIDVALUE
#define MATROSKA_ID_BLKADDIDVALUE
Definition: matroska.h:193
AV_CODEC_ID_SVQ3
@ AV_CODEC_ID_SVQ3
Definition: codec_id.h:75
EbmlType
EbmlType
Definition: matroskaenc.c:106
key
const char * key
Definition: hwcontext_opencl.c:189
AVCodecParameters::nb_coded_side_data
int nb_coded_side_data
Amount of entries in coded_side_data.
Definition: codec_par.h:86
AVCOL_PRI_UNSPECIFIED
@ AVCOL_PRI_UNSPECIFIED
Definition: pixfmt.h:589
ff_format_shift_data
int ff_format_shift_data(AVFormatContext *s, int64_t read_start, int shift_size)
Make shift_size amount of space at read_start by shifting data in the output at read_start until the ...
Definition: mux_utils.c:72
AV_CODEC_ID_H264
@ AV_CODEC_ID_H264
Definition: codec_id.h:79
MATROSKA_ID_VIDEOSTEREOMODE
#define MATROSKA_ID_VIDEOSTEREOMODE
Definition: matroska.h:128
mkv_start_seekhead
static void mkv_start_seekhead(MatroskaMuxContext *mkv, AVIOContext *pb)
Initialize the SeekHead element to be ready to index level 1 Matroska elements.
Definition: matroskaenc.c:869
ff_webm_codec_tags
const CodecTags ff_webm_codec_tags[]
Definition: matroska.c:108
mkv_track::uid
uint64_t uid
Definition: matroskaenc.c:188
HDIV2
#define HDIV2(STEREOMODETYPE, WDIV, HDIV, WEBM)
AV_CODEC_ID_ARIB_CAPTION
@ AV_CODEC_ID_ARIB_CAPTION
Definition: codec_id.h:581
AVStereo3D::flags
int flags
Additional information about the frame packing.
Definition: stereo3d.h:212
MATROSKA_ID_VIDEOCOLORSPACE
#define MATROSKA_ID_VIDEOCOLORSPACE
Definition: matroska.h:131
if
if(ret)
Definition: filter_design.txt:179
MATROSKA_ID_TRACKNAME
#define MATROSKA_ID_TRACKNAME
Definition: matroska.h:95
FFFormatContext
Definition: internal.h:64
BlockContext::track
struct mkv_track * track
Definition: matroskaenc.c:119
AV_CODEC_ID_WEBVTT
@ AV_CODEC_ID_WEBVTT
Definition: codec_id.h:574
EBML_ID_DOCTYPEREADVERSION
#define EBML_ID_DOCTYPEREADVERSION
Definition: matroska.h:41
mkv_cues::entries
mkv_cuepoint * entries
Definition: matroskaenc.c:179
AVFormatContext
Format I/O context.
Definition: avformat.h:1300
internal.h
MATROSKA_ID_TRACKFLAGHEARINGIMPAIRED
#define MATROSKA_ID_TRACKFLAGHEARINGIMPAIRED
Definition: matroska.h:100
AVStream::codecpar
AVCodecParameters * codecpar
Codec parameters associated with this stream.
Definition: avformat.h:771
AV_LANG_ISO639_2_BIBL
@ AV_LANG_ISO639_2_BIBL
Definition: avlanguage.h:28
LIBAVUTIL_VERSION_INT
#define LIBAVUTIL_VERSION_INT
Definition: version.h:85
MATROSKA_ID_BLOCKGROUP
#define MATROSKA_ID_BLOCKGROUP
Definition: matroska.h:238
MATROSKA_ID_VIDEOCOLOR_LUMINANCEMIN
#define MATROSKA_ID_VIDEOCOLOR_LUMINANCEMIN
Definition: matroska.h:159
AVClass
Describe the class of an AVClass context structure.
Definition: log.h:75
EbmlWriter
Definition: matroskaenc.c:147
mkv_assemble_codecprivate
static int mkv_assemble_codecprivate(AVFormatContext *s, AVIOContext *dyn_cp, AVCodecParameters *par, const uint8_t *extradata, int extradata_size, int native_id, int qt_id, uint8_t **codecpriv, int *codecpriv_size, unsigned *max_payload_size)
Definition: matroskaenc.c:1193
AVStream::time_base
AVRational time_base
This is the fundamental unit of time (in seconds) in terms of which frame timestamps are represented.
Definition: avformat.h:787
NULL
#define NULL
Definition: coverity.c:32
MATROSKA_ID_ATTACHMENTS
#define MATROSKA_ID_ATTACHMENTS
Definition: matroska.h:60
STEREOMODE_STEREO3D_MAPPING
#define STEREOMODE_STEREO3D_MAPPING(MAP, MKV_ONLY)
Definition: matroska.h:401
ff_put_wav_header
int ff_put_wav_header(AVFormatContext *s, AVIOContext *pb, AVCodecParameters *par, int flags)
Write WAVEFORMAT header structure.
Definition: riffenc.c:54
AVERROR_PATCHWELCOME
#define AVERROR_PATCHWELCOME
Not yet implemented in FFmpeg, patches welcome.
Definition: error.h:64
MATROSKA_ID_CHAPTERATOM
#define MATROSKA_ID_CHAPTERATOM
Definition: matroska.h:262
AV_CODEC_ID_AV1
@ AV_CODEC_ID_AV1
Definition: codec_id.h:284
MATROSKA_TRACK_TYPE_AUDIO
@ MATROSKA_TRACK_TYPE_AUDIO
Definition: matroska.h:281
ebml_length_size
static int ebml_length_size(uint64_t length)
Calculate how many bytes are needed to represent the length field of an EBML element whose payload ha...
Definition: matroskaenc.c:326
STEREOMODE
#define STEREOMODE(STEREOMODETYPE, STEREO3DTYPE, FLAGS, WDIV, HDIV, WEBM)
isom.h
MATROSKA_ID_TRACKFLAGORIGINAL
#define MATROSKA_ID_TRACKFLAGORIGINAL
Definition: matroska.h:103
MATROSKA_VIDEO_DISPLAYUNIT_DAR
@ MATROSKA_VIDEO_DISPLAYUNIT_DAR
Definition: matroska.h:335
mkv_track::default_duration_high
uint64_t default_duration_high
Definition: matroskaenc.c:203
AVRational
Rational number (pair of numerator and denominator).
Definition: rational.h:58
MATROSKA_ID_WRITINGAPP
#define MATROSKA_ID_WRITINGAPP
Definition: matroska.h:68
WV_HEADER_SIZE
#define WV_HEADER_SIZE
Definition: wavpack.h:33
MatroskaMuxContext::info
ebml_stored_master info
Definition: matroskaenc.c:218
AV_DISPOSITION_COMMENT
#define AV_DISPOSITION_COMMENT
The stream is a commentary track.
Definition: avformat.h:639
MATROSKA_ID_VIDEOCOLOR_GY
#define MATROSKA_ID_VIDEOCOLOR_GY
Definition: matroska.h:153
AV_CODEC_ID_CINEPAK
@ AV_CODEC_ID_CINEPAK
Definition: codec_id.h:95
AV_CODEC_ID_DVD_SUBTITLE
@ AV_CODEC_ID_DVD_SUBTITLE
Definition: codec_id.h:556
MAX_VIDEO_PROJECTION_ELEMS
#define MAX_VIDEO_PROJECTION_ELEMS
Definition: matroskaenc.c:1417
av_default_item_name
const char * av_default_item_name(void *ptr)
Return the context name.
Definition: log.c:237
avc.h
parseutils.h
DEFAULT_MODE_INFER
@ DEFAULT_MODE_INFER
Definition: matroskaenc.c:91
MATROSKA_ID_SIMPLETAG
#define MATROSKA_ID_SIMPLETAG
Definition: matroska.h:214
MATROSKA_ID_VIDEOPROJECTION
#define MATROSKA_ID_VIDEOPROJECTION
Definition: matroska.h:161
mkv_assemble_native_codecprivate
static int mkv_assemble_native_codecprivate(AVFormatContext *s, AVIOContext *dyn_cp, const AVCodecParameters *par, const uint8_t *extradata, int extradata_size, unsigned *size_to_reserve)
Definition: matroskaenc.c:1116
options
Definition: swscale.c:42
MatroskaMuxContext::segment_uid
uint32_t segment_uid[4]
Definition: matroskaenc.c:263
MatroskaMuxContext::cur_block
BlockContext cur_block
Definition: matroskaenc.c:232
put_xiph_codecpriv
static int put_xiph_codecpriv(AVFormatContext *s, AVIOContext *pb, const AVCodecParameters *par, const uint8_t *extradata, int extradata_size)
Definition: matroskaenc.c:1004
AVStream::metadata
AVDictionary * metadata
Definition: avformat.h:828
MATROSKA_ID_SEEKID
#define MATROSKA_ID_SEEKID
Definition: matroska.h:231
put_ebml_num
static void put_ebml_num(AVIOContext *pb, uint64_t num, int bytes)
Write a number as EBML variable length integer on bytes bytes.
Definition: matroskaenc.c:335
FFOutputFormat
Definition: mux.h:61
AV_DISPOSITION_METADATA
#define AV_DISPOSITION_METADATA
The subtitle stream contains time-aligned metadata that is not intended to be directly presented to t...
Definition: avformat.h:703
EBML_STR
@ EBML_STR
Definition: matroskaenc.c:111
double
double
Definition: af_crystalizer.c:132
av_parse_time
int av_parse_time(int64_t *timeval, const char *timestr, int duration)
Parse timestr and return in *time a corresponding number of microseconds.
Definition: parseutils.c:592
avio_w8
void avio_w8(AVIOContext *s, int b)
Definition: aviobuf.c:179
MATROSKA_ID_CHAPTERTIMESTART
#define MATROSKA_ID_CHAPTERTIMESTART
Definition: matroska.h:263
ff_codec_movvideo_tags
const AVCodecTag ff_codec_movvideo_tags[]
Definition: isom_tags.c:29
ffio_fill
void ffio_fill(AVIOContext *s, int b, int64_t count)
Definition: aviobuf.c:187
mkv_add_seekhead_entry
static void mkv_add_seekhead_entry(MatroskaMuxContext *mkv, uint32_t elementid, uint64_t filepos)
Definition: matroskaenc.c:756
AV_DISPOSITION_ORIGINAL
#define AV_DISPOSITION_ORIGINAL
The stream is in original language.
Definition: avformat.h:635
mkv_track::sample_rate_offset
int64_t sample_rate_offset
Definition: matroskaenc.c:193
AV_CODEC_ID_QDM2
@ AV_CODEC_ID_QDM2
Definition: codec_id.h:465
mkv_get_uid
static uint64_t mkv_get_uid(const mkv_track *tracks, int i, AVLFG *c)
Definition: matroskaenc.c:3363
MATROSKA_TRACK_TYPE_VIDEO
@ MATROSKA_TRACK_TYPE_VIDEO
Definition: matroska.h:280
ebml_writer_add
static EbmlElement * ebml_writer_add(EbmlWriter *writer, uint32_t id, EbmlType type)
Definition: matroskaenc.c:451
av_packet_ref
int av_packet_ref(AVPacket *dst, const AVPacket *src)
Setup a new reference to the data described by a given packet.
Definition: packet.c:437
get_metadata_duration
static int64_t get_metadata_duration(AVFormatContext *s)
Definition: matroskaenc.c:2493
AVCodecParameters::ch_layout
AVChannelLayout ch_layout
Audio only.
Definition: codec_par.h:180
mkv_track::has_cue
int has_cue
Definition: matroskaenc.c:187
MATROSKA_ID_FILEMIMETYPE
#define MATROSKA_ID_FILEMIMETYPE
Definition: matroska.h:256
MATROSKA_ID_VIDEODISPLAYHEIGHT
#define MATROSKA_ID_VIDEODISPLAYHEIGHT
Definition: matroska.h:118
WDIV1
#define WDIV1(STEREOMODETYPE, STEREO3DTYPE, FLAGS, WDIV, HDIV, WEBM)
EbmlWriter::elements
EbmlElement * elements
Definition: matroskaenc.c:150
ff_matroska_audio_muxer
const FFOutputFormat ff_matroska_audio_muxer
DURATION_STRING_LENGTH
#define DURATION_STRING_LENGTH
DURATION_STRING_LENGTH must be <= 112 or the containing simpletag will need more than one byte for it...
Definition: matroskaenc.c:275
AV_PKT_DATA_CONTENT_LIGHT_LEVEL
@ AV_PKT_DATA_CONTENT_LIGHT_LEVEL
Content light level (based on CTA-861.3).
Definition: packet.h:232
MATROSKA_ID_TRACKAUDIO
#define MATROSKA_ID_TRACKAUDIO
Definition: matroska.h:81
AVCOL_RANGE_UNSPECIFIED
@ AVCOL_RANGE_UNSPECIFIED
Definition: pixfmt.h:683
EbmlElement::str
const char * str
Definition: matroskaenc.c:140
ff_vorbiscomment_length
int64_t ff_vorbiscomment_length(const AVDictionary *m, const char *vendor_string, AVChapter **chapters, unsigned int nb_chapters)
Calculate the length in bytes of a VorbisComment.
Definition: vorbiscomment.c:41
c
Undefined Behavior In the C some operations are like signed integer dereferencing freed accessing outside allocated Undefined Behavior must not occur in a C it is not safe even if the output of undefined operations is unused The unsafety may seem nit picking but Optimizing compilers have in fact optimized code on the assumption that no undefined Behavior occurs Optimizing code based on wrong assumptions can and has in some cases lead to effects beyond the output of computations The signed integer overflow problem in speed critical code Code which is highly optimized and works with signed integers sometimes has the problem that often the output of the computation does not c
Definition: undefined.txt:32
MatroskaMuxContext::nb_attachments
unsigned nb_attachments
Definition: matroskaenc.c:244
AVCodecParameters::sample_rate
int sample_rate
Audio only.
Definition: codec_par.h:184
put_ebml_float
static void put_ebml_float(AVIOContext *pb, uint32_t elementid, double val)
Definition: matroskaenc.c:386
uint_size
static av_const int uint_size(uint64_t val)
Definition: matroskaenc.c:567
AVCodecID
AVCodecID
Identify the syntax and semantics of the bitstream.
Definition: codec_id.h:49
av_packet_side_data_get
const AVPacketSideData * av_packet_side_data_get(const AVPacketSideData *sd, int nb_sd, enum AVPacketSideDataType type)
Get side information from a side data array.
Definition: packet.c:656
MATROSKA_ID_VIDEOCOLORMAXCLL
#define MATROSKA_ID_VIDEOCOLORMAXCLL
Definition: matroska.h:146
AV_PKT_DATA_SPHERICAL
@ AV_PKT_DATA_SPHERICAL
This side data should be associated with a video stream and corresponds to the AVSphericalMapping str...
Definition: packet.h:225
MATROSKA_ID_TRACKENTRY
#define MATROSKA_ID_TRACKENTRY
Definition: matroska.h:74
ebml_stored_master
Definition: matroskaenc.c:101
WDIV2
#define WDIV2(STEREOMODETYPE, WDIV, HDIV, WEBM)
AVCodecParameters::extradata_size
int extradata_size
Size of the extradata content in bytes.
Definition: codec_par.h:73
AV_WB32
#define AV_WB32(p, v)
Definition: intreadwrite.h:415
ff_wv_parse_header
int ff_wv_parse_header(WvHeader *wv, const uint8_t *data)
Parse a WavPack block header.
Definition: wv.c:30
mkv_put_codecprivate
static void mkv_put_codecprivate(AVIOContext *pb, unsigned max_payload_size, const uint8_t *codecpriv, unsigned codecpriv_size)
Definition: matroskaenc.c:1268
AV_CODEC_ID_AAC
@ AV_CODEC_ID_AAC
Definition: codec_id.h:448
mkv_write_header
static int mkv_write_header(AVFormatContext *s)
Definition: matroskaenc.c:2592
mkv_track::default_duration_low
uint64_t default_duration_low
Definition: matroskaenc.c:202
MatroskaMuxContext
Definition: matroskaenc.c:213
mkv_cuepoint::duration
int64_t duration
duration of the block according to time base
Definition: matroskaenc.c:175
EbmlMaster::nb_elements
int nb_elements
-1 if not finished
Definition: matroskaenc.c:127
ebml_writer_add_bin
static void ebml_writer_add_bin(EbmlWriter *writer, uint32_t id, const uint8_t *data, size_t size)
Definition: matroskaenc.c:510
AV_DISPOSITION_CAPTIONS
#define AV_DISPOSITION_CAPTIONS
The subtitle stream contains captions, providing a transcription and possibly a translation of audio.
Definition: avformat.h:692
mkv_track::blockadditionmapping_offset
int64_t blockadditionmapping_offset
Definition: matroskaenc.c:198
MATROSKA_ID_AUDIOBITDEPTH
#define MATROSKA_ID_AUDIOBITDEPTH
Definition: matroska.h:172
AV_CODEC_ID_FFV1
@ AV_CODEC_ID_FFV1
Definition: codec_id.h:85
AVLFG
Context structure for the Lagged Fibonacci PRNG.
Definition: lfg.h:33
mkv_track::offset
unsigned offset
Definition: matroskaenc.c:192
MATROSKA_ID_TRACKFLAGDEFAULT
#define MATROSKA_ID_TRACKFLAGDEFAULT
Definition: matroska.h:98
AVIOContext
Bytestream IO Context.
Definition: avio.h:160
AV_SPHERICAL_CUBEMAP
@ AV_SPHERICAL_CUBEMAP
Video frame is split into 6 faces of a cube, and arranged on a 3x2 layout.
Definition: spherical.h:61
MATROSKA_ID_TRACKFLAGCOMMENTARY
#define MATROSKA_ID_TRACKFLAGCOMMENTARY
Definition: matroska.h:104
ffio_reset_dyn_buf
void ffio_reset_dyn_buf(AVIOContext *s)
Reset a dynamic buffer.
Definition: aviobuf.c:1396
AVMediaType
AVMediaType
Definition: avutil.h:199
mkv_write_stereo_mode
static int mkv_write_stereo_mode(AVFormatContext *s, EbmlWriter *writer, const AVCodecParameters *par, const AVStream *st, int is_webm, int *h_width, int *h_height)
Definition: matroskaenc.c:1597
MATROSKA_ID_TRACKFLAGLACING
#define MATROSKA_ID_TRACKFLAGLACING
Definition: matroska.h:105
AVPacket::size
int size
Definition: packet.h:540
NULL_IF_CONFIG_SMALL
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification.
Definition: internal.h:94
MATROSKA_ID_VIDEOCOLOR_GX
#define MATROSKA_ID_VIDEOCOLOR_GX
Definition: matroska.h:152
ff_codec_get_id
enum AVCodecID ff_codec_get_id(const AVCodecTag *tags, unsigned int tag)
Definition: utils.c:133
master
const char * master
Definition: vf_curves.c:130
FF