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