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