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