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