LCOV - code coverage report
Current view: top level - libavformat - matroskaenc.c (source / functions) Hit Total Coverage
Test: coverage.info Lines: 987 1525 64.7 %
Date: 2017-12-18 13:19:42 Functions: 54 59 91.5 %

          Line data    Source code
       1             : /*
       2             :  * Matroska muxer
       3             :  * Copyright (c) 2007 David Conrad
       4             :  *
       5             :  * This file is part of FFmpeg.
       6             :  *
       7             :  * FFmpeg 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             :  * FFmpeg 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 FFmpeg; 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 "avio_internal.h"
      28             : #include "avlanguage.h"
      29             : #include "flacenc.h"
      30             : #include "internal.h"
      31             : #include "isom.h"
      32             : #include "matroska.h"
      33             : #include "riff.h"
      34             : #include "subtitles.h"
      35             : #include "vorbiscomment.h"
      36             : #include "wv.h"
      37             : 
      38             : #include "libavutil/avstring.h"
      39             : #include "libavutil/channel_layout.h"
      40             : #include "libavutil/crc.h"
      41             : #include "libavutil/dict.h"
      42             : #include "libavutil/intfloat.h"
      43             : #include "libavutil/intreadwrite.h"
      44             : #include "libavutil/lfg.h"
      45             : #include "libavutil/mastering_display_metadata.h"
      46             : #include "libavutil/mathematics.h"
      47             : #include "libavutil/opt.h"
      48             : #include "libavutil/parseutils.h"
      49             : #include "libavutil/random_seed.h"
      50             : #include "libavutil/rational.h"
      51             : #include "libavutil/samplefmt.h"
      52             : #include "libavutil/sha.h"
      53             : #include "libavutil/stereo3d.h"
      54             : 
      55             : #include "libavcodec/xiph.h"
      56             : #include "libavcodec/mpeg4audio.h"
      57             : #include "libavcodec/internal.h"
      58             : 
      59             : typedef struct ebml_master {
      60             :     int64_t         pos;                ///< absolute offset in the file where the master's elements start
      61             :     int             sizebytes;          ///< how many bytes were reserved for the size
      62             : } ebml_master;
      63             : 
      64             : typedef struct mkv_seekhead_entry {
      65             :     unsigned int    elementid;
      66             :     uint64_t        segmentpos;
      67             : } mkv_seekhead_entry;
      68             : 
      69             : typedef struct mkv_seekhead {
      70             :     int64_t                 filepos;
      71             :     int64_t                 segment_offset;     ///< the file offset to the beginning of the segment
      72             :     int                     reserved_size;      ///< -1 if appending to file
      73             :     int                     max_entries;
      74             :     mkv_seekhead_entry      *entries;
      75             :     int                     num_entries;
      76             : } mkv_seekhead;
      77             : 
      78             : typedef struct mkv_cuepoint {
      79             :     uint64_t        pts;
      80             :     int             stream_idx;
      81             :     int             tracknum;
      82             :     int64_t         cluster_pos;        ///< file offset of the cluster containing the block
      83             :     int64_t         relative_pos;       ///< relative offset from the position of the cluster containing the block
      84             :     int64_t         duration;           ///< duration of the block according to time base
      85             : } mkv_cuepoint;
      86             : 
      87             : typedef struct mkv_cues {
      88             :     int64_t         segment_offset;
      89             :     mkv_cuepoint    *entries;
      90             :     int             num_entries;
      91             : } mkv_cues;
      92             : 
      93             : typedef struct mkv_track {
      94             :     int             write_dts;
      95             :     int             has_cue;
      96             :     int             sample_rate;
      97             :     int64_t         sample_rate_offset;
      98             :     int64_t         codecpriv_offset;
      99             :     int64_t         ts_offset;
     100             : } mkv_track;
     101             : 
     102             : typedef struct mkv_attachment {
     103             :     int             stream_idx;
     104             :     uint32_t        fileuid;
     105             : } mkv_attachment;
     106             : 
     107             : typedef struct mkv_attachments {
     108             :     mkv_attachment  *entries;
     109             :     int             num_entries;
     110             : } mkv_attachments;
     111             : 
     112             : #define MODE_MATROSKAv2 0x01
     113             : #define MODE_WEBM       0x02
     114             : 
     115             : /** Maximum number of tracks allowed in a Matroska file (with track numbers in
     116             :  * range 1 to 126 (inclusive) */
     117             : #define MAX_TRACKS 126
     118             : 
     119             : typedef struct MatroskaMuxContext {
     120             :     const AVClass  *class;
     121             :     int             mode;
     122             :     AVIOContext   *dyn_bc;
     123             :     AVIOContext     *tags_bc;
     124             :     ebml_master     tags;
     125             :     AVIOContext     *info_bc;
     126             :     ebml_master     info;
     127             :     AVIOContext     *tracks_bc;
     128             :     ebml_master     tracks_master;
     129             :     ebml_master     segment;
     130             :     int64_t         segment_offset;
     131             :     ebml_master     cluster;
     132             :     int64_t         cluster_pos;        ///< file offset of the current cluster
     133             :     int64_t         cluster_pts;
     134             :     int64_t         duration_offset;
     135             :     int64_t         duration;
     136             :     mkv_seekhead    *main_seekhead;
     137             :     mkv_cues        *cues;
     138             :     mkv_track       *tracks;
     139             :     mkv_attachments *attachments;
     140             : 
     141             :     AVPacket        cur_audio_pkt;
     142             : 
     143             :     int have_attachments;
     144             :     int have_video;
     145             : 
     146             :     int reserve_cues_space;
     147             :     int cluster_size_limit;
     148             :     int64_t cues_pos;
     149             :     int64_t cluster_time_limit;
     150             :     int is_dash;
     151             :     int dash_track_number;
     152             :     int is_live;
     153             :     int write_crc;
     154             : 
     155             :     uint32_t chapter_id_offset;
     156             :     int wrote_chapters;
     157             : 
     158             :     int64_t last_track_timestamp[MAX_TRACKS];
     159             : 
     160             :     int64_t* stream_durations;
     161             :     int64_t* stream_duration_offsets;
     162             : 
     163             :     int allow_raw_vfw;
     164             : } MatroskaMuxContext;
     165             : 
     166             : 
     167             : /** 2 bytes * 3 for EBML IDs, 3 1-byte EBML lengths, 8 bytes for 64 bit
     168             :  * offset, 4 bytes for target EBML ID */
     169             : #define MAX_SEEKENTRY_SIZE 21
     170             : 
     171             : /** per-cuepoint-track - 5 1-byte EBML IDs, 5 1-byte EBML sizes, 4
     172             :  * 8-byte uint max */
     173             : #define MAX_CUETRACKPOS_SIZE 42
     174             : 
     175             : /** per-cuepoint - 2 1-byte EBML IDs, 2 1-byte EBML sizes, 8-byte uint max */
     176             : #define MAX_CUEPOINT_SIZE(num_tracks) 12 + MAX_CUETRACKPOS_SIZE * num_tracks
     177             : 
     178             : /** Seek preroll value for opus */
     179             : #define OPUS_SEEK_PREROLL 80000000
     180             : 
     181        1332 : static int ebml_id_size(unsigned int id)
     182             : {
     183        1332 :     return (av_log2(id + 1) - 1) / 7 + 1;
     184             : }
     185             : 
     186        1305 : static void put_ebml_id(AVIOContext *pb, unsigned int id)
     187             : {
     188        1305 :     int i = ebml_id_size(id);
     189        4876 :     while (i--)
     190        2266 :         avio_w8(pb, (uint8_t)(id >> (i * 8)));
     191        1305 : }
     192             : 
     193             : /**
     194             :  * Write an EBML size meaning "unknown size".
     195             :  *
     196             :  * @param bytes The number of bytes the size should occupy (maximum: 8).
     197             :  */
     198         282 : static void put_ebml_size_unknown(AVIOContext *pb, int bytes)
     199             : {
     200         282 :     av_assert0(bytes <= 8);
     201         282 :     avio_w8(pb, 0x1ff >> bytes);
     202         282 :     ffio_fill(pb, 0xff, bytes - 1);
     203         282 : }
     204             : 
     205             : /**
     206             :  * Calculate how many bytes are needed to represent a given number in EBML.
     207             :  */
     208        1360 : static int ebml_num_size(uint64_t num)
     209             : {
     210        1360 :     int bytes = 1;
     211        3232 :     while ((num + 1) >> bytes * 7)
     212         512 :         bytes++;
     213        1360 :     return bytes;
     214             : }
     215             : 
     216             : /**
     217             :  * Write a number in EBML variable length format.
     218             :  *
     219             :  * @param bytes The number of bytes that need to be used to write the number.
     220             :  *              If zero, any number of bytes can be used.
     221             :  */
     222        1285 : static void put_ebml_num(AVIOContext *pb, uint64_t num, int bytes)
     223             : {
     224        1285 :     int i, needed_bytes = ebml_num_size(num);
     225             : 
     226             :     // sizes larger than this are currently undefined in EBML
     227        1285 :     av_assert0(num < (1ULL << 56) - 1);
     228             : 
     229        1285 :     if (bytes == 0)
     230             :         // don't care how many bytes are used, so use the min
     231         959 :         bytes = needed_bytes;
     232             :     // the bytes needed to write the given size would exceed the bytes
     233             :     // that we need to use, so write unknown size. This shouldn't happen.
     234        1285 :     av_assert0(bytes >= needed_bytes);
     235             : 
     236        1285 :     num |= 1ULL << bytes * 7;
     237        4779 :     for (i = bytes - 1; i >= 0; i--)
     238        3494 :         avio_w8(pb, (uint8_t)(num >> i * 8));
     239        1285 : }
     240             : 
     241         328 : static void put_ebml_uint(AVIOContext *pb, unsigned int elementid, uint64_t val)
     242             : {
     243         328 :     int i, bytes = 1;
     244         328 :     uint64_t tmp = val;
     245         798 :     while (tmp >>= 8)
     246         142 :         bytes++;
     247             : 
     248         328 :     put_ebml_id(pb, elementid);
     249         328 :     put_ebml_num(pb, bytes, 0);
     250         798 :     for (i = bytes - 1; i >= 0; i--)
     251         470 :         avio_w8(pb, (uint8_t)(val >> i * 8));
     252         328 : }
     253             : 
     254           0 : static void put_ebml_sint(AVIOContext *pb, unsigned int elementid, int64_t val)
     255             : {
     256           0 :     int i, bytes = 1;
     257           0 :     uint64_t tmp = 2*(val < 0 ? val^-1 : val);
     258             : 
     259           0 :     while (tmp>>=8) bytes++;
     260             : 
     261           0 :     put_ebml_id(pb, elementid);
     262           0 :     put_ebml_num(pb, bytes, 0);
     263           0 :     for (i = bytes - 1; i >= 0; i--)
     264           0 :         avio_w8(pb, (uint8_t)(val >> i * 8));
     265           0 : }
     266             : 
     267          21 : static void put_ebml_float(AVIOContext *pb, unsigned int elementid, double val)
     268             : {
     269          21 :     put_ebml_id(pb, elementid);
     270          21 :     put_ebml_num(pb, 8, 0);
     271          21 :     avio_wb64(pb, av_double2int(val));
     272          21 : }
     273             : 
     274         207 : static void put_ebml_binary(AVIOContext *pb, unsigned int elementid,
     275             :                             const void *buf, int size)
     276             : {
     277         207 :     put_ebml_id(pb, elementid);
     278         207 :     put_ebml_num(pb, size, 0);
     279         207 :     avio_write(pb, buf, size);
     280         207 : }
     281             : 
     282         135 : static void put_ebml_string(AVIOContext *pb, unsigned int elementid,
     283             :                             const char *str)
     284             : {
     285         135 :     put_ebml_binary(pb, elementid, str, strlen(str));
     286         135 : }
     287             : 
     288             : /**
     289             :  * Write a void element of a given size. Useful for reserving space in
     290             :  * the file to be written to later.
     291             :  *
     292             :  * @param size The number of bytes to reserve, which must be at least 2.
     293             :  */
     294          85 : static void put_ebml_void(AVIOContext *pb, uint64_t size)
     295             : {
     296          85 :     int64_t currentpos = avio_tell(pb);
     297             : 
     298          85 :     av_assert0(size >= 2);
     299             : 
     300          85 :     put_ebml_id(pb, EBML_ID_VOID);
     301             :     // we need to subtract the length needed to store the size from the
     302             :     // size we need to reserve so 2 cases, we use 8 bytes to store the
     303             :     // size if possible, 1 byte otherwise
     304          85 :     if (size < 10)
     305          48 :         put_ebml_num(pb, size - 2, 0);
     306             :     else
     307          37 :         put_ebml_num(pb, size - 9, 8);
     308          85 :     ffio_fill(pb, 0, currentpos + size - avio_tell(pb));
     309          85 : }
     310             : 
     311         282 : static ebml_master start_ebml_master(AVIOContext *pb, unsigned int elementid,
     312             :                                      uint64_t expectedsize)
     313             : {
     314         282 :     int bytes = expectedsize ? ebml_num_size(expectedsize) : 8;
     315         282 :     put_ebml_id(pb, elementid);
     316         282 :     put_ebml_size_unknown(pb, bytes);
     317         282 :     return (ebml_master) {avio_tell(pb), bytes };
     318             : }
     319             : 
     320         293 : static void end_ebml_master(AVIOContext *pb, ebml_master master)
     321             : {
     322         293 :     int64_t pos = avio_tell(pb);
     323             : 
     324         293 :     if (avio_seek(pb, master.pos - master.sizebytes, SEEK_SET) < 0)
     325           4 :         return;
     326         289 :     put_ebml_num(pb, pos - master.pos, master.sizebytes);
     327         289 :     avio_seek(pb, pos, SEEK_SET);
     328             : }
     329             : 
     330         108 : static int start_ebml_master_crc32(AVIOContext *pb, AVIOContext **dyn_cp, MatroskaMuxContext *mkv,
     331             :                                    ebml_master *master, unsigned int elementid, uint64_t expectedsize)
     332             : {
     333             :     int ret;
     334             : 
     335         108 :     if ((ret = avio_open_dyn_buf(dyn_cp)) < 0)
     336           0 :         return ret;
     337             : 
     338         108 :     if (pb->seekable & AVIO_SEEKABLE_NORMAL) {
     339          48 :         *master = start_ebml_master(pb, elementid, expectedsize);
     340          48 :         if (mkv->write_crc && mkv->mode != MODE_WEBM)
     341          48 :             put_ebml_void(*dyn_cp, 6); /* Reserve space for CRC32 so position/size calculations using avio_tell() take it into account */
     342             :     } else
     343          60 :         *master = start_ebml_master(*dyn_cp, elementid, expectedsize);
     344             : 
     345         108 :     return 0;
     346             : }
     347             : 
     348         108 : static void end_ebml_master_crc32(AVIOContext *pb, AVIOContext **dyn_cp, MatroskaMuxContext *mkv,
     349             :                                   ebml_master master)
     350             : {
     351             :     uint8_t *buf, crc[4];
     352         108 :     int size, skip = 0;
     353             : 
     354         108 :     if (pb->seekable & AVIO_SEEKABLE_NORMAL) {
     355          48 :         size = avio_close_dyn_buf(*dyn_cp, &buf);
     356          48 :         if (mkv->write_crc && mkv->mode != MODE_WEBM) {
     357          48 :             skip = 6; /* Skip reserved 6-byte long void element from the dynamic buffer. */
     358          48 :             AV_WL32(crc, av_crc(av_crc_get_table(AV_CRC_32_IEEE_LE), UINT32_MAX, buf + skip, size - skip) ^ UINT32_MAX);
     359          48 :             put_ebml_binary(pb, EBML_ID_CRC32, crc, sizeof(crc));
     360             :         }
     361          48 :         avio_write(pb, buf + skip, size - skip);
     362          48 :         end_ebml_master(pb, master);
     363             :     } else {
     364          60 :         end_ebml_master(*dyn_cp, master);
     365          60 :         size = avio_close_dyn_buf(*dyn_cp, &buf);
     366          60 :         avio_write(pb, buf, size);
     367             :     }
     368         108 :     av_free(buf);
     369         108 :     *dyn_cp = NULL;
     370         108 : }
     371             : 
     372             : /**
     373             : * Complete ebml master whithout destroying the buffer, allowing for later updates
     374             : */
     375          15 : static void end_ebml_master_crc32_preliminary(AVIOContext *pb, AVIOContext **dyn_cp, MatroskaMuxContext *mkv,
     376             :     ebml_master master)
     377             : {
     378          15 :     if (pb->seekable & AVIO_SEEKABLE_NORMAL) {
     379             : 
     380             :         uint8_t *buf;
     381          15 :         int size = avio_get_dyn_buf(*dyn_cp, &buf);
     382             : 
     383          15 :         avio_write(pb, buf, size);
     384          15 :         end_ebml_master(pb, master);
     385             :     }
     386          15 : }
     387             : 
     388           0 : static void put_xiph_size(AVIOContext *pb, int size)
     389             : {
     390           0 :     ffio_fill(pb, 255, size / 255);
     391           0 :     avio_w8(pb, size % 255);
     392           0 : }
     393             : 
     394             : /**
     395             :  * Free the members allocated in the mux context.
     396             :  */
     397          13 : static void mkv_free(MatroskaMuxContext *mkv) {
     398             :     uint8_t* buf;
     399          13 :     if (mkv->dyn_bc) {
     400           0 :         avio_close_dyn_buf(mkv->dyn_bc, &buf);
     401           0 :         av_free(buf);
     402             :     }
     403          13 :     if (mkv->info_bc) {
     404           0 :         avio_close_dyn_buf(mkv->info_bc, &buf);
     405           0 :         av_free(buf);
     406             :     }
     407          13 :     if (mkv->tracks_bc) {
     408           0 :         avio_close_dyn_buf(mkv->tracks_bc, &buf);
     409           0 :         av_free(buf);
     410             :     }
     411          13 :     if (mkv->tags_bc) {
     412           0 :         avio_close_dyn_buf(mkv->tags_bc, &buf);
     413           0 :         av_free(buf);
     414             :     }
     415          13 :     if (mkv->main_seekhead) {
     416           4 :         av_freep(&mkv->main_seekhead->entries);
     417           4 :         av_freep(&mkv->main_seekhead);
     418             :     }
     419          13 :     if (mkv->cues) {
     420          13 :         av_freep(&mkv->cues->entries);
     421          13 :         av_freep(&mkv->cues);
     422             :     }
     423          13 :     if (mkv->attachments) {
     424           1 :         av_freep(&mkv->attachments->entries);
     425           1 :         av_freep(&mkv->attachments);
     426             :     }
     427          13 :     av_freep(&mkv->tracks);
     428          13 :     av_freep(&mkv->stream_durations);
     429          13 :     av_freep(&mkv->stream_duration_offsets);
     430          13 : }
     431             : 
     432             : /**
     433             :  * Initialize a mkv_seekhead element to be ready to index level 1 Matroska
     434             :  * elements. If a maximum number of elements is specified, enough space
     435             :  * will be reserved at the current file location to write a seek head of
     436             :  * that size.
     437             :  *
     438             :  * @param segment_offset The absolute offset to the position in the file
     439             :  *                       where the segment begins.
     440             :  * @param numelements The maximum number of elements that will be indexed
     441             :  *                    by this seek head, 0 if unlimited.
     442             :  */
     443          13 : static mkv_seekhead *mkv_start_seekhead(AVIOContext *pb, int64_t segment_offset,
     444             :                                         int numelements)
     445             : {
     446          13 :     mkv_seekhead *new_seekhead = av_mallocz(sizeof(mkv_seekhead));
     447          13 :     if (!new_seekhead)
     448           0 :         return NULL;
     449             : 
     450          13 :     new_seekhead->segment_offset = segment_offset;
     451             : 
     452          13 :     if (numelements > 0) {
     453          13 :         new_seekhead->filepos = avio_tell(pb);
     454             :         // 21 bytes max for a seek entry, 10 bytes max for the SeekHead ID
     455             :         // and size, 6 bytes for a CRC32 element, and 3 bytes to guarantee
     456             :         // that an EBML void element will fit afterwards
     457          13 :         new_seekhead->reserved_size = numelements * MAX_SEEKENTRY_SIZE + 19;
     458          13 :         new_seekhead->max_entries   = numelements;
     459          13 :         put_ebml_void(pb, new_seekhead->reserved_size);
     460             :     }
     461          13 :     return new_seekhead;
     462             : }
     463             : 
     464          39 : static int mkv_add_seekhead_entry(mkv_seekhead *seekhead, unsigned int elementid, uint64_t filepos)
     465             : {
     466          39 :     mkv_seekhead_entry *entries = seekhead->entries;
     467             : 
     468             :     // don't store more elements than we reserved space for
     469          39 :     if (seekhead->max_entries > 0 && seekhead->max_entries <= seekhead->num_entries)
     470           0 :         return -1;
     471             : 
     472          39 :     entries = av_realloc_array(entries, seekhead->num_entries + 1, sizeof(mkv_seekhead_entry));
     473          39 :     if (!entries)
     474           0 :         return AVERROR(ENOMEM);
     475          39 :     seekhead->entries = entries;
     476             : 
     477          39 :     seekhead->entries[seekhead->num_entries].elementid    = elementid;
     478          39 :     seekhead->entries[seekhead->num_entries++].segmentpos = filepos - seekhead->segment_offset;
     479             : 
     480          39 :     return 0;
     481             : }
     482             : 
     483             : /**
     484             :  * Write the seek head to the file and free it. If a maximum number of
     485             :  * elements was specified to mkv_start_seekhead(), the seek head will
     486             :  * be written at the location reserved for it. Otherwise, it is written
     487             :  * at the current location in the file.
     488             :  *
     489             :  * @return The file offset where the seekhead was written,
     490             :  * -1 if an error occurred.
     491             :  */
     492           9 : static int64_t mkv_write_seekhead(AVIOContext *pb, MatroskaMuxContext *mkv)
     493             : {
     494             :     AVIOContext *dyn_cp;
     495           9 :     mkv_seekhead *seekhead = mkv->main_seekhead;
     496             :     ebml_master metaseek, seekentry;
     497             :     int64_t currentpos;
     498             :     int i;
     499             : 
     500           9 :     currentpos = avio_tell(pb);
     501             : 
     502           9 :     if (seekhead->reserved_size > 0) {
     503           9 :         if (avio_seek(pb, seekhead->filepos, SEEK_SET) < 0) {
     504           0 :             currentpos = -1;
     505           0 :             goto fail;
     506             :         }
     507             :     }
     508             : 
     509           9 :     if (start_ebml_master_crc32(pb, &dyn_cp, mkv, &metaseek, MATROSKA_ID_SEEKHEAD,
     510           9 :                                 seekhead->reserved_size) < 0) {
     511           0 :         currentpos = -1;
     512           0 :         goto fail;
     513             :     }
     514             : 
     515          36 :     for (i = 0; i < seekhead->num_entries; i++) {
     516          27 :         mkv_seekhead_entry *entry = &seekhead->entries[i];
     517             : 
     518          27 :         seekentry = start_ebml_master(dyn_cp, MATROSKA_ID_SEEKENTRY, MAX_SEEKENTRY_SIZE);
     519             : 
     520          27 :         put_ebml_id(dyn_cp, MATROSKA_ID_SEEKID);
     521          27 :         put_ebml_num(dyn_cp, ebml_id_size(entry->elementid), 0);
     522          27 :         put_ebml_id(dyn_cp, entry->elementid);
     523             : 
     524          27 :         put_ebml_uint(dyn_cp, MATROSKA_ID_SEEKPOSITION, entry->segmentpos);
     525          27 :         end_ebml_master(dyn_cp, seekentry);
     526             :     }
     527           9 :     end_ebml_master_crc32(pb, &dyn_cp, mkv, metaseek);
     528             : 
     529           9 :     if (seekhead->reserved_size > 0) {
     530           9 :         uint64_t remaining = seekhead->filepos + seekhead->reserved_size - avio_tell(pb);
     531           9 :         put_ebml_void(pb, remaining);
     532           9 :         avio_seek(pb, currentpos, SEEK_SET);
     533             : 
     534           9 :         currentpos = seekhead->filepos;
     535             :     }
     536           9 : fail:
     537           9 :     av_freep(&mkv->main_seekhead->entries);
     538           9 :     av_freep(&mkv->main_seekhead);
     539             : 
     540           9 :     return currentpos;
     541             : }
     542             : 
     543          13 : static mkv_cues *mkv_start_cues(int64_t segment_offset)
     544             : {
     545          13 :     mkv_cues *cues = av_mallocz(sizeof(mkv_cues));
     546          13 :     if (!cues)
     547           0 :         return NULL;
     548             : 
     549          13 :     cues->segment_offset = segment_offset;
     550          13 :     return cues;
     551             : }
     552             : 
     553           7 : static int mkv_add_cuepoint(mkv_cues *cues, int stream, int tracknum, int64_t ts,
     554             :                             int64_t cluster_pos, int64_t relative_pos, int64_t duration)
     555             : {
     556           7 :     mkv_cuepoint *entries = cues->entries;
     557             : 
     558           7 :     if (ts < 0)
     559           0 :         return 0;
     560             : 
     561           7 :     entries = av_realloc_array(entries, cues->num_entries + 1, sizeof(mkv_cuepoint));
     562           7 :     if (!entries)
     563           0 :         return AVERROR(ENOMEM);
     564           7 :     cues->entries = entries;
     565             : 
     566           7 :     cues->entries[cues->num_entries].pts           = ts;
     567           7 :     cues->entries[cues->num_entries].stream_idx    = stream;
     568           7 :     cues->entries[cues->num_entries].tracknum      = tracknum;
     569           7 :     cues->entries[cues->num_entries].cluster_pos   = cluster_pos - cues->segment_offset;
     570           7 :     cues->entries[cues->num_entries].relative_pos  = relative_pos;
     571           7 :     cues->entries[cues->num_entries++].duration    = duration;
     572             : 
     573           7 :     return 0;
     574             : }
     575             : 
     576           3 : static int64_t mkv_write_cues(AVFormatContext *s, mkv_cues *cues, mkv_track *tracks, int num_tracks)
     577             : {
     578           3 :     MatroskaMuxContext *mkv = s->priv_data;
     579           3 :     AVIOContext *dyn_cp, *pb = s->pb;
     580             :     ebml_master cues_element;
     581             :     int64_t currentpos;
     582             :     int i, j, ret;
     583             : 
     584           3 :     currentpos = avio_tell(pb);
     585           3 :     ret = start_ebml_master_crc32(pb, &dyn_cp, mkv, &cues_element, MATROSKA_ID_CUES, 0);
     586           3 :     if (ret < 0)
     587           0 :         return ret;
     588             : 
     589          10 :     for (i = 0; i < cues->num_entries; i++) {
     590             :         ebml_master cuepoint, track_positions;
     591           7 :         mkv_cuepoint *entry = &cues->entries[i];
     592           7 :         uint64_t pts = entry->pts;
     593           7 :         int ctp_nb = 0;
     594             : 
     595             :         // Calculate the number of entries, so we know the element size
     596          23 :         for (j = 0; j < num_tracks; j++)
     597          16 :             tracks[j].has_cue = 0;
     598          14 :         for (j = 0; j < cues->num_entries - i && entry[j].pts == pts; j++) {
     599           7 :             int tracknum = entry[j].stream_idx;
     600           7 :             av_assert0(tracknum>=0 && tracknum<num_tracks);
     601           7 :             if (tracks[tracknum].has_cue && s->streams[tracknum]->codecpar->codec_type != AVMEDIA_TYPE_SUBTITLE)
     602           0 :                 continue;
     603           7 :             tracks[tracknum].has_cue = 1;
     604           7 :             ctp_nb ++;
     605             :         }
     606             : 
     607           7 :         cuepoint = start_ebml_master(dyn_cp, MATROSKA_ID_POINTENTRY, MAX_CUEPOINT_SIZE(ctp_nb));
     608           7 :         put_ebml_uint(dyn_cp, MATROSKA_ID_CUETIME, pts);
     609             : 
     610             :         // put all the entries from different tracks that have the exact same
     611             :         // timestamp into the same CuePoint
     612          23 :         for (j = 0; j < num_tracks; j++)
     613          16 :             tracks[j].has_cue = 0;
     614          14 :         for (j = 0; j < cues->num_entries - i && entry[j].pts == pts; j++) {
     615           7 :             int tracknum = entry[j].stream_idx;
     616           7 :             av_assert0(tracknum>=0 && tracknum<num_tracks);
     617           7 :             if (tracks[tracknum].has_cue && s->streams[tracknum]->codecpar->codec_type != AVMEDIA_TYPE_SUBTITLE)
     618           0 :                 continue;
     619           7 :             tracks[tracknum].has_cue = 1;
     620           7 :             track_positions = start_ebml_master(dyn_cp, MATROSKA_ID_CUETRACKPOSITION, MAX_CUETRACKPOS_SIZE);
     621           7 :             put_ebml_uint(dyn_cp, MATROSKA_ID_CUETRACK           , entry[j].tracknum   );
     622           7 :             put_ebml_uint(dyn_cp, MATROSKA_ID_CUECLUSTERPOSITION , entry[j].cluster_pos);
     623           7 :             put_ebml_uint(dyn_cp, MATROSKA_ID_CUERELATIVEPOSITION, entry[j].relative_pos);
     624           7 :             if (entry[j].duration != -1)
     625           0 :                 put_ebml_uint(dyn_cp, MATROSKA_ID_CUEDURATION    , entry[j].duration);
     626           7 :             end_ebml_master(dyn_cp, track_positions);
     627             :         }
     628           7 :         i += j - 1;
     629           7 :         end_ebml_master(dyn_cp, cuepoint);
     630             :     }
     631           3 :     end_ebml_master_crc32(pb, &dyn_cp, mkv, cues_element);
     632             : 
     633           3 :     return currentpos;
     634             : }
     635             : 
     636           0 : static int put_xiph_codecpriv(AVFormatContext *s, AVIOContext *pb, AVCodecParameters *par)
     637             : {
     638             :     const uint8_t *header_start[3];
     639             :     int header_len[3];
     640             :     int first_header_size;
     641             :     int j;
     642             : 
     643           0 :     if (par->codec_id == AV_CODEC_ID_VORBIS)
     644           0 :         first_header_size = 30;
     645             :     else
     646           0 :         first_header_size = 42;
     647             : 
     648           0 :     if (avpriv_split_xiph_headers(par->extradata, par->extradata_size,
     649             :                               first_header_size, header_start, header_len) < 0) {
     650           0 :         av_log(s, AV_LOG_ERROR, "Extradata corrupt.\n");
     651           0 :         return -1;
     652             :     }
     653             : 
     654           0 :     avio_w8(pb, 2);                    // number packets - 1
     655           0 :     for (j = 0; j < 2; j++) {
     656           0 :         put_xiph_size(pb, header_len[j]);
     657             :     }
     658           0 :     for (j = 0; j < 3; j++)
     659           0 :         avio_write(pb, header_start[j], header_len[j]);
     660             : 
     661           0 :     return 0;
     662             : }
     663             : 
     664           2 : static int put_wv_codecpriv(AVIOContext *pb, AVCodecParameters *par)
     665             : {
     666           2 :     if (par->extradata && par->extradata_size == 2)
     667           0 :         avio_write(pb, par->extradata, 2);
     668             :     else
     669           2 :         avio_wl16(pb, 0x403); // fallback to the version mentioned in matroska specs
     670           2 :     return 0;
     671             : }
     672             : 
     673           0 : static int put_flac_codecpriv(AVFormatContext *s,
     674             :                               AVIOContext *pb, AVCodecParameters *par)
     675             : {
     676           0 :     int write_comment = (par->channel_layout &&
     677           0 :                          !(par->channel_layout & ~0x3ffffULL) &&
     678           0 :                          !ff_flac_is_native_layout(par->channel_layout));
     679           0 :     int ret = ff_flac_write_header(pb, par->extradata, par->extradata_size,
     680             :                                    !write_comment);
     681             : 
     682           0 :     if (ret < 0)
     683           0 :         return ret;
     684             : 
     685           0 :     if (write_comment) {
     686           0 :         const char *vendor = (s->flags & AVFMT_FLAG_BITEXACT) ?
     687           0 :                              "Lavf" : LIBAVFORMAT_IDENT;
     688           0 :         AVDictionary *dict = NULL;
     689             :         uint8_t buf[32], *data, *p;
     690             :         int64_t len;
     691             : 
     692           0 :         snprintf(buf, sizeof(buf), "0x%"PRIx64, par->channel_layout);
     693           0 :         av_dict_set(&dict, "WAVEFORMATEXTENSIBLE_CHANNEL_MASK", buf, 0);
     694             : 
     695           0 :         len = ff_vorbiscomment_length(dict, vendor);
     696           0 :         if (len >= ((1<<24) - 4))
     697           0 :             return AVERROR(EINVAL);
     698             : 
     699           0 :         data = av_malloc(len + 4);
     700           0 :         if (!data) {
     701           0 :             av_dict_free(&dict);
     702           0 :             return AVERROR(ENOMEM);
     703             :         }
     704             : 
     705           0 :         data[0] = 0x84;
     706           0 :         AV_WB24(data + 1, len);
     707             : 
     708           0 :         p = data + 4;
     709           0 :         ff_vorbiscomment_write(&p, &dict, vendor);
     710             : 
     711           0 :         avio_write(pb, data, len + 4);
     712             : 
     713           0 :         av_freep(&data);
     714           0 :         av_dict_free(&dict);
     715             :     }
     716             : 
     717           0 :     return 0;
     718             : }
     719             : 
     720           6 : static int get_aac_sample_rates(AVFormatContext *s, uint8_t *extradata, int extradata_size,
     721             :                                 int *sample_rate, int *output_sample_rate)
     722             : {
     723             :     MPEG4AudioConfig mp4ac;
     724             :     int ret;
     725             : 
     726           6 :     ret = avpriv_mpeg4audio_get_config(&mp4ac, extradata,
     727             :                                        extradata_size * 8, 1);
     728             :     /* Don't abort if the failure is because of missing extradata. Assume in that
     729             :      * case a bitstream filter will provide the muxer with the extradata in the
     730             :      * first packet.
     731             :      * Abort however if s->pb is not seekable, as we would not be able to seek back
     732             :      * to write the sample rate elements once the extradata shows up, anyway. */
     733           6 :     if (ret < 0 && (extradata_size || !(s->pb->seekable & AVIO_SEEKABLE_NORMAL))) {
     734           0 :         av_log(s, AV_LOG_ERROR,
     735             :                "Error parsing AAC extradata, unable to determine samplerate.\n");
     736           0 :         return AVERROR(EINVAL);
     737             :     }
     738             : 
     739           6 :     if (ret < 0) {
     740             :         /* This will only happen when this function is called while writing the
     741             :          * header and no extradata is available. The space for this element has
     742             :          * to be reserved for when this function is called again after the
     743             :          * extradata shows up in the first packet, as there's no way to know if
     744             :          * output_sample_rate will be different than sample_rate or not. */
     745           1 :         *output_sample_rate = *sample_rate;
     746             :     } else {
     747           5 :         *sample_rate        = mp4ac.sample_rate;
     748           5 :         *output_sample_rate = mp4ac.ext_sample_rate;
     749             :     }
     750           6 :     return 0;
     751             : }
     752             : 
     753          15 : static int mkv_write_native_codecprivate(AVFormatContext *s, AVIOContext *pb,
     754             :                                          AVCodecParameters *par,
     755             :                                          AVIOContext *dyn_cp)
     756             : {
     757          15 :     switch (par->codec_id) {
     758           0 :     case AV_CODEC_ID_VORBIS:
     759             :     case AV_CODEC_ID_THEORA:
     760           0 :         return put_xiph_codecpriv(s, dyn_cp, par);
     761           0 :     case AV_CODEC_ID_FLAC:
     762           0 :         return put_flac_codecpriv(s, dyn_cp, par);
     763           2 :     case AV_CODEC_ID_WAVPACK:
     764           2 :         return put_wv_codecpriv(dyn_cp, par);
     765           0 :     case AV_CODEC_ID_H264:
     766           0 :         return ff_isom_write_avcc(dyn_cp, par->extradata,
     767             :                                   par->extradata_size);
     768           0 :     case AV_CODEC_ID_HEVC:
     769           0 :         ff_isom_write_hvcc(dyn_cp, par->extradata,
     770             :                            par->extradata_size, 0);
     771           0 :         return 0;
     772           0 :     case AV_CODEC_ID_ALAC:
     773           0 :         if (par->extradata_size < 36) {
     774           0 :             av_log(s, AV_LOG_ERROR,
     775             :                    "Invalid extradata found, ALAC expects a 36-byte "
     776             :                    "QuickTime atom.");
     777           0 :             return AVERROR_INVALIDDATA;
     778             :         } else
     779           0 :             avio_write(dyn_cp, par->extradata + 12,
     780           0 :                        par->extradata_size - 12);
     781           0 :         break;
     782           6 :     case AV_CODEC_ID_AAC:
     783           6 :         if (par->extradata_size)
     784           5 :             avio_write(dyn_cp, par->extradata, par->extradata_size);
     785             :         else
     786           1 :             put_ebml_void(pb, MAX_PCE_SIZE + 2 + 4);
     787           6 :         break;
     788           7 :     default:
     789           7 :         if (par->codec_id == AV_CODEC_ID_PRORES &&
     790           0 :             ff_codec_get_id(ff_codec_movvideo_tags, par->codec_tag) == AV_CODEC_ID_PRORES) {
     791           0 :             avio_wl32(dyn_cp, par->codec_tag);
     792           7 :         } else if (par->extradata_size && par->codec_id != AV_CODEC_ID_TTA)
     793           3 :             avio_write(dyn_cp, par->extradata, par->extradata_size);
     794             :     }
     795             : 
     796          13 :     return 0;
     797             : }
     798             : 
     799          16 : static int mkv_write_codecprivate(AVFormatContext *s, AVIOContext *pb,
     800             :                                   AVCodecParameters *par,
     801             :                                   int native_id, int qt_id)
     802             : {
     803             :     AVIOContext *dyn_cp;
     804             :     uint8_t *codecpriv;
     805             :     int ret, codecpriv_size;
     806             : 
     807          16 :     ret = avio_open_dyn_buf(&dyn_cp);
     808          16 :     if (ret < 0)
     809           0 :         return ret;
     810             : 
     811          16 :     if (native_id) {
     812          15 :         ret = mkv_write_native_codecprivate(s, pb, par, dyn_cp);
     813           1 :     } else if (par->codec_type == AVMEDIA_TYPE_VIDEO) {
     814           1 :         if (qt_id) {
     815           0 :             if (!par->codec_tag)
     816           0 :                 par->codec_tag = ff_codec_get_tag(ff_codec_movvideo_tags,
     817             :                                                     par->codec_id);
     818           0 :             if (   ff_codec_get_id(ff_codec_movvideo_tags, par->codec_tag) == par->codec_id
     819           0 :                 && (!par->extradata_size || ff_codec_get_id(ff_codec_movvideo_tags, AV_RL32(par->extradata + 4)) != par->codec_id)
     820             :             ) {
     821             :                 int i;
     822           0 :                 avio_wb32(dyn_cp, 0x5a + par->extradata_size);
     823           0 :                 avio_wl32(dyn_cp, par->codec_tag);
     824           0 :                 for(i = 0; i < 0x5a - 8; i++)
     825           0 :                     avio_w8(dyn_cp, 0);
     826             :             }
     827           0 :             avio_write(dyn_cp, par->extradata, par->extradata_size);
     828             :         } else {
     829           1 :             if (!ff_codec_get_tag(ff_codec_bmp_tags, par->codec_id))
     830           1 :                 av_log(s, AV_LOG_WARNING, "codec %s is not supported by this format\n",
     831             :                        avcodec_get_name(par->codec_id));
     832             : 
     833           1 :             if (!par->codec_tag)
     834           1 :                 par->codec_tag = ff_codec_get_tag(ff_codec_bmp_tags,
     835             :                                                   par->codec_id);
     836           1 :             if (!par->codec_tag && par->codec_id != AV_CODEC_ID_RAWVIDEO) {
     837           0 :                 av_log(s, AV_LOG_ERROR, "No bmp codec tag found for codec %s\n",
     838             :                        avcodec_get_name(par->codec_id));
     839           0 :                 ret = AVERROR(EINVAL);
     840             :             }
     841             : 
     842           1 :             ff_put_bmp_header(dyn_cp, par, 0, 0);
     843             :         }
     844           0 :     } else if (par->codec_type == AVMEDIA_TYPE_AUDIO) {
     845             :         unsigned int tag;
     846           0 :         tag = ff_codec_get_tag(ff_codec_wav_tags, par->codec_id);
     847           0 :         if (!tag) {
     848           0 :             av_log(s, AV_LOG_ERROR, "No wav codec tag found for codec %s\n",
     849             :                    avcodec_get_name(par->codec_id));
     850           0 :             ret = AVERROR(EINVAL);
     851             :         }
     852           0 :         if (!par->codec_tag)
     853           0 :             par->codec_tag = tag;
     854             : 
     855           0 :         ff_put_wav_header(s, dyn_cp, par, FF_PUT_WAV_HEADER_FORCE_WAVEFORMATEX);
     856             :     }
     857             : 
     858          16 :     codecpriv_size = avio_close_dyn_buf(dyn_cp, &codecpriv);
     859          16 :     if (codecpriv_size)
     860          11 :         put_ebml_binary(pb, MATROSKA_ID_CODECPRIVATE, codecpriv,
     861             :                         codecpriv_size);
     862          16 :     av_free(codecpriv);
     863          16 :     return ret;
     864             : }
     865             : 
     866           4 : static int mkv_write_video_color(AVIOContext *pb, AVCodecParameters *par, AVStream *st) {
     867             :     AVIOContext *dyn_cp;
     868             :     uint8_t *colorinfo_ptr;
     869           4 :     int side_data_size = 0;
     870             :     int ret, colorinfo_size;
     871             :     const uint8_t *side_data;
     872             : 
     873           4 :     ret = avio_open_dyn_buf(&dyn_cp);
     874           4 :     if (ret < 0)
     875           0 :         return ret;
     876             : 
     877           5 :     if (par->color_trc != AVCOL_TRC_UNSPECIFIED &&
     878           1 :         par->color_trc < AVCOL_TRC_NB) {
     879           1 :         put_ebml_uint(dyn_cp, MATROSKA_ID_VIDEOCOLORTRANSFERCHARACTERISTICS,
     880           1 :                       par->color_trc);
     881             :     }
     882           4 :     if (par->color_space != AVCOL_SPC_UNSPECIFIED &&
     883           0 :         par->color_space < AVCOL_SPC_NB) {
     884           0 :         put_ebml_uint(dyn_cp, MATROSKA_ID_VIDEOCOLORMATRIXCOEFF, par->color_space);
     885             :     }
     886           4 :     if (par->color_primaries != AVCOL_PRI_UNSPECIFIED &&
     887           0 :         par->color_primaries < AVCOL_PRI_NB) {
     888           0 :         put_ebml_uint(dyn_cp, MATROSKA_ID_VIDEOCOLORPRIMARIES, par->color_primaries);
     889             :     }
     890           5 :     if (par->color_range != AVCOL_RANGE_UNSPECIFIED &&
     891           1 :         par->color_range < AVCOL_RANGE_NB) {
     892           1 :         put_ebml_uint(dyn_cp, MATROSKA_ID_VIDEOCOLORRANGE, par->color_range);
     893             :     }
     894           4 :     if (par->chroma_location != AVCHROMA_LOC_UNSPECIFIED &&
     895           0 :         par->chroma_location <= AVCHROMA_LOC_TOP) {
     896             :         int xpos, ypos;
     897             : 
     898           0 :         avcodec_enum_to_chroma_pos(&xpos, &ypos, par->chroma_location);
     899           0 :         put_ebml_uint(dyn_cp, MATROSKA_ID_VIDEOCOLORCHROMASITINGHORZ, (xpos >> 7) + 1);
     900           0 :         put_ebml_uint(dyn_cp, MATROSKA_ID_VIDEOCOLORCHROMASITINGVERT, (ypos >> 7) + 1);
     901             :     }
     902             : 
     903           4 :     side_data = av_stream_get_side_data(st, AV_PKT_DATA_CONTENT_LIGHT_LEVEL,
     904             :                                         &side_data_size);
     905           4 :     if (side_data_size) {
     906           0 :         const AVContentLightMetadata *metadata =
     907             :             (const AVContentLightMetadata*)side_data;
     908           0 :         put_ebml_uint(dyn_cp, MATROSKA_ID_VIDEOCOLORMAXCLL,  metadata->MaxCLL);
     909           0 :         put_ebml_uint(dyn_cp, MATROSKA_ID_VIDEOCOLORMAXFALL, metadata->MaxFALL);
     910             :     }
     911             : 
     912           4 :     side_data = av_stream_get_side_data(st, AV_PKT_DATA_MASTERING_DISPLAY_METADATA,
     913             :                                         &side_data_size);
     914           4 :     if (side_data_size == sizeof(AVMasteringDisplayMetadata)) {
     915           0 :         ebml_master meta_element = start_ebml_master(
     916             :             dyn_cp, MATROSKA_ID_VIDEOCOLORMASTERINGMETA, 0);
     917           0 :         const AVMasteringDisplayMetadata *metadata =
     918             :             (const AVMasteringDisplayMetadata*)side_data;
     919           0 :         if (metadata->has_primaries) {
     920           0 :             put_ebml_float(dyn_cp, MATROSKA_ID_VIDEOCOLOR_RX,
     921             :                            av_q2d(metadata->display_primaries[0][0]));
     922           0 :             put_ebml_float(dyn_cp, MATROSKA_ID_VIDEOCOLOR_RY,
     923             :                            av_q2d(metadata->display_primaries[0][1]));
     924           0 :             put_ebml_float(dyn_cp, MATROSKA_ID_VIDEOCOLOR_GX,
     925             :                            av_q2d(metadata->display_primaries[1][0]));
     926           0 :             put_ebml_float(dyn_cp, MATROSKA_ID_VIDEOCOLOR_GY,
     927             :                            av_q2d(metadata->display_primaries[1][1]));
     928           0 :             put_ebml_float(dyn_cp, MATROSKA_ID_VIDEOCOLOR_BX,
     929             :                            av_q2d(metadata->display_primaries[2][0]));
     930           0 :             put_ebml_float(dyn_cp, MATROSKA_ID_VIDEOCOLOR_BY,
     931             :                            av_q2d(metadata->display_primaries[2][1]));
     932           0 :             put_ebml_float(dyn_cp, MATROSKA_ID_VIDEOCOLOR_WHITEX,
     933             :                            av_q2d(metadata->white_point[0]));
     934           0 :             put_ebml_float(dyn_cp, MATROSKA_ID_VIDEOCOLOR_WHITEY,
     935             :                            av_q2d(metadata->white_point[1]));
     936             :         }
     937           0 :         if (metadata->has_luminance) {
     938           0 :             put_ebml_float(dyn_cp, MATROSKA_ID_VIDEOCOLOR_LUMINANCEMAX,
     939             :                            av_q2d(metadata->max_luminance));
     940           0 :             put_ebml_float(dyn_cp, MATROSKA_ID_VIDEOCOLOR_LUMINANCEMIN,
     941             :                            av_q2d(metadata->min_luminance));
     942             :         }
     943           0 :         end_ebml_master(dyn_cp, meta_element);
     944             :     }
     945             : 
     946           4 :     colorinfo_size = avio_close_dyn_buf(dyn_cp, &colorinfo_ptr);
     947           4 :     if (colorinfo_size) {
     948           1 :         ebml_master colorinfo = start_ebml_master(pb, MATROSKA_ID_VIDEOCOLOR, colorinfo_size);
     949           1 :         avio_write(pb, colorinfo_ptr, colorinfo_size);
     950           1 :         end_ebml_master(pb, colorinfo);
     951             :     }
     952           4 :     av_free(colorinfo_ptr);
     953           4 :     return 0;
     954             : }
     955             : 
     956           4 : static int mkv_write_video_projection(AVFormatContext *s, AVIOContext *pb,
     957             :                                       AVStream *st)
     958             : {
     959             :     AVIOContext b;
     960             :     AVIOContext *dyn_cp;
     961           4 :     int side_data_size = 0;
     962             :     int ret, projection_size;
     963             :     uint8_t *projection_ptr;
     964             :     uint8_t private[20];
     965             : 
     966           4 :     const AVSphericalMapping *spherical =
     967             :         (const AVSphericalMapping *)av_stream_get_side_data(st, AV_PKT_DATA_SPHERICAL,
     968             :                                                             &side_data_size);
     969             : 
     970           4 :     if (!side_data_size)
     971           4 :         return 0;
     972             : 
     973           0 :     ret = avio_open_dyn_buf(&dyn_cp);
     974           0 :     if (ret < 0)
     975           0 :         return ret;
     976             : 
     977           0 :     switch (spherical->projection) {
     978           0 :     case AV_SPHERICAL_EQUIRECTANGULAR:
     979           0 :         put_ebml_uint(dyn_cp, MATROSKA_ID_VIDEOPROJECTIONTYPE,
     980             :                       MATROSKA_VIDEO_PROJECTION_TYPE_EQUIRECTANGULAR);
     981           0 :         break;
     982           0 :     case AV_SPHERICAL_EQUIRECTANGULAR_TILE:
     983           0 :         ffio_init_context(&b, private, 20, 1, NULL, NULL, NULL, NULL);
     984           0 :         put_ebml_uint(dyn_cp, MATROSKA_ID_VIDEOPROJECTIONTYPE,
     985             :                       MATROSKA_VIDEO_PROJECTION_TYPE_EQUIRECTANGULAR);
     986           0 :         avio_wb32(&b, 0); // version + flags
     987           0 :         avio_wb32(&b, spherical->bound_top);
     988           0 :         avio_wb32(&b, spherical->bound_bottom);
     989           0 :         avio_wb32(&b, spherical->bound_left);
     990           0 :         avio_wb32(&b, spherical->bound_right);
     991           0 :         put_ebml_binary(dyn_cp, MATROSKA_ID_VIDEOPROJECTIONPRIVATE,
     992           0 :                         private, avio_tell(&b));
     993           0 :         break;
     994           0 :     case AV_SPHERICAL_CUBEMAP:
     995           0 :         ffio_init_context(&b, private, 12, 1, NULL, NULL, NULL, NULL);
     996           0 :         put_ebml_uint(dyn_cp, MATROSKA_ID_VIDEOPROJECTIONTYPE,
     997             :                       MATROSKA_VIDEO_PROJECTION_TYPE_CUBEMAP);
     998           0 :         avio_wb32(&b, 0); // version + flags
     999           0 :         avio_wb32(&b, 0); // layout
    1000           0 :         avio_wb32(&b, spherical->padding);
    1001           0 :         put_ebml_binary(dyn_cp, MATROSKA_ID_VIDEOPROJECTIONPRIVATE,
    1002           0 :                         private, avio_tell(&b));
    1003           0 :         break;
    1004           0 :     default:
    1005           0 :         av_log(s, AV_LOG_WARNING, "Unknown projection type\n");
    1006           0 :         goto end;
    1007             :     }
    1008             : 
    1009           0 :     if (spherical->yaw)
    1010           0 :         put_ebml_float(dyn_cp, MATROSKA_ID_VIDEOPROJECTIONPOSEYAW,
    1011           0 :                        (double) spherical->yaw   / (1 << 16));
    1012           0 :     if (spherical->pitch)
    1013           0 :         put_ebml_float(dyn_cp, MATROSKA_ID_VIDEOPROJECTIONPOSEPITCH,
    1014           0 :                        (double) spherical->pitch / (1 << 16));
    1015           0 :     if (spherical->roll)
    1016           0 :         put_ebml_float(dyn_cp, MATROSKA_ID_VIDEOPROJECTIONPOSEROLL,
    1017           0 :                        (double) spherical->roll  / (1 << 16));
    1018             : 
    1019           0 : end:
    1020           0 :     projection_size = avio_close_dyn_buf(dyn_cp, &projection_ptr);
    1021           0 :     if (projection_size) {
    1022           0 :         ebml_master projection = start_ebml_master(pb,
    1023             :                                                    MATROSKA_ID_VIDEOPROJECTION,
    1024             :                                                    projection_size);
    1025           0 :         avio_write(pb, projection_ptr, projection_size);
    1026           0 :         end_ebml_master(pb, projection);
    1027             :     }
    1028           0 :     av_freep(&projection_ptr);
    1029             : 
    1030           0 :     return 0;
    1031             : }
    1032             : 
    1033           4 : static void mkv_write_field_order(AVIOContext *pb, int mode,
    1034             :                                   enum AVFieldOrder field_order)
    1035             : {
    1036           4 :     switch (field_order) {
    1037           2 :     case AV_FIELD_UNKNOWN:
    1038           2 :         break;
    1039           2 :     case AV_FIELD_PROGRESSIVE:
    1040           2 :         put_ebml_uint(pb, MATROSKA_ID_VIDEOFLAGINTERLACED,
    1041             :                       MATROSKA_VIDEO_INTERLACE_FLAG_PROGRESSIVE);
    1042           2 :         break;
    1043           0 :     case AV_FIELD_TT:
    1044             :     case AV_FIELD_BB:
    1045             :     case AV_FIELD_TB:
    1046             :     case AV_FIELD_BT:
    1047           0 :         put_ebml_uint(pb, MATROSKA_ID_VIDEOFLAGINTERLACED,
    1048             :                       MATROSKA_VIDEO_INTERLACE_FLAG_INTERLACED);
    1049           0 :         if (mode != MODE_WEBM) {
    1050           0 :             switch (field_order) {
    1051           0 :             case AV_FIELD_TT:
    1052           0 :                 put_ebml_uint(pb, MATROSKA_ID_VIDEOFIELDORDER,
    1053             :                               MATROSKA_VIDEO_FIELDORDER_TT);
    1054           0 :                 break;
    1055           0 :             case AV_FIELD_BB:
    1056           0 :                 put_ebml_uint(pb, MATROSKA_ID_VIDEOFIELDORDER,
    1057             :                               MATROSKA_VIDEO_FIELDORDER_BB);
    1058           0 :                 break;
    1059           0 :             case AV_FIELD_TB:
    1060           0 :                 put_ebml_uint(pb, MATROSKA_ID_VIDEOFIELDORDER,
    1061             :                               MATROSKA_VIDEO_FIELDORDER_TB);
    1062           0 :                 break;
    1063           0 :             case AV_FIELD_BT:
    1064           0 :                 put_ebml_uint(pb, MATROSKA_ID_VIDEOFIELDORDER,
    1065             :                               MATROSKA_VIDEO_FIELDORDER_BT);
    1066           0 :                 break;
    1067             :             }
    1068             :         }
    1069             :     }
    1070           4 : }
    1071             : 
    1072           4 : static int mkv_write_stereo_mode(AVFormatContext *s, AVIOContext *pb,
    1073             :                                  AVStream *st, int mode, int *h_width, int *h_height)
    1074             : {
    1075             :     int i;
    1076           4 :     int ret = 0;
    1077             :     AVDictionaryEntry *tag;
    1078           4 :     MatroskaVideoStereoModeType format = MATROSKA_VIDEO_STEREOMODE_TYPE_NB;
    1079             : 
    1080           4 :     *h_width = 1;
    1081           4 :     *h_height = 1;
    1082             :     // convert metadata into proper side data and add it to the stream
    1083           8 :     if ((tag = av_dict_get(st->metadata, "stereo_mode", NULL, 0)) ||
    1084           4 :         (tag = av_dict_get( s->metadata, "stereo_mode", NULL, 0))) {
    1085           0 :         int stereo_mode = atoi(tag->value);
    1086             : 
    1087           0 :         for (i=0; i<MATROSKA_VIDEO_STEREOMODE_TYPE_NB; i++)
    1088           0 :             if (!strcmp(tag->value, ff_matroska_video_stereo_mode[i])){
    1089           0 :                 stereo_mode = i;
    1090           0 :                 break;
    1091             :             }
    1092             : 
    1093           0 :         if (stereo_mode < MATROSKA_VIDEO_STEREOMODE_TYPE_NB &&
    1094           0 :             stereo_mode != 10 && stereo_mode != 12) {
    1095           0 :             int ret = ff_mkv_stereo3d_conv(st, stereo_mode);
    1096           0 :             if (ret < 0)
    1097           0 :                 return ret;
    1098             :         }
    1099             :     }
    1100             : 
    1101             :     // iterate to find the stereo3d side data
    1102          12 :     for (i = 0; i < st->nb_side_data; i++) {
    1103           3 :         AVPacketSideData sd = st->side_data[i];
    1104           3 :         if (sd.type == AV_PKT_DATA_STEREO3D) {
    1105           1 :             AVStereo3D *stereo = (AVStereo3D *)sd.data;
    1106             : 
    1107           1 :             switch (stereo->type) {
    1108           1 :             case AV_STEREO3D_2D:
    1109           1 :                 format = MATROSKA_VIDEO_STEREOMODE_TYPE_MONO;
    1110           1 :                 break;
    1111           0 :             case AV_STEREO3D_SIDEBYSIDE:
    1112           0 :                 format = (stereo->flags & AV_STEREO3D_FLAG_INVERT)
    1113             :                     ? MATROSKA_VIDEO_STEREOMODE_TYPE_RIGHT_LEFT
    1114           0 :                     : MATROSKA_VIDEO_STEREOMODE_TYPE_LEFT_RIGHT;
    1115           0 :                 *h_width = 2;
    1116           0 :                 break;
    1117           0 :             case AV_STEREO3D_TOPBOTTOM:
    1118           0 :                 format = MATROSKA_VIDEO_STEREOMODE_TYPE_TOP_BOTTOM;
    1119           0 :                 if (stereo->flags & AV_STEREO3D_FLAG_INVERT)
    1120           0 :                     format--;
    1121           0 :                 *h_height = 2;
    1122           0 :                 break;
    1123           0 :             case AV_STEREO3D_CHECKERBOARD:
    1124           0 :                 format = MATROSKA_VIDEO_STEREOMODE_TYPE_CHECKERBOARD_LR;
    1125           0 :                 if (stereo->flags & AV_STEREO3D_FLAG_INVERT)
    1126           0 :                     format--;
    1127           0 :                 break;
    1128           0 :             case AV_STEREO3D_LINES:
    1129           0 :                 format = MATROSKA_VIDEO_STEREOMODE_TYPE_ROW_INTERLEAVED_LR;
    1130           0 :                 if (stereo->flags & AV_STEREO3D_FLAG_INVERT)
    1131           0 :                     format--;
    1132           0 :                 *h_height = 2;
    1133           0 :                 break;
    1134           0 :             case AV_STEREO3D_COLUMNS:
    1135           0 :                 format = MATROSKA_VIDEO_STEREOMODE_TYPE_COL_INTERLEAVED_LR;
    1136           0 :                 if (stereo->flags & AV_STEREO3D_FLAG_INVERT)
    1137           0 :                     format--;
    1138           0 :                 *h_width = 2;
    1139           0 :                 break;
    1140           0 :             case AV_STEREO3D_FRAMESEQUENCE:
    1141           0 :                 format = MATROSKA_VIDEO_STEREOMODE_TYPE_BOTH_EYES_BLOCK_LR;
    1142           0 :                 if (stereo->flags & AV_STEREO3D_FLAG_INVERT)
    1143           0 :                     format++;
    1144           0 :                 break;
    1145             :             }
    1146           2 :             break;
    1147             :         }
    1148             :     }
    1149             : 
    1150           4 :     if (format == MATROSKA_VIDEO_STEREOMODE_TYPE_NB)
    1151           3 :         return ret;
    1152             : 
    1153             :     // if webm, do not write unsupported modes
    1154           1 :     if ((mode == MODE_WEBM &&
    1155           0 :         format > MATROSKA_VIDEO_STEREOMODE_TYPE_TOP_BOTTOM &&
    1156             :         format != MATROSKA_VIDEO_STEREOMODE_TYPE_RIGHT_LEFT)
    1157           1 :         || format >= MATROSKA_VIDEO_STEREOMODE_TYPE_NB) {
    1158           0 :         av_log(s, AV_LOG_ERROR,
    1159             :                "The specified stereo mode is not valid.\n");
    1160           0 :         format = MATROSKA_VIDEO_STEREOMODE_TYPE_NB;
    1161           0 :         return AVERROR(EINVAL);
    1162             :     }
    1163             : 
    1164             :     // write StereoMode if format is valid
    1165           1 :     put_ebml_uint(pb, MATROSKA_ID_VIDEOSTEREOMODE, format);
    1166             : 
    1167           1 :     return ret;
    1168             : }
    1169             : 
    1170          16 : static int mkv_write_track(AVFormatContext *s, MatroskaMuxContext *mkv,
    1171             :                            int i, AVIOContext *pb, int default_stream_exists)
    1172             : {
    1173          16 :     AVStream *st = s->streams[i];
    1174          16 :     AVCodecParameters *par = st->codecpar;
    1175             :     ebml_master subinfo, track;
    1176          16 :     int native_id = 0;
    1177          16 :     int qt_id = 0;
    1178          16 :     int bit_depth = av_get_bits_per_sample(par->codec_id);
    1179          16 :     int sample_rate = par->sample_rate;
    1180          16 :     int output_sample_rate = 0;
    1181          16 :     int display_width_div = 1;
    1182          16 :     int display_height_div = 1;
    1183             :     int j, ret;
    1184             :     AVDictionaryEntry *tag;
    1185             : 
    1186          16 :     if (par->codec_type == AVMEDIA_TYPE_ATTACHMENT) {
    1187           1 :         mkv->have_attachments = 1;
    1188           1 :         return 0;
    1189             :     }
    1190             : 
    1191          15 :     if (par->codec_type == AVMEDIA_TYPE_AUDIO) {
    1192          10 :         if (!bit_depth && par->codec_id != AV_CODEC_ID_ADPCM_G726) {
    1193          10 :             if (par->bits_per_raw_sample)
    1194           1 :                 bit_depth = par->bits_per_raw_sample;
    1195             :             else
    1196           9 :                 bit_depth = av_get_bytes_per_sample(par->format) << 3;
    1197             :         }
    1198          10 :         if (!bit_depth)
    1199           0 :             bit_depth = par->bits_per_coded_sample;
    1200             :     }
    1201             : 
    1202          15 :     if (par->codec_id == AV_CODEC_ID_AAC) {
    1203           5 :         ret = get_aac_sample_rates(s, par->extradata, par->extradata_size, &sample_rate,
    1204             :                                    &output_sample_rate);
    1205           5 :         if (ret < 0)
    1206           0 :             return ret;
    1207             :     }
    1208             : 
    1209          15 :     track = start_ebml_master(pb, MATROSKA_ID_TRACKENTRY, 0);
    1210          30 :     put_ebml_uint (pb, MATROSKA_ID_TRACKNUMBER,
    1211          30 :                    mkv->is_dash ? mkv->dash_track_number : i + 1);
    1212          30 :     put_ebml_uint (pb, MATROSKA_ID_TRACKUID,
    1213          30 :                    mkv->is_dash ? mkv->dash_track_number : i + 1);
    1214          15 :     put_ebml_uint (pb, MATROSKA_ID_TRACKFLAGLACING , 0);    // no lacing (yet)
    1215             : 
    1216          15 :     if ((tag = av_dict_get(st->metadata, "title", NULL, 0)))
    1217           0 :         put_ebml_string(pb, MATROSKA_ID_TRACKNAME, tag->value);
    1218          15 :     tag = av_dict_get(st->metadata, "language", NULL, 0);
    1219          15 :     if (mkv->mode != MODE_WEBM || par->codec_id != AV_CODEC_ID_WEBVTT) {
    1220          15 :         put_ebml_string(pb, MATROSKA_ID_TRACKLANGUAGE, tag && tag->value ? tag->value:"und");
    1221           0 :     } else if (tag && tag->value) {
    1222           0 :         put_ebml_string(pb, MATROSKA_ID_TRACKLANGUAGE, tag->value);
    1223             :     }
    1224             : 
    1225             :     // The default value for TRACKFLAGDEFAULT is 1, so add element
    1226             :     // if we need to clear it.
    1227          15 :     if (default_stream_exists && !(st->disposition & AV_DISPOSITION_DEFAULT))
    1228           0 :         put_ebml_uint(pb, MATROSKA_ID_TRACKFLAGDEFAULT, !!(st->disposition & AV_DISPOSITION_DEFAULT));
    1229             : 
    1230          15 :     if (st->disposition & AV_DISPOSITION_FORCED)
    1231           0 :         put_ebml_uint(pb, MATROSKA_ID_TRACKFLAGFORCED, 1);
    1232             : 
    1233          15 :     if (mkv->mode == MODE_WEBM && par->codec_id == AV_CODEC_ID_WEBVTT) {
    1234             :         const char *codec_id;
    1235           0 :         if (st->disposition & AV_DISPOSITION_CAPTIONS) {
    1236           0 :             codec_id = "D_WEBVTT/CAPTIONS";
    1237           0 :             native_id = MATROSKA_TRACK_TYPE_SUBTITLE;
    1238           0 :         } else if (st->disposition & AV_DISPOSITION_DESCRIPTIONS) {
    1239           0 :             codec_id = "D_WEBVTT/DESCRIPTIONS";
    1240           0 :             native_id = MATROSKA_TRACK_TYPE_METADATA;
    1241           0 :         } else if (st->disposition & AV_DISPOSITION_METADATA) {
    1242           0 :             codec_id = "D_WEBVTT/METADATA";
    1243           0 :             native_id = MATROSKA_TRACK_TYPE_METADATA;
    1244             :         } else {
    1245           0 :             codec_id = "D_WEBVTT/SUBTITLES";
    1246           0 :             native_id = MATROSKA_TRACK_TYPE_SUBTITLE;
    1247             :         }
    1248           0 :         put_ebml_string(pb, MATROSKA_ID_CODECID, codec_id);
    1249             :     } else {
    1250             :         // look for a codec ID string specific to mkv to use,
    1251             :         // if none are found, use AVI codes
    1252          29 :         if (par->codec_id != AV_CODEC_ID_RAWVIDEO || par->codec_tag) {
    1253         332 :             for (j = 0; ff_mkv_codec_tags[j].id != AV_CODEC_ID_NONE; j++) {
    1254         332 :                 if (ff_mkv_codec_tags[j].id == par->codec_id && par->codec_id != AV_CODEC_ID_FFV1) {
    1255          14 :                     put_ebml_string(pb, MATROSKA_ID_CODECID, ff_mkv_codec_tags[j].str);
    1256          14 :                     native_id = 1;
    1257          14 :                     break;
    1258             :                 }
    1259             :             }
    1260             :         } else {
    1261           1 :             if (mkv->allow_raw_vfw) {
    1262           1 :                 native_id = 0;
    1263             :             } else {
    1264           0 :                 av_log(s, AV_LOG_ERROR, "Raw RGB is not supported Natively in Matroska, you can use AVI or NUT or\n"
    1265             :                                         "If you would like to store it anyway using VFW mode, enable allow_raw_vfw (-allow_raw_vfw 1)\n");
    1266           0 :                 return AVERROR(EINVAL);
    1267             :             }
    1268             :         }
    1269             :     }
    1270             : 
    1271          15 :     if (par->codec_type == AVMEDIA_TYPE_AUDIO && par->initial_padding && par->codec_id == AV_CODEC_ID_OPUS) {
    1272           0 :         int64_t codecdelay = av_rescale_q(par->initial_padding,
    1273           0 :                                           (AVRational){ 1, 48000 },
    1274           0 :                                           (AVRational){ 1, 1000000000 });
    1275           0 :         if (codecdelay < 0) {
    1276           0 :             av_log(s, AV_LOG_ERROR, "Initial padding is invalid\n");
    1277           0 :             return AVERROR(EINVAL);
    1278             :         }
    1279             : //         mkv->tracks[i].ts_offset = av_rescale_q(par->initial_padding,
    1280             : //                                                 (AVRational){ 1, par->sample_rate },
    1281             : //                                                 st->time_base);
    1282             : 
    1283           0 :         put_ebml_uint(pb, MATROSKA_ID_CODECDELAY, codecdelay);
    1284             :     }
    1285          15 :     if (par->codec_id == AV_CODEC_ID_OPUS) {
    1286           0 :         put_ebml_uint(pb, MATROSKA_ID_SEEKPREROLL, OPUS_SEEK_PREROLL);
    1287             :     }
    1288             : 
    1289          15 :     if (mkv->mode == MODE_WEBM && !(par->codec_id == AV_CODEC_ID_VP8 ||
    1290           0 :                                     par->codec_id == AV_CODEC_ID_VP9 ||
    1291           0 :                                     par->codec_id == AV_CODEC_ID_OPUS ||
    1292           0 :                                     par->codec_id == AV_CODEC_ID_VORBIS ||
    1293           0 :                                     par->codec_id == AV_CODEC_ID_WEBVTT)) {
    1294           0 :         av_log(s, AV_LOG_ERROR,
    1295             :                "Only VP8 or VP9 video and Vorbis or Opus audio and WebVTT subtitles are supported for WebM.\n");
    1296           0 :         return AVERROR(EINVAL);
    1297             :     }
    1298             : 
    1299          15 :     switch (par->codec_type) {
    1300           4 :     case AVMEDIA_TYPE_VIDEO:
    1301           4 :         mkv->have_video = 1;
    1302           4 :         put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, MATROSKA_TRACK_TYPE_VIDEO);
    1303             : 
    1304           4 :         if(   st->avg_frame_rate.num > 0 && st->avg_frame_rate.den > 0
    1305           4 :            && av_cmp_q(av_inv_q(st->avg_frame_rate), st->time_base) > 0)
    1306           4 :             put_ebml_uint(pb, MATROSKA_ID_TRACKDEFAULTDURATION, 1000000000LL * st->avg_frame_rate.den / st->avg_frame_rate.num);
    1307             :         else
    1308           0 :             put_ebml_uint(pb, MATROSKA_ID_TRACKDEFAULTDURATION, 1000000000LL * st->time_base.num / st->time_base.den);
    1309             : 
    1310           5 :         if (!native_id &&
    1311           2 :             ff_codec_get_tag(ff_codec_movvideo_tags, par->codec_id) &&
    1312           3 :             ((!ff_codec_get_tag(ff_codec_bmp_tags,   par->codec_id) && par->codec_id != AV_CODEC_ID_RAWVIDEO) ||
    1313           2 :              par->codec_id == AV_CODEC_ID_SVQ1 ||
    1314           2 :              par->codec_id == AV_CODEC_ID_SVQ3 ||
    1315           1 :              par->codec_id == AV_CODEC_ID_CINEPAK))
    1316           0 :             qt_id = 1;
    1317             : 
    1318           4 :         if (qt_id)
    1319           0 :             put_ebml_string(pb, MATROSKA_ID_CODECID, "V_QUICKTIME");
    1320           4 :         else if (!native_id) {
    1321             :             // if there is no mkv-specific codec ID, use VFW mode
    1322           1 :             put_ebml_string(pb, MATROSKA_ID_CODECID, "V_MS/VFW/FOURCC");
    1323           1 :             mkv->tracks[i].write_dts = 1;
    1324           1 :             s->internal->avoid_negative_ts_use_pts = 0;
    1325             :         }
    1326             : 
    1327           4 :         subinfo = start_ebml_master(pb, MATROSKA_ID_TRACKVIDEO, 0);
    1328             : 
    1329           4 :         put_ebml_uint (pb, MATROSKA_ID_VIDEOPIXELWIDTH , par->width);
    1330           4 :         put_ebml_uint (pb, MATROSKA_ID_VIDEOPIXELHEIGHT, par->height);
    1331             : 
    1332           4 :         mkv_write_field_order(pb, mkv->mode, par->field_order);
    1333             : 
    1334             :         // check both side data and metadata for stereo information,
    1335             :         // write the result to the bitstream if any is found
    1336           4 :         ret = mkv_write_stereo_mode(s, pb, st, mkv->mode,
    1337             :                                     &display_width_div,
    1338             :                                     &display_height_div);
    1339           4 :         if (ret < 0)
    1340           0 :             return ret;
    1341             : 
    1342           8 :         if (((tag = av_dict_get(st->metadata, "alpha_mode", NULL, 0)) && atoi(tag->value)) ||
    1343           8 :             ((tag = av_dict_get( s->metadata, "alpha_mode", NULL, 0)) && atoi(tag->value)) ||
    1344           4 :             (par->format == AV_PIX_FMT_YUVA420P)) {
    1345           0 :             put_ebml_uint(pb, MATROSKA_ID_VIDEOALPHAMODE, 1);
    1346             :         }
    1347             : 
    1348             :         // write DisplayWidth and DisplayHeight, they contain the size of
    1349             :         // a single source view and/or the display aspect ratio
    1350           4 :         if (st->sample_aspect_ratio.num) {
    1351           1 :             int64_t d_width = av_rescale(par->width, st->sample_aspect_ratio.num, st->sample_aspect_ratio.den);
    1352           1 :             if (d_width > INT_MAX) {
    1353           0 :                 av_log(s, AV_LOG_ERROR, "Overflow in display width\n");
    1354           0 :                 return AVERROR(EINVAL);
    1355             :             }
    1356           1 :             if (d_width != par->width || display_width_div != 1 || display_height_div != 1) {
    1357           0 :                 if (mkv->mode == MODE_WEBM || display_width_div != 1 || display_height_div != 1) {
    1358           0 :                     put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYWIDTH , d_width / display_width_div);
    1359           0 :                     put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYHEIGHT, par->height / display_height_div);
    1360             :                 } else {
    1361             :                     AVRational display_aspect_ratio;
    1362           0 :                     av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den,
    1363           0 :                               par->width  * (int64_t)st->sample_aspect_ratio.num,
    1364           0 :                               par->height * (int64_t)st->sample_aspect_ratio.den,
    1365             :                               1024 * 1024);
    1366           0 :                     put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYWIDTH,  display_aspect_ratio.num);
    1367           0 :                     put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYHEIGHT, display_aspect_ratio.den);
    1368           0 :                     put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYUNIT, MATROSKA_VIDEO_DISPLAYUNIT_DAR);
    1369             :                 }
    1370             :             }
    1371           3 :         } else if (display_width_div != 1 || display_height_div != 1) {
    1372           0 :             put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYWIDTH , par->width / display_width_div);
    1373           0 :             put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYHEIGHT, par->height / display_height_div);
    1374           3 :         } else if (mkv->mode != MODE_WEBM)
    1375           3 :             put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYUNIT, MATROSKA_VIDEO_DISPLAYUNIT_UNKNOWN);
    1376             : 
    1377           4 :         if (par->codec_id == AV_CODEC_ID_RAWVIDEO) {
    1378           1 :             uint32_t color_space = av_le2ne32(par->codec_tag);
    1379           1 :             put_ebml_binary(pb, MATROSKA_ID_VIDEOCOLORSPACE, &color_space, sizeof(color_space));
    1380             :         }
    1381           4 :         ret = mkv_write_video_color(pb, par, st);
    1382           4 :         if (ret < 0)
    1383           0 :             return ret;
    1384           4 :         ret = mkv_write_video_projection(s, pb, st);
    1385           4 :         if (ret < 0)
    1386           0 :             return ret;
    1387           4 :         end_ebml_master(pb, subinfo);
    1388           4 :         break;
    1389             : 
    1390          10 :     case AVMEDIA_TYPE_AUDIO:
    1391          10 :         put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, MATROSKA_TRACK_TYPE_AUDIO);
    1392             : 
    1393          10 :         if (!native_id)
    1394             :             // no mkv-specific ID, use ACM mode
    1395           0 :             put_ebml_string(pb, MATROSKA_ID_CODECID, "A_MS/ACM");
    1396             : 
    1397          10 :         subinfo = start_ebml_master(pb, MATROSKA_ID_TRACKAUDIO, 0);
    1398          10 :         put_ebml_uint  (pb, MATROSKA_ID_AUDIOCHANNELS    , par->channels);
    1399             : 
    1400          10 :         mkv->tracks[i].sample_rate_offset = avio_tell(pb);
    1401          10 :         put_ebml_float (pb, MATROSKA_ID_AUDIOSAMPLINGFREQ, sample_rate);
    1402          10 :         if (output_sample_rate)
    1403           1 :             put_ebml_float(pb, MATROSKA_ID_AUDIOOUTSAMPLINGFREQ, output_sample_rate);
    1404          10 :         if (bit_depth)
    1405          10 :             put_ebml_uint(pb, MATROSKA_ID_AUDIOBITDEPTH, bit_depth);
    1406          10 :         end_ebml_master(pb, subinfo);
    1407          10 :         break;
    1408             : 
    1409           1 :     case AVMEDIA_TYPE_SUBTITLE:
    1410           1 :         if (!native_id) {
    1411           0 :             av_log(s, AV_LOG_ERROR, "Subtitle codec %d is not supported.\n", par->codec_id);
    1412           0 :             return AVERROR(ENOSYS);
    1413             :         }
    1414             : 
    1415           1 :         if (mkv->mode != MODE_WEBM || par->codec_id != AV_CODEC_ID_WEBVTT)
    1416           1 :             native_id = MATROSKA_TRACK_TYPE_SUBTITLE;
    1417             : 
    1418           1 :         put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, native_id);
    1419           1 :         break;
    1420           0 :     default:
    1421           0 :         av_log(s, AV_LOG_ERROR, "Only audio, video, and subtitles are supported for Matroska.\n");
    1422           0 :         return AVERROR(EINVAL);
    1423             :     }
    1424             : 
    1425          15 :     if (mkv->mode != MODE_WEBM || par->codec_id != AV_CODEC_ID_WEBVTT) {
    1426          15 :         mkv->tracks[i].codecpriv_offset = avio_tell(pb);
    1427          15 :         ret = mkv_write_codecprivate(s, pb, par, native_id, qt_id);
    1428          15 :         if (ret < 0)
    1429           0 :             return ret;
    1430             :     }
    1431             : 
    1432          15 :     end_ebml_master(pb, track);
    1433             : 
    1434          15 :     return 0;
    1435             : }
    1436             : 
    1437          13 : static int mkv_write_tracks(AVFormatContext *s)
    1438             : {
    1439          13 :     MatroskaMuxContext *mkv = s->priv_data;
    1440          13 :     AVIOContext *pb = s->pb;
    1441          13 :     int i, ret, default_stream_exists = 0;
    1442             : 
    1443          13 :     ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_TRACKS, avio_tell(pb));
    1444          13 :     if (ret < 0)
    1445           0 :         return ret;
    1446             : 
    1447          13 :     ret = start_ebml_master_crc32(pb, &mkv->tracks_bc, mkv, &mkv->tracks_master, MATROSKA_ID_TRACKS, 0);
    1448          13 :     if (ret < 0)
    1449           0 :         return ret;
    1450             : 
    1451          29 :     for (i = 0; i < s->nb_streams; i++) {
    1452          16 :         AVStream *st = s->streams[i];
    1453          16 :         default_stream_exists |= st->disposition & AV_DISPOSITION_DEFAULT;
    1454             :     }
    1455          29 :     for (i = 0; i < s->nb_streams; i++) {
    1456          16 :         ret = mkv_write_track(s, mkv, i, mkv->tracks_bc, default_stream_exists);
    1457          16 :         if (ret < 0)
    1458           0 :             return ret;
    1459             :     }
    1460             : 
    1461          13 :     if ((pb->seekable & AVIO_SEEKABLE_NORMAL) && !mkv->is_live)
    1462           5 :         end_ebml_master_crc32_preliminary(pb, &mkv->tracks_bc, mkv, mkv->tracks_master);
    1463             :     else
    1464           8 :         end_ebml_master_crc32(pb, &mkv->tracks_bc, mkv, mkv->tracks_master);
    1465             : 
    1466          13 :     return 0;
    1467             : }
    1468             : 
    1469          26 : static int mkv_write_chapters(AVFormatContext *s)
    1470             : {
    1471          26 :     MatroskaMuxContext *mkv = s->priv_data;
    1472          26 :     AVIOContext *dyn_cp, *pb = s->pb;
    1473             :     ebml_master chapters, editionentry;
    1474          26 :     AVRational scale = {1, 1E9};
    1475             :     int i, ret;
    1476             : 
    1477          26 :     if (!s->nb_chapters || mkv->wrote_chapters)
    1478          26 :         return 0;
    1479             : 
    1480           0 :     ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_CHAPTERS, avio_tell(pb));
    1481           0 :     if (ret < 0) return ret;
    1482             : 
    1483           0 :     ret = start_ebml_master_crc32(pb, &dyn_cp, mkv, &chapters, MATROSKA_ID_CHAPTERS, 0);
    1484           0 :     if (ret < 0) return ret;
    1485             : 
    1486           0 :     editionentry = start_ebml_master(dyn_cp, MATROSKA_ID_EDITIONENTRY, 0);
    1487           0 :     if (mkv->mode != MODE_WEBM) {
    1488           0 :         put_ebml_uint(dyn_cp, MATROSKA_ID_EDITIONFLAGDEFAULT, 1);
    1489           0 :         put_ebml_uint(dyn_cp, MATROSKA_ID_EDITIONFLAGHIDDEN , 0);
    1490             :     }
    1491           0 :     for (i = 0; i < s->nb_chapters; i++) {
    1492             :         ebml_master chapteratom, chapterdisplay;
    1493           0 :         AVChapter *c     = s->chapters[i];
    1494           0 :         int64_t chapterstart = av_rescale_q(c->start, c->time_base, scale);
    1495           0 :         int64_t chapterend   = av_rescale_q(c->end,   c->time_base, scale);
    1496           0 :         AVDictionaryEntry *t = NULL;
    1497           0 :         if (chapterstart < 0 || chapterstart > chapterend || chapterend < 0) {
    1498           0 :             av_log(s, AV_LOG_ERROR,
    1499             :                    "Invalid chapter start (%"PRId64") or end (%"PRId64").\n",
    1500             :                    chapterstart, chapterend);
    1501           0 :             return AVERROR_INVALIDDATA;
    1502             :         }
    1503             : 
    1504           0 :         chapteratom = start_ebml_master(dyn_cp, MATROSKA_ID_CHAPTERATOM, 0);
    1505           0 :         put_ebml_uint(dyn_cp, MATROSKA_ID_CHAPTERUID, c->id + mkv->chapter_id_offset);
    1506           0 :         put_ebml_uint(dyn_cp, MATROSKA_ID_CHAPTERTIMESTART, chapterstart);
    1507           0 :         put_ebml_uint(dyn_cp, MATROSKA_ID_CHAPTERTIMEEND, chapterend);
    1508           0 :         if (mkv->mode != MODE_WEBM) {
    1509           0 :             put_ebml_uint(dyn_cp, MATROSKA_ID_CHAPTERFLAGHIDDEN , 0);
    1510           0 :             put_ebml_uint(dyn_cp, MATROSKA_ID_CHAPTERFLAGENABLED, 1);
    1511             :         }
    1512           0 :         if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
    1513           0 :             chapterdisplay = start_ebml_master(dyn_cp, MATROSKA_ID_CHAPTERDISPLAY, 0);
    1514           0 :             put_ebml_string(dyn_cp, MATROSKA_ID_CHAPSTRING, t->value);
    1515           0 :             put_ebml_string(dyn_cp, MATROSKA_ID_CHAPLANG  , "und");
    1516           0 :             end_ebml_master(dyn_cp, chapterdisplay);
    1517             :         }
    1518           0 :         end_ebml_master(dyn_cp, chapteratom);
    1519             :     }
    1520           0 :     end_ebml_master(dyn_cp, editionentry);
    1521           0 :     end_ebml_master_crc32(pb, &dyn_cp, mkv, chapters);
    1522             : 
    1523           0 :     mkv->wrote_chapters = 1;
    1524           0 :     return 0;
    1525             : }
    1526             : 
    1527          27 : static int mkv_write_simpletag(AVIOContext *pb, AVDictionaryEntry *t)
    1528             : {
    1529          27 :     uint8_t *key = av_strdup(t->key);
    1530          27 :     uint8_t *p   = key;
    1531          27 :     const uint8_t *lang = NULL;
    1532             :     ebml_master tag;
    1533             : 
    1534          27 :     if (!key)
    1535           0 :         return AVERROR(ENOMEM);
    1536             : 
    1537          27 :     if ((p = strrchr(p, '-')) &&
    1538           0 :         (lang = ff_convert_lang_to(p + 1, AV_LANG_ISO639_2_BIBL)))
    1539           0 :         *p = 0;
    1540             : 
    1541          27 :     p = key;
    1542         332 :     while (*p) {
    1543         278 :         if (*p == ' ')
    1544           0 :             *p = '_';
    1545         278 :         else if (*p >= 'a' && *p <= 'z')
    1546         245 :             *p -= 'a' - 'A';
    1547         278 :         p++;
    1548             :     }
    1549             : 
    1550          27 :     tag = start_ebml_master(pb, MATROSKA_ID_SIMPLETAG, 0);
    1551          27 :     put_ebml_string(pb, MATROSKA_ID_TAGNAME, key);
    1552          27 :     if (lang)
    1553           0 :         put_ebml_string(pb, MATROSKA_ID_TAGLANG, lang);
    1554          27 :     put_ebml_string(pb, MATROSKA_ID_TAGSTRING, t->value);
    1555          27 :     end_ebml_master(pb, tag);
    1556             : 
    1557          27 :     av_freep(&key);
    1558          27 :     return 0;
    1559             : }
    1560             : 
    1561          17 : static int mkv_write_tag_targets(AVFormatContext *s,
    1562             :                                  unsigned int elementid, unsigned int uid,
    1563             :                                  ebml_master *tags, ebml_master* tag)
    1564             : {
    1565             :     AVIOContext *pb;
    1566          17 :     MatroskaMuxContext *mkv = s->priv_data;
    1567             :     ebml_master targets;
    1568             :     int ret;
    1569             : 
    1570          17 :     if (!tags->pos) {
    1571           9 :         ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_TAGS, avio_tell(s->pb));
    1572           9 :         if (ret < 0) return ret;
    1573             : 
    1574           9 :         start_ebml_master_crc32(s->pb, &mkv->tags_bc, mkv, tags, MATROSKA_ID_TAGS, 0);
    1575             :     }
    1576          17 :     pb = mkv->tags_bc;
    1577             : 
    1578          17 :     *tag     = start_ebml_master(pb, MATROSKA_ID_TAG,       0);
    1579          17 :     targets = start_ebml_master(pb, MATROSKA_ID_TAGTARGETS, 0);
    1580          17 :     if (elementid)
    1581          13 :         put_ebml_uint(pb, elementid, uid);
    1582          17 :     end_ebml_master(pb, targets);
    1583          17 :     return 0;
    1584             : }
    1585             : 
    1586          55 : static int mkv_check_tag_name(const char *name, unsigned int elementid)
    1587             : {
    1588         107 :     return av_strcasecmp(name, "title") &&
    1589         104 :            av_strcasecmp(name, "stereo_mode") &&
    1590          98 :            av_strcasecmp(name, "creation_time") &&
    1591          92 :            av_strcasecmp(name, "encoding_tool") &&
    1592          92 :            av_strcasecmp(name, "duration") &&
    1593          20 :            (elementid != MATROSKA_ID_TAGTARGETS_TRACKUID ||
    1594         151 :             av_strcasecmp(name, "language")) &&
    1595           2 :            (elementid != MATROSKA_ID_TAGTARGETS_ATTACHUID ||
    1596           3 :             (av_strcasecmp(name, "filename") &&
    1597           1 :              av_strcasecmp(name, "mimetype")));
    1598             : }
    1599             : 
    1600          10 : static int mkv_write_tag(AVFormatContext *s, AVDictionary *m, unsigned int elementid,
    1601             :                          unsigned int uid, ebml_master *tags)
    1602             : {
    1603          10 :     MatroskaMuxContext *mkv = s->priv_data;
    1604             :     ebml_master tag;
    1605             :     int ret;
    1606          10 :     AVDictionaryEntry *t = NULL;
    1607             : 
    1608          10 :     ret = mkv_write_tag_targets(s, elementid, uid, tags, &tag);
    1609          10 :     if (ret < 0)
    1610           0 :         return ret;
    1611             : 
    1612          49 :     while ((t = av_dict_get(m, "", t, AV_DICT_IGNORE_SUFFIX))) {
    1613          29 :         if (mkv_check_tag_name(t->key, elementid)) {
    1614          27 :             ret = mkv_write_simpletag(mkv->tags_bc, t);
    1615          27 :             if (ret < 0)
    1616           0 :                 return ret;
    1617             :         }
    1618             :     }
    1619             : 
    1620          10 :     end_ebml_master(mkv->tags_bc, tag);
    1621          10 :     return 0;
    1622             : }
    1623             : 
    1624          29 : static int mkv_check_tag(AVDictionary *m, unsigned int elementid)
    1625             : {
    1626          29 :     AVDictionaryEntry *t = NULL;
    1627             : 
    1628          74 :     while ((t = av_dict_get(m, "", t, AV_DICT_IGNORE_SUFFIX)))
    1629          26 :         if (mkv_check_tag_name(t->key, elementid))
    1630          10 :             return 1;
    1631             : 
    1632          19 :     return 0;
    1633             : }
    1634             : 
    1635          13 : static int mkv_write_tags(AVFormatContext *s)
    1636             : {
    1637          13 :     MatroskaMuxContext *mkv = s->priv_data;
    1638             :     int i, ret;
    1639             : 
    1640          13 :     ff_metadata_conv_ctx(s, ff_mkv_metadata_conv, NULL);
    1641             : 
    1642          13 :     if (mkv_check_tag(s->metadata, 0)) {
    1643           4 :         ret = mkv_write_tag(s, s->metadata, 0, 0, &mkv->tags);
    1644           4 :         if (ret < 0) return ret;
    1645             :     }
    1646             : 
    1647          29 :     for (i = 0; i < s->nb_streams; i++) {
    1648          16 :         AVStream *st = s->streams[i];
    1649             : 
    1650          16 :         if (st->codecpar->codec_type == AVMEDIA_TYPE_ATTACHMENT)
    1651           1 :             continue;
    1652             : 
    1653          15 :         if (!mkv_check_tag(st->metadata, MATROSKA_ID_TAGTARGETS_TRACKUID))
    1654           9 :             continue;
    1655             : 
    1656           6 :         ret = mkv_write_tag(s, st->metadata, MATROSKA_ID_TAGTARGETS_TRACKUID, i + 1, &mkv->tags);
    1657           6 :         if (ret < 0) return ret;
    1658             :     }
    1659             : 
    1660          13 :     if ((s->pb->seekable & AVIO_SEEKABLE_NORMAL) && !mkv->is_live) {
    1661          13 :         for (i = 0; i < s->nb_streams; i++) {
    1662             :             AVIOContext *pb;
    1663           8 :             AVStream *st = s->streams[i];
    1664             :             ebml_master tag_target;
    1665             :             ebml_master tag;
    1666             : 
    1667           8 :             if (st->codecpar->codec_type == AVMEDIA_TYPE_ATTACHMENT)
    1668           1 :                 continue;
    1669             : 
    1670           7 :             mkv_write_tag_targets(s, MATROSKA_ID_TAGTARGETS_TRACKUID, i + 1, &mkv->tags, &tag_target);
    1671           7 :             pb = mkv->tags_bc;
    1672             : 
    1673           7 :             tag = start_ebml_master(pb, MATROSKA_ID_SIMPLETAG, 0);
    1674           7 :             put_ebml_string(pb, MATROSKA_ID_TAGNAME, "DURATION");
    1675           7 :             mkv->stream_duration_offsets[i] = avio_tell(pb);
    1676             : 
    1677             :             // Reserve space to write duration as a 20-byte string.
    1678             :             // 2 (ebml id) + 1 (data size) + 20 (data)
    1679           7 :             put_ebml_void(pb, 23);
    1680           7 :             end_ebml_master(pb, tag);
    1681           7 :             end_ebml_master(pb, tag_target);
    1682             :         }
    1683             :     }
    1684             : 
    1685          13 :     if (mkv->mode != MODE_WEBM) {
    1686          13 :         for (i = 0; i < s->nb_chapters; i++) {
    1687           0 :             AVChapter *ch = s->chapters[i];
    1688             : 
    1689           0 :             if (!mkv_check_tag(ch->metadata, MATROSKA_ID_TAGTARGETS_CHAPTERUID))
    1690           0 :                 continue;
    1691             : 
    1692           0 :             ret = mkv_write_tag(s, ch->metadata, MATROSKA_ID_TAGTARGETS_CHAPTERUID, ch->id + mkv->chapter_id_offset, &mkv->tags);
    1693           0 :             if (ret < 0)
    1694           0 :                 return ret;
    1695             :         }
    1696             :     }
    1697             : 
    1698          13 :     if (mkv->have_attachments && mkv->mode != MODE_WEBM) {
    1699           2 :         for (i = 0; i < mkv->attachments->num_entries; i++) {
    1700           1 :             mkv_attachment *attachment = &mkv->attachments->entries[i];
    1701           1 :             AVStream *st = s->streams[attachment->stream_idx];
    1702             : 
    1703           1 :             if (!mkv_check_tag(st->metadata, MATROSKA_ID_TAGTARGETS_ATTACHUID))
    1704           1 :                 continue;
    1705             : 
    1706           0 :             ret = mkv_write_tag(s, st->metadata, MATROSKA_ID_TAGTARGETS_ATTACHUID, attachment->fileuid, &mkv->tags);
    1707           0 :             if (ret < 0)
    1708           0 :                 return ret;
    1709             :         }
    1710             :     }
    1711             : 
    1712          13 :     if (mkv->tags.pos) {
    1713           9 :         if ((s->pb->seekable & AVIO_SEEKABLE_NORMAL) && !mkv->is_live)
    1714           5 :             end_ebml_master_crc32_preliminary(s->pb, &mkv->tags_bc, mkv, mkv->tags);
    1715             :         else
    1716           4 :             end_ebml_master_crc32(s->pb, &mkv->tags_bc, mkv, mkv->tags);
    1717             :     }
    1718          13 :     return 0;
    1719             : }
    1720             : 
    1721          13 : static int mkv_write_attachments(AVFormatContext *s)
    1722             : {
    1723          13 :     MatroskaMuxContext *mkv = s->priv_data;
    1724          13 :     AVIOContext *dyn_cp, *pb = s->pb;
    1725             :     ebml_master attachments;
    1726             :     AVLFG c;
    1727             :     int i, ret;
    1728             : 
    1729          13 :     if (!mkv->have_attachments)
    1730          12 :         return 0;
    1731             : 
    1732           1 :     mkv->attachments = av_mallocz(sizeof(*mkv->attachments));
    1733           1 :     if (!mkv->attachments)
    1734           0 :         return AVERROR(ENOMEM);
    1735             : 
    1736           1 :     av_lfg_init(&c, av_get_random_seed());
    1737             : 
    1738           1 :     ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_ATTACHMENTS, avio_tell(pb));
    1739           1 :     if (ret < 0) return ret;
    1740             : 
    1741           1 :     ret = start_ebml_master_crc32(pb, &dyn_cp, mkv, &attachments, MATROSKA_ID_ATTACHMENTS, 0);
    1742           1 :     if (ret < 0) return ret;
    1743             : 
    1744           4 :     for (i = 0; i < s->nb_streams; i++) {
    1745           3 :         AVStream *st = s->streams[i];
    1746             :         ebml_master attached_file;
    1747           3 :         mkv_attachment *attachment = mkv->attachments->entries;
    1748             :         AVDictionaryEntry *t;
    1749           3 :         const char *mimetype = NULL;
    1750             :         uint32_t fileuid;
    1751             : 
    1752           3 :         if (st->codecpar->codec_type != AVMEDIA_TYPE_ATTACHMENT)
    1753           2 :             continue;
    1754             : 
    1755           1 :         attachment = av_realloc_array(attachment, mkv->attachments->num_entries + 1, sizeof(mkv_attachment));
    1756           1 :         if (!attachment)
    1757           0 :             return AVERROR(ENOMEM);
    1758           1 :         mkv->attachments->entries = attachment;
    1759             : 
    1760           1 :         attached_file = start_ebml_master(dyn_cp, MATROSKA_ID_ATTACHEDFILE, 0);
    1761             : 
    1762           1 :         if (t = av_dict_get(st->metadata, "title", NULL, 0))
    1763           0 :             put_ebml_string(dyn_cp, MATROSKA_ID_FILEDESC, t->value);
    1764           1 :         if (!(t = av_dict_get(st->metadata, "filename", NULL, 0))) {
    1765           0 :             av_log(s, AV_LOG_ERROR, "Attachment stream %d has no filename tag.\n", i);
    1766           0 :             return AVERROR(EINVAL);
    1767             :         }
    1768           1 :         put_ebml_string(dyn_cp, MATROSKA_ID_FILENAME, t->value);
    1769           1 :         if (t = av_dict_get(st->metadata, "mimetype", NULL, 0))
    1770           1 :             mimetype = t->value;
    1771           0 :         else if (st->codecpar->codec_id != AV_CODEC_ID_NONE ) {
    1772             :             int i;
    1773           0 :             for (i = 0; ff_mkv_mime_tags[i].id != AV_CODEC_ID_NONE; i++)
    1774           0 :                 if (ff_mkv_mime_tags[i].id == st->codecpar->codec_id) {
    1775           0 :                     mimetype = ff_mkv_mime_tags[i].str;
    1776           0 :                     break;
    1777             :                 }
    1778           0 :             for (i = 0; ff_mkv_image_mime_tags[i].id != AV_CODEC_ID_NONE; i++)
    1779           0 :                 if (ff_mkv_image_mime_tags[i].id == st->codecpar->codec_id) {
    1780           0 :                     mimetype = ff_mkv_image_mime_tags[i].str;
    1781           0 :                     break;
    1782             :                 }
    1783             :         }
    1784           1 :         if (!mimetype) {
    1785           0 :             av_log(s, AV_LOG_ERROR, "Attachment stream %d has no mimetype tag and "
    1786             :                                     "it cannot be deduced from the codec id.\n", i);
    1787           0 :             return AVERROR(EINVAL);
    1788             :         }
    1789             : 
    1790           1 :         if (s->flags & AVFMT_FLAG_BITEXACT) {
    1791           1 :             struct AVSHA *sha = av_sha_alloc();
    1792             :             uint8_t digest[20];
    1793           1 :             if (!sha)
    1794           0 :                 return AVERROR(ENOMEM);
    1795           1 :             av_sha_init(sha, 160);
    1796           1 :             av_sha_update(sha, st->codecpar->extradata, st->codecpar->extradata_size);
    1797           1 :             av_sha_final(sha, digest);
    1798           1 :             av_free(sha);
    1799           1 :             fileuid = AV_RL32(digest);
    1800             :         } else {
    1801           0 :             fileuid = av_lfg_get(&c);
    1802             :         }
    1803           1 :         av_log(s, AV_LOG_VERBOSE, "Using %.8"PRIx32" for attachment %d\n",
    1804           1 :                fileuid, mkv->attachments->num_entries);
    1805             : 
    1806           1 :         put_ebml_string(dyn_cp, MATROSKA_ID_FILEMIMETYPE, mimetype);
    1807           1 :         put_ebml_binary(dyn_cp, MATROSKA_ID_FILEDATA, st->codecpar->extradata, st->codecpar->extradata_size);
    1808           1 :         put_ebml_uint(dyn_cp, MATROSKA_ID_FILEUID, fileuid);
    1809           1 :         end_ebml_master(dyn_cp, attached_file);
    1810             : 
    1811           1 :         mkv->attachments->entries[mkv->attachments->num_entries].stream_idx = i;
    1812           1 :         mkv->attachments->entries[mkv->attachments->num_entries++].fileuid  = fileuid;
    1813             :     }
    1814           1 :     end_ebml_master_crc32(pb, &dyn_cp, mkv, attachments);
    1815             : 
    1816           1 :     return 0;
    1817             : }
    1818             : 
    1819           9 : static int64_t get_metadata_duration(AVFormatContext *s)
    1820             : {
    1821           9 :     int i = 0;
    1822           9 :     int64_t max = 0;
    1823             :     int64_t us;
    1824             : 
    1825           9 :     AVDictionaryEntry *explicitDuration = av_dict_get(s->metadata, "DURATION", NULL, 0);
    1826           9 :     if (explicitDuration && (av_parse_time(&us, explicitDuration->value, 1) == 0) && us > 0) {
    1827           0 :         av_log(s, AV_LOG_DEBUG, "get_metadata_duration found duration in context metadata: %" PRId64 "\n", us);
    1828           0 :         return us;
    1829             :     }
    1830             : 
    1831          21 :     for (i = 0; i < s->nb_streams; i++) {
    1832             :         int64_t us;
    1833          12 :         AVDictionaryEntry *duration = av_dict_get(s->streams[i]->metadata, "DURATION", NULL, 0);
    1834             : 
    1835          12 :         if (duration && (av_parse_time(&us, duration->value, 1) == 0))
    1836           0 :             max = FFMAX(max, us);
    1837             :     }
    1838             : 
    1839           9 :     av_log(s, AV_LOG_DEBUG, "get_metadata_duration returned: %" PRId64 "\n", max);
    1840           9 :     return max;
    1841             : }
    1842             : 
    1843          13 : static int mkv_write_header(AVFormatContext *s)
    1844             : {
    1845          13 :     MatroskaMuxContext *mkv = s->priv_data;
    1846          13 :     AVIOContext *pb = s->pb;
    1847             :     ebml_master ebml_header;
    1848             :     AVDictionaryEntry *tag;
    1849          13 :     int ret, i, version = 2;
    1850             :     int64_t creation_time;
    1851             : 
    1852          13 :     if (!strcmp(s->oformat->name, "webm"))
    1853           0 :         mkv->mode = MODE_WEBM;
    1854             :     else
    1855          13 :         mkv->mode = MODE_MATROSKAv2;
    1856             : 
    1857          13 :     if (mkv->mode != MODE_WEBM ||
    1858           0 :         av_dict_get(s->metadata, "stereo_mode", NULL, 0) ||
    1859           0 :         av_dict_get(s->metadata, "alpha_mode", NULL, 0))
    1860          13 :         version = 4;
    1861             : 
    1862          29 :     for (i = 0; i < s->nb_streams; i++) {
    1863          32 :         if (s->streams[i]->codecpar->codec_id == AV_CODEC_ID_OPUS ||
    1864          32 :             av_dict_get(s->streams[i]->metadata, "stereo_mode", NULL, 0) ||
    1865          16 :             av_dict_get(s->streams[i]->metadata, "alpha_mode", NULL, 0))
    1866           0 :             version = 4;
    1867             :     }
    1868             : 
    1869          13 :     mkv->tracks = av_mallocz_array(s->nb_streams, sizeof(*mkv->tracks));
    1870          13 :     if (!mkv->tracks) {
    1871           0 :         ret = AVERROR(ENOMEM);
    1872           0 :         goto fail;
    1873             :     }
    1874          13 :     ebml_header = start_ebml_master(pb, EBML_ID_HEADER, 0);
    1875          13 :     put_ebml_uint   (pb, EBML_ID_EBMLVERSION        ,           1);
    1876          13 :     put_ebml_uint   (pb, EBML_ID_EBMLREADVERSION    ,           1);
    1877          13 :     put_ebml_uint   (pb, EBML_ID_EBMLMAXIDLENGTH    ,           4);
    1878          13 :     put_ebml_uint   (pb, EBML_ID_EBMLMAXSIZELENGTH  ,           8);
    1879          13 :     put_ebml_string (pb, EBML_ID_DOCTYPE            , s->oformat->name);
    1880          13 :     put_ebml_uint   (pb, EBML_ID_DOCTYPEVERSION     ,     version);
    1881          13 :     put_ebml_uint   (pb, EBML_ID_DOCTYPEREADVERSION ,           2);
    1882          13 :     end_ebml_master(pb, ebml_header);
    1883             : 
    1884          13 :     mkv->segment = start_ebml_master(pb, MATROSKA_ID_SEGMENT, 0);
    1885          13 :     mkv->segment_offset = avio_tell(pb);
    1886             : 
    1887             :     // we write 2 seek heads - one at the end of the file to point to each
    1888             :     // cluster, and one at the beginning to point to all other level one
    1889             :     // elements (including the seek head at the end of the file), which
    1890             :     // isn't more than 10 elements if we only write one of each other
    1891             :     // currently defined level 1 element
    1892          13 :     mkv->main_seekhead    = mkv_start_seekhead(pb, mkv->segment_offset, 10);
    1893          13 :     if (!mkv->main_seekhead) {
    1894           0 :         ret = AVERROR(ENOMEM);
    1895           0 :         goto fail;
    1896             :     }
    1897             : 
    1898          13 :     ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_INFO, avio_tell(pb));
    1899          13 :     if (ret < 0) goto fail;
    1900             : 
    1901          13 :     ret = start_ebml_master_crc32(pb, &mkv->info_bc, mkv, &mkv->info, MATROSKA_ID_INFO, 0);
    1902          13 :     if (ret < 0)
    1903           0 :         return ret;
    1904          13 :     pb = mkv->info_bc;
    1905             : 
    1906          13 :     put_ebml_uint(pb, MATROSKA_ID_TIMECODESCALE, 1000000);
    1907          13 :     if ((tag = av_dict_get(s->metadata, "title", NULL, 0)))
    1908           3 :         put_ebml_string(pb, MATROSKA_ID_TITLE, tag->value);
    1909          13 :     if (!(s->flags & AVFMT_FLAG_BITEXACT)) {
    1910           4 :         put_ebml_string(pb, MATROSKA_ID_MUXINGAPP, LIBAVFORMAT_IDENT);
    1911           4 :         if ((tag = av_dict_get(s->metadata, "encoding_tool", NULL, 0)))
    1912           0 :             put_ebml_string(pb, MATROSKA_ID_WRITINGAPP, tag->value);
    1913             :         else
    1914           4 :             put_ebml_string(pb, MATROSKA_ID_WRITINGAPP, LIBAVFORMAT_IDENT);
    1915             : 
    1916           4 :         if (mkv->mode != MODE_WEBM) {
    1917             :             uint32_t segment_uid[4];
    1918             :             AVLFG lfg;
    1919             : 
    1920           4 :             av_lfg_init(&lfg, av_get_random_seed());
    1921             : 
    1922          20 :             for (i = 0; i < 4; i++)
    1923          16 :                 segment_uid[i] = av_lfg_get(&lfg);
    1924             : 
    1925           4 :             put_ebml_binary(pb, MATROSKA_ID_SEGMENTUID, segment_uid, 16);
    1926             :         }
    1927             :     } else {
    1928           9 :         const char *ident = "Lavf";
    1929           9 :         put_ebml_string(pb, MATROSKA_ID_MUXINGAPP , ident);
    1930           9 :         put_ebml_string(pb, MATROSKA_ID_WRITINGAPP, ident);
    1931             :     }
    1932             : 
    1933          13 :     if (ff_parse_creation_time_metadata(s, &creation_time, 0) > 0) {
    1934             :         // Adjust time so it's relative to 2001-01-01 and convert to nanoseconds.
    1935           0 :         int64_t date_utc = (creation_time - 978307200000000LL) * 1000;
    1936             :         uint8_t date_utc_buf[8];
    1937           0 :         AV_WB64(date_utc_buf, date_utc);
    1938           0 :         put_ebml_binary(pb, MATROSKA_ID_DATEUTC, date_utc_buf, 8);
    1939             :     }
    1940             : 
    1941             :     // reserve space for the duration
    1942          13 :     mkv->duration = 0;
    1943          13 :     mkv->duration_offset = avio_tell(pb);
    1944          13 :     if (!mkv->is_live) {
    1945           9 :         int64_t metadata_duration = get_metadata_duration(s);
    1946             : 
    1947           9 :         if (s->duration > 0) {
    1948           3 :             int64_t scaledDuration = av_rescale(s->duration, 1000, AV_TIME_BASE);
    1949           3 :             put_ebml_float(pb, MATROSKA_ID_DURATION, scaledDuration);
    1950           3 :             av_log(s, AV_LOG_DEBUG, "Write early duration from recording time = %" PRIu64 "\n", scaledDuration);
    1951           6 :         } else if (metadata_duration > 0) {
    1952           0 :             int64_t scaledDuration = av_rescale(metadata_duration, 1000, AV_TIME_BASE);
    1953           0 :             put_ebml_float(pb, MATROSKA_ID_DURATION, scaledDuration);
    1954           0 :             av_log(s, AV_LOG_DEBUG, "Write early duration from metadata = %" PRIu64 "\n", scaledDuration);
    1955             :         } else {
    1956           6 :             put_ebml_void(pb, 11);              // assumes double-precision float to be written
    1957             :         }
    1958             :     }
    1959          13 :     if ((s->pb->seekable & AVIO_SEEKABLE_NORMAL) && !mkv->is_live)
    1960           5 :         end_ebml_master_crc32_preliminary(s->pb, &mkv->info_bc, mkv, mkv->info);
    1961             :     else
    1962           8 :         end_ebml_master_crc32(s->pb, &mkv->info_bc, mkv, mkv->info);
    1963          13 :     pb = s->pb;
    1964             : 
    1965             :     // initialize stream_duration fields
    1966          13 :     mkv->stream_durations = av_mallocz(s->nb_streams * sizeof(int64_t));
    1967          13 :     mkv->stream_duration_offsets = av_mallocz(s->nb_streams * sizeof(int64_t));
    1968          13 :     if (!mkv->stream_durations || !mkv->stream_duration_offsets) {
    1969           0 :         ret = AVERROR(ENOMEM);
    1970           0 :         goto fail;
    1971             :     }
    1972             : 
    1973          13 :     ret = mkv_write_tracks(s);
    1974          13 :     if (ret < 0)
    1975           0 :         goto fail;
    1976             : 
    1977          13 :     for (i = 0; i < s->nb_chapters; i++)
    1978           0 :         mkv->chapter_id_offset = FFMAX(mkv->chapter_id_offset, 1LL - s->chapters[i]->id);
    1979             : 
    1980          13 :     ret = mkv_write_chapters(s);
    1981          13 :     if (ret < 0)
    1982           0 :         goto fail;
    1983             : 
    1984          13 :     if (mkv->mode != MODE_WEBM) {
    1985          13 :         ret = mkv_write_attachments(s);
    1986          13 :         if (ret < 0)
    1987           0 :             goto fail;
    1988             :     }
    1989             : 
    1990          13 :     ret = mkv_write_tags(s);
    1991          13 :     if (ret < 0)
    1992           0 :         goto fail;
    1993             : 
    1994          13 :     if (!(s->pb->seekable & AVIO_SEEKABLE_NORMAL) && !mkv->is_live)
    1995           4 :         mkv_write_seekhead(pb, mkv);
    1996             : 
    1997          13 :     mkv->cues = mkv_start_cues(mkv->segment_offset);
    1998          13 :     if (!mkv->cues) {
    1999           0 :         ret = AVERROR(ENOMEM);
    2000           0 :         goto fail;
    2001             :     }
    2002          13 :     if ((pb->seekable & AVIO_SEEKABLE_NORMAL) && mkv->reserve_cues_space) {
    2003           0 :         mkv->cues_pos = avio_tell(pb);
    2004           0 :         put_ebml_void(pb, mkv->reserve_cues_space);
    2005             :     }
    2006             : 
    2007          13 :     av_init_packet(&mkv->cur_audio_pkt);
    2008          13 :     mkv->cur_audio_pkt.size = 0;
    2009          13 :     mkv->cluster_pos = -1;
    2010             : 
    2011          13 :     avio_flush(pb);
    2012             : 
    2013             :     // start a new cluster every 5 MB or 5 sec, or 32k / 1 sec for streaming or
    2014             :     // after 4k and on a keyframe
    2015          13 :     if (pb->seekable & AVIO_SEEKABLE_NORMAL) {
    2016           8 :         if (mkv->cluster_time_limit < 0)
    2017           8 :             mkv->cluster_time_limit = 5000;
    2018           8 :         if (mkv->cluster_size_limit < 0)
    2019           8 :             mkv->cluster_size_limit = 5 * 1024 * 1024;
    2020             :     } else {
    2021           5 :         if (mkv->cluster_time_limit < 0)
    2022           5 :             mkv->cluster_time_limit = 1000;
    2023           5 :         if (mkv->cluster_size_limit < 0)
    2024           5 :             mkv->cluster_size_limit = 32 * 1024;
    2025             :     }
    2026             : 
    2027          13 :     return 0;
    2028           0 : fail:
    2029           0 :     mkv_free(mkv);
    2030           0 :     return ret;
    2031             : }
    2032             : 
    2033           8 : static int mkv_blockgroup_size(int pkt_size)
    2034             : {
    2035           8 :     int size = pkt_size + 4;
    2036           8 :     size += ebml_num_size(size);
    2037           8 :     size += 2;              // EBML ID for block and block duration
    2038           8 :     size += 8;              // max size of block duration
    2039           8 :     size += ebml_num_size(size);
    2040           8 :     size += 1;              // blockgroup EBML ID
    2041           8 :     return size;
    2042             : }
    2043             : 
    2044          38 : static int mkv_strip_wavpack(const uint8_t *src, uint8_t **pdst, int *size)
    2045             : {
    2046             :     uint8_t *dst;
    2047          38 :     int srclen = *size;
    2048          38 :     int offset = 0;
    2049             :     int ret;
    2050             : 
    2051          38 :     dst = av_malloc(srclen);
    2052          38 :     if (!dst)
    2053           0 :         return AVERROR(ENOMEM);
    2054             : 
    2055         170 :     while (srclen >= WV_HEADER_SIZE) {
    2056             :         WvHeader header;
    2057             : 
    2058          94 :         ret = ff_wv_parse_header(&header, src);
    2059          94 :         if (ret < 0)
    2060           0 :             goto fail;
    2061          94 :         src    += WV_HEADER_SIZE;
    2062          94 :         srclen -= WV_HEADER_SIZE;
    2063             : 
    2064          94 :         if (srclen < header.blocksize) {
    2065           0 :             ret = AVERROR_INVALIDDATA;
    2066           0 :             goto fail;
    2067             :         }
    2068             : 
    2069          94 :         if (header.initial) {
    2070          38 :             AV_WL32(dst + offset, header.samples);
    2071          38 :             offset += 4;
    2072             :         }
    2073          94 :         AV_WL32(dst + offset,     header.flags);
    2074          94 :         AV_WL32(dst + offset + 4, header.crc);
    2075          94 :         offset += 8;
    2076             : 
    2077          94 :         if (!(header.initial && header.final)) {
    2078          70 :             AV_WL32(dst + offset, header.blocksize);
    2079          70 :             offset += 4;
    2080             :         }
    2081             : 
    2082          94 :         memcpy(dst + offset, src, header.blocksize);
    2083          94 :         src    += header.blocksize;
    2084          94 :         srclen -= header.blocksize;
    2085          94 :         offset += header.blocksize;
    2086             :     }
    2087             : 
    2088          38 :     *pdst = dst;
    2089          38 :     *size = offset;
    2090             : 
    2091          38 :     return 0;
    2092           0 : fail:
    2093           0 :     av_freep(&dst);
    2094           0 :     return ret;
    2095             : }
    2096             : 
    2097         328 : static void mkv_write_block(AVFormatContext *s, AVIOContext *pb,
    2098             :                             unsigned int blockid, AVPacket *pkt, int keyframe)
    2099             : {
    2100         328 :     MatroskaMuxContext *mkv = s->priv_data;
    2101         328 :     AVCodecParameters *par = s->streams[pkt->stream_index]->codecpar;
    2102         328 :     uint8_t *data = NULL, *side_data = NULL;
    2103         328 :     int offset = 0, size = pkt->size, side_data_size = 0;
    2104         328 :     int64_t ts = mkv->tracks[pkt->stream_index].write_dts ? pkt->dts : pkt->pts;
    2105         328 :     uint64_t additional_id = 0;
    2106         328 :     int64_t discard_padding = 0;
    2107         328 :     uint8_t track_number = (mkv->is_dash ? mkv->dash_track_number : (pkt->stream_index + 1));
    2108             :     ebml_master block_group, block_additions, block_more;
    2109             : 
    2110         328 :     ts += mkv->tracks[pkt->stream_index].ts_offset;
    2111             : 
    2112         328 :     av_log(s, AV_LOG_DEBUG, "Writing block at offset %" PRIu64 ", size %d, "
    2113             :            "pts %" PRId64 ", dts %" PRId64 ", duration %" PRId64 ", keyframe %d\n",
    2114             :            avio_tell(pb), pkt->size, pkt->pts, pkt->dts, pkt->duration,
    2115             :            keyframe != 0);
    2116         328 :     if (par->codec_id == AV_CODEC_ID_H264 && par->extradata_size > 0 &&
    2117           0 :         (AV_RB24(par->extradata) == 1 || AV_RB32(par->extradata) == 1))
    2118           0 :         ff_avc_parse_nal_units_buf(pkt->data, &data, &size);
    2119         328 :     else if (par->codec_id == AV_CODEC_ID_HEVC && par->extradata_size > 6 &&
    2120           0 :              (AV_RB24(par->extradata) == 1 || AV_RB32(par->extradata) == 1))
    2121             :         /* extradata is Annex B, assume the bitstream is too and convert it */
    2122           0 :         ff_hevc_annexb2mp4_buf(pkt->data, &data, &size, 0, NULL);
    2123         328 :     else if (par->codec_id == AV_CODEC_ID_WAVPACK) {
    2124          38 :         int ret = mkv_strip_wavpack(pkt->data, &data, &size);
    2125          38 :         if (ret < 0) {
    2126           0 :             av_log(s, AV_LOG_ERROR, "Error stripping a WavPack packet.\n");
    2127           0 :             return;
    2128             :         }
    2129             :     } else
    2130         290 :         data = pkt->data;
    2131             : 
    2132         328 :     if (par->codec_id == AV_CODEC_ID_PRORES && size >= 8) {
    2133             :         /* Matroska specification requires to remove the first QuickTime atom
    2134             :          */
    2135           0 :         size  -= 8;
    2136           0 :         offset = 8;
    2137             :     }
    2138             : 
    2139         328 :     side_data = av_packet_get_side_data(pkt,
    2140             :                                         AV_PKT_DATA_SKIP_SAMPLES,
    2141             :                                         &side_data_size);
    2142             : 
    2143         328 :     if (side_data && side_data_size >= 10) {
    2144           2 :         discard_padding = av_rescale_q(AV_RL32(side_data + 4),
    2145           2 :                                        (AVRational){1, par->sample_rate},
    2146           2 :                                        (AVRational){1, 1000000000});
    2147             :     }
    2148             : 
    2149         328 :     side_data = av_packet_get_side_data(pkt,
    2150             :                                         AV_PKT_DATA_MATROSKA_BLOCKADDITIONAL,
    2151             :                                         &side_data_size);
    2152         328 :     if (side_data) {
    2153           0 :         additional_id = AV_RB64(side_data);
    2154           0 :         side_data += 8;
    2155           0 :         side_data_size -= 8;
    2156             :     }
    2157             : 
    2158         328 :     if ((side_data_size && additional_id == 1) || discard_padding) {
    2159           0 :         block_group = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP, 0);
    2160           0 :         blockid = MATROSKA_ID_BLOCK;
    2161             :     }
    2162             : 
    2163         328 :     put_ebml_id(pb, blockid);
    2164         328 :     put_ebml_num(pb, size + 4, 0);
    2165             :     // this assumes stream_index is less than 126
    2166         328 :     avio_w8(pb, 0x80 | track_number);
    2167         328 :     avio_wb16(pb, ts - mkv->cluster_pts);
    2168         328 :     avio_w8(pb, (blockid == MATROSKA_ID_SIMPLEBLOCK && keyframe) ? (1 << 7) : 0);
    2169         328 :     avio_write(pb, data + offset, size);
    2170         328 :     if (data != pkt->data)
    2171          38 :         av_free(data);
    2172             : 
    2173         328 :     if (blockid == MATROSKA_ID_BLOCK && !keyframe) {
    2174           0 :         put_ebml_sint(pb, MATROSKA_ID_BLOCKREFERENCE,
    2175           0 :                       mkv->last_track_timestamp[track_number - 1]);
    2176             :     }
    2177         328 :     mkv->last_track_timestamp[track_number - 1] = ts - mkv->cluster_pts;
    2178             : 
    2179         328 :     if (discard_padding) {
    2180           0 :         put_ebml_sint(pb, MATROSKA_ID_DISCARDPADDING, discard_padding);
    2181             :     }
    2182             : 
    2183         328 :     if (side_data_size && additional_id == 1) {
    2184           0 :         block_additions = start_ebml_master(pb, MATROSKA_ID_BLOCKADDITIONS, 0);
    2185           0 :         block_more = start_ebml_master(pb, MATROSKA_ID_BLOCKMORE, 0);
    2186           0 :         put_ebml_uint(pb, MATROSKA_ID_BLOCKADDID, 1);
    2187           0 :         put_ebml_id(pb, MATROSKA_ID_BLOCKADDITIONAL);
    2188           0 :         put_ebml_num(pb, side_data_size, 0);
    2189           0 :         avio_write(pb, side_data, side_data_size);
    2190           0 :         end_ebml_master(pb, block_more);
    2191           0 :         end_ebml_master(pb, block_additions);
    2192             :     }
    2193         328 :     if ((side_data_size && additional_id == 1) || discard_padding) {
    2194           0 :         end_ebml_master(pb, block_group);
    2195             :     }
    2196             : }
    2197             : 
    2198           0 : static int mkv_write_vtt_blocks(AVFormatContext *s, AVIOContext *pb, AVPacket *pkt)
    2199             : {
    2200           0 :     MatroskaMuxContext *mkv = s->priv_data;
    2201             :     ebml_master blockgroup;
    2202             :     int id_size, settings_size, size;
    2203             :     uint8_t *id, *settings;
    2204           0 :     int64_t ts = mkv->tracks[pkt->stream_index].write_dts ? pkt->dts : pkt->pts;
    2205           0 :     const int flags = 0;
    2206             : 
    2207           0 :     id_size = 0;
    2208           0 :     id = av_packet_get_side_data(pkt, AV_PKT_DATA_WEBVTT_IDENTIFIER,
    2209             :                                  &id_size);
    2210             : 
    2211           0 :     settings_size = 0;
    2212           0 :     settings = av_packet_get_side_data(pkt, AV_PKT_DATA_WEBVTT_SETTINGS,
    2213             :                                        &settings_size);
    2214             : 
    2215           0 :     size = id_size + 1 + settings_size + 1 + pkt->size;
    2216             : 
    2217           0 :     av_log(s, AV_LOG_DEBUG, "Writing block at offset %" PRIu64 ", size %d, "
    2218             :            "pts %" PRId64 ", dts %" PRId64 ", duration %" PRId64 ", flags %d\n",
    2219             :            avio_tell(pb), size, pkt->pts, pkt->dts, pkt->duration, flags);
    2220             : 
    2221           0 :     blockgroup = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP, mkv_blockgroup_size(size));
    2222             : 
    2223           0 :     put_ebml_id(pb, MATROSKA_ID_BLOCK);
    2224           0 :     put_ebml_num(pb, size + 4, 0);
    2225           0 :     avio_w8(pb, 0x80 | (pkt->stream_index + 1));     // this assumes stream_index is less than 126
    2226           0 :     avio_wb16(pb, ts - mkv->cluster_pts);
    2227           0 :     avio_w8(pb, flags);
    2228           0 :     avio_printf(pb, "%.*s\n%.*s\n%.*s", id_size, id, settings_size, settings, pkt->size, pkt->data);
    2229             : 
    2230           0 :     put_ebml_uint(pb, MATROSKA_ID_BLOCKDURATION, pkt->duration);
    2231           0 :     end_ebml_master(pb, blockgroup);
    2232             : 
    2233           0 :     return pkt->duration;
    2234             : }
    2235             : 
    2236          41 : static void mkv_start_new_cluster(AVFormatContext *s, AVPacket *pkt)
    2237             : {
    2238          41 :     MatroskaMuxContext *mkv = s->priv_data;
    2239             : 
    2240          41 :     end_ebml_master_crc32(s->pb, &mkv->dyn_bc, mkv, mkv->cluster);
    2241          41 :     mkv->cluster_pos = -1;
    2242          41 :     if (s->pb->seekable & AVIO_SEEKABLE_NORMAL)
    2243           4 :         av_log(s, AV_LOG_DEBUG,
    2244             :                "Starting new cluster at offset %" PRIu64 " bytes, "
    2245             :                "pts %" PRIu64 "dts %" PRIu64 "\n",
    2246             :                avio_tell(s->pb), pkt->pts, pkt->dts);
    2247             :     else
    2248          37 :         av_log(s, AV_LOG_DEBUG, "Starting new cluster, "
    2249             :                "pts %" PRIu64 "dts %" PRIu64 "\n",
    2250             :                pkt->pts, pkt->dts);
    2251          41 :     avio_flush(s->pb);
    2252          41 : }
    2253             : 
    2254         328 : static int mkv_check_new_extra_data(AVFormatContext *s, AVPacket *pkt)
    2255             : {
    2256         328 :     MatroskaMuxContext *mkv = s->priv_data;
    2257         328 :     mkv_track *track        = &mkv->tracks[pkt->stream_index];
    2258         328 :     AVCodecParameters *par  = s->streams[pkt->stream_index]->codecpar;
    2259             :     uint8_t *side_data;
    2260         328 :     int side_data_size = 0, ret;
    2261             : 
    2262         328 :     side_data = av_packet_get_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA,
    2263             :                                         &side_data_size);
    2264             : 
    2265         328 :     switch (par->codec_id) {
    2266         102 :     case AV_CODEC_ID_AAC:
    2267         103 :         if (side_data_size && (s->pb->seekable & AVIO_SEEKABLE_NORMAL) && !mkv->is_live) {
    2268           1 :             int filler, output_sample_rate = 0;
    2269             :             int64_t curpos;
    2270           1 :             ret = get_aac_sample_rates(s, side_data, side_data_size, &track->sample_rate,
    2271             :                                        &output_sample_rate);
    2272           1 :             if (ret < 0)
    2273           0 :                 return ret;
    2274           1 :             if (!output_sample_rate)
    2275           1 :                 output_sample_rate = track->sample_rate; // Space is already reserved, so it's this or a void element.
    2276           1 :             av_freep(&par->extradata);
    2277           1 :             ret = ff_alloc_extradata(par, side_data_size);
    2278           1 :             if (ret < 0)
    2279           0 :                 return ret;
    2280           1 :             memcpy(par->extradata, side_data, side_data_size);
    2281           1 :             curpos = avio_tell(mkv->tracks_bc);
    2282           1 :             avio_seek(mkv->tracks_bc, track->codecpriv_offset, SEEK_SET);
    2283           1 :             mkv_write_codecprivate(s, mkv->tracks_bc, par, 1, 0);
    2284           1 :             filler = MAX_PCE_SIZE + 2 + 4 - (avio_tell(mkv->tracks_bc) - track->codecpriv_offset);
    2285           1 :             if (filler)
    2286           1 :                 put_ebml_void(mkv->tracks_bc, filler);
    2287           1 :             avio_seek(mkv->tracks_bc, track->sample_rate_offset, SEEK_SET);
    2288           1 :             put_ebml_float(mkv->tracks_bc, MATROSKA_ID_AUDIOSAMPLINGFREQ, track->sample_rate);
    2289           1 :             put_ebml_float(mkv->tracks_bc, MATROSKA_ID_AUDIOOUTSAMPLINGFREQ, output_sample_rate);
    2290           1 :             avio_seek(mkv->tracks_bc, curpos, SEEK_SET);
    2291         101 :         } else if (!par->extradata_size && !track->sample_rate) {
    2292             :             // No extradata (codecpar or packet side data).
    2293           0 :             av_log(s, AV_LOG_ERROR, "Error parsing AAC extradata, unable to determine samplerate.\n");
    2294           0 :             return AVERROR(EINVAL);
    2295             :         }
    2296         102 :         break;
    2297           0 :     case AV_CODEC_ID_FLAC:
    2298           0 :         if (side_data_size && (s->pb->seekable & AVIO_SEEKABLE_NORMAL) && !mkv->is_live) {
    2299             :             AVCodecParameters *codecpriv_par;
    2300             :             int64_t curpos;
    2301           0 :             if (side_data_size != par->extradata_size) {
    2302           0 :                 av_log(s, AV_LOG_ERROR, "Invalid FLAC STREAMINFO metadata for output stream %d\n",
    2303             :                        pkt->stream_index);
    2304           0 :                 return AVERROR(EINVAL);
    2305             :             }
    2306           0 :             codecpriv_par = avcodec_parameters_alloc();
    2307           0 :             if (!codecpriv_par)
    2308           0 :                 return AVERROR(ENOMEM);
    2309           0 :             ret = avcodec_parameters_copy(codecpriv_par, par);
    2310           0 :             if (ret < 0) {
    2311           0 :                 avcodec_parameters_free(&codecpriv_par);
    2312           0 :                 return ret;
    2313             :             }
    2314           0 :             memcpy(codecpriv_par->extradata, side_data, side_data_size);
    2315           0 :             curpos = avio_tell(mkv->tracks_bc);
    2316           0 :             avio_seek(mkv->tracks_bc, track->codecpriv_offset, SEEK_SET);
    2317           0 :             mkv_write_codecprivate(s, mkv->tracks_bc, codecpriv_par, 1, 0);
    2318           0 :             avio_seek(mkv->tracks_bc, curpos, SEEK_SET);
    2319           0 :             avcodec_parameters_free(&codecpriv_par);
    2320             :         }
    2321           0 :         break;
    2322         226 :     default:
    2323         226 :         if (side_data_size)
    2324           0 :             av_log(s, AV_LOG_DEBUG, "Ignoring new extradata in a packet for stream %d.\n", pkt->stream_index);
    2325         226 :         break;
    2326             :     }
    2327             : 
    2328         328 :     return 0;
    2329             : }
    2330             : 
    2331         328 : static int mkv_write_packet_internal(AVFormatContext *s, AVPacket *pkt, int add_cue)
    2332             : {
    2333         328 :     MatroskaMuxContext *mkv = s->priv_data;
    2334         328 :     AVIOContext *pb         = s->pb;
    2335         328 :     AVCodecParameters *par  = s->streams[pkt->stream_index]->codecpar;
    2336         328 :     int keyframe            = !!(pkt->flags & AV_PKT_FLAG_KEY);
    2337         328 :     int duration            = pkt->duration;
    2338             :     int ret;
    2339         328 :     int64_t ts = mkv->tracks[pkt->stream_index].write_dts ? pkt->dts : pkt->pts;
    2340             :     int64_t relative_packet_pos;
    2341         328 :     int dash_tracknum = mkv->is_dash ? mkv->dash_track_number : pkt->stream_index + 1;
    2342             : 
    2343         328 :     if (ts == AV_NOPTS_VALUE) {
    2344           0 :         av_log(s, AV_LOG_ERROR, "Can't write packet with unknown timestamp\n");
    2345           0 :         return AVERROR(EINVAL);
    2346             :     }
    2347         328 :     ts += mkv->tracks[pkt->stream_index].ts_offset;
    2348             : 
    2349         328 :     if (mkv->cluster_pos != -1) {
    2350         268 :         int64_t cluster_time = ts - mkv->cluster_pts + mkv->tracks[pkt->stream_index].ts_offset;
    2351         268 :         if ((int16_t)cluster_time != cluster_time) {
    2352           0 :             av_log(s, AV_LOG_WARNING, "Starting new cluster due to timestamp\n");
    2353           0 :             mkv_start_new_cluster(s, pkt);
    2354             :         }
    2355             :     }
    2356             : 
    2357         328 :     if (mkv->cluster_pos == -1) {
    2358          60 :         mkv->cluster_pos = avio_tell(s->pb);
    2359          60 :         ret = start_ebml_master_crc32(s->pb, &mkv->dyn_bc, mkv, &mkv->cluster, MATROSKA_ID_CLUSTER, 0);
    2360          60 :         if (ret < 0)
    2361           0 :             return ret;
    2362          60 :         put_ebml_uint(mkv->dyn_bc, MATROSKA_ID_CLUSTERTIMECODE, FFMAX(0, ts));
    2363          60 :         mkv->cluster_pts = FFMAX(0, ts);
    2364             :     }
    2365         328 :     pb = mkv->dyn_bc;
    2366             : 
    2367         328 :     relative_packet_pos = avio_tell(pb);
    2368             : 
    2369         328 :     if (par->codec_type != AVMEDIA_TYPE_SUBTITLE) {
    2370         320 :         mkv_write_block(s, pb, MATROSKA_ID_SIMPLEBLOCK, pkt, keyframe);
    2371         320 :         if ((s->pb->seekable & AVIO_SEEKABLE_NORMAL) && (par->codec_type == AVMEDIA_TYPE_VIDEO && keyframe || add_cue)) {
    2372           7 :             ret = mkv_add_cuepoint(mkv->cues, pkt->stream_index, dash_tracknum, ts, mkv->cluster_pos, relative_packet_pos, -1);
    2373           7 :             if (ret < 0) return ret;
    2374             :         }
    2375             :     } else {
    2376           8 :         if (par->codec_id == AV_CODEC_ID_WEBVTT) {
    2377           0 :             duration = mkv_write_vtt_blocks(s, pb, pkt);
    2378             :         } else {
    2379           8 :             ebml_master blockgroup = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP,
    2380           8 :                                                        mkv_blockgroup_size(pkt->size));
    2381             : 
    2382             : #if FF_API_CONVERGENCE_DURATION
    2383             : FF_DISABLE_DEPRECATION_WARNINGS
    2384             :             /* For backward compatibility, prefer convergence_duration. */
    2385           8 :             if (pkt->convergence_duration > 0) {
    2386           0 :                 duration = pkt->convergence_duration;
    2387             :             }
    2388             : FF_ENABLE_DEPRECATION_WARNINGS
    2389             : #endif
    2390             :             /* All subtitle blocks are considered to be keyframes. */
    2391           8 :             mkv_write_block(s, pb, MATROSKA_ID_BLOCK, pkt, 1);
    2392           8 :             put_ebml_uint(pb, MATROSKA_ID_BLOCKDURATION, duration);
    2393           8 :             end_ebml_master(pb, blockgroup);
    2394             :         }
    2395             : 
    2396           8 :         if (s->pb->seekable & AVIO_SEEKABLE_NORMAL) {
    2397           0 :             ret = mkv_add_cuepoint(mkv->cues, pkt->stream_index, dash_tracknum, ts,
    2398             :                                    mkv->cluster_pos, relative_packet_pos, duration);
    2399           0 :             if (ret < 0)
    2400           0 :                 return ret;
    2401             :         }
    2402             :     }
    2403             : 
    2404         328 :     mkv->duration = FFMAX(mkv->duration, ts + duration);
    2405             : 
    2406         328 :     if (mkv->stream_durations)
    2407         656 :         mkv->stream_durations[pkt->stream_index] =
    2408         656 :             FFMAX(mkv->stream_durations[pkt->stream_index], ts + duration);
    2409             : 
    2410         328 :     return 0;
    2411             : }
    2412             : 
    2413         328 : static int mkv_write_packet(AVFormatContext *s, AVPacket *pkt)
    2414             : {
    2415         328 :     MatroskaMuxContext *mkv = s->priv_data;
    2416         328 :     int codec_type          = s->streams[pkt->stream_index]->codecpar->codec_type;
    2417         328 :     int keyframe            = !!(pkt->flags & AV_PKT_FLAG_KEY);
    2418             :     int cluster_size;
    2419             :     int64_t cluster_time;
    2420             :     int ret;
    2421             :     int start_new_cluster;
    2422             : 
    2423         328 :     ret = mkv_check_new_extra_data(s, pkt);
    2424         328 :     if (ret < 0)
    2425           0 :         return ret;
    2426             : 
    2427         328 :     if (mkv->tracks[pkt->stream_index].write_dts)
    2428           1 :         cluster_time = pkt->dts - mkv->cluster_pts;
    2429             :     else
    2430         327 :         cluster_time = pkt->pts - mkv->cluster_pts;
    2431         328 :     cluster_time += mkv->tracks[pkt->stream_index].ts_offset;
    2432             : 
    2433             :     // start a new cluster every 5 MB or 5 sec, or 32k / 1 sec for streaming or
    2434             :     // after 4k and on a keyframe
    2435         328 :     cluster_size = avio_tell(mkv->dyn_bc);
    2436             : 
    2437         328 :     if (mkv->is_dash && codec_type == AVMEDIA_TYPE_VIDEO) {
    2438             :         // WebM DASH specification states that the first block of every cluster
    2439             :         // has to be a key frame. So for DASH video, we only create a cluster
    2440             :         // on seeing key frames.
    2441           0 :         start_new_cluster = keyframe;
    2442         328 :     } else if (mkv->is_dash && codec_type == AVMEDIA_TYPE_AUDIO &&
    2443           0 :                (mkv->cluster_pos == -1 ||
    2444           0 :                 cluster_time > mkv->cluster_time_limit)) {
    2445             :         // For DASH audio, we create a Cluster based on cluster_time_limit
    2446           0 :         start_new_cluster = 1;
    2447         656 :     } else if (!mkv->is_dash &&
    2448         626 :                (cluster_size > mkv->cluster_size_limit ||
    2449         587 :                 cluster_time > mkv->cluster_time_limit ||
    2450         100 :                 (codec_type == AVMEDIA_TYPE_VIDEO && keyframe &&
    2451             :                  cluster_size > 4 * 1024))) {
    2452          43 :         start_new_cluster = 1;
    2453             :     } else {
    2454         285 :         start_new_cluster = 0;
    2455             :     }
    2456             : 
    2457         328 :     if (mkv->cluster_pos != -1 && start_new_cluster) {
    2458          41 :         mkv_start_new_cluster(s, pkt);
    2459             :     }
    2460             : 
    2461         328 :     if (!mkv->cluster_pos)
    2462          87 :         avio_write_marker(s->pb,
    2463          29 :                           av_rescale_q(pkt->dts, s->streams[pkt->stream_index]->time_base, AV_TIME_BASE_Q),
    2464          29 :                           keyframe && (mkv->have_video ? codec_type == AVMEDIA_TYPE_VIDEO : 1) ? AVIO_DATA_MARKER_SYNC_POINT : AVIO_DATA_MARKER_BOUNDARY_POINT);
    2465             : 
    2466             :     // check if we have an audio packet cached
    2467         328 :     if (mkv->cur_audio_pkt.size > 0) {
    2468             :         // for DASH audio, a CuePoint has to be added when there is a new cluster.
    2469         209 :         ret = mkv_write_packet_internal(s, &mkv->cur_audio_pkt,
    2470         209 :                                         mkv->is_dash ? start_new_cluster : 0);
    2471         209 :         av_packet_unref(&mkv->cur_audio_pkt);
    2472         209 :         if (ret < 0) {
    2473           0 :             av_log(s, AV_LOG_ERROR,
    2474             :                    "Could not write cached audio packet ret:%d\n", ret);
    2475           0 :             return ret;
    2476             :         }
    2477             :     }
    2478             : 
    2479             :     // buffer an audio packet to ensure the packet containing the video
    2480             :     // keyframe's timecode is contained in the same cluster for WebM
    2481         328 :     if (codec_type == AVMEDIA_TYPE_AUDIO) {
    2482         219 :         ret = av_packet_ref(&mkv->cur_audio_pkt, pkt);
    2483             :     } else
    2484         109 :         ret = mkv_write_packet_internal(s, pkt, 0);
    2485         328 :     return ret;
    2486             : }
    2487             : 
    2488         335 : static int mkv_write_flush_packet(AVFormatContext *s, AVPacket *pkt)
    2489             : {
    2490         335 :     MatroskaMuxContext *mkv = s->priv_data;
    2491             : 
    2492         335 :     if (!pkt) {
    2493           7 :         if (mkv->cluster_pos != -1) {
    2494           6 :             end_ebml_master_crc32(s->pb, &mkv->dyn_bc, mkv, mkv->cluster);
    2495           6 :             mkv->cluster_pos = -1;
    2496           6 :             if (s->pb->seekable & AVIO_SEEKABLE_NORMAL)
    2497           3 :                 av_log(s, AV_LOG_DEBUG,
    2498             :                        "Flushing cluster at offset %" PRIu64 " bytes\n",
    2499             :                        avio_tell(s->pb));
    2500             :             else
    2501           3 :                 av_log(s, AV_LOG_DEBUG, "Flushing cluster\n");
    2502           6 :             avio_flush(s->pb);
    2503             :         }
    2504           7 :         return 1;
    2505             :     }
    2506         328 :     return mkv_write_packet(s, pkt);
    2507             : }
    2508             : 
    2509          13 : static int mkv_write_trailer(AVFormatContext *s)
    2510             : {
    2511          13 :     MatroskaMuxContext *mkv = s->priv_data;
    2512          13 :     AVIOContext *pb = s->pb;
    2513             :     int64_t currentpos, cuespos;
    2514             :     int ret;
    2515             : 
    2516             :     // check if we have an audio packet cached
    2517          13 :     if (mkv->cur_audio_pkt.size > 0) {
    2518          10 :         ret = mkv_write_packet_internal(s, &mkv->cur_audio_pkt, 0);
    2519          10 :         av_packet_unref(&mkv->cur_audio_pkt);
    2520          10 :         if (ret < 0) {
    2521           0 :             av_log(s, AV_LOG_ERROR,
    2522             :                    "Could not write cached audio packet ret:%d\n", ret);
    2523           0 :             return ret;
    2524             :         }
    2525             :     }
    2526             : 
    2527          13 :     if (mkv->dyn_bc) {
    2528          13 :         end_ebml_master_crc32(pb, &mkv->dyn_bc, mkv, mkv->cluster);
    2529             :     }
    2530             : 
    2531          13 :     ret = mkv_write_chapters(s);
    2532          13 :     if (ret < 0)
    2533           0 :         return ret;
    2534             : 
    2535             : 
    2536          13 :     if ((pb->seekable & AVIO_SEEKABLE_NORMAL) && !mkv->is_live) {
    2537           5 :         if (mkv->cues->num_entries) {
    2538           3 :             if (mkv->reserve_cues_space) {
    2539             :                 int64_t cues_end;
    2540             : 
    2541           0 :                 currentpos = avio_tell(pb);
    2542           0 :                 avio_seek(pb, mkv->cues_pos, SEEK_SET);
    2543             : 
    2544           0 :                 cuespos  = mkv_write_cues(s, mkv->cues, mkv->tracks, s->nb_streams);
    2545           0 :                 cues_end = avio_tell(pb);
    2546           0 :                 if (cues_end > cuespos + mkv->reserve_cues_space) {
    2547           0 :                     av_log(s, AV_LOG_ERROR,
    2548             :                            "Insufficient space reserved for cues: %d "
    2549             :                            "(needed: %" PRId64 ").\n",
    2550             :                            mkv->reserve_cues_space, cues_end - cuespos);
    2551           0 :                     return AVERROR(EINVAL);
    2552             :                 }
    2553             : 
    2554           0 :                 if (cues_end < cuespos + mkv->reserve_cues_space)
    2555           0 :                     put_ebml_void(pb, mkv->reserve_cues_space -
    2556           0 :                                   (cues_end - cuespos));
    2557             : 
    2558           0 :                 avio_seek(pb, currentpos, SEEK_SET);
    2559             :             } else {
    2560           3 :                 cuespos = mkv_write_cues(s, mkv->cues, mkv->tracks, s->nb_streams);
    2561             :             }
    2562             : 
    2563           3 :             ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_CUES,
    2564             :                                          cuespos);
    2565           3 :             if (ret < 0)
    2566           0 :                 return ret;
    2567             :         }
    2568             : 
    2569           5 :         mkv_write_seekhead(pb, mkv);
    2570             : 
    2571             :         // update the duration
    2572           5 :         av_log(s, AV_LOG_DEBUG, "end duration = %" PRIu64 "\n", mkv->duration);
    2573           5 :         currentpos = avio_tell(pb);
    2574           5 :         avio_seek(mkv->info_bc, mkv->duration_offset, SEEK_SET);
    2575           5 :         put_ebml_float(mkv->info_bc, MATROSKA_ID_DURATION, mkv->duration);
    2576           5 :         avio_seek(pb, mkv->info.pos, SEEK_SET);
    2577           5 :         end_ebml_master_crc32(pb, &mkv->info_bc, mkv, mkv->info);
    2578             : 
    2579             :         // write tracks master
    2580           5 :         avio_seek(pb, mkv->tracks_master.pos, SEEK_SET);
    2581           5 :         end_ebml_master_crc32(pb, &mkv->tracks_bc, mkv, mkv->tracks_master);
    2582             : 
    2583             :         // update stream durations
    2584           5 :         if (!mkv->is_live && mkv->stream_durations) {
    2585             :             int i;
    2586           5 :             int64_t curr = avio_tell(mkv->tags_bc);
    2587          13 :             for (i = 0; i < s->nb_streams; ++i) {
    2588           8 :                 AVStream *st = s->streams[i];
    2589             : 
    2590           8 :                 if (mkv->stream_duration_offsets[i] > 0) {
    2591           7 :                     double duration_sec = mkv->stream_durations[i] * av_q2d(st->time_base);
    2592           7 :                     char duration_string[20] = "";
    2593             : 
    2594           7 :                     av_log(s, AV_LOG_DEBUG, "stream %d end duration = %" PRIu64 "\n", i,
    2595           7 :                            mkv->stream_durations[i]);
    2596             : 
    2597           7 :                     avio_seek(mkv->tags_bc, mkv->stream_duration_offsets[i], SEEK_SET);
    2598             : 
    2599          21 :                     snprintf(duration_string, 20, "%02d:%02d:%012.9f",
    2600          14 :                              (int) duration_sec / 3600, ((int) duration_sec / 60) % 60,
    2601             :                              fmod(duration_sec, 60));
    2602             : 
    2603           7 :                     put_ebml_binary(mkv->tags_bc, MATROSKA_ID_TAGSTRING, duration_string, 20);
    2604             :                 }
    2605             :             }
    2606           5 :             avio_seek(mkv->tags_bc, curr, SEEK_SET);
    2607             :         }
    2608           5 :         if (mkv->tags.pos && !mkv->is_live) {
    2609           5 :             avio_seek(pb, mkv->tags.pos, SEEK_SET);
    2610           5 :             end_ebml_master_crc32(pb, &mkv->tags_bc, mkv, mkv->tags);
    2611             :         }
    2612             : 
    2613           5 :         avio_seek(pb, currentpos, SEEK_SET);
    2614             :     }
    2615             : 
    2616          13 :     if (!mkv->is_live) {
    2617           9 :         end_ebml_master(pb, mkv->segment);
    2618             :     }
    2619             : 
    2620          13 :     mkv_free(mkv);
    2621          13 :     return 0;
    2622             : }
    2623             : 
    2624           8 : static int mkv_query_codec(enum AVCodecID codec_id, int std_compliance)
    2625             : {
    2626             :     int i;
    2627         432 :     for (i = 0; ff_mkv_codec_tags[i].id != AV_CODEC_ID_NONE; i++)
    2628         432 :         if (ff_mkv_codec_tags[i].id == codec_id)
    2629           8 :             return 1;
    2630             : 
    2631           0 :     if (std_compliance < FF_COMPLIANCE_NORMAL) {
    2632           0 :         enum AVMediaType type = avcodec_get_type(codec_id);
    2633             :         // mkv theoretically supports any video/audio through VFW/ACM
    2634           0 :         if (type == AVMEDIA_TYPE_VIDEO || type == AVMEDIA_TYPE_AUDIO)
    2635           0 :             return 1;
    2636             :     }
    2637             : 
    2638           0 :     return 0;
    2639             : }
    2640             : 
    2641          13 : static int mkv_init(struct AVFormatContext *s)
    2642             : {
    2643             :     int i;
    2644             : 
    2645          13 :     if (s->nb_streams > MAX_TRACKS) {
    2646           0 :         av_log(s, AV_LOG_ERROR,
    2647             :                "At most %d streams are supported for muxing in Matroska\n",
    2648             :                MAX_TRACKS);
    2649           0 :         return AVERROR(EINVAL);
    2650             :     }
    2651             : 
    2652          29 :     for (i = 0; i < s->nb_streams; i++) {
    2653          32 :         if (s->streams[i]->codecpar->codec_id == AV_CODEC_ID_ATRAC3 ||
    2654          32 :             s->streams[i]->codecpar->codec_id == AV_CODEC_ID_COOK ||
    2655          32 :             s->streams[i]->codecpar->codec_id == AV_CODEC_ID_RA_288 ||
    2656          32 :             s->streams[i]->codecpar->codec_id == AV_CODEC_ID_SIPR ||
    2657          32 :             s->streams[i]->codecpar->codec_id == AV_CODEC_ID_RV10 ||
    2658          16 :             s->streams[i]->codecpar->codec_id == AV_CODEC_ID_RV20) {
    2659           0 :             av_log(s, AV_LOG_ERROR,
    2660             :                    "The Matroska muxer does not yet support muxing %s\n",
    2661           0 :                    avcodec_get_name(s->streams[i]->codecpar->codec_id));
    2662           0 :             return AVERROR_PATCHWELCOME;
    2663             :         }
    2664             :     }
    2665             : 
    2666          13 :     if (s->avoid_negative_ts < 0) {
    2667          13 :         s->avoid_negative_ts = 1;
    2668          13 :         s->internal->avoid_negative_ts_use_pts = 1;
    2669             :     }
    2670             : 
    2671          29 :     for (i = 0; i < s->nb_streams; i++) {
    2672             :         // ms precision is the de-facto standard timescale for mkv files
    2673          16 :         avpriv_set_pts_info(s->streams[i], 64, 1, 1000);
    2674             :     }
    2675             : 
    2676          13 :     return 0;
    2677             : }
    2678             : 
    2679          13 : static int mkv_check_bitstream(struct AVFormatContext *s, const AVPacket *pkt)
    2680             : {
    2681          13 :     int ret = 1;
    2682          13 :     AVStream *st = s->streams[pkt->stream_index];
    2683             : 
    2684          13 :     if (st->codecpar->codec_id == AV_CODEC_ID_AAC) {
    2685           3 :         if (pkt->size > 2 && (AV_RB16(pkt->data) & 0xfff0) == 0xfff0)
    2686           1 :             ret = ff_stream_add_bitstream_filter(st, "aac_adtstoasc", NULL);
    2687          10 :     } else if (st->codecpar->codec_id == AV_CODEC_ID_VP9) {
    2688           1 :         ret = ff_stream_add_bitstream_filter(st, "vp9_superframe", NULL);
    2689             :     }
    2690             : 
    2691          13 :     return ret;
    2692             : }
    2693             : 
    2694             : static const AVCodecTag additional_audio_tags[] = {
    2695             :     { AV_CODEC_ID_ALAC,      0XFFFFFFFF },
    2696             :     { AV_CODEC_ID_EAC3,      0XFFFFFFFF },
    2697             :     { AV_CODEC_ID_MLP,       0xFFFFFFFF },
    2698             :     { AV_CODEC_ID_OPUS,      0xFFFFFFFF },
    2699             :     { AV_CODEC_ID_PCM_S16BE, 0xFFFFFFFF },
    2700             :     { AV_CODEC_ID_PCM_S24BE, 0xFFFFFFFF },
    2701             :     { AV_CODEC_ID_PCM_S32BE, 0xFFFFFFFF },
    2702             :     { AV_CODEC_ID_QDMC,      0xFFFFFFFF },
    2703             :     { AV_CODEC_ID_QDM2,      0xFFFFFFFF },
    2704             :     { AV_CODEC_ID_RA_144,    0xFFFFFFFF },
    2705             :     { AV_CODEC_ID_RA_288,    0xFFFFFFFF },
    2706             :     { AV_CODEC_ID_COOK,      0xFFFFFFFF },
    2707             :     { AV_CODEC_ID_TRUEHD,    0xFFFFFFFF },
    2708             :     { AV_CODEC_ID_NONE,      0xFFFFFFFF }
    2709             : };
    2710             : 
    2711             : static const AVCodecTag additional_video_tags[] = {
    2712             :     { AV_CODEC_ID_RV10,      0xFFFFFFFF },
    2713             :     { AV_CODEC_ID_RV20,      0xFFFFFFFF },
    2714             :     { AV_CODEC_ID_RV30,      0xFFFFFFFF },
    2715             :     { AV_CODEC_ID_RV40,      0xFFFFFFFF },
    2716             :     { AV_CODEC_ID_VP9,       0xFFFFFFFF },
    2717             :     { AV_CODEC_ID_NONE,      0xFFFFFFFF }
    2718             : };
    2719             : 
    2720             : static const AVCodecTag additional_subtitle_tags[] = {
    2721             :     { AV_CODEC_ID_DVB_SUBTITLE,      0xFFFFFFFF },
    2722             :     { AV_CODEC_ID_HDMV_PGS_SUBTITLE, 0xFFFFFFFF },
    2723             :     { AV_CODEC_ID_NONE,              0xFFFFFFFF }
    2724             : };
    2725             : 
    2726             : #define OFFSET(x) offsetof(MatroskaMuxContext, x)
    2727             : #define FLAGS AV_OPT_FLAG_ENCODING_PARAM
    2728             : static const AVOption options[] = {
    2729             :     { "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 },
    2730             :     { "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 },
    2731             :     { "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 },
    2732             :     { "dash", "Create a WebM file conforming to WebM DASH specification", OFFSET(is_dash), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, FLAGS },
    2733             :     { "dash_track_number", "Track number for the DASH stream", OFFSET(dash_track_number), AV_OPT_TYPE_INT, { .i64 = 1 }, 0, 127, FLAGS },
    2734             :     { "live", "Write files assuming it is a live stream.", OFFSET(is_live), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, FLAGS },
    2735             :     { "allow_raw_vfw", "allow RAW VFW mode", OFFSET(allow_raw_vfw), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, FLAGS },
    2736             :     { "write_crc32", "write a CRC32 element inside every Level 1 element", OFFSET(write_crc), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, FLAGS },
    2737             :     { NULL },
    2738             : };
    2739             : 
    2740             : #if CONFIG_MATROSKA_MUXER
    2741             : static const AVClass matroska_class = {
    2742             :     .class_name = "matroska muxer",
    2743             :     .item_name  = av_default_item_name,
    2744             :     .option     = options,
    2745             :     .version    = LIBAVUTIL_VERSION_INT,
    2746             : };
    2747             : 
    2748             : AVOutputFormat ff_matroska_muxer = {
    2749             :     .name              = "matroska",
    2750             :     .long_name         = NULL_IF_CONFIG_SMALL("Matroska"),
    2751             :     .mime_type         = "video/x-matroska",
    2752             :     .extensions        = "mkv",
    2753             :     .priv_data_size    = sizeof(MatroskaMuxContext),
    2754             :     .audio_codec       = CONFIG_LIBVORBIS_ENCODER ?
    2755             :                          AV_CODEC_ID_VORBIS : AV_CODEC_ID_AC3,
    2756             :     .video_codec       = CONFIG_LIBX264_ENCODER ?
    2757             :                          AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
    2758             :     .init              = mkv_init,
    2759             :     .write_header      = mkv_write_header,
    2760             :     .write_packet      = mkv_write_flush_packet,
    2761             :     .write_trailer     = mkv_write_trailer,
    2762             :     .flags             = AVFMT_GLOBALHEADER | AVFMT_VARIABLE_FPS |
    2763             :                          AVFMT_TS_NONSTRICT | AVFMT_ALLOW_FLUSH,
    2764             :     .codec_tag         = (const AVCodecTag* const []){
    2765             :          ff_codec_bmp_tags, ff_codec_wav_tags,
    2766             :          additional_audio_tags, additional_video_tags, additional_subtitle_tags, 0
    2767             :     },
    2768             :     .subtitle_codec    = AV_CODEC_ID_ASS,
    2769             :     .query_codec       = mkv_query_codec,
    2770             :     .check_bitstream   = mkv_check_bitstream,
    2771             :     .priv_class        = &matroska_class,
    2772             : };
    2773             : #endif
    2774             : 
    2775             : #if CONFIG_WEBM_MUXER
    2776             : static const AVClass webm_class = {
    2777             :     .class_name = "webm muxer",
    2778             :     .item_name  = av_default_item_name,
    2779             :     .option     = options,
    2780             :     .version    = LIBAVUTIL_VERSION_INT,
    2781             : };
    2782             : 
    2783             : AVOutputFormat ff_webm_muxer = {
    2784             :     .name              = "webm",
    2785             :     .long_name         = NULL_IF_CONFIG_SMALL("WebM"),
    2786             :     .mime_type         = "video/webm",
    2787             :     .extensions        = "webm",
    2788             :     .priv_data_size    = sizeof(MatroskaMuxContext),
    2789             :     .audio_codec       = CONFIG_LIBOPUS_ENCODER ? AV_CODEC_ID_OPUS : AV_CODEC_ID_VORBIS,
    2790             :     .video_codec       = CONFIG_LIBVPX_VP9_ENCODER? AV_CODEC_ID_VP9 : AV_CODEC_ID_VP8,
    2791             :     .subtitle_codec    = AV_CODEC_ID_WEBVTT,
    2792             :     .init              = mkv_init,
    2793             :     .write_header      = mkv_write_header,
    2794             :     .write_packet      = mkv_write_flush_packet,
    2795             :     .write_trailer     = mkv_write_trailer,
    2796             :     .check_bitstream   = mkv_check_bitstream,
    2797             :     .flags             = AVFMT_GLOBALHEADER | AVFMT_VARIABLE_FPS |
    2798             :                          AVFMT_TS_NONSTRICT | AVFMT_ALLOW_FLUSH,
    2799             :     .priv_class        = &webm_class,
    2800             : };
    2801             : #endif
    2802             : 
    2803             : #if CONFIG_MATROSKA_AUDIO_MUXER
    2804             : static const AVClass mka_class = {
    2805             :     .class_name = "matroska audio muxer",
    2806             :     .item_name  = av_default_item_name,
    2807             :     .option     = options,
    2808             :     .version    = LIBAVUTIL_VERSION_INT,
    2809             : };
    2810             : AVOutputFormat ff_matroska_audio_muxer = {
    2811             :     .name              = "matroska",
    2812             :     .long_name         = NULL_IF_CONFIG_SMALL("Matroska Audio"),
    2813             :     .mime_type         = "audio/x-matroska",
    2814             :     .extensions        = "mka",
    2815             :     .priv_data_size    = sizeof(MatroskaMuxContext),
    2816             :     .audio_codec       = CONFIG_LIBVORBIS_ENCODER ?
    2817             :                          AV_CODEC_ID_VORBIS : AV_CODEC_ID_AC3,
    2818             :     .video_codec       = AV_CODEC_ID_NONE,
    2819             :     .init              = mkv_init,
    2820             :     .write_header      = mkv_write_header,
    2821             :     .write_packet      = mkv_write_flush_packet,
    2822             :     .write_trailer     = mkv_write_trailer,
    2823             :     .check_bitstream   = mkv_check_bitstream,
    2824             :     .flags             = AVFMT_GLOBALHEADER | AVFMT_TS_NONSTRICT |
    2825             :                          AVFMT_ALLOW_FLUSH,
    2826             :     .codec_tag         = (const AVCodecTag* const []){
    2827             :         ff_codec_wav_tags, additional_audio_tags, 0
    2828             :     },
    2829             :     .priv_class        = &mka_class,
    2830             : };
    2831             : #endif

Generated by: LCOV version 1.13