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