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