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