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