]> git.sesse.net Git - ffmpeg/blob - libavformat/movenc.c
lavc: Enable a53cc by default for x264 and qsv_h264.
[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     { NULL },
94 };
95
96 #define MOV_CLASS(flavor)\
97 static const AVClass flavor ## _muxer_class = {\
98     .class_name = #flavor " muxer",\
99     .item_name  = av_default_item_name,\
100     .option     = options,\
101     .version    = LIBAVUTIL_VERSION_INT,\
102 };
103
104 static int get_moov_size(AVFormatContext *s);
105
106 static int utf8len(const uint8_t *b)
107 {
108     int len = 0;
109     int val;
110     while (*b) {
111         GET_UTF8(val, *b++, return -1;)
112         len++;
113     }
114     return len;
115 }
116
117 //FIXME support 64 bit variant with wide placeholders
118 static int64_t update_size(AVIOContext *pb, int64_t pos)
119 {
120     int64_t curpos = avio_tell(pb);
121     avio_seek(pb, pos, SEEK_SET);
122     avio_wb32(pb, curpos - pos); /* rewrite size */
123     avio_seek(pb, curpos, SEEK_SET);
124
125     return curpos - pos;
126 }
127
128 static int co64_required(const MOVTrack *track)
129 {
130     if (track->entry > 0 && track->cluster[track->entry - 1].pos + track->data_offset > UINT32_MAX)
131         return 1;
132     return 0;
133 }
134
135 /* Chunk offset atom */
136 static int mov_write_stco_tag(AVIOContext *pb, MOVTrack *track)
137 {
138     int i;
139     int mode64 = co64_required(track); // use 32 bit size variant if possible
140     int64_t pos = avio_tell(pb);
141     avio_wb32(pb, 0); /* size */
142     if (mode64)
143         ffio_wfourcc(pb, "co64");
144     else
145         ffio_wfourcc(pb, "stco");
146     avio_wb32(pb, 0); /* version & flags */
147     avio_wb32(pb, track->chunkCount); /* entry count */
148     for (i = 0; i < track->entry; i++) {
149         if (!track->cluster[i].chunkNum)
150             continue;
151         if (mode64 == 1)
152             avio_wb64(pb, track->cluster[i].pos + track->data_offset);
153         else
154             avio_wb32(pb, track->cluster[i].pos + track->data_offset);
155     }
156     return update_size(pb, pos);
157 }
158
159 /* Sample size atom */
160 static int mov_write_stsz_tag(AVIOContext *pb, MOVTrack *track)
161 {
162     int equalChunks = 1;
163     int i, j, entries = 0, tst = -1, oldtst = -1;
164
165     int64_t pos = avio_tell(pb);
166     avio_wb32(pb, 0); /* size */
167     ffio_wfourcc(pb, "stsz");
168     avio_wb32(pb, 0); /* version & flags */
169
170     for (i = 0; i < track->entry; i++) {
171         tst = track->cluster[i].size / track->cluster[i].entries;
172         if (oldtst != -1 && tst != oldtst)
173             equalChunks = 0;
174         oldtst = tst;
175         entries += track->cluster[i].entries;
176     }
177     if (equalChunks && track->entry) {
178         int sSize = track->entry ? track->cluster[0].size / track->cluster[0].entries : 0;
179         sSize = FFMAX(1, sSize); // adpcm mono case could make sSize == 0
180         avio_wb32(pb, sSize); // sample size
181         avio_wb32(pb, entries); // sample count
182     } else {
183         avio_wb32(pb, 0); // sample size
184         avio_wb32(pb, entries); // sample count
185         for (i = 0; i < track->entry; i++) {
186             for (j = 0; j < track->cluster[i].entries; j++) {
187                 avio_wb32(pb, track->cluster[i].size /
188                           track->cluster[i].entries);
189             }
190         }
191     }
192     return update_size(pb, pos);
193 }
194
195 /* Sample to chunk atom */
196 static int mov_write_stsc_tag(AVIOContext *pb, MOVTrack *track)
197 {
198     int index = 0, oldval = -1, i;
199     int64_t entryPos, curpos;
200
201     int64_t pos = avio_tell(pb);
202     avio_wb32(pb, 0); /* size */
203     ffio_wfourcc(pb, "stsc");
204     avio_wb32(pb, 0); // version & flags
205     entryPos = avio_tell(pb);
206     avio_wb32(pb, track->chunkCount); // entry count
207     for (i = 0; i < track->entry; i++) {
208         if (oldval != track->cluster[i].samples_in_chunk && track->cluster[i].chunkNum) {
209             avio_wb32(pb, track->cluster[i].chunkNum); // first chunk
210             avio_wb32(pb, track->cluster[i].samples_in_chunk); // samples per chunk
211             avio_wb32(pb, 0x1); // sample description index
212             oldval = track->cluster[i].samples_in_chunk;
213             index++;
214         }
215     }
216     curpos = avio_tell(pb);
217     avio_seek(pb, entryPos, SEEK_SET);
218     avio_wb32(pb, index); // rewrite size
219     avio_seek(pb, curpos, SEEK_SET);
220
221     return update_size(pb, pos);
222 }
223
224 /* Sync sample atom */
225 static int mov_write_stss_tag(AVIOContext *pb, MOVTrack *track, uint32_t flag)
226 {
227     int64_t curpos, entryPos;
228     int i, index = 0;
229     int64_t pos = avio_tell(pb);
230     avio_wb32(pb, 0); // size
231     ffio_wfourcc(pb, flag == MOV_SYNC_SAMPLE ? "stss" : "stps");
232     avio_wb32(pb, 0); // version & flags
233     entryPos = avio_tell(pb);
234     avio_wb32(pb, track->entry); // entry count
235     for (i = 0; i < track->entry; i++) {
236         if (track->cluster[i].flags & flag) {
237             avio_wb32(pb, i + 1);
238             index++;
239         }
240     }
241     curpos = avio_tell(pb);
242     avio_seek(pb, entryPos, SEEK_SET);
243     avio_wb32(pb, index); // rewrite size
244     avio_seek(pb, curpos, SEEK_SET);
245     return update_size(pb, pos);
246 }
247
248 static int mov_write_amr_tag(AVIOContext *pb, MOVTrack *track)
249 {
250     avio_wb32(pb, 0x11); /* size */
251     if (track->mode == MODE_MOV) ffio_wfourcc(pb, "samr");
252     else                         ffio_wfourcc(pb, "damr");
253     ffio_wfourcc(pb, "FFMP");
254     avio_w8(pb, 0); /* decoder version */
255
256     avio_wb16(pb, 0x81FF); /* Mode set (all modes for AMR_NB) */
257     avio_w8(pb, 0x00); /* Mode change period (no restriction) */
258     avio_w8(pb, 0x01); /* Frames per sample */
259     return 0x11;
260 }
261
262 static int mov_write_ac3_tag(AVIOContext *pb, MOVTrack *track)
263 {
264     GetBitContext gbc;
265     PutBitContext pbc;
266     uint8_t buf[3];
267     int fscod, bsid, bsmod, acmod, lfeon, frmsizecod;
268
269     if (track->vos_len < 7)
270         return -1;
271
272     avio_wb32(pb, 11);
273     ffio_wfourcc(pb, "dac3");
274
275     init_get_bits(&gbc, track->vos_data + 4, (track->vos_len - 4) * 8);
276     fscod      = get_bits(&gbc, 2);
277     frmsizecod = get_bits(&gbc, 6);
278     bsid       = get_bits(&gbc, 5);
279     bsmod      = get_bits(&gbc, 3);
280     acmod      = get_bits(&gbc, 3);
281     if (acmod == 2) {
282         skip_bits(&gbc, 2); // dsurmod
283     } else {
284         if ((acmod & 1) && acmod != 1)
285             skip_bits(&gbc, 2); // cmixlev
286         if (acmod & 4)
287             skip_bits(&gbc, 2); // surmixlev
288     }
289     lfeon = get_bits1(&gbc);
290
291     init_put_bits(&pbc, buf, sizeof(buf));
292     put_bits(&pbc, 2, fscod);
293     put_bits(&pbc, 5, bsid);
294     put_bits(&pbc, 3, bsmod);
295     put_bits(&pbc, 3, acmod);
296     put_bits(&pbc, 1, lfeon);
297     put_bits(&pbc, 5, frmsizecod >> 1); // bit_rate_code
298     put_bits(&pbc, 5, 0); // reserved
299
300     flush_put_bits(&pbc);
301     avio_write(pb, buf, sizeof(buf));
302
303     return 11;
304 }
305
306 struct eac3_info {
307     AVPacket pkt;
308     uint8_t ec3_done;
309     uint8_t num_blocks;
310
311     /* Layout of the EC3SpecificBox */
312     /* maximum bitrate */
313     uint16_t data_rate;
314     /* number of independent substreams */
315     uint8_t  num_ind_sub;
316     struct {
317         /* sample rate code (see ff_ac3_sample_rate_tab) 2 bits */
318         uint8_t fscod;
319         /* bit stream identification 5 bits */
320         uint8_t bsid;
321         /* one bit reserved */
322         /* audio service mixing (not supported yet) 1 bit */
323         /* bit stream mode 3 bits */
324         uint8_t bsmod;
325         /* audio coding mode 3 bits */
326         uint8_t acmod;
327         /* sub woofer on 1 bit */
328         uint8_t lfeon;
329         /* 3 bits reserved */
330         /* number of dependent substreams associated with this substream 4 bits */
331         uint8_t num_dep_sub;
332         /* channel locations of the dependent substream(s), if any, 9 bits */
333         uint16_t chan_loc;
334         /* if there is no dependent substream, then one bit reserved instead */
335     } substream[1]; /* TODO: support 8 independent substreams */
336 };
337
338 #if CONFIG_AC3_PARSER
339 static int handle_eac3(MOVMuxContext *mov, AVPacket *pkt, MOVTrack *track)
340 {
341     GetBitContext gbc;
342     AC3HeaderInfo tmp, *hdr = &tmp;
343     struct eac3_info *info;
344     int num_blocks;
345
346     if (!track->eac3_priv && !(track->eac3_priv = av_mallocz(sizeof(*info))))
347         return AVERROR(ENOMEM);
348     info = track->eac3_priv;
349
350     init_get_bits(&gbc, pkt->data, pkt->size * 8);
351     if (avpriv_ac3_parse_header(&gbc, &hdr) < 0) {
352         /* drop the packets until we see a good one */
353         if (!track->entry) {
354             av_log(mov, AV_LOG_WARNING, "Dropping invalid packet from start of the stream\n");
355             return 0;
356         }
357         return AVERROR_INVALIDDATA;
358     }
359
360     info->data_rate = FFMAX(info->data_rate, hdr->bit_rate / 1000);
361     num_blocks = hdr->num_blocks;
362
363     if (!info->ec3_done) {
364         /* AC-3 substream must be the first one */
365         if (hdr->bitstream_id <= 10 && hdr->substreamid != 0)
366             return AVERROR(EINVAL);
367
368         /* this should always be the case, given that our AC-3 parser
369          * concatenates dependent frames to their independent parent */
370         if (hdr->frame_type == EAC3_FRAME_TYPE_INDEPENDENT) {
371             /* substream ids must be incremental */
372             if (hdr->substreamid > info->num_ind_sub + 1)
373                 return AVERROR(EINVAL);
374
375             if (hdr->substreamid == info->num_ind_sub + 1) {
376                 //info->num_ind_sub++;
377                 avpriv_request_sample(track->par, "Multiple independent substreams");
378                 return AVERROR_PATCHWELCOME;
379             } else if (hdr->substreamid < info->num_ind_sub ||
380                        hdr->substreamid == 0 && info->substream[0].bsid) {
381                 info->ec3_done = 1;
382                 goto concatenate;
383             }
384         }
385
386         /* fill the info needed for the "dec3" atom */
387         info->substream[hdr->substreamid].fscod = hdr->sr_code;
388         info->substream[hdr->substreamid].bsid  = hdr->bitstream_id;
389         info->substream[hdr->substreamid].bsmod = hdr->bitstream_mode;
390         info->substream[hdr->substreamid].acmod = hdr->channel_mode;
391         info->substream[hdr->substreamid].lfeon = hdr->lfe_on;
392
393         /* Parse dependent substream(s), if any */
394         if (pkt->size != hdr->frame_size) {
395             int cumul_size = hdr->frame_size;
396             int parent = hdr->substreamid;
397
398             while (cumul_size != pkt->size) {
399                 int i;
400                 init_get_bits(&gbc, pkt->data + cumul_size, (pkt->size - cumul_size) * 8);
401                 if (avpriv_ac3_parse_header(&gbc, &hdr) < 0)
402                     return AVERROR_INVALIDDATA;
403                 if (hdr->frame_type != EAC3_FRAME_TYPE_DEPENDENT)
404                     return AVERROR(EINVAL);
405                 cumul_size += hdr->frame_size;
406                 info->substream[parent].num_dep_sub++;
407
408                 /* header is parsed up to lfeon, but custom channel map may be needed */
409                 /* skip bsid */
410                 skip_bits(&gbc, 5);
411                 /* skip volume control params */
412                 for (i = 0; i < (hdr->channel_mode ? 1 : 2); i++) {
413                     skip_bits(&gbc, 5); // skip dialog normalization
414                     if (get_bits1(&gbc)) {
415                         skip_bits(&gbc, 8); // skip compression gain word
416                     }
417                 }
418                 /* get the dependent stream channel map, if exists */
419                 if (get_bits1(&gbc))
420                     info->substream[parent].chan_loc |= (get_bits(&gbc, 16) >> 5) & 0x1f;
421                 else
422                     info->substream[parent].chan_loc |= hdr->channel_mode;
423             }
424         }
425     }
426
427 concatenate:
428     if (!info->num_blocks && num_blocks == 6)
429         return pkt->size;
430     else if (info->num_blocks + num_blocks > 6)
431         return AVERROR_INVALIDDATA;
432
433     if (!info->num_blocks) {
434         int ret;
435         if ((ret = av_copy_packet(&info->pkt, pkt)) < 0)
436             return ret;
437         info->num_blocks = num_blocks;
438         return 0;
439     } else {
440         int ret;
441         if ((ret = av_grow_packet(&info->pkt, pkt->size)) < 0)
442             return ret;
443         memcpy(info->pkt.data + info->pkt.size - pkt->size, pkt->data, pkt->size);
444         info->num_blocks += num_blocks;
445         info->pkt.duration += pkt->duration;
446         if ((ret = av_copy_packet_side_data(&info->pkt, pkt)) < 0)
447             return ret;
448         if (info->num_blocks != 6)
449             return 0;
450         av_packet_unref(pkt);
451         if ((ret = av_copy_packet(pkt, &info->pkt)) < 0)
452             return ret;
453         av_packet_unref(&info->pkt);
454         info->num_blocks = 0;
455     }
456
457     return pkt->size;
458 }
459 #endif
460
461 static int mov_write_eac3_tag(AVIOContext *pb, MOVTrack *track)
462 {
463     PutBitContext pbc;
464     uint8_t *buf;
465     struct eac3_info *info;
466     int size, i;
467
468     if (!track->eac3_priv)
469         return AVERROR(EINVAL);
470
471     info = track->eac3_priv;
472     size = 2 + 4 * (info->num_ind_sub + 1);
473     buf = av_malloc(size);
474     if (!buf) {
475         size = AVERROR(ENOMEM);
476         goto end;
477     }
478
479     init_put_bits(&pbc, buf, size);
480     put_bits(&pbc, 13, info->data_rate);
481     put_bits(&pbc,  3, info->num_ind_sub);
482     for (i = 0; i <= info->num_ind_sub; i++) {
483         put_bits(&pbc, 2, info->substream[i].fscod);
484         put_bits(&pbc, 5, info->substream[i].bsid);
485         put_bits(&pbc, 1, 0); /* reserved */
486         put_bits(&pbc, 1, 0); /* asvc */
487         put_bits(&pbc, 3, info->substream[i].bsmod);
488         put_bits(&pbc, 3, info->substream[i].acmod);
489         put_bits(&pbc, 1, info->substream[i].lfeon);
490         put_bits(&pbc, 5, 0); /* reserved */
491         put_bits(&pbc, 4, info->substream[i].num_dep_sub);
492         if (!info->substream[i].num_dep_sub) {
493             put_bits(&pbc, 1, 0); /* reserved */
494             size--;
495         } else {
496             put_bits(&pbc, 9, info->substream[i].chan_loc);
497         }
498     }
499     flush_put_bits(&pbc);
500
501     avio_wb32(pb, size + 8);
502     ffio_wfourcc(pb, "dec3");
503     avio_write(pb, buf, size);
504
505     av_free(buf);
506
507 end:
508     av_packet_unref(&info->pkt);
509     av_freep(&track->eac3_priv);
510
511     return size;
512 }
513
514 /**
515  * This function writes extradata "as is".
516  * Extradata must be formatted like a valid atom (with size and tag).
517  */
518 static int mov_write_extradata_tag(AVIOContext *pb, MOVTrack *track)
519 {
520     avio_write(pb, track->par->extradata, track->par->extradata_size);
521     return track->par->extradata_size;
522 }
523
524 static int mov_write_enda_tag(AVIOContext *pb)
525 {
526     avio_wb32(pb, 10);
527     ffio_wfourcc(pb, "enda");
528     avio_wb16(pb, 1); /* little endian */
529     return 10;
530 }
531
532 static int mov_write_enda_tag_be(AVIOContext *pb)
533 {
534   avio_wb32(pb, 10);
535   ffio_wfourcc(pb, "enda");
536   avio_wb16(pb, 0); /* big endian */
537   return 10;
538 }
539
540 static void put_descr(AVIOContext *pb, int tag, unsigned int size)
541 {
542     int i = 3;
543     avio_w8(pb, tag);
544     for (; i > 0; i--)
545         avio_w8(pb, (size >> (7 * i)) | 0x80);
546     avio_w8(pb, size & 0x7F);
547 }
548
549 static unsigned compute_avg_bitrate(MOVTrack *track)
550 {
551     uint64_t size = 0;
552     int i;
553     if (!track->track_duration)
554         return 0;
555     for (i = 0; i < track->entry; i++)
556         size += track->cluster[i].size;
557     return size * 8 * track->timescale / track->track_duration;
558 }
559
560 static int mov_write_esds_tag(AVIOContext *pb, MOVTrack *track) // Basic
561 {
562     AVCPBProperties *props;
563     int64_t pos = avio_tell(pb);
564     int decoder_specific_info_len = track->vos_len ? 5 + track->vos_len : 0;
565     unsigned avg_bitrate;
566
567     avio_wb32(pb, 0); // size
568     ffio_wfourcc(pb, "esds");
569     avio_wb32(pb, 0); // Version
570
571     // ES descriptor
572     put_descr(pb, 0x03, 3 + 5+13 + decoder_specific_info_len + 5+1);
573     avio_wb16(pb, track->track_id);
574     avio_w8(pb, 0x00); // flags (= no flags)
575
576     // DecoderConfig descriptor
577     put_descr(pb, 0x04, 13 + decoder_specific_info_len);
578
579     // Object type indication
580     if ((track->par->codec_id == AV_CODEC_ID_MP2 ||
581          track->par->codec_id == AV_CODEC_ID_MP3) &&
582         track->par->sample_rate > 24000)
583         avio_w8(pb, 0x6B); // 11172-3
584     else
585         avio_w8(pb, ff_codec_get_tag(ff_mp4_obj_type, track->par->codec_id));
586
587     // the following fields is made of 6 bits to identify the streamtype (4 for video, 5 for audio)
588     // plus 1 bit to indicate upstream and 1 bit set to 1 (reserved)
589     if (track->par->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
590         avio_w8(pb, (0x38 << 2) | 1); // flags (= NeroSubpicStream)
591     else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
592         avio_w8(pb, 0x15); // flags (= Audiostream)
593     else
594         avio_w8(pb, 0x11); // flags (= Visualstream)
595
596     props = (AVCPBProperties*)av_stream_get_side_data(track->st, AV_PKT_DATA_CPB_PROPERTIES,
597                                                       NULL);
598
599     avio_wb24(pb, props ? props->buffer_size / 8 : 0); // Buffersize DB
600
601     avg_bitrate = compute_avg_bitrate(track);
602     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)
603     avio_wb32(pb, avg_bitrate);
604
605     if (track->vos_len) {
606         // DecoderSpecific info descriptor
607         put_descr(pb, 0x05, track->vos_len);
608         avio_write(pb, track->vos_data, track->vos_len);
609     }
610
611     // SL descriptor
612     put_descr(pb, 0x06, 1);
613     avio_w8(pb, 0x02);
614     return update_size(pb, pos);
615 }
616
617 static int mov_pcm_le_gt16(enum AVCodecID codec_id)
618 {
619     return codec_id == AV_CODEC_ID_PCM_S24LE ||
620            codec_id == AV_CODEC_ID_PCM_S32LE ||
621            codec_id == AV_CODEC_ID_PCM_F32LE ||
622            codec_id == AV_CODEC_ID_PCM_F64LE;
623 }
624
625 static int mov_pcm_be_gt16(enum AVCodecID codec_id)
626 {
627     return codec_id == AV_CODEC_ID_PCM_S24BE ||
628            codec_id == AV_CODEC_ID_PCM_S32BE ||
629            codec_id == AV_CODEC_ID_PCM_F32BE ||
630            codec_id == AV_CODEC_ID_PCM_F64BE;
631 }
632
633 static int mov_write_ms_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
634 {
635     int ret;
636     int64_t pos = avio_tell(pb);
637     avio_wb32(pb, 0);
638     avio_wl32(pb, track->tag); // store it byteswapped
639     track->par->codec_tag = av_bswap16(track->tag >> 16);
640     if ((ret = ff_put_wav_header(s, pb, track->par, 0)) < 0)
641         return ret;
642     return update_size(pb, pos);
643 }
644
645 static int mov_write_wfex_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
646 {
647     int ret;
648     int64_t pos = avio_tell(pb);
649     avio_wb32(pb, 0);
650     ffio_wfourcc(pb, "wfex");
651     if ((ret = ff_put_wav_header(s, pb, track->st->codecpar, FF_PUT_WAV_HEADER_FORCE_WAVEFORMATEX)) < 0)
652         return ret;
653     return update_size(pb, pos);
654 }
655
656 static int mov_write_chan_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
657 {
658     uint32_t layout_tag, bitmap;
659     int64_t pos = avio_tell(pb);
660
661     layout_tag = ff_mov_get_channel_layout_tag(track->par->codec_id,
662                                                track->par->channel_layout,
663                                                &bitmap);
664     if (!layout_tag) {
665         av_log(s, AV_LOG_WARNING, "not writing 'chan' tag due to "
666                "lack of channel information\n");
667         return 0;
668     }
669
670     if (track->multichannel_as_mono)
671         return 0;
672
673     avio_wb32(pb, 0);           // Size
674     ffio_wfourcc(pb, "chan");   // Type
675     avio_w8(pb, 0);             // Version
676     avio_wb24(pb, 0);           // Flags
677     avio_wb32(pb, layout_tag);  // mChannelLayoutTag
678     avio_wb32(pb, bitmap);      // mChannelBitmap
679     avio_wb32(pb, 0);           // mNumberChannelDescriptions
680
681     return update_size(pb, pos);
682 }
683
684 static int mov_write_wave_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
685 {
686     int64_t pos = avio_tell(pb);
687
688     avio_wb32(pb, 0);     /* size */
689     ffio_wfourcc(pb, "wave");
690
691     if (track->par->codec_id != AV_CODEC_ID_QDM2) {
692     avio_wb32(pb, 12);    /* size */
693     ffio_wfourcc(pb, "frma");
694     avio_wl32(pb, track->tag);
695     }
696
697     if (track->par->codec_id == AV_CODEC_ID_AAC) {
698         /* useless atom needed by mplayer, ipod, not needed by quicktime */
699         avio_wb32(pb, 12); /* size */
700         ffio_wfourcc(pb, "mp4a");
701         avio_wb32(pb, 0);
702         mov_write_esds_tag(pb, track);
703     } else if (mov_pcm_le_gt16(track->par->codec_id))  {
704       mov_write_enda_tag(pb);
705     } else if (mov_pcm_be_gt16(track->par->codec_id))  {
706       mov_write_enda_tag_be(pb);
707     } else if (track->par->codec_id == AV_CODEC_ID_AMR_NB) {
708         mov_write_amr_tag(pb, track);
709     } else if (track->par->codec_id == AV_CODEC_ID_AC3) {
710         mov_write_ac3_tag(pb, track);
711     } else if (track->par->codec_id == AV_CODEC_ID_EAC3) {
712         mov_write_eac3_tag(pb, track);
713     } else if (track->par->codec_id == AV_CODEC_ID_ALAC ||
714                track->par->codec_id == AV_CODEC_ID_QDM2) {
715         mov_write_extradata_tag(pb, track);
716     } else if (track->par->codec_id == AV_CODEC_ID_ADPCM_MS ||
717                track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) {
718         mov_write_ms_tag(s, pb, track);
719     }
720
721     avio_wb32(pb, 8);     /* size */
722     avio_wb32(pb, 0);     /* null tag */
723
724     return update_size(pb, pos);
725 }
726
727 static int mov_write_dvc1_structs(MOVTrack *track, uint8_t *buf)
728 {
729     uint8_t *unescaped;
730     const uint8_t *start, *next, *end = track->vos_data + track->vos_len;
731     int unescaped_size, seq_found = 0;
732     int level = 0, interlace = 0;
733     int packet_seq   = track->vc1_info.packet_seq;
734     int packet_entry = track->vc1_info.packet_entry;
735     int slices       = track->vc1_info.slices;
736     PutBitContext pbc;
737
738     if (track->start_dts == AV_NOPTS_VALUE) {
739         /* No packets written yet, vc1_info isn't authoritative yet. */
740         /* Assume inline sequence and entry headers. */
741         packet_seq = packet_entry = 1;
742         av_log(NULL, AV_LOG_WARNING,
743                "moov atom written before any packets, unable to write correct "
744                "dvc1 atom. Set the delay_moov flag to fix this.\n");
745     }
746
747     unescaped = av_mallocz(track->vos_len + AV_INPUT_BUFFER_PADDING_SIZE);
748     if (!unescaped)
749         return AVERROR(ENOMEM);
750     start = find_next_marker(track->vos_data, end);
751     for (next = start; next < end; start = next) {
752         GetBitContext gb;
753         int size;
754         next = find_next_marker(start + 4, end);
755         size = next - start - 4;
756         if (size <= 0)
757             continue;
758         unescaped_size = vc1_unescape_buffer(start + 4, size, unescaped);
759         init_get_bits(&gb, unescaped, 8 * unescaped_size);
760         if (AV_RB32(start) == VC1_CODE_SEQHDR) {
761             int profile = get_bits(&gb, 2);
762             if (profile != PROFILE_ADVANCED) {
763                 av_free(unescaped);
764                 return AVERROR(ENOSYS);
765             }
766             seq_found = 1;
767             level = get_bits(&gb, 3);
768             /* chromaformat, frmrtq_postproc, bitrtq_postproc, postprocflag,
769              * width, height */
770             skip_bits_long(&gb, 2 + 3 + 5 + 1 + 2*12);
771             skip_bits(&gb, 1); /* broadcast */
772             interlace = get_bits1(&gb);
773             skip_bits(&gb, 4); /* tfcntrflag, finterpflag, reserved, psf */
774         }
775     }
776     if (!seq_found) {
777         av_free(unescaped);
778         return AVERROR(ENOSYS);
779     }
780
781     init_put_bits(&pbc, buf, 7);
782     /* VC1DecSpecStruc */
783     put_bits(&pbc, 4, 12); /* profile - advanced */
784     put_bits(&pbc, 3, level);
785     put_bits(&pbc, 1, 0); /* reserved */
786     /* VC1AdvDecSpecStruc */
787     put_bits(&pbc, 3, level);
788     put_bits(&pbc, 1, 0); /* cbr */
789     put_bits(&pbc, 6, 0); /* reserved */
790     put_bits(&pbc, 1, !interlace); /* no interlace */
791     put_bits(&pbc, 1, !packet_seq); /* no multiple seq */
792     put_bits(&pbc, 1, !packet_entry); /* no multiple entry */
793     put_bits(&pbc, 1, !slices); /* no slice code */
794     put_bits(&pbc, 1, 0); /* no bframe */
795     put_bits(&pbc, 1, 0); /* reserved */
796
797     /* framerate */
798     if (track->st->avg_frame_rate.num > 0 && track->st->avg_frame_rate.den > 0)
799         put_bits32(&pbc, track->st->avg_frame_rate.num / track->st->avg_frame_rate.den);
800     else
801         put_bits32(&pbc, 0xffffffff);
802
803     flush_put_bits(&pbc);
804
805     av_free(unescaped);
806
807     return 0;
808 }
809
810 static int mov_write_dvc1_tag(AVIOContext *pb, MOVTrack *track)
811 {
812     uint8_t buf[7] = { 0 };
813     int ret;
814
815     if ((ret = mov_write_dvc1_structs(track, buf)) < 0)
816         return ret;
817
818     avio_wb32(pb, track->vos_len + 8 + sizeof(buf));
819     ffio_wfourcc(pb, "dvc1");
820     avio_write(pb, buf, sizeof(buf));
821     avio_write(pb, track->vos_data, track->vos_len);
822
823     return 0;
824 }
825
826 static int mov_write_glbl_tag(AVIOContext *pb, MOVTrack *track)
827 {
828     avio_wb32(pb, track->vos_len + 8);
829     ffio_wfourcc(pb, "glbl");
830     avio_write(pb, track->vos_data, track->vos_len);
831     return 8 + track->vos_len;
832 }
833
834 /**
835  * Compute flags for 'lpcm' tag.
836  * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
837  */
838 static int mov_get_lpcm_flags(enum AVCodecID codec_id)
839 {
840     switch (codec_id) {
841     case AV_CODEC_ID_PCM_F32BE:
842     case AV_CODEC_ID_PCM_F64BE:
843         return 11;
844     case AV_CODEC_ID_PCM_F32LE:
845     case AV_CODEC_ID_PCM_F64LE:
846         return 9;
847     case AV_CODEC_ID_PCM_U8:
848         return 10;
849     case AV_CODEC_ID_PCM_S16BE:
850     case AV_CODEC_ID_PCM_S24BE:
851     case AV_CODEC_ID_PCM_S32BE:
852         return 14;
853     case AV_CODEC_ID_PCM_S8:
854     case AV_CODEC_ID_PCM_S16LE:
855     case AV_CODEC_ID_PCM_S24LE:
856     case AV_CODEC_ID_PCM_S32LE:
857         return 12;
858     default:
859         return 0;
860     }
861 }
862
863 static int get_cluster_duration(MOVTrack *track, int cluster_idx)
864 {
865     int64_t next_dts;
866
867     if (cluster_idx >= track->entry)
868         return 0;
869
870     if (cluster_idx + 1 == track->entry)
871         next_dts = track->track_duration + track->start_dts;
872     else
873         next_dts = track->cluster[cluster_idx + 1].dts;
874
875     next_dts -= track->cluster[cluster_idx].dts;
876
877     av_assert0(next_dts >= 0);
878     av_assert0(next_dts <= INT_MAX);
879
880     return next_dts;
881 }
882
883 static int get_samples_per_packet(MOVTrack *track)
884 {
885     int i, first_duration;
886
887 // return track->par->frame_size;
888
889     /* use 1 for raw PCM */
890     if (!track->audio_vbr)
891         return 1;
892
893     /* check to see if duration is constant for all clusters */
894     if (!track->entry)
895         return 0;
896     first_duration = get_cluster_duration(track, 0);
897     for (i = 1; i < track->entry; i++) {
898         if (get_cluster_duration(track, i) != first_duration)
899             return 0;
900     }
901     return first_duration;
902 }
903
904 static int mov_write_audio_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
905 {
906     int64_t pos = avio_tell(pb);
907     int version = 0;
908     uint32_t tag = track->tag;
909
910     if (track->mode == MODE_MOV) {
911         if (track->timescale > UINT16_MAX) {
912             if (mov_get_lpcm_flags(track->par->codec_id))
913                 tag = AV_RL32("lpcm");
914             version = 2;
915         } else if (track->audio_vbr || mov_pcm_le_gt16(track->par->codec_id) ||
916                    mov_pcm_be_gt16(track->par->codec_id) ||
917                    track->par->codec_id == AV_CODEC_ID_ADPCM_MS ||
918                    track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
919                    track->par->codec_id == AV_CODEC_ID_QDM2) {
920             version = 1;
921         }
922     }
923
924     avio_wb32(pb, 0); /* size */
925     if (mov->encryption_scheme != MOV_ENC_NONE) {
926         ffio_wfourcc(pb, "enca");
927     } else {
928         avio_wl32(pb, tag); // store it byteswapped
929     }
930     avio_wb32(pb, 0); /* Reserved */
931     avio_wb16(pb, 0); /* Reserved */
932     avio_wb16(pb, 1); /* Data-reference index, XXX  == 1 */
933
934     /* SoundDescription */
935     avio_wb16(pb, version); /* Version */
936     avio_wb16(pb, 0); /* Revision level */
937     avio_wb32(pb, 0); /* Reserved */
938
939     if (version == 2) {
940         avio_wb16(pb, 3);
941         avio_wb16(pb, 16);
942         avio_wb16(pb, 0xfffe);
943         avio_wb16(pb, 0);
944         avio_wb32(pb, 0x00010000);
945         avio_wb32(pb, 72);
946         avio_wb64(pb, av_double2int(track->par->sample_rate));
947         avio_wb32(pb, track->par->channels);
948         avio_wb32(pb, 0x7F000000);
949         avio_wb32(pb, av_get_bits_per_sample(track->par->codec_id));
950         avio_wb32(pb, mov_get_lpcm_flags(track->par->codec_id));
951         avio_wb32(pb, track->sample_size);
952         avio_wb32(pb, get_samples_per_packet(track));
953     } else {
954         if (track->mode == MODE_MOV) {
955             avio_wb16(pb, track->par->channels);
956             if (track->par->codec_id == AV_CODEC_ID_PCM_U8 ||
957                 track->par->codec_id == AV_CODEC_ID_PCM_S8)
958                 avio_wb16(pb, 8); /* bits per sample */
959             else if (track->par->codec_id == AV_CODEC_ID_ADPCM_G726)
960                 avio_wb16(pb, track->par->bits_per_coded_sample);
961             else
962                 avio_wb16(pb, 16);
963             avio_wb16(pb, track->audio_vbr ? -2 : 0); /* compression ID */
964         } else { /* reserved for mp4/3gp */
965             avio_wb16(pb, 2);
966             avio_wb16(pb, 16);
967             avio_wb16(pb, 0);
968         }
969
970         avio_wb16(pb, 0); /* packet size (= 0) */
971         avio_wb16(pb, track->par->sample_rate <= UINT16_MAX ?
972                       track->par->sample_rate : 0);
973         avio_wb16(pb, 0); /* Reserved */
974     }
975
976     if (version == 1) { /* SoundDescription V1 extended info */
977         if (mov_pcm_le_gt16(track->par->codec_id) ||
978             mov_pcm_be_gt16(track->par->codec_id))
979             avio_wb32(pb, 1); /*  must be 1 for  uncompressed formats */
980         else
981             avio_wb32(pb, track->par->frame_size); /* Samples per packet */
982         avio_wb32(pb, track->sample_size / track->par->channels); /* Bytes per packet */
983         avio_wb32(pb, track->sample_size); /* Bytes per frame */
984         avio_wb32(pb, 2); /* Bytes per sample */
985     }
986
987     if (track->mode == MODE_MOV &&
988         (track->par->codec_id == AV_CODEC_ID_AAC           ||
989          track->par->codec_id == AV_CODEC_ID_AC3           ||
990          track->par->codec_id == AV_CODEC_ID_EAC3          ||
991          track->par->codec_id == AV_CODEC_ID_AMR_NB        ||
992          track->par->codec_id == AV_CODEC_ID_ALAC          ||
993          track->par->codec_id == AV_CODEC_ID_ADPCM_MS      ||
994          track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
995          track->par->codec_id == AV_CODEC_ID_QDM2          ||
996          (mov_pcm_le_gt16(track->par->codec_id) && version==1) ||
997          (mov_pcm_be_gt16(track->par->codec_id) && version==1)))
998         mov_write_wave_tag(s, pb, track);
999     else if (track->tag == MKTAG('m','p','4','a'))
1000         mov_write_esds_tag(pb, track);
1001     else if (track->par->codec_id == AV_CODEC_ID_AMR_NB)
1002         mov_write_amr_tag(pb, track);
1003     else if (track->par->codec_id == AV_CODEC_ID_AC3)
1004         mov_write_ac3_tag(pb, track);
1005     else if (track->par->codec_id == AV_CODEC_ID_EAC3)
1006         mov_write_eac3_tag(pb, track);
1007     else if (track->par->codec_id == AV_CODEC_ID_ALAC)
1008         mov_write_extradata_tag(pb, track);
1009     else if (track->par->codec_id == AV_CODEC_ID_WMAPRO)
1010         mov_write_wfex_tag(s, pb, track);
1011     else if (track->vos_len > 0)
1012         mov_write_glbl_tag(pb, track);
1013
1014     if (track->mode == MODE_MOV && track->par->codec_type == AVMEDIA_TYPE_AUDIO)
1015         mov_write_chan_tag(s, pb, track);
1016
1017     if (mov->encryption_scheme != MOV_ENC_NONE) {
1018         ff_mov_cenc_write_sinf_tag(track, pb, mov->encryption_kid);
1019     }
1020
1021     return update_size(pb, pos);
1022 }
1023
1024 static int mov_write_d263_tag(AVIOContext *pb)
1025 {
1026     avio_wb32(pb, 0xf); /* size */
1027     ffio_wfourcc(pb, "d263");
1028     ffio_wfourcc(pb, "FFMP");
1029     avio_w8(pb, 0); /* decoder version */
1030     /* FIXME use AVCodecContext level/profile, when encoder will set values */
1031     avio_w8(pb, 0xa); /* level */
1032     avio_w8(pb, 0); /* profile */
1033     return 0xf;
1034 }
1035
1036 static int mov_write_avcc_tag(AVIOContext *pb, MOVTrack *track)
1037 {
1038     int64_t pos = avio_tell(pb);
1039
1040     avio_wb32(pb, 0);
1041     ffio_wfourcc(pb, "avcC");
1042     ff_isom_write_avcc(pb, track->vos_data, track->vos_len);
1043     return update_size(pb, pos);
1044 }
1045
1046 static int mov_write_vpcc_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
1047 {
1048     int64_t pos = avio_tell(pb);
1049
1050     avio_wb32(pb, 0);
1051     ffio_wfourcc(pb, "vpcC");
1052     avio_wb32(pb, 0); /* version & flags */
1053     ff_isom_write_vpcc(s, pb, track->par);
1054     return update_size(pb, pos);
1055 }
1056
1057 static int mov_write_hvcc_tag(AVIOContext *pb, MOVTrack *track)
1058 {
1059     int64_t pos = avio_tell(pb);
1060
1061     avio_wb32(pb, 0);
1062     ffio_wfourcc(pb, "hvcC");
1063     ff_isom_write_hvcc(pb, track->vos_data, track->vos_len, 0);
1064     return update_size(pb, pos);
1065 }
1066
1067 /* also used by all avid codecs (dv, imx, meridien) and their variants */
1068 static int mov_write_avid_tag(AVIOContext *pb, MOVTrack *track)
1069 {
1070     int i;
1071     int interlaced;
1072     int cid;
1073
1074     if (track->vos_data && track->vos_len > 0x29) {
1075         if (ff_dnxhd_parse_header_prefix(track->vos_data) != 0) {
1076             /* looks like a DNxHD bit stream */
1077             interlaced = (track->vos_data[5] & 2);
1078             cid = AV_RB32(track->vos_data + 0x28);
1079         } else {
1080             av_log(NULL, AV_LOG_WARNING, "Could not locate DNxHD bit stream in vos_data\n");
1081             return 0;
1082         }
1083     } else {
1084         av_log(NULL, AV_LOG_WARNING, "Could not locate DNxHD bit stream, vos_data too small\n");
1085         return 0;
1086     }
1087
1088     avio_wb32(pb, 24); /* size */
1089     ffio_wfourcc(pb, "ACLR");
1090     ffio_wfourcc(pb, "ACLR");
1091     ffio_wfourcc(pb, "0001");
1092     if (track->par->color_range == AVCOL_RANGE_MPEG || /* Legal range (16-235) */
1093         track->par->color_range == AVCOL_RANGE_UNSPECIFIED) {
1094         avio_wb32(pb, 1); /* Corresponds to 709 in official encoder */
1095     } else { /* Full range (0-255) */
1096         avio_wb32(pb, 2); /* Corresponds to RGB in official encoder */
1097     }
1098     avio_wb32(pb, 0); /* unknown */
1099
1100     if (track->tag == MKTAG('A','V','d','h')) {
1101         avio_wb32(pb, 32);
1102         ffio_wfourcc(pb, "ADHR");
1103         ffio_wfourcc(pb, "0001");
1104         avio_wb32(pb, cid);
1105         avio_wb32(pb, 0); /* unknown */
1106         avio_wb32(pb, 1); /* unknown */
1107         avio_wb32(pb, 0); /* unknown */
1108         avio_wb32(pb, 0); /* unknown */
1109         return 0;
1110     }
1111
1112     avio_wb32(pb, 24); /* size */
1113     ffio_wfourcc(pb, "APRG");
1114     ffio_wfourcc(pb, "APRG");
1115     ffio_wfourcc(pb, "0001");
1116     avio_wb32(pb, 1); /* unknown */
1117     avio_wb32(pb, 0); /* unknown */
1118
1119     avio_wb32(pb, 120); /* size */
1120     ffio_wfourcc(pb, "ARES");
1121     ffio_wfourcc(pb, "ARES");
1122     ffio_wfourcc(pb, "0001");
1123     avio_wb32(pb, cid); /* dnxhd cid, some id ? */
1124     avio_wb32(pb, track->par->width);
1125     /* values below are based on samples created with quicktime and avid codecs */
1126     if (interlaced) {
1127         avio_wb32(pb, track->par->height / 2);
1128         avio_wb32(pb, 2); /* unknown */
1129         avio_wb32(pb, 0); /* unknown */
1130         avio_wb32(pb, 4); /* unknown */
1131     } else {
1132         avio_wb32(pb, track->par->height);
1133         avio_wb32(pb, 1); /* unknown */
1134         avio_wb32(pb, 0); /* unknown */
1135         if (track->par->height == 1080)
1136             avio_wb32(pb, 5); /* unknown */
1137         else
1138             avio_wb32(pb, 6); /* unknown */
1139     }
1140     /* padding */
1141     for (i = 0; i < 10; i++)
1142         avio_wb64(pb, 0);
1143
1144     return 0;
1145 }
1146
1147 static int mov_write_dpxe_tag(AVIOContext *pb, MOVTrack *track)
1148 {
1149     avio_wb32(pb, 12);
1150     ffio_wfourcc(pb, "DpxE");
1151     if (track->par->extradata_size >= 12 &&
1152         !memcmp(&track->par->extradata[4], "DpxE", 4)) {
1153         avio_wb32(pb, track->par->extradata[11]);
1154     } else {
1155         avio_wb32(pb, 1);
1156     }
1157     return 0;
1158 }
1159
1160 static int mp4_get_codec_tag(AVFormatContext *s, MOVTrack *track)
1161 {
1162     int tag = track->par->codec_tag;
1163
1164     if (!ff_codec_get_tag(ff_mp4_obj_type, track->par->codec_id))
1165         return 0;
1166
1167     if      (track->par->codec_id == AV_CODEC_ID_H264)      tag = MKTAG('a','v','c','1');
1168     else if (track->par->codec_id == AV_CODEC_ID_HEVC)      tag = MKTAG('h','e','v','1');
1169     else if (track->par->codec_id == AV_CODEC_ID_VP9)       tag = MKTAG('v','p','0','9');
1170     else if (track->par->codec_id == AV_CODEC_ID_AC3)       tag = MKTAG('a','c','-','3');
1171     else if (track->par->codec_id == AV_CODEC_ID_EAC3)      tag = MKTAG('e','c','-','3');
1172     else if (track->par->codec_id == AV_CODEC_ID_DIRAC)     tag = MKTAG('d','r','a','c');
1173     else if (track->par->codec_id == AV_CODEC_ID_MOV_TEXT)  tag = MKTAG('t','x','3','g');
1174     else if (track->par->codec_id == AV_CODEC_ID_VC1)       tag = MKTAG('v','c','-','1');
1175     else if (track->par->codec_type == AVMEDIA_TYPE_VIDEO)  tag = MKTAG('m','p','4','v');
1176     else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)  tag = MKTAG('m','p','4','a');
1177     else if (track->par->codec_id == AV_CODEC_ID_DVD_SUBTITLE)  tag = MKTAG('m','p','4','s');
1178
1179     return tag;
1180 }
1181
1182 static const AVCodecTag codec_ipod_tags[] = {
1183     { AV_CODEC_ID_H264,     MKTAG('a','v','c','1') },
1184     { AV_CODEC_ID_MPEG4,    MKTAG('m','p','4','v') },
1185     { AV_CODEC_ID_AAC,      MKTAG('m','p','4','a') },
1186     { AV_CODEC_ID_ALAC,     MKTAG('a','l','a','c') },
1187     { AV_CODEC_ID_AC3,      MKTAG('a','c','-','3') },
1188     { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
1189     { AV_CODEC_ID_MOV_TEXT, MKTAG('t','e','x','t') },
1190     { AV_CODEC_ID_NONE, 0 },
1191 };
1192
1193 static int ipod_get_codec_tag(AVFormatContext *s, MOVTrack *track)
1194 {
1195     int tag = track->par->codec_tag;
1196
1197     // keep original tag for subs, ipod supports both formats
1198     if (!(track->par->codec_type == AVMEDIA_TYPE_SUBTITLE &&
1199           (tag == MKTAG('t', 'x', '3', 'g') ||
1200            tag == MKTAG('t', 'e', 'x', 't'))))
1201         tag = ff_codec_get_tag(codec_ipod_tags, track->par->codec_id);
1202
1203     if (!av_match_ext(s->filename, "m4a") &&
1204         !av_match_ext(s->filename, "m4b") &&
1205         !av_match_ext(s->filename, "m4v"))
1206         av_log(s, AV_LOG_WARNING, "Warning, extension is not .m4a, .m4v nor  .m4b "
1207                "Quicktime/Ipod might not play the file\n");
1208
1209     return tag;
1210 }
1211
1212 static int mov_get_dv_codec_tag(AVFormatContext *s, MOVTrack *track)
1213 {
1214     int tag;
1215
1216     if (track->par->width == 720) { /* SD */
1217         if (track->par->height == 480) { /* NTSC */
1218             if  (track->par->format == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','n');
1219             else                                            tag = MKTAG('d','v','c',' ');
1220        }else if (track->par->format == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','p');
1221         else if (track->par->format == AV_PIX_FMT_YUV420P) tag = MKTAG('d','v','c','p');
1222         else                                                tag = MKTAG('d','v','p','p');
1223     } else if (track->par->height == 720) { /* HD 720 line */
1224         if  (track->st->time_base.den == 50)                tag = MKTAG('d','v','h','q');
1225         else                                                tag = MKTAG('d','v','h','p');
1226     } else if (track->par->height == 1080) { /* HD 1080 line */
1227         if  (track->st->time_base.den == 25)                tag = MKTAG('d','v','h','5');
1228         else                                                tag = MKTAG('d','v','h','6');
1229     } else {
1230         av_log(s, AV_LOG_ERROR, "unsupported height for dv codec\n");
1231         return 0;
1232     }
1233
1234     return tag;
1235 }
1236
1237 static AVRational find_fps(AVFormatContext *s, AVStream *st)
1238 {
1239     AVRational rate = st->avg_frame_rate;
1240
1241 #if FF_API_LAVF_AVCTX
1242     FF_DISABLE_DEPRECATION_WARNINGS
1243     rate = av_inv_q(st->codec->time_base);
1244     if (av_timecode_check_frame_rate(rate) < 0) {
1245         av_log(s, AV_LOG_DEBUG, "timecode: tbc=%d/%d invalid, fallback on %d/%d\n",
1246                rate.num, rate.den, st->avg_frame_rate.num, st->avg_frame_rate.den);
1247         rate = st->avg_frame_rate;
1248     }
1249     FF_ENABLE_DEPRECATION_WARNINGS
1250 #endif
1251
1252     return rate;
1253 }
1254
1255 static int mov_get_mpeg2_xdcam_codec_tag(AVFormatContext *s, MOVTrack *track)
1256 {
1257     int tag = track->par->codec_tag;
1258     int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE;
1259     AVStream *st = track->st;
1260     int rate = av_q2d(find_fps(s, st));
1261
1262     if (!tag)
1263         tag = MKTAG('m', '2', 'v', '1'); //fallback tag
1264
1265     if (track->par->format == AV_PIX_FMT_YUV420P) {
1266         if (track->par->width == 1280 && track->par->height == 720) {
1267             if (!interlaced) {
1268                 if      (rate == 24) tag = MKTAG('x','d','v','4');
1269                 else if (rate == 25) tag = MKTAG('x','d','v','5');
1270                 else if (rate == 30) tag = MKTAG('x','d','v','1');
1271                 else if (rate == 50) tag = MKTAG('x','d','v','a');
1272                 else if (rate == 60) tag = MKTAG('x','d','v','9');
1273             }
1274         } else if (track->par->width == 1440 && track->par->height == 1080) {
1275             if (!interlaced) {
1276                 if      (rate == 24) tag = MKTAG('x','d','v','6');
1277                 else if (rate == 25) tag = MKTAG('x','d','v','7');
1278                 else if (rate == 30) tag = MKTAG('x','d','v','8');
1279             } else {
1280                 if      (rate == 25) tag = MKTAG('x','d','v','3');
1281                 else if (rate == 30) tag = MKTAG('x','d','v','2');
1282             }
1283         } else if (track->par->width == 1920 && track->par->height == 1080) {
1284             if (!interlaced) {
1285                 if      (rate == 24) tag = MKTAG('x','d','v','d');
1286                 else if (rate == 25) tag = MKTAG('x','d','v','e');
1287                 else if (rate == 30) tag = MKTAG('x','d','v','f');
1288             } else {
1289                 if      (rate == 25) tag = MKTAG('x','d','v','c');
1290                 else if (rate == 30) tag = MKTAG('x','d','v','b');
1291             }
1292         }
1293     } else if (track->par->format == AV_PIX_FMT_YUV422P) {
1294         if (track->par->width == 1280 && track->par->height == 720) {
1295             if (!interlaced) {
1296                 if      (rate == 24) tag = MKTAG('x','d','5','4');
1297                 else if (rate == 25) tag = MKTAG('x','d','5','5');
1298                 else if (rate == 30) tag = MKTAG('x','d','5','1');
1299                 else if (rate == 50) tag = MKTAG('x','d','5','a');
1300                 else if (rate == 60) tag = MKTAG('x','d','5','9');
1301             }
1302         } else if (track->par->width == 1920 && track->par->height == 1080) {
1303             if (!interlaced) {
1304                 if      (rate == 24) tag = MKTAG('x','d','5','d');
1305                 else if (rate == 25) tag = MKTAG('x','d','5','e');
1306                 else if (rate == 30) tag = MKTAG('x','d','5','f');
1307             } else {
1308                 if      (rate == 25) tag = MKTAG('x','d','5','c');
1309                 else if (rate == 30) tag = MKTAG('x','d','5','b');
1310             }
1311         }
1312     }
1313
1314     return tag;
1315 }
1316
1317 static int mov_get_h264_codec_tag(AVFormatContext *s, MOVTrack *track)
1318 {
1319     int tag = track->par->codec_tag;
1320     int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE;
1321     AVStream *st = track->st;
1322     int rate = av_q2d(find_fps(s, st));
1323
1324     if (!tag)
1325         tag = MKTAG('a', 'v', 'c', 'i'); //fallback tag
1326
1327     if (track->par->format == AV_PIX_FMT_YUV420P10) {
1328         if (track->par->width == 960 && track->par->height == 720) {
1329             if (!interlaced) {
1330                 if      (rate == 24) tag = MKTAG('a','i','5','p');
1331                 else if (rate == 25) tag = MKTAG('a','i','5','q');
1332                 else if (rate == 30) tag = MKTAG('a','i','5','p');
1333                 else if (rate == 50) tag = MKTAG('a','i','5','q');
1334                 else if (rate == 60) tag = MKTAG('a','i','5','p');
1335             }
1336         } else if (track->par->width == 1440 && track->par->height == 1080) {
1337             if (!interlaced) {
1338                 if      (rate == 24) tag = MKTAG('a','i','5','3');
1339                 else if (rate == 25) tag = MKTAG('a','i','5','2');
1340                 else if (rate == 30) tag = MKTAG('a','i','5','3');
1341             } else {
1342                 if      (rate == 50) tag = MKTAG('a','i','5','5');
1343                 else if (rate == 60) tag = MKTAG('a','i','5','6');
1344             }
1345         }
1346     } else if (track->par->format == AV_PIX_FMT_YUV422P10) {
1347         if (track->par->width == 1280 && track->par->height == 720) {
1348             if (!interlaced) {
1349                 if      (rate == 24) tag = MKTAG('a','i','1','p');
1350                 else if (rate == 25) tag = MKTAG('a','i','1','q');
1351                 else if (rate == 30) tag = MKTAG('a','i','1','p');
1352                 else if (rate == 50) tag = MKTAG('a','i','1','q');
1353                 else if (rate == 60) tag = MKTAG('a','i','1','p');
1354             }
1355         } else if (track->par->width == 1920 && track->par->height == 1080) {
1356             if (!interlaced) {
1357                 if      (rate == 24) tag = MKTAG('a','i','1','3');
1358                 else if (rate == 25) tag = MKTAG('a','i','1','2');
1359                 else if (rate == 30) tag = MKTAG('a','i','1','3');
1360             } else {
1361                 if      (rate == 25) tag = MKTAG('a','i','1','5');
1362                 else if (rate == 50) tag = MKTAG('a','i','1','5');
1363                 else if (rate == 60) tag = MKTAG('a','i','1','6');
1364             }
1365         } else if (   track->par->width == 4096 && track->par->height == 2160
1366                    || track->par->width == 3840 && track->par->height == 2160
1367                    || track->par->width == 2048 && track->par->height == 1080) {
1368             tag = MKTAG('a','i','v','x');
1369         }
1370     }
1371
1372     return tag;
1373 }
1374
1375 static const struct {
1376     enum AVPixelFormat pix_fmt;
1377     uint32_t tag;
1378     unsigned bps;
1379 } mov_pix_fmt_tags[] = {
1380     { AV_PIX_FMT_YUYV422, MKTAG('y','u','v','2'),  0 },
1381     { AV_PIX_FMT_YUYV422, MKTAG('y','u','v','s'),  0 },
1382     { AV_PIX_FMT_UYVY422, MKTAG('2','v','u','y'),  0 },
1383     { AV_PIX_FMT_RGB555BE,MKTAG('r','a','w',' '), 16 },
1384     { AV_PIX_FMT_RGB555LE,MKTAG('L','5','5','5'), 16 },
1385     { AV_PIX_FMT_RGB565LE,MKTAG('L','5','6','5'), 16 },
1386     { AV_PIX_FMT_RGB565BE,MKTAG('B','5','6','5'), 16 },
1387     { AV_PIX_FMT_GRAY16BE,MKTAG('b','1','6','g'), 16 },
1388     { AV_PIX_FMT_RGB24,   MKTAG('r','a','w',' '), 24 },
1389     { AV_PIX_FMT_BGR24,   MKTAG('2','4','B','G'), 24 },
1390     { AV_PIX_FMT_ARGB,    MKTAG('r','a','w',' '), 32 },
1391     { AV_PIX_FMT_BGRA,    MKTAG('B','G','R','A'), 32 },
1392     { AV_PIX_FMT_RGBA,    MKTAG('R','G','B','A'), 32 },
1393     { AV_PIX_FMT_ABGR,    MKTAG('A','B','G','R'), 32 },
1394     { AV_PIX_FMT_RGB48BE, MKTAG('b','4','8','r'), 48 },
1395 };
1396
1397 static int mov_get_dnxhd_codec_tag(AVFormatContext *s, MOVTrack *track)
1398 {
1399   int tag = MKTAG('A','V','d','n');
1400   if (track->par->profile != FF_PROFILE_UNKNOWN &&
1401       track->par->profile != FF_PROFILE_DNXHD)
1402       tag = MKTAG('A','V','d','h');
1403   return tag;
1404 }
1405
1406 static int mov_get_rawvideo_codec_tag(AVFormatContext *s, MOVTrack *track)
1407 {
1408     int tag = track->par->codec_tag;
1409     int i;
1410     enum AVPixelFormat pix_fmt;
1411
1412     for (i = 0; i < FF_ARRAY_ELEMS(mov_pix_fmt_tags); i++) {
1413         if (track->par->format == mov_pix_fmt_tags[i].pix_fmt) {
1414             tag = mov_pix_fmt_tags[i].tag;
1415             track->par->bits_per_coded_sample = mov_pix_fmt_tags[i].bps;
1416             if (track->par->codec_tag == mov_pix_fmt_tags[i].tag)
1417                 break;
1418         }
1419     }
1420
1421     pix_fmt = avpriv_find_pix_fmt(avpriv_pix_fmt_bps_mov,
1422                                   track->par->bits_per_coded_sample);
1423     if (tag == MKTAG('r','a','w',' ') &&
1424         track->par->format != pix_fmt &&
1425         track->par->format != AV_PIX_FMT_NONE)
1426         av_log(s, AV_LOG_ERROR, "%s rawvideo cannot be written to mov, output file will be unreadable\n",
1427                av_get_pix_fmt_name(track->par->format));
1428     return tag;
1429 }
1430
1431 static int mov_get_codec_tag(AVFormatContext *s, MOVTrack *track)
1432 {
1433     int tag = track->par->codec_tag;
1434
1435     if (!tag || (s->strict_std_compliance >= FF_COMPLIANCE_NORMAL &&
1436                  (track->par->codec_id == AV_CODEC_ID_DVVIDEO ||
1437                   track->par->codec_id == AV_CODEC_ID_RAWVIDEO ||
1438                   track->par->codec_id == AV_CODEC_ID_H263 ||
1439                   track->par->codec_id == AV_CODEC_ID_H264 ||
1440                   track->par->codec_id == AV_CODEC_ID_DNXHD ||
1441                   track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO ||
1442                   av_get_bits_per_sample(track->par->codec_id)))) { // pcm audio
1443         if (track->par->codec_id == AV_CODEC_ID_DVVIDEO)
1444             tag = mov_get_dv_codec_tag(s, track);
1445         else if (track->par->codec_id == AV_CODEC_ID_RAWVIDEO)
1446             tag = mov_get_rawvideo_codec_tag(s, track);
1447         else if (track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO)
1448             tag = mov_get_mpeg2_xdcam_codec_tag(s, track);
1449         else if (track->par->codec_id == AV_CODEC_ID_H264)
1450             tag = mov_get_h264_codec_tag(s, track);
1451         else if (track->par->codec_id == AV_CODEC_ID_DNXHD)
1452             tag = mov_get_dnxhd_codec_tag(s, track);
1453         else if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
1454             tag = ff_codec_get_tag(ff_codec_movvideo_tags, track->par->codec_id);
1455             if (!tag) { // if no mac fcc found, try with Microsoft tags
1456                 tag = ff_codec_get_tag(ff_codec_bmp_tags, track->par->codec_id);
1457                 if (tag)
1458                     av_log(s, AV_LOG_WARNING, "Using MS style video codec tag, "
1459                            "the file may be unplayable!\n");
1460             }
1461         } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
1462             tag = ff_codec_get_tag(ff_codec_movaudio_tags, track->par->codec_id);
1463             if (!tag) { // if no mac fcc found, try with Microsoft tags
1464                 int ms_tag = ff_codec_get_tag(ff_codec_wav_tags, track->par->codec_id);
1465                 if (ms_tag) {
1466                     tag = MKTAG('m', 's', ((ms_tag >> 8) & 0xff), (ms_tag & 0xff));
1467                     av_log(s, AV_LOG_WARNING, "Using MS style audio codec tag, "
1468                            "the file may be unplayable!\n");
1469                 }
1470             }
1471         } else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)
1472             tag = ff_codec_get_tag(ff_codec_movsubtitle_tags, track->par->codec_id);
1473     }
1474
1475     return tag;
1476 }
1477
1478 static const AVCodecTag codec_3gp_tags[] = {
1479     { AV_CODEC_ID_H263,     MKTAG('s','2','6','3') },
1480     { AV_CODEC_ID_H264,     MKTAG('a','v','c','1') },
1481     { AV_CODEC_ID_MPEG4,    MKTAG('m','p','4','v') },
1482     { AV_CODEC_ID_AAC,      MKTAG('m','p','4','a') },
1483     { AV_CODEC_ID_AMR_NB,   MKTAG('s','a','m','r') },
1484     { AV_CODEC_ID_AMR_WB,   MKTAG('s','a','w','b') },
1485     { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
1486     { AV_CODEC_ID_NONE, 0 },
1487 };
1488
1489 static const AVCodecTag codec_f4v_tags[] = { // XXX: add GIF/PNG/JPEG?
1490     { AV_CODEC_ID_MP3,    MKTAG('.','m','p','3') },
1491     { AV_CODEC_ID_AAC,    MKTAG('m','p','4','a') },
1492     { AV_CODEC_ID_H264,   MKTAG('a','v','c','1') },
1493     { AV_CODEC_ID_VP6A,   MKTAG('V','P','6','A') },
1494     { AV_CODEC_ID_VP6F,   MKTAG('V','P','6','F') },
1495     { AV_CODEC_ID_NONE, 0 },
1496 };
1497
1498 static int mov_find_codec_tag(AVFormatContext *s, MOVTrack *track)
1499 {
1500     int tag;
1501
1502     if (track->mode == MODE_MP4 || track->mode == MODE_PSP)
1503         tag = mp4_get_codec_tag(s, track);
1504     else if (track->mode == MODE_ISM) {
1505         tag = mp4_get_codec_tag(s, track);
1506         if (!tag && track->par->codec_id == AV_CODEC_ID_WMAPRO)
1507             tag = MKTAG('w', 'm', 'a', ' ');
1508     } else if (track->mode == MODE_IPOD)
1509         tag = ipod_get_codec_tag(s, track);
1510     else if (track->mode & MODE_3GP)
1511         tag = ff_codec_get_tag(codec_3gp_tags, track->par->codec_id);
1512     else if (track->mode == MODE_F4V)
1513         tag = ff_codec_get_tag(codec_f4v_tags, track->par->codec_id);
1514     else
1515         tag = mov_get_codec_tag(s, track);
1516
1517     return tag;
1518 }
1519
1520 /** Write uuid atom.
1521  * Needed to make file play in iPods running newest firmware
1522  * goes after avcC atom in moov.trak.mdia.minf.stbl.stsd.avc1
1523  */
1524 static int mov_write_uuid_tag_ipod(AVIOContext *pb)
1525 {
1526     avio_wb32(pb, 28);
1527     ffio_wfourcc(pb, "uuid");
1528     avio_wb32(pb, 0x6b6840f2);
1529     avio_wb32(pb, 0x5f244fc5);
1530     avio_wb32(pb, 0xba39a51b);
1531     avio_wb32(pb, 0xcf0323f3);
1532     avio_wb32(pb, 0x0);
1533     return 28;
1534 }
1535
1536 static const uint16_t fiel_data[] = {
1537     0x0000, 0x0100, 0x0201, 0x0206, 0x0209, 0x020e
1538 };
1539
1540 static int mov_write_fiel_tag(AVIOContext *pb, MOVTrack *track, int field_order)
1541 {
1542     unsigned mov_field_order = 0;
1543     if (field_order < FF_ARRAY_ELEMS(fiel_data))
1544         mov_field_order = fiel_data[field_order];
1545     else
1546         return 0;
1547     avio_wb32(pb, 10);
1548     ffio_wfourcc(pb, "fiel");
1549     avio_wb16(pb, mov_field_order);
1550     return 10;
1551 }
1552
1553 static int mov_write_subtitle_tag(AVIOContext *pb, MOVTrack *track)
1554 {
1555     int64_t pos = avio_tell(pb);
1556     avio_wb32(pb, 0);    /* size */
1557     avio_wl32(pb, track->tag); // store it byteswapped
1558     avio_wb32(pb, 0);    /* Reserved */
1559     avio_wb16(pb, 0);    /* Reserved */
1560     avio_wb16(pb, 1);    /* Data-reference index */
1561
1562     if (track->par->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
1563         mov_write_esds_tag(pb, track);
1564     else if (track->par->extradata_size)
1565         avio_write(pb, track->par->extradata, track->par->extradata_size);
1566
1567     return update_size(pb, pos);
1568 }
1569
1570 static int mov_write_pasp_tag(AVIOContext *pb, MOVTrack *track)
1571 {
1572     AVRational sar;
1573     av_reduce(&sar.num, &sar.den, track->par->sample_aspect_ratio.num,
1574               track->par->sample_aspect_ratio.den, INT_MAX);
1575
1576     avio_wb32(pb, 16);
1577     ffio_wfourcc(pb, "pasp");
1578     avio_wb32(pb, sar.num);
1579     avio_wb32(pb, sar.den);
1580     return 16;
1581 }
1582
1583 static int mov_write_gama_tag(AVIOContext *pb, MOVTrack *track, double gamma)
1584 {
1585     uint32_t gama = 0;
1586     if (gamma <= 0.0)
1587     {
1588         gamma = avpriv_get_gamma_from_trc(track->par->color_trc);
1589     }
1590     av_log(pb, AV_LOG_DEBUG, "gamma value %g\n", gamma);
1591
1592     if (gamma > 1e-6) {
1593         gama = (uint32_t)lrint((double)(1<<16) * gamma);
1594         av_log(pb, AV_LOG_DEBUG, "writing gama value %d\n", gama);
1595
1596         av_assert0(track->mode == MODE_MOV);
1597         avio_wb32(pb, 12);
1598         ffio_wfourcc(pb, "gama");
1599         avio_wb32(pb, gama);
1600         return 12;
1601     }
1602     else {
1603         av_log(pb, AV_LOG_WARNING, "gamma value unknown, unable to write gama atom\n");
1604     }
1605     return 0;
1606 }
1607
1608 static int mov_write_colr_tag(AVIOContext *pb, MOVTrack *track)
1609 {
1610     // Ref (MOV): https://developer.apple.com/library/mac/technotes/tn2162/_index.html#//apple_ref/doc/uid/DTS40013070-CH1-TNTAG9
1611     // Ref (MP4): ISO/IEC 14496-12:2012
1612
1613     if (track->par->color_primaries == AVCOL_PRI_UNSPECIFIED &&
1614         track->par->color_trc == AVCOL_TRC_UNSPECIFIED &&
1615         track->par->color_space == AVCOL_SPC_UNSPECIFIED) {
1616         if ((track->par->width >= 1920 && track->par->height >= 1080)
1617           || (track->par->width == 1280 && track->par->height == 720)) {
1618             av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming bt709\n");
1619             track->par->color_primaries = AVCOL_PRI_BT709;
1620         } else if (track->par->width == 720 && track->height == 576) {
1621             av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming bt470bg\n");
1622             track->par->color_primaries = AVCOL_PRI_BT470BG;
1623         } else if (track->par->width == 720 &&
1624                    (track->height == 486 || track->height == 480)) {
1625             av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming smpte170\n");
1626             track->par->color_primaries = AVCOL_PRI_SMPTE170M;
1627         } else {
1628             av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, unable to assume anything\n");
1629         }
1630         switch (track->par->color_primaries) {
1631         case AVCOL_PRI_BT709:
1632             track->par->color_trc = AVCOL_TRC_BT709;
1633             track->par->color_space = AVCOL_SPC_BT709;
1634             break;
1635         case AVCOL_PRI_SMPTE170M:
1636         case AVCOL_PRI_BT470BG:
1637             track->par->color_trc = AVCOL_TRC_BT709;
1638             track->par->color_space = AVCOL_SPC_SMPTE170M;
1639             break;
1640         }
1641     }
1642
1643     /* We should only ever be called by MOV or MP4. */
1644     av_assert0(track->mode == MODE_MOV || track->mode == MODE_MP4);
1645
1646     avio_wb32(pb, 18 + (track->mode == MODE_MP4));
1647     ffio_wfourcc(pb, "colr");
1648     if (track->mode == MODE_MP4)
1649         ffio_wfourcc(pb, "nclx");
1650     else
1651         ffio_wfourcc(pb, "nclc");
1652     switch (track->par->color_primaries) {
1653     case AVCOL_PRI_BT709:     avio_wb16(pb, 1); break;
1654     case AVCOL_PRI_SMPTE170M:
1655     case AVCOL_PRI_SMPTE240M: avio_wb16(pb, 6); break;
1656     case AVCOL_PRI_BT470BG:   avio_wb16(pb, 5); break;
1657     default:                  avio_wb16(pb, 2);
1658     }
1659     switch (track->par->color_trc) {
1660     case AVCOL_TRC_BT709:     avio_wb16(pb, 1); break;
1661     case AVCOL_TRC_SMPTE170M: avio_wb16(pb, 1); break; // remapped
1662     case AVCOL_TRC_SMPTE240M: avio_wb16(pb, 7); break;
1663     default:                  avio_wb16(pb, 2);
1664     }
1665     switch (track->par->color_space) {
1666     case AVCOL_SPC_BT709:     avio_wb16(pb, 1); break;
1667     case AVCOL_SPC_BT470BG:
1668     case AVCOL_SPC_SMPTE170M: avio_wb16(pb, 6); break;
1669     case AVCOL_SPC_SMPTE240M: avio_wb16(pb, 7); break;
1670     default:                  avio_wb16(pb, 2);
1671     }
1672
1673     if (track->mode == MODE_MP4) {
1674         int full_range = track->par->color_range == AVCOL_RANGE_JPEG;
1675         avio_w8(pb, full_range << 7);
1676         return 19;
1677     } else {
1678         return 18;
1679     }
1680 }
1681
1682 static void find_compressor(char * compressor_name, int len, MOVTrack *track)
1683 {
1684     AVDictionaryEntry *encoder;
1685     int xdcam_res =  (track->par->width == 1280 && track->par->height == 720)
1686                   || (track->par->width == 1440 && track->par->height == 1080)
1687                   || (track->par->width == 1920 && track->par->height == 1080);
1688
1689     if (track->mode == MODE_MOV &&
1690         (encoder = av_dict_get(track->st->metadata, "encoder", NULL, 0))) {
1691         av_strlcpy(compressor_name, encoder->value, 32);
1692     } else if (track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO && xdcam_res) {
1693         int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE;
1694         AVStream *st = track->st;
1695         int rate = av_q2d(find_fps(NULL, st));
1696         av_strlcatf(compressor_name, len, "XDCAM");
1697         if (track->par->format == AV_PIX_FMT_YUV422P) {
1698             av_strlcatf(compressor_name, len, " HD422");
1699         } else if(track->par->width == 1440) {
1700             av_strlcatf(compressor_name, len, " HD");
1701         } else
1702             av_strlcatf(compressor_name, len, " EX");
1703
1704         av_strlcatf(compressor_name, len, " %d%c", track->par->height, interlaced ? 'i' : 'p');
1705
1706         av_strlcatf(compressor_name, len, "%d", rate * (interlaced + 1));
1707     }
1708 }
1709
1710 static int mov_write_video_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
1711 {
1712     int64_t pos = avio_tell(pb);
1713     char compressor_name[32] = { 0 };
1714     int avid = 0;
1715
1716     avio_wb32(pb, 0); /* size */
1717     if (mov->encryption_scheme != MOV_ENC_NONE) {
1718         ffio_wfourcc(pb, "encv");
1719     } else {
1720         avio_wl32(pb, track->tag); // store it byteswapped
1721     }
1722     avio_wb32(pb, 0); /* Reserved */
1723     avio_wb16(pb, 0); /* Reserved */
1724     avio_wb16(pb, 1); /* Data-reference index */
1725
1726     avio_wb16(pb, 0); /* Codec stream version */
1727     avio_wb16(pb, 0); /* Codec stream revision (=0) */
1728     if (track->mode == MODE_MOV) {
1729         ffio_wfourcc(pb, "FFMP"); /* Vendor */
1730         if (track->par->codec_id == AV_CODEC_ID_RAWVIDEO) {
1731             avio_wb32(pb, 0); /* Temporal Quality */
1732             avio_wb32(pb, 0x400); /* Spatial Quality = lossless*/
1733         } else {
1734             avio_wb32(pb, 0x200); /* Temporal Quality = normal */
1735             avio_wb32(pb, 0x200); /* Spatial Quality = normal */
1736         }
1737     } else {
1738         avio_wb32(pb, 0); /* Reserved */
1739         avio_wb32(pb, 0); /* Reserved */
1740         avio_wb32(pb, 0); /* Reserved */
1741     }
1742     avio_wb16(pb, track->par->width); /* Video width */
1743     avio_wb16(pb, track->height); /* Video height */
1744     avio_wb32(pb, 0x00480000); /* Horizontal resolution 72dpi */
1745     avio_wb32(pb, 0x00480000); /* Vertical resolution 72dpi */
1746     avio_wb32(pb, 0); /* Data size (= 0) */
1747     avio_wb16(pb, 1); /* Frame count (= 1) */
1748
1749     /* FIXME not sure, ISO 14496-1 draft where it shall be set to 0 */
1750     find_compressor(compressor_name, 32, track);
1751     avio_w8(pb, strlen(compressor_name));
1752     avio_write(pb, compressor_name, 31);
1753
1754     if (track->mode == MODE_MOV && track->par->bits_per_coded_sample)
1755         avio_wb16(pb, track->par->bits_per_coded_sample |
1756                   (track->par->format == AV_PIX_FMT_GRAY8 ? 0x20 : 0));
1757     else
1758         avio_wb16(pb, 0x18); /* Reserved */
1759
1760     if (track->mode == MODE_MOV && track->par->format == AV_PIX_FMT_PAL8) {
1761         int pal_size = 1 << track->par->bits_per_coded_sample;
1762         int i;
1763         avio_wb16(pb, 0);             /* Color table ID */
1764         avio_wb32(pb, 0);             /* Color table seed */
1765         avio_wb16(pb, 0x8000);        /* Color table flags */
1766         avio_wb16(pb, pal_size - 1);  /* Color table size (zero-relative) */
1767         for (i = 0; i < pal_size; i++) {
1768             uint32_t rgb = track->palette[i];
1769             uint16_t r = (rgb >> 16) & 0xff;
1770             uint16_t g = (rgb >> 8)  & 0xff;
1771             uint16_t b = rgb         & 0xff;
1772             avio_wb16(pb, 0);
1773             avio_wb16(pb, (r << 8) | r);
1774             avio_wb16(pb, (g << 8) | g);
1775             avio_wb16(pb, (b << 8) | b);
1776         }
1777     } else
1778         avio_wb16(pb, 0xffff); /* Reserved */
1779
1780     if (track->tag == MKTAG('m','p','4','v'))
1781         mov_write_esds_tag(pb, track);
1782     else if (track->par->codec_id == AV_CODEC_ID_H263)
1783         mov_write_d263_tag(pb);
1784     else if (track->par->codec_id == AV_CODEC_ID_AVUI ||
1785             track->par->codec_id == AV_CODEC_ID_SVQ3) {
1786         mov_write_extradata_tag(pb, track);
1787         avio_wb32(pb, 0);
1788     } else if (track->par->codec_id == AV_CODEC_ID_DNXHD) {
1789         mov_write_avid_tag(pb, track);
1790         avid = 1;
1791     } else if (track->par->codec_id == AV_CODEC_ID_HEVC)
1792         mov_write_hvcc_tag(pb, track);
1793     else if (track->par->codec_id == AV_CODEC_ID_H264 && !TAG_IS_AVCI(track->tag)) {
1794         mov_write_avcc_tag(pb, track);
1795         if (track->mode == MODE_IPOD)
1796             mov_write_uuid_tag_ipod(pb);
1797     } else if (track->par->codec_id == AV_CODEC_ID_VP9) {
1798         mov_write_vpcc_tag(mov->fc, pb, track);
1799     } else if (track->par->codec_id == AV_CODEC_ID_VC1 && track->vos_len > 0)
1800         mov_write_dvc1_tag(pb, track);
1801     else if (track->par->codec_id == AV_CODEC_ID_VP6F ||
1802              track->par->codec_id == AV_CODEC_ID_VP6A) {
1803         /* Don't write any potential extradata here - the cropping
1804          * is signalled via the normal width/height fields. */
1805     } else if (track->par->codec_id == AV_CODEC_ID_R10K) {
1806         if (track->par->codec_tag == MKTAG('R','1','0','k'))
1807             mov_write_dpxe_tag(pb, track);
1808     } else if (track->vos_len > 0)
1809         mov_write_glbl_tag(pb, track);
1810
1811     if (track->par->codec_id != AV_CODEC_ID_H264 &&
1812         track->par->codec_id != AV_CODEC_ID_MPEG4 &&
1813         track->par->codec_id != AV_CODEC_ID_DNXHD) {
1814         int field_order = track->par->field_order;
1815
1816 #if FF_API_LAVF_AVCTX
1817     FF_DISABLE_DEPRECATION_WARNINGS
1818     if (field_order != track->st->codec->field_order && track->st->codec->field_order != AV_FIELD_UNKNOWN)
1819         field_order = track->st->codec->field_order;
1820     FF_ENABLE_DEPRECATION_WARNINGS
1821 #endif
1822
1823         if (field_order != AV_FIELD_UNKNOWN)
1824             mov_write_fiel_tag(pb, track, field_order);
1825     }
1826
1827     if (mov->flags & FF_MOV_FLAG_WRITE_GAMA) {
1828         if (track->mode == MODE_MOV)
1829             mov_write_gama_tag(pb, track, mov->gamma);
1830         else
1831             av_log(mov->fc, AV_LOG_WARNING, "Not writing 'gama' atom. Format is not MOV.\n");
1832     }
1833     if (mov->flags & FF_MOV_FLAG_WRITE_COLR) {
1834         if (track->mode == MODE_MOV || track->mode == MODE_MP4)
1835             mov_write_colr_tag(pb, track);
1836         else
1837             av_log(mov->fc, AV_LOG_WARNING, "Not writing 'colr' atom. Format is not MOV or MP4.\n");
1838     }
1839
1840     if (track->par->sample_aspect_ratio.den && track->par->sample_aspect_ratio.num &&
1841         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_MP4)
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     static const uint8_t uuid[] = {
3585         0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd,
3586         0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66
3587     };
3588
3589     avio_wb32(pb, 0);
3590     ffio_wfourcc(pb, "uuid");
3591     avio_write(pb, uuid, sizeof(uuid));
3592     avio_wb32(pb, 0);
3593
3594     avio_printf(pb, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
3595     avio_printf(pb, "<smil xmlns=\"http://www.w3.org/2001/SMIL20/Language\">\n");
3596     avio_printf(pb, "<head>\n");
3597     if (!(mov->fc->flags & AVFMT_FLAG_BITEXACT))
3598         avio_printf(pb, "<meta name=\"creator\" content=\"%s\" />\n",
3599                     LIBAVFORMAT_IDENT);
3600     avio_printf(pb, "</head>\n");
3601     avio_printf(pb, "<body>\n");
3602     avio_printf(pb, "<switch>\n");
3603
3604     mov_setup_track_ids(mov, s);
3605
3606     for (i = 0; i < mov->nb_streams; i++) {
3607         MOVTrack *track = &mov->tracks[i];
3608         const char *type;
3609         int track_id = track->track_id;
3610
3611         if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
3612             type = "video";
3613         } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
3614             type = "audio";
3615         } else {
3616             continue;
3617         }
3618         avio_printf(pb, "<%s systemBitrate=\"%"PRId64"\">\n", type,
3619                     (int64_t)track->par->bit_rate);
3620         param_write_int(pb, "systemBitrate", track->par->bit_rate);
3621         param_write_int(pb, "trackID", track_id);
3622         if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
3623             if (track->par->codec_id == AV_CODEC_ID_H264) {
3624                 uint8_t *ptr;
3625                 int size = track->par->extradata_size;
3626                 if (!ff_avc_write_annexb_extradata(track->par->extradata, &ptr,
3627                                                    &size)) {
3628                     param_write_hex(pb, "CodecPrivateData",
3629                                     ptr ? ptr : track->par->extradata,
3630                                     size);
3631                     av_free(ptr);
3632                 }
3633                 param_write_string(pb, "FourCC", "H264");
3634             } else if (track->par->codec_id == AV_CODEC_ID_VC1) {
3635                 param_write_string(pb, "FourCC", "WVC1");
3636                 param_write_hex(pb, "CodecPrivateData", track->par->extradata,
3637                                 track->par->extradata_size);
3638             }
3639             param_write_int(pb, "MaxWidth", track->par->width);
3640             param_write_int(pb, "MaxHeight", track->par->height);
3641             param_write_int(pb, "DisplayWidth", track->par->width);
3642             param_write_int(pb, "DisplayHeight", track->par->height);
3643         } else {
3644             if (track->par->codec_id == AV_CODEC_ID_AAC) {
3645                 switch (track->par->profile)
3646                 {
3647                     case FF_PROFILE_AAC_HE_V2:
3648                         param_write_string(pb, "FourCC", "AACP");
3649                         break;
3650                     case FF_PROFILE_AAC_HE:
3651                         param_write_string(pb, "FourCC", "AACH");
3652                         break;
3653                     default:
3654                         param_write_string(pb, "FourCC", "AACL");
3655                 }
3656             } else if (track->par->codec_id == AV_CODEC_ID_WMAPRO) {
3657                 param_write_string(pb, "FourCC", "WMAP");
3658             }
3659             param_write_hex(pb, "CodecPrivateData", track->par->extradata,
3660                             track->par->extradata_size);
3661             param_write_int(pb, "AudioTag", ff_codec_get_tag(ff_codec_wav_tags,
3662                                                              track->par->codec_id));
3663             param_write_int(pb, "Channels", track->par->channels);
3664             param_write_int(pb, "SamplingRate", track->par->sample_rate);
3665             param_write_int(pb, "BitsPerSample", 16);
3666             param_write_int(pb, "PacketSize", track->par->block_align ?
3667                                               track->par->block_align : 4);
3668         }
3669         avio_printf(pb, "</%s>\n", type);
3670     }
3671     avio_printf(pb, "</switch>\n");
3672     avio_printf(pb, "</body>\n");
3673     avio_printf(pb, "</smil>\n");
3674
3675     return update_size(pb, pos);
3676 }
3677
3678 static int mov_write_mfhd_tag(AVIOContext *pb, MOVMuxContext *mov)
3679 {
3680     avio_wb32(pb, 16);
3681     ffio_wfourcc(pb, "mfhd");
3682     avio_wb32(pb, 0);
3683     avio_wb32(pb, mov->fragments);
3684     return 0;
3685 }
3686
3687 static uint32_t get_sample_flags(MOVTrack *track, MOVIentry *entry)
3688 {
3689     return entry->flags & MOV_SYNC_SAMPLE ? MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO :
3690            (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC);
3691 }
3692
3693 static int mov_write_tfhd_tag(AVIOContext *pb, MOVMuxContext *mov,
3694                               MOVTrack *track, int64_t moof_offset)
3695 {
3696     int64_t pos = avio_tell(pb);
3697     uint32_t flags = MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
3698                      MOV_TFHD_BASE_DATA_OFFSET;
3699     if (!track->entry) {
3700         flags |= MOV_TFHD_DURATION_IS_EMPTY;
3701     } else {
3702         flags |= MOV_TFHD_DEFAULT_FLAGS;
3703     }
3704     if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET)
3705         flags &= ~MOV_TFHD_BASE_DATA_OFFSET;
3706     if (mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) {
3707         flags &= ~MOV_TFHD_BASE_DATA_OFFSET;
3708         flags |= MOV_TFHD_DEFAULT_BASE_IS_MOOF;
3709     }
3710
3711     /* Don't set a default sample size, the silverlight player refuses
3712      * to play files with that set. Don't set a default sample duration,
3713      * WMP freaks out if it is set. Don't set a base data offset, PIFF
3714      * file format says it MUST NOT be set. */
3715     if (track->mode == MODE_ISM)
3716         flags &= ~(MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
3717                    MOV_TFHD_BASE_DATA_OFFSET);
3718
3719     avio_wb32(pb, 0); /* size placeholder */
3720     ffio_wfourcc(pb, "tfhd");
3721     avio_w8(pb, 0); /* version */
3722     avio_wb24(pb, flags);
3723
3724     avio_wb32(pb, track->track_id); /* track-id */
3725     if (flags & MOV_TFHD_BASE_DATA_OFFSET)
3726         avio_wb64(pb, moof_offset);
3727     if (flags & MOV_TFHD_DEFAULT_DURATION) {
3728         track->default_duration = get_cluster_duration(track, 0);
3729         avio_wb32(pb, track->default_duration);
3730     }
3731     if (flags & MOV_TFHD_DEFAULT_SIZE) {
3732         track->default_size = track->entry ? track->cluster[0].size : 1;
3733         avio_wb32(pb, track->default_size);
3734     } else
3735         track->default_size = -1;
3736
3737     if (flags & MOV_TFHD_DEFAULT_FLAGS) {
3738         /* Set the default flags based on the second sample, if available.
3739          * If the first sample is different, that can be signaled via a separate field. */
3740         if (track->entry > 1)
3741             track->default_sample_flags = get_sample_flags(track, &track->cluster[1]);
3742         else
3743             track->default_sample_flags =
3744                 track->par->codec_type == AVMEDIA_TYPE_VIDEO ?
3745                 (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC) :
3746                 MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO;
3747         avio_wb32(pb, track->default_sample_flags);
3748     }
3749
3750     return update_size(pb, pos);
3751 }
3752
3753 static int mov_write_trun_tag(AVIOContext *pb, MOVMuxContext *mov,
3754                               MOVTrack *track, int moof_size,
3755                               int first, int end)
3756 {
3757     int64_t pos = avio_tell(pb);
3758     uint32_t flags = MOV_TRUN_DATA_OFFSET;
3759     int i;
3760
3761     for (i = first; i < end; i++) {
3762         if (get_cluster_duration(track, i) != track->default_duration)
3763             flags |= MOV_TRUN_SAMPLE_DURATION;
3764         if (track->cluster[i].size != track->default_size)
3765             flags |= MOV_TRUN_SAMPLE_SIZE;
3766         if (i > first && get_sample_flags(track, &track->cluster[i]) != track->default_sample_flags)
3767             flags |= MOV_TRUN_SAMPLE_FLAGS;
3768     }
3769     if (!(flags & MOV_TRUN_SAMPLE_FLAGS) && track->entry > 0 &&
3770          get_sample_flags(track, &track->cluster[0]) != track->default_sample_flags)
3771         flags |= MOV_TRUN_FIRST_SAMPLE_FLAGS;
3772     if (track->flags & MOV_TRACK_CTTS)
3773         flags |= MOV_TRUN_SAMPLE_CTS;
3774
3775     avio_wb32(pb, 0); /* size placeholder */
3776     ffio_wfourcc(pb, "trun");
3777     avio_w8(pb, 0); /* version */
3778     avio_wb24(pb, flags);
3779
3780     avio_wb32(pb, end - first); /* sample count */
3781     if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET &&
3782         !(mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) &&
3783         !mov->first_trun)
3784         avio_wb32(pb, 0); /* Later tracks follow immediately after the previous one */
3785     else
3786         avio_wb32(pb, moof_size + 8 + track->data_offset +
3787                       track->cluster[first].pos); /* data offset */
3788     if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS)
3789         avio_wb32(pb, get_sample_flags(track, &track->cluster[first]));
3790
3791     for (i = first; i < end; i++) {
3792         if (flags & MOV_TRUN_SAMPLE_DURATION)
3793             avio_wb32(pb, get_cluster_duration(track, i));
3794         if (flags & MOV_TRUN_SAMPLE_SIZE)
3795             avio_wb32(pb, track->cluster[i].size);
3796         if (flags & MOV_TRUN_SAMPLE_FLAGS)
3797             avio_wb32(pb, get_sample_flags(track, &track->cluster[i]));
3798         if (flags & MOV_TRUN_SAMPLE_CTS)
3799             avio_wb32(pb, track->cluster[i].cts);
3800     }
3801
3802     mov->first_trun = 0;
3803     return update_size(pb, pos);
3804 }
3805
3806 static int mov_write_tfxd_tag(AVIOContext *pb, MOVTrack *track)
3807 {
3808     int64_t pos = avio_tell(pb);
3809     static const uint8_t uuid[] = {
3810         0x6d, 0x1d, 0x9b, 0x05, 0x42, 0xd5, 0x44, 0xe6,
3811         0x80, 0xe2, 0x14, 0x1d, 0xaf, 0xf7, 0x57, 0xb2
3812     };
3813
3814     avio_wb32(pb, 0); /* size placeholder */
3815     ffio_wfourcc(pb, "uuid");
3816     avio_write(pb, uuid, sizeof(uuid));
3817     avio_w8(pb, 1);
3818     avio_wb24(pb, 0);
3819     avio_wb64(pb, track->start_dts + track->frag_start +
3820                   track->cluster[0].cts);
3821     avio_wb64(pb, track->end_pts -
3822                   (track->cluster[0].dts + track->cluster[0].cts));
3823
3824     return update_size(pb, pos);
3825 }
3826
3827 static int mov_write_tfrf_tag(AVIOContext *pb, MOVMuxContext *mov,
3828                               MOVTrack *track, int entry)
3829 {
3830     int n = track->nb_frag_info - 1 - entry, i;
3831     int size = 8 + 16 + 4 + 1 + 16*n;
3832     static const uint8_t uuid[] = {
3833         0xd4, 0x80, 0x7e, 0xf2, 0xca, 0x39, 0x46, 0x95,
3834         0x8e, 0x54, 0x26, 0xcb, 0x9e, 0x46, 0xa7, 0x9f
3835     };
3836
3837     if (entry < 0)
3838         return 0;
3839
3840     avio_seek(pb, track->frag_info[entry].tfrf_offset, SEEK_SET);
3841     avio_wb32(pb, size);
3842     ffio_wfourcc(pb, "uuid");
3843     avio_write(pb, uuid, sizeof(uuid));
3844     avio_w8(pb, 1);
3845     avio_wb24(pb, 0);
3846     avio_w8(pb, n);
3847     for (i = 0; i < n; i++) {
3848         int index = entry + 1 + i;
3849         avio_wb64(pb, track->frag_info[index].time);
3850         avio_wb64(pb, track->frag_info[index].duration);
3851     }
3852     if (n < mov->ism_lookahead) {
3853         int free_size = 16 * (mov->ism_lookahead - n);
3854         avio_wb32(pb, free_size);
3855         ffio_wfourcc(pb, "free");
3856         ffio_fill(pb, 0, free_size - 8);
3857     }
3858
3859     return 0;
3860 }
3861
3862 static int mov_write_tfrf_tags(AVIOContext *pb, MOVMuxContext *mov,
3863                                MOVTrack *track)
3864 {
3865     int64_t pos = avio_tell(pb);
3866     int i;
3867     for (i = 0; i < mov->ism_lookahead; i++) {
3868         /* Update the tfrf tag for the last ism_lookahead fragments,
3869          * nb_frag_info - 1 is the next fragment to be written. */
3870         mov_write_tfrf_tag(pb, mov, track, track->nb_frag_info - 2 - i);
3871     }
3872     avio_seek(pb, pos, SEEK_SET);
3873     return 0;
3874 }
3875
3876 static int mov_add_tfra_entries(AVIOContext *pb, MOVMuxContext *mov, int tracks,
3877                                 int size)
3878 {
3879     int i;
3880     for (i = 0; i < mov->nb_streams; i++) {
3881         MOVTrack *track = &mov->tracks[i];
3882         MOVFragmentInfo *info;
3883         if ((tracks >= 0 && i != tracks) || !track->entry)
3884             continue;
3885         track->nb_frag_info++;
3886         if (track->nb_frag_info >= track->frag_info_capacity) {
3887             unsigned new_capacity = track->nb_frag_info + MOV_FRAG_INFO_ALLOC_INCREMENT;
3888             if (av_reallocp_array(&track->frag_info,
3889                                   new_capacity,
3890                                   sizeof(*track->frag_info)))
3891                 return AVERROR(ENOMEM);
3892             track->frag_info_capacity = new_capacity;
3893         }
3894         info = &track->frag_info[track->nb_frag_info - 1];
3895         info->offset   = avio_tell(pb);
3896         info->size     = size;
3897         // Try to recreate the original pts for the first packet
3898         // from the fields we have stored
3899         info->time     = track->start_dts + track->frag_start +
3900                          track->cluster[0].cts;
3901         info->duration = track->end_pts -
3902                          (track->cluster[0].dts + track->cluster[0].cts);
3903         // If the pts is less than zero, we will have trimmed
3904         // away parts of the media track using an edit list,
3905         // and the corresponding start presentation time is zero.
3906         if (info->time < 0) {
3907             info->duration += info->time;
3908             info->time = 0;
3909         }
3910         info->tfrf_offset = 0;
3911         mov_write_tfrf_tags(pb, mov, track);
3912     }
3913     return 0;
3914 }
3915
3916 static int mov_write_tfdt_tag(AVIOContext *pb, MOVTrack *track)
3917 {
3918     int64_t pos = avio_tell(pb);
3919
3920     avio_wb32(pb, 0); /* size */
3921     ffio_wfourcc(pb, "tfdt");
3922     avio_w8(pb, 1); /* version */
3923     avio_wb24(pb, 0);
3924     avio_wb64(pb, track->frag_start);
3925     return update_size(pb, pos);
3926 }
3927
3928 static int mov_write_traf_tag(AVIOContext *pb, MOVMuxContext *mov,
3929                               MOVTrack *track, int64_t moof_offset,
3930                               int moof_size)
3931 {
3932     int64_t pos = avio_tell(pb);
3933     int i, start = 0;
3934     avio_wb32(pb, 0); /* size placeholder */
3935     ffio_wfourcc(pb, "traf");
3936
3937     mov_write_tfhd_tag(pb, mov, track, moof_offset);
3938     if (mov->mode != MODE_ISM)
3939         mov_write_tfdt_tag(pb, track);
3940     for (i = 1; i < track->entry; i++) {
3941         if (track->cluster[i].pos != track->cluster[i - 1].pos + track->cluster[i - 1].size) {
3942             mov_write_trun_tag(pb, mov, track, moof_size, start, i);
3943             start = i;
3944         }
3945     }
3946     mov_write_trun_tag(pb, mov, track, moof_size, start, track->entry);
3947     if (mov->mode == MODE_ISM) {
3948         mov_write_tfxd_tag(pb, track);
3949
3950         if (mov->ism_lookahead) {
3951             int i, size = 16 + 4 + 1 + 16 * mov->ism_lookahead;
3952
3953             if (track->nb_frag_info > 0) {
3954                 MOVFragmentInfo *info = &track->frag_info[track->nb_frag_info - 1];
3955                 if (!info->tfrf_offset)
3956                     info->tfrf_offset = avio_tell(pb);
3957             }
3958             avio_wb32(pb, 8 + size);
3959             ffio_wfourcc(pb, "free");
3960             for (i = 0; i < size; i++)
3961                 avio_w8(pb, 0);
3962         }
3963     }
3964
3965     return update_size(pb, pos);
3966 }
3967
3968 static int mov_write_moof_tag_internal(AVIOContext *pb, MOVMuxContext *mov,
3969                                        int tracks, int moof_size)
3970 {
3971     int64_t pos = avio_tell(pb);
3972     int i;
3973
3974     avio_wb32(pb, 0); /* size placeholder */
3975     ffio_wfourcc(pb, "moof");
3976     mov->first_trun = 1;
3977
3978     mov_write_mfhd_tag(pb, mov);
3979     for (i = 0; i < mov->nb_streams; i++) {
3980         MOVTrack *track = &mov->tracks[i];
3981         if (tracks >= 0 && i != tracks)
3982             continue;
3983         if (!track->entry)
3984             continue;
3985         mov_write_traf_tag(pb, mov, track, pos, moof_size);
3986     }
3987
3988     return update_size(pb, pos);
3989 }
3990
3991 static int mov_write_sidx_tag(AVIOContext *pb,
3992                               MOVTrack *track, int ref_size, int total_sidx_size)
3993 {
3994     int64_t pos = avio_tell(pb), offset_pos, end_pos;
3995     int64_t presentation_time, duration, offset;
3996     int starts_with_SAP, i, entries;
3997
3998     if (track->entry) {
3999         entries = 1;
4000         presentation_time = track->start_dts + track->frag_start +
4001                             track->cluster[0].cts;
4002         duration = track->end_pts -
4003                    (track->cluster[0].dts + track->cluster[0].cts);
4004         starts_with_SAP = track->cluster[0].flags & MOV_SYNC_SAMPLE;
4005
4006         // pts<0 should be cut away using edts
4007         if (presentation_time < 0) {
4008             duration += presentation_time;
4009             presentation_time = 0;
4010         }
4011     } else {
4012         entries = track->nb_frag_info;
4013         if (entries <= 0)
4014             return 0;
4015         presentation_time = track->frag_info[0].time;
4016     }
4017
4018     avio_wb32(pb, 0); /* size */
4019     ffio_wfourcc(pb, "sidx");
4020     avio_w8(pb, 1); /* version */
4021     avio_wb24(pb, 0);
4022     avio_wb32(pb, track->track_id); /* reference_ID */
4023     avio_wb32(pb, track->timescale); /* timescale */
4024     avio_wb64(pb, presentation_time); /* earliest_presentation_time */
4025     offset_pos = avio_tell(pb);
4026     avio_wb64(pb, 0); /* first_offset (offset to referenced moof) */
4027     avio_wb16(pb, 0); /* reserved */
4028
4029     avio_wb16(pb, entries); /* reference_count */
4030     for (i = 0; i < entries; i++) {
4031         if (!track->entry) {
4032             if (i > 1 && track->frag_info[i].offset != track->frag_info[i - 1].offset + track->frag_info[i - 1].size) {
4033                av_log(NULL, AV_LOG_ERROR, "Non-consecutive fragments, writing incorrect sidx\n");
4034             }
4035             duration = track->frag_info[i].duration;
4036             ref_size = track->frag_info[i].size;
4037             starts_with_SAP = 1;
4038         }
4039         avio_wb32(pb, (0 << 31) | (ref_size & 0x7fffffff)); /* reference_type (0 = media) | referenced_size */
4040         avio_wb32(pb, duration); /* subsegment_duration */
4041         avio_wb32(pb, (starts_with_SAP << 31) | (0 << 28) | 0); /* starts_with_SAP | SAP_type | SAP_delta_time */
4042     }
4043
4044     end_pos = avio_tell(pb);
4045     offset = pos + total_sidx_size - end_pos;
4046     avio_seek(pb, offset_pos, SEEK_SET);
4047     avio_wb64(pb, offset);
4048     avio_seek(pb, end_pos, SEEK_SET);
4049     return update_size(pb, pos);
4050 }
4051
4052 static int mov_write_sidx_tags(AVIOContext *pb, MOVMuxContext *mov,
4053                                int tracks, int ref_size)
4054 {
4055     int i, round, ret;
4056     AVIOContext *avio_buf;
4057     int total_size = 0;
4058     for (round = 0; round < 2; round++) {
4059         // First run one round to calculate the total size of all
4060         // sidx atoms.
4061         // This would be much simpler if we'd only write one sidx
4062         // atom, for the first track in the moof.
4063         if (round == 0) {
4064             if ((ret = ffio_open_null_buf(&avio_buf)) < 0)
4065                 return ret;
4066         } else {
4067             avio_buf = pb;
4068         }
4069         for (i = 0; i < mov->nb_streams; i++) {
4070             MOVTrack *track = &mov->tracks[i];
4071             if (tracks >= 0 && i != tracks)
4072                 continue;
4073             // When writing a sidx for the full file, entry is 0, but
4074             // we want to include all tracks. ref_size is 0 in this case,
4075             // since we read it from frag_info instead.
4076             if (!track->entry && ref_size > 0)
4077                 continue;
4078             total_size -= mov_write_sidx_tag(avio_buf, track, ref_size,
4079                                              total_size);
4080         }
4081         if (round == 0)
4082             total_size = ffio_close_null_buf(avio_buf);
4083     }
4084     return 0;
4085 }
4086
4087 static int mov_write_moof_tag(AVIOContext *pb, MOVMuxContext *mov, int tracks,
4088                               int64_t mdat_size)
4089 {
4090     AVIOContext *avio_buf;
4091     int ret, moof_size;
4092
4093     if ((ret = ffio_open_null_buf(&avio_buf)) < 0)
4094         return ret;
4095     mov_write_moof_tag_internal(avio_buf, mov, tracks, 0);
4096     moof_size = ffio_close_null_buf(avio_buf);
4097
4098     if (mov->flags & FF_MOV_FLAG_DASH && !(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX))
4099         mov_write_sidx_tags(pb, mov, tracks, moof_size + 8 + mdat_size);
4100
4101     if ((ret = mov_add_tfra_entries(pb, mov, tracks, moof_size + 8 + mdat_size)) < 0)
4102         return ret;
4103
4104     return mov_write_moof_tag_internal(pb, mov, tracks, moof_size);
4105 }
4106
4107 static int mov_write_tfra_tag(AVIOContext *pb, MOVTrack *track)
4108 {
4109     int64_t pos = avio_tell(pb);
4110     int i;
4111
4112     avio_wb32(pb, 0); /* size placeholder */
4113     ffio_wfourcc(pb, "tfra");
4114     avio_w8(pb, 1); /* version */
4115     avio_wb24(pb, 0);
4116
4117     avio_wb32(pb, track->track_id);
4118     avio_wb32(pb, 0); /* length of traf/trun/sample num */
4119     avio_wb32(pb, track->nb_frag_info);
4120     for (i = 0; i < track->nb_frag_info; i++) {
4121         avio_wb64(pb, track->frag_info[i].time);
4122         avio_wb64(pb, track->frag_info[i].offset + track->data_offset);
4123         avio_w8(pb, 1); /* traf number */
4124         avio_w8(pb, 1); /* trun number */
4125         avio_w8(pb, 1); /* sample number */
4126     }
4127
4128     return update_size(pb, pos);
4129 }
4130
4131 static int mov_write_mfra_tag(AVIOContext *pb, MOVMuxContext *mov)
4132 {
4133     int64_t pos = avio_tell(pb);
4134     int i;
4135
4136     avio_wb32(pb, 0); /* size placeholder */
4137     ffio_wfourcc(pb, "mfra");
4138     /* An empty mfra atom is enough to indicate to the publishing point that
4139      * the stream has ended. */
4140     if (mov->flags & FF_MOV_FLAG_ISML)
4141         return update_size(pb, pos);
4142
4143     for (i = 0; i < mov->nb_streams; i++) {
4144         MOVTrack *track = &mov->tracks[i];
4145         if (track->nb_frag_info)
4146             mov_write_tfra_tag(pb, track);
4147     }
4148
4149     avio_wb32(pb, 16);
4150     ffio_wfourcc(pb, "mfro");
4151     avio_wb32(pb, 0); /* version + flags */
4152     avio_wb32(pb, avio_tell(pb) + 4 - pos);
4153
4154     return update_size(pb, pos);
4155 }
4156
4157 static int mov_write_mdat_tag(AVIOContext *pb, MOVMuxContext *mov)
4158 {
4159     avio_wb32(pb, 8);    // placeholder for extended size field (64 bit)
4160     ffio_wfourcc(pb, mov->mode == MODE_MOV ? "wide" : "free");
4161
4162     mov->mdat_pos = avio_tell(pb);
4163     avio_wb32(pb, 0); /* size placeholder*/
4164     ffio_wfourcc(pb, "mdat");
4165     return 0;
4166 }
4167
4168 /* TODO: This needs to be more general */
4169 static int mov_write_ftyp_tag(AVIOContext *pb, AVFormatContext *s)
4170 {
4171     MOVMuxContext *mov = s->priv_data;
4172     int64_t pos = avio_tell(pb);
4173     int has_h264 = 0, has_video = 0;
4174     int minor = 0x200;
4175     int i;
4176
4177     for (i = 0; i < s->nb_streams; i++) {
4178         AVStream *st = s->streams[i];
4179         if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
4180             has_video = 1;
4181         if (st->codecpar->codec_id == AV_CODEC_ID_H264)
4182             has_h264 = 1;
4183     }
4184
4185     avio_wb32(pb, 0); /* size */
4186     ffio_wfourcc(pb, "ftyp");
4187
4188     if (mov->major_brand && strlen(mov->major_brand) >= 4)
4189         ffio_wfourcc(pb, mov->major_brand);
4190     else if (mov->mode == MODE_3GP) {
4191         ffio_wfourcc(pb, has_h264 ? "3gp6"  : "3gp4");
4192         minor =     has_h264 ?   0x100 :   0x200;
4193     } else if (mov->mode & MODE_3G2) {
4194         ffio_wfourcc(pb, has_h264 ? "3g2b"  : "3g2a");
4195         minor =     has_h264 ? 0x20000 : 0x10000;
4196     } else if (mov->mode == MODE_PSP)
4197         ffio_wfourcc(pb, "MSNV");
4198     else if (mov->mode == MODE_MP4 && mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)
4199         ffio_wfourcc(pb, "iso5"); // Required when using default-base-is-moof
4200     else if (mov->mode == MODE_MP4)
4201         ffio_wfourcc(pb, "isom");
4202     else if (mov->mode == MODE_IPOD)
4203         ffio_wfourcc(pb, has_video ? "M4V ":"M4A ");
4204     else if (mov->mode == MODE_ISM)
4205         ffio_wfourcc(pb, "isml");
4206     else if (mov->mode == MODE_F4V)
4207         ffio_wfourcc(pb, "f4v ");
4208     else
4209         ffio_wfourcc(pb, "qt  ");
4210
4211     avio_wb32(pb, minor);
4212
4213     if (mov->mode == MODE_MOV)
4214         ffio_wfourcc(pb, "qt  ");
4215     else if (mov->mode == MODE_ISM) {
4216         ffio_wfourcc(pb, "piff");
4217     } else if (!(mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)) {
4218         ffio_wfourcc(pb, "isom");
4219         ffio_wfourcc(pb, "iso2");
4220         if (has_h264)
4221             ffio_wfourcc(pb, "avc1");
4222     }
4223
4224     // We add tfdt atoms when fragmenting, signal this with the iso6 compatible
4225     // brand. This is compatible with users that don't understand tfdt.
4226     if (mov->flags & FF_MOV_FLAG_FRAGMENT && mov->mode != MODE_ISM)
4227         ffio_wfourcc(pb, "iso6");
4228
4229     if (mov->mode == MODE_3GP)
4230         ffio_wfourcc(pb, has_h264 ? "3gp6":"3gp4");
4231     else if (mov->mode & MODE_3G2)
4232         ffio_wfourcc(pb, has_h264 ? "3g2b":"3g2a");
4233     else if (mov->mode == MODE_PSP)
4234         ffio_wfourcc(pb, "MSNV");
4235     else if (mov->mode == MODE_MP4)
4236         ffio_wfourcc(pb, "mp41");
4237
4238     if (mov->flags & FF_MOV_FLAG_DASH && mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
4239         ffio_wfourcc(pb, "dash");
4240
4241     return update_size(pb, pos);
4242 }
4243
4244 static void mov_write_uuidprof_tag(AVIOContext *pb, AVFormatContext *s)
4245 {
4246     AVStream       *video_st    = s->streams[0];
4247     AVCodecParameters *video_par = s->streams[0]->codecpar;
4248     AVCodecParameters *audio_par = s->streams[1]->codecpar;
4249     int audio_rate = audio_par->sample_rate;
4250     // TODO: should be avg_frame_rate
4251     int frame_rate = ((video_st->time_base.den) * (0x10000)) / (video_st->time_base.num);
4252     int audio_kbitrate = audio_par->bit_rate / 1000;
4253     int video_kbitrate = FFMIN(video_par->bit_rate / 1000, 800 - audio_kbitrate);
4254
4255     avio_wb32(pb, 0x94); /* size */
4256     ffio_wfourcc(pb, "uuid");
4257     ffio_wfourcc(pb, "PROF");
4258
4259     avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
4260     avio_wb32(pb, 0xbb88695c);
4261     avio_wb32(pb, 0xfac9c740);
4262
4263     avio_wb32(pb, 0x0);  /* ? */
4264     avio_wb32(pb, 0x3);  /* 3 sections ? */
4265
4266     avio_wb32(pb, 0x14); /* size */
4267     ffio_wfourcc(pb, "FPRF");
4268     avio_wb32(pb, 0x0);  /* ? */
4269     avio_wb32(pb, 0x0);  /* ? */
4270     avio_wb32(pb, 0x0);  /* ? */
4271
4272     avio_wb32(pb, 0x2c);  /* size */
4273     ffio_wfourcc(pb, "APRF"); /* audio */
4274     avio_wb32(pb, 0x0);
4275     avio_wb32(pb, 0x2);   /* TrackID */
4276     ffio_wfourcc(pb, "mp4a");
4277     avio_wb32(pb, 0x20f);
4278     avio_wb32(pb, 0x0);
4279     avio_wb32(pb, audio_kbitrate);
4280     avio_wb32(pb, audio_kbitrate);
4281     avio_wb32(pb, audio_rate);
4282     avio_wb32(pb, audio_par->channels);
4283
4284     avio_wb32(pb, 0x34);  /* size */
4285     ffio_wfourcc(pb, "VPRF");   /* video */
4286     avio_wb32(pb, 0x0);
4287     avio_wb32(pb, 0x1);    /* TrackID */
4288     if (video_par->codec_id == AV_CODEC_ID_H264) {
4289         ffio_wfourcc(pb, "avc1");
4290         avio_wb16(pb, 0x014D);
4291         avio_wb16(pb, 0x0015);
4292     } else {
4293         ffio_wfourcc(pb, "mp4v");
4294         avio_wb16(pb, 0x0000);
4295         avio_wb16(pb, 0x0103);
4296     }
4297     avio_wb32(pb, 0x0);
4298     avio_wb32(pb, video_kbitrate);
4299     avio_wb32(pb, video_kbitrate);
4300     avio_wb32(pb, frame_rate);
4301     avio_wb32(pb, frame_rate);
4302     avio_wb16(pb, video_par->width);
4303     avio_wb16(pb, video_par->height);
4304     avio_wb32(pb, 0x010001); /* ? */
4305 }
4306
4307 static int mov_write_identification(AVIOContext *pb, AVFormatContext *s)
4308 {
4309     MOVMuxContext *mov = s->priv_data;
4310     int i;
4311
4312     mov_write_ftyp_tag(pb,s);
4313     if (mov->mode == MODE_PSP) {
4314         int video_streams_nb = 0, audio_streams_nb = 0, other_streams_nb = 0;
4315         for (i = 0; i < s->nb_streams; i++) {
4316             AVStream *st = s->streams[i];
4317             if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
4318                 video_streams_nb++;
4319             else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
4320                 audio_streams_nb++;
4321             else
4322                 other_streams_nb++;
4323             }
4324
4325         if (video_streams_nb != 1 || audio_streams_nb != 1 || other_streams_nb) {
4326             av_log(s, AV_LOG_ERROR, "PSP mode need one video and one audio stream\n");
4327             return AVERROR(EINVAL);
4328         }
4329         mov_write_uuidprof_tag(pb, s);
4330     }
4331     return 0;
4332 }
4333
4334 static int mov_parse_mpeg2_frame(AVPacket *pkt, uint32_t *flags)
4335 {
4336     uint32_t c = -1;
4337     int i, closed_gop = 0;
4338
4339     for (i = 0; i < pkt->size - 4; i++) {
4340         c = (c << 8) + pkt->data[i];
4341         if (c == 0x1b8) { // gop
4342             closed_gop = pkt->data[i + 4] >> 6 & 0x01;
4343         } else if (c == 0x100) { // pic
4344             int temp_ref = (pkt->data[i + 1] << 2) | (pkt->data[i + 2] >> 6);
4345             if (!temp_ref || closed_gop) // I picture is not reordered
4346                 *flags = MOV_SYNC_SAMPLE;
4347             else
4348                 *flags = MOV_PARTIAL_SYNC_SAMPLE;
4349             break;
4350         }
4351     }
4352     return 0;
4353 }
4354
4355 static void mov_parse_vc1_frame(AVPacket *pkt, MOVTrack *trk)
4356 {
4357     const uint8_t *start, *next, *end = pkt->data + pkt->size;
4358     int seq = 0, entry = 0;
4359     int key = pkt->flags & AV_PKT_FLAG_KEY;
4360     start = find_next_marker(pkt->data, end);
4361     for (next = start; next < end; start = next) {
4362         next = find_next_marker(start + 4, end);
4363         switch (AV_RB32(start)) {
4364         case VC1_CODE_SEQHDR:
4365             seq = 1;
4366             break;
4367         case VC1_CODE_ENTRYPOINT:
4368             entry = 1;
4369             break;
4370         case VC1_CODE_SLICE:
4371             trk->vc1_info.slices = 1;
4372             break;
4373         }
4374     }
4375     if (!trk->entry && trk->vc1_info.first_packet_seen)
4376         trk->vc1_info.first_frag_written = 1;
4377     if (!trk->entry && !trk->vc1_info.first_frag_written) {
4378         /* First packet in first fragment */
4379         trk->vc1_info.first_packet_seq   = seq;
4380         trk->vc1_info.first_packet_entry = entry;
4381         trk->vc1_info.first_packet_seen  = 1;
4382     } else if ((seq && !trk->vc1_info.packet_seq) ||
4383                (entry && !trk->vc1_info.packet_entry)) {
4384         int i;
4385         for (i = 0; i < trk->entry; i++)
4386             trk->cluster[i].flags &= ~MOV_SYNC_SAMPLE;
4387         trk->has_keyframes = 0;
4388         if (seq)
4389             trk->vc1_info.packet_seq = 1;
4390         if (entry)
4391             trk->vc1_info.packet_entry = 1;
4392         if (!trk->vc1_info.first_frag_written) {
4393             /* First fragment */
4394             if ((!seq   || trk->vc1_info.first_packet_seq) &&
4395                 (!entry || trk->vc1_info.first_packet_entry)) {
4396                 /* First packet had the same headers as this one, readd the
4397                  * sync sample flag. */
4398                 trk->cluster[0].flags |= MOV_SYNC_SAMPLE;
4399                 trk->has_keyframes = 1;
4400             }
4401         }
4402     }
4403     if (trk->vc1_info.packet_seq && trk->vc1_info.packet_entry)
4404         key = seq && entry;
4405     else if (trk->vc1_info.packet_seq)
4406         key = seq;
4407     else if (trk->vc1_info.packet_entry)
4408         key = entry;
4409     if (key) {
4410         trk->cluster[trk->entry].flags |= MOV_SYNC_SAMPLE;
4411         trk->has_keyframes++;
4412     }
4413 }
4414
4415 static int mov_flush_fragment_interleaving(AVFormatContext *s, MOVTrack *track)
4416 {
4417     MOVMuxContext *mov = s->priv_data;
4418     int ret, buf_size;
4419     uint8_t *buf;
4420     int i, offset;
4421
4422     if (!track->mdat_buf)
4423         return 0;
4424     if (!mov->mdat_buf) {
4425         if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0)
4426             return ret;
4427     }
4428     buf_size = avio_close_dyn_buf(track->mdat_buf, &buf);
4429     track->mdat_buf = NULL;
4430
4431     offset = avio_tell(mov->mdat_buf);
4432     avio_write(mov->mdat_buf, buf, buf_size);
4433     av_free(buf);
4434
4435     for (i = track->entries_flushed; i < track->entry; i++)
4436         track->cluster[i].pos += offset;
4437     track->entries_flushed = track->entry;
4438     return 0;
4439 }
4440
4441 static int mov_flush_fragment(AVFormatContext *s, int force)
4442 {
4443     MOVMuxContext *mov = s->priv_data;
4444     int i, first_track = -1;
4445     int64_t mdat_size = 0;
4446     int ret;
4447     int has_video = 0, starts_with_key = 0, first_video_track = 1;
4448
4449     if (!(mov->flags & FF_MOV_FLAG_FRAGMENT))
4450         return 0;
4451
4452     // Try to fill in the duration of the last packet in each stream
4453     // from queued packets in the interleave queues. If the flushing
4454     // of fragments was triggered automatically by an AVPacket, we
4455     // already have reliable info for the end of that track, but other
4456     // tracks may need to be filled in.
4457     for (i = 0; i < s->nb_streams; i++) {
4458         MOVTrack *track = &mov->tracks[i];
4459         if (!track->end_reliable) {
4460             int64_t ts_offset;
4461             const AVPacket *next = ff_interleaved_peek(s, i, &ts_offset);
4462             if (next) {
4463                 track->track_duration = next->dts - track->start_dts + ts_offset;
4464                 if (next->pts != AV_NOPTS_VALUE)
4465                     track->end_pts = next->pts;
4466                 else
4467                     track->end_pts = next->dts;
4468                 track->end_pts += ts_offset;
4469             }
4470         }
4471     }
4472
4473     for (i = 0; i < mov->nb_streams; i++) {
4474         MOVTrack *track = &mov->tracks[i];
4475         if (track->entry <= 1)
4476             continue;
4477         // Sample durations are calculated as the diff of dts values,
4478         // but for the last sample in a fragment, we don't know the dts
4479         // of the first sample in the next fragment, so we have to rely
4480         // on what was set as duration in the AVPacket. Not all callers
4481         // set this though, so we might want to replace it with an
4482         // estimate if it currently is zero.
4483         if (get_cluster_duration(track, track->entry - 1) != 0)
4484             continue;
4485         // Use the duration (i.e. dts diff) of the second last sample for
4486         // the last one. This is a wild guess (and fatal if it turns out
4487         // to be too long), but probably the best we can do - having a zero
4488         // duration is bad as well.
4489         track->track_duration += get_cluster_duration(track, track->entry - 2);
4490         track->end_pts        += get_cluster_duration(track, track->entry - 2);
4491         if (!mov->missing_duration_warned) {
4492             av_log(s, AV_LOG_WARNING,
4493                    "Estimating the duration of the last packet in a "
4494                    "fragment, consider setting the duration field in "
4495                    "AVPacket instead.\n");
4496             mov->missing_duration_warned = 1;
4497         }
4498     }
4499
4500     if (!mov->moov_written) {
4501         int64_t pos = avio_tell(s->pb);
4502         uint8_t *buf;
4503         int buf_size, moov_size;
4504
4505         for (i = 0; i < mov->nb_streams; i++)
4506             if (!mov->tracks[i].entry)
4507                 break;
4508         /* Don't write the initial moov unless all tracks have data */
4509         if (i < mov->nb_streams && !force)
4510             return 0;
4511
4512         moov_size = get_moov_size(s);
4513         for (i = 0; i < mov->nb_streams; i++)
4514             mov->tracks[i].data_offset = pos + moov_size + 8;
4515
4516         avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_HEADER);
4517         if (mov->flags & FF_MOV_FLAG_DELAY_MOOV)
4518             mov_write_identification(s->pb, s);
4519         if ((ret = mov_write_moov_tag(s->pb, mov, s)) < 0)
4520             return ret;
4521
4522         if (mov->flags & FF_MOV_FLAG_DELAY_MOOV) {
4523             if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
4524                 mov->reserved_header_pos = avio_tell(s->pb);
4525             avio_flush(s->pb);
4526             mov->moov_written = 1;
4527             return 0;
4528         }
4529
4530         buf_size = avio_close_dyn_buf(mov->mdat_buf, &buf);
4531         mov->mdat_buf = NULL;
4532         avio_wb32(s->pb, buf_size + 8);
4533         ffio_wfourcc(s->pb, "mdat");
4534         avio_write(s->pb, buf, buf_size);
4535         av_free(buf);
4536
4537         if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
4538             mov->reserved_header_pos = avio_tell(s->pb);
4539
4540         mov->moov_written = 1;
4541         mov->mdat_size = 0;
4542         for (i = 0; i < mov->nb_streams; i++) {
4543             if (mov->tracks[i].entry)
4544                 mov->tracks[i].frag_start += mov->tracks[i].start_dts +
4545                                              mov->tracks[i].track_duration -
4546                                              mov->tracks[i].cluster[0].dts;
4547             mov->tracks[i].entry = 0;
4548             mov->tracks[i].end_reliable = 0;
4549         }
4550         avio_flush(s->pb);
4551         return 0;
4552     }
4553
4554     if (mov->frag_interleave) {
4555         for (i = 0; i < mov->nb_streams; i++) {
4556             MOVTrack *track = &mov->tracks[i];
4557             int ret;
4558             if ((ret = mov_flush_fragment_interleaving(s, track)) < 0)
4559                 return ret;
4560         }
4561
4562         if (!mov->mdat_buf)
4563             return 0;
4564         mdat_size = avio_tell(mov->mdat_buf);
4565     }
4566
4567     for (i = 0; i < mov->nb_streams; i++) {
4568         MOVTrack *track = &mov->tracks[i];
4569         if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF || mov->frag_interleave)
4570             track->data_offset = 0;
4571         else
4572             track->data_offset = mdat_size;
4573         if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
4574             has_video = 1;
4575             if (first_video_track) {
4576                 if (track->entry)
4577                     starts_with_key = track->cluster[0].flags & MOV_SYNC_SAMPLE;
4578                 first_video_track = 0;
4579             }
4580         }
4581         if (!track->entry)
4582             continue;
4583         if (track->mdat_buf)
4584             mdat_size += avio_tell(track->mdat_buf);
4585         if (first_track < 0)
4586             first_track = i;
4587     }
4588
4589     if (!mdat_size)
4590         return 0;
4591
4592     avio_write_marker(s->pb,
4593                       av_rescale(mov->tracks[first_track].cluster[0].dts, AV_TIME_BASE, mov->tracks[first_track].timescale),
4594                       (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);
4595
4596     for (i = 0; i < mov->nb_streams; i++) {
4597         MOVTrack *track = &mov->tracks[i];
4598         int buf_size, write_moof = 1, moof_tracks = -1;
4599         uint8_t *buf;
4600         int64_t duration = 0;
4601
4602         if (track->entry)
4603             duration = track->start_dts + track->track_duration -
4604                        track->cluster[0].dts;
4605         if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF) {
4606             if (!track->mdat_buf)
4607                 continue;
4608             mdat_size = avio_tell(track->mdat_buf);
4609             moof_tracks = i;
4610         } else {
4611             write_moof = i == first_track;
4612         }
4613
4614         if (write_moof) {
4615             avio_flush(s->pb);
4616
4617             mov_write_moof_tag(s->pb, mov, moof_tracks, mdat_size);
4618             mov->fragments++;
4619
4620             avio_wb32(s->pb, mdat_size + 8);
4621             ffio_wfourcc(s->pb, "mdat");
4622         }
4623
4624         if (track->entry)
4625             track->frag_start += duration;
4626         track->entry = 0;
4627         track->entries_flushed = 0;
4628         track->end_reliable = 0;
4629         if (!mov->frag_interleave) {
4630             if (!track->mdat_buf)
4631                 continue;
4632             buf_size = avio_close_dyn_buf(track->mdat_buf, &buf);
4633             track->mdat_buf = NULL;
4634         } else {
4635             if (!mov->mdat_buf)
4636                 continue;
4637             buf_size = avio_close_dyn_buf(mov->mdat_buf, &buf);
4638             mov->mdat_buf = NULL;
4639         }
4640
4641         avio_write(s->pb, buf, buf_size);
4642         av_free(buf);
4643     }
4644
4645     mov->mdat_size = 0;
4646
4647     avio_flush(s->pb);
4648     return 0;
4649 }
4650
4651 static int mov_auto_flush_fragment(AVFormatContext *s, int force)
4652 {
4653     MOVMuxContext *mov = s->priv_data;
4654     int had_moov = mov->moov_written;
4655     int ret = mov_flush_fragment(s, force);
4656     if (ret < 0)
4657         return ret;
4658     // If using delay_moov, the first flush only wrote the moov,
4659     // not the actual moof+mdat pair, thus flush once again.
4660     if (!had_moov && mov->flags & FF_MOV_FLAG_DELAY_MOOV)
4661         ret = mov_flush_fragment(s, force);
4662     return ret;
4663 }
4664
4665 int ff_mov_write_packet(AVFormatContext *s, AVPacket *pkt)
4666 {
4667     MOVMuxContext *mov = s->priv_data;
4668     AVIOContext *pb = s->pb;
4669     MOVTrack *trk = &mov->tracks[pkt->stream_index];
4670     AVCodecParameters *par = trk->par;
4671     unsigned int samples_in_chunk = 0;
4672     int size = pkt->size, ret = 0;
4673     uint8_t *reformatted_data = NULL;
4674
4675     if (trk->entry) {
4676         int64_t duration = pkt->dts - trk->cluster[trk->entry - 1].dts;
4677         if (duration < 0 || duration > INT_MAX) {
4678             av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" / timestamp: %"PRId64" is out of range for mov/mp4 format\n",
4679                 duration, pkt->dts
4680             );
4681
4682             pkt->dts = trk->cluster[trk->entry - 1].dts + 1;
4683             pkt->pts = AV_NOPTS_VALUE;
4684         }
4685     } else if (pkt->dts <= INT_MIN || pkt->dts >= INT_MAX) {
4686             av_log(s, AV_LOG_ERROR, "Application provided initial timestamp: %"PRId64" is out of range for mov/mp4 format\n",
4687                 pkt->dts
4688             );
4689
4690             pkt->dts = 0;
4691             pkt->pts = AV_NOPTS_VALUE;
4692     }
4693     if (pkt->duration < 0 || pkt->duration > INT_MAX) {
4694         av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" is invalid\n", pkt->duration);
4695         return AVERROR(EINVAL);
4696     }
4697     if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
4698         int ret;
4699         if (mov->moov_written || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
4700             if (mov->frag_interleave && mov->fragments > 0) {
4701                 if (trk->entry - trk->entries_flushed >= mov->frag_interleave) {
4702                     if ((ret = mov_flush_fragment_interleaving(s, trk)) < 0)
4703                         return ret;
4704                 }
4705             }
4706
4707             if (!trk->mdat_buf) {
4708                 if ((ret = avio_open_dyn_buf(&trk->mdat_buf)) < 0)
4709                     return ret;
4710             }
4711             pb = trk->mdat_buf;
4712         } else {
4713             if (!mov->mdat_buf) {
4714                 if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0)
4715                     return ret;
4716             }
4717             pb = mov->mdat_buf;
4718         }
4719     }
4720
4721     if (par->codec_id == AV_CODEC_ID_AMR_NB) {
4722         /* We must find out how many AMR blocks there are in one packet */
4723         static const uint16_t packed_size[16] =
4724             {13, 14, 16, 18, 20, 21, 27, 32, 6, 0, 0, 0, 0, 0, 0, 1};
4725         int len = 0;
4726
4727         while (len < size && samples_in_chunk < 100) {
4728             len += packed_size[(pkt->data[len] >> 3) & 0x0F];
4729             samples_in_chunk++;
4730         }
4731         if (samples_in_chunk > 1) {
4732             av_log(s, AV_LOG_ERROR, "fatal error, input is not a single packet, implement a AVParser for it\n");
4733             return -1;
4734         }
4735     } else if (par->codec_id == AV_CODEC_ID_ADPCM_MS ||
4736                par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) {
4737         samples_in_chunk = trk->par->frame_size;
4738     } else if (trk->sample_size)
4739         samples_in_chunk = size / trk->sample_size;
4740     else
4741         samples_in_chunk = 1;
4742
4743     /* copy extradata if it exists */
4744     if (trk->vos_len == 0 && par->extradata_size > 0 &&
4745         !TAG_IS_AVCI(trk->tag) &&
4746         (par->codec_id != AV_CODEC_ID_DNXHD)) {
4747         trk->vos_len  = par->extradata_size;
4748         trk->vos_data = av_malloc(trk->vos_len);
4749         if (!trk->vos_data) {
4750             ret = AVERROR(ENOMEM);
4751             goto err;
4752         }
4753         memcpy(trk->vos_data, par->extradata, trk->vos_len);
4754     }
4755
4756     if (par->codec_id == AV_CODEC_ID_AAC && pkt->size > 2 &&
4757         (AV_RB16(pkt->data) & 0xfff0) == 0xfff0) {
4758         if (!s->streams[pkt->stream_index]->nb_frames) {
4759             av_log(s, AV_LOG_ERROR, "Malformed AAC bitstream detected: "
4760                    "use the audio bitstream filter 'aac_adtstoasc' to fix it "
4761                    "('-bsf:a aac_adtstoasc' option with ffmpeg)\n");
4762             return -1;
4763         }
4764         av_log(s, AV_LOG_WARNING, "aac bitstream error\n");
4765     }
4766     if (par->codec_id == AV_CODEC_ID_H264 && trk->vos_len > 0 && *(uint8_t *)trk->vos_data != 1 && !TAG_IS_AVCI(trk->tag)) {
4767         /* from x264 or from bytestream H.264 */
4768         /* NAL reformatting needed */
4769         if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
4770             ff_avc_parse_nal_units_buf(pkt->data, &reformatted_data,
4771                                        &size);
4772             avio_write(pb, reformatted_data, size);
4773         } else {
4774             if (mov->encryption_scheme == MOV_ENC_CENC_AES_CTR) {
4775                 size = ff_mov_cenc_avc_parse_nal_units(&trk->cenc, pb, pkt->data, size);
4776                 if (size < 0) {
4777                     ret = size;
4778                     goto err;
4779                 }
4780             } else {
4781                 size = ff_avc_parse_nal_units(pb, pkt->data, pkt->size);
4782             }
4783         }
4784     } else if (par->codec_id == AV_CODEC_ID_HEVC && trk->vos_len > 6 &&
4785                (AV_RB24(trk->vos_data) == 1 || AV_RB32(trk->vos_data) == 1)) {
4786         /* extradata is Annex B, assume the bitstream is too and convert it */
4787         if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
4788             ff_hevc_annexb2mp4_buf(pkt->data, &reformatted_data, &size, 0, NULL);
4789             avio_write(pb, reformatted_data, size);
4790         } else {
4791             size = ff_hevc_annexb2mp4(pb, pkt->data, pkt->size, 0, NULL);
4792         }
4793 #if CONFIG_AC3_PARSER
4794     } else if (par->codec_id == AV_CODEC_ID_EAC3) {
4795         size = handle_eac3(mov, pkt, trk);
4796         if (size < 0)
4797             return size;
4798         else if (!size)
4799             goto end;
4800         avio_write(pb, pkt->data, size);
4801 #endif
4802     } else {
4803         if (mov->encryption_scheme == MOV_ENC_CENC_AES_CTR) {
4804             if (par->codec_id == AV_CODEC_ID_H264 && par->extradata_size > 4) {
4805                 int nal_size_length = (par->extradata[4] & 0x3) + 1;
4806                 ret = ff_mov_cenc_avc_write_nal_units(s, &trk->cenc, nal_size_length, pb, pkt->data, size);
4807             } else {
4808                 ret = ff_mov_cenc_write_packet(&trk->cenc, pb, pkt->data, size);
4809             }
4810
4811             if (ret) {
4812                 goto err;
4813             }
4814         } else {
4815             avio_write(pb, pkt->data, size);
4816         }
4817     }
4818
4819     if ((par->codec_id == AV_CODEC_ID_DNXHD ||
4820          par->codec_id == AV_CODEC_ID_AC3) && !trk->vos_len) {
4821         /* copy frame to create needed atoms */
4822         trk->vos_len  = size;
4823         trk->vos_data = av_malloc(size);
4824         if (!trk->vos_data) {
4825             ret = AVERROR(ENOMEM);
4826             goto err;
4827         }
4828         memcpy(trk->vos_data, pkt->data, size);
4829     }
4830
4831     if (trk->entry >= trk->cluster_capacity) {
4832         unsigned new_capacity = 2 * (trk->entry + MOV_INDEX_CLUSTER_SIZE);
4833         if (av_reallocp_array(&trk->cluster, new_capacity,
4834                               sizeof(*trk->cluster))) {
4835             ret = AVERROR(ENOMEM);
4836             goto err;
4837         }
4838         trk->cluster_capacity = new_capacity;
4839     }
4840
4841     trk->cluster[trk->entry].pos              = avio_tell(pb) - size;
4842     trk->cluster[trk->entry].samples_in_chunk = samples_in_chunk;
4843     trk->cluster[trk->entry].chunkNum         = 0;
4844     trk->cluster[trk->entry].size             = size;
4845     trk->cluster[trk->entry].entries          = samples_in_chunk;
4846     trk->cluster[trk->entry].dts              = pkt->dts;
4847     if (!trk->entry && trk->start_dts != AV_NOPTS_VALUE) {
4848         if (!trk->frag_discont) {
4849             /* First packet of a new fragment. We already wrote the duration
4850              * of the last packet of the previous fragment based on track_duration,
4851              * which might not exactly match our dts. Therefore adjust the dts
4852              * of this packet to be what the previous packets duration implies. */
4853             trk->cluster[trk->entry].dts = trk->start_dts + trk->track_duration;
4854             /* We also may have written the pts and the corresponding duration
4855              * in sidx/tfrf/tfxd tags; make sure the sidx pts and duration match up with
4856              * the next fragment. This means the cts of the first sample must
4857              * be the same in all fragments, unless end_pts was updated by
4858              * the packet causing the fragment to be written. */
4859             if ((mov->flags & FF_MOV_FLAG_DASH && !(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)) ||
4860                 mov->mode == MODE_ISM)
4861                 pkt->pts = pkt->dts + trk->end_pts - trk->cluster[trk->entry].dts;
4862         } else {
4863             /* New fragment, but discontinuous from previous fragments.
4864              * Pretend the duration sum of the earlier fragments is
4865              * pkt->dts - trk->start_dts. */
4866             trk->frag_start = pkt->dts - trk->start_dts;
4867             trk->end_pts = AV_NOPTS_VALUE;
4868             trk->frag_discont = 0;
4869         }
4870     }
4871
4872     if (!trk->entry && trk->start_dts == AV_NOPTS_VALUE && !mov->use_editlist &&
4873         s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO) {
4874         /* Not using edit lists and shifting the first track to start from zero.
4875          * If the other streams start from a later timestamp, we won't be able
4876          * to signal the difference in starting time without an edit list.
4877          * Thus move the timestamp for this first sample to 0, increasing
4878          * its duration instead. */
4879         trk->cluster[trk->entry].dts = trk->start_dts = 0;
4880     }
4881     if (trk->start_dts == AV_NOPTS_VALUE) {
4882         trk->start_dts = pkt->dts;
4883         if (trk->frag_discont) {
4884             if (mov->use_editlist) {
4885                 /* Pretend the whole stream started at pts=0, with earlier fragments
4886                  * already written. If the stream started at pts=0, the duration sum
4887                  * of earlier fragments would have been pkt->pts. */
4888                 trk->frag_start = pkt->pts;
4889                 trk->start_dts  = pkt->dts - pkt->pts;
4890             } else {
4891                 /* Pretend the whole stream started at dts=0, with earlier fragments
4892                  * already written, with a duration summing up to pkt->dts. */
4893                 trk->frag_start = pkt->dts;
4894                 trk->start_dts  = 0;
4895             }
4896             trk->frag_discont = 0;
4897         } else if (pkt->dts && mov->moov_written)
4898             av_log(s, AV_LOG_WARNING,
4899                    "Track %d starts with a nonzero dts %"PRId64", while the moov "
4900                    "already has been written. Set the delay_moov flag to handle "
4901                    "this case.\n",
4902                    pkt->stream_index, pkt->dts);
4903     }
4904     trk->track_duration = pkt->dts - trk->start_dts + pkt->duration;
4905     trk->last_sample_is_subtitle_end = 0;
4906
4907     if (pkt->pts == AV_NOPTS_VALUE) {
4908         av_log(s, AV_LOG_WARNING, "pts has no value\n");
4909         pkt->pts = pkt->dts;
4910     }
4911     if (pkt->dts != pkt->pts)
4912         trk->flags |= MOV_TRACK_CTTS;
4913     trk->cluster[trk->entry].cts   = pkt->pts - pkt->dts;
4914     trk->cluster[trk->entry].flags = 0;
4915     if (trk->start_cts == AV_NOPTS_VALUE)
4916         trk->start_cts = pkt->pts - pkt->dts;
4917     if (trk->end_pts == AV_NOPTS_VALUE)
4918         trk->end_pts = trk->cluster[trk->entry].dts +
4919                        trk->cluster[trk->entry].cts + pkt->duration;
4920     else
4921         trk->end_pts = FFMAX(trk->end_pts, trk->cluster[trk->entry].dts +
4922                                            trk->cluster[trk->entry].cts +
4923                                            pkt->duration);
4924
4925     if (par->codec_id == AV_CODEC_ID_VC1) {
4926         mov_parse_vc1_frame(pkt, trk);
4927     } else if (pkt->flags & AV_PKT_FLAG_KEY) {
4928         if (mov->mode == MODE_MOV && par->codec_id == AV_CODEC_ID_MPEG2VIDEO &&
4929             trk->entry > 0) { // force sync sample for the first key frame
4930             mov_parse_mpeg2_frame(pkt, &trk->cluster[trk->entry].flags);
4931             if (trk->cluster[trk->entry].flags & MOV_PARTIAL_SYNC_SAMPLE)
4932                 trk->flags |= MOV_TRACK_STPS;
4933         } else {
4934             trk->cluster[trk->entry].flags = MOV_SYNC_SAMPLE;
4935         }
4936         if (trk->cluster[trk->entry].flags & MOV_SYNC_SAMPLE)
4937             trk->has_keyframes++;
4938     }
4939     trk->entry++;
4940     trk->sample_count += samples_in_chunk;
4941     mov->mdat_size    += size;
4942
4943     if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams)
4944         ff_mov_add_hinted_packet(s, pkt, trk->hint_track, trk->entry,
4945                                  reformatted_data, size);
4946
4947 end:
4948 err:
4949
4950     av_free(reformatted_data);
4951     return ret;
4952 }
4953
4954 static int mov_write_single_packet(AVFormatContext *s, AVPacket *pkt)
4955 {
4956         MOVMuxContext *mov = s->priv_data;
4957         MOVTrack *trk = &mov->tracks[pkt->stream_index];
4958         AVCodecParameters *par = trk->par;
4959         int64_t frag_duration = 0;
4960         int size = pkt->size;
4961
4962         if (mov->flags & FF_MOV_FLAG_FRAG_DISCONT) {
4963             int i;
4964             for (i = 0; i < s->nb_streams; i++)
4965                 mov->tracks[i].frag_discont = 1;
4966             mov->flags &= ~FF_MOV_FLAG_FRAG_DISCONT;
4967         }
4968
4969         if (!pkt->size) {
4970             if (trk->start_dts == AV_NOPTS_VALUE && trk->frag_discont) {
4971                 trk->start_dts = pkt->dts;
4972                 if (pkt->pts != AV_NOPTS_VALUE)
4973                     trk->start_cts = pkt->pts - pkt->dts;
4974                 else
4975                     trk->start_cts = 0;
4976             }
4977
4978             if (trk->par->codec_id == AV_CODEC_ID_MP4ALS) {
4979                 int side_size = 0;
4980                 uint8_t *side = av_packet_get_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA, &side_size);
4981                 if (side && side_size > 0 && (side_size != par->extradata_size || memcmp(side, par->extradata, side_size))) {
4982                     void *newextra = av_mallocz(side_size + AV_INPUT_BUFFER_PADDING_SIZE);
4983                     if (!newextra)
4984                         return AVERROR(ENOMEM);
4985                     av_free(par->extradata);
4986                     par->extradata = newextra;
4987                     memcpy(par->extradata, side, side_size);
4988                     par->extradata_size = side_size;
4989                     mov->need_rewrite_extradata = 1;
4990                 }
4991             }
4992
4993             return 0;             /* Discard 0 sized packets */
4994         }
4995
4996         if (trk->entry && pkt->stream_index < s->nb_streams)
4997             frag_duration = av_rescale_q(pkt->dts - trk->cluster[0].dts,
4998                                          s->streams[pkt->stream_index]->time_base,
4999                                          AV_TIME_BASE_Q);
5000         if ((mov->max_fragment_duration &&
5001              frag_duration >= mov->max_fragment_duration) ||
5002              (mov->max_fragment_size && mov->mdat_size + size >= mov->max_fragment_size) ||
5003              (mov->flags & FF_MOV_FLAG_FRAG_KEYFRAME &&
5004               par->codec_type == AVMEDIA_TYPE_VIDEO &&
5005               trk->entry && pkt->flags & AV_PKT_FLAG_KEY)) {
5006             if (frag_duration >= mov->min_fragment_duration) {
5007                 // Set the duration of this track to line up with the next
5008                 // sample in this track. This avoids relying on AVPacket
5009                 // duration, but only helps for this particular track, not
5010                 // for the other ones that are flushed at the same time.
5011                 trk->track_duration = pkt->dts - trk->start_dts;
5012                 if (pkt->pts != AV_NOPTS_VALUE)
5013                     trk->end_pts = pkt->pts;
5014                 else
5015                     trk->end_pts = pkt->dts;
5016                 trk->end_reliable = 1;
5017                 mov_auto_flush_fragment(s, 0);
5018             }
5019         }
5020
5021         return ff_mov_write_packet(s, pkt);
5022 }
5023
5024 static int mov_write_subtitle_end_packet(AVFormatContext *s,
5025                                          int stream_index,
5026                                          int64_t dts) {
5027     AVPacket end;
5028     uint8_t data[2] = {0};
5029     int ret;
5030
5031     av_init_packet(&end);
5032     end.size = sizeof(data);
5033     end.data = data;
5034     end.pts = dts;
5035     end.dts = dts;
5036     end.duration = 0;
5037     end.stream_index = stream_index;
5038
5039     ret = mov_write_single_packet(s, &end);
5040     av_packet_unref(&end);
5041
5042     return ret;
5043 }
5044
5045 static int mov_write_packet(AVFormatContext *s, AVPacket *pkt)
5046 {
5047     if (!pkt) {
5048         mov_flush_fragment(s, 1);
5049         return 1;
5050     } else {
5051         int i;
5052         MOVMuxContext *mov = s->priv_data;
5053         MOVTrack *trk = &mov->tracks[pkt->stream_index];
5054
5055         if (!pkt->size)
5056             return mov_write_single_packet(s, pkt); /* Passthrough. */
5057
5058         /*
5059          * Subtitles require special handling.
5060          *
5061          * 1) For full complaince, every track must have a sample at
5062          * dts == 0, which is rarely true for subtitles. So, as soon
5063          * as we see any packet with dts > 0, write an empty subtitle
5064          * at dts == 0 for any subtitle track with no samples in it.
5065          *
5066          * 2) For each subtitle track, check if the current packet's
5067          * dts is past the duration of the last subtitle sample. If
5068          * so, we now need to write an end sample for that subtitle.
5069          *
5070          * This must be done conditionally to allow for subtitles that
5071          * immediately replace each other, in which case an end sample
5072          * is not needed, and is, in fact, actively harmful.
5073          *
5074          * 3) See mov_write_trailer for how the final end sample is
5075          * handled.
5076          */
5077         for (i = 0; i < mov->nb_streams; i++) {
5078             MOVTrack *trk = &mov->tracks[i];
5079             int ret;
5080
5081             if (trk->par->codec_id == AV_CODEC_ID_MOV_TEXT &&
5082                 trk->track_duration < pkt->dts &&
5083                 (trk->entry == 0 || !trk->last_sample_is_subtitle_end)) {
5084                 ret = mov_write_subtitle_end_packet(s, i, trk->track_duration);
5085                 if (ret < 0) return ret;
5086                 trk->last_sample_is_subtitle_end = 1;
5087             }
5088         }
5089
5090         if (trk->mode == MODE_MOV && trk->par->codec_type == AVMEDIA_TYPE_VIDEO) {
5091             AVPacket *opkt = pkt;
5092             int reshuffle_ret, ret;
5093             if (trk->is_unaligned_qt_rgb) {
5094                 int64_t bpc = trk->par->bits_per_coded_sample != 15 ? trk->par->bits_per_coded_sample : 16;
5095                 int expected_stride = ((trk->par->width * bpc + 15) >> 4)*2;
5096                 reshuffle_ret = ff_reshuffle_raw_rgb(s, &pkt, trk->par, expected_stride);
5097                 if (reshuffle_ret < 0)
5098                     return reshuffle_ret;
5099             } else
5100                 reshuffle_ret = 0;
5101             if (trk->par->format == AV_PIX_FMT_PAL8 && !trk->pal_done) {
5102                 ret = ff_get_packet_palette(s, opkt, reshuffle_ret, trk->palette);
5103                 if (ret < 0)
5104                     goto fail;
5105                 if (ret)
5106                     trk->pal_done++;
5107             } else if (trk->par->codec_id == AV_CODEC_ID_RAWVIDEO &&
5108                        (trk->par->format == AV_PIX_FMT_GRAY8 ||
5109                        trk->par->format == AV_PIX_FMT_MONOBLACK)) {
5110                 for (i = 0; i < pkt->size; i++)
5111                     pkt->data[i] = ~pkt->data[i];
5112             }
5113             if (reshuffle_ret) {
5114                 ret = mov_write_single_packet(s, pkt);
5115 fail:
5116                 if (reshuffle_ret)
5117                     av_packet_free(&pkt);
5118                 return ret;
5119             }
5120         }
5121
5122         return mov_write_single_packet(s, pkt);
5123     }
5124 }
5125
5126 // QuickTime chapters involve an additional text track with the chapter names
5127 // as samples, and a tref pointing from the other tracks to the chapter one.
5128 static int mov_create_chapter_track(AVFormatContext *s, int tracknum)
5129 {
5130     AVIOContext *pb;
5131
5132     MOVMuxContext *mov = s->priv_data;
5133     MOVTrack *track = &mov->tracks[tracknum];
5134     AVPacket pkt = { .stream_index = tracknum, .flags = AV_PKT_FLAG_KEY };
5135     int i, len;
5136
5137     track->mode = mov->mode;
5138     track->tag = MKTAG('t','e','x','t');
5139     track->timescale = MOV_TIMESCALE;
5140     track->par = avcodec_parameters_alloc();
5141     if (!track->par)
5142         return AVERROR(ENOMEM);
5143     track->par->codec_type = AVMEDIA_TYPE_SUBTITLE;
5144 #if 0
5145     // These properties are required to make QT recognize the chapter track
5146     uint8_t chapter_properties[43] = { 0, 0, 0, 0, 0, 0, 0, 1, };
5147     if (ff_alloc_extradata(track->par, sizeof(chapter_properties)))
5148         return AVERROR(ENOMEM);
5149     memcpy(track->par->extradata, chapter_properties, sizeof(chapter_properties));
5150 #else
5151     if (avio_open_dyn_buf(&pb) >= 0) {
5152         int size;
5153         uint8_t *buf;
5154
5155         /* Stub header (usually for Quicktime chapter track) */
5156         // TextSampleEntry
5157         avio_wb32(pb, 0x01); // displayFlags
5158         avio_w8(pb, 0x00);   // horizontal justification
5159         avio_w8(pb, 0x00);   // vertical justification
5160         avio_w8(pb, 0x00);   // bgColourRed
5161         avio_w8(pb, 0x00);   // bgColourGreen
5162         avio_w8(pb, 0x00);   // bgColourBlue
5163         avio_w8(pb, 0x00);   // bgColourAlpha
5164         // BoxRecord
5165         avio_wb16(pb, 0x00); // defTextBoxTop
5166         avio_wb16(pb, 0x00); // defTextBoxLeft
5167         avio_wb16(pb, 0x00); // defTextBoxBottom
5168         avio_wb16(pb, 0x00); // defTextBoxRight
5169         // StyleRecord
5170         avio_wb16(pb, 0x00); // startChar
5171         avio_wb16(pb, 0x00); // endChar
5172         avio_wb16(pb, 0x01); // fontID
5173         avio_w8(pb, 0x00);   // fontStyleFlags
5174         avio_w8(pb, 0x00);   // fontSize
5175         avio_w8(pb, 0x00);   // fgColourRed
5176         avio_w8(pb, 0x00);   // fgColourGreen
5177         avio_w8(pb, 0x00);   // fgColourBlue
5178         avio_w8(pb, 0x00);   // fgColourAlpha
5179         // FontTableBox
5180         avio_wb32(pb, 0x0D); // box size
5181         ffio_wfourcc(pb, "ftab"); // box atom name
5182         avio_wb16(pb, 0x01); // entry count
5183         // FontRecord
5184         avio_wb16(pb, 0x01); // font ID
5185         avio_w8(pb, 0x00);   // font name length
5186
5187         if ((size = avio_close_dyn_buf(pb, &buf)) > 0) {
5188             track->par->extradata = buf;
5189             track->par->extradata_size = size;
5190         } else {
5191             av_freep(&buf);
5192         }
5193     }
5194 #endif
5195
5196     for (i = 0; i < s->nb_chapters; i++) {
5197         AVChapter *c = s->chapters[i];
5198         AVDictionaryEntry *t;
5199
5200         int64_t end = av_rescale_q(c->end, c->time_base, (AVRational){1,MOV_TIMESCALE});
5201         pkt.pts = pkt.dts = av_rescale_q(c->start, c->time_base, (AVRational){1,MOV_TIMESCALE});
5202         pkt.duration = end - pkt.dts;
5203
5204         if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
5205             static const char encd[12] = {
5206                 0x00, 0x00, 0x00, 0x0C,
5207                 'e',  'n',  'c',  'd',
5208                 0x00, 0x00, 0x01, 0x00 };
5209             len      = strlen(t->value);
5210             pkt.size = len + 2 + 12;
5211             pkt.data = av_malloc(pkt.size);
5212             if (!pkt.data)
5213                 return AVERROR(ENOMEM);
5214             AV_WB16(pkt.data, len);
5215             memcpy(pkt.data + 2, t->value, len);
5216             memcpy(pkt.data + len + 2, encd, sizeof(encd));
5217             ff_mov_write_packet(s, &pkt);
5218             av_freep(&pkt.data);
5219         }
5220     }
5221
5222     return 0;
5223 }
5224
5225
5226 static int mov_check_timecode_track(AVFormatContext *s, AVTimecode *tc, int src_index, const char *tcstr)
5227 {
5228     int ret;
5229
5230     /* compute the frame number */
5231     ret = av_timecode_init_from_string(tc, find_fps(s,  s->streams[src_index]), tcstr, s);
5232     return ret;
5233 }
5234
5235 static int mov_create_timecode_track(AVFormatContext *s, int index, int src_index, AVTimecode tc)
5236 {
5237     int ret;
5238     MOVMuxContext *mov  = s->priv_data;
5239     MOVTrack *track     = &mov->tracks[index];
5240     AVStream *src_st    = s->streams[src_index];
5241     AVPacket pkt    = {.stream_index = index, .flags = AV_PKT_FLAG_KEY, .size = 4};
5242     AVRational rate = find_fps(s, src_st);
5243
5244     /* tmcd track based on video stream */
5245     track->mode      = mov->mode;
5246     track->tag       = MKTAG('t','m','c','d');
5247     track->src_track = src_index;
5248     track->timescale = mov->tracks[src_index].timescale;
5249     if (tc.flags & AV_TIMECODE_FLAG_DROPFRAME)
5250         track->timecode_flags |= MOV_TIMECODE_FLAG_DROPFRAME;
5251
5252     /* set st to src_st for metadata access*/
5253     track->st = src_st;
5254
5255     /* encode context: tmcd data stream */
5256     track->par = avcodec_parameters_alloc();
5257     if (!track->par)
5258         return AVERROR(ENOMEM);
5259     track->par->codec_type = AVMEDIA_TYPE_DATA;
5260     track->par->codec_tag  = track->tag;
5261     track->st->avg_frame_rate = av_inv_q(rate);
5262
5263     /* the tmcd track just contains one packet with the frame number */
5264     pkt.data = av_malloc(pkt.size);
5265     if (!pkt.data)
5266         return AVERROR(ENOMEM);
5267     AV_WB32(pkt.data, tc.start);
5268     ret = ff_mov_write_packet(s, &pkt);
5269     av_free(pkt.data);
5270     return ret;
5271 }
5272
5273 /*
5274  * st->disposition controls the "enabled" flag in the tkhd tag.
5275  * QuickTime will not play a track if it is not enabled.  So make sure
5276  * that one track of each type (audio, video, subtitle) is enabled.
5277  *
5278  * Subtitles are special.  For audio and video, setting "enabled" also
5279  * makes the track "default" (i.e. it is rendered when played). For
5280  * subtitles, an "enabled" subtitle is not rendered by default, but
5281  * if no subtitle is enabled, the subtitle menu in QuickTime will be
5282  * empty!
5283  */
5284 static void enable_tracks(AVFormatContext *s)
5285 {
5286     MOVMuxContext *mov = s->priv_data;
5287     int i;
5288     int enabled[AVMEDIA_TYPE_NB];
5289     int first[AVMEDIA_TYPE_NB];
5290
5291     for (i = 0; i < AVMEDIA_TYPE_NB; i++) {
5292         enabled[i] = 0;
5293         first[i] = -1;
5294     }
5295
5296     for (i = 0; i < s->nb_streams; i++) {
5297         AVStream *st = s->streams[i];
5298
5299         if (st->codecpar->codec_type <= AVMEDIA_TYPE_UNKNOWN ||
5300             st->codecpar->codec_type >= AVMEDIA_TYPE_NB)
5301             continue;
5302
5303         if (first[st->codecpar->codec_type] < 0)
5304             first[st->codecpar->codec_type] = i;
5305         if (st->disposition & AV_DISPOSITION_DEFAULT) {
5306             mov->tracks[i].flags |= MOV_TRACK_ENABLED;
5307             enabled[st->codecpar->codec_type]++;
5308         }
5309     }
5310
5311     for (i = 0; i < AVMEDIA_TYPE_NB; i++) {
5312         switch (i) {
5313         case AVMEDIA_TYPE_VIDEO:
5314         case AVMEDIA_TYPE_AUDIO:
5315         case AVMEDIA_TYPE_SUBTITLE:
5316             if (enabled[i] > 1)
5317                 mov->per_stream_grouping = 1;
5318             if (!enabled[i] && first[i] >= 0)
5319                 mov->tracks[first[i]].flags |= MOV_TRACK_ENABLED;
5320             break;
5321         }
5322     }
5323 }
5324
5325 static void mov_free(AVFormatContext *s)
5326 {
5327     MOVMuxContext *mov = s->priv_data;
5328     int i;
5329
5330     if (mov->chapter_track) {
5331         if (mov->tracks[mov->chapter_track].par)
5332             av_freep(&mov->tracks[mov->chapter_track].par->extradata);
5333         av_freep(&mov->tracks[mov->chapter_track].par);
5334     }
5335
5336     for (i = 0; i < mov->nb_streams; i++) {
5337         if (mov->tracks[i].tag == MKTAG('r','t','p',' '))
5338             ff_mov_close_hinting(&mov->tracks[i]);
5339         else if (mov->tracks[i].tag == MKTAG('t','m','c','d') && mov->nb_meta_tmcd)
5340             av_freep(&mov->tracks[i].par);
5341         av_freep(&mov->tracks[i].cluster);
5342         av_freep(&mov->tracks[i].frag_info);
5343
5344         if (mov->tracks[i].vos_len)
5345             av_freep(&mov->tracks[i].vos_data);
5346
5347         ff_mov_cenc_free(&mov->tracks[i].cenc);
5348     }
5349
5350     av_freep(&mov->tracks);
5351 }
5352
5353 static uint32_t rgb_to_yuv(uint32_t rgb)
5354 {
5355     uint8_t r, g, b;
5356     int y, cb, cr;
5357
5358     r = (rgb >> 16) & 0xFF;
5359     g = (rgb >>  8) & 0xFF;
5360     b = (rgb      ) & 0xFF;
5361
5362     y  = av_clip_uint8(( 16000 +  257 * r + 504 * g +  98 * b)/1000);
5363     cb = av_clip_uint8((128000 -  148 * r - 291 * g + 439 * b)/1000);
5364     cr = av_clip_uint8((128000 +  439 * r - 368 * g -  71 * b)/1000);
5365
5366     return (y << 16) | (cr << 8) | cb;
5367 }
5368
5369 static int mov_create_dvd_sub_decoder_specific_info(MOVTrack *track,
5370                                                     AVStream *st)
5371 {
5372     int i, width = 720, height = 480;
5373     int have_palette = 0, have_size = 0;
5374     uint32_t palette[16];
5375     char *cur = st->codecpar->extradata;
5376
5377     while (cur && *cur) {
5378         if (strncmp("palette:", cur, 8) == 0) {
5379             int i, count;
5380             count = sscanf(cur + 8,
5381                 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
5382                 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
5383                 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
5384                 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32"",
5385                 &palette[ 0], &palette[ 1], &palette[ 2], &palette[ 3],
5386                 &palette[ 4], &palette[ 5], &palette[ 6], &palette[ 7],
5387                 &palette[ 8], &palette[ 9], &palette[10], &palette[11],
5388                 &palette[12], &palette[13], &palette[14], &palette[15]);
5389
5390             for (i = 0; i < count; i++) {
5391                 palette[i] = rgb_to_yuv(palette[i]);
5392             }
5393             have_palette = 1;
5394         } else if (!strncmp("size:", cur, 5)) {
5395             sscanf(cur + 5, "%dx%d", &width, &height);
5396             have_size = 1;
5397         }
5398         if (have_palette && have_size)
5399             break;
5400         cur += strcspn(cur, "\n\r");
5401         cur += strspn(cur, "\n\r");
5402     }
5403     if (have_palette) {
5404         track->vos_data = av_malloc(16*4);
5405         if (!track->vos_data)
5406             return AVERROR(ENOMEM);
5407         for (i = 0; i < 16; i++) {
5408             AV_WB32(track->vos_data + i * 4, palette[i]);
5409         }
5410         track->vos_len = 16 * 4;
5411     }
5412     st->codecpar->width = width;
5413     st->codecpar->height = track->height = height;
5414
5415     return 0;
5416 }
5417
5418 static int mov_write_header(AVFormatContext *s)
5419 {
5420     AVIOContext *pb = s->pb;
5421     MOVMuxContext *mov = s->priv_data;
5422     AVDictionaryEntry *t, *global_tcr = av_dict_get(s->metadata, "timecode", NULL, 0);
5423     int i, ret, hint_track = 0, tmcd_track = 0;
5424
5425     mov->fc = s;
5426
5427     /* Default mode == MP4 */
5428     mov->mode = MODE_MP4;
5429
5430     if (s->oformat) {
5431         if (!strcmp("3gp", s->oformat->name)) mov->mode = MODE_3GP;
5432         else if (!strcmp("3g2", s->oformat->name)) mov->mode = MODE_3GP|MODE_3G2;
5433         else if (!strcmp("mov", s->oformat->name)) mov->mode = MODE_MOV;
5434         else if (!strcmp("psp", s->oformat->name)) mov->mode = MODE_PSP;
5435         else if (!strcmp("ipod",s->oformat->name)) mov->mode = MODE_IPOD;
5436         else if (!strcmp("ismv",s->oformat->name)) mov->mode = MODE_ISM;
5437         else if (!strcmp("f4v", s->oformat->name)) mov->mode = MODE_F4V;
5438     }
5439
5440     if (mov->flags & FF_MOV_FLAG_DELAY_MOOV)
5441         mov->flags |= FF_MOV_FLAG_EMPTY_MOOV;
5442
5443     /* Set the FRAGMENT flag if any of the fragmentation methods are
5444      * enabled. */
5445     if (mov->max_fragment_duration || mov->max_fragment_size ||
5446         mov->flags & (FF_MOV_FLAG_EMPTY_MOOV |
5447                       FF_MOV_FLAG_FRAG_KEYFRAME |
5448                       FF_MOV_FLAG_FRAG_CUSTOM))
5449         mov->flags |= FF_MOV_FLAG_FRAGMENT;
5450
5451     /* Set other implicit flags immediately */
5452     if (mov->mode == MODE_ISM)
5453         mov->flags |= FF_MOV_FLAG_EMPTY_MOOV | FF_MOV_FLAG_SEPARATE_MOOF |
5454                       FF_MOV_FLAG_FRAGMENT;
5455     if (mov->flags & FF_MOV_FLAG_DASH)
5456         mov->flags |= FF_MOV_FLAG_FRAGMENT | FF_MOV_FLAG_EMPTY_MOOV |
5457                       FF_MOV_FLAG_DEFAULT_BASE_MOOF;
5458
5459     if (mov->flags & FF_MOV_FLAG_FASTSTART) {
5460         mov->reserved_moov_size = -1;
5461     }
5462
5463     if (mov->use_editlist < 0) {
5464         mov->use_editlist = 1;
5465         if (mov->flags & FF_MOV_FLAG_FRAGMENT &&
5466             !(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
5467             // If we can avoid needing an edit list by shifting the
5468             // tracks, prefer that over (trying to) write edit lists
5469             // in fragmented output.
5470             if (s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO ||
5471                 s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO)
5472                 mov->use_editlist = 0;
5473         }
5474     }
5475     if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV &&
5476         !(mov->flags & FF_MOV_FLAG_DELAY_MOOV) && mov->use_editlist)
5477         av_log(s, AV_LOG_WARNING, "No meaningful edit list will be written when using empty_moov without delay_moov\n");
5478
5479     if (!mov->use_editlist && s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO)
5480         s->avoid_negative_ts = AVFMT_AVOID_NEG_TS_MAKE_ZERO;
5481
5482     /* Clear the omit_tfhd_offset flag if default_base_moof is set;
5483      * if the latter is set that's enough and omit_tfhd_offset doesn't
5484      * add anything extra on top of that. */
5485     if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET &&
5486         mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)
5487         mov->flags &= ~FF_MOV_FLAG_OMIT_TFHD_OFFSET;
5488
5489     if (mov->frag_interleave &&
5490         mov->flags & (FF_MOV_FLAG_OMIT_TFHD_OFFSET | FF_MOV_FLAG_SEPARATE_MOOF)) {
5491         av_log(s, AV_LOG_ERROR,
5492                "Sample interleaving in fragments is mutually exclusive with "
5493                "omit_tfhd_offset and separate_moof\n");
5494         return AVERROR(EINVAL);
5495     }
5496
5497     /* Non-seekable output is ok if using fragmentation. If ism_lookahead
5498      * is enabled, we don't support non-seekable output at all. */
5499     if (!s->pb->seekable &&
5500         (!(mov->flags & FF_MOV_FLAG_FRAGMENT) || mov->ism_lookahead)) {
5501         av_log(s, AV_LOG_ERROR, "muxer does not support non seekable output\n");
5502         return AVERROR(EINVAL);
5503     }
5504
5505     if (!(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
5506         if ((ret = mov_write_identification(pb, s)) < 0)
5507             return ret;
5508     }
5509
5510     mov->nb_streams = s->nb_streams;
5511     if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters)
5512         mov->chapter_track = mov->nb_streams++;
5513
5514     if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
5515         /* Add hint tracks for each audio and video stream */
5516         hint_track = mov->nb_streams;
5517         for (i = 0; i < s->nb_streams; i++) {
5518             AVStream *st = s->streams[i];
5519             if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ||
5520                 st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
5521                 mov->nb_streams++;
5522             }
5523         }
5524     }
5525
5526     if (mov->mode == MODE_MOV || mov->mode == MODE_MP4) {
5527         tmcd_track = mov->nb_streams;
5528
5529         /* +1 tmcd track for each video stream with a timecode */
5530         for (i = 0; i < s->nb_streams; i++) {
5531             AVStream *st = s->streams[i];
5532             t = global_tcr;
5533             if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
5534                 (t || (t=av_dict_get(st->metadata, "timecode", NULL, 0)))) {
5535                 AVTimecode tc;
5536                 ret = mov_check_timecode_track(s, &tc, i, t->value);
5537                 if (ret >= 0)
5538                     mov->nb_meta_tmcd++;
5539             }
5540         }
5541
5542         /* check if there is already a tmcd track to remux */
5543         if (mov->nb_meta_tmcd) {
5544             for (i = 0; i < s->nb_streams; i++) {
5545                 AVStream *st = s->streams[i];
5546                 if (st->codecpar->codec_tag == MKTAG('t','m','c','d')) {
5547                     av_log(s, AV_LOG_WARNING, "You requested a copy of the original timecode track "
5548                            "so timecode metadata are now ignored\n");
5549                     mov->nb_meta_tmcd = 0;
5550                 }
5551             }
5552         }
5553
5554         mov->nb_streams += mov->nb_meta_tmcd;
5555     }
5556
5557     // Reserve an extra stream for chapters for the case where chapters
5558     // are written in the trailer
5559     mov->tracks = av_mallocz_array((mov->nb_streams + 1), sizeof(*mov->tracks));
5560     if (!mov->tracks)
5561         return AVERROR(ENOMEM);
5562
5563     if (mov->encryption_scheme_str != NULL && strcmp(mov->encryption_scheme_str, "none") != 0) {
5564         if (strcmp(mov->encryption_scheme_str, "cenc-aes-ctr") == 0) {
5565             mov->encryption_scheme = MOV_ENC_CENC_AES_CTR;
5566
5567             if (mov->encryption_key_len != AES_CTR_KEY_SIZE) {
5568                 av_log(s, AV_LOG_ERROR, "Invalid encryption key len %d expected %d\n",
5569                     mov->encryption_key_len, AES_CTR_KEY_SIZE);
5570                 ret = AVERROR(EINVAL);
5571                 goto error;
5572             }
5573
5574             if (mov->encryption_kid_len != CENC_KID_SIZE) {
5575                 av_log(s, AV_LOG_ERROR, "Invalid encryption kid len %d expected %d\n",
5576                     mov->encryption_kid_len, CENC_KID_SIZE);
5577                 ret = AVERROR(EINVAL);
5578                 goto error;
5579             }
5580         } else {
5581             av_log(s, AV_LOG_ERROR, "unsupported encryption scheme %s\n",
5582                 mov->encryption_scheme_str);
5583             ret = AVERROR(EINVAL);
5584             goto error;
5585         }
5586     }
5587
5588     for (i = 0; i < s->nb_streams; i++) {
5589         AVStream *st= s->streams[i];
5590         MOVTrack *track= &mov->tracks[i];
5591         AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0);
5592
5593         track->st  = st;
5594         track->par = st->codecpar;
5595         track->language = ff_mov_iso639_to_lang(lang?lang->value:"und", mov->mode!=MODE_MOV);
5596         if (track->language < 0)
5597             track->language = 0;
5598         track->mode = mov->mode;
5599         track->tag  = mov_find_codec_tag(s, track);
5600         if (!track->tag) {
5601             av_log(s, AV_LOG_ERROR, "Could not find tag for codec %s in stream #%d, "
5602                    "codec not currently supported in container\n",
5603                    avcodec_get_name(st->codecpar->codec_id), i);
5604             ret = AVERROR(EINVAL);
5605             goto error;
5606         }
5607         /* If hinting of this track is enabled by a later hint track,
5608          * this is updated. */
5609         track->hint_track = -1;
5610         track->start_dts  = AV_NOPTS_VALUE;
5611         track->start_cts  = AV_NOPTS_VALUE;
5612         track->end_pts    = AV_NOPTS_VALUE;
5613         if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
5614             if (track->tag == MKTAG('m','x','3','p') || track->tag == MKTAG('m','x','3','n') ||
5615                 track->tag == MKTAG('m','x','4','p') || track->tag == MKTAG('m','x','4','n') ||
5616                 track->tag == MKTAG('m','x','5','p') || track->tag == MKTAG('m','x','5','n')) {
5617                 if (st->codecpar->width != 720 || (st->codecpar->height != 608 && st->codecpar->height != 512)) {
5618                     av_log(s, AV_LOG_ERROR, "D-10/IMX must use 720x608 or 720x512 video resolution\n");
5619                     ret = AVERROR(EINVAL);
5620                     goto error;
5621                 }
5622                 track->height = track->tag >> 24 == 'n' ? 486 : 576;
5623             }
5624             if (mov->video_track_timescale) {
5625                 track->timescale = mov->video_track_timescale;
5626             } else {
5627                 track->timescale = st->time_base.den;
5628                 while(track->timescale < 10000)
5629                     track->timescale *= 2;
5630             }
5631             if (st->codecpar->width > 65535 || st->codecpar->height > 65535) {
5632                 av_log(s, AV_LOG_ERROR, "Resolution %dx%d too large for mov/mp4\n", st->codecpar->width, st->codecpar->height);
5633                 ret = AVERROR(EINVAL);
5634                 goto error;
5635             }
5636             if (track->mode == MODE_MOV && track->timescale > 100000)
5637                 av_log(s, AV_LOG_WARNING,
5638                        "WARNING codec timebase is very high. If duration is too long,\n"
5639                        "file may not be playable by quicktime. Specify a shorter timebase\n"
5640                        "or choose different container.\n");
5641             if (track->mode == MODE_MOV &&
5642                 track->par->codec_id == AV_CODEC_ID_RAWVIDEO &&
5643                 track->tag == MKTAG('r','a','w',' ')) {
5644                 enum AVPixelFormat pix_fmt = track->par->format;
5645                 if (pix_fmt == AV_PIX_FMT_NONE && track->par->bits_per_coded_sample == 1)
5646                     pix_fmt = AV_PIX_FMT_MONOWHITE;
5647                 track->is_unaligned_qt_rgb =
5648                         pix_fmt == AV_PIX_FMT_RGB24 ||
5649                         pix_fmt == AV_PIX_FMT_BGR24 ||
5650                         pix_fmt == AV_PIX_FMT_PAL8 ||
5651                         pix_fmt == AV_PIX_FMT_GRAY8 ||
5652                         pix_fmt == AV_PIX_FMT_MONOWHITE ||
5653                         pix_fmt == AV_PIX_FMT_MONOBLACK;
5654             }
5655             if (track->mode == MODE_MP4 &&
5656                 track->par->codec_id == AV_CODEC_ID_VP9) {
5657                 if (s->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
5658                     av_log(s, AV_LOG_ERROR,
5659                            "VP9 in MP4 support is experimental, add "
5660                            "'-strict %d' if you want to use it.\n",
5661                            FF_COMPLIANCE_EXPERIMENTAL);
5662                     ret = AVERROR_EXPERIMENTAL;
5663                     goto error;
5664                 }
5665             }
5666         } else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
5667             track->timescale = st->codecpar->sample_rate;
5668             if (!st->codecpar->frame_size && !av_get_bits_per_sample(st->codecpar->codec_id)) {
5669                 av_log(s, AV_LOG_WARNING, "track %d: codec frame size is not set\n", i);
5670                 track->audio_vbr = 1;
5671             }else if (st->codecpar->codec_id == AV_CODEC_ID_ADPCM_MS ||
5672                      st->codecpar->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
5673                      st->codecpar->codec_id == AV_CODEC_ID_ILBC){
5674                 if (!st->codecpar->block_align) {
5675                     av_log(s, AV_LOG_ERROR, "track %d: codec block align is not set for adpcm\n", i);
5676                     ret = AVERROR(EINVAL);
5677                     goto error;
5678                 }
5679                 track->sample_size = st->codecpar->block_align;
5680             }else if (st->codecpar->frame_size > 1){ /* assume compressed audio */
5681                 track->audio_vbr = 1;
5682             }else{
5683                 track->sample_size = (av_get_bits_per_sample(st->codecpar->codec_id) >> 3) * st->codecpar->channels;
5684             }
5685             if (st->codecpar->codec_id == AV_CODEC_ID_ILBC ||
5686                 st->codecpar->codec_id == AV_CODEC_ID_ADPCM_IMA_QT) {
5687                 track->audio_vbr = 1;
5688             }
5689             if (track->mode != MODE_MOV &&
5690                 track->par->codec_id == AV_CODEC_ID_MP3 && track->timescale < 16000) {
5691                 if (s->strict_std_compliance >= FF_COMPLIANCE_NORMAL) {
5692                     av_log(s, AV_LOG_ERROR, "track %d: muxing mp3 at %dhz is not standard, to mux anyway set strict to -1\n",
5693                         i, track->par->sample_rate);
5694                     ret = AVERROR(EINVAL);
5695                     goto error;
5696                 } else {
5697                     av_log(s, AV_LOG_WARNING, "track %d: muxing mp3 at %dhz is not standard in MP4\n",
5698                            i, track->par->sample_rate);
5699                 }
5700             }
5701         } else if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) {
5702             track->timescale = st->time_base.den;
5703         } else if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA) {
5704             track->timescale = st->time_base.den;
5705         } else {
5706             track->timescale = MOV_TIMESCALE;
5707         }
5708         if (!track->height)
5709             track->height = st->codecpar->height;
5710         /* The ism specific timescale isn't mandatory, but is assumed by
5711          * some tools, such as mp4split. */
5712         if (mov->mode == MODE_ISM)
5713             track->timescale = 10000000;
5714
5715         avpriv_set_pts_info(st, 64, 1, track->timescale);
5716
5717         /* copy extradata if it exists */
5718         if (st->codecpar->extradata_size) {
5719             if (st->codecpar->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
5720                 mov_create_dvd_sub_decoder_specific_info(track, st);
5721             else if (!TAG_IS_AVCI(track->tag) && st->codecpar->codec_id != AV_CODEC_ID_DNXHD) {
5722                 track->vos_len  = st->codecpar->extradata_size;
5723                 track->vos_data = av_malloc(track->vos_len);
5724                 if (!track->vos_data) {
5725                     ret = AVERROR(ENOMEM);
5726                     goto error;
5727                 }
5728                 memcpy(track->vos_data, st->codecpar->extradata, track->vos_len);
5729             }
5730         }
5731
5732         if (mov->encryption_scheme == MOV_ENC_CENC_AES_CTR) {
5733             ret = ff_mov_cenc_init(&track->cenc, mov->encryption_key,
5734                 track->par->codec_id == AV_CODEC_ID_H264, s->flags & AVFMT_FLAG_BITEXACT);
5735             if (ret) {
5736                 goto error;
5737             }
5738         }
5739     }
5740
5741     for (i = 0; i < s->nb_streams; i++) {
5742         int j;
5743         AVStream *st= s->streams[i];
5744         MOVTrack *track= &mov->tracks[i];
5745
5746         if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ||
5747             track->par->channel_layout != AV_CH_LAYOUT_MONO)
5748             continue;
5749
5750         for (j = 0; j < s->nb_streams; j++) {
5751             AVStream *stj= s->streams[j];
5752             MOVTrack *trackj= &mov->tracks[j];
5753             if (j == i)
5754                 continue;
5755
5756             if (stj->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ||
5757                 trackj->par->channel_layout != AV_CH_LAYOUT_MONO ||
5758                 trackj->language != track->language ||
5759                 trackj->tag != track->tag
5760             )
5761                 continue;
5762             track->multichannel_as_mono++;
5763         }
5764     }
5765
5766     enable_tracks(s);
5767
5768
5769     if (mov->reserved_moov_size){
5770         mov->reserved_header_pos = avio_tell(pb);
5771         if (mov->reserved_moov_size > 0)
5772             avio_skip(pb, mov->reserved_moov_size);
5773     }
5774
5775     if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
5776         /* If no fragmentation options have been set, set a default. */
5777         if (!(mov->flags & (FF_MOV_FLAG_FRAG_KEYFRAME |
5778                             FF_MOV_FLAG_FRAG_CUSTOM)) &&
5779             !mov->max_fragment_duration && !mov->max_fragment_size)
5780             mov->flags |= FF_MOV_FLAG_FRAG_KEYFRAME;
5781     } else {
5782         if (mov->flags & FF_MOV_FLAG_FASTSTART)
5783             mov->reserved_header_pos = avio_tell(pb);
5784         mov_write_mdat_tag(pb, mov);
5785     }
5786
5787     ff_parse_creation_time_metadata(s, &mov->time, 1);
5788     if (mov->time)
5789         mov->time += 0x7C25B080; // 1970 based -> 1904 based
5790
5791     if (mov->chapter_track)
5792         if ((ret = mov_create_chapter_track(s, mov->chapter_track)) < 0)
5793             goto error;
5794
5795     if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
5796         /* Initialize the hint tracks for each audio and video stream */
5797         for (i = 0; i < s->nb_streams; i++) {
5798             AVStream *st = s->streams[i];
5799             if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ||
5800                 st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
5801                 if ((ret = ff_mov_init_hinting(s, hint_track, i)) < 0)
5802                     goto error;
5803                 hint_track++;
5804             }
5805         }
5806     }
5807
5808     if (mov->nb_meta_tmcd) {
5809         /* Initialize the tmcd tracks */
5810         for (i = 0; i < s->nb_streams; i++) {
5811             AVStream *st = s->streams[i];
5812             t = global_tcr;
5813
5814             if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
5815                 AVTimecode tc;
5816                 if (!t)
5817                     t = av_dict_get(st->metadata, "timecode", NULL, 0);
5818                 if (!t)
5819                     continue;
5820                 if (mov_check_timecode_track(s, &tc, i, t->value) < 0)
5821                     continue;
5822                 if ((ret = mov_create_timecode_track(s, tmcd_track, i, tc)) < 0)
5823                     goto error;
5824                 tmcd_track++;
5825             }
5826         }
5827     }
5828
5829     avio_flush(pb);
5830
5831     if (mov->flags & FF_MOV_FLAG_ISML)
5832         mov_write_isml_manifest(pb, mov, s);
5833
5834     if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV &&
5835         !(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
5836         if ((ret = mov_write_moov_tag(pb, mov, s)) < 0)
5837             return ret;
5838         avio_flush(pb);
5839         mov->moov_written = 1;
5840         if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
5841             mov->reserved_header_pos = avio_tell(pb);
5842     }
5843
5844     return 0;
5845  error:
5846     mov_free(s);
5847     return ret;
5848 }
5849
5850 static int get_moov_size(AVFormatContext *s)
5851 {
5852     int ret;
5853     AVIOContext *moov_buf;
5854     MOVMuxContext *mov = s->priv_data;
5855
5856     if ((ret = ffio_open_null_buf(&moov_buf)) < 0)
5857         return ret;
5858     if ((ret = mov_write_moov_tag(moov_buf, mov, s)) < 0)
5859         return ret;
5860     return ffio_close_null_buf(moov_buf);
5861 }
5862
5863 static int get_sidx_size(AVFormatContext *s)
5864 {
5865     int ret;
5866     AVIOContext *buf;
5867     MOVMuxContext *mov = s->priv_data;
5868
5869     if ((ret = ffio_open_null_buf(&buf)) < 0)
5870         return ret;
5871     mov_write_sidx_tags(buf, mov, -1, 0);
5872     return ffio_close_null_buf(buf);
5873 }
5874
5875 /*
5876  * This function gets the moov size if moved to the top of the file: the chunk
5877  * offset table can switch between stco (32-bit entries) to co64 (64-bit
5878  * entries) when the moov is moved to the beginning, so the size of the moov
5879  * would change. It also updates the chunk offset tables.
5880  */
5881 static int compute_moov_size(AVFormatContext *s)
5882 {
5883     int i, moov_size, moov_size2;
5884     MOVMuxContext *mov = s->priv_data;
5885
5886     moov_size = get_moov_size(s);
5887     if (moov_size < 0)
5888         return moov_size;
5889
5890     for (i = 0; i < mov->nb_streams; i++)
5891         mov->tracks[i].data_offset += moov_size;
5892
5893     moov_size2 = get_moov_size(s);
5894     if (moov_size2 < 0)
5895         return moov_size2;
5896
5897     /* if the size changed, we just switched from stco to co64 and need to
5898      * update the offsets */
5899     if (moov_size2 != moov_size)
5900         for (i = 0; i < mov->nb_streams; i++)
5901             mov->tracks[i].data_offset += moov_size2 - moov_size;
5902
5903     return moov_size2;
5904 }
5905
5906 static int compute_sidx_size(AVFormatContext *s)
5907 {
5908     int i, sidx_size;
5909     MOVMuxContext *mov = s->priv_data;
5910
5911     sidx_size = get_sidx_size(s);
5912     if (sidx_size < 0)
5913         return sidx_size;
5914
5915     for (i = 0; i < mov->nb_streams; i++)
5916         mov->tracks[i].data_offset += sidx_size;
5917
5918     return sidx_size;
5919 }
5920
5921 static int shift_data(AVFormatContext *s)
5922 {
5923     int ret = 0, moov_size;
5924     MOVMuxContext *mov = s->priv_data;
5925     int64_t pos, pos_end = avio_tell(s->pb);
5926     uint8_t *buf, *read_buf[2];
5927     int read_buf_id = 0;
5928     int read_size[2];
5929     AVIOContext *read_pb;
5930
5931     if (mov->flags & FF_MOV_FLAG_FRAGMENT)
5932         moov_size = compute_sidx_size(s);
5933     else
5934         moov_size = compute_moov_size(s);
5935     if (moov_size < 0)
5936         return moov_size;
5937
5938     buf = av_malloc(moov_size * 2);
5939     if (!buf)
5940         return AVERROR(ENOMEM);
5941     read_buf[0] = buf;
5942     read_buf[1] = buf + moov_size;
5943
5944     /* Shift the data: the AVIO context of the output can only be used for
5945      * writing, so we re-open the same output, but for reading. It also avoids
5946      * a read/seek/write/seek back and forth. */
5947     avio_flush(s->pb);
5948     ret = s->io_open(s, &read_pb, s->filename, AVIO_FLAG_READ, NULL);
5949     if (ret < 0) {
5950         av_log(s, AV_LOG_ERROR, "Unable to re-open %s output file for "
5951                "the second pass (faststart)\n", s->filename);
5952         goto end;
5953     }
5954
5955     /* mark the end of the shift to up to the last data we wrote, and get ready
5956      * for writing */
5957     pos_end = avio_tell(s->pb);
5958     avio_seek(s->pb, mov->reserved_header_pos + moov_size, SEEK_SET);
5959
5960     /* start reading at where the new moov will be placed */
5961     avio_seek(read_pb, mov->reserved_header_pos, SEEK_SET);
5962     pos = avio_tell(read_pb);
5963
5964 #define READ_BLOCK do {                                                             \
5965     read_size[read_buf_id] = avio_read(read_pb, read_buf[read_buf_id], moov_size);  \
5966     read_buf_id ^= 1;                                                               \
5967 } while (0)
5968
5969     /* shift data by chunk of at most moov_size */
5970     READ_BLOCK;
5971     do {
5972         int n;
5973         READ_BLOCK;
5974         n = read_size[read_buf_id];
5975         if (n <= 0)
5976             break;
5977         avio_write(s->pb, read_buf[read_buf_id], n);
5978         pos += n;
5979     } while (pos < pos_end);
5980     ff_format_io_close(s, &read_pb);
5981
5982 end:
5983     av_free(buf);
5984     return ret;
5985 }
5986
5987 static int mov_write_trailer(AVFormatContext *s)
5988 {
5989     MOVMuxContext *mov = s->priv_data;
5990     AVIOContext *pb = s->pb;
5991     int res = 0;
5992     int i;
5993     int64_t moov_pos;
5994
5995     if (mov->need_rewrite_extradata) {
5996         for (i = 0; i < s->nb_streams; i++) {
5997             MOVTrack *track = &mov->tracks[i];
5998             AVCodecParameters *par = track->par;
5999
6000             track->vos_len  = par->extradata_size;
6001             track->vos_data = av_malloc(track->vos_len);
6002             if (!track->vos_data) {
6003                 res = AVERROR(ENOMEM);
6004                 goto error;
6005             }
6006             memcpy(track->vos_data, par->extradata, track->vos_len);
6007         }
6008         mov->need_rewrite_extradata = 0;
6009     }
6010
6011     /*
6012      * Before actually writing the trailer, make sure that there are no
6013      * dangling subtitles, that need a terminating sample.
6014      */
6015     for (i = 0; i < mov->nb_streams; i++) {
6016         MOVTrack *trk = &mov->tracks[i];
6017         if (trk->par->codec_id == AV_CODEC_ID_MOV_TEXT &&
6018             !trk->last_sample_is_subtitle_end) {
6019             mov_write_subtitle_end_packet(s, i, trk->track_duration);
6020             trk->last_sample_is_subtitle_end = 1;
6021         }
6022     }
6023
6024     // If there were no chapters when the header was written, but there
6025     // are chapters now, write them in the trailer.  This only works
6026     // when we are not doing fragments.
6027     if (!mov->chapter_track && !(mov->flags & FF_MOV_FLAG_FRAGMENT)) {
6028         if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters) {
6029             mov->chapter_track = mov->nb_streams++;
6030             if ((res = mov_create_chapter_track(s, mov->chapter_track)) < 0)
6031                 goto error;
6032         }
6033     }
6034
6035     if (!(mov->flags & FF_MOV_FLAG_FRAGMENT)) {
6036         moov_pos = avio_tell(pb);
6037
6038         /* Write size of mdat tag */
6039         if (mov->mdat_size + 8 <= UINT32_MAX) {
6040             avio_seek(pb, mov->mdat_pos, SEEK_SET);
6041             avio_wb32(pb, mov->mdat_size + 8);
6042         } else {
6043             /* overwrite 'wide' placeholder atom */
6044             avio_seek(pb, mov->mdat_pos - 8, SEEK_SET);
6045             /* special value: real atom size will be 64 bit value after
6046              * tag field */
6047             avio_wb32(pb, 1);
6048             ffio_wfourcc(pb, "mdat");
6049             avio_wb64(pb, mov->mdat_size + 16);
6050         }
6051         avio_seek(pb, mov->reserved_moov_size > 0 ? mov->reserved_header_pos : moov_pos, SEEK_SET);
6052
6053         if (mov->flags & FF_MOV_FLAG_FASTSTART) {
6054             av_log(s, AV_LOG_INFO, "Starting second pass: moving the moov atom to the beginning of the file\n");
6055             res = shift_data(s);
6056             if (res < 0)
6057                 goto error;
6058             avio_seek(pb, mov->reserved_header_pos, SEEK_SET);
6059             if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
6060                 goto error;
6061         } else if (mov->reserved_moov_size > 0) {
6062             int64_t size;
6063             if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
6064                 goto error;
6065             size = mov->reserved_moov_size - (avio_tell(pb) - mov->reserved_header_pos);
6066             if (size < 8){
6067                 av_log(s, AV_LOG_ERROR, "reserved_moov_size is too small, needed %"PRId64" additional\n", 8-size);
6068                 res = AVERROR(EINVAL);
6069                 goto error;
6070             }
6071             avio_wb32(pb, size);
6072             ffio_wfourcc(pb, "free");
6073             ffio_fill(pb, 0, size - 8);
6074             avio_seek(pb, moov_pos, SEEK_SET);
6075         } else {
6076             if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
6077                 goto error;
6078         }
6079         res = 0;
6080     } else {
6081         mov_auto_flush_fragment(s, 1);
6082         for (i = 0; i < mov->nb_streams; i++)
6083            mov->tracks[i].data_offset = 0;
6084         if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) {
6085             int64_t end;
6086             av_log(s, AV_LOG_INFO, "Starting second pass: inserting sidx atoms\n");
6087             res = shift_data(s);
6088             if (res < 0)
6089                 goto error;
6090             end = avio_tell(pb);
6091             avio_seek(pb, mov->reserved_header_pos, SEEK_SET);
6092             mov_write_sidx_tags(pb, mov, -1, 0);
6093             avio_seek(pb, end, SEEK_SET);
6094             avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_TRAILER);
6095             mov_write_mfra_tag(pb, mov);
6096         } else {
6097             avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_TRAILER);
6098             mov_write_mfra_tag(pb, mov);
6099         }
6100     }
6101
6102 error:
6103     mov_free(s);
6104
6105     return res;
6106 }
6107
6108 #if CONFIG_MOV_MUXER
6109 MOV_CLASS(mov)
6110 AVOutputFormat ff_mov_muxer = {
6111     .name              = "mov",
6112     .long_name         = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
6113     .extensions        = "mov",
6114     .priv_data_size    = sizeof(MOVMuxContext),
6115     .audio_codec       = AV_CODEC_ID_AAC,
6116     .video_codec       = CONFIG_LIBX264_ENCODER ?
6117                          AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
6118     .write_header      = mov_write_header,
6119     .write_packet      = mov_write_packet,
6120     .write_trailer     = mov_write_trailer,
6121     .flags             = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6122     .codec_tag         = (const AVCodecTag* const []){
6123         ff_codec_movvideo_tags, ff_codec_movaudio_tags, 0
6124     },
6125     .priv_class        = &mov_muxer_class,
6126 };
6127 #endif
6128 #if CONFIG_TGP_MUXER
6129 MOV_CLASS(tgp)
6130 AVOutputFormat ff_tgp_muxer = {
6131     .name              = "3gp",
6132     .long_name         = NULL_IF_CONFIG_SMALL("3GP (3GPP file format)"),
6133     .extensions        = "3gp",
6134     .priv_data_size    = sizeof(MOVMuxContext),
6135     .audio_codec       = AV_CODEC_ID_AMR_NB,
6136     .video_codec       = AV_CODEC_ID_H263,
6137     .write_header      = mov_write_header,
6138     .write_packet      = mov_write_packet,
6139     .write_trailer     = mov_write_trailer,
6140     .flags             = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6141     .codec_tag         = (const AVCodecTag* const []){ codec_3gp_tags, 0 },
6142     .priv_class        = &tgp_muxer_class,
6143 };
6144 #endif
6145 #if CONFIG_MP4_MUXER
6146 MOV_CLASS(mp4)
6147 AVOutputFormat ff_mp4_muxer = {
6148     .name              = "mp4",
6149     .long_name         = NULL_IF_CONFIG_SMALL("MP4 (MPEG-4 Part 14)"),
6150     .mime_type         = "video/mp4",
6151     .extensions        = "mp4",
6152     .priv_data_size    = sizeof(MOVMuxContext),
6153     .audio_codec       = AV_CODEC_ID_AAC,
6154     .video_codec       = CONFIG_LIBX264_ENCODER ?
6155                          AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
6156     .write_header      = mov_write_header,
6157     .write_packet      = mov_write_packet,
6158     .write_trailer     = mov_write_trailer,
6159     .flags             = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6160     .codec_tag         = (const AVCodecTag* const []){ ff_mp4_obj_type, 0 },
6161     .priv_class        = &mp4_muxer_class,
6162 };
6163 #endif
6164 #if CONFIG_PSP_MUXER
6165 MOV_CLASS(psp)
6166 AVOutputFormat ff_psp_muxer = {
6167     .name              = "psp",
6168     .long_name         = NULL_IF_CONFIG_SMALL("PSP MP4 (MPEG-4 Part 14)"),
6169     .extensions        = "mp4,psp",
6170     .priv_data_size    = sizeof(MOVMuxContext),
6171     .audio_codec       = AV_CODEC_ID_AAC,
6172     .video_codec       = CONFIG_LIBX264_ENCODER ?
6173                          AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
6174     .write_header      = mov_write_header,
6175     .write_packet      = mov_write_packet,
6176     .write_trailer     = mov_write_trailer,
6177     .flags             = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6178     .codec_tag         = (const AVCodecTag* const []){ ff_mp4_obj_type, 0 },
6179     .priv_class        = &psp_muxer_class,
6180 };
6181 #endif
6182 #if CONFIG_TG2_MUXER
6183 MOV_CLASS(tg2)
6184 AVOutputFormat ff_tg2_muxer = {
6185     .name              = "3g2",
6186     .long_name         = NULL_IF_CONFIG_SMALL("3GP2 (3GPP2 file format)"),
6187     .extensions        = "3g2",
6188     .priv_data_size    = sizeof(MOVMuxContext),
6189     .audio_codec       = AV_CODEC_ID_AMR_NB,
6190     .video_codec       = AV_CODEC_ID_H263,
6191     .write_header      = mov_write_header,
6192     .write_packet      = mov_write_packet,
6193     .write_trailer     = mov_write_trailer,
6194     .flags             = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6195     .codec_tag         = (const AVCodecTag* const []){ codec_3gp_tags, 0 },
6196     .priv_class        = &tg2_muxer_class,
6197 };
6198 #endif
6199 #if CONFIG_IPOD_MUXER
6200 MOV_CLASS(ipod)
6201 AVOutputFormat ff_ipod_muxer = {
6202     .name              = "ipod",
6203     .long_name         = NULL_IF_CONFIG_SMALL("iPod H.264 MP4 (MPEG-4 Part 14)"),
6204     .mime_type         = "video/mp4",
6205     .extensions        = "m4v,m4a",
6206     .priv_data_size    = sizeof(MOVMuxContext),
6207     .audio_codec       = AV_CODEC_ID_AAC,
6208     .video_codec       = AV_CODEC_ID_H264,
6209     .write_header      = mov_write_header,
6210     .write_packet      = mov_write_packet,
6211     .write_trailer     = mov_write_trailer,
6212     .flags             = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6213     .codec_tag         = (const AVCodecTag* const []){ codec_ipod_tags, 0 },
6214     .priv_class        = &ipod_muxer_class,
6215 };
6216 #endif
6217 #if CONFIG_ISMV_MUXER
6218 MOV_CLASS(ismv)
6219 AVOutputFormat ff_ismv_muxer = {
6220     .name              = "ismv",
6221     .long_name         = NULL_IF_CONFIG_SMALL("ISMV/ISMA (Smooth Streaming)"),
6222     .mime_type         = "video/mp4",
6223     .extensions        = "ismv,isma",
6224     .priv_data_size    = sizeof(MOVMuxContext),
6225     .audio_codec       = AV_CODEC_ID_AAC,
6226     .video_codec       = AV_CODEC_ID_H264,
6227     .write_header      = mov_write_header,
6228     .write_packet      = mov_write_packet,
6229     .write_trailer     = mov_write_trailer,
6230     .flags             = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6231     .codec_tag         = (const AVCodecTag* const []){ ff_mp4_obj_type, 0 },
6232     .priv_class        = &ismv_muxer_class,
6233 };
6234 #endif
6235 #if CONFIG_F4V_MUXER
6236 MOV_CLASS(f4v)
6237 AVOutputFormat ff_f4v_muxer = {
6238     .name              = "f4v",
6239     .long_name         = NULL_IF_CONFIG_SMALL("F4V Adobe Flash Video"),
6240     .mime_type         = "application/f4v",
6241     .extensions        = "f4v",
6242     .priv_data_size    = sizeof(MOVMuxContext),
6243     .audio_codec       = AV_CODEC_ID_AAC,
6244     .video_codec       = AV_CODEC_ID_H264,
6245     .write_header      = mov_write_header,
6246     .write_packet      = mov_write_packet,
6247     .write_trailer     = mov_write_trailer,
6248     .flags             = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH,
6249     .codec_tag         = (const AVCodecTag* const []){ codec_f4v_tags, 0 },
6250     .priv_class        = &f4v_muxer_class,
6251 };
6252 #endif