FFmpeg
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
matroskaenc.c
Go to the documentation of this file.
1 /*
2  * Matroska muxer
3  * Copyright (c) 2007 David Conrad
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21 
22 #include <stdint.h>
23 
24 #include "avc.h"
25 #include "hevc.h"
26 #include "avformat.h"
27 #include "avio_internal.h"
28 #include "avlanguage.h"
29 #include "flacenc.h"
30 #include "internal.h"
31 #include "isom.h"
32 #include "matroska.h"
33 #include "riff.h"
34 #include "subtitles.h"
35 #include "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/sha.h"
53 #include "libavutil/stereo3d.h"
54 
55 #include "libavcodec/xiph.h"
56 #include "libavcodec/mpeg4audio.h"
57 #include "libavcodec/internal.h"
58 
59 typedef struct ebml_master {
60  int64_t pos; ///< absolute offset in the file where the master's elements start
61  int sizebytes; ///< how many bytes were reserved for the size
62 } ebml_master;
63 
64 typedef struct mkv_seekhead_entry {
65  unsigned int elementid;
66  uint64_t segmentpos;
68 
69 typedef struct mkv_seekhead {
70  int64_t filepos;
71  int64_t segment_offset; ///< the file offset to the beginning of the segment
72  int reserved_size; ///< -1 if appending to file
76 } mkv_seekhead;
77 
78 typedef struct mkv_cuepoint {
79  uint64_t pts;
81  int tracknum;
82  int64_t cluster_pos; ///< file offset of the cluster containing the block
83  int64_t relative_pos; ///< relative offset from the position of the cluster containing the block
84  int64_t duration; ///< duration of the block according to time base
85 } mkv_cuepoint;
86 
87 typedef struct mkv_cues {
88  int64_t segment_offset;
91 } mkv_cues;
92 
93 typedef struct mkv_track {
94  int write_dts;
95  int has_cue;
97  int64_t ts_offset;
98 } mkv_track;
99 
100 typedef struct mkv_attachment {
102  uint32_t fileuid;
104 
105 typedef struct mkv_attachments {
109 
110 #define MODE_MATROSKAv2 0x01
111 #define MODE_WEBM 0x02
112 
113 /** Maximum number of tracks allowed in a Matroska file (with track numbers in
114  * range 1 to 126 (inclusive) */
115 #define MAX_TRACKS 126
116 
117 typedef struct MatroskaMuxContext {
118  const AVClass *class;
119  int mode;
128  int64_t segment_offset;
130  int64_t cluster_pos; ///< file offset of the current cluster
131  int64_t cluster_pts;
133  int64_t duration;
138 
140 
143 
146  int64_t cues_pos;
148  int is_dash;
150  int is_live;
152 
155 
157 
160 
163 
164 
165 /** 2 bytes * 3 for EBML IDs, 3 1-byte EBML lengths, 8 bytes for 64 bit
166  * offset, 4 bytes for target EBML ID */
167 #define MAX_SEEKENTRY_SIZE 21
168 
169 /** per-cuepoint-track - 5 1-byte EBML IDs, 5 1-byte EBML sizes, 4
170  * 8-byte uint max */
171 #define MAX_CUETRACKPOS_SIZE 42
172 
173 /** per-cuepoint - 2 1-byte EBML IDs, 2 1-byte EBML sizes, 8-byte uint max */
174 #define MAX_CUEPOINT_SIZE(num_tracks) 12 + MAX_CUETRACKPOS_SIZE * num_tracks
175 
176 /** Seek preroll value for opus */
177 #define OPUS_SEEK_PREROLL 80000000
178 
179 static int ebml_id_size(unsigned int id)
180 {
181  return (av_log2(id + 1) - 1) / 7 + 1;
182 }
183 
184 static void put_ebml_id(AVIOContext *pb, unsigned int id)
185 {
186  int i = ebml_id_size(id);
187  while (i--)
188  avio_w8(pb, (uint8_t)(id >> (i * 8)));
189 }
190 
191 /**
192  * Write an EBML size meaning "unknown size".
193  *
194  * @param bytes The number of bytes the size should occupy (maximum: 8).
195  */
196 static void put_ebml_size_unknown(AVIOContext *pb, int bytes)
197 {
198  av_assert0(bytes <= 8);
199  avio_w8(pb, 0x1ff >> bytes);
200  ffio_fill(pb, 0xff, bytes - 1);
201 }
202 
203 /**
204  * Calculate how many bytes are needed to represent a given number in EBML.
205  */
206 static int ebml_num_size(uint64_t num)
207 {
208  int bytes = 1;
209  while ((num + 1) >> bytes * 7)
210  bytes++;
211  return bytes;
212 }
213 
214 /**
215  * Write a number in EBML variable length format.
216  *
217  * @param bytes The number of bytes that need to be used to write the number.
218  * If zero, any number of bytes can be used.
219  */
220 static void put_ebml_num(AVIOContext *pb, uint64_t num, int bytes)
221 {
222  int i, needed_bytes = ebml_num_size(num);
223 
224  // sizes larger than this are currently undefined in EBML
225  av_assert0(num < (1ULL << 56) - 1);
226 
227  if (bytes == 0)
228  // don't care how many bytes are used, so use the min
229  bytes = needed_bytes;
230  // the bytes needed to write the given size would exceed the bytes
231  // that we need to use, so write unknown size. This shouldn't happen.
232  av_assert0(bytes >= needed_bytes);
233 
234  num |= 1ULL << bytes * 7;
235  for (i = bytes - 1; i >= 0; i--)
236  avio_w8(pb, (uint8_t)(num >> i * 8));
237 }
238 
239 static void put_ebml_uint(AVIOContext *pb, unsigned int elementid, uint64_t val)
240 {
241  int i, bytes = 1;
242  uint64_t tmp = val;
243  while (tmp >>= 8)
244  bytes++;
245 
246  put_ebml_id(pb, elementid);
247  put_ebml_num(pb, bytes, 0);
248  for (i = bytes - 1; i >= 0; i--)
249  avio_w8(pb, (uint8_t)(val >> i * 8));
250 }
251 
252 static void put_ebml_sint(AVIOContext *pb, unsigned int elementid, int64_t val)
253 {
254  int i, bytes = 1;
255  uint64_t tmp = 2*(val < 0 ? val^-1 : val);
256 
257  while (tmp>>=8) bytes++;
258 
259  put_ebml_id(pb, elementid);
260  put_ebml_num(pb, bytes, 0);
261  for (i = bytes - 1; i >= 0; i--)
262  avio_w8(pb, (uint8_t)(val >> i * 8));
263 }
264 
265 static void put_ebml_float(AVIOContext *pb, unsigned int elementid, double val)
266 {
267  put_ebml_id(pb, elementid);
268  put_ebml_num(pb, 8, 0);
269  avio_wb64(pb, av_double2int(val));
270 }
271 
272 static void put_ebml_binary(AVIOContext *pb, unsigned int elementid,
273  const void *buf, int size)
274 {
275  put_ebml_id(pb, elementid);
276  put_ebml_num(pb, size, 0);
277  avio_write(pb, buf, size);
278 }
279 
280 static void put_ebml_string(AVIOContext *pb, unsigned int elementid,
281  const char *str)
282 {
283  put_ebml_binary(pb, elementid, str, strlen(str));
284 }
285 
286 /**
287  * Write a void element of a given size. Useful for reserving space in
288  * the file to be written to later.
289  *
290  * @param size The number of bytes to reserve, which must be at least 2.
291  */
292 static void put_ebml_void(AVIOContext *pb, uint64_t size)
293 {
294  int64_t currentpos = avio_tell(pb);
295 
296  av_assert0(size >= 2);
297 
299  // we need to subtract the length needed to store the size from the
300  // size we need to reserve so 2 cases, we use 8 bytes to store the
301  // size if possible, 1 byte otherwise
302  if (size < 10)
303  put_ebml_num(pb, size - 2, 0);
304  else
305  put_ebml_num(pb, size - 9, 8);
306  ffio_fill(pb, 0, currentpos + size - avio_tell(pb));
307 }
308 
309 static ebml_master start_ebml_master(AVIOContext *pb, unsigned int elementid,
310  uint64_t expectedsize)
311 {
312  int bytes = expectedsize ? ebml_num_size(expectedsize) : 8;
313  put_ebml_id(pb, elementid);
314  put_ebml_size_unknown(pb, bytes);
315  return (ebml_master) {avio_tell(pb), bytes };
316 }
317 
319 {
320  int64_t pos = avio_tell(pb);
321 
322  if (avio_seek(pb, master.pos - master.sizebytes, SEEK_SET) < 0)
323  return;
324  put_ebml_num(pb, pos - master.pos, master.sizebytes);
325  avio_seek(pb, pos, SEEK_SET);
326 }
327 
329  ebml_master *master, unsigned int elementid, uint64_t expectedsize)
330 {
331  int ret;
332 
333  if ((ret = avio_open_dyn_buf(dyn_cp)) < 0)
334  return ret;
335 
336  if (pb->seekable & AVIO_SEEKABLE_NORMAL) {
337  *master = start_ebml_master(pb, elementid, expectedsize);
338  if (mkv->write_crc && mkv->mode != MODE_WEBM)
339  put_ebml_void(*dyn_cp, 6); /* Reserve space for CRC32 so position/size calculations using avio_tell() take it into account */
340  } else
341  *master = start_ebml_master(*dyn_cp, elementid, expectedsize);
342 
343  return 0;
344 }
345 
348 {
349  uint8_t *buf, crc[4];
350  int size, skip = 0;
351 
352  if (pb->seekable & AVIO_SEEKABLE_NORMAL) {
353  size = avio_close_dyn_buf(*dyn_cp, &buf);
354  if (mkv->write_crc && mkv->mode != MODE_WEBM) {
355  skip = 6; /* Skip reserved 6-byte long void element from the dynamic buffer. */
356  AV_WL32(crc, av_crc(av_crc_get_table(AV_CRC_32_IEEE_LE), UINT32_MAX, buf + skip, size - skip) ^ UINT32_MAX);
357  put_ebml_binary(pb, EBML_ID_CRC32, crc, sizeof(crc));
358  }
359  avio_write(pb, buf + skip, size - skip);
360  end_ebml_master(pb, master);
361  } else {
362  end_ebml_master(*dyn_cp, master);
363  size = avio_close_dyn_buf(*dyn_cp, &buf);
364  avio_write(pb, buf, size);
365  }
366  av_free(buf);
367  *dyn_cp = NULL;
368 }
369 
370 /**
371 * Complete ebml master whithout destroying the buffer, allowing for later updates
372 */
375 {
376  if (pb->seekable & AVIO_SEEKABLE_NORMAL) {
377 
378  uint8_t *buf;
379  int size = avio_get_dyn_buf(*dyn_cp, &buf);
380 
381  avio_write(pb, buf, size);
382  end_ebml_master(pb, master);
383  }
384 }
385 
386 static void put_xiph_size(AVIOContext *pb, int size)
387 {
388  ffio_fill(pb, 255, size / 255);
389  avio_w8(pb, size % 255);
390 }
391 
392 /**
393  * Free the members allocated in the mux context.
394  */
395 static void mkv_free(MatroskaMuxContext *mkv) {
396  uint8_t* buf;
397  if (mkv->dyn_bc) {
398  avio_close_dyn_buf(mkv->dyn_bc, &buf);
399  av_free(buf);
400  }
401  if (mkv->info_bc) {
402  avio_close_dyn_buf(mkv->info_bc, &buf);
403  av_free(buf);
404  }
405  if (mkv->tracks_bc) {
406  avio_close_dyn_buf(mkv->tracks_bc, &buf);
407  av_free(buf);
408  }
409  if (mkv->tags_bc) {
410  avio_close_dyn_buf(mkv->tags_bc, &buf);
411  av_free(buf);
412  }
413  if (mkv->main_seekhead) {
415  av_freep(&mkv->main_seekhead);
416  }
417  if (mkv->cues) {
418  av_freep(&mkv->cues->entries);
419  av_freep(&mkv->cues);
420  }
421  if (mkv->attachments) {
422  av_freep(&mkv->attachments->entries);
423  av_freep(&mkv->attachments);
424  }
425  av_freep(&mkv->tracks);
426  av_freep(&mkv->stream_durations);
428 }
429 
430 /**
431  * Initialize a mkv_seekhead element to be ready to index level 1 Matroska
432  * elements. If a maximum number of elements is specified, enough space
433  * will be reserved at the current file location to write a seek head of
434  * that size.
435  *
436  * @param segment_offset The absolute offset to the position in the file
437  * where the segment begins.
438  * @param numelements The maximum number of elements that will be indexed
439  * by this seek head, 0 if unlimited.
440  */
441 static mkv_seekhead *mkv_start_seekhead(AVIOContext *pb, int64_t segment_offset,
442  int numelements)
443 {
444  mkv_seekhead *new_seekhead = av_mallocz(sizeof(mkv_seekhead));
445  if (!new_seekhead)
446  return NULL;
447 
448  new_seekhead->segment_offset = segment_offset;
449 
450  if (numelements > 0) {
451  new_seekhead->filepos = avio_tell(pb);
452  // 21 bytes max for a seek entry, 10 bytes max for the SeekHead ID
453  // and size, 6 bytes for a CRC32 element, and 3 bytes to guarantee
454  // that an EBML void element will fit afterwards
455  new_seekhead->reserved_size = numelements * MAX_SEEKENTRY_SIZE + 19;
456  new_seekhead->max_entries = numelements;
457  put_ebml_void(pb, new_seekhead->reserved_size);
458  }
459  return new_seekhead;
460 }
461 
462 static int mkv_add_seekhead_entry(mkv_seekhead *seekhead, unsigned int elementid, uint64_t filepos)
463 {
464  mkv_seekhead_entry *entries = seekhead->entries;
465 
466  // don't store more elements than we reserved space for
467  if (seekhead->max_entries > 0 && seekhead->max_entries <= seekhead->num_entries)
468  return -1;
469 
470  entries = av_realloc_array(entries, seekhead->num_entries + 1, sizeof(mkv_seekhead_entry));
471  if (!entries)
472  return AVERROR(ENOMEM);
473  seekhead->entries = entries;
474 
475  seekhead->entries[seekhead->num_entries].elementid = elementid;
476  seekhead->entries[seekhead->num_entries++].segmentpos = filepos - seekhead->segment_offset;
477 
478  return 0;
479 }
480 
481 /**
482  * Write the seek head to the file and free it. If a maximum number of
483  * elements was specified to mkv_start_seekhead(), the seek head will
484  * be written at the location reserved for it. Otherwise, it is written
485  * at the current location in the file.
486  *
487  * @return The file offset where the seekhead was written,
488  * -1 if an error occurred.
489  */
491 {
492  AVIOContext *dyn_cp;
493  mkv_seekhead *seekhead = mkv->main_seekhead;
494  ebml_master metaseek, seekentry;
495  int64_t currentpos;
496  int i;
497 
498  currentpos = avio_tell(pb);
499 
500  if (seekhead->reserved_size > 0) {
501  if (avio_seek(pb, seekhead->filepos, SEEK_SET) < 0) {
502  currentpos = -1;
503  goto fail;
504  }
505  }
506 
507  if (start_ebml_master_crc32(pb, &dyn_cp, mkv, &metaseek, MATROSKA_ID_SEEKHEAD,
508  seekhead->reserved_size) < 0) {
509  currentpos = -1;
510  goto fail;
511  }
512 
513  for (i = 0; i < seekhead->num_entries; i++) {
514  mkv_seekhead_entry *entry = &seekhead->entries[i];
515 
517 
519  put_ebml_num(dyn_cp, ebml_id_size(entry->elementid), 0);
520  put_ebml_id(dyn_cp, entry->elementid);
521 
523  end_ebml_master(dyn_cp, seekentry);
524  }
525  end_ebml_master_crc32(pb, &dyn_cp, mkv, metaseek);
526 
527  if (seekhead->reserved_size > 0) {
528  uint64_t remaining = seekhead->filepos + seekhead->reserved_size - avio_tell(pb);
529  put_ebml_void(pb, remaining);
530  avio_seek(pb, currentpos, SEEK_SET);
531 
532  currentpos = seekhead->filepos;
533  }
534 fail:
536  av_freep(&mkv->main_seekhead);
537 
538  return currentpos;
539 }
540 
541 static mkv_cues *mkv_start_cues(int64_t segment_offset)
542 {
543  mkv_cues *cues = av_mallocz(sizeof(mkv_cues));
544  if (!cues)
545  return NULL;
546 
547  cues->segment_offset = segment_offset;
548  return cues;
549 }
550 
551 static int mkv_add_cuepoint(mkv_cues *cues, int stream, int tracknum, int64_t ts,
552  int64_t cluster_pos, int64_t relative_pos, int64_t duration)
553 {
554  mkv_cuepoint *entries = cues->entries;
555 
556  if (ts < 0)
557  return 0;
558 
559  entries = av_realloc_array(entries, cues->num_entries + 1, sizeof(mkv_cuepoint));
560  if (!entries)
561  return AVERROR(ENOMEM);
562  cues->entries = entries;
563 
564  cues->entries[cues->num_entries].pts = ts;
565  cues->entries[cues->num_entries].stream_idx = stream;
566  cues->entries[cues->num_entries].tracknum = tracknum;
567  cues->entries[cues->num_entries].cluster_pos = cluster_pos - cues->segment_offset;
568  cues->entries[cues->num_entries].relative_pos = relative_pos;
569  cues->entries[cues->num_entries++].duration = duration;
570 
571  return 0;
572 }
573 
574 static int64_t mkv_write_cues(AVFormatContext *s, mkv_cues *cues, mkv_track *tracks, int num_tracks)
575 {
576  MatroskaMuxContext *mkv = s->priv_data;
577  AVIOContext *dyn_cp, *pb = s->pb;
578  ebml_master cues_element;
579  int64_t currentpos;
580  int i, j, ret;
581 
582  currentpos = avio_tell(pb);
583  ret = start_ebml_master_crc32(pb, &dyn_cp, mkv, &cues_element, MATROSKA_ID_CUES, 0);
584  if (ret < 0)
585  return ret;
586 
587  for (i = 0; i < cues->num_entries; i++) {
588  ebml_master cuepoint, track_positions;
589  mkv_cuepoint *entry = &cues->entries[i];
590  uint64_t pts = entry->pts;
591  int ctp_nb = 0;
592 
593  // Calculate the number of entries, so we know the element size
594  for (j = 0; j < num_tracks; j++)
595  tracks[j].has_cue = 0;
596  for (j = 0; j < cues->num_entries - i && entry[j].pts == pts; j++) {
597  int tracknum = entry[j].stream_idx;
598  av_assert0(tracknum>=0 && tracknum<num_tracks);
599  if (tracks[tracknum].has_cue && s->streams[tracknum]->codecpar->codec_type != AVMEDIA_TYPE_SUBTITLE)
600  continue;
601  tracks[tracknum].has_cue = 1;
602  ctp_nb ++;
603  }
604 
605  cuepoint = start_ebml_master(dyn_cp, MATROSKA_ID_POINTENTRY, MAX_CUEPOINT_SIZE(ctp_nb));
606  put_ebml_uint(dyn_cp, MATROSKA_ID_CUETIME, pts);
607 
608  // put all the entries from different tracks that have the exact same
609  // timestamp into the same CuePoint
610  for (j = 0; j < num_tracks; j++)
611  tracks[j].has_cue = 0;
612  for (j = 0; j < cues->num_entries - i && entry[j].pts == pts; j++) {
613  int tracknum = entry[j].stream_idx;
614  av_assert0(tracknum>=0 && tracknum<num_tracks);
615  if (tracks[tracknum].has_cue && s->streams[tracknum]->codecpar->codec_type != AVMEDIA_TYPE_SUBTITLE)
616  continue;
617  tracks[tracknum].has_cue = 1;
619  put_ebml_uint(dyn_cp, MATROSKA_ID_CUETRACK , entry[j].tracknum );
620  put_ebml_uint(dyn_cp, MATROSKA_ID_CUECLUSTERPOSITION , entry[j].cluster_pos);
621  put_ebml_uint(dyn_cp, MATROSKA_ID_CUERELATIVEPOSITION, entry[j].relative_pos);
622  if (entry[j].duration != -1)
623  put_ebml_uint(dyn_cp, MATROSKA_ID_CUEDURATION , entry[j].duration);
624  end_ebml_master(dyn_cp, track_positions);
625  }
626  i += j - 1;
627  end_ebml_master(dyn_cp, cuepoint);
628  }
629  end_ebml_master_crc32(pb, &dyn_cp, mkv, cues_element);
630 
631  return currentpos;
632 }
633 
635 {
636  const uint8_t *header_start[3];
637  int header_len[3];
638  int first_header_size;
639  int j;
640 
641  if (par->codec_id == AV_CODEC_ID_VORBIS)
642  first_header_size = 30;
643  else
644  first_header_size = 42;
645 
647  first_header_size, header_start, header_len) < 0) {
648  av_log(s, AV_LOG_ERROR, "Extradata corrupt.\n");
649  return -1;
650  }
651 
652  avio_w8(pb, 2); // number packets - 1
653  for (j = 0; j < 2; j++) {
654  put_xiph_size(pb, header_len[j]);
655  }
656  for (j = 0; j < 3; j++)
657  avio_write(pb, header_start[j], header_len[j]);
658 
659  return 0;
660 }
661 
663 {
664  if (par->extradata && par->extradata_size == 2)
665  avio_write(pb, par->extradata, 2);
666  else
667  avio_wl16(pb, 0x403); // fallback to the version mentioned in matroska specs
668  return 0;
669 }
670 
672  AVIOContext *pb, AVCodecParameters *par)
673 {
674  int write_comment = (par->channel_layout &&
675  !(par->channel_layout & ~0x3ffffULL) &&
677  int ret = ff_flac_write_header(pb, par->extradata, par->extradata_size,
678  !write_comment);
679 
680  if (ret < 0)
681  return ret;
682 
683  if (write_comment) {
684  const char *vendor = (s->flags & AVFMT_FLAG_BITEXACT) ?
685  "Lavf" : LIBAVFORMAT_IDENT;
686  AVDictionary *dict = NULL;
687  uint8_t buf[32], *data, *p;
688  int64_t len;
689 
690  snprintf(buf, sizeof(buf), "0x%"PRIx64, par->channel_layout);
691  av_dict_set(&dict, "WAVEFORMATEXTENSIBLE_CHANNEL_MASK", buf, 0);
692 
693  len = ff_vorbiscomment_length(dict, vendor);
694  if (len >= ((1<<24) - 4))
695  return AVERROR(EINVAL);
696 
697  data = av_malloc(len + 4);
698  if (!data) {
699  av_dict_free(&dict);
700  return AVERROR(ENOMEM);
701  }
702 
703  data[0] = 0x84;
704  AV_WB24(data + 1, len);
705 
706  p = data + 4;
707  ff_vorbiscomment_write(&p, &dict, vendor);
708 
709  avio_write(pb, data, len + 4);
710 
711  av_freep(&data);
712  av_dict_free(&dict);
713  }
714 
715  return 0;
716 }
717 
719  int *sample_rate, int *output_sample_rate)
720 {
721  MPEG4AudioConfig mp4ac;
722 
723  if (avpriv_mpeg4audio_get_config(&mp4ac, par->extradata,
724  par->extradata_size * 8, 1) < 0) {
725  av_log(s, AV_LOG_ERROR,
726  "Error parsing AAC extradata, unable to determine samplerate.\n");
727  return AVERROR(EINVAL);
728  }
729 
730  *sample_rate = mp4ac.sample_rate;
731  *output_sample_rate = mp4ac.ext_sample_rate;
732  return 0;
733 }
734 
736  AVCodecParameters *par,
737  AVIOContext *dyn_cp)
738 {
739  switch (par->codec_id) {
740  case AV_CODEC_ID_VORBIS:
741  case AV_CODEC_ID_THEORA:
742  return put_xiph_codecpriv(s, dyn_cp, par);
743  case AV_CODEC_ID_FLAC:
744  return put_flac_codecpriv(s, dyn_cp, par);
745  case AV_CODEC_ID_WAVPACK:
746  return put_wv_codecpriv(dyn_cp, par);
747  case AV_CODEC_ID_H264:
748  return ff_isom_write_avcc(dyn_cp, par->extradata,
749  par->extradata_size);
750  case AV_CODEC_ID_HEVC:
751  ff_isom_write_hvcc(dyn_cp, par->extradata,
752  par->extradata_size, 0);
753  return 0;
754  case AV_CODEC_ID_ALAC:
755  if (par->extradata_size < 36) {
756  av_log(s, AV_LOG_ERROR,
757  "Invalid extradata found, ALAC expects a 36-byte "
758  "QuickTime atom.");
759  return AVERROR_INVALIDDATA;
760  } else
761  avio_write(dyn_cp, par->extradata + 12,
762  par->extradata_size - 12);
763  break;
764  default:
765  if (par->codec_id == AV_CODEC_ID_PRORES &&
767  avio_wl32(dyn_cp, par->codec_tag);
768  } else if (par->extradata_size && par->codec_id != AV_CODEC_ID_TTA)
769  avio_write(dyn_cp, par->extradata, par->extradata_size);
770  }
771 
772  return 0;
773 }
774 
776  AVCodecParameters *par,
777  int native_id, int qt_id)
778 {
779  AVIOContext *dyn_cp;
780  uint8_t *codecpriv;
781  int ret, codecpriv_size;
782 
783  ret = avio_open_dyn_buf(&dyn_cp);
784  if (ret < 0)
785  return ret;
786 
787  if (native_id) {
788  ret = mkv_write_native_codecprivate(s, par, dyn_cp);
789  } else if (par->codec_type == AVMEDIA_TYPE_VIDEO) {
790  if (qt_id) {
791  if (!par->codec_tag)
793  par->codec_id);
796  ) {
797  int i;
798  avio_wb32(dyn_cp, 0x5a + par->extradata_size);
799  avio_wl32(dyn_cp, par->codec_tag);
800  for(i = 0; i < 0x5a - 8; i++)
801  avio_w8(dyn_cp, 0);
802  }
803  avio_write(dyn_cp, par->extradata, par->extradata_size);
804  } else {
806  av_log(s, AV_LOG_WARNING, "codec %s is not supported by this format\n",
807  avcodec_get_name(par->codec_id));
808 
809  if (!par->codec_tag)
811  par->codec_id);
812  if (!par->codec_tag && par->codec_id != AV_CODEC_ID_RAWVIDEO) {
813  av_log(s, AV_LOG_ERROR, "No bmp codec tag found for codec %s\n",
814  avcodec_get_name(par->codec_id));
815  ret = AVERROR(EINVAL);
816  }
817 
818  ff_put_bmp_header(dyn_cp, par, ff_codec_bmp_tags, 0, 0);
819  }
820  } else if (par->codec_type == AVMEDIA_TYPE_AUDIO) {
821  unsigned int tag;
823  if (!tag) {
824  av_log(s, AV_LOG_ERROR, "No wav codec tag found for codec %s\n",
825  avcodec_get_name(par->codec_id));
826  ret = AVERROR(EINVAL);
827  }
828  if (!par->codec_tag)
829  par->codec_tag = tag;
830 
832  }
833 
834  codecpriv_size = avio_close_dyn_buf(dyn_cp, &codecpriv);
835  if (codecpriv_size)
837  codecpriv_size);
838  av_free(codecpriv);
839  return ret;
840 }
841 
843  AVIOContext *dyn_cp;
844  uint8_t *colorinfo_ptr;
845  int side_data_size = 0;
846  int ret, colorinfo_size;
847  const uint8_t *side_data = av_stream_get_side_data(
848  st, AV_PKT_DATA_MASTERING_DISPLAY_METADATA, &side_data_size);
849 
850  ret = avio_open_dyn_buf(&dyn_cp);
851  if (ret < 0)
852  return ret;
853 
854  if (par->color_trc != AVCOL_TRC_UNSPECIFIED &&
855  par->color_trc < AVCOL_TRC_NB) {
857  par->color_trc);
858  }
859  if (par->color_space != AVCOL_SPC_UNSPECIFIED &&
860  par->color_space < AVCOL_SPC_NB) {
862  }
864  par->color_primaries < AVCOL_PRI_NB) {
866  }
867  if (par->color_range != AVCOL_RANGE_UNSPECIFIED &&
868  par->color_range < AVCOL_RANGE_NB) {
870  }
873  int xpos, ypos;
874 
875  avcodec_enum_to_chroma_pos(&xpos, &ypos, par->chroma_location);
876  put_ebml_uint(dyn_cp, MATROSKA_ID_VIDEOCOLORCHROMASITINGHORZ, (xpos >> 7) + 1);
877  put_ebml_uint(dyn_cp, MATROSKA_ID_VIDEOCOLORCHROMASITINGVERT, (ypos >> 7) + 1);
878  }
879  if (side_data_size == sizeof(AVMasteringDisplayMetadata)) {
880  ebml_master meta_element = start_ebml_master(
882  const AVMasteringDisplayMetadata *metadata =
883  (const AVMasteringDisplayMetadata*)side_data;
884  if (metadata->has_primaries) {
886  av_q2d(metadata->display_primaries[0][0]));
888  av_q2d(metadata->display_primaries[0][1]));
890  av_q2d(metadata->display_primaries[1][0]));
892  av_q2d(metadata->display_primaries[1][1]));
894  av_q2d(metadata->display_primaries[2][0]));
896  av_q2d(metadata->display_primaries[2][1]));
898  av_q2d(metadata->white_point[0]));
900  av_q2d(metadata->white_point[1]));
901  }
902  if (metadata->has_luminance) {
904  av_q2d(metadata->max_luminance));
906  av_q2d(metadata->min_luminance));
907  }
908  end_ebml_master(dyn_cp, meta_element);
909  }
910 
911  colorinfo_size = avio_close_dyn_buf(dyn_cp, &colorinfo_ptr);
912  if (colorinfo_size) {
913  ebml_master colorinfo = start_ebml_master(pb, MATROSKA_ID_VIDEOCOLOR, colorinfo_size);
914  avio_write(pb, colorinfo_ptr, colorinfo_size);
915  end_ebml_master(pb, colorinfo);
916  }
917  av_free(colorinfo_ptr);
918  return 0;
919 }
920 
922 {
923  int side_data_size = 0;
924  const AVSphericalMapping *spherical =
926  &side_data_size);
927 
928  if (side_data_size) {
929  AVIOContext *dyn_cp;
930  uint8_t *projection_ptr;
931  int ret, projection_size;
932 
933  ret = avio_open_dyn_buf(&dyn_cp);
934  if (ret < 0)
935  return ret;
936 
937  switch (spherical->projection) {
941  break;
943  {
944  AVIOContext b;
945  uint8_t private[20];
946  ffio_init_context(&b, private, sizeof(private),
947  1, NULL, NULL, NULL, NULL);
950  avio_wb32(&b, 0); // version + flags
951  avio_wb32(&b, spherical->bound_top);
952  avio_wb32(&b, spherical->bound_bottom);
953  avio_wb32(&b, spherical->bound_left);
954  avio_wb32(&b, spherical->bound_right);
955  put_ebml_binary(dyn_cp, MATROSKA_ID_VIDEOPROJECTIONPRIVATE, private, sizeof(private));
956  break;
957  }
959  {
960  AVIOContext b;
961  uint8_t private[12];
962  ffio_init_context(&b, private, sizeof(private),
963  1, NULL, NULL, NULL, NULL);
966  avio_wb32(&b, 0); // version + flags
967  avio_wb32(&b, 0); // layout
968  avio_wb32(&b, spherical->padding);
969  put_ebml_binary(dyn_cp, MATROSKA_ID_VIDEOPROJECTIONPRIVATE, private, sizeof(private));
970  break;
971  }
972  default:
973  av_log(s, AV_LOG_WARNING, "Unknown projection type\n");
974  goto end;
975  }
976 
977  if (spherical->yaw)
978  put_ebml_float(dyn_cp, MATROSKA_ID_VIDEOPROJECTIONPOSEYAW, (double)spherical->yaw / (1 << 16));
979  if (spherical->pitch)
980  put_ebml_float(dyn_cp, MATROSKA_ID_VIDEOPROJECTIONPOSEPITCH, (double)spherical->pitch / (1 << 16));
981  if (spherical->roll)
982  put_ebml_float(dyn_cp, MATROSKA_ID_VIDEOPROJECTIONPOSEROLL, (double)spherical->roll / (1 << 16));
983 
984 end:
985  projection_size = avio_close_dyn_buf(dyn_cp, &projection_ptr);
986  if (projection_size) {
987  ebml_master projection = start_ebml_master(pb, MATROSKA_ID_VIDEOPROJECTION, projection_size);
988  avio_write(pb, projection_ptr, projection_size);
989  end_ebml_master(pb, projection);
990  }
991  av_freep(&projection_ptr);
992  }
993 
994  return 0;
995 }
996 
998  enum AVFieldOrder field_order)
999 {
1000  switch (field_order) {
1001  case AV_FIELD_UNKNOWN:
1002  break;
1003  case AV_FIELD_PROGRESSIVE:
1006  break;
1007  case AV_FIELD_TT:
1008  case AV_FIELD_BB:
1009  case AV_FIELD_TB:
1010  case AV_FIELD_BT:
1013  if (mode != MODE_WEBM) {
1014  switch (field_order) {
1015  case AV_FIELD_TT:
1018  break;
1019  case AV_FIELD_BB:
1022  break;
1023  case AV_FIELD_TB:
1026  break;
1027  case AV_FIELD_BT:
1030  break;
1031  }
1032  }
1033  }
1034 }
1035 
1037  AVStream *st, int mode, int *h_width, int *h_height)
1038 {
1039  int i;
1040  int ret = 0;
1043 
1044  *h_width = 1;
1045  *h_height = 1;
1046  // convert metadata into proper side data and add it to the stream
1047  if ((tag = av_dict_get(st->metadata, "stereo_mode", NULL, 0)) ||
1048  (tag = av_dict_get( s->metadata, "stereo_mode", NULL, 0))) {
1049  int stereo_mode = atoi(tag->value);
1050 
1051  for (i=0; i<MATROSKA_VIDEO_STEREOMODE_TYPE_NB; i++)
1052  if (!strcmp(tag->value, ff_matroska_video_stereo_mode[i])){
1053  stereo_mode = i;
1054  break;
1055  }
1056 
1057  if (stereo_mode < MATROSKA_VIDEO_STEREOMODE_TYPE_NB &&
1058  stereo_mode != 10 && stereo_mode != 12) {
1059  int ret = ff_mkv_stereo3d_conv(st, stereo_mode);
1060  if (ret < 0)
1061  return ret;
1062  }
1063  }
1064 
1065  // iterate to find the stereo3d side data
1066  for (i = 0; i < st->nb_side_data; i++) {
1067  AVPacketSideData sd = st->side_data[i];
1068  if (sd.type == AV_PKT_DATA_STEREO3D) {
1069  AVStereo3D *stereo = (AVStereo3D *)sd.data;
1070 
1071  switch (stereo->type) {
1072  case AV_STEREO3D_2D:
1074  break;
1076  format = (stereo->flags & AV_STEREO3D_FLAG_INVERT)
1079  *h_width = 2;
1080  break;
1081  case AV_STEREO3D_TOPBOTTOM:
1083  if (stereo->flags & AV_STEREO3D_FLAG_INVERT)
1084  format--;
1085  *h_height = 2;
1086  break;
1089  if (stereo->flags & AV_STEREO3D_FLAG_INVERT)
1090  format--;
1091  break;
1092  case AV_STEREO3D_LINES:
1094  if (stereo->flags & AV_STEREO3D_FLAG_INVERT)
1095  format--;
1096  *h_height = 2;
1097  break;
1098  case AV_STEREO3D_COLUMNS:
1100  if (stereo->flags & AV_STEREO3D_FLAG_INVERT)
1101  format--;
1102  *h_width = 2;
1103  break;
1106  if (stereo->flags & AV_STEREO3D_FLAG_INVERT)
1107  format++;
1108  break;
1109  }
1110  break;
1111  }
1112  }
1113 
1114  if (format == MATROSKA_VIDEO_STEREOMODE_TYPE_NB)
1115  return ret;
1116 
1117  // if webm, do not write unsupported modes
1118  if ((mode == MODE_WEBM &&
1121  || format >= MATROSKA_VIDEO_STEREOMODE_TYPE_NB) {
1122  av_log(s, AV_LOG_ERROR,
1123  "The specified stereo mode is not valid.\n");
1125  return AVERROR(EINVAL);
1126  }
1127 
1128  // write StereoMode if format is valid
1130 
1131  return ret;
1132 }
1133 
1135  int i, AVIOContext *pb, int default_stream_exists)
1136 {
1137  AVStream *st = s->streams[i];
1138  AVCodecParameters *par = st->codecpar;
1139  ebml_master subinfo, track;
1140  int native_id = 0;
1141  int qt_id = 0;
1143  int sample_rate = par->sample_rate;
1144  int output_sample_rate = 0;
1145  int display_width_div = 1;
1146  int display_height_div = 1;
1147  int j, ret;
1149 
1150  if (par->codec_type == AVMEDIA_TYPE_ATTACHMENT) {
1151  mkv->have_attachments = 1;
1152  return 0;
1153  }
1154 
1155  if (par->codec_type == AVMEDIA_TYPE_AUDIO) {
1156  if (!bit_depth && par->codec_id != AV_CODEC_ID_ADPCM_G726) {
1157  if (par->bits_per_raw_sample)
1158  bit_depth = par->bits_per_raw_sample;
1159  else
1160  bit_depth = av_get_bytes_per_sample(par->format) << 3;
1161  }
1162  if (!bit_depth)
1163  bit_depth = par->bits_per_coded_sample;
1164  }
1165 
1166  if (par->codec_id == AV_CODEC_ID_AAC) {
1167  ret = get_aac_sample_rates(s, par, &sample_rate, &output_sample_rate);
1168  if (ret < 0)
1169  return ret;
1170  }
1171 
1172  track = start_ebml_master(pb, MATROSKA_ID_TRACKENTRY, 0);
1174  mkv->is_dash ? mkv->dash_track_number : i + 1);
1176  mkv->is_dash ? mkv->dash_track_number : i + 1);
1177  put_ebml_uint (pb, MATROSKA_ID_TRACKFLAGLACING , 0); // no lacing (yet)
1178 
1179  if ((tag = av_dict_get(st->metadata, "title", NULL, 0)))
1181  tag = av_dict_get(st->metadata, "language", NULL, 0);
1182  if (mkv->mode != MODE_WEBM || par->codec_id != AV_CODEC_ID_WEBVTT) {
1183  put_ebml_string(pb, MATROSKA_ID_TRACKLANGUAGE, tag && tag->value ? tag->value:"und");
1184  } else if (tag && tag->value) {
1186  }
1187 
1188  // The default value for TRACKFLAGDEFAULT is 1, so add element
1189  // if we need to clear it.
1190  if (default_stream_exists && !(st->disposition & AV_DISPOSITION_DEFAULT))
1192 
1195 
1196  if (mkv->mode == MODE_WEBM && par->codec_id == AV_CODEC_ID_WEBVTT) {
1197  const char *codec_id;
1199  codec_id = "D_WEBVTT/CAPTIONS";
1200  native_id = MATROSKA_TRACK_TYPE_SUBTITLE;
1201  } else if (st->disposition & AV_DISPOSITION_DESCRIPTIONS) {
1202  codec_id = "D_WEBVTT/DESCRIPTIONS";
1203  native_id = MATROSKA_TRACK_TYPE_METADATA;
1204  } else if (st->disposition & AV_DISPOSITION_METADATA) {
1205  codec_id = "D_WEBVTT/METADATA";
1206  native_id = MATROSKA_TRACK_TYPE_METADATA;
1207  } else {
1208  codec_id = "D_WEBVTT/SUBTITLES";
1209  native_id = MATROSKA_TRACK_TYPE_SUBTITLE;
1210  }
1211  put_ebml_string(pb, MATROSKA_ID_CODECID, codec_id);
1212  } else {
1213  // look for a codec ID string specific to mkv to use,
1214  // if none are found, use AVI codes
1215  if (par->codec_id != AV_CODEC_ID_RAWVIDEO || par->codec_tag) {
1216  for (j = 0; ff_mkv_codec_tags[j].id != AV_CODEC_ID_NONE; j++) {
1217  if (ff_mkv_codec_tags[j].id == par->codec_id && par->codec_id != AV_CODEC_ID_FFV1) {
1219  native_id = 1;
1220  break;
1221  }
1222  }
1223  } else {
1224  if (mkv->allow_raw_vfw) {
1225  native_id = 0;
1226  } else {
1227  av_log(s, AV_LOG_ERROR, "Raw RGB is not supported Natively in Matroska, you can use AVI or NUT or\n"
1228  "If you would like to store it anyway using VFW mode, enable allow_raw_vfw (-allow_raw_vfw 1)\n");
1229  return AVERROR(EINVAL);
1230  }
1231  }
1232  }
1233 
1234  if (par->codec_type == AVMEDIA_TYPE_AUDIO && par->initial_padding && par->codec_id == AV_CODEC_ID_OPUS) {
1235  int64_t codecdelay = av_rescale_q(par->initial_padding,
1236  (AVRational){ 1, 48000 },
1237  (AVRational){ 1, 1000000000 });
1238  if (codecdelay < 0) {
1239  av_log(s, AV_LOG_ERROR, "Initial padding is invalid\n");
1240  return AVERROR(EINVAL);
1241  }
1242 // mkv->tracks[i].ts_offset = av_rescale_q(par->initial_padding,
1243 // (AVRational){ 1, par->sample_rate },
1244 // st->time_base);
1245 
1246  put_ebml_uint(pb, MATROSKA_ID_CODECDELAY, codecdelay);
1247  }
1248  if (par->codec_id == AV_CODEC_ID_OPUS) {
1250  }
1251 
1252  if (mkv->mode == MODE_WEBM && !(par->codec_id == AV_CODEC_ID_VP8 ||
1253  par->codec_id == AV_CODEC_ID_VP9 ||
1254  par->codec_id == AV_CODEC_ID_OPUS ||
1255  par->codec_id == AV_CODEC_ID_VORBIS ||
1256  par->codec_id == AV_CODEC_ID_WEBVTT)) {
1258  "Only VP8 or VP9 video and Vorbis or Opus audio and WebVTT subtitles are supported for WebM.\n");
1259  return AVERROR(EINVAL);
1260  }
1261 
1262  switch (par->codec_type) {
1263  case AVMEDIA_TYPE_VIDEO:
1264  mkv->have_video = 1;
1266 
1267  if( st->avg_frame_rate.num > 0 && st->avg_frame_rate.den > 0
1268  && av_cmp_q(av_inv_q(st->avg_frame_rate), st->time_base) > 0)
1269  put_ebml_uint(pb, MATROSKA_ID_TRACKDEFAULTDURATION, 1000000000LL * st->avg_frame_rate.den / st->avg_frame_rate.num);
1270  else
1271  put_ebml_uint(pb, MATROSKA_ID_TRACKDEFAULTDURATION, 1000000000LL * st->time_base.num / st->time_base.den);
1272 
1273  if (!native_id &&
1274  ff_codec_get_tag(ff_codec_movvideo_tags, par->codec_id) &&
1275  ((!ff_codec_get_tag(ff_codec_bmp_tags, par->codec_id) && par->codec_id != AV_CODEC_ID_RAWVIDEO) ||
1276  par->codec_id == AV_CODEC_ID_SVQ1 ||
1277  par->codec_id == AV_CODEC_ID_SVQ3 ||
1278  par->codec_id == AV_CODEC_ID_CINEPAK))
1279  qt_id = 1;
1280 
1281  if (qt_id)
1282  put_ebml_string(pb, MATROSKA_ID_CODECID, "V_QUICKTIME");
1283  else if (!native_id) {
1284  // if there is no mkv-specific codec ID, use VFW mode
1285  put_ebml_string(pb, MATROSKA_ID_CODECID, "V_MS/VFW/FOURCC");
1286  mkv->tracks[i].write_dts = 1;
1287  s->internal->avoid_negative_ts_use_pts = 0;
1288  }
1289 
1290  subinfo = start_ebml_master(pb, MATROSKA_ID_TRACKVIDEO, 0);
1291 
1292  put_ebml_uint (pb, MATROSKA_ID_VIDEOPIXELWIDTH , par->width);
1293  put_ebml_uint (pb, MATROSKA_ID_VIDEOPIXELHEIGHT, par->height);
1294 
1295  mkv_write_field_order(pb, mkv->mode, par->field_order);
1296 
1297  // check both side data and metadata for stereo information,
1298  // write the result to the bitstream if any is found
1299  ret = mkv_write_stereo_mode(s, pb, st, mkv->mode,
1300  &display_width_div,
1301  &display_height_div);
1302  if (ret < 0)
1303  return ret;
1304 
1305  if (((tag = av_dict_get(st->metadata, "alpha_mode", NULL, 0)) && atoi(tag->value)) ||
1306  ((tag = av_dict_get( s->metadata, "alpha_mode", NULL, 0)) && atoi(tag->value)) ||
1307  (par->format == AV_PIX_FMT_YUVA420P)) {
1309  }
1310 
1311  // write DisplayWidth and DisplayHeight, they contain the size of
1312  // a single source view and/or the display aspect ratio
1313  if (st->sample_aspect_ratio.num) {
1314  int64_t d_width = av_rescale(par->width, st->sample_aspect_ratio.num, st->sample_aspect_ratio.den);
1315  if (d_width > INT_MAX) {
1316  av_log(s, AV_LOG_ERROR, "Overflow in display width\n");
1317  return AVERROR(EINVAL);
1318  }
1319  if (d_width != par->width || display_width_div != 1 || display_height_div != 1) {
1320  if (mkv->mode == MODE_WEBM || display_width_div != 1 || display_height_div != 1) {
1321  put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYWIDTH , d_width / display_width_div);
1322  put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYHEIGHT, par->height / display_height_div);
1323  } else {
1324  AVRational display_aspect_ratio;
1325  av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den,
1326  par->width * (int64_t)st->sample_aspect_ratio.num,
1327  par->height * (int64_t)st->sample_aspect_ratio.den,
1328  1024 * 1024);
1329  put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYWIDTH, display_aspect_ratio.num);
1330  put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYHEIGHT, display_aspect_ratio.den);
1332  }
1333  }
1334  } else if (display_width_div != 1 || display_height_div != 1) {
1335  put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYWIDTH , par->width / display_width_div);
1336  put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYHEIGHT, par->height / display_height_div);
1337  } else if (mkv->mode != MODE_WEBM)
1339 
1340  if (par->codec_id == AV_CODEC_ID_RAWVIDEO) {
1341  uint32_t color_space = av_le2ne32(par->codec_tag);
1342  put_ebml_binary(pb, MATROSKA_ID_VIDEOCOLORSPACE, &color_space, sizeof(color_space));
1343  }
1344  ret = mkv_write_video_color(pb, par, st);
1345  if (ret < 0)
1346  return ret;
1347  ret = mkv_write_video_projection(s, pb, st);
1348  if (ret < 0)
1349  return ret;
1350  end_ebml_master(pb, subinfo);
1351  break;
1352 
1353  case AVMEDIA_TYPE_AUDIO:
1355 
1356  if (!native_id)
1357  // no mkv-specific ID, use ACM mode
1358  put_ebml_string(pb, MATROSKA_ID_CODECID, "A_MS/ACM");
1359 
1360  subinfo = start_ebml_master(pb, MATROSKA_ID_TRACKAUDIO, 0);
1361  put_ebml_uint (pb, MATROSKA_ID_AUDIOCHANNELS , par->channels);
1363  if (output_sample_rate)
1364  put_ebml_float(pb, MATROSKA_ID_AUDIOOUTSAMPLINGFREQ, output_sample_rate);
1365  if (bit_depth)
1367  end_ebml_master(pb, subinfo);
1368  break;
1369 
1370  case AVMEDIA_TYPE_SUBTITLE:
1371  if (!native_id) {
1372  av_log(s, AV_LOG_ERROR, "Subtitle codec %d is not supported.\n", par->codec_id);
1373  return AVERROR(ENOSYS);
1374  }
1375 
1376  if (mkv->mode != MODE_WEBM || par->codec_id != AV_CODEC_ID_WEBVTT)
1377  native_id = MATROSKA_TRACK_TYPE_SUBTITLE;
1378 
1379  put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, native_id);
1380  break;
1381  default:
1382  av_log(s, AV_LOG_ERROR, "Only audio, video, and subtitles are supported for Matroska.\n");
1383  return AVERROR(EINVAL);
1384  }
1385 
1386  if (mkv->mode != MODE_WEBM || par->codec_id != AV_CODEC_ID_WEBVTT) {
1387  mkv->tracks[i].codecpriv_offset = avio_tell(pb);
1388  ret = mkv_write_codecprivate(s, pb, par, native_id, qt_id);
1389  if (ret < 0)
1390  return ret;
1391  }
1392 
1393  end_ebml_master(pb, track);
1394 
1395  return 0;
1396 }
1397 
1399 {
1400  MatroskaMuxContext *mkv = s->priv_data;
1401  AVIOContext *pb = s->pb;
1402  int i, ret, default_stream_exists = 0;
1403 
1405  if (ret < 0)
1406  return ret;
1407 
1408  ret = start_ebml_master_crc32(pb, &mkv->tracks_bc, mkv, &mkv->tracks_master, MATROSKA_ID_TRACKS, 0);
1409  if (ret < 0)
1410  return ret;
1411 
1412  for (i = 0; i < s->nb_streams; i++) {
1413  AVStream *st = s->streams[i];
1414  default_stream_exists |= st->disposition & AV_DISPOSITION_DEFAULT;
1415  }
1416  for (i = 0; i < s->nb_streams; i++) {
1417  ret = mkv_write_track(s, mkv, i, mkv->tracks_bc, default_stream_exists);
1418  if (ret < 0)
1419  return ret;
1420  }
1421 
1422  if ((pb->seekable & AVIO_SEEKABLE_NORMAL) && !mkv->is_live)
1424  else
1425  end_ebml_master_crc32(pb, &mkv->tracks_bc, mkv, mkv->tracks_master);
1426 
1427  return 0;
1428 }
1429 
1431 {
1432  MatroskaMuxContext *mkv = s->priv_data;
1433  AVIOContext *dyn_cp, *pb = s->pb;
1434  ebml_master chapters, editionentry;
1435  AVRational scale = {1, 1E9};
1436  int i, ret;
1437 
1438  if (!s->nb_chapters || mkv->wrote_chapters)
1439  return 0;
1440 
1442  if (ret < 0) return ret;
1443 
1444  ret = start_ebml_master_crc32(pb, &dyn_cp, mkv, &chapters, MATROSKA_ID_CHAPTERS, 0);
1445  if (ret < 0) return ret;
1446 
1447  editionentry = start_ebml_master(dyn_cp, MATROSKA_ID_EDITIONENTRY, 0);
1450  for (i = 0; i < s->nb_chapters; i++) {
1451  ebml_master chapteratom, chapterdisplay;
1452  AVChapter *c = s->chapters[i];
1453  int64_t chapterstart = av_rescale_q(c->start, c->time_base, scale);
1454  int64_t chapterend = av_rescale_q(c->end, c->time_base, scale);
1455  AVDictionaryEntry *t = NULL;
1456  if (chapterstart < 0 || chapterstart > chapterend || chapterend < 0) {
1457  av_log(s, AV_LOG_ERROR,
1458  "Invalid chapter start (%"PRId64") or end (%"PRId64").\n",
1459  chapterstart, chapterend);
1460  return AVERROR_INVALIDDATA;
1461  }
1462 
1463  chapteratom = start_ebml_master(dyn_cp, MATROSKA_ID_CHAPTERATOM, 0);
1465  put_ebml_uint(dyn_cp, MATROSKA_ID_CHAPTERTIMESTART, chapterstart);
1466  put_ebml_uint(dyn_cp, MATROSKA_ID_CHAPTERTIMEEND, chapterend);
1469  if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
1470  chapterdisplay = start_ebml_master(dyn_cp, MATROSKA_ID_CHAPTERDISPLAY, 0);
1472  put_ebml_string(dyn_cp, MATROSKA_ID_CHAPLANG , "und");
1473  end_ebml_master(dyn_cp, chapterdisplay);
1474  }
1475  end_ebml_master(dyn_cp, chapteratom);
1476  }
1477  end_ebml_master(dyn_cp, editionentry);
1478  end_ebml_master_crc32(pb, &dyn_cp, mkv, chapters);
1479 
1480  mkv->wrote_chapters = 1;
1481  return 0;
1482 }
1483 
1485 {
1486  uint8_t *key = av_strdup(t->key);
1487  uint8_t *p = key;
1488  const uint8_t *lang = NULL;
1489  ebml_master tag;
1490 
1491  if (!key)
1492  return AVERROR(ENOMEM);
1493 
1494  if ((p = strrchr(p, '-')) &&
1495  (lang = ff_convert_lang_to(p + 1, AV_LANG_ISO639_2_BIBL)))
1496  *p = 0;
1497 
1498  p = key;
1499  while (*p) {
1500  if (*p == ' ')
1501  *p = '_';
1502  else if (*p >= 'a' && *p <= 'z')
1503  *p -= 'a' - 'A';
1504  p++;
1505  }
1506 
1509  if (lang)
1512  end_ebml_master(pb, tag);
1513 
1514  av_freep(&key);
1515  return 0;
1516 }
1517 
1519  unsigned int elementid, unsigned int uid,
1520  ebml_master *tags, ebml_master* tag)
1521 {
1522  AVIOContext *pb;
1523  MatroskaMuxContext *mkv = s->priv_data;
1524  ebml_master targets;
1525  int ret;
1526 
1527  if (!tags->pos) {
1529  if (ret < 0) return ret;
1530 
1531  start_ebml_master_crc32(s->pb, &mkv->tags_bc, mkv, tags, MATROSKA_ID_TAGS, 0);
1532  }
1533  pb = mkv->tags_bc;
1534 
1535  *tag = start_ebml_master(pb, MATROSKA_ID_TAG, 0);
1536  targets = start_ebml_master(pb, MATROSKA_ID_TAGTARGETS, 0);
1537  if (elementid)
1538  put_ebml_uint(pb, elementid, uid);
1539  end_ebml_master(pb, targets);
1540  return 0;
1541 }
1542 
1543 static int mkv_check_tag_name(const char *name, unsigned int elementid)
1544 {
1545  return av_strcasecmp(name, "title") &&
1546  av_strcasecmp(name, "stereo_mode") &&
1547  av_strcasecmp(name, "creation_time") &&
1548  av_strcasecmp(name, "encoding_tool") &&
1549  av_strcasecmp(name, "duration") &&
1550  (elementid != MATROSKA_ID_TAGTARGETS_TRACKUID ||
1551  av_strcasecmp(name, "language")) &&
1552  (elementid != MATROSKA_ID_TAGTARGETS_ATTACHUID ||
1553  (av_strcasecmp(name, "filename") &&
1554  av_strcasecmp(name, "mimetype")));
1555 }
1556 
1557 static int mkv_write_tag(AVFormatContext *s, AVDictionary *m, unsigned int elementid,
1558  unsigned int uid, ebml_master *tags)
1559 {
1560  MatroskaMuxContext *mkv = s->priv_data;
1561  ebml_master tag;
1562  int ret;
1563  AVDictionaryEntry *t = NULL;
1564 
1565  ret = mkv_write_tag_targets(s, elementid, uid, tags, &tag);
1566  if (ret < 0)
1567  return ret;
1568 
1569  while ((t = av_dict_get(m, "", t, AV_DICT_IGNORE_SUFFIX))) {
1570  if (mkv_check_tag_name(t->key, elementid)) {
1571  ret = mkv_write_simpletag(mkv->tags_bc, t);
1572  if (ret < 0)
1573  return ret;
1574  }
1575  }
1576 
1577  end_ebml_master(mkv->tags_bc, tag);
1578  return 0;
1579 }
1580 
1581 static int mkv_check_tag(AVDictionary *m, unsigned int elementid)
1582 {
1583  AVDictionaryEntry *t = NULL;
1584 
1585  while ((t = av_dict_get(m, "", t, AV_DICT_IGNORE_SUFFIX)))
1586  if (mkv_check_tag_name(t->key, elementid))
1587  return 1;
1588 
1589  return 0;
1590 }
1591 
1593 {
1594  MatroskaMuxContext *mkv = s->priv_data;
1595  int i, ret;
1596 
1598 
1599  if (mkv_check_tag(s->metadata, 0)) {
1600  ret = mkv_write_tag(s, s->metadata, 0, 0, &mkv->tags);
1601  if (ret < 0) return ret;
1602  }
1603 
1604  for (i = 0; i < s->nb_streams; i++) {
1605  AVStream *st = s->streams[i];
1606 
1608  continue;
1609 
1611  continue;
1612 
1613  ret = mkv_write_tag(s, st->metadata, MATROSKA_ID_TAGTARGETS_TRACKUID, i + 1, &mkv->tags);
1614  if (ret < 0) return ret;
1615  }
1616 
1617  if ((s->pb->seekable & AVIO_SEEKABLE_NORMAL) && !mkv->is_live) {
1618  for (i = 0; i < s->nb_streams; i++) {
1619  AVIOContext *pb;
1620  AVStream *st = s->streams[i];
1621  ebml_master tag_target;
1622  ebml_master tag;
1623 
1625  continue;
1626 
1627  mkv_write_tag_targets(s, MATROSKA_ID_TAGTARGETS_TRACKUID, i + 1, &mkv->tags, &tag_target);
1628  pb = mkv->tags_bc;
1629 
1631  put_ebml_string(pb, MATROSKA_ID_TAGNAME, "DURATION");
1632  mkv->stream_duration_offsets[i] = avio_tell(pb);
1633 
1634  // Reserve space to write duration as a 20-byte string.
1635  // 2 (ebml id) + 1 (data size) + 20 (data)
1636  put_ebml_void(pb, 23);
1637  end_ebml_master(pb, tag);
1638  end_ebml_master(pb, tag_target);
1639  }
1640  }
1641 
1642  for (i = 0; i < s->nb_chapters; i++) {
1643  AVChapter *ch = s->chapters[i];
1644 
1646  continue;
1647 
1649  if (ret < 0) return ret;
1650  }
1651 
1652  if (mkv->have_attachments) {
1653  for (i = 0; i < mkv->attachments->num_entries; i++) {
1654  mkv_attachment *attachment = &mkv->attachments->entries[i];
1655  AVStream *st = s->streams[attachment->stream_idx];
1656 
1658  continue;
1659 
1660  ret = mkv_write_tag(s, st->metadata, MATROSKA_ID_TAGTARGETS_ATTACHUID, attachment->fileuid, &mkv->tags);
1661  if (ret < 0)
1662  return ret;
1663  }
1664  }
1665 
1666  if (mkv->tags.pos) {
1667  if ((s->pb->seekable & AVIO_SEEKABLE_NORMAL) && !mkv->is_live)
1668  end_ebml_master_crc32_preliminary(s->pb, &mkv->tags_bc, mkv, mkv->tags);
1669  else
1670  end_ebml_master_crc32(s->pb, &mkv->tags_bc, mkv, mkv->tags);
1671  }
1672  return 0;
1673 }
1674 
1676 {
1677  MatroskaMuxContext *mkv = s->priv_data;
1678  AVIOContext *dyn_cp, *pb = s->pb;
1679  ebml_master attachments;
1680  AVLFG c;
1681  int i, ret;
1682 
1683  if (!mkv->have_attachments)
1684  return 0;
1685 
1686  mkv->attachments = av_mallocz(sizeof(*mkv->attachments));
1687  if (!mkv->attachments)
1688  return AVERROR(ENOMEM);
1689 
1691 
1693  if (ret < 0) return ret;
1694 
1695  ret = start_ebml_master_crc32(pb, &dyn_cp, mkv, &attachments, MATROSKA_ID_ATTACHMENTS, 0);
1696  if (ret < 0) return ret;
1697 
1698  for (i = 0; i < s->nb_streams; i++) {
1699  AVStream *st = s->streams[i];
1700  ebml_master attached_file;
1701  mkv_attachment *attachment = mkv->attachments->entries;
1702  AVDictionaryEntry *t;
1703  const char *mimetype = NULL;
1704  uint32_t fileuid;
1705 
1707  continue;
1708 
1709  attachment = av_realloc_array(attachment, mkv->attachments->num_entries + 1, sizeof(mkv_attachment));
1710  if (!attachment)
1711  return AVERROR(ENOMEM);
1712  mkv->attachments->entries = attachment;
1713 
1714  attached_file = start_ebml_master(dyn_cp, MATROSKA_ID_ATTACHEDFILE, 0);
1715 
1716  if (t = av_dict_get(st->metadata, "title", NULL, 0))
1718  if (!(t = av_dict_get(st->metadata, "filename", NULL, 0))) {
1719  av_log(s, AV_LOG_ERROR, "Attachment stream %d has no filename tag.\n", i);
1720  return AVERROR(EINVAL);
1721  }
1723  if (t = av_dict_get(st->metadata, "mimetype", NULL, 0))
1724  mimetype = t->value;
1725  else if (st->codecpar->codec_id != AV_CODEC_ID_NONE ) {
1726  int i;
1727  for (i = 0; ff_mkv_mime_tags[i].id != AV_CODEC_ID_NONE; i++)
1728  if (ff_mkv_mime_tags[i].id == st->codecpar->codec_id) {
1729  mimetype = ff_mkv_mime_tags[i].str;
1730  break;
1731  }
1732  for (i = 0; ff_mkv_image_mime_tags[i].id != AV_CODEC_ID_NONE; i++)
1733  if (ff_mkv_image_mime_tags[i].id == st->codecpar->codec_id) {
1734  mimetype = ff_mkv_image_mime_tags[i].str;
1735  break;
1736  }
1737  }
1738  if (!mimetype) {
1739  av_log(s, AV_LOG_ERROR, "Attachment stream %d has no mimetype tag and "
1740  "it cannot be deduced from the codec id.\n", i);
1741  return AVERROR(EINVAL);
1742  }
1743 
1744  if (s->flags & AVFMT_FLAG_BITEXACT) {
1745  struct AVSHA *sha = av_sha_alloc();
1746  uint8_t digest[20];
1747  if (!sha)
1748  return AVERROR(ENOMEM);
1749  av_sha_init(sha, 160);
1751  av_sha_final(sha, digest);
1752  av_free(sha);
1753  fileuid = AV_RL32(digest);
1754  } else {
1755  fileuid = av_lfg_get(&c);
1756  }
1757  av_log(s, AV_LOG_VERBOSE, "Using %.8"PRIx32" for attachment %d\n",
1758  fileuid, mkv->attachments->num_entries);
1759 
1760  put_ebml_string(dyn_cp, MATROSKA_ID_FILEMIMETYPE, mimetype);
1762  put_ebml_uint(dyn_cp, MATROSKA_ID_FILEUID, fileuid);
1763  end_ebml_master(dyn_cp, attached_file);
1764 
1766  mkv->attachments->entries[mkv->attachments->num_entries++].fileuid = fileuid;
1767  }
1768  end_ebml_master_crc32(pb, &dyn_cp, mkv, attachments);
1769 
1770  return 0;
1771 }
1772 
1774 {
1775  int i = 0;
1776  int64_t max = 0;
1777  int64_t us;
1778 
1779  AVDictionaryEntry *explicitDuration = av_dict_get(s->metadata, "DURATION", NULL, 0);
1780  if (explicitDuration && (av_parse_time(&us, explicitDuration->value, 1) == 0) && us > 0) {
1781  av_log(s, AV_LOG_DEBUG, "get_metadata_duration found duration in context metadata: %" PRId64 "\n", us);
1782  return us;
1783  }
1784 
1785  for (i = 0; i < s->nb_streams; i++) {
1786  int64_t us;
1787  AVDictionaryEntry *duration = av_dict_get(s->streams[i]->metadata, "DURATION", NULL, 0);
1788 
1789  if (duration && (av_parse_time(&us, duration->value, 1) == 0))
1790  max = FFMAX(max, us);
1791  }
1792 
1793  av_log(s, AV_LOG_DEBUG, "get_metadata_duration returned: %" PRId64 "\n", max);
1794  return max;
1795 }
1796 
1798 {
1799  MatroskaMuxContext *mkv = s->priv_data;
1800  AVIOContext *pb = s->pb;
1803  int ret, i, version = 2;
1804  int64_t creation_time;
1805 
1806  if (!strcmp(s->oformat->name, "webm"))
1807  mkv->mode = MODE_WEBM;
1808  else
1809  mkv->mode = MODE_MATROSKAv2;
1810 
1811  if (mkv->mode != MODE_WEBM ||
1812  av_dict_get(s->metadata, "stereo_mode", NULL, 0) ||
1813  av_dict_get(s->metadata, "alpha_mode", NULL, 0))
1814  version = 4;
1815 
1816  for (i = 0; i < s->nb_streams; i++) {
1817  if (s->streams[i]->codecpar->codec_id == AV_CODEC_ID_ATRAC3 ||
1823  av_log(s, AV_LOG_ERROR,
1824  "The Matroska muxer does not yet support muxing %s\n",
1826  return AVERROR_PATCHWELCOME;
1827  }
1828  if (s->streams[i]->codecpar->codec_id == AV_CODEC_ID_OPUS ||
1829  av_dict_get(s->streams[i]->metadata, "stereo_mode", NULL, 0) ||
1830  av_dict_get(s->streams[i]->metadata, "alpha_mode", NULL, 0))
1831  version = 4;
1832  }
1833 
1834  mkv->tracks = av_mallocz_array(s->nb_streams, sizeof(*mkv->tracks));
1835  if (!mkv->tracks) {
1836  ret = AVERROR(ENOMEM);
1837  goto fail;
1838  }
1839  ebml_header = start_ebml_master(pb, EBML_ID_HEADER, 0);
1845  put_ebml_uint (pb, EBML_ID_DOCTYPEVERSION , version);
1847  end_ebml_master(pb, ebml_header);
1848 
1850  mkv->segment_offset = avio_tell(pb);
1851 
1852  // we write 2 seek heads - one at the end of the file to point to each
1853  // cluster, and one at the beginning to point to all other level one
1854  // elements (including the seek head at the end of the file), which
1855  // isn't more than 10 elements if we only write one of each other
1856  // currently defined level 1 element
1857  mkv->main_seekhead = mkv_start_seekhead(pb, mkv->segment_offset, 10);
1858  if (!mkv->main_seekhead) {
1859  ret = AVERROR(ENOMEM);
1860  goto fail;
1861  }
1862 
1864  if (ret < 0) goto fail;
1865 
1866  ret = start_ebml_master_crc32(pb, &mkv->info_bc, mkv, &mkv->info, MATROSKA_ID_INFO, 0);
1867  if (ret < 0)
1868  return ret;
1869  pb = mkv->info_bc;
1870 
1872  if ((tag = av_dict_get(s->metadata, "title", NULL, 0)))
1874  if (!(s->flags & AVFMT_FLAG_BITEXACT)) {
1876  if ((tag = av_dict_get(s->metadata, "encoding_tool", NULL, 0)))
1878  else
1880 
1881  if (mkv->mode != MODE_WEBM) {
1882  uint32_t segment_uid[4];
1883  AVLFG lfg;
1884 
1886 
1887  for (i = 0; i < 4; i++)
1888  segment_uid[i] = av_lfg_get(&lfg);
1889 
1890  put_ebml_binary(pb, MATROSKA_ID_SEGMENTUID, segment_uid, 16);
1891  }
1892  } else {
1893  const char *ident = "Lavf";
1896  }
1897 
1898  if (ff_parse_creation_time_metadata(s, &creation_time, 0) > 0) {
1899  // Adjust time so it's relative to 2001-01-01 and convert to nanoseconds.
1900  int64_t date_utc = (creation_time - 978307200000000LL) * 1000;
1901  uint8_t date_utc_buf[8];
1902  AV_WB64(date_utc_buf, date_utc);
1903  put_ebml_binary(pb, MATROSKA_ID_DATEUTC, date_utc_buf, 8);
1904  }
1905 
1906  // reserve space for the duration
1907  mkv->duration = 0;
1908  mkv->duration_offset = avio_tell(pb);
1909  if (!mkv->is_live) {
1910  int64_t metadata_duration = get_metadata_duration(s);
1911 
1912  if (s->duration > 0) {
1913  int64_t scaledDuration = av_rescale(s->duration, 1000, AV_TIME_BASE);
1914  put_ebml_float(pb, MATROSKA_ID_DURATION, scaledDuration);
1915  av_log(s, AV_LOG_DEBUG, "Write early duration from recording time = %" PRIu64 "\n", scaledDuration);
1916  } else if (metadata_duration > 0) {
1917  int64_t scaledDuration = av_rescale(metadata_duration, 1000, AV_TIME_BASE);
1918  put_ebml_float(pb, MATROSKA_ID_DURATION, scaledDuration);
1919  av_log(s, AV_LOG_DEBUG, "Write early duration from metadata = %" PRIu64 "\n", scaledDuration);
1920  } else {
1921  put_ebml_void(pb, 11); // assumes double-precision float to be written
1922  }
1923  }
1924  if ((s->pb->seekable & AVIO_SEEKABLE_NORMAL) && !mkv->is_live)
1925  end_ebml_master_crc32_preliminary(s->pb, &mkv->info_bc, mkv, mkv->info);
1926  else
1927  end_ebml_master_crc32(s->pb, &mkv->info_bc, mkv, mkv->info);
1928  pb = s->pb;
1929 
1930  // initialize stream_duration fields
1931  mkv->stream_durations = av_mallocz(s->nb_streams * sizeof(int64_t));
1932  mkv->stream_duration_offsets = av_mallocz(s->nb_streams * sizeof(int64_t));
1933 
1934  ret = mkv_write_tracks(s);
1935  if (ret < 0)
1936  goto fail;
1937 
1938  for (i = 0; i < s->nb_chapters; i++)
1939  mkv->chapter_id_offset = FFMAX(mkv->chapter_id_offset, 1LL - s->chapters[i]->id);
1940 
1941  if (mkv->mode != MODE_WEBM) {
1942  ret = mkv_write_chapters(s);
1943  if (ret < 0)
1944  goto fail;
1945 
1946  ret = mkv_write_attachments(s);
1947  if (ret < 0)
1948  goto fail;
1949 
1950  ret = mkv_write_tags(s);
1951  if (ret < 0)
1952  goto fail;
1953  }
1954 
1955  if (!(s->pb->seekable & AVIO_SEEKABLE_NORMAL) && !mkv->is_live)
1956  mkv_write_seekhead(pb, mkv);
1957 
1958  mkv->cues = mkv_start_cues(mkv->segment_offset);
1959  if (!mkv->cues) {
1960  ret = AVERROR(ENOMEM);
1961  goto fail;
1962  }
1963  if ((pb->seekable & AVIO_SEEKABLE_NORMAL) && mkv->reserve_cues_space) {
1964  mkv->cues_pos = avio_tell(pb);
1966  }
1967 
1969  mkv->cur_audio_pkt.size = 0;
1970  mkv->cluster_pos = -1;
1971 
1972  avio_flush(pb);
1973 
1974  // start a new cluster every 5 MB or 5 sec, or 32k / 1 sec for streaming or
1975  // after 4k and on a keyframe
1976  if (pb->seekable & AVIO_SEEKABLE_NORMAL) {
1977  if (mkv->cluster_time_limit < 0)
1978  mkv->cluster_time_limit = 5000;
1979  if (mkv->cluster_size_limit < 0)
1980  mkv->cluster_size_limit = 5 * 1024 * 1024;
1981  } else {
1982  if (mkv->cluster_time_limit < 0)
1983  mkv->cluster_time_limit = 1000;
1984  if (mkv->cluster_size_limit < 0)
1985  mkv->cluster_size_limit = 32 * 1024;
1986  }
1987 
1988  return 0;
1989 fail:
1990  mkv_free(mkv);
1991  return ret;
1992 }
1993 
1994 static int mkv_blockgroup_size(int pkt_size)
1995 {
1996  int size = pkt_size + 4;
1997  size += ebml_num_size(size);
1998  size += 2; // EBML ID for block and block duration
1999  size += 8; // max size of block duration
2000  size += ebml_num_size(size);
2001  size += 1; // blockgroup EBML ID
2002  return size;
2003 }
2004 
2005 static int mkv_strip_wavpack(const uint8_t *src, uint8_t **pdst, int *size)
2006 {
2007  uint8_t *dst;
2008  int srclen = *size;
2009  int offset = 0;
2010  int ret;
2011 
2012  dst = av_malloc(srclen);
2013  if (!dst)
2014  return AVERROR(ENOMEM);
2015 
2016  while (srclen >= WV_HEADER_SIZE) {
2017  WvHeader header;
2018 
2019  ret = ff_wv_parse_header(&header, src);
2020  if (ret < 0)
2021  goto fail;
2022  src += WV_HEADER_SIZE;
2023  srclen -= WV_HEADER_SIZE;
2024 
2025  if (srclen < header.blocksize) {
2026  ret = AVERROR_INVALIDDATA;
2027  goto fail;
2028  }
2029 
2030  if (header.initial) {
2031  AV_WL32(dst + offset, header.samples);
2032  offset += 4;
2033  }
2034  AV_WL32(dst + offset, header.flags);
2035  AV_WL32(dst + offset + 4, header.crc);
2036  offset += 8;
2037 
2038  if (!(header.initial && header.final)) {
2039  AV_WL32(dst + offset, header.blocksize);
2040  offset += 4;
2041  }
2042 
2043  memcpy(dst + offset, src, header.blocksize);
2044  src += header.blocksize;
2045  srclen -= header.blocksize;
2046  offset += header.blocksize;
2047  }
2048 
2049  *pdst = dst;
2050  *size = offset;
2051 
2052  return 0;
2053 fail:
2054  av_freep(&dst);
2055  return ret;
2056 }
2057 
2059  unsigned int blockid, AVPacket *pkt, int keyframe)
2060 {
2061  MatroskaMuxContext *mkv = s->priv_data;
2063  uint8_t *data = NULL, *side_data = NULL;
2064  int offset = 0, size = pkt->size, side_data_size = 0;
2065  int64_t ts = mkv->tracks[pkt->stream_index].write_dts ? pkt->dts : pkt->pts;
2066  uint64_t additional_id = 0;
2067  int64_t discard_padding = 0;
2068  uint8_t track_number = (mkv->is_dash ? mkv->dash_track_number : (pkt->stream_index + 1));
2069  ebml_master block_group, block_additions, block_more;
2070 
2071  av_log(s, AV_LOG_DEBUG, "Writing block at offset %" PRIu64 ", size %d, "
2072  "pts %" PRId64 ", dts %" PRId64 ", duration %" PRId64 ", keyframe %d\n",
2073  avio_tell(pb), pkt->size, pkt->pts, pkt->dts, pkt->duration,
2074  keyframe != 0);
2075  if (par->codec_id == AV_CODEC_ID_H264 && par->extradata_size > 0 &&
2076  (AV_RB24(par->extradata) == 1 || AV_RB32(par->extradata) == 1))
2077  ff_avc_parse_nal_units_buf(pkt->data, &data, &size);
2078  else if (par->codec_id == AV_CODEC_ID_HEVC && par->extradata_size > 6 &&
2079  (AV_RB24(par->extradata) == 1 || AV_RB32(par->extradata) == 1))
2080  /* extradata is Annex B, assume the bitstream is too and convert it */
2081  ff_hevc_annexb2mp4_buf(pkt->data, &data, &size, 0, NULL);
2082  else if (par->codec_id == AV_CODEC_ID_WAVPACK) {
2083  int ret = mkv_strip_wavpack(pkt->data, &data, &size);
2084  if (ret < 0) {
2085  av_log(s, AV_LOG_ERROR, "Error stripping a WavPack packet.\n");
2086  return;
2087  }
2088  } else
2089  data = pkt->data;
2090 
2091  if (par->codec_id == AV_CODEC_ID_PRORES && size >= 8) {
2092  /* Matroska specification requires to remove the first QuickTime atom
2093  */
2094  size -= 8;
2095  offset = 8;
2096  }
2097 
2098  side_data = av_packet_get_side_data(pkt,
2100  &side_data_size);
2101 
2102  if (side_data && side_data_size >= 10) {
2103  discard_padding = av_rescale_q(AV_RL32(side_data + 4),
2104  (AVRational){1, par->sample_rate},
2105  (AVRational){1, 1000000000});
2106  }
2107 
2108  side_data = av_packet_get_side_data(pkt,
2110  &side_data_size);
2111  if (side_data) {
2112  additional_id = AV_RB64(side_data);
2113  side_data += 8;
2114  side_data_size -= 8;
2115  }
2116 
2117  if ((side_data_size && additional_id == 1) || discard_padding) {
2118  block_group = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP, 0);
2119  blockid = MATROSKA_ID_BLOCK;
2120  }
2121 
2122  put_ebml_id(pb, blockid);
2123  put_ebml_num(pb, size + 4, 0);
2124  // this assumes stream_index is less than 126
2125  avio_w8(pb, 0x80 | track_number);
2126  avio_wb16(pb, ts - mkv->cluster_pts);
2127  avio_w8(pb, (blockid == MATROSKA_ID_SIMPLEBLOCK && keyframe) ? (1 << 7) : 0);
2128  avio_write(pb, data + offset, size);
2129  if (data != pkt->data)
2130  av_free(data);
2131 
2132  if (blockid == MATROSKA_ID_BLOCK && !keyframe) {
2134  mkv->last_track_timestamp[track_number - 1]);
2135  }
2136  mkv->last_track_timestamp[track_number - 1] = ts - mkv->cluster_pts;
2137 
2138  if (discard_padding) {
2139  put_ebml_sint(pb, MATROSKA_ID_DISCARDPADDING, discard_padding);
2140  }
2141 
2142  if (side_data_size && additional_id == 1) {
2143  block_additions = start_ebml_master(pb, MATROSKA_ID_BLOCKADDITIONS, 0);
2144  block_more = start_ebml_master(pb, MATROSKA_ID_BLOCKMORE, 0);
2147  put_ebml_num(pb, side_data_size, 0);
2148  avio_write(pb, side_data, side_data_size);
2149  end_ebml_master(pb, block_more);
2150  end_ebml_master(pb, block_additions);
2151  }
2152  if ((side_data_size && additional_id == 1) || discard_padding) {
2153  end_ebml_master(pb, block_group);
2154  }
2155 }
2156 
2158 {
2159  MatroskaMuxContext *mkv = s->priv_data;
2160  ebml_master blockgroup;
2161  int id_size, settings_size, size;
2162  uint8_t *id, *settings;
2163  int64_t ts = mkv->tracks[pkt->stream_index].write_dts ? pkt->dts : pkt->pts;
2164  const int flags = 0;
2165 
2166  id_size = 0;
2168  &id_size);
2169 
2170  settings_size = 0;
2172  &settings_size);
2173 
2174  size = id_size + 1 + settings_size + 1 + pkt->size;
2175 
2176  av_log(s, AV_LOG_DEBUG, "Writing block at offset %" PRIu64 ", size %d, "
2177  "pts %" PRId64 ", dts %" PRId64 ", duration %" PRId64 ", flags %d\n",
2178  avio_tell(pb), size, pkt->pts, pkt->dts, pkt->duration, flags);
2179 
2181 
2183  put_ebml_num(pb, size + 4, 0);
2184  avio_w8(pb, 0x80 | (pkt->stream_index + 1)); // this assumes stream_index is less than 126
2185  avio_wb16(pb, ts - mkv->cluster_pts);
2186  avio_w8(pb, flags);
2187  avio_printf(pb, "%.*s\n%.*s\n%.*s", id_size, id, settings_size, settings, pkt->size, pkt->data);
2188 
2190  end_ebml_master(pb, blockgroup);
2191 
2192  return pkt->duration;
2193 }
2194 
2196 {
2197  MatroskaMuxContext *mkv = s->priv_data;
2198 
2199  end_ebml_master_crc32(s->pb, &mkv->dyn_bc, mkv, mkv->cluster);
2200  mkv->cluster_pos = -1;
2201  if (s->pb->seekable & AVIO_SEEKABLE_NORMAL)
2202  av_log(s, AV_LOG_DEBUG,
2203  "Starting new cluster at offset %" PRIu64 " bytes, "
2204  "pts %" PRIu64 "dts %" PRIu64 "\n",
2205  avio_tell(s->pb), pkt->pts, pkt->dts);
2206  else
2207  av_log(s, AV_LOG_DEBUG, "Starting new cluster, "
2208  "pts %" PRIu64 "dts %" PRIu64 "\n",
2209  pkt->pts, pkt->dts);
2210  avio_flush(s->pb);
2211 }
2212 
2214 {
2215  MatroskaMuxContext *mkv = s->priv_data;
2216  mkv_track *track = &mkv->tracks[pkt->stream_index];
2218  uint8_t *side_data;
2219  int side_data_size = 0, ret;
2220 
2222  &side_data_size);
2223 
2224  switch (par->codec_id) {
2225  case AV_CODEC_ID_FLAC:
2226  if (side_data_size && (s->pb->seekable & AVIO_SEEKABLE_NORMAL) && !mkv->is_live) {
2227  AVCodecParameters *codecpriv_par;
2228  int64_t curpos;
2229  if (side_data_size != par->extradata_size) {
2230  av_log(s, AV_LOG_ERROR, "Invalid FLAC STREAMINFO metadata for output stream %d\n",
2231  pkt->stream_index);
2232  return AVERROR(EINVAL);
2233  }
2234  codecpriv_par = avcodec_parameters_alloc();
2235  if (!codecpriv_par)
2236  return AVERROR(ENOMEM);
2237  ret = avcodec_parameters_copy(codecpriv_par, par);
2238  if (ret < 0) {
2239  avcodec_parameters_free(&codecpriv_par);
2240  return ret;
2241  }
2242  memcpy(codecpriv_par->extradata, side_data, side_data_size);
2243  curpos = avio_tell(mkv->tracks_bc);
2244  avio_seek(mkv->tracks_bc, track->codecpriv_offset, SEEK_SET);
2245  mkv_write_codecprivate(s, mkv->tracks_bc, codecpriv_par, 1, 0);
2246  avio_seek(mkv->tracks_bc, curpos, SEEK_SET);
2247  avcodec_parameters_free(&codecpriv_par);
2248  }
2249  break;
2250  default:
2251  if (side_data_size)
2252  av_log(s, AV_LOG_DEBUG, "Ignoring new extradata in a packet for stream %d.\n", pkt->stream_index);
2253  break;
2254  }
2255 
2256  return 0;
2257 }
2258 
2260 {
2261  MatroskaMuxContext *mkv = s->priv_data;
2262  AVIOContext *pb = s->pb;
2264  int keyframe = !!(pkt->flags & AV_PKT_FLAG_KEY);
2265  int duration = pkt->duration;
2266  int ret;
2267  int64_t ts = mkv->tracks[pkt->stream_index].write_dts ? pkt->dts : pkt->pts;
2268  int64_t relative_packet_pos;
2269  int dash_tracknum = mkv->is_dash ? mkv->dash_track_number : pkt->stream_index + 1;
2270 
2271  if (ts == AV_NOPTS_VALUE) {
2272  av_log(s, AV_LOG_ERROR, "Can't write packet with unknown timestamp\n");
2273  return AVERROR(EINVAL);
2274  }
2275  ts += mkv->tracks[pkt->stream_index].ts_offset;
2276 
2277  if (mkv->cluster_pos != -1) {
2278  int64_t cluster_time = ts - mkv->cluster_pts + mkv->tracks[pkt->stream_index].ts_offset;
2279  if ((int16_t)cluster_time != cluster_time) {
2280  av_log(s, AV_LOG_WARNING, "Starting new cluster due to timestamp\n");
2281  mkv_start_new_cluster(s, pkt);
2282  }
2283  }
2284 
2285  if (mkv->cluster_pos == -1) {
2286  mkv->cluster_pos = avio_tell(s->pb);
2287  ret = start_ebml_master_crc32(s->pb, &mkv->dyn_bc, mkv, &mkv->cluster, MATROSKA_ID_CLUSTER, 0);
2288  if (ret < 0)
2289  return ret;
2291  mkv->cluster_pts = FFMAX(0, ts);
2292  }
2293  pb = mkv->dyn_bc;
2294 
2295  relative_packet_pos = avio_tell(pb);
2296 
2297  if (par->codec_type != AVMEDIA_TYPE_SUBTITLE) {
2298  mkv_write_block(s, pb, MATROSKA_ID_SIMPLEBLOCK, pkt, keyframe);
2299  if ((s->pb->seekable & AVIO_SEEKABLE_NORMAL) && (par->codec_type == AVMEDIA_TYPE_VIDEO && keyframe || add_cue)) {
2300  ret = mkv_add_cuepoint(mkv->cues, pkt->stream_index, dash_tracknum, ts, mkv->cluster_pos, relative_packet_pos, -1);
2301  if (ret < 0) return ret;
2302  }
2303  } else {
2304  if (par->codec_id == AV_CODEC_ID_WEBVTT) {
2305  duration = mkv_write_vtt_blocks(s, pb, pkt);
2306  } else {
2308  mkv_blockgroup_size(pkt->size));
2309 
2310 #if FF_API_CONVERGENCE_DURATION
2312  /* For backward compatibility, prefer convergence_duration. */
2313  if (pkt->convergence_duration > 0) {
2314  duration = pkt->convergence_duration;
2315  }
2317 #endif
2318  /* All subtitle blocks are considered to be keyframes. */
2319  mkv_write_block(s, pb, MATROSKA_ID_BLOCK, pkt, 1);
2321  end_ebml_master(pb, blockgroup);
2322  }
2323 
2324  if (s->pb->seekable & AVIO_SEEKABLE_NORMAL) {
2325  ret = mkv_add_cuepoint(mkv->cues, pkt->stream_index, dash_tracknum, ts,
2326  mkv->cluster_pos, relative_packet_pos, duration);
2327  if (ret < 0)
2328  return ret;
2329  }
2330  }
2331 
2332  mkv->duration = FFMAX(mkv->duration, ts + duration);
2333 
2334  if (mkv->stream_durations)
2335  mkv->stream_durations[pkt->stream_index] =
2336  FFMAX(mkv->stream_durations[pkt->stream_index], ts + duration);
2337 
2338  return 0;
2339 }
2340 
2342 {
2343  MatroskaMuxContext *mkv = s->priv_data;
2345  int keyframe = !!(pkt->flags & AV_PKT_FLAG_KEY);
2346  int cluster_size;
2347  int64_t cluster_time;
2348  int ret;
2349  int start_new_cluster;
2350 
2351  ret = mkv_check_new_extra_data(s, pkt);
2352  if (ret < 0)
2353  return ret;
2354 
2355  if (mkv->tracks[pkt->stream_index].write_dts)
2356  cluster_time = pkt->dts - mkv->cluster_pts;
2357  else
2358  cluster_time = pkt->pts - mkv->cluster_pts;
2359  cluster_time += mkv->tracks[pkt->stream_index].ts_offset;
2360 
2361  // start a new cluster every 5 MB or 5 sec, or 32k / 1 sec for streaming or
2362  // after 4k and on a keyframe
2363  cluster_size = avio_tell(mkv->dyn_bc);
2364 
2365  if (mkv->is_dash && codec_type == AVMEDIA_TYPE_VIDEO) {
2366  // WebM DASH specification states that the first block of every cluster
2367  // has to be a key frame. So for DASH video, we only create a cluster
2368  // on seeing key frames.
2369  start_new_cluster = keyframe;
2370  } else if (mkv->is_dash && codec_type == AVMEDIA_TYPE_AUDIO &&
2371  (mkv->cluster_pos == -1 ||
2372  cluster_time > mkv->cluster_time_limit)) {
2373  // For DASH audio, we create a Cluster based on cluster_time_limit
2374  start_new_cluster = 1;
2375  } else if (!mkv->is_dash &&
2376  (cluster_size > mkv->cluster_size_limit ||
2377  cluster_time > mkv->cluster_time_limit ||
2378  (codec_type == AVMEDIA_TYPE_VIDEO && keyframe &&
2379  cluster_size > 4 * 1024))) {
2380  start_new_cluster = 1;
2381  } else {
2382  start_new_cluster = 0;
2383  }
2384 
2385  if (mkv->cluster_pos != -1 && start_new_cluster) {
2386  mkv_start_new_cluster(s, pkt);
2387  }
2388 
2389  if (!mkv->cluster_pos)
2390  avio_write_marker(s->pb,
2393 
2394  // check if we have an audio packet cached
2395  if (mkv->cur_audio_pkt.size > 0) {
2396  // for DASH audio, a CuePoint has to be added when there is a new cluster.
2398  mkv->is_dash ? start_new_cluster : 0);
2400  if (ret < 0) {
2401  av_log(s, AV_LOG_ERROR,
2402  "Could not write cached audio packet ret:%d\n", ret);
2403  return ret;
2404  }
2405  }
2406 
2407  // buffer an audio packet to ensure the packet containing the video
2408  // keyframe's timecode is contained in the same cluster for WebM
2409  if (codec_type == AVMEDIA_TYPE_AUDIO) {
2410  ret = av_packet_ref(&mkv->cur_audio_pkt, pkt);
2411  } else
2412  ret = mkv_write_packet_internal(s, pkt, 0);
2413  return ret;
2414 }
2415 
2417 {
2418  MatroskaMuxContext *mkv = s->priv_data;
2419 
2420  if (!pkt) {
2421  if (mkv->cluster_pos != -1) {
2422  end_ebml_master_crc32(s->pb, &mkv->dyn_bc, mkv, mkv->cluster);
2423  mkv->cluster_pos = -1;
2424  if (s->pb->seekable & AVIO_SEEKABLE_NORMAL)
2425  av_log(s, AV_LOG_DEBUG,
2426  "Flushing cluster at offset %" PRIu64 " bytes\n",
2427  avio_tell(s->pb));
2428  else
2429  av_log(s, AV_LOG_DEBUG, "Flushing cluster\n");
2430  avio_flush(s->pb);
2431  }
2432  return 1;
2433  }
2434  return mkv_write_packet(s, pkt);
2435 }
2436 
2438 {
2439  MatroskaMuxContext *mkv = s->priv_data;
2440  AVIOContext *pb = s->pb;
2441  int64_t currentpos, cuespos;
2442  int ret;
2443 
2444  // check if we have an audio packet cached
2445  if (mkv->cur_audio_pkt.size > 0) {
2446  ret = mkv_write_packet_internal(s, &mkv->cur_audio_pkt, 0);
2448  if (ret < 0) {
2449  av_log(s, AV_LOG_ERROR,
2450  "Could not write cached audio packet ret:%d\n", ret);
2451  return ret;
2452  }
2453  }
2454 
2455  if (mkv->dyn_bc) {
2456  end_ebml_master_crc32(pb, &mkv->dyn_bc, mkv, mkv->cluster);
2457  }
2458 
2459  if (mkv->mode != MODE_WEBM) {
2460  ret = mkv_write_chapters(s);
2461  if (ret < 0)
2462  return ret;
2463  }
2464 
2465  if ((pb->seekable & AVIO_SEEKABLE_NORMAL) && !mkv->is_live) {
2466  if (mkv->cues->num_entries) {
2467  if (mkv->reserve_cues_space) {
2468  int64_t cues_end;
2469 
2470  currentpos = avio_tell(pb);
2471  avio_seek(pb, mkv->cues_pos, SEEK_SET);
2472 
2473  cuespos = mkv_write_cues(s, mkv->cues, mkv->tracks, s->nb_streams);
2474  cues_end = avio_tell(pb);
2475  if (cues_end > cuespos + mkv->reserve_cues_space) {
2476  av_log(s, AV_LOG_ERROR,
2477  "Insufficient space reserved for cues: %d "
2478  "(needed: %" PRId64 ").\n",
2479  mkv->reserve_cues_space, cues_end - cuespos);
2480  return AVERROR(EINVAL);
2481  }
2482 
2483  if (cues_end < cuespos + mkv->reserve_cues_space)
2485  (cues_end - cuespos));
2486 
2487  avio_seek(pb, currentpos, SEEK_SET);
2488  } else {
2489  cuespos = mkv_write_cues(s, mkv->cues, mkv->tracks, s->nb_streams);
2490  }
2491 
2493  cuespos);
2494  if (ret < 0)
2495  return ret;
2496  }
2497 
2498  mkv_write_seekhead(pb, mkv);
2499 
2500  // update the duration
2501  av_log(s, AV_LOG_DEBUG, "end duration = %" PRIu64 "\n", mkv->duration);
2502  currentpos = avio_tell(pb);
2503  avio_seek(mkv->info_bc, mkv->duration_offset, SEEK_SET);
2505  avio_seek(pb, mkv->info.pos, SEEK_SET);
2506  end_ebml_master_crc32(pb, &mkv->info_bc, mkv, mkv->info);
2507 
2508  // write tracks master
2509  avio_seek(pb, mkv->tracks_master.pos, SEEK_SET);
2510  end_ebml_master_crc32(pb, &mkv->tracks_bc, mkv, mkv->tracks_master);
2511 
2512  // update stream durations
2513  if (!mkv->is_live && mkv->stream_durations) {
2514  int i;
2515  int64_t curr = avio_tell(mkv->tags_bc);
2516  for (i = 0; i < s->nb_streams; ++i) {
2517  AVStream *st = s->streams[i];
2518 
2519  if (mkv->stream_duration_offsets[i] > 0) {
2520  double duration_sec = mkv->stream_durations[i] * av_q2d(st->time_base);
2521  char duration_string[20] = "";
2522 
2523  av_log(s, AV_LOG_DEBUG, "stream %d end duration = %" PRIu64 "\n", i,
2524  mkv->stream_durations[i]);
2525 
2526  avio_seek(mkv->tags_bc, mkv->stream_duration_offsets[i], SEEK_SET);
2527 
2528  snprintf(duration_string, 20, "%02d:%02d:%012.9f",
2529  (int) duration_sec / 3600, ((int) duration_sec / 60) % 60,
2530  fmod(duration_sec, 60));
2531 
2532  put_ebml_binary(mkv->tags_bc, MATROSKA_ID_TAGSTRING, duration_string, 20);
2533  }
2534  }
2535  avio_seek(mkv->tags_bc, curr, SEEK_SET);
2536  }
2537  if (mkv->tags.pos && !mkv->is_live) {
2538  avio_seek(pb, mkv->tags.pos, SEEK_SET);
2539  end_ebml_master_crc32(pb, &mkv->tags_bc, mkv, mkv->tags);
2540  }
2541 
2542  avio_seek(pb, currentpos, SEEK_SET);
2543  }
2544 
2545  if (!mkv->is_live) {
2546  end_ebml_master(pb, mkv->segment);
2547  }
2548 
2549  mkv_free(mkv);
2550  return 0;
2551 }
2552 
2553 static int mkv_query_codec(enum AVCodecID codec_id, int std_compliance)
2554 {
2555  int i;
2556  for (i = 0; ff_mkv_codec_tags[i].id != AV_CODEC_ID_NONE; i++)
2557  if (ff_mkv_codec_tags[i].id == codec_id)
2558  return 1;
2559 
2560  if (std_compliance < FF_COMPLIANCE_NORMAL) {
2561  enum AVMediaType type = avcodec_get_type(codec_id);
2562  // mkv theoretically supports any video/audio through VFW/ACM
2563  if (type == AVMEDIA_TYPE_VIDEO || type == AVMEDIA_TYPE_AUDIO)
2564  return 1;
2565  }
2566 
2567  return 0;
2568 }
2569 
2570 static int mkv_init(struct AVFormatContext *s)
2571 {
2572  int i;
2573 
2574  if (s->avoid_negative_ts < 0) {
2575  s->avoid_negative_ts = 1;
2577  }
2578 
2579  for (i = 0; i < s->nb_streams; i++) {
2580  // ms precision is the de-facto standard timescale for mkv files
2581  avpriv_set_pts_info(s->streams[i], 64, 1, 1000);
2582  }
2583 
2584  return 0;
2585 }
2586 
2587 static int mkv_check_bitstream(struct AVFormatContext *s, const AVPacket *pkt)
2588 {
2589  int ret = 1;
2590  AVStream *st = s->streams[pkt->stream_index];
2591 
2592  if (st->codecpar->codec_id == AV_CODEC_ID_AAC) {
2593  if (pkt->size > 2 && (AV_RB16(pkt->data) & 0xfff0) == 0xfff0)
2594  ret = ff_stream_add_bitstream_filter(st, "aac_adtstoasc", NULL);
2595  } else if (st->codecpar->codec_id == AV_CODEC_ID_VP9) {
2596  ret = ff_stream_add_bitstream_filter(st, "vp9_superframe", NULL);
2597  }
2598 
2599  return ret;
2600 }
2601 
2603  { AV_CODEC_ID_ALAC, 0XFFFFFFFF },
2604  { AV_CODEC_ID_EAC3, 0XFFFFFFFF },
2605  { AV_CODEC_ID_MLP, 0xFFFFFFFF },
2606  { AV_CODEC_ID_OPUS, 0xFFFFFFFF },
2607  { AV_CODEC_ID_PCM_S16BE, 0xFFFFFFFF },
2608  { AV_CODEC_ID_PCM_S24BE, 0xFFFFFFFF },
2609  { AV_CODEC_ID_PCM_S32BE, 0xFFFFFFFF },
2610  { AV_CODEC_ID_QDMC, 0xFFFFFFFF },
2611  { AV_CODEC_ID_QDM2, 0xFFFFFFFF },
2612  { AV_CODEC_ID_RA_144, 0xFFFFFFFF },
2613  { AV_CODEC_ID_RA_288, 0xFFFFFFFF },
2614  { AV_CODEC_ID_COOK, 0xFFFFFFFF },
2615  { AV_CODEC_ID_TRUEHD, 0xFFFFFFFF },
2616  { AV_CODEC_ID_NONE, 0xFFFFFFFF }
2617 };
2618 
2620  { AV_CODEC_ID_RV10, 0xFFFFFFFF },
2621  { AV_CODEC_ID_RV20, 0xFFFFFFFF },
2622  { AV_CODEC_ID_RV30, 0xFFFFFFFF },
2623  { AV_CODEC_ID_RV40, 0xFFFFFFFF },
2624  { AV_CODEC_ID_VP9, 0xFFFFFFFF },
2625  { AV_CODEC_ID_NONE, 0xFFFFFFFF }
2626 };
2627 
2629  { AV_CODEC_ID_DVB_SUBTITLE, 0xFFFFFFFF },
2630  { AV_CODEC_ID_HDMV_PGS_SUBTITLE, 0xFFFFFFFF },
2631  { AV_CODEC_ID_NONE, 0xFFFFFFFF }
2632 };
2633 
2634 #define OFFSET(x) offsetof(MatroskaMuxContext, x)
2635 #define FLAGS AV_OPT_FLAG_ENCODING_PARAM
2636 static const AVOption options[] = {
2637  { "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 },
2638  { "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 },
2639  { "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 },
2640  { "dash", "Create a WebM file conforming to WebM DASH specification", OFFSET(is_dash), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, FLAGS },
2641  { "dash_track_number", "Track number for the DASH stream", OFFSET(dash_track_number), AV_OPT_TYPE_INT, { .i64 = 1 }, 0, 127, FLAGS },
2642  { "live", "Write files assuming it is a live stream.", OFFSET(is_live), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, FLAGS },
2643  { "allow_raw_vfw", "allow RAW VFW mode", OFFSET(allow_raw_vfw), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, FLAGS },
2644  { "write_crc32", "write a CRC32 element inside every Level 1 element", OFFSET(write_crc), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, FLAGS },
2645  { NULL },
2646 };
2647 
2648 #if CONFIG_MATROSKA_MUXER
2649 static const AVClass matroska_class = {
2650  .class_name = "matroska muxer",
2651  .item_name = av_default_item_name,
2652  .option = options,
2653  .version = LIBAVUTIL_VERSION_INT,
2654 };
2655 
2656 AVOutputFormat ff_matroska_muxer = {
2657  .name = "matroska",
2658  .long_name = NULL_IF_CONFIG_SMALL("Matroska"),
2659  .mime_type = "video/x-matroska",
2660  .extensions = "mkv",
2661  .priv_data_size = sizeof(MatroskaMuxContext),
2662  .audio_codec = CONFIG_LIBVORBIS_ENCODER ?
2664  .video_codec = CONFIG_LIBX264_ENCODER ?
2666  .init = mkv_init,
2672  .codec_tag = (const AVCodecTag* const []){
2675  },
2676  .subtitle_codec = AV_CODEC_ID_ASS,
2677  .query_codec = mkv_query_codec,
2678  .check_bitstream = mkv_check_bitstream,
2679  .priv_class = &matroska_class,
2680 };
2681 #endif
2682 
2683 #if CONFIG_WEBM_MUXER
2684 static const AVClass webm_class = {
2685  .class_name = "webm muxer",
2686  .item_name = av_default_item_name,
2687  .option = options,
2688  .version = LIBAVUTIL_VERSION_INT,
2689 };
2690 
2691 AVOutputFormat ff_webm_muxer = {
2692  .name = "webm",
2693  .long_name = NULL_IF_CONFIG_SMALL("WebM"),
2694  .mime_type = "video/webm",
2695  .extensions = "webm",
2696  .priv_data_size = sizeof(MatroskaMuxContext),
2697  .audio_codec = CONFIG_LIBOPUS_ENCODER ? AV_CODEC_ID_OPUS : AV_CODEC_ID_VORBIS,
2698  .video_codec = CONFIG_LIBVPX_VP9_ENCODER? AV_CODEC_ID_VP9 : AV_CODEC_ID_VP8,
2699  .subtitle_codec = AV_CODEC_ID_WEBVTT,
2700  .init = mkv_init,
2704  .check_bitstream = mkv_check_bitstream,
2707  .priv_class = &webm_class,
2708 };
2709 #endif
2710 
2711 #if CONFIG_MATROSKA_AUDIO_MUXER
2712 static const AVClass mka_class = {
2713  .class_name = "matroska audio muxer",
2714  .item_name = av_default_item_name,
2715  .option = options,
2716  .version = LIBAVUTIL_VERSION_INT,
2717 };
2718 AVOutputFormat ff_matroska_audio_muxer = {
2719  .name = "matroska",
2720  .long_name = NULL_IF_CONFIG_SMALL("Matroska Audio"),
2721  .mime_type = "audio/x-matroska",
2722  .extensions = "mka",
2723  .priv_data_size = sizeof(MatroskaMuxContext),
2724  .audio_codec = CONFIG_LIBVORBIS_ENCODER ?
2725  AV_CODEC_ID_VORBIS : AV_CODEC_ID_AC3,
2726  .video_codec = AV_CODEC_ID_NONE,
2727  .init = mkv_init,
2731  .check_bitstream = mkv_check_bitstream,
2734  .codec_tag = (const AVCodecTag* const []){
2736  },
2737  .priv_class = &mka_class,
2738 };
2739 #endif
unsigned int nb_chapters
Number of chapters in AVChapter array.
Definition: avformat.h:1556
static int mkv_write_packet_internal(AVFormatContext *s, AVPacket *pkt, int add_cue)
Definition: matroskaenc.c:2259
int32_t pitch
Rotation around the right vector [-90, 90].
Definition: spherical.h:127
Definition: lfg.h:27
#define MATROSKA_ID_SEEKPREROLL
Definition: matroska.h:95
void av_sha_final(AVSHA *ctx, uint8_t *digest)
Finish hashing and output digest value.
Definition: sha.c:341
#define MATROSKA_ID_VIDEOPROJECTIONPOSEYAW
Definition: matroska.h:159
static void write_packet(OutputFile *of, AVPacket *pkt, OutputStream *ost, int unqueue)
Definition: ffmpeg.c:672
enum AVChromaLocation chroma_location
Definition: avcodec.h:4156
internal header for HEVC (de)muxer utilities
#define AV_DISPOSITION_METADATA
Definition: avformat.h:873
void avio_wb64(AVIOContext *s, uint64_t val)
Definition: aviobuf.c:452
#define NULL
Definition: coverity.c:32
static int mkv_write_vtt_blocks(AVFormatContext *s, AVIOContext *pb, AVPacket *pkt)
Definition: matroskaenc.c:2157
const char const char void * val
Definition: avisynth_c.h:771
#define MATROSKA_ID_BLOCKADDID
Definition: matroska.h:230
#define MATROSKA_ID_TRACKDEFAULTDURATION
Definition: matroska.h:104
void avio_wl16(AVIOContext *s, unsigned int val)
Definition: aviobuf.c:458
static void put_ebml_size_unknown(AVIOContext *pb, int bytes)
Write an EBML size meaning "unknown size".
Definition: matroskaenc.c:196
const char * s
Definition: avisynth_c.h:768
Bytestream IO Context.
Definition: avio.h:155
enum AVColorTransferCharacteristic color_trc
Definition: avcodec.h:4154
#define MATROSKA_ID_VIDEOFLAGINTERLACED
Definition: matroska.h:121
#define AVERROR_INVALIDDATA
Invalid data found when processing input.
Definition: error.h:59
#define MATROSKA_ID_VIDEOCOLOR_GX
Definition: matroska.h:147
void ff_metadata_conv_ctx(AVFormatContext *ctx, const AVMetadataConv *d_conv, const AVMetadataConv *s_conv)
Definition: metadata.c:59
#define MATROSKA_ID_DATEUTC
Definition: matroska.h:71
int sizebytes
how many bytes were reserved for the size
Definition: matroskaenc.c:61
#define MAX_TRACKS
Maximum number of tracks allowed in a Matroska file (with track numbers in range 1 to 126 (inclusive)...
Definition: matroskaenc.c:115
The optional first identifier line of a WebVTT cue.
Definition: avcodec.h:1553
uint32_t samples
Definition: wv.h:39
int initial
Definition: wv.h:43
void av_sha_update(AVSHA *ctx, const uint8_t *data, unsigned int len)
Update hash value.
Definition: sha.c:314
#define MATROSKA_ID_TRACKFLAGLACING
Definition: matroska.h:101
#define MATROSKA_ID_TRACKENTRY
Definition: matroska.h:75
#define MATROSKA_ID_VIDEODISPLAYHEIGHT
Definition: matroska.h:113
static void mkv_start_new_cluster(AVFormatContext *s, AVPacket *pkt)
Definition: matroskaenc.c:2195
int avio_close_dyn_buf(AVIOContext *s, uint8_t **pbuffer)
Return the written size and a pointer to the buffer.
Definition: aviobuf.c:1319
AVOption.
Definition: opt.h:246
hash context
Definition: sha.c:34
int64_t cluster_pos
file offset of the cluster containing the block
Definition: matroskaenc.c:82
ptrdiff_t const GLvoid * data
Definition: opengl_enc.c:101
int ff_put_wav_header(AVFormatContext *s, AVIOContext *pb, AVCodecParameters *par, int flags)
Write WAVEFORMAT header structure.
Definition: riffenc.c:54
static int mkv_init(struct AVFormatContext *s)
Definition: matroskaenc.c:2570
ebml_master tracks_master
Definition: matroskaenc.c:126
#define MATROSKA_ID_VIDEOPROJECTIONPOSEROLL
Definition: matroska.h:161
#define MATROSKA_ID_CUETRACKPOSITION
Definition: matroska.h:192
enum AVCodecID ff_codec_get_id(const AVCodecTag *tags, unsigned int tag)
Definition: utils.c:3050
#define MATROSKA_ID_CODECPRIVATE
Definition: matroska.h:89
av_cold int av_sha_init(AVSHA *ctx, int bits)
Initialize SHA-1 or SHA-2 hashing.
Definition: sha.c:273
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition: log.h:182
#define LIBAVUTIL_VERSION_INT
Definition: version.h:85
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:4601
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
static av_cold int init(AVCodecContext *avctx)
Definition: avrndec.c:35
#define MATROSKA_ID_AUDIOBITDEPTH
Definition: matroska.h:167
#define MATROSKA_ID_TRACKFLAGDEFAULT
Definition: matroska.h:99
static const AVCodecTag additional_subtitle_tags[]
Definition: matroskaenc.c:2628
This side data should be associated with a video stream and contains Stereoscopic 3D information in f...
Definition: avcodec.h:1471
static int mkv_write_attachments(AVFormatContext *s)
Definition: matroskaenc.c:1675
uint64_t pts
Definition: matroskaenc.c:79
Video represents a portion of a sphere mapped on a flat surface using equirectangular projection...
Definition: spherical.h:72
static int mkv_write_video_color(AVIOContext *pb, AVCodecParameters *par, AVStream *st)
Definition: matroskaenc.c:842
AVRational white_point[2]
CIE 1931 xy chromaticity coords of white point.
enum AVCodecID codec_id
Specific type of the encoded data (the codec used).
Definition: avcodec.h:4066
#define MATROSKA_ID_TAGTARGETS_ATTACHUID
Definition: matroska.h:214
int num
Numerator.
Definition: rational.h:59
int size
Definition: avcodec.h:1658
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:1078
const char * b
Definition: vf_curves.c:113
int64_t avio_seek(AVIOContext *s, int64_t offset, int whence)
fseek() equivalent for AVIOContext.
Definition: aviobuf.c:231
#define MATROSKA_ID_FILEDATA
Definition: matroska.h:246
AVFormatInternal * internal
An opaque field for libavformat internal usage.
Definition: avformat.h:1780
#define EBML_ID_DOCTYPEREADVERSION
Definition: matroska.h:42
#define MATROSKA_ID_BLOCKREFERENCE
Definition: matroska.h:237
int av_log2(unsigned v)
Definition: intmath.c:26
static int mkv_write_header(AVFormatContext *s)
Definition: matroskaenc.c:1797
#define MATROSKA_ID_TRACKTYPE
Definition: matroska.h:80
enum AVMediaType codec_type
Definition: rtp.c:37
#define MATROSKA_ID_TAGTARGETS_CHAPTERUID
Definition: matroska.h:213
int ff_flac_is_native_layout(uint64_t channel_layout)
int64_t duration
duration of the block according to time base
Definition: matroskaenc.c:84
static av_always_inline uint64_t av_double2int(double f)
Reinterpret a double as a 64-bit integer.
Definition: intfloat.h:70
#define MATROSKA_ID_VIDEOCOLOR_RX
Definition: matroska.h:145
Video represents a sphere mapped on a flat surface using equirectangular projection.
Definition: spherical.h:56
#define MATROSKA_ID_MUXINGAPP
Definition: matroska.h:70
int64_t cluster_time_limit
Definition: matroskaenc.c:147
#define MATROSKA_ID_AUDIOCHANNELS
Definition: matroska.h:168
int has_primaries
Flag indicating whether the display primaries (and white point) are set.
unsigned int ff_codec_get_tag(const AVCodecTag *tags, enum AVCodecID id)
Definition: utils.c:3040
int64_t segment_offset
Definition: matroskaenc.c:88
int version
Definition: avisynth_c.h:766
void * av_mallocz(size_t size)
Allocate a memory block with alignment suitable for all memory accesses (including vectors if availab...
Definition: mem.c:222
int avoid_negative_ts_use_pts
Definition: internal.h:121
const char * master
Definition: vf_curves.c:114
#define MATROSKA_ID_VIDEOPROJECTIONTYPE
Definition: matroska.h:157
AVPacketSideData * side_data
An array of side data that applies to the whole stream (i.e.
Definition: avformat.h:999
static AVPacket pkt
#define av_le2ne32(x)
Definition: bswap.h:96
#define MATROSKA_ID_CUECLUSTERPOSITION
Definition: matroska.h:196
#define MATROSKA_ID_VIDEOCOLOR_LUMINANCEMAX
Definition: matroska.h:153
Definition: matroskaenc.c:64
int avcodec_enum_to_chroma_pos(int *xpos, int *ypos, enum AVChromaLocation pos)
Converts AVChromaLocation to swscale x/y chroma position.
Definition: utils.c:452
uint64_t_TMPL AV_WL64 unsigned int_TMPL AV_WL32 unsigned int_TMPL AV_WL24 unsigned int_TMPL AV_WL16 uint64_t_TMPL AV_WB64 unsigned int_TMPL AV_WB32 unsigned int_TMPL AV_WB24 unsigned int_TMPL AV_RB16
Definition: bytestream.h:87
AVDictionary * metadata
Definition: avformat.h:1310
#define MATROSKA_ID_VIDEOCOLORCHROMASITINGHORZ
Definition: matroska.h:135
mkv_track * tracks
Definition: matroskaenc.c:136
#define src
Definition: vp8dsp.c:254
#define AVFMT_ALLOW_FLUSH
Format allows flushing.
Definition: avformat.h:495
Views are next to each other.
Definition: stereo3d.h:45
#define MATROSKA_ID_EDITIONFLAGDEFAULT
Definition: matroska.h:260
#define MATROSKA_ID_CLUSTERTIMECODE
Definition: matroska.h:224
int avio_open_dyn_buf(AVIOContext **s)
Open a write only memory stream.
Definition: aviobuf.c:1290
#define EBML_ID_DOCTYPE
Definition: matroska.h:40
#define AVFMT_TS_NONSTRICT
Format does not require strictly increasing timestamps, but they must still be monotonic.
Definition: avformat.h:496
This struct describes the properties of an encoded stream.
Definition: avcodec.h:4058
#define MATROSKA_ID_CHAPTERTIMEEND
Definition: matroska.h:253
enum AVColorSpace color_space
Definition: avcodec.h:4155
int64_t pos
absolute offset in the file where the master's elements start
Definition: matroskaenc.c:60
MatroskaVideoStereoModeType
Definition: matroska.h:300
Mastering display metadata (based on SMPTE-2086:2014).
Definition: avcodec.h:1579
int ff_vorbiscomment_write(uint8_t **p, AVDictionary **m, const char *vendor_string)
Write a VorbisComment into a buffer.
Definition: vorbiscomment.c:54
#define FLAGS
Definition: matroskaenc.c:2635
#define MATROSKA_ID_FILEDESC
Definition: matroska.h:243
Format I/O context.
Definition: avformat.h:1349
#define EBML_ID_CRC32
Definition: matroska.h:46
UID uid
Definition: mxfenc.c:1819
char str[32]
Definition: internal.h:50
int64_t cluster_pos
file offset of the current cluster
Definition: matroskaenc.c:130
const char * class_name
The name of the class; usually it is the same name as the context structure type to which the AVClass...
Definition: log.h:72
#define AV_WB64(p, v)
Definition: intreadwrite.h:438
#define av_assert0(cond)
assert() equivalent, that is always enabled.
Definition: avassert.h:37
static const AVCodecTag additional_audio_tags[]
Definition: matroskaenc.c:2602
Public dictionary API.
planar YUV 4:2:0, 20bpp, (1 Cr & Cb sample per 2x2 Y & A samples)
Definition: pixfmt.h:102
void avio_wl32(AVIOContext *s, unsigned int val)
Definition: aviobuf.c:358
uint8_t
#define MATROSKA_ID_VIDEOCOLOR_BX
Definition: matroska.h:149
#define MATROSKA_ID_CHAPLANG
Definition: matroska.h:256
#define av_malloc(s)
static int mkv_write_tag(AVFormatContext *s, AVDictionary *m, unsigned int elementid, unsigned int uid, ebml_master *tags)
Definition: matroskaenc.c:1557
AVOptions.
#define MATROSKA_ID_TRACKLANGUAGE
Definition: matroska.h:97
AVCodecParameters * avcodec_parameters_alloc(void)
Allocate a new AVCodecParameters and set its fields to default values (unknown/invalid/0).
Definition: utils.c:4168
Stereo 3D type: this structure describes how two videos are packed within a single video surface...
Definition: stereo3d.h:123
const AVCodecTag ff_codec_movvideo_tags[]
Definition: isom.c:74
static int ebml_id_size(unsigned int id)
Definition: matroskaenc.c:179
#define OPUS_SEEK_PREROLL
Seek preroll value for opus.
Definition: matroskaenc.c:177
uint32_t flags
Definition: wv.h:40
int ff_mkv_stereo3d_conv(AVStream *st, MatroskaVideoStereoModeType stereo_mode)
Definition: matroska.c:155
static av_cold int end(AVCodecContext *avctx)
Definition: avrndec.c:90
uint64_t segmentpos
Definition: matroskaenc.c:66
int id
unique ID to identify the chapter
Definition: avformat.h:1307
int64_t duration
Duration of this packet in AVStream->time_base units, 0 if unknown.
Definition: avcodec.h:1675
#define MATROSKA_ID_TIMECODESCALE
Definition: matroska.h:66
static int mkv_write_codecprivate(AVFormatContext *s, AVIOContext *pb, AVCodecParameters *par, int native_id, int qt_id)
Definition: matroskaenc.c:775
#define MATROSKA_ID_SIMPLEBLOCK
Definition: matroska.h:232
#define MATROSKA_ID_EDITIONFLAGHIDDEN
Definition: matroska.h:259
int nb_side_data
The number of elements in the AVStream.side_data array.
Definition: avformat.h:1003
void avio_write_marker(AVIOContext *s, int64_t time, enum AVIODataMarkerType type)
Mark the written bytestream as a specific type.
Definition: aviobuf.c:482
uint8_t * av_stream_get_side_data(const AVStream *stream, enum AVPacketSideDataType type, int *size)
Get side information from stream.
Definition: utils.c:5118
#define MATROSKA_ID_BLOCKMORE
Definition: matroska.h:229
uint64_t_TMPL AV_WL64 unsigned int_TMPL AV_WL32 unsigned int_TMPL AV_WL24 unsigned int_TMPL AV_WL16 uint64_t_TMPL AV_WB64 unsigned int_TMPL AV_RB32
Definition: bytestream.h:87
AVStream ** streams
A list of all streams in the file.
Definition: avformat.h:1417
int64_t duration
Definition: movenc.c:63
#define MATROSKA_ID_CUERELATIVEPOSITION
Definition: matroska.h:197
A point in the output bytestream where a demuxer can start parsing (for non self synchronizing bytest...
Definition: avio.h:128
#define MATROSKA_ID_AUDIOOUTSAMPLINGFREQ
Definition: matroska.h:165
#define MATROSKA_ID_VIDEOCOLOR
Definition: matroska.h:127
Public header for CRC hash function implementation.
int initial_padding
Audio only.
Definition: avcodec.h:4195
AVDictionaryEntry * av_dict_get(const AVDictionary *m, const char *key, const AVDictionaryEntry *prev, int flags)
Get a dictionary entry with matching key.
Definition: dict.c:40
int flags
Flags modifying the (de)muxer behaviour.
Definition: avformat.h:1460
uint8_t * data
Definition: avcodec.h:1657
static double av_q2d(AVRational a)
Convert an AVRational to a double.
Definition: rational.h:104
static int64_t mkv_write_cues(AVFormatContext *s, mkv_cues *cues, mkv_track *tracks, int num_tracks)
Definition: matroskaenc.c:574
#define MATROSKA_ID_VIDEODISPLAYWIDTH
Definition: matroska.h:112
static int flags
Definition: log.c:57
#define MATROSKA_ID_BLOCKADDITIONS
Definition: matroska.h:228
uint32_t tag
Definition: movenc.c:1413
Not part of ABI.
Definition: pixfmt.h:477
#define WV_HEADER_SIZE
Definition: wavpack.h:30
enum AVCodecID id
Definition: internal.h:51
#define AV_LOG_VERBOSE
Detailed information.
Definition: log.h:192
uint8_t * data
Definition: avcodec.h:1601
#define MATROSKA_ID_CUES
Definition: matroska.h:58
static int start_ebml_master_crc32(AVIOContext *pb, AVIOContext **dyn_cp, MatroskaMuxContext *mkv, ebml_master *master, unsigned int elementid, uint64_t expectedsize)
Definition: matroskaenc.c:328
int64_t ts_offset
Definition: matroskaenc.c:97
ptrdiff_t size
Definition: opengl_enc.c:101
static av_always_inline int64_t avio_tell(AVIOContext *s)
ftell() equivalent for AVIOContext.
Definition: avio.h:525
int av_reduce(int *dst_num, int *dst_den, int64_t num, int64_t den, int64_t max)
Reduce a fraction.
Definition: rational.c:35
int has_luminance
Flag indicating whether the luminance (min_ and max_) have been set.
static const uint8_t header[24]
Definition: sdr2.c:67
#define MATROSKA_ID_TRACKNUMBER
Definition: matroska.h:78
#define MATROSKA_ID_VIDEOCOLOR_WHITEY
Definition: matroska.h:152
void avio_write(AVIOContext *s, const unsigned char *buf, int size)
Definition: aviobuf.c:205
Definition: wv.h:34
#define AVFMT_FLAG_BITEXACT
When muxing, try to avoid writing any random/volatile data to the output.
Definition: avformat.h:1477
Views are alternated temporally.
Definition: stereo3d.h:66
void * av_realloc_array(void *ptr, size_t nmemb, size_t size)
Definition: mem.c:184
#define MATROSKA_ID_SEGMENTUID
Definition: matroska.h:72
uint64_t channel_layout
Audio only.
Definition: avcodec.h:4168
static void put_ebml_num(AVIOContext *pb, uint64_t num, int bytes)
Write a number in EBML variable length format.
Definition: matroskaenc.c:220
#define av_log(a,...)
int has_cue
Definition: matroskaenc.c:95
#define AV_DISPOSITION_CAPTIONS
To specify text track kind (different from subtitles default).
Definition: avformat.h:871
static int mkv_add_seekhead_entry(mkv_seekhead *seekhead, unsigned int elementid, uint64_t filepos)
Definition: matroskaenc.c:462
int64_t segment_offset
the file offset to the beginning of the segment
Definition: matroskaenc.c:71
struct AVOutputFormat * oformat
The output container format.
Definition: avformat.h:1368
int av_packet_ref(AVPacket *dst, const AVPacket *src)
Setup a new reference to the data described by a given packet.
Definition: avpacket.c:598
#define AV_PKT_FLAG_KEY
The packet contains a keyframe.
Definition: avcodec.h:1689
static int get_aac_sample_rates(AVFormatContext *s, AVCodecParameters *par, int *sample_rate, int *output_sample_rate)
Definition: matroskaenc.c:718
#define MATROSKA_ID_TRACKUID
Definition: matroska.h:79
int64_t av_rescale_q(int64_t a, AVRational bq, AVRational cq)
Rescale a 64-bit integer by 2 rational numbers.
Definition: mathematics.c:142
ebml_master segment
Definition: matroskaenc.c:127
static int mkv_write_simpletag(AVIOContext *pb, AVDictionaryEntry *t)
Definition: matroskaenc.c:1484
#define MATROSKA_ID_VIDEOSTEREOMODE
Definition: matroska.h:123
uint32_t chapter_id_offset
Definition: matroskaenc.c:153
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:5320
AVPacket cur_audio_pkt
Definition: matroskaenc.c:139
AVCodecID
Identify the syntax and semantics of the bitstream.
Definition: avcodec.h:214
static int mkv_write_tags(AVFormatContext *s)
Definition: matroskaenc.c:1592
#define MATROSKA_ID_VIDEOCOLOR_BY
Definition: matroska.h:150
int avcodec_parameters_copy(AVCodecParameters *dst, const AVCodecParameters *src)
Copy the contents of src to dst.
Definition: utils.c:4189
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition: log.h:176
int av_get_bits_per_sample(enum AVCodecID codec_id)
Return codec bits per sample.
Definition: utils.c:3575
AVDictionary * metadata
Metadata that applies to the whole file.
Definition: avformat.h:1567
int flags
Additional information about the frame packing.
Definition: stereo3d.h:132
#define MATROSKA_ID_BLOCKDURATION
Definition: matroska.h:236
#define EBML_ID_EBMLREADVERSION
Definition: matroska.h:37
#define MAX_CUETRACKPOS_SIZE
per-cuepoint-track - 5 1-byte EBML IDs, 5 1-byte EBML sizes, 4 8-byte uint max
Definition: matroskaenc.c:171
#define MATROSKA_ID_VIDEOCOLOR_WHITEX
Definition: matroska.h:151
static void end_ebml_master_crc32_preliminary(AVIOContext *pb, AVIOContext **dyn_cp, MatroskaMuxContext *mkv, ebml_master master)
Complete ebml master whithout destroying the buffer, allowing for later updates.
Definition: matroskaenc.c:373
av_default_item_name
#define AVERROR(e)
Definition: error.h:43
unsigned int elementid
Definition: matroskaenc.c:65
uint8_t * av_packet_get_side_data(const AVPacket *pkt, enum AVPacketSideDataType type, int *size)
Get side information from packet.
Definition: avpacket.c:350
int reserved_size
-1 if appending to file
Definition: matroskaenc.c:72
#define MATROSKA_ID_CLUSTER
Definition: matroska.h:62
const char * ff_convert_lang_to(const char *lang, enum AVLangCodespace target_codespace)
Convert a language code to a target codespace.
Definition: avlanguage.c:736
#define MATROSKA_ID_VIDEOCOLORCHROMASITINGVERT
Definition: matroska.h:136
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification. ...
Definition: internal.h:179
enum AVColorPrimaries color_primaries
Definition: avcodec.h:4153
#define MATROSKA_ID_FILEMIMETYPE
Definition: matroska.h:245
#define MATROSKA_ID_WRITINGAPP
Definition: matroska.h:69
#define AV_LOG_DEBUG
Stuff which is only useful for libav* developers.
Definition: log.h:197
int ff_isom_write_hvcc(AVIOContext *pb, const uint8_t *data, int size, int ps_array_completeness)
Writes HEVC extradata (parameter sets, declarative SEI NAL units) to the provided AVIOContext...
Definition: hevc.c:1094
Not part of ABI.
Definition: pixfmt.h:417
AVIOContext * tracks_bc
Definition: matroskaenc.c:125
const char *const ff_matroska_video_stereo_mode[MATROSKA_VIDEO_STEREOMODE_TYPE_NB]
Definition: matroska.c:131
void av_dict_free(AVDictionary **pm)
Free all the memory allocated for an AVDictionary struct and all keys and values. ...
Definition: dict.c:203
static int mkv_blockgroup_size(int pkt_size)
Definition: matroskaenc.c:1994
enum AVMediaType codec_type
General type of the encoded data.
Definition: avcodec.h:4062
static int ebml_num_size(uint64_t num)
Calculate how many bytes are needed to represent a given number in EBML.
Definition: matroskaenc.c:206
int write_dts
Definition: matroskaenc.c:94
int final
Definition: wv.h:43
AVChapter ** chapters
Definition: avformat.h:1557
enum AVCodecID id
Definition: matroska.h:354
enum AVPacketSideDataType type
Definition: avcodec.h:1603
enum AVMediaType avcodec_get_type(enum AVCodecID codec_id)
Get the type of the given codec.
Definition: codec_desc.c:3092
static int mkv_write_chapters(AVFormatContext *s)
Definition: matroskaenc.c:1430
static int mkv_check_tag(AVDictionary *m, unsigned int elementid)
Definition: matroskaenc.c:1581
#define EBML_ID_EBMLMAXIDLENGTH
Definition: matroska.h:38
int64_t ff_vorbiscomment_length(AVDictionary *m, const char *vendor_string)
Calculate the length in bytes of a VorbisComment.
Definition: vorbiscomment.c:41
#define MATROSKA_ID_CHAPTERFLAGHIDDEN
Definition: matroska.h:263
static const uint8_t offset[127][2]
Definition: vf_spp.c:92
uint32_t crc
Definition: wv.h:41
void ff_put_bmp_header(AVIOContext *pb, AVCodecParameters *par, const AVCodecTag *tags, int for_asf, int ignore_extradata)
Definition: riffenc.c:209
const AVCodecTag ff_codec_wav_tags[]
Definition: riff.c:458
#define FFMAX(a, b)
Definition: common.h:94
static mkv_seekhead * mkv_start_seekhead(AVIOContext *pb, int64_t segment_offset, int numelements)
Initialize a mkv_seekhead element to be ready to index level 1 Matroska elements. ...
Definition: matroskaenc.c:441
int ff_avc_parse_nal_units_buf(const uint8_t *buf_in, uint8_t **buf, int *size)
Definition: avc.c:92
AVRational max_luminance
Max luminance of mastering display (cd/m^2).
void avcodec_parameters_free(AVCodecParameters **par)
Free an AVCodecParameters instance and everything associated with it and write NULL to the supplied p...
Definition: utils.c:4178
int64_t filepos
Definition: matroskaenc.c:70
static void * av_mallocz_array(size_t nmemb, size_t size)
Definition: mem.h:229
#define fail()
Definition: checkasm.h:89
int flags
A combination of AV_PKT_FLAG values.
Definition: avcodec.h:1663
int extradata_size
Size of the extradata content in bytes.
Definition: avcodec.h:4084
const CodecMime ff_mkv_mime_tags[]
Definition: matroska.c:115
#define MATROSKA_ID_TAG
Definition: matroska.h:202
#define AV_DISPOSITION_FORCED
Track should be used during playback by default.
Definition: avformat.h:848
unsigned int nb_streams
Number of elements in AVFormatContext.streams.
Definition: avformat.h:1405
uint32_t bound_bottom
Distance from the bottom edge.
Definition: spherical.h:170
#define LIBAVFORMAT_IDENT
Definition: version.h:46
Views are packed per line, as if interlaced.
Definition: stereo3d.h:97
int seekable
A combination of AVIO_SEEKABLE_ flags or 0 when the stream is not seekable.
Definition: avio.h:251
Video frame is split into 6 faces of a cube, and arranged on a 3x2 layout.
Definition: spherical.h:65
int void avio_flush(AVIOContext *s)
Force flushing of buffered data.
Definition: aviobuf.c:225
#define MATROSKA_ID_VIDEOCOLOR_LUMINANCEMIN
Definition: matroska.h:154
audio channel layout utility functions
#define EBML_ID_EBMLVERSION
Definition: matroska.h:36
int64_t av_rescale(int64_t a, int64_t b, int64_t c)
Rescale a 64-bit integer with rounding to nearest.
Definition: mathematics.c:129
mkv_cuepoint * entries
Definition: matroskaenc.c:89
void ffio_fill(AVIOContext *s, int b, int count)
Definition: aviobuf.c:191
#define AV_TIME_BASE
Internal time base represented as integer.
Definition: avutil.h:254
#define MATROSKA_ID_TAGTARGETS
Definition: matroska.h:209
const AVCodecTag ff_codec_bmp_tags[]
Definition: riff.c:32
int av_strcasecmp(const char *a, const char *b)
Locale-independent case-insensitive compare.
Definition: avstring.c:213
#define MATROSKA_ID_TAGNAME
Definition: matroska.h:204
AVRational min_luminance
Min luminance of mastering display (cd/m^2).
static int put_wv_codecpriv(AVIOContext *pb, AVCodecParameters *par)
Definition: matroskaenc.c:662
static void mkv_free(MatroskaMuxContext *mkv)
Free the members allocated in the mux context.
Definition: matroskaenc.c:395
#define MATROSKA_ID_CHAPTERFLAGENABLED
Definition: matroska.h:264
static int64_t mkv_write_seekhead(AVIOContext *pb, MatroskaMuxContext *mkv)
Write the seek head to the file and free it.
Definition: matroskaenc.c:490
static int64_t get_metadata_duration(AVFormatContext *s)
Definition: matroskaenc.c:1773
static int write_trailer(AVFormatContext *s1)
Definition: v4l2enc.c:94
static void bit_depth(AudioStatsContext *s, uint64_t mask, uint64_t imask, AVRational *depth)
Definition: af_astats.c:150
#define AVFMT_GLOBALHEADER
Format wants global header.
Definition: avformat.h:485
This side data should be associated with a video stream and corresponds to the AVSphericalMapping str...
Definition: avcodec.h:1585
uint32_t bound_right
Distance from the right edge.
Definition: spherical.h:169
int ff_wv_parse_header(WvHeader *wv, const uint8_t *data)
Parse a WavPack block header.
Definition: wv.c:29
#define MATROSKA_ID_SIMPLETAG
Definition: matroska.h:203
const char * name
Definition: avformat.h:524
internal header for RIFF based (de)muxers do NOT include this in end user applications ...
uint32_t av_crc(const AVCRC *ctx, uint32_t crc, const uint8_t *buffer, size_t length)
Calculate the CRC of a block.
Definition: crc.c:357
#define AV_WB24(p, d)
Definition: intreadwrite.h:455
static int mkv_check_new_extra_data(AVFormatContext *s, AVPacket *pkt)
Definition: matroskaenc.c:2213
int ff_flac_write_header(AVIOContext *pb, uint8_t *extradata, int extradata_size, int last_block)
int avoid_negative_ts
Avoid negative timestamps during muxing.
Definition: avformat.h:1658
#define MATROSKA_ID_CHAPTERATOM
Definition: matroska.h:251
int avpriv_split_xiph_headers(const uint8_t *extradata, int extradata_size, int first_header_size, const uint8_t *header_start[3], int header_len[3])
Split a single extradata buffer into the three headers that most Xiph codecs use. ...
Definition: xiph.c:24
int32_t yaw
Rotation around the up vector [-180, 180].
Definition: spherical.h:126
AVDictionary * metadata
Definition: avformat.h:961
enum AVCodecID codec_id
Definition: vaapi_decode.c:235
enum AVColorRange color_range
Video only.
Definition: avcodec.h:4152
AVIOContext * info_bc
Definition: matroskaenc.c:123
Opaque data information usually sparse.
Definition: avutil.h:205
#define MATROSKA_ID_VIDEOCOLORSPACE
Definition: matroska.h:126
#define MATROSKA_ID_CHAPTERS
Definition: matroska.h:63
#define EBML_ID_VOID
Definition: matroska.h:45
#define OFFSET(x)
Definition: matroskaenc.c:2634
#define AV_STEREO3D_FLAG_INVERT
Inverted views, Right/Bottom represents the left view.
Definition: stereo3d.h:114
#define MATROSKA_ID_AUDIOSAMPLINGFREQ
Definition: matroska.h:164
const char * avcodec_get_name(enum AVCodecID id)
Get the name of a codec.
Definition: utils.c:3187
static void end_ebml_master_crc32(AVIOContext *pb, AVIOContext **dyn_cp, MatroskaMuxContext *mkv, ebml_master master)
Definition: matroskaenc.c:346
Views are packed per column.
Definition: stereo3d.h:107
uint32_t padding
Number of pixels to pad from the edge of each cube face.
Definition: spherical.h:182
static int mkv_add_cuepoint(mkv_cues *cues, int stream, int tracknum, int64_t ts, int64_t cluster_pos, int64_t relative_pos, int64_t duration)
Definition: matroskaenc.c:551
static void put_ebml_float(AVIOContext *pb, unsigned int elementid, double val)
Definition: matroskaenc.c:265
Stream structure.
Definition: avformat.h:889
#define AVERROR_PATCHWELCOME
Not yet implemented in FFmpeg, patches welcome.
Definition: error.h:62
static void put_ebml_string(AVIOContext *pb, unsigned int elementid, const char *str)
Definition: matroskaenc.c:280
int64_t end
chapter start/end time in time_base units
Definition: avformat.h:1309
static int mkv_write_track(AVFormatContext *s, MatroskaMuxContext *mkv, int i, AVIOContext *pb, int default_stream_exists)
Definition: matroskaenc.c:1134
#define AVIO_SEEKABLE_NORMAL
Seeking works like for a local file.
Definition: avio.h:40
The AV_PKT_DATA_NEW_EXTRADATA is used to notify the codec or the format that the extradata buffer was...
Definition: avcodec.h:1412
#define AV_DISPOSITION_DEFAULT
Definition: avformat.h:836
sample_rate
enum AVStereo3DType type
How views are packed within the video.
Definition: stereo3d.h:127
#define MATROSKA_ID_VIDEOCOLORMATRIXCOEFF
Definition: matroska.h:129
#define AV_DISPOSITION_DESCRIPTIONS
Definition: avformat.h:872
char * av_strdup(const char *s)
Duplicate a string.
Definition: mem.c:237
#define MATROSKA_ID_TRACKFLAGFORCED
Definition: matroska.h:100
#define MATROSKA_ID_TAGS
Definition: matroska.h:59
#define MATROSKA_ID_VIDEOCOLORPRIMARIES
Definition: matroska.h:140
uint64_t_TMPL AV_WL64 unsigned int_TMPL AV_WL32 unsigned int_TMPL AV_WL24 unsigned int_TMPL AV_WL16 uint64_t_TMPL AV_WB64 unsigned int_TMPL AV_WB32 unsigned int_TMPL AV_RB24
Definition: bytestream.h:87
#define MATROSKA_ID_VIDEOPROJECTIONPOSEPITCH
Definition: matroska.h:160
#define AV_TIME_BASE_Q
Internal time base represented as fractional value.
Definition: avutil.h:260
#define MATROSKA_ID_SEEKID
Definition: matroska.h:220
AVIOContext * pb
I/O context.
Definition: avformat.h:1391
int64_t codecpriv_offset
Definition: matroskaenc.c:96
void avio_w8(AVIOContext *s, int b)
Definition: aviobuf.c:183
Public header for SHA-1 & SHA-256 hash function implementations.
#define MATROSKA_ID_BLOCK
Definition: matroska.h:235
#define MATROSKA_ID_INFO
Definition: matroska.h:56
void av_packet_unref(AVPacket *pkt)
Wipe the packet.
Definition: avpacket.c:589
#define MATROSKA_ID_TAGTARGETS_TRACKUID
Definition: matroska.h:212
static const EbmlSyntax ebml_header[]
Definition: matroskadec.c:379
mkv_attachment * entries
Definition: matroskaenc.c:106
uint32_t fileuid
Definition: matroskaenc.c:102
#define MATROSKA_ID_TAGLANG
Definition: matroska.h:206
static int mkv_check_tag_name(const char *name, unsigned int elementid)
Definition: matroskaenc.c:1543
struct AVSHA * av_sha_alloc(void)
Allocate an AVSHA context.
Definition: sha.c:45
static unsigned int av_lfg_get(AVLFG *c)
Get the next random unsigned 32-bit number using an ALFG.
Definition: lfg.h:47
#define MATROSKA_ID_TRACKS
Definition: matroska.h:57
void * buf
Definition: avisynth_c.h:690
Data found in BlockAdditional element of matroska container.
Definition: avcodec.h:1548
GLint GLenum type
Definition: opengl_enc.c:105
#define MATROSKA_ID_TRACKNAME
Definition: matroska.h:96
int av_dict_set(AVDictionary **pm, const char *key, const char *value, int flags)
Set the given entry in *pm, overwriting an existing entry.
Definition: dict.c:70
#define MATROSKA_ID_SEEKENTRY
Definition: matroska.h:217
static const char * format
Definition: movenc.c:47
Describe the class of an AVClass context structure.
Definition: log.h:67
#define MATROSKA_ID_EDITIONENTRY
Definition: matroska.h:250
#define FF_COMPLIANCE_NORMAL
Definition: avcodec.h:2954
#define MAX_CUEPOINT_SIZE(num_tracks)
per-cuepoint - 2 1-byte EBML IDs, 2 1-byte EBML sizes, 8-byte uint max
Definition: matroskaenc.c:174
#define MATROSKA_ID_BLOCKGROUP
Definition: matroska.h:227
#define MATROSKA_ID_VIDEOPIXELHEIGHT
Definition: matroska.h:115
int32_t roll
Rotation around the forward vector [-180, 180].
Definition: spherical.h:128
static int mkv_write_tracks(AVFormatContext *s)
Definition: matroskaenc.c:1398
Rational number (pair of numerator and denominator).
Definition: rational.h:58
Copyright (c) 2016 Neil Birkbeck neil.birkbeck@gmail.com
static void put_ebml_uint(AVIOContext *pb, unsigned int elementid, uint64_t val)
Definition: matroskaenc.c:239
#define MATROSKA_ID_CUEDURATION
Definition: matroska.h:198
#define MATROSKA_ID_CUETIME
Definition: matroska.h:191
Not part of ABI.
Definition: pixfmt.h:445
AVFieldOrder
Definition: avcodec.h:1710
Recommmends skipping the specified number of samples.
Definition: avcodec.h:1513
AVIOContext * dyn_bc
Definition: matroskaenc.c:120
AVMediaType
Definition: avutil.h:199
av_cold void av_lfg_init(AVLFG *c, unsigned int seed)
Definition: lfg.c:32
int64_t duration_offset
Definition: matroskaenc.c:132
#define MATROSKA_ID_VIDEOCOLORTRANSFERCHARACTERISTICS
Definition: matroska.h:138
#define MATROSKA_ID_TITLE
Definition: matroska.h:68
#define snprintf
Definition: snprintf.h:34
#define MATROSKA_ID_TRACKVIDEO
Definition: matroska.h:81
static int mkv_strip_wavpack(const uint8_t *src, uint8_t **pdst, int *size)
Definition: matroskaenc.c:2005
This structure describes how to handle spherical videos, outlining information about projection...
Definition: spherical.h:82
static void put_ebml_id(AVIOContext *pb, unsigned int id)
Definition: matroskaenc.c:184
#define MATROSKA_ID_VIDEOPROJECTION
Definition: matroska.h:156
#define MATROSKA_ID_VIDEOCOLORMASTERINGMETA
Definition: matroska.h:144
misc parsing utilities
#define MATROSKA_ID_VIDEOPROJECTIONPRIVATE
Definition: matroska.h:158
AVRational display_primaries[3][2]
CIE 1931 xy chromaticity coords of color primaries (r, g, b order).
static void put_ebml_sint(AVIOContext *pb, unsigned int elementid, int64_t val)
Definition: matroskaenc.c:252
#define MATROSKA_ID_ATTACHMENTS
Definition: matroska.h:61
static int64_t pts
Global timestamp for the audio frames.
void avio_wb16(AVIOContext *s, unsigned int val)
Definition: aviobuf.c:464
int64_t * stream_duration_offsets
Definition: matroskaenc.c:159
#define MATROSKA_ID_CHAPTERDISPLAY
Definition: matroska.h:254
static int put_xiph_codecpriv(AVFormatContext *s, AVIOContext *pb, AVCodecParameters *par)
Definition: matroskaenc.c:634
int bits_per_raw_sample
This is the number of valid bits in each output sample.
Definition: avcodec.h:4121
#define MATROSKA_ID_FILENAME
Definition: matroska.h:244
int av_get_bytes_per_sample(enum AVSampleFormat sample_fmt)
Return number of bytes per sample.
Definition: samplefmt.c:106
#define MATROSKA_ID_BLOCKADDITIONAL
Definition: matroska.h:231
uint32_t bound_top
Distance from the top edge.
Definition: spherical.h:168
const AVMetadataConv ff_mkv_metadata_conv[]
Definition: matroska.c:125
#define MATROSKA_ID_CODECID
Definition: matroska.h:88
static const AVCodecTag additional_video_tags[]
Definition: matroskaenc.c:2619
static int put_flac_codecpriv(AVFormatContext *s, AVIOContext *pb, AVCodecParameters *par)
Definition: matroskaenc.c:671
#define MATROSKA_ID_VIDEOFIELDORDER
Definition: matroska.h:122
int64_t start
Definition: avformat.h:1309
static av_always_inline AVRational av_inv_q(AVRational q)
Invert a rational.
Definition: rational.h:159
const AVCRC * av_crc_get_table(AVCRCId crc_id)
Get an initialized standard CRC table.
Definition: crc.c:343
int sample_rate
Audio only.
Definition: avcodec.h:4176
#define MATROSKA_ID_VIDEOALPHAMODE
Definition: matroska.h:124
static int av_cmp_q(AVRational a, AVRational b)
Compare two rationals.
Definition: rational.h:89
static int mkv_write_trailer(AVFormatContext *s)
Definition: matroskaenc.c:2437
uint64_t_TMPL AV_WL64 unsigned int_TMPL AV_WL32 unsigned int_TMPL AV_WL24 unsigned int_TMPL AV_WL16 uint64_t_TMPL AV_RB64
Definition: bytestream.h:87
Main libavformat public API header.
static int mkv_check_bitstream(struct AVFormatContext *s, const AVPacket *pkt)
Definition: matroskaenc.c:2587
attribute_deprecated int64_t convergence_duration
Definition: avcodec.h:1686
#define MATROSKA_ID_CUETRACK
Definition: matroska.h:195
#define MATROSKA_ID_SEEKPOSITION
Definition: matroska.h:221
int64_t last_track_timestamp[MAX_TRACKS]
Definition: matroskaenc.c:156
#define MATROSKA_ID_CODECDELAY
Definition: matroska.h:94
#define FF_DISABLE_DEPRECATION_WARNINGS
Definition: internal.h:83
#define MATROSKA_ID_CHAPTERTIMESTART
Definition: matroska.h:252
common internal api header.
#define MATROSKA_ID_VIDEOCOLORRANGE
Definition: matroska.h:137
static void put_ebml_binary(AVIOContext *pb, unsigned int elementid, const void *buf, int size)
Definition: matroskaenc.c:272
enum AVSphericalProjection projection
Projection type.
Definition: spherical.h:86
Utilties for rational number calculation.
int ffio_init_context(AVIOContext *s, unsigned char *buffer, int buffer_size, int write_flag, void *opaque, int(*read_packet)(void *opaque, uint8_t *buf, int buf_size), int(*write_packet)(void *opaque, uint8_t *buf, int buf_size), int64_t(*seek)(void *opaque, int64_t offset, int whence))
Definition: aviobuf.c:81
Video is not stereoscopic (and metadata has to be there).
Definition: stereo3d.h:35
Views are packed in a checkerboard-like structure per pixel.
Definition: stereo3d.h:76
static double c[64]
static void mkv_write_block(AVFormatContext *s, AVIOContext *pb, unsigned int blockid, AVPacket *pkt, int keyframe)
Definition: matroskaenc.c:2058
static int mkv_write_flush_packet(AVFormatContext *s, AVPacket *pkt)
Definition: matroskaenc.c:2416
int disposition
AV_DISPOSITION_* bit field.
Definition: avformat.h:950
static void put_ebml_void(AVIOContext *pb, uint64_t size)
Write a void element of a given size.
Definition: matroskaenc.c:292
AVRational time_base
time base in which the start/end timestamps are specified
Definition: avformat.h:1308
void av_init_packet(AVPacket *pkt)
Initialize optional fields of a packet with default values.
Definition: avpacket.c:33
char * key
Definition: dict.h:86
int den
Denominator.
Definition: rational.h:60
uint8_t pi<< 24) CONV_FUNC(AV_SAMPLE_FMT_S64, int64_t, AV_SAMPLE_FMT_U8,(uint64_t)((*(constuint8_t *) pi-0x80U))<< 56) CONV_FUNC(AV_SAMPLE_FMT_FLT, float, AV_SAMPLE_FMT_U8,(*(constuint8_t *) pi-0x80)*(1.0f/(1<< 7))) CONV_FUNC(AV_SAMPLE_FMT_DBL, double, AV_SAMPLE_FMT_U8,(*(constuint8_t *) pi-0x80)*(1.0/(1<< 7))) CONV_FUNC(AV_SAMPLE_FMT_U8, uint8_t, AV_SAMPLE_FMT_S16,(*(constint16_t *) pi >>8)+0x80) CONV_FUNC(AV_SAMPLE_FMT_S64, int64_t, AV_SAMPLE_FMT_S16,(uint64_t)(*(constint16_t *) pi)<< 48) CONV_FUNC(AV_SAMPLE_FMT_FLT, float, AV_SAMPLE_FMT_S16,*(constint16_t *) pi *(1.0f/(1<< 15))) CONV_FUNC(AV_SAMPLE_FMT_DBL, double, AV_SAMPLE_FMT_S16,*(constint16_t *) pi *(1.0/(1<< 15))) CONV_FUNC(AV_SAMPLE_FMT_U8, uint8_t, AV_SAMPLE_FMT_S32,(*(constint32_t *) pi >>24)+0x80) CONV_FUNC(AV_SAMPLE_FMT_S64, int64_t, AV_SAMPLE_FMT_S32,(uint64_t)(*(constint32_t *) pi)<< 32) CONV_FUNC(AV_SAMPLE_FMT_FLT, float, AV_SAMPLE_FMT_S32,*(constint32_t *) pi *(1.0f/(1U<< 31))) CONV_FUNC(AV_SAMPLE_FMT_DBL, double, AV_SAMPLE_FMT_S32,*(constint32_t *) pi *(1.0/(1U<< 31))) CONV_FUNC(AV_SAMPLE_FMT_U8, uint8_t, AV_SAMPLE_FMT_S64,(*(constint64_t *) pi >>56)+0x80) CONV_FUNC(AV_SAMPLE_FMT_FLT, float, AV_SAMPLE_FMT_S64,*(constint64_t *) pi *(1.0f/(INT64_C(1)<< 63))) CONV_FUNC(AV_SAMPLE_FMT_DBL, double, AV_SAMPLE_FMT_S64,*(constint64_t *) pi *(1.0/(INT64_C(1)<< 63))) CONV_FUNC(AV_SAMPLE_FMT_U8, uint8_t, AV_SAMPLE_FMT_FLT, av_clip_uint8(lrintf(*(constfloat *) pi *(1<< 7))+0x80)) CONV_FUNC(AV_SAMPLE_FMT_S16, int16_t, AV_SAMPLE_FMT_FLT, av_clip_int16(lrintf(*(constfloat *) pi *(1<< 15)))) CONV_FUNC(AV_SAMPLE_FMT_S32, int32_t, AV_SAMPLE_FMT_FLT, av_clipl_int32(llrintf(*(constfloat *) pi *(1U<< 31)))) CONV_FUNC(AV_SAMPLE_FMT_S64, int64_t, AV_SAMPLE_FMT_FLT, llrintf(*(constfloat *) pi *(INT64_C(1)<< 63))) CONV_FUNC(AV_SAMPLE_FMT_U8, uint8_t, AV_SAMPLE_FMT_DBL, av_clip_uint8(lrint(*(constdouble *) pi *(1<< 7))+0x80)) CONV_FUNC(AV_SAMPLE_FMT_S16, int16_t, AV_SAMPLE_FMT_DBL, av_clip_int16(lrint(*(constdouble *) pi *(1<< 15)))) CONV_FUNC(AV_SAMPLE_FMT_S32, int32_t, AV_SAMPLE_FMT_DBL, av_clipl_int32(llrint(*(constdouble *) pi *(1U<< 31)))) CONV_FUNC(AV_SAMPLE_FMT_S64, int64_t, AV_SAMPLE_FMT_DBL, llrint(*(constdouble *) pi *(INT64_C(1)<< 63)))#defineFMT_PAIR_FUNC(out, in) staticconv_func_type *constfmt_pair_to_conv_functions[AV_SAMPLE_FMT_NB *AV_SAMPLE_FMT_NB]={FMT_PAIR_FUNC(AV_SAMPLE_FMT_U8, AV_SAMPLE_FMT_U8), FMT_PAIR_FUNC(AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_U8), FMT_PAIR_FUNC(AV_SAMPLE_FMT_S32, AV_SAMPLE_FMT_U8), FMT_PAIR_FUNC(AV_SAMPLE_FMT_FLT, AV_SAMPLE_FMT_U8), FMT_PAIR_FUNC(AV_SAMPLE_FMT_DBL, AV_SAMPLE_FMT_U8), FMT_PAIR_FUNC(AV_SAMPLE_FMT_S64, AV_SAMPLE_FMT_U8), FMT_PAIR_FUNC(AV_SAMPLE_FMT_U8, AV_SAMPLE_FMT_S16), FMT_PAIR_FUNC(AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_S16), FMT_PAIR_FUNC(AV_SAMPLE_FMT_S32, AV_SAMPLE_FMT_S16), FMT_PAIR_FUNC(AV_SAMPLE_FMT_FLT, AV_SAMPLE_FMT_S16), FMT_PAIR_FUNC(AV_SAMPLE_FMT_DBL, AV_SAMPLE_FMT_S16), FMT_PAIR_FUNC(AV_SAMPLE_FMT_S64, AV_SAMPLE_FMT_S16), FMT_PAIR_FUNC(AV_SAMPLE_FMT_U8, AV_SAMPLE_FMT_S32), FMT_PAIR_FUNC(AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_S32), FMT_PAIR_FUNC(AV_SAMPLE_FMT_S32, AV_SAMPLE_FMT_S32), FMT_PAIR_FUNC(AV_SAMPLE_FMT_FLT, AV_SAMPLE_FMT_S32), FMT_PAIR_FUNC(AV_SAMPLE_FMT_DBL, AV_SAMPLE_FMT_S32), FMT_PAIR_FUNC(AV_SAMPLE_FMT_S64, AV_SAMPLE_FMT_S32), FMT_PAIR_FUNC(AV_SAMPLE_FMT_U8, AV_SAMPLE_FMT_FLT), FMT_PAIR_FUNC(AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_FLT), FMT_PAIR_FUNC(AV_SAMPLE_FMT_S32, AV_SAMPLE_FMT_FLT), FMT_PAIR_FUNC(AV_SAMPLE_FMT_FLT, AV_SAMPLE_FMT_FLT), FMT_PAIR_FUNC(AV_SAMPLE_FMT_DBL, AV_SAMPLE_FMT_FLT), FMT_PAIR_FUNC(AV_SAMPLE_FMT_S64, AV_SAMPLE_FMT_FLT), FMT_PAIR_FUNC(AV_SAMPLE_FMT_U8, AV_SAMPLE_FMT_DBL), FMT_PAIR_FUNC(AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_DBL), FMT_PAIR_FUNC(AV_SAMPLE_FMT_S32, AV_SAMPLE_FMT_DBL), FMT_PAIR_FUNC(AV_SAMPLE_FMT_FLT, AV_SAMPLE_FMT_DBL), FMT_PAIR_FUNC(AV_SAMPLE_FMT_DBL, AV_SAMPLE_FMT_DBL), FMT_PAIR_FUNC(AV_SAMPLE_FMT_S64, AV_SAMPLE_FMT_DBL), FMT_PAIR_FUNC(AV_SAMPLE_FMT_U8, AV_SAMPLE_FMT_S64), FMT_PAIR_FUNC(AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_S64), FMT_PAIR_FUNC(AV_SAMPLE_FMT_S32, AV_SAMPLE_FMT_S64), FMT_PAIR_FUNC(AV_SAMPLE_FMT_FLT, AV_SAMPLE_FMT_S64), FMT_PAIR_FUNC(AV_SAMPLE_FMT_DBL, AV_SAMPLE_FMT_S64), FMT_PAIR_FUNC(AV_SAMPLE_FMT_S64, AV_SAMPLE_FMT_S64),};staticvoidcpy1(uint8_t **dst, constuint8_t **src, intlen){memcpy(*dst,*src, len);}staticvoidcpy2(uint8_t **dst, constuint8_t **src, intlen){memcpy(*dst,*src, 2 *len);}staticvoidcpy4(uint8_t **dst, constuint8_t **src, intlen){memcpy(*dst,*src, 4 *len);}staticvoidcpy8(uint8_t **dst, constuint8_t **src, intlen){memcpy(*dst,*src, 8 *len);}AudioConvert *swri_audio_convert_alloc(enumAVSampleFormatout_fmt, enumAVSampleFormatin_fmt, intchannels, constint *ch_map, intflags){AudioConvert *ctx;conv_func_type *f=fmt_pair_to_conv_functions[av_get_packed_sample_fmt(out_fmt)+AV_SAMPLE_FMT_NB *av_get_packed_sample_fmt(in_fmt)];if(!f) returnNULL;ctx=av_mallocz(sizeof(*ctx));if(!ctx) returnNULL;if(channels==1){in_fmt=av_get_planar_sample_fmt(in_fmt);out_fmt=av_get_planar_sample_fmt(out_fmt);}ctx->channels=channels;ctx->conv_f=f;ctx->ch_map=ch_map;if(in_fmt==AV_SAMPLE_FMT_U8||in_fmt==AV_SAMPLE_FMT_U8P) memset(ctx->silence, 0x80, sizeof(ctx->silence));if(out_fmt==in_fmt &&!ch_map){switch(av_get_bytes_per_sample(in_fmt)){case1:ctx->simd_f=cpy1;break;case2:ctx->simd_f=cpy2;break;case4:ctx->simd_f=cpy4;break;case8:ctx->simd_f=cpy8;break;}}if(HAVE_YASM &&1) swri_audio_convert_init_x86(ctx, out_fmt, in_fmt, channels);if(ARCH_ARM) swri_audio_convert_init_arm(ctx, out_fmt, in_fmt, channels);if(ARCH_AARCH64) swri_audio_convert_init_aarch64(ctx, out_fmt, in_fmt, channels);returnctx;}voidswri_audio_convert_free(AudioConvert **ctx){av_freep(ctx);}intswri_audio_convert(AudioConvert *ctx, AudioData *out, AudioData *in, intlen){intch;intoff=0;constintos=(out->planar?1:out->ch_count)*out->bps;unsignedmisaligned=0;av_assert0(ctx->channels==out->ch_count);if(ctx->in_simd_align_mask){intplanes=in->planar?in->ch_count:1;unsignedm=0;for(ch=0;ch< planes;ch++) m|=(intptr_t) in->ch[ch];misaligned|=m &ctx->in_simd_align_mask;}if(ctx->out_simd_align_mask){intplanes=out->planar?out->ch_count:1;unsignedm=0;for(ch=0;ch< planes;ch++) m|=(intptr_t) out->ch[ch];misaligned|=m &ctx->out_simd_align_mask;}if(ctx->simd_f &&!ctx->ch_map &&!misaligned){off=len &~15;av_assert1(off >=0);av_assert1(off<=len);av_assert2(ctx->channels==SWR_CH_MAX||!in->ch[ctx->channels]);if(off >0){if(out->planar==in->planar){intplanes=out->planar?out->ch_count:1;for(ch=0;ch< planes;ch++){ctx->simd_f(out-> ch ch
Definition: audioconvert.c:56
#define MATROSKA_ID_SEGMENT
Definition: matroska.h:53
int avpriv_mpeg4audio_get_config(MPEG4AudioConfig *c, const uint8_t *buf, int bit_size, int sync_extension)
Parse MPEG-4 systems extradata from a raw buffer to retrieve audio configuration. ...
Definition: mpeg4audio.c:155
The optional settings (rendering instructions) that immediately follow the timestamp specifier of a W...
Definition: avcodec.h:1559
#define MATROSKA_ID_SEEKHEAD
Definition: matroska.h:60
#define EBML_ID_HEADER
Definition: matroska.h:33
A point in the output bytestream where a decoder can start decoding (i.e.
Definition: avio.h:122
mkv_attachments * attachments
Definition: matroskaenc.c:137
#define AVFMT_VARIABLE_FPS
Format allows variable fps.
Definition: avformat.h:489
ebml_master cluster
Definition: matroskaenc.c:129
#define av_free(p)
char * value
Definition: dict.h:87
#define FF_ENABLE_DEPRECATION_WARNINGS
Definition: internal.h:84
#define MATROSKA_ID_POINTENTRY
Definition: matroska.h:188
mkv_seekhead_entry * entries
Definition: matroskaenc.c:74
int len
static int mkv_write_native_codecprivate(AVFormatContext *s, AVCodecParameters *par, AVIOContext *dyn_cp)
Definition: matroskaenc.c:735
static int mkv_write_stereo_mode(AVFormatContext *s, AVIOContext *pb, AVStream *st, int mode, int *h_width, int *h_height)
Definition: matroskaenc.c:1036
#define MATROSKA_ID_FILEUID
Definition: matroska.h:247
int ff_stream_add_bitstream_filter(AVStream *st, const char *name, const char *args)
Add a bitstream filter to a stream.
Definition: utils.c:5188
static int mkv_write_tag_targets(AVFormatContext *s, unsigned int elementid, unsigned int uid, ebml_master *tags, ebml_master *tag)
Definition: matroskaenc.c:1518
void * priv_data
Format private data.
Definition: avformat.h:1377
#define MATROSKA_ID_CHAPTERUID
Definition: matroska.h:262
Views are on top of each other.
Definition: stereo3d.h:55
static void write_header(FFV1Context *f)
Definition: ffv1enc.c:337
uint32_t bound_left
Distance from the left edge.
Definition: spherical.h:167
int bits_per_coded_sample
The number of bits per sample in the codedwords.
Definition: avcodec.h:4108
int64_t relative_pos
relative offset from the position of the cluster containing the block
Definition: matroskaenc.c:83
uint8_t * extradata
Extra binary data needed for initializing the decoder, codec-dependent.
Definition: avcodec.h:4080
#define MATROSKA_ID_VIDEODISPLAYUNIT
Definition: matroska.h:120
int64_t dts
Decompression timestamp in AVStream->time_base units; the time at which the packet is decompressed...
Definition: avcodec.h:1656
static const AVOption options[]
Definition: matroskaenc.c:2636
#define EBML_ID_EBMLMAXSIZELENGTH
Definition: matroska.h:39
void avio_wb32(AVIOContext *s, unsigned int val)
Definition: aviobuf.c:366
int64_t duration
Duration of the stream, in AV_TIME_BASE fractional seconds.
Definition: avformat.h:1444
#define MATROSKA_ID_CHAPSTRING
Definition: matroska.h:255
#define av_freep(p)
#define MATROSKA_ID_TAGSTRING
Definition: matroska.h:205
#define AV_DICT_IGNORE_SUFFIX
Return first entry in a dictionary whose first part corresponds to the search key, ignoring the suffix of the found key string.
Definition: dict.h:70
#define MODE_MATROSKAv2
Definition: matroskaenc.c:110
uint32_t av_get_random_seed(void)
Get a seed to use in conjunction with random functions.
Definition: random_seed.c:120
const CodecMime ff_mkv_image_mime_tags[]
Definition: matroska.c:106
AVCodecParameters * codecpar
Definition: avformat.h:1252
ebml_master info
Definition: matroskaenc.c:124
uint32_t codec_tag
Additional information about the codec (corresponds to the AVI FOURCC).
Definition: avcodec.h:4070
#define MODE_WEBM
Definition: matroskaenc.c:111
static int mkv_write_packet(AVFormatContext *s, AVPacket *pkt)
Definition: matroskaenc.c:2341
ebml_master tags
Definition: matroskaenc.c:122
#define MATROSKA_ID_DURATION
Definition: matroska.h:67
#define MAX_SEEKENTRY_SIZE
2 bytes * 3 for EBML IDs, 3 1-byte EBML lengths, 8 bytes for 64 bit offset, 4 bytes for target EBML I...
Definition: matroskaenc.c:167
static mkv_cues * mkv_start_cues(int64_t segment_offset)
Definition: matroskaenc.c:541
int stream_index
Definition: avcodec.h:1659
int num_entries
Definition: matroskaenc.c:90
#define EBML_ID_DOCTYPEVERSION
Definition: matroska.h:41
AVRational time_base
This is the fundamental unit of time (in seconds) in terms of which frame timestamps are represented...
Definition: avformat.h:926
static void end_ebml_master(AVIOContext *pb, ebml_master master)
Definition: matroskaenc.c:318
int64_t segment_offset
Definition: matroskaenc.c:128
#define MATROSKA_ID_ATTACHEDFILE
Definition: matroska.h:242
#define MATROSKA_ID_VIDEOCOLOR_GY
Definition: matroska.h:148
static ebml_master start_ebml_master(AVIOContext *pb, unsigned int elementid, uint64_t expectedsize)
Definition: matroskaenc.c:309
mkv_seekhead * main_seekhead
Definition: matroskaenc.c:134
enum AVCodecID id
uint64_t_TMPL AV_WL64 unsigned int_TMPL AV_RL32
Definition: bytestream.h:87
This structure stores compressed data.
Definition: avcodec.h:1634
int64_t * stream_durations
Definition: matroskaenc.c:158
static void mkv_write_field_order(AVIOContext *pb, int mode, enum AVFieldOrder field_order)
Definition: matroskaenc.c:997
mode
Use these values in ebur128_init (or'ed).
Definition: ebur128.h:83
#define MATROSKA_ID_VIDEOCOLOR_RY
Definition: matroska.h:146
uint32_t blocksize
Definition: wv.h:35
static int mkv_query_codec(enum AVCodecID codec_id, int std_compliance)
Definition: matroskaenc.c:2553
static void put_xiph_size(AVIOContext *pb, int size)
Definition: matroskaenc.c:386
int64_t pts
Presentation timestamp in AVStream->time_base units; the time at which the decompressed packet will b...
Definition: avcodec.h:1650
Not part of ABI.
Definition: pixfmt.h:465
#define MATROSKA_ID_VIDEOPIXELWIDTH
Definition: matroska.h:114
int ff_isom_write_avcc(AVIOContext *pb, const uint8_t *data, int len)
Definition: avc.c:106
#define MATROSKA_ID_TRACKAUDIO
Definition: matroska.h:82
#define AV_NOPTS_VALUE
Undefined timestamp value.
Definition: avutil.h:248
AVIOContext * tags_bc
Definition: matroskaenc.c:121
const CodecTags ff_mkv_codec_tags[]
Definition: matroska.c:29
int avio_printf(AVIOContext *s, const char *fmt,...) av_printf_format(2
#define AV_WL32(p, v)
Definition: intreadwrite.h:431
#define MATROSKA_ID_DISCARDPADDING
Definition: matroska.h:239
#define FF_PUT_WAV_HEADER_FORCE_WAVEFORMATEX
Tell ff_put_wav_header() to use WAVEFORMATEX even for PCM codecs.
Definition: riff.h:53
static int mkv_write_video_projection(AVFormatContext *s, AVIOContext *pb, AVStream *st)
Definition: matroskaenc.c:921
const char * name
Definition: opengl_enc.c:103
int avio_get_dyn_buf(AVIOContext *s, uint8_t **pbuffer)
Return the written size and a pointer to the buffer.
Definition: aviobuf.c:1302
static uint8_t tmp[11]
Definition: aes_ctr.c:26