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 
47 #include "libavcodec/xiph.h"
48 #include "libavcodec/mpeg4audio.h"
49 
50 typedef struct ebml_master {
51  int64_t pos;
52  int sizebytes;
53 } ebml_master;
54 
55 typedef struct mkv_seekhead_entry {
56  unsigned int elementid;
57  uint64_t segmentpos;
59 
60 typedef struct mkv_seekhead {
61  int64_t filepos;
62  int64_t segment_offset;
67 } mkv_seekhead;
68 
69 typedef struct {
70  uint64_t pts;
71  int tracknum;
72  int64_t cluster_pos;
73 } mkv_cuepoint;
74 
75 typedef struct {
76  int64_t segment_offset;
79 } mkv_cues;
80 
81 typedef struct {
82  int write_dts;
83  int64_t ts_offset;
84 } mkv_track;
85 
86 #define MODE_MATROSKAv2 0x01
87 #define MODE_WEBM 0x02
88 
89 typedef struct MatroskaMuxContext {
90  const AVClass *class;
91  int mode;
94  int64_t segment_offset;
96  int64_t cluster_pos;
97  int64_t cluster_pts;
98  int64_t duration_offset;
99  int64_t duration;
103 
105 
107 
110  int64_t cues_pos;
114 
115 
118 #define MAX_SEEKENTRY_SIZE 21
119 
122 #define MAX_CUETRACKPOS_SIZE 22
123 
125 #define MAX_CUEPOINT_SIZE(num_tracks) 12 + MAX_CUETRACKPOS_SIZE * num_tracks
126 
127 static int ebml_id_size(unsigned int id)
128 {
129  return (av_log2(id + 1) - 1) / 7 + 1;
130 }
131 
132 static void put_ebml_id(AVIOContext *pb, unsigned int id)
133 {
134  int i = ebml_id_size(id);
135  while (i--)
136  avio_w8(pb, id >> (i * 8));
137 }
138 
144 static void put_ebml_size_unknown(AVIOContext *pb, int bytes)
145 {
146  assert(bytes <= 8);
147  avio_w8(pb, 0x1ff >> bytes);
148  while (--bytes)
149  avio_w8(pb, 0xff);
150 }
151 
155 static int ebml_num_size(uint64_t num)
156 {
157  int bytes = 1;
158  while ((num + 1) >> bytes * 7)
159  bytes++;
160  return bytes;
161 }
162 
169 static void put_ebml_num(AVIOContext *pb, uint64_t num, int bytes)
170 {
171  int i, needed_bytes = ebml_num_size(num);
172 
173  // sizes larger than this are currently undefined in EBML
174  assert(num < (1ULL << 56) - 1);
175 
176  if (bytes == 0)
177  // don't care how many bytes are used, so use the min
178  bytes = needed_bytes;
179  // the bytes needed to write the given size would exceed the bytes
180  // that we need to use, so write unknown size. This shouldn't happen.
181  assert(bytes >= needed_bytes);
182 
183  num |= 1ULL << bytes * 7;
184  for (i = bytes - 1; i >= 0; i--)
185  avio_w8(pb, num >> i * 8);
186 }
187 
188 static void put_ebml_uint(AVIOContext *pb, unsigned int elementid, uint64_t val)
189 {
190  int i, bytes = 1;
191  uint64_t tmp = val;
192  while (tmp >>= 8)
193  bytes++;
194 
195  put_ebml_id(pb, elementid);
196  put_ebml_num(pb, bytes, 0);
197  for (i = bytes - 1; i >= 0; i--)
198  avio_w8(pb, val >> i * 8);
199 }
200 
201 static void put_ebml_float(AVIOContext *pb, unsigned int elementid, double val)
202 {
203  put_ebml_id(pb, elementid);
204  put_ebml_num(pb, 8, 0);
205  avio_wb64(pb, av_double2int(val));
206 }
207 
208 static void put_ebml_binary(AVIOContext *pb, unsigned int elementid,
209  const void *buf, int size)
210 {
211  put_ebml_id(pb, elementid);
212  put_ebml_num(pb, size, 0);
213  avio_write(pb, buf, size);
214 }
215 
216 static void put_ebml_string(AVIOContext *pb, unsigned int elementid,
217  const char *str)
218 {
219  put_ebml_binary(pb, elementid, str, strlen(str));
220 }
221 
228 static void put_ebml_void(AVIOContext *pb, uint64_t size)
229 {
230  int64_t currentpos = avio_tell(pb);
231 
232  assert(size >= 2);
233 
235  // we need to subtract the length needed to store the size from the
236  // size we need to reserve so 2 cases, we use 8 bytes to store the
237  // size if possible, 1 byte otherwise
238  if (size < 10)
239  put_ebml_num(pb, size - 1, 0);
240  else
241  put_ebml_num(pb, size - 9, 8);
242  while (avio_tell(pb) < currentpos + size)
243  avio_w8(pb, 0);
244 }
245 
246 static ebml_master start_ebml_master(AVIOContext *pb, unsigned int elementid,
247  uint64_t expectedsize)
248 {
249  int bytes = expectedsize ? ebml_num_size(expectedsize) : 8;
250  put_ebml_id(pb, elementid);
251  put_ebml_size_unknown(pb, bytes);
252  return (ebml_master) {avio_tell(pb), bytes };
253 }
254 
255 static void end_ebml_master(AVIOContext *pb, ebml_master master)
256 {
257  int64_t pos = avio_tell(pb);
258 
259  if (avio_seek(pb, master.pos - master.sizebytes, SEEK_SET) < 0)
260  return;
261  put_ebml_num(pb, pos - master.pos, master.sizebytes);
262  avio_seek(pb, pos, SEEK_SET);
263 }
264 
265 static void put_xiph_size(AVIOContext *pb, int size)
266 {
267  int i;
268  for (i = 0; i < size / 255; i++)
269  avio_w8(pb, 255);
270  avio_w8(pb, size % 255);
271 }
272 
284 static mkv_seekhead *mkv_start_seekhead(AVIOContext *pb, int64_t segment_offset,
285  int numelements)
286 {
287  mkv_seekhead *new_seekhead = av_mallocz(sizeof(mkv_seekhead));
288  if (!new_seekhead)
289  return NULL;
290 
291  new_seekhead->segment_offset = segment_offset;
292 
293  if (numelements > 0) {
294  new_seekhead->filepos = avio_tell(pb);
295  // 21 bytes max for a seek entry, 10 bytes max for the SeekHead ID
296  // and size, and 3 bytes to guarantee that an EBML void element
297  // will fit afterwards
298  new_seekhead->reserved_size = numelements * MAX_SEEKENTRY_SIZE + 13;
299  new_seekhead->max_entries = numelements;
300  put_ebml_void(pb, new_seekhead->reserved_size);
301  }
302  return new_seekhead;
303 }
304 
305 static int mkv_add_seekhead_entry(mkv_seekhead *seekhead, unsigned int elementid, uint64_t filepos)
306 {
307  int err;
308 
309  // don't store more elements than we reserved space for
310  if (seekhead->max_entries > 0 && seekhead->max_entries <= seekhead->num_entries)
311  return -1;
312 
313  if ((err = av_reallocp_array(&seekhead->entries, seekhead->num_entries + 1,
314  sizeof(*seekhead->entries))) < 0) {
315  seekhead->num_entries = 0;
316  return err;
317  }
318 
319  seekhead->entries[seekhead->num_entries].elementid = elementid;
320  seekhead->entries[seekhead->num_entries++].segmentpos = filepos - seekhead->segment_offset;
321 
322  return 0;
323 }
324 
334 static int64_t mkv_write_seekhead(AVIOContext *pb, mkv_seekhead *seekhead)
335 {
336  ebml_master metaseek, seekentry;
337  int64_t currentpos;
338  int i;
339 
340  currentpos = avio_tell(pb);
341 
342  if (seekhead->reserved_size > 0) {
343  if (avio_seek(pb, seekhead->filepos, SEEK_SET) < 0) {
344  currentpos = -1;
345  goto fail;
346  }
347  }
348 
349  metaseek = start_ebml_master(pb, MATROSKA_ID_SEEKHEAD, seekhead->reserved_size);
350  for (i = 0; i < seekhead->num_entries; i++) {
351  mkv_seekhead_entry *entry = &seekhead->entries[i];
352 
354 
356  put_ebml_num(pb, ebml_id_size(entry->elementid), 0);
357  put_ebml_id(pb, entry->elementid);
358 
360  end_ebml_master(pb, seekentry);
361  }
362  end_ebml_master(pb, metaseek);
363 
364  if (seekhead->reserved_size > 0) {
365  uint64_t remaining = seekhead->filepos + seekhead->reserved_size - avio_tell(pb);
366  put_ebml_void(pb, remaining);
367  avio_seek(pb, currentpos, SEEK_SET);
368 
369  currentpos = seekhead->filepos;
370  }
371 fail:
372  av_free(seekhead->entries);
373  av_free(seekhead);
374 
375  return currentpos;
376 }
377 
378 static mkv_cues *mkv_start_cues(int64_t segment_offset)
379 {
380  mkv_cues *cues = av_mallocz(sizeof(mkv_cues));
381  if (!cues)
382  return NULL;
383 
384  cues->segment_offset = segment_offset;
385  return cues;
386 }
387 
388 static int mkv_add_cuepoint(mkv_cues *cues, int stream, int64_t ts, int64_t cluster_pos)
389 {
390  int err;
391 
392  if (ts < 0)
393  return 0;
394 
395  if ((err = av_reallocp_array(&cues->entries, cues->num_entries + 1,
396  sizeof(*cues->entries))) < 0) {
397  cues->num_entries = 0;
398  return err;
399  }
400 
401  cues->entries[cues->num_entries].pts = ts;
402  cues->entries[cues->num_entries].tracknum = stream + 1;
403  cues->entries[cues->num_entries++].cluster_pos = cluster_pos - cues->segment_offset;
404 
405  return 0;
406 }
407 
408 static int64_t mkv_write_cues(AVIOContext *pb, mkv_cues *cues, int num_tracks)
409 {
410  ebml_master cues_element;
411  int64_t currentpos;
412  int i, j;
413 
414  currentpos = avio_tell(pb);
415  cues_element = start_ebml_master(pb, MATROSKA_ID_CUES, 0);
416 
417  for (i = 0; i < cues->num_entries; i++) {
418  ebml_master cuepoint, track_positions;
419  mkv_cuepoint *entry = &cues->entries[i];
420  uint64_t pts = entry->pts;
421 
422  cuepoint = start_ebml_master(pb, MATROSKA_ID_POINTENTRY, MAX_CUEPOINT_SIZE(num_tracks));
424 
425  // put all the entries from different tracks that have the exact same
426  // timestamp into the same CuePoint
427  for (j = 0; j < cues->num_entries - i && entry[j].pts == pts; j++) {
429  put_ebml_uint(pb, MATROSKA_ID_CUETRACK , entry[j].tracknum );
430  put_ebml_uint(pb, MATROSKA_ID_CUECLUSTERPOSITION, entry[j].cluster_pos);
431  end_ebml_master(pb, track_positions);
432  }
433  i += j - 1;
434  end_ebml_master(pb, cuepoint);
435  }
436  end_ebml_master(pb, cues_element);
437 
438  return currentpos;
439 }
440 
442 {
443  uint8_t *header_start[3];
444  int header_len[3];
445  int first_header_size;
446  int j;
447 
448  if (codec->codec_id == AV_CODEC_ID_VORBIS)
449  first_header_size = 30;
450  else
451  first_header_size = 42;
452 
454  first_header_size, header_start, header_len) < 0) {
455  av_log(s, AV_LOG_ERROR, "Extradata corrupt.\n");
456  return -1;
457  }
458 
459  avio_w8(pb, 2); // number packets - 1
460  for (j = 0; j < 2; j++) {
461  put_xiph_size(pb, header_len[j]);
462  }
463  for (j = 0; j < 3; j++)
464  avio_write(pb, header_start[j], header_len[j]);
465 
466  return 0;
467 }
468 
470 {
471  if (codec->extradata && codec->extradata_size == 2)
472  avio_write(pb, codec->extradata, 2);
473  else
474  avio_wl16(pb, 0x403); // fallback to the version mentioned in matroska specs
475  return 0;
476 }
477 
479  AVIOContext *pb, AVCodecContext *codec)
480 {
481  int write_comment = (codec->channel_layout &&
482  !(codec->channel_layout & ~0x3ffffULL) &&
484  int ret = ff_flac_write_header(pb, codec->extradata, codec->extradata_size,
485  !write_comment);
486 
487  if (ret < 0)
488  return ret;
489 
490  if (write_comment) {
491  const char *vendor = (s->flags & AVFMT_FLAG_BITEXACT) ?
492  "Libav" : LIBAVFORMAT_IDENT;
493  AVDictionary *dict = NULL;
494  uint8_t buf[32], *data, *p;
495  int len;
496 
497  snprintf(buf, sizeof(buf), "0x%"PRIx64, codec->channel_layout);
498  av_dict_set(&dict, "WAVEFORMATEXTENSIBLE_CHANNEL_MASK", buf, 0);
499 
500  len = ff_vorbiscomment_length(dict, vendor);
501  data = av_malloc(len + 4);
502  if (!data) {
503  av_dict_free(&dict);
504  return AVERROR(ENOMEM);
505  }
506 
507  data[0] = 0x84;
508  AV_WB24(data + 1, len);
509 
510  p = data + 4;
511  ff_vorbiscomment_write(&p, &dict, vendor);
512 
513  avio_write(pb, data, len + 4);
514 
515  av_freep(&data);
516  av_dict_free(&dict);
517  }
518 
519  return 0;
520 }
521 
523  int *sample_rate, int *output_sample_rate)
524 {
525  MPEG4AudioConfig mp4ac;
526 
527  if (avpriv_mpeg4audio_get_config(&mp4ac, codec->extradata,
528  codec->extradata_size * 8, 1) < 0) {
530  "Error parsing AAC extradata, unable to determine samplerate.\n");
531  return;
532  }
533 
534  *sample_rate = mp4ac.sample_rate;
535  *output_sample_rate = mp4ac.ext_sample_rate;
536 }
537 
539  AVCodecContext *codec,
540  AVIOContext *dyn_cp)
541 {
542  switch (codec->codec_id) {
543  case AV_CODEC_ID_VORBIS:
544  case AV_CODEC_ID_THEORA:
545  return put_xiph_codecpriv(s, dyn_cp, codec);
546  case AV_CODEC_ID_FLAC:
547  return put_flac_codecpriv(s, dyn_cp, codec);
548  case AV_CODEC_ID_WAVPACK:
549  return put_wv_codecpriv(dyn_cp, codec);
550  case AV_CODEC_ID_H264:
551  return ff_isom_write_avcc(dyn_cp, codec->extradata,
552  codec->extradata_size);
553  case AV_CODEC_ID_HEVC:
554  return ff_isom_write_hvcc(dyn_cp, codec->extradata,
555  codec->extradata_size, 0);
556  case AV_CODEC_ID_ALAC:
557  if (codec->extradata_size < 36) {
558  av_log(s, AV_LOG_ERROR,
559  "Invalid extradata found, ALAC expects a 36-byte "
560  "QuickTime atom.");
561  return AVERROR_INVALIDDATA;
562  } else
563  avio_write(dyn_cp, codec->extradata + 12,
564  codec->extradata_size - 12);
565  break;
566  default:
567  if (codec->extradata_size)
568  avio_write(dyn_cp, codec->extradata, codec->extradata_size);
569  }
570 
571  return 0;
572 }
573 
575  AVCodecContext *codec, int native_id,
576  int qt_id)
577 {
578  AVIOContext *dyn_cp;
579  uint8_t *codecpriv;
580  int ret, codecpriv_size;
581 
582  ret = avio_open_dyn_buf(&dyn_cp);
583  if (ret < 0)
584  return ret;
585 
586  if (native_id) {
587  ret = mkv_write_native_codecprivate(s, codec, dyn_cp);
588  } else if (codec->codec_type == AVMEDIA_TYPE_VIDEO) {
589  if (qt_id) {
590  if (!codec->codec_tag)
592  codec->codec_id);
593  if (codec->extradata_size)
594  avio_write(dyn_cp, codec->extradata, codec->extradata_size);
595  } else {
596  if (!codec->codec_tag)
598  codec->codec_id);
599  if (!codec->codec_tag) {
600  av_log(s, AV_LOG_ERROR, "No bmp codec ID found.\n");
601  ret = -1;
602  }
603 
604  ff_put_bmp_header(dyn_cp, codec, ff_codec_bmp_tags, 0);
605  }
606  } else if (codec->codec_type == AVMEDIA_TYPE_AUDIO) {
607  unsigned int tag;
609  if (!tag) {
610  av_log(s, AV_LOG_ERROR, "No wav codec ID found.\n");
611  ret = -1;
612  }
613  if (!codec->codec_tag)
614  codec->codec_tag = tag;
615 
616  ff_put_wav_header(dyn_cp, codec);
617  }
618 
619  codecpriv_size = avio_close_dyn_buf(dyn_cp, &codecpriv);
620  if (codecpriv_size)
622  codecpriv_size);
623  av_free(codecpriv);
624  return ret;
625 }
626 
627 static void mkv_write_stereo_mode(AVIOContext *pb, uint8_t stereo_fmt,
628  int mode)
629 {
630  int valid_fmt = 0;
631 
632  switch (mode) {
633  case MODE_WEBM:
634  if (stereo_fmt <= MATROSKA_VIDEO_STEREOMODE_TYPE_TOP_BOTTOM ||
636  valid_fmt = 1;
637  break;
638  case MODE_MATROSKAv2:
640  valid_fmt = 1;
641  break;
642  }
643 
644  if (valid_fmt)
645  put_ebml_uint (pb, MATROSKA_ID_VIDEOSTEREOMODE, stereo_fmt);
646 }
647 
649  int i, AVIOContext *pb)
650 {
651  AVStream *st = s->streams[i];
652  AVCodecContext *codec = st->codec;
653  ebml_master subinfo, track;
654  int native_id = 0;
655  int qt_id = 0;
656  int bit_depth = av_get_bits_per_sample(codec->codec_id);
657  int sample_rate = codec->sample_rate;
658  int output_sample_rate = 0;
659  int j, ret;
661 
662  // ms precision is the de-facto standard timescale for mkv files
663  avpriv_set_pts_info(st, 64, 1, 1000);
664 
665  if (codec->codec_type == AVMEDIA_TYPE_ATTACHMENT) {
666  mkv->have_attachments = 1;
667  return 0;
668  }
669 
670  if (!bit_depth)
671  bit_depth = av_get_bytes_per_sample(codec->sample_fmt) << 3;
672 
673  if (codec->codec_id == AV_CODEC_ID_AAC)
674  get_aac_sample_rates(s, codec, &sample_rate, &output_sample_rate);
675 
678  put_ebml_uint (pb, MATROSKA_ID_TRACKUID , i + 1);
679  put_ebml_uint (pb, MATROSKA_ID_TRACKFLAGLACING , 0); // no lacing (yet)
680 
681  if ((tag = av_dict_get(st->metadata, "title", NULL, 0)))
683  tag = av_dict_get(st->metadata, "language", NULL, 0);
684  put_ebml_string(pb, MATROSKA_ID_TRACKLANGUAGE, tag ? tag->value:"und");
685 
686  // The default value for TRACKFLAGDEFAULT is 1, so add element
687  // if we need to clear it.
688  if (!(st->disposition & AV_DISPOSITION_DEFAULT))
690 
691  if (codec->codec_type == AVMEDIA_TYPE_AUDIO && codec->delay) {
692  mkv->tracks[i].ts_offset = av_rescale_q(codec->delay,
693  (AVRational){ 1, codec->sample_rate },
694  st->time_base);
695 
697  av_rescale_q(codec->delay, (AVRational){ 1, codec->sample_rate },
698  (AVRational){ 1, 1000000000 }));
699  }
700 
701  // look for a codec ID string specific to mkv to use,
702  // if none are found, use AVI codes
703  for (j = 0; ff_mkv_codec_tags[j].id != AV_CODEC_ID_NONE; j++) {
704  if (ff_mkv_codec_tags[j].id == codec->codec_id) {
706  native_id = 1;
707  break;
708  }
709  }
710 
711  if (mkv->mode == MODE_WEBM && !(codec->codec_id == AV_CODEC_ID_VP8 ||
712  codec->codec_id == AV_CODEC_ID_VP9 ||
713  codec->codec_id == AV_CODEC_ID_OPUS ||
714  codec->codec_id == AV_CODEC_ID_VORBIS)) {
715  av_log(s, AV_LOG_ERROR,
716  "Only VP8 or VP9 video and Vorbis or Opus audio are supported for WebM.\n");
717  return AVERROR(EINVAL);
718  }
719 
720  switch (codec->codec_type) {
721  case AVMEDIA_TYPE_VIDEO:
723  if (st->avg_frame_rate.num > 0 && st->avg_frame_rate.den > 0)
725 
726  if (!native_id &&
729  codec->codec_id == AV_CODEC_ID_SVQ1 ||
730  codec->codec_id == AV_CODEC_ID_SVQ3 ||
731  codec->codec_id == AV_CODEC_ID_CINEPAK))
732  qt_id = 1;
733 
734  if (qt_id)
735  put_ebml_string(pb, MATROSKA_ID_CODECID, "V_QUICKTIME");
736  else if (!native_id) {
737  // if there is no mkv-specific codec ID, use VFW mode
738  put_ebml_string(pb, MATROSKA_ID_CODECID, "V_MS/VFW/FOURCC");
739  mkv->tracks[i].write_dts = 1;
740  }
741 
742  subinfo = start_ebml_master(pb, MATROSKA_ID_TRACKVIDEO, 0);
743  // XXX: interlace flag?
746  if ((tag = av_dict_get(s->metadata, "stereo_mode", NULL, 0))) {
747  mkv_write_stereo_mode(pb, atoi(tag->value), mkv->mode);
748  }
749  if (st->sample_aspect_ratio.num) {
750  int d_width = codec->width*av_q2d(st->sample_aspect_ratio);
754  }
755  end_ebml_master(pb, subinfo);
756  break;
757 
758  case AVMEDIA_TYPE_AUDIO:
760 
761  if (!native_id)
762  // no mkv-specific ID, use ACM mode
763  put_ebml_string(pb, MATROSKA_ID_CODECID, "A_MS/ACM");
764 
765  subinfo = start_ebml_master(pb, MATROSKA_ID_TRACKAUDIO, 0);
768  if (output_sample_rate)
769  put_ebml_float(pb, MATROSKA_ID_AUDIOOUTSAMPLINGFREQ, output_sample_rate);
770  if (bit_depth)
772  end_ebml_master(pb, subinfo);
773  break;
774 
777  if (!native_id) {
778  av_log(s, AV_LOG_ERROR, "Subtitle codec %d is not supported.\n", codec->codec_id);
779  return AVERROR(ENOSYS);
780  }
781  break;
782  default:
783  av_log(s, AV_LOG_ERROR, "Only audio, video, and subtitles are supported for Matroska.\n");
784  break;
785  }
786  ret = mkv_write_codecprivate(s, pb, codec, native_id, qt_id);
787  if (ret < 0)
788  return ret;
789 
790  end_ebml_master(pb, track);
791 
792  return 0;
793 }
794 
796 {
797  MatroskaMuxContext *mkv = s->priv_data;
798  AVIOContext *pb = s->pb;
799  ebml_master tracks;
800  int i, ret;
801 
803  if (ret < 0)
804  return ret;
805 
806  tracks = start_ebml_master(pb, MATROSKA_ID_TRACKS, 0);
807  for (i = 0; i < s->nb_streams; i++) {
808  ret = mkv_write_track(s, mkv, i, pb);
809  if (ret < 0)
810  return ret;
811  }
812  end_ebml_master(pb, tracks);
813  return 0;
814 }
815 
817 {
818  MatroskaMuxContext *mkv = s->priv_data;
819  AVIOContext *pb = s->pb;
820  ebml_master chapters, editionentry;
821  AVRational scale = {1, 1E9};
822  int i, ret;
823 
824  if (!s->nb_chapters || mkv->wrote_chapters)
825  return 0;
826 
828  if (ret < 0) return ret;
829 
830  chapters = start_ebml_master(pb, MATROSKA_ID_CHAPTERS , 0);
831  editionentry = start_ebml_master(pb, MATROSKA_ID_EDITIONENTRY, 0);
834  for (i = 0; i < s->nb_chapters; i++) {
835  ebml_master chapteratom, chapterdisplay;
836  AVChapter *c = s->chapters[i];
837  AVDictionaryEntry *t = NULL;
838 
839  chapteratom = start_ebml_master(pb, MATROSKA_ID_CHAPTERATOM, 0);
842  av_rescale_q(c->start, c->time_base, scale));
844  av_rescale_q(c->end, c->time_base, scale));
847  if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
848  chapterdisplay = start_ebml_master(pb, MATROSKA_ID_CHAPTERDISPLAY, 0);
851  end_ebml_master(pb, chapterdisplay);
852  }
853  end_ebml_master(pb, chapteratom);
854  }
855  end_ebml_master(pb, editionentry);
856  end_ebml_master(pb, chapters);
857 
858  mkv->wrote_chapters = 1;
859  return 0;
860 }
861 
863 {
864  uint8_t *key = av_strdup(t->key);
865  uint8_t *p = key;
866  const uint8_t *lang = NULL;
868 
869  if ((p = strrchr(p, '-')) &&
870  (lang = av_convert_lang_to(p + 1, AV_LANG_ISO639_2_BIBL)))
871  *p = 0;
872 
873  p = key;
874  while (*p) {
875  if (*p == ' ')
876  *p = '_';
877  else if (*p >= 'a' && *p <= 'z')
878  *p -= 'a' - 'A';
879  p++;
880  }
881 
884  if (lang)
887  end_ebml_master(pb, tag);
888 
889  av_freep(&key);
890 }
891 
892 static int mkv_write_tag(AVFormatContext *s, AVDictionary *m, unsigned int elementid,
893  unsigned int uid, ebml_master *tags)
894 {
895  MatroskaMuxContext *mkv = s->priv_data;
896  ebml_master tag, targets;
897  AVDictionaryEntry *t = NULL;
898  int ret;
899 
900  if (!tags->pos) {
902  if (ret < 0) return ret;
903 
904  *tags = start_ebml_master(s->pb, MATROSKA_ID_TAGS, 0);
905  }
906 
907  tag = start_ebml_master(s->pb, MATROSKA_ID_TAG, 0);
908  targets = start_ebml_master(s->pb, MATROSKA_ID_TAGTARGETS, 0);
909  if (elementid)
910  put_ebml_uint(s->pb, elementid, uid);
911  end_ebml_master(s->pb, targets);
912 
913  while ((t = av_dict_get(m, "", t, AV_DICT_IGNORE_SUFFIX)))
914  if (av_strcasecmp(t->key, "title") &&
915  av_strcasecmp(t->key, "encoding_tool"))
916  mkv_write_simpletag(s->pb, t);
917 
918  end_ebml_master(s->pb, tag);
919  return 0;
920 }
921 
923 {
924  ebml_master tags = {0};
925  int i, ret;
926 
928 
930  ret = mkv_write_tag(s, s->metadata, 0, 0, &tags);
931  if (ret < 0) return ret;
932  }
933 
934  for (i = 0; i < s->nb_streams; i++) {
935  AVStream *st = s->streams[i];
936 
937  if (!av_dict_get(st->metadata, "", 0, AV_DICT_IGNORE_SUFFIX))
938  continue;
939 
940  ret = mkv_write_tag(s, st->metadata, MATROSKA_ID_TAGTARGETS_TRACKUID, i + 1, &tags);
941  if (ret < 0) return ret;
942  }
943 
944  for (i = 0; i < s->nb_chapters; i++) {
945  AVChapter *ch = s->chapters[i];
946 
948  continue;
949 
950  ret = mkv_write_tag(s, ch->metadata, MATROSKA_ID_TAGTARGETS_CHAPTERUID, ch->id, &tags);
951  if (ret < 0) return ret;
952  }
953 
954  if (tags.pos)
955  end_ebml_master(s->pb, tags);
956  return 0;
957 }
958 
960 {
961  MatroskaMuxContext *mkv = s->priv_data;
962  AVIOContext *pb = s->pb;
963  ebml_master attachments;
964  AVLFG c;
965  int i, ret;
966 
967  if (!mkv->have_attachments)
968  return 0;
969 
971 
973  if (ret < 0) return ret;
974 
975  attachments = start_ebml_master(pb, MATROSKA_ID_ATTACHMENTS, 0);
976 
977  for (i = 0; i < s->nb_streams; i++) {
978  AVStream *st = s->streams[i];
979  ebml_master attached_file;
981  const char *mimetype = NULL;
982 
984  continue;
985 
986  attached_file = start_ebml_master(pb, MATROSKA_ID_ATTACHEDFILE, 0);
987 
988  if (t = av_dict_get(st->metadata, "title", NULL, 0))
990  if (!(t = av_dict_get(st->metadata, "filename", NULL, 0))) {
991  av_log(s, AV_LOG_ERROR, "Attachment stream %d has no filename tag.\n", i);
992  return AVERROR(EINVAL);
993  }
995  if (t = av_dict_get(st->metadata, "mimetype", NULL, 0))
996  mimetype = t->value;
997  else if (st->codec->codec_id != AV_CODEC_ID_NONE ) {
998  int i;
999  for (i = 0; ff_mkv_mime_tags[i].id != AV_CODEC_ID_NONE; i++)
1000  if (ff_mkv_mime_tags[i].id == st->codec->codec_id) {
1001  mimetype = ff_mkv_mime_tags[i].str;
1002  break;
1003  }
1004  }
1005  if (!mimetype) {
1006  av_log(s, AV_LOG_ERROR, "Attachment stream %d has no mimetype tag and "
1007  "it cannot be deduced from the codec id.\n", i);
1008  return AVERROR(EINVAL);
1009  }
1010 
1014  end_ebml_master(pb, attached_file);
1015  }
1016  end_ebml_master(pb, attachments);
1017 
1018  return 0;
1019 }
1020 
1022 {
1023  MatroskaMuxContext *mkv = s->priv_data;
1024  AVIOContext *pb = s->pb;
1025  ebml_master ebml_header, segment_info;
1027  int ret, i;
1028 
1029  if (!strcmp(s->oformat->name, "webm"))
1030  mkv->mode = MODE_WEBM;
1031  else
1032  mkv->mode = MODE_MATROSKAv2;
1033 
1034  mkv->tracks = av_mallocz(s->nb_streams * sizeof(*mkv->tracks));
1035  if (!mkv->tracks)
1036  return AVERROR(ENOMEM);
1037 
1038  ebml_header = start_ebml_master(pb, EBML_ID_HEADER, 0);
1046  end_ebml_master(pb, ebml_header);
1047 
1049  mkv->segment_offset = avio_tell(pb);
1050 
1051  // we write 2 seek heads - one at the end of the file to point to each
1052  // cluster, and one at the beginning to point to all other level one
1053  // elements (including the seek head at the end of the file), which
1054  // isn't more than 10 elements if we only write one of each other
1055  // currently defined level 1 element
1056  mkv->main_seekhead = mkv_start_seekhead(pb, mkv->segment_offset, 10);
1057  if (!mkv->main_seekhead)
1058  return AVERROR(ENOMEM);
1059 
1061  if (ret < 0) return ret;
1062 
1063  segment_info = start_ebml_master(pb, MATROSKA_ID_INFO, 0);
1065  if ((tag = av_dict_get(s->metadata, "title", NULL, 0)))
1067  if (!(s->flags & AVFMT_FLAG_BITEXACT)) {
1068  uint32_t segment_uid[4];
1069  AVLFG lfg;
1070 
1072 
1073  for (i = 0; i < 4; i++)
1074  segment_uid[i] = av_lfg_get(&lfg);
1075 
1077  if ((tag = av_dict_get(s->metadata, "encoding_tool", NULL, 0)))
1079  else
1081  put_ebml_binary(pb, MATROSKA_ID_SEGMENTUID, segment_uid, 16);
1082  }
1083 
1084  // reserve space for the duration
1085  mkv->duration = 0;
1086  mkv->duration_offset = avio_tell(pb);
1087  put_ebml_void(pb, 11); // assumes double-precision float to be written
1088  end_ebml_master(pb, segment_info);
1089 
1090  ret = mkv_write_tracks(s);
1091  if (ret < 0)
1092  return ret;
1093 
1094  if (mkv->mode != MODE_WEBM) {
1095  ret = mkv_write_chapters(s);
1096  if (ret < 0)
1097  return ret;
1098 
1099  ret = mkv_write_tags(s);
1100  if (ret < 0)
1101  return ret;
1102 
1103  ret = mkv_write_attachments(s);
1104  if (ret < 0)
1105  return ret;
1106  }
1107 
1108  if (!s->pb->seekable)
1110 
1111  mkv->cues = mkv_start_cues(mkv->segment_offset);
1112  if (!mkv->cues)
1113  return AVERROR(ENOMEM);
1114 
1115  if (pb->seekable && mkv->reserve_cues_space) {
1116  mkv->cues_pos = avio_tell(pb);
1118  }
1119 
1121  mkv->cur_audio_pkt.size = 0;
1122 
1123  avio_flush(pb);
1124 
1125  // start a new cluster every 5 MB or 5 sec, or 32k / 1 sec for streaming or
1126  // after 4k and on a keyframe
1127  if (pb->seekable) {
1128  if (mkv->cluster_time_limit < 0)
1129  mkv->cluster_time_limit = 5000;
1130  if (mkv->cluster_size_limit < 0)
1131  mkv->cluster_size_limit = 5 * 1024 * 1024;
1132  } else {
1133  if (mkv->cluster_time_limit < 0)
1134  mkv->cluster_time_limit = 1000;
1135  if (mkv->cluster_size_limit < 0)
1136  mkv->cluster_size_limit = 32 * 1024;
1137  }
1138 
1139  return 0;
1140 }
1141 
1142 static int mkv_blockgroup_size(int pkt_size)
1143 {
1144  int size = pkt_size + 4;
1145  size += ebml_num_size(size);
1146  size += 2; // EBML ID for block and block duration
1147  size += 8; // max size of block duration
1148  size += ebml_num_size(size);
1149  size += 1; // blockgroup EBML ID
1150  return size;
1151 }
1152 
1153 static int ass_get_duration(const uint8_t *p)
1154 {
1155  int sh, sm, ss, sc, eh, em, es, ec;
1156  uint64_t start, end;
1157 
1158  if (sscanf(p, "%*[^,],%d:%d:%d%*c%d,%d:%d:%d%*c%d",
1159  &sh, &sm, &ss, &sc, &eh, &em, &es, &ec) != 8)
1160  return 0;
1161  start = 3600000 * sh + 60000 * sm + 1000 * ss + 10 * sc;
1162  end = 3600000 * eh + 60000 * em + 1000 * es + 10 * ec;
1163  return end - start;
1164 }
1165 
1167  AVPacket *pkt)
1168 {
1169  MatroskaMuxContext *mkv = s->priv_data;
1170  int i, layer = 0, max_duration = 0, size, line_size, data_size = pkt->size;
1171  uint8_t *start, *end, *data = pkt->data;
1172  ebml_master blockgroup;
1173  char buffer[2048];
1174 
1175  while (data_size) {
1176  int duration = ass_get_duration(data);
1177  max_duration = FFMAX(duration, max_duration);
1178  end = memchr(data, '\n', data_size);
1179  size = line_size = end ? end - data + 1 : data_size;
1180  size -= end ? (end[-1] == '\r') + 1 : 0;
1181  start = data;
1182  for (i = 0; i < 3; i++, start++)
1183  if (!(start = memchr(start, ',', size - (start - data))))
1184  return max_duration;
1185  size -= start - data;
1186  sscanf(data, "Dialogue: %d,", &layer);
1187  i = snprintf(buffer, sizeof(buffer), "%" PRId64 ",%d,",
1188  s->streams[pkt->stream_index]->nb_frames, layer);
1189  size = FFMIN(i + size, sizeof(buffer));
1190  memcpy(buffer + i, start, size - i);
1191 
1192  av_log(s, AV_LOG_DEBUG,
1193  "Writing block at offset %" PRIu64 ", size %d, "
1194  "pts %" PRId64 ", duration %d\n",
1195  avio_tell(pb), size, pkt->pts, duration);
1196  blockgroup = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP,
1199  put_ebml_num(pb, size + 4, 0);
1200  // this assumes stream_index is less than 126
1201  avio_w8(pb, 0x80 | (pkt->stream_index + 1));
1202  avio_wb16(pb, pkt->pts - mkv->cluster_pts);
1203  avio_w8(pb, 0);
1204  avio_write(pb, buffer, size);
1206  end_ebml_master(pb, blockgroup);
1207 
1208  data += line_size;
1209  data_size -= line_size;
1210  }
1211 
1212  return max_duration;
1213 }
1214 
1215 static int mkv_strip_wavpack(const uint8_t *src, uint8_t **pdst, int *size)
1216 {
1217  uint8_t *dst;
1218  int srclen = *size;
1219  int offset = 0;
1220  int ret;
1221 
1222  dst = av_malloc(srclen);
1223  if (!dst)
1224  return AVERROR(ENOMEM);
1225 
1226  while (srclen >= WV_HEADER_SIZE) {
1227  WvHeader header;
1228 
1229  ret = ff_wv_parse_header(&header, src);
1230  if (ret < 0)
1231  goto fail;
1232  src += WV_HEADER_SIZE;
1233  srclen -= WV_HEADER_SIZE;
1234 
1235  if (srclen < header.blocksize) {
1236  ret = AVERROR_INVALIDDATA;
1237  goto fail;
1238  }
1239 
1240  if (header.initial) {
1241  AV_WL32(dst + offset, header.samples);
1242  offset += 4;
1243  }
1244  AV_WL32(dst + offset, header.flags);
1245  AV_WL32(dst + offset + 4, header.crc);
1246  offset += 8;
1247 
1248  if (!(header.initial && header.final)) {
1249  AV_WL32(dst + offset, header.blocksize);
1250  offset += 4;
1251  }
1252 
1253  memcpy(dst + offset, src, header.blocksize);
1254  src += header.blocksize;
1255  srclen -= header.blocksize;
1256  offset += header.blocksize;
1257  }
1258 
1259  *pdst = dst;
1260  *size = offset;
1261 
1262  return 0;
1263 fail:
1264  av_freep(&dst);
1265  return ret;
1266 }
1267 
1269  unsigned int blockid, AVPacket *pkt, int flags)
1270 {
1271  MatroskaMuxContext *mkv = s->priv_data;
1272  AVCodecContext *codec = s->streams[pkt->stream_index]->codec;
1273  uint8_t *data = NULL;
1274  int offset = 0, size = pkt->size;
1275  int64_t ts = mkv->tracks[pkt->stream_index].write_dts ? pkt->dts : pkt->pts;
1276 
1277  av_log(s, AV_LOG_DEBUG, "Writing block at offset %" PRIu64 ", size %d, "
1278  "pts %" PRId64 ", dts %" PRId64 ", duration %d, flags %d\n",
1279  avio_tell(pb), pkt->size, pkt->pts, pkt->dts, pkt->duration, flags);
1280  if (codec->codec_id == AV_CODEC_ID_H264 && codec->extradata_size > 0 &&
1281  (AV_RB24(codec->extradata) == 1 || AV_RB32(codec->extradata) == 1))
1282  ff_avc_parse_nal_units_buf(pkt->data, &data, &size);
1283  else if (codec->codec_id == AV_CODEC_ID_HEVC && codec->extradata_size > 6 &&
1284  (AV_RB24(codec->extradata) == 1 || AV_RB32(codec->extradata) == 1))
1285  /* extradata is Annex B, assume the bitstream is too and convert it */
1286  ff_hevc_annexb2mp4_buf(pkt->data, &data, &size, 0, NULL);
1287  else if (codec->codec_id == AV_CODEC_ID_WAVPACK) {
1288  int ret = mkv_strip_wavpack(pkt->data, &data, &size);
1289  if (ret < 0) {
1290  av_log(s, AV_LOG_ERROR, "Error stripping a WavPack packet.\n");
1291  return;
1292  }
1293  } else
1294  data = pkt->data;
1295 
1296  if (codec->codec_id == AV_CODEC_ID_PRORES) {
1297  /* Matroska specification requires to remove the first QuickTime atom
1298  */
1299  size -= 8;
1300  offset = 8;
1301  }
1302 
1303  put_ebml_id(pb, blockid);
1304  put_ebml_num(pb, size + 4, 0);
1305  // this assumes stream_index is less than 126
1306  avio_w8(pb, 0x80 | (pkt->stream_index + 1));
1307  avio_wb16(pb, ts - mkv->cluster_pts);
1308  avio_w8(pb, flags);
1309  avio_write(pb, data + offset, size);
1310  if (data != pkt->data)
1311  av_free(data);
1312 }
1313 
1314 static int srt_get_duration(uint8_t **buf)
1315 {
1316  int i, duration = 0;
1317 
1318  for (i = 0; i < 2 && !duration; i++) {
1319  int s_hour, s_min, s_sec, s_hsec, e_hour, e_min, e_sec, e_hsec;
1320  if (sscanf(*buf, "%d:%2d:%2d%*1[,.]%3d --> %d:%2d:%2d%*1[,.]%3d",
1321  &s_hour, &s_min, &s_sec, &s_hsec,
1322  &e_hour, &e_min, &e_sec, &e_hsec) == 8) {
1323  s_min += 60 * s_hour;
1324  e_min += 60 * e_hour;
1325  s_sec += 60 * s_min;
1326 
1327  e_sec += 60 * e_min;
1328  s_hsec += 1000 * s_sec;
1329  e_hsec += 1000 * e_sec;
1330 
1331  duration = e_hsec - s_hsec;
1332  }
1333  *buf += strcspn(*buf, "\n") + 1;
1334  }
1335  return duration;
1336 }
1337 
1339  AVPacket *pkt)
1340 {
1341  ebml_master blockgroup;
1342  AVPacket pkt2 = *pkt;
1343  int64_t duration = srt_get_duration(&pkt2.data);
1344  pkt2.size -= pkt2.data - pkt->data;
1345 
1346  blockgroup = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP,
1347  mkv_blockgroup_size(pkt2.size));
1348  mkv_write_block(s, pb, MATROSKA_ID_BLOCK, &pkt2, 0);
1350  end_ebml_master(pb, blockgroup);
1351 
1352  return duration;
1353 }
1354 
1356 {
1357  MatroskaMuxContext *mkv = s->priv_data;
1358  int bufsize;
1359  uint8_t *dyn_buf;
1360 
1361  if (!mkv->dyn_bc)
1362  return;
1363 
1364  bufsize = avio_close_dyn_buf(mkv->dyn_bc, &dyn_buf);
1365  avio_write(s->pb, dyn_buf, bufsize);
1366  av_free(dyn_buf);
1367  mkv->dyn_bc = NULL;
1368 }
1369 
1371 {
1372  MatroskaMuxContext *mkv = s->priv_data;
1373  AVIOContext *pb = s->pb;
1374  AVCodecContext *codec = s->streams[pkt->stream_index]->codec;
1375  int keyframe = !!(pkt->flags & AV_PKT_FLAG_KEY);
1376  int duration = pkt->duration;
1377  int ret;
1378  int64_t ts = mkv->tracks[pkt->stream_index].write_dts ? pkt->dts : pkt->pts;
1379 
1380  if (ts == AV_NOPTS_VALUE) {
1381  av_log(s, AV_LOG_ERROR, "Can't write packet with unknown timestamp\n");
1382  return AVERROR(EINVAL);
1383  }
1384  ts += mkv->tracks[pkt->stream_index].ts_offset;
1385 
1386  if (!s->pb->seekable) {
1387  if (!mkv->dyn_bc)
1388  avio_open_dyn_buf(&mkv->dyn_bc);
1389  pb = mkv->dyn_bc;
1390  }
1391 
1392  if (!mkv->cluster_pos) {
1393  mkv->cluster_pos = avio_tell(s->pb);
1396  mkv->cluster_pts = FFMAX(0, ts);
1397  }
1398 
1399  if (codec->codec_type != AVMEDIA_TYPE_SUBTITLE) {
1400  mkv_write_block(s, pb, MATROSKA_ID_SIMPLEBLOCK, pkt, keyframe << 7);
1401  } else if (codec->codec_id == AV_CODEC_ID_SSA) {
1402  duration = mkv_write_ass_blocks(s, pb, pkt);
1403  } else if (codec->codec_id == AV_CODEC_ID_SRT) {
1404  duration = mkv_write_srt_blocks(s, pb, pkt);
1405  } else {
1407  mkv_blockgroup_size(pkt->size));
1408  duration = pkt->convergence_duration;
1409  mkv_write_block(s, pb, MATROSKA_ID_BLOCK, pkt, 0);
1411  end_ebml_master(pb, blockgroup);
1412  }
1413 
1414  if (codec->codec_type == AVMEDIA_TYPE_VIDEO && keyframe) {
1415  ret = mkv_add_cuepoint(mkv->cues, pkt->stream_index, ts,
1416  mkv->cluster_pos);
1417  if (ret < 0)
1418  return ret;
1419  }
1420 
1421  mkv->duration = FFMAX(mkv->duration, ts + duration);
1422  return 0;
1423 }
1424 
1426 {
1427  MatroskaMuxContext *mkv = s->priv_data;
1428  int codec_type = s->streams[pkt->stream_index]->codec->codec_type;
1429  int keyframe = !!(pkt->flags & AV_PKT_FLAG_KEY);
1430  int cluster_size;
1431  int64_t cluster_time;
1432  AVIOContext *pb;
1433  int ret;
1434 
1435  if (mkv->tracks[pkt->stream_index].write_dts)
1436  cluster_time = pkt->dts - mkv->cluster_pts;
1437  else
1438  cluster_time = pkt->pts - mkv->cluster_pts;
1439  cluster_time += mkv->tracks[pkt->stream_index].ts_offset;
1440 
1441  // start a new cluster every 5 MB or 5 sec, or 32k / 1 sec for streaming or
1442  // after 4k and on a keyframe
1443  if (s->pb->seekable) {
1444  pb = s->pb;
1445  cluster_size = avio_tell(pb) - mkv->cluster_pos;
1446  } else {
1447  pb = mkv->dyn_bc;
1448  cluster_size = avio_tell(pb);
1449  }
1450 
1451  if (mkv->cluster_pos &&
1452  (cluster_size > mkv->cluster_size_limit ||
1453  cluster_time > mkv->cluster_time_limit ||
1454  (codec_type == AVMEDIA_TYPE_VIDEO && keyframe &&
1455  cluster_size > 4 * 1024))) {
1456  av_log(s, AV_LOG_DEBUG,
1457  "Starting new cluster at offset %" PRIu64 " bytes, "
1458  "pts %" PRIu64 "dts %" PRIu64 "\n",
1459  avio_tell(pb), pkt->pts, pkt->dts);
1460  end_ebml_master(pb, mkv->cluster);
1461  mkv->cluster_pos = 0;
1462  if (mkv->dyn_bc)
1463  mkv_flush_dynbuf(s);
1464  avio_flush(s->pb);
1465  }
1466 
1467  // check if we have an audio packet cached
1468  if (mkv->cur_audio_pkt.size > 0) {
1469  ret = mkv_write_packet_internal(s, &mkv->cur_audio_pkt);
1471  if (ret < 0) {
1472  av_log(s, AV_LOG_ERROR,
1473  "Could not write cached audio packet ret:%d\n", ret);
1474  return ret;
1475  }
1476  }
1477 
1478  // buffer an audio packet to ensure the packet containing the video
1479  // keyframe's timecode is contained in the same cluster for WebM
1480  if (codec_type == AVMEDIA_TYPE_AUDIO) {
1481  mkv->cur_audio_pkt = *pkt;
1482  if (pkt->buf) {
1483  mkv->cur_audio_pkt.buf = av_buffer_ref(pkt->buf);
1484  ret = mkv->cur_audio_pkt.buf ? 0 : AVERROR(ENOMEM);
1485  } else
1486  ret = av_dup_packet(&mkv->cur_audio_pkt);
1487  } else
1488  ret = mkv_write_packet_internal(s, pkt);
1489  return ret;
1490 }
1491 
1493 {
1494  MatroskaMuxContext *mkv = s->priv_data;
1495  AVIOContext *pb;
1496  if (s->pb->seekable)
1497  pb = s->pb;
1498  else
1499  pb = mkv->dyn_bc;
1500  if (!pkt) {
1501  if (mkv->cluster_pos) {
1502  av_log(s, AV_LOG_DEBUG,
1503  "Flushing cluster at offset %" PRIu64 " bytes\n",
1504  avio_tell(pb));
1505  end_ebml_master(pb, mkv->cluster);
1506  mkv->cluster_pos = 0;
1507  if (mkv->dyn_bc)
1508  mkv_flush_dynbuf(s);
1509  avio_flush(s->pb);
1510  }
1511  return 0;
1512  }
1513  return mkv_write_packet(s, pkt);
1514 }
1515 
1517 {
1518  MatroskaMuxContext *mkv = s->priv_data;
1519  AVIOContext *pb = s->pb;
1520  int64_t currentpos, cuespos;
1521  int ret;
1522 
1523  // check if we have an audio packet cached
1524  if (mkv->cur_audio_pkt.size > 0) {
1525  ret = mkv_write_packet_internal(s, &mkv->cur_audio_pkt);
1527  if (ret < 0) {
1528  av_log(s, AV_LOG_ERROR,
1529  "Could not write cached audio packet ret:%d\n", ret);
1530  return ret;
1531  }
1532  }
1533 
1534  if (mkv->dyn_bc) {
1535  end_ebml_master(mkv->dyn_bc, mkv->cluster);
1536  mkv_flush_dynbuf(s);
1537  } else if (mkv->cluster_pos) {
1538  end_ebml_master(pb, mkv->cluster);
1539  }
1540 
1541  if (mkv->mode != MODE_WEBM) {
1542  ret = mkv_write_chapters(s);
1543  if (ret < 0)
1544  return ret;
1545  }
1546 
1547  if (pb->seekable) {
1548  if (mkv->cues->num_entries) {
1549  if (mkv->reserve_cues_space) {
1550  int64_t cues_end;
1551 
1552  currentpos = avio_tell(pb);
1553  avio_seek(pb, mkv->cues_pos, SEEK_SET);
1554 
1555  cuespos = mkv_write_cues(pb, mkv->cues, s->nb_streams);
1556  cues_end = avio_tell(pb);
1557  if (cues_end > cuespos + mkv->reserve_cues_space) {
1558  av_log(s, AV_LOG_ERROR,
1559  "Insufficient space reserved for cues: %d "
1560  "(needed: %" PRId64 ").\n",
1561  mkv->reserve_cues_space, cues_end - cuespos);
1562  return AVERROR(EINVAL);
1563  }
1564 
1565  if (cues_end < cuespos + mkv->reserve_cues_space)
1567  (cues_end - cuespos));
1568 
1569  avio_seek(pb, currentpos, SEEK_SET);
1570  } else {
1571  cuespos = mkv_write_cues(pb, mkv->cues, s->nb_streams);
1572  }
1573 
1575  cuespos);
1576  if (ret < 0)
1577  return ret;
1578  }
1579 
1581 
1582  // update the duration
1583  av_log(s, AV_LOG_DEBUG, "end duration = %" PRIu64 "\n", mkv->duration);
1584  currentpos = avio_tell(pb);
1585  avio_seek(pb, mkv->duration_offset, SEEK_SET);
1587 
1588  avio_seek(pb, currentpos, SEEK_SET);
1589  }
1590 
1591  end_ebml_master(pb, mkv->segment);
1592  av_free(mkv->tracks);
1593  av_freep(&mkv->cues->entries);
1594  av_freep(&mkv->cues);
1595 
1596  return 0;
1597 }
1598 
1599 static int mkv_query_codec(enum AVCodecID codec_id, int std_compliance)
1600 {
1601  int i;
1602  for (i = 0; ff_mkv_codec_tags[i].id != AV_CODEC_ID_NONE; i++)
1603  if (ff_mkv_codec_tags[i].id == codec_id)
1604  return 1;
1605 
1606  if (std_compliance < FF_COMPLIANCE_NORMAL) {
1607  enum AVMediaType type = avcodec_get_type(codec_id);
1608  // mkv theoretically supports any video/audio through VFW/ACM
1609  if (type == AVMEDIA_TYPE_VIDEO || type == AVMEDIA_TYPE_AUDIO)
1610  return 1;
1611  }
1612 
1613  return 0;
1614 }
1615 
1616 #define OFFSET(x) offsetof(MatroskaMuxContext, x)
1617 #define FLAGS AV_OPT_FLAG_ENCODING_PARAM
1618 static const AVOption options[] = {
1619  { "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 },
1620  { "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 },
1621  { "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 },
1622  { NULL },
1623 };
1624 
1625 #if CONFIG_MATROSKA_MUXER
1626 static const AVClass matroska_class = {
1627  .class_name = "matroska muxer",
1628  .item_name = av_default_item_name,
1629  .option = options,
1630  .version = LIBAVUTIL_VERSION_INT,
1631 };
1632 
1633 AVOutputFormat ff_matroska_muxer = {
1634  .name = "matroska",
1635  .long_name = NULL_IF_CONFIG_SMALL("Matroska"),
1636  .mime_type = "video/x-matroska",
1637  .extensions = "mkv",
1638  .priv_data_size = sizeof(MatroskaMuxContext),
1639  .audio_codec = CONFIG_LIBVORBIS_ENCODER ?
1641  .video_codec = CONFIG_LIBX264_ENCODER ?
1648  .codec_tag = (const AVCodecTag* const []){
1650  },
1651  .subtitle_codec = AV_CODEC_ID_SSA,
1652  .query_codec = mkv_query_codec,
1653  .priv_class = &matroska_class,
1654 };
1655 #endif
1656 
1657 #if CONFIG_WEBM_MUXER
1658 static const AVClass webm_class = {
1659  .class_name = "webm muxer",
1660  .item_name = av_default_item_name,
1661  .option = options,
1662  .version = LIBAVUTIL_VERSION_INT,
1663 };
1664 
1665 AVOutputFormat ff_webm_muxer = {
1666  .name = "webm",
1667  .long_name = NULL_IF_CONFIG_SMALL("WebM"),
1668  .mime_type = "video/webm",
1669  .extensions = "webm",
1670  .priv_data_size = sizeof(MatroskaMuxContext),
1671  .audio_codec = AV_CODEC_ID_VORBIS,
1672  .video_codec = AV_CODEC_ID_VP8,
1678  .priv_class = &webm_class,
1679 };
1680 #endif
1681 
1682 #if CONFIG_MATROSKA_AUDIO_MUXER
1683 static const AVClass mka_class = {
1684  .class_name = "matroska audio muxer",
1685  .item_name = av_default_item_name,
1686  .option = options,
1687  .version = LIBAVUTIL_VERSION_INT,
1688 };
1689 AVOutputFormat ff_matroska_audio_muxer = {
1690  .name = "matroska",
1691  .long_name = NULL_IF_CONFIG_SMALL("Matroska"),
1692  .mime_type = "audio/x-matroska",
1693  .extensions = "mka",
1694  .priv_data_size = sizeof(MatroskaMuxContext),
1695  .audio_codec = CONFIG_LIBVORBIS_ENCODER ?
1696  AV_CODEC_ID_VORBIS : AV_CODEC_ID_AC3,
1697  .video_codec = AV_CODEC_ID_NONE,
1703  .codec_tag = (const AVCodecTag* const []){ ff_codec_wav_tags, 0 },
1704  .priv_class = &mka_class,
1705 };
1706 #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:144
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
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:52
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:72
static void mkv_write_simpletag(AVIOContext *pb, AVDictionaryEntry *t)
Definition: matroskaenc.c:862
#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:2800
#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
static int mkv_write_attachments(AVFormatContext *s)
Definition: matroskaenc.c:959
uint64_t pts
Definition: matroskaenc.c:70
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:968
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:1021
#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:111
#define MATROSKA_ID_AUDIOCHANNELS
Definition: matroska.h:125
unsigned int ff_codec_get_tag(const AVCodecTag *tags, enum AVCodecID id)
Definition: utils.c:1912
int64_t segment_offset
Definition: matroskaenc.c:76
#define MATROSKA_ID_CUECLUSTERPOSITION
Definition: matroska.h:144
Definition: matroskaenc.c:55
AVDictionary * metadata
Definition: avformat.h:909
int av_dup_packet(AVPacket *pkt)
Definition: avpacket.c:190
mkv_track * tracks
Definition: matroskaenc.c:102
#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:51
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:408
#define FLAGS
Definition: matroskaenc.c:1617
#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:96
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:538
#define CONFIG_LIBVORBIS_ENCODER
Definition: config.h:1049
enum AVSampleFormat sample_fmt
audio sample format
Definition: avcodec.h:1793
uint8_t
#define MATROSKA_ID_CHAPLANG
Definition: matroska.h:197
static int srt_get_duration(uint8_t **buf)
Definition: matroskaenc.c:1314
static int mkv_write_tag(AVFormatContext *s, AVDictionary *m, unsigned int elementid, unsigned int uid, ebml_master *tags)
Definition: matroskaenc.c:892
AVOptions.
#define MATROSKA_ID_TRACKLANGUAGE
Definition: matroska.h:91
const AVCodecTag ff_codec_movvideo_tags[]
Definition: isom.c:69
static int ebml_id_size(unsigned int id)
Definition: matroskaenc.c:127
uint32_t flags
Definition: wv.h:40
#define AV_RB32
Definition: intreadwrite.h:130
uint64_t segmentpos
Definition: matroskaenc.c:57
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
uint8_t * extradata
some codecs need / can use extradata like Huffman tables.
Definition: avcodec.h:1158
static int mkv_write_srt_blocks(AVFormatContext *s, AVIOContext *pb, AVPacket *pkt)
Definition: matroskaenc.c:1338
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:967
#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:522
static EbmlSyntax ebml_header[]
Definition: matroskadec.c:282
enum AVCodecID id
Definition: internal.h:42
static int put_flac_codecpriv(AVFormatContext *s, AVIOContext *pb, AVCodecContext *codec)
Definition: matroskaenc.c:478
#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:83
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:985
#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:169
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:305
int64_t segment_offset
the file offset to the beginning of the segment
Definition: matroskaenc.c:62
struct AVOutputFormat * oformat
The output container format.
Definition: avformat.h:941
#define AV_PKT_FLAG_KEY
The packet contains a keyframe.
Definition: avcodec.h:1013
#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:93
#define MATROSKA_ID_VIDEOSTEREOMODE
Definition: matroska.h:116
AVPacket cur_audio_pkt
Definition: matroskaenc.c:104
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:922
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition: log.h:123
AVDictionary * metadata
Metadata that applies to the whole file.
Definition: avformat.h:1130
int av_get_bits_per_sample(enum AVCodecID codec_id)
Return codec bits per sample.
Definition: utils.c:2034
void av_free(void *ptr)
Free a memory block which has been allocated with av_malloc(z)() or av_realloc(). ...
Definition: mem.c:186
#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:122
static int mkv_write_ass_blocks(AVFormatContext *s, AVIOContext *pb, AVPacket *pkt)
Definition: matroskaenc.c:1166
#define AVERROR(e)
Definition: error.h:43
unsigned int elementid
Definition: matroskaenc.c:56
int reserved_size
-1 if appending to file
Definition: matroskaenc.c:63
#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:441
#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:1011
#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:1142
AVBufferRef * buf
A reference to the reference-counted buffer where the packet data is stored.
Definition: avcodec.h:950
static int ebml_num_size(uint64_t num)
Calculate how many bytes are needed to represent a given number in EBML.
Definition: matroskaenc.c:155
int write_dts
Definition: matroskaenc.c:82
int final
Definition: wv.h:43
AVChapter ** chapters
Definition: avformat.h:1120
enum AVCodecID id
Definition: matroska.h:248
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:2366
static int mkv_write_chapters(AVFormatContext *s)
Definition: matroskaenc.c:816
#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
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:284
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:61
int flags
A combination of AV_PKT_FLAG values.
Definition: avcodec.h:973
uint64_t channel_layout
Audio channel layout.
Definition: avcodec.h:1846
static void mkv_write_block(AVFormatContext *s, AVIOContext *pb, unsigned int blockid, AVPacket *pkt, int flags)
Definition: matroskaenc.c:1268
AVCodecContext * codec
Codec context associated with this stream.
Definition: avformat.h:718
const CodecMime ff_mkv_mime_tags[]
Definition: matroska.c:89
#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:77
#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:1218
#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_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:388
#define EBML_ID_VOID
Definition: matroska.h:45
#define OFFSET(x)
Definition: matroskaenc.c:1616
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:201
Stream structure.
Definition: avformat.h:699
static void put_ebml_string(AVIOContext *pb, unsigned int elementid, const char *str)
Definition: matroskaenc.c:216
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
#define MATROSKA_ID_TAGS
Definition: matroska.h:59
enum AVMediaType codec_type
Definition: avcodec.h:1052
enum AVCodecID codec_id
Definition: avcodec.h:1061
#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:1785
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:1044
#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:1076
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:1159
#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:2338
#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:125
#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:795
rational number numerator/denominator
Definition: rational.h:43
static void put_ebml_uint(AVIOContext *pb, unsigned int elementid, uint64_t val)
Definition: matroskaenc.c:188
#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:334
AVIOContext * dyn_bc
Definition: matroskaenc.c:92
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:98
static int mkv_write_packet_internal(AVFormatContext *s, AVPacket *pkt)
Definition: matroskaenc.c:1370
#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:1215
static int ass_get_duration(const uint8_t *p)
Definition: matroskaenc.c:1153
static void put_ebml_id(AVIOContext *pb, unsigned int id)
Definition: matroskaenc.c:132
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:469
#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:101
#define MATROSKA_ID_CODECID
Definition: matroska.h:83
int64_t start
Definition: avformat.h:908
static int mkv_write_trailer(AVFormatContext *s)
Definition: matroskaenc.c:1516
Main libavformat public API header.
#define MATROSKA_ID_CUETRACK
Definition: matroska.h:143
static void mkv_write_stereo_mode(AVIOContext *pb, uint8_t stereo_fmt, int mode)
Definition: matroskaenc.c:627
#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:208
static int mkv_write_track(AVFormatContext *s, MatroskaMuxContext *mkv, int i, AVIOContext *pb)
Definition: matroskaenc.c:648
static int mkv_write_codecprivate(AVFormatContext *s, AVIOContext *pb, AVCodecContext *codec, int native_id, int qt_id)
Definition: matroskaenc.c:574
static int mkv_write_flush_packet(AVFormatContext *s, AVPacket *pkt)
Definition: matroskaenc.c:1492
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:91
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:228
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:95
char * value
Definition: dict.h:76
#define MATROSKA_ID_POINTENTRY
Definition: matroska.h:136
mkv_seekhead_entry * entries
Definition: matroskaenc.c:65
int len
int channels
number of audio channels
Definition: avcodec.h:1786
#define av_log2
Definition: intmath.h:85
#define MATROSKA_ID_FILEUID
Definition: matroska.h:188
void * priv_data
Format private data.
Definition: avformat.h:950
#define MATROSKA_ID_CHAPTERUID
Definition: matroska.h:202
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:966
static void mkv_flush_dynbuf(AVFormatContext *s)
Definition: matroskaenc.c:1355
static const AVOption options[]
Definition: matroskaenc.c:1618
#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:86
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
#define MODE_WEBM
Definition: matroskaenc.c:87
static int mkv_write_packet(AVFormatContext *s, AVPacket *pkt)
Definition: matroskaenc.c:1425
#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:118
static mkv_cues * mkv_start_cues(int64_t segment_offset)
Definition: matroskaenc.c:378
int stream_index
Definition: avcodec.h:969
int num_entries
Definition: matroskaenc.c:78
#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:255
int64_t segment_offset
Definition: matroskaenc.c:94
#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:246
mkv_seekhead * main_seekhead
Definition: matroskaenc.c:100
This structure stores compressed data.
Definition: avcodec.h:944
int delay
Codec delay.
Definition: avcodec.h:1206
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:1599
static void put_xiph_size(AVIOContext *pb, int size)
Definition: matroskaenc.c:265
int64_t pts
Presentation timestamp in AVStream->time_base units; the time at which the decompressed packet will b...
Definition: avcodec.h:960
#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:24