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