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