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