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