Libav
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 Libav.
6  *
7  * Libav 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  * Libav 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 Libav; 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 "avlanguage.h"
28 #include "flacenc.h"
29 #include "internal.h"
30 #include "isom.h"
31 #include "matroska.h"
32 #include "riff.h"
33 #include "vorbiscomment.h"
34 #include "wv.h"
35 
36 #include "libavutil/avstring.h"
38 #include "libavutil/dict.h"
39 #include "libavutil/intfloat.h"
40 #include "libavutil/intreadwrite.h"
41 #include "libavutil/lfg.h"
42 #include "libavutil/mathematics.h"
43 #include "libavutil/opt.h"
44 #include "libavutil/random_seed.h"
45 #include "libavutil/samplefmt.h"
46 #include "libavutil/stereo3d.h"
47 
48 #include "libavcodec/xiph.h"
49 #include "libavcodec/mpeg4audio.h"
50 
51 typedef struct ebml_master {
52  int64_t pos;
53  int sizebytes;
54 } ebml_master;
55 
56 typedef struct mkv_seekhead_entry {
57  unsigned int elementid;
58  uint64_t segmentpos;
60 
61 typedef struct mkv_seekhead {
62  int64_t filepos;
63  int64_t segment_offset;
68 } mkv_seekhead;
69 
70 typedef struct {
71  uint64_t pts;
72  int tracknum;
73  int64_t cluster_pos;
74 } mkv_cuepoint;
75 
76 typedef struct {
77  int64_t segment_offset;
80 } mkv_cues;
81 
82 typedef struct {
83  int write_dts;
84  int64_t ts_offset;
85 } mkv_track;
86 
87 #define MODE_MATROSKAv2 0x01
88 #define MODE_WEBM 0x02
89 
90 typedef struct MatroskaMuxContext {
91  const AVClass *class;
92  int mode;
95  int64_t segment_offset;
97  int64_t cluster_pos;
98  int64_t cluster_pts;
99  int64_t duration_offset;
100  int64_t duration;
104 
106 
108 
111  int64_t cues_pos;
115 
116 
119 #define MAX_SEEKENTRY_SIZE 21
120 
123 #define MAX_CUETRACKPOS_SIZE 22
124 
126 #define MAX_CUEPOINT_SIZE(num_tracks) 12 + MAX_CUETRACKPOS_SIZE * num_tracks
127 
128 static int ebml_id_size(unsigned int id)
129 {
130  return (av_log2(id + 1) - 1) / 7 + 1;
131 }
132 
133 static void put_ebml_id(AVIOContext *pb, unsigned int id)
134 {
135  int i = ebml_id_size(id);
136  while (i--)
137  avio_w8(pb, id >> (i * 8));
138 }
139 
145 static void put_ebml_size_unknown(AVIOContext *pb, int bytes)
146 {
147  assert(bytes <= 8);
148  avio_w8(pb, 0x1ff >> bytes);
149  while (--bytes)
150  avio_w8(pb, 0xff);
151 }
152 
156 static int ebml_num_size(uint64_t num)
157 {
158  int bytes = 1;
159  while ((num + 1) >> bytes * 7)
160  bytes++;
161  return bytes;
162 }
163 
170 static void put_ebml_num(AVIOContext *pb, uint64_t num, int bytes)
171 {
172  int i, needed_bytes = ebml_num_size(num);
173 
174  // sizes larger than this are currently undefined in EBML
175  assert(num < (1ULL << 56) - 1);
176 
177  if (bytes == 0)
178  // don't care how many bytes are used, so use the min
179  bytes = needed_bytes;
180  // the bytes needed to write the given size would exceed the bytes
181  // that we need to use, so write unknown size. This shouldn't happen.
182  assert(bytes >= needed_bytes);
183 
184  num |= 1ULL << bytes * 7;
185  for (i = bytes - 1; i >= 0; i--)
186  avio_w8(pb, num >> i * 8);
187 }
188 
189 static void put_ebml_uint(AVIOContext *pb, unsigned int elementid, uint64_t val)
190 {
191  int i, bytes = 1;
192  uint64_t tmp = val;
193  while (tmp >>= 8)
194  bytes++;
195 
196  put_ebml_id(pb, elementid);
197  put_ebml_num(pb, bytes, 0);
198  for (i = bytes - 1; i >= 0; i--)
199  avio_w8(pb, val >> i * 8);
200 }
201 
202 static void put_ebml_float(AVIOContext *pb, unsigned int elementid, double val)
203 {
204  put_ebml_id(pb, elementid);
205  put_ebml_num(pb, 8, 0);
206  avio_wb64(pb, av_double2int(val));
207 }
208 
209 static void put_ebml_binary(AVIOContext *pb, unsigned int elementid,
210  const void *buf, int size)
211 {
212  put_ebml_id(pb, elementid);
213  put_ebml_num(pb, size, 0);
214  avio_write(pb, buf, size);
215 }
216 
217 static void put_ebml_string(AVIOContext *pb, unsigned int elementid,
218  const char *str)
219 {
220  put_ebml_binary(pb, elementid, str, strlen(str));
221 }
222 
229 static void put_ebml_void(AVIOContext *pb, uint64_t size)
230 {
231  int64_t currentpos = avio_tell(pb);
232 
233  assert(size >= 2);
234 
236  // we need to subtract the length needed to store the size from the
237  // size we need to reserve so 2 cases, we use 8 bytes to store the
238  // size if possible, 1 byte otherwise
239  if (size < 10)
240  put_ebml_num(pb, size - 1, 0);
241  else
242  put_ebml_num(pb, size - 9, 8);
243  while (avio_tell(pb) < currentpos + size)
244  avio_w8(pb, 0);
245 }
246 
247 static ebml_master start_ebml_master(AVIOContext *pb, unsigned int elementid,
248  uint64_t expectedsize)
249 {
250  int bytes = expectedsize ? ebml_num_size(expectedsize) : 8;
251  put_ebml_id(pb, elementid);
252  put_ebml_size_unknown(pb, bytes);
253  return (ebml_master) {avio_tell(pb), bytes };
254 }
255 
256 static void end_ebml_master(AVIOContext *pb, ebml_master master)
257 {
258  int64_t pos = avio_tell(pb);
259 
260  if (avio_seek(pb, master.pos - master.sizebytes, SEEK_SET) < 0)
261  return;
262  put_ebml_num(pb, pos - master.pos, master.sizebytes);
263  avio_seek(pb, pos, SEEK_SET);
264 }
265 
266 static void put_xiph_size(AVIOContext *pb, int size)
267 {
268  int i;
269  for (i = 0; i < size / 255; i++)
270  avio_w8(pb, 255);
271  avio_w8(pb, size % 255);
272 }
273 
285 static mkv_seekhead *mkv_start_seekhead(AVIOContext *pb, int64_t segment_offset,
286  int numelements)
287 {
288  mkv_seekhead *new_seekhead = av_mallocz(sizeof(mkv_seekhead));
289  if (!new_seekhead)
290  return NULL;
291 
292  new_seekhead->segment_offset = segment_offset;
293 
294  if (numelements > 0) {
295  new_seekhead->filepos = avio_tell(pb);
296  // 21 bytes max for a seek entry, 10 bytes max for the SeekHead ID
297  // and size, and 3 bytes to guarantee that an EBML void element
298  // will fit afterwards
299  new_seekhead->reserved_size = numelements * MAX_SEEKENTRY_SIZE + 13;
300  new_seekhead->max_entries = numelements;
301  put_ebml_void(pb, new_seekhead->reserved_size);
302  }
303  return new_seekhead;
304 }
305 
306 static int mkv_add_seekhead_entry(mkv_seekhead *seekhead, unsigned int elementid, uint64_t filepos)
307 {
308  int err;
309 
310  // don't store more elements than we reserved space for
311  if (seekhead->max_entries > 0 && seekhead->max_entries <= seekhead->num_entries)
312  return -1;
313 
314  if ((err = av_reallocp_array(&seekhead->entries, seekhead->num_entries + 1,
315  sizeof(*seekhead->entries))) < 0) {
316  seekhead->num_entries = 0;
317  return err;
318  }
319 
320  seekhead->entries[seekhead->num_entries].elementid = elementid;
321  seekhead->entries[seekhead->num_entries++].segmentpos = filepos - seekhead->segment_offset;
322 
323  return 0;
324 }
325 
335 static int64_t mkv_write_seekhead(AVIOContext *pb, mkv_seekhead *seekhead)
336 {
337  ebml_master metaseek, seekentry;
338  int64_t currentpos;
339  int i;
340 
341  currentpos = avio_tell(pb);
342 
343  if (seekhead->reserved_size > 0) {
344  if (avio_seek(pb, seekhead->filepos, SEEK_SET) < 0) {
345  currentpos = -1;
346  goto fail;
347  }
348  }
349 
350  metaseek = start_ebml_master(pb, MATROSKA_ID_SEEKHEAD, seekhead->reserved_size);
351  for (i = 0; i < seekhead->num_entries; i++) {
352  mkv_seekhead_entry *entry = &seekhead->entries[i];
353 
355 
357  put_ebml_num(pb, ebml_id_size(entry->elementid), 0);
358  put_ebml_id(pb, entry->elementid);
359 
361  end_ebml_master(pb, seekentry);
362  }
363  end_ebml_master(pb, metaseek);
364 
365  if (seekhead->reserved_size > 0) {
366  uint64_t remaining = seekhead->filepos + seekhead->reserved_size - avio_tell(pb);
367  put_ebml_void(pb, remaining);
368  avio_seek(pb, currentpos, SEEK_SET);
369 
370  currentpos = seekhead->filepos;
371  }
372 fail:
373  av_free(seekhead->entries);
374  av_free(seekhead);
375 
376  return currentpos;
377 }
378 
379 static mkv_cues *mkv_start_cues(int64_t segment_offset)
380 {
381  mkv_cues *cues = av_mallocz(sizeof(mkv_cues));
382  if (!cues)
383  return NULL;
384 
385  cues->segment_offset = segment_offset;
386  return cues;
387 }
388 
389 static int mkv_add_cuepoint(mkv_cues *cues, int stream, int64_t ts, int64_t cluster_pos)
390 {
391  int err;
392 
393  if (ts < 0)
394  return 0;
395 
396  if ((err = av_reallocp_array(&cues->entries, cues->num_entries + 1,
397  sizeof(*cues->entries))) < 0) {
398  cues->num_entries = 0;
399  return err;
400  }
401 
402  cues->entries[cues->num_entries].pts = ts;
403  cues->entries[cues->num_entries].tracknum = stream + 1;
404  cues->entries[cues->num_entries++].cluster_pos = cluster_pos - cues->segment_offset;
405 
406  return 0;
407 }
408 
409 static int64_t mkv_write_cues(AVIOContext *pb, mkv_cues *cues, int num_tracks)
410 {
411  ebml_master cues_element;
412  int64_t currentpos;
413  int i, j;
414 
415  currentpos = avio_tell(pb);
416  cues_element = start_ebml_master(pb, MATROSKA_ID_CUES, 0);
417 
418  for (i = 0; i < cues->num_entries; i++) {
419  ebml_master cuepoint, track_positions;
420  mkv_cuepoint *entry = &cues->entries[i];
421  uint64_t pts = entry->pts;
422 
423  cuepoint = start_ebml_master(pb, MATROSKA_ID_POINTENTRY, MAX_CUEPOINT_SIZE(num_tracks));
425 
426  // put all the entries from different tracks that have the exact same
427  // timestamp into the same CuePoint
428  for (j = 0; j < cues->num_entries - i && entry[j].pts == pts; j++) {
430  put_ebml_uint(pb, MATROSKA_ID_CUETRACK , entry[j].tracknum );
431  put_ebml_uint(pb, MATROSKA_ID_CUECLUSTERPOSITION, entry[j].cluster_pos);
432  end_ebml_master(pb, track_positions);
433  }
434  i += j - 1;
435  end_ebml_master(pb, cuepoint);
436  }
437  end_ebml_master(pb, cues_element);
438 
439  return currentpos;
440 }
441 
443 {
444  uint8_t *header_start[3];
445  int header_len[3];
446  int first_header_size;
447  int j;
448 
449  if (codec->codec_id == AV_CODEC_ID_VORBIS)
450  first_header_size = 30;
451  else
452  first_header_size = 42;
453 
455  first_header_size, header_start, header_len) < 0) {
456  av_log(s, AV_LOG_ERROR, "Extradata corrupt.\n");
457  return -1;
458  }
459 
460  avio_w8(pb, 2); // number packets - 1
461  for (j = 0; j < 2; j++) {
462  put_xiph_size(pb, header_len[j]);
463  }
464  for (j = 0; j < 3; j++)
465  avio_write(pb, header_start[j], header_len[j]);
466 
467  return 0;
468 }
469 
471 {
472  if (codec->extradata && codec->extradata_size == 2)
473  avio_write(pb, codec->extradata, 2);
474  else
475  avio_wl16(pb, 0x403); // fallback to the version mentioned in matroska specs
476  return 0;
477 }
478 
480  AVIOContext *pb, AVCodecContext *codec)
481 {
482  int write_comment = (codec->channel_layout &&
483  !(codec->channel_layout & ~0x3ffffULL) &&
485  int ret = ff_flac_write_header(pb, codec->extradata, codec->extradata_size,
486  !write_comment);
487 
488  if (ret < 0)
489  return ret;
490 
491  if (write_comment) {
492  const char *vendor = (s->flags & AVFMT_FLAG_BITEXACT) ?
493  "Libav" : LIBAVFORMAT_IDENT;
494  AVDictionary *dict = NULL;
495  uint8_t buf[32], *data, *p;
496  int len;
497 
498  snprintf(buf, sizeof(buf), "0x%"PRIx64, codec->channel_layout);
499  av_dict_set(&dict, "WAVEFORMATEXTENSIBLE_CHANNEL_MASK", buf, 0);
500 
501  len = ff_vorbiscomment_length(dict, vendor);
502  data = av_malloc(len + 4);
503  if (!data) {
504  av_dict_free(&dict);
505  return AVERROR(ENOMEM);
506  }
507 
508  data[0] = 0x84;
509  AV_WB24(data + 1, len);
510 
511  p = data + 4;
512  ff_vorbiscomment_write(&p, &dict, vendor);
513 
514  avio_write(pb, data, len + 4);
515 
516  av_freep(&data);
517  av_dict_free(&dict);
518  }
519 
520  return 0;
521 }
522 
524  int *sample_rate, int *output_sample_rate)
525 {
526  MPEG4AudioConfig mp4ac;
527 
528  if (avpriv_mpeg4audio_get_config(&mp4ac, codec->extradata,
529  codec->extradata_size * 8, 1) < 0) {
531  "Error parsing AAC extradata, unable to determine samplerate.\n");
532  return;
533  }
534 
535  *sample_rate = mp4ac.sample_rate;
536  *output_sample_rate = mp4ac.ext_sample_rate;
537 }
538 
540  AVCodecContext *codec,
541  AVIOContext *dyn_cp)
542 {
543  switch (codec->codec_id) {
544  case AV_CODEC_ID_VORBIS:
545  case AV_CODEC_ID_THEORA:
546  return put_xiph_codecpriv(s, dyn_cp, codec);
547  case AV_CODEC_ID_FLAC:
548  return put_flac_codecpriv(s, dyn_cp, codec);
549  case AV_CODEC_ID_WAVPACK:
550  return put_wv_codecpriv(dyn_cp, codec);
551  case AV_CODEC_ID_H264:
552  return ff_isom_write_avcc(dyn_cp, codec->extradata,
553  codec->extradata_size);
554  case AV_CODEC_ID_HEVC:
555  return ff_isom_write_hvcc(dyn_cp, codec->extradata,
556  codec->extradata_size, 0);
557  case AV_CODEC_ID_ALAC:
558  if (codec->extradata_size < 36) {
559  av_log(s, AV_LOG_ERROR,
560  "Invalid extradata found, ALAC expects a 36-byte "
561  "QuickTime atom.");
562  return AVERROR_INVALIDDATA;
563  } else
564  avio_write(dyn_cp, codec->extradata + 12,
565  codec->extradata_size - 12);
566  break;
567  default:
568  if (codec->extradata_size)
569  avio_write(dyn_cp, codec->extradata, codec->extradata_size);
570  }
571 
572  return 0;
573 }
574 
576  AVCodecContext *codec, int native_id,
577  int qt_id)
578 {
579  AVIOContext *dyn_cp;
580  uint8_t *codecpriv;
581  int ret, codecpriv_size;
582 
583  ret = avio_open_dyn_buf(&dyn_cp);
584  if (ret < 0)
585  return ret;
586 
587  if (native_id) {
588  ret = mkv_write_native_codecprivate(s, codec, dyn_cp);
589  } else if (codec->codec_type == AVMEDIA_TYPE_VIDEO) {
590  if (qt_id) {
591  if (!codec->codec_tag)
593  codec->codec_id);
594  if (codec->extradata_size)
595  avio_write(dyn_cp, codec->extradata, codec->extradata_size);
596  } else {
597  if (!codec->codec_tag)
599  codec->codec_id);
600  if (!codec->codec_tag) {
601  av_log(s, AV_LOG_ERROR, "No bmp codec ID found.\n");
602  ret = -1;
603  }
604 
605  ff_put_bmp_header(dyn_cp, codec, ff_codec_bmp_tags, 0);
606  }
607  } else if (codec->codec_type == AVMEDIA_TYPE_AUDIO) {
608  unsigned int tag;
610  if (!tag) {
611  av_log(s, AV_LOG_ERROR, "No wav codec ID found.\n");
612  ret = -1;
613  }
614  if (!codec->codec_tag)
615  codec->codec_tag = tag;
616 
617  ff_put_wav_header(dyn_cp, codec);
618  }
619 
620  codecpriv_size = avio_close_dyn_buf(dyn_cp, &codecpriv);
621  if (codecpriv_size)
623  codecpriv_size);
624  av_free(codecpriv);
625  return ret;
626 }
627 
629  AVStream *st, int mode)
630 {
631  int i;
634 
635  // convert metadata into proper side data and add it to the stream
636  if ((tag = av_dict_get(s->metadata, "stereo_mode", NULL, 0))) {
637  int stereo_mode = atoi(tag->value);
638  if (stereo_mode < MATROSKA_VIDEO_STEREOMODE_TYPE_NB &&
639  stereo_mode != 10 && stereo_mode != 12) {
640  int ret = ff_mkv_stereo3d_conv(st, stereo_mode);
641  if (ret < 0)
642  return ret;
643  }
644  }
645 
646  for (i = 0; i < st->nb_side_data; i++) {
647  AVPacketSideData sd = st->side_data[i];
648  if (sd.type == AV_PKT_DATA_STEREO3D) {
649  AVStereo3D *stereo = (AVStereo3D *)sd.data;
650 
651  switch (stereo->type) {
652  case AV_STEREO3D_2D:
654  break;
656  format = (stereo->flags & AV_STEREO3D_FLAG_INVERT)
659  break;
662  if (stereo->flags & AV_STEREO3D_FLAG_INVERT)
663  format--;
664  break;
667  if (stereo->flags & AV_STEREO3D_FLAG_INVERT)
668  format--;
669  break;
670  case AV_STEREO3D_LINES:
672  if (stereo->flags & AV_STEREO3D_FLAG_INVERT)
673  format--;
674  break;
675  case AV_STEREO3D_COLUMNS:
677  if (stereo->flags & AV_STEREO3D_FLAG_INVERT)
678  format--;
679  break;
682  if (stereo->flags & AV_STEREO3D_FLAG_INVERT)
683  format++;
684  break;
685  }
686 
687  break;
688  }
689  }
690 
691  if (mode == MODE_WEBM &&
695 
698 
699  return 0;
700 }
701 
703  int i, AVIOContext *pb)
704 {
705  AVStream *st = s->streams[i];
706  AVCodecContext *codec = st->codec;
707  ebml_master subinfo, track;
708  int native_id = 0;
709  int qt_id = 0;
710  int bit_depth = av_get_bits_per_sample(codec->codec_id);
711  int sample_rate = codec->sample_rate;
712  int output_sample_rate = 0;
713  int j, ret;
715 
716  // ms precision is the de-facto standard timescale for mkv files
717  avpriv_set_pts_info(st, 64, 1, 1000);
718 
719  if (codec->codec_type == AVMEDIA_TYPE_ATTACHMENT) {
720  mkv->have_attachments = 1;
721  return 0;
722  }
723 
724  if (!bit_depth)
725  bit_depth = av_get_bytes_per_sample(codec->sample_fmt) << 3;
726 
727  if (codec->codec_id == AV_CODEC_ID_AAC)
728  get_aac_sample_rates(s, codec, &sample_rate, &output_sample_rate);
729 
732  put_ebml_uint (pb, MATROSKA_ID_TRACKUID , i + 1);
733  put_ebml_uint (pb, MATROSKA_ID_TRACKFLAGLACING , 0); // no lacing (yet)
734 
735  if ((tag = av_dict_get(st->metadata, "title", NULL, 0)))
737  tag = av_dict_get(st->metadata, "language", NULL, 0);
738  put_ebml_string(pb, MATROSKA_ID_TRACKLANGUAGE, tag ? tag->value:"und");
739 
740  // The default value for TRACKFLAGDEFAULT is 1, so add element
741  // if we need to clear it.
742  if (!(st->disposition & AV_DISPOSITION_DEFAULT))
744 
745  if (codec->codec_type == AVMEDIA_TYPE_AUDIO && codec->delay) {
746  mkv->tracks[i].ts_offset = av_rescale_q(codec->delay,
747  (AVRational){ 1, codec->sample_rate },
748  st->time_base);
749 
751  av_rescale_q(codec->delay, (AVRational){ 1, codec->sample_rate },
752  (AVRational){ 1, 1000000000 }));
753  }
754 
755  // look for a codec ID string specific to mkv to use,
756  // if none are found, use AVI codes
757  for (j = 0; ff_mkv_codec_tags[j].id != AV_CODEC_ID_NONE; j++) {
758  if (ff_mkv_codec_tags[j].id == codec->codec_id) {
760  native_id = 1;
761  break;
762  }
763  }
764 
765  if (mkv->mode == MODE_WEBM && !(codec->codec_id == AV_CODEC_ID_VP8 ||
766  codec->codec_id == AV_CODEC_ID_VP9 ||
767  codec->codec_id == AV_CODEC_ID_OPUS ||
768  codec->codec_id == AV_CODEC_ID_VORBIS)) {
769  av_log(s, AV_LOG_ERROR,
770  "Only VP8 or VP9 video and Vorbis or Opus audio are supported for WebM.\n");
771  return AVERROR(EINVAL);
772  }
773 
774  switch (codec->codec_type) {
775  case AVMEDIA_TYPE_VIDEO:
777  if (st->avg_frame_rate.num > 0 && st->avg_frame_rate.den > 0)
779 
780  if (!native_id &&
783  codec->codec_id == AV_CODEC_ID_SVQ1 ||
784  codec->codec_id == AV_CODEC_ID_SVQ3 ||
785  codec->codec_id == AV_CODEC_ID_CINEPAK))
786  qt_id = 1;
787 
788  if (qt_id)
789  put_ebml_string(pb, MATROSKA_ID_CODECID, "V_QUICKTIME");
790  else if (!native_id) {
791  // if there is no mkv-specific codec ID, use VFW mode
792  put_ebml_string(pb, MATROSKA_ID_CODECID, "V_MS/VFW/FOURCC");
793  mkv->tracks[i].write_dts = 1;
794  }
795 
796  subinfo = start_ebml_master(pb, MATROSKA_ID_TRACKVIDEO, 0);
797  // XXX: interlace flag?
800 
801  // check both side data and metadata for stereo information,
802  // write the result to the bitstream if any is found
803  ret = mkv_write_stereo_mode(s, pb, st, mkv->mode);
804  if (ret < 0)
805  return ret;
806 
807  if (st->sample_aspect_ratio.num) {
808  int d_width = codec->width*av_q2d(st->sample_aspect_ratio);
812  }
813  end_ebml_master(pb, subinfo);
814  break;
815 
816  case AVMEDIA_TYPE_AUDIO:
818 
819  if (!native_id)
820  // no mkv-specific ID, use ACM mode
821  put_ebml_string(pb, MATROSKA_ID_CODECID, "A_MS/ACM");
822 
823  subinfo = start_ebml_master(pb, MATROSKA_ID_TRACKAUDIO, 0);
826  if (output_sample_rate)
827  put_ebml_float(pb, MATROSKA_ID_AUDIOOUTSAMPLINGFREQ, output_sample_rate);
828  if (bit_depth)
830  end_ebml_master(pb, subinfo);
831  break;
832 
835  if (!native_id) {
836  av_log(s, AV_LOG_ERROR, "Subtitle codec %d is not supported.\n", codec->codec_id);
837  return AVERROR(ENOSYS);
838  }
839  break;
840  default:
841  av_log(s, AV_LOG_ERROR, "Only audio, video, and subtitles are supported for Matroska.\n");
842  break;
843  }
844  ret = mkv_write_codecprivate(s, pb, codec, native_id, qt_id);
845  if (ret < 0)
846  return ret;
847 
848  end_ebml_master(pb, track);
849 
850  return 0;
851 }
852 
854 {
855  MatroskaMuxContext *mkv = s->priv_data;
856  AVIOContext *pb = s->pb;
857  ebml_master tracks;
858  int i, ret;
859 
861  if (ret < 0)
862  return ret;
863 
864  tracks = start_ebml_master(pb, MATROSKA_ID_TRACKS, 0);
865  for (i = 0; i < s->nb_streams; i++) {
866  ret = mkv_write_track(s, mkv, i, pb);
867  if (ret < 0)
868  return ret;
869  }
870  end_ebml_master(pb, tracks);
871  return 0;
872 }
873 
875 {
876  MatroskaMuxContext *mkv = s->priv_data;
877  AVIOContext *pb = s->pb;
878  ebml_master chapters, editionentry;
879  AVRational scale = {1, 1E9};
880  int i, ret;
881 
882  if (!s->nb_chapters || mkv->wrote_chapters)
883  return 0;
884 
886  if (ret < 0) return ret;
887 
888  chapters = start_ebml_master(pb, MATROSKA_ID_CHAPTERS , 0);
889  editionentry = start_ebml_master(pb, MATROSKA_ID_EDITIONENTRY, 0);
892  for (i = 0; i < s->nb_chapters; i++) {
893  ebml_master chapteratom, chapterdisplay;
894  AVChapter *c = s->chapters[i];
895  AVDictionaryEntry *t = NULL;
896 
897  chapteratom = start_ebml_master(pb, MATROSKA_ID_CHAPTERATOM, 0);
900  av_rescale_q(c->start, c->time_base, scale));
902  av_rescale_q(c->end, c->time_base, scale));
905  if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
906  chapterdisplay = start_ebml_master(pb, MATROSKA_ID_CHAPTERDISPLAY, 0);
909  end_ebml_master(pb, chapterdisplay);
910  }
911  end_ebml_master(pb, chapteratom);
912  }
913  end_ebml_master(pb, editionentry);
914  end_ebml_master(pb, chapters);
915 
916  mkv->wrote_chapters = 1;
917  return 0;
918 }
919 
921 {
922  uint8_t *key = av_strdup(t->key);
923  uint8_t *p = key;
924  const uint8_t *lang = NULL;
926 
927  if ((p = strrchr(p, '-')) &&
928  (lang = av_convert_lang_to(p + 1, AV_LANG_ISO639_2_BIBL)))
929  *p = 0;
930 
931  p = key;
932  while (*p) {
933  if (*p == ' ')
934  *p = '_';
935  else if (*p >= 'a' && *p <= 'z')
936  *p -= 'a' - 'A';
937  p++;
938  }
939 
942  if (lang)
945  end_ebml_master(pb, tag);
946 
947  av_freep(&key);
948 }
949 
950 static int mkv_write_tag(AVFormatContext *s, AVDictionary *m, unsigned int elementid,
951  unsigned int uid, ebml_master *tags)
952 {
953  MatroskaMuxContext *mkv = s->priv_data;
954  ebml_master tag, targets;
955  AVDictionaryEntry *t = NULL;
956  int ret;
957 
958  if (!tags->pos) {
960  if (ret < 0) return ret;
961 
962  *tags = start_ebml_master(s->pb, MATROSKA_ID_TAGS, 0);
963  }
964 
965  tag = start_ebml_master(s->pb, MATROSKA_ID_TAG, 0);
966  targets = start_ebml_master(s->pb, MATROSKA_ID_TAGTARGETS, 0);
967  if (elementid)
968  put_ebml_uint(s->pb, elementid, uid);
969  end_ebml_master(s->pb, targets);
970 
971  while ((t = av_dict_get(m, "", t, AV_DICT_IGNORE_SUFFIX)))
972  if (av_strcasecmp(t->key, "title") &&
973  av_strcasecmp(t->key, "encoding_tool"))
974  mkv_write_simpletag(s->pb, t);
975 
976  end_ebml_master(s->pb, tag);
977  return 0;
978 }
979 
981 {
982  ebml_master tags = {0};
983  int i, ret;
984 
986 
988  ret = mkv_write_tag(s, s->metadata, 0, 0, &tags);
989  if (ret < 0) return ret;
990  }
991 
992  for (i = 0; i < s->nb_streams; i++) {
993  AVStream *st = s->streams[i];
994 
995  if (!av_dict_get(st->metadata, "", 0, AV_DICT_IGNORE_SUFFIX))
996  continue;
997 
998  ret = mkv_write_tag(s, st->metadata, MATROSKA_ID_TAGTARGETS_TRACKUID, i + 1, &tags);
999  if (ret < 0) return ret;
1000  }
1001 
1002  for (i = 0; i < s->nb_chapters; i++) {
1003  AVChapter *ch = s->chapters[i];
1004 
1006  continue;
1007 
1008  ret = mkv_write_tag(s, ch->metadata, MATROSKA_ID_TAGTARGETS_CHAPTERUID, ch->id, &tags);
1009  if (ret < 0) return ret;
1010  }
1011 
1012  if (tags.pos)
1013  end_ebml_master(s->pb, tags);
1014  return 0;
1015 }
1016 
1018 {
1019  MatroskaMuxContext *mkv = s->priv_data;
1020  AVIOContext *pb = s->pb;
1021  ebml_master attachments;
1022  AVLFG c;
1023  int i, ret;
1024 
1025  if (!mkv->have_attachments)
1026  return 0;
1027 
1029 
1031  if (ret < 0) return ret;
1032 
1033  attachments = start_ebml_master(pb, MATROSKA_ID_ATTACHMENTS, 0);
1034 
1035  for (i = 0; i < s->nb_streams; i++) {
1036  AVStream *st = s->streams[i];
1037  ebml_master attached_file;
1038  AVDictionaryEntry *t;
1039  const char *mimetype = NULL;
1040 
1042  continue;
1043 
1044  attached_file = start_ebml_master(pb, MATROSKA_ID_ATTACHEDFILE, 0);
1045 
1046  if (t = av_dict_get(st->metadata, "title", NULL, 0))
1048  if (!(t = av_dict_get(st->metadata, "filename", NULL, 0))) {
1049  av_log(s, AV_LOG_ERROR, "Attachment stream %d has no filename tag.\n", i);
1050  return AVERROR(EINVAL);
1051  }
1053  if (t = av_dict_get(st->metadata, "mimetype", NULL, 0))
1054  mimetype = t->value;
1055  else if (st->codec->codec_id != AV_CODEC_ID_NONE ) {
1056  int i;
1057  for (i = 0; ff_mkv_mime_tags[i].id != AV_CODEC_ID_NONE; i++)
1058  if (ff_mkv_mime_tags[i].id == st->codec->codec_id) {
1059  mimetype = ff_mkv_mime_tags[i].str;
1060  break;
1061  }
1062  }
1063  if (!mimetype) {
1064  av_log(s, AV_LOG_ERROR, "Attachment stream %d has no mimetype tag and "
1065  "it cannot be deduced from the codec id.\n", i);
1066  return AVERROR(EINVAL);
1067  }
1068 
1072  end_ebml_master(pb, attached_file);
1073  }
1074  end_ebml_master(pb, attachments);
1075 
1076  return 0;
1077 }
1078 
1080 {
1081  MatroskaMuxContext *mkv = s->priv_data;
1082  AVIOContext *pb = s->pb;
1083  ebml_master ebml_header, segment_info;
1085  int ret, i;
1086 
1087  if (!strcmp(s->oformat->name, "webm"))
1088  mkv->mode = MODE_WEBM;
1089  else
1090  mkv->mode = MODE_MATROSKAv2;
1091 
1092  mkv->tracks = av_mallocz(s->nb_streams * sizeof(*mkv->tracks));
1093  if (!mkv->tracks)
1094  return AVERROR(ENOMEM);
1095 
1096  ebml_header = start_ebml_master(pb, EBML_ID_HEADER, 0);
1104  end_ebml_master(pb, ebml_header);
1105 
1107  mkv->segment_offset = avio_tell(pb);
1108 
1109  // we write 2 seek heads - one at the end of the file to point to each
1110  // cluster, and one at the beginning to point to all other level one
1111  // elements (including the seek head at the end of the file), which
1112  // isn't more than 10 elements if we only write one of each other
1113  // currently defined level 1 element
1114  mkv->main_seekhead = mkv_start_seekhead(pb, mkv->segment_offset, 10);
1115  if (!mkv->main_seekhead)
1116  return AVERROR(ENOMEM);
1117 
1119  if (ret < 0) return ret;
1120 
1121  segment_info = start_ebml_master(pb, MATROSKA_ID_INFO, 0);
1123  if ((tag = av_dict_get(s->metadata, "title", NULL, 0)))
1125  if (!(s->flags & AVFMT_FLAG_BITEXACT)) {
1126  uint32_t segment_uid[4];
1127  AVLFG lfg;
1128 
1130 
1131  for (i = 0; i < 4; i++)
1132  segment_uid[i] = av_lfg_get(&lfg);
1133 
1135  if ((tag = av_dict_get(s->metadata, "encoding_tool", NULL, 0)))
1137  else
1139  put_ebml_binary(pb, MATROSKA_ID_SEGMENTUID, segment_uid, 16);
1140  }
1141 
1142  // reserve space for the duration
1143  mkv->duration = 0;
1144  mkv->duration_offset = avio_tell(pb);
1145  put_ebml_void(pb, 11); // assumes double-precision float to be written
1146  end_ebml_master(pb, segment_info);
1147 
1148  ret = mkv_write_tracks(s);
1149  if (ret < 0)
1150  return ret;
1151 
1152  if (mkv->mode != MODE_WEBM) {
1153  ret = mkv_write_chapters(s);
1154  if (ret < 0)
1155  return ret;
1156 
1157  ret = mkv_write_tags(s);
1158  if (ret < 0)
1159  return ret;
1160 
1161  ret = mkv_write_attachments(s);
1162  if (ret < 0)
1163  return ret;
1164  }
1165 
1166  if (!s->pb->seekable)
1168 
1169  mkv->cues = mkv_start_cues(mkv->segment_offset);
1170  if (!mkv->cues)
1171  return AVERROR(ENOMEM);
1172 
1173  if (pb->seekable && mkv->reserve_cues_space) {
1174  mkv->cues_pos = avio_tell(pb);
1176  }
1177 
1179  mkv->cur_audio_pkt.size = 0;
1180 
1181  avio_flush(pb);
1182 
1183  // start a new cluster every 5 MB or 5 sec, or 32k / 1 sec for streaming or
1184  // after 4k and on a keyframe
1185  if (pb->seekable) {
1186  if (mkv->cluster_time_limit < 0)
1187  mkv->cluster_time_limit = 5000;
1188  if (mkv->cluster_size_limit < 0)
1189  mkv->cluster_size_limit = 5 * 1024 * 1024;
1190  } else {
1191  if (mkv->cluster_time_limit < 0)
1192  mkv->cluster_time_limit = 1000;
1193  if (mkv->cluster_size_limit < 0)
1194  mkv->cluster_size_limit = 32 * 1024;
1195  }
1196 
1197  return 0;
1198 }
1199 
1200 static int mkv_blockgroup_size(int pkt_size)
1201 {
1202  int size = pkt_size + 4;
1203  size += ebml_num_size(size);
1204  size += 2; // EBML ID for block and block duration
1205  size += 8; // max size of block duration
1206  size += ebml_num_size(size);
1207  size += 1; // blockgroup EBML ID
1208  return size;
1209 }
1210 
1211 static int ass_get_duration(const uint8_t *p)
1212 {
1213  int sh, sm, ss, sc, eh, em, es, ec;
1214  uint64_t start, end;
1215 
1216  if (sscanf(p, "%*[^,],%d:%d:%d%*c%d,%d:%d:%d%*c%d",
1217  &sh, &sm, &ss, &sc, &eh, &em, &es, &ec) != 8)
1218  return 0;
1219  start = 3600000 * sh + 60000 * sm + 1000 * ss + 10 * sc;
1220  end = 3600000 * eh + 60000 * em + 1000 * es + 10 * ec;
1221  return end - start;
1222 }
1223 
1225  AVPacket *pkt)
1226 {
1227  MatroskaMuxContext *mkv = s->priv_data;
1228  int i, layer = 0, max_duration = 0, size, line_size, data_size = pkt->size;
1229  uint8_t *start, *end, *data = pkt->data;
1230  ebml_master blockgroup;
1231  char buffer[2048];
1232 
1233  while (data_size) {
1234  int duration = ass_get_duration(data);
1235  max_duration = FFMAX(duration, max_duration);
1236  end = memchr(data, '\n', data_size);
1237  size = line_size = end ? end - data + 1 : data_size;
1238  size -= end ? (end[-1] == '\r') + 1 : 0;
1239  start = data;
1240  for (i = 0; i < 3; i++, start++)
1241  if (!(start = memchr(start, ',', size - (start - data))))
1242  return max_duration;
1243  size -= start - data;
1244  sscanf(data, "Dialogue: %d,", &layer);
1245  i = snprintf(buffer, sizeof(buffer), "%" PRId64 ",%d,",
1246  s->streams[pkt->stream_index]->nb_frames, layer);
1247  size = FFMIN(i + size, sizeof(buffer));
1248  memcpy(buffer + i, start, size - i);
1249 
1250  av_log(s, AV_LOG_DEBUG,
1251  "Writing block at offset %" PRIu64 ", size %d, "
1252  "pts %" PRId64 ", duration %d\n",
1253  avio_tell(pb), size, pkt->pts, duration);
1254  blockgroup = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP,
1257  put_ebml_num(pb, size + 4, 0);
1258  // this assumes stream_index is less than 126
1259  avio_w8(pb, 0x80 | (pkt->stream_index + 1));
1260  avio_wb16(pb, pkt->pts - mkv->cluster_pts);
1261  avio_w8(pb, 0);
1262  avio_write(pb, buffer, size);
1264  end_ebml_master(pb, blockgroup);
1265 
1266  data += line_size;
1267  data_size -= line_size;
1268  }
1269 
1270  return max_duration;
1271 }
1272 
1273 static int mkv_strip_wavpack(const uint8_t *src, uint8_t **pdst, int *size)
1274 {
1275  uint8_t *dst;
1276  int srclen = *size;
1277  int offset = 0;
1278  int ret;
1279 
1280  dst = av_malloc(srclen);
1281  if (!dst)
1282  return AVERROR(ENOMEM);
1283 
1284  while (srclen >= WV_HEADER_SIZE) {
1285  WvHeader header;
1286 
1287  ret = ff_wv_parse_header(&header, src);
1288  if (ret < 0)
1289  goto fail;
1290  src += WV_HEADER_SIZE;
1291  srclen -= WV_HEADER_SIZE;
1292 
1293  if (srclen < header.blocksize) {
1294  ret = AVERROR_INVALIDDATA;
1295  goto fail;
1296  }
1297 
1298  if (header.initial) {
1299  AV_WL32(dst + offset, header.samples);
1300  offset += 4;
1301  }
1302  AV_WL32(dst + offset, header.flags);
1303  AV_WL32(dst + offset + 4, header.crc);
1304  offset += 8;
1305 
1306  if (!(header.initial && header.final)) {
1307  AV_WL32(dst + offset, header.blocksize);
1308  offset += 4;
1309  }
1310 
1311  memcpy(dst + offset, src, header.blocksize);
1312  src += header.blocksize;
1313  srclen -= header.blocksize;
1314  offset += header.blocksize;
1315  }
1316 
1317  *pdst = dst;
1318  *size = offset;
1319 
1320  return 0;
1321 fail:
1322  av_freep(&dst);
1323  return ret;
1324 }
1325 
1327  unsigned int blockid, AVPacket *pkt, int flags)
1328 {
1329  MatroskaMuxContext *mkv = s->priv_data;
1330  AVCodecContext *codec = s->streams[pkt->stream_index]->codec;
1331  uint8_t *data = NULL;
1332  int offset = 0, size = pkt->size;
1333  int64_t ts = mkv->tracks[pkt->stream_index].write_dts ? pkt->dts : pkt->pts;
1334 
1335  av_log(s, AV_LOG_DEBUG, "Writing block at offset %" PRIu64 ", size %d, "
1336  "pts %" PRId64 ", dts %" PRId64 ", duration %d, flags %d\n",
1337  avio_tell(pb), pkt->size, pkt->pts, pkt->dts, pkt->duration, flags);
1338  if (codec->codec_id == AV_CODEC_ID_H264 && codec->extradata_size > 0 &&
1339  (AV_RB24(codec->extradata) == 1 || AV_RB32(codec->extradata) == 1))
1340  ff_avc_parse_nal_units_buf(pkt->data, &data, &size);
1341  else if (codec->codec_id == AV_CODEC_ID_HEVC && codec->extradata_size > 6 &&
1342  (AV_RB24(codec->extradata) == 1 || AV_RB32(codec->extradata) == 1))
1343  /* extradata is Annex B, assume the bitstream is too and convert it */
1344  ff_hevc_annexb2mp4_buf(pkt->data, &data, &size, 0, NULL);
1345  else if (codec->codec_id == AV_CODEC_ID_WAVPACK) {
1346  int ret = mkv_strip_wavpack(pkt->data, &data, &size);
1347  if (ret < 0) {
1348  av_log(s, AV_LOG_ERROR, "Error stripping a WavPack packet.\n");
1349  return;
1350  }
1351  } else
1352  data = pkt->data;
1353 
1354  if (codec->codec_id == AV_CODEC_ID_PRORES) {
1355  /* Matroska specification requires to remove the first QuickTime atom
1356  */
1357  size -= 8;
1358  offset = 8;
1359  }
1360 
1361  put_ebml_id(pb, blockid);
1362  put_ebml_num(pb, size + 4, 0);
1363  // this assumes stream_index is less than 126
1364  avio_w8(pb, 0x80 | (pkt->stream_index + 1));
1365  avio_wb16(pb, ts - mkv->cluster_pts);
1366  avio_w8(pb, flags);
1367  avio_write(pb, data + offset, size);
1368  if (data != pkt->data)
1369  av_free(data);
1370 }
1371 
1372 static int srt_get_duration(uint8_t **buf)
1373 {
1374  int i, duration = 0;
1375 
1376  for (i = 0; i < 2 && !duration; i++) {
1377  int s_hour, s_min, s_sec, s_hsec, e_hour, e_min, e_sec, e_hsec;
1378  if (sscanf(*buf, "%d:%2d:%2d%*1[,.]%3d --> %d:%2d:%2d%*1[,.]%3d",
1379  &s_hour, &s_min, &s_sec, &s_hsec,
1380  &e_hour, &e_min, &e_sec, &e_hsec) == 8) {
1381  s_min += 60 * s_hour;
1382  e_min += 60 * e_hour;
1383  s_sec += 60 * s_min;
1384 
1385  e_sec += 60 * e_min;
1386  s_hsec += 1000 * s_sec;
1387  e_hsec += 1000 * e_sec;
1388 
1389  duration = e_hsec - s_hsec;
1390  }
1391  *buf += strcspn(*buf, "\n") + 1;
1392  }
1393  return duration;
1394 }
1395 
1397  AVPacket *pkt)
1398 {
1399  ebml_master blockgroup;
1400  AVPacket pkt2 = *pkt;
1401  int64_t duration = srt_get_duration(&pkt2.data);
1402  pkt2.size -= pkt2.data - pkt->data;
1403 
1404  blockgroup = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP,
1405  mkv_blockgroup_size(pkt2.size));
1406  mkv_write_block(s, pb, MATROSKA_ID_BLOCK, &pkt2, 0);
1408  end_ebml_master(pb, blockgroup);
1409 
1410  return duration;
1411 }
1412 
1414 {
1415  MatroskaMuxContext *mkv = s->priv_data;
1416  int bufsize;
1417  uint8_t *dyn_buf;
1418 
1419  if (!mkv->dyn_bc)
1420  return;
1421 
1422  bufsize = avio_close_dyn_buf(mkv->dyn_bc, &dyn_buf);
1423  avio_write(s->pb, dyn_buf, bufsize);
1424  av_free(dyn_buf);
1425  mkv->dyn_bc = NULL;
1426 }
1427 
1429 {
1430  MatroskaMuxContext *mkv = s->priv_data;
1431  AVIOContext *pb = s->pb;
1432  AVCodecContext *codec = s->streams[pkt->stream_index]->codec;
1433  int keyframe = !!(pkt->flags & AV_PKT_FLAG_KEY);
1434  int duration = pkt->duration;
1435  int ret;
1436  int64_t ts = mkv->tracks[pkt->stream_index].write_dts ? pkt->dts : pkt->pts;
1437 
1438  if (ts == AV_NOPTS_VALUE) {
1439  av_log(s, AV_LOG_ERROR, "Can't write packet with unknown timestamp\n");
1440  return AVERROR(EINVAL);
1441  }
1442  ts += mkv->tracks[pkt->stream_index].ts_offset;
1443 
1444  if (!s->pb->seekable) {
1445  if (!mkv->dyn_bc)
1446  avio_open_dyn_buf(&mkv->dyn_bc);
1447  pb = mkv->dyn_bc;
1448  }
1449 
1450  if (!mkv->cluster_pos) {
1451  mkv->cluster_pos = avio_tell(s->pb);
1454  mkv->cluster_pts = FFMAX(0, ts);
1455  }
1456 
1457  if (codec->codec_type != AVMEDIA_TYPE_SUBTITLE) {
1458  mkv_write_block(s, pb, MATROSKA_ID_SIMPLEBLOCK, pkt, keyframe << 7);
1459  } else if (codec->codec_id == AV_CODEC_ID_SSA) {
1460  duration = mkv_write_ass_blocks(s, pb, pkt);
1461  } else if (codec->codec_id == AV_CODEC_ID_SRT) {
1462  duration = mkv_write_srt_blocks(s, pb, pkt);
1463  } else {
1465  mkv_blockgroup_size(pkt->size));
1466  duration = pkt->convergence_duration;
1467  mkv_write_block(s, pb, MATROSKA_ID_BLOCK, pkt, 0);
1469  end_ebml_master(pb, blockgroup);
1470  }
1471 
1472  if (codec->codec_type == AVMEDIA_TYPE_VIDEO && keyframe) {
1473  ret = mkv_add_cuepoint(mkv->cues, pkt->stream_index, ts,
1474  mkv->cluster_pos);
1475  if (ret < 0)
1476  return ret;
1477  }
1478 
1479  mkv->duration = FFMAX(mkv->duration, ts + duration);
1480  return 0;
1481 }
1482 
1484 {
1485  MatroskaMuxContext *mkv = s->priv_data;
1486  int codec_type = s->streams[pkt->stream_index]->codec->codec_type;
1487  int keyframe = !!(pkt->flags & AV_PKT_FLAG_KEY);
1488  int cluster_size;
1489  int64_t cluster_time;
1490  AVIOContext *pb;
1491  int ret;
1492 
1493  if (mkv->tracks[pkt->stream_index].write_dts)
1494  cluster_time = pkt->dts - mkv->cluster_pts;
1495  else
1496  cluster_time = pkt->pts - mkv->cluster_pts;
1497  cluster_time += mkv->tracks[pkt->stream_index].ts_offset;
1498 
1499  // start a new cluster every 5 MB or 5 sec, or 32k / 1 sec for streaming or
1500  // after 4k and on a keyframe
1501  if (s->pb->seekable) {
1502  pb = s->pb;
1503  cluster_size = avio_tell(pb) - mkv->cluster_pos;
1504  } else {
1505  pb = mkv->dyn_bc;
1506  cluster_size = avio_tell(pb);
1507  }
1508 
1509  if (mkv->cluster_pos &&
1510  (cluster_size > mkv->cluster_size_limit ||
1511  cluster_time > mkv->cluster_time_limit ||
1512  (codec_type == AVMEDIA_TYPE_VIDEO && keyframe &&
1513  cluster_size > 4 * 1024))) {
1514  av_log(s, AV_LOG_DEBUG,
1515  "Starting new cluster at offset %" PRIu64 " bytes, "
1516  "pts %" PRIu64 "dts %" PRIu64 "\n",
1517  avio_tell(pb), pkt->pts, pkt->dts);
1518  end_ebml_master(pb, mkv->cluster);
1519  mkv->cluster_pos = 0;
1520  if (mkv->dyn_bc)
1521  mkv_flush_dynbuf(s);
1522  avio_flush(s->pb);
1523  }
1524 
1525  // check if we have an audio packet cached
1526  if (mkv->cur_audio_pkt.size > 0) {
1527  ret = mkv_write_packet_internal(s, &mkv->cur_audio_pkt);
1529  if (ret < 0) {
1530  av_log(s, AV_LOG_ERROR,
1531  "Could not write cached audio packet ret:%d\n", ret);
1532  return ret;
1533  }
1534  }
1535 
1536  // buffer an audio packet to ensure the packet containing the video
1537  // keyframe's timecode is contained in the same cluster for WebM
1538  if (codec_type == AVMEDIA_TYPE_AUDIO) {
1539  mkv->cur_audio_pkt = *pkt;
1540  if (pkt->buf) {
1541  mkv->cur_audio_pkt.buf = av_buffer_ref(pkt->buf);
1542  ret = mkv->cur_audio_pkt.buf ? 0 : AVERROR(ENOMEM);
1543  } else
1544  ret = av_dup_packet(&mkv->cur_audio_pkt);
1545  } else
1546  ret = mkv_write_packet_internal(s, pkt);
1547  return ret;
1548 }
1549 
1551 {
1552  MatroskaMuxContext *mkv = s->priv_data;
1553  AVIOContext *pb;
1554  if (s->pb->seekable)
1555  pb = s->pb;
1556  else
1557  pb = mkv->dyn_bc;
1558  if (!pkt) {
1559  if (mkv->cluster_pos) {
1560  av_log(s, AV_LOG_DEBUG,
1561  "Flushing cluster at offset %" PRIu64 " bytes\n",
1562  avio_tell(pb));
1563  end_ebml_master(pb, mkv->cluster);
1564  mkv->cluster_pos = 0;
1565  if (mkv->dyn_bc)
1566  mkv_flush_dynbuf(s);
1567  avio_flush(s->pb);
1568  }
1569  return 0;
1570  }
1571  return mkv_write_packet(s, pkt);
1572 }
1573 
1575 {
1576  MatroskaMuxContext *mkv = s->priv_data;
1577  AVIOContext *pb = s->pb;
1578  int64_t currentpos, cuespos;
1579  int ret;
1580 
1581  // check if we have an audio packet cached
1582  if (mkv->cur_audio_pkt.size > 0) {
1583  ret = mkv_write_packet_internal(s, &mkv->cur_audio_pkt);
1585  if (ret < 0) {
1586  av_log(s, AV_LOG_ERROR,
1587  "Could not write cached audio packet ret:%d\n", ret);
1588  return ret;
1589  }
1590  }
1591 
1592  if (mkv->dyn_bc) {
1593  end_ebml_master(mkv->dyn_bc, mkv->cluster);
1594  mkv_flush_dynbuf(s);
1595  } else if (mkv->cluster_pos) {
1596  end_ebml_master(pb, mkv->cluster);
1597  }
1598 
1599  if (mkv->mode != MODE_WEBM) {
1600  ret = mkv_write_chapters(s);
1601  if (ret < 0)
1602  return ret;
1603  }
1604 
1605  if (pb->seekable) {
1606  if (mkv->cues->num_entries) {
1607  if (mkv->reserve_cues_space) {
1608  int64_t cues_end;
1609 
1610  currentpos = avio_tell(pb);
1611  avio_seek(pb, mkv->cues_pos, SEEK_SET);
1612 
1613  cuespos = mkv_write_cues(pb, mkv->cues, s->nb_streams);
1614  cues_end = avio_tell(pb);
1615  if (cues_end > cuespos + mkv->reserve_cues_space) {
1616  av_log(s, AV_LOG_ERROR,
1617  "Insufficient space reserved for cues: %d "
1618  "(needed: %" PRId64 ").\n",
1619  mkv->reserve_cues_space, cues_end - cuespos);
1620  return AVERROR(EINVAL);
1621  }
1622 
1623  if (cues_end < cuespos + mkv->reserve_cues_space)
1625  (cues_end - cuespos));
1626 
1627  avio_seek(pb, currentpos, SEEK_SET);
1628  } else {
1629  cuespos = mkv_write_cues(pb, mkv->cues, s->nb_streams);
1630  }
1631 
1633  cuespos);
1634  if (ret < 0)
1635  return ret;
1636  }
1637 
1639 
1640  // update the duration
1641  av_log(s, AV_LOG_DEBUG, "end duration = %" PRIu64 "\n", mkv->duration);
1642  currentpos = avio_tell(pb);
1643  avio_seek(pb, mkv->duration_offset, SEEK_SET);
1645 
1646  avio_seek(pb, currentpos, SEEK_SET);
1647  }
1648 
1649  end_ebml_master(pb, mkv->segment);
1650  av_free(mkv->tracks);
1651  av_freep(&mkv->cues->entries);
1652  av_freep(&mkv->cues);
1653 
1654  return 0;
1655 }
1656 
1657 static int mkv_query_codec(enum AVCodecID codec_id, int std_compliance)
1658 {
1659  int i;
1660  for (i = 0; ff_mkv_codec_tags[i].id != AV_CODEC_ID_NONE; i++)
1661  if (ff_mkv_codec_tags[i].id == codec_id)
1662  return 1;
1663 
1664  if (std_compliance < FF_COMPLIANCE_NORMAL) {
1665  enum AVMediaType type = avcodec_get_type(codec_id);
1666  // mkv theoretically supports any video/audio through VFW/ACM
1667  if (type == AVMEDIA_TYPE_VIDEO || type == AVMEDIA_TYPE_AUDIO)
1668  return 1;
1669  }
1670 
1671  return 0;
1672 }
1673 
1674 #define OFFSET(x) offsetof(MatroskaMuxContext, x)
1675 #define FLAGS AV_OPT_FLAG_ENCODING_PARAM
1676 static const AVOption options[] = {
1677  { "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 },
1678  { "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 },
1679  { "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 },
1680  { NULL },
1681 };
1682 
1683 #if CONFIG_MATROSKA_MUXER
1684 static const AVClass matroska_class = {
1685  .class_name = "matroska muxer",
1686  .item_name = av_default_item_name,
1687  .option = options,
1688  .version = LIBAVUTIL_VERSION_INT,
1689 };
1690 
1691 AVOutputFormat ff_matroska_muxer = {
1692  .name = "matroska",
1693  .long_name = NULL_IF_CONFIG_SMALL("Matroska"),
1694  .mime_type = "video/x-matroska",
1695  .extensions = "mkv",
1696  .priv_data_size = sizeof(MatroskaMuxContext),
1697  .audio_codec = CONFIG_LIBVORBIS_ENCODER ?
1699  .video_codec = CONFIG_LIBX264_ENCODER ?
1706  .codec_tag = (const AVCodecTag* const []){
1708  },
1709  .subtitle_codec = AV_CODEC_ID_SSA,
1710  .query_codec = mkv_query_codec,
1711  .priv_class = &matroska_class,
1712 };
1713 #endif
1714 
1715 #if CONFIG_WEBM_MUXER
1716 static const AVClass webm_class = {
1717  .class_name = "webm muxer",
1718  .item_name = av_default_item_name,
1719  .option = options,
1720  .version = LIBAVUTIL_VERSION_INT,
1721 };
1722 
1723 AVOutputFormat ff_webm_muxer = {
1724  .name = "webm",
1725  .long_name = NULL_IF_CONFIG_SMALL("WebM"),
1726  .mime_type = "video/webm",
1727  .extensions = "webm",
1728  .priv_data_size = sizeof(MatroskaMuxContext),
1729  .audio_codec = AV_CODEC_ID_VORBIS,
1730  .video_codec = AV_CODEC_ID_VP8,
1736  .priv_class = &webm_class,
1737 };
1738 #endif
1739 
1740 #if CONFIG_MATROSKA_AUDIO_MUXER
1741 static const AVClass mka_class = {
1742  .class_name = "matroska audio muxer",
1743  .item_name = av_default_item_name,
1744  .option = options,
1745  .version = LIBAVUTIL_VERSION_INT,
1746 };
1747 AVOutputFormat ff_matroska_audio_muxer = {
1748  .name = "matroska",
1749  .long_name = NULL_IF_CONFIG_SMALL("Matroska"),
1750  .mime_type = "audio/x-matroska",
1751  .extensions = "mka",
1752  .priv_data_size = sizeof(MatroskaMuxContext),
1753  .audio_codec = CONFIG_LIBVORBIS_ENCODER ?
1754  AV_CODEC_ID_VORBIS : AV_CODEC_ID_AC3,
1755  .video_codec = AV_CODEC_ID_NONE,
1761  .codec_tag = (const AVCodecTag* const []){ ff_codec_wav_tags, 0 },
1762  .priv_class = &mka_class,
1763 };
1764 #endif
unsigned int nb_chapters
Number of chapters in AVChapter array.
Definition: avformat.h:1119
Definition: lfg.h:25
internal header for HEVC (de)muxer utilities
void avio_wb64(AVIOContext *s, uint64_t val)
Definition: aviobuf.c:330
void * av_malloc(size_t size)
Allocate a block of size bytes with alignment suitable for all memory accesses (including vectors if ...
Definition: mem.c:62
#define MATROSKA_ID_TRACKDEFAULTDURATION
Definition: matroska.h:98
void avio_wl16(AVIOContext *s, unsigned int val)
Definition: aviobuf.c:336
static void put_ebml_size_unknown(AVIOContext *pb, int bytes)
Write an EBML size meaning "unknown size".
Definition: matroskaenc.c:145
Bytestream IO Context.
Definition: avio.h:68
#define AVERROR_INVALIDDATA
Invalid data found when processing input.
Definition: error.h:54
void ff_metadata_conv_ctx(AVFormatContext *ctx, const AVMetadataConv *d_conv, const AVMetadataConv *s_conv)
Definition: metadata.c:59
Views are packed per line, as if interlaced.
Definition: stereo3d.h:97
int size
void av_free_packet(AVPacket *pkt)
Free a packet.
Definition: avpacket.c:243
int sizebytes
how many bytes were reserved for the size
Definition: matroskaenc.c:53
uint32_t samples
Definition: wv.h:39
int initial
Definition: wv.h:43
#define MATROSKA_ID_TRACKFLAGLACING
Definition: matroska.h:95
#define MATROSKA_ID_TRACKENTRY
Definition: matroska.h:75
#define MATROSKA_ID_VIDEODISPLAYHEIGHT
Definition: matroska.h:107
int avio_close_dyn_buf(AVIOContext *s, uint8_t **pbuffer)
Return the written size and a pointer to the buffer.
Definition: aviobuf.c:966
AVOption.
Definition: opt.h:234
int64_t cluster_pos
file offset of the cluster containing the block
Definition: matroskaenc.c:73
Views are alternated temporally.
Definition: stereo3d.h:66
static void mkv_write_simpletag(AVIOContext *pb, AVDictionaryEntry *t)
Definition: matroskaenc.c:920
#define MATROSKA_ID_CUETRACKPOSITION
Definition: matroska.h:140
#define MATROSKA_ID_CODECPRIVATE
Definition: matroska.h:84
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition: log.h:129
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:2821
#define MATROSKA_ID_AUDIOBITDEPTH
Definition: matroska.h:124
#define MATROSKA_ID_TRACKFLAGDEFAULT
Definition: matroska.h:93
static int write_packet(AVFormatContext *s, AVPacket *pkt)
Definition: assenc.c:58
This side data should be associated with a video stream and contains Stereoscopic 3D information in f...
Definition: avcodec.h:919
static int mkv_write_attachments(AVFormatContext *s)
Definition: matroskaenc.c:1017
uint64_t pts
Definition: matroskaenc.c:71
AVRational sample_aspect_ratio
sample aspect ratio (0 if unknown)
Definition: avformat.h:769
int num
numerator
Definition: rational.h:44
int size
Definition: avcodec.h:974
int64_t avio_seek(AVIOContext *s, int64_t offset, int whence)
fseek() equivalent for AVIOContext.
Definition: aviobuf.c:186
#define MATROSKA_ID_FILEDATA
Definition: matroska.h:187
#define EBML_ID_DOCTYPEREADVERSION
Definition: matroska.h:42
#define AV_RB24
Definition: intreadwrite.h:64
static int mkv_write_header(AVFormatContext *s)
Definition: matroskaenc.c:1079
#define MATROSKA_ID_TRACKTYPE
Definition: matroska.h:80
enum AVMediaType codec_type
Definition: rtp.c:36
#define MATROSKA_ID_TAGTARGETS_CHAPTERUID
Definition: matroska.h:159
int ff_flac_is_native_layout(uint64_t channel_layout)
static av_always_inline uint64_t av_double2int(double f)
Reinterpret a double as a 64-bit integer.
Definition: intfloat.h:70
#define MATROSKA_ID_MUXINGAPP
Definition: matroska.h:70
int64_t cluster_time_limit
Definition: matroskaenc.c:112
#define MATROSKA_ID_AUDIOCHANNELS
Definition: matroska.h:125
unsigned int ff_codec_get_tag(const AVCodecTag *tags, enum AVCodecID id)
Definition: utils.c:1933
int64_t segment_offset
Definition: matroskaenc.c:77
AVPacketSideData * side_data
An array of side data that applies to the whole stream (i.e.
Definition: avformat.h:807
#define MATROSKA_ID_CUECLUSTERPOSITION
Definition: matroska.h:144
Definition: matroskaenc.c:56
AVDictionary * metadata
Definition: avformat.h:909
int av_dup_packet(AVPacket *pkt)
Definition: avpacket.c:190
mkv_track * tracks
Definition: matroskaenc.c:103
#define AVFMT_ALLOW_FLUSH
Format allows flushing.
Definition: avformat.h:425
#define MATROSKA_ID_EDITIONFLAGDEFAULT
Definition: matroska.h:200
#define MATROSKA_ID_CLUSTERTIMECODE
Definition: matroska.h:170
int avio_open_dyn_buf(AVIOContext **s)
Open a write only memory stream.
Definition: aviobuf.c:954
#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:426
#define MATROSKA_ID_CHAPTERTIMEEND
Definition: matroska.h:194
static int64_t duration
Definition: avplay.c:246
int64_t pos
absolute offset in the file where the master's elements start
Definition: matroskaenc.c:52
MatroskaVideoStereoModeType
Definition: matroska.h:224
int ff_vorbiscomment_write(uint8_t **p, AVDictionary **m, const char *vendor_string)
Write a VorbisComment into a buffer.
Definition: vorbiscomment.c:53
void av_freep(void *arg)
Free a memory block which has been allocated with av_malloc(z)() or av_realloc() and set the pointer ...
Definition: mem.c:198
static int64_t mkv_write_cues(AVIOContext *pb, mkv_cues *cues, int num_tracks)
Definition: matroskaenc.c:409
#define FLAGS
Definition: matroskaenc.c:1675
#define MATROSKA_ID_FILEDESC
Definition: matroska.h:184
Format I/O context.
Definition: avformat.h:922
char str[32]
Definition: internal.h:41
int64_t cluster_pos
file offset of the current cluster
Definition: matroskaenc.c:97
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:38
Public dictionary API.
static int mkv_write_native_codecprivate(AVFormatContext *s, AVCodecContext *codec, AVIOContext *dyn_cp)
Definition: matroskaenc.c:539
#define CONFIG_LIBVORBIS_ENCODER
Definition: config.h:1049
enum AVSampleFormat sample_fmt
audio sample format
Definition: avcodec.h:1799
uint8_t
#define MATROSKA_ID_CHAPLANG
Definition: matroska.h:197
static int srt_get_duration(uint8_t **buf)
Definition: matroskaenc.c:1372
static int mkv_write_tag(AVFormatContext *s, AVDictionary *m, unsigned int elementid, unsigned int uid, ebml_master *tags)
Definition: matroskaenc.c:950
AVOptions.
#define MATROSKA_ID_TRACKLANGUAGE
Definition: matroska.h:91
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:69
static int ebml_id_size(unsigned int id)
Definition: matroskaenc.c:128
uint32_t flags
Definition: wv.h:40
#define AV_RB32
Definition: intreadwrite.h:130
int ff_mkv_stereo3d_conv(AVStream *st, MatroskaVideoStereoModeType stereo_mode)
Definition: matroska.c:109
uint64_t segmentpos
Definition: matroskaenc.c:58
int id
unique ID to identify the chapter
Definition: avformat.h:906
#define MATROSKA_ID_TIMECODESCALE
Definition: matroska.h:66
#define MATROSKA_ID_SIMPLEBLOCK
Definition: matroska.h:174
#define AV_WL32(p, d)
Definition: intreadwrite.h:255
#define MATROSKA_ID_EDITIONFLAGHIDDEN
Definition: matroska.h:199
int nb_side_data
The number of elements in the AVStream.side_data array.
Definition: avformat.h:811
uint8_t * extradata
some codecs need / can use extradata like Huffman tables.
Definition: avcodec.h:1164
static int mkv_write_srt_blocks(AVFormatContext *s, AVIOContext *pb, AVPacket *pkt)
Definition: matroskaenc.c:1396
AVStream ** streams
A list of all streams in the file.
Definition: avformat.h:990
#define MATROSKA_ID_AUDIOOUTSAMPLINGFREQ
Definition: matroska.h:122
const char data[16]
Definition: mxf.c:70
static double av_q2d(AVRational a)
Convert rational to double.
Definition: rational.h:69
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:38
int flags
Flags modifying the (de)muxer behaviour.
Definition: avformat.h:1033
uint8_t * data
Definition: avcodec.h:973
#define MATROSKA_ID_VIDEODISPLAYWIDTH
Definition: matroska.h:106
static int flags
Definition: log.c:44
uint32_t tag
Definition: movenc.c:844
static void get_aac_sample_rates(AVFormatContext *s, AVCodecContext *codec, int *sample_rate, int *output_sample_rate)
Definition: matroskaenc.c:523
static EbmlSyntax ebml_header[]
Definition: matroskadec.c:283
enum AVCodecID id
Definition: internal.h:42
static int put_flac_codecpriv(AVFormatContext *s, AVIOContext *pb, AVCodecContext *codec)
Definition: matroskaenc.c:479
uint8_t * data
Definition: avcodec.h:923
#define MATROSKA_ID_CUES
Definition: matroska.h:58
int ff_vorbiscomment_length(AVDictionary *m, const char *vendor_string)
Calculate the length in bytes of a VorbisComment.
Definition: vorbiscomment.c:40
int64_t ts_offset
Definition: matroskaenc.c:84
static av_always_inline int64_t avio_tell(AVIOContext *s)
ftell() equivalent for AVIOContext.
Definition: avio.h:219
#define MATROSKA_ID_TRACKNUMBER
Definition: matroska.h:78
void avio_write(AVIOContext *s, const unsigned char *buf, int size)
Definition: aviobuf.c:165
Definition: wv.h:34
#define AVFMT_FLAG_BITEXACT
When muxing, try to avoid writing any random/volatile data to the output.
Definition: avformat.h:1050
int duration
Duration of this packet in AVStream->time_base units, 0 if unknown.
Definition: avcodec.h:991
#define MATROSKA_ID_SEGMENTUID
Definition: matroska.h:72
static void put_ebml_num(AVIOContext *pb, uint64_t num, int bytes)
Write a number in EBML variable length format.
Definition: matroskaenc.c:170
static int write_trailer(AVFormatContext *s)
Definition: assenc.c:64
static int mkv_add_seekhead_entry(mkv_seekhead *seekhead, unsigned int elementid, uint64_t filepos)
Definition: matroskaenc.c:306
int64_t segment_offset
the file offset to the beginning of the segment
Definition: matroskaenc.c:63
struct AVOutputFormat * oformat
The output container format.
Definition: avformat.h:941
#define AV_PKT_FLAG_KEY
The packet contains a keyframe.
Definition: avcodec.h:1019
#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:129
ebml_master segment
Definition: matroskaenc.c:94
#define MATROSKA_ID_VIDEOSTEREOMODE
Definition: matroska.h:116
AVPacket cur_audio_pkt
Definition: matroskaenc.c:105
int av_reallocp_array(void *ptr, size_t nmemb, size_t size)
Definition: mem.c:167
AVCodecID
Identify the syntax and semantics of the bitstream.
Definition: avcodec.h:105
static int mkv_write_tags(AVFormatContext *s)
Definition: matroskaenc.c:980
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition: log.h:123
int av_get_bits_per_sample(enum AVCodecID codec_id)
Return codec bits per sample.
Definition: utils.c:2043
AVDictionary * metadata
Metadata that applies to the whole file.
Definition: avformat.h:1130
void av_free(void *ptr)
Free a memory block which has been allocated with av_malloc(z)() or av_realloc(). ...
Definition: mem.c:186
int flags
Additional information about the frame packing.
Definition: stereo3d.h:132
#define MATROSKA_ID_BLOCKDURATION
Definition: matroska.h:178
#define EBML_ID_EBMLREADVERSION
Definition: matroska.h:37
#define MAX_CUETRACKPOS_SIZE
per-cuepoint-track - 3 1-byte EBML IDs, 3 1-byte EBML sizes, 2 8-byte uint max
Definition: matroskaenc.c:123
static int mkv_write_ass_blocks(AVFormatContext *s, AVIOContext *pb, AVPacket *pkt)
Definition: matroskaenc.c:1224
#define AVERROR(e)
Definition: error.h:43
unsigned int elementid
Definition: matroskaenc.c:57
int reserved_size
-1 if appending to file
Definition: matroskaenc.c:64
#define MATROSKA_ID_CLUSTER
Definition: matroska.h:62
const char * av_convert_lang_to(const char *lang, enum AVLangCodespace target_codespace)
Convert a language code to a target codespace.
Definition: avlanguage.c:736
static int put_xiph_codecpriv(AVFormatContext *s, AVIOContext *pb, AVCodecContext *codec)
Definition: matroskaenc.c:442
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification. ...
Definition: internal.h:150
#define MATROSKA_ID_FILEMIMETYPE
Definition: matroska.h:186
int64_t convergence_duration
Time difference in AVStream->time_base units from the pts of this packet to the point at which the ou...
Definition: avcodec.h:1017
#define MATROSKA_ID_WRITINGAPP
Definition: matroska.h:69
#define AV_LOG_DEBUG
Stuff which is only useful for libav* developers.
Definition: log.h:144
void av_dict_free(AVDictionary **pm)
Free all the memory allocated for an AVDictionary struct and all keys and values. ...
Definition: dict.c:170
static int mkv_blockgroup_size(int pkt_size)
Definition: matroskaenc.c:1200
AVBufferRef * buf
A reference to the reference-counted buffer where the packet data is stored.
Definition: avcodec.h:956
static int ebml_num_size(uint64_t num)
Calculate how many bytes are needed to represent a given number in EBML.
Definition: matroskaenc.c:156
int write_dts
Definition: matroskaenc.c:83
int final
Definition: wv.h:43
AVChapter ** chapters
Definition: avformat.h:1120
enum AVCodecID id
Definition: matroska.h:249
enum AVPacketSideDataType type
Definition: avcodec.h:925
void av_log(void *avcl, int level, const char *fmt,...)
Definition: log.c:168
enum AVMediaType avcodec_get_type(enum AVCodecID codec_id)
Get the type of the given codec.
Definition: utils.c:2375
static int mkv_write_chapters(AVFormatContext *s)
Definition: matroskaenc.c:874
#define EBML_ID_EBMLMAXIDLENGTH
Definition: matroska.h:38
#define MATROSKA_ID_CHAPTERFLAGHIDDEN
Definition: matroska.h:203
enum AVCodecID codec_id
Definition: mov_chan.c:432
Video is not stereoscopic (and metadata has to be there).
Definition: stereo3d.h:35
uint32_t crc
Definition: wv.h:41
AVRational avg_frame_rate
Average framerate.
Definition: avformat.h:780
const AVCodecTag ff_codec_wav_tags[]
Definition: riff.c:353
#define FFMAX(a, b)
Definition: common.h:55
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:285
int ff_avc_parse_nal_units_buf(const uint8_t *buf_in, uint8_t **buf, int *size)
Definition: avc.c:92
int64_t filepos
Definition: matroskaenc.c:62
int flags
A combination of AV_PKT_FLAG values.
Definition: avcodec.h:979
uint64_t channel_layout
Audio channel layout.
Definition: avcodec.h:1852
static void mkv_write_block(AVFormatContext *s, AVIOContext *pb, unsigned int blockid, AVPacket *pkt, int flags)
Definition: matroskaenc.c:1326
AVCodecContext * codec
Codec context associated with this stream.
Definition: avformat.h:718
const CodecMime ff_mkv_mime_tags[]
Definition: matroska.c:91
#define MATROSKA_ID_TAG
Definition: matroska.h:148
unsigned int nb_streams
Number of elements in AVFormatContext.streams.
Definition: avformat.h:978
#define LIBAVFORMAT_IDENT
Definition: version.h:44
int seekable
A combination of AVIO_SEEKABLE_ flags or 0 when the stream is not seekable.
Definition: avio.h:117
int void avio_flush(AVIOContext *s)
Definition: aviobuf.c:180
audio channel layout utility functions
#define EBML_ID_EBMLVERSION
Definition: matroska.h:36
mkv_cuepoint * entries
Definition: matroskaenc.c:78
#define FFMIN(a, b)
Definition: common.h:57
#define MATROSKA_ID_TAGTARGETS
Definition: matroska.h:155
const AVCodecTag ff_codec_bmp_tags[]
Definition: riff.c:29
int av_strcasecmp(const char *a, const char *b)
Definition: avstring.c:156
#define MATROSKA_ID_TAGNAME
Definition: matroska.h:150
int width
picture width / height.
Definition: avcodec.h:1224
#define MATROSKA_ID_CHAPTERFLAGENABLED
Definition: matroska.h:204
#define AVFMT_GLOBALHEADER
Format wants global header.
Definition: avformat.h:415
int ff_wv_parse_header(WvHeader *wv, const uint8_t *data)
Parse a WavPack block header.
Definition: wv.c:29
int ff_hevc_annexb2mp4_buf(const uint8_t *buf_in, uint8_t **buf_out, int *size, int filter_ps, int *ps_count)
Writes Annex B formatted HEVC NAL units to a data buffer.
Definition: hevc.c:1065
#define MATROSKA_ID_SIMPLETAG
Definition: matroska.h:149
const char * name
Definition: avformat.h:446
internal header for RIFF based (de)muxers do NOT include this in end user applications ...
#define WV_HEADER_SIZE
Definition: wavpack.c:36
#define AV_STEREO3D_FLAG_INVERT
Inverted views, Right/Bottom represents the left view.
Definition: stereo3d.h:114
#define AV_WB24(p, d)
Definition: intreadwrite.h:412
int ff_flac_write_header(AVIOContext *pb, uint8_t *extradata, int extradata_size, int last_block)
static char buffer[20]
Definition: seek-test.c:31
#define MATROSKA_ID_CHAPTERATOM
Definition: matroska.h:192
AVDictionary * metadata
Definition: avformat.h:771
Opaque data information usually sparse.
Definition: avutil.h:191
#define MATROSKA_ID_CHAPTERS
Definition: matroska.h:63
static int mkv_add_cuepoint(mkv_cues *cues, int stream, int64_t ts, int64_t cluster_pos)
Definition: matroskaenc.c:389
#define EBML_ID_VOID
Definition: matroska.h:45
#define OFFSET(x)
Definition: matroskaenc.c:1674
LIBAVUTIL_VERSION_INT
Definition: eval.c:55
#define MATROSKA_ID_AUDIOSAMPLINGFREQ
Definition: matroska.h:121
static void put_ebml_float(AVIOContext *pb, unsigned int elementid, double val)
Definition: matroskaenc.c:202
Stream structure.
Definition: avformat.h:699
static void put_ebml_string(AVIOContext *pb, unsigned int elementid, const char *str)
Definition: matroskaenc.c:217
int64_t end
chapter start/end time in time_base units
Definition: avformat.h:908
NULL
Definition: eval.c:55
#define AV_DISPOSITION_DEFAULT
Definition: avformat.h:668
enum AVStereo3DType type
How views are packed within the video.
Definition: stereo3d.h:127
#define MATROSKA_ID_TAGS
Definition: matroska.h:59
enum AVMediaType codec_type
Definition: avcodec.h:1058
enum AVCodecID codec_id
Definition: avcodec.h:1067
#define MATROSKA_ID_SEEKID
Definition: matroska.h:166
char * av_strdup(const char *s)
Duplicate the string s.
Definition: mem.c:213
int sample_rate
samples per second
Definition: avcodec.h:1791
AVIOContext * pb
I/O context.
Definition: avformat.h:964
av_default_item_name
Definition: dnxhdenc.c:52
void avio_w8(AVIOContext *s, int b)
Definition: aviobuf.c:144
main external API structure.
Definition: avcodec.h:1050
#define MATROSKA_ID_BLOCK
Definition: matroska.h:177
#define MATROSKA_ID_INFO
Definition: matroska.h:56
#define MATROSKA_ID_TAGTARGETS_TRACKUID
Definition: matroska.h:158
#define MATROSKA_ID_TAGLANG
Definition: matroska.h:152
unsigned int codec_tag
fourcc (LSB first, so "ABCD" -> ('D'<<24) + ('C'<<16) + ('B'<<8) + 'A').
Definition: avcodec.h:1082
static unsigned int av_lfg_get(AVLFG *c)
Get the next random unsigned 32-bit number using an ALFG.
Definition: lfg.h:38
#define MATROSKA_ID_TRACKS
Definition: matroska.h:57
int extradata_size
Definition: avcodec.h:1165
#define MATROSKA_ID_TRACKNAME
Definition: matroska.h:90
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:68
#define MATROSKA_ID_SEEKENTRY
Definition: matroska.h:163
Describe the class of an AVClass context structure.
Definition: log.h:33
#define CONFIG_LIBX264_ENCODER
Definition: config.h:1054
#define MATROSKA_ID_EDITIONENTRY
Definition: matroska.h:191
#define FF_COMPLIANCE_NORMAL
Definition: avcodec.h:2344
#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:126
#define MATROSKA_ID_BLOCKGROUP
Definition: matroska.h:173
#define MATROSKA_ID_VIDEOPIXELHEIGHT
Definition: matroska.h:109
static int mkv_write_tracks(AVFormatContext *s)
Definition: matroskaenc.c:853
rational number numerator/denominator
Definition: rational.h:43
static void put_ebml_uint(AVIOContext *pb, unsigned int elementid, uint64_t val)
Definition: matroskaenc.c:189
#define MATROSKA_ID_CUETIME
Definition: matroska.h:139
static int64_t mkv_write_seekhead(AVIOContext *pb, mkv_seekhead *seekhead)
Write the seek head to the file and free it.
Definition: matroskaenc.c:335
AVIOContext * dyn_bc
Definition: matroskaenc.c:93
AVMediaType
Definition: avutil.h:185
int avpriv_split_xiph_headers(uint8_t *extradata, int extradata_size, int first_header_size, 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
av_cold void av_lfg_init(AVLFG *c, unsigned int seed)
Definition: lfg.c:30
int64_t duration_offset
Definition: matroskaenc.c:99
static int mkv_write_packet_internal(AVFormatContext *s, AVPacket *pkt)
Definition: matroskaenc.c:1428
#define MATROSKA_ID_TITLE
Definition: matroska.h:68
#define MATROSKA_ID_TRACKVIDEO
Definition: matroska.h:82
static int mkv_strip_wavpack(const uint8_t *src, uint8_t **pdst, int *size)
Definition: matroskaenc.c:1273
static int ass_get_duration(const uint8_t *p)
Definition: matroskaenc.c:1211
static void put_ebml_id(AVIOContext *pb, unsigned int id)
Definition: matroskaenc.c:133
void ff_put_bmp_header(AVIOContext *pb, AVCodecContext *enc, const AVCodecTag *tags, int for_asf)
Definition: riffenc.c:186
static int put_wv_codecpriv(AVIOContext *pb, AVCodecContext *codec)
Definition: matroskaenc.c:470
Views are on top of each other.
Definition: stereo3d.h:55
#define MATROSKA_ID_ATTACHMENTS
Definition: matroska.h:61
void avio_wb16(AVIOContext *s, unsigned int val)
Definition: aviobuf.c:342
#define MATROSKA_ID_CHAPTERDISPLAY
Definition: matroska.h:195
#define MATROSKA_ID_FILENAME
Definition: matroska.h:185
int av_get_bytes_per_sample(enum AVSampleFormat sample_fmt)
Return number of bytes per sample.
Definition: samplefmt.c:95
const AVMetadataConv ff_mkv_metadata_conv[]
Definition: matroska.c:103
#define MATROSKA_ID_CODECID
Definition: matroska.h:83
int64_t start
Definition: avformat.h:908
Views are next to each other.
Definition: stereo3d.h:45
static int mkv_write_trailer(AVFormatContext *s)
Definition: matroskaenc.c:1574
Main libavformat public API header.
#define MATROSKA_ID_CUETRACK
Definition: matroska.h:143
#define MATROSKA_ID_SEEKPOSITION
Definition: matroska.h:167
#define MATROSKA_ID_CODECDELAY
Definition: matroska.h:89
#define MATROSKA_ID_CHAPTERTIMESTART
Definition: matroska.h:193
static void put_ebml_binary(AVIOContext *pb, unsigned int elementid, const void *buf, int size)
Definition: matroskaenc.c:209
static int mkv_write_track(AVFormatContext *s, MatroskaMuxContext *mkv, int i, AVIOContext *pb)
Definition: matroskaenc.c:702
static int mkv_write_codecprivate(AVFormatContext *s, AVIOContext *pb, AVCodecContext *codec, int native_id, int qt_id)
Definition: matroskaenc.c:575
static int mkv_write_flush_packet(AVFormatContext *s, AVPacket *pkt)
Definition: matroskaenc.c:1550
int disposition
AV_DISPOSITION_* bit field.
Definition: avformat.h:760
AVBufferRef * av_buffer_ref(AVBufferRef *buf)
Create a new reference to an AVBuffer.
Definition: buffer.c:92
int ff_put_wav_header(AVIOContext *pb, AVCodecContext *enc)
Definition: riffenc.c:50
static void put_ebml_void(AVIOContext *pb, uint64_t size)
Write a void element of a given size.
Definition: matroskaenc.c:229
AVRational time_base
time base in which the start/end timestamps are specified
Definition: avformat.h:907
void av_init_packet(AVPacket *pkt)
Initialize optional fields of a packet with default values.
Definition: avpacket.c:47
int64_t nb_frames
number of frames in this stream if known or 0
Definition: avformat.h:758
char * key
Definition: dict.h:75
int den
denominator
Definition: rational.h:45
#define MATROSKA_ID_SEGMENT
Definition: matroska.h:53
int avpriv_mpeg4audio_get_config(MPEG4AudioConfig *c, const uint8_t *buf, int bit_size, int sync_extension)
Parse MPEG-4 systems extradata to retrieve audio configuration.
Definition: mpeg4audio.c:79
#define MATROSKA_ID_SEEKHEAD
Definition: matroska.h:60
#define EBML_ID_HEADER
Definition: matroska.h:33
#define AVFMT_VARIABLE_FPS
Format allows variable fps.
Definition: avformat.h:419
ebml_master cluster
Definition: matroskaenc.c:96
char * value
Definition: dict.h:76
#define MATROSKA_ID_POINTENTRY
Definition: matroska.h:136
mkv_seekhead_entry * entries
Definition: matroskaenc.c:66
int len
int channels
number of audio channels
Definition: avcodec.h:1792
#define av_log2
Definition: intmath.h:85
#define MATROSKA_ID_FILEUID
Definition: matroska.h:188
Views are packed in a checkerboard-like structure per pixel.
Definition: stereo3d.h:76
void * priv_data
Format private data.
Definition: avformat.h:950
#define MATROSKA_ID_CHAPTERUID
Definition: matroska.h:202
Views are packed per column.
Definition: stereo3d.h:107
static void write_header(FFV1Context *f)
Definition: ffv1enc.c:380
#define MATROSKA_ID_VIDEODISPLAYUNIT
Definition: matroska.h:114
int64_t dts
Decompression timestamp in AVStream->time_base units; the time at which the packet is decompressed...
Definition: avcodec.h:972
static void mkv_flush_dynbuf(AVFormatContext *s)
Definition: matroskaenc.c:1413
static const AVOption options[]
Definition: matroskaenc.c:1676
#define EBML_ID_EBMLMAXSIZELENGTH
Definition: matroska.h:39
#define MATROSKA_ID_CHAPSTRING
Definition: matroska.h:196
#define MATROSKA_ID_TAGSTRING
Definition: matroska.h:151
#define AV_DICT_IGNORE_SUFFIX
Definition: dict.h:62
#define MODE_MATROSKAv2
Definition: matroskaenc.c:87
uint32_t av_get_random_seed(void)
Get random data.
Definition: random_seed.c:95
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:1081
static int mkv_write_stereo_mode(AVFormatContext *s, AVIOContext *pb, AVStream *st, int mode)
Definition: matroskaenc.c:628
#define MODE_WEBM
Definition: matroskaenc.c:88
static int mkv_write_packet(AVFormatContext *s, AVPacket *pkt)
Definition: matroskaenc.c:1483
#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:119
static mkv_cues * mkv_start_cues(int64_t segment_offset)
Definition: matroskaenc.c:379
int stream_index
Definition: avcodec.h:975
int num_entries
Definition: matroskaenc.c:79
#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:741
static void end_ebml_master(AVIOContext *pb, ebml_master master)
Definition: matroskaenc.c:256
int64_t segment_offset
Definition: matroskaenc.c:95
#define MATROSKA_ID_ATTACHEDFILE
Definition: matroska.h:183
static ebml_master start_ebml_master(AVIOContext *pb, unsigned int elementid, uint64_t expectedsize)
Definition: matroskaenc.c:247
mkv_seekhead * main_seekhead
Definition: matroskaenc.c:101
This structure stores compressed data.
Definition: avcodec.h:950
int delay
Codec delay.
Definition: avcodec.h:1212
void * av_mallocz(size_t size)
Allocate a block of size bytes with alignment suitable for all memory accesses (including vectors if ...
Definition: mem.c:205
uint32_t blocksize
Definition: wv.h:35
static int mkv_query_codec(enum AVCodecID codec_id, int std_compliance)
Definition: matroskaenc.c:1657
static void put_xiph_size(AVIOContext *pb, int size)
Definition: matroskaenc.c:266
int64_t pts
Presentation timestamp in AVStream->time_base units; the time at which the decompressed packet will b...
Definition: avcodec.h:966
#define MATROSKA_ID_VIDEOPIXELWIDTH
Definition: matroska.h:108
int ff_isom_write_avcc(AVIOContext *pb, const uint8_t *data, int len)
Definition: avc.c:106
#define MATROSKA_ID_TRACKAUDIO
Definition: matroska.h:81
#define AV_NOPTS_VALUE
Undefined timestamp value.
Definition: avutil.h:228
const CodecTags ff_mkv_codec_tags[]
Definition: matroska.c:26