]> git.sesse.net Git - ffmpeg/blob - libavformat/movenc.c
Merge commit '12b3459979f5ea6481660cd2c99a0381e2b5ba37'
[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 (MOV): https://developer.apple.com/library/mac/technotes/tn2162/_index.html#//apple_ref/doc/uid/DTS40013070-CH1-TNTAG9
1525     // Ref (MP4): ISO/IEC 14496-12:2012
1526
1527     if (track->enc->color_primaries == AVCOL_PRI_UNSPECIFIED &&
1528         track->enc->color_trc == AVCOL_TRC_UNSPECIFIED &&
1529         track->enc->colorspace == AVCOL_SPC_UNSPECIFIED) {
1530         if ((track->enc->width >= 1920 && track->enc->height >= 1080)
1531           || (track->enc->width == 1280 && track->enc->height == 720)) {
1532             av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming bt709\n");
1533             track->enc->color_primaries = AVCOL_PRI_BT709;
1534         } else if (track->enc->width == 720 && track->height == 576) {
1535             av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming bt470bg\n");
1536             track->enc->color_primaries = AVCOL_PRI_BT470BG;
1537         } else if (track->enc->width == 720 &&
1538                    (track->height == 486 || track->height == 480)) {
1539             av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming smpte170\n");
1540             track->enc->color_primaries = AVCOL_PRI_SMPTE170M;
1541         } else {
1542             av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, unable to assume anything\n");
1543         }
1544         switch (track->enc->color_primaries) {
1545         case AVCOL_PRI_BT709:
1546             track->enc->color_trc = AVCOL_TRC_BT709;
1547             track->enc->colorspace = AVCOL_SPC_BT709;
1548             break;
1549         case AVCOL_PRI_SMPTE170M:
1550         case AVCOL_PRI_BT470BG:
1551             track->enc->color_trc = AVCOL_TRC_BT709;
1552             track->enc->colorspace = AVCOL_SPC_SMPTE170M;
1553             break;
1554         }
1555     }
1556
1557     /* We should only ever be called by MOV or MP4. */
1558     av_assert0(track->mode == MODE_MOV || track->mode == MODE_MP4);
1559
1560     avio_wb32(pb, 18 + (track->mode == MODE_MP4));
1561     ffio_wfourcc(pb, "colr");
1562     if (track->mode == MODE_MP4)
1563         ffio_wfourcc(pb, "nclx");
1564     else
1565         ffio_wfourcc(pb, "nclc");
1566     switch (track->enc->color_primaries) {
1567     case AVCOL_PRI_BT709:     avio_wb16(pb, 1); break;
1568     case AVCOL_PRI_SMPTE170M:
1569     case AVCOL_PRI_SMPTE240M: avio_wb16(pb, 6); break;
1570     case AVCOL_PRI_BT470BG:   avio_wb16(pb, 5); break;
1571     default:                  avio_wb16(pb, 2);
1572     }
1573     switch (track->enc->color_trc) {
1574     case AVCOL_TRC_BT709:     avio_wb16(pb, 1); break;
1575     case AVCOL_TRC_SMPTE170M: avio_wb16(pb, 1); break; // remapped
1576     case AVCOL_TRC_SMPTE240M: avio_wb16(pb, 7); break;
1577     default:                  avio_wb16(pb, 2);
1578     }
1579     switch (track->enc->colorspace) {
1580     case AVCOL_TRC_BT709:     avio_wb16(pb, 1); break;
1581     case AVCOL_PRI_SMPTE170M: avio_wb16(pb, 6); break;
1582     case AVCOL_PRI_SMPTE240M: avio_wb16(pb, 7); break;
1583     default:                  avio_wb16(pb, 2);
1584     }
1585
1586     if (track->mode == MODE_MP4) {
1587         int full_range = track->enc->color_range == AVCOL_RANGE_JPEG;
1588         avio_w8(pb, full_range << 7);
1589         return 19;
1590     } else {
1591         return 18;
1592     }
1593 }
1594
1595 static void find_compressor(char * compressor_name, int len, MOVTrack *track)
1596 {
1597     AVDictionaryEntry *encoder;
1598     int xdcam_res =  (track->enc->width == 1280 && track->enc->height == 720)
1599                   || (track->enc->width == 1440 && track->enc->height == 1080)
1600                   || (track->enc->width == 1920 && track->enc->height == 1080);
1601
1602     if (track->mode == MODE_MOV &&
1603         (encoder = av_dict_get(track->st->metadata, "encoder", NULL, 0))) {
1604         av_strlcpy(compressor_name, encoder->value, 32);
1605     } else if (track->enc->codec_id == AV_CODEC_ID_MPEG2VIDEO && xdcam_res) {
1606         int interlaced = track->enc->field_order > AV_FIELD_PROGRESSIVE;
1607         AVStream *st = track->st;
1608         int rate = av_q2d(find_fps(NULL, st));
1609         av_strlcatf(compressor_name, len, "XDCAM");
1610         if (track->enc->pix_fmt == AV_PIX_FMT_YUV422P) {
1611             av_strlcatf(compressor_name, len, " HD422");
1612         } else if(track->enc->width == 1440) {
1613             av_strlcatf(compressor_name, len, " HD");
1614         } else
1615             av_strlcatf(compressor_name, len, " EX");
1616
1617         av_strlcatf(compressor_name, len, " %d%c", track->enc->height, interlaced ? 'i' : 'p');
1618
1619         av_strlcatf(compressor_name, len, "%d", rate * (interlaced + 1));
1620     }
1621 }
1622
1623 static int mov_write_video_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
1624 {
1625     int64_t pos = avio_tell(pb);
1626     char compressor_name[32] = { 0 };
1627     int avid = 0;
1628
1629     avio_wb32(pb, 0); /* size */
1630     avio_wl32(pb, track->tag); // store it byteswapped
1631     avio_wb32(pb, 0); /* Reserved */
1632     avio_wb16(pb, 0); /* Reserved */
1633     avio_wb16(pb, 1); /* Data-reference index */
1634
1635     avio_wb16(pb, 0); /* Codec stream version */
1636     avio_wb16(pb, 0); /* Codec stream revision (=0) */
1637     if (track->mode == MODE_MOV) {
1638         ffio_wfourcc(pb, "FFMP"); /* Vendor */
1639         if (track->enc->codec_id == AV_CODEC_ID_RAWVIDEO) {
1640             avio_wb32(pb, 0); /* Temporal Quality */
1641             avio_wb32(pb, 0x400); /* Spatial Quality = lossless*/
1642         } else {
1643             avio_wb32(pb, 0x200); /* Temporal Quality = normal */
1644             avio_wb32(pb, 0x200); /* Spatial Quality = normal */
1645         }
1646     } else {
1647         avio_wb32(pb, 0); /* Reserved */
1648         avio_wb32(pb, 0); /* Reserved */
1649         avio_wb32(pb, 0); /* Reserved */
1650     }
1651     avio_wb16(pb, track->enc->width); /* Video width */
1652     avio_wb16(pb, track->height); /* Video height */
1653     avio_wb32(pb, 0x00480000); /* Horizontal resolution 72dpi */
1654     avio_wb32(pb, 0x00480000); /* Vertical resolution 72dpi */
1655     avio_wb32(pb, 0); /* Data size (= 0) */
1656     avio_wb16(pb, 1); /* Frame count (= 1) */
1657
1658     /* FIXME not sure, ISO 14496-1 draft where it shall be set to 0 */
1659     find_compressor(compressor_name, 32, track);
1660     avio_w8(pb, strlen(compressor_name));
1661     avio_write(pb, compressor_name, 31);
1662
1663     if (track->mode == MODE_MOV && track->enc->bits_per_coded_sample)
1664         avio_wb16(pb, track->enc->bits_per_coded_sample);
1665     else
1666         avio_wb16(pb, 0x18); /* Reserved */
1667     avio_wb16(pb, 0xffff); /* Reserved */
1668     if (track->tag == MKTAG('m','p','4','v'))
1669         mov_write_esds_tag(pb, track);
1670     else if (track->enc->codec_id == AV_CODEC_ID_H263)
1671         mov_write_d263_tag(pb);
1672     else if (track->enc->codec_id == AV_CODEC_ID_AVUI ||
1673             track->enc->codec_id == AV_CODEC_ID_SVQ3) {
1674         mov_write_extradata_tag(pb, track);
1675         avio_wb32(pb, 0);
1676     } else if (track->enc->codec_id == AV_CODEC_ID_DNXHD) {
1677         mov_write_avid_tag(pb, track);
1678         avid = 1;
1679     } else if (track->enc->codec_id == AV_CODEC_ID_HEVC)
1680         mov_write_hvcc_tag(pb, track);
1681     else if (track->enc->codec_id == AV_CODEC_ID_H264 && !TAG_IS_AVCI(track->tag)) {
1682         mov_write_avcc_tag(pb, track);
1683         if (track->mode == MODE_IPOD)
1684             mov_write_uuid_tag_ipod(pb);
1685     } else if (track->enc->codec_id == AV_CODEC_ID_VC1 && track->vos_len > 0)
1686         mov_write_dvc1_tag(pb, track);
1687     else if (track->enc->codec_id == AV_CODEC_ID_VP6F ||
1688              track->enc->codec_id == AV_CODEC_ID_VP6A) {
1689         /* Don't write any potential extradata here - the cropping
1690          * is signalled via the normal width/height fields. */
1691     } else if (track->enc->codec_id == AV_CODEC_ID_R10K) {
1692         if (track->enc->codec_tag == MKTAG('R','1','0','k'))
1693             mov_write_dpxe_tag(pb, track);
1694     } else if (track->vos_len > 0)
1695         mov_write_glbl_tag(pb, track);
1696
1697     if (track->enc->codec_id != AV_CODEC_ID_H264 &&
1698         track->enc->codec_id != AV_CODEC_ID_MPEG4 &&
1699         track->enc->codec_id != AV_CODEC_ID_DNXHD)
1700         if (track->enc->field_order != AV_FIELD_UNKNOWN)
1701             mov_write_fiel_tag(pb, track);
1702
1703     if (mov->flags & FF_MOV_FLAG_WRITE_COLR) {
1704         if (track->mode == MODE_MOV || track->mode == MODE_MP4)
1705             mov_write_colr_tag(pb, track);
1706         else
1707             av_log(mov->fc, AV_LOG_WARNING, "Not writing 'colr' atom. Format is not MOV or MP4.\n");
1708     }
1709
1710     if (track->enc->sample_aspect_ratio.den && track->enc->sample_aspect_ratio.num &&
1711         track->enc->sample_aspect_ratio.den != track->enc->sample_aspect_ratio.num) {
1712         mov_write_pasp_tag(pb, track);
1713     }
1714
1715     /* extra padding for avid stsd */
1716     /* https://developer.apple.com/library/mac/documentation/QuickTime/QTFF/QTFFChap2/qtff2.html#//apple_ref/doc/uid/TP40000939-CH204-61112 */
1717     if (avid)
1718         avio_wb32(pb, 0);
1719
1720     return update_size(pb, pos);
1721 }
1722
1723 static int mov_write_rtp_tag(AVIOContext *pb, MOVTrack *track)
1724 {
1725     int64_t pos = avio_tell(pb);
1726     avio_wb32(pb, 0); /* size */
1727     ffio_wfourcc(pb, "rtp ");
1728     avio_wb32(pb, 0); /* Reserved */
1729     avio_wb16(pb, 0); /* Reserved */
1730     avio_wb16(pb, 1); /* Data-reference index */
1731
1732     avio_wb16(pb, 1); /* Hint track version */
1733     avio_wb16(pb, 1); /* Highest compatible version */
1734     avio_wb32(pb, track->max_packet_size); /* Max packet size */
1735
1736     avio_wb32(pb, 12); /* size */
1737     ffio_wfourcc(pb, "tims");
1738     avio_wb32(pb, track->timescale);
1739
1740     return update_size(pb, pos);
1741 }
1742
1743 static int mov_write_source_reference_tag(AVIOContext *pb, MOVTrack *track, const char *reel_name)
1744 {
1745     uint64_t str_size =strlen(reel_name);
1746     int64_t pos = avio_tell(pb);
1747
1748     if (str_size >= UINT16_MAX){
1749         av_log(NULL, AV_LOG_ERROR, "reel_name length %"PRIu64" is too large\n", str_size);
1750         avio_wb16(pb, 0);
1751         return AVERROR(EINVAL);
1752     }
1753
1754     avio_wb32(pb, 0);                              /* size */
1755     ffio_wfourcc(pb, "name");                      /* Data format */
1756     avio_wb16(pb, str_size);                       /* string size */
1757     avio_wb16(pb, track->language);                /* langcode */
1758     avio_write(pb, reel_name, str_size);           /* reel name */
1759     return update_size(pb,pos);
1760 }
1761
1762 static int mov_write_tmcd_tag(AVIOContext *pb, MOVTrack *track)
1763 {
1764     int64_t pos = avio_tell(pb);
1765 #if 1
1766     int frame_duration = av_rescale(track->timescale, track->enc->time_base.num, track->enc->time_base.den);
1767     int nb_frames = 1.0/av_q2d(track->enc->time_base) + 0.5;
1768     AVDictionaryEntry *t = NULL;
1769
1770     if (nb_frames > 255) {
1771         av_log(NULL, AV_LOG_ERROR, "fps %d is too large\n", nb_frames);
1772         return AVERROR(EINVAL);
1773     }
1774
1775     avio_wb32(pb, 0); /* size */
1776     ffio_wfourcc(pb, "tmcd");               /* Data format */
1777     avio_wb32(pb, 0);                       /* Reserved */
1778     avio_wb32(pb, 1);                       /* Data reference index */
1779     avio_wb32(pb, 0);                       /* Flags */
1780     avio_wb32(pb, track->timecode_flags);   /* Flags (timecode) */
1781     avio_wb32(pb, track->timescale);        /* Timescale */
1782     avio_wb32(pb, frame_duration);          /* Frame duration */
1783     avio_w8(pb, nb_frames);                 /* Number of frames */
1784     avio_w8(pb, 0);                         /* Reserved */
1785
1786     if (track->st)
1787         t = av_dict_get(track->st->metadata, "reel_name", NULL, 0);
1788
1789     if (t && utf8len(t->value))
1790         mov_write_source_reference_tag(pb, track, t->value);
1791     else
1792         avio_wb16(pb, 0); /* zero size */
1793 #else
1794
1795     avio_wb32(pb, 0); /* size */
1796     ffio_wfourcc(pb, "tmcd");               /* Data format */
1797     avio_wb32(pb, 0);                       /* Reserved */
1798     avio_wb32(pb, 1);                       /* Data reference index */
1799     if (track->enc->extradata_size)
1800         avio_write(pb, track->enc->extradata, track->enc->extradata_size);
1801 #endif
1802     return update_size(pb, pos);
1803 }
1804
1805 static int mov_write_stsd_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
1806 {
1807     int64_t pos = avio_tell(pb);
1808     avio_wb32(pb, 0); /* size */
1809     ffio_wfourcc(pb, "stsd");
1810     avio_wb32(pb, 0); /* version & flags */
1811     avio_wb32(pb, 1); /* entry count */
1812     if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO)
1813         mov_write_video_tag(pb, mov,  track);
1814     else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
1815         mov_write_audio_tag(pb, track);
1816     else if (track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE)
1817         mov_write_subtitle_tag(pb, track);
1818     else if (track->enc->codec_tag == MKTAG('r','t','p',' '))
1819         mov_write_rtp_tag(pb, track);
1820     else if (track->enc->codec_tag == MKTAG('t','m','c','d'))
1821         mov_write_tmcd_tag(pb, track);
1822     return update_size(pb, pos);
1823 }
1824
1825 static int mov_write_ctts_tag(AVIOContext *pb, MOVTrack *track)
1826 {
1827     MOVStts *ctts_entries;
1828     uint32_t entries = 0;
1829     uint32_t atom_size;
1830     int i;
1831
1832     ctts_entries = av_malloc_array((track->entry + 1), sizeof(*ctts_entries)); /* worst case */
1833     if (!ctts_entries)
1834         return AVERROR(ENOMEM);
1835     ctts_entries[0].count = 1;
1836     ctts_entries[0].duration = track->cluster[0].cts;
1837     for (i = 1; i < track->entry; i++) {
1838         if (track->cluster[i].cts == ctts_entries[entries].duration) {
1839             ctts_entries[entries].count++; /* compress */
1840         } else {
1841             entries++;
1842             ctts_entries[entries].duration = track->cluster[i].cts;
1843             ctts_entries[entries].count = 1;
1844         }
1845     }
1846     entries++; /* last one */
1847     atom_size = 16 + (entries * 8);
1848     avio_wb32(pb, atom_size); /* size */
1849     ffio_wfourcc(pb, "ctts");
1850     avio_wb32(pb, 0); /* version & flags */
1851     avio_wb32(pb, entries); /* entry count */
1852     for (i = 0; i < entries; i++) {
1853         avio_wb32(pb, ctts_entries[i].count);
1854         avio_wb32(pb, ctts_entries[i].duration);
1855     }
1856     av_free(ctts_entries);
1857     return atom_size;
1858 }
1859
1860 /* Time to sample atom */
1861 static int mov_write_stts_tag(AVIOContext *pb, MOVTrack *track)
1862 {
1863     MOVStts *stts_entries;
1864     uint32_t entries = -1;
1865     uint32_t atom_size;
1866     int i;
1867
1868     if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO && !track->audio_vbr) {
1869         stts_entries = av_malloc(sizeof(*stts_entries)); /* one entry */
1870         if (!stts_entries)
1871             return AVERROR(ENOMEM);
1872         stts_entries[0].count = track->sample_count;
1873         stts_entries[0].duration = 1;
1874         entries = 1;
1875     } else {
1876         stts_entries = track->entry ?
1877                        av_malloc_array(track->entry, sizeof(*stts_entries)) : /* worst case */
1878                        NULL;
1879         if (track->entry && !stts_entries)
1880             return AVERROR(ENOMEM);
1881         for (i = 0; i < track->entry; i++) {
1882             int duration = get_cluster_duration(track, i);
1883             if (i && duration == stts_entries[entries].duration) {
1884                 stts_entries[entries].count++; /* compress */
1885             } else {
1886                 entries++;
1887                 stts_entries[entries].duration = duration;
1888                 stts_entries[entries].count = 1;
1889             }
1890         }
1891         entries++; /* last one */
1892     }
1893     atom_size = 16 + (entries * 8);
1894     avio_wb32(pb, atom_size); /* size */
1895     ffio_wfourcc(pb, "stts");
1896     avio_wb32(pb, 0); /* version & flags */
1897     avio_wb32(pb, entries); /* entry count */
1898     for (i = 0; i < entries; i++) {
1899         avio_wb32(pb, stts_entries[i].count);
1900         avio_wb32(pb, stts_entries[i].duration);
1901     }
1902     av_free(stts_entries);
1903     return atom_size;
1904 }
1905
1906 static int mov_write_dref_tag(AVIOContext *pb)
1907 {
1908     avio_wb32(pb, 28); /* size */
1909     ffio_wfourcc(pb, "dref");
1910     avio_wb32(pb, 0); /* version & flags */
1911     avio_wb32(pb, 1); /* entry count */
1912
1913     avio_wb32(pb, 0xc); /* size */
1914     //FIXME add the alis and rsrc atom
1915     ffio_wfourcc(pb, "url ");
1916     avio_wb32(pb, 1); /* version & flags */
1917
1918     return 28;
1919 }
1920
1921 static int mov_write_stbl_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
1922 {
1923     int64_t pos = avio_tell(pb);
1924     int ret;
1925
1926     avio_wb32(pb, 0); /* size */
1927     ffio_wfourcc(pb, "stbl");
1928     mov_write_stsd_tag(pb, mov, track);
1929     mov_write_stts_tag(pb, track);
1930     if ((track->enc->codec_type == AVMEDIA_TYPE_VIDEO ||
1931          track->enc->codec_tag == MKTAG('r','t','p',' ')) &&
1932         track->has_keyframes && track->has_keyframes < track->entry)
1933         mov_write_stss_tag(pb, track, MOV_SYNC_SAMPLE);
1934     if (track->mode == MODE_MOV && track->flags & MOV_TRACK_STPS)
1935         mov_write_stss_tag(pb, track, MOV_PARTIAL_SYNC_SAMPLE);
1936     if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO &&
1937         track->flags & MOV_TRACK_CTTS && track->entry) {
1938
1939         if ((ret = mov_write_ctts_tag(pb, track)) < 0)
1940             return ret;
1941     }
1942     mov_write_stsc_tag(pb, track);
1943     mov_write_stsz_tag(pb, track);
1944     mov_write_stco_tag(pb, track);
1945     return update_size(pb, pos);
1946 }
1947
1948 static int mov_write_dinf_tag(AVIOContext *pb)
1949 {
1950     int64_t pos = avio_tell(pb);
1951     avio_wb32(pb, 0); /* size */
1952     ffio_wfourcc(pb, "dinf");
1953     mov_write_dref_tag(pb);
1954     return update_size(pb, pos);
1955 }
1956
1957 static int mov_write_nmhd_tag(AVIOContext *pb)
1958 {
1959     avio_wb32(pb, 12);
1960     ffio_wfourcc(pb, "nmhd");
1961     avio_wb32(pb, 0);
1962     return 12;
1963 }
1964
1965 static int mov_write_tcmi_tag(AVIOContext *pb, MOVTrack *track)
1966 {
1967     int64_t pos = avio_tell(pb);
1968     const char *font = "Lucida Grande";
1969     avio_wb32(pb, 0);                   /* size */
1970     ffio_wfourcc(pb, "tcmi");           /* timecode media information atom */
1971     avio_wb32(pb, 0);                   /* version & flags */
1972     avio_wb16(pb, 0);                   /* text font */
1973     avio_wb16(pb, 0);                   /* text face */
1974     avio_wb16(pb, 12);                  /* text size */
1975     avio_wb16(pb, 0);                   /* (unknown, not in the QT specs...) */
1976     avio_wb16(pb, 0x0000);              /* text color (red) */
1977     avio_wb16(pb, 0x0000);              /* text color (green) */
1978     avio_wb16(pb, 0x0000);              /* text color (blue) */
1979     avio_wb16(pb, 0xffff);              /* background color (red) */
1980     avio_wb16(pb, 0xffff);              /* background color (green) */
1981     avio_wb16(pb, 0xffff);              /* background color (blue) */
1982     avio_w8(pb, strlen(font));          /* font len (part of the pascal string) */
1983     avio_write(pb, font, strlen(font)); /* font name */
1984     return update_size(pb, pos);
1985 }
1986
1987 static int mov_write_gmhd_tag(AVIOContext *pb, MOVTrack *track)
1988 {
1989     int64_t pos = avio_tell(pb);
1990     avio_wb32(pb, 0);      /* size */
1991     ffio_wfourcc(pb, "gmhd");
1992     avio_wb32(pb, 0x18);   /* gmin size */
1993     ffio_wfourcc(pb, "gmin");/* generic media info */
1994     avio_wb32(pb, 0);      /* version & flags */
1995     avio_wb16(pb, 0x40);   /* graphics mode = */
1996     avio_wb16(pb, 0x8000); /* opColor (r?) */
1997     avio_wb16(pb, 0x8000); /* opColor (g?) */
1998     avio_wb16(pb, 0x8000); /* opColor (b?) */
1999     avio_wb16(pb, 0);      /* balance */
2000     avio_wb16(pb, 0);      /* reserved */
2001
2002     /*
2003      * This special text atom is required for
2004      * Apple Quicktime chapters. The contents
2005      * don't appear to be documented, so the
2006      * bytes are copied verbatim.
2007      */
2008     if (track->tag != MKTAG('c','6','0','8')) {
2009     avio_wb32(pb, 0x2C);   /* size */
2010     ffio_wfourcc(pb, "text");
2011     avio_wb16(pb, 0x01);
2012     avio_wb32(pb, 0x00);
2013     avio_wb32(pb, 0x00);
2014     avio_wb32(pb, 0x00);
2015     avio_wb32(pb, 0x01);
2016     avio_wb32(pb, 0x00);
2017     avio_wb32(pb, 0x00);
2018     avio_wb32(pb, 0x00);
2019     avio_wb32(pb, 0x00004000);
2020     avio_wb16(pb, 0x0000);
2021     }
2022
2023     if (track->enc->codec_tag == MKTAG('t','m','c','d')) {
2024         int64_t tmcd_pos = avio_tell(pb);
2025         avio_wb32(pb, 0); /* size */
2026         ffio_wfourcc(pb, "tmcd");
2027         mov_write_tcmi_tag(pb, track);
2028         update_size(pb, tmcd_pos);
2029     }
2030     return update_size(pb, pos);
2031 }
2032
2033 static int mov_write_smhd_tag(AVIOContext *pb)
2034 {
2035     avio_wb32(pb, 16); /* size */
2036     ffio_wfourcc(pb, "smhd");
2037     avio_wb32(pb, 0); /* version & flags */
2038     avio_wb16(pb, 0); /* reserved (balance, normally = 0) */
2039     avio_wb16(pb, 0); /* reserved */
2040     return 16;
2041 }
2042
2043 static int mov_write_vmhd_tag(AVIOContext *pb)
2044 {
2045     avio_wb32(pb, 0x14); /* size (always 0x14) */
2046     ffio_wfourcc(pb, "vmhd");
2047     avio_wb32(pb, 0x01); /* version & flags */
2048     avio_wb64(pb, 0); /* reserved (graphics mode = copy) */
2049     return 0x14;
2050 }
2051
2052 static int is_clcp_track(MOVTrack *track)
2053 {
2054     return track->tag == MKTAG('c','7','0','8') ||
2055            track->tag == MKTAG('c','6','0','8');
2056 }
2057
2058 static int mov_write_hdlr_tag(AVIOContext *pb, MOVTrack *track)
2059 {
2060     const char *hdlr, *descr = NULL, *hdlr_type = NULL;
2061     int64_t pos = avio_tell(pb);
2062
2063     hdlr      = "dhlr";
2064     hdlr_type = "url ";
2065     descr     = "DataHandler";
2066
2067     if (track) {
2068         hdlr = (track->mode == MODE_MOV) ? "mhlr" : "\0\0\0\0";
2069         if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) {
2070             hdlr_type = "vide";
2071             descr     = "VideoHandler";
2072         } else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO) {
2073             hdlr_type = "soun";
2074             descr     = "SoundHandler";
2075         } else if (track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE) {
2076             if (is_clcp_track(track)) {
2077                 hdlr_type = "clcp";
2078                 descr = "ClosedCaptionHandler";
2079             } else {
2080                 if (track->tag == MKTAG('t','x','3','g')) {
2081                     hdlr_type = "sbtl";
2082                 } else if (track->tag == MKTAG('m','p','4','s')) {
2083                     hdlr_type = "subp";
2084                 } else {
2085                     hdlr_type = "text";
2086                 }
2087             descr = "SubtitleHandler";
2088             }
2089         } else if (track->enc->codec_tag == MKTAG('r','t','p',' ')) {
2090             hdlr_type = "hint";
2091             descr     = "HintHandler";
2092         } else if (track->enc->codec_tag == MKTAG('t','m','c','d')) {
2093             hdlr_type = "tmcd";
2094             descr = "TimeCodeHandler";
2095         } else {
2096             char tag_buf[32];
2097             av_get_codec_tag_string(tag_buf, sizeof(tag_buf),
2098                                     track->enc->codec_tag);
2099
2100             av_log(track->enc, AV_LOG_WARNING,
2101                    "Unknown hldr_type for %s / 0x%04X, writing dummy values\n",
2102                    tag_buf, track->enc->codec_tag);
2103         }
2104         if (track->st) {
2105             // hdlr.name is used by some players to identify the content title
2106             // of the track. So if an alternate handler description is
2107             // specified, use it.
2108             AVDictionaryEntry *t;
2109             t = av_dict_get(track->st->metadata, "handler", NULL, 0);
2110             if (t && utf8len(t->value))
2111                 descr = t->value;
2112         }
2113     }
2114
2115     avio_wb32(pb, 0); /* size */
2116     ffio_wfourcc(pb, "hdlr");
2117     avio_wb32(pb, 0); /* Version & flags */
2118     avio_write(pb, hdlr, 4); /* handler */
2119     ffio_wfourcc(pb, hdlr_type); /* handler type */
2120     avio_wb32(pb, 0); /* reserved */
2121     avio_wb32(pb, 0); /* reserved */
2122     avio_wb32(pb, 0); /* reserved */
2123     if (!track || track->mode == MODE_MOV)
2124         avio_w8(pb, strlen(descr)); /* pascal string */
2125     avio_write(pb, descr, strlen(descr)); /* handler description */
2126     if (track && track->mode != MODE_MOV)
2127         avio_w8(pb, 0); /* c string */
2128     return update_size(pb, pos);
2129 }
2130
2131 static int mov_write_hmhd_tag(AVIOContext *pb)
2132 {
2133     /* This atom must be present, but leaving the values at zero
2134      * seems harmless. */
2135     avio_wb32(pb, 28); /* size */
2136     ffio_wfourcc(pb, "hmhd");
2137     avio_wb32(pb, 0); /* version, flags */
2138     avio_wb16(pb, 0); /* maxPDUsize */
2139     avio_wb16(pb, 0); /* avgPDUsize */
2140     avio_wb32(pb, 0); /* maxbitrate */
2141     avio_wb32(pb, 0); /* avgbitrate */
2142     avio_wb32(pb, 0); /* reserved */
2143     return 28;
2144 }
2145
2146 static int mov_write_minf_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
2147 {
2148     int64_t pos = avio_tell(pb);
2149     int ret;
2150
2151     avio_wb32(pb, 0); /* size */
2152     ffio_wfourcc(pb, "minf");
2153     if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO)
2154         mov_write_vmhd_tag(pb);
2155     else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
2156         mov_write_smhd_tag(pb);
2157     else if (track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE) {
2158         if (track->tag == MKTAG('t','e','x','t') || is_clcp_track(track)) {
2159             mov_write_gmhd_tag(pb, track);
2160         } else {
2161             mov_write_nmhd_tag(pb);
2162         }
2163     } else if (track->tag == MKTAG('r','t','p',' ')) {
2164         mov_write_hmhd_tag(pb);
2165     } else if (track->tag == MKTAG('t','m','c','d')) {
2166         mov_write_gmhd_tag(pb, track);
2167     }
2168     if (track->mode == MODE_MOV) /* FIXME: Why do it for MODE_MOV only ? */
2169         mov_write_hdlr_tag(pb, NULL);
2170     mov_write_dinf_tag(pb);
2171     if ((ret = mov_write_stbl_tag(pb, mov, track)) < 0)
2172         return ret;
2173     return update_size(pb, pos);
2174 }
2175
2176 static int mov_write_mdhd_tag(AVIOContext *pb, MOVMuxContext *mov,
2177                               MOVTrack *track)
2178 {
2179     int version = track->track_duration < INT32_MAX ? 0 : 1;
2180
2181     if (track->mode == MODE_ISM)
2182         version = 1;
2183
2184     (version == 1) ? avio_wb32(pb, 44) : avio_wb32(pb, 32); /* size */
2185     ffio_wfourcc(pb, "mdhd");
2186     avio_w8(pb, version);
2187     avio_wb24(pb, 0); /* flags */
2188     if (version == 1) {
2189         avio_wb64(pb, track->time);
2190         avio_wb64(pb, track->time);
2191     } else {
2192         avio_wb32(pb, track->time); /* creation time */
2193         avio_wb32(pb, track->time); /* modification time */
2194     }
2195     avio_wb32(pb, track->timescale); /* time scale (sample rate for audio) */
2196     if (!track->entry && mov->mode == MODE_ISM)
2197         (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
2198     else if (!track->entry)
2199         (version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0);
2200     else
2201         (version == 1) ? avio_wb64(pb, track->track_duration) : avio_wb32(pb, track->track_duration); /* duration */
2202     avio_wb16(pb, track->language); /* language */
2203     avio_wb16(pb, 0); /* reserved (quality) */
2204
2205     if (version != 0 && track->mode == MODE_MOV) {
2206         av_log(NULL, AV_LOG_ERROR,
2207                "FATAL error, file duration too long for timebase, this file will not be\n"
2208                "playable with quicktime. Choose a different timebase or a different\n"
2209                "container format\n");
2210     }
2211
2212     return 32;
2213 }
2214
2215 static int mov_write_mdia_tag(AVIOContext *pb, MOVMuxContext *mov,
2216                               MOVTrack *track)
2217 {
2218     int64_t pos = avio_tell(pb);
2219     int ret;
2220
2221     avio_wb32(pb, 0); /* size */
2222     ffio_wfourcc(pb, "mdia");
2223     mov_write_mdhd_tag(pb, mov, track);
2224     mov_write_hdlr_tag(pb, track);
2225     if ((ret = mov_write_minf_tag(pb, mov, track)) < 0)
2226         return ret;
2227     return update_size(pb, pos);
2228 }
2229
2230 /* transformation matrix
2231      |a  b  u|
2232      |c  d  v|
2233      |tx ty w| */
2234 static void write_matrix(AVIOContext *pb, int16_t a, int16_t b, int16_t c,
2235                          int16_t d, int16_t tx, int16_t ty)
2236 {
2237     avio_wb32(pb, a << 16);  /* 16.16 format */
2238     avio_wb32(pb, b << 16);  /* 16.16 format */
2239     avio_wb32(pb, 0);        /* u in 2.30 format */
2240     avio_wb32(pb, c << 16);  /* 16.16 format */
2241     avio_wb32(pb, d << 16);  /* 16.16 format */
2242     avio_wb32(pb, 0);        /* v in 2.30 format */
2243     avio_wb32(pb, tx << 16); /* 16.16 format */
2244     avio_wb32(pb, ty << 16); /* 16.16 format */
2245     avio_wb32(pb, 1 << 30);  /* w in 2.30 format */
2246 }
2247
2248 static int mov_write_tkhd_tag(AVIOContext *pb, MOVMuxContext *mov,
2249                               MOVTrack *track, AVStream *st)
2250 {
2251     int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE,
2252                                       track->timescale, AV_ROUND_UP);
2253     int version = duration < INT32_MAX ? 0 : 1;
2254     int flags   = MOV_TKHD_FLAG_IN_MOVIE;
2255     int rotation = 0;
2256     int group   = 0;
2257
2258
2259     if (st) {
2260         if (mov->per_stream_grouping)
2261             group = st->index;
2262         else
2263             group = st->codec->codec_type;
2264     }
2265
2266     if (track->flags & MOV_TRACK_ENABLED)
2267         flags |= MOV_TKHD_FLAG_ENABLED;
2268
2269     if (track->mode == MODE_ISM)
2270         version = 1;
2271
2272     (version == 1) ? avio_wb32(pb, 104) : avio_wb32(pb, 92); /* size */
2273     ffio_wfourcc(pb, "tkhd");
2274     avio_w8(pb, version);
2275     avio_wb24(pb, flags);
2276     if (version == 1) {
2277         avio_wb64(pb, track->time);
2278         avio_wb64(pb, track->time);
2279     } else {
2280         avio_wb32(pb, track->time); /* creation time */
2281         avio_wb32(pb, track->time); /* modification time */
2282     }
2283     avio_wb32(pb, track->track_id); /* track-id */
2284     avio_wb32(pb, 0); /* reserved */
2285     if (!track->entry && mov->mode == MODE_ISM)
2286         (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
2287     else if (!track->entry)
2288         (version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0);
2289     else
2290         (version == 1) ? avio_wb64(pb, duration) : avio_wb32(pb, duration);
2291
2292     avio_wb32(pb, 0); /* reserved */
2293     avio_wb32(pb, 0); /* reserved */
2294     avio_wb16(pb, 0); /* layer */
2295     avio_wb16(pb, group); /* alternate group) */
2296     /* Volume, only for audio */
2297     if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
2298         avio_wb16(pb, 0x0100);
2299     else
2300         avio_wb16(pb, 0);
2301     avio_wb16(pb, 0); /* reserved */
2302
2303     /* Matrix structure */
2304     if (st && st->metadata) {
2305         AVDictionaryEntry *rot = av_dict_get(st->metadata, "rotate", NULL, 0);
2306         rotation = (rot && rot->value) ? atoi(rot->value) : 0;
2307     }
2308     if (rotation == 90) {
2309         write_matrix(pb,  0,  1, -1,  0, track->enc->height, 0);
2310     } else if (rotation == 180) {
2311         write_matrix(pb, -1,  0,  0, -1, track->enc->width, track->enc->height);
2312     } else if (rotation == 270) {
2313         write_matrix(pb,  0, -1,  1,  0, 0, track->enc->width);
2314     } else {
2315         write_matrix(pb,  1,  0,  0,  1, 0, 0);
2316     }
2317     /* Track width and height, for visual only */
2318     if (st && (track->enc->codec_type == AVMEDIA_TYPE_VIDEO ||
2319                track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE)) {
2320         if (track->mode == MODE_MOV) {
2321             avio_wb32(pb, track->enc->width << 16);
2322             avio_wb32(pb, track->height << 16);
2323         } else {
2324             double sample_aspect_ratio = av_q2d(st->sample_aspect_ratio);
2325             if (!sample_aspect_ratio || track->height != track->enc->height)
2326                 sample_aspect_ratio = 1;
2327             avio_wb32(pb, sample_aspect_ratio * track->enc->width * 0x10000);
2328             avio_wb32(pb, track->height * 0x10000);
2329         }
2330     } else {
2331         avio_wb32(pb, 0);
2332         avio_wb32(pb, 0);
2333     }
2334     return 0x5c;
2335 }
2336
2337 static int mov_write_tapt_tag(AVIOContext *pb, MOVTrack *track)
2338 {
2339     int32_t width = av_rescale(track->enc->sample_aspect_ratio.num, track->enc->width,
2340                                track->enc->sample_aspect_ratio.den);
2341
2342     int64_t pos = avio_tell(pb);
2343
2344     avio_wb32(pb, 0); /* size */
2345     ffio_wfourcc(pb, "tapt");
2346
2347     avio_wb32(pb, 20);
2348     ffio_wfourcc(pb, "clef");
2349     avio_wb32(pb, 0);
2350     avio_wb32(pb, width << 16);
2351     avio_wb32(pb, track->enc->height << 16);
2352
2353     avio_wb32(pb, 20);
2354     ffio_wfourcc(pb, "prof");
2355     avio_wb32(pb, 0);
2356     avio_wb32(pb, width << 16);
2357     avio_wb32(pb, track->enc->height << 16);
2358
2359     avio_wb32(pb, 20);
2360     ffio_wfourcc(pb, "enof");
2361     avio_wb32(pb, 0);
2362     avio_wb32(pb, track->enc->width << 16);
2363     avio_wb32(pb, track->enc->height << 16);
2364
2365     return update_size(pb, pos);
2366 }
2367
2368 // This box seems important for the psp playback ... without it the movie seems to hang
2369 static int mov_write_edts_tag(AVIOContext *pb, MOVMuxContext *mov,
2370                               MOVTrack *track)
2371 {
2372     int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE,
2373                                       track->timescale, AV_ROUND_UP);
2374     int version = duration < INT32_MAX ? 0 : 1;
2375     int entry_size, entry_count, size;
2376     int64_t delay, start_ct = track->start_cts;
2377     int64_t start_dts = track->start_dts;
2378
2379     if (track->entry) {
2380         if (start_dts != track->cluster[0].dts || start_ct != track->cluster[0].cts) {
2381
2382             av_log(mov->fc, AV_LOG_DEBUG,
2383                    "EDTS using dts:%"PRId64" cts:%d instead of dts:%"PRId64" cts:%"PRId64" tid:%d\n",
2384                    track->cluster[0].dts, track->cluster[0].cts,
2385                    start_dts, start_ct, track->track_id);
2386             start_dts = track->cluster[0].dts;
2387             start_ct  = track->cluster[0].cts;
2388         }
2389     }
2390
2391     delay = av_rescale_rnd(start_dts + start_ct, MOV_TIMESCALE,
2392                            track->timescale, AV_ROUND_DOWN);
2393     version |= delay < INT32_MAX ? 0 : 1;
2394
2395     entry_size = (version == 1) ? 20 : 12;
2396     entry_count = 1 + (delay > 0);
2397     size = 24 + entry_count * entry_size;
2398
2399     /* write the atom data */
2400     avio_wb32(pb, size);
2401     ffio_wfourcc(pb, "edts");
2402     avio_wb32(pb, size - 8);
2403     ffio_wfourcc(pb, "elst");
2404     avio_w8(pb, version);
2405     avio_wb24(pb, 0); /* flags */
2406
2407     avio_wb32(pb, entry_count);
2408     if (delay > 0) { /* add an empty edit to delay presentation */
2409         /* In the positive delay case, the delay includes the cts
2410          * offset, and the second edit list entry below trims out
2411          * the same amount from the actual content. This makes sure
2412          * that the offsetted last sample is included in the edit
2413          * list duration as well. */
2414         if (version == 1) {
2415             avio_wb64(pb, delay);
2416             avio_wb64(pb, -1);
2417         } else {
2418             avio_wb32(pb, delay);
2419             avio_wb32(pb, -1);
2420         }
2421         avio_wb32(pb, 0x00010000);
2422     } else {
2423         /* Avoid accidentally ending up with start_ct = -1 which has got a
2424          * special meaning. Normally start_ct should end up positive or zero
2425          * here, but use FFMIN in case dts is a a small positive integer
2426          * rounded to 0 when represented in MOV_TIMESCALE units. */
2427         av_assert0(av_rescale_rnd(start_dts, MOV_TIMESCALE, track->timescale, AV_ROUND_DOWN) <= 0);
2428         start_ct  = -FFMIN(start_dts, 0);
2429         /* Note, this delay is calculated from the pts of the first sample,
2430          * ensuring that we don't reduce the duration for cases with
2431          * dts<0 pts=0. */
2432         duration += delay;
2433     }
2434
2435     /* For fragmented files, we don't know the full length yet. Setting
2436      * duration to 0 allows us to only specify the offset, including
2437      * the rest of the content (from all future fragments) without specifying
2438      * an explicit duration. */
2439     if (mov->flags & FF_MOV_FLAG_FRAGMENT)
2440         duration = 0;
2441
2442     /* duration */
2443     if (version == 1) {
2444         avio_wb64(pb, duration);
2445         avio_wb64(pb, start_ct);
2446     } else {
2447         avio_wb32(pb, duration);
2448         avio_wb32(pb, start_ct);
2449     }
2450     avio_wb32(pb, 0x00010000);
2451     return size;
2452 }
2453
2454 static int mov_write_tref_tag(AVIOContext *pb, MOVTrack *track)
2455 {
2456     avio_wb32(pb, 20);   // size
2457     ffio_wfourcc(pb, "tref");
2458     avio_wb32(pb, 12);   // size (subatom)
2459     avio_wl32(pb, track->tref_tag);
2460     avio_wb32(pb, track->tref_id);
2461     return 20;
2462 }
2463
2464 // goes at the end of each track!  ... Critical for PSP playback ("Incompatible data" without it)
2465 static int mov_write_uuid_tag_psp(AVIOContext *pb, MOVTrack *mov)
2466 {
2467     avio_wb32(pb, 0x34); /* size ... reports as 28 in mp4box! */
2468     ffio_wfourcc(pb, "uuid");
2469     ffio_wfourcc(pb, "USMT");
2470     avio_wb32(pb, 0x21d24fce);
2471     avio_wb32(pb, 0xbb88695c);
2472     avio_wb32(pb, 0xfac9c740);
2473     avio_wb32(pb, 0x1c);     // another size here!
2474     ffio_wfourcc(pb, "MTDT");
2475     avio_wb32(pb, 0x00010012);
2476     avio_wb32(pb, 0x0a);
2477     avio_wb32(pb, 0x55c40000);
2478     avio_wb32(pb, 0x1);
2479     avio_wb32(pb, 0x0);
2480     return 0x34;
2481 }
2482
2483 static int mov_write_udta_sdp(AVIOContext *pb, MOVTrack *track)
2484 {
2485     AVFormatContext *ctx = track->rtp_ctx;
2486     char buf[1000] = "";
2487     int len;
2488
2489     ff_sdp_write_media(buf, sizeof(buf), ctx->streams[0], track->src_track,
2490                        NULL, NULL, 0, 0, ctx);
2491     av_strlcatf(buf, sizeof(buf), "a=control:streamid=%d\r\n", track->track_id);
2492     len = strlen(buf);
2493
2494     avio_wb32(pb, len + 24);
2495     ffio_wfourcc(pb, "udta");
2496     avio_wb32(pb, len + 16);
2497     ffio_wfourcc(pb, "hnti");
2498     avio_wb32(pb, len + 8);
2499     ffio_wfourcc(pb, "sdp ");
2500     avio_write(pb, buf, len);
2501     return len + 24;
2502 }
2503
2504 static int mov_write_track_metadata(AVIOContext *pb, AVStream *st,
2505                                     const char *tag, const char *str)
2506 {
2507     int64_t pos = avio_tell(pb);
2508     AVDictionaryEntry *t = av_dict_get(st->metadata, str, NULL, 0);
2509     if (!t || !utf8len(t->value))
2510         return 0;
2511
2512     avio_wb32(pb, 0);   /* size */
2513     ffio_wfourcc(pb, tag); /* type */
2514     avio_write(pb, t->value, strlen(t->value)); /* UTF8 string value */
2515     return update_size(pb, pos);
2516 }
2517
2518 static int mov_write_track_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
2519                                     AVStream *st)
2520 {
2521     AVIOContext *pb_buf;
2522     int ret, size;
2523     uint8_t *buf;
2524
2525     if (!st || mov->fc->flags & AVFMT_FLAG_BITEXACT)
2526         return 0;
2527
2528     ret = avio_open_dyn_buf(&pb_buf);
2529     if (ret < 0)
2530         return ret;
2531
2532     if (mov->mode & MODE_MP4)
2533         mov_write_track_metadata(pb_buf, st, "name", "title");
2534
2535     if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) {
2536         avio_wb32(pb, size + 8);
2537         ffio_wfourcc(pb, "udta");
2538         avio_write(pb, buf, size);
2539     }
2540     av_free(buf);
2541
2542     return 0;
2543 }
2544
2545 static int mov_write_trak_tag(AVIOContext *pb, MOVMuxContext *mov,
2546                               MOVTrack *track, AVStream *st)
2547 {
2548     int64_t pos = avio_tell(pb);
2549     int entry_backup = track->entry;
2550     int chunk_backup = track->chunkCount;
2551     int ret;
2552
2553     /* If we want to have an empty moov, but some samples already have been
2554      * buffered (delay_moov), pretend that no samples have been written yet. */
2555     if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV)
2556         track->chunkCount = track->entry = 0;
2557
2558     avio_wb32(pb, 0); /* size */
2559     ffio_wfourcc(pb, "trak");
2560     mov_write_tkhd_tag(pb, mov, track, st);
2561
2562     av_assert2(mov->use_editlist >= 0);
2563
2564     if (track->start_dts != AV_NOPTS_VALUE) {
2565         if (mov->use_editlist)
2566             mov_write_edts_tag(pb, mov, track);  // PSP Movies and several other cases require edts box
2567         else if ((track->entry && track->cluster[0].dts) || track->mode == MODE_PSP || is_clcp_track(track))
2568             av_log(mov->fc, AV_LOG_WARNING,
2569                    "Not writing any edit list even though one would have been required\n");
2570     }
2571
2572     if (track->tref_tag)
2573         mov_write_tref_tag(pb, track);
2574
2575     if ((ret = mov_write_mdia_tag(pb, mov, track)) < 0)
2576         return ret;
2577     if (track->mode == MODE_PSP)
2578         mov_write_uuid_tag_psp(pb, track); // PSP Movies require this uuid box
2579     if (track->tag == MKTAG('r','t','p',' '))
2580         mov_write_udta_sdp(pb, track);
2581     if (track->mode == MODE_MOV) {
2582         if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) {
2583             double sample_aspect_ratio = av_q2d(st->sample_aspect_ratio);
2584             if (st->sample_aspect_ratio.num && 1.0 != sample_aspect_ratio) {
2585                 mov_write_tapt_tag(pb, track);
2586             }
2587         }
2588         if (is_clcp_track(track) && st->sample_aspect_ratio.num) {
2589             mov_write_tapt_tag(pb, track);
2590         }
2591     }
2592     mov_write_track_udta_tag(pb, mov, st);
2593     track->entry = entry_backup;
2594     track->chunkCount = chunk_backup;
2595     return update_size(pb, pos);
2596 }
2597
2598 static int mov_write_iods_tag(AVIOContext *pb, MOVMuxContext *mov)
2599 {
2600     int i, has_audio = 0, has_video = 0;
2601     int64_t pos = avio_tell(pb);
2602     int audio_profile = mov->iods_audio_profile;
2603     int video_profile = mov->iods_video_profile;
2604     for (i = 0; i < mov->nb_streams; i++) {
2605         if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
2606             has_audio |= mov->tracks[i].enc->codec_type == AVMEDIA_TYPE_AUDIO;
2607             has_video |= mov->tracks[i].enc->codec_type == AVMEDIA_TYPE_VIDEO;
2608         }
2609     }
2610     if (audio_profile < 0)
2611         audio_profile = 0xFF - has_audio;
2612     if (video_profile < 0)
2613         video_profile = 0xFF - has_video;
2614     avio_wb32(pb, 0x0); /* size */
2615     ffio_wfourcc(pb, "iods");
2616     avio_wb32(pb, 0);    /* version & flags */
2617     put_descr(pb, 0x10, 7);
2618     avio_wb16(pb, 0x004f);
2619     avio_w8(pb, 0xff);
2620     avio_w8(pb, 0xff);
2621     avio_w8(pb, audio_profile);
2622     avio_w8(pb, video_profile);
2623     avio_w8(pb, 0xff);
2624     return update_size(pb, pos);
2625 }
2626
2627 static int mov_write_trex_tag(AVIOContext *pb, MOVTrack *track)
2628 {
2629     avio_wb32(pb, 0x20); /* size */
2630     ffio_wfourcc(pb, "trex");
2631     avio_wb32(pb, 0);   /* version & flags */
2632     avio_wb32(pb, track->track_id); /* track ID */
2633     avio_wb32(pb, 1);   /* default sample description index */
2634     avio_wb32(pb, 0);   /* default sample duration */
2635     avio_wb32(pb, 0);   /* default sample size */
2636     avio_wb32(pb, 0);   /* default sample flags */
2637     return 0;
2638 }
2639
2640 static int mov_write_mvex_tag(AVIOContext *pb, MOVMuxContext *mov)
2641 {
2642     int64_t pos = avio_tell(pb);
2643     int i;
2644     avio_wb32(pb, 0x0); /* size */
2645     ffio_wfourcc(pb, "mvex");
2646     for (i = 0; i < mov->nb_streams; i++)
2647         mov_write_trex_tag(pb, &mov->tracks[i]);
2648     return update_size(pb, pos);
2649 }
2650
2651 static int mov_write_mvhd_tag(AVIOContext *pb, MOVMuxContext *mov)
2652 {
2653     int max_track_id = 1, i;
2654     int64_t max_track_len = 0;
2655     int version;
2656
2657     for (i = 0; i < mov->nb_streams; i++) {
2658         if (mov->tracks[i].entry > 0 && mov->tracks[i].timescale) {
2659             int64_t max_track_len_temp = av_rescale_rnd(mov->tracks[i].track_duration,
2660                                                 MOV_TIMESCALE,
2661                                                 mov->tracks[i].timescale,
2662                                                 AV_ROUND_UP);
2663             if (max_track_len < max_track_len_temp)
2664                 max_track_len = max_track_len_temp;
2665             if (max_track_id < mov->tracks[i].track_id)
2666                 max_track_id = mov->tracks[i].track_id;
2667         }
2668     }
2669     /* If using delay_moov, make sure the output is the same as if no
2670      * samples had been written yet. */
2671     if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
2672         max_track_len = 0;
2673         max_track_id  = 1;
2674     }
2675
2676     version = max_track_len < UINT32_MAX ? 0 : 1;
2677     avio_wb32(pb, version == 1 ? 120 : 108); /* size */
2678
2679     ffio_wfourcc(pb, "mvhd");
2680     avio_w8(pb, version);
2681     avio_wb24(pb, 0); /* flags */
2682     if (version == 1) {
2683         avio_wb64(pb, mov->time);
2684         avio_wb64(pb, mov->time);
2685     } else {
2686         avio_wb32(pb, mov->time); /* creation time */
2687         avio_wb32(pb, mov->time); /* modification time */
2688     }
2689     avio_wb32(pb, MOV_TIMESCALE);
2690     (version == 1) ? avio_wb64(pb, max_track_len) : avio_wb32(pb, max_track_len); /* duration of longest track */
2691
2692     avio_wb32(pb, 0x00010000); /* reserved (preferred rate) 1.0 = normal */
2693     avio_wb16(pb, 0x0100); /* reserved (preferred volume) 1.0 = normal */
2694     avio_wb16(pb, 0); /* reserved */
2695     avio_wb32(pb, 0); /* reserved */
2696     avio_wb32(pb, 0); /* reserved */
2697
2698     /* Matrix structure */
2699     write_matrix(pb, 1, 0, 0, 1, 0, 0);
2700
2701     avio_wb32(pb, 0); /* reserved (preview time) */
2702     avio_wb32(pb, 0); /* reserved (preview duration) */
2703     avio_wb32(pb, 0); /* reserved (poster time) */
2704     avio_wb32(pb, 0); /* reserved (selection time) */
2705     avio_wb32(pb, 0); /* reserved (selection duration) */
2706     avio_wb32(pb, 0); /* reserved (current time) */
2707     avio_wb32(pb, max_track_id + 1); /* Next track id */
2708     return 0x6c;
2709 }
2710
2711 static int mov_write_itunes_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov,
2712                                      AVFormatContext *s)
2713 {
2714     avio_wb32(pb, 33); /* size */
2715     ffio_wfourcc(pb, "hdlr");
2716     avio_wb32(pb, 0);
2717     avio_wb32(pb, 0);
2718     ffio_wfourcc(pb, "mdir");
2719     ffio_wfourcc(pb, "appl");
2720     avio_wb32(pb, 0);
2721     avio_wb32(pb, 0);
2722     avio_w8(pb, 0);
2723     return 33;
2724 }
2725
2726 /* helper function to write a data tag with the specified string as data */
2727 static int mov_write_string_data_tag(AVIOContext *pb, const char *data, int lang, int long_style)
2728 {
2729     if (long_style) {
2730         int size = 16 + strlen(data);
2731         avio_wb32(pb, size); /* size */
2732         ffio_wfourcc(pb, "data");
2733         avio_wb32(pb, 1);
2734         avio_wb32(pb, 0);
2735         avio_write(pb, data, strlen(data));
2736         return size;
2737     } else {
2738         if (!lang)
2739             lang = ff_mov_iso639_to_lang("und", 1);
2740         avio_wb16(pb, strlen(data)); /* string length */
2741         avio_wb16(pb, lang);
2742         avio_write(pb, data, strlen(data));
2743         return strlen(data) + 4;
2744     }
2745 }
2746
2747 static int mov_write_string_tag(AVIOContext *pb, const char *name,
2748                                 const char *value, int lang, int long_style)
2749 {
2750     int size = 0;
2751     if (value && value[0]) {
2752         int64_t pos = avio_tell(pb);
2753         avio_wb32(pb, 0); /* size */
2754         ffio_wfourcc(pb, name);
2755         mov_write_string_data_tag(pb, value, lang, long_style);
2756         size = update_size(pb, pos);
2757     }
2758     return size;
2759 }
2760
2761 static int mov_write_string_metadata(AVFormatContext *s, AVIOContext *pb,
2762                                      const char *name, const char *tag,
2763                                      int long_style)
2764 {
2765     int l, lang = 0, len, len2;
2766     AVDictionaryEntry *t, *t2 = NULL;
2767     char tag2[16];
2768
2769     if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
2770         return 0;
2771
2772     len = strlen(t->key);
2773     snprintf(tag2, sizeof(tag2), "%s-", tag);
2774     while ((t2 = av_dict_get(s->metadata, tag2, t2, AV_DICT_IGNORE_SUFFIX))) {
2775         len2 = strlen(t2->key);
2776         if (len2 == len + 4 && !strcmp(t->value, t2->value)
2777             && (l = ff_mov_iso639_to_lang(&t2->key[len2 - 3], 1)) >= 0) {
2778             lang = l;
2779             break;
2780         }
2781     }
2782     return mov_write_string_tag(pb, name, t->value, lang, long_style);
2783 }
2784
2785 /* iTunes bpm number */
2786 static int mov_write_tmpo_tag(AVIOContext *pb, AVFormatContext *s)
2787 {
2788     AVDictionaryEntry *t = av_dict_get(s->metadata, "tmpo", NULL, 0);
2789     int size = 0, tmpo = t ? atoi(t->value) : 0;
2790     if (tmpo) {
2791         size = 26;
2792         avio_wb32(pb, size);
2793         ffio_wfourcc(pb, "tmpo");
2794         avio_wb32(pb, size-8); /* size */
2795         ffio_wfourcc(pb, "data");
2796         avio_wb32(pb, 0x15);  //type specifier
2797         avio_wb32(pb, 0);
2798         avio_wb16(pb, tmpo);        // data
2799     }
2800     return size;
2801 }
2802
2803 /* iTunes track or disc number */
2804 static int mov_write_trkn_tag(AVIOContext *pb, MOVMuxContext *mov,
2805                               AVFormatContext *s, int disc)
2806 {
2807     AVDictionaryEntry *t = av_dict_get(s->metadata,
2808                                        disc ? "disc" : "track",
2809                                        NULL, 0);
2810     int size = 0, track = t ? atoi(t->value) : 0;
2811     if (track) {
2812         int tracks = 0;
2813         char *slash = strchr(t->value, '/');
2814         if (slash)
2815             tracks = atoi(slash + 1);
2816         avio_wb32(pb, 32); /* size */
2817         ffio_wfourcc(pb, disc ? "disk" : "trkn");
2818         avio_wb32(pb, 24); /* size */
2819         ffio_wfourcc(pb, "data");
2820         avio_wb32(pb, 0);        // 8 bytes empty
2821         avio_wb32(pb, 0);
2822         avio_wb16(pb, 0);        // empty
2823         avio_wb16(pb, track);    // track / disc number
2824         avio_wb16(pb, tracks);   // total track / disc number
2825         avio_wb16(pb, 0);        // empty
2826         size = 32;
2827     }
2828     return size;
2829 }
2830
2831 static int mov_write_int8_metadata(AVFormatContext *s, AVIOContext *pb,
2832                                    const char *name, const char *tag,
2833                                    int len)
2834 {
2835     AVDictionaryEntry *t = NULL;
2836     uint8_t num;
2837     int size = 24 + len;
2838
2839     if (len != 1 && len != 4)
2840         return -1;
2841
2842     if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
2843         return 0;
2844     num = atoi(t->value);
2845
2846     avio_wb32(pb, size);
2847     ffio_wfourcc(pb, name);
2848     avio_wb32(pb, size - 8);
2849     ffio_wfourcc(pb, "data");
2850     avio_wb32(pb, 0x15);
2851     avio_wb32(pb, 0);
2852     if (len==4) avio_wb32(pb, num);
2853     else        avio_w8 (pb, num);
2854
2855     return size;
2856 }
2857
2858 /* iTunes meta data list */
2859 static int mov_write_ilst_tag(AVIOContext *pb, MOVMuxContext *mov,
2860                               AVFormatContext *s)
2861 {
2862     int64_t pos = avio_tell(pb);
2863     avio_wb32(pb, 0); /* size */
2864     ffio_wfourcc(pb, "ilst");
2865     mov_write_string_metadata(s, pb, "\251nam", "title"    , 1);
2866     mov_write_string_metadata(s, pb, "\251ART", "artist"   , 1);
2867     mov_write_string_metadata(s, pb, "aART", "album_artist", 1);
2868     mov_write_string_metadata(s, pb, "\251wrt", "composer" , 1);
2869     mov_write_string_metadata(s, pb, "\251alb", "album"    , 1);
2870     mov_write_string_metadata(s, pb, "\251day", "date"     , 1);
2871     if (!mov->exact &&
2872         !mov_write_string_metadata(s, pb, "\251too", "encoding_tool", 1))
2873         mov_write_string_tag(pb, "\251too", LIBAVFORMAT_IDENT, 0, 1);
2874     mov_write_string_metadata(s, pb, "\251cmt", "comment"  , 1);
2875     mov_write_string_metadata(s, pb, "\251gen", "genre"    , 1);
2876     mov_write_string_metadata(s, pb, "\251cpy", "copyright", 1);
2877     mov_write_string_metadata(s, pb, "\251grp", "grouping" , 1);
2878     mov_write_string_metadata(s, pb, "\251lyr", "lyrics"   , 1);
2879     mov_write_string_metadata(s, pb, "desc",    "description",1);
2880     mov_write_string_metadata(s, pb, "ldes",    "synopsis" , 1);
2881     mov_write_string_metadata(s, pb, "tvsh",    "show"     , 1);
2882     mov_write_string_metadata(s, pb, "tven",    "episode_id",1);
2883     mov_write_string_metadata(s, pb, "tvnn",    "network"  , 1);
2884     mov_write_int8_metadata  (s, pb, "tves",    "episode_sort",4);
2885     mov_write_int8_metadata  (s, pb, "tvsn",    "season_number",4);
2886     mov_write_int8_metadata  (s, pb, "stik",    "media_type",1);
2887     mov_write_int8_metadata  (s, pb, "hdvd",    "hd_video",  1);
2888     mov_write_int8_metadata  (s, pb, "pgap",    "gapless_playback",1);
2889     mov_write_int8_metadata  (s, pb, "cpil",    "compilation", 1);
2890     mov_write_trkn_tag(pb, mov, s, 0); // track number
2891     mov_write_trkn_tag(pb, mov, s, 1); // disc number
2892     mov_write_tmpo_tag(pb, s);
2893     return update_size(pb, pos);
2894 }
2895
2896 /* iTunes meta data tag */
2897 static int mov_write_meta_tag(AVIOContext *pb, MOVMuxContext *mov,
2898                               AVFormatContext *s)
2899 {
2900     int size = 0;
2901     int64_t pos = avio_tell(pb);
2902     avio_wb32(pb, 0); /* size */
2903     ffio_wfourcc(pb, "meta");
2904     avio_wb32(pb, 0);
2905     mov_write_itunes_hdlr_tag(pb, mov, s);
2906     mov_write_ilst_tag(pb, mov, s);
2907     size = update_size(pb, pos);
2908     return size;
2909 }
2910
2911 static int mov_write_raw_metadata_tag(AVFormatContext *s, AVIOContext *pb,
2912                                       const char *name, const char *key)
2913 {
2914     int len;
2915     AVDictionaryEntry *t;
2916
2917     if (!(t = av_dict_get(s->metadata, key, NULL, 0)))
2918         return 0;
2919
2920     len = strlen(t->value);
2921     if (len > 0) {
2922         int size = len + 8;
2923         avio_wb32(pb, size);
2924         ffio_wfourcc(pb, name);
2925         avio_write(pb, t->value, len);
2926         return size;
2927     }
2928     return 0;
2929 }
2930
2931 static int ascii_to_wc(AVIOContext *pb, const uint8_t *b)
2932 {
2933     int val;
2934     while (*b) {
2935         GET_UTF8(val, *b++, return -1;)
2936         avio_wb16(pb, val);
2937     }
2938     avio_wb16(pb, 0x00);
2939     return 0;
2940 }
2941
2942 static uint16_t language_code(const char *str)
2943 {
2944     return (((str[0] - 0x60) & 0x1F) << 10) +
2945            (((str[1] - 0x60) & 0x1F) <<  5) +
2946            (( str[2] - 0x60) & 0x1F);
2947 }
2948
2949 static int mov_write_3gp_udta_tag(AVIOContext *pb, AVFormatContext *s,
2950                                   const char *tag, const char *str)
2951 {
2952     int64_t pos = avio_tell(pb);
2953     AVDictionaryEntry *t = av_dict_get(s->metadata, str, NULL, 0);
2954     if (!t || !utf8len(t->value))
2955         return 0;
2956     avio_wb32(pb, 0);   /* size */
2957     ffio_wfourcc(pb, tag); /* type */
2958     avio_wb32(pb, 0);   /* version + flags */
2959     if (!strcmp(tag, "yrrc"))
2960         avio_wb16(pb, atoi(t->value));
2961     else {
2962         avio_wb16(pb, language_code("eng")); /* language */
2963         avio_write(pb, t->value, strlen(t->value) + 1); /* UTF8 string value */
2964         if (!strcmp(tag, "albm") &&
2965             (t = av_dict_get(s->metadata, "track", NULL, 0)))
2966             avio_w8(pb, atoi(t->value));
2967     }
2968     return update_size(pb, pos);
2969 }
2970
2971 static int mov_write_chpl_tag(AVIOContext *pb, AVFormatContext *s)
2972 {
2973     int64_t pos = avio_tell(pb);
2974     int i, nb_chapters = FFMIN(s->nb_chapters, 255);
2975
2976     avio_wb32(pb, 0);            // size
2977     ffio_wfourcc(pb, "chpl");
2978     avio_wb32(pb, 0x01000000);   // version + flags
2979     avio_wb32(pb, 0);            // unknown
2980     avio_w8(pb, nb_chapters);
2981
2982     for (i = 0; i < nb_chapters; i++) {
2983         AVChapter *c = s->chapters[i];
2984         AVDictionaryEntry *t;
2985         avio_wb64(pb, av_rescale_q(c->start, c->time_base, (AVRational){1,10000000}));
2986
2987         if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
2988             int len = FFMIN(strlen(t->value), 255);
2989             avio_w8(pb, len);
2990             avio_write(pb, t->value, len);
2991         } else
2992             avio_w8(pb, 0);
2993     }
2994     return update_size(pb, pos);
2995 }
2996
2997 static int mov_write_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
2998                               AVFormatContext *s)
2999 {
3000     AVIOContext *pb_buf;
3001     int ret, size;
3002     uint8_t *buf;
3003
3004     ret = avio_open_dyn_buf(&pb_buf);
3005     if (ret < 0)
3006         return ret;
3007
3008     if (mov->mode & MODE_3GP) {
3009         mov_write_3gp_udta_tag(pb_buf, s, "perf", "artist");
3010         mov_write_3gp_udta_tag(pb_buf, s, "titl", "title");
3011         mov_write_3gp_udta_tag(pb_buf, s, "auth", "author");
3012         mov_write_3gp_udta_tag(pb_buf, s, "gnre", "genre");
3013         mov_write_3gp_udta_tag(pb_buf, s, "dscp", "comment");
3014         mov_write_3gp_udta_tag(pb_buf, s, "albm", "album");
3015         mov_write_3gp_udta_tag(pb_buf, s, "cprt", "copyright");
3016         mov_write_3gp_udta_tag(pb_buf, s, "yrrc", "date");
3017     } else if (mov->mode == MODE_MOV) { // the title field breaks gtkpod with mp4 and my suspicion is that stuff is not valid in mp4
3018         mov_write_string_metadata(s, pb_buf, "\251ART", "artist",      0);
3019         mov_write_string_metadata(s, pb_buf, "\251nam", "title",       0);
3020         mov_write_string_metadata(s, pb_buf, "\251aut", "author",      0);
3021         mov_write_string_metadata(s, pb_buf, "\251alb", "album",       0);
3022         mov_write_string_metadata(s, pb_buf, "\251day", "date",        0);
3023         mov_write_string_metadata(s, pb_buf, "\251swr", "encoder",     0);
3024         // currently ignored by mov.c
3025         mov_write_string_metadata(s, pb_buf, "\251des", "comment",     0);
3026         // add support for libquicktime, this atom is also actually read by mov.c
3027         mov_write_string_metadata(s, pb_buf, "\251cmt", "comment",     0);
3028         mov_write_string_metadata(s, pb_buf, "\251gen", "genre",       0);
3029         mov_write_string_metadata(s, pb_buf, "\251cpy", "copyright",   0);
3030         mov_write_raw_metadata_tag(s, pb_buf, "XMP_", "xmp");
3031     } else {
3032         /* iTunes meta data */
3033         mov_write_meta_tag(pb_buf, mov, s);
3034     }
3035
3036     if (s->nb_chapters && !(mov->flags & FF_MOV_FLAG_DISABLE_CHPL))
3037         mov_write_chpl_tag(pb_buf, s);
3038
3039     if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) {
3040         avio_wb32(pb, size + 8);
3041         ffio_wfourcc(pb, "udta");
3042         avio_write(pb, buf, size);
3043     }
3044     av_free(buf);
3045
3046     return 0;
3047 }
3048
3049 static void mov_write_psp_udta_tag(AVIOContext *pb,
3050                                    const char *str, const char *lang, int type)
3051 {
3052     int len = utf8len(str) + 1;
3053     if (len <= 0)
3054         return;
3055     avio_wb16(pb, len * 2 + 10);        /* size */
3056     avio_wb32(pb, type);                /* type */
3057     avio_wb16(pb, language_code(lang)); /* language */
3058     avio_wb16(pb, 0x01);                /* ? */
3059     ascii_to_wc(pb, str);
3060 }
3061
3062 static int mov_write_uuidusmt_tag(AVIOContext *pb, AVFormatContext *s)
3063 {
3064     MOVMuxContext *mov = s->priv_data;
3065     AVDictionaryEntry *title = av_dict_get(s->metadata, "title", NULL, 0);
3066     int64_t pos, pos2;
3067
3068     if (title) {
3069         pos = avio_tell(pb);
3070         avio_wb32(pb, 0); /* size placeholder*/
3071         ffio_wfourcc(pb, "uuid");
3072         ffio_wfourcc(pb, "USMT");
3073         avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
3074         avio_wb32(pb, 0xbb88695c);
3075         avio_wb32(pb, 0xfac9c740);
3076
3077         pos2 = avio_tell(pb);
3078         avio_wb32(pb, 0); /* size placeholder*/
3079         ffio_wfourcc(pb, "MTDT");
3080         avio_wb16(pb, 4);
3081
3082         // ?
3083         avio_wb16(pb, 0x0C);                 /* size */
3084         avio_wb32(pb, 0x0B);                 /* type */
3085         avio_wb16(pb, language_code("und")); /* language */
3086         avio_wb16(pb, 0x0);                  /* ? */
3087         avio_wb16(pb, 0x021C);               /* data */
3088
3089         if (!mov->exact)
3090             mov_write_psp_udta_tag(pb, LIBAVCODEC_IDENT,      "eng", 0x04);
3091         mov_write_psp_udta_tag(pb, title->value,          "eng", 0x01);
3092         mov_write_psp_udta_tag(pb, "2006/04/01 11:11:11", "und", 0x03);
3093
3094         update_size(pb, pos2);
3095         return update_size(pb, pos);
3096     }
3097
3098     return 0;
3099 }
3100
3101 static void build_chunks(MOVTrack *trk)
3102 {
3103     int i;
3104     MOVIentry *chunk = &trk->cluster[0];
3105     uint64_t chunkSize = chunk->size;
3106     chunk->chunkNum = 1;
3107     if (trk->chunkCount)
3108         return;
3109     trk->chunkCount = 1;
3110     for (i = 1; i<trk->entry; i++){
3111         if (chunk->pos + chunkSize == trk->cluster[i].pos &&
3112             chunkSize + trk->cluster[i].size < (1<<20)){
3113             chunkSize             += trk->cluster[i].size;
3114             chunk->samples_in_chunk += trk->cluster[i].entries;
3115         } else {
3116             trk->cluster[i].chunkNum = chunk->chunkNum+1;
3117             chunk=&trk->cluster[i];
3118             chunkSize = chunk->size;
3119             trk->chunkCount++;
3120         }
3121     }
3122 }
3123
3124 static int mov_write_moov_tag(AVIOContext *pb, MOVMuxContext *mov,
3125                               AVFormatContext *s)
3126 {
3127     int i;
3128     int64_t pos = avio_tell(pb);
3129     avio_wb32(pb, 0); /* size placeholder*/
3130     ffio_wfourcc(pb, "moov");
3131
3132     for (i = 0; i < mov->nb_streams; i++) {
3133         if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
3134             continue;
3135
3136         mov->tracks[i].time     = mov->time;
3137         mov->tracks[i].track_id = i + 1;
3138
3139         if (mov->tracks[i].entry)
3140             build_chunks(&mov->tracks[i]);
3141     }
3142
3143     if (mov->chapter_track)
3144         for (i = 0; i < s->nb_streams; i++) {
3145             mov->tracks[i].tref_tag = MKTAG('c','h','a','p');
3146             mov->tracks[i].tref_id  = mov->tracks[mov->chapter_track].track_id;
3147         }
3148     for (i = 0; i < mov->nb_streams; i++) {
3149         if (mov->tracks[i].tag == MKTAG('r','t','p',' ')) {
3150             mov->tracks[i].tref_tag = MKTAG('h','i','n','t');
3151             mov->tracks[i].tref_id =
3152                 mov->tracks[mov->tracks[i].src_track].track_id;
3153         }
3154     }
3155     for (i = 0; i < mov->nb_streams; i++) {
3156         if (mov->tracks[i].tag == MKTAG('t','m','c','d')) {
3157             int src_trk = mov->tracks[i].src_track;
3158             mov->tracks[src_trk].tref_tag = mov->tracks[i].tag;
3159             mov->tracks[src_trk].tref_id  = mov->tracks[i].track_id;
3160             //src_trk may have a different timescale than the tmcd track
3161             mov->tracks[i].track_duration = av_rescale(mov->tracks[src_trk].track_duration,
3162                                                        mov->tracks[i].timescale,
3163                                                        mov->tracks[src_trk].timescale);
3164         }
3165     }
3166
3167     mov_write_mvhd_tag(pb, mov);
3168     if (mov->mode != MODE_MOV && !mov->iods_skip)
3169         mov_write_iods_tag(pb, mov);
3170     for (i = 0; i < mov->nb_streams; i++) {
3171         if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_FRAGMENT) {
3172             int ret = mov_write_trak_tag(pb, mov, &(mov->tracks[i]), i < s->nb_streams ? s->streams[i] : NULL);
3173             if (ret < 0)
3174                 return ret;
3175         }
3176     }
3177     if (mov->flags & FF_MOV_FLAG_FRAGMENT)
3178         mov_write_mvex_tag(pb, mov); /* QuickTime requires trak to precede this */
3179
3180     if (mov->mode == MODE_PSP)
3181         mov_write_uuidusmt_tag(pb, s);
3182     else
3183         mov_write_udta_tag(pb, mov, s);
3184
3185     return update_size(pb, pos);
3186 }
3187
3188 static void param_write_int(AVIOContext *pb, const char *name, int value)
3189 {
3190     avio_printf(pb, "<param name=\"%s\" value=\"%d\" valuetype=\"data\"/>\n", name, value);
3191 }
3192
3193 static void param_write_string(AVIOContext *pb, const char *name, const char *value)
3194 {
3195     avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, value);
3196 }
3197
3198 static void param_write_hex(AVIOContext *pb, const char *name, const uint8_t *value, int len)
3199 {
3200     char buf[150];
3201     len = FFMIN(sizeof(buf) / 2 - 1, len);
3202     ff_data_to_hex(buf, value, len, 0);
3203     buf[2 * len] = '\0';
3204     avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, buf);
3205 }
3206
3207 static int mov_write_isml_manifest(AVIOContext *pb, MOVMuxContext *mov)
3208 {
3209     int64_t pos = avio_tell(pb);
3210     int i;
3211     static const uint8_t uuid[] = {
3212         0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd,
3213         0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66
3214     };
3215
3216     avio_wb32(pb, 0);
3217     ffio_wfourcc(pb, "uuid");
3218     avio_write(pb, uuid, sizeof(uuid));
3219     avio_wb32(pb, 0);
3220
3221     avio_printf(pb, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
3222     avio_printf(pb, "<smil xmlns=\"http://www.w3.org/2001/SMIL20/Language\">\n");
3223     avio_printf(pb, "<head>\n");
3224     if (!mov->exact)
3225         avio_printf(pb, "<meta name=\"creator\" content=\"%s\" />\n",
3226                     LIBAVFORMAT_IDENT);
3227     avio_printf(pb, "</head>\n");
3228     avio_printf(pb, "<body>\n");
3229     avio_printf(pb, "<switch>\n");
3230     for (i = 0; i < mov->nb_streams; i++) {
3231         MOVTrack *track = &mov->tracks[i];
3232         const char *type;
3233         /* track->track_id is initialized in write_moov, and thus isn't known
3234          * here yet */
3235         int track_id = i + 1;
3236
3237         if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) {
3238             type = "video";
3239         } else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO) {
3240             type = "audio";
3241         } else {
3242             continue;
3243         }
3244         avio_printf(pb, "<%s systemBitrate=\"%d\">\n", type,
3245                                                        track->enc->bit_rate);
3246         param_write_int(pb, "systemBitrate", track->enc->bit_rate);
3247         param_write_int(pb, "trackID", track_id);
3248         if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) {
3249             if (track->enc->codec_id == AV_CODEC_ID_H264) {
3250                 uint8_t *ptr;
3251                 int size = track->enc->extradata_size;
3252                 if (!ff_avc_write_annexb_extradata(track->enc->extradata, &ptr,
3253                                                    &size)) {
3254                     param_write_hex(pb, "CodecPrivateData",
3255                                     ptr ? ptr : track->enc->extradata,
3256                                     size);
3257                     av_free(ptr);
3258                 }
3259                 param_write_string(pb, "FourCC", "H264");
3260             } else if (track->enc->codec_id == AV_CODEC_ID_VC1) {
3261                 param_write_string(pb, "FourCC", "WVC1");
3262                 param_write_hex(pb, "CodecPrivateData", track->enc->extradata,
3263                                 track->enc->extradata_size);
3264             }
3265             param_write_int(pb, "MaxWidth", track->enc->width);
3266             param_write_int(pb, "MaxHeight", track->enc->height);
3267             param_write_int(pb, "DisplayWidth", track->enc->width);
3268             param_write_int(pb, "DisplayHeight", track->enc->height);
3269         } else {
3270             if (track->enc->codec_id == AV_CODEC_ID_AAC) {
3271                 param_write_string(pb, "FourCC", "AACL");
3272             } else if (track->enc->codec_id == AV_CODEC_ID_WMAPRO) {
3273                 param_write_string(pb, "FourCC", "WMAP");
3274             }
3275             param_write_hex(pb, "CodecPrivateData", track->enc->extradata,
3276                             track->enc->extradata_size);
3277             param_write_int(pb, "AudioTag", ff_codec_get_tag(ff_codec_wav_tags,
3278                                                              track->enc->codec_id));
3279             param_write_int(pb, "Channels", track->enc->channels);
3280             param_write_int(pb, "SamplingRate", track->enc->sample_rate);
3281             param_write_int(pb, "BitsPerSample", 16);
3282             param_write_int(pb, "PacketSize", track->enc->block_align ?
3283                                               track->enc->block_align : 4);
3284         }
3285         avio_printf(pb, "</%s>\n", type);
3286     }
3287     avio_printf(pb, "</switch>\n");
3288     avio_printf(pb, "</body>\n");
3289     avio_printf(pb, "</smil>\n");
3290
3291     return update_size(pb, pos);
3292 }
3293
3294 static int mov_write_mfhd_tag(AVIOContext *pb, MOVMuxContext *mov)
3295 {
3296     avio_wb32(pb, 16);
3297     ffio_wfourcc(pb, "mfhd");
3298     avio_wb32(pb, 0);
3299     avio_wb32(pb, mov->fragments);
3300     return 0;
3301 }
3302
3303 static int mov_write_tfhd_tag(AVIOContext *pb, MOVMuxContext *mov,
3304                               MOVTrack *track, int64_t moof_offset)
3305 {
3306     int64_t pos = avio_tell(pb);
3307     uint32_t flags = MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
3308                      MOV_TFHD_BASE_DATA_OFFSET;
3309     if (!track->entry) {
3310         flags |= MOV_TFHD_DURATION_IS_EMPTY;
3311     } else {
3312         flags |= MOV_TFHD_DEFAULT_FLAGS;
3313     }
3314     if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET)
3315         flags &= ~MOV_TFHD_BASE_DATA_OFFSET;
3316     if (mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) {
3317         flags &= ~MOV_TFHD_BASE_DATA_OFFSET;
3318         flags |= MOV_TFHD_DEFAULT_BASE_IS_MOOF;
3319     }
3320
3321     /* Don't set a default sample size, the silverlight player refuses
3322      * to play files with that set. Don't set a default sample duration,
3323      * WMP freaks out if it is set. Don't set a base data offset, PIFF
3324      * file format says it MUST NOT be set. */
3325     if (track->mode == MODE_ISM)
3326         flags &= ~(MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
3327                    MOV_TFHD_BASE_DATA_OFFSET);
3328
3329     avio_wb32(pb, 0); /* size placeholder */
3330     ffio_wfourcc(pb, "tfhd");
3331     avio_w8(pb, 0); /* version */
3332     avio_wb24(pb, flags);
3333
3334     avio_wb32(pb, track->track_id); /* track-id */
3335     if (flags & MOV_TFHD_BASE_DATA_OFFSET)
3336         avio_wb64(pb, moof_offset);
3337     if (flags & MOV_TFHD_DEFAULT_DURATION) {
3338         track->default_duration = get_cluster_duration(track, 0);
3339         avio_wb32(pb, track->default_duration);
3340     }
3341     if (flags & MOV_TFHD_DEFAULT_SIZE) {
3342         track->default_size = track->entry ? track->cluster[0].size : 1;
3343         avio_wb32(pb, track->default_size);
3344     } else
3345         track->default_size = -1;
3346
3347     if (flags & MOV_TFHD_DEFAULT_FLAGS) {
3348         track->default_sample_flags =
3349             track->enc->codec_type == AVMEDIA_TYPE_VIDEO ?
3350             (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC) :
3351             MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO;
3352         avio_wb32(pb, track->default_sample_flags);
3353     }
3354
3355     return update_size(pb, pos);
3356 }
3357
3358 static uint32_t get_sample_flags(MOVTrack *track, MOVIentry *entry)
3359 {
3360     return entry->flags & MOV_SYNC_SAMPLE ? MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO :
3361            (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC);
3362 }
3363
3364 static int mov_write_trun_tag(AVIOContext *pb, MOVMuxContext *mov,
3365                               MOVTrack *track, int moof_size)
3366 {
3367     int64_t pos = avio_tell(pb);
3368     uint32_t flags = MOV_TRUN_DATA_OFFSET;
3369     int i;
3370
3371     for (i = 0; i < track->entry; i++) {
3372         if (get_cluster_duration(track, i) != track->default_duration)
3373             flags |= MOV_TRUN_SAMPLE_DURATION;
3374         if (track->cluster[i].size != track->default_size)
3375             flags |= MOV_TRUN_SAMPLE_SIZE;
3376         if (i > 0 && get_sample_flags(track, &track->cluster[i]) != track->default_sample_flags)
3377             flags |= MOV_TRUN_SAMPLE_FLAGS;
3378     }
3379     if (!(flags & MOV_TRUN_SAMPLE_FLAGS))
3380         flags |= MOV_TRUN_FIRST_SAMPLE_FLAGS;
3381     if (track->flags & MOV_TRACK_CTTS)
3382         flags |= MOV_TRUN_SAMPLE_CTS;
3383
3384     avio_wb32(pb, 0); /* size placeholder */
3385     ffio_wfourcc(pb, "trun");
3386     avio_w8(pb, 0); /* version */
3387     avio_wb24(pb, flags);
3388
3389     avio_wb32(pb, track->entry); /* sample count */
3390     if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET &&
3391         !(mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) &&
3392         !mov->first_trun)
3393         avio_wb32(pb, 0); /* Later tracks follow immediately after the previous one */
3394     else
3395         avio_wb32(pb, moof_size + 8 + track->data_offset +
3396                       track->cluster[0].pos); /* data offset */
3397     if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS)
3398         avio_wb32(pb, get_sample_flags(track, &track->cluster[0]));
3399
3400     for (i = 0; i < track->entry; i++) {
3401         if (flags & MOV_TRUN_SAMPLE_DURATION)
3402             avio_wb32(pb, get_cluster_duration(track, i));
3403         if (flags & MOV_TRUN_SAMPLE_SIZE)
3404             avio_wb32(pb, track->cluster[i].size);
3405         if (flags & MOV_TRUN_SAMPLE_FLAGS)
3406             avio_wb32(pb, get_sample_flags(track, &track->cluster[i]));
3407         if (flags & MOV_TRUN_SAMPLE_CTS)
3408             avio_wb32(pb, track->cluster[i].cts);
3409     }
3410
3411     mov->first_trun = 0;
3412     return update_size(pb, pos);
3413 }
3414
3415 static int mov_write_tfxd_tag(AVIOContext *pb, MOVTrack *track)
3416 {
3417     int64_t pos = avio_tell(pb);
3418     static const uint8_t uuid[] = {
3419         0x6d, 0x1d, 0x9b, 0x05, 0x42, 0xd5, 0x44, 0xe6,
3420         0x80, 0xe2, 0x14, 0x1d, 0xaf, 0xf7, 0x57, 0xb2
3421     };
3422
3423     avio_wb32(pb, 0); /* size placeholder */
3424     ffio_wfourcc(pb, "uuid");
3425     avio_write(pb, uuid, sizeof(uuid));
3426     avio_w8(pb, 1);
3427     avio_wb24(pb, 0);
3428     avio_wb64(pb, track->frag_start);
3429     avio_wb64(pb, track->start_dts + track->track_duration -
3430                   track->cluster[0].dts);
3431
3432     return update_size(pb, pos);
3433 }
3434
3435 static int mov_write_tfrf_tag(AVIOContext *pb, MOVMuxContext *mov,
3436                               MOVTrack *track, int entry)
3437 {
3438     int n = track->nb_frag_info - 1 - entry, i;
3439     int size = 8 + 16 + 4 + 1 + 16*n;
3440     static const uint8_t uuid[] = {
3441         0xd4, 0x80, 0x7e, 0xf2, 0xca, 0x39, 0x46, 0x95,
3442         0x8e, 0x54, 0x26, 0xcb, 0x9e, 0x46, 0xa7, 0x9f
3443     };
3444
3445     if (entry < 0)
3446         return 0;
3447
3448     avio_seek(pb, track->frag_info[entry].tfrf_offset, SEEK_SET);
3449     avio_wb32(pb, size);
3450     ffio_wfourcc(pb, "uuid");
3451     avio_write(pb, uuid, sizeof(uuid));
3452     avio_w8(pb, 1);
3453     avio_wb24(pb, 0);
3454     avio_w8(pb, n);
3455     for (i = 0; i < n; i++) {
3456         int index = entry + 1 + i;
3457         avio_wb64(pb, track->frag_info[index].time);
3458         avio_wb64(pb, track->frag_info[index].duration);
3459     }
3460     if (n < mov->ism_lookahead) {
3461         int free_size = 16 * (mov->ism_lookahead - n);
3462         avio_wb32(pb, free_size);
3463         ffio_wfourcc(pb, "free");
3464         ffio_fill(pb, 0, free_size - 8);
3465     }
3466
3467     return 0;
3468 }
3469
3470 static int mov_write_tfrf_tags(AVIOContext *pb, MOVMuxContext *mov,
3471                                MOVTrack *track)
3472 {
3473     int64_t pos = avio_tell(pb);
3474     int i;
3475     for (i = 0; i < mov->ism_lookahead; i++) {
3476         /* Update the tfrf tag for the last ism_lookahead fragments,
3477          * nb_frag_info - 1 is the next fragment to be written. */
3478         mov_write_tfrf_tag(pb, mov, track, track->nb_frag_info - 2 - i);
3479     }
3480     avio_seek(pb, pos, SEEK_SET);
3481     return 0;
3482 }
3483
3484 static int mov_add_tfra_entries(AVIOContext *pb, MOVMuxContext *mov, int tracks,
3485                                 int size)
3486 {
3487     int i;
3488     for (i = 0; i < mov->nb_streams; i++) {
3489         MOVTrack *track = &mov->tracks[i];
3490         MOVFragmentInfo *info;
3491         if ((tracks >= 0 && i != tracks) || !track->entry)
3492             continue;
3493         track->nb_frag_info++;
3494         if (track->nb_frag_info >= track->frag_info_capacity) {
3495             unsigned new_capacity = track->nb_frag_info + MOV_FRAG_INFO_ALLOC_INCREMENT;
3496             if (av_reallocp_array(&track->frag_info,
3497                                   new_capacity,
3498                                   sizeof(*track->frag_info)))
3499                 return AVERROR(ENOMEM);
3500             track->frag_info_capacity = new_capacity;
3501         }
3502         info = &track->frag_info[track->nb_frag_info - 1];
3503         info->offset   = avio_tell(pb);
3504         info->size     = size;
3505         // Try to recreate the original pts for the first packet
3506         // from the fields we have stored
3507         info->time     = track->start_dts + track->frag_start +
3508                          track->cluster[0].cts;
3509         // If the pts is less than zero, we will have trimmed
3510         // away parts of the media track using an edit list,
3511         // and the corresponding start presentation time is zero.
3512         if (info->time < 0)
3513             info->time = 0;
3514         info->duration = track->start_dts + track->track_duration -
3515                          track->cluster[0].dts;
3516         info->tfrf_offset = 0;
3517         mov_write_tfrf_tags(pb, mov, track);
3518     }
3519     return 0;
3520 }
3521
3522 static int mov_write_tfdt_tag(AVIOContext *pb, MOVTrack *track)
3523 {
3524     int64_t pos = avio_tell(pb);
3525
3526     avio_wb32(pb, 0); /* size */
3527     ffio_wfourcc(pb, "tfdt");
3528     avio_w8(pb, 1); /* version */
3529     avio_wb24(pb, 0);
3530     avio_wb64(pb, track->frag_start);
3531     return update_size(pb, pos);
3532 }
3533
3534 static int mov_write_traf_tag(AVIOContext *pb, MOVMuxContext *mov,
3535                               MOVTrack *track, int64_t moof_offset,
3536                               int moof_size)
3537 {
3538     int64_t pos = avio_tell(pb);
3539     avio_wb32(pb, 0); /* size placeholder */
3540     ffio_wfourcc(pb, "traf");
3541
3542     mov_write_tfhd_tag(pb, mov, track, moof_offset);
3543     if (mov->mode != MODE_ISM)
3544         mov_write_tfdt_tag(pb, track);
3545     mov_write_trun_tag(pb, mov, track, moof_size);
3546     if (mov->mode == MODE_ISM) {
3547         mov_write_tfxd_tag(pb, track);
3548
3549         if (mov->ism_lookahead) {
3550             int i, size = 16 + 4 + 1 + 16 * mov->ism_lookahead;
3551
3552             if (track->nb_frag_info > 0) {
3553                 MOVFragmentInfo *info = &track->frag_info[track->nb_frag_info - 1];
3554                 if (!info->tfrf_offset)
3555                     info->tfrf_offset = avio_tell(pb);
3556             }
3557             avio_wb32(pb, 8 + size);
3558             ffio_wfourcc(pb, "free");
3559             for (i = 0; i < size; i++)
3560                 avio_w8(pb, 0);
3561         }
3562     }
3563
3564     return update_size(pb, pos);
3565 }
3566
3567 static int mov_write_moof_tag_internal(AVIOContext *pb, MOVMuxContext *mov,
3568                                        int tracks, int moof_size)
3569 {
3570     int64_t pos = avio_tell(pb);
3571     int i;
3572
3573     avio_wb32(pb, 0); /* size placeholder */
3574     ffio_wfourcc(pb, "moof");
3575     mov->first_trun = 1;
3576
3577     mov_write_mfhd_tag(pb, mov);
3578     for (i = 0; i < mov->nb_streams; i++) {
3579         MOVTrack *track = &mov->tracks[i];
3580         if (tracks >= 0 && i != tracks)
3581             continue;
3582         if (!track->entry)
3583             continue;
3584         mov_write_traf_tag(pb, mov, track, pos, moof_size);
3585     }
3586
3587     return update_size(pb, pos);
3588 }
3589
3590 static int mov_write_sidx_tag(AVIOContext *pb,
3591                               MOVTrack *track, int ref_size, int total_sidx_size)
3592 {
3593     int64_t pos = avio_tell(pb), offset_pos, end_pos;
3594     int64_t presentation_time, duration, offset;
3595     int starts_with_SAP, i, entries;
3596
3597     if (track->entry) {
3598         entries = 1;
3599         presentation_time = track->start_dts + track->frag_start +
3600                             track->cluster[0].cts;
3601         duration = track->start_dts + track->track_duration -
3602                    track->cluster[0].dts;
3603         starts_with_SAP = track->cluster[0].flags & MOV_SYNC_SAMPLE;
3604     } else {
3605         entries = track->nb_frag_info;
3606         presentation_time = track->frag_info[0].time;
3607     }
3608
3609     // pts<0 should be cut away using edts
3610     if (presentation_time < 0)
3611         presentation_time = 0;
3612
3613     avio_wb32(pb, 0); /* size */
3614     ffio_wfourcc(pb, "sidx");
3615     avio_w8(pb, 1); /* version */
3616     avio_wb24(pb, 0);
3617     avio_wb32(pb, track->track_id); /* reference_ID */
3618     avio_wb32(pb, track->timescale); /* timescale */
3619     avio_wb64(pb, presentation_time); /* earliest_presentation_time */
3620     offset_pos = avio_tell(pb);
3621     avio_wb64(pb, 0); /* first_offset (offset to referenced moof) */
3622     avio_wb16(pb, 0); /* reserved */
3623
3624     avio_wb16(pb, entries); /* reference_count */
3625     for (i = 0; i < entries; i++) {
3626         if (!track->entry) {
3627             if (i > 1 && track->frag_info[i].offset != track->frag_info[i - 1].offset + track->frag_info[i - 1].size) {
3628                av_log(NULL, AV_LOG_ERROR, "Non-consecutive fragments, writing incorrect sidx\n");
3629             }
3630             duration = track->frag_info[i].duration;
3631             ref_size = track->frag_info[i].size;
3632             starts_with_SAP = 1;
3633         }
3634         avio_wb32(pb, (0 << 31) | (ref_size & 0x7fffffff)); /* reference_type (0 = media) | referenced_size */
3635         avio_wb32(pb, duration); /* subsegment_duration */
3636         avio_wb32(pb, (starts_with_SAP << 31) | (0 << 28) | 0); /* starts_with_SAP | SAP_type | SAP_delta_time */
3637     }
3638
3639     end_pos = avio_tell(pb);
3640     offset = pos + total_sidx_size - end_pos;
3641     avio_seek(pb, offset_pos, SEEK_SET);
3642     avio_wb64(pb, offset);
3643     avio_seek(pb, end_pos, SEEK_SET);
3644     return update_size(pb, pos);
3645 }
3646
3647 static int mov_write_sidx_tags(AVIOContext *pb, MOVMuxContext *mov,
3648                                int tracks, int ref_size)
3649 {
3650     int i, round, ret;
3651     AVIOContext *avio_buf;
3652     int total_size = 0;
3653     for (round = 0; round < 2; round++) {
3654         // First run one round to calculate the total size of all
3655         // sidx atoms.
3656         // This would be much simpler if we'd only write one sidx
3657         // atom, for the first track in the moof.
3658         if (round == 0) {
3659             if ((ret = ffio_open_null_buf(&avio_buf)) < 0)
3660                 return ret;
3661         } else {
3662             avio_buf = pb;
3663         }
3664         for (i = 0; i < mov->nb_streams; i++) {
3665             MOVTrack *track = &mov->tracks[i];
3666             if (tracks >= 0 && i != tracks)
3667                 continue;
3668             // When writing a sidx for the full file, entry is 0, but
3669             // we want to include all tracks. ref_size is 0 in this case,
3670             // since we read it from frag_info instead.
3671             if (!track->entry && ref_size > 0)
3672                 continue;
3673             total_size -= mov_write_sidx_tag(avio_buf, track, ref_size,
3674                                              total_size);
3675         }
3676         if (round == 0)
3677             total_size = ffio_close_null_buf(avio_buf);
3678     }
3679     return 0;
3680 }
3681
3682 static int mov_write_moof_tag(AVIOContext *pb, MOVMuxContext *mov, int tracks,
3683                               int64_t mdat_size)
3684 {
3685     AVIOContext *avio_buf;
3686     int ret, moof_size;
3687
3688     if ((ret = ffio_open_null_buf(&avio_buf)) < 0)
3689         return ret;
3690     mov_write_moof_tag_internal(avio_buf, mov, tracks, 0);
3691     moof_size = ffio_close_null_buf(avio_buf);
3692
3693     if (mov->flags & FF_MOV_FLAG_DASH && !(mov->flags & FF_MOV_FLAG_FASTSTART))
3694         mov_write_sidx_tags(pb, mov, tracks, moof_size + 8 + mdat_size);
3695
3696     if ((ret = mov_add_tfra_entries(pb, mov, tracks, moof_size + 8 + mdat_size)) < 0)
3697         return ret;
3698
3699     return mov_write_moof_tag_internal(pb, mov, tracks, moof_size);
3700 }
3701
3702 static int mov_write_tfra_tag(AVIOContext *pb, MOVTrack *track)
3703 {
3704     int64_t pos = avio_tell(pb);
3705     int i;
3706
3707     avio_wb32(pb, 0); /* size placeholder */
3708     ffio_wfourcc(pb, "tfra");
3709     avio_w8(pb, 1); /* version */
3710     avio_wb24(pb, 0);
3711
3712     avio_wb32(pb, track->track_id);
3713     avio_wb32(pb, 0); /* length of traf/trun/sample num */
3714     avio_wb32(pb, track->nb_frag_info);
3715     for (i = 0; i < track->nb_frag_info; i++) {
3716         avio_wb64(pb, track->frag_info[i].time);
3717         avio_wb64(pb, track->frag_info[i].offset + track->data_offset);
3718         avio_w8(pb, 1); /* traf number */
3719         avio_w8(pb, 1); /* trun number */
3720         avio_w8(pb, 1); /* sample number */
3721     }
3722
3723     return update_size(pb, pos);
3724 }
3725
3726 static int mov_write_mfra_tag(AVIOContext *pb, MOVMuxContext *mov)
3727 {
3728     int64_t pos = avio_tell(pb);
3729     int i;
3730
3731     avio_wb32(pb, 0); /* size placeholder */
3732     ffio_wfourcc(pb, "mfra");
3733     /* An empty mfra atom is enough to indicate to the publishing point that
3734      * the stream has ended. */
3735     if (mov->flags & FF_MOV_FLAG_ISML)
3736         return update_size(pb, pos);
3737
3738     for (i = 0; i < mov->nb_streams; i++) {
3739         MOVTrack *track = &mov->tracks[i];
3740         if (track->nb_frag_info)
3741             mov_write_tfra_tag(pb, track);
3742     }
3743
3744     avio_wb32(pb, 16);
3745     ffio_wfourcc(pb, "mfro");
3746     avio_wb32(pb, 0); /* version + flags */
3747     avio_wb32(pb, avio_tell(pb) + 4 - pos);
3748
3749     return update_size(pb, pos);
3750 }
3751
3752 static int mov_write_mdat_tag(AVIOContext *pb, MOVMuxContext *mov)
3753 {
3754     avio_wb32(pb, 8);    // placeholder for extended size field (64 bit)
3755     ffio_wfourcc(pb, mov->mode == MODE_MOV ? "wide" : "free");
3756
3757     mov->mdat_pos = avio_tell(pb);
3758     avio_wb32(pb, 0); /* size placeholder*/
3759     ffio_wfourcc(pb, "mdat");
3760     return 0;
3761 }
3762
3763 /* TODO: This needs to be more general */
3764 static int mov_write_ftyp_tag(AVIOContext *pb, AVFormatContext *s)
3765 {
3766     MOVMuxContext *mov = s->priv_data;
3767     int64_t pos = avio_tell(pb);
3768     int has_h264 = 0, has_video = 0;
3769     int minor = 0x200;
3770     int i;
3771
3772     for (i = 0; i < s->nb_streams; i++) {
3773         AVStream *st = s->streams[i];
3774         if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
3775             has_video = 1;
3776         if (st->codec->codec_id == AV_CODEC_ID_H264)
3777             has_h264 = 1;
3778     }
3779
3780     avio_wb32(pb, 0); /* size */
3781     ffio_wfourcc(pb, "ftyp");
3782
3783     if (mov->major_brand && strlen(mov->major_brand) >= 4)
3784         ffio_wfourcc(pb, mov->major_brand);
3785     else if (mov->mode == MODE_3GP) {
3786         ffio_wfourcc(pb, has_h264 ? "3gp6"  : "3gp4");
3787         minor =     has_h264 ?   0x100 :   0x200;
3788     } else if (mov->mode & MODE_3G2) {
3789         ffio_wfourcc(pb, has_h264 ? "3g2b"  : "3g2a");
3790         minor =     has_h264 ? 0x20000 : 0x10000;
3791     } else if (mov->mode == MODE_PSP)
3792         ffio_wfourcc(pb, "MSNV");
3793     else if (mov->mode == MODE_MP4 && mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)
3794         ffio_wfourcc(pb, "iso5"); // Required when using default-base-is-moof
3795     else if (mov->mode == MODE_MP4)
3796         ffio_wfourcc(pb, "isom");
3797     else if (mov->mode == MODE_IPOD)
3798         ffio_wfourcc(pb, has_video ? "M4V ":"M4A ");
3799     else if (mov->mode == MODE_ISM)
3800         ffio_wfourcc(pb, "isml");
3801     else if (mov->mode == MODE_F4V)
3802         ffio_wfourcc(pb, "f4v ");
3803     else
3804         ffio_wfourcc(pb, "qt  ");
3805
3806     avio_wb32(pb, minor);
3807
3808     if (mov->mode == MODE_MOV)
3809         ffio_wfourcc(pb, "qt  ");
3810     else if (mov->mode == MODE_ISM) {
3811         ffio_wfourcc(pb, "piff");
3812     } else if (!(mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)) {
3813         ffio_wfourcc(pb, "isom");
3814         ffio_wfourcc(pb, "iso2");
3815         if (has_h264)
3816             ffio_wfourcc(pb, "avc1");
3817     }
3818
3819     // We add tfdt atoms when fragmenting, signal this with the iso6 compatible
3820     // brand. This is compatible with users that don't understand tfdt.
3821     if (mov->flags & FF_MOV_FLAG_FRAGMENT && mov->mode != MODE_ISM)
3822         ffio_wfourcc(pb, "iso6");
3823
3824     if (mov->mode == MODE_3GP)
3825         ffio_wfourcc(pb, has_h264 ? "3gp6":"3gp4");
3826     else if (mov->mode & MODE_3G2)
3827         ffio_wfourcc(pb, has_h264 ? "3g2b":"3g2a");
3828     else if (mov->mode == MODE_PSP)
3829         ffio_wfourcc(pb, "MSNV");
3830     else if (mov->mode == MODE_MP4)
3831         ffio_wfourcc(pb, "mp41");
3832
3833     if (mov->flags & FF_MOV_FLAG_DASH && mov->flags & FF_MOV_FLAG_FASTSTART)
3834         ffio_wfourcc(pb, "dash");
3835
3836     return update_size(pb, pos);
3837 }
3838
3839 static void mov_write_uuidprof_tag(AVIOContext *pb, AVFormatContext *s)
3840 {
3841     AVStream       *video_st    = s->streams[0];
3842     AVCodecContext *video_codec = s->streams[0]->codec;
3843     AVCodecContext *audio_codec = s->streams[1]->codec;
3844     int audio_rate = audio_codec->sample_rate;
3845     // TODO: should be avg_frame_rate
3846     int frame_rate = ((video_st->time_base.den) * (0x10000)) / (video_st->time_base.num);
3847     int audio_kbitrate = audio_codec->bit_rate / 1000;
3848     int video_kbitrate = FFMIN(video_codec->bit_rate / 1000, 800 - audio_kbitrate);
3849
3850     avio_wb32(pb, 0x94); /* size */
3851     ffio_wfourcc(pb, "uuid");
3852     ffio_wfourcc(pb, "PROF");
3853
3854     avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
3855     avio_wb32(pb, 0xbb88695c);
3856     avio_wb32(pb, 0xfac9c740);
3857
3858     avio_wb32(pb, 0x0);  /* ? */
3859     avio_wb32(pb, 0x3);  /* 3 sections ? */
3860
3861     avio_wb32(pb, 0x14); /* size */
3862     ffio_wfourcc(pb, "FPRF");
3863     avio_wb32(pb, 0x0);  /* ? */
3864     avio_wb32(pb, 0x0);  /* ? */
3865     avio_wb32(pb, 0x0);  /* ? */
3866
3867     avio_wb32(pb, 0x2c);  /* size */
3868     ffio_wfourcc(pb, "APRF"); /* audio */
3869     avio_wb32(pb, 0x0);
3870     avio_wb32(pb, 0x2);   /* TrackID */
3871     ffio_wfourcc(pb, "mp4a");
3872     avio_wb32(pb, 0x20f);
3873     avio_wb32(pb, 0x0);
3874     avio_wb32(pb, audio_kbitrate);
3875     avio_wb32(pb, audio_kbitrate);
3876     avio_wb32(pb, audio_rate);
3877     avio_wb32(pb, audio_codec->channels);
3878
3879     avio_wb32(pb, 0x34);  /* size */
3880     ffio_wfourcc(pb, "VPRF");   /* video */
3881     avio_wb32(pb, 0x0);
3882     avio_wb32(pb, 0x1);    /* TrackID */
3883     if (video_codec->codec_id == AV_CODEC_ID_H264) {
3884         ffio_wfourcc(pb, "avc1");
3885         avio_wb16(pb, 0x014D);
3886         avio_wb16(pb, 0x0015);
3887     } else {
3888         ffio_wfourcc(pb, "mp4v");
3889         avio_wb16(pb, 0x0000);
3890         avio_wb16(pb, 0x0103);
3891     }
3892     avio_wb32(pb, 0x0);
3893     avio_wb32(pb, video_kbitrate);
3894     avio_wb32(pb, video_kbitrate);
3895     avio_wb32(pb, frame_rate);
3896     avio_wb32(pb, frame_rate);
3897     avio_wb16(pb, video_codec->width);
3898     avio_wb16(pb, video_codec->height);
3899     avio_wb32(pb, 0x010001); /* ? */
3900 }
3901
3902 static int mov_write_identification(AVIOContext *pb, AVFormatContext *s)
3903 {
3904     MOVMuxContext *mov = s->priv_data;
3905     int i;
3906
3907     mov_write_ftyp_tag(pb,s);
3908     if (mov->mode == MODE_PSP) {
3909         int video_streams_nb = 0, audio_streams_nb = 0, other_streams_nb = 0;
3910         for (i = 0; i < s->nb_streams; i++) {
3911             AVStream *st = s->streams[i];
3912             if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
3913                 video_streams_nb++;
3914             else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
3915                 audio_streams_nb++;
3916             else
3917                 other_streams_nb++;
3918             }
3919
3920         if (video_streams_nb != 1 || audio_streams_nb != 1 || other_streams_nb) {
3921             av_log(s, AV_LOG_ERROR, "PSP mode need one video and one audio stream\n");
3922             return AVERROR(EINVAL);
3923         }
3924         mov_write_uuidprof_tag(pb, s);
3925     }
3926     return 0;
3927 }
3928
3929 static int mov_parse_mpeg2_frame(AVPacket *pkt, uint32_t *flags)
3930 {
3931     uint32_t c = -1;
3932     int i, closed_gop = 0;
3933
3934     for (i = 0; i < pkt->size - 4; i++) {
3935         c = (c << 8) + pkt->data[i];
3936         if (c == 0x1b8) { // gop
3937             closed_gop = pkt->data[i + 4] >> 6 & 0x01;
3938         } else if (c == 0x100) { // pic
3939             int temp_ref = (pkt->data[i + 1] << 2) | (pkt->data[i + 2] >> 6);
3940             if (!temp_ref || closed_gop) // I picture is not reordered
3941                 *flags = MOV_SYNC_SAMPLE;
3942             else
3943                 *flags = MOV_PARTIAL_SYNC_SAMPLE;
3944             break;
3945         }
3946     }
3947     return 0;
3948 }
3949
3950 static void mov_parse_vc1_frame(AVPacket *pkt, MOVTrack *trk, int fragment)
3951 {
3952     const uint8_t *start, *next, *end = pkt->data + pkt->size;
3953     int seq = 0, entry = 0;
3954     int key = pkt->flags & AV_PKT_FLAG_KEY;
3955     start = find_next_marker(pkt->data, end);
3956     for (next = start; next < end; start = next) {
3957         next = find_next_marker(start + 4, end);
3958         switch (AV_RB32(start)) {
3959         case VC1_CODE_SEQHDR:
3960             seq = 1;
3961             break;
3962         case VC1_CODE_ENTRYPOINT:
3963             entry = 1;
3964             break;
3965         case VC1_CODE_SLICE:
3966             trk->vc1_info.slices = 1;
3967             break;
3968         }
3969     }
3970     if (!trk->entry && !fragment) {
3971         /* First packet in first fragment */
3972         trk->vc1_info.first_packet_seq   = seq;
3973         trk->vc1_info.first_packet_entry = entry;
3974     } else if ((seq && !trk->vc1_info.packet_seq) ||
3975                (entry && !trk->vc1_info.packet_entry)) {
3976         int i;
3977         for (i = 0; i < trk->entry; i++)
3978             trk->cluster[i].flags &= ~MOV_SYNC_SAMPLE;
3979         trk->has_keyframes = 0;
3980         if (seq)
3981             trk->vc1_info.packet_seq = 1;
3982         if (entry)
3983             trk->vc1_info.packet_entry = 1;
3984         if (!fragment) {
3985             /* First fragment */
3986             if ((!seq   || trk->vc1_info.first_packet_seq) &&
3987                 (!entry || trk->vc1_info.first_packet_entry)) {
3988                 /* First packet had the same headers as this one, readd the
3989                  * sync sample flag. */
3990                 trk->cluster[0].flags |= MOV_SYNC_SAMPLE;
3991                 trk->has_keyframes = 1;
3992             }
3993         }
3994     }
3995     if (trk->vc1_info.packet_seq && trk->vc1_info.packet_entry)
3996         key = seq && entry;
3997     else if (trk->vc1_info.packet_seq)
3998         key = seq;
3999     else if (trk->vc1_info.packet_entry)
4000         key = entry;
4001     if (key) {
4002         trk->cluster[trk->entry].flags |= MOV_SYNC_SAMPLE;
4003         trk->has_keyframes++;
4004     }
4005 }
4006
4007 static int mov_flush_fragment(AVFormatContext *s)
4008 {
4009     MOVMuxContext *mov = s->priv_data;
4010     int i, first_track = -1;
4011     int64_t mdat_size = 0;
4012     int ret;
4013
4014     if (!(mov->flags & FF_MOV_FLAG_FRAGMENT))
4015         return 0;
4016
4017     if (mov->fragments == 0) {
4018         int64_t pos = avio_tell(s->pb);
4019         uint8_t *buf;
4020         int buf_size, moov_size;
4021
4022         for (i = 0; i < mov->nb_streams; i++)
4023             if (!mov->tracks[i].entry)
4024                 break;
4025         /* Don't write the initial moov unless all tracks have data */
4026         if (i < mov->nb_streams)
4027             return 0;
4028
4029         moov_size = get_moov_size(s);
4030         for (i = 0; i < mov->nb_streams; i++)
4031             mov->tracks[i].data_offset = pos + moov_size + 8;
4032
4033         if (mov->flags & FF_MOV_FLAG_DELAY_MOOV)
4034             mov_write_identification(s->pb, s);
4035         if ((ret = mov_write_moov_tag(s->pb, mov, s)) < 0)
4036             return ret;
4037
4038         if (mov->flags & FF_MOV_FLAG_DELAY_MOOV) {
4039             if (mov->flags & FF_MOV_FLAG_FASTSTART)
4040                 mov->reserved_moov_pos = avio_tell(s->pb);
4041             avio_flush(s->pb);
4042             mov->fragments++;
4043             return 0;
4044         }
4045
4046         buf_size = avio_close_dyn_buf(mov->mdat_buf, &buf);
4047         mov->mdat_buf = NULL;
4048         avio_wb32(s->pb, buf_size + 8);
4049         ffio_wfourcc(s->pb, "mdat");
4050         avio_write(s->pb, buf, buf_size);
4051         av_free(buf);
4052
4053         mov->fragments++;
4054         mov->mdat_size = 0;
4055         for (i = 0; i < mov->nb_streams; i++) {
4056             if (mov->tracks[i].entry)
4057                 mov->tracks[i].frag_start += mov->tracks[i].start_dts +
4058                                              mov->tracks[i].track_duration -
4059                                              mov->tracks[i].cluster[0].dts;
4060             mov->tracks[i].entry = 0;
4061         }
4062         avio_flush(s->pb);
4063         return 0;
4064     }
4065
4066     for (i = 0; i < mov->nb_streams; i++) {
4067         MOVTrack *track = &mov->tracks[i];
4068         if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF)
4069             track->data_offset = 0;
4070         else
4071             track->data_offset = mdat_size;
4072         if (!track->mdat_buf)
4073             continue;
4074         mdat_size += avio_tell(track->mdat_buf);
4075         if (first_track < 0)
4076             first_track = i;
4077     }
4078
4079     if (!mdat_size)
4080         return 0;
4081
4082     for (i = 0; i < mov->nb_streams; i++) {
4083         MOVTrack *track = &mov->tracks[i];
4084         int buf_size, write_moof = 1, moof_tracks = -1;
4085         uint8_t *buf;
4086         int64_t duration = 0;
4087
4088         if (track->entry)
4089             duration = track->start_dts + track->track_duration -
4090                        track->cluster[0].dts;
4091         if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF) {
4092             if (!track->mdat_buf)
4093                 continue;
4094             mdat_size = avio_tell(track->mdat_buf);
4095             moof_tracks = i;
4096         } else {
4097             write_moof = i == first_track;
4098         }
4099
4100         if (write_moof) {
4101             avio_flush(s->pb);
4102
4103             mov_write_moof_tag(s->pb, mov, moof_tracks, mdat_size);
4104             mov->fragments++;
4105
4106             avio_wb32(s->pb, mdat_size + 8);
4107             ffio_wfourcc(s->pb, "mdat");
4108         }
4109
4110         if (track->entry)
4111             track->frag_start += duration;
4112         track->entry = 0;
4113         if (!track->mdat_buf)
4114             continue;
4115         buf_size = avio_close_dyn_buf(track->mdat_buf, &buf);
4116         track->mdat_buf = NULL;
4117
4118         avio_write(s->pb, buf, buf_size);
4119         av_free(buf);
4120     }
4121
4122     mov->mdat_size = 0;
4123
4124     avio_flush(s->pb);
4125     return 0;
4126 }
4127
4128 static int mov_auto_flush_fragment(AVFormatContext *s)
4129 {
4130     MOVMuxContext *mov = s->priv_data;
4131     int ret = mov_flush_fragment(s);
4132     if (ret < 0)
4133         return ret;
4134     // If using delay_moov, the first flush only wrote the moov,
4135     // not the actual moof+mdat pair, thus flush once again.
4136     if (mov->fragments == 1 && mov->flags & FF_MOV_FLAG_DELAY_MOOV)
4137         ret = mov_flush_fragment(s);
4138     return ret;
4139 }
4140
4141 int ff_mov_write_packet(AVFormatContext *s, AVPacket *pkt)
4142 {
4143     MOVMuxContext *mov = s->priv_data;
4144     AVIOContext *pb = s->pb;
4145     MOVTrack *trk = &mov->tracks[pkt->stream_index];
4146     AVCodecContext *enc = trk->enc;
4147     unsigned int samples_in_chunk = 0;
4148     int size = pkt->size, ret = 0;
4149     uint8_t *reformatted_data = NULL;
4150
4151     if (trk->entry) {
4152         int64_t duration = pkt->dts - trk->cluster[trk->entry - 1].dts;
4153         if (duration < 0 || duration > INT_MAX) {
4154             av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" / timestamp: %"PRId64" is out of range for mov/mp4 format\n",
4155                 duration, pkt->dts
4156             );
4157
4158             pkt->dts = trk->cluster[trk->entry - 1].dts + 1;
4159             pkt->pts = AV_NOPTS_VALUE;
4160         }
4161         if (pkt->duration < 0) {
4162             av_log(s, AV_LOG_ERROR, "Application provided duration: %d is invalid\n", pkt->duration);
4163             return AVERROR(EINVAL);
4164         }
4165     }
4166     if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
4167         int ret;
4168         if (mov->fragments > 0 || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
4169             if (!trk->mdat_buf) {
4170                 if ((ret = avio_open_dyn_buf(&trk->mdat_buf)) < 0)
4171                     return ret;
4172             }
4173             pb = trk->mdat_buf;
4174         } else {
4175             if (!mov->mdat_buf) {
4176                 if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0)
4177                     return ret;
4178             }
4179             pb = mov->mdat_buf;
4180         }
4181     }
4182
4183     if (enc->codec_id == AV_CODEC_ID_AMR_NB) {
4184         /* We must find out how many AMR blocks there are in one packet */
4185         static uint16_t packed_size[16] =
4186             {13, 14, 16, 18, 20, 21, 27, 32, 6, 0, 0, 0, 0, 0, 0, 1};
4187         int len = 0;
4188
4189         while (len < size && samples_in_chunk < 100) {
4190             len += packed_size[(pkt->data[len] >> 3) & 0x0F];
4191             samples_in_chunk++;
4192         }
4193         if (samples_in_chunk > 1) {
4194             av_log(s, AV_LOG_ERROR, "fatal error, input is not a single packet, implement a AVParser for it\n");
4195             return -1;
4196         }
4197     } else if (enc->codec_id == AV_CODEC_ID_ADPCM_MS ||
4198                enc->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) {
4199         samples_in_chunk = enc->frame_size;
4200     } else if (trk->sample_size)
4201         samples_in_chunk = size / trk->sample_size;
4202     else
4203         samples_in_chunk = 1;
4204
4205     /* copy extradata if it exists */
4206     if (trk->vos_len == 0 && enc->extradata_size > 0 &&
4207         !TAG_IS_AVCI(trk->tag) &&
4208         (enc->codec_id != AV_CODEC_ID_DNXHD)) {
4209         trk->vos_len  = enc->extradata_size;
4210         trk->vos_data = av_malloc(trk->vos_len);
4211         if (!trk->vos_data) {
4212             ret = AVERROR(ENOMEM);
4213             goto err;
4214         }
4215         memcpy(trk->vos_data, enc->extradata, trk->vos_len);
4216     }
4217
4218     if (enc->codec_id == AV_CODEC_ID_AAC && pkt->size > 2 &&
4219         (AV_RB16(pkt->data) & 0xfff0) == 0xfff0) {
4220         if (!s->streams[pkt->stream_index]->nb_frames) {
4221             av_log(s, AV_LOG_ERROR, "Malformed AAC bitstream detected: "
4222                    "use the audio bitstream filter 'aac_adtstoasc' to fix it "
4223                    "('-bsf:a aac_adtstoasc' option with ffmpeg)\n");
4224             return -1;
4225         }
4226         av_log(s, AV_LOG_WARNING, "aac bitstream error\n");
4227     }
4228     if (enc->codec_id == AV_CODEC_ID_H264 && trk->vos_len > 0 && *(uint8_t *)trk->vos_data != 1 && !TAG_IS_AVCI(trk->tag)) {
4229         /* from x264 or from bytestream h264 */
4230         /* nal reformating needed */
4231         if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
4232             ff_avc_parse_nal_units_buf(pkt->data, &reformatted_data,
4233                                        &size);
4234             avio_write(pb, reformatted_data, size);
4235         } else {
4236             size = ff_avc_parse_nal_units(pb, pkt->data, pkt->size);
4237         }
4238     } else if (enc->codec_id == AV_CODEC_ID_HEVC && trk->vos_len > 6 &&
4239                (AV_RB24(trk->vos_data) == 1 || AV_RB32(trk->vos_data) == 1)) {
4240         /* extradata is Annex B, assume the bitstream is too and convert it */
4241         if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
4242             ff_hevc_annexb2mp4_buf(pkt->data, &reformatted_data, &size, 0, NULL);
4243             avio_write(pb, reformatted_data, size);
4244         } else {
4245             size = ff_hevc_annexb2mp4(pb, pkt->data, pkt->size, 0, NULL);
4246         }
4247 #if CONFIG_AC3_PARSER
4248     } else if (enc->codec_id == AV_CODEC_ID_EAC3) {
4249         size = handle_eac3(mov, pkt, trk);
4250         if (size < 0)
4251             return size;
4252         else if (!size)
4253             goto end;
4254         avio_write(pb, pkt->data, size);
4255 #endif
4256     } else {
4257         avio_write(pb, pkt->data, size);
4258     }
4259
4260     if ((enc->codec_id == AV_CODEC_ID_DNXHD ||
4261          enc->codec_id == AV_CODEC_ID_AC3) && !trk->vos_len) {
4262         /* copy frame to create needed atoms */
4263         trk->vos_len  = size;
4264         trk->vos_data = av_malloc(size);
4265         if (!trk->vos_data) {
4266             ret = AVERROR(ENOMEM);
4267             goto err;
4268         }
4269         memcpy(trk->vos_data, pkt->data, size);
4270     }
4271
4272     if (trk->entry >= trk->cluster_capacity) {
4273         unsigned new_capacity = 2 * (trk->entry + MOV_INDEX_CLUSTER_SIZE);
4274         if (av_reallocp_array(&trk->cluster, new_capacity,
4275                               sizeof(*trk->cluster))) {
4276             ret = AVERROR(ENOMEM);
4277             goto err;
4278         }
4279         trk->cluster_capacity = new_capacity;
4280     }
4281
4282     trk->cluster[trk->entry].pos              = avio_tell(pb) - size;
4283     trk->cluster[trk->entry].samples_in_chunk = samples_in_chunk;
4284     trk->cluster[trk->entry].chunkNum         = 0;
4285     trk->cluster[trk->entry].size             = size;
4286     trk->cluster[trk->entry].entries          = samples_in_chunk;
4287     trk->cluster[trk->entry].dts              = pkt->dts;
4288     if (!trk->entry && trk->start_dts != AV_NOPTS_VALUE) {
4289         if (!trk->frag_discont) {
4290             /* First packet of a new fragment. We already wrote the duration
4291              * of the last packet of the previous fragment based on track_duration,
4292              * which might not exactly match our dts. Therefore adjust the dts
4293              * of this packet to be what the previous packets duration implies. */
4294             trk->cluster[trk->entry].dts = trk->start_dts + trk->track_duration;
4295             /* We also may have written the pts and the corresponding duration
4296              * in sidx tags; make sure the sidx pts and duration match up with
4297              * the next fragment. This means the cts of the first sample must
4298              * be the same in all fragments. */
4299             pkt->pts = pkt->dts + trk->start_cts;
4300         } else {
4301             /* New fragment, but discontinuous from previous fragments.
4302              * Pretend the duration sum of the earlier fragments is
4303              * pkt->dts - trk->start_dts. */
4304             trk->frag_start = pkt->dts - trk->start_dts;
4305             trk->frag_discont = 0;
4306         }
4307     }
4308
4309     if (!trk->entry && trk->start_dts == AV_NOPTS_VALUE && !mov->use_editlist &&
4310         s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO) {
4311         /* Not using edit lists and shifting the first track to start from zero.
4312          * If the other streams start from a later timestamp, we won't be able
4313          * to signal the difference in starting time without an edit list.
4314          * Thus move the timestamp for this first sample to 0, increasing
4315          * its duration instead. */
4316         trk->cluster[trk->entry].dts = trk->start_dts = 0;
4317     }
4318     if (trk->start_dts == AV_NOPTS_VALUE) {
4319         trk->start_dts = pkt->dts;
4320         if (trk->frag_discont) {
4321             /* Pretend the whole stream started at dts=0, with earlier fragments
4322              * already written, with a duration summing up to pkt->dts. */
4323             trk->frag_start   = pkt->dts;
4324             trk->start_dts    = 0;
4325             trk->frag_discont = 0;
4326         } else if (pkt->dts && mov->fragments >= 1)
4327             av_log(s, AV_LOG_WARNING,
4328                    "Track %d starts with a nonzero dts %"PRId64", while the moov "
4329                    "already has been written. Set the delay_moov flag to handle "
4330                    "this case.\n",
4331                    pkt->stream_index, pkt->dts);
4332     }
4333     trk->track_duration = pkt->dts - trk->start_dts + pkt->duration;
4334     trk->last_sample_is_subtitle_end = 0;
4335
4336     if (pkt->pts == AV_NOPTS_VALUE) {
4337         av_log(s, AV_LOG_WARNING, "pts has no value\n");
4338         pkt->pts = pkt->dts;
4339     }
4340     if (pkt->dts != pkt->pts)
4341         trk->flags |= MOV_TRACK_CTTS;
4342     trk->cluster[trk->entry].cts   = pkt->pts - pkt->dts;
4343     trk->cluster[trk->entry].flags = 0;
4344     if (trk->start_cts == AV_NOPTS_VALUE)
4345         trk->start_cts = pkt->pts - pkt->dts;
4346
4347     if (enc->codec_id == AV_CODEC_ID_VC1) {
4348         mov_parse_vc1_frame(pkt, trk, mov->fragments);
4349     } else if (pkt->flags & AV_PKT_FLAG_KEY) {
4350         if (mov->mode == MODE_MOV && enc->codec_id == AV_CODEC_ID_MPEG2VIDEO &&
4351             trk->entry > 0) { // force sync sample for the first key frame
4352             mov_parse_mpeg2_frame(pkt, &trk->cluster[trk->entry].flags);
4353             if (trk->cluster[trk->entry].flags & MOV_PARTIAL_SYNC_SAMPLE)
4354                 trk->flags |= MOV_TRACK_STPS;
4355         } else {
4356             trk->cluster[trk->entry].flags = MOV_SYNC_SAMPLE;
4357         }
4358         if (trk->cluster[trk->entry].flags & MOV_SYNC_SAMPLE)
4359             trk->has_keyframes++;
4360     }
4361     trk->entry++;
4362     trk->sample_count += samples_in_chunk;
4363     mov->mdat_size    += size;
4364
4365     if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams)
4366         ff_mov_add_hinted_packet(s, pkt, trk->hint_track, trk->entry,
4367                                  reformatted_data, size);
4368
4369 end:
4370 err:
4371
4372     av_free(reformatted_data);
4373     return ret;
4374 }
4375
4376 static int mov_write_single_packet(AVFormatContext *s, AVPacket *pkt)
4377 {
4378         MOVMuxContext *mov = s->priv_data;
4379         MOVTrack *trk = &mov->tracks[pkt->stream_index];
4380         AVCodecContext *enc = trk->enc;
4381         int64_t frag_duration = 0;
4382         int size = pkt->size;
4383
4384         if (!pkt->size)
4385             return 0;             /* Discard 0 sized packets */
4386
4387         if (mov->flags & FF_MOV_FLAG_FRAG_DISCONT) {
4388             int i;
4389             for (i = 0; i < s->nb_streams; i++)
4390                 mov->tracks[i].frag_discont = 1;
4391             mov->flags &= ~FF_MOV_FLAG_FRAG_DISCONT;
4392         }
4393
4394         if (trk->entry && pkt->stream_index < s->nb_streams)
4395             frag_duration = av_rescale_q(pkt->dts - trk->cluster[0].dts,
4396                                          s->streams[pkt->stream_index]->time_base,
4397                                          AV_TIME_BASE_Q);
4398         if ((mov->max_fragment_duration &&
4399              frag_duration >= mov->max_fragment_duration) ||
4400              (mov->max_fragment_size && mov->mdat_size + size >= mov->max_fragment_size) ||
4401              (mov->flags & FF_MOV_FLAG_FRAG_KEYFRAME &&
4402               enc->codec_type == AVMEDIA_TYPE_VIDEO &&
4403               trk->entry && pkt->flags & AV_PKT_FLAG_KEY)) {
4404             if (frag_duration >= mov->min_fragment_duration)
4405                 mov_auto_flush_fragment(s);
4406         }
4407
4408         return ff_mov_write_packet(s, pkt);
4409 }
4410
4411 static int mov_write_subtitle_end_packet(AVFormatContext *s,
4412                                          int stream_index,
4413                                          int64_t dts) {
4414     AVPacket end;
4415     uint8_t data[2] = {0};
4416     int ret;
4417
4418     av_init_packet(&end);
4419     end.size = sizeof(data);
4420     end.data = data;
4421     end.pts = dts;
4422     end.dts = dts;
4423     end.duration = 0;
4424     end.stream_index = stream_index;
4425
4426     ret = mov_write_single_packet(s, &end);
4427     av_free_packet(&end);
4428
4429     return ret;
4430 }
4431
4432 static int mov_write_packet(AVFormatContext *s, AVPacket *pkt)
4433 {
4434     if (!pkt) {
4435         mov_flush_fragment(s);
4436         return 1;
4437     } else {
4438         int i;
4439         MOVMuxContext *mov = s->priv_data;
4440
4441         if (!pkt->size) return 0; /* Discard 0 sized packets */
4442
4443         /*
4444          * Subtitles require special handling.
4445          *
4446          * 1) For full complaince, every track must have a sample at
4447          * dts == 0, which is rarely true for subtitles. So, as soon
4448          * as we see any packet with dts > 0, write an empty subtitle
4449          * at dts == 0 for any subtitle track with no samples in it.
4450          *
4451          * 2) For each subtitle track, check if the current packet's
4452          * dts is past the duration of the last subtitle sample. If
4453          * so, we now need to write an end sample for that subtitle.
4454          *
4455          * This must be done conditionally to allow for subtitles that
4456          * immediately replace each other, in which case an end sample
4457          * is not needed, and is, in fact, actively harmful.
4458          *
4459          * 3) See mov_write_trailer for how the final end sample is
4460          * handled.
4461          */
4462         for (i = 0; i < mov->nb_streams; i++) {
4463             MOVTrack *trk = &mov->tracks[i];
4464             int ret;
4465
4466             if (trk->enc->codec_id == AV_CODEC_ID_MOV_TEXT &&
4467                 trk->track_duration < pkt->dts &&
4468                 (trk->entry == 0 || !trk->last_sample_is_subtitle_end)) {
4469                 ret = mov_write_subtitle_end_packet(s, i, trk->track_duration);
4470                 if (ret < 0) return ret;
4471                 trk->last_sample_is_subtitle_end = 1;
4472             }
4473         }
4474
4475         return mov_write_single_packet(s, pkt);
4476     }
4477 }
4478
4479 // QuickTime chapters involve an additional text track with the chapter names
4480 // as samples, and a tref pointing from the other tracks to the chapter one.
4481 static int mov_create_chapter_track(AVFormatContext *s, int tracknum)
4482 {
4483     AVIOContext *pb;
4484
4485     MOVMuxContext *mov = s->priv_data;
4486     MOVTrack *track = &mov->tracks[tracknum];
4487     AVPacket pkt = { .stream_index = tracknum, .flags = AV_PKT_FLAG_KEY };
4488     int i, len;
4489
4490     track->mode = mov->mode;
4491     track->tag = MKTAG('t','e','x','t');
4492     track->timescale = MOV_TIMESCALE;
4493     track->enc = avcodec_alloc_context3(NULL);
4494     if (!track->enc)
4495         return AVERROR(ENOMEM);
4496     track->enc->codec_type = AVMEDIA_TYPE_SUBTITLE;
4497 #if 0
4498     // These properties are required to make QT recognize the chapter track
4499     uint8_t chapter_properties[43] = { 0, 0, 0, 0, 0, 0, 0, 1, };
4500     if (ff_alloc_extradata(track->enc, sizeof(chapter_properties)))
4501         return AVERROR(ENOMEM);
4502     memcpy(track->enc->extradata, chapter_properties, sizeof(chapter_properties));
4503 #else
4504     if (avio_open_dyn_buf(&pb) >= 0) {
4505         int size;
4506         uint8_t *buf;
4507
4508         /* Stub header (usually for Quicktime chapter track) */
4509         // TextSampleEntry
4510         avio_wb32(pb, 0x01); // displayFlags
4511         avio_w8(pb, 0x00);   // horizontal justification
4512         avio_w8(pb, 0x00);   // vertical justification
4513         avio_w8(pb, 0x00);   // bgColourRed
4514         avio_w8(pb, 0x00);   // bgColourGreen
4515         avio_w8(pb, 0x00);   // bgColourBlue
4516         avio_w8(pb, 0x00);   // bgColourAlpha
4517         // BoxRecord
4518         avio_wb16(pb, 0x00); // defTextBoxTop
4519         avio_wb16(pb, 0x00); // defTextBoxLeft
4520         avio_wb16(pb, 0x00); // defTextBoxBottom
4521         avio_wb16(pb, 0x00); // defTextBoxRight
4522         // StyleRecord
4523         avio_wb16(pb, 0x00); // startChar
4524         avio_wb16(pb, 0x00); // endChar
4525         avio_wb16(pb, 0x01); // fontID
4526         avio_w8(pb, 0x00);   // fontStyleFlags
4527         avio_w8(pb, 0x00);   // fontSize
4528         avio_w8(pb, 0x00);   // fgColourRed
4529         avio_w8(pb, 0x00);   // fgColourGreen
4530         avio_w8(pb, 0x00);   // fgColourBlue
4531         avio_w8(pb, 0x00);   // fgColourAlpha
4532         // FontTableBox
4533         avio_wb32(pb, 0x0D); // box size
4534         ffio_wfourcc(pb, "ftab"); // box atom name
4535         avio_wb16(pb, 0x01); // entry count
4536         // FontRecord
4537         avio_wb16(pb, 0x01); // font ID
4538         avio_w8(pb, 0x00);   // font name length
4539
4540         if ((size = avio_close_dyn_buf(pb, &buf)) > 0) {
4541             track->enc->extradata = buf;
4542             track->enc->extradata_size = size;
4543         } else {
4544             av_freep(&buf);
4545         }
4546     }
4547 #endif
4548
4549     for (i = 0; i < s->nb_chapters; i++) {
4550         AVChapter *c = s->chapters[i];
4551         AVDictionaryEntry *t;
4552
4553         int64_t end = av_rescale_q(c->end, c->time_base, (AVRational){1,MOV_TIMESCALE});
4554         pkt.pts = pkt.dts = av_rescale_q(c->start, c->time_base, (AVRational){1,MOV_TIMESCALE});
4555         pkt.duration = end - pkt.dts;
4556
4557         if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
4558             const char encd[12] = {
4559                 0x00, 0x00, 0x00, 0x0C,
4560                 'e',  'n',  'c',  'd',
4561                 0x00, 0x00, 0x01, 0x00 };
4562             len      = strlen(t->value);
4563             pkt.size = len + 2 + 12;
4564             pkt.data = av_malloc(pkt.size);
4565             if (!pkt.data)
4566                 return AVERROR(ENOMEM);
4567             AV_WB16(pkt.data, len);
4568             memcpy(pkt.data + 2, t->value, len);
4569             memcpy(pkt.data + len + 2, encd, sizeof(encd));
4570             ff_mov_write_packet(s, &pkt);
4571             av_freep(&pkt.data);
4572         }
4573     }
4574
4575     return 0;
4576 }
4577
4578 static int mov_create_timecode_track(AVFormatContext *s, int index, int src_index, const char *tcstr)
4579 {
4580     int ret;
4581     MOVMuxContext *mov  = s->priv_data;
4582     MOVTrack *track     = &mov->tracks[index];
4583     AVStream *src_st    = s->streams[src_index];
4584     AVTimecode tc;
4585     AVPacket pkt    = {.stream_index = index, .flags = AV_PKT_FLAG_KEY, .size = 4};
4586     AVRational rate = find_fps(s, src_st);
4587
4588     /* compute the frame number */
4589     ret = av_timecode_init_from_string(&tc, rate, tcstr, s);
4590     if (ret < 0)
4591         return ret;
4592
4593     /* tmcd track based on video stream */
4594     track->mode      = mov->mode;
4595     track->tag       = MKTAG('t','m','c','d');
4596     track->src_track = src_index;
4597     track->timescale = mov->tracks[src_index].timescale;
4598     if (tc.flags & AV_TIMECODE_FLAG_DROPFRAME)
4599         track->timecode_flags |= MOV_TIMECODE_FLAG_DROPFRAME;
4600
4601     /* set st to src_st for metadata access*/
4602     track->st = src_st;
4603
4604     /* encode context: tmcd data stream */
4605     track->enc = avcodec_alloc_context3(NULL);
4606     if (!track->enc)
4607         return AVERROR(ENOMEM);
4608     track->enc->codec_type = AVMEDIA_TYPE_DATA;
4609     track->enc->codec_tag  = track->tag;
4610     track->enc->time_base  = av_inv_q(rate);
4611
4612     /* the tmcd track just contains one packet with the frame number */
4613     pkt.data = av_malloc(pkt.size);
4614     if (!pkt.data)
4615         return AVERROR(ENOMEM);
4616     AV_WB32(pkt.data, tc.start);
4617     ret = ff_mov_write_packet(s, &pkt);
4618     av_free(pkt.data);
4619     return ret;
4620 }
4621
4622 /*
4623  * st->disposition controls the "enabled" flag in the tkhd tag.
4624  * QuickTime will not play a track if it is not enabled.  So make sure
4625  * that one track of each type (audio, video, subtitle) is enabled.
4626  *
4627  * Subtitles are special.  For audio and video, setting "enabled" also
4628  * makes the track "default" (i.e. it is rendered when played). For
4629  * subtitles, an "enabled" subtitle is not rendered by default, but
4630  * if no subtitle is enabled, the subtitle menu in QuickTime will be
4631  * empty!
4632  */
4633 static void enable_tracks(AVFormatContext *s)
4634 {
4635     MOVMuxContext *mov = s->priv_data;
4636     int i;
4637     int enabled[AVMEDIA_TYPE_NB];
4638     int first[AVMEDIA_TYPE_NB];
4639
4640     for (i = 0; i < AVMEDIA_TYPE_NB; i++) {
4641         enabled[i] = 0;
4642         first[i] = -1;
4643     }
4644
4645     for (i = 0; i < s->nb_streams; i++) {
4646         AVStream *st = s->streams[i];
4647
4648         if (st->codec->codec_type <= AVMEDIA_TYPE_UNKNOWN ||
4649             st->codec->codec_type >= AVMEDIA_TYPE_NB)
4650             continue;
4651
4652         if (first[st->codec->codec_type] < 0)
4653             first[st->codec->codec_type] = i;
4654         if (st->disposition & AV_DISPOSITION_DEFAULT) {
4655             mov->tracks[i].flags |= MOV_TRACK_ENABLED;
4656             enabled[st->codec->codec_type]++;
4657         }
4658     }
4659
4660     for (i = 0; i < AVMEDIA_TYPE_NB; i++) {
4661         switch (i) {
4662         case AVMEDIA_TYPE_VIDEO:
4663         case AVMEDIA_TYPE_AUDIO:
4664         case AVMEDIA_TYPE_SUBTITLE:
4665             if (enabled[i] > 1)
4666                 mov->per_stream_grouping = 1;
4667             if (!enabled[i] && first[i] >= 0)
4668                 mov->tracks[first[i]].flags |= MOV_TRACK_ENABLED;
4669             break;
4670         }
4671     }
4672 }
4673
4674 static void mov_free(AVFormatContext *s)
4675 {
4676     MOVMuxContext *mov = s->priv_data;
4677     int i;
4678
4679     if (mov->chapter_track) {
4680         if (mov->tracks[mov->chapter_track].enc)
4681             av_freep(&mov->tracks[mov->chapter_track].enc->extradata);
4682         av_freep(&mov->tracks[mov->chapter_track].enc);
4683     }
4684
4685     for (i = 0; i < mov->nb_streams; i++) {
4686         if (mov->tracks[i].tag == MKTAG('r','t','p',' '))
4687             ff_mov_close_hinting(&mov->tracks[i]);
4688         else if (mov->tracks[i].tag == MKTAG('t','m','c','d') && mov->nb_meta_tmcd)
4689             av_freep(&mov->tracks[i].enc);
4690         av_freep(&mov->tracks[i].cluster);
4691         av_freep(&mov->tracks[i].frag_info);
4692
4693         if (mov->tracks[i].vos_len)
4694             av_freep(&mov->tracks[i].vos_data);
4695     }
4696
4697     av_freep(&mov->tracks);
4698 }
4699
4700 static uint32_t rgb_to_yuv(uint32_t rgb)
4701 {
4702     uint8_t r, g, b;
4703     int y, cb, cr;
4704
4705     r = (rgb >> 16) & 0xFF;
4706     g = (rgb >>  8) & 0xFF;
4707     b = (rgb      ) & 0xFF;
4708
4709     y  = av_clip_uint8( 16. +  0.257 * r + 0.504 * g + 0.098 * b);
4710     cb = av_clip_uint8(128. -  0.148 * r - 0.291 * g + 0.439 * b);
4711     cr = av_clip_uint8(128. +  0.439 * r - 0.368 * g - 0.071 * b);
4712
4713     return (y << 16) | (cr << 8) | cb;
4714 }
4715
4716 static int mov_create_dvd_sub_decoder_specific_info(MOVTrack *track,
4717                                                     AVStream *st)
4718 {
4719     int i, width = 720, height = 480;
4720     int have_palette = 0, have_size = 0;
4721     uint32_t palette[16];
4722     char *cur = st->codec->extradata;
4723
4724     while (cur && *cur) {
4725         if (strncmp("palette:", cur, 8) == 0) {
4726             int i, count;
4727             count = sscanf(cur + 8,
4728                 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
4729                 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
4730                 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
4731                 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32"",
4732                 &palette[ 0], &palette[ 1], &palette[ 2], &palette[ 3],
4733                 &palette[ 4], &palette[ 5], &palette[ 6], &palette[ 7],
4734                 &palette[ 8], &palette[ 9], &palette[10], &palette[11],
4735                 &palette[12], &palette[13], &palette[14], &palette[15]);
4736
4737             for (i = 0; i < count; i++) {
4738                 palette[i] = rgb_to_yuv(palette[i]);
4739             }
4740             have_palette = 1;
4741         } else if (!strncmp("size:", cur, 5)) {
4742             sscanf(cur + 5, "%dx%d", &width, &height);
4743             have_size = 1;
4744         }
4745         if (have_palette && have_size)
4746             break;
4747         cur += strcspn(cur, "\n\r");
4748         cur += strspn(cur, "\n\r");
4749     }
4750     if (have_palette) {
4751         track->vos_data = av_malloc(16*4);
4752         if (!track->vos_data)
4753             return AVERROR(ENOMEM);
4754         for (i = 0; i < 16; i++) {
4755             AV_WB32(track->vos_data + i * 4, palette[i]);
4756         }
4757         track->vos_len = 16 * 4;
4758     }
4759     st->codec->width = width;
4760     st->codec->height = track->height = height;
4761
4762     return 0;
4763 }
4764
4765 static int mov_write_header(AVFormatContext *s)
4766 {
4767     AVIOContext *pb = s->pb;
4768     MOVMuxContext *mov = s->priv_data;
4769     AVDictionaryEntry *t, *global_tcr = av_dict_get(s->metadata, "timecode", NULL, 0);
4770     int i, ret, hint_track = 0, tmcd_track = 0;
4771
4772     mov->fc = s;
4773
4774     /* Default mode == MP4 */
4775     mov->mode = MODE_MP4;
4776
4777     if (s->oformat) {
4778         if (!strcmp("3gp", s->oformat->name)) mov->mode = MODE_3GP;
4779         else if (!strcmp("3g2", s->oformat->name)) mov->mode = MODE_3GP|MODE_3G2;
4780         else if (!strcmp("mov", s->oformat->name)) mov->mode = MODE_MOV;
4781         else if (!strcmp("psp", s->oformat->name)) mov->mode = MODE_PSP;
4782         else if (!strcmp("ipod",s->oformat->name)) mov->mode = MODE_IPOD;
4783         else if (!strcmp("ismv",s->oformat->name)) mov->mode = MODE_ISM;
4784         else if (!strcmp("f4v", s->oformat->name)) mov->mode = MODE_F4V;
4785     }
4786
4787     if (s->flags & AVFMT_FLAG_BITEXACT)
4788         mov->exact = 1;
4789
4790     if (mov->flags & FF_MOV_FLAG_DELAY_MOOV)
4791         mov->flags |= FF_MOV_FLAG_EMPTY_MOOV;
4792
4793     /* Set the FRAGMENT flag if any of the fragmentation methods are
4794      * enabled. */
4795     if (mov->max_fragment_duration || mov->max_fragment_size ||
4796         mov->flags & (FF_MOV_FLAG_EMPTY_MOOV |
4797                       FF_MOV_FLAG_FRAG_KEYFRAME |
4798                       FF_MOV_FLAG_FRAG_CUSTOM))
4799         mov->flags |= FF_MOV_FLAG_FRAGMENT;
4800
4801     /* Set other implicit flags immediately */
4802     if (mov->mode == MODE_ISM)
4803         mov->flags |= FF_MOV_FLAG_EMPTY_MOOV | FF_MOV_FLAG_SEPARATE_MOOF |
4804                       FF_MOV_FLAG_FRAGMENT;
4805     if (mov->flags & FF_MOV_FLAG_DASH)
4806         mov->flags |= FF_MOV_FLAG_FRAGMENT | FF_MOV_FLAG_EMPTY_MOOV |
4807                       FF_MOV_FLAG_DEFAULT_BASE_MOOF;
4808
4809     if (mov->flags & FF_MOV_FLAG_FASTSTART) {
4810         mov->reserved_moov_size = -1;
4811     }
4812
4813     if (mov->use_editlist < 0) {
4814         mov->use_editlist = 1;
4815         if (mov->flags & FF_MOV_FLAG_FRAGMENT &&
4816             !(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
4817             // If we can avoid needing an edit list by shifting the
4818             // tracks, prefer that over (trying to) write edit lists
4819             // in fragmented output.
4820             if (s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO ||
4821                 s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO)
4822                 mov->use_editlist = 0;
4823         }
4824     }
4825     if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV &&
4826         !(mov->flags & FF_MOV_FLAG_DELAY_MOOV) && mov->use_editlist)
4827         av_log(s, AV_LOG_WARNING, "No meaningful edit list will be written when using empty_moov without delay_moov\n");
4828
4829     if (!mov->use_editlist && s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO)
4830         s->avoid_negative_ts = AVFMT_AVOID_NEG_TS_MAKE_ZERO;
4831
4832     /* Non-seekable output is ok if using fragmentation. If ism_lookahead
4833      * is enabled, we don't support non-seekable output at all. */
4834     if (!s->pb->seekable &&
4835         (!(mov->flags & FF_MOV_FLAG_FRAGMENT) || mov->ism_lookahead)) {
4836         av_log(s, AV_LOG_ERROR, "muxer does not support non seekable output\n");
4837         return AVERROR(EINVAL);
4838     }
4839
4840     if (!(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
4841         if ((ret = mov_write_identification(pb, s)) < 0)
4842             return ret;
4843     }
4844
4845     mov->nb_streams = s->nb_streams;
4846     if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters)
4847         mov->chapter_track = mov->nb_streams++;
4848
4849     if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
4850         /* Add hint tracks for each audio and video stream */
4851         hint_track = mov->nb_streams;
4852         for (i = 0; i < s->nb_streams; i++) {
4853             AVStream *st = s->streams[i];
4854             if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO ||
4855                 st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
4856                 mov->nb_streams++;
4857             }
4858         }
4859     }
4860
4861     if (mov->mode == MODE_MOV) {
4862         tmcd_track = mov->nb_streams;
4863
4864         /* +1 tmcd track for each video stream with a timecode */
4865         for (i = 0; i < s->nb_streams; i++) {
4866             AVStream *st = s->streams[i];
4867             if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
4868                 (global_tcr || av_dict_get(st->metadata, "timecode", NULL, 0)))
4869                 mov->nb_meta_tmcd++;
4870         }
4871
4872         /* check if there is already a tmcd track to remux */
4873         if (mov->nb_meta_tmcd) {
4874             for (i = 0; i < s->nb_streams; i++) {
4875                 AVStream *st = s->streams[i];
4876                 if (st->codec->codec_tag == MKTAG('t','m','c','d')) {
4877                     av_log(s, AV_LOG_WARNING, "You requested a copy of the original timecode track "
4878                            "so timecode metadata are now ignored\n");
4879                     mov->nb_meta_tmcd = 0;
4880                 }
4881             }
4882         }
4883
4884         mov->nb_streams += mov->nb_meta_tmcd;
4885     }
4886
4887     // Reserve an extra stream for chapters for the case where chapters
4888     // are written in the trailer
4889     mov->tracks = av_mallocz_array((mov->nb_streams + 1), sizeof(*mov->tracks));
4890     if (!mov->tracks)
4891         return AVERROR(ENOMEM);
4892
4893     for (i = 0; i < s->nb_streams; i++) {
4894         AVStream *st= s->streams[i];
4895         MOVTrack *track= &mov->tracks[i];
4896         AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0);
4897
4898         track->st  = st;
4899         track->enc = st->codec;
4900         track->language = ff_mov_iso639_to_lang(lang?lang->value:"und", mov->mode!=MODE_MOV);
4901         if (track->language < 0)
4902             track->language = 0;
4903         track->mode = mov->mode;
4904         track->tag  = mov_find_codec_tag(s, track);
4905         if (!track->tag) {
4906             av_log(s, AV_LOG_ERROR, "Could not find tag for codec %s in stream #%d, "
4907                    "codec not currently supported in container\n",
4908                    avcodec_get_name(st->codec->codec_id), i);
4909             ret = AVERROR(EINVAL);
4910             goto error;
4911         }
4912         /* If hinting of this track is enabled by a later hint track,
4913          * this is updated. */
4914         track->hint_track = -1;
4915         track->start_dts  = AV_NOPTS_VALUE;
4916         track->start_cts  = AV_NOPTS_VALUE;
4917         if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
4918             if (track->tag == MKTAG('m','x','3','p') || track->tag == MKTAG('m','x','3','n') ||
4919                 track->tag == MKTAG('m','x','4','p') || track->tag == MKTAG('m','x','4','n') ||
4920                 track->tag == MKTAG('m','x','5','p') || track->tag == MKTAG('m','x','5','n')) {
4921                 if (st->codec->width != 720 || (st->codec->height != 608 && st->codec->height != 512)) {
4922                     av_log(s, AV_LOG_ERROR, "D-10/IMX must use 720x608 or 720x512 video resolution\n");
4923                     ret = AVERROR(EINVAL);
4924                     goto error;
4925                 }
4926                 track->height = track->tag >> 24 == 'n' ? 486 : 576;
4927             }
4928             if (mov->video_track_timescale) {
4929                 track->timescale = mov->video_track_timescale;
4930             } else {
4931                 track->timescale = st->time_base.den;
4932                 while(track->timescale < 10000)
4933                     track->timescale *= 2;
4934             }
4935             if (st->codec->width > 65535 || st->codec->height > 65535) {
4936                 av_log(s, AV_LOG_ERROR, "Resolution %dx%d too large for mov/mp4\n", st->codec->width, st->codec->height);
4937                 ret = AVERROR(EINVAL);
4938                 goto error;
4939             }
4940             if (track->mode == MODE_MOV && track->timescale > 100000)
4941                 av_log(s, AV_LOG_WARNING,
4942                        "WARNING codec timebase is very high. If duration is too long,\n"
4943                        "file may not be playable by quicktime. Specify a shorter timebase\n"
4944                        "or choose different container.\n");
4945         } else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
4946             track->timescale = st->codec->sample_rate;
4947             if (!st->codec->frame_size && !av_get_bits_per_sample(st->codec->codec_id)) {
4948                 av_log(s, AV_LOG_WARNING, "track %d: codec frame size is not set\n", i);
4949                 track->audio_vbr = 1;
4950             }else if (st->codec->codec_id == AV_CODEC_ID_ADPCM_MS ||
4951                      st->codec->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
4952                      st->codec->codec_id == AV_CODEC_ID_ILBC){
4953                 if (!st->codec->block_align) {
4954                     av_log(s, AV_LOG_ERROR, "track %d: codec block align is not set for adpcm\n", i);
4955                     ret = AVERROR(EINVAL);
4956                     goto error;
4957                 }
4958                 track->sample_size = st->codec->block_align;
4959             }else if (st->codec->frame_size > 1){ /* assume compressed audio */
4960                 track->audio_vbr = 1;
4961             }else{
4962                 track->sample_size = (av_get_bits_per_sample(st->codec->codec_id) >> 3) * st->codec->channels;
4963             }
4964             if (st->codec->codec_id == AV_CODEC_ID_ILBC ||
4965                 st->codec->codec_id == AV_CODEC_ID_ADPCM_IMA_QT) {
4966                 track->audio_vbr = 1;
4967             }
4968             if (track->mode != MODE_MOV &&
4969                 track->enc->codec_id == AV_CODEC_ID_MP3 && track->timescale < 16000) {
4970                 av_log(s, AV_LOG_ERROR, "track %d: muxing mp3 at %dhz is not supported\n",
4971                        i, track->enc->sample_rate);
4972                 ret = AVERROR(EINVAL);
4973                 goto error;
4974             }
4975         } else if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
4976             track->timescale = st->time_base.den;
4977         } else if (st->codec->codec_type == AVMEDIA_TYPE_DATA) {
4978             track->timescale = st->time_base.den;
4979         } else {
4980             track->timescale = MOV_TIMESCALE;
4981         }
4982         if (!track->height)
4983             track->height = st->codec->height;
4984         /* The ism specific timescale isn't mandatory, but is assumed by
4985          * some tools, such as mp4split. */
4986         if (mov->mode == MODE_ISM)
4987             track->timescale = 10000000;
4988
4989         avpriv_set_pts_info(st, 64, 1, track->timescale);
4990
4991         /* copy extradata if it exists */
4992         if (st->codec->extradata_size) {
4993             if (st->codec->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
4994                 mov_create_dvd_sub_decoder_specific_info(track, st);
4995             else if (!TAG_IS_AVCI(track->tag) && st->codec->codec_id != AV_CODEC_ID_DNXHD) {
4996                 track->vos_len  = st->codec->extradata_size;
4997                 track->vos_data = av_malloc(track->vos_len);
4998                 if (!track->vos_data) {
4999                     ret = AVERROR(ENOMEM);
5000                     goto error;
5001                 }
5002                 memcpy(track->vos_data, st->codec->extradata, track->vos_len);
5003             }
5004         }
5005     }
5006
5007     for (i = 0; i < s->nb_streams; i++) {
5008         int j;
5009         AVStream *st= s->streams[i];
5010         MOVTrack *track= &mov->tracks[i];
5011
5012         if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO ||
5013             track->enc->channel_layout != AV_CH_LAYOUT_MONO)
5014             continue;
5015
5016         for (j = 0; j < s->nb_streams; j++) {
5017             AVStream *stj= s->streams[j];
5018             MOVTrack *trackj= &mov->tracks[j];
5019             if (j == i)
5020                 continue;
5021
5022             if (stj->codec->codec_type != AVMEDIA_TYPE_AUDIO ||
5023                 trackj->enc->channel_layout != AV_CH_LAYOUT_MONO ||
5024                 trackj->language != track->language ||
5025                 trackj->tag != track->tag
5026             )
5027                 continue;
5028             track->multichannel_as_mono++;
5029         }
5030     }
5031
5032     enable_tracks(s);
5033
5034
5035     if (mov->reserved_moov_size){
5036         mov->reserved_moov_pos= avio_tell(pb);
5037         if (mov->reserved_moov_size > 0)
5038             avio_skip(pb, mov->reserved_moov_size);
5039     }
5040
5041     if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
5042         /* If no fragmentation options have been set, set a default. */
5043         if (!(mov->flags & (FF_MOV_FLAG_FRAG_KEYFRAME |
5044                             FF_MOV_FLAG_FRAG_CUSTOM)) &&
5045             !mov->max_fragment_duration && !mov->max_fragment_size)
5046             mov->flags |= FF_MOV_FLAG_FRAG_KEYFRAME;
5047     } else {
5048         if (mov->flags & FF_MOV_FLAG_FASTSTART)
5049             mov->reserved_moov_pos = avio_tell(pb);
5050         mov_write_mdat_tag(pb, mov);
5051     }
5052
5053     if (t = av_dict_get(s->metadata, "creation_time", NULL, 0))
5054         mov->time = ff_iso8601_to_unix_time(t->value);
5055     if (mov->time)
5056         mov->time += 0x7C25B080; // 1970 based -> 1904 based
5057
5058     if (mov->chapter_track)
5059         if ((ret = mov_create_chapter_track(s, mov->chapter_track)) < 0)
5060             goto error;
5061
5062     if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
5063         /* Initialize the hint tracks for each audio and video stream */
5064         for (i = 0; i < s->nb_streams; i++) {
5065             AVStream *st = s->streams[i];
5066             if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO ||
5067                 st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
5068                 if ((ret = ff_mov_init_hinting(s, hint_track, i)) < 0)
5069                     goto error;
5070                 hint_track++;
5071             }
5072         }
5073     }
5074
5075     if (mov->nb_meta_tmcd) {
5076         /* Initialize the tmcd tracks */
5077         for (i = 0; i < s->nb_streams; i++) {
5078             AVStream *st = s->streams[i];
5079             t = global_tcr;
5080
5081             if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
5082                 if (!t)
5083                     t = av_dict_get(st->metadata, "timecode", NULL, 0);
5084                 if (!t)
5085                     continue;
5086                 if ((ret = mov_create_timecode_track(s, tmcd_track, i, t->value)) < 0)
5087                     goto error;
5088                 tmcd_track++;
5089             }
5090         }
5091     }
5092
5093     avio_flush(pb);
5094
5095     if (mov->flags & FF_MOV_FLAG_ISML)
5096         mov_write_isml_manifest(pb, mov);
5097
5098     if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV &&
5099         !(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
5100         if ((ret = mov_write_moov_tag(pb, mov, s)) < 0)
5101             return ret;
5102         mov->fragments++;
5103         if (mov->flags & FF_MOV_FLAG_FASTSTART)
5104             mov->reserved_moov_pos = avio_tell(pb);
5105     }
5106
5107     return 0;
5108  error:
5109     mov_free(s);
5110     return ret;
5111 }
5112
5113 static int get_moov_size(AVFormatContext *s)
5114 {
5115     int ret;
5116     AVIOContext *moov_buf;
5117     MOVMuxContext *mov = s->priv_data;
5118
5119     if ((ret = ffio_open_null_buf(&moov_buf)) < 0)
5120         return ret;
5121     if ((ret = mov_write_moov_tag(moov_buf, mov, s)) < 0)
5122         return ret;
5123     return ffio_close_null_buf(moov_buf);
5124 }
5125
5126 static int get_sidx_size(AVFormatContext *s)
5127 {
5128     int ret;
5129     AVIOContext *buf;
5130     MOVMuxContext *mov = s->priv_data;
5131
5132     if ((ret = ffio_open_null_buf(&buf)) < 0)
5133         return ret;
5134     mov_write_sidx_tags(buf, mov, -1, 0);
5135     return ffio_close_null_buf(buf);
5136 }
5137
5138 /*
5139  * This function gets the moov size if moved to the top of the file: the chunk
5140  * offset table can switch between stco (32-bit entries) to co64 (64-bit
5141  * entries) when the moov is moved to the beginning, so the size of the moov
5142  * would change. It also updates the chunk offset tables.
5143  */
5144 static int compute_moov_size(AVFormatContext *s)
5145 {
5146     int i, moov_size, moov_size2;
5147     MOVMuxContext *mov = s->priv_data;
5148
5149     moov_size = get_moov_size(s);
5150     if (moov_size < 0)
5151         return moov_size;
5152
5153     for (i = 0; i < mov->nb_streams; i++)
5154         mov->tracks[i].data_offset += moov_size;
5155
5156     moov_size2 = get_moov_size(s);
5157     if (moov_size2 < 0)
5158         return moov_size2;
5159
5160     /* if the size changed, we just switched from stco to co64 and need to
5161      * update the offsets */
5162     if (moov_size2 != moov_size)
5163         for (i = 0; i < mov->nb_streams; i++)
5164             mov->tracks[i].data_offset += moov_size2 - moov_size;
5165
5166     return moov_size2;
5167 }
5168
5169 static int compute_sidx_size(AVFormatContext *s)
5170 {
5171     int i, sidx_size;
5172     MOVMuxContext *mov = s->priv_data;
5173
5174     sidx_size = get_sidx_size(s);
5175     if (sidx_size < 0)
5176         return sidx_size;
5177
5178     for (i = 0; i < mov->nb_streams; i++)
5179         mov->tracks[i].data_offset += sidx_size;
5180
5181     return sidx_size;
5182 }
5183
5184 static int shift_data(AVFormatContext *s)
5185 {
5186     int ret = 0, moov_size;
5187     MOVMuxContext *mov = s->priv_data;
5188     int64_t pos, pos_end = avio_tell(s->pb);
5189     uint8_t *buf, *read_buf[2];
5190     int read_buf_id = 0;
5191     int read_size[2];
5192     AVIOContext *read_pb;
5193
5194     if (mov->flags & FF_MOV_FLAG_FRAGMENT)
5195         moov_size = compute_sidx_size(s);
5196     else
5197         moov_size = compute_moov_size(s);
5198     if (moov_size < 0)
5199         return moov_size;
5200
5201     buf = av_malloc(moov_size * 2);
5202     if (!buf)
5203         return AVERROR(ENOMEM);
5204     read_buf[0] = buf;
5205     read_buf[1] = buf + moov_size;
5206
5207     /* Shift the data: the AVIO context of the output can only be used for
5208      * writing, so we re-open the same output, but for reading. It also avoids
5209      * a read/seek/write/seek back and forth. */
5210     avio_flush(s->pb);
5211     ret = avio_open(&read_pb, s->filename, AVIO_FLAG_READ);
5212     if (ret < 0) {
5213         av_log(s, AV_LOG_ERROR, "Unable to re-open %s output file for "
5214                "the second pass (faststart)\n", s->filename);
5215         goto end;
5216     }
5217
5218     /* mark the end of the shift to up to the last data we wrote, and get ready
5219      * for writing */
5220     pos_end = avio_tell(s->pb);
5221     avio_seek(s->pb, mov->reserved_moov_pos + moov_size, SEEK_SET);
5222
5223     /* start reading at where the new moov will be placed */
5224     avio_seek(read_pb, mov->reserved_moov_pos, SEEK_SET);
5225     pos = avio_tell(read_pb);
5226
5227 #define READ_BLOCK do {                                                             \
5228     read_size[read_buf_id] = avio_read(read_pb, read_buf[read_buf_id], moov_size);  \
5229     read_buf_id ^= 1;                                                               \
5230 } while (0)
5231
5232     /* shift data by chunk of at most moov_size */
5233     READ_BLOCK;
5234     do {
5235         int n;
5236         READ_BLOCK;
5237         n = read_size[read_buf_id];
5238         if (n <= 0)
5239             break;
5240         avio_write(s->pb, read_buf[read_buf_id], n);
5241         pos += n;
5242     } while (pos < pos_end);
5243     avio_close(read_pb);
5244
5245 end:
5246     av_free(buf);
5247     return ret;
5248 }
5249
5250 static int mov_write_trailer(AVFormatContext *s)
5251 {
5252     MOVMuxContext *mov = s->priv_data;
5253     AVIOContext *pb = s->pb;
5254     int res = 0;
5255     int i;
5256     int64_t moov_pos;
5257
5258     /*
5259      * Before actually writing the trailer, make sure that there are no
5260      * dangling subtitles, that need a terminating sample.
5261      */
5262     for (i = 0; i < mov->nb_streams; i++) {
5263         MOVTrack *trk = &mov->tracks[i];
5264         if (trk->enc->codec_id == AV_CODEC_ID_MOV_TEXT &&
5265             !trk->last_sample_is_subtitle_end) {
5266             mov_write_subtitle_end_packet(s, i, trk->track_duration);
5267             trk->last_sample_is_subtitle_end = 1;
5268         }
5269     }
5270
5271     // If there were no chapters when the header was written, but there
5272     // are chapters now, write them in the trailer.  This only works
5273     // when we are not doing fragments.
5274     if (!mov->chapter_track && !(mov->flags & FF_MOV_FLAG_FRAGMENT)) {
5275         if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters) {
5276             mov->chapter_track = mov->nb_streams++;
5277             if ((res = mov_create_chapter_track(s, mov->chapter_track)) < 0)
5278                 goto error;
5279         }
5280     }
5281
5282     if (!(mov->flags & FF_MOV_FLAG_FRAGMENT)) {
5283         moov_pos = avio_tell(pb);
5284
5285         /* Write size of mdat tag */
5286         if (mov->mdat_size + 8 <= UINT32_MAX) {
5287             avio_seek(pb, mov->mdat_pos, SEEK_SET);
5288             avio_wb32(pb, mov->mdat_size + 8);
5289         } else {
5290             /* overwrite 'wide' placeholder atom */
5291             avio_seek(pb, mov->mdat_pos - 8, SEEK_SET);
5292             /* special value: real atom size will be 64 bit value after
5293              * tag field */
5294             avio_wb32(pb, 1);
5295             ffio_wfourcc(pb, "mdat");
5296             avio_wb64(pb, mov->mdat_size + 16);
5297         }
5298         avio_seek(pb, mov->reserved_moov_size > 0 ? mov->reserved_moov_pos : moov_pos, SEEK_SET);
5299
5300         if (mov->flags & FF_MOV_FLAG_FASTSTART) {
5301             av_log(s, AV_LOG_INFO, "Starting second pass: moving the moov atom to the beginning of the file\n");
5302             res = shift_data(s);
5303             if (res == 0) {
5304                 avio_seek(pb, mov->reserved_moov_pos, SEEK_SET);
5305                 if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
5306                     goto error;
5307             }
5308         } else if (mov->reserved_moov_size > 0) {
5309             int64_t size;
5310             if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
5311                 goto error;
5312             size = mov->reserved_moov_size - (avio_tell(pb) - mov->reserved_moov_pos);
5313             if (size < 8){
5314                 av_log(s, AV_LOG_ERROR, "reserved_moov_size is too small, needed %"PRId64" additional\n", 8-size);
5315                 res = AVERROR(EINVAL);
5316                 goto error;
5317             }
5318             avio_wb32(pb, size);
5319             ffio_wfourcc(pb, "free");
5320             ffio_fill(pb, 0, size - 8);
5321             avio_seek(pb, moov_pos, SEEK_SET);
5322         } else {
5323             if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
5324                 goto error;
5325         }
5326         res = 0;
5327     } else {
5328         mov_auto_flush_fragment(s);
5329         for (i = 0; i < mov->nb_streams; i++)
5330            mov->tracks[i].data_offset = 0;
5331         if (mov->flags & FF_MOV_FLAG_FASTSTART) {
5332             av_log(s, AV_LOG_INFO, "Starting second pass: inserting sidx atoms\n");
5333             res = shift_data(s);
5334             if (res == 0) {
5335                 int64_t end = avio_tell(pb);
5336                 avio_seek(pb, mov->reserved_moov_pos, SEEK_SET);
5337                 mov_write_sidx_tags(pb, mov, -1, 0);
5338                 avio_seek(pb, end, SEEK_SET);
5339                 mov_write_mfra_tag(pb, mov);
5340             }
5341         } else {
5342             mov_write_mfra_tag(pb, mov);
5343         }
5344     }
5345
5346 error:
5347     mov_free(s);
5348
5349     return res;
5350 }
5351
5352 #if CONFIG_MOV_MUXER
5353 MOV_CLASS(mov)
5354 AVOutputFormat ff_mov_muxer = {
5355     .name              = "mov",
5356     .long_name         = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
5357     .extensions        = "mov",
5358     .priv_data_size    = sizeof(MOVMuxContext),
5359     .audio_codec       = AV_CODEC_ID_AAC,
5360     .video_codec       = CONFIG_LIBX264_ENCODER ?
5361                          AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
5362     .write_header      = mov_write_header,
5363     .write_packet      = mov_write_packet,
5364     .write_trailer     = mov_write_trailer,
5365     .flags             = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
5366     .codec_tag         = (const AVCodecTag* const []){
5367         ff_codec_movvideo_tags, ff_codec_movaudio_tags, 0
5368     },
5369     .priv_class        = &mov_muxer_class,
5370 };
5371 #endif
5372 #if CONFIG_TGP_MUXER
5373 MOV_CLASS(tgp)
5374 AVOutputFormat ff_tgp_muxer = {
5375     .name              = "3gp",
5376     .long_name         = NULL_IF_CONFIG_SMALL("3GP (3GPP file format)"),
5377     .extensions        = "3gp",
5378     .priv_data_size    = sizeof(MOVMuxContext),
5379     .audio_codec       = AV_CODEC_ID_AMR_NB,
5380     .video_codec       = AV_CODEC_ID_H263,
5381     .write_header      = mov_write_header,
5382     .write_packet      = mov_write_packet,
5383     .write_trailer     = mov_write_trailer,
5384     .flags             = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
5385     .codec_tag         = (const AVCodecTag* const []){ codec_3gp_tags, 0 },
5386     .priv_class        = &tgp_muxer_class,
5387 };
5388 #endif
5389 #if CONFIG_MP4_MUXER
5390 MOV_CLASS(mp4)
5391 AVOutputFormat ff_mp4_muxer = {
5392     .name              = "mp4",
5393     .long_name         = NULL_IF_CONFIG_SMALL("MP4 (MPEG-4 Part 14)"),
5394     .mime_type         = "application/mp4",
5395     .extensions        = "mp4",
5396     .priv_data_size    = sizeof(MOVMuxContext),
5397     .audio_codec       = AV_CODEC_ID_AAC,
5398     .video_codec       = CONFIG_LIBX264_ENCODER ?
5399                          AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
5400     .write_header      = mov_write_header,
5401     .write_packet      = mov_write_packet,
5402     .write_trailer     = mov_write_trailer,
5403     .flags             = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
5404     .codec_tag         = (const AVCodecTag* const []){ ff_mp4_obj_type, 0 },
5405     .priv_class        = &mp4_muxer_class,
5406 };
5407 #endif
5408 #if CONFIG_PSP_MUXER
5409 MOV_CLASS(psp)
5410 AVOutputFormat ff_psp_muxer = {
5411     .name              = "psp",
5412     .long_name         = NULL_IF_CONFIG_SMALL("PSP MP4 (MPEG-4 Part 14)"),
5413     .extensions        = "mp4,psp",
5414     .priv_data_size    = sizeof(MOVMuxContext),
5415     .audio_codec       = AV_CODEC_ID_AAC,
5416     .video_codec       = CONFIG_LIBX264_ENCODER ?
5417                          AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
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 []){ ff_mp4_obj_type, 0 },
5423     .priv_class        = &psp_muxer_class,
5424 };
5425 #endif
5426 #if CONFIG_TG2_MUXER
5427 MOV_CLASS(tg2)
5428 AVOutputFormat ff_tg2_muxer = {
5429     .name              = "3g2",
5430     .long_name         = NULL_IF_CONFIG_SMALL("3GP2 (3GPP2 file format)"),
5431     .extensions        = "3g2",
5432     .priv_data_size    = sizeof(MOVMuxContext),
5433     .audio_codec       = AV_CODEC_ID_AMR_NB,
5434     .video_codec       = AV_CODEC_ID_H263,
5435     .write_header      = mov_write_header,
5436     .write_packet      = mov_write_packet,
5437     .write_trailer     = mov_write_trailer,
5438     .flags             = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
5439     .codec_tag         = (const AVCodecTag* const []){ codec_3gp_tags, 0 },
5440     .priv_class        = &tg2_muxer_class,
5441 };
5442 #endif
5443 #if CONFIG_IPOD_MUXER
5444 MOV_CLASS(ipod)
5445 AVOutputFormat ff_ipod_muxer = {
5446     .name              = "ipod",
5447     .long_name         = NULL_IF_CONFIG_SMALL("iPod H.264 MP4 (MPEG-4 Part 14)"),
5448     .mime_type         = "application/mp4",
5449     .extensions        = "m4v,m4a",
5450     .priv_data_size    = sizeof(MOVMuxContext),
5451     .audio_codec       = AV_CODEC_ID_AAC,
5452     .video_codec       = AV_CODEC_ID_H264,
5453     .write_header      = mov_write_header,
5454     .write_packet      = mov_write_packet,
5455     .write_trailer     = mov_write_trailer,
5456     .flags             = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
5457     .codec_tag         = (const AVCodecTag* const []){ codec_ipod_tags, 0 },
5458     .priv_class        = &ipod_muxer_class,
5459 };
5460 #endif
5461 #if CONFIG_ISMV_MUXER
5462 MOV_CLASS(ismv)
5463 AVOutputFormat ff_ismv_muxer = {
5464     .name              = "ismv",
5465     .long_name         = NULL_IF_CONFIG_SMALL("ISMV/ISMA (Smooth Streaming)"),
5466     .mime_type         = "application/mp4",
5467     .extensions        = "ismv,isma",
5468     .priv_data_size    = sizeof(MOVMuxContext),
5469     .audio_codec       = AV_CODEC_ID_AAC,
5470     .video_codec       = AV_CODEC_ID_H264,
5471     .write_header      = mov_write_header,
5472     .write_packet      = mov_write_packet,
5473     .write_trailer     = mov_write_trailer,
5474     .flags             = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
5475     .codec_tag         = (const AVCodecTag* const []){ ff_mp4_obj_type, 0 },
5476     .priv_class        = &ismv_muxer_class,
5477 };
5478 #endif
5479 #if CONFIG_F4V_MUXER
5480 MOV_CLASS(f4v)
5481 AVOutputFormat ff_f4v_muxer = {
5482     .name              = "f4v",
5483     .long_name         = NULL_IF_CONFIG_SMALL("F4V Adobe Flash Video"),
5484     .mime_type         = "application/f4v",
5485     .extensions        = "f4v",
5486     .priv_data_size    = sizeof(MOVMuxContext),
5487     .audio_codec       = AV_CODEC_ID_AAC,
5488     .video_codec       = AV_CODEC_ID_H264,
5489     .write_header      = mov_write_header,
5490     .write_packet      = mov_write_packet,
5491     .write_trailer     = mov_write_trailer,
5492     .flags             = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH,
5493     .codec_tag         = (const AVCodecTag* const []){ codec_f4v_tags, 0 },
5494     .priv_class        = &f4v_muxer_class,
5495 };
5496 #endif