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