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/libm.h"
44 #include "libavutil/opt.h"
45 #include "libavutil/dict.h"
46 #include "libavutil/pixdesc.h"
47 #include "libavutil/timecode.h"
48 #include "libavutil/color_utils.h"
53 static const AVOption options[] = {
54 { "movflags", "MOV muxer flags", offsetof(MOVMuxContext, flags), AV_OPT_TYPE_FLAGS, {.i64 = 0}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
55 { "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" },
56 { "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 },
57 { "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" },
58 { "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" },
59 { "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" },
60 { "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" },
61 { "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" },
62 { "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" },
63 { "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" },
64 { "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" },
65 { "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" },
66 { "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" },
67 { "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" },
68 { "delay_moov", "Delay writing the initial moov until the first fragment is cut, or until the first fragment flush", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_DELAY_MOOV}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
69 { "write_colr", "Write colr atom (Experimental, may be renamed or changed, do not use from scripts)", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_WRITE_COLR}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
70 { "write_gama", "Write deprecated gama atom", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_WRITE_GAMA}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
71 FF_RTP_FLAG_OPTS(MOVMuxContext, rtp_flags),
72 { "skip_iods", "Skip writing iods atom.", offsetof(MOVMuxContext, iods_skip), AV_OPT_TYPE_INT, {.i64 = 1}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM},
73 { "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},
74 { "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},
75 { "frag_duration", "Maximum fragment duration", offsetof(MOVMuxContext, max_fragment_duration), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
76 { "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},
77 { "frag_size", "Maximum fragment size", offsetof(MOVMuxContext, max_fragment_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
78 { "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},
79 { "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},
80 { "brand", "Override major brand", offsetof(MOVMuxContext, major_brand), AV_OPT_TYPE_STRING, {.str = NULL}, .flags = AV_OPT_FLAG_ENCODING_PARAM },
81 { "use_editlist", "use edit list", offsetof(MOVMuxContext, use_editlist), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 1, AV_OPT_FLAG_ENCODING_PARAM},
82 { "fragment_index", "Fragment number of the next fragment", offsetof(MOVMuxContext, fragments), AV_OPT_TYPE_INT, {.i64 = 1}, 1, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
83 { "mov_gamma", "gamma value for gama atom", offsetof(MOVMuxContext, gamma), AV_OPT_TYPE_FLOAT, {.dbl = 0.0 }, 0.0, 10, AV_OPT_FLAG_ENCODING_PARAM},
84 { "frag_interleave", "Interleave samples within fragments (max number of consecutive samples, lower is tighter interleaving, but with more overhead)", offsetof(MOVMuxContext, frag_interleave), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM },
88 #define MOV_CLASS(flavor)\
89 static const AVClass flavor ## _muxer_class = {\
90 .class_name = #flavor " muxer",\
91 .item_name = av_default_item_name,\
93 .version = LIBAVUTIL_VERSION_INT,\
96 static int get_moov_size(AVFormatContext *s);
98 static int utf8len(const uint8_t *b)
103 GET_UTF8(val, *b++, return -1;)
109 //FIXME support 64 bit variant with wide placeholders
110 static int64_t update_size(AVIOContext *pb, int64_t pos)
112 int64_t curpos = avio_tell(pb);
113 avio_seek(pb, pos, SEEK_SET);
114 avio_wb32(pb, curpos - pos); /* rewrite size */
115 avio_seek(pb, curpos, SEEK_SET);
120 static int co64_required(const MOVTrack *track)
122 if (track->entry > 0 && track->cluster[track->entry - 1].pos + track->data_offset > UINT32_MAX)
127 /* Chunk offset atom */
128 static int mov_write_stco_tag(AVIOContext *pb, MOVTrack *track)
131 int mode64 = co64_required(track); // use 32 bit size variant if possible
132 int64_t pos = avio_tell(pb);
133 avio_wb32(pb, 0); /* size */
135 ffio_wfourcc(pb, "co64");
137 ffio_wfourcc(pb, "stco");
138 avio_wb32(pb, 0); /* version & flags */
139 avio_wb32(pb, track->chunkCount); /* entry count */
140 for (i = 0; i < track->entry; i++) {
141 if (!track->cluster[i].chunkNum)
144 avio_wb64(pb, track->cluster[i].pos + track->data_offset);
146 avio_wb32(pb, track->cluster[i].pos + track->data_offset);
148 return update_size(pb, pos);
151 /* Sample size atom */
152 static int mov_write_stsz_tag(AVIOContext *pb, MOVTrack *track)
155 int i, j, entries = 0, tst = -1, oldtst = -1;
157 int64_t pos = avio_tell(pb);
158 avio_wb32(pb, 0); /* size */
159 ffio_wfourcc(pb, "stsz");
160 avio_wb32(pb, 0); /* version & flags */
162 for (i = 0; i < track->entry; i++) {
163 tst = track->cluster[i].size / track->cluster[i].entries;
164 if (oldtst != -1 && tst != oldtst)
167 entries += track->cluster[i].entries;
169 if (equalChunks && track->entry) {
170 int sSize = track->entry ? track->cluster[0].size / track->cluster[0].entries : 0;
171 sSize = FFMAX(1, sSize); // adpcm mono case could make sSize == 0
172 avio_wb32(pb, sSize); // sample size
173 avio_wb32(pb, entries); // sample count
175 avio_wb32(pb, 0); // sample size
176 avio_wb32(pb, entries); // sample count
177 for (i = 0; i < track->entry; i++) {
178 for (j = 0; j < track->cluster[i].entries; j++) {
179 avio_wb32(pb, track->cluster[i].size /
180 track->cluster[i].entries);
184 return update_size(pb, pos);
187 /* Sample to chunk atom */
188 static int mov_write_stsc_tag(AVIOContext *pb, MOVTrack *track)
190 int index = 0, oldval = -1, i;
191 int64_t entryPos, curpos;
193 int64_t pos = avio_tell(pb);
194 avio_wb32(pb, 0); /* size */
195 ffio_wfourcc(pb, "stsc");
196 avio_wb32(pb, 0); // version & flags
197 entryPos = avio_tell(pb);
198 avio_wb32(pb, track->chunkCount); // entry count
199 for (i = 0; i < track->entry; i++) {
200 if (oldval != track->cluster[i].samples_in_chunk && track->cluster[i].chunkNum) {
201 avio_wb32(pb, track->cluster[i].chunkNum); // first chunk
202 avio_wb32(pb, track->cluster[i].samples_in_chunk); // samples per chunk
203 avio_wb32(pb, 0x1); // sample description index
204 oldval = track->cluster[i].samples_in_chunk;
208 curpos = avio_tell(pb);
209 avio_seek(pb, entryPos, SEEK_SET);
210 avio_wb32(pb, index); // rewrite size
211 avio_seek(pb, curpos, SEEK_SET);
213 return update_size(pb, pos);
216 /* Sync sample atom */
217 static int mov_write_stss_tag(AVIOContext *pb, MOVTrack *track, uint32_t flag)
219 int64_t curpos, entryPos;
221 int64_t pos = avio_tell(pb);
222 avio_wb32(pb, 0); // size
223 ffio_wfourcc(pb, flag == MOV_SYNC_SAMPLE ? "stss" : "stps");
224 avio_wb32(pb, 0); // version & flags
225 entryPos = avio_tell(pb);
226 avio_wb32(pb, track->entry); // entry count
227 for (i = 0; i < track->entry; i++) {
228 if (track->cluster[i].flags & flag) {
229 avio_wb32(pb, i + 1);
233 curpos = avio_tell(pb);
234 avio_seek(pb, entryPos, SEEK_SET);
235 avio_wb32(pb, index); // rewrite size
236 avio_seek(pb, curpos, SEEK_SET);
237 return update_size(pb, pos);
240 static int mov_write_amr_tag(AVIOContext *pb, MOVTrack *track)
242 avio_wb32(pb, 0x11); /* size */
243 if (track->mode == MODE_MOV) ffio_wfourcc(pb, "samr");
244 else ffio_wfourcc(pb, "damr");
245 ffio_wfourcc(pb, "FFMP");
246 avio_w8(pb, 0); /* decoder version */
248 avio_wb16(pb, 0x81FF); /* Mode set (all modes for AMR_NB) */
249 avio_w8(pb, 0x00); /* Mode change period (no restriction) */
250 avio_w8(pb, 0x01); /* Frames per sample */
254 static int mov_write_ac3_tag(AVIOContext *pb, MOVTrack *track)
259 int fscod, bsid, bsmod, acmod, lfeon, frmsizecod;
261 if (track->vos_len < 7)
265 ffio_wfourcc(pb, "dac3");
267 init_get_bits(&gbc, track->vos_data + 4, (track->vos_len - 4) * 8);
268 fscod = get_bits(&gbc, 2);
269 frmsizecod = get_bits(&gbc, 6);
270 bsid = get_bits(&gbc, 5);
271 bsmod = get_bits(&gbc, 3);
272 acmod = get_bits(&gbc, 3);
274 skip_bits(&gbc, 2); // dsurmod
276 if ((acmod & 1) && acmod != 1)
277 skip_bits(&gbc, 2); // cmixlev
279 skip_bits(&gbc, 2); // surmixlev
281 lfeon = get_bits1(&gbc);
283 init_put_bits(&pbc, buf, sizeof(buf));
284 put_bits(&pbc, 2, fscod);
285 put_bits(&pbc, 5, bsid);
286 put_bits(&pbc, 3, bsmod);
287 put_bits(&pbc, 3, acmod);
288 put_bits(&pbc, 1, lfeon);
289 put_bits(&pbc, 5, frmsizecod >> 1); // bit_rate_code
290 put_bits(&pbc, 5, 0); // reserved
292 flush_put_bits(&pbc);
293 avio_write(pb, buf, sizeof(buf));
303 /* Layout of the EC3SpecificBox */
304 /* maximum bitrate */
306 /* number of independent substreams */
309 /* sample rate code (see ff_ac3_sample_rate_tab) 2 bits */
311 /* bit stream identification 5 bits */
313 /* one bit reserved */
314 /* audio service mixing (not supported yet) 1 bit */
315 /* bit stream mode 3 bits */
317 /* audio coding mode 3 bits */
319 /* sub woofer on 1 bit */
321 /* 3 bits reserved */
322 /* number of dependent substreams associated with this substream 4 bits */
324 /* channel locations of the dependent substream(s), if any, 9 bits */
326 /* if there is no dependent substream, then one bit reserved instead */
327 } substream[1]; /* TODO: support 8 independent substreams */
330 #if CONFIG_AC3_PARSER
331 static int handle_eac3(MOVMuxContext *mov, AVPacket *pkt, MOVTrack *track)
334 AC3HeaderInfo tmp, *hdr = &tmp;
335 struct eac3_info *info;
338 if (!track->eac3_priv && !(track->eac3_priv = av_mallocz(sizeof(*info))))
339 return AVERROR(ENOMEM);
340 info = track->eac3_priv;
342 init_get_bits(&gbc, pkt->data, pkt->size * 8);
343 if (avpriv_ac3_parse_header2(&gbc, &hdr) < 0) {
344 /* drop the packets until we see a good one */
346 av_log(mov, AV_LOG_WARNING, "Dropping invalid packet from start of the stream\n");
349 return AVERROR_INVALIDDATA;
352 info->data_rate = FFMAX(info->data_rate, hdr->bit_rate / 1000);
353 num_blocks = hdr->num_blocks;
355 if (!info->ec3_done) {
356 /* AC-3 substream must be the first one */
357 if (hdr->bitstream_id <= 10 && hdr->substreamid != 0)
358 return AVERROR(EINVAL);
360 /* this should always be the case, given that our AC-3 parser
361 * concatenates dependent frames to their independent parent */
362 if (hdr->frame_type == EAC3_FRAME_TYPE_INDEPENDENT) {
363 /* substream ids must be incremental */
364 if (hdr->substreamid > info->num_ind_sub + 1)
365 return AVERROR(EINVAL);
367 if (hdr->substreamid == info->num_ind_sub + 1) {
368 //info->num_ind_sub++;
369 avpriv_request_sample(track->enc, "Multiple independent substreams");
370 return AVERROR_PATCHWELCOME;
371 } else if (hdr->substreamid < info->num_ind_sub ||
372 hdr->substreamid == 0 && info->substream[0].bsid) {
378 /* fill the info needed for the "dec3" atom */
379 info->substream[hdr->substreamid].fscod = hdr->sr_code;
380 info->substream[hdr->substreamid].bsid = hdr->bitstream_id;
381 info->substream[hdr->substreamid].bsmod = hdr->bitstream_mode;
382 info->substream[hdr->substreamid].acmod = hdr->channel_mode;
383 info->substream[hdr->substreamid].lfeon = hdr->lfe_on;
385 /* Parse dependent substream(s), if any */
386 if (pkt->size != hdr->frame_size) {
387 int cumul_size = hdr->frame_size;
388 int parent = hdr->substreamid;
390 while (cumul_size != pkt->size) {
392 init_get_bits(&gbc, pkt->data + cumul_size, (pkt->size - cumul_size) * 8);
393 if (avpriv_ac3_parse_header2(&gbc, &hdr) < 0)
394 return AVERROR_INVALIDDATA;
395 if (hdr->frame_type != EAC3_FRAME_TYPE_DEPENDENT)
396 return AVERROR(EINVAL);
397 cumul_size += hdr->frame_size;
398 info->substream[parent].num_dep_sub++;
400 /* header is parsed up to lfeon, but custom channel map may be needed */
403 /* skip volume control params */
404 for (i = 0; i < (hdr->channel_mode ? 1 : 2); i++) {
405 skip_bits(&gbc, 5); // skip dialog normalization
406 if (get_bits1(&gbc)) {
407 skip_bits(&gbc, 8); // skip compression gain word
410 /* get the dependent stream channel map, if exists */
412 info->substream[parent].chan_loc |= (get_bits(&gbc, 16) >> 5) & 0x1f;
414 info->substream[parent].chan_loc |= hdr->channel_mode;
420 if (!info->num_blocks && num_blocks == 6)
422 else if (info->num_blocks + num_blocks > 6)
423 return AVERROR_INVALIDDATA;
425 if (!info->num_blocks) {
427 if ((ret = av_copy_packet(&info->pkt, pkt)) < 0)
429 info->num_blocks = num_blocks;
433 if ((ret = av_grow_packet(&info->pkt, pkt->size)) < 0)
435 memcpy(info->pkt.data + info->pkt.size - pkt->size, pkt->data, pkt->size);
436 info->num_blocks += num_blocks;
437 info->pkt.duration += pkt->duration;
438 if ((ret = av_copy_packet_side_data(&info->pkt, pkt)) < 0)
440 if (info->num_blocks != 6)
443 if ((ret = av_copy_packet(pkt, &info->pkt)) < 0)
445 av_free_packet(&info->pkt);
446 info->num_blocks = 0;
453 static int mov_write_eac3_tag(AVIOContext *pb, MOVTrack *track)
457 struct eac3_info *info;
460 if (!track->eac3_priv)
461 return AVERROR(EINVAL);
463 info = track->eac3_priv;
464 size = 2 + 4 * (info->num_ind_sub + 1);
465 buf = av_malloc(size);
467 size = AVERROR(ENOMEM);
471 init_put_bits(&pbc, buf, size);
472 put_bits(&pbc, 13, info->data_rate);
473 put_bits(&pbc, 3, info->num_ind_sub);
474 for (i = 0; i <= info->num_ind_sub; i++) {
475 put_bits(&pbc, 2, info->substream[i].fscod);
476 put_bits(&pbc, 5, info->substream[i].bsid);
477 put_bits(&pbc, 1, 0); /* reserved */
478 put_bits(&pbc, 1, 0); /* asvc */
479 put_bits(&pbc, 3, info->substream[i].bsmod);
480 put_bits(&pbc, 3, info->substream[i].acmod);
481 put_bits(&pbc, 1, info->substream[i].lfeon);
482 put_bits(&pbc, 5, 0); /* reserved */
483 put_bits(&pbc, 4, info->substream[i].num_dep_sub);
484 if (!info->substream[i].num_dep_sub) {
485 put_bits(&pbc, 1, 0); /* reserved */
488 put_bits(&pbc, 9, info->substream[i].chan_loc);
491 flush_put_bits(&pbc);
493 avio_wb32(pb, size + 8);
494 ffio_wfourcc(pb, "dec3");
495 avio_write(pb, buf, size);
500 av_free_packet(&info->pkt);
501 av_freep(&track->eac3_priv);
507 * This function writes extradata "as is".
508 * Extradata must be formatted like a valid atom (with size and tag).
510 static int mov_write_extradata_tag(AVIOContext *pb, MOVTrack *track)
512 avio_write(pb, track->enc->extradata, track->enc->extradata_size);
513 return track->enc->extradata_size;
516 static int mov_write_enda_tag(AVIOContext *pb)
519 ffio_wfourcc(pb, "enda");
520 avio_wb16(pb, 1); /* little endian */
524 static int mov_write_enda_tag_be(AVIOContext *pb)
527 ffio_wfourcc(pb, "enda");
528 avio_wb16(pb, 0); /* big endian */
532 static void put_descr(AVIOContext *pb, int tag, unsigned int size)
537 avio_w8(pb, (size >> (7 * i)) | 0x80);
538 avio_w8(pb, size & 0x7F);
541 static unsigned compute_avg_bitrate(MOVTrack *track)
545 if (!track->track_duration)
547 for (i = 0; i < track->entry; i++)
548 size += track->cluster[i].size;
549 return size * 8 * track->timescale / track->track_duration;
552 static int mov_write_esds_tag(AVIOContext *pb, MOVTrack *track) // Basic
554 int64_t pos = avio_tell(pb);
555 int decoder_specific_info_len = track->vos_len ? 5 + track->vos_len : 0;
556 unsigned avg_bitrate;
558 avio_wb32(pb, 0); // size
559 ffio_wfourcc(pb, "esds");
560 avio_wb32(pb, 0); // Version
563 put_descr(pb, 0x03, 3 + 5+13 + decoder_specific_info_len + 5+1);
564 avio_wb16(pb, track->track_id);
565 avio_w8(pb, 0x00); // flags (= no flags)
567 // DecoderConfig descriptor
568 put_descr(pb, 0x04, 13 + decoder_specific_info_len);
570 // Object type indication
571 if ((track->enc->codec_id == AV_CODEC_ID_MP2 ||
572 track->enc->codec_id == AV_CODEC_ID_MP3) &&
573 track->enc->sample_rate > 24000)
574 avio_w8(pb, 0x6B); // 11172-3
576 avio_w8(pb, ff_codec_get_tag(ff_mp4_obj_type, track->enc->codec_id));
578 // the following fields is made of 6 bits to identify the streamtype (4 for video, 5 for audio)
579 // plus 1 bit to indicate upstream and 1 bit set to 1 (reserved)
580 if (track->enc->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
581 avio_w8(pb, (0x38 << 2) | 1); // flags (= NeroSubpicStream)
582 else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
583 avio_w8(pb, 0x15); // flags (= Audiostream)
585 avio_w8(pb, 0x11); // flags (= Visualstream)
587 avio_wb24(pb, track->enc->rc_buffer_size >> 3); // Buffersize DB
589 avg_bitrate = compute_avg_bitrate(track);
590 // maxbitrate (FIXME should be max rate in any 1 sec window)
591 avio_wb32(pb, FFMAX3(track->enc->bit_rate, track->enc->rc_max_rate, avg_bitrate));
592 avio_wb32(pb, avg_bitrate);
594 if (track->vos_len) {
595 // DecoderSpecific info descriptor
596 put_descr(pb, 0x05, track->vos_len);
597 avio_write(pb, track->vos_data, track->vos_len);
601 put_descr(pb, 0x06, 1);
603 return update_size(pb, pos);
606 static int mov_pcm_le_gt16(enum AVCodecID codec_id)
608 return codec_id == AV_CODEC_ID_PCM_S24LE ||
609 codec_id == AV_CODEC_ID_PCM_S32LE ||
610 codec_id == AV_CODEC_ID_PCM_F32LE ||
611 codec_id == AV_CODEC_ID_PCM_F64LE;
614 static int mov_pcm_be_gt16(enum AVCodecID codec_id)
616 return codec_id == AV_CODEC_ID_PCM_S24BE ||
617 codec_id == AV_CODEC_ID_PCM_S32BE ||
618 codec_id == AV_CODEC_ID_PCM_F32BE ||
619 codec_id == AV_CODEC_ID_PCM_F64BE;
622 static int mov_write_ms_tag(AVIOContext *pb, MOVTrack *track)
625 int64_t pos = avio_tell(pb);
627 avio_wl32(pb, track->tag); // store it byteswapped
628 track->enc->codec_tag = av_bswap16(track->tag >> 16);
629 if ((ret = ff_put_wav_header(pb, track->enc, 0)) < 0)
631 return update_size(pb, pos);
634 static int mov_write_wfex_tag(AVIOContext *pb, MOVTrack *track)
637 int64_t pos = avio_tell(pb);
639 ffio_wfourcc(pb, "wfex");
640 if ((ret = ff_put_wav_header(pb, track->enc, FF_PUT_WAV_HEADER_FORCE_WAVEFORMATEX)) < 0)
642 return update_size(pb, pos);
645 static int mov_write_chan_tag(AVIOContext *pb, MOVTrack *track)
647 uint32_t layout_tag, bitmap;
648 int64_t pos = avio_tell(pb);
650 layout_tag = ff_mov_get_channel_layout_tag(track->enc->codec_id,
651 track->enc->channel_layout,
654 av_log(track->enc, AV_LOG_WARNING, "not writing 'chan' tag due to "
655 "lack of channel information\n");
659 if (track->multichannel_as_mono)
662 avio_wb32(pb, 0); // Size
663 ffio_wfourcc(pb, "chan"); // Type
664 avio_w8(pb, 0); // Version
665 avio_wb24(pb, 0); // Flags
666 avio_wb32(pb, layout_tag); // mChannelLayoutTag
667 avio_wb32(pb, bitmap); // mChannelBitmap
668 avio_wb32(pb, 0); // mNumberChannelDescriptions
670 return update_size(pb, pos);
673 static int mov_write_wave_tag(AVIOContext *pb, MOVTrack *track)
675 int64_t pos = avio_tell(pb);
677 avio_wb32(pb, 0); /* size */
678 ffio_wfourcc(pb, "wave");
680 if (track->enc->codec_id != AV_CODEC_ID_QDM2) {
681 avio_wb32(pb, 12); /* size */
682 ffio_wfourcc(pb, "frma");
683 avio_wl32(pb, track->tag);
686 if (track->enc->codec_id == AV_CODEC_ID_AAC) {
687 /* useless atom needed by mplayer, ipod, not needed by quicktime */
688 avio_wb32(pb, 12); /* size */
689 ffio_wfourcc(pb, "mp4a");
691 mov_write_esds_tag(pb, track);
692 } else if (mov_pcm_le_gt16(track->enc->codec_id)) {
693 mov_write_enda_tag(pb);
694 } else if (mov_pcm_be_gt16(track->enc->codec_id)) {
695 mov_write_enda_tag_be(pb);
696 } else if (track->enc->codec_id == AV_CODEC_ID_AMR_NB) {
697 mov_write_amr_tag(pb, track);
698 } else if (track->enc->codec_id == AV_CODEC_ID_AC3) {
699 mov_write_ac3_tag(pb, track);
700 } else if (track->enc->codec_id == AV_CODEC_ID_EAC3) {
701 mov_write_eac3_tag(pb, track);
702 } else if (track->enc->codec_id == AV_CODEC_ID_ALAC ||
703 track->enc->codec_id == AV_CODEC_ID_QDM2) {
704 mov_write_extradata_tag(pb, track);
705 } else if (track->enc->codec_id == AV_CODEC_ID_ADPCM_MS ||
706 track->enc->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) {
707 mov_write_ms_tag(pb, track);
710 avio_wb32(pb, 8); /* size */
711 avio_wb32(pb, 0); /* null tag */
713 return update_size(pb, pos);
716 static int mov_write_dvc1_structs(MOVTrack *track, uint8_t *buf)
719 const uint8_t *start, *next, *end = track->vos_data + track->vos_len;
720 int unescaped_size, seq_found = 0;
721 int level = 0, interlace = 0;
722 int packet_seq = track->vc1_info.packet_seq;
723 int packet_entry = track->vc1_info.packet_entry;
724 int slices = track->vc1_info.slices;
727 if (track->start_dts == AV_NOPTS_VALUE) {
728 /* No packets written yet, vc1_info isn't authoritative yet. */
729 /* Assume inline sequence and entry headers. */
730 packet_seq = packet_entry = 1;
731 av_log(NULL, AV_LOG_WARNING,
732 "moov atom written before any packets, unable to write correct "
733 "dvc1 atom. Set the delay_moov flag to fix this.\n");
736 unescaped = av_mallocz(track->vos_len + FF_INPUT_BUFFER_PADDING_SIZE);
738 return AVERROR(ENOMEM);
739 start = find_next_marker(track->vos_data, end);
740 for (next = start; next < end; start = next) {
743 next = find_next_marker(start + 4, end);
744 size = next - start - 4;
747 unescaped_size = vc1_unescape_buffer(start + 4, size, unescaped);
748 init_get_bits(&gb, unescaped, 8 * unescaped_size);
749 if (AV_RB32(start) == VC1_CODE_SEQHDR) {
750 int profile = get_bits(&gb, 2);
751 if (profile != PROFILE_ADVANCED) {
753 return AVERROR(ENOSYS);
756 level = get_bits(&gb, 3);
757 /* chromaformat, frmrtq_postproc, bitrtq_postproc, postprocflag,
759 skip_bits_long(&gb, 2 + 3 + 5 + 1 + 2*12);
760 skip_bits(&gb, 1); /* broadcast */
761 interlace = get_bits1(&gb);
762 skip_bits(&gb, 4); /* tfcntrflag, finterpflag, reserved, psf */
767 return AVERROR(ENOSYS);
770 init_put_bits(&pbc, buf, 7);
771 /* VC1DecSpecStruc */
772 put_bits(&pbc, 4, 12); /* profile - advanced */
773 put_bits(&pbc, 3, level);
774 put_bits(&pbc, 1, 0); /* reserved */
775 /* VC1AdvDecSpecStruc */
776 put_bits(&pbc, 3, level);
777 put_bits(&pbc, 1, 0); /* cbr */
778 put_bits(&pbc, 6, 0); /* reserved */
779 put_bits(&pbc, 1, !interlace); /* no interlace */
780 put_bits(&pbc, 1, !packet_seq); /* no multiple seq */
781 put_bits(&pbc, 1, !packet_entry); /* no multiple entry */
782 put_bits(&pbc, 1, !slices); /* no slice code */
783 put_bits(&pbc, 1, 0); /* no bframe */
784 put_bits(&pbc, 1, 0); /* reserved */
787 if (track->st->avg_frame_rate.num > 0 && track->st->avg_frame_rate.den > 0)
788 put_bits32(&pbc, track->st->avg_frame_rate.num / track->st->avg_frame_rate.den);
790 put_bits32(&pbc, 0xffffffff);
792 flush_put_bits(&pbc);
799 static int mov_write_dvc1_tag(AVIOContext *pb, MOVTrack *track)
801 uint8_t buf[7] = { 0 };
804 if ((ret = mov_write_dvc1_structs(track, buf)) < 0)
807 avio_wb32(pb, track->vos_len + 8 + sizeof(buf));
808 ffio_wfourcc(pb, "dvc1");
809 avio_write(pb, buf, sizeof(buf));
810 avio_write(pb, track->vos_data, track->vos_len);
815 static int mov_write_glbl_tag(AVIOContext *pb, MOVTrack *track)
817 avio_wb32(pb, track->vos_len + 8);
818 ffio_wfourcc(pb, "glbl");
819 avio_write(pb, track->vos_data, track->vos_len);
820 return 8 + track->vos_len;
824 * Compute flags for 'lpcm' tag.
825 * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
827 static int mov_get_lpcm_flags(enum AVCodecID codec_id)
830 case AV_CODEC_ID_PCM_F32BE:
831 case AV_CODEC_ID_PCM_F64BE:
833 case AV_CODEC_ID_PCM_F32LE:
834 case AV_CODEC_ID_PCM_F64LE:
836 case AV_CODEC_ID_PCM_U8:
838 case AV_CODEC_ID_PCM_S16BE:
839 case AV_CODEC_ID_PCM_S24BE:
840 case AV_CODEC_ID_PCM_S32BE:
842 case AV_CODEC_ID_PCM_S8:
843 case AV_CODEC_ID_PCM_S16LE:
844 case AV_CODEC_ID_PCM_S24LE:
845 case AV_CODEC_ID_PCM_S32LE:
852 static int get_cluster_duration(MOVTrack *track, int cluster_idx)
856 if (cluster_idx >= track->entry)
859 if (cluster_idx + 1 == track->entry)
860 next_dts = track->track_duration + track->start_dts;
862 next_dts = track->cluster[cluster_idx + 1].dts;
864 next_dts -= track->cluster[cluster_idx].dts;
866 av_assert0(next_dts >= 0);
867 av_assert0(next_dts <= INT_MAX);
872 static int get_samples_per_packet(MOVTrack *track)
874 int i, first_duration;
876 // return track->enc->frame_size;
878 /* use 1 for raw PCM */
879 if (!track->audio_vbr)
882 /* check to see if duration is constant for all clusters */
885 first_duration = get_cluster_duration(track, 0);
886 for (i = 1; i < track->entry; i++) {
887 if (get_cluster_duration(track, i) != first_duration)
890 return first_duration;
893 static int mov_write_audio_tag(AVIOContext *pb, MOVTrack *track)
895 int64_t pos = avio_tell(pb);
897 uint32_t tag = track->tag;
899 if (track->mode == MODE_MOV) {
900 if (track->timescale > UINT16_MAX) {
901 if (mov_get_lpcm_flags(track->enc->codec_id))
902 tag = AV_RL32("lpcm");
904 } else if (track->audio_vbr || mov_pcm_le_gt16(track->enc->codec_id) ||
905 mov_pcm_be_gt16(track->enc->codec_id) ||
906 track->enc->codec_id == AV_CODEC_ID_ADPCM_MS ||
907 track->enc->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
908 track->enc->codec_id == AV_CODEC_ID_QDM2) {
913 avio_wb32(pb, 0); /* size */
914 avio_wl32(pb, tag); // store it byteswapped
915 avio_wb32(pb, 0); /* Reserved */
916 avio_wb16(pb, 0); /* Reserved */
917 avio_wb16(pb, 1); /* Data-reference index, XXX == 1 */
919 /* SoundDescription */
920 avio_wb16(pb, version); /* Version */
921 avio_wb16(pb, 0); /* Revision level */
922 avio_wb32(pb, 0); /* Reserved */
927 avio_wb16(pb, 0xfffe);
929 avio_wb32(pb, 0x00010000);
931 avio_wb64(pb, av_double2int(track->enc->sample_rate));
932 avio_wb32(pb, track->enc->channels);
933 avio_wb32(pb, 0x7F000000);
934 avio_wb32(pb, av_get_bits_per_sample(track->enc->codec_id));
935 avio_wb32(pb, mov_get_lpcm_flags(track->enc->codec_id));
936 avio_wb32(pb, track->sample_size);
937 avio_wb32(pb, get_samples_per_packet(track));
939 if (track->mode == MODE_MOV) {
940 avio_wb16(pb, track->enc->channels);
941 if (track->enc->codec_id == AV_CODEC_ID_PCM_U8 ||
942 track->enc->codec_id == AV_CODEC_ID_PCM_S8)
943 avio_wb16(pb, 8); /* bits per sample */
944 else if (track->enc->codec_id == AV_CODEC_ID_ADPCM_G726)
945 avio_wb16(pb, track->enc->bits_per_coded_sample);
948 avio_wb16(pb, track->audio_vbr ? -2 : 0); /* compression ID */
949 } else { /* reserved for mp4/3gp */
955 avio_wb16(pb, 0); /* packet size (= 0) */
956 avio_wb16(pb, track->enc->sample_rate <= UINT16_MAX ?
957 track->enc->sample_rate : 0);
958 avio_wb16(pb, 0); /* Reserved */
961 if (version == 1) { /* SoundDescription V1 extended info */
962 if (mov_pcm_le_gt16(track->enc->codec_id) ||
963 mov_pcm_be_gt16(track->enc->codec_id))
964 avio_wb32(pb, 1); /* must be 1 for uncompressed formats */
966 avio_wb32(pb, track->enc->frame_size); /* Samples per packet */
967 avio_wb32(pb, track->sample_size / track->enc->channels); /* Bytes per packet */
968 avio_wb32(pb, track->sample_size); /* Bytes per frame */
969 avio_wb32(pb, 2); /* Bytes per sample */
972 if (track->mode == MODE_MOV &&
973 (track->enc->codec_id == AV_CODEC_ID_AAC ||
974 track->enc->codec_id == AV_CODEC_ID_AC3 ||
975 track->enc->codec_id == AV_CODEC_ID_EAC3 ||
976 track->enc->codec_id == AV_CODEC_ID_AMR_NB ||
977 track->enc->codec_id == AV_CODEC_ID_ALAC ||
978 track->enc->codec_id == AV_CODEC_ID_ADPCM_MS ||
979 track->enc->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
980 track->enc->codec_id == AV_CODEC_ID_QDM2 ||
981 (mov_pcm_le_gt16(track->enc->codec_id) && version==1) ||
982 (mov_pcm_be_gt16(track->enc->codec_id) && version==1)))
983 mov_write_wave_tag(pb, track);
984 else if (track->tag == MKTAG('m','p','4','a'))
985 mov_write_esds_tag(pb, track);
986 else if (track->enc->codec_id == AV_CODEC_ID_AMR_NB)
987 mov_write_amr_tag(pb, track);
988 else if (track->enc->codec_id == AV_CODEC_ID_AC3)
989 mov_write_ac3_tag(pb, track);
990 else if (track->enc->codec_id == AV_CODEC_ID_EAC3)
991 mov_write_eac3_tag(pb, track);
992 else if (track->enc->codec_id == AV_CODEC_ID_ALAC)
993 mov_write_extradata_tag(pb, track);
994 else if (track->enc->codec_id == AV_CODEC_ID_WMAPRO)
995 mov_write_wfex_tag(pb, track);
996 else if (track->vos_len > 0)
997 mov_write_glbl_tag(pb, track);
999 if (track->mode == MODE_MOV && track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
1000 mov_write_chan_tag(pb, track);
1002 return update_size(pb, pos);
1005 static int mov_write_d263_tag(AVIOContext *pb)
1007 avio_wb32(pb, 0xf); /* size */
1008 ffio_wfourcc(pb, "d263");
1009 ffio_wfourcc(pb, "FFMP");
1010 avio_w8(pb, 0); /* decoder version */
1011 /* FIXME use AVCodecContext level/profile, when encoder will set values */
1012 avio_w8(pb, 0xa); /* level */
1013 avio_w8(pb, 0); /* profile */
1017 static int mov_write_avcc_tag(AVIOContext *pb, MOVTrack *track)
1019 int64_t pos = avio_tell(pb);
1022 ffio_wfourcc(pb, "avcC");
1023 ff_isom_write_avcc(pb, track->vos_data, track->vos_len);
1024 return update_size(pb, pos);
1027 static int mov_write_hvcc_tag(AVIOContext *pb, MOVTrack *track)
1029 int64_t pos = avio_tell(pb);
1032 ffio_wfourcc(pb, "hvcC");
1033 ff_isom_write_hvcc(pb, track->vos_data, track->vos_len, 0);
1034 return update_size(pb, pos);
1037 /* also used by all avid codecs (dv, imx, meridien) and their variants */
1038 static int mov_write_avid_tag(AVIOContext *pb, MOVTrack *track)
1044 if (track->vos_data && track->vos_len > 0x29) {
1045 if (track->vos_data[0] == 0x00 &&
1046 track->vos_data[1] == 0x00 &&
1047 track->vos_data[2] == 0x02 &&
1048 track->vos_data[3] == 0x80 &&
1049 (track->vos_data[4] == 0x01 || track->vos_data[4] == 0x02)) {
1050 /* looks like a DNxHD bit stream */
1051 interlaced = (track->vos_data[5] & 2);
1052 cid = AV_RB32(track->vos_data + 0x28);
1054 av_log(NULL, AV_LOG_WARNING, "Could not locate DNxHD bit stream in vos_data\n");
1058 av_log(NULL, AV_LOG_WARNING, "Could not locate DNxHD bit stream, vos_data too small\n");
1062 avio_wb32(pb, 24); /* size */
1063 ffio_wfourcc(pb, "ACLR");
1064 ffio_wfourcc(pb, "ACLR");
1065 ffio_wfourcc(pb, "0001");
1066 if (track->enc->color_range == AVCOL_RANGE_MPEG || /* Legal range (16-235) */
1067 track->enc->color_range == AVCOL_RANGE_UNSPECIFIED) {
1068 avio_wb32(pb, 1); /* Corresponds to 709 in official encoder */
1069 } else { /* Full range (0-255) */
1070 avio_wb32(pb, 2); /* Corresponds to RGB in official encoder */
1072 avio_wb32(pb, 0); /* unknown */
1074 avio_wb32(pb, 24); /* size */
1075 ffio_wfourcc(pb, "APRG");
1076 ffio_wfourcc(pb, "APRG");
1077 ffio_wfourcc(pb, "0001");
1078 avio_wb32(pb, 1); /* unknown */
1079 avio_wb32(pb, 0); /* unknown */
1081 avio_wb32(pb, 120); /* size */
1082 ffio_wfourcc(pb, "ARES");
1083 ffio_wfourcc(pb, "ARES");
1084 ffio_wfourcc(pb, "0001");
1085 avio_wb32(pb, cid); /* dnxhd cid, some id ? */
1086 avio_wb32(pb, track->enc->width);
1087 /* values below are based on samples created with quicktime and avid codecs */
1089 avio_wb32(pb, track->enc->height / 2);
1090 avio_wb32(pb, 2); /* unknown */
1091 avio_wb32(pb, 0); /* unknown */
1092 avio_wb32(pb, 4); /* unknown */
1094 avio_wb32(pb, track->enc->height);
1095 avio_wb32(pb, 1); /* unknown */
1096 avio_wb32(pb, 0); /* unknown */
1097 if (track->enc->height == 1080)
1098 avio_wb32(pb, 5); /* unknown */
1100 avio_wb32(pb, 6); /* unknown */
1103 for (i = 0; i < 10; i++)
1109 static int mov_write_dpxe_tag(AVIOContext *pb, MOVTrack *track)
1112 ffio_wfourcc(pb, "DpxE");
1113 if (track->enc->extradata_size >= 12 &&
1114 !memcmp(&track->enc->extradata[4], "DpxE", 4)) {
1115 avio_wb32(pb, track->enc->extradata[11]);
1122 static int mp4_get_codec_tag(AVFormatContext *s, MOVTrack *track)
1124 int tag = track->enc->codec_tag;
1126 if (!ff_codec_get_tag(ff_mp4_obj_type, track->enc->codec_id))
1129 if (track->enc->codec_id == AV_CODEC_ID_H264) tag = MKTAG('a','v','c','1');
1130 else if (track->enc->codec_id == AV_CODEC_ID_HEVC) tag = MKTAG('h','e','v','1');
1131 else if (track->enc->codec_id == AV_CODEC_ID_AC3) tag = MKTAG('a','c','-','3');
1132 else if (track->enc->codec_id == AV_CODEC_ID_EAC3) tag = MKTAG('e','c','-','3');
1133 else if (track->enc->codec_id == AV_CODEC_ID_DIRAC) tag = MKTAG('d','r','a','c');
1134 else if (track->enc->codec_id == AV_CODEC_ID_MOV_TEXT) tag = MKTAG('t','x','3','g');
1135 else if (track->enc->codec_id == AV_CODEC_ID_VC1) tag = MKTAG('v','c','-','1');
1136 else if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) tag = MKTAG('m','p','4','v');
1137 else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO) tag = MKTAG('m','p','4','a');
1138 else if (track->enc->codec_id == AV_CODEC_ID_DVD_SUBTITLE) tag = MKTAG('m','p','4','s');
1143 static const AVCodecTag codec_ipod_tags[] = {
1144 { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
1145 { AV_CODEC_ID_MPEG4, MKTAG('m','p','4','v') },
1146 { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
1147 { AV_CODEC_ID_ALAC, MKTAG('a','l','a','c') },
1148 { AV_CODEC_ID_AC3, MKTAG('a','c','-','3') },
1149 { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
1150 { AV_CODEC_ID_MOV_TEXT, MKTAG('t','e','x','t') },
1151 { AV_CODEC_ID_NONE, 0 },
1154 static int ipod_get_codec_tag(AVFormatContext *s, MOVTrack *track)
1156 int tag = track->enc->codec_tag;
1158 // keep original tag for subs, ipod supports both formats
1159 if (!(track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE &&
1160 (tag == MKTAG('t', 'x', '3', 'g') ||
1161 tag == MKTAG('t', 'e', 'x', 't'))))
1162 tag = ff_codec_get_tag(codec_ipod_tags, track->enc->codec_id);
1164 if (!av_match_ext(s->filename, "m4a") &&
1165 !av_match_ext(s->filename, "m4b") &&
1166 !av_match_ext(s->filename, "m4v"))
1167 av_log(s, AV_LOG_WARNING, "Warning, extension is not .m4a, .m4v nor .m4b "
1168 "Quicktime/Ipod might not play the file\n");
1173 static int mov_get_dv_codec_tag(AVFormatContext *s, MOVTrack *track)
1177 if (track->enc->width == 720) { /* SD */
1178 if (track->enc->height == 480) { /* NTSC */
1179 if (track->enc->pix_fmt == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','n');
1180 else tag = MKTAG('d','v','c',' ');
1181 }else if (track->enc->pix_fmt == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','p');
1182 else if (track->enc->pix_fmt == AV_PIX_FMT_YUV420P) tag = MKTAG('d','v','c','p');
1183 else tag = MKTAG('d','v','p','p');
1184 } else if (track->enc->height == 720) { /* HD 720 line */
1185 if (track->st->time_base.den == 50) tag = MKTAG('d','v','h','q');
1186 else tag = MKTAG('d','v','h','p');
1187 } else if (track->enc->height == 1080) { /* HD 1080 line */
1188 if (track->st->time_base.den == 25) tag = MKTAG('d','v','h','5');
1189 else tag = MKTAG('d','v','h','6');
1191 av_log(s, AV_LOG_ERROR, "unsupported height for dv codec\n");
1198 static AVRational find_fps(AVFormatContext *s, AVStream *st)
1200 AVRational rate = {st->codec->time_base.den, st->codec->time_base.num};
1201 /* if the codec time base makes no sense, try to fallback on stream frame rate */
1202 if (av_timecode_check_frame_rate(rate) < 0) {
1203 av_log(s, AV_LOG_DEBUG, "timecode: tbc=%d/%d invalid, fallback on %d/%d\n",
1204 rate.num, rate.den, st->avg_frame_rate.num, st->avg_frame_rate.den);
1205 rate = st->avg_frame_rate;
1211 static int mov_get_mpeg2_xdcam_codec_tag(AVFormatContext *s, MOVTrack *track)
1213 int tag = track->enc->codec_tag;
1214 int interlaced = track->enc->field_order > AV_FIELD_PROGRESSIVE;
1215 AVStream *st = track->st;
1216 int rate = av_q2d(find_fps(s, st));
1219 tag = MKTAG('m', '2', 'v', '1'); //fallback tag
1221 if (track->enc->pix_fmt == AV_PIX_FMT_YUV420P) {
1222 if (track->enc->width == 1280 && track->enc->height == 720) {
1224 if (rate == 24) tag = MKTAG('x','d','v','4');
1225 else if (rate == 25) tag = MKTAG('x','d','v','5');
1226 else if (rate == 30) tag = MKTAG('x','d','v','1');
1227 else if (rate == 50) tag = MKTAG('x','d','v','a');
1228 else if (rate == 60) tag = MKTAG('x','d','v','9');
1230 } else if (track->enc->width == 1440 && track->enc->height == 1080) {
1232 if (rate == 24) tag = MKTAG('x','d','v','6');
1233 else if (rate == 25) tag = MKTAG('x','d','v','7');
1234 else if (rate == 30) tag = MKTAG('x','d','v','8');
1236 if (rate == 25) tag = MKTAG('x','d','v','3');
1237 else if (rate == 30) tag = MKTAG('x','d','v','2');
1239 } else if (track->enc->width == 1920 && track->enc->height == 1080) {
1241 if (rate == 24) tag = MKTAG('x','d','v','d');
1242 else if (rate == 25) tag = MKTAG('x','d','v','e');
1243 else if (rate == 30) tag = MKTAG('x','d','v','f');
1245 if (rate == 25) tag = MKTAG('x','d','v','c');
1246 else if (rate == 30) tag = MKTAG('x','d','v','b');
1249 } else if (track->enc->pix_fmt == AV_PIX_FMT_YUV422P) {
1250 if (track->enc->width == 1280 && track->enc->height == 720) {
1252 if (rate == 24) tag = MKTAG('x','d','5','4');
1253 else if (rate == 25) tag = MKTAG('x','d','5','5');
1254 else if (rate == 30) tag = MKTAG('x','d','5','1');
1255 else if (rate == 50) tag = MKTAG('x','d','5','a');
1256 else if (rate == 60) tag = MKTAG('x','d','5','9');
1258 } else if (track->enc->width == 1920 && track->enc->height == 1080) {
1260 if (rate == 24) tag = MKTAG('x','d','5','d');
1261 else if (rate == 25) tag = MKTAG('x','d','5','e');
1262 else if (rate == 30) tag = MKTAG('x','d','5','f');
1264 if (rate == 25) tag = MKTAG('x','d','5','c');
1265 else if (rate == 30) tag = MKTAG('x','d','5','b');
1273 static int mov_get_h264_codec_tag(AVFormatContext *s, MOVTrack *track)
1275 int tag = track->enc->codec_tag;
1276 int interlaced = track->enc->field_order > AV_FIELD_PROGRESSIVE;
1277 AVStream *st = track->st;
1278 int rate = av_q2d(find_fps(s, st));
1281 tag = MKTAG('a', 'v', 'c', 'i'); //fallback tag
1283 if (track->enc->pix_fmt == AV_PIX_FMT_YUV420P10) {
1284 if (track->enc->width == 960 && track->enc->height == 720) {
1286 if (rate == 24) tag = MKTAG('a','i','5','p');
1287 else if (rate == 25) tag = MKTAG('a','i','5','q');
1288 else if (rate == 30) tag = MKTAG('a','i','5','p');
1289 else if (rate == 50) tag = MKTAG('a','i','5','q');
1290 else if (rate == 60) tag = MKTAG('a','i','5','p');
1292 } else if (track->enc->width == 1440 && track->enc->height == 1080) {
1294 if (rate == 24) tag = MKTAG('a','i','5','3');
1295 else if (rate == 25) tag = MKTAG('a','i','5','2');
1296 else if (rate == 30) tag = MKTAG('a','i','5','3');
1298 if (rate == 50) tag = MKTAG('a','i','5','5');
1299 else if (rate == 60) tag = MKTAG('a','i','5','6');
1302 } else if (track->enc->pix_fmt == AV_PIX_FMT_YUV422P10) {
1303 if (track->enc->width == 1280 && track->enc->height == 720) {
1305 if (rate == 24) tag = MKTAG('a','i','1','p');
1306 else if (rate == 25) tag = MKTAG('a','i','1','q');
1307 else if (rate == 30) tag = MKTAG('a','i','1','p');
1308 else if (rate == 50) tag = MKTAG('a','i','1','q');
1309 else if (rate == 60) tag = MKTAG('a','i','1','p');
1311 } else if (track->enc->width == 1920 && track->enc->height == 1080) {
1313 if (rate == 24) tag = MKTAG('a','i','1','3');
1314 else if (rate == 25) tag = MKTAG('a','i','1','2');
1315 else if (rate == 30) tag = MKTAG('a','i','1','3');
1317 if (rate == 25) tag = MKTAG('a','i','1','5');
1318 else if (rate == 50) tag = MKTAG('a','i','1','5');
1319 else if (rate == 60) tag = MKTAG('a','i','1','6');
1321 } else if ( track->enc->width == 4096 && track->enc->height == 2160
1322 || track->enc->width == 3840 && track->enc->height == 2160
1323 || track->enc->width == 2048 && track->enc->height == 1080) {
1324 tag = MKTAG('a','i','v','x');
1331 static const struct {
1332 enum AVPixelFormat pix_fmt;
1335 } mov_pix_fmt_tags[] = {
1336 { AV_PIX_FMT_YUYV422, MKTAG('y','u','v','2'), 0 },
1337 { AV_PIX_FMT_YUYV422, MKTAG('y','u','v','s'), 0 },
1338 { AV_PIX_FMT_UYVY422, MKTAG('2','v','u','y'), 0 },
1339 { AV_PIX_FMT_RGB555BE,MKTAG('r','a','w',' '), 16 },
1340 { AV_PIX_FMT_RGB555LE,MKTAG('L','5','5','5'), 16 },
1341 { AV_PIX_FMT_RGB565LE,MKTAG('L','5','6','5'), 16 },
1342 { AV_PIX_FMT_RGB565BE,MKTAG('B','5','6','5'), 16 },
1343 { AV_PIX_FMT_GRAY16BE,MKTAG('b','1','6','g'), 16 },
1344 { AV_PIX_FMT_RGB24, MKTAG('r','a','w',' '), 24 },
1345 { AV_PIX_FMT_BGR24, MKTAG('2','4','B','G'), 24 },
1346 { AV_PIX_FMT_ARGB, MKTAG('r','a','w',' '), 32 },
1347 { AV_PIX_FMT_BGRA, MKTAG('B','G','R','A'), 32 },
1348 { AV_PIX_FMT_RGBA, MKTAG('R','G','B','A'), 32 },
1349 { AV_PIX_FMT_ABGR, MKTAG('A','B','G','R'), 32 },
1350 { AV_PIX_FMT_RGB48BE, MKTAG('b','4','8','r'), 48 },
1353 static int mov_get_rawvideo_codec_tag(AVFormatContext *s, MOVTrack *track)
1355 int tag = track->enc->codec_tag;
1357 enum AVPixelFormat pix_fmt;
1359 for (i = 0; i < FF_ARRAY_ELEMS(mov_pix_fmt_tags); i++) {
1360 if (track->enc->pix_fmt == mov_pix_fmt_tags[i].pix_fmt) {
1361 tag = mov_pix_fmt_tags[i].tag;
1362 track->enc->bits_per_coded_sample = mov_pix_fmt_tags[i].bps;
1363 if (track->enc->codec_tag == mov_pix_fmt_tags[i].tag)
1368 pix_fmt = avpriv_find_pix_fmt(avpriv_pix_fmt_bps_mov,
1369 track->enc->bits_per_coded_sample);
1370 if (tag == MKTAG('r','a','w',' ') &&
1371 track->enc->pix_fmt != pix_fmt &&
1372 track->enc->pix_fmt != AV_PIX_FMT_NONE)
1373 av_log(s, AV_LOG_ERROR, "%s rawvideo cannot be written to mov, output file will be unreadable\n",
1374 av_get_pix_fmt_name(track->enc->pix_fmt));
1378 static int mov_get_codec_tag(AVFormatContext *s, MOVTrack *track)
1380 int tag = track->enc->codec_tag;
1382 if (!tag || (s->strict_std_compliance >= FF_COMPLIANCE_NORMAL &&
1383 (track->enc->codec_id == AV_CODEC_ID_DVVIDEO ||
1384 track->enc->codec_id == AV_CODEC_ID_RAWVIDEO ||
1385 track->enc->codec_id == AV_CODEC_ID_H263 ||
1386 track->enc->codec_id == AV_CODEC_ID_H264 ||
1387 track->enc->codec_id == AV_CODEC_ID_MPEG2VIDEO ||
1388 av_get_bits_per_sample(track->enc->codec_id)))) { // pcm audio
1389 if (track->enc->codec_id == AV_CODEC_ID_DVVIDEO)
1390 tag = mov_get_dv_codec_tag(s, track);
1391 else if (track->enc->codec_id == AV_CODEC_ID_RAWVIDEO)
1392 tag = mov_get_rawvideo_codec_tag(s, track);
1393 else if (track->enc->codec_id == AV_CODEC_ID_MPEG2VIDEO)
1394 tag = mov_get_mpeg2_xdcam_codec_tag(s, track);
1395 else if (track->enc->codec_id == AV_CODEC_ID_H264)
1396 tag = mov_get_h264_codec_tag(s, track);
1397 else if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1398 tag = ff_codec_get_tag(ff_codec_movvideo_tags, track->enc->codec_id);
1399 if (!tag) { // if no mac fcc found, try with Microsoft tags
1400 tag = ff_codec_get_tag(ff_codec_bmp_tags, track->enc->codec_id);
1402 av_log(s, AV_LOG_WARNING, "Using MS style video codec tag, "
1403 "the file may be unplayable!\n");
1405 } else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO) {
1406 tag = ff_codec_get_tag(ff_codec_movaudio_tags, track->enc->codec_id);
1407 if (!tag) { // if no mac fcc found, try with Microsoft tags
1408 int ms_tag = ff_codec_get_tag(ff_codec_wav_tags, track->enc->codec_id);
1410 tag = MKTAG('m', 's', ((ms_tag >> 8) & 0xff), (ms_tag & 0xff));
1411 av_log(s, AV_LOG_WARNING, "Using MS style audio codec tag, "
1412 "the file may be unplayable!\n");
1415 } else if (track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE)
1416 tag = ff_codec_get_tag(ff_codec_movsubtitle_tags, track->enc->codec_id);
1422 static const AVCodecTag codec_3gp_tags[] = {
1423 { AV_CODEC_ID_H263, MKTAG('s','2','6','3') },
1424 { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
1425 { AV_CODEC_ID_MPEG4, MKTAG('m','p','4','v') },
1426 { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
1427 { AV_CODEC_ID_AMR_NB, MKTAG('s','a','m','r') },
1428 { AV_CODEC_ID_AMR_WB, MKTAG('s','a','w','b') },
1429 { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
1430 { AV_CODEC_ID_NONE, 0 },
1433 static const AVCodecTag codec_f4v_tags[] = { // XXX: add GIF/PNG/JPEG?
1434 { AV_CODEC_ID_MP3, MKTAG('.','m','p','3') },
1435 { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
1436 { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
1437 { AV_CODEC_ID_VP6A, MKTAG('V','P','6','A') },
1438 { AV_CODEC_ID_VP6F, MKTAG('V','P','6','F') },
1439 { AV_CODEC_ID_NONE, 0 },
1442 static int mov_find_codec_tag(AVFormatContext *s, MOVTrack *track)
1446 if (track->mode == MODE_MP4 || track->mode == MODE_PSP)
1447 tag = mp4_get_codec_tag(s, track);
1448 else if (track->mode == MODE_ISM) {
1449 tag = mp4_get_codec_tag(s, track);
1450 if (!tag && track->enc->codec_id == AV_CODEC_ID_WMAPRO)
1451 tag = MKTAG('w', 'm', 'a', ' ');
1452 } else if (track->mode == MODE_IPOD)
1453 tag = ipod_get_codec_tag(s, track);
1454 else if (track->mode & MODE_3GP)
1455 tag = ff_codec_get_tag(codec_3gp_tags, track->enc->codec_id);
1456 else if (track->mode == MODE_F4V)
1457 tag = ff_codec_get_tag(codec_f4v_tags, track->enc->codec_id);
1459 tag = mov_get_codec_tag(s, track);
1464 /** Write uuid atom.
1465 * Needed to make file play in iPods running newest firmware
1466 * goes after avcC atom in moov.trak.mdia.minf.stbl.stsd.avc1
1468 static int mov_write_uuid_tag_ipod(AVIOContext *pb)
1471 ffio_wfourcc(pb, "uuid");
1472 avio_wb32(pb, 0x6b6840f2);
1473 avio_wb32(pb, 0x5f244fc5);
1474 avio_wb32(pb, 0xba39a51b);
1475 avio_wb32(pb, 0xcf0323f3);
1480 static const uint16_t fiel_data[] = {
1481 0x0000, 0x0100, 0x0201, 0x0206, 0x0209, 0x020e
1484 static int mov_write_fiel_tag(AVIOContext *pb, MOVTrack *track)
1486 unsigned mov_field_order = 0;
1487 if (track->enc->field_order < FF_ARRAY_ELEMS(fiel_data))
1488 mov_field_order = fiel_data[track->enc->field_order];
1492 ffio_wfourcc(pb, "fiel");
1493 avio_wb16(pb, mov_field_order);
1497 static int mov_write_subtitle_tag(AVIOContext *pb, MOVTrack *track)
1499 int64_t pos = avio_tell(pb);
1500 avio_wb32(pb, 0); /* size */
1501 avio_wl32(pb, track->tag); // store it byteswapped
1502 avio_wb32(pb, 0); /* Reserved */
1503 avio_wb16(pb, 0); /* Reserved */
1504 avio_wb16(pb, 1); /* Data-reference index */
1506 if (track->enc->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
1507 mov_write_esds_tag(pb, track);
1508 else if (track->enc->extradata_size)
1509 avio_write(pb, track->enc->extradata, track->enc->extradata_size);
1511 return update_size(pb, pos);
1514 static int mov_write_pasp_tag(AVIOContext *pb, MOVTrack *track)
1517 av_reduce(&sar.num, &sar.den, track->enc->sample_aspect_ratio.num,
1518 track->enc->sample_aspect_ratio.den, INT_MAX);
1521 ffio_wfourcc(pb, "pasp");
1522 avio_wb32(pb, sar.num);
1523 avio_wb32(pb, sar.den);
1527 static int mov_write_gama_tag(AVIOContext *pb, MOVTrack *track, double gamma)
1532 gamma = avpriv_get_gamma_from_trc(track->enc->color_trc);
1534 av_log(pb, AV_LOG_DEBUG, "gamma value %g\n", gamma);
1537 gama = (uint32_t)lrint((double)(1<<16) * gamma);
1538 av_log(pb, AV_LOG_DEBUG, "writing gama value %d\n", gama);
1540 av_assert0(track->mode == MODE_MOV);
1542 ffio_wfourcc(pb, "gama");
1543 avio_wb32(pb, gama);
1547 av_log(pb, AV_LOG_WARNING, "gamma value unknown, unable to write gama atom\n");
1552 static int mov_write_colr_tag(AVIOContext *pb, MOVTrack *track)
1554 // Ref (MOV): https://developer.apple.com/library/mac/technotes/tn2162/_index.html#//apple_ref/doc/uid/DTS40013070-CH1-TNTAG9
1555 // Ref (MP4): ISO/IEC 14496-12:2012
1557 if (track->enc->color_primaries == AVCOL_PRI_UNSPECIFIED &&
1558 track->enc->color_trc == AVCOL_TRC_UNSPECIFIED &&
1559 track->enc->colorspace == AVCOL_SPC_UNSPECIFIED) {
1560 if ((track->enc->width >= 1920 && track->enc->height >= 1080)
1561 || (track->enc->width == 1280 && track->enc->height == 720)) {
1562 av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming bt709\n");
1563 track->enc->color_primaries = AVCOL_PRI_BT709;
1564 } else if (track->enc->width == 720 && track->height == 576) {
1565 av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming bt470bg\n");
1566 track->enc->color_primaries = AVCOL_PRI_BT470BG;
1567 } else if (track->enc->width == 720 &&
1568 (track->height == 486 || track->height == 480)) {
1569 av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming smpte170\n");
1570 track->enc->color_primaries = AVCOL_PRI_SMPTE170M;
1572 av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, unable to assume anything\n");
1574 switch (track->enc->color_primaries) {
1575 case AVCOL_PRI_BT709:
1576 track->enc->color_trc = AVCOL_TRC_BT709;
1577 track->enc->colorspace = AVCOL_SPC_BT709;
1579 case AVCOL_PRI_SMPTE170M:
1580 case AVCOL_PRI_BT470BG:
1581 track->enc->color_trc = AVCOL_TRC_BT709;
1582 track->enc->colorspace = AVCOL_SPC_SMPTE170M;
1587 /* We should only ever be called by MOV or MP4. */
1588 av_assert0(track->mode == MODE_MOV || track->mode == MODE_MP4);
1590 avio_wb32(pb, 18 + (track->mode == MODE_MP4));
1591 ffio_wfourcc(pb, "colr");
1592 if (track->mode == MODE_MP4)
1593 ffio_wfourcc(pb, "nclx");
1595 ffio_wfourcc(pb, "nclc");
1596 switch (track->enc->color_primaries) {
1597 case AVCOL_PRI_BT709: avio_wb16(pb, 1); break;
1598 case AVCOL_PRI_SMPTE170M:
1599 case AVCOL_PRI_SMPTE240M: avio_wb16(pb, 6); break;
1600 case AVCOL_PRI_BT470BG: avio_wb16(pb, 5); break;
1601 default: avio_wb16(pb, 2);
1603 switch (track->enc->color_trc) {
1604 case AVCOL_TRC_BT709: avio_wb16(pb, 1); break;
1605 case AVCOL_TRC_SMPTE170M: avio_wb16(pb, 1); break; // remapped
1606 case AVCOL_TRC_SMPTE240M: avio_wb16(pb, 7); break;
1607 default: avio_wb16(pb, 2);
1609 switch (track->enc->colorspace) {
1610 case AVCOL_TRC_BT709: avio_wb16(pb, 1); break;
1611 case AVCOL_PRI_SMPTE170M: avio_wb16(pb, 6); break;
1612 case AVCOL_PRI_SMPTE240M: avio_wb16(pb, 7); break;
1613 default: avio_wb16(pb, 2);
1616 if (track->mode == MODE_MP4) {
1617 int full_range = track->enc->color_range == AVCOL_RANGE_JPEG;
1618 avio_w8(pb, full_range << 7);
1625 static void find_compressor(char * compressor_name, int len, MOVTrack *track)
1627 AVDictionaryEntry *encoder;
1628 int xdcam_res = (track->enc->width == 1280 && track->enc->height == 720)
1629 || (track->enc->width == 1440 && track->enc->height == 1080)
1630 || (track->enc->width == 1920 && track->enc->height == 1080);
1632 if (track->mode == MODE_MOV &&
1633 (encoder = av_dict_get(track->st->metadata, "encoder", NULL, 0))) {
1634 av_strlcpy(compressor_name, encoder->value, 32);
1635 } else if (track->enc->codec_id == AV_CODEC_ID_MPEG2VIDEO && xdcam_res) {
1636 int interlaced = track->enc->field_order > AV_FIELD_PROGRESSIVE;
1637 AVStream *st = track->st;
1638 int rate = av_q2d(find_fps(NULL, st));
1639 av_strlcatf(compressor_name, len, "XDCAM");
1640 if (track->enc->pix_fmt == AV_PIX_FMT_YUV422P) {
1641 av_strlcatf(compressor_name, len, " HD422");
1642 } else if(track->enc->width == 1440) {
1643 av_strlcatf(compressor_name, len, " HD");
1645 av_strlcatf(compressor_name, len, " EX");
1647 av_strlcatf(compressor_name, len, " %d%c", track->enc->height, interlaced ? 'i' : 'p');
1649 av_strlcatf(compressor_name, len, "%d", rate * (interlaced + 1));
1653 static int mov_write_video_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
1655 int64_t pos = avio_tell(pb);
1656 char compressor_name[32] = { 0 };
1659 avio_wb32(pb, 0); /* size */
1660 avio_wl32(pb, track->tag); // store it byteswapped
1661 avio_wb32(pb, 0); /* Reserved */
1662 avio_wb16(pb, 0); /* Reserved */
1663 avio_wb16(pb, 1); /* Data-reference index */
1665 avio_wb16(pb, 0); /* Codec stream version */
1666 avio_wb16(pb, 0); /* Codec stream revision (=0) */
1667 if (track->mode == MODE_MOV) {
1668 ffio_wfourcc(pb, "FFMP"); /* Vendor */
1669 if (track->enc->codec_id == AV_CODEC_ID_RAWVIDEO) {
1670 avio_wb32(pb, 0); /* Temporal Quality */
1671 avio_wb32(pb, 0x400); /* Spatial Quality = lossless*/
1673 avio_wb32(pb, 0x200); /* Temporal Quality = normal */
1674 avio_wb32(pb, 0x200); /* Spatial Quality = normal */
1677 avio_wb32(pb, 0); /* Reserved */
1678 avio_wb32(pb, 0); /* Reserved */
1679 avio_wb32(pb, 0); /* Reserved */
1681 avio_wb16(pb, track->enc->width); /* Video width */
1682 avio_wb16(pb, track->height); /* Video height */
1683 avio_wb32(pb, 0x00480000); /* Horizontal resolution 72dpi */
1684 avio_wb32(pb, 0x00480000); /* Vertical resolution 72dpi */
1685 avio_wb32(pb, 0); /* Data size (= 0) */
1686 avio_wb16(pb, 1); /* Frame count (= 1) */
1688 /* FIXME not sure, ISO 14496-1 draft where it shall be set to 0 */
1689 find_compressor(compressor_name, 32, track);
1690 avio_w8(pb, strlen(compressor_name));
1691 avio_write(pb, compressor_name, 31);
1693 if (track->mode == MODE_MOV && track->enc->bits_per_coded_sample)
1694 avio_wb16(pb, track->enc->bits_per_coded_sample);
1696 avio_wb16(pb, 0x18); /* Reserved */
1697 avio_wb16(pb, 0xffff); /* Reserved */
1698 if (track->tag == MKTAG('m','p','4','v'))
1699 mov_write_esds_tag(pb, track);
1700 else if (track->enc->codec_id == AV_CODEC_ID_H263)
1701 mov_write_d263_tag(pb);
1702 else if (track->enc->codec_id == AV_CODEC_ID_AVUI ||
1703 track->enc->codec_id == AV_CODEC_ID_SVQ3) {
1704 mov_write_extradata_tag(pb, track);
1706 } else if (track->enc->codec_id == AV_CODEC_ID_DNXHD) {
1707 mov_write_avid_tag(pb, track);
1709 } else if (track->enc->codec_id == AV_CODEC_ID_HEVC)
1710 mov_write_hvcc_tag(pb, track);
1711 else if (track->enc->codec_id == AV_CODEC_ID_H264 && !TAG_IS_AVCI(track->tag)) {
1712 mov_write_avcc_tag(pb, track);
1713 if (track->mode == MODE_IPOD)
1714 mov_write_uuid_tag_ipod(pb);
1715 } else if (track->enc->codec_id == AV_CODEC_ID_VC1 && track->vos_len > 0)
1716 mov_write_dvc1_tag(pb, track);
1717 else if (track->enc->codec_id == AV_CODEC_ID_VP6F ||
1718 track->enc->codec_id == AV_CODEC_ID_VP6A) {
1719 /* Don't write any potential extradata here - the cropping
1720 * is signalled via the normal width/height fields. */
1721 } else if (track->enc->codec_id == AV_CODEC_ID_R10K) {
1722 if (track->enc->codec_tag == MKTAG('R','1','0','k'))
1723 mov_write_dpxe_tag(pb, track);
1724 } else if (track->vos_len > 0)
1725 mov_write_glbl_tag(pb, track);
1727 if (track->enc->codec_id != AV_CODEC_ID_H264 &&
1728 track->enc->codec_id != AV_CODEC_ID_MPEG4 &&
1729 track->enc->codec_id != AV_CODEC_ID_DNXHD)
1730 if (track->enc->field_order != AV_FIELD_UNKNOWN)
1731 mov_write_fiel_tag(pb, track);
1733 if (mov->flags & FF_MOV_FLAG_WRITE_GAMA) {
1734 if (track->mode == MODE_MOV)
1735 mov_write_gama_tag(pb, track, mov->gamma);
1737 av_log(mov->fc, AV_LOG_WARNING, "Not writing 'gama' atom. Format is not MOV.\n");
1739 if (mov->flags & FF_MOV_FLAG_WRITE_COLR) {
1740 if (track->mode == MODE_MOV || track->mode == MODE_MP4)
1741 mov_write_colr_tag(pb, track);
1743 av_log(mov->fc, AV_LOG_WARNING, "Not writing 'colr' atom. Format is not MOV or MP4.\n");
1746 if (track->enc->sample_aspect_ratio.den && track->enc->sample_aspect_ratio.num &&
1747 track->enc->sample_aspect_ratio.den != track->enc->sample_aspect_ratio.num) {
1748 mov_write_pasp_tag(pb, track);
1751 /* extra padding for avid stsd */
1752 /* https://developer.apple.com/library/mac/documentation/QuickTime/QTFF/QTFFChap2/qtff2.html#//apple_ref/doc/uid/TP40000939-CH204-61112 */
1756 return update_size(pb, pos);
1759 static int mov_write_rtp_tag(AVIOContext *pb, MOVTrack *track)
1761 int64_t pos = avio_tell(pb);
1762 avio_wb32(pb, 0); /* size */
1763 ffio_wfourcc(pb, "rtp ");
1764 avio_wb32(pb, 0); /* Reserved */
1765 avio_wb16(pb, 0); /* Reserved */
1766 avio_wb16(pb, 1); /* Data-reference index */
1768 avio_wb16(pb, 1); /* Hint track version */
1769 avio_wb16(pb, 1); /* Highest compatible version */
1770 avio_wb32(pb, track->max_packet_size); /* Max packet size */
1772 avio_wb32(pb, 12); /* size */
1773 ffio_wfourcc(pb, "tims");
1774 avio_wb32(pb, track->timescale);
1776 return update_size(pb, pos);
1779 static int mov_write_source_reference_tag(AVIOContext *pb, MOVTrack *track, const char *reel_name)
1781 uint64_t str_size =strlen(reel_name);
1782 int64_t pos = avio_tell(pb);
1784 if (str_size >= UINT16_MAX){
1785 av_log(NULL, AV_LOG_ERROR, "reel_name length %"PRIu64" is too large\n", str_size);
1787 return AVERROR(EINVAL);
1790 avio_wb32(pb, 0); /* size */
1791 ffio_wfourcc(pb, "name"); /* Data format */
1792 avio_wb16(pb, str_size); /* string size */
1793 avio_wb16(pb, track->language); /* langcode */
1794 avio_write(pb, reel_name, str_size); /* reel name */
1795 return update_size(pb,pos);
1798 static int mov_write_tmcd_tag(AVIOContext *pb, MOVTrack *track)
1800 int64_t pos = avio_tell(pb);
1802 int frame_duration = av_rescale(track->timescale, track->enc->time_base.num, track->enc->time_base.den);
1803 int nb_frames = 1.0/av_q2d(track->enc->time_base) + 0.5;
1804 AVDictionaryEntry *t = NULL;
1806 if (nb_frames > 255) {
1807 av_log(NULL, AV_LOG_ERROR, "fps %d is too large\n", nb_frames);
1808 return AVERROR(EINVAL);
1811 avio_wb32(pb, 0); /* size */
1812 ffio_wfourcc(pb, "tmcd"); /* Data format */
1813 avio_wb32(pb, 0); /* Reserved */
1814 avio_wb32(pb, 1); /* Data reference index */
1815 avio_wb32(pb, 0); /* Flags */
1816 avio_wb32(pb, track->timecode_flags); /* Flags (timecode) */
1817 avio_wb32(pb, track->timescale); /* Timescale */
1818 avio_wb32(pb, frame_duration); /* Frame duration */
1819 avio_w8(pb, nb_frames); /* Number of frames */
1820 avio_w8(pb, 0); /* Reserved */
1823 t = av_dict_get(track->st->metadata, "reel_name", NULL, 0);
1825 if (t && utf8len(t->value))
1826 mov_write_source_reference_tag(pb, track, t->value);
1828 avio_wb16(pb, 0); /* zero size */
1831 avio_wb32(pb, 0); /* size */
1832 ffio_wfourcc(pb, "tmcd"); /* Data format */
1833 avio_wb32(pb, 0); /* Reserved */
1834 avio_wb32(pb, 1); /* Data reference index */
1835 if (track->enc->extradata_size)
1836 avio_write(pb, track->enc->extradata, track->enc->extradata_size);
1838 return update_size(pb, pos);
1841 static int mov_write_stsd_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
1843 int64_t pos = avio_tell(pb);
1844 avio_wb32(pb, 0); /* size */
1845 ffio_wfourcc(pb, "stsd");
1846 avio_wb32(pb, 0); /* version & flags */
1847 avio_wb32(pb, 1); /* entry count */
1848 if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO)
1849 mov_write_video_tag(pb, mov, track);
1850 else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
1851 mov_write_audio_tag(pb, track);
1852 else if (track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE)
1853 mov_write_subtitle_tag(pb, track);
1854 else if (track->enc->codec_tag == MKTAG('r','t','p',' '))
1855 mov_write_rtp_tag(pb, track);
1856 else if (track->enc->codec_tag == MKTAG('t','m','c','d'))
1857 mov_write_tmcd_tag(pb, track);
1858 return update_size(pb, pos);
1861 static int mov_write_ctts_tag(AVIOContext *pb, MOVTrack *track)
1863 MOVStts *ctts_entries;
1864 uint32_t entries = 0;
1868 ctts_entries = av_malloc_array((track->entry + 1), sizeof(*ctts_entries)); /* worst case */
1870 return AVERROR(ENOMEM);
1871 ctts_entries[0].count = 1;
1872 ctts_entries[0].duration = track->cluster[0].cts;
1873 for (i = 1; i < track->entry; i++) {
1874 if (track->cluster[i].cts == ctts_entries[entries].duration) {
1875 ctts_entries[entries].count++; /* compress */
1878 ctts_entries[entries].duration = track->cluster[i].cts;
1879 ctts_entries[entries].count = 1;
1882 entries++; /* last one */
1883 atom_size = 16 + (entries * 8);
1884 avio_wb32(pb, atom_size); /* size */
1885 ffio_wfourcc(pb, "ctts");
1886 avio_wb32(pb, 0); /* version & flags */
1887 avio_wb32(pb, entries); /* entry count */
1888 for (i = 0; i < entries; i++) {
1889 avio_wb32(pb, ctts_entries[i].count);
1890 avio_wb32(pb, ctts_entries[i].duration);
1892 av_free(ctts_entries);
1896 /* Time to sample atom */
1897 static int mov_write_stts_tag(AVIOContext *pb, MOVTrack *track)
1899 MOVStts *stts_entries = NULL;
1900 uint32_t entries = -1;
1904 if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO && !track->audio_vbr) {
1905 stts_entries = av_malloc(sizeof(*stts_entries)); /* one entry */
1907 return AVERROR(ENOMEM);
1908 stts_entries[0].count = track->sample_count;
1909 stts_entries[0].duration = 1;
1913 stts_entries = av_malloc_array(track->entry, sizeof(*stts_entries)); /* worst case */
1915 return AVERROR(ENOMEM);
1917 for (i = 0; i < track->entry; i++) {
1918 int duration = get_cluster_duration(track, i);
1919 if (i && duration == stts_entries[entries].duration) {
1920 stts_entries[entries].count++; /* compress */
1923 stts_entries[entries].duration = duration;
1924 stts_entries[entries].count = 1;
1927 entries++; /* last one */
1929 atom_size = 16 + (entries * 8);
1930 avio_wb32(pb, atom_size); /* size */
1931 ffio_wfourcc(pb, "stts");
1932 avio_wb32(pb, 0); /* version & flags */
1933 avio_wb32(pb, entries); /* entry count */
1934 for (i = 0; i < entries; i++) {
1935 avio_wb32(pb, stts_entries[i].count);
1936 avio_wb32(pb, stts_entries[i].duration);
1938 av_free(stts_entries);
1942 static int mov_write_dref_tag(AVIOContext *pb)
1944 avio_wb32(pb, 28); /* size */
1945 ffio_wfourcc(pb, "dref");
1946 avio_wb32(pb, 0); /* version & flags */
1947 avio_wb32(pb, 1); /* entry count */
1949 avio_wb32(pb, 0xc); /* size */
1950 //FIXME add the alis and rsrc atom
1951 ffio_wfourcc(pb, "url ");
1952 avio_wb32(pb, 1); /* version & flags */
1957 static int mov_write_stbl_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
1959 int64_t pos = avio_tell(pb);
1962 avio_wb32(pb, 0); /* size */
1963 ffio_wfourcc(pb, "stbl");
1964 mov_write_stsd_tag(pb, mov, track);
1965 mov_write_stts_tag(pb, track);
1966 if ((track->enc->codec_type == AVMEDIA_TYPE_VIDEO ||
1967 track->enc->codec_tag == MKTAG('r','t','p',' ')) &&
1968 track->has_keyframes && track->has_keyframes < track->entry)
1969 mov_write_stss_tag(pb, track, MOV_SYNC_SAMPLE);
1970 if (track->mode == MODE_MOV && track->flags & MOV_TRACK_STPS)
1971 mov_write_stss_tag(pb, track, MOV_PARTIAL_SYNC_SAMPLE);
1972 if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO &&
1973 track->flags & MOV_TRACK_CTTS && track->entry) {
1975 if ((ret = mov_write_ctts_tag(pb, track)) < 0)
1978 mov_write_stsc_tag(pb, track);
1979 mov_write_stsz_tag(pb, track);
1980 mov_write_stco_tag(pb, track);
1981 return update_size(pb, pos);
1984 static int mov_write_dinf_tag(AVIOContext *pb)
1986 int64_t pos = avio_tell(pb);
1987 avio_wb32(pb, 0); /* size */
1988 ffio_wfourcc(pb, "dinf");
1989 mov_write_dref_tag(pb);
1990 return update_size(pb, pos);
1993 static int mov_write_nmhd_tag(AVIOContext *pb)
1996 ffio_wfourcc(pb, "nmhd");
2001 static int mov_write_tcmi_tag(AVIOContext *pb, MOVTrack *track)
2003 int64_t pos = avio_tell(pb);
2004 const char *font = "Lucida Grande";
2005 avio_wb32(pb, 0); /* size */
2006 ffio_wfourcc(pb, "tcmi"); /* timecode media information atom */
2007 avio_wb32(pb, 0); /* version & flags */
2008 avio_wb16(pb, 0); /* text font */
2009 avio_wb16(pb, 0); /* text face */
2010 avio_wb16(pb, 12); /* text size */
2011 avio_wb16(pb, 0); /* (unknown, not in the QT specs...) */
2012 avio_wb16(pb, 0x0000); /* text color (red) */
2013 avio_wb16(pb, 0x0000); /* text color (green) */
2014 avio_wb16(pb, 0x0000); /* text color (blue) */
2015 avio_wb16(pb, 0xffff); /* background color (red) */
2016 avio_wb16(pb, 0xffff); /* background color (green) */
2017 avio_wb16(pb, 0xffff); /* background color (blue) */
2018 avio_w8(pb, strlen(font)); /* font len (part of the pascal string) */
2019 avio_write(pb, font, strlen(font)); /* font name */
2020 return update_size(pb, pos);
2023 static int mov_write_gmhd_tag(AVIOContext *pb, MOVTrack *track)
2025 int64_t pos = avio_tell(pb);
2026 avio_wb32(pb, 0); /* size */
2027 ffio_wfourcc(pb, "gmhd");
2028 avio_wb32(pb, 0x18); /* gmin size */
2029 ffio_wfourcc(pb, "gmin");/* generic media info */
2030 avio_wb32(pb, 0); /* version & flags */
2031 avio_wb16(pb, 0x40); /* graphics mode = */
2032 avio_wb16(pb, 0x8000); /* opColor (r?) */
2033 avio_wb16(pb, 0x8000); /* opColor (g?) */
2034 avio_wb16(pb, 0x8000); /* opColor (b?) */
2035 avio_wb16(pb, 0); /* balance */
2036 avio_wb16(pb, 0); /* reserved */
2039 * This special text atom is required for
2040 * Apple Quicktime chapters. The contents
2041 * don't appear to be documented, so the
2042 * bytes are copied verbatim.
2044 if (track->tag != MKTAG('c','6','0','8')) {
2045 avio_wb32(pb, 0x2C); /* size */
2046 ffio_wfourcc(pb, "text");
2047 avio_wb16(pb, 0x01);
2048 avio_wb32(pb, 0x00);
2049 avio_wb32(pb, 0x00);
2050 avio_wb32(pb, 0x00);
2051 avio_wb32(pb, 0x01);
2052 avio_wb32(pb, 0x00);
2053 avio_wb32(pb, 0x00);
2054 avio_wb32(pb, 0x00);
2055 avio_wb32(pb, 0x00004000);
2056 avio_wb16(pb, 0x0000);
2059 if (track->enc->codec_tag == MKTAG('t','m','c','d')) {
2060 int64_t tmcd_pos = avio_tell(pb);
2061 avio_wb32(pb, 0); /* size */
2062 ffio_wfourcc(pb, "tmcd");
2063 mov_write_tcmi_tag(pb, track);
2064 update_size(pb, tmcd_pos);
2066 return update_size(pb, pos);
2069 static int mov_write_smhd_tag(AVIOContext *pb)
2071 avio_wb32(pb, 16); /* size */
2072 ffio_wfourcc(pb, "smhd");
2073 avio_wb32(pb, 0); /* version & flags */
2074 avio_wb16(pb, 0); /* reserved (balance, normally = 0) */
2075 avio_wb16(pb, 0); /* reserved */
2079 static int mov_write_vmhd_tag(AVIOContext *pb)
2081 avio_wb32(pb, 0x14); /* size (always 0x14) */
2082 ffio_wfourcc(pb, "vmhd");
2083 avio_wb32(pb, 0x01); /* version & flags */
2084 avio_wb64(pb, 0); /* reserved (graphics mode = copy) */
2088 static int is_clcp_track(MOVTrack *track)
2090 return track->tag == MKTAG('c','7','0','8') ||
2091 track->tag == MKTAG('c','6','0','8');
2094 static int mov_write_hdlr_tag(AVIOContext *pb, MOVTrack *track)
2096 const char *hdlr, *descr = NULL, *hdlr_type = NULL;
2097 int64_t pos = avio_tell(pb);
2101 descr = "DataHandler";
2104 hdlr = (track->mode == MODE_MOV) ? "mhlr" : "\0\0\0\0";
2105 if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) {
2107 descr = "VideoHandler";
2108 } else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO) {
2110 descr = "SoundHandler";
2111 } else if (track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE) {
2112 if (is_clcp_track(track)) {
2114 descr = "ClosedCaptionHandler";
2116 if (track->tag == MKTAG('t','x','3','g')) {
2118 } else if (track->tag == MKTAG('m','p','4','s')) {
2123 descr = "SubtitleHandler";
2125 } else if (track->enc->codec_tag == MKTAG('r','t','p',' ')) {
2127 descr = "HintHandler";
2128 } else if (track->enc->codec_tag == MKTAG('t','m','c','d')) {
2130 descr = "TimeCodeHandler";
2133 av_get_codec_tag_string(tag_buf, sizeof(tag_buf),
2134 track->enc->codec_tag);
2136 av_log(track->enc, AV_LOG_WARNING,
2137 "Unknown hldr_type for %s / 0x%04X, writing dummy values\n",
2138 tag_buf, track->enc->codec_tag);
2141 // hdlr.name is used by some players to identify the content title
2142 // of the track. So if an alternate handler description is
2143 // specified, use it.
2144 AVDictionaryEntry *t;
2145 t = av_dict_get(track->st->metadata, "handler", NULL, 0);
2146 if (t && utf8len(t->value))
2151 avio_wb32(pb, 0); /* size */
2152 ffio_wfourcc(pb, "hdlr");
2153 avio_wb32(pb, 0); /* Version & flags */
2154 avio_write(pb, hdlr, 4); /* handler */
2155 ffio_wfourcc(pb, hdlr_type); /* handler type */
2156 avio_wb32(pb, 0); /* reserved */
2157 avio_wb32(pb, 0); /* reserved */
2158 avio_wb32(pb, 0); /* reserved */
2159 if (!track || track->mode == MODE_MOV)
2160 avio_w8(pb, strlen(descr)); /* pascal string */
2161 avio_write(pb, descr, strlen(descr)); /* handler description */
2162 if (track && track->mode != MODE_MOV)
2163 avio_w8(pb, 0); /* c string */
2164 return update_size(pb, pos);
2167 static int mov_write_hmhd_tag(AVIOContext *pb)
2169 /* This atom must be present, but leaving the values at zero
2170 * seems harmless. */
2171 avio_wb32(pb, 28); /* size */
2172 ffio_wfourcc(pb, "hmhd");
2173 avio_wb32(pb, 0); /* version, flags */
2174 avio_wb16(pb, 0); /* maxPDUsize */
2175 avio_wb16(pb, 0); /* avgPDUsize */
2176 avio_wb32(pb, 0); /* maxbitrate */
2177 avio_wb32(pb, 0); /* avgbitrate */
2178 avio_wb32(pb, 0); /* reserved */
2182 static int mov_write_minf_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
2184 int64_t pos = avio_tell(pb);
2187 avio_wb32(pb, 0); /* size */
2188 ffio_wfourcc(pb, "minf");
2189 if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO)
2190 mov_write_vmhd_tag(pb);
2191 else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
2192 mov_write_smhd_tag(pb);
2193 else if (track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE) {
2194 if (track->tag == MKTAG('t','e','x','t') || is_clcp_track(track)) {
2195 mov_write_gmhd_tag(pb, track);
2197 mov_write_nmhd_tag(pb);
2199 } else if (track->tag == MKTAG('r','t','p',' ')) {
2200 mov_write_hmhd_tag(pb);
2201 } else if (track->tag == MKTAG('t','m','c','d')) {
2202 mov_write_gmhd_tag(pb, track);
2204 if (track->mode == MODE_MOV) /* FIXME: Why do it for MODE_MOV only ? */
2205 mov_write_hdlr_tag(pb, NULL);
2206 mov_write_dinf_tag(pb);
2207 if ((ret = mov_write_stbl_tag(pb, mov, track)) < 0)
2209 return update_size(pb, pos);
2212 static int mov_write_mdhd_tag(AVIOContext *pb, MOVMuxContext *mov,
2215 int version = track->track_duration < INT32_MAX ? 0 : 1;
2217 if (track->mode == MODE_ISM)
2220 (version == 1) ? avio_wb32(pb, 44) : avio_wb32(pb, 32); /* size */
2221 ffio_wfourcc(pb, "mdhd");
2222 avio_w8(pb, version);
2223 avio_wb24(pb, 0); /* flags */
2225 avio_wb64(pb, track->time);
2226 avio_wb64(pb, track->time);
2228 avio_wb32(pb, track->time); /* creation time */
2229 avio_wb32(pb, track->time); /* modification time */
2231 avio_wb32(pb, track->timescale); /* time scale (sample rate for audio) */
2232 if (!track->entry && mov->mode == MODE_ISM)
2233 (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
2234 else if (!track->entry)
2235 (version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0);
2237 (version == 1) ? avio_wb64(pb, track->track_duration) : avio_wb32(pb, track->track_duration); /* duration */
2238 avio_wb16(pb, track->language); /* language */
2239 avio_wb16(pb, 0); /* reserved (quality) */
2241 if (version != 0 && track->mode == MODE_MOV) {
2242 av_log(NULL, AV_LOG_ERROR,
2243 "FATAL error, file duration too long for timebase, this file will not be\n"
2244 "playable with quicktime. Choose a different timebase or a different\n"
2245 "container format\n");
2251 static int mov_write_mdia_tag(AVIOContext *pb, MOVMuxContext *mov,
2254 int64_t pos = avio_tell(pb);
2257 avio_wb32(pb, 0); /* size */
2258 ffio_wfourcc(pb, "mdia");
2259 mov_write_mdhd_tag(pb, mov, track);
2260 mov_write_hdlr_tag(pb, track);
2261 if ((ret = mov_write_minf_tag(pb, mov, track)) < 0)
2263 return update_size(pb, pos);
2266 /* transformation matrix
2270 static void write_matrix(AVIOContext *pb, int16_t a, int16_t b, int16_t c,
2271 int16_t d, int16_t tx, int16_t ty)
2273 avio_wb32(pb, a << 16); /* 16.16 format */
2274 avio_wb32(pb, b << 16); /* 16.16 format */
2275 avio_wb32(pb, 0); /* u in 2.30 format */
2276 avio_wb32(pb, c << 16); /* 16.16 format */
2277 avio_wb32(pb, d << 16); /* 16.16 format */
2278 avio_wb32(pb, 0); /* v in 2.30 format */
2279 avio_wb32(pb, tx << 16); /* 16.16 format */
2280 avio_wb32(pb, ty << 16); /* 16.16 format */
2281 avio_wb32(pb, 1 << 30); /* w in 2.30 format */
2284 static int mov_write_tkhd_tag(AVIOContext *pb, MOVMuxContext *mov,
2285 MOVTrack *track, AVStream *st)
2287 int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE,
2288 track->timescale, AV_ROUND_UP);
2289 int version = duration < INT32_MAX ? 0 : 1;
2290 int flags = MOV_TKHD_FLAG_IN_MOVIE;
2294 uint32_t *display_matrix = NULL;
2295 int display_matrix_size, i;
2298 if (mov->per_stream_grouping)
2301 group = st->codec->codec_type;
2303 display_matrix = (uint32_t*)av_stream_get_side_data(st, AV_PKT_DATA_DISPLAYMATRIX,
2304 &display_matrix_size);
2305 if (display_matrix && display_matrix_size < 9 * sizeof(*display_matrix))
2306 display_matrix = NULL;
2309 if (track->flags & MOV_TRACK_ENABLED)
2310 flags |= MOV_TKHD_FLAG_ENABLED;
2312 if (track->mode == MODE_ISM)
2315 (version == 1) ? avio_wb32(pb, 104) : avio_wb32(pb, 92); /* size */
2316 ffio_wfourcc(pb, "tkhd");
2317 avio_w8(pb, version);
2318 avio_wb24(pb, flags);
2320 avio_wb64(pb, track->time);
2321 avio_wb64(pb, track->time);
2323 avio_wb32(pb, track->time); /* creation time */
2324 avio_wb32(pb, track->time); /* modification time */
2326 avio_wb32(pb, track->track_id); /* track-id */
2327 avio_wb32(pb, 0); /* reserved */
2328 if (!track->entry && mov->mode == MODE_ISM)
2329 (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
2330 else if (!track->entry)
2331 (version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0);
2333 (version == 1) ? avio_wb64(pb, duration) : avio_wb32(pb, duration);
2335 avio_wb32(pb, 0); /* reserved */
2336 avio_wb32(pb, 0); /* reserved */
2337 avio_wb16(pb, 0); /* layer */
2338 avio_wb16(pb, group); /* alternate group) */
2339 /* Volume, only for audio */
2340 if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
2341 avio_wb16(pb, 0x0100);
2344 avio_wb16(pb, 0); /* reserved */
2346 /* Matrix structure */
2347 if (st && st->metadata) {
2348 AVDictionaryEntry *rot = av_dict_get(st->metadata, "rotate", NULL, 0);
2349 rotation = (rot && rot->value) ? atoi(rot->value) : 0;
2351 if (display_matrix) {
2352 for (i = 0; i < 9; i++)
2353 avio_wb32(pb, display_matrix[i]);
2354 } else if (rotation == 90) {
2355 write_matrix(pb, 0, 1, -1, 0, track->enc->height, 0);
2356 } else if (rotation == 180) {
2357 write_matrix(pb, -1, 0, 0, -1, track->enc->width, track->enc->height);
2358 } else if (rotation == 270) {
2359 write_matrix(pb, 0, -1, 1, 0, 0, track->enc->width);
2361 write_matrix(pb, 1, 0, 0, 1, 0, 0);
2363 /* Track width and height, for visual only */
2364 if (st && (track->enc->codec_type == AVMEDIA_TYPE_VIDEO ||
2365 track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE)) {
2366 if (track->mode == MODE_MOV) {
2367 avio_wb32(pb, track->enc->width << 16);
2368 avio_wb32(pb, track->height << 16);
2370 double sample_aspect_ratio = av_q2d(st->sample_aspect_ratio);
2371 if (!sample_aspect_ratio || track->height != track->enc->height)
2372 sample_aspect_ratio = 1;
2373 avio_wb32(pb, sample_aspect_ratio * track->enc->width * 0x10000);
2374 avio_wb32(pb, track->height * 0x10000);
2383 static int mov_write_tapt_tag(AVIOContext *pb, MOVTrack *track)
2385 int32_t width = av_rescale(track->enc->sample_aspect_ratio.num, track->enc->width,
2386 track->enc->sample_aspect_ratio.den);
2388 int64_t pos = avio_tell(pb);
2390 avio_wb32(pb, 0); /* size */
2391 ffio_wfourcc(pb, "tapt");
2394 ffio_wfourcc(pb, "clef");
2396 avio_wb32(pb, width << 16);
2397 avio_wb32(pb, track->enc->height << 16);
2400 ffio_wfourcc(pb, "prof");
2402 avio_wb32(pb, width << 16);
2403 avio_wb32(pb, track->enc->height << 16);
2406 ffio_wfourcc(pb, "enof");
2408 avio_wb32(pb, track->enc->width << 16);
2409 avio_wb32(pb, track->enc->height << 16);
2411 return update_size(pb, pos);
2414 // This box seems important for the psp playback ... without it the movie seems to hang
2415 static int mov_write_edts_tag(AVIOContext *pb, MOVMuxContext *mov,
2418 int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE,
2419 track->timescale, AV_ROUND_UP);
2420 int version = duration < INT32_MAX ? 0 : 1;
2421 int entry_size, entry_count, size;
2422 int64_t delay, start_ct = track->start_cts;
2423 int64_t start_dts = track->start_dts;
2426 if (start_dts != track->cluster[0].dts || start_ct != track->cluster[0].cts) {
2428 av_log(mov->fc, AV_LOG_DEBUG,
2429 "EDTS using dts:%"PRId64" cts:%d instead of dts:%"PRId64" cts:%"PRId64" tid:%d\n",
2430 track->cluster[0].dts, track->cluster[0].cts,
2431 start_dts, start_ct, track->track_id);
2432 start_dts = track->cluster[0].dts;
2433 start_ct = track->cluster[0].cts;
2437 delay = av_rescale_rnd(start_dts + start_ct, MOV_TIMESCALE,
2438 track->timescale, AV_ROUND_DOWN);
2439 version |= delay < INT32_MAX ? 0 : 1;
2441 entry_size = (version == 1) ? 20 : 12;
2442 entry_count = 1 + (delay > 0);
2443 size = 24 + entry_count * entry_size;
2445 /* write the atom data */
2446 avio_wb32(pb, size);
2447 ffio_wfourcc(pb, "edts");
2448 avio_wb32(pb, size - 8);
2449 ffio_wfourcc(pb, "elst");
2450 avio_w8(pb, version);
2451 avio_wb24(pb, 0); /* flags */
2453 avio_wb32(pb, entry_count);
2454 if (delay > 0) { /* add an empty edit to delay presentation */
2455 /* In the positive delay case, the delay includes the cts
2456 * offset, and the second edit list entry below trims out
2457 * the same amount from the actual content. This makes sure
2458 * that the offsetted last sample is included in the edit
2459 * list duration as well. */
2461 avio_wb64(pb, delay);
2464 avio_wb32(pb, delay);
2467 avio_wb32(pb, 0x00010000);
2469 /* Avoid accidentally ending up with start_ct = -1 which has got a
2470 * special meaning. Normally start_ct should end up positive or zero
2471 * here, but use FFMIN in case dts is a a small positive integer
2472 * rounded to 0 when represented in MOV_TIMESCALE units. */
2473 av_assert0(av_rescale_rnd(start_dts, MOV_TIMESCALE, track->timescale, AV_ROUND_DOWN) <= 0);
2474 start_ct = -FFMIN(start_dts, 0);
2475 /* Note, this delay is calculated from the pts of the first sample,
2476 * ensuring that we don't reduce the duration for cases with
2481 /* For fragmented files, we don't know the full length yet. Setting
2482 * duration to 0 allows us to only specify the offset, including
2483 * the rest of the content (from all future fragments) without specifying
2484 * an explicit duration. */
2485 if (mov->flags & FF_MOV_FLAG_FRAGMENT)
2490 avio_wb64(pb, duration);
2491 avio_wb64(pb, start_ct);
2493 avio_wb32(pb, duration);
2494 avio_wb32(pb, start_ct);
2496 avio_wb32(pb, 0x00010000);
2500 static int mov_write_tref_tag(AVIOContext *pb, MOVTrack *track)
2502 avio_wb32(pb, 20); // size
2503 ffio_wfourcc(pb, "tref");
2504 avio_wb32(pb, 12); // size (subatom)
2505 avio_wl32(pb, track->tref_tag);
2506 avio_wb32(pb, track->tref_id);
2510 // goes at the end of each track! ... Critical for PSP playback ("Incompatible data" without it)
2511 static int mov_write_uuid_tag_psp(AVIOContext *pb, MOVTrack *mov)
2513 avio_wb32(pb, 0x34); /* size ... reports as 28 in mp4box! */
2514 ffio_wfourcc(pb, "uuid");
2515 ffio_wfourcc(pb, "USMT");
2516 avio_wb32(pb, 0x21d24fce);
2517 avio_wb32(pb, 0xbb88695c);
2518 avio_wb32(pb, 0xfac9c740);
2519 avio_wb32(pb, 0x1c); // another size here!
2520 ffio_wfourcc(pb, "MTDT");
2521 avio_wb32(pb, 0x00010012);
2522 avio_wb32(pb, 0x0a);
2523 avio_wb32(pb, 0x55c40000);
2529 static int mov_write_udta_sdp(AVIOContext *pb, MOVTrack *track)
2531 AVFormatContext *ctx = track->rtp_ctx;
2532 char buf[1000] = "";
2535 ff_sdp_write_media(buf, sizeof(buf), ctx->streams[0], track->src_track,
2536 NULL, NULL, 0, 0, ctx);
2537 av_strlcatf(buf, sizeof(buf), "a=control:streamid=%d\r\n", track->track_id);
2540 avio_wb32(pb, len + 24);
2541 ffio_wfourcc(pb, "udta");
2542 avio_wb32(pb, len + 16);
2543 ffio_wfourcc(pb, "hnti");
2544 avio_wb32(pb, len + 8);
2545 ffio_wfourcc(pb, "sdp ");
2546 avio_write(pb, buf, len);
2550 static int mov_write_track_metadata(AVIOContext *pb, AVStream *st,
2551 const char *tag, const char *str)
2553 int64_t pos = avio_tell(pb);
2554 AVDictionaryEntry *t = av_dict_get(st->metadata, str, NULL, 0);
2555 if (!t || !utf8len(t->value))
2558 avio_wb32(pb, 0); /* size */
2559 ffio_wfourcc(pb, tag); /* type */
2560 avio_write(pb, t->value, strlen(t->value)); /* UTF8 string value */
2561 return update_size(pb, pos);
2564 static int mov_write_track_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
2567 AVIOContext *pb_buf;
2571 if (!st || mov->fc->flags & AVFMT_FLAG_BITEXACT)
2574 ret = avio_open_dyn_buf(&pb_buf);
2578 if (mov->mode & MODE_MP4)
2579 mov_write_track_metadata(pb_buf, st, "name", "title");
2581 if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) {
2582 avio_wb32(pb, size + 8);
2583 ffio_wfourcc(pb, "udta");
2584 avio_write(pb, buf, size);
2591 static int mov_write_trak_tag(AVIOContext *pb, MOVMuxContext *mov,
2592 MOVTrack *track, AVStream *st)
2594 int64_t pos = avio_tell(pb);
2595 int entry_backup = track->entry;
2596 int chunk_backup = track->chunkCount;
2599 /* If we want to have an empty moov, but some samples already have been
2600 * buffered (delay_moov), pretend that no samples have been written yet. */
2601 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV)
2602 track->chunkCount = track->entry = 0;
2604 avio_wb32(pb, 0); /* size */
2605 ffio_wfourcc(pb, "trak");
2606 mov_write_tkhd_tag(pb, mov, track, st);
2608 av_assert2(mov->use_editlist >= 0);
2610 if (track->start_dts != AV_NOPTS_VALUE) {
2611 if (mov->use_editlist)
2612 mov_write_edts_tag(pb, mov, track); // PSP Movies and several other cases require edts box
2613 else if ((track->entry && track->cluster[0].dts) || track->mode == MODE_PSP || is_clcp_track(track))
2614 av_log(mov->fc, AV_LOG_WARNING,
2615 "Not writing any edit list even though one would have been required\n");
2618 if (track->tref_tag)
2619 mov_write_tref_tag(pb, track);
2621 if ((ret = mov_write_mdia_tag(pb, mov, track)) < 0)
2623 if (track->mode == MODE_PSP)
2624 mov_write_uuid_tag_psp(pb, track); // PSP Movies require this uuid box
2625 if (track->tag == MKTAG('r','t','p',' '))
2626 mov_write_udta_sdp(pb, track);
2627 if (track->mode == MODE_MOV) {
2628 if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) {
2629 double sample_aspect_ratio = av_q2d(st->sample_aspect_ratio);
2630 if (st->sample_aspect_ratio.num && 1.0 != sample_aspect_ratio) {
2631 mov_write_tapt_tag(pb, track);
2634 if (is_clcp_track(track) && st->sample_aspect_ratio.num) {
2635 mov_write_tapt_tag(pb, track);
2638 mov_write_track_udta_tag(pb, mov, st);
2639 track->entry = entry_backup;
2640 track->chunkCount = chunk_backup;
2641 return update_size(pb, pos);
2644 static int mov_write_iods_tag(AVIOContext *pb, MOVMuxContext *mov)
2646 int i, has_audio = 0, has_video = 0;
2647 int64_t pos = avio_tell(pb);
2648 int audio_profile = mov->iods_audio_profile;
2649 int video_profile = mov->iods_video_profile;
2650 for (i = 0; i < mov->nb_streams; i++) {
2651 if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
2652 has_audio |= mov->tracks[i].enc->codec_type == AVMEDIA_TYPE_AUDIO;
2653 has_video |= mov->tracks[i].enc->codec_type == AVMEDIA_TYPE_VIDEO;
2656 if (audio_profile < 0)
2657 audio_profile = 0xFF - has_audio;
2658 if (video_profile < 0)
2659 video_profile = 0xFF - has_video;
2660 avio_wb32(pb, 0x0); /* size */
2661 ffio_wfourcc(pb, "iods");
2662 avio_wb32(pb, 0); /* version & flags */
2663 put_descr(pb, 0x10, 7);
2664 avio_wb16(pb, 0x004f);
2667 avio_w8(pb, audio_profile);
2668 avio_w8(pb, video_profile);
2670 return update_size(pb, pos);
2673 static int mov_write_trex_tag(AVIOContext *pb, MOVTrack *track)
2675 avio_wb32(pb, 0x20); /* size */
2676 ffio_wfourcc(pb, "trex");
2677 avio_wb32(pb, 0); /* version & flags */
2678 avio_wb32(pb, track->track_id); /* track ID */
2679 avio_wb32(pb, 1); /* default sample description index */
2680 avio_wb32(pb, 0); /* default sample duration */
2681 avio_wb32(pb, 0); /* default sample size */
2682 avio_wb32(pb, 0); /* default sample flags */
2686 static int mov_write_mvex_tag(AVIOContext *pb, MOVMuxContext *mov)
2688 int64_t pos = avio_tell(pb);
2690 avio_wb32(pb, 0x0); /* size */
2691 ffio_wfourcc(pb, "mvex");
2692 for (i = 0; i < mov->nb_streams; i++)
2693 mov_write_trex_tag(pb, &mov->tracks[i]);
2694 return update_size(pb, pos);
2697 static int mov_write_mvhd_tag(AVIOContext *pb, MOVMuxContext *mov)
2699 int max_track_id = 1, i;
2700 int64_t max_track_len = 0;
2703 for (i = 0; i < mov->nb_streams; i++) {
2704 if (mov->tracks[i].entry > 0 && mov->tracks[i].timescale) {
2705 int64_t max_track_len_temp = av_rescale_rnd(mov->tracks[i].track_duration,
2707 mov->tracks[i].timescale,
2709 if (max_track_len < max_track_len_temp)
2710 max_track_len = max_track_len_temp;
2711 if (max_track_id < mov->tracks[i].track_id)
2712 max_track_id = mov->tracks[i].track_id;
2715 /* If using delay_moov, make sure the output is the same as if no
2716 * samples had been written yet. */
2717 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
2722 version = max_track_len < UINT32_MAX ? 0 : 1;
2723 avio_wb32(pb, version == 1 ? 120 : 108); /* size */
2725 ffio_wfourcc(pb, "mvhd");
2726 avio_w8(pb, version);
2727 avio_wb24(pb, 0); /* flags */
2729 avio_wb64(pb, mov->time);
2730 avio_wb64(pb, mov->time);
2732 avio_wb32(pb, mov->time); /* creation time */
2733 avio_wb32(pb, mov->time); /* modification time */
2735 avio_wb32(pb, MOV_TIMESCALE);
2736 (version == 1) ? avio_wb64(pb, max_track_len) : avio_wb32(pb, max_track_len); /* duration of longest track */
2738 avio_wb32(pb, 0x00010000); /* reserved (preferred rate) 1.0 = normal */
2739 avio_wb16(pb, 0x0100); /* reserved (preferred volume) 1.0 = normal */
2740 avio_wb16(pb, 0); /* reserved */
2741 avio_wb32(pb, 0); /* reserved */
2742 avio_wb32(pb, 0); /* reserved */
2744 /* Matrix structure */
2745 write_matrix(pb, 1, 0, 0, 1, 0, 0);
2747 avio_wb32(pb, 0); /* reserved (preview time) */
2748 avio_wb32(pb, 0); /* reserved (preview duration) */
2749 avio_wb32(pb, 0); /* reserved (poster time) */
2750 avio_wb32(pb, 0); /* reserved (selection time) */
2751 avio_wb32(pb, 0); /* reserved (selection duration) */
2752 avio_wb32(pb, 0); /* reserved (current time) */
2753 avio_wb32(pb, max_track_id + 1); /* Next track id */
2757 static int mov_write_itunes_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov,
2760 avio_wb32(pb, 33); /* size */
2761 ffio_wfourcc(pb, "hdlr");
2764 ffio_wfourcc(pb, "mdir");
2765 ffio_wfourcc(pb, "appl");
2772 /* helper function to write a data tag with the specified string as data */
2773 static int mov_write_string_data_tag(AVIOContext *pb, const char *data, int lang, int long_style)
2776 int size = 16 + strlen(data);
2777 avio_wb32(pb, size); /* size */
2778 ffio_wfourcc(pb, "data");
2781 avio_write(pb, data, strlen(data));
2785 lang = ff_mov_iso639_to_lang("und", 1);
2786 avio_wb16(pb, strlen(data)); /* string length */
2787 avio_wb16(pb, lang);
2788 avio_write(pb, data, strlen(data));
2789 return strlen(data) + 4;
2793 static int mov_write_string_tag(AVIOContext *pb, const char *name,
2794 const char *value, int lang, int long_style)
2797 if (value && value[0]) {
2798 int64_t pos = avio_tell(pb);
2799 avio_wb32(pb, 0); /* size */
2800 ffio_wfourcc(pb, name);
2801 mov_write_string_data_tag(pb, value, lang, long_style);
2802 size = update_size(pb, pos);
2807 static int mov_write_string_metadata(AVFormatContext *s, AVIOContext *pb,
2808 const char *name, const char *tag,
2811 int l, lang = 0, len, len2;
2812 AVDictionaryEntry *t, *t2 = NULL;
2815 if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
2818 len = strlen(t->key);
2819 snprintf(tag2, sizeof(tag2), "%s-", tag);
2820 while ((t2 = av_dict_get(s->metadata, tag2, t2, AV_DICT_IGNORE_SUFFIX))) {
2821 len2 = strlen(t2->key);
2822 if (len2 == len + 4 && !strcmp(t->value, t2->value)
2823 && (l = ff_mov_iso639_to_lang(&t2->key[len2 - 3], 1)) >= 0) {
2828 return mov_write_string_tag(pb, name, t->value, lang, long_style);
2831 /* iTunes bpm number */
2832 static int mov_write_tmpo_tag(AVIOContext *pb, AVFormatContext *s)
2834 AVDictionaryEntry *t = av_dict_get(s->metadata, "tmpo", NULL, 0);
2835 int size = 0, tmpo = t ? atoi(t->value) : 0;
2838 avio_wb32(pb, size);
2839 ffio_wfourcc(pb, "tmpo");
2840 avio_wb32(pb, size-8); /* size */
2841 ffio_wfourcc(pb, "data");
2842 avio_wb32(pb, 0x15); //type specifier
2844 avio_wb16(pb, tmpo); // data
2849 /* iTunes track or disc number */
2850 static int mov_write_trkn_tag(AVIOContext *pb, MOVMuxContext *mov,
2851 AVFormatContext *s, int disc)
2853 AVDictionaryEntry *t = av_dict_get(s->metadata,
2854 disc ? "disc" : "track",
2856 int size = 0, track = t ? atoi(t->value) : 0;
2859 char *slash = strchr(t->value, '/');
2861 tracks = atoi(slash + 1);
2862 avio_wb32(pb, 32); /* size */
2863 ffio_wfourcc(pb, disc ? "disk" : "trkn");
2864 avio_wb32(pb, 24); /* size */
2865 ffio_wfourcc(pb, "data");
2866 avio_wb32(pb, 0); // 8 bytes empty
2868 avio_wb16(pb, 0); // empty
2869 avio_wb16(pb, track); // track / disc number
2870 avio_wb16(pb, tracks); // total track / disc number
2871 avio_wb16(pb, 0); // empty
2877 static int mov_write_int8_metadata(AVFormatContext *s, AVIOContext *pb,
2878 const char *name, const char *tag,
2881 AVDictionaryEntry *t = NULL;
2883 int size = 24 + len;
2885 if (len != 1 && len != 4)
2888 if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
2890 num = atoi(t->value);
2892 avio_wb32(pb, size);
2893 ffio_wfourcc(pb, name);
2894 avio_wb32(pb, size - 8);
2895 ffio_wfourcc(pb, "data");
2896 avio_wb32(pb, 0x15);
2898 if (len==4) avio_wb32(pb, num);
2899 else avio_w8 (pb, num);
2904 /* iTunes meta data list */
2905 static int mov_write_ilst_tag(AVIOContext *pb, MOVMuxContext *mov,
2908 int64_t pos = avio_tell(pb);
2909 avio_wb32(pb, 0); /* size */
2910 ffio_wfourcc(pb, "ilst");
2911 mov_write_string_metadata(s, pb, "\251nam", "title" , 1);
2912 mov_write_string_metadata(s, pb, "\251ART", "artist" , 1);
2913 mov_write_string_metadata(s, pb, "aART", "album_artist", 1);
2914 mov_write_string_metadata(s, pb, "\251wrt", "composer" , 1);
2915 mov_write_string_metadata(s, pb, "\251alb", "album" , 1);
2916 mov_write_string_metadata(s, pb, "\251day", "date" , 1);
2918 !mov_write_string_metadata(s, pb, "\251too", "encoding_tool", 1))
2919 mov_write_string_tag(pb, "\251too", LIBAVFORMAT_IDENT, 0, 1);
2920 mov_write_string_metadata(s, pb, "\251cmt", "comment" , 1);
2921 mov_write_string_metadata(s, pb, "\251gen", "genre" , 1);
2922 mov_write_string_metadata(s, pb, "\251cpy", "copyright", 1);
2923 mov_write_string_metadata(s, pb, "\251grp", "grouping" , 1);
2924 mov_write_string_metadata(s, pb, "\251lyr", "lyrics" , 1);
2925 mov_write_string_metadata(s, pb, "desc", "description",1);
2926 mov_write_string_metadata(s, pb, "ldes", "synopsis" , 1);
2927 mov_write_string_metadata(s, pb, "tvsh", "show" , 1);
2928 mov_write_string_metadata(s, pb, "tven", "episode_id",1);
2929 mov_write_string_metadata(s, pb, "tvnn", "network" , 1);
2930 mov_write_int8_metadata (s, pb, "tves", "episode_sort",4);
2931 mov_write_int8_metadata (s, pb, "tvsn", "season_number",4);
2932 mov_write_int8_metadata (s, pb, "stik", "media_type",1);
2933 mov_write_int8_metadata (s, pb, "hdvd", "hd_video", 1);
2934 mov_write_int8_metadata (s, pb, "pgap", "gapless_playback",1);
2935 mov_write_int8_metadata (s, pb, "cpil", "compilation", 1);
2936 mov_write_trkn_tag(pb, mov, s, 0); // track number
2937 mov_write_trkn_tag(pb, mov, s, 1); // disc number
2938 mov_write_tmpo_tag(pb, s);
2939 return update_size(pb, pos);
2942 /* iTunes meta data tag */
2943 static int mov_write_meta_tag(AVIOContext *pb, MOVMuxContext *mov,
2947 int64_t pos = avio_tell(pb);
2948 avio_wb32(pb, 0); /* size */
2949 ffio_wfourcc(pb, "meta");
2951 mov_write_itunes_hdlr_tag(pb, mov, s);
2952 mov_write_ilst_tag(pb, mov, s);
2953 size = update_size(pb, pos);
2957 static int mov_write_raw_metadata_tag(AVFormatContext *s, AVIOContext *pb,
2958 const char *name, const char *key)
2961 AVDictionaryEntry *t;
2963 if (!(t = av_dict_get(s->metadata, key, NULL, 0)))
2966 len = strlen(t->value);
2969 avio_wb32(pb, size);
2970 ffio_wfourcc(pb, name);
2971 avio_write(pb, t->value, len);
2977 static int ascii_to_wc(AVIOContext *pb, const uint8_t *b)
2981 GET_UTF8(val, *b++, return -1;)
2984 avio_wb16(pb, 0x00);
2988 static uint16_t language_code(const char *str)
2990 return (((str[0] - 0x60) & 0x1F) << 10) +
2991 (((str[1] - 0x60) & 0x1F) << 5) +
2992 (( str[2] - 0x60) & 0x1F);
2995 static int mov_write_3gp_udta_tag(AVIOContext *pb, AVFormatContext *s,
2996 const char *tag, const char *str)
2998 int64_t pos = avio_tell(pb);
2999 AVDictionaryEntry *t = av_dict_get(s->metadata, str, NULL, 0);
3000 if (!t || !utf8len(t->value))
3002 avio_wb32(pb, 0); /* size */
3003 ffio_wfourcc(pb, tag); /* type */
3004 avio_wb32(pb, 0); /* version + flags */
3005 if (!strcmp(tag, "yrrc"))
3006 avio_wb16(pb, atoi(t->value));
3008 avio_wb16(pb, language_code("eng")); /* language */
3009 avio_write(pb, t->value, strlen(t->value) + 1); /* UTF8 string value */
3010 if (!strcmp(tag, "albm") &&
3011 (t = av_dict_get(s->metadata, "track", NULL, 0)))
3012 avio_w8(pb, atoi(t->value));
3014 return update_size(pb, pos);
3017 static int mov_write_chpl_tag(AVIOContext *pb, AVFormatContext *s)
3019 int64_t pos = avio_tell(pb);
3020 int i, nb_chapters = FFMIN(s->nb_chapters, 255);
3022 avio_wb32(pb, 0); // size
3023 ffio_wfourcc(pb, "chpl");
3024 avio_wb32(pb, 0x01000000); // version + flags
3025 avio_wb32(pb, 0); // unknown
3026 avio_w8(pb, nb_chapters);
3028 for (i = 0; i < nb_chapters; i++) {
3029 AVChapter *c = s->chapters[i];
3030 AVDictionaryEntry *t;
3031 avio_wb64(pb, av_rescale_q(c->start, c->time_base, (AVRational){1,10000000}));
3033 if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
3034 int len = FFMIN(strlen(t->value), 255);
3036 avio_write(pb, t->value, len);
3040 return update_size(pb, pos);
3043 static int mov_write_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
3046 AVIOContext *pb_buf;
3050 ret = avio_open_dyn_buf(&pb_buf);
3054 if (mov->mode & MODE_3GP) {
3055 mov_write_3gp_udta_tag(pb_buf, s, "perf", "artist");
3056 mov_write_3gp_udta_tag(pb_buf, s, "titl", "title");
3057 mov_write_3gp_udta_tag(pb_buf, s, "auth", "author");
3058 mov_write_3gp_udta_tag(pb_buf, s, "gnre", "genre");
3059 mov_write_3gp_udta_tag(pb_buf, s, "dscp", "comment");
3060 mov_write_3gp_udta_tag(pb_buf, s, "albm", "album");
3061 mov_write_3gp_udta_tag(pb_buf, s, "cprt", "copyright");
3062 mov_write_3gp_udta_tag(pb_buf, s, "yrrc", "date");
3063 } else if (mov->mode == MODE_MOV) { // the title field breaks gtkpod with mp4 and my suspicion is that stuff is not valid in mp4
3064 mov_write_string_metadata(s, pb_buf, "\251ART", "artist", 0);
3065 mov_write_string_metadata(s, pb_buf, "\251nam", "title", 0);
3066 mov_write_string_metadata(s, pb_buf, "\251aut", "author", 0);
3067 mov_write_string_metadata(s, pb_buf, "\251alb", "album", 0);
3068 mov_write_string_metadata(s, pb_buf, "\251day", "date", 0);
3069 mov_write_string_metadata(s, pb_buf, "\251swr", "encoder", 0);
3070 // currently ignored by mov.c
3071 mov_write_string_metadata(s, pb_buf, "\251des", "comment", 0);
3072 // add support for libquicktime, this atom is also actually read by mov.c
3073 mov_write_string_metadata(s, pb_buf, "\251cmt", "comment", 0);
3074 mov_write_string_metadata(s, pb_buf, "\251gen", "genre", 0);
3075 mov_write_string_metadata(s, pb_buf, "\251cpy", "copyright", 0);
3076 mov_write_string_metadata(s, pb_buf, "\251mak", "make", 0);
3077 mov_write_string_metadata(s, pb_buf, "\251mod", "model", 0);
3078 mov_write_raw_metadata_tag(s, pb_buf, "XMP_", "xmp");
3080 /* iTunes meta data */
3081 mov_write_meta_tag(pb_buf, mov, s);
3084 if (s->nb_chapters && !(mov->flags & FF_MOV_FLAG_DISABLE_CHPL))
3085 mov_write_chpl_tag(pb_buf, s);
3087 if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) {
3088 avio_wb32(pb, size + 8);
3089 ffio_wfourcc(pb, "udta");
3090 avio_write(pb, buf, size);
3097 static void mov_write_psp_udta_tag(AVIOContext *pb,
3098 const char *str, const char *lang, int type)
3100 int len = utf8len(str) + 1;
3103 avio_wb16(pb, len * 2 + 10); /* size */
3104 avio_wb32(pb, type); /* type */
3105 avio_wb16(pb, language_code(lang)); /* language */
3106 avio_wb16(pb, 0x01); /* ? */
3107 ascii_to_wc(pb, str);
3110 static int mov_write_uuidusmt_tag(AVIOContext *pb, AVFormatContext *s)
3112 MOVMuxContext *mov = s->priv_data;
3113 AVDictionaryEntry *title = av_dict_get(s->metadata, "title", NULL, 0);
3117 pos = avio_tell(pb);
3118 avio_wb32(pb, 0); /* size placeholder*/
3119 ffio_wfourcc(pb, "uuid");
3120 ffio_wfourcc(pb, "USMT");
3121 avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
3122 avio_wb32(pb, 0xbb88695c);
3123 avio_wb32(pb, 0xfac9c740);
3125 pos2 = avio_tell(pb);
3126 avio_wb32(pb, 0); /* size placeholder*/
3127 ffio_wfourcc(pb, "MTDT");
3131 avio_wb16(pb, 0x0C); /* size */
3132 avio_wb32(pb, 0x0B); /* type */
3133 avio_wb16(pb, language_code("und")); /* language */
3134 avio_wb16(pb, 0x0); /* ? */
3135 avio_wb16(pb, 0x021C); /* data */
3138 mov_write_psp_udta_tag(pb, LIBAVCODEC_IDENT, "eng", 0x04);
3139 mov_write_psp_udta_tag(pb, title->value, "eng", 0x01);
3140 mov_write_psp_udta_tag(pb, "2006/04/01 11:11:11", "und", 0x03);
3142 update_size(pb, pos2);
3143 return update_size(pb, pos);
3149 static void build_chunks(MOVTrack *trk)
3152 MOVIentry *chunk = &trk->cluster[0];
3153 uint64_t chunkSize = chunk->size;
3154 chunk->chunkNum = 1;
3155 if (trk->chunkCount)
3157 trk->chunkCount = 1;
3158 for (i = 1; i<trk->entry; i++){
3159 if (chunk->pos + chunkSize == trk->cluster[i].pos &&
3160 chunkSize + trk->cluster[i].size < (1<<20)){
3161 chunkSize += trk->cluster[i].size;
3162 chunk->samples_in_chunk += trk->cluster[i].entries;
3164 trk->cluster[i].chunkNum = chunk->chunkNum+1;
3165 chunk=&trk->cluster[i];
3166 chunkSize = chunk->size;
3172 static int mov_write_moov_tag(AVIOContext *pb, MOVMuxContext *mov,
3176 int64_t pos = avio_tell(pb);
3177 avio_wb32(pb, 0); /* size placeholder*/
3178 ffio_wfourcc(pb, "moov");
3180 for (i = 0; i < mov->nb_streams; i++) {
3181 if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
3184 mov->tracks[i].time = mov->time;
3185 mov->tracks[i].track_id = i + 1;
3187 if (mov->tracks[i].entry)
3188 build_chunks(&mov->tracks[i]);
3191 if (mov->chapter_track)
3192 for (i = 0; i < s->nb_streams; i++) {
3193 mov->tracks[i].tref_tag = MKTAG('c','h','a','p');
3194 mov->tracks[i].tref_id = mov->tracks[mov->chapter_track].track_id;
3196 for (i = 0; i < mov->nb_streams; i++) {
3197 if (mov->tracks[i].tag == MKTAG('r','t','p',' ')) {
3198 mov->tracks[i].tref_tag = MKTAG('h','i','n','t');
3199 mov->tracks[i].tref_id =
3200 mov->tracks[mov->tracks[i].src_track].track_id;
3203 for (i = 0; i < mov->nb_streams; i++) {
3204 if (mov->tracks[i].tag == MKTAG('t','m','c','d')) {
3205 int src_trk = mov->tracks[i].src_track;
3206 mov->tracks[src_trk].tref_tag = mov->tracks[i].tag;
3207 mov->tracks[src_trk].tref_id = mov->tracks[i].track_id;
3208 //src_trk may have a different timescale than the tmcd track
3209 mov->tracks[i].track_duration = av_rescale(mov->tracks[src_trk].track_duration,
3210 mov->tracks[i].timescale,
3211 mov->tracks[src_trk].timescale);
3215 mov_write_mvhd_tag(pb, mov);
3216 if (mov->mode != MODE_MOV && !mov->iods_skip)
3217 mov_write_iods_tag(pb, mov);
3218 for (i = 0; i < mov->nb_streams; i++) {
3219 if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_FRAGMENT) {
3220 int ret = mov_write_trak_tag(pb, mov, &(mov->tracks[i]), i < s->nb_streams ? s->streams[i] : NULL);
3225 if (mov->flags & FF_MOV_FLAG_FRAGMENT)
3226 mov_write_mvex_tag(pb, mov); /* QuickTime requires trak to precede this */
3228 if (mov->mode == MODE_PSP)
3229 mov_write_uuidusmt_tag(pb, s);
3231 mov_write_udta_tag(pb, mov, s);
3233 return update_size(pb, pos);
3236 static void param_write_int(AVIOContext *pb, const char *name, int value)
3238 avio_printf(pb, "<param name=\"%s\" value=\"%d\" valuetype=\"data\"/>\n", name, value);
3241 static void param_write_string(AVIOContext *pb, const char *name, const char *value)
3243 avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, value);
3246 static void param_write_hex(AVIOContext *pb, const char *name, const uint8_t *value, int len)
3249 len = FFMIN(sizeof(buf) / 2 - 1, len);
3250 ff_data_to_hex(buf, value, len, 0);
3251 buf[2 * len] = '\0';
3252 avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, buf);
3255 static int mov_write_isml_manifest(AVIOContext *pb, MOVMuxContext *mov)
3257 int64_t pos = avio_tell(pb);
3259 static const uint8_t uuid[] = {
3260 0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd,
3261 0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66
3265 ffio_wfourcc(pb, "uuid");
3266 avio_write(pb, uuid, sizeof(uuid));
3269 avio_printf(pb, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
3270 avio_printf(pb, "<smil xmlns=\"http://www.w3.org/2001/SMIL20/Language\">\n");
3271 avio_printf(pb, "<head>\n");
3273 avio_printf(pb, "<meta name=\"creator\" content=\"%s\" />\n",
3275 avio_printf(pb, "</head>\n");
3276 avio_printf(pb, "<body>\n");
3277 avio_printf(pb, "<switch>\n");
3278 for (i = 0; i < mov->nb_streams; i++) {
3279 MOVTrack *track = &mov->tracks[i];
3281 /* track->track_id is initialized in write_moov, and thus isn't known
3283 int track_id = i + 1;
3285 if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) {
3287 } else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO) {
3292 avio_printf(pb, "<%s systemBitrate=\"%d\">\n", type,
3293 track->enc->bit_rate);
3294 param_write_int(pb, "systemBitrate", track->enc->bit_rate);
3295 param_write_int(pb, "trackID", track_id);
3296 if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) {
3297 if (track->enc->codec_id == AV_CODEC_ID_H264) {
3299 int size = track->enc->extradata_size;
3300 if (!ff_avc_write_annexb_extradata(track->enc->extradata, &ptr,
3302 param_write_hex(pb, "CodecPrivateData",
3303 ptr ? ptr : track->enc->extradata,
3307 param_write_string(pb, "FourCC", "H264");
3308 } else if (track->enc->codec_id == AV_CODEC_ID_VC1) {
3309 param_write_string(pb, "FourCC", "WVC1");
3310 param_write_hex(pb, "CodecPrivateData", track->enc->extradata,
3311 track->enc->extradata_size);
3313 param_write_int(pb, "MaxWidth", track->enc->width);
3314 param_write_int(pb, "MaxHeight", track->enc->height);
3315 param_write_int(pb, "DisplayWidth", track->enc->width);
3316 param_write_int(pb, "DisplayHeight", track->enc->height);
3318 if (track->enc->codec_id == AV_CODEC_ID_AAC) {
3319 param_write_string(pb, "FourCC", "AACL");
3320 } else if (track->enc->codec_id == AV_CODEC_ID_WMAPRO) {
3321 param_write_string(pb, "FourCC", "WMAP");
3323 param_write_hex(pb, "CodecPrivateData", track->enc->extradata,
3324 track->enc->extradata_size);
3325 param_write_int(pb, "AudioTag", ff_codec_get_tag(ff_codec_wav_tags,
3326 track->enc->codec_id));
3327 param_write_int(pb, "Channels", track->enc->channels);
3328 param_write_int(pb, "SamplingRate", track->enc->sample_rate);
3329 param_write_int(pb, "BitsPerSample", 16);
3330 param_write_int(pb, "PacketSize", track->enc->block_align ?
3331 track->enc->block_align : 4);
3333 avio_printf(pb, "</%s>\n", type);
3335 avio_printf(pb, "</switch>\n");
3336 avio_printf(pb, "</body>\n");
3337 avio_printf(pb, "</smil>\n");
3339 return update_size(pb, pos);
3342 static int mov_write_mfhd_tag(AVIOContext *pb, MOVMuxContext *mov)
3345 ffio_wfourcc(pb, "mfhd");
3347 avio_wb32(pb, mov->fragments);
3351 static uint32_t get_sample_flags(MOVTrack *track, MOVIentry *entry)
3353 return entry->flags & MOV_SYNC_SAMPLE ? MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO :
3354 (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC);
3357 static int mov_write_tfhd_tag(AVIOContext *pb, MOVMuxContext *mov,
3358 MOVTrack *track, int64_t moof_offset)
3360 int64_t pos = avio_tell(pb);
3361 uint32_t flags = MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
3362 MOV_TFHD_BASE_DATA_OFFSET;
3363 if (!track->entry) {
3364 flags |= MOV_TFHD_DURATION_IS_EMPTY;
3366 flags |= MOV_TFHD_DEFAULT_FLAGS;
3368 if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET)
3369 flags &= ~MOV_TFHD_BASE_DATA_OFFSET;
3370 if (mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) {
3371 flags &= ~MOV_TFHD_BASE_DATA_OFFSET;
3372 flags |= MOV_TFHD_DEFAULT_BASE_IS_MOOF;
3375 /* Don't set a default sample size, the silverlight player refuses
3376 * to play files with that set. Don't set a default sample duration,
3377 * WMP freaks out if it is set. Don't set a base data offset, PIFF
3378 * file format says it MUST NOT be set. */
3379 if (track->mode == MODE_ISM)
3380 flags &= ~(MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
3381 MOV_TFHD_BASE_DATA_OFFSET);
3383 avio_wb32(pb, 0); /* size placeholder */
3384 ffio_wfourcc(pb, "tfhd");
3385 avio_w8(pb, 0); /* version */
3386 avio_wb24(pb, flags);
3388 avio_wb32(pb, track->track_id); /* track-id */
3389 if (flags & MOV_TFHD_BASE_DATA_OFFSET)
3390 avio_wb64(pb, moof_offset);
3391 if (flags & MOV_TFHD_DEFAULT_DURATION) {
3392 track->default_duration = get_cluster_duration(track, 0);
3393 avio_wb32(pb, track->default_duration);
3395 if (flags & MOV_TFHD_DEFAULT_SIZE) {
3396 track->default_size = track->entry ? track->cluster[0].size : 1;
3397 avio_wb32(pb, track->default_size);
3399 track->default_size = -1;
3401 if (flags & MOV_TFHD_DEFAULT_FLAGS) {
3402 /* Set the default flags based on the second sample, if available.
3403 * If the first sample is different, that can be signaled via a separate field. */
3404 if (track->entry > 1)
3405 track->default_sample_flags = get_sample_flags(track, &track->cluster[1]);
3407 track->default_sample_flags =
3408 track->enc->codec_type == AVMEDIA_TYPE_VIDEO ?
3409 (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC) :
3410 MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO;
3411 avio_wb32(pb, track->default_sample_flags);
3414 return update_size(pb, pos);
3417 static int mov_write_trun_tag(AVIOContext *pb, MOVMuxContext *mov,
3418 MOVTrack *track, int moof_size,
3421 int64_t pos = avio_tell(pb);
3422 uint32_t flags = MOV_TRUN_DATA_OFFSET;
3425 for (i = first; i < end; i++) {
3426 if (get_cluster_duration(track, i) != track->default_duration)
3427 flags |= MOV_TRUN_SAMPLE_DURATION;
3428 if (track->cluster[i].size != track->default_size)
3429 flags |= MOV_TRUN_SAMPLE_SIZE;
3430 if (i > first && get_sample_flags(track, &track->cluster[i]) != track->default_sample_flags)
3431 flags |= MOV_TRUN_SAMPLE_FLAGS;
3433 if (!(flags & MOV_TRUN_SAMPLE_FLAGS) && track->entry > 0 &&
3434 get_sample_flags(track, &track->cluster[0]) != track->default_sample_flags)
3435 flags |= MOV_TRUN_FIRST_SAMPLE_FLAGS;
3436 if (track->flags & MOV_TRACK_CTTS)
3437 flags |= MOV_TRUN_SAMPLE_CTS;
3439 avio_wb32(pb, 0); /* size placeholder */
3440 ffio_wfourcc(pb, "trun");
3441 avio_w8(pb, 0); /* version */
3442 avio_wb24(pb, flags);
3444 avio_wb32(pb, end - first); /* sample count */
3445 if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET &&
3446 !(mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) &&
3448 avio_wb32(pb, 0); /* Later tracks follow immediately after the previous one */
3450 avio_wb32(pb, moof_size + 8 + track->data_offset +
3451 track->cluster[first].pos); /* data offset */
3452 if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS)
3453 avio_wb32(pb, get_sample_flags(track, &track->cluster[first]));
3455 for (i = first; i < end; i++) {
3456 if (flags & MOV_TRUN_SAMPLE_DURATION)
3457 avio_wb32(pb, get_cluster_duration(track, i));
3458 if (flags & MOV_TRUN_SAMPLE_SIZE)
3459 avio_wb32(pb, track->cluster[i].size);
3460 if (flags & MOV_TRUN_SAMPLE_FLAGS)
3461 avio_wb32(pb, get_sample_flags(track, &track->cluster[i]));
3462 if (flags & MOV_TRUN_SAMPLE_CTS)
3463 avio_wb32(pb, track->cluster[i].cts);
3466 mov->first_trun = 0;
3467 return update_size(pb, pos);
3470 static int mov_write_tfxd_tag(AVIOContext *pb, MOVTrack *track)
3472 int64_t pos = avio_tell(pb);
3473 static const uint8_t uuid[] = {
3474 0x6d, 0x1d, 0x9b, 0x05, 0x42, 0xd5, 0x44, 0xe6,
3475 0x80, 0xe2, 0x14, 0x1d, 0xaf, 0xf7, 0x57, 0xb2
3478 avio_wb32(pb, 0); /* size placeholder */
3479 ffio_wfourcc(pb, "uuid");
3480 avio_write(pb, uuid, sizeof(uuid));
3483 avio_wb64(pb, track->start_dts + track->frag_start +
3484 track->cluster[0].cts);
3485 avio_wb64(pb, track->end_pts -
3486 (track->cluster[0].dts + track->cluster[0].cts));
3488 return update_size(pb, pos);
3491 static int mov_write_tfrf_tag(AVIOContext *pb, MOVMuxContext *mov,
3492 MOVTrack *track, int entry)
3494 int n = track->nb_frag_info - 1 - entry, i;
3495 int size = 8 + 16 + 4 + 1 + 16*n;
3496 static const uint8_t uuid[] = {
3497 0xd4, 0x80, 0x7e, 0xf2, 0xca, 0x39, 0x46, 0x95,
3498 0x8e, 0x54, 0x26, 0xcb, 0x9e, 0x46, 0xa7, 0x9f
3504 avio_seek(pb, track->frag_info[entry].tfrf_offset, SEEK_SET);
3505 avio_wb32(pb, size);
3506 ffio_wfourcc(pb, "uuid");
3507 avio_write(pb, uuid, sizeof(uuid));
3511 for (i = 0; i < n; i++) {
3512 int index = entry + 1 + i;
3513 avio_wb64(pb, track->frag_info[index].time);
3514 avio_wb64(pb, track->frag_info[index].duration);
3516 if (n < mov->ism_lookahead) {
3517 int free_size = 16 * (mov->ism_lookahead - n);
3518 avio_wb32(pb, free_size);
3519 ffio_wfourcc(pb, "free");
3520 ffio_fill(pb, 0, free_size - 8);
3526 static int mov_write_tfrf_tags(AVIOContext *pb, MOVMuxContext *mov,
3529 int64_t pos = avio_tell(pb);
3531 for (i = 0; i < mov->ism_lookahead; i++) {
3532 /* Update the tfrf tag for the last ism_lookahead fragments,
3533 * nb_frag_info - 1 is the next fragment to be written. */
3534 mov_write_tfrf_tag(pb, mov, track, track->nb_frag_info - 2 - i);
3536 avio_seek(pb, pos, SEEK_SET);
3540 static int mov_add_tfra_entries(AVIOContext *pb, MOVMuxContext *mov, int tracks,
3544 for (i = 0; i < mov->nb_streams; i++) {
3545 MOVTrack *track = &mov->tracks[i];
3546 MOVFragmentInfo *info;
3547 if ((tracks >= 0 && i != tracks) || !track->entry)
3549 track->nb_frag_info++;
3550 if (track->nb_frag_info >= track->frag_info_capacity) {
3551 unsigned new_capacity = track->nb_frag_info + MOV_FRAG_INFO_ALLOC_INCREMENT;
3552 if (av_reallocp_array(&track->frag_info,
3554 sizeof(*track->frag_info)))
3555 return AVERROR(ENOMEM);
3556 track->frag_info_capacity = new_capacity;
3558 info = &track->frag_info[track->nb_frag_info - 1];
3559 info->offset = avio_tell(pb);
3561 // Try to recreate the original pts for the first packet
3562 // from the fields we have stored
3563 info->time = track->start_dts + track->frag_start +
3564 track->cluster[0].cts;
3565 info->duration = track->end_pts -
3566 (track->cluster[0].dts + track->cluster[0].cts);
3567 // If the pts is less than zero, we will have trimmed
3568 // away parts of the media track using an edit list,
3569 // and the corresponding start presentation time is zero.
3570 if (info->time < 0) {
3571 info->duration += info->time;
3574 info->tfrf_offset = 0;
3575 mov_write_tfrf_tags(pb, mov, track);
3580 static int mov_write_tfdt_tag(AVIOContext *pb, MOVTrack *track)
3582 int64_t pos = avio_tell(pb);
3584 avio_wb32(pb, 0); /* size */
3585 ffio_wfourcc(pb, "tfdt");
3586 avio_w8(pb, 1); /* version */
3588 avio_wb64(pb, track->frag_start);
3589 return update_size(pb, pos);
3592 static int mov_write_traf_tag(AVIOContext *pb, MOVMuxContext *mov,
3593 MOVTrack *track, int64_t moof_offset,
3596 int64_t pos = avio_tell(pb);
3598 avio_wb32(pb, 0); /* size placeholder */
3599 ffio_wfourcc(pb, "traf");
3601 mov_write_tfhd_tag(pb, mov, track, moof_offset);
3602 if (mov->mode != MODE_ISM)
3603 mov_write_tfdt_tag(pb, track);
3604 for (i = 1; i < track->entry; i++) {
3605 if (track->cluster[i].pos != track->cluster[i - 1].pos + track->cluster[i - 1].size) {
3606 mov_write_trun_tag(pb, mov, track, moof_size, start, i);
3610 mov_write_trun_tag(pb, mov, track, moof_size, start, track->entry);
3611 if (mov->mode == MODE_ISM) {
3612 mov_write_tfxd_tag(pb, track);
3614 if (mov->ism_lookahead) {
3615 int i, size = 16 + 4 + 1 + 16 * mov->ism_lookahead;
3617 if (track->nb_frag_info > 0) {
3618 MOVFragmentInfo *info = &track->frag_info[track->nb_frag_info - 1];
3619 if (!info->tfrf_offset)
3620 info->tfrf_offset = avio_tell(pb);
3622 avio_wb32(pb, 8 + size);
3623 ffio_wfourcc(pb, "free");
3624 for (i = 0; i < size; i++)
3629 return update_size(pb, pos);
3632 static int mov_write_moof_tag_internal(AVIOContext *pb, MOVMuxContext *mov,
3633 int tracks, int moof_size)
3635 int64_t pos = avio_tell(pb);
3638 avio_wb32(pb, 0); /* size placeholder */
3639 ffio_wfourcc(pb, "moof");
3640 mov->first_trun = 1;
3642 mov_write_mfhd_tag(pb, mov);
3643 for (i = 0; i < mov->nb_streams; i++) {
3644 MOVTrack *track = &mov->tracks[i];
3645 if (tracks >= 0 && i != tracks)
3649 mov_write_traf_tag(pb, mov, track, pos, moof_size);
3652 return update_size(pb, pos);
3655 static int mov_write_sidx_tag(AVIOContext *pb,
3656 MOVTrack *track, int ref_size, int total_sidx_size)
3658 int64_t pos = avio_tell(pb), offset_pos, end_pos;
3659 int64_t presentation_time, duration, offset;
3660 int starts_with_SAP, i, entries;
3664 presentation_time = track->start_dts + track->frag_start +
3665 track->cluster[0].cts;
3666 duration = track->end_pts -
3667 (track->cluster[0].dts + track->cluster[0].cts);
3668 starts_with_SAP = track->cluster[0].flags & MOV_SYNC_SAMPLE;
3670 // pts<0 should be cut away using edts
3671 if (presentation_time < 0) {
3672 duration += presentation_time;
3673 presentation_time = 0;
3676 entries = track->nb_frag_info;
3677 presentation_time = track->frag_info[0].time;
3680 avio_wb32(pb, 0); /* size */
3681 ffio_wfourcc(pb, "sidx");
3682 avio_w8(pb, 1); /* version */
3684 avio_wb32(pb, track->track_id); /* reference_ID */
3685 avio_wb32(pb, track->timescale); /* timescale */
3686 avio_wb64(pb, presentation_time); /* earliest_presentation_time */
3687 offset_pos = avio_tell(pb);
3688 avio_wb64(pb, 0); /* first_offset (offset to referenced moof) */
3689 avio_wb16(pb, 0); /* reserved */
3691 avio_wb16(pb, entries); /* reference_count */
3692 for (i = 0; i < entries; i++) {
3693 if (!track->entry) {
3694 if (i > 1 && track->frag_info[i].offset != track->frag_info[i - 1].offset + track->frag_info[i - 1].size) {
3695 av_log(NULL, AV_LOG_ERROR, "Non-consecutive fragments, writing incorrect sidx\n");
3697 duration = track->frag_info[i].duration;
3698 ref_size = track->frag_info[i].size;
3699 starts_with_SAP = 1;
3701 avio_wb32(pb, (0 << 31) | (ref_size & 0x7fffffff)); /* reference_type (0 = media) | referenced_size */
3702 avio_wb32(pb, duration); /* subsegment_duration */
3703 avio_wb32(pb, (starts_with_SAP << 31) | (0 << 28) | 0); /* starts_with_SAP | SAP_type | SAP_delta_time */
3706 end_pos = avio_tell(pb);
3707 offset = pos + total_sidx_size - end_pos;
3708 avio_seek(pb, offset_pos, SEEK_SET);
3709 avio_wb64(pb, offset);
3710 avio_seek(pb, end_pos, SEEK_SET);
3711 return update_size(pb, pos);
3714 static int mov_write_sidx_tags(AVIOContext *pb, MOVMuxContext *mov,
3715 int tracks, int ref_size)
3718 AVIOContext *avio_buf;
3720 for (round = 0; round < 2; round++) {
3721 // First run one round to calculate the total size of all
3723 // This would be much simpler if we'd only write one sidx
3724 // atom, for the first track in the moof.
3726 if ((ret = ffio_open_null_buf(&avio_buf)) < 0)
3731 for (i = 0; i < mov->nb_streams; i++) {
3732 MOVTrack *track = &mov->tracks[i];
3733 if (tracks >= 0 && i != tracks)
3735 // When writing a sidx for the full file, entry is 0, but
3736 // we want to include all tracks. ref_size is 0 in this case,
3737 // since we read it from frag_info instead.
3738 if (!track->entry && ref_size > 0)
3740 total_size -= mov_write_sidx_tag(avio_buf, track, ref_size,
3744 total_size = ffio_close_null_buf(avio_buf);
3749 static int mov_write_moof_tag(AVIOContext *pb, MOVMuxContext *mov, int tracks,
3752 AVIOContext *avio_buf;
3755 if ((ret = ffio_open_null_buf(&avio_buf)) < 0)
3757 mov_write_moof_tag_internal(avio_buf, mov, tracks, 0);
3758 moof_size = ffio_close_null_buf(avio_buf);
3760 if (mov->flags & FF_MOV_FLAG_DASH && !(mov->flags & FF_MOV_FLAG_FASTSTART))
3761 mov_write_sidx_tags(pb, mov, tracks, moof_size + 8 + mdat_size);
3763 if ((ret = mov_add_tfra_entries(pb, mov, tracks, moof_size + 8 + mdat_size)) < 0)
3766 return mov_write_moof_tag_internal(pb, mov, tracks, moof_size);
3769 static int mov_write_tfra_tag(AVIOContext *pb, MOVTrack *track)
3771 int64_t pos = avio_tell(pb);
3774 avio_wb32(pb, 0); /* size placeholder */
3775 ffio_wfourcc(pb, "tfra");
3776 avio_w8(pb, 1); /* version */
3779 avio_wb32(pb, track->track_id);
3780 avio_wb32(pb, 0); /* length of traf/trun/sample num */
3781 avio_wb32(pb, track->nb_frag_info);
3782 for (i = 0; i < track->nb_frag_info; i++) {
3783 avio_wb64(pb, track->frag_info[i].time);
3784 avio_wb64(pb, track->frag_info[i].offset + track->data_offset);
3785 avio_w8(pb, 1); /* traf number */
3786 avio_w8(pb, 1); /* trun number */
3787 avio_w8(pb, 1); /* sample number */
3790 return update_size(pb, pos);
3793 static int mov_write_mfra_tag(AVIOContext *pb, MOVMuxContext *mov)
3795 int64_t pos = avio_tell(pb);
3798 avio_wb32(pb, 0); /* size placeholder */
3799 ffio_wfourcc(pb, "mfra");
3800 /* An empty mfra atom is enough to indicate to the publishing point that
3801 * the stream has ended. */
3802 if (mov->flags & FF_MOV_FLAG_ISML)
3803 return update_size(pb, pos);
3805 for (i = 0; i < mov->nb_streams; i++) {
3806 MOVTrack *track = &mov->tracks[i];
3807 if (track->nb_frag_info)
3808 mov_write_tfra_tag(pb, track);
3812 ffio_wfourcc(pb, "mfro");
3813 avio_wb32(pb, 0); /* version + flags */
3814 avio_wb32(pb, avio_tell(pb) + 4 - pos);
3816 return update_size(pb, pos);
3819 static int mov_write_mdat_tag(AVIOContext *pb, MOVMuxContext *mov)
3821 avio_wb32(pb, 8); // placeholder for extended size field (64 bit)
3822 ffio_wfourcc(pb, mov->mode == MODE_MOV ? "wide" : "free");
3824 mov->mdat_pos = avio_tell(pb);
3825 avio_wb32(pb, 0); /* size placeholder*/
3826 ffio_wfourcc(pb, "mdat");
3830 /* TODO: This needs to be more general */
3831 static int mov_write_ftyp_tag(AVIOContext *pb, AVFormatContext *s)
3833 MOVMuxContext *mov = s->priv_data;
3834 int64_t pos = avio_tell(pb);
3835 int has_h264 = 0, has_video = 0;
3839 for (i = 0; i < s->nb_streams; i++) {
3840 AVStream *st = s->streams[i];
3841 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
3843 if (st->codec->codec_id == AV_CODEC_ID_H264)
3847 avio_wb32(pb, 0); /* size */
3848 ffio_wfourcc(pb, "ftyp");
3850 if (mov->major_brand && strlen(mov->major_brand) >= 4)
3851 ffio_wfourcc(pb, mov->major_brand);
3852 else if (mov->mode == MODE_3GP) {
3853 ffio_wfourcc(pb, has_h264 ? "3gp6" : "3gp4");
3854 minor = has_h264 ? 0x100 : 0x200;
3855 } else if (mov->mode & MODE_3G2) {
3856 ffio_wfourcc(pb, has_h264 ? "3g2b" : "3g2a");
3857 minor = has_h264 ? 0x20000 : 0x10000;
3858 } else if (mov->mode == MODE_PSP)
3859 ffio_wfourcc(pb, "MSNV");
3860 else if (mov->mode == MODE_MP4 && mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)
3861 ffio_wfourcc(pb, "iso5"); // Required when using default-base-is-moof
3862 else if (mov->mode == MODE_MP4)
3863 ffio_wfourcc(pb, "isom");
3864 else if (mov->mode == MODE_IPOD)
3865 ffio_wfourcc(pb, has_video ? "M4V ":"M4A ");
3866 else if (mov->mode == MODE_ISM)
3867 ffio_wfourcc(pb, "isml");
3868 else if (mov->mode == MODE_F4V)
3869 ffio_wfourcc(pb, "f4v ");
3871 ffio_wfourcc(pb, "qt ");
3873 avio_wb32(pb, minor);
3875 if (mov->mode == MODE_MOV)
3876 ffio_wfourcc(pb, "qt ");
3877 else if (mov->mode == MODE_ISM) {
3878 ffio_wfourcc(pb, "piff");
3879 } else if (!(mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)) {
3880 ffio_wfourcc(pb, "isom");
3881 ffio_wfourcc(pb, "iso2");
3883 ffio_wfourcc(pb, "avc1");
3886 // We add tfdt atoms when fragmenting, signal this with the iso6 compatible
3887 // brand. This is compatible with users that don't understand tfdt.
3888 if (mov->flags & FF_MOV_FLAG_FRAGMENT && mov->mode != MODE_ISM)
3889 ffio_wfourcc(pb, "iso6");
3891 if (mov->mode == MODE_3GP)
3892 ffio_wfourcc(pb, has_h264 ? "3gp6":"3gp4");
3893 else if (mov->mode & MODE_3G2)
3894 ffio_wfourcc(pb, has_h264 ? "3g2b":"3g2a");
3895 else if (mov->mode == MODE_PSP)
3896 ffio_wfourcc(pb, "MSNV");
3897 else if (mov->mode == MODE_MP4)
3898 ffio_wfourcc(pb, "mp41");
3900 if (mov->flags & FF_MOV_FLAG_DASH && mov->flags & FF_MOV_FLAG_FASTSTART)
3901 ffio_wfourcc(pb, "dash");
3903 return update_size(pb, pos);
3906 static void mov_write_uuidprof_tag(AVIOContext *pb, AVFormatContext *s)
3908 AVStream *video_st = s->streams[0];
3909 AVCodecContext *video_codec = s->streams[0]->codec;
3910 AVCodecContext *audio_codec = s->streams[1]->codec;
3911 int audio_rate = audio_codec->sample_rate;
3912 // TODO: should be avg_frame_rate
3913 int frame_rate = ((video_st->time_base.den) * (0x10000)) / (video_st->time_base.num);
3914 int audio_kbitrate = audio_codec->bit_rate / 1000;
3915 int video_kbitrate = FFMIN(video_codec->bit_rate / 1000, 800 - audio_kbitrate);
3917 avio_wb32(pb, 0x94); /* size */
3918 ffio_wfourcc(pb, "uuid");
3919 ffio_wfourcc(pb, "PROF");
3921 avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
3922 avio_wb32(pb, 0xbb88695c);
3923 avio_wb32(pb, 0xfac9c740);
3925 avio_wb32(pb, 0x0); /* ? */
3926 avio_wb32(pb, 0x3); /* 3 sections ? */
3928 avio_wb32(pb, 0x14); /* size */
3929 ffio_wfourcc(pb, "FPRF");
3930 avio_wb32(pb, 0x0); /* ? */
3931 avio_wb32(pb, 0x0); /* ? */
3932 avio_wb32(pb, 0x0); /* ? */
3934 avio_wb32(pb, 0x2c); /* size */
3935 ffio_wfourcc(pb, "APRF"); /* audio */
3937 avio_wb32(pb, 0x2); /* TrackID */
3938 ffio_wfourcc(pb, "mp4a");
3939 avio_wb32(pb, 0x20f);
3941 avio_wb32(pb, audio_kbitrate);
3942 avio_wb32(pb, audio_kbitrate);
3943 avio_wb32(pb, audio_rate);
3944 avio_wb32(pb, audio_codec->channels);
3946 avio_wb32(pb, 0x34); /* size */
3947 ffio_wfourcc(pb, "VPRF"); /* video */
3949 avio_wb32(pb, 0x1); /* TrackID */
3950 if (video_codec->codec_id == AV_CODEC_ID_H264) {
3951 ffio_wfourcc(pb, "avc1");
3952 avio_wb16(pb, 0x014D);
3953 avio_wb16(pb, 0x0015);
3955 ffio_wfourcc(pb, "mp4v");
3956 avio_wb16(pb, 0x0000);
3957 avio_wb16(pb, 0x0103);
3960 avio_wb32(pb, video_kbitrate);
3961 avio_wb32(pb, video_kbitrate);
3962 avio_wb32(pb, frame_rate);
3963 avio_wb32(pb, frame_rate);
3964 avio_wb16(pb, video_codec->width);
3965 avio_wb16(pb, video_codec->height);
3966 avio_wb32(pb, 0x010001); /* ? */
3969 static int mov_write_identification(AVIOContext *pb, AVFormatContext *s)
3971 MOVMuxContext *mov = s->priv_data;
3974 mov_write_ftyp_tag(pb,s);
3975 if (mov->mode == MODE_PSP) {
3976 int video_streams_nb = 0, audio_streams_nb = 0, other_streams_nb = 0;
3977 for (i = 0; i < s->nb_streams; i++) {
3978 AVStream *st = s->streams[i];
3979 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
3981 else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
3987 if (video_streams_nb != 1 || audio_streams_nb != 1 || other_streams_nb) {
3988 av_log(s, AV_LOG_ERROR, "PSP mode need one video and one audio stream\n");
3989 return AVERROR(EINVAL);
3991 mov_write_uuidprof_tag(pb, s);
3996 static int mov_parse_mpeg2_frame(AVPacket *pkt, uint32_t *flags)
3999 int i, closed_gop = 0;
4001 for (i = 0; i < pkt->size - 4; i++) {
4002 c = (c << 8) + pkt->data[i];
4003 if (c == 0x1b8) { // gop
4004 closed_gop = pkt->data[i + 4] >> 6 & 0x01;
4005 } else if (c == 0x100) { // pic
4006 int temp_ref = (pkt->data[i + 1] << 2) | (pkt->data[i + 2] >> 6);
4007 if (!temp_ref || closed_gop) // I picture is not reordered
4008 *flags = MOV_SYNC_SAMPLE;
4010 *flags = MOV_PARTIAL_SYNC_SAMPLE;
4017 static void mov_parse_vc1_frame(AVPacket *pkt, MOVTrack *trk)
4019 const uint8_t *start, *next, *end = pkt->data + pkt->size;
4020 int seq = 0, entry = 0;
4021 int key = pkt->flags & AV_PKT_FLAG_KEY;
4022 start = find_next_marker(pkt->data, end);
4023 for (next = start; next < end; start = next) {
4024 next = find_next_marker(start + 4, end);
4025 switch (AV_RB32(start)) {
4026 case VC1_CODE_SEQHDR:
4029 case VC1_CODE_ENTRYPOINT:
4032 case VC1_CODE_SLICE:
4033 trk->vc1_info.slices = 1;
4037 if (!trk->entry && trk->vc1_info.first_packet_seen)
4038 trk->vc1_info.first_frag_written = 1;
4039 if (!trk->entry && !trk->vc1_info.first_frag_written) {
4040 /* First packet in first fragment */
4041 trk->vc1_info.first_packet_seq = seq;
4042 trk->vc1_info.first_packet_entry = entry;
4043 trk->vc1_info.first_packet_seen = 1;
4044 } else if ((seq && !trk->vc1_info.packet_seq) ||
4045 (entry && !trk->vc1_info.packet_entry)) {
4047 for (i = 0; i < trk->entry; i++)
4048 trk->cluster[i].flags &= ~MOV_SYNC_SAMPLE;
4049 trk->has_keyframes = 0;
4051 trk->vc1_info.packet_seq = 1;
4053 trk->vc1_info.packet_entry = 1;
4054 if (!trk->vc1_info.first_frag_written) {
4055 /* First fragment */
4056 if ((!seq || trk->vc1_info.first_packet_seq) &&
4057 (!entry || trk->vc1_info.first_packet_entry)) {
4058 /* First packet had the same headers as this one, readd the
4059 * sync sample flag. */
4060 trk->cluster[0].flags |= MOV_SYNC_SAMPLE;
4061 trk->has_keyframes = 1;
4065 if (trk->vc1_info.packet_seq && trk->vc1_info.packet_entry)
4067 else if (trk->vc1_info.packet_seq)
4069 else if (trk->vc1_info.packet_entry)
4072 trk->cluster[trk->entry].flags |= MOV_SYNC_SAMPLE;
4073 trk->has_keyframes++;
4077 static int mov_flush_fragment_interleaving(AVFormatContext *s, MOVTrack *track)
4079 MOVMuxContext *mov = s->priv_data;
4084 if (!track->mdat_buf)
4086 if (!mov->mdat_buf) {
4087 if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0)
4090 buf_size = avio_close_dyn_buf(track->mdat_buf, &buf);
4091 track->mdat_buf = NULL;
4093 offset = avio_tell(mov->mdat_buf);
4094 avio_write(mov->mdat_buf, buf, buf_size);
4097 for (i = track->entries_flushed; i < track->entry; i++)
4098 track->cluster[i].pos += offset;
4099 track->entries_flushed = track->entry;
4103 static int mov_flush_fragment(AVFormatContext *s)
4105 MOVMuxContext *mov = s->priv_data;
4106 int i, first_track = -1;
4107 int64_t mdat_size = 0;
4110 if (!(mov->flags & FF_MOV_FLAG_FRAGMENT))
4113 for (i = 0; i < mov->nb_streams; i++) {
4114 MOVTrack *track = &mov->tracks[i];
4115 if (track->entry <= 1)
4117 // Sample durations are calculated as the diff of dts values,
4118 // but for the last sample in a fragment, we don't know the dts
4119 // of the first sample in the next fragment, so we have to rely
4120 // on what was set as duration in the AVPacket. Not all callers
4121 // set this though, so we might want to replace it with an
4122 // estimate if it currently is zero.
4123 if (get_cluster_duration(track, track->entry - 1) != 0)
4125 // Use the duration (i.e. dts diff) of the second last sample for
4126 // the last one. This is a wild guess (and fatal if it turns out
4127 // to be too long), but probably the best we can do - having a zero
4128 // duration is bad as well.
4129 track->track_duration += get_cluster_duration(track, track->entry - 2);
4130 track->end_pts += get_cluster_duration(track, track->entry - 2);
4131 if (!mov->missing_duration_warned) {
4132 av_log(s, AV_LOG_WARNING,
4133 "Estimating the duration of the last packet in a "
4134 "fragment, consider setting the duration field in "
4135 "AVPacket instead.\n");
4136 mov->missing_duration_warned = 1;
4140 if (!mov->moov_written) {
4141 int64_t pos = avio_tell(s->pb);
4143 int buf_size, moov_size;
4145 for (i = 0; i < mov->nb_streams; i++)
4146 if (!mov->tracks[i].entry)
4148 /* Don't write the initial moov unless all tracks have data */
4149 if (i < mov->nb_streams)
4152 moov_size = get_moov_size(s);
4153 for (i = 0; i < mov->nb_streams; i++)
4154 mov->tracks[i].data_offset = pos + moov_size + 8;
4156 if (mov->flags & FF_MOV_FLAG_DELAY_MOOV)
4157 mov_write_identification(s->pb, s);
4158 if ((ret = mov_write_moov_tag(s->pb, mov, s)) < 0)
4161 if (mov->flags & FF_MOV_FLAG_DELAY_MOOV) {
4162 if (mov->flags & FF_MOV_FLAG_FASTSTART)
4163 mov->reserved_moov_pos = avio_tell(s->pb);
4165 mov->moov_written = 1;
4169 buf_size = avio_close_dyn_buf(mov->mdat_buf, &buf);
4170 mov->mdat_buf = NULL;
4171 avio_wb32(s->pb, buf_size + 8);
4172 ffio_wfourcc(s->pb, "mdat");
4173 avio_write(s->pb, buf, buf_size);
4176 mov->moov_written = 1;
4178 for (i = 0; i < mov->nb_streams; i++) {
4179 if (mov->tracks[i].entry)
4180 mov->tracks[i].frag_start += mov->tracks[i].start_dts +
4181 mov->tracks[i].track_duration -
4182 mov->tracks[i].cluster[0].dts;
4183 mov->tracks[i].entry = 0;
4189 if (mov->frag_interleave) {
4190 for (i = 0; i < mov->nb_streams; i++) {
4191 MOVTrack *track = &mov->tracks[i];
4193 if ((ret = mov_flush_fragment_interleaving(s, track)) < 0)
4199 mdat_size = avio_tell(mov->mdat_buf);
4202 for (i = 0; i < mov->nb_streams; i++) {
4203 MOVTrack *track = &mov->tracks[i];
4204 if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF || mov->frag_interleave)
4205 track->data_offset = 0;
4207 track->data_offset = mdat_size;
4210 if (track->mdat_buf)
4211 mdat_size += avio_tell(track->mdat_buf);
4212 if (first_track < 0)
4219 for (i = 0; i < mov->nb_streams; i++) {
4220 MOVTrack *track = &mov->tracks[i];
4221 int buf_size, write_moof = 1, moof_tracks = -1;
4223 int64_t duration = 0;
4226 duration = track->start_dts + track->track_duration -
4227 track->cluster[0].dts;
4228 if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF) {
4229 if (!track->mdat_buf)
4231 mdat_size = avio_tell(track->mdat_buf);
4234 write_moof = i == first_track;
4240 mov_write_moof_tag(s->pb, mov, moof_tracks, mdat_size);
4243 avio_wb32(s->pb, mdat_size + 8);
4244 ffio_wfourcc(s->pb, "mdat");
4248 track->frag_start += duration;
4250 track->entries_flushed = 0;
4251 if (!mov->frag_interleave) {
4252 if (!track->mdat_buf)
4254 buf_size = avio_close_dyn_buf(track->mdat_buf, &buf);
4255 track->mdat_buf = NULL;
4259 buf_size = avio_close_dyn_buf(mov->mdat_buf, &buf);
4260 mov->mdat_buf = NULL;
4263 avio_write(s->pb, buf, buf_size);
4273 static int mov_auto_flush_fragment(AVFormatContext *s)
4275 MOVMuxContext *mov = s->priv_data;
4276 int had_moov = mov->moov_written;
4277 int ret = mov_flush_fragment(s);
4280 // If using delay_moov, the first flush only wrote the moov,
4281 // not the actual moof+mdat pair, thus flush once again.
4282 if (!had_moov && mov->flags & FF_MOV_FLAG_DELAY_MOOV)
4283 ret = mov_flush_fragment(s);
4287 int ff_mov_write_packet(AVFormatContext *s, AVPacket *pkt)
4289 MOVMuxContext *mov = s->priv_data;
4290 AVIOContext *pb = s->pb;
4291 MOVTrack *trk = &mov->tracks[pkt->stream_index];
4292 AVCodecContext *enc = trk->enc;
4293 unsigned int samples_in_chunk = 0;
4294 int size = pkt->size, ret = 0;
4295 uint8_t *reformatted_data = NULL;
4298 int64_t duration = pkt->dts - trk->cluster[trk->entry - 1].dts;
4299 if (duration < 0 || duration > INT_MAX) {
4300 av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" / timestamp: %"PRId64" is out of range for mov/mp4 format\n",
4304 pkt->dts = trk->cluster[trk->entry - 1].dts + 1;
4305 pkt->pts = AV_NOPTS_VALUE;
4307 if (pkt->duration < 0) {
4308 av_log(s, AV_LOG_ERROR, "Application provided duration: %d is invalid\n", pkt->duration);
4309 return AVERROR(EINVAL);
4312 if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
4314 if (mov->moov_written || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
4315 if (mov->frag_interleave && mov->fragments > 0) {
4316 if (trk->entry - trk->entries_flushed >= mov->frag_interleave) {
4317 if ((ret = mov_flush_fragment_interleaving(s, trk)) < 0)
4322 if (!trk->mdat_buf) {
4323 if ((ret = avio_open_dyn_buf(&trk->mdat_buf)) < 0)
4328 if (!mov->mdat_buf) {
4329 if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0)
4336 if (enc->codec_id == AV_CODEC_ID_AMR_NB) {
4337 /* We must find out how many AMR blocks there are in one packet */
4338 static uint16_t packed_size[16] =
4339 {13, 14, 16, 18, 20, 21, 27, 32, 6, 0, 0, 0, 0, 0, 0, 1};
4342 while (len < size && samples_in_chunk < 100) {
4343 len += packed_size[(pkt->data[len] >> 3) & 0x0F];
4346 if (samples_in_chunk > 1) {
4347 av_log(s, AV_LOG_ERROR, "fatal error, input is not a single packet, implement a AVParser for it\n");
4350 } else if (enc->codec_id == AV_CODEC_ID_ADPCM_MS ||
4351 enc->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) {
4352 samples_in_chunk = enc->frame_size;
4353 } else if (trk->sample_size)
4354 samples_in_chunk = size / trk->sample_size;
4356 samples_in_chunk = 1;
4358 /* copy extradata if it exists */
4359 if (trk->vos_len == 0 && enc->extradata_size > 0 &&
4360 !TAG_IS_AVCI(trk->tag) &&
4361 (enc->codec_id != AV_CODEC_ID_DNXHD)) {
4362 trk->vos_len = enc->extradata_size;
4363 trk->vos_data = av_malloc(trk->vos_len);
4364 if (!trk->vos_data) {
4365 ret = AVERROR(ENOMEM);
4368 memcpy(trk->vos_data, enc->extradata, trk->vos_len);
4371 if (enc->codec_id == AV_CODEC_ID_AAC && pkt->size > 2 &&
4372 (AV_RB16(pkt->data) & 0xfff0) == 0xfff0) {
4373 if (!s->streams[pkt->stream_index]->nb_frames) {
4374 av_log(s, AV_LOG_ERROR, "Malformed AAC bitstream detected: "
4375 "use the audio bitstream filter 'aac_adtstoasc' to fix it "
4376 "('-bsf:a aac_adtstoasc' option with ffmpeg)\n");
4379 av_log(s, AV_LOG_WARNING, "aac bitstream error\n");
4381 if (enc->codec_id == AV_CODEC_ID_H264 && trk->vos_len > 0 && *(uint8_t *)trk->vos_data != 1 && !TAG_IS_AVCI(trk->tag)) {
4382 /* from x264 or from bytestream h264 */
4383 /* nal reformating needed */
4384 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
4385 ff_avc_parse_nal_units_buf(pkt->data, &reformatted_data,
4387 avio_write(pb, reformatted_data, size);
4389 size = ff_avc_parse_nal_units(pb, pkt->data, pkt->size);
4391 } else if (enc->codec_id == AV_CODEC_ID_HEVC && trk->vos_len > 6 &&
4392 (AV_RB24(trk->vos_data) == 1 || AV_RB32(trk->vos_data) == 1)) {
4393 /* extradata is Annex B, assume the bitstream is too and convert it */
4394 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
4395 ff_hevc_annexb2mp4_buf(pkt->data, &reformatted_data, &size, 0, NULL);
4396 avio_write(pb, reformatted_data, size);
4398 size = ff_hevc_annexb2mp4(pb, pkt->data, pkt->size, 0, NULL);
4400 #if CONFIG_AC3_PARSER
4401 } else if (enc->codec_id == AV_CODEC_ID_EAC3) {
4402 size = handle_eac3(mov, pkt, trk);
4407 avio_write(pb, pkt->data, size);
4410 avio_write(pb, pkt->data, size);
4413 if ((enc->codec_id == AV_CODEC_ID_DNXHD ||
4414 enc->codec_id == AV_CODEC_ID_AC3) && !trk->vos_len) {
4415 /* copy frame to create needed atoms */
4416 trk->vos_len = size;
4417 trk->vos_data = av_malloc(size);
4418 if (!trk->vos_data) {
4419 ret = AVERROR(ENOMEM);
4422 memcpy(trk->vos_data, pkt->data, size);
4425 if (trk->entry >= trk->cluster_capacity) {
4426 unsigned new_capacity = 2 * (trk->entry + MOV_INDEX_CLUSTER_SIZE);
4427 if (av_reallocp_array(&trk->cluster, new_capacity,
4428 sizeof(*trk->cluster))) {
4429 ret = AVERROR(ENOMEM);
4432 trk->cluster_capacity = new_capacity;
4435 trk->cluster[trk->entry].pos = avio_tell(pb) - size;
4436 trk->cluster[trk->entry].samples_in_chunk = samples_in_chunk;
4437 trk->cluster[trk->entry].chunkNum = 0;
4438 trk->cluster[trk->entry].size = size;
4439 trk->cluster[trk->entry].entries = samples_in_chunk;
4440 trk->cluster[trk->entry].dts = pkt->dts;
4441 if (!trk->entry && trk->start_dts != AV_NOPTS_VALUE) {
4442 if (!trk->frag_discont) {
4443 /* First packet of a new fragment. We already wrote the duration
4444 * of the last packet of the previous fragment based on track_duration,
4445 * which might not exactly match our dts. Therefore adjust the dts
4446 * of this packet to be what the previous packets duration implies. */
4447 trk->cluster[trk->entry].dts = trk->start_dts + trk->track_duration;
4448 /* We also may have written the pts and the corresponding duration
4449 * in sidx/tfrf/tfxd tags; make sure the sidx pts and duration match up with
4450 * the next fragment. This means the cts of the first sample must
4451 * be the same in all fragments. */
4452 if ((mov->flags & FF_MOV_FLAG_DASH && !(mov->flags & FF_MOV_FLAG_FASTSTART)) ||
4453 mov->mode == MODE_ISM)
4454 pkt->pts = pkt->dts + trk->end_pts - trk->cluster[trk->entry].dts;
4456 /* New fragment, but discontinuous from previous fragments.
4457 * Pretend the duration sum of the earlier fragments is
4458 * pkt->dts - trk->start_dts. */
4459 trk->frag_start = pkt->dts - trk->start_dts;
4460 trk->end_pts = AV_NOPTS_VALUE;
4461 trk->frag_discont = 0;
4465 if (!trk->entry && trk->start_dts == AV_NOPTS_VALUE && !mov->use_editlist &&
4466 s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO) {
4467 /* Not using edit lists and shifting the first track to start from zero.
4468 * If the other streams start from a later timestamp, we won't be able
4469 * to signal the difference in starting time without an edit list.
4470 * Thus move the timestamp for this first sample to 0, increasing
4471 * its duration instead. */
4472 trk->cluster[trk->entry].dts = trk->start_dts = 0;
4474 if (trk->start_dts == AV_NOPTS_VALUE) {
4475 trk->start_dts = pkt->dts;
4476 if (trk->frag_discont) {
4477 /* Pretend the whole stream started at dts=0, with earlier fragments
4478 * already written, with a duration summing up to pkt->dts. */
4479 trk->frag_start = pkt->dts;
4481 trk->frag_discont = 0;
4482 } else if (pkt->dts && mov->moov_written)
4483 av_log(s, AV_LOG_WARNING,
4484 "Track %d starts with a nonzero dts %"PRId64", while the moov "
4485 "already has been written. Set the delay_moov flag to handle "
4487 pkt->stream_index, pkt->dts);
4489 trk->track_duration = pkt->dts - trk->start_dts + pkt->duration;
4490 trk->last_sample_is_subtitle_end = 0;
4492 if (pkt->pts == AV_NOPTS_VALUE) {
4493 av_log(s, AV_LOG_WARNING, "pts has no value\n");
4494 pkt->pts = pkt->dts;
4496 if (pkt->dts != pkt->pts)
4497 trk->flags |= MOV_TRACK_CTTS;
4498 trk->cluster[trk->entry].cts = pkt->pts - pkt->dts;
4499 trk->cluster[trk->entry].flags = 0;
4500 if (trk->start_cts == AV_NOPTS_VALUE)
4501 trk->start_cts = pkt->pts - pkt->dts;
4502 if (trk->end_pts == AV_NOPTS_VALUE)
4503 trk->end_pts = trk->cluster[trk->entry].dts +
4504 trk->cluster[trk->entry].cts + pkt->duration;
4506 trk->end_pts = FFMAX(trk->end_pts, trk->cluster[trk->entry].dts +
4507 trk->cluster[trk->entry].cts +
4510 if (enc->codec_id == AV_CODEC_ID_VC1) {
4511 mov_parse_vc1_frame(pkt, trk);
4512 } else if (pkt->flags & AV_PKT_FLAG_KEY) {
4513 if (mov->mode == MODE_MOV && enc->codec_id == AV_CODEC_ID_MPEG2VIDEO &&
4514 trk->entry > 0) { // force sync sample for the first key frame
4515 mov_parse_mpeg2_frame(pkt, &trk->cluster[trk->entry].flags);
4516 if (trk->cluster[trk->entry].flags & MOV_PARTIAL_SYNC_SAMPLE)
4517 trk->flags |= MOV_TRACK_STPS;
4519 trk->cluster[trk->entry].flags = MOV_SYNC_SAMPLE;
4521 if (trk->cluster[trk->entry].flags & MOV_SYNC_SAMPLE)
4522 trk->has_keyframes++;
4525 trk->sample_count += samples_in_chunk;
4526 mov->mdat_size += size;
4528 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams)
4529 ff_mov_add_hinted_packet(s, pkt, trk->hint_track, trk->entry,
4530 reformatted_data, size);
4535 av_free(reformatted_data);
4539 static int mov_write_single_packet(AVFormatContext *s, AVPacket *pkt)
4541 MOVMuxContext *mov = s->priv_data;
4542 MOVTrack *trk = &mov->tracks[pkt->stream_index];
4543 AVCodecContext *enc = trk->enc;
4544 int64_t frag_duration = 0;
4545 int size = pkt->size;
4548 return 0; /* Discard 0 sized packets */
4550 if (mov->flags & FF_MOV_FLAG_FRAG_DISCONT) {
4552 for (i = 0; i < s->nb_streams; i++)
4553 mov->tracks[i].frag_discont = 1;
4554 mov->flags &= ~FF_MOV_FLAG_FRAG_DISCONT;
4557 if (trk->entry && pkt->stream_index < s->nb_streams)
4558 frag_duration = av_rescale_q(pkt->dts - trk->cluster[0].dts,
4559 s->streams[pkt->stream_index]->time_base,
4561 if ((mov->max_fragment_duration &&
4562 frag_duration >= mov->max_fragment_duration) ||
4563 (mov->max_fragment_size && mov->mdat_size + size >= mov->max_fragment_size) ||
4564 (mov->flags & FF_MOV_FLAG_FRAG_KEYFRAME &&
4565 enc->codec_type == AVMEDIA_TYPE_VIDEO &&
4566 trk->entry && pkt->flags & AV_PKT_FLAG_KEY)) {
4567 if (frag_duration >= mov->min_fragment_duration) {
4568 // Set the duration of this track to line up with the next
4569 // sample in this track. This avoids relying on AVPacket
4570 // duration, but only helps for this particular track, not
4571 // for the other ones that are flushed at the same time.
4572 trk->track_duration = pkt->dts - trk->start_dts;
4573 trk->end_pts = pkt->pts;
4574 mov_auto_flush_fragment(s);
4578 return ff_mov_write_packet(s, pkt);
4581 static int mov_write_subtitle_end_packet(AVFormatContext *s,
4585 uint8_t data[2] = {0};
4588 av_init_packet(&end);
4589 end.size = sizeof(data);
4594 end.stream_index = stream_index;
4596 ret = mov_write_single_packet(s, &end);
4597 av_free_packet(&end);
4602 static int mov_write_packet(AVFormatContext *s, AVPacket *pkt)
4605 mov_flush_fragment(s);
4609 MOVMuxContext *mov = s->priv_data;
4611 if (!pkt->size) return 0; /* Discard 0 sized packets */
4614 * Subtitles require special handling.
4616 * 1) For full complaince, every track must have a sample at
4617 * dts == 0, which is rarely true for subtitles. So, as soon
4618 * as we see any packet with dts > 0, write an empty subtitle
4619 * at dts == 0 for any subtitle track with no samples in it.
4621 * 2) For each subtitle track, check if the current packet's
4622 * dts is past the duration of the last subtitle sample. If
4623 * so, we now need to write an end sample for that subtitle.
4625 * This must be done conditionally to allow for subtitles that
4626 * immediately replace each other, in which case an end sample
4627 * is not needed, and is, in fact, actively harmful.
4629 * 3) See mov_write_trailer for how the final end sample is
4632 for (i = 0; i < mov->nb_streams; i++) {
4633 MOVTrack *trk = &mov->tracks[i];
4636 if (trk->enc->codec_id == AV_CODEC_ID_MOV_TEXT &&
4637 trk->track_duration < pkt->dts &&
4638 (trk->entry == 0 || !trk->last_sample_is_subtitle_end)) {
4639 ret = mov_write_subtitle_end_packet(s, i, trk->track_duration);
4640 if (ret < 0) return ret;
4641 trk->last_sample_is_subtitle_end = 1;
4645 return mov_write_single_packet(s, pkt);
4649 // QuickTime chapters involve an additional text track with the chapter names
4650 // as samples, and a tref pointing from the other tracks to the chapter one.
4651 static int mov_create_chapter_track(AVFormatContext *s, int tracknum)
4655 MOVMuxContext *mov = s->priv_data;
4656 MOVTrack *track = &mov->tracks[tracknum];
4657 AVPacket pkt = { .stream_index = tracknum, .flags = AV_PKT_FLAG_KEY };
4660 track->mode = mov->mode;
4661 track->tag = MKTAG('t','e','x','t');
4662 track->timescale = MOV_TIMESCALE;
4663 track->enc = avcodec_alloc_context3(NULL);
4665 return AVERROR(ENOMEM);
4666 track->enc->codec_type = AVMEDIA_TYPE_SUBTITLE;
4668 // These properties are required to make QT recognize the chapter track
4669 uint8_t chapter_properties[43] = { 0, 0, 0, 0, 0, 0, 0, 1, };
4670 if (ff_alloc_extradata(track->enc, sizeof(chapter_properties)))
4671 return AVERROR(ENOMEM);
4672 memcpy(track->enc->extradata, chapter_properties, sizeof(chapter_properties));
4674 if (avio_open_dyn_buf(&pb) >= 0) {
4678 /* Stub header (usually for Quicktime chapter track) */
4680 avio_wb32(pb, 0x01); // displayFlags
4681 avio_w8(pb, 0x00); // horizontal justification
4682 avio_w8(pb, 0x00); // vertical justification
4683 avio_w8(pb, 0x00); // bgColourRed
4684 avio_w8(pb, 0x00); // bgColourGreen
4685 avio_w8(pb, 0x00); // bgColourBlue
4686 avio_w8(pb, 0x00); // bgColourAlpha
4688 avio_wb16(pb, 0x00); // defTextBoxTop
4689 avio_wb16(pb, 0x00); // defTextBoxLeft
4690 avio_wb16(pb, 0x00); // defTextBoxBottom
4691 avio_wb16(pb, 0x00); // defTextBoxRight
4693 avio_wb16(pb, 0x00); // startChar
4694 avio_wb16(pb, 0x00); // endChar
4695 avio_wb16(pb, 0x01); // fontID
4696 avio_w8(pb, 0x00); // fontStyleFlags
4697 avio_w8(pb, 0x00); // fontSize
4698 avio_w8(pb, 0x00); // fgColourRed
4699 avio_w8(pb, 0x00); // fgColourGreen
4700 avio_w8(pb, 0x00); // fgColourBlue
4701 avio_w8(pb, 0x00); // fgColourAlpha
4703 avio_wb32(pb, 0x0D); // box size
4704 ffio_wfourcc(pb, "ftab"); // box atom name
4705 avio_wb16(pb, 0x01); // entry count
4707 avio_wb16(pb, 0x01); // font ID
4708 avio_w8(pb, 0x00); // font name length
4710 if ((size = avio_close_dyn_buf(pb, &buf)) > 0) {
4711 track->enc->extradata = buf;
4712 track->enc->extradata_size = size;
4719 for (i = 0; i < s->nb_chapters; i++) {
4720 AVChapter *c = s->chapters[i];
4721 AVDictionaryEntry *t;
4723 int64_t end = av_rescale_q(c->end, c->time_base, (AVRational){1,MOV_TIMESCALE});
4724 pkt.pts = pkt.dts = av_rescale_q(c->start, c->time_base, (AVRational){1,MOV_TIMESCALE});
4725 pkt.duration = end - pkt.dts;
4727 if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
4728 const char encd[12] = {
4729 0x00, 0x00, 0x00, 0x0C,
4731 0x00, 0x00, 0x01, 0x00 };
4732 len = strlen(t->value);
4733 pkt.size = len + 2 + 12;
4734 pkt.data = av_malloc(pkt.size);
4736 return AVERROR(ENOMEM);
4737 AV_WB16(pkt.data, len);
4738 memcpy(pkt.data + 2, t->value, len);
4739 memcpy(pkt.data + len + 2, encd, sizeof(encd));
4740 ff_mov_write_packet(s, &pkt);
4741 av_freep(&pkt.data);
4748 static int mov_create_timecode_track(AVFormatContext *s, int index, int src_index, const char *tcstr)
4751 MOVMuxContext *mov = s->priv_data;
4752 MOVTrack *track = &mov->tracks[index];
4753 AVStream *src_st = s->streams[src_index];
4755 AVPacket pkt = {.stream_index = index, .flags = AV_PKT_FLAG_KEY, .size = 4};
4756 AVRational rate = find_fps(s, src_st);
4758 /* compute the frame number */
4759 ret = av_timecode_init_from_string(&tc, rate, tcstr, s);
4763 /* tmcd track based on video stream */
4764 track->mode = mov->mode;
4765 track->tag = MKTAG('t','m','c','d');
4766 track->src_track = src_index;
4767 track->timescale = mov->tracks[src_index].timescale;
4768 if (tc.flags & AV_TIMECODE_FLAG_DROPFRAME)
4769 track->timecode_flags |= MOV_TIMECODE_FLAG_DROPFRAME;
4771 /* set st to src_st for metadata access*/
4774 /* encode context: tmcd data stream */
4775 track->enc = avcodec_alloc_context3(NULL);
4777 return AVERROR(ENOMEM);
4778 track->enc->codec_type = AVMEDIA_TYPE_DATA;
4779 track->enc->codec_tag = track->tag;
4780 track->enc->time_base = av_inv_q(rate);
4782 /* the tmcd track just contains one packet with the frame number */
4783 pkt.data = av_malloc(pkt.size);
4785 return AVERROR(ENOMEM);
4786 AV_WB32(pkt.data, tc.start);
4787 ret = ff_mov_write_packet(s, &pkt);
4793 * st->disposition controls the "enabled" flag in the tkhd tag.
4794 * QuickTime will not play a track if it is not enabled. So make sure
4795 * that one track of each type (audio, video, subtitle) is enabled.
4797 * Subtitles are special. For audio and video, setting "enabled" also
4798 * makes the track "default" (i.e. it is rendered when played). For
4799 * subtitles, an "enabled" subtitle is not rendered by default, but
4800 * if no subtitle is enabled, the subtitle menu in QuickTime will be
4803 static void enable_tracks(AVFormatContext *s)
4805 MOVMuxContext *mov = s->priv_data;
4807 int enabled[AVMEDIA_TYPE_NB];
4808 int first[AVMEDIA_TYPE_NB];
4810 for (i = 0; i < AVMEDIA_TYPE_NB; i++) {
4815 for (i = 0; i < s->nb_streams; i++) {
4816 AVStream *st = s->streams[i];
4818 if (st->codec->codec_type <= AVMEDIA_TYPE_UNKNOWN ||
4819 st->codec->codec_type >= AVMEDIA_TYPE_NB)
4822 if (first[st->codec->codec_type] < 0)
4823 first[st->codec->codec_type] = i;
4824 if (st->disposition & AV_DISPOSITION_DEFAULT) {
4825 mov->tracks[i].flags |= MOV_TRACK_ENABLED;
4826 enabled[st->codec->codec_type]++;
4830 for (i = 0; i < AVMEDIA_TYPE_NB; i++) {
4832 case AVMEDIA_TYPE_VIDEO:
4833 case AVMEDIA_TYPE_AUDIO:
4834 case AVMEDIA_TYPE_SUBTITLE:
4836 mov->per_stream_grouping = 1;
4837 if (!enabled[i] && first[i] >= 0)
4838 mov->tracks[first[i]].flags |= MOV_TRACK_ENABLED;
4844 static void mov_free(AVFormatContext *s)
4846 MOVMuxContext *mov = s->priv_data;
4849 if (mov->chapter_track) {
4850 if (mov->tracks[mov->chapter_track].enc)
4851 av_freep(&mov->tracks[mov->chapter_track].enc->extradata);
4852 av_freep(&mov->tracks[mov->chapter_track].enc);
4855 for (i = 0; i < mov->nb_streams; i++) {
4856 if (mov->tracks[i].tag == MKTAG('r','t','p',' '))
4857 ff_mov_close_hinting(&mov->tracks[i]);
4858 else if (mov->tracks[i].tag == MKTAG('t','m','c','d') && mov->nb_meta_tmcd)
4859 av_freep(&mov->tracks[i].enc);
4860 av_freep(&mov->tracks[i].cluster);
4861 av_freep(&mov->tracks[i].frag_info);
4863 if (mov->tracks[i].vos_len)
4864 av_freep(&mov->tracks[i].vos_data);
4867 av_freep(&mov->tracks);
4870 static uint32_t rgb_to_yuv(uint32_t rgb)
4875 r = (rgb >> 16) & 0xFF;
4876 g = (rgb >> 8) & 0xFF;
4879 y = av_clip_uint8( 16. + 0.257 * r + 0.504 * g + 0.098 * b);
4880 cb = av_clip_uint8(128. - 0.148 * r - 0.291 * g + 0.439 * b);
4881 cr = av_clip_uint8(128. + 0.439 * r - 0.368 * g - 0.071 * b);
4883 return (y << 16) | (cr << 8) | cb;
4886 static int mov_create_dvd_sub_decoder_specific_info(MOVTrack *track,
4889 int i, width = 720, height = 480;
4890 int have_palette = 0, have_size = 0;
4891 uint32_t palette[16];
4892 char *cur = st->codec->extradata;
4894 while (cur && *cur) {
4895 if (strncmp("palette:", cur, 8) == 0) {
4897 count = sscanf(cur + 8,
4898 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
4899 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
4900 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
4901 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32"",
4902 &palette[ 0], &palette[ 1], &palette[ 2], &palette[ 3],
4903 &palette[ 4], &palette[ 5], &palette[ 6], &palette[ 7],
4904 &palette[ 8], &palette[ 9], &palette[10], &palette[11],
4905 &palette[12], &palette[13], &palette[14], &palette[15]);
4907 for (i = 0; i < count; i++) {
4908 palette[i] = rgb_to_yuv(palette[i]);
4911 } else if (!strncmp("size:", cur, 5)) {
4912 sscanf(cur + 5, "%dx%d", &width, &height);
4915 if (have_palette && have_size)
4917 cur += strcspn(cur, "\n\r");
4918 cur += strspn(cur, "\n\r");
4921 track->vos_data = av_malloc(16*4);
4922 if (!track->vos_data)
4923 return AVERROR(ENOMEM);
4924 for (i = 0; i < 16; i++) {
4925 AV_WB32(track->vos_data + i * 4, palette[i]);
4927 track->vos_len = 16 * 4;
4929 st->codec->width = width;
4930 st->codec->height = track->height = height;
4935 static int mov_write_header(AVFormatContext *s)
4937 AVIOContext *pb = s->pb;
4938 MOVMuxContext *mov = s->priv_data;
4939 AVDictionaryEntry *t, *global_tcr = av_dict_get(s->metadata, "timecode", NULL, 0);
4940 int i, ret, hint_track = 0, tmcd_track = 0;
4944 /* Default mode == MP4 */
4945 mov->mode = MODE_MP4;
4948 if (!strcmp("3gp", s->oformat->name)) mov->mode = MODE_3GP;
4949 else if (!strcmp("3g2", s->oformat->name)) mov->mode = MODE_3GP|MODE_3G2;
4950 else if (!strcmp("mov", s->oformat->name)) mov->mode = MODE_MOV;
4951 else if (!strcmp("psp", s->oformat->name)) mov->mode = MODE_PSP;
4952 else if (!strcmp("ipod",s->oformat->name)) mov->mode = MODE_IPOD;
4953 else if (!strcmp("ismv",s->oformat->name)) mov->mode = MODE_ISM;
4954 else if (!strcmp("f4v", s->oformat->name)) mov->mode = MODE_F4V;
4957 if (s->flags & AVFMT_FLAG_BITEXACT)
4960 if (mov->flags & FF_MOV_FLAG_DELAY_MOOV)
4961 mov->flags |= FF_MOV_FLAG_EMPTY_MOOV;
4963 /* Set the FRAGMENT flag if any of the fragmentation methods are
4965 if (mov->max_fragment_duration || mov->max_fragment_size ||
4966 mov->flags & (FF_MOV_FLAG_EMPTY_MOOV |
4967 FF_MOV_FLAG_FRAG_KEYFRAME |
4968 FF_MOV_FLAG_FRAG_CUSTOM))
4969 mov->flags |= FF_MOV_FLAG_FRAGMENT;
4971 /* Set other implicit flags immediately */
4972 if (mov->mode == MODE_ISM)
4973 mov->flags |= FF_MOV_FLAG_EMPTY_MOOV | FF_MOV_FLAG_SEPARATE_MOOF |
4974 FF_MOV_FLAG_FRAGMENT;
4975 if (mov->flags & FF_MOV_FLAG_DASH)
4976 mov->flags |= FF_MOV_FLAG_FRAGMENT | FF_MOV_FLAG_EMPTY_MOOV |
4977 FF_MOV_FLAG_DEFAULT_BASE_MOOF;
4979 if (mov->flags & FF_MOV_FLAG_FASTSTART) {
4980 mov->reserved_moov_size = -1;
4983 if (mov->use_editlist < 0) {
4984 mov->use_editlist = 1;
4985 if (mov->flags & FF_MOV_FLAG_FRAGMENT &&
4986 !(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
4987 // If we can avoid needing an edit list by shifting the
4988 // tracks, prefer that over (trying to) write edit lists
4989 // in fragmented output.
4990 if (s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO ||
4991 s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO)
4992 mov->use_editlist = 0;
4995 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV &&
4996 !(mov->flags & FF_MOV_FLAG_DELAY_MOOV) && mov->use_editlist)
4997 av_log(s, AV_LOG_WARNING, "No meaningful edit list will be written when using empty_moov without delay_moov\n");
4999 if (!mov->use_editlist && s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO)
5000 s->avoid_negative_ts = AVFMT_AVOID_NEG_TS_MAKE_ZERO;
5002 /* Clear the omit_tfhd_offset flag if default_base_moof is set;
5003 * if the latter is set that's enough and omit_tfhd_offset doesn't
5004 * add anything extra on top of that. */
5005 if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET &&
5006 mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)
5007 mov->flags &= ~FF_MOV_FLAG_OMIT_TFHD_OFFSET;
5009 if (mov->frag_interleave &&
5010 mov->flags & (FF_MOV_FLAG_OMIT_TFHD_OFFSET | FF_MOV_FLAG_SEPARATE_MOOF)) {
5011 av_log(s, AV_LOG_ERROR,
5012 "Sample interleaving in fragments is mutually exclusive with "
5013 "omit_tfhd_offset and separate_moof\n");
5014 return AVERROR(EINVAL);
5017 /* Non-seekable output is ok if using fragmentation. If ism_lookahead
5018 * is enabled, we don't support non-seekable output at all. */
5019 if (!s->pb->seekable &&
5020 (!(mov->flags & FF_MOV_FLAG_FRAGMENT) || mov->ism_lookahead)) {
5021 av_log(s, AV_LOG_ERROR, "muxer does not support non seekable output\n");
5022 return AVERROR(EINVAL);
5025 if (!(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
5026 if ((ret = mov_write_identification(pb, s)) < 0)
5030 mov->nb_streams = s->nb_streams;
5031 if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters)
5032 mov->chapter_track = mov->nb_streams++;
5034 if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
5035 /* Add hint tracks for each audio and video stream */
5036 hint_track = mov->nb_streams;
5037 for (i = 0; i < s->nb_streams; i++) {
5038 AVStream *st = s->streams[i];
5039 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO ||
5040 st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
5046 if (mov->mode == MODE_MOV) {
5047 tmcd_track = mov->nb_streams;
5049 /* +1 tmcd track for each video stream with a timecode */
5050 for (i = 0; i < s->nb_streams; i++) {
5051 AVStream *st = s->streams[i];
5052 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
5053 (global_tcr || av_dict_get(st->metadata, "timecode", NULL, 0)))
5054 mov->nb_meta_tmcd++;
5057 /* check if there is already a tmcd track to remux */
5058 if (mov->nb_meta_tmcd) {
5059 for (i = 0; i < s->nb_streams; i++) {
5060 AVStream *st = s->streams[i];
5061 if (st->codec->codec_tag == MKTAG('t','m','c','d')) {
5062 av_log(s, AV_LOG_WARNING, "You requested a copy of the original timecode track "
5063 "so timecode metadata are now ignored\n");
5064 mov->nb_meta_tmcd = 0;
5069 mov->nb_streams += mov->nb_meta_tmcd;
5072 // Reserve an extra stream for chapters for the case where chapters
5073 // are written in the trailer
5074 mov->tracks = av_mallocz_array((mov->nb_streams + 1), sizeof(*mov->tracks));
5076 return AVERROR(ENOMEM);
5078 for (i = 0; i < s->nb_streams; i++) {
5079 AVStream *st= s->streams[i];
5080 MOVTrack *track= &mov->tracks[i];
5081 AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0);
5084 track->enc = st->codec;
5085 track->language = ff_mov_iso639_to_lang(lang?lang->value:"und", mov->mode!=MODE_MOV);
5086 if (track->language < 0)
5087 track->language = 0;
5088 track->mode = mov->mode;
5089 track->tag = mov_find_codec_tag(s, track);
5091 av_log(s, AV_LOG_ERROR, "Could not find tag for codec %s in stream #%d, "
5092 "codec not currently supported in container\n",
5093 avcodec_get_name(st->codec->codec_id), i);
5094 ret = AVERROR(EINVAL);
5097 /* If hinting of this track is enabled by a later hint track,
5098 * this is updated. */
5099 track->hint_track = -1;
5100 track->start_dts = AV_NOPTS_VALUE;
5101 track->start_cts = AV_NOPTS_VALUE;
5102 track->end_pts = AV_NOPTS_VALUE;
5103 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
5104 if (track->tag == MKTAG('m','x','3','p') || track->tag == MKTAG('m','x','3','n') ||
5105 track->tag == MKTAG('m','x','4','p') || track->tag == MKTAG('m','x','4','n') ||
5106 track->tag == MKTAG('m','x','5','p') || track->tag == MKTAG('m','x','5','n')) {
5107 if (st->codec->width != 720 || (st->codec->height != 608 && st->codec->height != 512)) {
5108 av_log(s, AV_LOG_ERROR, "D-10/IMX must use 720x608 or 720x512 video resolution\n");
5109 ret = AVERROR(EINVAL);
5112 track->height = track->tag >> 24 == 'n' ? 486 : 576;
5114 if (mov->video_track_timescale) {
5115 track->timescale = mov->video_track_timescale;
5117 track->timescale = st->time_base.den;
5118 while(track->timescale < 10000)
5119 track->timescale *= 2;
5121 if (st->codec->width > 65535 || st->codec->height > 65535) {
5122 av_log(s, AV_LOG_ERROR, "Resolution %dx%d too large for mov/mp4\n", st->codec->width, st->codec->height);
5123 ret = AVERROR(EINVAL);
5126 if (track->mode == MODE_MOV && track->timescale > 100000)
5127 av_log(s, AV_LOG_WARNING,
5128 "WARNING codec timebase is very high. If duration is too long,\n"
5129 "file may not be playable by quicktime. Specify a shorter timebase\n"
5130 "or choose different container.\n");
5131 } else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
5132 track->timescale = st->codec->sample_rate;
5133 if (!st->codec->frame_size && !av_get_bits_per_sample(st->codec->codec_id)) {
5134 av_log(s, AV_LOG_WARNING, "track %d: codec frame size is not set\n", i);
5135 track->audio_vbr = 1;
5136 }else if (st->codec->codec_id == AV_CODEC_ID_ADPCM_MS ||
5137 st->codec->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
5138 st->codec->codec_id == AV_CODEC_ID_ILBC){
5139 if (!st->codec->block_align) {
5140 av_log(s, AV_LOG_ERROR, "track %d: codec block align is not set for adpcm\n", i);
5141 ret = AVERROR(EINVAL);
5144 track->sample_size = st->codec->block_align;
5145 }else if (st->codec->frame_size > 1){ /* assume compressed audio */
5146 track->audio_vbr = 1;
5148 track->sample_size = (av_get_bits_per_sample(st->codec->codec_id) >> 3) * st->codec->channels;
5150 if (st->codec->codec_id == AV_CODEC_ID_ILBC ||
5151 st->codec->codec_id == AV_CODEC_ID_ADPCM_IMA_QT) {
5152 track->audio_vbr = 1;
5154 if (track->mode != MODE_MOV &&
5155 track->enc->codec_id == AV_CODEC_ID_MP3 && track->timescale < 16000) {
5156 av_log(s, AV_LOG_ERROR, "track %d: muxing mp3 at %dhz is not supported\n",
5157 i, track->enc->sample_rate);
5158 ret = AVERROR(EINVAL);
5161 } else if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
5162 track->timescale = st->time_base.den;
5163 } else if (st->codec->codec_type == AVMEDIA_TYPE_DATA) {
5164 track->timescale = st->time_base.den;
5166 track->timescale = MOV_TIMESCALE;
5169 track->height = st->codec->height;
5170 /* The ism specific timescale isn't mandatory, but is assumed by
5171 * some tools, such as mp4split. */
5172 if (mov->mode == MODE_ISM)
5173 track->timescale = 10000000;
5175 avpriv_set_pts_info(st, 64, 1, track->timescale);
5177 /* copy extradata if it exists */
5178 if (st->codec->extradata_size) {
5179 if (st->codec->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
5180 mov_create_dvd_sub_decoder_specific_info(track, st);
5181 else if (!TAG_IS_AVCI(track->tag) && st->codec->codec_id != AV_CODEC_ID_DNXHD) {
5182 track->vos_len = st->codec->extradata_size;
5183 track->vos_data = av_malloc(track->vos_len);
5184 if (!track->vos_data) {
5185 ret = AVERROR(ENOMEM);
5188 memcpy(track->vos_data, st->codec->extradata, track->vos_len);
5193 for (i = 0; i < s->nb_streams; i++) {
5195 AVStream *st= s->streams[i];
5196 MOVTrack *track= &mov->tracks[i];
5198 if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO ||
5199 track->enc->channel_layout != AV_CH_LAYOUT_MONO)
5202 for (j = 0; j < s->nb_streams; j++) {
5203 AVStream *stj= s->streams[j];
5204 MOVTrack *trackj= &mov->tracks[j];
5208 if (stj->codec->codec_type != AVMEDIA_TYPE_AUDIO ||
5209 trackj->enc->channel_layout != AV_CH_LAYOUT_MONO ||
5210 trackj->language != track->language ||
5211 trackj->tag != track->tag
5214 track->multichannel_as_mono++;
5221 if (mov->reserved_moov_size){
5222 mov->reserved_moov_pos= avio_tell(pb);
5223 if (mov->reserved_moov_size > 0)
5224 avio_skip(pb, mov->reserved_moov_size);
5227 if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
5228 /* If no fragmentation options have been set, set a default. */
5229 if (!(mov->flags & (FF_MOV_FLAG_FRAG_KEYFRAME |
5230 FF_MOV_FLAG_FRAG_CUSTOM)) &&
5231 !mov->max_fragment_duration && !mov->max_fragment_size)
5232 mov->flags |= FF_MOV_FLAG_FRAG_KEYFRAME;
5234 if (mov->flags & FF_MOV_FLAG_FASTSTART)
5235 mov->reserved_moov_pos = avio_tell(pb);
5236 mov_write_mdat_tag(pb, mov);
5239 if (t = av_dict_get(s->metadata, "creation_time", NULL, 0))
5240 mov->time = ff_iso8601_to_unix_time(t->value);
5242 mov->time += 0x7C25B080; // 1970 based -> 1904 based
5244 if (mov->chapter_track)
5245 if ((ret = mov_create_chapter_track(s, mov->chapter_track)) < 0)
5248 if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
5249 /* Initialize the hint tracks for each audio and video stream */
5250 for (i = 0; i < s->nb_streams; i++) {
5251 AVStream *st = s->streams[i];
5252 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO ||
5253 st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
5254 if ((ret = ff_mov_init_hinting(s, hint_track, i)) < 0)
5261 if (mov->nb_meta_tmcd) {
5262 /* Initialize the tmcd tracks */
5263 for (i = 0; i < s->nb_streams; i++) {
5264 AVStream *st = s->streams[i];
5267 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
5269 t = av_dict_get(st->metadata, "timecode", NULL, 0);
5272 if ((ret = mov_create_timecode_track(s, tmcd_track, i, t->value)) < 0)
5281 if (mov->flags & FF_MOV_FLAG_ISML)
5282 mov_write_isml_manifest(pb, mov);
5284 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV &&
5285 !(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
5286 if ((ret = mov_write_moov_tag(pb, mov, s)) < 0)
5288 mov->moov_written = 1;
5289 if (mov->flags & FF_MOV_FLAG_FASTSTART)
5290 mov->reserved_moov_pos = avio_tell(pb);
5299 static int get_moov_size(AVFormatContext *s)
5302 AVIOContext *moov_buf;
5303 MOVMuxContext *mov = s->priv_data;
5305 if ((ret = ffio_open_null_buf(&moov_buf)) < 0)
5307 if ((ret = mov_write_moov_tag(moov_buf, mov, s)) < 0)
5309 return ffio_close_null_buf(moov_buf);
5312 static int get_sidx_size(AVFormatContext *s)
5316 MOVMuxContext *mov = s->priv_data;
5318 if ((ret = ffio_open_null_buf(&buf)) < 0)
5320 mov_write_sidx_tags(buf, mov, -1, 0);
5321 return ffio_close_null_buf(buf);
5325 * This function gets the moov size if moved to the top of the file: the chunk
5326 * offset table can switch between stco (32-bit entries) to co64 (64-bit
5327 * entries) when the moov is moved to the beginning, so the size of the moov
5328 * would change. It also updates the chunk offset tables.
5330 static int compute_moov_size(AVFormatContext *s)
5332 int i, moov_size, moov_size2;
5333 MOVMuxContext *mov = s->priv_data;
5335 moov_size = get_moov_size(s);
5339 for (i = 0; i < mov->nb_streams; i++)
5340 mov->tracks[i].data_offset += moov_size;
5342 moov_size2 = get_moov_size(s);
5346 /* if the size changed, we just switched from stco to co64 and need to
5347 * update the offsets */
5348 if (moov_size2 != moov_size)
5349 for (i = 0; i < mov->nb_streams; i++)
5350 mov->tracks[i].data_offset += moov_size2 - moov_size;
5355 static int compute_sidx_size(AVFormatContext *s)
5358 MOVMuxContext *mov = s->priv_data;
5360 sidx_size = get_sidx_size(s);
5364 for (i = 0; i < mov->nb_streams; i++)
5365 mov->tracks[i].data_offset += sidx_size;
5370 static int shift_data(AVFormatContext *s)
5372 int ret = 0, moov_size;
5373 MOVMuxContext *mov = s->priv_data;
5374 int64_t pos, pos_end = avio_tell(s->pb);
5375 uint8_t *buf, *read_buf[2];
5376 int read_buf_id = 0;
5378 AVIOContext *read_pb;
5380 if (mov->flags & FF_MOV_FLAG_FRAGMENT)
5381 moov_size = compute_sidx_size(s);
5383 moov_size = compute_moov_size(s);
5387 buf = av_malloc(moov_size * 2);
5389 return AVERROR(ENOMEM);
5391 read_buf[1] = buf + moov_size;
5393 /* Shift the data: the AVIO context of the output can only be used for
5394 * writing, so we re-open the same output, but for reading. It also avoids
5395 * a read/seek/write/seek back and forth. */
5397 ret = avio_open(&read_pb, s->filename, AVIO_FLAG_READ);
5399 av_log(s, AV_LOG_ERROR, "Unable to re-open %s output file for "
5400 "the second pass (faststart)\n", s->filename);
5404 /* mark the end of the shift to up to the last data we wrote, and get ready
5406 pos_end = avio_tell(s->pb);
5407 avio_seek(s->pb, mov->reserved_moov_pos + moov_size, SEEK_SET);
5409 /* start reading at where the new moov will be placed */
5410 avio_seek(read_pb, mov->reserved_moov_pos, SEEK_SET);
5411 pos = avio_tell(read_pb);
5413 #define READ_BLOCK do { \
5414 read_size[read_buf_id] = avio_read(read_pb, read_buf[read_buf_id], moov_size); \
5418 /* shift data by chunk of at most moov_size */
5423 n = read_size[read_buf_id];
5426 avio_write(s->pb, read_buf[read_buf_id], n);
5428 } while (pos < pos_end);
5429 avio_close(read_pb);
5436 static int mov_write_trailer(AVFormatContext *s)
5438 MOVMuxContext *mov = s->priv_data;
5439 AVIOContext *pb = s->pb;
5445 * Before actually writing the trailer, make sure that there are no
5446 * dangling subtitles, that need a terminating sample.
5448 for (i = 0; i < mov->nb_streams; i++) {
5449 MOVTrack *trk = &mov->tracks[i];
5450 if (trk->enc->codec_id == AV_CODEC_ID_MOV_TEXT &&
5451 !trk->last_sample_is_subtitle_end) {
5452 mov_write_subtitle_end_packet(s, i, trk->track_duration);
5453 trk->last_sample_is_subtitle_end = 1;
5457 // If there were no chapters when the header was written, but there
5458 // are chapters now, write them in the trailer. This only works
5459 // when we are not doing fragments.
5460 if (!mov->chapter_track && !(mov->flags & FF_MOV_FLAG_FRAGMENT)) {
5461 if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters) {
5462 mov->chapter_track = mov->nb_streams++;
5463 if ((res = mov_create_chapter_track(s, mov->chapter_track)) < 0)
5468 if (!(mov->flags & FF_MOV_FLAG_FRAGMENT)) {
5469 moov_pos = avio_tell(pb);
5471 /* Write size of mdat tag */
5472 if (mov->mdat_size + 8 <= UINT32_MAX) {
5473 avio_seek(pb, mov->mdat_pos, SEEK_SET);
5474 avio_wb32(pb, mov->mdat_size + 8);
5476 /* overwrite 'wide' placeholder atom */
5477 avio_seek(pb, mov->mdat_pos - 8, SEEK_SET);
5478 /* special value: real atom size will be 64 bit value after
5481 ffio_wfourcc(pb, "mdat");
5482 avio_wb64(pb, mov->mdat_size + 16);
5484 avio_seek(pb, mov->reserved_moov_size > 0 ? mov->reserved_moov_pos : moov_pos, SEEK_SET);
5486 if (mov->flags & FF_MOV_FLAG_FASTSTART) {
5487 av_log(s, AV_LOG_INFO, "Starting second pass: moving the moov atom to the beginning of the file\n");
5488 res = shift_data(s);
5490 avio_seek(pb, mov->reserved_moov_pos, SEEK_SET);
5491 if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
5494 } else if (mov->reserved_moov_size > 0) {
5496 if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
5498 size = mov->reserved_moov_size - (avio_tell(pb) - mov->reserved_moov_pos);
5500 av_log(s, AV_LOG_ERROR, "reserved_moov_size is too small, needed %"PRId64" additional\n", 8-size);
5501 res = AVERROR(EINVAL);
5504 avio_wb32(pb, size);
5505 ffio_wfourcc(pb, "free");
5506 ffio_fill(pb, 0, size - 8);
5507 avio_seek(pb, moov_pos, SEEK_SET);
5509 if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
5514 mov_auto_flush_fragment(s);
5515 for (i = 0; i < mov->nb_streams; i++)
5516 mov->tracks[i].data_offset = 0;
5517 if (mov->flags & FF_MOV_FLAG_FASTSTART) {
5518 av_log(s, AV_LOG_INFO, "Starting second pass: inserting sidx atoms\n");
5519 res = shift_data(s);
5521 int64_t end = avio_tell(pb);
5522 avio_seek(pb, mov->reserved_moov_pos, SEEK_SET);
5523 mov_write_sidx_tags(pb, mov, -1, 0);
5524 avio_seek(pb, end, SEEK_SET);
5525 mov_write_mfra_tag(pb, mov);
5528 mov_write_mfra_tag(pb, mov);
5538 #if CONFIG_MOV_MUXER
5540 AVOutputFormat ff_mov_muxer = {
5542 .long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
5543 .extensions = "mov",
5544 .priv_data_size = sizeof(MOVMuxContext),
5545 .audio_codec = AV_CODEC_ID_AAC,
5546 .video_codec = CONFIG_LIBX264_ENCODER ?
5547 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
5548 .write_header = mov_write_header,
5549 .write_packet = mov_write_packet,
5550 .write_trailer = mov_write_trailer,
5551 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
5552 .codec_tag = (const AVCodecTag* const []){
5553 ff_codec_movvideo_tags, ff_codec_movaudio_tags, 0
5555 .priv_class = &mov_muxer_class,
5558 #if CONFIG_TGP_MUXER
5560 AVOutputFormat ff_tgp_muxer = {
5562 .long_name = NULL_IF_CONFIG_SMALL("3GP (3GPP file format)"),
5563 .extensions = "3gp",
5564 .priv_data_size = sizeof(MOVMuxContext),
5565 .audio_codec = AV_CODEC_ID_AMR_NB,
5566 .video_codec = AV_CODEC_ID_H263,
5567 .write_header = mov_write_header,
5568 .write_packet = mov_write_packet,
5569 .write_trailer = mov_write_trailer,
5570 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
5571 .codec_tag = (const AVCodecTag* const []){ codec_3gp_tags, 0 },
5572 .priv_class = &tgp_muxer_class,
5575 #if CONFIG_MP4_MUXER
5577 AVOutputFormat ff_mp4_muxer = {
5579 .long_name = NULL_IF_CONFIG_SMALL("MP4 (MPEG-4 Part 14)"),
5580 .mime_type = "application/mp4",
5581 .extensions = "mp4",
5582 .priv_data_size = sizeof(MOVMuxContext),
5583 .audio_codec = AV_CODEC_ID_AAC,
5584 .video_codec = CONFIG_LIBX264_ENCODER ?
5585 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
5586 .write_header = mov_write_header,
5587 .write_packet = mov_write_packet,
5588 .write_trailer = mov_write_trailer,
5589 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
5590 .codec_tag = (const AVCodecTag* const []){ ff_mp4_obj_type, 0 },
5591 .priv_class = &mp4_muxer_class,
5594 #if CONFIG_PSP_MUXER
5596 AVOutputFormat ff_psp_muxer = {
5598 .long_name = NULL_IF_CONFIG_SMALL("PSP MP4 (MPEG-4 Part 14)"),
5599 .extensions = "mp4,psp",
5600 .priv_data_size = sizeof(MOVMuxContext),
5601 .audio_codec = AV_CODEC_ID_AAC,
5602 .video_codec = CONFIG_LIBX264_ENCODER ?
5603 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
5604 .write_header = mov_write_header,
5605 .write_packet = mov_write_packet,
5606 .write_trailer = mov_write_trailer,
5607 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
5608 .codec_tag = (const AVCodecTag* const []){ ff_mp4_obj_type, 0 },
5609 .priv_class = &psp_muxer_class,
5612 #if CONFIG_TG2_MUXER
5614 AVOutputFormat ff_tg2_muxer = {
5616 .long_name = NULL_IF_CONFIG_SMALL("3GP2 (3GPP2 file format)"),
5617 .extensions = "3g2",
5618 .priv_data_size = sizeof(MOVMuxContext),
5619 .audio_codec = AV_CODEC_ID_AMR_NB,
5620 .video_codec = AV_CODEC_ID_H263,
5621 .write_header = mov_write_header,
5622 .write_packet = mov_write_packet,
5623 .write_trailer = mov_write_trailer,
5624 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
5625 .codec_tag = (const AVCodecTag* const []){ codec_3gp_tags, 0 },
5626 .priv_class = &tg2_muxer_class,
5629 #if CONFIG_IPOD_MUXER
5631 AVOutputFormat ff_ipod_muxer = {
5633 .long_name = NULL_IF_CONFIG_SMALL("iPod H.264 MP4 (MPEG-4 Part 14)"),
5634 .mime_type = "application/mp4",
5635 .extensions = "m4v,m4a",
5636 .priv_data_size = sizeof(MOVMuxContext),
5637 .audio_codec = AV_CODEC_ID_AAC,
5638 .video_codec = AV_CODEC_ID_H264,
5639 .write_header = mov_write_header,
5640 .write_packet = mov_write_packet,
5641 .write_trailer = mov_write_trailer,
5642 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
5643 .codec_tag = (const AVCodecTag* const []){ codec_ipod_tags, 0 },
5644 .priv_class = &ipod_muxer_class,
5647 #if CONFIG_ISMV_MUXER
5649 AVOutputFormat ff_ismv_muxer = {
5651 .long_name = NULL_IF_CONFIG_SMALL("ISMV/ISMA (Smooth Streaming)"),
5652 .mime_type = "application/mp4",
5653 .extensions = "ismv,isma",
5654 .priv_data_size = sizeof(MOVMuxContext),
5655 .audio_codec = AV_CODEC_ID_AAC,
5656 .video_codec = AV_CODEC_ID_H264,
5657 .write_header = mov_write_header,
5658 .write_packet = mov_write_packet,
5659 .write_trailer = mov_write_trailer,
5660 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
5661 .codec_tag = (const AVCodecTag* const []){ ff_mp4_obj_type, 0 },
5662 .priv_class = &ismv_muxer_class,
5665 #if CONFIG_F4V_MUXER
5667 AVOutputFormat ff_f4v_muxer = {
5669 .long_name = NULL_IF_CONFIG_SMALL("F4V Adobe Flash Video"),
5670 .mime_type = "application/f4v",
5671 .extensions = "f4v",
5672 .priv_data_size = sizeof(MOVMuxContext),
5673 .audio_codec = AV_CODEC_ID_AAC,
5674 .video_codec = AV_CODEC_ID_H264,
5675 .write_header = mov_write_header,
5676 .write_packet = mov_write_packet,
5677 .write_trailer = mov_write_trailer,
5678 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH,
5679 .codec_tag = (const AVCodecTag* const []){ codec_f4v_tags, 0 },
5680 .priv_class = &f4v_muxer_class,