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