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