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