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