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 mkv_cuepoint {
71  uint64_t pts;
72  int tracknum;
73  int64_t cluster_pos;
74 } mkv_cuepoint;
75 
76 typedef struct mkv_cues {
77  int64_t segment_offset;
80 } mkv_cues;
81 
82 typedef struct mkv_track {
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 
109 
112  int64_t cues_pos;
116 
117 
120 #define MAX_SEEKENTRY_SIZE 21
121 
124 #define MAX_CUETRACKPOS_SIZE 22
125 
127 #define MAX_CUEPOINT_SIZE(num_tracks) 12 + MAX_CUETRACKPOS_SIZE * num_tracks
128 
129 static int ebml_id_size(unsigned int id)
130 {
131  return (av_log2(id + 1) - 1) / 7 + 1;
132 }
133 
134 static void put_ebml_id(AVIOContext *pb, unsigned int id)
135 {
136  int i = ebml_id_size(id);
137  while (i--)
138  avio_w8(pb, id >> (i * 8));
139 }
140 
146 static void put_ebml_size_unknown(AVIOContext *pb, int bytes)
147 {
148  assert(bytes <= 8);
149  avio_w8(pb, 0x1ff >> bytes);
150  while (--bytes)
151  avio_w8(pb, 0xff);
152 }
153 
157 static int ebml_num_size(uint64_t num)
158 {
159  int bytes = 1;
160  while ((num + 1) >> bytes * 7)
161  bytes++;
162  return bytes;
163 }
164 
171 static void put_ebml_num(AVIOContext *pb, uint64_t num, int bytes)
172 {
173  int i, needed_bytes = ebml_num_size(num);
174 
175  // sizes larger than this are currently undefined in EBML
176  assert(num < (1ULL << 56) - 1);
177 
178  if (bytes == 0)
179  // don't care how many bytes are used, so use the min
180  bytes = needed_bytes;
181  // the bytes needed to write the given size would exceed the bytes
182  // that we need to use, so write unknown size. This shouldn't happen.
183  assert(bytes >= needed_bytes);
184 
185  num |= 1ULL << bytes * 7;
186  for (i = bytes - 1; i >= 0; i--)
187  avio_w8(pb, num >> i * 8);
188 }
189 
190 static void put_ebml_uint(AVIOContext *pb, unsigned int elementid, uint64_t val)
191 {
192  int i, bytes = 1;
193  uint64_t tmp = val;
194  while (tmp >>= 8)
195  bytes++;
196 
197  put_ebml_id(pb, elementid);
198  put_ebml_num(pb, bytes, 0);
199  for (i = bytes - 1; i >= 0; i--)
200  avio_w8(pb, val >> i * 8);
201 }
202 
203 static void put_ebml_float(AVIOContext *pb, unsigned int elementid, double val)
204 {
205  put_ebml_id(pb, elementid);
206  put_ebml_num(pb, 8, 0);
207  avio_wb64(pb, av_double2int(val));
208 }
209 
210 static void put_ebml_binary(AVIOContext *pb, unsigned int elementid,
211  const void *buf, int size)
212 {
213  put_ebml_id(pb, elementid);
214  put_ebml_num(pb, size, 0);
215  avio_write(pb, buf, size);
216 }
217 
218 static void put_ebml_string(AVIOContext *pb, unsigned int elementid,
219  const char *str)
220 {
221  put_ebml_binary(pb, elementid, str, strlen(str));
222 }
223 
230 static void put_ebml_void(AVIOContext *pb, uint64_t size)
231 {
232  int64_t currentpos = avio_tell(pb);
233 
234  assert(size >= 2);
235 
237  // we need to subtract the length needed to store the size from the
238  // size we need to reserve so 2 cases, we use 8 bytes to store the
239  // size if possible, 1 byte otherwise
240  if (size < 10)
241  put_ebml_num(pb, size - 1, 0);
242  else
243  put_ebml_num(pb, size - 9, 8);
244  while (avio_tell(pb) < currentpos + size)
245  avio_w8(pb, 0);
246 }
247 
248 static ebml_master start_ebml_master(AVIOContext *pb, unsigned int elementid,
249  uint64_t expectedsize)
250 {
251  int bytes = expectedsize ? ebml_num_size(expectedsize) : 8;
252  put_ebml_id(pb, elementid);
253  put_ebml_size_unknown(pb, bytes);
254  return (ebml_master) {avio_tell(pb), bytes };
255 }
256 
257 static void end_ebml_master(AVIOContext *pb, ebml_master master)
258 {
259  int64_t pos = avio_tell(pb);
260 
261  if (avio_seek(pb, master.pos - master.sizebytes, SEEK_SET) < 0)
262  return;
263  put_ebml_num(pb, pos - master.pos, master.sizebytes);
264  avio_seek(pb, pos, SEEK_SET);
265 }
266 
267 static void put_xiph_size(AVIOContext *pb, int size)
268 {
269  int i;
270  for (i = 0; i < size / 255; i++)
271  avio_w8(pb, 255);
272  avio_w8(pb, size % 255);
273 }
274 
286 static mkv_seekhead *mkv_start_seekhead(AVIOContext *pb, int64_t segment_offset,
287  int numelements)
288 {
289  mkv_seekhead *new_seekhead = av_mallocz(sizeof(mkv_seekhead));
290  if (!new_seekhead)
291  return NULL;
292 
293  new_seekhead->segment_offset = segment_offset;
294 
295  if (numelements > 0) {
296  new_seekhead->filepos = avio_tell(pb);
297  // 21 bytes max for a seek entry, 10 bytes max for the SeekHead ID
298  // and size, and 3 bytes to guarantee that an EBML void element
299  // will fit afterwards
300  new_seekhead->reserved_size = numelements * MAX_SEEKENTRY_SIZE + 13;
301  new_seekhead->max_entries = numelements;
302  put_ebml_void(pb, new_seekhead->reserved_size);
303  }
304  return new_seekhead;
305 }
306 
307 static int mkv_add_seekhead_entry(mkv_seekhead *seekhead, unsigned int elementid, uint64_t filepos)
308 {
309  int err;
310 
311  // don't store more elements than we reserved space for
312  if (seekhead->max_entries > 0 && seekhead->max_entries <= seekhead->num_entries)
313  return -1;
314 
315  if ((err = av_reallocp_array(&seekhead->entries, seekhead->num_entries + 1,
316  sizeof(*seekhead->entries))) < 0) {
317  seekhead->num_entries = 0;
318  return err;
319  }
320 
321  seekhead->entries[seekhead->num_entries].elementid = elementid;
322  seekhead->entries[seekhead->num_entries++].segmentpos = filepos - seekhead->segment_offset;
323 
324  return 0;
325 }
326 
336 static int64_t mkv_write_seekhead(AVIOContext *pb, mkv_seekhead *seekhead)
337 {
338  ebml_master metaseek, seekentry;
339  int64_t currentpos;
340  int i;
341 
342  currentpos = avio_tell(pb);
343 
344  if (seekhead->reserved_size > 0) {
345  if (avio_seek(pb, seekhead->filepos, SEEK_SET) < 0) {
346  currentpos = -1;
347  goto fail;
348  }
349  }
350 
351  metaseek = start_ebml_master(pb, MATROSKA_ID_SEEKHEAD, seekhead->reserved_size);
352  for (i = 0; i < seekhead->num_entries; i++) {
353  mkv_seekhead_entry *entry = &seekhead->entries[i];
354 
356 
358  put_ebml_num(pb, ebml_id_size(entry->elementid), 0);
359  put_ebml_id(pb, entry->elementid);
360 
362  end_ebml_master(pb, seekentry);
363  }
364  end_ebml_master(pb, metaseek);
365 
366  if (seekhead->reserved_size > 0) {
367  uint64_t remaining = seekhead->filepos + seekhead->reserved_size - avio_tell(pb);
368  put_ebml_void(pb, remaining);
369  avio_seek(pb, currentpos, SEEK_SET);
370 
371  currentpos = seekhead->filepos;
372  }
373 fail:
374  av_free(seekhead->entries);
375  av_free(seekhead);
376 
377  return currentpos;
378 }
379 
380 static mkv_cues *mkv_start_cues(int64_t segment_offset)
381 {
382  mkv_cues *cues = av_mallocz(sizeof(mkv_cues));
383  if (!cues)
384  return NULL;
385 
386  cues->segment_offset = segment_offset;
387  return cues;
388 }
389 
390 static int mkv_add_cuepoint(mkv_cues *cues, int stream, int64_t ts, int64_t cluster_pos)
391 {
392  int err;
393 
394  if (ts < 0)
395  return 0;
396 
397  if ((err = av_reallocp_array(&cues->entries, cues->num_entries + 1,
398  sizeof(*cues->entries))) < 0) {
399  cues->num_entries = 0;
400  return err;
401  }
402 
403  cues->entries[cues->num_entries].pts = ts;
404  cues->entries[cues->num_entries].tracknum = stream + 1;
405  cues->entries[cues->num_entries++].cluster_pos = cluster_pos - cues->segment_offset;
406 
407  return 0;
408 }
409 
410 static int64_t mkv_write_cues(AVIOContext *pb, mkv_cues *cues, int num_tracks)
411 {
412  ebml_master cues_element;
413  int64_t currentpos;
414  int i, j;
415 
416  currentpos = avio_tell(pb);
417  cues_element = start_ebml_master(pb, MATROSKA_ID_CUES, 0);
418 
419  for (i = 0; i < cues->num_entries; i++) {
420  ebml_master cuepoint, track_positions;
421  mkv_cuepoint *entry = &cues->entries[i];
422  uint64_t pts = entry->pts;
423 
424  cuepoint = start_ebml_master(pb, MATROSKA_ID_POINTENTRY, MAX_CUEPOINT_SIZE(num_tracks));
426 
427  // put all the entries from different tracks that have the exact same
428  // timestamp into the same CuePoint
429  for (j = 0; j < cues->num_entries - i && entry[j].pts == pts; j++) {
431  put_ebml_uint(pb, MATROSKA_ID_CUETRACK , entry[j].tracknum );
432  put_ebml_uint(pb, MATROSKA_ID_CUECLUSTERPOSITION, entry[j].cluster_pos);
433  end_ebml_master(pb, track_positions);
434  }
435  i += j - 1;
436  end_ebml_master(pb, cuepoint);
437  }
438  end_ebml_master(pb, cues_element);
439 
440  return currentpos;
441 }
442 
444 {
445  uint8_t *header_start[3];
446  int header_len[3];
447  int first_header_size;
448  int j;
449 
450  if (par->codec_id == AV_CODEC_ID_VORBIS)
451  first_header_size = 30;
452  else
453  first_header_size = 42;
454 
456  first_header_size, header_start, header_len) < 0) {
457  av_log(s, AV_LOG_ERROR, "Extradata corrupt.\n");
458  return -1;
459  }
460 
461  avio_w8(pb, 2); // number packets - 1
462  for (j = 0; j < 2; j++) {
463  put_xiph_size(pb, header_len[j]);
464  }
465  for (j = 0; j < 3; j++)
466  avio_write(pb, header_start[j], header_len[j]);
467 
468  return 0;
469 }
470 
472 {
473  if (par->extradata && par->extradata_size == 2)
474  avio_write(pb, par->extradata, 2);
475  else
476  avio_wl16(pb, 0x403); // fallback to the version mentioned in matroska specs
477  return 0;
478 }
479 
481  AVIOContext *pb, AVCodecParameters *par)
482 {
483  int write_comment = (par->channel_layout &&
484  !(par->channel_layout & ~0x3ffffULL) &&
486  int ret = ff_flac_write_header(pb, par->extradata, par->extradata_size,
487  !write_comment);
488 
489  if (ret < 0)
490  return ret;
491 
492  if (write_comment) {
493  const char *vendor = (s->flags & AVFMT_FLAG_BITEXACT) ?
494  "Libav" : LIBAVFORMAT_IDENT;
495  AVDictionary *dict = NULL;
496  uint8_t buf[32], *data, *p;
497  int len;
498 
499  snprintf(buf, sizeof(buf), "0x%"PRIx64, par->channel_layout);
500  av_dict_set(&dict, "WAVEFORMATEXTENSIBLE_CHANNEL_MASK", buf, 0);
501 
502  len = ff_vorbiscomment_length(dict, vendor);
503  data = av_malloc(len + 4);
504  if (!data) {
505  av_dict_free(&dict);
506  return AVERROR(ENOMEM);
507  }
508 
509  data[0] = 0x84;
510  AV_WB24(data + 1, len);
511 
512  p = data + 4;
513  ff_vorbiscomment_write(&p, &dict, vendor);
514 
515  avio_write(pb, data, len + 4);
516 
517  av_freep(&data);
518  av_dict_free(&dict);
519  }
520 
521  return 0;
522 }
523 
525  int *sample_rate, int *output_sample_rate)
526 {
527  MPEG4AudioConfig mp4ac;
528 
529  if (avpriv_mpeg4audio_get_config(&mp4ac, par->extradata,
530  par->extradata_size * 8, 1) < 0) {
531  av_log(s, AV_LOG_ERROR,
532  "Error parsing AAC extradata, unable to determine samplerate.\n");
533  return AVERROR(EINVAL);
534  }
535 
536  *sample_rate = mp4ac.sample_rate;
537  *output_sample_rate = mp4ac.ext_sample_rate;
538  return 0;
539 }
540 
542  AVCodecParameters *par,
543  AVIOContext *dyn_cp)
544 {
545  switch (par->codec_id) {
546  case AV_CODEC_ID_VORBIS:
547  case AV_CODEC_ID_THEORA:
548  return put_xiph_codecpriv(s, dyn_cp, par);
549  case AV_CODEC_ID_FLAC:
550  return put_flac_codecpriv(s, dyn_cp, par);
551  case AV_CODEC_ID_WAVPACK:
552  return put_wv_codecpriv(dyn_cp, par);
553  case AV_CODEC_ID_H264:
554  return ff_isom_write_avcc(dyn_cp, par->extradata,
555  par->extradata_size);
556  case AV_CODEC_ID_HEVC:
557  return ff_isom_write_hvcc(dyn_cp, par->extradata,
558  par->extradata_size, 0);
559  case AV_CODEC_ID_ALAC:
560  if (par->extradata_size < 36) {
561  av_log(s, AV_LOG_ERROR,
562  "Invalid extradata found, ALAC expects a 36-byte "
563  "QuickTime atom.");
564  return AVERROR_INVALIDDATA;
565  } else
566  avio_write(dyn_cp, par->extradata + 12,
567  par->extradata_size - 12);
568  break;
569  default:
570  if (par->extradata_size)
571  avio_write(dyn_cp, par->extradata, par->extradata_size);
572  }
573 
574  return 0;
575 }
576 
578  AVCodecParameters *par,
579  int native_id, int qt_id)
580 {
581  AVIOContext *dyn_cp;
582  uint8_t *codecpriv;
583  int ret, codecpriv_size;
584 
585  ret = avio_open_dyn_buf(&dyn_cp);
586  if (ret < 0)
587  return ret;
588 
589  if (native_id) {
590  ret = mkv_write_native_codecprivate(s, par, dyn_cp);
591  } else if (par->codec_type == AVMEDIA_TYPE_VIDEO) {
592  if (qt_id) {
593  if (!par->codec_tag)
595  par->codec_id);
596  if (par->extradata_size)
597  avio_write(dyn_cp, par->extradata, par->extradata_size);
598  } else {
599  if (!par->codec_tag)
601  par->codec_id);
602  if (!par->codec_tag) {
603  av_log(s, AV_LOG_ERROR, "No bmp codec ID found.\n");
604  ret = -1;
605  }
606 
607  ff_put_bmp_header(dyn_cp, par, ff_codec_bmp_tags, 0);
608  }
609  } else if (par->codec_type == AVMEDIA_TYPE_AUDIO) {
610  unsigned int tag;
612  if (!tag) {
613  av_log(s, AV_LOG_ERROR, "No wav codec ID found.\n");
614  ret = -1;
615  }
616  if (!par->codec_tag)
617  par->codec_tag = tag;
618 
619  ff_put_wav_header(s, dyn_cp, par);
620  }
621 
622  codecpriv_size = avio_close_dyn_buf(dyn_cp, &codecpriv);
623  if (codecpriv_size)
625  codecpriv_size);
626  av_free(codecpriv);
627  return ret;
628 }
629 
631  enum AVFieldOrder field_order)
632 {
633  switch (field_order) {
634  case AV_FIELD_UNKNOWN:
637  break;
641  break;
642  case AV_FIELD_TT:
643  case AV_FIELD_BB:
644  case AV_FIELD_TB:
645  case AV_FIELD_BT:
648  switch (field_order) {
649  case AV_FIELD_TT:
652  break;
653  case AV_FIELD_BB:
656  break;
657  case AV_FIELD_TB:
660  break;
661  case AV_FIELD_BT:
664  break;
665  }
666  }
667 }
668 
670  AVStream *st, int mode)
671 {
672  int i;
673  int display_width, display_height;
674  int h_width = 1, h_height = 1;
675  AVCodecParameters *par = st->codecpar;
678 
679  // convert metadata into proper side data and add it to the stream
680  if ((tag = av_dict_get(s->metadata, "stereo_mode", NULL, 0))) {
681  int stereo_mode = atoi(tag->value);
682  if (stereo_mode < MATROSKA_VIDEO_STEREOMODE_TYPE_NB &&
683  stereo_mode != 10 && stereo_mode != 12) {
684  int ret = ff_mkv_stereo3d_conv(st, stereo_mode);
685  if (ret < 0)
686  return ret;
687  }
688  }
689 
690  // iterate to find the stereo3d side data
691  for (i = 0; i < st->nb_side_data; i++) {
692  AVPacketSideData sd = st->side_data[i];
693  if (sd.type == AV_PKT_DATA_STEREO3D) {
694  AVStereo3D *stereo = (AVStereo3D *)sd.data;
695 
696  switch (stereo->type) {
697  case AV_STEREO3D_2D:
699  break;
701  format = (stereo->flags & AV_STEREO3D_FLAG_INVERT)
704  h_width = 2;
705  break;
708  if (stereo->flags & AV_STEREO3D_FLAG_INVERT)
709  format--;
710  h_height = 2;
711  break;
714  if (stereo->flags & AV_STEREO3D_FLAG_INVERT)
715  format--;
716  break;
717  case AV_STEREO3D_LINES:
719  if (stereo->flags & AV_STEREO3D_FLAG_INVERT)
720  format--;
721  h_height = 2;
722  break;
723  case AV_STEREO3D_COLUMNS:
725  if (stereo->flags & AV_STEREO3D_FLAG_INVERT)
726  format--;
727  h_width = 2;
728  break;
731  if (stereo->flags & AV_STEREO3D_FLAG_INVERT)
732  format++;
733  break;
734  }
735 
736  break;
737  }
738  }
739 
740  // if webm, do not write unsupported modes
741  if (mode == MODE_WEBM &&
745 
746  // write StereoMode if format is valid
749 
750  // write DisplayWidth and DisplayHeight, they contain the size of
751  // a single source view and/or the display aspect ratio
752  display_width = par->width / h_width;
753  display_height = par->height / h_height;
754  if (st->sample_aspect_ratio.num) {
755  display_width *= av_q2d(st->sample_aspect_ratio);
757  }
758  if (st->sample_aspect_ratio.num ||
760  put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYWIDTH, display_width);
761  put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYHEIGHT, display_height);
762  }
763 
764  return 0;
765 }
766 
768  int i, AVIOContext *pb)
769 {
770  AVStream *st = s->streams[i];
771  AVCodecParameters *par = st->codecpar;
772  ebml_master subinfo, track;
773  int native_id = 0;
774  int qt_id = 0;
775  int bit_depth = av_get_bits_per_sample(par->codec_id);
776  int sample_rate = par->sample_rate;
777  int output_sample_rate = 0;
778  int j, ret;
780 
781  // ms precision is the de-facto standard timescale for mkv files
782  avpriv_set_pts_info(st, 64, 1, 1000);
783 
784  if (par->codec_type == AVMEDIA_TYPE_ATTACHMENT) {
785  mkv->have_attachments = 1;
786  return 0;
787  }
788 
789  if (!bit_depth)
790  bit_depth = av_get_bytes_per_sample(par->format) << 3;
791 
792  if (par->codec_id == AV_CODEC_ID_AAC) {
793  ret = get_aac_sample_rates(s, par, &sample_rate, &output_sample_rate);
794  if (ret < 0)
795  return ret;
796  }
797 
800  put_ebml_uint (pb, MATROSKA_ID_TRACKUID , i + 1);
801  put_ebml_uint (pb, MATROSKA_ID_TRACKFLAGLACING , 0); // no lacing (yet)
802 
803  if ((tag = av_dict_get(st->metadata, "title", NULL, 0)))
805  tag = av_dict_get(st->metadata, "language", NULL, 0);
806  put_ebml_string(pb, MATROSKA_ID_TRACKLANGUAGE, tag ? tag->value:"und");
807 
808  // The default value for TRACKFLAGDEFAULT is 1, so add element
809  // if we need to clear it.
810  if (!(st->disposition & AV_DISPOSITION_DEFAULT))
814 
815  if (par->codec_type == AVMEDIA_TYPE_AUDIO && par->initial_padding) {
817  (AVRational){ 1, par->sample_rate },
818  st->time_base);
819 
822  (AVRational){ 1, par->sample_rate },
823  (AVRational){ 1, 1000000000 }));
824  }
825 
826  // look for a codec ID string specific to mkv to use,
827  // if none are found, use AVI codes
828  for (j = 0; ff_mkv_codec_tags[j].id != AV_CODEC_ID_NONE; j++) {
829  if (ff_mkv_codec_tags[j].id == par->codec_id) {
831  native_id = 1;
832  break;
833  }
834  }
835 
836  if (mkv->mode == MODE_WEBM && !(par->codec_id == AV_CODEC_ID_VP8 ||
837  par->codec_id == AV_CODEC_ID_VP9 ||
838  par->codec_id == AV_CODEC_ID_OPUS ||
839  par->codec_id == AV_CODEC_ID_VORBIS)) {
840  av_log(s, AV_LOG_ERROR,
841  "Only VP8 or VP9 video and Vorbis or Opus audio are supported for WebM.\n");
842  return AVERROR(EINVAL);
843  }
844 
845  switch (par->codec_type) {
846  case AVMEDIA_TYPE_VIDEO:
847  mkv->have_video = 1;
849  if (st->avg_frame_rate.num > 0 && st->avg_frame_rate.den > 0)
851 
852  if (!native_id &&
855  par->codec_id == AV_CODEC_ID_SVQ1 ||
856  par->codec_id == AV_CODEC_ID_SVQ3 ||
857  par->codec_id == AV_CODEC_ID_CINEPAK))
858  qt_id = 1;
859 
860  if (qt_id)
861  put_ebml_string(pb, MATROSKA_ID_CODECID, "V_QUICKTIME");
862  else if (!native_id) {
863  // if there is no mkv-specific codec ID, use VFW mode
864  put_ebml_string(pb, MATROSKA_ID_CODECID, "V_MS/VFW/FOURCC");
865  mkv->tracks[i].write_dts = 1;
866  }
867 
868  subinfo = start_ebml_master(pb, MATROSKA_ID_TRACKVIDEO, 0);
869 
872 
874 
875  // check both side data and metadata for stereo information,
876  // write the result to the bitstream if any is found
877  ret = mkv_write_stereo_mode(s, pb, st, mkv->mode);
878  if (ret < 0)
879  return ret;
880 
881  end_ebml_master(pb, subinfo);
882  break;
883 
884  case AVMEDIA_TYPE_AUDIO:
886 
887  if (!native_id)
888  // no mkv-specific ID, use ACM mode
889  put_ebml_string(pb, MATROSKA_ID_CODECID, "A_MS/ACM");
890 
891  subinfo = start_ebml_master(pb, MATROSKA_ID_TRACKAUDIO, 0);
894  if (output_sample_rate)
895  put_ebml_float(pb, MATROSKA_ID_AUDIOOUTSAMPLINGFREQ, output_sample_rate);
896  if (bit_depth)
898  end_ebml_master(pb, subinfo);
899  break;
900 
903  if (!native_id) {
904  av_log(s, AV_LOG_ERROR, "Subtitle codec %d is not supported.\n", par->codec_id);
905  return AVERROR(ENOSYS);
906  }
907  break;
908  default:
909  av_log(s, AV_LOG_ERROR, "Only audio, video, and subtitles are supported for Matroska.\n");
910  break;
911  }
912  ret = mkv_write_codecprivate(s, pb, par, native_id, qt_id);
913  if (ret < 0)
914  return ret;
915 
916  end_ebml_master(pb, track);
917 
918  return 0;
919 }
920 
922 {
923  MatroskaMuxContext *mkv = s->priv_data;
924  AVIOContext *pb = s->pb;
925  ebml_master tracks;
926  int i, ret;
927 
929  if (ret < 0)
930  return ret;
931 
932  tracks = start_ebml_master(pb, MATROSKA_ID_TRACKS, 0);
933  for (i = 0; i < s->nb_streams; i++) {
934  ret = mkv_write_track(s, mkv, i, pb);
935  if (ret < 0)
936  return ret;
937  }
938  end_ebml_master(pb, tracks);
939  return 0;
940 }
941 
943 {
944  MatroskaMuxContext *mkv = s->priv_data;
945  AVIOContext *pb = s->pb;
946  ebml_master chapters, editionentry;
947  AVRational scale = {1, 1E9};
948  int i, ret;
949 
950  if (!s->nb_chapters || mkv->wrote_chapters)
951  return 0;
952 
954  if (ret < 0) return ret;
955 
956  chapters = start_ebml_master(pb, MATROSKA_ID_CHAPTERS , 0);
957  editionentry = start_ebml_master(pb, MATROSKA_ID_EDITIONENTRY, 0);
960  for (i = 0; i < s->nb_chapters; i++) {
961  ebml_master chapteratom, chapterdisplay;
962  AVChapter *c = s->chapters[i];
963  int64_t chapterstart = av_rescale_q(c->start, c->time_base, scale);
964  int64_t chapterend = av_rescale_q(c->end, c->time_base, scale);
965  AVDictionaryEntry *t = NULL;
966  if (chapterstart < 0 || chapterstart > chapterend || chapterend < 0) {
967  av_log(s, AV_LOG_ERROR,
968  "Invalid chapter start (%"PRId64") or end (%"PRId64").\n",
969  chapterstart, chapterend);
970  return AVERROR_INVALIDDATA;
971  }
972 
973  chapteratom = start_ebml_master(pb, MATROSKA_ID_CHAPTERATOM, 0);
975  put_ebml_uint(pb, MATROSKA_ID_CHAPTERTIMESTART, chapterstart);
976  put_ebml_uint(pb, MATROSKA_ID_CHAPTERTIMEEND, chapterend);
979  if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
980  chapterdisplay = start_ebml_master(pb, MATROSKA_ID_CHAPTERDISPLAY, 0);
983  end_ebml_master(pb, chapterdisplay);
984  }
985  end_ebml_master(pb, chapteratom);
986  }
987  end_ebml_master(pb, editionentry);
988  end_ebml_master(pb, chapters);
989 
990  mkv->wrote_chapters = 1;
991  return 0;
992 }
993 
995 {
996  uint8_t *key = av_strdup(t->key);
997  uint8_t *p = key;
998  const uint8_t *lang = NULL;
1000 
1001  if (!key)
1002  return AVERROR(ENOMEM);
1003 
1004  if ((p = strrchr(p, '-')) &&
1005  (lang = av_convert_lang_to(p + 1, AV_LANG_ISO639_2_BIBL)))
1006  *p = 0;
1007 
1008  p = key;
1009  while (*p) {
1010  if (*p == ' ')
1011  *p = '_';
1012  else if (*p >= 'a' && *p <= 'z')
1013  *p -= 'a' - 'A';
1014  p++;
1015  }
1016 
1019  if (lang)
1022  end_ebml_master(pb, tag);
1023 
1024  av_freep(&key);
1025  return 0;
1026 }
1027 
1028 static int mkv_write_tag(AVFormatContext *s, AVDictionary *m, unsigned int elementid,
1029  unsigned int uid, ebml_master *tags)
1030 {
1031  MatroskaMuxContext *mkv = s->priv_data;
1032  ebml_master tag, targets;
1033  AVDictionaryEntry *t = NULL;
1034  int ret;
1035 
1036  if (!tags->pos) {
1038  if (ret < 0) return ret;
1039 
1040  *tags = start_ebml_master(s->pb, MATROSKA_ID_TAGS, 0);
1041  }
1042 
1043  tag = start_ebml_master(s->pb, MATROSKA_ID_TAG, 0);
1044  targets = start_ebml_master(s->pb, MATROSKA_ID_TAGTARGETS, 0);
1045  if (elementid)
1046  put_ebml_uint(s->pb, elementid, uid);
1047  end_ebml_master(s->pb, targets);
1048 
1049  while ((t = av_dict_get(m, "", t, AV_DICT_IGNORE_SUFFIX))) {
1050  if (av_strcasecmp(t->key, "title") &&
1051  av_strcasecmp(t->key, "encoding_tool") &&
1052  (elementid != MATROSKA_ID_TAGTARGETS_TRACKUID ||
1053  av_strcasecmp(t->key, "language"))) {
1054  ret = mkv_write_simpletag(s->pb, t);
1055  if (ret < 0)
1056  return ret;
1057  }
1058  }
1059 
1060  end_ebml_master(s->pb, tag);
1061  return 0;
1062 }
1063 
1065 {
1066  ebml_master tags = {0};
1067  int i, ret;
1068 
1070 
1072  ret = mkv_write_tag(s, s->metadata, 0, 0, &tags);
1073  if (ret < 0) return ret;
1074  }
1075 
1076  for (i = 0; i < s->nb_streams; i++) {
1077  AVStream *st = s->streams[i];
1078 
1079  if (!av_dict_get(st->metadata, "", 0, AV_DICT_IGNORE_SUFFIX))
1080  continue;
1081 
1082  ret = mkv_write_tag(s, st->metadata, MATROSKA_ID_TAGTARGETS_TRACKUID, i + 1, &tags);
1083  if (ret < 0) return ret;
1084  }
1085 
1086  for (i = 0; i < s->nb_chapters; i++) {
1087  AVChapter *ch = s->chapters[i];
1088 
1090  continue;
1091 
1092  ret = mkv_write_tag(s, ch->metadata, MATROSKA_ID_TAGTARGETS_CHAPTERUID, ch->id, &tags);
1093  if (ret < 0) return ret;
1094  }
1095 
1096  if (tags.pos)
1097  end_ebml_master(s->pb, tags);
1098  return 0;
1099 }
1100 
1102 {
1103  MatroskaMuxContext *mkv = s->priv_data;
1104  AVIOContext *pb = s->pb;
1105  ebml_master attachments;
1106  AVLFG c;
1107  int i, ret;
1108 
1109  if (!mkv->have_attachments)
1110  return 0;
1111 
1113 
1115  if (ret < 0) return ret;
1116 
1117  attachments = start_ebml_master(pb, MATROSKA_ID_ATTACHMENTS, 0);
1118 
1119  for (i = 0; i < s->nb_streams; i++) {
1120  AVStream *st = s->streams[i];
1121  ebml_master attached_file;
1122  AVDictionaryEntry *t;
1123  const char *mimetype = NULL;
1124 
1126  continue;
1127 
1128  attached_file = start_ebml_master(pb, MATROSKA_ID_ATTACHEDFILE, 0);
1129 
1130  if (t = av_dict_get(st->metadata, "title", NULL, 0))
1132  if (!(t = av_dict_get(st->metadata, "filename", NULL, 0))) {
1133  av_log(s, AV_LOG_ERROR, "Attachment stream %d has no filename tag.\n", i);
1134  return AVERROR(EINVAL);
1135  }
1137  if (t = av_dict_get(st->metadata, "mimetype", NULL, 0))
1138  mimetype = t->value;
1139  else if (st->codecpar->codec_id != AV_CODEC_ID_NONE ) {
1140  int i;
1141  for (i = 0; ff_mkv_mime_tags[i].id != AV_CODEC_ID_NONE; i++)
1142  if (ff_mkv_mime_tags[i].id == st->codecpar->codec_id) {
1143  mimetype = ff_mkv_mime_tags[i].str;
1144  break;
1145  }
1146  for (i = 0; ff_mkv_image_mime_tags[i].id != AV_CODEC_ID_NONE; i++)
1147  if (ff_mkv_image_mime_tags[i].id == st->codecpar->codec_id) {
1148  mimetype = ff_mkv_image_mime_tags[i].str;
1149  break;
1150  }
1151  }
1152  if (!mimetype) {
1153  av_log(s, AV_LOG_ERROR, "Attachment stream %d has no mimetype tag and "
1154  "it cannot be deduced from the codec id.\n", i);
1155  return AVERROR(EINVAL);
1156  }
1157 
1161  end_ebml_master(pb, attached_file);
1162  }
1163  end_ebml_master(pb, attachments);
1164 
1165  return 0;
1166 }
1167 
1169 {
1170  MatroskaMuxContext *mkv = s->priv_data;
1171  AVIOContext *pb = s->pb;
1172  ebml_master ebml_header, segment_info;
1174  int ret, i;
1175 
1176  if (!strcmp(s->oformat->name, "webm"))
1177  mkv->mode = MODE_WEBM;
1178  else
1179  mkv->mode = MODE_MATROSKAv2;
1180 
1181  mkv->tracks = av_mallocz(s->nb_streams * sizeof(*mkv->tracks));
1182  if (!mkv->tracks)
1183  return AVERROR(ENOMEM);
1184 
1185  ebml_header = start_ebml_master(pb, EBML_ID_HEADER, 0);
1193  end_ebml_master(pb, ebml_header);
1194 
1196  mkv->segment_offset = avio_tell(pb);
1197 
1198  // we write 2 seek heads - one at the end of the file to point to each
1199  // cluster, and one at the beginning to point to all other level one
1200  // elements (including the seek head at the end of the file), which
1201  // isn't more than 10 elements if we only write one of each other
1202  // currently defined level 1 element
1203  mkv->main_seekhead = mkv_start_seekhead(pb, mkv->segment_offset, 10);
1204  if (!mkv->main_seekhead)
1205  return AVERROR(ENOMEM);
1206 
1208  if (ret < 0) return ret;
1209 
1210  segment_info = start_ebml_master(pb, MATROSKA_ID_INFO, 0);
1212  if ((tag = av_dict_get(s->metadata, "title", NULL, 0)))
1214  if (!(s->flags & AVFMT_FLAG_BITEXACT)) {
1215  uint32_t segment_uid[4];
1216  AVLFG lfg;
1217 
1219 
1220  for (i = 0; i < 4; i++)
1221  segment_uid[i] = av_lfg_get(&lfg);
1222 
1224  if ((tag = av_dict_get(s->metadata, "encoding_tool", NULL, 0)))
1226  else
1228  put_ebml_binary(pb, MATROSKA_ID_SEGMENTUID, segment_uid, 16);
1229  }
1230 
1231  // reserve space for the duration
1232  mkv->duration = 0;
1233  mkv->duration_offset = avio_tell(pb);
1234  put_ebml_void(pb, 11); // assumes double-precision float to be written
1235  end_ebml_master(pb, segment_info);
1236 
1237  ret = mkv_write_tracks(s);
1238  if (ret < 0)
1239  return ret;
1240 
1241  if (mkv->mode != MODE_WEBM) {
1242  ret = mkv_write_chapters(s);
1243  if (ret < 0)
1244  return ret;
1245 
1246  ret = mkv_write_tags(s);
1247  if (ret < 0)
1248  return ret;
1249 
1250  ret = mkv_write_attachments(s);
1251  if (ret < 0)
1252  return ret;
1253  }
1254 
1255  if (!s->pb->seekable)
1257 
1258  mkv->cues = mkv_start_cues(mkv->segment_offset);
1259  if (!mkv->cues)
1260  return AVERROR(ENOMEM);
1261 
1262  if (pb->seekable && mkv->reserve_cues_space) {
1263  mkv->cues_pos = avio_tell(pb);
1265  }
1266 
1268  mkv->cur_audio_pkt.size = 0;
1269 
1270  avio_flush(pb);
1271 
1272  // start a new cluster every 5 MB or 5 sec, or 32k / 1 sec for streaming or
1273  // after 4k and on a keyframe
1274  if (pb->seekable) {
1275  if (mkv->cluster_time_limit < 0)
1276  mkv->cluster_time_limit = 5000;
1277  if (mkv->cluster_size_limit < 0)
1278  mkv->cluster_size_limit = 5 * 1024 * 1024;
1279  } else {
1280  if (mkv->cluster_time_limit < 0)
1281  mkv->cluster_time_limit = 1000;
1282  if (mkv->cluster_size_limit < 0)
1283  mkv->cluster_size_limit = 32 * 1024;
1284  }
1285 
1286  return 0;
1287 }
1288 
1289 static int mkv_blockgroup_size(int pkt_size)
1290 {
1291  int size = pkt_size + 4;
1292  size += ebml_num_size(size);
1293  size += 2; // EBML ID for block and block duration
1294  size += 8; // max size of block duration
1295  size += ebml_num_size(size);
1296  size += 1; // blockgroup EBML ID
1297  return size;
1298 }
1299 
1300 static int ass_get_duration(AVFormatContext *s, const uint8_t *p)
1301 {
1302  int sh, sm, ss, sc, eh, em, es, ec;
1303  uint64_t start, end;
1304 
1305  if (sscanf(p, "%*[^,],%d:%d:%d%*c%d,%d:%d:%d%*c%d",
1306  &sh, &sm, &ss, &sc, &eh, &em, &es, &ec) != 8)
1307  return 0;
1308 
1309  if (sh > 9 || sm > 59 || ss > 59 || sc > 99 ||
1310  eh > 9 || em > 59 || es > 59 || ec > 99) {
1312  "Non-standard time reference %d:%d:%d.%d,%d:%d:%d.%d\n",
1313  sh, sm, ss, sc, eh, em, es, ec);
1314  return 0;
1315  }
1316 
1317  start = 3600000 * sh + 60000 * sm + 1000 * ss + 10 * sc;
1318  end = 3600000 * eh + 60000 * em + 1000 * es + 10 * ec;
1319 
1320  if (start > end) {
1322  "Unexpected time reference %d:%d:%d.%d,%d:%d:%d.%d\n",
1323  sh, sm, ss, sc, eh, em, es, ec);
1324  return 0;
1325  }
1326 
1327  return end - start;
1328 }
1329 
1331  AVPacket *pkt)
1332 {
1333  MatroskaMuxContext *mkv = s->priv_data;
1334  int i, layer = 0, max_duration = 0, size, line_size, data_size = pkt->size;
1335  uint8_t *start, *end, *data = pkt->data;
1336  ebml_master blockgroup;
1337  char buffer[2048];
1338 
1339  while (data_size) {
1340  int duration = ass_get_duration(s, data);
1341  max_duration = FFMAX(duration, max_duration);
1342  end = memchr(data, '\n', data_size);
1343  size = line_size = end ? end - data + 1 : data_size;
1344  size -= end ? (end[-1] == '\r') + 1 : 0;
1345  start = data;
1346  for (i = 0; i < 3; i++, start++)
1347  if (!(start = memchr(start, ',', size - (start - data))))
1348  return max_duration;
1349  size -= start - data;
1350  sscanf(data, "Dialogue: %d,", &layer);
1351  i = snprintf(buffer, sizeof(buffer), "%" PRId64 ",%d,",
1352  s->streams[pkt->stream_index]->nb_frames, layer);
1353  size = FFMIN(i + size, sizeof(buffer));
1354  memcpy(buffer + i, start, size - i);
1355 
1356  av_log(s, AV_LOG_DEBUG,
1357  "Writing block at offset %" PRIu64 ", size %d, "
1358  "pts %" PRId64 ", duration %d\n",
1359  avio_tell(pb), size, pkt->pts, duration);
1360  blockgroup = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP,
1363  put_ebml_num(pb, size + 4, 0);
1364  // this assumes stream_index is less than 126
1365  avio_w8(pb, 0x80 | (pkt->stream_index + 1));
1366  avio_wb16(pb, pkt->pts - mkv->cluster_pts);
1367  avio_w8(pb, 0);
1368  avio_write(pb, buffer, size);
1370  end_ebml_master(pb, blockgroup);
1371 
1372  data += line_size;
1373  data_size -= line_size;
1374  }
1375 
1376  return max_duration;
1377 }
1378 
1379 static int mkv_strip_wavpack(const uint8_t *src, uint8_t **pdst, int *size)
1380 {
1381  uint8_t *dst;
1382  int srclen = *size;
1383  int offset = 0;
1384  int ret;
1385 
1386  dst = av_malloc(srclen);
1387  if (!dst)
1388  return AVERROR(ENOMEM);
1389 
1390  while (srclen >= WV_HEADER_SIZE) {
1391  WvHeader header;
1392 
1393  ret = ff_wv_parse_header(&header, src);
1394  if (ret < 0)
1395  goto fail;
1396  src += WV_HEADER_SIZE;
1397  srclen -= WV_HEADER_SIZE;
1398 
1399  if (srclen < header.blocksize) {
1400  ret = AVERROR_INVALIDDATA;
1401  goto fail;
1402  }
1403 
1404  if (header.initial) {
1405  AV_WL32(dst + offset, header.samples);
1406  offset += 4;
1407  }
1408  AV_WL32(dst + offset, header.flags);
1409  AV_WL32(dst + offset + 4, header.crc);
1410  offset += 8;
1411 
1412  if (!(header.initial && header.final)) {
1413  AV_WL32(dst + offset, header.blocksize);
1414  offset += 4;
1415  }
1416 
1417  memcpy(dst + offset, src, header.blocksize);
1418  src += header.blocksize;
1419  srclen -= header.blocksize;
1420  offset += header.blocksize;
1421  }
1422 
1423  *pdst = dst;
1424  *size = offset;
1425 
1426  return 0;
1427 fail:
1428  av_freep(&dst);
1429  return ret;
1430 }
1431 
1433  unsigned int blockid, AVPacket *pkt, int flags)
1434 {
1435  MatroskaMuxContext *mkv = s->priv_data;
1437  uint8_t *data = NULL;
1438  int offset = 0, size = pkt->size;
1439  int64_t ts = mkv->tracks[pkt->stream_index].write_dts ? pkt->dts : pkt->pts;
1440 
1441  av_log(s, AV_LOG_DEBUG, "Writing block at offset %" PRIu64 ", size %d, "
1442  "pts %" PRId64 ", dts %" PRId64 ", duration %" PRId64 ", flags %d\n",
1443  avio_tell(pb), pkt->size, pkt->pts, pkt->dts, pkt->duration, flags);
1444  if (par->codec_id == AV_CODEC_ID_H264 && par->extradata_size > 0 &&
1445  (AV_RB24(par->extradata) == 1 || AV_RB32(par->extradata) == 1))
1446  ff_avc_parse_nal_units_buf(pkt->data, &data, &size);
1447  else if (par->codec_id == AV_CODEC_ID_HEVC && par->extradata_size > 6 &&
1448  (AV_RB24(par->extradata) == 1 || AV_RB32(par->extradata) == 1))
1449  /* extradata is Annex B, assume the bitstream is too and convert it */
1450  ff_hevc_annexb2mp4_buf(pkt->data, &data, &size, 0, NULL);
1451  else if (par->codec_id == AV_CODEC_ID_WAVPACK) {
1452  int ret = mkv_strip_wavpack(pkt->data, &data, &size);
1453  if (ret < 0) {
1454  av_log(s, AV_LOG_ERROR, "Error stripping a WavPack packet.\n");
1455  return;
1456  }
1457  } else
1458  data = pkt->data;
1459 
1460  if (par->codec_id == AV_CODEC_ID_PRORES) {
1461  /* Matroska specification requires to remove the first QuickTime atom
1462  */
1463  size -= 8;
1464  offset = 8;
1465  }
1466 
1467  put_ebml_id(pb, blockid);
1468  put_ebml_num(pb, size + 4, 0);
1469  // this assumes stream_index is less than 126
1470  avio_w8(pb, 0x80 | (pkt->stream_index + 1));
1471  avio_wb16(pb, ts - mkv->cluster_pts);
1472  avio_w8(pb, flags);
1473  avio_write(pb, data + offset, size);
1474  if (data != pkt->data)
1475  av_free(data);
1476 }
1477 
1478 static int srt_get_duration(uint8_t **buf)
1479 {
1480  int i, duration = 0;
1481 
1482  for (i = 0; i < 2 && !duration; i++) {
1483  int s_hour, s_min, s_sec, s_hsec, e_hour, e_min, e_sec, e_hsec;
1484  if (sscanf(*buf, "%d:%2d:%2d%*1[,.]%3d --> %d:%2d:%2d%*1[,.]%3d",
1485  &s_hour, &s_min, &s_sec, &s_hsec,
1486  &e_hour, &e_min, &e_sec, &e_hsec) == 8) {
1487  s_min += 60 * s_hour;
1488  e_min += 60 * e_hour;
1489  s_sec += 60 * s_min;
1490 
1491  e_sec += 60 * e_min;
1492  s_hsec += 1000 * s_sec;
1493  e_hsec += 1000 * e_sec;
1494 
1495  duration = e_hsec - s_hsec;
1496  }
1497  *buf += strcspn(*buf, "\n") + 1;
1498  }
1499  return duration;
1500 }
1501 
1503  AVPacket *pkt)
1504 {
1505  ebml_master blockgroup;
1506  AVPacket pkt2 = *pkt;
1507  int64_t duration = srt_get_duration(&pkt2.data);
1508  pkt2.size -= pkt2.data - pkt->data;
1509 
1510  blockgroup = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP,
1511  mkv_blockgroup_size(pkt2.size));
1512  mkv_write_block(s, pb, MATROSKA_ID_BLOCK, &pkt2, 0);
1514  end_ebml_master(pb, blockgroup);
1515 
1516  return duration;
1517 }
1518 
1520 {
1521  MatroskaMuxContext *mkv = s->priv_data;
1522  int bufsize;
1523  uint8_t *dyn_buf;
1524 
1525  if (!mkv->dyn_bc)
1526  return;
1527 
1528  bufsize = avio_close_dyn_buf(mkv->dyn_bc, &dyn_buf);
1529  avio_write(s->pb, dyn_buf, bufsize);
1530  av_free(dyn_buf);
1531  mkv->dyn_bc = NULL;
1532 }
1533 
1535 {
1536  MatroskaMuxContext *mkv = s->priv_data;
1537  AVIOContext *pb = s->pb;
1539  int keyframe = !!(pkt->flags & AV_PKT_FLAG_KEY);
1540  int duration = pkt->duration;
1541  int ret;
1542  int64_t ts = mkv->tracks[pkt->stream_index].write_dts ? pkt->dts : pkt->pts;
1543 
1544  if (ts == AV_NOPTS_VALUE) {
1545  av_log(s, AV_LOG_ERROR, "Can't write packet with unknown timestamp\n");
1546  return AVERROR(EINVAL);
1547  }
1548  ts += mkv->tracks[pkt->stream_index].ts_offset;
1549 
1550  if (!s->pb->seekable) {
1551  if (!mkv->dyn_bc) {
1552  ret = avio_open_dyn_buf(&mkv->dyn_bc);
1553  if (ret < 0)
1554  return ret;
1555  }
1556  pb = mkv->dyn_bc;
1557  }
1558 
1559  if (!mkv->cluster_pos) {
1560  mkv->cluster_pos = avio_tell(s->pb);
1563  mkv->cluster_pts = FFMAX(0, ts);
1564  }
1565 
1566  if (par->codec_type != AVMEDIA_TYPE_SUBTITLE) {
1567  mkv_write_block(s, pb, MATROSKA_ID_SIMPLEBLOCK, pkt, keyframe << 7);
1568  } else if (par->codec_id == AV_CODEC_ID_SSA) {
1569  duration = mkv_write_ass_blocks(s, pb, pkt);
1570  } else if (par->codec_id == AV_CODEC_ID_SRT) {
1571  duration = mkv_write_srt_blocks(s, pb, pkt);
1572  } else {
1574  mkv_blockgroup_size(pkt->size));
1575  duration = pkt->duration;
1576 #if FF_API_CONVERGENCE_DURATION
1578  if (pkt->convergence_duration)
1579  duration = pkt->convergence_duration;
1581 #endif
1582  mkv_write_block(s, pb, MATROSKA_ID_BLOCK, pkt, 0);
1584  end_ebml_master(pb, blockgroup);
1585  }
1586 
1587  if (par->codec_type == AVMEDIA_TYPE_VIDEO && keyframe) {
1588  ret = mkv_add_cuepoint(mkv->cues, pkt->stream_index, ts,
1589  mkv->cluster_pos);
1590  if (ret < 0)
1591  return ret;
1592  }
1593 
1594  mkv->duration = FFMAX(mkv->duration, ts + duration);
1595  return 0;
1596 }
1597 
1599 {
1600  MatroskaMuxContext *mkv = s->priv_data;
1602  int keyframe = !!(pkt->flags & AV_PKT_FLAG_KEY);
1603  int cluster_size;
1604  int64_t cluster_time;
1605  AVIOContext *pb;
1606  int ret;
1607 
1608  if (mkv->tracks[pkt->stream_index].write_dts)
1609  cluster_time = pkt->dts - mkv->cluster_pts;
1610  else
1611  cluster_time = pkt->pts - mkv->cluster_pts;
1612  cluster_time += mkv->tracks[pkt->stream_index].ts_offset;
1613 
1614  // start a new cluster every 5 MB or 5 sec, or 32k / 1 sec for streaming or
1615  // after 4k and on a keyframe
1616  if (s->pb->seekable) {
1617  pb = s->pb;
1618  cluster_size = avio_tell(pb) - mkv->cluster_pos;
1619  } else {
1620  pb = mkv->dyn_bc;
1621  cluster_size = avio_tell(pb);
1622  }
1623 
1624  if (mkv->cluster_pos &&
1625  (cluster_size > mkv->cluster_size_limit ||
1626  cluster_time > mkv->cluster_time_limit ||
1627  (codec_type == AVMEDIA_TYPE_VIDEO && keyframe &&
1628  cluster_size > 4 * 1024))) {
1629  av_log(s, AV_LOG_DEBUG,
1630  "Starting new cluster at offset %" PRIu64 " bytes, "
1631  "pts %" PRIu64 "dts %" PRIu64 "\n",
1632  avio_tell(pb), pkt->pts, pkt->dts);
1633  end_ebml_master(pb, mkv->cluster);
1634  mkv->cluster_pos = 0;
1635  if (mkv->dyn_bc)
1636  mkv_flush_dynbuf(s);
1637  avio_flush(s->pb);
1638  }
1639 
1640  if (!mkv->cluster_pos)
1641  avio_write_marker(s->pb,
1644 
1645  // check if we have an audio packet cached
1646  if (mkv->cur_audio_pkt.size > 0) {
1647  ret = mkv_write_packet_internal(s, &mkv->cur_audio_pkt);
1649  if (ret < 0) {
1650  av_log(s, AV_LOG_ERROR,
1651  "Could not write cached audio packet ret:%d\n", ret);
1652  return ret;
1653  }
1654  }
1655 
1656  // buffer an audio packet to ensure the packet containing the video
1657  // keyframe's timecode is contained in the same cluster for WebM
1658  if (codec_type == AVMEDIA_TYPE_AUDIO) {
1659  ret = av_packet_ref(&mkv->cur_audio_pkt, pkt);
1660  } else
1661  ret = mkv_write_packet_internal(s, pkt);
1662  return ret;
1663 }
1664 
1666 {
1667  MatroskaMuxContext *mkv = s->priv_data;
1668  AVIOContext *pb;
1669  if (s->pb->seekable)
1670  pb = s->pb;
1671  else
1672  pb = mkv->dyn_bc;
1673  if (!pkt) {
1674  if (mkv->cluster_pos) {
1675  av_log(s, AV_LOG_DEBUG,
1676  "Flushing cluster at offset %" PRIu64 " bytes\n",
1677  avio_tell(pb));
1678  end_ebml_master(pb, mkv->cluster);
1679  mkv->cluster_pos = 0;
1680  if (mkv->dyn_bc)
1681  mkv_flush_dynbuf(s);
1682  avio_flush(s->pb);
1683  }
1684  return 1;
1685  }
1686  return mkv_write_packet(s, pkt);
1687 }
1688 
1690 {
1691  MatroskaMuxContext *mkv = s->priv_data;
1692  AVIOContext *pb = s->pb;
1693  int64_t currentpos, cuespos;
1694  int ret;
1695 
1696  // check if we have an audio packet cached
1697  if (mkv->cur_audio_pkt.size > 0) {
1698  ret = mkv_write_packet_internal(s, &mkv->cur_audio_pkt);
1700  if (ret < 0) {
1701  av_log(s, AV_LOG_ERROR,
1702  "Could not write cached audio packet ret:%d\n", ret);
1703  return ret;
1704  }
1705  }
1706 
1707  if (mkv->dyn_bc) {
1708  end_ebml_master(mkv->dyn_bc, mkv->cluster);
1709  mkv_flush_dynbuf(s);
1710  } else if (mkv->cluster_pos) {
1711  end_ebml_master(pb, mkv->cluster);
1712  }
1713 
1714  if (mkv->mode != MODE_WEBM) {
1715  ret = mkv_write_chapters(s);
1716  if (ret < 0)
1717  return ret;
1718  }
1719 
1720  if (pb->seekable) {
1721  if (mkv->cues->num_entries) {
1722  if (mkv->reserve_cues_space) {
1723  int64_t cues_end;
1724 
1725  currentpos = avio_tell(pb);
1726  avio_seek(pb, mkv->cues_pos, SEEK_SET);
1727 
1728  cuespos = mkv_write_cues(pb, mkv->cues, s->nb_streams);
1729  cues_end = avio_tell(pb);
1730  if (cues_end > cuespos + mkv->reserve_cues_space) {
1731  av_log(s, AV_LOG_ERROR,
1732  "Insufficient space reserved for cues: %d "
1733  "(needed: %" PRId64 ").\n",
1734  mkv->reserve_cues_space, cues_end - cuespos);
1735  return AVERROR(EINVAL);
1736  }
1737 
1738  if (cues_end < cuespos + mkv->reserve_cues_space)
1740  (cues_end - cuespos));
1741 
1742  avio_seek(pb, currentpos, SEEK_SET);
1743  } else {
1744  cuespos = mkv_write_cues(pb, mkv->cues, s->nb_streams);
1745  }
1746 
1748  cuespos);
1749  if (ret < 0)
1750  return ret;
1751  }
1752 
1754 
1755  // update the duration
1756  av_log(s, AV_LOG_DEBUG, "end duration = %" PRIu64 "\n", mkv->duration);
1757  currentpos = avio_tell(pb);
1758  avio_seek(pb, mkv->duration_offset, SEEK_SET);
1760 
1761  avio_seek(pb, currentpos, SEEK_SET);
1762  }
1763 
1764  end_ebml_master(pb, mkv->segment);
1765  av_free(mkv->tracks);
1766  av_freep(&mkv->cues->entries);
1767  av_freep(&mkv->cues);
1768 
1769  return 0;
1770 }
1771 
1772 static int mkv_query_codec(enum AVCodecID codec_id, int std_compliance)
1773 {
1774  int i;
1775  for (i = 0; ff_mkv_codec_tags[i].id != AV_CODEC_ID_NONE; i++)
1776  if (ff_mkv_codec_tags[i].id == codec_id)
1777  return 1;
1778 
1779  if (std_compliance < FF_COMPLIANCE_NORMAL) {
1780  enum AVMediaType type = avcodec_get_type(codec_id);
1781  // mkv theoretically supports any video/audio through VFW/ACM
1782  if (type == AVMEDIA_TYPE_VIDEO || type == AVMEDIA_TYPE_AUDIO)
1783  return 1;
1784  }
1785 
1786  return 0;
1787 }
1788 
1789 #define OFFSET(x) offsetof(MatroskaMuxContext, x)
1790 #define FLAGS AV_OPT_FLAG_ENCODING_PARAM
1791 static const AVOption options[] = {
1792  { "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 },
1793  { "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 },
1794  { "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 },
1795  { NULL },
1796 };
1797 
1798 #if CONFIG_MATROSKA_MUXER
1799 static const AVClass matroska_class = {
1800  .class_name = "matroska muxer",
1801  .item_name = av_default_item_name,
1802  .option = options,
1803  .version = LIBAVUTIL_VERSION_INT,
1804 };
1805 
1806 AVOutputFormat ff_matroska_muxer = {
1807  .name = "matroska",
1808  .long_name = NULL_IF_CONFIG_SMALL("Matroska"),
1809  .mime_type = "video/x-matroska",
1810  .extensions = "mkv",
1811  .priv_data_size = sizeof(MatroskaMuxContext),
1812  .audio_codec = CONFIG_LIBVORBIS_ENCODER ?
1814  .video_codec = CONFIG_LIBX264_ENCODER ?
1821  .codec_tag = (const AVCodecTag* const []){
1823  },
1824  .subtitle_codec = AV_CODEC_ID_SSA,
1825  .query_codec = mkv_query_codec,
1826  .priv_class = &matroska_class,
1827 };
1828 #endif
1829 
1830 #if CONFIG_WEBM_MUXER
1831 static const AVClass webm_class = {
1832  .class_name = "webm muxer",
1833  .item_name = av_default_item_name,
1834  .option = options,
1835  .version = LIBAVUTIL_VERSION_INT,
1836 };
1837 
1838 AVOutputFormat ff_webm_muxer = {
1839  .name = "webm",
1840  .long_name = NULL_IF_CONFIG_SMALL("WebM"),
1841  .mime_type = "video/webm",
1842  .extensions = "webm",
1843  .priv_data_size = sizeof(MatroskaMuxContext),
1851  .priv_class = &webm_class,
1852 };
1853 #endif
1854 
1855 #if CONFIG_MATROSKA_AUDIO_MUXER
1856 static const AVClass mka_class = {
1857  .class_name = "matroska audio muxer",
1858  .item_name = av_default_item_name,
1859  .option = options,
1860  .version = LIBAVUTIL_VERSION_INT,
1861 };
1862 AVOutputFormat ff_matroska_audio_muxer = {
1863  .name = "matroska",
1864  .long_name = NULL_IF_CONFIG_SMALL("Matroska"),
1865  .mime_type = "audio/x-matroska",
1866  .extensions = "mka",
1867  .priv_data_size = sizeof(MatroskaMuxContext),
1868  .audio_codec = CONFIG_LIBVORBIS_ENCODER ?
1870  .video_codec = AV_CODEC_ID_NONE,
1876  .codec_tag = (const AVCodecTag* const []){ ff_codec_wav_tags, 0 },
1877  .priv_class = &mka_class,
1878 };
1879 #endif
unsigned int nb_chapters
Number of chapters in AVChapter array.
Definition: avformat.h:1137
Definition: lfg.h:25
internal header for HEVC (de)muxer utilities
void avio_wb64(AVIOContext *s, uint64_t val)
Definition: aviobuf.c:392
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
enum AVFieldOrder field_order
Video only.
Definition: avcodec.h:3540
void avio_wl16(AVIOContext *s, unsigned int val)
Definition: aviobuf.c:398
static void put_ebml_size_unknown(AVIOContext *pb, int bytes)
Write an EBML size meaning "unknown size".
Definition: matroskaenc.c:146
Bytestream IO Context.
Definition: avio.h:104
#define MATROSKA_ID_VIDEOFLAGINTERLACED
Definition: matroska.h:115
#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
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:1155
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
#define MATROSKA_ID_CUETRACKPOSITION
Definition: matroska.h:141
#define MATROSKA_ID_CODECPRIVATE
Definition: matroska.h:84
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition: log.h:130
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:2986
#define MATROSKA_ID_AUDIOBITDEPTH
Definition: matroska.h:125
#define MATROSKA_ID_TRACKFLAGDEFAULT
Definition: matroska.h:93
This side data should be associated with a video stream and contains Stereoscopic 3D information in f...
Definition: avcodec.h:1260
static int mkv_write_attachments(AVFormatContext *s)
Definition: matroskaenc.c:1101
uint64_t pts
Definition: matroskaenc.c:71
enum AVCodecID codec_id
Specific type of the encoded data (the codec used).
Definition: avcodec.h:3483
AVRational sample_aspect_ratio
sample aspect ratio (0 if unknown)
Definition: avformat.h:770
int num
numerator
Definition: rational.h:44
int size
Definition: avcodec.h:1347
av_log(ac->avr, AV_LOG_TRACE, "%d samples - audio_convert: %s to %s (%s)\, len, av_get_sample_fmt_name(ac->in_fmt), av_get_sample_fmt_name(ac->out_fmt), use_generic ? ac->func_descr_generic :ac->func_descr)
int64_t avio_seek(AVIOContext *s, int64_t offset, int whence)
fseek() equivalent for AVIOContext.
Definition: aviobuf.c:242
#define MATROSKA_ID_FILEDATA
Definition: matroska.h:188
#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:1168
#define MATROSKA_ID_TRACKTYPE
Definition: matroska.h:80
enum AVMediaType codec_type
Definition: rtp.c:36
#define MATROSKA_ID_TAGTARGETS_CHAPTERUID
Definition: matroska.h:160
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
int ff_put_wav_header(AVFormatContext *s, AVIOContext *pb, AVCodecParameters *par)
Definition: riffenc.c:50
#define MATROSKA_ID_MUXINGAPP
Definition: matroska.h:70
int64_t cluster_time_limit
Definition: matroskaenc.c:113
#define MATROSKA_ID_AUDIOCHANNELS
Definition: matroska.h:126
unsigned int ff_codec_get_tag(const AVCodecTag *tags, enum AVCodecID id)
Definition: utils.c:1973
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:808
#define MATROSKA_ID_CUECLUSTERPOSITION
Definition: matroska.h:145
Definition: matroskaenc.c:56
AVDictionary * metadata
Definition: avformat.h:927
mkv_track * tracks
Definition: matroskaenc.c:103
#define AVFMT_ALLOW_FLUSH
Format allows flushing.
Definition: avformat.h:429
#define MATROSKA_ID_EDITIONFLAGDEFAULT
Definition: matroska.h:201
#define MATROSKA_ID_CLUSTERTIMECODE
Definition: matroska.h:171
int avio_open_dyn_buf(AVIOContext **s)
Open a write only memory stream.
Definition: aviobuf.c:1143
#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:430
This struct describes the properties of an encoded stream.
Definition: avcodec.h:3475
#define MATROSKA_ID_CHAPTERTIMEEND
Definition: matroska.h:195
int64_t pos
absolute offset in the file where the master&#39;s elements start
Definition: matroskaenc.c:52
MatroskaVideoStereoModeType
Definition: matroska.h:240
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:202
static int64_t mkv_write_cues(AVIOContext *pb, mkv_cues *cues, int num_tracks)
Definition: matroskaenc.c:410
#define FLAGS
Definition: matroskaenc.c:1790
#define MATROSKA_ID_FILEDESC
Definition: matroska.h:185
Format I/O context.
Definition: avformat.h:940
char str[32]
Definition: internal.h:42
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:39
Public dictionary API.
static char buffer[20]
Definition: seek.c:32
uint8_t
#define MATROSKA_ID_CHAPLANG
Definition: matroska.h:198
static int srt_get_duration(uint8_t **buf)
Definition: matroskaenc.c:1478
int width
Video only.
Definition: avcodec.h:3525
static int mkv_write_tag(AVFormatContext *s, AVDictionary *m, unsigned int elementid, unsigned int uid, ebml_master *tags)
Definition: matroskaenc.c:1028
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:70
static int ebml_id_size(unsigned int id)
Definition: matroskaenc.c:129
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:116
uint64_t segmentpos
Definition: matroskaenc.c:58
int id
unique ID to identify the chapter
Definition: avformat.h:924
int64_t duration
Duration of this packet in AVStream->time_base units, 0 if unknown.
Definition: avcodec.h:1364
#define MATROSKA_ID_TIMECODESCALE
Definition: matroska.h:66
static int mkv_write_codecprivate(AVFormatContext *s, AVIOContext *pb, AVCodecParameters *par, int native_id, int qt_id)
Definition: matroskaenc.c:577
#define MATROSKA_ID_SIMPLEBLOCK
Definition: matroska.h:175
#define MATROSKA_ID_EDITIONFLAGHIDDEN
Definition: matroska.h:200
int nb_side_data
The number of elements in the AVStream.side_data array.
Definition: avformat.h:812
void avio_write_marker(AVIOContext *s, int64_t time, enum AVIODataMarkerType type)
Mark the written bytestream as a specific type.
Definition: aviobuf.c:422
static int mkv_write_srt_blocks(AVFormatContext *s, AVIOContext *pb, AVPacket *pkt)
Definition: matroskaenc.c:1502
AVStream ** streams
A list of all streams in the file.
Definition: avformat.h:1008
int64_t duration
Definition: movenc.c:63
A point in the output bytestream where a demuxer can start parsing (for non self synchronizing bytest...
Definition: avio.h:77
#define MATROSKA_ID_AUDIOOUTSAMPLINGFREQ
Definition: matroska.h:123
int initial_padding
Audio only.
Definition: avcodec.h:3579
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:1051
uint8_t * data
Definition: avcodec.h:1346
#define CONFIG_LIBVPX_VP9_ENCODER
Definition: config.h:1164
#define MATROSKA_ID_VIDEODISPLAYWIDTH
Definition: matroska.h:106
static int flags
Definition: log.c:50
uint32_t tag
Definition: movenc.c:854
static EbmlSyntax ebml_header[]
Definition: matroskadec.c:285
enum AVCodecID id
Definition: internal.h:43
uint8_t * data
Definition: avcodec.h:1290
#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:295
#define MATROSKA_ID_TRACKNUMBER
Definition: matroska.h:78
void avio_write(AVIOContext *s, const unsigned char *buf, int size)
Definition: aviobuf.c:221
Definition: wv.h:34
#define AVFMT_FLAG_BITEXACT
When muxing, try to avoid writing any random/volatile data to the output.
Definition: avformat.h:1068
#define MATROSKA_ID_SEGMENTUID
Definition: matroska.h:72
uint64_t channel_layout
Audio only.
Definition: avcodec.h:3556
static void put_ebml_num(AVIOContext *pb, uint64_t num, int bytes)
Write a number in EBML variable length format.
Definition: matroskaenc.c:171
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:307
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:959
#define AV_PKT_FLAG_KEY
The packet contains a keyframe.
Definition: avcodec.h:1378
static int get_aac_sample_rates(AVFormatContext *s, AVCodecParameters *par, int *sample_rate, int *output_sample_rate)
Definition: matroskaenc.c:524
#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:99
ebml_master segment
Definition: matroskaenc.c:94
static int mkv_write_simpletag(AVIOContext *pb, AVDictionaryEntry *t)
Definition: matroskaenc.c:994
#define src
Definition: vp8dsp.c:254
#define MATROSKA_ID_VIDEOSTEREOMODE
Definition: matroska.h:117
AVPacket cur_audio_pkt
Definition: matroskaenc.c:105
int av_reallocp_array(void *ptr, size_t nmemb, size_t size)
Definition: mem.c:168
AVCodecID
Identify the syntax and semantics of the bitstream.
Definition: avcodec.h:193
static int mkv_write_tags(AVFormatContext *s)
Definition: matroskaenc.c:1064
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition: log.h:124
int av_get_bits_per_sample(enum AVCodecID codec_id)
Return codec bits per sample.
Definition: utils.c:2348
AVDictionary * metadata
Metadata that applies to the whole file.
Definition: avformat.h:1148
void av_free(void *ptr)
Free a memory block which has been allocated with av_malloc(z)() or av_realloc(). ...
Definition: mem.c:190
int flags
Additional information about the frame packing.
Definition: stereo3d.h:132
#define MATROSKA_ID_BLOCKDURATION
Definition: matroska.h:179
#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:124
static int mkv_write_ass_blocks(AVFormatContext *s, AVIOContext *pb, AVPacket *pkt)
Definition: matroskaenc.c:1330
#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
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification. ...
Definition: internal.h:148
#define MATROSKA_ID_FILEMIMETYPE
Definition: matroska.h:187
#define MATROSKA_ID_WRITINGAPP
Definition: matroska.h:69
#define AV_LOG_DEBUG
Stuff which is only useful for libav* developers.
Definition: log.h:145
void av_dict_free(AVDictionary **pm)
Free all the memory allocated for an AVDictionary struct and all keys and values. ...
Definition: dict.c:175
static int mkv_blockgroup_size(int pkt_size)
Definition: matroskaenc.c:1289
enum AVMediaType codec_type
General type of the encoded data.
Definition: avcodec.h:3479
static int ebml_num_size(uint64_t num)
Calculate how many bytes are needed to represent a given number in EBML.
Definition: matroskaenc.c:157
int write_dts
Definition: matroskaenc.c:83
int final
Definition: wv.h:43
AVChapter ** chapters
Definition: avformat.h:1138
enum AVCodecID id
Definition: matroska.h:265
enum AVPacketSideDataType type
Definition: avcodec.h:1292
enum AVMediaType avcodec_get_type(enum AVCodecID codec_id)
Get the type of the given codec.
Definition: codec_desc.c:2491
static int mkv_write_chapters(AVFormatContext *s)
Definition: matroskaenc.c:942
#define EBML_ID_EBMLMAXIDLENGTH
Definition: matroska.h:38
#define MATROSKA_ID_CHAPTERFLAGHIDDEN
Definition: matroska.h:204
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:781
const AVCodecTag ff_codec_wav_tags[]
Definition: riff.c:374
#define FFMAX(a, b)
Definition: common.h:64
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:286
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
#define fail()
Definition: checkasm.h:80
int flags
A combination of AV_PKT_FLAG values.
Definition: avcodec.h:1352
static void mkv_write_block(AVFormatContext *s, AVIOContext *pb, unsigned int blockid, AVPacket *pkt, int flags)
Definition: matroskaenc.c:1432
int extradata_size
Size of the extradata content in bytes.
Definition: avcodec.h:3501
static void mkv_write_field_order(AVIOContext *pb, enum AVFieldOrder field_order)
Definition: matroskaenc.c:630
const CodecMime ff_mkv_mime_tags[]
Definition: matroska.c:102
#define MATROSKA_ID_TAG
Definition: matroska.h:149
#define AV_DISPOSITION_FORCED
Track should be used during playback by default.
Definition: avformat.h:684
unsigned int nb_streams
Number of elements in AVFormatContext.streams.
Definition: avformat.h:996
#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:153
int void avio_flush(AVIOContext *s)
Definition: aviobuf.c:236
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:66
#define MATROSKA_ID_TAGTARGETS
Definition: matroska.h:156
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:151
static int put_wv_codecpriv(AVIOContext *pb, AVCodecParameters *par)
Definition: matroskaenc.c:471
enum AVCodecID codec_id
Definition: avconv_vaapi.c:149
#define MATROSKA_ID_CHAPTERFLAGENABLED
Definition: matroska.h:205
#define AVFMT_GLOBALHEADER
Format wants global header.
Definition: avformat.h:419
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:150
const char * name
Definition: avformat.h:450
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:423
int ff_flac_write_header(AVIOContext *pb, uint8_t *extradata, int extradata_size, int last_block)
#define MATROSKA_ID_CHAPTERATOM
Definition: matroska.h:193
#define CONFIG_LIBVORBIS_ENCODER
Definition: config.h:1162
AVDictionary * metadata
Definition: avformat.h:772
Opaque data information usually sparse.
Definition: avutil.h:198
#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:390
#define EBML_ID_VOID
Definition: matroska.h:45
#define OFFSET(x)
Definition: matroskaenc.c:1789
LIBAVUTIL_VERSION_INT
Definition: eval.c:55
#define MATROSKA_ID_AUDIOSAMPLINGFREQ
Definition: matroska.h:122
static void put_ebml_float(AVIOContext *pb, unsigned int elementid, double val)
Definition: matroskaenc.c:203
Stream structure.
Definition: avformat.h:705
static void put_ebml_string(AVIOContext *pb, unsigned int elementid, const char *str)
Definition: matroskaenc.c:218
int64_t end
chapter start/end time in time_base units
Definition: avformat.h:926
NULL
Definition: eval.c:55
#define AV_DISPOSITION_DEFAULT
Definition: avformat.h:672
enum AVStereo3DType type
How views are packed within the video.
Definition: stereo3d.h:127
#define MATROSKA_ID_TRACKFLAGFORCED
Definition: matroska.h:94
#define MATROSKA_ID_TAGS
Definition: matroska.h:59
#define AV_TIME_BASE_Q
Internal time base represented as fractional value.
Definition: avutil.h:247
#define MATROSKA_ID_SEEKID
Definition: matroska.h:167
char * av_strdup(const char *s)
Duplicate the string s.
Definition: mem.c:219
AVIOContext * pb
I/O context.
Definition: avformat.h:982
av_default_item_name
Definition: dnxhdenc.c:55
void avio_w8(AVIOContext *s, int b)
Definition: aviobuf.c:200
static void write_packet(OutputFile *of, AVPacket *pkt, OutputStream *ost)
Definition: avconv.c:278
#define MATROSKA_ID_BLOCK
Definition: matroska.h:178
#define MATROSKA_ID_INFO
Definition: matroska.h:56
void av_packet_unref(AVPacket *pkt)
Wipe the packet.
Definition: avpacket.c:347
#define MATROSKA_ID_TAGTARGETS_TRACKUID
Definition: matroska.h:159
#define MATROSKA_ID_TAGLANG
Definition: matroska.h:153
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
#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:164
const char * format
Definition: movenc.c:47
Describe the class of an AVClass context structure.
Definition: log.h:34
#define MATROSKA_ID_EDITIONENTRY
Definition: matroska.h:192
#define FF_COMPLIANCE_NORMAL
Definition: avcodec.h:2608
#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:127
#define MATROSKA_ID_BLOCKGROUP
Definition: matroska.h:174
#define MATROSKA_ID_VIDEOPIXELHEIGHT
Definition: matroska.h:109
static int mkv_write_tracks(AVFormatContext *s)
Definition: matroskaenc.c:921
rational number numerator/denominator
Definition: rational.h:43
static void put_ebml_uint(AVIOContext *pb, unsigned int elementid, uint64_t val)
Definition: matroskaenc.c:190
#define MATROSKA_ID_CUETIME
Definition: matroska.h:140
static int64_t mkv_write_seekhead(AVIOContext *pb, mkv_seekhead *seekhead)
Write the seek head to the file and free it.
Definition: matroskaenc.c:336
AVFieldOrder
Definition: avcodec.h:1393
AVIOContext * dyn_bc
Definition: matroskaenc.c:93
AVMediaType
Definition: avutil.h:192
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
void ff_put_bmp_header(AVIOContext *pb, AVCodecParameters *par, const AVCodecTag *tags, int for_asf)
Definition: riffenc.c:183
int64_t duration_offset
Definition: matroskaenc.c:99
static int mkv_write_packet_internal(AVFormatContext *s, AVPacket *pkt)
Definition: matroskaenc.c:1534
#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:1379
static void put_ebml_id(AVIOContext *pb, unsigned int id)
Definition: matroskaenc.c:134
#define CONFIG_LIBOPUS_ENCODER
Definition: config.h:1155
Views are on top of each other.
Definition: stereo3d.h:55
#define MATROSKA_ID_ATTACHMENTS
Definition: matroska.h:61
static int64_t pts
Global timestamp for the audio frames.
void avio_wb16(AVIOContext *s, unsigned int val)
Definition: aviobuf.c:404
#define MATROSKA_ID_CHAPTERDISPLAY
Definition: matroska.h:196
static int put_xiph_codecpriv(AVFormatContext *s, AVIOContext *pb, AVCodecParameters *par)
Definition: matroskaenc.c:443
#define MATROSKA_ID_FILENAME
Definition: matroska.h:186
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:110
#define MATROSKA_ID_CODECID
Definition: matroska.h:83
static int put_flac_codecpriv(AVFormatContext *s, AVIOContext *pb, AVCodecParameters *par)
Definition: matroskaenc.c:480
#define MATROSKA_ID_VIDEOFIELDORDER
Definition: matroska.h:116
int64_t start
Definition: avformat.h:926
Views are next to each other.
Definition: stereo3d.h:45
int sample_rate
Audio only.
Definition: avcodec.h:3564
static int mkv_write_trailer(AVFormatContext *s)
Definition: matroskaenc.c:1689
Main libavformat public API header.
attribute_deprecated int64_t convergence_duration
Definition: avcodec.h:1375
#define MATROSKA_ID_CUETRACK
Definition: matroska.h:144
#define MATROSKA_ID_SEEKPOSITION
Definition: matroska.h:168
#define MATROSKA_ID_CODECDELAY
Definition: matroska.h:89
#define FF_DISABLE_DEPRECATION_WARNINGS
Definition: internal.h:77
#define MATROSKA_ID_CHAPTERTIMESTART
Definition: matroska.h:194
static void put_ebml_binary(AVIOContext *pb, unsigned int elementid, const void *buf, int size)
Definition: matroskaenc.c:210
static int mkv_write_track(AVFormatContext *s, MatroskaMuxContext *mkv, int i, AVIOContext *pb)
Definition: matroskaenc.c:767
static int mkv_write_flush_packet(AVFormatContext *s, AVPacket *pkt)
Definition: matroskaenc.c:1665
int disposition
AV_DISPOSITION_* bit field.
Definition: avformat.h:761
static void put_ebml_void(AVIOContext *pb, uint64_t size)
Write a void element of a given size.
Definition: matroskaenc.c:230
AVRational time_base
time base in which the start/end timestamps are specified
Definition: avformat.h:925
void av_init_packet(AVPacket *pkt)
Initialize optional fields of a packet with default values.
Definition: avpacket.c:31
int64_t nb_frames
number of frames in this stream if known or 0
Definition: avformat.h:759
char * key
Definition: dict.h:73
int den
denominator
Definition: rational.h:45
#define MATROSKA_ID_SEGMENT
Definition: matroska.h:53
static int ass_get_duration(AVFormatContext *s, const uint8_t *p)
Definition: matroskaenc.c:1300
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
int av_packet_ref(AVPacket *dst, AVPacket *src)
Setup a new reference to the data described by a given packet.
Definition: avpacket.c:356
#define EBML_ID_HEADER
Definition: matroska.h:33
A point in the output bytestream where a decoder can start decoding (i.e.
Definition: avio.h:71
#define AVFMT_VARIABLE_FPS
Format allows variable fps.
Definition: avformat.h:423
ebml_master cluster
Definition: matroskaenc.c:96
char * value
Definition: dict.h:74
#define FF_ENABLE_DEPRECATION_WARNINGS
Definition: internal.h:78
#define MATROSKA_ID_POINTENTRY
Definition: matroska.h:137
mkv_seekhead_entry * entries
Definition: matroskaenc.c:66
int len
static int mkv_write_native_codecprivate(AVFormatContext *s, AVCodecParameters *par, AVIOContext *dyn_cp)
Definition: matroskaenc.c:541
#define av_log2
Definition: intmath.h:85
#define MATROSKA_ID_FILEUID
Definition: matroska.h:189
static uint8_t tmp[8]
Definition: des.c:38
Views are packed in a checkerboard-like structure per pixel.
Definition: stereo3d.h:76
void * priv_data
Format private data.
Definition: avformat.h:968
#define MATROSKA_ID_CHAPTERUID
Definition: matroska.h:203
Views are packed per column.
Definition: stereo3d.h:107
static void write_header(FFV1Context *f)
Definition: ffv1enc.c:373
uint8_t * extradata
Extra binary data needed for initializing the decoder, codec-dependent.
Definition: avcodec.h:3497
#define MATROSKA_ID_VIDEODISPLAYUNIT
Definition: matroska.h:114
int channels
Audio only.
Definition: avcodec.h:3560
#define AV_WL32(p, val)
Definition: intreadwrite.h:263
int64_t dts
Decompression timestamp in AVStream->time_base units; the time at which the packet is decompressed...
Definition: avcodec.h:1345
static void mkv_flush_dynbuf(AVFormatContext *s)
Definition: matroskaenc.c:1519
static const AVOption options[]
Definition: matroskaenc.c:1791
#define EBML_ID_EBMLMAXSIZELENGTH
Definition: matroska.h:39
#define MATROSKA_ID_CHAPSTRING
Definition: matroska.h:197
#define MATROSKA_ID_TAGSTRING
Definition: matroska.h:152
#define AV_DICT_IGNORE_SUFFIX
Definition: dict.h:60
#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
const CodecMime ff_mkv_image_mime_tags[]
Definition: matroska.c:93
AVCodecParameters * codecpar
Definition: avformat.h:831
static int mkv_write_stereo_mode(AVFormatContext *s, AVIOContext *pb, AVStream *st, int mode)
Definition: matroskaenc.c:669
#define MODE_WEBM
Definition: matroskaenc.c:88
uint32_t codec_tag
Additional information about the codec (corresponds to the AVI FOURCC).
Definition: avcodec.h:3487
static int mkv_write_packet(AVFormatContext *s, AVPacket *pkt)
Definition: matroskaenc.c:1598
#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:120
static mkv_cues * mkv_start_cues(int64_t segment_offset)
Definition: matroskaenc.c:380
int stream_index
Definition: avcodec.h:1348
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:742
static void end_ebml_master(AVIOContext *pb, ebml_master master)
Definition: matroskaenc.c:257
int64_t segment_offset
Definition: matroskaenc.c:95
#define CONFIG_LIBX264_ENCODER
Definition: config.h:1168
#define MATROSKA_ID_ATTACHEDFILE
Definition: matroska.h:184
static ebml_master start_ebml_master(AVIOContext *pb, unsigned int elementid, uint64_t expectedsize)
Definition: matroskaenc.c:248
mkv_seekhead * main_seekhead
Definition: matroskaenc.c:101
This structure stores compressed data.
Definition: avcodec.h:1323
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:211
uint32_t blocksize
Definition: wv.h:35
static int mkv_query_codec(enum AVCodecID codec_id, int std_compliance)
Definition: matroskaenc.c:1772
static void put_xiph_size(AVIOContext *pb, int size)
Definition: matroskaenc.c:267
int64_t pts
Presentation timestamp in AVStream->time_base units; the time at which the decompressed packet will b...
Definition: avcodec.h:1339
#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:235
const CodecTags ff_mkv_codec_tags[]
Definition: matroska.c:26