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