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