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