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