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