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