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