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