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