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