]> git.sesse.net Git - ffmpeg/blob - libavformat/movenc.c
avformat/movenc: write the mdcv atom by default
[ffmpeg] / libavformat / movenc.c
1 /*
2  * MOV, 3GP, MP4 muxer
3  * Copyright (c) 2003 Thomas Raivio
4  * Copyright (c) 2004 Gildas Bazin <gbazin at videolan dot org>
5  * Copyright (c) 2009 Baptiste Coudurier <baptiste dot coudurier at gmail dot com>
6  *
7  * This file is part of FFmpeg.
8  *
9  * FFmpeg is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public
11  * License as published by the Free Software Foundation; either
12  * version 2.1 of the License, or (at your option) any later version.
13  *
14  * FFmpeg is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with FFmpeg; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22  */
23
24 #include <stdint.h>
25 #include <inttypes.h>
26
27 #include "movenc.h"
28 #include "avformat.h"
29 #include "avio_internal.h"
30 #include "riff.h"
31 #include "avio.h"
32 #include "isom.h"
33 #include "av1.h"
34 #include "avc.h"
35 #include "libavcodec/ac3_parser_internal.h"
36 #include "libavcodec/dnxhddata.h"
37 #include "libavcodec/flac.h"
38 #include "libavcodec/get_bits.h"
39
40 #include "libavcodec/internal.h"
41 #include "libavcodec/put_bits.h"
42 #include "libavcodec/vc1_common.h"
43 #include "libavcodec/raw.h"
44 #include "internal.h"
45 #include "libavutil/avstring.h"
46 #include "libavutil/intfloat.h"
47 #include "libavutil/mathematics.h"
48 #include "libavutil/libm.h"
49 #include "libavutil/opt.h"
50 #include "libavutil/dict.h"
51 #include "libavutil/pixdesc.h"
52 #include "libavutil/stereo3d.h"
53 #include "libavutil/timecode.h"
54 #include "libavutil/color_utils.h"
55 #include "hevc.h"
56 #include "rtpenc.h"
57 #include "mov_chan.h"
58 #include "vpcc.h"
59
60 static const AVOption options[] = {
61     { "movflags", "MOV muxer flags", offsetof(MOVMuxContext, flags), AV_OPT_TYPE_FLAGS, {.i64 = 0}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
62     { "rtphint", "Add RTP hint tracks", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_RTP_HINT}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
63     { "moov_size", "maximum moov size so it can be placed at the begin", offsetof(MOVMuxContext, reserved_moov_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, 0 },
64     { "empty_moov", "Make the initial moov atom empty", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_EMPTY_MOOV}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
65     { "frag_keyframe", "Fragment at video keyframes", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FRAG_KEYFRAME}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
66     { "frag_every_frame", "Fragment at every frame", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FRAG_EVERY_FRAME}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
67     { "separate_moof", "Write separate moof/mdat atoms for each track", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_SEPARATE_MOOF}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
68     { "frag_custom", "Flush fragments on caller requests", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FRAG_CUSTOM}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
69     { "isml", "Create a live smooth streaming feed (for pushing to a publishing point)", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_ISML}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
70     { "faststart", "Run a second pass to put the index (moov atom) at the beginning of the file", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FASTSTART}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
71     { "omit_tfhd_offset", "Omit the base data offset in tfhd atoms", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_OMIT_TFHD_OFFSET}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
72     { "disable_chpl", "Disable Nero chapter atom", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_DISABLE_CHPL}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
73     { "default_base_moof", "Set the default-base-is-moof flag in tfhd atoms", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_DEFAULT_BASE_MOOF}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
74     { "dash", "Write DASH compatible fragmented MP4", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_DASH}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
75     { "cmaf", "Write CMAF compatible fragmented MP4", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_CMAF}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
76     { "frag_discont", "Signal that the next fragment is discontinuous from earlier ones", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FRAG_DISCONT}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
77     { "delay_moov", "Delay writing the initial moov until the first fragment is cut, or until the first fragment flush", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_DELAY_MOOV}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
78     { "global_sidx", "Write a global sidx index at the start of the file", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_GLOBAL_SIDX}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
79     { "skip_sidx", "Skip writing of sidx atom", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_SKIP_SIDX}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
80     { "write_colr", "Write colr atom (Experimental, may be renamed or changed, do not use from scripts)", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_WRITE_COLR}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
81     { "prefer_icc", "If writing colr atom prioritise usage of ICC profile if it exists in stream packet side data", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_PREFER_ICC}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
82     { "write_gama", "Write deprecated gama atom", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_WRITE_GAMA}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
83     { "use_metadata_tags", "Use mdta atom for metadata.", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_USE_MDTA}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
84     { "skip_trailer", "Skip writing the mfra/tfra/mfro trailer for fragmented files", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_SKIP_TRAILER}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
85     { "negative_cts_offsets", "Use negative CTS offsets (reducing the need for edit lists)", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
86     FF_RTP_FLAG_OPTS(MOVMuxContext, rtp_flags),
87     { "skip_iods", "Skip writing iods atom.", offsetof(MOVMuxContext, iods_skip), AV_OPT_TYPE_BOOL, {.i64 = 1}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM},
88     { "iods_audio_profile", "iods audio profile atom.", offsetof(MOVMuxContext, iods_audio_profile), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 255, AV_OPT_FLAG_ENCODING_PARAM},
89     { "iods_video_profile", "iods video profile atom.", offsetof(MOVMuxContext, iods_video_profile), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 255, AV_OPT_FLAG_ENCODING_PARAM},
90     { "frag_duration", "Maximum fragment duration", offsetof(MOVMuxContext, max_fragment_duration), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
91     { "min_frag_duration", "Minimum fragment duration", offsetof(MOVMuxContext, min_fragment_duration), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
92     { "frag_size", "Maximum fragment size", offsetof(MOVMuxContext, max_fragment_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
93     { "ism_lookahead", "Number of lookahead entries for ISM files", offsetof(MOVMuxContext, ism_lookahead), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
94     { "video_track_timescale", "set timescale of all video tracks", offsetof(MOVMuxContext, video_track_timescale), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
95     { "brand",    "Override major brand", offsetof(MOVMuxContext, major_brand),   AV_OPT_TYPE_STRING, {.str = NULL}, .flags = AV_OPT_FLAG_ENCODING_PARAM },
96     { "use_editlist", "use edit list", offsetof(MOVMuxContext, use_editlist), AV_OPT_TYPE_BOOL, {.i64 = -1}, -1, 1, AV_OPT_FLAG_ENCODING_PARAM},
97     { "fragment_index", "Fragment number of the next fragment", offsetof(MOVMuxContext, fragments), AV_OPT_TYPE_INT, {.i64 = 1}, 1, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
98     { "mov_gamma", "gamma value for gama atom", offsetof(MOVMuxContext, gamma), AV_OPT_TYPE_FLOAT, {.dbl = 0.0 }, 0.0, 10, AV_OPT_FLAG_ENCODING_PARAM},
99     { "frag_interleave", "Interleave samples within fragments (max number of consecutive samples, lower is tighter interleaving, but with more overhead)", offsetof(MOVMuxContext, frag_interleave), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM },
100     { "encryption_scheme",    "Configures the encryption scheme, allowed values are none, cenc-aes-ctr", offsetof(MOVMuxContext, encryption_scheme_str),   AV_OPT_TYPE_STRING, {.str = NULL}, .flags = AV_OPT_FLAG_ENCODING_PARAM },
101     { "encryption_key", "The media encryption key (hex)", offsetof(MOVMuxContext, encryption_key), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_ENCODING_PARAM },
102     { "encryption_kid", "The media encryption key identifier (hex)", offsetof(MOVMuxContext, encryption_kid), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_ENCODING_PARAM },
103     { "use_stream_ids_as_track_ids", "use stream ids as track ids", offsetof(MOVMuxContext, use_stream_ids_as_track_ids), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM},
104     { "write_tmcd", "force or disable writing tmcd", offsetof(MOVMuxContext, write_tmcd), AV_OPT_TYPE_BOOL, {.i64 = -1}, -1, 1, AV_OPT_FLAG_ENCODING_PARAM},
105     { "write_prft", "Write producer reference time box with specified time source", offsetof(MOVMuxContext, write_prft), AV_OPT_TYPE_INT, {.i64 = MOV_PRFT_NONE}, 0, MOV_PRFT_NB-1, AV_OPT_FLAG_ENCODING_PARAM, "prft"},
106     { "wallclock", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = MOV_PRFT_SRC_WALLCLOCK}, 0, 0, AV_OPT_FLAG_ENCODING_PARAM, "prft"},
107     { "pts", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = MOV_PRFT_SRC_PTS}, 0, 0, AV_OPT_FLAG_ENCODING_PARAM, "prft"},
108     { "empty_hdlr_name", "write zero-length name string in hdlr atoms within mdia and minf atoms", offsetof(MOVMuxContext, empty_hdlr_name), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM},
109     { NULL },
110 };
111
112 #define MOV_CLASS(flavor)\
113 static const AVClass flavor ## _muxer_class = {\
114     .class_name = #flavor " muxer",\
115     .item_name  = av_default_item_name,\
116     .option     = options,\
117     .version    = LIBAVUTIL_VERSION_INT,\
118 };
119
120 static int get_moov_size(AVFormatContext *s);
121
122 static int utf8len(const uint8_t *b)
123 {
124     int len = 0;
125     int val;
126     while (*b) {
127         GET_UTF8(val, *b++, return -1;)
128         len++;
129     }
130     return len;
131 }
132
133 //FIXME support 64 bit variant with wide placeholders
134 static int64_t update_size(AVIOContext *pb, int64_t pos)
135 {
136     int64_t curpos = avio_tell(pb);
137     avio_seek(pb, pos, SEEK_SET);
138     avio_wb32(pb, curpos - pos); /* rewrite size */
139     avio_seek(pb, curpos, SEEK_SET);
140
141     return curpos - pos;
142 }
143
144 static int co64_required(const MOVTrack *track)
145 {
146     if (track->entry > 0 && track->cluster[track->entry - 1].pos + track->data_offset > UINT32_MAX)
147         return 1;
148     return 0;
149 }
150
151 static int is_cover_image(const AVStream *st)
152 {
153     /* Eg. AV_DISPOSITION_ATTACHED_PIC | AV_DISPOSITION_TIMED_THUMBNAILS
154      * is encoded as sparse video track */
155     return st && st->disposition == AV_DISPOSITION_ATTACHED_PIC;
156 }
157
158 static int rtp_hinting_needed(const AVStream *st)
159 {
160     /* Add hint tracks for each real audio and video stream */
161     if (is_cover_image(st))
162         return 0;
163     return st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ||
164            st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO;
165 }
166
167 /* Chunk offset atom */
168 static int mov_write_stco_tag(AVIOContext *pb, MOVTrack *track)
169 {
170     int i;
171     int mode64 = co64_required(track); // use 32 bit size variant if possible
172     int64_t pos = avio_tell(pb);
173     avio_wb32(pb, 0); /* size */
174     if (mode64)
175         ffio_wfourcc(pb, "co64");
176     else
177         ffio_wfourcc(pb, "stco");
178     avio_wb32(pb, 0); /* version & flags */
179     avio_wb32(pb, track->chunkCount); /* entry count */
180     for (i = 0; i < track->entry; i++) {
181         if (!track->cluster[i].chunkNum)
182             continue;
183         if (mode64 == 1)
184             avio_wb64(pb, track->cluster[i].pos + track->data_offset);
185         else
186             avio_wb32(pb, track->cluster[i].pos + track->data_offset);
187     }
188     return update_size(pb, pos);
189 }
190
191 /* Sample size atom */
192 static int mov_write_stsz_tag(AVIOContext *pb, MOVTrack *track)
193 {
194     int equalChunks = 1;
195     int i, j, entries = 0, tst = -1, oldtst = -1;
196
197     int64_t pos = avio_tell(pb);
198     avio_wb32(pb, 0); /* size */
199     ffio_wfourcc(pb, "stsz");
200     avio_wb32(pb, 0); /* version & flags */
201
202     for (i = 0; i < track->entry; i++) {
203         tst = track->cluster[i].size / track->cluster[i].entries;
204         if (oldtst != -1 && tst != oldtst)
205             equalChunks = 0;
206         oldtst = tst;
207         entries += track->cluster[i].entries;
208     }
209     if (equalChunks && track->entry) {
210         int sSize = track->entry ? track->cluster[0].size / track->cluster[0].entries : 0;
211         sSize = FFMAX(1, sSize); // adpcm mono case could make sSize == 0
212         avio_wb32(pb, sSize); // sample size
213         avio_wb32(pb, entries); // sample count
214     } else {
215         avio_wb32(pb, 0); // sample size
216         avio_wb32(pb, entries); // sample count
217         for (i = 0; i < track->entry; i++) {
218             for (j = 0; j < track->cluster[i].entries; j++) {
219                 avio_wb32(pb, track->cluster[i].size /
220                           track->cluster[i].entries);
221             }
222         }
223     }
224     return update_size(pb, pos);
225 }
226
227 /* Sample to chunk atom */
228 static int mov_write_stsc_tag(AVIOContext *pb, MOVTrack *track)
229 {
230     int index = 0, oldval = -1, i;
231     int64_t entryPos, curpos;
232
233     int64_t pos = avio_tell(pb);
234     avio_wb32(pb, 0); /* size */
235     ffio_wfourcc(pb, "stsc");
236     avio_wb32(pb, 0); // version & flags
237     entryPos = avio_tell(pb);
238     avio_wb32(pb, track->chunkCount); // entry count
239     for (i = 0; i < track->entry; i++) {
240         if (oldval != track->cluster[i].samples_in_chunk && track->cluster[i].chunkNum) {
241             avio_wb32(pb, track->cluster[i].chunkNum); // first chunk
242             avio_wb32(pb, track->cluster[i].samples_in_chunk); // samples per chunk
243             avio_wb32(pb, 0x1); // sample description index
244             oldval = track->cluster[i].samples_in_chunk;
245             index++;
246         }
247     }
248     curpos = avio_tell(pb);
249     avio_seek(pb, entryPos, SEEK_SET);
250     avio_wb32(pb, index); // rewrite size
251     avio_seek(pb, curpos, SEEK_SET);
252
253     return update_size(pb, pos);
254 }
255
256 /* Sync sample atom */
257 static int mov_write_stss_tag(AVIOContext *pb, MOVTrack *track, uint32_t flag)
258 {
259     int64_t curpos, entryPos;
260     int i, index = 0;
261     int64_t pos = avio_tell(pb);
262     avio_wb32(pb, 0); // size
263     ffio_wfourcc(pb, flag == MOV_SYNC_SAMPLE ? "stss" : "stps");
264     avio_wb32(pb, 0); // version & flags
265     entryPos = avio_tell(pb);
266     avio_wb32(pb, track->entry); // entry count
267     for (i = 0; i < track->entry; i++) {
268         if (track->cluster[i].flags & flag) {
269             avio_wb32(pb, i + 1);
270             index++;
271         }
272     }
273     curpos = avio_tell(pb);
274     avio_seek(pb, entryPos, SEEK_SET);
275     avio_wb32(pb, index); // rewrite size
276     avio_seek(pb, curpos, SEEK_SET);
277     return update_size(pb, pos);
278 }
279
280 /* Sample dependency atom */
281 static int mov_write_sdtp_tag(AVIOContext *pb, MOVTrack *track)
282 {
283     int i;
284     uint8_t leading, dependent, reference, redundancy;
285     int64_t pos = avio_tell(pb);
286     avio_wb32(pb, 0); // size
287     ffio_wfourcc(pb, "sdtp");
288     avio_wb32(pb, 0); // version & flags
289     for (i = 0; i < track->entry; i++) {
290         dependent = MOV_SAMPLE_DEPENDENCY_YES;
291         leading = reference = redundancy = MOV_SAMPLE_DEPENDENCY_UNKNOWN;
292         if (track->cluster[i].flags & MOV_DISPOSABLE_SAMPLE) {
293             reference = MOV_SAMPLE_DEPENDENCY_NO;
294         }
295         if (track->cluster[i].flags & MOV_SYNC_SAMPLE) {
296             dependent = MOV_SAMPLE_DEPENDENCY_NO;
297         }
298         avio_w8(pb, (leading << 6)   | (dependent << 4) |
299                     (reference << 2) | redundancy);
300     }
301     return update_size(pb, pos);
302 }
303
304 static int mov_write_amr_tag(AVIOContext *pb, MOVTrack *track)
305 {
306     avio_wb32(pb, 0x11); /* size */
307     if (track->mode == MODE_MOV) ffio_wfourcc(pb, "samr");
308     else                         ffio_wfourcc(pb, "damr");
309     ffio_wfourcc(pb, "FFMP");
310     avio_w8(pb, 0); /* decoder version */
311
312     avio_wb16(pb, 0x81FF); /* Mode set (all modes for AMR_NB) */
313     avio_w8(pb, 0x00); /* Mode change period (no restriction) */
314     avio_w8(pb, 0x01); /* Frames per sample */
315     return 0x11;
316 }
317
318 static int mov_write_ac3_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
319 {
320     GetBitContext gbc;
321     PutBitContext pbc;
322     uint8_t buf[3];
323     int fscod, bsid, bsmod, acmod, lfeon, frmsizecod;
324
325     if (track->vos_len < 7) {
326         av_log(s, AV_LOG_ERROR,
327                "Cannot write moov atom before AC3 packets."
328                " Set the delay_moov flag to fix this.\n");
329         return AVERROR(EINVAL);
330     }
331
332     avio_wb32(pb, 11);
333     ffio_wfourcc(pb, "dac3");
334
335     init_get_bits(&gbc, track->vos_data + 4, (track->vos_len - 4) * 8);
336     fscod      = get_bits(&gbc, 2);
337     frmsizecod = get_bits(&gbc, 6);
338     bsid       = get_bits(&gbc, 5);
339     bsmod      = get_bits(&gbc, 3);
340     acmod      = get_bits(&gbc, 3);
341     if (acmod == 2) {
342         skip_bits(&gbc, 2); // dsurmod
343     } else {
344         if ((acmod & 1) && acmod != 1)
345             skip_bits(&gbc, 2); // cmixlev
346         if (acmod & 4)
347             skip_bits(&gbc, 2); // surmixlev
348     }
349     lfeon = get_bits1(&gbc);
350
351     init_put_bits(&pbc, buf, sizeof(buf));
352     put_bits(&pbc, 2, fscod);
353     put_bits(&pbc, 5, bsid);
354     put_bits(&pbc, 3, bsmod);
355     put_bits(&pbc, 3, acmod);
356     put_bits(&pbc, 1, lfeon);
357     put_bits(&pbc, 5, frmsizecod >> 1); // bit_rate_code
358     put_bits(&pbc, 5, 0); // reserved
359
360     flush_put_bits(&pbc);
361     avio_write(pb, buf, sizeof(buf));
362
363     return 11;
364 }
365
366 struct eac3_info {
367     AVPacket pkt;
368     uint8_t ec3_done;
369     uint8_t num_blocks;
370
371     /* Layout of the EC3SpecificBox */
372     /* maximum bitrate */
373     uint16_t data_rate;
374     /* number of independent substreams */
375     uint8_t  num_ind_sub;
376     struct {
377         /* sample rate code (see ff_ac3_sample_rate_tab) 2 bits */
378         uint8_t fscod;
379         /* bit stream identification 5 bits */
380         uint8_t bsid;
381         /* one bit reserved */
382         /* audio service mixing (not supported yet) 1 bit */
383         /* bit stream mode 3 bits */
384         uint8_t bsmod;
385         /* audio coding mode 3 bits */
386         uint8_t acmod;
387         /* sub woofer on 1 bit */
388         uint8_t lfeon;
389         /* 3 bits reserved */
390         /* number of dependent substreams associated with this substream 4 bits */
391         uint8_t num_dep_sub;
392         /* channel locations of the dependent substream(s), if any, 9 bits */
393         uint16_t chan_loc;
394         /* if there is no dependent substream, then one bit reserved instead */
395     } substream[1]; /* TODO: support 8 independent substreams */
396 };
397
398 #if CONFIG_AC3_PARSER
399 static int handle_eac3(MOVMuxContext *mov, AVPacket *pkt, MOVTrack *track)
400 {
401     AC3HeaderInfo *hdr = NULL;
402     struct eac3_info *info;
403     int num_blocks, ret;
404
405     if (!track->eac3_priv && !(track->eac3_priv = av_mallocz(sizeof(*info))))
406         return AVERROR(ENOMEM);
407     info = track->eac3_priv;
408
409     if (avpriv_ac3_parse_header(&hdr, pkt->data, pkt->size) < 0) {
410         /* drop the packets until we see a good one */
411         if (!track->entry) {
412             av_log(mov->fc, AV_LOG_WARNING, "Dropping invalid packet from start of the stream\n");
413             ret = 0;
414         } else
415             ret = AVERROR_INVALIDDATA;
416         goto end;
417     }
418
419     info->data_rate = FFMAX(info->data_rate, hdr->bit_rate / 1000);
420     num_blocks = hdr->num_blocks;
421
422     if (!info->ec3_done) {
423         /* AC-3 substream must be the first one */
424         if (hdr->bitstream_id <= 10 && hdr->substreamid != 0) {
425             ret = AVERROR(EINVAL);
426             goto end;
427         }
428
429         /* this should always be the case, given that our AC-3 parser
430          * concatenates dependent frames to their independent parent */
431         if (hdr->frame_type == EAC3_FRAME_TYPE_INDEPENDENT) {
432             /* substream ids must be incremental */
433             if (hdr->substreamid > info->num_ind_sub + 1) {
434                 ret = AVERROR(EINVAL);
435                 goto end;
436             }
437
438             if (hdr->substreamid == info->num_ind_sub + 1) {
439                 //info->num_ind_sub++;
440                 avpriv_request_sample(mov->fc, "Multiple independent substreams");
441                 ret = AVERROR_PATCHWELCOME;
442                 goto end;
443             } else if (hdr->substreamid < info->num_ind_sub ||
444                        hdr->substreamid == 0 && info->substream[0].bsid) {
445                 info->ec3_done = 1;
446                 goto concatenate;
447             }
448         } else {
449             if (hdr->substreamid != 0) {
450                 avpriv_request_sample(mov->fc, "Multiple non EAC3 independent substreams");
451                 ret = AVERROR_PATCHWELCOME;
452                 goto end;
453             }
454         }
455
456         /* fill the info needed for the "dec3" atom */
457         info->substream[hdr->substreamid].fscod = hdr->sr_code;
458         info->substream[hdr->substreamid].bsid  = hdr->bitstream_id;
459         info->substream[hdr->substreamid].bsmod = hdr->bitstream_mode;
460         info->substream[hdr->substreamid].acmod = hdr->channel_mode;
461         info->substream[hdr->substreamid].lfeon = hdr->lfe_on;
462
463         /* Parse dependent substream(s), if any */
464         if (pkt->size != hdr->frame_size) {
465             int cumul_size = hdr->frame_size;
466             int parent = hdr->substreamid;
467
468             while (cumul_size != pkt->size) {
469                 GetBitContext gbc;
470                 int i;
471                 ret = avpriv_ac3_parse_header(&hdr, pkt->data + cumul_size, pkt->size - cumul_size);
472                 if (ret < 0)
473                     goto end;
474                 if (hdr->frame_type != EAC3_FRAME_TYPE_DEPENDENT) {
475                     ret = AVERROR(EINVAL);
476                     goto end;
477                 }
478                 info->substream[parent].num_dep_sub++;
479                 ret /= 8;
480
481                 /* header is parsed up to lfeon, but custom channel map may be needed */
482                 init_get_bits8(&gbc, pkt->data + cumul_size + ret, pkt->size - cumul_size - ret);
483                 /* skip bsid */
484                 skip_bits(&gbc, 5);
485                 /* skip volume control params */
486                 for (i = 0; i < (hdr->channel_mode ? 1 : 2); i++) {
487                     skip_bits(&gbc, 5); // skip dialog normalization
488                     if (get_bits1(&gbc)) {
489                         skip_bits(&gbc, 8); // skip compression gain word
490                     }
491                 }
492                 /* get the dependent stream channel map, if exists */
493                 if (get_bits1(&gbc))
494                     info->substream[parent].chan_loc |= (get_bits(&gbc, 16) >> 5) & 0x1f;
495                 else
496                     info->substream[parent].chan_loc |= hdr->channel_mode;
497                 cumul_size += hdr->frame_size;
498             }
499         }
500     }
501
502 concatenate:
503     if (!info->num_blocks && num_blocks == 6) {
504         ret = pkt->size;
505         goto end;
506     }
507     else if (info->num_blocks + num_blocks > 6) {
508         ret = AVERROR_INVALIDDATA;
509         goto end;
510     }
511
512     if (!info->num_blocks) {
513         ret = av_packet_ref(&info->pkt, pkt);
514         if (!ret)
515             info->num_blocks = num_blocks;
516         goto end;
517     } else {
518         if ((ret = av_grow_packet(&info->pkt, pkt->size)) < 0)
519             goto end;
520         memcpy(info->pkt.data + info->pkt.size - pkt->size, pkt->data, pkt->size);
521         info->num_blocks += num_blocks;
522         info->pkt.duration += pkt->duration;
523         if ((ret = av_copy_packet_side_data(&info->pkt, pkt)) < 0)
524             goto end;
525         if (info->num_blocks != 6)
526             goto end;
527         av_packet_unref(pkt);
528         av_packet_move_ref(pkt, &info->pkt);
529         info->num_blocks = 0;
530     }
531     ret = pkt->size;
532
533 end:
534     av_free(hdr);
535
536     return ret;
537 }
538 #endif
539
540 static int mov_write_eac3_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
541 {
542     PutBitContext pbc;
543     uint8_t *buf;
544     struct eac3_info *info;
545     int size, i;
546
547     if (!track->eac3_priv) {
548         av_log(s, AV_LOG_ERROR,
549                "Cannot write moov atom before EAC3 packets parsed.\n");
550         return AVERROR(EINVAL);
551     }
552
553     info = track->eac3_priv;
554     size = 2 + ((34 * (info->num_ind_sub + 1) + 7) >> 3);
555     buf = av_malloc(size);
556     if (!buf) {
557         return AVERROR(ENOMEM);
558     }
559
560     init_put_bits(&pbc, buf, size);
561     put_bits(&pbc, 13, info->data_rate);
562     put_bits(&pbc,  3, info->num_ind_sub);
563     for (i = 0; i <= info->num_ind_sub; i++) {
564         put_bits(&pbc, 2, info->substream[i].fscod);
565         put_bits(&pbc, 5, info->substream[i].bsid);
566         put_bits(&pbc, 1, 0); /* reserved */
567         put_bits(&pbc, 1, 0); /* asvc */
568         put_bits(&pbc, 3, info->substream[i].bsmod);
569         put_bits(&pbc, 3, info->substream[i].acmod);
570         put_bits(&pbc, 1, info->substream[i].lfeon);
571         put_bits(&pbc, 5, 0); /* reserved */
572         put_bits(&pbc, 4, info->substream[i].num_dep_sub);
573         if (!info->substream[i].num_dep_sub) {
574             put_bits(&pbc, 1, 0); /* reserved */
575         } else {
576             put_bits(&pbc, 9, info->substream[i].chan_loc);
577         }
578     }
579     flush_put_bits(&pbc);
580     size = put_bits_count(&pbc) >> 3;
581
582     avio_wb32(pb, size + 8);
583     ffio_wfourcc(pb, "dec3");
584     avio_write(pb, buf, size);
585
586     av_free(buf);
587
588     return size;
589 }
590
591 /**
592  * This function writes extradata "as is".
593  * Extradata must be formatted like a valid atom (with size and tag).
594  */
595 static int mov_write_extradata_tag(AVIOContext *pb, MOVTrack *track)
596 {
597     avio_write(pb, track->par->extradata, track->par->extradata_size);
598     return track->par->extradata_size;
599 }
600
601 static int mov_write_enda_tag(AVIOContext *pb)
602 {
603     avio_wb32(pb, 10);
604     ffio_wfourcc(pb, "enda");
605     avio_wb16(pb, 1); /* little endian */
606     return 10;
607 }
608
609 static int mov_write_enda_tag_be(AVIOContext *pb)
610 {
611   avio_wb32(pb, 10);
612   ffio_wfourcc(pb, "enda");
613   avio_wb16(pb, 0); /* big endian */
614   return 10;
615 }
616
617 static void put_descr(AVIOContext *pb, int tag, unsigned int size)
618 {
619     int i = 3;
620     avio_w8(pb, tag);
621     for (; i > 0; i--)
622         avio_w8(pb, (size >> (7 * i)) | 0x80);
623     avio_w8(pb, size & 0x7F);
624 }
625
626 static unsigned compute_avg_bitrate(MOVTrack *track)
627 {
628     uint64_t size = 0;
629     int i;
630     if (!track->track_duration)
631         return 0;
632     for (i = 0; i < track->entry; i++)
633         size += track->cluster[i].size;
634     return size * 8 * track->timescale / track->track_duration;
635 }
636
637 static int mov_write_esds_tag(AVIOContext *pb, MOVTrack *track) // Basic
638 {
639     AVCPBProperties *props;
640     int64_t pos = avio_tell(pb);
641     int decoder_specific_info_len = track->vos_len ? 5 + track->vos_len : 0;
642     unsigned avg_bitrate;
643
644     avio_wb32(pb, 0); // size
645     ffio_wfourcc(pb, "esds");
646     avio_wb32(pb, 0); // Version
647
648     // ES descriptor
649     put_descr(pb, 0x03, 3 + 5+13 + decoder_specific_info_len + 5+1);
650     avio_wb16(pb, track->track_id);
651     avio_w8(pb, 0x00); // flags (= no flags)
652
653     // DecoderConfig descriptor
654     put_descr(pb, 0x04, 13 + decoder_specific_info_len);
655
656     // Object type indication
657     if ((track->par->codec_id == AV_CODEC_ID_MP2 ||
658          track->par->codec_id == AV_CODEC_ID_MP3) &&
659         track->par->sample_rate > 24000)
660         avio_w8(pb, 0x6B); // 11172-3
661     else
662         avio_w8(pb, ff_codec_get_tag(ff_mp4_obj_type, track->par->codec_id));
663
664     // the following fields is made of 6 bits to identify the streamtype (4 for video, 5 for audio)
665     // plus 1 bit to indicate upstream and 1 bit set to 1 (reserved)
666     if (track->par->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
667         avio_w8(pb, (0x38 << 2) | 1); // flags (= NeroSubpicStream)
668     else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
669         avio_w8(pb, 0x15); // flags (= Audiostream)
670     else
671         avio_w8(pb, 0x11); // flags (= Visualstream)
672
673     props = (AVCPBProperties*)av_stream_get_side_data(track->st, AV_PKT_DATA_CPB_PROPERTIES,
674                                                       NULL);
675
676     avio_wb24(pb, props ? props->buffer_size / 8 : 0); // Buffersize DB
677
678     avg_bitrate = compute_avg_bitrate(track);
679     avio_wb32(pb, props ? FFMAX3(props->max_bitrate, props->avg_bitrate, avg_bitrate) : FFMAX(track->par->bit_rate, avg_bitrate)); // maxbitrate (FIXME should be max rate in any 1 sec window)
680     avio_wb32(pb, avg_bitrate);
681
682     if (track->vos_len) {
683         // DecoderSpecific info descriptor
684         put_descr(pb, 0x05, track->vos_len);
685         avio_write(pb, track->vos_data, track->vos_len);
686     }
687
688     // SL descriptor
689     put_descr(pb, 0x06, 1);
690     avio_w8(pb, 0x02);
691     return update_size(pb, pos);
692 }
693
694 static int mov_pcm_le_gt16(enum AVCodecID codec_id)
695 {
696     return codec_id == AV_CODEC_ID_PCM_S24LE ||
697            codec_id == AV_CODEC_ID_PCM_S32LE ||
698            codec_id == AV_CODEC_ID_PCM_F32LE ||
699            codec_id == AV_CODEC_ID_PCM_F64LE;
700 }
701
702 static int mov_pcm_be_gt16(enum AVCodecID codec_id)
703 {
704     return codec_id == AV_CODEC_ID_PCM_S24BE ||
705            codec_id == AV_CODEC_ID_PCM_S32BE ||
706            codec_id == AV_CODEC_ID_PCM_F32BE ||
707            codec_id == AV_CODEC_ID_PCM_F64BE;
708 }
709
710 static int mov_write_ms_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
711 {
712     int ret;
713     int64_t pos = avio_tell(pb);
714     avio_wb32(pb, 0);
715     avio_wl32(pb, track->tag); // store it byteswapped
716     track->par->codec_tag = av_bswap16(track->tag >> 16);
717     if ((ret = ff_put_wav_header(s, pb, track->par, 0)) < 0)
718         return ret;
719     return update_size(pb, pos);
720 }
721
722 static int mov_write_wfex_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
723 {
724     int ret;
725     int64_t pos = avio_tell(pb);
726     avio_wb32(pb, 0);
727     ffio_wfourcc(pb, "wfex");
728     if ((ret = ff_put_wav_header(s, pb, track->st->codecpar, FF_PUT_WAV_HEADER_FORCE_WAVEFORMATEX)) < 0)
729         return ret;
730     return update_size(pb, pos);
731 }
732
733 static int mov_write_dfla_tag(AVIOContext *pb, MOVTrack *track)
734 {
735     int64_t pos = avio_tell(pb);
736     avio_wb32(pb, 0);
737     ffio_wfourcc(pb, "dfLa");
738     avio_w8(pb, 0); /* version */
739     avio_wb24(pb, 0); /* flags */
740
741     /* Expect the encoder to pass a METADATA_BLOCK_TYPE_STREAMINFO. */
742     if (track->par->extradata_size != FLAC_STREAMINFO_SIZE)
743         return AVERROR_INVALIDDATA;
744
745     /* TODO: Write other METADATA_BLOCK_TYPEs if the encoder makes them available. */
746     avio_w8(pb, 1 << 7 | FLAC_METADATA_TYPE_STREAMINFO); /* LastMetadataBlockFlag << 7 | BlockType */
747     avio_wb24(pb, track->par->extradata_size); /* Length */
748     avio_write(pb, track->par->extradata, track->par->extradata_size); /* BlockData[Length] */
749
750     return update_size(pb, pos);
751 }
752
753 static int mov_write_dops_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
754 {
755     int64_t pos = avio_tell(pb);
756     avio_wb32(pb, 0);
757     ffio_wfourcc(pb, "dOps");
758     avio_w8(pb, 0); /* Version */
759     if (track->par->extradata_size < 19) {
760         av_log(s, AV_LOG_ERROR, "invalid extradata size\n");
761         return AVERROR_INVALIDDATA;
762     }
763     /* extradata contains an Ogg OpusHead, other than byte-ordering and
764        OpusHead's preceeding magic/version, OpusSpecificBox is currently
765        identical. */
766     avio_w8(pb, AV_RB8(track->par->extradata + 9)); /* OuputChannelCount */
767     avio_wb16(pb, AV_RL16(track->par->extradata + 10)); /* PreSkip */
768     avio_wb32(pb, AV_RL32(track->par->extradata + 12)); /* InputSampleRate */
769     avio_wb16(pb, AV_RL16(track->par->extradata + 16)); /* OutputGain */
770     /* Write the rest of the header out without byte-swapping. */
771     avio_write(pb, track->par->extradata + 18, track->par->extradata_size - 18);
772
773     return update_size(pb, pos);
774 }
775
776 static int mov_write_dmlp_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
777 {
778     int64_t pos = avio_tell(pb);
779     int length;
780     avio_wb32(pb, 0);
781     ffio_wfourcc(pb, "dmlp");
782
783     if (track->vos_len < 20) {
784         av_log(s, AV_LOG_ERROR,
785                "Cannot write moov atom before TrueHD packets."
786                " Set the delay_moov flag to fix this.\n");
787         return AVERROR(EINVAL);
788     }
789
790     length = (AV_RB16(track->vos_data) & 0xFFF) * 2;
791     if (length < 20 || length > track->vos_len)
792         return AVERROR_INVALIDDATA;
793
794     // Only TrueHD is supported
795     if (AV_RB32(track->vos_data + 4) != 0xF8726FBA)
796         return AVERROR_INVALIDDATA;
797
798     avio_wb32(pb, AV_RB32(track->vos_data + 8)); /* format_info */
799     avio_wb16(pb, AV_RB16(track->vos_data + 18) << 1); /* peak_data_rate */
800     avio_wb32(pb, 0); /* reserved */
801
802     return update_size(pb, pos);
803 }
804
805 static int mov_write_chan_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
806 {
807     uint32_t layout_tag, bitmap;
808     int64_t pos = avio_tell(pb);
809
810     layout_tag = ff_mov_get_channel_layout_tag(track->par->codec_id,
811                                                track->par->channel_layout,
812                                                &bitmap);
813     if (!layout_tag) {
814         av_log(s, AV_LOG_WARNING, "not writing 'chan' tag due to "
815                "lack of channel information\n");
816         return 0;
817     }
818
819     if (track->multichannel_as_mono)
820         return 0;
821
822     avio_wb32(pb, 0);           // Size
823     ffio_wfourcc(pb, "chan");   // Type
824     avio_w8(pb, 0);             // Version
825     avio_wb24(pb, 0);           // Flags
826     avio_wb32(pb, layout_tag);  // mChannelLayoutTag
827     avio_wb32(pb, bitmap);      // mChannelBitmap
828     avio_wb32(pb, 0);           // mNumberChannelDescriptions
829
830     return update_size(pb, pos);
831 }
832
833 static int mov_write_wave_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
834 {
835     int64_t pos = avio_tell(pb);
836
837     avio_wb32(pb, 0);     /* size */
838     ffio_wfourcc(pb, "wave");
839
840     if (track->par->codec_id != AV_CODEC_ID_QDM2) {
841     avio_wb32(pb, 12);    /* size */
842     ffio_wfourcc(pb, "frma");
843     avio_wl32(pb, track->tag);
844     }
845
846     if (track->par->codec_id == AV_CODEC_ID_AAC) {
847         /* useless atom needed by mplayer, ipod, not needed by quicktime */
848         avio_wb32(pb, 12); /* size */
849         ffio_wfourcc(pb, "mp4a");
850         avio_wb32(pb, 0);
851         mov_write_esds_tag(pb, track);
852     } else if (mov_pcm_le_gt16(track->par->codec_id))  {
853       mov_write_enda_tag(pb);
854     } else if (mov_pcm_be_gt16(track->par->codec_id))  {
855       mov_write_enda_tag_be(pb);
856     } else if (track->par->codec_id == AV_CODEC_ID_AMR_NB) {
857         mov_write_amr_tag(pb, track);
858     } else if (track->par->codec_id == AV_CODEC_ID_AC3) {
859         mov_write_ac3_tag(s, pb, track);
860     } else if (track->par->codec_id == AV_CODEC_ID_EAC3) {
861         mov_write_eac3_tag(s, pb, track);
862     } else if (track->par->codec_id == AV_CODEC_ID_ALAC ||
863                track->par->codec_id == AV_CODEC_ID_QDM2) {
864         mov_write_extradata_tag(pb, track);
865     } else if (track->par->codec_id == AV_CODEC_ID_ADPCM_MS ||
866                track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) {
867         mov_write_ms_tag(s, pb, track);
868     }
869
870     avio_wb32(pb, 8);     /* size */
871     avio_wb32(pb, 0);     /* null tag */
872
873     return update_size(pb, pos);
874 }
875
876 static int mov_write_dvc1_structs(MOVTrack *track, uint8_t *buf)
877 {
878     uint8_t *unescaped;
879     const uint8_t *start, *next, *end = track->vos_data + track->vos_len;
880     int unescaped_size, seq_found = 0;
881     int level = 0, interlace = 0;
882     int packet_seq   = track->vc1_info.packet_seq;
883     int packet_entry = track->vc1_info.packet_entry;
884     int slices       = track->vc1_info.slices;
885     PutBitContext pbc;
886
887     if (track->start_dts == AV_NOPTS_VALUE) {
888         /* No packets written yet, vc1_info isn't authoritative yet. */
889         /* Assume inline sequence and entry headers. */
890         packet_seq = packet_entry = 1;
891         av_log(NULL, AV_LOG_WARNING,
892                "moov atom written before any packets, unable to write correct "
893                "dvc1 atom. Set the delay_moov flag to fix this.\n");
894     }
895
896     unescaped = av_mallocz(track->vos_len + AV_INPUT_BUFFER_PADDING_SIZE);
897     if (!unescaped)
898         return AVERROR(ENOMEM);
899     start = find_next_marker(track->vos_data, end);
900     for (next = start; next < end; start = next) {
901         GetBitContext gb;
902         int size;
903         next = find_next_marker(start + 4, end);
904         size = next - start - 4;
905         if (size <= 0)
906             continue;
907         unescaped_size = vc1_unescape_buffer(start + 4, size, unescaped);
908         init_get_bits(&gb, unescaped, 8 * unescaped_size);
909         if (AV_RB32(start) == VC1_CODE_SEQHDR) {
910             int profile = get_bits(&gb, 2);
911             if (profile != PROFILE_ADVANCED) {
912                 av_free(unescaped);
913                 return AVERROR(ENOSYS);
914             }
915             seq_found = 1;
916             level = get_bits(&gb, 3);
917             /* chromaformat, frmrtq_postproc, bitrtq_postproc, postprocflag,
918              * width, height */
919             skip_bits_long(&gb, 2 + 3 + 5 + 1 + 2*12);
920             skip_bits(&gb, 1); /* broadcast */
921             interlace = get_bits1(&gb);
922             skip_bits(&gb, 4); /* tfcntrflag, finterpflag, reserved, psf */
923         }
924     }
925     if (!seq_found) {
926         av_free(unescaped);
927         return AVERROR(ENOSYS);
928     }
929
930     init_put_bits(&pbc, buf, 7);
931     /* VC1DecSpecStruc */
932     put_bits(&pbc, 4, 12); /* profile - advanced */
933     put_bits(&pbc, 3, level);
934     put_bits(&pbc, 1, 0); /* reserved */
935     /* VC1AdvDecSpecStruc */
936     put_bits(&pbc, 3, level);
937     put_bits(&pbc, 1, 0); /* cbr */
938     put_bits(&pbc, 6, 0); /* reserved */
939     put_bits(&pbc, 1, !interlace); /* no interlace */
940     put_bits(&pbc, 1, !packet_seq); /* no multiple seq */
941     put_bits(&pbc, 1, !packet_entry); /* no multiple entry */
942     put_bits(&pbc, 1, !slices); /* no slice code */
943     put_bits(&pbc, 1, 0); /* no bframe */
944     put_bits(&pbc, 1, 0); /* reserved */
945
946     /* framerate */
947     if (track->st->avg_frame_rate.num > 0 && track->st->avg_frame_rate.den > 0)
948         put_bits32(&pbc, track->st->avg_frame_rate.num / track->st->avg_frame_rate.den);
949     else
950         put_bits32(&pbc, 0xffffffff);
951
952     flush_put_bits(&pbc);
953
954     av_free(unescaped);
955
956     return 0;
957 }
958
959 static int mov_write_dvc1_tag(AVIOContext *pb, MOVTrack *track)
960 {
961     uint8_t buf[7] = { 0 };
962     int ret;
963
964     if ((ret = mov_write_dvc1_structs(track, buf)) < 0)
965         return ret;
966
967     avio_wb32(pb, track->vos_len + 8 + sizeof(buf));
968     ffio_wfourcc(pb, "dvc1");
969     avio_write(pb, buf, sizeof(buf));
970     avio_write(pb, track->vos_data, track->vos_len);
971
972     return 0;
973 }
974
975 static int mov_write_glbl_tag(AVIOContext *pb, MOVTrack *track)
976 {
977     avio_wb32(pb, track->vos_len + 8);
978     ffio_wfourcc(pb, "glbl");
979     avio_write(pb, track->vos_data, track->vos_len);
980     return 8 + track->vos_len;
981 }
982
983 /**
984  * Compute flags for 'lpcm' tag.
985  * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
986  */
987 static int mov_get_lpcm_flags(enum AVCodecID codec_id)
988 {
989     switch (codec_id) {
990     case AV_CODEC_ID_PCM_F32BE:
991     case AV_CODEC_ID_PCM_F64BE:
992         return 11;
993     case AV_CODEC_ID_PCM_F32LE:
994     case AV_CODEC_ID_PCM_F64LE:
995         return 9;
996     case AV_CODEC_ID_PCM_U8:
997         return 10;
998     case AV_CODEC_ID_PCM_S16BE:
999     case AV_CODEC_ID_PCM_S24BE:
1000     case AV_CODEC_ID_PCM_S32BE:
1001         return 14;
1002     case AV_CODEC_ID_PCM_S8:
1003     case AV_CODEC_ID_PCM_S16LE:
1004     case AV_CODEC_ID_PCM_S24LE:
1005     case AV_CODEC_ID_PCM_S32LE:
1006         return 12;
1007     default:
1008         return 0;
1009     }
1010 }
1011
1012 static int get_cluster_duration(MOVTrack *track, int cluster_idx)
1013 {
1014     int64_t next_dts;
1015
1016     if (cluster_idx >= track->entry)
1017         return 0;
1018
1019     if (cluster_idx + 1 == track->entry)
1020         next_dts = track->track_duration + track->start_dts;
1021     else
1022         next_dts = track->cluster[cluster_idx + 1].dts;
1023
1024     next_dts -= track->cluster[cluster_idx].dts;
1025
1026     av_assert0(next_dts >= 0);
1027     av_assert0(next_dts <= INT_MAX);
1028
1029     return next_dts;
1030 }
1031
1032 static int get_samples_per_packet(MOVTrack *track)
1033 {
1034     int i, first_duration;
1035
1036 // return track->par->frame_size;
1037
1038     /* use 1 for raw PCM */
1039     if (!track->audio_vbr)
1040         return 1;
1041
1042     /* check to see if duration is constant for all clusters */
1043     if (!track->entry)
1044         return 0;
1045     first_duration = get_cluster_duration(track, 0);
1046     for (i = 1; i < track->entry; i++) {
1047         if (get_cluster_duration(track, i) != first_duration)
1048             return 0;
1049     }
1050     return first_duration;
1051 }
1052
1053 static int mov_write_audio_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
1054 {
1055     int64_t pos = avio_tell(pb);
1056     int version = 0;
1057     uint32_t tag = track->tag;
1058     int ret = 0;
1059
1060     if (track->mode == MODE_MOV) {
1061         if (track->timescale > UINT16_MAX || !track->par->channels) {
1062             if (mov_get_lpcm_flags(track->par->codec_id))
1063                 tag = AV_RL32("lpcm");
1064             version = 2;
1065         } else if (track->audio_vbr || mov_pcm_le_gt16(track->par->codec_id) ||
1066                    mov_pcm_be_gt16(track->par->codec_id) ||
1067                    track->par->codec_id == AV_CODEC_ID_ADPCM_MS ||
1068                    track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
1069                    track->par->codec_id == AV_CODEC_ID_QDM2) {
1070             version = 1;
1071         }
1072     }
1073
1074     avio_wb32(pb, 0); /* size */
1075     if (mov->encryption_scheme != MOV_ENC_NONE) {
1076         ffio_wfourcc(pb, "enca");
1077     } else {
1078         avio_wl32(pb, tag); // store it byteswapped
1079     }
1080     avio_wb32(pb, 0); /* Reserved */
1081     avio_wb16(pb, 0); /* Reserved */
1082     avio_wb16(pb, 1); /* Data-reference index, XXX  == 1 */
1083
1084     /* SoundDescription */
1085     avio_wb16(pb, version); /* Version */
1086     avio_wb16(pb, 0); /* Revision level */
1087     avio_wb32(pb, 0); /* Reserved */
1088
1089     if (version == 2) {
1090         avio_wb16(pb, 3);
1091         avio_wb16(pb, 16);
1092         avio_wb16(pb, 0xfffe);
1093         avio_wb16(pb, 0);
1094         avio_wb32(pb, 0x00010000);
1095         avio_wb32(pb, 72);
1096         avio_wb64(pb, av_double2int(track->par->sample_rate));
1097         avio_wb32(pb, track->par->channels);
1098         avio_wb32(pb, 0x7F000000);
1099         avio_wb32(pb, av_get_bits_per_sample(track->par->codec_id));
1100         avio_wb32(pb, mov_get_lpcm_flags(track->par->codec_id));
1101         avio_wb32(pb, track->sample_size);
1102         avio_wb32(pb, get_samples_per_packet(track));
1103     } else {
1104         if (track->mode == MODE_MOV) {
1105             avio_wb16(pb, track->par->channels);
1106             if (track->par->codec_id == AV_CODEC_ID_PCM_U8 ||
1107                 track->par->codec_id == AV_CODEC_ID_PCM_S8)
1108                 avio_wb16(pb, 8); /* bits per sample */
1109             else if (track->par->codec_id == AV_CODEC_ID_ADPCM_G726)
1110                 avio_wb16(pb, track->par->bits_per_coded_sample);
1111             else
1112                 avio_wb16(pb, 16);
1113             avio_wb16(pb, track->audio_vbr ? -2 : 0); /* compression ID */
1114         } else { /* reserved for mp4/3gp */
1115             if (track->par->codec_id == AV_CODEC_ID_FLAC ||
1116                 track->par->codec_id == AV_CODEC_ID_ALAC ||
1117                 track->par->codec_id == AV_CODEC_ID_OPUS) {
1118                 avio_wb16(pb, track->par->channels);
1119             } else {
1120                 avio_wb16(pb, 2);
1121             }
1122             if (track->par->codec_id == AV_CODEC_ID_FLAC ||
1123                 track->par->codec_id == AV_CODEC_ID_ALAC) {
1124                 avio_wb16(pb, track->par->bits_per_raw_sample);
1125             } else {
1126                 avio_wb16(pb, 16);
1127             }
1128             avio_wb16(pb, 0);
1129         }
1130
1131         avio_wb16(pb, 0); /* packet size (= 0) */
1132         if (track->par->codec_id == AV_CODEC_ID_OPUS)
1133             avio_wb16(pb, 48000);
1134         else if (track->par->codec_id == AV_CODEC_ID_TRUEHD)
1135             avio_wb32(pb, track->par->sample_rate);
1136         else
1137             avio_wb16(pb, track->par->sample_rate <= UINT16_MAX ?
1138                           track->par->sample_rate : 0);
1139
1140         if (track->par->codec_id != AV_CODEC_ID_TRUEHD)
1141             avio_wb16(pb, 0); /* Reserved */
1142     }
1143
1144     if (version == 1) { /* SoundDescription V1 extended info */
1145         if (mov_pcm_le_gt16(track->par->codec_id) ||
1146             mov_pcm_be_gt16(track->par->codec_id))
1147             avio_wb32(pb, 1); /*  must be 1 for  uncompressed formats */
1148         else
1149             avio_wb32(pb, track->par->frame_size); /* Samples per packet */
1150         avio_wb32(pb, track->sample_size / track->par->channels); /* Bytes per packet */
1151         avio_wb32(pb, track->sample_size); /* Bytes per frame */
1152         avio_wb32(pb, 2); /* Bytes per sample */
1153     }
1154
1155     if (track->mode == MODE_MOV &&
1156         (track->par->codec_id == AV_CODEC_ID_AAC           ||
1157          track->par->codec_id == AV_CODEC_ID_AC3           ||
1158          track->par->codec_id == AV_CODEC_ID_EAC3          ||
1159          track->par->codec_id == AV_CODEC_ID_AMR_NB        ||
1160          track->par->codec_id == AV_CODEC_ID_ALAC          ||
1161          track->par->codec_id == AV_CODEC_ID_ADPCM_MS      ||
1162          track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
1163          track->par->codec_id == AV_CODEC_ID_QDM2          ||
1164          (mov_pcm_le_gt16(track->par->codec_id) && version==1) ||
1165          (mov_pcm_be_gt16(track->par->codec_id) && version==1)))
1166         ret = mov_write_wave_tag(s, pb, track);
1167     else if (track->tag == MKTAG('m','p','4','a'))
1168         ret = mov_write_esds_tag(pb, track);
1169     else if (track->par->codec_id == AV_CODEC_ID_AMR_NB)
1170         ret = mov_write_amr_tag(pb, track);
1171     else if (track->par->codec_id == AV_CODEC_ID_AC3)
1172         ret = mov_write_ac3_tag(s, pb, track);
1173     else if (track->par->codec_id == AV_CODEC_ID_EAC3)
1174         ret = mov_write_eac3_tag(s, pb, track);
1175     else if (track->par->codec_id == AV_CODEC_ID_ALAC)
1176         ret = mov_write_extradata_tag(pb, track);
1177     else if (track->par->codec_id == AV_CODEC_ID_WMAPRO)
1178         ret = mov_write_wfex_tag(s, pb, track);
1179     else if (track->par->codec_id == AV_CODEC_ID_FLAC)
1180         ret = mov_write_dfla_tag(pb, track);
1181     else if (track->par->codec_id == AV_CODEC_ID_OPUS)
1182         ret = mov_write_dops_tag(s, pb, track);
1183     else if (track->par->codec_id == AV_CODEC_ID_TRUEHD)
1184         ret = mov_write_dmlp_tag(s, pb, track);
1185     else if (track->vos_len > 0)
1186         ret = mov_write_glbl_tag(pb, track);
1187
1188     if (ret < 0)
1189         return ret;
1190
1191     if (track->mode == MODE_MOV && track->par->codec_type == AVMEDIA_TYPE_AUDIO
1192             && ((ret = mov_write_chan_tag(s, pb, track)) < 0)) {
1193         return ret;
1194     }
1195
1196     if (mov->encryption_scheme != MOV_ENC_NONE
1197             && ((ret = ff_mov_cenc_write_sinf_tag(track, pb, mov->encryption_kid)) < 0)) {
1198         return ret;
1199     }
1200
1201     ret = update_size(pb, pos);
1202     return ret;
1203 }
1204
1205 static int mov_write_d263_tag(AVIOContext *pb)
1206 {
1207     avio_wb32(pb, 0xf); /* size */
1208     ffio_wfourcc(pb, "d263");
1209     ffio_wfourcc(pb, "FFMP");
1210     avio_w8(pb, 0); /* decoder version */
1211     /* FIXME use AVCodecContext level/profile, when encoder will set values */
1212     avio_w8(pb, 0xa); /* level */
1213     avio_w8(pb, 0); /* profile */
1214     return 0xf;
1215 }
1216
1217 static int mov_write_av1c_tag(AVIOContext *pb, MOVTrack *track)
1218 {
1219     int64_t pos = avio_tell(pb);
1220
1221     avio_wb32(pb, 0);
1222     ffio_wfourcc(pb, "av1C");
1223     ff_isom_write_av1c(pb, track->vos_data, track->vos_len);
1224     return update_size(pb, pos);
1225 }
1226
1227 static int mov_write_avcc_tag(AVIOContext *pb, MOVTrack *track)
1228 {
1229     int64_t pos = avio_tell(pb);
1230
1231     avio_wb32(pb, 0);
1232     ffio_wfourcc(pb, "avcC");
1233     ff_isom_write_avcc(pb, track->vos_data, track->vos_len);
1234     return update_size(pb, pos);
1235 }
1236
1237 static int mov_write_vpcc_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
1238 {
1239     int64_t pos = avio_tell(pb);
1240
1241     avio_wb32(pb, 0);
1242     ffio_wfourcc(pb, "vpcC");
1243     avio_w8(pb, 1); /* version */
1244     avio_wb24(pb, 0); /* flags */
1245     ff_isom_write_vpcc(s, pb, track->par);
1246     return update_size(pb, pos);
1247 }
1248
1249 static int mov_write_hvcc_tag(AVIOContext *pb, MOVTrack *track)
1250 {
1251     int64_t pos = avio_tell(pb);
1252
1253     avio_wb32(pb, 0);
1254     ffio_wfourcc(pb, "hvcC");
1255     if (track->tag == MKTAG('h','v','c','1'))
1256         ff_isom_write_hvcc(pb, track->vos_data, track->vos_len, 1);
1257     else
1258         ff_isom_write_hvcc(pb, track->vos_data, track->vos_len, 0);
1259     return update_size(pb, pos);
1260 }
1261
1262 /* also used by all avid codecs (dv, imx, meridien) and their variants */
1263 static int mov_write_avid_tag(AVIOContext *pb, MOVTrack *track)
1264 {
1265     int i;
1266     int interlaced;
1267     int cid;
1268     int display_width = track->par->width;
1269
1270     if (track->vos_data && track->vos_len > 0x29) {
1271         if (ff_dnxhd_parse_header_prefix(track->vos_data) != 0) {
1272             /* looks like a DNxHD bit stream */
1273             interlaced = (track->vos_data[5] & 2);
1274             cid = AV_RB32(track->vos_data + 0x28);
1275         } else {
1276             av_log(NULL, AV_LOG_WARNING, "Could not locate DNxHD bit stream in vos_data\n");
1277             return 0;
1278         }
1279     } else {
1280         av_log(NULL, AV_LOG_WARNING, "Could not locate DNxHD bit stream, vos_data too small\n");
1281         return 0;
1282     }
1283
1284     avio_wb32(pb, 24); /* size */
1285     ffio_wfourcc(pb, "ACLR");
1286     ffio_wfourcc(pb, "ACLR");
1287     ffio_wfourcc(pb, "0001");
1288     if (track->par->color_range == AVCOL_RANGE_MPEG || /* Legal range (16-235) */
1289         track->par->color_range == AVCOL_RANGE_UNSPECIFIED) {
1290         avio_wb32(pb, 1); /* Corresponds to 709 in official encoder */
1291     } else { /* Full range (0-255) */
1292         avio_wb32(pb, 2); /* Corresponds to RGB in official encoder */
1293     }
1294     avio_wb32(pb, 0); /* unknown */
1295
1296     if (track->tag == MKTAG('A','V','d','h')) {
1297         avio_wb32(pb, 32);
1298         ffio_wfourcc(pb, "ADHR");
1299         ffio_wfourcc(pb, "0001");
1300         avio_wb32(pb, cid);
1301         avio_wb32(pb, 0); /* unknown */
1302         avio_wb32(pb, 1); /* unknown */
1303         avio_wb32(pb, 0); /* unknown */
1304         avio_wb32(pb, 0); /* unknown */
1305         return 0;
1306     }
1307
1308     avio_wb32(pb, 24); /* size */
1309     ffio_wfourcc(pb, "APRG");
1310     ffio_wfourcc(pb, "APRG");
1311     ffio_wfourcc(pb, "0001");
1312     avio_wb32(pb, 1); /* unknown */
1313     avio_wb32(pb, 0); /* unknown */
1314
1315     avio_wb32(pb, 120); /* size */
1316     ffio_wfourcc(pb, "ARES");
1317     ffio_wfourcc(pb, "ARES");
1318     ffio_wfourcc(pb, "0001");
1319     avio_wb32(pb, cid); /* dnxhd cid, some id ? */
1320     if (   track->par->sample_aspect_ratio.num > 0
1321         && track->par->sample_aspect_ratio.den > 0)
1322         display_width = display_width * track->par->sample_aspect_ratio.num / track->par->sample_aspect_ratio.den;
1323     avio_wb32(pb, display_width);
1324     /* values below are based on samples created with quicktime and avid codecs */
1325     if (interlaced) {
1326         avio_wb32(pb, track->par->height / 2);
1327         avio_wb32(pb, 2); /* unknown */
1328         avio_wb32(pb, 0); /* unknown */
1329         avio_wb32(pb, 4); /* unknown */
1330     } else {
1331         avio_wb32(pb, track->par->height);
1332         avio_wb32(pb, 1); /* unknown */
1333         avio_wb32(pb, 0); /* unknown */
1334         if (track->par->height == 1080)
1335             avio_wb32(pb, 5); /* unknown */
1336         else
1337             avio_wb32(pb, 6); /* unknown */
1338     }
1339     /* padding */
1340     for (i = 0; i < 10; i++)
1341         avio_wb64(pb, 0);
1342
1343     return 0;
1344 }
1345
1346 static int mov_write_dpxe_tag(AVIOContext *pb, MOVTrack *track)
1347 {
1348     avio_wb32(pb, 12);
1349     ffio_wfourcc(pb, "DpxE");
1350     if (track->par->extradata_size >= 12 &&
1351         !memcmp(&track->par->extradata[4], "DpxE", 4)) {
1352         avio_wb32(pb, track->par->extradata[11]);
1353     } else {
1354         avio_wb32(pb, 1);
1355     }
1356     return 0;
1357 }
1358
1359 static int mov_get_dv_codec_tag(AVFormatContext *s, MOVTrack *track)
1360 {
1361     int tag;
1362
1363     if (track->par->width == 720) { /* SD */
1364         if (track->par->height == 480) { /* NTSC */
1365             if  (track->par->format == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','n');
1366             else                                            tag = MKTAG('d','v','c',' ');
1367        }else if (track->par->format == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','p');
1368         else if (track->par->format == AV_PIX_FMT_YUV420P) tag = MKTAG('d','v','c','p');
1369         else                                                tag = MKTAG('d','v','p','p');
1370     } else if (track->par->height == 720) { /* HD 720 line */
1371         if  (track->st->time_base.den == 50)                tag = MKTAG('d','v','h','q');
1372         else                                                tag = MKTAG('d','v','h','p');
1373     } else if (track->par->height == 1080) { /* HD 1080 line */
1374         if  (track->st->time_base.den == 25)                tag = MKTAG('d','v','h','5');
1375         else                                                tag = MKTAG('d','v','h','6');
1376     } else {
1377         av_log(s, AV_LOG_ERROR, "unsupported height for dv codec\n");
1378         return 0;
1379     }
1380
1381     return tag;
1382 }
1383
1384 static AVRational find_fps(AVFormatContext *s, AVStream *st)
1385 {
1386     AVRational rate = st->avg_frame_rate;
1387
1388 #if FF_API_LAVF_AVCTX
1389     FF_DISABLE_DEPRECATION_WARNINGS
1390     rate = av_inv_q(st->codec->time_base);
1391     if (av_timecode_check_frame_rate(rate) < 0) {
1392         av_log(s, AV_LOG_DEBUG, "timecode: tbc=%d/%d invalid, fallback on %d/%d\n",
1393                rate.num, rate.den, st->avg_frame_rate.num, st->avg_frame_rate.den);
1394         rate = st->avg_frame_rate;
1395     }
1396     FF_ENABLE_DEPRECATION_WARNINGS
1397 #endif
1398
1399     return rate;
1400 }
1401
1402 static int defined_frame_rate(AVFormatContext *s, AVStream *st)
1403 {
1404     AVRational rational_framerate = find_fps(s, st);
1405     int rate = 0;
1406     if (rational_framerate.den != 0)
1407         rate = av_q2d(rational_framerate);
1408     return rate;
1409 }
1410
1411 static int mov_get_mpeg2_xdcam_codec_tag(AVFormatContext *s, MOVTrack *track)
1412 {
1413     int tag = track->par->codec_tag;
1414     int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE;
1415     AVStream *st = track->st;
1416     int rate = defined_frame_rate(s, st);
1417
1418     if (!tag)
1419         tag = MKTAG('m', '2', 'v', '1'); //fallback tag
1420
1421     if (track->par->format == AV_PIX_FMT_YUV420P) {
1422         if (track->par->width == 1280 && track->par->height == 720) {
1423             if (!interlaced) {
1424                 if      (rate == 24) tag = MKTAG('x','d','v','4');
1425                 else if (rate == 25) tag = MKTAG('x','d','v','5');
1426                 else if (rate == 30) tag = MKTAG('x','d','v','1');
1427                 else if (rate == 50) tag = MKTAG('x','d','v','a');
1428                 else if (rate == 60) tag = MKTAG('x','d','v','9');
1429             }
1430         } else if (track->par->width == 1440 && track->par->height == 1080) {
1431             if (!interlaced) {
1432                 if      (rate == 24) tag = MKTAG('x','d','v','6');
1433                 else if (rate == 25) tag = MKTAG('x','d','v','7');
1434                 else if (rate == 30) tag = MKTAG('x','d','v','8');
1435             } else {
1436                 if      (rate == 25) tag = MKTAG('x','d','v','3');
1437                 else if (rate == 30) tag = MKTAG('x','d','v','2');
1438             }
1439         } else if (track->par->width == 1920 && track->par->height == 1080) {
1440             if (!interlaced) {
1441                 if      (rate == 24) tag = MKTAG('x','d','v','d');
1442                 else if (rate == 25) tag = MKTAG('x','d','v','e');
1443                 else if (rate == 30) tag = MKTAG('x','d','v','f');
1444             } else {
1445                 if      (rate == 25) tag = MKTAG('x','d','v','c');
1446                 else if (rate == 30) tag = MKTAG('x','d','v','b');
1447             }
1448         }
1449     } else if (track->par->format == AV_PIX_FMT_YUV422P) {
1450         if (track->par->width == 1280 && track->par->height == 720) {
1451             if (!interlaced) {
1452                 if      (rate == 24) tag = MKTAG('x','d','5','4');
1453                 else if (rate == 25) tag = MKTAG('x','d','5','5');
1454                 else if (rate == 30) tag = MKTAG('x','d','5','1');
1455                 else if (rate == 50) tag = MKTAG('x','d','5','a');
1456                 else if (rate == 60) tag = MKTAG('x','d','5','9');
1457             }
1458         } else if (track->par->width == 1920 && track->par->height == 1080) {
1459             if (!interlaced) {
1460                 if      (rate == 24) tag = MKTAG('x','d','5','d');
1461                 else if (rate == 25) tag = MKTAG('x','d','5','e');
1462                 else if (rate == 30) tag = MKTAG('x','d','5','f');
1463             } else {
1464                 if      (rate == 25) tag = MKTAG('x','d','5','c');
1465                 else if (rate == 30) tag = MKTAG('x','d','5','b');
1466             }
1467         }
1468     }
1469
1470     return tag;
1471 }
1472
1473 static int mov_get_h264_codec_tag(AVFormatContext *s, MOVTrack *track)
1474 {
1475     int tag = track->par->codec_tag;
1476     int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE;
1477     AVStream *st = track->st;
1478     int rate = defined_frame_rate(s, st);
1479
1480     if (!tag)
1481         tag = MKTAG('a', 'v', 'c', 'i'); //fallback tag
1482
1483     if (track->par->format == AV_PIX_FMT_YUV420P10) {
1484         if (track->par->width == 960 && track->par->height == 720) {
1485             if (!interlaced) {
1486                 if      (rate == 24) tag = MKTAG('a','i','5','p');
1487                 else if (rate == 25) tag = MKTAG('a','i','5','q');
1488                 else if (rate == 30) tag = MKTAG('a','i','5','p');
1489                 else if (rate == 50) tag = MKTAG('a','i','5','q');
1490                 else if (rate == 60) tag = MKTAG('a','i','5','p');
1491             }
1492         } else if (track->par->width == 1440 && track->par->height == 1080) {
1493             if (!interlaced) {
1494                 if      (rate == 24) tag = MKTAG('a','i','5','3');
1495                 else if (rate == 25) tag = MKTAG('a','i','5','2');
1496                 else if (rate == 30) tag = MKTAG('a','i','5','3');
1497             } else {
1498                 if      (rate == 50) tag = MKTAG('a','i','5','5');
1499                 else if (rate == 60) tag = MKTAG('a','i','5','6');
1500             }
1501         }
1502     } else if (track->par->format == AV_PIX_FMT_YUV422P10) {
1503         if (track->par->width == 1280 && track->par->height == 720) {
1504             if (!interlaced) {
1505                 if      (rate == 24) tag = MKTAG('a','i','1','p');
1506                 else if (rate == 25) tag = MKTAG('a','i','1','q');
1507                 else if (rate == 30) tag = MKTAG('a','i','1','p');
1508                 else if (rate == 50) tag = MKTAG('a','i','1','q');
1509                 else if (rate == 60) tag = MKTAG('a','i','1','p');
1510             }
1511         } else if (track->par->width == 1920 && track->par->height == 1080) {
1512             if (!interlaced) {
1513                 if      (rate == 24) tag = MKTAG('a','i','1','3');
1514                 else if (rate == 25) tag = MKTAG('a','i','1','2');
1515                 else if (rate == 30) tag = MKTAG('a','i','1','3');
1516             } else {
1517                 if      (rate == 25) tag = MKTAG('a','i','1','5');
1518                 else if (rate == 50) tag = MKTAG('a','i','1','5');
1519                 else if (rate == 60) tag = MKTAG('a','i','1','6');
1520             }
1521         } else if (   track->par->width == 4096 && track->par->height == 2160
1522                    || track->par->width == 3840 && track->par->height == 2160
1523                    || track->par->width == 2048 && track->par->height == 1080) {
1524             tag = MKTAG('a','i','v','x');
1525         }
1526     }
1527
1528     return tag;
1529 }
1530
1531 static const struct {
1532     enum AVPixelFormat pix_fmt;
1533     uint32_t tag;
1534     unsigned bps;
1535 } mov_pix_fmt_tags[] = {
1536     { AV_PIX_FMT_YUYV422, MKTAG('y','u','v','2'),  0 },
1537     { AV_PIX_FMT_YUYV422, MKTAG('y','u','v','s'),  0 },
1538     { AV_PIX_FMT_UYVY422, MKTAG('2','v','u','y'),  0 },
1539     { AV_PIX_FMT_RGB555BE,MKTAG('r','a','w',' '), 16 },
1540     { AV_PIX_FMT_RGB555LE,MKTAG('L','5','5','5'), 16 },
1541     { AV_PIX_FMT_RGB565LE,MKTAG('L','5','6','5'), 16 },
1542     { AV_PIX_FMT_RGB565BE,MKTAG('B','5','6','5'), 16 },
1543     { AV_PIX_FMT_GRAY16BE,MKTAG('b','1','6','g'), 16 },
1544     { AV_PIX_FMT_RGB24,   MKTAG('r','a','w',' '), 24 },
1545     { AV_PIX_FMT_BGR24,   MKTAG('2','4','B','G'), 24 },
1546     { AV_PIX_FMT_ARGB,    MKTAG('r','a','w',' '), 32 },
1547     { AV_PIX_FMT_BGRA,    MKTAG('B','G','R','A'), 32 },
1548     { AV_PIX_FMT_RGBA,    MKTAG('R','G','B','A'), 32 },
1549     { AV_PIX_FMT_ABGR,    MKTAG('A','B','G','R'), 32 },
1550     { AV_PIX_FMT_RGB48BE, MKTAG('b','4','8','r'), 48 },
1551 };
1552
1553 static int mov_get_dnxhd_codec_tag(AVFormatContext *s, MOVTrack *track)
1554 {
1555   int tag = MKTAG('A','V','d','n');
1556   if (track->par->profile != FF_PROFILE_UNKNOWN &&
1557       track->par->profile != FF_PROFILE_DNXHD)
1558       tag = MKTAG('A','V','d','h');
1559   return tag;
1560 }
1561
1562 static int mov_get_rawvideo_codec_tag(AVFormatContext *s, MOVTrack *track)
1563 {
1564     int tag = track->par->codec_tag;
1565     int i;
1566     enum AVPixelFormat pix_fmt;
1567
1568     for (i = 0; i < FF_ARRAY_ELEMS(mov_pix_fmt_tags); i++) {
1569         if (track->par->format == mov_pix_fmt_tags[i].pix_fmt) {
1570             tag = mov_pix_fmt_tags[i].tag;
1571             track->par->bits_per_coded_sample = mov_pix_fmt_tags[i].bps;
1572             if (track->par->codec_tag == mov_pix_fmt_tags[i].tag)
1573                 break;
1574         }
1575     }
1576
1577     pix_fmt = avpriv_find_pix_fmt(avpriv_pix_fmt_bps_mov,
1578                                   track->par->bits_per_coded_sample);
1579     if (tag == MKTAG('r','a','w',' ') &&
1580         track->par->format != pix_fmt &&
1581         track->par->format != AV_PIX_FMT_GRAY8 &&
1582         track->par->format != AV_PIX_FMT_NONE)
1583         av_log(s, AV_LOG_ERROR, "%s rawvideo cannot be written to mov, output file will be unreadable\n",
1584                av_get_pix_fmt_name(track->par->format));
1585     return tag;
1586 }
1587
1588 static unsigned int mov_get_codec_tag(AVFormatContext *s, MOVTrack *track)
1589 {
1590     unsigned int tag = track->par->codec_tag;
1591
1592     if (!tag || (s->strict_std_compliance >= FF_COMPLIANCE_NORMAL &&
1593                  (track->par->codec_id == AV_CODEC_ID_DVVIDEO ||
1594                   track->par->codec_id == AV_CODEC_ID_RAWVIDEO ||
1595                   track->par->codec_id == AV_CODEC_ID_H263 ||
1596                   track->par->codec_id == AV_CODEC_ID_H264 ||
1597                   track->par->codec_id == AV_CODEC_ID_DNXHD ||
1598                   track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO ||
1599                   av_get_bits_per_sample(track->par->codec_id)))) { // pcm audio
1600         if (track->par->codec_id == AV_CODEC_ID_DVVIDEO)
1601             tag = mov_get_dv_codec_tag(s, track);
1602         else if (track->par->codec_id == AV_CODEC_ID_RAWVIDEO)
1603             tag = mov_get_rawvideo_codec_tag(s, track);
1604         else if (track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO)
1605             tag = mov_get_mpeg2_xdcam_codec_tag(s, track);
1606         else if (track->par->codec_id == AV_CODEC_ID_H264)
1607             tag = mov_get_h264_codec_tag(s, track);
1608         else if (track->par->codec_id == AV_CODEC_ID_DNXHD)
1609             tag = mov_get_dnxhd_codec_tag(s, track);
1610         else if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
1611             tag = ff_codec_get_tag(ff_codec_movvideo_tags, track->par->codec_id);
1612             if (!tag) { // if no mac fcc found, try with Microsoft tags
1613                 tag = ff_codec_get_tag(ff_codec_bmp_tags, track->par->codec_id);
1614                 if (tag)
1615                     av_log(s, AV_LOG_WARNING, "Using MS style video codec tag, "
1616                            "the file may be unplayable!\n");
1617             }
1618         } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
1619             tag = ff_codec_get_tag(ff_codec_movaudio_tags, track->par->codec_id);
1620             if (!tag) { // if no mac fcc found, try with Microsoft tags
1621                 int ms_tag = ff_codec_get_tag(ff_codec_wav_tags, track->par->codec_id);
1622                 if (ms_tag) {
1623                     tag = MKTAG('m', 's', ((ms_tag >> 8) & 0xff), (ms_tag & 0xff));
1624                     av_log(s, AV_LOG_WARNING, "Using MS style audio codec tag, "
1625                            "the file may be unplayable!\n");
1626                 }
1627             }
1628         } else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)
1629             tag = ff_codec_get_tag(ff_codec_movsubtitle_tags, track->par->codec_id);
1630     }
1631
1632     return tag;
1633 }
1634
1635 static const AVCodecTag codec_cover_image_tags[] = {
1636     { AV_CODEC_ID_MJPEG,  0xD },
1637     { AV_CODEC_ID_PNG,    0xE },
1638     { AV_CODEC_ID_BMP,    0x1B },
1639     { AV_CODEC_ID_NONE, 0 },
1640 };
1641
1642 static unsigned int validate_codec_tag(const AVCodecTag *const *tags,
1643                                        unsigned int tag, int codec_id)
1644 {
1645     int i;
1646
1647     /**
1648      * Check that tag + id is in the table
1649      */
1650     for (i = 0; tags && tags[i]; i++) {
1651         const AVCodecTag *codec_tags = tags[i];
1652         while (codec_tags->id != AV_CODEC_ID_NONE) {
1653             if (avpriv_toupper4(codec_tags->tag) == avpriv_toupper4(tag) &&
1654                 codec_tags->id == codec_id)
1655                 return codec_tags->tag;
1656             codec_tags++;
1657         }
1658     }
1659     return 0;
1660 }
1661
1662 static unsigned int mov_find_codec_tag(AVFormatContext *s, MOVTrack *track)
1663 {
1664     if (is_cover_image(track->st))
1665         return ff_codec_get_tag(codec_cover_image_tags, track->par->codec_id);
1666
1667     if (track->mode == MODE_IPOD)
1668         if (!av_match_ext(s->url, "m4a") &&
1669             !av_match_ext(s->url, "m4v") &&
1670             !av_match_ext(s->url, "m4b"))
1671             av_log(s, AV_LOG_WARNING, "Warning, extension is not .m4a nor .m4v "
1672                    "Quicktime/Ipod might not play the file\n");
1673
1674     if (track->mode == MODE_MOV) {
1675         return mov_get_codec_tag(s, track);
1676     } else
1677         return validate_codec_tag(s->oformat->codec_tag, track->par->codec_tag,
1678                                   track->par->codec_id);
1679 }
1680
1681 /** Write uuid atom.
1682  * Needed to make file play in iPods running newest firmware
1683  * goes after avcC atom in moov.trak.mdia.minf.stbl.stsd.avc1
1684  */
1685 static int mov_write_uuid_tag_ipod(AVIOContext *pb)
1686 {
1687     avio_wb32(pb, 28);
1688     ffio_wfourcc(pb, "uuid");
1689     avio_wb32(pb, 0x6b6840f2);
1690     avio_wb32(pb, 0x5f244fc5);
1691     avio_wb32(pb, 0xba39a51b);
1692     avio_wb32(pb, 0xcf0323f3);
1693     avio_wb32(pb, 0x0);
1694     return 28;
1695 }
1696
1697 static const uint16_t fiel_data[] = {
1698     0x0000, 0x0100, 0x0201, 0x0206, 0x0209, 0x020e
1699 };
1700
1701 static int mov_write_fiel_tag(AVIOContext *pb, MOVTrack *track, int field_order)
1702 {
1703     unsigned mov_field_order = 0;
1704     if (field_order < FF_ARRAY_ELEMS(fiel_data))
1705         mov_field_order = fiel_data[field_order];
1706     else
1707         return 0;
1708     avio_wb32(pb, 10);
1709     ffio_wfourcc(pb, "fiel");
1710     avio_wb16(pb, mov_field_order);
1711     return 10;
1712 }
1713
1714 static int mov_write_subtitle_tag(AVIOContext *pb, MOVTrack *track)
1715 {
1716     int64_t pos = avio_tell(pb);
1717     avio_wb32(pb, 0);    /* size */
1718     avio_wl32(pb, track->tag); // store it byteswapped
1719     avio_wb32(pb, 0);    /* Reserved */
1720     avio_wb16(pb, 0);    /* Reserved */
1721     avio_wb16(pb, 1);    /* Data-reference index */
1722
1723     if (track->par->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
1724         mov_write_esds_tag(pb, track);
1725     else if (track->par->extradata_size)
1726         avio_write(pb, track->par->extradata, track->par->extradata_size);
1727
1728     return update_size(pb, pos);
1729 }
1730
1731 static int mov_write_st3d_tag(AVFormatContext *s, AVIOContext *pb, AVStereo3D *stereo_3d)
1732 {
1733     int8_t stereo_mode;
1734
1735     if (stereo_3d->flags != 0) {
1736         av_log(s, AV_LOG_WARNING, "Unsupported stereo_3d flags %x. st3d not written.\n", stereo_3d->flags);
1737         return 0;
1738     }
1739
1740     switch (stereo_3d->type) {
1741     case AV_STEREO3D_2D:
1742         stereo_mode = 0;
1743         break;
1744     case AV_STEREO3D_TOPBOTTOM:
1745         stereo_mode = 1;
1746         break;
1747     case AV_STEREO3D_SIDEBYSIDE:
1748         stereo_mode = 2;
1749         break;
1750     default:
1751         av_log(s, AV_LOG_WARNING, "Unsupported stereo_3d type %s. st3d not written.\n", av_stereo3d_type_name(stereo_3d->type));
1752         return 0;
1753     }
1754     avio_wb32(pb, 13); /* size */
1755     ffio_wfourcc(pb, "st3d");
1756     avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1757     avio_w8(pb, stereo_mode);
1758     return 13;
1759 }
1760
1761 static int mov_write_sv3d_tag(AVFormatContext *s, AVIOContext *pb, AVSphericalMapping *spherical_mapping)
1762 {
1763     int64_t sv3d_pos, svhd_pos, proj_pos;
1764     const char* metadata_source = s->flags & AVFMT_FLAG_BITEXACT ? "Lavf" : LIBAVFORMAT_IDENT;
1765
1766     if (spherical_mapping->projection != AV_SPHERICAL_EQUIRECTANGULAR &&
1767         spherical_mapping->projection != AV_SPHERICAL_EQUIRECTANGULAR_TILE &&
1768         spherical_mapping->projection != AV_SPHERICAL_CUBEMAP) {
1769         av_log(s, AV_LOG_WARNING, "Unsupported projection %d. sv3d not written.\n", spherical_mapping->projection);
1770         return 0;
1771     }
1772
1773     sv3d_pos = avio_tell(pb);
1774     avio_wb32(pb, 0);  /* size */
1775     ffio_wfourcc(pb, "sv3d");
1776
1777     svhd_pos = avio_tell(pb);
1778     avio_wb32(pb, 0);  /* size */
1779     ffio_wfourcc(pb, "svhd");
1780     avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1781     avio_put_str(pb, metadata_source);
1782     update_size(pb, svhd_pos);
1783
1784     proj_pos = avio_tell(pb);
1785     avio_wb32(pb, 0); /* size */
1786     ffio_wfourcc(pb, "proj");
1787
1788     avio_wb32(pb, 24); /* size */
1789     ffio_wfourcc(pb, "prhd");
1790     avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1791     avio_wb32(pb, spherical_mapping->yaw);
1792     avio_wb32(pb, spherical_mapping->pitch);
1793     avio_wb32(pb, spherical_mapping->roll);
1794
1795     switch (spherical_mapping->projection) {
1796     case AV_SPHERICAL_EQUIRECTANGULAR:
1797     case AV_SPHERICAL_EQUIRECTANGULAR_TILE:
1798         avio_wb32(pb, 28);    /* size */
1799         ffio_wfourcc(pb, "equi");
1800         avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1801         avio_wb32(pb, spherical_mapping->bound_top);
1802         avio_wb32(pb, spherical_mapping->bound_bottom);
1803         avio_wb32(pb, spherical_mapping->bound_left);
1804         avio_wb32(pb, spherical_mapping->bound_right);
1805         break;
1806     case AV_SPHERICAL_CUBEMAP:
1807         avio_wb32(pb, 20);    /* size */
1808         ffio_wfourcc(pb, "cbmp");
1809         avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1810         avio_wb32(pb, 0); /* layout */
1811         avio_wb32(pb, spherical_mapping->padding); /* padding */
1812         break;
1813     }
1814     update_size(pb, proj_pos);
1815
1816     return update_size(pb, sv3d_pos);
1817 }
1818
1819 static int mov_write_clap_tag(AVIOContext *pb, MOVTrack *track)
1820 {
1821     avio_wb32(pb, 40);
1822     ffio_wfourcc(pb, "clap");
1823     avio_wb32(pb, track->par->width); /* apertureWidth_N */
1824     avio_wb32(pb, 1); /* apertureWidth_D (= 1) */
1825     avio_wb32(pb, track->height); /* apertureHeight_N */
1826     avio_wb32(pb, 1); /* apertureHeight_D (= 1) */
1827     avio_wb32(pb, 0); /* horizOff_N (= 0) */
1828     avio_wb32(pb, 1); /* horizOff_D (= 1) */
1829     avio_wb32(pb, 0); /* vertOff_N (= 0) */
1830     avio_wb32(pb, 1); /* vertOff_D (= 1) */
1831     return 40;
1832 }
1833
1834 static int mov_write_pasp_tag(AVIOContext *pb, MOVTrack *track)
1835 {
1836     AVRational sar;
1837     av_reduce(&sar.num, &sar.den, track->par->sample_aspect_ratio.num,
1838               track->par->sample_aspect_ratio.den, INT_MAX);
1839
1840     avio_wb32(pb, 16);
1841     ffio_wfourcc(pb, "pasp");
1842     avio_wb32(pb, sar.num);
1843     avio_wb32(pb, sar.den);
1844     return 16;
1845 }
1846
1847 static int mov_write_gama_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track, double gamma)
1848 {
1849     uint32_t gama = 0;
1850     if (gamma <= 0.0) {
1851         gamma = avpriv_get_gamma_from_trc(track->par->color_trc);
1852     }
1853     av_log(s, AV_LOG_DEBUG, "gamma value %g\n", gamma);
1854
1855     if (gamma > 1e-6) {
1856         gama = (uint32_t)lrint((double)(1<<16) * gamma);
1857         av_log(s, AV_LOG_DEBUG, "writing gama value %"PRId32"\n", gama);
1858
1859         av_assert0(track->mode == MODE_MOV);
1860         avio_wb32(pb, 12);
1861         ffio_wfourcc(pb, "gama");
1862         avio_wb32(pb, gama);
1863         return 12;
1864     } else {
1865         av_log(s, AV_LOG_WARNING, "gamma value unknown, unable to write gama atom\n");
1866     }
1867     return 0;
1868 }
1869
1870 static int mov_write_colr_tag(AVIOContext *pb, MOVTrack *track, int prefer_icc)
1871 {
1872     int64_t pos = avio_tell(pb);
1873
1874     // Ref (MOV): https://developer.apple.com/library/mac/technotes/tn2162/_index.html#//apple_ref/doc/uid/DTS40013070-CH1-TNTAG9
1875     // Ref (MP4): ISO/IEC 14496-12:2012
1876
1877     const uint8_t *icc_profile;
1878     int icc_profile_size;
1879
1880     if (prefer_icc) {
1881         icc_profile = av_stream_get_side_data(track->st, AV_PKT_DATA_ICC_PROFILE, &icc_profile_size);
1882
1883         if (icc_profile) {
1884             avio_wb32(pb, 12 + icc_profile_size);
1885             ffio_wfourcc(pb, "colr");
1886             ffio_wfourcc(pb, "prof");
1887             avio_write(pb, icc_profile, icc_profile_size);
1888             return 12 + icc_profile_size;
1889         }
1890         else {
1891             av_log(NULL, AV_LOG_INFO, "no ICC profile found, will write nclx/nclc colour info instead\n");
1892         }
1893     }
1894
1895     /* We should only ever be called by MOV or MP4. */
1896     av_assert0(track->mode == MODE_MOV || track->mode == MODE_MP4);
1897
1898     avio_wb32(pb, 0); /* size */
1899     ffio_wfourcc(pb, "colr");
1900     if (track->mode == MODE_MP4)
1901         ffio_wfourcc(pb, "nclx");
1902     else
1903         ffio_wfourcc(pb, "nclc");
1904     // Do not try to guess the color info if it is AVCOL_PRI_UNSPECIFIED.
1905     // e.g., Dolby Vision for Apple devices should be set to AVCOL_PRI_UNSPECIFIED. See
1906     // https://developer.apple.com/av-foundation/High-Dynamic-Range-Metadata-for-Apple-Devices.pdf
1907     avio_wb16(pb, track->par->color_primaries);
1908     avio_wb16(pb, track->par->color_trc);
1909     avio_wb16(pb, track->par->color_space);
1910     if (track->mode == MODE_MP4) {
1911         int full_range = track->par->color_range == AVCOL_RANGE_JPEG;
1912         avio_w8(pb, full_range << 7);
1913     }
1914
1915     return update_size(pb, pos);
1916 }
1917
1918 static int mov_write_clli_tag(AVIOContext *pb, MOVTrack *track)
1919 {
1920     const uint8_t *side_data;
1921     const AVContentLightMetadata *content_light_metadata;
1922
1923     side_data = av_stream_get_side_data(track->st, AV_PKT_DATA_CONTENT_LIGHT_LEVEL, NULL);
1924     if (!side_data) {
1925         av_log(NULL, AV_LOG_VERBOSE, "Not writing 'clli' atom. No content light level info.\n");
1926         return 0;
1927     }
1928     content_light_metadata = (const AVContentLightMetadata*)side_data;
1929
1930     avio_wb32(pb, 12); // size
1931     ffio_wfourcc(pb, "clli");
1932     avio_wb16(pb, content_light_metadata->MaxCLL);
1933     avio_wb16(pb, content_light_metadata->MaxFALL);
1934     return 12;
1935 }
1936
1937 static inline int64_t rescale_mdcv(AVRational q, int b)
1938 {
1939     return av_rescale(q.num, b, q.den);
1940 }
1941
1942 static int mov_write_mdcv_tag(AVIOContext *pb, MOVTrack *track)
1943 {
1944     const int chroma_den = 50000;
1945     const int luma_den = 10000;
1946     const uint8_t *side_data;
1947     const AVMasteringDisplayMetadata *metadata;
1948
1949     side_data = av_stream_get_side_data(track->st, AV_PKT_DATA_MASTERING_DISPLAY_METADATA, NULL);
1950     metadata = (const AVMasteringDisplayMetadata*)side_data;
1951     if (!metadata || !metadata->has_primaries || !metadata->has_luminance) {
1952         av_log(NULL, AV_LOG_VERBOSE, "Not writing 'mdcv' atom. Missing mastering metadata.\n");
1953         return 0;
1954     }
1955
1956     avio_wb32(pb, 32); // size
1957     ffio_wfourcc(pb, "mdcv");
1958     avio_wb16(pb, rescale_mdcv(metadata->display_primaries[1][0], chroma_den));
1959     avio_wb16(pb, rescale_mdcv(metadata->display_primaries[1][1], chroma_den));
1960     avio_wb16(pb, rescale_mdcv(metadata->display_primaries[2][0], chroma_den));
1961     avio_wb16(pb, rescale_mdcv(metadata->display_primaries[2][1], chroma_den));
1962     avio_wb16(pb, rescale_mdcv(metadata->display_primaries[0][0], chroma_den));
1963     avio_wb16(pb, rescale_mdcv(metadata->display_primaries[0][1], chroma_den));
1964     avio_wb16(pb, rescale_mdcv(metadata->white_point[0], chroma_den));
1965     avio_wb16(pb, rescale_mdcv(metadata->white_point[1], chroma_den));
1966     avio_wb32(pb, rescale_mdcv(metadata->max_luminance, luma_den));
1967     avio_wb32(pb, rescale_mdcv(metadata->min_luminance, luma_den));
1968     return 32;
1969 }
1970
1971 static void find_compressor(char * compressor_name, int len, MOVTrack *track)
1972 {
1973     AVDictionaryEntry *encoder;
1974     int xdcam_res =  (track->par->width == 1280 && track->par->height == 720)
1975                   || (track->par->width == 1440 && track->par->height == 1080)
1976                   || (track->par->width == 1920 && track->par->height == 1080);
1977
1978     if (track->mode == MODE_MOV &&
1979         (encoder = av_dict_get(track->st->metadata, "encoder", NULL, 0))) {
1980         av_strlcpy(compressor_name, encoder->value, 32);
1981     } else if (track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO && xdcam_res) {
1982         int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE;
1983         AVStream *st = track->st;
1984         int rate = defined_frame_rate(NULL, st);
1985         av_strlcatf(compressor_name, len, "XDCAM");
1986         if (track->par->format == AV_PIX_FMT_YUV422P) {
1987             av_strlcatf(compressor_name, len, " HD422");
1988         } else if(track->par->width == 1440) {
1989             av_strlcatf(compressor_name, len, " HD");
1990         } else
1991             av_strlcatf(compressor_name, len, " EX");
1992
1993         av_strlcatf(compressor_name, len, " %d%c", track->par->height, interlaced ? 'i' : 'p');
1994
1995         av_strlcatf(compressor_name, len, "%d", rate * (interlaced + 1));
1996     }
1997 }
1998
1999 static int mov_write_video_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
2000 {
2001     int64_t pos = avio_tell(pb);
2002     char compressor_name[32] = { 0 };
2003     int avid = 0;
2004
2005     int uncompressed_ycbcr = ((track->par->codec_id == AV_CODEC_ID_RAWVIDEO && track->par->format == AV_PIX_FMT_UYVY422)
2006                            || (track->par->codec_id == AV_CODEC_ID_RAWVIDEO && track->par->format == AV_PIX_FMT_YUYV422)
2007                            ||  track->par->codec_id == AV_CODEC_ID_V308
2008                            ||  track->par->codec_id == AV_CODEC_ID_V408
2009                            ||  track->par->codec_id == AV_CODEC_ID_V410
2010                            ||  track->par->codec_id == AV_CODEC_ID_V210);
2011
2012     avio_wb32(pb, 0); /* size */
2013     if (mov->encryption_scheme != MOV_ENC_NONE) {
2014         ffio_wfourcc(pb, "encv");
2015     } else {
2016         avio_wl32(pb, track->tag); // store it byteswapped
2017     }
2018     avio_wb32(pb, 0); /* Reserved */
2019     avio_wb16(pb, 0); /* Reserved */
2020     avio_wb16(pb, 1); /* Data-reference index */
2021
2022     if (uncompressed_ycbcr) {
2023         avio_wb16(pb, 2); /* Codec stream version */
2024     } else {
2025         avio_wb16(pb, 0); /* Codec stream version */
2026     }
2027     avio_wb16(pb, 0); /* Codec stream revision (=0) */
2028     if (track->mode == MODE_MOV) {
2029         ffio_wfourcc(pb, "FFMP"); /* Vendor */
2030         if (track->par->codec_id == AV_CODEC_ID_RAWVIDEO || uncompressed_ycbcr) {
2031             avio_wb32(pb, 0); /* Temporal Quality */
2032             avio_wb32(pb, 0x400); /* Spatial Quality = lossless*/
2033         } else {
2034             avio_wb32(pb, 0x200); /* Temporal Quality = normal */
2035             avio_wb32(pb, 0x200); /* Spatial Quality = normal */
2036         }
2037     } else {
2038         avio_wb32(pb, 0); /* Reserved */
2039         avio_wb32(pb, 0); /* Reserved */
2040         avio_wb32(pb, 0); /* Reserved */
2041     }
2042     avio_wb16(pb, track->par->width); /* Video width */
2043     avio_wb16(pb, track->height); /* Video height */
2044     avio_wb32(pb, 0x00480000); /* Horizontal resolution 72dpi */
2045     avio_wb32(pb, 0x00480000); /* Vertical resolution 72dpi */
2046     avio_wb32(pb, 0); /* Data size (= 0) */
2047     avio_wb16(pb, 1); /* Frame count (= 1) */
2048
2049     /* FIXME not sure, ISO 14496-1 draft where it shall be set to 0 */
2050     find_compressor(compressor_name, 32, track);
2051     avio_w8(pb, strlen(compressor_name));
2052     avio_write(pb, compressor_name, 31);
2053
2054     if (track->mode == MODE_MOV &&
2055        (track->par->codec_id == AV_CODEC_ID_V410 || track->par->codec_id == AV_CODEC_ID_V210))
2056         avio_wb16(pb, 0x18);
2057     else if (track->mode == MODE_MOV && track->par->bits_per_coded_sample)
2058         avio_wb16(pb, track->par->bits_per_coded_sample |
2059                   (track->par->format == AV_PIX_FMT_GRAY8 ? 0x20 : 0));
2060     else
2061         avio_wb16(pb, 0x18); /* Reserved */
2062
2063     if (track->mode == MODE_MOV && track->par->format == AV_PIX_FMT_PAL8) {
2064         int pal_size = 1 << track->par->bits_per_coded_sample;
2065         int i;
2066         avio_wb16(pb, 0);             /* Color table ID */
2067         avio_wb32(pb, 0);             /* Color table seed */
2068         avio_wb16(pb, 0x8000);        /* Color table flags */
2069         avio_wb16(pb, pal_size - 1);  /* Color table size (zero-relative) */
2070         for (i = 0; i < pal_size; i++) {
2071             uint32_t rgb = track->palette[i];
2072             uint16_t r = (rgb >> 16) & 0xff;
2073             uint16_t g = (rgb >> 8)  & 0xff;
2074             uint16_t b = rgb         & 0xff;
2075             avio_wb16(pb, 0);
2076             avio_wb16(pb, (r << 8) | r);
2077             avio_wb16(pb, (g << 8) | g);
2078             avio_wb16(pb, (b << 8) | b);
2079         }
2080     } else
2081         avio_wb16(pb, 0xffff); /* Reserved */
2082
2083     if (track->tag == MKTAG('m','p','4','v'))
2084         mov_write_esds_tag(pb, track);
2085     else if (track->par->codec_id == AV_CODEC_ID_H263)
2086         mov_write_d263_tag(pb);
2087     else if (track->par->codec_id == AV_CODEC_ID_AVUI ||
2088             track->par->codec_id == AV_CODEC_ID_SVQ3) {
2089         mov_write_extradata_tag(pb, track);
2090         avio_wb32(pb, 0);
2091     } else if (track->par->codec_id == AV_CODEC_ID_DNXHD) {
2092         mov_write_avid_tag(pb, track);
2093         avid = 1;
2094     } else if (track->par->codec_id == AV_CODEC_ID_HEVC)
2095         mov_write_hvcc_tag(pb, track);
2096     else if (track->par->codec_id == AV_CODEC_ID_H264 && !TAG_IS_AVCI(track->tag)) {
2097         mov_write_avcc_tag(pb, track);
2098         if (track->mode == MODE_IPOD)
2099             mov_write_uuid_tag_ipod(pb);
2100     } else if (track->par->codec_id == AV_CODEC_ID_VP9) {
2101         mov_write_vpcc_tag(mov->fc, pb, track);
2102     } else if (track->par->codec_id == AV_CODEC_ID_AV1) {
2103         mov_write_av1c_tag(pb, track);
2104     } else if (track->par->codec_id == AV_CODEC_ID_VC1 && track->vos_len > 0)
2105         mov_write_dvc1_tag(pb, track);
2106     else if (track->par->codec_id == AV_CODEC_ID_VP6F ||
2107              track->par->codec_id == AV_CODEC_ID_VP6A) {
2108         /* Don't write any potential extradata here - the cropping
2109          * is signalled via the normal width/height fields. */
2110     } else if (track->par->codec_id == AV_CODEC_ID_R10K) {
2111         if (track->par->codec_tag == MKTAG('R','1','0','k'))
2112             mov_write_dpxe_tag(pb, track);
2113     } else if (track->vos_len > 0)
2114         mov_write_glbl_tag(pb, track);
2115
2116     if (track->par->codec_id != AV_CODEC_ID_H264 &&
2117         track->par->codec_id != AV_CODEC_ID_MPEG4 &&
2118         track->par->codec_id != AV_CODEC_ID_DNXHD) {
2119         int field_order = track->par->field_order;
2120
2121 #if FF_API_LAVF_AVCTX
2122     FF_DISABLE_DEPRECATION_WARNINGS
2123     if (field_order != track->st->codec->field_order && track->st->codec->field_order != AV_FIELD_UNKNOWN)
2124         field_order = track->st->codec->field_order;
2125     FF_ENABLE_DEPRECATION_WARNINGS
2126 #endif
2127
2128         if (field_order != AV_FIELD_UNKNOWN)
2129             mov_write_fiel_tag(pb, track, field_order);
2130     }
2131
2132     if (mov->flags & FF_MOV_FLAG_WRITE_GAMA) {
2133         if (track->mode == MODE_MOV)
2134             mov_write_gama_tag(s, pb, track, mov->gamma);
2135         else
2136             av_log(mov->fc, AV_LOG_WARNING, "Not writing 'gama' atom. Format is not MOV.\n");
2137     }
2138     if (mov->flags & FF_MOV_FLAG_WRITE_COLR) {
2139         if (track->mode == MODE_MOV || track->mode == MODE_MP4)
2140             mov_write_colr_tag(pb, track, mov->flags & FF_MOV_FLAG_PREFER_ICC);
2141         else
2142             av_log(mov->fc, AV_LOG_WARNING, "Not writing 'colr' atom. Format is not MOV or MP4.\n");
2143     }
2144     if (track->mode == MODE_MOV || track->mode == MODE_MP4) {
2145         mov_write_clli_tag(pb, track);
2146         mov_write_mdcv_tag(pb, track);
2147     }
2148
2149     if (track->mode == MODE_MP4 && mov->fc->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL) {
2150         AVStereo3D* stereo_3d = (AVStereo3D*) av_stream_get_side_data(track->st, AV_PKT_DATA_STEREO3D, NULL);
2151         AVSphericalMapping* spherical_mapping = (AVSphericalMapping*)av_stream_get_side_data(track->st, AV_PKT_DATA_SPHERICAL, NULL);
2152
2153         if (stereo_3d)
2154             mov_write_st3d_tag(s, pb, stereo_3d);
2155         if (spherical_mapping)
2156             mov_write_sv3d_tag(mov->fc, pb, spherical_mapping);
2157     }
2158
2159     if (track->par->sample_aspect_ratio.den && track->par->sample_aspect_ratio.num) {
2160         mov_write_pasp_tag(pb, track);
2161     }
2162
2163     if (uncompressed_ycbcr){
2164         mov_write_clap_tag(pb, track);
2165     }
2166
2167     if (mov->encryption_scheme != MOV_ENC_NONE) {
2168         ff_mov_cenc_write_sinf_tag(track, pb, mov->encryption_kid);
2169     }
2170
2171     /* extra padding for avid stsd */
2172     /* https://developer.apple.com/library/mac/documentation/QuickTime/QTFF/QTFFChap2/qtff2.html#//apple_ref/doc/uid/TP40000939-CH204-61112 */
2173     if (avid)
2174         avio_wb32(pb, 0);
2175
2176     return update_size(pb, pos);
2177 }
2178
2179 static int mov_write_rtp_tag(AVIOContext *pb, MOVTrack *track)
2180 {
2181     int64_t pos = avio_tell(pb);
2182     avio_wb32(pb, 0); /* size */
2183     ffio_wfourcc(pb, "rtp ");
2184     avio_wb32(pb, 0); /* Reserved */
2185     avio_wb16(pb, 0); /* Reserved */
2186     avio_wb16(pb, 1); /* Data-reference index */
2187
2188     avio_wb16(pb, 1); /* Hint track version */
2189     avio_wb16(pb, 1); /* Highest compatible version */
2190     avio_wb32(pb, track->max_packet_size); /* Max packet size */
2191
2192     avio_wb32(pb, 12); /* size */
2193     ffio_wfourcc(pb, "tims");
2194     avio_wb32(pb, track->timescale);
2195
2196     return update_size(pb, pos);
2197 }
2198
2199 static int mov_write_source_reference_tag(AVIOContext *pb, MOVTrack *track, const char *reel_name)
2200 {
2201     uint64_t str_size =strlen(reel_name);
2202     int64_t pos = avio_tell(pb);
2203
2204     if (str_size >= UINT16_MAX){
2205         av_log(NULL, AV_LOG_ERROR, "reel_name length %"PRIu64" is too large\n", str_size);
2206         avio_wb16(pb, 0);
2207         return AVERROR(EINVAL);
2208     }
2209
2210     avio_wb32(pb, 0);                              /* size */
2211     ffio_wfourcc(pb, "name");                      /* Data format */
2212     avio_wb16(pb, str_size);                       /* string size */
2213     avio_wb16(pb, track->language);                /* langcode */
2214     avio_write(pb, reel_name, str_size);           /* reel name */
2215     return update_size(pb,pos);
2216 }
2217
2218 static int mov_write_tmcd_tag(AVIOContext *pb, MOVTrack *track)
2219 {
2220     int64_t pos = avio_tell(pb);
2221 #if 1
2222     int frame_duration;
2223     int nb_frames;
2224     AVDictionaryEntry *t = NULL;
2225
2226     if (!track->st->avg_frame_rate.num || !track->st->avg_frame_rate.den) {
2227 #if FF_API_LAVF_AVCTX
2228     FF_DISABLE_DEPRECATION_WARNINGS
2229         frame_duration = av_rescale(track->timescale, track->st->codec->time_base.num, track->st->codec->time_base.den);
2230         nb_frames      = ROUNDED_DIV(track->st->codec->time_base.den, track->st->codec->time_base.num);
2231     FF_ENABLE_DEPRECATION_WARNINGS
2232 #else
2233         av_log(NULL, AV_LOG_ERROR, "avg_frame_rate not set for tmcd track.\n");
2234         return AVERROR(EINVAL);
2235 #endif
2236     } else {
2237         frame_duration = av_rescale(track->timescale, track->st->avg_frame_rate.num, track->st->avg_frame_rate.den);
2238         nb_frames      = ROUNDED_DIV(track->st->avg_frame_rate.den, track->st->avg_frame_rate.num);
2239     }
2240
2241     if (nb_frames > 255) {
2242         av_log(NULL, AV_LOG_ERROR, "fps %d is too large\n", nb_frames);
2243         return AVERROR(EINVAL);
2244     }
2245
2246     avio_wb32(pb, 0); /* size */
2247     ffio_wfourcc(pb, "tmcd");               /* Data format */
2248     avio_wb32(pb, 0);                       /* Reserved */
2249     avio_wb32(pb, 1);                       /* Data reference index */
2250     avio_wb32(pb, 0);                       /* Flags */
2251     avio_wb32(pb, track->timecode_flags);   /* Flags (timecode) */
2252     avio_wb32(pb, track->timescale);        /* Timescale */
2253     avio_wb32(pb, frame_duration);          /* Frame duration */
2254     avio_w8(pb, nb_frames);                 /* Number of frames */
2255     avio_w8(pb, 0);                         /* Reserved */
2256
2257     t = av_dict_get(track->st->metadata, "reel_name", NULL, 0);
2258     if (t && utf8len(t->value) && track->mode != MODE_MP4)
2259         mov_write_source_reference_tag(pb, track, t->value);
2260     else
2261         avio_wb16(pb, 0); /* zero size */
2262 #else
2263
2264     avio_wb32(pb, 0); /* size */
2265     ffio_wfourcc(pb, "tmcd");               /* Data format */
2266     avio_wb32(pb, 0);                       /* Reserved */
2267     avio_wb32(pb, 1);                       /* Data reference index */
2268     if (track->par->extradata_size)
2269         avio_write(pb, track->par->extradata, track->par->extradata_size);
2270 #endif
2271     return update_size(pb, pos);
2272 }
2273
2274 static int mov_write_gpmd_tag(AVIOContext *pb, const MOVTrack *track)
2275 {
2276     int64_t pos = avio_tell(pb);
2277     avio_wb32(pb, 0); /* size */
2278     ffio_wfourcc(pb, "gpmd");
2279     avio_wb32(pb, 0); /* Reserved */
2280     avio_wb16(pb, 0); /* Reserved */
2281     avio_wb16(pb, 1); /* Data-reference index */
2282     avio_wb32(pb, 0); /* Reserved */
2283     return update_size(pb, pos);
2284 }
2285
2286 static int mov_write_stsd_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
2287 {
2288     int64_t pos = avio_tell(pb);
2289     int ret = 0;
2290     avio_wb32(pb, 0); /* size */
2291     ffio_wfourcc(pb, "stsd");
2292     avio_wb32(pb, 0); /* version & flags */
2293     avio_wb32(pb, 1); /* entry count */
2294     if (track->par->codec_type == AVMEDIA_TYPE_VIDEO)
2295         ret = mov_write_video_tag(s, pb, mov, track);
2296     else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
2297         ret = mov_write_audio_tag(s, pb, mov, track);
2298     else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)
2299         ret = mov_write_subtitle_tag(pb, track);
2300     else if (track->par->codec_tag == MKTAG('r','t','p',' '))
2301         ret = mov_write_rtp_tag(pb, track);
2302     else if (track->par->codec_tag == MKTAG('t','m','c','d'))
2303         ret = mov_write_tmcd_tag(pb, track);
2304     else if (track->par->codec_tag == MKTAG('g','p','m','d'))
2305         ret = mov_write_gpmd_tag(pb, track);
2306
2307     if (ret < 0)
2308         return ret;
2309
2310     return update_size(pb, pos);
2311 }
2312
2313 static int mov_write_ctts_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
2314 {
2315     MOVMuxContext *mov = s->priv_data;
2316     MOVStts *ctts_entries;
2317     uint32_t entries = 0;
2318     uint32_t atom_size;
2319     int i;
2320
2321     ctts_entries = av_malloc_array((track->entry + 1), sizeof(*ctts_entries)); /* worst case */
2322     if (!ctts_entries)
2323         return AVERROR(ENOMEM);
2324     ctts_entries[0].count = 1;
2325     ctts_entries[0].duration = track->cluster[0].cts;
2326     for (i = 1; i < track->entry; i++) {
2327         if (track->cluster[i].cts == ctts_entries[entries].duration) {
2328             ctts_entries[entries].count++; /* compress */
2329         } else {
2330             entries++;
2331             ctts_entries[entries].duration = track->cluster[i].cts;
2332             ctts_entries[entries].count = 1;
2333         }
2334     }
2335     entries++; /* last one */
2336     atom_size = 16 + (entries * 8);
2337     avio_wb32(pb, atom_size); /* size */
2338     ffio_wfourcc(pb, "ctts");
2339     if (mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS)
2340         avio_w8(pb, 1); /* version */
2341     else
2342         avio_w8(pb, 0); /* version */
2343     avio_wb24(pb, 0); /* flags */
2344     avio_wb32(pb, entries); /* entry count */
2345     for (i = 0; i < entries; i++) {
2346         avio_wb32(pb, ctts_entries[i].count);
2347         avio_wb32(pb, ctts_entries[i].duration);
2348     }
2349     av_free(ctts_entries);
2350     return atom_size;
2351 }
2352
2353 /* Time to sample atom */
2354 static int mov_write_stts_tag(AVIOContext *pb, MOVTrack *track)
2355 {
2356     MOVStts *stts_entries = NULL;
2357     uint32_t entries = -1;
2358     uint32_t atom_size;
2359     int i;
2360
2361     if (track->par->codec_type == AVMEDIA_TYPE_AUDIO && !track->audio_vbr) {
2362         stts_entries = av_malloc(sizeof(*stts_entries)); /* one entry */
2363         if (!stts_entries)
2364             return AVERROR(ENOMEM);
2365         stts_entries[0].count = track->sample_count;
2366         stts_entries[0].duration = 1;
2367         entries = 1;
2368     } else {
2369         if (track->entry) {
2370             stts_entries = av_malloc_array(track->entry, sizeof(*stts_entries)); /* worst case */
2371             if (!stts_entries)
2372                 return AVERROR(ENOMEM);
2373         }
2374         for (i = 0; i < track->entry; i++) {
2375             int duration = get_cluster_duration(track, i);
2376             if (i && duration == stts_entries[entries].duration) {
2377                 stts_entries[entries].count++; /* compress */
2378             } else {
2379                 entries++;
2380                 stts_entries[entries].duration = duration;
2381                 stts_entries[entries].count = 1;
2382             }
2383         }
2384         entries++; /* last one */
2385     }
2386     atom_size = 16 + (entries * 8);
2387     avio_wb32(pb, atom_size); /* size */
2388     ffio_wfourcc(pb, "stts");
2389     avio_wb32(pb, 0); /* version & flags */
2390     avio_wb32(pb, entries); /* entry count */
2391     for (i = 0; i < entries; i++) {
2392         avio_wb32(pb, stts_entries[i].count);
2393         avio_wb32(pb, stts_entries[i].duration);
2394     }
2395     av_free(stts_entries);
2396     return atom_size;
2397 }
2398
2399 static int mov_write_dref_tag(AVIOContext *pb)
2400 {
2401     avio_wb32(pb, 28); /* size */
2402     ffio_wfourcc(pb, "dref");
2403     avio_wb32(pb, 0); /* version & flags */
2404     avio_wb32(pb, 1); /* entry count */
2405
2406     avio_wb32(pb, 0xc); /* size */
2407     //FIXME add the alis and rsrc atom
2408     ffio_wfourcc(pb, "url ");
2409     avio_wb32(pb, 1); /* version & flags */
2410
2411     return 28;
2412 }
2413
2414 static int mov_preroll_write_stbl_atoms(AVIOContext *pb, MOVTrack *track)
2415 {
2416     struct sgpd_entry {
2417         int count;
2418         int16_t roll_distance;
2419         int group_description_index;
2420     };
2421
2422     struct sgpd_entry *sgpd_entries = NULL;
2423     int entries = -1;
2424     int group = 0;
2425     int i, j;
2426
2427     const int OPUS_SEEK_PREROLL_MS = 80;
2428     int roll_samples = av_rescale_q(OPUS_SEEK_PREROLL_MS,
2429                                     (AVRational){1, 1000},
2430                                     (AVRational){1, 48000});
2431
2432     if (!track->entry)
2433         return 0;
2434
2435     sgpd_entries = av_malloc_array(track->entry, sizeof(*sgpd_entries));
2436     if (!sgpd_entries)
2437         return AVERROR(ENOMEM);
2438
2439     av_assert0(track->par->codec_id == AV_CODEC_ID_OPUS || track->par->codec_id == AV_CODEC_ID_AAC);
2440
2441     if (track->par->codec_id == AV_CODEC_ID_OPUS) {
2442         for (i = 0; i < track->entry; i++) {
2443             int roll_samples_remaining = roll_samples;
2444             int distance = 0;
2445             for (j = i - 1; j >= 0; j--) {
2446                 roll_samples_remaining -= get_cluster_duration(track, j);
2447                 distance++;
2448                 if (roll_samples_remaining <= 0)
2449                     break;
2450             }
2451             /* We don't have enough preceeding samples to compute a valid
2452                roll_distance here, so this sample can't be independently
2453                decoded. */
2454             if (roll_samples_remaining > 0)
2455                 distance = 0;
2456             /* Verify distance is a maximum of 32 (2.5ms) packets. */
2457             if (distance > 32)
2458                 return AVERROR_INVALIDDATA;
2459             if (i && distance == sgpd_entries[entries].roll_distance) {
2460                 sgpd_entries[entries].count++;
2461             } else {
2462                 entries++;
2463                 sgpd_entries[entries].count = 1;
2464                 sgpd_entries[entries].roll_distance = distance;
2465                 sgpd_entries[entries].group_description_index = distance ? ++group : 0;
2466             }
2467         }
2468     } else {
2469         entries++;
2470         sgpd_entries[entries].count = track->sample_count;
2471         sgpd_entries[entries].roll_distance = 1;
2472         sgpd_entries[entries].group_description_index = ++group;
2473     }
2474     entries++;
2475
2476     if (!group) {
2477         av_free(sgpd_entries);
2478         return 0;
2479     }
2480
2481     /* Write sgpd tag */
2482     avio_wb32(pb, 24 + (group * 2)); /* size */
2483     ffio_wfourcc(pb, "sgpd");
2484     avio_wb32(pb, 1 << 24); /* fullbox */
2485     ffio_wfourcc(pb, "roll");
2486     avio_wb32(pb, 2); /* default_length */
2487     avio_wb32(pb, group); /* entry_count */
2488     for (i = 0; i < entries; i++) {
2489         if (sgpd_entries[i].group_description_index) {
2490             avio_wb16(pb, -sgpd_entries[i].roll_distance); /* roll_distance */
2491         }
2492     }
2493
2494     /* Write sbgp tag */
2495     avio_wb32(pb, 20 + (entries * 8)); /* size */
2496     ffio_wfourcc(pb, "sbgp");
2497     avio_wb32(pb, 0); /* fullbox */
2498     ffio_wfourcc(pb, "roll");
2499     avio_wb32(pb, entries); /* entry_count */
2500     for (i = 0; i < entries; i++) {
2501         avio_wb32(pb, sgpd_entries[i].count); /* sample_count */
2502         avio_wb32(pb, sgpd_entries[i].group_description_index); /* group_description_index */
2503     }
2504
2505     av_free(sgpd_entries);
2506     return 0;
2507 }
2508
2509 static int mov_write_stbl_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
2510 {
2511     int64_t pos = avio_tell(pb);
2512     int ret = 0;
2513
2514     avio_wb32(pb, 0); /* size */
2515     ffio_wfourcc(pb, "stbl");
2516     if ((ret = mov_write_stsd_tag(s, pb, mov, track)) < 0)
2517         return ret;
2518     mov_write_stts_tag(pb, track);
2519     if ((track->par->codec_type == AVMEDIA_TYPE_VIDEO ||
2520          track->par->codec_id == AV_CODEC_ID_TRUEHD ||
2521          track->par->codec_id == AV_CODEC_ID_MPEGH_3D_AUDIO ||
2522          track->par->codec_tag == MKTAG('r','t','p',' ')) &&
2523         track->has_keyframes && track->has_keyframes < track->entry)
2524         mov_write_stss_tag(pb, track, MOV_SYNC_SAMPLE);
2525     if (track->par->codec_type == AVMEDIA_TYPE_VIDEO && track->has_disposable)
2526         mov_write_sdtp_tag(pb, track);
2527     if (track->mode == MODE_MOV && track->flags & MOV_TRACK_STPS)
2528         mov_write_stss_tag(pb, track, MOV_PARTIAL_SYNC_SAMPLE);
2529     if (track->par->codec_type == AVMEDIA_TYPE_VIDEO &&
2530         track->flags & MOV_TRACK_CTTS && track->entry) {
2531
2532         if ((ret = mov_write_ctts_tag(s, pb, track)) < 0)
2533             return ret;
2534     }
2535     mov_write_stsc_tag(pb, track);
2536     mov_write_stsz_tag(pb, track);
2537     mov_write_stco_tag(pb, track);
2538     if (track->cenc.aes_ctr) {
2539         ff_mov_cenc_write_stbl_atoms(&track->cenc, pb);
2540     }
2541     if (track->par->codec_id == AV_CODEC_ID_OPUS || track->par->codec_id == AV_CODEC_ID_AAC) {
2542         mov_preroll_write_stbl_atoms(pb, track);
2543     }
2544     return update_size(pb, pos);
2545 }
2546
2547 static int mov_write_dinf_tag(AVIOContext *pb)
2548 {
2549     int64_t pos = avio_tell(pb);
2550     avio_wb32(pb, 0); /* size */
2551     ffio_wfourcc(pb, "dinf");
2552     mov_write_dref_tag(pb);
2553     return update_size(pb, pos);
2554 }
2555
2556 static int mov_write_nmhd_tag(AVIOContext *pb)
2557 {
2558     avio_wb32(pb, 12);
2559     ffio_wfourcc(pb, "nmhd");
2560     avio_wb32(pb, 0);
2561     return 12;
2562 }
2563
2564 static int mov_write_tcmi_tag(AVIOContext *pb, MOVTrack *track)
2565 {
2566     int64_t pos = avio_tell(pb);
2567     const char *font = "Lucida Grande";
2568     avio_wb32(pb, 0);                   /* size */
2569     ffio_wfourcc(pb, "tcmi");           /* timecode media information atom */
2570     avio_wb32(pb, 0);                   /* version & flags */
2571     avio_wb16(pb, 0);                   /* text font */
2572     avio_wb16(pb, 0);                   /* text face */
2573     avio_wb16(pb, 12);                  /* text size */
2574     avio_wb16(pb, 0);                   /* (unknown, not in the QT specs...) */
2575     avio_wb16(pb, 0x0000);              /* text color (red) */
2576     avio_wb16(pb, 0x0000);              /* text color (green) */
2577     avio_wb16(pb, 0x0000);              /* text color (blue) */
2578     avio_wb16(pb, 0xffff);              /* background color (red) */
2579     avio_wb16(pb, 0xffff);              /* background color (green) */
2580     avio_wb16(pb, 0xffff);              /* background color (blue) */
2581     avio_w8(pb, strlen(font));          /* font len (part of the pascal string) */
2582     avio_write(pb, font, strlen(font)); /* font name */
2583     return update_size(pb, pos);
2584 }
2585
2586 static int mov_write_gmhd_tag(AVIOContext *pb, MOVTrack *track)
2587 {
2588     int64_t pos = avio_tell(pb);
2589     avio_wb32(pb, 0);      /* size */
2590     ffio_wfourcc(pb, "gmhd");
2591     avio_wb32(pb, 0x18);   /* gmin size */
2592     ffio_wfourcc(pb, "gmin");/* generic media info */
2593     avio_wb32(pb, 0);      /* version & flags */
2594     avio_wb16(pb, 0x40);   /* graphics mode = */
2595     avio_wb16(pb, 0x8000); /* opColor (r?) */
2596     avio_wb16(pb, 0x8000); /* opColor (g?) */
2597     avio_wb16(pb, 0x8000); /* opColor (b?) */
2598     avio_wb16(pb, 0);      /* balance */
2599     avio_wb16(pb, 0);      /* reserved */
2600
2601     /*
2602      * This special text atom is required for
2603      * Apple Quicktime chapters. The contents
2604      * don't appear to be documented, so the
2605      * bytes are copied verbatim.
2606      */
2607     if (track->tag != MKTAG('c','6','0','8')) {
2608     avio_wb32(pb, 0x2C);   /* size */
2609     ffio_wfourcc(pb, "text");
2610     avio_wb16(pb, 0x01);
2611     avio_wb32(pb, 0x00);
2612     avio_wb32(pb, 0x00);
2613     avio_wb32(pb, 0x00);
2614     avio_wb32(pb, 0x01);
2615     avio_wb32(pb, 0x00);
2616     avio_wb32(pb, 0x00);
2617     avio_wb32(pb, 0x00);
2618     avio_wb32(pb, 0x00004000);
2619     avio_wb16(pb, 0x0000);
2620     }
2621
2622     if (track->par->codec_tag == MKTAG('t','m','c','d')) {
2623         int64_t tmcd_pos = avio_tell(pb);
2624         avio_wb32(pb, 0); /* size */
2625         ffio_wfourcc(pb, "tmcd");
2626         mov_write_tcmi_tag(pb, track);
2627         update_size(pb, tmcd_pos);
2628     } else if (track->par->codec_tag == MKTAG('g','p','m','d')) {
2629         int64_t gpmd_pos = avio_tell(pb);
2630         avio_wb32(pb, 0); /* size */
2631         ffio_wfourcc(pb, "gpmd");
2632         avio_wb32(pb, 0); /* version */
2633         update_size(pb, gpmd_pos);
2634     }
2635     return update_size(pb, pos);
2636 }
2637
2638 static int mov_write_smhd_tag(AVIOContext *pb)
2639 {
2640     avio_wb32(pb, 16); /* size */
2641     ffio_wfourcc(pb, "smhd");
2642     avio_wb32(pb, 0); /* version & flags */
2643     avio_wb16(pb, 0); /* reserved (balance, normally = 0) */
2644     avio_wb16(pb, 0); /* reserved */
2645     return 16;
2646 }
2647
2648 static int mov_write_vmhd_tag(AVIOContext *pb)
2649 {
2650     avio_wb32(pb, 0x14); /* size (always 0x14) */
2651     ffio_wfourcc(pb, "vmhd");
2652     avio_wb32(pb, 0x01); /* version & flags */
2653     avio_wb64(pb, 0); /* reserved (graphics mode = copy) */
2654     return 0x14;
2655 }
2656
2657 static int is_clcp_track(MOVTrack *track)
2658 {
2659     return track->tag == MKTAG('c','7','0','8') ||
2660            track->tag == MKTAG('c','6','0','8');
2661 }
2662
2663 static int mov_write_hdlr_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
2664 {
2665     MOVMuxContext *mov = s->priv_data;
2666     const char *hdlr, *descr = NULL, *hdlr_type = NULL;
2667     int64_t pos = avio_tell(pb);
2668
2669     hdlr      = "dhlr";
2670     hdlr_type = "url ";
2671     descr     = "DataHandler";
2672
2673     if (track) {
2674         hdlr = (track->mode == MODE_MOV) ? "mhlr" : "\0\0\0\0";
2675         if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
2676             hdlr_type = "vide";
2677             descr     = "VideoHandler";
2678         } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
2679             hdlr_type = "soun";
2680             descr     = "SoundHandler";
2681         } else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE) {
2682             if (is_clcp_track(track)) {
2683                 hdlr_type = "clcp";
2684                 descr = "ClosedCaptionHandler";
2685             } else {
2686                 if (track->tag == MKTAG('t','x','3','g')) {
2687                     hdlr_type = "sbtl";
2688                 } else if (track->tag == MKTAG('m','p','4','s')) {
2689                     hdlr_type = "subp";
2690                 } else {
2691                     hdlr_type = "text";
2692                 }
2693             descr = "SubtitleHandler";
2694             }
2695         } else if (track->par->codec_tag == MKTAG('r','t','p',' ')) {
2696             hdlr_type = "hint";
2697             descr     = "HintHandler";
2698         } else if (track->par->codec_tag == MKTAG('t','m','c','d')) {
2699             hdlr_type = "tmcd";
2700             descr = "TimeCodeHandler";
2701         } else if (track->par->codec_tag == MKTAG('g','p','m','d')) {
2702             hdlr_type = "meta";
2703             descr = "GoPro MET"; // GoPro Metadata
2704         } else {
2705             av_log(s, AV_LOG_WARNING,
2706                    "Unknown hldr_type for %s, writing dummy values\n",
2707                    av_fourcc2str(track->par->codec_tag));
2708         }
2709         if (track->st) {
2710             // hdlr.name is used by some players to identify the content title
2711             // of the track. So if an alternate handler description is
2712             // specified, use it.
2713             AVDictionaryEntry *t;
2714             t = av_dict_get(track->st->metadata, "handler_name", NULL, 0);
2715             if (t && utf8len(t->value))
2716                 descr = t->value;
2717         }
2718     }
2719
2720     if (mov->empty_hdlr_name) /* expressly allowed by QTFF and not prohibited in ISO 14496-12 8.4.3.3 */
2721         descr = "";
2722
2723     avio_wb32(pb, 0); /* size */
2724     ffio_wfourcc(pb, "hdlr");
2725     avio_wb32(pb, 0); /* Version & flags */
2726     avio_write(pb, hdlr, 4); /* handler */
2727     ffio_wfourcc(pb, hdlr_type); /* handler type */
2728     avio_wb32(pb, 0); /* reserved */
2729     avio_wb32(pb, 0); /* reserved */
2730     avio_wb32(pb, 0); /* reserved */
2731     if (!track || track->mode == MODE_MOV)
2732         avio_w8(pb, strlen(descr)); /* pascal string */
2733     avio_write(pb, descr, strlen(descr)); /* handler description */
2734     if (track && track->mode != MODE_MOV)
2735         avio_w8(pb, 0); /* c string */
2736     return update_size(pb, pos);
2737 }
2738
2739 static int mov_write_hmhd_tag(AVIOContext *pb)
2740 {
2741     /* This atom must be present, but leaving the values at zero
2742      * seems harmless. */
2743     avio_wb32(pb, 28); /* size */
2744     ffio_wfourcc(pb, "hmhd");
2745     avio_wb32(pb, 0); /* version, flags */
2746     avio_wb16(pb, 0); /* maxPDUsize */
2747     avio_wb16(pb, 0); /* avgPDUsize */
2748     avio_wb32(pb, 0); /* maxbitrate */
2749     avio_wb32(pb, 0); /* avgbitrate */
2750     avio_wb32(pb, 0); /* reserved */
2751     return 28;
2752 }
2753
2754 static int mov_write_minf_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
2755 {
2756     int64_t pos = avio_tell(pb);
2757     int ret;
2758
2759     avio_wb32(pb, 0); /* size */
2760     ffio_wfourcc(pb, "minf");
2761     if (track->par->codec_type == AVMEDIA_TYPE_VIDEO)
2762         mov_write_vmhd_tag(pb);
2763     else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
2764         mov_write_smhd_tag(pb);
2765     else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE) {
2766         if (track->tag == MKTAG('t','e','x','t') || is_clcp_track(track)) {
2767             mov_write_gmhd_tag(pb, track);
2768         } else {
2769             mov_write_nmhd_tag(pb);
2770         }
2771     } else if (track->tag == MKTAG('r','t','p',' ')) {
2772         mov_write_hmhd_tag(pb);
2773     } else if (track->tag == MKTAG('t','m','c','d')) {
2774         if (track->mode != MODE_MOV)
2775             mov_write_nmhd_tag(pb);
2776         else
2777             mov_write_gmhd_tag(pb, track);
2778     } else if (track->tag == MKTAG('g','p','m','d')) {
2779         mov_write_gmhd_tag(pb, track);
2780     }
2781     if (track->mode == MODE_MOV) /* ISO 14496-12 8.4.3.1 specifies hdlr only within mdia or meta boxes */
2782         mov_write_hdlr_tag(s, pb, NULL);
2783     mov_write_dinf_tag(pb);
2784     if ((ret = mov_write_stbl_tag(s, pb, mov, track)) < 0)
2785         return ret;
2786     return update_size(pb, pos);
2787 }
2788
2789 static int64_t calc_pts_duration(MOVMuxContext *mov, MOVTrack *track)
2790 {
2791     if (track->tag == MKTAG('t','m','c','d')) {
2792         // tmcd tracks gets track_duration set in mov_write_moov_tag from
2793         // another track's duration, while the end_pts may be left at zero.
2794         // Calculate the pts duration for that track instead.
2795         return av_rescale(calc_pts_duration(mov, &mov->tracks[track->src_track]),
2796                           track->timescale, mov->tracks[track->src_track].timescale);
2797     }
2798     if (track->end_pts != AV_NOPTS_VALUE &&
2799         track->start_dts != AV_NOPTS_VALUE &&
2800         track->start_cts != AV_NOPTS_VALUE) {
2801         return track->end_pts - (track->start_dts + track->start_cts);
2802     }
2803     return track->track_duration;
2804 }
2805
2806 static int mov_write_mdhd_tag(AVIOContext *pb, MOVMuxContext *mov,
2807                               MOVTrack *track)
2808 {
2809     int64_t duration = calc_pts_duration(mov, track);
2810     int version = duration < INT32_MAX ? 0 : 1;
2811
2812     if (track->mode == MODE_ISM)
2813         version = 1;
2814
2815     (version == 1) ? avio_wb32(pb, 44) : avio_wb32(pb, 32); /* size */
2816     ffio_wfourcc(pb, "mdhd");
2817     avio_w8(pb, version);
2818     avio_wb24(pb, 0); /* flags */
2819     if (version == 1) {
2820         avio_wb64(pb, track->time);
2821         avio_wb64(pb, track->time);
2822     } else {
2823         avio_wb32(pb, track->time); /* creation time */
2824         avio_wb32(pb, track->time); /* modification time */
2825     }
2826     avio_wb32(pb, track->timescale); /* time scale (sample rate for audio) */
2827     if (!track->entry && mov->mode == MODE_ISM)
2828         (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
2829     else if (!track->entry)
2830         (version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0);
2831     else
2832         (version == 1) ? avio_wb64(pb, duration) : avio_wb32(pb, duration); /* duration */
2833     avio_wb16(pb, track->language); /* language */
2834     avio_wb16(pb, 0); /* reserved (quality) */
2835
2836     if (version != 0 && track->mode == MODE_MOV) {
2837         av_log(NULL, AV_LOG_ERROR,
2838                "FATAL error, file duration too long for timebase, this file will not be\n"
2839                "playable with QuickTime. Choose a different timebase with "
2840                "-video_track_timescale or a different container format\n");
2841     }
2842
2843     return 32;
2844 }
2845
2846 static int mov_write_mdia_tag(AVFormatContext *s, AVIOContext *pb,
2847                               MOVMuxContext *mov, MOVTrack *track)
2848 {
2849     int64_t pos = avio_tell(pb);
2850     int ret;
2851
2852     avio_wb32(pb, 0); /* size */
2853     ffio_wfourcc(pb, "mdia");
2854     mov_write_mdhd_tag(pb, mov, track);
2855     mov_write_hdlr_tag(s, pb, track);
2856     if ((ret = mov_write_minf_tag(s, pb, mov, track)) < 0)
2857         return ret;
2858     return update_size(pb, pos);
2859 }
2860
2861 /* transformation matrix
2862      |a  b  u|
2863      |c  d  v|
2864      |tx ty w| */
2865 static void write_matrix(AVIOContext *pb, int16_t a, int16_t b, int16_t c,
2866                          int16_t d, int16_t tx, int16_t ty)
2867 {
2868     avio_wb32(pb, a << 16);  /* 16.16 format */
2869     avio_wb32(pb, b << 16);  /* 16.16 format */
2870     avio_wb32(pb, 0);        /* u in 2.30 format */
2871     avio_wb32(pb, c << 16);  /* 16.16 format */
2872     avio_wb32(pb, d << 16);  /* 16.16 format */
2873     avio_wb32(pb, 0);        /* v in 2.30 format */
2874     avio_wb32(pb, tx << 16); /* 16.16 format */
2875     avio_wb32(pb, ty << 16); /* 16.16 format */
2876     avio_wb32(pb, 1 << 30);  /* w in 2.30 format */
2877 }
2878
2879 static int mov_write_tkhd_tag(AVIOContext *pb, MOVMuxContext *mov,
2880                               MOVTrack *track, AVStream *st)
2881 {
2882     int64_t duration = av_rescale_rnd(calc_pts_duration(mov, track),
2883                                       MOV_TIMESCALE, track->timescale,
2884                                       AV_ROUND_UP);
2885     int version = duration < INT32_MAX ? 0 : 1;
2886     int flags   = MOV_TKHD_FLAG_IN_MOVIE;
2887     int rotation = 0;
2888     int group   = 0;
2889
2890     uint32_t *display_matrix = NULL;
2891     int      display_matrix_size, i;
2892
2893     if (st) {
2894         if (mov->per_stream_grouping)
2895             group = st->index;
2896         else
2897             group = st->codecpar->codec_type;
2898
2899         display_matrix = (uint32_t*)av_stream_get_side_data(st, AV_PKT_DATA_DISPLAYMATRIX,
2900                                                             &display_matrix_size);
2901         if (display_matrix && display_matrix_size < 9 * sizeof(*display_matrix))
2902             display_matrix = NULL;
2903     }
2904
2905     if (track->flags & MOV_TRACK_ENABLED)
2906         flags |= MOV_TKHD_FLAG_ENABLED;
2907
2908     if (track->mode == MODE_ISM)
2909         version = 1;
2910
2911     (version == 1) ? avio_wb32(pb, 104) : avio_wb32(pb, 92); /* size */
2912     ffio_wfourcc(pb, "tkhd");
2913     avio_w8(pb, version);
2914     avio_wb24(pb, flags);
2915     if (version == 1) {
2916         avio_wb64(pb, track->time);
2917         avio_wb64(pb, track->time);
2918     } else {
2919         avio_wb32(pb, track->time); /* creation time */
2920         avio_wb32(pb, track->time); /* modification time */
2921     }
2922     avio_wb32(pb, track->track_id); /* track-id */
2923     avio_wb32(pb, 0); /* reserved */
2924     if (!track->entry && mov->mode == MODE_ISM)
2925         (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
2926     else if (!track->entry)
2927         (version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0);
2928     else
2929         (version == 1) ? avio_wb64(pb, duration) : avio_wb32(pb, duration);
2930
2931     avio_wb32(pb, 0); /* reserved */
2932     avio_wb32(pb, 0); /* reserved */
2933     avio_wb16(pb, 0); /* layer */
2934     avio_wb16(pb, group); /* alternate group) */
2935     /* Volume, only for audio */
2936     if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
2937         avio_wb16(pb, 0x0100);
2938     else
2939         avio_wb16(pb, 0);
2940     avio_wb16(pb, 0); /* reserved */
2941
2942     /* Matrix structure */
2943 #if FF_API_OLD_ROTATE_API
2944     if (st && st->metadata) {
2945         AVDictionaryEntry *rot = av_dict_get(st->metadata, "rotate", NULL, 0);
2946         rotation = (rot && rot->value) ? atoi(rot->value) : 0;
2947     }
2948 #endif
2949     if (display_matrix) {
2950         for (i = 0; i < 9; i++)
2951             avio_wb32(pb, display_matrix[i]);
2952 #if FF_API_OLD_ROTATE_API
2953     } else if (rotation == 90) {
2954         write_matrix(pb,  0,  1, -1,  0, track->par->height, 0);
2955     } else if (rotation == 180) {
2956         write_matrix(pb, -1,  0,  0, -1, track->par->width, track->par->height);
2957     } else if (rotation == 270) {
2958         write_matrix(pb,  0, -1,  1,  0, 0, track->par->width);
2959 #endif
2960     } else {
2961         write_matrix(pb,  1,  0,  0,  1, 0, 0);
2962     }
2963     /* Track width and height, for visual only */
2964     if (st && (track->par->codec_type == AVMEDIA_TYPE_VIDEO ||
2965                track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)) {
2966         int64_t track_width_1616;
2967         if (track->mode == MODE_MOV) {
2968             track_width_1616 = track->par->width * 0x10000ULL;
2969         } else {
2970             track_width_1616 = av_rescale(st->sample_aspect_ratio.num,
2971                                                   track->par->width * 0x10000LL,
2972                                                   st->sample_aspect_ratio.den);
2973             if (!track_width_1616 ||
2974                 track->height != track->par->height ||
2975                 track_width_1616 > UINT32_MAX)
2976                 track_width_1616 = track->par->width * 0x10000ULL;
2977         }
2978         if (track_width_1616 > UINT32_MAX) {
2979             av_log(mov->fc, AV_LOG_WARNING, "track width is too large\n");
2980             track_width_1616 = 0;
2981         }
2982         avio_wb32(pb, track_width_1616);
2983         if (track->height > 0xFFFF) {
2984             av_log(mov->fc, AV_LOG_WARNING, "track height is too large\n");
2985             avio_wb32(pb, 0);
2986         } else
2987             avio_wb32(pb, track->height * 0x10000U);
2988     } else {
2989         avio_wb32(pb, 0);
2990         avio_wb32(pb, 0);
2991     }
2992     return 0x5c;
2993 }
2994
2995 static int mov_write_tapt_tag(AVIOContext *pb, MOVTrack *track)
2996 {
2997     int32_t width = av_rescale(track->par->sample_aspect_ratio.num, track->par->width,
2998                                track->par->sample_aspect_ratio.den);
2999
3000     int64_t pos = avio_tell(pb);
3001
3002     avio_wb32(pb, 0); /* size */
3003     ffio_wfourcc(pb, "tapt");
3004
3005     avio_wb32(pb, 20);
3006     ffio_wfourcc(pb, "clef");
3007     avio_wb32(pb, 0);
3008     avio_wb32(pb, width << 16);
3009     avio_wb32(pb, track->par->height << 16);
3010
3011     avio_wb32(pb, 20);
3012     ffio_wfourcc(pb, "prof");
3013     avio_wb32(pb, 0);
3014     avio_wb32(pb, width << 16);
3015     avio_wb32(pb, track->par->height << 16);
3016
3017     avio_wb32(pb, 20);
3018     ffio_wfourcc(pb, "enof");
3019     avio_wb32(pb, 0);
3020     avio_wb32(pb, track->par->width << 16);
3021     avio_wb32(pb, track->par->height << 16);
3022
3023     return update_size(pb, pos);
3024 }
3025
3026 // This box seems important for the psp playback ... without it the movie seems to hang
3027 static int mov_write_edts_tag(AVIOContext *pb, MOVMuxContext *mov,
3028                               MOVTrack *track)
3029 {
3030     int64_t duration = av_rescale_rnd(calc_pts_duration(mov, track),
3031                                       MOV_TIMESCALE, track->timescale,
3032                                       AV_ROUND_UP);
3033     int version = duration < INT32_MAX ? 0 : 1;
3034     int entry_size, entry_count, size;
3035     int64_t delay, start_ct = track->start_cts;
3036     int64_t start_dts = track->start_dts;
3037
3038     if (track->entry) {
3039         if (start_dts != track->cluster[0].dts || start_ct != track->cluster[0].cts) {
3040
3041             av_log(mov->fc, AV_LOG_DEBUG,
3042                    "EDTS using dts:%"PRId64" cts:%d instead of dts:%"PRId64" cts:%"PRId64" tid:%d\n",
3043                    track->cluster[0].dts, track->cluster[0].cts,
3044                    start_dts, start_ct, track->track_id);
3045             start_dts = track->cluster[0].dts;
3046             start_ct  = track->cluster[0].cts;
3047         }
3048     }
3049
3050     delay = av_rescale_rnd(start_dts + start_ct, MOV_TIMESCALE,
3051                            track->timescale, AV_ROUND_DOWN);
3052     version |= delay < INT32_MAX ? 0 : 1;
3053
3054     entry_size = (version == 1) ? 20 : 12;
3055     entry_count = 1 + (delay > 0);
3056     size = 24 + entry_count * entry_size;
3057
3058     /* write the atom data */
3059     avio_wb32(pb, size);
3060     ffio_wfourcc(pb, "edts");
3061     avio_wb32(pb, size - 8);
3062     ffio_wfourcc(pb, "elst");
3063     avio_w8(pb, version);
3064     avio_wb24(pb, 0); /* flags */
3065
3066     avio_wb32(pb, entry_count);
3067     if (delay > 0) { /* add an empty edit to delay presentation */
3068         /* In the positive delay case, the delay includes the cts
3069          * offset, and the second edit list entry below trims out
3070          * the same amount from the actual content. This makes sure
3071          * that the offset last sample is included in the edit
3072          * list duration as well. */
3073         if (version == 1) {
3074             avio_wb64(pb, delay);
3075             avio_wb64(pb, -1);
3076         } else {
3077             avio_wb32(pb, delay);
3078             avio_wb32(pb, -1);
3079         }
3080         avio_wb32(pb, 0x00010000);
3081     } else {
3082         /* Avoid accidentally ending up with start_ct = -1 which has got a
3083          * special meaning. Normally start_ct should end up positive or zero
3084          * here, but use FFMIN in case dts is a small positive integer
3085          * rounded to 0 when represented in MOV_TIMESCALE units. */
3086         av_assert0(av_rescale_rnd(start_dts, MOV_TIMESCALE, track->timescale, AV_ROUND_DOWN) <= 0);
3087         start_ct  = -FFMIN(start_dts, 0);
3088         /* Note, this delay is calculated from the pts of the first sample,
3089          * ensuring that we don't reduce the duration for cases with
3090          * dts<0 pts=0. */
3091         duration += delay;
3092     }
3093
3094     /* For fragmented files, we don't know the full length yet. Setting
3095      * duration to 0 allows us to only specify the offset, including
3096      * the rest of the content (from all future fragments) without specifying
3097      * an explicit duration. */
3098     if (mov->flags & FF_MOV_FLAG_FRAGMENT)
3099         duration = 0;
3100
3101     /* duration */
3102     if (version == 1) {
3103         avio_wb64(pb, duration);
3104         avio_wb64(pb, start_ct);
3105     } else {
3106         avio_wb32(pb, duration);
3107         avio_wb32(pb, start_ct);
3108     }
3109     avio_wb32(pb, 0x00010000);
3110     return size;
3111 }
3112
3113 static int mov_write_tref_tag(AVIOContext *pb, MOVTrack *track)
3114 {
3115     avio_wb32(pb, 20);   // size
3116     ffio_wfourcc(pb, "tref");
3117     avio_wb32(pb, 12);   // size (subatom)
3118     avio_wl32(pb, track->tref_tag);
3119     avio_wb32(pb, track->tref_id);
3120     return 20;
3121 }
3122
3123 // goes at the end of each track!  ... Critical for PSP playback ("Incompatible data" without it)
3124 static int mov_write_uuid_tag_psp(AVIOContext *pb, MOVTrack *mov)
3125 {
3126     avio_wb32(pb, 0x34); /* size ... reports as 28 in mp4box! */
3127     ffio_wfourcc(pb, "uuid");
3128     ffio_wfourcc(pb, "USMT");
3129     avio_wb32(pb, 0x21d24fce);
3130     avio_wb32(pb, 0xbb88695c);
3131     avio_wb32(pb, 0xfac9c740);
3132     avio_wb32(pb, 0x1c);     // another size here!
3133     ffio_wfourcc(pb, "MTDT");
3134     avio_wb32(pb, 0x00010012);
3135     avio_wb32(pb, 0x0a);
3136     avio_wb32(pb, 0x55c40000);
3137     avio_wb32(pb, 0x1);
3138     avio_wb32(pb, 0x0);
3139     return 0x34;
3140 }
3141
3142 static int mov_write_udta_sdp(AVIOContext *pb, MOVTrack *track)
3143 {
3144     AVFormatContext *ctx = track->rtp_ctx;
3145     char buf[1000] = "";
3146     int len;
3147
3148     ff_sdp_write_media(buf, sizeof(buf), ctx->streams[0], track->src_track,
3149                        NULL, NULL, 0, 0, ctx);
3150     av_strlcatf(buf, sizeof(buf), "a=control:streamid=%d\r\n", track->track_id);
3151     len = strlen(buf);
3152
3153     avio_wb32(pb, len + 24);
3154     ffio_wfourcc(pb, "udta");
3155     avio_wb32(pb, len + 16);
3156     ffio_wfourcc(pb, "hnti");
3157     avio_wb32(pb, len + 8);
3158     ffio_wfourcc(pb, "sdp ");
3159     avio_write(pb, buf, len);
3160     return len + 24;
3161 }
3162
3163 static int mov_write_track_metadata(AVIOContext *pb, AVStream *st,
3164                                     const char *tag, const char *str)
3165 {
3166     int64_t pos = avio_tell(pb);
3167     AVDictionaryEntry *t = av_dict_get(st->metadata, str, NULL, 0);
3168     if (!t || !utf8len(t->value))
3169         return 0;
3170
3171     avio_wb32(pb, 0);   /* size */
3172     ffio_wfourcc(pb, tag); /* type */
3173     avio_write(pb, t->value, strlen(t->value)); /* UTF8 string value */
3174     return update_size(pb, pos);
3175 }
3176
3177 static int mov_write_track_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
3178                                     AVStream *st)
3179 {
3180     AVIOContext *pb_buf;
3181     int ret, size;
3182     uint8_t *buf;
3183
3184     if (!st)
3185         return 0;
3186
3187     ret = avio_open_dyn_buf(&pb_buf);
3188     if (ret < 0)
3189         return ret;
3190
3191     if (mov->mode & (MODE_MP4|MODE_MOV))
3192         mov_write_track_metadata(pb_buf, st, "name", "title");
3193
3194     if ((size = avio_get_dyn_buf(pb_buf, &buf)) > 0) {
3195         avio_wb32(pb, size + 8);
3196         ffio_wfourcc(pb, "udta");
3197         avio_write(pb, buf, size);
3198     }
3199     ffio_free_dyn_buf(&pb_buf);
3200
3201     return 0;
3202 }
3203
3204 static int mov_write_trak_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov,
3205                               MOVTrack *track, AVStream *st)
3206 {
3207     int64_t pos = avio_tell(pb);
3208     int entry_backup = track->entry;
3209     int chunk_backup = track->chunkCount;
3210     int ret;
3211
3212     /* If we want to have an empty moov, but some samples already have been
3213      * buffered (delay_moov), pretend that no samples have been written yet. */
3214     if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV)
3215         track->chunkCount = track->entry = 0;
3216
3217     avio_wb32(pb, 0); /* size */
3218     ffio_wfourcc(pb, "trak");
3219     mov_write_tkhd_tag(pb, mov, track, st);
3220
3221     av_assert2(mov->use_editlist >= 0);
3222
3223     if (track->start_dts != AV_NOPTS_VALUE) {
3224         if (mov->use_editlist)
3225             mov_write_edts_tag(pb, mov, track);  // PSP Movies and several other cases require edts box
3226         else if ((track->entry && track->cluster[0].dts) || track->mode == MODE_PSP || is_clcp_track(track))
3227             av_log(mov->fc, AV_LOG_WARNING,
3228                    "Not writing any edit list even though one would have been required\n");
3229     }
3230
3231     if (track->tref_tag)
3232         mov_write_tref_tag(pb, track);
3233
3234     if ((ret = mov_write_mdia_tag(s, pb, mov, track)) < 0)
3235         return ret;
3236     if (track->mode == MODE_PSP)
3237         mov_write_uuid_tag_psp(pb, track); // PSP Movies require this uuid box
3238     if (track->tag == MKTAG('r','t','p',' '))
3239         mov_write_udta_sdp(pb, track);
3240     if (track->mode == MODE_MOV) {
3241         if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
3242             double sample_aspect_ratio = av_q2d(st->sample_aspect_ratio);
3243             if (st->sample_aspect_ratio.num && 1.0 != sample_aspect_ratio) {
3244                 mov_write_tapt_tag(pb, track);
3245             }
3246         }
3247         if (is_clcp_track(track) && st->sample_aspect_ratio.num) {
3248             mov_write_tapt_tag(pb, track);
3249         }
3250     }
3251     mov_write_track_udta_tag(pb, mov, st);
3252     track->entry = entry_backup;
3253     track->chunkCount = chunk_backup;
3254     return update_size(pb, pos);
3255 }
3256
3257 static int mov_write_iods_tag(AVIOContext *pb, MOVMuxContext *mov)
3258 {
3259     int i, has_audio = 0, has_video = 0;
3260     int64_t pos = avio_tell(pb);
3261     int audio_profile = mov->iods_audio_profile;
3262     int video_profile = mov->iods_video_profile;
3263     for (i = 0; i < mov->nb_streams; i++) {
3264         if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
3265             has_audio |= mov->tracks[i].par->codec_type == AVMEDIA_TYPE_AUDIO;
3266             has_video |= mov->tracks[i].par->codec_type == AVMEDIA_TYPE_VIDEO;
3267         }
3268     }
3269     if (audio_profile < 0)
3270         audio_profile = 0xFF - has_audio;
3271     if (video_profile < 0)
3272         video_profile = 0xFF - has_video;
3273     avio_wb32(pb, 0x0); /* size */
3274     ffio_wfourcc(pb, "iods");
3275     avio_wb32(pb, 0);    /* version & flags */
3276     put_descr(pb, 0x10, 7);
3277     avio_wb16(pb, 0x004f);
3278     avio_w8(pb, 0xff);
3279     avio_w8(pb, 0xff);
3280     avio_w8(pb, audio_profile);
3281     avio_w8(pb, video_profile);
3282     avio_w8(pb, 0xff);
3283     return update_size(pb, pos);
3284 }
3285
3286 static int mov_write_trex_tag(AVIOContext *pb, MOVTrack *track)
3287 {
3288     avio_wb32(pb, 0x20); /* size */
3289     ffio_wfourcc(pb, "trex");
3290     avio_wb32(pb, 0);   /* version & flags */
3291     avio_wb32(pb, track->track_id); /* track ID */
3292     avio_wb32(pb, 1);   /* default sample description index */
3293     avio_wb32(pb, 0);   /* default sample duration */
3294     avio_wb32(pb, 0);   /* default sample size */
3295     avio_wb32(pb, 0);   /* default sample flags */
3296     return 0;
3297 }
3298
3299 static int mov_write_mvex_tag(AVIOContext *pb, MOVMuxContext *mov)
3300 {
3301     int64_t pos = avio_tell(pb);
3302     int i;
3303     avio_wb32(pb, 0x0); /* size */
3304     ffio_wfourcc(pb, "mvex");
3305     for (i = 0; i < mov->nb_streams; i++)
3306         mov_write_trex_tag(pb, &mov->tracks[i]);
3307     return update_size(pb, pos);
3308 }
3309
3310 static int mov_write_mvhd_tag(AVIOContext *pb, MOVMuxContext *mov)
3311 {
3312     int max_track_id = 1, i;
3313     int64_t max_track_len = 0;
3314     int version;
3315
3316     for (i = 0; i < mov->nb_streams; i++) {
3317         if (mov->tracks[i].entry > 0 && mov->tracks[i].timescale) {
3318             int64_t max_track_len_temp = av_rescale_rnd(
3319                                                 calc_pts_duration(mov, &mov->tracks[i]),
3320                                                 MOV_TIMESCALE,
3321                                                 mov->tracks[i].timescale,
3322                                                 AV_ROUND_UP);
3323             if (max_track_len < max_track_len_temp)
3324                 max_track_len = max_track_len_temp;
3325             if (max_track_id < mov->tracks[i].track_id)
3326                 max_track_id = mov->tracks[i].track_id;
3327         }
3328     }
3329     /* If using delay_moov, make sure the output is the same as if no
3330      * samples had been written yet. */
3331     if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
3332         max_track_len = 0;
3333         max_track_id  = 1;
3334     }
3335
3336     version = max_track_len < UINT32_MAX ? 0 : 1;
3337     avio_wb32(pb, version == 1 ? 120 : 108); /* size */
3338
3339     ffio_wfourcc(pb, "mvhd");
3340     avio_w8(pb, version);
3341     avio_wb24(pb, 0); /* flags */
3342     if (version == 1) {
3343         avio_wb64(pb, mov->time);
3344         avio_wb64(pb, mov->time);
3345     } else {
3346         avio_wb32(pb, mov->time); /* creation time */
3347         avio_wb32(pb, mov->time); /* modification time */
3348     }
3349     avio_wb32(pb, MOV_TIMESCALE);
3350     (version == 1) ? avio_wb64(pb, max_track_len) : avio_wb32(pb, max_track_len); /* duration of longest track */
3351
3352     avio_wb32(pb, 0x00010000); /* reserved (preferred rate) 1.0 = normal */
3353     avio_wb16(pb, 0x0100); /* reserved (preferred volume) 1.0 = normal */
3354     avio_wb16(pb, 0); /* reserved */
3355     avio_wb32(pb, 0); /* reserved */
3356     avio_wb32(pb, 0); /* reserved */
3357
3358     /* Matrix structure */
3359     write_matrix(pb, 1, 0, 0, 1, 0, 0);
3360
3361     avio_wb32(pb, 0); /* reserved (preview time) */
3362     avio_wb32(pb, 0); /* reserved (preview duration) */
3363     avio_wb32(pb, 0); /* reserved (poster time) */
3364     avio_wb32(pb, 0); /* reserved (selection time) */
3365     avio_wb32(pb, 0); /* reserved (selection duration) */
3366     avio_wb32(pb, 0); /* reserved (current time) */
3367     avio_wb32(pb, max_track_id + 1); /* Next track id */
3368     return 0x6c;
3369 }
3370
3371 static int mov_write_itunes_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov,
3372                                      AVFormatContext *s)
3373 {
3374     avio_wb32(pb, 33); /* size */
3375     ffio_wfourcc(pb, "hdlr");
3376     avio_wb32(pb, 0);
3377     avio_wb32(pb, 0);
3378     ffio_wfourcc(pb, "mdir");
3379     ffio_wfourcc(pb, "appl");
3380     avio_wb32(pb, 0);
3381     avio_wb32(pb, 0);
3382     avio_w8(pb, 0);
3383     return 33;
3384 }
3385
3386 /* helper function to write a data tag with the specified string as data */
3387 static int mov_write_string_data_tag(AVIOContext *pb, const char *data, int lang, int long_style)
3388 {
3389     if (long_style) {
3390         int size = 16 + strlen(data);
3391         avio_wb32(pb, size); /* size */
3392         ffio_wfourcc(pb, "data");
3393         avio_wb32(pb, 1);
3394         avio_wb32(pb, 0);
3395         avio_write(pb, data, strlen(data));
3396         return size;
3397     } else {
3398         if (!lang)
3399             lang = ff_mov_iso639_to_lang("und", 1);
3400         avio_wb16(pb, strlen(data)); /* string length */
3401         avio_wb16(pb, lang);
3402         avio_write(pb, data, strlen(data));
3403         return strlen(data) + 4;
3404     }
3405 }
3406
3407 static int mov_write_string_tag(AVIOContext *pb, const char *name,
3408                                 const char *value, int lang, int long_style)
3409 {
3410     int size = 0;
3411     if (value && value[0]) {
3412         int64_t pos = avio_tell(pb);
3413         avio_wb32(pb, 0); /* size */
3414         ffio_wfourcc(pb, name);
3415         mov_write_string_data_tag(pb, value, lang, long_style);
3416         size = update_size(pb, pos);
3417     }
3418     return size;
3419 }
3420
3421 static AVDictionaryEntry *get_metadata_lang(AVFormatContext *s,
3422                                             const char *tag, int *lang)
3423 {
3424     int l, len, len2;
3425     AVDictionaryEntry *t, *t2 = NULL;
3426     char tag2[16];
3427
3428     *lang = 0;
3429
3430     if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
3431         return NULL;
3432
3433     len = strlen(t->key);
3434     snprintf(tag2, sizeof(tag2), "%s-", tag);
3435     while ((t2 = av_dict_get(s->metadata, tag2, t2, AV_DICT_IGNORE_SUFFIX))) {
3436         len2 = strlen(t2->key);
3437         if (len2 == len + 4 && !strcmp(t->value, t2->value)
3438             && (l = ff_mov_iso639_to_lang(&t2->key[len2 - 3], 1)) >= 0) {
3439             *lang = l;
3440             return t;
3441         }
3442     }
3443     return t;
3444 }
3445
3446 static int mov_write_string_metadata(AVFormatContext *s, AVIOContext *pb,
3447                                      const char *name, const char *tag,
3448                                      int long_style)
3449 {
3450     int lang;
3451     AVDictionaryEntry *t = get_metadata_lang(s, tag, &lang);
3452     if (!t)
3453         return 0;
3454     return mov_write_string_tag(pb, name, t->value, lang, long_style);
3455 }
3456
3457 /* iTunes bpm number */
3458 static int mov_write_tmpo_tag(AVIOContext *pb, AVFormatContext *s)
3459 {
3460     AVDictionaryEntry *t = av_dict_get(s->metadata, "tmpo", NULL, 0);
3461     int size = 0, tmpo = t ? atoi(t->value) : 0;
3462     if (tmpo) {
3463         size = 26;
3464         avio_wb32(pb, size);
3465         ffio_wfourcc(pb, "tmpo");
3466         avio_wb32(pb, size-8); /* size */
3467         ffio_wfourcc(pb, "data");
3468         avio_wb32(pb, 0x15);  //type specifier
3469         avio_wb32(pb, 0);
3470         avio_wb16(pb, tmpo);        // data
3471     }
3472     return size;
3473 }
3474
3475 /* 3GPP TS 26.244 */
3476 static int mov_write_loci_tag(AVFormatContext *s, AVIOContext *pb)
3477 {
3478     int lang;
3479     int64_t pos = avio_tell(pb);
3480     double latitude, longitude, altitude;
3481     int32_t latitude_fix, longitude_fix, altitude_fix;
3482     AVDictionaryEntry *t = get_metadata_lang(s, "location", &lang);
3483     const char *ptr, *place = "";
3484     char *end;
3485     static const char *astronomical_body = "earth";
3486     if (!t)
3487         return 0;
3488
3489     ptr = t->value;
3490     longitude = strtod(ptr, &end);
3491     if (end == ptr) {
3492         av_log(s, AV_LOG_WARNING, "malformed location metadata\n");
3493         return 0;
3494     }
3495     ptr = end;
3496     latitude = strtod(ptr, &end);
3497     if (end == ptr) {
3498         av_log(s, AV_LOG_WARNING, "malformed location metadata\n");
3499         return 0;
3500     }
3501     ptr = end;
3502     altitude = strtod(ptr, &end);
3503     /* If no altitude was present, the default 0 should be fine */
3504     if (*end == '/')
3505         place = end + 1;
3506
3507     latitude_fix  = (int32_t) ((1 << 16) * latitude);
3508     longitude_fix = (int32_t) ((1 << 16) * longitude);
3509     altitude_fix  = (int32_t) ((1 << 16) * altitude);
3510
3511     avio_wb32(pb, 0);         /* size */
3512     ffio_wfourcc(pb, "loci"); /* type */
3513     avio_wb32(pb, 0);         /* version + flags */
3514     avio_wb16(pb, lang);
3515     avio_write(pb, place, strlen(place) + 1);
3516     avio_w8(pb, 0);           /* role of place (0 == shooting location, 1 == real location, 2 == fictional location) */
3517     avio_wb32(pb, latitude_fix);
3518     avio_wb32(pb, longitude_fix);
3519     avio_wb32(pb, altitude_fix);
3520     avio_write(pb, astronomical_body, strlen(astronomical_body) + 1);
3521     avio_w8(pb, 0);           /* additional notes, null terminated string */
3522
3523     return update_size(pb, pos);
3524 }
3525
3526 /* iTunes track or disc number */
3527 static int mov_write_trkn_tag(AVIOContext *pb, MOVMuxContext *mov,
3528                               AVFormatContext *s, int disc)
3529 {
3530     AVDictionaryEntry *t = av_dict_get(s->metadata,
3531                                        disc ? "disc" : "track",
3532                                        NULL, 0);
3533     int size = 0, track = t ? atoi(t->value) : 0;
3534     if (track) {
3535         int tracks = 0;
3536         char *slash = strchr(t->value, '/');
3537         if (slash)
3538             tracks = atoi(slash + 1);
3539         avio_wb32(pb, 32); /* size */
3540         ffio_wfourcc(pb, disc ? "disk" : "trkn");
3541         avio_wb32(pb, 24); /* size */
3542         ffio_wfourcc(pb, "data");
3543         avio_wb32(pb, 0);        // 8 bytes empty
3544         avio_wb32(pb, 0);
3545         avio_wb16(pb, 0);        // empty
3546         avio_wb16(pb, track);    // track / disc number
3547         avio_wb16(pb, tracks);   // total track / disc number
3548         avio_wb16(pb, 0);        // empty
3549         size = 32;
3550     }
3551     return size;
3552 }
3553
3554 static int mov_write_int8_metadata(AVFormatContext *s, AVIOContext *pb,
3555                                    const char *name, const char *tag,
3556                                    int len)
3557 {
3558     AVDictionaryEntry *t = NULL;
3559     uint8_t num;
3560     int size = 24 + len;
3561
3562     if (len != 1 && len != 4)
3563         return -1;
3564
3565     if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
3566         return 0;
3567     num = atoi(t->value);
3568
3569     avio_wb32(pb, size);
3570     ffio_wfourcc(pb, name);
3571     avio_wb32(pb, size - 8);
3572     ffio_wfourcc(pb, "data");
3573     avio_wb32(pb, 0x15);
3574     avio_wb32(pb, 0);
3575     if (len==4) avio_wb32(pb, num);
3576     else        avio_w8 (pb, num);
3577
3578     return size;
3579 }
3580
3581 static int mov_write_covr(AVIOContext *pb, AVFormatContext *s)
3582 {
3583     MOVMuxContext *mov = s->priv_data;
3584     int64_t pos = 0;
3585     int i;
3586
3587     for (i = 0; i < s->nb_streams; i++) {
3588         MOVTrack *trk = &mov->tracks[i];
3589
3590         if (!is_cover_image(trk->st) || trk->cover_image.size <= 0)
3591             continue;
3592
3593         if (!pos) {
3594             pos = avio_tell(pb);
3595             avio_wb32(pb, 0);
3596             ffio_wfourcc(pb, "covr");
3597         }
3598         avio_wb32(pb, 16 + trk->cover_image.size);
3599         ffio_wfourcc(pb, "data");
3600         avio_wb32(pb, trk->tag);
3601         avio_wb32(pb , 0);
3602         avio_write(pb, trk->cover_image.data, trk->cover_image.size);
3603     }
3604
3605     return pos ? update_size(pb, pos) : 0;
3606 }
3607
3608 /* iTunes meta data list */
3609 static int mov_write_ilst_tag(AVIOContext *pb, MOVMuxContext *mov,
3610                               AVFormatContext *s)
3611 {
3612     int64_t pos = avio_tell(pb);
3613     avio_wb32(pb, 0); /* size */
3614     ffio_wfourcc(pb, "ilst");
3615     mov_write_string_metadata(s, pb, "\251nam", "title"    , 1);
3616     mov_write_string_metadata(s, pb, "\251ART", "artist"   , 1);
3617     mov_write_string_metadata(s, pb, "aART", "album_artist", 1);
3618     mov_write_string_metadata(s, pb, "\251wrt", "composer" , 1);
3619     mov_write_string_metadata(s, pb, "\251alb", "album"    , 1);
3620     mov_write_string_metadata(s, pb, "\251day", "date"     , 1);
3621     if (!mov_write_string_metadata(s, pb, "\251too", "encoding_tool", 1)) {
3622         if (!(s->flags & AVFMT_FLAG_BITEXACT))
3623             mov_write_string_tag(pb, "\251too", LIBAVFORMAT_IDENT, 0, 1);
3624     }
3625     mov_write_string_metadata(s, pb, "\251cmt", "comment"  , 1);
3626     mov_write_string_metadata(s, pb, "\251gen", "genre"    , 1);
3627     mov_write_string_metadata(s, pb, "cprt",    "copyright", 1);
3628     mov_write_string_metadata(s, pb, "\251grp", "grouping" , 1);
3629     mov_write_string_metadata(s, pb, "\251lyr", "lyrics"   , 1);
3630     mov_write_string_metadata(s, pb, "desc",    "description",1);
3631     mov_write_string_metadata(s, pb, "ldes",    "synopsis" , 1);
3632     mov_write_string_metadata(s, pb, "tvsh",    "show"     , 1);
3633     mov_write_string_metadata(s, pb, "tven",    "episode_id",1);
3634     mov_write_string_metadata(s, pb, "tvnn",    "network"  , 1);
3635     mov_write_string_metadata(s, pb, "keyw",    "keywords"  , 1);
3636     mov_write_int8_metadata  (s, pb, "tves",    "episode_sort",4);
3637     mov_write_int8_metadata  (s, pb, "tvsn",    "season_number",4);
3638     mov_write_int8_metadata  (s, pb, "stik",    "media_type",1);
3639     mov_write_int8_metadata  (s, pb, "hdvd",    "hd_video",  1);
3640     mov_write_int8_metadata  (s, pb, "pgap",    "gapless_playback",1);
3641     mov_write_int8_metadata  (s, pb, "cpil",    "compilation", 1);
3642     mov_write_covr(pb, s);
3643     mov_write_trkn_tag(pb, mov, s, 0); // track number
3644     mov_write_trkn_tag(pb, mov, s, 1); // disc number
3645     mov_write_tmpo_tag(pb, s);
3646     return update_size(pb, pos);
3647 }
3648
3649 static int mov_write_mdta_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov,
3650                                    AVFormatContext *s)
3651 {
3652     avio_wb32(pb, 33); /* size */
3653     ffio_wfourcc(pb, "hdlr");
3654     avio_wb32(pb, 0);
3655     avio_wb32(pb, 0);
3656     ffio_wfourcc(pb, "mdta");
3657     avio_wb32(pb, 0);
3658     avio_wb32(pb, 0);
3659     avio_wb32(pb, 0);
3660     avio_w8(pb, 0);
3661     return 33;
3662 }
3663
3664 static int mov_write_mdta_keys_tag(AVIOContext *pb, MOVMuxContext *mov,
3665                                    AVFormatContext *s)
3666 {
3667     AVDictionaryEntry *t = NULL;
3668     int64_t pos = avio_tell(pb);
3669     int64_t curpos, entry_pos;
3670     int count = 0;
3671
3672     avio_wb32(pb, 0); /* size */
3673     ffio_wfourcc(pb, "keys");
3674     avio_wb32(pb, 0);
3675     entry_pos = avio_tell(pb);
3676     avio_wb32(pb, 0); /* entry count */
3677
3678     while (t = av_dict_get(s->metadata, "", t, AV_DICT_IGNORE_SUFFIX)) {
3679         avio_wb32(pb, strlen(t->key) + 8);
3680         ffio_wfourcc(pb, "mdta");
3681         avio_write(pb, t->key, strlen(t->key));
3682         count += 1;
3683     }
3684     curpos = avio_tell(pb);
3685     avio_seek(pb, entry_pos, SEEK_SET);
3686     avio_wb32(pb, count); // rewrite entry count
3687     avio_seek(pb, curpos, SEEK_SET);
3688
3689     return update_size(pb, pos);
3690 }
3691
3692 static int mov_write_mdta_ilst_tag(AVIOContext *pb, MOVMuxContext *mov,
3693                                    AVFormatContext *s)
3694 {
3695     AVDictionaryEntry *t = NULL;
3696     int64_t pos = avio_tell(pb);
3697     int count = 1; /* keys are 1-index based */
3698
3699     avio_wb32(pb, 0); /* size */
3700     ffio_wfourcc(pb, "ilst");
3701
3702     while (t = av_dict_get(s->metadata, "", t, AV_DICT_IGNORE_SUFFIX)) {
3703         int64_t entry_pos = avio_tell(pb);
3704         avio_wb32(pb, 0); /* size */
3705         avio_wb32(pb, count); /* key */
3706         mov_write_string_data_tag(pb, t->value, 0, 1);
3707         update_size(pb, entry_pos);
3708         count += 1;
3709     }
3710     return update_size(pb, pos);
3711 }
3712
3713 /* meta data tags */
3714 static int mov_write_meta_tag(AVIOContext *pb, MOVMuxContext *mov,
3715                               AVFormatContext *s)
3716 {
3717     int size = 0;
3718     int64_t pos = avio_tell(pb);
3719     avio_wb32(pb, 0); /* size */
3720     ffio_wfourcc(pb, "meta");
3721     avio_wb32(pb, 0);
3722     if (mov->flags & FF_MOV_FLAG_USE_MDTA) {
3723         mov_write_mdta_hdlr_tag(pb, mov, s);
3724         mov_write_mdta_keys_tag(pb, mov, s);
3725         mov_write_mdta_ilst_tag(pb, mov, s);
3726     }
3727     else {
3728         /* iTunes metadata tag */
3729         mov_write_itunes_hdlr_tag(pb, mov, s);
3730         mov_write_ilst_tag(pb, mov, s);
3731     }
3732     size = update_size(pb, pos);
3733     return size;
3734 }
3735
3736 static int mov_write_raw_metadata_tag(AVFormatContext *s, AVIOContext *pb,
3737                                       const char *name, const char *key)
3738 {
3739     int len;
3740     AVDictionaryEntry *t;
3741
3742     if (!(t = av_dict_get(s->metadata, key, NULL, 0)))
3743         return 0;
3744
3745     len = strlen(t->value);
3746     if (len > 0) {
3747         int size = len + 8;
3748         avio_wb32(pb, size);
3749         ffio_wfourcc(pb, name);
3750         avio_write(pb, t->value, len);
3751         return size;
3752     }
3753     return 0;
3754 }
3755
3756 static int ascii_to_wc(AVIOContext *pb, const uint8_t *b)
3757 {
3758     int val;
3759     while (*b) {
3760         GET_UTF8(val, *b++, return -1;)
3761         avio_wb16(pb, val);
3762     }
3763     avio_wb16(pb, 0x00);
3764     return 0;
3765 }
3766
3767 static uint16_t language_code(const char *str)
3768 {
3769     return (((str[0] - 0x60) & 0x1F) << 10) +
3770            (((str[1] - 0x60) & 0x1F) <<  5) +
3771            (( str[2] - 0x60) & 0x1F);
3772 }
3773
3774 static int mov_write_3gp_udta_tag(AVIOContext *pb, AVFormatContext *s,
3775                                   const char *tag, const char *str)
3776 {
3777     int64_t pos = avio_tell(pb);
3778     AVDictionaryEntry *t = av_dict_get(s->metadata, str, NULL, 0);
3779     if (!t || !utf8len(t->value))
3780         return 0;
3781     avio_wb32(pb, 0);   /* size */
3782     ffio_wfourcc(pb, tag); /* type */
3783     avio_wb32(pb, 0);   /* version + flags */
3784     if (!strcmp(tag, "yrrc"))
3785         avio_wb16(pb, atoi(t->value));
3786     else {
3787         avio_wb16(pb, language_code("eng")); /* language */
3788         avio_write(pb, t->value, strlen(t->value) + 1); /* UTF8 string value */
3789         if (!strcmp(tag, "albm") &&
3790             (t = av_dict_get(s->metadata, "track", NULL, 0)))
3791             avio_w8(pb, atoi(t->value));
3792     }
3793     return update_size(pb, pos);
3794 }
3795
3796 static int mov_write_chpl_tag(AVIOContext *pb, AVFormatContext *s)
3797 {
3798     int64_t pos = avio_tell(pb);
3799     int i, nb_chapters = FFMIN(s->nb_chapters, 255);
3800
3801     avio_wb32(pb, 0);            // size
3802     ffio_wfourcc(pb, "chpl");
3803     avio_wb32(pb, 0x01000000);   // version + flags
3804     avio_wb32(pb, 0);            // unknown
3805     avio_w8(pb, nb_chapters);
3806
3807     for (i = 0; i < nb_chapters; i++) {
3808         AVChapter *c = s->chapters[i];
3809         AVDictionaryEntry *t;
3810         avio_wb64(pb, av_rescale_q(c->start, c->time_base, (AVRational){1,10000000}));
3811
3812         if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
3813             int len = FFMIN(strlen(t->value), 255);
3814             avio_w8(pb, len);
3815             avio_write(pb, t->value, len);
3816         } else
3817             avio_w8(pb, 0);
3818     }
3819     return update_size(pb, pos);
3820 }
3821
3822 static int mov_write_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
3823                               AVFormatContext *s)
3824 {
3825     AVIOContext *pb_buf;
3826     int ret, size;
3827     uint8_t *buf;
3828
3829     ret = avio_open_dyn_buf(&pb_buf);
3830     if (ret < 0)
3831         return ret;
3832
3833     if (mov->mode & MODE_3GP) {
3834         mov_write_3gp_udta_tag(pb_buf, s, "perf", "artist");
3835         mov_write_3gp_udta_tag(pb_buf, s, "titl", "title");
3836         mov_write_3gp_udta_tag(pb_buf, s, "auth", "author");
3837         mov_write_3gp_udta_tag(pb_buf, s, "gnre", "genre");
3838         mov_write_3gp_udta_tag(pb_buf, s, "dscp", "comment");
3839         mov_write_3gp_udta_tag(pb_buf, s, "albm", "album");
3840         mov_write_3gp_udta_tag(pb_buf, s, "cprt", "copyright");
3841         mov_write_3gp_udta_tag(pb_buf, s, "yrrc", "date");
3842         mov_write_loci_tag(s, pb_buf);
3843     } else if (mov->mode == MODE_MOV && !(mov->flags & FF_MOV_FLAG_USE_MDTA)) { // the title field breaks gtkpod with mp4 and my suspicion is that stuff is not valid in mp4
3844         mov_write_string_metadata(s, pb_buf, "\251ART", "artist",      0);
3845         mov_write_string_metadata(s, pb_buf, "\251nam", "title",       0);
3846         mov_write_string_metadata(s, pb_buf, "\251aut", "author",      0);
3847         mov_write_string_metadata(s, pb_buf, "\251alb", "album",       0);
3848         mov_write_string_metadata(s, pb_buf, "\251day", "date",        0);
3849         mov_write_string_metadata(s, pb_buf, "\251swr", "encoder",     0);
3850         // currently ignored by mov.c
3851         mov_write_string_metadata(s, pb_buf, "\251des", "comment",     0);
3852         // add support for libquicktime, this atom is also actually read by mov.c
3853         mov_write_string_metadata(s, pb_buf, "\251cmt", "comment",     0);
3854         mov_write_string_metadata(s, pb_buf, "\251gen", "genre",       0);
3855         mov_write_string_metadata(s, pb_buf, "\251cpy", "copyright",   0);
3856         mov_write_string_metadata(s, pb_buf, "\251mak", "make",        0);
3857         mov_write_string_metadata(s, pb_buf, "\251mod", "model",       0);
3858         mov_write_string_metadata(s, pb_buf, "\251xyz", "location",    0);
3859         mov_write_string_metadata(s, pb_buf, "\251key", "keywords",    0);
3860         mov_write_raw_metadata_tag(s, pb_buf, "XMP_", "xmp");
3861     } else {
3862         /* iTunes meta data */
3863         mov_write_meta_tag(pb_buf, mov, s);
3864         mov_write_loci_tag(s, pb_buf);
3865     }
3866
3867     if (s->nb_chapters && !(mov->flags & FF_MOV_FLAG_DISABLE_CHPL))
3868         mov_write_chpl_tag(pb_buf, s);
3869
3870     if ((size = avio_get_dyn_buf(pb_buf, &buf)) > 0) {
3871         avio_wb32(pb, size + 8);
3872         ffio_wfourcc(pb, "udta");
3873         avio_write(pb, buf, size);
3874     }
3875     ffio_free_dyn_buf(&pb_buf);
3876
3877     return 0;
3878 }
3879
3880 static void mov_write_psp_udta_tag(AVIOContext *pb,
3881                                    const char *str, const char *lang, int type)
3882 {
3883     int len = utf8len(str) + 1;
3884     if (len <= 0)
3885         return;
3886     avio_wb16(pb, len * 2 + 10);        /* size */
3887     avio_wb32(pb, type);                /* type */
3888     avio_wb16(pb, language_code(lang)); /* language */
3889     avio_wb16(pb, 0x01);                /* ? */
3890     ascii_to_wc(pb, str);
3891 }
3892
3893 static int mov_write_uuidusmt_tag(AVIOContext *pb, AVFormatContext *s)
3894 {
3895     AVDictionaryEntry *title = av_dict_get(s->metadata, "title", NULL, 0);
3896     int64_t pos, pos2;
3897
3898     if (title) {
3899         pos = avio_tell(pb);
3900         avio_wb32(pb, 0); /* size placeholder*/
3901         ffio_wfourcc(pb, "uuid");
3902         ffio_wfourcc(pb, "USMT");
3903         avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
3904         avio_wb32(pb, 0xbb88695c);
3905         avio_wb32(pb, 0xfac9c740);
3906
3907         pos2 = avio_tell(pb);
3908         avio_wb32(pb, 0); /* size placeholder*/
3909         ffio_wfourcc(pb, "MTDT");
3910         avio_wb16(pb, 4);
3911
3912         // ?
3913         avio_wb16(pb, 0x0C);                 /* size */
3914         avio_wb32(pb, 0x0B);                 /* type */
3915         avio_wb16(pb, language_code("und")); /* language */
3916         avio_wb16(pb, 0x0);                  /* ? */
3917         avio_wb16(pb, 0x021C);               /* data */
3918
3919         if (!(s->flags & AVFMT_FLAG_BITEXACT))
3920             mov_write_psp_udta_tag(pb, LIBAVCODEC_IDENT,      "eng", 0x04);
3921         mov_write_psp_udta_tag(pb, title->value,          "eng", 0x01);
3922         mov_write_psp_udta_tag(pb, "2006/04/01 11:11:11", "und", 0x03);
3923
3924         update_size(pb, pos2);
3925         return update_size(pb, pos);
3926     }
3927
3928     return 0;
3929 }
3930
3931 static void build_chunks(MOVTrack *trk)
3932 {
3933     int i;
3934     MOVIentry *chunk = &trk->cluster[0];
3935     uint64_t chunkSize = chunk->size;
3936     chunk->chunkNum = 1;
3937     if (trk->chunkCount)
3938         return;
3939     trk->chunkCount = 1;
3940     for (i = 1; i<trk->entry; i++){
3941         if (chunk->pos + chunkSize == trk->cluster[i].pos &&
3942             chunkSize + trk->cluster[i].size < (1<<20)){
3943             chunkSize             += trk->cluster[i].size;
3944             chunk->samples_in_chunk += trk->cluster[i].entries;
3945         } else {
3946             trk->cluster[i].chunkNum = chunk->chunkNum+1;
3947             chunk=&trk->cluster[i];
3948             chunkSize = chunk->size;
3949             trk->chunkCount++;
3950         }
3951     }
3952 }
3953
3954 /**
3955  * Assign track ids. If option "use_stream_ids_as_track_ids" is set,
3956  * the stream ids are used as track ids.
3957  *
3958  * This assumes mov->tracks and s->streams are in the same order and
3959  * there are no gaps in either of them (so mov->tracks[n] refers to
3960  * s->streams[n]).
3961  *
3962  * As an exception, there can be more entries in
3963  * s->streams than in mov->tracks, in which case new track ids are
3964  * generated (starting after the largest found stream id).
3965  */
3966 static int mov_setup_track_ids(MOVMuxContext *mov, AVFormatContext *s)
3967 {
3968     int i;
3969
3970     if (mov->track_ids_ok)
3971         return 0;
3972
3973     if (mov->use_stream_ids_as_track_ids) {
3974         int next_generated_track_id = 0;
3975         for (i = 0; i < s->nb_streams; i++) {
3976             if (s->streams[i]->id > next_generated_track_id)
3977                 next_generated_track_id = s->streams[i]->id;
3978         }
3979
3980         for (i = 0; i < mov->nb_streams; i++) {
3981             if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
3982                 continue;
3983
3984             mov->tracks[i].track_id = i >= s->nb_streams ? ++next_generated_track_id : s->streams[i]->id;
3985         }
3986     } else {
3987         for (i = 0; i < mov->nb_streams; i++) {
3988             if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
3989                 continue;
3990
3991             mov->tracks[i].track_id = i + 1;
3992         }
3993     }
3994
3995     mov->track_ids_ok = 1;
3996
3997     return 0;
3998 }
3999
4000 static int mov_write_moov_tag(AVIOContext *pb, MOVMuxContext *mov,
4001                               AVFormatContext *s)
4002 {
4003     int i;
4004     int64_t pos = avio_tell(pb);
4005     avio_wb32(pb, 0); /* size placeholder*/
4006     ffio_wfourcc(pb, "moov");
4007
4008     mov_setup_track_ids(mov, s);
4009
4010     for (i = 0; i < mov->nb_streams; i++) {
4011         if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
4012             continue;
4013
4014         mov->tracks[i].time     = mov->time;
4015
4016         if (mov->tracks[i].entry)
4017             build_chunks(&mov->tracks[i]);
4018     }
4019
4020     if (mov->chapter_track)
4021         for (i = 0; i < s->nb_streams; i++) {
4022             mov->tracks[i].tref_tag = MKTAG('c','h','a','p');
4023             mov->tracks[i].tref_id  = mov->tracks[mov->chapter_track].track_id;
4024         }
4025     for (i = 0; i < mov->nb_streams; i++) {
4026         MOVTrack *track = &mov->tracks[i];
4027         if (track->tag == MKTAG('r','t','p',' ')) {
4028             track->tref_tag = MKTAG('h','i','n','t');
4029             track->tref_id = mov->tracks[track->src_track].track_id;
4030         } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
4031             int * fallback, size;
4032             fallback = (int*)av_stream_get_side_data(track->st,
4033                                                      AV_PKT_DATA_FALLBACK_TRACK,
4034                                                      &size);
4035             if (fallback != NULL && size == sizeof(int)) {
4036                 if (*fallback >= 0 && *fallback < mov->nb_streams) {
4037                     track->tref_tag = MKTAG('f','a','l','l');
4038                     track->tref_id = mov->tracks[*fallback].track_id;
4039                 }
4040             }
4041         }
4042     }
4043     for (i = 0; i < mov->nb_streams; i++) {
4044         if (mov->tracks[i].tag == MKTAG('t','m','c','d')) {
4045             int src_trk = mov->tracks[i].src_track;
4046             mov->tracks[src_trk].tref_tag = mov->tracks[i].tag;
4047             mov->tracks[src_trk].tref_id  = mov->tracks[i].track_id;
4048             //src_trk may have a different timescale than the tmcd track
4049             mov->tracks[i].track_duration = av_rescale(mov->tracks[src_trk].track_duration,
4050                                                        mov->tracks[i].timescale,
4051                                                        mov->tracks[src_trk].timescale);
4052         }
4053     }
4054
4055     mov_write_mvhd_tag(pb, mov);
4056     if (mov->mode != MODE_MOV && !mov->iods_skip)
4057         mov_write_iods_tag(pb, mov);
4058     for (i = 0; i < mov->nb_streams; i++) {
4059         if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_FRAGMENT) {
4060             int ret = mov_write_trak_tag(s, pb, mov, &(mov->tracks[i]), i < s->nb_streams ? s->streams[i] : NULL);
4061             if (ret < 0)
4062                 return ret;
4063         }
4064     }
4065     if (mov->flags & FF_MOV_FLAG_FRAGMENT)
4066         mov_write_mvex_tag(pb, mov); /* QuickTime requires trak to precede this */
4067
4068     if (mov->mode == MODE_PSP)
4069         mov_write_uuidusmt_tag(pb, s);
4070     else
4071         mov_write_udta_tag(pb, mov, s);
4072
4073     return update_size(pb, pos);
4074 }
4075
4076 static void param_write_int(AVIOContext *pb, const char *name, int value)
4077 {
4078     avio_printf(pb, "<param name=\"%s\" value=\"%d\" valuetype=\"data\"/>\n", name, value);
4079 }
4080
4081 static void param_write_string(AVIOContext *pb, const char *name, const char *value)
4082 {
4083     avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, value);
4084 }
4085
4086 static void param_write_hex(AVIOContext *pb, const char *name, const uint8_t *value, int len)
4087 {
4088     char buf[150];
4089     len = FFMIN(sizeof(buf) / 2 - 1, len);
4090     ff_data_to_hex(buf, value, len, 0);
4091     buf[2 * len] = '\0';
4092     avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, buf);
4093 }
4094
4095 static int mov_write_isml_manifest(AVIOContext *pb, MOVMuxContext *mov, AVFormatContext *s)
4096 {
4097     int64_t pos = avio_tell(pb);
4098     int i;
4099     int64_t manifest_bit_rate = 0;
4100     AVCPBProperties *props = NULL;
4101
4102     static const uint8_t uuid[] = {
4103         0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd,
4104         0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66
4105     };
4106
4107     avio_wb32(pb, 0);
4108     ffio_wfourcc(pb, "uuid");
4109     avio_write(pb, uuid, sizeof(uuid));
4110     avio_wb32(pb, 0);
4111
4112     avio_printf(pb, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
4113     avio_printf(pb, "<smil xmlns=\"http://www.w3.org/2001/SMIL20/Language\">\n");
4114     avio_printf(pb, "<head>\n");
4115     if (!(mov->fc->flags & AVFMT_FLAG_BITEXACT))
4116         avio_printf(pb, "<meta name=\"creator\" content=\"%s\" />\n",
4117                     LIBAVFORMAT_IDENT);
4118     avio_printf(pb, "</head>\n");
4119     avio_printf(pb, "<body>\n");
4120     avio_printf(pb, "<switch>\n");
4121
4122     mov_setup_track_ids(mov, s);
4123
4124     for (i = 0; i < mov->nb_streams; i++) {
4125         MOVTrack *track = &mov->tracks[i];
4126         const char *type;
4127         int track_id = track->track_id;
4128         char track_name_buf[32] = { 0 };
4129
4130         AVStream *st = track->st;
4131         AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0);
4132
4133         if (track->par->codec_type == AVMEDIA_TYPE_VIDEO && !is_cover_image(st)) {
4134             type = "video";
4135         } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
4136             type = "audio";
4137         } else {
4138             continue;
4139         }
4140
4141         props = (AVCPBProperties*)av_stream_get_side_data(track->st, AV_PKT_DATA_CPB_PROPERTIES, NULL);
4142
4143         if (track->par->bit_rate) {
4144             manifest_bit_rate = track->par->bit_rate;
4145         } else if (props) {
4146             manifest_bit_rate = props->max_bitrate;
4147         }
4148
4149         avio_printf(pb, "<%s systemBitrate=\"%"PRId64"\">\n", type,
4150                     manifest_bit_rate);
4151         param_write_int(pb, "systemBitrate", manifest_bit_rate);
4152         param_write_int(pb, "trackID", track_id);
4153         param_write_string(pb, "systemLanguage", lang ? lang->value : "und");
4154
4155         /* Build track name piece by piece: */
4156         /* 1. track type */
4157         av_strlcat(track_name_buf, type, sizeof(track_name_buf));
4158         /* 2. track language, if available */
4159         if (lang)
4160             av_strlcatf(track_name_buf, sizeof(track_name_buf),
4161                         "_%s", lang->value);
4162         /* 3. special type suffix */
4163         /* "_cc" = closed captions, "_ad" = audio_description */
4164         if (st->disposition & AV_DISPOSITION_HEARING_IMPAIRED)
4165             av_strlcat(track_name_buf, "_cc", sizeof(track_name_buf));
4166         else if (st->disposition & AV_DISPOSITION_VISUAL_IMPAIRED)
4167             av_strlcat(track_name_buf, "_ad", sizeof(track_name_buf));
4168
4169         param_write_string(pb, "trackName", track_name_buf);
4170
4171         if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
4172             if (track->par->codec_id == AV_CODEC_ID_H264) {
4173                 uint8_t *ptr;
4174                 int size = track->par->extradata_size;
4175                 if (!ff_avc_write_annexb_extradata(track->par->extradata, &ptr,
4176                                                    &size)) {
4177                     param_write_hex(pb, "CodecPrivateData",
4178                                     ptr ? ptr : track->par->extradata,
4179                                     size);
4180                     av_free(ptr);
4181                 }
4182                 param_write_string(pb, "FourCC", "H264");
4183             } else if (track->par->codec_id == AV_CODEC_ID_VC1) {
4184                 param_write_string(pb, "FourCC", "WVC1");
4185                 param_write_hex(pb, "CodecPrivateData", track->par->extradata,
4186                                 track->par->extradata_size);
4187             }
4188             param_write_int(pb, "MaxWidth", track->par->width);
4189             param_write_int(pb, "MaxHeight", track->par->height);
4190             param_write_int(pb, "DisplayWidth", track->par->width);
4191             param_write_int(pb, "DisplayHeight", track->par->height);
4192         } else {
4193             if (track->par->codec_id == AV_CODEC_ID_AAC) {
4194                 switch (track->par->profile)
4195                 {
4196                     case FF_PROFILE_AAC_HE_V2:
4197                         param_write_string(pb, "FourCC", "AACP");
4198                         break;
4199                     case FF_PROFILE_AAC_HE:
4200                         param_write_string(pb, "FourCC", "AACH");
4201                         break;
4202                     default:
4203                         param_write_string(pb, "FourCC", "AACL");
4204                 }
4205             } else if (track->par->codec_id == AV_CODEC_ID_WMAPRO) {
4206                 param_write_string(pb, "FourCC", "WMAP");
4207             }
4208             param_write_hex(pb, "CodecPrivateData", track->par->extradata,
4209                             track->par->extradata_size);
4210             param_write_int(pb, "AudioTag", ff_codec_get_tag(ff_codec_wav_tags,
4211                                                              track->par->codec_id));
4212             param_write_int(pb, "Channels", track->par->channels);
4213             param_write_int(pb, "SamplingRate", track->par->sample_rate);
4214             param_write_int(pb, "BitsPerSample", 16);
4215             param_write_int(pb, "PacketSize", track->par->block_align ?
4216                                               track->par->block_align : 4);
4217         }
4218         avio_printf(pb, "</%s>\n", type);
4219     }
4220     avio_printf(pb, "</switch>\n");
4221     avio_printf(pb, "</body>\n");
4222     avio_printf(pb, "</smil>\n");
4223
4224     return update_size(pb, pos);
4225 }
4226
4227 static int mov_write_mfhd_tag(AVIOContext *pb, MOVMuxContext *mov)
4228 {
4229     avio_wb32(pb, 16);
4230     ffio_wfourcc(pb, "mfhd");
4231     avio_wb32(pb, 0);
4232     avio_wb32(pb, mov->fragments);
4233     return 0;
4234 }
4235
4236 static uint32_t get_sample_flags(MOVTrack *track, MOVIentry *entry)
4237 {
4238     return entry->flags & MOV_SYNC_SAMPLE ? MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO :
4239            (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC);
4240 }
4241
4242 static int mov_write_tfhd_tag(AVIOContext *pb, MOVMuxContext *mov,
4243                               MOVTrack *track, int64_t moof_offset)
4244 {
4245     int64_t pos = avio_tell(pb);
4246     uint32_t flags = MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
4247                      MOV_TFHD_BASE_DATA_OFFSET;
4248     if (!track->entry) {
4249         flags |= MOV_TFHD_DURATION_IS_EMPTY;
4250     } else {
4251         flags |= MOV_TFHD_DEFAULT_FLAGS;
4252     }
4253     if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET)
4254         flags &= ~MOV_TFHD_BASE_DATA_OFFSET;
4255     if (mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) {
4256         flags &= ~MOV_TFHD_BASE_DATA_OFFSET;
4257         flags |= MOV_TFHD_DEFAULT_BASE_IS_MOOF;
4258     }
4259     /* CMAF requires all values to be explicit in tfhd atoms */
4260     if (mov->flags & FF_MOV_FLAG_CMAF)
4261         flags |= MOV_TFHD_STSD_ID;
4262
4263     /* Don't set a default sample size, the silverlight player refuses
4264      * to play files with that set. Don't set a default sample duration,
4265      * WMP freaks out if it is set. Don't set a base data offset, PIFF
4266      * file format says it MUST NOT be set. */
4267     if (track->mode == MODE_ISM)
4268         flags &= ~(MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
4269                    MOV_TFHD_BASE_DATA_OFFSET | MOV_TFHD_STSD_ID);
4270
4271     avio_wb32(pb, 0); /* size placeholder */
4272     ffio_wfourcc(pb, "tfhd");
4273     avio_w8(pb, 0); /* version */
4274     avio_wb24(pb, flags);
4275
4276     avio_wb32(pb, track->track_id); /* track-id */
4277     if (flags & MOV_TFHD_BASE_DATA_OFFSET)
4278         avio_wb64(pb, moof_offset);
4279     if (flags & MOV_TFHD_STSD_ID) {
4280         avio_wb32(pb, 1);
4281     }
4282     if (flags & MOV_TFHD_DEFAULT_DURATION) {
4283         track->default_duration = get_cluster_duration(track, 0);
4284         avio_wb32(pb, track->default_duration);
4285     }
4286     if (flags & MOV_TFHD_DEFAULT_SIZE) {
4287         track->default_size = track->entry ? track->cluster[0].size : 1;
4288         avio_wb32(pb, track->default_size);
4289     } else
4290         track->default_size = -1;
4291
4292     if (flags & MOV_TFHD_DEFAULT_FLAGS) {
4293         /* Set the default flags based on the second sample, if available.
4294          * If the first sample is different, that can be signaled via a separate field. */
4295         if (track->entry > 1)
4296             track->default_sample_flags = get_sample_flags(track, &track->cluster[1]);
4297         else
4298             track->default_sample_flags =
4299                 track->par->codec_type == AVMEDIA_TYPE_VIDEO ?
4300                 (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC) :
4301                 MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO;
4302         avio_wb32(pb, track->default_sample_flags);
4303     }
4304
4305     return update_size(pb, pos);
4306 }
4307
4308 static int mov_write_trun_tag(AVIOContext *pb, MOVMuxContext *mov,
4309                               MOVTrack *track, int moof_size,
4310                               int first, int end)
4311 {
4312     int64_t pos = avio_tell(pb);
4313     uint32_t flags = MOV_TRUN_DATA_OFFSET;
4314     int i;
4315
4316     for (i = first; i < end; i++) {
4317         if (get_cluster_duration(track, i) != track->default_duration)
4318             flags |= MOV_TRUN_SAMPLE_DURATION;
4319         if (track->cluster[i].size != track->default_size)
4320             flags |= MOV_TRUN_SAMPLE_SIZE;
4321         if (i > first && get_sample_flags(track, &track->cluster[i]) != track->default_sample_flags)
4322             flags |= MOV_TRUN_SAMPLE_FLAGS;
4323     }
4324     if (!(flags & MOV_TRUN_SAMPLE_FLAGS) && track->entry > 0 &&
4325          get_sample_flags(track, &track->cluster[0]) != track->default_sample_flags)
4326         flags |= MOV_TRUN_FIRST_SAMPLE_FLAGS;
4327     if (track->flags & MOV_TRACK_CTTS)
4328         flags |= MOV_TRUN_SAMPLE_CTS;
4329
4330     avio_wb32(pb, 0); /* size placeholder */
4331     ffio_wfourcc(pb, "trun");
4332     if (mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS)
4333         avio_w8(pb, 1); /* version */
4334     else
4335         avio_w8(pb, 0); /* version */
4336     avio_wb24(pb, flags);
4337
4338     avio_wb32(pb, end - first); /* sample count */
4339     if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET &&
4340         !(mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) &&
4341         !mov->first_trun)
4342         avio_wb32(pb, 0); /* Later tracks follow immediately after the previous one */
4343     else
4344         avio_wb32(pb, moof_size + 8 + track->data_offset +
4345                       track->cluster[first].pos); /* data offset */
4346     if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS)
4347         avio_wb32(pb, get_sample_flags(track, &track->cluster[first]));
4348
4349     for (i = first; i < end; i++) {
4350         if (flags & MOV_TRUN_SAMPLE_DURATION)
4351             avio_wb32(pb, get_cluster_duration(track, i));
4352         if (flags & MOV_TRUN_SAMPLE_SIZE)
4353             avio_wb32(pb, track->cluster[i].size);
4354         if (flags & MOV_TRUN_SAMPLE_FLAGS)
4355             avio_wb32(pb, get_sample_flags(track, &track->cluster[i]));
4356         if (flags & MOV_TRUN_SAMPLE_CTS)
4357             avio_wb32(pb, track->cluster[i].cts);
4358     }
4359
4360     mov->first_trun = 0;
4361     return update_size(pb, pos);
4362 }
4363
4364 static int mov_write_tfxd_tag(AVIOContext *pb, MOVTrack *track)
4365 {
4366     int64_t pos = avio_tell(pb);
4367     static const uint8_t uuid[] = {
4368         0x6d, 0x1d, 0x9b, 0x05, 0x42, 0xd5, 0x44, 0xe6,
4369         0x80, 0xe2, 0x14, 0x1d, 0xaf, 0xf7, 0x57, 0xb2
4370     };
4371
4372     avio_wb32(pb, 0); /* size placeholder */
4373     ffio_wfourcc(pb, "uuid");
4374     avio_write(pb, uuid, sizeof(uuid));
4375     avio_w8(pb, 1);
4376     avio_wb24(pb, 0);
4377     avio_wb64(pb, track->start_dts + track->frag_start +
4378                   track->cluster[0].cts);
4379     avio_wb64(pb, track->end_pts -
4380                   (track->cluster[0].dts + track->cluster[0].cts));
4381
4382     return update_size(pb, pos);
4383 }
4384
4385 static int mov_write_tfrf_tag(AVIOContext *pb, MOVMuxContext *mov,
4386                               MOVTrack *track, int entry)
4387 {
4388     int n = track->nb_frag_info - 1 - entry, i;
4389     int size = 8 + 16 + 4 + 1 + 16*n;
4390     static const uint8_t uuid[] = {
4391         0xd4, 0x80, 0x7e, 0xf2, 0xca, 0x39, 0x46, 0x95,
4392         0x8e, 0x54, 0x26, 0xcb, 0x9e, 0x46, 0xa7, 0x9f
4393     };
4394
4395     if (entry < 0)
4396         return 0;
4397
4398     avio_seek(pb, track->frag_info[entry].tfrf_offset, SEEK_SET);
4399     avio_wb32(pb, size);
4400     ffio_wfourcc(pb, "uuid");
4401     avio_write(pb, uuid, sizeof(uuid));
4402     avio_w8(pb, 1);
4403     avio_wb24(pb, 0);
4404     avio_w8(pb, n);
4405     for (i = 0; i < n; i++) {
4406         int index = entry + 1 + i;
4407         avio_wb64(pb, track->frag_info[index].time);
4408         avio_wb64(pb, track->frag_info[index].duration);
4409     }
4410     if (n < mov->ism_lookahead) {
4411         int free_size = 16 * (mov->ism_lookahead - n);
4412         avio_wb32(pb, free_size);
4413         ffio_wfourcc(pb, "free");
4414         ffio_fill(pb, 0, free_size - 8);
4415     }
4416
4417     return 0;
4418 }
4419
4420 static int mov_write_tfrf_tags(AVIOContext *pb, MOVMuxContext *mov,
4421                                MOVTrack *track)
4422 {
4423     int64_t pos = avio_tell(pb);
4424     int i;
4425     for (i = 0; i < mov->ism_lookahead; i++) {
4426         /* Update the tfrf tag for the last ism_lookahead fragments,
4427          * nb_frag_info - 1 is the next fragment to be written. */
4428         mov_write_tfrf_tag(pb, mov, track, track->nb_frag_info - 2 - i);
4429     }
4430     avio_seek(pb, pos, SEEK_SET);
4431     return 0;
4432 }
4433
4434 static int mov_add_tfra_entries(AVIOContext *pb, MOVMuxContext *mov, int tracks,
4435                                 int size)
4436 {
4437     int i;
4438     for (i = 0; i < mov->nb_streams; i++) {
4439         MOVTrack *track = &mov->tracks[i];
4440         MOVFragmentInfo *info;
4441         if ((tracks >= 0 && i != tracks) || !track->entry)
4442             continue;
4443         track->nb_frag_info++;
4444         if (track->nb_frag_info >= track->frag_info_capacity) {
4445             unsigned new_capacity = track->nb_frag_info + MOV_FRAG_INFO_ALLOC_INCREMENT;
4446             if (av_reallocp_array(&track->frag_info,
4447                                   new_capacity,
4448                                   sizeof(*track->frag_info)))
4449                 return AVERROR(ENOMEM);
4450             track->frag_info_capacity = new_capacity;
4451         }
4452         info = &track->frag_info[track->nb_frag_info - 1];
4453         info->offset   = avio_tell(pb);
4454         info->size     = size;
4455         // Try to recreate the original pts for the first packet
4456         // from the fields we have stored
4457         info->time     = track->start_dts + track->frag_start +
4458                          track->cluster[0].cts;
4459         info->duration = track->end_pts -
4460                          (track->cluster[0].dts + track->cluster[0].cts);
4461         // If the pts is less than zero, we will have trimmed
4462         // away parts of the media track using an edit list,
4463         // and the corresponding start presentation time is zero.
4464         if (info->time < 0) {
4465             info->duration += info->time;
4466             info->time = 0;
4467         }
4468         info->tfrf_offset = 0;
4469         mov_write_tfrf_tags(pb, mov, track);
4470     }
4471     return 0;
4472 }
4473
4474 static void mov_prune_frag_info(MOVMuxContext *mov, int tracks, int max)
4475 {
4476     int i;
4477     for (i = 0; i < mov->nb_streams; i++) {
4478         MOVTrack *track = &mov->tracks[i];
4479         if ((tracks >= 0 && i != tracks) || !track->entry)
4480             continue;
4481         if (track->nb_frag_info > max) {
4482             memmove(track->frag_info, track->frag_info + (track->nb_frag_info - max), max * sizeof(*track->frag_info));
4483             track->nb_frag_info = max;
4484         }
4485     }
4486 }
4487
4488 static int mov_write_tfdt_tag(AVIOContext *pb, MOVTrack *track)
4489 {
4490     int64_t pos = avio_tell(pb);
4491
4492     avio_wb32(pb, 0); /* size */
4493     ffio_wfourcc(pb, "tfdt");
4494     avio_w8(pb, 1); /* version */
4495     avio_wb24(pb, 0);
4496     avio_wb64(pb, track->frag_start);
4497     return update_size(pb, pos);
4498 }
4499
4500 static int mov_write_traf_tag(AVIOContext *pb, MOVMuxContext *mov,
4501                               MOVTrack *track, int64_t moof_offset,
4502                               int moof_size)
4503 {
4504     int64_t pos = avio_tell(pb);
4505     int i, start = 0;
4506     avio_wb32(pb, 0); /* size placeholder */
4507     ffio_wfourcc(pb, "traf");
4508
4509     mov_write_tfhd_tag(pb, mov, track, moof_offset);
4510     if (mov->mode != MODE_ISM)
4511         mov_write_tfdt_tag(pb, track);
4512     for (i = 1; i < track->entry; i++) {
4513         if (track->cluster[i].pos != track->cluster[i - 1].pos + track->cluster[i - 1].size) {
4514             mov_write_trun_tag(pb, mov, track, moof_size, start, i);
4515             start = i;
4516         }
4517     }
4518     mov_write_trun_tag(pb, mov, track, moof_size, start, track->entry);
4519     if (mov->mode == MODE_ISM) {
4520         mov_write_tfxd_tag(pb, track);
4521
4522         if (mov->ism_lookahead) {
4523             int i, size = 16 + 4 + 1 + 16 * mov->ism_lookahead;
4524
4525             if (track->nb_frag_info > 0) {
4526                 MOVFragmentInfo *info = &track->frag_info[track->nb_frag_info - 1];
4527                 if (!info->tfrf_offset)
4528                     info->tfrf_offset = avio_tell(pb);
4529             }
4530             avio_wb32(pb, 8 + size);
4531             ffio_wfourcc(pb, "free");
4532             for (i = 0; i < size; i++)
4533                 avio_w8(pb, 0);
4534         }
4535     }
4536
4537     return update_size(pb, pos);
4538 }
4539
4540 static int mov_write_moof_tag_internal(AVIOContext *pb, MOVMuxContext *mov,
4541                                        int tracks, int moof_size)
4542 {
4543     int64_t pos = avio_tell(pb);
4544     int i;
4545
4546     avio_wb32(pb, 0); /* size placeholder */
4547     ffio_wfourcc(pb, "moof");
4548     mov->first_trun = 1;
4549
4550     mov_write_mfhd_tag(pb, mov);
4551     for (i = 0; i < mov->nb_streams; i++) {
4552         MOVTrack *track = &mov->tracks[i];
4553         if (tracks >= 0 && i != tracks)
4554             continue;
4555         if (!track->entry)
4556             continue;
4557         mov_write_traf_tag(pb, mov, track, pos, moof_size);
4558     }
4559
4560     return update_size(pb, pos);
4561 }
4562
4563 static int mov_write_sidx_tag(AVIOContext *pb,
4564                               MOVTrack *track, int ref_size, int total_sidx_size)
4565 {
4566     int64_t pos = avio_tell(pb), offset_pos, end_pos;
4567     int64_t presentation_time, duration, offset;
4568     unsigned starts_with_SAP;
4569     int i, entries;
4570
4571     if (track->entry) {
4572         entries = 1;
4573         presentation_time = track->start_dts + track->frag_start +
4574                             track->cluster[0].cts;
4575         duration = track->end_pts -
4576                    (track->cluster[0].dts + track->cluster[0].cts);
4577         starts_with_SAP = track->cluster[0].flags & MOV_SYNC_SAMPLE;
4578
4579         // pts<0 should be cut away using edts
4580         if (presentation_time < 0) {
4581             duration += presentation_time;
4582             presentation_time = 0;
4583         }
4584     } else {
4585         entries = track->nb_frag_info;
4586         if (entries <= 0)
4587             return 0;
4588         presentation_time = track->frag_info[0].time;
4589     }
4590
4591     avio_wb32(pb, 0); /* size */
4592     ffio_wfourcc(pb, "sidx");
4593     avio_w8(pb, 1); /* version */
4594     avio_wb24(pb, 0);
4595     avio_wb32(pb, track->track_id); /* reference_ID */
4596     avio_wb32(pb, track->timescale); /* timescale */
4597     avio_wb64(pb, presentation_time); /* earliest_presentation_time */
4598     offset_pos = avio_tell(pb);
4599     avio_wb64(pb, 0); /* first_offset (offset to referenced moof) */
4600     avio_wb16(pb, 0); /* reserved */
4601
4602     avio_wb16(pb, entries); /* reference_count */
4603     for (i = 0; i < entries; i++) {
4604         if (!track->entry) {
4605             if (i > 1 && track->frag_info[i].offset != track->frag_info[i - 1].offset + track->frag_info[i - 1].size) {
4606                av_log(NULL, AV_LOG_ERROR, "Non-consecutive fragments, writing incorrect sidx\n");
4607             }
4608             duration = track->frag_info[i].duration;
4609             ref_size = track->frag_info[i].size;
4610             starts_with_SAP = 1;
4611         }
4612         avio_wb32(pb, (0 << 31) | (ref_size & 0x7fffffff)); /* reference_type (0 = media) | referenced_size */
4613         avio_wb32(pb, duration); /* subsegment_duration */
4614         avio_wb32(pb, (starts_with_SAP << 31) | (0 << 28) | 0); /* starts_with_SAP | SAP_type | SAP_delta_time */
4615     }
4616
4617     end_pos = avio_tell(pb);
4618     offset = pos + total_sidx_size - end_pos;
4619     avio_seek(pb, offset_pos, SEEK_SET);
4620     avio_wb64(pb, offset);
4621     avio_seek(pb, end_pos, SEEK_SET);
4622     return update_size(pb, pos);
4623 }
4624
4625 static int mov_write_sidx_tags(AVIOContext *pb, MOVMuxContext *mov,
4626                                int tracks, int ref_size)
4627 {
4628     int i, round, ret;
4629     AVIOContext *avio_buf;
4630     int total_size = 0;
4631     for (round = 0; round < 2; round++) {
4632         // First run one round to calculate the total size of all
4633         // sidx atoms.
4634         // This would be much simpler if we'd only write one sidx
4635         // atom, for the first track in the moof.
4636         if (round == 0) {
4637             if ((ret = ffio_open_null_buf(&avio_buf)) < 0)
4638                 return ret;
4639         } else {
4640             avio_buf = pb;
4641         }
4642         for (i = 0; i < mov->nb_streams; i++) {
4643             MOVTrack *track = &mov->tracks[i];
4644             if (tracks >= 0 && i != tracks)
4645                 continue;
4646             // When writing a sidx for the full file, entry is 0, but
4647             // we want to include all tracks. ref_size is 0 in this case,
4648             // since we read it from frag_info instead.
4649             if (!track->entry && ref_size > 0)
4650                 continue;
4651             total_size -= mov_write_sidx_tag(avio_buf, track, ref_size,
4652                                              total_size);
4653         }
4654         if (round == 0)
4655             total_size = ffio_close_null_buf(avio_buf);
4656     }
4657     return 0;
4658 }
4659
4660 static int mov_write_prft_tag(AVIOContext *pb, MOVMuxContext *mov, int tracks)
4661 {
4662     int64_t pos = avio_tell(pb), pts_us, ntp_ts;
4663     MOVTrack *first_track;
4664     int flags = 24;
4665
4666     /* PRFT should be associated with at most one track. So, choosing only the
4667      * first track. */
4668     if (tracks > 0)
4669         return 0;
4670     first_track = &(mov->tracks[0]);
4671
4672     if (!first_track->entry) {
4673         av_log(mov->fc, AV_LOG_WARNING, "Unable to write PRFT, no entries in the track\n");
4674         return 0;
4675     }
4676
4677     if (first_track->cluster[0].pts == AV_NOPTS_VALUE) {
4678         av_log(mov->fc, AV_LOG_WARNING, "Unable to write PRFT, first PTS is invalid\n");
4679         return 0;
4680     }
4681
4682     if (mov->write_prft == MOV_PRFT_SRC_WALLCLOCK) {
4683         if (first_track->cluster[0].prft.wallclock) {
4684             /* Round the NTP time to whole milliseconds. */
4685             ntp_ts = ff_get_formatted_ntp_time((first_track->cluster[0].prft.wallclock / 1000) * 1000 +
4686                                                NTP_OFFSET_US);
4687             flags = first_track->cluster[0].prft.flags;
4688         } else
4689             ntp_ts = ff_get_formatted_ntp_time(ff_ntp_time());
4690     } else if (mov->write_prft == MOV_PRFT_SRC_PTS) {
4691         pts_us = av_rescale_q(first_track->cluster[0].pts,
4692                               first_track->st->time_base, AV_TIME_BASE_Q);
4693         ntp_ts = ff_get_formatted_ntp_time(pts_us + NTP_OFFSET_US);
4694     } else {
4695         av_log(mov->fc, AV_LOG_WARNING, "Unsupported PRFT box configuration: %d\n",
4696                mov->write_prft);
4697         return 0;
4698     }
4699
4700     avio_wb32(pb, 0);                           // Size place holder
4701     ffio_wfourcc(pb, "prft");                   // Type
4702     avio_w8(pb, 1);                             // Version
4703     avio_wb24(pb, flags);                       // Flags
4704     avio_wb32(pb, first_track->track_id);       // reference track ID
4705     avio_wb64(pb, ntp_ts);                      // NTP time stamp
4706     avio_wb64(pb, first_track->cluster[0].pts); //media time
4707     return update_size(pb, pos);
4708 }
4709
4710 static int mov_write_moof_tag(AVIOContext *pb, MOVMuxContext *mov, int tracks,
4711                               int64_t mdat_size)
4712 {
4713     AVIOContext *avio_buf;
4714     int ret, moof_size;
4715
4716     if ((ret = ffio_open_null_buf(&avio_buf)) < 0)
4717         return ret;
4718     mov_write_moof_tag_internal(avio_buf, mov, tracks, 0);
4719     moof_size = ffio_close_null_buf(avio_buf);
4720
4721     if (mov->flags & FF_MOV_FLAG_DASH &&
4722         !(mov->flags & (FF_MOV_FLAG_GLOBAL_SIDX | FF_MOV_FLAG_SKIP_SIDX)))
4723         mov_write_sidx_tags(pb, mov, tracks, moof_size + 8 + mdat_size);
4724
4725     if (mov->write_prft > MOV_PRFT_NONE && mov->write_prft < MOV_PRFT_NB)
4726         mov_write_prft_tag(pb, mov, tracks);
4727
4728     if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX ||
4729         !(mov->flags & FF_MOV_FLAG_SKIP_TRAILER) ||
4730         mov->ism_lookahead) {
4731         if ((ret = mov_add_tfra_entries(pb, mov, tracks, moof_size + 8 + mdat_size)) < 0)
4732             return ret;
4733         if (!(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) &&
4734             mov->flags & FF_MOV_FLAG_SKIP_TRAILER) {
4735             mov_prune_frag_info(mov, tracks, mov->ism_lookahead + 1);
4736         }
4737     }
4738
4739     return mov_write_moof_tag_internal(pb, mov, tracks, moof_size);
4740 }
4741
4742 static int mov_write_tfra_tag(AVIOContext *pb, MOVTrack *track)
4743 {
4744     int64_t pos = avio_tell(pb);
4745     int i;
4746
4747     avio_wb32(pb, 0); /* size placeholder */
4748     ffio_wfourcc(pb, "tfra");
4749     avio_w8(pb, 1); /* version */
4750     avio_wb24(pb, 0);
4751
4752     avio_wb32(pb, track->track_id);
4753     avio_wb32(pb, 0); /* length of traf/trun/sample num */
4754     avio_wb32(pb, track->nb_frag_info);
4755     for (i = 0; i < track->nb_frag_info; i++) {
4756         avio_wb64(pb, track->frag_info[i].time);
4757         avio_wb64(pb, track->frag_info[i].offset + track->data_offset);
4758         avio_w8(pb, 1); /* traf number */
4759         avio_w8(pb, 1); /* trun number */
4760         avio_w8(pb, 1); /* sample number */
4761     }
4762
4763     return update_size(pb, pos);
4764 }
4765
4766 static int mov_write_mfra_tag(AVIOContext *pb, MOVMuxContext *mov)
4767 {
4768     int64_t pos = avio_tell(pb);
4769     int i;
4770
4771     avio_wb32(pb, 0); /* size placeholder */
4772     ffio_wfourcc(pb, "mfra");
4773     /* An empty mfra atom is enough to indicate to the publishing point that
4774      * the stream has ended. */
4775     if (mov->flags & FF_MOV_FLAG_ISML)
4776         return update_size(pb, pos);
4777
4778     for (i = 0; i < mov->nb_streams; i++) {
4779         MOVTrack *track = &mov->tracks[i];
4780         if (track->nb_frag_info)
4781             mov_write_tfra_tag(pb, track);
4782     }
4783
4784     avio_wb32(pb, 16);
4785     ffio_wfourcc(pb, "mfro");
4786     avio_wb32(pb, 0); /* version + flags */
4787     avio_wb32(pb, avio_tell(pb) + 4 - pos);
4788
4789     return update_size(pb, pos);
4790 }
4791
4792 static int mov_write_mdat_tag(AVIOContext *pb, MOVMuxContext *mov)
4793 {
4794     avio_wb32(pb, 8);    // placeholder for extended size field (64 bit)
4795     ffio_wfourcc(pb, mov->mode == MODE_MOV ? "wide" : "free");
4796
4797     mov->mdat_pos = avio_tell(pb);
4798     avio_wb32(pb, 0); /* size placeholder*/
4799     ffio_wfourcc(pb, "mdat");
4800     return 0;
4801 }
4802
4803 static void mov_write_ftyp_tag_internal(AVIOContext *pb, AVFormatContext *s,
4804                                         int has_h264, int has_video, int write_minor)
4805 {
4806     MOVMuxContext *mov = s->priv_data;
4807     int minor = 0x200;
4808
4809     if (mov->major_brand && strlen(mov->major_brand) >= 4)
4810         ffio_wfourcc(pb, mov->major_brand);
4811     else if (mov->mode == MODE_3GP) {
4812         ffio_wfourcc(pb, has_h264 ? "3gp6"  : "3gp4");
4813         minor =     has_h264 ?   0x100 :   0x200;
4814     } else if (mov->mode & MODE_3G2) {
4815         ffio_wfourcc(pb, has_h264 ? "3g2b"  : "3g2a");
4816         minor =     has_h264 ? 0x20000 : 0x10000;
4817     } else if (mov->mode == MODE_PSP)
4818         ffio_wfourcc(pb, "MSNV");
4819     else if (mov->mode == MODE_MP4 && mov->flags & FF_MOV_FLAG_FRAGMENT &&
4820                                       mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS)
4821         ffio_wfourcc(pb, "iso6"); // Required when using signed CTS offsets in trun boxes
4822     else if (mov->mode == MODE_MP4 && mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)
4823         ffio_wfourcc(pb, "iso5"); // Required when using default-base-is-moof
4824     else if (mov->mode == MODE_MP4 && mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS)
4825         ffio_wfourcc(pb, "iso4");
4826     else if (mov->mode == MODE_MP4)
4827         ffio_wfourcc(pb, "isom");
4828     else if (mov->mode == MODE_IPOD)
4829         ffio_wfourcc(pb, has_video ? "M4V ":"M4A ");
4830     else if (mov->mode == MODE_ISM)
4831         ffio_wfourcc(pb, "isml");
4832     else if (mov->mode == MODE_F4V)
4833         ffio_wfourcc(pb, "f4v ");
4834     else
4835         ffio_wfourcc(pb, "qt  ");
4836
4837     if (write_minor)
4838         avio_wb32(pb, minor);
4839 }
4840
4841 static int mov_write_ftyp_tag(AVIOContext *pb, AVFormatContext *s)
4842 {
4843     MOVMuxContext *mov = s->priv_data;
4844     int64_t pos = avio_tell(pb);
4845     int has_h264 = 0, has_video = 0;
4846     int i;
4847
4848     for (i = 0; i < s->nb_streams; i++) {
4849         AVStream *st = s->streams[i];
4850         if (is_cover_image(st))
4851             continue;
4852         if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
4853             has_video = 1;
4854         if (st->codecpar->codec_id == AV_CODEC_ID_H264)
4855             has_h264 = 1;
4856     }
4857
4858     avio_wb32(pb, 0); /* size */
4859     ffio_wfourcc(pb, "ftyp");
4860
4861     // Write major brand
4862     mov_write_ftyp_tag_internal(pb, s, has_h264, has_video, 1);
4863     // Write the major brand as the first compatible brand as well
4864     mov_write_ftyp_tag_internal(pb, s, has_h264, has_video, 0);
4865
4866     // Write compatible brands, ensuring that we don't write the major brand as a
4867     // compatible brand a second time.
4868     if (mov->mode == MODE_ISM) {
4869         ffio_wfourcc(pb, "piff");
4870     } else if (mov->mode != MODE_MOV) {
4871         // We add tfdt atoms when fragmenting, signal this with the iso6 compatible
4872         // brand, if not already the major brand. This is compatible with users that
4873         // don't understand tfdt.
4874         if (mov->mode == MODE_MP4) {
4875             if (mov->flags & FF_MOV_FLAG_CMAF)
4876                 ffio_wfourcc(pb, "cmfc");
4877             if (mov->flags & FF_MOV_FLAG_FRAGMENT && !(mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS))
4878                 ffio_wfourcc(pb, "iso6");
4879         } else {
4880             if (mov->flags & FF_MOV_FLAG_FRAGMENT)
4881                 ffio_wfourcc(pb, "iso6");
4882             if (mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)
4883                 ffio_wfourcc(pb, "iso5");
4884             else if (mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS)
4885                 ffio_wfourcc(pb, "iso4");
4886         }
4887         // Brands prior to iso5 can't be signaled when using default-base-is-moof
4888         if (!(mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)) {
4889             // write isom for mp4 only if it it's not the major brand already.
4890             if (mov->mode != MODE_MP4 || mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS)
4891                 ffio_wfourcc(pb, "isom");
4892             ffio_wfourcc(pb, "iso2");
4893             if (has_h264)
4894                 ffio_wfourcc(pb, "avc1");
4895         }
4896     }
4897
4898     if (mov->mode == MODE_MP4)
4899         ffio_wfourcc(pb, "mp41");
4900
4901     if (mov->flags & FF_MOV_FLAG_DASH && mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
4902         ffio_wfourcc(pb, "dash");
4903
4904     return update_size(pb, pos);
4905 }
4906
4907 static int mov_write_uuidprof_tag(AVIOContext *pb, AVFormatContext *s)
4908 {
4909     AVStream       *video_st    = s->streams[0];
4910     AVCodecParameters *video_par = s->streams[0]->codecpar;
4911     AVCodecParameters *audio_par = s->streams[1]->codecpar;
4912     int audio_rate = audio_par->sample_rate;
4913     int64_t frame_rate = video_st->avg_frame_rate.den ?
4914                         (video_st->avg_frame_rate.num * 0x10000LL) / video_st->avg_frame_rate.den :
4915                         0;
4916     int audio_kbitrate = audio_par->bit_rate / 1000;
4917     int video_kbitrate = FFMIN(video_par->bit_rate / 1000, 800 - audio_kbitrate);
4918
4919     if (frame_rate < 0 || frame_rate > INT32_MAX) {
4920         av_log(s, AV_LOG_ERROR, "Frame rate %f outside supported range\n", frame_rate / (double)0x10000);
4921         return AVERROR(EINVAL);
4922     }
4923
4924     avio_wb32(pb, 0x94); /* size */
4925     ffio_wfourcc(pb, "uuid");
4926     ffio_wfourcc(pb, "PROF");
4927
4928     avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
4929     avio_wb32(pb, 0xbb88695c);
4930     avio_wb32(pb, 0xfac9c740);
4931
4932     avio_wb32(pb, 0x0);  /* ? */
4933     avio_wb32(pb, 0x3);  /* 3 sections ? */
4934
4935     avio_wb32(pb, 0x14); /* size */
4936     ffio_wfourcc(pb, "FPRF");
4937     avio_wb32(pb, 0x0);  /* ? */
4938     avio_wb32(pb, 0x0);  /* ? */
4939     avio_wb32(pb, 0x0);  /* ? */
4940
4941     avio_wb32(pb, 0x2c);  /* size */
4942     ffio_wfourcc(pb, "APRF"); /* audio */
4943     avio_wb32(pb, 0x0);
4944     avio_wb32(pb, 0x2);   /* TrackID */
4945     ffio_wfourcc(pb, "mp4a");
4946     avio_wb32(pb, 0x20f);
4947     avio_wb32(pb, 0x0);
4948     avio_wb32(pb, audio_kbitrate);
4949     avio_wb32(pb, audio_kbitrate);
4950     avio_wb32(pb, audio_rate);
4951     avio_wb32(pb, audio_par->channels);
4952
4953     avio_wb32(pb, 0x34);  /* size */
4954     ffio_wfourcc(pb, "VPRF");   /* video */
4955     avio_wb32(pb, 0x0);
4956     avio_wb32(pb, 0x1);    /* TrackID */
4957     if (video_par->codec_id == AV_CODEC_ID_H264) {
4958         ffio_wfourcc(pb, "avc1");
4959         avio_wb16(pb, 0x014D);
4960         avio_wb16(pb, 0x0015);
4961     } else {
4962         ffio_wfourcc(pb, "mp4v");
4963         avio_wb16(pb, 0x0000);
4964         avio_wb16(pb, 0x0103);
4965     }
4966     avio_wb32(pb, 0x0);
4967     avio_wb32(pb, video_kbitrate);
4968     avio_wb32(pb, video_kbitrate);
4969     avio_wb32(pb, frame_rate);
4970     avio_wb32(pb, frame_rate);
4971     avio_wb16(pb, video_par->width);
4972     avio_wb16(pb, video_par->height);
4973     avio_wb32(pb, 0x010001); /* ? */
4974
4975     return 0;
4976 }
4977
4978 static int mov_write_identification(AVIOContext *pb, AVFormatContext *s)
4979 {
4980     MOVMuxContext *mov = s->priv_data;
4981     int i;
4982
4983     mov_write_ftyp_tag(pb,s);
4984     if (mov->mode == MODE_PSP) {
4985         int video_streams_nb = 0, audio_streams_nb = 0, other_streams_nb = 0;
4986         for (i = 0; i < s->nb_streams; i++) {
4987             AVStream *st = s->streams[i];
4988             if (is_cover_image(st))
4989                 continue;
4990             if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
4991                 video_streams_nb++;
4992             else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
4993                 audio_streams_nb++;
4994             else
4995                 other_streams_nb++;
4996             }
4997
4998         if (video_streams_nb != 1 || audio_streams_nb != 1 || other_streams_nb) {
4999             av_log(s, AV_LOG_ERROR, "PSP mode need one video and one audio stream\n");
5000             return AVERROR(EINVAL);
5001         }
5002         return mov_write_uuidprof_tag(pb, s);
5003     }
5004     return 0;
5005 }
5006
5007 static int mov_parse_mpeg2_frame(AVPacket *pkt, uint32_t *flags)
5008 {
5009     uint32_t c = -1;
5010     int i, closed_gop = 0;
5011
5012     for (i = 0; i < pkt->size - 4; i++) {
5013         c = (c << 8) + pkt->data[i];
5014         if (c == 0x1b8) { // gop
5015             closed_gop = pkt->data[i + 4] >> 6 & 0x01;
5016         } else if (c == 0x100) { // pic
5017             int temp_ref = (pkt->data[i + 1] << 2) | (pkt->data[i + 2] >> 6);
5018             if (!temp_ref || closed_gop) // I picture is not reordered
5019                 *flags = MOV_SYNC_SAMPLE;
5020             else
5021                 *flags = MOV_PARTIAL_SYNC_SAMPLE;
5022             break;
5023         }
5024     }
5025     return 0;
5026 }
5027
5028 static void mov_parse_vc1_frame(AVPacket *pkt, MOVTrack *trk)
5029 {
5030     const uint8_t *start, *next, *end = pkt->data + pkt->size;
5031     int seq = 0, entry = 0;
5032     int key = pkt->flags & AV_PKT_FLAG_KEY;
5033     start = find_next_marker(pkt->data, end);
5034     for (next = start; next < end; start = next) {
5035         next = find_next_marker(start + 4, end);
5036         switch (AV_RB32(start)) {
5037         case VC1_CODE_SEQHDR:
5038             seq = 1;
5039             break;
5040         case VC1_CODE_ENTRYPOINT:
5041             entry = 1;
5042             break;
5043         case VC1_CODE_SLICE:
5044             trk->vc1_info.slices = 1;
5045             break;
5046         }
5047     }
5048     if (!trk->entry && trk->vc1_info.first_packet_seen)
5049         trk->vc1_info.first_frag_written = 1;
5050     if (!trk->entry && !trk->vc1_info.first_frag_written) {
5051         /* First packet in first fragment */
5052         trk->vc1_info.first_packet_seq   = seq;
5053         trk->vc1_info.first_packet_entry = entry;
5054         trk->vc1_info.first_packet_seen  = 1;
5055     } else if ((seq && !trk->vc1_info.packet_seq) ||
5056                (entry && !trk->vc1_info.packet_entry)) {
5057         int i;
5058         for (i = 0; i < trk->entry; i++)
5059             trk->cluster[i].flags &= ~MOV_SYNC_SAMPLE;
5060         trk->has_keyframes = 0;
5061         if (seq)
5062             trk->vc1_info.packet_seq = 1;
5063         if (entry)
5064             trk->vc1_info.packet_entry = 1;
5065         if (!trk->vc1_info.first_frag_written) {
5066             /* First fragment */
5067             if ((!seq   || trk->vc1_info.first_packet_seq) &&
5068                 (!entry || trk->vc1_info.first_packet_entry)) {
5069                 /* First packet had the same headers as this one, readd the
5070                  * sync sample flag. */
5071                 trk->cluster[0].flags |= MOV_SYNC_SAMPLE;
5072                 trk->has_keyframes = 1;
5073             }
5074         }
5075     }
5076     if (trk->vc1_info.packet_seq && trk->vc1_info.packet_entry)
5077         key = seq && entry;
5078     else if (trk->vc1_info.packet_seq)
5079         key = seq;
5080     else if (trk->vc1_info.packet_entry)
5081         key = entry;
5082     if (key) {
5083         trk->cluster[trk->entry].flags |= MOV_SYNC_SAMPLE;
5084         trk->has_keyframes++;
5085     }
5086 }
5087
5088 static void mov_parse_truehd_frame(AVPacket *pkt, MOVTrack *trk)
5089 {
5090     int length;
5091
5092     if (pkt->size < 8)
5093         return;
5094
5095     length = (AV_RB16(pkt->data) & 0xFFF) * 2;
5096     if (length < 8 || length > pkt->size)
5097         return;
5098
5099     if (AV_RB32(pkt->data + 4) == 0xF8726FBA) {
5100         trk->cluster[trk->entry].flags |= MOV_SYNC_SAMPLE;
5101         trk->has_keyframes++;
5102     }
5103
5104     return;
5105 }
5106
5107 static int mov_flush_fragment_interleaving(AVFormatContext *s, MOVTrack *track)
5108 {
5109     MOVMuxContext *mov = s->priv_data;
5110     int ret, buf_size;
5111     uint8_t *buf;
5112     int i, offset;
5113
5114     if (!track->mdat_buf)
5115         return 0;
5116     if (!mov->mdat_buf) {
5117         if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0)
5118             return ret;
5119     }
5120     buf_size = avio_get_dyn_buf(track->mdat_buf, &buf);
5121
5122     offset = avio_tell(mov->mdat_buf);
5123     avio_write(mov->mdat_buf, buf, buf_size);
5124     ffio_free_dyn_buf(&track->mdat_buf);
5125
5126     for (i = track->entries_flushed; i < track->entry; i++)
5127         track->cluster[i].pos += offset;
5128     track->entries_flushed = track->entry;
5129     return 0;
5130 }
5131
5132 static int mov_flush_fragment(AVFormatContext *s, int force)
5133 {
5134     MOVMuxContext *mov = s->priv_data;
5135     int i, first_track = -1;
5136     int64_t mdat_size = 0;
5137     int ret;
5138     int has_video = 0, starts_with_key = 0, first_video_track = 1;
5139
5140     if (!(mov->flags & FF_MOV_FLAG_FRAGMENT))
5141         return 0;
5142
5143     // Try to fill in the duration of the last packet in each stream
5144     // from queued packets in the interleave queues. If the flushing
5145     // of fragments was triggered automatically by an AVPacket, we
5146     // already have reliable info for the end of that track, but other
5147     // tracks may need to be filled in.
5148     for (i = 0; i < s->nb_streams; i++) {
5149         MOVTrack *track = &mov->tracks[i];
5150         if (!track->end_reliable) {
5151             AVPacket pkt;
5152             if (!ff_interleaved_peek(s, i, &pkt, 1)) {
5153                 if (track->dts_shift != AV_NOPTS_VALUE)
5154                     pkt.dts += track->dts_shift;
5155                 track->track_duration = pkt.dts - track->start_dts;
5156                 if (pkt.pts != AV_NOPTS_VALUE)
5157                     track->end_pts = pkt.pts;
5158                 else
5159                     track->end_pts = pkt.dts;
5160             }
5161         }
5162     }
5163
5164     for (i = 0; i < mov->nb_streams; i++) {
5165         MOVTrack *track = &mov->tracks[i];
5166         if (track->entry <= 1)
5167             continue;
5168         // Sample durations are calculated as the diff of dts values,
5169         // but for the last sample in a fragment, we don't know the dts
5170         // of the first sample in the next fragment, so we have to rely
5171         // on what was set as duration in the AVPacket. Not all callers
5172         // set this though, so we might want to replace it with an
5173         // estimate if it currently is zero.
5174         if (get_cluster_duration(track, track->entry - 1) != 0)
5175             continue;
5176         // Use the duration (i.e. dts diff) of the second last sample for
5177         // the last one. This is a wild guess (and fatal if it turns out
5178         // to be too long), but probably the best we can do - having a zero
5179         // duration is bad as well.
5180         track->track_duration += get_cluster_duration(track, track->entry - 2);
5181         track->end_pts        += get_cluster_duration(track, track->entry - 2);
5182         if (!mov->missing_duration_warned) {
5183             av_log(s, AV_LOG_WARNING,
5184                    "Estimating the duration of the last packet in a "
5185                    "fragment, consider setting the duration field in "
5186                    "AVPacket instead.\n");
5187             mov->missing_duration_warned = 1;
5188         }
5189     }
5190
5191     if (!mov->moov_written) {
5192         int64_t pos = avio_tell(s->pb);
5193         uint8_t *buf;
5194         int buf_size, moov_size;
5195
5196         for (i = 0; i < mov->nb_streams; i++)
5197             if (!mov->tracks[i].entry && !is_cover_image(mov->tracks[i].st))
5198                 break;
5199         /* Don't write the initial moov unless all tracks have data */
5200         if (i < mov->nb_streams && !force)
5201             return 0;
5202
5203         moov_size = get_moov_size(s);
5204         for (i = 0; i < mov->nb_streams; i++)
5205             mov->tracks[i].data_offset = pos + moov_size + 8;
5206
5207         avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_HEADER);
5208         if (mov->flags & FF_MOV_FLAG_DELAY_MOOV)
5209             mov_write_identification(s->pb, s);
5210         if ((ret = mov_write_moov_tag(s->pb, mov, s)) < 0)
5211             return ret;
5212
5213         if (mov->flags & FF_MOV_FLAG_DELAY_MOOV) {
5214             if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
5215                 mov->reserved_header_pos = avio_tell(s->pb);
5216             avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_FLUSH_POINT);
5217             mov->moov_written = 1;
5218             return 0;
5219         }
5220
5221         buf_size = avio_get_dyn_buf(mov->mdat_buf, &buf);
5222         avio_wb32(s->pb, buf_size + 8);
5223         ffio_wfourcc(s->pb, "mdat");
5224         avio_write(s->pb, buf, buf_size);
5225         ffio_free_dyn_buf(&mov->mdat_buf);
5226
5227         if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
5228             mov->reserved_header_pos = avio_tell(s->pb);
5229
5230         mov->moov_written = 1;
5231         mov->mdat_size = 0;
5232         for (i = 0; i < mov->nb_streams; i++) {
5233             if (mov->tracks[i].entry)
5234                 mov->tracks[i].frag_start += mov->tracks[i].start_dts +
5235                                              mov->tracks[i].track_duration -
5236                                              mov->tracks[i].cluster[0].dts;
5237             mov->tracks[i].entry = 0;
5238             mov->tracks[i].end_reliable = 0;
5239         }
5240         avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_FLUSH_POINT);
5241         return 0;
5242     }
5243
5244     if (mov->frag_interleave) {
5245         for (i = 0; i < mov->nb_streams; i++) {
5246             MOVTrack *track = &mov->tracks[i];
5247             int ret;
5248             if ((ret = mov_flush_fragment_interleaving(s, track)) < 0)
5249                 return ret;
5250         }
5251
5252         if (!mov->mdat_buf)
5253             return 0;
5254         mdat_size = avio_tell(mov->mdat_buf);
5255     }
5256
5257     for (i = 0; i < mov->nb_streams; i++) {
5258         MOVTrack *track = &mov->tracks[i];
5259         if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF || mov->frag_interleave)
5260             track->data_offset = 0;
5261         else
5262             track->data_offset = mdat_size;
5263         if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
5264             has_video = 1;
5265             if (first_video_track) {
5266                 if (track->entry)
5267                     starts_with_key = track->cluster[0].flags & MOV_SYNC_SAMPLE;
5268                 first_video_track = 0;
5269             }
5270         }
5271         if (!track->entry)
5272             continue;
5273         if (track->mdat_buf)
5274             mdat_size += avio_tell(track->mdat_buf);
5275         if (first_track < 0)
5276             first_track = i;
5277     }
5278
5279     if (!mdat_size)
5280         return 0;
5281
5282     avio_write_marker(s->pb,
5283                       av_rescale(mov->tracks[first_track].cluster[0].dts, AV_TIME_BASE, mov->tracks[first_track].timescale),
5284                       (has_video ? starts_with_key : mov->tracks[first_track].cluster[0].flags & MOV_SYNC_SAMPLE) ? AVIO_DATA_MARKER_SYNC_POINT : AVIO_DATA_MARKER_BOUNDARY_POINT);
5285
5286     for (i = 0; i < mov->nb_streams; i++) {
5287         MOVTrack *track = &mov->tracks[i];
5288         int buf_size, write_moof = 1, moof_tracks = -1;
5289         uint8_t *buf;
5290         int64_t duration = 0;
5291
5292         if (track->entry)
5293             duration = track->start_dts + track->track_duration -
5294                        track->cluster[0].dts;
5295         if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF) {
5296             if (!track->mdat_buf)
5297                 continue;
5298             mdat_size = avio_tell(track->mdat_buf);
5299             moof_tracks = i;
5300         } else {
5301             write_moof = i == first_track;
5302         }
5303
5304         if (write_moof) {
5305             avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_FLUSH_POINT);
5306
5307             mov_write_moof_tag(s->pb, mov, moof_tracks, mdat_size);
5308             mov->fragments++;
5309
5310             avio_wb32(s->pb, mdat_size + 8);
5311             ffio_wfourcc(s->pb, "mdat");
5312         }
5313
5314         if (track->entry)
5315             track->frag_start += duration;
5316         track->entry = 0;
5317         track->entries_flushed = 0;
5318         track->end_reliable = 0;
5319         if (!mov->frag_interleave) {
5320             if (!track->mdat_buf)
5321                 continue;
5322             buf_size = avio_close_dyn_buf(track->mdat_buf, &buf);
5323             track->mdat_buf = NULL;
5324         } else {
5325             if (!mov->mdat_buf)
5326                 continue;
5327             buf_size = avio_close_dyn_buf(mov->mdat_buf, &buf);
5328             mov->mdat_buf = NULL;
5329         }
5330
5331         avio_write(s->pb, buf, buf_size);
5332         av_free(buf);
5333     }
5334
5335     mov->mdat_size = 0;
5336
5337     avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_FLUSH_POINT);
5338     return 0;
5339 }
5340
5341 static int mov_auto_flush_fragment(AVFormatContext *s, int force)
5342 {
5343     MOVMuxContext *mov = s->priv_data;
5344     int had_moov = mov->moov_written;
5345     int ret = mov_flush_fragment(s, force);
5346     if (ret < 0)
5347         return ret;
5348     // If using delay_moov, the first flush only wrote the moov,
5349     // not the actual moof+mdat pair, thus flush once again.
5350     if (!had_moov && mov->flags & FF_MOV_FLAG_DELAY_MOOV)
5351         ret = mov_flush_fragment(s, force);
5352     return ret;
5353 }
5354
5355 static int check_pkt(AVFormatContext *s, AVPacket *pkt)
5356 {
5357     MOVMuxContext *mov = s->priv_data;
5358     MOVTrack *trk = &mov->tracks[pkt->stream_index];
5359     int64_t ref;
5360     uint64_t duration;
5361
5362     if (trk->entry) {
5363         ref = trk->cluster[trk->entry - 1].dts;
5364     } else if (   trk->start_dts != AV_NOPTS_VALUE
5365                && !trk->frag_discont) {
5366         ref = trk->start_dts + trk->track_duration;
5367     } else
5368         ref = pkt->dts; // Skip tests for the first packet
5369
5370     if (trk->dts_shift != AV_NOPTS_VALUE) {
5371         /* With negative CTS offsets we have set an offset to the DTS,
5372          * reverse this for the check. */
5373         ref -= trk->dts_shift;
5374     }
5375
5376     duration = pkt->dts - ref;
5377     if (pkt->dts < ref || duration >= INT_MAX) {
5378         av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" / timestamp: %"PRId64" is out of range for mov/mp4 format\n",
5379             duration, pkt->dts
5380         );
5381
5382         pkt->dts = ref + 1;
5383         pkt->pts = AV_NOPTS_VALUE;
5384     }
5385
5386     if (pkt->duration < 0 || pkt->duration > INT_MAX) {
5387         av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" is invalid\n", pkt->duration);
5388         return AVERROR(EINVAL);
5389     }
5390     return 0;
5391 }
5392
5393 int ff_mov_write_packet(AVFormatContext *s, AVPacket *pkt)
5394 {
5395     MOVMuxContext *mov = s->priv_data;
5396     AVIOContext *pb = s->pb;
5397     MOVTrack *trk = &mov->tracks[pkt->stream_index];
5398     AVCodecParameters *par = trk->par;
5399     AVProducerReferenceTime *prft;
5400     unsigned int samples_in_chunk = 0;
5401     int size = pkt->size, ret = 0, offset = 0;
5402     int prft_size;
5403     uint8_t *reformatted_data = NULL;
5404
5405     ret = check_pkt(s, pkt);
5406     if (ret < 0)
5407         return ret;
5408
5409     if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
5410         int ret;
5411         if (mov->moov_written || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
5412             if (mov->frag_interleave && mov->fragments > 0) {
5413                 if (trk->entry - trk->entries_flushed >= mov->frag_interleave) {
5414                     if ((ret = mov_flush_fragment_interleaving(s, trk)) < 0)
5415                         return ret;
5416                 }
5417             }
5418
5419             if (!trk->mdat_buf) {
5420                 if ((ret = avio_open_dyn_buf(&trk->mdat_buf)) < 0)
5421                     return ret;
5422             }
5423             pb = trk->mdat_buf;
5424         } else {
5425             if (!mov->mdat_buf) {
5426                 if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0)
5427                     return ret;
5428             }
5429             pb = mov->mdat_buf;
5430         }
5431     }
5432
5433     if (par->codec_id == AV_CODEC_ID_AMR_NB) {
5434         /* We must find out how many AMR blocks there are in one packet */
5435         static const uint16_t packed_size[16] =
5436             {13, 14, 16, 18, 20, 21, 27, 32, 6, 0, 0, 0, 0, 0, 0, 1};
5437         int len = 0;
5438
5439         while (len < size && samples_in_chunk < 100) {
5440             len += packed_size[(pkt->data[len] >> 3) & 0x0F];
5441             samples_in_chunk++;
5442         }
5443         if (samples_in_chunk > 1) {
5444             av_log(s, AV_LOG_ERROR, "fatal error, input is not a single packet, implement a AVParser for it\n");
5445             return -1;
5446         }
5447     } else if (par->codec_id == AV_CODEC_ID_ADPCM_MS ||
5448                par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) {
5449         samples_in_chunk = trk->par->frame_size;
5450     } else if (trk->sample_size)
5451         samples_in_chunk = size / trk->sample_size;
5452     else
5453         samples_in_chunk = 1;
5454
5455     if (samples_in_chunk < 1) {
5456         av_log(s, AV_LOG_ERROR, "fatal error, input packet contains no samples\n");
5457         return AVERROR_PATCHWELCOME;
5458     }
5459
5460     /* copy extradata if it exists */
5461     if (trk->vos_len == 0 && par->extradata_size > 0 &&
5462         !TAG_IS_AVCI(trk->tag) &&
5463         (par->codec_id != AV_CODEC_ID_DNXHD)) {
5464         trk->vos_len  = par->extradata_size;
5465         trk->vos_data = av_malloc(trk->vos_len + AV_INPUT_BUFFER_PADDING_SIZE);
5466         if (!trk->vos_data) {
5467             ret = AVERROR(ENOMEM);
5468             goto err;
5469         }
5470         memcpy(trk->vos_data, par->extradata, trk->vos_len);
5471         memset(trk->vos_data + trk->vos_len, 0, AV_INPUT_BUFFER_PADDING_SIZE);
5472     }
5473
5474     if (par->codec_id == AV_CODEC_ID_AAC && pkt->size > 2 &&
5475         (AV_RB16(pkt->data) & 0xfff0) == 0xfff0) {
5476         if (!s->streams[pkt->stream_index]->nb_frames) {
5477             av_log(s, AV_LOG_ERROR, "Malformed AAC bitstream detected: "
5478                    "use the audio bitstream filter 'aac_adtstoasc' to fix it "
5479                    "('-bsf:a aac_adtstoasc' option with ffmpeg)\n");
5480             return -1;
5481         }
5482         av_log(s, AV_LOG_WARNING, "aac bitstream error\n");
5483     }
5484     if (par->codec_id == AV_CODEC_ID_H264 && trk->vos_len > 0 && *(uint8_t *)trk->vos_data != 1 && !TAG_IS_AVCI(trk->tag)) {
5485         /* from x264 or from bytestream H.264 */
5486         /* NAL reformatting needed */
5487         if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
5488             ret = ff_avc_parse_nal_units_buf(pkt->data, &reformatted_data,
5489                                              &size);
5490             if (ret < 0)
5491                 return ret;
5492             avio_write(pb, reformatted_data, size);
5493         } else {
5494             if (trk->cenc.aes_ctr) {
5495                 size = ff_mov_cenc_avc_parse_nal_units(&trk->cenc, pb, pkt->data, size);
5496                 if (size < 0) {
5497                     ret = size;
5498                     goto err;
5499                 }
5500             } else {
5501                 size = ff_avc_parse_nal_units(pb, pkt->data, pkt->size);
5502             }
5503         }
5504     } else if (par->codec_id == AV_CODEC_ID_HEVC && trk->vos_len > 6 &&
5505                (AV_RB24(trk->vos_data) == 1 || AV_RB32(trk->vos_data) == 1)) {
5506         /* extradata is Annex B, assume the bitstream is too and convert it */
5507         if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
5508             ret = ff_hevc_annexb2mp4_buf(pkt->data, &reformatted_data,
5509                                          &size, 0, NULL);
5510             if (ret < 0)
5511                 return ret;
5512             avio_write(pb, reformatted_data, size);
5513         } else {
5514             size = ff_hevc_annexb2mp4(pb, pkt->data, pkt->size, 0, NULL);
5515         }
5516     } else if (par->codec_id == AV_CODEC_ID_AV1) {
5517         if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
5518             ret = ff_av1_filter_obus_buf(pkt->data, &reformatted_data,
5519                                          &size, &offset);
5520             if (ret < 0)
5521                 return ret;
5522             avio_write(pb, reformatted_data, size);
5523         } else {
5524             size = ff_av1_filter_obus(pb, pkt->data, pkt->size);
5525         }
5526 #if CONFIG_AC3_PARSER
5527     } else if (par->codec_id == AV_CODEC_ID_EAC3) {
5528         size = handle_eac3(mov, pkt, trk);
5529         if (size < 0)
5530             return size;
5531         else if (!size)
5532             goto end;
5533         avio_write(pb, pkt->data, size);
5534 #endif
5535     } else {
5536         if (trk->cenc.aes_ctr) {
5537             if (par->codec_id == AV_CODEC_ID_H264 && par->extradata_size > 4) {
5538                 int nal_size_length = (par->extradata[4] & 0x3) + 1;
5539                 ret = ff_mov_cenc_avc_write_nal_units(s, &trk->cenc, nal_size_length, pb, pkt->data, size);
5540             } else {
5541                 ret = ff_mov_cenc_write_packet(&trk->cenc, pb, pkt->data, size);
5542             }
5543
5544             if (ret) {
5545                 goto err;
5546             }
5547         } else {
5548             avio_write(pb, pkt->data, size);
5549         }
5550     }
5551
5552     if ((par->codec_id == AV_CODEC_ID_DNXHD ||
5553          par->codec_id == AV_CODEC_ID_TRUEHD ||
5554          par->codec_id == AV_CODEC_ID_AC3) && !trk->vos_len) {
5555         /* copy frame to create needed atoms */
5556         trk->vos_len  = size;
5557         trk->vos_data = av_malloc(size + AV_INPUT_BUFFER_PADDING_SIZE);
5558         if (!trk->vos_data) {
5559             ret = AVERROR(ENOMEM);
5560             goto err;
5561         }
5562         memcpy(trk->vos_data, pkt->data, size);
5563         memset(trk->vos_data + size, 0, AV_INPUT_BUFFER_PADDING_SIZE);
5564     }
5565
5566     if (trk->entry >= trk->cluster_capacity) {
5567         unsigned new_capacity = trk->entry + MOV_INDEX_CLUSTER_SIZE;
5568         if (av_reallocp_array(&trk->cluster, new_capacity,
5569                               sizeof(*trk->cluster))) {
5570             ret = AVERROR(ENOMEM);
5571             goto err;
5572         }
5573         trk->cluster_capacity = new_capacity;
5574     }
5575
5576     trk->cluster[trk->entry].pos              = avio_tell(pb) - size;
5577     trk->cluster[trk->entry].samples_in_chunk = samples_in_chunk;
5578     trk->cluster[trk->entry].chunkNum         = 0;
5579     trk->cluster[trk->entry].size             = size;
5580     trk->cluster[trk->entry].entries          = samples_in_chunk;
5581     trk->cluster[trk->entry].dts              = pkt->dts;
5582     trk->cluster[trk->entry].pts              = pkt->pts;
5583     if (!trk->entry && trk->start_dts != AV_NOPTS_VALUE) {
5584         if (!trk->frag_discont) {
5585             /* First packet of a new fragment. We already wrote the duration
5586              * of the last packet of the previous fragment based on track_duration,
5587              * which might not exactly match our dts. Therefore adjust the dts
5588              * of this packet to be what the previous packets duration implies. */
5589             trk->cluster[trk->entry].dts = trk->start_dts + trk->track_duration;
5590             /* We also may have written the pts and the corresponding duration
5591              * in sidx/tfrf/tfxd tags; make sure the sidx pts and duration match up with
5592              * the next fragment. This means the cts of the first sample must
5593              * be the same in all fragments, unless end_pts was updated by
5594              * the packet causing the fragment to be written. */
5595             if ((mov->flags & FF_MOV_FLAG_DASH &&
5596                 !(mov->flags & (FF_MOV_FLAG_GLOBAL_SIDX | FF_MOV_FLAG_SKIP_SIDX))) ||
5597                 mov->mode == MODE_ISM)
5598                 pkt->pts = pkt->dts + trk->end_pts - trk->cluster[trk->entry].dts;
5599         } else {
5600             /* New fragment, but discontinuous from previous fragments.
5601              * Pretend the duration sum of the earlier fragments is
5602              * pkt->dts - trk->start_dts. */
5603             trk->frag_start = pkt->dts - trk->start_dts;
5604             trk->end_pts = AV_NOPTS_VALUE;
5605             trk->frag_discont = 0;
5606         }
5607     }
5608
5609     if (!trk->entry && trk->start_dts == AV_NOPTS_VALUE && !mov->use_editlist &&
5610         s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO) {
5611         /* Not using edit lists and shifting the first track to start from zero.
5612          * If the other streams start from a later timestamp, we won't be able
5613          * to signal the difference in starting time without an edit list.
5614          * Thus move the timestamp for this first sample to 0, increasing
5615          * its duration instead. */
5616         trk->cluster[trk->entry].dts = trk->start_dts = 0;
5617     }
5618     if (trk->start_dts == AV_NOPTS_VALUE) {
5619         trk->start_dts = pkt->dts;
5620         if (trk->frag_discont) {
5621             if (mov->use_editlist) {
5622                 /* Pretend the whole stream started at pts=0, with earlier fragments
5623                  * already written. If the stream started at pts=0, the duration sum
5624                  * of earlier fragments would have been pkt->pts. */
5625                 trk->frag_start = pkt->pts;
5626                 trk->start_dts  = pkt->dts - pkt->pts;
5627             } else {
5628                 /* Pretend the whole stream started at dts=0, with earlier fragments
5629                  * already written, with a duration summing up to pkt->dts. */
5630                 trk->frag_start = pkt->dts;
5631                 trk->start_dts  = 0;
5632             }
5633             trk->frag_discont = 0;
5634         } else if (pkt->dts && mov->moov_written)
5635             av_log(s, AV_LOG_WARNING,
5636                    "Track %d starts with a nonzero dts %"PRId64", while the moov "
5637                    "already has been written. Set the delay_moov flag to handle "
5638                    "this case.\n",
5639                    pkt->stream_index, pkt->dts);
5640     }
5641     trk->track_duration = pkt->dts - trk->start_dts + pkt->duration;
5642     trk->last_sample_is_subtitle_end = 0;
5643
5644     if (pkt->pts == AV_NOPTS_VALUE) {
5645         av_log(s, AV_LOG_WARNING, "pts has no value\n");
5646         pkt->pts = pkt->dts;
5647     }
5648     if (pkt->dts != pkt->pts)
5649         trk->flags |= MOV_TRACK_CTTS;
5650     trk->cluster[trk->entry].cts   = pkt->pts - pkt->dts;
5651     trk->cluster[trk->entry].flags = 0;
5652     if (trk->start_cts == AV_NOPTS_VALUE)
5653         trk->start_cts = pkt->pts - pkt->dts;
5654     if (trk->end_pts == AV_NOPTS_VALUE)
5655         trk->end_pts = trk->cluster[trk->entry].dts +
5656                        trk->cluster[trk->entry].cts + pkt->duration;
5657     else
5658         trk->end_pts = FFMAX(trk->end_pts, trk->cluster[trk->entry].dts +
5659                                            trk->cluster[trk->entry].cts +
5660                                            pkt->duration);
5661
5662     if (par->codec_id == AV_CODEC_ID_VC1) {
5663         mov_parse_vc1_frame(pkt, trk);
5664     } else if (par->codec_id == AV_CODEC_ID_TRUEHD) {
5665         mov_parse_truehd_frame(pkt, trk);
5666     } else if (pkt->flags & AV_PKT_FLAG_KEY) {
5667         if (mov->mode == MODE_MOV && par->codec_id == AV_CODEC_ID_MPEG2VIDEO &&
5668             trk->entry > 0) { // force sync sample for the first key frame
5669             mov_parse_mpeg2_frame(pkt, &trk->cluster[trk->entry].flags);
5670             if (trk->cluster[trk->entry].flags & MOV_PARTIAL_SYNC_SAMPLE)
5671                 trk->flags |= MOV_TRACK_STPS;
5672         } else {
5673             trk->cluster[trk->entry].flags = MOV_SYNC_SAMPLE;
5674         }
5675         if (trk->cluster[trk->entry].flags & MOV_SYNC_SAMPLE)
5676             trk->has_keyframes++;
5677     }
5678     if (pkt->flags & AV_PKT_FLAG_DISPOSABLE) {
5679         trk->cluster[trk->entry].flags |= MOV_DISPOSABLE_SAMPLE;
5680         trk->has_disposable++;
5681     }
5682
5683     prft = (AVProducerReferenceTime *)av_packet_get_side_data(pkt, AV_PKT_DATA_PRFT, &prft_size);
5684     if (prft && prft_size == sizeof(AVProducerReferenceTime))
5685         memcpy(&trk->cluster[trk->entry].prft, prft, prft_size);
5686     else
5687         memset(&trk->cluster[trk->entry].prft, 0, sizeof(AVProducerReferenceTime));
5688
5689     trk->entry++;
5690     trk->sample_count += samples_in_chunk;
5691     mov->mdat_size    += size;
5692
5693     if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams)
5694         ff_mov_add_hinted_packet(s, pkt, trk->hint_track, trk->entry,
5695                                  reformatted_data ? reformatted_data + offset
5696                                                   : NULL, size);
5697
5698 end:
5699 err:
5700
5701     if (pkt->data != reformatted_data)
5702         av_free(reformatted_data);
5703     return ret;
5704 }
5705
5706 static int mov_write_single_packet(AVFormatContext *s, AVPacket *pkt)
5707 {
5708         MOVMuxContext *mov = s->priv_data;
5709         MOVTrack *trk = &mov->tracks[pkt->stream_index];
5710         AVCodecParameters *par = trk->par;
5711         int64_t frag_duration = 0;
5712         int size = pkt->size;
5713
5714         int ret = check_pkt(s, pkt);
5715         if (ret < 0)
5716             return ret;
5717
5718         if (mov->flags & FF_MOV_FLAG_FRAG_DISCONT) {
5719             int i;
5720             for (i = 0; i < s->nb_streams; i++)
5721                 mov->tracks[i].frag_discont = 1;
5722             mov->flags &= ~FF_MOV_FLAG_FRAG_DISCONT;
5723         }
5724
5725         if (mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS) {
5726             if (trk->dts_shift == AV_NOPTS_VALUE)
5727                 trk->dts_shift = pkt->pts - pkt->dts;
5728             pkt->dts += trk->dts_shift;
5729         }
5730
5731         if (trk->par->codec_id == AV_CODEC_ID_MP4ALS ||
5732             trk->par->codec_id == AV_CODEC_ID_AAC ||
5733             trk->par->codec_id == AV_CODEC_ID_AV1 ||
5734             trk->par->codec_id == AV_CODEC_ID_FLAC) {
5735             int side_size = 0;
5736             uint8_t *side = av_packet_get_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA, &side_size);
5737             if (side && side_size > 0 && (side_size != par->extradata_size || memcmp(side, par->extradata, side_size))) {
5738                 void *newextra = av_mallocz(side_size + AV_INPUT_BUFFER_PADDING_SIZE);
5739                 if (!newextra)
5740                     return AVERROR(ENOMEM);
5741                 av_free(par->extradata);
5742                 par->extradata = newextra;
5743                 memcpy(par->extradata, side, side_size);
5744                 par->extradata_size = side_size;
5745                 if (!pkt->size) // Flush packet
5746                     mov->need_rewrite_extradata = 1;
5747             }
5748         }
5749
5750         if (!pkt->size) {
5751             if (trk->start_dts == AV_NOPTS_VALUE && trk->frag_discont) {
5752                 trk->start_dts = pkt->dts;
5753                 if (pkt->pts != AV_NOPTS_VALUE)
5754                     trk->start_cts = pkt->pts - pkt->dts;
5755                 else
5756                     trk->start_cts = 0;
5757             }
5758
5759             return 0;             /* Discard 0 sized packets */
5760         }
5761
5762         if (trk->entry && pkt->stream_index < s->nb_streams)
5763             frag_duration = av_rescale_q(pkt->dts - trk->cluster[0].dts,
5764                                          s->streams[pkt->stream_index]->time_base,
5765                                          AV_TIME_BASE_Q);
5766         if ((mov->max_fragment_duration &&
5767              frag_duration >= mov->max_fragment_duration) ||
5768              (mov->max_fragment_size && mov->mdat_size + size >= mov->max_fragment_size) ||
5769              (mov->flags & FF_MOV_FLAG_FRAG_KEYFRAME &&
5770               par->codec_type == AVMEDIA_TYPE_VIDEO &&
5771               trk->entry && pkt->flags & AV_PKT_FLAG_KEY) ||
5772               (mov->flags & FF_MOV_FLAG_FRAG_EVERY_FRAME)) {
5773             if (frag_duration >= mov->min_fragment_duration) {
5774                 // Set the duration of this track to line up with the next
5775                 // sample in this track. This avoids relying on AVPacket
5776                 // duration, but only helps for this particular track, not
5777                 // for the other ones that are flushed at the same time.
5778                 trk->track_duration = pkt->dts - trk->start_dts;
5779                 if (pkt->pts != AV_NOPTS_VALUE)
5780                     trk->end_pts = pkt->pts;
5781                 else
5782                     trk->end_pts = pkt->dts;
5783                 trk->end_reliable = 1;
5784                 mov_auto_flush_fragment(s, 0);
5785             }
5786         }
5787
5788         return ff_mov_write_packet(s, pkt);
5789 }
5790
5791 static int mov_write_subtitle_end_packet(AVFormatContext *s,
5792                                          int stream_index,
5793                                          int64_t dts) {
5794     AVPacket end;
5795     uint8_t data[2] = {0};
5796     int ret;
5797
5798     av_init_packet(&end);
5799     end.size = sizeof(data);
5800     end.data = data;
5801     end.pts = dts;
5802     end.dts = dts;
5803     end.duration = 0;
5804     end.stream_index = stream_index;
5805
5806     ret = mov_write_single_packet(s, &end);
5807     av_packet_unref(&end);
5808
5809     return ret;
5810 }
5811
5812 static int mov_write_packet(AVFormatContext *s, AVPacket *pkt)
5813 {
5814     MOVMuxContext *mov = s->priv_data;
5815     MOVTrack *trk;
5816
5817     if (!pkt) {
5818         mov_flush_fragment(s, 1);
5819         return 1;
5820     }
5821
5822     trk = &mov->tracks[pkt->stream_index];
5823
5824     if (is_cover_image(trk->st)) {
5825         int ret;
5826
5827         if (trk->st->nb_frames >= 1) {
5828             if (trk->st->nb_frames == 1)
5829                 av_log(s, AV_LOG_WARNING, "Got more than one picture in stream %d,"
5830                        " ignoring.\n", pkt->stream_index);
5831             return 0;
5832         }
5833
5834         if ((ret = av_packet_ref(&trk->cover_image, pkt)) < 0)
5835             return ret;
5836
5837         return 0;
5838     } else {
5839         int i;
5840
5841         if (!pkt->size)
5842             return mov_write_single_packet(s, pkt); /* Passthrough. */
5843
5844         /*
5845          * Subtitles require special handling.
5846          *
5847          * 1) For full complaince, every track must have a sample at
5848          * dts == 0, which is rarely true for subtitles. So, as soon
5849          * as we see any packet with dts > 0, write an empty subtitle
5850          * at dts == 0 for any subtitle track with no samples in it.
5851          *
5852          * 2) For each subtitle track, check if the current packet's
5853          * dts is past the duration of the last subtitle sample. If
5854          * so, we now need to write an end sample for that subtitle.
5855          *
5856          * This must be done conditionally to allow for subtitles that
5857          * immediately replace each other, in which case an end sample
5858          * is not needed, and is, in fact, actively harmful.
5859          *
5860          * 3) See mov_write_trailer for how the final end sample is
5861          * handled.
5862          */
5863         for (i = 0; i < mov->nb_streams; i++) {
5864             MOVTrack *trk = &mov->tracks[i];
5865             int ret;
5866
5867             if (trk->par->codec_id == AV_CODEC_ID_MOV_TEXT &&
5868                 trk->track_duration < pkt->dts &&
5869                 (trk->entry == 0 || !trk->last_sample_is_subtitle_end)) {
5870                 ret = mov_write_subtitle_end_packet(s, i, trk->track_duration);
5871                 if (ret < 0) return ret;
5872                 trk->last_sample_is_subtitle_end = 1;
5873             }
5874         }
5875
5876         if (trk->mode == MODE_MOV && trk->par->codec_type == AVMEDIA_TYPE_VIDEO) {
5877             AVPacket *opkt = pkt;
5878             int reshuffle_ret, ret;
5879             if (trk->is_unaligned_qt_rgb) {
5880                 int64_t bpc = trk->par->bits_per_coded_sample != 15 ? trk->par->bits_per_coded_sample : 16;
5881                 int expected_stride = ((trk->par->width * bpc + 15) >> 4)*2;
5882                 reshuffle_ret = ff_reshuffle_raw_rgb(s, &pkt, trk->par, expected_stride);
5883                 if (reshuffle_ret < 0)
5884                     return reshuffle_ret;
5885             } else
5886                 reshuffle_ret = 0;
5887             if (trk->par->format == AV_PIX_FMT_PAL8 && !trk->pal_done) {
5888                 ret = ff_get_packet_palette(s, opkt, reshuffle_ret, trk->palette);
5889                 if (ret < 0)
5890                     goto fail;
5891                 if (ret)
5892                     trk->pal_done++;
5893             } else if (trk->par->codec_id == AV_CODEC_ID_RAWVIDEO &&
5894                        (trk->par->format == AV_PIX_FMT_GRAY8 ||
5895                        trk->par->format == AV_PIX_FMT_MONOBLACK)) {
5896                 for (i = 0; i < pkt->size; i++)
5897                     pkt->data[i] = ~pkt->data[i];
5898             }
5899             if (reshuffle_ret) {
5900                 ret = mov_write_single_packet(s, pkt);
5901 fail:
5902                 if (reshuffle_ret)
5903                     av_packet_free(&pkt);
5904                 return ret;
5905             }
5906         }
5907
5908         return mov_write_single_packet(s, pkt);
5909     }
5910 }
5911
5912 // QuickTime chapters involve an additional text track with the chapter names
5913 // as samples, and a tref pointing from the other tracks to the chapter one.
5914 static int mov_create_chapter_track(AVFormatContext *s, int tracknum)
5915 {
5916     AVIOContext *pb;
5917
5918     MOVMuxContext *mov = s->priv_data;
5919     MOVTrack *track = &mov->tracks[tracknum];
5920     AVPacket pkt = { .stream_index = tracknum, .flags = AV_PKT_FLAG_KEY };
5921     int i, len;
5922
5923     track->mode = mov->mode;
5924     track->tag = MKTAG('t','e','x','t');
5925     track->timescale = MOV_TIMESCALE;
5926     track->par = avcodec_parameters_alloc();
5927     if (!track->par)
5928         return AVERROR(ENOMEM);
5929     track->par->codec_type = AVMEDIA_TYPE_SUBTITLE;
5930 #if 0
5931     // These properties are required to make QT recognize the chapter track
5932     uint8_t chapter_properties[43] = { 0, 0, 0, 0, 0, 0, 0, 1, };
5933     if (ff_alloc_extradata(track->par, sizeof(chapter_properties)))
5934         return AVERROR(ENOMEM);
5935     memcpy(track->par->extradata, chapter_properties, sizeof(chapter_properties));
5936 #else
5937     if (avio_open_dyn_buf(&pb) >= 0) {
5938         int size;
5939         uint8_t *buf;
5940
5941         /* Stub header (usually for Quicktime chapter track) */
5942         // TextSampleEntry
5943         avio_wb32(pb, 0x01); // displayFlags
5944         avio_w8(pb, 0x00);   // horizontal justification
5945         avio_w8(pb, 0x00);   // vertical justification
5946         avio_w8(pb, 0x00);   // bgColourRed
5947         avio_w8(pb, 0x00);   // bgColourGreen
5948         avio_w8(pb, 0x00);   // bgColourBlue
5949         avio_w8(pb, 0x00);   // bgColourAlpha
5950         // BoxRecord
5951         avio_wb16(pb, 0x00); // defTextBoxTop
5952         avio_wb16(pb, 0x00); // defTextBoxLeft
5953         avio_wb16(pb, 0x00); // defTextBoxBottom
5954         avio_wb16(pb, 0x00); // defTextBoxRight
5955         // StyleRecord
5956         avio_wb16(pb, 0x00); // startChar
5957         avio_wb16(pb, 0x00); // endChar
5958         avio_wb16(pb, 0x01); // fontID
5959         avio_w8(pb, 0x00);   // fontStyleFlags
5960         avio_w8(pb, 0x00);   // fontSize
5961         avio_w8(pb, 0x00);   // fgColourRed
5962         avio_w8(pb, 0x00);   // fgColourGreen
5963         avio_w8(pb, 0x00);   // fgColourBlue
5964         avio_w8(pb, 0x00);   // fgColourAlpha
5965         // FontTableBox
5966         avio_wb32(pb, 0x0D); // box size
5967         ffio_wfourcc(pb, "ftab"); // box atom name
5968         avio_wb16(pb, 0x01); // entry count
5969         // FontRecord
5970         avio_wb16(pb, 0x01); // font ID
5971         avio_w8(pb, 0x00);   // font name length
5972
5973         if ((size = avio_close_dyn_buf(pb, &buf)) > 0) {
5974             track->par->extradata = buf;
5975             track->par->extradata_size = size;
5976         } else {
5977             av_freep(&buf);
5978         }
5979     }
5980 #endif
5981
5982     for (i = 0; i < s->nb_chapters; i++) {
5983         AVChapter *c = s->chapters[i];
5984         AVDictionaryEntry *t;
5985
5986         int64_t end = av_rescale_q(c->end, c->time_base, (AVRational){1,MOV_TIMESCALE});
5987         pkt.pts = pkt.dts = av_rescale_q(c->start, c->time_base, (AVRational){1,MOV_TIMESCALE});
5988         pkt.duration = end - pkt.dts;
5989
5990         if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
5991             static const char encd[12] = {
5992                 0x00, 0x00, 0x00, 0x0C,
5993                 'e',  'n',  'c',  'd',
5994                 0x00, 0x00, 0x01, 0x00 };
5995             len      = strlen(t->value);
5996             pkt.size = len + 2 + 12;
5997             pkt.data = av_malloc(pkt.size);
5998             if (!pkt.data)
5999                 return AVERROR(ENOMEM);
6000             AV_WB16(pkt.data, len);
6001             memcpy(pkt.data + 2, t->value, len);
6002             memcpy(pkt.data + len + 2, encd, sizeof(encd));
6003             ff_mov_write_packet(s, &pkt);
6004             av_freep(&pkt.data);
6005         }
6006     }
6007
6008     return 0;
6009 }
6010
6011
6012 static int mov_check_timecode_track(AVFormatContext *s, AVTimecode *tc, int src_index, const char *tcstr)
6013 {
6014     int ret;
6015
6016     /* compute the frame number */
6017     ret = av_timecode_init_from_string(tc, find_fps(s,  s->streams[src_index]), tcstr, s);
6018     return ret;
6019 }
6020
6021 static int mov_create_timecode_track(AVFormatContext *s, int index, int src_index, AVTimecode tc)
6022 {
6023     int ret;
6024     MOVMuxContext *mov  = s->priv_data;
6025     MOVTrack *track     = &mov->tracks[index];
6026     AVStream *src_st    = s->streams[src_index];
6027     AVPacket pkt    = {.stream_index = index, .flags = AV_PKT_FLAG_KEY, .size = 4};
6028     AVRational rate = find_fps(s, src_st);
6029
6030     /* tmcd track based on video stream */
6031     track->mode      = mov->mode;
6032     track->tag       = MKTAG('t','m','c','d');
6033     track->src_track = src_index;
6034     track->timescale = mov->tracks[src_index].timescale;
6035     if (tc.flags & AV_TIMECODE_FLAG_DROPFRAME)
6036         track->timecode_flags |= MOV_TIMECODE_FLAG_DROPFRAME;
6037
6038     /* set st to src_st for metadata access*/
6039     track->st = src_st;
6040
6041     /* encode context: tmcd data stream */
6042     track->par = avcodec_parameters_alloc();
6043     if (!track->par)
6044         return AVERROR(ENOMEM);
6045     track->par->codec_type = AVMEDIA_TYPE_DATA;
6046     track->par->codec_tag  = track->tag;
6047     track->st->avg_frame_rate = av_inv_q(rate);
6048
6049     /* the tmcd track just contains one packet with the frame number */
6050     pkt.data = av_malloc(pkt.size);
6051     if (!pkt.data)
6052         return AVERROR(ENOMEM);
6053     AV_WB32(pkt.data, tc.start);
6054     ret = ff_mov_write_packet(s, &pkt);
6055     av_free(pkt.data);
6056     return ret;
6057 }
6058
6059 /*
6060  * st->disposition controls the "enabled" flag in the tkhd tag.
6061  * QuickTime will not play a track if it is not enabled.  So make sure
6062  * that one track of each type (audio, video, subtitle) is enabled.
6063  *
6064  * Subtitles are special.  For audio and video, setting "enabled" also
6065  * makes the track "default" (i.e. it is rendered when played). For
6066  * subtitles, an "enabled" subtitle is not rendered by default, but
6067  * if no subtitle is enabled, the subtitle menu in QuickTime will be
6068  * empty!
6069  */
6070 static void enable_tracks(AVFormatContext *s)
6071 {
6072     MOVMuxContext *mov = s->priv_data;
6073     int i;
6074     int enabled[AVMEDIA_TYPE_NB];
6075     int first[AVMEDIA_TYPE_NB];
6076
6077     for (i = 0; i < AVMEDIA_TYPE_NB; i++) {
6078         enabled[i] = 0;
6079         first[i] = -1;
6080     }
6081
6082     for (i = 0; i < s->nb_streams; i++) {
6083         AVStream *st = s->streams[i];
6084
6085         if (st->codecpar->codec_type <= AVMEDIA_TYPE_UNKNOWN ||
6086             st->codecpar->codec_type >= AVMEDIA_TYPE_NB ||
6087             is_cover_image(st))
6088             continue;
6089
6090         if (first[st->codecpar->codec_type] < 0)
6091             first[st->codecpar->codec_type] = i;
6092         if (st->disposition & AV_DISPOSITION_DEFAULT) {
6093             mov->tracks[i].flags |= MOV_TRACK_ENABLED;
6094             enabled[st->codecpar->codec_type]++;
6095         }
6096     }
6097
6098     for (i = 0; i < AVMEDIA_TYPE_NB; i++) {
6099         switch (i) {
6100         case AVMEDIA_TYPE_VIDEO:
6101         case AVMEDIA_TYPE_AUDIO:
6102         case AVMEDIA_TYPE_SUBTITLE:
6103             if (enabled[i] > 1)
6104                 mov->per_stream_grouping = 1;
6105             if (!enabled[i] && first[i] >= 0)
6106                 mov->tracks[first[i]].flags |= MOV_TRACK_ENABLED;
6107             break;
6108         }
6109     }
6110 }
6111
6112 static void mov_free(AVFormatContext *s)
6113 {
6114     MOVMuxContext *mov = s->priv_data;
6115     int i;
6116
6117     if (mov->chapter_track) {
6118         if (mov->tracks[mov->chapter_track].par)
6119             av_freep(&mov->tracks[mov->chapter_track].par->extradata);
6120         av_freep(&mov->tracks[mov->chapter_track].par);
6121     }
6122
6123     for (i = 0; i < mov->nb_streams; i++) {
6124         if (mov->tracks[i].tag == MKTAG('r','t','p',' '))
6125             ff_mov_close_hinting(&mov->tracks[i]);
6126         else if (mov->tracks[i].tag == MKTAG('t','m','c','d') && mov->nb_meta_tmcd)
6127             av_freep(&mov->tracks[i].par);
6128         av_freep(&mov->tracks[i].cluster);
6129         av_freep(&mov->tracks[i].frag_info);
6130         av_packet_unref(&mov->tracks[i].cover_image);
6131
6132         if (mov->tracks[i].eac3_priv) {
6133             struct eac3_info *info = mov->tracks[i].eac3_priv;
6134             av_packet_unref(&info->pkt);
6135             av_freep(&mov->tracks[i].eac3_priv);
6136         }
6137         if (mov->tracks[i].vos_len)
6138             av_freep(&mov->tracks[i].vos_data);
6139
6140         ff_mov_cenc_free(&mov->tracks[i].cenc);
6141     }
6142
6143     av_freep(&mov->tracks);
6144 }
6145
6146 static uint32_t rgb_to_yuv(uint32_t rgb)
6147 {
6148     uint8_t r, g, b;
6149     int y, cb, cr;
6150
6151     r = (rgb >> 16) & 0xFF;
6152     g = (rgb >>  8) & 0xFF;
6153     b = (rgb      ) & 0xFF;
6154
6155     y  = av_clip_uint8(( 16000 +  257 * r + 504 * g +  98 * b)/1000);
6156     cb = av_clip_uint8((128000 -  148 * r - 291 * g + 439 * b)/1000);
6157     cr = av_clip_uint8((128000 +  439 * r - 368 * g -  71 * b)/1000);
6158
6159     return (y << 16) | (cr << 8) | cb;
6160 }
6161
6162 static int mov_create_dvd_sub_decoder_specific_info(MOVTrack *track,
6163                                                     AVStream *st)
6164 {
6165     int i, width = 720, height = 480;
6166     int have_palette = 0, have_size = 0;
6167     uint32_t palette[16];
6168     char *cur = st->codecpar->extradata;
6169
6170     while (cur && *cur) {
6171         if (strncmp("palette:", cur, 8) == 0) {
6172             int i, count;
6173             count = sscanf(cur + 8,
6174                 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
6175                 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
6176                 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
6177                 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32"",
6178                 &palette[ 0], &palette[ 1], &palette[ 2], &palette[ 3],
6179                 &palette[ 4], &palette[ 5], &palette[ 6], &palette[ 7],
6180                 &palette[ 8], &palette[ 9], &palette[10], &palette[11],
6181                 &palette[12], &palette[13], &palette[14], &palette[15]);
6182
6183             for (i = 0; i < count; i++) {
6184                 palette[i] = rgb_to_yuv(palette[i]);
6185             }
6186             have_palette = 1;
6187         } else if (!strncmp("size:", cur, 5)) {
6188             sscanf(cur + 5, "%dx%d", &width, &height);
6189             have_size = 1;
6190         }
6191         if (have_palette && have_size)
6192             break;
6193         cur += strcspn(cur, "\n\r");
6194         cur += strspn(cur, "\n\r");
6195     }
6196     if (have_palette) {
6197         track->vos_data = av_malloc(16*4 + AV_INPUT_BUFFER_PADDING_SIZE);
6198         if (!track->vos_data)
6199             return AVERROR(ENOMEM);
6200         for (i = 0; i < 16; i++) {
6201             AV_WB32(track->vos_data + i * 4, palette[i]);
6202         }
6203         memset(track->vos_data + 16*4, 0, AV_INPUT_BUFFER_PADDING_SIZE);
6204         track->vos_len = 16 * 4;
6205     }
6206     st->codecpar->width = width;
6207     st->codecpar->height = track->height = height;
6208
6209     return 0;
6210 }
6211
6212 static int mov_init(AVFormatContext *s)
6213 {
6214     MOVMuxContext *mov = s->priv_data;
6215     AVDictionaryEntry *global_tcr = av_dict_get(s->metadata, "timecode", NULL, 0);
6216     int i, ret;
6217
6218     mov->fc = s;
6219
6220     /* Default mode == MP4 */
6221     mov->mode = MODE_MP4;
6222
6223     if (s->oformat) {
6224         if (!strcmp("3gp", s->oformat->name)) mov->mode = MODE_3GP;
6225         else if (!strcmp("3g2", s->oformat->name)) mov->mode = MODE_3GP|MODE_3G2;
6226         else if (!strcmp("mov", s->oformat->name)) mov->mode = MODE_MOV;
6227         else if (!strcmp("psp", s->oformat->name)) mov->mode = MODE_PSP;
6228         else if (!strcmp("ipod",s->oformat->name)) mov->mode = MODE_IPOD;
6229         else if (!strcmp("ismv",s->oformat->name)) mov->mode = MODE_ISM;
6230         else if (!strcmp("f4v", s->oformat->name)) mov->mode = MODE_F4V;
6231     }
6232
6233     if (mov->flags & FF_MOV_FLAG_DELAY_MOOV)
6234         mov->flags |= FF_MOV_FLAG_EMPTY_MOOV;
6235
6236     /* Set the FRAGMENT flag if any of the fragmentation methods are
6237      * enabled. */
6238     if (mov->max_fragment_duration || mov->max_fragment_size ||
6239         mov->flags & (FF_MOV_FLAG_EMPTY_MOOV |
6240                       FF_MOV_FLAG_FRAG_KEYFRAME |
6241                       FF_MOV_FLAG_FRAG_CUSTOM |
6242                       FF_MOV_FLAG_FRAG_EVERY_FRAME))
6243         mov->flags |= FF_MOV_FLAG_FRAGMENT;
6244
6245     /* Set other implicit flags immediately */
6246     if (mov->mode == MODE_ISM)
6247         mov->flags |= FF_MOV_FLAG_EMPTY_MOOV | FF_MOV_FLAG_SEPARATE_MOOF |
6248                       FF_MOV_FLAG_FRAGMENT | FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS;
6249     if (mov->flags & FF_MOV_FLAG_DASH)
6250         mov->flags |= FF_MOV_FLAG_FRAGMENT | FF_MOV_FLAG_EMPTY_MOOV |
6251                       FF_MOV_FLAG_DEFAULT_BASE_MOOF;
6252     if (mov->flags & FF_MOV_FLAG_CMAF)
6253         mov->flags |= FF_MOV_FLAG_FRAGMENT | FF_MOV_FLAG_EMPTY_MOOV |
6254                       FF_MOV_FLAG_DEFAULT_BASE_MOOF | FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS;
6255
6256     if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV && s->flags & AVFMT_FLAG_AUTO_BSF) {
6257         av_log(s, AV_LOG_VERBOSE, "Empty MOOV enabled; disabling automatic bitstream filtering\n");
6258         s->flags &= ~AVFMT_FLAG_AUTO_BSF;
6259     }
6260
6261     if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX && mov->flags & FF_MOV_FLAG_SKIP_SIDX) {
6262         av_log(s, AV_LOG_WARNING, "Global SIDX enabled; Ignoring skip_sidx option\n");
6263         mov->flags &= ~FF_MOV_FLAG_SKIP_SIDX;
6264     }
6265
6266     if (mov->flags & FF_MOV_FLAG_FASTSTART) {
6267         mov->reserved_moov_size = -1;
6268     }
6269
6270     if (mov->use_editlist < 0) {
6271         mov->use_editlist = 1;
6272         if (mov->flags & FF_MOV_FLAG_FRAGMENT &&
6273             !(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
6274             // If we can avoid needing an edit list by shifting the
6275             // tracks, prefer that over (trying to) write edit lists
6276             // in fragmented output.
6277             if (s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO ||
6278                 s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO)
6279                 mov->use_editlist = 0;
6280         }
6281         if (mov->flags & FF_MOV_FLAG_CMAF) {
6282             // CMAF Track requires negative cts offsets without edit lists
6283             mov->use_editlist = 0;
6284         }
6285     }
6286     if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV &&
6287         !(mov->flags & FF_MOV_FLAG_DELAY_MOOV) && mov->use_editlist)
6288         av_log(s, AV_LOG_WARNING, "No meaningful edit list will be written when using empty_moov without delay_moov\n");
6289
6290     if (mov->flags & FF_MOV_FLAG_CMAF && mov->use_editlist) {
6291         av_log(s, AV_LOG_WARNING, "Edit list enabled; Assuming writing CMAF Track File\n");
6292         mov->flags &= ~FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS;
6293     }
6294     if (!mov->use_editlist && s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO &&
6295         !(mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS))
6296         s->avoid_negative_ts = AVFMT_AVOID_NEG_TS_MAKE_ZERO;
6297
6298     /* Clear the omit_tfhd_offset flag if default_base_moof is set;
6299      * if the latter is set that's enough and omit_tfhd_offset doesn't
6300      * add anything extra on top of that. */
6301     if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET &&
6302         mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)
6303         mov->flags &= ~FF_MOV_FLAG_OMIT_TFHD_OFFSET;
6304
6305     if (mov->frag_interleave &&
6306         mov->flags & (FF_MOV_FLAG_OMIT_TFHD_OFFSET | FF_MOV_FLAG_SEPARATE_MOOF)) {
6307         av_log(s, AV_LOG_ERROR,
6308                "Sample interleaving in fragments is mutually exclusive with "
6309                "omit_tfhd_offset and separate_moof\n");
6310         return AVERROR(EINVAL);
6311     }
6312
6313     /* Non-seekable output is ok if using fragmentation. If ism_lookahead
6314      * is enabled, we don't support non-seekable output at all. */
6315     if (!(s->pb->seekable & AVIO_SEEKABLE_NORMAL) &&
6316         (!(mov->flags & FF_MOV_FLAG_FRAGMENT) || mov->ism_lookahead)) {
6317         av_log(s, AV_LOG_ERROR, "muxer does not support non seekable output\n");
6318         return AVERROR(EINVAL);
6319     }
6320
6321     mov->nb_streams = s->nb_streams;
6322     if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters)
6323         mov->chapter_track = mov->nb_streams++;
6324
6325     if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
6326         for (i = 0; i < s->nb_streams; i++)
6327             if (rtp_hinting_needed(s->streams[i]))
6328                 mov->nb_streams++;
6329     }
6330
6331     if (   mov->write_tmcd == -1 && (mov->mode == MODE_MOV || mov->mode == MODE_MP4)
6332         || mov->write_tmcd == 1) {
6333         /* +1 tmcd track for each video stream with a timecode */
6334         for (i = 0; i < s->nb_streams; i++) {
6335             AVStream *st = s->streams[i];
6336             AVDictionaryEntry *t = global_tcr;
6337             if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
6338                 (t || (t=av_dict_get(st->metadata, "timecode", NULL, 0)))) {
6339                 AVTimecode tc;
6340                 ret = mov_check_timecode_track(s, &tc, i, t->value);
6341                 if (ret >= 0)
6342                     mov->nb_meta_tmcd++;
6343             }
6344         }
6345
6346         /* check if there is already a tmcd track to remux */
6347         if (mov->nb_meta_tmcd) {
6348             for (i = 0; i < s->nb_streams; i++) {
6349                 AVStream *st = s->streams[i];
6350                 if (st->codecpar->codec_tag == MKTAG('t','m','c','d')) {
6351                     av_log(s, AV_LOG_WARNING, "You requested a copy of the original timecode track "
6352                            "so timecode metadata are now ignored\n");
6353                     mov->nb_meta_tmcd = 0;
6354                 }
6355             }
6356         }
6357
6358         mov->nb_streams += mov->nb_meta_tmcd;
6359     }
6360
6361     // Reserve an extra stream for chapters for the case where chapters
6362     // are written in the trailer
6363     mov->tracks = av_mallocz_array((mov->nb_streams + 1), sizeof(*mov->tracks));
6364     if (!mov->tracks)
6365         return AVERROR(ENOMEM);
6366
6367     if (mov->encryption_scheme_str != NULL && strcmp(mov->encryption_scheme_str, "none") != 0) {
6368         if (strcmp(mov->encryption_scheme_str, "cenc-aes-ctr") == 0) {
6369             mov->encryption_scheme = MOV_ENC_CENC_AES_CTR;
6370
6371             if (mov->encryption_key_len != AES_CTR_KEY_SIZE) {
6372                 av_log(s, AV_LOG_ERROR, "Invalid encryption key len %d expected %d\n",
6373                     mov->encryption_key_len, AES_CTR_KEY_SIZE);
6374                 return AVERROR(EINVAL);
6375             }
6376
6377             if (mov->encryption_kid_len != CENC_KID_SIZE) {
6378                 av_log(s, AV_LOG_ERROR, "Invalid encryption kid len %d expected %d\n",
6379                     mov->encryption_kid_len, CENC_KID_SIZE);
6380                 return AVERROR(EINVAL);
6381             }
6382         } else {
6383             av_log(s, AV_LOG_ERROR, "unsupported encryption scheme %s\n",
6384                 mov->encryption_scheme_str);
6385             return AVERROR(EINVAL);
6386         }
6387     }
6388
6389     for (i = 0; i < s->nb_streams; i++) {
6390         AVStream *st= s->streams[i];
6391         MOVTrack *track= &mov->tracks[i];
6392         AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0);
6393
6394         track->st  = st;
6395         track->par = st->codecpar;
6396         track->language = ff_mov_iso639_to_lang(lang?lang->value:"und", mov->mode!=MODE_MOV);
6397         if (track->language < 0)
6398             track->language = 32767;  // Unspecified Macintosh language code
6399         track->mode = mov->mode;
6400         track->tag  = mov_find_codec_tag(s, track);
6401         if (!track->tag) {
6402             av_log(s, AV_LOG_ERROR, "Could not find tag for codec %s in stream #%d, "
6403                    "codec not currently supported in container\n",
6404                    avcodec_get_name(st->codecpar->codec_id), i);
6405             return AVERROR(EINVAL);
6406         }
6407         /* If hinting of this track is enabled by a later hint track,
6408          * this is updated. */
6409         track->hint_track = -1;
6410         track->start_dts  = AV_NOPTS_VALUE;
6411         track->start_cts  = AV_NOPTS_VALUE;
6412         track->end_pts    = AV_NOPTS_VALUE;
6413         track->dts_shift  = AV_NOPTS_VALUE;
6414         if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
6415             if (track->tag == MKTAG('m','x','3','p') || track->tag == MKTAG('m','x','3','n') ||
6416                 track->tag == MKTAG('m','x','4','p') || track->tag == MKTAG('m','x','4','n') ||
6417                 track->tag == MKTAG('m','x','5','p') || track->tag == MKTAG('m','x','5','n')) {
6418                 if (st->codecpar->width != 720 || (st->codecpar->height != 608 && st->codecpar->height != 512)) {
6419                     av_log(s, AV_LOG_ERROR, "D-10/IMX must use 720x608 or 720x512 video resolution\n");
6420                     return AVERROR(EINVAL);
6421                 }
6422                 track->height = track->tag >> 24 == 'n' ? 486 : 576;
6423             }
6424             if (mov->video_track_timescale) {
6425                 track->timescale = mov->video_track_timescale;
6426                 if (mov->mode == MODE_ISM && mov->video_track_timescale != 10000000)
6427                     av_log(s, AV_LOG_WARNING, "Warning: some tools, like mp4split, assume a timescale of 10000000 for ISMV.\n");
6428             } else {
6429                 track->timescale = st->time_base.den;
6430                 while(track->timescale < 10000)
6431                     track->timescale *= 2;
6432             }
6433             if (st->codecpar->width > 65535 || st->codecpar->height > 65535) {
6434                 av_log(s, AV_LOG_ERROR, "Resolution %dx%d too large for mov/mp4\n", st->codecpar->width, st->codecpar->height);
6435                 return AVERROR(EINVAL);
6436             }
6437             if (track->mode == MODE_MOV && track->timescale > 100000)
6438                 av_log(s, AV_LOG_WARNING,
6439                        "WARNING codec timebase is very high. If duration is too long,\n"
6440                        "file may not be playable by quicktime. Specify a shorter timebase\n"
6441                        "or choose different container.\n");
6442             if (track->mode == MODE_MOV &&
6443                 track->par->codec_id == AV_CODEC_ID_RAWVIDEO &&
6444                 track->tag == MKTAG('r','a','w',' ')) {
6445                 enum AVPixelFormat pix_fmt = track->par->format;
6446                 if (pix_fmt == AV_PIX_FMT_NONE && track->par->bits_per_coded_sample == 1)
6447                     pix_fmt = AV_PIX_FMT_MONOWHITE;
6448                 track->is_unaligned_qt_rgb =
6449                         pix_fmt == AV_PIX_FMT_RGB24 ||
6450                         pix_fmt == AV_PIX_FMT_BGR24 ||
6451                         pix_fmt == AV_PIX_FMT_PAL8 ||
6452                         pix_fmt == AV_PIX_FMT_GRAY8 ||
6453                         pix_fmt == AV_PIX_FMT_MONOWHITE ||
6454                         pix_fmt == AV_PIX_FMT_MONOBLACK;
6455             }
6456             if (track->par->codec_id == AV_CODEC_ID_VP9 ||
6457                 track->par->codec_id == AV_CODEC_ID_AV1) {
6458                 if (track->mode != MODE_MP4) {
6459                     av_log(s, AV_LOG_ERROR, "%s only supported in MP4.\n", avcodec_get_name(track->par->codec_id));
6460                     return AVERROR(EINVAL);
6461                 }
6462             } else if (track->par->codec_id == AV_CODEC_ID_VP8) {
6463                 /* altref frames handling is not defined in the spec as of version v1.0,
6464                  * so just forbid muxing VP8 streams altogether until a new version does */
6465                 av_log(s, AV_LOG_ERROR, "VP8 muxing is currently not supported.\n");
6466                 return AVERROR_PATCHWELCOME;
6467             }
6468         } else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
6469             track->timescale = st->codecpar->sample_rate;
6470             if (!st->codecpar->frame_size && !av_get_bits_per_sample(st->codecpar->codec_id)) {
6471                 av_log(s, AV_LOG_WARNING, "track %d: codec frame size is not set\n", i);
6472                 track->audio_vbr = 1;
6473             }else if (st->codecpar->codec_id == AV_CODEC_ID_ADPCM_MS ||
6474                      st->codecpar->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
6475                      st->codecpar->codec_id == AV_CODEC_ID_ILBC){
6476                 if (!st->codecpar->block_align) {
6477                     av_log(s, AV_LOG_ERROR, "track %d: codec block align is not set for adpcm\n", i);
6478                     return AVERROR(EINVAL);
6479                 }
6480                 track->sample_size = st->codecpar->block_align;
6481             }else if (st->codecpar->frame_size > 1){ /* assume compressed audio */
6482                 track->audio_vbr = 1;
6483             }else{
6484                 track->sample_size = (av_get_bits_per_sample(st->codecpar->codec_id) >> 3) * st->codecpar->channels;
6485             }
6486             if (st->codecpar->codec_id == AV_CODEC_ID_ILBC ||
6487                 st->codecpar->codec_id == AV_CODEC_ID_ADPCM_IMA_QT) {
6488                 track->audio_vbr = 1;
6489             }
6490             if (track->mode != MODE_MOV &&
6491                 track->par->codec_id == AV_CODEC_ID_MP3 && track->timescale < 16000) {
6492                 if (s->strict_std_compliance >= FF_COMPLIANCE_NORMAL) {
6493                     av_log(s, AV_LOG_ERROR, "track %d: muxing mp3 at %dhz is not standard, to mux anyway set strict to -1\n",
6494                         i, track->par->sample_rate);
6495                     return AVERROR(EINVAL);
6496                 } else {
6497                     av_log(s, AV_LOG_WARNING, "track %d: muxing mp3 at %dhz is not standard in MP4\n",
6498                            i, track->par->sample_rate);
6499                 }
6500             }
6501             if (track->par->codec_id == AV_CODEC_ID_FLAC ||
6502                 track->par->codec_id == AV_CODEC_ID_TRUEHD ||
6503                 track->par->codec_id == AV_CODEC_ID_OPUS) {
6504                 if (track->mode != MODE_MP4) {
6505                     av_log(s, AV_LOG_ERROR, "%s only supported in MP4.\n", avcodec_get_name(track->par->codec_id));
6506                     return AVERROR(EINVAL);
6507                 }
6508                 if (track->par->codec_id != AV_CODEC_ID_OPUS &&
6509                     s->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
6510                     av_log(s, AV_LOG_ERROR,
6511                            "%s in MP4 support is experimental, add "
6512                            "'-strict %d' if you want to use it.\n",
6513                            avcodec_get_name(track->par->codec_id), FF_COMPLIANCE_EXPERIMENTAL);
6514                     return AVERROR_EXPERIMENTAL;
6515                 }
6516             }
6517         } else if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) {
6518             track->timescale = st->time_base.den;
6519         } else if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA) {
6520             track->timescale = st->time_base.den;
6521         } else {
6522             track->timescale = MOV_TIMESCALE;
6523         }
6524         if (!track->height)
6525             track->height = st->codecpar->height;
6526         /* The Protected Interoperable File Format (PIFF) standard, used by ISMV recommends but
6527            doesn't mandate a track timescale of 10,000,000. The muxer allows a custom timescale
6528            for video tracks, so if user-set, it isn't overwritten */
6529         if (mov->mode == MODE_ISM &&
6530             (st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO ||
6531             (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && !mov->video_track_timescale))) {
6532              track->timescale = 10000000;
6533         }
6534
6535         avpriv_set_pts_info(st, 64, 1, track->timescale);
6536
6537         if (mov->encryption_scheme == MOV_ENC_CENC_AES_CTR) {
6538             ret = ff_mov_cenc_init(&track->cenc, mov->encryption_key,
6539                 track->par->codec_id == AV_CODEC_ID_H264, s->flags & AVFMT_FLAG_BITEXACT);
6540             if (ret)
6541                 return ret;
6542         }
6543     }
6544
6545     enable_tracks(s);
6546     return 0;
6547 }
6548
6549 static int mov_write_header(AVFormatContext *s)
6550 {
6551     AVIOContext *pb = s->pb;
6552     MOVMuxContext *mov = s->priv_data;
6553     AVDictionaryEntry *t, *global_tcr = av_dict_get(s->metadata, "timecode", NULL, 0);
6554     int i, ret, hint_track = 0, tmcd_track = 0, nb_tracks = s->nb_streams;
6555
6556     if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters)
6557         nb_tracks++;
6558
6559     if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
6560         hint_track = nb_tracks;
6561         for (i = 0; i < s->nb_streams; i++)
6562             if (rtp_hinting_needed(s->streams[i]))
6563                 nb_tracks++;
6564     }
6565
6566     if (mov->nb_meta_tmcd)
6567         tmcd_track = nb_tracks;
6568
6569     for (i = 0; i < s->nb_streams; i++) {
6570         int j;
6571         AVStream *st= s->streams[i];
6572         MOVTrack *track= &mov->tracks[i];
6573
6574         /* copy extradata if it exists */
6575         if (st->codecpar->extradata_size) {
6576             if (st->codecpar->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
6577                 mov_create_dvd_sub_decoder_specific_info(track, st);
6578             else if (!TAG_IS_AVCI(track->tag) && st->codecpar->codec_id != AV_CODEC_ID_DNXHD) {
6579                 track->vos_len  = st->codecpar->extradata_size;
6580                 track->vos_data = av_malloc(track->vos_len + AV_INPUT_BUFFER_PADDING_SIZE);
6581                 if (!track->vos_data) {
6582                     return AVERROR(ENOMEM);
6583                 }
6584                 memcpy(track->vos_data, st->codecpar->extradata, track->vos_len);
6585                 memset(track->vos_data + track->vos_len, 0, AV_INPUT_BUFFER_PADDING_SIZE);
6586             }
6587         }
6588
6589         if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ||
6590             track->par->channel_layout != AV_CH_LAYOUT_MONO)
6591             continue;
6592
6593         for (j = 0; j < s->nb_streams; j++) {
6594             AVStream *stj= s->streams[j];
6595             MOVTrack *trackj= &mov->tracks[j];
6596             if (j == i)
6597                 continue;
6598
6599             if (stj->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ||
6600                 trackj->par->channel_layout != AV_CH_LAYOUT_MONO ||
6601                 trackj->language != track->language ||
6602                 trackj->tag != track->tag
6603             )
6604                 continue;
6605             track->multichannel_as_mono++;
6606         }
6607     }
6608
6609     if (!(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
6610         if ((ret = mov_write_identification(pb, s)) < 0)
6611             return ret;
6612     }
6613
6614     if (mov->reserved_moov_size){
6615         mov->reserved_header_pos = avio_tell(pb);
6616         if (mov->reserved_moov_size > 0)
6617             avio_skip(pb, mov->reserved_moov_size);
6618     }
6619
6620     if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
6621         /* If no fragmentation options have been set, set a default. */
6622         if (!(mov->flags & (FF_MOV_FLAG_FRAG_KEYFRAME |
6623                             FF_MOV_FLAG_FRAG_CUSTOM |
6624                             FF_MOV_FLAG_FRAG_EVERY_FRAME)) &&
6625             !mov->max_fragment_duration && !mov->max_fragment_size)
6626             mov->flags |= FF_MOV_FLAG_FRAG_KEYFRAME;
6627     } else {
6628         if (mov->flags & FF_MOV_FLAG_FASTSTART)
6629             mov->reserved_header_pos = avio_tell(pb);
6630         mov_write_mdat_tag(pb, mov);
6631     }
6632
6633     ff_parse_creation_time_metadata(s, &mov->time, 1);
6634     if (mov->time)
6635         mov->time += 0x7C25B080; // 1970 based -> 1904 based
6636
6637     if (mov->chapter_track)
6638         if ((ret = mov_create_chapter_track(s, mov->chapter_track)) < 0)
6639             return ret;
6640
6641     if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
6642         for (i = 0; i < s->nb_streams; i++) {
6643             if (rtp_hinting_needed(s->streams[i])) {
6644                 if ((ret = ff_mov_init_hinting(s, hint_track, i)) < 0)
6645                     return ret;
6646                 hint_track++;
6647             }
6648         }
6649     }
6650
6651     if (mov->nb_meta_tmcd) {
6652         /* Initialize the tmcd tracks */
6653         for (i = 0; i < s->nb_streams; i++) {
6654             AVStream *st = s->streams[i];
6655             t = global_tcr;
6656
6657             if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
6658                 AVTimecode tc;
6659                 if (!t)
6660                     t = av_dict_get(st->metadata, "timecode", NULL, 0);
6661                 if (!t)
6662                     continue;
6663                 if (mov_check_timecode_track(s, &tc, i, t->value) < 0)
6664                     continue;
6665                 if ((ret = mov_create_timecode_track(s, tmcd_track, i, tc)) < 0)
6666                     return ret;
6667                 tmcd_track++;
6668             }
6669         }
6670     }
6671
6672     avio_flush(pb);
6673
6674     if (mov->flags & FF_MOV_FLAG_ISML)
6675         mov_write_isml_manifest(pb, mov, s);
6676
6677     if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV &&
6678         !(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
6679         if ((ret = mov_write_moov_tag(pb, mov, s)) < 0)
6680             return ret;
6681         mov->moov_written = 1;
6682         if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
6683             mov->reserved_header_pos = avio_tell(pb);
6684     }
6685
6686     return 0;
6687 }
6688
6689 static int get_moov_size(AVFormatContext *s)
6690 {
6691     int ret;
6692     AVIOContext *moov_buf;
6693     MOVMuxContext *mov = s->priv_data;
6694
6695     if ((ret = ffio_open_null_buf(&moov_buf)) < 0)
6696         return ret;
6697     if ((ret = mov_write_moov_tag(moov_buf, mov, s)) < 0)
6698         return ret;
6699     return ffio_close_null_buf(moov_buf);
6700 }
6701
6702 static int get_sidx_size(AVFormatContext *s)
6703 {
6704     int ret;
6705     AVIOContext *buf;
6706     MOVMuxContext *mov = s->priv_data;
6707
6708     if ((ret = ffio_open_null_buf(&buf)) < 0)
6709         return ret;
6710     mov_write_sidx_tags(buf, mov, -1, 0);
6711     return ffio_close_null_buf(buf);
6712 }
6713
6714 /*
6715  * This function gets the moov size if moved to the top of the file: the chunk
6716  * offset table can switch between stco (32-bit entries) to co64 (64-bit
6717  * entries) when the moov is moved to the beginning, so the size of the moov
6718  * would change. It also updates the chunk offset tables.
6719  */
6720 static int compute_moov_size(AVFormatContext *s)
6721 {
6722     int i, moov_size, moov_size2;
6723     MOVMuxContext *mov = s->priv_data;
6724
6725     moov_size = get_moov_size(s);
6726     if (moov_size < 0)
6727         return moov_size;
6728
6729     for (i = 0; i < mov->nb_streams; i++)
6730         mov->tracks[i].data_offset += moov_size;
6731
6732     moov_size2 = get_moov_size(s);
6733     if (moov_size2 < 0)
6734         return moov_size2;
6735
6736     /* if the size changed, we just switched from stco to co64 and need to
6737      * update the offsets */
6738     if (moov_size2 != moov_size)
6739         for (i = 0; i < mov->nb_streams; i++)
6740             mov->tracks[i].data_offset += moov_size2 - moov_size;
6741
6742     return moov_size2;
6743 }
6744
6745 static int compute_sidx_size(AVFormatContext *s)
6746 {
6747     int i, sidx_size;
6748     MOVMuxContext *mov = s->priv_data;
6749
6750     sidx_size = get_sidx_size(s);
6751     if (sidx_size < 0)
6752         return sidx_size;
6753
6754     for (i = 0; i < mov->nb_streams; i++)
6755         mov->tracks[i].data_offset += sidx_size;
6756
6757     return sidx_size;
6758 }
6759
6760 static int shift_data(AVFormatContext *s)
6761 {
6762     int ret = 0, moov_size;
6763     MOVMuxContext *mov = s->priv_data;
6764     int64_t pos, pos_end;
6765     uint8_t *buf, *read_buf[2];
6766     int read_buf_id = 0;
6767     int read_size[2];
6768     AVIOContext *read_pb;
6769
6770     if (mov->flags & FF_MOV_FLAG_FRAGMENT)
6771         moov_size = compute_sidx_size(s);
6772     else
6773         moov_size = compute_moov_size(s);
6774     if (moov_size < 0)
6775         return moov_size;
6776
6777     buf = av_malloc(moov_size * 2);
6778     if (!buf)
6779         return AVERROR(ENOMEM);
6780     read_buf[0] = buf;
6781     read_buf[1] = buf + moov_size;
6782
6783     /* Shift the data: the AVIO context of the output can only be used for
6784      * writing, so we re-open the same output, but for reading. It also avoids
6785      * a read/seek/write/seek back and forth. */
6786     avio_flush(s->pb);
6787     ret = s->io_open(s, &read_pb, s->url, AVIO_FLAG_READ, NULL);
6788     if (ret < 0) {
6789         av_log(s, AV_LOG_ERROR, "Unable to re-open %s output file for "
6790                "the second pass (faststart)\n", s->url);
6791         goto end;
6792     }
6793
6794     /* mark the end of the shift to up to the last data we wrote, and get ready
6795      * for writing */
6796     pos_end = avio_tell(s->pb);
6797     avio_seek(s->pb, mov->reserved_header_pos + moov_size, SEEK_SET);
6798
6799     /* start reading at where the new moov will be placed */
6800     avio_seek(read_pb, mov->reserved_header_pos, SEEK_SET);
6801     pos = avio_tell(read_pb);
6802
6803 #define READ_BLOCK do {                                                             \
6804     read_size[read_buf_id] = avio_read(read_pb, read_buf[read_buf_id], moov_size);  \
6805     read_buf_id ^= 1;                                                               \
6806 } while (0)
6807
6808     /* shift data by chunk of at most moov_size */
6809     READ_BLOCK;
6810     do {
6811         int n;
6812         READ_BLOCK;
6813         n = read_size[read_buf_id];
6814         if (n <= 0)
6815             break;
6816         avio_write(s->pb, read_buf[read_buf_id], n);
6817         pos += n;
6818     } while (pos < pos_end);
6819     ff_format_io_close(s, &read_pb);
6820
6821 end:
6822     av_free(buf);
6823     return ret;
6824 }
6825
6826 static int mov_write_trailer(AVFormatContext *s)
6827 {
6828     MOVMuxContext *mov = s->priv_data;
6829     AVIOContext *pb = s->pb;
6830     int res = 0;
6831     int i;
6832     int64_t moov_pos;
6833
6834     if (mov->need_rewrite_extradata) {
6835         for (i = 0; i < s->nb_streams; i++) {
6836             MOVTrack *track = &mov->tracks[i];
6837             AVCodecParameters *par = track->par;
6838
6839             track->vos_len  = par->extradata_size;
6840             track->vos_data = av_malloc(track->vos_len + AV_INPUT_BUFFER_PADDING_SIZE);
6841             if (!track->vos_data)
6842                 return AVERROR(ENOMEM);
6843             memcpy(track->vos_data, par->extradata, track->vos_len);
6844             memset(track->vos_data + track->vos_len, 0, AV_INPUT_BUFFER_PADDING_SIZE);
6845         }
6846         mov->need_rewrite_extradata = 0;
6847     }
6848
6849     /*
6850      * Before actually writing the trailer, make sure that there are no
6851      * dangling subtitles, that need a terminating sample.
6852      */
6853     for (i = 0; i < mov->nb_streams; i++) {
6854         MOVTrack *trk = &mov->tracks[i];
6855         if (trk->par->codec_id == AV_CODEC_ID_MOV_TEXT &&
6856             !trk->last_sample_is_subtitle_end) {
6857             mov_write_subtitle_end_packet(s, i, trk->track_duration);
6858             trk->last_sample_is_subtitle_end = 1;
6859         }
6860     }
6861
6862     // If there were no chapters when the header was written, but there
6863     // are chapters now, write them in the trailer.  This only works
6864     // when we are not doing fragments.
6865     if (!mov->chapter_track && !(mov->flags & FF_MOV_FLAG_FRAGMENT)) {
6866         if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters) {
6867             mov->chapter_track = mov->nb_streams++;
6868             if ((res = mov_create_chapter_track(s, mov->chapter_track)) < 0)
6869                 return res;
6870         }
6871     }
6872
6873     if (!(mov->flags & FF_MOV_FLAG_FRAGMENT)) {
6874         moov_pos = avio_tell(pb);
6875
6876         /* Write size of mdat tag */
6877         if (mov->mdat_size + 8 <= UINT32_MAX) {
6878             avio_seek(pb, mov->mdat_pos, SEEK_SET);
6879             avio_wb32(pb, mov->mdat_size + 8);
6880         } else {
6881             /* overwrite 'wide' placeholder atom */
6882             avio_seek(pb, mov->mdat_pos - 8, SEEK_SET);
6883             /* special value: real atom size will be 64 bit value after
6884              * tag field */
6885             avio_wb32(pb, 1);
6886             ffio_wfourcc(pb, "mdat");
6887             avio_wb64(pb, mov->mdat_size + 16);
6888         }
6889         avio_seek(pb, mov->reserved_moov_size > 0 ? mov->reserved_header_pos : moov_pos, SEEK_SET);
6890
6891         if (mov->flags & FF_MOV_FLAG_FASTSTART) {
6892             av_log(s, AV_LOG_INFO, "Starting second pass: moving the moov atom to the beginning of the file\n");
6893             res = shift_data(s);
6894             if (res < 0)
6895                 return res;
6896             avio_seek(pb, mov->reserved_header_pos, SEEK_SET);
6897             if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
6898                 return res;
6899         } else if (mov->reserved_moov_size > 0) {
6900             int64_t size;
6901             if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
6902                 return res;
6903             size = mov->reserved_moov_size - (avio_tell(pb) - mov->reserved_header_pos);
6904             if (size < 8){
6905                 av_log(s, AV_LOG_ERROR, "reserved_moov_size is too small, needed %"PRId64" additional\n", 8-size);
6906                 return AVERROR(EINVAL);
6907             }
6908             avio_wb32(pb, size);
6909             ffio_wfourcc(pb, "free");
6910             ffio_fill(pb, 0, size - 8);
6911             avio_seek(pb, moov_pos, SEEK_SET);
6912         } else {
6913             if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
6914                 return res;
6915         }
6916         res = 0;
6917     } else {
6918         mov_auto_flush_fragment(s, 1);
6919         for (i = 0; i < mov->nb_streams; i++)
6920            mov->tracks[i].data_offset = 0;
6921         if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) {
6922             int64_t end;
6923             av_log(s, AV_LOG_INFO, "Starting second pass: inserting sidx atoms\n");
6924             res = shift_data(s);
6925             if (res < 0)
6926                 return res;
6927             end = avio_tell(pb);
6928             avio_seek(pb, mov->reserved_header_pos, SEEK_SET);
6929             mov_write_sidx_tags(pb, mov, -1, 0);
6930             avio_seek(pb, end, SEEK_SET);
6931         }
6932         if (!(mov->flags & FF_MOV_FLAG_SKIP_TRAILER)) {
6933             avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_TRAILER);
6934             mov_write_mfra_tag(pb, mov);
6935         }
6936     }
6937
6938     return res;
6939 }
6940
6941 static int mov_check_bitstream(struct AVFormatContext *s, const AVPacket *pkt)
6942 {
6943     int ret = 1;
6944     AVStream *st = s->streams[pkt->stream_index];
6945
6946     if (st->codecpar->codec_id == AV_CODEC_ID_AAC) {
6947         if (pkt->size > 2 && (AV_RB16(pkt->data) & 0xfff0) == 0xfff0)
6948             ret = ff_stream_add_bitstream_filter(st, "aac_adtstoasc", NULL);
6949     } else if (st->codecpar->codec_id == AV_CODEC_ID_VP9) {
6950         ret = ff_stream_add_bitstream_filter(st, "vp9_superframe", NULL);
6951     }
6952
6953     return ret;
6954 }
6955
6956 static const AVCodecTag codec_3gp_tags[] = {
6957     { AV_CODEC_ID_H263,     MKTAG('s','2','6','3') },
6958     { AV_CODEC_ID_H264,     MKTAG('a','v','c','1') },
6959     { AV_CODEC_ID_MPEG4,    MKTAG('m','p','4','v') },
6960     { AV_CODEC_ID_AAC,      MKTAG('m','p','4','a') },
6961     { AV_CODEC_ID_AMR_NB,   MKTAG('s','a','m','r') },
6962     { AV_CODEC_ID_AMR_WB,   MKTAG('s','a','w','b') },
6963     { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
6964     { AV_CODEC_ID_NONE, 0 },
6965 };
6966
6967 const AVCodecTag codec_mp4_tags[] = {
6968     { AV_CODEC_ID_MPEG4,           MKTAG('m', 'p', '4', 'v') },
6969     { AV_CODEC_ID_H264,            MKTAG('a', 'v', 'c', '1') },
6970     { AV_CODEC_ID_H264,            MKTAG('a', 'v', 'c', '3') },
6971     { AV_CODEC_ID_HEVC,            MKTAG('h', 'e', 'v', '1') },
6972     { AV_CODEC_ID_HEVC,            MKTAG('h', 'v', 'c', '1') },
6973     { AV_CODEC_ID_MPEG2VIDEO,      MKTAG('m', 'p', '4', 'v') },
6974     { AV_CODEC_ID_MPEG1VIDEO,      MKTAG('m', 'p', '4', 'v') },
6975     { AV_CODEC_ID_MJPEG,           MKTAG('m', 'p', '4', 'v') },
6976     { AV_CODEC_ID_PNG,             MKTAG('m', 'p', '4', 'v') },
6977     { AV_CODEC_ID_JPEG2000,        MKTAG('m', 'p', '4', 'v') },
6978     { AV_CODEC_ID_VC1,             MKTAG('v', 'c', '-', '1') },
6979     { AV_CODEC_ID_DIRAC,           MKTAG('d', 'r', 'a', 'c') },
6980     { AV_CODEC_ID_TSCC2,           MKTAG('m', 'p', '4', 'v') },
6981     { AV_CODEC_ID_VP9,             MKTAG('v', 'p', '0', '9') },
6982     { AV_CODEC_ID_AV1,             MKTAG('a', 'v', '0', '1') },
6983     { AV_CODEC_ID_AAC,             MKTAG('m', 'p', '4', 'a') },
6984     { AV_CODEC_ID_MP4ALS,          MKTAG('m', 'p', '4', 'a') },
6985     { AV_CODEC_ID_MP3,             MKTAG('m', 'p', '4', 'a') },
6986     { AV_CODEC_ID_MP2,             MKTAG('m', 'p', '4', 'a') },
6987     { AV_CODEC_ID_AC3,             MKTAG('a', 'c', '-', '3') },
6988     { AV_CODEC_ID_EAC3,            MKTAG('e', 'c', '-', '3') },
6989     { AV_CODEC_ID_DTS,             MKTAG('m', 'p', '4', 'a') },
6990     { AV_CODEC_ID_TRUEHD,          MKTAG('m', 'l', 'p', 'a') },
6991     { AV_CODEC_ID_FLAC,            MKTAG('f', 'L', 'a', 'C') },
6992     { AV_CODEC_ID_OPUS,            MKTAG('O', 'p', 'u', 's') },
6993     { AV_CODEC_ID_VORBIS,          MKTAG('m', 'p', '4', 'a') },
6994     { AV_CODEC_ID_QCELP,           MKTAG('m', 'p', '4', 'a') },
6995     { AV_CODEC_ID_EVRC,            MKTAG('m', 'p', '4', 'a') },
6996     { AV_CODEC_ID_DVD_SUBTITLE,    MKTAG('m', 'p', '4', 's') },
6997     { AV_CODEC_ID_MOV_TEXT,        MKTAG('t', 'x', '3', 'g') },
6998     { AV_CODEC_ID_BIN_DATA,        MKTAG('g', 'p', 'm', 'd') },
6999     { AV_CODEC_ID_MPEGH_3D_AUDIO,  MKTAG('m', 'h', 'm', '1') },
7000     { AV_CODEC_ID_NONE,               0 },
7001 };
7002
7003 const AVCodecTag codec_ism_tags[] = {
7004     { AV_CODEC_ID_WMAPRO      , MKTAG('w', 'm', 'a', ' ') },
7005     { AV_CODEC_ID_NONE        ,    0 },
7006 };
7007
7008 static const AVCodecTag codec_ipod_tags[] = {
7009     { AV_CODEC_ID_H264,     MKTAG('a','v','c','1') },
7010     { AV_CODEC_ID_MPEG4,    MKTAG('m','p','4','v') },
7011     { AV_CODEC_ID_AAC,      MKTAG('m','p','4','a') },
7012     { AV_CODEC_ID_ALAC,     MKTAG('a','l','a','c') },
7013     { AV_CODEC_ID_AC3,      MKTAG('a','c','-','3') },
7014     { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
7015     { AV_CODEC_ID_MOV_TEXT, MKTAG('t','e','x','t') },
7016     { AV_CODEC_ID_NONE, 0 },
7017 };
7018
7019 static const AVCodecTag codec_f4v_tags[] = {
7020     { AV_CODEC_ID_MP3,    MKTAG('.','m','p','3') },
7021     { AV_CODEC_ID_AAC,    MKTAG('m','p','4','a') },
7022     { AV_CODEC_ID_H264,   MKTAG('a','v','c','1') },
7023     { AV_CODEC_ID_VP6A,   MKTAG('V','P','6','A') },
7024     { AV_CODEC_ID_VP6F,   MKTAG('V','P','6','F') },
7025     { AV_CODEC_ID_NONE, 0 },
7026 };
7027
7028 #if CONFIG_MOV_MUXER
7029 MOV_CLASS(mov)
7030 AVOutputFormat ff_mov_muxer = {
7031     .name              = "mov",
7032     .long_name         = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
7033     .extensions        = "mov",
7034     .priv_data_size    = sizeof(MOVMuxContext),
7035     .audio_codec       = AV_CODEC_ID_AAC,
7036     .video_codec       = CONFIG_LIBX264_ENCODER ?
7037                          AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
7038     .init              = mov_init,
7039     .write_header      = mov_write_header,
7040     .write_packet      = mov_write_packet,
7041     .write_trailer     = mov_write_trailer,
7042     .deinit            = mov_free,
7043     .flags             = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
7044     .codec_tag         = (const AVCodecTag* const []){
7045         ff_codec_movvideo_tags, ff_codec_movaudio_tags, ff_codec_movsubtitle_tags, 0
7046     },
7047     .check_bitstream   = mov_check_bitstream,
7048     .priv_class        = &mov_muxer_class,
7049 };
7050 #endif
7051 #if CONFIG_TGP_MUXER
7052 MOV_CLASS(tgp)
7053 AVOutputFormat ff_tgp_muxer = {
7054     .name              = "3gp",
7055     .long_name         = NULL_IF_CONFIG_SMALL("3GP (3GPP file format)"),
7056     .extensions        = "3gp",
7057     .priv_data_size    = sizeof(MOVMuxContext),
7058     .audio_codec       = AV_CODEC_ID_AMR_NB,
7059     .video_codec       = AV_CODEC_ID_H263,
7060     .init              = mov_init,
7061     .write_header      = mov_write_header,
7062     .write_packet      = mov_write_packet,
7063     .write_trailer     = mov_write_trailer,
7064     .deinit            = mov_free,
7065     .flags             = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
7066     .codec_tag         = (const AVCodecTag* const []){ codec_3gp_tags, 0 },
7067     .check_bitstream   = mov_check_bitstream,
7068     .priv_class        = &tgp_muxer_class,
7069 };
7070 #endif
7071 #if CONFIG_MP4_MUXER
7072 MOV_CLASS(mp4)
7073 AVOutputFormat ff_mp4_muxer = {
7074     .name              = "mp4",
7075     .long_name         = NULL_IF_CONFIG_SMALL("MP4 (MPEG-4 Part 14)"),
7076     .mime_type         = "video/mp4",
7077     .extensions        = "mp4",
7078     .priv_data_size    = sizeof(MOVMuxContext),
7079     .audio_codec       = AV_CODEC_ID_AAC,
7080     .video_codec       = CONFIG_LIBX264_ENCODER ?
7081                          AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
7082     .init              = mov_init,
7083     .write_header      = mov_write_header,
7084     .write_packet      = mov_write_packet,
7085     .write_trailer     = mov_write_trailer,
7086     .deinit            = mov_free,
7087     .flags             = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
7088     .codec_tag         = (const AVCodecTag* const []){ codec_mp4_tags, 0 },
7089     .check_bitstream   = mov_check_bitstream,
7090     .priv_class        = &mp4_muxer_class,
7091 };
7092 #endif
7093 #if CONFIG_PSP_MUXER
7094 MOV_CLASS(psp)
7095 AVOutputFormat ff_psp_muxer = {
7096     .name              = "psp",
7097     .long_name         = NULL_IF_CONFIG_SMALL("PSP MP4 (MPEG-4 Part 14)"),
7098     .extensions        = "mp4,psp",
7099     .priv_data_size    = sizeof(MOVMuxContext),
7100     .audio_codec       = AV_CODEC_ID_AAC,
7101     .video_codec       = CONFIG_LIBX264_ENCODER ?
7102                          AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
7103     .init              = mov_init,
7104     .write_header      = mov_write_header,
7105     .write_packet      = mov_write_packet,
7106     .write_trailer     = mov_write_trailer,
7107     .deinit            = mov_free,
7108     .flags             = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
7109     .codec_tag         = (const AVCodecTag* const []){ codec_mp4_tags, 0 },
7110     .check_bitstream   = mov_check_bitstream,
7111     .priv_class        = &psp_muxer_class,
7112 };
7113 #endif
7114 #if CONFIG_TG2_MUXER
7115 MOV_CLASS(tg2)
7116 AVOutputFormat ff_tg2_muxer = {
7117     .name              = "3g2",
7118     .long_name         = NULL_IF_CONFIG_SMALL("3GP2 (3GPP2 file format)"),
7119     .extensions        = "3g2",
7120     .priv_data_size    = sizeof(MOVMuxContext),
7121     .audio_codec       = AV_CODEC_ID_AMR_NB,
7122     .video_codec       = AV_CODEC_ID_H263,
7123     .init              = mov_init,
7124     .write_header      = mov_write_header,
7125     .write_packet      = mov_write_packet,
7126     .write_trailer     = mov_write_trailer,
7127     .deinit            = mov_free,
7128     .flags             = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
7129     .codec_tag         = (const AVCodecTag* const []){ codec_3gp_tags, 0 },
7130     .check_bitstream   = mov_check_bitstream,
7131     .priv_class        = &tg2_muxer_class,
7132 };
7133 #endif
7134 #if CONFIG_IPOD_MUXER
7135 MOV_CLASS(ipod)
7136 AVOutputFormat ff_ipod_muxer = {
7137     .name              = "ipod",
7138     .long_name         = NULL_IF_CONFIG_SMALL("iPod H.264 MP4 (MPEG-4 Part 14)"),
7139     .mime_type         = "video/mp4",
7140     .extensions        = "m4v,m4a,m4b",
7141     .priv_data_size    = sizeof(MOVMuxContext),
7142     .audio_codec       = AV_CODEC_ID_AAC,
7143     .video_codec       = AV_CODEC_ID_H264,
7144     .init              = mov_init,
7145     .write_header      = mov_write_header,
7146     .write_packet      = mov_write_packet,
7147     .write_trailer     = mov_write_trailer,
7148     .deinit            = mov_free,
7149     .flags             = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
7150     .codec_tag         = (const AVCodecTag* const []){ codec_ipod_tags, 0 },
7151     .check_bitstream   = mov_check_bitstream,
7152     .priv_class        = &ipod_muxer_class,
7153 };
7154 #endif
7155 #if CONFIG_ISMV_MUXER
7156 MOV_CLASS(ismv)
7157 AVOutputFormat ff_ismv_muxer = {
7158     .name              = "ismv",
7159     .long_name         = NULL_IF_CONFIG_SMALL("ISMV/ISMA (Smooth Streaming)"),
7160     .mime_type         = "video/mp4",
7161     .extensions        = "ismv,isma",
7162     .priv_data_size    = sizeof(MOVMuxContext),
7163     .audio_codec       = AV_CODEC_ID_AAC,
7164     .video_codec       = AV_CODEC_ID_H264,
7165     .init              = mov_init,
7166     .write_header      = mov_write_header,
7167     .write_packet      = mov_write_packet,
7168     .write_trailer     = mov_write_trailer,
7169     .deinit            = mov_free,
7170     .flags             = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
7171     .codec_tag         = (const AVCodecTag* const []){
7172         codec_mp4_tags, codec_ism_tags, 0 },
7173     .check_bitstream   = mov_check_bitstream,
7174     .priv_class        = &ismv_muxer_class,
7175 };
7176 #endif
7177 #if CONFIG_F4V_MUXER
7178 MOV_CLASS(f4v)
7179 AVOutputFormat ff_f4v_muxer = {
7180     .name              = "f4v",
7181     .long_name         = NULL_IF_CONFIG_SMALL("F4V Adobe Flash Video"),
7182     .mime_type         = "application/f4v",
7183     .extensions        = "f4v",
7184     .priv_data_size    = sizeof(MOVMuxContext),
7185     .audio_codec       = AV_CODEC_ID_AAC,
7186     .video_codec       = AV_CODEC_ID_H264,
7187     .init              = mov_init,
7188     .write_header      = mov_write_header,
7189     .write_packet      = mov_write_packet,
7190     .write_trailer     = mov_write_trailer,
7191     .deinit            = mov_free,
7192     .flags             = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH,
7193     .codec_tag         = (const AVCodecTag* const []){ codec_f4v_tags, 0 },
7194     .check_bitstream   = mov_check_bitstream,
7195     .priv_class        = &f4v_muxer_class,
7196 };
7197 #endif