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