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_internal.h"
35 #include "libavcodec/dnxhddata.h"
36 #include "libavcodec/flac.h"
37 #include "libavcodec/get_bits.h"
39 #include "libavcodec/internal.h"
40 #include "libavcodec/put_bits.h"
41 #include "libavcodec/vc1_common.h"
42 #include "libavcodec/raw.h"
44 #include "libavutil/avstring.h"
45 #include "libavutil/intfloat.h"
46 #include "libavutil/mathematics.h"
47 #include "libavutil/libm.h"
48 #include "libavutil/opt.h"
49 #include "libavutil/dict.h"
50 #include "libavutil/pixdesc.h"
51 #include "libavutil/stereo3d.h"
52 #include "libavutil/timecode.h"
53 #include "libavutil/color_utils.h"
59 static const AVOption options[] = {
60 { "movflags", "MOV muxer flags", offsetof(MOVMuxContext, flags), AV_OPT_TYPE_FLAGS, {.i64 = 0}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
61 { "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" },
62 { "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 },
63 { "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" },
64 { "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" },
65 { "frag_every_frame", "Fragment at every frame", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FRAG_EVERY_FRAME}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
66 { "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" },
67 { "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" },
68 { "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" },
69 { "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" },
70 { "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" },
71 { "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" },
72 { "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" },
73 { "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" },
74 { "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" },
75 { "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" },
76 { "global_sidx", "Write a global sidx index at the start of the file", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_GLOBAL_SIDX}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
77 { "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" },
78 { "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" },
79 { "use_metadata_tags", "Use mdta atom for metadata.", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_USE_MDTA}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
80 { "skip_trailer", "Skip writing the mfra/tfra/mfro trailer for fragmented files", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_SKIP_TRAILER}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
81 { "negative_cts_offsets", "Use negative CTS offsets (reducing the need for edit lists)", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
82 FF_RTP_FLAG_OPTS(MOVMuxContext, rtp_flags),
83 { "skip_iods", "Skip writing iods atom.", offsetof(MOVMuxContext, iods_skip), AV_OPT_TYPE_BOOL, {.i64 = 1}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM},
84 { "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},
85 { "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},
86 { "frag_duration", "Maximum fragment duration", offsetof(MOVMuxContext, max_fragment_duration), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
87 { "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},
88 { "frag_size", "Maximum fragment size", offsetof(MOVMuxContext, max_fragment_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
89 { "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},
90 { "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},
91 { "brand", "Override major brand", offsetof(MOVMuxContext, major_brand), AV_OPT_TYPE_STRING, {.str = NULL}, .flags = AV_OPT_FLAG_ENCODING_PARAM },
92 { "use_editlist", "use edit list", offsetof(MOVMuxContext, use_editlist), AV_OPT_TYPE_BOOL, {.i64 = -1}, -1, 1, AV_OPT_FLAG_ENCODING_PARAM},
93 { "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},
94 { "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},
95 { "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 },
96 { "encryption_scheme", "Configures the encryption scheme, allowed values are none, cenc-aes-ctr", offsetof(MOVMuxContext, encryption_scheme_str), AV_OPT_TYPE_STRING, {.str = NULL}, .flags = AV_OPT_FLAG_ENCODING_PARAM },
97 { "encryption_key", "The media encryption key (hex)", offsetof(MOVMuxContext, encryption_key), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_ENCODING_PARAM },
98 { "encryption_kid", "The media encryption key identifier (hex)", offsetof(MOVMuxContext, encryption_kid), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_ENCODING_PARAM },
99 { "use_stream_ids_as_track_ids", "use stream ids as track ids", offsetof(MOVMuxContext, use_stream_ids_as_track_ids), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM},
100 { "write_tmcd", "force or disable writing tmcd", offsetof(MOVMuxContext, write_tmcd), AV_OPT_TYPE_BOOL, {.i64 = -1}, -1, 1, AV_OPT_FLAG_ENCODING_PARAM},
101 { "write_prft", "Write producer reference time box with specified time source", offsetof(MOVMuxContext, write_prft), AV_OPT_TYPE_INT, {.i64 = MOV_PRFT_NONE}, 0, MOV_PRFT_NB-1, AV_OPT_FLAG_ENCODING_PARAM, "prft"},
102 { "wallclock", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = MOV_PRFT_SRC_WALLCLOCK}, 0, 0, AV_OPT_FLAG_ENCODING_PARAM, "prft"},
103 { "pts", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = MOV_PRFT_SRC_PTS}, 0, 0, AV_OPT_FLAG_ENCODING_PARAM, "prft"},
107 #define MOV_CLASS(flavor)\
108 static const AVClass flavor ## _muxer_class = {\
109 .class_name = #flavor " muxer",\
110 .item_name = av_default_item_name,\
112 .version = LIBAVUTIL_VERSION_INT,\
115 static int get_moov_size(AVFormatContext *s);
117 static int utf8len(const uint8_t *b)
122 GET_UTF8(val, *b++, return -1;)
128 //FIXME support 64 bit variant with wide placeholders
129 static int64_t update_size(AVIOContext *pb, int64_t pos)
131 int64_t curpos = avio_tell(pb);
132 avio_seek(pb, pos, SEEK_SET);
133 avio_wb32(pb, curpos - pos); /* rewrite size */
134 avio_seek(pb, curpos, SEEK_SET);
139 static int co64_required(const MOVTrack *track)
141 if (track->entry > 0 && track->cluster[track->entry - 1].pos + track->data_offset > UINT32_MAX)
146 static int rtp_hinting_needed(const AVStream *st)
148 /* Add hint tracks for each real audio and video stream */
149 if (st->disposition & AV_DISPOSITION_ATTACHED_PIC)
151 return st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ||
152 st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO;
155 /* Chunk offset atom */
156 static int mov_write_stco_tag(AVIOContext *pb, MOVTrack *track)
159 int mode64 = co64_required(track); // use 32 bit size variant if possible
160 int64_t pos = avio_tell(pb);
161 avio_wb32(pb, 0); /* size */
163 ffio_wfourcc(pb, "co64");
165 ffio_wfourcc(pb, "stco");
166 avio_wb32(pb, 0); /* version & flags */
167 avio_wb32(pb, track->chunkCount); /* entry count */
168 for (i = 0; i < track->entry; i++) {
169 if (!track->cluster[i].chunkNum)
172 avio_wb64(pb, track->cluster[i].pos + track->data_offset);
174 avio_wb32(pb, track->cluster[i].pos + track->data_offset);
176 return update_size(pb, pos);
179 /* Sample size atom */
180 static int mov_write_stsz_tag(AVIOContext *pb, MOVTrack *track)
183 int i, j, entries = 0, tst = -1, oldtst = -1;
185 int64_t pos = avio_tell(pb);
186 avio_wb32(pb, 0); /* size */
187 ffio_wfourcc(pb, "stsz");
188 avio_wb32(pb, 0); /* version & flags */
190 for (i = 0; i < track->entry; i++) {
191 tst = track->cluster[i].size / track->cluster[i].entries;
192 if (oldtst != -1 && tst != oldtst)
195 entries += track->cluster[i].entries;
197 if (equalChunks && track->entry) {
198 int sSize = track->entry ? track->cluster[0].size / track->cluster[0].entries : 0;
199 sSize = FFMAX(1, sSize); // adpcm mono case could make sSize == 0
200 avio_wb32(pb, sSize); // sample size
201 avio_wb32(pb, entries); // sample count
203 avio_wb32(pb, 0); // sample size
204 avio_wb32(pb, entries); // sample count
205 for (i = 0; i < track->entry; i++) {
206 for (j = 0; j < track->cluster[i].entries; j++) {
207 avio_wb32(pb, track->cluster[i].size /
208 track->cluster[i].entries);
212 return update_size(pb, pos);
215 /* Sample to chunk atom */
216 static int mov_write_stsc_tag(AVIOContext *pb, MOVTrack *track)
218 int index = 0, oldval = -1, i;
219 int64_t entryPos, curpos;
221 int64_t pos = avio_tell(pb);
222 avio_wb32(pb, 0); /* size */
223 ffio_wfourcc(pb, "stsc");
224 avio_wb32(pb, 0); // version & flags
225 entryPos = avio_tell(pb);
226 avio_wb32(pb, track->chunkCount); // entry count
227 for (i = 0; i < track->entry; i++) {
228 if (oldval != track->cluster[i].samples_in_chunk && track->cluster[i].chunkNum) {
229 avio_wb32(pb, track->cluster[i].chunkNum); // first chunk
230 avio_wb32(pb, track->cluster[i].samples_in_chunk); // samples per chunk
231 avio_wb32(pb, 0x1); // sample description index
232 oldval = track->cluster[i].samples_in_chunk;
236 curpos = avio_tell(pb);
237 avio_seek(pb, entryPos, SEEK_SET);
238 avio_wb32(pb, index); // rewrite size
239 avio_seek(pb, curpos, SEEK_SET);
241 return update_size(pb, pos);
244 /* Sync sample atom */
245 static int mov_write_stss_tag(AVIOContext *pb, MOVTrack *track, uint32_t flag)
247 int64_t curpos, entryPos;
249 int64_t pos = avio_tell(pb);
250 avio_wb32(pb, 0); // size
251 ffio_wfourcc(pb, flag == MOV_SYNC_SAMPLE ? "stss" : "stps");
252 avio_wb32(pb, 0); // version & flags
253 entryPos = avio_tell(pb);
254 avio_wb32(pb, track->entry); // entry count
255 for (i = 0; i < track->entry; i++) {
256 if (track->cluster[i].flags & flag) {
257 avio_wb32(pb, i + 1);
261 curpos = avio_tell(pb);
262 avio_seek(pb, entryPos, SEEK_SET);
263 avio_wb32(pb, index); // rewrite size
264 avio_seek(pb, curpos, SEEK_SET);
265 return update_size(pb, pos);
268 /* Sample dependency atom */
269 static int mov_write_sdtp_tag(AVIOContext *pb, MOVTrack *track)
272 uint8_t leading, dependent, reference, redundancy;
273 int64_t pos = avio_tell(pb);
274 avio_wb32(pb, 0); // size
275 ffio_wfourcc(pb, "sdtp");
276 avio_wb32(pb, 0); // version & flags
277 for (i = 0; i < track->entry; i++) {
278 dependent = MOV_SAMPLE_DEPENDENCY_YES;
279 leading = reference = redundancy = MOV_SAMPLE_DEPENDENCY_UNKNOWN;
280 if (track->cluster[i].flags & MOV_DISPOSABLE_SAMPLE) {
281 reference = MOV_SAMPLE_DEPENDENCY_NO;
283 if (track->cluster[i].flags & MOV_SYNC_SAMPLE) {
284 dependent = MOV_SAMPLE_DEPENDENCY_NO;
286 avio_w8(pb, (leading << 6) | (dependent << 4) |
287 (reference << 2) | redundancy);
289 return update_size(pb, pos);
292 static int mov_write_amr_tag(AVIOContext *pb, MOVTrack *track)
294 avio_wb32(pb, 0x11); /* size */
295 if (track->mode == MODE_MOV) ffio_wfourcc(pb, "samr");
296 else ffio_wfourcc(pb, "damr");
297 ffio_wfourcc(pb, "FFMP");
298 avio_w8(pb, 0); /* decoder version */
300 avio_wb16(pb, 0x81FF); /* Mode set (all modes for AMR_NB) */
301 avio_w8(pb, 0x00); /* Mode change period (no restriction) */
302 avio_w8(pb, 0x01); /* Frames per sample */
306 static int mov_write_ac3_tag(AVIOContext *pb, MOVTrack *track)
311 int fscod, bsid, bsmod, acmod, lfeon, frmsizecod;
313 if (track->vos_len < 7)
317 ffio_wfourcc(pb, "dac3");
319 init_get_bits(&gbc, track->vos_data + 4, (track->vos_len - 4) * 8);
320 fscod = get_bits(&gbc, 2);
321 frmsizecod = get_bits(&gbc, 6);
322 bsid = get_bits(&gbc, 5);
323 bsmod = get_bits(&gbc, 3);
324 acmod = get_bits(&gbc, 3);
326 skip_bits(&gbc, 2); // dsurmod
328 if ((acmod & 1) && acmod != 1)
329 skip_bits(&gbc, 2); // cmixlev
331 skip_bits(&gbc, 2); // surmixlev
333 lfeon = get_bits1(&gbc);
335 init_put_bits(&pbc, buf, sizeof(buf));
336 put_bits(&pbc, 2, fscod);
337 put_bits(&pbc, 5, bsid);
338 put_bits(&pbc, 3, bsmod);
339 put_bits(&pbc, 3, acmod);
340 put_bits(&pbc, 1, lfeon);
341 put_bits(&pbc, 5, frmsizecod >> 1); // bit_rate_code
342 put_bits(&pbc, 5, 0); // reserved
344 flush_put_bits(&pbc);
345 avio_write(pb, buf, sizeof(buf));
355 /* Layout of the EC3SpecificBox */
356 /* maximum bitrate */
358 /* number of independent substreams */
361 /* sample rate code (see ff_ac3_sample_rate_tab) 2 bits */
363 /* bit stream identification 5 bits */
365 /* one bit reserved */
366 /* audio service mixing (not supported yet) 1 bit */
367 /* bit stream mode 3 bits */
369 /* audio coding mode 3 bits */
371 /* sub woofer on 1 bit */
373 /* 3 bits reserved */
374 /* number of dependent substreams associated with this substream 4 bits */
376 /* channel locations of the dependent substream(s), if any, 9 bits */
378 /* if there is no dependent substream, then one bit reserved instead */
379 } substream[1]; /* TODO: support 8 independent substreams */
382 #if CONFIG_AC3_PARSER
383 static int handle_eac3(MOVMuxContext *mov, AVPacket *pkt, MOVTrack *track)
385 AC3HeaderInfo *hdr = NULL;
386 struct eac3_info *info;
389 if (!track->eac3_priv && !(track->eac3_priv = av_mallocz(sizeof(*info))))
390 return AVERROR(ENOMEM);
391 info = track->eac3_priv;
393 if (avpriv_ac3_parse_header(&hdr, pkt->data, pkt->size) < 0) {
394 /* drop the packets until we see a good one */
396 av_log(mov, AV_LOG_WARNING, "Dropping invalid packet from start of the stream\n");
399 ret = AVERROR_INVALIDDATA;
403 info->data_rate = FFMAX(info->data_rate, hdr->bit_rate / 1000);
404 num_blocks = hdr->num_blocks;
406 if (!info->ec3_done) {
407 /* AC-3 substream must be the first one */
408 if (hdr->bitstream_id <= 10 && hdr->substreamid != 0) {
409 ret = AVERROR(EINVAL);
413 /* this should always be the case, given that our AC-3 parser
414 * concatenates dependent frames to their independent parent */
415 if (hdr->frame_type == EAC3_FRAME_TYPE_INDEPENDENT) {
416 /* substream ids must be incremental */
417 if (hdr->substreamid > info->num_ind_sub + 1) {
418 ret = AVERROR(EINVAL);
422 if (hdr->substreamid == info->num_ind_sub + 1) {
423 //info->num_ind_sub++;
424 avpriv_request_sample(track->par, "Multiple independent substreams");
425 ret = AVERROR_PATCHWELCOME;
427 } else if (hdr->substreamid < info->num_ind_sub ||
428 hdr->substreamid == 0 && info->substream[0].bsid) {
434 /* fill the info needed for the "dec3" atom */
435 info->substream[hdr->substreamid].fscod = hdr->sr_code;
436 info->substream[hdr->substreamid].bsid = hdr->bitstream_id;
437 info->substream[hdr->substreamid].bsmod = hdr->bitstream_mode;
438 info->substream[hdr->substreamid].acmod = hdr->channel_mode;
439 info->substream[hdr->substreamid].lfeon = hdr->lfe_on;
441 /* Parse dependent substream(s), if any */
442 if (pkt->size != hdr->frame_size) {
443 int cumul_size = hdr->frame_size;
444 int parent = hdr->substreamid;
446 while (cumul_size != pkt->size) {
449 ret = avpriv_ac3_parse_header(&hdr, pkt->data + cumul_size, pkt->size - cumul_size);
452 if (hdr->frame_type != EAC3_FRAME_TYPE_DEPENDENT) {
453 ret = AVERROR(EINVAL);
456 info->substream[parent].num_dep_sub++;
459 /* header is parsed up to lfeon, but custom channel map may be needed */
460 init_get_bits8(&gbc, pkt->data + cumul_size + ret, pkt->size - cumul_size - ret);
463 /* skip volume control params */
464 for (i = 0; i < (hdr->channel_mode ? 1 : 2); i++) {
465 skip_bits(&gbc, 5); // skip dialog normalization
466 if (get_bits1(&gbc)) {
467 skip_bits(&gbc, 8); // skip compression gain word
470 /* get the dependent stream channel map, if exists */
472 info->substream[parent].chan_loc |= (get_bits(&gbc, 16) >> 5) & 0x1f;
474 info->substream[parent].chan_loc |= hdr->channel_mode;
475 cumul_size += hdr->frame_size;
481 if (!info->num_blocks && num_blocks == 6) {
485 else if (info->num_blocks + num_blocks > 6) {
486 ret = AVERROR_INVALIDDATA;
490 if (!info->num_blocks) {
491 ret = av_packet_ref(&info->pkt, pkt);
493 info->num_blocks = num_blocks;
496 if ((ret = av_grow_packet(&info->pkt, pkt->size)) < 0)
498 memcpy(info->pkt.data + info->pkt.size - pkt->size, pkt->data, pkt->size);
499 info->num_blocks += num_blocks;
500 info->pkt.duration += pkt->duration;
501 if ((ret = av_copy_packet_side_data(&info->pkt, pkt)) < 0)
503 if (info->num_blocks != 6)
505 av_packet_unref(pkt);
506 av_packet_move_ref(pkt, &info->pkt);
507 info->num_blocks = 0;
518 static int mov_write_eac3_tag(AVIOContext *pb, MOVTrack *track)
522 struct eac3_info *info;
525 if (!track->eac3_priv)
526 return AVERROR(EINVAL);
528 info = track->eac3_priv;
529 size = 2 + 4 * (info->num_ind_sub + 1);
530 buf = av_malloc(size);
532 size = AVERROR(ENOMEM);
536 init_put_bits(&pbc, buf, size);
537 put_bits(&pbc, 13, info->data_rate);
538 put_bits(&pbc, 3, info->num_ind_sub);
539 for (i = 0; i <= info->num_ind_sub; i++) {
540 put_bits(&pbc, 2, info->substream[i].fscod);
541 put_bits(&pbc, 5, info->substream[i].bsid);
542 put_bits(&pbc, 1, 0); /* reserved */
543 put_bits(&pbc, 1, 0); /* asvc */
544 put_bits(&pbc, 3, info->substream[i].bsmod);
545 put_bits(&pbc, 3, info->substream[i].acmod);
546 put_bits(&pbc, 1, info->substream[i].lfeon);
547 put_bits(&pbc, 5, 0); /* reserved */
548 put_bits(&pbc, 4, info->substream[i].num_dep_sub);
549 if (!info->substream[i].num_dep_sub) {
550 put_bits(&pbc, 1, 0); /* reserved */
553 put_bits(&pbc, 9, info->substream[i].chan_loc);
556 flush_put_bits(&pbc);
558 avio_wb32(pb, size + 8);
559 ffio_wfourcc(pb, "dec3");
560 avio_write(pb, buf, size);
565 av_packet_unref(&info->pkt);
566 av_freep(&track->eac3_priv);
572 * This function writes extradata "as is".
573 * Extradata must be formatted like a valid atom (with size and tag).
575 static int mov_write_extradata_tag(AVIOContext *pb, MOVTrack *track)
577 avio_write(pb, track->par->extradata, track->par->extradata_size);
578 return track->par->extradata_size;
581 static int mov_write_enda_tag(AVIOContext *pb)
584 ffio_wfourcc(pb, "enda");
585 avio_wb16(pb, 1); /* little endian */
589 static int mov_write_enda_tag_be(AVIOContext *pb)
592 ffio_wfourcc(pb, "enda");
593 avio_wb16(pb, 0); /* big endian */
597 static void put_descr(AVIOContext *pb, int tag, unsigned int size)
602 avio_w8(pb, (size >> (7 * i)) | 0x80);
603 avio_w8(pb, size & 0x7F);
606 static unsigned compute_avg_bitrate(MOVTrack *track)
610 if (!track->track_duration)
612 for (i = 0; i < track->entry; i++)
613 size += track->cluster[i].size;
614 return size * 8 * track->timescale / track->track_duration;
617 static int mov_write_esds_tag(AVIOContext *pb, MOVTrack *track) // Basic
619 AVCPBProperties *props;
620 int64_t pos = avio_tell(pb);
621 int decoder_specific_info_len = track->vos_len ? 5 + track->vos_len : 0;
622 unsigned avg_bitrate;
624 avio_wb32(pb, 0); // size
625 ffio_wfourcc(pb, "esds");
626 avio_wb32(pb, 0); // Version
629 put_descr(pb, 0x03, 3 + 5+13 + decoder_specific_info_len + 5+1);
630 avio_wb16(pb, track->track_id);
631 avio_w8(pb, 0x00); // flags (= no flags)
633 // DecoderConfig descriptor
634 put_descr(pb, 0x04, 13 + decoder_specific_info_len);
636 // Object type indication
637 if ((track->par->codec_id == AV_CODEC_ID_MP2 ||
638 track->par->codec_id == AV_CODEC_ID_MP3) &&
639 track->par->sample_rate > 24000)
640 avio_w8(pb, 0x6B); // 11172-3
642 avio_w8(pb, ff_codec_get_tag(ff_mp4_obj_type, track->par->codec_id));
644 // the following fields is made of 6 bits to identify the streamtype (4 for video, 5 for audio)
645 // plus 1 bit to indicate upstream and 1 bit set to 1 (reserved)
646 if (track->par->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
647 avio_w8(pb, (0x38 << 2) | 1); // flags (= NeroSubpicStream)
648 else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
649 avio_w8(pb, 0x15); // flags (= Audiostream)
651 avio_w8(pb, 0x11); // flags (= Visualstream)
653 props = (AVCPBProperties*)av_stream_get_side_data(track->st, AV_PKT_DATA_CPB_PROPERTIES,
656 avio_wb24(pb, props ? props->buffer_size / 8 : 0); // Buffersize DB
658 avg_bitrate = compute_avg_bitrate(track);
659 avio_wb32(pb, props ? FFMAX3(props->max_bitrate, props->avg_bitrate, avg_bitrate) : FFMAX(track->par->bit_rate, avg_bitrate)); // maxbitrate (FIXME should be max rate in any 1 sec window)
660 avio_wb32(pb, avg_bitrate);
662 if (track->vos_len) {
663 // DecoderSpecific info descriptor
664 put_descr(pb, 0x05, track->vos_len);
665 avio_write(pb, track->vos_data, track->vos_len);
669 put_descr(pb, 0x06, 1);
671 return update_size(pb, pos);
674 static int mov_pcm_le_gt16(enum AVCodecID codec_id)
676 return codec_id == AV_CODEC_ID_PCM_S24LE ||
677 codec_id == AV_CODEC_ID_PCM_S32LE ||
678 codec_id == AV_CODEC_ID_PCM_F32LE ||
679 codec_id == AV_CODEC_ID_PCM_F64LE;
682 static int mov_pcm_be_gt16(enum AVCodecID codec_id)
684 return codec_id == AV_CODEC_ID_PCM_S24BE ||
685 codec_id == AV_CODEC_ID_PCM_S32BE ||
686 codec_id == AV_CODEC_ID_PCM_F32BE ||
687 codec_id == AV_CODEC_ID_PCM_F64BE;
690 static int mov_write_ms_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
693 int64_t pos = avio_tell(pb);
695 avio_wl32(pb, track->tag); // store it byteswapped
696 track->par->codec_tag = av_bswap16(track->tag >> 16);
697 if ((ret = ff_put_wav_header(s, pb, track->par, 0)) < 0)
699 return update_size(pb, pos);
702 static int mov_write_wfex_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
705 int64_t pos = avio_tell(pb);
707 ffio_wfourcc(pb, "wfex");
708 if ((ret = ff_put_wav_header(s, pb, track->st->codecpar, FF_PUT_WAV_HEADER_FORCE_WAVEFORMATEX)) < 0)
710 return update_size(pb, pos);
713 static int mov_write_dfla_tag(AVIOContext *pb, MOVTrack *track)
715 int64_t pos = avio_tell(pb);
717 ffio_wfourcc(pb, "dfLa");
718 avio_w8(pb, 0); /* version */
719 avio_wb24(pb, 0); /* flags */
721 /* Expect the encoder to pass a METADATA_BLOCK_TYPE_STREAMINFO. */
722 if (track->par->extradata_size != FLAC_STREAMINFO_SIZE)
723 return AVERROR_INVALIDDATA;
725 /* TODO: Write other METADATA_BLOCK_TYPEs if the encoder makes them available. */
726 avio_w8(pb, 1 << 7 | FLAC_METADATA_TYPE_STREAMINFO); /* LastMetadataBlockFlag << 7 | BlockType */
727 avio_wb24(pb, track->par->extradata_size); /* Length */
728 avio_write(pb, track->par->extradata, track->par->extradata_size); /* BlockData[Length] */
730 return update_size(pb, pos);
733 static int mov_write_dops_tag(AVIOContext *pb, MOVTrack *track)
735 int64_t pos = avio_tell(pb);
737 ffio_wfourcc(pb, "dOps");
738 avio_w8(pb, 0); /* Version */
739 if (track->par->extradata_size < 19) {
740 av_log(pb, AV_LOG_ERROR, "invalid extradata size\n");
741 return AVERROR_INVALIDDATA;
743 /* extradata contains an Ogg OpusHead, other than byte-ordering and
744 OpusHead's preceeding magic/version, OpusSpecificBox is currently
746 avio_w8(pb, AV_RB8(track->par->extradata + 9)); /* OuputChannelCount */
747 avio_wb16(pb, AV_RL16(track->par->extradata + 10)); /* PreSkip */
748 avio_wb32(pb, AV_RL32(track->par->extradata + 12)); /* InputSampleRate */
749 avio_wb16(pb, AV_RL16(track->par->extradata + 16)); /* OutputGain */
750 /* Write the rest of the header out without byte-swapping. */
751 avio_write(pb, track->par->extradata + 18, track->par->extradata_size - 18);
753 return update_size(pb, pos);
756 static int mov_write_chan_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
758 uint32_t layout_tag, bitmap;
759 int64_t pos = avio_tell(pb);
761 layout_tag = ff_mov_get_channel_layout_tag(track->par->codec_id,
762 track->par->channel_layout,
765 av_log(s, AV_LOG_WARNING, "not writing 'chan' tag due to "
766 "lack of channel information\n");
770 if (track->multichannel_as_mono)
773 avio_wb32(pb, 0); // Size
774 ffio_wfourcc(pb, "chan"); // Type
775 avio_w8(pb, 0); // Version
776 avio_wb24(pb, 0); // Flags
777 avio_wb32(pb, layout_tag); // mChannelLayoutTag
778 avio_wb32(pb, bitmap); // mChannelBitmap
779 avio_wb32(pb, 0); // mNumberChannelDescriptions
781 return update_size(pb, pos);
784 static int mov_write_wave_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
786 int64_t pos = avio_tell(pb);
788 avio_wb32(pb, 0); /* size */
789 ffio_wfourcc(pb, "wave");
791 if (track->par->codec_id != AV_CODEC_ID_QDM2) {
792 avio_wb32(pb, 12); /* size */
793 ffio_wfourcc(pb, "frma");
794 avio_wl32(pb, track->tag);
797 if (track->par->codec_id == AV_CODEC_ID_AAC) {
798 /* useless atom needed by mplayer, ipod, not needed by quicktime */
799 avio_wb32(pb, 12); /* size */
800 ffio_wfourcc(pb, "mp4a");
802 mov_write_esds_tag(pb, track);
803 } else if (mov_pcm_le_gt16(track->par->codec_id)) {
804 mov_write_enda_tag(pb);
805 } else if (mov_pcm_be_gt16(track->par->codec_id)) {
806 mov_write_enda_tag_be(pb);
807 } else if (track->par->codec_id == AV_CODEC_ID_AMR_NB) {
808 mov_write_amr_tag(pb, track);
809 } else if (track->par->codec_id == AV_CODEC_ID_AC3) {
810 mov_write_ac3_tag(pb, track);
811 } else if (track->par->codec_id == AV_CODEC_ID_EAC3) {
812 mov_write_eac3_tag(pb, track);
813 } else if (track->par->codec_id == AV_CODEC_ID_ALAC ||
814 track->par->codec_id == AV_CODEC_ID_QDM2) {
815 mov_write_extradata_tag(pb, track);
816 } else if (track->par->codec_id == AV_CODEC_ID_ADPCM_MS ||
817 track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) {
818 mov_write_ms_tag(s, pb, track);
821 avio_wb32(pb, 8); /* size */
822 avio_wb32(pb, 0); /* null tag */
824 return update_size(pb, pos);
827 static int mov_write_dvc1_structs(MOVTrack *track, uint8_t *buf)
830 const uint8_t *start, *next, *end = track->vos_data + track->vos_len;
831 int unescaped_size, seq_found = 0;
832 int level = 0, interlace = 0;
833 int packet_seq = track->vc1_info.packet_seq;
834 int packet_entry = track->vc1_info.packet_entry;
835 int slices = track->vc1_info.slices;
838 if (track->start_dts == AV_NOPTS_VALUE) {
839 /* No packets written yet, vc1_info isn't authoritative yet. */
840 /* Assume inline sequence and entry headers. */
841 packet_seq = packet_entry = 1;
842 av_log(NULL, AV_LOG_WARNING,
843 "moov atom written before any packets, unable to write correct "
844 "dvc1 atom. Set the delay_moov flag to fix this.\n");
847 unescaped = av_mallocz(track->vos_len + AV_INPUT_BUFFER_PADDING_SIZE);
849 return AVERROR(ENOMEM);
850 start = find_next_marker(track->vos_data, end);
851 for (next = start; next < end; start = next) {
854 next = find_next_marker(start + 4, end);
855 size = next - start - 4;
858 unescaped_size = vc1_unescape_buffer(start + 4, size, unescaped);
859 init_get_bits(&gb, unescaped, 8 * unescaped_size);
860 if (AV_RB32(start) == VC1_CODE_SEQHDR) {
861 int profile = get_bits(&gb, 2);
862 if (profile != PROFILE_ADVANCED) {
864 return AVERROR(ENOSYS);
867 level = get_bits(&gb, 3);
868 /* chromaformat, frmrtq_postproc, bitrtq_postproc, postprocflag,
870 skip_bits_long(&gb, 2 + 3 + 5 + 1 + 2*12);
871 skip_bits(&gb, 1); /* broadcast */
872 interlace = get_bits1(&gb);
873 skip_bits(&gb, 4); /* tfcntrflag, finterpflag, reserved, psf */
878 return AVERROR(ENOSYS);
881 init_put_bits(&pbc, buf, 7);
882 /* VC1DecSpecStruc */
883 put_bits(&pbc, 4, 12); /* profile - advanced */
884 put_bits(&pbc, 3, level);
885 put_bits(&pbc, 1, 0); /* reserved */
886 /* VC1AdvDecSpecStruc */
887 put_bits(&pbc, 3, level);
888 put_bits(&pbc, 1, 0); /* cbr */
889 put_bits(&pbc, 6, 0); /* reserved */
890 put_bits(&pbc, 1, !interlace); /* no interlace */
891 put_bits(&pbc, 1, !packet_seq); /* no multiple seq */
892 put_bits(&pbc, 1, !packet_entry); /* no multiple entry */
893 put_bits(&pbc, 1, !slices); /* no slice code */
894 put_bits(&pbc, 1, 0); /* no bframe */
895 put_bits(&pbc, 1, 0); /* reserved */
898 if (track->st->avg_frame_rate.num > 0 && track->st->avg_frame_rate.den > 0)
899 put_bits32(&pbc, track->st->avg_frame_rate.num / track->st->avg_frame_rate.den);
901 put_bits32(&pbc, 0xffffffff);
903 flush_put_bits(&pbc);
910 static int mov_write_dvc1_tag(AVIOContext *pb, MOVTrack *track)
912 uint8_t buf[7] = { 0 };
915 if ((ret = mov_write_dvc1_structs(track, buf)) < 0)
918 avio_wb32(pb, track->vos_len + 8 + sizeof(buf));
919 ffio_wfourcc(pb, "dvc1");
920 avio_write(pb, buf, sizeof(buf));
921 avio_write(pb, track->vos_data, track->vos_len);
926 static int mov_write_glbl_tag(AVIOContext *pb, MOVTrack *track)
928 avio_wb32(pb, track->vos_len + 8);
929 ffio_wfourcc(pb, "glbl");
930 avio_write(pb, track->vos_data, track->vos_len);
931 return 8 + track->vos_len;
935 * Compute flags for 'lpcm' tag.
936 * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
938 static int mov_get_lpcm_flags(enum AVCodecID codec_id)
941 case AV_CODEC_ID_PCM_F32BE:
942 case AV_CODEC_ID_PCM_F64BE:
944 case AV_CODEC_ID_PCM_F32LE:
945 case AV_CODEC_ID_PCM_F64LE:
947 case AV_CODEC_ID_PCM_U8:
949 case AV_CODEC_ID_PCM_S16BE:
950 case AV_CODEC_ID_PCM_S24BE:
951 case AV_CODEC_ID_PCM_S32BE:
953 case AV_CODEC_ID_PCM_S8:
954 case AV_CODEC_ID_PCM_S16LE:
955 case AV_CODEC_ID_PCM_S24LE:
956 case AV_CODEC_ID_PCM_S32LE:
963 static int get_cluster_duration(MOVTrack *track, int cluster_idx)
967 if (cluster_idx >= track->entry)
970 if (cluster_idx + 1 == track->entry)
971 next_dts = track->track_duration + track->start_dts;
973 next_dts = track->cluster[cluster_idx + 1].dts;
975 next_dts -= track->cluster[cluster_idx].dts;
977 av_assert0(next_dts >= 0);
978 av_assert0(next_dts <= INT_MAX);
983 static int get_samples_per_packet(MOVTrack *track)
985 int i, first_duration;
987 // return track->par->frame_size;
989 /* use 1 for raw PCM */
990 if (!track->audio_vbr)
993 /* check to see if duration is constant for all clusters */
996 first_duration = get_cluster_duration(track, 0);
997 for (i = 1; i < track->entry; i++) {
998 if (get_cluster_duration(track, i) != first_duration)
1001 return first_duration;
1004 static int mov_write_audio_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
1006 int64_t pos = avio_tell(pb);
1008 uint32_t tag = track->tag;
1010 if (track->mode == MODE_MOV) {
1011 if (track->timescale > UINT16_MAX) {
1012 if (mov_get_lpcm_flags(track->par->codec_id))
1013 tag = AV_RL32("lpcm");
1015 } else if (track->audio_vbr || mov_pcm_le_gt16(track->par->codec_id) ||
1016 mov_pcm_be_gt16(track->par->codec_id) ||
1017 track->par->codec_id == AV_CODEC_ID_ADPCM_MS ||
1018 track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
1019 track->par->codec_id == AV_CODEC_ID_QDM2) {
1024 avio_wb32(pb, 0); /* size */
1025 if (mov->encryption_scheme != MOV_ENC_NONE) {
1026 ffio_wfourcc(pb, "enca");
1028 avio_wl32(pb, tag); // store it byteswapped
1030 avio_wb32(pb, 0); /* Reserved */
1031 avio_wb16(pb, 0); /* Reserved */
1032 avio_wb16(pb, 1); /* Data-reference index, XXX == 1 */
1034 /* SoundDescription */
1035 avio_wb16(pb, version); /* Version */
1036 avio_wb16(pb, 0); /* Revision level */
1037 avio_wb32(pb, 0); /* Reserved */
1042 avio_wb16(pb, 0xfffe);
1044 avio_wb32(pb, 0x00010000);
1046 avio_wb64(pb, av_double2int(track->par->sample_rate));
1047 avio_wb32(pb, track->par->channels);
1048 avio_wb32(pb, 0x7F000000);
1049 avio_wb32(pb, av_get_bits_per_sample(track->par->codec_id));
1050 avio_wb32(pb, mov_get_lpcm_flags(track->par->codec_id));
1051 avio_wb32(pb, track->sample_size);
1052 avio_wb32(pb, get_samples_per_packet(track));
1054 if (track->mode == MODE_MOV) {
1055 avio_wb16(pb, track->par->channels);
1056 if (track->par->codec_id == AV_CODEC_ID_PCM_U8 ||
1057 track->par->codec_id == AV_CODEC_ID_PCM_S8)
1058 avio_wb16(pb, 8); /* bits per sample */
1059 else if (track->par->codec_id == AV_CODEC_ID_ADPCM_G726)
1060 avio_wb16(pb, track->par->bits_per_coded_sample);
1063 avio_wb16(pb, track->audio_vbr ? -2 : 0); /* compression ID */
1064 } else { /* reserved for mp4/3gp */
1065 if (track->par->codec_id == AV_CODEC_ID_FLAC ||
1066 track->par->codec_id == AV_CODEC_ID_OPUS) {
1067 avio_wb16(pb, track->par->channels);
1071 if (track->par->codec_id == AV_CODEC_ID_FLAC) {
1072 avio_wb16(pb, track->par->bits_per_raw_sample);
1079 avio_wb16(pb, 0); /* packet size (= 0) */
1080 if (track->par->codec_id == AV_CODEC_ID_OPUS)
1081 avio_wb16(pb, 48000);
1083 avio_wb16(pb, track->par->sample_rate <= UINT16_MAX ?
1084 track->par->sample_rate : 0);
1085 avio_wb16(pb, 0); /* Reserved */
1088 if (version == 1) { /* SoundDescription V1 extended info */
1089 if (mov_pcm_le_gt16(track->par->codec_id) ||
1090 mov_pcm_be_gt16(track->par->codec_id))
1091 avio_wb32(pb, 1); /* must be 1 for uncompressed formats */
1093 avio_wb32(pb, track->par->frame_size); /* Samples per packet */
1094 avio_wb32(pb, track->sample_size / track->par->channels); /* Bytes per packet */
1095 avio_wb32(pb, track->sample_size); /* Bytes per frame */
1096 avio_wb32(pb, 2); /* Bytes per sample */
1099 if (track->mode == MODE_MOV &&
1100 (track->par->codec_id == AV_CODEC_ID_AAC ||
1101 track->par->codec_id == AV_CODEC_ID_AC3 ||
1102 track->par->codec_id == AV_CODEC_ID_EAC3 ||
1103 track->par->codec_id == AV_CODEC_ID_AMR_NB ||
1104 track->par->codec_id == AV_CODEC_ID_ALAC ||
1105 track->par->codec_id == AV_CODEC_ID_ADPCM_MS ||
1106 track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
1107 track->par->codec_id == AV_CODEC_ID_QDM2 ||
1108 (mov_pcm_le_gt16(track->par->codec_id) && version==1) ||
1109 (mov_pcm_be_gt16(track->par->codec_id) && version==1)))
1110 mov_write_wave_tag(s, pb, track);
1111 else if (track->tag == MKTAG('m','p','4','a'))
1112 mov_write_esds_tag(pb, track);
1113 else if (track->par->codec_id == AV_CODEC_ID_AMR_NB)
1114 mov_write_amr_tag(pb, track);
1115 else if (track->par->codec_id == AV_CODEC_ID_AC3)
1116 mov_write_ac3_tag(pb, track);
1117 else if (track->par->codec_id == AV_CODEC_ID_EAC3)
1118 mov_write_eac3_tag(pb, track);
1119 else if (track->par->codec_id == AV_CODEC_ID_ALAC)
1120 mov_write_extradata_tag(pb, track);
1121 else if (track->par->codec_id == AV_CODEC_ID_WMAPRO)
1122 mov_write_wfex_tag(s, pb, track);
1123 else if (track->par->codec_id == AV_CODEC_ID_FLAC)
1124 mov_write_dfla_tag(pb, track);
1125 else if (track->par->codec_id == AV_CODEC_ID_OPUS)
1126 mov_write_dops_tag(pb, track);
1127 else if (track->vos_len > 0)
1128 mov_write_glbl_tag(pb, track);
1130 if (track->mode == MODE_MOV && track->par->codec_type == AVMEDIA_TYPE_AUDIO)
1131 mov_write_chan_tag(s, pb, track);
1133 if (mov->encryption_scheme != MOV_ENC_NONE) {
1134 ff_mov_cenc_write_sinf_tag(track, pb, mov->encryption_kid);
1137 return update_size(pb, pos);
1140 static int mov_write_d263_tag(AVIOContext *pb)
1142 avio_wb32(pb, 0xf); /* size */
1143 ffio_wfourcc(pb, "d263");
1144 ffio_wfourcc(pb, "FFMP");
1145 avio_w8(pb, 0); /* decoder version */
1146 /* FIXME use AVCodecContext level/profile, when encoder will set values */
1147 avio_w8(pb, 0xa); /* level */
1148 avio_w8(pb, 0); /* profile */
1152 static int mov_write_avcc_tag(AVIOContext *pb, MOVTrack *track)
1154 int64_t pos = avio_tell(pb);
1157 ffio_wfourcc(pb, "avcC");
1158 ff_isom_write_avcc(pb, track->vos_data, track->vos_len);
1159 return update_size(pb, pos);
1162 static int mov_write_vpcc_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
1164 int64_t pos = avio_tell(pb);
1167 ffio_wfourcc(pb, "vpcC");
1168 avio_w8(pb, 1); /* version */
1169 avio_wb24(pb, 0); /* flags */
1170 ff_isom_write_vpcc(s, pb, track->par);
1171 return update_size(pb, pos);
1174 static int mov_write_hvcc_tag(AVIOContext *pb, MOVTrack *track)
1176 int64_t pos = avio_tell(pb);
1179 ffio_wfourcc(pb, "hvcC");
1180 if (track->tag == MKTAG('h','v','c','1'))
1181 ff_isom_write_hvcc(pb, track->vos_data, track->vos_len, 1);
1183 ff_isom_write_hvcc(pb, track->vos_data, track->vos_len, 0);
1184 return update_size(pb, pos);
1187 /* also used by all avid codecs (dv, imx, meridien) and their variants */
1188 static int mov_write_avid_tag(AVIOContext *pb, MOVTrack *track)
1193 int display_width = track->par->width;
1195 if (track->vos_data && track->vos_len > 0x29) {
1196 if (ff_dnxhd_parse_header_prefix(track->vos_data) != 0) {
1197 /* looks like a DNxHD bit stream */
1198 interlaced = (track->vos_data[5] & 2);
1199 cid = AV_RB32(track->vos_data + 0x28);
1201 av_log(NULL, AV_LOG_WARNING, "Could not locate DNxHD bit stream in vos_data\n");
1205 av_log(NULL, AV_LOG_WARNING, "Could not locate DNxHD bit stream, vos_data too small\n");
1209 avio_wb32(pb, 24); /* size */
1210 ffio_wfourcc(pb, "ACLR");
1211 ffio_wfourcc(pb, "ACLR");
1212 ffio_wfourcc(pb, "0001");
1213 if (track->par->color_range == AVCOL_RANGE_MPEG || /* Legal range (16-235) */
1214 track->par->color_range == AVCOL_RANGE_UNSPECIFIED) {
1215 avio_wb32(pb, 1); /* Corresponds to 709 in official encoder */
1216 } else { /* Full range (0-255) */
1217 avio_wb32(pb, 2); /* Corresponds to RGB in official encoder */
1219 avio_wb32(pb, 0); /* unknown */
1221 if (track->tag == MKTAG('A','V','d','h')) {
1223 ffio_wfourcc(pb, "ADHR");
1224 ffio_wfourcc(pb, "0001");
1226 avio_wb32(pb, 0); /* unknown */
1227 avio_wb32(pb, 1); /* unknown */
1228 avio_wb32(pb, 0); /* unknown */
1229 avio_wb32(pb, 0); /* unknown */
1233 avio_wb32(pb, 24); /* size */
1234 ffio_wfourcc(pb, "APRG");
1235 ffio_wfourcc(pb, "APRG");
1236 ffio_wfourcc(pb, "0001");
1237 avio_wb32(pb, 1); /* unknown */
1238 avio_wb32(pb, 0); /* unknown */
1240 avio_wb32(pb, 120); /* size */
1241 ffio_wfourcc(pb, "ARES");
1242 ffio_wfourcc(pb, "ARES");
1243 ffio_wfourcc(pb, "0001");
1244 avio_wb32(pb, cid); /* dnxhd cid, some id ? */
1245 if ( track->par->sample_aspect_ratio.num > 0
1246 && track->par->sample_aspect_ratio.den > 0)
1247 display_width = display_width * track->par->sample_aspect_ratio.num / track->par->sample_aspect_ratio.den;
1248 avio_wb32(pb, display_width);
1249 /* values below are based on samples created with quicktime and avid codecs */
1251 avio_wb32(pb, track->par->height / 2);
1252 avio_wb32(pb, 2); /* unknown */
1253 avio_wb32(pb, 0); /* unknown */
1254 avio_wb32(pb, 4); /* unknown */
1256 avio_wb32(pb, track->par->height);
1257 avio_wb32(pb, 1); /* unknown */
1258 avio_wb32(pb, 0); /* unknown */
1259 if (track->par->height == 1080)
1260 avio_wb32(pb, 5); /* unknown */
1262 avio_wb32(pb, 6); /* unknown */
1265 for (i = 0; i < 10; i++)
1271 static int mov_write_dpxe_tag(AVIOContext *pb, MOVTrack *track)
1274 ffio_wfourcc(pb, "DpxE");
1275 if (track->par->extradata_size >= 12 &&
1276 !memcmp(&track->par->extradata[4], "DpxE", 4)) {
1277 avio_wb32(pb, track->par->extradata[11]);
1284 static int mov_get_dv_codec_tag(AVFormatContext *s, MOVTrack *track)
1288 if (track->par->width == 720) { /* SD */
1289 if (track->par->height == 480) { /* NTSC */
1290 if (track->par->format == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','n');
1291 else tag = MKTAG('d','v','c',' ');
1292 }else if (track->par->format == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','p');
1293 else if (track->par->format == AV_PIX_FMT_YUV420P) tag = MKTAG('d','v','c','p');
1294 else tag = MKTAG('d','v','p','p');
1295 } else if (track->par->height == 720) { /* HD 720 line */
1296 if (track->st->time_base.den == 50) tag = MKTAG('d','v','h','q');
1297 else tag = MKTAG('d','v','h','p');
1298 } else if (track->par->height == 1080) { /* HD 1080 line */
1299 if (track->st->time_base.den == 25) tag = MKTAG('d','v','h','5');
1300 else tag = MKTAG('d','v','h','6');
1302 av_log(s, AV_LOG_ERROR, "unsupported height for dv codec\n");
1309 static AVRational find_fps(AVFormatContext *s, AVStream *st)
1311 AVRational rate = st->avg_frame_rate;
1313 #if FF_API_LAVF_AVCTX
1314 FF_DISABLE_DEPRECATION_WARNINGS
1315 rate = av_inv_q(st->codec->time_base);
1316 if (av_timecode_check_frame_rate(rate) < 0) {
1317 av_log(s, AV_LOG_DEBUG, "timecode: tbc=%d/%d invalid, fallback on %d/%d\n",
1318 rate.num, rate.den, st->avg_frame_rate.num, st->avg_frame_rate.den);
1319 rate = st->avg_frame_rate;
1321 FF_ENABLE_DEPRECATION_WARNINGS
1327 static int defined_frame_rate(AVFormatContext *s, AVStream *st)
1329 AVRational rational_framerate = find_fps(s, st);
1331 if (rational_framerate.den != 0)
1332 rate = av_q2d(rational_framerate);
1336 static int mov_get_mpeg2_xdcam_codec_tag(AVFormatContext *s, MOVTrack *track)
1338 int tag = track->par->codec_tag;
1339 int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE;
1340 AVStream *st = track->st;
1341 int rate = defined_frame_rate(s, st);
1344 tag = MKTAG('m', '2', 'v', '1'); //fallback tag
1346 if (track->par->format == AV_PIX_FMT_YUV420P) {
1347 if (track->par->width == 1280 && track->par->height == 720) {
1349 if (rate == 24) tag = MKTAG('x','d','v','4');
1350 else if (rate == 25) tag = MKTAG('x','d','v','5');
1351 else if (rate == 30) tag = MKTAG('x','d','v','1');
1352 else if (rate == 50) tag = MKTAG('x','d','v','a');
1353 else if (rate == 60) tag = MKTAG('x','d','v','9');
1355 } else if (track->par->width == 1440 && track->par->height == 1080) {
1357 if (rate == 24) tag = MKTAG('x','d','v','6');
1358 else if (rate == 25) tag = MKTAG('x','d','v','7');
1359 else if (rate == 30) tag = MKTAG('x','d','v','8');
1361 if (rate == 25) tag = MKTAG('x','d','v','3');
1362 else if (rate == 30) tag = MKTAG('x','d','v','2');
1364 } else if (track->par->width == 1920 && track->par->height == 1080) {
1366 if (rate == 24) tag = MKTAG('x','d','v','d');
1367 else if (rate == 25) tag = MKTAG('x','d','v','e');
1368 else if (rate == 30) tag = MKTAG('x','d','v','f');
1370 if (rate == 25) tag = MKTAG('x','d','v','c');
1371 else if (rate == 30) tag = MKTAG('x','d','v','b');
1374 } else if (track->par->format == AV_PIX_FMT_YUV422P) {
1375 if (track->par->width == 1280 && track->par->height == 720) {
1377 if (rate == 24) tag = MKTAG('x','d','5','4');
1378 else if (rate == 25) tag = MKTAG('x','d','5','5');
1379 else if (rate == 30) tag = MKTAG('x','d','5','1');
1380 else if (rate == 50) tag = MKTAG('x','d','5','a');
1381 else if (rate == 60) tag = MKTAG('x','d','5','9');
1383 } else if (track->par->width == 1920 && track->par->height == 1080) {
1385 if (rate == 24) tag = MKTAG('x','d','5','d');
1386 else if (rate == 25) tag = MKTAG('x','d','5','e');
1387 else if (rate == 30) tag = MKTAG('x','d','5','f');
1389 if (rate == 25) tag = MKTAG('x','d','5','c');
1390 else if (rate == 30) tag = MKTAG('x','d','5','b');
1398 static int mov_get_h264_codec_tag(AVFormatContext *s, MOVTrack *track)
1400 int tag = track->par->codec_tag;
1401 int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE;
1402 AVStream *st = track->st;
1403 int rate = defined_frame_rate(s, st);
1406 tag = MKTAG('a', 'v', 'c', 'i'); //fallback tag
1408 if (track->par->format == AV_PIX_FMT_YUV420P10) {
1409 if (track->par->width == 960 && track->par->height == 720) {
1411 if (rate == 24) tag = MKTAG('a','i','5','p');
1412 else if (rate == 25) tag = MKTAG('a','i','5','q');
1413 else if (rate == 30) tag = MKTAG('a','i','5','p');
1414 else if (rate == 50) tag = MKTAG('a','i','5','q');
1415 else if (rate == 60) tag = MKTAG('a','i','5','p');
1417 } else if (track->par->width == 1440 && track->par->height == 1080) {
1419 if (rate == 24) tag = MKTAG('a','i','5','3');
1420 else if (rate == 25) tag = MKTAG('a','i','5','2');
1421 else if (rate == 30) tag = MKTAG('a','i','5','3');
1423 if (rate == 50) tag = MKTAG('a','i','5','5');
1424 else if (rate == 60) tag = MKTAG('a','i','5','6');
1427 } else if (track->par->format == AV_PIX_FMT_YUV422P10) {
1428 if (track->par->width == 1280 && track->par->height == 720) {
1430 if (rate == 24) tag = MKTAG('a','i','1','p');
1431 else if (rate == 25) tag = MKTAG('a','i','1','q');
1432 else if (rate == 30) tag = MKTAG('a','i','1','p');
1433 else if (rate == 50) tag = MKTAG('a','i','1','q');
1434 else if (rate == 60) tag = MKTAG('a','i','1','p');
1436 } else if (track->par->width == 1920 && track->par->height == 1080) {
1438 if (rate == 24) tag = MKTAG('a','i','1','3');
1439 else if (rate == 25) tag = MKTAG('a','i','1','2');
1440 else if (rate == 30) tag = MKTAG('a','i','1','3');
1442 if (rate == 25) tag = MKTAG('a','i','1','5');
1443 else if (rate == 50) tag = MKTAG('a','i','1','5');
1444 else if (rate == 60) tag = MKTAG('a','i','1','6');
1446 } else if ( track->par->width == 4096 && track->par->height == 2160
1447 || track->par->width == 3840 && track->par->height == 2160
1448 || track->par->width == 2048 && track->par->height == 1080) {
1449 tag = MKTAG('a','i','v','x');
1456 static const struct {
1457 enum AVPixelFormat pix_fmt;
1460 } mov_pix_fmt_tags[] = {
1461 { AV_PIX_FMT_YUYV422, MKTAG('y','u','v','2'), 0 },
1462 { AV_PIX_FMT_YUYV422, MKTAG('y','u','v','s'), 0 },
1463 { AV_PIX_FMT_UYVY422, MKTAG('2','v','u','y'), 0 },
1464 { AV_PIX_FMT_RGB555BE,MKTAG('r','a','w',' '), 16 },
1465 { AV_PIX_FMT_RGB555LE,MKTAG('L','5','5','5'), 16 },
1466 { AV_PIX_FMT_RGB565LE,MKTAG('L','5','6','5'), 16 },
1467 { AV_PIX_FMT_RGB565BE,MKTAG('B','5','6','5'), 16 },
1468 { AV_PIX_FMT_GRAY16BE,MKTAG('b','1','6','g'), 16 },
1469 { AV_PIX_FMT_RGB24, MKTAG('r','a','w',' '), 24 },
1470 { AV_PIX_FMT_BGR24, MKTAG('2','4','B','G'), 24 },
1471 { AV_PIX_FMT_ARGB, MKTAG('r','a','w',' '), 32 },
1472 { AV_PIX_FMT_BGRA, MKTAG('B','G','R','A'), 32 },
1473 { AV_PIX_FMT_RGBA, MKTAG('R','G','B','A'), 32 },
1474 { AV_PIX_FMT_ABGR, MKTAG('A','B','G','R'), 32 },
1475 { AV_PIX_FMT_RGB48BE, MKTAG('b','4','8','r'), 48 },
1478 static int mov_get_dnxhd_codec_tag(AVFormatContext *s, MOVTrack *track)
1480 int tag = MKTAG('A','V','d','n');
1481 if (track->par->profile != FF_PROFILE_UNKNOWN &&
1482 track->par->profile != FF_PROFILE_DNXHD)
1483 tag = MKTAG('A','V','d','h');
1487 static int mov_get_rawvideo_codec_tag(AVFormatContext *s, MOVTrack *track)
1489 int tag = track->par->codec_tag;
1491 enum AVPixelFormat pix_fmt;
1493 for (i = 0; i < FF_ARRAY_ELEMS(mov_pix_fmt_tags); i++) {
1494 if (track->par->format == mov_pix_fmt_tags[i].pix_fmt) {
1495 tag = mov_pix_fmt_tags[i].tag;
1496 track->par->bits_per_coded_sample = mov_pix_fmt_tags[i].bps;
1497 if (track->par->codec_tag == mov_pix_fmt_tags[i].tag)
1502 pix_fmt = avpriv_find_pix_fmt(avpriv_pix_fmt_bps_mov,
1503 track->par->bits_per_coded_sample);
1504 if (tag == MKTAG('r','a','w',' ') &&
1505 track->par->format != pix_fmt &&
1506 track->par->format != AV_PIX_FMT_GRAY8 &&
1507 track->par->format != AV_PIX_FMT_NONE)
1508 av_log(s, AV_LOG_ERROR, "%s rawvideo cannot be written to mov, output file will be unreadable\n",
1509 av_get_pix_fmt_name(track->par->format));
1513 static int mov_get_codec_tag(AVFormatContext *s, MOVTrack *track)
1515 int tag = track->par->codec_tag;
1517 if (!tag || (s->strict_std_compliance >= FF_COMPLIANCE_NORMAL &&
1518 (track->par->codec_id == AV_CODEC_ID_DVVIDEO ||
1519 track->par->codec_id == AV_CODEC_ID_RAWVIDEO ||
1520 track->par->codec_id == AV_CODEC_ID_H263 ||
1521 track->par->codec_id == AV_CODEC_ID_H264 ||
1522 track->par->codec_id == AV_CODEC_ID_DNXHD ||
1523 track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO ||
1524 av_get_bits_per_sample(track->par->codec_id)))) { // pcm audio
1525 if (track->par->codec_id == AV_CODEC_ID_DVVIDEO)
1526 tag = mov_get_dv_codec_tag(s, track);
1527 else if (track->par->codec_id == AV_CODEC_ID_RAWVIDEO)
1528 tag = mov_get_rawvideo_codec_tag(s, track);
1529 else if (track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO)
1530 tag = mov_get_mpeg2_xdcam_codec_tag(s, track);
1531 else if (track->par->codec_id == AV_CODEC_ID_H264)
1532 tag = mov_get_h264_codec_tag(s, track);
1533 else if (track->par->codec_id == AV_CODEC_ID_DNXHD)
1534 tag = mov_get_dnxhd_codec_tag(s, track);
1535 else if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
1536 tag = ff_codec_get_tag(ff_codec_movvideo_tags, track->par->codec_id);
1537 if (!tag) { // if no mac fcc found, try with Microsoft tags
1538 tag = ff_codec_get_tag(ff_codec_bmp_tags, track->par->codec_id);
1540 av_log(s, AV_LOG_WARNING, "Using MS style video codec tag, "
1541 "the file may be unplayable!\n");
1543 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
1544 tag = ff_codec_get_tag(ff_codec_movaudio_tags, track->par->codec_id);
1545 if (!tag) { // if no mac fcc found, try with Microsoft tags
1546 int ms_tag = ff_codec_get_tag(ff_codec_wav_tags, track->par->codec_id);
1548 tag = MKTAG('m', 's', ((ms_tag >> 8) & 0xff), (ms_tag & 0xff));
1549 av_log(s, AV_LOG_WARNING, "Using MS style audio codec tag, "
1550 "the file may be unplayable!\n");
1553 } else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)
1554 tag = ff_codec_get_tag(ff_codec_movsubtitle_tags, track->par->codec_id);
1560 static int mov_find_codec_tag(AVFormatContext *s, MOVTrack *track)
1564 if (track->mode == MODE_MP4 || track->mode == MODE_PSP)
1565 tag = track->par->codec_tag;
1566 else if (track->mode == MODE_ISM)
1567 tag = track->par->codec_tag;
1568 else if (track->mode == MODE_IPOD) {
1569 if (!av_match_ext(s->url, "m4a") &&
1570 !av_match_ext(s->url, "m4v") &&
1571 !av_match_ext(s->url, "m4b"))
1572 av_log(s, AV_LOG_WARNING, "Warning, extension is not .m4a nor .m4v "
1573 "Quicktime/Ipod might not play the file\n");
1574 tag = track->par->codec_tag;
1575 } else if (track->mode & MODE_3GP)
1576 tag = track->par->codec_tag;
1577 else if (track->mode == MODE_F4V)
1578 tag = track->par->codec_tag;
1580 tag = mov_get_codec_tag(s, track);
1585 /** Write uuid atom.
1586 * Needed to make file play in iPods running newest firmware
1587 * goes after avcC atom in moov.trak.mdia.minf.stbl.stsd.avc1
1589 static int mov_write_uuid_tag_ipod(AVIOContext *pb)
1592 ffio_wfourcc(pb, "uuid");
1593 avio_wb32(pb, 0x6b6840f2);
1594 avio_wb32(pb, 0x5f244fc5);
1595 avio_wb32(pb, 0xba39a51b);
1596 avio_wb32(pb, 0xcf0323f3);
1601 static const uint16_t fiel_data[] = {
1602 0x0000, 0x0100, 0x0201, 0x0206, 0x0209, 0x020e
1605 static int mov_write_fiel_tag(AVIOContext *pb, MOVTrack *track, int field_order)
1607 unsigned mov_field_order = 0;
1608 if (field_order < FF_ARRAY_ELEMS(fiel_data))
1609 mov_field_order = fiel_data[field_order];
1613 ffio_wfourcc(pb, "fiel");
1614 avio_wb16(pb, mov_field_order);
1618 static int mov_write_subtitle_tag(AVIOContext *pb, MOVTrack *track)
1620 int64_t pos = avio_tell(pb);
1621 avio_wb32(pb, 0); /* size */
1622 avio_wl32(pb, track->tag); // store it byteswapped
1623 avio_wb32(pb, 0); /* Reserved */
1624 avio_wb16(pb, 0); /* Reserved */
1625 avio_wb16(pb, 1); /* Data-reference index */
1627 if (track->par->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
1628 mov_write_esds_tag(pb, track);
1629 else if (track->par->extradata_size)
1630 avio_write(pb, track->par->extradata, track->par->extradata_size);
1632 return update_size(pb, pos);
1635 static int mov_write_st3d_tag(AVIOContext *pb, AVStereo3D *stereo_3d)
1639 if (stereo_3d->flags != 0) {
1640 av_log(pb, AV_LOG_WARNING, "Unsupported stereo_3d flags %x. st3d not written.\n", stereo_3d->flags);
1644 switch (stereo_3d->type) {
1645 case AV_STEREO3D_2D:
1648 case AV_STEREO3D_TOPBOTTOM:
1651 case AV_STEREO3D_SIDEBYSIDE:
1655 av_log(pb, AV_LOG_WARNING, "Unsupported stereo_3d type %s. st3d not written.\n", av_stereo3d_type_name(stereo_3d->type));
1658 avio_wb32(pb, 13); /* size */
1659 ffio_wfourcc(pb, "st3d");
1660 avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1661 avio_w8(pb, stereo_mode);
1665 static int mov_write_sv3d_tag(AVFormatContext *s, AVIOContext *pb, AVSphericalMapping *spherical_mapping)
1667 int64_t sv3d_pos, svhd_pos, proj_pos;
1668 const char* metadata_source = s->flags & AVFMT_FLAG_BITEXACT ? "Lavf" : LIBAVFORMAT_IDENT;
1670 if (spherical_mapping->projection != AV_SPHERICAL_EQUIRECTANGULAR &&
1671 spherical_mapping->projection != AV_SPHERICAL_EQUIRECTANGULAR_TILE &&
1672 spherical_mapping->projection != AV_SPHERICAL_CUBEMAP) {
1673 av_log(pb, AV_LOG_WARNING, "Unsupported projection %d. sv3d not written.\n", spherical_mapping->projection);
1677 sv3d_pos = avio_tell(pb);
1678 avio_wb32(pb, 0); /* size */
1679 ffio_wfourcc(pb, "sv3d");
1681 svhd_pos = avio_tell(pb);
1682 avio_wb32(pb, 0); /* size */
1683 ffio_wfourcc(pb, "svhd");
1684 avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1685 avio_put_str(pb, metadata_source);
1686 update_size(pb, svhd_pos);
1688 proj_pos = avio_tell(pb);
1689 avio_wb32(pb, 0); /* size */
1690 ffio_wfourcc(pb, "proj");
1692 avio_wb32(pb, 24); /* size */
1693 ffio_wfourcc(pb, "prhd");
1694 avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1695 avio_wb32(pb, spherical_mapping->yaw);
1696 avio_wb32(pb, spherical_mapping->pitch);
1697 avio_wb32(pb, spherical_mapping->roll);
1699 switch (spherical_mapping->projection) {
1700 case AV_SPHERICAL_EQUIRECTANGULAR:
1701 case AV_SPHERICAL_EQUIRECTANGULAR_TILE:
1702 avio_wb32(pb, 28); /* size */
1703 ffio_wfourcc(pb, "equi");
1704 avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1705 avio_wb32(pb, spherical_mapping->bound_top);
1706 avio_wb32(pb, spherical_mapping->bound_bottom);
1707 avio_wb32(pb, spherical_mapping->bound_left);
1708 avio_wb32(pb, spherical_mapping->bound_right);
1710 case AV_SPHERICAL_CUBEMAP:
1711 avio_wb32(pb, 20); /* size */
1712 ffio_wfourcc(pb, "cbmp");
1713 avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1714 avio_wb32(pb, 0); /* layout */
1715 avio_wb32(pb, spherical_mapping->padding); /* padding */
1718 update_size(pb, proj_pos);
1720 return update_size(pb, sv3d_pos);
1723 static int mov_write_clap_tag(AVIOContext *pb, MOVTrack *track)
1726 ffio_wfourcc(pb, "clap");
1727 avio_wb32(pb, track->par->width); /* apertureWidth_N */
1728 avio_wb32(pb, 1); /* apertureWidth_D (= 1) */
1729 avio_wb32(pb, track->height); /* apertureHeight_N */
1730 avio_wb32(pb, 1); /* apertureHeight_D (= 1) */
1731 avio_wb32(pb, 0); /* horizOff_N (= 0) */
1732 avio_wb32(pb, 1); /* horizOff_D (= 1) */
1733 avio_wb32(pb, 0); /* vertOff_N (= 0) */
1734 avio_wb32(pb, 1); /* vertOff_D (= 1) */
1738 static int mov_write_pasp_tag(AVIOContext *pb, MOVTrack *track)
1741 av_reduce(&sar.num, &sar.den, track->par->sample_aspect_ratio.num,
1742 track->par->sample_aspect_ratio.den, INT_MAX);
1745 ffio_wfourcc(pb, "pasp");
1746 avio_wb32(pb, sar.num);
1747 avio_wb32(pb, sar.den);
1751 static int mov_write_gama_tag(AVIOContext *pb, MOVTrack *track, double gamma)
1756 gamma = avpriv_get_gamma_from_trc(track->par->color_trc);
1758 av_log(pb, AV_LOG_DEBUG, "gamma value %g\n", gamma);
1761 gama = (uint32_t)lrint((double)(1<<16) * gamma);
1762 av_log(pb, AV_LOG_DEBUG, "writing gama value %"PRId32"\n", gama);
1764 av_assert0(track->mode == MODE_MOV);
1766 ffio_wfourcc(pb, "gama");
1767 avio_wb32(pb, gama);
1771 av_log(pb, AV_LOG_WARNING, "gamma value unknown, unable to write gama atom\n");
1776 static int mov_write_colr_tag(AVIOContext *pb, MOVTrack *track)
1778 // Ref (MOV): https://developer.apple.com/library/mac/technotes/tn2162/_index.html#//apple_ref/doc/uid/DTS40013070-CH1-TNTAG9
1779 // Ref (MP4): ISO/IEC 14496-12:2012
1781 if (track->par->color_primaries == AVCOL_PRI_UNSPECIFIED &&
1782 track->par->color_trc == AVCOL_TRC_UNSPECIFIED &&
1783 track->par->color_space == AVCOL_SPC_UNSPECIFIED) {
1784 if ((track->par->width >= 1920 && track->par->height >= 1080)
1785 || (track->par->width == 1280 && track->par->height == 720)) {
1786 av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming bt709\n");
1787 track->par->color_primaries = AVCOL_PRI_BT709;
1788 } else if (track->par->width == 720 && track->height == 576) {
1789 av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming bt470bg\n");
1790 track->par->color_primaries = AVCOL_PRI_BT470BG;
1791 } else if (track->par->width == 720 &&
1792 (track->height == 486 || track->height == 480)) {
1793 av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming smpte170\n");
1794 track->par->color_primaries = AVCOL_PRI_SMPTE170M;
1796 av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, unable to assume anything\n");
1798 switch (track->par->color_primaries) {
1799 case AVCOL_PRI_BT709:
1800 track->par->color_trc = AVCOL_TRC_BT709;
1801 track->par->color_space = AVCOL_SPC_BT709;
1803 case AVCOL_PRI_SMPTE170M:
1804 case AVCOL_PRI_BT470BG:
1805 track->par->color_trc = AVCOL_TRC_BT709;
1806 track->par->color_space = AVCOL_SPC_SMPTE170M;
1811 /* We should only ever be called by MOV or MP4. */
1812 av_assert0(track->mode == MODE_MOV || track->mode == MODE_MP4);
1814 avio_wb32(pb, 18 + (track->mode == MODE_MP4));
1815 ffio_wfourcc(pb, "colr");
1816 if (track->mode == MODE_MP4)
1817 ffio_wfourcc(pb, "nclx");
1819 ffio_wfourcc(pb, "nclc");
1820 switch (track->par->color_primaries) {
1821 case AVCOL_PRI_BT709: avio_wb16(pb, 1); break;
1822 case AVCOL_PRI_BT470BG: avio_wb16(pb, 5); break;
1823 case AVCOL_PRI_SMPTE170M:
1824 case AVCOL_PRI_SMPTE240M: avio_wb16(pb, 6); break;
1825 case AVCOL_PRI_BT2020: avio_wb16(pb, 9); break;
1826 case AVCOL_PRI_SMPTE431: avio_wb16(pb, 11); break;
1827 case AVCOL_PRI_SMPTE432: avio_wb16(pb, 12); break;
1828 default: avio_wb16(pb, 2);
1830 switch (track->par->color_trc) {
1831 case AVCOL_TRC_BT709: avio_wb16(pb, 1); break;
1832 case AVCOL_TRC_SMPTE170M: avio_wb16(pb, 1); break; // remapped
1833 case AVCOL_TRC_SMPTE240M: avio_wb16(pb, 7); break;
1834 case AVCOL_TRC_SMPTEST2084: avio_wb16(pb, 16); break;
1835 case AVCOL_TRC_SMPTE428: avio_wb16(pb, 17); break;
1836 case AVCOL_TRC_ARIB_STD_B67: avio_wb16(pb, 18); break;
1837 default: avio_wb16(pb, 2);
1839 switch (track->par->color_space) {
1840 case AVCOL_SPC_BT709: avio_wb16(pb, 1); break;
1841 case AVCOL_SPC_BT470BG:
1842 case AVCOL_SPC_SMPTE170M: avio_wb16(pb, 6); break;
1843 case AVCOL_SPC_SMPTE240M: avio_wb16(pb, 7); break;
1844 case AVCOL_SPC_BT2020_NCL: avio_wb16(pb, 9); break;
1845 default: avio_wb16(pb, 2);
1848 if (track->mode == MODE_MP4) {
1849 int full_range = track->par->color_range == AVCOL_RANGE_JPEG;
1850 avio_w8(pb, full_range << 7);
1857 static void find_compressor(char * compressor_name, int len, MOVTrack *track)
1859 AVDictionaryEntry *encoder;
1860 int xdcam_res = (track->par->width == 1280 && track->par->height == 720)
1861 || (track->par->width == 1440 && track->par->height == 1080)
1862 || (track->par->width == 1920 && track->par->height == 1080);
1864 if (track->mode == MODE_MOV &&
1865 (encoder = av_dict_get(track->st->metadata, "encoder", NULL, 0))) {
1866 av_strlcpy(compressor_name, encoder->value, 32);
1867 } else if (track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO && xdcam_res) {
1868 int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE;
1869 AVStream *st = track->st;
1870 int rate = defined_frame_rate(NULL, st);
1871 av_strlcatf(compressor_name, len, "XDCAM");
1872 if (track->par->format == AV_PIX_FMT_YUV422P) {
1873 av_strlcatf(compressor_name, len, " HD422");
1874 } else if(track->par->width == 1440) {
1875 av_strlcatf(compressor_name, len, " HD");
1877 av_strlcatf(compressor_name, len, " EX");
1879 av_strlcatf(compressor_name, len, " %d%c", track->par->height, interlaced ? 'i' : 'p');
1881 av_strlcatf(compressor_name, len, "%d", rate * (interlaced + 1));
1885 static int mov_write_video_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
1887 int64_t pos = avio_tell(pb);
1888 char compressor_name[32] = { 0 };
1891 int uncompressed_ycbcr = ((track->par->codec_id == AV_CODEC_ID_RAWVIDEO && track->par->format == AV_PIX_FMT_UYVY422)
1892 || (track->par->codec_id == AV_CODEC_ID_RAWVIDEO && track->par->format == AV_PIX_FMT_YUYV422)
1893 || track->par->codec_id == AV_CODEC_ID_V308
1894 || track->par->codec_id == AV_CODEC_ID_V408
1895 || track->par->codec_id == AV_CODEC_ID_V410
1896 || track->par->codec_id == AV_CODEC_ID_V210);
1898 avio_wb32(pb, 0); /* size */
1899 if (mov->encryption_scheme != MOV_ENC_NONE) {
1900 ffio_wfourcc(pb, "encv");
1902 avio_wl32(pb, track->tag); // store it byteswapped
1904 avio_wb32(pb, 0); /* Reserved */
1905 avio_wb16(pb, 0); /* Reserved */
1906 avio_wb16(pb, 1); /* Data-reference index */
1908 if (uncompressed_ycbcr) {
1909 avio_wb16(pb, 2); /* Codec stream version */
1911 avio_wb16(pb, 0); /* Codec stream version */
1913 avio_wb16(pb, 0); /* Codec stream revision (=0) */
1914 if (track->mode == MODE_MOV) {
1915 ffio_wfourcc(pb, "FFMP"); /* Vendor */
1916 if (track->par->codec_id == AV_CODEC_ID_RAWVIDEO || uncompressed_ycbcr) {
1917 avio_wb32(pb, 0); /* Temporal Quality */
1918 avio_wb32(pb, 0x400); /* Spatial Quality = lossless*/
1920 avio_wb32(pb, 0x200); /* Temporal Quality = normal */
1921 avio_wb32(pb, 0x200); /* Spatial Quality = normal */
1924 avio_wb32(pb, 0); /* Reserved */
1925 avio_wb32(pb, 0); /* Reserved */
1926 avio_wb32(pb, 0); /* Reserved */
1928 avio_wb16(pb, track->par->width); /* Video width */
1929 avio_wb16(pb, track->height); /* Video height */
1930 avio_wb32(pb, 0x00480000); /* Horizontal resolution 72dpi */
1931 avio_wb32(pb, 0x00480000); /* Vertical resolution 72dpi */
1932 avio_wb32(pb, 0); /* Data size (= 0) */
1933 avio_wb16(pb, 1); /* Frame count (= 1) */
1935 /* FIXME not sure, ISO 14496-1 draft where it shall be set to 0 */
1936 find_compressor(compressor_name, 32, track);
1937 avio_w8(pb, strlen(compressor_name));
1938 avio_write(pb, compressor_name, 31);
1940 if (track->mode == MODE_MOV &&
1941 (track->par->codec_id == AV_CODEC_ID_V410 || track->par->codec_id == AV_CODEC_ID_V210))
1942 avio_wb16(pb, 0x18);
1943 else if (track->mode == MODE_MOV && track->par->bits_per_coded_sample)
1944 avio_wb16(pb, track->par->bits_per_coded_sample |
1945 (track->par->format == AV_PIX_FMT_GRAY8 ? 0x20 : 0));
1947 avio_wb16(pb, 0x18); /* Reserved */
1949 if (track->mode == MODE_MOV && track->par->format == AV_PIX_FMT_PAL8) {
1950 int pal_size = 1 << track->par->bits_per_coded_sample;
1952 avio_wb16(pb, 0); /* Color table ID */
1953 avio_wb32(pb, 0); /* Color table seed */
1954 avio_wb16(pb, 0x8000); /* Color table flags */
1955 avio_wb16(pb, pal_size - 1); /* Color table size (zero-relative) */
1956 for (i = 0; i < pal_size; i++) {
1957 uint32_t rgb = track->palette[i];
1958 uint16_t r = (rgb >> 16) & 0xff;
1959 uint16_t g = (rgb >> 8) & 0xff;
1960 uint16_t b = rgb & 0xff;
1962 avio_wb16(pb, (r << 8) | r);
1963 avio_wb16(pb, (g << 8) | g);
1964 avio_wb16(pb, (b << 8) | b);
1967 avio_wb16(pb, 0xffff); /* Reserved */
1969 if (track->tag == MKTAG('m','p','4','v'))
1970 mov_write_esds_tag(pb, track);
1971 else if (track->par->codec_id == AV_CODEC_ID_H263)
1972 mov_write_d263_tag(pb);
1973 else if (track->par->codec_id == AV_CODEC_ID_AVUI ||
1974 track->par->codec_id == AV_CODEC_ID_SVQ3) {
1975 mov_write_extradata_tag(pb, track);
1977 } else if (track->par->codec_id == AV_CODEC_ID_DNXHD) {
1978 mov_write_avid_tag(pb, track);
1980 } else if (track->par->codec_id == AV_CODEC_ID_HEVC)
1981 mov_write_hvcc_tag(pb, track);
1982 else if (track->par->codec_id == AV_CODEC_ID_H264 && !TAG_IS_AVCI(track->tag)) {
1983 mov_write_avcc_tag(pb, track);
1984 if (track->mode == MODE_IPOD)
1985 mov_write_uuid_tag_ipod(pb);
1986 } else if (track->par->codec_id == AV_CODEC_ID_VP9) {
1987 mov_write_vpcc_tag(mov->fc, pb, track);
1988 } else if (track->par->codec_id == AV_CODEC_ID_VC1 && track->vos_len > 0)
1989 mov_write_dvc1_tag(pb, track);
1990 else if (track->par->codec_id == AV_CODEC_ID_VP6F ||
1991 track->par->codec_id == AV_CODEC_ID_VP6A) {
1992 /* Don't write any potential extradata here - the cropping
1993 * is signalled via the normal width/height fields. */
1994 } else if (track->par->codec_id == AV_CODEC_ID_R10K) {
1995 if (track->par->codec_tag == MKTAG('R','1','0','k'))
1996 mov_write_dpxe_tag(pb, track);
1997 } else if (track->vos_len > 0)
1998 mov_write_glbl_tag(pb, track);
2000 if (track->par->codec_id != AV_CODEC_ID_H264 &&
2001 track->par->codec_id != AV_CODEC_ID_MPEG4 &&
2002 track->par->codec_id != AV_CODEC_ID_DNXHD) {
2003 int field_order = track->par->field_order;
2005 #if FF_API_LAVF_AVCTX
2006 FF_DISABLE_DEPRECATION_WARNINGS
2007 if (field_order != track->st->codec->field_order && track->st->codec->field_order != AV_FIELD_UNKNOWN)
2008 field_order = track->st->codec->field_order;
2009 FF_ENABLE_DEPRECATION_WARNINGS
2012 if (field_order != AV_FIELD_UNKNOWN)
2013 mov_write_fiel_tag(pb, track, field_order);
2016 if (mov->flags & FF_MOV_FLAG_WRITE_GAMA) {
2017 if (track->mode == MODE_MOV)
2018 mov_write_gama_tag(pb, track, mov->gamma);
2020 av_log(mov->fc, AV_LOG_WARNING, "Not writing 'gama' atom. Format is not MOV.\n");
2022 if (mov->flags & FF_MOV_FLAG_WRITE_COLR) {
2023 if (track->mode == MODE_MOV || track->mode == MODE_MP4)
2024 mov_write_colr_tag(pb, track);
2026 av_log(mov->fc, AV_LOG_WARNING, "Not writing 'colr' atom. Format is not MOV or MP4.\n");
2029 if (track->mode == MODE_MP4 && mov->fc->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL) {
2030 AVStereo3D* stereo_3d = (AVStereo3D*) av_stream_get_side_data(track->st, AV_PKT_DATA_STEREO3D, NULL);
2031 AVSphericalMapping* spherical_mapping = (AVSphericalMapping*)av_stream_get_side_data(track->st, AV_PKT_DATA_SPHERICAL, NULL);
2034 mov_write_st3d_tag(pb, stereo_3d);
2035 if (spherical_mapping)
2036 mov_write_sv3d_tag(mov->fc, pb, spherical_mapping);
2039 if (track->par->sample_aspect_ratio.den && track->par->sample_aspect_ratio.num) {
2040 mov_write_pasp_tag(pb, track);
2043 if (uncompressed_ycbcr){
2044 mov_write_clap_tag(pb, track);
2047 if (mov->encryption_scheme != MOV_ENC_NONE) {
2048 ff_mov_cenc_write_sinf_tag(track, pb, mov->encryption_kid);
2051 /* extra padding for avid stsd */
2052 /* https://developer.apple.com/library/mac/documentation/QuickTime/QTFF/QTFFChap2/qtff2.html#//apple_ref/doc/uid/TP40000939-CH204-61112 */
2056 return update_size(pb, pos);
2059 static int mov_write_rtp_tag(AVIOContext *pb, MOVTrack *track)
2061 int64_t pos = avio_tell(pb);
2062 avio_wb32(pb, 0); /* size */
2063 ffio_wfourcc(pb, "rtp ");
2064 avio_wb32(pb, 0); /* Reserved */
2065 avio_wb16(pb, 0); /* Reserved */
2066 avio_wb16(pb, 1); /* Data-reference index */
2068 avio_wb16(pb, 1); /* Hint track version */
2069 avio_wb16(pb, 1); /* Highest compatible version */
2070 avio_wb32(pb, track->max_packet_size); /* Max packet size */
2072 avio_wb32(pb, 12); /* size */
2073 ffio_wfourcc(pb, "tims");
2074 avio_wb32(pb, track->timescale);
2076 return update_size(pb, pos);
2079 static int mov_write_source_reference_tag(AVIOContext *pb, MOVTrack *track, const char *reel_name)
2081 uint64_t str_size =strlen(reel_name);
2082 int64_t pos = avio_tell(pb);
2084 if (str_size >= UINT16_MAX){
2085 av_log(NULL, AV_LOG_ERROR, "reel_name length %"PRIu64" is too large\n", str_size);
2087 return AVERROR(EINVAL);
2090 avio_wb32(pb, 0); /* size */
2091 ffio_wfourcc(pb, "name"); /* Data format */
2092 avio_wb16(pb, str_size); /* string size */
2093 avio_wb16(pb, track->language); /* langcode */
2094 avio_write(pb, reel_name, str_size); /* reel name */
2095 return update_size(pb,pos);
2098 static int mov_write_tmcd_tag(AVIOContext *pb, MOVTrack *track)
2100 int64_t pos = avio_tell(pb);
2104 AVDictionaryEntry *t = NULL;
2106 if (!track->st->avg_frame_rate.num || !track->st->avg_frame_rate.den) {
2107 #if FF_API_LAVF_AVCTX
2108 FF_DISABLE_DEPRECATION_WARNINGS
2109 frame_duration = av_rescale(track->timescale, track->st->codec->time_base.num, track->st->codec->time_base.den);
2110 nb_frames = ROUNDED_DIV(track->st->codec->time_base.den, track->st->codec->time_base.num);
2111 FF_ENABLE_DEPRECATION_WARNINGS
2113 av_log(NULL, AV_LOG_ERROR, "avg_frame_rate not set for tmcd track.\n");
2114 return AVERROR(EINVAL);
2117 frame_duration = av_rescale(track->timescale, track->st->avg_frame_rate.num, track->st->avg_frame_rate.den);
2118 nb_frames = ROUNDED_DIV(track->st->avg_frame_rate.den, track->st->avg_frame_rate.num);
2121 if (nb_frames > 255) {
2122 av_log(NULL, AV_LOG_ERROR, "fps %d is too large\n", nb_frames);
2123 return AVERROR(EINVAL);
2126 avio_wb32(pb, 0); /* size */
2127 ffio_wfourcc(pb, "tmcd"); /* Data format */
2128 avio_wb32(pb, 0); /* Reserved */
2129 avio_wb32(pb, 1); /* Data reference index */
2130 avio_wb32(pb, 0); /* Flags */
2131 avio_wb32(pb, track->timecode_flags); /* Flags (timecode) */
2132 avio_wb32(pb, track->timescale); /* Timescale */
2133 avio_wb32(pb, frame_duration); /* Frame duration */
2134 avio_w8(pb, nb_frames); /* Number of frames */
2135 avio_w8(pb, 0); /* Reserved */
2137 t = av_dict_get(track->st->metadata, "reel_name", NULL, 0);
2138 if (t && utf8len(t->value) && track->mode != MODE_MP4)
2139 mov_write_source_reference_tag(pb, track, t->value);
2141 avio_wb16(pb, 0); /* zero size */
2144 avio_wb32(pb, 0); /* size */
2145 ffio_wfourcc(pb, "tmcd"); /* Data format */
2146 avio_wb32(pb, 0); /* Reserved */
2147 avio_wb32(pb, 1); /* Data reference index */
2148 if (track->par->extradata_size)
2149 avio_write(pb, track->par->extradata, track->par->extradata_size);
2151 return update_size(pb, pos);
2154 static int mov_write_gpmd_tag(AVIOContext *pb, const MOVTrack *track)
2156 int64_t pos = avio_tell(pb);
2157 avio_wb32(pb, 0); /* size */
2158 ffio_wfourcc(pb, "gpmd");
2159 avio_wb32(pb, 0); /* Reserved */
2160 avio_wb16(pb, 0); /* Reserved */
2161 avio_wb16(pb, 1); /* Data-reference index */
2162 avio_wb32(pb, 0); /* Reserved */
2163 return update_size(pb, pos);
2166 static int mov_write_stsd_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
2168 int64_t pos = avio_tell(pb);
2169 avio_wb32(pb, 0); /* size */
2170 ffio_wfourcc(pb, "stsd");
2171 avio_wb32(pb, 0); /* version & flags */
2172 avio_wb32(pb, 1); /* entry count */
2173 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO)
2174 mov_write_video_tag(pb, mov, track);
2175 else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
2176 mov_write_audio_tag(s, pb, mov, track);
2177 else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)
2178 mov_write_subtitle_tag(pb, track);
2179 else if (track->par->codec_tag == MKTAG('r','t','p',' '))
2180 mov_write_rtp_tag(pb, track);
2181 else if (track->par->codec_tag == MKTAG('t','m','c','d'))
2182 mov_write_tmcd_tag(pb, track);
2183 else if (track->par->codec_tag == MKTAG('g','p','m','d'))
2184 mov_write_gpmd_tag(pb, track);
2185 return update_size(pb, pos);
2188 static int mov_write_ctts_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
2190 MOVMuxContext *mov = s->priv_data;
2191 MOVStts *ctts_entries;
2192 uint32_t entries = 0;
2196 ctts_entries = av_malloc_array((track->entry + 1), sizeof(*ctts_entries)); /* worst case */
2198 return AVERROR(ENOMEM);
2199 ctts_entries[0].count = 1;
2200 ctts_entries[0].duration = track->cluster[0].cts;
2201 for (i = 1; i < track->entry; i++) {
2202 if (track->cluster[i].cts == ctts_entries[entries].duration) {
2203 ctts_entries[entries].count++; /* compress */
2206 ctts_entries[entries].duration = track->cluster[i].cts;
2207 ctts_entries[entries].count = 1;
2210 entries++; /* last one */
2211 atom_size = 16 + (entries * 8);
2212 avio_wb32(pb, atom_size); /* size */
2213 ffio_wfourcc(pb, "ctts");
2214 if (mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS)
2215 avio_w8(pb, 1); /* version */
2217 avio_w8(pb, 0); /* version */
2218 avio_wb24(pb, 0); /* flags */
2219 avio_wb32(pb, entries); /* entry count */
2220 for (i = 0; i < entries; i++) {
2221 avio_wb32(pb, ctts_entries[i].count);
2222 avio_wb32(pb, ctts_entries[i].duration);
2224 av_free(ctts_entries);
2228 /* Time to sample atom */
2229 static int mov_write_stts_tag(AVIOContext *pb, MOVTrack *track)
2231 MOVStts *stts_entries = NULL;
2232 uint32_t entries = -1;
2236 if (track->par->codec_type == AVMEDIA_TYPE_AUDIO && !track->audio_vbr) {
2237 stts_entries = av_malloc(sizeof(*stts_entries)); /* one entry */
2239 return AVERROR(ENOMEM);
2240 stts_entries[0].count = track->sample_count;
2241 stts_entries[0].duration = 1;
2245 stts_entries = av_malloc_array(track->entry, sizeof(*stts_entries)); /* worst case */
2247 return AVERROR(ENOMEM);
2249 for (i = 0; i < track->entry; i++) {
2250 int duration = get_cluster_duration(track, i);
2251 if (i && duration == stts_entries[entries].duration) {
2252 stts_entries[entries].count++; /* compress */
2255 stts_entries[entries].duration = duration;
2256 stts_entries[entries].count = 1;
2259 entries++; /* last one */
2261 atom_size = 16 + (entries * 8);
2262 avio_wb32(pb, atom_size); /* size */
2263 ffio_wfourcc(pb, "stts");
2264 avio_wb32(pb, 0); /* version & flags */
2265 avio_wb32(pb, entries); /* entry count */
2266 for (i = 0; i < entries; i++) {
2267 avio_wb32(pb, stts_entries[i].count);
2268 avio_wb32(pb, stts_entries[i].duration);
2270 av_free(stts_entries);
2274 static int mov_write_dref_tag(AVIOContext *pb)
2276 avio_wb32(pb, 28); /* size */
2277 ffio_wfourcc(pb, "dref");
2278 avio_wb32(pb, 0); /* version & flags */
2279 avio_wb32(pb, 1); /* entry count */
2281 avio_wb32(pb, 0xc); /* size */
2282 //FIXME add the alis and rsrc atom
2283 ffio_wfourcc(pb, "url ");
2284 avio_wb32(pb, 1); /* version & flags */
2289 static int mov_preroll_write_stbl_atoms(AVIOContext *pb, MOVTrack *track)
2293 int16_t roll_distance;
2294 int group_description_index;
2297 struct sgpd_entry *sgpd_entries = NULL;
2302 const int OPUS_SEEK_PREROLL_MS = 80;
2303 int roll_samples = av_rescale_q(OPUS_SEEK_PREROLL_MS,
2304 (AVRational){1, 1000},
2305 (AVRational){1, 48000});
2310 sgpd_entries = av_malloc_array(track->entry, sizeof(*sgpd_entries));
2312 return AVERROR(ENOMEM);
2314 av_assert0(track->par->codec_id == AV_CODEC_ID_OPUS || track->par->codec_id == AV_CODEC_ID_AAC);
2316 if (track->par->codec_id == AV_CODEC_ID_OPUS) {
2317 for (i = 0; i < track->entry; i++) {
2318 int roll_samples_remaining = roll_samples;
2320 for (j = i - 1; j >= 0; j--) {
2321 roll_samples_remaining -= get_cluster_duration(track, j);
2323 if (roll_samples_remaining <= 0)
2326 /* We don't have enough preceeding samples to compute a valid
2327 roll_distance here, so this sample can't be independently
2329 if (roll_samples_remaining > 0)
2331 /* Verify distance is a minimum of 2 (60ms) packets and a maximum of
2332 32 (2.5ms) packets. */
2333 av_assert0(distance == 0 || (distance >= 2 && distance <= 32));
2334 if (i && distance == sgpd_entries[entries].roll_distance) {
2335 sgpd_entries[entries].count++;
2338 sgpd_entries[entries].count = 1;
2339 sgpd_entries[entries].roll_distance = distance;
2340 sgpd_entries[entries].group_description_index = distance ? ++group : 0;
2345 sgpd_entries[entries].count = track->sample_count;
2346 sgpd_entries[entries].roll_distance = 1;
2347 sgpd_entries[entries].group_description_index = ++group;
2352 av_free(sgpd_entries);
2356 /* Write sgpd tag */
2357 avio_wb32(pb, 24 + (group * 2)); /* size */
2358 ffio_wfourcc(pb, "sgpd");
2359 avio_wb32(pb, 1 << 24); /* fullbox */
2360 ffio_wfourcc(pb, "roll");
2361 avio_wb32(pb, 2); /* default_length */
2362 avio_wb32(pb, group); /* entry_count */
2363 for (i = 0; i < entries; i++) {
2364 if (sgpd_entries[i].group_description_index) {
2365 avio_wb16(pb, -sgpd_entries[i].roll_distance); /* roll_distance */
2369 /* Write sbgp tag */
2370 avio_wb32(pb, 20 + (entries * 8)); /* size */
2371 ffio_wfourcc(pb, "sbgp");
2372 avio_wb32(pb, 0); /* fullbox */
2373 ffio_wfourcc(pb, "roll");
2374 avio_wb32(pb, entries); /* entry_count */
2375 for (i = 0; i < entries; i++) {
2376 avio_wb32(pb, sgpd_entries[i].count); /* sample_count */
2377 avio_wb32(pb, sgpd_entries[i].group_description_index); /* group_description_index */
2380 av_free(sgpd_entries);
2384 static int mov_write_stbl_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
2386 int64_t pos = avio_tell(pb);
2389 avio_wb32(pb, 0); /* size */
2390 ffio_wfourcc(pb, "stbl");
2391 mov_write_stsd_tag(s, pb, mov, track);
2392 mov_write_stts_tag(pb, track);
2393 if ((track->par->codec_type == AVMEDIA_TYPE_VIDEO ||
2394 track->par->codec_tag == MKTAG('r','t','p',' ')) &&
2395 track->has_keyframes && track->has_keyframes < track->entry)
2396 mov_write_stss_tag(pb, track, MOV_SYNC_SAMPLE);
2397 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO && track->has_disposable)
2398 mov_write_sdtp_tag(pb, track);
2399 if (track->mode == MODE_MOV && track->flags & MOV_TRACK_STPS)
2400 mov_write_stss_tag(pb, track, MOV_PARTIAL_SYNC_SAMPLE);
2401 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO &&
2402 track->flags & MOV_TRACK_CTTS && track->entry) {
2404 if ((ret = mov_write_ctts_tag(s, pb, track)) < 0)
2407 mov_write_stsc_tag(pb, track);
2408 mov_write_stsz_tag(pb, track);
2409 mov_write_stco_tag(pb, track);
2410 if (track->cenc.aes_ctr) {
2411 ff_mov_cenc_write_stbl_atoms(&track->cenc, pb);
2413 if (track->par->codec_id == AV_CODEC_ID_OPUS || track->par->codec_id == AV_CODEC_ID_AAC) {
2414 mov_preroll_write_stbl_atoms(pb, track);
2416 return update_size(pb, pos);
2419 static int mov_write_dinf_tag(AVIOContext *pb)
2421 int64_t pos = avio_tell(pb);
2422 avio_wb32(pb, 0); /* size */
2423 ffio_wfourcc(pb, "dinf");
2424 mov_write_dref_tag(pb);
2425 return update_size(pb, pos);
2428 static int mov_write_nmhd_tag(AVIOContext *pb)
2431 ffio_wfourcc(pb, "nmhd");
2436 static int mov_write_tcmi_tag(AVIOContext *pb, MOVTrack *track)
2438 int64_t pos = avio_tell(pb);
2439 const char *font = "Lucida Grande";
2440 avio_wb32(pb, 0); /* size */
2441 ffio_wfourcc(pb, "tcmi"); /* timecode media information atom */
2442 avio_wb32(pb, 0); /* version & flags */
2443 avio_wb16(pb, 0); /* text font */
2444 avio_wb16(pb, 0); /* text face */
2445 avio_wb16(pb, 12); /* text size */
2446 avio_wb16(pb, 0); /* (unknown, not in the QT specs...) */
2447 avio_wb16(pb, 0x0000); /* text color (red) */
2448 avio_wb16(pb, 0x0000); /* text color (green) */
2449 avio_wb16(pb, 0x0000); /* text color (blue) */
2450 avio_wb16(pb, 0xffff); /* background color (red) */
2451 avio_wb16(pb, 0xffff); /* background color (green) */
2452 avio_wb16(pb, 0xffff); /* background color (blue) */
2453 avio_w8(pb, strlen(font)); /* font len (part of the pascal string) */
2454 avio_write(pb, font, strlen(font)); /* font name */
2455 return update_size(pb, pos);
2458 static int mov_write_gmhd_tag(AVIOContext *pb, MOVTrack *track)
2460 int64_t pos = avio_tell(pb);
2461 avio_wb32(pb, 0); /* size */
2462 ffio_wfourcc(pb, "gmhd");
2463 avio_wb32(pb, 0x18); /* gmin size */
2464 ffio_wfourcc(pb, "gmin");/* generic media info */
2465 avio_wb32(pb, 0); /* version & flags */
2466 avio_wb16(pb, 0x40); /* graphics mode = */
2467 avio_wb16(pb, 0x8000); /* opColor (r?) */
2468 avio_wb16(pb, 0x8000); /* opColor (g?) */
2469 avio_wb16(pb, 0x8000); /* opColor (b?) */
2470 avio_wb16(pb, 0); /* balance */
2471 avio_wb16(pb, 0); /* reserved */
2474 * This special text atom is required for
2475 * Apple Quicktime chapters. The contents
2476 * don't appear to be documented, so the
2477 * bytes are copied verbatim.
2479 if (track->tag != MKTAG('c','6','0','8')) {
2480 avio_wb32(pb, 0x2C); /* size */
2481 ffio_wfourcc(pb, "text");
2482 avio_wb16(pb, 0x01);
2483 avio_wb32(pb, 0x00);
2484 avio_wb32(pb, 0x00);
2485 avio_wb32(pb, 0x00);
2486 avio_wb32(pb, 0x01);
2487 avio_wb32(pb, 0x00);
2488 avio_wb32(pb, 0x00);
2489 avio_wb32(pb, 0x00);
2490 avio_wb32(pb, 0x00004000);
2491 avio_wb16(pb, 0x0000);
2494 if (track->par->codec_tag == MKTAG('t','m','c','d')) {
2495 int64_t tmcd_pos = avio_tell(pb);
2496 avio_wb32(pb, 0); /* size */
2497 ffio_wfourcc(pb, "tmcd");
2498 mov_write_tcmi_tag(pb, track);
2499 update_size(pb, tmcd_pos);
2500 } else if (track->par->codec_tag == MKTAG('g','p','m','d')) {
2501 int64_t gpmd_pos = avio_tell(pb);
2502 avio_wb32(pb, 0); /* size */
2503 ffio_wfourcc(pb, "gpmd");
2504 avio_wb32(pb, 0); /* version */
2505 update_size(pb, gpmd_pos);
2507 return update_size(pb, pos);
2510 static int mov_write_smhd_tag(AVIOContext *pb)
2512 avio_wb32(pb, 16); /* size */
2513 ffio_wfourcc(pb, "smhd");
2514 avio_wb32(pb, 0); /* version & flags */
2515 avio_wb16(pb, 0); /* reserved (balance, normally = 0) */
2516 avio_wb16(pb, 0); /* reserved */
2520 static int mov_write_vmhd_tag(AVIOContext *pb)
2522 avio_wb32(pb, 0x14); /* size (always 0x14) */
2523 ffio_wfourcc(pb, "vmhd");
2524 avio_wb32(pb, 0x01); /* version & flags */
2525 avio_wb64(pb, 0); /* reserved (graphics mode = copy) */
2529 static int is_clcp_track(MOVTrack *track)
2531 return track->tag == MKTAG('c','7','0','8') ||
2532 track->tag == MKTAG('c','6','0','8');
2535 static int mov_write_hdlr_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
2537 const char *hdlr, *descr = NULL, *hdlr_type = NULL;
2538 int64_t pos = avio_tell(pb);
2542 descr = "DataHandler";
2545 hdlr = (track->mode == MODE_MOV) ? "mhlr" : "\0\0\0\0";
2546 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
2548 descr = "VideoHandler";
2549 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
2551 descr = "SoundHandler";
2552 } else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE) {
2553 if (is_clcp_track(track)) {
2555 descr = "ClosedCaptionHandler";
2557 if (track->tag == MKTAG('t','x','3','g')) {
2559 } else if (track->tag == MKTAG('m','p','4','s')) {
2564 descr = "SubtitleHandler";
2566 } else if (track->par->codec_tag == MKTAG('r','t','p',' ')) {
2568 descr = "HintHandler";
2569 } else if (track->par->codec_tag == MKTAG('t','m','c','d')) {
2571 descr = "TimeCodeHandler";
2572 } else if (track->par->codec_tag == MKTAG('g','p','m','d')) {
2574 descr = "GoPro MET"; // GoPro Metadata
2576 av_log(s, AV_LOG_WARNING,
2577 "Unknown hldr_type for %s, writing dummy values\n",
2578 av_fourcc2str(track->par->codec_tag));
2581 // hdlr.name is used by some players to identify the content title
2582 // of the track. So if an alternate handler description is
2583 // specified, use it.
2584 AVDictionaryEntry *t;
2585 t = av_dict_get(track->st->metadata, "handler", NULL, 0);
2586 if (t && utf8len(t->value))
2591 avio_wb32(pb, 0); /* size */
2592 ffio_wfourcc(pb, "hdlr");
2593 avio_wb32(pb, 0); /* Version & flags */
2594 avio_write(pb, hdlr, 4); /* handler */
2595 ffio_wfourcc(pb, hdlr_type); /* handler type */
2596 avio_wb32(pb, 0); /* reserved */
2597 avio_wb32(pb, 0); /* reserved */
2598 avio_wb32(pb, 0); /* reserved */
2599 if (!track || track->mode == MODE_MOV)
2600 avio_w8(pb, strlen(descr)); /* pascal string */
2601 avio_write(pb, descr, strlen(descr)); /* handler description */
2602 if (track && track->mode != MODE_MOV)
2603 avio_w8(pb, 0); /* c string */
2604 return update_size(pb, pos);
2607 static int mov_write_hmhd_tag(AVIOContext *pb)
2609 /* This atom must be present, but leaving the values at zero
2610 * seems harmless. */
2611 avio_wb32(pb, 28); /* size */
2612 ffio_wfourcc(pb, "hmhd");
2613 avio_wb32(pb, 0); /* version, flags */
2614 avio_wb16(pb, 0); /* maxPDUsize */
2615 avio_wb16(pb, 0); /* avgPDUsize */
2616 avio_wb32(pb, 0); /* maxbitrate */
2617 avio_wb32(pb, 0); /* avgbitrate */
2618 avio_wb32(pb, 0); /* reserved */
2622 static int mov_write_minf_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
2624 int64_t pos = avio_tell(pb);
2627 avio_wb32(pb, 0); /* size */
2628 ffio_wfourcc(pb, "minf");
2629 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO)
2630 mov_write_vmhd_tag(pb);
2631 else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
2632 mov_write_smhd_tag(pb);
2633 else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE) {
2634 if (track->tag == MKTAG('t','e','x','t') || is_clcp_track(track)) {
2635 mov_write_gmhd_tag(pb, track);
2637 mov_write_nmhd_tag(pb);
2639 } else if (track->tag == MKTAG('r','t','p',' ')) {
2640 mov_write_hmhd_tag(pb);
2641 } else if (track->tag == MKTAG('t','m','c','d')) {
2642 if (track->mode != MODE_MOV)
2643 mov_write_nmhd_tag(pb);
2645 mov_write_gmhd_tag(pb, track);
2646 } else if (track->tag == MKTAG('g','p','m','d')) {
2647 mov_write_gmhd_tag(pb, track);
2649 if (track->mode == MODE_MOV) /* FIXME: Why do it for MODE_MOV only ? */
2650 mov_write_hdlr_tag(s, pb, NULL);
2651 mov_write_dinf_tag(pb);
2652 if ((ret = mov_write_stbl_tag(s, pb, mov, track)) < 0)
2654 return update_size(pb, pos);
2657 static int mov_write_mdhd_tag(AVIOContext *pb, MOVMuxContext *mov,
2660 int version = track->track_duration < INT32_MAX ? 0 : 1;
2662 if (track->mode == MODE_ISM)
2665 (version == 1) ? avio_wb32(pb, 44) : avio_wb32(pb, 32); /* size */
2666 ffio_wfourcc(pb, "mdhd");
2667 avio_w8(pb, version);
2668 avio_wb24(pb, 0); /* flags */
2670 avio_wb64(pb, track->time);
2671 avio_wb64(pb, track->time);
2673 avio_wb32(pb, track->time); /* creation time */
2674 avio_wb32(pb, track->time); /* modification time */
2676 avio_wb32(pb, track->timescale); /* time scale (sample rate for audio) */
2677 if (!track->entry && mov->mode == MODE_ISM)
2678 (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
2679 else if (!track->entry)
2680 (version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0);
2682 (version == 1) ? avio_wb64(pb, track->track_duration) : avio_wb32(pb, track->track_duration); /* duration */
2683 avio_wb16(pb, track->language); /* language */
2684 avio_wb16(pb, 0); /* reserved (quality) */
2686 if (version != 0 && track->mode == MODE_MOV) {
2687 av_log(NULL, AV_LOG_ERROR,
2688 "FATAL error, file duration too long for timebase, this file will not be\n"
2689 "playable with quicktime. Choose a different timebase or a different\n"
2690 "container format\n");
2696 static int mov_write_mdia_tag(AVFormatContext *s, AVIOContext *pb,
2697 MOVMuxContext *mov, MOVTrack *track)
2699 int64_t pos = avio_tell(pb);
2702 avio_wb32(pb, 0); /* size */
2703 ffio_wfourcc(pb, "mdia");
2704 mov_write_mdhd_tag(pb, mov, track);
2705 mov_write_hdlr_tag(s, pb, track);
2706 if ((ret = mov_write_minf_tag(s, pb, mov, track)) < 0)
2708 return update_size(pb, pos);
2711 /* transformation matrix
2715 static void write_matrix(AVIOContext *pb, int16_t a, int16_t b, int16_t c,
2716 int16_t d, int16_t tx, int16_t ty)
2718 avio_wb32(pb, a << 16); /* 16.16 format */
2719 avio_wb32(pb, b << 16); /* 16.16 format */
2720 avio_wb32(pb, 0); /* u in 2.30 format */
2721 avio_wb32(pb, c << 16); /* 16.16 format */
2722 avio_wb32(pb, d << 16); /* 16.16 format */
2723 avio_wb32(pb, 0); /* v in 2.30 format */
2724 avio_wb32(pb, tx << 16); /* 16.16 format */
2725 avio_wb32(pb, ty << 16); /* 16.16 format */
2726 avio_wb32(pb, 1 << 30); /* w in 2.30 format */
2729 static int mov_write_tkhd_tag(AVIOContext *pb, MOVMuxContext *mov,
2730 MOVTrack *track, AVStream *st)
2732 int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE,
2733 track->timescale, AV_ROUND_UP);
2734 int version = duration < INT32_MAX ? 0 : 1;
2735 int flags = MOV_TKHD_FLAG_IN_MOVIE;
2739 uint32_t *display_matrix = NULL;
2740 int display_matrix_size, i;
2743 if (mov->per_stream_grouping)
2746 group = st->codecpar->codec_type;
2748 display_matrix = (uint32_t*)av_stream_get_side_data(st, AV_PKT_DATA_DISPLAYMATRIX,
2749 &display_matrix_size);
2750 if (display_matrix && display_matrix_size < 9 * sizeof(*display_matrix))
2751 display_matrix = NULL;
2754 if (track->flags & MOV_TRACK_ENABLED)
2755 flags |= MOV_TKHD_FLAG_ENABLED;
2757 if (track->mode == MODE_ISM)
2760 (version == 1) ? avio_wb32(pb, 104) : avio_wb32(pb, 92); /* size */
2761 ffio_wfourcc(pb, "tkhd");
2762 avio_w8(pb, version);
2763 avio_wb24(pb, flags);
2765 avio_wb64(pb, track->time);
2766 avio_wb64(pb, track->time);
2768 avio_wb32(pb, track->time); /* creation time */
2769 avio_wb32(pb, track->time); /* modification time */
2771 avio_wb32(pb, track->track_id); /* track-id */
2772 avio_wb32(pb, 0); /* reserved */
2773 if (!track->entry && mov->mode == MODE_ISM)
2774 (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
2775 else if (!track->entry)
2776 (version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0);
2778 (version == 1) ? avio_wb64(pb, duration) : avio_wb32(pb, duration);
2780 avio_wb32(pb, 0); /* reserved */
2781 avio_wb32(pb, 0); /* reserved */
2782 avio_wb16(pb, 0); /* layer */
2783 avio_wb16(pb, group); /* alternate group) */
2784 /* Volume, only for audio */
2785 if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
2786 avio_wb16(pb, 0x0100);
2789 avio_wb16(pb, 0); /* reserved */
2791 /* Matrix structure */
2792 #if FF_API_OLD_ROTATE_API
2793 if (st && st->metadata) {
2794 AVDictionaryEntry *rot = av_dict_get(st->metadata, "rotate", NULL, 0);
2795 rotation = (rot && rot->value) ? atoi(rot->value) : 0;
2798 if (display_matrix) {
2799 for (i = 0; i < 9; i++)
2800 avio_wb32(pb, display_matrix[i]);
2801 #if FF_API_OLD_ROTATE_API
2802 } else if (rotation == 90) {
2803 write_matrix(pb, 0, 1, -1, 0, track->par->height, 0);
2804 } else if (rotation == 180) {
2805 write_matrix(pb, -1, 0, 0, -1, track->par->width, track->par->height);
2806 } else if (rotation == 270) {
2807 write_matrix(pb, 0, -1, 1, 0, 0, track->par->width);
2810 write_matrix(pb, 1, 0, 0, 1, 0, 0);
2812 /* Track width and height, for visual only */
2813 if (st && (track->par->codec_type == AVMEDIA_TYPE_VIDEO ||
2814 track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)) {
2815 int64_t track_width_1616;
2816 if (track->mode == MODE_MOV) {
2817 track_width_1616 = track->par->width * 0x10000ULL;
2819 track_width_1616 = av_rescale(st->sample_aspect_ratio.num,
2820 track->par->width * 0x10000LL,
2821 st->sample_aspect_ratio.den);
2822 if (!track_width_1616 ||
2823 track->height != track->par->height ||
2824 track_width_1616 > UINT32_MAX)
2825 track_width_1616 = track->par->width * 0x10000ULL;
2827 if (track_width_1616 > UINT32_MAX) {
2828 av_log(mov->fc, AV_LOG_WARNING, "track width is too large\n");
2829 track_width_1616 = 0;
2831 avio_wb32(pb, track_width_1616);
2832 if (track->height > 0xFFFF) {
2833 av_log(mov->fc, AV_LOG_WARNING, "track height is too large\n");
2836 avio_wb32(pb, track->height * 0x10000U);
2844 static int mov_write_tapt_tag(AVIOContext *pb, MOVTrack *track)
2846 int32_t width = av_rescale(track->par->sample_aspect_ratio.num, track->par->width,
2847 track->par->sample_aspect_ratio.den);
2849 int64_t pos = avio_tell(pb);
2851 avio_wb32(pb, 0); /* size */
2852 ffio_wfourcc(pb, "tapt");
2855 ffio_wfourcc(pb, "clef");
2857 avio_wb32(pb, width << 16);
2858 avio_wb32(pb, track->par->height << 16);
2861 ffio_wfourcc(pb, "prof");
2863 avio_wb32(pb, width << 16);
2864 avio_wb32(pb, track->par->height << 16);
2867 ffio_wfourcc(pb, "enof");
2869 avio_wb32(pb, track->par->width << 16);
2870 avio_wb32(pb, track->par->height << 16);
2872 return update_size(pb, pos);
2875 // This box seems important for the psp playback ... without it the movie seems to hang
2876 static int mov_write_edts_tag(AVIOContext *pb, MOVMuxContext *mov,
2879 int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE,
2880 track->timescale, AV_ROUND_UP);
2881 int version = duration < INT32_MAX ? 0 : 1;
2882 int entry_size, entry_count, size;
2883 int64_t delay, start_ct = track->start_cts;
2884 int64_t start_dts = track->start_dts;
2887 if (start_dts != track->cluster[0].dts || start_ct != track->cluster[0].cts) {
2889 av_log(mov->fc, AV_LOG_DEBUG,
2890 "EDTS using dts:%"PRId64" cts:%d instead of dts:%"PRId64" cts:%"PRId64" tid:%d\n",
2891 track->cluster[0].dts, track->cluster[0].cts,
2892 start_dts, start_ct, track->track_id);
2893 start_dts = track->cluster[0].dts;
2894 start_ct = track->cluster[0].cts;
2898 delay = av_rescale_rnd(start_dts + start_ct, MOV_TIMESCALE,
2899 track->timescale, AV_ROUND_DOWN);
2900 version |= delay < INT32_MAX ? 0 : 1;
2902 entry_size = (version == 1) ? 20 : 12;
2903 entry_count = 1 + (delay > 0);
2904 size = 24 + entry_count * entry_size;
2906 /* write the atom data */
2907 avio_wb32(pb, size);
2908 ffio_wfourcc(pb, "edts");
2909 avio_wb32(pb, size - 8);
2910 ffio_wfourcc(pb, "elst");
2911 avio_w8(pb, version);
2912 avio_wb24(pb, 0); /* flags */
2914 avio_wb32(pb, entry_count);
2915 if (delay > 0) { /* add an empty edit to delay presentation */
2916 /* In the positive delay case, the delay includes the cts
2917 * offset, and the second edit list entry below trims out
2918 * the same amount from the actual content. This makes sure
2919 * that the offset last sample is included in the edit
2920 * list duration as well. */
2922 avio_wb64(pb, delay);
2925 avio_wb32(pb, delay);
2928 avio_wb32(pb, 0x00010000);
2930 /* Avoid accidentally ending up with start_ct = -1 which has got a
2931 * special meaning. Normally start_ct should end up positive or zero
2932 * here, but use FFMIN in case dts is a small positive integer
2933 * rounded to 0 when represented in MOV_TIMESCALE units. */
2934 av_assert0(av_rescale_rnd(start_dts, MOV_TIMESCALE, track->timescale, AV_ROUND_DOWN) <= 0);
2935 start_ct = -FFMIN(start_dts, 0);
2936 /* Note, this delay is calculated from the pts of the first sample,
2937 * ensuring that we don't reduce the duration for cases with
2942 /* For fragmented files, we don't know the full length yet. Setting
2943 * duration to 0 allows us to only specify the offset, including
2944 * the rest of the content (from all future fragments) without specifying
2945 * an explicit duration. */
2946 if (mov->flags & FF_MOV_FLAG_FRAGMENT)
2951 avio_wb64(pb, duration);
2952 avio_wb64(pb, start_ct);
2954 avio_wb32(pb, duration);
2955 avio_wb32(pb, start_ct);
2957 avio_wb32(pb, 0x00010000);
2961 static int mov_write_tref_tag(AVIOContext *pb, MOVTrack *track)
2963 avio_wb32(pb, 20); // size
2964 ffio_wfourcc(pb, "tref");
2965 avio_wb32(pb, 12); // size (subatom)
2966 avio_wl32(pb, track->tref_tag);
2967 avio_wb32(pb, track->tref_id);
2971 // goes at the end of each track! ... Critical for PSP playback ("Incompatible data" without it)
2972 static int mov_write_uuid_tag_psp(AVIOContext *pb, MOVTrack *mov)
2974 avio_wb32(pb, 0x34); /* size ... reports as 28 in mp4box! */
2975 ffio_wfourcc(pb, "uuid");
2976 ffio_wfourcc(pb, "USMT");
2977 avio_wb32(pb, 0x21d24fce);
2978 avio_wb32(pb, 0xbb88695c);
2979 avio_wb32(pb, 0xfac9c740);
2980 avio_wb32(pb, 0x1c); // another size here!
2981 ffio_wfourcc(pb, "MTDT");
2982 avio_wb32(pb, 0x00010012);
2983 avio_wb32(pb, 0x0a);
2984 avio_wb32(pb, 0x55c40000);
2990 static int mov_write_udta_sdp(AVIOContext *pb, MOVTrack *track)
2992 AVFormatContext *ctx = track->rtp_ctx;
2993 char buf[1000] = "";
2996 ff_sdp_write_media(buf, sizeof(buf), ctx->streams[0], track->src_track,
2997 NULL, NULL, 0, 0, ctx);
2998 av_strlcatf(buf, sizeof(buf), "a=control:streamid=%d\r\n", track->track_id);
3001 avio_wb32(pb, len + 24);
3002 ffio_wfourcc(pb, "udta");
3003 avio_wb32(pb, len + 16);
3004 ffio_wfourcc(pb, "hnti");
3005 avio_wb32(pb, len + 8);
3006 ffio_wfourcc(pb, "sdp ");
3007 avio_write(pb, buf, len);
3011 static int mov_write_track_metadata(AVIOContext *pb, AVStream *st,
3012 const char *tag, const char *str)
3014 int64_t pos = avio_tell(pb);
3015 AVDictionaryEntry *t = av_dict_get(st->metadata, str, NULL, 0);
3016 if (!t || !utf8len(t->value))
3019 avio_wb32(pb, 0); /* size */
3020 ffio_wfourcc(pb, tag); /* type */
3021 avio_write(pb, t->value, strlen(t->value)); /* UTF8 string value */
3022 return update_size(pb, pos);
3025 static int mov_write_track_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
3028 AVIOContext *pb_buf;
3035 ret = avio_open_dyn_buf(&pb_buf);
3039 if (mov->mode & (MODE_MP4|MODE_MOV))
3040 mov_write_track_metadata(pb_buf, st, "name", "title");
3042 if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) {
3043 avio_wb32(pb, size + 8);
3044 ffio_wfourcc(pb, "udta");
3045 avio_write(pb, buf, size);
3052 static int mov_write_trak_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov,
3053 MOVTrack *track, AVStream *st)
3055 int64_t pos = avio_tell(pb);
3056 int entry_backup = track->entry;
3057 int chunk_backup = track->chunkCount;
3060 /* If we want to have an empty moov, but some samples already have been
3061 * buffered (delay_moov), pretend that no samples have been written yet. */
3062 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV)
3063 track->chunkCount = track->entry = 0;
3065 avio_wb32(pb, 0); /* size */
3066 ffio_wfourcc(pb, "trak");
3067 mov_write_tkhd_tag(pb, mov, track, st);
3069 av_assert2(mov->use_editlist >= 0);
3071 if (track->start_dts != AV_NOPTS_VALUE) {
3072 if (mov->use_editlist)
3073 mov_write_edts_tag(pb, mov, track); // PSP Movies and several other cases require edts box
3074 else if ((track->entry && track->cluster[0].dts) || track->mode == MODE_PSP || is_clcp_track(track))
3075 av_log(mov->fc, AV_LOG_WARNING,
3076 "Not writing any edit list even though one would have been required\n");
3079 if (track->tref_tag)
3080 mov_write_tref_tag(pb, track);
3082 if ((ret = mov_write_mdia_tag(s, pb, mov, track)) < 0)
3084 if (track->mode == MODE_PSP)
3085 mov_write_uuid_tag_psp(pb, track); // PSP Movies require this uuid box
3086 if (track->tag == MKTAG('r','t','p',' '))
3087 mov_write_udta_sdp(pb, track);
3088 if (track->mode == MODE_MOV) {
3089 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
3090 double sample_aspect_ratio = av_q2d(st->sample_aspect_ratio);
3091 if (st->sample_aspect_ratio.num && 1.0 != sample_aspect_ratio) {
3092 mov_write_tapt_tag(pb, track);
3095 if (is_clcp_track(track) && st->sample_aspect_ratio.num) {
3096 mov_write_tapt_tag(pb, track);
3099 mov_write_track_udta_tag(pb, mov, st);
3100 track->entry = entry_backup;
3101 track->chunkCount = chunk_backup;
3102 return update_size(pb, pos);
3105 static int mov_write_iods_tag(AVIOContext *pb, MOVMuxContext *mov)
3107 int i, has_audio = 0, has_video = 0;
3108 int64_t pos = avio_tell(pb);
3109 int audio_profile = mov->iods_audio_profile;
3110 int video_profile = mov->iods_video_profile;
3111 for (i = 0; i < mov->nb_streams; i++) {
3112 if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
3113 has_audio |= mov->tracks[i].par->codec_type == AVMEDIA_TYPE_AUDIO;
3114 has_video |= mov->tracks[i].par->codec_type == AVMEDIA_TYPE_VIDEO;
3117 if (audio_profile < 0)
3118 audio_profile = 0xFF - has_audio;
3119 if (video_profile < 0)
3120 video_profile = 0xFF - has_video;
3121 avio_wb32(pb, 0x0); /* size */
3122 ffio_wfourcc(pb, "iods");
3123 avio_wb32(pb, 0); /* version & flags */
3124 put_descr(pb, 0x10, 7);
3125 avio_wb16(pb, 0x004f);
3128 avio_w8(pb, audio_profile);
3129 avio_w8(pb, video_profile);
3131 return update_size(pb, pos);
3134 static int mov_write_trex_tag(AVIOContext *pb, MOVTrack *track)
3136 avio_wb32(pb, 0x20); /* size */
3137 ffio_wfourcc(pb, "trex");
3138 avio_wb32(pb, 0); /* version & flags */
3139 avio_wb32(pb, track->track_id); /* track ID */
3140 avio_wb32(pb, 1); /* default sample description index */
3141 avio_wb32(pb, 0); /* default sample duration */
3142 avio_wb32(pb, 0); /* default sample size */
3143 avio_wb32(pb, 0); /* default sample flags */
3147 static int mov_write_mvex_tag(AVIOContext *pb, MOVMuxContext *mov)
3149 int64_t pos = avio_tell(pb);
3151 avio_wb32(pb, 0x0); /* size */
3152 ffio_wfourcc(pb, "mvex");
3153 for (i = 0; i < mov->nb_streams; i++)
3154 mov_write_trex_tag(pb, &mov->tracks[i]);
3155 return update_size(pb, pos);
3158 static int mov_write_mvhd_tag(AVIOContext *pb, MOVMuxContext *mov)
3160 int max_track_id = 1, i;
3161 int64_t max_track_len = 0;
3164 for (i = 0; i < mov->nb_streams; i++) {
3165 if (mov->tracks[i].entry > 0 && mov->tracks[i].timescale) {
3166 int64_t max_track_len_temp = av_rescale_rnd(mov->tracks[i].track_duration,
3168 mov->tracks[i].timescale,
3170 if (max_track_len < max_track_len_temp)
3171 max_track_len = max_track_len_temp;
3172 if (max_track_id < mov->tracks[i].track_id)
3173 max_track_id = mov->tracks[i].track_id;
3176 /* If using delay_moov, make sure the output is the same as if no
3177 * samples had been written yet. */
3178 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
3183 version = max_track_len < UINT32_MAX ? 0 : 1;
3184 avio_wb32(pb, version == 1 ? 120 : 108); /* size */
3186 ffio_wfourcc(pb, "mvhd");
3187 avio_w8(pb, version);
3188 avio_wb24(pb, 0); /* flags */
3190 avio_wb64(pb, mov->time);
3191 avio_wb64(pb, mov->time);
3193 avio_wb32(pb, mov->time); /* creation time */
3194 avio_wb32(pb, mov->time); /* modification time */
3196 avio_wb32(pb, MOV_TIMESCALE);
3197 (version == 1) ? avio_wb64(pb, max_track_len) : avio_wb32(pb, max_track_len); /* duration of longest track */
3199 avio_wb32(pb, 0x00010000); /* reserved (preferred rate) 1.0 = normal */
3200 avio_wb16(pb, 0x0100); /* reserved (preferred volume) 1.0 = normal */
3201 avio_wb16(pb, 0); /* reserved */
3202 avio_wb32(pb, 0); /* reserved */
3203 avio_wb32(pb, 0); /* reserved */
3205 /* Matrix structure */
3206 write_matrix(pb, 1, 0, 0, 1, 0, 0);
3208 avio_wb32(pb, 0); /* reserved (preview time) */
3209 avio_wb32(pb, 0); /* reserved (preview duration) */
3210 avio_wb32(pb, 0); /* reserved (poster time) */
3211 avio_wb32(pb, 0); /* reserved (selection time) */
3212 avio_wb32(pb, 0); /* reserved (selection duration) */
3213 avio_wb32(pb, 0); /* reserved (current time) */
3214 avio_wb32(pb, max_track_id + 1); /* Next track id */
3218 static int mov_write_itunes_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov,
3221 avio_wb32(pb, 33); /* size */
3222 ffio_wfourcc(pb, "hdlr");
3225 ffio_wfourcc(pb, "mdir");
3226 ffio_wfourcc(pb, "appl");
3233 /* helper function to write a data tag with the specified string as data */
3234 static int mov_write_string_data_tag(AVIOContext *pb, const char *data, int lang, int long_style)
3237 int size = 16 + strlen(data);
3238 avio_wb32(pb, size); /* size */
3239 ffio_wfourcc(pb, "data");
3242 avio_write(pb, data, strlen(data));
3246 lang = ff_mov_iso639_to_lang("und", 1);
3247 avio_wb16(pb, strlen(data)); /* string length */
3248 avio_wb16(pb, lang);
3249 avio_write(pb, data, strlen(data));
3250 return strlen(data) + 4;
3254 static int mov_write_string_tag(AVIOContext *pb, const char *name,
3255 const char *value, int lang, int long_style)
3258 if (value && value[0]) {
3259 int64_t pos = avio_tell(pb);
3260 avio_wb32(pb, 0); /* size */
3261 ffio_wfourcc(pb, name);
3262 mov_write_string_data_tag(pb, value, lang, long_style);
3263 size = update_size(pb, pos);
3268 static AVDictionaryEntry *get_metadata_lang(AVFormatContext *s,
3269 const char *tag, int *lang)
3272 AVDictionaryEntry *t, *t2 = NULL;
3277 if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
3280 len = strlen(t->key);
3281 snprintf(tag2, sizeof(tag2), "%s-", tag);
3282 while ((t2 = av_dict_get(s->metadata, tag2, t2, AV_DICT_IGNORE_SUFFIX))) {
3283 len2 = strlen(t2->key);
3284 if (len2 == len + 4 && !strcmp(t->value, t2->value)
3285 && (l = ff_mov_iso639_to_lang(&t2->key[len2 - 3], 1)) >= 0) {
3293 static int mov_write_string_metadata(AVFormatContext *s, AVIOContext *pb,
3294 const char *name, const char *tag,
3298 AVDictionaryEntry *t = get_metadata_lang(s, tag, &lang);
3301 return mov_write_string_tag(pb, name, t->value, lang, long_style);
3304 /* iTunes bpm number */
3305 static int mov_write_tmpo_tag(AVIOContext *pb, AVFormatContext *s)
3307 AVDictionaryEntry *t = av_dict_get(s->metadata, "tmpo", NULL, 0);
3308 int size = 0, tmpo = t ? atoi(t->value) : 0;
3311 avio_wb32(pb, size);
3312 ffio_wfourcc(pb, "tmpo");
3313 avio_wb32(pb, size-8); /* size */
3314 ffio_wfourcc(pb, "data");
3315 avio_wb32(pb, 0x15); //type specifier
3317 avio_wb16(pb, tmpo); // data
3322 /* 3GPP TS 26.244 */
3323 static int mov_write_loci_tag(AVFormatContext *s, AVIOContext *pb)
3326 int64_t pos = avio_tell(pb);
3327 double latitude, longitude, altitude;
3328 int32_t latitude_fix, longitude_fix, altitude_fix;
3329 AVDictionaryEntry *t = get_metadata_lang(s, "location", &lang);
3330 const char *ptr, *place = "";
3332 static const char *astronomical_body = "earth";
3337 longitude = strtod(ptr, &end);
3339 av_log(s, AV_LOG_WARNING, "malformed location metadata\n");
3343 latitude = strtod(ptr, &end);
3345 av_log(s, AV_LOG_WARNING, "malformed location metadata\n");
3349 altitude = strtod(ptr, &end);
3350 /* If no altitude was present, the default 0 should be fine */
3354 latitude_fix = (int32_t) ((1 << 16) * latitude);
3355 longitude_fix = (int32_t) ((1 << 16) * longitude);
3356 altitude_fix = (int32_t) ((1 << 16) * altitude);
3358 avio_wb32(pb, 0); /* size */
3359 ffio_wfourcc(pb, "loci"); /* type */
3360 avio_wb32(pb, 0); /* version + flags */
3361 avio_wb16(pb, lang);
3362 avio_write(pb, place, strlen(place) + 1);
3363 avio_w8(pb, 0); /* role of place (0 == shooting location, 1 == real location, 2 == fictional location) */
3364 avio_wb32(pb, latitude_fix);
3365 avio_wb32(pb, longitude_fix);
3366 avio_wb32(pb, altitude_fix);
3367 avio_write(pb, astronomical_body, strlen(astronomical_body) + 1);
3368 avio_w8(pb, 0); /* additional notes, null terminated string */
3370 return update_size(pb, pos);
3373 /* iTunes track or disc number */
3374 static int mov_write_trkn_tag(AVIOContext *pb, MOVMuxContext *mov,
3375 AVFormatContext *s, int disc)
3377 AVDictionaryEntry *t = av_dict_get(s->metadata,
3378 disc ? "disc" : "track",
3380 int size = 0, track = t ? atoi(t->value) : 0;
3383 char *slash = strchr(t->value, '/');
3385 tracks = atoi(slash + 1);
3386 avio_wb32(pb, 32); /* size */
3387 ffio_wfourcc(pb, disc ? "disk" : "trkn");
3388 avio_wb32(pb, 24); /* size */
3389 ffio_wfourcc(pb, "data");
3390 avio_wb32(pb, 0); // 8 bytes empty
3392 avio_wb16(pb, 0); // empty
3393 avio_wb16(pb, track); // track / disc number
3394 avio_wb16(pb, tracks); // total track / disc number
3395 avio_wb16(pb, 0); // empty
3401 static int mov_write_int8_metadata(AVFormatContext *s, AVIOContext *pb,
3402 const char *name, const char *tag,
3405 AVDictionaryEntry *t = NULL;
3407 int size = 24 + len;
3409 if (len != 1 && len != 4)
3412 if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
3414 num = atoi(t->value);
3416 avio_wb32(pb, size);
3417 ffio_wfourcc(pb, name);
3418 avio_wb32(pb, size - 8);
3419 ffio_wfourcc(pb, "data");
3420 avio_wb32(pb, 0x15);
3422 if (len==4) avio_wb32(pb, num);
3423 else avio_w8 (pb, num);
3428 static int mov_write_covr(AVIOContext *pb, AVFormatContext *s)
3430 MOVMuxContext *mov = s->priv_data;
3434 for (i = 0; i < s->nb_streams; i++) {
3435 MOVTrack *trk = &mov->tracks[i];
3436 AVStream *st = s->streams[i];
3438 if (!(st->disposition & AV_DISPOSITION_ATTACHED_PIC) ||
3439 trk->cover_image.size <= 0)
3442 switch (st->codecpar->codec_id) {
3443 case AV_CODEC_ID_MJPEG:
3446 case AV_CODEC_ID_PNG:
3449 case AV_CODEC_ID_BMP:
3453 av_log(s, AV_LOG_ERROR, "unsupported codec_id (0x%x) for cover",
3454 st->codecpar->codec_id);
3459 pos = avio_tell(pb);
3461 ffio_wfourcc(pb, "covr");
3463 avio_wb32(pb, 16 + trk->cover_image.size);
3464 ffio_wfourcc(pb, "data");
3465 avio_wb32(pb, type);
3467 avio_write(pb, trk->cover_image.data, trk->cover_image.size);
3470 return pos ? update_size(pb, pos) : 0;
3473 /* iTunes meta data list */
3474 static int mov_write_ilst_tag(AVIOContext *pb, MOVMuxContext *mov,
3477 int64_t pos = avio_tell(pb);
3478 avio_wb32(pb, 0); /* size */
3479 ffio_wfourcc(pb, "ilst");
3480 mov_write_string_metadata(s, pb, "\251nam", "title" , 1);
3481 mov_write_string_metadata(s, pb, "\251ART", "artist" , 1);
3482 mov_write_string_metadata(s, pb, "aART", "album_artist", 1);
3483 mov_write_string_metadata(s, pb, "\251wrt", "composer" , 1);
3484 mov_write_string_metadata(s, pb, "\251alb", "album" , 1);
3485 mov_write_string_metadata(s, pb, "\251day", "date" , 1);
3486 if (!mov_write_string_metadata(s, pb, "\251too", "encoding_tool", 1)) {
3487 if (!(s->flags & AVFMT_FLAG_BITEXACT))
3488 mov_write_string_tag(pb, "\251too", LIBAVFORMAT_IDENT, 0, 1);
3490 mov_write_string_metadata(s, pb, "\251cmt", "comment" , 1);
3491 mov_write_string_metadata(s, pb, "\251gen", "genre" , 1);
3492 mov_write_string_metadata(s, pb, "cprt", "copyright", 1);
3493 mov_write_string_metadata(s, pb, "\251grp", "grouping" , 1);
3494 mov_write_string_metadata(s, pb, "\251lyr", "lyrics" , 1);
3495 mov_write_string_metadata(s, pb, "desc", "description",1);
3496 mov_write_string_metadata(s, pb, "ldes", "synopsis" , 1);
3497 mov_write_string_metadata(s, pb, "tvsh", "show" , 1);
3498 mov_write_string_metadata(s, pb, "tven", "episode_id",1);
3499 mov_write_string_metadata(s, pb, "tvnn", "network" , 1);
3500 mov_write_string_metadata(s, pb, "keyw", "keywords" , 1);
3501 mov_write_int8_metadata (s, pb, "tves", "episode_sort",4);
3502 mov_write_int8_metadata (s, pb, "tvsn", "season_number",4);
3503 mov_write_int8_metadata (s, pb, "stik", "media_type",1);
3504 mov_write_int8_metadata (s, pb, "hdvd", "hd_video", 1);
3505 mov_write_int8_metadata (s, pb, "pgap", "gapless_playback",1);
3506 mov_write_int8_metadata (s, pb, "cpil", "compilation", 1);
3507 mov_write_covr(pb, s);
3508 mov_write_trkn_tag(pb, mov, s, 0); // track number
3509 mov_write_trkn_tag(pb, mov, s, 1); // disc number
3510 mov_write_tmpo_tag(pb, s);
3511 return update_size(pb, pos);
3514 static int mov_write_mdta_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov,
3517 avio_wb32(pb, 33); /* size */
3518 ffio_wfourcc(pb, "hdlr");
3521 ffio_wfourcc(pb, "mdta");
3529 static int mov_write_mdta_keys_tag(AVIOContext *pb, MOVMuxContext *mov,
3532 AVDictionaryEntry *t = NULL;
3533 int64_t pos = avio_tell(pb);
3534 int64_t curpos, entry_pos;
3537 avio_wb32(pb, 0); /* size */
3538 ffio_wfourcc(pb, "keys");
3540 entry_pos = avio_tell(pb);
3541 avio_wb32(pb, 0); /* entry count */
3543 while (t = av_dict_get(s->metadata, "", t, AV_DICT_IGNORE_SUFFIX)) {
3544 avio_wb32(pb, strlen(t->key) + 8);
3545 ffio_wfourcc(pb, "mdta");
3546 avio_write(pb, t->key, strlen(t->key));
3549 curpos = avio_tell(pb);
3550 avio_seek(pb, entry_pos, SEEK_SET);
3551 avio_wb32(pb, count); // rewrite entry count
3552 avio_seek(pb, curpos, SEEK_SET);
3554 return update_size(pb, pos);
3557 static int mov_write_mdta_ilst_tag(AVIOContext *pb, MOVMuxContext *mov,
3560 AVDictionaryEntry *t = NULL;
3561 int64_t pos = avio_tell(pb);
3562 int count = 1; /* keys are 1-index based */
3564 avio_wb32(pb, 0); /* size */
3565 ffio_wfourcc(pb, "ilst");
3567 while (t = av_dict_get(s->metadata, "", t, AV_DICT_IGNORE_SUFFIX)) {
3568 int64_t entry_pos = avio_tell(pb);
3569 avio_wb32(pb, 0); /* size */
3570 avio_wb32(pb, count); /* key */
3571 mov_write_string_data_tag(pb, t->value, 0, 1);
3572 update_size(pb, entry_pos);
3575 return update_size(pb, pos);
3578 /* meta data tags */
3579 static int mov_write_meta_tag(AVIOContext *pb, MOVMuxContext *mov,
3583 int64_t pos = avio_tell(pb);
3584 avio_wb32(pb, 0); /* size */
3585 ffio_wfourcc(pb, "meta");
3587 if (mov->flags & FF_MOV_FLAG_USE_MDTA) {
3588 mov_write_mdta_hdlr_tag(pb, mov, s);
3589 mov_write_mdta_keys_tag(pb, mov, s);
3590 mov_write_mdta_ilst_tag(pb, mov, s);
3593 /* iTunes metadata tag */
3594 mov_write_itunes_hdlr_tag(pb, mov, s);
3595 mov_write_ilst_tag(pb, mov, s);
3597 size = update_size(pb, pos);
3601 static int mov_write_raw_metadata_tag(AVFormatContext *s, AVIOContext *pb,
3602 const char *name, const char *key)
3605 AVDictionaryEntry *t;
3607 if (!(t = av_dict_get(s->metadata, key, NULL, 0)))
3610 len = strlen(t->value);
3613 avio_wb32(pb, size);
3614 ffio_wfourcc(pb, name);
3615 avio_write(pb, t->value, len);
3621 static int ascii_to_wc(AVIOContext *pb, const uint8_t *b)
3625 GET_UTF8(val, *b++, return -1;)
3628 avio_wb16(pb, 0x00);
3632 static uint16_t language_code(const char *str)
3634 return (((str[0] - 0x60) & 0x1F) << 10) +
3635 (((str[1] - 0x60) & 0x1F) << 5) +
3636 (( str[2] - 0x60) & 0x1F);
3639 static int mov_write_3gp_udta_tag(AVIOContext *pb, AVFormatContext *s,
3640 const char *tag, const char *str)
3642 int64_t pos = avio_tell(pb);
3643 AVDictionaryEntry *t = av_dict_get(s->metadata, str, NULL, 0);
3644 if (!t || !utf8len(t->value))
3646 avio_wb32(pb, 0); /* size */
3647 ffio_wfourcc(pb, tag); /* type */
3648 avio_wb32(pb, 0); /* version + flags */
3649 if (!strcmp(tag, "yrrc"))
3650 avio_wb16(pb, atoi(t->value));
3652 avio_wb16(pb, language_code("eng")); /* language */
3653 avio_write(pb, t->value, strlen(t->value) + 1); /* UTF8 string value */
3654 if (!strcmp(tag, "albm") &&
3655 (t = av_dict_get(s->metadata, "track", NULL, 0)))
3656 avio_w8(pb, atoi(t->value));
3658 return update_size(pb, pos);
3661 static int mov_write_chpl_tag(AVIOContext *pb, AVFormatContext *s)
3663 int64_t pos = avio_tell(pb);
3664 int i, nb_chapters = FFMIN(s->nb_chapters, 255);
3666 avio_wb32(pb, 0); // size
3667 ffio_wfourcc(pb, "chpl");
3668 avio_wb32(pb, 0x01000000); // version + flags
3669 avio_wb32(pb, 0); // unknown
3670 avio_w8(pb, nb_chapters);
3672 for (i = 0; i < nb_chapters; i++) {
3673 AVChapter *c = s->chapters[i];
3674 AVDictionaryEntry *t;
3675 avio_wb64(pb, av_rescale_q(c->start, c->time_base, (AVRational){1,10000000}));
3677 if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
3678 int len = FFMIN(strlen(t->value), 255);
3680 avio_write(pb, t->value, len);
3684 return update_size(pb, pos);
3687 static int mov_write_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
3690 AVIOContext *pb_buf;
3694 ret = avio_open_dyn_buf(&pb_buf);
3698 if (mov->mode & MODE_3GP) {
3699 mov_write_3gp_udta_tag(pb_buf, s, "perf", "artist");
3700 mov_write_3gp_udta_tag(pb_buf, s, "titl", "title");
3701 mov_write_3gp_udta_tag(pb_buf, s, "auth", "author");
3702 mov_write_3gp_udta_tag(pb_buf, s, "gnre", "genre");
3703 mov_write_3gp_udta_tag(pb_buf, s, "dscp", "comment");
3704 mov_write_3gp_udta_tag(pb_buf, s, "albm", "album");
3705 mov_write_3gp_udta_tag(pb_buf, s, "cprt", "copyright");
3706 mov_write_3gp_udta_tag(pb_buf, s, "yrrc", "date");
3707 mov_write_loci_tag(s, pb_buf);
3708 } else if (mov->mode == MODE_MOV && !(mov->flags & FF_MOV_FLAG_USE_MDTA)) { // the title field breaks gtkpod with mp4 and my suspicion is that stuff is not valid in mp4
3709 mov_write_string_metadata(s, pb_buf, "\251ART", "artist", 0);
3710 mov_write_string_metadata(s, pb_buf, "\251nam", "title", 0);
3711 mov_write_string_metadata(s, pb_buf, "\251aut", "author", 0);
3712 mov_write_string_metadata(s, pb_buf, "\251alb", "album", 0);
3713 mov_write_string_metadata(s, pb_buf, "\251day", "date", 0);
3714 mov_write_string_metadata(s, pb_buf, "\251swr", "encoder", 0);
3715 // currently ignored by mov.c
3716 mov_write_string_metadata(s, pb_buf, "\251des", "comment", 0);
3717 // add support for libquicktime, this atom is also actually read by mov.c
3718 mov_write_string_metadata(s, pb_buf, "\251cmt", "comment", 0);
3719 mov_write_string_metadata(s, pb_buf, "\251gen", "genre", 0);
3720 mov_write_string_metadata(s, pb_buf, "\251cpy", "copyright", 0);
3721 mov_write_string_metadata(s, pb_buf, "\251mak", "make", 0);
3722 mov_write_string_metadata(s, pb_buf, "\251mod", "model", 0);
3723 mov_write_string_metadata(s, pb_buf, "\251xyz", "location", 0);
3724 mov_write_string_metadata(s, pb_buf, "\251key", "keywords", 0);
3725 mov_write_raw_metadata_tag(s, pb_buf, "XMP_", "xmp");
3727 /* iTunes meta data */
3728 mov_write_meta_tag(pb_buf, mov, s);
3729 mov_write_loci_tag(s, pb_buf);
3732 if (s->nb_chapters && !(mov->flags & FF_MOV_FLAG_DISABLE_CHPL))
3733 mov_write_chpl_tag(pb_buf, s);
3735 if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) {
3736 avio_wb32(pb, size + 8);
3737 ffio_wfourcc(pb, "udta");
3738 avio_write(pb, buf, size);
3745 static void mov_write_psp_udta_tag(AVIOContext *pb,
3746 const char *str, const char *lang, int type)
3748 int len = utf8len(str) + 1;
3751 avio_wb16(pb, len * 2 + 10); /* size */
3752 avio_wb32(pb, type); /* type */
3753 avio_wb16(pb, language_code(lang)); /* language */
3754 avio_wb16(pb, 0x01); /* ? */
3755 ascii_to_wc(pb, str);
3758 static int mov_write_uuidusmt_tag(AVIOContext *pb, AVFormatContext *s)
3760 AVDictionaryEntry *title = av_dict_get(s->metadata, "title", NULL, 0);
3764 pos = avio_tell(pb);
3765 avio_wb32(pb, 0); /* size placeholder*/
3766 ffio_wfourcc(pb, "uuid");
3767 ffio_wfourcc(pb, "USMT");
3768 avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
3769 avio_wb32(pb, 0xbb88695c);
3770 avio_wb32(pb, 0xfac9c740);
3772 pos2 = avio_tell(pb);
3773 avio_wb32(pb, 0); /* size placeholder*/
3774 ffio_wfourcc(pb, "MTDT");
3778 avio_wb16(pb, 0x0C); /* size */
3779 avio_wb32(pb, 0x0B); /* type */
3780 avio_wb16(pb, language_code("und")); /* language */
3781 avio_wb16(pb, 0x0); /* ? */
3782 avio_wb16(pb, 0x021C); /* data */
3784 if (!(s->flags & AVFMT_FLAG_BITEXACT))
3785 mov_write_psp_udta_tag(pb, LIBAVCODEC_IDENT, "eng", 0x04);
3786 mov_write_psp_udta_tag(pb, title->value, "eng", 0x01);
3787 mov_write_psp_udta_tag(pb, "2006/04/01 11:11:11", "und", 0x03);
3789 update_size(pb, pos2);
3790 return update_size(pb, pos);
3796 static void build_chunks(MOVTrack *trk)
3799 MOVIentry *chunk = &trk->cluster[0];
3800 uint64_t chunkSize = chunk->size;
3801 chunk->chunkNum = 1;
3802 if (trk->chunkCount)
3804 trk->chunkCount = 1;
3805 for (i = 1; i<trk->entry; i++){
3806 if (chunk->pos + chunkSize == trk->cluster[i].pos &&
3807 chunkSize + trk->cluster[i].size < (1<<20)){
3808 chunkSize += trk->cluster[i].size;
3809 chunk->samples_in_chunk += trk->cluster[i].entries;
3811 trk->cluster[i].chunkNum = chunk->chunkNum+1;
3812 chunk=&trk->cluster[i];
3813 chunkSize = chunk->size;
3820 * Assign track ids. If option "use_stream_ids_as_track_ids" is set,
3821 * the stream ids are used as track ids.
3823 * This assumes mov->tracks and s->streams are in the same order and
3824 * there are no gaps in either of them (so mov->tracks[n] refers to
3827 * As an exception, there can be more entries in
3828 * s->streams than in mov->tracks, in which case new track ids are
3829 * generated (starting after the largest found stream id).
3831 static int mov_setup_track_ids(MOVMuxContext *mov, AVFormatContext *s)
3835 if (mov->track_ids_ok)
3838 if (mov->use_stream_ids_as_track_ids) {
3839 int next_generated_track_id = 0;
3840 for (i = 0; i < s->nb_streams; i++) {
3841 if (s->streams[i]->id > next_generated_track_id)
3842 next_generated_track_id = s->streams[i]->id;
3845 for (i = 0; i < mov->nb_streams; i++) {
3846 if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
3849 mov->tracks[i].track_id = i >= s->nb_streams ? ++next_generated_track_id : s->streams[i]->id;
3852 for (i = 0; i < mov->nb_streams; i++) {
3853 if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
3856 mov->tracks[i].track_id = i + 1;
3860 mov->track_ids_ok = 1;
3865 static int mov_write_moov_tag(AVIOContext *pb, MOVMuxContext *mov,
3869 int64_t pos = avio_tell(pb);
3870 avio_wb32(pb, 0); /* size placeholder*/
3871 ffio_wfourcc(pb, "moov");
3873 mov_setup_track_ids(mov, s);
3875 for (i = 0; i < mov->nb_streams; i++) {
3876 if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
3879 mov->tracks[i].time = mov->time;
3881 if (mov->tracks[i].entry)
3882 build_chunks(&mov->tracks[i]);
3885 if (mov->chapter_track)
3886 for (i = 0; i < s->nb_streams; i++) {
3887 mov->tracks[i].tref_tag = MKTAG('c','h','a','p');
3888 mov->tracks[i].tref_id = mov->tracks[mov->chapter_track].track_id;
3890 for (i = 0; i < mov->nb_streams; i++) {
3891 MOVTrack *track = &mov->tracks[i];
3892 if (track->tag == MKTAG('r','t','p',' ')) {
3893 track->tref_tag = MKTAG('h','i','n','t');
3894 track->tref_id = mov->tracks[track->src_track].track_id;
3895 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
3896 int * fallback, size;
3897 fallback = (int*)av_stream_get_side_data(track->st,
3898 AV_PKT_DATA_FALLBACK_TRACK,
3900 if (fallback != NULL && size == sizeof(int)) {
3901 if (*fallback >= 0 && *fallback < mov->nb_streams) {
3902 track->tref_tag = MKTAG('f','a','l','l');
3903 track->tref_id = mov->tracks[*fallback].track_id;
3908 for (i = 0; i < mov->nb_streams; i++) {
3909 if (mov->tracks[i].tag == MKTAG('t','m','c','d')) {
3910 int src_trk = mov->tracks[i].src_track;
3911 mov->tracks[src_trk].tref_tag = mov->tracks[i].tag;
3912 mov->tracks[src_trk].tref_id = mov->tracks[i].track_id;
3913 //src_trk may have a different timescale than the tmcd track
3914 mov->tracks[i].track_duration = av_rescale(mov->tracks[src_trk].track_duration,
3915 mov->tracks[i].timescale,
3916 mov->tracks[src_trk].timescale);
3920 mov_write_mvhd_tag(pb, mov);
3921 if (mov->mode != MODE_MOV && !mov->iods_skip)
3922 mov_write_iods_tag(pb, mov);
3923 for (i = 0; i < mov->nb_streams; i++) {
3924 if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_FRAGMENT) {
3925 int ret = mov_write_trak_tag(s, pb, mov, &(mov->tracks[i]), i < s->nb_streams ? s->streams[i] : NULL);
3930 if (mov->flags & FF_MOV_FLAG_FRAGMENT)
3931 mov_write_mvex_tag(pb, mov); /* QuickTime requires trak to precede this */
3933 if (mov->mode == MODE_PSP)
3934 mov_write_uuidusmt_tag(pb, s);
3936 mov_write_udta_tag(pb, mov, s);
3938 return update_size(pb, pos);
3941 static void param_write_int(AVIOContext *pb, const char *name, int value)
3943 avio_printf(pb, "<param name=\"%s\" value=\"%d\" valuetype=\"data\"/>\n", name, value);
3946 static void param_write_string(AVIOContext *pb, const char *name, const char *value)
3948 avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, value);
3951 static void param_write_hex(AVIOContext *pb, const char *name, const uint8_t *value, int len)
3954 len = FFMIN(sizeof(buf) / 2 - 1, len);
3955 ff_data_to_hex(buf, value, len, 0);
3956 buf[2 * len] = '\0';
3957 avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, buf);
3960 static int mov_write_isml_manifest(AVIOContext *pb, MOVMuxContext *mov, AVFormatContext *s)
3962 int64_t pos = avio_tell(pb);
3964 int64_t manifest_bit_rate = 0;
3965 AVCPBProperties *props = NULL;
3967 static const uint8_t uuid[] = {
3968 0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd,
3969 0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66
3973 ffio_wfourcc(pb, "uuid");
3974 avio_write(pb, uuid, sizeof(uuid));
3977 avio_printf(pb, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
3978 avio_printf(pb, "<smil xmlns=\"http://www.w3.org/2001/SMIL20/Language\">\n");
3979 avio_printf(pb, "<head>\n");
3980 if (!(mov->fc->flags & AVFMT_FLAG_BITEXACT))
3981 avio_printf(pb, "<meta name=\"creator\" content=\"%s\" />\n",
3983 avio_printf(pb, "</head>\n");
3984 avio_printf(pb, "<body>\n");
3985 avio_printf(pb, "<switch>\n");
3987 mov_setup_track_ids(mov, s);
3989 for (i = 0; i < mov->nb_streams; i++) {
3990 MOVTrack *track = &mov->tracks[i];
3992 int track_id = track->track_id;
3993 char track_name_buf[32] = { 0 };
3995 AVStream *st = track->st;
3996 AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0);
3998 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
4000 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
4005 if (st->disposition & AV_DISPOSITION_ATTACHED_PIC)
4008 props = (AVCPBProperties*)av_stream_get_side_data(track->st, AV_PKT_DATA_CPB_PROPERTIES, NULL);
4010 if (track->par->bit_rate) {
4011 manifest_bit_rate = track->par->bit_rate;
4013 manifest_bit_rate = props->max_bitrate;
4016 avio_printf(pb, "<%s systemBitrate=\"%"PRId64"\">\n", type,
4018 param_write_int(pb, "systemBitrate", manifest_bit_rate);
4019 param_write_int(pb, "trackID", track_id);
4020 param_write_string(pb, "systemLanguage", lang ? lang->value : "und");
4022 /* Build track name piece by piece: */
4024 av_strlcat(track_name_buf, type, sizeof(track_name_buf));
4025 /* 2. track language, if available */
4027 av_strlcatf(track_name_buf, sizeof(track_name_buf),
4028 "_%s", lang->value);
4029 /* 3. special type suffix */
4030 /* "_cc" = closed captions, "_ad" = audio_description */
4031 if (st->disposition & AV_DISPOSITION_HEARING_IMPAIRED)
4032 av_strlcat(track_name_buf, "_cc", sizeof(track_name_buf));
4033 else if (st->disposition & AV_DISPOSITION_VISUAL_IMPAIRED)
4034 av_strlcat(track_name_buf, "_ad", sizeof(track_name_buf));
4036 param_write_string(pb, "trackName", track_name_buf);
4038 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
4039 if (track->par->codec_id == AV_CODEC_ID_H264) {
4041 int size = track->par->extradata_size;
4042 if (!ff_avc_write_annexb_extradata(track->par->extradata, &ptr,
4044 param_write_hex(pb, "CodecPrivateData",
4045 ptr ? ptr : track->par->extradata,
4049 param_write_string(pb, "FourCC", "H264");
4050 } else if (track->par->codec_id == AV_CODEC_ID_VC1) {
4051 param_write_string(pb, "FourCC", "WVC1");
4052 param_write_hex(pb, "CodecPrivateData", track->par->extradata,
4053 track->par->extradata_size);
4055 param_write_int(pb, "MaxWidth", track->par->width);
4056 param_write_int(pb, "MaxHeight", track->par->height);
4057 param_write_int(pb, "DisplayWidth", track->par->width);
4058 param_write_int(pb, "DisplayHeight", track->par->height);
4060 if (track->par->codec_id == AV_CODEC_ID_AAC) {
4061 switch (track->par->profile)
4063 case FF_PROFILE_AAC_HE_V2:
4064 param_write_string(pb, "FourCC", "AACP");
4066 case FF_PROFILE_AAC_HE:
4067 param_write_string(pb, "FourCC", "AACH");
4070 param_write_string(pb, "FourCC", "AACL");
4072 } else if (track->par->codec_id == AV_CODEC_ID_WMAPRO) {
4073 param_write_string(pb, "FourCC", "WMAP");
4075 param_write_hex(pb, "CodecPrivateData", track->par->extradata,
4076 track->par->extradata_size);
4077 param_write_int(pb, "AudioTag", ff_codec_get_tag(ff_codec_wav_tags,
4078 track->par->codec_id));
4079 param_write_int(pb, "Channels", track->par->channels);
4080 param_write_int(pb, "SamplingRate", track->par->sample_rate);
4081 param_write_int(pb, "BitsPerSample", 16);
4082 param_write_int(pb, "PacketSize", track->par->block_align ?
4083 track->par->block_align : 4);
4085 avio_printf(pb, "</%s>\n", type);
4087 avio_printf(pb, "</switch>\n");
4088 avio_printf(pb, "</body>\n");
4089 avio_printf(pb, "</smil>\n");
4091 return update_size(pb, pos);
4094 static int mov_write_mfhd_tag(AVIOContext *pb, MOVMuxContext *mov)
4097 ffio_wfourcc(pb, "mfhd");
4099 avio_wb32(pb, mov->fragments);
4103 static uint32_t get_sample_flags(MOVTrack *track, MOVIentry *entry)
4105 return entry->flags & MOV_SYNC_SAMPLE ? MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO :
4106 (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC);
4109 static int mov_write_tfhd_tag(AVIOContext *pb, MOVMuxContext *mov,
4110 MOVTrack *track, int64_t moof_offset)
4112 int64_t pos = avio_tell(pb);
4113 uint32_t flags = MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
4114 MOV_TFHD_BASE_DATA_OFFSET;
4115 if (!track->entry) {
4116 flags |= MOV_TFHD_DURATION_IS_EMPTY;
4118 flags |= MOV_TFHD_DEFAULT_FLAGS;
4120 if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET)
4121 flags &= ~MOV_TFHD_BASE_DATA_OFFSET;
4122 if (mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) {
4123 flags &= ~MOV_TFHD_BASE_DATA_OFFSET;
4124 flags |= MOV_TFHD_DEFAULT_BASE_IS_MOOF;
4127 /* Don't set a default sample size, the silverlight player refuses
4128 * to play files with that set. Don't set a default sample duration,
4129 * WMP freaks out if it is set. Don't set a base data offset, PIFF
4130 * file format says it MUST NOT be set. */
4131 if (track->mode == MODE_ISM)
4132 flags &= ~(MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
4133 MOV_TFHD_BASE_DATA_OFFSET);
4135 avio_wb32(pb, 0); /* size placeholder */
4136 ffio_wfourcc(pb, "tfhd");
4137 avio_w8(pb, 0); /* version */
4138 avio_wb24(pb, flags);
4140 avio_wb32(pb, track->track_id); /* track-id */
4141 if (flags & MOV_TFHD_BASE_DATA_OFFSET)
4142 avio_wb64(pb, moof_offset);
4143 if (flags & MOV_TFHD_DEFAULT_DURATION) {
4144 track->default_duration = get_cluster_duration(track, 0);
4145 avio_wb32(pb, track->default_duration);
4147 if (flags & MOV_TFHD_DEFAULT_SIZE) {
4148 track->default_size = track->entry ? track->cluster[0].size : 1;
4149 avio_wb32(pb, track->default_size);
4151 track->default_size = -1;
4153 if (flags & MOV_TFHD_DEFAULT_FLAGS) {
4154 /* Set the default flags based on the second sample, if available.
4155 * If the first sample is different, that can be signaled via a separate field. */
4156 if (track->entry > 1)
4157 track->default_sample_flags = get_sample_flags(track, &track->cluster[1]);
4159 track->default_sample_flags =
4160 track->par->codec_type == AVMEDIA_TYPE_VIDEO ?
4161 (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC) :
4162 MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO;
4163 avio_wb32(pb, track->default_sample_flags);
4166 return update_size(pb, pos);
4169 static int mov_write_trun_tag(AVIOContext *pb, MOVMuxContext *mov,
4170 MOVTrack *track, int moof_size,
4173 int64_t pos = avio_tell(pb);
4174 uint32_t flags = MOV_TRUN_DATA_OFFSET;
4177 for (i = first; i < end; i++) {
4178 if (get_cluster_duration(track, i) != track->default_duration)
4179 flags |= MOV_TRUN_SAMPLE_DURATION;
4180 if (track->cluster[i].size != track->default_size)
4181 flags |= MOV_TRUN_SAMPLE_SIZE;
4182 if (i > first && get_sample_flags(track, &track->cluster[i]) != track->default_sample_flags)
4183 flags |= MOV_TRUN_SAMPLE_FLAGS;
4185 if (!(flags & MOV_TRUN_SAMPLE_FLAGS) && track->entry > 0 &&
4186 get_sample_flags(track, &track->cluster[0]) != track->default_sample_flags)
4187 flags |= MOV_TRUN_FIRST_SAMPLE_FLAGS;
4188 if (track->flags & MOV_TRACK_CTTS)
4189 flags |= MOV_TRUN_SAMPLE_CTS;
4191 avio_wb32(pb, 0); /* size placeholder */
4192 ffio_wfourcc(pb, "trun");
4193 if (mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS)
4194 avio_w8(pb, 1); /* version */
4196 avio_w8(pb, 0); /* version */
4197 avio_wb24(pb, flags);
4199 avio_wb32(pb, end - first); /* sample count */
4200 if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET &&
4201 !(mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) &&
4203 avio_wb32(pb, 0); /* Later tracks follow immediately after the previous one */
4205 avio_wb32(pb, moof_size + 8 + track->data_offset +
4206 track->cluster[first].pos); /* data offset */
4207 if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS)
4208 avio_wb32(pb, get_sample_flags(track, &track->cluster[first]));
4210 for (i = first; i < end; i++) {
4211 if (flags & MOV_TRUN_SAMPLE_DURATION)
4212 avio_wb32(pb, get_cluster_duration(track, i));
4213 if (flags & MOV_TRUN_SAMPLE_SIZE)
4214 avio_wb32(pb, track->cluster[i].size);
4215 if (flags & MOV_TRUN_SAMPLE_FLAGS)
4216 avio_wb32(pb, get_sample_flags(track, &track->cluster[i]));
4217 if (flags & MOV_TRUN_SAMPLE_CTS)
4218 avio_wb32(pb, track->cluster[i].cts);
4221 mov->first_trun = 0;
4222 return update_size(pb, pos);
4225 static int mov_write_tfxd_tag(AVIOContext *pb, MOVTrack *track)
4227 int64_t pos = avio_tell(pb);
4228 static const uint8_t uuid[] = {
4229 0x6d, 0x1d, 0x9b, 0x05, 0x42, 0xd5, 0x44, 0xe6,
4230 0x80, 0xe2, 0x14, 0x1d, 0xaf, 0xf7, 0x57, 0xb2
4233 avio_wb32(pb, 0); /* size placeholder */
4234 ffio_wfourcc(pb, "uuid");
4235 avio_write(pb, uuid, sizeof(uuid));
4238 avio_wb64(pb, track->start_dts + track->frag_start +
4239 track->cluster[0].cts);
4240 avio_wb64(pb, track->end_pts -
4241 (track->cluster[0].dts + track->cluster[0].cts));
4243 return update_size(pb, pos);
4246 static int mov_write_tfrf_tag(AVIOContext *pb, MOVMuxContext *mov,
4247 MOVTrack *track, int entry)
4249 int n = track->nb_frag_info - 1 - entry, i;
4250 int size = 8 + 16 + 4 + 1 + 16*n;
4251 static const uint8_t uuid[] = {
4252 0xd4, 0x80, 0x7e, 0xf2, 0xca, 0x39, 0x46, 0x95,
4253 0x8e, 0x54, 0x26, 0xcb, 0x9e, 0x46, 0xa7, 0x9f
4259 avio_seek(pb, track->frag_info[entry].tfrf_offset, SEEK_SET);
4260 avio_wb32(pb, size);
4261 ffio_wfourcc(pb, "uuid");
4262 avio_write(pb, uuid, sizeof(uuid));
4266 for (i = 0; i < n; i++) {
4267 int index = entry + 1 + i;
4268 avio_wb64(pb, track->frag_info[index].time);
4269 avio_wb64(pb, track->frag_info[index].duration);
4271 if (n < mov->ism_lookahead) {
4272 int free_size = 16 * (mov->ism_lookahead - n);
4273 avio_wb32(pb, free_size);
4274 ffio_wfourcc(pb, "free");
4275 ffio_fill(pb, 0, free_size - 8);
4281 static int mov_write_tfrf_tags(AVIOContext *pb, MOVMuxContext *mov,
4284 int64_t pos = avio_tell(pb);
4286 for (i = 0; i < mov->ism_lookahead; i++) {
4287 /* Update the tfrf tag for the last ism_lookahead fragments,
4288 * nb_frag_info - 1 is the next fragment to be written. */
4289 mov_write_tfrf_tag(pb, mov, track, track->nb_frag_info - 2 - i);
4291 avio_seek(pb, pos, SEEK_SET);
4295 static int mov_add_tfra_entries(AVIOContext *pb, MOVMuxContext *mov, int tracks,
4299 for (i = 0; i < mov->nb_streams; i++) {
4300 MOVTrack *track = &mov->tracks[i];
4301 MOVFragmentInfo *info;
4302 if ((tracks >= 0 && i != tracks) || !track->entry)
4304 track->nb_frag_info++;
4305 if (track->nb_frag_info >= track->frag_info_capacity) {
4306 unsigned new_capacity = track->nb_frag_info + MOV_FRAG_INFO_ALLOC_INCREMENT;
4307 if (av_reallocp_array(&track->frag_info,
4309 sizeof(*track->frag_info)))
4310 return AVERROR(ENOMEM);
4311 track->frag_info_capacity = new_capacity;
4313 info = &track->frag_info[track->nb_frag_info - 1];
4314 info->offset = avio_tell(pb);
4316 // Try to recreate the original pts for the first packet
4317 // from the fields we have stored
4318 info->time = track->start_dts + track->frag_start +
4319 track->cluster[0].cts;
4320 info->duration = track->end_pts -
4321 (track->cluster[0].dts + track->cluster[0].cts);
4322 // If the pts is less than zero, we will have trimmed
4323 // away parts of the media track using an edit list,
4324 // and the corresponding start presentation time is zero.
4325 if (info->time < 0) {
4326 info->duration += info->time;
4329 info->tfrf_offset = 0;
4330 mov_write_tfrf_tags(pb, mov, track);
4335 static void mov_prune_frag_info(MOVMuxContext *mov, int tracks, int max)
4338 for (i = 0; i < mov->nb_streams; i++) {
4339 MOVTrack *track = &mov->tracks[i];
4340 if ((tracks >= 0 && i != tracks) || !track->entry)
4342 if (track->nb_frag_info > max) {
4343 memmove(track->frag_info, track->frag_info + (track->nb_frag_info - max), max * sizeof(*track->frag_info));
4344 track->nb_frag_info = max;
4349 static int mov_write_tfdt_tag(AVIOContext *pb, MOVTrack *track)
4351 int64_t pos = avio_tell(pb);
4353 avio_wb32(pb, 0); /* size */
4354 ffio_wfourcc(pb, "tfdt");
4355 avio_w8(pb, 1); /* version */
4357 avio_wb64(pb, track->frag_start);
4358 return update_size(pb, pos);
4361 static int mov_write_traf_tag(AVIOContext *pb, MOVMuxContext *mov,
4362 MOVTrack *track, int64_t moof_offset,
4365 int64_t pos = avio_tell(pb);
4367 avio_wb32(pb, 0); /* size placeholder */
4368 ffio_wfourcc(pb, "traf");
4370 mov_write_tfhd_tag(pb, mov, track, moof_offset);
4371 if (mov->mode != MODE_ISM)
4372 mov_write_tfdt_tag(pb, track);
4373 for (i = 1; i < track->entry; i++) {
4374 if (track->cluster[i].pos != track->cluster[i - 1].pos + track->cluster[i - 1].size) {
4375 mov_write_trun_tag(pb, mov, track, moof_size, start, i);
4379 mov_write_trun_tag(pb, mov, track, moof_size, start, track->entry);
4380 if (mov->mode == MODE_ISM) {
4381 mov_write_tfxd_tag(pb, track);
4383 if (mov->ism_lookahead) {
4384 int i, size = 16 + 4 + 1 + 16 * mov->ism_lookahead;
4386 if (track->nb_frag_info > 0) {
4387 MOVFragmentInfo *info = &track->frag_info[track->nb_frag_info - 1];
4388 if (!info->tfrf_offset)
4389 info->tfrf_offset = avio_tell(pb);
4391 avio_wb32(pb, 8 + size);
4392 ffio_wfourcc(pb, "free");
4393 for (i = 0; i < size; i++)
4398 return update_size(pb, pos);
4401 static int mov_write_moof_tag_internal(AVIOContext *pb, MOVMuxContext *mov,
4402 int tracks, int moof_size)
4404 int64_t pos = avio_tell(pb);
4407 avio_wb32(pb, 0); /* size placeholder */
4408 ffio_wfourcc(pb, "moof");
4409 mov->first_trun = 1;
4411 mov_write_mfhd_tag(pb, mov);
4412 for (i = 0; i < mov->nb_streams; i++) {
4413 MOVTrack *track = &mov->tracks[i];
4414 if (tracks >= 0 && i != tracks)
4418 mov_write_traf_tag(pb, mov, track, pos, moof_size);
4421 return update_size(pb, pos);
4424 static int mov_write_sidx_tag(AVIOContext *pb,
4425 MOVTrack *track, int ref_size, int total_sidx_size)
4427 int64_t pos = avio_tell(pb), offset_pos, end_pos;
4428 int64_t presentation_time, duration, offset;
4429 int starts_with_SAP, i, entries;
4433 presentation_time = track->start_dts + track->frag_start +
4434 track->cluster[0].cts;
4435 duration = track->end_pts -
4436 (track->cluster[0].dts + track->cluster[0].cts);
4437 starts_with_SAP = track->cluster[0].flags & MOV_SYNC_SAMPLE;
4439 // pts<0 should be cut away using edts
4440 if (presentation_time < 0) {
4441 duration += presentation_time;
4442 presentation_time = 0;
4445 entries = track->nb_frag_info;
4448 presentation_time = track->frag_info[0].time;
4451 avio_wb32(pb, 0); /* size */
4452 ffio_wfourcc(pb, "sidx");
4453 avio_w8(pb, 1); /* version */
4455 avio_wb32(pb, track->track_id); /* reference_ID */
4456 avio_wb32(pb, track->timescale); /* timescale */
4457 avio_wb64(pb, presentation_time); /* earliest_presentation_time */
4458 offset_pos = avio_tell(pb);
4459 avio_wb64(pb, 0); /* first_offset (offset to referenced moof) */
4460 avio_wb16(pb, 0); /* reserved */
4462 avio_wb16(pb, entries); /* reference_count */
4463 for (i = 0; i < entries; i++) {
4464 if (!track->entry) {
4465 if (i > 1 && track->frag_info[i].offset != track->frag_info[i - 1].offset + track->frag_info[i - 1].size) {
4466 av_log(NULL, AV_LOG_ERROR, "Non-consecutive fragments, writing incorrect sidx\n");
4468 duration = track->frag_info[i].duration;
4469 ref_size = track->frag_info[i].size;
4470 starts_with_SAP = 1;
4472 avio_wb32(pb, (0 << 31) | (ref_size & 0x7fffffff)); /* reference_type (0 = media) | referenced_size */
4473 avio_wb32(pb, duration); /* subsegment_duration */
4474 avio_wb32(pb, (starts_with_SAP << 31) | (0 << 28) | 0); /* starts_with_SAP | SAP_type | SAP_delta_time */
4477 end_pos = avio_tell(pb);
4478 offset = pos + total_sidx_size - end_pos;
4479 avio_seek(pb, offset_pos, SEEK_SET);
4480 avio_wb64(pb, offset);
4481 avio_seek(pb, end_pos, SEEK_SET);
4482 return update_size(pb, pos);
4485 static int mov_write_sidx_tags(AVIOContext *pb, MOVMuxContext *mov,
4486 int tracks, int ref_size)
4489 AVIOContext *avio_buf;
4491 for (round = 0; round < 2; round++) {
4492 // First run one round to calculate the total size of all
4494 // This would be much simpler if we'd only write one sidx
4495 // atom, for the first track in the moof.
4497 if ((ret = ffio_open_null_buf(&avio_buf)) < 0)
4502 for (i = 0; i < mov->nb_streams; i++) {
4503 MOVTrack *track = &mov->tracks[i];
4504 if (tracks >= 0 && i != tracks)
4506 // When writing a sidx for the full file, entry is 0, but
4507 // we want to include all tracks. ref_size is 0 in this case,
4508 // since we read it from frag_info instead.
4509 if (!track->entry && ref_size > 0)
4511 total_size -= mov_write_sidx_tag(avio_buf, track, ref_size,
4515 total_size = ffio_close_null_buf(avio_buf);
4520 static int mov_write_prft_tag(AVIOContext *pb, MOVMuxContext *mov, int tracks)
4522 int64_t pos = avio_tell(pb), pts_us, ntp_ts;
4523 MOVTrack *first_track;
4525 /* PRFT should be associated with at most one track. So, choosing only the
4529 first_track = &(mov->tracks[0]);
4531 if (!first_track->entry) {
4532 av_log(mov->fc, AV_LOG_WARNING, "Unable to write PRFT, no entries in the track\n");
4536 if (first_track->cluster[0].pts == AV_NOPTS_VALUE) {
4537 av_log(mov->fc, AV_LOG_WARNING, "Unable to write PRFT, first PTS is invalid\n");
4541 if (mov->write_prft == MOV_PRFT_SRC_WALLCLOCK) {
4542 ntp_ts = ff_get_formatted_ntp_time(ff_ntp_time());
4543 } else if (mov->write_prft == MOV_PRFT_SRC_PTS) {
4544 pts_us = av_rescale_q(first_track->cluster[0].pts,
4545 first_track->st->time_base, AV_TIME_BASE_Q);
4546 ntp_ts = ff_get_formatted_ntp_time(pts_us + NTP_OFFSET_US);
4548 av_log(mov->fc, AV_LOG_WARNING, "Unsupported PRFT box configuration: %d\n",
4553 avio_wb32(pb, 0); // Size place holder
4554 ffio_wfourcc(pb, "prft"); // Type
4555 avio_w8(pb, 1); // Version
4556 avio_wb24(pb, 0); // Flags
4557 avio_wb32(pb, first_track->track_id); // reference track ID
4558 avio_wb64(pb, ntp_ts); // NTP time stamp
4559 avio_wb64(pb, first_track->cluster[0].pts); //media time
4560 return update_size(pb, pos);
4563 static int mov_write_moof_tag(AVIOContext *pb, MOVMuxContext *mov, int tracks,
4566 AVIOContext *avio_buf;
4569 if ((ret = ffio_open_null_buf(&avio_buf)) < 0)
4571 mov_write_moof_tag_internal(avio_buf, mov, tracks, 0);
4572 moof_size = ffio_close_null_buf(avio_buf);
4574 if (mov->flags & FF_MOV_FLAG_DASH && !(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX))
4575 mov_write_sidx_tags(pb, mov, tracks, moof_size + 8 + mdat_size);
4577 if (mov->write_prft > MOV_PRFT_NONE && mov->write_prft < MOV_PRFT_NB)
4578 mov_write_prft_tag(pb, mov, tracks);
4580 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX ||
4581 !(mov->flags & FF_MOV_FLAG_SKIP_TRAILER) ||
4582 mov->ism_lookahead) {
4583 if ((ret = mov_add_tfra_entries(pb, mov, tracks, moof_size + 8 + mdat_size)) < 0)
4585 if (!(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) &&
4586 mov->flags & FF_MOV_FLAG_SKIP_TRAILER) {
4587 mov_prune_frag_info(mov, tracks, mov->ism_lookahead + 1);
4591 return mov_write_moof_tag_internal(pb, mov, tracks, moof_size);
4594 static int mov_write_tfra_tag(AVIOContext *pb, MOVTrack *track)
4596 int64_t pos = avio_tell(pb);
4599 avio_wb32(pb, 0); /* size placeholder */
4600 ffio_wfourcc(pb, "tfra");
4601 avio_w8(pb, 1); /* version */
4604 avio_wb32(pb, track->track_id);
4605 avio_wb32(pb, 0); /* length of traf/trun/sample num */
4606 avio_wb32(pb, track->nb_frag_info);
4607 for (i = 0; i < track->nb_frag_info; i++) {
4608 avio_wb64(pb, track->frag_info[i].time);
4609 avio_wb64(pb, track->frag_info[i].offset + track->data_offset);
4610 avio_w8(pb, 1); /* traf number */
4611 avio_w8(pb, 1); /* trun number */
4612 avio_w8(pb, 1); /* sample number */
4615 return update_size(pb, pos);
4618 static int mov_write_mfra_tag(AVIOContext *pb, MOVMuxContext *mov)
4620 int64_t pos = avio_tell(pb);
4623 avio_wb32(pb, 0); /* size placeholder */
4624 ffio_wfourcc(pb, "mfra");
4625 /* An empty mfra atom is enough to indicate to the publishing point that
4626 * the stream has ended. */
4627 if (mov->flags & FF_MOV_FLAG_ISML)
4628 return update_size(pb, pos);
4630 for (i = 0; i < mov->nb_streams; i++) {
4631 MOVTrack *track = &mov->tracks[i];
4632 if (track->nb_frag_info)
4633 mov_write_tfra_tag(pb, track);
4637 ffio_wfourcc(pb, "mfro");
4638 avio_wb32(pb, 0); /* version + flags */
4639 avio_wb32(pb, avio_tell(pb) + 4 - pos);
4641 return update_size(pb, pos);
4644 static int mov_write_mdat_tag(AVIOContext *pb, MOVMuxContext *mov)
4646 avio_wb32(pb, 8); // placeholder for extended size field (64 bit)
4647 ffio_wfourcc(pb, mov->mode == MODE_MOV ? "wide" : "free");
4649 mov->mdat_pos = avio_tell(pb);
4650 avio_wb32(pb, 0); /* size placeholder*/
4651 ffio_wfourcc(pb, "mdat");
4655 /* TODO: This needs to be more general */
4656 static int mov_write_ftyp_tag(AVIOContext *pb, AVFormatContext *s)
4658 MOVMuxContext *mov = s->priv_data;
4659 int64_t pos = avio_tell(pb);
4660 int has_h264 = 0, has_video = 0;
4664 for (i = 0; i < s->nb_streams; i++) {
4665 AVStream *st = s->streams[i];
4666 if (st->disposition & AV_DISPOSITION_ATTACHED_PIC)
4668 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
4670 if (st->codecpar->codec_id == AV_CODEC_ID_H264)
4674 avio_wb32(pb, 0); /* size */
4675 ffio_wfourcc(pb, "ftyp");
4677 if (mov->major_brand && strlen(mov->major_brand) >= 4)
4678 ffio_wfourcc(pb, mov->major_brand);
4679 else if (mov->mode == MODE_3GP) {
4680 ffio_wfourcc(pb, has_h264 ? "3gp6" : "3gp4");
4681 minor = has_h264 ? 0x100 : 0x200;
4682 } else if (mov->mode & MODE_3G2) {
4683 ffio_wfourcc(pb, has_h264 ? "3g2b" : "3g2a");
4684 minor = has_h264 ? 0x20000 : 0x10000;
4685 } else if (mov->mode == MODE_PSP)
4686 ffio_wfourcc(pb, "MSNV");
4687 else if (mov->mode == MODE_MP4 && mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)
4688 ffio_wfourcc(pb, "iso5"); // Required when using default-base-is-moof
4689 else if (mov->mode == MODE_MP4 && mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS)
4690 ffio_wfourcc(pb, "iso4");
4691 else if (mov->mode == MODE_MP4)
4692 ffio_wfourcc(pb, "isom");
4693 else if (mov->mode == MODE_IPOD)
4694 ffio_wfourcc(pb, has_video ? "M4V ":"M4A ");
4695 else if (mov->mode == MODE_ISM)
4696 ffio_wfourcc(pb, "isml");
4697 else if (mov->mode == MODE_F4V)
4698 ffio_wfourcc(pb, "f4v ");
4700 ffio_wfourcc(pb, "qt ");
4702 avio_wb32(pb, minor);
4704 if (mov->mode == MODE_MOV)
4705 ffio_wfourcc(pb, "qt ");
4706 else if (mov->mode == MODE_ISM) {
4707 ffio_wfourcc(pb, "piff");
4708 } else if (!(mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)) {
4709 ffio_wfourcc(pb, "isom");
4710 ffio_wfourcc(pb, "iso2");
4712 ffio_wfourcc(pb, "avc1");
4715 // We add tfdt atoms when fragmenting, signal this with the iso6 compatible
4716 // brand. This is compatible with users that don't understand tfdt.
4717 if (mov->flags & FF_MOV_FLAG_FRAGMENT && mov->mode != MODE_ISM)
4718 ffio_wfourcc(pb, "iso6");
4720 if (mov->mode == MODE_3GP)
4721 ffio_wfourcc(pb, has_h264 ? "3gp6":"3gp4");
4722 else if (mov->mode & MODE_3G2)
4723 ffio_wfourcc(pb, has_h264 ? "3g2b":"3g2a");
4724 else if (mov->mode == MODE_PSP)
4725 ffio_wfourcc(pb, "MSNV");
4726 else if (mov->mode == MODE_MP4)
4727 ffio_wfourcc(pb, "mp41");
4729 if (mov->flags & FF_MOV_FLAG_DASH && mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
4730 ffio_wfourcc(pb, "dash");
4732 return update_size(pb, pos);
4735 static int mov_write_uuidprof_tag(AVIOContext *pb, AVFormatContext *s)
4737 AVStream *video_st = s->streams[0];
4738 AVCodecParameters *video_par = s->streams[0]->codecpar;
4739 AVCodecParameters *audio_par = s->streams[1]->codecpar;
4740 int audio_rate = audio_par->sample_rate;
4741 int64_t frame_rate = video_st->avg_frame_rate.den ?
4742 (video_st->avg_frame_rate.num * 0x10000LL) / video_st->avg_frame_rate.den :
4744 int audio_kbitrate = audio_par->bit_rate / 1000;
4745 int video_kbitrate = FFMIN(video_par->bit_rate / 1000, 800 - audio_kbitrate);
4747 if (frame_rate < 0 || frame_rate > INT32_MAX) {
4748 av_log(s, AV_LOG_ERROR, "Frame rate %f outside supported range\n", frame_rate / (double)0x10000);
4749 return AVERROR(EINVAL);
4752 avio_wb32(pb, 0x94); /* size */
4753 ffio_wfourcc(pb, "uuid");
4754 ffio_wfourcc(pb, "PROF");
4756 avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
4757 avio_wb32(pb, 0xbb88695c);
4758 avio_wb32(pb, 0xfac9c740);
4760 avio_wb32(pb, 0x0); /* ? */
4761 avio_wb32(pb, 0x3); /* 3 sections ? */
4763 avio_wb32(pb, 0x14); /* size */
4764 ffio_wfourcc(pb, "FPRF");
4765 avio_wb32(pb, 0x0); /* ? */
4766 avio_wb32(pb, 0x0); /* ? */
4767 avio_wb32(pb, 0x0); /* ? */
4769 avio_wb32(pb, 0x2c); /* size */
4770 ffio_wfourcc(pb, "APRF"); /* audio */
4772 avio_wb32(pb, 0x2); /* TrackID */
4773 ffio_wfourcc(pb, "mp4a");
4774 avio_wb32(pb, 0x20f);
4776 avio_wb32(pb, audio_kbitrate);
4777 avio_wb32(pb, audio_kbitrate);
4778 avio_wb32(pb, audio_rate);
4779 avio_wb32(pb, audio_par->channels);
4781 avio_wb32(pb, 0x34); /* size */
4782 ffio_wfourcc(pb, "VPRF"); /* video */
4784 avio_wb32(pb, 0x1); /* TrackID */
4785 if (video_par->codec_id == AV_CODEC_ID_H264) {
4786 ffio_wfourcc(pb, "avc1");
4787 avio_wb16(pb, 0x014D);
4788 avio_wb16(pb, 0x0015);
4790 ffio_wfourcc(pb, "mp4v");
4791 avio_wb16(pb, 0x0000);
4792 avio_wb16(pb, 0x0103);
4795 avio_wb32(pb, video_kbitrate);
4796 avio_wb32(pb, video_kbitrate);
4797 avio_wb32(pb, frame_rate);
4798 avio_wb32(pb, frame_rate);
4799 avio_wb16(pb, video_par->width);
4800 avio_wb16(pb, video_par->height);
4801 avio_wb32(pb, 0x010001); /* ? */
4806 static int mov_write_identification(AVIOContext *pb, AVFormatContext *s)
4808 MOVMuxContext *mov = s->priv_data;
4811 mov_write_ftyp_tag(pb,s);
4812 if (mov->mode == MODE_PSP) {
4813 int video_streams_nb = 0, audio_streams_nb = 0, other_streams_nb = 0;
4814 for (i = 0; i < s->nb_streams; i++) {
4815 AVStream *st = s->streams[i];
4816 if (st->disposition & AV_DISPOSITION_ATTACHED_PIC)
4818 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
4820 else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
4826 if (video_streams_nb != 1 || audio_streams_nb != 1 || other_streams_nb) {
4827 av_log(s, AV_LOG_ERROR, "PSP mode need one video and one audio stream\n");
4828 return AVERROR(EINVAL);
4830 return mov_write_uuidprof_tag(pb, s);
4835 static int mov_parse_mpeg2_frame(AVPacket *pkt, uint32_t *flags)
4838 int i, closed_gop = 0;
4840 for (i = 0; i < pkt->size - 4; i++) {
4841 c = (c << 8) + pkt->data[i];
4842 if (c == 0x1b8) { // gop
4843 closed_gop = pkt->data[i + 4] >> 6 & 0x01;
4844 } else if (c == 0x100) { // pic
4845 int temp_ref = (pkt->data[i + 1] << 2) | (pkt->data[i + 2] >> 6);
4846 if (!temp_ref || closed_gop) // I picture is not reordered
4847 *flags = MOV_SYNC_SAMPLE;
4849 *flags = MOV_PARTIAL_SYNC_SAMPLE;
4856 static void mov_parse_vc1_frame(AVPacket *pkt, MOVTrack *trk)
4858 const uint8_t *start, *next, *end = pkt->data + pkt->size;
4859 int seq = 0, entry = 0;
4860 int key = pkt->flags & AV_PKT_FLAG_KEY;
4861 start = find_next_marker(pkt->data, end);
4862 for (next = start; next < end; start = next) {
4863 next = find_next_marker(start + 4, end);
4864 switch (AV_RB32(start)) {
4865 case VC1_CODE_SEQHDR:
4868 case VC1_CODE_ENTRYPOINT:
4871 case VC1_CODE_SLICE:
4872 trk->vc1_info.slices = 1;
4876 if (!trk->entry && trk->vc1_info.first_packet_seen)
4877 trk->vc1_info.first_frag_written = 1;
4878 if (!trk->entry && !trk->vc1_info.first_frag_written) {
4879 /* First packet in first fragment */
4880 trk->vc1_info.first_packet_seq = seq;
4881 trk->vc1_info.first_packet_entry = entry;
4882 trk->vc1_info.first_packet_seen = 1;
4883 } else if ((seq && !trk->vc1_info.packet_seq) ||
4884 (entry && !trk->vc1_info.packet_entry)) {
4886 for (i = 0; i < trk->entry; i++)
4887 trk->cluster[i].flags &= ~MOV_SYNC_SAMPLE;
4888 trk->has_keyframes = 0;
4890 trk->vc1_info.packet_seq = 1;
4892 trk->vc1_info.packet_entry = 1;
4893 if (!trk->vc1_info.first_frag_written) {
4894 /* First fragment */
4895 if ((!seq || trk->vc1_info.first_packet_seq) &&
4896 (!entry || trk->vc1_info.first_packet_entry)) {
4897 /* First packet had the same headers as this one, readd the
4898 * sync sample flag. */
4899 trk->cluster[0].flags |= MOV_SYNC_SAMPLE;
4900 trk->has_keyframes = 1;
4904 if (trk->vc1_info.packet_seq && trk->vc1_info.packet_entry)
4906 else if (trk->vc1_info.packet_seq)
4908 else if (trk->vc1_info.packet_entry)
4911 trk->cluster[trk->entry].flags |= MOV_SYNC_SAMPLE;
4912 trk->has_keyframes++;
4916 static int mov_flush_fragment_interleaving(AVFormatContext *s, MOVTrack *track)
4918 MOVMuxContext *mov = s->priv_data;
4923 if (!track->mdat_buf)
4925 if (!mov->mdat_buf) {
4926 if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0)
4929 buf_size = avio_close_dyn_buf(track->mdat_buf, &buf);
4930 track->mdat_buf = NULL;
4932 offset = avio_tell(mov->mdat_buf);
4933 avio_write(mov->mdat_buf, buf, buf_size);
4936 for (i = track->entries_flushed; i < track->entry; i++)
4937 track->cluster[i].pos += offset;
4938 track->entries_flushed = track->entry;
4942 static int mov_flush_fragment(AVFormatContext *s, int force)
4944 MOVMuxContext *mov = s->priv_data;
4945 int i, first_track = -1;
4946 int64_t mdat_size = 0;
4948 int has_video = 0, starts_with_key = 0, first_video_track = 1;
4950 if (!(mov->flags & FF_MOV_FLAG_FRAGMENT))
4953 // Try to fill in the duration of the last packet in each stream
4954 // from queued packets in the interleave queues. If the flushing
4955 // of fragments was triggered automatically by an AVPacket, we
4956 // already have reliable info for the end of that track, but other
4957 // tracks may need to be filled in.
4958 for (i = 0; i < s->nb_streams; i++) {
4959 MOVTrack *track = &mov->tracks[i];
4960 if (!track->end_reliable) {
4962 if (!ff_interleaved_peek(s, i, &pkt, 1)) {
4963 if (track->dts_shift != AV_NOPTS_VALUE)
4964 pkt.dts += track->dts_shift;
4965 track->track_duration = pkt.dts - track->start_dts;
4966 if (pkt.pts != AV_NOPTS_VALUE)
4967 track->end_pts = pkt.pts;
4969 track->end_pts = pkt.dts;
4974 for (i = 0; i < mov->nb_streams; i++) {
4975 MOVTrack *track = &mov->tracks[i];
4976 if (track->entry <= 1)
4978 // Sample durations are calculated as the diff of dts values,
4979 // but for the last sample in a fragment, we don't know the dts
4980 // of the first sample in the next fragment, so we have to rely
4981 // on what was set as duration in the AVPacket. Not all callers
4982 // set this though, so we might want to replace it with an
4983 // estimate if it currently is zero.
4984 if (get_cluster_duration(track, track->entry - 1) != 0)
4986 // Use the duration (i.e. dts diff) of the second last sample for
4987 // the last one. This is a wild guess (and fatal if it turns out
4988 // to be too long), but probably the best we can do - having a zero
4989 // duration is bad as well.
4990 track->track_duration += get_cluster_duration(track, track->entry - 2);
4991 track->end_pts += get_cluster_duration(track, track->entry - 2);
4992 if (!mov->missing_duration_warned) {
4993 av_log(s, AV_LOG_WARNING,
4994 "Estimating the duration of the last packet in a "
4995 "fragment, consider setting the duration field in "
4996 "AVPacket instead.\n");
4997 mov->missing_duration_warned = 1;
5001 if (!mov->moov_written) {
5002 int64_t pos = avio_tell(s->pb);
5004 int buf_size, moov_size;
5006 for (i = 0; i < mov->nb_streams; i++)
5007 if (!mov->tracks[i].entry &&
5008 (i >= s->nb_streams || !(s->streams[i]->disposition & AV_DISPOSITION_ATTACHED_PIC)))
5010 /* Don't write the initial moov unless all tracks have data */
5011 if (i < mov->nb_streams && !force)
5014 moov_size = get_moov_size(s);
5015 for (i = 0; i < mov->nb_streams; i++)
5016 mov->tracks[i].data_offset = pos + moov_size + 8;
5018 avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_HEADER);
5019 if (mov->flags & FF_MOV_FLAG_DELAY_MOOV)
5020 mov_write_identification(s->pb, s);
5021 if ((ret = mov_write_moov_tag(s->pb, mov, s)) < 0)
5024 if (mov->flags & FF_MOV_FLAG_DELAY_MOOV) {
5025 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
5026 mov->reserved_header_pos = avio_tell(s->pb);
5028 mov->moov_written = 1;
5032 buf_size = avio_close_dyn_buf(mov->mdat_buf, &buf);
5033 mov->mdat_buf = NULL;
5034 avio_wb32(s->pb, buf_size + 8);
5035 ffio_wfourcc(s->pb, "mdat");
5036 avio_write(s->pb, buf, buf_size);
5039 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
5040 mov->reserved_header_pos = avio_tell(s->pb);
5042 mov->moov_written = 1;
5044 for (i = 0; i < mov->nb_streams; i++) {
5045 if (mov->tracks[i].entry)
5046 mov->tracks[i].frag_start += mov->tracks[i].start_dts +
5047 mov->tracks[i].track_duration -
5048 mov->tracks[i].cluster[0].dts;
5049 mov->tracks[i].entry = 0;
5050 mov->tracks[i].end_reliable = 0;
5056 if (mov->frag_interleave) {
5057 for (i = 0; i < mov->nb_streams; i++) {
5058 MOVTrack *track = &mov->tracks[i];
5060 if ((ret = mov_flush_fragment_interleaving(s, track)) < 0)
5066 mdat_size = avio_tell(mov->mdat_buf);
5069 for (i = 0; i < mov->nb_streams; i++) {
5070 MOVTrack *track = &mov->tracks[i];
5071 if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF || mov->frag_interleave)
5072 track->data_offset = 0;
5074 track->data_offset = mdat_size;
5075 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
5077 if (first_video_track) {
5079 starts_with_key = track->cluster[0].flags & MOV_SYNC_SAMPLE;
5080 first_video_track = 0;
5085 if (track->mdat_buf)
5086 mdat_size += avio_tell(track->mdat_buf);
5087 if (first_track < 0)
5094 avio_write_marker(s->pb,
5095 av_rescale(mov->tracks[first_track].cluster[0].dts, AV_TIME_BASE, mov->tracks[first_track].timescale),
5096 (has_video ? starts_with_key : mov->tracks[first_track].cluster[0].flags & MOV_SYNC_SAMPLE) ? AVIO_DATA_MARKER_SYNC_POINT : AVIO_DATA_MARKER_BOUNDARY_POINT);
5098 for (i = 0; i < mov->nb_streams; i++) {
5099 MOVTrack *track = &mov->tracks[i];
5100 int buf_size, write_moof = 1, moof_tracks = -1;
5102 int64_t duration = 0;
5105 duration = track->start_dts + track->track_duration -
5106 track->cluster[0].dts;
5107 if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF) {
5108 if (!track->mdat_buf)
5110 mdat_size = avio_tell(track->mdat_buf);
5113 write_moof = i == first_track;
5119 mov_write_moof_tag(s->pb, mov, moof_tracks, mdat_size);
5122 avio_wb32(s->pb, mdat_size + 8);
5123 ffio_wfourcc(s->pb, "mdat");
5127 track->frag_start += duration;
5129 track->entries_flushed = 0;
5130 track->end_reliable = 0;
5131 if (!mov->frag_interleave) {
5132 if (!track->mdat_buf)
5134 buf_size = avio_close_dyn_buf(track->mdat_buf, &buf);
5135 track->mdat_buf = NULL;
5139 buf_size = avio_close_dyn_buf(mov->mdat_buf, &buf);
5140 mov->mdat_buf = NULL;
5143 avio_write(s->pb, buf, buf_size);
5153 static int mov_auto_flush_fragment(AVFormatContext *s, int force)
5155 MOVMuxContext *mov = s->priv_data;
5156 int had_moov = mov->moov_written;
5157 int ret = mov_flush_fragment(s, force);
5160 // If using delay_moov, the first flush only wrote the moov,
5161 // not the actual moof+mdat pair, thus flush once again.
5162 if (!had_moov && mov->flags & FF_MOV_FLAG_DELAY_MOOV)
5163 ret = mov_flush_fragment(s, force);
5167 static int check_pkt(AVFormatContext *s, AVPacket *pkt)
5169 MOVMuxContext *mov = s->priv_data;
5170 MOVTrack *trk = &mov->tracks[pkt->stream_index];
5175 ref = trk->cluster[trk->entry - 1].dts;
5176 } else if ( trk->start_dts != AV_NOPTS_VALUE
5177 && !trk->frag_discont) {
5178 ref = trk->start_dts + trk->track_duration;
5180 ref = pkt->dts; // Skip tests for the first packet
5182 if (trk->dts_shift != AV_NOPTS_VALUE) {
5183 /* With negative CTS offsets we have set an offset to the DTS,
5184 * reverse this for the check. */
5185 ref -= trk->dts_shift;
5188 duration = pkt->dts - ref;
5189 if (pkt->dts < ref || duration >= INT_MAX) {
5190 av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" / timestamp: %"PRId64" is out of range for mov/mp4 format\n",
5195 pkt->pts = AV_NOPTS_VALUE;
5198 if (pkt->duration < 0 || pkt->duration > INT_MAX) {
5199 av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" is invalid\n", pkt->duration);
5200 return AVERROR(EINVAL);
5205 int ff_mov_write_packet(AVFormatContext *s, AVPacket *pkt)
5207 MOVMuxContext *mov = s->priv_data;
5208 AVIOContext *pb = s->pb;
5209 MOVTrack *trk = &mov->tracks[pkt->stream_index];
5210 AVCodecParameters *par = trk->par;
5211 unsigned int samples_in_chunk = 0;
5212 int size = pkt->size, ret = 0;
5213 uint8_t *reformatted_data = NULL;
5215 ret = check_pkt(s, pkt);
5219 if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
5221 if (mov->moov_written || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
5222 if (mov->frag_interleave && mov->fragments > 0) {
5223 if (trk->entry - trk->entries_flushed >= mov->frag_interleave) {
5224 if ((ret = mov_flush_fragment_interleaving(s, trk)) < 0)
5229 if (!trk->mdat_buf) {
5230 if ((ret = avio_open_dyn_buf(&trk->mdat_buf)) < 0)
5235 if (!mov->mdat_buf) {
5236 if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0)
5243 if (par->codec_id == AV_CODEC_ID_AMR_NB) {
5244 /* We must find out how many AMR blocks there are in one packet */
5245 static const uint16_t packed_size[16] =
5246 {13, 14, 16, 18, 20, 21, 27, 32, 6, 0, 0, 0, 0, 0, 0, 1};
5249 while (len < size && samples_in_chunk < 100) {
5250 len += packed_size[(pkt->data[len] >> 3) & 0x0F];
5253 if (samples_in_chunk > 1) {
5254 av_log(s, AV_LOG_ERROR, "fatal error, input is not a single packet, implement a AVParser for it\n");
5257 } else if (par->codec_id == AV_CODEC_ID_ADPCM_MS ||
5258 par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) {
5259 samples_in_chunk = trk->par->frame_size;
5260 } else if (trk->sample_size)
5261 samples_in_chunk = size / trk->sample_size;
5263 samples_in_chunk = 1;
5265 /* copy extradata if it exists */
5266 if (trk->vos_len == 0 && par->extradata_size > 0 &&
5267 !TAG_IS_AVCI(trk->tag) &&
5268 (par->codec_id != AV_CODEC_ID_DNXHD)) {
5269 trk->vos_len = par->extradata_size;
5270 trk->vos_data = av_malloc(trk->vos_len);
5271 if (!trk->vos_data) {
5272 ret = AVERROR(ENOMEM);
5275 memcpy(trk->vos_data, par->extradata, trk->vos_len);
5278 if (par->codec_id == AV_CODEC_ID_AAC && pkt->size > 2 &&
5279 (AV_RB16(pkt->data) & 0xfff0) == 0xfff0) {
5280 if (!s->streams[pkt->stream_index]->nb_frames) {
5281 av_log(s, AV_LOG_ERROR, "Malformed AAC bitstream detected: "
5282 "use the audio bitstream filter 'aac_adtstoasc' to fix it "
5283 "('-bsf:a aac_adtstoasc' option with ffmpeg)\n");
5286 av_log(s, AV_LOG_WARNING, "aac bitstream error\n");
5288 if (par->codec_id == AV_CODEC_ID_H264 && trk->vos_len > 0 && *(uint8_t *)trk->vos_data != 1 && !TAG_IS_AVCI(trk->tag)) {
5289 /* from x264 or from bytestream H.264 */
5290 /* NAL reformatting needed */
5291 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
5292 ff_avc_parse_nal_units_buf(pkt->data, &reformatted_data,
5294 avio_write(pb, reformatted_data, size);
5296 if (trk->cenc.aes_ctr) {
5297 size = ff_mov_cenc_avc_parse_nal_units(&trk->cenc, pb, pkt->data, size);
5303 size = ff_avc_parse_nal_units(pb, pkt->data, pkt->size);
5306 } else if (par->codec_id == AV_CODEC_ID_HEVC && trk->vos_len > 6 &&
5307 (AV_RB24(trk->vos_data) == 1 || AV_RB32(trk->vos_data) == 1)) {
5308 /* extradata is Annex B, assume the bitstream is too and convert it */
5309 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
5310 ff_hevc_annexb2mp4_buf(pkt->data, &reformatted_data, &size, 0, NULL);
5311 avio_write(pb, reformatted_data, size);
5313 size = ff_hevc_annexb2mp4(pb, pkt->data, pkt->size, 0, NULL);
5315 #if CONFIG_AC3_PARSER
5316 } else if (par->codec_id == AV_CODEC_ID_EAC3) {
5317 size = handle_eac3(mov, pkt, trk);
5322 avio_write(pb, pkt->data, size);
5325 if (trk->cenc.aes_ctr) {
5326 if (par->codec_id == AV_CODEC_ID_H264 && par->extradata_size > 4) {
5327 int nal_size_length = (par->extradata[4] & 0x3) + 1;
5328 ret = ff_mov_cenc_avc_write_nal_units(s, &trk->cenc, nal_size_length, pb, pkt->data, size);
5330 ret = ff_mov_cenc_write_packet(&trk->cenc, pb, pkt->data, size);
5337 avio_write(pb, pkt->data, size);
5341 if ((par->codec_id == AV_CODEC_ID_DNXHD ||
5342 par->codec_id == AV_CODEC_ID_AC3) && !trk->vos_len) {
5343 /* copy frame to create needed atoms */
5344 trk->vos_len = size;
5345 trk->vos_data = av_malloc(size);
5346 if (!trk->vos_data) {
5347 ret = AVERROR(ENOMEM);
5350 memcpy(trk->vos_data, pkt->data, size);
5353 if (trk->entry >= trk->cluster_capacity) {
5354 unsigned new_capacity = 2 * (trk->entry + MOV_INDEX_CLUSTER_SIZE);
5355 if (av_reallocp_array(&trk->cluster, new_capacity,
5356 sizeof(*trk->cluster))) {
5357 ret = AVERROR(ENOMEM);
5360 trk->cluster_capacity = new_capacity;
5363 trk->cluster[trk->entry].pos = avio_tell(pb) - size;
5364 trk->cluster[trk->entry].samples_in_chunk = samples_in_chunk;
5365 trk->cluster[trk->entry].chunkNum = 0;
5366 trk->cluster[trk->entry].size = size;
5367 trk->cluster[trk->entry].entries = samples_in_chunk;
5368 trk->cluster[trk->entry].dts = pkt->dts;
5369 trk->cluster[trk->entry].pts = pkt->pts;
5370 if (!trk->entry && trk->start_dts != AV_NOPTS_VALUE) {
5371 if (!trk->frag_discont) {
5372 /* First packet of a new fragment. We already wrote the duration
5373 * of the last packet of the previous fragment based on track_duration,
5374 * which might not exactly match our dts. Therefore adjust the dts
5375 * of this packet to be what the previous packets duration implies. */
5376 trk->cluster[trk->entry].dts = trk->start_dts + trk->track_duration;
5377 /* We also may have written the pts and the corresponding duration
5378 * in sidx/tfrf/tfxd tags; make sure the sidx pts and duration match up with
5379 * the next fragment. This means the cts of the first sample must
5380 * be the same in all fragments, unless end_pts was updated by
5381 * the packet causing the fragment to be written. */
5382 if ((mov->flags & FF_MOV_FLAG_DASH && !(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)) ||
5383 mov->mode == MODE_ISM)
5384 pkt->pts = pkt->dts + trk->end_pts - trk->cluster[trk->entry].dts;
5386 /* New fragment, but discontinuous from previous fragments.
5387 * Pretend the duration sum of the earlier fragments is
5388 * pkt->dts - trk->start_dts. */
5389 trk->frag_start = pkt->dts - trk->start_dts;
5390 trk->end_pts = AV_NOPTS_VALUE;
5391 trk->frag_discont = 0;
5395 if (!trk->entry && trk->start_dts == AV_NOPTS_VALUE && !mov->use_editlist &&
5396 s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO) {
5397 /* Not using edit lists and shifting the first track to start from zero.
5398 * If the other streams start from a later timestamp, we won't be able
5399 * to signal the difference in starting time without an edit list.
5400 * Thus move the timestamp for this first sample to 0, increasing
5401 * its duration instead. */
5402 trk->cluster[trk->entry].dts = trk->start_dts = 0;
5404 if (trk->start_dts == AV_NOPTS_VALUE) {
5405 trk->start_dts = pkt->dts;
5406 if (trk->frag_discont) {
5407 if (mov->use_editlist) {
5408 /* Pretend the whole stream started at pts=0, with earlier fragments
5409 * already written. If the stream started at pts=0, the duration sum
5410 * of earlier fragments would have been pkt->pts. */
5411 trk->frag_start = pkt->pts;
5412 trk->start_dts = pkt->dts - pkt->pts;
5414 /* Pretend the whole stream started at dts=0, with earlier fragments
5415 * already written, with a duration summing up to pkt->dts. */
5416 trk->frag_start = pkt->dts;
5419 trk->frag_discont = 0;
5420 } else if (pkt->dts && mov->moov_written)
5421 av_log(s, AV_LOG_WARNING,
5422 "Track %d starts with a nonzero dts %"PRId64", while the moov "
5423 "already has been written. Set the delay_moov flag to handle "
5425 pkt->stream_index, pkt->dts);
5427 trk->track_duration = pkt->dts - trk->start_dts + pkt->duration;
5428 trk->last_sample_is_subtitle_end = 0;
5430 if (pkt->pts == AV_NOPTS_VALUE) {
5431 av_log(s, AV_LOG_WARNING, "pts has no value\n");
5432 pkt->pts = pkt->dts;
5434 if (pkt->dts != pkt->pts)
5435 trk->flags |= MOV_TRACK_CTTS;
5436 trk->cluster[trk->entry].cts = pkt->pts - pkt->dts;
5437 trk->cluster[trk->entry].flags = 0;
5438 if (trk->start_cts == AV_NOPTS_VALUE)
5439 trk->start_cts = pkt->pts - pkt->dts;
5440 if (trk->end_pts == AV_NOPTS_VALUE)
5441 trk->end_pts = trk->cluster[trk->entry].dts +
5442 trk->cluster[trk->entry].cts + pkt->duration;
5444 trk->end_pts = FFMAX(trk->end_pts, trk->cluster[trk->entry].dts +
5445 trk->cluster[trk->entry].cts +
5448 if (par->codec_id == AV_CODEC_ID_VC1) {
5449 mov_parse_vc1_frame(pkt, trk);
5450 } else if (pkt->flags & AV_PKT_FLAG_KEY) {
5451 if (mov->mode == MODE_MOV && par->codec_id == AV_CODEC_ID_MPEG2VIDEO &&
5452 trk->entry > 0) { // force sync sample for the first key frame
5453 mov_parse_mpeg2_frame(pkt, &trk->cluster[trk->entry].flags);
5454 if (trk->cluster[trk->entry].flags & MOV_PARTIAL_SYNC_SAMPLE)
5455 trk->flags |= MOV_TRACK_STPS;
5457 trk->cluster[trk->entry].flags = MOV_SYNC_SAMPLE;
5459 if (trk->cluster[trk->entry].flags & MOV_SYNC_SAMPLE)
5460 trk->has_keyframes++;
5462 if (pkt->flags & AV_PKT_FLAG_DISPOSABLE) {
5463 trk->cluster[trk->entry].flags |= MOV_DISPOSABLE_SAMPLE;
5464 trk->has_disposable++;
5467 trk->sample_count += samples_in_chunk;
5468 mov->mdat_size += size;
5470 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams)
5471 ff_mov_add_hinted_packet(s, pkt, trk->hint_track, trk->entry,
5472 reformatted_data, size);
5477 av_free(reformatted_data);
5481 static int mov_write_single_packet(AVFormatContext *s, AVPacket *pkt)
5483 MOVMuxContext *mov = s->priv_data;
5484 MOVTrack *trk = &mov->tracks[pkt->stream_index];
5485 AVCodecParameters *par = trk->par;
5486 int64_t frag_duration = 0;
5487 int size = pkt->size;
5489 int ret = check_pkt(s, pkt);
5493 if (mov->flags & FF_MOV_FLAG_FRAG_DISCONT) {
5495 for (i = 0; i < s->nb_streams; i++)
5496 mov->tracks[i].frag_discont = 1;
5497 mov->flags &= ~FF_MOV_FLAG_FRAG_DISCONT;
5500 if (mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS) {
5501 if (trk->dts_shift == AV_NOPTS_VALUE)
5502 trk->dts_shift = pkt->pts - pkt->dts;
5503 pkt->dts += trk->dts_shift;
5506 if (trk->par->codec_id == AV_CODEC_ID_MP4ALS ||
5507 trk->par->codec_id == AV_CODEC_ID_AAC ||
5508 trk->par->codec_id == AV_CODEC_ID_FLAC) {
5510 uint8_t *side = av_packet_get_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA, &side_size);
5511 if (side && side_size > 0 && (side_size != par->extradata_size || memcmp(side, par->extradata, side_size))) {
5512 void *newextra = av_mallocz(side_size + AV_INPUT_BUFFER_PADDING_SIZE);
5514 return AVERROR(ENOMEM);
5515 av_free(par->extradata);
5516 par->extradata = newextra;
5517 memcpy(par->extradata, side, side_size);
5518 par->extradata_size = side_size;
5519 if (!pkt->size) // Flush packet
5520 mov->need_rewrite_extradata = 1;
5525 if (trk->start_dts == AV_NOPTS_VALUE && trk->frag_discont) {
5526 trk->start_dts = pkt->dts;
5527 if (pkt->pts != AV_NOPTS_VALUE)
5528 trk->start_cts = pkt->pts - pkt->dts;
5533 return 0; /* Discard 0 sized packets */
5536 if (trk->entry && pkt->stream_index < s->nb_streams)
5537 frag_duration = av_rescale_q(pkt->dts - trk->cluster[0].dts,
5538 s->streams[pkt->stream_index]->time_base,
5540 if ((mov->max_fragment_duration &&
5541 frag_duration >= mov->max_fragment_duration) ||
5542 (mov->max_fragment_size && mov->mdat_size + size >= mov->max_fragment_size) ||
5543 (mov->flags & FF_MOV_FLAG_FRAG_KEYFRAME &&
5544 par->codec_type == AVMEDIA_TYPE_VIDEO &&
5545 trk->entry && pkt->flags & AV_PKT_FLAG_KEY) ||
5546 (mov->flags & FF_MOV_FLAG_FRAG_EVERY_FRAME)) {
5547 if (frag_duration >= mov->min_fragment_duration) {
5548 // Set the duration of this track to line up with the next
5549 // sample in this track. This avoids relying on AVPacket
5550 // duration, but only helps for this particular track, not
5551 // for the other ones that are flushed at the same time.
5552 trk->track_duration = pkt->dts - trk->start_dts;
5553 if (pkt->pts != AV_NOPTS_VALUE)
5554 trk->end_pts = pkt->pts;
5556 trk->end_pts = pkt->dts;
5557 trk->end_reliable = 1;
5558 mov_auto_flush_fragment(s, 0);
5562 return ff_mov_write_packet(s, pkt);
5565 static int mov_write_subtitle_end_packet(AVFormatContext *s,
5569 uint8_t data[2] = {0};
5572 av_init_packet(&end);
5573 end.size = sizeof(data);
5578 end.stream_index = stream_index;
5580 ret = mov_write_single_packet(s, &end);
5581 av_packet_unref(&end);
5586 static int mov_write_packet(AVFormatContext *s, AVPacket *pkt)
5588 MOVMuxContext *mov = s->priv_data;
5593 mov_flush_fragment(s, 1);
5597 st = s->streams[pkt->stream_index];
5598 trk = &mov->tracks[pkt->stream_index];
5600 if (st->disposition & AV_DISPOSITION_ATTACHED_PIC) {
5603 if (st->nb_frames >= 1) {
5604 if (st->nb_frames == 1)
5605 av_log(s, AV_LOG_WARNING, "Got more than one picture in stream %d,"
5606 " ignoring.\n", pkt->stream_index);
5610 if ((ret = av_packet_ref(&trk->cover_image, pkt)) < 0)
5618 return mov_write_single_packet(s, pkt); /* Passthrough. */
5621 * Subtitles require special handling.
5623 * 1) For full complaince, every track must have a sample at
5624 * dts == 0, which is rarely true for subtitles. So, as soon
5625 * as we see any packet with dts > 0, write an empty subtitle
5626 * at dts == 0 for any subtitle track with no samples in it.
5628 * 2) For each subtitle track, check if the current packet's
5629 * dts is past the duration of the last subtitle sample. If
5630 * so, we now need to write an end sample for that subtitle.
5632 * This must be done conditionally to allow for subtitles that
5633 * immediately replace each other, in which case an end sample
5634 * is not needed, and is, in fact, actively harmful.
5636 * 3) See mov_write_trailer for how the final end sample is
5639 for (i = 0; i < mov->nb_streams; i++) {
5640 MOVTrack *trk = &mov->tracks[i];
5643 if (trk->par->codec_id == AV_CODEC_ID_MOV_TEXT &&
5644 trk->track_duration < pkt->dts &&
5645 (trk->entry == 0 || !trk->last_sample_is_subtitle_end)) {
5646 ret = mov_write_subtitle_end_packet(s, i, trk->track_duration);
5647 if (ret < 0) return ret;
5648 trk->last_sample_is_subtitle_end = 1;
5652 if (trk->mode == MODE_MOV && trk->par->codec_type == AVMEDIA_TYPE_VIDEO) {
5653 AVPacket *opkt = pkt;
5654 int reshuffle_ret, ret;
5655 if (trk->is_unaligned_qt_rgb) {
5656 int64_t bpc = trk->par->bits_per_coded_sample != 15 ? trk->par->bits_per_coded_sample : 16;
5657 int expected_stride = ((trk->par->width * bpc + 15) >> 4)*2;
5658 reshuffle_ret = ff_reshuffle_raw_rgb(s, &pkt, trk->par, expected_stride);
5659 if (reshuffle_ret < 0)
5660 return reshuffle_ret;
5663 if (trk->par->format == AV_PIX_FMT_PAL8 && !trk->pal_done) {
5664 ret = ff_get_packet_palette(s, opkt, reshuffle_ret, trk->palette);
5669 } else if (trk->par->codec_id == AV_CODEC_ID_RAWVIDEO &&
5670 (trk->par->format == AV_PIX_FMT_GRAY8 ||
5671 trk->par->format == AV_PIX_FMT_MONOBLACK)) {
5672 for (i = 0; i < pkt->size; i++)
5673 pkt->data[i] = ~pkt->data[i];
5675 if (reshuffle_ret) {
5676 ret = mov_write_single_packet(s, pkt);
5679 av_packet_free(&pkt);
5684 return mov_write_single_packet(s, pkt);
5688 // QuickTime chapters involve an additional text track with the chapter names
5689 // as samples, and a tref pointing from the other tracks to the chapter one.
5690 static int mov_create_chapter_track(AVFormatContext *s, int tracknum)
5694 MOVMuxContext *mov = s->priv_data;
5695 MOVTrack *track = &mov->tracks[tracknum];
5696 AVPacket pkt = { .stream_index = tracknum, .flags = AV_PKT_FLAG_KEY };
5699 track->mode = mov->mode;
5700 track->tag = MKTAG('t','e','x','t');
5701 track->timescale = MOV_TIMESCALE;
5702 track->par = avcodec_parameters_alloc();
5704 return AVERROR(ENOMEM);
5705 track->par->codec_type = AVMEDIA_TYPE_SUBTITLE;
5707 // These properties are required to make QT recognize the chapter track
5708 uint8_t chapter_properties[43] = { 0, 0, 0, 0, 0, 0, 0, 1, };
5709 if (ff_alloc_extradata(track->par, sizeof(chapter_properties)))
5710 return AVERROR(ENOMEM);
5711 memcpy(track->par->extradata, chapter_properties, sizeof(chapter_properties));
5713 if (avio_open_dyn_buf(&pb) >= 0) {
5717 /* Stub header (usually for Quicktime chapter track) */
5719 avio_wb32(pb, 0x01); // displayFlags
5720 avio_w8(pb, 0x00); // horizontal justification
5721 avio_w8(pb, 0x00); // vertical justification
5722 avio_w8(pb, 0x00); // bgColourRed
5723 avio_w8(pb, 0x00); // bgColourGreen
5724 avio_w8(pb, 0x00); // bgColourBlue
5725 avio_w8(pb, 0x00); // bgColourAlpha
5727 avio_wb16(pb, 0x00); // defTextBoxTop
5728 avio_wb16(pb, 0x00); // defTextBoxLeft
5729 avio_wb16(pb, 0x00); // defTextBoxBottom
5730 avio_wb16(pb, 0x00); // defTextBoxRight
5732 avio_wb16(pb, 0x00); // startChar
5733 avio_wb16(pb, 0x00); // endChar
5734 avio_wb16(pb, 0x01); // fontID
5735 avio_w8(pb, 0x00); // fontStyleFlags
5736 avio_w8(pb, 0x00); // fontSize
5737 avio_w8(pb, 0x00); // fgColourRed
5738 avio_w8(pb, 0x00); // fgColourGreen
5739 avio_w8(pb, 0x00); // fgColourBlue
5740 avio_w8(pb, 0x00); // fgColourAlpha
5742 avio_wb32(pb, 0x0D); // box size
5743 ffio_wfourcc(pb, "ftab"); // box atom name
5744 avio_wb16(pb, 0x01); // entry count
5746 avio_wb16(pb, 0x01); // font ID
5747 avio_w8(pb, 0x00); // font name length
5749 if ((size = avio_close_dyn_buf(pb, &buf)) > 0) {
5750 track->par->extradata = buf;
5751 track->par->extradata_size = size;
5758 for (i = 0; i < s->nb_chapters; i++) {
5759 AVChapter *c = s->chapters[i];
5760 AVDictionaryEntry *t;
5762 int64_t end = av_rescale_q(c->end, c->time_base, (AVRational){1,MOV_TIMESCALE});
5763 pkt.pts = pkt.dts = av_rescale_q(c->start, c->time_base, (AVRational){1,MOV_TIMESCALE});
5764 pkt.duration = end - pkt.dts;
5766 if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
5767 static const char encd[12] = {
5768 0x00, 0x00, 0x00, 0x0C,
5770 0x00, 0x00, 0x01, 0x00 };
5771 len = strlen(t->value);
5772 pkt.size = len + 2 + 12;
5773 pkt.data = av_malloc(pkt.size);
5775 return AVERROR(ENOMEM);
5776 AV_WB16(pkt.data, len);
5777 memcpy(pkt.data + 2, t->value, len);
5778 memcpy(pkt.data + len + 2, encd, sizeof(encd));
5779 ff_mov_write_packet(s, &pkt);
5780 av_freep(&pkt.data);
5788 static int mov_check_timecode_track(AVFormatContext *s, AVTimecode *tc, int src_index, const char *tcstr)
5792 /* compute the frame number */
5793 ret = av_timecode_init_from_string(tc, find_fps(s, s->streams[src_index]), tcstr, s);
5797 static int mov_create_timecode_track(AVFormatContext *s, int index, int src_index, AVTimecode tc)
5800 MOVMuxContext *mov = s->priv_data;
5801 MOVTrack *track = &mov->tracks[index];
5802 AVStream *src_st = s->streams[src_index];
5803 AVPacket pkt = {.stream_index = index, .flags = AV_PKT_FLAG_KEY, .size = 4};
5804 AVRational rate = find_fps(s, src_st);
5806 /* tmcd track based on video stream */
5807 track->mode = mov->mode;
5808 track->tag = MKTAG('t','m','c','d');
5809 track->src_track = src_index;
5810 track->timescale = mov->tracks[src_index].timescale;
5811 if (tc.flags & AV_TIMECODE_FLAG_DROPFRAME)
5812 track->timecode_flags |= MOV_TIMECODE_FLAG_DROPFRAME;
5814 /* set st to src_st for metadata access*/
5817 /* encode context: tmcd data stream */
5818 track->par = avcodec_parameters_alloc();
5820 return AVERROR(ENOMEM);
5821 track->par->codec_type = AVMEDIA_TYPE_DATA;
5822 track->par->codec_tag = track->tag;
5823 track->st->avg_frame_rate = av_inv_q(rate);
5825 /* the tmcd track just contains one packet with the frame number */
5826 pkt.data = av_malloc(pkt.size);
5828 return AVERROR(ENOMEM);
5829 AV_WB32(pkt.data, tc.start);
5830 ret = ff_mov_write_packet(s, &pkt);
5836 * st->disposition controls the "enabled" flag in the tkhd tag.
5837 * QuickTime will not play a track if it is not enabled. So make sure
5838 * that one track of each type (audio, video, subtitle) is enabled.
5840 * Subtitles are special. For audio and video, setting "enabled" also
5841 * makes the track "default" (i.e. it is rendered when played). For
5842 * subtitles, an "enabled" subtitle is not rendered by default, but
5843 * if no subtitle is enabled, the subtitle menu in QuickTime will be
5846 static void enable_tracks(AVFormatContext *s)
5848 MOVMuxContext *mov = s->priv_data;
5850 int enabled[AVMEDIA_TYPE_NB];
5851 int first[AVMEDIA_TYPE_NB];
5853 for (i = 0; i < AVMEDIA_TYPE_NB; i++) {
5858 for (i = 0; i < s->nb_streams; i++) {
5859 AVStream *st = s->streams[i];
5861 if (st->codecpar->codec_type <= AVMEDIA_TYPE_UNKNOWN ||
5862 st->codecpar->codec_type >= AVMEDIA_TYPE_NB ||
5863 st->disposition & AV_DISPOSITION_ATTACHED_PIC)
5866 if (first[st->codecpar->codec_type] < 0)
5867 first[st->codecpar->codec_type] = i;
5868 if (st->disposition & AV_DISPOSITION_DEFAULT) {
5869 mov->tracks[i].flags |= MOV_TRACK_ENABLED;
5870 enabled[st->codecpar->codec_type]++;
5874 for (i = 0; i < AVMEDIA_TYPE_NB; i++) {
5876 case AVMEDIA_TYPE_VIDEO:
5877 case AVMEDIA_TYPE_AUDIO:
5878 case AVMEDIA_TYPE_SUBTITLE:
5880 mov->per_stream_grouping = 1;
5881 if (!enabled[i] && first[i] >= 0)
5882 mov->tracks[first[i]].flags |= MOV_TRACK_ENABLED;
5888 static void mov_free(AVFormatContext *s)
5890 MOVMuxContext *mov = s->priv_data;
5893 if (mov->chapter_track) {
5894 if (mov->tracks[mov->chapter_track].par)
5895 av_freep(&mov->tracks[mov->chapter_track].par->extradata);
5896 av_freep(&mov->tracks[mov->chapter_track].par);
5899 for (i = 0; i < mov->nb_streams; i++) {
5900 if (mov->tracks[i].tag == MKTAG('r','t','p',' '))
5901 ff_mov_close_hinting(&mov->tracks[i]);
5902 else if (mov->tracks[i].tag == MKTAG('t','m','c','d') && mov->nb_meta_tmcd)
5903 av_freep(&mov->tracks[i].par);
5904 av_freep(&mov->tracks[i].cluster);
5905 av_freep(&mov->tracks[i].frag_info);
5906 av_packet_unref(&mov->tracks[i].cover_image);
5908 if (mov->tracks[i].vos_len)
5909 av_freep(&mov->tracks[i].vos_data);
5911 ff_mov_cenc_free(&mov->tracks[i].cenc);
5914 av_freep(&mov->tracks);
5917 static uint32_t rgb_to_yuv(uint32_t rgb)
5922 r = (rgb >> 16) & 0xFF;
5923 g = (rgb >> 8) & 0xFF;
5926 y = av_clip_uint8(( 16000 + 257 * r + 504 * g + 98 * b)/1000);
5927 cb = av_clip_uint8((128000 - 148 * r - 291 * g + 439 * b)/1000);
5928 cr = av_clip_uint8((128000 + 439 * r - 368 * g - 71 * b)/1000);
5930 return (y << 16) | (cr << 8) | cb;
5933 static int mov_create_dvd_sub_decoder_specific_info(MOVTrack *track,
5936 int i, width = 720, height = 480;
5937 int have_palette = 0, have_size = 0;
5938 uint32_t palette[16];
5939 char *cur = st->codecpar->extradata;
5941 while (cur && *cur) {
5942 if (strncmp("palette:", cur, 8) == 0) {
5944 count = sscanf(cur + 8,
5945 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
5946 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
5947 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
5948 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32"",
5949 &palette[ 0], &palette[ 1], &palette[ 2], &palette[ 3],
5950 &palette[ 4], &palette[ 5], &palette[ 6], &palette[ 7],
5951 &palette[ 8], &palette[ 9], &palette[10], &palette[11],
5952 &palette[12], &palette[13], &palette[14], &palette[15]);
5954 for (i = 0; i < count; i++) {
5955 palette[i] = rgb_to_yuv(palette[i]);
5958 } else if (!strncmp("size:", cur, 5)) {
5959 sscanf(cur + 5, "%dx%d", &width, &height);
5962 if (have_palette && have_size)
5964 cur += strcspn(cur, "\n\r");
5965 cur += strspn(cur, "\n\r");
5968 track->vos_data = av_malloc(16*4);
5969 if (!track->vos_data)
5970 return AVERROR(ENOMEM);
5971 for (i = 0; i < 16; i++) {
5972 AV_WB32(track->vos_data + i * 4, palette[i]);
5974 track->vos_len = 16 * 4;
5976 st->codecpar->width = width;
5977 st->codecpar->height = track->height = height;
5982 static int mov_init(AVFormatContext *s)
5984 MOVMuxContext *mov = s->priv_data;
5985 AVDictionaryEntry *global_tcr = av_dict_get(s->metadata, "timecode", NULL, 0);
5990 /* Default mode == MP4 */
5991 mov->mode = MODE_MP4;
5994 if (!strcmp("3gp", s->oformat->name)) mov->mode = MODE_3GP;
5995 else if (!strcmp("3g2", s->oformat->name)) mov->mode = MODE_3GP|MODE_3G2;
5996 else if (!strcmp("mov", s->oformat->name)) mov->mode = MODE_MOV;
5997 else if (!strcmp("psp", s->oformat->name)) mov->mode = MODE_PSP;
5998 else if (!strcmp("ipod",s->oformat->name)) mov->mode = MODE_IPOD;
5999 else if (!strcmp("ismv",s->oformat->name)) mov->mode = MODE_ISM;
6000 else if (!strcmp("f4v", s->oformat->name)) mov->mode = MODE_F4V;
6003 if (mov->flags & FF_MOV_FLAG_DELAY_MOOV)
6004 mov->flags |= FF_MOV_FLAG_EMPTY_MOOV;
6006 /* Set the FRAGMENT flag if any of the fragmentation methods are
6008 if (mov->max_fragment_duration || mov->max_fragment_size ||
6009 mov->flags & (FF_MOV_FLAG_EMPTY_MOOV |
6010 FF_MOV_FLAG_FRAG_KEYFRAME |
6011 FF_MOV_FLAG_FRAG_CUSTOM |
6012 FF_MOV_FLAG_FRAG_EVERY_FRAME))
6013 mov->flags |= FF_MOV_FLAG_FRAGMENT;
6015 /* Set other implicit flags immediately */
6016 if (mov->mode == MODE_ISM)
6017 mov->flags |= FF_MOV_FLAG_EMPTY_MOOV | FF_MOV_FLAG_SEPARATE_MOOF |
6018 FF_MOV_FLAG_FRAGMENT;
6019 if (mov->flags & FF_MOV_FLAG_DASH)
6020 mov->flags |= FF_MOV_FLAG_FRAGMENT | FF_MOV_FLAG_EMPTY_MOOV |
6021 FF_MOV_FLAG_DEFAULT_BASE_MOOF;
6023 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV && s->flags & AVFMT_FLAG_AUTO_BSF) {
6024 av_log(s, AV_LOG_VERBOSE, "Empty MOOV enabled; disabling automatic bitstream filtering\n");
6025 s->flags &= ~AVFMT_FLAG_AUTO_BSF;
6028 if (mov->flags & FF_MOV_FLAG_FASTSTART) {
6029 mov->reserved_moov_size = -1;
6032 if (mov->use_editlist < 0) {
6033 mov->use_editlist = 1;
6034 if (mov->flags & FF_MOV_FLAG_FRAGMENT &&
6035 !(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
6036 // If we can avoid needing an edit list by shifting the
6037 // tracks, prefer that over (trying to) write edit lists
6038 // in fragmented output.
6039 if (s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO ||
6040 s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO)
6041 mov->use_editlist = 0;
6044 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV &&
6045 !(mov->flags & FF_MOV_FLAG_DELAY_MOOV) && mov->use_editlist)
6046 av_log(s, AV_LOG_WARNING, "No meaningful edit list will be written when using empty_moov without delay_moov\n");
6048 if (!mov->use_editlist && s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO)
6049 s->avoid_negative_ts = AVFMT_AVOID_NEG_TS_MAKE_ZERO;
6051 /* Clear the omit_tfhd_offset flag if default_base_moof is set;
6052 * if the latter is set that's enough and omit_tfhd_offset doesn't
6053 * add anything extra on top of that. */
6054 if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET &&
6055 mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)
6056 mov->flags &= ~FF_MOV_FLAG_OMIT_TFHD_OFFSET;
6058 if (mov->frag_interleave &&
6059 mov->flags & (FF_MOV_FLAG_OMIT_TFHD_OFFSET | FF_MOV_FLAG_SEPARATE_MOOF)) {
6060 av_log(s, AV_LOG_ERROR,
6061 "Sample interleaving in fragments is mutually exclusive with "
6062 "omit_tfhd_offset and separate_moof\n");
6063 return AVERROR(EINVAL);
6066 /* Non-seekable output is ok if using fragmentation. If ism_lookahead
6067 * is enabled, we don't support non-seekable output at all. */
6068 if (!(s->pb->seekable & AVIO_SEEKABLE_NORMAL) &&
6069 (!(mov->flags & FF_MOV_FLAG_FRAGMENT) || mov->ism_lookahead)) {
6070 av_log(s, AV_LOG_ERROR, "muxer does not support non seekable output\n");
6071 return AVERROR(EINVAL);
6074 mov->nb_streams = s->nb_streams;
6075 if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters)
6076 mov->chapter_track = mov->nb_streams++;
6078 if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
6079 for (i = 0; i < s->nb_streams; i++)
6080 if (rtp_hinting_needed(s->streams[i]))
6084 if ( mov->write_tmcd == -1 && (mov->mode == MODE_MOV || mov->mode == MODE_MP4)
6085 || mov->write_tmcd == 1) {
6086 /* +1 tmcd track for each video stream with a timecode */
6087 for (i = 0; i < s->nb_streams; i++) {
6088 AVStream *st = s->streams[i];
6089 AVDictionaryEntry *t = global_tcr;
6090 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
6091 (t || (t=av_dict_get(st->metadata, "timecode", NULL, 0)))) {
6093 ret = mov_check_timecode_track(s, &tc, i, t->value);
6095 mov->nb_meta_tmcd++;
6099 /* check if there is already a tmcd track to remux */
6100 if (mov->nb_meta_tmcd) {
6101 for (i = 0; i < s->nb_streams; i++) {
6102 AVStream *st = s->streams[i];
6103 if (st->codecpar->codec_tag == MKTAG('t','m','c','d')) {
6104 av_log(s, AV_LOG_WARNING, "You requested a copy of the original timecode track "
6105 "so timecode metadata are now ignored\n");
6106 mov->nb_meta_tmcd = 0;
6111 mov->nb_streams += mov->nb_meta_tmcd;
6114 // Reserve an extra stream for chapters for the case where chapters
6115 // are written in the trailer
6116 mov->tracks = av_mallocz_array((mov->nb_streams + 1), sizeof(*mov->tracks));
6118 return AVERROR(ENOMEM);
6120 if (mov->encryption_scheme_str != NULL && strcmp(mov->encryption_scheme_str, "none") != 0) {
6121 if (strcmp(mov->encryption_scheme_str, "cenc-aes-ctr") == 0) {
6122 mov->encryption_scheme = MOV_ENC_CENC_AES_CTR;
6124 if (mov->encryption_key_len != AES_CTR_KEY_SIZE) {
6125 av_log(s, AV_LOG_ERROR, "Invalid encryption key len %d expected %d\n",
6126 mov->encryption_key_len, AES_CTR_KEY_SIZE);
6127 return AVERROR(EINVAL);
6130 if (mov->encryption_kid_len != CENC_KID_SIZE) {
6131 av_log(s, AV_LOG_ERROR, "Invalid encryption kid len %d expected %d\n",
6132 mov->encryption_kid_len, CENC_KID_SIZE);
6133 return AVERROR(EINVAL);
6136 av_log(s, AV_LOG_ERROR, "unsupported encryption scheme %s\n",
6137 mov->encryption_scheme_str);
6138 return AVERROR(EINVAL);
6142 for (i = 0; i < s->nb_streams; i++) {
6143 AVStream *st= s->streams[i];
6144 MOVTrack *track= &mov->tracks[i];
6145 AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0);
6148 track->par = st->codecpar;
6149 track->language = ff_mov_iso639_to_lang(lang?lang->value:"und", mov->mode!=MODE_MOV);
6150 if (track->language < 0)
6151 track->language = 0;
6152 track->mode = mov->mode;
6153 track->tag = mov_find_codec_tag(s, track);
6155 av_log(s, AV_LOG_ERROR, "Could not find tag for codec %s in stream #%d, "
6156 "codec not currently supported in container\n",
6157 avcodec_get_name(st->codecpar->codec_id), i);
6158 return AVERROR(EINVAL);
6160 /* If hinting of this track is enabled by a later hint track,
6161 * this is updated. */
6162 track->hint_track = -1;
6163 track->start_dts = AV_NOPTS_VALUE;
6164 track->start_cts = AV_NOPTS_VALUE;
6165 track->end_pts = AV_NOPTS_VALUE;
6166 track->dts_shift = AV_NOPTS_VALUE;
6167 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
6168 if (track->tag == MKTAG('m','x','3','p') || track->tag == MKTAG('m','x','3','n') ||
6169 track->tag == MKTAG('m','x','4','p') || track->tag == MKTAG('m','x','4','n') ||
6170 track->tag == MKTAG('m','x','5','p') || track->tag == MKTAG('m','x','5','n')) {
6171 if (st->codecpar->width != 720 || (st->codecpar->height != 608 && st->codecpar->height != 512)) {
6172 av_log(s, AV_LOG_ERROR, "D-10/IMX must use 720x608 or 720x512 video resolution\n");
6173 return AVERROR(EINVAL);
6175 track->height = track->tag >> 24 == 'n' ? 486 : 576;
6177 if (mov->video_track_timescale) {
6178 track->timescale = mov->video_track_timescale;
6180 track->timescale = st->time_base.den;
6181 while(track->timescale < 10000)
6182 track->timescale *= 2;
6184 if (st->codecpar->width > 65535 || st->codecpar->height > 65535) {
6185 av_log(s, AV_LOG_ERROR, "Resolution %dx%d too large for mov/mp4\n", st->codecpar->width, st->codecpar->height);
6186 return AVERROR(EINVAL);
6188 if (track->mode == MODE_MOV && track->timescale > 100000)
6189 av_log(s, AV_LOG_WARNING,
6190 "WARNING codec timebase is very high. If duration is too long,\n"
6191 "file may not be playable by quicktime. Specify a shorter timebase\n"
6192 "or choose different container.\n");
6193 if (track->mode == MODE_MOV &&
6194 track->par->codec_id == AV_CODEC_ID_RAWVIDEO &&
6195 track->tag == MKTAG('r','a','w',' ')) {
6196 enum AVPixelFormat pix_fmt = track->par->format;
6197 if (pix_fmt == AV_PIX_FMT_NONE && track->par->bits_per_coded_sample == 1)
6198 pix_fmt = AV_PIX_FMT_MONOWHITE;
6199 track->is_unaligned_qt_rgb =
6200 pix_fmt == AV_PIX_FMT_RGB24 ||
6201 pix_fmt == AV_PIX_FMT_BGR24 ||
6202 pix_fmt == AV_PIX_FMT_PAL8 ||
6203 pix_fmt == AV_PIX_FMT_GRAY8 ||
6204 pix_fmt == AV_PIX_FMT_MONOWHITE ||
6205 pix_fmt == AV_PIX_FMT_MONOBLACK;
6207 if (track->par->codec_id == AV_CODEC_ID_VP9) {
6208 if (track->mode != MODE_MP4) {
6209 av_log(s, AV_LOG_ERROR, "VP9 only supported in MP4.\n");
6210 return AVERROR(EINVAL);
6212 } else if (track->par->codec_id == AV_CODEC_ID_AV1) {
6213 /* spec is not finished, so forbid for now */
6214 av_log(s, AV_LOG_ERROR, "AV1 muxing is currently not supported.\n");
6215 return AVERROR_PATCHWELCOME;
6216 } else if (track->par->codec_id == AV_CODEC_ID_VP8) {
6217 /* altref frames handling is not defined in the spec as of version v1.0,
6218 * so just forbid muxing VP8 streams altogether until a new version does */
6219 av_log(s, AV_LOG_ERROR, "VP8 muxing is currently not supported.\n");
6220 return AVERROR_PATCHWELCOME;
6222 } else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
6223 track->timescale = st->codecpar->sample_rate;
6224 if (!st->codecpar->frame_size && !av_get_bits_per_sample(st->codecpar->codec_id)) {
6225 av_log(s, AV_LOG_WARNING, "track %d: codec frame size is not set\n", i);
6226 track->audio_vbr = 1;
6227 }else if (st->codecpar->codec_id == AV_CODEC_ID_ADPCM_MS ||
6228 st->codecpar->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
6229 st->codecpar->codec_id == AV_CODEC_ID_ILBC){
6230 if (!st->codecpar->block_align) {
6231 av_log(s, AV_LOG_ERROR, "track %d: codec block align is not set for adpcm\n", i);
6232 return AVERROR(EINVAL);
6234 track->sample_size = st->codecpar->block_align;
6235 }else if (st->codecpar->frame_size > 1){ /* assume compressed audio */
6236 track->audio_vbr = 1;
6238 track->sample_size = (av_get_bits_per_sample(st->codecpar->codec_id) >> 3) * st->codecpar->channels;
6240 if (st->codecpar->codec_id == AV_CODEC_ID_ILBC ||
6241 st->codecpar->codec_id == AV_CODEC_ID_ADPCM_IMA_QT) {
6242 track->audio_vbr = 1;
6244 if (track->mode != MODE_MOV &&
6245 track->par->codec_id == AV_CODEC_ID_MP3 && track->timescale < 16000) {
6246 if (s->strict_std_compliance >= FF_COMPLIANCE_NORMAL) {
6247 av_log(s, AV_LOG_ERROR, "track %d: muxing mp3 at %dhz is not standard, to mux anyway set strict to -1\n",
6248 i, track->par->sample_rate);
6249 return AVERROR(EINVAL);
6251 av_log(s, AV_LOG_WARNING, "track %d: muxing mp3 at %dhz is not standard in MP4\n",
6252 i, track->par->sample_rate);
6255 if (track->par->codec_id == AV_CODEC_ID_FLAC ||
6256 track->par->codec_id == AV_CODEC_ID_OPUS) {
6257 if (track->mode != MODE_MP4) {
6258 av_log(s, AV_LOG_ERROR, "%s only supported in MP4.\n", avcodec_get_name(track->par->codec_id));
6259 return AVERROR(EINVAL);
6261 if (s->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
6262 av_log(s, AV_LOG_ERROR,
6263 "%s in MP4 support is experimental, add "
6264 "'-strict %d' if you want to use it.\n",
6265 avcodec_get_name(track->par->codec_id), FF_COMPLIANCE_EXPERIMENTAL);
6266 return AVERROR_EXPERIMENTAL;
6269 } else if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) {
6270 track->timescale = st->time_base.den;
6271 } else if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA) {
6272 track->timescale = st->time_base.den;
6274 track->timescale = MOV_TIMESCALE;
6277 track->height = st->codecpar->height;
6278 /* The ism specific timescale isn't mandatory, but is assumed by
6279 * some tools, such as mp4split. */
6280 if (mov->mode == MODE_ISM)
6281 track->timescale = 10000000;
6283 avpriv_set_pts_info(st, 64, 1, track->timescale);
6285 if (mov->encryption_scheme == MOV_ENC_CENC_AES_CTR) {
6286 ret = ff_mov_cenc_init(&track->cenc, mov->encryption_key,
6287 track->par->codec_id == AV_CODEC_ID_H264, s->flags & AVFMT_FLAG_BITEXACT);
6297 static int mov_write_header(AVFormatContext *s)
6299 AVIOContext *pb = s->pb;
6300 MOVMuxContext *mov = s->priv_data;
6301 AVDictionaryEntry *t, *global_tcr = av_dict_get(s->metadata, "timecode", NULL, 0);
6302 int i, ret, hint_track = 0, tmcd_track = 0, nb_tracks = s->nb_streams;
6304 if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters)
6307 if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
6308 hint_track = nb_tracks;
6309 for (i = 0; i < s->nb_streams; i++)
6310 if (rtp_hinting_needed(s->streams[i]))
6314 if (mov->mode == MODE_MOV || mov->mode == MODE_MP4)
6315 tmcd_track = nb_tracks;
6317 for (i = 0; i < s->nb_streams; i++) {
6319 AVStream *st= s->streams[i];
6320 MOVTrack *track= &mov->tracks[i];
6322 /* copy extradata if it exists */
6323 if (st->codecpar->extradata_size) {
6324 if (st->codecpar->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
6325 mov_create_dvd_sub_decoder_specific_info(track, st);
6326 else if (!TAG_IS_AVCI(track->tag) && st->codecpar->codec_id != AV_CODEC_ID_DNXHD) {
6327 track->vos_len = st->codecpar->extradata_size;
6328 track->vos_data = av_malloc(track->vos_len);
6329 if (!track->vos_data) {
6330 return AVERROR(ENOMEM);
6332 memcpy(track->vos_data, st->codecpar->extradata, track->vos_len);
6336 if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ||
6337 track->par->channel_layout != AV_CH_LAYOUT_MONO)
6340 for (j = 0; j < s->nb_streams; j++) {
6341 AVStream *stj= s->streams[j];
6342 MOVTrack *trackj= &mov->tracks[j];
6346 if (stj->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ||
6347 trackj->par->channel_layout != AV_CH_LAYOUT_MONO ||
6348 trackj->language != track->language ||
6349 trackj->tag != track->tag
6352 track->multichannel_as_mono++;
6356 if (!(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
6357 if ((ret = mov_write_identification(pb, s)) < 0)
6361 if (mov->reserved_moov_size){
6362 mov->reserved_header_pos = avio_tell(pb);
6363 if (mov->reserved_moov_size > 0)
6364 avio_skip(pb, mov->reserved_moov_size);
6367 if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
6368 /* If no fragmentation options have been set, set a default. */
6369 if (!(mov->flags & (FF_MOV_FLAG_FRAG_KEYFRAME |
6370 FF_MOV_FLAG_FRAG_CUSTOM |
6371 FF_MOV_FLAG_FRAG_EVERY_FRAME)) &&
6372 !mov->max_fragment_duration && !mov->max_fragment_size)
6373 mov->flags |= FF_MOV_FLAG_FRAG_KEYFRAME;
6375 if (mov->flags & FF_MOV_FLAG_FASTSTART)
6376 mov->reserved_header_pos = avio_tell(pb);
6377 mov_write_mdat_tag(pb, mov);
6380 ff_parse_creation_time_metadata(s, &mov->time, 1);
6382 mov->time += 0x7C25B080; // 1970 based -> 1904 based
6384 if (mov->chapter_track)
6385 if ((ret = mov_create_chapter_track(s, mov->chapter_track)) < 0)
6388 if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
6389 for (i = 0; i < s->nb_streams; i++) {
6390 if (rtp_hinting_needed(s->streams[i])) {
6391 if ((ret = ff_mov_init_hinting(s, hint_track, i)) < 0)
6398 if (mov->nb_meta_tmcd) {
6399 /* Initialize the tmcd tracks */
6400 for (i = 0; i < s->nb_streams; i++) {
6401 AVStream *st = s->streams[i];
6404 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
6407 t = av_dict_get(st->metadata, "timecode", NULL, 0);
6410 if (mov_check_timecode_track(s, &tc, i, t->value) < 0)
6412 if ((ret = mov_create_timecode_track(s, tmcd_track, i, tc)) < 0)
6421 if (mov->flags & FF_MOV_FLAG_ISML)
6422 mov_write_isml_manifest(pb, mov, s);
6424 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV &&
6425 !(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
6426 if ((ret = mov_write_moov_tag(pb, mov, s)) < 0)
6429 mov->moov_written = 1;
6430 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
6431 mov->reserved_header_pos = avio_tell(pb);
6437 static int get_moov_size(AVFormatContext *s)
6440 AVIOContext *moov_buf;
6441 MOVMuxContext *mov = s->priv_data;
6443 if ((ret = ffio_open_null_buf(&moov_buf)) < 0)
6445 if ((ret = mov_write_moov_tag(moov_buf, mov, s)) < 0)
6447 return ffio_close_null_buf(moov_buf);
6450 static int get_sidx_size(AVFormatContext *s)
6454 MOVMuxContext *mov = s->priv_data;
6456 if ((ret = ffio_open_null_buf(&buf)) < 0)
6458 mov_write_sidx_tags(buf, mov, -1, 0);
6459 return ffio_close_null_buf(buf);
6463 * This function gets the moov size if moved to the top of the file: the chunk
6464 * offset table can switch between stco (32-bit entries) to co64 (64-bit
6465 * entries) when the moov is moved to the beginning, so the size of the moov
6466 * would change. It also updates the chunk offset tables.
6468 static int compute_moov_size(AVFormatContext *s)
6470 int i, moov_size, moov_size2;
6471 MOVMuxContext *mov = s->priv_data;
6473 moov_size = get_moov_size(s);
6477 for (i = 0; i < mov->nb_streams; i++)
6478 mov->tracks[i].data_offset += moov_size;
6480 moov_size2 = get_moov_size(s);
6484 /* if the size changed, we just switched from stco to co64 and need to
6485 * update the offsets */
6486 if (moov_size2 != moov_size)
6487 for (i = 0; i < mov->nb_streams; i++)
6488 mov->tracks[i].data_offset += moov_size2 - moov_size;
6493 static int compute_sidx_size(AVFormatContext *s)
6496 MOVMuxContext *mov = s->priv_data;
6498 sidx_size = get_sidx_size(s);
6502 for (i = 0; i < mov->nb_streams; i++)
6503 mov->tracks[i].data_offset += sidx_size;
6508 static int shift_data(AVFormatContext *s)
6510 int ret = 0, moov_size;
6511 MOVMuxContext *mov = s->priv_data;
6512 int64_t pos, pos_end = avio_tell(s->pb);
6513 uint8_t *buf, *read_buf[2];
6514 int read_buf_id = 0;
6516 AVIOContext *read_pb;
6518 if (mov->flags & FF_MOV_FLAG_FRAGMENT)
6519 moov_size = compute_sidx_size(s);
6521 moov_size = compute_moov_size(s);
6525 buf = av_malloc(moov_size * 2);
6527 return AVERROR(ENOMEM);
6529 read_buf[1] = buf + moov_size;
6531 /* Shift the data: the AVIO context of the output can only be used for
6532 * writing, so we re-open the same output, but for reading. It also avoids
6533 * a read/seek/write/seek back and forth. */
6535 ret = s->io_open(s, &read_pb, s->url, AVIO_FLAG_READ, NULL);
6537 av_log(s, AV_LOG_ERROR, "Unable to re-open %s output file for "
6538 "the second pass (faststart)\n", s->url);
6542 /* mark the end of the shift to up to the last data we wrote, and get ready
6544 pos_end = avio_tell(s->pb);
6545 avio_seek(s->pb, mov->reserved_header_pos + moov_size, SEEK_SET);
6547 /* start reading at where the new moov will be placed */
6548 avio_seek(read_pb, mov->reserved_header_pos, SEEK_SET);
6549 pos = avio_tell(read_pb);
6551 #define READ_BLOCK do { \
6552 read_size[read_buf_id] = avio_read(read_pb, read_buf[read_buf_id], moov_size); \
6556 /* shift data by chunk of at most moov_size */
6561 n = read_size[read_buf_id];
6564 avio_write(s->pb, read_buf[read_buf_id], n);
6566 } while (pos < pos_end);
6567 ff_format_io_close(s, &read_pb);
6574 static int mov_write_trailer(AVFormatContext *s)
6576 MOVMuxContext *mov = s->priv_data;
6577 AVIOContext *pb = s->pb;
6582 if (mov->need_rewrite_extradata) {
6583 for (i = 0; i < s->nb_streams; i++) {
6584 MOVTrack *track = &mov->tracks[i];
6585 AVCodecParameters *par = track->par;
6587 track->vos_len = par->extradata_size;
6588 track->vos_data = av_malloc(track->vos_len);
6589 if (!track->vos_data)
6590 return AVERROR(ENOMEM);
6591 memcpy(track->vos_data, par->extradata, track->vos_len);
6593 mov->need_rewrite_extradata = 0;
6597 * Before actually writing the trailer, make sure that there are no
6598 * dangling subtitles, that need a terminating sample.
6600 for (i = 0; i < mov->nb_streams; i++) {
6601 MOVTrack *trk = &mov->tracks[i];
6602 if (trk->par->codec_id == AV_CODEC_ID_MOV_TEXT &&
6603 !trk->last_sample_is_subtitle_end) {
6604 mov_write_subtitle_end_packet(s, i, trk->track_duration);
6605 trk->last_sample_is_subtitle_end = 1;
6609 // If there were no chapters when the header was written, but there
6610 // are chapters now, write them in the trailer. This only works
6611 // when we are not doing fragments.
6612 if (!mov->chapter_track && !(mov->flags & FF_MOV_FLAG_FRAGMENT)) {
6613 if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters) {
6614 mov->chapter_track = mov->nb_streams++;
6615 if ((res = mov_create_chapter_track(s, mov->chapter_track)) < 0)
6620 if (!(mov->flags & FF_MOV_FLAG_FRAGMENT)) {
6621 moov_pos = avio_tell(pb);
6623 /* Write size of mdat tag */
6624 if (mov->mdat_size + 8 <= UINT32_MAX) {
6625 avio_seek(pb, mov->mdat_pos, SEEK_SET);
6626 avio_wb32(pb, mov->mdat_size + 8);
6628 /* overwrite 'wide' placeholder atom */
6629 avio_seek(pb, mov->mdat_pos - 8, SEEK_SET);
6630 /* special value: real atom size will be 64 bit value after
6633 ffio_wfourcc(pb, "mdat");
6634 avio_wb64(pb, mov->mdat_size + 16);
6636 avio_seek(pb, mov->reserved_moov_size > 0 ? mov->reserved_header_pos : moov_pos, SEEK_SET);
6638 if (mov->flags & FF_MOV_FLAG_FASTSTART) {
6639 av_log(s, AV_LOG_INFO, "Starting second pass: moving the moov atom to the beginning of the file\n");
6640 res = shift_data(s);
6643 avio_seek(pb, mov->reserved_header_pos, SEEK_SET);
6644 if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
6646 } else if (mov->reserved_moov_size > 0) {
6648 if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
6650 size = mov->reserved_moov_size - (avio_tell(pb) - mov->reserved_header_pos);
6652 av_log(s, AV_LOG_ERROR, "reserved_moov_size is too small, needed %"PRId64" additional\n", 8-size);
6653 return AVERROR(EINVAL);
6655 avio_wb32(pb, size);
6656 ffio_wfourcc(pb, "free");
6657 ffio_fill(pb, 0, size - 8);
6658 avio_seek(pb, moov_pos, SEEK_SET);
6660 if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
6665 mov_auto_flush_fragment(s, 1);
6666 for (i = 0; i < mov->nb_streams; i++)
6667 mov->tracks[i].data_offset = 0;
6668 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) {
6670 av_log(s, AV_LOG_INFO, "Starting second pass: inserting sidx atoms\n");
6671 res = shift_data(s);
6674 end = avio_tell(pb);
6675 avio_seek(pb, mov->reserved_header_pos, SEEK_SET);
6676 mov_write_sidx_tags(pb, mov, -1, 0);
6677 avio_seek(pb, end, SEEK_SET);
6678 avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_TRAILER);
6679 mov_write_mfra_tag(pb, mov);
6680 } else if (!(mov->flags & FF_MOV_FLAG_SKIP_TRAILER)) {
6681 avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_TRAILER);
6682 mov_write_mfra_tag(pb, mov);
6689 static int mov_check_bitstream(struct AVFormatContext *s, const AVPacket *pkt)
6692 AVStream *st = s->streams[pkt->stream_index];
6694 if (st->codecpar->codec_id == AV_CODEC_ID_AAC) {
6695 if (pkt->size > 2 && (AV_RB16(pkt->data) & 0xfff0) == 0xfff0)
6696 ret = ff_stream_add_bitstream_filter(st, "aac_adtstoasc", NULL);
6697 } else if (st->codecpar->codec_id == AV_CODEC_ID_VP9) {
6698 ret = ff_stream_add_bitstream_filter(st, "vp9_superframe", NULL);
6704 static const AVCodecTag codec_3gp_tags[] = {
6705 { AV_CODEC_ID_H263, MKTAG('s','2','6','3') },
6706 { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
6707 { AV_CODEC_ID_MPEG4, MKTAG('m','p','4','v') },
6708 { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
6709 { AV_CODEC_ID_AMR_NB, MKTAG('s','a','m','r') },
6710 { AV_CODEC_ID_AMR_WB, MKTAG('s','a','w','b') },
6711 { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
6712 { AV_CODEC_ID_NONE, 0 },
6715 const AVCodecTag codec_mp4_tags[] = {
6716 { AV_CODEC_ID_MPEG4 , MKTAG('m', 'p', '4', 'v') },
6717 { AV_CODEC_ID_H264 , MKTAG('a', 'v', 'c', '1') },
6718 { AV_CODEC_ID_H264 , MKTAG('a', 'v', 'c', '3') },
6719 { AV_CODEC_ID_HEVC , MKTAG('h', 'e', 'v', '1') },
6720 { AV_CODEC_ID_HEVC , MKTAG('h', 'v', 'c', '1') },
6721 { AV_CODEC_ID_MPEG2VIDEO , MKTAG('m', 'p', '4', 'v') },
6722 { AV_CODEC_ID_MPEG1VIDEO , MKTAG('m', 'p', '4', 'v') },
6723 { AV_CODEC_ID_MJPEG , MKTAG('m', 'p', '4', 'v') },
6724 { AV_CODEC_ID_PNG , MKTAG('m', 'p', '4', 'v') },
6725 { AV_CODEC_ID_JPEG2000 , MKTAG('m', 'p', '4', 'v') },
6726 { AV_CODEC_ID_VC1 , MKTAG('v', 'c', '-', '1') },
6727 { AV_CODEC_ID_DIRAC , MKTAG('d', 'r', 'a', 'c') },
6728 { AV_CODEC_ID_TSCC2 , MKTAG('m', 'p', '4', 'v') },
6729 { AV_CODEC_ID_VP9 , MKTAG('v', 'p', '0', '9') },
6730 { AV_CODEC_ID_AAC , MKTAG('m', 'p', '4', 'a') },
6731 { AV_CODEC_ID_MP4ALS , MKTAG('m', 'p', '4', 'a') },
6732 { AV_CODEC_ID_MP3 , MKTAG('m', 'p', '4', 'a') },
6733 { AV_CODEC_ID_MP2 , MKTAG('m', 'p', '4', 'a') },
6734 { AV_CODEC_ID_AC3 , MKTAG('a', 'c', '-', '3') },
6735 { AV_CODEC_ID_EAC3 , MKTAG('e', 'c', '-', '3') },
6736 { AV_CODEC_ID_DTS , MKTAG('m', 'p', '4', 'a') },
6737 { AV_CODEC_ID_FLAC , MKTAG('f', 'L', 'a', 'C') },
6738 { AV_CODEC_ID_OPUS , MKTAG('O', 'p', 'u', 's') },
6739 { AV_CODEC_ID_VORBIS , MKTAG('m', 'p', '4', 'a') },
6740 { AV_CODEC_ID_QCELP , MKTAG('m', 'p', '4', 'a') },
6741 { AV_CODEC_ID_EVRC , MKTAG('m', 'p', '4', 'a') },
6742 { AV_CODEC_ID_DVD_SUBTITLE, MKTAG('m', 'p', '4', 's') },
6743 { AV_CODEC_ID_MOV_TEXT , MKTAG('t', 'x', '3', 'g') },
6744 { AV_CODEC_ID_NONE , 0 },
6747 const AVCodecTag codec_ism_tags[] = {
6748 { AV_CODEC_ID_WMAPRO , MKTAG('w', 'm', 'a', ' ') },
6749 { AV_CODEC_ID_NONE , 0 },
6752 static const AVCodecTag codec_ipod_tags[] = {
6753 { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
6754 { AV_CODEC_ID_MPEG4, MKTAG('m','p','4','v') },
6755 { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
6756 { AV_CODEC_ID_ALAC, MKTAG('a','l','a','c') },
6757 { AV_CODEC_ID_AC3, MKTAG('a','c','-','3') },
6758 { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
6759 { AV_CODEC_ID_MOV_TEXT, MKTAG('t','e','x','t') },
6760 { AV_CODEC_ID_NONE, 0 },
6763 static const AVCodecTag codec_f4v_tags[] = {
6764 { AV_CODEC_ID_MP3, MKTAG('.','m','p','3') },
6765 { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
6766 { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
6767 { AV_CODEC_ID_VP6A, MKTAG('V','P','6','A') },
6768 { AV_CODEC_ID_VP6F, MKTAG('V','P','6','F') },
6769 { AV_CODEC_ID_NONE, 0 },
6772 #if CONFIG_MOV_MUXER
6774 AVOutputFormat ff_mov_muxer = {
6776 .long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
6777 .extensions = "mov",
6778 .priv_data_size = sizeof(MOVMuxContext),
6779 .audio_codec = AV_CODEC_ID_AAC,
6780 .video_codec = CONFIG_LIBX264_ENCODER ?
6781 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
6783 .write_header = mov_write_header,
6784 .write_packet = mov_write_packet,
6785 .write_trailer = mov_write_trailer,
6787 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6788 .codec_tag = (const AVCodecTag* const []){
6789 ff_codec_movvideo_tags, ff_codec_movaudio_tags, 0
6791 .check_bitstream = mov_check_bitstream,
6792 .priv_class = &mov_muxer_class,
6795 #if CONFIG_TGP_MUXER
6797 AVOutputFormat ff_tgp_muxer = {
6799 .long_name = NULL_IF_CONFIG_SMALL("3GP (3GPP file format)"),
6800 .extensions = "3gp",
6801 .priv_data_size = sizeof(MOVMuxContext),
6802 .audio_codec = AV_CODEC_ID_AMR_NB,
6803 .video_codec = AV_CODEC_ID_H263,
6805 .write_header = mov_write_header,
6806 .write_packet = mov_write_packet,
6807 .write_trailer = mov_write_trailer,
6809 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6810 .codec_tag = (const AVCodecTag* const []){ codec_3gp_tags, 0 },
6811 .check_bitstream = mov_check_bitstream,
6812 .priv_class = &tgp_muxer_class,
6815 #if CONFIG_MP4_MUXER
6817 AVOutputFormat ff_mp4_muxer = {
6819 .long_name = NULL_IF_CONFIG_SMALL("MP4 (MPEG-4 Part 14)"),
6820 .mime_type = "video/mp4",
6821 .extensions = "mp4",
6822 .priv_data_size = sizeof(MOVMuxContext),
6823 .audio_codec = AV_CODEC_ID_AAC,
6824 .video_codec = CONFIG_LIBX264_ENCODER ?
6825 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
6827 .write_header = mov_write_header,
6828 .write_packet = mov_write_packet,
6829 .write_trailer = mov_write_trailer,
6831 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6832 .codec_tag = (const AVCodecTag* const []){ codec_mp4_tags, 0 },
6833 .check_bitstream = mov_check_bitstream,
6834 .priv_class = &mp4_muxer_class,
6837 #if CONFIG_PSP_MUXER
6839 AVOutputFormat ff_psp_muxer = {
6841 .long_name = NULL_IF_CONFIG_SMALL("PSP MP4 (MPEG-4 Part 14)"),
6842 .extensions = "mp4,psp",
6843 .priv_data_size = sizeof(MOVMuxContext),
6844 .audio_codec = AV_CODEC_ID_AAC,
6845 .video_codec = CONFIG_LIBX264_ENCODER ?
6846 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
6848 .write_header = mov_write_header,
6849 .write_packet = mov_write_packet,
6850 .write_trailer = mov_write_trailer,
6852 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6853 .codec_tag = (const AVCodecTag* const []){ codec_mp4_tags, 0 },
6854 .check_bitstream = mov_check_bitstream,
6855 .priv_class = &psp_muxer_class,
6858 #if CONFIG_TG2_MUXER
6860 AVOutputFormat ff_tg2_muxer = {
6862 .long_name = NULL_IF_CONFIG_SMALL("3GP2 (3GPP2 file format)"),
6863 .extensions = "3g2",
6864 .priv_data_size = sizeof(MOVMuxContext),
6865 .audio_codec = AV_CODEC_ID_AMR_NB,
6866 .video_codec = AV_CODEC_ID_H263,
6868 .write_header = mov_write_header,
6869 .write_packet = mov_write_packet,
6870 .write_trailer = mov_write_trailer,
6872 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6873 .codec_tag = (const AVCodecTag* const []){ codec_3gp_tags, 0 },
6874 .check_bitstream = mov_check_bitstream,
6875 .priv_class = &tg2_muxer_class,
6878 #if CONFIG_IPOD_MUXER
6880 AVOutputFormat ff_ipod_muxer = {
6882 .long_name = NULL_IF_CONFIG_SMALL("iPod H.264 MP4 (MPEG-4 Part 14)"),
6883 .mime_type = "video/mp4",
6884 .extensions = "m4v,m4a,m4b",
6885 .priv_data_size = sizeof(MOVMuxContext),
6886 .audio_codec = AV_CODEC_ID_AAC,
6887 .video_codec = AV_CODEC_ID_H264,
6889 .write_header = mov_write_header,
6890 .write_packet = mov_write_packet,
6891 .write_trailer = mov_write_trailer,
6893 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6894 .codec_tag = (const AVCodecTag* const []){ codec_ipod_tags, 0 },
6895 .check_bitstream = mov_check_bitstream,
6896 .priv_class = &ipod_muxer_class,
6899 #if CONFIG_ISMV_MUXER
6901 AVOutputFormat ff_ismv_muxer = {
6903 .long_name = NULL_IF_CONFIG_SMALL("ISMV/ISMA (Smooth Streaming)"),
6904 .mime_type = "video/mp4",
6905 .extensions = "ismv,isma",
6906 .priv_data_size = sizeof(MOVMuxContext),
6907 .audio_codec = AV_CODEC_ID_AAC,
6908 .video_codec = AV_CODEC_ID_H264,
6910 .write_header = mov_write_header,
6911 .write_packet = mov_write_packet,
6912 .write_trailer = mov_write_trailer,
6914 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6915 .codec_tag = (const AVCodecTag* const []){
6916 codec_mp4_tags, codec_ism_tags, 0 },
6917 .check_bitstream = mov_check_bitstream,
6918 .priv_class = &ismv_muxer_class,
6921 #if CONFIG_F4V_MUXER
6923 AVOutputFormat ff_f4v_muxer = {
6925 .long_name = NULL_IF_CONFIG_SMALL("F4V Adobe Flash Video"),
6926 .mime_type = "application/f4v",
6927 .extensions = "f4v",
6928 .priv_data_size = sizeof(MOVMuxContext),
6929 .audio_codec = AV_CODEC_ID_AAC,
6930 .video_codec = AV_CODEC_ID_H264,
6932 .write_header = mov_write_header,
6933 .write_packet = mov_write_packet,
6934 .write_trailer = mov_write_trailer,
6936 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH,
6937 .codec_tag = (const AVCodecTag* const []){ codec_f4v_tags, 0 },
6938 .check_bitstream = mov_check_bitstream,
6939 .priv_class = &f4v_muxer_class,