]> git.sesse.net Git - ffmpeg/blob - libavformat/movenc.c
movenc: mark Opus encapsulation as stable
[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     if (track->par->color_primaries == AVCOL_PRI_UNSPECIFIED &&
1896         track->par->color_trc == AVCOL_TRC_UNSPECIFIED &&
1897         track->par->color_space == AVCOL_SPC_UNSPECIFIED) {
1898         if ((track->par->width >= 1920 && track->par->height >= 1080)
1899           || (track->par->width == 1280 && track->par->height == 720)) {
1900             av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming bt709\n");
1901             track->par->color_primaries = AVCOL_PRI_BT709;
1902         } else if (track->par->width == 720 && track->height == 576) {
1903             av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming bt470bg\n");
1904             track->par->color_primaries = AVCOL_PRI_BT470BG;
1905         } else if (track->par->width == 720 &&
1906                    (track->height == 486 || track->height == 480)) {
1907             av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming smpte170\n");
1908             track->par->color_primaries = AVCOL_PRI_SMPTE170M;
1909         } else {
1910             av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, unable to assume anything\n");
1911         }
1912         switch (track->par->color_primaries) {
1913         case AVCOL_PRI_BT709:
1914             track->par->color_trc = AVCOL_TRC_BT709;
1915             track->par->color_space = AVCOL_SPC_BT709;
1916             break;
1917         case AVCOL_PRI_SMPTE170M:
1918         case AVCOL_PRI_BT470BG:
1919             track->par->color_trc = AVCOL_TRC_BT709;
1920             track->par->color_space = AVCOL_SPC_SMPTE170M;
1921             break;
1922         }
1923     }
1924
1925     /* We should only ever be called by MOV or MP4. */
1926     av_assert0(track->mode == MODE_MOV || track->mode == MODE_MP4);
1927
1928     avio_wb32(pb, 0); /* size */
1929     ffio_wfourcc(pb, "colr");
1930     if (track->mode == MODE_MP4)
1931         ffio_wfourcc(pb, "nclx");
1932     else
1933         ffio_wfourcc(pb, "nclc");
1934     switch (track->par->color_primaries) {
1935     case AVCOL_PRI_BT709:     avio_wb16(pb, 1); break;
1936     case AVCOL_PRI_BT470BG:   avio_wb16(pb, 5); break;
1937     case AVCOL_PRI_SMPTE170M:
1938     case AVCOL_PRI_SMPTE240M: avio_wb16(pb, 6); break;
1939     case AVCOL_PRI_BT2020:    avio_wb16(pb, 9); break;
1940     case AVCOL_PRI_SMPTE431:  avio_wb16(pb, 11); break;
1941     case AVCOL_PRI_SMPTE432:  avio_wb16(pb, 12); break;
1942     default:                  avio_wb16(pb, 2);
1943     }
1944     switch (track->par->color_trc) {
1945     case AVCOL_TRC_BT709:        avio_wb16(pb, 1); break;
1946     case AVCOL_TRC_SMPTE170M:    avio_wb16(pb, 1); break; // remapped
1947     case AVCOL_TRC_SMPTE240M:    avio_wb16(pb, 7); break;
1948     case AVCOL_TRC_SMPTEST2084:  avio_wb16(pb, 16); break;
1949     case AVCOL_TRC_SMPTE428:     avio_wb16(pb, 17); break;
1950     case AVCOL_TRC_ARIB_STD_B67: avio_wb16(pb, 18); break;
1951     default:                     avio_wb16(pb, 2);
1952     }
1953     switch (track->par->color_space) {
1954     case AVCOL_SPC_BT709:      avio_wb16(pb, 1); break;
1955     case AVCOL_SPC_BT470BG:
1956     case AVCOL_SPC_SMPTE170M:  avio_wb16(pb, 6); break;
1957     case AVCOL_SPC_SMPTE240M:  avio_wb16(pb, 7); break;
1958     case AVCOL_SPC_BT2020_NCL: avio_wb16(pb, 9); break;
1959     default:                   avio_wb16(pb, 2);
1960     }
1961
1962     if (track->mode == MODE_MP4) {
1963         int full_range = track->par->color_range == AVCOL_RANGE_JPEG;
1964         avio_w8(pb, full_range << 7);
1965     }
1966
1967     return update_size(pb, pos);
1968 }
1969
1970 static void find_compressor(char * compressor_name, int len, MOVTrack *track)
1971 {
1972     AVDictionaryEntry *encoder;
1973     int xdcam_res =  (track->par->width == 1280 && track->par->height == 720)
1974                   || (track->par->width == 1440 && track->par->height == 1080)
1975                   || (track->par->width == 1920 && track->par->height == 1080);
1976
1977     if (track->mode == MODE_MOV &&
1978         (encoder = av_dict_get(track->st->metadata, "encoder", NULL, 0))) {
1979         av_strlcpy(compressor_name, encoder->value, 32);
1980     } else if (track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO && xdcam_res) {
1981         int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE;
1982         AVStream *st = track->st;
1983         int rate = defined_frame_rate(NULL, st);
1984         av_strlcatf(compressor_name, len, "XDCAM");
1985         if (track->par->format == AV_PIX_FMT_YUV422P) {
1986             av_strlcatf(compressor_name, len, " HD422");
1987         } else if(track->par->width == 1440) {
1988             av_strlcatf(compressor_name, len, " HD");
1989         } else
1990             av_strlcatf(compressor_name, len, " EX");
1991
1992         av_strlcatf(compressor_name, len, " %d%c", track->par->height, interlaced ? 'i' : 'p');
1993
1994         av_strlcatf(compressor_name, len, "%d", rate * (interlaced + 1));
1995     }
1996 }
1997
1998 static int mov_write_video_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
1999 {
2000     int64_t pos = avio_tell(pb);
2001     char compressor_name[32] = { 0 };
2002     int avid = 0;
2003
2004     int uncompressed_ycbcr = ((track->par->codec_id == AV_CODEC_ID_RAWVIDEO && track->par->format == AV_PIX_FMT_UYVY422)
2005                            || (track->par->codec_id == AV_CODEC_ID_RAWVIDEO && track->par->format == AV_PIX_FMT_YUYV422)
2006                            ||  track->par->codec_id == AV_CODEC_ID_V308
2007                            ||  track->par->codec_id == AV_CODEC_ID_V408
2008                            ||  track->par->codec_id == AV_CODEC_ID_V410
2009                            ||  track->par->codec_id == AV_CODEC_ID_V210);
2010
2011     avio_wb32(pb, 0); /* size */
2012     if (mov->encryption_scheme != MOV_ENC_NONE) {
2013         ffio_wfourcc(pb, "encv");
2014     } else {
2015         avio_wl32(pb, track->tag); // store it byteswapped
2016     }
2017     avio_wb32(pb, 0); /* Reserved */
2018     avio_wb16(pb, 0); /* Reserved */
2019     avio_wb16(pb, 1); /* Data-reference index */
2020
2021     if (uncompressed_ycbcr) {
2022         avio_wb16(pb, 2); /* Codec stream version */
2023     } else {
2024         avio_wb16(pb, 0); /* Codec stream version */
2025     }
2026     avio_wb16(pb, 0); /* Codec stream revision (=0) */
2027     if (track->mode == MODE_MOV) {
2028         ffio_wfourcc(pb, "FFMP"); /* Vendor */
2029         if (track->par->codec_id == AV_CODEC_ID_RAWVIDEO || uncompressed_ycbcr) {
2030             avio_wb32(pb, 0); /* Temporal Quality */
2031             avio_wb32(pb, 0x400); /* Spatial Quality = lossless*/
2032         } else {
2033             avio_wb32(pb, 0x200); /* Temporal Quality = normal */
2034             avio_wb32(pb, 0x200); /* Spatial Quality = normal */
2035         }
2036     } else {
2037         avio_wb32(pb, 0); /* Reserved */
2038         avio_wb32(pb, 0); /* Reserved */
2039         avio_wb32(pb, 0); /* Reserved */
2040     }
2041     avio_wb16(pb, track->par->width); /* Video width */
2042     avio_wb16(pb, track->height); /* Video height */
2043     avio_wb32(pb, 0x00480000); /* Horizontal resolution 72dpi */
2044     avio_wb32(pb, 0x00480000); /* Vertical resolution 72dpi */
2045     avio_wb32(pb, 0); /* Data size (= 0) */
2046     avio_wb16(pb, 1); /* Frame count (= 1) */
2047
2048     /* FIXME not sure, ISO 14496-1 draft where it shall be set to 0 */
2049     find_compressor(compressor_name, 32, track);
2050     avio_w8(pb, strlen(compressor_name));
2051     avio_write(pb, compressor_name, 31);
2052
2053     if (track->mode == MODE_MOV &&
2054        (track->par->codec_id == AV_CODEC_ID_V410 || track->par->codec_id == AV_CODEC_ID_V210))
2055         avio_wb16(pb, 0x18);
2056     else if (track->mode == MODE_MOV && track->par->bits_per_coded_sample)
2057         avio_wb16(pb, track->par->bits_per_coded_sample |
2058                   (track->par->format == AV_PIX_FMT_GRAY8 ? 0x20 : 0));
2059     else
2060         avio_wb16(pb, 0x18); /* Reserved */
2061
2062     if (track->mode == MODE_MOV && track->par->format == AV_PIX_FMT_PAL8) {
2063         int pal_size = 1 << track->par->bits_per_coded_sample;
2064         int i;
2065         avio_wb16(pb, 0);             /* Color table ID */
2066         avio_wb32(pb, 0);             /* Color table seed */
2067         avio_wb16(pb, 0x8000);        /* Color table flags */
2068         avio_wb16(pb, pal_size - 1);  /* Color table size (zero-relative) */
2069         for (i = 0; i < pal_size; i++) {
2070             uint32_t rgb = track->palette[i];
2071             uint16_t r = (rgb >> 16) & 0xff;
2072             uint16_t g = (rgb >> 8)  & 0xff;
2073             uint16_t b = rgb         & 0xff;
2074             avio_wb16(pb, 0);
2075             avio_wb16(pb, (r << 8) | r);
2076             avio_wb16(pb, (g << 8) | g);
2077             avio_wb16(pb, (b << 8) | b);
2078         }
2079     } else
2080         avio_wb16(pb, 0xffff); /* Reserved */
2081
2082     if (track->tag == MKTAG('m','p','4','v'))
2083         mov_write_esds_tag(pb, track);
2084     else if (track->par->codec_id == AV_CODEC_ID_H263)
2085         mov_write_d263_tag(pb);
2086     else if (track->par->codec_id == AV_CODEC_ID_AVUI ||
2087             track->par->codec_id == AV_CODEC_ID_SVQ3) {
2088         mov_write_extradata_tag(pb, track);
2089         avio_wb32(pb, 0);
2090     } else if (track->par->codec_id == AV_CODEC_ID_DNXHD) {
2091         mov_write_avid_tag(pb, track);
2092         avid = 1;
2093     } else if (track->par->codec_id == AV_CODEC_ID_HEVC)
2094         mov_write_hvcc_tag(pb, track);
2095     else if (track->par->codec_id == AV_CODEC_ID_H264 && !TAG_IS_AVCI(track->tag)) {
2096         mov_write_avcc_tag(pb, track);
2097         if (track->mode == MODE_IPOD)
2098             mov_write_uuid_tag_ipod(pb);
2099     } else if (track->par->codec_id == AV_CODEC_ID_VP9) {
2100         mov_write_vpcc_tag(mov->fc, pb, track);
2101     } else if (track->par->codec_id == AV_CODEC_ID_AV1) {
2102         mov_write_av1c_tag(pb, track);
2103     } else if (track->par->codec_id == AV_CODEC_ID_VC1 && track->vos_len > 0)
2104         mov_write_dvc1_tag(pb, track);
2105     else if (track->par->codec_id == AV_CODEC_ID_VP6F ||
2106              track->par->codec_id == AV_CODEC_ID_VP6A) {
2107         /* Don't write any potential extradata here - the cropping
2108          * is signalled via the normal width/height fields. */
2109     } else if (track->par->codec_id == AV_CODEC_ID_R10K) {
2110         if (track->par->codec_tag == MKTAG('R','1','0','k'))
2111             mov_write_dpxe_tag(pb, track);
2112     } else if (track->vos_len > 0)
2113         mov_write_glbl_tag(pb, track);
2114
2115     if (track->par->codec_id != AV_CODEC_ID_H264 &&
2116         track->par->codec_id != AV_CODEC_ID_MPEG4 &&
2117         track->par->codec_id != AV_CODEC_ID_DNXHD) {
2118         int field_order = track->par->field_order;
2119
2120 #if FF_API_LAVF_AVCTX
2121     FF_DISABLE_DEPRECATION_WARNINGS
2122     if (field_order != track->st->codec->field_order && track->st->codec->field_order != AV_FIELD_UNKNOWN)
2123         field_order = track->st->codec->field_order;
2124     FF_ENABLE_DEPRECATION_WARNINGS
2125 #endif
2126
2127         if (field_order != AV_FIELD_UNKNOWN)
2128             mov_write_fiel_tag(pb, track, field_order);
2129     }
2130
2131     if (mov->flags & FF_MOV_FLAG_WRITE_GAMA) {
2132         if (track->mode == MODE_MOV)
2133             mov_write_gama_tag(s, pb, track, mov->gamma);
2134         else
2135             av_log(mov->fc, AV_LOG_WARNING, "Not writing 'gama' atom. Format is not MOV.\n");
2136     }
2137     if (mov->flags & FF_MOV_FLAG_WRITE_COLR) {
2138         if (track->mode == MODE_MOV || track->mode == MODE_MP4)
2139             mov_write_colr_tag(pb, track, mov->flags & FF_MOV_FLAG_PREFER_ICC);
2140         else
2141             av_log(mov->fc, AV_LOG_WARNING, "Not writing 'colr' atom. Format is not MOV or MP4.\n");
2142     }
2143
2144     if (track->mode == MODE_MP4 && mov->fc->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL) {
2145         AVStereo3D* stereo_3d = (AVStereo3D*) av_stream_get_side_data(track->st, AV_PKT_DATA_STEREO3D, NULL);
2146         AVSphericalMapping* spherical_mapping = (AVSphericalMapping*)av_stream_get_side_data(track->st, AV_PKT_DATA_SPHERICAL, NULL);
2147
2148         if (stereo_3d)
2149             mov_write_st3d_tag(s, pb, stereo_3d);
2150         if (spherical_mapping)
2151             mov_write_sv3d_tag(mov->fc, pb, spherical_mapping);
2152     }
2153
2154     if (track->par->sample_aspect_ratio.den && track->par->sample_aspect_ratio.num) {
2155         mov_write_pasp_tag(pb, track);
2156     }
2157
2158     if (uncompressed_ycbcr){
2159         mov_write_clap_tag(pb, track);
2160     }
2161
2162     if (mov->encryption_scheme != MOV_ENC_NONE) {
2163         ff_mov_cenc_write_sinf_tag(track, pb, mov->encryption_kid);
2164     }
2165
2166     /* extra padding for avid stsd */
2167     /* https://developer.apple.com/library/mac/documentation/QuickTime/QTFF/QTFFChap2/qtff2.html#//apple_ref/doc/uid/TP40000939-CH204-61112 */
2168     if (avid)
2169         avio_wb32(pb, 0);
2170
2171     return update_size(pb, pos);
2172 }
2173
2174 static int mov_write_rtp_tag(AVIOContext *pb, MOVTrack *track)
2175 {
2176     int64_t pos = avio_tell(pb);
2177     avio_wb32(pb, 0); /* size */
2178     ffio_wfourcc(pb, "rtp ");
2179     avio_wb32(pb, 0); /* Reserved */
2180     avio_wb16(pb, 0); /* Reserved */
2181     avio_wb16(pb, 1); /* Data-reference index */
2182
2183     avio_wb16(pb, 1); /* Hint track version */
2184     avio_wb16(pb, 1); /* Highest compatible version */
2185     avio_wb32(pb, track->max_packet_size); /* Max packet size */
2186
2187     avio_wb32(pb, 12); /* size */
2188     ffio_wfourcc(pb, "tims");
2189     avio_wb32(pb, track->timescale);
2190
2191     return update_size(pb, pos);
2192 }
2193
2194 static int mov_write_source_reference_tag(AVIOContext *pb, MOVTrack *track, const char *reel_name)
2195 {
2196     uint64_t str_size =strlen(reel_name);
2197     int64_t pos = avio_tell(pb);
2198
2199     if (str_size >= UINT16_MAX){
2200         av_log(NULL, AV_LOG_ERROR, "reel_name length %"PRIu64" is too large\n", str_size);
2201         avio_wb16(pb, 0);
2202         return AVERROR(EINVAL);
2203     }
2204
2205     avio_wb32(pb, 0);                              /* size */
2206     ffio_wfourcc(pb, "name");                      /* Data format */
2207     avio_wb16(pb, str_size);                       /* string size */
2208     avio_wb16(pb, track->language);                /* langcode */
2209     avio_write(pb, reel_name, str_size);           /* reel name */
2210     return update_size(pb,pos);
2211 }
2212
2213 static int mov_write_tmcd_tag(AVIOContext *pb, MOVTrack *track)
2214 {
2215     int64_t pos = avio_tell(pb);
2216 #if 1
2217     int frame_duration;
2218     int nb_frames;
2219     AVDictionaryEntry *t = NULL;
2220
2221     if (!track->st->avg_frame_rate.num || !track->st->avg_frame_rate.den) {
2222 #if FF_API_LAVF_AVCTX
2223     FF_DISABLE_DEPRECATION_WARNINGS
2224         frame_duration = av_rescale(track->timescale, track->st->codec->time_base.num, track->st->codec->time_base.den);
2225         nb_frames      = ROUNDED_DIV(track->st->codec->time_base.den, track->st->codec->time_base.num);
2226     FF_ENABLE_DEPRECATION_WARNINGS
2227 #else
2228         av_log(NULL, AV_LOG_ERROR, "avg_frame_rate not set for tmcd track.\n");
2229         return AVERROR(EINVAL);
2230 #endif
2231     } else {
2232         frame_duration = av_rescale(track->timescale, track->st->avg_frame_rate.num, track->st->avg_frame_rate.den);
2233         nb_frames      = ROUNDED_DIV(track->st->avg_frame_rate.den, track->st->avg_frame_rate.num);
2234     }
2235
2236     if (nb_frames > 255) {
2237         av_log(NULL, AV_LOG_ERROR, "fps %d is too large\n", nb_frames);
2238         return AVERROR(EINVAL);
2239     }
2240
2241     avio_wb32(pb, 0); /* size */
2242     ffio_wfourcc(pb, "tmcd");               /* Data format */
2243     avio_wb32(pb, 0);                       /* Reserved */
2244     avio_wb32(pb, 1);                       /* Data reference index */
2245     avio_wb32(pb, 0);                       /* Flags */
2246     avio_wb32(pb, track->timecode_flags);   /* Flags (timecode) */
2247     avio_wb32(pb, track->timescale);        /* Timescale */
2248     avio_wb32(pb, frame_duration);          /* Frame duration */
2249     avio_w8(pb, nb_frames);                 /* Number of frames */
2250     avio_w8(pb, 0);                         /* Reserved */
2251
2252     t = av_dict_get(track->st->metadata, "reel_name", NULL, 0);
2253     if (t && utf8len(t->value) && track->mode != MODE_MP4)
2254         mov_write_source_reference_tag(pb, track, t->value);
2255     else
2256         avio_wb16(pb, 0); /* zero size */
2257 #else
2258
2259     avio_wb32(pb, 0); /* size */
2260     ffio_wfourcc(pb, "tmcd");               /* Data format */
2261     avio_wb32(pb, 0);                       /* Reserved */
2262     avio_wb32(pb, 1);                       /* Data reference index */
2263     if (track->par->extradata_size)
2264         avio_write(pb, track->par->extradata, track->par->extradata_size);
2265 #endif
2266     return update_size(pb, pos);
2267 }
2268
2269 static int mov_write_gpmd_tag(AVIOContext *pb, const MOVTrack *track)
2270 {
2271     int64_t pos = avio_tell(pb);
2272     avio_wb32(pb, 0); /* size */
2273     ffio_wfourcc(pb, "gpmd");
2274     avio_wb32(pb, 0); /* Reserved */
2275     avio_wb16(pb, 0); /* Reserved */
2276     avio_wb16(pb, 1); /* Data-reference index */
2277     avio_wb32(pb, 0); /* Reserved */
2278     return update_size(pb, pos);
2279 }
2280
2281 static int mov_write_stsd_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
2282 {
2283     int64_t pos = avio_tell(pb);
2284     int ret = 0;
2285     avio_wb32(pb, 0); /* size */
2286     ffio_wfourcc(pb, "stsd");
2287     avio_wb32(pb, 0); /* version & flags */
2288     avio_wb32(pb, 1); /* entry count */
2289     if (track->par->codec_type == AVMEDIA_TYPE_VIDEO)
2290         ret = mov_write_video_tag(s, pb, mov, track);
2291     else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
2292         ret = mov_write_audio_tag(s, pb, mov, track);
2293     else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)
2294         ret = mov_write_subtitle_tag(pb, track);
2295     else if (track->par->codec_tag == MKTAG('r','t','p',' '))
2296         ret = mov_write_rtp_tag(pb, track);
2297     else if (track->par->codec_tag == MKTAG('t','m','c','d'))
2298         ret = mov_write_tmcd_tag(pb, track);
2299     else if (track->par->codec_tag == MKTAG('g','p','m','d'))
2300         ret = mov_write_gpmd_tag(pb, track);
2301
2302     if (ret < 0)
2303         return ret;
2304
2305     return update_size(pb, pos);
2306 }
2307
2308 static int mov_write_ctts_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
2309 {
2310     MOVMuxContext *mov = s->priv_data;
2311     MOVStts *ctts_entries;
2312     uint32_t entries = 0;
2313     uint32_t atom_size;
2314     int i;
2315
2316     ctts_entries = av_malloc_array((track->entry + 1), sizeof(*ctts_entries)); /* worst case */
2317     if (!ctts_entries)
2318         return AVERROR(ENOMEM);
2319     ctts_entries[0].count = 1;
2320     ctts_entries[0].duration = track->cluster[0].cts;
2321     for (i = 1; i < track->entry; i++) {
2322         if (track->cluster[i].cts == ctts_entries[entries].duration) {
2323             ctts_entries[entries].count++; /* compress */
2324         } else {
2325             entries++;
2326             ctts_entries[entries].duration = track->cluster[i].cts;
2327             ctts_entries[entries].count = 1;
2328         }
2329     }
2330     entries++; /* last one */
2331     atom_size = 16 + (entries * 8);
2332     avio_wb32(pb, atom_size); /* size */
2333     ffio_wfourcc(pb, "ctts");
2334     if (mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS)
2335         avio_w8(pb, 1); /* version */
2336     else
2337         avio_w8(pb, 0); /* version */
2338     avio_wb24(pb, 0); /* flags */
2339     avio_wb32(pb, entries); /* entry count */
2340     for (i = 0; i < entries; i++) {
2341         avio_wb32(pb, ctts_entries[i].count);
2342         avio_wb32(pb, ctts_entries[i].duration);
2343     }
2344     av_free(ctts_entries);
2345     return atom_size;
2346 }
2347
2348 /* Time to sample atom */
2349 static int mov_write_stts_tag(AVIOContext *pb, MOVTrack *track)
2350 {
2351     MOVStts *stts_entries = NULL;
2352     uint32_t entries = -1;
2353     uint32_t atom_size;
2354     int i;
2355
2356     if (track->par->codec_type == AVMEDIA_TYPE_AUDIO && !track->audio_vbr) {
2357         stts_entries = av_malloc(sizeof(*stts_entries)); /* one entry */
2358         if (!stts_entries)
2359             return AVERROR(ENOMEM);
2360         stts_entries[0].count = track->sample_count;
2361         stts_entries[0].duration = 1;
2362         entries = 1;
2363     } else {
2364         if (track->entry) {
2365             stts_entries = av_malloc_array(track->entry, sizeof(*stts_entries)); /* worst case */
2366             if (!stts_entries)
2367                 return AVERROR(ENOMEM);
2368         }
2369         for (i = 0; i < track->entry; i++) {
2370             int duration = get_cluster_duration(track, i);
2371             if (i && duration == stts_entries[entries].duration) {
2372                 stts_entries[entries].count++; /* compress */
2373             } else {
2374                 entries++;
2375                 stts_entries[entries].duration = duration;
2376                 stts_entries[entries].count = 1;
2377             }
2378         }
2379         entries++; /* last one */
2380     }
2381     atom_size = 16 + (entries * 8);
2382     avio_wb32(pb, atom_size); /* size */
2383     ffio_wfourcc(pb, "stts");
2384     avio_wb32(pb, 0); /* version & flags */
2385     avio_wb32(pb, entries); /* entry count */
2386     for (i = 0; i < entries; i++) {
2387         avio_wb32(pb, stts_entries[i].count);
2388         avio_wb32(pb, stts_entries[i].duration);
2389     }
2390     av_free(stts_entries);
2391     return atom_size;
2392 }
2393
2394 static int mov_write_dref_tag(AVIOContext *pb)
2395 {
2396     avio_wb32(pb, 28); /* size */
2397     ffio_wfourcc(pb, "dref");
2398     avio_wb32(pb, 0); /* version & flags */
2399     avio_wb32(pb, 1); /* entry count */
2400
2401     avio_wb32(pb, 0xc); /* size */
2402     //FIXME add the alis and rsrc atom
2403     ffio_wfourcc(pb, "url ");
2404     avio_wb32(pb, 1); /* version & flags */
2405
2406     return 28;
2407 }
2408
2409 static int mov_preroll_write_stbl_atoms(AVIOContext *pb, MOVTrack *track)
2410 {
2411     struct sgpd_entry {
2412         int count;
2413         int16_t roll_distance;
2414         int group_description_index;
2415     };
2416
2417     struct sgpd_entry *sgpd_entries = NULL;
2418     int entries = -1;
2419     int group = 0;
2420     int i, j;
2421
2422     const int OPUS_SEEK_PREROLL_MS = 80;
2423     int roll_samples = av_rescale_q(OPUS_SEEK_PREROLL_MS,
2424                                     (AVRational){1, 1000},
2425                                     (AVRational){1, 48000});
2426
2427     if (!track->entry)
2428         return 0;
2429
2430     sgpd_entries = av_malloc_array(track->entry, sizeof(*sgpd_entries));
2431     if (!sgpd_entries)
2432         return AVERROR(ENOMEM);
2433
2434     av_assert0(track->par->codec_id == AV_CODEC_ID_OPUS || track->par->codec_id == AV_CODEC_ID_AAC);
2435
2436     if (track->par->codec_id == AV_CODEC_ID_OPUS) {
2437         for (i = 0; i < track->entry; i++) {
2438             int roll_samples_remaining = roll_samples;
2439             int distance = 0;
2440             for (j = i - 1; j >= 0; j--) {
2441                 roll_samples_remaining -= get_cluster_duration(track, j);
2442                 distance++;
2443                 if (roll_samples_remaining <= 0)
2444                     break;
2445             }
2446             /* We don't have enough preceeding samples to compute a valid
2447                roll_distance here, so this sample can't be independently
2448                decoded. */
2449             if (roll_samples_remaining > 0)
2450                 distance = 0;
2451             /* Verify distance is a maximum of 32 (2.5ms) packets. */
2452             if (distance > 32)
2453                 return AVERROR_INVALIDDATA;
2454             if (i && distance == sgpd_entries[entries].roll_distance) {
2455                 sgpd_entries[entries].count++;
2456             } else {
2457                 entries++;
2458                 sgpd_entries[entries].count = 1;
2459                 sgpd_entries[entries].roll_distance = distance;
2460                 sgpd_entries[entries].group_description_index = distance ? ++group : 0;
2461             }
2462         }
2463     } else {
2464         entries++;
2465         sgpd_entries[entries].count = track->sample_count;
2466         sgpd_entries[entries].roll_distance = 1;
2467         sgpd_entries[entries].group_description_index = ++group;
2468     }
2469     entries++;
2470
2471     if (!group) {
2472         av_free(sgpd_entries);
2473         return 0;
2474     }
2475
2476     /* Write sgpd tag */
2477     avio_wb32(pb, 24 + (group * 2)); /* size */
2478     ffio_wfourcc(pb, "sgpd");
2479     avio_wb32(pb, 1 << 24); /* fullbox */
2480     ffio_wfourcc(pb, "roll");
2481     avio_wb32(pb, 2); /* default_length */
2482     avio_wb32(pb, group); /* entry_count */
2483     for (i = 0; i < entries; i++) {
2484         if (sgpd_entries[i].group_description_index) {
2485             avio_wb16(pb, -sgpd_entries[i].roll_distance); /* roll_distance */
2486         }
2487     }
2488
2489     /* Write sbgp tag */
2490     avio_wb32(pb, 20 + (entries * 8)); /* size */
2491     ffio_wfourcc(pb, "sbgp");
2492     avio_wb32(pb, 0); /* fullbox */
2493     ffio_wfourcc(pb, "roll");
2494     avio_wb32(pb, entries); /* entry_count */
2495     for (i = 0; i < entries; i++) {
2496         avio_wb32(pb, sgpd_entries[i].count); /* sample_count */
2497         avio_wb32(pb, sgpd_entries[i].group_description_index); /* group_description_index */
2498     }
2499
2500     av_free(sgpd_entries);
2501     return 0;
2502 }
2503
2504 static int mov_write_stbl_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
2505 {
2506     int64_t pos = avio_tell(pb);
2507     int ret = 0;
2508
2509     avio_wb32(pb, 0); /* size */
2510     ffio_wfourcc(pb, "stbl");
2511     if ((ret = mov_write_stsd_tag(s, pb, mov, track)) < 0)
2512         return ret;
2513     mov_write_stts_tag(pb, track);
2514     if ((track->par->codec_type == AVMEDIA_TYPE_VIDEO ||
2515          track->par->codec_id == AV_CODEC_ID_TRUEHD ||
2516          track->par->codec_id == AV_CODEC_ID_MPEGH_3D_AUDIO ||
2517          track->par->codec_tag == MKTAG('r','t','p',' ')) &&
2518         track->has_keyframes && track->has_keyframes < track->entry)
2519         mov_write_stss_tag(pb, track, MOV_SYNC_SAMPLE);
2520     if (track->par->codec_type == AVMEDIA_TYPE_VIDEO && track->has_disposable)
2521         mov_write_sdtp_tag(pb, track);
2522     if (track->mode == MODE_MOV && track->flags & MOV_TRACK_STPS)
2523         mov_write_stss_tag(pb, track, MOV_PARTIAL_SYNC_SAMPLE);
2524     if (track->par->codec_type == AVMEDIA_TYPE_VIDEO &&
2525         track->flags & MOV_TRACK_CTTS && track->entry) {
2526
2527         if ((ret = mov_write_ctts_tag(s, pb, track)) < 0)
2528             return ret;
2529     }
2530     mov_write_stsc_tag(pb, track);
2531     mov_write_stsz_tag(pb, track);
2532     mov_write_stco_tag(pb, track);
2533     if (track->cenc.aes_ctr) {
2534         ff_mov_cenc_write_stbl_atoms(&track->cenc, pb);
2535     }
2536     if (track->par->codec_id == AV_CODEC_ID_OPUS || track->par->codec_id == AV_CODEC_ID_AAC) {
2537         mov_preroll_write_stbl_atoms(pb, track);
2538     }
2539     return update_size(pb, pos);
2540 }
2541
2542 static int mov_write_dinf_tag(AVIOContext *pb)
2543 {
2544     int64_t pos = avio_tell(pb);
2545     avio_wb32(pb, 0); /* size */
2546     ffio_wfourcc(pb, "dinf");
2547     mov_write_dref_tag(pb);
2548     return update_size(pb, pos);
2549 }
2550
2551 static int mov_write_nmhd_tag(AVIOContext *pb)
2552 {
2553     avio_wb32(pb, 12);
2554     ffio_wfourcc(pb, "nmhd");
2555     avio_wb32(pb, 0);
2556     return 12;
2557 }
2558
2559 static int mov_write_tcmi_tag(AVIOContext *pb, MOVTrack *track)
2560 {
2561     int64_t pos = avio_tell(pb);
2562     const char *font = "Lucida Grande";
2563     avio_wb32(pb, 0);                   /* size */
2564     ffio_wfourcc(pb, "tcmi");           /* timecode media information atom */
2565     avio_wb32(pb, 0);                   /* version & flags */
2566     avio_wb16(pb, 0);                   /* text font */
2567     avio_wb16(pb, 0);                   /* text face */
2568     avio_wb16(pb, 12);                  /* text size */
2569     avio_wb16(pb, 0);                   /* (unknown, not in the QT specs...) */
2570     avio_wb16(pb, 0x0000);              /* text color (red) */
2571     avio_wb16(pb, 0x0000);              /* text color (green) */
2572     avio_wb16(pb, 0x0000);              /* text color (blue) */
2573     avio_wb16(pb, 0xffff);              /* background color (red) */
2574     avio_wb16(pb, 0xffff);              /* background color (green) */
2575     avio_wb16(pb, 0xffff);              /* background color (blue) */
2576     avio_w8(pb, strlen(font));          /* font len (part of the pascal string) */
2577     avio_write(pb, font, strlen(font)); /* font name */
2578     return update_size(pb, pos);
2579 }
2580
2581 static int mov_write_gmhd_tag(AVIOContext *pb, MOVTrack *track)
2582 {
2583     int64_t pos = avio_tell(pb);
2584     avio_wb32(pb, 0);      /* size */
2585     ffio_wfourcc(pb, "gmhd");
2586     avio_wb32(pb, 0x18);   /* gmin size */
2587     ffio_wfourcc(pb, "gmin");/* generic media info */
2588     avio_wb32(pb, 0);      /* version & flags */
2589     avio_wb16(pb, 0x40);   /* graphics mode = */
2590     avio_wb16(pb, 0x8000); /* opColor (r?) */
2591     avio_wb16(pb, 0x8000); /* opColor (g?) */
2592     avio_wb16(pb, 0x8000); /* opColor (b?) */
2593     avio_wb16(pb, 0);      /* balance */
2594     avio_wb16(pb, 0);      /* reserved */
2595
2596     /*
2597      * This special text atom is required for
2598      * Apple Quicktime chapters. The contents
2599      * don't appear to be documented, so the
2600      * bytes are copied verbatim.
2601      */
2602     if (track->tag != MKTAG('c','6','0','8')) {
2603     avio_wb32(pb, 0x2C);   /* size */
2604     ffio_wfourcc(pb, "text");
2605     avio_wb16(pb, 0x01);
2606     avio_wb32(pb, 0x00);
2607     avio_wb32(pb, 0x00);
2608     avio_wb32(pb, 0x00);
2609     avio_wb32(pb, 0x01);
2610     avio_wb32(pb, 0x00);
2611     avio_wb32(pb, 0x00);
2612     avio_wb32(pb, 0x00);
2613     avio_wb32(pb, 0x00004000);
2614     avio_wb16(pb, 0x0000);
2615     }
2616
2617     if (track->par->codec_tag == MKTAG('t','m','c','d')) {
2618         int64_t tmcd_pos = avio_tell(pb);
2619         avio_wb32(pb, 0); /* size */
2620         ffio_wfourcc(pb, "tmcd");
2621         mov_write_tcmi_tag(pb, track);
2622         update_size(pb, tmcd_pos);
2623     } else if (track->par->codec_tag == MKTAG('g','p','m','d')) {
2624         int64_t gpmd_pos = avio_tell(pb);
2625         avio_wb32(pb, 0); /* size */
2626         ffio_wfourcc(pb, "gpmd");
2627         avio_wb32(pb, 0); /* version */
2628         update_size(pb, gpmd_pos);
2629     }
2630     return update_size(pb, pos);
2631 }
2632
2633 static int mov_write_smhd_tag(AVIOContext *pb)
2634 {
2635     avio_wb32(pb, 16); /* size */
2636     ffio_wfourcc(pb, "smhd");
2637     avio_wb32(pb, 0); /* version & flags */
2638     avio_wb16(pb, 0); /* reserved (balance, normally = 0) */
2639     avio_wb16(pb, 0); /* reserved */
2640     return 16;
2641 }
2642
2643 static int mov_write_vmhd_tag(AVIOContext *pb)
2644 {
2645     avio_wb32(pb, 0x14); /* size (always 0x14) */
2646     ffio_wfourcc(pb, "vmhd");
2647     avio_wb32(pb, 0x01); /* version & flags */
2648     avio_wb64(pb, 0); /* reserved (graphics mode = copy) */
2649     return 0x14;
2650 }
2651
2652 static int is_clcp_track(MOVTrack *track)
2653 {
2654     return track->tag == MKTAG('c','7','0','8') ||
2655            track->tag == MKTAG('c','6','0','8');
2656 }
2657
2658 static int mov_write_hdlr_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
2659 {
2660     MOVMuxContext *mov = s->priv_data;
2661     const char *hdlr, *descr = NULL, *hdlr_type = NULL;
2662     int64_t pos = avio_tell(pb);
2663
2664     hdlr      = "dhlr";
2665     hdlr_type = "url ";
2666     descr     = "DataHandler";
2667
2668     if (track) {
2669         hdlr = (track->mode == MODE_MOV) ? "mhlr" : "\0\0\0\0";
2670         if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
2671             hdlr_type = "vide";
2672             descr     = "VideoHandler";
2673         } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
2674             hdlr_type = "soun";
2675             descr     = "SoundHandler";
2676         } else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE) {
2677             if (is_clcp_track(track)) {
2678                 hdlr_type = "clcp";
2679                 descr = "ClosedCaptionHandler";
2680             } else {
2681                 if (track->tag == MKTAG('t','x','3','g')) {
2682                     hdlr_type = "sbtl";
2683                 } else if (track->tag == MKTAG('m','p','4','s')) {
2684                     hdlr_type = "subp";
2685                 } else {
2686                     hdlr_type = "text";
2687                 }
2688             descr = "SubtitleHandler";
2689             }
2690         } else if (track->par->codec_tag == MKTAG('r','t','p',' ')) {
2691             hdlr_type = "hint";
2692             descr     = "HintHandler";
2693         } else if (track->par->codec_tag == MKTAG('t','m','c','d')) {
2694             hdlr_type = "tmcd";
2695             descr = "TimeCodeHandler";
2696         } else if (track->par->codec_tag == MKTAG('g','p','m','d')) {
2697             hdlr_type = "meta";
2698             descr = "GoPro MET"; // GoPro Metadata
2699         } else {
2700             av_log(s, AV_LOG_WARNING,
2701                    "Unknown hldr_type for %s, writing dummy values\n",
2702                    av_fourcc2str(track->par->codec_tag));
2703         }
2704         if (track->st) {
2705             // hdlr.name is used by some players to identify the content title
2706             // of the track. So if an alternate handler description is
2707             // specified, use it.
2708             AVDictionaryEntry *t;
2709             t = av_dict_get(track->st->metadata, "handler_name", NULL, 0);
2710             if (t && utf8len(t->value))
2711                 descr = t->value;
2712         }
2713     }
2714
2715     if (mov->empty_hdlr_name) /* expressly allowed by QTFF and not prohibited in ISO 14496-12 8.4.3.3 */
2716         descr = "";
2717
2718     avio_wb32(pb, 0); /* size */
2719     ffio_wfourcc(pb, "hdlr");
2720     avio_wb32(pb, 0); /* Version & flags */
2721     avio_write(pb, hdlr, 4); /* handler */
2722     ffio_wfourcc(pb, hdlr_type); /* handler type */
2723     avio_wb32(pb, 0); /* reserved */
2724     avio_wb32(pb, 0); /* reserved */
2725     avio_wb32(pb, 0); /* reserved */
2726     if (!track || track->mode == MODE_MOV)
2727         avio_w8(pb, strlen(descr)); /* pascal string */
2728     avio_write(pb, descr, strlen(descr)); /* handler description */
2729     if (track && track->mode != MODE_MOV)
2730         avio_w8(pb, 0); /* c string */
2731     return update_size(pb, pos);
2732 }
2733
2734 static int mov_write_hmhd_tag(AVIOContext *pb)
2735 {
2736     /* This atom must be present, but leaving the values at zero
2737      * seems harmless. */
2738     avio_wb32(pb, 28); /* size */
2739     ffio_wfourcc(pb, "hmhd");
2740     avio_wb32(pb, 0); /* version, flags */
2741     avio_wb16(pb, 0); /* maxPDUsize */
2742     avio_wb16(pb, 0); /* avgPDUsize */
2743     avio_wb32(pb, 0); /* maxbitrate */
2744     avio_wb32(pb, 0); /* avgbitrate */
2745     avio_wb32(pb, 0); /* reserved */
2746     return 28;
2747 }
2748
2749 static int mov_write_minf_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
2750 {
2751     int64_t pos = avio_tell(pb);
2752     int ret;
2753
2754     avio_wb32(pb, 0); /* size */
2755     ffio_wfourcc(pb, "minf");
2756     if (track->par->codec_type == AVMEDIA_TYPE_VIDEO)
2757         mov_write_vmhd_tag(pb);
2758     else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
2759         mov_write_smhd_tag(pb);
2760     else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE) {
2761         if (track->tag == MKTAG('t','e','x','t') || is_clcp_track(track)) {
2762             mov_write_gmhd_tag(pb, track);
2763         } else {
2764             mov_write_nmhd_tag(pb);
2765         }
2766     } else if (track->tag == MKTAG('r','t','p',' ')) {
2767         mov_write_hmhd_tag(pb);
2768     } else if (track->tag == MKTAG('t','m','c','d')) {
2769         if (track->mode != MODE_MOV)
2770             mov_write_nmhd_tag(pb);
2771         else
2772             mov_write_gmhd_tag(pb, track);
2773     } else if (track->tag == MKTAG('g','p','m','d')) {
2774         mov_write_gmhd_tag(pb, track);
2775     }
2776     if (track->mode == MODE_MOV) /* ISO 14496-12 8.4.3.1 specifies hdlr only within mdia or meta boxes */
2777         mov_write_hdlr_tag(s, pb, NULL);
2778     mov_write_dinf_tag(pb);
2779     if ((ret = mov_write_stbl_tag(s, pb, mov, track)) < 0)
2780         return ret;
2781     return update_size(pb, pos);
2782 }
2783
2784 static int64_t calc_pts_duration(MOVMuxContext *mov, MOVTrack *track)
2785 {
2786     if (track->tag == MKTAG('t','m','c','d')) {
2787         // tmcd tracks gets track_duration set in mov_write_moov_tag from
2788         // another track's duration, while the end_pts may be left at zero.
2789         // Calculate the pts duration for that track instead.
2790         return av_rescale(calc_pts_duration(mov, &mov->tracks[track->src_track]),
2791                           track->timescale, mov->tracks[track->src_track].timescale);
2792     }
2793     if (track->end_pts != AV_NOPTS_VALUE &&
2794         track->start_dts != AV_NOPTS_VALUE &&
2795         track->start_cts != AV_NOPTS_VALUE) {
2796         return track->end_pts - (track->start_dts + track->start_cts);
2797     }
2798     return track->track_duration;
2799 }
2800
2801 static int mov_write_mdhd_tag(AVIOContext *pb, MOVMuxContext *mov,
2802                               MOVTrack *track)
2803 {
2804     int64_t duration = calc_pts_duration(mov, track);
2805     int version = duration < INT32_MAX ? 0 : 1;
2806
2807     if (track->mode == MODE_ISM)
2808         version = 1;
2809
2810     (version == 1) ? avio_wb32(pb, 44) : avio_wb32(pb, 32); /* size */
2811     ffio_wfourcc(pb, "mdhd");
2812     avio_w8(pb, version);
2813     avio_wb24(pb, 0); /* flags */
2814     if (version == 1) {
2815         avio_wb64(pb, track->time);
2816         avio_wb64(pb, track->time);
2817     } else {
2818         avio_wb32(pb, track->time); /* creation time */
2819         avio_wb32(pb, track->time); /* modification time */
2820     }
2821     avio_wb32(pb, track->timescale); /* time scale (sample rate for audio) */
2822     if (!track->entry && mov->mode == MODE_ISM)
2823         (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
2824     else if (!track->entry)
2825         (version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0);
2826     else
2827         (version == 1) ? avio_wb64(pb, duration) : avio_wb32(pb, duration); /* duration */
2828     avio_wb16(pb, track->language); /* language */
2829     avio_wb16(pb, 0); /* reserved (quality) */
2830
2831     if (version != 0 && track->mode == MODE_MOV) {
2832         av_log(NULL, AV_LOG_ERROR,
2833                "FATAL error, file duration too long for timebase, this file will not be\n"
2834                "playable with QuickTime. Choose a different timebase with "
2835                "-video_track_timescale or a different container format\n");
2836     }
2837
2838     return 32;
2839 }
2840
2841 static int mov_write_mdia_tag(AVFormatContext *s, AVIOContext *pb,
2842                               MOVMuxContext *mov, MOVTrack *track)
2843 {
2844     int64_t pos = avio_tell(pb);
2845     int ret;
2846
2847     avio_wb32(pb, 0); /* size */
2848     ffio_wfourcc(pb, "mdia");
2849     mov_write_mdhd_tag(pb, mov, track);
2850     mov_write_hdlr_tag(s, pb, track);
2851     if ((ret = mov_write_minf_tag(s, pb, mov, track)) < 0)
2852         return ret;
2853     return update_size(pb, pos);
2854 }
2855
2856 /* transformation matrix
2857      |a  b  u|
2858      |c  d  v|
2859      |tx ty w| */
2860 static void write_matrix(AVIOContext *pb, int16_t a, int16_t b, int16_t c,
2861                          int16_t d, int16_t tx, int16_t ty)
2862 {
2863     avio_wb32(pb, a << 16);  /* 16.16 format */
2864     avio_wb32(pb, b << 16);  /* 16.16 format */
2865     avio_wb32(pb, 0);        /* u in 2.30 format */
2866     avio_wb32(pb, c << 16);  /* 16.16 format */
2867     avio_wb32(pb, d << 16);  /* 16.16 format */
2868     avio_wb32(pb, 0);        /* v in 2.30 format */
2869     avio_wb32(pb, tx << 16); /* 16.16 format */
2870     avio_wb32(pb, ty << 16); /* 16.16 format */
2871     avio_wb32(pb, 1 << 30);  /* w in 2.30 format */
2872 }
2873
2874 static int mov_write_tkhd_tag(AVIOContext *pb, MOVMuxContext *mov,
2875                               MOVTrack *track, AVStream *st)
2876 {
2877     int64_t duration = av_rescale_rnd(calc_pts_duration(mov, track),
2878                                       MOV_TIMESCALE, track->timescale,
2879                                       AV_ROUND_UP);
2880     int version = duration < INT32_MAX ? 0 : 1;
2881     int flags   = MOV_TKHD_FLAG_IN_MOVIE;
2882     int rotation = 0;
2883     int group   = 0;
2884
2885     uint32_t *display_matrix = NULL;
2886     int      display_matrix_size, i;
2887
2888     if (st) {
2889         if (mov->per_stream_grouping)
2890             group = st->index;
2891         else
2892             group = st->codecpar->codec_type;
2893
2894         display_matrix = (uint32_t*)av_stream_get_side_data(st, AV_PKT_DATA_DISPLAYMATRIX,
2895                                                             &display_matrix_size);
2896         if (display_matrix && display_matrix_size < 9 * sizeof(*display_matrix))
2897             display_matrix = NULL;
2898     }
2899
2900     if (track->flags & MOV_TRACK_ENABLED)
2901         flags |= MOV_TKHD_FLAG_ENABLED;
2902
2903     if (track->mode == MODE_ISM)
2904         version = 1;
2905
2906     (version == 1) ? avio_wb32(pb, 104) : avio_wb32(pb, 92); /* size */
2907     ffio_wfourcc(pb, "tkhd");
2908     avio_w8(pb, version);
2909     avio_wb24(pb, flags);
2910     if (version == 1) {
2911         avio_wb64(pb, track->time);
2912         avio_wb64(pb, track->time);
2913     } else {
2914         avio_wb32(pb, track->time); /* creation time */
2915         avio_wb32(pb, track->time); /* modification time */
2916     }
2917     avio_wb32(pb, track->track_id); /* track-id */
2918     avio_wb32(pb, 0); /* reserved */
2919     if (!track->entry && mov->mode == MODE_ISM)
2920         (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
2921     else if (!track->entry)
2922         (version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0);
2923     else
2924         (version == 1) ? avio_wb64(pb, duration) : avio_wb32(pb, duration);
2925
2926     avio_wb32(pb, 0); /* reserved */
2927     avio_wb32(pb, 0); /* reserved */
2928     avio_wb16(pb, 0); /* layer */
2929     avio_wb16(pb, group); /* alternate group) */
2930     /* Volume, only for audio */
2931     if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
2932         avio_wb16(pb, 0x0100);
2933     else
2934         avio_wb16(pb, 0);
2935     avio_wb16(pb, 0); /* reserved */
2936
2937     /* Matrix structure */
2938 #if FF_API_OLD_ROTATE_API
2939     if (st && st->metadata) {
2940         AVDictionaryEntry *rot = av_dict_get(st->metadata, "rotate", NULL, 0);
2941         rotation = (rot && rot->value) ? atoi(rot->value) : 0;
2942     }
2943 #endif
2944     if (display_matrix) {
2945         for (i = 0; i < 9; i++)
2946             avio_wb32(pb, display_matrix[i]);
2947 #if FF_API_OLD_ROTATE_API
2948     } else if (rotation == 90) {
2949         write_matrix(pb,  0,  1, -1,  0, track->par->height, 0);
2950     } else if (rotation == 180) {
2951         write_matrix(pb, -1,  0,  0, -1, track->par->width, track->par->height);
2952     } else if (rotation == 270) {
2953         write_matrix(pb,  0, -1,  1,  0, 0, track->par->width);
2954 #endif
2955     } else {
2956         write_matrix(pb,  1,  0,  0,  1, 0, 0);
2957     }
2958     /* Track width and height, for visual only */
2959     if (st && (track->par->codec_type == AVMEDIA_TYPE_VIDEO ||
2960                track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)) {
2961         int64_t track_width_1616;
2962         if (track->mode == MODE_MOV) {
2963             track_width_1616 = track->par->width * 0x10000ULL;
2964         } else {
2965             track_width_1616 = av_rescale(st->sample_aspect_ratio.num,
2966                                                   track->par->width * 0x10000LL,
2967                                                   st->sample_aspect_ratio.den);
2968             if (!track_width_1616 ||
2969                 track->height != track->par->height ||
2970                 track_width_1616 > UINT32_MAX)
2971                 track_width_1616 = track->par->width * 0x10000ULL;
2972         }
2973         if (track_width_1616 > UINT32_MAX) {
2974             av_log(mov->fc, AV_LOG_WARNING, "track width is too large\n");
2975             track_width_1616 = 0;
2976         }
2977         avio_wb32(pb, track_width_1616);
2978         if (track->height > 0xFFFF) {
2979             av_log(mov->fc, AV_LOG_WARNING, "track height is too large\n");
2980             avio_wb32(pb, 0);
2981         } else
2982             avio_wb32(pb, track->height * 0x10000U);
2983     } else {
2984         avio_wb32(pb, 0);
2985         avio_wb32(pb, 0);
2986     }
2987     return 0x5c;
2988 }
2989
2990 static int mov_write_tapt_tag(AVIOContext *pb, MOVTrack *track)
2991 {
2992     int32_t width = av_rescale(track->par->sample_aspect_ratio.num, track->par->width,
2993                                track->par->sample_aspect_ratio.den);
2994
2995     int64_t pos = avio_tell(pb);
2996
2997     avio_wb32(pb, 0); /* size */
2998     ffio_wfourcc(pb, "tapt");
2999
3000     avio_wb32(pb, 20);
3001     ffio_wfourcc(pb, "clef");
3002     avio_wb32(pb, 0);
3003     avio_wb32(pb, width << 16);
3004     avio_wb32(pb, track->par->height << 16);
3005
3006     avio_wb32(pb, 20);
3007     ffio_wfourcc(pb, "prof");
3008     avio_wb32(pb, 0);
3009     avio_wb32(pb, width << 16);
3010     avio_wb32(pb, track->par->height << 16);
3011
3012     avio_wb32(pb, 20);
3013     ffio_wfourcc(pb, "enof");
3014     avio_wb32(pb, 0);
3015     avio_wb32(pb, track->par->width << 16);
3016     avio_wb32(pb, track->par->height << 16);
3017
3018     return update_size(pb, pos);
3019 }
3020
3021 // This box seems important for the psp playback ... without it the movie seems to hang
3022 static int mov_write_edts_tag(AVIOContext *pb, MOVMuxContext *mov,
3023                               MOVTrack *track)
3024 {
3025     int64_t duration = av_rescale_rnd(calc_pts_duration(mov, track),
3026                                       MOV_TIMESCALE, track->timescale,
3027                                       AV_ROUND_UP);
3028     int version = duration < INT32_MAX ? 0 : 1;
3029     int entry_size, entry_count, size;
3030     int64_t delay, start_ct = track->start_cts;
3031     int64_t start_dts = track->start_dts;
3032
3033     if (track->entry) {
3034         if (start_dts != track->cluster[0].dts || start_ct != track->cluster[0].cts) {
3035
3036             av_log(mov->fc, AV_LOG_DEBUG,
3037                    "EDTS using dts:%"PRId64" cts:%d instead of dts:%"PRId64" cts:%"PRId64" tid:%d\n",
3038                    track->cluster[0].dts, track->cluster[0].cts,
3039                    start_dts, start_ct, track->track_id);
3040             start_dts = track->cluster[0].dts;
3041             start_ct  = track->cluster[0].cts;
3042         }
3043     }
3044
3045     delay = av_rescale_rnd(start_dts + start_ct, MOV_TIMESCALE,
3046                            track->timescale, AV_ROUND_DOWN);
3047     version |= delay < INT32_MAX ? 0 : 1;
3048
3049     entry_size = (version == 1) ? 20 : 12;
3050     entry_count = 1 + (delay > 0);
3051     size = 24 + entry_count * entry_size;
3052
3053     /* write the atom data */
3054     avio_wb32(pb, size);
3055     ffio_wfourcc(pb, "edts");
3056     avio_wb32(pb, size - 8);
3057     ffio_wfourcc(pb, "elst");
3058     avio_w8(pb, version);
3059     avio_wb24(pb, 0); /* flags */
3060
3061     avio_wb32(pb, entry_count);
3062     if (delay > 0) { /* add an empty edit to delay presentation */
3063         /* In the positive delay case, the delay includes the cts
3064          * offset, and the second edit list entry below trims out
3065          * the same amount from the actual content. This makes sure
3066          * that the offset last sample is included in the edit
3067          * list duration as well. */
3068         if (version == 1) {
3069             avio_wb64(pb, delay);
3070             avio_wb64(pb, -1);
3071         } else {
3072             avio_wb32(pb, delay);
3073             avio_wb32(pb, -1);
3074         }
3075         avio_wb32(pb, 0x00010000);
3076     } else {
3077         /* Avoid accidentally ending up with start_ct = -1 which has got a
3078          * special meaning. Normally start_ct should end up positive or zero
3079          * here, but use FFMIN in case dts is a small positive integer
3080          * rounded to 0 when represented in MOV_TIMESCALE units. */
3081         av_assert0(av_rescale_rnd(start_dts, MOV_TIMESCALE, track->timescale, AV_ROUND_DOWN) <= 0);
3082         start_ct  = -FFMIN(start_dts, 0);
3083         /* Note, this delay is calculated from the pts of the first sample,
3084          * ensuring that we don't reduce the duration for cases with
3085          * dts<0 pts=0. */
3086         duration += delay;
3087     }
3088
3089     /* For fragmented files, we don't know the full length yet. Setting
3090      * duration to 0 allows us to only specify the offset, including
3091      * the rest of the content (from all future fragments) without specifying
3092      * an explicit duration. */
3093     if (mov->flags & FF_MOV_FLAG_FRAGMENT)
3094         duration = 0;
3095
3096     /* duration */
3097     if (version == 1) {
3098         avio_wb64(pb, duration);
3099         avio_wb64(pb, start_ct);
3100     } else {
3101         avio_wb32(pb, duration);
3102         avio_wb32(pb, start_ct);
3103     }
3104     avio_wb32(pb, 0x00010000);
3105     return size;
3106 }
3107
3108 static int mov_write_tref_tag(AVIOContext *pb, MOVTrack *track)
3109 {
3110     avio_wb32(pb, 20);   // size
3111     ffio_wfourcc(pb, "tref");
3112     avio_wb32(pb, 12);   // size (subatom)
3113     avio_wl32(pb, track->tref_tag);
3114     avio_wb32(pb, track->tref_id);
3115     return 20;
3116 }
3117
3118 // goes at the end of each track!  ... Critical for PSP playback ("Incompatible data" without it)
3119 static int mov_write_uuid_tag_psp(AVIOContext *pb, MOVTrack *mov)
3120 {
3121     avio_wb32(pb, 0x34); /* size ... reports as 28 in mp4box! */
3122     ffio_wfourcc(pb, "uuid");
3123     ffio_wfourcc(pb, "USMT");
3124     avio_wb32(pb, 0x21d24fce);
3125     avio_wb32(pb, 0xbb88695c);
3126     avio_wb32(pb, 0xfac9c740);
3127     avio_wb32(pb, 0x1c);     // another size here!
3128     ffio_wfourcc(pb, "MTDT");
3129     avio_wb32(pb, 0x00010012);
3130     avio_wb32(pb, 0x0a);
3131     avio_wb32(pb, 0x55c40000);
3132     avio_wb32(pb, 0x1);
3133     avio_wb32(pb, 0x0);
3134     return 0x34;
3135 }
3136
3137 static int mov_write_udta_sdp(AVIOContext *pb, MOVTrack *track)
3138 {
3139     AVFormatContext *ctx = track->rtp_ctx;
3140     char buf[1000] = "";
3141     int len;
3142
3143     ff_sdp_write_media(buf, sizeof(buf), ctx->streams[0], track->src_track,
3144                        NULL, NULL, 0, 0, ctx);
3145     av_strlcatf(buf, sizeof(buf), "a=control:streamid=%d\r\n", track->track_id);
3146     len = strlen(buf);
3147
3148     avio_wb32(pb, len + 24);
3149     ffio_wfourcc(pb, "udta");
3150     avio_wb32(pb, len + 16);
3151     ffio_wfourcc(pb, "hnti");
3152     avio_wb32(pb, len + 8);
3153     ffio_wfourcc(pb, "sdp ");
3154     avio_write(pb, buf, len);
3155     return len + 24;
3156 }
3157
3158 static int mov_write_track_metadata(AVIOContext *pb, AVStream *st,
3159                                     const char *tag, const char *str)
3160 {
3161     int64_t pos = avio_tell(pb);
3162     AVDictionaryEntry *t = av_dict_get(st->metadata, str, NULL, 0);
3163     if (!t || !utf8len(t->value))
3164         return 0;
3165
3166     avio_wb32(pb, 0);   /* size */
3167     ffio_wfourcc(pb, tag); /* type */
3168     avio_write(pb, t->value, strlen(t->value)); /* UTF8 string value */
3169     return update_size(pb, pos);
3170 }
3171
3172 static int mov_write_track_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
3173                                     AVStream *st)
3174 {
3175     AVIOContext *pb_buf;
3176     int ret, size;
3177     uint8_t *buf;
3178
3179     if (!st)
3180         return 0;
3181
3182     ret = avio_open_dyn_buf(&pb_buf);
3183     if (ret < 0)
3184         return ret;
3185
3186     if (mov->mode & (MODE_MP4|MODE_MOV))
3187         mov_write_track_metadata(pb_buf, st, "name", "title");
3188
3189     if ((size = avio_get_dyn_buf(pb_buf, &buf)) > 0) {
3190         avio_wb32(pb, size + 8);
3191         ffio_wfourcc(pb, "udta");
3192         avio_write(pb, buf, size);
3193     }
3194     ffio_free_dyn_buf(&pb_buf);
3195
3196     return 0;
3197 }
3198
3199 static int mov_write_trak_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov,
3200                               MOVTrack *track, AVStream *st)
3201 {
3202     int64_t pos = avio_tell(pb);
3203     int entry_backup = track->entry;
3204     int chunk_backup = track->chunkCount;
3205     int ret;
3206
3207     /* If we want to have an empty moov, but some samples already have been
3208      * buffered (delay_moov), pretend that no samples have been written yet. */
3209     if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV)
3210         track->chunkCount = track->entry = 0;
3211
3212     avio_wb32(pb, 0); /* size */
3213     ffio_wfourcc(pb, "trak");
3214     mov_write_tkhd_tag(pb, mov, track, st);
3215
3216     av_assert2(mov->use_editlist >= 0);
3217
3218     if (track->start_dts != AV_NOPTS_VALUE) {
3219         if (mov->use_editlist)
3220             mov_write_edts_tag(pb, mov, track);  // PSP Movies and several other cases require edts box
3221         else if ((track->entry && track->cluster[0].dts) || track->mode == MODE_PSP || is_clcp_track(track))
3222             av_log(mov->fc, AV_LOG_WARNING,
3223                    "Not writing any edit list even though one would have been required\n");
3224     }
3225
3226     if (track->tref_tag)
3227         mov_write_tref_tag(pb, track);
3228
3229     if ((ret = mov_write_mdia_tag(s, pb, mov, track)) < 0)
3230         return ret;
3231     if (track->mode == MODE_PSP)
3232         mov_write_uuid_tag_psp(pb, track); // PSP Movies require this uuid box
3233     if (track->tag == MKTAG('r','t','p',' '))
3234         mov_write_udta_sdp(pb, track);
3235     if (track->mode == MODE_MOV) {
3236         if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
3237             double sample_aspect_ratio = av_q2d(st->sample_aspect_ratio);
3238             if (st->sample_aspect_ratio.num && 1.0 != sample_aspect_ratio) {
3239                 mov_write_tapt_tag(pb, track);
3240             }
3241         }
3242         if (is_clcp_track(track) && st->sample_aspect_ratio.num) {
3243             mov_write_tapt_tag(pb, track);
3244         }
3245     }
3246     mov_write_track_udta_tag(pb, mov, st);
3247     track->entry = entry_backup;
3248     track->chunkCount = chunk_backup;
3249     return update_size(pb, pos);
3250 }
3251
3252 static int mov_write_iods_tag(AVIOContext *pb, MOVMuxContext *mov)
3253 {
3254     int i, has_audio = 0, has_video = 0;
3255     int64_t pos = avio_tell(pb);
3256     int audio_profile = mov->iods_audio_profile;
3257     int video_profile = mov->iods_video_profile;
3258     for (i = 0; i < mov->nb_streams; i++) {
3259         if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
3260             has_audio |= mov->tracks[i].par->codec_type == AVMEDIA_TYPE_AUDIO;
3261             has_video |= mov->tracks[i].par->codec_type == AVMEDIA_TYPE_VIDEO;
3262         }
3263     }
3264     if (audio_profile < 0)
3265         audio_profile = 0xFF - has_audio;
3266     if (video_profile < 0)
3267         video_profile = 0xFF - has_video;
3268     avio_wb32(pb, 0x0); /* size */
3269     ffio_wfourcc(pb, "iods");
3270     avio_wb32(pb, 0);    /* version & flags */
3271     put_descr(pb, 0x10, 7);
3272     avio_wb16(pb, 0x004f);
3273     avio_w8(pb, 0xff);
3274     avio_w8(pb, 0xff);
3275     avio_w8(pb, audio_profile);
3276     avio_w8(pb, video_profile);
3277     avio_w8(pb, 0xff);
3278     return update_size(pb, pos);
3279 }
3280
3281 static int mov_write_trex_tag(AVIOContext *pb, MOVTrack *track)
3282 {
3283     avio_wb32(pb, 0x20); /* size */
3284     ffio_wfourcc(pb, "trex");
3285     avio_wb32(pb, 0);   /* version & flags */
3286     avio_wb32(pb, track->track_id); /* track ID */
3287     avio_wb32(pb, 1);   /* default sample description index */
3288     avio_wb32(pb, 0);   /* default sample duration */
3289     avio_wb32(pb, 0);   /* default sample size */
3290     avio_wb32(pb, 0);   /* default sample flags */
3291     return 0;
3292 }
3293
3294 static int mov_write_mvex_tag(AVIOContext *pb, MOVMuxContext *mov)
3295 {
3296     int64_t pos = avio_tell(pb);
3297     int i;
3298     avio_wb32(pb, 0x0); /* size */
3299     ffio_wfourcc(pb, "mvex");
3300     for (i = 0; i < mov->nb_streams; i++)
3301         mov_write_trex_tag(pb, &mov->tracks[i]);
3302     return update_size(pb, pos);
3303 }
3304
3305 static int mov_write_mvhd_tag(AVIOContext *pb, MOVMuxContext *mov)
3306 {
3307     int max_track_id = 1, i;
3308     int64_t max_track_len = 0;
3309     int version;
3310
3311     for (i = 0; i < mov->nb_streams; i++) {
3312         if (mov->tracks[i].entry > 0 && mov->tracks[i].timescale) {
3313             int64_t max_track_len_temp = av_rescale_rnd(
3314                                                 calc_pts_duration(mov, &mov->tracks[i]),
3315                                                 MOV_TIMESCALE,
3316                                                 mov->tracks[i].timescale,
3317                                                 AV_ROUND_UP);
3318             if (max_track_len < max_track_len_temp)
3319                 max_track_len = max_track_len_temp;
3320             if (max_track_id < mov->tracks[i].track_id)
3321                 max_track_id = mov->tracks[i].track_id;
3322         }
3323     }
3324     /* If using delay_moov, make sure the output is the same as if no
3325      * samples had been written yet. */
3326     if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
3327         max_track_len = 0;
3328         max_track_id  = 1;
3329     }
3330
3331     version = max_track_len < UINT32_MAX ? 0 : 1;
3332     avio_wb32(pb, version == 1 ? 120 : 108); /* size */
3333
3334     ffio_wfourcc(pb, "mvhd");
3335     avio_w8(pb, version);
3336     avio_wb24(pb, 0); /* flags */
3337     if (version == 1) {
3338         avio_wb64(pb, mov->time);
3339         avio_wb64(pb, mov->time);
3340     } else {
3341         avio_wb32(pb, mov->time); /* creation time */
3342         avio_wb32(pb, mov->time); /* modification time */
3343     }
3344     avio_wb32(pb, MOV_TIMESCALE);
3345     (version == 1) ? avio_wb64(pb, max_track_len) : avio_wb32(pb, max_track_len); /* duration of longest track */
3346
3347     avio_wb32(pb, 0x00010000); /* reserved (preferred rate) 1.0 = normal */
3348     avio_wb16(pb, 0x0100); /* reserved (preferred volume) 1.0 = normal */
3349     avio_wb16(pb, 0); /* reserved */
3350     avio_wb32(pb, 0); /* reserved */
3351     avio_wb32(pb, 0); /* reserved */
3352
3353     /* Matrix structure */
3354     write_matrix(pb, 1, 0, 0, 1, 0, 0);
3355
3356     avio_wb32(pb, 0); /* reserved (preview time) */
3357     avio_wb32(pb, 0); /* reserved (preview duration) */
3358     avio_wb32(pb, 0); /* reserved (poster time) */
3359     avio_wb32(pb, 0); /* reserved (selection time) */
3360     avio_wb32(pb, 0); /* reserved (selection duration) */
3361     avio_wb32(pb, 0); /* reserved (current time) */
3362     avio_wb32(pb, max_track_id + 1); /* Next track id */
3363     return 0x6c;
3364 }
3365
3366 static int mov_write_itunes_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov,
3367                                      AVFormatContext *s)
3368 {
3369     avio_wb32(pb, 33); /* size */
3370     ffio_wfourcc(pb, "hdlr");
3371     avio_wb32(pb, 0);
3372     avio_wb32(pb, 0);
3373     ffio_wfourcc(pb, "mdir");
3374     ffio_wfourcc(pb, "appl");
3375     avio_wb32(pb, 0);
3376     avio_wb32(pb, 0);
3377     avio_w8(pb, 0);
3378     return 33;
3379 }
3380
3381 /* helper function to write a data tag with the specified string as data */
3382 static int mov_write_string_data_tag(AVIOContext *pb, const char *data, int lang, int long_style)
3383 {
3384     if (long_style) {
3385         int size = 16 + strlen(data);
3386         avio_wb32(pb, size); /* size */
3387         ffio_wfourcc(pb, "data");
3388         avio_wb32(pb, 1);
3389         avio_wb32(pb, 0);
3390         avio_write(pb, data, strlen(data));
3391         return size;
3392     } else {
3393         if (!lang)
3394             lang = ff_mov_iso639_to_lang("und", 1);
3395         avio_wb16(pb, strlen(data)); /* string length */
3396         avio_wb16(pb, lang);
3397         avio_write(pb, data, strlen(data));
3398         return strlen(data) + 4;
3399     }
3400 }
3401
3402 static int mov_write_string_tag(AVIOContext *pb, const char *name,
3403                                 const char *value, int lang, int long_style)
3404 {
3405     int size = 0;
3406     if (value && value[0]) {
3407         int64_t pos = avio_tell(pb);
3408         avio_wb32(pb, 0); /* size */
3409         ffio_wfourcc(pb, name);
3410         mov_write_string_data_tag(pb, value, lang, long_style);
3411         size = update_size(pb, pos);
3412     }
3413     return size;
3414 }
3415
3416 static AVDictionaryEntry *get_metadata_lang(AVFormatContext *s,
3417                                             const char *tag, int *lang)
3418 {
3419     int l, len, len2;
3420     AVDictionaryEntry *t, *t2 = NULL;
3421     char tag2[16];
3422
3423     *lang = 0;
3424
3425     if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
3426         return NULL;
3427
3428     len = strlen(t->key);
3429     snprintf(tag2, sizeof(tag2), "%s-", tag);
3430     while ((t2 = av_dict_get(s->metadata, tag2, t2, AV_DICT_IGNORE_SUFFIX))) {
3431         len2 = strlen(t2->key);
3432         if (len2 == len + 4 && !strcmp(t->value, t2->value)
3433             && (l = ff_mov_iso639_to_lang(&t2->key[len2 - 3], 1)) >= 0) {
3434             *lang = l;
3435             return t;
3436         }
3437     }
3438     return t;
3439 }
3440
3441 static int mov_write_string_metadata(AVFormatContext *s, AVIOContext *pb,
3442                                      const char *name, const char *tag,
3443                                      int long_style)
3444 {
3445     int lang;
3446     AVDictionaryEntry *t = get_metadata_lang(s, tag, &lang);
3447     if (!t)
3448         return 0;
3449     return mov_write_string_tag(pb, name, t->value, lang, long_style);
3450 }
3451
3452 /* iTunes bpm number */
3453 static int mov_write_tmpo_tag(AVIOContext *pb, AVFormatContext *s)
3454 {
3455     AVDictionaryEntry *t = av_dict_get(s->metadata, "tmpo", NULL, 0);
3456     int size = 0, tmpo = t ? atoi(t->value) : 0;
3457     if (tmpo) {
3458         size = 26;
3459         avio_wb32(pb, size);
3460         ffio_wfourcc(pb, "tmpo");
3461         avio_wb32(pb, size-8); /* size */
3462         ffio_wfourcc(pb, "data");
3463         avio_wb32(pb, 0x15);  //type specifier
3464         avio_wb32(pb, 0);
3465         avio_wb16(pb, tmpo);        // data
3466     }
3467     return size;
3468 }
3469
3470 /* 3GPP TS 26.244 */
3471 static int mov_write_loci_tag(AVFormatContext *s, AVIOContext *pb)
3472 {
3473     int lang;
3474     int64_t pos = avio_tell(pb);
3475     double latitude, longitude, altitude;
3476     int32_t latitude_fix, longitude_fix, altitude_fix;
3477     AVDictionaryEntry *t = get_metadata_lang(s, "location", &lang);
3478     const char *ptr, *place = "";
3479     char *end;
3480     static const char *astronomical_body = "earth";
3481     if (!t)
3482         return 0;
3483
3484     ptr = t->value;
3485     longitude = strtod(ptr, &end);
3486     if (end == ptr) {
3487         av_log(s, AV_LOG_WARNING, "malformed location metadata\n");
3488         return 0;
3489     }
3490     ptr = end;
3491     latitude = strtod(ptr, &end);
3492     if (end == ptr) {
3493         av_log(s, AV_LOG_WARNING, "malformed location metadata\n");
3494         return 0;
3495     }
3496     ptr = end;
3497     altitude = strtod(ptr, &end);
3498     /* If no altitude was present, the default 0 should be fine */
3499     if (*end == '/')
3500         place = end + 1;
3501
3502     latitude_fix  = (int32_t) ((1 << 16) * latitude);
3503     longitude_fix = (int32_t) ((1 << 16) * longitude);
3504     altitude_fix  = (int32_t) ((1 << 16) * altitude);
3505
3506     avio_wb32(pb, 0);         /* size */
3507     ffio_wfourcc(pb, "loci"); /* type */
3508     avio_wb32(pb, 0);         /* version + flags */
3509     avio_wb16(pb, lang);
3510     avio_write(pb, place, strlen(place) + 1);
3511     avio_w8(pb, 0);           /* role of place (0 == shooting location, 1 == real location, 2 == fictional location) */
3512     avio_wb32(pb, latitude_fix);
3513     avio_wb32(pb, longitude_fix);
3514     avio_wb32(pb, altitude_fix);
3515     avio_write(pb, astronomical_body, strlen(astronomical_body) + 1);
3516     avio_w8(pb, 0);           /* additional notes, null terminated string */
3517
3518     return update_size(pb, pos);
3519 }
3520
3521 /* iTunes track or disc number */
3522 static int mov_write_trkn_tag(AVIOContext *pb, MOVMuxContext *mov,
3523                               AVFormatContext *s, int disc)
3524 {
3525     AVDictionaryEntry *t = av_dict_get(s->metadata,
3526                                        disc ? "disc" : "track",
3527                                        NULL, 0);
3528     int size = 0, track = t ? atoi(t->value) : 0;
3529     if (track) {
3530         int tracks = 0;
3531         char *slash = strchr(t->value, '/');
3532         if (slash)
3533             tracks = atoi(slash + 1);
3534         avio_wb32(pb, 32); /* size */
3535         ffio_wfourcc(pb, disc ? "disk" : "trkn");
3536         avio_wb32(pb, 24); /* size */
3537         ffio_wfourcc(pb, "data");
3538         avio_wb32(pb, 0);        // 8 bytes empty
3539         avio_wb32(pb, 0);
3540         avio_wb16(pb, 0);        // empty
3541         avio_wb16(pb, track);    // track / disc number
3542         avio_wb16(pb, tracks);   // total track / disc number
3543         avio_wb16(pb, 0);        // empty
3544         size = 32;
3545     }
3546     return size;
3547 }
3548
3549 static int mov_write_int8_metadata(AVFormatContext *s, AVIOContext *pb,
3550                                    const char *name, const char *tag,
3551                                    int len)
3552 {
3553     AVDictionaryEntry *t = NULL;
3554     uint8_t num;
3555     int size = 24 + len;
3556
3557     if (len != 1 && len != 4)
3558         return -1;
3559
3560     if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
3561         return 0;
3562     num = atoi(t->value);
3563
3564     avio_wb32(pb, size);
3565     ffio_wfourcc(pb, name);
3566     avio_wb32(pb, size - 8);
3567     ffio_wfourcc(pb, "data");
3568     avio_wb32(pb, 0x15);
3569     avio_wb32(pb, 0);
3570     if (len==4) avio_wb32(pb, num);
3571     else        avio_w8 (pb, num);
3572
3573     return size;
3574 }
3575
3576 static int mov_write_covr(AVIOContext *pb, AVFormatContext *s)
3577 {
3578     MOVMuxContext *mov = s->priv_data;
3579     int64_t pos = 0;
3580     int i;
3581
3582     for (i = 0; i < s->nb_streams; i++) {
3583         MOVTrack *trk = &mov->tracks[i];
3584
3585         if (!is_cover_image(trk->st) || trk->cover_image.size <= 0)
3586             continue;
3587
3588         if (!pos) {
3589             pos = avio_tell(pb);
3590             avio_wb32(pb, 0);
3591             ffio_wfourcc(pb, "covr");
3592         }
3593         avio_wb32(pb, 16 + trk->cover_image.size);
3594         ffio_wfourcc(pb, "data");
3595         avio_wb32(pb, trk->tag);
3596         avio_wb32(pb , 0);
3597         avio_write(pb, trk->cover_image.data, trk->cover_image.size);
3598     }
3599
3600     return pos ? update_size(pb, pos) : 0;
3601 }
3602
3603 /* iTunes meta data list */
3604 static int mov_write_ilst_tag(AVIOContext *pb, MOVMuxContext *mov,
3605                               AVFormatContext *s)
3606 {
3607     int64_t pos = avio_tell(pb);
3608     avio_wb32(pb, 0); /* size */
3609     ffio_wfourcc(pb, "ilst");
3610     mov_write_string_metadata(s, pb, "\251nam", "title"    , 1);
3611     mov_write_string_metadata(s, pb, "\251ART", "artist"   , 1);
3612     mov_write_string_metadata(s, pb, "aART", "album_artist", 1);
3613     mov_write_string_metadata(s, pb, "\251wrt", "composer" , 1);
3614     mov_write_string_metadata(s, pb, "\251alb", "album"    , 1);
3615     mov_write_string_metadata(s, pb, "\251day", "date"     , 1);
3616     if (!mov_write_string_metadata(s, pb, "\251too", "encoding_tool", 1)) {
3617         if (!(s->flags & AVFMT_FLAG_BITEXACT))
3618             mov_write_string_tag(pb, "\251too", LIBAVFORMAT_IDENT, 0, 1);
3619     }
3620     mov_write_string_metadata(s, pb, "\251cmt", "comment"  , 1);
3621     mov_write_string_metadata(s, pb, "\251gen", "genre"    , 1);
3622     mov_write_string_metadata(s, pb, "cprt",    "copyright", 1);
3623     mov_write_string_metadata(s, pb, "\251grp", "grouping" , 1);
3624     mov_write_string_metadata(s, pb, "\251lyr", "lyrics"   , 1);
3625     mov_write_string_metadata(s, pb, "desc",    "description",1);
3626     mov_write_string_metadata(s, pb, "ldes",    "synopsis" , 1);
3627     mov_write_string_metadata(s, pb, "tvsh",    "show"     , 1);
3628     mov_write_string_metadata(s, pb, "tven",    "episode_id",1);
3629     mov_write_string_metadata(s, pb, "tvnn",    "network"  , 1);
3630     mov_write_string_metadata(s, pb, "keyw",    "keywords"  , 1);
3631     mov_write_int8_metadata  (s, pb, "tves",    "episode_sort",4);
3632     mov_write_int8_metadata  (s, pb, "tvsn",    "season_number",4);
3633     mov_write_int8_metadata  (s, pb, "stik",    "media_type",1);
3634     mov_write_int8_metadata  (s, pb, "hdvd",    "hd_video",  1);
3635     mov_write_int8_metadata  (s, pb, "pgap",    "gapless_playback",1);
3636     mov_write_int8_metadata  (s, pb, "cpil",    "compilation", 1);
3637     mov_write_covr(pb, s);
3638     mov_write_trkn_tag(pb, mov, s, 0); // track number
3639     mov_write_trkn_tag(pb, mov, s, 1); // disc number
3640     mov_write_tmpo_tag(pb, s);
3641     return update_size(pb, pos);
3642 }
3643
3644 static int mov_write_mdta_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov,
3645                                    AVFormatContext *s)
3646 {
3647     avio_wb32(pb, 33); /* size */
3648     ffio_wfourcc(pb, "hdlr");
3649     avio_wb32(pb, 0);
3650     avio_wb32(pb, 0);
3651     ffio_wfourcc(pb, "mdta");
3652     avio_wb32(pb, 0);
3653     avio_wb32(pb, 0);
3654     avio_wb32(pb, 0);
3655     avio_w8(pb, 0);
3656     return 33;
3657 }
3658
3659 static int mov_write_mdta_keys_tag(AVIOContext *pb, MOVMuxContext *mov,
3660                                    AVFormatContext *s)
3661 {
3662     AVDictionaryEntry *t = NULL;
3663     int64_t pos = avio_tell(pb);
3664     int64_t curpos, entry_pos;
3665     int count = 0;
3666
3667     avio_wb32(pb, 0); /* size */
3668     ffio_wfourcc(pb, "keys");
3669     avio_wb32(pb, 0);
3670     entry_pos = avio_tell(pb);
3671     avio_wb32(pb, 0); /* entry count */
3672
3673     while (t = av_dict_get(s->metadata, "", t, AV_DICT_IGNORE_SUFFIX)) {
3674         avio_wb32(pb, strlen(t->key) + 8);
3675         ffio_wfourcc(pb, "mdta");
3676         avio_write(pb, t->key, strlen(t->key));
3677         count += 1;
3678     }
3679     curpos = avio_tell(pb);
3680     avio_seek(pb, entry_pos, SEEK_SET);
3681     avio_wb32(pb, count); // rewrite entry count
3682     avio_seek(pb, curpos, SEEK_SET);
3683
3684     return update_size(pb, pos);
3685 }
3686
3687 static int mov_write_mdta_ilst_tag(AVIOContext *pb, MOVMuxContext *mov,
3688                                    AVFormatContext *s)
3689 {
3690     AVDictionaryEntry *t = NULL;
3691     int64_t pos = avio_tell(pb);
3692     int count = 1; /* keys are 1-index based */
3693
3694     avio_wb32(pb, 0); /* size */
3695     ffio_wfourcc(pb, "ilst");
3696
3697     while (t = av_dict_get(s->metadata, "", t, AV_DICT_IGNORE_SUFFIX)) {
3698         int64_t entry_pos = avio_tell(pb);
3699         avio_wb32(pb, 0); /* size */
3700         avio_wb32(pb, count); /* key */
3701         mov_write_string_data_tag(pb, t->value, 0, 1);
3702         update_size(pb, entry_pos);
3703         count += 1;
3704     }
3705     return update_size(pb, pos);
3706 }
3707
3708 /* meta data tags */
3709 static int mov_write_meta_tag(AVIOContext *pb, MOVMuxContext *mov,
3710                               AVFormatContext *s)
3711 {
3712     int size = 0;
3713     int64_t pos = avio_tell(pb);
3714     avio_wb32(pb, 0); /* size */
3715     ffio_wfourcc(pb, "meta");
3716     avio_wb32(pb, 0);
3717     if (mov->flags & FF_MOV_FLAG_USE_MDTA) {
3718         mov_write_mdta_hdlr_tag(pb, mov, s);
3719         mov_write_mdta_keys_tag(pb, mov, s);
3720         mov_write_mdta_ilst_tag(pb, mov, s);
3721     }
3722     else {
3723         /* iTunes metadata tag */
3724         mov_write_itunes_hdlr_tag(pb, mov, s);
3725         mov_write_ilst_tag(pb, mov, s);
3726     }
3727     size = update_size(pb, pos);
3728     return size;
3729 }
3730
3731 static int mov_write_raw_metadata_tag(AVFormatContext *s, AVIOContext *pb,
3732                                       const char *name, const char *key)
3733 {
3734     int len;
3735     AVDictionaryEntry *t;
3736
3737     if (!(t = av_dict_get(s->metadata, key, NULL, 0)))
3738         return 0;
3739
3740     len = strlen(t->value);
3741     if (len > 0) {
3742         int size = len + 8;
3743         avio_wb32(pb, size);
3744         ffio_wfourcc(pb, name);
3745         avio_write(pb, t->value, len);
3746         return size;
3747     }
3748     return 0;
3749 }
3750
3751 static int ascii_to_wc(AVIOContext *pb, const uint8_t *b)
3752 {
3753     int val;
3754     while (*b) {
3755         GET_UTF8(val, *b++, return -1;)
3756         avio_wb16(pb, val);
3757     }
3758     avio_wb16(pb, 0x00);
3759     return 0;
3760 }
3761
3762 static uint16_t language_code(const char *str)
3763 {
3764     return (((str[0] - 0x60) & 0x1F) << 10) +
3765            (((str[1] - 0x60) & 0x1F) <<  5) +
3766            (( str[2] - 0x60) & 0x1F);
3767 }
3768
3769 static int mov_write_3gp_udta_tag(AVIOContext *pb, AVFormatContext *s,
3770                                   const char *tag, const char *str)
3771 {
3772     int64_t pos = avio_tell(pb);
3773     AVDictionaryEntry *t = av_dict_get(s->metadata, str, NULL, 0);
3774     if (!t || !utf8len(t->value))
3775         return 0;
3776     avio_wb32(pb, 0);   /* size */
3777     ffio_wfourcc(pb, tag); /* type */
3778     avio_wb32(pb, 0);   /* version + flags */
3779     if (!strcmp(tag, "yrrc"))
3780         avio_wb16(pb, atoi(t->value));
3781     else {
3782         avio_wb16(pb, language_code("eng")); /* language */
3783         avio_write(pb, t->value, strlen(t->value) + 1); /* UTF8 string value */
3784         if (!strcmp(tag, "albm") &&
3785             (t = av_dict_get(s->metadata, "track", NULL, 0)))
3786             avio_w8(pb, atoi(t->value));
3787     }
3788     return update_size(pb, pos);
3789 }
3790
3791 static int mov_write_chpl_tag(AVIOContext *pb, AVFormatContext *s)
3792 {
3793     int64_t pos = avio_tell(pb);
3794     int i, nb_chapters = FFMIN(s->nb_chapters, 255);
3795
3796     avio_wb32(pb, 0);            // size
3797     ffio_wfourcc(pb, "chpl");
3798     avio_wb32(pb, 0x01000000);   // version + flags
3799     avio_wb32(pb, 0);            // unknown
3800     avio_w8(pb, nb_chapters);
3801
3802     for (i = 0; i < nb_chapters; i++) {
3803         AVChapter *c = s->chapters[i];
3804         AVDictionaryEntry *t;
3805         avio_wb64(pb, av_rescale_q(c->start, c->time_base, (AVRational){1,10000000}));
3806
3807         if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
3808             int len = FFMIN(strlen(t->value), 255);
3809             avio_w8(pb, len);
3810             avio_write(pb, t->value, len);
3811         } else
3812             avio_w8(pb, 0);
3813     }
3814     return update_size(pb, pos);
3815 }
3816
3817 static int mov_write_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
3818                               AVFormatContext *s)
3819 {
3820     AVIOContext *pb_buf;
3821     int ret, size;
3822     uint8_t *buf;
3823
3824     ret = avio_open_dyn_buf(&pb_buf);
3825     if (ret < 0)
3826         return ret;
3827
3828     if (mov->mode & MODE_3GP) {
3829         mov_write_3gp_udta_tag(pb_buf, s, "perf", "artist");
3830         mov_write_3gp_udta_tag(pb_buf, s, "titl", "title");
3831         mov_write_3gp_udta_tag(pb_buf, s, "auth", "author");
3832         mov_write_3gp_udta_tag(pb_buf, s, "gnre", "genre");
3833         mov_write_3gp_udta_tag(pb_buf, s, "dscp", "comment");
3834         mov_write_3gp_udta_tag(pb_buf, s, "albm", "album");
3835         mov_write_3gp_udta_tag(pb_buf, s, "cprt", "copyright");
3836         mov_write_3gp_udta_tag(pb_buf, s, "yrrc", "date");
3837         mov_write_loci_tag(s, pb_buf);
3838     } 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
3839         mov_write_string_metadata(s, pb_buf, "\251ART", "artist",      0);
3840         mov_write_string_metadata(s, pb_buf, "\251nam", "title",       0);
3841         mov_write_string_metadata(s, pb_buf, "\251aut", "author",      0);
3842         mov_write_string_metadata(s, pb_buf, "\251alb", "album",       0);
3843         mov_write_string_metadata(s, pb_buf, "\251day", "date",        0);
3844         mov_write_string_metadata(s, pb_buf, "\251swr", "encoder",     0);
3845         // currently ignored by mov.c
3846         mov_write_string_metadata(s, pb_buf, "\251des", "comment",     0);
3847         // add support for libquicktime, this atom is also actually read by mov.c
3848         mov_write_string_metadata(s, pb_buf, "\251cmt", "comment",     0);
3849         mov_write_string_metadata(s, pb_buf, "\251gen", "genre",       0);
3850         mov_write_string_metadata(s, pb_buf, "\251cpy", "copyright",   0);
3851         mov_write_string_metadata(s, pb_buf, "\251mak", "make",        0);
3852         mov_write_string_metadata(s, pb_buf, "\251mod", "model",       0);
3853         mov_write_string_metadata(s, pb_buf, "\251xyz", "location",    0);
3854         mov_write_string_metadata(s, pb_buf, "\251key", "keywords",    0);
3855         mov_write_raw_metadata_tag(s, pb_buf, "XMP_", "xmp");
3856     } else {
3857         /* iTunes meta data */
3858         mov_write_meta_tag(pb_buf, mov, s);
3859         mov_write_loci_tag(s, pb_buf);
3860     }
3861
3862     if (s->nb_chapters && !(mov->flags & FF_MOV_FLAG_DISABLE_CHPL))
3863         mov_write_chpl_tag(pb_buf, s);
3864
3865     if ((size = avio_get_dyn_buf(pb_buf, &buf)) > 0) {
3866         avio_wb32(pb, size + 8);
3867         ffio_wfourcc(pb, "udta");
3868         avio_write(pb, buf, size);
3869     }
3870     ffio_free_dyn_buf(&pb_buf);
3871
3872     return 0;
3873 }
3874
3875 static void mov_write_psp_udta_tag(AVIOContext *pb,
3876                                    const char *str, const char *lang, int type)
3877 {
3878     int len = utf8len(str) + 1;
3879     if (len <= 0)
3880         return;
3881     avio_wb16(pb, len * 2 + 10);        /* size */
3882     avio_wb32(pb, type);                /* type */
3883     avio_wb16(pb, language_code(lang)); /* language */
3884     avio_wb16(pb, 0x01);                /* ? */
3885     ascii_to_wc(pb, str);
3886 }
3887
3888 static int mov_write_uuidusmt_tag(AVIOContext *pb, AVFormatContext *s)
3889 {
3890     AVDictionaryEntry *title = av_dict_get(s->metadata, "title", NULL, 0);
3891     int64_t pos, pos2;
3892
3893     if (title) {
3894         pos = avio_tell(pb);
3895         avio_wb32(pb, 0); /* size placeholder*/
3896         ffio_wfourcc(pb, "uuid");
3897         ffio_wfourcc(pb, "USMT");
3898         avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
3899         avio_wb32(pb, 0xbb88695c);
3900         avio_wb32(pb, 0xfac9c740);
3901
3902         pos2 = avio_tell(pb);
3903         avio_wb32(pb, 0); /* size placeholder*/
3904         ffio_wfourcc(pb, "MTDT");
3905         avio_wb16(pb, 4);
3906
3907         // ?
3908         avio_wb16(pb, 0x0C);                 /* size */
3909         avio_wb32(pb, 0x0B);                 /* type */
3910         avio_wb16(pb, language_code("und")); /* language */
3911         avio_wb16(pb, 0x0);                  /* ? */
3912         avio_wb16(pb, 0x021C);               /* data */
3913
3914         if (!(s->flags & AVFMT_FLAG_BITEXACT))
3915             mov_write_psp_udta_tag(pb, LIBAVCODEC_IDENT,      "eng", 0x04);
3916         mov_write_psp_udta_tag(pb, title->value,          "eng", 0x01);
3917         mov_write_psp_udta_tag(pb, "2006/04/01 11:11:11", "und", 0x03);
3918
3919         update_size(pb, pos2);
3920         return update_size(pb, pos);
3921     }
3922
3923     return 0;
3924 }
3925
3926 static void build_chunks(MOVTrack *trk)
3927 {
3928     int i;
3929     MOVIentry *chunk = &trk->cluster[0];
3930     uint64_t chunkSize = chunk->size;
3931     chunk->chunkNum = 1;
3932     if (trk->chunkCount)
3933         return;
3934     trk->chunkCount = 1;
3935     for (i = 1; i<trk->entry; i++){
3936         if (chunk->pos + chunkSize == trk->cluster[i].pos &&
3937             chunkSize + trk->cluster[i].size < (1<<20)){
3938             chunkSize             += trk->cluster[i].size;
3939             chunk->samples_in_chunk += trk->cluster[i].entries;
3940         } else {
3941             trk->cluster[i].chunkNum = chunk->chunkNum+1;
3942             chunk=&trk->cluster[i];
3943             chunkSize = chunk->size;
3944             trk->chunkCount++;
3945         }
3946     }
3947 }
3948
3949 /**
3950  * Assign track ids. If option "use_stream_ids_as_track_ids" is set,
3951  * the stream ids are used as track ids.
3952  *
3953  * This assumes mov->tracks and s->streams are in the same order and
3954  * there are no gaps in either of them (so mov->tracks[n] refers to
3955  * s->streams[n]).
3956  *
3957  * As an exception, there can be more entries in
3958  * s->streams than in mov->tracks, in which case new track ids are
3959  * generated (starting after the largest found stream id).
3960  */
3961 static int mov_setup_track_ids(MOVMuxContext *mov, AVFormatContext *s)
3962 {
3963     int i;
3964
3965     if (mov->track_ids_ok)
3966         return 0;
3967
3968     if (mov->use_stream_ids_as_track_ids) {
3969         int next_generated_track_id = 0;
3970         for (i = 0; i < s->nb_streams; i++) {
3971             if (s->streams[i]->id > next_generated_track_id)
3972                 next_generated_track_id = s->streams[i]->id;
3973         }
3974
3975         for (i = 0; i < mov->nb_streams; i++) {
3976             if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
3977                 continue;
3978
3979             mov->tracks[i].track_id = i >= s->nb_streams ? ++next_generated_track_id : s->streams[i]->id;
3980         }
3981     } else {
3982         for (i = 0; i < mov->nb_streams; i++) {
3983             if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
3984                 continue;
3985
3986             mov->tracks[i].track_id = i + 1;
3987         }
3988     }
3989
3990     mov->track_ids_ok = 1;
3991
3992     return 0;
3993 }
3994
3995 static int mov_write_moov_tag(AVIOContext *pb, MOVMuxContext *mov,
3996                               AVFormatContext *s)
3997 {
3998     int i;
3999     int64_t pos = avio_tell(pb);
4000     avio_wb32(pb, 0); /* size placeholder*/
4001     ffio_wfourcc(pb, "moov");
4002
4003     mov_setup_track_ids(mov, s);
4004
4005     for (i = 0; i < mov->nb_streams; i++) {
4006         if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
4007             continue;
4008
4009         mov->tracks[i].time     = mov->time;
4010
4011         if (mov->tracks[i].entry)
4012             build_chunks(&mov->tracks[i]);
4013     }
4014
4015     if (mov->chapter_track)
4016         for (i = 0; i < s->nb_streams; i++) {
4017             mov->tracks[i].tref_tag = MKTAG('c','h','a','p');
4018             mov->tracks[i].tref_id  = mov->tracks[mov->chapter_track].track_id;
4019         }
4020     for (i = 0; i < mov->nb_streams; i++) {
4021         MOVTrack *track = &mov->tracks[i];
4022         if (track->tag == MKTAG('r','t','p',' ')) {
4023             track->tref_tag = MKTAG('h','i','n','t');
4024             track->tref_id = mov->tracks[track->src_track].track_id;
4025         } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
4026             int * fallback, size;
4027             fallback = (int*)av_stream_get_side_data(track->st,
4028                                                      AV_PKT_DATA_FALLBACK_TRACK,
4029                                                      &size);
4030             if (fallback != NULL && size == sizeof(int)) {
4031                 if (*fallback >= 0 && *fallback < mov->nb_streams) {
4032                     track->tref_tag = MKTAG('f','a','l','l');
4033                     track->tref_id = mov->tracks[*fallback].track_id;
4034                 }
4035             }
4036         }
4037     }
4038     for (i = 0; i < mov->nb_streams; i++) {
4039         if (mov->tracks[i].tag == MKTAG('t','m','c','d')) {
4040             int src_trk = mov->tracks[i].src_track;
4041             mov->tracks[src_trk].tref_tag = mov->tracks[i].tag;
4042             mov->tracks[src_trk].tref_id  = mov->tracks[i].track_id;
4043             //src_trk may have a different timescale than the tmcd track
4044             mov->tracks[i].track_duration = av_rescale(mov->tracks[src_trk].track_duration,
4045                                                        mov->tracks[i].timescale,
4046                                                        mov->tracks[src_trk].timescale);
4047         }
4048     }
4049
4050     mov_write_mvhd_tag(pb, mov);
4051     if (mov->mode != MODE_MOV && !mov->iods_skip)
4052         mov_write_iods_tag(pb, mov);
4053     for (i = 0; i < mov->nb_streams; i++) {
4054         if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_FRAGMENT) {
4055             int ret = mov_write_trak_tag(s, pb, mov, &(mov->tracks[i]), i < s->nb_streams ? s->streams[i] : NULL);
4056             if (ret < 0)
4057                 return ret;
4058         }
4059     }
4060     if (mov->flags & FF_MOV_FLAG_FRAGMENT)
4061         mov_write_mvex_tag(pb, mov); /* QuickTime requires trak to precede this */
4062
4063     if (mov->mode == MODE_PSP)
4064         mov_write_uuidusmt_tag(pb, s);
4065     else
4066         mov_write_udta_tag(pb, mov, s);
4067
4068     return update_size(pb, pos);
4069 }
4070
4071 static void param_write_int(AVIOContext *pb, const char *name, int value)
4072 {
4073     avio_printf(pb, "<param name=\"%s\" value=\"%d\" valuetype=\"data\"/>\n", name, value);
4074 }
4075
4076 static void param_write_string(AVIOContext *pb, const char *name, const char *value)
4077 {
4078     avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, value);
4079 }
4080
4081 static void param_write_hex(AVIOContext *pb, const char *name, const uint8_t *value, int len)
4082 {
4083     char buf[150];
4084     len = FFMIN(sizeof(buf) / 2 - 1, len);
4085     ff_data_to_hex(buf, value, len, 0);
4086     buf[2 * len] = '\0';
4087     avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, buf);
4088 }
4089
4090 static int mov_write_isml_manifest(AVIOContext *pb, MOVMuxContext *mov, AVFormatContext *s)
4091 {
4092     int64_t pos = avio_tell(pb);
4093     int i;
4094     int64_t manifest_bit_rate = 0;
4095     AVCPBProperties *props = NULL;
4096
4097     static const uint8_t uuid[] = {
4098         0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd,
4099         0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66
4100     };
4101
4102     avio_wb32(pb, 0);
4103     ffio_wfourcc(pb, "uuid");
4104     avio_write(pb, uuid, sizeof(uuid));
4105     avio_wb32(pb, 0);
4106
4107     avio_printf(pb, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
4108     avio_printf(pb, "<smil xmlns=\"http://www.w3.org/2001/SMIL20/Language\">\n");
4109     avio_printf(pb, "<head>\n");
4110     if (!(mov->fc->flags & AVFMT_FLAG_BITEXACT))
4111         avio_printf(pb, "<meta name=\"creator\" content=\"%s\" />\n",
4112                     LIBAVFORMAT_IDENT);
4113     avio_printf(pb, "</head>\n");
4114     avio_printf(pb, "<body>\n");
4115     avio_printf(pb, "<switch>\n");
4116
4117     mov_setup_track_ids(mov, s);
4118
4119     for (i = 0; i < mov->nb_streams; i++) {
4120         MOVTrack *track = &mov->tracks[i];
4121         const char *type;
4122         int track_id = track->track_id;
4123         char track_name_buf[32] = { 0 };
4124
4125         AVStream *st = track->st;
4126         AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0);
4127
4128         if (track->par->codec_type == AVMEDIA_TYPE_VIDEO && !is_cover_image(st)) {
4129             type = "video";
4130         } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
4131             type = "audio";
4132         } else {
4133             continue;
4134         }
4135
4136         props = (AVCPBProperties*)av_stream_get_side_data(track->st, AV_PKT_DATA_CPB_PROPERTIES, NULL);
4137
4138         if (track->par->bit_rate) {
4139             manifest_bit_rate = track->par->bit_rate;
4140         } else if (props) {
4141             manifest_bit_rate = props->max_bitrate;
4142         }
4143
4144         avio_printf(pb, "<%s systemBitrate=\"%"PRId64"\">\n", type,
4145                     manifest_bit_rate);
4146         param_write_int(pb, "systemBitrate", manifest_bit_rate);
4147         param_write_int(pb, "trackID", track_id);
4148         param_write_string(pb, "systemLanguage", lang ? lang->value : "und");
4149
4150         /* Build track name piece by piece: */
4151         /* 1. track type */
4152         av_strlcat(track_name_buf, type, sizeof(track_name_buf));
4153         /* 2. track language, if available */
4154         if (lang)
4155             av_strlcatf(track_name_buf, sizeof(track_name_buf),
4156                         "_%s", lang->value);
4157         /* 3. special type suffix */
4158         /* "_cc" = closed captions, "_ad" = audio_description */
4159         if (st->disposition & AV_DISPOSITION_HEARING_IMPAIRED)
4160             av_strlcat(track_name_buf, "_cc", sizeof(track_name_buf));
4161         else if (st->disposition & AV_DISPOSITION_VISUAL_IMPAIRED)
4162             av_strlcat(track_name_buf, "_ad", sizeof(track_name_buf));
4163
4164         param_write_string(pb, "trackName", track_name_buf);
4165
4166         if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
4167             if (track->par->codec_id == AV_CODEC_ID_H264) {
4168                 uint8_t *ptr;
4169                 int size = track->par->extradata_size;
4170                 if (!ff_avc_write_annexb_extradata(track->par->extradata, &ptr,
4171                                                    &size)) {
4172                     param_write_hex(pb, "CodecPrivateData",
4173                                     ptr ? ptr : track->par->extradata,
4174                                     size);
4175                     av_free(ptr);
4176                 }
4177                 param_write_string(pb, "FourCC", "H264");
4178             } else if (track->par->codec_id == AV_CODEC_ID_VC1) {
4179                 param_write_string(pb, "FourCC", "WVC1");
4180                 param_write_hex(pb, "CodecPrivateData", track->par->extradata,
4181                                 track->par->extradata_size);
4182             }
4183             param_write_int(pb, "MaxWidth", track->par->width);
4184             param_write_int(pb, "MaxHeight", track->par->height);
4185             param_write_int(pb, "DisplayWidth", track->par->width);
4186             param_write_int(pb, "DisplayHeight", track->par->height);
4187         } else {
4188             if (track->par->codec_id == AV_CODEC_ID_AAC) {
4189                 switch (track->par->profile)
4190                 {
4191                     case FF_PROFILE_AAC_HE_V2:
4192                         param_write_string(pb, "FourCC", "AACP");
4193                         break;
4194                     case FF_PROFILE_AAC_HE:
4195                         param_write_string(pb, "FourCC", "AACH");
4196                         break;
4197                     default:
4198                         param_write_string(pb, "FourCC", "AACL");
4199                 }
4200             } else if (track->par->codec_id == AV_CODEC_ID_WMAPRO) {
4201                 param_write_string(pb, "FourCC", "WMAP");
4202             }
4203             param_write_hex(pb, "CodecPrivateData", track->par->extradata,
4204                             track->par->extradata_size);
4205             param_write_int(pb, "AudioTag", ff_codec_get_tag(ff_codec_wav_tags,
4206                                                              track->par->codec_id));
4207             param_write_int(pb, "Channels", track->par->channels);
4208             param_write_int(pb, "SamplingRate", track->par->sample_rate);
4209             param_write_int(pb, "BitsPerSample", 16);
4210             param_write_int(pb, "PacketSize", track->par->block_align ?
4211                                               track->par->block_align : 4);
4212         }
4213         avio_printf(pb, "</%s>\n", type);
4214     }
4215     avio_printf(pb, "</switch>\n");
4216     avio_printf(pb, "</body>\n");
4217     avio_printf(pb, "</smil>\n");
4218
4219     return update_size(pb, pos);
4220 }
4221
4222 static int mov_write_mfhd_tag(AVIOContext *pb, MOVMuxContext *mov)
4223 {
4224     avio_wb32(pb, 16);
4225     ffio_wfourcc(pb, "mfhd");
4226     avio_wb32(pb, 0);
4227     avio_wb32(pb, mov->fragments);
4228     return 0;
4229 }
4230
4231 static uint32_t get_sample_flags(MOVTrack *track, MOVIentry *entry)
4232 {
4233     return entry->flags & MOV_SYNC_SAMPLE ? MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO :
4234            (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC);
4235 }
4236
4237 static int mov_write_tfhd_tag(AVIOContext *pb, MOVMuxContext *mov,
4238                               MOVTrack *track, int64_t moof_offset)
4239 {
4240     int64_t pos = avio_tell(pb);
4241     uint32_t flags = MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
4242                      MOV_TFHD_BASE_DATA_OFFSET;
4243     if (!track->entry) {
4244         flags |= MOV_TFHD_DURATION_IS_EMPTY;
4245     } else {
4246         flags |= MOV_TFHD_DEFAULT_FLAGS;
4247     }
4248     if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET)
4249         flags &= ~MOV_TFHD_BASE_DATA_OFFSET;
4250     if (mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) {
4251         flags &= ~MOV_TFHD_BASE_DATA_OFFSET;
4252         flags |= MOV_TFHD_DEFAULT_BASE_IS_MOOF;
4253     }
4254     /* CMAF requires all values to be explicit in tfhd atoms */
4255     if (mov->flags & FF_MOV_FLAG_CMAF)
4256         flags |= MOV_TFHD_STSD_ID;
4257
4258     /* Don't set a default sample size, the silverlight player refuses
4259      * to play files with that set. Don't set a default sample duration,
4260      * WMP freaks out if it is set. Don't set a base data offset, PIFF
4261      * file format says it MUST NOT be set. */
4262     if (track->mode == MODE_ISM)
4263         flags &= ~(MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
4264                    MOV_TFHD_BASE_DATA_OFFSET | MOV_TFHD_STSD_ID);
4265
4266     avio_wb32(pb, 0); /* size placeholder */
4267     ffio_wfourcc(pb, "tfhd");
4268     avio_w8(pb, 0); /* version */
4269     avio_wb24(pb, flags);
4270
4271     avio_wb32(pb, track->track_id); /* track-id */
4272     if (flags & MOV_TFHD_BASE_DATA_OFFSET)
4273         avio_wb64(pb, moof_offset);
4274     if (flags & MOV_TFHD_STSD_ID) {
4275         avio_wb32(pb, 1);
4276     }
4277     if (flags & MOV_TFHD_DEFAULT_DURATION) {
4278         track->default_duration = get_cluster_duration(track, 0);
4279         avio_wb32(pb, track->default_duration);
4280     }
4281     if (flags & MOV_TFHD_DEFAULT_SIZE) {
4282         track->default_size = track->entry ? track->cluster[0].size : 1;
4283         avio_wb32(pb, track->default_size);
4284     } else
4285         track->default_size = -1;
4286
4287     if (flags & MOV_TFHD_DEFAULT_FLAGS) {
4288         /* Set the default flags based on the second sample, if available.
4289          * If the first sample is different, that can be signaled via a separate field. */
4290         if (track->entry > 1)
4291             track->default_sample_flags = get_sample_flags(track, &track->cluster[1]);
4292         else
4293             track->default_sample_flags =
4294                 track->par->codec_type == AVMEDIA_TYPE_VIDEO ?
4295                 (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC) :
4296                 MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO;
4297         avio_wb32(pb, track->default_sample_flags);
4298     }
4299
4300     return update_size(pb, pos);
4301 }
4302
4303 static int mov_write_trun_tag(AVIOContext *pb, MOVMuxContext *mov,
4304                               MOVTrack *track, int moof_size,
4305                               int first, int end)
4306 {
4307     int64_t pos = avio_tell(pb);
4308     uint32_t flags = MOV_TRUN_DATA_OFFSET;
4309     int i;
4310
4311     for (i = first; i < end; i++) {
4312         if (get_cluster_duration(track, i) != track->default_duration)
4313             flags |= MOV_TRUN_SAMPLE_DURATION;
4314         if (track->cluster[i].size != track->default_size)
4315             flags |= MOV_TRUN_SAMPLE_SIZE;
4316         if (i > first && get_sample_flags(track, &track->cluster[i]) != track->default_sample_flags)
4317             flags |= MOV_TRUN_SAMPLE_FLAGS;
4318     }
4319     if (!(flags & MOV_TRUN_SAMPLE_FLAGS) && track->entry > 0 &&
4320          get_sample_flags(track, &track->cluster[0]) != track->default_sample_flags)
4321         flags |= MOV_TRUN_FIRST_SAMPLE_FLAGS;
4322     if (track->flags & MOV_TRACK_CTTS)
4323         flags |= MOV_TRUN_SAMPLE_CTS;
4324
4325     avio_wb32(pb, 0); /* size placeholder */
4326     ffio_wfourcc(pb, "trun");
4327     if (mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS)
4328         avio_w8(pb, 1); /* version */
4329     else
4330         avio_w8(pb, 0); /* version */
4331     avio_wb24(pb, flags);
4332
4333     avio_wb32(pb, end - first); /* sample count */
4334     if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET &&
4335         !(mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) &&
4336         !mov->first_trun)
4337         avio_wb32(pb, 0); /* Later tracks follow immediately after the previous one */
4338     else
4339         avio_wb32(pb, moof_size + 8 + track->data_offset +
4340                       track->cluster[first].pos); /* data offset */
4341     if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS)
4342         avio_wb32(pb, get_sample_flags(track, &track->cluster[first]));
4343
4344     for (i = first; i < end; i++) {
4345         if (flags & MOV_TRUN_SAMPLE_DURATION)
4346             avio_wb32(pb, get_cluster_duration(track, i));
4347         if (flags & MOV_TRUN_SAMPLE_SIZE)
4348             avio_wb32(pb, track->cluster[i].size);
4349         if (flags & MOV_TRUN_SAMPLE_FLAGS)
4350             avio_wb32(pb, get_sample_flags(track, &track->cluster[i]));
4351         if (flags & MOV_TRUN_SAMPLE_CTS)
4352             avio_wb32(pb, track->cluster[i].cts);
4353     }
4354
4355     mov->first_trun = 0;
4356     return update_size(pb, pos);
4357 }
4358
4359 static int mov_write_tfxd_tag(AVIOContext *pb, MOVTrack *track)
4360 {
4361     int64_t pos = avio_tell(pb);
4362     static const uint8_t uuid[] = {
4363         0x6d, 0x1d, 0x9b, 0x05, 0x42, 0xd5, 0x44, 0xe6,
4364         0x80, 0xe2, 0x14, 0x1d, 0xaf, 0xf7, 0x57, 0xb2
4365     };
4366
4367     avio_wb32(pb, 0); /* size placeholder */
4368     ffio_wfourcc(pb, "uuid");
4369     avio_write(pb, uuid, sizeof(uuid));
4370     avio_w8(pb, 1);
4371     avio_wb24(pb, 0);
4372     avio_wb64(pb, track->start_dts + track->frag_start +
4373                   track->cluster[0].cts);
4374     avio_wb64(pb, track->end_pts -
4375                   (track->cluster[0].dts + track->cluster[0].cts));
4376
4377     return update_size(pb, pos);
4378 }
4379
4380 static int mov_write_tfrf_tag(AVIOContext *pb, MOVMuxContext *mov,
4381                               MOVTrack *track, int entry)
4382 {
4383     int n = track->nb_frag_info - 1 - entry, i;
4384     int size = 8 + 16 + 4 + 1 + 16*n;
4385     static const uint8_t uuid[] = {
4386         0xd4, 0x80, 0x7e, 0xf2, 0xca, 0x39, 0x46, 0x95,
4387         0x8e, 0x54, 0x26, 0xcb, 0x9e, 0x46, 0xa7, 0x9f
4388     };
4389
4390     if (entry < 0)
4391         return 0;
4392
4393     avio_seek(pb, track->frag_info[entry].tfrf_offset, SEEK_SET);
4394     avio_wb32(pb, size);
4395     ffio_wfourcc(pb, "uuid");
4396     avio_write(pb, uuid, sizeof(uuid));
4397     avio_w8(pb, 1);
4398     avio_wb24(pb, 0);
4399     avio_w8(pb, n);
4400     for (i = 0; i < n; i++) {
4401         int index = entry + 1 + i;
4402         avio_wb64(pb, track->frag_info[index].time);
4403         avio_wb64(pb, track->frag_info[index].duration);
4404     }
4405     if (n < mov->ism_lookahead) {
4406         int free_size = 16 * (mov->ism_lookahead - n);
4407         avio_wb32(pb, free_size);
4408         ffio_wfourcc(pb, "free");
4409         ffio_fill(pb, 0, free_size - 8);
4410     }
4411
4412     return 0;
4413 }
4414
4415 static int mov_write_tfrf_tags(AVIOContext *pb, MOVMuxContext *mov,
4416                                MOVTrack *track)
4417 {
4418     int64_t pos = avio_tell(pb);
4419     int i;
4420     for (i = 0; i < mov->ism_lookahead; i++) {
4421         /* Update the tfrf tag for the last ism_lookahead fragments,
4422          * nb_frag_info - 1 is the next fragment to be written. */
4423         mov_write_tfrf_tag(pb, mov, track, track->nb_frag_info - 2 - i);
4424     }
4425     avio_seek(pb, pos, SEEK_SET);
4426     return 0;
4427 }
4428
4429 static int mov_add_tfra_entries(AVIOContext *pb, MOVMuxContext *mov, int tracks,
4430                                 int size)
4431 {
4432     int i;
4433     for (i = 0; i < mov->nb_streams; i++) {
4434         MOVTrack *track = &mov->tracks[i];
4435         MOVFragmentInfo *info;
4436         if ((tracks >= 0 && i != tracks) || !track->entry)
4437             continue;
4438         track->nb_frag_info++;
4439         if (track->nb_frag_info >= track->frag_info_capacity) {
4440             unsigned new_capacity = track->nb_frag_info + MOV_FRAG_INFO_ALLOC_INCREMENT;
4441             if (av_reallocp_array(&track->frag_info,
4442                                   new_capacity,
4443                                   sizeof(*track->frag_info)))
4444                 return AVERROR(ENOMEM);
4445             track->frag_info_capacity = new_capacity;
4446         }
4447         info = &track->frag_info[track->nb_frag_info - 1];
4448         info->offset   = avio_tell(pb);
4449         info->size     = size;
4450         // Try to recreate the original pts for the first packet
4451         // from the fields we have stored
4452         info->time     = track->start_dts + track->frag_start +
4453                          track->cluster[0].cts;
4454         info->duration = track->end_pts -
4455                          (track->cluster[0].dts + track->cluster[0].cts);
4456         // If the pts is less than zero, we will have trimmed
4457         // away parts of the media track using an edit list,
4458         // and the corresponding start presentation time is zero.
4459         if (info->time < 0) {
4460             info->duration += info->time;
4461             info->time = 0;
4462         }
4463         info->tfrf_offset = 0;
4464         mov_write_tfrf_tags(pb, mov, track);
4465     }
4466     return 0;
4467 }
4468
4469 static void mov_prune_frag_info(MOVMuxContext *mov, int tracks, int max)
4470 {
4471     int i;
4472     for (i = 0; i < mov->nb_streams; i++) {
4473         MOVTrack *track = &mov->tracks[i];
4474         if ((tracks >= 0 && i != tracks) || !track->entry)
4475             continue;
4476         if (track->nb_frag_info > max) {
4477             memmove(track->frag_info, track->frag_info + (track->nb_frag_info - max), max * sizeof(*track->frag_info));
4478             track->nb_frag_info = max;
4479         }
4480     }
4481 }
4482
4483 static int mov_write_tfdt_tag(AVIOContext *pb, MOVTrack *track)
4484 {
4485     int64_t pos = avio_tell(pb);
4486
4487     avio_wb32(pb, 0); /* size */
4488     ffio_wfourcc(pb, "tfdt");
4489     avio_w8(pb, 1); /* version */
4490     avio_wb24(pb, 0);
4491     avio_wb64(pb, track->frag_start);
4492     return update_size(pb, pos);
4493 }
4494
4495 static int mov_write_traf_tag(AVIOContext *pb, MOVMuxContext *mov,
4496                               MOVTrack *track, int64_t moof_offset,
4497                               int moof_size)
4498 {
4499     int64_t pos = avio_tell(pb);
4500     int i, start = 0;
4501     avio_wb32(pb, 0); /* size placeholder */
4502     ffio_wfourcc(pb, "traf");
4503
4504     mov_write_tfhd_tag(pb, mov, track, moof_offset);
4505     if (mov->mode != MODE_ISM)
4506         mov_write_tfdt_tag(pb, track);
4507     for (i = 1; i < track->entry; i++) {
4508         if (track->cluster[i].pos != track->cluster[i - 1].pos + track->cluster[i - 1].size) {
4509             mov_write_trun_tag(pb, mov, track, moof_size, start, i);
4510             start = i;
4511         }
4512     }
4513     mov_write_trun_tag(pb, mov, track, moof_size, start, track->entry);
4514     if (mov->mode == MODE_ISM) {
4515         mov_write_tfxd_tag(pb, track);
4516
4517         if (mov->ism_lookahead) {
4518             int i, size = 16 + 4 + 1 + 16 * mov->ism_lookahead;
4519
4520             if (track->nb_frag_info > 0) {
4521                 MOVFragmentInfo *info = &track->frag_info[track->nb_frag_info - 1];
4522                 if (!info->tfrf_offset)
4523                     info->tfrf_offset = avio_tell(pb);
4524             }
4525             avio_wb32(pb, 8 + size);
4526             ffio_wfourcc(pb, "free");
4527             for (i = 0; i < size; i++)
4528                 avio_w8(pb, 0);
4529         }
4530     }
4531
4532     return update_size(pb, pos);
4533 }
4534
4535 static int mov_write_moof_tag_internal(AVIOContext *pb, MOVMuxContext *mov,
4536                                        int tracks, int moof_size)
4537 {
4538     int64_t pos = avio_tell(pb);
4539     int i;
4540
4541     avio_wb32(pb, 0); /* size placeholder */
4542     ffio_wfourcc(pb, "moof");
4543     mov->first_trun = 1;
4544
4545     mov_write_mfhd_tag(pb, mov);
4546     for (i = 0; i < mov->nb_streams; i++) {
4547         MOVTrack *track = &mov->tracks[i];
4548         if (tracks >= 0 && i != tracks)
4549             continue;
4550         if (!track->entry)
4551             continue;
4552         mov_write_traf_tag(pb, mov, track, pos, moof_size);
4553     }
4554
4555     return update_size(pb, pos);
4556 }
4557
4558 static int mov_write_sidx_tag(AVIOContext *pb,
4559                               MOVTrack *track, int ref_size, int total_sidx_size)
4560 {
4561     int64_t pos = avio_tell(pb), offset_pos, end_pos;
4562     int64_t presentation_time, duration, offset;
4563     unsigned starts_with_SAP;
4564     int i, entries;
4565
4566     if (track->entry) {
4567         entries = 1;
4568         presentation_time = track->start_dts + track->frag_start +
4569                             track->cluster[0].cts;
4570         duration = track->end_pts -
4571                    (track->cluster[0].dts + track->cluster[0].cts);
4572         starts_with_SAP = track->cluster[0].flags & MOV_SYNC_SAMPLE;
4573
4574         // pts<0 should be cut away using edts
4575         if (presentation_time < 0) {
4576             duration += presentation_time;
4577             presentation_time = 0;
4578         }
4579     } else {
4580         entries = track->nb_frag_info;
4581         if (entries <= 0)
4582             return 0;
4583         presentation_time = track->frag_info[0].time;
4584     }
4585
4586     avio_wb32(pb, 0); /* size */
4587     ffio_wfourcc(pb, "sidx");
4588     avio_w8(pb, 1); /* version */
4589     avio_wb24(pb, 0);
4590     avio_wb32(pb, track->track_id); /* reference_ID */
4591     avio_wb32(pb, track->timescale); /* timescale */
4592     avio_wb64(pb, presentation_time); /* earliest_presentation_time */
4593     offset_pos = avio_tell(pb);
4594     avio_wb64(pb, 0); /* first_offset (offset to referenced moof) */
4595     avio_wb16(pb, 0); /* reserved */
4596
4597     avio_wb16(pb, entries); /* reference_count */
4598     for (i = 0; i < entries; i++) {
4599         if (!track->entry) {
4600             if (i > 1 && track->frag_info[i].offset != track->frag_info[i - 1].offset + track->frag_info[i - 1].size) {
4601                av_log(NULL, AV_LOG_ERROR, "Non-consecutive fragments, writing incorrect sidx\n");
4602             }
4603             duration = track->frag_info[i].duration;
4604             ref_size = track->frag_info[i].size;
4605             starts_with_SAP = 1;
4606         }
4607         avio_wb32(pb, (0 << 31) | (ref_size & 0x7fffffff)); /* reference_type (0 = media) | referenced_size */
4608         avio_wb32(pb, duration); /* subsegment_duration */
4609         avio_wb32(pb, (starts_with_SAP << 31) | (0 << 28) | 0); /* starts_with_SAP | SAP_type | SAP_delta_time */
4610     }
4611
4612     end_pos = avio_tell(pb);
4613     offset = pos + total_sidx_size - end_pos;
4614     avio_seek(pb, offset_pos, SEEK_SET);
4615     avio_wb64(pb, offset);
4616     avio_seek(pb, end_pos, SEEK_SET);
4617     return update_size(pb, pos);
4618 }
4619
4620 static int mov_write_sidx_tags(AVIOContext *pb, MOVMuxContext *mov,
4621                                int tracks, int ref_size)
4622 {
4623     int i, round, ret;
4624     AVIOContext *avio_buf;
4625     int total_size = 0;
4626     for (round = 0; round < 2; round++) {
4627         // First run one round to calculate the total size of all
4628         // sidx atoms.
4629         // This would be much simpler if we'd only write one sidx
4630         // atom, for the first track in the moof.
4631         if (round == 0) {
4632             if ((ret = ffio_open_null_buf(&avio_buf)) < 0)
4633                 return ret;
4634         } else {
4635             avio_buf = pb;
4636         }
4637         for (i = 0; i < mov->nb_streams; i++) {
4638             MOVTrack *track = &mov->tracks[i];
4639             if (tracks >= 0 && i != tracks)
4640                 continue;
4641             // When writing a sidx for the full file, entry is 0, but
4642             // we want to include all tracks. ref_size is 0 in this case,
4643             // since we read it from frag_info instead.
4644             if (!track->entry && ref_size > 0)
4645                 continue;
4646             total_size -= mov_write_sidx_tag(avio_buf, track, ref_size,
4647                                              total_size);
4648         }
4649         if (round == 0)
4650             total_size = ffio_close_null_buf(avio_buf);
4651     }
4652     return 0;
4653 }
4654
4655 static int mov_write_prft_tag(AVIOContext *pb, MOVMuxContext *mov, int tracks)
4656 {
4657     int64_t pos = avio_tell(pb), pts_us, ntp_ts;
4658     MOVTrack *first_track;
4659     int flags = 24;
4660
4661     /* PRFT should be associated with at most one track. So, choosing only the
4662      * first track. */
4663     if (tracks > 0)
4664         return 0;
4665     first_track = &(mov->tracks[0]);
4666
4667     if (!first_track->entry) {
4668         av_log(mov->fc, AV_LOG_WARNING, "Unable to write PRFT, no entries in the track\n");
4669         return 0;
4670     }
4671
4672     if (first_track->cluster[0].pts == AV_NOPTS_VALUE) {
4673         av_log(mov->fc, AV_LOG_WARNING, "Unable to write PRFT, first PTS is invalid\n");
4674         return 0;
4675     }
4676
4677     if (mov->write_prft == MOV_PRFT_SRC_WALLCLOCK) {
4678         if (first_track->cluster[0].prft.wallclock) {
4679             /* Round the NTP time to whole milliseconds. */
4680             ntp_ts = ff_get_formatted_ntp_time((first_track->cluster[0].prft.wallclock / 1000) * 1000 +
4681                                                NTP_OFFSET_US);
4682             flags = first_track->cluster[0].prft.flags;
4683         } else
4684             ntp_ts = ff_get_formatted_ntp_time(ff_ntp_time());
4685     } else if (mov->write_prft == MOV_PRFT_SRC_PTS) {
4686         pts_us = av_rescale_q(first_track->cluster[0].pts,
4687                               first_track->st->time_base, AV_TIME_BASE_Q);
4688         ntp_ts = ff_get_formatted_ntp_time(pts_us + NTP_OFFSET_US);
4689     } else {
4690         av_log(mov->fc, AV_LOG_WARNING, "Unsupported PRFT box configuration: %d\n",
4691                mov->write_prft);
4692         return 0;
4693     }
4694
4695     avio_wb32(pb, 0);                           // Size place holder
4696     ffio_wfourcc(pb, "prft");                   // Type
4697     avio_w8(pb, 1);                             // Version
4698     avio_wb24(pb, flags);                       // Flags
4699     avio_wb32(pb, first_track->track_id);       // reference track ID
4700     avio_wb64(pb, ntp_ts);                      // NTP time stamp
4701     avio_wb64(pb, first_track->cluster[0].pts); //media time
4702     return update_size(pb, pos);
4703 }
4704
4705 static int mov_write_moof_tag(AVIOContext *pb, MOVMuxContext *mov, int tracks,
4706                               int64_t mdat_size)
4707 {
4708     AVIOContext *avio_buf;
4709     int ret, moof_size;
4710
4711     if ((ret = ffio_open_null_buf(&avio_buf)) < 0)
4712         return ret;
4713     mov_write_moof_tag_internal(avio_buf, mov, tracks, 0);
4714     moof_size = ffio_close_null_buf(avio_buf);
4715
4716     if (mov->flags & FF_MOV_FLAG_DASH &&
4717         !(mov->flags & (FF_MOV_FLAG_GLOBAL_SIDX | FF_MOV_FLAG_SKIP_SIDX)))
4718         mov_write_sidx_tags(pb, mov, tracks, moof_size + 8 + mdat_size);
4719
4720     if (mov->write_prft > MOV_PRFT_NONE && mov->write_prft < MOV_PRFT_NB)
4721         mov_write_prft_tag(pb, mov, tracks);
4722
4723     if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX ||
4724         !(mov->flags & FF_MOV_FLAG_SKIP_TRAILER) ||
4725         mov->ism_lookahead) {
4726         if ((ret = mov_add_tfra_entries(pb, mov, tracks, moof_size + 8 + mdat_size)) < 0)
4727             return ret;
4728         if (!(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) &&
4729             mov->flags & FF_MOV_FLAG_SKIP_TRAILER) {
4730             mov_prune_frag_info(mov, tracks, mov->ism_lookahead + 1);
4731         }
4732     }
4733
4734     return mov_write_moof_tag_internal(pb, mov, tracks, moof_size);
4735 }
4736
4737 static int mov_write_tfra_tag(AVIOContext *pb, MOVTrack *track)
4738 {
4739     int64_t pos = avio_tell(pb);
4740     int i;
4741
4742     avio_wb32(pb, 0); /* size placeholder */
4743     ffio_wfourcc(pb, "tfra");
4744     avio_w8(pb, 1); /* version */
4745     avio_wb24(pb, 0);
4746
4747     avio_wb32(pb, track->track_id);
4748     avio_wb32(pb, 0); /* length of traf/trun/sample num */
4749     avio_wb32(pb, track->nb_frag_info);
4750     for (i = 0; i < track->nb_frag_info; i++) {
4751         avio_wb64(pb, track->frag_info[i].time);
4752         avio_wb64(pb, track->frag_info[i].offset + track->data_offset);
4753         avio_w8(pb, 1); /* traf number */
4754         avio_w8(pb, 1); /* trun number */
4755         avio_w8(pb, 1); /* sample number */
4756     }
4757
4758     return update_size(pb, pos);
4759 }
4760
4761 static int mov_write_mfra_tag(AVIOContext *pb, MOVMuxContext *mov)
4762 {
4763     int64_t pos = avio_tell(pb);
4764     int i;
4765
4766     avio_wb32(pb, 0); /* size placeholder */
4767     ffio_wfourcc(pb, "mfra");
4768     /* An empty mfra atom is enough to indicate to the publishing point that
4769      * the stream has ended. */
4770     if (mov->flags & FF_MOV_FLAG_ISML)
4771         return update_size(pb, pos);
4772
4773     for (i = 0; i < mov->nb_streams; i++) {
4774         MOVTrack *track = &mov->tracks[i];
4775         if (track->nb_frag_info)
4776             mov_write_tfra_tag(pb, track);
4777     }
4778
4779     avio_wb32(pb, 16);
4780     ffio_wfourcc(pb, "mfro");
4781     avio_wb32(pb, 0); /* version + flags */
4782     avio_wb32(pb, avio_tell(pb) + 4 - pos);
4783
4784     return update_size(pb, pos);
4785 }
4786
4787 static int mov_write_mdat_tag(AVIOContext *pb, MOVMuxContext *mov)
4788 {
4789     avio_wb32(pb, 8);    // placeholder for extended size field (64 bit)
4790     ffio_wfourcc(pb, mov->mode == MODE_MOV ? "wide" : "free");
4791
4792     mov->mdat_pos = avio_tell(pb);
4793     avio_wb32(pb, 0); /* size placeholder*/
4794     ffio_wfourcc(pb, "mdat");
4795     return 0;
4796 }
4797
4798 static void mov_write_ftyp_tag_internal(AVIOContext *pb, AVFormatContext *s,
4799                                         int has_h264, int has_video, int write_minor)
4800 {
4801     MOVMuxContext *mov = s->priv_data;
4802     int minor = 0x200;
4803
4804     if (mov->major_brand && strlen(mov->major_brand) >= 4)
4805         ffio_wfourcc(pb, mov->major_brand);
4806     else if (mov->mode == MODE_3GP) {
4807         ffio_wfourcc(pb, has_h264 ? "3gp6"  : "3gp4");
4808         minor =     has_h264 ?   0x100 :   0x200;
4809     } else if (mov->mode & MODE_3G2) {
4810         ffio_wfourcc(pb, has_h264 ? "3g2b"  : "3g2a");
4811         minor =     has_h264 ? 0x20000 : 0x10000;
4812     } else if (mov->mode == MODE_PSP)
4813         ffio_wfourcc(pb, "MSNV");
4814     else if (mov->mode == MODE_MP4 && mov->flags & FF_MOV_FLAG_FRAGMENT &&
4815                                       mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS)
4816         ffio_wfourcc(pb, "iso6"); // Required when using signed CTS offsets in trun boxes
4817     else if (mov->mode == MODE_MP4 && mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)
4818         ffio_wfourcc(pb, "iso5"); // Required when using default-base-is-moof
4819     else if (mov->mode == MODE_MP4 && mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS)
4820         ffio_wfourcc(pb, "iso4");
4821     else if (mov->mode == MODE_MP4)
4822         ffio_wfourcc(pb, "isom");
4823     else if (mov->mode == MODE_IPOD)
4824         ffio_wfourcc(pb, has_video ? "M4V ":"M4A ");
4825     else if (mov->mode == MODE_ISM)
4826         ffio_wfourcc(pb, "isml");
4827     else if (mov->mode == MODE_F4V)
4828         ffio_wfourcc(pb, "f4v ");
4829     else
4830         ffio_wfourcc(pb, "qt  ");
4831
4832     if (write_minor)
4833         avio_wb32(pb, minor);
4834 }
4835
4836 static int mov_write_ftyp_tag(AVIOContext *pb, AVFormatContext *s)
4837 {
4838     MOVMuxContext *mov = s->priv_data;
4839     int64_t pos = avio_tell(pb);
4840     int has_h264 = 0, has_video = 0;
4841     int i;
4842
4843     for (i = 0; i < s->nb_streams; i++) {
4844         AVStream *st = s->streams[i];
4845         if (is_cover_image(st))
4846             continue;
4847         if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
4848             has_video = 1;
4849         if (st->codecpar->codec_id == AV_CODEC_ID_H264)
4850             has_h264 = 1;
4851     }
4852
4853     avio_wb32(pb, 0); /* size */
4854     ffio_wfourcc(pb, "ftyp");
4855
4856     // Write major brand
4857     mov_write_ftyp_tag_internal(pb, s, has_h264, has_video, 1);
4858     // Write the major brand as the first compatible brand as well
4859     mov_write_ftyp_tag_internal(pb, s, has_h264, has_video, 0);
4860
4861     // Write compatible brands, ensuring that we don't write the major brand as a
4862     // compatible brand a second time.
4863     if (mov->mode == MODE_ISM) {
4864         ffio_wfourcc(pb, "piff");
4865     } else if (mov->mode != MODE_MOV) {
4866         // We add tfdt atoms when fragmenting, signal this with the iso6 compatible
4867         // brand, if not already the major brand. This is compatible with users that
4868         // don't understand tfdt.
4869         if (mov->mode == MODE_MP4) {
4870             if (mov->flags & FF_MOV_FLAG_CMAF)
4871                 ffio_wfourcc(pb, "cmfc");
4872             if (mov->flags & FF_MOV_FLAG_FRAGMENT && !(mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS))
4873                 ffio_wfourcc(pb, "iso6");
4874         } else {
4875             if (mov->flags & FF_MOV_FLAG_FRAGMENT)
4876                 ffio_wfourcc(pb, "iso6");
4877             if (mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)
4878                 ffio_wfourcc(pb, "iso5");
4879             else if (mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS)
4880                 ffio_wfourcc(pb, "iso4");
4881         }
4882         // Brands prior to iso5 can't be signaled when using default-base-is-moof
4883         if (!(mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)) {
4884             // write isom for mp4 only if it it's not the major brand already.
4885             if (mov->mode != MODE_MP4 || mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS)
4886                 ffio_wfourcc(pb, "isom");
4887             ffio_wfourcc(pb, "iso2");
4888             if (has_h264)
4889                 ffio_wfourcc(pb, "avc1");
4890         }
4891     }
4892
4893     if (mov->mode == MODE_MP4)
4894         ffio_wfourcc(pb, "mp41");
4895
4896     if (mov->flags & FF_MOV_FLAG_DASH && mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
4897         ffio_wfourcc(pb, "dash");
4898
4899     return update_size(pb, pos);
4900 }
4901
4902 static int mov_write_uuidprof_tag(AVIOContext *pb, AVFormatContext *s)
4903 {
4904     AVStream       *video_st    = s->streams[0];
4905     AVCodecParameters *video_par = s->streams[0]->codecpar;
4906     AVCodecParameters *audio_par = s->streams[1]->codecpar;
4907     int audio_rate = audio_par->sample_rate;
4908     int64_t frame_rate = video_st->avg_frame_rate.den ?
4909                         (video_st->avg_frame_rate.num * 0x10000LL) / video_st->avg_frame_rate.den :
4910                         0;
4911     int audio_kbitrate = audio_par->bit_rate / 1000;
4912     int video_kbitrate = FFMIN(video_par->bit_rate / 1000, 800 - audio_kbitrate);
4913
4914     if (frame_rate < 0 || frame_rate > INT32_MAX) {
4915         av_log(s, AV_LOG_ERROR, "Frame rate %f outside supported range\n", frame_rate / (double)0x10000);
4916         return AVERROR(EINVAL);
4917     }
4918
4919     avio_wb32(pb, 0x94); /* size */
4920     ffio_wfourcc(pb, "uuid");
4921     ffio_wfourcc(pb, "PROF");
4922
4923     avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
4924     avio_wb32(pb, 0xbb88695c);
4925     avio_wb32(pb, 0xfac9c740);
4926
4927     avio_wb32(pb, 0x0);  /* ? */
4928     avio_wb32(pb, 0x3);  /* 3 sections ? */
4929
4930     avio_wb32(pb, 0x14); /* size */
4931     ffio_wfourcc(pb, "FPRF");
4932     avio_wb32(pb, 0x0);  /* ? */
4933     avio_wb32(pb, 0x0);  /* ? */
4934     avio_wb32(pb, 0x0);  /* ? */
4935
4936     avio_wb32(pb, 0x2c);  /* size */
4937     ffio_wfourcc(pb, "APRF"); /* audio */
4938     avio_wb32(pb, 0x0);
4939     avio_wb32(pb, 0x2);   /* TrackID */
4940     ffio_wfourcc(pb, "mp4a");
4941     avio_wb32(pb, 0x20f);
4942     avio_wb32(pb, 0x0);
4943     avio_wb32(pb, audio_kbitrate);
4944     avio_wb32(pb, audio_kbitrate);
4945     avio_wb32(pb, audio_rate);
4946     avio_wb32(pb, audio_par->channels);
4947
4948     avio_wb32(pb, 0x34);  /* size */
4949     ffio_wfourcc(pb, "VPRF");   /* video */
4950     avio_wb32(pb, 0x0);
4951     avio_wb32(pb, 0x1);    /* TrackID */
4952     if (video_par->codec_id == AV_CODEC_ID_H264) {
4953         ffio_wfourcc(pb, "avc1");
4954         avio_wb16(pb, 0x014D);
4955         avio_wb16(pb, 0x0015);
4956     } else {
4957         ffio_wfourcc(pb, "mp4v");
4958         avio_wb16(pb, 0x0000);
4959         avio_wb16(pb, 0x0103);
4960     }
4961     avio_wb32(pb, 0x0);
4962     avio_wb32(pb, video_kbitrate);
4963     avio_wb32(pb, video_kbitrate);
4964     avio_wb32(pb, frame_rate);
4965     avio_wb32(pb, frame_rate);
4966     avio_wb16(pb, video_par->width);
4967     avio_wb16(pb, video_par->height);
4968     avio_wb32(pb, 0x010001); /* ? */
4969
4970     return 0;
4971 }
4972
4973 static int mov_write_identification(AVIOContext *pb, AVFormatContext *s)
4974 {
4975     MOVMuxContext *mov = s->priv_data;
4976     int i;
4977
4978     mov_write_ftyp_tag(pb,s);
4979     if (mov->mode == MODE_PSP) {
4980         int video_streams_nb = 0, audio_streams_nb = 0, other_streams_nb = 0;
4981         for (i = 0; i < s->nb_streams; i++) {
4982             AVStream *st = s->streams[i];
4983             if (is_cover_image(st))
4984                 continue;
4985             if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
4986                 video_streams_nb++;
4987             else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
4988                 audio_streams_nb++;
4989             else
4990                 other_streams_nb++;
4991             }
4992
4993         if (video_streams_nb != 1 || audio_streams_nb != 1 || other_streams_nb) {
4994             av_log(s, AV_LOG_ERROR, "PSP mode need one video and one audio stream\n");
4995             return AVERROR(EINVAL);
4996         }
4997         return mov_write_uuidprof_tag(pb, s);
4998     }
4999     return 0;
5000 }
5001
5002 static int mov_parse_mpeg2_frame(AVPacket *pkt, uint32_t *flags)
5003 {
5004     uint32_t c = -1;
5005     int i, closed_gop = 0;
5006
5007     for (i = 0; i < pkt->size - 4; i++) {
5008         c = (c << 8) + pkt->data[i];
5009         if (c == 0x1b8) { // gop
5010             closed_gop = pkt->data[i + 4] >> 6 & 0x01;
5011         } else if (c == 0x100) { // pic
5012             int temp_ref = (pkt->data[i + 1] << 2) | (pkt->data[i + 2] >> 6);
5013             if (!temp_ref || closed_gop) // I picture is not reordered
5014                 *flags = MOV_SYNC_SAMPLE;
5015             else
5016                 *flags = MOV_PARTIAL_SYNC_SAMPLE;
5017             break;
5018         }
5019     }
5020     return 0;
5021 }
5022
5023 static void mov_parse_vc1_frame(AVPacket *pkt, MOVTrack *trk)
5024 {
5025     const uint8_t *start, *next, *end = pkt->data + pkt->size;
5026     int seq = 0, entry = 0;
5027     int key = pkt->flags & AV_PKT_FLAG_KEY;
5028     start = find_next_marker(pkt->data, end);
5029     for (next = start; next < end; start = next) {
5030         next = find_next_marker(start + 4, end);
5031         switch (AV_RB32(start)) {
5032         case VC1_CODE_SEQHDR:
5033             seq = 1;
5034             break;
5035         case VC1_CODE_ENTRYPOINT:
5036             entry = 1;
5037             break;
5038         case VC1_CODE_SLICE:
5039             trk->vc1_info.slices = 1;
5040             break;
5041         }
5042     }
5043     if (!trk->entry && trk->vc1_info.first_packet_seen)
5044         trk->vc1_info.first_frag_written = 1;
5045     if (!trk->entry && !trk->vc1_info.first_frag_written) {
5046         /* First packet in first fragment */
5047         trk->vc1_info.first_packet_seq   = seq;
5048         trk->vc1_info.first_packet_entry = entry;
5049         trk->vc1_info.first_packet_seen  = 1;
5050     } else if ((seq && !trk->vc1_info.packet_seq) ||
5051                (entry && !trk->vc1_info.packet_entry)) {
5052         int i;
5053         for (i = 0; i < trk->entry; i++)
5054             trk->cluster[i].flags &= ~MOV_SYNC_SAMPLE;
5055         trk->has_keyframes = 0;
5056         if (seq)
5057             trk->vc1_info.packet_seq = 1;
5058         if (entry)
5059             trk->vc1_info.packet_entry = 1;
5060         if (!trk->vc1_info.first_frag_written) {
5061             /* First fragment */
5062             if ((!seq   || trk->vc1_info.first_packet_seq) &&
5063                 (!entry || trk->vc1_info.first_packet_entry)) {
5064                 /* First packet had the same headers as this one, readd the
5065                  * sync sample flag. */
5066                 trk->cluster[0].flags |= MOV_SYNC_SAMPLE;
5067                 trk->has_keyframes = 1;
5068             }
5069         }
5070     }
5071     if (trk->vc1_info.packet_seq && trk->vc1_info.packet_entry)
5072         key = seq && entry;
5073     else if (trk->vc1_info.packet_seq)
5074         key = seq;
5075     else if (trk->vc1_info.packet_entry)
5076         key = entry;
5077     if (key) {
5078         trk->cluster[trk->entry].flags |= MOV_SYNC_SAMPLE;
5079         trk->has_keyframes++;
5080     }
5081 }
5082
5083 static void mov_parse_truehd_frame(AVPacket *pkt, MOVTrack *trk)
5084 {
5085     int length;
5086
5087     if (pkt->size < 8)
5088         return;
5089
5090     length = (AV_RB16(pkt->data) & 0xFFF) * 2;
5091     if (length < 8 || length > pkt->size)
5092         return;
5093
5094     if (AV_RB32(pkt->data + 4) == 0xF8726FBA) {
5095         trk->cluster[trk->entry].flags |= MOV_SYNC_SAMPLE;
5096         trk->has_keyframes++;
5097     }
5098
5099     return;
5100 }
5101
5102 static int mov_flush_fragment_interleaving(AVFormatContext *s, MOVTrack *track)
5103 {
5104     MOVMuxContext *mov = s->priv_data;
5105     int ret, buf_size;
5106     uint8_t *buf;
5107     int i, offset;
5108
5109     if (!track->mdat_buf)
5110         return 0;
5111     if (!mov->mdat_buf) {
5112         if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0)
5113             return ret;
5114     }
5115     buf_size = avio_get_dyn_buf(track->mdat_buf, &buf);
5116
5117     offset = avio_tell(mov->mdat_buf);
5118     avio_write(mov->mdat_buf, buf, buf_size);
5119     ffio_free_dyn_buf(&track->mdat_buf);
5120
5121     for (i = track->entries_flushed; i < track->entry; i++)
5122         track->cluster[i].pos += offset;
5123     track->entries_flushed = track->entry;
5124     return 0;
5125 }
5126
5127 static int mov_flush_fragment(AVFormatContext *s, int force)
5128 {
5129     MOVMuxContext *mov = s->priv_data;
5130     int i, first_track = -1;
5131     int64_t mdat_size = 0;
5132     int ret;
5133     int has_video = 0, starts_with_key = 0, first_video_track = 1;
5134
5135     if (!(mov->flags & FF_MOV_FLAG_FRAGMENT))
5136         return 0;
5137
5138     // Try to fill in the duration of the last packet in each stream
5139     // from queued packets in the interleave queues. If the flushing
5140     // of fragments was triggered automatically by an AVPacket, we
5141     // already have reliable info for the end of that track, but other
5142     // tracks may need to be filled in.
5143     for (i = 0; i < s->nb_streams; i++) {
5144         MOVTrack *track = &mov->tracks[i];
5145         if (!track->end_reliable) {
5146             AVPacket pkt;
5147             if (!ff_interleaved_peek(s, i, &pkt, 1)) {
5148                 if (track->dts_shift != AV_NOPTS_VALUE)
5149                     pkt.dts += track->dts_shift;
5150                 track->track_duration = pkt.dts - track->start_dts;
5151                 if (pkt.pts != AV_NOPTS_VALUE)
5152                     track->end_pts = pkt.pts;
5153                 else
5154                     track->end_pts = pkt.dts;
5155             }
5156         }
5157     }
5158
5159     for (i = 0; i < mov->nb_streams; i++) {
5160         MOVTrack *track = &mov->tracks[i];
5161         if (track->entry <= 1)
5162             continue;
5163         // Sample durations are calculated as the diff of dts values,
5164         // but for the last sample in a fragment, we don't know the dts
5165         // of the first sample in the next fragment, so we have to rely
5166         // on what was set as duration in the AVPacket. Not all callers
5167         // set this though, so we might want to replace it with an
5168         // estimate if it currently is zero.
5169         if (get_cluster_duration(track, track->entry - 1) != 0)
5170             continue;
5171         // Use the duration (i.e. dts diff) of the second last sample for
5172         // the last one. This is a wild guess (and fatal if it turns out
5173         // to be too long), but probably the best we can do - having a zero
5174         // duration is bad as well.
5175         track->track_duration += get_cluster_duration(track, track->entry - 2);
5176         track->end_pts        += get_cluster_duration(track, track->entry - 2);
5177         if (!mov->missing_duration_warned) {
5178             av_log(s, AV_LOG_WARNING,
5179                    "Estimating the duration of the last packet in a "
5180                    "fragment, consider setting the duration field in "
5181                    "AVPacket instead.\n");
5182             mov->missing_duration_warned = 1;
5183         }
5184     }
5185
5186     if (!mov->moov_written) {
5187         int64_t pos = avio_tell(s->pb);
5188         uint8_t *buf;
5189         int buf_size, moov_size;
5190
5191         for (i = 0; i < mov->nb_streams; i++)
5192             if (!mov->tracks[i].entry && !is_cover_image(mov->tracks[i].st))
5193                 break;
5194         /* Don't write the initial moov unless all tracks have data */
5195         if (i < mov->nb_streams && !force)
5196             return 0;
5197
5198         moov_size = get_moov_size(s);
5199         for (i = 0; i < mov->nb_streams; i++)
5200             mov->tracks[i].data_offset = pos + moov_size + 8;
5201
5202         avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_HEADER);
5203         if (mov->flags & FF_MOV_FLAG_DELAY_MOOV)
5204             mov_write_identification(s->pb, s);
5205         if ((ret = mov_write_moov_tag(s->pb, mov, s)) < 0)
5206             return ret;
5207
5208         if (mov->flags & FF_MOV_FLAG_DELAY_MOOV) {
5209             if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
5210                 mov->reserved_header_pos = avio_tell(s->pb);
5211             avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_FLUSH_POINT);
5212             mov->moov_written = 1;
5213             return 0;
5214         }
5215
5216         buf_size = avio_get_dyn_buf(mov->mdat_buf, &buf);
5217         avio_wb32(s->pb, buf_size + 8);
5218         ffio_wfourcc(s->pb, "mdat");
5219         avio_write(s->pb, buf, buf_size);
5220         ffio_free_dyn_buf(&mov->mdat_buf);
5221
5222         if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
5223             mov->reserved_header_pos = avio_tell(s->pb);
5224
5225         mov->moov_written = 1;
5226         mov->mdat_size = 0;
5227         for (i = 0; i < mov->nb_streams; i++) {
5228             if (mov->tracks[i].entry)
5229                 mov->tracks[i].frag_start += mov->tracks[i].start_dts +
5230                                              mov->tracks[i].track_duration -
5231                                              mov->tracks[i].cluster[0].dts;
5232             mov->tracks[i].entry = 0;
5233             mov->tracks[i].end_reliable = 0;
5234         }
5235         avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_FLUSH_POINT);
5236         return 0;
5237     }
5238
5239     if (mov->frag_interleave) {
5240         for (i = 0; i < mov->nb_streams; i++) {
5241             MOVTrack *track = &mov->tracks[i];
5242             int ret;
5243             if ((ret = mov_flush_fragment_interleaving(s, track)) < 0)
5244                 return ret;
5245         }
5246
5247         if (!mov->mdat_buf)
5248             return 0;
5249         mdat_size = avio_tell(mov->mdat_buf);
5250     }
5251
5252     for (i = 0; i < mov->nb_streams; i++) {
5253         MOVTrack *track = &mov->tracks[i];
5254         if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF || mov->frag_interleave)
5255             track->data_offset = 0;
5256         else
5257             track->data_offset = mdat_size;
5258         if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
5259             has_video = 1;
5260             if (first_video_track) {
5261                 if (track->entry)
5262                     starts_with_key = track->cluster[0].flags & MOV_SYNC_SAMPLE;
5263                 first_video_track = 0;
5264             }
5265         }
5266         if (!track->entry)
5267             continue;
5268         if (track->mdat_buf)
5269             mdat_size += avio_tell(track->mdat_buf);
5270         if (first_track < 0)
5271             first_track = i;
5272     }
5273
5274     if (!mdat_size)
5275         return 0;
5276
5277     avio_write_marker(s->pb,
5278                       av_rescale(mov->tracks[first_track].cluster[0].dts, AV_TIME_BASE, mov->tracks[first_track].timescale),
5279                       (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);
5280
5281     for (i = 0; i < mov->nb_streams; i++) {
5282         MOVTrack *track = &mov->tracks[i];
5283         int buf_size, write_moof = 1, moof_tracks = -1;
5284         uint8_t *buf;
5285         int64_t duration = 0;
5286
5287         if (track->entry)
5288             duration = track->start_dts + track->track_duration -
5289                        track->cluster[0].dts;
5290         if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF) {
5291             if (!track->mdat_buf)
5292                 continue;
5293             mdat_size = avio_tell(track->mdat_buf);
5294             moof_tracks = i;
5295         } else {
5296             write_moof = i == first_track;
5297         }
5298
5299         if (write_moof) {
5300             avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_FLUSH_POINT);
5301
5302             mov_write_moof_tag(s->pb, mov, moof_tracks, mdat_size);
5303             mov->fragments++;
5304
5305             avio_wb32(s->pb, mdat_size + 8);
5306             ffio_wfourcc(s->pb, "mdat");
5307         }
5308
5309         if (track->entry)
5310             track->frag_start += duration;
5311         track->entry = 0;
5312         track->entries_flushed = 0;
5313         track->end_reliable = 0;
5314         if (!mov->frag_interleave) {
5315             if (!track->mdat_buf)
5316                 continue;
5317             buf_size = avio_close_dyn_buf(track->mdat_buf, &buf);
5318             track->mdat_buf = NULL;
5319         } else {
5320             if (!mov->mdat_buf)
5321                 continue;
5322             buf_size = avio_close_dyn_buf(mov->mdat_buf, &buf);
5323             mov->mdat_buf = NULL;
5324         }
5325
5326         avio_write(s->pb, buf, buf_size);
5327         av_free(buf);
5328     }
5329
5330     mov->mdat_size = 0;
5331
5332     avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_FLUSH_POINT);
5333     return 0;
5334 }
5335
5336 static int mov_auto_flush_fragment(AVFormatContext *s, int force)
5337 {
5338     MOVMuxContext *mov = s->priv_data;
5339     int had_moov = mov->moov_written;
5340     int ret = mov_flush_fragment(s, force);
5341     if (ret < 0)
5342         return ret;
5343     // If using delay_moov, the first flush only wrote the moov,
5344     // not the actual moof+mdat pair, thus flush once again.
5345     if (!had_moov && mov->flags & FF_MOV_FLAG_DELAY_MOOV)
5346         ret = mov_flush_fragment(s, force);
5347     return ret;
5348 }
5349
5350 static int check_pkt(AVFormatContext *s, AVPacket *pkt)
5351 {
5352     MOVMuxContext *mov = s->priv_data;
5353     MOVTrack *trk = &mov->tracks[pkt->stream_index];
5354     int64_t ref;
5355     uint64_t duration;
5356
5357     if (trk->entry) {
5358         ref = trk->cluster[trk->entry - 1].dts;
5359     } else if (   trk->start_dts != AV_NOPTS_VALUE
5360                && !trk->frag_discont) {
5361         ref = trk->start_dts + trk->track_duration;
5362     } else
5363         ref = pkt->dts; // Skip tests for the first packet
5364
5365     if (trk->dts_shift != AV_NOPTS_VALUE) {
5366         /* With negative CTS offsets we have set an offset to the DTS,
5367          * reverse this for the check. */
5368         ref -= trk->dts_shift;
5369     }
5370
5371     duration = pkt->dts - ref;
5372     if (pkt->dts < ref || duration >= INT_MAX) {
5373         av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" / timestamp: %"PRId64" is out of range for mov/mp4 format\n",
5374             duration, pkt->dts
5375         );
5376
5377         pkt->dts = ref + 1;
5378         pkt->pts = AV_NOPTS_VALUE;
5379     }
5380
5381     if (pkt->duration < 0 || pkt->duration > INT_MAX) {
5382         av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" is invalid\n", pkt->duration);
5383         return AVERROR(EINVAL);
5384     }
5385     return 0;
5386 }
5387
5388 int ff_mov_write_packet(AVFormatContext *s, AVPacket *pkt)
5389 {
5390     MOVMuxContext *mov = s->priv_data;
5391     AVIOContext *pb = s->pb;
5392     MOVTrack *trk = &mov->tracks[pkt->stream_index];
5393     AVCodecParameters *par = trk->par;
5394     AVProducerReferenceTime *prft;
5395     unsigned int samples_in_chunk = 0;
5396     int size = pkt->size, ret = 0, offset = 0;
5397     int prft_size;
5398     uint8_t *reformatted_data = NULL;
5399
5400     ret = check_pkt(s, pkt);
5401     if (ret < 0)
5402         return ret;
5403
5404     if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
5405         int ret;
5406         if (mov->moov_written || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
5407             if (mov->frag_interleave && mov->fragments > 0) {
5408                 if (trk->entry - trk->entries_flushed >= mov->frag_interleave) {
5409                     if ((ret = mov_flush_fragment_interleaving(s, trk)) < 0)
5410                         return ret;
5411                 }
5412             }
5413
5414             if (!trk->mdat_buf) {
5415                 if ((ret = avio_open_dyn_buf(&trk->mdat_buf)) < 0)
5416                     return ret;
5417             }
5418             pb = trk->mdat_buf;
5419         } else {
5420             if (!mov->mdat_buf) {
5421                 if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0)
5422                     return ret;
5423             }
5424             pb = mov->mdat_buf;
5425         }
5426     }
5427
5428     if (par->codec_id == AV_CODEC_ID_AMR_NB) {
5429         /* We must find out how many AMR blocks there are in one packet */
5430         static const uint16_t packed_size[16] =
5431             {13, 14, 16, 18, 20, 21, 27, 32, 6, 0, 0, 0, 0, 0, 0, 1};
5432         int len = 0;
5433
5434         while (len < size && samples_in_chunk < 100) {
5435             len += packed_size[(pkt->data[len] >> 3) & 0x0F];
5436             samples_in_chunk++;
5437         }
5438         if (samples_in_chunk > 1) {
5439             av_log(s, AV_LOG_ERROR, "fatal error, input is not a single packet, implement a AVParser for it\n");
5440             return -1;
5441         }
5442     } else if (par->codec_id == AV_CODEC_ID_ADPCM_MS ||
5443                par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) {
5444         samples_in_chunk = trk->par->frame_size;
5445     } else if (trk->sample_size)
5446         samples_in_chunk = size / trk->sample_size;
5447     else
5448         samples_in_chunk = 1;
5449
5450     if (samples_in_chunk < 1) {
5451         av_log(s, AV_LOG_ERROR, "fatal error, input packet contains no samples\n");
5452         return AVERROR_PATCHWELCOME;
5453     }
5454
5455     /* copy extradata if it exists */
5456     if (trk->vos_len == 0 && par->extradata_size > 0 &&
5457         !TAG_IS_AVCI(trk->tag) &&
5458         (par->codec_id != AV_CODEC_ID_DNXHD)) {
5459         trk->vos_len  = par->extradata_size;
5460         trk->vos_data = av_malloc(trk->vos_len + AV_INPUT_BUFFER_PADDING_SIZE);
5461         if (!trk->vos_data) {
5462             ret = AVERROR(ENOMEM);
5463             goto err;
5464         }
5465         memcpy(trk->vos_data, par->extradata, trk->vos_len);
5466         memset(trk->vos_data + trk->vos_len, 0, AV_INPUT_BUFFER_PADDING_SIZE);
5467     }
5468
5469     if (par->codec_id == AV_CODEC_ID_AAC && pkt->size > 2 &&
5470         (AV_RB16(pkt->data) & 0xfff0) == 0xfff0) {
5471         if (!s->streams[pkt->stream_index]->nb_frames) {
5472             av_log(s, AV_LOG_ERROR, "Malformed AAC bitstream detected: "
5473                    "use the audio bitstream filter 'aac_adtstoasc' to fix it "
5474                    "('-bsf:a aac_adtstoasc' option with ffmpeg)\n");
5475             return -1;
5476         }
5477         av_log(s, AV_LOG_WARNING, "aac bitstream error\n");
5478     }
5479     if (par->codec_id == AV_CODEC_ID_H264 && trk->vos_len > 0 && *(uint8_t *)trk->vos_data != 1 && !TAG_IS_AVCI(trk->tag)) {
5480         /* from x264 or from bytestream H.264 */
5481         /* NAL reformatting needed */
5482         if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
5483             ret = ff_avc_parse_nal_units_buf(pkt->data, &reformatted_data,
5484                                              &size);
5485             if (ret < 0)
5486                 return ret;
5487             avio_write(pb, reformatted_data, size);
5488         } else {
5489             if (trk->cenc.aes_ctr) {
5490                 size = ff_mov_cenc_avc_parse_nal_units(&trk->cenc, pb, pkt->data, size);
5491                 if (size < 0) {
5492                     ret = size;
5493                     goto err;
5494                 }
5495             } else {
5496                 size = ff_avc_parse_nal_units(pb, pkt->data, pkt->size);
5497             }
5498         }
5499     } else if (par->codec_id == AV_CODEC_ID_HEVC && trk->vos_len > 6 &&
5500                (AV_RB24(trk->vos_data) == 1 || AV_RB32(trk->vos_data) == 1)) {
5501         /* extradata is Annex B, assume the bitstream is too and convert it */
5502         if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
5503             ret = ff_hevc_annexb2mp4_buf(pkt->data, &reformatted_data,
5504                                          &size, 0, NULL);
5505             if (ret < 0)
5506                 return ret;
5507             avio_write(pb, reformatted_data, size);
5508         } else {
5509             size = ff_hevc_annexb2mp4(pb, pkt->data, pkt->size, 0, NULL);
5510         }
5511     } else if (par->codec_id == AV_CODEC_ID_AV1) {
5512         if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
5513             ret = ff_av1_filter_obus_buf(pkt->data, &reformatted_data,
5514                                          &size, &offset);
5515             if (ret < 0)
5516                 return ret;
5517             avio_write(pb, reformatted_data, size);
5518         } else {
5519             size = ff_av1_filter_obus(pb, pkt->data, pkt->size);
5520         }
5521 #if CONFIG_AC3_PARSER
5522     } else if (par->codec_id == AV_CODEC_ID_EAC3) {
5523         size = handle_eac3(mov, pkt, trk);
5524         if (size < 0)
5525             return size;
5526         else if (!size)
5527             goto end;
5528         avio_write(pb, pkt->data, size);
5529 #endif
5530     } else {
5531         if (trk->cenc.aes_ctr) {
5532             if (par->codec_id == AV_CODEC_ID_H264 && par->extradata_size > 4) {
5533                 int nal_size_length = (par->extradata[4] & 0x3) + 1;
5534                 ret = ff_mov_cenc_avc_write_nal_units(s, &trk->cenc, nal_size_length, pb, pkt->data, size);
5535             } else {
5536                 ret = ff_mov_cenc_write_packet(&trk->cenc, pb, pkt->data, size);
5537             }
5538
5539             if (ret) {
5540                 goto err;
5541             }
5542         } else {
5543             avio_write(pb, pkt->data, size);
5544         }
5545     }
5546
5547     if ((par->codec_id == AV_CODEC_ID_DNXHD ||
5548          par->codec_id == AV_CODEC_ID_TRUEHD ||
5549          par->codec_id == AV_CODEC_ID_AC3) && !trk->vos_len) {
5550         /* copy frame to create needed atoms */
5551         trk->vos_len  = size;
5552         trk->vos_data = av_malloc(size + AV_INPUT_BUFFER_PADDING_SIZE);
5553         if (!trk->vos_data) {
5554             ret = AVERROR(ENOMEM);
5555             goto err;
5556         }
5557         memcpy(trk->vos_data, pkt->data, size);
5558         memset(trk->vos_data + size, 0, AV_INPUT_BUFFER_PADDING_SIZE);
5559     }
5560
5561     if (trk->entry >= trk->cluster_capacity) {
5562         unsigned new_capacity = trk->entry + MOV_INDEX_CLUSTER_SIZE;
5563         if (av_reallocp_array(&trk->cluster, new_capacity,
5564                               sizeof(*trk->cluster))) {
5565             ret = AVERROR(ENOMEM);
5566             goto err;
5567         }
5568         trk->cluster_capacity = new_capacity;
5569     }
5570
5571     trk->cluster[trk->entry].pos              = avio_tell(pb) - size;
5572     trk->cluster[trk->entry].samples_in_chunk = samples_in_chunk;
5573     trk->cluster[trk->entry].chunkNum         = 0;
5574     trk->cluster[trk->entry].size             = size;
5575     trk->cluster[trk->entry].entries          = samples_in_chunk;
5576     trk->cluster[trk->entry].dts              = pkt->dts;
5577     trk->cluster[trk->entry].pts              = pkt->pts;
5578     if (!trk->entry && trk->start_dts != AV_NOPTS_VALUE) {
5579         if (!trk->frag_discont) {
5580             /* First packet of a new fragment. We already wrote the duration
5581              * of the last packet of the previous fragment based on track_duration,
5582              * which might not exactly match our dts. Therefore adjust the dts
5583              * of this packet to be what the previous packets duration implies. */
5584             trk->cluster[trk->entry].dts = trk->start_dts + trk->track_duration;
5585             /* We also may have written the pts and the corresponding duration
5586              * in sidx/tfrf/tfxd tags; make sure the sidx pts and duration match up with
5587              * the next fragment. This means the cts of the first sample must
5588              * be the same in all fragments, unless end_pts was updated by
5589              * the packet causing the fragment to be written. */
5590             if ((mov->flags & FF_MOV_FLAG_DASH &&
5591                 !(mov->flags & (FF_MOV_FLAG_GLOBAL_SIDX | FF_MOV_FLAG_SKIP_SIDX))) ||
5592                 mov->mode == MODE_ISM)
5593                 pkt->pts = pkt->dts + trk->end_pts - trk->cluster[trk->entry].dts;
5594         } else {
5595             /* New fragment, but discontinuous from previous fragments.
5596              * Pretend the duration sum of the earlier fragments is
5597              * pkt->dts - trk->start_dts. */
5598             trk->frag_start = pkt->dts - trk->start_dts;
5599             trk->end_pts = AV_NOPTS_VALUE;
5600             trk->frag_discont = 0;
5601         }
5602     }
5603
5604     if (!trk->entry && trk->start_dts == AV_NOPTS_VALUE && !mov->use_editlist &&
5605         s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO) {
5606         /* Not using edit lists and shifting the first track to start from zero.
5607          * If the other streams start from a later timestamp, we won't be able
5608          * to signal the difference in starting time without an edit list.
5609          * Thus move the timestamp for this first sample to 0, increasing
5610          * its duration instead. */
5611         trk->cluster[trk->entry].dts = trk->start_dts = 0;
5612     }
5613     if (trk->start_dts == AV_NOPTS_VALUE) {
5614         trk->start_dts = pkt->dts;
5615         if (trk->frag_discont) {
5616             if (mov->use_editlist) {
5617                 /* Pretend the whole stream started at pts=0, with earlier fragments
5618                  * already written. If the stream started at pts=0, the duration sum
5619                  * of earlier fragments would have been pkt->pts. */
5620                 trk->frag_start = pkt->pts;
5621                 trk->start_dts  = pkt->dts - pkt->pts;
5622             } else {
5623                 /* Pretend the whole stream started at dts=0, with earlier fragments
5624                  * already written, with a duration summing up to pkt->dts. */
5625                 trk->frag_start = pkt->dts;
5626                 trk->start_dts  = 0;
5627             }
5628             trk->frag_discont = 0;
5629         } else if (pkt->dts && mov->moov_written)
5630             av_log(s, AV_LOG_WARNING,
5631                    "Track %d starts with a nonzero dts %"PRId64", while the moov "
5632                    "already has been written. Set the delay_moov flag to handle "
5633                    "this case.\n",
5634                    pkt->stream_index, pkt->dts);
5635     }
5636     trk->track_duration = pkt->dts - trk->start_dts + pkt->duration;
5637     trk->last_sample_is_subtitle_end = 0;
5638
5639     if (pkt->pts == AV_NOPTS_VALUE) {
5640         av_log(s, AV_LOG_WARNING, "pts has no value\n");
5641         pkt->pts = pkt->dts;
5642     }
5643     if (pkt->dts != pkt->pts)
5644         trk->flags |= MOV_TRACK_CTTS;
5645     trk->cluster[trk->entry].cts   = pkt->pts - pkt->dts;
5646     trk->cluster[trk->entry].flags = 0;
5647     if (trk->start_cts == AV_NOPTS_VALUE)
5648         trk->start_cts = pkt->pts - pkt->dts;
5649     if (trk->end_pts == AV_NOPTS_VALUE)
5650         trk->end_pts = trk->cluster[trk->entry].dts +
5651                        trk->cluster[trk->entry].cts + pkt->duration;
5652     else
5653         trk->end_pts = FFMAX(trk->end_pts, trk->cluster[trk->entry].dts +
5654                                            trk->cluster[trk->entry].cts +
5655                                            pkt->duration);
5656
5657     if (par->codec_id == AV_CODEC_ID_VC1) {
5658         mov_parse_vc1_frame(pkt, trk);
5659     } else if (par->codec_id == AV_CODEC_ID_TRUEHD) {
5660         mov_parse_truehd_frame(pkt, trk);
5661     } else if (pkt->flags & AV_PKT_FLAG_KEY) {
5662         if (mov->mode == MODE_MOV && par->codec_id == AV_CODEC_ID_MPEG2VIDEO &&
5663             trk->entry > 0) { // force sync sample for the first key frame
5664             mov_parse_mpeg2_frame(pkt, &trk->cluster[trk->entry].flags);
5665             if (trk->cluster[trk->entry].flags & MOV_PARTIAL_SYNC_SAMPLE)
5666                 trk->flags |= MOV_TRACK_STPS;
5667         } else {
5668             trk->cluster[trk->entry].flags = MOV_SYNC_SAMPLE;
5669         }
5670         if (trk->cluster[trk->entry].flags & MOV_SYNC_SAMPLE)
5671             trk->has_keyframes++;
5672     }
5673     if (pkt->flags & AV_PKT_FLAG_DISPOSABLE) {
5674         trk->cluster[trk->entry].flags |= MOV_DISPOSABLE_SAMPLE;
5675         trk->has_disposable++;
5676     }
5677
5678     prft = (AVProducerReferenceTime *)av_packet_get_side_data(pkt, AV_PKT_DATA_PRFT, &prft_size);
5679     if (prft && prft_size == sizeof(AVProducerReferenceTime))
5680         memcpy(&trk->cluster[trk->entry].prft, prft, prft_size);
5681     else
5682         memset(&trk->cluster[trk->entry].prft, 0, sizeof(AVProducerReferenceTime));
5683
5684     trk->entry++;
5685     trk->sample_count += samples_in_chunk;
5686     mov->mdat_size    += size;
5687
5688     if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams)
5689         ff_mov_add_hinted_packet(s, pkt, trk->hint_track, trk->entry,
5690                                  reformatted_data ? reformatted_data + offset
5691                                                   : NULL, size);
5692
5693 end:
5694 err:
5695
5696     if (pkt->data != reformatted_data)
5697         av_free(reformatted_data);
5698     return ret;
5699 }
5700
5701 static int mov_write_single_packet(AVFormatContext *s, AVPacket *pkt)
5702 {
5703         MOVMuxContext *mov = s->priv_data;
5704         MOVTrack *trk = &mov->tracks[pkt->stream_index];
5705         AVCodecParameters *par = trk->par;
5706         int64_t frag_duration = 0;
5707         int size = pkt->size;
5708
5709         int ret = check_pkt(s, pkt);
5710         if (ret < 0)
5711             return ret;
5712
5713         if (mov->flags & FF_MOV_FLAG_FRAG_DISCONT) {
5714             int i;
5715             for (i = 0; i < s->nb_streams; i++)
5716                 mov->tracks[i].frag_discont = 1;
5717             mov->flags &= ~FF_MOV_FLAG_FRAG_DISCONT;
5718         }
5719
5720         if (mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS) {
5721             if (trk->dts_shift == AV_NOPTS_VALUE)
5722                 trk->dts_shift = pkt->pts - pkt->dts;
5723             pkt->dts += trk->dts_shift;
5724         }
5725
5726         if (trk->par->codec_id == AV_CODEC_ID_MP4ALS ||
5727             trk->par->codec_id == AV_CODEC_ID_AAC ||
5728             trk->par->codec_id == AV_CODEC_ID_AV1 ||
5729             trk->par->codec_id == AV_CODEC_ID_FLAC) {
5730             int side_size = 0;
5731             uint8_t *side = av_packet_get_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA, &side_size);
5732             if (side && side_size > 0 && (side_size != par->extradata_size || memcmp(side, par->extradata, side_size))) {
5733                 void *newextra = av_mallocz(side_size + AV_INPUT_BUFFER_PADDING_SIZE);
5734                 if (!newextra)
5735                     return AVERROR(ENOMEM);
5736                 av_free(par->extradata);
5737                 par->extradata = newextra;
5738                 memcpy(par->extradata, side, side_size);
5739                 par->extradata_size = side_size;
5740                 if (!pkt->size) // Flush packet
5741                     mov->need_rewrite_extradata = 1;
5742             }
5743         }
5744
5745         if (!pkt->size) {
5746             if (trk->start_dts == AV_NOPTS_VALUE && trk->frag_discont) {
5747                 trk->start_dts = pkt->dts;
5748                 if (pkt->pts != AV_NOPTS_VALUE)
5749                     trk->start_cts = pkt->pts - pkt->dts;
5750                 else
5751                     trk->start_cts = 0;
5752             }
5753
5754             return 0;             /* Discard 0 sized packets */
5755         }
5756
5757         if (trk->entry && pkt->stream_index < s->nb_streams)
5758             frag_duration = av_rescale_q(pkt->dts - trk->cluster[0].dts,
5759                                          s->streams[pkt->stream_index]->time_base,
5760                                          AV_TIME_BASE_Q);
5761         if ((mov->max_fragment_duration &&
5762              frag_duration >= mov->max_fragment_duration) ||
5763              (mov->max_fragment_size && mov->mdat_size + size >= mov->max_fragment_size) ||
5764              (mov->flags & FF_MOV_FLAG_FRAG_KEYFRAME &&
5765               par->codec_type == AVMEDIA_TYPE_VIDEO &&
5766               trk->entry && pkt->flags & AV_PKT_FLAG_KEY) ||
5767               (mov->flags & FF_MOV_FLAG_FRAG_EVERY_FRAME)) {
5768             if (frag_duration >= mov->min_fragment_duration) {
5769                 // Set the duration of this track to line up with the next
5770                 // sample in this track. This avoids relying on AVPacket
5771                 // duration, but only helps for this particular track, not
5772                 // for the other ones that are flushed at the same time.
5773                 trk->track_duration = pkt->dts - trk->start_dts;
5774                 if (pkt->pts != AV_NOPTS_VALUE)
5775                     trk->end_pts = pkt->pts;
5776                 else
5777                     trk->end_pts = pkt->dts;
5778                 trk->end_reliable = 1;
5779                 mov_auto_flush_fragment(s, 0);
5780             }
5781         }
5782
5783         return ff_mov_write_packet(s, pkt);
5784 }
5785
5786 static int mov_write_subtitle_end_packet(AVFormatContext *s,
5787                                          int stream_index,
5788                                          int64_t dts) {
5789     AVPacket end;
5790     uint8_t data[2] = {0};
5791     int ret;
5792
5793     av_init_packet(&end);
5794     end.size = sizeof(data);
5795     end.data = data;
5796     end.pts = dts;
5797     end.dts = dts;
5798     end.duration = 0;
5799     end.stream_index = stream_index;
5800
5801     ret = mov_write_single_packet(s, &end);
5802     av_packet_unref(&end);
5803
5804     return ret;
5805 }
5806
5807 static int mov_write_packet(AVFormatContext *s, AVPacket *pkt)
5808 {
5809     MOVMuxContext *mov = s->priv_data;
5810     MOVTrack *trk;
5811
5812     if (!pkt) {
5813         mov_flush_fragment(s, 1);
5814         return 1;
5815     }
5816
5817     trk = &mov->tracks[pkt->stream_index];
5818
5819     if (is_cover_image(trk->st)) {
5820         int ret;
5821
5822         if (trk->st->nb_frames >= 1) {
5823             if (trk->st->nb_frames == 1)
5824                 av_log(s, AV_LOG_WARNING, "Got more than one picture in stream %d,"
5825                        " ignoring.\n", pkt->stream_index);
5826             return 0;
5827         }
5828
5829         if ((ret = av_packet_ref(&trk->cover_image, pkt)) < 0)
5830             return ret;
5831
5832         return 0;
5833     } else {
5834         int i;
5835
5836         if (!pkt->size)
5837             return mov_write_single_packet(s, pkt); /* Passthrough. */
5838
5839         /*
5840          * Subtitles require special handling.
5841          *
5842          * 1) For full complaince, every track must have a sample at
5843          * dts == 0, which is rarely true for subtitles. So, as soon
5844          * as we see any packet with dts > 0, write an empty subtitle
5845          * at dts == 0 for any subtitle track with no samples in it.
5846          *
5847          * 2) For each subtitle track, check if the current packet's
5848          * dts is past the duration of the last subtitle sample. If
5849          * so, we now need to write an end sample for that subtitle.
5850          *
5851          * This must be done conditionally to allow for subtitles that
5852          * immediately replace each other, in which case an end sample
5853          * is not needed, and is, in fact, actively harmful.
5854          *
5855          * 3) See mov_write_trailer for how the final end sample is
5856          * handled.
5857          */
5858         for (i = 0; i < mov->nb_streams; i++) {
5859             MOVTrack *trk = &mov->tracks[i];
5860             int ret;
5861
5862             if (trk->par->codec_id == AV_CODEC_ID_MOV_TEXT &&
5863                 trk->track_duration < pkt->dts &&
5864                 (trk->entry == 0 || !trk->last_sample_is_subtitle_end)) {
5865                 ret = mov_write_subtitle_end_packet(s, i, trk->track_duration);
5866                 if (ret < 0) return ret;
5867                 trk->last_sample_is_subtitle_end = 1;
5868             }
5869         }
5870
5871         if (trk->mode == MODE_MOV && trk->par->codec_type == AVMEDIA_TYPE_VIDEO) {
5872             AVPacket *opkt = pkt;
5873             int reshuffle_ret, ret;
5874             if (trk->is_unaligned_qt_rgb) {
5875                 int64_t bpc = trk->par->bits_per_coded_sample != 15 ? trk->par->bits_per_coded_sample : 16;
5876                 int expected_stride = ((trk->par->width * bpc + 15) >> 4)*2;
5877                 reshuffle_ret = ff_reshuffle_raw_rgb(s, &pkt, trk->par, expected_stride);
5878                 if (reshuffle_ret < 0)
5879                     return reshuffle_ret;
5880             } else
5881                 reshuffle_ret = 0;
5882             if (trk->par->format == AV_PIX_FMT_PAL8 && !trk->pal_done) {
5883                 ret = ff_get_packet_palette(s, opkt, reshuffle_ret, trk->palette);
5884                 if (ret < 0)
5885                     goto fail;
5886                 if (ret)
5887                     trk->pal_done++;
5888             } else if (trk->par->codec_id == AV_CODEC_ID_RAWVIDEO &&
5889                        (trk->par->format == AV_PIX_FMT_GRAY8 ||
5890                        trk->par->format == AV_PIX_FMT_MONOBLACK)) {
5891                 for (i = 0; i < pkt->size; i++)
5892                     pkt->data[i] = ~pkt->data[i];
5893             }
5894             if (reshuffle_ret) {
5895                 ret = mov_write_single_packet(s, pkt);
5896 fail:
5897                 if (reshuffle_ret)
5898                     av_packet_free(&pkt);
5899                 return ret;
5900             }
5901         }
5902
5903         return mov_write_single_packet(s, pkt);
5904     }
5905 }
5906
5907 // QuickTime chapters involve an additional text track with the chapter names
5908 // as samples, and a tref pointing from the other tracks to the chapter one.
5909 static int mov_create_chapter_track(AVFormatContext *s, int tracknum)
5910 {
5911     AVIOContext *pb;
5912
5913     MOVMuxContext *mov = s->priv_data;
5914     MOVTrack *track = &mov->tracks[tracknum];
5915     AVPacket pkt = { .stream_index = tracknum, .flags = AV_PKT_FLAG_KEY };
5916     int i, len;
5917
5918     track->mode = mov->mode;
5919     track->tag = MKTAG('t','e','x','t');
5920     track->timescale = MOV_TIMESCALE;
5921     track->par = avcodec_parameters_alloc();
5922     if (!track->par)
5923         return AVERROR(ENOMEM);
5924     track->par->codec_type = AVMEDIA_TYPE_SUBTITLE;
5925 #if 0
5926     // These properties are required to make QT recognize the chapter track
5927     uint8_t chapter_properties[43] = { 0, 0, 0, 0, 0, 0, 0, 1, };
5928     if (ff_alloc_extradata(track->par, sizeof(chapter_properties)))
5929         return AVERROR(ENOMEM);
5930     memcpy(track->par->extradata, chapter_properties, sizeof(chapter_properties));
5931 #else
5932     if (avio_open_dyn_buf(&pb) >= 0) {
5933         int size;
5934         uint8_t *buf;
5935
5936         /* Stub header (usually for Quicktime chapter track) */
5937         // TextSampleEntry
5938         avio_wb32(pb, 0x01); // displayFlags
5939         avio_w8(pb, 0x00);   // horizontal justification
5940         avio_w8(pb, 0x00);   // vertical justification
5941         avio_w8(pb, 0x00);   // bgColourRed
5942         avio_w8(pb, 0x00);   // bgColourGreen
5943         avio_w8(pb, 0x00);   // bgColourBlue
5944         avio_w8(pb, 0x00);   // bgColourAlpha
5945         // BoxRecord
5946         avio_wb16(pb, 0x00); // defTextBoxTop
5947         avio_wb16(pb, 0x00); // defTextBoxLeft
5948         avio_wb16(pb, 0x00); // defTextBoxBottom
5949         avio_wb16(pb, 0x00); // defTextBoxRight
5950         // StyleRecord
5951         avio_wb16(pb, 0x00); // startChar
5952         avio_wb16(pb, 0x00); // endChar
5953         avio_wb16(pb, 0x01); // fontID
5954         avio_w8(pb, 0x00);   // fontStyleFlags
5955         avio_w8(pb, 0x00);   // fontSize
5956         avio_w8(pb, 0x00);   // fgColourRed
5957         avio_w8(pb, 0x00);   // fgColourGreen
5958         avio_w8(pb, 0x00);   // fgColourBlue
5959         avio_w8(pb, 0x00);   // fgColourAlpha
5960         // FontTableBox
5961         avio_wb32(pb, 0x0D); // box size
5962         ffio_wfourcc(pb, "ftab"); // box atom name
5963         avio_wb16(pb, 0x01); // entry count
5964         // FontRecord
5965         avio_wb16(pb, 0x01); // font ID
5966         avio_w8(pb, 0x00);   // font name length
5967
5968         if ((size = avio_close_dyn_buf(pb, &buf)) > 0) {
5969             track->par->extradata = buf;
5970             track->par->extradata_size = size;
5971         } else {
5972             av_freep(&buf);
5973         }
5974     }
5975 #endif
5976
5977     for (i = 0; i < s->nb_chapters; i++) {
5978         AVChapter *c = s->chapters[i];
5979         AVDictionaryEntry *t;
5980
5981         int64_t end = av_rescale_q(c->end, c->time_base, (AVRational){1,MOV_TIMESCALE});
5982         pkt.pts = pkt.dts = av_rescale_q(c->start, c->time_base, (AVRational){1,MOV_TIMESCALE});
5983         pkt.duration = end - pkt.dts;
5984
5985         if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
5986             static const char encd[12] = {
5987                 0x00, 0x00, 0x00, 0x0C,
5988                 'e',  'n',  'c',  'd',
5989                 0x00, 0x00, 0x01, 0x00 };
5990             len      = strlen(t->value);
5991             pkt.size = len + 2 + 12;
5992             pkt.data = av_malloc(pkt.size);
5993             if (!pkt.data)
5994                 return AVERROR(ENOMEM);
5995             AV_WB16(pkt.data, len);
5996             memcpy(pkt.data + 2, t->value, len);
5997             memcpy(pkt.data + len + 2, encd, sizeof(encd));
5998             ff_mov_write_packet(s, &pkt);
5999             av_freep(&pkt.data);
6000         }
6001     }
6002
6003     return 0;
6004 }
6005
6006
6007 static int mov_check_timecode_track(AVFormatContext *s, AVTimecode *tc, int src_index, const char *tcstr)
6008 {
6009     int ret;
6010
6011     /* compute the frame number */
6012     ret = av_timecode_init_from_string(tc, find_fps(s,  s->streams[src_index]), tcstr, s);
6013     return ret;
6014 }
6015
6016 static int mov_create_timecode_track(AVFormatContext *s, int index, int src_index, AVTimecode tc)
6017 {
6018     int ret;
6019     MOVMuxContext *mov  = s->priv_data;
6020     MOVTrack *track     = &mov->tracks[index];
6021     AVStream *src_st    = s->streams[src_index];
6022     AVPacket pkt    = {.stream_index = index, .flags = AV_PKT_FLAG_KEY, .size = 4};
6023     AVRational rate = find_fps(s, src_st);
6024
6025     /* tmcd track based on video stream */
6026     track->mode      = mov->mode;
6027     track->tag       = MKTAG('t','m','c','d');
6028     track->src_track = src_index;
6029     track->timescale = mov->tracks[src_index].timescale;
6030     if (tc.flags & AV_TIMECODE_FLAG_DROPFRAME)
6031         track->timecode_flags |= MOV_TIMECODE_FLAG_DROPFRAME;
6032
6033     /* set st to src_st for metadata access*/
6034     track->st = src_st;
6035
6036     /* encode context: tmcd data stream */
6037     track->par = avcodec_parameters_alloc();
6038     if (!track->par)
6039         return AVERROR(ENOMEM);
6040     track->par->codec_type = AVMEDIA_TYPE_DATA;
6041     track->par->codec_tag  = track->tag;
6042     track->st->avg_frame_rate = av_inv_q(rate);
6043
6044     /* the tmcd track just contains one packet with the frame number */
6045     pkt.data = av_malloc(pkt.size);
6046     if (!pkt.data)
6047         return AVERROR(ENOMEM);
6048     AV_WB32(pkt.data, tc.start);
6049     ret = ff_mov_write_packet(s, &pkt);
6050     av_free(pkt.data);
6051     return ret;
6052 }
6053
6054 /*
6055  * st->disposition controls the "enabled" flag in the tkhd tag.
6056  * QuickTime will not play a track if it is not enabled.  So make sure
6057  * that one track of each type (audio, video, subtitle) is enabled.
6058  *
6059  * Subtitles are special.  For audio and video, setting "enabled" also
6060  * makes the track "default" (i.e. it is rendered when played). For
6061  * subtitles, an "enabled" subtitle is not rendered by default, but
6062  * if no subtitle is enabled, the subtitle menu in QuickTime will be
6063  * empty!
6064  */
6065 static void enable_tracks(AVFormatContext *s)
6066 {
6067     MOVMuxContext *mov = s->priv_data;
6068     int i;
6069     int enabled[AVMEDIA_TYPE_NB];
6070     int first[AVMEDIA_TYPE_NB];
6071
6072     for (i = 0; i < AVMEDIA_TYPE_NB; i++) {
6073         enabled[i] = 0;
6074         first[i] = -1;
6075     }
6076
6077     for (i = 0; i < s->nb_streams; i++) {
6078         AVStream *st = s->streams[i];
6079
6080         if (st->codecpar->codec_type <= AVMEDIA_TYPE_UNKNOWN ||
6081             st->codecpar->codec_type >= AVMEDIA_TYPE_NB ||
6082             is_cover_image(st))
6083             continue;
6084
6085         if (first[st->codecpar->codec_type] < 0)
6086             first[st->codecpar->codec_type] = i;
6087         if (st->disposition & AV_DISPOSITION_DEFAULT) {
6088             mov->tracks[i].flags |= MOV_TRACK_ENABLED;
6089             enabled[st->codecpar->codec_type]++;
6090         }
6091     }
6092
6093     for (i = 0; i < AVMEDIA_TYPE_NB; i++) {
6094         switch (i) {
6095         case AVMEDIA_TYPE_VIDEO:
6096         case AVMEDIA_TYPE_AUDIO:
6097         case AVMEDIA_TYPE_SUBTITLE:
6098             if (enabled[i] > 1)
6099                 mov->per_stream_grouping = 1;
6100             if (!enabled[i] && first[i] >= 0)
6101                 mov->tracks[first[i]].flags |= MOV_TRACK_ENABLED;
6102             break;
6103         }
6104     }
6105 }
6106
6107 static void mov_free(AVFormatContext *s)
6108 {
6109     MOVMuxContext *mov = s->priv_data;
6110     int i;
6111
6112     if (mov->chapter_track) {
6113         if (mov->tracks[mov->chapter_track].par)
6114             av_freep(&mov->tracks[mov->chapter_track].par->extradata);
6115         av_freep(&mov->tracks[mov->chapter_track].par);
6116     }
6117
6118     for (i = 0; i < mov->nb_streams; i++) {
6119         if (mov->tracks[i].tag == MKTAG('r','t','p',' '))
6120             ff_mov_close_hinting(&mov->tracks[i]);
6121         else if (mov->tracks[i].tag == MKTAG('t','m','c','d') && mov->nb_meta_tmcd)
6122             av_freep(&mov->tracks[i].par);
6123         av_freep(&mov->tracks[i].cluster);
6124         av_freep(&mov->tracks[i].frag_info);
6125         av_packet_unref(&mov->tracks[i].cover_image);
6126
6127         if (mov->tracks[i].eac3_priv) {
6128             struct eac3_info *info = mov->tracks[i].eac3_priv;
6129             av_packet_unref(&info->pkt);
6130             av_freep(&mov->tracks[i].eac3_priv);
6131         }
6132         if (mov->tracks[i].vos_len)
6133             av_freep(&mov->tracks[i].vos_data);
6134
6135         ff_mov_cenc_free(&mov->tracks[i].cenc);
6136     }
6137
6138     av_freep(&mov->tracks);
6139 }
6140
6141 static uint32_t rgb_to_yuv(uint32_t rgb)
6142 {
6143     uint8_t r, g, b;
6144     int y, cb, cr;
6145
6146     r = (rgb >> 16) & 0xFF;
6147     g = (rgb >>  8) & 0xFF;
6148     b = (rgb      ) & 0xFF;
6149
6150     y  = av_clip_uint8(( 16000 +  257 * r + 504 * g +  98 * b)/1000);
6151     cb = av_clip_uint8((128000 -  148 * r - 291 * g + 439 * b)/1000);
6152     cr = av_clip_uint8((128000 +  439 * r - 368 * g -  71 * b)/1000);
6153
6154     return (y << 16) | (cr << 8) | cb;
6155 }
6156
6157 static int mov_create_dvd_sub_decoder_specific_info(MOVTrack *track,
6158                                                     AVStream *st)
6159 {
6160     int i, width = 720, height = 480;
6161     int have_palette = 0, have_size = 0;
6162     uint32_t palette[16];
6163     char *cur = st->codecpar->extradata;
6164
6165     while (cur && *cur) {
6166         if (strncmp("palette:", cur, 8) == 0) {
6167             int i, count;
6168             count = sscanf(cur + 8,
6169                 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
6170                 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
6171                 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
6172                 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32"",
6173                 &palette[ 0], &palette[ 1], &palette[ 2], &palette[ 3],
6174                 &palette[ 4], &palette[ 5], &palette[ 6], &palette[ 7],
6175                 &palette[ 8], &palette[ 9], &palette[10], &palette[11],
6176                 &palette[12], &palette[13], &palette[14], &palette[15]);
6177
6178             for (i = 0; i < count; i++) {
6179                 palette[i] = rgb_to_yuv(palette[i]);
6180             }
6181             have_palette = 1;
6182         } else if (!strncmp("size:", cur, 5)) {
6183             sscanf(cur + 5, "%dx%d", &width, &height);
6184             have_size = 1;
6185         }
6186         if (have_palette && have_size)
6187             break;
6188         cur += strcspn(cur, "\n\r");
6189         cur += strspn(cur, "\n\r");
6190     }
6191     if (have_palette) {
6192         track->vos_data = av_malloc(16*4 + AV_INPUT_BUFFER_PADDING_SIZE);
6193         if (!track->vos_data)
6194             return AVERROR(ENOMEM);
6195         for (i = 0; i < 16; i++) {
6196             AV_WB32(track->vos_data + i * 4, palette[i]);
6197         }
6198         memset(track->vos_data + 16*4, 0, AV_INPUT_BUFFER_PADDING_SIZE);
6199         track->vos_len = 16 * 4;
6200     }
6201     st->codecpar->width = width;
6202     st->codecpar->height = track->height = height;
6203
6204     return 0;
6205 }
6206
6207 static int mov_init(AVFormatContext *s)
6208 {
6209     MOVMuxContext *mov = s->priv_data;
6210     AVDictionaryEntry *global_tcr = av_dict_get(s->metadata, "timecode", NULL, 0);
6211     int i, ret;
6212
6213     mov->fc = s;
6214
6215     /* Default mode == MP4 */
6216     mov->mode = MODE_MP4;
6217
6218     if (s->oformat) {
6219         if (!strcmp("3gp", s->oformat->name)) mov->mode = MODE_3GP;
6220         else if (!strcmp("3g2", s->oformat->name)) mov->mode = MODE_3GP|MODE_3G2;
6221         else if (!strcmp("mov", s->oformat->name)) mov->mode = MODE_MOV;
6222         else if (!strcmp("psp", s->oformat->name)) mov->mode = MODE_PSP;
6223         else if (!strcmp("ipod",s->oformat->name)) mov->mode = MODE_IPOD;
6224         else if (!strcmp("ismv",s->oformat->name)) mov->mode = MODE_ISM;
6225         else if (!strcmp("f4v", s->oformat->name)) mov->mode = MODE_F4V;
6226     }
6227
6228     if (mov->flags & FF_MOV_FLAG_DELAY_MOOV)
6229         mov->flags |= FF_MOV_FLAG_EMPTY_MOOV;
6230
6231     /* Set the FRAGMENT flag if any of the fragmentation methods are
6232      * enabled. */
6233     if (mov->max_fragment_duration || mov->max_fragment_size ||
6234         mov->flags & (FF_MOV_FLAG_EMPTY_MOOV |
6235                       FF_MOV_FLAG_FRAG_KEYFRAME |
6236                       FF_MOV_FLAG_FRAG_CUSTOM |
6237                       FF_MOV_FLAG_FRAG_EVERY_FRAME))
6238         mov->flags |= FF_MOV_FLAG_FRAGMENT;
6239
6240     /* Set other implicit flags immediately */
6241     if (mov->mode == MODE_ISM)
6242         mov->flags |= FF_MOV_FLAG_EMPTY_MOOV | FF_MOV_FLAG_SEPARATE_MOOF |
6243                       FF_MOV_FLAG_FRAGMENT | FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS;
6244     if (mov->flags & FF_MOV_FLAG_DASH)
6245         mov->flags |= FF_MOV_FLAG_FRAGMENT | FF_MOV_FLAG_EMPTY_MOOV |
6246                       FF_MOV_FLAG_DEFAULT_BASE_MOOF;
6247     if (mov->flags & FF_MOV_FLAG_CMAF)
6248         mov->flags |= FF_MOV_FLAG_FRAGMENT | FF_MOV_FLAG_EMPTY_MOOV |
6249                       FF_MOV_FLAG_DEFAULT_BASE_MOOF | FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS;
6250
6251     if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV && s->flags & AVFMT_FLAG_AUTO_BSF) {
6252         av_log(s, AV_LOG_VERBOSE, "Empty MOOV enabled; disabling automatic bitstream filtering\n");
6253         s->flags &= ~AVFMT_FLAG_AUTO_BSF;
6254     }
6255
6256     if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX && mov->flags & FF_MOV_FLAG_SKIP_SIDX) {
6257         av_log(s, AV_LOG_WARNING, "Global SIDX enabled; Ignoring skip_sidx option\n");
6258         mov->flags &= ~FF_MOV_FLAG_SKIP_SIDX;
6259     }
6260
6261     if (mov->flags & FF_MOV_FLAG_FASTSTART) {
6262         mov->reserved_moov_size = -1;
6263     }
6264
6265     if (mov->use_editlist < 0) {
6266         mov->use_editlist = 1;
6267         if (mov->flags & FF_MOV_FLAG_FRAGMENT &&
6268             !(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
6269             // If we can avoid needing an edit list by shifting the
6270             // tracks, prefer that over (trying to) write edit lists
6271             // in fragmented output.
6272             if (s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO ||
6273                 s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO)
6274                 mov->use_editlist = 0;
6275         }
6276         if (mov->flags & FF_MOV_FLAG_CMAF) {
6277             // CMAF Track requires negative cts offsets without edit lists
6278             mov->use_editlist = 0;
6279         }
6280     }
6281     if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV &&
6282         !(mov->flags & FF_MOV_FLAG_DELAY_MOOV) && mov->use_editlist)
6283         av_log(s, AV_LOG_WARNING, "No meaningful edit list will be written when using empty_moov without delay_moov\n");
6284
6285     if (mov->flags & FF_MOV_FLAG_CMAF && mov->use_editlist) {
6286         av_log(s, AV_LOG_WARNING, "Edit list enabled; Assuming writing CMAF Track File\n");
6287         mov->flags &= ~FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS;
6288     }
6289     if (!mov->use_editlist && s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO &&
6290         !(mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS))
6291         s->avoid_negative_ts = AVFMT_AVOID_NEG_TS_MAKE_ZERO;
6292
6293     /* Clear the omit_tfhd_offset flag if default_base_moof is set;
6294      * if the latter is set that's enough and omit_tfhd_offset doesn't
6295      * add anything extra on top of that. */
6296     if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET &&
6297         mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)
6298         mov->flags &= ~FF_MOV_FLAG_OMIT_TFHD_OFFSET;
6299
6300     if (mov->frag_interleave &&
6301         mov->flags & (FF_MOV_FLAG_OMIT_TFHD_OFFSET | FF_MOV_FLAG_SEPARATE_MOOF)) {
6302         av_log(s, AV_LOG_ERROR,
6303                "Sample interleaving in fragments is mutually exclusive with "
6304                "omit_tfhd_offset and separate_moof\n");
6305         return AVERROR(EINVAL);
6306     }
6307
6308     /* Non-seekable output is ok if using fragmentation. If ism_lookahead
6309      * is enabled, we don't support non-seekable output at all. */
6310     if (!(s->pb->seekable & AVIO_SEEKABLE_NORMAL) &&
6311         (!(mov->flags & FF_MOV_FLAG_FRAGMENT) || mov->ism_lookahead)) {
6312         av_log(s, AV_LOG_ERROR, "muxer does not support non seekable output\n");
6313         return AVERROR(EINVAL);
6314     }
6315
6316     mov->nb_streams = s->nb_streams;
6317     if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters)
6318         mov->chapter_track = mov->nb_streams++;
6319
6320     if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
6321         for (i = 0; i < s->nb_streams; i++)
6322             if (rtp_hinting_needed(s->streams[i]))
6323                 mov->nb_streams++;
6324     }
6325
6326     if (   mov->write_tmcd == -1 && (mov->mode == MODE_MOV || mov->mode == MODE_MP4)
6327         || mov->write_tmcd == 1) {
6328         /* +1 tmcd track for each video stream with a timecode */
6329         for (i = 0; i < s->nb_streams; i++) {
6330             AVStream *st = s->streams[i];
6331             AVDictionaryEntry *t = global_tcr;
6332             if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
6333                 (t || (t=av_dict_get(st->metadata, "timecode", NULL, 0)))) {
6334                 AVTimecode tc;
6335                 ret = mov_check_timecode_track(s, &tc, i, t->value);
6336                 if (ret >= 0)
6337                     mov->nb_meta_tmcd++;
6338             }
6339         }
6340
6341         /* check if there is already a tmcd track to remux */
6342         if (mov->nb_meta_tmcd) {
6343             for (i = 0; i < s->nb_streams; i++) {
6344                 AVStream *st = s->streams[i];
6345                 if (st->codecpar->codec_tag == MKTAG('t','m','c','d')) {
6346                     av_log(s, AV_LOG_WARNING, "You requested a copy of the original timecode track "
6347                            "so timecode metadata are now ignored\n");
6348                     mov->nb_meta_tmcd = 0;
6349                 }
6350             }
6351         }
6352
6353         mov->nb_streams += mov->nb_meta_tmcd;
6354     }
6355
6356     // Reserve an extra stream for chapters for the case where chapters
6357     // are written in the trailer
6358     mov->tracks = av_mallocz_array((mov->nb_streams + 1), sizeof(*mov->tracks));
6359     if (!mov->tracks)
6360         return AVERROR(ENOMEM);
6361
6362     if (mov->encryption_scheme_str != NULL && strcmp(mov->encryption_scheme_str, "none") != 0) {
6363         if (strcmp(mov->encryption_scheme_str, "cenc-aes-ctr") == 0) {
6364             mov->encryption_scheme = MOV_ENC_CENC_AES_CTR;
6365
6366             if (mov->encryption_key_len != AES_CTR_KEY_SIZE) {
6367                 av_log(s, AV_LOG_ERROR, "Invalid encryption key len %d expected %d\n",
6368                     mov->encryption_key_len, AES_CTR_KEY_SIZE);
6369                 return AVERROR(EINVAL);
6370             }
6371
6372             if (mov->encryption_kid_len != CENC_KID_SIZE) {
6373                 av_log(s, AV_LOG_ERROR, "Invalid encryption kid len %d expected %d\n",
6374                     mov->encryption_kid_len, CENC_KID_SIZE);
6375                 return AVERROR(EINVAL);
6376             }
6377         } else {
6378             av_log(s, AV_LOG_ERROR, "unsupported encryption scheme %s\n",
6379                 mov->encryption_scheme_str);
6380             return AVERROR(EINVAL);
6381         }
6382     }
6383
6384     for (i = 0; i < s->nb_streams; i++) {
6385         AVStream *st= s->streams[i];
6386         MOVTrack *track= &mov->tracks[i];
6387         AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0);
6388
6389         track->st  = st;
6390         track->par = st->codecpar;
6391         track->language = ff_mov_iso639_to_lang(lang?lang->value:"und", mov->mode!=MODE_MOV);
6392         if (track->language < 0)
6393             track->language = 32767;  // Unspecified Macintosh language code
6394         track->mode = mov->mode;
6395         track->tag  = mov_find_codec_tag(s, track);
6396         if (!track->tag) {
6397             av_log(s, AV_LOG_ERROR, "Could not find tag for codec %s in stream #%d, "
6398                    "codec not currently supported in container\n",
6399                    avcodec_get_name(st->codecpar->codec_id), i);
6400             return AVERROR(EINVAL);
6401         }
6402         /* If hinting of this track is enabled by a later hint track,
6403          * this is updated. */
6404         track->hint_track = -1;
6405         track->start_dts  = AV_NOPTS_VALUE;
6406         track->start_cts  = AV_NOPTS_VALUE;
6407         track->end_pts    = AV_NOPTS_VALUE;
6408         track->dts_shift  = AV_NOPTS_VALUE;
6409         if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
6410             if (track->tag == MKTAG('m','x','3','p') || track->tag == MKTAG('m','x','3','n') ||
6411                 track->tag == MKTAG('m','x','4','p') || track->tag == MKTAG('m','x','4','n') ||
6412                 track->tag == MKTAG('m','x','5','p') || track->tag == MKTAG('m','x','5','n')) {
6413                 if (st->codecpar->width != 720 || (st->codecpar->height != 608 && st->codecpar->height != 512)) {
6414                     av_log(s, AV_LOG_ERROR, "D-10/IMX must use 720x608 or 720x512 video resolution\n");
6415                     return AVERROR(EINVAL);
6416                 }
6417                 track->height = track->tag >> 24 == 'n' ? 486 : 576;
6418             }
6419             if (mov->video_track_timescale) {
6420                 track->timescale = mov->video_track_timescale;
6421                 if (mov->mode == MODE_ISM && mov->video_track_timescale != 10000000)
6422                     av_log(s, AV_LOG_WARNING, "Warning: some tools, like mp4split, assume a timescale of 10000000 for ISMV.\n");
6423             } else {
6424                 track->timescale = st->time_base.den;
6425                 while(track->timescale < 10000)
6426                     track->timescale *= 2;
6427             }
6428             if (st->codecpar->width > 65535 || st->codecpar->height > 65535) {
6429                 av_log(s, AV_LOG_ERROR, "Resolution %dx%d too large for mov/mp4\n", st->codecpar->width, st->codecpar->height);
6430                 return AVERROR(EINVAL);
6431             }
6432             if (track->mode == MODE_MOV && track->timescale > 100000)
6433                 av_log(s, AV_LOG_WARNING,
6434                        "WARNING codec timebase is very high. If duration is too long,\n"
6435                        "file may not be playable by quicktime. Specify a shorter timebase\n"
6436                        "or choose different container.\n");
6437             if (track->mode == MODE_MOV &&
6438                 track->par->codec_id == AV_CODEC_ID_RAWVIDEO &&
6439                 track->tag == MKTAG('r','a','w',' ')) {
6440                 enum AVPixelFormat pix_fmt = track->par->format;
6441                 if (pix_fmt == AV_PIX_FMT_NONE && track->par->bits_per_coded_sample == 1)
6442                     pix_fmt = AV_PIX_FMT_MONOWHITE;
6443                 track->is_unaligned_qt_rgb =
6444                         pix_fmt == AV_PIX_FMT_RGB24 ||
6445                         pix_fmt == AV_PIX_FMT_BGR24 ||
6446                         pix_fmt == AV_PIX_FMT_PAL8 ||
6447                         pix_fmt == AV_PIX_FMT_GRAY8 ||
6448                         pix_fmt == AV_PIX_FMT_MONOWHITE ||
6449                         pix_fmt == AV_PIX_FMT_MONOBLACK;
6450             }
6451             if (track->par->codec_id == AV_CODEC_ID_VP9 ||
6452                 track->par->codec_id == AV_CODEC_ID_AV1) {
6453                 if (track->mode != MODE_MP4) {
6454                     av_log(s, AV_LOG_ERROR, "%s only supported in MP4.\n", avcodec_get_name(track->par->codec_id));
6455                     return AVERROR(EINVAL);
6456                 }
6457             } else if (track->par->codec_id == AV_CODEC_ID_VP8) {
6458                 /* altref frames handling is not defined in the spec as of version v1.0,
6459                  * so just forbid muxing VP8 streams altogether until a new version does */
6460                 av_log(s, AV_LOG_ERROR, "VP8 muxing is currently not supported.\n");
6461                 return AVERROR_PATCHWELCOME;
6462             }
6463         } else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
6464             track->timescale = st->codecpar->sample_rate;
6465             if (!st->codecpar->frame_size && !av_get_bits_per_sample(st->codecpar->codec_id)) {
6466                 av_log(s, AV_LOG_WARNING, "track %d: codec frame size is not set\n", i);
6467                 track->audio_vbr = 1;
6468             }else if (st->codecpar->codec_id == AV_CODEC_ID_ADPCM_MS ||
6469                      st->codecpar->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
6470                      st->codecpar->codec_id == AV_CODEC_ID_ILBC){
6471                 if (!st->codecpar->block_align) {
6472                     av_log(s, AV_LOG_ERROR, "track %d: codec block align is not set for adpcm\n", i);
6473                     return AVERROR(EINVAL);
6474                 }
6475                 track->sample_size = st->codecpar->block_align;
6476             }else if (st->codecpar->frame_size > 1){ /* assume compressed audio */
6477                 track->audio_vbr = 1;
6478             }else{
6479                 track->sample_size = (av_get_bits_per_sample(st->codecpar->codec_id) >> 3) * st->codecpar->channels;
6480             }
6481             if (st->codecpar->codec_id == AV_CODEC_ID_ILBC ||
6482                 st->codecpar->codec_id == AV_CODEC_ID_ADPCM_IMA_QT) {
6483                 track->audio_vbr = 1;
6484             }
6485             if (track->mode != MODE_MOV &&
6486                 track->par->codec_id == AV_CODEC_ID_MP3 && track->timescale < 16000) {
6487                 if (s->strict_std_compliance >= FF_COMPLIANCE_NORMAL) {
6488                     av_log(s, AV_LOG_ERROR, "track %d: muxing mp3 at %dhz is not standard, to mux anyway set strict to -1\n",
6489                         i, track->par->sample_rate);
6490                     return AVERROR(EINVAL);
6491                 } else {
6492                     av_log(s, AV_LOG_WARNING, "track %d: muxing mp3 at %dhz is not standard in MP4\n",
6493                            i, track->par->sample_rate);
6494                 }
6495             }
6496             if (track->par->codec_id == AV_CODEC_ID_FLAC ||
6497                 track->par->codec_id == AV_CODEC_ID_TRUEHD ||
6498                 track->par->codec_id == AV_CODEC_ID_OPUS) {
6499                 if (track->mode != MODE_MP4) {
6500                     av_log(s, AV_LOG_ERROR, "%s only supported in MP4.\n", avcodec_get_name(track->par->codec_id));
6501                     return AVERROR(EINVAL);
6502                 }
6503                 if (track->par->codec_id != AV_CODEC_ID_OPUS &&
6504                     s->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
6505                     av_log(s, AV_LOG_ERROR,
6506                            "%s in MP4 support is experimental, add "
6507                            "'-strict %d' if you want to use it.\n",
6508                            avcodec_get_name(track->par->codec_id), FF_COMPLIANCE_EXPERIMENTAL);
6509                     return AVERROR_EXPERIMENTAL;
6510                 }
6511             }
6512         } else if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) {
6513             track->timescale = st->time_base.den;
6514         } else if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA) {
6515             track->timescale = st->time_base.den;
6516         } else {
6517             track->timescale = MOV_TIMESCALE;
6518         }
6519         if (!track->height)
6520             track->height = st->codecpar->height;
6521         /* The Protected Interoperable File Format (PIFF) standard, used by ISMV recommends but
6522            doesn't mandate a track timescale of 10,000,000. The muxer allows a custom timescale
6523            for video tracks, so if user-set, it isn't overwritten */
6524         if (mov->mode == MODE_ISM &&
6525             (st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO ||
6526             (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && !mov->video_track_timescale))) {
6527              track->timescale = 10000000;
6528         }
6529
6530         avpriv_set_pts_info(st, 64, 1, track->timescale);
6531
6532         if (mov->encryption_scheme == MOV_ENC_CENC_AES_CTR) {
6533             ret = ff_mov_cenc_init(&track->cenc, mov->encryption_key,
6534                 track->par->codec_id == AV_CODEC_ID_H264, s->flags & AVFMT_FLAG_BITEXACT);
6535             if (ret)
6536                 return ret;
6537         }
6538     }
6539
6540     enable_tracks(s);
6541     return 0;
6542 }
6543
6544 static int mov_write_header(AVFormatContext *s)
6545 {
6546     AVIOContext *pb = s->pb;
6547     MOVMuxContext *mov = s->priv_data;
6548     AVDictionaryEntry *t, *global_tcr = av_dict_get(s->metadata, "timecode", NULL, 0);
6549     int i, ret, hint_track = 0, tmcd_track = 0, nb_tracks = s->nb_streams;
6550
6551     if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters)
6552         nb_tracks++;
6553
6554     if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
6555         hint_track = nb_tracks;
6556         for (i = 0; i < s->nb_streams; i++)
6557             if (rtp_hinting_needed(s->streams[i]))
6558                 nb_tracks++;
6559     }
6560
6561     if (mov->nb_meta_tmcd)
6562         tmcd_track = nb_tracks;
6563
6564     for (i = 0; i < s->nb_streams; i++) {
6565         int j;
6566         AVStream *st= s->streams[i];
6567         MOVTrack *track= &mov->tracks[i];
6568
6569         /* copy extradata if it exists */
6570         if (st->codecpar->extradata_size) {
6571             if (st->codecpar->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
6572                 mov_create_dvd_sub_decoder_specific_info(track, st);
6573             else if (!TAG_IS_AVCI(track->tag) && st->codecpar->codec_id != AV_CODEC_ID_DNXHD) {
6574                 track->vos_len  = st->codecpar->extradata_size;
6575                 track->vos_data = av_malloc(track->vos_len + AV_INPUT_BUFFER_PADDING_SIZE);
6576                 if (!track->vos_data) {
6577                     return AVERROR(ENOMEM);
6578                 }
6579                 memcpy(track->vos_data, st->codecpar->extradata, track->vos_len);
6580                 memset(track->vos_data + track->vos_len, 0, AV_INPUT_BUFFER_PADDING_SIZE);
6581             }
6582         }
6583
6584         if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ||
6585             track->par->channel_layout != AV_CH_LAYOUT_MONO)
6586             continue;
6587
6588         for (j = 0; j < s->nb_streams; j++) {
6589             AVStream *stj= s->streams[j];
6590             MOVTrack *trackj= &mov->tracks[j];
6591             if (j == i)
6592                 continue;
6593
6594             if (stj->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ||
6595                 trackj->par->channel_layout != AV_CH_LAYOUT_MONO ||
6596                 trackj->language != track->language ||
6597                 trackj->tag != track->tag
6598             )
6599                 continue;
6600             track->multichannel_as_mono++;
6601         }
6602     }
6603
6604     if (!(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
6605         if ((ret = mov_write_identification(pb, s)) < 0)
6606             return ret;
6607     }
6608
6609     if (mov->reserved_moov_size){
6610         mov->reserved_header_pos = avio_tell(pb);
6611         if (mov->reserved_moov_size > 0)
6612             avio_skip(pb, mov->reserved_moov_size);
6613     }
6614
6615     if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
6616         /* If no fragmentation options have been set, set a default. */
6617         if (!(mov->flags & (FF_MOV_FLAG_FRAG_KEYFRAME |
6618                             FF_MOV_FLAG_FRAG_CUSTOM |
6619                             FF_MOV_FLAG_FRAG_EVERY_FRAME)) &&
6620             !mov->max_fragment_duration && !mov->max_fragment_size)
6621             mov->flags |= FF_MOV_FLAG_FRAG_KEYFRAME;
6622     } else {
6623         if (mov->flags & FF_MOV_FLAG_FASTSTART)
6624             mov->reserved_header_pos = avio_tell(pb);
6625         mov_write_mdat_tag(pb, mov);
6626     }
6627
6628     ff_parse_creation_time_metadata(s, &mov->time, 1);
6629     if (mov->time)
6630         mov->time += 0x7C25B080; // 1970 based -> 1904 based
6631
6632     if (mov->chapter_track)
6633         if ((ret = mov_create_chapter_track(s, mov->chapter_track)) < 0)
6634             return ret;
6635
6636     if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
6637         for (i = 0; i < s->nb_streams; i++) {
6638             if (rtp_hinting_needed(s->streams[i])) {
6639                 if ((ret = ff_mov_init_hinting(s, hint_track, i)) < 0)
6640                     return ret;
6641                 hint_track++;
6642             }
6643         }
6644     }
6645
6646     if (mov->nb_meta_tmcd) {
6647         /* Initialize the tmcd tracks */
6648         for (i = 0; i < s->nb_streams; i++) {
6649             AVStream *st = s->streams[i];
6650             t = global_tcr;
6651
6652             if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
6653                 AVTimecode tc;
6654                 if (!t)
6655                     t = av_dict_get(st->metadata, "timecode", NULL, 0);
6656                 if (!t)
6657                     continue;
6658                 if (mov_check_timecode_track(s, &tc, i, t->value) < 0)
6659                     continue;
6660                 if ((ret = mov_create_timecode_track(s, tmcd_track, i, tc)) < 0)
6661                     return ret;
6662                 tmcd_track++;
6663             }
6664         }
6665     }
6666
6667     avio_flush(pb);
6668
6669     if (mov->flags & FF_MOV_FLAG_ISML)
6670         mov_write_isml_manifest(pb, mov, s);
6671
6672     if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV &&
6673         !(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
6674         if ((ret = mov_write_moov_tag(pb, mov, s)) < 0)
6675             return ret;
6676         mov->moov_written = 1;
6677         if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
6678             mov->reserved_header_pos = avio_tell(pb);
6679     }
6680
6681     return 0;
6682 }
6683
6684 static int get_moov_size(AVFormatContext *s)
6685 {
6686     int ret;
6687     AVIOContext *moov_buf;
6688     MOVMuxContext *mov = s->priv_data;
6689
6690     if ((ret = ffio_open_null_buf(&moov_buf)) < 0)
6691         return ret;
6692     if ((ret = mov_write_moov_tag(moov_buf, mov, s)) < 0)
6693         return ret;
6694     return ffio_close_null_buf(moov_buf);
6695 }
6696
6697 static int get_sidx_size(AVFormatContext *s)
6698 {
6699     int ret;
6700     AVIOContext *buf;
6701     MOVMuxContext *mov = s->priv_data;
6702
6703     if ((ret = ffio_open_null_buf(&buf)) < 0)
6704         return ret;
6705     mov_write_sidx_tags(buf, mov, -1, 0);
6706     return ffio_close_null_buf(buf);
6707 }
6708
6709 /*
6710  * This function gets the moov size if moved to the top of the file: the chunk
6711  * offset table can switch between stco (32-bit entries) to co64 (64-bit
6712  * entries) when the moov is moved to the beginning, so the size of the moov
6713  * would change. It also updates the chunk offset tables.
6714  */
6715 static int compute_moov_size(AVFormatContext *s)
6716 {
6717     int i, moov_size, moov_size2;
6718     MOVMuxContext *mov = s->priv_data;
6719
6720     moov_size = get_moov_size(s);
6721     if (moov_size < 0)
6722         return moov_size;
6723
6724     for (i = 0; i < mov->nb_streams; i++)
6725         mov->tracks[i].data_offset += moov_size;
6726
6727     moov_size2 = get_moov_size(s);
6728     if (moov_size2 < 0)
6729         return moov_size2;
6730
6731     /* if the size changed, we just switched from stco to co64 and need to
6732      * update the offsets */
6733     if (moov_size2 != moov_size)
6734         for (i = 0; i < mov->nb_streams; i++)
6735             mov->tracks[i].data_offset += moov_size2 - moov_size;
6736
6737     return moov_size2;
6738 }
6739
6740 static int compute_sidx_size(AVFormatContext *s)
6741 {
6742     int i, sidx_size;
6743     MOVMuxContext *mov = s->priv_data;
6744
6745     sidx_size = get_sidx_size(s);
6746     if (sidx_size < 0)
6747         return sidx_size;
6748
6749     for (i = 0; i < mov->nb_streams; i++)
6750         mov->tracks[i].data_offset += sidx_size;
6751
6752     return sidx_size;
6753 }
6754
6755 static int shift_data(AVFormatContext *s)
6756 {
6757     int ret = 0, moov_size;
6758     MOVMuxContext *mov = s->priv_data;
6759     int64_t pos, pos_end;
6760     uint8_t *buf, *read_buf[2];
6761     int read_buf_id = 0;
6762     int read_size[2];
6763     AVIOContext *read_pb;
6764
6765     if (mov->flags & FF_MOV_FLAG_FRAGMENT)
6766         moov_size = compute_sidx_size(s);
6767     else
6768         moov_size = compute_moov_size(s);
6769     if (moov_size < 0)
6770         return moov_size;
6771
6772     buf = av_malloc(moov_size * 2);
6773     if (!buf)
6774         return AVERROR(ENOMEM);
6775     read_buf[0] = buf;
6776     read_buf[1] = buf + moov_size;
6777
6778     /* Shift the data: the AVIO context of the output can only be used for
6779      * writing, so we re-open the same output, but for reading. It also avoids
6780      * a read/seek/write/seek back and forth. */
6781     avio_flush(s->pb);
6782     ret = s->io_open(s, &read_pb, s->url, AVIO_FLAG_READ, NULL);
6783     if (ret < 0) {
6784         av_log(s, AV_LOG_ERROR, "Unable to re-open %s output file for "
6785                "the second pass (faststart)\n", s->url);
6786         goto end;
6787     }
6788
6789     /* mark the end of the shift to up to the last data we wrote, and get ready
6790      * for writing */
6791     pos_end = avio_tell(s->pb);
6792     avio_seek(s->pb, mov->reserved_header_pos + moov_size, SEEK_SET);
6793
6794     /* start reading at where the new moov will be placed */
6795     avio_seek(read_pb, mov->reserved_header_pos, SEEK_SET);
6796     pos = avio_tell(read_pb);
6797
6798 #define READ_BLOCK do {                                                             \
6799     read_size[read_buf_id] = avio_read(read_pb, read_buf[read_buf_id], moov_size);  \
6800     read_buf_id ^= 1;                                                               \
6801 } while (0)
6802
6803     /* shift data by chunk of at most moov_size */
6804     READ_BLOCK;
6805     do {
6806         int n;
6807         READ_BLOCK;
6808         n = read_size[read_buf_id];
6809         if (n <= 0)
6810             break;
6811         avio_write(s->pb, read_buf[read_buf_id], n);
6812         pos += n;
6813     } while (pos < pos_end);
6814     ff_format_io_close(s, &read_pb);
6815
6816 end:
6817     av_free(buf);
6818     return ret;
6819 }
6820
6821 static int mov_write_trailer(AVFormatContext *s)
6822 {
6823     MOVMuxContext *mov = s->priv_data;
6824     AVIOContext *pb = s->pb;
6825     int res = 0;
6826     int i;
6827     int64_t moov_pos;
6828
6829     if (mov->need_rewrite_extradata) {
6830         for (i = 0; i < s->nb_streams; i++) {
6831             MOVTrack *track = &mov->tracks[i];
6832             AVCodecParameters *par = track->par;
6833
6834             track->vos_len  = par->extradata_size;
6835             track->vos_data = av_malloc(track->vos_len + AV_INPUT_BUFFER_PADDING_SIZE);
6836             if (!track->vos_data)
6837                 return AVERROR(ENOMEM);
6838             memcpy(track->vos_data, par->extradata, track->vos_len);
6839             memset(track->vos_data + track->vos_len, 0, AV_INPUT_BUFFER_PADDING_SIZE);
6840         }
6841         mov->need_rewrite_extradata = 0;
6842     }
6843
6844     /*
6845      * Before actually writing the trailer, make sure that there are no
6846      * dangling subtitles, that need a terminating sample.
6847      */
6848     for (i = 0; i < mov->nb_streams; i++) {
6849         MOVTrack *trk = &mov->tracks[i];
6850         if (trk->par->codec_id == AV_CODEC_ID_MOV_TEXT &&
6851             !trk->last_sample_is_subtitle_end) {
6852             mov_write_subtitle_end_packet(s, i, trk->track_duration);
6853             trk->last_sample_is_subtitle_end = 1;
6854         }
6855     }
6856
6857     // If there were no chapters when the header was written, but there
6858     // are chapters now, write them in the trailer.  This only works
6859     // when we are not doing fragments.
6860     if (!mov->chapter_track && !(mov->flags & FF_MOV_FLAG_FRAGMENT)) {
6861         if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters) {
6862             mov->chapter_track = mov->nb_streams++;
6863             if ((res = mov_create_chapter_track(s, mov->chapter_track)) < 0)
6864                 return res;
6865         }
6866     }
6867
6868     if (!(mov->flags & FF_MOV_FLAG_FRAGMENT)) {
6869         moov_pos = avio_tell(pb);
6870
6871         /* Write size of mdat tag */
6872         if (mov->mdat_size + 8 <= UINT32_MAX) {
6873             avio_seek(pb, mov->mdat_pos, SEEK_SET);
6874             avio_wb32(pb, mov->mdat_size + 8);
6875         } else {
6876             /* overwrite 'wide' placeholder atom */
6877             avio_seek(pb, mov->mdat_pos - 8, SEEK_SET);
6878             /* special value: real atom size will be 64 bit value after
6879              * tag field */
6880             avio_wb32(pb, 1);
6881             ffio_wfourcc(pb, "mdat");
6882             avio_wb64(pb, mov->mdat_size + 16);
6883         }
6884         avio_seek(pb, mov->reserved_moov_size > 0 ? mov->reserved_header_pos : moov_pos, SEEK_SET);
6885
6886         if (mov->flags & FF_MOV_FLAG_FASTSTART) {
6887             av_log(s, AV_LOG_INFO, "Starting second pass: moving the moov atom to the beginning of the file\n");
6888             res = shift_data(s);
6889             if (res < 0)
6890                 return res;
6891             avio_seek(pb, mov->reserved_header_pos, SEEK_SET);
6892             if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
6893                 return res;
6894         } else if (mov->reserved_moov_size > 0) {
6895             int64_t size;
6896             if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
6897                 return res;
6898             size = mov->reserved_moov_size - (avio_tell(pb) - mov->reserved_header_pos);
6899             if (size < 8){
6900                 av_log(s, AV_LOG_ERROR, "reserved_moov_size is too small, needed %"PRId64" additional\n", 8-size);
6901                 return AVERROR(EINVAL);
6902             }
6903             avio_wb32(pb, size);
6904             ffio_wfourcc(pb, "free");
6905             ffio_fill(pb, 0, size - 8);
6906             avio_seek(pb, moov_pos, SEEK_SET);
6907         } else {
6908             if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
6909                 return res;
6910         }
6911         res = 0;
6912     } else {
6913         mov_auto_flush_fragment(s, 1);
6914         for (i = 0; i < mov->nb_streams; i++)
6915            mov->tracks[i].data_offset = 0;
6916         if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) {
6917             int64_t end;
6918             av_log(s, AV_LOG_INFO, "Starting second pass: inserting sidx atoms\n");
6919             res = shift_data(s);
6920             if (res < 0)
6921                 return res;
6922             end = avio_tell(pb);
6923             avio_seek(pb, mov->reserved_header_pos, SEEK_SET);
6924             mov_write_sidx_tags(pb, mov, -1, 0);
6925             avio_seek(pb, end, SEEK_SET);
6926         }
6927         if (!(mov->flags & FF_MOV_FLAG_SKIP_TRAILER)) {
6928             avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_TRAILER);
6929             mov_write_mfra_tag(pb, mov);
6930         }
6931     }
6932
6933     return res;
6934 }
6935
6936 static int mov_check_bitstream(struct AVFormatContext *s, const AVPacket *pkt)
6937 {
6938     int ret = 1;
6939     AVStream *st = s->streams[pkt->stream_index];
6940
6941     if (st->codecpar->codec_id == AV_CODEC_ID_AAC) {
6942         if (pkt->size > 2 && (AV_RB16(pkt->data) & 0xfff0) == 0xfff0)
6943             ret = ff_stream_add_bitstream_filter(st, "aac_adtstoasc", NULL);
6944     } else if (st->codecpar->codec_id == AV_CODEC_ID_VP9) {
6945         ret = ff_stream_add_bitstream_filter(st, "vp9_superframe", NULL);
6946     }
6947
6948     return ret;
6949 }
6950
6951 static const AVCodecTag codec_3gp_tags[] = {
6952     { AV_CODEC_ID_H263,     MKTAG('s','2','6','3') },
6953     { AV_CODEC_ID_H264,     MKTAG('a','v','c','1') },
6954     { AV_CODEC_ID_MPEG4,    MKTAG('m','p','4','v') },
6955     { AV_CODEC_ID_AAC,      MKTAG('m','p','4','a') },
6956     { AV_CODEC_ID_AMR_NB,   MKTAG('s','a','m','r') },
6957     { AV_CODEC_ID_AMR_WB,   MKTAG('s','a','w','b') },
6958     { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
6959     { AV_CODEC_ID_NONE, 0 },
6960 };
6961
6962 const AVCodecTag codec_mp4_tags[] = {
6963     { AV_CODEC_ID_MPEG4,           MKTAG('m', 'p', '4', 'v') },
6964     { AV_CODEC_ID_H264,            MKTAG('a', 'v', 'c', '1') },
6965     { AV_CODEC_ID_H264,            MKTAG('a', 'v', 'c', '3') },
6966     { AV_CODEC_ID_HEVC,            MKTAG('h', 'e', 'v', '1') },
6967     { AV_CODEC_ID_HEVC,            MKTAG('h', 'v', 'c', '1') },
6968     { AV_CODEC_ID_MPEG2VIDEO,      MKTAG('m', 'p', '4', 'v') },
6969     { AV_CODEC_ID_MPEG1VIDEO,      MKTAG('m', 'p', '4', 'v') },
6970     { AV_CODEC_ID_MJPEG,           MKTAG('m', 'p', '4', 'v') },
6971     { AV_CODEC_ID_PNG,             MKTAG('m', 'p', '4', 'v') },
6972     { AV_CODEC_ID_JPEG2000,        MKTAG('m', 'p', '4', 'v') },
6973     { AV_CODEC_ID_VC1,             MKTAG('v', 'c', '-', '1') },
6974     { AV_CODEC_ID_DIRAC,           MKTAG('d', 'r', 'a', 'c') },
6975     { AV_CODEC_ID_TSCC2,           MKTAG('m', 'p', '4', 'v') },
6976     { AV_CODEC_ID_VP9,             MKTAG('v', 'p', '0', '9') },
6977     { AV_CODEC_ID_AV1,             MKTAG('a', 'v', '0', '1') },
6978     { AV_CODEC_ID_AAC,             MKTAG('m', 'p', '4', 'a') },
6979     { AV_CODEC_ID_MP4ALS,          MKTAG('m', 'p', '4', 'a') },
6980     { AV_CODEC_ID_MP3,             MKTAG('m', 'p', '4', 'a') },
6981     { AV_CODEC_ID_MP2,             MKTAG('m', 'p', '4', 'a') },
6982     { AV_CODEC_ID_AC3,             MKTAG('a', 'c', '-', '3') },
6983     { AV_CODEC_ID_EAC3,            MKTAG('e', 'c', '-', '3') },
6984     { AV_CODEC_ID_DTS,             MKTAG('m', 'p', '4', 'a') },
6985     { AV_CODEC_ID_TRUEHD,          MKTAG('m', 'l', 'p', 'a') },
6986     { AV_CODEC_ID_FLAC,            MKTAG('f', 'L', 'a', 'C') },
6987     { AV_CODEC_ID_OPUS,            MKTAG('O', 'p', 'u', 's') },
6988     { AV_CODEC_ID_VORBIS,          MKTAG('m', 'p', '4', 'a') },
6989     { AV_CODEC_ID_QCELP,           MKTAG('m', 'p', '4', 'a') },
6990     { AV_CODEC_ID_EVRC,            MKTAG('m', 'p', '4', 'a') },
6991     { AV_CODEC_ID_DVD_SUBTITLE,    MKTAG('m', 'p', '4', 's') },
6992     { AV_CODEC_ID_MOV_TEXT,        MKTAG('t', 'x', '3', 'g') },
6993     { AV_CODEC_ID_BIN_DATA,        MKTAG('g', 'p', 'm', 'd') },
6994     { AV_CODEC_ID_MPEGH_3D_AUDIO,  MKTAG('m', 'h', 'm', '1') },
6995     { AV_CODEC_ID_NONE,               0 },
6996 };
6997
6998 const AVCodecTag codec_ism_tags[] = {
6999     { AV_CODEC_ID_WMAPRO      , MKTAG('w', 'm', 'a', ' ') },
7000     { AV_CODEC_ID_NONE        ,    0 },
7001 };
7002
7003 static const AVCodecTag codec_ipod_tags[] = {
7004     { AV_CODEC_ID_H264,     MKTAG('a','v','c','1') },
7005     { AV_CODEC_ID_MPEG4,    MKTAG('m','p','4','v') },
7006     { AV_CODEC_ID_AAC,      MKTAG('m','p','4','a') },
7007     { AV_CODEC_ID_ALAC,     MKTAG('a','l','a','c') },
7008     { AV_CODEC_ID_AC3,      MKTAG('a','c','-','3') },
7009     { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
7010     { AV_CODEC_ID_MOV_TEXT, MKTAG('t','e','x','t') },
7011     { AV_CODEC_ID_NONE, 0 },
7012 };
7013
7014 static const AVCodecTag codec_f4v_tags[] = {
7015     { AV_CODEC_ID_MP3,    MKTAG('.','m','p','3') },
7016     { AV_CODEC_ID_AAC,    MKTAG('m','p','4','a') },
7017     { AV_CODEC_ID_H264,   MKTAG('a','v','c','1') },
7018     { AV_CODEC_ID_VP6A,   MKTAG('V','P','6','A') },
7019     { AV_CODEC_ID_VP6F,   MKTAG('V','P','6','F') },
7020     { AV_CODEC_ID_NONE, 0 },
7021 };
7022
7023 #if CONFIG_MOV_MUXER
7024 MOV_CLASS(mov)
7025 AVOutputFormat ff_mov_muxer = {
7026     .name              = "mov",
7027     .long_name         = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
7028     .extensions        = "mov",
7029     .priv_data_size    = sizeof(MOVMuxContext),
7030     .audio_codec       = AV_CODEC_ID_AAC,
7031     .video_codec       = CONFIG_LIBX264_ENCODER ?
7032                          AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
7033     .init              = mov_init,
7034     .write_header      = mov_write_header,
7035     .write_packet      = mov_write_packet,
7036     .write_trailer     = mov_write_trailer,
7037     .deinit            = mov_free,
7038     .flags             = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
7039     .codec_tag         = (const AVCodecTag* const []){
7040         ff_codec_movvideo_tags, ff_codec_movaudio_tags, ff_codec_movsubtitle_tags, 0
7041     },
7042     .check_bitstream   = mov_check_bitstream,
7043     .priv_class        = &mov_muxer_class,
7044 };
7045 #endif
7046 #if CONFIG_TGP_MUXER
7047 MOV_CLASS(tgp)
7048 AVOutputFormat ff_tgp_muxer = {
7049     .name              = "3gp",
7050     .long_name         = NULL_IF_CONFIG_SMALL("3GP (3GPP file format)"),
7051     .extensions        = "3gp",
7052     .priv_data_size    = sizeof(MOVMuxContext),
7053     .audio_codec       = AV_CODEC_ID_AMR_NB,
7054     .video_codec       = AV_CODEC_ID_H263,
7055     .init              = mov_init,
7056     .write_header      = mov_write_header,
7057     .write_packet      = mov_write_packet,
7058     .write_trailer     = mov_write_trailer,
7059     .deinit            = mov_free,
7060     .flags             = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
7061     .codec_tag         = (const AVCodecTag* const []){ codec_3gp_tags, 0 },
7062     .check_bitstream   = mov_check_bitstream,
7063     .priv_class        = &tgp_muxer_class,
7064 };
7065 #endif
7066 #if CONFIG_MP4_MUXER
7067 MOV_CLASS(mp4)
7068 AVOutputFormat ff_mp4_muxer = {
7069     .name              = "mp4",
7070     .long_name         = NULL_IF_CONFIG_SMALL("MP4 (MPEG-4 Part 14)"),
7071     .mime_type         = "video/mp4",
7072     .extensions        = "mp4",
7073     .priv_data_size    = sizeof(MOVMuxContext),
7074     .audio_codec       = AV_CODEC_ID_AAC,
7075     .video_codec       = CONFIG_LIBX264_ENCODER ?
7076                          AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
7077     .init              = mov_init,
7078     .write_header      = mov_write_header,
7079     .write_packet      = mov_write_packet,
7080     .write_trailer     = mov_write_trailer,
7081     .deinit            = mov_free,
7082     .flags             = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
7083     .codec_tag         = (const AVCodecTag* const []){ codec_mp4_tags, 0 },
7084     .check_bitstream   = mov_check_bitstream,
7085     .priv_class        = &mp4_muxer_class,
7086 };
7087 #endif
7088 #if CONFIG_PSP_MUXER
7089 MOV_CLASS(psp)
7090 AVOutputFormat ff_psp_muxer = {
7091     .name              = "psp",
7092     .long_name         = NULL_IF_CONFIG_SMALL("PSP MP4 (MPEG-4 Part 14)"),
7093     .extensions        = "mp4,psp",
7094     .priv_data_size    = sizeof(MOVMuxContext),
7095     .audio_codec       = AV_CODEC_ID_AAC,
7096     .video_codec       = CONFIG_LIBX264_ENCODER ?
7097                          AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
7098     .init              = mov_init,
7099     .write_header      = mov_write_header,
7100     .write_packet      = mov_write_packet,
7101     .write_trailer     = mov_write_trailer,
7102     .deinit            = mov_free,
7103     .flags             = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
7104     .codec_tag         = (const AVCodecTag* const []){ codec_mp4_tags, 0 },
7105     .check_bitstream   = mov_check_bitstream,
7106     .priv_class        = &psp_muxer_class,
7107 };
7108 #endif
7109 #if CONFIG_TG2_MUXER
7110 MOV_CLASS(tg2)
7111 AVOutputFormat ff_tg2_muxer = {
7112     .name              = "3g2",
7113     .long_name         = NULL_IF_CONFIG_SMALL("3GP2 (3GPP2 file format)"),
7114     .extensions        = "3g2",
7115     .priv_data_size    = sizeof(MOVMuxContext),
7116     .audio_codec       = AV_CODEC_ID_AMR_NB,
7117     .video_codec       = AV_CODEC_ID_H263,
7118     .init              = mov_init,
7119     .write_header      = mov_write_header,
7120     .write_packet      = mov_write_packet,
7121     .write_trailer     = mov_write_trailer,
7122     .deinit            = mov_free,
7123     .flags             = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
7124     .codec_tag         = (const AVCodecTag* const []){ codec_3gp_tags, 0 },
7125     .check_bitstream   = mov_check_bitstream,
7126     .priv_class        = &tg2_muxer_class,
7127 };
7128 #endif
7129 #if CONFIG_IPOD_MUXER
7130 MOV_CLASS(ipod)
7131 AVOutputFormat ff_ipod_muxer = {
7132     .name              = "ipod",
7133     .long_name         = NULL_IF_CONFIG_SMALL("iPod H.264 MP4 (MPEG-4 Part 14)"),
7134     .mime_type         = "video/mp4",
7135     .extensions        = "m4v,m4a,m4b",
7136     .priv_data_size    = sizeof(MOVMuxContext),
7137     .audio_codec       = AV_CODEC_ID_AAC,
7138     .video_codec       = AV_CODEC_ID_H264,
7139     .init              = mov_init,
7140     .write_header      = mov_write_header,
7141     .write_packet      = mov_write_packet,
7142     .write_trailer     = mov_write_trailer,
7143     .deinit            = mov_free,
7144     .flags             = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
7145     .codec_tag         = (const AVCodecTag* const []){ codec_ipod_tags, 0 },
7146     .check_bitstream   = mov_check_bitstream,
7147     .priv_class        = &ipod_muxer_class,
7148 };
7149 #endif
7150 #if CONFIG_ISMV_MUXER
7151 MOV_CLASS(ismv)
7152 AVOutputFormat ff_ismv_muxer = {
7153     .name              = "ismv",
7154     .long_name         = NULL_IF_CONFIG_SMALL("ISMV/ISMA (Smooth Streaming)"),
7155     .mime_type         = "video/mp4",
7156     .extensions        = "ismv,isma",
7157     .priv_data_size    = sizeof(MOVMuxContext),
7158     .audio_codec       = AV_CODEC_ID_AAC,
7159     .video_codec       = AV_CODEC_ID_H264,
7160     .init              = mov_init,
7161     .write_header      = mov_write_header,
7162     .write_packet      = mov_write_packet,
7163     .write_trailer     = mov_write_trailer,
7164     .deinit            = mov_free,
7165     .flags             = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
7166     .codec_tag         = (const AVCodecTag* const []){
7167         codec_mp4_tags, codec_ism_tags, 0 },
7168     .check_bitstream   = mov_check_bitstream,
7169     .priv_class        = &ismv_muxer_class,
7170 };
7171 #endif
7172 #if CONFIG_F4V_MUXER
7173 MOV_CLASS(f4v)
7174 AVOutputFormat ff_f4v_muxer = {
7175     .name              = "f4v",
7176     .long_name         = NULL_IF_CONFIG_SMALL("F4V Adobe Flash Video"),
7177     .mime_type         = "application/f4v",
7178     .extensions        = "f4v",
7179     .priv_data_size    = sizeof(MOVMuxContext),
7180     .audio_codec       = AV_CODEC_ID_AAC,
7181     .video_codec       = AV_CODEC_ID_H264,
7182     .init              = mov_init,
7183     .write_header      = mov_write_header,
7184     .write_packet      = mov_write_packet,
7185     .write_trailer     = mov_write_trailer,
7186     .deinit            = mov_free,
7187     .flags             = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH,
7188     .codec_tag         = (const AVCodecTag* const []){ codec_f4v_tags, 0 },
7189     .check_bitstream   = mov_check_bitstream,
7190     .priv_class        = &f4v_muxer_class,
7191 };
7192 #endif