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