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