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