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