movenc: Factorize a function for finding a metadata entry and the associated language
[libav.git] / libavformat / movenc.c
CommitLineData
1cb5f7fd 1/*
7fbde343 2 * MOV, 3GP, MP4 muxer
406792e7
DB
3 * Copyright (c) 2003 Thomas Raivio
4 * Copyright (c) 2004 Gildas Bazin <gbazin at videolan dot org>
7c4502c8 5 * Copyright (c) 2009 Baptiste Coudurier <baptiste dot coudurier at gmail dot com>
1cb5f7fd 6 *
2912e87a 7 * This file is part of Libav.
b78e7197 8 *
2912e87a 9 * Libav is free software; you can redistribute it and/or
1cb5f7fd
MN
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
b78e7197 12 * version 2.1 of the License, or (at your option) any later version.
1cb5f7fd 13 *
2912e87a 14 * Libav is distributed in the hope that it will be useful,
1cb5f7fd
MN
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
2912e87a 20 * License along with Libav; if not, write to the Free Software
5509bffa 21 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
1cb5f7fd 22 */
4909e517 23
8f8bc923 24#include <stdint.h>
cba4e606 25#include <inttypes.h>
8f8bc923 26
f72dad41 27#include "movenc.h"
1cb5f7fd 28#include "avformat.h"
0abdb293 29#include "avio_internal.h"
9d9f4119 30#include "riff.h"
1cb5f7fd 31#include "avio.h"
e40ee6a2 32#include "isom.h"
1bd2d763 33#include "avc.h"
9106a698 34#include "libavcodec/get_bits.h"
b2755007 35#include "libavcodec/put_bits.h"
4d55e9de 36#include "libavcodec/vc1_common.h"
e977af6f
MS
37#include "internal.h"
38#include "libavutil/avstring.h"
3383a53e 39#include "libavutil/intfloat.h"
0ebcdf5c 40#include "libavutil/mathematics.h"
91e3a25e 41#include "libavutil/opt.h"
d2d67e42 42#include "libavutil/dict.h"
20b40a59 43#include "hevc.h"
d16cccac 44#include "rtpenc.h"
1fdf18f4 45#include "mov_chan.h"
1cb5f7fd 46
91e3a25e 47static const AVOption options[] = {
d58dd4b5 48 { "movflags", "MOV muxer flags", offsetof(MOVMuxContext, flags), AV_OPT_TYPE_FLAGS, {.i64 = 0}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
124134e4 49 { "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" },
95a449d3 50 { "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" },
124134e4
MS
51 { "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" },
52 { "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" },
53 { "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" },
54 { "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" },
f8ef91ff 55 { "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" },
e7bf085b 56 { "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" },
0897d2fd 57 { "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" },
cf589faa 58 { "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" },
2ded5737 59 { "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" },
ee37620b 60 { "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" },
847bf598 61 { "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" },
26ac22e5 62 { "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" },
5354a904 63 FF_RTP_FLAG_OPTS(MOVMuxContext, rtp_flags),
e6153f17
MS
64 { "skip_iods", "Skip writing iods atom.", offsetof(MOVMuxContext, iods_skip), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM},
65 { "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},
66 { "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},
67 { "frag_duration", "Maximum fragment duration", offsetof(MOVMuxContext, max_fragment_duration), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
68 { "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},
69 { "frag_size", "Maximum fragment size", offsetof(MOVMuxContext, max_fragment_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
70 { "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},
1e9db41e 71 { "brand", "Override major brand", offsetof(MOVMuxContext, major_brand), AV_OPT_TYPE_STRING, {.str = NULL}, .flags = AV_OPT_FLAG_ENCODING_PARAM },
1d8a0c1b 72 { "use_editlist", "use edit list", offsetof(MOVMuxContext, use_editlist), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 1, AV_OPT_FLAG_ENCODING_PARAM},
448c8cfe 73 { "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},
2cb9c2fc 74 { "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 },
91e3a25e
MS
75 { NULL },
76};
77
a4ea00d0
AK
78#define MOV_CLASS(flavor)\
79static const AVClass flavor ## _muxer_class = {\
80 .class_name = #flavor " muxer",\
81 .item_name = av_default_item_name,\
82 .option = options,\
83 .version = LIBAVUTIL_VERSION_INT,\
91e3a25e
MS
84};
85
da9cc22d
JS
86static int utf8len(const uint8_t *b)
87{
88 int len = 0;
89 int val;
90 while (*b) {
91 GET_UTF8(val, *b++, return -1;)
92 len++;
93 }
94 return len;
95}
96
90b5b51e 97//FIXME support 64 bit variant with wide placeholders
b7d3dd90 98static int64_t update_size(AVIOContext *pb, int64_t pos)
1cb5f7fd 99{
a2704c97 100 int64_t curpos = avio_tell(pb);
6b4aa5da 101 avio_seek(pb, pos, SEEK_SET);
77eb5504 102 avio_wb32(pb, curpos - pos); /* rewrite size */
6b4aa5da 103 avio_seek(pb, curpos, SEEK_SET);
6e6d6dc0
MN
104
105 return curpos - pos;
1cb5f7fd
MN
106}
107
60198742
CB
108static int co64_required(const MOVTrack *track)
109{
110 if (track->entry > 0 && track->cluster[track->entry - 1].pos + track->data_offset > UINT32_MAX)
111 return 1;
112 return 0;
113}
114
e45ccf79 115/* Chunk offset atom */
ae628ec1 116static int mov_write_stco_tag(AVIOContext *pb, MOVTrack *track)
1cb5f7fd
MN
117{
118 int i;
60198742 119 int mode64 = co64_required(track); // use 32 bit size variant if possible
a2704c97 120 int64_t pos = avio_tell(pb);
77eb5504 121 avio_wb32(pb, 0); /* size */
60198742 122 if (mode64) {
0abdb293 123 ffio_wfourcc(pb, "co64");
b29af723 124 } else
0abdb293 125 ffio_wfourcc(pb, "stco");
77eb5504
AK
126 avio_wb32(pb, 0); /* version & flags */
127 avio_wb32(pb, track->entry); /* entry count */
21732063
MS
128 for (i = 0; i < track->entry; i++) {
129 if (mode64 == 1)
0c7b8b75 130 avio_wb64(pb, track->cluster[i].pos + track->data_offset);
b29af723 131 else
0c7b8b75 132 avio_wb32(pb, track->cluster[i].pos + track->data_offset);
1cb5f7fd 133 }
b7d3dd90 134 return update_size(pb, pos);
1cb5f7fd
MN
135}
136
e45ccf79 137/* Sample size atom */
ae628ec1 138static int mov_write_stsz_tag(AVIOContext *pb, MOVTrack *track)
1cb5f7fd 139{
f578f938 140 int equalChunks = 1;
e45ccf79 141 int i, j, entries = 0, tst = -1, oldtst = -1;
1cb5f7fd 142
a2704c97 143 int64_t pos = avio_tell(pb);
77eb5504 144 avio_wb32(pb, 0); /* size */
0abdb293 145 ffio_wfourcc(pb, "stsz");
77eb5504 146 avio_wb32(pb, 0); /* version & flags */
1cb5f7fd 147
21732063
MS
148 for (i = 0; i < track->entry; i++) {
149 tst = track->cluster[i].size / track->cluster[i].entries;
150 if (oldtst != -1 && tst != oldtst)
e45ccf79 151 equalChunks = 0;
f578f938 152 oldtst = tst;
0aec3c5c 153 entries += track->cluster[i].entries;
f578f938 154 }
83988d58 155 if (equalChunks && track->entry) {
21732063 156 int sSize = track->entry ? track->cluster[0].size / track->cluster[0].entries : 0;
7fe3207e 157 sSize = FFMAX(1, sSize); // adpcm mono case could make sSize == 0
77eb5504
AK
158 avio_wb32(pb, sSize); // sample size
159 avio_wb32(pb, entries); // sample count
21732063 160 } else {
77eb5504
AK
161 avio_wb32(pb, 0); // sample size
162 avio_wb32(pb, entries); // sample count
21732063
MS
163 for (i = 0; i < track->entry; i++) {
164 for (j = 0; j < track->cluster[i].entries; j++) {
77eb5504 165 avio_wb32(pb, track->cluster[i].size /
21732063 166 track->cluster[i].entries);
e45ccf79 167 }
1cb5f7fd
MN
168 }
169 }
b7d3dd90 170 return update_size(pb, pos);
1cb5f7fd
MN
171}
172
e45ccf79 173/* Sample to chunk atom */
ae628ec1 174static int mov_write_stsc_tag(AVIOContext *pb, MOVTrack *track)
1cb5f7fd 175{
b29af723 176 int index = 0, oldval = -1, i;
bc5c918e 177 int64_t entryPos, curpos;
f578f938 178
a2704c97 179 int64_t pos = avio_tell(pb);
77eb5504 180 avio_wb32(pb, 0); /* size */
0abdb293 181 ffio_wfourcc(pb, "stsc");
77eb5504 182 avio_wb32(pb, 0); // version & flags
a2704c97 183 entryPos = avio_tell(pb);
77eb5504 184 avio_wb32(pb, track->entry); // entry count
21732063
MS
185 for (i = 0; i < track->entry; i++) {
186 if (oldval != track->cluster[i].samples_in_chunk) {
187 avio_wb32(pb, i + 1); // first chunk
b7d3dd90 188 avio_wb32(pb, track->cluster[i].samples_in_chunk); // samples per chunk
77eb5504 189 avio_wb32(pb, 0x1); // sample description index
b7d3dd90 190 oldval = track->cluster[i].samples_in_chunk;
f578f938 191 index++;
1cb5f7fd
MN
192 }
193 }
a2704c97 194 curpos = avio_tell(pb);
6b4aa5da 195 avio_seek(pb, entryPos, SEEK_SET);
77eb5504 196 avio_wb32(pb, index); // rewrite size
6b4aa5da 197 avio_seek(pb, curpos, SEEK_SET);
1cb5f7fd 198
b7d3dd90 199 return update_size(pb, pos);
1cb5f7fd
MN
200}
201
e45ccf79 202/* Sync sample atom */
ae628ec1 203static int mov_write_stss_tag(AVIOContext *pb, MOVTrack *track, uint32_t flag)
1cb5f7fd 204{
bc5c918e 205 int64_t curpos, entryPos;
b29af723 206 int i, index = 0;
a2704c97 207 int64_t pos = avio_tell(pb);
77eb5504 208 avio_wb32(pb, 0); // size
0abdb293 209 ffio_wfourcc(pb, flag == MOV_SYNC_SAMPLE ? "stss" : "stps");
77eb5504 210 avio_wb32(pb, 0); // version & flags
a2704c97 211 entryPos = avio_tell(pb);
77eb5504 212 avio_wb32(pb, track->entry); // entry count
21732063 213 for (i = 0; i < track->entry; i++) {
e1316b19 214 if (track->cluster[i].flags & flag) {
21732063 215 avio_wb32(pb, i + 1);
f578f938
TR
216 index++;
217 }
218 }
a2704c97 219 curpos = avio_tell(pb);
6b4aa5da 220 avio_seek(pb, entryPos, SEEK_SET);
77eb5504 221 avio_wb32(pb, index); // rewrite size
6b4aa5da 222 avio_seek(pb, curpos, SEEK_SET);
b7d3dd90 223 return update_size(pb, pos);
1cb5f7fd
MN
224}
225
ae628ec1 226static int mov_write_amr_tag(AVIOContext *pb, MOVTrack *track)
1cb5f7fd 227{
77eb5504 228 avio_wb32(pb, 0x11); /* size */
0abdb293
AK
229 if (track->mode == MODE_MOV) ffio_wfourcc(pb, "samr");
230 else ffio_wfourcc(pb, "damr");
231 ffio_wfourcc(pb, "FFMP");
77eb5504 232 avio_w8(pb, 0); /* decoder version */
3a72cbd9 233
77eb5504
AK
234 avio_wb16(pb, 0x81FF); /* Mode set (all modes for AMR_NB) */
235 avio_w8(pb, 0x00); /* Mode change period (no restriction) */
236 avio_w8(pb, 0x01); /* Frames per sample */
3a72cbd9
BC
237 return 0x11;
238}
239
ae628ec1 240static int mov_write_ac3_tag(AVIOContext *pb, MOVTrack *track)
d4a240cb
BC
241{
242 GetBitContext gbc;
243 PutBitContext pbc;
244 uint8_t buf[3];
245 int fscod, bsid, bsmod, acmod, lfeon, frmsizecod;
246
b7d3dd90 247 if (track->vos_len < 7)
d4a240cb
BC
248 return -1;
249
77eb5504 250 avio_wb32(pb, 11);
0abdb293 251 ffio_wfourcc(pb, "dac3");
d4a240cb 252
b7d3dd90 253 init_get_bits(&gbc, track->vos_data + 4, (track->vos_len - 4) * 8);
d4a240cb
BC
254 fscod = get_bits(&gbc, 2);
255 frmsizecod = get_bits(&gbc, 6);
256 bsid = get_bits(&gbc, 5);
257 bsmod = get_bits(&gbc, 3);
258 acmod = get_bits(&gbc, 3);
259 if (acmod == 2) {
260 skip_bits(&gbc, 2); // dsurmod
261 } else {
262 if ((acmod & 1) && acmod != 1)
263 skip_bits(&gbc, 2); // cmixlev
264 if (acmod & 4)
265 skip_bits(&gbc, 2); // surmixlev
266 }
267 lfeon = get_bits1(&gbc);
268
269 init_put_bits(&pbc, buf, sizeof(buf));
270 put_bits(&pbc, 2, fscod);
271 put_bits(&pbc, 5, bsid);
272 put_bits(&pbc, 3, bsmod);
273 put_bits(&pbc, 3, acmod);
274 put_bits(&pbc, 1, lfeon);
21732063 275 put_bits(&pbc, 5, frmsizecod >> 1); // bit_rate_code
d4a240cb
BC
276 put_bits(&pbc, 5, 0); // reserved
277
278 flush_put_bits(&pbc);
77eb5504 279 avio_write(pb, buf, sizeof(buf));
d4a240cb
BC
280
281 return 11;
282}
283
463e7afd
BC
284/**
285 * This function writes extradata "as is".
da9cea77 286 * Extradata must be formatted like a valid atom (with size and tag).
463e7afd 287 */
ae628ec1 288static int mov_write_extradata_tag(AVIOContext *pb, MOVTrack *track)
463e7afd 289{
9200514a
AK
290 avio_write(pb, track->par->extradata, track->par->extradata_size);
291 return track->par->extradata_size;
463e7afd
BC
292}
293
b7d3dd90 294static void put_descr(AVIOContext *pb, int tag, unsigned int size)
039627cf 295{
7e19a6e8 296 int i = 3;
77eb5504 297 avio_w8(pb, tag);
21732063
MS
298 for (; i > 0; i--)
299 avio_w8(pb, (size >> (7 * i)) | 0x80);
77eb5504 300 avio_w8(pb, size & 0x7F);
039627cf
BC
301}
302
ae628ec1 303static int mov_write_esds_tag(AVIOContext *pb, MOVTrack *track) // Basic
039627cf 304{
5845a827 305 AVCPBProperties *props;
a2704c97 306 int64_t pos = avio_tell(pb);
b7d3dd90 307 int decoder_specific_info_len = track->vos_len ? 5 + track->vos_len : 0;
039627cf 308
77eb5504 309 avio_wb32(pb, 0); // size
0abdb293 310 ffio_wfourcc(pb, "esds");
77eb5504 311 avio_wb32(pb, 0); // Version
039627cf
BC
312
313 // ES descriptor
b7d3dd90
MS
314 put_descr(pb, 0x03, 3 + 5+13 + decoder_specific_info_len + 5+1);
315 avio_wb16(pb, track->track_id);
77eb5504 316 avio_w8(pb, 0x00); // flags (= no flags)
039627cf
BC
317
318 // DecoderConfig descriptor
b7d3dd90 319 put_descr(pb, 0x04, 13 + decoder_specific_info_len);
039627cf
BC
320
321 // Object type indication
9200514a
AK
322 if ((track->par->codec_id == AV_CODEC_ID_MP2 ||
323 track->par->codec_id == AV_CODEC_ID_MP3) &&
324 track->par->sample_rate > 24000)
77eb5504 325 avio_w8(pb, 0x6B); // 11172-3
dfce888f 326 else
9200514a 327 avio_w8(pb, ff_codec_get_tag(ff_mp4_obj_type, track->par->codec_id));
039627cf
BC
328
329 // the following fields is made of 6 bits to identify the streamtype (4 for video, 5 for audio)
330 // plus 1 bit to indicate upstream and 1 bit set to 1 (reserved)
9200514a 331 if (track->par->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
6adf3bc4 332 avio_w8(pb, (0x38 << 2) | 1); // flags (= NeroSubpicStream)
9200514a 333 else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
77eb5504 334 avio_w8(pb, 0x15); // flags (= Audiostream)
039627cf 335 else
77eb5504 336 avio_w8(pb, 0x11); // flags (= Visualstream)
039627cf 337
5845a827
AK
338 props = (AVCPBProperties*)av_stream_get_side_data(track->st, AV_PKT_DATA_CPB_PROPERTIES,
339 NULL);
039627cf 340
5845a827
AK
341 avio_wb24(pb, props ? props->buffer_size / 8 : 0); // Buffersize DB
342
9200514a 343 avio_wb32(pb, props ? FFMAX(props->max_bitrate, props->avg_bitrate) : track->par->bit_rate); // maxbitrate (FIXME should be max rate in any 1 sec window)
5845a827 344 if (!props || !props->min_bitrate || props->max_bitrate != props->min_bitrate)
77eb5504 345 avio_wb32(pb, 0); // vbr
039627cf 346 else
5845a827 347 avio_wb32(pb, props->max_bitrate); // avg bitrate
039627cf 348
b7d3dd90 349 if (track->vos_len) {
039627cf 350 // DecoderSpecific info descriptor
b7d3dd90
MS
351 put_descr(pb, 0x05, track->vos_len);
352 avio_write(pb, track->vos_data, track->vos_len);
039627cf
BC
353 }
354
039627cf 355 // SL descriptor
b7d3dd90 356 put_descr(pb, 0x06, 1);
77eb5504 357 avio_w8(pb, 0x02);
b7d3dd90 358 return update_size(pb, pos);
039627cf
BC
359}
360
9200514a 361static int mov_write_ms_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
f2589642 362{
a2704c97 363 int64_t pos = avio_tell(pb);
77eb5504
AK
364 avio_wb32(pb, 0);
365 avio_wl32(pb, track->tag); // store it byteswapped
9200514a
AK
366 track->par->codec_tag = av_bswap16(track->tag >> 16);
367 ff_put_wav_header(s, pb, track->st->codecpar);
b7d3dd90 368 return update_size(pb, pos);
f2589642
BC
369}
370
9200514a 371static int mov_write_wfex_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
5d561514
MS
372{
373 int64_t pos = avio_tell(pb);
374 avio_wb32(pb, 0);
375 ffio_wfourcc(pb, "wfex");
9200514a 376 ff_put_wav_header(s, pb, track->st->codecpar);
5d561514
MS
377 return update_size(pb, pos);
378}
379
9200514a 380static int mov_write_chan_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
1fdf18f4
JR
381{
382 uint32_t layout_tag, bitmap;
383 int64_t pos = avio_tell(pb);
384
9200514a
AK
385 layout_tag = ff_mov_get_channel_layout_tag(track->par->codec_id,
386 track->par->channel_layout,
1fdf18f4
JR
387 &bitmap);
388 if (!layout_tag) {
9200514a 389 av_log(s, AV_LOG_WARNING, "not writing 'chan' tag due to "
1fdf18f4
JR
390 "lack of channel information\n");
391 return 0;
392 }
393
394 avio_wb32(pb, 0); // Size
395 ffio_wfourcc(pb, "chan"); // Type
396 avio_w8(pb, 0); // Version
397 avio_wb24(pb, 0); // Flags
398 avio_wb32(pb, layout_tag); // mChannelLayoutTag
399 avio_wb32(pb, bitmap); // mChannelBitmap
400 avio_wb32(pb, 0); // mNumberChannelDescriptions
401
b7d3dd90 402 return update_size(pb, pos);
1fdf18f4
JR
403}
404
9200514a 405static int mov_write_wave_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
69dde1ad 406{
a2704c97 407 int64_t pos = avio_tell(pb);
69dde1ad 408
77eb5504 409 avio_wb32(pb, 0); /* size */
0abdb293 410 ffio_wfourcc(pb, "wave");
69dde1ad 411
77eb5504 412 avio_wb32(pb, 12); /* size */
0abdb293 413 ffio_wfourcc(pb, "frma");
77eb5504 414 avio_wl32(pb, track->tag);
69dde1ad 415
9200514a 416 if (track->par->codec_id == AV_CODEC_ID_AAC) {
aa1c1c61 417 /* useless atom needed by mplayer, ipod, not needed by quicktime */
77eb5504 418 avio_wb32(pb, 12); /* size */
0abdb293 419 ffio_wfourcc(pb, "mp4a");
77eb5504 420 avio_wb32(pb, 0);
fcef991a 421 mov_write_esds_tag(pb, track);
9200514a 422 } else if (track->par->codec_id == AV_CODEC_ID_AMR_NB) {
b7d9da10 423 mov_write_amr_tag(pb, track);
9200514a 424 } else if (track->par->codec_id == AV_CODEC_ID_AC3) {
d4a240cb 425 mov_write_ac3_tag(pb, track);
9200514a 426 } else if (track->par->codec_id == AV_CODEC_ID_ALAC) {
463e7afd 427 mov_write_extradata_tag(pb, track);
9200514a
AK
428 } else if (track->par->codec_id == AV_CODEC_ID_ADPCM_MS ||
429 track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) {
430 mov_write_ms_tag(s, pb, track);
fcef991a 431 }
69dde1ad 432
77eb5504
AK
433 avio_wb32(pb, 8); /* size */
434 avio_wb32(pb, 0); /* null tag */
69dde1ad 435
b7d3dd90 436 return update_size(pb, pos);
69dde1ad
GB
437}
438
4ace130e
MS
439static int mov_write_dvc1_structs(MOVTrack *track, uint8_t *buf)
440{
441 uint8_t *unescaped;
442 const uint8_t *start, *next, *end = track->vos_data + track->vos_len;
443 int unescaped_size, seq_found = 0;
444 int level = 0, interlace = 0;
445 int packet_seq = track->vc1_info.packet_seq;
446 int packet_entry = track->vc1_info.packet_entry;
447 int slices = track->vc1_info.slices;
448 PutBitContext pbc;
449
450 if (track->start_dts == AV_NOPTS_VALUE) {
451 /* No packets written yet, vc1_info isn't authoritative yet. */
b3b0b35d 452 /* Assume inline sequence and entry headers. */
4ace130e 453 packet_seq = packet_entry = 1;
b3b0b35d
MS
454 av_log(NULL, AV_LOG_WARNING,
455 "moov atom written before any packets, unable to write correct "
456 "dvc1 atom. Set the delay_moov flag to fix this.\n");
4ace130e
MS
457 }
458
059a9348 459 unescaped = av_mallocz(track->vos_len + AV_INPUT_BUFFER_PADDING_SIZE);
4ace130e
MS
460 if (!unescaped)
461 return AVERROR(ENOMEM);
462 start = find_next_marker(track->vos_data, end);
463 for (next = start; next < end; start = next) {
464 GetBitContext gb;
465 int size;
466 next = find_next_marker(start + 4, end);
467 size = next - start - 4;
468 if (size <= 0)
469 continue;
470 unescaped_size = vc1_unescape_buffer(start + 4, size, unescaped);
471 init_get_bits(&gb, unescaped, 8 * unescaped_size);
472 if (AV_RB32(start) == VC1_CODE_SEQHDR) {
473 int profile = get_bits(&gb, 2);
474 if (profile != PROFILE_ADVANCED) {
475 av_free(unescaped);
476 return AVERROR(ENOSYS);
477 }
478 seq_found = 1;
479 level = get_bits(&gb, 3);
480 /* chromaformat, frmrtq_postproc, bitrtq_postproc, postprocflag,
481 * width, height */
482 skip_bits_long(&gb, 2 + 3 + 5 + 1 + 2*12);
483 skip_bits(&gb, 1); /* broadcast */
484 interlace = get_bits1(&gb);
485 skip_bits(&gb, 4); /* tfcntrflag, finterpflag, reserved, psf */
486 }
487 }
488 if (!seq_found) {
489 av_free(unescaped);
490 return AVERROR(ENOSYS);
491 }
492
493 init_put_bits(&pbc, buf, 7);
494 /* VC1DecSpecStruc */
495 put_bits(&pbc, 4, 12); /* profile - advanced */
496 put_bits(&pbc, 3, level);
497 put_bits(&pbc, 1, 0); /* reserved */
498 /* VC1AdvDecSpecStruc */
499 put_bits(&pbc, 3, level);
500 put_bits(&pbc, 1, 0); /* cbr */
501 put_bits(&pbc, 6, 0); /* reserved */
502 put_bits(&pbc, 1, !interlace); /* no interlace */
503 put_bits(&pbc, 1, !packet_seq); /* no multiple seq */
504 put_bits(&pbc, 1, !packet_entry); /* no multiple entry */
505 put_bits(&pbc, 1, !slices); /* no slice code */
506 put_bits(&pbc, 1, 0); /* no bframe */
507 put_bits(&pbc, 1, 0); /* reserved */
cf697771
AK
508
509 /* framerate */
510 if (track->st->avg_frame_rate.num > 0 && track->st->avg_frame_rate.den > 0)
511 put_bits32(&pbc, track->st->avg_frame_rate.num / track->st->avg_frame_rate.den);
512 else
513 put_bits32(&pbc, 0xffffffff);
514
4ace130e
MS
515 flush_put_bits(&pbc);
516
517 av_free(unescaped);
518
519 return 0;
520}
521
522static int mov_write_dvc1_tag(AVIOContext *pb, MOVTrack *track)
523{
524 uint8_t buf[7] = { 0 };
525 int ret;
526
527 if ((ret = mov_write_dvc1_structs(track, buf)) < 0)
528 return ret;
529
530 avio_wb32(pb, track->vos_len + 8 + sizeof(buf));
531 ffio_wfourcc(pb, "dvc1");
4ace130e
MS
532 avio_write(pb, buf, sizeof(buf));
533 avio_write(pb, track->vos_data, track->vos_len);
534
535 return 0;
536}
537
ae628ec1 538static int mov_write_glbl_tag(AVIOContext *pb, MOVTrack *track)
79e42311 539{
b7d3dd90 540 avio_wb32(pb, track->vos_len + 8);
0abdb293 541 ffio_wfourcc(pb, "glbl");
b7d3dd90
MS
542 avio_write(pb, track->vos_data, track->vos_len);
543 return 8 + track->vos_len;
79e42311
BC
544}
545
feaa8d11
BC
546/**
547 * Compute flags for 'lpcm' tag.
548 * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
549 */
36ef5369 550static int mov_get_lpcm_flags(enum AVCodecID codec_id)
feaa8d11
BC
551{
552 switch (codec_id) {
36ef5369
AK
553 case AV_CODEC_ID_PCM_F32BE:
554 case AV_CODEC_ID_PCM_F64BE:
feaa8d11 555 return 11;
36ef5369
AK
556 case AV_CODEC_ID_PCM_F32LE:
557 case AV_CODEC_ID_PCM_F64LE:
feaa8d11 558 return 9;
36ef5369 559 case AV_CODEC_ID_PCM_U8:
feaa8d11 560 return 10;
36ef5369
AK
561 case AV_CODEC_ID_PCM_S16BE:
562 case AV_CODEC_ID_PCM_S24BE:
563 case AV_CODEC_ID_PCM_S32BE:
feaa8d11 564 return 14;
36ef5369
AK
565 case AV_CODEC_ID_PCM_S8:
566 case AV_CODEC_ID_PCM_S16LE:
567 case AV_CODEC_ID_PCM_S24LE:
568 case AV_CODEC_ID_PCM_S32LE:
feaa8d11
BC
569 return 12;
570 default:
571 return 0;
572 }
573}
574
681d1726
JR
575static int get_cluster_duration(MOVTrack *track, int cluster_idx)
576{
577 int64_t next_dts;
578
579 if (cluster_idx >= track->entry)
580 return 0;
581
582 if (cluster_idx + 1 == track->entry)
583 next_dts = track->track_duration + track->start_dts;
584 else
585 next_dts = track->cluster[cluster_idx + 1].dts;
586
587 return next_dts - track->cluster[cluster_idx].dts;
588}
589
f234e8a3
JR
590static int get_samples_per_packet(MOVTrack *track)
591{
592 int i, first_duration;
593
594 /* use 1 for raw PCM */
595 if (!track->audio_vbr)
596 return 1;
597
598 /* check to see if duration is constant for all clusters */
599 if (!track->entry)
600 return 0;
601 first_duration = get_cluster_duration(track, 0);
602 for (i = 1; i < track->entry; i++) {
603 if (get_cluster_duration(track, i) != first_duration)
604 return 0;
605 }
606 return first_duration;
607}
608
9200514a 609static int mov_write_audio_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
1cb5f7fd 610{
a2704c97 611 int64_t pos = avio_tell(pb);
feaa8d11
BC
612 int version = 0;
613 uint32_t tag = track->tag;
614
615 if (track->mode == MODE_MOV) {
9200514a 616 if (mov_get_lpcm_flags(track->par->codec_id))
8e8c5131
JR
617 tag = AV_RL32("lpcm");
618 version = 2;
feaa8d11 619 }
115329f1 620
77eb5504
AK
621 avio_wb32(pb, 0); /* size */
622 avio_wl32(pb, tag); // store it byteswapped
623 avio_wb32(pb, 0); /* Reserved */
624 avio_wb16(pb, 0); /* Reserved */
625 avio_wb16(pb, 1); /* Data-reference index, XXX == 1 */
69dde1ad 626
e45ccf79 627 /* SoundDescription */
77eb5504
AK
628 avio_wb16(pb, version); /* Version */
629 avio_wb16(pb, 0); /* Revision level */
630 avio_wb32(pb, 0); /* Reserved */
1cb5f7fd 631
feaa8d11 632 if (version == 2) {
77eb5504
AK
633 avio_wb16(pb, 3);
634 avio_wb16(pb, 16);
635 avio_wb16(pb, 0xfffe);
636 avio_wb16(pb, 0);
637 avio_wb32(pb, 0x00010000);
638 avio_wb32(pb, 72);
9200514a
AK
639 avio_wb64(pb, av_double2int(track->par->sample_rate));
640 avio_wb32(pb, track->par->channels);
77eb5504 641 avio_wb32(pb, 0x7F000000);
9200514a
AK
642 avio_wb32(pb, av_get_bits_per_sample(track->par->codec_id));
643 avio_wb32(pb, mov_get_lpcm_flags(track->par->codec_id));
b7d3dd90 644 avio_wb32(pb, track->sample_size);
f234e8a3 645 avio_wb32(pb, get_samples_per_packet(track));
feaa8d11 646 } else {
8e8c5131
JR
647 /* reserved for mp4/3gp */
648 avio_wb16(pb, 2);
649 avio_wb16(pb, 16);
650 avio_wb16(pb, 0);
ef19c7eb 651
77eb5504 652 avio_wb16(pb, 0); /* packet size (= 0) */
9200514a
AK
653 avio_wb16(pb, track->par->sample_rate <= UINT16_MAX ?
654 track->par->sample_rate : 0);
77eb5504 655 avio_wb16(pb, 0); /* Reserved */
feaa8d11 656 }
1cb5f7fd 657
21732063 658 if (track->mode == MODE_MOV &&
9200514a
AK
659 (track->par->codec_id == AV_CODEC_ID_AAC ||
660 track->par->codec_id == AV_CODEC_ID_AC3 ||
661 track->par->codec_id == AV_CODEC_ID_AMR_NB ||
662 track->par->codec_id == AV_CODEC_ID_ALAC ||
663 track->par->codec_id == AV_CODEC_ID_ADPCM_MS ||
664 track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV))
665 mov_write_wave_tag(s, pb, track);
21732063 666 else if (track->tag == MKTAG('m','p','4','a'))
3a72cbd9 667 mov_write_esds_tag(pb, track);
9200514a 668 else if (track->par->codec_id == AV_CODEC_ID_AMR_NB)
b7d9da10 669 mov_write_amr_tag(pb, track);
9200514a 670 else if (track->par->codec_id == AV_CODEC_ID_AC3)
4ed19420 671 mov_write_ac3_tag(pb, track);
9200514a 672 else if (track->par->codec_id == AV_CODEC_ID_ALAC)
709c9f8d 673 mov_write_extradata_tag(pb, track);
9200514a
AK
674 else if (track->par->codec_id == AV_CODEC_ID_WMAPRO)
675 mov_write_wfex_tag(s, pb, track);
b7d3dd90 676 else if (track->vos_len > 0)
79e42311 677 mov_write_glbl_tag(pb, track);
3a72cbd9 678
9200514a
AK
679 if (track->mode == MODE_MOV && track->par->codec_type == AVMEDIA_TYPE_AUDIO)
680 mov_write_chan_tag(s, pb, track);
41e9682a 681
b7d3dd90 682 return update_size(pb, pos);
1cb5f7fd
MN
683}
684
ae628ec1 685static int mov_write_d263_tag(AVIOContext *pb)
1cb5f7fd 686{
77eb5504 687 avio_wb32(pb, 0xf); /* size */
0abdb293
AK
688 ffio_wfourcc(pb, "d263");
689 ffio_wfourcc(pb, "FFMP");
77eb5504 690 avio_w8(pb, 0); /* decoder version */
87494ea0 691 /* FIXME use AVCodecContext level/profile, when encoder will set values */
77eb5504
AK
692 avio_w8(pb, 0xa); /* level */
693 avio_w8(pb, 0); /* profile */
1cb5f7fd
MN
694 return 0xf;
695}
696
f578f938 697/* TODO: No idea about these values */
ae628ec1 698static int mov_write_svq3_tag(AVIOContext *pb)
1cb5f7fd 699{
77eb5504 700 avio_wb32(pb, 0x15);
0abdb293
AK
701 ffio_wfourcc(pb, "SMI ");
702 ffio_wfourcc(pb, "SEQH");
77eb5504
AK
703 avio_wb32(pb, 0x5);
704 avio_wb32(pb, 0xe2c0211d);
705 avio_wb32(pb, 0xc0000000);
706 avio_w8(pb, 0);
f578f938 707 return 0x15;
1cb5f7fd
MN
708}
709
ae628ec1 710static int mov_write_avcc_tag(AVIOContext *pb, MOVTrack *track)
6e6eebf9 711{
a2704c97 712 int64_t pos = avio_tell(pb);
6e6eebf9 713
77eb5504 714 avio_wb32(pb, 0);
0abdb293 715 ffio_wfourcc(pb, "avcC");
b7d3dd90
MS
716 ff_isom_write_avcc(pb, track->vos_data, track->vos_len);
717 return update_size(pb, pos);
c1b8e6d8
BC
718}
719
20b40a59
TW
720static int mov_write_hvcc_tag(AVIOContext *pb, MOVTrack *track)
721{
722 int64_t pos = avio_tell(pb);
723
724 avio_wb32(pb, 0);
725 ffio_wfourcc(pb, "hvcC");
726 ff_isom_write_hvcc(pb, track->vos_data, track->vos_len, 0);
727 return update_size(pb, pos);
728}
729
fc4cbc16 730/* also used by all avid codecs (dv, imx, meridien) and their variants */
ae628ec1 731static int mov_write_avid_tag(AVIOContext *pb, MOVTrack *track)
fc4cbc16
BC
732{
733 int i;
77eb5504 734 avio_wb32(pb, 24); /* size */
0abdb293
AK
735 ffio_wfourcc(pb, "ACLR");
736 ffio_wfourcc(pb, "ACLR");
737 ffio_wfourcc(pb, "0001");
304e983d 738 avio_wb32(pb, 2); /* yuv range: full 1 / normal 2 */
77eb5504 739 avio_wb32(pb, 0); /* unknown */
fc4cbc16 740
77eb5504 741 avio_wb32(pb, 24); /* size */
0abdb293
AK
742 ffio_wfourcc(pb, "APRG");
743 ffio_wfourcc(pb, "APRG");
744 ffio_wfourcc(pb, "0001");
77eb5504
AK
745 avio_wb32(pb, 1); /* unknown */
746 avio_wb32(pb, 0); /* unknown */
fc4cbc16 747
77eb5504 748 avio_wb32(pb, 120); /* size */
0abdb293
AK
749 ffio_wfourcc(pb, "ARES");
750 ffio_wfourcc(pb, "ARES");
751 ffio_wfourcc(pb, "0001");
b7d3dd90 752 avio_wb32(pb, AV_RB32(track->vos_data + 0x28)); /* dnxhd cid, some id ? */
9200514a 753 avio_wb32(pb, track->par->width);
fc4cbc16 754 /* values below are based on samples created with quicktime and avid codecs */
b7d3dd90 755 if (track->vos_data[5] & 2) { // interlaced
9200514a 756 avio_wb32(pb, track->par->height / 2);
77eb5504
AK
757 avio_wb32(pb, 2); /* unknown */
758 avio_wb32(pb, 0); /* unknown */
759 avio_wb32(pb, 4); /* unknown */
fc4cbc16 760 } else {
9200514a 761 avio_wb32(pb, track->par->height);
77eb5504
AK
762 avio_wb32(pb, 1); /* unknown */
763 avio_wb32(pb, 0); /* unknown */
9200514a 764 if (track->par->height == 1080)
77eb5504 765 avio_wb32(pb, 5); /* unknown */
44fb8ebb 766 else
77eb5504 767 avio_wb32(pb, 6); /* unknown */
fc4cbc16
BC
768 }
769 /* padding */
770 for (i = 0; i < 10; i++)
77eb5504 771 avio_wb64(pb, 0);
fc4cbc16
BC
772
773 /* extra padding for stsd needed */
77eb5504 774 avio_wb32(pb, 0);
fc4cbc16
BC
775 return 0;
776}
777
6b600285 778static int mp4_get_codec_tag(AVFormatContext *s, MOVTrack *track)
8e321619 779{
9200514a 780 int tag = track->par->codec_tag;
2ab57c04 781
9200514a 782 if (!ff_codec_get_tag(ff_mp4_obj_type, track->par->codec_id))
2ab57c04
BC
783 return 0;
784
9200514a
AK
785 if (track->par->codec_id == AV_CODEC_ID_H264) tag = MKTAG('a','v','c','1');
786 else if (track->par->codec_id == AV_CODEC_ID_HEVC) tag = MKTAG('h','e','v','1');
787 else if (track->par->codec_id == AV_CODEC_ID_AC3) tag = MKTAG('a','c','-','3');
788 else if (track->par->codec_id == AV_CODEC_ID_DIRAC) tag = MKTAG('d','r','a','c');
789 else if (track->par->codec_id == AV_CODEC_ID_MOV_TEXT) tag = MKTAG('t','x','3','g');
790 else if (track->par->codec_id == AV_CODEC_ID_VC1) tag = MKTAG('v','c','-','1');
791 else if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) tag = MKTAG('m','p','4','v');
792 else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) tag = MKTAG('m','p','4','a');
793 else if (track->par->codec_id == AV_CODEC_ID_DVD_SUBTITLE) tag = MKTAG('m','p','4','s');
6b600285
BC
794
795 return tag;
796}
797
3c8d1447 798static const AVCodecTag codec_ipod_tags[] = {
21732063
MS
799 { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
800 { AV_CODEC_ID_MPEG4, MKTAG('m','p','4','v') },
801 { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
802 { AV_CODEC_ID_ALAC, MKTAG('a','l','a','c') },
803 { AV_CODEC_ID_AC3, MKTAG('a','c','-','3') },
36ef5369
AK
804 { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
805 { AV_CODEC_ID_MOV_TEXT, MKTAG('t','e','x','t') },
806 { AV_CODEC_ID_NONE, 0 },
3c8d1447
BC
807};
808
6b600285
BC
809static int ipod_get_codec_tag(AVFormatContext *s, MOVTrack *track)
810{
9200514a 811 int tag = track->par->codec_tag;
6b600285 812
130ba4b1 813 // keep original tag for subs, ipod supports both formats
9200514a 814 if (!(track->par->codec_type == AVMEDIA_TYPE_SUBTITLE &&
21732063
MS
815 (tag == MKTAG('t', 'x', '3', 'g') ||
816 tag == MKTAG('t', 'e', 'x', 't'))))
9200514a 817 tag = ff_codec_get_tag(codec_ipod_tags, track->par->codec_id);
0872acc4 818
ade5b91d 819 if (!av_match_ext(s->filename, "m4a") && !av_match_ext(s->filename, "m4v"))
2ab57c04
BC
820 av_log(s, AV_LOG_WARNING, "Warning, extension is not .m4a nor .m4v "
821 "Quicktime/Ipod might not play the file\n");
6b600285
BC
822
823 return tag;
824}
825
826static int mov_get_dv_codec_tag(AVFormatContext *s, MOVTrack *track)
827{
828 int tag;
829
9200514a
AK
830 if (track->par->width == 720) /* SD */
831 if (track->par->height == 480) /* NTSC */
832 if (track->par->format == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','n');
21732063 833 else tag = MKTAG('d','v','c',' ');
9200514a
AK
834 else if (track->par->format == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','p');
835 else if (track->par->format == AV_PIX_FMT_YUV420P) tag = MKTAG('d','v','c','p');
21732063 836 else tag = MKTAG('d','v','p','p');
9200514a 837 else if (track->par->height == 720) /* HD 720 line */
194be1f4 838 if (track->st->time_base.den == 50) tag = MKTAG('d','v','h','q');
21732063 839 else tag = MKTAG('d','v','h','p');
9200514a 840 else if (track->par->height == 1080) /* HD 1080 line */
194be1f4 841 if (track->st->time_base.den == 25) tag = MKTAG('d','v','h','5');
21732063 842 else tag = MKTAG('d','v','h','6');
06ed4873
BC
843 else {
844 av_log(s, AV_LOG_ERROR, "unsupported height for dv codec\n");
845 return 0;
846 }
6b600285
BC
847
848 return tag;
849}
850
3c8d1447 851static const struct {
716d413c 852 enum AVPixelFormat pix_fmt;
3c8d1447
BC
853 uint32_t tag;
854 unsigned bps;
855} mov_pix_fmt_tags[] = {
716d413c
AK
856 { AV_PIX_FMT_YUYV422, MKTAG('y','u','v','s'), 0 },
857 { AV_PIX_FMT_UYVY422, MKTAG('2','v','u','y'), 0 },
858 { AV_PIX_FMT_RGB555BE,MKTAG('r','a','w',' '), 16 },
859 { AV_PIX_FMT_RGB555LE,MKTAG('L','5','5','5'), 16 },
860 { AV_PIX_FMT_RGB565LE,MKTAG('L','5','6','5'), 16 },
861 { AV_PIX_FMT_RGB565BE,MKTAG('B','5','6','5'), 16 },
862 { AV_PIX_FMT_GRAY16BE,MKTAG('b','1','6','g'), 16 },
863 { AV_PIX_FMT_RGB24, MKTAG('r','a','w',' '), 24 },
864 { AV_PIX_FMT_BGR24, MKTAG('2','4','B','G'), 24 },
865 { AV_PIX_FMT_ARGB, MKTAG('r','a','w',' '), 32 },
866 { AV_PIX_FMT_BGRA, MKTAG('B','G','R','A'), 32 },
867 { AV_PIX_FMT_RGBA, MKTAG('R','G','B','A'), 32 },
868 { AV_PIX_FMT_ABGR, MKTAG('A','B','G','R'), 32 },
869 { AV_PIX_FMT_RGB48BE, MKTAG('b','4','8','r'), 48 },
3c8d1447
BC
870};
871
6b600285
BC
872static int mov_get_rawvideo_codec_tag(AVFormatContext *s, MOVTrack *track)
873{
9200514a 874 int tag = track->par->codec_tag;
2ab57c04
BC
875 int i;
876
877 for (i = 0; i < FF_ARRAY_ELEMS(mov_pix_fmt_tags); i++) {
9200514a 878 if (track->par->format == mov_pix_fmt_tags[i].pix_fmt) {
2ab57c04 879 tag = mov_pix_fmt_tags[i].tag;
9200514a 880 track->par->bits_per_coded_sample = mov_pix_fmt_tags[i].bps;
2ab57c04
BC
881 break;
882 }
883 }
6b600285
BC
884
885 return tag;
886}
887
888static int mov_get_codec_tag(AVFormatContext *s, MOVTrack *track)
889{
9200514a 890 int tag = track->par->codec_tag;
6b600285 891
91e8d2eb 892 if (!tag || (s->strict_std_compliance >= FF_COMPLIANCE_NORMAL &&
9200514a
AK
893 (track->par->codec_id == AV_CODEC_ID_DVVIDEO ||
894 track->par->codec_id == AV_CODEC_ID_RAWVIDEO ||
895 track->par->codec_id == AV_CODEC_ID_H263 ||
896 av_get_bits_per_sample(track->par->codec_id)))) { // pcm audio
897 if (track->par->codec_id == AV_CODEC_ID_DVVIDEO)
6b600285 898 tag = mov_get_dv_codec_tag(s, track);
9200514a 899 else if (track->par->codec_id == AV_CODEC_ID_RAWVIDEO)
6b600285 900 tag = mov_get_rawvideo_codec_tag(s, track);
9200514a
AK
901 else if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
902 tag = ff_codec_get_tag(ff_codec_movvideo_tags, track->par->codec_id);
08680ab8 903 if (!tag) { // if no mac fcc found, try with Microsoft tags
9200514a 904 tag = ff_codec_get_tag(ff_codec_bmp_tags, track->par->codec_id);
08680ab8 905 if (tag)
eb97dbb0 906 av_log(s, AV_LOG_WARNING, "Using MS style video codec tag, "
08680ab8
BC
907 "the file may be unplayable!\n");
908 }
9200514a
AK
909 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
910 tag = ff_codec_get_tag(ff_codec_movaudio_tags, track->par->codec_id);
08680ab8 911 if (!tag) { // if no mac fcc found, try with Microsoft tags
9200514a 912 int ms_tag = ff_codec_get_tag(ff_codec_wav_tags, track->par->codec_id);
08680ab8
BC
913 if (ms_tag) {
914 tag = MKTAG('m', 's', ((ms_tag >> 8) & 0xff), (ms_tag & 0xff));
eb97dbb0 915 av_log(s, AV_LOG_WARNING, "Using MS style audio codec tag, "
08680ab8 916 "the file may be unplayable!\n");
d97f2144 917 }
08680ab8 918 }
9200514a
AK
919 } else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)
920 tag = ff_codec_get_tag(ff_codec_movsubtitle_tags, track->par->codec_id);
a23c9c4a 921 }
2ab57c04 922
8e321619
BC
923 return tag;
924}
925
3c8d1447 926static const AVCodecTag codec_3gp_tags[] = {
21732063
MS
927 { AV_CODEC_ID_H263, MKTAG('s','2','6','3') },
928 { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
929 { AV_CODEC_ID_MPEG4, MKTAG('m','p','4','v') },
930 { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
931 { AV_CODEC_ID_AMR_NB, MKTAG('s','a','m','r') },
932 { AV_CODEC_ID_AMR_WB, MKTAG('s','a','w','b') },
36ef5369
AK
933 { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
934 { AV_CODEC_ID_NONE, 0 },
3c8d1447
BC
935};
936
e01fba55
CB
937static const AVCodecTag codec_f4v_tags[] = {
938 { AV_CODEC_ID_MP3, MKTAG('.','m','p','3') },
939 { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
940 { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
941 { AV_CODEC_ID_VP6A, MKTAG('V','P','6','A') },
942 { AV_CODEC_ID_VP6F, MKTAG('V','P','6','F') },
943 { AV_CODEC_ID_NONE, 0 },
944};
945
6b600285
BC
946static int mov_find_codec_tag(AVFormatContext *s, MOVTrack *track)
947{
73b7437f 948 int tag;
6b600285 949
5d561514
MS
950 if (track->mode == MODE_MP4 || track->mode == MODE_PSP)
951 tag = mp4_get_codec_tag(s, track);
952 else if (track->mode == MODE_ISM) {
6b600285 953 tag = mp4_get_codec_tag(s, track);
9200514a 954 if (!tag && track->par->codec_id == AV_CODEC_ID_WMAPRO)
5d561514
MS
955 tag = MKTAG('w', 'm', 'a', ' ');
956 } else if (track->mode == MODE_IPOD)
6b600285
BC
957 tag = ipod_get_codec_tag(s, track);
958 else if (track->mode & MODE_3GP)
9200514a 959 tag = ff_codec_get_tag(codec_3gp_tags, track->par->codec_id);
e01fba55 960 else if (track->mode == MODE_F4V)
9200514a 961 tag = ff_codec_get_tag(codec_f4v_tags, track->par->codec_id);
6b600285
BC
962 else
963 tag = mov_get_codec_tag(s, track);
964
965 return tag;
966}
967
aa9f4208
BC
968/** Write uuid atom.
969 * Needed to make file play in iPods running newest firmware
970 * goes after avcC atom in moov.trak.mdia.minf.stbl.stsd.avc1
971 */
ae628ec1 972static int mov_write_uuid_tag_ipod(AVIOContext *pb)
aa9f4208 973{
77eb5504 974 avio_wb32(pb, 28);
0abdb293 975 ffio_wfourcc(pb, "uuid");
77eb5504
AK
976 avio_wb32(pb, 0x6b6840f2);
977 avio_wb32(pb, 0x5f244fc5);
978 avio_wb32(pb, 0xba39a51b);
979 avio_wb32(pb, 0xcf0323f3);
980 avio_wb32(pb, 0x0);
aa9f4208
BC
981 return 28;
982}
983
4bf3c8f2
AC
984static const uint16_t fiel_data[] = {
985 0x0000, 0x0100, 0x0201, 0x0206, 0x0209, 0x020e
986};
987
988static int mov_write_fiel_tag(AVIOContext *pb, MOVTrack *track)
989{
990 unsigned mov_field_order = 0;
9200514a
AK
991 if (track->par->field_order < FF_ARRAY_ELEMS(fiel_data))
992 mov_field_order = fiel_data[track->par->field_order];
4bf3c8f2
AC
993 else
994 return 0;
995 avio_wb32(pb, 10);
996 ffio_wfourcc(pb, "fiel");
997 avio_wb16(pb, mov_field_order);
998 return 10;
999}
1000
ae628ec1 1001static int mov_write_subtitle_tag(AVIOContext *pb, MOVTrack *track)
f6204886 1002{
a2704c97 1003 int64_t pos = avio_tell(pb);
77eb5504
AK
1004 avio_wb32(pb, 0); /* size */
1005 avio_wl32(pb, track->tag); // store it byteswapped
1006 avio_wb32(pb, 0); /* Reserved */
1007 avio_wb16(pb, 0); /* Reserved */
1008 avio_wb16(pb, 1); /* Data-reference index */
f6204886 1009
9200514a 1010 if (track->par->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
6adf3bc4 1011 mov_write_esds_tag(pb, track);
9200514a
AK
1012 else if (track->par->extradata_size)
1013 avio_write(pb, track->par->extradata, track->par->extradata_size);
f6204886 1014
b7d3dd90 1015 return update_size(pb, pos);
f6204886
DC
1016}
1017
ae628ec1 1018static int mov_write_pasp_tag(AVIOContext *pb, MOVTrack *track)
b015be21
BC
1019{
1020 AVRational sar;
9200514a
AK
1021 av_reduce(&sar.num, &sar.den, track->par->sample_aspect_ratio.num,
1022 track->par->sample_aspect_ratio.den, INT_MAX);
b015be21 1023
77eb5504 1024 avio_wb32(pb, 16);
0abdb293 1025 ffio_wfourcc(pb, "pasp");
77eb5504
AK
1026 avio_wb32(pb, sar.num);
1027 avio_wb32(pb, sar.den);
b015be21
BC
1028 return 16;
1029}
1030
ae628ec1 1031static int mov_write_video_tag(AVIOContext *pb, MOVTrack *track)
1cb5f7fd 1032{
0ba5299a 1033 AVDictionaryEntry *encoder;
a2704c97 1034 int64_t pos = avio_tell(pb);
a92be9b8 1035 char compressor_name[32] = { 0 };
8cc7a34d 1036
77eb5504
AK
1037 avio_wb32(pb, 0); /* size */
1038 avio_wl32(pb, track->tag); // store it byteswapped
1039 avio_wb32(pb, 0); /* Reserved */
1040 avio_wb16(pb, 0); /* Reserved */
1041 avio_wb16(pb, 1); /* Data-reference index */
f578f938 1042
77eb5504
AK
1043 avio_wb16(pb, 0); /* Codec stream version */
1044 avio_wb16(pb, 0); /* Codec stream revision (=0) */
5997ed78 1045 if (track->mode == MODE_MOV) {
0abdb293 1046 ffio_wfourcc(pb, "FFMP"); /* Vendor */
9200514a 1047 if (track->par->codec_id == AV_CODEC_ID_RAWVIDEO) {
77eb5504
AK
1048 avio_wb32(pb, 0); /* Temporal Quality */
1049 avio_wb32(pb, 0x400); /* Spatial Quality = lossless*/
915282e5 1050 } else {
77eb5504
AK
1051 avio_wb32(pb, 0x200); /* Temporal Quality = normal */
1052 avio_wb32(pb, 0x200); /* Spatial Quality = normal */
915282e5 1053 }
5997ed78 1054 } else {
77eb5504
AK
1055 avio_wb32(pb, 0); /* Reserved */
1056 avio_wb32(pb, 0); /* Reserved */
1057 avio_wb32(pb, 0); /* Reserved */
5997ed78 1058 }
9200514a 1059 avio_wb16(pb, track->par->width); /* Video width */
77eb5504
AK
1060 avio_wb16(pb, track->height); /* Video height */
1061 avio_wb32(pb, 0x00480000); /* Horizontal resolution 72dpi */
1062 avio_wb32(pb, 0x00480000); /* Vertical resolution 72dpi */
1063 avio_wb32(pb, 0); /* Data size (= 0) */
1064 avio_wb16(pb, 1); /* Frame count (= 1) */
115329f1 1065
5997ed78 1066 /* FIXME not sure, ISO 14496-1 draft where it shall be set to 0 */
0ba5299a
AK
1067 if (track->mode == MODE_MOV &&
1068 (encoder = av_dict_get(track->st->metadata, "encoder", NULL, 0)))
1069 av_strlcpy(compressor_name, encoder->value, 32);
77eb5504
AK
1070 avio_w8(pb, strlen(compressor_name));
1071 avio_write(pb, compressor_name, 31);
115329f1 1072
9200514a
AK
1073 if (track->mode == MODE_MOV && track->par->bits_per_coded_sample)
1074 avio_wb16(pb, track->par->bits_per_coded_sample);
ccac8438 1075 else
77eb5504
AK
1076 avio_wb16(pb, 0x18); /* Reserved */
1077 avio_wb16(pb, 0xffff); /* Reserved */
21732063 1078 if (track->tag == MKTAG('m','p','4','v'))
f578f938 1079 mov_write_esds_tag(pb, track);
9200514a 1080 else if (track->par->codec_id == AV_CODEC_ID_H263)
f578f938 1081 mov_write_d263_tag(pb);
9200514a 1082 else if (track->par->codec_id == AV_CODEC_ID_SVQ3)
115329f1 1083 mov_write_svq3_tag(pb);
9200514a 1084 else if (track->par->codec_id == AV_CODEC_ID_DNXHD)
7b0f4c9a 1085 mov_write_avid_tag(pb, track);
9200514a 1086 else if (track->par->codec_id == AV_CODEC_ID_HEVC)
20b40a59 1087 mov_write_hvcc_tag(pb, track);
9200514a 1088 else if (track->par->codec_id == AV_CODEC_ID_H264) {
c1b8e6d8 1089 mov_write_avcc_tag(pb, track);
21732063 1090 if (track->mode == MODE_IPOD)
aa9f4208 1091 mov_write_uuid_tag_ipod(pb);
9200514a 1092 } else if (track->par->field_order != AV_FIELD_UNKNOWN)
4bf3c8f2 1093 mov_write_fiel_tag(pb, track);
9200514a 1094 else if (track->par->codec_id == AV_CODEC_ID_VC1 && track->vos_len > 0)
4ace130e 1095 mov_write_dvc1_tag(pb, track);
9200514a
AK
1096 else if (track->par->codec_id == AV_CODEC_ID_VP6F ||
1097 track->par->codec_id == AV_CODEC_ID_VP6A) {
e01fba55
CB
1098 /* Don't write any potential extradata here - the cropping
1099 * is signalled via the normal width/height fields. */
1100 } else if (track->vos_len > 0)
79e42311 1101 mov_write_glbl_tag(pb, track);
f578f938 1102
9200514a
AK
1103 if (track->par->sample_aspect_ratio.den && track->par->sample_aspect_ratio.num &&
1104 track->par->sample_aspect_ratio.den != track->par->sample_aspect_ratio.num) {
b015be21
BC
1105 mov_write_pasp_tag(pb, track);
1106 }
1107
b7d3dd90 1108 return update_size(pb, pos);
1cb5f7fd
MN
1109}
1110
ae628ec1 1111static int mov_write_rtp_tag(AVIOContext *pb, MOVTrack *track)
e977af6f 1112{
a2704c97 1113 int64_t pos = avio_tell(pb);
77eb5504 1114 avio_wb32(pb, 0); /* size */
0abdb293 1115 ffio_wfourcc(pb, "rtp ");
77eb5504
AK
1116 avio_wb32(pb, 0); /* Reserved */
1117 avio_wb16(pb, 0); /* Reserved */
1118 avio_wb16(pb, 1); /* Data-reference index */
e977af6f 1119
77eb5504
AK
1120 avio_wb16(pb, 1); /* Hint track version */
1121 avio_wb16(pb, 1); /* Highest compatible version */
1122 avio_wb32(pb, track->max_packet_size); /* Max packet size */
e977af6f 1123
77eb5504 1124 avio_wb32(pb, 12); /* size */
0abdb293 1125 ffio_wfourcc(pb, "tims");
77eb5504 1126 avio_wb32(pb, track->timescale);
e977af6f 1127
b7d3dd90 1128 return update_size(pb, pos);
e977af6f
MS
1129}
1130
b89e8759
LB
1131static int mov_write_tmcd_tag(AVIOContext *pb, MOVTrack *track)
1132{
1133 int64_t pos = avio_tell(pb);
1134
1135 avio_wb32(pb, 0); /* size */
1136 ffio_wfourcc(pb, "tmcd"); /* Data format */
1137 avio_wb32(pb, 0); /* Reserved */
1138 avio_wb32(pb, 1); /* Data reference index */
9200514a
AK
1139 if (track->par->extradata_size)
1140 avio_write(pb, track->par->extradata, track->par->extradata_size);
b89e8759
LB
1141 return update_size(pb, pos);
1142}
1143
9200514a 1144static int mov_write_stsd_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
1cb5f7fd 1145{
a2704c97 1146 int64_t pos = avio_tell(pb);
77eb5504 1147 avio_wb32(pb, 0); /* size */
0abdb293 1148 ffio_wfourcc(pb, "stsd");
77eb5504
AK
1149 avio_wb32(pb, 0); /* version & flags */
1150 avio_wb32(pb, 1); /* entry count */
9200514a 1151 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO)
f578f938 1152 mov_write_video_tag(pb, track);
9200514a
AK
1153 else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
1154 mov_write_audio_tag(s, pb, track);
1155 else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)
f6204886 1156 mov_write_subtitle_tag(pb, track);
9200514a 1157 else if (track->par->codec_tag == MKTAG('r','t','p',' '))
e977af6f 1158 mov_write_rtp_tag(pb, track);
9200514a 1159 else if (track->par->codec_tag == MKTAG('t','m','c','d'))
b89e8759 1160 mov_write_tmcd_tag(pb, track);
b7d3dd90 1161 return update_size(pb, pos);
1cb5f7fd
MN
1162}
1163
ae628ec1 1164static int mov_write_ctts_tag(AVIOContext *pb, MOVTrack *track)
b4712e3c 1165{
c3e92a6c 1166 MOVStts *ctts_entries;
b4712e3c
BC
1167 uint32_t entries = 0;
1168 uint32_t atom_size;
1169 int i;
1170
1171 ctts_entries = av_malloc((track->entry + 1) * sizeof(*ctts_entries)); /* worst case */
a8765852
HBL
1172 if (!ctts_entries)
1173 return AVERROR(ENOMEM);
b4712e3c 1174 ctts_entries[0].count = 1;
0aec3c5c 1175 ctts_entries[0].duration = track->cluster[0].cts;
21732063 1176 for (i = 1; i < track->entry; i++) {
0aec3c5c 1177 if (track->cluster[i].cts == ctts_entries[entries].duration) {
b4712e3c
BC
1178 ctts_entries[entries].count++; /* compress */
1179 } else {
1180 entries++;
0aec3c5c 1181 ctts_entries[entries].duration = track->cluster[i].cts;
b4712e3c
BC
1182 ctts_entries[entries].count = 1;
1183 }
1184 }
1185 entries++; /* last one */
1186 atom_size = 16 + (entries * 8);
77eb5504 1187 avio_wb32(pb, atom_size); /* size */
0abdb293 1188 ffio_wfourcc(pb, "ctts");
77eb5504
AK
1189 avio_wb32(pb, 0); /* version & flags */
1190 avio_wb32(pb, entries); /* entry count */
21732063 1191 for (i = 0; i < entries; i++) {
77eb5504
AK
1192 avio_wb32(pb, ctts_entries[i].count);
1193 avio_wb32(pb, ctts_entries[i].duration);
b4712e3c
BC
1194 }
1195 av_free(ctts_entries);
1196 return atom_size;
1197}
1198
e45ccf79 1199/* Time to sample atom */
ae628ec1 1200static int mov_write_stts_tag(AVIOContext *pb, MOVTrack *track)
1cb5f7fd 1201{
9731cf40 1202 MOVStts *stts_entries = NULL;
aa90239f
BC
1203 uint32_t entries = -1;
1204 uint32_t atom_size;
1205 int i;
1206
9200514a 1207 if (track->par->codec_type == AVMEDIA_TYPE_AUDIO && !track->audio_vbr) {
aa90239f 1208 stts_entries = av_malloc(sizeof(*stts_entries)); /* one entry */
a8765852
HBL
1209 if (!stts_entries)
1210 return AVERROR(ENOMEM);
b7d3dd90 1211 stts_entries[0].count = track->sample_count;
aa90239f
BC
1212 stts_entries[0].duration = 1;
1213 entries = 1;
1214 } else {
9731cf40
MS
1215 if (track->entry) {
1216 stts_entries = av_malloc(track->entry * sizeof(*stts_entries)); /* worst case */
1217 if (!stts_entries)
1218 return AVERROR(ENOMEM);
1219 }
21732063 1220 for (i = 0; i < track->entry; i++) {
681d1726 1221 int duration = get_cluster_duration(track, i);
aa90239f
BC
1222 if (i && duration == stts_entries[entries].duration) {
1223 stts_entries[entries].count++; /* compress */
1224 } else {
1225 entries++;
1226 stts_entries[entries].duration = duration;
1227 stts_entries[entries].count = 1;
1228 }
1229 }
1230 entries++; /* last one */
1231 }
1232 atom_size = 16 + (entries * 8);
77eb5504 1233 avio_wb32(pb, atom_size); /* size */
0abdb293 1234 ffio_wfourcc(pb, "stts");
77eb5504
AK
1235 avio_wb32(pb, 0); /* version & flags */
1236 avio_wb32(pb, entries); /* entry count */
21732063 1237 for (i = 0; i < entries; i++) {
77eb5504
AK
1238 avio_wb32(pb, stts_entries[i].count);
1239 avio_wb32(pb, stts_entries[i].duration);
aa90239f
BC
1240 }
1241 av_free(stts_entries);
1242 return atom_size;
1cb5f7fd
MN
1243}
1244
ae628ec1 1245static int mov_write_dref_tag(AVIOContext *pb)
1cb5f7fd 1246{
77eb5504 1247 avio_wb32(pb, 28); /* size */
0abdb293 1248 ffio_wfourcc(pb, "dref");
77eb5504
AK
1249 avio_wb32(pb, 0); /* version & flags */
1250 avio_wb32(pb, 1); /* entry count */
1cb5f7fd 1251
77eb5504 1252 avio_wb32(pb, 0xc); /* size */
0abdb293 1253 ffio_wfourcc(pb, "url ");
77eb5504 1254 avio_wb32(pb, 1); /* version & flags */
1cb5f7fd
MN
1255
1256 return 28;
1257}
1258
9200514a 1259static int mov_write_stbl_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
1cb5f7fd 1260{
a2704c97 1261 int64_t pos = avio_tell(pb);
77eb5504 1262 avio_wb32(pb, 0); /* size */
0abdb293 1263 ffio_wfourcc(pb, "stbl");
9200514a 1264 mov_write_stsd_tag(s, pb, track);
6e6d6dc0 1265 mov_write_stts_tag(pb, track);
9200514a
AK
1266 if ((track->par->codec_type == AVMEDIA_TYPE_VIDEO ||
1267 track->par->codec_tag == MKTAG('r','t','p',' ')) &&
b7d3dd90 1268 track->has_keyframes && track->has_keyframes < track->entry)
e1316b19
BC
1269 mov_write_stss_tag(pb, track, MOV_SYNC_SAMPLE);
1270 if (track->mode == MODE_MOV && track->flags & MOV_TRACK_STPS)
1271 mov_write_stss_tag(pb, track, MOV_PARTIAL_SYNC_SAMPLE);
9200514a 1272 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO &&
847bf598 1273 track->flags & MOV_TRACK_CTTS && track->entry)
b4712e3c 1274 mov_write_ctts_tag(pb, track);
6e6d6dc0
MN
1275 mov_write_stsc_tag(pb, track);
1276 mov_write_stsz_tag(pb, track);
1277 mov_write_stco_tag(pb, track);
b7d3dd90 1278 return update_size(pb, pos);
1cb5f7fd
MN
1279}
1280
ae628ec1 1281static int mov_write_dinf_tag(AVIOContext *pb)
1cb5f7fd 1282{
a2704c97 1283 int64_t pos = avio_tell(pb);
77eb5504 1284 avio_wb32(pb, 0); /* size */
0abdb293 1285 ffio_wfourcc(pb, "dinf");
6e6d6dc0 1286 mov_write_dref_tag(pb);
b7d3dd90 1287 return update_size(pb, pos);
1cb5f7fd
MN
1288}
1289
ae628ec1 1290static int mov_write_nmhd_tag(AVIOContext *pb)
f6204886 1291{
77eb5504 1292 avio_wb32(pb, 12);
0abdb293 1293 ffio_wfourcc(pb, "nmhd");
77eb5504 1294 avio_wb32(pb, 0);
f6204886
DC
1295 return 12;
1296}
1297
ae628ec1 1298static int mov_write_gmhd_tag(AVIOContext *pb)
f6204886 1299{
77eb5504 1300 avio_wb32(pb, 0x20); /* size */
0abdb293 1301 ffio_wfourcc(pb, "gmhd");
77eb5504 1302 avio_wb32(pb, 0x18); /* gmin size */
0abdb293 1303 ffio_wfourcc(pb, "gmin");/* generic media info */
77eb5504
AK
1304 avio_wb32(pb, 0); /* version & flags */
1305 avio_wb16(pb, 0x40); /* graphics mode = */
1306 avio_wb16(pb, 0x8000); /* opColor (r?) */
1307 avio_wb16(pb, 0x8000); /* opColor (g?) */
1308 avio_wb16(pb, 0x8000); /* opColor (b?) */
1309 avio_wb16(pb, 0); /* balance */
1310 avio_wb16(pb, 0); /* reserved */
f6204886
DC
1311 return 0x20;
1312}
1313
ae628ec1 1314static int mov_write_smhd_tag(AVIOContext *pb)
1cb5f7fd 1315{
77eb5504 1316 avio_wb32(pb, 16); /* size */
0abdb293 1317 ffio_wfourcc(pb, "smhd");
77eb5504
AK
1318 avio_wb32(pb, 0); /* version & flags */
1319 avio_wb16(pb, 0); /* reserved (balance, normally = 0) */
1320 avio_wb16(pb, 0); /* reserved */
1cb5f7fd
MN
1321 return 16;
1322}
1323
ae628ec1 1324static int mov_write_vmhd_tag(AVIOContext *pb)
1cb5f7fd 1325{
77eb5504 1326 avio_wb32(pb, 0x14); /* size (always 0x14) */
0abdb293 1327 ffio_wfourcc(pb, "vmhd");
77eb5504
AK
1328 avio_wb32(pb, 0x01); /* version & flags */
1329 avio_wb64(pb, 0); /* reserved (graphics mode = copy) */
1cb5f7fd
MN
1330 return 0x14;
1331}
1332
99e22b78
MG
1333static int is_clcp_track(MOVTrack *track)
1334{
1335 return track->tag == MKTAG('c','7','0','8') ||
1336 track->tag == MKTAG('c','6','0','8');
1337}
1338
9200514a 1339static int mov_write_hdlr_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
1cb5f7fd 1340{
985688b8 1341 const char *hdlr, *descr = NULL, *hdlr_type = NULL;
a2704c97 1342 int64_t pos = avio_tell(pb);
115329f1 1343
67400f6b
LB
1344 hdlr = "dhlr";
1345 hdlr_type = "url ";
1346 descr = "DataHandler";
1347
1348 if (track) {
bb270c08 1349 hdlr = (track->mode == MODE_MOV) ? "mhlr" : "\0\0\0\0";
9200514a 1350 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
bb270c08 1351 hdlr_type = "vide";
21732063 1352 descr = "VideoHandler";
9200514a 1353 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
bb270c08 1354 hdlr_type = "soun";
21732063 1355 descr = "SoundHandler";
9200514a 1356 } else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE) {
f94371b1
MN
1357 if (track->tag == MKTAG('t','x','3','g')) {
1358 hdlr_type = "sbtl";
1359 } else if (track->tag == MKTAG('m','p','4','s')) {
1360 hdlr_type = "subp";
99e22b78
MG
1361 } else if (is_clcp_track(track)) {
1362 hdlr_type = "clcp";
f94371b1
MN
1363 } else {
1364 hdlr_type = "text";
1365 }
f6204886 1366 descr = "SubtitleHandler";
9200514a 1367 } else if (track->par->codec_tag == MKTAG('r','t','p',' ')) {
e977af6f 1368 hdlr_type = "hint";
21732063 1369 descr = "HintHandler";
9200514a 1370 } else if (track->par->codec_tag == MKTAG('t','m','c','d')) {
67400f6b
LB
1371 hdlr_type = "tmcd";
1372 descr = "TimeCodeHandler";
1373 } else {
1374 char tag_buf[32];
1375 av_get_codec_tag_string(tag_buf, sizeof(tag_buf),
9200514a 1376 track->par->codec_tag);
67400f6b 1377
9200514a 1378 av_log(s, AV_LOG_WARNING,
67400f6b 1379 "Unknown hldr_type for %s / 0x%04X, writing dummy values\n",
9200514a 1380 tag_buf, track->par->codec_tag);
bb270c08 1381 }
da9cc22d
JS
1382 if (track->st) {
1383 // hdlr.name is used by some players to identify the content title
1384 // of the track. So if an alternate handler description is
1385 // specified, use it.
1386 AVDictionaryEntry *t;
1387 t = av_dict_get(track->st->metadata, "handler", NULL, 0);
1388 if (t && utf8len(t->value))
1389 descr = t->value;
1390 }
9a4d9388 1391 }
115329f1 1392
77eb5504 1393 avio_wb32(pb, 0); /* size */
0abdb293 1394 ffio_wfourcc(pb, "hdlr");
77eb5504
AK
1395 avio_wb32(pb, 0); /* Version & flags */
1396 avio_write(pb, hdlr, 4); /* handler */
0abdb293 1397 ffio_wfourcc(pb, hdlr_type); /* handler type */
21732063
MS
1398 avio_wb32(pb, 0); /* reserved */
1399 avio_wb32(pb, 0); /* reserved */
1400 avio_wb32(pb, 0); /* reserved */
606d48ce 1401 if (!track || track->mode == MODE_MOV)
77eb5504
AK
1402 avio_w8(pb, strlen(descr)); /* pascal string */
1403 avio_write(pb, descr, strlen(descr)); /* handler description */
606d48ce 1404 if (track && track->mode != MODE_MOV)
77eb5504 1405 avio_w8(pb, 0); /* c string */
b7d3dd90 1406 return update_size(pb, pos);
9a4d9388
RS
1407}
1408
ae628ec1 1409static int mov_write_hmhd_tag(AVIOContext *pb)
e977af6f
MS
1410{
1411 /* This atom must be present, but leaving the values at zero
1412 * seems harmless. */
77eb5504 1413 avio_wb32(pb, 28); /* size */
0abdb293 1414 ffio_wfourcc(pb, "hmhd");
77eb5504
AK
1415 avio_wb32(pb, 0); /* version, flags */
1416 avio_wb16(pb, 0); /* maxPDUsize */
1417 avio_wb16(pb, 0); /* avgPDUsize */
1418 avio_wb32(pb, 0); /* maxbitrate */
1419 avio_wb32(pb, 0); /* avgbitrate */
1420 avio_wb32(pb, 0); /* reserved */
e977af6f
MS
1421 return 28;
1422}
1423
9200514a 1424static int mov_write_minf_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
9a4d9388 1425{
a2704c97 1426 int64_t pos = avio_tell(pb);
77eb5504 1427 avio_wb32(pb, 0); /* size */
0abdb293 1428 ffio_wfourcc(pb, "minf");
9200514a 1429 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO)
9a4d9388 1430 mov_write_vmhd_tag(pb);
9200514a 1431 else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
9a4d9388 1432 mov_write_smhd_tag(pb);
9200514a 1433 else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE) {
99e22b78
MG
1434 if (track->tag == MKTAG('t','e','x','t') || is_clcp_track(track)) {
1435 mov_write_gmhd_tag(pb);
1436 } else {
1437 mov_write_nmhd_tag(pb);
1438 }
e977af6f
MS
1439 } else if (track->tag == MKTAG('r','t','p',' ')) {
1440 mov_write_hmhd_tag(pb);
b89e8759
LB
1441 } else if (track->tag == MKTAG('t','m','c','d')) {
1442 mov_write_gmhd_tag(pb);
f6204886 1443 }
9a4d9388 1444 if (track->mode == MODE_MOV) /* FIXME: Why do it for MODE_MOV only ? */
9200514a 1445 mov_write_hdlr_tag(s, pb, NULL);
9a4d9388 1446 mov_write_dinf_tag(pb);
9200514a 1447 mov_write_stbl_tag(s, pb, track);
b7d3dd90 1448 return update_size(pb, pos);
1cb5f7fd
MN
1449}
1450
00c67fe1
MS
1451static int mov_write_mdhd_tag(AVIOContext *pb, MOVMuxContext *mov,
1452 MOVTrack *track)
1cb5f7fd 1453{
b7d3dd90 1454 int version = track->track_duration < INT32_MAX ? 0 : 1;
a3a80ddc 1455
53026339
MS
1456 if (track->mode == MODE_ISM)
1457 version = 1;
1458
77eb5504 1459 (version == 1) ? avio_wb32(pb, 44) : avio_wb32(pb, 32); /* size */
0abdb293 1460 ffio_wfourcc(pb, "mdhd");
77eb5504
AK
1461 avio_w8(pb, version);
1462 avio_wb24(pb, 0); /* flags */
a3a80ddc 1463 if (version == 1) {
77eb5504
AK
1464 avio_wb64(pb, track->time);
1465 avio_wb64(pb, track->time);
a3a80ddc 1466 } else {
77eb5504
AK
1467 avio_wb32(pb, track->time); /* creation time */
1468 avio_wb32(pb, track->time); /* modification time */
a3a80ddc 1469 }
77eb5504 1470 avio_wb32(pb, track->timescale); /* time scale (sample rate for audio) */
00c67fe1 1471 if (!track->entry && mov->mode == MODE_ISM)
99a357f4 1472 (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
00c67fe1
MS
1473 else if (!track->entry)
1474 (version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0);
99a357f4
MS
1475 else
1476 (version == 1) ? avio_wb64(pb, track->track_duration) : avio_wb32(pb, track->track_duration); /* duration */
77eb5504
AK
1477 avio_wb16(pb, track->language); /* language */
1478 avio_wb16(pb, 0); /* reserved (quality) */
db8f4a92 1479
21732063 1480 if (version != 0 && track->mode == MODE_MOV) {
db8f4a92 1481 av_log(NULL, AV_LOG_ERROR,
21732063
MS
1482 "FATAL error, file duration too long for timebase, this file will not be\n"
1483 "playable with quicktime. Choose a different timebase or a different\n"
1484 "container format\n");
db8f4a92
MN
1485 }
1486
1cb5f7fd
MN
1487 return 32;
1488}
1489
9200514a
AK
1490static int mov_write_mdia_tag(AVFormatContext *s, AVIOContext *pb,
1491 MOVMuxContext *mov, MOVTrack *track)
1cb5f7fd 1492{
a2704c97 1493 int64_t pos = avio_tell(pb);
77eb5504 1494 avio_wb32(pb, 0); /* size */
0abdb293 1495 ffio_wfourcc(pb, "mdia");
00c67fe1 1496 mov_write_mdhd_tag(pb, mov, track);
9200514a
AK
1497 mov_write_hdlr_tag(s, pb, track);
1498 mov_write_minf_tag(s, pb, track);
b7d3dd90 1499 return update_size(pb, pos);
1cb5f7fd
MN
1500}
1501
f9072969
LB
1502static int mov_write_tkhd_tag(AVIOContext *pb, MOVMuxContext *mov,
1503 MOVTrack *track, AVStream *st)
1cb5f7fd 1504{
b7d3dd90 1505 int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE,
729ef3ba 1506 track->timescale, AV_ROUND_UP);
a3a80ddc 1507 int version = duration < INT32_MAX ? 0 : 1;
df2aa222 1508 int flags = MOV_TKHD_FLAG_IN_MOVIE;
f9072969
LB
1509 int group = 0;
1510
cf18e777
AK
1511 uint32_t *display_matrix = NULL;
1512 int display_matrix_size, i;
df2aa222 1513
f9072969
LB
1514 if (st) {
1515 if (mov->per_stream_grouping)
1516 group = st->index;
1517 else
9200514a 1518 group = st->codecpar->codec_type;
cf18e777
AK
1519
1520 display_matrix = (uint32_t*)av_stream_get_side_data(st, AV_PKT_DATA_DISPLAYMATRIX,
1521 &display_matrix_size);
529c0569 1522 if (display_matrix && display_matrix_size < 9 * sizeof(*display_matrix))
cf18e777 1523 display_matrix = NULL;
f9072969 1524 }
a3a80ddc 1525
df2aa222
LB
1526 if (track->flags & MOV_TRACK_ENABLED)
1527 flags |= MOV_TKHD_FLAG_ENABLED;
1528
53026339
MS
1529 if (track->mode == MODE_ISM)
1530 version = 1;
1531
77eb5504 1532 (version == 1) ? avio_wb32(pb, 104) : avio_wb32(pb, 92); /* size */
0abdb293 1533 ffio_wfourcc(pb, "tkhd");
77eb5504 1534 avio_w8(pb, version);
df2aa222 1535 avio_wb24(pb, flags);
a3a80ddc 1536 if (version == 1) {
77eb5504
AK
1537 avio_wb64(pb, track->time);
1538 avio_wb64(pb, track->time);
a3a80ddc 1539 } else {
77eb5504
AK
1540 avio_wb32(pb, track->time); /* creation time */
1541 avio_wb32(pb, track->time); /* modification time */
a3a80ddc 1542 }
b7d3dd90 1543 avio_wb32(pb, track->track_id); /* track-id */
77eb5504 1544 avio_wb32(pb, 0); /* reserved */
00c67fe1 1545 if (!track->entry && mov->mode == MODE_ISM)
99a357f4 1546 (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
00c67fe1
MS
1547 else if (!track->entry)
1548 (version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0);
99a357f4
MS
1549 else
1550 (version == 1) ? avio_wb64(pb, duration) : avio_wb32(pb, duration);
1cb5f7fd 1551
77eb5504
AK
1552 avio_wb32(pb, 0); /* reserved */
1553 avio_wb32(pb, 0); /* reserved */
7574cacb 1554 avio_wb16(pb, 0); /* layer */
f9072969 1555 avio_wb16(pb, group); /* alternate group) */
1cb5f7fd 1556 /* Volume, only for audio */
9200514a 1557 if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
77eb5504 1558 avio_wb16(pb, 0x0100);
1cb5f7fd 1559 else
77eb5504
AK
1560 avio_wb16(pb, 0);
1561 avio_wb16(pb, 0); /* reserved */
1cb5f7fd
MN
1562
1563 /* Matrix structure */
cf18e777
AK
1564 if (display_matrix) {
1565 for (i = 0; i < 9; i++)
1566 avio_wb32(pb, display_matrix[i]);
1567 } else {
1568 avio_wb32(pb, 0x00010000); /* reserved */
1569 avio_wb32(pb, 0x0); /* reserved */
1570 avio_wb32(pb, 0x0); /* reserved */
1571 avio_wb32(pb, 0x0); /* reserved */
1572 avio_wb32(pb, 0x00010000); /* reserved */
1573 avio_wb32(pb, 0x0); /* reserved */
1574 avio_wb32(pb, 0x0); /* reserved */
1575 avio_wb32(pb, 0x0); /* reserved */
1576 avio_wb32(pb, 0x40000000); /* reserved */
1577 }
1cb5f7fd
MN
1578
1579 /* Track width and height, for visual only */
9200514a
AK
1580 if (st && (track->par->codec_type == AVMEDIA_TYPE_VIDEO ||
1581 track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)) {
21732063 1582 if (track->mode == MODE_MOV) {
9200514a 1583 avio_wb32(pb, track->par->width << 16);
fffdee89 1584 avio_wb32(pb, track->height << 16);
ea1afa12 1585 } else {
77d207cb 1586 double sample_aspect_ratio = av_q2d(st->sample_aspect_ratio);
9200514a 1587 if (!sample_aspect_ratio || track->height != track->par->height)
77d207cb 1588 sample_aspect_ratio = 1;
9200514a 1589 avio_wb32(pb, sample_aspect_ratio * track->par->width * 0x10000);
21732063 1590 avio_wb32(pb, track->height * 0x10000);
ea1afa12 1591 }
21732063 1592 } else {
77eb5504
AK
1593 avio_wb32(pb, 0);
1594 avio_wb32(pb, 0);
1cb5f7fd
MN
1595 }
1596 return 0x5c;
1597}
1598
13ff92d1 1599static int mov_write_tapt_tag(AVIOContext *pb, MOVTrack *track)
ea1afa12 1600{
9200514a
AK
1601 int32_t width = av_rescale(track->par->sample_aspect_ratio.num, track->par->width,
1602 track->par->sample_aspect_ratio.den);
ea1afa12 1603
a2704c97 1604 int64_t pos = avio_tell(pb);
ea1afa12
MV
1605
1606 avio_wb32(pb, 0); /* size */
13ff92d1 1607 ffio_wfourcc(pb, "tapt");
ea1afa12
MV
1608
1609 avio_wb32(pb, 20);
13ff92d1 1610 ffio_wfourcc(pb, "clef");
ea1afa12
MV
1611 avio_wb32(pb, 0);
1612 avio_wb32(pb, width << 16);
9200514a 1613 avio_wb32(pb, track->par->height << 16);
802385db
AS
1614
1615 avio_wb32(pb, 20);
1616 ffio_wfourcc(pb, "prof");
1617 avio_wb32(pb, 0);
1618 avio_wb32(pb, width << 16);
9200514a 1619 avio_wb32(pb, track->par->height << 16);
ea1afa12
MV
1620
1621 avio_wb32(pb, 20);
13ff92d1 1622 ffio_wfourcc(pb, "enof");
ea1afa12 1623 avio_wb32(pb, 0);
9200514a
AK
1624 avio_wb32(pb, track->par->width << 16);
1625 avio_wb32(pb, track->par->height << 16);
ea1afa12 1626
b7d3dd90 1627 return update_size(pb, pos);
373211d8 1628}
ea1afa12 1629
8af18154 1630// This box seems important for the psp playback ... without it the movie seems to hang
dbb472cb
MS
1631static int mov_write_edts_tag(AVIOContext *pb, MOVMuxContext *mov,
1632 MOVTrack *track)
8af18154 1633{
b7d3dd90 1634 int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE,
c1691948
GP
1635 track->timescale, AV_ROUND_UP);
1636 int version = duration < INT32_MAX ? 0 : 1;
1637 int entry_size, entry_count, size;
c725faeb
MS
1638 int64_t delay, start_ct = track->start_cts;
1639 delay = av_rescale_rnd(track->start_dts + start_ct, MOV_TIMESCALE,
c1691948
GP
1640 track->timescale, AV_ROUND_DOWN);
1641 version |= delay < INT32_MAX ? 0 : 1;
1642
1643 entry_size = (version == 1) ? 20 : 12;
1644 entry_count = 1 + (delay > 0);
1645 size = 24 + entry_count * entry_size;
1646
1647 /* write the atom data */
1648 avio_wb32(pb, size);
0abdb293 1649 ffio_wfourcc(pb, "edts");
c1691948 1650 avio_wb32(pb, size - 8);
0abdb293 1651 ffio_wfourcc(pb, "elst");
c1691948
GP
1652 avio_w8(pb, version);
1653 avio_wb24(pb, 0); /* flags */
8af18154 1654
c1691948
GP
1655 avio_wb32(pb, entry_count);
1656 if (delay > 0) { /* add an empty edit to delay presentation */
95ee4e2c
MS
1657 /* In the positive delay case, the delay includes the cts
1658 * offset, and the second edit list entry below trims out
1659 * the same amount from the actual content. This makes sure
41ed7ab4 1660 * that the offset last sample is included in the edit
95ee4e2c 1661 * list duration as well. */
c1691948
GP
1662 if (version == 1) {
1663 avio_wb64(pb, delay);
1664 avio_wb64(pb, -1);
1665 } else {
1666 avio_wb32(pb, delay);
1667 avio_wb32(pb, -1);
1668 }
1669 avio_wb32(pb, 0x00010000);
72f80161
MN
1670 } else {
1671 /* Avoid accidentally ending up with start_ct = -1 which has got a
1672 * special meaning. Normally start_ct should end up positive or zero
1673 * here, but use FFMIN in case dts is a a small positive integer
1674 * rounded to 0 when represented in MOV_TIMESCALE units. */
c725faeb 1675 start_ct = -FFMIN(track->start_dts, 0);
95ee4e2c
MS
1676 /* Note, this delay is calculated from the pts of the first sample,
1677 * ensuring that we don't reduce the duration for cases with
1678 * dts<0 pts=0. */
72f80161 1679 duration += delay;
c1691948 1680 }
8af18154 1681
dbb472cb
MS
1682 /* For fragmented files, we don't know the full length yet. Setting
1683 * duration to 0 allows us to only specify the offset, including
1684 * the rest of the content (from all future fragments) without specifying
1685 * an explicit duration. */
1686 if (mov->flags & FF_MOV_FLAG_FRAGMENT)
1687 duration = 0;
1688
c1691948
GP
1689 /* duration */
1690 if (version == 1) {
1691 avio_wb64(pb, duration);
1692 avio_wb64(pb, start_ct);
1693 } else {
1694 avio_wb32(pb, duration);
1695 avio_wb32(pb, start_ct);
1696 }
77eb5504 1697 avio_wb32(pb, 0x00010000);
c1691948 1698 return size;
8af18154 1699}
1700
ae628ec1 1701static int mov_write_tref_tag(AVIOContext *pb, MOVTrack *track)
ddb63017 1702{
77eb5504 1703 avio_wb32(pb, 20); // size
0abdb293 1704 ffio_wfourcc(pb, "tref");
77eb5504
AK
1705 avio_wb32(pb, 12); // size (subatom)
1706 avio_wl32(pb, track->tref_tag);
1707 avio_wb32(pb, track->tref_id);
ddb63017
DC
1708 return 20;
1709}
1710
8af18154 1711// goes at the end of each track! ... Critical for PSP playback ("Incompatible data" without it)
ae628ec1 1712static int mov_write_uuid_tag_psp(AVIOContext *pb, MOVTrack *mov)
8af18154 1713{
77eb5504 1714 avio_wb32(pb, 0x34); /* size ... reports as 28 in mp4box! */
0abdb293
AK
1715 ffio_wfourcc(pb, "uuid");
1716 ffio_wfourcc(pb, "USMT");
77eb5504
AK
1717 avio_wb32(pb, 0x21d24fce);
1718 avio_wb32(pb, 0xbb88695c);
1719 avio_wb32(pb, 0xfac9c740);
1720 avio_wb32(pb, 0x1c); // another size here!
0abdb293 1721 ffio_wfourcc(pb, "MTDT");
77eb5504
AK
1722 avio_wb32(pb, 0x00010012);
1723 avio_wb32(pb, 0x0a);
1724 avio_wb32(pb, 0x55c40000);
1725 avio_wb32(pb, 0x1);
1726 avio_wb32(pb, 0x0);
8af18154 1727 return 0x34;
1728}
1729
8034130e 1730static int mov_write_udta_sdp(AVIOContext *pb, MOVTrack *track)
e977af6f 1731{
8034130e 1732 AVFormatContext *ctx = track->rtp_ctx;
e977af6f
MS
1733 char buf[1000] = "";
1734 int len;
1735
8034130e
LB
1736 ff_sdp_write_media(buf, sizeof(buf), ctx->streams[0], track->src_track,
1737 NULL, NULL, 0, 0, ctx);
1738 av_strlcatf(buf, sizeof(buf), "a=control:streamid=%d\r\n", track->track_id);
e977af6f
MS
1739 len = strlen(buf);
1740
77eb5504 1741 avio_wb32(pb, len + 24);
0abdb293 1742 ffio_wfourcc(pb, "udta");
77eb5504 1743 avio_wb32(pb, len + 16);
0abdb293 1744 ffio_wfourcc(pb, "hnti");
77eb5504 1745 avio_wb32(pb, len + 8);
0abdb293 1746 ffio_wfourcc(pb, "sdp ");
77eb5504 1747 avio_write(pb, buf, len);
e977af6f
MS
1748 return len + 24;
1749}
1750
da9cc22d
JS
1751static int mov_write_track_metadata(AVIOContext *pb, AVStream *st,
1752 const char *tag, const char *str)
1753{
1754 int64_t pos = avio_tell(pb);
1755 AVDictionaryEntry *t = av_dict_get(st->metadata, str, NULL, 0);
1756 if (!t || !utf8len(t->value))
1757 return 0;
1758
1759 avio_wb32(pb, 0); /* size */
1760 ffio_wfourcc(pb, tag); /* type */
1761 avio_write(pb, t->value, strlen(t->value)); /* UTF8 string value */
1762 return update_size(pb, pos);
1763}
1764
1765static int mov_write_track_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
1766 AVStream *st)
1767{
1768 AVIOContext *pb_buf;
1769 int ret, size;
1770 uint8_t *buf;
1771
e95c7a61 1772 if (!st)
da9cc22d
JS
1773 return 0;
1774
1775 ret = avio_open_dyn_buf(&pb_buf);
1776 if (ret < 0)
1777 return ret;
1778
1779 if (mov->mode & MODE_MP4)
1780 mov_write_track_metadata(pb_buf, st, "name", "title");
1781
1782 if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) {
1783 avio_wb32(pb, size + 8);
1784 ffio_wfourcc(pb, "udta");
1785 avio_write(pb, buf, size);
1786 }
1787 av_free(buf);
1788
1789 return 0;
1790}
1791
83988d58
MS
1792static int mov_write_trak_tag(AVIOContext *pb, MOVMuxContext *mov,
1793 MOVTrack *track, AVStream *st)
1cb5f7fd 1794{
a2704c97 1795 int64_t pos = avio_tell(pb);
847bf598
MS
1796 int entry_backup = track->entry;
1797 /* If we want to have an empty moov, but some samples already have been
1798 * buffered (delay_moov), pretend that no samples have been written yet. */
1799 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV)
1800 track->entry = 0;
1801
77eb5504 1802 avio_wb32(pb, 0); /* size */
0abdb293 1803 ffio_wfourcc(pb, "trak");
f9072969 1804 mov_write_tkhd_tag(pb, mov, track, st);
c725faeb 1805 if (track->start_dts != AV_NOPTS_VALUE &&
9a5ac36b 1806 (track->mode == MODE_PSP || track->flags & MOV_TRACK_CTTS ||
c725faeb 1807 track->start_dts || is_clcp_track(track))) {
1d8a0c1b
MS
1808 if (mov->use_editlist)
1809 mov_write_edts_tag(pb, mov, track); // PSP Movies require edts box
1810 else if ((track->entry && track->cluster[0].dts) || track->mode == MODE_PSP || is_clcp_track(track))
1811 av_log(mov->fc, AV_LOG_WARNING,
1812 "Not writing any edit list even though one would have been required\n");
83988d58 1813 }
ddb63017
DC
1814 if (track->tref_tag)
1815 mov_write_tref_tag(pb, track);
9200514a 1816 mov_write_mdia_tag(mov->fc, pb, mov, track);
115329f1 1817 if (track->mode == MODE_PSP)
21732063 1818 mov_write_uuid_tag_psp(pb, track); // PSP Movies require this uuid box
e977af6f 1819 if (track->tag == MKTAG('r','t','p',' '))
8034130e 1820 mov_write_udta_sdp(pb, track);
99e22b78 1821 if (track->mode == MODE_MOV) {
9200514a 1822 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
99e22b78
MG
1823 double sample_aspect_ratio = av_q2d(st->sample_aspect_ratio);
1824 if ((0.0 != sample_aspect_ratio && 1.0 != sample_aspect_ratio)) {
1825 mov_write_tapt_tag(pb, track);
1826 }
1827 }
1828 if (is_clcp_track(track)) {
ea1afa12 1829 mov_write_tapt_tag(pb, track);
99e22b78 1830 }
21732063 1831 }
da9cc22d 1832 mov_write_track_udta_tag(pb, mov, st);
847bf598 1833 track->entry = entry_backup;
b7d3dd90 1834 return update_size(pb, pos);
1cb5f7fd
MN
1835}
1836
ae628ec1 1837static int mov_write_iods_tag(AVIOContext *pb, MOVMuxContext *mov)
1cb5f7fd 1838{
d3b8bde2
AC
1839 int i, has_audio = 0, has_video = 0;
1840 int64_t pos = avio_tell(pb);
1841 int audio_profile = mov->iods_audio_profile;
1842 int video_profile = mov->iods_video_profile;
1843 for (i = 0; i < mov->nb_streams; i++) {
0f9eb916 1844 if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
9200514a
AK
1845 has_audio |= mov->tracks[i].par->codec_type == AVMEDIA_TYPE_AUDIO;
1846 has_video |= mov->tracks[i].par->codec_type == AVMEDIA_TYPE_VIDEO;
d3b8bde2
AC
1847 }
1848 }
1849 if (audio_profile < 0)
1850 audio_profile = 0xFF - has_audio;
1851 if (video_profile < 0)
1852 video_profile = 0xFF - has_video;
1853 avio_wb32(pb, 0x0); /* size */
0abdb293 1854 ffio_wfourcc(pb, "iods");
77eb5504 1855 avio_wb32(pb, 0); /* version & flags */
b7d3dd90 1856 put_descr(pb, 0x10, 7);
d3b8bde2
AC
1857 avio_wb16(pb, 0x004f);
1858 avio_w8(pb, 0xff);
1859 avio_w8(pb, 0xff);
1860 avio_w8(pb, audio_profile);
1861 avio_w8(pb, video_profile);
1862 avio_w8(pb, 0xff);
b7d3dd90 1863 return update_size(pb, pos);
1cb5f7fd
MN
1864}
1865
83988d58
MS
1866static int mov_write_trex_tag(AVIOContext *pb, MOVTrack *track)
1867{
1868 avio_wb32(pb, 0x20); /* size */
1869 ffio_wfourcc(pb, "trex");
1870 avio_wb32(pb, 0); /* version & flags */
b7d3dd90 1871 avio_wb32(pb, track->track_id); /* track ID */
83988d58
MS
1872 avio_wb32(pb, 1); /* default sample description index */
1873 avio_wb32(pb, 0); /* default sample duration */
1874 avio_wb32(pb, 0); /* default sample size */
1875 avio_wb32(pb, 0); /* default sample flags */
1876 return 0;
1877}
1878
1879static int mov_write_mvex_tag(AVIOContext *pb, MOVMuxContext *mov)
1880{
1881 int64_t pos = avio_tell(pb);
1882 int i;
1883 avio_wb32(pb, 0x0); /* size */
1884 ffio_wfourcc(pb, "mvex");
1885 for (i = 0; i < mov->nb_streams; i++)
1886 mov_write_trex_tag(pb, &mov->tracks[i]);
b7d3dd90 1887 return update_size(pb, pos);
83988d58
MS
1888}
1889
ae628ec1 1890static int mov_write_mvhd_tag(AVIOContext *pb, MOVMuxContext *mov)
1cb5f7fd 1891{
b7d3dd90
MS
1892 int max_track_id = 1, i;
1893 int64_t max_track_len_temp, max_track_len = 0;
a3a80ddc 1894 int version;
1cb5f7fd 1895
21732063 1896 for (i = 0; i < mov->nb_streams; i++) {
22de0f83 1897 if (mov->tracks[i].entry > 0 && mov->tracks[i].timescale) {
b7d3dd90
MS
1898 max_track_len_temp = av_rescale_rnd(mov->tracks[i].track_duration,
1899 MOV_TIMESCALE,
1900 mov->tracks[i].timescale,
1901 AV_ROUND_UP);
1902 if (max_track_len < max_track_len_temp)
1903 max_track_len = max_track_len_temp;
1904 if (max_track_id < mov->tracks[i].track_id)
1905 max_track_id = mov->tracks[i].track_id;
1cb5f7fd
MN
1906 }
1907 }
847bf598
MS
1908 /* If using delay_moov, make sure the output is the same as if no
1909 * samples had been written yet. */
1910 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
1911 max_track_len = 0;
1912 max_track_id = 1;
1913 }
a3a80ddc 1914
b7d3dd90 1915 version = max_track_len < UINT32_MAX ? 0 : 1;
77eb5504 1916 (version == 1) ? avio_wb32(pb, 120) : avio_wb32(pb, 108); /* size */
0abdb293 1917 ffio_wfourcc(pb, "mvhd");
77eb5504
AK
1918 avio_w8(pb, version);
1919 avio_wb24(pb, 0); /* flags */
a3a80ddc 1920 if (version == 1) {
77eb5504
AK
1921 avio_wb64(pb, mov->time);
1922 avio_wb64(pb, mov->time);
a3a80ddc 1923 } else {
77eb5504
AK
1924 avio_wb32(pb, mov->time); /* creation time */
1925 avio_wb32(pb, mov->time); /* modification time */
a3a80ddc 1926 }
77eb5504 1927 avio_wb32(pb, MOV_TIMESCALE);
b7d3dd90 1928 (version == 1) ? avio_wb64(pb, max_track_len) : avio_wb32(pb, max_track_len); /* duration of longest track */
1cb5f7fd 1929
77eb5504
AK
1930 avio_wb32(pb, 0x00010000); /* reserved (preferred rate) 1.0 = normal */
1931 avio_wb16(pb, 0x0100); /* reserved (preferred volume) 1.0 = normal */
1932 avio_wb16(pb, 0); /* reserved */
1933 avio_wb32(pb, 0); /* reserved */
1934 avio_wb32(pb, 0); /* reserved */
1cb5f7fd
MN
1935
1936 /* Matrix structure */
77eb5504
AK
1937 avio_wb32(pb, 0x00010000); /* reserved */
1938 avio_wb32(pb, 0x0); /* reserved */
1939 avio_wb32(pb, 0x0); /* reserved */
1940 avio_wb32(pb, 0x0); /* reserved */
1941 avio_wb32(pb, 0x00010000); /* reserved */
1942 avio_wb32(pb, 0x0); /* reserved */
1943 avio_wb32(pb, 0x0); /* reserved */
1944 avio_wb32(pb, 0x0); /* reserved */
1945 avio_wb32(pb, 0x40000000); /* reserved */
1946
1947 avio_wb32(pb, 0); /* reserved (preview time) */
1948 avio_wb32(pb, 0); /* reserved (preview duration) */
1949 avio_wb32(pb, 0); /* reserved (poster time) */
1950 avio_wb32(pb, 0); /* reserved (selection time) */
1951 avio_wb32(pb, 0); /* reserved (selection duration) */
1952 avio_wb32(pb, 0); /* reserved (current time) */
b7d3dd90 1953 avio_wb32(pb, max_track_id + 1); /* Next track id */
1cb5f7fd
MN
1954 return 0x6c;
1955}
1956
ae628ec1 1957static int mov_write_itunes_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov,
b6c50eb1
PB
1958 AVFormatContext *s)
1959{
77eb5504 1960 avio_wb32(pb, 33); /* size */
0abdb293 1961 ffio_wfourcc(pb, "hdlr");
77eb5504
AK
1962 avio_wb32(pb, 0);
1963 avio_wb32(pb, 0);
0abdb293
AK
1964 ffio_wfourcc(pb, "mdir");
1965 ffio_wfourcc(pb, "appl");
77eb5504
AK
1966 avio_wb32(pb, 0);
1967 avio_wb32(pb, 0);
1968 avio_w8(pb, 0);
6b174197 1969 return 33;
b6c50eb1
PB
1970}
1971
1972/* helper function to write a data tag with the specified string as data */
ae628ec1 1973static int mov_write_string_data_tag(AVIOContext *pb, const char *data, int lang, int long_style)
b6c50eb1 1974{
21732063 1975 if (long_style) {
6b174197 1976 int size = 16 + strlen(data);
77eb5504 1977 avio_wb32(pb, size); /* size */
0abdb293 1978 ffio_wfourcc(pb, "data");
77eb5504
AK
1979 avio_wb32(pb, 1);
1980 avio_wb32(pb, 0);
1981 avio_write(pb, data, strlen(data));
6b174197 1982 return size;
21732063 1983 } else {
fe3ab8ad
BC
1984 if (!lang)
1985 lang = ff_mov_iso639_to_lang("und", 1);
77eb5504
AK
1986 avio_wb16(pb, strlen(data)); /* string length */
1987 avio_wb16(pb, lang);
1988 avio_write(pb, data, strlen(data));
efda3395 1989 return strlen(data) + 4;
b6c50eb1 1990 }
b6c50eb1
PB
1991}
1992
21732063
MS
1993static int mov_write_string_tag(AVIOContext *pb, const char *name,
1994 const char *value, int lang, int long_style)
1995{
b6c50eb1 1996 int size = 0;
91208916 1997 if (value && value[0]) {
a2704c97 1998 int64_t pos = avio_tell(pb);
77eb5504 1999 avio_wb32(pb, 0); /* size */
0abdb293 2000 ffio_wfourcc(pb, name);
d9fc9ff3 2001 mov_write_string_data_tag(pb, value, lang, long_style);
b7d3dd90 2002 size = update_size(pb, pos);
b6c50eb1
PB
2003 }
2004 return size;
2005}
2006
f12a705e
MS
2007static AVDictionaryEntry *get_metadata_lang(AVFormatContext *s,
2008 const char *tag, int *lang)
b6c50eb1 2009{
f12a705e 2010 int l, len, len2;
d2d67e42 2011 AVDictionaryEntry *t, *t2 = NULL;
d9fc9ff3 2012 char tag2[16];
1ee2d448 2013
f12a705e
MS
2014 *lang = 0;
2015
d2d67e42 2016 if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
f12a705e 2017 return NULL;
1ee2d448 2018
d9fc9ff3
AJ
2019 len = strlen(t->key);
2020 snprintf(tag2, sizeof(tag2), "%s-", tag);
d2d67e42 2021 while ((t2 = av_dict_get(s->metadata, tag2, t2, AV_DICT_IGNORE_SUFFIX))) {
d9fc9ff3 2022 len2 = strlen(t2->key);
21732063
MS
2023 if (len2 == len + 4 && !strcmp(t->value, t2->value)
2024 && (l = ff_mov_iso639_to_lang(&t2->key[len2 - 3], 1)) >= 0) {
f12a705e
MS
2025 *lang = l;
2026 return t;
d9fc9ff3
AJ
2027 }
2028 }
f12a705e
MS
2029 return t;
2030}
2031
2032static int mov_write_string_metadata(AVFormatContext *s, AVIOContext *pb,
2033 const char *name, const char *tag,
2034 int long_style)
2035{
2036 int lang;
2037 AVDictionaryEntry *t = get_metadata_lang(s, tag, &lang);
2038 if (!t)
2039 return 0;
d9fc9ff3 2040 return mov_write_string_tag(pb, name, t->value, lang, long_style);
b6c50eb1
PB
2041}
2042
2043/* iTunes track number */
ae628ec1 2044static int mov_write_trkn_tag(AVIOContext *pb, MOVMuxContext *mov,
b6c50eb1
PB
2045 AVFormatContext *s)
2046{
d2d67e42 2047 AVDictionaryEntry *t = av_dict_get(s->metadata, "track", NULL, 0);
1ee2d448
AJ
2048 int size = 0, track = t ? atoi(t->value) : 0;
2049 if (track) {
77eb5504 2050 avio_wb32(pb, 32); /* size */
0abdb293 2051 ffio_wfourcc(pb, "trkn");
21732063
MS
2052 avio_wb32(pb, 24); /* size */
2053 ffio_wfourcc(pb, "data");
2054 avio_wb32(pb, 0); // 8 bytes empty
2055 avio_wb32(pb, 0);
2056 avio_wb16(pb, 0); // empty
2057 avio_wb16(pb, track); // track number
2058 avio_wb16(pb, 0); // total track number
2059 avio_wb16(pb, 0); // empty
6b174197 2060 size = 32;
b6c50eb1
PB
2061 }
2062 return size;
2063}
2064
2065/* iTunes meta data list */
ae628ec1 2066static int mov_write_ilst_tag(AVIOContext *pb, MOVMuxContext *mov,
b6c50eb1
PB
2067 AVFormatContext *s)
2068{
a2704c97 2069 int64_t pos = avio_tell(pb);
77eb5504 2070 avio_wb32(pb, 0); /* size */
0abdb293 2071 ffio_wfourcc(pb, "ilst");
1ee2d448 2072 mov_write_string_metadata(s, pb, "\251nam", "title" , 1);
ea4c4d7f 2073 mov_write_string_metadata(s, pb, "\251ART", "artist" , 1);
2cf9c7ef 2074 mov_write_string_metadata(s, pb, "aART", "album_artist", 1);
620af1a1 2075 mov_write_string_metadata(s, pb, "\251wrt", "composer" , 1);
1ee2d448 2076 mov_write_string_metadata(s, pb, "\251alb", "album" , 1);
ca76a119 2077 mov_write_string_metadata(s, pb, "\251day", "date" , 1);
e95c7a61
LB
2078 if (!mov_write_string_metadata(s, pb, "\251too", "encoding_tool", 1)) {
2079 if (!(s->flags & AVFMT_FLAG_BITEXACT))
2080 mov_write_string_tag(pb, "\251too", LIBAVFORMAT_IDENT, 0, 1);
2081 }
1ee2d448
AJ
2082 mov_write_string_metadata(s, pb, "\251cmt", "comment" , 1);
2083 mov_write_string_metadata(s, pb, "\251gen", "genre" , 1);
2084 mov_write_string_metadata(s, pb, "\251cpy", "copyright", 1);
2cf9c7ef
MM
2085 mov_write_string_metadata(s, pb, "\251grp", "grouping" , 1);
2086 mov_write_string_metadata(s, pb, "\251lyr", "lyrics" , 1);
7382902b
DC
2087 mov_write_string_metadata(s, pb, "desc", "description",1);
2088 mov_write_string_metadata(s, pb, "ldes", "synopsis" , 1);
2089 mov_write_string_metadata(s, pb, "tvsh", "show" , 1);
2090 mov_write_string_metadata(s, pb, "tven", "episode_id",1);
2091 mov_write_string_metadata(s, pb, "tvnn", "network" , 1);
b6c50eb1 2092 mov_write_trkn_tag(pb, mov, s);
b7d3dd90 2093 return update_size(pb, pos);
b6c50eb1
PB
2094}
2095
2096/* iTunes meta data tag */
ae628ec1 2097static int mov_write_meta_tag(AVIOContext *pb, MOVMuxContext *mov,
b6c50eb1
PB
2098 AVFormatContext *s)
2099{
2100 int size = 0;
a2704c97 2101 int64_t pos = avio_tell(pb);
77eb5504 2102 avio_wb32(pb, 0); /* size */
0abdb293 2103 ffio_wfourcc(pb, "meta");
77eb5504 2104 avio_wb32(pb, 0);
b97fb809
AJ
2105 mov_write_itunes_hdlr_tag(pb, mov, s);
2106 mov_write_ilst_tag(pb, mov, s);
b7d3dd90 2107 size = update_size(pb, pos);
b6c50eb1
PB
2108 return size;
2109}
115329f1 2110
ae628ec1 2111static int ascii_to_wc(AVIOContext *pb, const uint8_t *b)
07b7b06d
BC
2112{
2113 int val;
21732063 2114 while (*b) {
07b7b06d 2115 GET_UTF8(val, *b++, return -1;)
77eb5504 2116 avio_wb16(pb, val);
07b7b06d 2117 }
77eb5504 2118 avio_wb16(pb, 0x00);
07b7b06d
BC
2119 return 0;
2120}
2121
2122static uint16_t language_code(const char *str)
2123{
21732063
MS
2124 return (((str[0] - 0x60) & 0x1F) << 10) +
2125 (((str[1] - 0x60) & 0x1F) << 5) +
2126 (( str[2] - 0x60) & 0x1F);
07b7b06d
BC
2127}
2128
ae628ec1 2129static int mov_write_3gp_udta_tag(AVIOContext *pb, AVFormatContext *s,
c6e2c6c9
BC
2130 const char *tag, const char *str)
2131{
a2704c97 2132 int64_t pos = avio_tell(pb);
d2d67e42 2133 AVDictionaryEntry *t = av_dict_get(s->metadata, str, NULL, 0);
1ee2d448 2134 if (!t || !utf8len(t->value))
c6e2c6c9 2135 return 0;
77eb5504 2136 avio_wb32(pb, 0); /* size */
0abdb293 2137 ffio_wfourcc(pb, tag); /* type */
77eb5504 2138 avio_wb32(pb, 0); /* version + flags */
c6e2c6c9 2139 if (!strcmp(tag, "yrrc"))
77eb5504 2140 avio_wb16(pb, atoi(t->value));
c6e2c6c9 2141 else {
77eb5504 2142 avio_wb16(pb, language_code("eng")); /* language */
21732063 2143 avio_write(pb, t->value, strlen(t->value) + 1); /* UTF8 string value */
1ee2d448 2144 if (!strcmp(tag, "albm") &&
d2d67e42 2145 (t = av_dict_get(s->metadata, "track", NULL, 0)))
77eb5504 2146 avio_w8(pb, atoi(t->value));
c6e2c6c9 2147 }
b7d3dd90 2148 return update_size(pb, pos);
c6e2c6c9
BC
2149}
2150
ae628ec1 2151static int mov_write_chpl_tag(AVIOContext *pb, AVFormatContext *s)
dc75e4e3 2152{
a2704c97 2153 int64_t pos = avio_tell(pb);
dc75e4e3
DC
2154 int i, nb_chapters = FFMIN(s->nb_chapters, 255);
2155
77eb5504 2156 avio_wb32(pb, 0); // size
0abdb293 2157 ffio_wfourcc(pb, "chpl");
77eb5504
AK
2158 avio_wb32(pb, 0x01000000); // version + flags
2159 avio_wb32(pb, 0); // unknown
2160 avio_w8(pb, nb_chapters);
dc75e4e3
DC
2161
2162 for (i = 0; i < nb_chapters; i++) {
2163 AVChapter *c = s->chapters[i];
d2d67e42 2164 AVDictionaryEntry *t;
77eb5504 2165 avio_wb64(pb, av_rescale_q(c->start, c->time_base, (AVRational){1,10000000}));
dc75e4e3 2166
d2d67e42 2167 if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
dc75e4e3 2168 int len = FFMIN(strlen(t->value), 255);
77eb5504
AK
2169 avio_w8(pb, len);
2170 avio_write(pb, t->value, len);
dc75e4e3 2171 } else
77eb5504 2172 avio_w8(pb, 0);
dc75e4e3 2173 }
b7d3dd90 2174 return update_size(pb, pos);
dc75e4e3
DC
2175}
2176
ae628ec1 2177static int mov_write_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
69dde1ad
GB
2178 AVFormatContext *s)
2179{
ae628ec1 2180 AVIOContext *pb_buf;
d9432789 2181 int ret, size;
1ee2d448 2182 uint8_t *buf;
89a0d790 2183
b92c5452 2184 ret = avio_open_dyn_buf(&pb_buf);
21732063 2185 if (ret < 0)
1ee2d448 2186 return ret;
69dde1ad 2187
21732063
MS
2188 if (mov->mode & MODE_3GP) {
2189 mov_write_3gp_udta_tag(pb_buf, s, "perf", "artist");
2190 mov_write_3gp_udta_tag(pb_buf, s, "titl", "title");
2191 mov_write_3gp_udta_tag(pb_buf, s, "auth", "author");
2192 mov_write_3gp_udta_tag(pb_buf, s, "gnre", "genre");
2193 mov_write_3gp_udta_tag(pb_buf, s, "dscp", "comment");
2194 mov_write_3gp_udta_tag(pb_buf, s, "albm", "album");
2195 mov_write_3gp_udta_tag(pb_buf, s, "cprt", "copyright");
2196 mov_write_3gp_udta_tag(pb_buf, s, "yrrc", "date");
2197 } else if (mov->mode == MODE_MOV) { // the title field breaks gtkpod with mp4 and my suspicion is that stuff is not valid in mp4
2198 mov_write_string_metadata(s, pb_buf, "\251ART", "artist", 0);
2199 mov_write_string_metadata(s, pb_buf, "\251nam", "title", 0);
2200 mov_write_string_metadata(s, pb_buf, "\251aut", "author", 0);
2201 mov_write_string_metadata(s, pb_buf, "\251alb", "album", 0);
2202 mov_write_string_metadata(s, pb_buf, "\251day", "date", 0);
e95c7a61
LB
2203 if (!(s->flags & AVFMT_FLAG_BITEXACT))
2204 mov_write_string_metadata(s, pb_buf, "\251swr", "encoder", 0);
21732063
MS
2205 mov_write_string_metadata(s, pb_buf, "\251des", "comment", 0);
2206 mov_write_string_metadata(s, pb_buf, "\251gen", "genre", 0);
2207 mov_write_string_metadata(s, pb_buf, "\251cpy", "copyright", 0);
e0046bc9
MS
2208 mov_write_string_metadata(s, pb_buf, "\251mak", "make", 0);
2209 mov_write_string_metadata(s, pb_buf, "\251mod", "model", 0);
daec1651 2210 mov_write_string_metadata(s, pb_buf, "\251xyz", "location", 0);
21732063
MS
2211 } else {
2212 /* iTunes meta data */
2213 mov_write_meta_tag(pb_buf, mov, s);
2214 }
1ee2d448 2215
0897d2fd 2216 if (s->nb_chapters && !(mov->flags & FF_MOV_FLAG_DISABLE_CHPL))
21732063 2217 mov_write_chpl_tag(pb_buf, s);
dc75e4e3 2218
6dc7d80d 2219 if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) {
21732063 2220 avio_wb32(pb, size + 8);
0abdb293 2221 ffio_wfourcc(pb, "udta");
77eb5504 2222 avio_write(pb, buf, size);
89a0d790 2223 }
8b6e0aec 2224 av_free(buf);
89a0d790
BF
2225
2226 return 0;
69dde1ad
GB
2227}
2228
ae628ec1 2229static void mov_write_psp_udta_tag(AVIOContext *pb,
21732063 2230 const char *str, const char *lang, int type)
20e22af8 2231{
21732063
MS
2232 int len = utf8len(str) + 1;
2233 if (len <= 0)
d32d6def 2234 return;
21732063 2235 avio_wb16(pb, len * 2 + 10); /* size */
77eb5504
AK
2236 avio_wb32(pb, type); /* type */
2237 avio_wb16(pb, language_code(lang)); /* language */
2238 avio_wb16(pb, 0x01); /* ? */
20e22af8 2239 ascii_to_wc(pb, str);
20e22af8
BC
2240}
2241
ae628ec1 2242static int mov_write_uuidusmt_tag(AVIOContext *pb, AVFormatContext *s)
dcfdb046 2243{
d2d67e42 2244 AVDictionaryEntry *title = av_dict_get(s->metadata, "title", NULL, 0);
bc5c918e 2245 int64_t pos, pos2;
dcfdb046 2246
1ee2d448 2247 if (title) {
a2704c97 2248 pos = avio_tell(pb);
77eb5504 2249 avio_wb32(pb, 0); /* size placeholder*/
0abdb293
AK
2250 ffio_wfourcc(pb, "uuid");
2251 ffio_wfourcc(pb, "USMT");
77eb5504
AK
2252 avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
2253 avio_wb32(pb, 0xbb88695c);
2254 avio_wb32(pb, 0xfac9c740);
dcfdb046 2255
a2704c97 2256 pos2 = avio_tell(pb);
77eb5504 2257 avio_wb32(pb, 0); /* size placeholder*/
0abdb293 2258 ffio_wfourcc(pb, "MTDT");
77eb5504 2259 avio_wb16(pb, 4);
dcfdb046 2260
7cf0e16f 2261 // ?
77eb5504
AK
2262 avio_wb16(pb, 0x0C); /* size */
2263 avio_wb32(pb, 0x0B); /* type */
2264 avio_wb16(pb, language_code("und")); /* language */
2265 avio_wb16(pb, 0x0); /* ? */
2266 avio_wb16(pb, 0x021C); /* data */
7cf0e16f 2267
d32d6def 2268 mov_write_psp_udta_tag(pb, LIBAVCODEC_IDENT, "eng", 0x04);
1ee2d448 2269 mov_write_psp_udta_tag(pb, title->value, "eng", 0x01);
d32d6def
BC
2270 mov_write_psp_udta_tag(pb, "2006/04/01 11:11:11", "und", 0x03);
2271
b7d3dd90
MS
2272 update_size(pb, pos2);
2273 return update_size(pb, pos);
dcfdb046
BL
2274 }
2275
d32d6def 2276 return 0;
dcfdb046
BL
2277}
2278
ae628ec1 2279static int mov_write_moov_tag(AVIOContext *pb, MOVMuxContext *mov,
69dde1ad 2280 AVFormatContext *s)
1cb5f7fd 2281{
b29af723 2282 int i;
a2704c97 2283 int64_t pos = avio_tell(pb);
77eb5504 2284 avio_wb32(pb, 0); /* size placeholder*/
0abdb293 2285 ffio_wfourcc(pb, "moov");
1cb5f7fd 2286
21732063 2287 for (i = 0; i < mov->nb_streams; i++) {
83988d58
MS
2288 if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
2289 continue;
e45ccf79 2290
21732063
MS
2291 mov->tracks[i].time = mov->time;
2292 mov->tracks[i].track_id = i + 1;
1cb5f7fd
MN
2293 }
2294
ddb63017 2295 if (mov->chapter_track)
21732063 2296 for (i = 0; i < s->nb_streams; i++) {
ddb63017 2297 mov->tracks[i].tref_tag = MKTAG('c','h','a','p');
21732063 2298 mov->tracks[i].tref_id = mov->tracks[mov->chapter_track].track_id;
ddb63017 2299 }
e977af6f 2300 for (i = 0; i < mov->nb_streams; i++) {
ca489564
JS
2301 MOVTrack *track = &mov->tracks[i];
2302 if (track->tag == MKTAG('r','t','p',' ')) {
2303 track->tref_tag = MKTAG('h','i','n','t');
2304 track->tref_id = mov->tracks[track->src_track].track_id;
9200514a 2305 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
ca489564
JS
2306 int * fallback, size;
2307 fallback = (int*)av_stream_get_side_data(track->st,
2308 AV_PKT_DATA_FALLBACK_TRACK,
2309 &size);
2310 if (fallback != NULL && size == sizeof(int)) {
2311 if (*fallback >= 0 && *fallback < mov->nb_streams) {
2312 track->tref_tag = MKTAG('f','a','l','l');
2313 track->tref_id = mov->tracks[*fallback].track_id;
2314 }
2315 }
e977af6f
MS
2316 }
2317 }
ddb63017 2318
6e6d6dc0 2319 mov_write_mvhd_tag(pb, mov);
d3b8bde2
AC
2320 if (mov->mode != MODE_MOV && !mov->iods_skip)
2321 mov_write_iods_tag(pb, mov);
21732063 2322 for (i = 0; i < mov->nb_streams; i++) {
83988d58
MS
2323 if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_FRAGMENT) {
2324 mov_write_trak_tag(pb, mov, &(mov->tracks[i]), i < s->nb_streams ? s->streams[i] : NULL);
1cb5f7fd
MN
2325 }
2326 }
83988d58
MS
2327 if (mov->flags & FF_MOV_FLAG_FRAGMENT)
2328 mov_write_mvex_tag(pb, mov); /* QuickTime requires trak to precede this */
1cb5f7fd 2329
dcfdb046
BL
2330 if (mov->mode == MODE_PSP)
2331 mov_write_uuidusmt_tag(pb, s);
c6e2c6c9 2332 else
e344c1ea 2333 mov_write_udta_tag(pb, mov, s);
69dde1ad 2334
b7d3dd90 2335 return update_size(pb, pos);
1cb5f7fd
MN
2336}
2337
f5322104
MS
2338static void param_write_int(AVIOContext *pb, const char *name, int value)
2339{
2340 avio_printf(pb, "<param name=\"%s\" value=\"%d\" valuetype=\"data\"/>\n", name, value);
2341}
2342
2343static void param_write_string(AVIOContext *pb, const char *name, const char *value)
2344{
2345 avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, value);
2346}
2347
2348static void param_write_hex(AVIOContext *pb, const char *name, const uint8_t *value, int len)
2349{
2350 char buf[150];
21732063 2351 len = FFMIN(sizeof(buf) / 2 - 1, len);
f5322104 2352 ff_data_to_hex(buf, value, len, 0);
21732063 2353 buf[2 * len] = '\0';
f5322104
MS
2354 avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, buf);
2355}
2356
f5322104
MS
2357static int mov_write_isml_manifest(AVIOContext *pb, MOVMuxContext *mov)
2358{
2359 int64_t pos = avio_tell(pb);
2360 int i;
5afb94c8 2361 static const uint8_t uuid[] = {
f5322104
MS
2362 0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd,
2363 0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66
2364 };
2365
2366 avio_wb32(pb, 0);
2367 ffio_wfourcc(pb, "uuid");
2368 avio_write(pb, uuid, sizeof(uuid));
2369 avio_wb32(pb, 0);
2370
2371 avio_printf(pb, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
2372 avio_printf(pb, "<smil xmlns=\"http://www.w3.org/2001/SMIL20/Language\">\n");
2373 avio_printf(pb, "<head>\n");
2374 avio_printf(pb, "<meta name=\"creator\" content=\"%s\" />\n",
2375 LIBAVFORMAT_IDENT);
2376 avio_printf(pb, "</head>\n");
2377 avio_printf(pb, "<body>\n");
2378 avio_printf(pb, "<switch>\n");
2379 for (i = 0; i < mov->nb_streams; i++) {
2380 MOVTrack *track = &mov->tracks[i];
2381 const char *type;
b7d3dd90 2382 /* track->track_id is initialized in write_moov, and thus isn't known
f5322104
MS
2383 * here yet */
2384 int track_id = i + 1;
2385
9200514a 2386 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
f5322104 2387 type = "video";
9200514a 2388 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
f5322104
MS
2389 type = "audio";
2390 } else {
2391 continue;
2392 }
2393 avio_printf(pb, "<%s systemBitrate=\"%d\">\n", type,
9200514a
AK
2394 track->par->bit_rate);
2395 param_write_int(pb, "systemBitrate", track->par->bit_rate);
f5322104 2396 param_write_int(pb, "trackID", track_id);
9200514a
AK
2397 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
2398 if (track->par->codec_id == AV_CODEC_ID_H264) {
d5ed5e7d 2399 uint8_t *ptr;
9200514a
AK
2400 int size = track->par->extradata_size;
2401 if (!ff_avc_write_annexb_extradata(track->par->extradata, &ptr,
d5ed5e7d
MS
2402 &size)) {
2403 param_write_hex(pb, "CodecPrivateData",
9200514a 2404 ptr ? ptr : track->par->extradata,
d5ed5e7d
MS
2405 size);
2406 av_free(ptr);
2407 }
f5322104 2408 param_write_string(pb, "FourCC", "H264");
9200514a 2409 } else if (track->par->codec_id == AV_CODEC_ID_VC1) {
f5322104 2410 param_write_string(pb, "FourCC", "WVC1");
9200514a
AK
2411 param_write_hex(pb, "CodecPrivateData", track->par->extradata,
2412 track->par->extradata_size);
f5322104 2413 }
9200514a
AK
2414 param_write_int(pb, "MaxWidth", track->par->width);
2415 param_write_int(pb, "MaxHeight", track->par->height);
2416 param_write_int(pb, "DisplayWidth", track->par->width);
2417 param_write_int(pb, "DisplayHeight", track->par->height);
f5322104 2418 } else {
9200514a 2419 if (track->par->codec_id == AV_CODEC_ID_AAC) {
f5322104 2420 param_write_string(pb, "FourCC", "AACL");
9200514a 2421 } else if (track->par->codec_id == AV_CODEC_ID_WMAPRO) {
f5322104
MS
2422 param_write_string(pb, "FourCC", "WMAP");
2423 }
9200514a
AK
2424 param_write_hex(pb, "CodecPrivateData", track->par->extradata,
2425 track->par->extradata_size);
f5322104 2426 param_write_int(pb, "AudioTag", ff_codec_get_tag(ff_codec_wav_tags,
9200514a
AK
2427 track->par->codec_id));
2428 param_write_int(pb, "Channels", track->par->channels);
2429 param_write_int(pb, "SamplingRate", track->par->sample_rate);
f5322104 2430 param_write_int(pb, "BitsPerSample", 16);
9200514a
AK
2431 param_write_int(pb, "PacketSize", track->par->block_align ?
2432 track->par->block_align : 4);
f5322104
MS
2433 }
2434 avio_printf(pb, "</%s>\n", type);
2435 }
2436 avio_printf(pb, "</switch>\n");
2437 avio_printf(pb, "</body>\n");
2438 avio_printf(pb, "</smil>\n");
2439
b7d3dd90 2440 return update_size(pb, pos);
f5322104
MS
2441}
2442
83988d58
MS
2443static int mov_write_mfhd_tag(AVIOContext *pb, MOVMuxContext *mov)
2444{
2445 avio_wb32(pb, 16);
2446 ffio_wfourcc(pb, "mfhd");
2447 avio_wb32(pb, 0);
2448 avio_wb32(pb, mov->fragments);
2449 return 0;
2450}
2451
00d751d4
MS
2452static uint32_t get_sample_flags(MOVTrack *track, MOVIentry *entry)
2453{
2454 return entry->flags & MOV_SYNC_SAMPLE ? MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO :
2455 (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC);
2456}
2457
e7bf085b
MS
2458static int mov_write_tfhd_tag(AVIOContext *pb, MOVMuxContext *mov,
2459 MOVTrack *track, int64_t moof_offset)
83988d58
MS
2460{
2461 int64_t pos = avio_tell(pb);
73328f24
MS
2462 uint32_t flags = MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
2463 MOV_TFHD_BASE_DATA_OFFSET;
83988d58 2464 if (!track->entry) {
73328f24 2465 flags |= MOV_TFHD_DURATION_IS_EMPTY;
83988d58 2466 } else {
73328f24 2467 flags |= MOV_TFHD_DEFAULT_FLAGS;
83988d58 2468 }
e7bf085b
MS
2469 if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET)
2470 flags &= ~MOV_TFHD_BASE_DATA_OFFSET;
cf589faa
MS
2471 if (mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) {
2472 flags &= ~MOV_TFHD_BASE_DATA_OFFSET;
2473 flags |= MOV_TFHD_DEFAULT_BASE_IS_MOOF;
2474 }
83988d58 2475
51df7b23
MS
2476 /* Don't set a default sample size, the silverlight player refuses
2477 * to play files with that set. Don't set a default sample duration,
40bbbce7
JH
2478 * WMP freaks out if it is set. Don't set a base data offset, PIFF
2479 * file format says it MUST NOT be set. */
4ddd54da 2480 if (track->mode == MODE_ISM)
40bbbce7
JH
2481 flags &= ~(MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
2482 MOV_TFHD_BASE_DATA_OFFSET);
4ddd54da 2483
83988d58
MS
2484 avio_wb32(pb, 0); /* size placeholder */
2485 ffio_wfourcc(pb, "tfhd");
2486 avio_w8(pb, 0); /* version */
2487 avio_wb24(pb, flags);
2488
b7d3dd90 2489 avio_wb32(pb, track->track_id); /* track-id */
73328f24 2490 if (flags & MOV_TFHD_BASE_DATA_OFFSET)
83988d58 2491 avio_wb64(pb, moof_offset);
73328f24 2492 if (flags & MOV_TFHD_DEFAULT_DURATION) {
f3dab5fb 2493 track->default_duration = get_cluster_duration(track, 0);
83988d58
MS
2494 avio_wb32(pb, track->default_duration);
2495 }
73328f24 2496 if (flags & MOV_TFHD_DEFAULT_SIZE) {
83988d58
MS
2497 track->default_size = track->entry ? track->cluster[0].size : 1;
2498 avio_wb32(pb, track->default_size);
2499 } else
2500 track->default_size = -1;
2501
73328f24 2502 if (flags & MOV_TFHD_DEFAULT_FLAGS) {
00d751d4
MS
2503 /* Set the default flags based on the second sample, if available.
2504 * If the first sample is different, that can be signaled via a separate field. */
2505 if (track->entry > 1)
2506 track->default_sample_flags = get_sample_flags(track, &track->cluster[1]);
2507 else
2508 track->default_sample_flags =
9200514a 2509 track->par->codec_type == AVMEDIA_TYPE_VIDEO ?
00d751d4
MS
2510 (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC) :
2511 MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO;
83988d58
MS
2512 avio_wb32(pb, track->default_sample_flags);
2513 }
2514
b7d3dd90 2515 return update_size(pb, pos);
83988d58
MS
2516}
2517
e7bf085b 2518static int mov_write_trun_tag(AVIOContext *pb, MOVMuxContext *mov,
50ff0c05
MS
2519 MOVTrack *track, int moof_size,
2520 int first, int end)
83988d58
MS
2521{
2522 int64_t pos = avio_tell(pb);
3eec23f3 2523 uint32_t flags = MOV_TRUN_DATA_OFFSET;
83988d58
MS
2524 int i;
2525
50ff0c05 2526 for (i = first; i < end; i++) {
681d1726 2527 if (get_cluster_duration(track, i) != track->default_duration)
3eec23f3 2528 flags |= MOV_TRUN_SAMPLE_DURATION;
83988d58 2529 if (track->cluster[i].size != track->default_size)
3eec23f3 2530 flags |= MOV_TRUN_SAMPLE_SIZE;
50ff0c05 2531 if (i > first && get_sample_flags(track, &track->cluster[i]) != track->default_sample_flags)
3eec23f3 2532 flags |= MOV_TRUN_SAMPLE_FLAGS;
83988d58 2533 }
46d4d857
MS
2534 if (!(flags & MOV_TRUN_SAMPLE_FLAGS) && track->entry > 0 &&
2535 get_sample_flags(track, &track->cluster[0]) != track->default_sample_flags)
3eec23f3 2536 flags |= MOV_TRUN_FIRST_SAMPLE_FLAGS;
83988d58 2537 if (track->flags & MOV_TRACK_CTTS)
3eec23f3 2538 flags |= MOV_TRUN_SAMPLE_CTS;
83988d58
MS
2539
2540 avio_wb32(pb, 0); /* size placeholder */
2541 ffio_wfourcc(pb, "trun");
2542 avio_w8(pb, 0); /* version */
2543 avio_wb24(pb, flags);
2544
50ff0c05 2545 avio_wb32(pb, end - first); /* sample count */
e7bf085b 2546 if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET &&
e7d20f12 2547 !(mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) &&
573b1de2 2548 !mov->first_trun)
e7bf085b
MS
2549 avio_wb32(pb, 0); /* Later tracks follow immediately after the previous one */
2550 else
2551 avio_wb32(pb, moof_size + 8 + track->data_offset +
50ff0c05 2552 track->cluster[first].pos); /* data offset */
3eec23f3 2553 if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS)
50ff0c05 2554 avio_wb32(pb, get_sample_flags(track, &track->cluster[first]));
83988d58 2555
50ff0c05 2556 for (i = first; i < end; i++) {
3eec23f3 2557 if (flags & MOV_TRUN_SAMPLE_DURATION)
681d1726 2558 avio_wb32(pb, get_cluster_duration(track, i));
3eec23f3 2559 if (flags & MOV_TRUN_SAMPLE_SIZE)
83988d58 2560 avio_wb32(pb, track->cluster[i].size);
3eec23f3 2561 if (flags & MOV_TRUN_SAMPLE_FLAGS)
83988d58 2562 avio_wb32(pb, get_sample_flags(track, &track->cluster[i]));
3eec23f3 2563 if (flags & MOV_TRUN_SAMPLE_CTS)
83988d58
MS
2564 avio_wb32(pb, track->cluster[i].cts);
2565 }
2566
573b1de2 2567 mov->first_trun = 0;
b7d3dd90 2568 return update_size(pb, pos);
83988d58
MS
2569}
2570
4ddd54da
MS
2571static int mov_write_tfxd_tag(AVIOContext *pb, MOVTrack *track)
2572{
2573 int64_t pos = avio_tell(pb);
5afb94c8 2574 static const uint8_t uuid[] = {
4ddd54da
MS
2575 0x6d, 0x1d, 0x9b, 0x05, 0x42, 0xd5, 0x44, 0xe6,
2576 0x80, 0xe2, 0x14, 0x1d, 0xaf, 0xf7, 0x57, 0xb2
2577 };
2578
2579 avio_wb32(pb, 0); /* size placeholder */
2580 ffio_wfourcc(pb, "uuid");
2581 avio_write(pb, uuid, sizeof(uuid));
2582 avio_w8(pb, 1);
2583 avio_wb24(pb, 0);
5cf892d6
MS
2584 avio_wb64(pb, track->start_dts + track->frag_start +
2585 track->cluster[0].cts);
67a29123
MS
2586 avio_wb64(pb, track->end_pts -
2587 (track->cluster[0].dts + track->cluster[0].cts));
4ddd54da 2588
b7d3dd90 2589 return update_size(pb, pos);
4ddd54da
MS
2590}
2591
2592static int mov_write_tfrf_tag(AVIOContext *pb, MOVMuxContext *mov,
2593 MOVTrack *track, int entry)
2594{
2595 int n = track->nb_frag_info - 1 - entry, i;
2596 int size = 8 + 16 + 4 + 1 + 16*n;
5afb94c8 2597 static const uint8_t uuid[] = {
4ddd54da
MS
2598 0xd4, 0x80, 0x7e, 0xf2, 0xca, 0x39, 0x46, 0x95,
2599 0x8e, 0x54, 0x26, 0xcb, 0x9e, 0x46, 0xa7, 0x9f
2600 };
2601
2602 if (entry < 0)
2603 return 0;
2604
2605 avio_seek(pb, track->frag_info[entry].tfrf_offset, SEEK_SET);
2606 avio_wb32(pb, size);
2607 ffio_wfourcc(pb, "uuid");
2608 avio_write(pb, uuid, sizeof(uuid));
2609 avio_w8(pb, 1);
2610 avio_wb24(pb, 0);
2611 avio_w8(pb, n);
2612 for (i = 0; i < n; i++) {
2613 int index = entry + 1 + i;
2614 avio_wb64(pb, track->frag_info[index].time);
2615 avio_wb64(pb, track->frag_info[index].duration);
2616 }
2617 if (n < mov->ism_lookahead) {
21732063 2618 int free_size = 16 * (mov->ism_lookahead - n);
4ddd54da
MS
2619 avio_wb32(pb, free_size);
2620 ffio_wfourcc(pb, "free");
2621 for (i = 0; i < free_size - 8; i++)
2622 avio_w8(pb, 0);
2623 }
2624
2625 return 0;
2626}
2627
2628static int mov_write_tfrf_tags(AVIOContext *pb, MOVMuxContext *mov,
2629 MOVTrack *track)
2630{
2631 int64_t pos = avio_tell(pb);
2632 int i;
2633 for (i = 0; i < mov->ism_lookahead; i++) {
2634 /* Update the tfrf tag for the last ism_lookahead fragments,
2635 * nb_frag_info - 1 is the next fragment to be written. */
2636 mov_write_tfrf_tag(pb, mov, track, track->nb_frag_info - 2 - i);
2637 }
2638 avio_seek(pb, pos, SEEK_SET);
2639 return 0;
2640}
2641
40ed1cbf
MS
2642static int mov_add_tfra_entries(AVIOContext *pb, MOVMuxContext *mov, int tracks,
2643 int size)
2d9d6afb
MS
2644{
2645 int i;
2646 for (i = 0; i < mov->nb_streams; i++) {
2647 MOVTrack *track = &mov->tracks[i];
2648 MOVFragmentInfo *info;
2649 if ((tracks >= 0 && i != tracks) || !track->entry)
2650 continue;
2651 track->nb_frag_info++;
2652 if (track->nb_frag_info >= track->frag_info_capacity) {
2653 unsigned new_capacity = track->nb_frag_info + MOV_FRAG_INFO_ALLOC_INCREMENT;
2654 if (av_reallocp_array(&track->frag_info,
2655 new_capacity,
2656 sizeof(*track->frag_info)))
2657 return AVERROR(ENOMEM);
2658 track->frag_info_capacity = new_capacity;
2659 }
2660 info = &track->frag_info[track->nb_frag_info - 1];
2661 info->offset = avio_tell(pb);
40ed1cbf 2662 info->size = size;
2d9d6afb
MS
2663 // Try to recreate the original pts for the first packet
2664 // from the fields we have stored
2665 info->time = track->start_dts + track->frag_start +
2666 track->cluster[0].cts;
67a29123
MS
2667 info->duration = track->end_pts -
2668 (track->cluster[0].dts + track->cluster[0].cts);
2d9d6afb
MS
2669 // If the pts is less than zero, we will have trimmed
2670 // away parts of the media track using an edit list,
2671 // and the corresponding start presentation time is zero.
67a29123
MS
2672 if (info->time < 0) {
2673 info->duration += info->time;
2d9d6afb 2674 info->time = 0;
67a29123 2675 }
2d9d6afb
MS
2676 info->tfrf_offset = 0;
2677 mov_write_tfrf_tags(pb, mov, track);
2d9d6afb
MS
2678 }
2679 return 0;
2680}
2681
c2c22c75
MS
2682static int mov_write_tfdt_tag(AVIOContext *pb, MOVTrack *track)
2683{
2684 int64_t pos = avio_tell(pb);
2685
2686 avio_wb32(pb, 0); /* size */
2687 ffio_wfourcc(pb, "tfdt");
2688 avio_w8(pb, 1); /* version */
2689 avio_wb24(pb, 0);
2690 avio_wb64(pb, track->frag_start);
2691 return update_size(pb, pos);
2692}
2693
4ddd54da 2694static int mov_write_traf_tag(AVIOContext *pb, MOVMuxContext *mov,
a4adabb4
MS
2695 MOVTrack *track, int64_t moof_offset,
2696 int moof_size)
83988d58
MS
2697{
2698 int64_t pos = avio_tell(pb);
50ff0c05 2699 int i, start = 0;
83988d58
MS
2700 avio_wb32(pb, 0); /* size placeholder */
2701 ffio_wfourcc(pb, "traf");
2702
e7bf085b 2703 mov_write_tfhd_tag(pb, mov, track, moof_offset);
c55d1d38
MS
2704 if (mov->mode != MODE_ISM)
2705 mov_write_tfdt_tag(pb, track);
50ff0c05
MS
2706 for (i = 1; i < track->entry; i++) {
2707 if (track->cluster[i].pos != track->cluster[i - 1].pos + track->cluster[i - 1].size) {
2708 mov_write_trun_tag(pb, mov, track, moof_size, start, i);
2709 start = i;
2710 }
2711 }
2712 mov_write_trun_tag(pb, mov, track, moof_size, start, track->entry);
4ddd54da
MS
2713 if (mov->mode == MODE_ISM) {
2714 mov_write_tfxd_tag(pb, track);
2715
2716 if (mov->ism_lookahead) {
21732063 2717 int i, size = 16 + 4 + 1 + 16 * mov->ism_lookahead;
4ddd54da 2718
2d9d6afb
MS
2719 if (track->nb_frag_info > 0) {
2720 MOVFragmentInfo *info = &track->frag_info[track->nb_frag_info - 1];
2721 if (!info->tfrf_offset)
2722 info->tfrf_offset = avio_tell(pb);
2723 }
4ddd54da
MS
2724 avio_wb32(pb, 8 + size);
2725 ffio_wfourcc(pb, "free");
2726 for (i = 0; i < size; i++)
2727 avio_w8(pb, 0);
2728 }
2729 }
83988d58 2730
b7d3dd90 2731 return update_size(pb, pos);
83988d58
MS
2732}
2733
a4adabb4
MS
2734static int mov_write_moof_tag_internal(AVIOContext *pb, MOVMuxContext *mov,
2735 int tracks, int moof_size)
83988d58 2736{
a4adabb4
MS
2737 int64_t pos = avio_tell(pb);
2738 int i;
83988d58
MS
2739
2740 avio_wb32(pb, 0); /* size placeholder */
2741 ffio_wfourcc(pb, "moof");
573b1de2 2742 mov->first_trun = 1;
83988d58
MS
2743
2744 mov_write_mfhd_tag(pb, mov);
2745 for (i = 0; i < mov->nb_streams; i++) {
2746 MOVTrack *track = &mov->tracks[i];
2747 if (tracks >= 0 && i != tracks)
2748 continue;
2749 if (!track->entry)
2750 continue;
a4adabb4 2751 mov_write_traf_tag(pb, mov, track, pos, moof_size);
83988d58
MS
2752 }
2753
b7d3dd90 2754 return update_size(pb, pos);
83988d58
MS
2755}
2756
2ded5737
MS
2757static int mov_write_sidx_tag(AVIOContext *pb,
2758 MOVTrack *track, int ref_size, int total_sidx_size)
2759{
2760 int64_t pos = avio_tell(pb), offset_pos, end_pos;
40ed1cbf
MS
2761 int64_t presentation_time, duration, offset;
2762 int starts_with_SAP, i, entries;
2763
2764 if (track->entry) {
2765 entries = 1;
2766 presentation_time = track->start_dts + track->frag_start +
2767 track->cluster[0].cts;
67a29123
MS
2768 duration = track->end_pts -
2769 (track->cluster[0].dts + track->cluster[0].cts);
40ed1cbf 2770 starts_with_SAP = track->cluster[0].flags & MOV_SYNC_SAMPLE;
5c337353
MS
2771
2772 // pts<0 should be cut away using edts
67a29123
MS
2773 if (presentation_time < 0) {
2774 duration += presentation_time;
5c337353 2775 presentation_time = 0;
67a29123 2776 }
40ed1cbf
MS
2777 } else {
2778 entries = track->nb_frag_info;
8e34089e
MS
2779 if (entries <= 0)
2780 return 0;
40ed1cbf
MS
2781 presentation_time = track->frag_info[0].time;
2782 }
2ded5737 2783
2ded5737
MS
2784 avio_wb32(pb, 0); /* size */
2785 ffio_wfourcc(pb, "sidx");
2786 avio_w8(pb, 1); /* version */
2787 avio_wb24(pb, 0);
2788 avio_wb32(pb, track->track_id); /* reference_ID */
2789 avio_wb32(pb, track->timescale); /* timescale */
2790 avio_wb64(pb, presentation_time); /* earliest_presentation_time */
2791 offset_pos = avio_tell(pb);
2792 avio_wb64(pb, 0); /* first_offset (offset to referenced moof) */
2793 avio_wb16(pb, 0); /* reserved */
40ed1cbf
MS
2794
2795 avio_wb16(pb, entries); /* reference_count */
2796 for (i = 0; i < entries; i++) {
2797 if (!track->entry) {
2798 if (i > 1 && track->frag_info[i].offset != track->frag_info[i - 1].offset + track->frag_info[i - 1].size) {
2799 av_log(NULL, AV_LOG_ERROR, "Non-consecutive fragments, writing incorrect sidx\n");
2800 }
2801 duration = track->frag_info[i].duration;
2802 ref_size = track->frag_info[i].size;
2803 starts_with_SAP = 1;
2804 }
2805 avio_wb32(pb, (0 << 31) | (ref_size & 0x7fffffff)); /* reference_type (0 = media) | referenced_size */
2806 avio_wb32(pb, duration); /* subsegment_duration */
2807 avio_wb32(pb, (starts_with_SAP << 31) | (0 << 28) | 0); /* starts_with_SAP | SAP_type | SAP_delta_time */
2808 }
2ded5737
MS
2809
2810 end_pos = avio_tell(pb);
2811 offset = pos + total_sidx_size - end_pos;
2812 avio_seek(pb, offset_pos, SEEK_SET);
2813 avio_wb64(pb, offset);
2814 avio_seek(pb, end_pos, SEEK_SET);
2815 return update_size(pb, pos);
2816}
2817
2818static int mov_write_sidx_tags(AVIOContext *pb, MOVMuxContext *mov,
2819 int tracks, int ref_size)
2820{
2821 int i, round, ret;
2822 AVIOContext *avio_buf;
2823 int total_size = 0;
2824 for (round = 0; round < 2; round++) {
2825 // First run one round to calculate the total size of all
2826 // sidx atoms.
2827 // This would be much simpler if we'd only write one sidx
2828 // atom, for the first track in the moof.
2829 if (round == 0) {
2830 if ((ret = ffio_open_null_buf(&avio_buf)) < 0)
2831 return ret;
2832 } else {
2833 avio_buf = pb;
2834 }
2835 for (i = 0; i < mov->nb_streams; i++) {
2836 MOVTrack *track = &mov->tracks[i];
2837 if (tracks >= 0 && i != tracks)
2838 continue;
40ed1cbf
MS
2839 // When writing a sidx for the full file, entry is 0, but
2840 // we want to include all tracks. ref_size is 0 in this case,
2841 // since we read it from frag_info instead.
2842 if (!track->entry && ref_size > 0)
2ded5737
MS
2843 continue;
2844 total_size -= mov_write_sidx_tag(avio_buf, track, ref_size,
2845 total_size);
2846 }
2847 if (round == 0)
2848 total_size = ffio_close_null_buf(avio_buf);
2849 }
2850 return 0;
2851}
2852
2853static int mov_write_moof_tag(AVIOContext *pb, MOVMuxContext *mov, int tracks,
2854 int64_t mdat_size)
a4adabb4
MS
2855{
2856 AVIOContext *avio_buf;
2857 int ret, moof_size;
a4adabb4 2858
72fe16a1 2859 if ((ret = ffio_open_null_buf(&avio_buf)) < 0)
a4adabb4
MS
2860 return ret;
2861 mov_write_moof_tag_internal(avio_buf, mov, tracks, 0);
72fe16a1 2862 moof_size = ffio_close_null_buf(avio_buf);
2d9d6afb 2863
26ac22e5 2864 if (mov->flags & FF_MOV_FLAG_DASH && !(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX))
2ded5737
MS
2865 mov_write_sidx_tags(pb, mov, tracks, moof_size + 8 + mdat_size);
2866
40ed1cbf 2867 if ((ret = mov_add_tfra_entries(pb, mov, tracks, moof_size + 8 + mdat_size)) < 0)
2d9d6afb
MS
2868 return ret;
2869
a4adabb4
MS
2870 return mov_write_moof_tag_internal(pb, mov, tracks, moof_size);
2871}
2872
83988d58
MS
2873static int mov_write_tfra_tag(AVIOContext *pb, MOVTrack *track)
2874{
2875 int64_t pos = avio_tell(pb);
2876 int i;
2877
2878 avio_wb32(pb, 0); /* size placeholder */
2879 ffio_wfourcc(pb, "tfra");
2880 avio_w8(pb, 1); /* version */
2881 avio_wb24(pb, 0);
2882
b7d3dd90 2883 avio_wb32(pb, track->track_id);
83988d58
MS
2884 avio_wb32(pb, 0); /* length of traf/trun/sample num */
2885 avio_wb32(pb, track->nb_frag_info);
2886 for (i = 0; i < track->nb_frag_info; i++) {
2887 avio_wb64(pb, track->frag_info[i].time);
40ed1cbf 2888 avio_wb64(pb, track->frag_info[i].offset + track->data_offset);
83988d58
MS
2889 avio_w8(pb, 1); /* traf number */
2890 avio_w8(pb, 1); /* trun number */
2891 avio_w8(pb, 1); /* sample number */
2892 }
2893
b7d3dd90 2894 return update_size(pb, pos);
83988d58
MS
2895}
2896
2897static int mov_write_mfra_tag(AVIOContext *pb, MOVMuxContext *mov)
2898{
2899 int64_t pos = avio_tell(pb);
2900 int i;
2901
2902 avio_wb32(pb, 0); /* size placeholder */
2903 ffio_wfourcc(pb, "mfra");
f5322104
MS
2904 /* An empty mfra atom is enough to indicate to the publishing point that
2905 * the stream has ended. */
2906 if (mov->flags & FF_MOV_FLAG_ISML)
b7d3dd90 2907 return update_size(pb, pos);
83988d58
MS
2908
2909 for (i = 0; i < mov->nb_streams; i++) {
2910 MOVTrack *track = &mov->tracks[i];
2911 if (track->nb_frag_info)
2912 mov_write_tfra_tag(pb, track);
2913 }
2914
2915 avio_wb32(pb, 16);
2916 ffio_wfourcc(pb, "mfro");
2917 avio_wb32(pb, 0); /* version + flags */
2918 avio_wb32(pb, avio_tell(pb) + 4 - pos);
2919
b7d3dd90 2920 return update_size(pb, pos);
83988d58
MS
2921}
2922
ae628ec1 2923static int mov_write_mdat_tag(AVIOContext *pb, MOVMuxContext *mov)
1cb5f7fd 2924{
77eb5504 2925 avio_wb32(pb, 8); // placeholder for extended size field (64 bit)
0abdb293 2926 ffio_wfourcc(pb, mov->mode == MODE_MOV ? "wide" : "free");
b29af723 2927
a2704c97 2928 mov->mdat_pos = avio_tell(pb);
77eb5504 2929 avio_wb32(pb, 0); /* size placeholder*/
0abdb293 2930 ffio_wfourcc(pb, "mdat");
1cb5f7fd
MN
2931 return 0;
2932}
2933
2934/* TODO: This needs to be more general */
ae628ec1 2935static int mov_write_ftyp_tag(AVIOContext *pb, AVFormatContext *s)
1cb5f7fd 2936{
2d243fb3 2937 MOVMuxContext *mov = s->priv_data;
a2704c97 2938 int64_t pos = avio_tell(pb);
cd70d17f 2939 int has_h264 = 0, has_video = 0;
40f8675c 2940 int minor = 0x200;
c55cc074 2941 int i;
69dde1ad 2942
83579084
BC
2943 for (i = 0; i < s->nb_streams; i++) {
2944 AVStream *st = s->streams[i];
9200514a 2945 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
cd70d17f 2946 has_video = 1;
9200514a 2947 if (st->codecpar->codec_id == AV_CODEC_ID_H264)
83579084
BC
2948 has_h264 = 1;
2949 }
2950
77eb5504 2951 avio_wb32(pb, 0); /* size */
0abdb293 2952 ffio_wfourcc(pb, "ftyp");
e45ccf79 2953
1e9db41e
JS
2954 if (mov->major_brand && strlen(mov->major_brand) >= 4)
2955 ffio_wfourcc(pb, mov->major_brand);
2956 else if (mov->mode == MODE_3GP) {
0abdb293 2957 ffio_wfourcc(pb, has_h264 ? "3gp6" : "3gp4");
40f8675c
BC
2958 minor = has_h264 ? 0x100 : 0x200;
2959 } else if (mov->mode & MODE_3G2) {
0abdb293 2960 ffio_wfourcc(pb, has_h264 ? "3g2b" : "3g2a");
40f8675c 2961 minor = has_h264 ? 0x20000 : 0x10000;
21732063 2962 } else if (mov->mode == MODE_PSP)
0abdb293 2963 ffio_wfourcc(pb, "MSNV");
cf589faa
MS
2964 else if (mov->mode == MODE_MP4 && mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)
2965 ffio_wfourcc(pb, "iso5"); // Required when using default-base-is-moof
c55cc074 2966 else if (mov->mode == MODE_MP4)
0abdb293 2967 ffio_wfourcc(pb, "isom");
cd70d17f 2968 else if (mov->mode == MODE_IPOD)
0abdb293 2969 ffio_wfourcc(pb, has_video ? "M4V ":"M4A ");
4ddd54da
MS
2970 else if (mov->mode == MODE_ISM)
2971 ffio_wfourcc(pb, "isml");
e01fba55
CB
2972 else if (mov->mode == MODE_F4V)
2973 ffio_wfourcc(pb, "f4v ");
cd70d17f 2974 else
0abdb293 2975 ffio_wfourcc(pb, "qt ");
e45ccf79 2976
77eb5504 2977 avio_wb32(pb, minor);
e45ccf79 2978
21732063 2979 if (mov->mode == MODE_MOV)
0abdb293 2980 ffio_wfourcc(pb, "qt ");
4ddd54da
MS
2981 else if (mov->mode == MODE_ISM) {
2982 ffio_wfourcc(pb, "piff");
cf589faa 2983 } else if (!(mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)) {
0abdb293
AK
2984 ffio_wfourcc(pb, "isom");
2985 ffio_wfourcc(pb, "iso2");
21732063 2986 if (has_h264)
0abdb293 2987 ffio_wfourcc(pb, "avc1");
6ba9ed95 2988 }
ed6e47c2 2989
600d5ee6
MS
2990 // We add tfdt atoms when fragmenting, signal this with the iso6 compatible
2991 // brand. This is compatible with users that don't understand tfdt.
c55d1d38 2992 if (mov->flags & FF_MOV_FLAG_FRAGMENT && mov->mode != MODE_ISM)
600d5ee6
MS
2993 ffio_wfourcc(pb, "iso6");
2994
91208916 2995 if (mov->mode == MODE_3GP)
0abdb293 2996 ffio_wfourcc(pb, has_h264 ? "3gp6":"3gp4");
a04aec6d 2997 else if (mov->mode & MODE_3G2)
0abdb293 2998 ffio_wfourcc(pb, has_h264 ? "3g2b":"3g2a");
91208916 2999 else if (mov->mode == MODE_PSP)
0abdb293 3000 ffio_wfourcc(pb, "MSNV");
c55cc074 3001 else if (mov->mode == MODE_MP4)
0abdb293 3002 ffio_wfourcc(pb, "mp41");
40ed1cbf 3003
26ac22e5 3004 if (mov->flags & FF_MOV_FLAG_DASH && mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
40ed1cbf
MS
3005 ffio_wfourcc(pb, "dash");
3006
b7d3dd90 3007 return update_size(pb, pos);
1cb5f7fd
MN
3008}
3009
ae628ec1 3010static void mov_write_uuidprof_tag(AVIOContext *pb, AVFormatContext *s)
8af18154