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