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 FF_RTP_FLAG_OPTS(MOVMuxContext, rtp_flags),
64 { "skip_iods", "Skip writing iods atom.", offsetof(MOVMuxContext, iods_skip), AV_OPT_TYPE_INT, {.i64 = 1}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM},
65 { "iods_audio_profile", "iods audio profile atom.", offsetof(MOVMuxContext, iods_audio_profile), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 255, AV_OPT_FLAG_ENCODING_PARAM},
66 { "iods_video_profile", "iods video profile atom.", offsetof(MOVMuxContext, iods_video_profile), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 255, AV_OPT_FLAG_ENCODING_PARAM},
67 { "frag_duration", "Maximum fragment duration", offsetof(MOVMuxContext, max_fragment_duration), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
68 { "min_frag_duration", "Minimum fragment duration", offsetof(MOVMuxContext, min_fragment_duration), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
69 { "frag_size", "Maximum fragment size", offsetof(MOVMuxContext, max_fragment_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
70 { "ism_lookahead", "Number of lookahead entries for ISM files", offsetof(MOVMuxContext, ism_lookahead), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
71 { "use_editlist", "use edit list", offsetof(MOVMuxContext, use_editlist), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 1, AV_OPT_FLAG_ENCODING_PARAM},
72 { "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},
73 { "brand", "Override major brand", offsetof(MOVMuxContext, major_brand), AV_OPT_TYPE_STRING, {.str = NULL}, .flags = AV_OPT_FLAG_ENCODING_PARAM },
77 #define MOV_CLASS(flavor)\
78 static const AVClass flavor ## _muxer_class = {\
79 .class_name = #flavor " muxer",\
80 .item_name = av_default_item_name,\
82 .version = LIBAVUTIL_VERSION_INT,\
85 static int get_moov_size(AVFormatContext *s);
87 //FIXME support 64 bit variant with wide placeholders
88 static int64_t update_size(AVIOContext *pb, int64_t pos)
90 int64_t curpos = avio_tell(pb);
91 avio_seek(pb, pos, SEEK_SET);
92 avio_wb32(pb, curpos - pos); /* rewrite size */
93 avio_seek(pb, curpos, SEEK_SET);
98 static int supports_edts(MOVMuxContext *mov)
100 // EDTS with fragments is tricky as we don't know the duration when its written
101 return (mov->use_editlist<0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT)) || mov->use_editlist>0;
104 static int co64_required(const MOVTrack *track)
106 if (track->entry > 0 && track->cluster[track->entry - 1].pos + track->data_offset > UINT32_MAX)
111 /* Chunk offset atom */
112 static int mov_write_stco_tag(AVIOContext *pb, MOVTrack *track)
115 int mode64 = co64_required(track); // use 32 bit size variant if possible
116 int64_t pos = avio_tell(pb);
117 avio_wb32(pb, 0); /* size */
119 ffio_wfourcc(pb, "co64");
121 ffio_wfourcc(pb, "stco");
122 avio_wb32(pb, 0); /* version & flags */
123 avio_wb32(pb, track->chunkCount); /* entry count */
124 for (i = 0; i < track->entry; i++) {
125 if (!track->cluster[i].chunkNum)
128 avio_wb64(pb, track->cluster[i].pos + track->data_offset);
130 avio_wb32(pb, track->cluster[i].pos + track->data_offset);
132 return update_size(pb, pos);
135 /* Sample size atom */
136 static int mov_write_stsz_tag(AVIOContext *pb, MOVTrack *track)
139 int i, j, entries = 0, tst = -1, oldtst = -1;
141 int64_t pos = avio_tell(pb);
142 avio_wb32(pb, 0); /* size */
143 ffio_wfourcc(pb, "stsz");
144 avio_wb32(pb, 0); /* version & flags */
146 for (i = 0; i < track->entry; i++) {
147 tst = track->cluster[i].size / track->cluster[i].entries;
148 if (oldtst != -1 && tst != oldtst)
151 entries += track->cluster[i].entries;
153 if (equalChunks && track->entry) {
154 int sSize = track->entry ? track->cluster[0].size / track->cluster[0].entries : 0;
155 sSize = FFMAX(1, sSize); // adpcm mono case could make sSize == 0
156 avio_wb32(pb, sSize); // sample size
157 avio_wb32(pb, entries); // sample count
159 avio_wb32(pb, 0); // sample size
160 avio_wb32(pb, entries); // sample count
161 for (i = 0; i < track->entry; i++) {
162 for (j = 0; j < track->cluster[i].entries; j++) {
163 avio_wb32(pb, track->cluster[i].size /
164 track->cluster[i].entries);
168 return update_size(pb, pos);
171 /* Sample to chunk atom */
172 static int mov_write_stsc_tag(AVIOContext *pb, MOVTrack *track)
174 int index = 0, oldval = -1, i;
175 int64_t entryPos, curpos;
177 int64_t pos = avio_tell(pb);
178 avio_wb32(pb, 0); /* size */
179 ffio_wfourcc(pb, "stsc");
180 avio_wb32(pb, 0); // version & flags
181 entryPos = avio_tell(pb);
182 avio_wb32(pb, track->chunkCount); // entry count
183 for (i = 0; i < track->entry; i++) {
184 if (oldval != track->cluster[i].samples_in_chunk && track->cluster[i].chunkNum) {
185 avio_wb32(pb, track->cluster[i].chunkNum); // first chunk
186 avio_wb32(pb, track->cluster[i].samples_in_chunk); // samples per chunk
187 avio_wb32(pb, 0x1); // sample description index
188 oldval = track->cluster[i].samples_in_chunk;
192 curpos = avio_tell(pb);
193 avio_seek(pb, entryPos, SEEK_SET);
194 avio_wb32(pb, index); // rewrite size
195 avio_seek(pb, curpos, SEEK_SET);
197 return update_size(pb, pos);
200 /* Sync sample atom */
201 static int mov_write_stss_tag(AVIOContext *pb, MOVTrack *track, uint32_t flag)
203 int64_t curpos, entryPos;
205 int64_t pos = avio_tell(pb);
206 avio_wb32(pb, 0); // size
207 ffio_wfourcc(pb, flag == MOV_SYNC_SAMPLE ? "stss" : "stps");
208 avio_wb32(pb, 0); // version & flags
209 entryPos = avio_tell(pb);
210 avio_wb32(pb, track->entry); // entry count
211 for (i = 0; i < track->entry; i++) {
212 if (track->cluster[i].flags & flag) {
213 avio_wb32(pb, i + 1);
217 curpos = avio_tell(pb);
218 avio_seek(pb, entryPos, SEEK_SET);
219 avio_wb32(pb, index); // rewrite size
220 avio_seek(pb, curpos, SEEK_SET);
221 return update_size(pb, pos);
224 static int mov_write_amr_tag(AVIOContext *pb, MOVTrack *track)
226 avio_wb32(pb, 0x11); /* size */
227 if (track->mode == MODE_MOV) ffio_wfourcc(pb, "samr");
228 else ffio_wfourcc(pb, "damr");
229 ffio_wfourcc(pb, "FFMP");
230 avio_w8(pb, 0); /* decoder version */
232 avio_wb16(pb, 0x81FF); /* Mode set (all modes for AMR_NB) */
233 avio_w8(pb, 0x00); /* Mode change period (no restriction) */
234 avio_w8(pb, 0x01); /* Frames per sample */
238 static int mov_write_ac3_tag(AVIOContext *pb, MOVTrack *track)
243 int fscod, bsid, bsmod, acmod, lfeon, frmsizecod;
245 if (track->vos_len < 7)
249 ffio_wfourcc(pb, "dac3");
251 init_get_bits(&gbc, track->vos_data + 4, (track->vos_len - 4) * 8);
252 fscod = get_bits(&gbc, 2);
253 frmsizecod = get_bits(&gbc, 6);
254 bsid = get_bits(&gbc, 5);
255 bsmod = get_bits(&gbc, 3);
256 acmod = get_bits(&gbc, 3);
258 skip_bits(&gbc, 2); // dsurmod
260 if ((acmod & 1) && acmod != 1)
261 skip_bits(&gbc, 2); // cmixlev
263 skip_bits(&gbc, 2); // surmixlev
265 lfeon = get_bits1(&gbc);
267 init_put_bits(&pbc, buf, sizeof(buf));
268 put_bits(&pbc, 2, fscod);
269 put_bits(&pbc, 5, bsid);
270 put_bits(&pbc, 3, bsmod);
271 put_bits(&pbc, 3, acmod);
272 put_bits(&pbc, 1, lfeon);
273 put_bits(&pbc, 5, frmsizecod >> 1); // bit_rate_code
274 put_bits(&pbc, 5, 0); // reserved
276 flush_put_bits(&pbc);
277 avio_write(pb, buf, sizeof(buf));
283 * This function writes extradata "as is".
284 * Extradata must be formatted like a valid atom (with size and tag).
286 static int mov_write_extradata_tag(AVIOContext *pb, MOVTrack *track)
288 avio_write(pb, track->enc->extradata, track->enc->extradata_size);
289 return track->enc->extradata_size;
292 static int mov_write_enda_tag(AVIOContext *pb)
295 ffio_wfourcc(pb, "enda");
296 avio_wb16(pb, 1); /* little endian */
300 static int mov_write_enda_tag_be(AVIOContext *pb)
303 ffio_wfourcc(pb, "enda");
304 avio_wb16(pb, 0); /* big endian */
308 static void put_descr(AVIOContext *pb, int tag, unsigned int size)
313 avio_w8(pb, (size >> (7 * i)) | 0x80);
314 avio_w8(pb, size & 0x7F);
317 static unsigned compute_avg_bitrate(MOVTrack *track)
321 if (!track->track_duration)
323 for (i = 0; i < track->entry; i++)
324 size += track->cluster[i].size;
325 return size * 8 * track->timescale / track->track_duration;
328 static int mov_write_esds_tag(AVIOContext *pb, MOVTrack *track) // Basic
330 int64_t pos = avio_tell(pb);
331 int decoder_specific_info_len = track->vos_len ? 5 + track->vos_len : 0;
332 unsigned avg_bitrate;
334 avio_wb32(pb, 0); // size
335 ffio_wfourcc(pb, "esds");
336 avio_wb32(pb, 0); // Version
339 put_descr(pb, 0x03, 3 + 5+13 + decoder_specific_info_len + 5+1);
340 avio_wb16(pb, track->track_id);
341 avio_w8(pb, 0x00); // flags (= no flags)
343 // DecoderConfig descriptor
344 put_descr(pb, 0x04, 13 + decoder_specific_info_len);
346 // Object type indication
347 if ((track->enc->codec_id == AV_CODEC_ID_MP2 ||
348 track->enc->codec_id == AV_CODEC_ID_MP3) &&
349 track->enc->sample_rate > 24000)
350 avio_w8(pb, 0x6B); // 11172-3
352 avio_w8(pb, ff_codec_get_tag(ff_mp4_obj_type, track->enc->codec_id));
354 // the following fields is made of 6 bits to identify the streamtype (4 for video, 5 for audio)
355 // plus 1 bit to indicate upstream and 1 bit set to 1 (reserved)
356 if (track->enc->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
357 avio_w8(pb, (0x38 << 2) | 1); // flags (= NeroSubpicStream)
358 else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
359 avio_w8(pb, 0x15); // flags (= Audiostream)
361 avio_w8(pb, 0x11); // flags (= Visualstream)
363 avio_wb24(pb, track->enc->rc_buffer_size >> 3); // Buffersize DB
365 avg_bitrate = compute_avg_bitrate(track);
366 // maxbitrate (FIXME should be max rate in any 1 sec window)
367 avio_wb32(pb, FFMAX3(track->enc->bit_rate, track->enc->rc_max_rate, avg_bitrate));
368 avio_wb32(pb, avg_bitrate);
370 if (track->vos_len) {
371 // DecoderSpecific info descriptor
372 put_descr(pb, 0x05, track->vos_len);
373 avio_write(pb, track->vos_data, track->vos_len);
377 put_descr(pb, 0x06, 1);
379 return update_size(pb, pos);
382 static int mov_pcm_le_gt16(enum AVCodecID codec_id)
384 return codec_id == AV_CODEC_ID_PCM_S24LE ||
385 codec_id == AV_CODEC_ID_PCM_S32LE ||
386 codec_id == AV_CODEC_ID_PCM_F32LE ||
387 codec_id == AV_CODEC_ID_PCM_F64LE;
390 static int mov_pcm_be_gt16(enum AVCodecID codec_id)
392 return codec_id == AV_CODEC_ID_PCM_S24BE ||
393 codec_id == AV_CODEC_ID_PCM_S32BE ||
394 codec_id == AV_CODEC_ID_PCM_F32BE ||
395 codec_id == AV_CODEC_ID_PCM_F64BE;
398 static int mov_write_ms_tag(AVIOContext *pb, MOVTrack *track)
401 int64_t pos = avio_tell(pb);
403 avio_wl32(pb, track->tag); // store it byteswapped
404 track->enc->codec_tag = av_bswap16(track->tag >> 16);
405 if ((ret = ff_put_wav_header(pb, track->enc, 0)) < 0)
407 return update_size(pb, pos);
410 static int mov_write_wfex_tag(AVIOContext *pb, MOVTrack *track)
413 int64_t pos = avio_tell(pb);
415 ffio_wfourcc(pb, "wfex");
416 if ((ret = ff_put_wav_header(pb, track->enc, FF_PUT_WAV_HEADER_FORCE_WAVEFORMATEX)) < 0)
418 return update_size(pb, pos);
421 static int mov_write_chan_tag(AVIOContext *pb, MOVTrack *track)
423 uint32_t layout_tag, bitmap;
424 int64_t pos = avio_tell(pb);
426 layout_tag = ff_mov_get_channel_layout_tag(track->enc->codec_id,
427 track->enc->channel_layout,
430 av_log(track->enc, AV_LOG_WARNING, "not writing 'chan' tag due to "
431 "lack of channel information\n");
435 avio_wb32(pb, 0); // Size
436 ffio_wfourcc(pb, "chan"); // Type
437 avio_w8(pb, 0); // Version
438 avio_wb24(pb, 0); // Flags
439 avio_wb32(pb, layout_tag); // mChannelLayoutTag
440 avio_wb32(pb, bitmap); // mChannelBitmap
441 avio_wb32(pb, 0); // mNumberChannelDescriptions
443 return update_size(pb, pos);
446 static int mov_write_wave_tag(AVIOContext *pb, MOVTrack *track)
448 int64_t pos = avio_tell(pb);
450 avio_wb32(pb, 0); /* size */
451 ffio_wfourcc(pb, "wave");
453 if (track->enc->codec_id != AV_CODEC_ID_QDM2) {
454 avio_wb32(pb, 12); /* size */
455 ffio_wfourcc(pb, "frma");
456 avio_wl32(pb, track->tag);
459 if (track->enc->codec_id == AV_CODEC_ID_AAC) {
460 /* useless atom needed by mplayer, ipod, not needed by quicktime */
461 avio_wb32(pb, 12); /* size */
462 ffio_wfourcc(pb, "mp4a");
464 mov_write_esds_tag(pb, track);
465 } else if (mov_pcm_le_gt16(track->enc->codec_id)) {
466 mov_write_enda_tag(pb);
467 } else if (mov_pcm_be_gt16(track->enc->codec_id)) {
468 mov_write_enda_tag_be(pb);
469 } else if (track->enc->codec_id == AV_CODEC_ID_AMR_NB) {
470 mov_write_amr_tag(pb, track);
471 } else if (track->enc->codec_id == AV_CODEC_ID_AC3) {
472 mov_write_ac3_tag(pb, track);
473 } else if (track->enc->codec_id == AV_CODEC_ID_ALAC ||
474 track->enc->codec_id == AV_CODEC_ID_QDM2) {
475 mov_write_extradata_tag(pb, track);
476 } else if (track->enc->codec_id == AV_CODEC_ID_ADPCM_MS ||
477 track->enc->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) {
478 mov_write_ms_tag(pb, track);
481 avio_wb32(pb, 8); /* size */
482 avio_wb32(pb, 0); /* null tag */
484 return update_size(pb, pos);
487 static int mov_write_dvc1_structs(MOVTrack *track, uint8_t *buf)
490 const uint8_t *start, *next, *end = track->vos_data + track->vos_len;
491 int unescaped_size, seq_found = 0;
492 int level = 0, interlace = 0;
493 int packet_seq = track->vc1_info.packet_seq;
494 int packet_entry = track->vc1_info.packet_entry;
495 int slices = track->vc1_info.slices;
498 if (track->start_dts == AV_NOPTS_VALUE) {
499 /* No packets written yet, vc1_info isn't authoritative yet. */
500 /* Assume inline sequence and entry headers. This will be
501 * overwritten at the end if the file is seekable. */
502 packet_seq = packet_entry = 1;
505 unescaped = av_mallocz(track->vos_len + FF_INPUT_BUFFER_PADDING_SIZE);
507 return AVERROR(ENOMEM);
508 start = find_next_marker(track->vos_data, end);
509 for (next = start; next < end; start = next) {
512 next = find_next_marker(start + 4, end);
513 size = next - start - 4;
516 unescaped_size = vc1_unescape_buffer(start + 4, size, unescaped);
517 init_get_bits(&gb, unescaped, 8 * unescaped_size);
518 if (AV_RB32(start) == VC1_CODE_SEQHDR) {
519 int profile = get_bits(&gb, 2);
520 if (profile != PROFILE_ADVANCED) {
522 return AVERROR(ENOSYS);
525 level = get_bits(&gb, 3);
526 /* chromaformat, frmrtq_postproc, bitrtq_postproc, postprocflag,
528 skip_bits_long(&gb, 2 + 3 + 5 + 1 + 2*12);
529 skip_bits(&gb, 1); /* broadcast */
530 interlace = get_bits1(&gb);
531 skip_bits(&gb, 4); /* tfcntrflag, finterpflag, reserved, psf */
536 return AVERROR(ENOSYS);
539 init_put_bits(&pbc, buf, 7);
540 /* VC1DecSpecStruc */
541 put_bits(&pbc, 4, 12); /* profile - advanced */
542 put_bits(&pbc, 3, level);
543 put_bits(&pbc, 1, 0); /* reserved */
544 /* VC1AdvDecSpecStruc */
545 put_bits(&pbc, 3, level);
546 put_bits(&pbc, 1, 0); /* cbr */
547 put_bits(&pbc, 6, 0); /* reserved */
548 put_bits(&pbc, 1, !interlace); /* no interlace */
549 put_bits(&pbc, 1, !packet_seq); /* no multiple seq */
550 put_bits(&pbc, 1, !packet_entry); /* no multiple entry */
551 put_bits(&pbc, 1, !slices); /* no slice code */
552 put_bits(&pbc, 1, 0); /* no bframe */
553 put_bits(&pbc, 1, 0); /* reserved */
556 if (track->st->avg_frame_rate.num > 0 && track->st->avg_frame_rate.den > 0)
557 put_bits32(&pbc, track->st->avg_frame_rate.num / track->st->avg_frame_rate.den);
559 put_bits32(&pbc, 0xffffffff);
561 flush_put_bits(&pbc);
568 static int mov_write_dvc1_tag(AVIOContext *pb, MOVTrack *track)
570 uint8_t buf[7] = { 0 };
573 if ((ret = mov_write_dvc1_structs(track, buf)) < 0)
576 avio_wb32(pb, track->vos_len + 8 + sizeof(buf));
577 ffio_wfourcc(pb, "dvc1");
578 track->vc1_info.struct_offset = avio_tell(pb);
579 avio_write(pb, buf, sizeof(buf));
580 avio_write(pb, track->vos_data, track->vos_len);
585 static int mov_write_glbl_tag(AVIOContext *pb, MOVTrack *track)
587 avio_wb32(pb, track->vos_len + 8);
588 ffio_wfourcc(pb, "glbl");
589 avio_write(pb, track->vos_data, track->vos_len);
590 return 8 + track->vos_len;
594 * Compute flags for 'lpcm' tag.
595 * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
597 static int mov_get_lpcm_flags(enum AVCodecID codec_id)
600 case AV_CODEC_ID_PCM_F32BE:
601 case AV_CODEC_ID_PCM_F64BE:
603 case AV_CODEC_ID_PCM_F32LE:
604 case AV_CODEC_ID_PCM_F64LE:
606 case AV_CODEC_ID_PCM_U8:
608 case AV_CODEC_ID_PCM_S16BE:
609 case AV_CODEC_ID_PCM_S24BE:
610 case AV_CODEC_ID_PCM_S32BE:
612 case AV_CODEC_ID_PCM_S8:
613 case AV_CODEC_ID_PCM_S16LE:
614 case AV_CODEC_ID_PCM_S24LE:
615 case AV_CODEC_ID_PCM_S32LE:
622 static int get_cluster_duration(MOVTrack *track, int cluster_idx)
626 if (cluster_idx >= track->entry)
629 if (cluster_idx + 1 == track->entry)
630 next_dts = track->track_duration + track->start_dts;
632 next_dts = track->cluster[cluster_idx + 1].dts;
634 next_dts -= track->cluster[cluster_idx].dts;
636 av_assert0(next_dts >= 0);
637 av_assert0(next_dts <= INT_MAX);
642 static int get_samples_per_packet(MOVTrack *track)
644 int i, first_duration;
646 // return track->enc->frame_size;
648 /* use 1 for raw PCM */
649 if (!track->audio_vbr)
652 /* check to see if duration is constant for all clusters */
655 first_duration = get_cluster_duration(track, 0);
656 for (i = 1; i < track->entry; i++) {
657 if (get_cluster_duration(track, i) != first_duration)
660 return first_duration;
663 static int mov_write_audio_tag(AVIOContext *pb, MOVTrack *track)
665 int64_t pos = avio_tell(pb);
667 uint32_t tag = track->tag;
669 if (track->mode == MODE_MOV) {
670 if (track->timescale > UINT16_MAX) {
671 if (mov_get_lpcm_flags(track->enc->codec_id))
672 tag = AV_RL32("lpcm");
674 } else if (track->audio_vbr || mov_pcm_le_gt16(track->enc->codec_id) ||
675 mov_pcm_be_gt16(track->enc->codec_id) ||
676 track->enc->codec_id == AV_CODEC_ID_ADPCM_MS ||
677 track->enc->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
678 track->enc->codec_id == AV_CODEC_ID_QDM2) {
683 avio_wb32(pb, 0); /* size */
684 avio_wl32(pb, tag); // store it byteswapped
685 avio_wb32(pb, 0); /* Reserved */
686 avio_wb16(pb, 0); /* Reserved */
687 avio_wb16(pb, 1); /* Data-reference index, XXX == 1 */
689 /* SoundDescription */
690 avio_wb16(pb, version); /* Version */
691 avio_wb16(pb, 0); /* Revision level */
692 avio_wb32(pb, 0); /* Reserved */
697 avio_wb16(pb, 0xfffe);
699 avio_wb32(pb, 0x00010000);
701 avio_wb64(pb, av_double2int(track->enc->sample_rate));
702 avio_wb32(pb, track->enc->channels);
703 avio_wb32(pb, 0x7F000000);
704 avio_wb32(pb, av_get_bits_per_sample(track->enc->codec_id));
705 avio_wb32(pb, mov_get_lpcm_flags(track->enc->codec_id));
706 avio_wb32(pb, track->sample_size);
707 avio_wb32(pb, get_samples_per_packet(track));
709 if (track->mode == MODE_MOV) {
710 avio_wb16(pb, track->enc->channels);
711 if (track->enc->codec_id == AV_CODEC_ID_PCM_U8 ||
712 track->enc->codec_id == AV_CODEC_ID_PCM_S8)
713 avio_wb16(pb, 8); /* bits per sample */
716 avio_wb16(pb, track->audio_vbr ? -2 : 0); /* compression ID */
717 } else { /* reserved for mp4/3gp */
723 avio_wb16(pb, 0); /* packet size (= 0) */
724 avio_wb16(pb, track->enc->sample_rate <= UINT16_MAX ?
725 track->enc->sample_rate : 0);
726 avio_wb16(pb, 0); /* Reserved */
729 if (version == 1) { /* SoundDescription V1 extended info */
730 if (mov_pcm_le_gt16(track->enc->codec_id) ||
731 mov_pcm_be_gt16(track->enc->codec_id))
732 avio_wb32(pb, 1); /* must be 1 for uncompressed formats */
734 avio_wb32(pb, track->enc->frame_size); /* Samples per packet */
735 avio_wb32(pb, track->sample_size / track->enc->channels); /* Bytes per packet */
736 avio_wb32(pb, track->sample_size); /* Bytes per frame */
737 avio_wb32(pb, 2); /* Bytes per sample */
740 if (track->mode == MODE_MOV &&
741 (track->enc->codec_id == AV_CODEC_ID_AAC ||
742 track->enc->codec_id == AV_CODEC_ID_AC3 ||
743 track->enc->codec_id == AV_CODEC_ID_AMR_NB ||
744 track->enc->codec_id == AV_CODEC_ID_ALAC ||
745 track->enc->codec_id == AV_CODEC_ID_ADPCM_MS ||
746 track->enc->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
747 track->enc->codec_id == AV_CODEC_ID_QDM2 ||
748 (mov_pcm_le_gt16(track->enc->codec_id) && version==1) ||
749 (mov_pcm_be_gt16(track->enc->codec_id) && version==1)))
750 mov_write_wave_tag(pb, track);
751 else if (track->tag == MKTAG('m','p','4','a'))
752 mov_write_esds_tag(pb, track);
753 else if (track->enc->codec_id == AV_CODEC_ID_AMR_NB)
754 mov_write_amr_tag(pb, track);
755 else if (track->enc->codec_id == AV_CODEC_ID_AC3)
756 mov_write_ac3_tag(pb, track);
757 else if (track->enc->codec_id == AV_CODEC_ID_ALAC)
758 mov_write_extradata_tag(pb, track);
759 else if (track->enc->codec_id == AV_CODEC_ID_WMAPRO)
760 mov_write_wfex_tag(pb, track);
761 else if (track->vos_len > 0)
762 mov_write_glbl_tag(pb, track);
764 if (track->mode == MODE_MOV && track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
765 mov_write_chan_tag(pb, track);
767 return update_size(pb, pos);
770 static int mov_write_d263_tag(AVIOContext *pb)
772 avio_wb32(pb, 0xf); /* size */
773 ffio_wfourcc(pb, "d263");
774 ffio_wfourcc(pb, "FFMP");
775 avio_w8(pb, 0); /* decoder version */
776 /* FIXME use AVCodecContext level/profile, when encoder will set values */
777 avio_w8(pb, 0xa); /* level */
778 avio_w8(pb, 0); /* profile */
782 static int mov_write_avcc_tag(AVIOContext *pb, MOVTrack *track)
784 int64_t pos = avio_tell(pb);
787 ffio_wfourcc(pb, "avcC");
788 ff_isom_write_avcc(pb, track->vos_data, track->vos_len);
789 return update_size(pb, pos);
792 static int mov_write_hvcc_tag(AVIOContext *pb, MOVTrack *track)
794 int64_t pos = avio_tell(pb);
797 ffio_wfourcc(pb, "hvcC");
798 ff_isom_write_hvcc(pb, track->vos_data, track->vos_len, 0);
799 return update_size(pb, pos);
802 /* also used by all avid codecs (dv, imx, meridien) and their variants */
803 static int mov_write_avid_tag(AVIOContext *pb, MOVTrack *track)
806 avio_wb32(pb, 24); /* size */
807 ffio_wfourcc(pb, "ACLR");
808 ffio_wfourcc(pb, "ACLR");
809 ffio_wfourcc(pb, "0001");
810 if (track->enc->color_range == AVCOL_RANGE_MPEG) { /* Legal range (16-235) */
811 avio_wb32(pb, 1); /* Corresponds to 709 in official encoder */
812 } else { /* Full range (0-255) */
813 avio_wb32(pb, 2); /* Corresponds to RGB in official encoder */
815 avio_wb32(pb, 0); /* unknown */
817 avio_wb32(pb, 24); /* size */
818 ffio_wfourcc(pb, "APRG");
819 ffio_wfourcc(pb, "APRG");
820 ffio_wfourcc(pb, "0001");
821 avio_wb32(pb, 1); /* unknown */
822 avio_wb32(pb, 0); /* unknown */
824 avio_wb32(pb, 120); /* size */
825 ffio_wfourcc(pb, "ARES");
826 ffio_wfourcc(pb, "ARES");
827 ffio_wfourcc(pb, "0001");
828 avio_wb32(pb, AV_RB32(track->vos_data + 0x28)); /* dnxhd cid, some id ? */
829 avio_wb32(pb, track->enc->width);
830 /* values below are based on samples created with quicktime and avid codecs */
831 if (track->vos_data[5] & 2) { // interlaced
832 avio_wb32(pb, track->enc->height / 2);
833 avio_wb32(pb, 2); /* unknown */
834 avio_wb32(pb, 0); /* unknown */
835 avio_wb32(pb, 4); /* unknown */
837 avio_wb32(pb, track->enc->height);
838 avio_wb32(pb, 1); /* unknown */
839 avio_wb32(pb, 0); /* unknown */
840 if (track->enc->height == 1080)
841 avio_wb32(pb, 5); /* unknown */
843 avio_wb32(pb, 6); /* unknown */
846 for (i = 0; i < 10; i++)
849 /* extra padding for stsd needed */
854 static int mp4_get_codec_tag(AVFormatContext *s, MOVTrack *track)
856 int tag = track->enc->codec_tag;
858 if (!ff_codec_get_tag(ff_mp4_obj_type, track->enc->codec_id))
861 if (track->enc->codec_id == AV_CODEC_ID_H264) tag = MKTAG('a','v','c','1');
862 else if (track->enc->codec_id == AV_CODEC_ID_HEVC) tag = MKTAG('h','e','v','1');
863 else if (track->enc->codec_id == AV_CODEC_ID_AC3) tag = MKTAG('a','c','-','3');
864 else if (track->enc->codec_id == AV_CODEC_ID_DIRAC) tag = MKTAG('d','r','a','c');
865 else if (track->enc->codec_id == AV_CODEC_ID_MOV_TEXT) tag = MKTAG('t','x','3','g');
866 else if (track->enc->codec_id == AV_CODEC_ID_VC1) tag = MKTAG('v','c','-','1');
867 else if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) tag = MKTAG('m','p','4','v');
868 else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO) tag = MKTAG('m','p','4','a');
869 else if (track->enc->codec_id == AV_CODEC_ID_DVD_SUBTITLE) tag = MKTAG('m','p','4','s');
874 static const AVCodecTag codec_ipod_tags[] = {
875 { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
876 { AV_CODEC_ID_MPEG4, MKTAG('m','p','4','v') },
877 { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
878 { AV_CODEC_ID_ALAC, MKTAG('a','l','a','c') },
879 { AV_CODEC_ID_AC3, MKTAG('a','c','-','3') },
880 { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
881 { AV_CODEC_ID_MOV_TEXT, MKTAG('t','e','x','t') },
882 { AV_CODEC_ID_NONE, 0 },
885 static int ipod_get_codec_tag(AVFormatContext *s, MOVTrack *track)
887 int tag = track->enc->codec_tag;
889 // keep original tag for subs, ipod supports both formats
890 if (!(track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE &&
891 (tag == MKTAG('t', 'x', '3', 'g') ||
892 tag == MKTAG('t', 'e', 'x', 't'))))
893 tag = ff_codec_get_tag(codec_ipod_tags, track->enc->codec_id);
895 if (!av_match_ext(s->filename, "m4a") && !av_match_ext(s->filename, "m4v"))
896 av_log(s, AV_LOG_WARNING, "Warning, extension is not .m4a nor .m4v "
897 "Quicktime/Ipod might not play the file\n");
902 static int mov_get_dv_codec_tag(AVFormatContext *s, MOVTrack *track)
906 if (track->enc->width == 720) { /* SD */
907 if (track->enc->height == 480) { /* NTSC */
908 if (track->enc->pix_fmt == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','n');
909 else tag = MKTAG('d','v','c',' ');
910 }else if (track->enc->pix_fmt == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','p');
911 else if (track->enc->pix_fmt == AV_PIX_FMT_YUV420P) tag = MKTAG('d','v','c','p');
912 else tag = MKTAG('d','v','p','p');
913 } else if (track->enc->height == 720) { /* HD 720 line */
914 if (track->st->time_base.den == 50) tag = MKTAG('d','v','h','q');
915 else tag = MKTAG('d','v','h','p');
916 } else if (track->enc->height == 1080) { /* HD 1080 line */
917 if (track->st->time_base.den == 25) tag = MKTAG('d','v','h','5');
918 else tag = MKTAG('d','v','h','6');
920 av_log(s, AV_LOG_ERROR, "unsupported height for dv codec\n");
927 static AVRational find_fps(AVFormatContext *s, AVStream *st)
929 AVRational rate = {st->codec->time_base.den, st->codec->time_base.num};
930 /* if the codec time base makes no sense, try to fallback on stream frame rate */
931 if (av_timecode_check_frame_rate(rate) < 0) {
932 av_log(s, AV_LOG_DEBUG, "timecode: tbc=%d/%d invalid, fallback on %d/%d\n",
933 rate.num, rate.den, st->avg_frame_rate.num, st->avg_frame_rate.den);
934 rate = st->avg_frame_rate;
940 static int mov_get_mpeg2_xdcam_codec_tag(AVFormatContext *s, MOVTrack *track)
942 int tag = track->enc->codec_tag;
943 int interlaced = track->enc->field_order > AV_FIELD_PROGRESSIVE;
944 AVStream *st = track->st;
945 int rate = av_q2d(find_fps(s, st));
948 tag = MKTAG('m', '2', 'v', '1'); //fallback tag
950 if (track->enc->pix_fmt == AV_PIX_FMT_YUV420P) {
951 if (track->enc->width == 1280 && track->enc->height == 720) {
953 if (rate == 24) tag = MKTAG('x','d','v','4');
954 else if (rate == 25) tag = MKTAG('x','d','v','5');
955 else if (rate == 30) tag = MKTAG('x','d','v','1');
956 else if (rate == 50) tag = MKTAG('x','d','v','a');
957 else if (rate == 60) tag = MKTAG('x','d','v','9');
959 } else if (track->enc->width == 1440 && track->enc->height == 1080) {
961 if (rate == 24) tag = MKTAG('x','d','v','6');
962 else if (rate == 25) tag = MKTAG('x','d','v','7');
963 else if (rate == 30) tag = MKTAG('x','d','v','8');
965 if (rate == 25) tag = MKTAG('x','d','v','3');
966 else if (rate == 30) tag = MKTAG('x','d','v','2');
968 } else if (track->enc->width == 1920 && track->enc->height == 1080) {
970 if (rate == 24) tag = MKTAG('x','d','v','d');
971 else if (rate == 25) tag = MKTAG('x','d','v','e');
972 else if (rate == 30) tag = MKTAG('x','d','v','f');
974 if (rate == 25) tag = MKTAG('x','d','v','c');
975 else if (rate == 30) tag = MKTAG('x','d','v','b');
978 } else if (track->enc->pix_fmt == AV_PIX_FMT_YUV422P) {
979 if (track->enc->width == 1280 && track->enc->height == 720) {
981 if (rate == 24) tag = MKTAG('x','d','5','4');
982 else if (rate == 25) tag = MKTAG('x','d','5','5');
983 else if (rate == 30) tag = MKTAG('x','d','5','1');
984 else if (rate == 50) tag = MKTAG('x','d','5','a');
985 else if (rate == 60) tag = MKTAG('x','d','5','9');
987 } else if (track->enc->width == 1920 && track->enc->height == 1080) {
989 if (rate == 24) tag = MKTAG('x','d','5','d');
990 else if (rate == 25) tag = MKTAG('x','d','5','e');
991 else if (rate == 30) tag = MKTAG('x','d','5','f');
993 if (rate == 25) tag = MKTAG('x','d','5','c');
994 else if (rate == 30) tag = MKTAG('x','d','5','b');
1002 static const struct {
1003 enum AVPixelFormat pix_fmt;
1006 } mov_pix_fmt_tags[] = {
1007 { AV_PIX_FMT_YUYV422, MKTAG('y','u','v','2'), 0 },
1008 { AV_PIX_FMT_YUYV422, MKTAG('y','u','v','s'), 0 },
1009 { AV_PIX_FMT_UYVY422, MKTAG('2','v','u','y'), 0 },
1010 { AV_PIX_FMT_RGB555BE,MKTAG('r','a','w',' '), 16 },
1011 { AV_PIX_FMT_RGB555LE,MKTAG('L','5','5','5'), 16 },
1012 { AV_PIX_FMT_RGB565LE,MKTAG('L','5','6','5'), 16 },
1013 { AV_PIX_FMT_RGB565BE,MKTAG('B','5','6','5'), 16 },
1014 { AV_PIX_FMT_GRAY16BE,MKTAG('b','1','6','g'), 16 },
1015 { AV_PIX_FMT_RGB24, MKTAG('r','a','w',' '), 24 },
1016 { AV_PIX_FMT_BGR24, MKTAG('2','4','B','G'), 24 },
1017 { AV_PIX_FMT_ARGB, MKTAG('r','a','w',' '), 32 },
1018 { AV_PIX_FMT_BGRA, MKTAG('B','G','R','A'), 32 },
1019 { AV_PIX_FMT_RGBA, MKTAG('R','G','B','A'), 32 },
1020 { AV_PIX_FMT_ABGR, MKTAG('A','B','G','R'), 32 },
1021 { AV_PIX_FMT_RGB48BE, MKTAG('b','4','8','r'), 48 },
1024 static int mov_get_rawvideo_codec_tag(AVFormatContext *s, MOVTrack *track)
1026 int tag = track->enc->codec_tag;
1028 enum AVPixelFormat pix_fmt;
1030 for (i = 0; i < FF_ARRAY_ELEMS(mov_pix_fmt_tags); i++) {
1031 if (track->enc->pix_fmt == mov_pix_fmt_tags[i].pix_fmt) {
1032 tag = mov_pix_fmt_tags[i].tag;
1033 track->enc->bits_per_coded_sample = mov_pix_fmt_tags[i].bps;
1034 if (track->enc->codec_tag == mov_pix_fmt_tags[i].tag)
1039 pix_fmt = avpriv_find_pix_fmt(avpriv_pix_fmt_bps_mov,
1040 track->enc->bits_per_coded_sample);
1041 if (tag == MKTAG('r','a','w',' ') &&
1042 track->enc->pix_fmt != pix_fmt &&
1043 track->enc->pix_fmt != AV_PIX_FMT_NONE)
1044 av_log(s, AV_LOG_ERROR, "%s rawvideo cannot be written to mov, output file will be unreadable\n",
1045 av_get_pix_fmt_name(track->enc->pix_fmt));
1049 static int mov_get_codec_tag(AVFormatContext *s, MOVTrack *track)
1051 int tag = track->enc->codec_tag;
1053 if (!tag || (track->enc->strict_std_compliance >= FF_COMPLIANCE_NORMAL &&
1054 (track->enc->codec_id == AV_CODEC_ID_DVVIDEO ||
1055 track->enc->codec_id == AV_CODEC_ID_RAWVIDEO ||
1056 track->enc->codec_id == AV_CODEC_ID_H263 ||
1057 track->enc->codec_id == AV_CODEC_ID_MPEG2VIDEO ||
1058 av_get_bits_per_sample(track->enc->codec_id)))) { // pcm audio
1059 if (track->enc->codec_id == AV_CODEC_ID_DVVIDEO)
1060 tag = mov_get_dv_codec_tag(s, track);
1061 else if (track->enc->codec_id == AV_CODEC_ID_RAWVIDEO)
1062 tag = mov_get_rawvideo_codec_tag(s, track);
1063 else if (track->enc->codec_id == AV_CODEC_ID_MPEG2VIDEO)
1064 tag = mov_get_mpeg2_xdcam_codec_tag(s, track);
1065 else if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1066 tag = ff_codec_get_tag(ff_codec_movvideo_tags, track->enc->codec_id);
1067 if (!tag) { // if no mac fcc found, try with Microsoft tags
1068 tag = ff_codec_get_tag(ff_codec_bmp_tags, track->enc->codec_id);
1070 av_log(s, AV_LOG_WARNING, "Using MS style video codec tag, "
1071 "the file may be unplayable!\n");
1073 } else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO) {
1074 tag = ff_codec_get_tag(ff_codec_movaudio_tags, track->enc->codec_id);
1075 if (!tag) { // if no mac fcc found, try with Microsoft tags
1076 int ms_tag = ff_codec_get_tag(ff_codec_wav_tags, track->enc->codec_id);
1078 tag = MKTAG('m', 's', ((ms_tag >> 8) & 0xff), (ms_tag & 0xff));
1079 av_log(s, AV_LOG_WARNING, "Using MS style audio codec tag, "
1080 "the file may be unplayable!\n");
1083 } else if (track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE)
1084 tag = ff_codec_get_tag(ff_codec_movsubtitle_tags, track->enc->codec_id);
1090 static const AVCodecTag codec_3gp_tags[] = {
1091 { AV_CODEC_ID_H263, MKTAG('s','2','6','3') },
1092 { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
1093 { AV_CODEC_ID_MPEG4, MKTAG('m','p','4','v') },
1094 { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
1095 { AV_CODEC_ID_AMR_NB, MKTAG('s','a','m','r') },
1096 { AV_CODEC_ID_AMR_WB, MKTAG('s','a','w','b') },
1097 { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
1098 { AV_CODEC_ID_NONE, 0 },
1101 static const AVCodecTag codec_f4v_tags[] = { // XXX: add GIF/PNG/JPEG?
1102 { AV_CODEC_ID_MP3, MKTAG('.','m','p','3') },
1103 { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
1104 { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
1105 { AV_CODEC_ID_VP6A, MKTAG('V','P','6','A') },
1106 { AV_CODEC_ID_VP6F, MKTAG('V','P','6','F') },
1107 { AV_CODEC_ID_NONE, 0 },
1110 static int mov_find_codec_tag(AVFormatContext *s, MOVTrack *track)
1114 if (track->mode == MODE_MP4 || track->mode == MODE_PSP)
1115 tag = mp4_get_codec_tag(s, track);
1116 else if (track->mode == MODE_ISM) {
1117 tag = mp4_get_codec_tag(s, track);
1118 if (!tag && track->enc->codec_id == AV_CODEC_ID_WMAPRO)
1119 tag = MKTAG('w', 'm', 'a', ' ');
1120 } else if (track->mode == MODE_IPOD)
1121 tag = ipod_get_codec_tag(s, track);
1122 else if (track->mode & MODE_3GP)
1123 tag = ff_codec_get_tag(codec_3gp_tags, track->enc->codec_id);
1124 else if (track->mode == MODE_F4V)
1125 tag = ff_codec_get_tag(codec_f4v_tags, track->enc->codec_id);
1127 tag = mov_get_codec_tag(s, track);
1132 /** Write uuid atom.
1133 * Needed to make file play in iPods running newest firmware
1134 * goes after avcC atom in moov.trak.mdia.minf.stbl.stsd.avc1
1136 static int mov_write_uuid_tag_ipod(AVIOContext *pb)
1139 ffio_wfourcc(pb, "uuid");
1140 avio_wb32(pb, 0x6b6840f2);
1141 avio_wb32(pb, 0x5f244fc5);
1142 avio_wb32(pb, 0xba39a51b);
1143 avio_wb32(pb, 0xcf0323f3);
1148 static const uint16_t fiel_data[] = {
1149 0x0000, 0x0100, 0x0201, 0x0206, 0x0209, 0x020e
1152 static int mov_write_fiel_tag(AVIOContext *pb, MOVTrack *track)
1154 unsigned mov_field_order = 0;
1155 if (track->enc->field_order < FF_ARRAY_ELEMS(fiel_data))
1156 mov_field_order = fiel_data[track->enc->field_order];
1160 ffio_wfourcc(pb, "fiel");
1161 avio_wb16(pb, mov_field_order);
1165 static int mov_write_subtitle_tag(AVIOContext *pb, MOVTrack *track)
1167 int64_t pos = avio_tell(pb);
1168 avio_wb32(pb, 0); /* size */
1169 avio_wl32(pb, track->tag); // store it byteswapped
1170 avio_wb32(pb, 0); /* Reserved */
1171 avio_wb16(pb, 0); /* Reserved */
1172 avio_wb16(pb, 1); /* Data-reference index */
1174 if (track->enc->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
1175 mov_write_esds_tag(pb, track);
1176 else if (track->enc->extradata_size)
1177 avio_write(pb, track->enc->extradata, track->enc->extradata_size);
1179 return update_size(pb, pos);
1182 static int mov_write_pasp_tag(AVIOContext *pb, MOVTrack *track)
1185 av_reduce(&sar.num, &sar.den, track->enc->sample_aspect_ratio.num,
1186 track->enc->sample_aspect_ratio.den, INT_MAX);
1189 ffio_wfourcc(pb, "pasp");
1190 avio_wb32(pb, sar.num);
1191 avio_wb32(pb, sar.den);
1195 static void find_compressor(char * compressor_name, int len, MOVTrack *track)
1197 AVDictionaryEntry *encoder;
1198 int xdcam_res = (track->enc->width == 1280 && track->enc->height == 720)
1199 || (track->enc->width == 1440 && track->enc->height == 1080)
1200 || (track->enc->width == 1920 && track->enc->height == 1080);
1202 if (track->mode == MODE_MOV &&
1203 (encoder = av_dict_get(track->st->metadata, "encoder", NULL, 0))) {
1204 av_strlcpy(compressor_name, encoder->value, 32);
1205 } else if (track->enc->codec_id == AV_CODEC_ID_MPEG2VIDEO && xdcam_res) {
1206 int interlaced = track->enc->field_order > AV_FIELD_PROGRESSIVE;
1207 AVStream *st = track->st;
1208 int rate = av_q2d(find_fps(NULL, st));
1209 av_strlcatf(compressor_name, len, "XDCAM");
1210 if (track->enc->pix_fmt == AV_PIX_FMT_YUV422P) {
1211 av_strlcatf(compressor_name, len, " HD422");
1212 } else if(track->enc->width == 1440) {
1213 av_strlcatf(compressor_name, len, " HD");
1215 av_strlcatf(compressor_name, len, " EX");
1217 av_strlcatf(compressor_name, len, " %d%c", track->enc->height, interlaced ? 'i' : 'p');
1219 av_strlcatf(compressor_name, len, "%d", rate * (interlaced + 1));
1223 static int mov_write_video_tag(AVIOContext *pb, MOVTrack *track)
1225 int64_t pos = avio_tell(pb);
1226 char compressor_name[32] = { 0 };
1228 avio_wb32(pb, 0); /* size */
1229 avio_wl32(pb, track->tag); // store it byteswapped
1230 avio_wb32(pb, 0); /* Reserved */
1231 avio_wb16(pb, 0); /* Reserved */
1232 avio_wb16(pb, 1); /* Data-reference index */
1234 avio_wb16(pb, 0); /* Codec stream version */
1235 avio_wb16(pb, 0); /* Codec stream revision (=0) */
1236 if (track->mode == MODE_MOV) {
1237 ffio_wfourcc(pb, "FFMP"); /* Vendor */
1238 if (track->enc->codec_id == AV_CODEC_ID_RAWVIDEO) {
1239 avio_wb32(pb, 0); /* Temporal Quality */
1240 avio_wb32(pb, 0x400); /* Spatial Quality = lossless*/
1242 avio_wb32(pb, 0x200); /* Temporal Quality = normal */
1243 avio_wb32(pb, 0x200); /* Spatial Quality = normal */
1246 avio_wb32(pb, 0); /* Reserved */
1247 avio_wb32(pb, 0); /* Reserved */
1248 avio_wb32(pb, 0); /* Reserved */
1250 avio_wb16(pb, track->enc->width); /* Video width */
1251 avio_wb16(pb, track->height); /* Video height */
1252 avio_wb32(pb, 0x00480000); /* Horizontal resolution 72dpi */
1253 avio_wb32(pb, 0x00480000); /* Vertical resolution 72dpi */
1254 avio_wb32(pb, 0); /* Data size (= 0) */
1255 avio_wb16(pb, 1); /* Frame count (= 1) */
1257 /* FIXME not sure, ISO 14496-1 draft where it shall be set to 0 */
1258 find_compressor(compressor_name, 32, track);
1259 avio_w8(pb, strlen(compressor_name));
1260 avio_write(pb, compressor_name, 31);
1262 if (track->mode == MODE_MOV && track->enc->bits_per_coded_sample)
1263 avio_wb16(pb, track->enc->bits_per_coded_sample);
1265 avio_wb16(pb, 0x18); /* Reserved */
1266 avio_wb16(pb, 0xffff); /* Reserved */
1267 if (track->tag == MKTAG('m','p','4','v'))
1268 mov_write_esds_tag(pb, track);
1269 else if (track->enc->codec_id == AV_CODEC_ID_H263)
1270 mov_write_d263_tag(pb);
1271 else if (track->enc->codec_id == AV_CODEC_ID_AVUI ||
1272 track->enc->codec_id == AV_CODEC_ID_SVQ3) {
1273 mov_write_extradata_tag(pb, track);
1275 } else if (track->enc->codec_id == AV_CODEC_ID_DNXHD)
1276 mov_write_avid_tag(pb, track);
1277 else if (track->enc->codec_id == AV_CODEC_ID_HEVC)
1278 mov_write_hvcc_tag(pb, track);
1279 else if (track->enc->codec_id == AV_CODEC_ID_H264) {
1280 mov_write_avcc_tag(pb, track);
1281 if (track->mode == MODE_IPOD)
1282 mov_write_uuid_tag_ipod(pb);
1283 } else if (track->enc->codec_id == AV_CODEC_ID_VC1 && track->vos_len > 0)
1284 mov_write_dvc1_tag(pb, track);
1285 else if (track->enc->codec_id == AV_CODEC_ID_VP6F ||
1286 track->enc->codec_id == AV_CODEC_ID_VP6A) {
1287 /* Don't write any potential extradata here - the cropping
1288 * is signalled via the normal width/height fields. */
1289 } else if (track->vos_len > 0)
1290 mov_write_glbl_tag(pb, track);
1292 if (track->enc->codec_id != AV_CODEC_ID_H264 &&
1293 track->enc->codec_id != AV_CODEC_ID_MPEG4 &&
1294 track->enc->codec_id != AV_CODEC_ID_DNXHD)
1295 if (track->enc->field_order != AV_FIELD_UNKNOWN)
1296 mov_write_fiel_tag(pb, track);
1298 if (track->enc->sample_aspect_ratio.den && track->enc->sample_aspect_ratio.num &&
1299 track->enc->sample_aspect_ratio.den != track->enc->sample_aspect_ratio.num) {
1300 mov_write_pasp_tag(pb, track);
1303 return update_size(pb, pos);
1306 static int mov_write_rtp_tag(AVIOContext *pb, MOVTrack *track)
1308 int64_t pos = avio_tell(pb);
1309 avio_wb32(pb, 0); /* size */
1310 ffio_wfourcc(pb, "rtp ");
1311 avio_wb32(pb, 0); /* Reserved */
1312 avio_wb16(pb, 0); /* Reserved */
1313 avio_wb16(pb, 1); /* Data-reference index */
1315 avio_wb16(pb, 1); /* Hint track version */
1316 avio_wb16(pb, 1); /* Highest compatible version */
1317 avio_wb32(pb, track->max_packet_size); /* Max packet size */
1319 avio_wb32(pb, 12); /* size */
1320 ffio_wfourcc(pb, "tims");
1321 avio_wb32(pb, track->timescale);
1323 return update_size(pb, pos);
1326 static int mov_write_tmcd_tag(AVIOContext *pb, MOVTrack *track)
1328 int64_t pos = avio_tell(pb);
1330 int frame_duration = av_rescale(track->timescale, track->enc->time_base.num, track->enc->time_base.den);
1331 int nb_frames = 1.0/av_q2d(track->enc->time_base) + 0.5;
1333 if (nb_frames > 255) {
1334 av_log(NULL, AV_LOG_ERROR, "fps %d is too large\n", nb_frames);
1335 return AVERROR(EINVAL);
1338 avio_wb32(pb, 0); /* size */
1339 ffio_wfourcc(pb, "tmcd"); /* Data format */
1340 avio_wb32(pb, 0); /* Reserved */
1341 avio_wb32(pb, 1); /* Data reference index */
1342 avio_wb32(pb, 0); /* Flags */
1343 avio_wb32(pb, track->timecode_flags); /* Flags (timecode) */
1344 avio_wb32(pb, track->timescale); /* Timescale */
1345 avio_wb32(pb, frame_duration); /* Frame duration */
1346 avio_w8(pb, nb_frames); /* Number of frames */
1347 avio_wb24(pb, 0); /* Reserved */
1348 /* TODO: source reference string */
1351 avio_wb32(pb, 0); /* size */
1352 ffio_wfourcc(pb, "tmcd"); /* Data format */
1353 avio_wb32(pb, 0); /* Reserved */
1354 avio_wb32(pb, 1); /* Data reference index */
1355 if (track->enc->extradata_size)
1356 avio_write(pb, track->enc->extradata, track->enc->extradata_size);
1358 return update_size(pb, pos);
1361 static int mov_write_stsd_tag(AVIOContext *pb, MOVTrack *track)
1363 int64_t pos = avio_tell(pb);
1364 avio_wb32(pb, 0); /* size */
1365 ffio_wfourcc(pb, "stsd");
1366 avio_wb32(pb, 0); /* version & flags */
1367 avio_wb32(pb, 1); /* entry count */
1368 if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO)
1369 mov_write_video_tag(pb, track);
1370 else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
1371 mov_write_audio_tag(pb, track);
1372 else if (track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE)
1373 mov_write_subtitle_tag(pb, track);
1374 else if (track->enc->codec_tag == MKTAG('r','t','p',' '))
1375 mov_write_rtp_tag(pb, track);
1376 else if (track->enc->codec_tag == MKTAG('t','m','c','d'))
1377 mov_write_tmcd_tag(pb, track);
1378 return update_size(pb, pos);
1381 static int mov_write_ctts_tag(AVIOContext *pb, MOVTrack *track)
1383 MOVStts *ctts_entries;
1384 uint32_t entries = 0;
1388 ctts_entries = av_malloc_array((track->entry + 1), sizeof(*ctts_entries)); /* worst case */
1389 ctts_entries[0].count = 1;
1390 ctts_entries[0].duration = track->cluster[0].cts;
1391 for (i = 1; i < track->entry; i++) {
1392 if (track->cluster[i].cts == ctts_entries[entries].duration) {
1393 ctts_entries[entries].count++; /* compress */
1396 ctts_entries[entries].duration = track->cluster[i].cts;
1397 ctts_entries[entries].count = 1;
1400 entries++; /* last one */
1401 atom_size = 16 + (entries * 8);
1402 avio_wb32(pb, atom_size); /* size */
1403 ffio_wfourcc(pb, "ctts");
1404 avio_wb32(pb, 0); /* version & flags */
1405 avio_wb32(pb, entries); /* entry count */
1406 for (i = 0; i < entries; i++) {
1407 avio_wb32(pb, ctts_entries[i].count);
1408 avio_wb32(pb, ctts_entries[i].duration);
1410 av_free(ctts_entries);
1414 /* Time to sample atom */
1415 static int mov_write_stts_tag(AVIOContext *pb, MOVTrack *track)
1417 MOVStts *stts_entries;
1418 uint32_t entries = -1;
1422 if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO && !track->audio_vbr) {
1423 stts_entries = av_malloc(sizeof(*stts_entries)); /* one entry */
1424 stts_entries[0].count = track->sample_count;
1425 stts_entries[0].duration = 1;
1428 stts_entries = track->entry ?
1429 av_malloc_array(track->entry, sizeof(*stts_entries)) : /* worst case */
1431 for (i = 0; i < track->entry; i++) {
1432 int duration = get_cluster_duration(track, i);
1433 if (i && duration == stts_entries[entries].duration) {
1434 stts_entries[entries].count++; /* compress */
1437 stts_entries[entries].duration = duration;
1438 stts_entries[entries].count = 1;
1441 entries++; /* last one */
1443 atom_size = 16 + (entries * 8);
1444 avio_wb32(pb, atom_size); /* size */
1445 ffio_wfourcc(pb, "stts");
1446 avio_wb32(pb, 0); /* version & flags */
1447 avio_wb32(pb, entries); /* entry count */
1448 for (i = 0; i < entries; i++) {
1449 avio_wb32(pb, stts_entries[i].count);
1450 avio_wb32(pb, stts_entries[i].duration);
1452 av_free(stts_entries);
1456 static int mov_write_dref_tag(AVIOContext *pb)
1458 avio_wb32(pb, 28); /* size */
1459 ffio_wfourcc(pb, "dref");
1460 avio_wb32(pb, 0); /* version & flags */
1461 avio_wb32(pb, 1); /* entry count */
1463 avio_wb32(pb, 0xc); /* size */
1464 //FIXME add the alis and rsrc atom
1465 ffio_wfourcc(pb, "url ");
1466 avio_wb32(pb, 1); /* version & flags */
1471 static int mov_write_stbl_tag(AVIOContext *pb, MOVTrack *track)
1473 int64_t pos = avio_tell(pb);
1474 avio_wb32(pb, 0); /* size */
1475 ffio_wfourcc(pb, "stbl");
1476 mov_write_stsd_tag(pb, track);
1477 mov_write_stts_tag(pb, track);
1478 if ((track->enc->codec_type == AVMEDIA_TYPE_VIDEO ||
1479 track->enc->codec_tag == MKTAG('r','t','p',' ')) &&
1480 track->has_keyframes && track->has_keyframes < track->entry)
1481 mov_write_stss_tag(pb, track, MOV_SYNC_SAMPLE);
1482 if (track->mode == MODE_MOV && track->flags & MOV_TRACK_STPS)
1483 mov_write_stss_tag(pb, track, MOV_PARTIAL_SYNC_SAMPLE);
1484 if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO &&
1485 track->flags & MOV_TRACK_CTTS)
1486 mov_write_ctts_tag(pb, track);
1487 mov_write_stsc_tag(pb, track);
1488 mov_write_stsz_tag(pb, track);
1489 mov_write_stco_tag(pb, track);
1490 return update_size(pb, pos);
1493 static int mov_write_dinf_tag(AVIOContext *pb)
1495 int64_t pos = avio_tell(pb);
1496 avio_wb32(pb, 0); /* size */
1497 ffio_wfourcc(pb, "dinf");
1498 mov_write_dref_tag(pb);
1499 return update_size(pb, pos);
1502 static int mov_write_nmhd_tag(AVIOContext *pb)
1505 ffio_wfourcc(pb, "nmhd");
1510 static int mov_write_tcmi_tag(AVIOContext *pb, MOVTrack *track)
1512 int64_t pos = avio_tell(pb);
1513 const char *font = "Lucida Grande";
1514 avio_wb32(pb, 0); /* size */
1515 ffio_wfourcc(pb, "tcmi"); /* timecode media information atom */
1516 avio_wb32(pb, 0); /* version & flags */
1517 avio_wb16(pb, 0); /* text font */
1518 avio_wb16(pb, 0); /* text face */
1519 avio_wb16(pb, 12); /* text size */
1520 avio_wb16(pb, 0); /* (unknown, not in the QT specs...) */
1521 avio_wb16(pb, 0x0000); /* text color (red) */
1522 avio_wb16(pb, 0x0000); /* text color (green) */
1523 avio_wb16(pb, 0x0000); /* text color (blue) */
1524 avio_wb16(pb, 0xffff); /* background color (red) */
1525 avio_wb16(pb, 0xffff); /* background color (green) */
1526 avio_wb16(pb, 0xffff); /* background color (blue) */
1527 avio_w8(pb, strlen(font)); /* font len (part of the pascal string) */
1528 avio_write(pb, font, strlen(font)); /* font name */
1529 return update_size(pb, pos);
1532 static int mov_write_gmhd_tag(AVIOContext *pb, MOVTrack *track)
1534 int64_t pos = avio_tell(pb);
1535 avio_wb32(pb, 0); /* size */
1536 ffio_wfourcc(pb, "gmhd");
1537 avio_wb32(pb, 0x18); /* gmin size */
1538 ffio_wfourcc(pb, "gmin");/* generic media info */
1539 avio_wb32(pb, 0); /* version & flags */
1540 avio_wb16(pb, 0x40); /* graphics mode = */
1541 avio_wb16(pb, 0x8000); /* opColor (r?) */
1542 avio_wb16(pb, 0x8000); /* opColor (g?) */
1543 avio_wb16(pb, 0x8000); /* opColor (b?) */
1544 avio_wb16(pb, 0); /* balance */
1545 avio_wb16(pb, 0); /* reserved */
1548 * This special text atom is required for
1549 * Apple Quicktime chapters. The contents
1550 * don't appear to be documented, so the
1551 * bytes are copied verbatim.
1553 if (track->tag != MKTAG('c','6','0','8')) {
1554 avio_wb32(pb, 0x2C); /* size */
1555 ffio_wfourcc(pb, "text");
1556 avio_wb16(pb, 0x01);
1557 avio_wb32(pb, 0x00);
1558 avio_wb32(pb, 0x00);
1559 avio_wb32(pb, 0x00);
1560 avio_wb32(pb, 0x01);
1561 avio_wb32(pb, 0x00);
1562 avio_wb32(pb, 0x00);
1563 avio_wb32(pb, 0x00);
1564 avio_wb32(pb, 0x00004000);
1565 avio_wb16(pb, 0x0000);
1568 if (track->enc->codec_tag == MKTAG('t','m','c','d')) {
1569 int64_t tmcd_pos = avio_tell(pb);
1570 avio_wb32(pb, 0); /* size */
1571 ffio_wfourcc(pb, "tmcd");
1572 mov_write_tcmi_tag(pb, track);
1573 update_size(pb, tmcd_pos);
1575 return update_size(pb, pos);
1578 static int mov_write_smhd_tag(AVIOContext *pb)
1580 avio_wb32(pb, 16); /* size */
1581 ffio_wfourcc(pb, "smhd");
1582 avio_wb32(pb, 0); /* version & flags */
1583 avio_wb16(pb, 0); /* reserved (balance, normally = 0) */
1584 avio_wb16(pb, 0); /* reserved */
1588 static int mov_write_vmhd_tag(AVIOContext *pb)
1590 avio_wb32(pb, 0x14); /* size (always 0x14) */
1591 ffio_wfourcc(pb, "vmhd");
1592 avio_wb32(pb, 0x01); /* version & flags */
1593 avio_wb64(pb, 0); /* reserved (graphics mode = copy) */
1597 static int is_clcp_track(MOVTrack *track)
1599 return track->tag == MKTAG('c','7','0','8') ||
1600 track->tag == MKTAG('c','6','0','8');
1603 static int mov_write_hdlr_tag(AVIOContext *pb, MOVTrack *track)
1605 const char *hdlr, *descr = NULL, *hdlr_type = NULL;
1606 int64_t pos = avio_tell(pb);
1610 descr = "DataHandler";
1613 hdlr = (track->mode == MODE_MOV) ? "mhlr" : "\0\0\0\0";
1614 if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1616 descr = "VideoHandler";
1617 } else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO) {
1619 descr = "SoundHandler";
1620 } else if (track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE) {
1621 if (is_clcp_track(track)) {
1623 descr = "ClosedCaptionHandler";
1625 if (track->tag == MKTAG('t','x','3','g')) {
1627 } else if (track->tag == MKTAG('m','p','4','s')) {
1632 descr = "SubtitleHandler";
1634 } else if (track->enc->codec_tag == MKTAG('r','t','p',' ')) {
1636 descr = "HintHandler";
1637 } else if (track->enc->codec_tag == MKTAG('t','m','c','d')) {
1639 descr = "TimeCodeHandler";
1642 av_get_codec_tag_string(tag_buf, sizeof(tag_buf),
1643 track->enc->codec_tag);
1645 av_log(track->enc, AV_LOG_WARNING,
1646 "Unknown hldr_type for %s / 0x%04X, writing dummy values\n",
1647 tag_buf, track->enc->codec_tag);
1651 avio_wb32(pb, 0); /* size */
1652 ffio_wfourcc(pb, "hdlr");
1653 avio_wb32(pb, 0); /* Version & flags */
1654 avio_write(pb, hdlr, 4); /* handler */
1655 ffio_wfourcc(pb, hdlr_type); /* handler type */
1656 avio_wb32(pb, 0); /* reserved */
1657 avio_wb32(pb, 0); /* reserved */
1658 avio_wb32(pb, 0); /* reserved */
1659 if (!track || track->mode == MODE_MOV)
1660 avio_w8(pb, strlen(descr)); /* pascal string */
1661 avio_write(pb, descr, strlen(descr)); /* handler description */
1662 if (track && track->mode != MODE_MOV)
1663 avio_w8(pb, 0); /* c string */
1664 return update_size(pb, pos);
1667 static int mov_write_hmhd_tag(AVIOContext *pb)
1669 /* This atom must be present, but leaving the values at zero
1670 * seems harmless. */
1671 avio_wb32(pb, 28); /* size */
1672 ffio_wfourcc(pb, "hmhd");
1673 avio_wb32(pb, 0); /* version, flags */
1674 avio_wb16(pb, 0); /* maxPDUsize */
1675 avio_wb16(pb, 0); /* avgPDUsize */
1676 avio_wb32(pb, 0); /* maxbitrate */
1677 avio_wb32(pb, 0); /* avgbitrate */
1678 avio_wb32(pb, 0); /* reserved */
1682 static int mov_write_minf_tag(AVIOContext *pb, MOVTrack *track)
1684 int64_t pos = avio_tell(pb);
1685 avio_wb32(pb, 0); /* size */
1686 ffio_wfourcc(pb, "minf");
1687 if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO)
1688 mov_write_vmhd_tag(pb);
1689 else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
1690 mov_write_smhd_tag(pb);
1691 else if (track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE) {
1692 if (track->tag == MKTAG('t','e','x','t') || is_clcp_track(track)) {
1693 mov_write_gmhd_tag(pb, track);
1695 mov_write_nmhd_tag(pb);
1697 } else if (track->tag == MKTAG('r','t','p',' ')) {
1698 mov_write_hmhd_tag(pb);
1699 } else if (track->tag == MKTAG('t','m','c','d')) {
1700 mov_write_gmhd_tag(pb, track);
1702 if (track->mode == MODE_MOV) /* FIXME: Why do it for MODE_MOV only ? */
1703 mov_write_hdlr_tag(pb, NULL);
1704 mov_write_dinf_tag(pb);
1705 mov_write_stbl_tag(pb, track);
1706 return update_size(pb, pos);
1709 static int mov_write_mdhd_tag(AVIOContext *pb, MOVTrack *track)
1711 int version = track->track_duration < INT32_MAX ? 0 : 1;
1713 if (track->mode == MODE_ISM)
1716 (version == 1) ? avio_wb32(pb, 44) : avio_wb32(pb, 32); /* size */
1717 ffio_wfourcc(pb, "mdhd");
1718 avio_w8(pb, version);
1719 avio_wb24(pb, 0); /* flags */
1721 avio_wb64(pb, track->time);
1722 avio_wb64(pb, track->time);
1724 avio_wb32(pb, track->time); /* creation time */
1725 avio_wb32(pb, track->time); /* modification time */
1727 avio_wb32(pb, track->timescale); /* time scale (sample rate for audio) */
1729 (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
1731 (version == 1) ? avio_wb64(pb, track->track_duration) : avio_wb32(pb, track->track_duration); /* duration */
1732 avio_wb16(pb, track->language); /* language */
1733 avio_wb16(pb, 0); /* reserved (quality) */
1735 if (version != 0 && track->mode == MODE_MOV) {
1736 av_log(NULL, AV_LOG_ERROR,
1737 "FATAL error, file duration too long for timebase, this file will not be\n"
1738 "playable with quicktime. Choose a different timebase or a different\n"
1739 "container format\n");
1745 static int mov_write_mdia_tag(AVIOContext *pb, MOVTrack *track)
1747 int64_t pos = avio_tell(pb);
1748 avio_wb32(pb, 0); /* size */
1749 ffio_wfourcc(pb, "mdia");
1750 mov_write_mdhd_tag(pb, track);
1751 mov_write_hdlr_tag(pb, track);
1752 mov_write_minf_tag(pb, track);
1753 return update_size(pb, pos);
1756 /* transformation matrix
1760 static void write_matrix(AVIOContext *pb, int16_t a, int16_t b, int16_t c,
1761 int16_t d, int16_t tx, int16_t ty)
1763 avio_wb32(pb, a << 16); /* 16.16 format */
1764 avio_wb32(pb, b << 16); /* 16.16 format */
1765 avio_wb32(pb, 0); /* u in 2.30 format */
1766 avio_wb32(pb, c << 16); /* 16.16 format */
1767 avio_wb32(pb, d << 16); /* 16.16 format */
1768 avio_wb32(pb, 0); /* v in 2.30 format */
1769 avio_wb32(pb, tx << 16); /* 16.16 format */
1770 avio_wb32(pb, ty << 16); /* 16.16 format */
1771 avio_wb32(pb, 1 << 30); /* w in 2.30 format */
1774 static int mov_write_tkhd_tag(AVIOContext *pb, MOVTrack *track, AVStream *st)
1776 int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE,
1777 track->timescale, AV_ROUND_UP);
1778 int version = duration < INT32_MAX ? 0 : 1;
1781 if (track->mode == MODE_ISM)
1784 (version == 1) ? avio_wb32(pb, 104) : avio_wb32(pb, 92); /* size */
1785 ffio_wfourcc(pb, "tkhd");
1786 avio_w8(pb, version);
1787 avio_wb24(pb, (track->flags & MOV_TRACK_ENABLED) ?
1788 MOV_TKHD_FLAG_ENABLED | MOV_TKHD_FLAG_IN_MOVIE :
1789 MOV_TKHD_FLAG_IN_MOVIE);
1791 avio_wb64(pb, track->time);
1792 avio_wb64(pb, track->time);
1794 avio_wb32(pb, track->time); /* creation time */
1795 avio_wb32(pb, track->time); /* modification time */
1797 avio_wb32(pb, track->track_id); /* track-id */
1798 avio_wb32(pb, 0); /* reserved */
1800 (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
1802 (version == 1) ? avio_wb64(pb, duration) : avio_wb32(pb, duration);
1804 avio_wb32(pb, 0); /* reserved */
1805 avio_wb32(pb, 0); /* reserved */
1806 avio_wb16(pb, 0); /* layer */
1807 avio_wb16(pb, st ? st->codec->codec_type : 0); /* alternate group) */
1808 /* Volume, only for audio */
1809 if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
1810 avio_wb16(pb, 0x0100);
1813 avio_wb16(pb, 0); /* reserved */
1815 /* Matrix structure */
1816 if (st && st->metadata) {
1817 AVDictionaryEntry *rot = av_dict_get(st->metadata, "rotate", NULL, 0);
1818 rotation = (rot && rot->value) ? atoi(rot->value) : 0;
1820 if (rotation == 90) {
1821 write_matrix(pb, 0, 1, -1, 0, track->enc->height, 0);
1822 } else if (rotation == 180) {
1823 write_matrix(pb, -1, 0, 0, -1, track->enc->width, track->enc->height);
1824 } else if (rotation == 270) {
1825 write_matrix(pb, 0, -1, 1, 0, 0, track->enc->width);
1827 write_matrix(pb, 1, 0, 0, 1, 0, 0);
1829 /* Track width and height, for visual only */
1830 if (st && (track->enc->codec_type == AVMEDIA_TYPE_VIDEO ||
1831 track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE)) {
1832 if (track->mode == MODE_MOV) {
1833 avio_wb32(pb, track->enc->width << 16);
1834 avio_wb32(pb, track->height << 16);
1836 double sample_aspect_ratio = av_q2d(st->sample_aspect_ratio);
1837 if (!sample_aspect_ratio || track->height != track->enc->height)
1838 sample_aspect_ratio = 1;
1839 avio_wb32(pb, sample_aspect_ratio * track->enc->width * 0x10000);
1840 avio_wb32(pb, track->height * 0x10000);
1849 static int mov_write_tapt_tag(AVIOContext *pb, MOVTrack *track)
1851 int32_t width = av_rescale(track->enc->sample_aspect_ratio.num, track->enc->width,
1852 track->enc->sample_aspect_ratio.den);
1854 int64_t pos = avio_tell(pb);
1856 avio_wb32(pb, 0); /* size */
1857 ffio_wfourcc(pb, "tapt");
1860 ffio_wfourcc(pb, "clef");
1862 avio_wb32(pb, width << 16);
1863 avio_wb32(pb, track->enc->height << 16);
1866 ffio_wfourcc(pb, "prof");
1868 avio_wb32(pb, width << 16);
1869 avio_wb32(pb, track->enc->height << 16);
1872 ffio_wfourcc(pb, "enof");
1874 avio_wb32(pb, track->enc->width << 16);
1875 avio_wb32(pb, track->enc->height << 16);
1877 return update_size(pb, pos);
1880 // This box seems important for the psp playback ... without it the movie seems to hang
1881 static int mov_write_edts_tag(AVIOContext *pb, MOVTrack *track)
1883 int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE,
1884 track->timescale, AV_ROUND_UP);
1885 int version = duration < INT32_MAX ? 0 : 1;
1886 int entry_size, entry_count, size;
1887 int64_t delay, start_ct = track->cluster[0].cts;
1888 delay = av_rescale_rnd(track->cluster[0].dts + start_ct, MOV_TIMESCALE,
1889 track->timescale, AV_ROUND_DOWN);
1890 version |= delay < INT32_MAX ? 0 : 1;
1892 entry_size = (version == 1) ? 20 : 12;
1893 entry_count = 1 + (delay > 0);
1894 size = 24 + entry_count * entry_size;
1896 /* write the atom data */
1897 avio_wb32(pb, size);
1898 ffio_wfourcc(pb, "edts");
1899 avio_wb32(pb, size - 8);
1900 ffio_wfourcc(pb, "elst");
1901 avio_w8(pb, version);
1902 avio_wb24(pb, 0); /* flags */
1904 avio_wb32(pb, entry_count);
1905 if (delay > 0) { /* add an empty edit to delay presentation */
1907 avio_wb64(pb, delay);
1910 avio_wb32(pb, delay);
1913 avio_wb32(pb, 0x00010000);
1915 av_assert0(av_rescale_rnd(track->cluster[0].dts, MOV_TIMESCALE, track->timescale, AV_ROUND_DOWN) <= 0);
1916 start_ct = -FFMIN(track->cluster[0].dts, 0); //FFMIN needed due to rounding
1922 avio_wb64(pb, duration);
1923 avio_wb64(pb, start_ct);
1925 avio_wb32(pb, duration);
1926 avio_wb32(pb, start_ct);
1928 avio_wb32(pb, 0x00010000);
1932 static int mov_write_tref_tag(AVIOContext *pb, MOVTrack *track)
1934 avio_wb32(pb, 20); // size
1935 ffio_wfourcc(pb, "tref");
1936 avio_wb32(pb, 12); // size (subatom)
1937 avio_wl32(pb, track->tref_tag);
1938 avio_wb32(pb, track->tref_id);
1942 // goes at the end of each track! ... Critical for PSP playback ("Incompatible data" without it)
1943 static int mov_write_uuid_tag_psp(AVIOContext *pb, MOVTrack *mov)
1945 avio_wb32(pb, 0x34); /* size ... reports as 28 in mp4box! */
1946 ffio_wfourcc(pb, "uuid");
1947 ffio_wfourcc(pb, "USMT");
1948 avio_wb32(pb, 0x21d24fce);
1949 avio_wb32(pb, 0xbb88695c);
1950 avio_wb32(pb, 0xfac9c740);
1951 avio_wb32(pb, 0x1c); // another size here!
1952 ffio_wfourcc(pb, "MTDT");
1953 avio_wb32(pb, 0x00010012);
1954 avio_wb32(pb, 0x0a);
1955 avio_wb32(pb, 0x55c40000);
1961 static int mov_write_udta_sdp(AVIOContext *pb, MOVTrack *track)
1963 AVFormatContext *ctx = track->rtp_ctx;
1964 char buf[1000] = "";
1967 ff_sdp_write_media(buf, sizeof(buf), ctx->streams[0], track->src_track,
1968 NULL, NULL, 0, 0, ctx);
1969 av_strlcatf(buf, sizeof(buf), "a=control:streamid=%d\r\n", track->track_id);
1972 avio_wb32(pb, len + 24);
1973 ffio_wfourcc(pb, "udta");
1974 avio_wb32(pb, len + 16);
1975 ffio_wfourcc(pb, "hnti");
1976 avio_wb32(pb, len + 8);
1977 ffio_wfourcc(pb, "sdp ");
1978 avio_write(pb, buf, len);
1982 static int mov_write_trak_tag(AVIOContext *pb, MOVMuxContext *mov,
1983 MOVTrack *track, AVStream *st)
1985 int64_t pos = avio_tell(pb);
1986 avio_wb32(pb, 0); /* size */
1987 ffio_wfourcc(pb, "trak");
1988 mov_write_tkhd_tag(pb, track, st);
1989 if (supports_edts(mov))
1990 mov_write_edts_tag(pb, track); // PSP Movies and several other cases require edts box
1991 if (track->tref_tag)
1992 mov_write_tref_tag(pb, track);
1993 mov_write_mdia_tag(pb, track);
1994 if (track->mode == MODE_PSP)
1995 mov_write_uuid_tag_psp(pb, track); // PSP Movies require this uuid box
1996 if (track->tag == MKTAG('r','t','p',' '))
1997 mov_write_udta_sdp(pb, track);
1998 if (track->mode == MODE_MOV) {
1999 if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) {
2000 double sample_aspect_ratio = av_q2d(st->sample_aspect_ratio);
2001 if (st->sample_aspect_ratio.num && 1.0 != sample_aspect_ratio) {
2002 mov_write_tapt_tag(pb, track);
2005 if (is_clcp_track(track) && st->sample_aspect_ratio.num) {
2006 mov_write_tapt_tag(pb, track);
2009 return update_size(pb, pos);
2012 static int mov_write_iods_tag(AVIOContext *pb, MOVMuxContext *mov)
2014 int i, has_audio = 0, has_video = 0;
2015 int64_t pos = avio_tell(pb);
2016 int audio_profile = mov->iods_audio_profile;
2017 int video_profile = mov->iods_video_profile;
2018 for (i = 0; i < mov->nb_streams; i++) {
2019 if (mov->tracks[i].entry > 0) {
2020 has_audio |= mov->tracks[i].enc->codec_type == AVMEDIA_TYPE_AUDIO;
2021 has_video |= mov->tracks[i].enc->codec_type == AVMEDIA_TYPE_VIDEO;
2024 if (audio_profile < 0)
2025 audio_profile = 0xFF - has_audio;
2026 if (video_profile < 0)
2027 video_profile = 0xFF - has_video;
2028 avio_wb32(pb, 0x0); /* size */
2029 ffio_wfourcc(pb, "iods");
2030 avio_wb32(pb, 0); /* version & flags */
2031 put_descr(pb, 0x10, 7);
2032 avio_wb16(pb, 0x004f);
2035 avio_w8(pb, audio_profile);
2036 avio_w8(pb, video_profile);
2038 return update_size(pb, pos);
2041 static int mov_write_trex_tag(AVIOContext *pb, MOVTrack *track)
2043 avio_wb32(pb, 0x20); /* size */
2044 ffio_wfourcc(pb, "trex");
2045 avio_wb32(pb, 0); /* version & flags */
2046 avio_wb32(pb, track->track_id); /* track ID */
2047 avio_wb32(pb, 1); /* default sample description index */
2048 avio_wb32(pb, 0); /* default sample duration */
2049 avio_wb32(pb, 0); /* default sample size */
2050 avio_wb32(pb, 0); /* default sample flags */
2054 static int mov_write_mvex_tag(AVIOContext *pb, MOVMuxContext *mov)
2056 int64_t pos = avio_tell(pb);
2058 avio_wb32(pb, 0x0); /* size */
2059 ffio_wfourcc(pb, "mvex");
2060 for (i = 0; i < mov->nb_streams; i++)
2061 mov_write_trex_tag(pb, &mov->tracks[i]);
2062 return update_size(pb, pos);
2065 static int mov_write_mvhd_tag(AVIOContext *pb, MOVMuxContext *mov)
2067 int max_track_id = 1, i;
2068 int64_t max_track_len_temp, max_track_len = 0;
2071 for (i = 0; i < mov->nb_streams; i++) {
2072 if (mov->tracks[i].entry > 0 && mov->tracks[i].timescale) {
2073 max_track_len_temp = av_rescale_rnd(mov->tracks[i].track_duration,
2075 mov->tracks[i].timescale,
2077 if (max_track_len < max_track_len_temp)
2078 max_track_len = max_track_len_temp;
2079 if (max_track_id < mov->tracks[i].track_id)
2080 max_track_id = mov->tracks[i].track_id;
2084 version = max_track_len < UINT32_MAX ? 0 : 1;
2085 (version == 1) ? avio_wb32(pb, 120) : avio_wb32(pb, 108); /* size */
2086 ffio_wfourcc(pb, "mvhd");
2087 avio_w8(pb, version);
2088 avio_wb24(pb, 0); /* flags */
2090 avio_wb64(pb, mov->time);
2091 avio_wb64(pb, mov->time);
2093 avio_wb32(pb, mov->time); /* creation time */
2094 avio_wb32(pb, mov->time); /* modification time */
2096 avio_wb32(pb, MOV_TIMESCALE);
2097 (version == 1) ? avio_wb64(pb, max_track_len) : avio_wb32(pb, max_track_len); /* duration of longest track */
2099 avio_wb32(pb, 0x00010000); /* reserved (preferred rate) 1.0 = normal */
2100 avio_wb16(pb, 0x0100); /* reserved (preferred volume) 1.0 = normal */
2101 avio_wb16(pb, 0); /* reserved */
2102 avio_wb32(pb, 0); /* reserved */
2103 avio_wb32(pb, 0); /* reserved */
2105 /* Matrix structure */
2106 write_matrix(pb, 1, 0, 0, 1, 0, 0);
2108 avio_wb32(pb, 0); /* reserved (preview time) */
2109 avio_wb32(pb, 0); /* reserved (preview duration) */
2110 avio_wb32(pb, 0); /* reserved (poster time) */
2111 avio_wb32(pb, 0); /* reserved (selection time) */
2112 avio_wb32(pb, 0); /* reserved (selection duration) */
2113 avio_wb32(pb, 0); /* reserved (current time) */
2114 avio_wb32(pb, max_track_id + 1); /* Next track id */
2118 static int mov_write_itunes_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov,
2121 avio_wb32(pb, 33); /* size */
2122 ffio_wfourcc(pb, "hdlr");
2125 ffio_wfourcc(pb, "mdir");
2126 ffio_wfourcc(pb, "appl");
2133 /* helper function to write a data tag with the specified string as data */
2134 static int mov_write_string_data_tag(AVIOContext *pb, const char *data, int lang, int long_style)
2137 int size = 16 + strlen(data);
2138 avio_wb32(pb, size); /* size */
2139 ffio_wfourcc(pb, "data");
2142 avio_write(pb, data, strlen(data));
2146 lang = ff_mov_iso639_to_lang("und", 1);
2147 avio_wb16(pb, strlen(data)); /* string length */
2148 avio_wb16(pb, lang);
2149 avio_write(pb, data, strlen(data));
2150 return strlen(data) + 4;
2154 static int mov_write_string_tag(AVIOContext *pb, const char *name,
2155 const char *value, int lang, int long_style)
2158 if (value && value[0]) {
2159 int64_t pos = avio_tell(pb);
2160 avio_wb32(pb, 0); /* size */
2161 ffio_wfourcc(pb, name);
2162 mov_write_string_data_tag(pb, value, lang, long_style);
2163 size = update_size(pb, pos);
2168 static int mov_write_string_metadata(AVFormatContext *s, AVIOContext *pb,
2169 const char *name, const char *tag,
2172 int l, lang = 0, len, len2;
2173 AVDictionaryEntry *t, *t2 = NULL;
2176 if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
2179 len = strlen(t->key);
2180 snprintf(tag2, sizeof(tag2), "%s-", tag);
2181 while ((t2 = av_dict_get(s->metadata, tag2, t2, AV_DICT_IGNORE_SUFFIX))) {
2182 len2 = strlen(t2->key);
2183 if (len2 == len + 4 && !strcmp(t->value, t2->value)
2184 && (l = ff_mov_iso639_to_lang(&t2->key[len2 - 3], 1)) >= 0) {
2189 return mov_write_string_tag(pb, name, t->value, lang, long_style);
2192 /* iTunes bpm number */
2193 static int mov_write_tmpo_tag(AVIOContext *pb, AVFormatContext *s)
2195 AVDictionaryEntry *t = av_dict_get(s->metadata, "tmpo", NULL, 0);
2196 int size = 0, tmpo = t ? atoi(t->value) : 0;
2199 avio_wb32(pb, size);
2200 ffio_wfourcc(pb, "tmpo");
2201 avio_wb32(pb, size-8); /* size */
2202 ffio_wfourcc(pb, "data");
2203 avio_wb32(pb, 0x15); //type specifier
2205 avio_wb16(pb, tmpo); // data
2210 /* iTunes track or disc number */
2211 static int mov_write_trkn_tag(AVIOContext *pb, MOVMuxContext *mov,
2212 AVFormatContext *s, int disc)
2214 AVDictionaryEntry *t = av_dict_get(s->metadata,
2215 disc ? "disc" : "track",
2217 int size = 0, track = t ? atoi(t->value) : 0;
2220 char *slash = strchr(t->value, '/');
2222 tracks = atoi(slash + 1);
2223 avio_wb32(pb, 32); /* size */
2224 ffio_wfourcc(pb, disc ? "disk" : "trkn");
2225 avio_wb32(pb, 24); /* size */
2226 ffio_wfourcc(pb, "data");
2227 avio_wb32(pb, 0); // 8 bytes empty
2229 avio_wb16(pb, 0); // empty
2230 avio_wb16(pb, track); // track / disc number
2231 avio_wb16(pb, tracks); // total track / disc number
2232 avio_wb16(pb, 0); // empty
2238 static int mov_write_int8_metadata(AVFormatContext *s, AVIOContext *pb,
2239 const char *name, const char *tag,
2242 AVDictionaryEntry *t = NULL;
2244 int size = 24 + len;
2246 if (len != 1 && len != 4)
2249 if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
2251 num = atoi(t->value);
2253 avio_wb32(pb, size);
2254 ffio_wfourcc(pb, name);
2255 avio_wb32(pb, size - 8);
2256 ffio_wfourcc(pb, "data");
2257 avio_wb32(pb, 0x15);
2259 if (len==4) avio_wb32(pb, num);
2260 else avio_w8 (pb, num);
2265 /* iTunes meta data list */
2266 static int mov_write_ilst_tag(AVIOContext *pb, MOVMuxContext *mov,
2269 int64_t pos = avio_tell(pb);
2270 avio_wb32(pb, 0); /* size */
2271 ffio_wfourcc(pb, "ilst");
2272 mov_write_string_metadata(s, pb, "\251nam", "title" , 1);
2273 mov_write_string_metadata(s, pb, "\251ART", "artist" , 1);
2274 mov_write_string_metadata(s, pb, "aART", "album_artist", 1);
2275 mov_write_string_metadata(s, pb, "\251wrt", "composer" , 1);
2276 mov_write_string_metadata(s, pb, "\251alb", "album" , 1);
2277 mov_write_string_metadata(s, pb, "\251day", "date" , 1);
2279 !mov_write_string_metadata(s, pb, "\251too", "encoding_tool", 1))
2280 mov_write_string_tag(pb, "\251too", LIBAVFORMAT_IDENT, 0, 1);
2281 mov_write_string_metadata(s, pb, "\251cmt", "comment" , 1);
2282 mov_write_string_metadata(s, pb, "\251gen", "genre" , 1);
2283 mov_write_string_metadata(s, pb, "\251cpy", "copyright", 1);
2284 mov_write_string_metadata(s, pb, "\251grp", "grouping" , 1);
2285 mov_write_string_metadata(s, pb, "\251lyr", "lyrics" , 1);
2286 mov_write_string_metadata(s, pb, "desc", "description",1);
2287 mov_write_string_metadata(s, pb, "ldes", "synopsis" , 1);
2288 mov_write_string_metadata(s, pb, "tvsh", "show" , 1);
2289 mov_write_string_metadata(s, pb, "tven", "episode_id",1);
2290 mov_write_string_metadata(s, pb, "tvnn", "network" , 1);
2291 mov_write_int8_metadata (s, pb, "tves", "episode_sort",4);
2292 mov_write_int8_metadata (s, pb, "tvsn", "season_number",4);
2293 mov_write_int8_metadata (s, pb, "stik", "media_type",1);
2294 mov_write_int8_metadata (s, pb, "hdvd", "hd_video", 1);
2295 mov_write_int8_metadata (s, pb, "pgap", "gapless_playback",1);
2296 mov_write_int8_metadata (s, pb, "cpil", "compilation", 1);
2297 mov_write_trkn_tag(pb, mov, s, 0); // track number
2298 mov_write_trkn_tag(pb, mov, s, 1); // disc number
2299 mov_write_tmpo_tag(pb, s);
2300 return update_size(pb, pos);
2303 /* iTunes meta data tag */
2304 static int mov_write_meta_tag(AVIOContext *pb, MOVMuxContext *mov,
2308 int64_t pos = avio_tell(pb);
2309 avio_wb32(pb, 0); /* size */
2310 ffio_wfourcc(pb, "meta");
2312 mov_write_itunes_hdlr_tag(pb, mov, s);
2313 mov_write_ilst_tag(pb, mov, s);
2314 size = update_size(pb, pos);
2318 static int utf8len(const uint8_t *b)
2323 GET_UTF8(val, *b++, return -1;)
2329 static int ascii_to_wc(AVIOContext *pb, const uint8_t *b)
2333 GET_UTF8(val, *b++, return -1;)
2336 avio_wb16(pb, 0x00);
2340 static uint16_t language_code(const char *str)
2342 return (((str[0] - 0x60) & 0x1F) << 10) +
2343 (((str[1] - 0x60) & 0x1F) << 5) +
2344 (( str[2] - 0x60) & 0x1F);
2347 static int mov_write_3gp_udta_tag(AVIOContext *pb, AVFormatContext *s,
2348 const char *tag, const char *str)
2350 int64_t pos = avio_tell(pb);
2351 AVDictionaryEntry *t = av_dict_get(s->metadata, str, NULL, 0);
2352 if (!t || !utf8len(t->value))
2354 avio_wb32(pb, 0); /* size */
2355 ffio_wfourcc(pb, tag); /* type */
2356 avio_wb32(pb, 0); /* version + flags */
2357 if (!strcmp(tag, "yrrc"))
2358 avio_wb16(pb, atoi(t->value));
2360 avio_wb16(pb, language_code("eng")); /* language */
2361 avio_write(pb, t->value, strlen(t->value) + 1); /* UTF8 string value */
2362 if (!strcmp(tag, "albm") &&
2363 (t = av_dict_get(s->metadata, "track", NULL, 0)))
2364 avio_w8(pb, atoi(t->value));
2366 return update_size(pb, pos);
2369 static int mov_write_chpl_tag(AVIOContext *pb, AVFormatContext *s)
2371 int64_t pos = avio_tell(pb);
2372 int i, nb_chapters = FFMIN(s->nb_chapters, 255);
2374 avio_wb32(pb, 0); // size
2375 ffio_wfourcc(pb, "chpl");
2376 avio_wb32(pb, 0x01000000); // version + flags
2377 avio_wb32(pb, 0); // unknown
2378 avio_w8(pb, nb_chapters);
2380 for (i = 0; i < nb_chapters; i++) {
2381 AVChapter *c = s->chapters[i];
2382 AVDictionaryEntry *t;
2383 avio_wb64(pb, av_rescale_q(c->start, c->time_base, (AVRational){1,10000000}));
2385 if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
2386 int len = FFMIN(strlen(t->value), 255);
2388 avio_write(pb, t->value, len);
2392 return update_size(pb, pos);
2395 static int mov_write_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
2398 AVIOContext *pb_buf;
2402 ret = avio_open_dyn_buf(&pb_buf);
2406 if (mov->mode & MODE_3GP) {
2407 mov_write_3gp_udta_tag(pb_buf, s, "perf", "artist");
2408 mov_write_3gp_udta_tag(pb_buf, s, "titl", "title");
2409 mov_write_3gp_udta_tag(pb_buf, s, "auth", "author");
2410 mov_write_3gp_udta_tag(pb_buf, s, "gnre", "genre");
2411 mov_write_3gp_udta_tag(pb_buf, s, "dscp", "comment");
2412 mov_write_3gp_udta_tag(pb_buf, s, "albm", "album");
2413 mov_write_3gp_udta_tag(pb_buf, s, "cprt", "copyright");
2414 mov_write_3gp_udta_tag(pb_buf, s, "yrrc", "date");
2415 } else if (mov->mode == MODE_MOV) { // the title field breaks gtkpod with mp4 and my suspicion is that stuff is not valid in mp4
2416 mov_write_string_metadata(s, pb_buf, "\251ART", "artist", 0);
2417 mov_write_string_metadata(s, pb_buf, "\251nam", "title", 0);
2418 mov_write_string_metadata(s, pb_buf, "\251aut", "author", 0);
2419 mov_write_string_metadata(s, pb_buf, "\251alb", "album", 0);
2420 mov_write_string_metadata(s, pb_buf, "\251day", "date", 0);
2421 mov_write_string_metadata(s, pb_buf, "\251swr", "encoder", 0);
2422 // currently ignored by mov.c
2423 mov_write_string_metadata(s, pb_buf, "\251des", "comment", 0);
2424 // add support for libquicktime, this atom is also actually read by mov.c
2425 mov_write_string_metadata(s, pb_buf, "\251cmt", "comment", 0);
2426 mov_write_string_metadata(s, pb_buf, "\251gen", "genre", 0);
2427 mov_write_string_metadata(s, pb_buf, "\251cpy", "copyright", 0);
2429 /* iTunes meta data */
2430 mov_write_meta_tag(pb_buf, mov, s);
2434 mov_write_chpl_tag(pb_buf, s);
2436 if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) {
2437 avio_wb32(pb, size + 8);
2438 ffio_wfourcc(pb, "udta");
2439 avio_write(pb, buf, size);
2446 static void mov_write_psp_udta_tag(AVIOContext *pb,
2447 const char *str, const char *lang, int type)
2449 int len = utf8len(str) + 1;
2452 avio_wb16(pb, len * 2 + 10); /* size */
2453 avio_wb32(pb, type); /* type */
2454 avio_wb16(pb, language_code(lang)); /* language */
2455 avio_wb16(pb, 0x01); /* ? */
2456 ascii_to_wc(pb, str);
2459 static int mov_write_uuidusmt_tag(AVIOContext *pb, AVFormatContext *s)
2461 MOVMuxContext *mov = s->priv_data;
2462 AVDictionaryEntry *title = av_dict_get(s->metadata, "title", NULL, 0);
2466 pos = avio_tell(pb);
2467 avio_wb32(pb, 0); /* size placeholder*/
2468 ffio_wfourcc(pb, "uuid");
2469 ffio_wfourcc(pb, "USMT");
2470 avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
2471 avio_wb32(pb, 0xbb88695c);
2472 avio_wb32(pb, 0xfac9c740);
2474 pos2 = avio_tell(pb);
2475 avio_wb32(pb, 0); /* size placeholder*/
2476 ffio_wfourcc(pb, "MTDT");
2480 avio_wb16(pb, 0x0C); /* size */
2481 avio_wb32(pb, 0x0B); /* type */
2482 avio_wb16(pb, language_code("und")); /* language */
2483 avio_wb16(pb, 0x0); /* ? */
2484 avio_wb16(pb, 0x021C); /* data */
2487 mov_write_psp_udta_tag(pb, LIBAVCODEC_IDENT, "eng", 0x04);
2488 mov_write_psp_udta_tag(pb, title->value, "eng", 0x01);
2489 mov_write_psp_udta_tag(pb, "2006/04/01 11:11:11", "und", 0x03);
2491 update_size(pb, pos2);
2492 return update_size(pb, pos);
2498 static void build_chunks(MOVTrack *trk)
2501 MOVIentry *chunk = &trk->cluster[0];
2502 uint64_t chunkSize = chunk->size;
2503 chunk->chunkNum = 1;
2504 if (trk->chunkCount)
2506 trk->chunkCount = 1;
2507 for (i = 1; i<trk->entry; i++){
2508 if (chunk->pos + chunkSize == trk->cluster[i].pos &&
2509 chunkSize + trk->cluster[i].size < (1<<20)){
2510 chunkSize += trk->cluster[i].size;
2511 chunk->samples_in_chunk += trk->cluster[i].entries;
2513 trk->cluster[i].chunkNum = chunk->chunkNum+1;
2514 chunk=&trk->cluster[i];
2515 chunkSize = chunk->size;
2521 static int mov_write_moov_tag(AVIOContext *pb, MOVMuxContext *mov,
2525 int64_t pos = avio_tell(pb);
2526 avio_wb32(pb, 0); /* size placeholder*/
2527 ffio_wfourcc(pb, "moov");
2529 for (i = 0; i < mov->nb_streams; i++) {
2530 if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
2533 mov->tracks[i].time = mov->time;
2534 mov->tracks[i].track_id = i + 1;
2536 if (mov->tracks[i].entry)
2537 build_chunks(&mov->tracks[i]);
2540 if (mov->chapter_track)
2541 for (i = 0; i < s->nb_streams; i++) {
2542 mov->tracks[i].tref_tag = MKTAG('c','h','a','p');
2543 mov->tracks[i].tref_id = mov->tracks[mov->chapter_track].track_id;
2545 for (i = 0; i < mov->nb_streams; i++) {
2546 if (mov->tracks[i].tag == MKTAG('r','t','p',' ')) {
2547 mov->tracks[i].tref_tag = MKTAG('h','i','n','t');
2548 mov->tracks[i].tref_id =
2549 mov->tracks[mov->tracks[i].src_track].track_id;
2552 for (i = 0; i < mov->nb_streams; i++) {
2553 if (mov->tracks[i].tag == MKTAG('t','m','c','d')) {
2554 int src_trk = mov->tracks[i].src_track;
2555 mov->tracks[src_trk].tref_tag = mov->tracks[i].tag;
2556 mov->tracks[src_trk].tref_id = mov->tracks[i].track_id;
2557 //src_trk may have a different timescale than the tmcd track
2558 mov->tracks[i].track_duration = av_rescale(mov->tracks[src_trk].track_duration,
2559 mov->tracks[i].timescale,
2560 mov->tracks[src_trk].timescale);
2564 mov_write_mvhd_tag(pb, mov);
2565 if (mov->mode != MODE_MOV && !mov->iods_skip)
2566 mov_write_iods_tag(pb, mov);
2567 for (i = 0; i < mov->nb_streams; i++) {
2568 if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_FRAGMENT) {
2569 mov_write_trak_tag(pb, mov, &(mov->tracks[i]), i < s->nb_streams ? s->streams[i] : NULL);
2572 if (mov->flags & FF_MOV_FLAG_FRAGMENT)
2573 mov_write_mvex_tag(pb, mov); /* QuickTime requires trak to precede this */
2575 if (mov->mode == MODE_PSP)
2576 mov_write_uuidusmt_tag(pb, s);
2578 mov_write_udta_tag(pb, mov, s);
2580 return update_size(pb, pos);
2583 static void param_write_int(AVIOContext *pb, const char *name, int value)
2585 avio_printf(pb, "<param name=\"%s\" value=\"%d\" valuetype=\"data\"/>\n", name, value);
2588 static void param_write_string(AVIOContext *pb, const char *name, const char *value)
2590 avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, value);
2593 static void param_write_hex(AVIOContext *pb, const char *name, const uint8_t *value, int len)
2596 len = FFMIN(sizeof(buf) / 2 - 1, len);
2597 ff_data_to_hex(buf, value, len, 0);
2598 buf[2 * len] = '\0';
2599 avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, buf);
2602 static int mov_write_isml_manifest(AVIOContext *pb, MOVMuxContext *mov)
2604 int64_t pos = avio_tell(pb);
2606 static const uint8_t uuid[] = {
2607 0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd,
2608 0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66
2612 ffio_wfourcc(pb, "uuid");
2613 avio_write(pb, uuid, sizeof(uuid));
2616 avio_printf(pb, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
2617 avio_printf(pb, "<smil xmlns=\"http://www.w3.org/2001/SMIL20/Language\">\n");
2618 avio_printf(pb, "<head>\n");
2620 avio_printf(pb, "<meta name=\"creator\" content=\"%s\" />\n",
2622 avio_printf(pb, "</head>\n");
2623 avio_printf(pb, "<body>\n");
2624 avio_printf(pb, "<switch>\n");
2625 for (i = 0; i < mov->nb_streams; i++) {
2626 MOVTrack *track = &mov->tracks[i];
2628 /* track->track_id is initialized in write_moov, and thus isn't known
2630 int track_id = i + 1;
2632 if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) {
2634 } else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO) {
2639 avio_printf(pb, "<%s systemBitrate=\"%d\">\n", type,
2640 track->enc->bit_rate);
2641 param_write_int(pb, "systemBitrate", track->enc->bit_rate);
2642 param_write_int(pb, "trackID", track_id);
2643 if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) {
2644 if (track->enc->codec_id == AV_CODEC_ID_H264) {
2646 int size = track->enc->extradata_size;
2647 if (!ff_avc_write_annexb_extradata(track->enc->extradata, &ptr,
2649 param_write_hex(pb, "CodecPrivateData",
2650 ptr ? ptr : track->enc->extradata,
2654 param_write_string(pb, "FourCC", "H264");
2655 } else if (track->enc->codec_id == AV_CODEC_ID_VC1) {
2656 param_write_string(pb, "FourCC", "WVC1");
2657 param_write_hex(pb, "CodecPrivateData", track->enc->extradata,
2658 track->enc->extradata_size);
2660 param_write_int(pb, "MaxWidth", track->enc->width);
2661 param_write_int(pb, "MaxHeight", track->enc->height);
2662 param_write_int(pb, "DisplayWidth", track->enc->width);
2663 param_write_int(pb, "DisplayHeight", track->enc->height);
2665 if (track->enc->codec_id == AV_CODEC_ID_AAC) {
2666 param_write_string(pb, "FourCC", "AACL");
2667 } else if (track->enc->codec_id == AV_CODEC_ID_WMAPRO) {
2668 param_write_string(pb, "FourCC", "WMAP");
2670 param_write_hex(pb, "CodecPrivateData", track->enc->extradata,
2671 track->enc->extradata_size);
2672 param_write_int(pb, "AudioTag", ff_codec_get_tag(ff_codec_wav_tags,
2673 track->enc->codec_id));
2674 param_write_int(pb, "Channels", track->enc->channels);
2675 param_write_int(pb, "SamplingRate", track->enc->sample_rate);
2676 param_write_int(pb, "BitsPerSample", 16);
2677 param_write_int(pb, "PacketSize", track->enc->block_align ?
2678 track->enc->block_align : 4);
2680 avio_printf(pb, "</%s>\n", type);
2682 avio_printf(pb, "</switch>\n");
2683 avio_printf(pb, "</body>\n");
2684 avio_printf(pb, "</smil>\n");
2686 return update_size(pb, pos);
2689 static int mov_write_mfhd_tag(AVIOContext *pb, MOVMuxContext *mov)
2692 ffio_wfourcc(pb, "mfhd");
2694 avio_wb32(pb, mov->fragments);
2698 static int mov_write_tfhd_tag(AVIOContext *pb, MOVMuxContext *mov,
2699 MOVTrack *track, int64_t moof_offset)
2701 int64_t pos = avio_tell(pb);
2702 uint32_t flags = MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
2703 MOV_TFHD_BASE_DATA_OFFSET;
2704 if (!track->entry) {
2705 flags |= MOV_TFHD_DURATION_IS_EMPTY;
2707 flags |= MOV_TFHD_DEFAULT_FLAGS;
2709 if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET)
2710 flags &= ~MOV_TFHD_BASE_DATA_OFFSET;
2712 /* Don't set a default sample size, the silverlight player refuses
2713 * to play files with that set. Don't set a default sample duration,
2714 * WMP freaks out if it is set. Don't set a base data offset, PIFF
2715 * file format says it MUST NOT be set. */
2716 if (track->mode == MODE_ISM)
2717 flags &= ~(MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
2718 MOV_TFHD_BASE_DATA_OFFSET);
2720 avio_wb32(pb, 0); /* size placeholder */
2721 ffio_wfourcc(pb, "tfhd");
2722 avio_w8(pb, 0); /* version */
2723 avio_wb24(pb, flags);
2725 avio_wb32(pb, track->track_id); /* track-id */
2726 if (flags & MOV_TFHD_BASE_DATA_OFFSET)
2727 avio_wb64(pb, moof_offset);
2728 if (flags & MOV_TFHD_DEFAULT_DURATION) {
2729 track->default_duration = get_cluster_duration(track, 0);
2730 avio_wb32(pb, track->default_duration);
2732 if (flags & MOV_TFHD_DEFAULT_SIZE) {
2733 track->default_size = track->entry ? track->cluster[0].size : 1;
2734 avio_wb32(pb, track->default_size);
2736 track->default_size = -1;
2738 if (flags & MOV_TFHD_DEFAULT_FLAGS) {
2739 track->default_sample_flags =
2740 track->enc->codec_type == AVMEDIA_TYPE_VIDEO ?
2741 (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC) :
2742 MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO;
2743 avio_wb32(pb, track->default_sample_flags);
2746 return update_size(pb, pos);
2749 static uint32_t get_sample_flags(MOVTrack *track, MOVIentry *entry)
2751 return entry->flags & MOV_SYNC_SAMPLE ? MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO :
2752 (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC);
2755 static int mov_write_trun_tag(AVIOContext *pb, MOVMuxContext *mov,
2756 MOVTrack *track, int moof_size)
2758 int64_t pos = avio_tell(pb);
2759 uint32_t flags = MOV_TRUN_DATA_OFFSET;
2762 for (i = 0; i < track->entry; i++) {
2763 if (get_cluster_duration(track, i) != track->default_duration)
2764 flags |= MOV_TRUN_SAMPLE_DURATION;
2765 if (track->cluster[i].size != track->default_size)
2766 flags |= MOV_TRUN_SAMPLE_SIZE;
2767 if (i > 0 && get_sample_flags(track, &track->cluster[i]) != track->default_sample_flags)
2768 flags |= MOV_TRUN_SAMPLE_FLAGS;
2770 if (!(flags & MOV_TRUN_SAMPLE_FLAGS))
2771 flags |= MOV_TRUN_FIRST_SAMPLE_FLAGS;
2772 if (track->flags & MOV_TRACK_CTTS)
2773 flags |= MOV_TRUN_SAMPLE_CTS;
2775 avio_wb32(pb, 0); /* size placeholder */
2776 ffio_wfourcc(pb, "trun");
2777 avio_w8(pb, 0); /* version */
2778 avio_wb24(pb, flags);
2780 avio_wb32(pb, track->entry); /* sample count */
2781 if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET &&
2782 !(mov->flags & FF_MOV_FLAG_SEPARATE_MOOF) &&
2783 track->track_id != 1)
2784 avio_wb32(pb, 0); /* Later tracks follow immediately after the previous one */
2786 avio_wb32(pb, moof_size + 8 + track->data_offset +
2787 track->cluster[0].pos); /* data offset */
2788 if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS)
2789 avio_wb32(pb, get_sample_flags(track, &track->cluster[0]));
2791 for (i = 0; i < track->entry; i++) {
2792 if (flags & MOV_TRUN_SAMPLE_DURATION)
2793 avio_wb32(pb, get_cluster_duration(track, i));
2794 if (flags & MOV_TRUN_SAMPLE_SIZE)
2795 avio_wb32(pb, track->cluster[i].size);
2796 if (flags & MOV_TRUN_SAMPLE_FLAGS)
2797 avio_wb32(pb, get_sample_flags(track, &track->cluster[i]));
2798 if (flags & MOV_TRUN_SAMPLE_CTS)
2799 avio_wb32(pb, track->cluster[i].cts);
2802 return update_size(pb, pos);
2805 static int mov_write_tfxd_tag(AVIOContext *pb, MOVTrack *track)
2807 int64_t pos = avio_tell(pb);
2808 static const uint8_t uuid[] = {
2809 0x6d, 0x1d, 0x9b, 0x05, 0x42, 0xd5, 0x44, 0xe6,
2810 0x80, 0xe2, 0x14, 0x1d, 0xaf, 0xf7, 0x57, 0xb2
2813 avio_wb32(pb, 0); /* size placeholder */
2814 ffio_wfourcc(pb, "uuid");
2815 avio_write(pb, uuid, sizeof(uuid));
2818 avio_wb64(pb, track->frag_start);
2819 avio_wb64(pb, track->start_dts + track->track_duration -
2820 track->cluster[0].dts);
2822 return update_size(pb, pos);
2825 static int mov_write_tfrf_tag(AVIOContext *pb, MOVMuxContext *mov,
2826 MOVTrack *track, int entry)
2828 int n = track->nb_frag_info - 1 - entry, i;
2829 int size = 8 + 16 + 4 + 1 + 16*n;
2830 static const uint8_t uuid[] = {
2831 0xd4, 0x80, 0x7e, 0xf2, 0xca, 0x39, 0x46, 0x95,
2832 0x8e, 0x54, 0x26, 0xcb, 0x9e, 0x46, 0xa7, 0x9f
2838 avio_seek(pb, track->frag_info[entry].tfrf_offset, SEEK_SET);
2839 avio_wb32(pb, size);
2840 ffio_wfourcc(pb, "uuid");
2841 avio_write(pb, uuid, sizeof(uuid));
2845 for (i = 0; i < n; i++) {
2846 int index = entry + 1 + i;
2847 avio_wb64(pb, track->frag_info[index].time);
2848 avio_wb64(pb, track->frag_info[index].duration);
2850 if (n < mov->ism_lookahead) {
2851 int free_size = 16 * (mov->ism_lookahead - n);
2852 avio_wb32(pb, free_size);
2853 ffio_wfourcc(pb, "free");
2854 ffio_fill(pb, 0, free_size - 8);
2860 static int mov_write_tfrf_tags(AVIOContext *pb, MOVMuxContext *mov,
2863 int64_t pos = avio_tell(pb);
2865 for (i = 0; i < mov->ism_lookahead; i++) {
2866 /* Update the tfrf tag for the last ism_lookahead fragments,
2867 * nb_frag_info - 1 is the next fragment to be written. */
2868 mov_write_tfrf_tag(pb, mov, track, track->nb_frag_info - 2 - i);
2870 avio_seek(pb, pos, SEEK_SET);
2874 static int mov_write_traf_tag(AVIOContext *pb, MOVMuxContext *mov,
2875 MOVTrack *track, int64_t moof_offset,
2878 int64_t pos = avio_tell(pb);
2879 avio_wb32(pb, 0); /* size placeholder */
2880 ffio_wfourcc(pb, "traf");
2882 mov_write_tfhd_tag(pb, mov, track, moof_offset);
2883 mov_write_trun_tag(pb, mov, track, moof_size);
2884 if (mov->mode == MODE_ISM) {
2885 mov_write_tfxd_tag(pb, track);
2887 if (mov->ism_lookahead) {
2888 int i, size = 16 + 4 + 1 + 16 * mov->ism_lookahead;
2890 track->tfrf_offset = avio_tell(pb);
2891 avio_wb32(pb, 8 + size);
2892 ffio_wfourcc(pb, "free");
2893 for (i = 0; i < size; i++)
2898 return update_size(pb, pos);
2901 static int mov_write_moof_tag_internal(AVIOContext *pb, MOVMuxContext *mov,
2902 int tracks, int moof_size)
2904 int64_t pos = avio_tell(pb);
2907 avio_wb32(pb, 0); /* size placeholder */
2908 ffio_wfourcc(pb, "moof");
2910 mov_write_mfhd_tag(pb, mov);
2911 for (i = 0; i < mov->nb_streams; i++) {
2912 MOVTrack *track = &mov->tracks[i];
2913 if (tracks >= 0 && i != tracks)
2917 mov_write_traf_tag(pb, mov, track, pos, moof_size);
2920 return update_size(pb, pos);
2923 static int mov_write_moof_tag(AVIOContext *pb, MOVMuxContext *mov, int tracks)
2925 AVIOContext *avio_buf;
2928 if ((ret = ffio_open_null_buf(&avio_buf)) < 0)
2930 mov_write_moof_tag_internal(avio_buf, mov, tracks, 0);
2931 moof_size = ffio_close_null_buf(avio_buf);
2932 return mov_write_moof_tag_internal(pb, mov, tracks, moof_size);
2935 static int mov_write_tfra_tag(AVIOContext *pb, MOVTrack *track)
2937 int64_t pos = avio_tell(pb);
2940 avio_wb32(pb, 0); /* size placeholder */
2941 ffio_wfourcc(pb, "tfra");
2942 avio_w8(pb, 1); /* version */
2945 avio_wb32(pb, track->track_id);
2946 avio_wb32(pb, 0); /* length of traf/trun/sample num */
2947 avio_wb32(pb, track->nb_frag_info);
2948 for (i = 0; i < track->nb_frag_info; i++) {
2949 avio_wb64(pb, track->frag_info[i].time);
2950 avio_wb64(pb, track->frag_info[i].offset);
2951 avio_w8(pb, 1); /* traf number */
2952 avio_w8(pb, 1); /* trun number */
2953 avio_w8(pb, 1); /* sample number */
2956 return update_size(pb, pos);
2959 static int mov_write_mfra_tag(AVIOContext *pb, MOVMuxContext *mov)
2961 int64_t pos = avio_tell(pb);
2964 avio_wb32(pb, 0); /* size placeholder */
2965 ffio_wfourcc(pb, "mfra");
2966 /* An empty mfra atom is enough to indicate to the publishing point that
2967 * the stream has ended. */
2968 if (mov->flags & FF_MOV_FLAG_ISML)
2969 return update_size(pb, pos);
2971 for (i = 0; i < mov->nb_streams; i++) {
2972 MOVTrack *track = &mov->tracks[i];
2973 if (track->nb_frag_info)
2974 mov_write_tfra_tag(pb, track);
2978 ffio_wfourcc(pb, "mfro");
2979 avio_wb32(pb, 0); /* version + flags */
2980 avio_wb32(pb, avio_tell(pb) + 4 - pos);
2982 return update_size(pb, pos);
2985 static int mov_write_mdat_tag(AVIOContext *pb, MOVMuxContext *mov)
2987 avio_wb32(pb, 8); // placeholder for extended size field (64 bit)
2988 ffio_wfourcc(pb, mov->mode == MODE_MOV ? "wide" : "free");
2990 mov->mdat_pos = avio_tell(pb);
2991 avio_wb32(pb, 0); /* size placeholder*/
2992 ffio_wfourcc(pb, "mdat");
2996 /* TODO: This needs to be more general */
2997 static int mov_write_ftyp_tag(AVIOContext *pb, AVFormatContext *s)
2999 MOVMuxContext *mov = s->priv_data;
3000 int64_t pos = avio_tell(pb);
3001 int has_h264 = 0, has_video = 0;
3005 for (i = 0; i < s->nb_streams; i++) {
3006 AVStream *st = s->streams[i];
3007 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
3009 if (st->codec->codec_id == AV_CODEC_ID_H264)
3013 avio_wb32(pb, 0); /* size */
3014 ffio_wfourcc(pb, "ftyp");
3016 if (mov->major_brand && strlen(mov->major_brand) >= 4)
3017 ffio_wfourcc(pb, mov->major_brand);
3018 else if (mov->mode == MODE_3GP) {
3019 ffio_wfourcc(pb, has_h264 ? "3gp6" : "3gp4");
3020 minor = has_h264 ? 0x100 : 0x200;
3021 } else if (mov->mode & MODE_3G2) {
3022 ffio_wfourcc(pb, has_h264 ? "3g2b" : "3g2a");
3023 minor = has_h264 ? 0x20000 : 0x10000;
3024 } else if (mov->mode == MODE_PSP)
3025 ffio_wfourcc(pb, "MSNV");
3026 else if (mov->mode == MODE_MP4)
3027 ffio_wfourcc(pb, "isom");
3028 else if (mov->mode == MODE_IPOD)
3029 ffio_wfourcc(pb, has_video ? "M4V ":"M4A ");
3030 else if (mov->mode == MODE_ISM)
3031 ffio_wfourcc(pb, "isml");
3032 else if (mov->mode == MODE_F4V)
3033 ffio_wfourcc(pb, "f4v ");
3035 ffio_wfourcc(pb, "qt ");
3037 avio_wb32(pb, minor);
3039 if (mov->mode == MODE_MOV)
3040 ffio_wfourcc(pb, "qt ");
3041 else if (mov->mode == MODE_ISM) {
3042 ffio_wfourcc(pb, "piff");
3043 ffio_wfourcc(pb, "iso2");
3045 ffio_wfourcc(pb, "isom");
3046 ffio_wfourcc(pb, "iso2");
3048 ffio_wfourcc(pb, "avc1");
3051 if (mov->mode == MODE_3GP)
3052 ffio_wfourcc(pb, has_h264 ? "3gp6":"3gp4");
3053 else if (mov->mode & MODE_3G2)
3054 ffio_wfourcc(pb, has_h264 ? "3g2b":"3g2a");
3055 else if (mov->mode == MODE_PSP)
3056 ffio_wfourcc(pb, "MSNV");
3057 else if (mov->mode == MODE_MP4)
3058 ffio_wfourcc(pb, "mp41");
3059 return update_size(pb, pos);
3062 static void mov_write_uuidprof_tag(AVIOContext *pb, AVFormatContext *s)
3064 AVStream *video_st = s->streams[0];
3065 AVCodecContext *video_codec = s->streams[0]->codec;
3066 AVCodecContext *audio_codec = s->streams[1]->codec;
3067 int audio_rate = audio_codec->sample_rate;
3068 // TODO: should be avg_frame_rate
3069 int frame_rate = ((video_st->time_base.den) * (0x10000)) / (video_st->time_base.num);
3070 int audio_kbitrate = audio_codec->bit_rate / 1000;
3071 int video_kbitrate = FFMIN(video_codec->bit_rate / 1000, 800 - audio_kbitrate);
3073 avio_wb32(pb, 0x94); /* size */
3074 ffio_wfourcc(pb, "uuid");
3075 ffio_wfourcc(pb, "PROF");
3077 avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
3078 avio_wb32(pb, 0xbb88695c);
3079 avio_wb32(pb, 0xfac9c740);
3081 avio_wb32(pb, 0x0); /* ? */
3082 avio_wb32(pb, 0x3); /* 3 sections ? */
3084 avio_wb32(pb, 0x14); /* size */
3085 ffio_wfourcc(pb, "FPRF");
3086 avio_wb32(pb, 0x0); /* ? */
3087 avio_wb32(pb, 0x0); /* ? */
3088 avio_wb32(pb, 0x0); /* ? */
3090 avio_wb32(pb, 0x2c); /* size */
3091 ffio_wfourcc(pb, "APRF"); /* audio */
3093 avio_wb32(pb, 0x2); /* TrackID */
3094 ffio_wfourcc(pb, "mp4a");
3095 avio_wb32(pb, 0x20f);
3097 avio_wb32(pb, audio_kbitrate);
3098 avio_wb32(pb, audio_kbitrate);
3099 avio_wb32(pb, audio_rate);
3100 avio_wb32(pb, audio_codec->channels);
3102 avio_wb32(pb, 0x34); /* size */
3103 ffio_wfourcc(pb, "VPRF"); /* video */
3105 avio_wb32(pb, 0x1); /* TrackID */
3106 if (video_codec->codec_id == AV_CODEC_ID_H264) {
3107 ffio_wfourcc(pb, "avc1");
3108 avio_wb16(pb, 0x014D);
3109 avio_wb16(pb, 0x0015);
3111 ffio_wfourcc(pb, "mp4v");
3112 avio_wb16(pb, 0x0000);
3113 avio_wb16(pb, 0x0103);
3116 avio_wb32(pb, video_kbitrate);
3117 avio_wb32(pb, video_kbitrate);
3118 avio_wb32(pb, frame_rate);
3119 avio_wb32(pb, frame_rate);
3120 avio_wb16(pb, video_codec->width);
3121 avio_wb16(pb, video_codec->height);
3122 avio_wb32(pb, 0x010001); /* ? */
3125 static int mov_parse_mpeg2_frame(AVPacket *pkt, uint32_t *flags)
3128 int i, closed_gop = 0;
3130 for (i = 0; i < pkt->size - 4; i++) {
3131 c = (c << 8) + pkt->data[i];
3132 if (c == 0x1b8) { // gop
3133 closed_gop = pkt->data[i + 4] >> 6 & 0x01;
3134 } else if (c == 0x100) { // pic
3135 int temp_ref = (pkt->data[i + 1] << 2) | (pkt->data[i + 2] >> 6);
3136 if (!temp_ref || closed_gop) // I picture is not reordered
3137 *flags = MOV_SYNC_SAMPLE;
3139 *flags = MOV_PARTIAL_SYNC_SAMPLE;
3146 static void mov_parse_vc1_frame(AVPacket *pkt, MOVTrack *trk, int fragment)
3148 const uint8_t *start, *next, *end = pkt->data + pkt->size;
3149 int seq = 0, entry = 0;
3150 int key = pkt->flags & AV_PKT_FLAG_KEY;
3151 start = find_next_marker(pkt->data, end);
3152 for (next = start; next < end; start = next) {
3153 next = find_next_marker(start + 4, end);
3154 switch (AV_RB32(start)) {
3155 case VC1_CODE_SEQHDR:
3158 case VC1_CODE_ENTRYPOINT:
3161 case VC1_CODE_SLICE:
3162 trk->vc1_info.slices = 1;
3166 if (!trk->entry && !fragment) {
3167 /* First packet in first fragment */
3168 trk->vc1_info.first_packet_seq = seq;
3169 trk->vc1_info.first_packet_entry = entry;
3170 } else if ((seq && !trk->vc1_info.packet_seq) ||
3171 (entry && !trk->vc1_info.packet_entry)) {
3173 for (i = 0; i < trk->entry; i++)
3174 trk->cluster[i].flags &= ~MOV_SYNC_SAMPLE;
3175 trk->has_keyframes = 0;
3177 trk->vc1_info.packet_seq = 1;
3179 trk->vc1_info.packet_entry = 1;
3181 /* First fragment */
3182 if ((!seq || trk->vc1_info.first_packet_seq) &&
3183 (!entry || trk->vc1_info.first_packet_entry)) {
3184 /* First packet had the same headers as this one, readd the
3185 * sync sample flag. */
3186 trk->cluster[0].flags |= MOV_SYNC_SAMPLE;
3187 trk->has_keyframes = 1;
3191 if (trk->vc1_info.packet_seq && trk->vc1_info.packet_entry)
3193 else if (trk->vc1_info.packet_seq)
3195 else if (trk->vc1_info.packet_entry)
3198 trk->cluster[trk->entry].flags |= MOV_SYNC_SAMPLE;
3199 trk->has_keyframes++;
3203 static int mov_flush_fragment(AVFormatContext *s)
3205 MOVMuxContext *mov = s->priv_data;
3206 int i, first_track = -1;
3207 int64_t mdat_size = 0;
3209 if (!(mov->flags & FF_MOV_FLAG_FRAGMENT))
3212 if (!(mov->flags & FF_MOV_FLAG_EMPTY_MOOV) && mov->fragments == 0) {
3213 int64_t pos = avio_tell(s->pb);
3215 int buf_size, moov_size;
3217 for (i = 0; i < mov->nb_streams; i++)
3218 if (!mov->tracks[i].entry)
3220 /* Don't write the initial moov unless all tracks have data */
3221 if (i < mov->nb_streams)
3224 moov_size = get_moov_size(s);
3225 for (i = 0; i < mov->nb_streams; i++)
3226 mov->tracks[i].data_offset = pos + moov_size + 8;
3228 mov_write_moov_tag(s->pb, mov, s);
3230 buf_size = avio_close_dyn_buf(mov->mdat_buf, &buf);
3231 mov->mdat_buf = NULL;
3232 avio_wb32(s->pb, buf_size + 8);
3233 ffio_wfourcc(s->pb, "mdat");
3234 avio_write(s->pb, buf, buf_size);
3239 for (i = 0; i < mov->nb_streams; i++) {
3240 if (mov->tracks[i].entry)
3241 mov->tracks[i].frag_start += mov->tracks[i].start_dts +
3242 mov->tracks[i].track_duration -
3243 mov->tracks[i].cluster[0].dts;
3244 mov->tracks[i].entry = 0;
3250 for (i = 0; i < mov->nb_streams; i++) {
3251 MOVTrack *track = &mov->tracks[i];
3252 if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF)
3253 track->data_offset = 0;
3255 track->data_offset = mdat_size;
3256 if (!track->mdat_buf)
3258 mdat_size += avio_tell(track->mdat_buf);
3259 if (first_track < 0)
3266 for (i = 0; i < mov->nb_streams; i++) {
3267 MOVTrack *track = &mov->tracks[i];
3268 int buf_size, write_moof = 1, moof_tracks = -1;
3270 int64_t duration = 0;
3273 duration = track->start_dts + track->track_duration -
3274 track->cluster[0].dts;
3275 if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF) {
3276 if (!track->mdat_buf)
3278 mdat_size = avio_tell(track->mdat_buf);
3281 write_moof = i == first_track;
3285 MOVFragmentInfo *info;
3287 track->nb_frag_info++;
3288 if (track->nb_frag_info >= track->frag_info_capacity) {
3289 unsigned new_capacity = track->nb_frag_info + MOV_FRAG_INFO_ALLOC_INCREMENT;
3290 if (av_reallocp_array(&track->frag_info,
3292 sizeof(*track->frag_info)))
3293 return AVERROR(ENOMEM);
3294 track->frag_info_capacity = new_capacity;
3296 info = &track->frag_info[track->nb_frag_info - 1];
3297 info->offset = avio_tell(s->pb);
3298 info->time = mov->tracks[i].frag_start;
3299 info->duration = duration;
3300 mov_write_tfrf_tags(s->pb, mov, track);
3302 mov_write_moof_tag(s->pb, mov, moof_tracks);
3303 info->tfrf_offset = track->tfrf_offset;
3306 avio_wb32(s->pb, mdat_size + 8);
3307 ffio_wfourcc(s->pb, "mdat");
3311 track->frag_start += duration;
3313 if (!track->mdat_buf)
3315 buf_size = avio_close_dyn_buf(track->mdat_buf, &buf);
3316 track->mdat_buf = NULL;
3318 avio_write(s->pb, buf, buf_size);
3328 int ff_mov_write_packet(AVFormatContext *s, AVPacket *pkt)
3330 MOVMuxContext *mov = s->priv_data;
3331 AVIOContext *pb = s->pb;
3332 MOVTrack *trk = &mov->tracks[pkt->stream_index];
3333 AVCodecContext *enc = trk->enc;
3334 unsigned int samples_in_chunk = 0;
3335 int size = pkt->size;
3336 uint8_t *reformatted_data = NULL;
3339 int64_t duration = pkt->dts - trk->cluster[trk->entry - 1].dts;
3340 if (duration < 0 || duration > INT_MAX) {
3341 av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" / timestamp: %"PRId64" is out of range for mov/mp4 format\n",
3345 pkt->dts = trk->cluster[trk->entry - 1].dts + 1;
3346 pkt->pts = AV_NOPTS_VALUE;
3348 if (pkt->duration < 0) {
3349 av_log(s, AV_LOG_ERROR, "Application provided duration: %d is invalid\n", pkt->duration);
3350 return AVERROR(EINVAL);
3353 if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
3355 if (mov->fragments > 0) {
3356 if (!trk->mdat_buf) {
3357 if ((ret = avio_open_dyn_buf(&trk->mdat_buf)) < 0)
3362 if (!mov->mdat_buf) {
3363 if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0)
3370 if (enc->codec_id == AV_CODEC_ID_AMR_NB) {
3371 /* We must find out how many AMR blocks there are in one packet */
3372 static uint16_t packed_size[16] =
3373 {13, 14, 16, 18, 20, 21, 27, 32, 6, 0, 0, 0, 0, 0, 0, 1};
3376 while (len < size && samples_in_chunk < 100) {
3377 len += packed_size[(pkt->data[len] >> 3) & 0x0F];
3380 if (samples_in_chunk > 1) {
3381 av_log(s, AV_LOG_ERROR, "fatal error, input is not a single packet, implement a AVParser for it\n");
3384 } else if (enc->codec_id == AV_CODEC_ID_ADPCM_MS ||
3385 enc->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) {
3386 samples_in_chunk = enc->frame_size;
3387 } else if (trk->sample_size)
3388 samples_in_chunk = size / trk->sample_size;
3390 samples_in_chunk = 1;
3392 /* copy extradata if it exists */
3393 if (trk->vos_len == 0 && enc->extradata_size > 0) {
3394 trk->vos_len = enc->extradata_size;
3395 trk->vos_data = av_malloc(trk->vos_len);
3396 memcpy(trk->vos_data, enc->extradata, trk->vos_len);
3399 if (enc->codec_id == AV_CODEC_ID_AAC && pkt->size > 2 &&
3400 (AV_RB16(pkt->data) & 0xfff0) == 0xfff0) {
3401 if (!s->streams[pkt->stream_index]->nb_frames) {
3402 av_log(s, AV_LOG_ERROR, "Malformed AAC bitstream detected: "
3403 "use audio bitstream filter 'aac_adtstoasc' to fix it "
3404 "('-bsf:a aac_adtstoasc' option with ffmpeg)\n");
3407 av_log(s, AV_LOG_WARNING, "aac bitstream error\n");
3409 if (enc->codec_id == AV_CODEC_ID_H264 && trk->vos_len > 0 && *(uint8_t *)trk->vos_data != 1) {
3410 /* from x264 or from bytestream h264 */
3411 /* nal reformating needed */
3412 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
3413 ff_avc_parse_nal_units_buf(pkt->data, &reformatted_data,
3415 avio_write(pb, reformatted_data, size);
3417 size = ff_avc_parse_nal_units(pb, pkt->data, pkt->size);
3419 } else if (enc->codec_id == AV_CODEC_ID_HEVC && trk->vos_len > 6 &&
3420 (AV_RB24(trk->vos_data) == 1 || AV_RB32(trk->vos_data) == 1)) {
3421 /* extradata is Annex B, assume the bitstream is too and convert it */
3422 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
3423 ff_hevc_annexb2mp4_buf(pkt->data, &reformatted_data, &size, 0, NULL);
3424 avio_write(pb, reformatted_data, size);
3426 size = ff_hevc_annexb2mp4(pb, pkt->data, pkt->size, 0, NULL);
3429 avio_write(pb, pkt->data, size);
3432 if ((enc->codec_id == AV_CODEC_ID_DNXHD ||
3433 enc->codec_id == AV_CODEC_ID_AC3) && !trk->vos_len) {
3434 /* copy frame to create needed atoms */
3435 trk->vos_len = size;
3436 trk->vos_data = av_malloc(size);
3438 return AVERROR(ENOMEM);
3439 memcpy(trk->vos_data, pkt->data, size);
3442 if (trk->entry >= trk->cluster_capacity) {
3443 unsigned new_capacity = 2 * (trk->entry + MOV_INDEX_CLUSTER_SIZE);
3444 if (av_reallocp_array(&trk->cluster, new_capacity,
3445 sizeof(*trk->cluster)))
3446 return AVERROR(ENOMEM);
3447 trk->cluster_capacity = new_capacity;
3450 trk->cluster[trk->entry].pos = avio_tell(pb) - size;
3451 trk->cluster[trk->entry].samples_in_chunk = samples_in_chunk;
3452 trk->cluster[trk->entry].chunkNum = 0;
3453 trk->cluster[trk->entry].size = size;
3454 trk->cluster[trk->entry].entries = samples_in_chunk;
3455 trk->cluster[trk->entry].dts = pkt->dts;
3456 if (!trk->entry && trk->start_dts != AV_NOPTS_VALUE) {
3457 /* First packet of a new fragment. We already wrote the duration
3458 * of the last packet of the previous fragment based on track_duration,
3459 * which might not exactly match our dts. Therefore adjust the dts
3460 * of this packet to be what the previous packets duration implies. */
3461 trk->cluster[trk->entry].dts = trk->start_dts + trk->track_duration;
3463 if (!trk->entry && trk->start_dts == AV_NOPTS_VALUE && !supports_edts(mov)) {
3464 trk->cluster[trk->entry].dts = trk->start_dts = 0;
3466 if (trk->start_dts == AV_NOPTS_VALUE)
3467 trk->start_dts = pkt->dts;
3468 trk->track_duration = pkt->dts - trk->start_dts + pkt->duration;
3469 trk->last_sample_is_subtitle_end = 0;
3471 if (pkt->pts == AV_NOPTS_VALUE) {
3472 av_log(s, AV_LOG_WARNING, "pts has no value\n");
3473 pkt->pts = pkt->dts;
3475 if (pkt->dts != pkt->pts)
3476 trk->flags |= MOV_TRACK_CTTS;
3477 trk->cluster[trk->entry].cts = pkt->pts - pkt->dts;
3478 trk->cluster[trk->entry].flags = 0;
3479 if (enc->codec_id == AV_CODEC_ID_VC1) {
3480 mov_parse_vc1_frame(pkt, trk, mov->fragments);
3481 } else if (pkt->flags & AV_PKT_FLAG_KEY) {
3482 if (mov->mode == MODE_MOV && enc->codec_id == AV_CODEC_ID_MPEG2VIDEO &&
3483 trk->entry > 0) { // force sync sample for the first key frame
3484 mov_parse_mpeg2_frame(pkt, &trk->cluster[trk->entry].flags);
3485 if (trk->cluster[trk->entry].flags & MOV_PARTIAL_SYNC_SAMPLE)
3486 trk->flags |= MOV_TRACK_STPS;
3488 trk->cluster[trk->entry].flags = MOV_SYNC_SAMPLE;
3490 if (trk->cluster[trk->entry].flags & MOV_SYNC_SAMPLE)
3491 trk->has_keyframes++;
3494 trk->sample_count += samples_in_chunk;
3495 mov->mdat_size += size;
3497 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams)
3498 ff_mov_add_hinted_packet(s, pkt, trk->hint_track, trk->entry,
3499 reformatted_data, size);
3500 av_free(reformatted_data);
3504 static int mov_write_single_packet(AVFormatContext *s, AVPacket *pkt)
3506 MOVMuxContext *mov = s->priv_data;
3507 MOVTrack *trk = &mov->tracks[pkt->stream_index];
3508 AVCodecContext *enc = trk->enc;
3509 int64_t frag_duration = 0;
3510 int size = pkt->size;
3513 return 0; /* Discard 0 sized packets */
3515 if (trk->entry && pkt->stream_index < s->nb_streams)
3516 frag_duration = av_rescale_q(pkt->dts - trk->cluster[0].dts,
3517 s->streams[pkt->stream_index]->time_base,
3519 if ((mov->max_fragment_duration &&
3520 frag_duration >= mov->max_fragment_duration) ||
3521 (mov->max_fragment_size && mov->mdat_size + size >= mov->max_fragment_size) ||
3522 (mov->flags & FF_MOV_FLAG_FRAG_KEYFRAME &&
3523 enc->codec_type == AVMEDIA_TYPE_VIDEO &&
3524 trk->entry && pkt->flags & AV_PKT_FLAG_KEY)) {
3525 if (frag_duration >= mov->min_fragment_duration)
3526 mov_flush_fragment(s);
3529 return ff_mov_write_packet(s, pkt);
3532 static int mov_write_subtitle_end_packet(AVFormatContext *s,
3536 uint8_t data[2] = {0};
3539 av_init_packet(&end);
3540 end.size = sizeof(data);
3545 end.stream_index = stream_index;
3547 ret = mov_write_single_packet(s, &end);
3548 av_free_packet(&end);
3553 static int mov_write_packet(AVFormatContext *s, AVPacket *pkt)
3556 mov_flush_fragment(s);
3560 MOVMuxContext *mov = s->priv_data;
3562 if (!pkt->size) return 0; /* Discard 0 sized packets */
3565 * Subtitles require special handling.
3567 * 1) For full complaince, every track must have a sample at
3568 * dts == 0, which is rarely true for subtitles. So, as soon
3569 * as we see any packet with dts > 0, write an empty subtitle
3570 * at dts == 0 for any subtitle track with no samples in it.
3572 * 2) For each subtitle track, check if the current packet's
3573 * dts is past the duration of the last subtitle sample. If
3574 * so, we now need to write an end sample for that subtitle.
3576 * This must be done conditionally to allow for subtitles that
3577 * immediately replace each other, in which case an end sample
3578 * is not needed, and is, in fact, actively harmful.
3580 * 3) See mov_write_trailer for how the final end sample is
3583 for (i = 0; i < mov->nb_streams; i++) {
3584 MOVTrack *trk = &mov->tracks[i];
3587 if (trk->enc->codec_id == AV_CODEC_ID_MOV_TEXT &&
3588 trk->track_duration < pkt->dts &&
3589 (trk->entry == 0 || !trk->last_sample_is_subtitle_end)) {
3590 ret = mov_write_subtitle_end_packet(s, i, trk->track_duration);
3591 if (ret < 0) return ret;
3592 trk->last_sample_is_subtitle_end = 1;
3596 return mov_write_single_packet(s, pkt);
3600 // QuickTime chapters involve an additional text track with the chapter names
3601 // as samples, and a tref pointing from the other tracks to the chapter one.
3602 static int mov_create_chapter_track(AVFormatContext *s, int tracknum)
3606 MOVMuxContext *mov = s->priv_data;
3607 MOVTrack *track = &mov->tracks[tracknum];
3608 AVPacket pkt = { .stream_index = tracknum, .flags = AV_PKT_FLAG_KEY };
3611 track->mode = mov->mode;
3612 track->tag = MKTAG('t','e','x','t');
3613 track->timescale = MOV_TIMESCALE;
3614 track->enc = avcodec_alloc_context3(NULL);
3616 return AVERROR(ENOMEM);
3617 track->enc->codec_type = AVMEDIA_TYPE_SUBTITLE;
3619 // These properties are required to make QT recognize the chapter track
3620 uint8_t chapter_properties[43] = { 0, 0, 0, 0, 0, 0, 0, 1, };
3621 if (ff_alloc_extradata(track->enc, sizeof(chapter_properties)))
3622 return AVERROR(ENOMEM);
3623 memcpy(track->enc->extradata, chapter_properties, sizeof(chapter_properties));
3625 if (avio_open_dyn_buf(&pb) >= 0) {
3629 /* Stub header (usually for Quicktime chapter track) */
3631 avio_wb32(pb, 0x01); // displayFlags
3632 avio_w8(pb, 0x00); // horizontal justification
3633 avio_w8(pb, 0x00); // vertical justification
3634 avio_w8(pb, 0x00); // bgColourRed
3635 avio_w8(pb, 0x00); // bgColourGreen
3636 avio_w8(pb, 0x00); // bgColourBlue
3637 avio_w8(pb, 0x00); // bgColourAlpha
3639 avio_wb16(pb, 0x00); // defTextBoxTop
3640 avio_wb16(pb, 0x00); // defTextBoxLeft
3641 avio_wb16(pb, 0x00); // defTextBoxBottom
3642 avio_wb16(pb, 0x00); // defTextBoxRight
3644 avio_wb16(pb, 0x00); // startChar
3645 avio_wb16(pb, 0x00); // endChar
3646 avio_wb16(pb, 0x01); // fontID
3647 avio_w8(pb, 0x00); // fontStyleFlags
3648 avio_w8(pb, 0x00); // fontSize
3649 avio_w8(pb, 0x00); // fgColourRed
3650 avio_w8(pb, 0x00); // fgColourGreen
3651 avio_w8(pb, 0x00); // fgColourBlue
3652 avio_w8(pb, 0x00); // fgColourAlpha
3654 avio_wb32(pb, 0x0D); // box size
3655 ffio_wfourcc(pb, "ftab"); // box atom name
3656 avio_wb16(pb, 0x01); // entry count
3658 avio_wb16(pb, 0x01); // font ID
3659 avio_w8(pb, 0x00); // font name length
3661 if ((size = avio_close_dyn_buf(pb, &buf)) > 0) {
3662 track->enc->extradata = buf;
3663 track->enc->extradata_size = size;
3670 for (i = 0; i < s->nb_chapters; i++) {
3671 AVChapter *c = s->chapters[i];
3672 AVDictionaryEntry *t;
3674 int64_t end = av_rescale_q(c->end, c->time_base, (AVRational){1,MOV_TIMESCALE});
3675 pkt.pts = pkt.dts = av_rescale_q(c->start, c->time_base, (AVRational){1,MOV_TIMESCALE});
3676 pkt.duration = end - pkt.dts;
3678 if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
3679 len = strlen(t->value);
3681 pkt.data = av_malloc(pkt.size);
3683 return AVERROR(ENOMEM);
3684 AV_WB16(pkt.data, len);
3685 memcpy(pkt.data + 2, t->value, len);
3686 ff_mov_write_packet(s, &pkt);
3687 av_freep(&pkt.data);
3694 static int mov_create_timecode_track(AVFormatContext *s, int index, int src_index, const char *tcstr)
3697 MOVMuxContext *mov = s->priv_data;
3698 MOVTrack *track = &mov->tracks[index];
3699 AVStream *src_st = s->streams[src_index];
3701 AVPacket pkt = {.stream_index = index, .flags = AV_PKT_FLAG_KEY, .size = 4};
3702 AVRational rate = find_fps(s, src_st);
3704 /* compute the frame number */
3705 ret = av_timecode_init_from_string(&tc, rate, tcstr, s);
3709 /* tmcd track based on video stream */
3710 track->mode = mov->mode;
3711 track->tag = MKTAG('t','m','c','d');
3712 track->src_track = src_index;
3713 track->timescale = mov->tracks[src_index].timescale;
3714 if (tc.flags & AV_TIMECODE_FLAG_DROPFRAME)
3715 track->timecode_flags |= MOV_TIMECODE_FLAG_DROPFRAME;
3717 /* encode context: tmcd data stream */
3718 track->enc = avcodec_alloc_context3(NULL);
3719 track->enc->codec_type = AVMEDIA_TYPE_DATA;
3720 track->enc->codec_tag = track->tag;
3721 track->enc->time_base = av_inv_q(rate);
3723 /* the tmcd track just contains one packet with the frame number */
3724 pkt.data = av_malloc(pkt.size);
3725 AV_WB32(pkt.data, tc.start);
3726 ret = ff_mov_write_packet(s, &pkt);
3732 * st->disposition controls the "enabled" flag in the tkhd tag.
3733 * QuickTime will not play a track if it is not enabled. So make sure
3734 * that one track of each type (audio, video, subtitle) is enabled.
3736 * Subtitles are special. For audio and video, setting "enabled" also
3737 * makes the track "default" (i.e. it is rendered when played). For
3738 * subtitles, an "enabled" subtitle is not rendered by default, but
3739 * if no subtitle is enabled, the subtitle menu in QuickTime will be
3742 static void enable_tracks(AVFormatContext *s)
3744 MOVMuxContext *mov = s->priv_data;
3746 uint8_t enabled[AVMEDIA_TYPE_NB];
3747 int first[AVMEDIA_TYPE_NB];
3749 for (i = 0; i < AVMEDIA_TYPE_NB; i++) {
3754 for (i = 0; i < s->nb_streams; i++) {
3755 AVStream *st = s->streams[i];
3757 if (st->codec->codec_type <= AVMEDIA_TYPE_UNKNOWN ||
3758 st->codec->codec_type >= AVMEDIA_TYPE_NB)
3761 if (first[st->codec->codec_type] < 0)
3762 first[st->codec->codec_type] = i;
3763 if (st->disposition & AV_DISPOSITION_DEFAULT) {
3764 mov->tracks[i].flags |= MOV_TRACK_ENABLED;
3765 enabled[st->codec->codec_type] = 1;
3769 for (i = 0; i < AVMEDIA_TYPE_NB; i++) {
3771 case AVMEDIA_TYPE_VIDEO:
3772 case AVMEDIA_TYPE_AUDIO:
3773 case AVMEDIA_TYPE_SUBTITLE:
3774 if (!enabled[i] && first[i] >= 0)
3775 mov->tracks[first[i]].flags |= MOV_TRACK_ENABLED;
3781 static void mov_free(AVFormatContext *s)
3783 MOVMuxContext *mov = s->priv_data;
3786 if (mov->chapter_track) {
3787 if (mov->tracks[mov->chapter_track].enc)
3788 av_freep(&mov->tracks[mov->chapter_track].enc->extradata);
3789 av_freep(&mov->tracks[mov->chapter_track].enc);
3792 for (i = 0; i < mov->nb_streams; i++) {
3793 if (mov->tracks[i].tag == MKTAG('r','t','p',' '))
3794 ff_mov_close_hinting(&mov->tracks[i]);
3795 else if (mov->tracks[i].tag == MKTAG('t','m','c','d') && mov->nb_meta_tmcd)
3796 av_freep(&mov->tracks[i].enc);
3797 av_freep(&mov->tracks[i].cluster);
3798 av_freep(&mov->tracks[i].frag_info);
3800 if (mov->tracks[i].vos_len)
3801 av_freep(&mov->tracks[i].vos_data);
3804 av_freep(&mov->tracks);
3807 static uint32_t rgb_to_yuv(uint32_t rgb)
3812 r = (rgb >> 16) & 0xFF;
3813 g = (rgb >> 8) & 0xFF;
3816 y = av_clip_uint8( 16. + 0.257 * r + 0.504 * g + 0.098 * b);
3817 cb = av_clip_uint8(128. - 0.148 * r - 0.291 * g + 0.439 * b);
3818 cr = av_clip_uint8(128. + 0.439 * r - 0.368 * g - 0.071 * b);
3820 return (y << 16) | (cr << 8) | cb;
3823 static int mov_create_dvd_sub_decoder_specific_info(MOVTrack *track,
3826 int i, width = 720, height = 480;
3827 int have_palette = 0, have_size = 0;
3828 uint32_t palette[16];
3829 char *cur = st->codec->extradata;
3831 while (cur && *cur) {
3832 if (strncmp("palette:", cur, 8) == 0) {
3834 count = sscanf(cur + 8,
3835 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
3836 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
3837 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
3838 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32"",
3839 &palette[ 0], &palette[ 1], &palette[ 2], &palette[ 3],
3840 &palette[ 4], &palette[ 5], &palette[ 6], &palette[ 7],
3841 &palette[ 8], &palette[ 9], &palette[10], &palette[11],
3842 &palette[12], &palette[13], &palette[14], &palette[15]);
3844 for (i = 0; i < count; i++) {
3845 palette[i] = rgb_to_yuv(palette[i]);
3848 } else if (!strncmp("size:", cur, 5)) {
3849 sscanf(cur + 5, "%dx%d", &width, &height);
3852 if (have_palette && have_size)
3854 cur += strcspn(cur, "\n\r");
3855 cur += strspn(cur, "\n\r");
3858 track->vos_data = av_malloc(16*4);
3859 if (!track->vos_data)
3860 return AVERROR(ENOMEM);
3861 for (i = 0; i < 16; i++) {
3862 AV_WB32(track->vos_data + i * 4, palette[i]);
3864 track->vos_len = 16 * 4;
3866 st->codec->width = width;
3867 st->codec->height = track->height = height;
3872 static int mov_write_header(AVFormatContext *s)
3874 AVIOContext *pb = s->pb;
3875 MOVMuxContext *mov = s->priv_data;
3876 AVDictionaryEntry *t, *global_tcr = av_dict_get(s->metadata, "timecode", NULL, 0);
3877 int i, ret, hint_track = 0, tmcd_track = 0;
3879 /* Default mode == MP4 */
3880 mov->mode = MODE_MP4;
3882 if (s->oformat != NULL) {
3883 if (!strcmp("3gp", s->oformat->name)) mov->mode = MODE_3GP;
3884 else if (!strcmp("3g2", s->oformat->name)) mov->mode = MODE_3GP|MODE_3G2;
3885 else if (!strcmp("mov", s->oformat->name)) mov->mode = MODE_MOV;
3886 else if (!strcmp("psp", s->oformat->name)) mov->mode = MODE_PSP;
3887 else if (!strcmp("ipod",s->oformat->name)) mov->mode = MODE_IPOD;
3888 else if (!strcmp("ismv",s->oformat->name)) mov->mode = MODE_ISM;
3889 else if (!strcmp("f4v", s->oformat->name)) mov->mode = MODE_F4V;
3892 for (i = 0; i < s->nb_streams; i++)
3893 if (s->flags & AVFMT_FLAG_BITEXACT)
3896 /* Set the FRAGMENT flag if any of the fragmentation methods are
3898 if (mov->max_fragment_duration || mov->max_fragment_size ||
3899 mov->flags & (FF_MOV_FLAG_EMPTY_MOOV |
3900 FF_MOV_FLAG_FRAG_KEYFRAME |
3901 FF_MOV_FLAG_FRAG_CUSTOM))
3902 mov->flags |= FF_MOV_FLAG_FRAGMENT;
3904 /* Set other implicit flags immediately */
3905 if (mov->mode == MODE_ISM)
3906 mov->flags |= FF_MOV_FLAG_EMPTY_MOOV | FF_MOV_FLAG_SEPARATE_MOOF |
3907 FF_MOV_FLAG_FRAGMENT;
3909 /* faststart: moov at the beginning of the file, if supported */
3910 if (mov->flags & FF_MOV_FLAG_FASTSTART) {
3911 if ((mov->flags & FF_MOV_FLAG_FRAGMENT) ||
3912 (s->flags & AVFMT_FLAG_CUSTOM_IO)) {
3913 av_log(s, AV_LOG_WARNING, "The faststart flag is incompatible "
3914 "with fragmentation and custom IO, disabling faststart\n");
3915 mov->flags &= ~FF_MOV_FLAG_FASTSTART;
3917 mov->reserved_moov_size = -1;
3920 if (!supports_edts(mov) && s->avoid_negative_ts < 0) {
3921 s->avoid_negative_ts = 2;
3924 /* Non-seekable output is ok if using fragmentation. If ism_lookahead
3925 * is enabled, we don't support non-seekable output at all. */
3926 if (!s->pb->seekable &&
3927 (!(mov->flags & FF_MOV_FLAG_FRAGMENT) || mov->ism_lookahead)) {
3928 av_log(s, AV_LOG_ERROR, "muxer does not support non seekable output\n");
3929 return AVERROR(EINVAL);
3932 mov_write_ftyp_tag(pb,s);
3933 if (mov->mode == MODE_PSP) {
3934 int video_streams_nb = 0, audio_streams_nb = 0, other_streams_nb = 0;
3935 for (i = 0; i < s->nb_streams; i++) {
3936 AVStream *st = s->streams[i];
3937 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
3939 else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
3945 if (video_streams_nb != 1 || audio_streams_nb != 1 || other_streams_nb) {
3946 av_log(s, AV_LOG_ERROR, "PSP mode need one video and one audio stream\n");
3947 return AVERROR(EINVAL);
3949 mov_write_uuidprof_tag(pb, s);
3952 mov->nb_streams = s->nb_streams;
3953 if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters)
3954 mov->chapter_track = mov->nb_streams++;
3956 if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
3957 /* Add hint tracks for each audio and video stream */
3958 hint_track = mov->nb_streams;
3959 for (i = 0; i < s->nb_streams; i++) {
3960 AVStream *st = s->streams[i];
3961 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO ||
3962 st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
3968 if (mov->mode == MODE_MOV) {
3969 tmcd_track = mov->nb_streams;
3971 /* +1 tmcd track for each video stream with a timecode */
3972 for (i = 0; i < s->nb_streams; i++) {
3973 AVStream *st = s->streams[i];
3974 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
3975 (global_tcr || av_dict_get(st->metadata, "timecode", NULL, 0)))
3976 mov->nb_meta_tmcd++;
3979 /* check if there is already a tmcd track to remux */
3980 if (mov->nb_meta_tmcd) {
3981 for (i = 0; i < s->nb_streams; i++) {
3982 AVStream *st = s->streams[i];
3983 if (st->codec->codec_tag == MKTAG('t','m','c','d')) {
3984 av_log(s, AV_LOG_WARNING, "You requested a copy of the original timecode track "
3985 "so timecode metadata are now ignored\n");
3986 mov->nb_meta_tmcd = 0;
3991 mov->nb_streams += mov->nb_meta_tmcd;
3994 // Reserve an extra stream for chapters for the case where chapters
3995 // are written in the trailer
3996 mov->tracks = av_mallocz_array((mov->nb_streams + 1), sizeof(*mov->tracks));
3998 return AVERROR(ENOMEM);
4000 for (i = 0; i < s->nb_streams; i++) {
4001 AVStream *st= s->streams[i];
4002 MOVTrack *track= &mov->tracks[i];
4003 AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0);
4006 track->enc = st->codec;
4007 track->language = ff_mov_iso639_to_lang(lang?lang->value:"und", mov->mode!=MODE_MOV);
4008 if (track->language < 0)
4009 track->language = 0;
4010 track->mode = mov->mode;
4011 track->tag = mov_find_codec_tag(s, track);
4013 av_log(s, AV_LOG_ERROR, "Could not find tag for codec %s in stream #%d, "
4014 "codec not currently supported in container\n",
4015 avcodec_get_name(st->codec->codec_id), i);
4016 ret = AVERROR(EINVAL);
4019 /* If hinting of this track is enabled by a later hint track,
4020 * this is updated. */
4021 track->hint_track = -1;
4022 track->start_dts = AV_NOPTS_VALUE;
4023 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
4024 if (track->tag == MKTAG('m','x','3','p') || track->tag == MKTAG('m','x','3','n') ||
4025 track->tag == MKTAG('m','x','4','p') || track->tag == MKTAG('m','x','4','n') ||
4026 track->tag == MKTAG('m','x','5','p') || track->tag == MKTAG('m','x','5','n')) {
4027 if (st->codec->width != 720 || (st->codec->height != 608 && st->codec->height != 512)) {
4028 av_log(s, AV_LOG_ERROR, "D-10/IMX must use 720x608 or 720x512 video resolution\n");
4029 ret = AVERROR(EINVAL);
4032 track->height = track->tag >> 24 == 'n' ? 486 : 576;
4034 if (mov->video_track_timescale) {
4035 track->timescale = mov->video_track_timescale;
4037 track->timescale = st->time_base.den;
4038 while(track->timescale < 10000)
4039 track->timescale *= 2;
4041 if (st->codec->width > 65535 || st->codec->height > 65535) {
4042 av_log(s, AV_LOG_ERROR, "Resolution %dx%d too large for mov/mp4\n", st->codec->width, st->codec->height);
4043 ret = AVERROR(EINVAL);
4046 if (track->mode == MODE_MOV && track->timescale > 100000)
4047 av_log(s, AV_LOG_WARNING,
4048 "WARNING codec timebase is very high. If duration is too long,\n"
4049 "file may not be playable by quicktime. Specify a shorter timebase\n"
4050 "or choose different container.\n");
4051 } else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
4052 track->timescale = st->codec->sample_rate;
4053 if (!st->codec->frame_size && !av_get_bits_per_sample(st->codec->codec_id)) {
4054 av_log(s, AV_LOG_WARNING, "track %d: codec frame size is not set\n", i);
4055 track->audio_vbr = 1;
4056 }else if (st->codec->codec_id == AV_CODEC_ID_ADPCM_MS ||
4057 st->codec->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
4058 st->codec->codec_id == AV_CODEC_ID_ILBC){
4059 if (!st->codec->block_align) {
4060 av_log(s, AV_LOG_ERROR, "track %d: codec block align is not set for adpcm\n", i);
4061 ret = AVERROR(EINVAL);
4064 track->sample_size = st->codec->block_align;
4065 }else if (st->codec->frame_size > 1){ /* assume compressed audio */
4066 track->audio_vbr = 1;
4068 track->sample_size = (av_get_bits_per_sample(st->codec->codec_id) >> 3) * st->codec->channels;
4070 if (st->codec->codec_id == AV_CODEC_ID_ILBC ||
4071 st->codec->codec_id == AV_CODEC_ID_ADPCM_IMA_QT) {
4072 track->audio_vbr = 1;
4074 if (track->mode != MODE_MOV &&
4075 track->enc->codec_id == AV_CODEC_ID_MP3 && track->timescale < 16000) {
4076 av_log(s, AV_LOG_ERROR, "track %d: muxing mp3 at %dhz is not supported\n",
4077 i, track->enc->sample_rate);
4078 ret = AVERROR(EINVAL);
4081 } else if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
4082 track->timescale = st->time_base.den;
4083 } else if (st->codec->codec_type == AVMEDIA_TYPE_DATA) {
4084 track->timescale = st->time_base.den;
4086 track->timescale = MOV_TIMESCALE;
4089 track->height = st->codec->height;
4090 /* The ism specific timescale isn't mandatory, but is assumed by
4091 * some tools, such as mp4split. */
4092 if (mov->mode == MODE_ISM)
4093 track->timescale = 10000000;
4095 avpriv_set_pts_info(st, 64, 1, track->timescale);
4097 /* copy extradata if it exists */
4098 if (st->codec->extradata_size) {
4099 if (st->codec->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
4100 mov_create_dvd_sub_decoder_specific_info(track, st);
4102 track->vos_len = st->codec->extradata_size;
4103 track->vos_data = av_malloc(track->vos_len);
4104 memcpy(track->vos_data, st->codec->extradata, track->vos_len);
4112 if (mov->reserved_moov_size){
4113 mov->reserved_moov_pos= avio_tell(pb);
4114 if (mov->reserved_moov_size > 0)
4115 avio_skip(pb, mov->reserved_moov_size);
4118 if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
4119 /* If no fragmentation options have been set, set a default. */
4120 if (!(mov->flags & (FF_MOV_FLAG_FRAG_KEYFRAME |
4121 FF_MOV_FLAG_FRAG_CUSTOM)) &&
4122 !mov->max_fragment_duration && !mov->max_fragment_size)
4123 mov->flags |= FF_MOV_FLAG_FRAG_KEYFRAME;
4125 if (mov->flags & FF_MOV_FLAG_FASTSTART)
4126 mov->reserved_moov_pos = avio_tell(pb);
4127 mov_write_mdat_tag(pb, mov);
4130 if (t = av_dict_get(s->metadata, "creation_time", NULL, 0))
4131 mov->time = ff_iso8601_to_unix_time(t->value);
4133 mov->time += 0x7C25B080; // 1970 based -> 1904 based
4135 if (mov->chapter_track)
4136 if ((ret = mov_create_chapter_track(s, mov->chapter_track)) < 0)
4139 if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
4140 /* Initialize the hint tracks for each audio and video stream */
4141 for (i = 0; i < s->nb_streams; i++) {
4142 AVStream *st = s->streams[i];
4143 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO ||
4144 st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
4145 if ((ret = ff_mov_init_hinting(s, hint_track, i)) < 0)
4152 if (mov->nb_meta_tmcd) {
4153 /* Initialize the tmcd tracks */
4154 for (i = 0; i < s->nb_streams; i++) {
4155 AVStream *st = s->streams[i];
4158 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
4160 t = av_dict_get(st->metadata, "timecode", NULL, 0);
4163 if ((ret = mov_create_timecode_track(s, tmcd_track, i, t->value)) < 0)
4172 if (mov->flags & FF_MOV_FLAG_ISML)
4173 mov_write_isml_manifest(pb, mov);
4175 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
4176 mov_write_moov_tag(pb, mov, s);
4186 static int get_moov_size(AVFormatContext *s)
4189 AVIOContext *moov_buf;
4190 MOVMuxContext *mov = s->priv_data;
4192 if ((ret = ffio_open_null_buf(&moov_buf)) < 0)
4194 mov_write_moov_tag(moov_buf, mov, s);
4195 return ffio_close_null_buf(moov_buf);
4199 * This function gets the moov size if moved to the top of the file: the chunk
4200 * offset table can switch between stco (32-bit entries) to co64 (64-bit
4201 * entries) when the moov is moved to the beginning, so the size of the moov
4202 * would change. It also updates the chunk offset tables.
4204 static int compute_moov_size(AVFormatContext *s)
4206 int i, moov_size, moov_size2;
4207 MOVMuxContext *mov = s->priv_data;
4209 moov_size = get_moov_size(s);
4213 for (i = 0; i < mov->nb_streams; i++)
4214 mov->tracks[i].data_offset += moov_size;
4216 moov_size2 = get_moov_size(s);
4220 /* if the size changed, we just switched from stco to co64 and need to
4221 * update the offsets */
4222 if (moov_size2 != moov_size)
4223 for (i = 0; i < mov->nb_streams; i++)
4224 mov->tracks[i].data_offset += moov_size2 - moov_size;
4229 static int shift_data(AVFormatContext *s)
4231 int ret = 0, moov_size;
4232 MOVMuxContext *mov = s->priv_data;
4233 int64_t pos, pos_end = avio_tell(s->pb);
4234 uint8_t *buf, *read_buf[2];
4235 int read_buf_id = 0;
4237 AVIOContext *read_pb;
4239 moov_size = compute_moov_size(s);
4243 buf = av_malloc(moov_size * 2);
4245 return AVERROR(ENOMEM);
4247 read_buf[1] = buf + moov_size;
4249 /* Shift the data: the AVIO context of the output can only be used for
4250 * writing, so we re-open the same output, but for reading. It also avoids
4251 * a read/seek/write/seek back and forth. */
4253 ret = avio_open(&read_pb, s->filename, AVIO_FLAG_READ);
4255 av_log(s, AV_LOG_ERROR, "Unable to re-open %s output file for "
4256 "the second pass (faststart)\n", s->filename);
4260 /* mark the end of the shift to up to the last data we wrote, and get ready
4262 pos_end = avio_tell(s->pb);
4263 avio_seek(s->pb, mov->reserved_moov_pos + moov_size, SEEK_SET);
4265 /* start reading at where the new moov will be placed */
4266 avio_seek(read_pb, mov->reserved_moov_pos, SEEK_SET);
4267 pos = avio_tell(read_pb);
4269 #define READ_BLOCK do { \
4270 read_size[read_buf_id] = avio_read(read_pb, read_buf[read_buf_id], moov_size); \
4274 /* shift data by chunk of at most moov_size */
4279 n = read_size[read_buf_id];
4282 avio_write(s->pb, read_buf[read_buf_id], n);
4284 } while (pos < pos_end);
4285 avio_close(read_pb);
4292 static int mov_write_trailer(AVFormatContext *s)
4294 MOVMuxContext *mov = s->priv_data;
4295 AVIOContext *pb = s->pb;
4301 * Before actually writing the trailer, make sure that there are no
4302 * dangling subtitles, that need a terminating sample.
4304 for (i = 0; i < mov->nb_streams; i++) {
4305 MOVTrack *trk = &mov->tracks[i];
4306 if (trk->enc->codec_id == AV_CODEC_ID_MOV_TEXT &&
4307 !trk->last_sample_is_subtitle_end) {
4308 mov_write_subtitle_end_packet(s, i, trk->track_duration);
4309 trk->last_sample_is_subtitle_end = 1;
4313 // If there were no chapters when the header was written, but there
4314 // are chapters now, write them in the trailer. This only works
4315 // when we are not doing fragments.
4316 if (!mov->chapter_track && !(mov->flags & FF_MOV_FLAG_FRAGMENT)) {
4317 if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters) {
4318 mov->chapter_track = mov->nb_streams++;
4319 if ((res = mov_create_chapter_track(s, mov->chapter_track)) < 0)
4324 if (!(mov->flags & FF_MOV_FLAG_FRAGMENT)) {
4325 moov_pos = avio_tell(pb);
4327 /* Write size of mdat tag */
4328 if (mov->mdat_size + 8 <= UINT32_MAX) {
4329 avio_seek(pb, mov->mdat_pos, SEEK_SET);
4330 avio_wb32(pb, mov->mdat_size + 8);
4332 /* overwrite 'wide' placeholder atom */
4333 avio_seek(pb, mov->mdat_pos - 8, SEEK_SET);
4334 /* special value: real atom size will be 64 bit value after
4337 ffio_wfourcc(pb, "mdat");
4338 avio_wb64(pb, mov->mdat_size + 16);
4340 avio_seek(pb, mov->reserved_moov_size > 0 ? mov->reserved_moov_pos : moov_pos, SEEK_SET);
4342 if (mov->flags & FF_MOV_FLAG_FASTSTART) {
4343 av_log(s, AV_LOG_INFO, "Starting second pass: moving the moov atom to the beginning of the file\n");
4344 res = shift_data(s);
4346 avio_seek(s->pb, mov->reserved_moov_pos, SEEK_SET);
4347 mov_write_moov_tag(pb, mov, s);
4349 } else if (mov->reserved_moov_size > 0) {
4351 mov_write_moov_tag(pb, mov, s);
4352 size = mov->reserved_moov_size - (avio_tell(pb) - mov->reserved_moov_pos);
4354 av_log(s, AV_LOG_ERROR, "reserved_moov_size is too small, needed %"PRId64" additional\n", 8-size);
4357 avio_wb32(pb, size);
4358 ffio_wfourcc(pb, "free");
4359 for (i = 0; i < size; i++)
4361 avio_seek(pb, moov_pos, SEEK_SET);
4363 mov_write_moov_tag(pb, mov, s);
4366 mov_flush_fragment(s);
4367 mov_write_mfra_tag(pb, mov);
4370 for (i = 0; i < mov->nb_streams; i++) {
4371 if (mov->flags & FF_MOV_FLAG_FRAGMENT &&
4372 mov->tracks[i].vc1_info.struct_offset && s->pb->seekable) {
4373 int64_t off = avio_tell(pb);
4375 if (mov_write_dvc1_structs(&mov->tracks[i], buf) >= 0) {
4376 avio_seek(pb, mov->tracks[i].vc1_info.struct_offset, SEEK_SET);
4377 avio_write(pb, buf, 7);
4378 avio_seek(pb, off, SEEK_SET);
4389 #if CONFIG_MOV_MUXER
4391 AVOutputFormat ff_mov_muxer = {
4393 .long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
4394 .extensions = "mov",
4395 .priv_data_size = sizeof(MOVMuxContext),
4396 .audio_codec = AV_CODEC_ID_AAC,
4397 .video_codec = CONFIG_LIBX264_ENCODER ?
4398 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
4399 .write_header = mov_write_header,
4400 .write_packet = mov_write_packet,
4401 .write_trailer = mov_write_trailer,
4402 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
4403 .codec_tag = (const AVCodecTag* const []){
4404 ff_codec_movvideo_tags, ff_codec_movaudio_tags, 0
4406 .priv_class = &mov_muxer_class,
4409 #if CONFIG_TGP_MUXER
4411 AVOutputFormat ff_tgp_muxer = {
4413 .long_name = NULL_IF_CONFIG_SMALL("3GP (3GPP file format)"),
4414 .extensions = "3gp",
4415 .priv_data_size = sizeof(MOVMuxContext),
4416 .audio_codec = AV_CODEC_ID_AMR_NB,
4417 .video_codec = AV_CODEC_ID_H263,
4418 .write_header = mov_write_header,
4419 .write_packet = mov_write_packet,
4420 .write_trailer = mov_write_trailer,
4421 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
4422 .codec_tag = (const AVCodecTag* const []){ codec_3gp_tags, 0 },
4423 .priv_class = &tgp_muxer_class,
4426 #if CONFIG_MP4_MUXER
4428 AVOutputFormat ff_mp4_muxer = {
4430 .long_name = NULL_IF_CONFIG_SMALL("MP4 (MPEG-4 Part 14)"),
4431 .mime_type = "application/mp4",
4432 .extensions = "mp4",
4433 .priv_data_size = sizeof(MOVMuxContext),
4434 .audio_codec = AV_CODEC_ID_AAC,
4435 .video_codec = CONFIG_LIBX264_ENCODER ?
4436 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
4437 .write_header = mov_write_header,
4438 .write_packet = mov_write_packet,
4439 .write_trailer = mov_write_trailer,
4440 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
4441 .codec_tag = (const AVCodecTag* const []){ ff_mp4_obj_type, 0 },
4442 .priv_class = &mp4_muxer_class,
4445 #if CONFIG_PSP_MUXER
4447 AVOutputFormat ff_psp_muxer = {
4449 .long_name = NULL_IF_CONFIG_SMALL("PSP MP4 (MPEG-4 Part 14)"),
4450 .extensions = "mp4,psp",
4451 .priv_data_size = sizeof(MOVMuxContext),
4452 .audio_codec = AV_CODEC_ID_AAC,
4453 .video_codec = CONFIG_LIBX264_ENCODER ?
4454 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
4455 .write_header = mov_write_header,
4456 .write_packet = mov_write_packet,
4457 .write_trailer = mov_write_trailer,
4458 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
4459 .codec_tag = (const AVCodecTag* const []){ ff_mp4_obj_type, 0 },
4460 .priv_class = &psp_muxer_class,
4463 #if CONFIG_TG2_MUXER
4465 AVOutputFormat ff_tg2_muxer = {
4467 .long_name = NULL_IF_CONFIG_SMALL("3GP2 (3GPP2 file format)"),
4468 .extensions = "3g2",
4469 .priv_data_size = sizeof(MOVMuxContext),
4470 .audio_codec = AV_CODEC_ID_AMR_NB,
4471 .video_codec = AV_CODEC_ID_H263,
4472 .write_header = mov_write_header,
4473 .write_packet = mov_write_packet,
4474 .write_trailer = mov_write_trailer,
4475 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
4476 .codec_tag = (const AVCodecTag* const []){ codec_3gp_tags, 0 },
4477 .priv_class = &tg2_muxer_class,
4480 #if CONFIG_IPOD_MUXER
4482 AVOutputFormat ff_ipod_muxer = {
4484 .long_name = NULL_IF_CONFIG_SMALL("iPod H.264 MP4 (MPEG-4 Part 14)"),
4485 .mime_type = "application/mp4",
4486 .extensions = "m4v,m4a",
4487 .priv_data_size = sizeof(MOVMuxContext),
4488 .audio_codec = AV_CODEC_ID_AAC,
4489 .video_codec = AV_CODEC_ID_H264,
4490 .write_header = mov_write_header,
4491 .write_packet = mov_write_packet,
4492 .write_trailer = mov_write_trailer,
4493 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
4494 .codec_tag = (const AVCodecTag* const []){ codec_ipod_tags, 0 },
4495 .priv_class = &ipod_muxer_class,
4498 #if CONFIG_ISMV_MUXER
4500 AVOutputFormat ff_ismv_muxer = {
4502 .long_name = NULL_IF_CONFIG_SMALL("ISMV/ISMA (Smooth Streaming)"),
4503 .mime_type = "application/mp4",
4504 .extensions = "ismv,isma",
4505 .priv_data_size = sizeof(MOVMuxContext),
4506 .audio_codec = AV_CODEC_ID_AAC,
4507 .video_codec = AV_CODEC_ID_H264,
4508 .write_header = mov_write_header,
4509 .write_packet = mov_write_packet,
4510 .write_trailer = mov_write_trailer,
4511 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
4512 .codec_tag = (const AVCodecTag* const []){ ff_mp4_obj_type, 0 },
4513 .priv_class = &ismv_muxer_class,
4516 #if CONFIG_F4V_MUXER
4518 AVOutputFormat ff_f4v_muxer = {
4520 .long_name = NULL_IF_CONFIG_SMALL("F4V Adobe Flash Video"),
4521 .mime_type = "application/f4v",
4522 .extensions = "f4v",
4523 .priv_data_size = sizeof(MOVMuxContext),
4524 .audio_codec = AV_CODEC_ID_AAC,
4525 .video_codec = AV_CODEC_ID_H264,
4526 .write_header = mov_write_header,
4527 .write_packet = mov_write_packet,
4528 .write_trailer = mov_write_trailer,
4529 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH,
4530 .codec_tag = (const AVCodecTag* const []){ codec_f4v_tags, 0 },
4531 .priv_class = &f4v_muxer_class,