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