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