3 * Copyright (c) 2003 Thomas Raivio
4 * Copyright (c) 2004 Gildas Bazin <gbazin at videolan dot org>
5 * Copyright (c) 2009 Baptiste Coudurier <baptiste dot coudurier at gmail dot com>
7 * This file is part of FFmpeg.
9 * FFmpeg is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
14 * FFmpeg is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with FFmpeg; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
29 #include "avio_internal.h"
34 #include "libavcodec/get_bits.h"
35 #include "libavcodec/put_bits.h"
36 #include "libavcodec/vc1.h"
37 #include "libavcodec/raw.h"
39 #include "libavutil/avstring.h"
40 #include "libavutil/intfloat.h"
41 #include "libavutil/mathematics.h"
42 #include "libavutil/opt.h"
43 #include "libavutil/dict.h"
44 #include "libavutil/pixdesc.h"
52 static const AVOption options[] = {
53 { "movflags", "MOV muxer flags", offsetof(MOVMuxContext, flags), AV_OPT_TYPE_FLAGS, {.i64 = 0}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
54 { "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" },
55 { "moov_size", "maximum moov size so it can be placed at the begin", offsetof(MOVMuxContext, reserved_moov_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, 0 },
56 { "empty_moov", "Make the initial moov atom empty (not supported by QuickTime)", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_EMPTY_MOOV}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
57 { "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" },
58 { "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" },
59 { "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" },
60 { "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" },
61 { "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" },
62 { "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" },
63 { "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" },
64 FF_RTP_FLAG_OPTS(MOVMuxContext, rtp_flags),
65 { "skip_iods", "Skip writing iods atom.", offsetof(MOVMuxContext, iods_skip), AV_OPT_TYPE_INT, {.i64 = 1}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM},
66 { "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},
67 { "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},
68 { "frag_duration", "Maximum fragment duration", offsetof(MOVMuxContext, max_fragment_duration), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
69 { "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},
70 { "frag_size", "Maximum fragment size", offsetof(MOVMuxContext, max_fragment_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
71 { "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},
72 { "use_editlist", "use edit list", offsetof(MOVMuxContext, use_editlist), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 1, AV_OPT_FLAG_ENCODING_PARAM},
73 { "video_track_timescale", "set timescale of all video tracks", offsetof(MOVMuxContext, video_track_timescale), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
74 { "brand", "Override major brand", offsetof(MOVMuxContext, major_brand), AV_OPT_TYPE_STRING, {.str = NULL}, .flags = AV_OPT_FLAG_ENCODING_PARAM },
78 #define MOV_CLASS(flavor)\
79 static const AVClass flavor ## _muxer_class = {\
80 .class_name = #flavor " muxer",\
81 .item_name = av_default_item_name,\
83 .version = LIBAVUTIL_VERSION_INT,\
86 static int get_moov_size(AVFormatContext *s);
88 static int utf8len(const uint8_t *b)
93 GET_UTF8(val, *b++, return -1;)
99 //FIXME support 64 bit variant with wide placeholders
100 static int64_t update_size(AVIOContext *pb, int64_t pos)
102 int64_t curpos = avio_tell(pb);
103 avio_seek(pb, pos, SEEK_SET);
104 avio_wb32(pb, curpos - pos); /* rewrite size */
105 avio_seek(pb, curpos, SEEK_SET);
110 static int supports_edts(MOVMuxContext *mov)
112 // EDTS with fragments is tricky as we don't know the duration when its written
113 return (mov->use_editlist<0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT)) || mov->use_editlist>0;
116 static int co64_required(const MOVTrack *track)
118 if (track->entry > 0 && track->cluster[track->entry - 1].pos + track->data_offset > UINT32_MAX)
123 /* Chunk offset atom */
124 static int mov_write_stco_tag(AVIOContext *pb, MOVTrack *track)
127 int mode64 = co64_required(track); // use 32 bit size variant if possible
128 int64_t pos = avio_tell(pb);
129 avio_wb32(pb, 0); /* size */
131 ffio_wfourcc(pb, "co64");
133 ffio_wfourcc(pb, "stco");
134 avio_wb32(pb, 0); /* version & flags */
135 avio_wb32(pb, track->chunkCount); /* entry count */
136 for (i = 0; i < track->entry; i++) {
137 if (!track->cluster[i].chunkNum)
140 avio_wb64(pb, track->cluster[i].pos + track->data_offset);
142 avio_wb32(pb, track->cluster[i].pos + track->data_offset);
144 return update_size(pb, pos);
147 /* Sample size atom */
148 static int mov_write_stsz_tag(AVIOContext *pb, MOVTrack *track)
151 int i, j, entries = 0, tst = -1, oldtst = -1;
153 int64_t pos = avio_tell(pb);
154 avio_wb32(pb, 0); /* size */
155 ffio_wfourcc(pb, "stsz");
156 avio_wb32(pb, 0); /* version & flags */
158 for (i = 0; i < track->entry; i++) {
159 tst = track->cluster[i].size / track->cluster[i].entries;
160 if (oldtst != -1 && tst != oldtst)
163 entries += track->cluster[i].entries;
165 if (equalChunks && track->entry) {
166 int sSize = track->entry ? track->cluster[0].size / track->cluster[0].entries : 0;
167 sSize = FFMAX(1, sSize); // adpcm mono case could make sSize == 0
168 avio_wb32(pb, sSize); // sample size
169 avio_wb32(pb, entries); // sample count
171 avio_wb32(pb, 0); // sample size
172 avio_wb32(pb, entries); // sample count
173 for (i = 0; i < track->entry; i++) {
174 for (j = 0; j < track->cluster[i].entries; j++) {
175 avio_wb32(pb, track->cluster[i].size /
176 track->cluster[i].entries);
180 return update_size(pb, pos);
183 /* Sample to chunk atom */
184 static int mov_write_stsc_tag(AVIOContext *pb, MOVTrack *track)
186 int index = 0, oldval = -1, i;
187 int64_t entryPos, curpos;
189 int64_t pos = avio_tell(pb);
190 avio_wb32(pb, 0); /* size */
191 ffio_wfourcc(pb, "stsc");
192 avio_wb32(pb, 0); // version & flags
193 entryPos = avio_tell(pb);
194 avio_wb32(pb, track->chunkCount); // entry count
195 for (i = 0; i < track->entry; i++) {
196 if (oldval != track->cluster[i].samples_in_chunk && track->cluster[i].chunkNum) {
197 avio_wb32(pb, track->cluster[i].chunkNum); // first chunk
198 avio_wb32(pb, track->cluster[i].samples_in_chunk); // samples per chunk
199 avio_wb32(pb, 0x1); // sample description index
200 oldval = track->cluster[i].samples_in_chunk;
204 curpos = avio_tell(pb);
205 avio_seek(pb, entryPos, SEEK_SET);
206 avio_wb32(pb, index); // rewrite size
207 avio_seek(pb, curpos, SEEK_SET);
209 return update_size(pb, pos);
212 /* Sync sample atom */
213 static int mov_write_stss_tag(AVIOContext *pb, MOVTrack *track, uint32_t flag)
215 int64_t curpos, entryPos;
217 int64_t pos = avio_tell(pb);
218 avio_wb32(pb, 0); // size
219 ffio_wfourcc(pb, flag == MOV_SYNC_SAMPLE ? "stss" : "stps");
220 avio_wb32(pb, 0); // version & flags
221 entryPos = avio_tell(pb);
222 avio_wb32(pb, track->entry); // entry count
223 for (i = 0; i < track->entry; i++) {
224 if (track->cluster[i].flags & flag) {
225 avio_wb32(pb, i + 1);
229 curpos = avio_tell(pb);
230 avio_seek(pb, entryPos, SEEK_SET);
231 avio_wb32(pb, index); // rewrite size
232 avio_seek(pb, curpos, SEEK_SET);
233 return update_size(pb, pos);
236 static int mov_write_amr_tag(AVIOContext *pb, MOVTrack *track)
238 avio_wb32(pb, 0x11); /* size */
239 if (track->mode == MODE_MOV) ffio_wfourcc(pb, "samr");
240 else ffio_wfourcc(pb, "damr");
241 ffio_wfourcc(pb, "FFMP");
242 avio_w8(pb, 0); /* decoder version */
244 avio_wb16(pb, 0x81FF); /* Mode set (all modes for AMR_NB) */
245 avio_w8(pb, 0x00); /* Mode change period (no restriction) */
246 avio_w8(pb, 0x01); /* Frames per sample */
250 static int mov_write_ac3_tag(AVIOContext *pb, MOVTrack *track)
255 int fscod, bsid, bsmod, acmod, lfeon, frmsizecod;
257 if (track->vos_len < 7)
261 ffio_wfourcc(pb, "dac3");
263 init_get_bits(&gbc, track->vos_data + 4, (track->vos_len - 4) * 8);
264 fscod = get_bits(&gbc, 2);
265 frmsizecod = get_bits(&gbc, 6);
266 bsid = get_bits(&gbc, 5);
267 bsmod = get_bits(&gbc, 3);
268 acmod = get_bits(&gbc, 3);
270 skip_bits(&gbc, 2); // dsurmod
272 if ((acmod & 1) && acmod != 1)
273 skip_bits(&gbc, 2); // cmixlev
275 skip_bits(&gbc, 2); // surmixlev
277 lfeon = get_bits1(&gbc);
279 init_put_bits(&pbc, buf, sizeof(buf));
280 put_bits(&pbc, 2, fscod);
281 put_bits(&pbc, 5, bsid);
282 put_bits(&pbc, 3, bsmod);
283 put_bits(&pbc, 3, acmod);
284 put_bits(&pbc, 1, lfeon);
285 put_bits(&pbc, 5, frmsizecod >> 1); // bit_rate_code
286 put_bits(&pbc, 5, 0); // reserved
288 flush_put_bits(&pbc);
289 avio_write(pb, buf, sizeof(buf));
295 * This function writes extradata "as is".
296 * Extradata must be formatted like a valid atom (with size and tag).
298 static int mov_write_extradata_tag(AVIOContext *pb, MOVTrack *track)
300 avio_write(pb, track->enc->extradata, track->enc->extradata_size);
301 return track->enc->extradata_size;
304 static int mov_write_enda_tag(AVIOContext *pb)
307 ffio_wfourcc(pb, "enda");
308 avio_wb16(pb, 1); /* little endian */
312 static int mov_write_enda_tag_be(AVIOContext *pb)
315 ffio_wfourcc(pb, "enda");
316 avio_wb16(pb, 0); /* big endian */
320 static void put_descr(AVIOContext *pb, int tag, unsigned int size)
325 avio_w8(pb, (size >> (7 * i)) | 0x80);
326 avio_w8(pb, size & 0x7F);
329 static unsigned compute_avg_bitrate(MOVTrack *track)
333 if (!track->track_duration)
335 for (i = 0; i < track->entry; i++)
336 size += track->cluster[i].size;
337 return size * 8 * track->timescale / track->track_duration;
340 static int mov_write_esds_tag(AVIOContext *pb, MOVTrack *track) // Basic
342 int64_t pos = avio_tell(pb);
343 int decoder_specific_info_len = track->vos_len ? 5 + track->vos_len : 0;
344 unsigned avg_bitrate;
346 avio_wb32(pb, 0); // size
347 ffio_wfourcc(pb, "esds");
348 avio_wb32(pb, 0); // Version
351 put_descr(pb, 0x03, 3 + 5+13 + decoder_specific_info_len + 5+1);
352 avio_wb16(pb, track->track_id);
353 avio_w8(pb, 0x00); // flags (= no flags)
355 // DecoderConfig descriptor
356 put_descr(pb, 0x04, 13 + decoder_specific_info_len);
358 // Object type indication
359 if ((track->enc->codec_id == AV_CODEC_ID_MP2 ||
360 track->enc->codec_id == AV_CODEC_ID_MP3) &&
361 track->enc->sample_rate > 24000)
362 avio_w8(pb, 0x6B); // 11172-3
364 avio_w8(pb, ff_codec_get_tag(ff_mp4_obj_type, track->enc->codec_id));
366 // the following fields is made of 6 bits to identify the streamtype (4 for video, 5 for audio)
367 // plus 1 bit to indicate upstream and 1 bit set to 1 (reserved)
368 if (track->enc->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
369 avio_w8(pb, (0x38 << 2) | 1); // flags (= NeroSubpicStream)
370 else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
371 avio_w8(pb, 0x15); // flags (= Audiostream)
373 avio_w8(pb, 0x11); // flags (= Visualstream)
375 avio_wb24(pb, track->enc->rc_buffer_size >> 3); // Buffersize DB
377 avg_bitrate = compute_avg_bitrate(track);
378 // maxbitrate (FIXME should be max rate in any 1 sec window)
379 avio_wb32(pb, FFMAX3(track->enc->bit_rate, track->enc->rc_max_rate, avg_bitrate));
380 avio_wb32(pb, avg_bitrate);
382 if (track->vos_len) {
383 // DecoderSpecific info descriptor
384 put_descr(pb, 0x05, track->vos_len);
385 avio_write(pb, track->vos_data, track->vos_len);
389 put_descr(pb, 0x06, 1);
391 return update_size(pb, pos);
394 static int mov_pcm_le_gt16(enum AVCodecID codec_id)
396 return codec_id == AV_CODEC_ID_PCM_S24LE ||
397 codec_id == AV_CODEC_ID_PCM_S32LE ||
398 codec_id == AV_CODEC_ID_PCM_F32LE ||
399 codec_id == AV_CODEC_ID_PCM_F64LE;
402 static int mov_pcm_be_gt16(enum AVCodecID codec_id)
404 return codec_id == AV_CODEC_ID_PCM_S24BE ||
405 codec_id == AV_CODEC_ID_PCM_S32BE ||
406 codec_id == AV_CODEC_ID_PCM_F32BE ||
407 codec_id == AV_CODEC_ID_PCM_F64BE;
410 static int mov_write_ms_tag(AVIOContext *pb, MOVTrack *track)
413 int64_t pos = avio_tell(pb);
415 avio_wl32(pb, track->tag); // store it byteswapped
416 track->enc->codec_tag = av_bswap16(track->tag >> 16);
417 if ((ret = ff_put_wav_header(pb, track->enc, 0)) < 0)
419 return update_size(pb, pos);
422 static int mov_write_wfex_tag(AVIOContext *pb, MOVTrack *track)
425 int64_t pos = avio_tell(pb);
427 ffio_wfourcc(pb, "wfex");
428 if ((ret = ff_put_wav_header(pb, track->enc, FF_PUT_WAV_HEADER_FORCE_WAVEFORMATEX)) < 0)
430 return update_size(pb, pos);
433 static int mov_write_chan_tag(AVIOContext *pb, MOVTrack *track)
435 uint32_t layout_tag, bitmap;
436 int64_t pos = avio_tell(pb);
438 layout_tag = ff_mov_get_channel_layout_tag(track->enc->codec_id,
439 track->enc->channel_layout,
442 av_log(track->enc, AV_LOG_WARNING, "not writing 'chan' tag due to "
443 "lack of channel information\n");
447 if (track->multichannel_as_mono)
450 avio_wb32(pb, 0); // Size
451 ffio_wfourcc(pb, "chan"); // Type
452 avio_w8(pb, 0); // Version
453 avio_wb24(pb, 0); // Flags
454 avio_wb32(pb, layout_tag); // mChannelLayoutTag
455 avio_wb32(pb, bitmap); // mChannelBitmap
456 avio_wb32(pb, 0); // mNumberChannelDescriptions
458 return update_size(pb, pos);
461 static int mov_write_wave_tag(AVIOContext *pb, MOVTrack *track)
463 int64_t pos = avio_tell(pb);
465 avio_wb32(pb, 0); /* size */
466 ffio_wfourcc(pb, "wave");
468 if (track->enc->codec_id != AV_CODEC_ID_QDM2) {
469 avio_wb32(pb, 12); /* size */
470 ffio_wfourcc(pb, "frma");
471 avio_wl32(pb, track->tag);
474 if (track->enc->codec_id == AV_CODEC_ID_AAC) {
475 /* useless atom needed by mplayer, ipod, not needed by quicktime */
476 avio_wb32(pb, 12); /* size */
477 ffio_wfourcc(pb, "mp4a");
479 mov_write_esds_tag(pb, track);
480 } else if (mov_pcm_le_gt16(track->enc->codec_id)) {
481 mov_write_enda_tag(pb);
482 } else if (mov_pcm_be_gt16(track->enc->codec_id)) {
483 mov_write_enda_tag_be(pb);
484 } else if (track->enc->codec_id == AV_CODEC_ID_AMR_NB) {
485 mov_write_amr_tag(pb, track);
486 } else if (track->enc->codec_id == AV_CODEC_ID_AC3) {
487 mov_write_ac3_tag(pb, track);
488 } else if (track->enc->codec_id == AV_CODEC_ID_ALAC ||
489 track->enc->codec_id == AV_CODEC_ID_QDM2) {
490 mov_write_extradata_tag(pb, track);
491 } else if (track->enc->codec_id == AV_CODEC_ID_ADPCM_MS ||
492 track->enc->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) {
493 mov_write_ms_tag(pb, track);
496 avio_wb32(pb, 8); /* size */
497 avio_wb32(pb, 0); /* null tag */
499 return update_size(pb, pos);
502 static int mov_write_dvc1_structs(MOVTrack *track, uint8_t *buf)
505 const uint8_t *start, *next, *end = track->vos_data + track->vos_len;
506 int unescaped_size, seq_found = 0;
507 int level = 0, interlace = 0;
508 int packet_seq = track->vc1_info.packet_seq;
509 int packet_entry = track->vc1_info.packet_entry;
510 int slices = track->vc1_info.slices;
513 if (track->start_dts == AV_NOPTS_VALUE) {
514 /* No packets written yet, vc1_info isn't authoritative yet. */
515 /* Assume inline sequence and entry headers. This will be
516 * overwritten at the end if the file is seekable. */
517 packet_seq = packet_entry = 1;
520 unescaped = av_mallocz(track->vos_len + FF_INPUT_BUFFER_PADDING_SIZE);
522 return AVERROR(ENOMEM);
523 start = find_next_marker(track->vos_data, end);
524 for (next = start; next < end; start = next) {
527 next = find_next_marker(start + 4, end);
528 size = next - start - 4;
531 unescaped_size = vc1_unescape_buffer(start + 4, size, unescaped);
532 init_get_bits(&gb, unescaped, 8 * unescaped_size);
533 if (AV_RB32(start) == VC1_CODE_SEQHDR) {
534 int profile = get_bits(&gb, 2);
535 if (profile != PROFILE_ADVANCED) {
537 return AVERROR(ENOSYS);
540 level = get_bits(&gb, 3);
541 /* chromaformat, frmrtq_postproc, bitrtq_postproc, postprocflag,
543 skip_bits_long(&gb, 2 + 3 + 5 + 1 + 2*12);
544 skip_bits(&gb, 1); /* broadcast */
545 interlace = get_bits1(&gb);
546 skip_bits(&gb, 4); /* tfcntrflag, finterpflag, reserved, psf */
551 return AVERROR(ENOSYS);
554 init_put_bits(&pbc, buf, 7);
555 /* VC1DecSpecStruc */
556 put_bits(&pbc, 4, 12); /* profile - advanced */
557 put_bits(&pbc, 3, level);
558 put_bits(&pbc, 1, 0); /* reserved */
559 /* VC1AdvDecSpecStruc */
560 put_bits(&pbc, 3, level);
561 put_bits(&pbc, 1, 0); /* cbr */
562 put_bits(&pbc, 6, 0); /* reserved */
563 put_bits(&pbc, 1, !interlace); /* no interlace */
564 put_bits(&pbc, 1, !packet_seq); /* no multiple seq */
565 put_bits(&pbc, 1, !packet_entry); /* no multiple entry */
566 put_bits(&pbc, 1, !slices); /* no slice code */
567 put_bits(&pbc, 1, 0); /* no bframe */
568 put_bits(&pbc, 1, 0); /* reserved */
571 if (track->st->avg_frame_rate.num > 0 && track->st->avg_frame_rate.den > 0)
572 put_bits32(&pbc, track->st->avg_frame_rate.num / track->st->avg_frame_rate.den);
574 put_bits32(&pbc, 0xffffffff);
576 flush_put_bits(&pbc);
583 static int mov_write_dvc1_tag(AVIOContext *pb, MOVTrack *track)
585 uint8_t buf[7] = { 0 };
588 if ((ret = mov_write_dvc1_structs(track, buf)) < 0)
591 avio_wb32(pb, track->vos_len + 8 + sizeof(buf));
592 ffio_wfourcc(pb, "dvc1");
593 track->vc1_info.struct_offset = avio_tell(pb);
594 avio_write(pb, buf, sizeof(buf));
595 avio_write(pb, track->vos_data, track->vos_len);
600 static int mov_write_glbl_tag(AVIOContext *pb, MOVTrack *track)
602 avio_wb32(pb, track->vos_len + 8);
603 ffio_wfourcc(pb, "glbl");
604 avio_write(pb, track->vos_data, track->vos_len);
605 return 8 + track->vos_len;
609 * Compute flags for 'lpcm' tag.
610 * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
612 static int mov_get_lpcm_flags(enum AVCodecID codec_id)
615 case AV_CODEC_ID_PCM_F32BE:
616 case AV_CODEC_ID_PCM_F64BE:
618 case AV_CODEC_ID_PCM_F32LE:
619 case AV_CODEC_ID_PCM_F64LE:
621 case AV_CODEC_ID_PCM_U8:
623 case AV_CODEC_ID_PCM_S16BE:
624 case AV_CODEC_ID_PCM_S24BE:
625 case AV_CODEC_ID_PCM_S32BE:
627 case AV_CODEC_ID_PCM_S8:
628 case AV_CODEC_ID_PCM_S16LE:
629 case AV_CODEC_ID_PCM_S24LE:
630 case AV_CODEC_ID_PCM_S32LE:
637 static int get_cluster_duration(MOVTrack *track, int cluster_idx)
641 if (cluster_idx >= track->entry)
644 if (cluster_idx + 1 == track->entry)
645 next_dts = track->track_duration + track->start_dts;
647 next_dts = track->cluster[cluster_idx + 1].dts;
649 next_dts -= track->cluster[cluster_idx].dts;
651 av_assert0(next_dts >= 0);
652 av_assert0(next_dts <= INT_MAX);
657 static int get_samples_per_packet(MOVTrack *track)
659 int i, first_duration;
661 // return track->enc->frame_size;
663 /* use 1 for raw PCM */
664 if (!track->audio_vbr)
667 /* check to see if duration is constant for all clusters */
670 first_duration = get_cluster_duration(track, 0);
671 for (i = 1; i < track->entry; i++) {
672 if (get_cluster_duration(track, i) != first_duration)
675 return first_duration;
678 static int mov_write_audio_tag(AVIOContext *pb, MOVTrack *track)
680 int64_t pos = avio_tell(pb);
682 uint32_t tag = track->tag;
684 if (track->mode == MODE_MOV) {
685 if (track->timescale > UINT16_MAX) {
686 if (mov_get_lpcm_flags(track->enc->codec_id))
687 tag = AV_RL32("lpcm");
689 } else if (track->audio_vbr || mov_pcm_le_gt16(track->enc->codec_id) ||
690 mov_pcm_be_gt16(track->enc->codec_id) ||
691 track->enc->codec_id == AV_CODEC_ID_ADPCM_MS ||
692 track->enc->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
693 track->enc->codec_id == AV_CODEC_ID_QDM2) {
698 avio_wb32(pb, 0); /* size */
699 avio_wl32(pb, tag); // store it byteswapped
700 avio_wb32(pb, 0); /* Reserved */
701 avio_wb16(pb, 0); /* Reserved */
702 avio_wb16(pb, 1); /* Data-reference index, XXX == 1 */
704 /* SoundDescription */
705 avio_wb16(pb, version); /* Version */
706 avio_wb16(pb, 0); /* Revision level */
707 avio_wb32(pb, 0); /* Reserved */
712 avio_wb16(pb, 0xfffe);
714 avio_wb32(pb, 0x00010000);
716 avio_wb64(pb, av_double2int(track->enc->sample_rate));
717 avio_wb32(pb, track->enc->channels);
718 avio_wb32(pb, 0x7F000000);
719 avio_wb32(pb, av_get_bits_per_sample(track->enc->codec_id));
720 avio_wb32(pb, mov_get_lpcm_flags(track->enc->codec_id));
721 avio_wb32(pb, track->sample_size);
722 avio_wb32(pb, get_samples_per_packet(track));
724 if (track->mode == MODE_MOV) {
725 avio_wb16(pb, track->enc->channels);
726 if (track->enc->codec_id == AV_CODEC_ID_PCM_U8 ||
727 track->enc->codec_id == AV_CODEC_ID_PCM_S8)
728 avio_wb16(pb, 8); /* bits per sample */
731 avio_wb16(pb, track->audio_vbr ? -2 : 0); /* compression ID */
732 } else { /* reserved for mp4/3gp */
738 avio_wb16(pb, 0); /* packet size (= 0) */
739 avio_wb16(pb, track->enc->sample_rate <= UINT16_MAX ?
740 track->enc->sample_rate : 0);
741 avio_wb16(pb, 0); /* Reserved */
744 if (version == 1) { /* SoundDescription V1 extended info */
745 if (mov_pcm_le_gt16(track->enc->codec_id) ||
746 mov_pcm_be_gt16(track->enc->codec_id))
747 avio_wb32(pb, 1); /* must be 1 for uncompressed formats */
749 avio_wb32(pb, track->enc->frame_size); /* Samples per packet */
750 avio_wb32(pb, track->sample_size / track->enc->channels); /* Bytes per packet */
751 avio_wb32(pb, track->sample_size); /* Bytes per frame */
752 avio_wb32(pb, 2); /* Bytes per sample */
755 if (track->mode == MODE_MOV &&
756 (track->enc->codec_id == AV_CODEC_ID_AAC ||
757 track->enc->codec_id == AV_CODEC_ID_AC3 ||
758 track->enc->codec_id == AV_CODEC_ID_AMR_NB ||
759 track->enc->codec_id == AV_CODEC_ID_ALAC ||
760 track->enc->codec_id == AV_CODEC_ID_ADPCM_MS ||
761 track->enc->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
762 track->enc->codec_id == AV_CODEC_ID_QDM2 ||
763 (mov_pcm_le_gt16(track->enc->codec_id) && version==1) ||
764 (mov_pcm_be_gt16(track->enc->codec_id) && version==1)))
765 mov_write_wave_tag(pb, track);
766 else if (track->tag == MKTAG('m','p','4','a'))
767 mov_write_esds_tag(pb, track);
768 else if (track->enc->codec_id == AV_CODEC_ID_AMR_NB)
769 mov_write_amr_tag(pb, track);
770 else if (track->enc->codec_id == AV_CODEC_ID_AC3)
771 mov_write_ac3_tag(pb, track);
772 else if (track->enc->codec_id == AV_CODEC_ID_ALAC)
773 mov_write_extradata_tag(pb, track);
774 else if (track->enc->codec_id == AV_CODEC_ID_WMAPRO)
775 mov_write_wfex_tag(pb, track);
776 else if (track->vos_len > 0)
777 mov_write_glbl_tag(pb, track);
779 if (track->mode == MODE_MOV && track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
780 mov_write_chan_tag(pb, track);
782 return update_size(pb, pos);
785 static int mov_write_d263_tag(AVIOContext *pb)
787 avio_wb32(pb, 0xf); /* size */
788 ffio_wfourcc(pb, "d263");
789 ffio_wfourcc(pb, "FFMP");
790 avio_w8(pb, 0); /* decoder version */
791 /* FIXME use AVCodecContext level/profile, when encoder will set values */
792 avio_w8(pb, 0xa); /* level */
793 avio_w8(pb, 0); /* profile */
797 static int mov_write_avcc_tag(AVIOContext *pb, MOVTrack *track)
799 int64_t pos = avio_tell(pb);
802 ffio_wfourcc(pb, "avcC");
803 ff_isom_write_avcc(pb, track->vos_data, track->vos_len);
804 return update_size(pb, pos);
807 static int mov_write_hvcc_tag(AVIOContext *pb, MOVTrack *track)
809 int64_t pos = avio_tell(pb);
812 ffio_wfourcc(pb, "hvcC");
813 ff_isom_write_hvcc(pb, track->vos_data, track->vos_len, 0);
814 return update_size(pb, pos);
817 /* also used by all avid codecs (dv, imx, meridien) and their variants */
818 static int mov_write_avid_tag(AVIOContext *pb, MOVTrack *track)
821 avio_wb32(pb, 24); /* size */
822 ffio_wfourcc(pb, "ACLR");
823 ffio_wfourcc(pb, "ACLR");
824 ffio_wfourcc(pb, "0001");
825 if (track->enc->color_range == AVCOL_RANGE_MPEG) { /* Legal range (16-235) */
826 avio_wb32(pb, 1); /* Corresponds to 709 in official encoder */
827 } else { /* Full range (0-255) */
828 avio_wb32(pb, 2); /* Corresponds to RGB in official encoder */
830 avio_wb32(pb, 0); /* unknown */
832 avio_wb32(pb, 24); /* size */
833 ffio_wfourcc(pb, "APRG");
834 ffio_wfourcc(pb, "APRG");
835 ffio_wfourcc(pb, "0001");
836 avio_wb32(pb, 1); /* unknown */
837 avio_wb32(pb, 0); /* unknown */
839 avio_wb32(pb, 120); /* size */
840 ffio_wfourcc(pb, "ARES");
841 ffio_wfourcc(pb, "ARES");
842 ffio_wfourcc(pb, "0001");
843 avio_wb32(pb, AV_RB32(track->vos_data + 0x28)); /* dnxhd cid, some id ? */
844 avio_wb32(pb, track->enc->width);
845 /* values below are based on samples created with quicktime and avid codecs */
846 if (track->vos_data[5] & 2) { // interlaced
847 avio_wb32(pb, track->enc->height / 2);
848 avio_wb32(pb, 2); /* unknown */
849 avio_wb32(pb, 0); /* unknown */
850 avio_wb32(pb, 4); /* unknown */
852 avio_wb32(pb, track->enc->height);
853 avio_wb32(pb, 1); /* unknown */
854 avio_wb32(pb, 0); /* unknown */
855 if (track->enc->height == 1080)
856 avio_wb32(pb, 5); /* unknown */
858 avio_wb32(pb, 6); /* unknown */
861 for (i = 0; i < 10; i++)
864 /* extra padding for stsd needed */
869 static int mp4_get_codec_tag(AVFormatContext *s, MOVTrack *track)
871 int tag = track->enc->codec_tag;
873 if (!ff_codec_get_tag(ff_mp4_obj_type, track->enc->codec_id))
876 if (track->enc->codec_id == AV_CODEC_ID_H264) tag = MKTAG('a','v','c','1');
877 else if (track->enc->codec_id == AV_CODEC_ID_HEVC) tag = MKTAG('h','e','v','1');
878 else if (track->enc->codec_id == AV_CODEC_ID_AC3) tag = MKTAG('a','c','-','3');
879 else if (track->enc->codec_id == AV_CODEC_ID_DIRAC) tag = MKTAG('d','r','a','c');
880 else if (track->enc->codec_id == AV_CODEC_ID_MOV_TEXT) tag = MKTAG('t','x','3','g');
881 else if (track->enc->codec_id == AV_CODEC_ID_VC1) tag = MKTAG('v','c','-','1');
882 else if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) tag = MKTAG('m','p','4','v');
883 else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO) tag = MKTAG('m','p','4','a');
884 else if (track->enc->codec_id == AV_CODEC_ID_DVD_SUBTITLE) tag = MKTAG('m','p','4','s');
889 static const AVCodecTag codec_ipod_tags[] = {
890 { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
891 { AV_CODEC_ID_MPEG4, MKTAG('m','p','4','v') },
892 { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
893 { AV_CODEC_ID_ALAC, MKTAG('a','l','a','c') },
894 { AV_CODEC_ID_AC3, MKTAG('a','c','-','3') },
895 { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
896 { AV_CODEC_ID_MOV_TEXT, MKTAG('t','e','x','t') },
897 { AV_CODEC_ID_NONE, 0 },
900 static int ipod_get_codec_tag(AVFormatContext *s, MOVTrack *track)
902 int tag = track->enc->codec_tag;
904 // keep original tag for subs, ipod supports both formats
905 if (!(track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE &&
906 (tag == MKTAG('t', 'x', '3', 'g') ||
907 tag == MKTAG('t', 'e', 'x', 't'))))
908 tag = ff_codec_get_tag(codec_ipod_tags, track->enc->codec_id);
910 if (!av_match_ext(s->filename, "m4a") &&
911 !av_match_ext(s->filename, "m4b") &&
912 !av_match_ext(s->filename, "m4v"))
913 av_log(s, AV_LOG_WARNING, "Warning, extension is not .m4a, .m4v nor .m4b "
914 "Quicktime/Ipod might not play the file\n");
919 static int mov_get_dv_codec_tag(AVFormatContext *s, MOVTrack *track)
923 if (track->enc->width == 720) { /* SD */
924 if (track->enc->height == 480) { /* NTSC */
925 if (track->enc->pix_fmt == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','n');
926 else tag = MKTAG('d','v','c',' ');
927 }else if (track->enc->pix_fmt == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','p');
928 else if (track->enc->pix_fmt == AV_PIX_FMT_YUV420P) tag = MKTAG('d','v','c','p');
929 else tag = MKTAG('d','v','p','p');
930 } else if (track->enc->height == 720) { /* HD 720 line */
931 if (track->st->time_base.den == 50) tag = MKTAG('d','v','h','q');
932 else tag = MKTAG('d','v','h','p');
933 } else if (track->enc->height == 1080) { /* HD 1080 line */
934 if (track->st->time_base.den == 25) tag = MKTAG('d','v','h','5');
935 else tag = MKTAG('d','v','h','6');
937 av_log(s, AV_LOG_ERROR, "unsupported height for dv codec\n");
944 static AVRational find_fps(AVFormatContext *s, AVStream *st)
946 AVRational rate = {st->codec->time_base.den, st->codec->time_base.num};
947 /* if the codec time base makes no sense, try to fallback on stream frame rate */
948 if (av_timecode_check_frame_rate(rate) < 0) {
949 av_log(s, AV_LOG_DEBUG, "timecode: tbc=%d/%d invalid, fallback on %d/%d\n",
950 rate.num, rate.den, st->avg_frame_rate.num, st->avg_frame_rate.den);
951 rate = st->avg_frame_rate;
957 static int mov_get_mpeg2_xdcam_codec_tag(AVFormatContext *s, MOVTrack *track)
959 int tag = track->enc->codec_tag;
960 int interlaced = track->enc->field_order > AV_FIELD_PROGRESSIVE;
961 AVStream *st = track->st;
962 int rate = av_q2d(find_fps(s, st));
965 tag = MKTAG('m', '2', 'v', '1'); //fallback tag
967 if (track->enc->pix_fmt == AV_PIX_FMT_YUV420P) {
968 if (track->enc->width == 1280 && track->enc->height == 720) {
970 if (rate == 24) tag = MKTAG('x','d','v','4');
971 else if (rate == 25) tag = MKTAG('x','d','v','5');
972 else if (rate == 30) tag = MKTAG('x','d','v','1');
973 else if (rate == 50) tag = MKTAG('x','d','v','a');
974 else if (rate == 60) tag = MKTAG('x','d','v','9');
976 } else if (track->enc->width == 1440 && track->enc->height == 1080) {
978 if (rate == 24) tag = MKTAG('x','d','v','6');
979 else if (rate == 25) tag = MKTAG('x','d','v','7');
980 else if (rate == 30) tag = MKTAG('x','d','v','8');
982 if (rate == 25) tag = MKTAG('x','d','v','3');
983 else if (rate == 30) tag = MKTAG('x','d','v','2');
985 } else if (track->enc->width == 1920 && track->enc->height == 1080) {
987 if (rate == 24) tag = MKTAG('x','d','v','d');
988 else if (rate == 25) tag = MKTAG('x','d','v','e');
989 else if (rate == 30) tag = MKTAG('x','d','v','f');
991 if (rate == 25) tag = MKTAG('x','d','v','c');
992 else if (rate == 30) tag = MKTAG('x','d','v','b');
995 } else if (track->enc->pix_fmt == AV_PIX_FMT_YUV422P) {
996 if (track->enc->width == 1280 && track->enc->height == 720) {
998 if (rate == 24) tag = MKTAG('x','d','5','4');
999 else if (rate == 25) tag = MKTAG('x','d','5','5');
1000 else if (rate == 30) tag = MKTAG('x','d','5','1');
1001 else if (rate == 50) tag = MKTAG('x','d','5','a');
1002 else if (rate == 60) tag = MKTAG('x','d','5','9');
1004 } else if (track->enc->width == 1920 && track->enc->height == 1080) {
1006 if (rate == 24) tag = MKTAG('x','d','5','d');
1007 else if (rate == 25) tag = MKTAG('x','d','5','e');
1008 else if (rate == 30) tag = MKTAG('x','d','5','f');
1010 if (rate == 25) tag = MKTAG('x','d','5','c');
1011 else if (rate == 30) tag = MKTAG('x','d','5','b');
1019 static const struct {
1020 enum AVPixelFormat pix_fmt;
1023 } mov_pix_fmt_tags[] = {
1024 { AV_PIX_FMT_YUYV422, MKTAG('y','u','v','2'), 0 },
1025 { AV_PIX_FMT_YUYV422, MKTAG('y','u','v','s'), 0 },
1026 { AV_PIX_FMT_UYVY422, MKTAG('2','v','u','y'), 0 },
1027 { AV_PIX_FMT_RGB555BE,MKTAG('r','a','w',' '), 16 },
1028 { AV_PIX_FMT_RGB555LE,MKTAG('L','5','5','5'), 16 },
1029 { AV_PIX_FMT_RGB565LE,MKTAG('L','5','6','5'), 16 },
1030 { AV_PIX_FMT_RGB565BE,MKTAG('B','5','6','5'), 16 },
1031 { AV_PIX_FMT_GRAY16BE,MKTAG('b','1','6','g'), 16 },
1032 { AV_PIX_FMT_RGB24, MKTAG('r','a','w',' '), 24 },
1033 { AV_PIX_FMT_BGR24, MKTAG('2','4','B','G'), 24 },
1034 { AV_PIX_FMT_ARGB, MKTAG('r','a','w',' '), 32 },
1035 { AV_PIX_FMT_BGRA, MKTAG('B','G','R','A'), 32 },
1036 { AV_PIX_FMT_RGBA, MKTAG('R','G','B','A'), 32 },
1037 { AV_PIX_FMT_ABGR, MKTAG('A','B','G','R'), 32 },
1038 { AV_PIX_FMT_RGB48BE, MKTAG('b','4','8','r'), 48 },
1041 static int mov_get_rawvideo_codec_tag(AVFormatContext *s, MOVTrack *track)
1043 int tag = track->enc->codec_tag;
1045 enum AVPixelFormat pix_fmt;
1047 for (i = 0; i < FF_ARRAY_ELEMS(mov_pix_fmt_tags); i++) {
1048 if (track->enc->pix_fmt == mov_pix_fmt_tags[i].pix_fmt) {
1049 tag = mov_pix_fmt_tags[i].tag;
1050 track->enc->bits_per_coded_sample = mov_pix_fmt_tags[i].bps;
1051 if (track->enc->codec_tag == mov_pix_fmt_tags[i].tag)
1056 pix_fmt = avpriv_find_pix_fmt(avpriv_pix_fmt_bps_mov,
1057 track->enc->bits_per_coded_sample);
1058 if (tag == MKTAG('r','a','w',' ') &&
1059 track->enc->pix_fmt != pix_fmt &&
1060 track->enc->pix_fmt != AV_PIX_FMT_NONE)
1061 av_log(s, AV_LOG_ERROR, "%s rawvideo cannot be written to mov, output file will be unreadable\n",
1062 av_get_pix_fmt_name(track->enc->pix_fmt));
1066 static int mov_get_codec_tag(AVFormatContext *s, MOVTrack *track)
1068 int tag = track->enc->codec_tag;
1070 if (!tag || (track->enc->strict_std_compliance >= FF_COMPLIANCE_NORMAL &&
1071 (track->enc->codec_id == AV_CODEC_ID_DVVIDEO ||
1072 track->enc->codec_id == AV_CODEC_ID_RAWVIDEO ||
1073 track->enc->codec_id == AV_CODEC_ID_H263 ||
1074 track->enc->codec_id == AV_CODEC_ID_MPEG2VIDEO ||
1075 av_get_bits_per_sample(track->enc->codec_id)))) { // pcm audio
1076 if (track->enc->codec_id == AV_CODEC_ID_DVVIDEO)
1077 tag = mov_get_dv_codec_tag(s, track);
1078 else if (track->enc->codec_id == AV_CODEC_ID_RAWVIDEO)
1079 tag = mov_get_rawvideo_codec_tag(s, track);
1080 else if (track->enc->codec_id == AV_CODEC_ID_MPEG2VIDEO)
1081 tag = mov_get_mpeg2_xdcam_codec_tag(s, track);
1082 else if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1083 tag = ff_codec_get_tag(ff_codec_movvideo_tags, track->enc->codec_id);
1084 if (!tag) { // if no mac fcc found, try with Microsoft tags
1085 tag = ff_codec_get_tag(ff_codec_bmp_tags, track->enc->codec_id);
1087 av_log(s, AV_LOG_WARNING, "Using MS style video codec tag, "
1088 "the file may be unplayable!\n");
1090 } else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO) {
1091 tag = ff_codec_get_tag(ff_codec_movaudio_tags, track->enc->codec_id);
1092 if (!tag) { // if no mac fcc found, try with Microsoft tags
1093 int ms_tag = ff_codec_get_tag(ff_codec_wav_tags, track->enc->codec_id);
1095 tag = MKTAG('m', 's', ((ms_tag >> 8) & 0xff), (ms_tag & 0xff));
1096 av_log(s, AV_LOG_WARNING, "Using MS style audio codec tag, "
1097 "the file may be unplayable!\n");
1100 } else if (track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE)
1101 tag = ff_codec_get_tag(ff_codec_movsubtitle_tags, track->enc->codec_id);
1107 static const AVCodecTag codec_3gp_tags[] = {
1108 { AV_CODEC_ID_H263, MKTAG('s','2','6','3') },
1109 { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
1110 { AV_CODEC_ID_MPEG4, MKTAG('m','p','4','v') },
1111 { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
1112 { AV_CODEC_ID_AMR_NB, MKTAG('s','a','m','r') },
1113 { AV_CODEC_ID_AMR_WB, MKTAG('s','a','w','b') },
1114 { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
1115 { AV_CODEC_ID_NONE, 0 },
1118 static const AVCodecTag codec_f4v_tags[] = { // XXX: add GIF/PNG/JPEG?
1119 { AV_CODEC_ID_MP3, MKTAG('.','m','p','3') },
1120 { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
1121 { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
1122 { AV_CODEC_ID_VP6A, MKTAG('V','P','6','A') },
1123 { AV_CODEC_ID_VP6F, MKTAG('V','P','6','F') },
1124 { AV_CODEC_ID_NONE, 0 },
1127 static int mov_find_codec_tag(AVFormatContext *s, MOVTrack *track)
1131 if (track->mode == MODE_MP4 || track->mode == MODE_PSP)
1132 tag = mp4_get_codec_tag(s, track);
1133 else if (track->mode == MODE_ISM) {
1134 tag = mp4_get_codec_tag(s, track);
1135 if (!tag && track->enc->codec_id == AV_CODEC_ID_WMAPRO)
1136 tag = MKTAG('w', 'm', 'a', ' ');
1137 } else if (track->mode == MODE_IPOD)
1138 tag = ipod_get_codec_tag(s, track);
1139 else if (track->mode & MODE_3GP)
1140 tag = ff_codec_get_tag(codec_3gp_tags, track->enc->codec_id);
1141 else if (track->mode == MODE_F4V)
1142 tag = ff_codec_get_tag(codec_f4v_tags, track->enc->codec_id);
1144 tag = mov_get_codec_tag(s, track);
1149 /** Write uuid atom.
1150 * Needed to make file play in iPods running newest firmware
1151 * goes after avcC atom in moov.trak.mdia.minf.stbl.stsd.avc1
1153 static int mov_write_uuid_tag_ipod(AVIOContext *pb)
1156 ffio_wfourcc(pb, "uuid");
1157 avio_wb32(pb, 0x6b6840f2);
1158 avio_wb32(pb, 0x5f244fc5);
1159 avio_wb32(pb, 0xba39a51b);
1160 avio_wb32(pb, 0xcf0323f3);
1165 static const uint16_t fiel_data[] = {
1166 0x0000, 0x0100, 0x0201, 0x0206, 0x0209, 0x020e
1169 static int mov_write_fiel_tag(AVIOContext *pb, MOVTrack *track)
1171 unsigned mov_field_order = 0;
1172 if (track->enc->field_order < FF_ARRAY_ELEMS(fiel_data))
1173 mov_field_order = fiel_data[track->enc->field_order];
1177 ffio_wfourcc(pb, "fiel");
1178 avio_wb16(pb, mov_field_order);
1182 static int mov_write_subtitle_tag(AVIOContext *pb, MOVTrack *track)
1184 int64_t pos = avio_tell(pb);
1185 avio_wb32(pb, 0); /* size */
1186 avio_wl32(pb, track->tag); // store it byteswapped
1187 avio_wb32(pb, 0); /* Reserved */
1188 avio_wb16(pb, 0); /* Reserved */
1189 avio_wb16(pb, 1); /* Data-reference index */
1191 if (track->enc->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
1192 mov_write_esds_tag(pb, track);
1193 else if (track->enc->extradata_size)
1194 avio_write(pb, track->enc->extradata, track->enc->extradata_size);
1196 return update_size(pb, pos);
1199 static int mov_write_pasp_tag(AVIOContext *pb, MOVTrack *track)
1202 av_reduce(&sar.num, &sar.den, track->enc->sample_aspect_ratio.num,
1203 track->enc->sample_aspect_ratio.den, INT_MAX);
1206 ffio_wfourcc(pb, "pasp");
1207 avio_wb32(pb, sar.num);
1208 avio_wb32(pb, sar.den);
1212 static void find_compressor(char * compressor_name, int len, MOVTrack *track)
1214 AVDictionaryEntry *encoder;
1215 int xdcam_res = (track->enc->width == 1280 && track->enc->height == 720)
1216 || (track->enc->width == 1440 && track->enc->height == 1080)
1217 || (track->enc->width == 1920 && track->enc->height == 1080);
1219 if (track->mode == MODE_MOV &&
1220 (encoder = av_dict_get(track->st->metadata, "encoder", NULL, 0))) {
1221 av_strlcpy(compressor_name, encoder->value, 32);
1222 } else if (track->enc->codec_id == AV_CODEC_ID_MPEG2VIDEO && xdcam_res) {
1223 int interlaced = track->enc->field_order > AV_FIELD_PROGRESSIVE;
1224 AVStream *st = track->st;
1225 int rate = av_q2d(find_fps(NULL, st));
1226 av_strlcatf(compressor_name, len, "XDCAM");
1227 if (track->enc->pix_fmt == AV_PIX_FMT_YUV422P) {
1228 av_strlcatf(compressor_name, len, " HD422");
1229 } else if(track->enc->width == 1440) {
1230 av_strlcatf(compressor_name, len, " HD");
1232 av_strlcatf(compressor_name, len, " EX");
1234 av_strlcatf(compressor_name, len, " %d%c", track->enc->height, interlaced ? 'i' : 'p');
1236 av_strlcatf(compressor_name, len, "%d", rate * (interlaced + 1));
1240 static int mov_write_video_tag(AVIOContext *pb, MOVTrack *track)
1242 int64_t pos = avio_tell(pb);
1243 char compressor_name[32] = { 0 };
1245 avio_wb32(pb, 0); /* size */
1246 avio_wl32(pb, track->tag); // store it byteswapped
1247 avio_wb32(pb, 0); /* Reserved */
1248 avio_wb16(pb, 0); /* Reserved */
1249 avio_wb16(pb, 1); /* Data-reference index */
1251 avio_wb16(pb, 0); /* Codec stream version */
1252 avio_wb16(pb, 0); /* Codec stream revision (=0) */
1253 if (track->mode == MODE_MOV) {
1254 ffio_wfourcc(pb, "FFMP"); /* Vendor */
1255 if (track->enc->codec_id == AV_CODEC_ID_RAWVIDEO) {
1256 avio_wb32(pb, 0); /* Temporal Quality */
1257 avio_wb32(pb, 0x400); /* Spatial Quality = lossless*/
1259 avio_wb32(pb, 0x200); /* Temporal Quality = normal */
1260 avio_wb32(pb, 0x200); /* Spatial Quality = normal */
1263 avio_wb32(pb, 0); /* Reserved */
1264 avio_wb32(pb, 0); /* Reserved */
1265 avio_wb32(pb, 0); /* Reserved */
1267 avio_wb16(pb, track->enc->width); /* Video width */
1268 avio_wb16(pb, track->height); /* Video height */
1269 avio_wb32(pb, 0x00480000); /* Horizontal resolution 72dpi */
1270 avio_wb32(pb, 0x00480000); /* Vertical resolution 72dpi */
1271 avio_wb32(pb, 0); /* Data size (= 0) */
1272 avio_wb16(pb, 1); /* Frame count (= 1) */
1274 /* FIXME not sure, ISO 14496-1 draft where it shall be set to 0 */
1275 find_compressor(compressor_name, 32, track);
1276 avio_w8(pb, strlen(compressor_name));
1277 avio_write(pb, compressor_name, 31);
1279 if (track->mode == MODE_MOV && track->enc->bits_per_coded_sample)
1280 avio_wb16(pb, track->enc->bits_per_coded_sample);
1282 avio_wb16(pb, 0x18); /* Reserved */
1283 avio_wb16(pb, 0xffff); /* Reserved */
1284 if (track->tag == MKTAG('m','p','4','v'))
1285 mov_write_esds_tag(pb, track);
1286 else if (track->enc->codec_id == AV_CODEC_ID_H263)
1287 mov_write_d263_tag(pb);
1288 else if (track->enc->codec_id == AV_CODEC_ID_AVUI ||
1289 track->enc->codec_id == AV_CODEC_ID_SVQ3) {
1290 mov_write_extradata_tag(pb, track);
1292 } else if (track->enc->codec_id == AV_CODEC_ID_DNXHD)
1293 mov_write_avid_tag(pb, track);
1294 else if (track->enc->codec_id == AV_CODEC_ID_HEVC)
1295 mov_write_hvcc_tag(pb, track);
1296 else if (track->enc->codec_id == AV_CODEC_ID_H264) {
1297 mov_write_avcc_tag(pb, track);
1298 if (track->mode == MODE_IPOD)
1299 mov_write_uuid_tag_ipod(pb);
1300 } else if (track->enc->codec_id == AV_CODEC_ID_VC1 && track->vos_len > 0)
1301 mov_write_dvc1_tag(pb, track);
1302 else if (track->enc->codec_id == AV_CODEC_ID_VP6F ||
1303 track->enc->codec_id == AV_CODEC_ID_VP6A) {
1304 /* Don't write any potential extradata here - the cropping
1305 * is signalled via the normal width/height fields. */
1306 } else if (track->vos_len > 0)
1307 mov_write_glbl_tag(pb, track);
1309 if (track->enc->codec_id != AV_CODEC_ID_H264 &&
1310 track->enc->codec_id != AV_CODEC_ID_MPEG4 &&
1311 track->enc->codec_id != AV_CODEC_ID_DNXHD)
1312 if (track->enc->field_order != AV_FIELD_UNKNOWN)
1313 mov_write_fiel_tag(pb, track);
1315 if (track->enc->sample_aspect_ratio.den && track->enc->sample_aspect_ratio.num &&
1316 track->enc->sample_aspect_ratio.den != track->enc->sample_aspect_ratio.num) {
1317 mov_write_pasp_tag(pb, track);
1320 return update_size(pb, pos);
1323 static int mov_write_rtp_tag(AVIOContext *pb, MOVTrack *track)
1325 int64_t pos = avio_tell(pb);
1326 avio_wb32(pb, 0); /* size */
1327 ffio_wfourcc(pb, "rtp ");
1328 avio_wb32(pb, 0); /* Reserved */
1329 avio_wb16(pb, 0); /* Reserved */
1330 avio_wb16(pb, 1); /* Data-reference index */
1332 avio_wb16(pb, 1); /* Hint track version */
1333 avio_wb16(pb, 1); /* Highest compatible version */
1334 avio_wb32(pb, track->max_packet_size); /* Max packet size */
1336 avio_wb32(pb, 12); /* size */
1337 ffio_wfourcc(pb, "tims");
1338 avio_wb32(pb, track->timescale);
1340 return update_size(pb, pos);
1343 static int mov_write_source_reference_tag(AVIOContext *pb, MOVTrack *track, const char *reel_name)
1345 uint64_t str_size =strlen(reel_name);
1346 int64_t pos = avio_tell(pb);
1348 if (str_size >= UINT16_MAX){
1349 av_log(NULL, AV_LOG_ERROR, "reel_name length %"PRIu64" is too large\n", str_size);
1351 return AVERROR(EINVAL);
1354 avio_wb32(pb, 0); /* size */
1355 ffio_wfourcc(pb, "name"); /* Data format */
1356 avio_wb16(pb, str_size); /* string size */
1357 avio_wb16(pb, track->language); /* langcode */
1358 avio_write(pb, reel_name, str_size); /* reel name */
1359 return update_size(pb,pos);
1362 static int mov_write_tmcd_tag(AVIOContext *pb, MOVTrack *track)
1364 int64_t pos = avio_tell(pb);
1366 int frame_duration = av_rescale(track->timescale, track->enc->time_base.num, track->enc->time_base.den);
1367 int nb_frames = 1.0/av_q2d(track->enc->time_base) + 0.5;
1368 AVDictionaryEntry *t = NULL;
1370 if (nb_frames > 255) {
1371 av_log(NULL, AV_LOG_ERROR, "fps %d is too large\n", nb_frames);
1372 return AVERROR(EINVAL);
1375 avio_wb32(pb, 0); /* size */
1376 ffio_wfourcc(pb, "tmcd"); /* Data format */
1377 avio_wb32(pb, 0); /* Reserved */
1378 avio_wb32(pb, 1); /* Data reference index */
1379 avio_wb32(pb, 0); /* Flags */
1380 avio_wb32(pb, track->timecode_flags); /* Flags (timecode) */
1381 avio_wb32(pb, track->timescale); /* Timescale */
1382 avio_wb32(pb, frame_duration); /* Frame duration */
1383 avio_w8(pb, nb_frames); /* Number of frames */
1384 avio_w8(pb, 0); /* Reserved */
1387 t = av_dict_get(track->st->metadata, "reel_name", NULL, 0);
1389 if (t && utf8len(t->value))
1390 mov_write_source_reference_tag(pb, track, t->value);
1392 avio_wb16(pb, 0); /* zero size */
1395 avio_wb32(pb, 0); /* size */
1396 ffio_wfourcc(pb, "tmcd"); /* Data format */
1397 avio_wb32(pb, 0); /* Reserved */
1398 avio_wb32(pb, 1); /* Data reference index */
1399 if (track->enc->extradata_size)
1400 avio_write(pb, track->enc->extradata, track->enc->extradata_size);
1402 return update_size(pb, pos);
1405 static int mov_write_stsd_tag(AVIOContext *pb, MOVTrack *track)
1407 int64_t pos = avio_tell(pb);
1408 avio_wb32(pb, 0); /* size */
1409 ffio_wfourcc(pb, "stsd");
1410 avio_wb32(pb, 0); /* version & flags */
1411 avio_wb32(pb, 1); /* entry count */
1412 if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO)
1413 mov_write_video_tag(pb, track);
1414 else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
1415 mov_write_audio_tag(pb, track);
1416 else if (track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE)
1417 mov_write_subtitle_tag(pb, track);
1418 else if (track->enc->codec_tag == MKTAG('r','t','p',' '))
1419 mov_write_rtp_tag(pb, track);
1420 else if (track->enc->codec_tag == MKTAG('t','m','c','d'))
1421 mov_write_tmcd_tag(pb, track);
1422 return update_size(pb, pos);
1425 static int mov_write_ctts_tag(AVIOContext *pb, MOVTrack *track)
1427 MOVStts *ctts_entries;
1428 uint32_t entries = 0;
1432 ctts_entries = av_malloc_array((track->entry + 1), sizeof(*ctts_entries)); /* worst case */
1433 ctts_entries[0].count = 1;
1434 ctts_entries[0].duration = track->cluster[0].cts;
1435 for (i = 1; i < track->entry; i++) {
1436 if (track->cluster[i].cts == ctts_entries[entries].duration) {
1437 ctts_entries[entries].count++; /* compress */
1440 ctts_entries[entries].duration = track->cluster[i].cts;
1441 ctts_entries[entries].count = 1;
1444 entries++; /* last one */
1445 atom_size = 16 + (entries * 8);
1446 avio_wb32(pb, atom_size); /* size */
1447 ffio_wfourcc(pb, "ctts");
1448 avio_wb32(pb, 0); /* version & flags */
1449 avio_wb32(pb, entries); /* entry count */
1450 for (i = 0; i < entries; i++) {
1451 avio_wb32(pb, ctts_entries[i].count);
1452 avio_wb32(pb, ctts_entries[i].duration);
1454 av_free(ctts_entries);
1458 /* Time to sample atom */
1459 static int mov_write_stts_tag(AVIOContext *pb, MOVTrack *track)
1461 MOVStts *stts_entries;
1462 uint32_t entries = -1;
1466 if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO && !track->audio_vbr) {
1467 stts_entries = av_malloc(sizeof(*stts_entries)); /* one entry */
1468 stts_entries[0].count = track->sample_count;
1469 stts_entries[0].duration = 1;
1472 stts_entries = track->entry ?
1473 av_malloc_array(track->entry, sizeof(*stts_entries)) : /* worst case */
1475 for (i = 0; i < track->entry; i++) {
1476 int duration = get_cluster_duration(track, i);
1477 if (i && duration == stts_entries[entries].duration) {
1478 stts_entries[entries].count++; /* compress */
1481 stts_entries[entries].duration = duration;
1482 stts_entries[entries].count = 1;
1485 entries++; /* last one */
1487 atom_size = 16 + (entries * 8);
1488 avio_wb32(pb, atom_size); /* size */
1489 ffio_wfourcc(pb, "stts");
1490 avio_wb32(pb, 0); /* version & flags */
1491 avio_wb32(pb, entries); /* entry count */
1492 for (i = 0; i < entries; i++) {
1493 avio_wb32(pb, stts_entries[i].count);
1494 avio_wb32(pb, stts_entries[i].duration);
1496 av_free(stts_entries);
1500 static int mov_write_dref_tag(AVIOContext *pb)
1502 avio_wb32(pb, 28); /* size */
1503 ffio_wfourcc(pb, "dref");
1504 avio_wb32(pb, 0); /* version & flags */
1505 avio_wb32(pb, 1); /* entry count */
1507 avio_wb32(pb, 0xc); /* size */
1508 //FIXME add the alis and rsrc atom
1509 ffio_wfourcc(pb, "url ");
1510 avio_wb32(pb, 1); /* version & flags */
1515 static int mov_write_stbl_tag(AVIOContext *pb, MOVTrack *track)
1517 int64_t pos = avio_tell(pb);
1518 avio_wb32(pb, 0); /* size */
1519 ffio_wfourcc(pb, "stbl");
1520 mov_write_stsd_tag(pb, track);
1521 mov_write_stts_tag(pb, track);
1522 if ((track->enc->codec_type == AVMEDIA_TYPE_VIDEO ||
1523 track->enc->codec_tag == MKTAG('r','t','p',' ')) &&
1524 track->has_keyframes && track->has_keyframes < track->entry)
1525 mov_write_stss_tag(pb, track, MOV_SYNC_SAMPLE);
1526 if (track->mode == MODE_MOV && track->flags & MOV_TRACK_STPS)
1527 mov_write_stss_tag(pb, track, MOV_PARTIAL_SYNC_SAMPLE);
1528 if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO &&
1529 track->flags & MOV_TRACK_CTTS)
1530 mov_write_ctts_tag(pb, track);
1531 mov_write_stsc_tag(pb, track);
1532 mov_write_stsz_tag(pb, track);
1533 mov_write_stco_tag(pb, track);
1534 return update_size(pb, pos);
1537 static int mov_write_dinf_tag(AVIOContext *pb)
1539 int64_t pos = avio_tell(pb);
1540 avio_wb32(pb, 0); /* size */
1541 ffio_wfourcc(pb, "dinf");
1542 mov_write_dref_tag(pb);
1543 return update_size(pb, pos);
1546 static int mov_write_nmhd_tag(AVIOContext *pb)
1549 ffio_wfourcc(pb, "nmhd");
1554 static int mov_write_tcmi_tag(AVIOContext *pb, MOVTrack *track)
1556 int64_t pos = avio_tell(pb);
1557 const char *font = "Lucida Grande";
1558 avio_wb32(pb, 0); /* size */
1559 ffio_wfourcc(pb, "tcmi"); /* timecode media information atom */
1560 avio_wb32(pb, 0); /* version & flags */
1561 avio_wb16(pb, 0); /* text font */
1562 avio_wb16(pb, 0); /* text face */
1563 avio_wb16(pb, 12); /* text size */
1564 avio_wb16(pb, 0); /* (unknown, not in the QT specs...) */
1565 avio_wb16(pb, 0x0000); /* text color (red) */
1566 avio_wb16(pb, 0x0000); /* text color (green) */
1567 avio_wb16(pb, 0x0000); /* text color (blue) */
1568 avio_wb16(pb, 0xffff); /* background color (red) */
1569 avio_wb16(pb, 0xffff); /* background color (green) */
1570 avio_wb16(pb, 0xffff); /* background color (blue) */
1571 avio_w8(pb, strlen(font)); /* font len (part of the pascal string) */
1572 avio_write(pb, font, strlen(font)); /* font name */
1573 return update_size(pb, pos);
1576 static int mov_write_gmhd_tag(AVIOContext *pb, MOVTrack *track)
1578 int64_t pos = avio_tell(pb);
1579 avio_wb32(pb, 0); /* size */
1580 ffio_wfourcc(pb, "gmhd");
1581 avio_wb32(pb, 0x18); /* gmin size */
1582 ffio_wfourcc(pb, "gmin");/* generic media info */
1583 avio_wb32(pb, 0); /* version & flags */
1584 avio_wb16(pb, 0x40); /* graphics mode = */
1585 avio_wb16(pb, 0x8000); /* opColor (r?) */
1586 avio_wb16(pb, 0x8000); /* opColor (g?) */
1587 avio_wb16(pb, 0x8000); /* opColor (b?) */
1588 avio_wb16(pb, 0); /* balance */
1589 avio_wb16(pb, 0); /* reserved */
1592 * This special text atom is required for
1593 * Apple Quicktime chapters. The contents
1594 * don't appear to be documented, so the
1595 * bytes are copied verbatim.
1597 if (track->tag != MKTAG('c','6','0','8')) {
1598 avio_wb32(pb, 0x2C); /* size */
1599 ffio_wfourcc(pb, "text");
1600 avio_wb16(pb, 0x01);
1601 avio_wb32(pb, 0x00);
1602 avio_wb32(pb, 0x00);
1603 avio_wb32(pb, 0x00);
1604 avio_wb32(pb, 0x01);
1605 avio_wb32(pb, 0x00);
1606 avio_wb32(pb, 0x00);
1607 avio_wb32(pb, 0x00);
1608 avio_wb32(pb, 0x00004000);
1609 avio_wb16(pb, 0x0000);
1612 if (track->enc->codec_tag == MKTAG('t','m','c','d')) {
1613 int64_t tmcd_pos = avio_tell(pb);
1614 avio_wb32(pb, 0); /* size */
1615 ffio_wfourcc(pb, "tmcd");
1616 mov_write_tcmi_tag(pb, track);
1617 update_size(pb, tmcd_pos);
1619 return update_size(pb, pos);
1622 static int mov_write_smhd_tag(AVIOContext *pb)
1624 avio_wb32(pb, 16); /* size */
1625 ffio_wfourcc(pb, "smhd");
1626 avio_wb32(pb, 0); /* version & flags */
1627 avio_wb16(pb, 0); /* reserved (balance, normally = 0) */
1628 avio_wb16(pb, 0); /* reserved */
1632 static int mov_write_vmhd_tag(AVIOContext *pb)
1634 avio_wb32(pb, 0x14); /* size (always 0x14) */
1635 ffio_wfourcc(pb, "vmhd");
1636 avio_wb32(pb, 0x01); /* version & flags */
1637 avio_wb64(pb, 0); /* reserved (graphics mode = copy) */
1641 static int is_clcp_track(MOVTrack *track)
1643 return track->tag == MKTAG('c','7','0','8') ||
1644 track->tag == MKTAG('c','6','0','8');
1647 static int mov_write_hdlr_tag(AVIOContext *pb, MOVTrack *track)
1649 const char *hdlr, *descr = NULL, *hdlr_type = NULL;
1650 int64_t pos = avio_tell(pb);
1654 descr = "DataHandler";
1657 hdlr = (track->mode == MODE_MOV) ? "mhlr" : "\0\0\0\0";
1658 if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1660 descr = "VideoHandler";
1661 } else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO) {
1663 descr = "SoundHandler";
1664 } else if (track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE) {
1665 if (is_clcp_track(track)) {
1667 descr = "ClosedCaptionHandler";
1669 if (track->tag == MKTAG('t','x','3','g')) {
1671 } else if (track->tag == MKTAG('m','p','4','s')) {
1676 descr = "SubtitleHandler";
1678 } else if (track->enc->codec_tag == MKTAG('r','t','p',' ')) {
1680 descr = "HintHandler";
1681 } else if (track->enc->codec_tag == MKTAG('t','m','c','d')) {
1683 descr = "TimeCodeHandler";
1686 av_get_codec_tag_string(tag_buf, sizeof(tag_buf),
1687 track->enc->codec_tag);
1689 av_log(track->enc, AV_LOG_WARNING,
1690 "Unknown hldr_type for %s / 0x%04X, writing dummy values\n",
1691 tag_buf, track->enc->codec_tag);
1694 // hdlr.name is used by some players to identify the content title
1695 // of the track. So if an alternate handler description is
1696 // specified, use it.
1697 AVDictionaryEntry *t;
1698 t = av_dict_get(track->st->metadata, "handler", NULL, 0);
1699 if (t && utf8len(t->value))
1704 avio_wb32(pb, 0); /* size */
1705 ffio_wfourcc(pb, "hdlr");
1706 avio_wb32(pb, 0); /* Version & flags */
1707 avio_write(pb, hdlr, 4); /* handler */
1708 ffio_wfourcc(pb, hdlr_type); /* handler type */
1709 avio_wb32(pb, 0); /* reserved */
1710 avio_wb32(pb, 0); /* reserved */
1711 avio_wb32(pb, 0); /* reserved */
1712 if (!track || track->mode == MODE_MOV)
1713 avio_w8(pb, strlen(descr)); /* pascal string */
1714 avio_write(pb, descr, strlen(descr)); /* handler description */
1715 if (track && track->mode != MODE_MOV)
1716 avio_w8(pb, 0); /* c string */
1717 return update_size(pb, pos);
1720 static int mov_write_hmhd_tag(AVIOContext *pb)
1722 /* This atom must be present, but leaving the values at zero
1723 * seems harmless. */
1724 avio_wb32(pb, 28); /* size */
1725 ffio_wfourcc(pb, "hmhd");
1726 avio_wb32(pb, 0); /* version, flags */
1727 avio_wb16(pb, 0); /* maxPDUsize */
1728 avio_wb16(pb, 0); /* avgPDUsize */
1729 avio_wb32(pb, 0); /* maxbitrate */
1730 avio_wb32(pb, 0); /* avgbitrate */
1731 avio_wb32(pb, 0); /* reserved */
1735 static int mov_write_minf_tag(AVIOContext *pb, MOVTrack *track)
1737 int64_t pos = avio_tell(pb);
1738 avio_wb32(pb, 0); /* size */
1739 ffio_wfourcc(pb, "minf");
1740 if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO)
1741 mov_write_vmhd_tag(pb);
1742 else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
1743 mov_write_smhd_tag(pb);
1744 else if (track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE) {
1745 if (track->tag == MKTAG('t','e','x','t') || is_clcp_track(track)) {
1746 mov_write_gmhd_tag(pb, track);
1748 mov_write_nmhd_tag(pb);
1750 } else if (track->tag == MKTAG('r','t','p',' ')) {
1751 mov_write_hmhd_tag(pb);
1752 } else if (track->tag == MKTAG('t','m','c','d')) {
1753 mov_write_gmhd_tag(pb, track);
1755 if (track->mode == MODE_MOV) /* FIXME: Why do it for MODE_MOV only ? */
1756 mov_write_hdlr_tag(pb, NULL);
1757 mov_write_dinf_tag(pb);
1758 mov_write_stbl_tag(pb, track);
1759 return update_size(pb, pos);
1762 static int mov_write_mdhd_tag(AVIOContext *pb, MOVTrack *track)
1764 int version = track->track_duration < INT32_MAX ? 0 : 1;
1766 if (track->mode == MODE_ISM)
1769 (version == 1) ? avio_wb32(pb, 44) : avio_wb32(pb, 32); /* size */
1770 ffio_wfourcc(pb, "mdhd");
1771 avio_w8(pb, version);
1772 avio_wb24(pb, 0); /* flags */
1774 avio_wb64(pb, track->time);
1775 avio_wb64(pb, track->time);
1777 avio_wb32(pb, track->time); /* creation time */
1778 avio_wb32(pb, track->time); /* modification time */
1780 avio_wb32(pb, track->timescale); /* time scale (sample rate for audio) */
1782 (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
1784 (version == 1) ? avio_wb64(pb, track->track_duration) : avio_wb32(pb, track->track_duration); /* duration */
1785 avio_wb16(pb, track->language); /* language */
1786 avio_wb16(pb, 0); /* reserved (quality) */
1788 if (version != 0 && track->mode == MODE_MOV) {
1789 av_log(NULL, AV_LOG_ERROR,
1790 "FATAL error, file duration too long for timebase, this file will not be\n"
1791 "playable with quicktime. Choose a different timebase or a different\n"
1792 "container format\n");
1798 static int mov_write_mdia_tag(AVIOContext *pb, MOVTrack *track)
1800 int64_t pos = avio_tell(pb);
1801 avio_wb32(pb, 0); /* size */
1802 ffio_wfourcc(pb, "mdia");
1803 mov_write_mdhd_tag(pb, track);
1804 mov_write_hdlr_tag(pb, track);
1805 mov_write_minf_tag(pb, track);
1806 return update_size(pb, pos);
1809 /* transformation matrix
1813 static void write_matrix(AVIOContext *pb, int16_t a, int16_t b, int16_t c,
1814 int16_t d, int16_t tx, int16_t ty)
1816 avio_wb32(pb, a << 16); /* 16.16 format */
1817 avio_wb32(pb, b << 16); /* 16.16 format */
1818 avio_wb32(pb, 0); /* u in 2.30 format */
1819 avio_wb32(pb, c << 16); /* 16.16 format */
1820 avio_wb32(pb, d << 16); /* 16.16 format */
1821 avio_wb32(pb, 0); /* v in 2.30 format */
1822 avio_wb32(pb, tx << 16); /* 16.16 format */
1823 avio_wb32(pb, ty << 16); /* 16.16 format */
1824 avio_wb32(pb, 1 << 30); /* w in 2.30 format */
1827 static int mov_write_tkhd_tag(AVIOContext *pb, MOVMuxContext *mov,
1828 MOVTrack *track, AVStream *st)
1830 int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE,
1831 track->timescale, AV_ROUND_UP);
1832 int version = duration < INT32_MAX ? 0 : 1;
1833 int flags = MOV_TKHD_FLAG_IN_MOVIE;
1839 if (mov->per_stream_grouping)
1842 group = st->codec->codec_type;
1845 if (track->flags & MOV_TRACK_ENABLED)
1846 flags |= MOV_TKHD_FLAG_ENABLED;
1848 if (track->mode == MODE_ISM)
1851 (version == 1) ? avio_wb32(pb, 104) : avio_wb32(pb, 92); /* size */
1852 ffio_wfourcc(pb, "tkhd");
1853 avio_w8(pb, version);
1854 avio_wb24(pb, flags);
1856 avio_wb64(pb, track->time);
1857 avio_wb64(pb, track->time);
1859 avio_wb32(pb, track->time); /* creation time */
1860 avio_wb32(pb, track->time); /* modification time */
1862 avio_wb32(pb, track->track_id); /* track-id */
1863 avio_wb32(pb, 0); /* reserved */
1865 (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
1867 (version == 1) ? avio_wb64(pb, duration) : avio_wb32(pb, duration);
1869 avio_wb32(pb, 0); /* reserved */
1870 avio_wb32(pb, 0); /* reserved */
1871 avio_wb16(pb, 0); /* layer */
1872 avio_wb16(pb, group); /* alternate group) */
1873 /* Volume, only for audio */
1874 if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
1875 avio_wb16(pb, 0x0100);
1878 avio_wb16(pb, 0); /* reserved */
1880 /* Matrix structure */
1881 if (st && st->metadata) {
1882 AVDictionaryEntry *rot = av_dict_get(st->metadata, "rotate", NULL, 0);
1883 rotation = (rot && rot->value) ? atoi(rot->value) : 0;
1885 if (rotation == 90) {
1886 write_matrix(pb, 0, 1, -1, 0, track->enc->height, 0);
1887 } else if (rotation == 180) {
1888 write_matrix(pb, -1, 0, 0, -1, track->enc->width, track->enc->height);
1889 } else if (rotation == 270) {
1890 write_matrix(pb, 0, -1, 1, 0, 0, track->enc->width);
1892 write_matrix(pb, 1, 0, 0, 1, 0, 0);
1894 /* Track width and height, for visual only */
1895 if (st && (track->enc->codec_type == AVMEDIA_TYPE_VIDEO ||
1896 track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE)) {
1897 if (track->mode == MODE_MOV) {
1898 avio_wb32(pb, track->enc->width << 16);
1899 avio_wb32(pb, track->height << 16);
1901 double sample_aspect_ratio = av_q2d(st->sample_aspect_ratio);
1902 if (!sample_aspect_ratio || track->height != track->enc->height)
1903 sample_aspect_ratio = 1;
1904 avio_wb32(pb, sample_aspect_ratio * track->enc->width * 0x10000);
1905 avio_wb32(pb, track->height * 0x10000);
1914 static int mov_write_tapt_tag(AVIOContext *pb, MOVTrack *track)
1916 int32_t width = av_rescale(track->enc->sample_aspect_ratio.num, track->enc->width,
1917 track->enc->sample_aspect_ratio.den);
1919 int64_t pos = avio_tell(pb);
1921 avio_wb32(pb, 0); /* size */
1922 ffio_wfourcc(pb, "tapt");
1925 ffio_wfourcc(pb, "clef");
1927 avio_wb32(pb, width << 16);
1928 avio_wb32(pb, track->enc->height << 16);
1931 ffio_wfourcc(pb, "prof");
1933 avio_wb32(pb, width << 16);
1934 avio_wb32(pb, track->enc->height << 16);
1937 ffio_wfourcc(pb, "enof");
1939 avio_wb32(pb, track->enc->width << 16);
1940 avio_wb32(pb, track->enc->height << 16);
1942 return update_size(pb, pos);
1945 // This box seems important for the psp playback ... without it the movie seems to hang
1946 static int mov_write_edts_tag(AVIOContext *pb, MOVTrack *track)
1948 int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE,
1949 track->timescale, AV_ROUND_UP);
1950 int version = duration < INT32_MAX ? 0 : 1;
1951 int entry_size, entry_count, size;
1952 int64_t delay, start_ct = track->cluster[0].cts;
1953 delay = av_rescale_rnd(track->cluster[0].dts + start_ct, MOV_TIMESCALE,
1954 track->timescale, AV_ROUND_DOWN);
1955 version |= delay < INT32_MAX ? 0 : 1;
1957 entry_size = (version == 1) ? 20 : 12;
1958 entry_count = 1 + (delay > 0);
1959 size = 24 + entry_count * entry_size;
1961 /* write the atom data */
1962 avio_wb32(pb, size);
1963 ffio_wfourcc(pb, "edts");
1964 avio_wb32(pb, size - 8);
1965 ffio_wfourcc(pb, "elst");
1966 avio_w8(pb, version);
1967 avio_wb24(pb, 0); /* flags */
1969 avio_wb32(pb, entry_count);
1970 if (delay > 0) { /* add an empty edit to delay presentation */
1972 avio_wb64(pb, delay);
1975 avio_wb32(pb, delay);
1978 avio_wb32(pb, 0x00010000);
1980 av_assert0(av_rescale_rnd(track->cluster[0].dts, MOV_TIMESCALE, track->timescale, AV_ROUND_DOWN) <= 0);
1981 start_ct = -FFMIN(track->cluster[0].dts, 0); //FFMIN needed due to rounding
1987 avio_wb64(pb, duration);
1988 avio_wb64(pb, start_ct);
1990 avio_wb32(pb, duration);
1991 avio_wb32(pb, start_ct);
1993 avio_wb32(pb, 0x00010000);
1997 static int mov_write_tref_tag(AVIOContext *pb, MOVTrack *track)
1999 avio_wb32(pb, 20); // size
2000 ffio_wfourcc(pb, "tref");
2001 avio_wb32(pb, 12); // size (subatom)
2002 avio_wl32(pb, track->tref_tag);
2003 avio_wb32(pb, track->tref_id);
2007 // goes at the end of each track! ... Critical for PSP playback ("Incompatible data" without it)
2008 static int mov_write_uuid_tag_psp(AVIOContext *pb, MOVTrack *mov)
2010 avio_wb32(pb, 0x34); /* size ... reports as 28 in mp4box! */
2011 ffio_wfourcc(pb, "uuid");
2012 ffio_wfourcc(pb, "USMT");
2013 avio_wb32(pb, 0x21d24fce);
2014 avio_wb32(pb, 0xbb88695c);
2015 avio_wb32(pb, 0xfac9c740);
2016 avio_wb32(pb, 0x1c); // another size here!
2017 ffio_wfourcc(pb, "MTDT");
2018 avio_wb32(pb, 0x00010012);
2019 avio_wb32(pb, 0x0a);
2020 avio_wb32(pb, 0x55c40000);
2026 static int mov_write_udta_sdp(AVIOContext *pb, MOVTrack *track)
2028 AVFormatContext *ctx = track->rtp_ctx;
2029 char buf[1000] = "";
2032 ff_sdp_write_media(buf, sizeof(buf), ctx->streams[0], track->src_track,
2033 NULL, NULL, 0, 0, ctx);
2034 av_strlcatf(buf, sizeof(buf), "a=control:streamid=%d\r\n", track->track_id);
2037 avio_wb32(pb, len + 24);
2038 ffio_wfourcc(pb, "udta");
2039 avio_wb32(pb, len + 16);
2040 ffio_wfourcc(pb, "hnti");
2041 avio_wb32(pb, len + 8);
2042 ffio_wfourcc(pb, "sdp ");
2043 avio_write(pb, buf, len);
2047 static int mov_write_track_metadata(AVIOContext *pb, AVStream *st,
2048 const char *tag, const char *str)
2050 int64_t pos = avio_tell(pb);
2051 AVDictionaryEntry *t = av_dict_get(st->metadata, str, NULL, 0);
2052 if (!t || !utf8len(t->value))
2055 avio_wb32(pb, 0); /* size */
2056 ffio_wfourcc(pb, tag); /* type */
2057 avio_write(pb, t->value, strlen(t->value)); /* UTF8 string value */
2058 return update_size(pb, pos);
2061 static int mov_write_track_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
2064 AVIOContext *pb_buf;
2068 if (!st || mov->fc->flags & AVFMT_FLAG_BITEXACT)
2071 ret = avio_open_dyn_buf(&pb_buf);
2075 if (mov->mode & MODE_MP4)
2076 mov_write_track_metadata(pb_buf, st, "name", "title");
2078 if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) {
2079 avio_wb32(pb, size + 8);
2080 ffio_wfourcc(pb, "udta");
2081 avio_write(pb, buf, size);
2088 static int mov_write_trak_tag(AVIOContext *pb, MOVMuxContext *mov,
2089 MOVTrack *track, AVStream *st)
2091 int64_t pos = avio_tell(pb);
2092 avio_wb32(pb, 0); /* size */
2093 ffio_wfourcc(pb, "trak");
2094 mov_write_tkhd_tag(pb, mov, track, st);
2095 if (supports_edts(mov))
2096 mov_write_edts_tag(pb, track); // PSP Movies and several other cases require edts box
2097 if (track->tref_tag)
2098 mov_write_tref_tag(pb, track);
2099 mov_write_mdia_tag(pb, track);
2100 if (track->mode == MODE_PSP)
2101 mov_write_uuid_tag_psp(pb, track); // PSP Movies require this uuid box
2102 if (track->tag == MKTAG('r','t','p',' '))
2103 mov_write_udta_sdp(pb, track);
2104 if (track->mode == MODE_MOV) {
2105 if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) {
2106 double sample_aspect_ratio = av_q2d(st->sample_aspect_ratio);
2107 if (st->sample_aspect_ratio.num && 1.0 != sample_aspect_ratio) {
2108 mov_write_tapt_tag(pb, track);
2111 if (is_clcp_track(track) && st->sample_aspect_ratio.num) {
2112 mov_write_tapt_tag(pb, track);
2115 mov_write_track_udta_tag(pb, mov, st);
2116 return update_size(pb, pos);
2119 static int mov_write_iods_tag(AVIOContext *pb, MOVMuxContext *mov)
2121 int i, has_audio = 0, has_video = 0;
2122 int64_t pos = avio_tell(pb);
2123 int audio_profile = mov->iods_audio_profile;
2124 int video_profile = mov->iods_video_profile;
2125 for (i = 0; i < mov->nb_streams; i++) {
2126 if (mov->tracks[i].entry > 0) {
2127 has_audio |= mov->tracks[i].enc->codec_type == AVMEDIA_TYPE_AUDIO;
2128 has_video |= mov->tracks[i].enc->codec_type == AVMEDIA_TYPE_VIDEO;
2131 if (audio_profile < 0)
2132 audio_profile = 0xFF - has_audio;
2133 if (video_profile < 0)
2134 video_profile = 0xFF - has_video;
2135 avio_wb32(pb, 0x0); /* size */
2136 ffio_wfourcc(pb, "iods");
2137 avio_wb32(pb, 0); /* version & flags */
2138 put_descr(pb, 0x10, 7);
2139 avio_wb16(pb, 0x004f);
2142 avio_w8(pb, audio_profile);
2143 avio_w8(pb, video_profile);
2145 return update_size(pb, pos);
2148 static int mov_write_trex_tag(AVIOContext *pb, MOVTrack *track)
2150 avio_wb32(pb, 0x20); /* size */
2151 ffio_wfourcc(pb, "trex");
2152 avio_wb32(pb, 0); /* version & flags */
2153 avio_wb32(pb, track->track_id); /* track ID */
2154 avio_wb32(pb, 1); /* default sample description index */
2155 avio_wb32(pb, 0); /* default sample duration */
2156 avio_wb32(pb, 0); /* default sample size */
2157 avio_wb32(pb, 0); /* default sample flags */
2161 static int mov_write_mvex_tag(AVIOContext *pb, MOVMuxContext *mov)
2163 int64_t pos = avio_tell(pb);
2165 avio_wb32(pb, 0x0); /* size */
2166 ffio_wfourcc(pb, "mvex");
2167 for (i = 0; i < mov->nb_streams; i++)
2168 mov_write_trex_tag(pb, &mov->tracks[i]);
2169 return update_size(pb, pos);
2172 static int mov_write_mvhd_tag(AVIOContext *pb, MOVMuxContext *mov)
2174 int max_track_id = 1, i;
2175 int64_t max_track_len_temp, max_track_len = 0;
2178 for (i = 0; i < mov->nb_streams; i++) {
2179 if (mov->tracks[i].entry > 0 && mov->tracks[i].timescale) {
2180 max_track_len_temp = av_rescale_rnd(mov->tracks[i].track_duration,
2182 mov->tracks[i].timescale,
2184 if (max_track_len < max_track_len_temp)
2185 max_track_len = max_track_len_temp;
2186 if (max_track_id < mov->tracks[i].track_id)
2187 max_track_id = mov->tracks[i].track_id;
2191 version = max_track_len < UINT32_MAX ? 0 : 1;
2192 (version == 1) ? avio_wb32(pb, 120) : avio_wb32(pb, 108); /* size */
2193 ffio_wfourcc(pb, "mvhd");
2194 avio_w8(pb, version);
2195 avio_wb24(pb, 0); /* flags */
2197 avio_wb64(pb, mov->time);
2198 avio_wb64(pb, mov->time);
2200 avio_wb32(pb, mov->time); /* creation time */
2201 avio_wb32(pb, mov->time); /* modification time */
2203 avio_wb32(pb, MOV_TIMESCALE);
2204 (version == 1) ? avio_wb64(pb, max_track_len) : avio_wb32(pb, max_track_len); /* duration of longest track */
2206 avio_wb32(pb, 0x00010000); /* reserved (preferred rate) 1.0 = normal */
2207 avio_wb16(pb, 0x0100); /* reserved (preferred volume) 1.0 = normal */
2208 avio_wb16(pb, 0); /* reserved */
2209 avio_wb32(pb, 0); /* reserved */
2210 avio_wb32(pb, 0); /* reserved */
2212 /* Matrix structure */
2213 write_matrix(pb, 1, 0, 0, 1, 0, 0);
2215 avio_wb32(pb, 0); /* reserved (preview time) */
2216 avio_wb32(pb, 0); /* reserved (preview duration) */
2217 avio_wb32(pb, 0); /* reserved (poster time) */
2218 avio_wb32(pb, 0); /* reserved (selection time) */
2219 avio_wb32(pb, 0); /* reserved (selection duration) */
2220 avio_wb32(pb, 0); /* reserved (current time) */
2221 avio_wb32(pb, max_track_id + 1); /* Next track id */
2225 static int mov_write_itunes_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov,
2228 avio_wb32(pb, 33); /* size */
2229 ffio_wfourcc(pb, "hdlr");
2232 ffio_wfourcc(pb, "mdir");
2233 ffio_wfourcc(pb, "appl");
2240 /* helper function to write a data tag with the specified string as data */
2241 static int mov_write_string_data_tag(AVIOContext *pb, const char *data, int lang, int long_style)
2244 int size = 16 + strlen(data);
2245 avio_wb32(pb, size); /* size */
2246 ffio_wfourcc(pb, "data");
2249 avio_write(pb, data, strlen(data));
2253 lang = ff_mov_iso639_to_lang("und", 1);
2254 avio_wb16(pb, strlen(data)); /* string length */
2255 avio_wb16(pb, lang);
2256 avio_write(pb, data, strlen(data));
2257 return strlen(data) + 4;
2261 static int mov_write_string_tag(AVIOContext *pb, const char *name,
2262 const char *value, int lang, int long_style)
2265 if (value && value[0]) {
2266 int64_t pos = avio_tell(pb);
2267 avio_wb32(pb, 0); /* size */
2268 ffio_wfourcc(pb, name);
2269 mov_write_string_data_tag(pb, value, lang, long_style);
2270 size = update_size(pb, pos);
2275 static int mov_write_string_metadata(AVFormatContext *s, AVIOContext *pb,
2276 const char *name, const char *tag,
2279 int l, lang = 0, len, len2;
2280 AVDictionaryEntry *t, *t2 = NULL;
2283 if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
2286 len = strlen(t->key);
2287 snprintf(tag2, sizeof(tag2), "%s-", tag);
2288 while ((t2 = av_dict_get(s->metadata, tag2, t2, AV_DICT_IGNORE_SUFFIX))) {
2289 len2 = strlen(t2->key);
2290 if (len2 == len + 4 && !strcmp(t->value, t2->value)
2291 && (l = ff_mov_iso639_to_lang(&t2->key[len2 - 3], 1)) >= 0) {
2296 return mov_write_string_tag(pb, name, t->value, lang, long_style);
2299 /* iTunes bpm number */
2300 static int mov_write_tmpo_tag(AVIOContext *pb, AVFormatContext *s)
2302 AVDictionaryEntry *t = av_dict_get(s->metadata, "tmpo", NULL, 0);
2303 int size = 0, tmpo = t ? atoi(t->value) : 0;
2306 avio_wb32(pb, size);
2307 ffio_wfourcc(pb, "tmpo");
2308 avio_wb32(pb, size-8); /* size */
2309 ffio_wfourcc(pb, "data");
2310 avio_wb32(pb, 0x15); //type specifier
2312 avio_wb16(pb, tmpo); // data
2317 /* iTunes track or disc number */
2318 static int mov_write_trkn_tag(AVIOContext *pb, MOVMuxContext *mov,
2319 AVFormatContext *s, int disc)
2321 AVDictionaryEntry *t = av_dict_get(s->metadata,
2322 disc ? "disc" : "track",
2324 int size = 0, track = t ? atoi(t->value) : 0;
2327 char *slash = strchr(t->value, '/');
2329 tracks = atoi(slash + 1);
2330 avio_wb32(pb, 32); /* size */
2331 ffio_wfourcc(pb, disc ? "disk" : "trkn");
2332 avio_wb32(pb, 24); /* size */
2333 ffio_wfourcc(pb, "data");
2334 avio_wb32(pb, 0); // 8 bytes empty
2336 avio_wb16(pb, 0); // empty
2337 avio_wb16(pb, track); // track / disc number
2338 avio_wb16(pb, tracks); // total track / disc number
2339 avio_wb16(pb, 0); // empty
2345 static int mov_write_int8_metadata(AVFormatContext *s, AVIOContext *pb,
2346 const char *name, const char *tag,
2349 AVDictionaryEntry *t = NULL;
2351 int size = 24 + len;
2353 if (len != 1 && len != 4)
2356 if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
2358 num = atoi(t->value);
2360 avio_wb32(pb, size);
2361 ffio_wfourcc(pb, name);
2362 avio_wb32(pb, size - 8);
2363 ffio_wfourcc(pb, "data");
2364 avio_wb32(pb, 0x15);
2366 if (len==4) avio_wb32(pb, num);
2367 else avio_w8 (pb, num);
2372 /* iTunes meta data list */
2373 static int mov_write_ilst_tag(AVIOContext *pb, MOVMuxContext *mov,
2376 int64_t pos = avio_tell(pb);
2377 avio_wb32(pb, 0); /* size */
2378 ffio_wfourcc(pb, "ilst");
2379 mov_write_string_metadata(s, pb, "\251nam", "title" , 1);
2380 mov_write_string_metadata(s, pb, "\251ART", "artist" , 1);
2381 mov_write_string_metadata(s, pb, "aART", "album_artist", 1);
2382 mov_write_string_metadata(s, pb, "\251wrt", "composer" , 1);
2383 mov_write_string_metadata(s, pb, "\251alb", "album" , 1);
2384 mov_write_string_metadata(s, pb, "\251day", "date" , 1);
2386 !mov_write_string_metadata(s, pb, "\251too", "encoding_tool", 1))
2387 mov_write_string_tag(pb, "\251too", LIBAVFORMAT_IDENT, 0, 1);
2388 mov_write_string_metadata(s, pb, "\251cmt", "comment" , 1);
2389 mov_write_string_metadata(s, pb, "\251gen", "genre" , 1);
2390 mov_write_string_metadata(s, pb, "\251cpy", "copyright", 1);
2391 mov_write_string_metadata(s, pb, "\251grp", "grouping" , 1);
2392 mov_write_string_metadata(s, pb, "\251lyr", "lyrics" , 1);
2393 mov_write_string_metadata(s, pb, "desc", "description",1);
2394 mov_write_string_metadata(s, pb, "ldes", "synopsis" , 1);
2395 mov_write_string_metadata(s, pb, "tvsh", "show" , 1);
2396 mov_write_string_metadata(s, pb, "tven", "episode_id",1);
2397 mov_write_string_metadata(s, pb, "tvnn", "network" , 1);
2398 mov_write_int8_metadata (s, pb, "tves", "episode_sort",4);
2399 mov_write_int8_metadata (s, pb, "tvsn", "season_number",4);
2400 mov_write_int8_metadata (s, pb, "stik", "media_type",1);
2401 mov_write_int8_metadata (s, pb, "hdvd", "hd_video", 1);
2402 mov_write_int8_metadata (s, pb, "pgap", "gapless_playback",1);
2403 mov_write_int8_metadata (s, pb, "cpil", "compilation", 1);
2404 mov_write_trkn_tag(pb, mov, s, 0); // track number
2405 mov_write_trkn_tag(pb, mov, s, 1); // disc number
2406 mov_write_tmpo_tag(pb, s);
2407 return update_size(pb, pos);
2410 /* iTunes meta data tag */
2411 static int mov_write_meta_tag(AVIOContext *pb, MOVMuxContext *mov,
2415 int64_t pos = avio_tell(pb);
2416 avio_wb32(pb, 0); /* size */
2417 ffio_wfourcc(pb, "meta");
2419 mov_write_itunes_hdlr_tag(pb, mov, s);
2420 mov_write_ilst_tag(pb, mov, s);
2421 size = update_size(pb, pos);
2425 static int mov_write_raw_metadata_tag(AVFormatContext *s, AVIOContext *pb,
2426 const char *name, const char *key)
2429 AVDictionaryEntry *t;
2431 if (!(t = av_dict_get(s->metadata, key, NULL, 0)))
2434 len = strlen(t->value);
2437 avio_wb32(pb, size);
2438 ffio_wfourcc(pb, name);
2439 avio_write(pb, t->value, len);
2445 static int ascii_to_wc(AVIOContext *pb, const uint8_t *b)
2449 GET_UTF8(val, *b++, return -1;)
2452 avio_wb16(pb, 0x00);
2456 static uint16_t language_code(const char *str)
2458 return (((str[0] - 0x60) & 0x1F) << 10) +
2459 (((str[1] - 0x60) & 0x1F) << 5) +
2460 (( str[2] - 0x60) & 0x1F);
2463 static int mov_write_3gp_udta_tag(AVIOContext *pb, AVFormatContext *s,
2464 const char *tag, const char *str)
2466 int64_t pos = avio_tell(pb);
2467 AVDictionaryEntry *t = av_dict_get(s->metadata, str, NULL, 0);
2468 if (!t || !utf8len(t->value))
2470 avio_wb32(pb, 0); /* size */
2471 ffio_wfourcc(pb, tag); /* type */
2472 avio_wb32(pb, 0); /* version + flags */
2473 if (!strcmp(tag, "yrrc"))
2474 avio_wb16(pb, atoi(t->value));
2476 avio_wb16(pb, language_code("eng")); /* language */
2477 avio_write(pb, t->value, strlen(t->value) + 1); /* UTF8 string value */
2478 if (!strcmp(tag, "albm") &&
2479 (t = av_dict_get(s->metadata, "track", NULL, 0)))
2480 avio_w8(pb, atoi(t->value));
2482 return update_size(pb, pos);
2485 static int mov_write_chpl_tag(AVIOContext *pb, AVFormatContext *s)
2487 int64_t pos = avio_tell(pb);
2488 int i, nb_chapters = FFMIN(s->nb_chapters, 255);
2490 avio_wb32(pb, 0); // size
2491 ffio_wfourcc(pb, "chpl");
2492 avio_wb32(pb, 0x01000000); // version + flags
2493 avio_wb32(pb, 0); // unknown
2494 avio_w8(pb, nb_chapters);
2496 for (i = 0; i < nb_chapters; i++) {
2497 AVChapter *c = s->chapters[i];
2498 AVDictionaryEntry *t;
2499 avio_wb64(pb, av_rescale_q(c->start, c->time_base, (AVRational){1,10000000}));
2501 if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
2502 int len = FFMIN(strlen(t->value), 255);
2504 avio_write(pb, t->value, len);
2508 return update_size(pb, pos);
2511 static int mov_write_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
2514 AVIOContext *pb_buf;
2518 ret = avio_open_dyn_buf(&pb_buf);
2522 if (mov->mode & MODE_3GP) {
2523 mov_write_3gp_udta_tag(pb_buf, s, "perf", "artist");
2524 mov_write_3gp_udta_tag(pb_buf, s, "titl", "title");
2525 mov_write_3gp_udta_tag(pb_buf, s, "auth", "author");
2526 mov_write_3gp_udta_tag(pb_buf, s, "gnre", "genre");
2527 mov_write_3gp_udta_tag(pb_buf, s, "dscp", "comment");
2528 mov_write_3gp_udta_tag(pb_buf, s, "albm", "album");
2529 mov_write_3gp_udta_tag(pb_buf, s, "cprt", "copyright");
2530 mov_write_3gp_udta_tag(pb_buf, s, "yrrc", "date");
2531 } else if (mov->mode == MODE_MOV) { // the title field breaks gtkpod with mp4 and my suspicion is that stuff is not valid in mp4
2532 mov_write_string_metadata(s, pb_buf, "\251ART", "artist", 0);
2533 mov_write_string_metadata(s, pb_buf, "\251nam", "title", 0);
2534 mov_write_string_metadata(s, pb_buf, "\251aut", "author", 0);
2535 mov_write_string_metadata(s, pb_buf, "\251alb", "album", 0);
2536 mov_write_string_metadata(s, pb_buf, "\251day", "date", 0);
2537 mov_write_string_metadata(s, pb_buf, "\251swr", "encoder", 0);
2538 // currently ignored by mov.c
2539 mov_write_string_metadata(s, pb_buf, "\251des", "comment", 0);
2540 // add support for libquicktime, this atom is also actually read by mov.c
2541 mov_write_string_metadata(s, pb_buf, "\251cmt", "comment", 0);
2542 mov_write_string_metadata(s, pb_buf, "\251gen", "genre", 0);
2543 mov_write_string_metadata(s, pb_buf, "\251cpy", "copyright", 0);
2544 mov_write_raw_metadata_tag(s, pb_buf, "XMP_", "xmp");
2546 /* iTunes meta data */
2547 mov_write_meta_tag(pb_buf, mov, s);
2550 if (s->nb_chapters && !(mov->flags & FF_MOV_FLAG_DISABLE_CHPL))
2551 mov_write_chpl_tag(pb_buf, s);
2553 if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) {
2554 avio_wb32(pb, size + 8);
2555 ffio_wfourcc(pb, "udta");
2556 avio_write(pb, buf, size);
2563 static void mov_write_psp_udta_tag(AVIOContext *pb,
2564 const char *str, const char *lang, int type)
2566 int len = utf8len(str) + 1;
2569 avio_wb16(pb, len * 2 + 10); /* size */
2570 avio_wb32(pb, type); /* type */
2571 avio_wb16(pb, language_code(lang)); /* language */
2572 avio_wb16(pb, 0x01); /* ? */
2573 ascii_to_wc(pb, str);
2576 static int mov_write_uuidusmt_tag(AVIOContext *pb, AVFormatContext *s)
2578 MOVMuxContext *mov = s->priv_data;
2579 AVDictionaryEntry *title = av_dict_get(s->metadata, "title", NULL, 0);
2583 pos = avio_tell(pb);
2584 avio_wb32(pb, 0); /* size placeholder*/
2585 ffio_wfourcc(pb, "uuid");
2586 ffio_wfourcc(pb, "USMT");
2587 avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
2588 avio_wb32(pb, 0xbb88695c);
2589 avio_wb32(pb, 0xfac9c740);
2591 pos2 = avio_tell(pb);
2592 avio_wb32(pb, 0); /* size placeholder*/
2593 ffio_wfourcc(pb, "MTDT");
2597 avio_wb16(pb, 0x0C); /* size */
2598 avio_wb32(pb, 0x0B); /* type */
2599 avio_wb16(pb, language_code("und")); /* language */
2600 avio_wb16(pb, 0x0); /* ? */
2601 avio_wb16(pb, 0x021C); /* data */
2604 mov_write_psp_udta_tag(pb, LIBAVCODEC_IDENT, "eng", 0x04);
2605 mov_write_psp_udta_tag(pb, title->value, "eng", 0x01);
2606 mov_write_psp_udta_tag(pb, "2006/04/01 11:11:11", "und", 0x03);
2608 update_size(pb, pos2);
2609 return update_size(pb, pos);
2615 static void build_chunks(MOVTrack *trk)
2618 MOVIentry *chunk = &trk->cluster[0];
2619 uint64_t chunkSize = chunk->size;
2620 chunk->chunkNum = 1;
2621 if (trk->chunkCount)
2623 trk->chunkCount = 1;
2624 for (i = 1; i<trk->entry; i++){
2625 if (chunk->pos + chunkSize == trk->cluster[i].pos &&
2626 chunkSize + trk->cluster[i].size < (1<<20)){
2627 chunkSize += trk->cluster[i].size;
2628 chunk->samples_in_chunk += trk->cluster[i].entries;
2630 trk->cluster[i].chunkNum = chunk->chunkNum+1;
2631 chunk=&trk->cluster[i];
2632 chunkSize = chunk->size;
2638 static int mov_write_moov_tag(AVIOContext *pb, MOVMuxContext *mov,
2642 int64_t pos = avio_tell(pb);
2643 avio_wb32(pb, 0); /* size placeholder*/
2644 ffio_wfourcc(pb, "moov");
2646 for (i = 0; i < mov->nb_streams; i++) {
2647 if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
2650 mov->tracks[i].time = mov->time;
2651 mov->tracks[i].track_id = i + 1;
2653 if (mov->tracks[i].entry)
2654 build_chunks(&mov->tracks[i]);
2657 if (mov->chapter_track)
2658 for (i = 0; i < s->nb_streams; i++) {
2659 mov->tracks[i].tref_tag = MKTAG('c','h','a','p');
2660 mov->tracks[i].tref_id = mov->tracks[mov->chapter_track].track_id;
2662 for (i = 0; i < mov->nb_streams; i++) {
2663 if (mov->tracks[i].tag == MKTAG('r','t','p',' ')) {
2664 mov->tracks[i].tref_tag = MKTAG('h','i','n','t');
2665 mov->tracks[i].tref_id =
2666 mov->tracks[mov->tracks[i].src_track].track_id;
2669 for (i = 0; i < mov->nb_streams; i++) {
2670 if (mov->tracks[i].tag == MKTAG('t','m','c','d')) {
2671 int src_trk = mov->tracks[i].src_track;
2672 mov->tracks[src_trk].tref_tag = mov->tracks[i].tag;
2673 mov->tracks[src_trk].tref_id = mov->tracks[i].track_id;
2674 //src_trk may have a different timescale than the tmcd track
2675 mov->tracks[i].track_duration = av_rescale(mov->tracks[src_trk].track_duration,
2676 mov->tracks[i].timescale,
2677 mov->tracks[src_trk].timescale);
2681 mov_write_mvhd_tag(pb, mov);
2682 if (mov->mode != MODE_MOV && !mov->iods_skip)
2683 mov_write_iods_tag(pb, mov);
2684 for (i = 0; i < mov->nb_streams; i++) {
2685 if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_FRAGMENT) {
2686 mov_write_trak_tag(pb, mov, &(mov->tracks[i]), i < s->nb_streams ? s->streams[i] : NULL);
2689 if (mov->flags & FF_MOV_FLAG_FRAGMENT)
2690 mov_write_mvex_tag(pb, mov); /* QuickTime requires trak to precede this */
2692 if (mov->mode == MODE_PSP)
2693 mov_write_uuidusmt_tag(pb, s);
2695 mov_write_udta_tag(pb, mov, s);
2697 return update_size(pb, pos);
2700 static void param_write_int(AVIOContext *pb, const char *name, int value)
2702 avio_printf(pb, "<param name=\"%s\" value=\"%d\" valuetype=\"data\"/>\n", name, value);
2705 static void param_write_string(AVIOContext *pb, const char *name, const char *value)
2707 avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, value);
2710 static void param_write_hex(AVIOContext *pb, const char *name, const uint8_t *value, int len)
2713 len = FFMIN(sizeof(buf) / 2 - 1, len);
2714 ff_data_to_hex(buf, value, len, 0);
2715 buf[2 * len] = '\0';
2716 avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, buf);
2719 static int mov_write_isml_manifest(AVIOContext *pb, MOVMuxContext *mov)
2721 int64_t pos = avio_tell(pb);
2723 static const uint8_t uuid[] = {
2724 0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd,
2725 0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66
2729 ffio_wfourcc(pb, "uuid");
2730 avio_write(pb, uuid, sizeof(uuid));
2733 avio_printf(pb, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
2734 avio_printf(pb, "<smil xmlns=\"http://www.w3.org/2001/SMIL20/Language\">\n");
2735 avio_printf(pb, "<head>\n");
2737 avio_printf(pb, "<meta name=\"creator\" content=\"%s\" />\n",
2739 avio_printf(pb, "</head>\n");
2740 avio_printf(pb, "<body>\n");
2741 avio_printf(pb, "<switch>\n");
2742 for (i = 0; i < mov->nb_streams; i++) {
2743 MOVTrack *track = &mov->tracks[i];
2745 /* track->track_id is initialized in write_moov, and thus isn't known
2747 int track_id = i + 1;
2749 if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) {
2751 } else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO) {
2756 avio_printf(pb, "<%s systemBitrate=\"%d\">\n", type,
2757 track->enc->bit_rate);
2758 param_write_int(pb, "systemBitrate", track->enc->bit_rate);
2759 param_write_int(pb, "trackID", track_id);
2760 if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) {
2761 if (track->enc->codec_id == AV_CODEC_ID_H264) {
2763 int size = track->enc->extradata_size;
2764 if (!ff_avc_write_annexb_extradata(track->enc->extradata, &ptr,
2766 param_write_hex(pb, "CodecPrivateData",
2767 ptr ? ptr : track->enc->extradata,
2771 param_write_string(pb, "FourCC", "H264");
2772 } else if (track->enc->codec_id == AV_CODEC_ID_VC1) {
2773 param_write_string(pb, "FourCC", "WVC1");
2774 param_write_hex(pb, "CodecPrivateData", track->enc->extradata,
2775 track->enc->extradata_size);
2777 param_write_int(pb, "MaxWidth", track->enc->width);
2778 param_write_int(pb, "MaxHeight", track->enc->height);
2779 param_write_int(pb, "DisplayWidth", track->enc->width);
2780 param_write_int(pb, "DisplayHeight", track->enc->height);
2782 if (track->enc->codec_id == AV_CODEC_ID_AAC) {
2783 param_write_string(pb, "FourCC", "AACL");
2784 } else if (track->enc->codec_id == AV_CODEC_ID_WMAPRO) {
2785 param_write_string(pb, "FourCC", "WMAP");
2787 param_write_hex(pb, "CodecPrivateData", track->enc->extradata,
2788 track->enc->extradata_size);
2789 param_write_int(pb, "AudioTag", ff_codec_get_tag(ff_codec_wav_tags,
2790 track->enc->codec_id));
2791 param_write_int(pb, "Channels", track->enc->channels);
2792 param_write_int(pb, "SamplingRate", track->enc->sample_rate);
2793 param_write_int(pb, "BitsPerSample", 16);
2794 param_write_int(pb, "PacketSize", track->enc->block_align ?
2795 track->enc->block_align : 4);
2797 avio_printf(pb, "</%s>\n", type);
2799 avio_printf(pb, "</switch>\n");
2800 avio_printf(pb, "</body>\n");
2801 avio_printf(pb, "</smil>\n");
2803 return update_size(pb, pos);
2806 static int mov_write_mfhd_tag(AVIOContext *pb, MOVMuxContext *mov)
2809 ffio_wfourcc(pb, "mfhd");
2811 avio_wb32(pb, mov->fragments);
2815 static int mov_write_tfhd_tag(AVIOContext *pb, MOVMuxContext *mov,
2816 MOVTrack *track, int64_t moof_offset)
2818 int64_t pos = avio_tell(pb);
2819 uint32_t flags = MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
2820 MOV_TFHD_BASE_DATA_OFFSET;
2821 if (!track->entry) {
2822 flags |= MOV_TFHD_DURATION_IS_EMPTY;
2824 flags |= MOV_TFHD_DEFAULT_FLAGS;
2826 if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET)
2827 flags &= ~MOV_TFHD_BASE_DATA_OFFSET;
2829 /* Don't set a default sample size, the silverlight player refuses
2830 * to play files with that set. Don't set a default sample duration,
2831 * WMP freaks out if it is set. Don't set a base data offset, PIFF
2832 * file format says it MUST NOT be set. */
2833 if (track->mode == MODE_ISM)
2834 flags &= ~(MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
2835 MOV_TFHD_BASE_DATA_OFFSET);
2837 avio_wb32(pb, 0); /* size placeholder */
2838 ffio_wfourcc(pb, "tfhd");
2839 avio_w8(pb, 0); /* version */
2840 avio_wb24(pb, flags);
2842 avio_wb32(pb, track->track_id); /* track-id */
2843 if (flags & MOV_TFHD_BASE_DATA_OFFSET)
2844 avio_wb64(pb, moof_offset);
2845 if (flags & MOV_TFHD_DEFAULT_DURATION) {
2846 track->default_duration = get_cluster_duration(track, 0);
2847 avio_wb32(pb, track->default_duration);
2849 if (flags & MOV_TFHD_DEFAULT_SIZE) {
2850 track->default_size = track->entry ? track->cluster[0].size : 1;
2851 avio_wb32(pb, track->default_size);
2853 track->default_size = -1;
2855 if (flags & MOV_TFHD_DEFAULT_FLAGS) {
2856 track->default_sample_flags =
2857 track->enc->codec_type == AVMEDIA_TYPE_VIDEO ?
2858 (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC) :
2859 MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO;
2860 avio_wb32(pb, track->default_sample_flags);
2863 return update_size(pb, pos);
2866 static uint32_t get_sample_flags(MOVTrack *track, MOVIentry *entry)
2868 return entry->flags & MOV_SYNC_SAMPLE ? MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO :
2869 (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC);
2872 static int mov_write_trun_tag(AVIOContext *pb, MOVMuxContext *mov,
2873 MOVTrack *track, int moof_size)
2875 int64_t pos = avio_tell(pb);
2876 uint32_t flags = MOV_TRUN_DATA_OFFSET;
2879 for (i = 0; i < track->entry; i++) {
2880 if (get_cluster_duration(track, i) != track->default_duration)
2881 flags |= MOV_TRUN_SAMPLE_DURATION;
2882 if (track->cluster[i].size != track->default_size)
2883 flags |= MOV_TRUN_SAMPLE_SIZE;
2884 if (i > 0 && get_sample_flags(track, &track->cluster[i]) != track->default_sample_flags)
2885 flags |= MOV_TRUN_SAMPLE_FLAGS;
2887 if (!(flags & MOV_TRUN_SAMPLE_FLAGS))
2888 flags |= MOV_TRUN_FIRST_SAMPLE_FLAGS;
2889 if (track->flags & MOV_TRACK_CTTS)
2890 flags |= MOV_TRUN_SAMPLE_CTS;
2892 avio_wb32(pb, 0); /* size placeholder */
2893 ffio_wfourcc(pb, "trun");
2894 avio_w8(pb, 0); /* version */
2895 avio_wb24(pb, flags);
2897 avio_wb32(pb, track->entry); /* sample count */
2898 if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET &&
2899 !(mov->flags & FF_MOV_FLAG_SEPARATE_MOOF) &&
2900 track->track_id != 1)
2901 avio_wb32(pb, 0); /* Later tracks follow immediately after the previous one */
2903 avio_wb32(pb, moof_size + 8 + track->data_offset +
2904 track->cluster[0].pos); /* data offset */
2905 if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS)
2906 avio_wb32(pb, get_sample_flags(track, &track->cluster[0]));
2908 for (i = 0; i < track->entry; i++) {
2909 if (flags & MOV_TRUN_SAMPLE_DURATION)
2910 avio_wb32(pb, get_cluster_duration(track, i));
2911 if (flags & MOV_TRUN_SAMPLE_SIZE)
2912 avio_wb32(pb, track->cluster[i].size);
2913 if (flags & MOV_TRUN_SAMPLE_FLAGS)
2914 avio_wb32(pb, get_sample_flags(track, &track->cluster[i]));
2915 if (flags & MOV_TRUN_SAMPLE_CTS)
2916 avio_wb32(pb, track->cluster[i].cts);
2919 return update_size(pb, pos);
2922 static int mov_write_tfxd_tag(AVIOContext *pb, MOVTrack *track)
2924 int64_t pos = avio_tell(pb);
2925 static const uint8_t uuid[] = {
2926 0x6d, 0x1d, 0x9b, 0x05, 0x42, 0xd5, 0x44, 0xe6,
2927 0x80, 0xe2, 0x14, 0x1d, 0xaf, 0xf7, 0x57, 0xb2
2930 avio_wb32(pb, 0); /* size placeholder */
2931 ffio_wfourcc(pb, "uuid");
2932 avio_write(pb, uuid, sizeof(uuid));
2935 avio_wb64(pb, track->frag_start);
2936 avio_wb64(pb, track->start_dts + track->track_duration -
2937 track->cluster[0].dts);
2939 return update_size(pb, pos);
2942 static int mov_write_tfrf_tag(AVIOContext *pb, MOVMuxContext *mov,
2943 MOVTrack *track, int entry)
2945 int n = track->nb_frag_info - 1 - entry, i;
2946 int size = 8 + 16 + 4 + 1 + 16*n;
2947 static const uint8_t uuid[] = {
2948 0xd4, 0x80, 0x7e, 0xf2, 0xca, 0x39, 0x46, 0x95,
2949 0x8e, 0x54, 0x26, 0xcb, 0x9e, 0x46, 0xa7, 0x9f
2955 avio_seek(pb, track->frag_info[entry].tfrf_offset, SEEK_SET);
2956 avio_wb32(pb, size);
2957 ffio_wfourcc(pb, "uuid");
2958 avio_write(pb, uuid, sizeof(uuid));
2962 for (i = 0; i < n; i++) {
2963 int index = entry + 1 + i;
2964 avio_wb64(pb, track->frag_info[index].time);
2965 avio_wb64(pb, track->frag_info[index].duration);
2967 if (n < mov->ism_lookahead) {
2968 int free_size = 16 * (mov->ism_lookahead - n);
2969 avio_wb32(pb, free_size);
2970 ffio_wfourcc(pb, "free");
2971 ffio_fill(pb, 0, free_size - 8);
2977 static int mov_write_tfrf_tags(AVIOContext *pb, MOVMuxContext *mov,
2980 int64_t pos = avio_tell(pb);
2982 for (i = 0; i < mov->ism_lookahead; i++) {
2983 /* Update the tfrf tag for the last ism_lookahead fragments,
2984 * nb_frag_info - 1 is the next fragment to be written. */
2985 mov_write_tfrf_tag(pb, mov, track, track->nb_frag_info - 2 - i);
2987 avio_seek(pb, pos, SEEK_SET);
2991 static int mov_write_traf_tag(AVIOContext *pb, MOVMuxContext *mov,
2992 MOVTrack *track, int64_t moof_offset,
2995 int64_t pos = avio_tell(pb);
2996 avio_wb32(pb, 0); /* size placeholder */
2997 ffio_wfourcc(pb, "traf");
2999 mov_write_tfhd_tag(pb, mov, track, moof_offset);
3000 mov_write_trun_tag(pb, mov, track, moof_size);
3001 if (mov->mode == MODE_ISM) {
3002 mov_write_tfxd_tag(pb, track);
3004 if (mov->ism_lookahead) {
3005 int i, size = 16 + 4 + 1 + 16 * mov->ism_lookahead;
3007 track->tfrf_offset = avio_tell(pb);
3008 avio_wb32(pb, 8 + size);
3009 ffio_wfourcc(pb, "free");
3010 for (i = 0; i < size; i++)
3015 return update_size(pb, pos);
3018 static int mov_write_moof_tag_internal(AVIOContext *pb, MOVMuxContext *mov,
3019 int tracks, int moof_size)
3021 int64_t pos = avio_tell(pb);
3024 avio_wb32(pb, 0); /* size placeholder */
3025 ffio_wfourcc(pb, "moof");
3027 mov_write_mfhd_tag(pb, mov);
3028 for (i = 0; i < mov->nb_streams; i++) {
3029 MOVTrack *track = &mov->tracks[i];
3030 if (tracks >= 0 && i != tracks)
3034 mov_write_traf_tag(pb, mov, track, pos, moof_size);
3037 return update_size(pb, pos);
3040 static int mov_write_moof_tag(AVIOContext *pb, MOVMuxContext *mov, int tracks)
3042 AVIOContext *avio_buf;
3045 if ((ret = ffio_open_null_buf(&avio_buf)) < 0)
3047 mov_write_moof_tag_internal(avio_buf, mov, tracks, 0);
3048 moof_size = ffio_close_null_buf(avio_buf);
3049 return mov_write_moof_tag_internal(pb, mov, tracks, moof_size);
3052 static int mov_write_tfra_tag(AVIOContext *pb, MOVTrack *track)
3054 int64_t pos = avio_tell(pb);
3057 avio_wb32(pb, 0); /* size placeholder */
3058 ffio_wfourcc(pb, "tfra");
3059 avio_w8(pb, 1); /* version */
3062 avio_wb32(pb, track->track_id);
3063 avio_wb32(pb, 0); /* length of traf/trun/sample num */
3064 avio_wb32(pb, track->nb_frag_info);
3065 for (i = 0; i < track->nb_frag_info; i++) {
3066 avio_wb64(pb, track->frag_info[i].time);
3067 avio_wb64(pb, track->frag_info[i].offset);
3068 avio_w8(pb, 1); /* traf number */
3069 avio_w8(pb, 1); /* trun number */
3070 avio_w8(pb, 1); /* sample number */
3073 return update_size(pb, pos);
3076 static int mov_write_mfra_tag(AVIOContext *pb, MOVMuxContext *mov)
3078 int64_t pos = avio_tell(pb);
3081 avio_wb32(pb, 0); /* size placeholder */
3082 ffio_wfourcc(pb, "mfra");
3083 /* An empty mfra atom is enough to indicate to the publishing point that
3084 * the stream has ended. */
3085 if (mov->flags & FF_MOV_FLAG_ISML)
3086 return update_size(pb, pos);
3088 for (i = 0; i < mov->nb_streams; i++) {
3089 MOVTrack *track = &mov->tracks[i];
3090 if (track->nb_frag_info)
3091 mov_write_tfra_tag(pb, track);
3095 ffio_wfourcc(pb, "mfro");
3096 avio_wb32(pb, 0); /* version + flags */
3097 avio_wb32(pb, avio_tell(pb) + 4 - pos);
3099 return update_size(pb, pos);
3102 static int mov_write_mdat_tag(AVIOContext *pb, MOVMuxContext *mov)
3104 avio_wb32(pb, 8); // placeholder for extended size field (64 bit)
3105 ffio_wfourcc(pb, mov->mode == MODE_MOV ? "wide" : "free");
3107 mov->mdat_pos = avio_tell(pb);
3108 avio_wb32(pb, 0); /* size placeholder*/
3109 ffio_wfourcc(pb, "mdat");
3113 /* TODO: This needs to be more general */
3114 static int mov_write_ftyp_tag(AVIOContext *pb, AVFormatContext *s)
3116 MOVMuxContext *mov = s->priv_data;
3117 int64_t pos = avio_tell(pb);
3118 int has_h264 = 0, has_video = 0;
3122 for (i = 0; i < s->nb_streams; i++) {
3123 AVStream *st = s->streams[i];
3124 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
3126 if (st->codec->codec_id == AV_CODEC_ID_H264)
3130 avio_wb32(pb, 0); /* size */
3131 ffio_wfourcc(pb, "ftyp");
3133 if (mov->major_brand && strlen(mov->major_brand) >= 4)
3134 ffio_wfourcc(pb, mov->major_brand);
3135 else if (mov->mode == MODE_3GP) {
3136 ffio_wfourcc(pb, has_h264 ? "3gp6" : "3gp4");
3137 minor = has_h264 ? 0x100 : 0x200;
3138 } else if (mov->mode & MODE_3G2) {
3139 ffio_wfourcc(pb, has_h264 ? "3g2b" : "3g2a");
3140 minor = has_h264 ? 0x20000 : 0x10000;
3141 } else if (mov->mode == MODE_PSP)
3142 ffio_wfourcc(pb, "MSNV");
3143 else if (mov->mode == MODE_MP4)
3144 ffio_wfourcc(pb, "isom");
3145 else if (mov->mode == MODE_IPOD)
3146 ffio_wfourcc(pb, has_video ? "M4V ":"M4A ");
3147 else if (mov->mode == MODE_ISM)
3148 ffio_wfourcc(pb, "isml");
3149 else if (mov->mode == MODE_F4V)
3150 ffio_wfourcc(pb, "f4v ");
3152 ffio_wfourcc(pb, "qt ");
3154 avio_wb32(pb, minor);
3156 if (mov->mode == MODE_MOV)
3157 ffio_wfourcc(pb, "qt ");
3158 else if (mov->mode == MODE_ISM) {
3159 ffio_wfourcc(pb, "piff");
3160 ffio_wfourcc(pb, "iso2");
3162 ffio_wfourcc(pb, "isom");
3163 ffio_wfourcc(pb, "iso2");
3165 ffio_wfourcc(pb, "avc1");
3168 if (mov->mode == MODE_3GP)
3169 ffio_wfourcc(pb, has_h264 ? "3gp6":"3gp4");
3170 else if (mov->mode & MODE_3G2)
3171 ffio_wfourcc(pb, has_h264 ? "3g2b":"3g2a");
3172 else if (mov->mode == MODE_PSP)
3173 ffio_wfourcc(pb, "MSNV");
3174 else if (mov->mode == MODE_MP4)
3175 ffio_wfourcc(pb, "mp41");
3176 return update_size(pb, pos);
3179 static void mov_write_uuidprof_tag(AVIOContext *pb, AVFormatContext *s)
3181 AVStream *video_st = s->streams[0];
3182 AVCodecContext *video_codec = s->streams[0]->codec;
3183 AVCodecContext *audio_codec = s->streams[1]->codec;
3184 int audio_rate = audio_codec->sample_rate;
3185 // TODO: should be avg_frame_rate
3186 int frame_rate = ((video_st->time_base.den) * (0x10000)) / (video_st->time_base.num);
3187 int audio_kbitrate = audio_codec->bit_rate / 1000;
3188 int video_kbitrate = FFMIN(video_codec->bit_rate / 1000, 800 - audio_kbitrate);
3190 avio_wb32(pb, 0x94); /* size */
3191 ffio_wfourcc(pb, "uuid");
3192 ffio_wfourcc(pb, "PROF");
3194 avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
3195 avio_wb32(pb, 0xbb88695c);
3196 avio_wb32(pb, 0xfac9c740);
3198 avio_wb32(pb, 0x0); /* ? */
3199 avio_wb32(pb, 0x3); /* 3 sections ? */
3201 avio_wb32(pb, 0x14); /* size */
3202 ffio_wfourcc(pb, "FPRF");
3203 avio_wb32(pb, 0x0); /* ? */
3204 avio_wb32(pb, 0x0); /* ? */
3205 avio_wb32(pb, 0x0); /* ? */
3207 avio_wb32(pb, 0x2c); /* size */
3208 ffio_wfourcc(pb, "APRF"); /* audio */
3210 avio_wb32(pb, 0x2); /* TrackID */
3211 ffio_wfourcc(pb, "mp4a");
3212 avio_wb32(pb, 0x20f);
3214 avio_wb32(pb, audio_kbitrate);
3215 avio_wb32(pb, audio_kbitrate);
3216 avio_wb32(pb, audio_rate);
3217 avio_wb32(pb, audio_codec->channels);
3219 avio_wb32(pb, 0x34); /* size */
3220 ffio_wfourcc(pb, "VPRF"); /* video */
3222 avio_wb32(pb, 0x1); /* TrackID */
3223 if (video_codec->codec_id == AV_CODEC_ID_H264) {
3224 ffio_wfourcc(pb, "avc1");
3225 avio_wb16(pb, 0x014D);
3226 avio_wb16(pb, 0x0015);
3228 ffio_wfourcc(pb, "mp4v");
3229 avio_wb16(pb, 0x0000);
3230 avio_wb16(pb, 0x0103);
3233 avio_wb32(pb, video_kbitrate);
3234 avio_wb32(pb, video_kbitrate);
3235 avio_wb32(pb, frame_rate);
3236 avio_wb32(pb, frame_rate);
3237 avio_wb16(pb, video_codec->width);
3238 avio_wb16(pb, video_codec->height);
3239 avio_wb32(pb, 0x010001); /* ? */
3242 static int mov_parse_mpeg2_frame(AVPacket *pkt, uint32_t *flags)
3245 int i, closed_gop = 0;
3247 for (i = 0; i < pkt->size - 4; i++) {
3248 c = (c << 8) + pkt->data[i];
3249 if (c == 0x1b8) { // gop
3250 closed_gop = pkt->data[i + 4] >> 6 & 0x01;
3251 } else if (c == 0x100) { // pic
3252 int temp_ref = (pkt->data[i + 1] << 2) | (pkt->data[i + 2] >> 6);
3253 if (!temp_ref || closed_gop) // I picture is not reordered
3254 *flags = MOV_SYNC_SAMPLE;
3256 *flags = MOV_PARTIAL_SYNC_SAMPLE;
3263 static void mov_parse_vc1_frame(AVPacket *pkt, MOVTrack *trk, int fragment)
3265 const uint8_t *start, *next, *end = pkt->data + pkt->size;
3266 int seq = 0, entry = 0;
3267 int key = pkt->flags & AV_PKT_FLAG_KEY;
3268 start = find_next_marker(pkt->data, end);
3269 for (next = start; next < end; start = next) {
3270 next = find_next_marker(start + 4, end);
3271 switch (AV_RB32(start)) {
3272 case VC1_CODE_SEQHDR:
3275 case VC1_CODE_ENTRYPOINT:
3278 case VC1_CODE_SLICE:
3279 trk->vc1_info.slices = 1;
3283 if (!trk->entry && !fragment) {
3284 /* First packet in first fragment */
3285 trk->vc1_info.first_packet_seq = seq;
3286 trk->vc1_info.first_packet_entry = entry;
3287 } else if ((seq && !trk->vc1_info.packet_seq) ||
3288 (entry && !trk->vc1_info.packet_entry)) {
3290 for (i = 0; i < trk->entry; i++)
3291 trk->cluster[i].flags &= ~MOV_SYNC_SAMPLE;
3292 trk->has_keyframes = 0;
3294 trk->vc1_info.packet_seq = 1;
3296 trk->vc1_info.packet_entry = 1;
3298 /* First fragment */
3299 if ((!seq || trk->vc1_info.first_packet_seq) &&
3300 (!entry || trk->vc1_info.first_packet_entry)) {
3301 /* First packet had the same headers as this one, readd the
3302 * sync sample flag. */
3303 trk->cluster[0].flags |= MOV_SYNC_SAMPLE;
3304 trk->has_keyframes = 1;
3308 if (trk->vc1_info.packet_seq && trk->vc1_info.packet_entry)
3310 else if (trk->vc1_info.packet_seq)
3312 else if (trk->vc1_info.packet_entry)
3315 trk->cluster[trk->entry].flags |= MOV_SYNC_SAMPLE;
3316 trk->has_keyframes++;
3320 static int mov_flush_fragment(AVFormatContext *s)
3322 MOVMuxContext *mov = s->priv_data;
3323 int i, first_track = -1;
3324 int64_t mdat_size = 0;
3326 if (!(mov->flags & FF_MOV_FLAG_FRAGMENT))
3329 if (!(mov->flags & FF_MOV_FLAG_EMPTY_MOOV) && mov->fragments == 0) {
3330 int64_t pos = avio_tell(s->pb);
3332 int buf_size, moov_size;
3334 for (i = 0; i < mov->nb_streams; i++)
3335 if (!mov->tracks[i].entry)
3337 /* Don't write the initial moov unless all tracks have data */
3338 if (i < mov->nb_streams)
3341 moov_size = get_moov_size(s);
3342 for (i = 0; i < mov->nb_streams; i++)
3343 mov->tracks[i].data_offset = pos + moov_size + 8;
3345 mov_write_moov_tag(s->pb, mov, s);
3347 buf_size = avio_close_dyn_buf(mov->mdat_buf, &buf);
3348 mov->mdat_buf = NULL;
3349 avio_wb32(s->pb, buf_size + 8);
3350 ffio_wfourcc(s->pb, "mdat");
3351 avio_write(s->pb, buf, buf_size);
3356 for (i = 0; i < mov->nb_streams; i++) {
3357 if (mov->tracks[i].entry)
3358 mov->tracks[i].frag_start += mov->tracks[i].start_dts +
3359 mov->tracks[i].track_duration -
3360 mov->tracks[i].cluster[0].dts;
3361 mov->tracks[i].entry = 0;
3367 for (i = 0; i < mov->nb_streams; i++) {
3368 MOVTrack *track = &mov->tracks[i];
3369 if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF)
3370 track->data_offset = 0;
3372 track->data_offset = mdat_size;
3373 if (!track->mdat_buf)
3375 mdat_size += avio_tell(track->mdat_buf);
3376 if (first_track < 0)
3383 for (i = 0; i < mov->nb_streams; i++) {
3384 MOVTrack *track = &mov->tracks[i];
3385 int buf_size, write_moof = 1, moof_tracks = -1;
3387 int64_t duration = 0;
3390 duration = track->start_dts + track->track_duration -
3391 track->cluster[0].dts;
3392 if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF) {
3393 if (!track->mdat_buf)
3395 mdat_size = avio_tell(track->mdat_buf);
3398 write_moof = i == first_track;
3402 MOVFragmentInfo *info;
3404 track->nb_frag_info++;
3405 if (track->nb_frag_info >= track->frag_info_capacity) {
3406 unsigned new_capacity = track->nb_frag_info + MOV_FRAG_INFO_ALLOC_INCREMENT;
3407 if (av_reallocp_array(&track->frag_info,
3409 sizeof(*track->frag_info)))
3410 return AVERROR(ENOMEM);
3411 track->frag_info_capacity = new_capacity;
3413 info = &track->frag_info[track->nb_frag_info - 1];
3414 info->offset = avio_tell(s->pb);
3415 info->time = mov->tracks[i].frag_start;
3416 info->duration = duration;
3417 mov_write_tfrf_tags(s->pb, mov, track);
3419 mov_write_moof_tag(s->pb, mov, moof_tracks);
3420 info->tfrf_offset = track->tfrf_offset;
3423 avio_wb32(s->pb, mdat_size + 8);
3424 ffio_wfourcc(s->pb, "mdat");
3428 track->frag_start += duration;
3430 if (!track->mdat_buf)
3432 buf_size = avio_close_dyn_buf(track->mdat_buf, &buf);
3433 track->mdat_buf = NULL;
3435 avio_write(s->pb, buf, buf_size);
3445 int ff_mov_write_packet(AVFormatContext *s, AVPacket *pkt)
3447 MOVMuxContext *mov = s->priv_data;
3448 AVIOContext *pb = s->pb;
3449 MOVTrack *trk = &mov->tracks[pkt->stream_index];
3450 AVCodecContext *enc = trk->enc;
3451 unsigned int samples_in_chunk = 0;
3452 int size = pkt->size;
3453 uint8_t *reformatted_data = NULL;
3456 int64_t duration = pkt->dts - trk->cluster[trk->entry - 1].dts;
3457 if (duration < 0 || duration > INT_MAX) {
3458 av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" / timestamp: %"PRId64" is out of range for mov/mp4 format\n",
3462 pkt->dts = trk->cluster[trk->entry - 1].dts + 1;
3463 pkt->pts = AV_NOPTS_VALUE;
3465 if (pkt->duration < 0) {
3466 av_log(s, AV_LOG_ERROR, "Application provided duration: %d is invalid\n", pkt->duration);
3467 return AVERROR(EINVAL);
3470 if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
3472 if (mov->fragments > 0) {
3473 if (!trk->mdat_buf) {
3474 if ((ret = avio_open_dyn_buf(&trk->mdat_buf)) < 0)
3479 if (!mov->mdat_buf) {
3480 if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0)
3487 if (enc->codec_id == AV_CODEC_ID_AMR_NB) {
3488 /* We must find out how many AMR blocks there are in one packet */
3489 static uint16_t packed_size[16] =
3490 {13, 14, 16, 18, 20, 21, 27, 32, 6, 0, 0, 0, 0, 0, 0, 1};
3493 while (len < size && samples_in_chunk < 100) {
3494 len += packed_size[(pkt->data[len] >> 3) & 0x0F];
3497 if (samples_in_chunk > 1) {
3498 av_log(s, AV_LOG_ERROR, "fatal error, input is not a single packet, implement a AVParser for it\n");
3501 } else if (enc->codec_id == AV_CODEC_ID_ADPCM_MS ||
3502 enc->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) {
3503 samples_in_chunk = enc->frame_size;
3504 } else if (trk->sample_size)
3505 samples_in_chunk = size / trk->sample_size;
3507 samples_in_chunk = 1;
3509 /* copy extradata if it exists */
3510 if (trk->vos_len == 0 && enc->extradata_size > 0) {
3511 trk->vos_len = enc->extradata_size;
3512 trk->vos_data = av_malloc(trk->vos_len);
3513 memcpy(trk->vos_data, enc->extradata, trk->vos_len);
3516 if (enc->codec_id == AV_CODEC_ID_AAC && pkt->size > 2 &&
3517 (AV_RB16(pkt->data) & 0xfff0) == 0xfff0) {
3518 if (!s->streams[pkt->stream_index]->nb_frames) {
3519 av_log(s, AV_LOG_ERROR, "Malformed AAC bitstream detected: "
3520 "use the audio bitstream filter 'aac_adtstoasc' to fix it "
3521 "('-bsf:a aac_adtstoasc' option with ffmpeg)\n");
3524 av_log(s, AV_LOG_WARNING, "aac bitstream error\n");
3526 if (enc->codec_id == AV_CODEC_ID_H264 && trk->vos_len > 0 && *(uint8_t *)trk->vos_data != 1) {
3527 /* from x264 or from bytestream h264 */
3528 /* nal reformating needed */
3529 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
3530 ff_avc_parse_nal_units_buf(pkt->data, &reformatted_data,
3532 avio_write(pb, reformatted_data, size);
3534 size = ff_avc_parse_nal_units(pb, pkt->data, pkt->size);
3536 } else if (enc->codec_id == AV_CODEC_ID_HEVC && trk->vos_len > 6 &&
3537 (AV_RB24(trk->vos_data) == 1 || AV_RB32(trk->vos_data) == 1)) {
3538 /* extradata is Annex B, assume the bitstream is too and convert it */
3539 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
3540 ff_hevc_annexb2mp4_buf(pkt->data, &reformatted_data, &size, 0, NULL);
3541 avio_write(pb, reformatted_data, size);
3543 size = ff_hevc_annexb2mp4(pb, pkt->data, pkt->size, 0, NULL);
3546 avio_write(pb, pkt->data, size);
3549 if ((enc->codec_id == AV_CODEC_ID_DNXHD ||
3550 enc->codec_id == AV_CODEC_ID_AC3) && !trk->vos_len) {
3551 /* copy frame to create needed atoms */
3552 trk->vos_len = size;
3553 trk->vos_data = av_malloc(size);
3555 return AVERROR(ENOMEM);
3556 memcpy(trk->vos_data, pkt->data, size);
3559 if (trk->entry >= trk->cluster_capacity) {
3560 unsigned new_capacity = 2 * (trk->entry + MOV_INDEX_CLUSTER_SIZE);
3561 if (av_reallocp_array(&trk->cluster, new_capacity,
3562 sizeof(*trk->cluster)))
3563 return AVERROR(ENOMEM);
3564 trk->cluster_capacity = new_capacity;
3567 trk->cluster[trk->entry].pos = avio_tell(pb) - size;
3568 trk->cluster[trk->entry].samples_in_chunk = samples_in_chunk;
3569 trk->cluster[trk->entry].chunkNum = 0;
3570 trk->cluster[trk->entry].size = size;
3571 trk->cluster[trk->entry].entries = samples_in_chunk;
3572 trk->cluster[trk->entry].dts = pkt->dts;
3573 if (!trk->entry && trk->start_dts != AV_NOPTS_VALUE) {
3574 /* First packet of a new fragment. We already wrote the duration
3575 * of the last packet of the previous fragment based on track_duration,
3576 * which might not exactly match our dts. Therefore adjust the dts
3577 * of this packet to be what the previous packets duration implies. */
3578 trk->cluster[trk->entry].dts = trk->start_dts + trk->track_duration;
3580 if (!trk->entry && trk->start_dts == AV_NOPTS_VALUE && !supports_edts(mov)) {
3581 trk->cluster[trk->entry].dts = trk->start_dts = 0;
3583 if (trk->start_dts == AV_NOPTS_VALUE)
3584 trk->start_dts = pkt->dts;
3585 trk->track_duration = pkt->dts - trk->start_dts + pkt->duration;
3586 trk->last_sample_is_subtitle_end = 0;
3588 if (pkt->pts == AV_NOPTS_VALUE) {
3589 av_log(s, AV_LOG_WARNING, "pts has no value\n");
3590 pkt->pts = pkt->dts;
3592 if (pkt->dts != pkt->pts)
3593 trk->flags |= MOV_TRACK_CTTS;
3594 trk->cluster[trk->entry].cts = pkt->pts - pkt->dts;
3595 trk->cluster[trk->entry].flags = 0;
3596 if (enc->codec_id == AV_CODEC_ID_VC1) {
3597 mov_parse_vc1_frame(pkt, trk, mov->fragments);
3598 } else if (pkt->flags & AV_PKT_FLAG_KEY) {
3599 if (mov->mode == MODE_MOV && enc->codec_id == AV_CODEC_ID_MPEG2VIDEO &&
3600 trk->entry > 0) { // force sync sample for the first key frame
3601 mov_parse_mpeg2_frame(pkt, &trk->cluster[trk->entry].flags);
3602 if (trk->cluster[trk->entry].flags & MOV_PARTIAL_SYNC_SAMPLE)
3603 trk->flags |= MOV_TRACK_STPS;
3605 trk->cluster[trk->entry].flags = MOV_SYNC_SAMPLE;
3607 if (trk->cluster[trk->entry].flags & MOV_SYNC_SAMPLE)
3608 trk->has_keyframes++;
3611 trk->sample_count += samples_in_chunk;
3612 mov->mdat_size += size;
3614 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams)
3615 ff_mov_add_hinted_packet(s, pkt, trk->hint_track, trk->entry,
3616 reformatted_data, size);
3617 av_free(reformatted_data);
3621 static int mov_write_single_packet(AVFormatContext *s, AVPacket *pkt)
3623 MOVMuxContext *mov = s->priv_data;
3624 MOVTrack *trk = &mov->tracks[pkt->stream_index];
3625 AVCodecContext *enc = trk->enc;
3626 int64_t frag_duration = 0;
3627 int size = pkt->size;
3630 return 0; /* Discard 0 sized packets */
3632 if (trk->entry && pkt->stream_index < s->nb_streams)
3633 frag_duration = av_rescale_q(pkt->dts - trk->cluster[0].dts,
3634 s->streams[pkt->stream_index]->time_base,
3636 if ((mov->max_fragment_duration &&
3637 frag_duration >= mov->max_fragment_duration) ||
3638 (mov->max_fragment_size && mov->mdat_size + size >= mov->max_fragment_size) ||
3639 (mov->flags & FF_MOV_FLAG_FRAG_KEYFRAME &&
3640 enc->codec_type == AVMEDIA_TYPE_VIDEO &&
3641 trk->entry && pkt->flags & AV_PKT_FLAG_KEY)) {
3642 if (frag_duration >= mov->min_fragment_duration)
3643 mov_flush_fragment(s);
3646 return ff_mov_write_packet(s, pkt);
3649 static int mov_write_subtitle_end_packet(AVFormatContext *s,
3653 uint8_t data[2] = {0};
3656 av_init_packet(&end);
3657 end.size = sizeof(data);
3662 end.stream_index = stream_index;
3664 ret = mov_write_single_packet(s, &end);
3665 av_free_packet(&end);
3670 static int mov_write_packet(AVFormatContext *s, AVPacket *pkt)
3673 mov_flush_fragment(s);
3677 MOVMuxContext *mov = s->priv_data;
3679 if (!pkt->size) return 0; /* Discard 0 sized packets */
3682 * Subtitles require special handling.
3684 * 1) For full complaince, every track must have a sample at
3685 * dts == 0, which is rarely true for subtitles. So, as soon
3686 * as we see any packet with dts > 0, write an empty subtitle
3687 * at dts == 0 for any subtitle track with no samples in it.
3689 * 2) For each subtitle track, check if the current packet's
3690 * dts is past the duration of the last subtitle sample. If
3691 * so, we now need to write an end sample for that subtitle.
3693 * This must be done conditionally to allow for subtitles that
3694 * immediately replace each other, in which case an end sample
3695 * is not needed, and is, in fact, actively harmful.
3697 * 3) See mov_write_trailer for how the final end sample is
3700 for (i = 0; i < mov->nb_streams; i++) {
3701 MOVTrack *trk = &mov->tracks[i];
3704 if (trk->enc->codec_id == AV_CODEC_ID_MOV_TEXT &&
3705 trk->track_duration < pkt->dts &&
3706 (trk->entry == 0 || !trk->last_sample_is_subtitle_end)) {
3707 ret = mov_write_subtitle_end_packet(s, i, trk->track_duration);
3708 if (ret < 0) return ret;
3709 trk->last_sample_is_subtitle_end = 1;
3713 return mov_write_single_packet(s, pkt);
3717 // QuickTime chapters involve an additional text track with the chapter names
3718 // as samples, and a tref pointing from the other tracks to the chapter one.
3719 static int mov_create_chapter_track(AVFormatContext *s, int tracknum)
3723 MOVMuxContext *mov = s->priv_data;
3724 MOVTrack *track = &mov->tracks[tracknum];
3725 AVPacket pkt = { .stream_index = tracknum, .flags = AV_PKT_FLAG_KEY };
3728 track->mode = mov->mode;
3729 track->tag = MKTAG('t','e','x','t');
3730 track->timescale = MOV_TIMESCALE;
3731 track->enc = avcodec_alloc_context3(NULL);
3733 return AVERROR(ENOMEM);
3734 track->enc->codec_type = AVMEDIA_TYPE_SUBTITLE;
3736 // These properties are required to make QT recognize the chapter track
3737 uint8_t chapter_properties[43] = { 0, 0, 0, 0, 0, 0, 0, 1, };
3738 if (ff_alloc_extradata(track->enc, sizeof(chapter_properties)))
3739 return AVERROR(ENOMEM);
3740 memcpy(track->enc->extradata, chapter_properties, sizeof(chapter_properties));
3742 if (avio_open_dyn_buf(&pb) >= 0) {
3746 /* Stub header (usually for Quicktime chapter track) */
3748 avio_wb32(pb, 0x01); // displayFlags
3749 avio_w8(pb, 0x00); // horizontal justification
3750 avio_w8(pb, 0x00); // vertical justification
3751 avio_w8(pb, 0x00); // bgColourRed
3752 avio_w8(pb, 0x00); // bgColourGreen
3753 avio_w8(pb, 0x00); // bgColourBlue
3754 avio_w8(pb, 0x00); // bgColourAlpha
3756 avio_wb16(pb, 0x00); // defTextBoxTop
3757 avio_wb16(pb, 0x00); // defTextBoxLeft
3758 avio_wb16(pb, 0x00); // defTextBoxBottom
3759 avio_wb16(pb, 0x00); // defTextBoxRight
3761 avio_wb16(pb, 0x00); // startChar
3762 avio_wb16(pb, 0x00); // endChar
3763 avio_wb16(pb, 0x01); // fontID
3764 avio_w8(pb, 0x00); // fontStyleFlags
3765 avio_w8(pb, 0x00); // fontSize
3766 avio_w8(pb, 0x00); // fgColourRed
3767 avio_w8(pb, 0x00); // fgColourGreen
3768 avio_w8(pb, 0x00); // fgColourBlue
3769 avio_w8(pb, 0x00); // fgColourAlpha
3771 avio_wb32(pb, 0x0D); // box size
3772 ffio_wfourcc(pb, "ftab"); // box atom name
3773 avio_wb16(pb, 0x01); // entry count
3775 avio_wb16(pb, 0x01); // font ID
3776 avio_w8(pb, 0x00); // font name length
3778 if ((size = avio_close_dyn_buf(pb, &buf)) > 0) {
3779 track->enc->extradata = buf;
3780 track->enc->extradata_size = size;
3787 for (i = 0; i < s->nb_chapters; i++) {
3788 AVChapter *c = s->chapters[i];
3789 AVDictionaryEntry *t;
3791 int64_t end = av_rescale_q(c->end, c->time_base, (AVRational){1,MOV_TIMESCALE});
3792 pkt.pts = pkt.dts = av_rescale_q(c->start, c->time_base, (AVRational){1,MOV_TIMESCALE});
3793 pkt.duration = end - pkt.dts;
3795 if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
3796 const char encd[12] = {
3797 0x00, 0x00, 0x00, 0x0C,
3799 0x00, 0x00, 0x01, 0x00 };
3800 len = strlen(t->value);
3801 pkt.size = len + 2 + 12;
3802 pkt.data = av_malloc(pkt.size);
3804 return AVERROR(ENOMEM);
3805 AV_WB16(pkt.data, len);
3806 memcpy(pkt.data + 2, t->value, len);
3807 memcpy(pkt.data + len + 2, encd, sizeof(encd));
3808 ff_mov_write_packet(s, &pkt);
3809 av_freep(&pkt.data);
3816 static int mov_create_timecode_track(AVFormatContext *s, int index, int src_index, const char *tcstr)
3819 MOVMuxContext *mov = s->priv_data;
3820 MOVTrack *track = &mov->tracks[index];
3821 AVStream *src_st = s->streams[src_index];
3823 AVPacket pkt = {.stream_index = index, .flags = AV_PKT_FLAG_KEY, .size = 4};
3824 AVRational rate = find_fps(s, src_st);
3826 /* compute the frame number */
3827 ret = av_timecode_init_from_string(&tc, rate, tcstr, s);
3831 /* tmcd track based on video stream */
3832 track->mode = mov->mode;
3833 track->tag = MKTAG('t','m','c','d');
3834 track->src_track = src_index;
3835 track->timescale = mov->tracks[src_index].timescale;
3836 if (tc.flags & AV_TIMECODE_FLAG_DROPFRAME)
3837 track->timecode_flags |= MOV_TIMECODE_FLAG_DROPFRAME;
3839 /* set st to src_st for metadata access*/
3842 /* encode context: tmcd data stream */
3843 track->enc = avcodec_alloc_context3(NULL);
3844 track->enc->codec_type = AVMEDIA_TYPE_DATA;
3845 track->enc->codec_tag = track->tag;
3846 track->enc->time_base = av_inv_q(rate);
3848 /* the tmcd track just contains one packet with the frame number */
3849 pkt.data = av_malloc(pkt.size);
3850 AV_WB32(pkt.data, tc.start);
3851 ret = ff_mov_write_packet(s, &pkt);
3857 * st->disposition controls the "enabled" flag in the tkhd tag.
3858 * QuickTime will not play a track if it is not enabled. So make sure
3859 * that one track of each type (audio, video, subtitle) is enabled.
3861 * Subtitles are special. For audio and video, setting "enabled" also
3862 * makes the track "default" (i.e. it is rendered when played). For
3863 * subtitles, an "enabled" subtitle is not rendered by default, but
3864 * if no subtitle is enabled, the subtitle menu in QuickTime will be
3867 static void enable_tracks(AVFormatContext *s)
3869 MOVMuxContext *mov = s->priv_data;
3871 int enabled[AVMEDIA_TYPE_NB];
3872 int first[AVMEDIA_TYPE_NB];
3874 for (i = 0; i < AVMEDIA_TYPE_NB; i++) {
3879 for (i = 0; i < s->nb_streams; i++) {
3880 AVStream *st = s->streams[i];
3882 if (st->codec->codec_type <= AVMEDIA_TYPE_UNKNOWN ||
3883 st->codec->codec_type >= AVMEDIA_TYPE_NB)
3886 if (first[st->codec->codec_type] < 0)
3887 first[st->codec->codec_type] = i;
3888 if (st->disposition & AV_DISPOSITION_DEFAULT) {
3889 mov->tracks[i].flags |= MOV_TRACK_ENABLED;
3890 enabled[st->codec->codec_type]++;
3894 for (i = 0; i < AVMEDIA_TYPE_NB; i++) {
3896 case AVMEDIA_TYPE_VIDEO:
3897 case AVMEDIA_TYPE_AUDIO:
3898 case AVMEDIA_TYPE_SUBTITLE:
3900 mov->per_stream_grouping = 1;
3901 if (!enabled[i] && first[i] >= 0)
3902 mov->tracks[first[i]].flags |= MOV_TRACK_ENABLED;
3908 static void mov_free(AVFormatContext *s)
3910 MOVMuxContext *mov = s->priv_data;
3913 if (mov->chapter_track) {
3914 if (mov->tracks[mov->chapter_track].enc)
3915 av_freep(&mov->tracks[mov->chapter_track].enc->extradata);
3916 av_freep(&mov->tracks[mov->chapter_track].enc);
3919 for (i = 0; i < mov->nb_streams; i++) {
3920 if (mov->tracks[i].tag == MKTAG('r','t','p',' '))
3921 ff_mov_close_hinting(&mov->tracks[i]);
3922 else if (mov->tracks[i].tag == MKTAG('t','m','c','d') && mov->nb_meta_tmcd)
3923 av_freep(&mov->tracks[i].enc);
3924 av_freep(&mov->tracks[i].cluster);
3925 av_freep(&mov->tracks[i].frag_info);
3927 if (mov->tracks[i].vos_len)
3928 av_freep(&mov->tracks[i].vos_data);
3931 av_freep(&mov->tracks);
3934 static uint32_t rgb_to_yuv(uint32_t rgb)
3939 r = (rgb >> 16) & 0xFF;
3940 g = (rgb >> 8) & 0xFF;
3943 y = av_clip_uint8( 16. + 0.257 * r + 0.504 * g + 0.098 * b);
3944 cb = av_clip_uint8(128. - 0.148 * r - 0.291 * g + 0.439 * b);
3945 cr = av_clip_uint8(128. + 0.439 * r - 0.368 * g - 0.071 * b);
3947 return (y << 16) | (cr << 8) | cb;
3950 static int mov_create_dvd_sub_decoder_specific_info(MOVTrack *track,
3953 int i, width = 720, height = 480;
3954 int have_palette = 0, have_size = 0;
3955 uint32_t palette[16];
3956 char *cur = st->codec->extradata;
3958 while (cur && *cur) {
3959 if (strncmp("palette:", cur, 8) == 0) {
3961 count = sscanf(cur + 8,
3962 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
3963 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
3964 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
3965 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32"",
3966 &palette[ 0], &palette[ 1], &palette[ 2], &palette[ 3],
3967 &palette[ 4], &palette[ 5], &palette[ 6], &palette[ 7],
3968 &palette[ 8], &palette[ 9], &palette[10], &palette[11],
3969 &palette[12], &palette[13], &palette[14], &palette[15]);
3971 for (i = 0; i < count; i++) {
3972 palette[i] = rgb_to_yuv(palette[i]);
3975 } else if (!strncmp("size:", cur, 5)) {
3976 sscanf(cur + 5, "%dx%d", &width, &height);
3979 if (have_palette && have_size)
3981 cur += strcspn(cur, "\n\r");
3982 cur += strspn(cur, "\n\r");
3985 track->vos_data = av_malloc(16*4);
3986 if (!track->vos_data)
3987 return AVERROR(ENOMEM);
3988 for (i = 0; i < 16; i++) {
3989 AV_WB32(track->vos_data + i * 4, palette[i]);
3991 track->vos_len = 16 * 4;
3993 st->codec->width = width;
3994 st->codec->height = track->height = height;
3999 static int mov_write_header(AVFormatContext *s)
4001 AVIOContext *pb = s->pb;
4002 MOVMuxContext *mov = s->priv_data;
4003 AVDictionaryEntry *t, *global_tcr = av_dict_get(s->metadata, "timecode", NULL, 0);
4004 int i, ret, hint_track = 0, tmcd_track = 0;
4008 /* Default mode == MP4 */
4009 mov->mode = MODE_MP4;
4012 if (!strcmp("3gp", s->oformat->name)) mov->mode = MODE_3GP;
4013 else if (!strcmp("3g2", s->oformat->name)) mov->mode = MODE_3GP|MODE_3G2;
4014 else if (!strcmp("mov", s->oformat->name)) mov->mode = MODE_MOV;
4015 else if (!strcmp("psp", s->oformat->name)) mov->mode = MODE_PSP;
4016 else if (!strcmp("ipod",s->oformat->name)) mov->mode = MODE_IPOD;
4017 else if (!strcmp("ismv",s->oformat->name)) mov->mode = MODE_ISM;
4018 else if (!strcmp("f4v", s->oformat->name)) mov->mode = MODE_F4V;
4021 if (s->flags & AVFMT_FLAG_BITEXACT)
4024 /* Set the FRAGMENT flag if any of the fragmentation methods are
4026 if (mov->max_fragment_duration || mov->max_fragment_size ||
4027 mov->flags & (FF_MOV_FLAG_EMPTY_MOOV |
4028 FF_MOV_FLAG_FRAG_KEYFRAME |
4029 FF_MOV_FLAG_FRAG_CUSTOM))
4030 mov->flags |= FF_MOV_FLAG_FRAGMENT;
4032 /* Set other implicit flags immediately */
4033 if (mov->mode == MODE_ISM)
4034 mov->flags |= FF_MOV_FLAG_EMPTY_MOOV | FF_MOV_FLAG_SEPARATE_MOOF |
4035 FF_MOV_FLAG_FRAGMENT;
4037 /* faststart: moov at the beginning of the file, if supported */
4038 if (mov->flags & FF_MOV_FLAG_FASTSTART) {
4039 if ((mov->flags & FF_MOV_FLAG_FRAGMENT) ||
4040 (s->flags & AVFMT_FLAG_CUSTOM_IO)) {
4041 av_log(s, AV_LOG_WARNING, "The faststart flag is incompatible "
4042 "with fragmentation and custom IO, disabling faststart\n");
4043 mov->flags &= ~FF_MOV_FLAG_FASTSTART;
4045 mov->reserved_moov_size = -1;
4048 if (!supports_edts(mov) && s->avoid_negative_ts < 0) {
4049 s->avoid_negative_ts = 2;
4052 /* Non-seekable output is ok if using fragmentation. If ism_lookahead
4053 * is enabled, we don't support non-seekable output at all. */
4054 if (!s->pb->seekable &&
4055 (!(mov->flags & FF_MOV_FLAG_FRAGMENT) || mov->ism_lookahead)) {
4056 av_log(s, AV_LOG_ERROR, "muxer does not support non seekable output\n");
4057 return AVERROR(EINVAL);
4060 mov_write_ftyp_tag(pb,s);
4061 if (mov->mode == MODE_PSP) {
4062 int video_streams_nb = 0, audio_streams_nb = 0, other_streams_nb = 0;
4063 for (i = 0; i < s->nb_streams; i++) {
4064 AVStream *st = s->streams[i];
4065 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
4067 else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
4073 if (video_streams_nb != 1 || audio_streams_nb != 1 || other_streams_nb) {
4074 av_log(s, AV_LOG_ERROR, "PSP mode need one video and one audio stream\n");
4075 return AVERROR(EINVAL);
4077 mov_write_uuidprof_tag(pb, s);
4080 mov->nb_streams = s->nb_streams;
4081 if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters)
4082 mov->chapter_track = mov->nb_streams++;
4084 if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
4085 /* Add hint tracks for each audio and video stream */
4086 hint_track = mov->nb_streams;
4087 for (i = 0; i < s->nb_streams; i++) {
4088 AVStream *st = s->streams[i];
4089 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO ||
4090 st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
4096 if (mov->mode == MODE_MOV) {
4097 tmcd_track = mov->nb_streams;
4099 /* +1 tmcd track for each video stream with a timecode */
4100 for (i = 0; i < s->nb_streams; i++) {
4101 AVStream *st = s->streams[i];
4102 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
4103 (global_tcr || av_dict_get(st->metadata, "timecode", NULL, 0)))
4104 mov->nb_meta_tmcd++;
4107 /* check if there is already a tmcd track to remux */
4108 if (mov->nb_meta_tmcd) {
4109 for (i = 0; i < s->nb_streams; i++) {
4110 AVStream *st = s->streams[i];
4111 if (st->codec->codec_tag == MKTAG('t','m','c','d')) {
4112 av_log(s, AV_LOG_WARNING, "You requested a copy of the original timecode track "
4113 "so timecode metadata are now ignored\n");
4114 mov->nb_meta_tmcd = 0;
4119 mov->nb_streams += mov->nb_meta_tmcd;
4122 // Reserve an extra stream for chapters for the case where chapters
4123 // are written in the trailer
4124 mov->tracks = av_mallocz_array((mov->nb_streams + 1), sizeof(*mov->tracks));
4126 return AVERROR(ENOMEM);
4128 for (i = 0; i < s->nb_streams; i++) {
4129 AVStream *st= s->streams[i];
4130 MOVTrack *track= &mov->tracks[i];
4131 AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0);
4134 track->enc = st->codec;
4135 track->language = ff_mov_iso639_to_lang(lang?lang->value:"und", mov->mode!=MODE_MOV);
4136 if (track->language < 0)
4137 track->language = 0;
4138 track->mode = mov->mode;
4139 track->tag = mov_find_codec_tag(s, track);
4141 av_log(s, AV_LOG_ERROR, "Could not find tag for codec %s in stream #%d, "
4142 "codec not currently supported in container\n",
4143 avcodec_get_name(st->codec->codec_id), i);
4144 ret = AVERROR(EINVAL);
4147 /* If hinting of this track is enabled by a later hint track,
4148 * this is updated. */
4149 track->hint_track = -1;
4150 track->start_dts = AV_NOPTS_VALUE;
4151 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
4152 if (track->tag == MKTAG('m','x','3','p') || track->tag == MKTAG('m','x','3','n') ||
4153 track->tag == MKTAG('m','x','4','p') || track->tag == MKTAG('m','x','4','n') ||
4154 track->tag == MKTAG('m','x','5','p') || track->tag == MKTAG('m','x','5','n')) {
4155 if (st->codec->width != 720 || (st->codec->height != 608 && st->codec->height != 512)) {
4156 av_log(s, AV_LOG_ERROR, "D-10/IMX must use 720x608 or 720x512 video resolution\n");
4157 ret = AVERROR(EINVAL);
4160 track->height = track->tag >> 24 == 'n' ? 486 : 576;
4162 if (mov->video_track_timescale) {
4163 track->timescale = mov->video_track_timescale;
4165 track->timescale = st->time_base.den;
4166 while(track->timescale < 10000)
4167 track->timescale *= 2;
4169 if (st->codec->width > 65535 || st->codec->height > 65535) {
4170 av_log(s, AV_LOG_ERROR, "Resolution %dx%d too large for mov/mp4\n", st->codec->width, st->codec->height);
4171 ret = AVERROR(EINVAL);
4174 if (track->mode == MODE_MOV && track->timescale > 100000)
4175 av_log(s, AV_LOG_WARNING,
4176 "WARNING codec timebase is very high. If duration is too long,\n"
4177 "file may not be playable by quicktime. Specify a shorter timebase\n"
4178 "or choose different container.\n");
4179 } else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
4180 track->timescale = st->codec->sample_rate;
4181 if (!st->codec->frame_size && !av_get_bits_per_sample(st->codec->codec_id)) {
4182 av_log(s, AV_LOG_WARNING, "track %d: codec frame size is not set\n", i);
4183 track->audio_vbr = 1;
4184 }else if (st->codec->codec_id == AV_CODEC_ID_ADPCM_MS ||
4185 st->codec->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
4186 st->codec->codec_id == AV_CODEC_ID_ILBC){
4187 if (!st->codec->block_align) {
4188 av_log(s, AV_LOG_ERROR, "track %d: codec block align is not set for adpcm\n", i);
4189 ret = AVERROR(EINVAL);
4192 track->sample_size = st->codec->block_align;
4193 }else if (st->codec->frame_size > 1){ /* assume compressed audio */
4194 track->audio_vbr = 1;
4196 track->sample_size = (av_get_bits_per_sample(st->codec->codec_id) >> 3) * st->codec->channels;
4198 if (st->codec->codec_id == AV_CODEC_ID_ILBC ||
4199 st->codec->codec_id == AV_CODEC_ID_ADPCM_IMA_QT) {
4200 track->audio_vbr = 1;
4202 if (track->mode != MODE_MOV &&
4203 track->enc->codec_id == AV_CODEC_ID_MP3 && track->timescale < 16000) {
4204 av_log(s, AV_LOG_ERROR, "track %d: muxing mp3 at %dhz is not supported\n",
4205 i, track->enc->sample_rate);
4206 ret = AVERROR(EINVAL);
4209 } else if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
4210 track->timescale = st->time_base.den;
4211 } else if (st->codec->codec_type == AVMEDIA_TYPE_DATA) {
4212 track->timescale = st->time_base.den;
4214 track->timescale = MOV_TIMESCALE;
4217 track->height = st->codec->height;
4218 /* The ism specific timescale isn't mandatory, but is assumed by
4219 * some tools, such as mp4split. */
4220 if (mov->mode == MODE_ISM)
4221 track->timescale = 10000000;
4223 avpriv_set_pts_info(st, 64, 1, track->timescale);
4225 /* copy extradata if it exists */
4226 if (st->codec->extradata_size) {
4227 if (st->codec->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
4228 mov_create_dvd_sub_decoder_specific_info(track, st);
4230 track->vos_len = st->codec->extradata_size;
4231 track->vos_data = av_malloc(track->vos_len);
4232 memcpy(track->vos_data, st->codec->extradata, track->vos_len);
4237 for (i = 0; i < s->nb_streams; i++) {
4239 AVStream *st= s->streams[i];
4240 MOVTrack *track= &mov->tracks[i];
4242 if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO ||
4243 track->enc->channel_layout != AV_CH_LAYOUT_MONO)
4246 for (j = 0; j < s->nb_streams; j++) {
4247 AVStream *stj= s->streams[j];
4248 MOVTrack *trackj= &mov->tracks[j];
4252 if (stj->codec->codec_type != AVMEDIA_TYPE_AUDIO ||
4253 trackj->enc->channel_layout != AV_CH_LAYOUT_MONO ||
4254 trackj->language != track->language ||
4255 trackj->tag != track->tag
4258 track->multichannel_as_mono++;
4265 if (mov->reserved_moov_size){
4266 mov->reserved_moov_pos= avio_tell(pb);
4267 if (mov->reserved_moov_size > 0)
4268 avio_skip(pb, mov->reserved_moov_size);
4271 if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
4272 /* If no fragmentation options have been set, set a default. */
4273 if (!(mov->flags & (FF_MOV_FLAG_FRAG_KEYFRAME |
4274 FF_MOV_FLAG_FRAG_CUSTOM)) &&
4275 !mov->max_fragment_duration && !mov->max_fragment_size)
4276 mov->flags |= FF_MOV_FLAG_FRAG_KEYFRAME;
4278 if (mov->flags & FF_MOV_FLAG_FASTSTART)
4279 mov->reserved_moov_pos = avio_tell(pb);
4280 mov_write_mdat_tag(pb, mov);
4283 if (t = av_dict_get(s->metadata, "creation_time", NULL, 0))
4284 mov->time = ff_iso8601_to_unix_time(t->value);
4286 mov->time += 0x7C25B080; // 1970 based -> 1904 based
4288 if (mov->chapter_track)
4289 if ((ret = mov_create_chapter_track(s, mov->chapter_track)) < 0)
4292 if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
4293 /* Initialize the hint tracks for each audio and video stream */
4294 for (i = 0; i < s->nb_streams; i++) {
4295 AVStream *st = s->streams[i];
4296 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO ||
4297 st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
4298 if ((ret = ff_mov_init_hinting(s, hint_track, i)) < 0)
4305 if (mov->nb_meta_tmcd) {
4306 /* Initialize the tmcd tracks */
4307 for (i = 0; i < s->nb_streams; i++) {
4308 AVStream *st = s->streams[i];
4311 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
4313 t = av_dict_get(st->metadata, "timecode", NULL, 0);
4316 if ((ret = mov_create_timecode_track(s, tmcd_track, i, t->value)) < 0)
4325 if (mov->flags & FF_MOV_FLAG_ISML)
4326 mov_write_isml_manifest(pb, mov);
4328 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
4329 mov_write_moov_tag(pb, mov, s);
4339 static int get_moov_size(AVFormatContext *s)
4342 AVIOContext *moov_buf;
4343 MOVMuxContext *mov = s->priv_data;
4345 if ((ret = ffio_open_null_buf(&moov_buf)) < 0)
4347 mov_write_moov_tag(moov_buf, mov, s);
4348 return ffio_close_null_buf(moov_buf);
4352 * This function gets the moov size if moved to the top of the file: the chunk
4353 * offset table can switch between stco (32-bit entries) to co64 (64-bit
4354 * entries) when the moov is moved to the beginning, so the size of the moov
4355 * would change. It also updates the chunk offset tables.
4357 static int compute_moov_size(AVFormatContext *s)
4359 int i, moov_size, moov_size2;
4360 MOVMuxContext *mov = s->priv_data;
4362 moov_size = get_moov_size(s);
4366 for (i = 0; i < mov->nb_streams; i++)
4367 mov->tracks[i].data_offset += moov_size;
4369 moov_size2 = get_moov_size(s);
4373 /* if the size changed, we just switched from stco to co64 and need to
4374 * update the offsets */
4375 if (moov_size2 != moov_size)
4376 for (i = 0; i < mov->nb_streams; i++)
4377 mov->tracks[i].data_offset += moov_size2 - moov_size;
4382 static int shift_data(AVFormatContext *s)
4384 int ret = 0, moov_size;
4385 MOVMuxContext *mov = s->priv_data;
4386 int64_t pos, pos_end = avio_tell(s->pb);
4387 uint8_t *buf, *read_buf[2];
4388 int read_buf_id = 0;
4390 AVIOContext *read_pb;
4392 moov_size = compute_moov_size(s);
4396 buf = av_malloc(moov_size * 2);
4398 return AVERROR(ENOMEM);
4400 read_buf[1] = buf + moov_size;
4402 /* Shift the data: the AVIO context of the output can only be used for
4403 * writing, so we re-open the same output, but for reading. It also avoids
4404 * a read/seek/write/seek back and forth. */
4406 ret = avio_open(&read_pb, s->filename, AVIO_FLAG_READ);
4408 av_log(s, AV_LOG_ERROR, "Unable to re-open %s output file for "
4409 "the second pass (faststart)\n", s->filename);
4413 /* mark the end of the shift to up to the last data we wrote, and get ready
4415 pos_end = avio_tell(s->pb);
4416 avio_seek(s->pb, mov->reserved_moov_pos + moov_size, SEEK_SET);
4418 /* start reading at where the new moov will be placed */
4419 avio_seek(read_pb, mov->reserved_moov_pos, SEEK_SET);
4420 pos = avio_tell(read_pb);
4422 #define READ_BLOCK do { \
4423 read_size[read_buf_id] = avio_read(read_pb, read_buf[read_buf_id], moov_size); \
4427 /* shift data by chunk of at most moov_size */
4432 n = read_size[read_buf_id];
4435 avio_write(s->pb, read_buf[read_buf_id], n);
4437 } while (pos < pos_end);
4438 avio_close(read_pb);
4445 static int mov_write_trailer(AVFormatContext *s)
4447 MOVMuxContext *mov = s->priv_data;
4448 AVIOContext *pb = s->pb;
4454 * Before actually writing the trailer, make sure that there are no
4455 * dangling subtitles, that need a terminating sample.
4457 for (i = 0; i < mov->nb_streams; i++) {
4458 MOVTrack *trk = &mov->tracks[i];
4459 if (trk->enc->codec_id == AV_CODEC_ID_MOV_TEXT &&
4460 !trk->last_sample_is_subtitle_end) {
4461 mov_write_subtitle_end_packet(s, i, trk->track_duration);
4462 trk->last_sample_is_subtitle_end = 1;
4466 // If there were no chapters when the header was written, but there
4467 // are chapters now, write them in the trailer. This only works
4468 // when we are not doing fragments.
4469 if (!mov->chapter_track && !(mov->flags & FF_MOV_FLAG_FRAGMENT)) {
4470 if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters) {
4471 mov->chapter_track = mov->nb_streams++;
4472 if ((res = mov_create_chapter_track(s, mov->chapter_track)) < 0)
4477 if (!(mov->flags & FF_MOV_FLAG_FRAGMENT)) {
4478 moov_pos = avio_tell(pb);
4480 /* Write size of mdat tag */
4481 if (mov->mdat_size + 8 <= UINT32_MAX) {
4482 avio_seek(pb, mov->mdat_pos, SEEK_SET);
4483 avio_wb32(pb, mov->mdat_size + 8);
4485 /* overwrite 'wide' placeholder atom */
4486 avio_seek(pb, mov->mdat_pos - 8, SEEK_SET);
4487 /* special value: real atom size will be 64 bit value after
4490 ffio_wfourcc(pb, "mdat");
4491 avio_wb64(pb, mov->mdat_size + 16);
4493 avio_seek(pb, mov->reserved_moov_size > 0 ? mov->reserved_moov_pos : moov_pos, SEEK_SET);
4495 if (mov->flags & FF_MOV_FLAG_FASTSTART) {
4496 av_log(s, AV_LOG_INFO, "Starting second pass: moving the moov atom to the beginning of the file\n");
4497 res = shift_data(s);
4499 avio_seek(s->pb, mov->reserved_moov_pos, SEEK_SET);
4500 mov_write_moov_tag(pb, mov, s);
4502 } else if (mov->reserved_moov_size > 0) {
4504 mov_write_moov_tag(pb, mov, s);
4505 size = mov->reserved_moov_size - (avio_tell(pb) - mov->reserved_moov_pos);
4507 av_log(s, AV_LOG_ERROR, "reserved_moov_size is too small, needed %"PRId64" additional\n", 8-size);
4510 avio_wb32(pb, size);
4511 ffio_wfourcc(pb, "free");
4512 ffio_fill(pb, 0, size - 8);
4513 avio_seek(pb, moov_pos, SEEK_SET);
4515 mov_write_moov_tag(pb, mov, s);
4518 mov_flush_fragment(s);
4519 mov_write_mfra_tag(pb, mov);
4522 for (i = 0; i < mov->nb_streams; i++) {
4523 if (mov->flags & FF_MOV_FLAG_FRAGMENT &&
4524 mov->tracks[i].vc1_info.struct_offset && s->pb->seekable) {
4525 int64_t off = avio_tell(pb);
4527 if (mov_write_dvc1_structs(&mov->tracks[i], buf) >= 0) {
4528 avio_seek(pb, mov->tracks[i].vc1_info.struct_offset, SEEK_SET);
4529 avio_write(pb, buf, 7);
4530 avio_seek(pb, off, SEEK_SET);
4541 #if CONFIG_MOV_MUXER
4543 AVOutputFormat ff_mov_muxer = {
4545 .long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
4546 .extensions = "mov",
4547 .priv_data_size = sizeof(MOVMuxContext),
4548 .audio_codec = AV_CODEC_ID_AAC,
4549 .video_codec = CONFIG_LIBX264_ENCODER ?
4550 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
4551 .write_header = mov_write_header,
4552 .write_packet = mov_write_packet,
4553 .write_trailer = mov_write_trailer,
4554 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
4555 .codec_tag = (const AVCodecTag* const []){
4556 ff_codec_movvideo_tags, ff_codec_movaudio_tags, 0
4558 .priv_class = &mov_muxer_class,
4561 #if CONFIG_TGP_MUXER
4563 AVOutputFormat ff_tgp_muxer = {
4565 .long_name = NULL_IF_CONFIG_SMALL("3GP (3GPP file format)"),
4566 .extensions = "3gp",
4567 .priv_data_size = sizeof(MOVMuxContext),
4568 .audio_codec = AV_CODEC_ID_AMR_NB,
4569 .video_codec = AV_CODEC_ID_H263,
4570 .write_header = mov_write_header,
4571 .write_packet = mov_write_packet,
4572 .write_trailer = mov_write_trailer,
4573 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
4574 .codec_tag = (const AVCodecTag* const []){ codec_3gp_tags, 0 },
4575 .priv_class = &tgp_muxer_class,
4578 #if CONFIG_MP4_MUXER
4580 AVOutputFormat ff_mp4_muxer = {
4582 .long_name = NULL_IF_CONFIG_SMALL("MP4 (MPEG-4 Part 14)"),
4583 .mime_type = "application/mp4",
4584 .extensions = "mp4",
4585 .priv_data_size = sizeof(MOVMuxContext),
4586 .audio_codec = AV_CODEC_ID_AAC,
4587 .video_codec = CONFIG_LIBX264_ENCODER ?
4588 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
4589 .write_header = mov_write_header,
4590 .write_packet = mov_write_packet,
4591 .write_trailer = mov_write_trailer,
4592 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
4593 .codec_tag = (const AVCodecTag* const []){ ff_mp4_obj_type, 0 },
4594 .priv_class = &mp4_muxer_class,
4597 #if CONFIG_PSP_MUXER
4599 AVOutputFormat ff_psp_muxer = {
4601 .long_name = NULL_IF_CONFIG_SMALL("PSP MP4 (MPEG-4 Part 14)"),
4602 .extensions = "mp4,psp",
4603 .priv_data_size = sizeof(MOVMuxContext),
4604 .audio_codec = AV_CODEC_ID_AAC,
4605 .video_codec = CONFIG_LIBX264_ENCODER ?
4606 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
4607 .write_header = mov_write_header,
4608 .write_packet = mov_write_packet,
4609 .write_trailer = mov_write_trailer,
4610 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
4611 .codec_tag = (const AVCodecTag* const []){ ff_mp4_obj_type, 0 },
4612 .priv_class = &psp_muxer_class,
4615 #if CONFIG_TG2_MUXER
4617 AVOutputFormat ff_tg2_muxer = {
4619 .long_name = NULL_IF_CONFIG_SMALL("3GP2 (3GPP2 file format)"),
4620 .extensions = "3g2",
4621 .priv_data_size = sizeof(MOVMuxContext),
4622 .audio_codec = AV_CODEC_ID_AMR_NB,
4623 .video_codec = AV_CODEC_ID_H263,
4624 .write_header = mov_write_header,
4625 .write_packet = mov_write_packet,
4626 .write_trailer = mov_write_trailer,
4627 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
4628 .codec_tag = (const AVCodecTag* const []){ codec_3gp_tags, 0 },
4629 .priv_class = &tg2_muxer_class,
4632 #if CONFIG_IPOD_MUXER
4634 AVOutputFormat ff_ipod_muxer = {
4636 .long_name = NULL_IF_CONFIG_SMALL("iPod H.264 MP4 (MPEG-4 Part 14)"),
4637 .mime_type = "application/mp4",
4638 .extensions = "m4v,m4a",
4639 .priv_data_size = sizeof(MOVMuxContext),
4640 .audio_codec = AV_CODEC_ID_AAC,
4641 .video_codec = AV_CODEC_ID_H264,
4642 .write_header = mov_write_header,
4643 .write_packet = mov_write_packet,
4644 .write_trailer = mov_write_trailer,
4645 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
4646 .codec_tag = (const AVCodecTag* const []){ codec_ipod_tags, 0 },
4647 .priv_class = &ipod_muxer_class,
4650 #if CONFIG_ISMV_MUXER
4652 AVOutputFormat ff_ismv_muxer = {
4654 .long_name = NULL_IF_CONFIG_SMALL("ISMV/ISMA (Smooth Streaming)"),
4655 .mime_type = "application/mp4",
4656 .extensions = "ismv,isma",
4657 .priv_data_size = sizeof(MOVMuxContext),
4658 .audio_codec = AV_CODEC_ID_AAC,
4659 .video_codec = AV_CODEC_ID_H264,
4660 .write_header = mov_write_header,
4661 .write_packet = mov_write_packet,
4662 .write_trailer = mov_write_trailer,
4663 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
4664 .codec_tag = (const AVCodecTag* const []){ ff_mp4_obj_type, 0 },
4665 .priv_class = &ismv_muxer_class,
4668 #if CONFIG_F4V_MUXER
4670 AVOutputFormat ff_f4v_muxer = {
4672 .long_name = NULL_IF_CONFIG_SMALL("F4V Adobe Flash Video"),
4673 .mime_type = "application/f4v",
4674 .extensions = "f4v",
4675 .priv_data_size = sizeof(MOVMuxContext),
4676 .audio_codec = AV_CODEC_ID_AAC,
4677 .video_codec = AV_CODEC_ID_H264,
4678 .write_header = mov_write_header,
4679 .write_packet = mov_write_packet,
4680 .write_trailer = mov_write_trailer,
4681 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH,
4682 .codec_tag = (const AVCodecTag* const []){ codec_f4v_tags, 0 },
4683 .priv_class = &f4v_muxer_class,