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