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;
632  int display_width, display_height;
633  int h_width = 1, h_height = 1;
634  AVCodecContext *codec = st->codec;
637 
638  // convert metadata into proper side data and add it to the stream
639  if ((tag = av_dict_get(s->metadata, "stereo_mode", NULL, 0))) {
640  int stereo_mode = atoi(tag->value);
641  if (stereo_mode < MATROSKA_VIDEO_STEREOMODE_TYPE_NB &&
642  stereo_mode != 10 && stereo_mode != 12) {
643  int ret = ff_mkv_stereo3d_conv(st, stereo_mode);
644  if (ret < 0)
645  return ret;
646  }
647  }
648 
649  // iterate to find the stereo3d side data
650  for (i = 0; i < st->nb_side_data; i++) {
651  AVPacketSideData sd = st->side_data[i];
652  if (sd.type == AV_PKT_DATA_STEREO3D) {
653  AVStereo3D *stereo = (AVStereo3D *)sd.data;
654 
655  switch (stereo->type) {
656  case AV_STEREO3D_2D:
658  break;
660  format = (stereo->flags & AV_STEREO3D_FLAG_INVERT)
663  h_width = 2;
664  break;
667  if (stereo->flags & AV_STEREO3D_FLAG_INVERT)
668  format--;
669  h_height = 2;
670  break;
673  if (stereo->flags & AV_STEREO3D_FLAG_INVERT)
674  format--;
675  break;
676  case AV_STEREO3D_LINES:
678  if (stereo->flags & AV_STEREO3D_FLAG_INVERT)
679  format--;
680  h_height = 2;
681  break;
682  case AV_STEREO3D_COLUMNS:
684  if (stereo->flags & AV_STEREO3D_FLAG_INVERT)
685  format--;
686  h_width = 2;
687  break;
690  if (stereo->flags & AV_STEREO3D_FLAG_INVERT)
691  format++;
692  break;
693  }
694 
695  break;
696  }
697  }
698 
699  // if webm, do not write unsupported modes
700  if (mode == MODE_WEBM &&
704 
705  // write StereoMode if format is valid
708 
709  // write DisplayWidth and DisplayHeight, they contain the size of
710  // a single source view and/or the display aspect ratio
711  display_width = codec->width / h_width;
712  display_height = codec->height / h_height;
713  if (st->sample_aspect_ratio.num) {
714  display_width *= av_q2d(st->sample_aspect_ratio);
716  }
717  if (st->sample_aspect_ratio.num ||
719  put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYWIDTH, display_width);
720  put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYHEIGHT, display_height);
721  }
722 
723  return 0;
724 }
725 
727  int i, AVIOContext *pb)
728 {
729  AVStream *st = s->streams[i];
730  AVCodecContext *codec = st->codec;
731  ebml_master subinfo, track;
732  int native_id = 0;
733  int qt_id = 0;
734  int bit_depth = av_get_bits_per_sample(codec->codec_id);
735  int sample_rate = codec->sample_rate;
736  int output_sample_rate = 0;
737  int j, ret;
739 
740  // ms precision is the de-facto standard timescale for mkv files
741  avpriv_set_pts_info(st, 64, 1, 1000);
742 
743  if (codec->codec_type == AVMEDIA_TYPE_ATTACHMENT) {
744  mkv->have_attachments = 1;
745  return 0;
746  }
747 
748  if (!bit_depth)
749  bit_depth = av_get_bytes_per_sample(codec->sample_fmt) << 3;
750 
751  if (codec->codec_id == AV_CODEC_ID_AAC)
752  get_aac_sample_rates(s, codec, &sample_rate, &output_sample_rate);
753 
756  put_ebml_uint (pb, MATROSKA_ID_TRACKUID , i + 1);
757  put_ebml_uint (pb, MATROSKA_ID_TRACKFLAGLACING , 0); // no lacing (yet)
758 
759  if ((tag = av_dict_get(st->metadata, "title", NULL, 0)))
761  tag = av_dict_get(st->metadata, "language", NULL, 0);
762  put_ebml_string(pb, MATROSKA_ID_TRACKLANGUAGE, tag ? tag->value:"und");
763 
764  // The default value for TRACKFLAGDEFAULT is 1, so add element
765  // if we need to clear it.
766  if (!(st->disposition & AV_DISPOSITION_DEFAULT))
768 
769  if (codec->codec_type == AVMEDIA_TYPE_AUDIO && codec->delay) {
770  mkv->tracks[i].ts_offset = av_rescale_q(codec->delay,
771  (AVRational){ 1, codec->sample_rate },
772  st->time_base);
773 
775  av_rescale_q(codec->delay, (AVRational){ 1, codec->sample_rate },
776  (AVRational){ 1, 1000000000 }));
777  }
778 
779  // look for a codec ID string specific to mkv to use,
780  // if none are found, use AVI codes
781  for (j = 0; ff_mkv_codec_tags[j].id != AV_CODEC_ID_NONE; j++) {
782  if (ff_mkv_codec_tags[j].id == codec->codec_id) {
784  native_id = 1;
785  break;
786  }
787  }
788 
789  if (mkv->mode == MODE_WEBM && !(codec->codec_id == AV_CODEC_ID_VP8 ||
790  codec->codec_id == AV_CODEC_ID_VP9 ||
791  codec->codec_id == AV_CODEC_ID_OPUS ||
792  codec->codec_id == AV_CODEC_ID_VORBIS)) {
793  av_log(s, AV_LOG_ERROR,
794  "Only VP8 or VP9 video and Vorbis or Opus audio are supported for WebM.\n");
795  return AVERROR(EINVAL);
796  }
797 
798  switch (codec->codec_type) {
799  case AVMEDIA_TYPE_VIDEO:
801  if (st->avg_frame_rate.num > 0 && st->avg_frame_rate.den > 0)
803 
804  if (!native_id &&
807  codec->codec_id == AV_CODEC_ID_SVQ1 ||
808  codec->codec_id == AV_CODEC_ID_SVQ3 ||
809  codec->codec_id == AV_CODEC_ID_CINEPAK))
810  qt_id = 1;
811 
812  if (qt_id)
813  put_ebml_string(pb, MATROSKA_ID_CODECID, "V_QUICKTIME");
814  else if (!native_id) {
815  // if there is no mkv-specific codec ID, use VFW mode
816  put_ebml_string(pb, MATROSKA_ID_CODECID, "V_MS/VFW/FOURCC");
817  mkv->tracks[i].write_dts = 1;
818  }
819 
820  subinfo = start_ebml_master(pb, MATROSKA_ID_TRACKVIDEO, 0);
821  // XXX: interlace flag?
824 
825  // check both side data and metadata for stereo information,
826  // write the result to the bitstream if any is found
827  ret = mkv_write_stereo_mode(s, pb, st, mkv->mode);
828  if (ret < 0)
829  return ret;
830 
831  end_ebml_master(pb, subinfo);
832  break;
833 
834  case AVMEDIA_TYPE_AUDIO:
836 
837  if (!native_id)
838  // no mkv-specific ID, use ACM mode
839  put_ebml_string(pb, MATROSKA_ID_CODECID, "A_MS/ACM");
840 
841  subinfo = start_ebml_master(pb, MATROSKA_ID_TRACKAUDIO, 0);
844  if (output_sample_rate)
845  put_ebml_float(pb, MATROSKA_ID_AUDIOOUTSAMPLINGFREQ, output_sample_rate);
846  if (bit_depth)
848  end_ebml_master(pb, subinfo);
849  break;
850 
853  if (!native_id) {
854  av_log(s, AV_LOG_ERROR, "Subtitle codec %d is not supported.\n", codec->codec_id);
855  return AVERROR(ENOSYS);
856  }
857  break;
858  default:
859  av_log(s, AV_LOG_ERROR, "Only audio, video, and subtitles are supported for Matroska.\n");
860  break;
861  }
862  ret = mkv_write_codecprivate(s, pb, codec, native_id, qt_id);
863  if (ret < 0)
864  return ret;
865 
866  end_ebml_master(pb, track);
867 
868  return 0;
869 }
870 
872 {
873  MatroskaMuxContext *mkv = s->priv_data;
874  AVIOContext *pb = s->pb;
875  ebml_master tracks;
876  int i, ret;
877 
879  if (ret < 0)
880  return ret;
881 
882  tracks = start_ebml_master(pb, MATROSKA_ID_TRACKS, 0);
883  for (i = 0; i < s->nb_streams; i++) {
884  ret = mkv_write_track(s, mkv, i, pb);
885  if (ret < 0)
886  return ret;
887  }
888  end_ebml_master(pb, tracks);
889  return 0;
890 }
891 
893 {
894  MatroskaMuxContext *mkv = s->priv_data;
895  AVIOContext *pb = s->pb;
896  ebml_master chapters, editionentry;
897  AVRational scale = {1, 1E9};
898  int i, ret;
899 
900  if (!s->nb_chapters || mkv->wrote_chapters)
901  return 0;
902 
904  if (ret < 0) return ret;
905 
906  chapters = start_ebml_master(pb, MATROSKA_ID_CHAPTERS , 0);
907  editionentry = start_ebml_master(pb, MATROSKA_ID_EDITIONENTRY, 0);
910  for (i = 0; i < s->nb_chapters; i++) {
911  ebml_master chapteratom, chapterdisplay;
912  AVChapter *c = s->chapters[i];
913  AVDictionaryEntry *t = NULL;
914 
915  chapteratom = start_ebml_master(pb, MATROSKA_ID_CHAPTERATOM, 0);
918  av_rescale_q(c->start, c->time_base, scale));
920  av_rescale_q(c->end, c->time_base, scale));
923  if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
924  chapterdisplay = start_ebml_master(pb, MATROSKA_ID_CHAPTERDISPLAY, 0);
927  end_ebml_master(pb, chapterdisplay);
928  }
929  end_ebml_master(pb, chapteratom);
930  }
931  end_ebml_master(pb, editionentry);
932  end_ebml_master(pb, chapters);
933 
934  mkv->wrote_chapters = 1;
935  return 0;
936 }
937 
939 {
940  uint8_t *key = av_strdup(t->key);
941  uint8_t *p = key;
942  const uint8_t *lang = NULL;
944 
945  if ((p = strrchr(p, '-')) &&
946  (lang = av_convert_lang_to(p + 1, AV_LANG_ISO639_2_BIBL)))
947  *p = 0;
948 
949  p = key;
950  while (*p) {
951  if (*p == ' ')
952  *p = '_';
953  else if (*p >= 'a' && *p <= 'z')
954  *p -= 'a' - 'A';
955  p++;
956  }
957 
960  if (lang)
963  end_ebml_master(pb, tag);
964 
965  av_freep(&key);
966 }
967 
968 static int mkv_write_tag(AVFormatContext *s, AVDictionary *m, unsigned int elementid,
969  unsigned int uid, ebml_master *tags)
970 {
971  MatroskaMuxContext *mkv = s->priv_data;
972  ebml_master tag, targets;
973  AVDictionaryEntry *t = NULL;
974  int ret;
975 
976  if (!tags->pos) {
978  if (ret < 0) return ret;
979 
980  *tags = start_ebml_master(s->pb, MATROSKA_ID_TAGS, 0);
981  }
982 
983  tag = start_ebml_master(s->pb, MATROSKA_ID_TAG, 0);
984  targets = start_ebml_master(s->pb, MATROSKA_ID_TAGTARGETS, 0);
985  if (elementid)
986  put_ebml_uint(s->pb, elementid, uid);
987  end_ebml_master(s->pb, targets);
988 
989  while ((t = av_dict_get(m, "", t, AV_DICT_IGNORE_SUFFIX)))
990  if (av_strcasecmp(t->key, "title") &&
991  av_strcasecmp(t->key, "encoding_tool"))
992  mkv_write_simpletag(s->pb, t);
993 
994  end_ebml_master(s->pb, tag);
995  return 0;
996 }
997 
999 {
1000  ebml_master tags = {0};
1001  int i, ret;
1002 
1004 
1006  ret = mkv_write_tag(s, s->metadata, 0, 0, &tags);
1007  if (ret < 0) return ret;
1008  }
1009 
1010  for (i = 0; i < s->nb_streams; i++) {
1011  AVStream *st = s->streams[i];
1012 
1013  if (!av_dict_get(st->metadata, "", 0, AV_DICT_IGNORE_SUFFIX))
1014  continue;
1015 
1016  ret = mkv_write_tag(s, st->metadata, MATROSKA_ID_TAGTARGETS_TRACKUID, i + 1, &tags);
1017  if (ret < 0) return ret;
1018  }
1019 
1020  for (i = 0; i < s->nb_chapters; i++) {
1021  AVChapter *ch = s->chapters[i];
1022 
1024  continue;
1025 
1026  ret = mkv_write_tag(s, ch->metadata, MATROSKA_ID_TAGTARGETS_CHAPTERUID, ch->id, &tags);
1027  if (ret < 0) return ret;
1028  }
1029 
1030  if (tags.pos)
1031  end_ebml_master(s->pb, tags);
1032  return 0;
1033 }
1034 
1036 {
1037  MatroskaMuxContext *mkv = s->priv_data;
1038  AVIOContext *pb = s->pb;
1039  ebml_master attachments;
1040  AVLFG c;
1041  int i, ret;
1042 
1043  if (!mkv->have_attachments)
1044  return 0;
1045 
1047 
1049  if (ret < 0) return ret;
1050 
1051  attachments = start_ebml_master(pb, MATROSKA_ID_ATTACHMENTS, 0);
1052 
1053  for (i = 0; i < s->nb_streams; i++) {
1054  AVStream *st = s->streams[i];
1055  ebml_master attached_file;
1056  AVDictionaryEntry *t;
1057  const char *mimetype = NULL;
1058 
1060  continue;
1061 
1062  attached_file = start_ebml_master(pb, MATROSKA_ID_ATTACHEDFILE, 0);
1063 
1064  if (t = av_dict_get(st->metadata, "title", NULL, 0))
1066  if (!(t = av_dict_get(st->metadata, "filename", NULL, 0))) {
1067  av_log(s, AV_LOG_ERROR, "Attachment stream %d has no filename tag.\n", i);
1068  return AVERROR(EINVAL);
1069  }
1071  if (t = av_dict_get(st->metadata, "mimetype", NULL, 0))
1072  mimetype = t->value;
1073  else if (st->codec->codec_id != AV_CODEC_ID_NONE ) {
1074  int i;
1075  for (i = 0; ff_mkv_mime_tags[i].id != AV_CODEC_ID_NONE; i++)
1076  if (ff_mkv_mime_tags[i].id == st->codec->codec_id) {
1077  mimetype = ff_mkv_mime_tags[i].str;
1078  break;
1079  }
1080  }
1081  if (!mimetype) {
1082  av_log(s, AV_LOG_ERROR, "Attachment stream %d has no mimetype tag and "
1083  "it cannot be deduced from the codec id.\n", i);
1084  return AVERROR(EINVAL);
1085  }
1086 
1090  end_ebml_master(pb, attached_file);
1091  }
1092  end_ebml_master(pb, attachments);
1093 
1094  return 0;
1095 }
1096 
1098 {
1099  MatroskaMuxContext *mkv = s->priv_data;
1100  AVIOContext *pb = s->pb;
1101  ebml_master ebml_header, segment_info;
1103  int ret, i;
1104 
1105  if (!strcmp(s->oformat->name, "webm"))
1106  mkv->mode = MODE_WEBM;
1107  else
1108  mkv->mode = MODE_MATROSKAv2;
1109 
1110  mkv->tracks = av_mallocz(s->nb_streams * sizeof(*mkv->tracks));
1111  if (!mkv->tracks)
1112  return AVERROR(ENOMEM);
1113 
1114  ebml_header = start_ebml_master(pb, EBML_ID_HEADER, 0);
1122  end_ebml_master(pb, ebml_header);
1123 
1125  mkv->segment_offset = avio_tell(pb);
1126 
1127  // we write 2 seek heads - one at the end of the file to point to each
1128  // cluster, and one at the beginning to point to all other level one
1129  // elements (including the seek head at the end of the file), which
1130  // isn't more than 10 elements if we only write one of each other
1131  // currently defined level 1 element
1132  mkv->main_seekhead = mkv_start_seekhead(pb, mkv->segment_offset, 10);
1133  if (!mkv->main_seekhead)
1134  return AVERROR(ENOMEM);
1135 
1137  if (ret < 0) return ret;
1138 
1139  segment_info = start_ebml_master(pb, MATROSKA_ID_INFO, 0);
1141  if ((tag = av_dict_get(s->metadata, "title", NULL, 0)))
1143  if (!(s->flags & AVFMT_FLAG_BITEXACT)) {
1144  uint32_t segment_uid[4];
1145  AVLFG lfg;
1146 
1148 
1149  for (i = 0; i < 4; i++)
1150  segment_uid[i] = av_lfg_get(&lfg);
1151 
1153  if ((tag = av_dict_get(s->metadata, "encoding_tool", NULL, 0)))
1155  else
1157  put_ebml_binary(pb, MATROSKA_ID_SEGMENTUID, segment_uid, 16);
1158  }
1159 
1160  // reserve space for the duration
1161  mkv->duration = 0;
1162  mkv->duration_offset = avio_tell(pb);
1163  put_ebml_void(pb, 11); // assumes double-precision float to be written
1164  end_ebml_master(pb, segment_info);
1165 
1166  ret = mkv_write_tracks(s);
1167  if (ret < 0)
1168  return ret;
1169 
1170  if (mkv->mode != MODE_WEBM) {
1171  ret = mkv_write_chapters(s);
1172  if (ret < 0)
1173  return ret;
1174 
1175  ret = mkv_write_tags(s);
1176  if (ret < 0)
1177  return ret;
1178 
1179  ret = mkv_write_attachments(s);
1180  if (ret < 0)
1181  return ret;
1182  }
1183 
1184  if (!s->pb->seekable)
1186 
1187  mkv->cues = mkv_start_cues(mkv->segment_offset);
1188  if (!mkv->cues)
1189  return AVERROR(ENOMEM);
1190 
1191  if (pb->seekable && mkv->reserve_cues_space) {
1192  mkv->cues_pos = avio_tell(pb);
1194  }
1195 
1197  mkv->cur_audio_pkt.size = 0;
1198 
1199  avio_flush(pb);
1200 
1201  // start a new cluster every 5 MB or 5 sec, or 32k / 1 sec for streaming or
1202  // after 4k and on a keyframe
1203  if (pb->seekable) {
1204  if (mkv->cluster_time_limit < 0)
1205  mkv->cluster_time_limit = 5000;
1206  if (mkv->cluster_size_limit < 0)
1207  mkv->cluster_size_limit = 5 * 1024 * 1024;
1208  } else {
1209  if (mkv->cluster_time_limit < 0)
1210  mkv->cluster_time_limit = 1000;
1211  if (mkv->cluster_size_limit < 0)
1212  mkv->cluster_size_limit = 32 * 1024;
1213  }
1214 
1215  return 0;
1216 }
1217 
1218 static int mkv_blockgroup_size(int pkt_size)
1219 {
1220  int size = pkt_size + 4;
1221  size += ebml_num_size(size);
1222  size += 2; // EBML ID for block and block duration
1223  size += 8; // max size of block duration
1224  size += ebml_num_size(size);
1225  size += 1; // blockgroup EBML ID
1226  return size;
1227 }
1228 
1229 static int ass_get_duration(const uint8_t *p)
1230 {
1231  int sh, sm, ss, sc, eh, em, es, ec;
1232  uint64_t start, end;
1233 
1234  if (sscanf(p, "%*[^,],%d:%d:%d%*c%d,%d:%d:%d%*c%d",
1235  &sh, &sm, &ss, &sc, &eh, &em, &es, &ec) != 8)
1236  return 0;
1237  start = 3600000 * sh + 60000 * sm + 1000 * ss + 10 * sc;
1238  end = 3600000 * eh + 60000 * em + 1000 * es + 10 * ec;
1239  return end - start;
1240 }
1241 
1243  AVPacket *pkt)
1244 {
1245  MatroskaMuxContext *mkv = s->priv_data;
1246  int i, layer = 0, max_duration = 0, size, line_size, data_size = pkt->size;
1247  uint8_t *start, *end, *data = pkt->data;
1248  ebml_master blockgroup;
1249  char buffer[2048];
1250 
1251  while (data_size) {
1252  int duration = ass_get_duration(data);
1253  max_duration = FFMAX(duration, max_duration);
1254  end = memchr(data, '\n', data_size);
1255  size = line_size = end ? end - data + 1 : data_size;
1256  size -= end ? (end[-1] == '\r') + 1 : 0;
1257  start = data;
1258  for (i = 0; i < 3; i++, start++)
1259  if (!(start = memchr(start, ',', size - (start - data))))
1260  return max_duration;
1261  size -= start - data;
1262  sscanf(data, "Dialogue: %d,", &layer);
1263  i = snprintf(buffer, sizeof(buffer), "%" PRId64 ",%d,",
1264  s->streams[pkt->stream_index]->nb_frames, layer);
1265  size = FFMIN(i + size, sizeof(buffer));
1266  memcpy(buffer + i, start, size - i);
1267 
1268  av_log(s, AV_LOG_DEBUG,
1269  "Writing block at offset %" PRIu64 ", size %d, "
1270  "pts %" PRId64 ", duration %d\n",
1271  avio_tell(pb), size, pkt->pts, duration);
1272  blockgroup = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP,
1275  put_ebml_num(pb, size + 4, 0);
1276  // this assumes stream_index is less than 126
1277  avio_w8(pb, 0x80 | (pkt->stream_index + 1));
1278  avio_wb16(pb, pkt->pts - mkv->cluster_pts);
1279  avio_w8(pb, 0);
1280  avio_write(pb, buffer, size);
1282  end_ebml_master(pb, blockgroup);
1283 
1284  data += line_size;
1285  data_size -= line_size;
1286  }
1287 
1288  return max_duration;
1289 }
1290 
1291 static int mkv_strip_wavpack(const uint8_t *src, uint8_t **pdst, int *size)
1292 {
1293  uint8_t *dst;
1294  int srclen = *size;
1295  int offset = 0;
1296  int ret;
1297 
1298  dst = av_malloc(srclen);
1299  if (!dst)
1300  return AVERROR(ENOMEM);
1301 
1302  while (srclen >= WV_HEADER_SIZE) {
1303  WvHeader header;
1304 
1305  ret = ff_wv_parse_header(&header, src);
1306  if (ret < 0)
1307  goto fail;
1308  src += WV_HEADER_SIZE;
1309  srclen -= WV_HEADER_SIZE;
1310 
1311  if (srclen < header.blocksize) {
1312  ret = AVERROR_INVALIDDATA;
1313  goto fail;
1314  }
1315 
1316  if (header.initial) {
1317  AV_WL32(dst + offset, header.samples);
1318  offset += 4;
1319  }
1320  AV_WL32(dst + offset, header.flags);
1321  AV_WL32(dst + offset + 4, header.crc);
1322  offset += 8;
1323 
1324  if (!(header.initial && header.final)) {
1325  AV_WL32(dst + offset, header.blocksize);
1326  offset += 4;
1327  }
1328 
1329  memcpy(dst + offset, src, header.blocksize);
1330  src += header.blocksize;
1331  srclen -= header.blocksize;
1332  offset += header.blocksize;
1333  }
1334 
1335  *pdst = dst;
1336  *size = offset;
1337 
1338  return 0;
1339 fail:
1340  av_freep(&dst);
1341  return ret;
1342 }
1343 
1345  unsigned int blockid, AVPacket *pkt, int flags)
1346 {
1347  MatroskaMuxContext *mkv = s->priv_data;
1348  AVCodecContext *codec = s->streams[pkt->stream_index]->codec;
1349  uint8_t *data = NULL;
1350  int offset = 0, size = pkt->size;
1351  int64_t ts = mkv->tracks[pkt->stream_index].write_dts ? pkt->dts : pkt->pts;
1352 
1353  av_log(s, AV_LOG_DEBUG, "Writing block at offset %" PRIu64 ", size %d, "
1354  "pts %" PRId64 ", dts %" PRId64 ", duration %d, flags %d\n",
1355  avio_tell(pb), pkt->size, pkt->pts, pkt->dts, pkt->duration, flags);
1356  if (codec->codec_id == AV_CODEC_ID_H264 && codec->extradata_size > 0 &&
1357  (AV_RB24(codec->extradata) == 1 || AV_RB32(codec->extradata) == 1))
1358  ff_avc_parse_nal_units_buf(pkt->data, &data, &size);
1359  else if (codec->codec_id == AV_CODEC_ID_HEVC && codec->extradata_size > 6 &&
1360  (AV_RB24(codec->extradata) == 1 || AV_RB32(codec->extradata) == 1))
1361  /* extradata is Annex B, assume the bitstream is too and convert it */
1362  ff_hevc_annexb2mp4_buf(pkt->data, &data, &size, 0, NULL);
1363  else if (codec->codec_id == AV_CODEC_ID_WAVPACK) {
1364  int ret = mkv_strip_wavpack(pkt->data, &data, &size);
1365  if (ret < 0) {
1366  av_log(s, AV_LOG_ERROR, "Error stripping a WavPack packet.\n");
1367  return;
1368  }
1369  } else
1370  data = pkt->data;
1371 
1372  if (codec->codec_id == AV_CODEC_ID_PRORES) {
1373  /* Matroska specification requires to remove the first QuickTime atom
1374  */
1375  size -= 8;
1376  offset = 8;
1377  }
1378 
1379  put_ebml_id(pb, blockid);
1380  put_ebml_num(pb, size + 4, 0);
1381  // this assumes stream_index is less than 126
1382  avio_w8(pb, 0x80 | (pkt->stream_index + 1));
1383  avio_wb16(pb, ts - mkv->cluster_pts);
1384  avio_w8(pb, flags);
1385  avio_write(pb, data + offset, size);
1386  if (data != pkt->data)
1387  av_free(data);
1388 }
1389 
1390 static int srt_get_duration(uint8_t **buf)
1391 {
1392  int i, duration = 0;
1393 
1394  for (i = 0; i < 2 && !duration; i++) {
1395  int s_hour, s_min, s_sec, s_hsec, e_hour, e_min, e_sec, e_hsec;
1396  if (sscanf(*buf, "%d:%2d:%2d%*1[,.]%3d --> %d:%2d:%2d%*1[,.]%3d",
1397  &s_hour, &s_min, &s_sec, &s_hsec,
1398  &e_hour, &e_min, &e_sec, &e_hsec) == 8) {
1399  s_min += 60 * s_hour;
1400  e_min += 60 * e_hour;
1401  s_sec += 60 * s_min;
1402 
1403  e_sec += 60 * e_min;
1404  s_hsec += 1000 * s_sec;
1405  e_hsec += 1000 * e_sec;
1406 
1407  duration = e_hsec - s_hsec;
1408  }
1409  *buf += strcspn(*buf, "\n") + 1;
1410  }
1411  return duration;
1412 }
1413 
1415  AVPacket *pkt)
1416 {
1417  ebml_master blockgroup;
1418  AVPacket pkt2 = *pkt;
1419  int64_t duration = srt_get_duration(&pkt2.data);
1420  pkt2.size -= pkt2.data - pkt->data;
1421 
1422  blockgroup = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP,
1423  mkv_blockgroup_size(pkt2.size));
1424  mkv_write_block(s, pb, MATROSKA_ID_BLOCK, &pkt2, 0);
1426  end_ebml_master(pb, blockgroup);
1427 
1428  return duration;
1429 }
1430 
1432 {
1433  MatroskaMuxContext *mkv = s->priv_data;
1434  int bufsize;
1435  uint8_t *dyn_buf;
1436 
1437  if (!mkv->dyn_bc)
1438  return;
1439 
1440  bufsize = avio_close_dyn_buf(mkv->dyn_bc, &dyn_buf);
1441  avio_write(s->pb, dyn_buf, bufsize);
1442  av_free(dyn_buf);
1443  mkv->dyn_bc = NULL;
1444 }
1445 
1447 {
1448  MatroskaMuxContext *mkv = s->priv_data;
1449  AVIOContext *pb = s->pb;
1450  AVCodecContext *codec = s->streams[pkt->stream_index]->codec;
1451  int keyframe = !!(pkt->flags & AV_PKT_FLAG_KEY);
1452  int duration = pkt->duration;
1453  int ret;
1454  int64_t ts = mkv->tracks[pkt->stream_index].write_dts ? pkt->dts : pkt->pts;
1455 
1456  if (ts == AV_NOPTS_VALUE) {
1457  av_log(s, AV_LOG_ERROR, "Can't write packet with unknown timestamp\n");
1458  return AVERROR(EINVAL);
1459  }
1460  ts += mkv->tracks[pkt->stream_index].ts_offset;
1461 
1462  if (!s->pb->seekable) {
1463  if (!mkv->dyn_bc)
1464  avio_open_dyn_buf(&mkv->dyn_bc);
1465  pb = mkv->dyn_bc;
1466  }
1467 
1468  if (!mkv->cluster_pos) {
1469  mkv->cluster_pos = avio_tell(s->pb);
1472  mkv->cluster_pts = FFMAX(0, ts);
1473  }
1474 
1475  if (codec->codec_type != AVMEDIA_TYPE_SUBTITLE) {
1476  mkv_write_block(s, pb, MATROSKA_ID_SIMPLEBLOCK, pkt, keyframe << 7);
1477  } else if (codec->codec_id == AV_CODEC_ID_SSA) {
1478  duration = mkv_write_ass_blocks(s, pb, pkt);
1479  } else if (codec->codec_id == AV_CODEC_ID_SRT) {
1480  duration = mkv_write_srt_blocks(s, pb, pkt);
1481  } else {
1483  mkv_blockgroup_size(pkt->size));
1484  duration = pkt->convergence_duration;
1485  mkv_write_block(s, pb, MATROSKA_ID_BLOCK, pkt, 0);
1487  end_ebml_master(pb, blockgroup);
1488  }
1489 
1490  if (codec->codec_type == AVMEDIA_TYPE_VIDEO && keyframe) {
1491  ret = mkv_add_cuepoint(mkv->cues, pkt->stream_index, ts,
1492  mkv->cluster_pos);
1493  if (ret < 0)
1494  return ret;
1495  }
1496 
1497  mkv->duration = FFMAX(mkv->duration, ts + duration);
1498  return 0;
1499 }
1500 
1502 {
1503  MatroskaMuxContext *mkv = s->priv_data;
1504  int codec_type = s->streams[pkt->stream_index]->codec->codec_type;
1505  int keyframe = !!(pkt->flags & AV_PKT_FLAG_KEY);
1506  int cluster_size;
1507  int64_t cluster_time;
1508  AVIOContext *pb;
1509  int ret;
1510 
1511  if (mkv->tracks[pkt->stream_index].write_dts)
1512  cluster_time = pkt->dts - mkv->cluster_pts;
1513  else
1514  cluster_time = pkt->pts - mkv->cluster_pts;
1515  cluster_time += mkv->tracks[pkt->stream_index].ts_offset;
1516 
1517  // start a new cluster every 5 MB or 5 sec, or 32k / 1 sec for streaming or
1518  // after 4k and on a keyframe
1519  if (s->pb->seekable) {
1520  pb = s->pb;
1521  cluster_size = avio_tell(pb) - mkv->cluster_pos;
1522  } else {
1523  pb = mkv->dyn_bc;
1524  cluster_size = avio_tell(pb);
1525  }
1526 
1527  if (mkv->cluster_pos &&
1528  (cluster_size > mkv->cluster_size_limit ||
1529  cluster_time > mkv->cluster_time_limit ||
1530  (codec_type == AVMEDIA_TYPE_VIDEO && keyframe &&
1531  cluster_size > 4 * 1024))) {
1532  av_log(s, AV_LOG_DEBUG,
1533  "Starting new cluster at offset %" PRIu64 " bytes, "
1534  "pts %" PRIu64 "dts %" PRIu64 "\n",
1535  avio_tell(pb), pkt->pts, pkt->dts);
1536  end_ebml_master(pb, mkv->cluster);
1537  mkv->cluster_pos = 0;
1538  if (mkv->dyn_bc)
1539  mkv_flush_dynbuf(s);
1540  avio_flush(s->pb);
1541  }
1542 
1543  // check if we have an audio packet cached
1544  if (mkv->cur_audio_pkt.size > 0) {
1545  ret = mkv_write_packet_internal(s, &mkv->cur_audio_pkt);
1547  if (ret < 0) {
1548  av_log(s, AV_LOG_ERROR,
1549  "Could not write cached audio packet ret:%d\n", ret);
1550  return ret;
1551  }
1552  }
1553 
1554  // buffer an audio packet to ensure the packet containing the video
1555  // keyframe's timecode is contained in the same cluster for WebM
1556  if (codec_type == AVMEDIA_TYPE_AUDIO) {
1557  mkv->cur_audio_pkt = *pkt;
1558  if (pkt->buf) {
1559  mkv->cur_audio_pkt.buf = av_buffer_ref(pkt->buf);
1560  ret = mkv->cur_audio_pkt.buf ? 0 : AVERROR(ENOMEM);
1561  } else
1562  ret = av_dup_packet(&mkv->cur_audio_pkt);
1563  } else
1564  ret = mkv_write_packet_internal(s, pkt);
1565  return ret;
1566 }
1567 
1569 {
1570  MatroskaMuxContext *mkv = s->priv_data;
1571  AVIOContext *pb;
1572  if (s->pb->seekable)
1573  pb = s->pb;
1574  else
1575  pb = mkv->dyn_bc;
1576  if (!pkt) {
1577  if (mkv->cluster_pos) {
1578  av_log(s, AV_LOG_DEBUG,
1579  "Flushing cluster at offset %" PRIu64 " bytes\n",
1580  avio_tell(pb));
1581  end_ebml_master(pb, mkv->cluster);
1582  mkv->cluster_pos = 0;
1583  if (mkv->dyn_bc)
1584  mkv_flush_dynbuf(s);
1585  avio_flush(s->pb);
1586  }
1587  return 1;
1588  }
1589  return mkv_write_packet(s, pkt);
1590 }
1591 
1593 {
1594  MatroskaMuxContext *mkv = s->priv_data;
1595  AVIOContext *pb = s->pb;
1596  int64_t currentpos, cuespos;
1597  int ret;
1598 
1599  // check if we have an audio packet cached
1600  if (mkv->cur_audio_pkt.size > 0) {
1601  ret = mkv_write_packet_internal(s, &mkv->cur_audio_pkt);
1603  if (ret < 0) {
1604  av_log(s, AV_LOG_ERROR,
1605  "Could not write cached audio packet ret:%d\n", ret);
1606  return ret;
1607  }
1608  }
1609 
1610  if (mkv->dyn_bc) {
1611  end_ebml_master(mkv->dyn_bc, mkv->cluster);
1612  mkv_flush_dynbuf(s);
1613  } else if (mkv->cluster_pos) {
1614  end_ebml_master(pb, mkv->cluster);
1615  }
1616 
1617  if (mkv->mode != MODE_WEBM) {
1618  ret = mkv_write_chapters(s);
1619  if (ret < 0)
1620  return ret;
1621  }
1622 
1623  if (pb->seekable) {
1624  if (mkv->cues->num_entries) {
1625  if (mkv->reserve_cues_space) {
1626  int64_t cues_end;
1627 
1628  currentpos = avio_tell(pb);
1629  avio_seek(pb, mkv->cues_pos, SEEK_SET);
1630 
1631  cuespos = mkv_write_cues(pb, mkv->cues, s->nb_streams);
1632  cues_end = avio_tell(pb);
1633  if (cues_end > cuespos + mkv->reserve_cues_space) {
1634  av_log(s, AV_LOG_ERROR,
1635  "Insufficient space reserved for cues: %d "
1636  "(needed: %" PRId64 ").\n",
1637  mkv->reserve_cues_space, cues_end - cuespos);
1638  return AVERROR(EINVAL);
1639  }
1640 
1641  if (cues_end < cuespos + mkv->reserve_cues_space)
1643  (cues_end - cuespos));
1644 
1645  avio_seek(pb, currentpos, SEEK_SET);
1646  } else {
1647  cuespos = mkv_write_cues(pb, mkv->cues, s->nb_streams);
1648  }
1649 
1651  cuespos);
1652  if (ret < 0)
1653  return ret;
1654  }
1655 
1657 
1658  // update the duration
1659  av_log(s, AV_LOG_DEBUG, "end duration = %" PRIu64 "\n", mkv->duration);
1660  currentpos = avio_tell(pb);
1661  avio_seek(pb, mkv->duration_offset, SEEK_SET);
1663 
1664  avio_seek(pb, currentpos, SEEK_SET);
1665  }
1666 
1667  end_ebml_master(pb, mkv->segment);
1668  av_free(mkv->tracks);
1669  av_freep(&mkv->cues->entries);
1670  av_freep(&mkv->cues);
1671 
1672  return 0;
1673 }
1674 
1675 static int mkv_query_codec(enum AVCodecID codec_id, int std_compliance)
1676 {
1677  int i;
1678  for (i = 0; ff_mkv_codec_tags[i].id != AV_CODEC_ID_NONE; i++)
1679  if (ff_mkv_codec_tags[i].id == codec_id)
1680  return 1;
1681 
1682  if (std_compliance < FF_COMPLIANCE_NORMAL) {
1683  enum AVMediaType type = avcodec_get_type(codec_id);
1684  // mkv theoretically supports any video/audio through VFW/ACM
1685  if (type == AVMEDIA_TYPE_VIDEO || type == AVMEDIA_TYPE_AUDIO)
1686  return 1;
1687  }
1688 
1689  return 0;
1690 }
1691 
1692 #define OFFSET(x) offsetof(MatroskaMuxContext, x)
1693 #define FLAGS AV_OPT_FLAG_ENCODING_PARAM
1694 static const AVOption options[] = {
1695  { "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 },
1696  { "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 },
1697  { "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 },
1698  { NULL },
1699 };
1700 
1701 #if CONFIG_MATROSKA_MUXER
1702 static const AVClass matroska_class = {
1703  .class_name = "matroska muxer",
1704  .item_name = av_default_item_name,
1705  .option = options,
1706  .version = LIBAVUTIL_VERSION_INT,
1707 };
1708 
1709 AVOutputFormat ff_matroska_muxer = {
1710  .name = "matroska",
1711  .long_name = NULL_IF_CONFIG_SMALL("Matroska"),
1712  .mime_type = "video/x-matroska",
1713  .extensions = "mkv",
1714  .priv_data_size = sizeof(MatroskaMuxContext),
1715  .audio_codec = CONFIG_LIBVORBIS_ENCODER ?
1717  .video_codec = CONFIG_LIBX264_ENCODER ?
1724  .codec_tag = (const AVCodecTag* const []){
1726  },
1727  .subtitle_codec = AV_CODEC_ID_SSA,
1728  .query_codec = mkv_query_codec,
1729  .priv_class = &matroska_class,
1730 };
1731 #endif
1732 
1733 #if CONFIG_WEBM_MUXER
1734 static const AVClass webm_class = {
1735  .class_name = "webm muxer",
1736  .item_name = av_default_item_name,
1737  .option = options,
1738  .version = LIBAVUTIL_VERSION_INT,
1739 };
1740 
1741 AVOutputFormat ff_webm_muxer = {
1742  .name = "webm",
1743  .long_name = NULL_IF_CONFIG_SMALL("WebM"),
1744  .mime_type = "video/webm",
1745  .extensions = "webm",
1746  .priv_data_size = sizeof(MatroskaMuxContext),
1747  .audio_codec = AV_CODEC_ID_VORBIS,
1748  .video_codec = AV_CODEC_ID_VP8,
1754  .priv_class = &webm_class,
1755 };
1756 #endif
1757 
1758 #if CONFIG_MATROSKA_AUDIO_MUXER
1759 static const AVClass mka_class = {
1760  .class_name = "matroska audio muxer",
1761  .item_name = av_default_item_name,
1762  .option = options,
1763  .version = LIBAVUTIL_VERSION_INT,
1764 };
1765 AVOutputFormat ff_matroska_audio_muxer = {
1766  .name = "matroska",
1767  .long_name = NULL_IF_CONFIG_SMALL("Matroska"),
1768  .mime_type = "audio/x-matroska",
1769  .extensions = "mka",
1770  .priv_data_size = sizeof(MatroskaMuxContext),
1771  .audio_codec = CONFIG_LIBVORBIS_ENCODER ?
1772  AV_CODEC_ID_VORBIS : AV_CODEC_ID_AC3,
1773  .video_codec = AV_CODEC_ID_NONE,
1779  .codec_tag = (const AVCodecTag* const []){ ff_codec_wav_tags, 0 },
1780  .priv_class = &mka_class,
1781 };
1782 #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:341
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:347
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:977
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:938
#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:2829
#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:1035
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:1097
#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:965
#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:1693
#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
enum AVSampleFormat sample_fmt
audio sample format
Definition: avcodec.h:1815
uint8_t
#define MATROSKA_ID_CHAPLANG
Definition: matroska.h:197
static int srt_get_duration(uint8_t **buf)
Definition: matroskaenc.c:1390
static int mkv_write_tag(AVFormatContext *s, AVDictionary *m, unsigned int elementid, unsigned int uid, ebml_master *tags)
Definition: matroskaenc.c:968
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:1414
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:998
#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:2064
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:1242
#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:145
#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:1218
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:169
enum AVMediaType avcodec_get_type(enum AVCodecID codec_id)
Get the type of the given codec.
Definition: utils.c:2396
static int mkv_write_chapters(AVFormatContext *s)
Definition: matroskaenc.c:892
#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:1868
static void mkv_write_block(AVFormatContext *s, AVIOContext *pb, unsigned int blockid, AVPacket *pkt, int flags)
Definition: matroskaenc.c:1344
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:1229
#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:1692
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:1807
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 MATROSKA_ID_EDITIONENTRY
Definition: matroska.h:191
#define FF_COMPLIANCE_NORMAL
Definition: avcodec.h:2360
#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:871
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
#define CONFIG_LIBX264_ENCODER
Definition: config.h:1073
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:1446
#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:1291
static int ass_get_duration(const uint8_t *p)
Definition: matroskaenc.c:1229
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
#define CONFIG_LIBVORBIS_ENCODER
Definition: config.h:1068
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:353
#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:1592
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:726
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:1568
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:1808
#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:1431
static const AVOption options[]
Definition: matroskaenc.c:1694
#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:1501
#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:1675
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