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