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