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