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