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