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