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