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