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