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