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/ac3_parser.h"
35 #include "libavcodec/get_bits.h"
36 #include "libavcodec/put_bits.h"
37 #include "libavcodec/vc1_common.h"
38 #include "libavcodec/raw.h"
40 #include "libavutil/avstring.h"
41 #include "libavutil/intfloat.h"
42 #include "libavutil/mathematics.h"
43 #include "libavutil/opt.h"
44 #include "libavutil/dict.h"
45 #include "libavutil/pixdesc.h"
46 #include "libavutil/timecode.h"
54 static const AVOption options[] = {
55 { "movflags", "MOV muxer flags", offsetof(MOVMuxContext, flags), AV_OPT_TYPE_FLAGS, {.i64 = 0}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
56 { "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" },
57 { "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 },
58 { "empty_moov", "Make the initial moov atom empty", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_EMPTY_MOOV}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
59 { "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" },
60 { "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" },
61 { "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" },
62 { "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" },
63 { "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" },
64 { "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" },
65 { "disable_chpl", "Disable Nero chapter atom", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_DISABLE_CHPL}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
66 { "default_base_moof", "Set the default-base-is-moof flag in tfhd atoms", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_DEFAULT_BASE_MOOF}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
67 { "dash", "Write DASH compatible fragmented MP4", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_DASH}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
68 { "frag_discont", "Signal that the next fragment is discontinuous from earlier ones", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FRAG_DISCONT}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
69 FF_RTP_FLAG_OPTS(MOVMuxContext, rtp_flags),
70 { "skip_iods", "Skip writing iods atom.", offsetof(MOVMuxContext, iods_skip), AV_OPT_TYPE_INT, {.i64 = 1}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM},
71 { "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},
72 { "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},
73 { "frag_duration", "Maximum fragment duration", offsetof(MOVMuxContext, max_fragment_duration), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
74 { "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},
75 { "frag_size", "Maximum fragment size", offsetof(MOVMuxContext, max_fragment_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
76 { "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},
77 { "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},
78 { "brand", "Override major brand", offsetof(MOVMuxContext, major_brand), AV_OPT_TYPE_STRING, {.str = NULL}, .flags = AV_OPT_FLAG_ENCODING_PARAM },
79 { "use_editlist", "use edit list", offsetof(MOVMuxContext, use_editlist), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 1, AV_OPT_FLAG_ENCODING_PARAM},
80 { "fragment_index", "Fragment number of the next fragment", offsetof(MOVMuxContext, fragments), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
84 #define MOV_CLASS(flavor)\
85 static const AVClass flavor ## _muxer_class = {\
86 .class_name = #flavor " muxer",\
87 .item_name = av_default_item_name,\
89 .version = LIBAVUTIL_VERSION_INT,\
92 static int get_moov_size(AVFormatContext *s);
94 static int utf8len(const uint8_t *b)
99 GET_UTF8(val, *b++, return -1;)
105 //FIXME support 64 bit variant with wide placeholders
106 static int64_t update_size(AVIOContext *pb, int64_t pos)
108 int64_t curpos = avio_tell(pb);
109 avio_seek(pb, pos, SEEK_SET);
110 avio_wb32(pb, curpos - pos); /* rewrite size */
111 avio_seek(pb, curpos, SEEK_SET);
116 static int co64_required(const MOVTrack *track)
118 if (track->entry > 0 && track->cluster[track->entry - 1].pos + track->data_offset > UINT32_MAX)
123 /* Chunk offset atom */
124 static int mov_write_stco_tag(AVIOContext *pb, MOVTrack *track)
127 int mode64 = co64_required(track); // use 32 bit size variant if possible
128 int64_t pos = avio_tell(pb);
129 avio_wb32(pb, 0); /* size */
131 ffio_wfourcc(pb, "co64");
133 ffio_wfourcc(pb, "stco");
134 avio_wb32(pb, 0); /* version & flags */
135 avio_wb32(pb, track->chunkCount); /* entry count */
136 for (i = 0; i < track->entry; i++) {
137 if (!track->cluster[i].chunkNum)
140 avio_wb64(pb, track->cluster[i].pos + track->data_offset);
142 avio_wb32(pb, track->cluster[i].pos + track->data_offset);
144 return update_size(pb, pos);
147 /* Sample size atom */
148 static int mov_write_stsz_tag(AVIOContext *pb, MOVTrack *track)
151 int i, j, entries = 0, tst = -1, oldtst = -1;
153 int64_t pos = avio_tell(pb);
154 avio_wb32(pb, 0); /* size */
155 ffio_wfourcc(pb, "stsz");
156 avio_wb32(pb, 0); /* version & flags */
158 for (i = 0; i < track->entry; i++) {
159 tst = track->cluster[i].size / track->cluster[i].entries;
160 if (oldtst != -1 && tst != oldtst)
163 entries += track->cluster[i].entries;
165 if (equalChunks && track->entry) {
166 int sSize = track->entry ? track->cluster[0].size / track->cluster[0].entries : 0;
167 sSize = FFMAX(1, sSize); // adpcm mono case could make sSize == 0
168 avio_wb32(pb, sSize); // sample size
169 avio_wb32(pb, entries); // sample count
171 avio_wb32(pb, 0); // sample size
172 avio_wb32(pb, entries); // sample count
173 for (i = 0; i < track->entry; i++) {
174 for (j = 0; j < track->cluster[i].entries; j++) {
175 avio_wb32(pb, track->cluster[i].size /
176 track->cluster[i].entries);
180 return update_size(pb, pos);
183 /* Sample to chunk atom */
184 static int mov_write_stsc_tag(AVIOContext *pb, MOVTrack *track)
186 int index = 0, oldval = -1, i;
187 int64_t entryPos, curpos;
189 int64_t pos = avio_tell(pb);
190 avio_wb32(pb, 0); /* size */
191 ffio_wfourcc(pb, "stsc");
192 avio_wb32(pb, 0); // version & flags
193 entryPos = avio_tell(pb);
194 avio_wb32(pb, track->chunkCount); // entry count
195 for (i = 0; i < track->entry; i++) {
196 if (oldval != track->cluster[i].samples_in_chunk && track->cluster[i].chunkNum) {
197 avio_wb32(pb, track->cluster[i].chunkNum); // first chunk
198 avio_wb32(pb, track->cluster[i].samples_in_chunk); // samples per chunk
199 avio_wb32(pb, 0x1); // sample description index
200 oldval = track->cluster[i].samples_in_chunk;
204 curpos = avio_tell(pb);
205 avio_seek(pb, entryPos, SEEK_SET);
206 avio_wb32(pb, index); // rewrite size
207 avio_seek(pb, curpos, SEEK_SET);
209 return update_size(pb, pos);
212 /* Sync sample atom */
213 static int mov_write_stss_tag(AVIOContext *pb, MOVTrack *track, uint32_t flag)
215 int64_t curpos, entryPos;
217 int64_t pos = avio_tell(pb);
218 avio_wb32(pb, 0); // size
219 ffio_wfourcc(pb, flag == MOV_SYNC_SAMPLE ? "stss" : "stps");
220 avio_wb32(pb, 0); // version & flags
221 entryPos = avio_tell(pb);
222 avio_wb32(pb, track->entry); // entry count
223 for (i = 0; i < track->entry; i++) {
224 if (track->cluster[i].flags & flag) {
225 avio_wb32(pb, i + 1);
229 curpos = avio_tell(pb);
230 avio_seek(pb, entryPos, SEEK_SET);
231 avio_wb32(pb, index); // rewrite size
232 avio_seek(pb, curpos, SEEK_SET);
233 return update_size(pb, pos);
236 static int mov_write_amr_tag(AVIOContext *pb, MOVTrack *track)
238 avio_wb32(pb, 0x11); /* size */
239 if (track->mode == MODE_MOV) ffio_wfourcc(pb, "samr");
240 else ffio_wfourcc(pb, "damr");
241 ffio_wfourcc(pb, "FFMP");
242 avio_w8(pb, 0); /* decoder version */
244 avio_wb16(pb, 0x81FF); /* Mode set (all modes for AMR_NB) */
245 avio_w8(pb, 0x00); /* Mode change period (no restriction) */
246 avio_w8(pb, 0x01); /* Frames per sample */
250 static int mov_write_ac3_tag(AVIOContext *pb, MOVTrack *track)
255 int fscod, bsid, bsmod, acmod, lfeon, frmsizecod;
257 if (track->vos_len < 7)
261 ffio_wfourcc(pb, "dac3");
263 init_get_bits(&gbc, track->vos_data + 4, (track->vos_len - 4) * 8);
264 fscod = get_bits(&gbc, 2);
265 frmsizecod = get_bits(&gbc, 6);
266 bsid = get_bits(&gbc, 5);
267 bsmod = get_bits(&gbc, 3);
268 acmod = get_bits(&gbc, 3);
270 skip_bits(&gbc, 2); // dsurmod
272 if ((acmod & 1) && acmod != 1)
273 skip_bits(&gbc, 2); // cmixlev
275 skip_bits(&gbc, 2); // surmixlev
277 lfeon = get_bits1(&gbc);
279 init_put_bits(&pbc, buf, sizeof(buf));
280 put_bits(&pbc, 2, fscod);
281 put_bits(&pbc, 5, bsid);
282 put_bits(&pbc, 3, bsmod);
283 put_bits(&pbc, 3, acmod);
284 put_bits(&pbc, 1, lfeon);
285 put_bits(&pbc, 5, frmsizecod >> 1); // bit_rate_code
286 put_bits(&pbc, 5, 0); // reserved
288 flush_put_bits(&pbc);
289 avio_write(pb, buf, sizeof(buf));
299 /* Layout of the EC3SpecificBox */
300 /* maximum bitrate */
302 /* number of independent substreams */
305 /* sample rate code (see ff_ac3_sample_rate_tab) 2 bits */
307 /* bit stream identification 5 bits */
309 /* one bit reserved */
310 /* audio service mixing (not supported yet) 1 bit */
311 /* bit stream mode 3 bits */
313 /* audio coding mode 3 bits */
315 /* sub woofer on 1 bit */
317 /* 3 bits reserved */
318 /* number of dependent substreams associated with this substream 4 bits */
320 /* channel locations of the dependent substream(s), if any, 9 bits */
322 /* if there is no dependent substream, then one bit reserved instead */
323 } substream[1]; /* TODO: support 8 independent substreams */
326 static int handle_eac3(MOVMuxContext *mov, AVPacket *pkt, MOVTrack *track)
329 AC3HeaderInfo tmp, *hdr = &tmp;
330 struct eac3_info *info;
333 if (!track->eac3_priv && !(track->eac3_priv = av_mallocz(sizeof(*info))))
334 return AVERROR(ENOMEM);
335 info = track->eac3_priv;
337 init_get_bits(&gbc, pkt->data, pkt->size * 8);
338 if (avpriv_ac3_parse_header2(&gbc, &hdr) < 0) {
339 /* drop the packets until we see a good one */
341 av_log(mov, AV_LOG_WARNING, "Dropping invalid packet from start of the stream\n");
344 return AVERROR_INVALIDDATA;
347 info->data_rate = FFMAX(info->data_rate, hdr->bit_rate / 1000);
348 num_blocks = hdr->num_blocks;
350 if (!info->ec3_done) {
351 /* AC-3 substream must be the first one */
352 if (hdr->bitstream_id <= 10 && hdr->substreamid != 0)
353 return AVERROR(EINVAL);
355 /* this should always be the case, given that our AC-3 parser
356 * concatenates dependent frames to their independent parent */
357 if (hdr->frame_type == EAC3_FRAME_TYPE_INDEPENDENT) {
358 /* substream ids must be incremental */
359 if (hdr->substreamid > info->num_ind_sub + 1)
360 return AVERROR(EINVAL);
362 if (hdr->substreamid == info->num_ind_sub + 1) {
363 //info->num_ind_sub++;
364 avpriv_request_sample(track->enc, "Multiple independent substreams");
365 return AVERROR_PATCHWELCOME;
366 } else if (hdr->substreamid < info->num_ind_sub ||
367 hdr->substreamid == 0 && info->substream[0].bsid) {
373 /* fill the info needed for the "dec3" atom */
374 info->substream[hdr->substreamid].fscod = hdr->sr_code;
375 info->substream[hdr->substreamid].bsid = hdr->bitstream_id;
376 info->substream[hdr->substreamid].bsmod = hdr->bitstream_mode;
377 info->substream[hdr->substreamid].acmod = hdr->channel_mode;
378 info->substream[hdr->substreamid].lfeon = hdr->lfe_on;
380 /* Parse dependent substream(s), if any */
381 if (pkt->size != hdr->frame_size) {
382 int cumul_size = hdr->frame_size;
383 int parent = hdr->substreamid;
385 while (cumul_size != pkt->size) {
387 init_get_bits(&gbc, pkt->data + cumul_size, (pkt->size - cumul_size) * 8);
388 if (avpriv_ac3_parse_header2(&gbc, &hdr) < 0)
389 return AVERROR_INVALIDDATA;
390 if (hdr->frame_type != EAC3_FRAME_TYPE_DEPENDENT)
391 return AVERROR(EINVAL);
392 cumul_size += hdr->frame_size;
393 info->substream[parent].num_dep_sub++;
395 /* header is parsed up to lfeon, but custom channel map may be needed */
398 /* skip volume control params */
399 for (i = 0; i < (hdr->channel_mode ? 1 : 2); i++) {
400 skip_bits(&gbc, 5); // skip dialog normalization
401 if (get_bits1(&gbc)) {
402 skip_bits(&gbc, 8); // skip compression gain word
405 /* get the dependent stream channel map, if exists */
407 info->substream[parent].chan_loc |= (get_bits(&gbc, 16) >> 5) & 0x1f;
409 info->substream[parent].chan_loc |= hdr->channel_mode;
415 if (!info->num_blocks && num_blocks == 6)
417 else if (info->num_blocks + num_blocks > 6)
418 return AVERROR_INVALIDDATA;
420 if (!info->num_blocks) {
422 if ((ret = av_copy_packet(&info->pkt, pkt)) < 0)
424 info->num_blocks = num_blocks;
428 if ((ret = av_grow_packet(&info->pkt, pkt->size)) < 0)
430 memcpy(info->pkt.data + info->pkt.size - pkt->size, pkt->data, pkt->size);
431 info->num_blocks += num_blocks;
432 info->pkt.duration += pkt->duration;
433 if ((ret = av_copy_packet_side_data(&info->pkt, pkt)) < 0)
435 if (info->num_blocks != 6)
438 if ((ret = av_copy_packet(pkt, &info->pkt)) < 0)
440 av_free_packet(&info->pkt);
441 info->num_blocks = 0;
447 static int mov_write_eac3_tag(AVIOContext *pb, MOVTrack *track)
451 struct eac3_info *info;
454 if (!track->eac3_priv)
455 return AVERROR(EINVAL);
457 info = track->eac3_priv;
458 size = 2 + 4 * (info->num_ind_sub + 1);
459 buf = av_malloc(size);
461 size = AVERROR(ENOMEM);
465 init_put_bits(&pbc, buf, size);
466 put_bits(&pbc, 13, info->data_rate);
467 put_bits(&pbc, 3, info->num_ind_sub);
468 for (i = 0; i <= info->num_ind_sub; i++) {
469 put_bits(&pbc, 2, info->substream[i].fscod);
470 put_bits(&pbc, 5, info->substream[i].bsid);
471 put_bits(&pbc, 1, 0); /* reserved */
472 put_bits(&pbc, 1, 0); /* asvc */
473 put_bits(&pbc, 3, info->substream[i].bsmod);
474 put_bits(&pbc, 3, info->substream[i].acmod);
475 put_bits(&pbc, 1, info->substream[i].lfeon);
476 put_bits(&pbc, 5, 0); /* reserved */
477 put_bits(&pbc, 4, info->substream[i].num_dep_sub);
478 if (!info->substream[i].num_dep_sub) {
479 put_bits(&pbc, 1, 0); /* reserved */
482 put_bits(&pbc, 9, info->substream[i].chan_loc);
485 flush_put_bits(&pbc);
487 avio_wb32(pb, size + 8);
488 ffio_wfourcc(pb, "dec3");
489 avio_write(pb, buf, size);
494 av_free_packet(&info->pkt);
495 av_freep(&track->eac3_priv);
501 * This function writes extradata "as is".
502 * Extradata must be formatted like a valid atom (with size and tag).
504 static int mov_write_extradata_tag(AVIOContext *pb, MOVTrack *track)
506 avio_write(pb, track->enc->extradata, track->enc->extradata_size);
507 return track->enc->extradata_size;
510 static int mov_write_enda_tag(AVIOContext *pb)
513 ffio_wfourcc(pb, "enda");
514 avio_wb16(pb, 1); /* little endian */
518 static int mov_write_enda_tag_be(AVIOContext *pb)
521 ffio_wfourcc(pb, "enda");
522 avio_wb16(pb, 0); /* big endian */
526 static void put_descr(AVIOContext *pb, int tag, unsigned int size)
531 avio_w8(pb, (size >> (7 * i)) | 0x80);
532 avio_w8(pb, size & 0x7F);
535 static unsigned compute_avg_bitrate(MOVTrack *track)
539 if (!track->track_duration)
541 for (i = 0; i < track->entry; i++)
542 size += track->cluster[i].size;
543 return size * 8 * track->timescale / track->track_duration;
546 static int mov_write_esds_tag(AVIOContext *pb, MOVTrack *track) // Basic
548 int64_t pos = avio_tell(pb);
549 int decoder_specific_info_len = track->vos_len ? 5 + track->vos_len : 0;
550 unsigned avg_bitrate;
552 avio_wb32(pb, 0); // size
553 ffio_wfourcc(pb, "esds");
554 avio_wb32(pb, 0); // Version
557 put_descr(pb, 0x03, 3 + 5+13 + decoder_specific_info_len + 5+1);
558 avio_wb16(pb, track->track_id);
559 avio_w8(pb, 0x00); // flags (= no flags)
561 // DecoderConfig descriptor
562 put_descr(pb, 0x04, 13 + decoder_specific_info_len);
564 // Object type indication
565 if ((track->enc->codec_id == AV_CODEC_ID_MP2 ||
566 track->enc->codec_id == AV_CODEC_ID_MP3) &&
567 track->enc->sample_rate > 24000)
568 avio_w8(pb, 0x6B); // 11172-3
570 avio_w8(pb, ff_codec_get_tag(ff_mp4_obj_type, track->enc->codec_id));
572 // the following fields is made of 6 bits to identify the streamtype (4 for video, 5 for audio)
573 // plus 1 bit to indicate upstream and 1 bit set to 1 (reserved)
574 if (track->enc->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
575 avio_w8(pb, (0x38 << 2) | 1); // flags (= NeroSubpicStream)
576 else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
577 avio_w8(pb, 0x15); // flags (= Audiostream)
579 avio_w8(pb, 0x11); // flags (= Visualstream)
581 avio_wb24(pb, track->enc->rc_buffer_size >> 3); // Buffersize DB
583 avg_bitrate = compute_avg_bitrate(track);
584 // maxbitrate (FIXME should be max rate in any 1 sec window)
585 avio_wb32(pb, FFMAX3(track->enc->bit_rate, track->enc->rc_max_rate, avg_bitrate));
586 avio_wb32(pb, avg_bitrate);
588 if (track->vos_len) {
589 // DecoderSpecific info descriptor
590 put_descr(pb, 0x05, track->vos_len);
591 avio_write(pb, track->vos_data, track->vos_len);
595 put_descr(pb, 0x06, 1);
597 return update_size(pb, pos);
600 static int mov_pcm_le_gt16(enum AVCodecID codec_id)
602 return codec_id == AV_CODEC_ID_PCM_S24LE ||
603 codec_id == AV_CODEC_ID_PCM_S32LE ||
604 codec_id == AV_CODEC_ID_PCM_F32LE ||
605 codec_id == AV_CODEC_ID_PCM_F64LE;
608 static int mov_pcm_be_gt16(enum AVCodecID codec_id)
610 return codec_id == AV_CODEC_ID_PCM_S24BE ||
611 codec_id == AV_CODEC_ID_PCM_S32BE ||
612 codec_id == AV_CODEC_ID_PCM_F32BE ||
613 codec_id == AV_CODEC_ID_PCM_F64BE;
616 static int mov_write_ms_tag(AVIOContext *pb, MOVTrack *track)
619 int64_t pos = avio_tell(pb);
621 avio_wl32(pb, track->tag); // store it byteswapped
622 track->enc->codec_tag = av_bswap16(track->tag >> 16);
623 if ((ret = ff_put_wav_header(pb, track->enc, 0)) < 0)
625 return update_size(pb, pos);
628 static int mov_write_wfex_tag(AVIOContext *pb, MOVTrack *track)
631 int64_t pos = avio_tell(pb);
633 ffio_wfourcc(pb, "wfex");
634 if ((ret = ff_put_wav_header(pb, track->enc, FF_PUT_WAV_HEADER_FORCE_WAVEFORMATEX)) < 0)
636 return update_size(pb, pos);
639 static int mov_write_chan_tag(AVIOContext *pb, MOVTrack *track)
641 uint32_t layout_tag, bitmap;
642 int64_t pos = avio_tell(pb);
644 layout_tag = ff_mov_get_channel_layout_tag(track->enc->codec_id,
645 track->enc->channel_layout,
648 av_log(track->enc, AV_LOG_WARNING, "not writing 'chan' tag due to "
649 "lack of channel information\n");
653 if (track->multichannel_as_mono)
656 avio_wb32(pb, 0); // Size
657 ffio_wfourcc(pb, "chan"); // Type
658 avio_w8(pb, 0); // Version
659 avio_wb24(pb, 0); // Flags
660 avio_wb32(pb, layout_tag); // mChannelLayoutTag
661 avio_wb32(pb, bitmap); // mChannelBitmap
662 avio_wb32(pb, 0); // mNumberChannelDescriptions
664 return update_size(pb, pos);
667 static int mov_write_wave_tag(AVIOContext *pb, MOVTrack *track)
669 int64_t pos = avio_tell(pb);
671 avio_wb32(pb, 0); /* size */
672 ffio_wfourcc(pb, "wave");
674 if (track->enc->codec_id != AV_CODEC_ID_QDM2) {
675 avio_wb32(pb, 12); /* size */
676 ffio_wfourcc(pb, "frma");
677 avio_wl32(pb, track->tag);
680 if (track->enc->codec_id == AV_CODEC_ID_AAC) {
681 /* useless atom needed by mplayer, ipod, not needed by quicktime */
682 avio_wb32(pb, 12); /* size */
683 ffio_wfourcc(pb, "mp4a");
685 mov_write_esds_tag(pb, track);
686 } else if (mov_pcm_le_gt16(track->enc->codec_id)) {
687 mov_write_enda_tag(pb);
688 } else if (mov_pcm_be_gt16(track->enc->codec_id)) {
689 mov_write_enda_tag_be(pb);
690 } else if (track->enc->codec_id == AV_CODEC_ID_AMR_NB) {
691 mov_write_amr_tag(pb, track);
692 } else if (track->enc->codec_id == AV_CODEC_ID_AC3) {
693 mov_write_ac3_tag(pb, track);
694 } else if (track->enc->codec_id == AV_CODEC_ID_EAC3) {
695 mov_write_eac3_tag(pb, track);
696 } else if (track->enc->codec_id == AV_CODEC_ID_ALAC ||
697 track->enc->codec_id == AV_CODEC_ID_QDM2) {
698 mov_write_extradata_tag(pb, track);
699 } else if (track->enc->codec_id == AV_CODEC_ID_ADPCM_MS ||
700 track->enc->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) {
701 mov_write_ms_tag(pb, track);
704 avio_wb32(pb, 8); /* size */
705 avio_wb32(pb, 0); /* null tag */
707 return update_size(pb, pos);
710 static int mov_write_dvc1_structs(MOVTrack *track, uint8_t *buf)
713 const uint8_t *start, *next, *end = track->vos_data + track->vos_len;
714 int unescaped_size, seq_found = 0;
715 int level = 0, interlace = 0;
716 int packet_seq = track->vc1_info.packet_seq;
717 int packet_entry = track->vc1_info.packet_entry;
718 int slices = track->vc1_info.slices;
721 if (track->start_dts == AV_NOPTS_VALUE) {
722 /* No packets written yet, vc1_info isn't authoritative yet. */
723 /* Assume inline sequence and entry headers. This will be
724 * overwritten at the end if the file is seekable. */
725 packet_seq = packet_entry = 1;
728 unescaped = av_mallocz(track->vos_len + FF_INPUT_BUFFER_PADDING_SIZE);
730 return AVERROR(ENOMEM);
731 start = find_next_marker(track->vos_data, end);
732 for (next = start; next < end; start = next) {
735 next = find_next_marker(start + 4, end);
736 size = next - start - 4;
739 unescaped_size = vc1_unescape_buffer(start + 4, size, unescaped);
740 init_get_bits(&gb, unescaped, 8 * unescaped_size);
741 if (AV_RB32(start) == VC1_CODE_SEQHDR) {
742 int profile = get_bits(&gb, 2);
743 if (profile != PROFILE_ADVANCED) {
745 return AVERROR(ENOSYS);
748 level = get_bits(&gb, 3);
749 /* chromaformat, frmrtq_postproc, bitrtq_postproc, postprocflag,
751 skip_bits_long(&gb, 2 + 3 + 5 + 1 + 2*12);
752 skip_bits(&gb, 1); /* broadcast */
753 interlace = get_bits1(&gb);
754 skip_bits(&gb, 4); /* tfcntrflag, finterpflag, reserved, psf */
759 return AVERROR(ENOSYS);
762 init_put_bits(&pbc, buf, 7);
763 /* VC1DecSpecStruc */
764 put_bits(&pbc, 4, 12); /* profile - advanced */
765 put_bits(&pbc, 3, level);
766 put_bits(&pbc, 1, 0); /* reserved */
767 /* VC1AdvDecSpecStruc */
768 put_bits(&pbc, 3, level);
769 put_bits(&pbc, 1, 0); /* cbr */
770 put_bits(&pbc, 6, 0); /* reserved */
771 put_bits(&pbc, 1, !interlace); /* no interlace */
772 put_bits(&pbc, 1, !packet_seq); /* no multiple seq */
773 put_bits(&pbc, 1, !packet_entry); /* no multiple entry */
774 put_bits(&pbc, 1, !slices); /* no slice code */
775 put_bits(&pbc, 1, 0); /* no bframe */
776 put_bits(&pbc, 1, 0); /* reserved */
779 if (track->st->avg_frame_rate.num > 0 && track->st->avg_frame_rate.den > 0)
780 put_bits32(&pbc, track->st->avg_frame_rate.num / track->st->avg_frame_rate.den);
782 put_bits32(&pbc, 0xffffffff);
784 flush_put_bits(&pbc);
791 static int mov_write_dvc1_tag(AVIOContext *pb, MOVTrack *track)
793 uint8_t buf[7] = { 0 };
796 if ((ret = mov_write_dvc1_structs(track, buf)) < 0)
799 avio_wb32(pb, track->vos_len + 8 + sizeof(buf));
800 ffio_wfourcc(pb, "dvc1");
801 track->vc1_info.struct_offset = avio_tell(pb);
802 avio_write(pb, buf, sizeof(buf));
803 avio_write(pb, track->vos_data, track->vos_len);
808 static int mov_write_glbl_tag(AVIOContext *pb, MOVTrack *track)
810 avio_wb32(pb, track->vos_len + 8);
811 ffio_wfourcc(pb, "glbl");
812 avio_write(pb, track->vos_data, track->vos_len);
813 return 8 + track->vos_len;
817 * Compute flags for 'lpcm' tag.
818 * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
820 static int mov_get_lpcm_flags(enum AVCodecID codec_id)
823 case AV_CODEC_ID_PCM_F32BE:
824 case AV_CODEC_ID_PCM_F64BE:
826 case AV_CODEC_ID_PCM_F32LE:
827 case AV_CODEC_ID_PCM_F64LE:
829 case AV_CODEC_ID_PCM_U8:
831 case AV_CODEC_ID_PCM_S16BE:
832 case AV_CODEC_ID_PCM_S24BE:
833 case AV_CODEC_ID_PCM_S32BE:
835 case AV_CODEC_ID_PCM_S8:
836 case AV_CODEC_ID_PCM_S16LE:
837 case AV_CODEC_ID_PCM_S24LE:
838 case AV_CODEC_ID_PCM_S32LE:
845 static int get_cluster_duration(MOVTrack *track, int cluster_idx)
849 if (cluster_idx >= track->entry)
852 if (cluster_idx + 1 == track->entry)
853 next_dts = track->track_duration + track->start_dts;
855 next_dts = track->cluster[cluster_idx + 1].dts;
857 next_dts -= track->cluster[cluster_idx].dts;
859 av_assert0(next_dts >= 0);
860 av_assert0(next_dts <= INT_MAX);
865 static int get_samples_per_packet(MOVTrack *track)
867 int i, first_duration;
869 // return track->enc->frame_size;
871 /* use 1 for raw PCM */
872 if (!track->audio_vbr)
875 /* check to see if duration is constant for all clusters */
878 first_duration = get_cluster_duration(track, 0);
879 for (i = 1; i < track->entry; i++) {
880 if (get_cluster_duration(track, i) != first_duration)
883 return first_duration;
886 static int mov_write_audio_tag(AVIOContext *pb, MOVTrack *track)
888 int64_t pos = avio_tell(pb);
890 uint32_t tag = track->tag;
892 if (track->mode == MODE_MOV) {
893 if (track->timescale > UINT16_MAX) {
894 if (mov_get_lpcm_flags(track->enc->codec_id))
895 tag = AV_RL32("lpcm");
897 } else if (track->audio_vbr || mov_pcm_le_gt16(track->enc->codec_id) ||
898 mov_pcm_be_gt16(track->enc->codec_id) ||
899 track->enc->codec_id == AV_CODEC_ID_ADPCM_MS ||
900 track->enc->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
901 track->enc->codec_id == AV_CODEC_ID_QDM2) {
906 avio_wb32(pb, 0); /* size */
907 avio_wl32(pb, tag); // store it byteswapped
908 avio_wb32(pb, 0); /* Reserved */
909 avio_wb16(pb, 0); /* Reserved */
910 avio_wb16(pb, 1); /* Data-reference index, XXX == 1 */
912 /* SoundDescription */
913 avio_wb16(pb, version); /* Version */
914 avio_wb16(pb, 0); /* Revision level */
915 avio_wb32(pb, 0); /* Reserved */
920 avio_wb16(pb, 0xfffe);
922 avio_wb32(pb, 0x00010000);
924 avio_wb64(pb, av_double2int(track->enc->sample_rate));
925 avio_wb32(pb, track->enc->channels);
926 avio_wb32(pb, 0x7F000000);
927 avio_wb32(pb, av_get_bits_per_sample(track->enc->codec_id));
928 avio_wb32(pb, mov_get_lpcm_flags(track->enc->codec_id));
929 avio_wb32(pb, track->sample_size);
930 avio_wb32(pb, get_samples_per_packet(track));
932 if (track->mode == MODE_MOV) {
933 avio_wb16(pb, track->enc->channels);
934 if (track->enc->codec_id == AV_CODEC_ID_PCM_U8 ||
935 track->enc->codec_id == AV_CODEC_ID_PCM_S8)
936 avio_wb16(pb, 8); /* bits per sample */
937 else if (track->enc->codec_id == AV_CODEC_ID_ADPCM_G726)
938 avio_wb16(pb, track->enc->bits_per_coded_sample);
941 avio_wb16(pb, track->audio_vbr ? -2 : 0); /* compression ID */
942 } else { /* reserved for mp4/3gp */
948 avio_wb16(pb, 0); /* packet size (= 0) */
949 avio_wb16(pb, track->enc->sample_rate <= UINT16_MAX ?
950 track->enc->sample_rate : 0);
951 avio_wb16(pb, 0); /* Reserved */
954 if (version == 1) { /* SoundDescription V1 extended info */
955 if (mov_pcm_le_gt16(track->enc->codec_id) ||
956 mov_pcm_be_gt16(track->enc->codec_id))
957 avio_wb32(pb, 1); /* must be 1 for uncompressed formats */
959 avio_wb32(pb, track->enc->frame_size); /* Samples per packet */
960 avio_wb32(pb, track->sample_size / track->enc->channels); /* Bytes per packet */
961 avio_wb32(pb, track->sample_size); /* Bytes per frame */
962 avio_wb32(pb, 2); /* Bytes per sample */
965 if (track->mode == MODE_MOV &&
966 (track->enc->codec_id == AV_CODEC_ID_AAC ||
967 track->enc->codec_id == AV_CODEC_ID_AC3 ||
968 track->enc->codec_id == AV_CODEC_ID_EAC3 ||
969 track->enc->codec_id == AV_CODEC_ID_AMR_NB ||
970 track->enc->codec_id == AV_CODEC_ID_ALAC ||
971 track->enc->codec_id == AV_CODEC_ID_ADPCM_MS ||
972 track->enc->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
973 track->enc->codec_id == AV_CODEC_ID_QDM2 ||
974 (mov_pcm_le_gt16(track->enc->codec_id) && version==1) ||
975 (mov_pcm_be_gt16(track->enc->codec_id) && version==1)))
976 mov_write_wave_tag(pb, track);
977 else if (track->tag == MKTAG('m','p','4','a'))
978 mov_write_esds_tag(pb, track);
979 else if (track->enc->codec_id == AV_CODEC_ID_AMR_NB)
980 mov_write_amr_tag(pb, track);
981 else if (track->enc->codec_id == AV_CODEC_ID_AC3)
982 mov_write_ac3_tag(pb, track);
983 else if (track->enc->codec_id == AV_CODEC_ID_EAC3)
984 mov_write_eac3_tag(pb, track);
985 else if (track->enc->codec_id == AV_CODEC_ID_ALAC)
986 mov_write_extradata_tag(pb, track);
987 else if (track->enc->codec_id == AV_CODEC_ID_WMAPRO)
988 mov_write_wfex_tag(pb, track);
989 else if (track->vos_len > 0)
990 mov_write_glbl_tag(pb, track);
992 if (track->mode == MODE_MOV && track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
993 mov_write_chan_tag(pb, track);
995 return update_size(pb, pos);
998 static int mov_write_d263_tag(AVIOContext *pb)
1000 avio_wb32(pb, 0xf); /* size */
1001 ffio_wfourcc(pb, "d263");
1002 ffio_wfourcc(pb, "FFMP");
1003 avio_w8(pb, 0); /* decoder version */
1004 /* FIXME use AVCodecContext level/profile, when encoder will set values */
1005 avio_w8(pb, 0xa); /* level */
1006 avio_w8(pb, 0); /* profile */
1010 static int mov_write_avcc_tag(AVIOContext *pb, MOVTrack *track)
1012 int64_t pos = avio_tell(pb);
1015 ffio_wfourcc(pb, "avcC");
1016 ff_isom_write_avcc(pb, track->vos_data, track->vos_len);
1017 return update_size(pb, pos);
1020 static int mov_write_hvcc_tag(AVIOContext *pb, MOVTrack *track)
1022 int64_t pos = avio_tell(pb);
1025 ffio_wfourcc(pb, "hvcC");
1026 ff_isom_write_hvcc(pb, track->vos_data, track->vos_len, 0);
1027 return update_size(pb, pos);
1030 /* also used by all avid codecs (dv, imx, meridien) and their variants */
1031 static int mov_write_avid_tag(AVIOContext *pb, MOVTrack *track)
1034 avio_wb32(pb, 24); /* size */
1035 ffio_wfourcc(pb, "ACLR");
1036 ffio_wfourcc(pb, "ACLR");
1037 ffio_wfourcc(pb, "0001");
1038 if (track->enc->color_range == AVCOL_RANGE_MPEG) { /* Legal range (16-235) */
1039 avio_wb32(pb, 1); /* Corresponds to 709 in official encoder */
1040 } else { /* Full range (0-255) */
1041 avio_wb32(pb, 2); /* Corresponds to RGB in official encoder */
1043 avio_wb32(pb, 0); /* unknown */
1045 avio_wb32(pb, 24); /* size */
1046 ffio_wfourcc(pb, "APRG");
1047 ffio_wfourcc(pb, "APRG");
1048 ffio_wfourcc(pb, "0001");
1049 avio_wb32(pb, 1); /* unknown */
1050 avio_wb32(pb, 0); /* unknown */
1052 avio_wb32(pb, 120); /* size */
1053 ffio_wfourcc(pb, "ARES");
1054 ffio_wfourcc(pb, "ARES");
1055 ffio_wfourcc(pb, "0001");
1056 avio_wb32(pb, AV_RB32(track->vos_data + 0x28)); /* dnxhd cid, some id ? */
1057 avio_wb32(pb, track->enc->width);
1058 /* values below are based on samples created with quicktime and avid codecs */
1059 if (track->vos_data[5] & 2) { // interlaced
1060 avio_wb32(pb, track->enc->height / 2);
1061 avio_wb32(pb, 2); /* unknown */
1062 avio_wb32(pb, 0); /* unknown */
1063 avio_wb32(pb, 4); /* unknown */
1065 avio_wb32(pb, track->enc->height);
1066 avio_wb32(pb, 1); /* unknown */
1067 avio_wb32(pb, 0); /* unknown */
1068 if (track->enc->height == 1080)
1069 avio_wb32(pb, 5); /* unknown */
1071 avio_wb32(pb, 6); /* unknown */
1074 for (i = 0; i < 10; i++)
1077 /* extra padding for stsd needed */
1082 static int mp4_get_codec_tag(AVFormatContext *s, MOVTrack *track)
1084 int tag = track->enc->codec_tag;
1086 if (!ff_codec_get_tag(ff_mp4_obj_type, track->enc->codec_id))
1089 if (track->enc->codec_id == AV_CODEC_ID_H264) tag = MKTAG('a','v','c','1');
1090 else if (track->enc->codec_id == AV_CODEC_ID_HEVC) tag = MKTAG('h','e','v','1');
1091 else if (track->enc->codec_id == AV_CODEC_ID_AC3) tag = MKTAG('a','c','-','3');
1092 else if (track->enc->codec_id == AV_CODEC_ID_EAC3) tag = MKTAG('e','c','-','3');
1093 else if (track->enc->codec_id == AV_CODEC_ID_DIRAC) tag = MKTAG('d','r','a','c');
1094 else if (track->enc->codec_id == AV_CODEC_ID_MOV_TEXT) tag = MKTAG('t','x','3','g');
1095 else if (track->enc->codec_id == AV_CODEC_ID_VC1) tag = MKTAG('v','c','-','1');
1096 else if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) tag = MKTAG('m','p','4','v');
1097 else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO) tag = MKTAG('m','p','4','a');
1098 else if (track->enc->codec_id == AV_CODEC_ID_DVD_SUBTITLE) tag = MKTAG('m','p','4','s');
1103 static const AVCodecTag codec_ipod_tags[] = {
1104 { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
1105 { AV_CODEC_ID_MPEG4, MKTAG('m','p','4','v') },
1106 { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
1107 { AV_CODEC_ID_ALAC, MKTAG('a','l','a','c') },
1108 { AV_CODEC_ID_AC3, MKTAG('a','c','-','3') },
1109 { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
1110 { AV_CODEC_ID_MOV_TEXT, MKTAG('t','e','x','t') },
1111 { AV_CODEC_ID_NONE, 0 },
1114 static int ipod_get_codec_tag(AVFormatContext *s, MOVTrack *track)
1116 int tag = track->enc->codec_tag;
1118 // keep original tag for subs, ipod supports both formats
1119 if (!(track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE &&
1120 (tag == MKTAG('t', 'x', '3', 'g') ||
1121 tag == MKTAG('t', 'e', 'x', 't'))))
1122 tag = ff_codec_get_tag(codec_ipod_tags, track->enc->codec_id);
1124 if (!av_match_ext(s->filename, "m4a") &&
1125 !av_match_ext(s->filename, "m4b") &&
1126 !av_match_ext(s->filename, "m4v"))
1127 av_log(s, AV_LOG_WARNING, "Warning, extension is not .m4a, .m4v nor .m4b "
1128 "Quicktime/Ipod might not play the file\n");
1133 static int mov_get_dv_codec_tag(AVFormatContext *s, MOVTrack *track)
1137 if (track->enc->width == 720) { /* SD */
1138 if (track->enc->height == 480) { /* NTSC */
1139 if (track->enc->pix_fmt == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','n');
1140 else tag = MKTAG('d','v','c',' ');
1141 }else if (track->enc->pix_fmt == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','p');
1142 else if (track->enc->pix_fmt == AV_PIX_FMT_YUV420P) tag = MKTAG('d','v','c','p');
1143 else tag = MKTAG('d','v','p','p');
1144 } else if (track->enc->height == 720) { /* HD 720 line */
1145 if (track->st->time_base.den == 50) tag = MKTAG('d','v','h','q');
1146 else tag = MKTAG('d','v','h','p');
1147 } else if (track->enc->height == 1080) { /* HD 1080 line */
1148 if (track->st->time_base.den == 25) tag = MKTAG('d','v','h','5');
1149 else tag = MKTAG('d','v','h','6');
1151 av_log(s, AV_LOG_ERROR, "unsupported height for dv codec\n");
1158 static AVRational find_fps(AVFormatContext *s, AVStream *st)
1160 AVRational rate = {st->codec->time_base.den, st->codec->time_base.num};
1161 /* if the codec time base makes no sense, try to fallback on stream frame rate */
1162 if (av_timecode_check_frame_rate(rate) < 0) {
1163 av_log(s, AV_LOG_DEBUG, "timecode: tbc=%d/%d invalid, fallback on %d/%d\n",
1164 rate.num, rate.den, st->avg_frame_rate.num, st->avg_frame_rate.den);
1165 rate = st->avg_frame_rate;
1171 static int mov_get_mpeg2_xdcam_codec_tag(AVFormatContext *s, MOVTrack *track)
1173 int tag = track->enc->codec_tag;
1174 int interlaced = track->enc->field_order > AV_FIELD_PROGRESSIVE;
1175 AVStream *st = track->st;
1176 int rate = av_q2d(find_fps(s, st));
1179 tag = MKTAG('m', '2', 'v', '1'); //fallback tag
1181 if (track->enc->pix_fmt == AV_PIX_FMT_YUV420P) {
1182 if (track->enc->width == 1280 && track->enc->height == 720) {
1184 if (rate == 24) tag = MKTAG('x','d','v','4');
1185 else if (rate == 25) tag = MKTAG('x','d','v','5');
1186 else if (rate == 30) tag = MKTAG('x','d','v','1');
1187 else if (rate == 50) tag = MKTAG('x','d','v','a');
1188 else if (rate == 60) tag = MKTAG('x','d','v','9');
1190 } else if (track->enc->width == 1440 && track->enc->height == 1080) {
1192 if (rate == 24) tag = MKTAG('x','d','v','6');
1193 else if (rate == 25) tag = MKTAG('x','d','v','7');
1194 else if (rate == 30) tag = MKTAG('x','d','v','8');
1196 if (rate == 25) tag = MKTAG('x','d','v','3');
1197 else if (rate == 30) tag = MKTAG('x','d','v','2');
1199 } else if (track->enc->width == 1920 && track->enc->height == 1080) {
1201 if (rate == 24) tag = MKTAG('x','d','v','d');
1202 else if (rate == 25) tag = MKTAG('x','d','v','e');
1203 else if (rate == 30) tag = MKTAG('x','d','v','f');
1205 if (rate == 25) tag = MKTAG('x','d','v','c');
1206 else if (rate == 30) tag = MKTAG('x','d','v','b');
1209 } else if (track->enc->pix_fmt == AV_PIX_FMT_YUV422P) {
1210 if (track->enc->width == 1280 && track->enc->height == 720) {
1212 if (rate == 24) tag = MKTAG('x','d','5','4');
1213 else if (rate == 25) tag = MKTAG('x','d','5','5');
1214 else if (rate == 30) tag = MKTAG('x','d','5','1');
1215 else if (rate == 50) tag = MKTAG('x','d','5','a');
1216 else if (rate == 60) tag = MKTAG('x','d','5','9');
1218 } else if (track->enc->width == 1920 && track->enc->height == 1080) {
1220 if (rate == 24) tag = MKTAG('x','d','5','d');
1221 else if (rate == 25) tag = MKTAG('x','d','5','e');
1222 else if (rate == 30) tag = MKTAG('x','d','5','f');
1224 if (rate == 25) tag = MKTAG('x','d','5','c');
1225 else if (rate == 30) tag = MKTAG('x','d','5','b');
1233 static int mov_get_h264_codec_tag(AVFormatContext *s, MOVTrack *track)
1235 int tag = track->enc->codec_tag;
1236 int interlaced = track->enc->field_order > AV_FIELD_PROGRESSIVE;
1237 AVStream *st = track->st;
1238 int rate = av_q2d(find_fps(s, st));
1241 tag = MKTAG('a', 'v', 'c', 'i'); //fallback tag
1243 if (track->enc->pix_fmt == AV_PIX_FMT_YUV420P10) {
1244 if (track->enc->width == 960 && track->enc->height == 720) {
1246 if (rate == 24) tag = MKTAG('a','i','5','p');
1247 else if (rate == 25) tag = MKTAG('a','i','5','q');
1248 else if (rate == 30) tag = MKTAG('a','i','5','p');
1249 else if (rate == 50) tag = MKTAG('a','i','5','q');
1250 else if (rate == 60) tag = MKTAG('a','i','5','p');
1252 } else if (track->enc->width == 1440 && track->enc->height == 1080) {
1254 if (rate == 24) tag = MKTAG('a','i','5','3');
1255 else if (rate == 25) tag = MKTAG('a','i','5','2');
1256 else if (rate == 30) tag = MKTAG('a','i','5','3');
1258 if (rate == 50) tag = MKTAG('a','i','5','5');
1259 else if (rate == 60) tag = MKTAG('a','i','5','6');
1262 } else if (track->enc->pix_fmt == AV_PIX_FMT_YUV422P10) {
1263 if (track->enc->width == 1280 && track->enc->height == 720) {
1265 if (rate == 24) tag = MKTAG('a','i','1','p');
1266 else if (rate == 25) tag = MKTAG('a','i','1','q');
1267 else if (rate == 30) tag = MKTAG('a','i','1','p');
1268 else if (rate == 50) tag = MKTAG('a','i','1','q');
1269 else if (rate == 60) tag = MKTAG('a','i','1','p');
1271 } else if (track->enc->width == 1920 && track->enc->height == 1080) {
1273 if (rate == 24) tag = MKTAG('a','i','1','3');
1274 else if (rate == 25) tag = MKTAG('a','i','1','2');
1275 else if (rate == 30) tag = MKTAG('a','i','1','3');
1277 if (rate == 25) tag = MKTAG('a','i','1','5');
1278 else if (rate == 50) tag = MKTAG('a','i','1','5');
1279 else if (rate == 60) tag = MKTAG('a','i','1','6');
1287 static const struct {
1288 enum AVPixelFormat pix_fmt;
1291 } mov_pix_fmt_tags[] = {
1292 { AV_PIX_FMT_YUYV422, MKTAG('y','u','v','2'), 0 },
1293 { AV_PIX_FMT_YUYV422, MKTAG('y','u','v','s'), 0 },
1294 { AV_PIX_FMT_UYVY422, MKTAG('2','v','u','y'), 0 },
1295 { AV_PIX_FMT_RGB555BE,MKTAG('r','a','w',' '), 16 },
1296 { AV_PIX_FMT_RGB555LE,MKTAG('L','5','5','5'), 16 },
1297 { AV_PIX_FMT_RGB565LE,MKTAG('L','5','6','5'), 16 },
1298 { AV_PIX_FMT_RGB565BE,MKTAG('B','5','6','5'), 16 },
1299 { AV_PIX_FMT_GRAY16BE,MKTAG('b','1','6','g'), 16 },
1300 { AV_PIX_FMT_RGB24, MKTAG('r','a','w',' '), 24 },
1301 { AV_PIX_FMT_BGR24, MKTAG('2','4','B','G'), 24 },
1302 { AV_PIX_FMT_ARGB, MKTAG('r','a','w',' '), 32 },
1303 { AV_PIX_FMT_BGRA, MKTAG('B','G','R','A'), 32 },
1304 { AV_PIX_FMT_RGBA, MKTAG('R','G','B','A'), 32 },
1305 { AV_PIX_FMT_ABGR, MKTAG('A','B','G','R'), 32 },
1306 { AV_PIX_FMT_RGB48BE, MKTAG('b','4','8','r'), 48 },
1309 static int mov_get_rawvideo_codec_tag(AVFormatContext *s, MOVTrack *track)
1311 int tag = track->enc->codec_tag;
1313 enum AVPixelFormat pix_fmt;
1315 for (i = 0; i < FF_ARRAY_ELEMS(mov_pix_fmt_tags); i++) {
1316 if (track->enc->pix_fmt == mov_pix_fmt_tags[i].pix_fmt) {
1317 tag = mov_pix_fmt_tags[i].tag;
1318 track->enc->bits_per_coded_sample = mov_pix_fmt_tags[i].bps;
1319 if (track->enc->codec_tag == mov_pix_fmt_tags[i].tag)
1324 pix_fmt = avpriv_find_pix_fmt(avpriv_pix_fmt_bps_mov,
1325 track->enc->bits_per_coded_sample);
1326 if (tag == MKTAG('r','a','w',' ') &&
1327 track->enc->pix_fmt != pix_fmt &&
1328 track->enc->pix_fmt != AV_PIX_FMT_NONE)
1329 av_log(s, AV_LOG_ERROR, "%s rawvideo cannot be written to mov, output file will be unreadable\n",
1330 av_get_pix_fmt_name(track->enc->pix_fmt));
1334 static int mov_get_codec_tag(AVFormatContext *s, MOVTrack *track)
1336 int tag = track->enc->codec_tag;
1338 if (!tag || (s->strict_std_compliance >= FF_COMPLIANCE_NORMAL &&
1339 (track->enc->codec_id == AV_CODEC_ID_DVVIDEO ||
1340 track->enc->codec_id == AV_CODEC_ID_RAWVIDEO ||
1341 track->enc->codec_id == AV_CODEC_ID_H263 ||
1342 track->enc->codec_id == AV_CODEC_ID_H264 ||
1343 track->enc->codec_id == AV_CODEC_ID_MPEG2VIDEO ||
1344 av_get_bits_per_sample(track->enc->codec_id)))) { // pcm audio
1345 if (track->enc->codec_id == AV_CODEC_ID_DVVIDEO)
1346 tag = mov_get_dv_codec_tag(s, track);
1347 else if (track->enc->codec_id == AV_CODEC_ID_RAWVIDEO)
1348 tag = mov_get_rawvideo_codec_tag(s, track);
1349 else if (track->enc->codec_id == AV_CODEC_ID_MPEG2VIDEO)
1350 tag = mov_get_mpeg2_xdcam_codec_tag(s, track);
1351 else if (track->enc->codec_id == AV_CODEC_ID_H264)
1352 tag = mov_get_h264_codec_tag(s, track);
1353 else if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1354 tag = ff_codec_get_tag(ff_codec_movvideo_tags, track->enc->codec_id);
1355 if (!tag) { // if no mac fcc found, try with Microsoft tags
1356 tag = ff_codec_get_tag(ff_codec_bmp_tags, track->enc->codec_id);
1358 av_log(s, AV_LOG_WARNING, "Using MS style video codec tag, "
1359 "the file may be unplayable!\n");
1361 } else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO) {
1362 tag = ff_codec_get_tag(ff_codec_movaudio_tags, track->enc->codec_id);
1363 if (!tag) { // if no mac fcc found, try with Microsoft tags
1364 int ms_tag = ff_codec_get_tag(ff_codec_wav_tags, track->enc->codec_id);
1366 tag = MKTAG('m', 's', ((ms_tag >> 8) & 0xff), (ms_tag & 0xff));
1367 av_log(s, AV_LOG_WARNING, "Using MS style audio codec tag, "
1368 "the file may be unplayable!\n");
1371 } else if (track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE)
1372 tag = ff_codec_get_tag(ff_codec_movsubtitle_tags, track->enc->codec_id);
1378 static const AVCodecTag codec_3gp_tags[] = {
1379 { AV_CODEC_ID_H263, MKTAG('s','2','6','3') },
1380 { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
1381 { AV_CODEC_ID_MPEG4, MKTAG('m','p','4','v') },
1382 { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
1383 { AV_CODEC_ID_AMR_NB, MKTAG('s','a','m','r') },
1384 { AV_CODEC_ID_AMR_WB, MKTAG('s','a','w','b') },
1385 { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
1386 { AV_CODEC_ID_NONE, 0 },
1389 static const AVCodecTag codec_f4v_tags[] = { // XXX: add GIF/PNG/JPEG?
1390 { AV_CODEC_ID_MP3, MKTAG('.','m','p','3') },
1391 { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
1392 { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
1393 { AV_CODEC_ID_VP6A, MKTAG('V','P','6','A') },
1394 { AV_CODEC_ID_VP6F, MKTAG('V','P','6','F') },
1395 { AV_CODEC_ID_NONE, 0 },
1398 static int mov_find_codec_tag(AVFormatContext *s, MOVTrack *track)
1402 if (track->mode == MODE_MP4 || track->mode == MODE_PSP)
1403 tag = mp4_get_codec_tag(s, track);
1404 else if (track->mode == MODE_ISM) {
1405 tag = mp4_get_codec_tag(s, track);
1406 if (!tag && track->enc->codec_id == AV_CODEC_ID_WMAPRO)
1407 tag = MKTAG('w', 'm', 'a', ' ');
1408 } else if (track->mode == MODE_IPOD)
1409 tag = ipod_get_codec_tag(s, track);
1410 else if (track->mode & MODE_3GP)
1411 tag = ff_codec_get_tag(codec_3gp_tags, track->enc->codec_id);
1412 else if (track->mode == MODE_F4V)
1413 tag = ff_codec_get_tag(codec_f4v_tags, track->enc->codec_id);
1415 tag = mov_get_codec_tag(s, track);
1420 /** Write uuid atom.
1421 * Needed to make file play in iPods running newest firmware
1422 * goes after avcC atom in moov.trak.mdia.minf.stbl.stsd.avc1
1424 static int mov_write_uuid_tag_ipod(AVIOContext *pb)
1427 ffio_wfourcc(pb, "uuid");
1428 avio_wb32(pb, 0x6b6840f2);
1429 avio_wb32(pb, 0x5f244fc5);
1430 avio_wb32(pb, 0xba39a51b);
1431 avio_wb32(pb, 0xcf0323f3);
1436 static const uint16_t fiel_data[] = {
1437 0x0000, 0x0100, 0x0201, 0x0206, 0x0209, 0x020e
1440 static int mov_write_fiel_tag(AVIOContext *pb, MOVTrack *track)
1442 unsigned mov_field_order = 0;
1443 if (track->enc->field_order < FF_ARRAY_ELEMS(fiel_data))
1444 mov_field_order = fiel_data[track->enc->field_order];
1448 ffio_wfourcc(pb, "fiel");
1449 avio_wb16(pb, mov_field_order);
1453 static int mov_write_subtitle_tag(AVIOContext *pb, MOVTrack *track)
1455 int64_t pos = avio_tell(pb);
1456 avio_wb32(pb, 0); /* size */
1457 avio_wl32(pb, track->tag); // store it byteswapped
1458 avio_wb32(pb, 0); /* Reserved */
1459 avio_wb16(pb, 0); /* Reserved */
1460 avio_wb16(pb, 1); /* Data-reference index */
1462 if (track->enc->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
1463 mov_write_esds_tag(pb, track);
1464 else if (track->enc->extradata_size)
1465 avio_write(pb, track->enc->extradata, track->enc->extradata_size);
1467 return update_size(pb, pos);
1470 static int mov_write_pasp_tag(AVIOContext *pb, MOVTrack *track)
1473 av_reduce(&sar.num, &sar.den, track->enc->sample_aspect_ratio.num,
1474 track->enc->sample_aspect_ratio.den, INT_MAX);
1477 ffio_wfourcc(pb, "pasp");
1478 avio_wb32(pb, sar.num);
1479 avio_wb32(pb, sar.den);
1483 static void find_compressor(char * compressor_name, int len, MOVTrack *track)
1485 AVDictionaryEntry *encoder;
1486 int xdcam_res = (track->enc->width == 1280 && track->enc->height == 720)
1487 || (track->enc->width == 1440 && track->enc->height == 1080)
1488 || (track->enc->width == 1920 && track->enc->height == 1080);
1490 if (track->mode == MODE_MOV &&
1491 (encoder = av_dict_get(track->st->metadata, "encoder", NULL, 0))) {
1492 av_strlcpy(compressor_name, encoder->value, 32);
1493 } else if (track->enc->codec_id == AV_CODEC_ID_MPEG2VIDEO && xdcam_res) {
1494 int interlaced = track->enc->field_order > AV_FIELD_PROGRESSIVE;
1495 AVStream *st = track->st;
1496 int rate = av_q2d(find_fps(NULL, st));
1497 av_strlcatf(compressor_name, len, "XDCAM");
1498 if (track->enc->pix_fmt == AV_PIX_FMT_YUV422P) {
1499 av_strlcatf(compressor_name, len, " HD422");
1500 } else if(track->enc->width == 1440) {
1501 av_strlcatf(compressor_name, len, " HD");
1503 av_strlcatf(compressor_name, len, " EX");
1505 av_strlcatf(compressor_name, len, " %d%c", track->enc->height, interlaced ? 'i' : 'p');
1507 av_strlcatf(compressor_name, len, "%d", rate * (interlaced + 1));
1511 static int mov_write_video_tag(AVIOContext *pb, MOVTrack *track)
1513 int64_t pos = avio_tell(pb);
1514 char compressor_name[32] = { 0 };
1516 avio_wb32(pb, 0); /* size */
1517 avio_wl32(pb, track->tag); // store it byteswapped
1518 avio_wb32(pb, 0); /* Reserved */
1519 avio_wb16(pb, 0); /* Reserved */
1520 avio_wb16(pb, 1); /* Data-reference index */
1522 avio_wb16(pb, 0); /* Codec stream version */
1523 avio_wb16(pb, 0); /* Codec stream revision (=0) */
1524 if (track->mode == MODE_MOV) {
1525 ffio_wfourcc(pb, "FFMP"); /* Vendor */
1526 if (track->enc->codec_id == AV_CODEC_ID_RAWVIDEO) {
1527 avio_wb32(pb, 0); /* Temporal Quality */
1528 avio_wb32(pb, 0x400); /* Spatial Quality = lossless*/
1530 avio_wb32(pb, 0x200); /* Temporal Quality = normal */
1531 avio_wb32(pb, 0x200); /* Spatial Quality = normal */
1534 avio_wb32(pb, 0); /* Reserved */
1535 avio_wb32(pb, 0); /* Reserved */
1536 avio_wb32(pb, 0); /* Reserved */
1538 avio_wb16(pb, track->enc->width); /* Video width */
1539 avio_wb16(pb, track->height); /* Video height */
1540 avio_wb32(pb, 0x00480000); /* Horizontal resolution 72dpi */
1541 avio_wb32(pb, 0x00480000); /* Vertical resolution 72dpi */
1542 avio_wb32(pb, 0); /* Data size (= 0) */
1543 avio_wb16(pb, 1); /* Frame count (= 1) */
1545 /* FIXME not sure, ISO 14496-1 draft where it shall be set to 0 */
1546 find_compressor(compressor_name, 32, track);
1547 avio_w8(pb, strlen(compressor_name));
1548 avio_write(pb, compressor_name, 31);
1550 if (track->mode == MODE_MOV && track->enc->bits_per_coded_sample)
1551 avio_wb16(pb, track->enc->bits_per_coded_sample);
1553 avio_wb16(pb, 0x18); /* Reserved */
1554 avio_wb16(pb, 0xffff); /* Reserved */
1555 if (track->tag == MKTAG('m','p','4','v'))
1556 mov_write_esds_tag(pb, track);
1557 else if (track->enc->codec_id == AV_CODEC_ID_H263)
1558 mov_write_d263_tag(pb);
1559 else if (track->enc->codec_id == AV_CODEC_ID_AVUI ||
1560 track->enc->codec_id == AV_CODEC_ID_SVQ3) {
1561 mov_write_extradata_tag(pb, track);
1563 } else if (track->enc->codec_id == AV_CODEC_ID_DNXHD)
1564 mov_write_avid_tag(pb, track);
1565 else if (track->enc->codec_id == AV_CODEC_ID_HEVC)
1566 mov_write_hvcc_tag(pb, track);
1567 else if (track->enc->codec_id == AV_CODEC_ID_H264 && !TAG_IS_AVCI(track->tag)) {
1568 mov_write_avcc_tag(pb, track);
1569 if (track->mode == MODE_IPOD)
1570 mov_write_uuid_tag_ipod(pb);
1571 } else if (track->enc->codec_id == AV_CODEC_ID_VC1 && track->vos_len > 0)
1572 mov_write_dvc1_tag(pb, track);
1573 else if (track->enc->codec_id == AV_CODEC_ID_VP6F ||
1574 track->enc->codec_id == AV_CODEC_ID_VP6A) {
1575 /* Don't write any potential extradata here - the cropping
1576 * is signalled via the normal width/height fields. */
1577 } else if (track->vos_len > 0)
1578 mov_write_glbl_tag(pb, track);
1580 if (track->enc->codec_id != AV_CODEC_ID_H264 &&
1581 track->enc->codec_id != AV_CODEC_ID_MPEG4 &&
1582 track->enc->codec_id != AV_CODEC_ID_DNXHD)
1583 if (track->enc->field_order != AV_FIELD_UNKNOWN)
1584 mov_write_fiel_tag(pb, track);
1586 if (track->enc->sample_aspect_ratio.den && track->enc->sample_aspect_ratio.num &&
1587 track->enc->sample_aspect_ratio.den != track->enc->sample_aspect_ratio.num) {
1588 mov_write_pasp_tag(pb, track);
1591 return update_size(pb, pos);
1594 static int mov_write_rtp_tag(AVIOContext *pb, MOVTrack *track)
1596 int64_t pos = avio_tell(pb);
1597 avio_wb32(pb, 0); /* size */
1598 ffio_wfourcc(pb, "rtp ");
1599 avio_wb32(pb, 0); /* Reserved */
1600 avio_wb16(pb, 0); /* Reserved */
1601 avio_wb16(pb, 1); /* Data-reference index */
1603 avio_wb16(pb, 1); /* Hint track version */
1604 avio_wb16(pb, 1); /* Highest compatible version */
1605 avio_wb32(pb, track->max_packet_size); /* Max packet size */
1607 avio_wb32(pb, 12); /* size */
1608 ffio_wfourcc(pb, "tims");
1609 avio_wb32(pb, track->timescale);
1611 return update_size(pb, pos);
1614 static int mov_write_source_reference_tag(AVIOContext *pb, MOVTrack *track, const char *reel_name)
1616 uint64_t str_size =strlen(reel_name);
1617 int64_t pos = avio_tell(pb);
1619 if (str_size >= UINT16_MAX){
1620 av_log(NULL, AV_LOG_ERROR, "reel_name length %"PRIu64" is too large\n", str_size);
1622 return AVERROR(EINVAL);
1625 avio_wb32(pb, 0); /* size */
1626 ffio_wfourcc(pb, "name"); /* Data format */
1627 avio_wb16(pb, str_size); /* string size */
1628 avio_wb16(pb, track->language); /* langcode */
1629 avio_write(pb, reel_name, str_size); /* reel name */
1630 return update_size(pb,pos);
1633 static int mov_write_tmcd_tag(AVIOContext *pb, MOVTrack *track)
1635 int64_t pos = avio_tell(pb);
1637 int frame_duration = av_rescale(track->timescale, track->enc->time_base.num, track->enc->time_base.den);
1638 int nb_frames = 1.0/av_q2d(track->enc->time_base) + 0.5;
1639 AVDictionaryEntry *t = NULL;
1641 if (nb_frames > 255) {
1642 av_log(NULL, AV_LOG_ERROR, "fps %d is too large\n", nb_frames);
1643 return AVERROR(EINVAL);
1646 avio_wb32(pb, 0); /* size */
1647 ffio_wfourcc(pb, "tmcd"); /* Data format */
1648 avio_wb32(pb, 0); /* Reserved */
1649 avio_wb32(pb, 1); /* Data reference index */
1650 avio_wb32(pb, 0); /* Flags */
1651 avio_wb32(pb, track->timecode_flags); /* Flags (timecode) */
1652 avio_wb32(pb, track->timescale); /* Timescale */
1653 avio_wb32(pb, frame_duration); /* Frame duration */
1654 avio_w8(pb, nb_frames); /* Number of frames */
1655 avio_w8(pb, 0); /* Reserved */
1658 t = av_dict_get(track->st->metadata, "reel_name", NULL, 0);
1660 if (t && utf8len(t->value))
1661 mov_write_source_reference_tag(pb, track, t->value);
1663 avio_wb16(pb, 0); /* zero size */
1666 avio_wb32(pb, 0); /* size */
1667 ffio_wfourcc(pb, "tmcd"); /* Data format */
1668 avio_wb32(pb, 0); /* Reserved */
1669 avio_wb32(pb, 1); /* Data reference index */
1670 if (track->enc->extradata_size)
1671 avio_write(pb, track->enc->extradata, track->enc->extradata_size);
1673 return update_size(pb, pos);
1676 static int mov_write_stsd_tag(AVIOContext *pb, MOVTrack *track)
1678 int64_t pos = avio_tell(pb);
1679 avio_wb32(pb, 0); /* size */
1680 ffio_wfourcc(pb, "stsd");
1681 avio_wb32(pb, 0); /* version & flags */
1682 avio_wb32(pb, 1); /* entry count */
1683 if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO)
1684 mov_write_video_tag(pb, track);
1685 else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
1686 mov_write_audio_tag(pb, track);
1687 else if (track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE)
1688 mov_write_subtitle_tag(pb, track);
1689 else if (track->enc->codec_tag == MKTAG('r','t','p',' '))
1690 mov_write_rtp_tag(pb, track);
1691 else if (track->enc->codec_tag == MKTAG('t','m','c','d'))
1692 mov_write_tmcd_tag(pb, track);
1693 return update_size(pb, pos);
1696 static int mov_write_ctts_tag(AVIOContext *pb, MOVTrack *track)
1698 MOVStts *ctts_entries;
1699 uint32_t entries = 0;
1703 ctts_entries = av_malloc_array((track->entry + 1), sizeof(*ctts_entries)); /* worst case */
1704 ctts_entries[0].count = 1;
1705 ctts_entries[0].duration = track->cluster[0].cts;
1706 for (i = 1; i < track->entry; i++) {
1707 if (track->cluster[i].cts == ctts_entries[entries].duration) {
1708 ctts_entries[entries].count++; /* compress */
1711 ctts_entries[entries].duration = track->cluster[i].cts;
1712 ctts_entries[entries].count = 1;
1715 entries++; /* last one */
1716 atom_size = 16 + (entries * 8);
1717 avio_wb32(pb, atom_size); /* size */
1718 ffio_wfourcc(pb, "ctts");
1719 avio_wb32(pb, 0); /* version & flags */
1720 avio_wb32(pb, entries); /* entry count */
1721 for (i = 0; i < entries; i++) {
1722 avio_wb32(pb, ctts_entries[i].count);
1723 avio_wb32(pb, ctts_entries[i].duration);
1725 av_free(ctts_entries);
1729 /* Time to sample atom */
1730 static int mov_write_stts_tag(AVIOContext *pb, MOVTrack *track)
1732 MOVStts *stts_entries;
1733 uint32_t entries = -1;
1737 if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO && !track->audio_vbr) {
1738 stts_entries = av_malloc(sizeof(*stts_entries)); /* one entry */
1739 stts_entries[0].count = track->sample_count;
1740 stts_entries[0].duration = 1;
1743 stts_entries = track->entry ?
1744 av_malloc_array(track->entry, sizeof(*stts_entries)) : /* worst case */
1746 for (i = 0; i < track->entry; i++) {
1747 int duration = get_cluster_duration(track, i);
1748 if (i && duration == stts_entries[entries].duration) {
1749 stts_entries[entries].count++; /* compress */
1752 stts_entries[entries].duration = duration;
1753 stts_entries[entries].count = 1;
1756 entries++; /* last one */
1758 atom_size = 16 + (entries * 8);
1759 avio_wb32(pb, atom_size); /* size */
1760 ffio_wfourcc(pb, "stts");
1761 avio_wb32(pb, 0); /* version & flags */
1762 avio_wb32(pb, entries); /* entry count */
1763 for (i = 0; i < entries; i++) {
1764 avio_wb32(pb, stts_entries[i].count);
1765 avio_wb32(pb, stts_entries[i].duration);
1767 av_free(stts_entries);
1771 static int mov_write_dref_tag(AVIOContext *pb)
1773 avio_wb32(pb, 28); /* size */
1774 ffio_wfourcc(pb, "dref");
1775 avio_wb32(pb, 0); /* version & flags */
1776 avio_wb32(pb, 1); /* entry count */
1778 avio_wb32(pb, 0xc); /* size */
1779 //FIXME add the alis and rsrc atom
1780 ffio_wfourcc(pb, "url ");
1781 avio_wb32(pb, 1); /* version & flags */
1786 static int mov_write_stbl_tag(AVIOContext *pb, MOVTrack *track)
1788 int64_t pos = avio_tell(pb);
1789 avio_wb32(pb, 0); /* size */
1790 ffio_wfourcc(pb, "stbl");
1791 mov_write_stsd_tag(pb, track);
1792 mov_write_stts_tag(pb, track);
1793 if ((track->enc->codec_type == AVMEDIA_TYPE_VIDEO ||
1794 track->enc->codec_tag == MKTAG('r','t','p',' ')) &&
1795 track->has_keyframes && track->has_keyframes < track->entry)
1796 mov_write_stss_tag(pb, track, MOV_SYNC_SAMPLE);
1797 if (track->mode == MODE_MOV && track->flags & MOV_TRACK_STPS)
1798 mov_write_stss_tag(pb, track, MOV_PARTIAL_SYNC_SAMPLE);
1799 if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO &&
1800 track->flags & MOV_TRACK_CTTS)
1801 mov_write_ctts_tag(pb, track);
1802 mov_write_stsc_tag(pb, track);
1803 mov_write_stsz_tag(pb, track);
1804 mov_write_stco_tag(pb, track);
1805 return update_size(pb, pos);
1808 static int mov_write_dinf_tag(AVIOContext *pb)
1810 int64_t pos = avio_tell(pb);
1811 avio_wb32(pb, 0); /* size */
1812 ffio_wfourcc(pb, "dinf");
1813 mov_write_dref_tag(pb);
1814 return update_size(pb, pos);
1817 static int mov_write_nmhd_tag(AVIOContext *pb)
1820 ffio_wfourcc(pb, "nmhd");
1825 static int mov_write_tcmi_tag(AVIOContext *pb, MOVTrack *track)
1827 int64_t pos = avio_tell(pb);
1828 const char *font = "Lucida Grande";
1829 avio_wb32(pb, 0); /* size */
1830 ffio_wfourcc(pb, "tcmi"); /* timecode media information atom */
1831 avio_wb32(pb, 0); /* version & flags */
1832 avio_wb16(pb, 0); /* text font */
1833 avio_wb16(pb, 0); /* text face */
1834 avio_wb16(pb, 12); /* text size */
1835 avio_wb16(pb, 0); /* (unknown, not in the QT specs...) */
1836 avio_wb16(pb, 0x0000); /* text color (red) */
1837 avio_wb16(pb, 0x0000); /* text color (green) */
1838 avio_wb16(pb, 0x0000); /* text color (blue) */
1839 avio_wb16(pb, 0xffff); /* background color (red) */
1840 avio_wb16(pb, 0xffff); /* background color (green) */
1841 avio_wb16(pb, 0xffff); /* background color (blue) */
1842 avio_w8(pb, strlen(font)); /* font len (part of the pascal string) */
1843 avio_write(pb, font, strlen(font)); /* font name */
1844 return update_size(pb, pos);
1847 static int mov_write_gmhd_tag(AVIOContext *pb, MOVTrack *track)
1849 int64_t pos = avio_tell(pb);
1850 avio_wb32(pb, 0); /* size */
1851 ffio_wfourcc(pb, "gmhd");
1852 avio_wb32(pb, 0x18); /* gmin size */
1853 ffio_wfourcc(pb, "gmin");/* generic media info */
1854 avio_wb32(pb, 0); /* version & flags */
1855 avio_wb16(pb, 0x40); /* graphics mode = */
1856 avio_wb16(pb, 0x8000); /* opColor (r?) */
1857 avio_wb16(pb, 0x8000); /* opColor (g?) */
1858 avio_wb16(pb, 0x8000); /* opColor (b?) */
1859 avio_wb16(pb, 0); /* balance */
1860 avio_wb16(pb, 0); /* reserved */
1863 * This special text atom is required for
1864 * Apple Quicktime chapters. The contents
1865 * don't appear to be documented, so the
1866 * bytes are copied verbatim.
1868 if (track->tag != MKTAG('c','6','0','8')) {
1869 avio_wb32(pb, 0x2C); /* size */
1870 ffio_wfourcc(pb, "text");
1871 avio_wb16(pb, 0x01);
1872 avio_wb32(pb, 0x00);
1873 avio_wb32(pb, 0x00);
1874 avio_wb32(pb, 0x00);
1875 avio_wb32(pb, 0x01);
1876 avio_wb32(pb, 0x00);
1877 avio_wb32(pb, 0x00);
1878 avio_wb32(pb, 0x00);
1879 avio_wb32(pb, 0x00004000);
1880 avio_wb16(pb, 0x0000);
1883 if (track->enc->codec_tag == MKTAG('t','m','c','d')) {
1884 int64_t tmcd_pos = avio_tell(pb);
1885 avio_wb32(pb, 0); /* size */
1886 ffio_wfourcc(pb, "tmcd");
1887 mov_write_tcmi_tag(pb, track);
1888 update_size(pb, tmcd_pos);
1890 return update_size(pb, pos);
1893 static int mov_write_smhd_tag(AVIOContext *pb)
1895 avio_wb32(pb, 16); /* size */
1896 ffio_wfourcc(pb, "smhd");
1897 avio_wb32(pb, 0); /* version & flags */
1898 avio_wb16(pb, 0); /* reserved (balance, normally = 0) */
1899 avio_wb16(pb, 0); /* reserved */
1903 static int mov_write_vmhd_tag(AVIOContext *pb)
1905 avio_wb32(pb, 0x14); /* size (always 0x14) */
1906 ffio_wfourcc(pb, "vmhd");
1907 avio_wb32(pb, 0x01); /* version & flags */
1908 avio_wb64(pb, 0); /* reserved (graphics mode = copy) */
1912 static int is_clcp_track(MOVTrack *track)
1914 return track->tag == MKTAG('c','7','0','8') ||
1915 track->tag == MKTAG('c','6','0','8');
1918 static int mov_write_hdlr_tag(AVIOContext *pb, MOVTrack *track)
1920 const char *hdlr, *descr = NULL, *hdlr_type = NULL;
1921 int64_t pos = avio_tell(pb);
1925 descr = "DataHandler";
1928 hdlr = (track->mode == MODE_MOV) ? "mhlr" : "\0\0\0\0";
1929 if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1931 descr = "VideoHandler";
1932 } else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO) {
1934 descr = "SoundHandler";
1935 } else if (track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE) {
1936 if (is_clcp_track(track)) {
1938 descr = "ClosedCaptionHandler";
1940 if (track->tag == MKTAG('t','x','3','g')) {
1942 } else if (track->tag == MKTAG('m','p','4','s')) {
1947 descr = "SubtitleHandler";
1949 } else if (track->enc->codec_tag == MKTAG('r','t','p',' ')) {
1951 descr = "HintHandler";
1952 } else if (track->enc->codec_tag == MKTAG('t','m','c','d')) {
1954 descr = "TimeCodeHandler";
1957 av_get_codec_tag_string(tag_buf, sizeof(tag_buf),
1958 track->enc->codec_tag);
1960 av_log(track->enc, AV_LOG_WARNING,
1961 "Unknown hldr_type for %s / 0x%04X, writing dummy values\n",
1962 tag_buf, track->enc->codec_tag);
1965 // hdlr.name is used by some players to identify the content title
1966 // of the track. So if an alternate handler description is
1967 // specified, use it.
1968 AVDictionaryEntry *t;
1969 t = av_dict_get(track->st->metadata, "handler", NULL, 0);
1970 if (t && utf8len(t->value))
1975 avio_wb32(pb, 0); /* size */
1976 ffio_wfourcc(pb, "hdlr");
1977 avio_wb32(pb, 0); /* Version & flags */
1978 avio_write(pb, hdlr, 4); /* handler */
1979 ffio_wfourcc(pb, hdlr_type); /* handler type */
1980 avio_wb32(pb, 0); /* reserved */
1981 avio_wb32(pb, 0); /* reserved */
1982 avio_wb32(pb, 0); /* reserved */
1983 if (!track || track->mode == MODE_MOV)
1984 avio_w8(pb, strlen(descr)); /* pascal string */
1985 avio_write(pb, descr, strlen(descr)); /* handler description */
1986 if (track && track->mode != MODE_MOV)
1987 avio_w8(pb, 0); /* c string */
1988 return update_size(pb, pos);
1991 static int mov_write_hmhd_tag(AVIOContext *pb)
1993 /* This atom must be present, but leaving the values at zero
1994 * seems harmless. */
1995 avio_wb32(pb, 28); /* size */
1996 ffio_wfourcc(pb, "hmhd");
1997 avio_wb32(pb, 0); /* version, flags */
1998 avio_wb16(pb, 0); /* maxPDUsize */
1999 avio_wb16(pb, 0); /* avgPDUsize */
2000 avio_wb32(pb, 0); /* maxbitrate */
2001 avio_wb32(pb, 0); /* avgbitrate */
2002 avio_wb32(pb, 0); /* reserved */
2006 static int mov_write_minf_tag(AVIOContext *pb, MOVTrack *track)
2008 int64_t pos = avio_tell(pb);
2009 avio_wb32(pb, 0); /* size */
2010 ffio_wfourcc(pb, "minf");
2011 if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO)
2012 mov_write_vmhd_tag(pb);
2013 else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
2014 mov_write_smhd_tag(pb);
2015 else if (track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE) {
2016 if (track->tag == MKTAG('t','e','x','t') || is_clcp_track(track)) {
2017 mov_write_gmhd_tag(pb, track);
2019 mov_write_nmhd_tag(pb);
2021 } else if (track->tag == MKTAG('r','t','p',' ')) {
2022 mov_write_hmhd_tag(pb);
2023 } else if (track->tag == MKTAG('t','m','c','d')) {
2024 mov_write_gmhd_tag(pb, track);
2026 if (track->mode == MODE_MOV) /* FIXME: Why do it for MODE_MOV only ? */
2027 mov_write_hdlr_tag(pb, NULL);
2028 mov_write_dinf_tag(pb);
2029 mov_write_stbl_tag(pb, track);
2030 return update_size(pb, pos);
2033 static int mov_write_mdhd_tag(AVIOContext *pb, MOVMuxContext *mov,
2036 int version = track->track_duration < INT32_MAX ? 0 : 1;
2038 if (track->mode == MODE_ISM)
2041 (version == 1) ? avio_wb32(pb, 44) : avio_wb32(pb, 32); /* size */
2042 ffio_wfourcc(pb, "mdhd");
2043 avio_w8(pb, version);
2044 avio_wb24(pb, 0); /* flags */
2046 avio_wb64(pb, track->time);
2047 avio_wb64(pb, track->time);
2049 avio_wb32(pb, track->time); /* creation time */
2050 avio_wb32(pb, track->time); /* modification time */
2052 avio_wb32(pb, track->timescale); /* time scale (sample rate for audio) */
2053 if (!track->entry && mov->mode == MODE_ISM)
2054 (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
2055 else if (!track->entry)
2056 (version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0);
2058 (version == 1) ? avio_wb64(pb, track->track_duration) : avio_wb32(pb, track->track_duration); /* duration */
2059 avio_wb16(pb, track->language); /* language */
2060 avio_wb16(pb, 0); /* reserved (quality) */
2062 if (version != 0 && track->mode == MODE_MOV) {
2063 av_log(NULL, AV_LOG_ERROR,
2064 "FATAL error, file duration too long for timebase, this file will not be\n"
2065 "playable with quicktime. Choose a different timebase or a different\n"
2066 "container format\n");
2072 static int mov_write_mdia_tag(AVIOContext *pb, MOVMuxContext *mov,
2075 int64_t pos = avio_tell(pb);
2076 avio_wb32(pb, 0); /* size */
2077 ffio_wfourcc(pb, "mdia");
2078 mov_write_mdhd_tag(pb, mov, track);
2079 mov_write_hdlr_tag(pb, track);
2080 mov_write_minf_tag(pb, track);
2081 return update_size(pb, pos);
2084 /* transformation matrix
2088 static void write_matrix(AVIOContext *pb, int16_t a, int16_t b, int16_t c,
2089 int16_t d, int16_t tx, int16_t ty)
2091 avio_wb32(pb, a << 16); /* 16.16 format */
2092 avio_wb32(pb, b << 16); /* 16.16 format */
2093 avio_wb32(pb, 0); /* u in 2.30 format */
2094 avio_wb32(pb, c << 16); /* 16.16 format */
2095 avio_wb32(pb, d << 16); /* 16.16 format */
2096 avio_wb32(pb, 0); /* v in 2.30 format */
2097 avio_wb32(pb, tx << 16); /* 16.16 format */
2098 avio_wb32(pb, ty << 16); /* 16.16 format */
2099 avio_wb32(pb, 1 << 30); /* w in 2.30 format */
2102 static int mov_write_tkhd_tag(AVIOContext *pb, MOVMuxContext *mov,
2103 MOVTrack *track, AVStream *st)
2105 int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE,
2106 track->timescale, AV_ROUND_UP);
2107 int version = duration < INT32_MAX ? 0 : 1;
2108 int flags = MOV_TKHD_FLAG_IN_MOVIE;
2114 if (mov->per_stream_grouping)
2117 group = st->codec->codec_type;
2120 if (track->flags & MOV_TRACK_ENABLED)
2121 flags |= MOV_TKHD_FLAG_ENABLED;
2123 if (track->mode == MODE_ISM)
2126 (version == 1) ? avio_wb32(pb, 104) : avio_wb32(pb, 92); /* size */
2127 ffio_wfourcc(pb, "tkhd");
2128 avio_w8(pb, version);
2129 avio_wb24(pb, flags);
2131 avio_wb64(pb, track->time);
2132 avio_wb64(pb, track->time);
2134 avio_wb32(pb, track->time); /* creation time */
2135 avio_wb32(pb, track->time); /* modification time */
2137 avio_wb32(pb, track->track_id); /* track-id */
2138 avio_wb32(pb, 0); /* reserved */
2139 if (!track->entry && mov->mode == MODE_ISM)
2140 (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
2141 else if (!track->entry)
2142 (version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0);
2144 (version == 1) ? avio_wb64(pb, duration) : avio_wb32(pb, duration);
2146 avio_wb32(pb, 0); /* reserved */
2147 avio_wb32(pb, 0); /* reserved */
2148 avio_wb16(pb, 0); /* layer */
2149 avio_wb16(pb, group); /* alternate group) */
2150 /* Volume, only for audio */
2151 if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
2152 avio_wb16(pb, 0x0100);
2155 avio_wb16(pb, 0); /* reserved */
2157 /* Matrix structure */
2158 if (st && st->metadata) {
2159 AVDictionaryEntry *rot = av_dict_get(st->metadata, "rotate", NULL, 0);
2160 rotation = (rot && rot->value) ? atoi(rot->value) : 0;
2162 if (rotation == 90) {
2163 write_matrix(pb, 0, 1, -1, 0, track->enc->height, 0);
2164 } else if (rotation == 180) {
2165 write_matrix(pb, -1, 0, 0, -1, track->enc->width, track->enc->height);
2166 } else if (rotation == 270) {
2167 write_matrix(pb, 0, -1, 1, 0, 0, track->enc->width);
2169 write_matrix(pb, 1, 0, 0, 1, 0, 0);
2171 /* Track width and height, for visual only */
2172 if (st && (track->enc->codec_type == AVMEDIA_TYPE_VIDEO ||
2173 track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE)) {
2174 if (track->mode == MODE_MOV) {
2175 avio_wb32(pb, track->enc->width << 16);
2176 avio_wb32(pb, track->height << 16);
2178 double sample_aspect_ratio = av_q2d(st->sample_aspect_ratio);
2179 if (!sample_aspect_ratio || track->height != track->enc->height)
2180 sample_aspect_ratio = 1;
2181 avio_wb32(pb, sample_aspect_ratio * track->enc->width * 0x10000);
2182 avio_wb32(pb, track->height * 0x10000);
2191 static int mov_write_tapt_tag(AVIOContext *pb, MOVTrack *track)
2193 int32_t width = av_rescale(track->enc->sample_aspect_ratio.num, track->enc->width,
2194 track->enc->sample_aspect_ratio.den);
2196 int64_t pos = avio_tell(pb);
2198 avio_wb32(pb, 0); /* size */
2199 ffio_wfourcc(pb, "tapt");
2202 ffio_wfourcc(pb, "clef");
2204 avio_wb32(pb, width << 16);
2205 avio_wb32(pb, track->enc->height << 16);
2208 ffio_wfourcc(pb, "prof");
2210 avio_wb32(pb, width << 16);
2211 avio_wb32(pb, track->enc->height << 16);
2214 ffio_wfourcc(pb, "enof");
2216 avio_wb32(pb, track->enc->width << 16);
2217 avio_wb32(pb, track->enc->height << 16);
2219 return update_size(pb, pos);
2222 // This box seems important for the psp playback ... without it the movie seems to hang
2223 static int mov_write_edts_tag(AVIOContext *pb, MOVMuxContext *mov,
2226 int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE,
2227 track->timescale, AV_ROUND_UP);
2228 int version = duration < INT32_MAX ? 0 : 1;
2229 int entry_size, entry_count, size;
2230 int64_t delay, start_ct = track->cluster[0].cts;
2231 delay = av_rescale_rnd(track->cluster[0].dts + start_ct, MOV_TIMESCALE,
2232 track->timescale, AV_ROUND_DOWN);
2233 version |= delay < INT32_MAX ? 0 : 1;
2235 entry_size = (version == 1) ? 20 : 12;
2236 entry_count = 1 + (delay > 0);
2237 size = 24 + entry_count * entry_size;
2239 /* write the atom data */
2240 avio_wb32(pb, size);
2241 ffio_wfourcc(pb, "edts");
2242 avio_wb32(pb, size - 8);
2243 ffio_wfourcc(pb, "elst");
2244 avio_w8(pb, version);
2245 avio_wb24(pb, 0); /* flags */
2247 avio_wb32(pb, entry_count);
2248 if (delay > 0) { /* add an empty edit to delay presentation */
2249 /* In the positive delay case, the delay includes the cts
2250 * offset, and the second edit list entry below trims out
2251 * the same amount from the actual content. This makes sure
2252 * that the offsetted last sample is included in the edit
2253 * list duration as well. */
2255 avio_wb64(pb, delay);
2258 avio_wb32(pb, delay);
2261 avio_wb32(pb, 0x00010000);
2263 /* Avoid accidentally ending up with start_ct = -1 which has got a
2264 * special meaning. Normally start_ct should end up positive or zero
2265 * here, but use FFMIN in case dts is a a small positive integer
2266 * rounded to 0 when represented in MOV_TIMESCALE units. */
2267 av_assert0(av_rescale_rnd(track->cluster[0].dts, MOV_TIMESCALE, track->timescale, AV_ROUND_DOWN) <= 0);
2268 start_ct = -FFMIN(track->cluster[0].dts, 0);
2269 /* Note, this delay is calculated from the pts of the first sample,
2270 * ensuring that we don't reduce the duration for cases with
2275 /* For fragmented files, we don't know the full length yet. Setting
2276 * duration to 0 allows us to only specify the offset, including
2277 * the rest of the content (from all future fragments) without specifying
2278 * an explicit duration. */
2279 if (mov->flags & FF_MOV_FLAG_FRAGMENT)
2284 avio_wb64(pb, duration);
2285 avio_wb64(pb, start_ct);
2287 avio_wb32(pb, duration);
2288 avio_wb32(pb, start_ct);
2290 avio_wb32(pb, 0x00010000);
2294 static int mov_write_tref_tag(AVIOContext *pb, MOVTrack *track)
2296 avio_wb32(pb, 20); // size
2297 ffio_wfourcc(pb, "tref");
2298 avio_wb32(pb, 12); // size (subatom)
2299 avio_wl32(pb, track->tref_tag);
2300 avio_wb32(pb, track->tref_id);
2304 // goes at the end of each track! ... Critical for PSP playback ("Incompatible data" without it)
2305 static int mov_write_uuid_tag_psp(AVIOContext *pb, MOVTrack *mov)
2307 avio_wb32(pb, 0x34); /* size ... reports as 28 in mp4box! */
2308 ffio_wfourcc(pb, "uuid");
2309 ffio_wfourcc(pb, "USMT");
2310 avio_wb32(pb, 0x21d24fce);
2311 avio_wb32(pb, 0xbb88695c);
2312 avio_wb32(pb, 0xfac9c740);
2313 avio_wb32(pb, 0x1c); // another size here!
2314 ffio_wfourcc(pb, "MTDT");
2315 avio_wb32(pb, 0x00010012);
2316 avio_wb32(pb, 0x0a);
2317 avio_wb32(pb, 0x55c40000);
2323 static int mov_write_udta_sdp(AVIOContext *pb, MOVTrack *track)
2325 AVFormatContext *ctx = track->rtp_ctx;
2326 char buf[1000] = "";
2329 ff_sdp_write_media(buf, sizeof(buf), ctx->streams[0], track->src_track,
2330 NULL, NULL, 0, 0, ctx);
2331 av_strlcatf(buf, sizeof(buf), "a=control:streamid=%d\r\n", track->track_id);
2334 avio_wb32(pb, len + 24);
2335 ffio_wfourcc(pb, "udta");
2336 avio_wb32(pb, len + 16);
2337 ffio_wfourcc(pb, "hnti");
2338 avio_wb32(pb, len + 8);
2339 ffio_wfourcc(pb, "sdp ");
2340 avio_write(pb, buf, len);
2344 static int mov_write_track_metadata(AVIOContext *pb, AVStream *st,
2345 const char *tag, const char *str)
2347 int64_t pos = avio_tell(pb);
2348 AVDictionaryEntry *t = av_dict_get(st->metadata, str, NULL, 0);
2349 if (!t || !utf8len(t->value))
2352 avio_wb32(pb, 0); /* size */
2353 ffio_wfourcc(pb, tag); /* type */
2354 avio_write(pb, t->value, strlen(t->value)); /* UTF8 string value */
2355 return update_size(pb, pos);
2358 static int mov_write_track_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
2361 AVIOContext *pb_buf;
2365 if (!st || mov->fc->flags & AVFMT_FLAG_BITEXACT)
2368 ret = avio_open_dyn_buf(&pb_buf);
2372 if (mov->mode & MODE_MP4)
2373 mov_write_track_metadata(pb_buf, st, "name", "title");
2375 if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) {
2376 avio_wb32(pb, size + 8);
2377 ffio_wfourcc(pb, "udta");
2378 avio_write(pb, buf, size);
2385 static int mov_write_trak_tag(AVIOContext *pb, MOVMuxContext *mov,
2386 MOVTrack *track, AVStream *st)
2388 int64_t pos = avio_tell(pb);
2389 avio_wb32(pb, 0); /* size */
2390 ffio_wfourcc(pb, "trak");
2391 mov_write_tkhd_tag(pb, mov, track, st);
2393 av_assert2(mov->use_editlist >= 0);
2397 if (mov->use_editlist)
2398 mov_write_edts_tag(pb, mov, track); // PSP Movies and several other cases require edts box
2399 else if ((track->entry && track->cluster[0].dts) || track->mode == MODE_PSP || is_clcp_track(track))
2400 av_log(mov->fc, AV_LOG_WARNING,
2401 "Not writing any edit list even though one would have been required\n");
2404 if (track->tref_tag)
2405 mov_write_tref_tag(pb, track);
2406 mov_write_mdia_tag(pb, mov, track);
2407 if (track->mode == MODE_PSP)
2408 mov_write_uuid_tag_psp(pb, track); // PSP Movies require this uuid box
2409 if (track->tag == MKTAG('r','t','p',' '))
2410 mov_write_udta_sdp(pb, track);
2411 if (track->mode == MODE_MOV) {
2412 if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) {
2413 double sample_aspect_ratio = av_q2d(st->sample_aspect_ratio);
2414 if (st->sample_aspect_ratio.num && 1.0 != sample_aspect_ratio) {
2415 mov_write_tapt_tag(pb, track);
2418 if (is_clcp_track(track) && st->sample_aspect_ratio.num) {
2419 mov_write_tapt_tag(pb, track);
2422 mov_write_track_udta_tag(pb, mov, st);
2423 return update_size(pb, pos);
2426 static int mov_write_iods_tag(AVIOContext *pb, MOVMuxContext *mov)
2428 int i, has_audio = 0, has_video = 0;
2429 int64_t pos = avio_tell(pb);
2430 int audio_profile = mov->iods_audio_profile;
2431 int video_profile = mov->iods_video_profile;
2432 for (i = 0; i < mov->nb_streams; i++) {
2433 if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
2434 has_audio |= mov->tracks[i].enc->codec_type == AVMEDIA_TYPE_AUDIO;
2435 has_video |= mov->tracks[i].enc->codec_type == AVMEDIA_TYPE_VIDEO;
2438 if (audio_profile < 0)
2439 audio_profile = 0xFF - has_audio;
2440 if (video_profile < 0)
2441 video_profile = 0xFF - has_video;
2442 avio_wb32(pb, 0x0); /* size */
2443 ffio_wfourcc(pb, "iods");
2444 avio_wb32(pb, 0); /* version & flags */
2445 put_descr(pb, 0x10, 7);
2446 avio_wb16(pb, 0x004f);
2449 avio_w8(pb, audio_profile);
2450 avio_w8(pb, video_profile);
2452 return update_size(pb, pos);
2455 static int mov_write_trex_tag(AVIOContext *pb, MOVTrack *track)
2457 avio_wb32(pb, 0x20); /* size */
2458 ffio_wfourcc(pb, "trex");
2459 avio_wb32(pb, 0); /* version & flags */
2460 avio_wb32(pb, track->track_id); /* track ID */
2461 avio_wb32(pb, 1); /* default sample description index */
2462 avio_wb32(pb, 0); /* default sample duration */
2463 avio_wb32(pb, 0); /* default sample size */
2464 avio_wb32(pb, 0); /* default sample flags */
2468 static int mov_write_mvex_tag(AVIOContext *pb, MOVMuxContext *mov)
2470 int64_t pos = avio_tell(pb);
2472 avio_wb32(pb, 0x0); /* size */
2473 ffio_wfourcc(pb, "mvex");
2474 for (i = 0; i < mov->nb_streams; i++)
2475 mov_write_trex_tag(pb, &mov->tracks[i]);
2476 return update_size(pb, pos);
2479 static int mov_write_mvhd_tag(AVIOContext *pb, MOVMuxContext *mov)
2481 int max_track_id = 1, i;
2482 int64_t max_track_len_temp, max_track_len = 0;
2485 for (i = 0; i < mov->nb_streams; i++) {
2486 if (mov->tracks[i].entry > 0 && mov->tracks[i].timescale) {
2487 max_track_len_temp = av_rescale_rnd(mov->tracks[i].track_duration,
2489 mov->tracks[i].timescale,
2491 if (max_track_len < max_track_len_temp)
2492 max_track_len = max_track_len_temp;
2493 if (max_track_id < mov->tracks[i].track_id)
2494 max_track_id = mov->tracks[i].track_id;
2498 version = max_track_len < UINT32_MAX ? 0 : 1;
2499 (version == 1) ? avio_wb32(pb, 120) : avio_wb32(pb, 108); /* size */
2500 ffio_wfourcc(pb, "mvhd");
2501 avio_w8(pb, version);
2502 avio_wb24(pb, 0); /* flags */
2504 avio_wb64(pb, mov->time);
2505 avio_wb64(pb, mov->time);
2507 avio_wb32(pb, mov->time); /* creation time */
2508 avio_wb32(pb, mov->time); /* modification time */
2510 avio_wb32(pb, MOV_TIMESCALE);
2511 (version == 1) ? avio_wb64(pb, max_track_len) : avio_wb32(pb, max_track_len); /* duration of longest track */
2513 avio_wb32(pb, 0x00010000); /* reserved (preferred rate) 1.0 = normal */
2514 avio_wb16(pb, 0x0100); /* reserved (preferred volume) 1.0 = normal */
2515 avio_wb16(pb, 0); /* reserved */
2516 avio_wb32(pb, 0); /* reserved */
2517 avio_wb32(pb, 0); /* reserved */
2519 /* Matrix structure */
2520 write_matrix(pb, 1, 0, 0, 1, 0, 0);
2522 avio_wb32(pb, 0); /* reserved (preview time) */
2523 avio_wb32(pb, 0); /* reserved (preview duration) */
2524 avio_wb32(pb, 0); /* reserved (poster time) */
2525 avio_wb32(pb, 0); /* reserved (selection time) */
2526 avio_wb32(pb, 0); /* reserved (selection duration) */
2527 avio_wb32(pb, 0); /* reserved (current time) */
2528 avio_wb32(pb, max_track_id + 1); /* Next track id */
2532 static int mov_write_itunes_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov,
2535 avio_wb32(pb, 33); /* size */
2536 ffio_wfourcc(pb, "hdlr");
2539 ffio_wfourcc(pb, "mdir");
2540 ffio_wfourcc(pb, "appl");
2547 /* helper function to write a data tag with the specified string as data */
2548 static int mov_write_string_data_tag(AVIOContext *pb, const char *data, int lang, int long_style)
2551 int size = 16 + strlen(data);
2552 avio_wb32(pb, size); /* size */
2553 ffio_wfourcc(pb, "data");
2556 avio_write(pb, data, strlen(data));
2560 lang = ff_mov_iso639_to_lang("und", 1);
2561 avio_wb16(pb, strlen(data)); /* string length */
2562 avio_wb16(pb, lang);
2563 avio_write(pb, data, strlen(data));
2564 return strlen(data) + 4;
2568 static int mov_write_string_tag(AVIOContext *pb, const char *name,
2569 const char *value, int lang, int long_style)
2572 if (value && value[0]) {
2573 int64_t pos = avio_tell(pb);
2574 avio_wb32(pb, 0); /* size */
2575 ffio_wfourcc(pb, name);
2576 mov_write_string_data_tag(pb, value, lang, long_style);
2577 size = update_size(pb, pos);
2582 static int mov_write_string_metadata(AVFormatContext *s, AVIOContext *pb,
2583 const char *name, const char *tag,
2586 int l, lang = 0, len, len2;
2587 AVDictionaryEntry *t, *t2 = NULL;
2590 if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
2593 len = strlen(t->key);
2594 snprintf(tag2, sizeof(tag2), "%s-", tag);
2595 while ((t2 = av_dict_get(s->metadata, tag2, t2, AV_DICT_IGNORE_SUFFIX))) {
2596 len2 = strlen(t2->key);
2597 if (len2 == len + 4 && !strcmp(t->value, t2->value)
2598 && (l = ff_mov_iso639_to_lang(&t2->key[len2 - 3], 1)) >= 0) {
2603 return mov_write_string_tag(pb, name, t->value, lang, long_style);
2606 /* iTunes bpm number */
2607 static int mov_write_tmpo_tag(AVIOContext *pb, AVFormatContext *s)
2609 AVDictionaryEntry *t = av_dict_get(s->metadata, "tmpo", NULL, 0);
2610 int size = 0, tmpo = t ? atoi(t->value) : 0;
2613 avio_wb32(pb, size);
2614 ffio_wfourcc(pb, "tmpo");
2615 avio_wb32(pb, size-8); /* size */
2616 ffio_wfourcc(pb, "data");
2617 avio_wb32(pb, 0x15); //type specifier
2619 avio_wb16(pb, tmpo); // data
2624 /* iTunes track or disc number */
2625 static int mov_write_trkn_tag(AVIOContext *pb, MOVMuxContext *mov,
2626 AVFormatContext *s, int disc)
2628 AVDictionaryEntry *t = av_dict_get(s->metadata,
2629 disc ? "disc" : "track",
2631 int size = 0, track = t ? atoi(t->value) : 0;
2634 char *slash = strchr(t->value, '/');
2636 tracks = atoi(slash + 1);
2637 avio_wb32(pb, 32); /* size */
2638 ffio_wfourcc(pb, disc ? "disk" : "trkn");
2639 avio_wb32(pb, 24); /* size */
2640 ffio_wfourcc(pb, "data");
2641 avio_wb32(pb, 0); // 8 bytes empty
2643 avio_wb16(pb, 0); // empty
2644 avio_wb16(pb, track); // track / disc number
2645 avio_wb16(pb, tracks); // total track / disc number
2646 avio_wb16(pb, 0); // empty
2652 static int mov_write_int8_metadata(AVFormatContext *s, AVIOContext *pb,
2653 const char *name, const char *tag,
2656 AVDictionaryEntry *t = NULL;
2658 int size = 24 + len;
2660 if (len != 1 && len != 4)
2663 if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
2665 num = atoi(t->value);
2667 avio_wb32(pb, size);
2668 ffio_wfourcc(pb, name);
2669 avio_wb32(pb, size - 8);
2670 ffio_wfourcc(pb, "data");
2671 avio_wb32(pb, 0x15);
2673 if (len==4) avio_wb32(pb, num);
2674 else avio_w8 (pb, num);
2679 /* iTunes meta data list */
2680 static int mov_write_ilst_tag(AVIOContext *pb, MOVMuxContext *mov,
2683 int64_t pos = avio_tell(pb);
2684 avio_wb32(pb, 0); /* size */
2685 ffio_wfourcc(pb, "ilst");
2686 mov_write_string_metadata(s, pb, "\251nam", "title" , 1);
2687 mov_write_string_metadata(s, pb, "\251ART", "artist" , 1);
2688 mov_write_string_metadata(s, pb, "aART", "album_artist", 1);
2689 mov_write_string_metadata(s, pb, "\251wrt", "composer" , 1);
2690 mov_write_string_metadata(s, pb, "\251alb", "album" , 1);
2691 mov_write_string_metadata(s, pb, "\251day", "date" , 1);
2693 !mov_write_string_metadata(s, pb, "\251too", "encoding_tool", 1))
2694 mov_write_string_tag(pb, "\251too", LIBAVFORMAT_IDENT, 0, 1);
2695 mov_write_string_metadata(s, pb, "\251cmt", "comment" , 1);
2696 mov_write_string_metadata(s, pb, "\251gen", "genre" , 1);
2697 mov_write_string_metadata(s, pb, "\251cpy", "copyright", 1);
2698 mov_write_string_metadata(s, pb, "\251grp", "grouping" , 1);
2699 mov_write_string_metadata(s, pb, "\251lyr", "lyrics" , 1);
2700 mov_write_string_metadata(s, pb, "desc", "description",1);
2701 mov_write_string_metadata(s, pb, "ldes", "synopsis" , 1);
2702 mov_write_string_metadata(s, pb, "tvsh", "show" , 1);
2703 mov_write_string_metadata(s, pb, "tven", "episode_id",1);
2704 mov_write_string_metadata(s, pb, "tvnn", "network" , 1);
2705 mov_write_int8_metadata (s, pb, "tves", "episode_sort",4);
2706 mov_write_int8_metadata (s, pb, "tvsn", "season_number",4);
2707 mov_write_int8_metadata (s, pb, "stik", "media_type",1);
2708 mov_write_int8_metadata (s, pb, "hdvd", "hd_video", 1);
2709 mov_write_int8_metadata (s, pb, "pgap", "gapless_playback",1);
2710 mov_write_int8_metadata (s, pb, "cpil", "compilation", 1);
2711 mov_write_trkn_tag(pb, mov, s, 0); // track number
2712 mov_write_trkn_tag(pb, mov, s, 1); // disc number
2713 mov_write_tmpo_tag(pb, s);
2714 return update_size(pb, pos);
2717 /* iTunes meta data tag */
2718 static int mov_write_meta_tag(AVIOContext *pb, MOVMuxContext *mov,
2722 int64_t pos = avio_tell(pb);
2723 avio_wb32(pb, 0); /* size */
2724 ffio_wfourcc(pb, "meta");
2726 mov_write_itunes_hdlr_tag(pb, mov, s);
2727 mov_write_ilst_tag(pb, mov, s);
2728 size = update_size(pb, pos);
2732 static int mov_write_raw_metadata_tag(AVFormatContext *s, AVIOContext *pb,
2733 const char *name, const char *key)
2736 AVDictionaryEntry *t;
2738 if (!(t = av_dict_get(s->metadata, key, NULL, 0)))
2741 len = strlen(t->value);
2744 avio_wb32(pb, size);
2745 ffio_wfourcc(pb, name);
2746 avio_write(pb, t->value, len);
2752 static int ascii_to_wc(AVIOContext *pb, const uint8_t *b)
2756 GET_UTF8(val, *b++, return -1;)
2759 avio_wb16(pb, 0x00);
2763 static uint16_t language_code(const char *str)
2765 return (((str[0] - 0x60) & 0x1F) << 10) +
2766 (((str[1] - 0x60) & 0x1F) << 5) +
2767 (( str[2] - 0x60) & 0x1F);
2770 static int mov_write_3gp_udta_tag(AVIOContext *pb, AVFormatContext *s,
2771 const char *tag, const char *str)
2773 int64_t pos = avio_tell(pb);
2774 AVDictionaryEntry *t = av_dict_get(s->metadata, str, NULL, 0);
2775 if (!t || !utf8len(t->value))
2777 avio_wb32(pb, 0); /* size */
2778 ffio_wfourcc(pb, tag); /* type */
2779 avio_wb32(pb, 0); /* version + flags */
2780 if (!strcmp(tag, "yrrc"))
2781 avio_wb16(pb, atoi(t->value));
2783 avio_wb16(pb, language_code("eng")); /* language */
2784 avio_write(pb, t->value, strlen(t->value) + 1); /* UTF8 string value */
2785 if (!strcmp(tag, "albm") &&
2786 (t = av_dict_get(s->metadata, "track", NULL, 0)))
2787 avio_w8(pb, atoi(t->value));
2789 return update_size(pb, pos);
2792 static int mov_write_chpl_tag(AVIOContext *pb, AVFormatContext *s)
2794 int64_t pos = avio_tell(pb);
2795 int i, nb_chapters = FFMIN(s->nb_chapters, 255);
2797 avio_wb32(pb, 0); // size
2798 ffio_wfourcc(pb, "chpl");
2799 avio_wb32(pb, 0x01000000); // version + flags
2800 avio_wb32(pb, 0); // unknown
2801 avio_w8(pb, nb_chapters);
2803 for (i = 0; i < nb_chapters; i++) {
2804 AVChapter *c = s->chapters[i];
2805 AVDictionaryEntry *t;
2806 avio_wb64(pb, av_rescale_q(c->start, c->time_base, (AVRational){1,10000000}));
2808 if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
2809 int len = FFMIN(strlen(t->value), 255);
2811 avio_write(pb, t->value, len);
2815 return update_size(pb, pos);
2818 static int mov_write_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
2821 AVIOContext *pb_buf;
2825 ret = avio_open_dyn_buf(&pb_buf);
2829 if (mov->mode & MODE_3GP) {
2830 mov_write_3gp_udta_tag(pb_buf, s, "perf", "artist");
2831 mov_write_3gp_udta_tag(pb_buf, s, "titl", "title");
2832 mov_write_3gp_udta_tag(pb_buf, s, "auth", "author");
2833 mov_write_3gp_udta_tag(pb_buf, s, "gnre", "genre");
2834 mov_write_3gp_udta_tag(pb_buf, s, "dscp", "comment");
2835 mov_write_3gp_udta_tag(pb_buf, s, "albm", "album");
2836 mov_write_3gp_udta_tag(pb_buf, s, "cprt", "copyright");
2837 mov_write_3gp_udta_tag(pb_buf, s, "yrrc", "date");
2838 } else if (mov->mode == MODE_MOV) { // the title field breaks gtkpod with mp4 and my suspicion is that stuff is not valid in mp4
2839 mov_write_string_metadata(s, pb_buf, "\251ART", "artist", 0);
2840 mov_write_string_metadata(s, pb_buf, "\251nam", "title", 0);
2841 mov_write_string_metadata(s, pb_buf, "\251aut", "author", 0);
2842 mov_write_string_metadata(s, pb_buf, "\251alb", "album", 0);
2843 mov_write_string_metadata(s, pb_buf, "\251day", "date", 0);
2844 mov_write_string_metadata(s, pb_buf, "\251swr", "encoder", 0);
2845 // currently ignored by mov.c
2846 mov_write_string_metadata(s, pb_buf, "\251des", "comment", 0);
2847 // add support for libquicktime, this atom is also actually read by mov.c
2848 mov_write_string_metadata(s, pb_buf, "\251cmt", "comment", 0);
2849 mov_write_string_metadata(s, pb_buf, "\251gen", "genre", 0);
2850 mov_write_string_metadata(s, pb_buf, "\251cpy", "copyright", 0);
2851 mov_write_raw_metadata_tag(s, pb_buf, "XMP_", "xmp");
2853 /* iTunes meta data */
2854 mov_write_meta_tag(pb_buf, mov, s);
2857 if (s->nb_chapters && !(mov->flags & FF_MOV_FLAG_DISABLE_CHPL))
2858 mov_write_chpl_tag(pb_buf, s);
2860 if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) {
2861 avio_wb32(pb, size + 8);
2862 ffio_wfourcc(pb, "udta");
2863 avio_write(pb, buf, size);
2870 static void mov_write_psp_udta_tag(AVIOContext *pb,
2871 const char *str, const char *lang, int type)
2873 int len = utf8len(str) + 1;
2876 avio_wb16(pb, len * 2 + 10); /* size */
2877 avio_wb32(pb, type); /* type */
2878 avio_wb16(pb, language_code(lang)); /* language */
2879 avio_wb16(pb, 0x01); /* ? */
2880 ascii_to_wc(pb, str);
2883 static int mov_write_uuidusmt_tag(AVIOContext *pb, AVFormatContext *s)
2885 MOVMuxContext *mov = s->priv_data;
2886 AVDictionaryEntry *title = av_dict_get(s->metadata, "title", NULL, 0);
2890 pos = avio_tell(pb);
2891 avio_wb32(pb, 0); /* size placeholder*/
2892 ffio_wfourcc(pb, "uuid");
2893 ffio_wfourcc(pb, "USMT");
2894 avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
2895 avio_wb32(pb, 0xbb88695c);
2896 avio_wb32(pb, 0xfac9c740);
2898 pos2 = avio_tell(pb);
2899 avio_wb32(pb, 0); /* size placeholder*/
2900 ffio_wfourcc(pb, "MTDT");
2904 avio_wb16(pb, 0x0C); /* size */
2905 avio_wb32(pb, 0x0B); /* type */
2906 avio_wb16(pb, language_code("und")); /* language */
2907 avio_wb16(pb, 0x0); /* ? */
2908 avio_wb16(pb, 0x021C); /* data */
2911 mov_write_psp_udta_tag(pb, LIBAVCODEC_IDENT, "eng", 0x04);
2912 mov_write_psp_udta_tag(pb, title->value, "eng", 0x01);
2913 mov_write_psp_udta_tag(pb, "2006/04/01 11:11:11", "und", 0x03);
2915 update_size(pb, pos2);
2916 return update_size(pb, pos);
2922 static void build_chunks(MOVTrack *trk)
2925 MOVIentry *chunk = &trk->cluster[0];
2926 uint64_t chunkSize = chunk->size;
2927 chunk->chunkNum = 1;
2928 if (trk->chunkCount)
2930 trk->chunkCount = 1;
2931 for (i = 1; i<trk->entry; i++){
2932 if (chunk->pos + chunkSize == trk->cluster[i].pos &&
2933 chunkSize + trk->cluster[i].size < (1<<20)){
2934 chunkSize += trk->cluster[i].size;
2935 chunk->samples_in_chunk += trk->cluster[i].entries;
2937 trk->cluster[i].chunkNum = chunk->chunkNum+1;
2938 chunk=&trk->cluster[i];
2939 chunkSize = chunk->size;
2945 static int mov_write_moov_tag(AVIOContext *pb, MOVMuxContext *mov,
2949 int64_t pos = avio_tell(pb);
2950 avio_wb32(pb, 0); /* size placeholder*/
2951 ffio_wfourcc(pb, "moov");
2953 for (i = 0; i < mov->nb_streams; i++) {
2954 if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
2957 mov->tracks[i].time = mov->time;
2958 mov->tracks[i].track_id = i + 1;
2960 if (mov->tracks[i].entry)
2961 build_chunks(&mov->tracks[i]);
2964 if (mov->chapter_track)
2965 for (i = 0; i < s->nb_streams; i++) {
2966 mov->tracks[i].tref_tag = MKTAG('c','h','a','p');
2967 mov->tracks[i].tref_id = mov->tracks[mov->chapter_track].track_id;
2969 for (i = 0; i < mov->nb_streams; i++) {
2970 if (mov->tracks[i].tag == MKTAG('r','t','p',' ')) {
2971 mov->tracks[i].tref_tag = MKTAG('h','i','n','t');
2972 mov->tracks[i].tref_id =
2973 mov->tracks[mov->tracks[i].src_track].track_id;
2976 for (i = 0; i < mov->nb_streams; i++) {
2977 if (mov->tracks[i].tag == MKTAG('t','m','c','d')) {
2978 int src_trk = mov->tracks[i].src_track;
2979 mov->tracks[src_trk].tref_tag = mov->tracks[i].tag;
2980 mov->tracks[src_trk].tref_id = mov->tracks[i].track_id;
2981 //src_trk may have a different timescale than the tmcd track
2982 mov->tracks[i].track_duration = av_rescale(mov->tracks[src_trk].track_duration,
2983 mov->tracks[i].timescale,
2984 mov->tracks[src_trk].timescale);
2988 mov_write_mvhd_tag(pb, mov);
2989 if (mov->mode != MODE_MOV && !mov->iods_skip)
2990 mov_write_iods_tag(pb, mov);
2991 for (i = 0; i < mov->nb_streams; i++) {
2992 if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_FRAGMENT) {
2993 mov_write_trak_tag(pb, mov, &(mov->tracks[i]), i < s->nb_streams ? s->streams[i] : NULL);
2996 if (mov->flags & FF_MOV_FLAG_FRAGMENT)
2997 mov_write_mvex_tag(pb, mov); /* QuickTime requires trak to precede this */
2999 if (mov->mode == MODE_PSP)
3000 mov_write_uuidusmt_tag(pb, s);
3002 mov_write_udta_tag(pb, mov, s);
3004 return update_size(pb, pos);
3007 static void param_write_int(AVIOContext *pb, const char *name, int value)
3009 avio_printf(pb, "<param name=\"%s\" value=\"%d\" valuetype=\"data\"/>\n", name, value);
3012 static void param_write_string(AVIOContext *pb, const char *name, const char *value)
3014 avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, value);
3017 static void param_write_hex(AVIOContext *pb, const char *name, const uint8_t *value, int len)
3020 len = FFMIN(sizeof(buf) / 2 - 1, len);
3021 ff_data_to_hex(buf, value, len, 0);
3022 buf[2 * len] = '\0';
3023 avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, buf);
3026 static int mov_write_isml_manifest(AVIOContext *pb, MOVMuxContext *mov)
3028 int64_t pos = avio_tell(pb);
3030 static const uint8_t uuid[] = {
3031 0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd,
3032 0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66
3036 ffio_wfourcc(pb, "uuid");
3037 avio_write(pb, uuid, sizeof(uuid));
3040 avio_printf(pb, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
3041 avio_printf(pb, "<smil xmlns=\"http://www.w3.org/2001/SMIL20/Language\">\n");
3042 avio_printf(pb, "<head>\n");
3044 avio_printf(pb, "<meta name=\"creator\" content=\"%s\" />\n",
3046 avio_printf(pb, "</head>\n");
3047 avio_printf(pb, "<body>\n");
3048 avio_printf(pb, "<switch>\n");
3049 for (i = 0; i < mov->nb_streams; i++) {
3050 MOVTrack *track = &mov->tracks[i];
3052 /* track->track_id is initialized in write_moov, and thus isn't known
3054 int track_id = i + 1;
3056 if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) {
3058 } else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO) {
3063 avio_printf(pb, "<%s systemBitrate=\"%d\">\n", type,
3064 track->enc->bit_rate);
3065 param_write_int(pb, "systemBitrate", track->enc->bit_rate);
3066 param_write_int(pb, "trackID", track_id);
3067 if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) {
3068 if (track->enc->codec_id == AV_CODEC_ID_H264) {
3070 int size = track->enc->extradata_size;
3071 if (!ff_avc_write_annexb_extradata(track->enc->extradata, &ptr,
3073 param_write_hex(pb, "CodecPrivateData",
3074 ptr ? ptr : track->enc->extradata,
3078 param_write_string(pb, "FourCC", "H264");
3079 } else if (track->enc->codec_id == AV_CODEC_ID_VC1) {
3080 param_write_string(pb, "FourCC", "WVC1");
3081 param_write_hex(pb, "CodecPrivateData", track->enc->extradata,
3082 track->enc->extradata_size);
3084 param_write_int(pb, "MaxWidth", track->enc->width);
3085 param_write_int(pb, "MaxHeight", track->enc->height);
3086 param_write_int(pb, "DisplayWidth", track->enc->width);
3087 param_write_int(pb, "DisplayHeight", track->enc->height);
3089 if (track->enc->codec_id == AV_CODEC_ID_AAC) {
3090 param_write_string(pb, "FourCC", "AACL");
3091 } else if (track->enc->codec_id == AV_CODEC_ID_WMAPRO) {
3092 param_write_string(pb, "FourCC", "WMAP");
3094 param_write_hex(pb, "CodecPrivateData", track->enc->extradata,
3095 track->enc->extradata_size);
3096 param_write_int(pb, "AudioTag", ff_codec_get_tag(ff_codec_wav_tags,
3097 track->enc->codec_id));
3098 param_write_int(pb, "Channels", track->enc->channels);
3099 param_write_int(pb, "SamplingRate", track->enc->sample_rate);
3100 param_write_int(pb, "BitsPerSample", 16);
3101 param_write_int(pb, "PacketSize", track->enc->block_align ?
3102 track->enc->block_align : 4);
3104 avio_printf(pb, "</%s>\n", type);
3106 avio_printf(pb, "</switch>\n");
3107 avio_printf(pb, "</body>\n");
3108 avio_printf(pb, "</smil>\n");
3110 return update_size(pb, pos);
3113 static int mov_write_mfhd_tag(AVIOContext *pb, MOVMuxContext *mov)
3116 ffio_wfourcc(pb, "mfhd");
3118 avio_wb32(pb, mov->fragments);
3122 static int mov_write_tfhd_tag(AVIOContext *pb, MOVMuxContext *mov,
3123 MOVTrack *track, int64_t moof_offset)
3125 int64_t pos = avio_tell(pb);
3126 uint32_t flags = MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
3127 MOV_TFHD_BASE_DATA_OFFSET;
3128 if (!track->entry) {
3129 flags |= MOV_TFHD_DURATION_IS_EMPTY;
3131 flags |= MOV_TFHD_DEFAULT_FLAGS;
3133 if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET)
3134 flags &= ~MOV_TFHD_BASE_DATA_OFFSET;
3135 if (mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) {
3136 flags &= ~MOV_TFHD_BASE_DATA_OFFSET;
3137 flags |= MOV_TFHD_DEFAULT_BASE_IS_MOOF;
3140 /* Don't set a default sample size, the silverlight player refuses
3141 * to play files with that set. Don't set a default sample duration,
3142 * WMP freaks out if it is set. Don't set a base data offset, PIFF
3143 * file format says it MUST NOT be set. */
3144 if (track->mode == MODE_ISM)
3145 flags &= ~(MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
3146 MOV_TFHD_BASE_DATA_OFFSET);
3148 avio_wb32(pb, 0); /* size placeholder */
3149 ffio_wfourcc(pb, "tfhd");
3150 avio_w8(pb, 0); /* version */
3151 avio_wb24(pb, flags);
3153 avio_wb32(pb, track->track_id); /* track-id */
3154 if (flags & MOV_TFHD_BASE_DATA_OFFSET)
3155 avio_wb64(pb, moof_offset);
3156 if (flags & MOV_TFHD_DEFAULT_DURATION) {
3157 track->default_duration = get_cluster_duration(track, 0);
3158 avio_wb32(pb, track->default_duration);
3160 if (flags & MOV_TFHD_DEFAULT_SIZE) {
3161 track->default_size = track->entry ? track->cluster[0].size : 1;
3162 avio_wb32(pb, track->default_size);
3164 track->default_size = -1;
3166 if (flags & MOV_TFHD_DEFAULT_FLAGS) {
3167 track->default_sample_flags =
3168 track->enc->codec_type == AVMEDIA_TYPE_VIDEO ?
3169 (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC) :
3170 MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO;
3171 avio_wb32(pb, track->default_sample_flags);
3174 return update_size(pb, pos);
3177 static uint32_t get_sample_flags(MOVTrack *track, MOVIentry *entry)
3179 return entry->flags & MOV_SYNC_SAMPLE ? MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO :
3180 (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC);
3183 static int mov_write_trun_tag(AVIOContext *pb, MOVMuxContext *mov,
3184 MOVTrack *track, int moof_size)
3186 int64_t pos = avio_tell(pb);
3187 uint32_t flags = MOV_TRUN_DATA_OFFSET;
3190 for (i = 0; i < track->entry; i++) {
3191 if (get_cluster_duration(track, i) != track->default_duration)
3192 flags |= MOV_TRUN_SAMPLE_DURATION;
3193 if (track->cluster[i].size != track->default_size)
3194 flags |= MOV_TRUN_SAMPLE_SIZE;
3195 if (i > 0 && get_sample_flags(track, &track->cluster[i]) != track->default_sample_flags)
3196 flags |= MOV_TRUN_SAMPLE_FLAGS;
3198 if (!(flags & MOV_TRUN_SAMPLE_FLAGS))
3199 flags |= MOV_TRUN_FIRST_SAMPLE_FLAGS;
3200 if (track->flags & MOV_TRACK_CTTS)
3201 flags |= MOV_TRUN_SAMPLE_CTS;
3203 avio_wb32(pb, 0); /* size placeholder */
3204 ffio_wfourcc(pb, "trun");
3205 avio_w8(pb, 0); /* version */
3206 avio_wb24(pb, flags);
3208 avio_wb32(pb, track->entry); /* sample count */
3209 if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET &&
3210 !(mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) &&
3212 avio_wb32(pb, 0); /* Later tracks follow immediately after the previous one */
3214 avio_wb32(pb, moof_size + 8 + track->data_offset +
3215 track->cluster[0].pos); /* data offset */
3216 if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS)
3217 avio_wb32(pb, get_sample_flags(track, &track->cluster[0]));
3219 for (i = 0; i < track->entry; i++) {
3220 if (flags & MOV_TRUN_SAMPLE_DURATION)
3221 avio_wb32(pb, get_cluster_duration(track, i));
3222 if (flags & MOV_TRUN_SAMPLE_SIZE)
3223 avio_wb32(pb, track->cluster[i].size);
3224 if (flags & MOV_TRUN_SAMPLE_FLAGS)
3225 avio_wb32(pb, get_sample_flags(track, &track->cluster[i]));
3226 if (flags & MOV_TRUN_SAMPLE_CTS)
3227 avio_wb32(pb, track->cluster[i].cts);
3230 mov->first_trun = 0;
3231 return update_size(pb, pos);
3234 static int mov_write_tfxd_tag(AVIOContext *pb, MOVTrack *track)
3236 int64_t pos = avio_tell(pb);
3237 static const uint8_t uuid[] = {
3238 0x6d, 0x1d, 0x9b, 0x05, 0x42, 0xd5, 0x44, 0xe6,
3239 0x80, 0xe2, 0x14, 0x1d, 0xaf, 0xf7, 0x57, 0xb2
3242 avio_wb32(pb, 0); /* size placeholder */
3243 ffio_wfourcc(pb, "uuid");
3244 avio_write(pb, uuid, sizeof(uuid));
3247 avio_wb64(pb, track->frag_start);
3248 avio_wb64(pb, track->start_dts + track->track_duration -
3249 track->cluster[0].dts);
3251 return update_size(pb, pos);
3254 static int mov_write_tfrf_tag(AVIOContext *pb, MOVMuxContext *mov,
3255 MOVTrack *track, int entry)
3257 int n = track->nb_frag_info - 1 - entry, i;
3258 int size = 8 + 16 + 4 + 1 + 16*n;
3259 static const uint8_t uuid[] = {
3260 0xd4, 0x80, 0x7e, 0xf2, 0xca, 0x39, 0x46, 0x95,
3261 0x8e, 0x54, 0x26, 0xcb, 0x9e, 0x46, 0xa7, 0x9f
3267 avio_seek(pb, track->frag_info[entry].tfrf_offset, SEEK_SET);
3268 avio_wb32(pb, size);
3269 ffio_wfourcc(pb, "uuid");
3270 avio_write(pb, uuid, sizeof(uuid));
3274 for (i = 0; i < n; i++) {
3275 int index = entry + 1 + i;
3276 avio_wb64(pb, track->frag_info[index].time);
3277 avio_wb64(pb, track->frag_info[index].duration);
3279 if (n < mov->ism_lookahead) {
3280 int free_size = 16 * (mov->ism_lookahead - n);
3281 avio_wb32(pb, free_size);
3282 ffio_wfourcc(pb, "free");
3283 ffio_fill(pb, 0, free_size - 8);
3289 static int mov_write_tfrf_tags(AVIOContext *pb, MOVMuxContext *mov,
3292 int64_t pos = avio_tell(pb);
3294 for (i = 0; i < mov->ism_lookahead; i++) {
3295 /* Update the tfrf tag for the last ism_lookahead fragments,
3296 * nb_frag_info - 1 is the next fragment to be written. */
3297 mov_write_tfrf_tag(pb, mov, track, track->nb_frag_info - 2 - i);
3299 avio_seek(pb, pos, SEEK_SET);
3303 static int mov_add_tfra_entries(AVIOContext *pb, MOVMuxContext *mov, int tracks,
3307 for (i = 0; i < mov->nb_streams; i++) {
3308 MOVTrack *track = &mov->tracks[i];
3309 MOVFragmentInfo *info;
3310 if ((tracks >= 0 && i != tracks) || !track->entry)
3312 track->nb_frag_info++;
3313 if (track->nb_frag_info >= track->frag_info_capacity) {
3314 unsigned new_capacity = track->nb_frag_info + MOV_FRAG_INFO_ALLOC_INCREMENT;
3315 if (av_reallocp_array(&track->frag_info,
3317 sizeof(*track->frag_info)))
3318 return AVERROR(ENOMEM);
3319 track->frag_info_capacity = new_capacity;
3321 info = &track->frag_info[track->nb_frag_info - 1];
3322 info->offset = avio_tell(pb);
3324 // Try to recreate the original pts for the first packet
3325 // from the fields we have stored
3326 info->time = track->start_dts + track->frag_start +
3327 track->cluster[0].cts;
3328 // If the pts is less than zero, we will have trimmed
3329 // away parts of the media track using an edit list,
3330 // and the corresponding start presentation time is zero.
3333 info->duration = track->start_dts + track->track_duration -
3334 track->cluster[0].dts;
3335 info->tfrf_offset = 0;
3336 mov_write_tfrf_tags(pb, mov, track);
3341 static int mov_write_tfdt_tag(AVIOContext *pb, MOVTrack *track)
3343 int64_t pos = avio_tell(pb);
3345 avio_wb32(pb, 0); /* size */
3346 ffio_wfourcc(pb, "tfdt");
3347 avio_w8(pb, 1); /* version */
3349 avio_wb64(pb, track->frag_start);
3350 return update_size(pb, pos);
3353 static int mov_write_traf_tag(AVIOContext *pb, MOVMuxContext *mov,
3354 MOVTrack *track, int64_t moof_offset,
3357 int64_t pos = avio_tell(pb);
3358 avio_wb32(pb, 0); /* size placeholder */
3359 ffio_wfourcc(pb, "traf");
3361 mov_write_tfhd_tag(pb, mov, track, moof_offset);
3362 if (mov->mode != MODE_ISM)
3363 mov_write_tfdt_tag(pb, track);
3364 mov_write_trun_tag(pb, mov, track, moof_size);
3365 if (mov->mode == MODE_ISM) {
3366 mov_write_tfxd_tag(pb, track);
3368 if (mov->ism_lookahead) {
3369 int i, size = 16 + 4 + 1 + 16 * mov->ism_lookahead;
3371 if (track->nb_frag_info > 0) {
3372 MOVFragmentInfo *info = &track->frag_info[track->nb_frag_info - 1];
3373 if (!info->tfrf_offset)
3374 info->tfrf_offset = avio_tell(pb);
3376 avio_wb32(pb, 8 + size);
3377 ffio_wfourcc(pb, "free");
3378 for (i = 0; i < size; i++)
3383 return update_size(pb, pos);
3386 static int mov_write_moof_tag_internal(AVIOContext *pb, MOVMuxContext *mov,
3387 int tracks, int moof_size)
3389 int64_t pos = avio_tell(pb);
3392 avio_wb32(pb, 0); /* size placeholder */
3393 ffio_wfourcc(pb, "moof");
3394 mov->first_trun = 1;
3396 mov_write_mfhd_tag(pb, mov);
3397 for (i = 0; i < mov->nb_streams; i++) {
3398 MOVTrack *track = &mov->tracks[i];
3399 if (tracks >= 0 && i != tracks)
3403 mov_write_traf_tag(pb, mov, track, pos, moof_size);
3406 return update_size(pb, pos);
3409 static int mov_write_sidx_tag(AVIOContext *pb,
3410 MOVTrack *track, int ref_size, int total_sidx_size)
3412 int64_t pos = avio_tell(pb), offset_pos, end_pos;
3413 int64_t presentation_time, duration, offset;
3414 int starts_with_SAP, i, entries;
3418 presentation_time = track->start_dts + track->frag_start +
3419 track->cluster[0].cts;
3420 duration = track->start_dts + track->track_duration -
3421 track->cluster[0].dts;
3422 starts_with_SAP = track->cluster[0].flags & MOV_SYNC_SAMPLE;
3424 entries = track->nb_frag_info;
3425 presentation_time = track->frag_info[0].time;
3428 // pts<0 should be cut away using edts
3429 if (presentation_time < 0)
3430 presentation_time = 0;
3432 avio_wb32(pb, 0); /* size */
3433 ffio_wfourcc(pb, "sidx");
3434 avio_w8(pb, 1); /* version */
3436 avio_wb32(pb, track->track_id); /* reference_ID */
3437 avio_wb32(pb, track->timescale); /* timescale */
3438 avio_wb64(pb, presentation_time); /* earliest_presentation_time */
3439 offset_pos = avio_tell(pb);
3440 avio_wb64(pb, 0); /* first_offset (offset to referenced moof) */
3441 avio_wb16(pb, 0); /* reserved */
3443 avio_wb16(pb, entries); /* reference_count */
3444 for (i = 0; i < entries; i++) {
3445 if (!track->entry) {
3446 if (i > 1 && track->frag_info[i].offset != track->frag_info[i - 1].offset + track->frag_info[i - 1].size) {
3447 av_log(NULL, AV_LOG_ERROR, "Non-consecutive fragments, writing incorrect sidx\n");
3449 duration = track->frag_info[i].duration;
3450 ref_size = track->frag_info[i].size;
3451 starts_with_SAP = 1;
3453 avio_wb32(pb, (0 << 31) | (ref_size & 0x7fffffff)); /* reference_type (0 = media) | referenced_size */
3454 avio_wb32(pb, duration); /* subsegment_duration */
3455 avio_wb32(pb, (starts_with_SAP << 31) | (0 << 28) | 0); /* starts_with_SAP | SAP_type | SAP_delta_time */
3458 end_pos = avio_tell(pb);
3459 offset = pos + total_sidx_size - end_pos;
3460 avio_seek(pb, offset_pos, SEEK_SET);
3461 avio_wb64(pb, offset);
3462 avio_seek(pb, end_pos, SEEK_SET);
3463 return update_size(pb, pos);
3466 static int mov_write_sidx_tags(AVIOContext *pb, MOVMuxContext *mov,
3467 int tracks, int ref_size)
3470 AVIOContext *avio_buf;
3472 for (round = 0; round < 2; round++) {
3473 // First run one round to calculate the total size of all
3475 // This would be much simpler if we'd only write one sidx
3476 // atom, for the first track in the moof.
3478 if ((ret = ffio_open_null_buf(&avio_buf)) < 0)
3483 for (i = 0; i < mov->nb_streams; i++) {
3484 MOVTrack *track = &mov->tracks[i];
3485 if (tracks >= 0 && i != tracks)
3487 // When writing a sidx for the full file, entry is 0, but
3488 // we want to include all tracks. ref_size is 0 in this case,
3489 // since we read it from frag_info instead.
3490 if (!track->entry && ref_size > 0)
3492 total_size -= mov_write_sidx_tag(avio_buf, track, ref_size,
3496 total_size = ffio_close_null_buf(avio_buf);
3501 static int mov_write_moof_tag(AVIOContext *pb, MOVMuxContext *mov, int tracks,
3504 AVIOContext *avio_buf;
3507 if ((ret = ffio_open_null_buf(&avio_buf)) < 0)
3509 mov_write_moof_tag_internal(avio_buf, mov, tracks, 0);
3510 moof_size = ffio_close_null_buf(avio_buf);
3512 if (mov->flags & FF_MOV_FLAG_DASH && !(mov->flags & FF_MOV_FLAG_FASTSTART))
3513 mov_write_sidx_tags(pb, mov, tracks, moof_size + 8 + mdat_size);
3515 if ((ret = mov_add_tfra_entries(pb, mov, tracks, moof_size + 8 + mdat_size)) < 0)
3518 return mov_write_moof_tag_internal(pb, mov, tracks, moof_size);
3521 static int mov_write_tfra_tag(AVIOContext *pb, MOVTrack *track)
3523 int64_t pos = avio_tell(pb);
3526 avio_wb32(pb, 0); /* size placeholder */
3527 ffio_wfourcc(pb, "tfra");
3528 avio_w8(pb, 1); /* version */
3531 avio_wb32(pb, track->track_id);
3532 avio_wb32(pb, 0); /* length of traf/trun/sample num */
3533 avio_wb32(pb, track->nb_frag_info);
3534 for (i = 0; i < track->nb_frag_info; i++) {
3535 avio_wb64(pb, track->frag_info[i].time);
3536 avio_wb64(pb, track->frag_info[i].offset + track->data_offset);
3537 avio_w8(pb, 1); /* traf number */
3538 avio_w8(pb, 1); /* trun number */
3539 avio_w8(pb, 1); /* sample number */
3542 return update_size(pb, pos);
3545 static int mov_write_mfra_tag(AVIOContext *pb, MOVMuxContext *mov)
3547 int64_t pos = avio_tell(pb);
3550 avio_wb32(pb, 0); /* size placeholder */
3551 ffio_wfourcc(pb, "mfra");
3552 /* An empty mfra atom is enough to indicate to the publishing point that
3553 * the stream has ended. */
3554 if (mov->flags & FF_MOV_FLAG_ISML)
3555 return update_size(pb, pos);
3557 for (i = 0; i < mov->nb_streams; i++) {
3558 MOVTrack *track = &mov->tracks[i];
3559 if (track->nb_frag_info)
3560 mov_write_tfra_tag(pb, track);
3564 ffio_wfourcc(pb, "mfro");
3565 avio_wb32(pb, 0); /* version + flags */
3566 avio_wb32(pb, avio_tell(pb) + 4 - pos);
3568 return update_size(pb, pos);
3571 static int mov_write_mdat_tag(AVIOContext *pb, MOVMuxContext *mov)
3573 avio_wb32(pb, 8); // placeholder for extended size field (64 bit)
3574 ffio_wfourcc(pb, mov->mode == MODE_MOV ? "wide" : "free");
3576 mov->mdat_pos = avio_tell(pb);
3577 avio_wb32(pb, 0); /* size placeholder*/
3578 ffio_wfourcc(pb, "mdat");
3582 /* TODO: This needs to be more general */
3583 static int mov_write_ftyp_tag(AVIOContext *pb, AVFormatContext *s)
3585 MOVMuxContext *mov = s->priv_data;
3586 int64_t pos = avio_tell(pb);
3587 int has_h264 = 0, has_video = 0;
3591 for (i = 0; i < s->nb_streams; i++) {
3592 AVStream *st = s->streams[i];
3593 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
3595 if (st->codec->codec_id == AV_CODEC_ID_H264)
3599 avio_wb32(pb, 0); /* size */
3600 ffio_wfourcc(pb, "ftyp");
3602 if (mov->major_brand && strlen(mov->major_brand) >= 4)
3603 ffio_wfourcc(pb, mov->major_brand);
3604 else if (mov->mode == MODE_3GP) {
3605 ffio_wfourcc(pb, has_h264 ? "3gp6" : "3gp4");
3606 minor = has_h264 ? 0x100 : 0x200;
3607 } else if (mov->mode & MODE_3G2) {
3608 ffio_wfourcc(pb, has_h264 ? "3g2b" : "3g2a");
3609 minor = has_h264 ? 0x20000 : 0x10000;
3610 } else if (mov->mode == MODE_PSP)
3611 ffio_wfourcc(pb, "MSNV");
3612 else if (mov->mode == MODE_MP4 && mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)
3613 ffio_wfourcc(pb, "iso5"); // Required when using default-base-is-moof
3614 else if (mov->mode == MODE_MP4)
3615 ffio_wfourcc(pb, "isom");
3616 else if (mov->mode == MODE_IPOD)
3617 ffio_wfourcc(pb, has_video ? "M4V ":"M4A ");
3618 else if (mov->mode == MODE_ISM)
3619 ffio_wfourcc(pb, "isml");
3620 else if (mov->mode == MODE_F4V)
3621 ffio_wfourcc(pb, "f4v ");
3623 ffio_wfourcc(pb, "qt ");
3625 avio_wb32(pb, minor);
3627 if (mov->mode == MODE_MOV)
3628 ffio_wfourcc(pb, "qt ");
3629 else if (mov->mode == MODE_ISM) {
3630 ffio_wfourcc(pb, "piff");
3631 } else if (!(mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)) {
3632 ffio_wfourcc(pb, "isom");
3633 ffio_wfourcc(pb, "iso2");
3635 ffio_wfourcc(pb, "avc1");
3638 // We add tfdt atoms when fragmenting, signal this with the iso6 compatible
3639 // brand. This is compatible with users that don't understand tfdt.
3640 if (mov->flags & FF_MOV_FLAG_FRAGMENT && mov->mode != MODE_ISM)
3641 ffio_wfourcc(pb, "iso6");
3643 if (mov->mode == MODE_3GP)
3644 ffio_wfourcc(pb, has_h264 ? "3gp6":"3gp4");
3645 else if (mov->mode & MODE_3G2)
3646 ffio_wfourcc(pb, has_h264 ? "3g2b":"3g2a");
3647 else if (mov->mode == MODE_PSP)
3648 ffio_wfourcc(pb, "MSNV");
3649 else if (mov->mode == MODE_MP4)
3650 ffio_wfourcc(pb, "mp41");
3652 if (mov->flags & FF_MOV_FLAG_DASH && mov->flags & FF_MOV_FLAG_FASTSTART)
3653 ffio_wfourcc(pb, "dash");
3655 return update_size(pb, pos);
3658 static void mov_write_uuidprof_tag(AVIOContext *pb, AVFormatContext *s)
3660 AVStream *video_st = s->streams[0];
3661 AVCodecContext *video_codec = s->streams[0]->codec;
3662 AVCodecContext *audio_codec = s->streams[1]->codec;
3663 int audio_rate = audio_codec->sample_rate;
3664 // TODO: should be avg_frame_rate
3665 int frame_rate = ((video_st->time_base.den) * (0x10000)) / (video_st->time_base.num);
3666 int audio_kbitrate = audio_codec->bit_rate / 1000;
3667 int video_kbitrate = FFMIN(video_codec->bit_rate / 1000, 800 - audio_kbitrate);
3669 avio_wb32(pb, 0x94); /* size */
3670 ffio_wfourcc(pb, "uuid");
3671 ffio_wfourcc(pb, "PROF");
3673 avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
3674 avio_wb32(pb, 0xbb88695c);
3675 avio_wb32(pb, 0xfac9c740);
3677 avio_wb32(pb, 0x0); /* ? */
3678 avio_wb32(pb, 0x3); /* 3 sections ? */
3680 avio_wb32(pb, 0x14); /* size */
3681 ffio_wfourcc(pb, "FPRF");
3682 avio_wb32(pb, 0x0); /* ? */
3683 avio_wb32(pb, 0x0); /* ? */
3684 avio_wb32(pb, 0x0); /* ? */
3686 avio_wb32(pb, 0x2c); /* size */
3687 ffio_wfourcc(pb, "APRF"); /* audio */
3689 avio_wb32(pb, 0x2); /* TrackID */
3690 ffio_wfourcc(pb, "mp4a");
3691 avio_wb32(pb, 0x20f);
3693 avio_wb32(pb, audio_kbitrate);
3694 avio_wb32(pb, audio_kbitrate);
3695 avio_wb32(pb, audio_rate);
3696 avio_wb32(pb, audio_codec->channels);
3698 avio_wb32(pb, 0x34); /* size */
3699 ffio_wfourcc(pb, "VPRF"); /* video */
3701 avio_wb32(pb, 0x1); /* TrackID */
3702 if (video_codec->codec_id == AV_CODEC_ID_H264) {
3703 ffio_wfourcc(pb, "avc1");
3704 avio_wb16(pb, 0x014D);
3705 avio_wb16(pb, 0x0015);
3707 ffio_wfourcc(pb, "mp4v");
3708 avio_wb16(pb, 0x0000);
3709 avio_wb16(pb, 0x0103);
3712 avio_wb32(pb, video_kbitrate);
3713 avio_wb32(pb, video_kbitrate);
3714 avio_wb32(pb, frame_rate);
3715 avio_wb32(pb, frame_rate);
3716 avio_wb16(pb, video_codec->width);
3717 avio_wb16(pb, video_codec->height);
3718 avio_wb32(pb, 0x010001); /* ? */
3721 static int mov_parse_mpeg2_frame(AVPacket *pkt, uint32_t *flags)
3724 int i, closed_gop = 0;
3726 for (i = 0; i < pkt->size - 4; i++) {
3727 c = (c << 8) + pkt->data[i];
3728 if (c == 0x1b8) { // gop
3729 closed_gop = pkt->data[i + 4] >> 6 & 0x01;
3730 } else if (c == 0x100) { // pic
3731 int temp_ref = (pkt->data[i + 1] << 2) | (pkt->data[i + 2] >> 6);
3732 if (!temp_ref || closed_gop) // I picture is not reordered
3733 *flags = MOV_SYNC_SAMPLE;
3735 *flags = MOV_PARTIAL_SYNC_SAMPLE;
3742 static void mov_parse_vc1_frame(AVPacket *pkt, MOVTrack *trk, int fragment)
3744 const uint8_t *start, *next, *end = pkt->data + pkt->size;
3745 int seq = 0, entry = 0;
3746 int key = pkt->flags & AV_PKT_FLAG_KEY;
3747 start = find_next_marker(pkt->data, end);
3748 for (next = start; next < end; start = next) {
3749 next = find_next_marker(start + 4, end);
3750 switch (AV_RB32(start)) {
3751 case VC1_CODE_SEQHDR:
3754 case VC1_CODE_ENTRYPOINT:
3757 case VC1_CODE_SLICE:
3758 trk->vc1_info.slices = 1;
3762 if (!trk->entry && !fragment) {
3763 /* First packet in first fragment */
3764 trk->vc1_info.first_packet_seq = seq;
3765 trk->vc1_info.first_packet_entry = entry;
3766 } else if ((seq && !trk->vc1_info.packet_seq) ||
3767 (entry && !trk->vc1_info.packet_entry)) {
3769 for (i = 0; i < trk->entry; i++)
3770 trk->cluster[i].flags &= ~MOV_SYNC_SAMPLE;
3771 trk->has_keyframes = 0;
3773 trk->vc1_info.packet_seq = 1;
3775 trk->vc1_info.packet_entry = 1;
3777 /* First fragment */
3778 if ((!seq || trk->vc1_info.first_packet_seq) &&
3779 (!entry || trk->vc1_info.first_packet_entry)) {
3780 /* First packet had the same headers as this one, readd the
3781 * sync sample flag. */
3782 trk->cluster[0].flags |= MOV_SYNC_SAMPLE;
3783 trk->has_keyframes = 1;
3787 if (trk->vc1_info.packet_seq && trk->vc1_info.packet_entry)
3789 else if (trk->vc1_info.packet_seq)
3791 else if (trk->vc1_info.packet_entry)
3794 trk->cluster[trk->entry].flags |= MOV_SYNC_SAMPLE;
3795 trk->has_keyframes++;
3799 static int mov_flush_fragment(AVFormatContext *s)
3801 MOVMuxContext *mov = s->priv_data;
3802 int i, first_track = -1;
3803 int64_t mdat_size = 0;
3805 if (!(mov->flags & FF_MOV_FLAG_FRAGMENT))
3808 if (!(mov->flags & FF_MOV_FLAG_EMPTY_MOOV) && mov->fragments == 0) {
3809 int64_t pos = avio_tell(s->pb);
3811 int buf_size, moov_size;
3813 for (i = 0; i < mov->nb_streams; i++)
3814 if (!mov->tracks[i].entry)
3816 /* Don't write the initial moov unless all tracks have data */
3817 if (i < mov->nb_streams)
3820 moov_size = get_moov_size(s);
3821 for (i = 0; i < mov->nb_streams; i++)
3822 mov->tracks[i].data_offset = pos + moov_size + 8;
3824 mov_write_moov_tag(s->pb, mov, s);
3826 buf_size = avio_close_dyn_buf(mov->mdat_buf, &buf);
3827 mov->mdat_buf = NULL;
3828 avio_wb32(s->pb, buf_size + 8);
3829 ffio_wfourcc(s->pb, "mdat");
3830 avio_write(s->pb, buf, buf_size);
3835 for (i = 0; i < mov->nb_streams; i++) {
3836 if (mov->tracks[i].entry)
3837 mov->tracks[i].frag_start += mov->tracks[i].start_dts +
3838 mov->tracks[i].track_duration -
3839 mov->tracks[i].cluster[0].dts;
3840 mov->tracks[i].entry = 0;
3846 for (i = 0; i < mov->nb_streams; i++) {
3847 MOVTrack *track = &mov->tracks[i];
3848 if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF)
3849 track->data_offset = 0;
3851 track->data_offset = mdat_size;
3852 if (!track->mdat_buf)
3854 mdat_size += avio_tell(track->mdat_buf);
3855 if (first_track < 0)
3862 for (i = 0; i < mov->nb_streams; i++) {
3863 MOVTrack *track = &mov->tracks[i];
3864 int buf_size, write_moof = 1, moof_tracks = -1;
3866 int64_t duration = 0;
3869 duration = track->start_dts + track->track_duration -
3870 track->cluster[0].dts;
3871 if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF) {
3872 if (!track->mdat_buf)
3874 mdat_size = avio_tell(track->mdat_buf);
3877 write_moof = i == first_track;
3883 mov_write_moof_tag(s->pb, mov, moof_tracks, mdat_size);
3886 avio_wb32(s->pb, mdat_size + 8);
3887 ffio_wfourcc(s->pb, "mdat");
3891 track->frag_start += duration;
3893 if (!track->mdat_buf)
3895 buf_size = avio_close_dyn_buf(track->mdat_buf, &buf);
3896 track->mdat_buf = NULL;
3898 avio_write(s->pb, buf, buf_size);
3908 int ff_mov_write_packet(AVFormatContext *s, AVPacket *pkt)
3910 MOVMuxContext *mov = s->priv_data;
3911 AVIOContext *pb = s->pb;
3912 MOVTrack *trk = &mov->tracks[pkt->stream_index];
3913 AVCodecContext *enc = trk->enc;
3914 unsigned int samples_in_chunk = 0;
3915 int size = pkt->size, ret = 0;
3916 uint8_t *reformatted_data = NULL;
3919 int64_t duration = pkt->dts - trk->cluster[trk->entry - 1].dts;
3920 if (duration < 0 || duration > INT_MAX) {
3921 av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" / timestamp: %"PRId64" is out of range for mov/mp4 format\n",
3925 pkt->dts = trk->cluster[trk->entry - 1].dts + 1;
3926 pkt->pts = AV_NOPTS_VALUE;
3928 if (pkt->duration < 0) {
3929 av_log(s, AV_LOG_ERROR, "Application provided duration: %d is invalid\n", pkt->duration);
3930 return AVERROR(EINVAL);
3933 if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
3935 if (mov->fragments > 0) {
3936 if (!trk->mdat_buf) {
3937 if ((ret = avio_open_dyn_buf(&trk->mdat_buf)) < 0)
3942 if (!mov->mdat_buf) {
3943 if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0)
3950 if (enc->codec_id == AV_CODEC_ID_AMR_NB) {
3951 /* We must find out how many AMR blocks there are in one packet */
3952 static uint16_t packed_size[16] =
3953 {13, 14, 16, 18, 20, 21, 27, 32, 6, 0, 0, 0, 0, 0, 0, 1};
3956 while (len < size && samples_in_chunk < 100) {
3957 len += packed_size[(pkt->data[len] >> 3) & 0x0F];
3960 if (samples_in_chunk > 1) {
3961 av_log(s, AV_LOG_ERROR, "fatal error, input is not a single packet, implement a AVParser for it\n");
3964 } else if (enc->codec_id == AV_CODEC_ID_ADPCM_MS ||
3965 enc->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) {
3966 samples_in_chunk = enc->frame_size;
3967 } else if (trk->sample_size)
3968 samples_in_chunk = size / trk->sample_size;
3970 samples_in_chunk = 1;
3972 /* copy extradata if it exists */
3973 if (trk->vos_len == 0 && enc->extradata_size > 0 && !TAG_IS_AVCI(trk->tag)) {
3974 trk->vos_len = enc->extradata_size;
3975 trk->vos_data = av_malloc(trk->vos_len);
3976 memcpy(trk->vos_data, enc->extradata, trk->vos_len);
3979 if (enc->codec_id == AV_CODEC_ID_AAC && pkt->size > 2 &&
3980 (AV_RB16(pkt->data) & 0xfff0) == 0xfff0) {
3981 if (!s->streams[pkt->stream_index]->nb_frames) {
3982 av_log(s, AV_LOG_ERROR, "Malformed AAC bitstream detected: "
3983 "use the audio bitstream filter 'aac_adtstoasc' to fix it "
3984 "('-bsf:a aac_adtstoasc' option with ffmpeg)\n");
3987 av_log(s, AV_LOG_WARNING, "aac bitstream error\n");
3989 if (enc->codec_id == AV_CODEC_ID_H264 && trk->vos_len > 0 && *(uint8_t *)trk->vos_data != 1 && !TAG_IS_AVCI(trk->tag)) {
3990 /* from x264 or from bytestream h264 */
3991 /* nal reformating needed */
3992 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
3993 ff_avc_parse_nal_units_buf(pkt->data, &reformatted_data,
3995 avio_write(pb, reformatted_data, size);
3997 size = ff_avc_parse_nal_units(pb, pkt->data, pkt->size);
3999 } else if (enc->codec_id == AV_CODEC_ID_HEVC && trk->vos_len > 6 &&
4000 (AV_RB24(trk->vos_data) == 1 || AV_RB32(trk->vos_data) == 1)) {
4001 /* extradata is Annex B, assume the bitstream is too and convert it */
4002 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
4003 ff_hevc_annexb2mp4_buf(pkt->data, &reformatted_data, &size, 0, NULL);
4004 avio_write(pb, reformatted_data, size);
4006 size = ff_hevc_annexb2mp4(pb, pkt->data, pkt->size, 0, NULL);
4008 } else if (enc->codec_id == AV_CODEC_ID_EAC3) {
4009 size = handle_eac3(mov, pkt, trk);
4014 avio_write(pb, pkt->data, size);
4016 avio_write(pb, pkt->data, size);
4019 if ((enc->codec_id == AV_CODEC_ID_DNXHD ||
4020 enc->codec_id == AV_CODEC_ID_AC3) && !trk->vos_len) {
4021 /* copy frame to create needed atoms */
4022 trk->vos_len = size;
4023 trk->vos_data = av_malloc(size);
4024 if (!trk->vos_data) {
4025 ret = AVERROR(ENOMEM);
4028 memcpy(trk->vos_data, pkt->data, size);
4031 if (trk->entry >= trk->cluster_capacity) {
4032 unsigned new_capacity = 2 * (trk->entry + MOV_INDEX_CLUSTER_SIZE);
4033 if (av_reallocp_array(&trk->cluster, new_capacity,
4034 sizeof(*trk->cluster))) {
4035 ret = AVERROR(ENOMEM);
4038 trk->cluster_capacity = new_capacity;
4041 trk->cluster[trk->entry].pos = avio_tell(pb) - size;
4042 trk->cluster[trk->entry].samples_in_chunk = samples_in_chunk;
4043 trk->cluster[trk->entry].chunkNum = 0;
4044 trk->cluster[trk->entry].size = size;
4045 trk->cluster[trk->entry].entries = samples_in_chunk;
4046 trk->cluster[trk->entry].dts = pkt->dts;
4047 if (!trk->entry && trk->start_dts != AV_NOPTS_VALUE) {
4048 if (!trk->frag_discont) {
4049 /* First packet of a new fragment. We already wrote the duration
4050 * of the last packet of the previous fragment based on track_duration,
4051 * which might not exactly match our dts. Therefore adjust the dts
4052 * of this packet to be what the previous packets duration implies. */
4053 trk->cluster[trk->entry].dts = trk->start_dts + trk->track_duration;
4055 /* New fragment, but discontinuous from previous fragments.
4056 * Pretend the duration sum of the earlier fragments is
4057 * pkt->dts - trk->start_dts. */
4058 trk->frag_start = pkt->dts - trk->start_dts;
4059 trk->frag_discont = 0;
4063 if (!trk->entry && trk->start_dts == AV_NOPTS_VALUE && !mov->use_editlist &&
4064 s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO) {
4065 /* Not using edit lists and shifting the first track to start from zero.
4066 * If the other streams start from a later timestamp, we won't be able
4067 * to signal the difference in starting time without an edit list.
4068 * Thus move the timestamp for this first sample to 0, increasing
4069 * its duration instead. */
4070 trk->cluster[trk->entry].dts = trk->start_dts = 0;
4072 if (trk->start_dts == AV_NOPTS_VALUE) {
4073 trk->start_dts = pkt->dts;
4074 if (trk->frag_discont) {
4075 /* Pretend the whole stream started at dts=0, with earlier framgents
4076 * already written, with a duration summing up to pkt->dts. */
4077 trk->frag_start = pkt->dts;
4079 trk->frag_discont = 0;
4080 } else if (pkt->dts && mov->flags & FF_MOV_FLAG_EMPTY_MOOV)
4081 av_log(s, AV_LOG_WARNING,
4082 "Track %d starts with a nonzero dts %"PRId64". This "
4083 "currently isn't handled correctly in combination with "
4084 "empty_moov.\n", pkt->stream_index, pkt->dts);
4086 trk->track_duration = pkt->dts - trk->start_dts + pkt->duration;
4087 trk->last_sample_is_subtitle_end = 0;
4089 if (pkt->pts == AV_NOPTS_VALUE) {
4090 av_log(s, AV_LOG_WARNING, "pts has no value\n");
4091 pkt->pts = pkt->dts;
4093 if (pkt->dts != pkt->pts)
4094 trk->flags |= MOV_TRACK_CTTS;
4095 trk->cluster[trk->entry].cts = pkt->pts - pkt->dts;
4096 trk->cluster[trk->entry].flags = 0;
4097 if (enc->codec_id == AV_CODEC_ID_VC1) {
4098 mov_parse_vc1_frame(pkt, trk, mov->fragments);
4099 } else if (pkt->flags & AV_PKT_FLAG_KEY) {
4100 if (mov->mode == MODE_MOV && enc->codec_id == AV_CODEC_ID_MPEG2VIDEO &&
4101 trk->entry > 0) { // force sync sample for the first key frame
4102 mov_parse_mpeg2_frame(pkt, &trk->cluster[trk->entry].flags);
4103 if (trk->cluster[trk->entry].flags & MOV_PARTIAL_SYNC_SAMPLE)
4104 trk->flags |= MOV_TRACK_STPS;
4106 trk->cluster[trk->entry].flags = MOV_SYNC_SAMPLE;
4108 if (trk->cluster[trk->entry].flags & MOV_SYNC_SAMPLE)
4109 trk->has_keyframes++;
4112 trk->sample_count += samples_in_chunk;
4113 mov->mdat_size += size;
4115 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams)
4116 ff_mov_add_hinted_packet(s, pkt, trk->hint_track, trk->entry,
4117 reformatted_data, size);
4122 av_free(reformatted_data);
4126 static int mov_write_single_packet(AVFormatContext *s, AVPacket *pkt)
4128 MOVMuxContext *mov = s->priv_data;
4129 MOVTrack *trk = &mov->tracks[pkt->stream_index];
4130 AVCodecContext *enc = trk->enc;
4131 int64_t frag_duration = 0;
4132 int size = pkt->size;
4135 return 0; /* Discard 0 sized packets */
4137 if (mov->flags & FF_MOV_FLAG_FRAG_DISCONT) {
4139 for (i = 0; i < s->nb_streams; i++)
4140 mov->tracks[i].frag_discont = 1;
4141 mov->flags &= ~FF_MOV_FLAG_FRAG_DISCONT;
4144 if (trk->entry && pkt->stream_index < s->nb_streams)
4145 frag_duration = av_rescale_q(pkt->dts - trk->cluster[0].dts,
4146 s->streams[pkt->stream_index]->time_base,
4148 if ((mov->max_fragment_duration &&
4149 frag_duration >= mov->max_fragment_duration) ||
4150 (mov->max_fragment_size && mov->mdat_size + size >= mov->max_fragment_size) ||
4151 (mov->flags & FF_MOV_FLAG_FRAG_KEYFRAME &&
4152 enc->codec_type == AVMEDIA_TYPE_VIDEO &&
4153 trk->entry && pkt->flags & AV_PKT_FLAG_KEY)) {
4154 if (frag_duration >= mov->min_fragment_duration)
4155 mov_flush_fragment(s);
4158 return ff_mov_write_packet(s, pkt);
4161 static int mov_write_subtitle_end_packet(AVFormatContext *s,
4165 uint8_t data[2] = {0};
4168 av_init_packet(&end);
4169 end.size = sizeof(data);
4174 end.stream_index = stream_index;
4176 ret = mov_write_single_packet(s, &end);
4177 av_free_packet(&end);
4182 static int mov_write_packet(AVFormatContext *s, AVPacket *pkt)
4185 mov_flush_fragment(s);
4189 MOVMuxContext *mov = s->priv_data;
4191 if (!pkt->size) return 0; /* Discard 0 sized packets */
4194 * Subtitles require special handling.
4196 * 1) For full complaince, every track must have a sample at
4197 * dts == 0, which is rarely true for subtitles. So, as soon
4198 * as we see any packet with dts > 0, write an empty subtitle
4199 * at dts == 0 for any subtitle track with no samples in it.
4201 * 2) For each subtitle track, check if the current packet's
4202 * dts is past the duration of the last subtitle sample. If
4203 * so, we now need to write an end sample for that subtitle.
4205 * This must be done conditionally to allow for subtitles that
4206 * immediately replace each other, in which case an end sample
4207 * is not needed, and is, in fact, actively harmful.
4209 * 3) See mov_write_trailer for how the final end sample is
4212 for (i = 0; i < mov->nb_streams; i++) {
4213 MOVTrack *trk = &mov->tracks[i];
4216 if (trk->enc->codec_id == AV_CODEC_ID_MOV_TEXT &&
4217 trk->track_duration < pkt->dts &&
4218 (trk->entry == 0 || !trk->last_sample_is_subtitle_end)) {
4219 ret = mov_write_subtitle_end_packet(s, i, trk->track_duration);
4220 if (ret < 0) return ret;
4221 trk->last_sample_is_subtitle_end = 1;
4225 return mov_write_single_packet(s, pkt);
4229 // QuickTime chapters involve an additional text track with the chapter names
4230 // as samples, and a tref pointing from the other tracks to the chapter one.
4231 static int mov_create_chapter_track(AVFormatContext *s, int tracknum)
4235 MOVMuxContext *mov = s->priv_data;
4236 MOVTrack *track = &mov->tracks[tracknum];
4237 AVPacket pkt = { .stream_index = tracknum, .flags = AV_PKT_FLAG_KEY };
4240 track->mode = mov->mode;
4241 track->tag = MKTAG('t','e','x','t');
4242 track->timescale = MOV_TIMESCALE;
4243 track->enc = avcodec_alloc_context3(NULL);
4245 return AVERROR(ENOMEM);
4246 track->enc->codec_type = AVMEDIA_TYPE_SUBTITLE;
4248 // These properties are required to make QT recognize the chapter track
4249 uint8_t chapter_properties[43] = { 0, 0, 0, 0, 0, 0, 0, 1, };
4250 if (ff_alloc_extradata(track->enc, sizeof(chapter_properties)))
4251 return AVERROR(ENOMEM);
4252 memcpy(track->enc->extradata, chapter_properties, sizeof(chapter_properties));
4254 if (avio_open_dyn_buf(&pb) >= 0) {
4258 /* Stub header (usually for Quicktime chapter track) */
4260 avio_wb32(pb, 0x01); // displayFlags
4261 avio_w8(pb, 0x00); // horizontal justification
4262 avio_w8(pb, 0x00); // vertical justification
4263 avio_w8(pb, 0x00); // bgColourRed
4264 avio_w8(pb, 0x00); // bgColourGreen
4265 avio_w8(pb, 0x00); // bgColourBlue
4266 avio_w8(pb, 0x00); // bgColourAlpha
4268 avio_wb16(pb, 0x00); // defTextBoxTop
4269 avio_wb16(pb, 0x00); // defTextBoxLeft
4270 avio_wb16(pb, 0x00); // defTextBoxBottom
4271 avio_wb16(pb, 0x00); // defTextBoxRight
4273 avio_wb16(pb, 0x00); // startChar
4274 avio_wb16(pb, 0x00); // endChar
4275 avio_wb16(pb, 0x01); // fontID
4276 avio_w8(pb, 0x00); // fontStyleFlags
4277 avio_w8(pb, 0x00); // fontSize
4278 avio_w8(pb, 0x00); // fgColourRed
4279 avio_w8(pb, 0x00); // fgColourGreen
4280 avio_w8(pb, 0x00); // fgColourBlue
4281 avio_w8(pb, 0x00); // fgColourAlpha
4283 avio_wb32(pb, 0x0D); // box size
4284 ffio_wfourcc(pb, "ftab"); // box atom name
4285 avio_wb16(pb, 0x01); // entry count
4287 avio_wb16(pb, 0x01); // font ID
4288 avio_w8(pb, 0x00); // font name length
4290 if ((size = avio_close_dyn_buf(pb, &buf)) > 0) {
4291 track->enc->extradata = buf;
4292 track->enc->extradata_size = size;
4299 for (i = 0; i < s->nb_chapters; i++) {
4300 AVChapter *c = s->chapters[i];
4301 AVDictionaryEntry *t;
4303 int64_t end = av_rescale_q(c->end, c->time_base, (AVRational){1,MOV_TIMESCALE});
4304 pkt.pts = pkt.dts = av_rescale_q(c->start, c->time_base, (AVRational){1,MOV_TIMESCALE});
4305 pkt.duration = end - pkt.dts;
4307 if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
4308 const char encd[12] = {
4309 0x00, 0x00, 0x00, 0x0C,
4311 0x00, 0x00, 0x01, 0x00 };
4312 len = strlen(t->value);
4313 pkt.size = len + 2 + 12;
4314 pkt.data = av_malloc(pkt.size);
4316 return AVERROR(ENOMEM);
4317 AV_WB16(pkt.data, len);
4318 memcpy(pkt.data + 2, t->value, len);
4319 memcpy(pkt.data + len + 2, encd, sizeof(encd));
4320 ff_mov_write_packet(s, &pkt);
4321 av_freep(&pkt.data);
4328 static int mov_create_timecode_track(AVFormatContext *s, int index, int src_index, const char *tcstr)
4331 MOVMuxContext *mov = s->priv_data;
4332 MOVTrack *track = &mov->tracks[index];
4333 AVStream *src_st = s->streams[src_index];
4335 AVPacket pkt = {.stream_index = index, .flags = AV_PKT_FLAG_KEY, .size = 4};
4336 AVRational rate = find_fps(s, src_st);
4338 /* compute the frame number */
4339 ret = av_timecode_init_from_string(&tc, rate, tcstr, s);
4343 /* tmcd track based on video stream */
4344 track->mode = mov->mode;
4345 track->tag = MKTAG('t','m','c','d');
4346 track->src_track = src_index;
4347 track->timescale = mov->tracks[src_index].timescale;
4348 if (tc.flags & AV_TIMECODE_FLAG_DROPFRAME)
4349 track->timecode_flags |= MOV_TIMECODE_FLAG_DROPFRAME;
4351 /* set st to src_st for metadata access*/
4354 /* encode context: tmcd data stream */
4355 track->enc = avcodec_alloc_context3(NULL);
4356 track->enc->codec_type = AVMEDIA_TYPE_DATA;
4357 track->enc->codec_tag = track->tag;
4358 track->enc->time_base = av_inv_q(rate);
4360 /* the tmcd track just contains one packet with the frame number */
4361 pkt.data = av_malloc(pkt.size);
4362 AV_WB32(pkt.data, tc.start);
4363 ret = ff_mov_write_packet(s, &pkt);
4369 * st->disposition controls the "enabled" flag in the tkhd tag.
4370 * QuickTime will not play a track if it is not enabled. So make sure
4371 * that one track of each type (audio, video, subtitle) is enabled.
4373 * Subtitles are special. For audio and video, setting "enabled" also
4374 * makes the track "default" (i.e. it is rendered when played). For
4375 * subtitles, an "enabled" subtitle is not rendered by default, but
4376 * if no subtitle is enabled, the subtitle menu in QuickTime will be
4379 static void enable_tracks(AVFormatContext *s)
4381 MOVMuxContext *mov = s->priv_data;
4383 int enabled[AVMEDIA_TYPE_NB];
4384 int first[AVMEDIA_TYPE_NB];
4386 for (i = 0; i < AVMEDIA_TYPE_NB; i++) {
4391 for (i = 0; i < s->nb_streams; i++) {
4392 AVStream *st = s->streams[i];
4394 if (st->codec->codec_type <= AVMEDIA_TYPE_UNKNOWN ||
4395 st->codec->codec_type >= AVMEDIA_TYPE_NB)
4398 if (first[st->codec->codec_type] < 0)
4399 first[st->codec->codec_type] = i;
4400 if (st->disposition & AV_DISPOSITION_DEFAULT) {
4401 mov->tracks[i].flags |= MOV_TRACK_ENABLED;
4402 enabled[st->codec->codec_type]++;
4406 for (i = 0; i < AVMEDIA_TYPE_NB; i++) {
4408 case AVMEDIA_TYPE_VIDEO:
4409 case AVMEDIA_TYPE_AUDIO:
4410 case AVMEDIA_TYPE_SUBTITLE:
4412 mov->per_stream_grouping = 1;
4413 if (!enabled[i] && first[i] >= 0)
4414 mov->tracks[first[i]].flags |= MOV_TRACK_ENABLED;
4420 static void mov_free(AVFormatContext *s)
4422 MOVMuxContext *mov = s->priv_data;
4425 if (mov->chapter_track) {
4426 if (mov->tracks[mov->chapter_track].enc)
4427 av_freep(&mov->tracks[mov->chapter_track].enc->extradata);
4428 av_freep(&mov->tracks[mov->chapter_track].enc);
4431 for (i = 0; i < mov->nb_streams; i++) {
4432 if (mov->tracks[i].tag == MKTAG('r','t','p',' '))
4433 ff_mov_close_hinting(&mov->tracks[i]);
4434 else if (mov->tracks[i].tag == MKTAG('t','m','c','d') && mov->nb_meta_tmcd)
4435 av_freep(&mov->tracks[i].enc);
4436 av_freep(&mov->tracks[i].cluster);
4437 av_freep(&mov->tracks[i].frag_info);
4439 if (mov->tracks[i].vos_len)
4440 av_freep(&mov->tracks[i].vos_data);
4443 av_freep(&mov->tracks);
4446 static uint32_t rgb_to_yuv(uint32_t rgb)
4451 r = (rgb >> 16) & 0xFF;
4452 g = (rgb >> 8) & 0xFF;
4455 y = av_clip_uint8( 16. + 0.257 * r + 0.504 * g + 0.098 * b);
4456 cb = av_clip_uint8(128. - 0.148 * r - 0.291 * g + 0.439 * b);
4457 cr = av_clip_uint8(128. + 0.439 * r - 0.368 * g - 0.071 * b);
4459 return (y << 16) | (cr << 8) | cb;
4462 static int mov_create_dvd_sub_decoder_specific_info(MOVTrack *track,
4465 int i, width = 720, height = 480;
4466 int have_palette = 0, have_size = 0;
4467 uint32_t palette[16];
4468 char *cur = st->codec->extradata;
4470 while (cur && *cur) {
4471 if (strncmp("palette:", cur, 8) == 0) {
4473 count = sscanf(cur + 8,
4474 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
4475 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
4476 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
4477 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32"",
4478 &palette[ 0], &palette[ 1], &palette[ 2], &palette[ 3],
4479 &palette[ 4], &palette[ 5], &palette[ 6], &palette[ 7],
4480 &palette[ 8], &palette[ 9], &palette[10], &palette[11],
4481 &palette[12], &palette[13], &palette[14], &palette[15]);
4483 for (i = 0; i < count; i++) {
4484 palette[i] = rgb_to_yuv(palette[i]);
4487 } else if (!strncmp("size:", cur, 5)) {
4488 sscanf(cur + 5, "%dx%d", &width, &height);
4491 if (have_palette && have_size)
4493 cur += strcspn(cur, "\n\r");
4494 cur += strspn(cur, "\n\r");
4497 track->vos_data = av_malloc(16*4);
4498 if (!track->vos_data)
4499 return AVERROR(ENOMEM);
4500 for (i = 0; i < 16; i++) {
4501 AV_WB32(track->vos_data + i * 4, palette[i]);
4503 track->vos_len = 16 * 4;
4505 st->codec->width = width;
4506 st->codec->height = track->height = height;
4511 static int mov_write_header(AVFormatContext *s)
4513 AVIOContext *pb = s->pb;
4514 MOVMuxContext *mov = s->priv_data;
4515 AVDictionaryEntry *t, *global_tcr = av_dict_get(s->metadata, "timecode", NULL, 0);
4516 int i, ret, hint_track = 0, tmcd_track = 0;
4520 /* Default mode == MP4 */
4521 mov->mode = MODE_MP4;
4524 if (!strcmp("3gp", s->oformat->name)) mov->mode = MODE_3GP;
4525 else if (!strcmp("3g2", s->oformat->name)) mov->mode = MODE_3GP|MODE_3G2;
4526 else if (!strcmp("mov", s->oformat->name)) mov->mode = MODE_MOV;
4527 else if (!strcmp("psp", s->oformat->name)) mov->mode = MODE_PSP;
4528 else if (!strcmp("ipod",s->oformat->name)) mov->mode = MODE_IPOD;
4529 else if (!strcmp("ismv",s->oformat->name)) mov->mode = MODE_ISM;
4530 else if (!strcmp("f4v", s->oformat->name)) mov->mode = MODE_F4V;
4533 if (s->flags & AVFMT_FLAG_BITEXACT)
4536 /* Set the FRAGMENT flag if any of the fragmentation methods are
4538 if (mov->max_fragment_duration || mov->max_fragment_size ||
4539 mov->flags & (FF_MOV_FLAG_EMPTY_MOOV |
4540 FF_MOV_FLAG_FRAG_KEYFRAME |
4541 FF_MOV_FLAG_FRAG_CUSTOM))
4542 mov->flags |= FF_MOV_FLAG_FRAGMENT;
4544 /* Set other implicit flags immediately */
4545 if (mov->mode == MODE_ISM)
4546 mov->flags |= FF_MOV_FLAG_EMPTY_MOOV | FF_MOV_FLAG_SEPARATE_MOOF |
4547 FF_MOV_FLAG_FRAGMENT;
4548 if (mov->flags & FF_MOV_FLAG_DASH)
4549 mov->flags |= FF_MOV_FLAG_FRAGMENT | FF_MOV_FLAG_EMPTY_MOOV |
4550 FF_MOV_FLAG_DEFAULT_BASE_MOOF;
4552 if (mov->flags & FF_MOV_FLAG_FASTSTART) {
4553 mov->reserved_moov_size = -1;
4556 if (mov->use_editlist < 0) {
4557 mov->use_editlist = 1;
4558 if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
4559 // If we can avoid needing an edit list by shifting the
4560 // tracks, prefer that over (trying to) write edit lists
4561 // in fragmented output.
4562 if (s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO ||
4563 s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO)
4564 mov->use_editlist = 0;
4567 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV && mov->use_editlist)
4568 av_log(s, AV_LOG_WARNING, "No meaningful edit list will be written when using empty_moov\n");
4570 if (!mov->use_editlist && s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO)
4571 s->avoid_negative_ts = AVFMT_AVOID_NEG_TS_MAKE_ZERO;
4573 /* Non-seekable output is ok if using fragmentation. If ism_lookahead
4574 * is enabled, we don't support non-seekable output at all. */
4575 if (!s->pb->seekable &&
4576 (!(mov->flags & FF_MOV_FLAG_FRAGMENT) || mov->ism_lookahead)) {
4577 av_log(s, AV_LOG_ERROR, "muxer does not support non seekable output\n");
4578 return AVERROR(EINVAL);
4581 mov_write_ftyp_tag(pb,s);
4582 if (mov->mode == MODE_PSP) {
4583 int video_streams_nb = 0, audio_streams_nb = 0, other_streams_nb = 0;
4584 for (i = 0; i < s->nb_streams; i++) {
4585 AVStream *st = s->streams[i];
4586 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
4588 else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
4594 if (video_streams_nb != 1 || audio_streams_nb != 1 || other_streams_nb) {
4595 av_log(s, AV_LOG_ERROR, "PSP mode need one video and one audio stream\n");
4596 return AVERROR(EINVAL);
4598 mov_write_uuidprof_tag(pb, s);
4601 mov->nb_streams = s->nb_streams;
4602 if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters)
4603 mov->chapter_track = mov->nb_streams++;
4605 if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
4606 /* Add hint tracks for each audio and video stream */
4607 hint_track = mov->nb_streams;
4608 for (i = 0; i < s->nb_streams; i++) {
4609 AVStream *st = s->streams[i];
4610 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO ||
4611 st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
4617 if (mov->mode == MODE_MOV) {
4618 tmcd_track = mov->nb_streams;
4620 /* +1 tmcd track for each video stream with a timecode */
4621 for (i = 0; i < s->nb_streams; i++) {
4622 AVStream *st = s->streams[i];
4623 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
4624 (global_tcr || av_dict_get(st->metadata, "timecode", NULL, 0)))
4625 mov->nb_meta_tmcd++;
4628 /* check if there is already a tmcd track to remux */
4629 if (mov->nb_meta_tmcd) {
4630 for (i = 0; i < s->nb_streams; i++) {
4631 AVStream *st = s->streams[i];
4632 if (st->codec->codec_tag == MKTAG('t','m','c','d')) {
4633 av_log(s, AV_LOG_WARNING, "You requested a copy of the original timecode track "
4634 "so timecode metadata are now ignored\n");
4635 mov->nb_meta_tmcd = 0;
4640 mov->nb_streams += mov->nb_meta_tmcd;
4643 // Reserve an extra stream for chapters for the case where chapters
4644 // are written in the trailer
4645 mov->tracks = av_mallocz_array((mov->nb_streams + 1), sizeof(*mov->tracks));
4647 return AVERROR(ENOMEM);
4649 for (i = 0; i < s->nb_streams; i++) {
4650 AVStream *st= s->streams[i];
4651 MOVTrack *track= &mov->tracks[i];
4652 AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0);
4655 track->enc = st->codec;
4656 track->language = ff_mov_iso639_to_lang(lang?lang->value:"und", mov->mode!=MODE_MOV);
4657 if (track->language < 0)
4658 track->language = 0;
4659 track->mode = mov->mode;
4660 track->tag = mov_find_codec_tag(s, track);
4662 av_log(s, AV_LOG_ERROR, "Could not find tag for codec %s in stream #%d, "
4663 "codec not currently supported in container\n",
4664 avcodec_get_name(st->codec->codec_id), i);
4665 ret = AVERROR(EINVAL);
4668 /* If hinting of this track is enabled by a later hint track,
4669 * this is updated. */
4670 track->hint_track = -1;
4671 track->start_dts = AV_NOPTS_VALUE;
4672 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
4673 if (track->tag == MKTAG('m','x','3','p') || track->tag == MKTAG('m','x','3','n') ||
4674 track->tag == MKTAG('m','x','4','p') || track->tag == MKTAG('m','x','4','n') ||
4675 track->tag == MKTAG('m','x','5','p') || track->tag == MKTAG('m','x','5','n')) {
4676 if (st->codec->width != 720 || (st->codec->height != 608 && st->codec->height != 512)) {
4677 av_log(s, AV_LOG_ERROR, "D-10/IMX must use 720x608 or 720x512 video resolution\n");
4678 ret = AVERROR(EINVAL);
4681 track->height = track->tag >> 24 == 'n' ? 486 : 576;
4683 if (mov->video_track_timescale) {
4684 track->timescale = mov->video_track_timescale;
4686 track->timescale = st->time_base.den;
4687 while(track->timescale < 10000)
4688 track->timescale *= 2;
4690 if (st->codec->width > 65535 || st->codec->height > 65535) {
4691 av_log(s, AV_LOG_ERROR, "Resolution %dx%d too large for mov/mp4\n", st->codec->width, st->codec->height);
4692 ret = AVERROR(EINVAL);
4695 if (track->mode == MODE_MOV && track->timescale > 100000)
4696 av_log(s, AV_LOG_WARNING,
4697 "WARNING codec timebase is very high. If duration is too long,\n"
4698 "file may not be playable by quicktime. Specify a shorter timebase\n"
4699 "or choose different container.\n");
4700 } else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
4701 track->timescale = st->codec->sample_rate;
4702 if (!st->codec->frame_size && !av_get_bits_per_sample(st->codec->codec_id)) {
4703 av_log(s, AV_LOG_WARNING, "track %d: codec frame size is not set\n", i);
4704 track->audio_vbr = 1;
4705 }else if (st->codec->codec_id == AV_CODEC_ID_ADPCM_MS ||
4706 st->codec->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
4707 st->codec->codec_id == AV_CODEC_ID_ILBC){
4708 if (!st->codec->block_align) {
4709 av_log(s, AV_LOG_ERROR, "track %d: codec block align is not set for adpcm\n", i);
4710 ret = AVERROR(EINVAL);
4713 track->sample_size = st->codec->block_align;
4714 }else if (st->codec->frame_size > 1){ /* assume compressed audio */
4715 track->audio_vbr = 1;
4717 track->sample_size = (av_get_bits_per_sample(st->codec->codec_id) >> 3) * st->codec->channels;
4719 if (st->codec->codec_id == AV_CODEC_ID_ILBC ||
4720 st->codec->codec_id == AV_CODEC_ID_ADPCM_IMA_QT) {
4721 track->audio_vbr = 1;
4723 if (track->mode != MODE_MOV &&
4724 track->enc->codec_id == AV_CODEC_ID_MP3 && track->timescale < 16000) {
4725 av_log(s, AV_LOG_ERROR, "track %d: muxing mp3 at %dhz is not supported\n",
4726 i, track->enc->sample_rate);
4727 ret = AVERROR(EINVAL);
4730 } else if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
4731 track->timescale = st->time_base.den;
4732 } else if (st->codec->codec_type == AVMEDIA_TYPE_DATA) {
4733 track->timescale = st->time_base.den;
4735 track->timescale = MOV_TIMESCALE;
4738 track->height = st->codec->height;
4739 /* The ism specific timescale isn't mandatory, but is assumed by
4740 * some tools, such as mp4split. */
4741 if (mov->mode == MODE_ISM)
4742 track->timescale = 10000000;
4744 avpriv_set_pts_info(st, 64, 1, track->timescale);
4746 /* copy extradata if it exists */
4747 if (st->codec->extradata_size) {
4748 if (st->codec->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
4749 mov_create_dvd_sub_decoder_specific_info(track, st);
4750 else if (!TAG_IS_AVCI(track->tag)){
4751 track->vos_len = st->codec->extradata_size;
4752 track->vos_data = av_malloc(track->vos_len);
4753 memcpy(track->vos_data, st->codec->extradata, track->vos_len);
4758 for (i = 0; i < s->nb_streams; i++) {
4760 AVStream *st= s->streams[i];
4761 MOVTrack *track= &mov->tracks[i];
4763 if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO ||
4764 track->enc->channel_layout != AV_CH_LAYOUT_MONO)
4767 for (j = 0; j < s->nb_streams; j++) {
4768 AVStream *stj= s->streams[j];
4769 MOVTrack *trackj= &mov->tracks[j];
4773 if (stj->codec->codec_type != AVMEDIA_TYPE_AUDIO ||
4774 trackj->enc->channel_layout != AV_CH_LAYOUT_MONO ||
4775 trackj->language != track->language ||
4776 trackj->tag != track->tag
4779 track->multichannel_as_mono++;
4786 if (mov->reserved_moov_size){
4787 mov->reserved_moov_pos= avio_tell(pb);
4788 if (mov->reserved_moov_size > 0)
4789 avio_skip(pb, mov->reserved_moov_size);
4792 if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
4793 /* If no fragmentation options have been set, set a default. */
4794 if (!(mov->flags & (FF_MOV_FLAG_FRAG_KEYFRAME |
4795 FF_MOV_FLAG_FRAG_CUSTOM)) &&
4796 !mov->max_fragment_duration && !mov->max_fragment_size)
4797 mov->flags |= FF_MOV_FLAG_FRAG_KEYFRAME;
4799 if (mov->flags & FF_MOV_FLAG_FASTSTART)
4800 mov->reserved_moov_pos = avio_tell(pb);
4801 mov_write_mdat_tag(pb, mov);
4804 if (t = av_dict_get(s->metadata, "creation_time", NULL, 0))
4805 mov->time = ff_iso8601_to_unix_time(t->value);
4807 mov->time += 0x7C25B080; // 1970 based -> 1904 based
4809 if (mov->chapter_track)
4810 if ((ret = mov_create_chapter_track(s, mov->chapter_track)) < 0)
4813 if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
4814 /* Initialize the hint tracks for each audio and video stream */
4815 for (i = 0; i < s->nb_streams; i++) {
4816 AVStream *st = s->streams[i];
4817 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO ||
4818 st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
4819 if ((ret = ff_mov_init_hinting(s, hint_track, i)) < 0)
4826 if (mov->nb_meta_tmcd) {
4827 /* Initialize the tmcd tracks */
4828 for (i = 0; i < s->nb_streams; i++) {
4829 AVStream *st = s->streams[i];
4832 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
4834 t = av_dict_get(st->metadata, "timecode", NULL, 0);
4837 if ((ret = mov_create_timecode_track(s, tmcd_track, i, t->value)) < 0)
4846 if (mov->flags & FF_MOV_FLAG_ISML)
4847 mov_write_isml_manifest(pb, mov);
4849 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
4850 mov_write_moov_tag(pb, mov, s);
4852 if (mov->flags & FF_MOV_FLAG_FASTSTART)
4853 mov->reserved_moov_pos = avio_tell(pb);
4862 static int get_moov_size(AVFormatContext *s)
4865 AVIOContext *moov_buf;
4866 MOVMuxContext *mov = s->priv_data;
4868 if ((ret = ffio_open_null_buf(&moov_buf)) < 0)
4870 mov_write_moov_tag(moov_buf, mov, s);
4871 return ffio_close_null_buf(moov_buf);
4874 static int get_sidx_size(AVFormatContext *s)
4878 MOVMuxContext *mov = s->priv_data;
4880 if ((ret = ffio_open_null_buf(&buf)) < 0)
4882 mov_write_sidx_tags(buf, mov, -1, 0);
4883 return ffio_close_null_buf(buf);
4887 * This function gets the moov size if moved to the top of the file: the chunk
4888 * offset table can switch between stco (32-bit entries) to co64 (64-bit
4889 * entries) when the moov is moved to the beginning, so the size of the moov
4890 * would change. It also updates the chunk offset tables.
4892 static int compute_moov_size(AVFormatContext *s)
4894 int i, moov_size, moov_size2;
4895 MOVMuxContext *mov = s->priv_data;
4897 moov_size = get_moov_size(s);
4901 for (i = 0; i < mov->nb_streams; i++)
4902 mov->tracks[i].data_offset += moov_size;
4904 moov_size2 = get_moov_size(s);
4908 /* if the size changed, we just switched from stco to co64 and need to
4909 * update the offsets */
4910 if (moov_size2 != moov_size)
4911 for (i = 0; i < mov->nb_streams; i++)
4912 mov->tracks[i].data_offset += moov_size2 - moov_size;
4917 static int compute_sidx_size(AVFormatContext *s)
4920 MOVMuxContext *mov = s->priv_data;
4922 sidx_size = get_sidx_size(s);
4926 for (i = 0; i < mov->nb_streams; i++)
4927 mov->tracks[i].data_offset += sidx_size;
4932 static int shift_data(AVFormatContext *s)
4934 int ret = 0, moov_size;
4935 MOVMuxContext *mov = s->priv_data;
4936 int64_t pos, pos_end = avio_tell(s->pb);
4937 uint8_t *buf, *read_buf[2];
4938 int read_buf_id = 0;
4940 AVIOContext *read_pb;
4942 if (mov->flags & FF_MOV_FLAG_FRAGMENT)
4943 moov_size = compute_sidx_size(s);
4945 moov_size = compute_moov_size(s);
4949 buf = av_malloc(moov_size * 2);
4951 return AVERROR(ENOMEM);
4953 read_buf[1] = buf + moov_size;
4955 /* Shift the data: the AVIO context of the output can only be used for
4956 * writing, so we re-open the same output, but for reading. It also avoids
4957 * a read/seek/write/seek back and forth. */
4959 ret = avio_open(&read_pb, s->filename, AVIO_FLAG_READ);
4961 av_log(s, AV_LOG_ERROR, "Unable to re-open %s output file for "
4962 "the second pass (faststart)\n", s->filename);
4966 /* mark the end of the shift to up to the last data we wrote, and get ready
4968 pos_end = avio_tell(s->pb);
4969 avio_seek(s->pb, mov->reserved_moov_pos + moov_size, SEEK_SET);
4971 /* start reading at where the new moov will be placed */
4972 avio_seek(read_pb, mov->reserved_moov_pos, SEEK_SET);
4973 pos = avio_tell(read_pb);
4975 #define READ_BLOCK do { \
4976 read_size[read_buf_id] = avio_read(read_pb, read_buf[read_buf_id], moov_size); \
4980 /* shift data by chunk of at most moov_size */
4985 n = read_size[read_buf_id];
4988 avio_write(s->pb, read_buf[read_buf_id], n);
4990 } while (pos < pos_end);
4991 avio_close(read_pb);
4998 static int mov_write_trailer(AVFormatContext *s)
5000 MOVMuxContext *mov = s->priv_data;
5001 AVIOContext *pb = s->pb;
5007 * Before actually writing the trailer, make sure that there are no
5008 * dangling subtitles, that need a terminating sample.
5010 for (i = 0; i < mov->nb_streams; i++) {
5011 MOVTrack *trk = &mov->tracks[i];
5012 if (trk->enc->codec_id == AV_CODEC_ID_MOV_TEXT &&
5013 !trk->last_sample_is_subtitle_end) {
5014 mov_write_subtitle_end_packet(s, i, trk->track_duration);
5015 trk->last_sample_is_subtitle_end = 1;
5019 // If there were no chapters when the header was written, but there
5020 // are chapters now, write them in the trailer. This only works
5021 // when we are not doing fragments.
5022 if (!mov->chapter_track && !(mov->flags & FF_MOV_FLAG_FRAGMENT)) {
5023 if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters) {
5024 mov->chapter_track = mov->nb_streams++;
5025 if ((res = mov_create_chapter_track(s, mov->chapter_track)) < 0)
5030 if (!(mov->flags & FF_MOV_FLAG_FRAGMENT)) {
5031 moov_pos = avio_tell(pb);
5033 /* Write size of mdat tag */
5034 if (mov->mdat_size + 8 <= UINT32_MAX) {
5035 avio_seek(pb, mov->mdat_pos, SEEK_SET);
5036 avio_wb32(pb, mov->mdat_size + 8);
5038 /* overwrite 'wide' placeholder atom */
5039 avio_seek(pb, mov->mdat_pos - 8, SEEK_SET);
5040 /* special value: real atom size will be 64 bit value after
5043 ffio_wfourcc(pb, "mdat");
5044 avio_wb64(pb, mov->mdat_size + 16);
5046 avio_seek(pb, mov->reserved_moov_size > 0 ? mov->reserved_moov_pos : moov_pos, SEEK_SET);
5048 if (mov->flags & FF_MOV_FLAG_FASTSTART) {
5049 av_log(s, AV_LOG_INFO, "Starting second pass: moving the moov atom to the beginning of the file\n");
5050 res = shift_data(s);
5052 avio_seek(pb, mov->reserved_moov_pos, SEEK_SET);
5053 mov_write_moov_tag(pb, mov, s);
5055 } else if (mov->reserved_moov_size > 0) {
5057 mov_write_moov_tag(pb, mov, s);
5058 size = mov->reserved_moov_size - (avio_tell(pb) - mov->reserved_moov_pos);
5060 av_log(s, AV_LOG_ERROR, "reserved_moov_size is too small, needed %"PRId64" additional\n", 8-size);
5063 avio_wb32(pb, size);
5064 ffio_wfourcc(pb, "free");
5065 ffio_fill(pb, 0, size - 8);
5066 avio_seek(pb, moov_pos, SEEK_SET);
5068 mov_write_moov_tag(pb, mov, s);
5071 mov_flush_fragment(s);
5072 for (i = 0; i < mov->nb_streams; i++)
5073 mov->tracks[i].data_offset = 0;
5074 if (mov->flags & FF_MOV_FLAG_FASTSTART) {
5075 av_log(s, AV_LOG_INFO, "Starting second pass: inserting sidx atoms\n");
5076 res = shift_data(s);
5078 int64_t end = avio_tell(pb);
5079 avio_seek(pb, mov->reserved_moov_pos, SEEK_SET);
5080 mov_write_sidx_tags(pb, mov, -1, 0);
5081 avio_seek(pb, end, SEEK_SET);
5082 mov_write_mfra_tag(pb, mov);
5085 mov_write_mfra_tag(pb, mov);
5089 for (i = 0; i < mov->nb_streams; i++) {
5090 if (mov->flags & FF_MOV_FLAG_FRAGMENT &&
5091 mov->tracks[i].vc1_info.struct_offset && s->pb->seekable) {
5092 int64_t off = avio_tell(pb);
5094 if (mov_write_dvc1_structs(&mov->tracks[i], buf) >= 0) {
5095 avio_seek(pb, mov->tracks[i].vc1_info.struct_offset, SEEK_SET);
5096 avio_write(pb, buf, 7);
5097 avio_seek(pb, off, SEEK_SET);
5108 #if CONFIG_MOV_MUXER
5110 AVOutputFormat ff_mov_muxer = {
5112 .long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
5113 .extensions = "mov",
5114 .priv_data_size = sizeof(MOVMuxContext),
5115 .audio_codec = AV_CODEC_ID_AAC,
5116 .video_codec = CONFIG_LIBX264_ENCODER ?
5117 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
5118 .write_header = mov_write_header,
5119 .write_packet = mov_write_packet,
5120 .write_trailer = mov_write_trailer,
5121 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
5122 .codec_tag = (const AVCodecTag* const []){
5123 ff_codec_movvideo_tags, ff_codec_movaudio_tags, 0
5125 .priv_class = &mov_muxer_class,
5128 #if CONFIG_TGP_MUXER
5130 AVOutputFormat ff_tgp_muxer = {
5132 .long_name = NULL_IF_CONFIG_SMALL("3GP (3GPP file format)"),
5133 .extensions = "3gp",
5134 .priv_data_size = sizeof(MOVMuxContext),
5135 .audio_codec = AV_CODEC_ID_AMR_NB,
5136 .video_codec = AV_CODEC_ID_H263,
5137 .write_header = mov_write_header,
5138 .write_packet = mov_write_packet,
5139 .write_trailer = mov_write_trailer,
5140 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
5141 .codec_tag = (const AVCodecTag* const []){ codec_3gp_tags, 0 },
5142 .priv_class = &tgp_muxer_class,
5145 #if CONFIG_MP4_MUXER
5147 AVOutputFormat ff_mp4_muxer = {
5149 .long_name = NULL_IF_CONFIG_SMALL("MP4 (MPEG-4 Part 14)"),
5150 .mime_type = "application/mp4",
5151 .extensions = "mp4",
5152 .priv_data_size = sizeof(MOVMuxContext),
5153 .audio_codec = AV_CODEC_ID_AAC,
5154 .video_codec = CONFIG_LIBX264_ENCODER ?
5155 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
5156 .write_header = mov_write_header,
5157 .write_packet = mov_write_packet,
5158 .write_trailer = mov_write_trailer,
5159 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
5160 .codec_tag = (const AVCodecTag* const []){ ff_mp4_obj_type, 0 },
5161 .priv_class = &mp4_muxer_class,
5164 #if CONFIG_PSP_MUXER
5166 AVOutputFormat ff_psp_muxer = {
5168 .long_name = NULL_IF_CONFIG_SMALL("PSP MP4 (MPEG-4 Part 14)"),
5169 .extensions = "mp4,psp",
5170 .priv_data_size = sizeof(MOVMuxContext),
5171 .audio_codec = AV_CODEC_ID_AAC,
5172 .video_codec = CONFIG_LIBX264_ENCODER ?
5173 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
5174 .write_header = mov_write_header,
5175 .write_packet = mov_write_packet,
5176 .write_trailer = mov_write_trailer,
5177 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
5178 .codec_tag = (const AVCodecTag* const []){ ff_mp4_obj_type, 0 },
5179 .priv_class = &psp_muxer_class,
5182 #if CONFIG_TG2_MUXER
5184 AVOutputFormat ff_tg2_muxer = {
5186 .long_name = NULL_IF_CONFIG_SMALL("3GP2 (3GPP2 file format)"),
5187 .extensions = "3g2",
5188 .priv_data_size = sizeof(MOVMuxContext),
5189 .audio_codec = AV_CODEC_ID_AMR_NB,
5190 .video_codec = AV_CODEC_ID_H263,
5191 .write_header = mov_write_header,
5192 .write_packet = mov_write_packet,
5193 .write_trailer = mov_write_trailer,
5194 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
5195 .codec_tag = (const AVCodecTag* const []){ codec_3gp_tags, 0 },
5196 .priv_class = &tg2_muxer_class,
5199 #if CONFIG_IPOD_MUXER
5201 AVOutputFormat ff_ipod_muxer = {
5203 .long_name = NULL_IF_CONFIG_SMALL("iPod H.264 MP4 (MPEG-4 Part 14)"),
5204 .mime_type = "application/mp4",
5205 .extensions = "m4v,m4a",
5206 .priv_data_size = sizeof(MOVMuxContext),
5207 .audio_codec = AV_CODEC_ID_AAC,
5208 .video_codec = AV_CODEC_ID_H264,
5209 .write_header = mov_write_header,
5210 .write_packet = mov_write_packet,
5211 .write_trailer = mov_write_trailer,
5212 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
5213 .codec_tag = (const AVCodecTag* const []){ codec_ipod_tags, 0 },
5214 .priv_class = &ipod_muxer_class,
5217 #if CONFIG_ISMV_MUXER
5219 AVOutputFormat ff_ismv_muxer = {
5221 .long_name = NULL_IF_CONFIG_SMALL("ISMV/ISMA (Smooth Streaming)"),
5222 .mime_type = "application/mp4",
5223 .extensions = "ismv,isma",
5224 .priv_data_size = sizeof(MOVMuxContext),
5225 .audio_codec = AV_CODEC_ID_AAC,
5226 .video_codec = AV_CODEC_ID_H264,
5227 .write_header = mov_write_header,
5228 .write_packet = mov_write_packet,
5229 .write_trailer = mov_write_trailer,
5230 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
5231 .codec_tag = (const AVCodecTag* const []){ ff_mp4_obj_type, 0 },
5232 .priv_class = &ismv_muxer_class,
5235 #if CONFIG_F4V_MUXER
5237 AVOutputFormat ff_f4v_muxer = {
5239 .long_name = NULL_IF_CONFIG_SMALL("F4V Adobe Flash Video"),
5240 .mime_type = "application/f4v",
5241 .extensions = "f4v",
5242 .priv_data_size = sizeof(MOVMuxContext),
5243 .audio_codec = AV_CODEC_ID_AAC,
5244 .video_codec = AV_CODEC_ID_H264,
5245 .write_header = mov_write_header,
5246 .write_packet = mov_write_packet,
5247 .write_trailer = mov_write_trailer,
5248 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH,
5249 .codec_tag = (const AVCodecTag* const []){ codec_f4v_tags, 0 },
5250 .priv_class = &f4v_muxer_class,