FFmpeg  4.3.7
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 "av1.h"
25 #include "avc.h"
26 #include "hevc.h"
27 #include "avformat.h"
28 #include "avio_internal.h"
29 #include "avlanguage.h"
30 #include "flacenc.h"
31 #include "internal.h"
32 #include "isom.h"
33 #include "matroska.h"
34 #include "riff.h"
35 #include "vorbiscomment.h"
36 #include "wv.h"
37 
38 #include "libavutil/avstring.h"
40 #include "libavutil/crc.h"
41 #include "libavutil/dict.h"
42 #include "libavutil/intfloat.h"
43 #include "libavutil/intreadwrite.h"
44 #include "libavutil/lfg.h"
46 #include "libavutil/mathematics.h"
47 #include "libavutil/opt.h"
48 #include "libavutil/parseutils.h"
49 #include "libavutil/random_seed.h"
50 #include "libavutil/rational.h"
51 #include "libavutil/samplefmt.h"
52 #include "libavutil/stereo3d.h"
53 
54 #include "libavcodec/xiph.h"
55 #include "libavcodec/mpeg4audio.h"
56 
57 /* Level 1 elements we create a SeekHead entry for:
58  * Info, Tracks, Chapters, Attachments, Tags (potentially twice) and Cues */
59 #define MAX_SEEKHEAD_ENTRIES 7
60 
61 #define IS_SEEKABLE(pb, mkv) (((pb)->seekable & AVIO_SEEKABLE_NORMAL) && \
62  !(mkv)->is_live)
63 
64 enum {
68 };
69 
70 typedef struct ebml_master {
71  int64_t pos; ///< absolute offset in the containing AVIOContext where the master's elements start
72  int sizebytes; ///< how many bytes were reserved for the size
73 } ebml_master;
74 
75 typedef struct ebml_stored_master {
77  int64_t pos;
79 
80 typedef struct mkv_seekhead_entry {
81  uint32_t elementid;
82  uint64_t segmentpos;
84 
85 typedef struct mkv_seekhead {
86  int64_t filepos;
90 } mkv_seekhead;
91 
92 typedef struct mkv_cuepoint {
93  uint64_t pts;
95  int64_t cluster_pos; ///< offset of the cluster containing the block relative to the segment
96  int64_t relative_pos; ///< relative offset from the position of the cluster containing the block
97  int64_t duration; ///< duration of the block according to time base
98 } mkv_cuepoint;
99 
100 typedef struct mkv_cues {
103 } mkv_cues;
104 
105 typedef struct mkv_track {
107  int has_cue;
108  uint64_t uid;
109  unsigned track_num;
113  int64_t last_timestamp;
114  int64_t duration;
117  int64_t ts_offset;
118 } mkv_track;
119 
120 #define MODE_MATROSKAv2 0x01
121 #define MODE_WEBM 0x02
122 
123 typedef struct MatroskaMuxContext {
124  const AVClass *class;
125  int mode;
129  int64_t segment_offset;
131  int64_t cluster_pos; ///< file offset of the current Cluster
132  int64_t cluster_pts;
134  int64_t duration;
138  int64_t cues_pos;
139 
141 
142  unsigned nb_attachments;
144 
147 
152  int is_live;
153 
154  int is_dash;
158 
159  uint32_t segment_uid[4];
161 
162 /** 2 bytes * 7 for EBML IDs, 7 1-byte EBML lengths, 6 1-byte uint,
163  * 8 byte for "matroska" doctype string */
164 #define MAX_EBML_HEADER_SIZE 35
165 
166 /** 2 bytes * 3 for EBML IDs, 3 1-byte EBML lengths, 8 bytes for 64 bit
167  * offset, 4 bytes for target EBML ID */
168 #define MAX_SEEKENTRY_SIZE 21
169 
170 /** 4 * (1-byte EBML ID, 1-byte EBML size, 8-byte uint max) */
171 #define MAX_CUETRACKPOS_SIZE 40
172 
173 /** Seek preroll value for opus */
174 #define OPUS_SEEK_PREROLL 80000000
175 
176 static int ebml_id_size(uint32_t id)
177 {
178  return (av_log2(id) + 7U) / 8;
179 }
180 
181 static void put_ebml_id(AVIOContext *pb, uint32_t id)
182 {
183  int i = ebml_id_size(id);
184  while (i--)
185  avio_w8(pb, (uint8_t)(id >> (i * 8)));
186 }
187 
188 /**
189  * Write an EBML size meaning "unknown size".
190  *
191  * @param bytes The number of bytes the size should occupy (maximum: 8).
192  */
193 static void put_ebml_size_unknown(AVIOContext *pb, int bytes)
194 {
195  av_assert0(bytes <= 8);
196  avio_w8(pb, 0x1ff >> bytes);
197  ffio_fill(pb, 0xff, bytes - 1);
198 }
199 
200 /**
201  * Returns how many bytes are needed to represent a number
202  * as EBML variable length integer.
203  */
204 static int ebml_num_size(uint64_t num)
205 {
206  int bytes = 0;
207  do {
208  bytes++;
209  } while (num >>= 7);
210  return bytes;
211 }
212 
213 /**
214  * Calculate how many bytes are needed to represent the length field
215  * of an EBML element whose payload has a given length.
216  */
217 static int ebml_length_size(uint64_t length)
218 {
219  return ebml_num_size(length + 1);
220 }
221 
222 /**
223  * Write a number as EBML variable length integer on `bytes` bytes.
224  * `bytes` is taken literally without checking.
225  */
226 static void put_ebml_num(AVIOContext *pb, uint64_t num, int bytes)
227 {
228  num |= 1ULL << bytes * 7;
229  for (int i = bytes - 1; i >= 0; i--)
230  avio_w8(pb, (uint8_t)(num >> i * 8));
231 }
232 
233 /**
234  * Write a length as EBML variable length integer.
235  *
236  * @param bytes The number of bytes that need to be used to write the number.
237  * If zero, the minimal number of bytes will be used.
238  */
239 static void put_ebml_length(AVIOContext *pb, uint64_t length, int bytes)
240 {
241  int needed_bytes = ebml_length_size(length);
242 
243  // sizes larger than this are currently undefined in EBML
244  av_assert0(length < (1ULL << 56) - 1);
245 
246  if (bytes == 0)
247  bytes = needed_bytes;
248  // The bytes needed to write the given size must not exceed
249  // the bytes that we ought to use.
250  av_assert0(bytes >= needed_bytes);
251  put_ebml_num(pb, length, bytes);
252 }
253 
254 /**
255  * Write a (random) UID with fixed size to make the output more deterministic
256  */
257 static void put_ebml_uid(AVIOContext *pb, uint32_t elementid, uint64_t uid)
258 {
259  put_ebml_id(pb, elementid);
260  put_ebml_length(pb, 8, 0);
261  avio_wb64(pb, uid);
262 }
263 
264 static void put_ebml_uint(AVIOContext *pb, uint32_t elementid, uint64_t val)
265 {
266  int i, bytes = 1;
267  uint64_t tmp = val;
268  while (tmp >>= 8)
269  bytes++;
270 
271  put_ebml_id(pb, elementid);
272  put_ebml_length(pb, bytes, 0);
273  for (i = bytes - 1; i >= 0; i--)
274  avio_w8(pb, (uint8_t)(val >> i * 8));
275 }
276 
277 static void put_ebml_sint(AVIOContext *pb, uint32_t elementid, int64_t val)
278 {
279  int i, bytes = 1;
280  uint64_t tmp = 2*(val < 0 ? val^-1 : val);
281 
282  while (tmp >>= 8)
283  bytes++;
284 
285  put_ebml_id(pb, elementid);
286  put_ebml_length(pb, bytes, 0);
287  for (i = bytes - 1; i >= 0; i--)
288  avio_w8(pb, (uint8_t)(val >> i * 8));
289 }
290 
291 static void put_ebml_float(AVIOContext *pb, uint32_t elementid, double val)
292 {
293  put_ebml_id(pb, elementid);
294  put_ebml_length(pb, 8, 0);
295  avio_wb64(pb, av_double2int(val));
296 }
297 
298 static void put_ebml_binary(AVIOContext *pb, uint32_t elementid,
299  const void *buf, int size)
300 {
301  put_ebml_id(pb, elementid);
302  put_ebml_length(pb, size, 0);
303  avio_write(pb, buf, size);
304 }
305 
306 static void put_ebml_string(AVIOContext *pb, uint32_t elementid,
307  const char *str)
308 {
309  put_ebml_binary(pb, elementid, str, strlen(str));
310 }
311 
312 /**
313  * Write a void element of a given size. Useful for reserving space in
314  * the file to be written to later.
315  *
316  * @param size The number of bytes to reserve, which must be at least 2.
317  */
318 static void put_ebml_void(AVIOContext *pb, int size)
319 {
320  av_assert0(size >= 2);
321 
323  // we need to subtract the length needed to store the size from the
324  // size we need to reserve so 2 cases, we use 8 bytes to store the
325  // size if possible, 1 byte otherwise
326  if (size < 10) {
327  size -= 2;
328  put_ebml_length(pb, size, 0);
329  } else {
330  size -= 9;
331  put_ebml_length(pb, size, 8);
332  }
333  ffio_fill(pb, 0, size);
334 }
335 
336 static ebml_master start_ebml_master(AVIOContext *pb, uint32_t elementid,
337  uint64_t expectedsize)
338 {
339  int bytes = expectedsize ? ebml_length_size(expectedsize) : 8;
340 
341  put_ebml_id(pb, elementid);
342  put_ebml_size_unknown(pb, bytes);
343  return (ebml_master) { avio_tell(pb), bytes };
344 }
345 
347 {
348  int64_t pos = avio_tell(pb);
349 
350  if (avio_seek(pb, master.pos - master.sizebytes, SEEK_SET) < 0)
351  return;
352  put_ebml_length(pb, pos - master.pos, master.sizebytes);
353  avio_seek(pb, pos, SEEK_SET);
354 }
355 
356 static void mkv_add_seekhead_entry(MatroskaMuxContext *mkv, uint32_t elementid,
357  uint64_t filepos)
358 {
359  mkv_seekhead *seekhead = &mkv->seekhead;
360 
362 
363  seekhead->entries[seekhead->num_entries].elementid = elementid;
364  seekhead->entries[seekhead->num_entries++].segmentpos = filepos - mkv->segment_offset;
365 }
366 
368 {
369  int ret;
370 
371  if (!*dyn_cp && (ret = avio_open_dyn_buf(dyn_cp)) < 0)
372  return ret;
373 
374  if (mkv->write_crc)
375  put_ebml_void(*dyn_cp, 6); /* Reserve space for CRC32 so position/size calculations using avio_tell() take it into account */
376 
377  return 0;
378 }
379 
381  MatroskaMuxContext *mkv, uint32_t id,
382  int length_size, int keep_buffer,
383  int add_seekentry)
384 {
385  uint8_t *buf, crc[4];
386  int ret, size, skip = 0;
387 
388  size = avio_get_dyn_buf(*dyn_cp, &buf);
389  if ((ret = (*dyn_cp)->error) < 0)
390  goto fail;
391 
392  if (add_seekentry)
393  mkv_add_seekhead_entry(mkv, id, avio_tell(pb));
394 
395  put_ebml_id(pb, id);
396  put_ebml_length(pb, size, length_size);
397  if (mkv->write_crc) {
398  skip = 6; /* Skip reserved 6-byte long void element from the dynamic buffer. */
399  AV_WL32(crc, av_crc(av_crc_get_table(AV_CRC_32_IEEE_LE), UINT32_MAX, buf + skip, size - skip) ^ UINT32_MAX);
400  put_ebml_binary(pb, EBML_ID_CRC32, crc, sizeof(crc));
401  }
402  avio_write(pb, buf + skip, size - skip);
403 
404 fail:
405  if (keep_buffer) {
406  ffio_reset_dyn_buf(*dyn_cp);
407  } else {
408  ffio_free_dyn_buf(dyn_cp);
409  }
410  return ret;
411 }
412 
413 /**
414  * Output EBML master. Keep the buffer if seekable, allowing for later updates.
415  * Furthermore always add a SeekHead Entry for this element.
416  */
418  ebml_stored_master *elem,
419  MatroskaMuxContext *mkv, uint32_t id)
420 {
421  if (IS_SEEKABLE(pb, mkv)) {
422  uint8_t *buf;
423  int size = avio_get_dyn_buf(elem->bc, &buf);
424 
425  if (elem->bc->error < 0)
426  return elem->bc->error;
427 
428  elem->pos = avio_tell(pb);
429  mkv_add_seekhead_entry(mkv, id, elem->pos);
430 
431  put_ebml_id(pb, id);
432  put_ebml_length(pb, size, 0);
433  avio_write(pb, buf, size);
434 
435  return 0;
436  } else
437  return end_ebml_master_crc32(pb, &elem->bc, mkv, id, 0, 0, 1);
438 }
439 
440 static void put_xiph_size(AVIOContext *pb, int size)
441 {
442  ffio_fill(pb, 255, size / 255);
443  avio_w8(pb, size % 255);
444 }
445 
446 /**
447  * Free the members allocated in the mux context.
448  */
450 {
451  MatroskaMuxContext *mkv = s->priv_data;
452 
454 
456  ffio_free_dyn_buf(&mkv->info.bc);
457  ffio_free_dyn_buf(&mkv->track.bc);
458  ffio_free_dyn_buf(&mkv->tags.bc);
459 
460  av_freep(&mkv->cues.entries);
461  av_freep(&mkv->tracks);
462 }
463 
464 /**
465  * Initialize the SeekHead element to be ready to index level 1 Matroska
466  * elements. Enough space to write MAX_SEEKHEAD_ENTRIES SeekHead entries
467  * will be reserved at the current file location.
468  */
470 {
471  mkv->seekhead.filepos = avio_tell(pb);
472  // 21 bytes max for a Seek entry, 6 bytes max for the SeekHead ID
473  // and size, 6 bytes for a CRC32 element, and 2 bytes to guarantee
474  // that an EBML void element will fit afterwards
477 }
478 
479 /**
480  * Write the SeekHead to the file at the location reserved for it
481  * and seek to destpos afterwards. When error_on_seek_failure
482  * is not set, failure to seek to the position designated for the
483  * SeekHead is not considered an error and it is presumed that
484  * destpos is the current position; failure to seek to destpos
485  * afterwards is always an error.
486  *
487  * @return 0 on success, < 0 on error.
488  */
490  int error_on_seek_failure, int64_t destpos)
491 {
492  AVIOContext *dyn_cp = NULL;
493  mkv_seekhead *seekhead = &mkv->seekhead;
494  int64_t remaining, ret64;
495  int i, ret;
496 
497  if ((ret64 = avio_seek(pb, seekhead->filepos, SEEK_SET)) < 0)
498  return error_on_seek_failure ? ret64 : 0;
499 
500  ret = start_ebml_master_crc32(&dyn_cp, mkv);
501  if (ret < 0)
502  return ret;
503 
504  for (i = 0; i < seekhead->num_entries; i++) {
505  mkv_seekhead_entry *entry = &seekhead->entries[i];
508 
510  put_ebml_length(dyn_cp, ebml_id_size(entry->elementid), 0);
511  put_ebml_id(dyn_cp, entry->elementid);
512 
514  end_ebml_master(dyn_cp, seekentry);
515  }
516  ret = end_ebml_master_crc32(pb, &dyn_cp, mkv,
517  MATROSKA_ID_SEEKHEAD, 0, 0, 0);
518  if (ret < 0)
519  return ret;
520 
521  remaining = seekhead->filepos + seekhead->reserved_size - avio_tell(pb);
522  put_ebml_void(pb, remaining);
523 
524  if ((ret64 = avio_seek(pb, destpos, SEEK_SET)) < 0)
525  return ret64;
526 
527  return 0;
528 }
529 
530 static int mkv_add_cuepoint(MatroskaMuxContext *mkv, int stream, int64_t ts,
531  int64_t cluster_pos, int64_t relative_pos, int64_t duration)
532 {
533  mkv_cues *cues = &mkv->cues;
534  mkv_cuepoint *entries = cues->entries;
535 
536  if (ts < 0)
537  return 0;
538 
539  entries = av_realloc_array(entries, cues->num_entries + 1, sizeof(mkv_cuepoint));
540  if (!entries)
541  return AVERROR(ENOMEM);
542  cues->entries = entries;
543 
544  cues->entries[cues->num_entries].pts = ts;
545  cues->entries[cues->num_entries].stream_idx = stream;
546  cues->entries[cues->num_entries].cluster_pos = cluster_pos - mkv->segment_offset;
547  cues->entries[cues->num_entries].relative_pos = relative_pos;
548  cues->entries[cues->num_entries++].duration = duration;
549 
550  return 0;
551 }
552 
553 static int mkv_assemble_cues(AVStream **streams, AVIOContext *dyn_cp,
554  mkv_cues *cues, mkv_track *tracks, int num_tracks)
555 {
556  AVIOContext *cuepoint;
557  int ret;
558 
559  ret = avio_open_dyn_buf(&cuepoint);
560  if (ret < 0)
561  return ret;
562 
563  for (mkv_cuepoint *entry = cues->entries, *end = entry + cues->num_entries;
564  entry < end;) {
565  uint64_t pts = entry->pts;
566  uint8_t *buf;
567  int size;
568 
569  put_ebml_uint(cuepoint, MATROSKA_ID_CUETIME, pts);
570 
571  // put all the entries from different tracks that have the exact same
572  // timestamp into the same CuePoint
573  for (int j = 0; j < num_tracks; j++)
574  tracks[j].has_cue = 0;
575  do {
576  ebml_master track_positions;
577  int idx = entry->stream_idx;
578 
579  av_assert0(idx >= 0 && idx < num_tracks);
580  if (tracks[idx].has_cue && streams[idx]->codecpar->codec_type != AVMEDIA_TYPE_SUBTITLE)
581  continue;
582  tracks[idx].has_cue = 1;
584  put_ebml_uint(cuepoint, MATROSKA_ID_CUETRACK , tracks[idx].track_num);
585  put_ebml_uint(cuepoint, MATROSKA_ID_CUECLUSTERPOSITION , entry->cluster_pos);
586  put_ebml_uint(cuepoint, MATROSKA_ID_CUERELATIVEPOSITION, entry->relative_pos);
587  if (entry->duration != -1)
588  put_ebml_uint(cuepoint, MATROSKA_ID_CUEDURATION , entry->duration);
589  end_ebml_master(cuepoint, track_positions);
590  } while (++entry < end && entry->pts == pts);
591  size = avio_get_dyn_buf(cuepoint, &buf);
592  if ((ret = cuepoint->error) < 0)
593  break;
594  put_ebml_binary(dyn_cp, MATROSKA_ID_POINTENTRY, buf, size);
595  ffio_reset_dyn_buf(cuepoint);
596  }
597  ffio_free_dyn_buf(&cuepoint);
598 
599  return ret;
600 }
601 
603  const AVCodecParameters *par)
604 {
605  const uint8_t *header_start[3];
606  int header_len[3];
607  int first_header_size;
608  int err, j;
609 
610  if (par->codec_id == AV_CODEC_ID_VORBIS)
611  first_header_size = 30;
612  else
613  first_header_size = 42;
614 
616  first_header_size, header_start, header_len);
617  if (err < 0) {
618  av_log(s, AV_LOG_ERROR, "Extradata corrupt.\n");
619  return err;
620  }
621 
622  avio_w8(pb, 2); // number packets - 1
623  for (j = 0; j < 2; j++) {
624  put_xiph_size(pb, header_len[j]);
625  }
626  for (j = 0; j < 3; j++)
627  avio_write(pb, header_start[j], header_len[j]);
628 
629  return 0;
630 }
631 
632 static int put_wv_codecpriv(AVIOContext *pb, const AVCodecParameters *par)
633 {
634  if (par->extradata && par->extradata_size == 2)
635  avio_write(pb, par->extradata, 2);
636  else
637  avio_wl16(pb, 0x410); // fallback to the most recent version
638  return 0;
639 }
640 
642  const AVCodecParameters *par)
643 {
644  int write_comment = (par->channel_layout &&
645  !(par->channel_layout & ~0x3ffffULL) &&
647  int ret = ff_flac_write_header(pb, par->extradata, par->extradata_size,
648  !write_comment);
649 
650  if (ret < 0)
651  return ret;
652 
653  if (write_comment) {
654  const char *vendor = (s->flags & AVFMT_FLAG_BITEXACT) ?
655  "Lavf" : LIBAVFORMAT_IDENT;
656  AVDictionary *dict = NULL;
657  uint8_t buf[32];
658  int64_t len;
659 
660  snprintf(buf, sizeof(buf), "0x%"PRIx64, par->channel_layout);
661  av_dict_set(&dict, "WAVEFORMATEXTENSIBLE_CHANNEL_MASK", buf, 0);
662 
663  len = ff_vorbiscomment_length(dict, vendor, NULL, 0);
664  av_assert1(len < (1 << 24) - 4);
665 
666  avio_w8(pb, 0x84);
667  avio_wb24(pb, len);
668 
669  ff_vorbiscomment_write(pb, dict, vendor, NULL, 0);
670 
671  av_dict_free(&dict);
672  }
673 
674  return 0;
675 }
676 
678  const uint8_t *extradata, int extradata_size,
679  int *sample_rate, int *output_sample_rate)
680 {
681  MPEG4AudioConfig mp4ac;
682  int ret;
683 
684  ret = avpriv_mpeg4audio_get_config2(&mp4ac, extradata, extradata_size, 1, s);
685  /* Don't abort if the failure is because of missing extradata. Assume in that
686  * case a bitstream filter will provide the muxer with the extradata in the
687  * first packet.
688  * Abort however if s->pb is not seekable, as we would not be able to seek back
689  * to write the sample rate elements once the extradata shows up, anyway. */
690  if (ret < 0 && (extradata_size || !IS_SEEKABLE(s->pb, mkv))) {
691  av_log(s, AV_LOG_ERROR,
692  "Error parsing AAC extradata, unable to determine samplerate.\n");
693  return AVERROR(EINVAL);
694  }
695 
696  if (ret < 0) {
697  /* This will only happen when this function is called while writing the
698  * header and no extradata is available. The space for this element has
699  * to be reserved for when this function is called again after the
700  * extradata shows up in the first packet, as there's no way to know if
701  * output_sample_rate will be different than sample_rate or not. */
702  *output_sample_rate = *sample_rate;
703  } else {
704  *sample_rate = mp4ac.sample_rate;
705  *output_sample_rate = mp4ac.ext_sample_rate;
706  }
707  return 0;
708 }
709 
711  const AVCodecParameters *par,
712  AVIOContext *dyn_cp)
713 {
714  switch (par->codec_id) {
715  case AV_CODEC_ID_VORBIS:
716  case AV_CODEC_ID_THEORA:
717  return put_xiph_codecpriv(s, dyn_cp, par);
718  case AV_CODEC_ID_FLAC:
719  return put_flac_codecpriv(s, dyn_cp, par);
720  case AV_CODEC_ID_WAVPACK:
721  return put_wv_codecpriv(dyn_cp, par);
722  case AV_CODEC_ID_H264:
723  return ff_isom_write_avcc(dyn_cp, par->extradata,
724  par->extradata_size);
725  case AV_CODEC_ID_HEVC:
726  return ff_isom_write_hvcc(dyn_cp, par->extradata,
727  par->extradata_size, 0);
728  case AV_CODEC_ID_AV1:
729  if (par->extradata_size)
730  return ff_isom_write_av1c(dyn_cp, par->extradata,
731  par->extradata_size);
732  else
733  put_ebml_void(pb, 4 + 3);
734  break;
735  case AV_CODEC_ID_ALAC:
736  if (par->extradata_size < 36) {
737  av_log(s, AV_LOG_ERROR,
738  "Invalid extradata found, ALAC expects a 36-byte "
739  "QuickTime atom.");
740  return AVERROR_INVALIDDATA;
741  } else
742  avio_write(dyn_cp, par->extradata + 12,
743  par->extradata_size - 12);
744  break;
745  case AV_CODEC_ID_AAC:
746  if (par->extradata_size)
747  avio_write(dyn_cp, par->extradata, par->extradata_size);
748  else
749  put_ebml_void(pb, MAX_PCE_SIZE + 2 + 4);
750  break;
751  default:
752  if (par->codec_id == AV_CODEC_ID_PRORES &&
754  avio_wl32(dyn_cp, par->codec_tag);
755  } else if (par->extradata_size && par->codec_id != AV_CODEC_ID_TTA)
756  avio_write(dyn_cp, par->extradata, par->extradata_size);
757  }
758 
759  return 0;
760 }
761 
763  AVCodecParameters *par,
764  int native_id, int qt_id)
765 {
766  AVIOContext *dyn_cp;
767  uint8_t *codecpriv;
768  int ret, codecpriv_size;
769 
770  ret = avio_open_dyn_buf(&dyn_cp);
771  if (ret < 0)
772  return ret;
773 
774  if (native_id) {
775  ret = mkv_write_native_codecprivate(s, pb, par, dyn_cp);
776  } else if (par->codec_type == AVMEDIA_TYPE_VIDEO) {
777  if (qt_id) {
778  if (!par->codec_tag)
780  par->codec_id);
783  ) {
784  int i;
785  avio_wb32(dyn_cp, 0x5a + par->extradata_size);
786  avio_wl32(dyn_cp, par->codec_tag);
787  for(i = 0; i < 0x5a - 8; i++)
788  avio_w8(dyn_cp, 0);
789  }
790  avio_write(dyn_cp, par->extradata, par->extradata_size);
791  } else {
793  av_log(s, AV_LOG_WARNING, "codec %s is not supported by this format\n",
794  avcodec_get_name(par->codec_id));
795 
796  if (!par->codec_tag)
798  par->codec_id);
799  if (!par->codec_tag && par->codec_id != AV_CODEC_ID_RAWVIDEO) {
800  av_log(s, AV_LOG_ERROR, "No bmp codec tag found for codec %s\n",
801  avcodec_get_name(par->codec_id));
802  ret = AVERROR(EINVAL);
803  }
804 
805  ff_put_bmp_header(dyn_cp, par, 0, 0);
806  }
807  } else if (par->codec_type == AVMEDIA_TYPE_AUDIO) {
808  unsigned int tag;
810  if (!tag) {
811  av_log(s, AV_LOG_ERROR, "No wav codec tag found for codec %s\n",
812  avcodec_get_name(par->codec_id));
813  ret = AVERROR(EINVAL);
814  }
815  if (!par->codec_tag)
816  par->codec_tag = tag;
817 
819  }
820 
821  if (ret >= 0) {
822  codecpriv_size = avio_get_dyn_buf(dyn_cp, &codecpriv);
823  if ((ret = dyn_cp->error) >= 0 && codecpriv_size)
825  codecpriv_size);
826  }
827  ffio_free_dyn_buf(&dyn_cp);
828  return ret;
829 }
830 
831 static void mkv_write_video_color(AVIOContext *pb, const AVStream *st,
832  const AVCodecParameters *par)
833 {
834  /* 18 Elements with two bytes ID, one byte length field, 8 bytes payload
835  * a master element with two bytes ID and one byte length field
836  * plus another byte to stay clear of the end. */
837  uint8_t colour[(2 + 1 + 8) * 18 + (2 + 1) + 1];
838  AVIOContext buf, *dyn_cp = &buf;
839  int colorinfo_size;
840  const void *side_data;
841 
842  ffio_init_context(dyn_cp, colour, sizeof(colour), 1, NULL, NULL, NULL, NULL);
843 
844  if (par->color_trc != AVCOL_TRC_UNSPECIFIED &&
845  par->color_trc < AVCOL_TRC_NB) {
847  par->color_trc);
848  }
849  if (par->color_space != AVCOL_SPC_UNSPECIFIED &&
850  par->color_space < AVCOL_SPC_NB) {
852  }
854  par->color_primaries < AVCOL_PRI_NB) {
856  }
857  if (par->color_range != AVCOL_RANGE_UNSPECIFIED &&
858  par->color_range < AVCOL_RANGE_NB) {
860  }
863  int xpos, ypos;
864 
865  avcodec_enum_to_chroma_pos(&xpos, &ypos, par->chroma_location);
866  put_ebml_uint(dyn_cp, MATROSKA_ID_VIDEOCOLORCHROMASITINGHORZ, (xpos >> 7) + 1);
867  put_ebml_uint(dyn_cp, MATROSKA_ID_VIDEOCOLORCHROMASITINGVERT, (ypos >> 7) + 1);
868  }
869 
871  NULL);
872  if (side_data) {
873  const AVContentLightMetadata *metadata = side_data;
876  }
877 
879  NULL);
880  if (side_data) {
881  ebml_master meta_element = start_ebml_master(
882  dyn_cp, MATROSKA_ID_VIDEOCOLORMASTERINGMETA, 10 * (2 + 1 + 8));
883  const AVMasteringDisplayMetadata *metadata = side_data;
884  if (metadata->has_primaries) {
886  av_q2d(metadata->display_primaries[0][0]));
888  av_q2d(metadata->display_primaries[0][1]));
890  av_q2d(metadata->display_primaries[1][0]));
892  av_q2d(metadata->display_primaries[1][1]));
894  av_q2d(metadata->display_primaries[2][0]));
896  av_q2d(metadata->display_primaries[2][1]));
898  av_q2d(metadata->white_point[0]));
900  av_q2d(metadata->white_point[1]));
901  }
902  if (metadata->has_luminance) {
904  av_q2d(metadata->max_luminance));
906  av_q2d(metadata->min_luminance));
907  }
908  end_ebml_master(dyn_cp, meta_element);
909  }
910 
911  colorinfo_size = avio_tell(dyn_cp);
912  if (colorinfo_size)
913  put_ebml_binary(pb, MATROSKA_ID_VIDEOCOLOR, colour, colorinfo_size);
914 }
915 
917  const AVStream *st)
918 {
919  ebml_master projection;
920  uint8_t private[20];
921 
922  const AVSphericalMapping *spherical =
924  NULL);
925 
926  if (!spherical)
927  return;
928 
929  if (spherical->projection != AV_SPHERICAL_EQUIRECTANGULAR &&
931  spherical->projection != AV_SPHERICAL_CUBEMAP) {
932  av_log(s, AV_LOG_WARNING, "Unknown projection type\n");
933  return;
934  }
935 
936  // Maximally 4 8-byte elements with id-length 2 + 1 byte length field
937  // and the private data of the AV_SPHERICAL_EQUIRECTANGULAR_TILE case
939  4 * (2 + 1 + 8) + (2 + 1 + 20));
940 
941  switch (spherical->projection) {
945  break;
949  AV_WB32(private, 0); // version + flags
950  AV_WB32(private + 4, spherical->bound_top);
951  AV_WB32(private + 8, spherical->bound_bottom);
952  AV_WB32(private + 12, spherical->bound_left);
953  AV_WB32(private + 16, spherical->bound_right);
955  private, 20);
956  break;
960  AV_WB32(private, 0); // version + flags
961  AV_WB32(private + 4, 0); // layout
962  AV_WB32(private + 8, spherical->padding);
964  private, 12);
965  break;
966  default:
967  av_assert0(0);
968  }
969 
970  if (spherical->yaw)
972  (double) spherical->yaw / (1 << 16));
973  if (spherical->pitch)
975  (double) spherical->pitch / (1 << 16));
976  if (spherical->roll)
978  (double) spherical->roll / (1 << 16));
979 
980  end_ebml_master(pb, projection);
981 }
982 
984  enum AVFieldOrder field_order)
985 {
986  switch (field_order) {
987  case AV_FIELD_UNKNOWN:
988  break;
992  break;
993  case AV_FIELD_TT:
994  case AV_FIELD_BB:
995  case AV_FIELD_TB:
996  case AV_FIELD_BT:
999  if (mode != MODE_WEBM) {
1000  switch (field_order) {
1001  case AV_FIELD_TT:
1004  break;
1005  case AV_FIELD_BB:
1008  break;
1009  case AV_FIELD_TB:
1012  break;
1013  case AV_FIELD_BT:
1016  break;
1017  }
1018  }
1019  }
1020 }
1021 
1023  AVStream *st, int mode, int *h_width, int *h_height)
1024 {
1025  const AVDictionaryEntry *tag;
1027  const AVStereo3D *stereo;
1028 
1029  *h_width = 1;
1030  *h_height = 1;
1031  // convert metadata into proper side data and add it to the stream
1032  if ((tag = av_dict_get(st->metadata, "stereo_mode", NULL, 0)) ||
1033  (tag = av_dict_get( s->metadata, "stereo_mode", NULL, 0))) {
1034  int stereo_mode = atoi(tag->value);
1035 
1036  for (int i = 0; i < MATROSKA_VIDEO_STEREOMODE_TYPE_NB; i++)
1037  if (!strcmp(tag->value, ff_matroska_video_stereo_mode[i])){
1038  stereo_mode = i;
1039  break;
1040  }
1041 
1042  if (stereo_mode < MATROSKA_VIDEO_STEREOMODE_TYPE_NB &&
1043  stereo_mode != 10 && stereo_mode != 12) {
1044  int ret = ff_mkv_stereo3d_conv(st, stereo_mode);
1045  if (ret < 0)
1046  return ret;
1047  }
1048  }
1049 
1051  NULL);
1052  if (stereo) {
1053  switch (stereo->type) {
1054  case AV_STEREO3D_2D:
1056  break;
1058  format = (stereo->flags & AV_STEREO3D_FLAG_INVERT)
1061  *h_width = 2;
1062  break;
1063  case AV_STEREO3D_TOPBOTTOM:
1065  if (stereo->flags & AV_STEREO3D_FLAG_INVERT)
1066  format--;
1067  *h_height = 2;
1068  break;
1071  if (stereo->flags & AV_STEREO3D_FLAG_INVERT)
1072  format--;
1073  break;
1074  case AV_STEREO3D_LINES:
1076  if (stereo->flags & AV_STEREO3D_FLAG_INVERT)
1077  format--;
1078  *h_height = 2;
1079  break;
1080  case AV_STEREO3D_COLUMNS:
1082  if (stereo->flags & AV_STEREO3D_FLAG_INVERT)
1083  format--;
1084  *h_width = 2;
1085  break;
1088  if (stereo->flags & AV_STEREO3D_FLAG_INVERT)
1089  format++;
1090  break;
1091  }
1092  }
1093 
1094  if (format == MATROSKA_VIDEO_STEREOMODE_TYPE_NB)
1095  return 0;
1096 
1097  // if webm, do not write unsupported modes
1098  if ((mode == MODE_WEBM &&
1101  || format >= MATROSKA_VIDEO_STEREOMODE_TYPE_NB) {
1102  av_log(s, AV_LOG_ERROR,
1103  "The specified stereo mode is not valid.\n");
1104  return AVERROR(EINVAL);
1105  }
1106 
1107  // write StereoMode if format is valid
1109 
1110  return 0;
1111 }
1112 
1114  AVStream *st, mkv_track *track, AVIOContext *pb,
1115  int is_default)
1116 {
1117  AVCodecParameters *par = st->codecpar;
1118  ebml_master subinfo, track_master;
1119  int native_id = 0;
1120  int qt_id = 0;
1121  int bit_depth;
1122  int sample_rate = par->sample_rate;
1123  int output_sample_rate = 0;
1124  int display_width_div = 1;
1125  int display_height_div = 1;
1126  int j, ret;
1127  const AVDictionaryEntry *tag;
1128 
1129  if (par->codec_type == AVMEDIA_TYPE_ATTACHMENT)
1130  return 0;
1131 
1132  if (par->codec_id == AV_CODEC_ID_AAC) {
1133  ret = get_aac_sample_rates(s, mkv, par->extradata, par->extradata_size,
1134  &sample_rate, &output_sample_rate);
1135  if (ret < 0)
1136  return ret;
1137  }
1138 
1139  track_master = start_ebml_master(pb, MATROSKA_ID_TRACKENTRY, 0);
1141  put_ebml_uid (pb, MATROSKA_ID_TRACKUID, track->uid);
1142  put_ebml_uint(pb, MATROSKA_ID_TRACKFLAGLACING, 0); // no lacing (yet)
1143 
1144  if ((tag = av_dict_get(st->metadata, "title", NULL, 0)))
1146  tag = av_dict_get(st->metadata, "language", NULL, 0);
1148  tag && tag->value ? tag->value : "und");
1149 
1150  // The default value for TRACKFLAGDEFAULT is 1, so add element
1151  // if we need to clear it.
1152  if (!is_default)
1154 
1157 
1158  if (mkv->mode == MODE_WEBM) {
1159  const char *codec_id;
1160  if (par->codec_type != AVMEDIA_TYPE_SUBTITLE) {
1161  for (j = 0; ff_webm_codec_tags[j].id != AV_CODEC_ID_NONE; j++) {
1162  if (ff_webm_codec_tags[j].id == par->codec_id) {
1163  codec_id = ff_webm_codec_tags[j].str;
1164  native_id = 1;
1165  break;
1166  }
1167  }
1168  } else if (par->codec_id == AV_CODEC_ID_WEBVTT) {
1170  codec_id = "D_WEBVTT/CAPTIONS";
1171  native_id = MATROSKA_TRACK_TYPE_SUBTITLE;
1172  } else if (st->disposition & AV_DISPOSITION_DESCRIPTIONS) {
1173  codec_id = "D_WEBVTT/DESCRIPTIONS";
1174  native_id = MATROSKA_TRACK_TYPE_METADATA;
1175  } else if (st->disposition & AV_DISPOSITION_METADATA) {
1176  codec_id = "D_WEBVTT/METADATA";
1177  native_id = MATROSKA_TRACK_TYPE_METADATA;
1178  } else {
1179  codec_id = "D_WEBVTT/SUBTITLES";
1180  native_id = MATROSKA_TRACK_TYPE_SUBTITLE;
1181  }
1182  }
1183 
1184  if (!native_id) {
1185  av_log(s, AV_LOG_ERROR,
1186  "Only VP8 or VP9 or AV1 video and Vorbis or Opus audio and WebVTT subtitles are supported for WebM.\n");
1187  return AVERROR(EINVAL);
1188  }
1189 
1190  put_ebml_string(pb, MATROSKA_ID_CODECID, codec_id);
1191  } else {
1192  // look for a codec ID string specific to mkv to use,
1193  // if none are found, use AVI codes
1194  if (par->codec_id != AV_CODEC_ID_RAWVIDEO || par->codec_tag) {
1195  for (j = 0; ff_mkv_codec_tags[j].id != AV_CODEC_ID_NONE; j++) {
1196  if (ff_mkv_codec_tags[j].id == par->codec_id && par->codec_id != AV_CODEC_ID_FFV1) {
1198  native_id = 1;
1199  break;
1200  }
1201  }
1202  } else {
1203  if (mkv->allow_raw_vfw) {
1204  native_id = 0;
1205  } else {
1206  av_log(s, AV_LOG_ERROR, "Raw RGB is not supported Natively in Matroska, you can use AVI or NUT or\n"
1207  "If you would like to store it anyway using VFW mode, enable allow_raw_vfw (-allow_raw_vfw 1)\n");
1208  return AVERROR(EINVAL);
1209  }
1210  }
1211  }
1212 
1213  switch (par->codec_type) {
1214  case AVMEDIA_TYPE_VIDEO:
1215  mkv->have_video = 1;
1217 
1218  if( st->avg_frame_rate.num > 0 && st->avg_frame_rate.den > 0
1219  && av_cmp_q(av_inv_q(st->avg_frame_rate), st->time_base) > 0)
1221  else if( st->r_frame_rate.num > 0 && st->r_frame_rate.den > 0
1222  && av_cmp_q(av_inv_q(st->r_frame_rate), st->time_base) > 0)
1224 
1225  if (!native_id &&
1228  par->codec_id == AV_CODEC_ID_SVQ1 ||
1229  par->codec_id == AV_CODEC_ID_SVQ3 ||
1230  par->codec_id == AV_CODEC_ID_CINEPAK))
1231  qt_id = 1;
1232 
1233  if (qt_id)
1234  put_ebml_string(pb, MATROSKA_ID_CODECID, "V_QUICKTIME");
1235  else if (!native_id) {
1236  // if there is no mkv-specific codec ID, use VFW mode
1237  put_ebml_string(pb, MATROSKA_ID_CODECID, "V_MS/VFW/FOURCC");
1238  track->write_dts = 1;
1240  }
1241 
1242  subinfo = start_ebml_master(pb, MATROSKA_ID_TRACKVIDEO, 0);
1243 
1246 
1247  mkv_write_field_order(pb, mkv->mode, par->field_order);
1248 
1249  // check both side data and metadata for stereo information,
1250  // write the result to the bitstream if any is found
1251  ret = mkv_write_stereo_mode(s, pb, st, mkv->mode,
1252  &display_width_div,
1253  &display_height_div);
1254  if (ret < 0)
1255  return ret;
1256 
1257  if (((tag = av_dict_get(st->metadata, "alpha_mode", NULL, 0)) && atoi(tag->value)) ||
1258  ((tag = av_dict_get( s->metadata, "alpha_mode", NULL, 0)) && atoi(tag->value)) ||
1259  (par->format == AV_PIX_FMT_YUVA420P)) {
1261  }
1262 
1263  // write DisplayWidth and DisplayHeight, they contain the size of
1264  // a single source view and/or the display aspect ratio
1265  if (st->sample_aspect_ratio.num) {
1266  int64_t d_width = av_rescale(par->width, st->sample_aspect_ratio.num, st->sample_aspect_ratio.den);
1267  if (d_width > INT_MAX) {
1268  av_log(s, AV_LOG_ERROR, "Overflow in display width\n");
1269  return AVERROR(EINVAL);
1270  }
1271  if (d_width != par->width || display_width_div != 1 || display_height_div != 1) {
1272  if (mkv->mode == MODE_WEBM || display_width_div != 1 || display_height_div != 1) {
1273  put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYWIDTH , d_width / display_width_div);
1274  put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYHEIGHT, par->height / display_height_div);
1275  } else {
1276  AVRational display_aspect_ratio;
1277  av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den,
1278  par->width * (int64_t)st->sample_aspect_ratio.num,
1279  par->height * (int64_t)st->sample_aspect_ratio.den,
1280  1024 * 1024);
1281  put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYWIDTH, display_aspect_ratio.num);
1282  put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYHEIGHT, display_aspect_ratio.den);
1284  }
1285  }
1286  } else if (display_width_div != 1 || display_height_div != 1) {
1287  put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYWIDTH , par->width / display_width_div);
1288  put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYHEIGHT, par->height / display_height_div);
1289  } else if (mkv->mode != MODE_WEBM)
1291 
1292  if (par->codec_id == AV_CODEC_ID_RAWVIDEO) {
1293  uint32_t color_space = av_le2ne32(par->codec_tag);
1294  put_ebml_binary(pb, MATROSKA_ID_VIDEOCOLORSPACE, &color_space, sizeof(color_space));
1295  }
1296  mkv_write_video_color(pb, st, par);
1297  mkv_write_video_projection(s, pb, st);
1298 
1299  end_ebml_master(pb, subinfo);
1300  break;
1301 
1302  case AVMEDIA_TYPE_AUDIO:
1303  if (par->initial_padding && par->codec_id == AV_CODEC_ID_OPUS) {
1304  int64_t codecdelay = av_rescale_q(par->initial_padding,
1305  (AVRational){ 1, 48000 },
1306  (AVRational){ 1, 1000000000 });
1307  if (codecdelay < 0) {
1308  av_log(s, AV_LOG_ERROR, "Initial padding is invalid\n");
1309  return AVERROR(EINVAL);
1310  }
1311 // track->ts_offset = av_rescale_q(par->initial_padding,
1312 // (AVRational){ 1, par->sample_rate },
1313 // st->time_base);
1314 
1315  put_ebml_uint(pb, MATROSKA_ID_CODECDELAY, codecdelay);
1316  }
1317  if (par->codec_id == AV_CODEC_ID_OPUS)
1319 
1321 
1322  if (!native_id)
1323  // no mkv-specific ID, use ACM mode
1324  put_ebml_string(pb, MATROSKA_ID_CODECID, "A_MS/ACM");
1325 
1326  subinfo = start_ebml_master(pb, MATROSKA_ID_TRACKAUDIO, 6 + 4 * 9);
1328 
1329  track->sample_rate_offset = avio_tell(pb);
1330  put_ebml_float (pb, MATROSKA_ID_AUDIOSAMPLINGFREQ, sample_rate);
1331  if (output_sample_rate)
1332  put_ebml_float(pb, MATROSKA_ID_AUDIOOUTSAMPLINGFREQ, output_sample_rate);
1333 
1334  bit_depth = av_get_bits_per_sample(par->codec_id);
1335  if (!bit_depth && par->codec_id != AV_CODEC_ID_ADPCM_G726) {
1336  if (par->bits_per_raw_sample)
1337  bit_depth = par->bits_per_raw_sample;
1338  else
1339  bit_depth = av_get_bytes_per_sample(par->format) << 3;
1340  }
1341  if (!bit_depth)
1342  bit_depth = par->bits_per_coded_sample;
1343  if (bit_depth)
1344  put_ebml_uint(pb, MATROSKA_ID_AUDIOBITDEPTH, bit_depth);
1345  end_ebml_master(pb, subinfo);
1346  break;
1347 
1348  case AVMEDIA_TYPE_SUBTITLE:
1349  if (!native_id) {
1350  av_log(s, AV_LOG_ERROR, "Subtitle codec %d is not supported.\n", par->codec_id);
1351  return AVERROR(ENOSYS);
1352  }
1353 
1354  if (mkv->mode != MODE_WEBM || par->codec_id != AV_CODEC_ID_WEBVTT)
1355  native_id = MATROSKA_TRACK_TYPE_SUBTITLE;
1356 
1357  put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, native_id);
1358  break;
1359  default:
1360  av_log(s, AV_LOG_ERROR, "Only audio, video, and subtitles are supported for Matroska.\n");
1361  return AVERROR(EINVAL);
1362  }
1363 
1364  if (mkv->mode != MODE_WEBM || par->codec_id != AV_CODEC_ID_WEBVTT) {
1365  track->codecpriv_offset = avio_tell(pb);
1366  ret = mkv_write_codecprivate(s, pb, par, native_id, qt_id);
1367  if (ret < 0)
1368  return ret;
1369  }
1370 
1371  end_ebml_master(pb, track_master);
1372 
1373  return 0;
1374 }
1375 
1377 {
1378  MatroskaMuxContext *mkv = s->priv_data;
1379  AVIOContext *pb = s->pb;
1380  int i, ret, video_default_idx, audio_default_idx, subtitle_default_idx;
1381 
1382  if (mkv->nb_attachments == s->nb_streams)
1383  return 0;
1384 
1385  ret = start_ebml_master_crc32(&mkv->track.bc, mkv);
1386  if (ret < 0)
1387  return ret;
1388 
1389  if (mkv->default_mode != DEFAULT_MODE_PASSTHROUGH) {
1390  int video_idx, audio_idx, subtitle_idx;
1391 
1392  video_idx = video_default_idx =
1393  audio_idx = audio_default_idx =
1394  subtitle_idx = subtitle_default_idx = -1;
1395 
1396  for (i = s->nb_streams - 1; i >= 0; i--) {
1397  AVStream *st = s->streams[i];
1398 
1399  switch (st->codecpar->codec_type) {
1400 #define CASE(type, variable) \
1401  case AVMEDIA_TYPE_ ## type: \
1402  variable ## _idx = i; \
1403  if (st->disposition & AV_DISPOSITION_DEFAULT) \
1404  variable ## _default_idx = i; \
1405  break;
1406  CASE(VIDEO, video)
1407  CASE(AUDIO, audio)
1408  CASE(SUBTITLE, subtitle)
1409 #undef CASE
1410  }
1411  }
1412 
1413  video_default_idx = FFMAX(video_default_idx, video_idx);
1414  audio_default_idx = FFMAX(audio_default_idx, audio_idx);
1416  subtitle_default_idx = FFMAX(subtitle_default_idx, subtitle_idx);
1417  }
1418  for (i = 0; i < s->nb_streams; i++) {
1419  AVStream *st = s->streams[i];
1420  int is_default = mkv->default_mode == DEFAULT_MODE_PASSTHROUGH ?
1422  i == video_default_idx || i == audio_default_idx ||
1423  i == subtitle_default_idx;
1424  ret = mkv_write_track(s, mkv, st, &mkv->tracks[i],
1425  mkv->track.bc, is_default);
1426  if (ret < 0)
1427  return ret;
1428  }
1429 
1430  return end_ebml_master_crc32_tentatively(pb, &mkv->track, mkv,
1432 }
1433 
1435 {
1436  uint8_t *key = av_strdup(t->key);
1437  uint8_t *p = key;
1438  const uint8_t *lang = NULL;
1439  ebml_master tag;
1440 
1441  if (!key)
1442  return AVERROR(ENOMEM);
1443 
1444  if ((p = strrchr(p, '-')) &&
1445  (lang = ff_convert_lang_to(p + 1, AV_LANG_ISO639_2_BIBL)))
1446  *p = 0;
1447 
1448  p = key;
1449  while (*p) {
1450  if (*p == ' ')
1451  *p = '_';
1452  else if (*p >= 'a' && *p <= 'z')
1453  *p -= 'a' - 'A';
1454  p++;
1455  }
1456 
1459  if (lang)
1462  end_ebml_master(pb, tag);
1463 
1464  av_freep(&key);
1465  return 0;
1466 }
1467 
1469  ebml_master *tag, uint32_t elementid, uint64_t uid)
1470 {
1471  ebml_master targets;
1472  int ret;
1473 
1474  if (!*pb) {
1475  ret = start_ebml_master_crc32(pb, mkv);
1476  if (ret < 0)
1477  return ret;
1478  }
1479 
1480  *tag = start_ebml_master(*pb, MATROSKA_ID_TAG, 0);
1481  targets = start_ebml_master(*pb, MATROSKA_ID_TAGTARGETS, 4 + 1 + 8);
1482  if (elementid)
1483  put_ebml_uid(*pb, elementid, uid);
1484  end_ebml_master(*pb, targets);
1485  return 0;
1486 }
1487 
1488 static int mkv_check_tag_name(const char *name, uint32_t elementid)
1489 {
1490  return av_strcasecmp(name, "title") &&
1491  av_strcasecmp(name, "stereo_mode") &&
1492  av_strcasecmp(name, "creation_time") &&
1493  av_strcasecmp(name, "encoding_tool") &&
1494  av_strcasecmp(name, "duration") &&
1495  (elementid != MATROSKA_ID_TAGTARGETS_TRACKUID ||
1496  av_strcasecmp(name, "language")) &&
1497  (elementid != MATROSKA_ID_TAGTARGETS_ATTACHUID ||
1498  (av_strcasecmp(name, "filename") &&
1499  av_strcasecmp(name, "mimetype")));
1500 }
1501 
1503  AVIOContext **pb, ebml_master *tag,
1504  uint32_t elementid, uint64_t uid)
1505 {
1506  const AVDictionaryEntry *t = NULL;
1507  ebml_master tag2;
1508  int ret;
1509 
1510  ret = mkv_write_tag_targets(mkv, pb, tag ? tag : &tag2, elementid, uid);
1511  if (ret < 0)
1512  return ret;
1513 
1514  while ((t = av_dict_get(m, "", t, AV_DICT_IGNORE_SUFFIX))) {
1515  if (mkv_check_tag_name(t->key, elementid)) {
1516  ret = mkv_write_simpletag(*pb, t);
1517  if (ret < 0)
1518  return ret;
1519  }
1520  }
1521 
1522  if (!tag)
1523  end_ebml_master(*pb, tag2);
1524 
1525  return 0;
1526 }
1527 
1528 static int mkv_check_tag(const AVDictionary *m, uint32_t elementid)
1529 {
1530  const AVDictionaryEntry *t = NULL;
1531 
1532  while ((t = av_dict_get(m, "", t, AV_DICT_IGNORE_SUFFIX)))
1533  if (mkv_check_tag_name(t->key, elementid))
1534  return 1;
1535 
1536  return 0;
1537 }
1538 
1540 {
1541  MatroskaMuxContext *mkv = s->priv_data;
1542  ebml_master tag, *tagp = IS_SEEKABLE(s->pb, mkv) ? &tag : NULL;
1543  int i, ret;
1544 
1545  mkv->wrote_tags = 1;
1546 
1548 
1549  if (mkv_check_tag(s->metadata, 0)) {
1550  ret = mkv_write_tag(mkv, s->metadata, &mkv->tags.bc, NULL, 0, 0);
1551  if (ret < 0)
1552  return ret;
1553  }
1554 
1555  for (i = 0; i < s->nb_streams; i++) {
1556  const AVStream *st = s->streams[i];
1557  mkv_track *track = &mkv->tracks[i];
1558 
1560  continue;
1561 
1563  continue;
1564 
1565  ret = mkv_write_tag(mkv, st->metadata, &mkv->tags.bc, tagp,
1567  if (ret < 0)
1568  return ret;
1569 
1570  if (tagp) {
1571  AVIOContext *pb = mkv->tags.bc;
1572  ebml_master simpletag;
1573 
1574  simpletag = start_ebml_master(pb, MATROSKA_ID_SIMPLETAG,
1575  2 + 1 + 8 + 23);
1576  put_ebml_string(pb, MATROSKA_ID_TAGNAME, "DURATION");
1577  track->duration_offset = avio_tell(pb);
1578 
1579  // Reserve space to write duration as a 20-byte string.
1580  // 2 (ebml id) + 1 (data size) + 20 (data)
1581  put_ebml_void(pb, 23);
1582  end_ebml_master(pb, simpletag);
1583  end_ebml_master(pb, tag);
1584  }
1585  }
1586 
1587  if (mkv->nb_attachments && mkv->mode != MODE_WEBM) {
1588  for (i = 0; i < s->nb_streams; i++) {
1589  const mkv_track *track = &mkv->tracks[i];
1590  const AVStream *st = s->streams[i];
1591 
1593  continue;
1594 
1596  continue;
1597 
1598  ret = mkv_write_tag(mkv, st->metadata, &mkv->tags.bc, NULL,
1600  if (ret < 0)
1601  return ret;
1602  }
1603  }
1604 
1605  if (mkv->tags.bc) {
1606  return end_ebml_master_crc32_tentatively(s->pb, &mkv->tags, mkv,
1608  }
1609  return 0;
1610 }
1611 
1613 {
1614  MatroskaMuxContext *mkv = s->priv_data;
1615  AVIOContext *dyn_cp = NULL, *dyn_tags = NULL, **tags, *pb = s->pb;
1616  ebml_master editionentry;
1617  uint64_t chapter_id_offset = 0;
1618  AVRational scale = {1, 1E9};
1619  int i, ret;
1620 
1621  if (!s->nb_chapters || mkv->wrote_chapters)
1622  return 0;
1623 
1624  for (i = 0; i < s->nb_chapters; i++)
1625  if (!s->chapters[i]->id) {
1626  chapter_id_offset = 1;
1627  break;
1628  }
1629 
1630  ret = start_ebml_master_crc32(&dyn_cp, mkv);
1631  if (ret < 0)
1632  return ret;
1633 
1634  editionentry = start_ebml_master(dyn_cp, MATROSKA_ID_EDITIONENTRY, 0);
1635  if (mkv->mode != MODE_WEBM) {
1637  /* If mkv_write_tags() has already been called, then any tags
1638  * corresponding to chapters will be put into a new Tags element. */
1639  tags = mkv->wrote_tags ? &dyn_tags : &mkv->tags.bc;
1640  } else
1641  tags = NULL;
1642 
1643  for (i = 0; i < s->nb_chapters; i++) {
1644  ebml_master chapteratom, chapterdisplay;
1645  const AVChapter *c = s->chapters[i];
1646  int64_t chapterstart = av_rescale_q(c->start, c->time_base, scale);
1647  int64_t chapterend = av_rescale_q(c->end, c->time_base, scale);
1648  const AVDictionaryEntry *t;
1649  if (chapterstart < 0 || chapterstart > chapterend || chapterend < 0) {
1650  av_log(s, AV_LOG_ERROR,
1651  "Invalid chapter start (%"PRId64") or end (%"PRId64").\n",
1652  chapterstart, chapterend);
1653  ret = AVERROR_INVALIDDATA;
1654  goto fail;
1655  }
1656 
1657  chapteratom = start_ebml_master(dyn_cp, MATROSKA_ID_CHAPTERATOM, 0);
1659  (uint32_t)c->id + chapter_id_offset);
1660  put_ebml_uint(dyn_cp, MATROSKA_ID_CHAPTERTIMESTART, chapterstart);
1661  put_ebml_uint(dyn_cp, MATROSKA_ID_CHAPTERTIMEEND, chapterend);
1662  if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
1663  chapterdisplay = start_ebml_master(dyn_cp, MATROSKA_ID_CHAPTERDISPLAY, 0);
1665  put_ebml_string(dyn_cp, MATROSKA_ID_CHAPLANG , "und");
1666  end_ebml_master(dyn_cp, chapterdisplay);
1667  }
1668  end_ebml_master(dyn_cp, chapteratom);
1669 
1671  ret = mkv_write_tag(mkv, c->metadata, tags, NULL,
1673  (uint32_t)c->id + chapter_id_offset);
1674  if (ret < 0)
1675  goto fail;
1676  }
1677  }
1678  end_ebml_master(dyn_cp, editionentry);
1679  mkv->wrote_chapters = 1;
1680 
1681  ret = end_ebml_master_crc32(pb, &dyn_cp, mkv, MATROSKA_ID_CHAPTERS, 0, 0, 1);
1682  if (ret < 0)
1683  goto fail;
1684  if (dyn_tags)
1685  return end_ebml_master_crc32(pb, &dyn_tags, mkv,
1686  MATROSKA_ID_TAGS, 0, 0, 1);
1687  return 0;
1688 
1689 fail:
1690  if (tags) {
1691  /* tags == &mkv->tags.bc can only happen if mkv->tags.bc was
1692  * initially NULL, so we never free older tags. */
1693  ffio_free_dyn_buf(tags);
1694  }
1695  ffio_free_dyn_buf(&dyn_cp);
1696  return ret;
1697 }
1698 
1699 static const char *get_mimetype(const AVStream *st)
1700 {
1701  const AVDictionaryEntry *t;
1702 
1703  if (t = av_dict_get(st->metadata, "mimetype", NULL, 0))
1704  return t->value;
1705  if (st->codecpar->codec_id != AV_CODEC_ID_NONE) {
1707  if (desc && desc->mime_types) {
1708  return desc->mime_types[0];
1709  } else if (st->codecpar->codec_id == AV_CODEC_ID_TEXT)
1710  return "text/plain";
1711  }
1712 
1713  return NULL;
1714 }
1715 
1717 {
1718  MatroskaMuxContext *mkv = s->priv_data;
1719  AVIOContext *dyn_cp = NULL, *pb = s->pb;
1720  int i, ret;
1721 
1722  if (!mkv->nb_attachments)
1723  return 0;
1724 
1725  ret = start_ebml_master_crc32(&dyn_cp, mkv);
1726  if (ret < 0)
1727  return ret;
1728 
1729  for (i = 0; i < s->nb_streams; i++) {
1730  const AVStream *st = s->streams[i];
1731  mkv_track *track = &mkv->tracks[i];
1732  ebml_master attached_file;
1733  const AVDictionaryEntry *t;
1734  const char *mimetype;
1735 
1737  continue;
1738 
1739  attached_file = start_ebml_master(dyn_cp, MATROSKA_ID_ATTACHEDFILE, 0);
1740 
1741  if (t = av_dict_get(st->metadata, "title", NULL, 0))
1743  if (!(t = av_dict_get(st->metadata, "filename", NULL, 0))) {
1744  av_log(s, AV_LOG_ERROR, "Attachment stream %d has no filename tag.\n", i);
1745  return AVERROR(EINVAL);
1746  }
1748 
1749  mimetype = get_mimetype(st);
1750  av_assert0(mimetype);
1751  put_ebml_string(dyn_cp, MATROSKA_ID_FILEMIMETYPE, mimetype);
1753  put_ebml_uid(dyn_cp, MATROSKA_ID_FILEUID, track->uid);
1754  end_ebml_master(dyn_cp, attached_file);
1755  }
1756  return end_ebml_master_crc32(pb, &dyn_cp, mkv,
1757  MATROSKA_ID_ATTACHMENTS, 0, 0, 1);
1758 }
1759 
1761 {
1762  const AVDictionaryEntry *duration = av_dict_get(s->metadata, "DURATION",
1763  NULL, 0);
1764  int64_t max = 0;
1765  int64_t us;
1766 
1767  if (duration && (av_parse_time(&us, duration->value, 1) == 0) && us > 0) {
1768  av_log(s, AV_LOG_DEBUG, "get_metadata_duration found duration in context metadata: %" PRId64 "\n", us);
1769  return us;
1770  }
1771 
1772  for (unsigned i = 0; i < s->nb_streams; i++) {
1773  int64_t us;
1774  duration = av_dict_get(s->streams[i]->metadata, "DURATION", NULL, 0);
1775 
1776  if (duration && (av_parse_time(&us, duration->value, 1) == 0))
1777  max = FFMAX(max, us);
1778  }
1779 
1780  av_log(s, AV_LOG_DEBUG, "get_metadata_duration returned: %" PRId64 "\n", max);
1781  return max;
1782 }
1783 
1785 {
1786  MatroskaMuxContext *mkv = s->priv_data;
1787  AVIOContext *pb = s->pb;
1789  const AVDictionaryEntry *tag;
1790  int ret, i, version = 2;
1791  int64_t creation_time;
1792 
1793  if (mkv->mode != MODE_WEBM ||
1794  av_dict_get(s->metadata, "stereo_mode", NULL, 0) ||
1795  av_dict_get(s->metadata, "alpha_mode", NULL, 0))
1796  version = 4;
1797 
1798  for (i = 0; i < s->nb_streams; i++) {
1799  if (s->streams[i]->codecpar->codec_id == AV_CODEC_ID_OPUS ||
1800  av_dict_get(s->streams[i]->metadata, "stereo_mode", NULL, 0) ||
1801  av_dict_get(s->streams[i]->metadata, "alpha_mode", NULL, 0))
1802  version = 4;
1803  }
1804 
1811  put_ebml_uint (pb, EBML_ID_DOCTYPEVERSION , version);
1813  end_ebml_master(pb, ebml_header);
1814 
1816  put_ebml_size_unknown(pb, 8);
1817  mkv->segment_offset = avio_tell(pb);
1818 
1819  // We write a SeekHead at the beginning to point to all other level
1820  // one elements (except Clusters).
1821  mkv_start_seekhead(mkv, pb);
1822 
1823  ret = start_ebml_master_crc32(&mkv->info.bc, mkv);
1824  if (ret < 0)
1825  return ret;
1826  pb = mkv->info.bc;
1827 
1829  if ((tag = av_dict_get(s->metadata, "title", NULL, 0)))
1831  if (!(s->flags & AVFMT_FLAG_BITEXACT)) {
1833  if ((tag = av_dict_get(s->metadata, "encoding_tool", NULL, 0)))
1835  else
1837 
1838  if (mkv->mode != MODE_WEBM)
1840  } else {
1841  const char *ident = "Lavf";
1844  }
1845 
1846  if (ff_parse_creation_time_metadata(s, &creation_time, 0) > 0) {
1847  // Adjust time so it's relative to 2001-01-01 and convert to nanoseconds.
1848  int64_t date_utc = (creation_time - 978307200000000LL) * 1000;
1849  uint8_t date_utc_buf[8];
1850  AV_WB64(date_utc_buf, date_utc);
1851  put_ebml_binary(pb, MATROSKA_ID_DATEUTC, date_utc_buf, 8);
1852  }
1853 
1854  // reserve space for the duration
1855  mkv->duration = 0;
1856  mkv->duration_offset = avio_tell(pb);
1857  if (!mkv->is_live) {
1858  int64_t metadata_duration = get_metadata_duration(s);
1859 
1860  if (s->duration > 0) {
1861  int64_t scaledDuration = av_rescale(s->duration, 1000, AV_TIME_BASE);
1862  put_ebml_float(pb, MATROSKA_ID_DURATION, scaledDuration);
1863  av_log(s, AV_LOG_DEBUG, "Write early duration from recording time = %" PRIu64 "\n", scaledDuration);
1864  } else if (metadata_duration > 0) {
1865  int64_t scaledDuration = av_rescale(metadata_duration, 1000, AV_TIME_BASE);
1866  put_ebml_float(pb, MATROSKA_ID_DURATION, scaledDuration);
1867  av_log(s, AV_LOG_DEBUG, "Write early duration from metadata = %" PRIu64 "\n", scaledDuration);
1868  } else if (s->pb->seekable & AVIO_SEEKABLE_NORMAL) {
1869  put_ebml_void(pb, 11); // assumes double-precision float to be written
1870  }
1871  }
1872  ret = end_ebml_master_crc32_tentatively(s->pb, &mkv->info,
1873  mkv, MATROSKA_ID_INFO);
1874  if (ret < 0)
1875  return ret;
1876  pb = s->pb;
1877 
1878  ret = mkv_write_tracks(s);
1879  if (ret < 0)
1880  return ret;
1881 
1882  ret = mkv_write_chapters(s);
1883  if (ret < 0)
1884  return ret;
1885 
1886  if (mkv->mode != MODE_WEBM) {
1887  ret = mkv_write_attachments(s);
1888  if (ret < 0)
1889  return ret;
1890  }
1891 
1892  /* Must come after mkv_write_chapters() to write chapter tags
1893  * into the same Tags element as the other tags. */
1894  ret = mkv_write_tags(s);
1895  if (ret < 0)
1896  return ret;
1897 
1898  if (!IS_SEEKABLE(pb, mkv)) {
1899  ret = mkv_write_seekhead(pb, mkv, 0, avio_tell(pb));
1900  if (ret < 0)
1901  return ret;
1902  }
1903 
1904  if (s->metadata_header_padding > 0) {
1905  if (s->metadata_header_padding == 1)
1908  }
1909 
1910  if (mkv->reserve_cues_space) {
1911  if (IS_SEEKABLE(pb, mkv)) {
1912  mkv->cues_pos = avio_tell(pb);
1913  if (mkv->reserve_cues_space == 1)
1914  mkv->reserve_cues_space++;
1916  } else
1917  mkv->reserve_cues_space = -1;
1918  }
1919 
1921  mkv->cur_audio_pkt.size = 0;
1922  mkv->cluster_pos = -1;
1923 
1924  // start a new cluster every 5 MB or 5 sec, or 32k / 1 sec for streaming or
1925  // after 4k and on a keyframe
1926  if (IS_SEEKABLE(pb, mkv)) {
1927  if (mkv->cluster_time_limit < 0)
1928  mkv->cluster_time_limit = 5000;
1929  if (mkv->cluster_size_limit < 0)
1930  mkv->cluster_size_limit = 5 * 1024 * 1024;
1931  } else {
1932  if (mkv->cluster_time_limit < 0)
1933  mkv->cluster_time_limit = 1000;
1934  if (mkv->cluster_size_limit < 0)
1935  mkv->cluster_size_limit = 32 * 1024;
1936  }
1937 
1938  return 0;
1939 }
1940 
1941 static int mkv_blockgroup_size(int pkt_size, int track_num_size)
1942 {
1943  int size = pkt_size + track_num_size + 3;
1944  size += ebml_length_size(size);
1945  size += 2; // EBML ID for block and block duration
1946  size += 9; // max size of block duration incl. length field
1947  return size;
1948 }
1949 
1950 static int mkv_strip_wavpack(const uint8_t *src, uint8_t **pdst, int *size)
1951 {
1952  uint8_t *dst;
1953  int srclen = *size;
1954  int offset = 0;
1955  int ret;
1956 
1957  dst = av_malloc(srclen);
1958  if (!dst)
1959  return AVERROR(ENOMEM);
1960 
1961  while (srclen >= WV_HEADER_SIZE) {
1962  WvHeader header;
1963 
1964  ret = ff_wv_parse_header(&header, src);
1965  if (ret < 0)
1966  goto fail;
1967  src += WV_HEADER_SIZE;
1968  srclen -= WV_HEADER_SIZE;
1969 
1970  if (srclen < header.blocksize) {
1971  ret = AVERROR_INVALIDDATA;
1972  goto fail;
1973  }
1974 
1975  if (header.initial) {
1976  AV_WL32(dst + offset, header.samples);
1977  offset += 4;
1978  }
1979  AV_WL32(dst + offset, header.flags);
1980  AV_WL32(dst + offset + 4, header.crc);
1981  offset += 8;
1982 
1983  if (!(header.initial && header.final)) {
1984  AV_WL32(dst + offset, header.blocksize);
1985  offset += 4;
1986  }
1987 
1988  memcpy(dst + offset, src, header.blocksize);
1989  src += header.blocksize;
1990  srclen -= header.blocksize;
1991  offset += header.blocksize;
1992  }
1993 
1994  *pdst = dst;
1995  *size = offset;
1996 
1997  return 0;
1998 fail:
1999  av_freep(&dst);
2000  return ret;
2001 }
2002 
2004  uint32_t blockid, const AVPacket *pkt, int keyframe)
2005 {
2006  MatroskaMuxContext *mkv = s->priv_data;
2008  mkv_track *track = &mkv->tracks[pkt->stream_index];
2009  uint8_t *data = NULL, *side_data = NULL;
2010  int err = 0, offset = 0, size = pkt->size, side_data_size = 0;
2011  int64_t ts = track->write_dts ? pkt->dts : pkt->pts;
2012  uint64_t additional_id;
2013  int64_t discard_padding = 0;
2014  unsigned track_number = track->track_num;
2015  ebml_master block_group, block_additions, block_more;
2016 
2017  ts += track->ts_offset;
2018 
2019  /* The following string is identical to the one in mkv_write_vtt_blocks
2020  * so that only one copy needs to exist in binaries. */
2021  av_log(s, AV_LOG_DEBUG,
2022  "Writing block of size %d with pts %" PRId64 ", dts %" PRId64 ", "
2023  "duration %" PRId64 " at relative offset %" PRId64 " in cluster "
2024  "at offset %" PRId64 ". TrackNumber %u, keyframe %d\n",
2025  pkt->size, pkt->pts, pkt->dts, pkt->duration, avio_tell(pb),
2026  mkv->cluster_pos, track_number, keyframe != 0);
2027 
2028  if (par->codec_id == AV_CODEC_ID_H264 && par->extradata_size > 0 &&
2029  (AV_RB24(par->extradata) == 1 || AV_RB32(par->extradata) == 1)) {
2030  err = ff_avc_parse_nal_units_buf(pkt->data, &data, &size);
2031  } else if (par->codec_id == AV_CODEC_ID_HEVC && par->extradata_size > 6 &&
2032  (AV_RB24(par->extradata) == 1 || AV_RB32(par->extradata) == 1)) {
2033  /* extradata is Annex B, assume the bitstream is too and convert it */
2034  err = ff_hevc_annexb2mp4_buf(pkt->data, &data, &size, 0, NULL);
2035  } else if (par->codec_id == AV_CODEC_ID_AV1) {
2036  err = ff_av1_filter_obus_buf(pkt->data, &data, &size, &offset);
2037  } else if (par->codec_id == AV_CODEC_ID_WAVPACK) {
2038  err = mkv_strip_wavpack(pkt->data, &data, &size);
2039  } else
2040  data = pkt->data;
2041 
2042  if (err < 0) {
2043  av_log(s, AV_LOG_ERROR, "Error when reformatting data of "
2044  "a packet from stream %d.\n", pkt->stream_index);
2045  return err;
2046  }
2047 
2048  if (par->codec_id == AV_CODEC_ID_PRORES && size >= 8) {
2049  /* Matroska specification requires to remove the first QuickTime atom
2050  */
2051  size -= 8;
2052  offset = 8;
2053  }
2054 
2055  side_data = av_packet_get_side_data(pkt,
2057  &side_data_size);
2058  if (side_data && side_data_size >= 10) {
2059  discard_padding = av_rescale_q(AV_RL32(side_data + 4),
2060  (AVRational){1, par->sample_rate},
2061  (AVRational){1, 1000000000});
2062  }
2063 
2064  side_data = av_packet_get_side_data(pkt,
2066  &side_data_size);
2067  if (side_data) {
2068  // Only the Codec-specific BlockMore (id == 1) is currently supported.
2069  if (side_data_size < 8 || (additional_id = AV_RB64(side_data)) != 1) {
2070  side_data_size = 0;
2071  } else {
2072  side_data += 8;
2073  side_data_size -= 8;
2074  }
2075  }
2076 
2077  if (side_data_size || discard_padding) {
2078  block_group = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP, 0);
2079  blockid = MATROSKA_ID_BLOCK;
2080  }
2081 
2082  put_ebml_id(pb, blockid);
2083  put_ebml_length(pb, size + track->track_num_size + 3, 0);
2084  put_ebml_num(pb, track_number, track->track_num_size);
2085  avio_wb16(pb, ts - mkv->cluster_pts);
2086  avio_w8(pb, (blockid == MATROSKA_ID_SIMPLEBLOCK && keyframe) ? (1 << 7) : 0);
2087  avio_write(pb, data + offset, size);
2088  if (data != pkt->data)
2089  av_free(data);
2090 
2091  if (blockid == MATROSKA_ID_BLOCK && !keyframe)
2093  track->last_timestamp = ts;
2094 
2095  if (discard_padding)
2096  put_ebml_sint(pb, MATROSKA_ID_DISCARDPADDING, discard_padding);
2097 
2098  if (side_data_size) {
2099  block_additions = start_ebml_master(pb, MATROSKA_ID_BLOCKADDITIONS, 0);
2100  block_more = start_ebml_master(pb, MATROSKA_ID_BLOCKMORE, 0);
2101  /* Until dbc50f8a our demuxer used a wrong default value
2102  * of BlockAddID, so we write it unconditionally. */
2103  put_ebml_uint (pb, MATROSKA_ID_BLOCKADDID, additional_id);
2105  side_data, side_data_size);
2106  end_ebml_master(pb, block_more);
2107  end_ebml_master(pb, block_additions);
2108  }
2109  if (side_data_size || discard_padding)
2110  end_ebml_master(pb, block_group);
2111 
2112  return 0;
2113 }
2114 
2116 {
2117  MatroskaMuxContext *mkv = s->priv_data;
2118  mkv_track *track = &mkv->tracks[pkt->stream_index];
2119  ebml_master blockgroup;
2120  int id_size, settings_size, size;
2121  const char *id, *settings;
2122  int64_t ts = track->write_dts ? pkt->dts : pkt->pts;
2123  const int flags = 0;
2124 
2125  id_size = 0;
2127  &id_size);
2128  id = id ? id : "";
2129 
2130  settings_size = 0;
2132  &settings_size);
2133  settings = settings ? settings : "";
2134 
2135  size = id_size + 1 + settings_size + 1 + pkt->size;
2136 
2137  /* The following string is identical to the one in mkv_write_block so that
2138  * only one copy needs to exist in binaries. */
2139  av_log(s, AV_LOG_DEBUG,
2140  "Writing block of size %d with pts %" PRId64 ", dts %" PRId64 ", "
2141  "duration %" PRId64 " at relative offset %" PRId64 " in cluster "
2142  "at offset %" PRId64 ". TrackNumber %u, keyframe %d\n",
2143  size, pkt->pts, pkt->dts, pkt->duration, avio_tell(pb),
2144  mkv->cluster_pos, track->track_num, 1);
2145 
2146  blockgroup = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP,
2147  mkv_blockgroup_size(size, track->track_num_size));
2148 
2150  put_ebml_length(pb, size + track->track_num_size + 3, 0);
2151  put_ebml_num(pb, track->track_num, track->track_num_size);
2152  avio_wb16(pb, ts - mkv->cluster_pts);
2153  avio_w8(pb, flags);
2154  avio_printf(pb, "%.*s\n%.*s\n%.*s", id_size, id, settings_size, settings, pkt->size, pkt->data);
2155 
2157  end_ebml_master(pb, blockgroup);
2158 
2159  return pkt->duration;
2160 }
2161 
2163 {
2164  MatroskaMuxContext *mkv = s->priv_data;
2165  int ret;
2166 
2167  if (!mkv->have_video) {
2168  for (unsigned i = 0; i < s->nb_streams; i++)
2169  mkv->tracks[i].has_cue = 0;
2170  }
2171  mkv->cluster_pos = -1;
2172  ret = end_ebml_master_crc32(s->pb, &mkv->cluster_bc, mkv,
2173  MATROSKA_ID_CLUSTER, 0, 1, 0);
2174  if (ret < 0)
2175  return ret;
2176 
2178  return 0;
2179 }
2180 
2182 {
2183  MatroskaMuxContext *mkv = s->priv_data;
2184  mkv_track *track = &mkv->tracks[pkt->stream_index];
2186  uint8_t *side_data;
2187  int side_data_size = 0, ret;
2188 
2190  &side_data_size);
2191 
2192  switch (par->codec_id) {
2193  case AV_CODEC_ID_AAC:
2194  if (side_data_size && mkv->track.bc) {
2195  int filler, output_sample_rate = 0;
2196  ret = get_aac_sample_rates(s, mkv, side_data, side_data_size,
2197  &track->sample_rate, &output_sample_rate);
2198  if (ret < 0)
2199  return ret;
2200  if (!output_sample_rate)
2201  output_sample_rate = track->sample_rate; // Space is already reserved, so it's this or a void element.
2202  ret = ff_alloc_extradata(par, side_data_size);
2203  if (ret < 0)
2204  return ret;
2205  memcpy(par->extradata, side_data, side_data_size);
2206  avio_seek(mkv->track.bc, track->codecpriv_offset, SEEK_SET);
2207  mkv_write_codecprivate(s, mkv->track.bc, par, 1, 0);
2208  filler = MAX_PCE_SIZE + 2 + 4 - (avio_tell(mkv->track.bc) - track->codecpriv_offset);
2209  if (filler)
2210  put_ebml_void(mkv->track.bc, filler);
2211  avio_seek(mkv->track.bc, track->sample_rate_offset, SEEK_SET);
2213  put_ebml_float(mkv->track.bc, MATROSKA_ID_AUDIOOUTSAMPLINGFREQ, output_sample_rate);
2214  } else if (!par->extradata_size && !track->sample_rate) {
2215  // No extradata (codecpar or packet side data).
2216  av_log(s, AV_LOG_ERROR, "Error parsing AAC extradata, unable to determine samplerate.\n");
2217  return AVERROR(EINVAL);
2218  }
2219  break;
2220  case AV_CODEC_ID_FLAC:
2221  if (side_data_size && mkv->track.bc) {
2222  uint8_t *old_extradata = par->extradata;
2223  if (side_data_size != par->extradata_size) {
2224  av_log(s, AV_LOG_ERROR, "Invalid FLAC STREAMINFO metadata for output stream %d\n",
2225  pkt->stream_index);
2226  return AVERROR(EINVAL);
2227  }
2228  par->extradata = side_data;
2229  avio_seek(mkv->track.bc, track->codecpriv_offset, SEEK_SET);
2230  mkv_write_codecprivate(s, mkv->track.bc, par, 1, 0);
2231  par->extradata = old_extradata;
2232  }
2233  break;
2234  // FIXME: Remove the following once libaom starts propagating extradata during init()
2235  // See https://bugs.chromium.org/p/aomedia/issues/detail?id=2012
2236  case AV_CODEC_ID_AV1:
2237  if (side_data_size && mkv->track.bc && !par->extradata_size) {
2238  AVIOContext *dyn_cp;
2239  uint8_t *codecpriv;
2240  int codecpriv_size;
2241  ret = avio_open_dyn_buf(&dyn_cp);
2242  if (ret < 0)
2243  return ret;
2244  ff_isom_write_av1c(dyn_cp, side_data, side_data_size);
2245  codecpriv_size = avio_get_dyn_buf(dyn_cp, &codecpriv);
2246  if ((ret = dyn_cp->error) < 0 ||
2247  !codecpriv_size && (ret = AVERROR_INVALIDDATA)) {
2248  ffio_free_dyn_buf(&dyn_cp);
2249  return ret;
2250  }
2251  avio_seek(mkv->track.bc, track->codecpriv_offset, SEEK_SET);
2252  // Do not write the OBUs as we don't have space saved for them
2253  put_ebml_binary(mkv->track.bc, MATROSKA_ID_CODECPRIVATE, codecpriv, 4);
2254  ffio_free_dyn_buf(&dyn_cp);
2255  ret = ff_alloc_extradata(par, side_data_size);
2256  if (ret < 0)
2257  return ret;
2258  memcpy(par->extradata, side_data, side_data_size);
2259  } else if (!par->extradata_size)
2260  return AVERROR_INVALIDDATA;
2261  break;
2262  default:
2263  if (side_data_size)
2264  av_log(s, AV_LOG_DEBUG, "Ignoring new extradata in a packet for stream %d.\n", pkt->stream_index);
2265  break;
2266  }
2267 
2268  return 0;
2269 }
2270 
2272 {
2273  MatroskaMuxContext *mkv = s->priv_data;
2274  AVIOContext *pb;
2276  mkv_track *track = &mkv->tracks[pkt->stream_index];
2277  int keyframe = !!(pkt->flags & AV_PKT_FLAG_KEY);
2278  int duration = pkt->duration;
2279  int ret;
2280  int64_t ts = track->write_dts ? pkt->dts : pkt->pts;
2281  int64_t relative_packet_pos;
2282 
2283  if (ts == AV_NOPTS_VALUE) {
2284  av_log(s, AV_LOG_ERROR, "Can't write packet with unknown timestamp\n");
2285  return AVERROR(EINVAL);
2286  }
2287  ts += track->ts_offset;
2288 
2289  if (mkv->cluster_pos != -1) {
2290  int64_t cluster_time = ts - mkv->cluster_pts;
2291  if ((int16_t)cluster_time != cluster_time) {
2292  ret = mkv_end_cluster(s);
2293  if (ret < 0)
2294  return ret;
2295  av_log(s, AV_LOG_WARNING, "Starting new cluster due to timestamp\n");
2296  }
2297  }
2298 
2299  if (mkv->cluster_pos == -1) {
2300  ret = start_ebml_master_crc32(&mkv->cluster_bc, mkv);
2301  if (ret < 0)
2302  return ret;
2303  mkv->cluster_pos = avio_tell(s->pb);
2305  mkv->cluster_pts = FFMAX(0, ts);
2306  av_log(s, AV_LOG_DEBUG,
2307  "Starting new cluster with timestamp "
2308  "%" PRId64 " at offset %" PRId64 " bytes\n",
2309  mkv->cluster_pts, mkv->cluster_pos);
2310  }
2311  pb = mkv->cluster_bc;
2312 
2313  relative_packet_pos = avio_tell(pb);
2314 
2315  if (par->codec_type != AVMEDIA_TYPE_SUBTITLE) {
2316  ret = mkv_write_block(s, pb, MATROSKA_ID_SIMPLEBLOCK, pkt, keyframe);
2317  if (ret < 0)
2318  return ret;
2319  if (keyframe && IS_SEEKABLE(s->pb, mkv) &&
2320  (par->codec_type == AVMEDIA_TYPE_VIDEO || !mkv->have_video && !track->has_cue)) {
2321  ret = mkv_add_cuepoint(mkv, pkt->stream_index, ts,
2322  mkv->cluster_pos, relative_packet_pos, -1);
2323  if (ret < 0)
2324  return ret;
2325  track->has_cue = 1;
2326  }
2327  } else {
2328  if (par->codec_id == AV_CODEC_ID_WEBVTT) {
2329  duration = mkv_write_vtt_blocks(s, pb, pkt);
2330  } else {
2333  track->track_num_size));
2334 
2335 #if FF_API_CONVERGENCE_DURATION
2337  /* For backward compatibility, prefer convergence_duration. */
2338  if (pkt->convergence_duration > 0) {
2339  duration = pkt->convergence_duration;
2340  }
2342 #endif
2343  /* All subtitle blocks are considered to be keyframes. */
2344  mkv_write_block(s, pb, MATROSKA_ID_BLOCK, pkt, 1);
2346  end_ebml_master(pb, blockgroup);
2347  }
2348 
2349  if (IS_SEEKABLE(s->pb, mkv)) {
2350  ret = mkv_add_cuepoint(mkv, pkt->stream_index, ts,
2351  mkv->cluster_pos, relative_packet_pos, duration);
2352  if (ret < 0)
2353  return ret;
2354  }
2355  }
2356 
2357  mkv->duration = FFMAX(mkv->duration, ts + duration);
2358  track->duration = FFMAX(track->duration, ts + duration);
2359 
2360  return 0;
2361 }
2362 
2364 {
2365  MatroskaMuxContext *mkv = s->priv_data;
2367  int keyframe = !!(pkt->flags & AV_PKT_FLAG_KEY);
2368  int cluster_size;
2369  int64_t cluster_time;
2370  int ret;
2371  int start_new_cluster;
2372 
2373  ret = mkv_check_new_extra_data(s, pkt);
2374  if (ret < 0)
2375  return ret;
2376 
2377  if (mkv->cluster_pos != -1) {
2378  if (mkv->tracks[pkt->stream_index].write_dts)
2379  cluster_time = pkt->dts - mkv->cluster_pts;
2380  else
2381  cluster_time = pkt->pts - mkv->cluster_pts;
2382  cluster_time += mkv->tracks[pkt->stream_index].ts_offset;
2383 
2384  cluster_size = avio_tell(mkv->cluster_bc);
2385 
2386  if (mkv->is_dash && codec_type == AVMEDIA_TYPE_VIDEO) {
2387  // WebM DASH specification states that the first block of
2388  // every Cluster has to be a key frame. So for DASH video,
2389  // we only create a Cluster on seeing key frames.
2390  start_new_cluster = keyframe;
2391  } else if (mkv->is_dash && codec_type == AVMEDIA_TYPE_AUDIO &&
2392  cluster_time > mkv->cluster_time_limit) {
2393  // For DASH audio, we create a Cluster based on cluster_time_limit.
2394  start_new_cluster = 1;
2395  } else if (!mkv->is_dash &&
2396  (cluster_size > mkv->cluster_size_limit ||
2397  cluster_time > mkv->cluster_time_limit ||
2398  (codec_type == AVMEDIA_TYPE_VIDEO && keyframe &&
2399  cluster_size > 4 * 1024))) {
2400  start_new_cluster = 1;
2401  } else
2402  start_new_cluster = 0;
2403 
2404  if (start_new_cluster) {
2405  ret = mkv_end_cluster(s);
2406  if (ret < 0)
2407  return ret;
2408  }
2409  }
2410 
2411  if (!mkv->cluster_pos)
2412  avio_write_marker(s->pb,
2415 
2416  // check if we have an audio packet cached
2417  if (mkv->cur_audio_pkt.size > 0) {
2418  ret = mkv_write_packet_internal(s, &mkv->cur_audio_pkt);
2420  if (ret < 0) {
2421  av_log(s, AV_LOG_ERROR,
2422  "Could not write cached audio packet ret:%d\n", ret);
2423  return ret;
2424  }
2425  }
2426 
2427  // buffer an audio packet to ensure the packet containing the video
2428  // keyframe's timecode is contained in the same cluster for WebM
2429  if (codec_type == AVMEDIA_TYPE_AUDIO) {
2430  if (pkt->size > 0)
2431  ret = av_packet_ref(&mkv->cur_audio_pkt, pkt);
2432  } else
2433  ret = mkv_write_packet_internal(s, pkt);
2434  return ret;
2435 }
2436 
2438 {
2439  MatroskaMuxContext *mkv = s->priv_data;
2440 
2441  if (!pkt) {
2442  if (mkv->cluster_pos != -1) {
2443  int ret = mkv_end_cluster(s);
2444  if (ret < 0)
2445  return ret;
2446  av_log(s, AV_LOG_DEBUG,
2447  "Flushing cluster at offset %" PRIu64 " bytes\n",
2448  avio_tell(s->pb));
2449  }
2450  return 1;
2451  }
2452  return mkv_write_packet(s, pkt);
2453 }
2454 
2456 {
2457  MatroskaMuxContext *mkv = s->priv_data;
2458  AVIOContext *pb = s->pb;
2459  int64_t endpos, ret64;
2460  int ret, ret2 = 0;
2461 
2462  // check if we have an audio packet cached
2463  if (mkv->cur_audio_pkt.size > 0) {
2464  ret = mkv_write_packet_internal(s, &mkv->cur_audio_pkt);
2465  if (ret < 0) {
2466  av_log(s, AV_LOG_ERROR,
2467  "Could not write cached audio packet ret:%d\n", ret);
2468  return ret;
2469  }
2470  }
2471 
2472  if (mkv->cluster_pos != -1) {
2473  ret = end_ebml_master_crc32(pb, &mkv->cluster_bc, mkv,
2474  MATROSKA_ID_CLUSTER, 0, 0, 0);
2475  if (ret < 0)
2476  return ret;
2477  }
2478 
2479  ret = mkv_write_chapters(s);
2480  if (ret < 0)
2481  return ret;
2482 
2483  if (!IS_SEEKABLE(pb, mkv))
2484  return 0;
2485 
2486  endpos = avio_tell(pb);
2487 
2488  if (mkv->cues.num_entries && mkv->reserve_cues_space >= 0) {
2489  AVIOContext *cues = NULL;
2490  uint64_t size;
2491  int length_size = 0;
2492 
2493  ret = start_ebml_master_crc32(&cues, mkv);
2494  if (ret < 0)
2495  return ret;
2496 
2497  ret = mkv_assemble_cues(s->streams, cues, &mkv->cues,
2498  mkv->tracks, s->nb_streams);
2499  if (ret < 0) {
2500  ffio_free_dyn_buf(&cues);
2501  return ret;
2502  }
2503 
2504  if (mkv->reserve_cues_space) {
2505  size = avio_tell(cues);
2506  length_size = ebml_length_size(size);
2507  size += 4 + length_size;
2508  if (mkv->reserve_cues_space < size) {
2510  "Insufficient space reserved for Cues: "
2511  "%d < %"PRIu64". No Cues will be output.\n",
2512  mkv->reserve_cues_space, size);
2513  ret2 = AVERROR(EINVAL);
2514  goto after_cues;
2515  } else {
2516  if ((ret64 = avio_seek(pb, mkv->cues_pos, SEEK_SET)) < 0) {
2517  ffio_free_dyn_buf(&cues);
2518  return ret64;
2519  }
2520  if (mkv->reserve_cues_space == size + 1) {
2521  /* There is no way to reserve a single byte because
2522  * the minimal size of an EBML Void element is 2
2523  * (1 byte ID, 1 byte length field). This problem
2524  * is solved by writing the Cues' length field on
2525  * one byte more than necessary. */
2526  length_size++;
2527  size++;
2528  }
2529  }
2530  }
2531  ret = end_ebml_master_crc32(pb, &cues, mkv, MATROSKA_ID_CUES,
2532  length_size, 0, 1);
2533  if (ret < 0)
2534  return ret;
2535  if (mkv->reserve_cues_space) {
2536  if (size < mkv->reserve_cues_space)
2537  put_ebml_void(pb, mkv->reserve_cues_space - size);
2538  } else
2539  endpos = avio_tell(pb);
2540  }
2541 
2542 after_cues:
2543  /* Lengths greater than (1ULL << 56) - 1 can't be represented
2544  * via an EBML number, so leave the unknown length field. */
2545  if (endpos - mkv->segment_offset < (1ULL << 56) - 1) {
2546  if ((ret64 = avio_seek(pb, mkv->segment_offset - 8, SEEK_SET)) < 0)
2547  return ret64;
2548  put_ebml_length(pb, endpos - mkv->segment_offset, 8);
2549  }
2550 
2551  ret = mkv_write_seekhead(pb, mkv, 1, mkv->info.pos);
2552  if (ret < 0)
2553  return ret;
2554 
2555  if (mkv->info.bc) {
2556  // update the duration
2557  av_log(s, AV_LOG_DEBUG, "end duration = %" PRIu64 "\n", mkv->duration);
2558  avio_seek(mkv->info.bc, mkv->duration_offset, SEEK_SET);
2560  ret = end_ebml_master_crc32(pb, &mkv->info.bc, mkv,
2561  MATROSKA_ID_INFO, 0, 0, 0);
2562  if (ret < 0)
2563  return ret;
2564  }
2565 
2566  if (mkv->track.bc) {
2567  // write Tracks master
2568  avio_seek(pb, mkv->track.pos, SEEK_SET);
2569  ret = end_ebml_master_crc32(pb, &mkv->track.bc, mkv,
2570  MATROSKA_ID_TRACKS, 0, 0, 0);
2571  if (ret < 0)
2572  return ret;
2573  }
2574 
2575  // update stream durations
2576  if (mkv->tags.bc) {
2577  int i;
2578  for (i = 0; i < s->nb_streams; ++i) {
2579  const AVStream *st = s->streams[i];
2580  const mkv_track *track = &mkv->tracks[i];
2581 
2582  if (track->duration_offset > 0) {
2583  double duration_sec = track->duration * av_q2d(st->time_base);
2584  char duration_string[20] = "";
2585 
2586  av_log(s, AV_LOG_DEBUG, "stream %d end duration = %" PRIu64 "\n", i,
2587  track->duration);
2588 
2589  avio_seek(mkv->tags.bc, track->duration_offset, SEEK_SET);
2590 
2591  snprintf(duration_string, 20, "%02d:%02d:%012.9f",
2592  (int) duration_sec / 3600, ((int) duration_sec / 60) % 60,
2593  fmod(duration_sec, 60));
2594 
2595  put_ebml_binary(mkv->tags.bc, MATROSKA_ID_TAGSTRING, duration_string, 20);
2596  }
2597  }
2598 
2599  avio_seek(pb, mkv->tags.pos, SEEK_SET);
2600  ret = end_ebml_master_crc32(pb, &mkv->tags.bc, mkv,
2601  MATROSKA_ID_TAGS, 0, 0, 0);
2602  if (ret < 0)
2603  return ret;
2604  }
2605 
2606  avio_seek(pb, endpos, SEEK_SET);
2607 
2608  return ret2;
2609 }
2610 
2611 static int mkv_query_codec(enum AVCodecID codec_id, int std_compliance)
2612 {
2613  int i;
2614  for (i = 0; ff_mkv_codec_tags[i].id != AV_CODEC_ID_NONE; i++)
2615  if (ff_mkv_codec_tags[i].id == codec_id)
2616  return 1;
2617 
2618  if (std_compliance < FF_COMPLIANCE_NORMAL) {
2619  enum AVMediaType type = avcodec_get_type(codec_id);
2620  // mkv theoretically supports any video/audio through VFW/ACM
2621  if (type == AVMEDIA_TYPE_VIDEO || type == AVMEDIA_TYPE_AUDIO)
2622  return 1;
2623  }
2624 
2625  return 0;
2626 }
2627 
2628 static int webm_query_codec(enum AVCodecID codec_id, int std_compliance)
2629 {
2630  int i;
2631  for (i = 0; ff_webm_codec_tags[i].id != AV_CODEC_ID_NONE; i++)
2632  if (ff_webm_codec_tags[i].id == codec_id)
2633  return 1;
2634 
2635  return 0;
2636 }
2637 
2638 static uint64_t mkv_get_uid(const mkv_track *tracks, int i, AVLFG *c)
2639 {
2640  while (1) {
2641  uint64_t uid;
2642  int k;
2643  uid = (uint64_t)av_lfg_get(c) << 32;
2644  uid |= av_lfg_get(c);
2645  if (!uid)
2646  continue;
2647  for (k = 0; k < i; k++) {
2648  if (tracks[k].uid == uid)
2649  break;
2650  }
2651  if (k == i)
2652  return uid;
2653  }
2654 }
2655 
2656 static int mkv_init(struct AVFormatContext *s)
2657 {
2658  MatroskaMuxContext *mkv = s->priv_data;
2659  AVLFG c;
2660  unsigned nb_tracks = 0;
2661  int i;
2662 
2663  for (i = 0; i < s->nb_streams; i++) {
2664  if (s->streams[i]->codecpar->codec_id == AV_CODEC_ID_ATRAC3 ||
2670  av_log(s, AV_LOG_ERROR,
2671  "The Matroska muxer does not yet support muxing %s\n",
2673  return AVERROR_PATCHWELCOME;
2674  }
2675  }
2676 
2677  if (s->avoid_negative_ts < 0) {
2678  s->avoid_negative_ts = 1;
2680  }
2681 
2682  if (!strcmp(s->oformat->name, "webm")) {
2683  mkv->mode = MODE_WEBM;
2684  mkv->write_crc = 0;
2685  } else
2686  mkv->mode = MODE_MATROSKAv2;
2687 
2688  mkv->tracks = av_mallocz_array(s->nb_streams, sizeof(*mkv->tracks));
2689  if (!mkv->tracks)
2690  return AVERROR(ENOMEM);
2691 
2692  if (!(s->flags & AVFMT_FLAG_BITEXACT)) {
2694 
2695  // Calculate the SegmentUID now in order not to waste our random seed.
2696  for (i = 0; i < 4; i++)
2697  mkv->segment_uid[i] = av_lfg_get(&c);
2698  }
2699 
2700  for (i = 0; i < s->nb_streams; i++) {
2701  AVStream *st = s->streams[i];
2702  mkv_track *track = &mkv->tracks[i];
2703 
2704  if (s->flags & AVFMT_FLAG_BITEXACT) {
2705  track->uid = i + 1;
2706  } else {
2707  track->uid = mkv_get_uid(mkv->tracks, i, &c);
2708  }
2709 
2710  // ms precision is the de-facto standard timescale for mkv files
2711  avpriv_set_pts_info(st, 64, 1, 1000);
2712 
2714  if (mkv->mode == MODE_WEBM) {
2715  av_log(s, AV_LOG_WARNING, "Stream %d will be ignored "
2716  "as WebM doesn't support attachments.\n", i);
2717  } else if (!get_mimetype(st)) {
2718  av_log(s, AV_LOG_ERROR, "Attachment stream %d has no mimetype "
2719  "tag and it cannot be deduced from the codec id.\n", i);
2720  return AVERROR(EINVAL);
2721  }
2722  mkv->nb_attachments++;
2723  continue;
2724  }
2725 
2726  nb_tracks++;
2727  track->track_num = mkv->is_dash ? mkv->dash_track_number : nb_tracks;
2728  track->track_num_size = ebml_num_size(track->track_num);
2729  }
2730 
2731  if (mkv->is_dash && nb_tracks != 1)
2732  return AVERROR(EINVAL);
2733 
2734  return 0;
2735 }
2736 
2737 static int mkv_check_bitstream(struct AVFormatContext *s, const AVPacket *pkt)
2738 {
2739  int ret = 1;
2740  AVStream *st = s->streams[pkt->stream_index];
2741 
2742  if (st->codecpar->codec_id == AV_CODEC_ID_AAC) {
2743  if (pkt->size > 2 && (AV_RB16(pkt->data) & 0xfff0) == 0xfff0)
2744  ret = ff_stream_add_bitstream_filter(st, "aac_adtstoasc", NULL);
2745  } else if (st->codecpar->codec_id == AV_CODEC_ID_VP9) {
2746  ret = ff_stream_add_bitstream_filter(st, "vp9_superframe", NULL);
2747  }
2748 
2749  return ret;
2750 }
2751 
2753  { AV_CODEC_ID_ALAC, 0XFFFFFFFF },
2754  { AV_CODEC_ID_MLP, 0xFFFFFFFF },
2755  { AV_CODEC_ID_OPUS, 0xFFFFFFFF },
2756  { AV_CODEC_ID_PCM_S16BE, 0xFFFFFFFF },
2757  { AV_CODEC_ID_PCM_S24BE, 0xFFFFFFFF },
2758  { AV_CODEC_ID_PCM_S32BE, 0xFFFFFFFF },
2759  { AV_CODEC_ID_QDMC, 0xFFFFFFFF },
2760  { AV_CODEC_ID_QDM2, 0xFFFFFFFF },
2761  { AV_CODEC_ID_RA_144, 0xFFFFFFFF },
2762  { AV_CODEC_ID_RA_288, 0xFFFFFFFF },
2763  { AV_CODEC_ID_COOK, 0xFFFFFFFF },
2764  { AV_CODEC_ID_TRUEHD, 0xFFFFFFFF },
2765  { AV_CODEC_ID_NONE, 0xFFFFFFFF }
2766 };
2767 
2769  { AV_CODEC_ID_RV10, 0xFFFFFFFF },
2770  { AV_CODEC_ID_RV20, 0xFFFFFFFF },
2771  { AV_CODEC_ID_RV30, 0xFFFFFFFF },
2772  { AV_CODEC_ID_NONE, 0xFFFFFFFF }
2773 };
2774 
2776  { AV_CODEC_ID_DVB_SUBTITLE, 0xFFFFFFFF },
2777  { AV_CODEC_ID_DVD_SUBTITLE, 0xFFFFFFFF },
2778  { AV_CODEC_ID_HDMV_PGS_SUBTITLE, 0xFFFFFFFF },
2779  { AV_CODEC_ID_NONE, 0xFFFFFFFF }
2780 };
2781 
2782 #define OFFSET(x) offsetof(MatroskaMuxContext, x)
2783 #define FLAGS AV_OPT_FLAG_ENCODING_PARAM
2784 static const AVOption options[] = {
2785  { "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 },
2786  { "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 },
2787  { "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 },
2788  { "dash", "Create a WebM file conforming to WebM DASH specification", OFFSET(is_dash), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, FLAGS },
2789  { "dash_track_number", "Track number for the DASH stream", OFFSET(dash_track_number), AV_OPT_TYPE_INT, { .i64 = 1 }, 1, INT_MAX, FLAGS },
2790  { "live", "Write files assuming it is a live stream.", OFFSET(is_live), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, FLAGS },
2791  { "allow_raw_vfw", "allow RAW VFW mode", OFFSET(allow_raw_vfw), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, FLAGS },
2792  { "write_crc32", "write a CRC32 element inside every Level 1 element", OFFSET(write_crc), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, FLAGS },
2793  { "default_mode", "Controls how a track's FlagDefault is inferred", OFFSET(default_mode), AV_OPT_TYPE_INT, { .i64 = DEFAULT_MODE_INFER }, DEFAULT_MODE_INFER, DEFAULT_MODE_PASSTHROUGH, FLAGS, "default_mode" },
2794  { "infer", "For each track type, mark the first 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, "default_mode" },
2795  { "infer_no_subs", "For each track type, mark the first 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, "default_mode" },
2796  { "passthrough", "Use the disposition flag as-is", 0, AV_OPT_TYPE_CONST, { .i64 = DEFAULT_MODE_PASSTHROUGH }, 0, 0, FLAGS, "default_mode" },
2797  { NULL },
2798 };
2799 
2800 #if CONFIG_MATROSKA_MUXER
2801 static const AVClass matroska_class = {
2802  .class_name = "matroska muxer",
2803  .item_name = av_default_item_name,
2804  .option = options,
2805  .version = LIBAVUTIL_VERSION_INT,
2806 };
2807 
2809  .name = "matroska",
2810  .long_name = NULL_IF_CONFIG_SMALL("Matroska"),
2811  .mime_type = "video/x-matroska",
2812  .extensions = "mkv",
2813  .priv_data_size = sizeof(MatroskaMuxContext),
2814  .audio_codec = CONFIG_LIBVORBIS_ENCODER ?
2816  .video_codec = CONFIG_LIBX264_ENCODER ?
2818  .init = mkv_init,
2819  .deinit = mkv_deinit,
2825  .codec_tag = (const AVCodecTag* const []){
2828  },
2829  .subtitle_codec = AV_CODEC_ID_ASS,
2830  .query_codec = mkv_query_codec,
2831  .check_bitstream = mkv_check_bitstream,
2832  .priv_class = &matroska_class,
2833 };
2834 #endif
2835 
2836 #if CONFIG_WEBM_MUXER
2837 static const AVClass webm_class = {
2838  .class_name = "webm muxer",
2839  .item_name = av_default_item_name,
2840  .option = options,
2841  .version = LIBAVUTIL_VERSION_INT,
2842 };
2843 
2845  .name = "webm",
2846  .long_name = NULL_IF_CONFIG_SMALL("WebM"),
2847  .mime_type = "video/webm",
2848  .extensions = "webm",
2849  .priv_data_size = sizeof(MatroskaMuxContext),
2852  .subtitle_codec = AV_CODEC_ID_WEBVTT,
2853  .init = mkv_init,
2854  .deinit = mkv_deinit,
2862  .priv_class = &webm_class,
2863 };
2864 #endif
2865 
2866 #if CONFIG_MATROSKA_AUDIO_MUXER
2867 static const AVClass mka_class = {
2868  .class_name = "matroska audio muxer",
2869  .item_name = av_default_item_name,
2870  .option = options,
2871  .version = LIBAVUTIL_VERSION_INT,
2872 };
2874  .name = "matroska",
2875  .long_name = NULL_IF_CONFIG_SMALL("Matroska Audio"),
2876  .mime_type = "audio/x-matroska",
2877  .extensions = "mka",
2878  .priv_data_size = sizeof(MatroskaMuxContext),
2879  .audio_codec = CONFIG_LIBVORBIS_ENCODER ?
2881  .video_codec = AV_CODEC_ID_NONE,
2882  .init = mkv_init,
2883  .deinit = mkv_deinit,
2890  .codec_tag = (const AVCodecTag* const []){
2892  },
2893  .priv_class = &mka_class,
2894 };
2895 #endif
unsigned int nb_chapters
Number of chapters in AVChapter array.
Definition: avformat.h:1580
int32_t pitch
Rotation around the right vector [-90, 90].
Definition: spherical.h:127
Context structure for the Lagged Fibonacci PRNG.
Definition: lfg.h:33
#define MATROSKA_ID_SEEKPREROLL
Definition: matroska.h:95
#define AV_STEREO3D_FLAG_INVERT
Inverted views, Right/Bottom represents the left view.
Definition: stereo3d.h:167
int track_num_size
Definition: matroskaenc.c:110
#define MATROSKA_ID_VIDEOPROJECTIONPOSEYAW
Definition: matroska.h:159
static void write_packet(OutputFile *of, AVPacket *pkt, OutputStream *ost, int unqueue)
Definition: ffmpeg.c:702
enum AVChromaLocation chroma_location
Definition: codec_par.h:150
internal header for HEVC (de)muxer utilities
#define AV_DISPOSITION_METADATA
Definition: avformat.h:858
void avio_wb64(AVIOContext *s, uint64_t val)
Definition: aviobuf.c:441
#define NULL
Definition: coverity.c:32
#define MATROSKA_ID_BLOCKADDID
Definition: matroska.h:230
#define MATROSKA_ID_TRACKDEFAULTDURATION
Definition: matroska.h:104
enum AVFieldOrder field_order
Video only.
Definition: codec_par.h:141
void avio_wl16(AVIOContext *s, unsigned int val)
Definition: aviobuf.c:447
static void put_ebml_size_unknown(AVIOContext *pb, int bytes)
Write an EBML size meaning "unknown size".
Definition: matroskaenc.c:193
Bytestream IO Context.
Definition: avio.h:161
enum AVColorTransferCharacteristic color_trc
Definition: codec_par.h:148
#define MATROSKA_ID_VIDEOFLAGINTERLACED
Definition: matroska.h:121
#define AVERROR_INVALIDDATA
Invalid data found when processing input.
Definition: error.h:59
#define MATROSKA_ID_VIDEOCOLOR_GX
Definition: matroska.h:147
static int start_ebml_master_crc32(AVIOContext **dyn_cp, MatroskaMuxContext *mkv)
Definition: matroskaenc.c:367
void ff_metadata_conv_ctx(AVFormatContext *ctx, const AVMetadataConv *d_conv, const AVMetadataConv *s_conv)
Definition: metadata.c:59
version
Definition: libkvazaar.c:292
static const char * format[]
Definition: af_aiir.c:339
#define MATROSKA_ID_DATEUTC
Definition: matroska.h:71
int size
int sizebytes
how many bytes were reserved for the size
Definition: matroskaenc.c:72
The optional first identifier line of a WebVTT cue.
Definition: packet.h:196
uint32_t samples
Definition: wv.h:39
int initial
Definition: wv.h:43
#define MATROSKA_ID_TRACKFLAGLACING
Definition: matroska.h:101
unsigned MaxCLL
Max content light level (cd/m^2).
#define MATROSKA_ID_TRACKENTRY
Definition: matroska.h:75
static int mkv_write_packet(AVFormatContext *s, const AVPacket *pkt)
Definition: matroskaenc.c:2363
#define MATROSKA_ID_VIDEODISPLAYHEIGHT
Definition: matroska.h:113
AVOption.
Definition: opt.h:246
int64_t cluster_pos
offset of the cluster containing the block relative to the segment
Definition: matroskaenc.c:95
void ff_put_bmp_header(AVIOContext *pb, AVCodecParameters *par, int for_asf, int ignore_extradata)
Definition: riffenc.c:209
int ff_put_wav_header(AVFormatContext *s, AVIOContext *pb, AVCodecParameters *par, int flags)
Write WAVEFORMAT header structure.
Definition: riffenc.c:54
static int mkv_init(struct AVFormatContext *s)
Definition: matroskaenc.c:2656
#define MAX_SEEKHEAD_ENTRIES
Definition: matroskaenc.c:59
static int mkv_write_packet_internal(AVFormatContext *s, const AVPacket *pkt)
Definition: matroskaenc.c:2271
#define MATROSKA_ID_VIDEOPROJECTIONPOSEROLL
Definition: matroska.h:161
#define MATROSKA_ID_CUETRACKPOSITION
Definition: matroska.h:192
enum AVCodecID ff_codec_get_id(const AVCodecTag *tags, unsigned int tag)
Definition: utils.c:3165
#define MATROSKA_ID_CODECPRIVATE
Definition: matroska.h:89
AVIOContext * cluster_bc
Definition: matroskaenc.c:130
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition: log.h:182
#define LIBAVUTIL_VERSION_INT
Definition: version.h:85
#define AV_RB64
Definition: intreadwrite.h:164
void avpriv_set_pts_info(AVStream *s, int pts_wrap_bits, unsigned int pts_num, unsigned int pts_den)
Set the time base and wrapping info for a given stream.
Definition: utils.c:4948
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:587
const char * desc
Definition: nvenc.c:79
static av_cold int init(AVCodecContext *avctx)
Definition: avrndec.c:35
#define MATROSKA_ID_AUDIOBITDEPTH
Definition: matroska.h:167
#define CASE(type, variable)
#define MATROSKA_ID_TRACKFLAGDEFAULT
Definition: matroska.h:99
static const AVCodecTag additional_subtitle_tags[]
Definition: matroskaenc.c:2775
This side data should be associated with a video stream and contains Stereoscopic 3D information in f...
Definition: packet.h:114
static int mkv_write_attachments(AVFormatContext *s)
Definition: matroskaenc.c:1716
uint64_t pts
Definition: matroskaenc.c:93
Video represents a portion of a sphere mapped on a flat surface using equirectangular projection...
Definition: spherical.h:72
AVRational white_point[2]
CIE 1931 xy chromaticity coords of white point.
enum AVCodecID codec_id
Specific type of the encoded data (the codec used).
Definition: codec_par.h:60
AVRational sample_aspect_ratio
sample aspect ratio (0 if unknown)
Definition: avformat.h:938
#define MATROSKA_ID_TAGTARGETS_ATTACHUID
Definition: matroska.h:214
int num
Numerator.
Definition: rational.h:59
int size
Definition: packet.h:356
int ff_hevc_annexb2mp4_buf(const uint8_t *buf_in, uint8_t **buf_out, int *size, int filter_ps, int *ps_count)
Writes Annex B formatted HEVC NAL units to a data buffer.
Definition: hevc.c:1047
int64_t avio_seek(AVIOContext *s, int64_t offset, int whence)
fseek() equivalent for AVIOContext.
Definition: aviobuf.c:241
#define MATROSKA_ID_FILEDATA
Definition: matroska.h:246
const char * av_default_item_name(void *ptr)
Return the context name.
Definition: log.c:235
AVFormatInternal * internal
An opaque field for libavformat internal usage.
Definition: avformat.h:1804
#define EBML_ID_DOCTYPEREADVERSION
Definition: matroska.h:42
#define us(width, name, range_min, range_max, subs,...)
Definition: cbs_h2645.c:276
#define MATROSKA_ID_BLOCKREFERENCE
Definition: matroska.h:237
#define AV_RB24
Definition: intreadwrite.h:64
static int mkv_write_header(AVFormatContext *s)
Definition: matroskaenc.c:1784
#define MATROSKA_ID_TRACKTYPE
Definition: matroska.h:80
enum AVMediaType codec_type
Definition: rtp.c:37
#define MATROSKA_ID_TAGTARGETS_CHAPTERUID
Definition: matroska.h:213
int ff_flac_is_native_layout(uint64_t channel_layout)
int64_t duration
duration of the block according to time base
Definition: matroskaenc.c:97
static av_always_inline uint64_t av_double2int(double f)
Reinterpret a double as a 64-bit integer.
Definition: intfloat.h:70
#define MATROSKA_ID_VIDEOCOLOR_RX
Definition: matroska.h:145
Video represents a sphere mapped on a flat surface using equirectangular projection.
Definition: spherical.h:56
static int mkv_write_tag(MatroskaMuxContext *mkv, const AVDictionary *m, AVIOContext **pb, ebml_master *tag, uint32_t elementid, uint64_t uid)
Definition: matroskaenc.c:1502
#define MATROSKA_ID_MUXINGAPP
Definition: matroska.h:70
int64_t cluster_time_limit
Definition: matroskaenc.c:150
#define MATROSKA_ID_AUDIOCHANNELS
Definition: matroska.h:168
int has_primaries
Flag indicating whether the display primaries (and white point) are set.
unsigned int ff_codec_get_tag(const AVCodecTag *tags, enum AVCodecID id)
Definition: utils.c:3155
const char * key
int avoid_negative_ts_use_pts
Definition: internal.h:119
const char * master
Definition: vf_curves.c:117
#define MATROSKA_ID_VIDEOPROJECTIONTYPE
Definition: matroska.h:157
Views are next to each other.
Definition: stereo3d.h:67
static AVPacket pkt
static void put_ebml_length(AVIOContext *pb, uint64_t length, int bytes)
Write a length as EBML variable length integer.
Definition: matroskaenc.c:239
#define av_le2ne32(x)
Definition: bswap.h:96
#define MATROSKA_ID_CUECLUSTERPOSITION
Definition: matroska.h:196
#define MATROSKA_ID_VIDEOCOLOR_LUMINANCEMAX
Definition: matroska.h:153
#define MAX_EBML_HEADER_SIZE
2 bytes * 7 for EBML IDs, 7 1-byte EBML lengths, 6 1-byte uint, 8 byte for "matroska" doctype string ...
Definition: matroskaenc.c:164
Definition: matroskaenc.c:80
int avcodec_enum_to_chroma_pos(int *xpos, int *ypos, enum AVChromaLocation pos)
Converts AVChromaLocation to swscale x/y chroma position.
Definition: utils.c:369
AVDictionary * metadata
Definition: avformat.h:1312
#define MATROSKA_ID_VIDEOCOLORCHROMASITINGHORZ
Definition: matroska.h:135
mkv_track * tracks
Definition: matroskaenc.c:135
ebml_stored_master track
Definition: matroskaenc.c:127
#define AVFMT_ALLOW_FLUSH
Format allows flushing.
Definition: avformat.h:471
#define MATROSKA_ID_EDITIONFLAGDEFAULT
Definition: matroska.h:260
#define MATROSKA_ID_CLUSTERTIMECODE
Definition: matroska.h:224
int avio_open_dyn_buf(AVIOContext **s)
Open a write only memory stream.
Definition: aviobuf.c:1356
#define EBML_ID_DOCTYPE
Definition: matroska.h:40
int64_t duration_offset
Definition: matroskaenc.c:115
#define AVFMT_TS_NONSTRICT
Format does not require strictly increasing timestamps, but they must still be monotonic.
Definition: avformat.h:472
This struct describes the properties of an encoded stream.
Definition: codec_par.h:52
#define MATROSKA_ID_CHAPTERTIMEEND
Definition: matroska.h:253
enum AVColorSpace color_space
Definition: codec_par.h:149
int64_t pos
absolute offset in the containing AVIOContext where the master&#39;s elements start
Definition: matroskaenc.c:71
MatroskaVideoStereoModeType
Definition: matroska.h:301
Mastering display metadata (based on SMPTE-2086:2014).
Definition: packet.h:222
#define FLAGS
Definition: matroskaenc.c:2783
#define MATROSKA_ID_FILEDESC
Definition: matroska.h:243
Format I/O context.
Definition: avformat.h:1351
#define EBML_ID_CRC32
Definition: matroska.h:46
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
UID uid
Definition: mxfenc.c:2136
static int query_codec(enum AVCodecID id, int std_compliance)
Definition: img2enc.c:229
int64_t cluster_pos
file offset of the current Cluster
Definition: matroskaenc.c:131
const char * class_name
The name of the class; usually it is the same name as the context structure type to which the AVClass...
Definition: log.h:72
#define AV_WB64(p, v)
Definition: intreadwrite.h:433
#define av_assert0(cond)
assert() equivalent, that is always enabled.
Definition: avassert.h:37
static const AVCodecTag additional_audio_tags[]
Definition: matroskaenc.c:2752
Public dictionary API.
planar YUV 4:2:0, 20bpp, (1 Cr & Cb sample per 2x2 Y & A samples)
Definition: pixfmt.h:101
void avio_wl32(AVIOContext *s, unsigned int val)
Definition: aviobuf.c:367
uint8_t
#define MATROSKA_ID_VIDEOCOLOR_BX
Definition: matroska.h:149
#define MATROSKA_ID_CHAPLANG
Definition: matroska.h:256
#define av_malloc(s)
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:177
int width
Video only.
Definition: codec_par.h:126
uint64_t uid
Definition: matroskaenc.c:108
unsigned track_num
Definition: matroskaenc.c:109
AVOptions.
#define MATROSKA_ID_TRACKLANGUAGE
Definition: matroska.h:97
int64_t duration
Definition: matroskaenc.c:114
A point in the output bytestream where the underlying AVIOContext might flush the buffer depending on...
Definition: avio.h:146
Stereo 3D type: this structure describes how two videos are packed within a single video surface...
Definition: stereo3d.h:176
const AVCodecTag ff_codec_movvideo_tags[]
Definition: isom.c:75
#define OPUS_SEEK_PREROLL
Seek preroll value for opus.
Definition: matroskaenc.c:174
uint32_t flags
Definition: wv.h:40
#define AV_RB32
Definition: intreadwrite.h:130
int ff_mkv_stereo3d_conv(AVStream *st, MatroskaVideoStereoModeType stereo_mode)
Definition: matroska.c:152
static av_cold int end(AVCodecContext *avctx)
Definition: avrndec.c:92
uint64_t segmentpos
Definition: matroskaenc.c:82
int id
unique ID to identify the chapter
Definition: avformat.h:1309
int64_t duration
Duration of this packet in AVStream->time_base units, 0 if unknown.
Definition: packet.h:373
#define MATROSKA_ID_TIMECODESCALE
Definition: matroska.h:66
static int mkv_write_codecprivate(AVFormatContext *s, AVIOContext *pb, AVCodecParameters *par, int native_id, int qt_id)
Definition: matroskaenc.c:762
#define MATROSKA_ID_SIMPLEBLOCK
Definition: matroska.h:232
void avio_write_marker(AVIOContext *s, int64_t time, enum AVIODataMarkerType type)
Mark the written bytestream as a specific type.
Definition: aviobuf.c:471
uint8_t * av_stream_get_side_data(const AVStream *stream, enum AVPacketSideDataType type, int *size)
Get side information from stream.
Definition: utils.c:5508
static int put_xiph_codecpriv(AVFormatContext *s, AVIOContext *pb, const AVCodecParameters *par)
Definition: matroskaenc.c:602
#define MATROSKA_ID_BLOCKMORE
Definition: matroska.h:229
AVStream ** streams
A list of all streams in the file.
Definition: avformat.h:1419
int64_t duration
Definition: movenc.c:63
#define MATROSKA_ID_CUERELATIVEPOSITION
Definition: matroska.h:197
A point in the output bytestream where a demuxer can start parsing (for non self synchronizing bytest...
Definition: avio.h:128
#define MATROSKA_ID_AUDIOOUTSAMPLINGFREQ
Definition: matroska.h:165
#define MATROSKA_ID_VIDEOCOLOR
Definition: matroska.h:127
Public header for CRC hash function implementation.
int initial_padding
Audio only.
Definition: codec_par.h:189
const char data[16]
Definition: mxf.c:91
static int webm_query_codec(enum AVCodecID codec_id, int std_compliance)
Definition: matroskaenc.c:2628
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:40
int flags
Flags modifying the (de)muxer behaviour.
Definition: avformat.h:1482
uint8_t * data
Definition: packet.h:355
static double av_q2d(AVRational a)
Convert an AVRational to a double.
Definition: rational.h:104
#define CONFIG_LIBVPX_VP9_ENCODER
Definition: config.h:1447
#define MATROSKA_ID_VIDEODISPLAYWIDTH
Definition: matroska.h:112
int ff_isom_write_av1c(AVIOContext *pb, const uint8_t *buf, int size)
Writes AV1 extradata (Sequence Header and Metadata OBUs) to the provided AVIOContext.
Definition: av1.c:364
#define MATROSKA_ID_BLOCKADDITIONS
Definition: matroska.h:228
uint32_t tag
Definition: movenc.c:1532
static int mkv_add_cuepoint(MatroskaMuxContext *mkv, int stream, int64_t ts, int64_t cluster_pos, int64_t relative_pos, int64_t duration)
Definition: matroskaenc.c:530
static EbmlSyntax ebml_header[]
Definition: matroskadec.c:406
Not part of ABI.
Definition: pixfmt.h:536
#define WV_HEADER_SIZE
Definition: wavpack.h:30
static int mkv_check_tag(const AVDictionary *m, uint32_t elementid)
Definition: matroskaenc.c:1528
#define MATROSKA_ID_CUES
Definition: matroska.h:58
int64_t ts_offset
Definition: matroskaenc.c:117
#define max(a, b)
Definition: cuda_runtime.h:33
Video is not stereoscopic (and metadata has to be there).
Definition: stereo3d.h:55
static av_always_inline int64_t avio_tell(AVIOContext *s)
ftell() equivalent for AVIOContext.
Definition: avio.h:557
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
int has_luminance
Flag indicating whether the luminance (min_ and max_) have been set.
static const uint8_t header[24]
Definition: sdr2.c:67
#define MATROSKA_ID_TRACKNUMBER
Definition: matroska.h:78
#define MATROSKA_ID_VIDEOCOLOR_WHITEY
Definition: matroska.h:152
void avio_write(AVIOContext *s, const unsigned char *buf, int size)
Definition: aviobuf.c:213
Definition: wv.h:34
#define AVFMT_FLAG_BITEXACT
When muxing, try to avoid writing any random/volatile data to the output.
Definition: avformat.h:1499
static uint64_t mkv_get_uid(const mkv_track *tracks, int i, AVLFG *c)
Definition: matroskaenc.c:2638
void * av_realloc_array(void *ptr, size_t nmemb, size_t size)
Allocate, reallocate, or free an array.
Definition: mem.c:198
#define MATROSKA_ID_SEGMENTUID
Definition: matroska.h:72
static int mkv_write_track(AVFormatContext *s, MatroskaMuxContext *mkv, AVStream *st, mkv_track *track, AVIOContext *pb, int is_default)
Definition: matroskaenc.c:1113
AVOutputFormat ff_webm_muxer
uint64_t channel_layout
Audio only.
Definition: codec_par.h:162
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:226
#define av_log(a,...)
#define AV_DISPOSITION_CAPTIONS
To specify text track kind (different from subtitles default).
Definition: avformat.h:856
int av_packet_ref(AVPacket *dst, const AVPacket *src)
Setup a new reference to the data described by a given packet.
Definition: avpacket.c:614
#define AV_PKT_FLAG_KEY
The packet contains a keyframe.
Definition: packet.h:388
static void mkv_add_seekhead_entry(MatroskaMuxContext *mkv, uint32_t elementid, uint64_t filepos)
Definition: matroskaenc.c:356
#define MATROSKA_ID_TRACKUID
Definition: matroska.h:79
int64_t av_rescale_q(int64_t a, AVRational bq, AVRational cq)
Rescale a 64-bit integer by 2 rational numbers.
Definition: mathematics.c:142
#define U(x)
Definition: vp56_arith.h:37
#define src
Definition: vp8dsp.c:254
#define MATROSKA_ID_VIDEOSTEREOMODE
Definition: matroska.h:123
static void put_ebml_id(AVIOContext *pb, uint32_t id)
Definition: matroskaenc.c:181
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: utils.c:5707
Content light level needed by to transmit HDR over HDMI (CTA-861.3).
AVPacket cur_audio_pkt
Definition: matroskaenc.c:140
#define i(width, name, range_min, range_max)
Definition: cbs_h2645.c:269
AVCodecID
Identify the syntax and semantics of the bitstream.
Definition: codec_id.h:46
static int mkv_write_tags(AVFormatContext *s)
Definition: matroskaenc.c:1539
#define MATROSKA_ID_VIDEOCOLOR_BY
Definition: matroska.h:150
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition: log.h:176
static void put_ebml_float(AVIOContext *pb, uint32_t elementid, double val)
Definition: matroskaenc.c:291
int av_get_bits_per_sample(enum AVCodecID codec_id)
Return codec bits per sample.
Definition: utils.c:1580
AVDictionary * metadata
Metadata that applies to the whole file.
Definition: avformat.h:1591
int flags
Additional information about the frame packing.
Definition: stereo3d.h:185
#define MATROSKA_ID_BLOCKDURATION
Definition: matroska.h:236
#define EBML_ID_EBMLREADVERSION
Definition: matroska.h:37
#define MATROSKA_ID_VIDEOCOLORMAXCLL
Definition: matroska.h:141
#define MAX_CUETRACKPOS_SIZE
4 * (1-byte EBML ID, 1-byte EBML size, 8-byte uint max)
Definition: matroskaenc.c:171
#define MATROSKA_ID_VIDEOCOLOR_WHITEX
Definition: matroska.h:151
#define AV_RB16
Definition: intreadwrite.h:53
#define AVERROR(e)
Definition: error.h:43
uint8_t * av_packet_get_side_data(const AVPacket *pkt, enum AVPacketSideDataType type, int *size)
Get side information from packet.
Definition: avpacket.c:353
int reserved_size
Definition: matroskaenc.c:89
#define MATROSKA_ID_CLUSTER
Definition: matroska.h:62
const char * ff_convert_lang_to(const char *lang, enum AVLangCodespace target_codespace)
Convert a language code to a target codespace.
Definition: avlanguage.c:736
#define MATROSKA_ID_VIDEOCOLORCHROMASITINGVERT
Definition: matroska.h:136
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification. ...
Definition: internal.h:188
int ff_av1_filter_obus_buf(const uint8_t *in, uint8_t **out, int *size, int *offset)
Filter out AV1 OBUs not meant to be present in ISOBMFF sample data and return the result in a data bu...
Definition: av1.c:86
Views are packed per line, as if interlaced.
Definition: stereo3d.h:129
enum AVColorPrimaries color_primaries
Definition: codec_par.h:147
void ffio_reset_dyn_buf(AVIOContext *s)
Reset a dynamic buffer.
Definition: aviobuf.c:1390
#define MATROSKA_ID_FILEMIMETYPE
Definition: matroska.h:245
#define MATROSKA_ID_WRITINGAPP
Definition: matroska.h:69
#define AV_LOG_DEBUG
Stuff which is only useful for libav* developers.
Definition: log.h:197
int ff_isom_write_hvcc(AVIOContext *pb, const uint8_t *data, int size, int ps_array_completeness)
Writes HEVC extradata (parameter sets, declarative SEI NAL units) to the provided AVIOContext...
Definition: hevc.c:1068
Not part of ABI.
Definition: pixfmt.h:473
const char *const ff_matroska_video_stereo_mode[MATROSKA_VIDEO_STEREOMODE_TYPE_NB]
Definition: matroska.c:128
void av_dict_free(AVDictionary **pm)
Free all the memory allocated for an AVDictionary struct and all keys and values. ...
Definition: dict.c:203
static void put_ebml_void(AVIOContext *pb, int size)
Write a void element of a given size.
Definition: matroskaenc.c:318
enum AVMediaType codec_type
General type of the encoded data.
Definition: codec_par.h:56
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:204
int write_dts
Definition: matroskaenc.c:106
int final
Definition: wv.h:43
AVChapter ** chapters
Definition: avformat.h:1581
enum AVCodecID id
Definition: matroska.h:355
static int mkv_write_chapters(AVFormatContext *s)
Definition: matroskaenc.c:1612
#define EBML_ID_EBMLMAXIDLENGTH
Definition: matroska.h:38
AVIOContext * bc
Definition: matroskaenc.c:76
static const uint8_t offset[127][2]
Definition: vf_spp.c:93
uint32_t crc
Definition: wv.h:41
static int mkv_write_seekhead(AVIOContext *pb, MatroskaMuxContext *mkv, int error_on_seek_failure, int64_t destpos)
Write the SeekHead to the file at the location reserved for it and seek to destpos afterwards...
Definition: matroskaenc.c:489
AVRational avg_frame_rate
Average framerate.
Definition: avformat.h:949
const AVCodecTag ff_codec_wav_tags[]
Definition: riff.c:506
#define FFMAX(a, b)
Definition: common.h:94
int ff_avc_parse_nal_units_buf(const uint8_t *buf_in, uint8_t **buf, int *size)
Definition: avc.c:95
AVRational max_luminance
Max luminance of mastering display (cd/m^2).
int64_t filepos
Definition: matroskaenc.c:86
#define fail()
Definition: checkasm.h:123
int flags
A combination of AV_PKT_FLAG values.
Definition: packet.h:361
int extradata_size
Size of the extradata content in bytes.
Definition: codec_par.h:78
#define MATROSKA_ID_TAG
Definition: matroska.h:202
const CodecTags ff_webm_codec_tags[]
Definition: matroska.c:106
Views are alternated temporally.
Definition: stereo3d.h:92
#define AV_DISPOSITION_FORCED
Track should be used during playback by default.
Definition: avformat.h:833
unsigned int nb_streams
Number of elements in AVFormatContext.streams.
Definition: avformat.h:1407
uint32_t bound_bottom
Distance from the bottom edge.
Definition: spherical.h:170
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:380
AVOutputFormat ff_matroska_audio_muxer
static int mkv_write_simpletag(AVIOContext *pb, const AVDictionaryEntry *t)
Definition: matroskaenc.c:1434
#define LIBAVFORMAT_IDENT
Definition: version.h:46
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:217
const char * name
Definition: qsvenc.c:46
int seekable
A combination of AVIO_SEEKABLE_ flags or 0 when the stream is not seekable.
Definition: avio.h:260
Video frame is split into 6 faces of a cube, and arranged on a 3x2 layout.
Definition: spherical.h:65
#define MATROSKA_ID_VIDEOCOLOR_LUMINANCEMIN
Definition: matroska.h:154
audio channel layout utility functions
int ff_alloc_extradata(AVCodecParameters *par, int size)
Allocate extradata with additional AV_INPUT_BUFFER_PADDING_SIZE at end which is always set to 0...
Definition: utils.c:3328
#define EBML_ID_EBMLVERSION
Definition: matroska.h:36
#define av_assert1(cond)
assert() equivalent, that does not lie in speed critical code.
Definition: avassert.h:53
int64_t av_rescale(int64_t a, int64_t b, int64_t c)
Rescale a 64-bit integer with rounding to nearest.
Definition: mathematics.c:129
mkv_cuepoint * entries
Definition: matroskaenc.c:101
void ffio_fill(AVIOContext *s, int b, int count)
Definition: aviobuf.c:199
#define AV_TIME_BASE
Internal time base represented as integer.
Definition: avutil.h:254
#define MATROSKA_ID_TAGTARGETS
Definition: matroska.h:209
const AVCodecTag ff_codec_bmp_tags[]
Definition: riff.c:32
int av_strcasecmp(const char *a, const char *b)
Locale-independent case-insensitive compare.
Definition: avstring.c:213
#define MATROSKA_ID_TAGNAME
Definition: matroska.h:204
AVRational min_luminance
Min luminance of mastering display (cd/m^2).
uint32_t segment_uid[4]
Definition: matroskaenc.c:159
static int64_t get_metadata_duration(AVFormatContext *s)
Definition: matroskaenc.c:1760
static int write_trailer(AVFormatContext *s1)
Definition: v4l2enc.c:98
static void bit_depth(AudioStatsContext *s, uint64_t mask, uint64_t imask, AVRational *depth)
Definition: af_astats.c:254
#define AVFMT_GLOBALHEADER
Format wants global header.
Definition: avformat.h:461
void avio_wb24(AVIOContext *s, unsigned int val)
Definition: aviobuf.c:465
This side data should be associated with a video stream and corresponds to the AVSphericalMapping str...
Definition: packet.h:228
uint32_t bound_right
Distance from the right edge.
Definition: spherical.h:169
int ff_wv_parse_header(WvHeader *wv, const uint8_t *data)
Parse a WavPack block header.
Definition: wv.c:29
#define MATROSKA_ID_SIMPLETAG
Definition: matroska.h:203
const char * name
Definition: avformat.h:500
internal header for RIFF based (de)muxers do NOT include this in end user applications ...
uint32_t av_crc(const AVCRC *ctx, uint32_t crc, const uint8_t *buffer, size_t length)
Calculate the CRC of a block.
Definition: crc.c:392
#define s(width, name)
Definition: cbs_vp9.c:257
static int end_ebml_master_crc32_tentatively(AVIOContext *pb, ebml_stored_master *elem, MatroskaMuxContext *mkv, uint32_t id)
Output EBML master.
Definition: matroskaenc.c:417
int avoid_negative_ts
Avoid negative timestamps during muxing.
Definition: avformat.h:1682
#define MATROSKA_ID_CHAPTERATOM
Definition: matroska.h:251
int avpriv_split_xiph_headers(const uint8_t *extradata, int extradata_size, int first_header_size, const uint8_t *header_start[3], int header_len[3])
Split a single extradata buffer into the three headers that most Xiph codecs use. ...
Definition: xiph.c:24
#define CONFIG_LIBVORBIS_ENCODER
Definition: config.h:1445
#define AV_RL32
Definition: intreadwrite.h:146
static int mkv_write_native_codecprivate(AVFormatContext *s, AVIOContext *pb, const AVCodecParameters *par, AVIOContext *dyn_cp)
Definition: matroskaenc.c:710
int32_t yaw
Rotation around the up vector [-180, 180].
Definition: spherical.h:126
static int get_aac_sample_rates(AVFormatContext *s, MatroskaMuxContext *mkv, const uint8_t *extradata, int extradata_size, int *sample_rate, int *output_sample_rate)
Definition: matroskaenc.c:677
AVDictionary * metadata
Definition: avformat.h:940
enum AVCodecID codec_id
Definition: vaapi_decode.c:369
enum AVColorRange color_range
Video only.
Definition: codec_par.h:146
static int mkv_check_new_extra_data(AVFormatContext *s, const AVPacket *pkt)
Definition: matroskaenc.c:2181
Opaque data information usually sparse.
Definition: avutil.h:205
#define MATROSKA_ID_VIDEOCOLORSPACE
Definition: matroska.h:126
#define MATROSKA_ID_CHAPTERS
Definition: matroska.h:63
ebml_stored_master info
Definition: matroskaenc.c:126
#define EBML_ID_VOID
Definition: matroska.h:45
#define OFFSET(x)
Definition: matroskaenc.c:2782
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
#define MATROSKA_ID_AUDIOSAMPLINGFREQ
Definition: matroska.h:164
#define av_log2
Definition: intmath.h:83
ff_const59 struct AVOutputFormat * oformat
The output container format.
Definition: avformat.h:1370
void ffio_free_dyn_buf(AVIOContext **s)
Free a dynamic buffer.
Definition: aviobuf.c:1431
uint32_t padding
Number of pixels to pad from the edge of each cube face.
Definition: spherical.h:182
int metadata_header_padding
Number of bytes to be written as padding in a metadata header.
Definition: avformat.h:1851
Stream structure.
Definition: avformat.h:876
#define IS_SEEKABLE(pb, mkv)
Definition: matroskaenc.c:61
#define AVERROR_PATCHWELCOME
Not yet implemented in FFmpeg, patches welcome.
Definition: error.h:62
int64_t end
chapter start/end time in time_base units
Definition: avformat.h:1311
Content light level (based on CTA-861.3).
Definition: packet.h:235
#define AVIO_SEEKABLE_NORMAL
Seeking works like for a local file.
Definition: avio.h:40
The AV_PKT_DATA_NEW_EXTRADATA is used to notify the codec or the format that the extradata buffer was...
Definition: packet.h:55
#define AV_DISPOSITION_DEFAULT
Definition: avformat.h:821
sample_rate
enum AVStereo3DType type
How views are packed within the video.
Definition: stereo3d.h:180
Views are packed in a checkerboard-like structure per pixel.
Definition: stereo3d.h:104
#define MATROSKA_ID_VIDEOCOLORMATRIXCOEFF
Definition: matroska.h:129
#define AV_DISPOSITION_DESCRIPTIONS
Definition: avformat.h:857
char * av_strdup(const char *s)
Duplicate a string.
Definition: mem.c:253
#define MATROSKA_ID_TRACKFLAGFORCED
Definition: matroska.h:100
#define MATROSKA_ID_TAGS
Definition: matroska.h:59
Views are on top of each other.
Definition: stereo3d.h:79
#define MATROSKA_ID_VIDEOCOLORPRIMARIES
Definition: matroska.h:140
int64_t sample_rate_offset
Definition: matroskaenc.c:112
#define MATROSKA_ID_VIDEOPROJECTIONPOSEPITCH
Definition: matroska.h:160
#define AV_TIME_BASE_Q
Internal time base represented as fractional value.
Definition: avutil.h:260
#define MATROSKA_ID_SEEKID
Definition: matroska.h:220
AVIOContext * pb
I/O context.
Definition: avformat.h:1393
int64_t codecpriv_offset
Definition: matroskaenc.c:116
static void put_ebml_uint(AVIOContext *pb, uint32_t elementid, uint64_t val)
Definition: matroskaenc.c:264
void avio_w8(AVIOContext *s, int b)
Definition: aviobuf.c:191
#define MATROSKA_ID_BLOCK
Definition: matroska.h:235
#define MATROSKA_ID_INFO
Definition: matroska.h:56
void av_packet_unref(AVPacket *pkt)
Wipe the packet.
Definition: avpacket.c:605
#define MATROSKA_ID_TAGTARGETS_TRACKUID
Definition: matroska.h:212
#define MATROSKA_ID_TAGLANG
Definition: matroska.h:206
static unsigned int av_lfg_get(AVLFG *c)
Get the next random unsigned 32-bit number using an ALFG.
Definition: lfg.h:53
#define MATROSKA_ID_TRACKS
Definition: matroska.h:57
Data found in BlockAdditional element of matroska container.
Definition: packet.h:191
#define MATROSKA_ID_TRACKNAME
Definition: matroska.h:96
int av_dict_set(AVDictionary **pm, const char *key, const char *value, int flags)
Set the given entry in *pm, overwriting an existing entry.
Definition: dict.c:70
static void mkv_write_video_color(AVIOContext *pb, const AVStream *st, const AVCodecParameters *par)
Definition: matroskaenc.c:831
#define MATROSKA_ID_SEEKENTRY
Definition: matroska.h:217
static void put_ebml_uid(AVIOContext *pb, uint32_t elementid, uint64_t uid)
Write a (random) UID with fixed size to make the output more deterministic.
Definition: matroskaenc.c:257
Describe the class of an AVClass context structure.
Definition: log.h:67
unsigned nb_attachments
Definition: matroskaenc.c:142
#define AV_WB32(p, v)
Definition: intreadwrite.h:419
#define MATROSKA_ID_EDITIONENTRY
Definition: matroska.h:250
#define FF_COMPLIANCE_NORMAL
Definition: avcodec.h:1592
static int mkv_check_tag_name(const char *name, uint32_t elementid)
Definition: matroskaenc.c:1488
#define MATROSKA_ID_BLOCKGROUP
Definition: matroska.h:227
#define MATROSKA_ID_VIDEOPIXELHEIGHT
Definition: matroska.h:115
int32_t roll
Rotation around the forward vector [-180, 180].
Definition: spherical.h:128
static int mkv_write_tracks(AVFormatContext *s)
Definition: matroskaenc.c:1376
Rational number (pair of numerator and denominator).
Definition: rational.h:58
Mastering display metadata capable of representing the color volume of the display used to master the...
#define MATROSKA_ID_CUEDURATION
Definition: matroska.h:198
#define MATROSKA_ID_CUETIME
Definition: matroska.h:191
Not part of ABI.
Definition: pixfmt.h:502
Recommmends skipping the specified number of samples.
Definition: packet.h:156
cl_device_type type
AVMediaType
Definition: avutil.h:199
av_cold void av_lfg_init(AVLFG *c, unsigned int seed)
Definition: lfg.c:32
int64_t duration_offset
Definition: matroskaenc.c:133
#define MATROSKA_ID_VIDEOCOLORTRANSFERCHARACTERISTICS
Definition: matroska.h:138
#define MATROSKA_ID_TITLE
Definition: matroska.h:68
#define snprintf
Definition: snprintf.h:34
#define MATROSKA_ID_TRACKVIDEO
Definition: matroska.h:81
static int mkv_strip_wavpack(const uint8_t *src, uint8_t **pdst, int *size)
Definition: matroskaenc.c:1950
This structure describes how to handle spherical videos, outlining information about projection...
Definition: spherical.h:82
int error
contains the error code or 0 if no error happened
Definition: avio.h:245
mkv_seekhead seekhead
Definition: matroskaenc.c:136
#define MATROSKA_ID_VIDEOPROJECTION
Definition: matroska.h:156
#define MATROSKA_ID_VIDEOCOLORMASTERINGMETA
Definition: matroska.h:144
misc parsing utilities
ebml_stored_master tags
Definition: matroskaenc.c:128
#define CONFIG_LIBOPUS_ENCODER
Definition: config.h:1438
#define MATROSKA_ID_VIDEOPROJECTIONPRIVATE
Definition: matroska.h:158
AVRational display_primaries[3][2]
CIE 1931 xy chromaticity coords of color primaries (r, g, b order).
This struct describes the properties of a single codec described by an AVCodecID. ...
Definition: codec_desc.h:38
#define MATROSKA_ID_ATTACHMENTS
Definition: matroska.h:61
static int64_t pts
void avio_wb16(AVIOContext *s, unsigned int val)
Definition: aviobuf.c:453
#define flags(name, subs,...)
Definition: cbs_av1.c:565
#define MATROSKA_ID_CHAPTERDISPLAY
Definition: matroska.h:254
static int mkv_end_cluster(AVFormatContext *s)
Definition: matroskaenc.c:2162
int bits_per_raw_sample
This is the number of valid bits in each output sample.
Definition: codec_par.h:115
#define MATROSKA_ID_FILENAME
Definition: matroska.h:244
int av_get_bytes_per_sample(enum AVSampleFormat sample_fmt)
Return number of bytes per sample.
Definition: samplefmt.c:106
#define MATROSKA_ID_BLOCKADDITIONAL
Definition: matroska.h:231
AVFieldOrder
Definition: codec_par.h:36
uint32_t bound_top
Distance from the top edge.
Definition: spherical.h:168
const AVMetadataConv ff_mkv_metadata_conv[]
Definition: matroska.c:122
#define MATROSKA_ID_CODECID
Definition: matroska.h:88
static const AVCodecTag additional_video_tags[]
Definition: matroskaenc.c:2768
mkv_seekhead_entry entries[MAX_SEEKHEAD_ENTRIES]
Definition: matroskaenc.c:87
#define MATROSKA_ID_VIDEOFIELDORDER
Definition: matroska.h:122
int64_t start
Definition: avformat.h:1311
static av_always_inline AVRational av_inv_q(AVRational q)
Invert a rational.
Definition: rational.h:159
const AVCRC * av_crc_get_table(AVCRCId crc_id)
Get an initialized standard CRC table.
Definition: crc.c:374
int sample_rate
Audio only.
Definition: codec_par.h:170
int ff_flac_write_header(AVIOContext *pb, const uint8_t *extradata, int extradata_size, int last_block)
#define MATROSKA_ID_VIDEOALPHAMODE
Definition: matroska.h:124
static int av_cmp_q(AVRational a, AVRational b)
Compare two rationals.
Definition: rational.h:89
static int mkv_write_trailer(AVFormatContext *s)
Definition: matroskaenc.c:2455
Main libavformat public API header.
static int put_flac_codecpriv(AVFormatContext *s, AVIOContext *pb, const AVCodecParameters *par)
Definition: matroskaenc.c:641
static int mkv_check_bitstream(struct AVFormatContext *s, const AVPacket *pkt)
Definition: matroskaenc.c:2737
#define MATROSKA_ID_CUETRACK
Definition: matroska.h:195
static int put_wv_codecpriv(AVIOContext *pb, const AVCodecParameters *par)
Definition: matroskaenc.c:632
#define MATROSKA_ID_SEEKPOSITION
Definition: matroska.h:221
#define MATROSKA_ID_CODECDELAY
Definition: matroska.h:94
#define FF_DISABLE_DEPRECATION_WARNINGS
Definition: internal.h:84
#define MATROSKA_ID_CHAPTERTIMESTART
Definition: matroska.h:252
#define MATROSKA_ID_VIDEOCOLORRANGE
Definition: matroska.h:137
enum AVSphericalProjection projection
Projection type.
Definition: spherical.h:86
Utilties for rational number calculation.
int ffio_init_context(AVIOContext *s, unsigned char *buffer, int buffer_size, int write_flag, void *opaque, int(*read_packet)(void *opaque, uint8_t *buf, int buf_size), int(*write_packet)(void *opaque, uint8_t *buf, int buf_size), int64_t(*seek)(void *opaque, int64_t offset, int whence))
Definition: aviobuf.c:76
static int mkv_write_tag_targets(MatroskaMuxContext *mkv, AVIOContext **pb, ebml_master *tag, uint32_t elementid, uint64_t uid)
Definition: matroskaenc.c:1468
raw UTF-8 text
Definition: codec_id.h:510
static double c[64]
static int mkv_write_flush_packet(AVFormatContext *s, AVPacket *pkt)
Definition: matroskaenc.c:2437
int disposition
AV_DISPOSITION_* bit field.
Definition: avformat.h:929
static ebml_master start_ebml_master(AVIOContext *pb, uint32_t elementid, uint64_t expectedsize)
Definition: matroskaenc.c:336
int64_t last_timestamp
Definition: matroskaenc.c:113
Stereoscopic video.
Views are packed per column.
Definition: stereo3d.h:141
AVRational time_base
time base in which the start/end timestamps are specified
Definition: avformat.h:1310
const char * avcodec_get_name(enum AVCodecID id)
Get the name of a codec.
Definition: utils.c:1212
void av_init_packet(AVPacket *pkt)
Initialize optional fields of a packet with default values.
Definition: avpacket.c:35
char * key
Definition: dict.h:86
int den
Denominator.
Definition: rational.h:60
static int mkv_write_vtt_blocks(AVFormatContext *s, AVIOContext *pb, const AVPacket *pkt)
Definition: matroskaenc.c:2115
#define MATROSKA_ID_SEGMENT
Definition: matroska.h:53
#define MAX_PCE_SIZE
Maximum size of a PCE including the 3-bit ID_PCE.
Definition: mpeg4audio.h:134
static void mkv_write_video_projection(AVFormatContext *s, AVIOContext *pb, const AVStream *st)
Definition: matroskaenc.c:916
The optional settings (rendering instructions) that immediately follow the timestamp specifier of a W...
Definition: packet.h:202
#define MATROSKA_ID_SEEKHEAD
Definition: matroska.h:60
#define EBML_ID_HEADER
Definition: matroska.h:33
uint32_t elementid
Definition: matroskaenc.c:81
A point in the output bytestream where a decoder can start decoding (i.e.
Definition: avio.h:122
#define AVFMT_VARIABLE_FPS
Format allows variable fps.
Definition: avformat.h:465
#define av_free(p)
char * value
Definition: dict.h:87
#define FF_ENABLE_DEPRECATION_WARNINGS
Definition: internal.h:85
#define MATROSKA_ID_POINTENTRY
Definition: matroska.h:188
int len
static int mkv_write_stereo_mode(AVFormatContext *s, AVIOContext *pb, AVStream *st, int mode, int *h_width, int *h_height)
Definition: matroskaenc.c:1022
#define MATROSKA_ID_FILEUID
Definition: matroska.h:247
int ff_stream_add_bitstream_filter(AVStream *st, const char *name, const char *args)
Add a bitstream filter to a stream.
Definition: utils.c:5579
static void put_ebml_binary(AVIOContext *pb, uint32_t elementid, const void *buf, int size)
Definition: matroskaenc.c:298
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:469
void * priv_data
Format private data.
Definition: avformat.h:1379
#define MATROSKA_ID_CHAPTERUID
Definition: matroska.h:262
char str[22]
Definition: matroska.h:354
static int check_bitstream(AVFormatContext *s, AVStream *st, AVPacket *pkt)
Definition: mux.c:1075
static void write_header(FFV1Context *f)
Definition: ffv1enc.c:346
uint32_t bound_left
Distance from the left edge.
Definition: spherical.h:167
const AVCodecDescriptor * avcodec_descriptor_get(enum AVCodecID id)
Definition: codec_desc.c:3394
static const char * get_mimetype(const AVStream *st)
Definition: matroskaenc.c:1699
int bits_per_coded_sample
The number of bits per sample in the codedwords.
Definition: codec_par.h:102
int64_t relative_pos
relative offset from the position of the cluster containing the block
Definition: matroskaenc.c:96
uint8_t * extradata
Extra binary data needed for initializing the decoder, codec-dependent.
Definition: codec_par.h:74
#define MATROSKA_ID_VIDEOCOLORMAXFALL
Definition: matroska.h:142
#define MATROSKA_ID_VIDEODISPLAYUNIT
Definition: matroska.h:120
int channels
Audio only.
Definition: codec_par.h:166
int64_t dts
Decompression timestamp in AVStream->time_base units; the time at which the packet is decompressed...
Definition: packet.h:354
static const AVOption options[]
Definition: matroskaenc.c:2784
#define EBML_ID_EBMLMAXSIZELENGTH
Definition: matroska.h:39
void avio_wb32(AVIOContext *s, unsigned int val)
Definition: aviobuf.c:375
enum AVMediaType avcodec_get_type(enum AVCodecID codec_id)
Get the type of the given codec.
Definition: codec_desc.c:3419
int64_t duration
Duration of the stream, in AV_TIME_BASE fractional seconds.
Definition: avformat.h:1466
#define MATROSKA_ID_CHAPSTRING
Definition: matroska.h:255
int sample_rate
Definition: matroskaenc.c:111
#define av_freep(p)
#define MATROSKA_ID_TAGSTRING
Definition: matroska.h:205
#define AV_DICT_IGNORE_SUFFIX
Return first entry in a dictionary whose first part corresponds to the search key, ignoring the suffix of the found key string.
Definition: dict.h:70
#define MODE_MATROSKAv2
Definition: matroskaenc.c:120
uint32_t av_get_random_seed(void)
Get a seed to use in conjunction with random functions.
Definition: random_seed.c:120
static void put_ebml_string(AVIOContext *pb, uint32_t elementid, const char *str)
Definition: matroskaenc.c:306
AVOutputFormat ff_matroska_muxer
AVCodecParameters * codecpar
Codec parameters associated with this stream.
Definition: avformat.h:1023
static void put_ebml_sint(AVIOContext *pb, uint32_t elementid, int64_t val)
Definition: matroskaenc.c:277
#define MODE_WEBM
Definition: matroskaenc.c:121
uint32_t codec_tag
Additional information about the codec (corresponds to the AVI FOURCC).
Definition: codec_par.h:64
#define MATROSKA_ID_DURATION
Definition: matroska.h:67
#define MAX_SEEKENTRY_SIZE
2 bytes * 3 for EBML IDs, 3 1-byte EBML lengths, 8 bytes for 64 bit offset, 4 bytes for target EBML I...
Definition: matroskaenc.c:168
static void mkv_deinit(AVFormatContext *s)
Free the members allocated in the mux context.
Definition: matroskaenc.c:449
int stream_index
Definition: packet.h:357
int num_entries
Definition: matroskaenc.c:102
#define EBML_ID_DOCTYPEVERSION
Definition: matroska.h:41
AVRational time_base
This is the fundamental unit of time (in seconds) in terms of which frame timestamps are represented...
Definition: avformat.h:905
static void end_ebml_master(AVIOContext *pb, ebml_master master)
Definition: matroskaenc.c:346
const char *const * mime_types
MIME type(s) associated with the codec.
Definition: codec_desc.h:60
int64_t segment_offset
Definition: matroskaenc.c:129
#define CONFIG_LIBX264_ENCODER
Definition: config.h:1452
AVRational r_frame_rate
Real base framerate of the stream.
Definition: avformat.h:1000
#define MATROSKA_ID_ATTACHEDFILE
Definition: matroska.h:242
#define MATROSKA_ID_VIDEOCOLOR_GY
Definition: matroska.h:148
static int mkv_write_block(AVFormatContext *s, AVIOContext *pb, uint32_t blockid, const AVPacket *pkt, int keyframe)
Definition: matroskaenc.c:2003
enum AVCodecID id
static double val(void *priv, double ch)
Definition: aeval.c:76
unsigned MaxFALL
Max average light level per frame (cd/m^2).
This structure stores compressed data.
Definition: packet.h:332
static void mkv_write_field_order(AVIOContext *pb, int mode, enum AVFieldOrder field_order)
Definition: matroskaenc.c:983
mode
Use these values in ebur128_init (or&#39;ed).
Definition: ebur128.h:83
#define MATROSKA_ID_VIDEOCOLOR_RY
Definition: matroska.h:146
uint32_t blocksize
Definition: wv.h:35
static int mkv_query_codec(enum AVCodecID codec_id, int std_compliance)
Definition: matroskaenc.c:2611
static void put_xiph_size(AVIOContext *pb, int size)
Definition: matroskaenc.c:440
int64_t pts
Presentation timestamp in AVStream->time_base units; the time at which the decompressed packet will b...
Definition: packet.h:348
Not part of ABI.
Definition: pixfmt.h:526
#define MATROSKA_ID_VIDEOPIXELWIDTH
Definition: matroska.h:114
static int mkv_blockgroup_size(int pkt_size, int track_num_size)
Definition: matroskaenc.c:1941
static int mkv_assemble_cues(AVStream **streams, AVIOContext *dyn_cp, mkv_cues *cues, mkv_track *tracks, int num_tracks)
Definition: matroskaenc.c:553
int ff_isom_write_avcc(AVIOContext *pb, const uint8_t *data, int len)
Definition: avc.c:108
#define MATROSKA_ID_TRACKAUDIO
Definition: matroska.h:82
#define AV_NOPTS_VALUE
Undefined timestamp value.
Definition: avutil.h:248
int(* filler)(InterplayACMContext *s, unsigned ind, unsigned col)
Definition: interplayacm.c:407
const CodecTags ff_mkv_codec_tags[]
Definition: matroska.c:29
int avio_printf(AVIOContext *s, const char *fmt,...) av_printf_format(2
Writes a formatted string to the context.
static int ebml_id_size(uint32_t id)
Definition: matroskaenc.c:176
#define AV_WL32(p, v)
Definition: intreadwrite.h:426
#define MATROSKA_ID_DISCARDPADDING
Definition: matroska.h:239
#define FF_PUT_WAV_HEADER_FORCE_WAVEFORMATEX
Tell ff_put_wav_header() to use WAVEFORMATEX even for PCM codecs.
Definition: riff.h:54
void * av_mallocz_array(size_t nmemb, size_t size)
Allocate a memory block for an array with av_mallocz().
Definition: mem.c:190
int avio_get_dyn_buf(AVIOContext *s, uint8_t **pbuffer)
Return the written size and a pointer to the buffer.
Definition: aviobuf.c:1368
static uint8_t tmp[11]
Definition: aes_ctr.c:26