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