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