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