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