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 "avformat.h"
23 #include "internal.h"
24 #include "riff.h"
25 #include "isom.h"
26 #include "matroska.h"
27 #include "avc.h"
28 #include "flacenc.h"
29 #include "avlanguage.h"
30 #include "libavutil/samplefmt.h"
31 #include "libavutil/intreadwrite.h"
32 #include "libavutil/intfloat.h"
33 #include "libavutil/mathematics.h"
34 #include "libavutil/random_seed.h"
35 #include "libavutil/lfg.h"
36 #include "libavutil/dict.h"
37 #include "libavutil/avstring.h"
38 #include "libavcodec/xiph.h"
39 #include "libavcodec/mpeg4audio.h"
40 
41 typedef struct ebml_master {
42  int64_t pos;
43  int sizebytes;
44 } ebml_master;
45 
46 typedef struct mkv_seekhead_entry {
47  unsigned int elementid;
48  uint64_t segmentpos;
50 
51 typedef struct mkv_seekhead {
52  int64_t filepos;
53  int64_t segment_offset;
58 } mkv_seekhead;
59 
60 typedef struct {
61  uint64_t pts;
62  int tracknum;
63  int64_t cluster_pos;
64 } mkv_cuepoint;
65 
66 typedef struct {
67  int64_t segment_offset;
70 } mkv_cues;
71 
72 typedef struct {
73  int write_dts;
74 } mkv_track;
75 
76 #define MODE_MATROSKAv2 0x01
77 #define MODE_WEBM 0x02
78 
79 typedef struct MatroskaMuxContext {
80  int mode;
83  int64_t segment_offset;
85  int64_t cluster_pos;
86  int64_t cluster_pts;
87  int64_t duration_offset;
88  int64_t duration;
92 
93  unsigned int audio_buffer_size;
95 
97 
98  int64_t ts_offset;
100 
101 
104 #define MAX_SEEKENTRY_SIZE 21
105 
108 #define MAX_CUETRACKPOS_SIZE 22
109 
111 #define MAX_CUEPOINT_SIZE(num_tracks) 12 + MAX_CUETRACKPOS_SIZE*num_tracks
112 
113 
114 static int ebml_id_size(unsigned int id)
115 {
116  return (av_log2(id+1)-1)/7+1;
117 }
118 
119 static void put_ebml_id(AVIOContext *pb, unsigned int id)
120 {
121  int i = ebml_id_size(id);
122  while (i--)
123  avio_w8(pb, id >> (i*8));
124 }
125 
131 static void put_ebml_size_unknown(AVIOContext *pb, int bytes)
132 {
133  assert(bytes <= 8);
134  avio_w8(pb, 0x1ff >> bytes);
135  while (--bytes)
136  avio_w8(pb, 0xff);
137 }
138 
142 static int ebml_num_size(uint64_t num)
143 {
144  int bytes = 1;
145  while ((num+1) >> bytes*7) bytes++;
146  return bytes;
147 }
148 
155 static void put_ebml_num(AVIOContext *pb, uint64_t num, int bytes)
156 {
157  int i, needed_bytes = ebml_num_size(num);
158 
159  // sizes larger than this are currently undefined in EBML
160  assert(num < (1ULL<<56)-1);
161 
162  if (bytes == 0)
163  // don't care how many bytes are used, so use the min
164  bytes = needed_bytes;
165  // the bytes needed to write the given size would exceed the bytes
166  // that we need to use, so write unknown size. This shouldn't happen.
167  assert(bytes >= needed_bytes);
168 
169  num |= 1ULL << bytes*7;
170  for (i = bytes - 1; i >= 0; i--)
171  avio_w8(pb, num >> i*8);
172 }
173 
174 static void put_ebml_uint(AVIOContext *pb, unsigned int elementid, uint64_t val)
175 {
176  int i, bytes = 1;
177  uint64_t tmp = val;
178  while (tmp>>=8) bytes++;
179 
180  put_ebml_id(pb, elementid);
181  put_ebml_num(pb, bytes, 0);
182  for (i = bytes - 1; i >= 0; i--)
183  avio_w8(pb, val >> i*8);
184 }
185 
186 static void put_ebml_float(AVIOContext *pb, unsigned int elementid, double val)
187 {
188  put_ebml_id(pb, elementid);
189  put_ebml_num(pb, 8, 0);
190  avio_wb64(pb, av_double2int(val));
191 }
192 
193 static void put_ebml_binary(AVIOContext *pb, unsigned int elementid,
194  const void *buf, int size)
195 {
196  put_ebml_id(pb, elementid);
197  put_ebml_num(pb, size, 0);
198  avio_write(pb, buf, size);
199 }
200 
201 static void put_ebml_string(AVIOContext *pb, unsigned int elementid, const char *str)
202 {
203  put_ebml_binary(pb, elementid, str, strlen(str));
204 }
205 
212 static void put_ebml_void(AVIOContext *pb, uint64_t size)
213 {
214  int64_t currentpos = avio_tell(pb);
215 
216  assert(size >= 2);
217 
219  // we need to subtract the length needed to store the size from the
220  // size we need to reserve so 2 cases, we use 8 bytes to store the
221  // size if possible, 1 byte otherwise
222  if (size < 10)
223  put_ebml_num(pb, size-1, 0);
224  else
225  put_ebml_num(pb, size-9, 8);
226  while(avio_tell(pb) < currentpos + size)
227  avio_w8(pb, 0);
228 }
229 
230 static ebml_master start_ebml_master(AVIOContext *pb, unsigned int elementid, uint64_t expectedsize)
231 {
232  int bytes = expectedsize ? ebml_num_size(expectedsize) : 8;
233  put_ebml_id(pb, elementid);
234  put_ebml_size_unknown(pb, bytes);
235  return (ebml_master){ avio_tell(pb), bytes };
236 }
237 
238 static void end_ebml_master(AVIOContext *pb, ebml_master master)
239 {
240  int64_t pos = avio_tell(pb);
241 
242  if (avio_seek(pb, master.pos - master.sizebytes, SEEK_SET) < 0)
243  return;
244  put_ebml_num(pb, pos - master.pos, master.sizebytes);
245  avio_seek(pb, pos, SEEK_SET);
246 }
247 
248 static void put_xiph_size(AVIOContext *pb, int size)
249 {
250  int i;
251  for (i = 0; i < size / 255; i++)
252  avio_w8(pb, 255);
253  avio_w8(pb, size % 255);
254 }
255 
267 static mkv_seekhead * mkv_start_seekhead(AVIOContext *pb, int64_t segment_offset, int numelements)
268 {
269  mkv_seekhead *new_seekhead = av_mallocz(sizeof(mkv_seekhead));
270  if (new_seekhead == NULL)
271  return NULL;
272 
273  new_seekhead->segment_offset = segment_offset;
274 
275  if (numelements > 0) {
276  new_seekhead->filepos = avio_tell(pb);
277  // 21 bytes max for a seek entry, 10 bytes max for the SeekHead ID
278  // and size, and 3 bytes to guarantee that an EBML void element
279  // will fit afterwards
280  new_seekhead->reserved_size = numelements * MAX_SEEKENTRY_SIZE + 13;
281  new_seekhead->max_entries = numelements;
282  put_ebml_void(pb, new_seekhead->reserved_size);
283  }
284  return new_seekhead;
285 }
286 
287 static int mkv_add_seekhead_entry(mkv_seekhead *seekhead, unsigned int elementid, uint64_t filepos)
288 {
289  mkv_seekhead_entry *entries = seekhead->entries;
290 
291  // don't store more elements than we reserved space for
292  if (seekhead->max_entries > 0 && seekhead->max_entries <= seekhead->num_entries)
293  return -1;
294 
295  entries = av_realloc(entries, (seekhead->num_entries + 1) * sizeof(mkv_seekhead_entry));
296  if (entries == NULL)
297  return AVERROR(ENOMEM);
298 
299  entries[seekhead->num_entries ].elementid = elementid;
300  entries[seekhead->num_entries++].segmentpos = filepos - seekhead->segment_offset;
301 
302  seekhead->entries = entries;
303  return 0;
304 }
305 
315 static int64_t mkv_write_seekhead(AVIOContext *pb, mkv_seekhead *seekhead)
316 {
317  ebml_master metaseek, seekentry;
318  int64_t currentpos;
319  int i;
320 
321  currentpos = avio_tell(pb);
322 
323  if (seekhead->reserved_size > 0) {
324  if (avio_seek(pb, seekhead->filepos, SEEK_SET) < 0) {
325  currentpos = -1;
326  goto fail;
327  }
328  }
329 
330  metaseek = start_ebml_master(pb, MATROSKA_ID_SEEKHEAD, seekhead->reserved_size);
331  for (i = 0; i < seekhead->num_entries; i++) {
332  mkv_seekhead_entry *entry = &seekhead->entries[i];
333 
335 
337  put_ebml_num(pb, ebml_id_size(entry->elementid), 0);
338  put_ebml_id(pb, entry->elementid);
339 
341  end_ebml_master(pb, seekentry);
342  }
343  end_ebml_master(pb, metaseek);
344 
345  if (seekhead->reserved_size > 0) {
346  uint64_t remaining = seekhead->filepos + seekhead->reserved_size - avio_tell(pb);
347  put_ebml_void(pb, remaining);
348  avio_seek(pb, currentpos, SEEK_SET);
349 
350  currentpos = seekhead->filepos;
351  }
352 fail:
353  av_free(seekhead->entries);
354  av_free(seekhead);
355 
356  return currentpos;
357 }
358 
359 static mkv_cues * mkv_start_cues(int64_t segment_offset)
360 {
361  mkv_cues *cues = av_mallocz(sizeof(mkv_cues));
362  if (cues == NULL)
363  return NULL;
364 
365  cues->segment_offset = segment_offset;
366  return cues;
367 }
368 
369 static int mkv_add_cuepoint(mkv_cues *cues, int stream, int64_t ts, int64_t cluster_pos)
370 {
371  mkv_cuepoint *entries = cues->entries;
372 
373  if (ts < 0)
374  return 0;
375 
376  entries = av_realloc(entries, (cues->num_entries + 1) * sizeof(mkv_cuepoint));
377  if (entries == NULL)
378  return AVERROR(ENOMEM);
379 
380  entries[cues->num_entries ].pts = ts;
381  entries[cues->num_entries ].tracknum = stream + 1;
382  entries[cues->num_entries++].cluster_pos = cluster_pos - cues->segment_offset;
383 
384  cues->entries = entries;
385  return 0;
386 }
387 
388 static int64_t mkv_write_cues(AVIOContext *pb, mkv_cues *cues, int num_tracks)
389 {
390  ebml_master cues_element;
391  int64_t currentpos;
392  int i, j;
393 
394  currentpos = avio_tell(pb);
395  cues_element = start_ebml_master(pb, MATROSKA_ID_CUES, 0);
396 
397  for (i = 0; i < cues->num_entries; i++) {
398  ebml_master cuepoint, track_positions;
399  mkv_cuepoint *entry = &cues->entries[i];
400  uint64_t pts = entry->pts;
401 
402  cuepoint = start_ebml_master(pb, MATROSKA_ID_POINTENTRY, MAX_CUEPOINT_SIZE(num_tracks));
404 
405  // put all the entries from different tracks that have the exact same
406  // timestamp into the same CuePoint
407  for (j = 0; j < cues->num_entries - i && entry[j].pts == pts; j++) {
409  put_ebml_uint(pb, MATROSKA_ID_CUETRACK , entry[j].tracknum );
410  put_ebml_uint(pb, MATROSKA_ID_CUECLUSTERPOSITION, entry[j].cluster_pos);
411  end_ebml_master(pb, track_positions);
412  }
413  i += j - 1;
414  end_ebml_master(pb, cuepoint);
415  }
416  end_ebml_master(pb, cues_element);
417 
418  return currentpos;
419 }
420 
422 {
423  uint8_t *header_start[3];
424  int header_len[3];
425  int first_header_size;
426  int j;
427 
428  if (codec->codec_id == AV_CODEC_ID_VORBIS)
429  first_header_size = 30;
430  else
431  first_header_size = 42;
432 
434  first_header_size, header_start, header_len) < 0) {
435  av_log(s, AV_LOG_ERROR, "Extradata corrupt.\n");
436  return -1;
437  }
438 
439  avio_w8(pb, 2); // number packets - 1
440  for (j = 0; j < 2; j++) {
441  put_xiph_size(pb, header_len[j]);
442  }
443  for (j = 0; j < 3; j++)
444  avio_write(pb, header_start[j], header_len[j]);
445 
446  return 0;
447 }
448 
449 static void get_aac_sample_rates(AVFormatContext *s, AVCodecContext *codec, int *sample_rate, int *output_sample_rate)
450 {
451  MPEG4AudioConfig mp4ac;
452 
453  if (avpriv_mpeg4audio_get_config(&mp4ac, codec->extradata,
454  codec->extradata_size * 8, 1) < 0) {
455  av_log(s, AV_LOG_WARNING, "Error parsing AAC extradata, unable to determine samplerate.\n");
456  return;
457  }
458 
459  *sample_rate = mp4ac.sample_rate;
460  *output_sample_rate = mp4ac.ext_sample_rate;
461 }
462 
463 static int mkv_write_codecprivate(AVFormatContext *s, AVIOContext *pb, AVCodecContext *codec, int native_id, int qt_id)
464 {
465  AVIOContext *dyn_cp;
466  uint8_t *codecpriv;
467  int ret, codecpriv_size;
468 
469  ret = avio_open_dyn_buf(&dyn_cp);
470  if(ret < 0)
471  return ret;
472 
473  if (native_id) {
474  if (codec->codec_id == AV_CODEC_ID_VORBIS || codec->codec_id == AV_CODEC_ID_THEORA)
475  ret = put_xiph_codecpriv(s, dyn_cp, codec);
476  else if (codec->codec_id == AV_CODEC_ID_FLAC)
477  ret = ff_flac_write_header(dyn_cp, codec, 1);
478  else if (codec->codec_id == AV_CODEC_ID_H264)
479  ret = ff_isom_write_avcc(dyn_cp, codec->extradata, codec->extradata_size);
480  else if (codec->codec_id == AV_CODEC_ID_ALAC) {
481  if (codec->extradata_size < 36) {
482  av_log(s, AV_LOG_ERROR,
483  "Invalid extradata found, ALAC expects a 36-byte "
484  "QuickTime atom.");
485  ret = AVERROR_INVALIDDATA;
486  } else
487  avio_write(dyn_cp, codec->extradata + 12,
488  codec->extradata_size - 12);
489  }
490  else if (codec->extradata_size)
491  avio_write(dyn_cp, codec->extradata, codec->extradata_size);
492  } else if (codec->codec_type == AVMEDIA_TYPE_VIDEO) {
493  if (qt_id) {
494  if (!codec->codec_tag)
496  if (codec->extradata_size)
497  avio_write(dyn_cp, codec->extradata, codec->extradata_size);
498  } else {
499  if (!codec->codec_tag)
501  if (!codec->codec_tag) {
502  av_log(s, AV_LOG_ERROR, "No bmp codec ID found.\n");
503  ret = -1;
504  }
505 
506  ff_put_bmp_header(dyn_cp, codec, ff_codec_bmp_tags, 0);
507  }
508 
509  } else if (codec->codec_type == AVMEDIA_TYPE_AUDIO) {
510  unsigned int tag;
512  if (!tag) {
513  av_log(s, AV_LOG_ERROR, "No wav codec ID found.\n");
514  ret = -1;
515  }
516  if (!codec->codec_tag)
517  codec->codec_tag = tag;
518 
519  ff_put_wav_header(dyn_cp, codec);
520  }
521 
522  codecpriv_size = avio_close_dyn_buf(dyn_cp, &codecpriv);
523  if (codecpriv_size)
524  put_ebml_binary(pb, MATROSKA_ID_CODECPRIVATE, codecpriv, codecpriv_size);
525  av_free(codecpriv);
526  return ret;
527 }
528 
530 {
531  MatroskaMuxContext *mkv = s->priv_data;
532  AVIOContext *pb = s->pb;
533  ebml_master tracks;
534  int i, j, ret;
535 
537  if (ret < 0) return ret;
538 
539  tracks = start_ebml_master(pb, MATROSKA_ID_TRACKS, 0);
540  for (i = 0; i < s->nb_streams; i++) {
541  AVStream *st = s->streams[i];
542  AVCodecContext *codec = st->codec;
543  ebml_master subinfo, track;
544  int native_id = 0;
545  int qt_id = 0;
546  int bit_depth = av_get_bits_per_sample(codec->codec_id);
547  int sample_rate = codec->sample_rate;
548  int output_sample_rate = 0;
550 
551  if (codec->codec_type == AVMEDIA_TYPE_ATTACHMENT) {
552  mkv->have_attachments = 1;
553  continue;
554  }
555 
556  if (!bit_depth)
557  bit_depth = av_get_bytes_per_sample(codec->sample_fmt) << 3;
558 
559  if (codec->codec_id == AV_CODEC_ID_AAC)
560  get_aac_sample_rates(s, codec, &sample_rate, &output_sample_rate);
561 
564  put_ebml_uint (pb, MATROSKA_ID_TRACKUID , i + 1);
565  put_ebml_uint (pb, MATROSKA_ID_TRACKFLAGLACING , 0); // no lacing (yet)
566 
567  if ((tag = av_dict_get(st->metadata, "title", NULL, 0)))
569  tag = av_dict_get(st->metadata, "language", NULL, 0);
570  put_ebml_string(pb, MATROSKA_ID_TRACKLANGUAGE, tag ? tag->value:"und");
571 
572  if (st->disposition)
574 
575  // look for a codec ID string specific to mkv to use,
576  // if none are found, use AVI codes
577  for (j = 0; ff_mkv_codec_tags[j].id != AV_CODEC_ID_NONE; j++) {
578  if (ff_mkv_codec_tags[j].id == codec->codec_id) {
580  native_id = 1;
581  break;
582  }
583  }
584 
585  if (mkv->mode == MODE_WEBM && !(codec->codec_id == AV_CODEC_ID_VP8 ||
586  codec->codec_id == AV_CODEC_ID_VORBIS)) {
587  av_log(s, AV_LOG_ERROR,
588  "Only VP8 video and Vorbis audio are supported for WebM.\n");
589  return AVERROR(EINVAL);
590  }
591 
592  switch (codec->codec_type) {
593  case AVMEDIA_TYPE_VIDEO:
596 
597  if (!native_id &&
600  || codec->codec_id == AV_CODEC_ID_SVQ1
601  || codec->codec_id == AV_CODEC_ID_SVQ3
602  || codec->codec_id == AV_CODEC_ID_CINEPAK))
603  qt_id = 1;
604 
605  if (qt_id)
606  put_ebml_string(pb, MATROSKA_ID_CODECID, "V_QUICKTIME");
607  else if (!native_id) {
608  // if there is no mkv-specific codec ID, use VFW mode
609  put_ebml_string(pb, MATROSKA_ID_CODECID, "V_MS/VFW/FOURCC");
610  mkv->tracks[i].write_dts = 1;
611  }
612 
613  subinfo = start_ebml_master(pb, MATROSKA_ID_TRACKVIDEO, 0);
614  // XXX: interlace flag?
617  if ((tag = av_dict_get(s->metadata, "stereo_mode", NULL, 0))) {
618  uint8_t stereo_fmt = atoi(tag->value);
619  int valid_fmt = 0;
620 
621  switch (mkv->mode) {
622  case MODE_WEBM:
625  valid_fmt = 1;
626  break;
627  case MODE_MATROSKAv2:
629  valid_fmt = 1;
630  break;
631  }
632 
633  if (valid_fmt)
634  put_ebml_uint (pb, MATROSKA_ID_VIDEOSTEREOMODE, stereo_fmt);
635  }
636  if (st->sample_aspect_ratio.num) {
637  int d_width = codec->width*av_q2d(st->sample_aspect_ratio);
641  }
642  end_ebml_master(pb, subinfo);
643  break;
644 
645  case AVMEDIA_TYPE_AUDIO:
647 
648  if (!native_id)
649  // no mkv-specific ID, use ACM mode
650  put_ebml_string(pb, MATROSKA_ID_CODECID, "A_MS/ACM");
651 
652  subinfo = start_ebml_master(pb, MATROSKA_ID_TRACKAUDIO, 0);
655  if (output_sample_rate)
656  put_ebml_float(pb, MATROSKA_ID_AUDIOOUTSAMPLINGFREQ, output_sample_rate);
657  if (bit_depth)
659  end_ebml_master(pb, subinfo);
660  break;
661 
664  if (!native_id) {
665  av_log(s, AV_LOG_ERROR, "Subtitle codec %d is not supported.\n", codec->codec_id);
666  return AVERROR(ENOSYS);
667  }
668  break;
669  default:
670  av_log(s, AV_LOG_ERROR, "Only audio, video, and subtitles are supported for Matroska.\n");
671  break;
672  }
673  ret = mkv_write_codecprivate(s, pb, codec, native_id, qt_id);
674  if (ret < 0) return ret;
675 
676  end_ebml_master(pb, track);
677 
678  // ms precision is the de-facto standard timescale for mkv files
679  avpriv_set_pts_info(st, 64, 1, 1000);
680  }
681  end_ebml_master(pb, tracks);
682  return 0;
683 }
684 
686 {
687  MatroskaMuxContext *mkv = s->priv_data;
688  AVIOContext *pb = s->pb;
689  ebml_master chapters, editionentry;
690  AVRational scale = {1, 1E9};
691  int i, ret;
692 
693  if (!s->nb_chapters)
694  return 0;
695 
697  if (ret < 0) return ret;
698 
699  chapters = start_ebml_master(pb, MATROSKA_ID_CHAPTERS , 0);
700  editionentry = start_ebml_master(pb, MATROSKA_ID_EDITIONENTRY, 0);
703  for (i = 0; i < s->nb_chapters; i++) {
704  ebml_master chapteratom, chapterdisplay;
705  AVChapter *c = s->chapters[i];
707 
708  chapteratom = start_ebml_master(pb, MATROSKA_ID_CHAPTERATOM, 0);
711  av_rescale_q(c->start, c->time_base, scale));
713  av_rescale_q(c->end, c->time_base, scale));
716  if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
717  chapterdisplay = start_ebml_master(pb, MATROSKA_ID_CHAPTERDISPLAY, 0);
720  end_ebml_master(pb, chapterdisplay);
721  }
722  end_ebml_master(pb, chapteratom);
723  }
724  end_ebml_master(pb, editionentry);
725  end_ebml_master(pb, chapters);
726  return 0;
727 }
728 
730 {
731  uint8_t *key = av_strdup(t->key);
732  uint8_t *p = key;
733  const uint8_t *lang = NULL;
735 
736  if ((p = strrchr(p, '-')) &&
737  (lang = av_convert_lang_to(p + 1, AV_LANG_ISO639_2_BIBL)))
738  *p = 0;
739 
740  p = key;
741  while (*p) {
742  if (*p == ' ')
743  *p = '_';
744  else if (*p >= 'a' && *p <= 'z')
745  *p -= 'a' - 'A';
746  p++;
747  }
748 
751  if (lang)
754  end_ebml_master(pb, tag);
755 
756  av_freep(&key);
757 }
758 
759 static int mkv_write_tag(AVFormatContext *s, AVDictionary *m, unsigned int elementid,
760  unsigned int uid, ebml_master *tags)
761 {
762  MatroskaMuxContext *mkv = s->priv_data;
763  ebml_master tag, targets;
765  int ret;
766 
767  if (!tags->pos) {
769  if (ret < 0) return ret;
770 
771  *tags = start_ebml_master(s->pb, MATROSKA_ID_TAGS, 0);
772  }
773 
774  tag = start_ebml_master(s->pb, MATROSKA_ID_TAG, 0);
775  targets = start_ebml_master(s->pb, MATROSKA_ID_TAGTARGETS, 0);
776  if (elementid)
777  put_ebml_uint(s->pb, elementid, uid);
778  end_ebml_master(s->pb, targets);
779 
780  while ((t = av_dict_get(m, "", t, AV_DICT_IGNORE_SUFFIX)))
781  if (av_strcasecmp(t->key, "title") &&
782  av_strcasecmp(t->key, "encoding_tool"))
783  mkv_write_simpletag(s->pb, t);
784 
785  end_ebml_master(s->pb, tag);
786  return 0;
787 }
788 
790 {
791  ebml_master tags = {0};
792  int i, ret;
793 
795 
797  ret = mkv_write_tag(s, s->metadata, 0, 0, &tags);
798  if (ret < 0) return ret;
799  }
800 
801  for (i = 0; i < s->nb_streams; i++) {
802  AVStream *st = s->streams[i];
803 
804  if (!av_dict_get(st->metadata, "", 0, AV_DICT_IGNORE_SUFFIX))
805  continue;
806 
807  ret = mkv_write_tag(s, st->metadata, MATROSKA_ID_TAGTARGETS_TRACKUID, i + 1, &tags);
808  if (ret < 0) return ret;
809  }
810 
811  for (i = 0; i < s->nb_chapters; i++) {
812  AVChapter *ch = s->chapters[i];
813 
815  continue;
816 
817  ret = mkv_write_tag(s, ch->metadata, MATROSKA_ID_TAGTARGETS_CHAPTERUID, ch->id, &tags);
818  if (ret < 0) return ret;
819  }
820 
821  if (tags.pos)
822  end_ebml_master(s->pb, tags);
823  return 0;
824 }
825 
827 {
828  MatroskaMuxContext *mkv = s->priv_data;
829  AVIOContext *pb = s->pb;
830  ebml_master attachments;
831  AVLFG c;
832  int i, ret;
833 
834  if (!mkv->have_attachments)
835  return 0;
836 
838 
840  if (ret < 0) return ret;
841 
842  attachments = start_ebml_master(pb, MATROSKA_ID_ATTACHMENTS, 0);
843 
844  for (i = 0; i < s->nb_streams; i++) {
845  AVStream *st = s->streams[i];
846  ebml_master attached_file;
848  const char *mimetype = NULL;
849 
851  continue;
852 
853  attached_file = start_ebml_master(pb, MATROSKA_ID_ATTACHEDFILE, 0);
854 
855  if (t = av_dict_get(st->metadata, "title", NULL, 0))
857  if (!(t = av_dict_get(st->metadata, "filename", NULL, 0))) {
858  av_log(s, AV_LOG_ERROR, "Attachment stream %d has no filename tag.\n", i);
859  return AVERROR(EINVAL);
860  }
862  if (t = av_dict_get(st->metadata, "mimetype", NULL, 0))
863  mimetype = t->value;
864  else if (st->codec->codec_id != AV_CODEC_ID_NONE ) {
865  int i;
866  for (i = 0; ff_mkv_mime_tags[i].id != AV_CODEC_ID_NONE; i++)
867  if (ff_mkv_mime_tags[i].id == st->codec->codec_id) {
868  mimetype = ff_mkv_mime_tags[i].str;
869  break;
870  }
871  }
872  if (!mimetype) {
873  av_log(s, AV_LOG_ERROR, "Attachment stream %d has no mimetype tag and "
874  "it cannot be deduced from the codec id.\n", i);
875  return AVERROR(EINVAL);
876  }
877 
881  end_ebml_master(pb, attached_file);
882  }
883  end_ebml_master(pb, attachments);
884 
885  return 0;
886 }
887 
889 {
890  MatroskaMuxContext *mkv = s->priv_data;
891  AVIOContext *pb = s->pb;
892  ebml_master ebml_header, segment_info;
894  int ret, i;
895 
896  if (!strcmp(s->oformat->name, "webm")) mkv->mode = MODE_WEBM;
897  else mkv->mode = MODE_MATROSKAv2;
898 
899  mkv->tracks = av_mallocz(s->nb_streams * sizeof(*mkv->tracks));
900  if (!mkv->tracks)
901  return AVERROR(ENOMEM);
902 
903  ebml_header = start_ebml_master(pb, EBML_ID_HEADER, 0);
911  end_ebml_master(pb, ebml_header);
912 
914  mkv->segment_offset = avio_tell(pb);
915 
916  // we write 2 seek heads - one at the end of the file to point to each
917  // cluster, and one at the beginning to point to all other level one
918  // elements (including the seek head at the end of the file), which
919  // isn't more than 10 elements if we only write one of each other
920  // currently defined level 1 element
921  mkv->main_seekhead = mkv_start_seekhead(pb, mkv->segment_offset, 10);
922  if (!mkv->main_seekhead)
923  return AVERROR(ENOMEM);
924 
926  if (ret < 0) return ret;
927 
928  segment_info = start_ebml_master(pb, MATROSKA_ID_INFO, 0);
930  if ((tag = av_dict_get(s->metadata, "title", NULL, 0)))
932  if (!(s->streams[0]->codec->flags & CODEC_FLAG_BITEXACT)) {
933  uint32_t segment_uid[4];
934  AVLFG lfg;
935 
937 
938  for (i = 0; i < 4; i++)
939  segment_uid[i] = av_lfg_get(&lfg);
940 
942  if ((tag = av_dict_get(s->metadata, "encoding_tool", NULL, 0)))
944  else
946  put_ebml_binary(pb, MATROSKA_ID_SEGMENTUID, segment_uid, 16);
947  }
948 
949  // reserve space for the duration
950  mkv->duration = 0;
951  mkv->duration_offset = avio_tell(pb);
952  put_ebml_void(pb, 11); // assumes double-precision float to be written
953  end_ebml_master(pb, segment_info);
954 
955  ret = mkv_write_tracks(s);
956  if (ret < 0) return ret;
957 
958  if (mkv->mode != MODE_WEBM) {
959  ret = mkv_write_chapters(s);
960  if (ret < 0) return ret;
961 
962  ret = mkv_write_tags(s);
963  if (ret < 0) return ret;
964 
965  ret = mkv_write_attachments(s);
966  if (ret < 0) return ret;
967  }
968 
969  if (!s->pb->seekable)
971 
972  mkv->cues = mkv_start_cues(mkv->segment_offset);
973  if (mkv->cues == NULL)
974  return AVERROR(ENOMEM);
975 
977  mkv->cur_audio_pkt.size = 0;
978  mkv->audio_buffer_size = 0;
979 
980  avio_flush(pb);
981  return 0;
982 }
983 
984 static int mkv_blockgroup_size(int pkt_size)
985 {
986  int size = pkt_size + 4;
987  size += ebml_num_size(size);
988  size += 2; // EBML ID for block and block duration
989  size += 8; // max size of block duration
990  size += ebml_num_size(size);
991  size += 1; // blockgroup EBML ID
992  return size;
993 }
994 
995 static int ass_get_duration(const uint8_t *p)
996 {
997  int sh, sm, ss, sc, eh, em, es, ec;
998  uint64_t start, end;
999 
1000  if (sscanf(p, "%*[^,],%d:%d:%d%*c%d,%d:%d:%d%*c%d",
1001  &sh, &sm, &ss, &sc, &eh, &em, &es, &ec) != 8)
1002  return 0;
1003  start = 3600000*sh + 60000*sm + 1000*ss + 10*sc;
1004  end = 3600000*eh + 60000*em + 1000*es + 10*ec;
1005  return end - start;
1006 }
1007 
1009 {
1010  MatroskaMuxContext *mkv = s->priv_data;
1011  int i, layer = 0, max_duration = 0, size, line_size, data_size = pkt->size;
1012  uint8_t *start, *end, *data = pkt->data;
1013  ebml_master blockgroup;
1014  char buffer[2048];
1015 
1016  while (data_size) {
1017  int duration = ass_get_duration(data);
1018  max_duration = FFMAX(duration, max_duration);
1019  end = memchr(data, '\n', data_size);
1020  size = line_size = end ? end-data+1 : data_size;
1021  size -= end ? (end[-1]=='\r')+1 : 0;
1022  start = data;
1023  for (i=0; i<3; i++, start++)
1024  if (!(start = memchr(start, ',', size-(start-data))))
1025  return max_duration;
1026  size -= start - data;
1027  sscanf(data, "Dialogue: %d,", &layer);
1028  i = snprintf(buffer, sizeof(buffer), "%"PRId64",%d,",
1029  s->streams[pkt->stream_index]->nb_frames, layer);
1030  size = FFMIN(i+size, sizeof(buffer));
1031  memcpy(buffer+i, start, size-i);
1032 
1033  av_log(s, AV_LOG_DEBUG, "Writing block at offset %" PRIu64 ", size %d, "
1034  "pts %" PRId64 ", duration %d\n",
1035  avio_tell(pb), size, pkt->pts, duration);
1038  put_ebml_num(pb, size+4, 0);
1039  avio_w8(pb, 0x80 | (pkt->stream_index + 1)); // this assumes stream_index is less than 126
1040  avio_wb16(pb, pkt->pts - mkv->cluster_pts);
1041  avio_w8(pb, 0);
1042  avio_write(pb, buffer, size);
1044  end_ebml_master(pb, blockgroup);
1045 
1046  data += line_size;
1047  data_size -= line_size;
1048  }
1049 
1050  return max_duration;
1051 }
1052 
1054  unsigned int blockid, AVPacket *pkt, int flags)
1055 {
1056  MatroskaMuxContext *mkv = s->priv_data;
1057  AVCodecContext *codec = s->streams[pkt->stream_index]->codec;
1058  uint8_t *data = NULL;
1059  int offset = 0, size = pkt->size;
1060  int64_t ts = mkv->tracks[pkt->stream_index].write_dts ? pkt->dts : pkt->pts;
1061 
1062  av_log(s, AV_LOG_DEBUG, "Writing block at offset %" PRIu64 ", size %d, "
1063  "pts %" PRId64 ", dts %" PRId64 ", duration %d, flags %d\n",
1064  avio_tell(pb), pkt->size, pkt->pts, pkt->dts, pkt->duration, flags);
1065  if (codec->codec_id == AV_CODEC_ID_H264 && codec->extradata_size > 0 &&
1066  (AV_RB24(codec->extradata) == 1 || AV_RB32(codec->extradata) == 1))
1067  ff_avc_parse_nal_units_buf(pkt->data, &data, &size);
1068  else
1069  data = pkt->data;
1070 
1071  if (codec->codec_id == AV_CODEC_ID_PRORES) {
1072  /* Matroska specification requires to remove the first QuickTime atom
1073  */
1074  size -= 8;
1075  offset = 8;
1076  }
1077 
1078  put_ebml_id(pb, blockid);
1079  put_ebml_num(pb, size+4, 0);
1080  avio_w8(pb, 0x80 | (pkt->stream_index + 1)); // this assumes stream_index is less than 126
1081  avio_wb16(pb, ts - mkv->cluster_pts);
1082  avio_w8(pb, flags);
1083  avio_write(pb, data + offset, size);
1084  if (data != pkt->data)
1085  av_free(data);
1086 }
1087 
1088 static int srt_get_duration(uint8_t **buf)
1089 {
1090  int i, duration = 0;
1091 
1092  for (i=0; i<2 && !duration; i++) {
1093  int s_hour, s_min, s_sec, s_hsec, e_hour, e_min, e_sec, e_hsec;
1094  if (sscanf(*buf, "%d:%2d:%2d%*1[,.]%3d --> %d:%2d:%2d%*1[,.]%3d",
1095  &s_hour, &s_min, &s_sec, &s_hsec,
1096  &e_hour, &e_min, &e_sec, &e_hsec) == 8) {
1097  s_min += 60*s_hour; e_min += 60*e_hour;
1098  s_sec += 60*s_min; e_sec += 60*e_min;
1099  s_hsec += 1000*s_sec; e_hsec += 1000*e_sec;
1100  duration = e_hsec - s_hsec;
1101  }
1102  *buf += strcspn(*buf, "\n") + 1;
1103  }
1104  return duration;
1105 }
1106 
1108 {
1109  ebml_master blockgroup;
1110  AVPacket pkt2 = *pkt;
1111  int64_t duration = srt_get_duration(&pkt2.data);
1112  pkt2.size -= pkt2.data - pkt->data;
1113 
1114  blockgroup = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP,
1115  mkv_blockgroup_size(pkt2.size));
1116  mkv_write_block(s, pb, MATROSKA_ID_BLOCK, &pkt2, 0);
1118  end_ebml_master(pb, blockgroup);
1119 
1120  return duration;
1121 }
1122 
1124 {
1125  MatroskaMuxContext *mkv = s->priv_data;
1126  int bufsize;
1127  uint8_t *dyn_buf;
1128 
1129  if (!mkv->dyn_bc)
1130  return;
1131 
1132  bufsize = avio_close_dyn_buf(mkv->dyn_bc, &dyn_buf);
1133  avio_write(s->pb, dyn_buf, bufsize);
1134  av_free(dyn_buf);
1135  mkv->dyn_bc = NULL;
1136 }
1137 
1139 {
1140  MatroskaMuxContext *mkv = s->priv_data;
1141  AVIOContext *pb = s->pb;
1142  AVCodecContext *codec = s->streams[pkt->stream_index]->codec;
1143  int keyframe = !!(pkt->flags & AV_PKT_FLAG_KEY);
1144  int duration = pkt->duration;
1145  int ret;
1146  int64_t ts = mkv->tracks[pkt->stream_index].write_dts ? pkt->dts : pkt->pts;
1147 
1148  if (ts == AV_NOPTS_VALUE) {
1149  av_log(s, AV_LOG_ERROR, "Can't write packet with unknown timestamp\n");
1150  return AVERROR(EINVAL);
1151  }
1152 
1153  if (!s->pb->seekable) {
1154  if (!mkv->dyn_bc)
1155  avio_open_dyn_buf(&mkv->dyn_bc);
1156  pb = mkv->dyn_bc;
1157  }
1158 
1159  if (!mkv->cluster_pos) {
1160  mkv->cluster_pos = avio_tell(s->pb);
1163  mkv->cluster_pts = FFMAX(0, ts);
1164  }
1165 
1166  if (codec->codec_type != AVMEDIA_TYPE_SUBTITLE) {
1167  mkv_write_block(s, pb, MATROSKA_ID_SIMPLEBLOCK, pkt, keyframe << 7);
1168  } else if (codec->codec_id == AV_CODEC_ID_SSA) {
1169  duration = mkv_write_ass_blocks(s, pb, pkt);
1170  } else if (codec->codec_id == AV_CODEC_ID_SRT) {
1171  duration = mkv_write_srt_blocks(s, pb, pkt);
1172  } else {
1174  duration = pkt->convergence_duration;
1175  mkv_write_block(s, pb, MATROSKA_ID_BLOCK, pkt, 0);
1177  end_ebml_master(pb, blockgroup);
1178  }
1179 
1180  if (codec->codec_type == AVMEDIA_TYPE_VIDEO && keyframe) {
1181  ret = mkv_add_cuepoint(mkv->cues, pkt->stream_index, ts, mkv->cluster_pos);
1182  if (ret < 0) return ret;
1183  }
1184 
1185  mkv->duration = FFMAX(mkv->duration, ts + duration);
1186  return 0;
1187 }
1188 
1189 static int mkv_copy_packet(MatroskaMuxContext *mkv, const AVPacket *pkt)
1190 {
1191  uint8_t *data = mkv->cur_audio_pkt.data;
1192  mkv->cur_audio_pkt = *pkt;
1193  mkv->cur_audio_pkt.data = av_fast_realloc(data, &mkv->audio_buffer_size, pkt->size);
1194  if (!mkv->cur_audio_pkt.data)
1195  return AVERROR(ENOMEM);
1196 
1197  memcpy(mkv->cur_audio_pkt.data, pkt->data, pkt->size);
1198  mkv->cur_audio_pkt.size = pkt->size;
1199  return 0;
1200 }
1201 
1203 {
1204  MatroskaMuxContext *mkv = s->priv_data;
1205  AVIOContext *pb = s->pb->seekable ? s->pb : mkv->dyn_bc;
1206  AVCodecContext *codec = s->streams[pkt->stream_index]->codec;
1207  int ret, keyframe = !!(pkt->flags & AV_PKT_FLAG_KEY);
1208  int64_t ts;
1209  int cluster_size = avio_tell(pb) - (s->pb->seekable ? mkv->cluster_pos : 0);
1210 
1211  if (pkt->dts < 0 && !mkv->ts_offset)
1212  mkv->ts_offset = -pkt->dts;
1213 
1214  pkt->dts += mkv->ts_offset;
1215  if (pkt->pts != AV_NOPTS_VALUE)
1216  pkt->pts += mkv->ts_offset;
1217 
1218  ts = mkv->tracks[pkt->stream_index].write_dts ? pkt->dts : pkt->pts;
1219 
1220  // start a new cluster every 5 MB or 5 sec, or 32k / 1 sec for streaming or
1221  // after 4k and on a keyframe
1222  if (mkv->cluster_pos &&
1223  ((!s->pb->seekable && (cluster_size > 32*1024 || ts > mkv->cluster_pts + 1000))
1224  || cluster_size > 5*1024*1024 || ts > mkv->cluster_pts + 5000
1225  || (codec->codec_type == AVMEDIA_TYPE_VIDEO && keyframe && cluster_size > 4*1024))) {
1226  av_log(s, AV_LOG_DEBUG, "Starting new cluster at offset %" PRIu64
1227  " bytes, pts %" PRIu64 "\n", avio_tell(pb), ts);
1228  end_ebml_master(pb, mkv->cluster);
1229  mkv->cluster_pos = 0;
1230  if (mkv->dyn_bc)
1231  mkv_flush_dynbuf(s);
1232  }
1233 
1234  // check if we have an audio packet cached
1235  if (mkv->cur_audio_pkt.size > 0) {
1236  ret = mkv_write_packet_internal(s, &mkv->cur_audio_pkt);
1237  mkv->cur_audio_pkt.size = 0;
1238  if (ret < 0) {
1239  av_log(s, AV_LOG_ERROR, "Could not write cached audio packet ret:%d\n", ret);
1240  return ret;
1241  }
1242  }
1243 
1244  // buffer an audio packet to ensure the packet containing the video
1245  // keyframe's timecode is contained in the same cluster for WebM
1246  if (codec->codec_type == AVMEDIA_TYPE_AUDIO)
1247  ret = mkv_copy_packet(mkv, pkt);
1248  else
1249  ret = mkv_write_packet_internal(s, pkt);
1250  return ret;
1251 }
1252 
1254 {
1255  MatroskaMuxContext *mkv = s->priv_data;
1256  AVIOContext *pb = s->pb;
1257  int64_t currentpos, cuespos;
1258  int ret;
1259 
1260  // check if we have an audio packet cached
1261  if (mkv->cur_audio_pkt.size > 0) {
1262  ret = mkv_write_packet_internal(s, &mkv->cur_audio_pkt);
1263  mkv->cur_audio_pkt.size = 0;
1264  if (ret < 0) {
1265  av_log(s, AV_LOG_ERROR, "Could not write cached audio packet ret:%d\n", ret);
1266  return ret;
1267  }
1268  }
1269 
1270  if (mkv->dyn_bc) {
1271  end_ebml_master(mkv->dyn_bc, mkv->cluster);
1272  mkv_flush_dynbuf(s);
1273  } else if (mkv->cluster_pos) {
1274  end_ebml_master(pb, mkv->cluster);
1275  }
1276 
1277  if (pb->seekable) {
1278  if (mkv->cues->num_entries) {
1279  cuespos = mkv_write_cues(pb, mkv->cues, s->nb_streams);
1280 
1282  if (ret < 0) return ret;
1283  }
1284 
1286 
1287  // update the duration
1288  av_log(s, AV_LOG_DEBUG, "end duration = %" PRIu64 "\n", mkv->duration);
1289  currentpos = avio_tell(pb);
1290  avio_seek(pb, mkv->duration_offset, SEEK_SET);
1292 
1293  avio_seek(pb, currentpos, SEEK_SET);
1294  }
1295 
1296  end_ebml_master(pb, mkv->segment);
1297  av_free(mkv->tracks);
1298  av_freep(&mkv->cues->entries);
1299  av_freep(&mkv->cues);
1301 
1302  return 0;
1303 }
1304 
1305 static int mkv_query_codec(enum AVCodecID codec_id, int std_compliance)
1306 {
1307  int i;
1308  for (i = 0; ff_mkv_codec_tags[i].id != AV_CODEC_ID_NONE; i++)
1309  if (ff_mkv_codec_tags[i].id == codec_id)
1310  return 1;
1311 
1312  if (std_compliance < FF_COMPLIANCE_NORMAL) { // mkv theoretically supports any
1313  enum AVMediaType type = avcodec_get_type(codec_id); // video/audio through VFW/ACM
1314  if (type == AVMEDIA_TYPE_VIDEO || type == AVMEDIA_TYPE_AUDIO)
1315  return 1;
1316  }
1317 
1318  return 0;
1319 }
1320 
1321 #if CONFIG_MATROSKA_MUXER
1322 AVOutputFormat ff_matroska_muxer = {
1323  .name = "matroska",
1324  .long_name = NULL_IF_CONFIG_SMALL("Matroska"),
1325  .mime_type = "video/x-matroska",
1326  .extensions = "mkv",
1327  .priv_data_size = sizeof(MatroskaMuxContext),
1328  .audio_codec = CONFIG_LIBVORBIS_ENCODER ?
1330  .video_codec = CONFIG_LIBX264_ENCODER ?
1337  .codec_tag = (const AVCodecTag* const []){
1339  },
1340  .subtitle_codec = AV_CODEC_ID_SSA,
1341  .query_codec = mkv_query_codec,
1342 };
1343 #endif
1344 
1345 #if CONFIG_WEBM_MUXER
1346 AVOutputFormat ff_webm_muxer = {
1347  .name = "webm",
1348  .long_name = NULL_IF_CONFIG_SMALL("WebM"),
1349  .mime_type = "video/webm",
1350  .extensions = "webm",
1351  .priv_data_size = sizeof(MatroskaMuxContext),
1352  .audio_codec = AV_CODEC_ID_VORBIS,
1353  .video_codec = AV_CODEC_ID_VP8,
1359 };
1360 #endif
1361 
1362 #if CONFIG_MATROSKA_AUDIO_MUXER
1363 AVOutputFormat ff_matroska_audio_muxer = {
1364  .name = "matroska",
1365  .long_name = NULL_IF_CONFIG_SMALL("Matroska"),
1366  .mime_type = "audio/x-matroska",
1367  .extensions = "mka",
1368  .priv_data_size = sizeof(MatroskaMuxContext),
1369  .audio_codec = CONFIG_LIBVORBIS_ENCODER ?
1370  AV_CODEC_ID_VORBIS : AV_CODEC_ID_AC3,
1371  .video_codec = AV_CODEC_ID_NONE,
1376  .codec_tag = (const AVCodecTag* const []){ ff_codec_wav_tags, 0 },
1377 };
1378 #endif
unsigned int nb_chapters
Definition: avformat.h:969
Definition: lfg.h:25
void avio_wb64(AVIOContext *s, uint64_t val)
Definition: aviobuf.c:330
#define MATROSKA_ID_TRACKDEFAULTDURATION
Definition: matroska.h:97
static void put_ebml_size_unknown(AVIOContext *pb, int bytes)
Write an EBML size meaning "unknown size".
Definition: matroskaenc.c:131
Bytestream IO Context.
Definition: avio.h:68
int size
int sizebytes
how many bytes were reserved for the size
Definition: matroskaenc.c:43
#define MATROSKA_ID_TRACKFLAGLACING
Definition: matroska.h:94
#define MATROSKA_ID_TRACKENTRY
Definition: matroska.h:75
#define MATROSKA_ID_VIDEODISPLAYHEIGHT
Definition: matroska.h:106
int avio_close_dyn_buf(AVIOContext *s, uint8_t **pbuffer)
Return the written size and a pointer to the buffer.
Definition: aviobuf.c:945
int64_t cluster_pos
file offset of the cluster containing the block
Definition: matroskaenc.c:63
static void mkv_write_simpletag(AVIOContext *pb, AVDictionaryEntry *t)
Definition: matroskaenc.c:729
#define MATROSKA_ID_CUETRACKPOSITION
Definition: matroska.h:139
#define MATROSKA_ID_CODECPRIVATE
Definition: matroska.h:84
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:3283
#define MATROSKA_ID_AUDIOBITDEPTH
Definition: matroska.h:123
#define MATROSKA_ID_TRACKFLAGDEFAULT
Definition: matroska.h:92
static int write_packet(AVFormatContext *s, AVPacket *pkt)
Definition: assenc.c:58
static int mkv_write_attachments(AVFormatContext *s)
Definition: matroskaenc.c:826
uint64_t pts
Definition: matroskaenc.c:61
AVRational sample_aspect_ratio
sample aspect ratio (0 if unknown)
Definition: avformat.h:697
int num
numerator
Definition: rational.h:44
int size
Definition: avcodec.h:916
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:185
#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:888
#define MATROSKA_ID_TRACKTYPE
Definition: matroska.h:80
#define MATROSKA_ID_TAGTARGETS_CHAPTERUID
Definition: matroska.h:158
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
#define MATROSKA_ID_AUDIOCHANNELS
Definition: matroska.h:124
unsigned int ff_codec_get_tag(const AVCodecTag *tags, enum AVCodecID id)
Definition: utils.c:2116
int64_t segment_offset
Definition: matroskaenc.c:67
#define MATROSKA_ID_CUECLUSTERPOSITION
Definition: matroska.h:143
Definition: matroskaenc.c:46
AVDictionary * metadata
Definition: avformat.h:817
AVDictionaryEntry * av_dict_get(AVDictionary *m, const char *key, const AVDictionaryEntry *prev, int flags)
Get a dictionary entry with matching key.
Definition: dict.c:40
mkv_track * tracks
Definition: matroskaenc.c:91
#define MATROSKA_ID_EDITIONFLAGDEFAULT
Definition: matroska.h:198
#define MATROSKA_ID_CLUSTERTIMECODE
Definition: matroska.h:169
int avio_open_dyn_buf(AVIOContext **s)
Open a write only memory stream.
Definition: aviobuf.c:933
#define EBML_ID_DOCTYPE
Definition: matroska.h:40
#define MATROSKA_ID_CHAPTERTIMEEND
Definition: matroska.h:192
static int64_t duration
Definition: avplay.c:249
int64_t pos
absolute offset in the file where the master's elements start
Definition: matroskaenc.c:42
AVRational time_base
This is the fundamental unit of time (in seconds) in terms of which frame timestamps are represented...
Definition: avcodec.h:1465
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:151
static int64_t mkv_write_cues(AVIOContext *pb, mkv_cues *cues, int num_tracks)
Definition: matroskaenc.c:388
#define MATROSKA_ID_FILEDESC
Definition: matroska.h:182
Format I/O context.
Definition: avformat.h:828
char str[32]
Definition: internal.h:41
int64_t cluster_pos
file offset of the current cluster
Definition: matroskaenc.c:85
Public dictionary API.
enum AVSampleFormat sample_fmt
audio sample format
Definition: avcodec.h:2112
uint8_t
#define MATROSKA_ID_CHAPLANG
Definition: matroska.h:195
static int srt_get_duration(uint8_t **buf)
Definition: matroskaenc.c:1088
static int mkv_write_tag(AVFormatContext *s, AVDictionary *m, unsigned int elementid, unsigned int uid, ebml_master *tags)
Definition: matroskaenc.c:759
#define MATROSKA_ID_TRACKLANGUAGE
Definition: matroska.h:90
const AVCodecTag ff_codec_movvideo_tags[]
Definition: isom.c:68
static int ebml_id_size(unsigned int id)
Definition: matroskaenc.c:114
#define AV_RB32
Definition: intreadwrite.h:130
uint64_t segmentpos
Definition: matroskaenc.c:48
int id
unique ID to identify the chapter
Definition: avformat.h:814
#define MATROSKA_ID_TIMECODESCALE
Definition: matroska.h:66
#define MATROSKA_ID_SIMPLEBLOCK
Definition: matroska.h:173
#define MATROSKA_ID_EDITIONFLAGHIDDEN
Definition: matroska.h:197
uint8_t * extradata
some codecs need / can use extradata like Huffman tables.
Definition: avcodec.h:1454
static int mkv_write_srt_blocks(AVFormatContext *s, AVIOContext *pb, AVPacket *pkt)
Definition: matroskaenc.c:1107
AVStream ** streams
Definition: avformat.h:876
#define MATROSKA_ID_AUDIOOUTSAMPLINGFREQ
Definition: matroska.h:121
const char data[16]
Definition: mxf.c:66
static double av_q2d(AVRational a)
Convert rational to double.
Definition: rational.h:69
uint8_t * data
Definition: avcodec.h:915
#define MATROSKA_ID_VIDEODISPLAYWIDTH
Definition: matroska.h:105
static int flags
Definition: log.c:42
uint32_t tag
Definition: movenc.c:802
static void get_aac_sample_rates(AVFormatContext *s, AVCodecContext *codec, int *sample_rate, int *output_sample_rate)
Definition: matroskaenc.c:449
static EbmlSyntax ebml_header[]
Definition: matroskadec.c:272
enum AVCodecID id
Definition: internal.h:42
struct MatroskaMuxContext MatroskaMuxContext
unsigned int audio_buffer_size
Definition: matroskaenc.c:93
#define MATROSKA_ID_CUES
Definition: matroska.h:58
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
int duration
Duration of this packet in AVStream->time_base units, 0 if unknown.
Definition: avcodec.h:937
#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:155
static int write_trailer(AVFormatContext *s)
Definition: assenc.c:67
static float t
static int mkv_copy_packet(MatroskaMuxContext *mkv, const AVPacket *pkt)
Definition: matroskaenc.c:1189
static int mkv_add_seekhead_entry(mkv_seekhead *seekhead, unsigned int elementid, uint64_t filepos)
Definition: matroskaenc.c:287
int64_t segment_offset
the file offset to the beginning of the segment
Definition: matroskaenc.c:53
struct AVOutputFormat * oformat
Definition: avformat.h:842
#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:122
ebml_master segment
Definition: matroskaenc.c:82
#define MATROSKA_ID_VIDEOSTEREOMODE
Definition: matroska.h:115
AVPacket cur_audio_pkt
Definition: matroskaenc.c:94
AVCodecID
Identify the syntax and semantics of the bitstream.
Definition: avcodec.h:95
static int mkv_write_tags(AVFormatContext *s)
Definition: matroskaenc.c:789
AVDictionary * metadata
Definition: avformat.h:972
int av_get_bits_per_sample(enum AVCodecID codec_id)
Return codec bits per sample.
Definition: utils.c:1813
void av_free(void *ptr)
Free a memory block which has been allocated with av_malloc(z)() or av_realloc(). ...
Definition: mem.c:139
struct mkv_seekhead mkv_seekhead
#define MATROSKA_ID_BLOCKDURATION
Definition: matroska.h:177
#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:108
void * av_fast_realloc(void *ptr, unsigned int *size, size_t min_size)
Reallocate the given block if it is not large enough, otherwise do nothing.
Definition: utils.c:53
static int mkv_write_ass_blocks(AVFormatContext *s, AVIOContext *pb, AVPacket *pkt)
Definition: matroskaenc.c:1008
unsigned int elementid
Definition: matroskaenc.c:47
int reserved_size
-1 if appending to file
Definition: matroskaenc.c:54
#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:421
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification. ...
Definition: internal.h:88
#define MATROSKA_ID_FILEMIMETYPE
Definition: matroska.h:184
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:959
#define MATROSKA_ID_WRITINGAPP
Definition: matroska.h:69
static int mkv_blockgroup_size(int pkt_size)
Definition: matroskaenc.c:984
int flags
CODEC_FLAG_*.
Definition: avcodec.h:1434
static int ebml_num_size(uint64_t num)
Calculate how many bytes are needed to represent a given number in EBML.
Definition: matroskaenc.c:142
int write_dts
Definition: matroskaenc.c:73
AVChapter ** chapters
Definition: avformat.h:970
enum AVCodecID id
Definition: matroska.h:246
void av_log(void *avcl, int level, const char *fmt,...)
Definition: log.c:146
enum AVMediaType avcodec_get_type(enum AVCodecID codec_id)
Get the type of the given codec.
Definition: utils.c:2132
static int mkv_write_chapters(AVFormatContext *s)
Definition: matroskaenc.c:685
#define EBML_ID_EBMLMAXIDLENGTH
Definition: matroska.h:38
#define MATROSKA_ID_CHAPTERFLAGHIDDEN
Definition: matroska.h:201
enum AVCodecID codec_id
Definition: mov_chan.c:432
const AVCodecTag ff_codec_wav_tags[]
Definition: riff.c:297
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:267
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:52
int flags
A combination of AV_PKT_FLAG values.
Definition: avcodec.h:921
static void mkv_write_block(AVFormatContext *s, AVIOContext *pb, unsigned int blockid, AVPacket *pkt, int flags)
Definition: matroskaenc.c:1053
AVCodecContext * codec
Codec context associated with this stream.
Definition: avformat.h:641
const CodecMime ff_mkv_mime_tags[]
Definition: matroska.c:88
#define MATROSKA_ID_TAG
Definition: matroska.h:147
unsigned int nb_streams
A list of all streams in the file.
Definition: avformat.h:875
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
#define EBML_ID_EBMLVERSION
Definition: matroska.h:36
mkv_cuepoint * entries
Definition: matroskaenc.c:68
#define MATROSKA_ID_TAGTARGETS
Definition: matroska.h:154
const AVCodecTag ff_codec_bmp_tags[]
Definition: riff.c:31
int av_strcasecmp(const char *a, const char *b)
Definition: avstring.c:140
#define MATROSKA_ID_TAGNAME
Definition: matroska.h:149
int width
picture width / height.
Definition: avcodec.h:1508
#define MATROSKA_ID_CHAPTERFLAGENABLED
Definition: matroska.h:202
#define MATROSKA_ID_SIMPLETAG
Definition: matroska.h:148
const char * name
Definition: avformat.h:376
internal header for RIFF based (de)muxers do NOT include this in end user applications ...
static char buffer[20]
Definition: seek-test.c:31
#define MATROSKA_ID_CHAPTERATOM
Definition: matroska.h:190
AVDictionary * metadata
Definition: avformat.h:699
Opaque data information usually sparse.
Definition: avutil.h:183
#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:369
#define EBML_ID_VOID
Definition: matroska.h:45
#define MATROSKA_ID_AUDIOSAMPLINGFREQ
Definition: matroska.h:120
int av_get_bytes_per_sample(enum AVSampleFormat sample_fmt)
Return number of bytes per sample.
Definition: samplefmt.c:95
static void put_ebml_float(AVIOContext *pb, unsigned int elementid, double val)
Definition: matroskaenc.c:186
Stream structure.
Definition: avformat.h:622
static void put_ebml_string(AVIOContext *pb, unsigned int elementid, const char *str)
Definition: matroskaenc.c:201
int64_t end
chapter start/end time in time_base units
Definition: avformat.h:816
NULL
Definition: eval.c:52
#define MATROSKA_ID_TAGS
Definition: matroska.h:59
enum AVMediaType codec_type
Definition: avcodec.h:1347
#define CONFIG_LIBX264_ENCODER
Definition: config.h:951
enum AVCodecID codec_id
Definition: avcodec.h:1350
#define MATROSKA_ID_SEEKID
Definition: matroska.h:165
char * av_strdup(const char *s)
Duplicate the string s.
Definition: mem.c:166
int sample_rate
samples per second
Definition: avcodec.h:2104
AVIOContext * pb
I/O context.
Definition: avformat.h:861
void av_destruct_packet(AVPacket *pkt)
Default packet destructor.
Definition: avpacket.c:28
void avio_w8(AVIOContext *s, int b)
Definition: aviobuf.c:144
struct mkv_seekhead_entry mkv_seekhead_entry
main external API structure.
Definition: avcodec.h:1339
#define MATROSKA_ID_BLOCK
Definition: matroska.h:176
#define MATROSKA_ID_INFO
Definition: matroska.h:56
#define MATROSKA_ID_TAGTARGETS_TRACKUID
Definition: matroska.h:157
#define MATROSKA_ID_TAGLANG
Definition: matroska.h:151
unsigned int codec_tag
fourcc (LSB first, so "ABCD" -> ('D'<<24) + ('C'<<16) + ('B'<<8) + 'A').
Definition: avcodec.h:1365
struct ebml_master ebml_master
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:1455
#define MATROSKA_ID_TRACKNAME
Definition: matroska.h:89
#define MATROSKA_ID_SEEKENTRY
Definition: matroska.h:162
#define MATROSKA_ID_EDITIONENTRY
Definition: matroska.h:189
#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:111
#define MATROSKA_ID_BLOCKGROUP
Definition: matroska.h:172
#define MATROSKA_ID_VIDEOPIXELHEIGHT
Definition: matroska.h:108
static int mkv_write_tracks(AVFormatContext *s)
Definition: matroskaenc.c:529
rational number numerator/denominator
Definition: rational.h:43
static void put_ebml_uint(AVIOContext *pb, unsigned int elementid, uint64_t val)
Definition: matroskaenc.c:174
#define MATROSKA_ID_CUETIME
Definition: matroska.h:138
static int64_t mkv_write_seekhead(AVIOContext *pb, mkv_seekhead *seekhead)
Write the seek head to the file and free it.
Definition: matroskaenc.c:315
#define CONFIG_LIBVORBIS_ENCODER
Definition: config.h:949
AVIOContext * dyn_bc
Definition: matroskaenc.c:81
AVMediaType
Definition: avutil.h:177
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:87
static int mkv_write_packet_internal(AVFormatContext *s, AVPacket *pkt)
Definition: matroskaenc.c:1138
#define MATROSKA_ID_TITLE
Definition: matroska.h:68
#define MATROSKA_ID_TRACKVIDEO
Definition: matroska.h:82
static int ass_get_duration(const uint8_t *p)
Definition: matroskaenc.c:995
static void put_ebml_id(AVIOContext *pb, unsigned int id)
Definition: matroskaenc.c:119
int ff_flac_write_header(AVIOContext *pb, AVCodecContext *codec, int last_block)
mkv_cues * cues
Definition: matroskaenc.c:90
void ff_put_bmp_header(AVIOContext *pb, AVCodecContext *enc, const AVCodecTag *tags, int for_asf)
#define MATROSKA_ID_ATTACHMENTS
Definition: matroska.h:61
void avio_wb16(AVIOContext *s, unsigned int val)
Definition: aviobuf.c:342
#define MATROSKA_ID_CHAPTERDISPLAY
Definition: matroska.h:193
static const uint16_t scale[4]
#define MATROSKA_ID_FILENAME
Definition: matroska.h:183
const AVMetadataConv ff_mkv_metadata_conv[]
Definition: matroska.c:100
#define MATROSKA_ID_CODECID
Definition: matroska.h:83
int64_t start
Definition: avformat.h:816
void ff_metadata_conv_ctx(AVFormatContext *ctx, const AVMetadataConv *d_conv, const AVMetadataConv *s_conv)
Definition: metadata.c:59
static int mkv_write_trailer(AVFormatContext *s)
Definition: matroskaenc.c:1253
Main libavformat public API header.
#define MATROSKA_ID_CUETRACK
Definition: matroska.h:142
#define MATROSKA_ID_SEEKPOSITION
Definition: matroska.h:166
#define MATROSKA_ID_CHAPTERTIMESTART
Definition: matroska.h:191
static void put_ebml_binary(AVIOContext *pb, unsigned int elementid, const void *buf, int size)
Definition: matroskaenc.c:193
void * av_realloc(void *ptr, size_t size)
Allocate or reallocate a block of memory.
Definition: mem.c:116
static int mkv_write_codecprivate(AVFormatContext *s, AVIOContext *pb, AVCodecContext *codec, int native_id, int qt_id)
Definition: matroskaenc.c:463
int disposition
AV_DISPOSITION_* bit field.
Definition: avformat.h:688
int ff_put_wav_header(AVIOContext *pb, AVCodecContext *enc)
static void put_ebml_void(AVIOContext *pb, uint64_t size)
Write a void element of a given size.
Definition: matroskaenc.c:212
AVRational time_base
time base in which the start/end timestamps are specified
Definition: avformat.h:815
void av_init_packet(AVPacket *pkt)
Initialize optional fields of a packet with default values.
Definition: avpacket.c:42
int64_t nb_frames
number of frames in this stream if known or 0
Definition: avformat.h:686
char * key
Definition: dict.h:75
#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
ebml_master cluster
Definition: matroskaenc.c:84
char * value
Definition: dict.h:76
#define MATROSKA_ID_POINTENTRY
Definition: matroska.h:135
mkv_seekhead_entry * entries
Definition: matroskaenc.c:56
int channels
number of audio channels
Definition: avcodec.h:2105
#define av_log2
Definition: intmath.h:85
#define MATROSKA_ID_FILEUID
Definition: matroska.h:186
void * priv_data
Format private data.
Definition: avformat.h:848
#define MATROSKA_ID_CHAPTERUID
Definition: matroska.h:200
static void write_header(FFV1Context *f)
Definition: ffv1enc.c:380
#define MATROSKA_ID_VIDEODISPLAYUNIT
Definition: matroska.h:113
int64_t dts
Decompression timestamp in AVStream->time_base units; the time at which the packet is decompressed...
Definition: avcodec.h:914
static void mkv_flush_dynbuf(AVFormatContext *s)
Definition: matroskaenc.c:1123
#define EBML_ID_EBMLMAXSIZELENGTH
Definition: matroska.h:39
#define MATROSKA_ID_CHAPSTRING
Definition: matroska.h:194
#define MATROSKA_ID_TAGSTRING
Definition: matroska.h:150
#define MODE_MATROSKAv2
Definition: matroskaenc.c:76
uint32_t av_get_random_seed(void)
Get random data.
Definition: random_seed.c:85
#define MODE_WEBM
Definition: matroskaenc.c:77
static int mkv_write_packet(AVFormatContext *s, AVPacket *pkt)
Definition: matroskaenc.c:1202
#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:104
static mkv_cues * mkv_start_cues(int64_t segment_offset)
Definition: matroskaenc.c:359
int stream_index
Definition: avcodec.h:917
int num_entries
Definition: matroskaenc.c:69
#define EBML_ID_DOCTYPEVERSION
Definition: matroska.h:41
static void end_ebml_master(AVIOContext *pb, ebml_master master)
Definition: matroskaenc.c:238
int64_t segment_offset
Definition: matroskaenc.c:83
#define MATROSKA_ID_ATTACHEDFILE
Definition: matroska.h:181
static ebml_master start_ebml_master(AVIOContext *pb, unsigned int elementid, uint64_t expectedsize)
Definition: matroskaenc.c:230
mkv_seekhead * main_seekhead
Definition: matroskaenc.c:89
This structure stores compressed data.
Definition: avcodec.h:898
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:158
static int mkv_query_codec(enum AVCodecID codec_id, int std_compliance)
Definition: matroskaenc.c:1305
static void put_xiph_size(AVIOContext *pb, int size)
Definition: matroskaenc.c:248
int64_t pts
Presentation timestamp in AVStream->time_base units; the time at which the decompressed packet will b...
Definition: avcodec.h:908
#define MATROSKA_ID_VIDEOPIXELWIDTH
Definition: matroska.h:107
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
const CodecTags ff_mkv_codec_tags[]
Definition: matroska.c:24