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