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