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