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"
35 #include "libavcodec/ac3_parser_internal.h"
36 #include "libavcodec/dnxhddata.h"
37 #include "libavcodec/flac.h"
38 #include "libavcodec/get_bits.h"
40 #include "libavcodec/internal.h"
41 #include "libavcodec/put_bits.h"
42 #include "libavcodec/vc1_common.h"
43 #include "libavcodec/raw.h"
45 #include "libavutil/avstring.h"
46 #include "libavutil/intfloat.h"
47 #include "libavutil/mathematics.h"
48 #include "libavutil/libm.h"
49 #include "libavutil/opt.h"
50 #include "libavutil/dict.h"
51 #include "libavutil/pixdesc.h"
52 #include "libavutil/stereo3d.h"
53 #include "libavutil/timecode.h"
54 #include "libavutil/color_utils.h"
60 static const AVOption options[] = {
61 { "movflags", "MOV muxer flags", offsetof(MOVMuxContext, flags), AV_OPT_TYPE_FLAGS, {.i64 = 0}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
62 { "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" },
63 { "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 },
64 { "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" },
65 { "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" },
66 { "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" },
67 { "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" },
68 { "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" },
69 { "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" },
70 { "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" },
71 { "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" },
72 { "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" },
73 { "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" },
74 { "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" },
75 { "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" },
76 { "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" },
77 { "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" },
78 { "skip_sidx", "Skip writing of sidx atom", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_SKIP_SIDX}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
79 { "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" },
80 { "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" },
81 { "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" },
82 { "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" },
83 { "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" },
84 FF_RTP_FLAG_OPTS(MOVMuxContext, rtp_flags),
85 { "skip_iods", "Skip writing iods atom.", offsetof(MOVMuxContext, iods_skip), AV_OPT_TYPE_BOOL, {.i64 = 1}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM},
86 { "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},
87 { "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},
88 { "frag_duration", "Maximum fragment duration", offsetof(MOVMuxContext, max_fragment_duration), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
89 { "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},
90 { "frag_size", "Maximum fragment size", offsetof(MOVMuxContext, max_fragment_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
91 { "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},
92 { "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},
93 { "brand", "Override major brand", offsetof(MOVMuxContext, major_brand), AV_OPT_TYPE_STRING, {.str = NULL}, .flags = AV_OPT_FLAG_ENCODING_PARAM },
94 { "use_editlist", "use edit list", offsetof(MOVMuxContext, use_editlist), AV_OPT_TYPE_BOOL, {.i64 = -1}, -1, 1, AV_OPT_FLAG_ENCODING_PARAM},
95 { "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},
96 { "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},
97 { "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 },
98 { "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 },
99 { "encryption_key", "The media encryption key (hex)", offsetof(MOVMuxContext, encryption_key), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_ENCODING_PARAM },
100 { "encryption_kid", "The media encryption key identifier (hex)", offsetof(MOVMuxContext, encryption_kid), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_ENCODING_PARAM },
101 { "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},
102 { "write_tmcd", "force or disable writing tmcd", offsetof(MOVMuxContext, write_tmcd), AV_OPT_TYPE_BOOL, {.i64 = -1}, -1, 1, AV_OPT_FLAG_ENCODING_PARAM},
103 { "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"},
104 { "wallclock", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = MOV_PRFT_SRC_WALLCLOCK}, 0, 0, AV_OPT_FLAG_ENCODING_PARAM, "prft"},
105 { "pts", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = MOV_PRFT_SRC_PTS}, 0, 0, AV_OPT_FLAG_ENCODING_PARAM, "prft"},
106 { "empty_hdlr_name", "write zero-length name string in hdlr atoms within mdia and minf atoms", offsetof(MOVMuxContext, empty_hdlr_name), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM},
110 #define MOV_CLASS(flavor)\
111 static const AVClass flavor ## _muxer_class = {\
112 .class_name = #flavor " muxer",\
113 .item_name = av_default_item_name,\
115 .version = LIBAVUTIL_VERSION_INT,\
118 static int get_moov_size(AVFormatContext *s);
120 static int utf8len(const uint8_t *b)
125 GET_UTF8(val, *b++, return -1;)
131 //FIXME support 64 bit variant with wide placeholders
132 static int64_t update_size(AVIOContext *pb, int64_t pos)
134 int64_t curpos = avio_tell(pb);
135 avio_seek(pb, pos, SEEK_SET);
136 avio_wb32(pb, curpos - pos); /* rewrite size */
137 avio_seek(pb, curpos, SEEK_SET);
142 static int co64_required(const MOVTrack *track)
144 if (track->entry > 0 && track->cluster[track->entry - 1].pos + track->data_offset > UINT32_MAX)
149 static int is_cover_image(const AVStream *st)
151 /* Eg. AV_DISPOSITION_ATTACHED_PIC | AV_DISPOSITION_TIMED_THUMBNAILS
152 * is encoded as sparse video track */
153 return st && st->disposition == AV_DISPOSITION_ATTACHED_PIC;
156 static int rtp_hinting_needed(const AVStream *st)
158 /* Add hint tracks for each real audio and video stream */
159 if (is_cover_image(st))
161 return st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ||
162 st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO;
165 /* Chunk offset atom */
166 static int mov_write_stco_tag(AVIOContext *pb, MOVTrack *track)
169 int mode64 = co64_required(track); // use 32 bit size variant if possible
170 int64_t pos = avio_tell(pb);
171 avio_wb32(pb, 0); /* size */
173 ffio_wfourcc(pb, "co64");
175 ffio_wfourcc(pb, "stco");
176 avio_wb32(pb, 0); /* version & flags */
177 avio_wb32(pb, track->chunkCount); /* entry count */
178 for (i = 0; i < track->entry; i++) {
179 if (!track->cluster[i].chunkNum)
182 avio_wb64(pb, track->cluster[i].pos + track->data_offset);
184 avio_wb32(pb, track->cluster[i].pos + track->data_offset);
186 return update_size(pb, pos);
189 /* Sample size atom */
190 static int mov_write_stsz_tag(AVIOContext *pb, MOVTrack *track)
193 int i, j, entries = 0, tst = -1, oldtst = -1;
195 int64_t pos = avio_tell(pb);
196 avio_wb32(pb, 0); /* size */
197 ffio_wfourcc(pb, "stsz");
198 avio_wb32(pb, 0); /* version & flags */
200 for (i = 0; i < track->entry; i++) {
201 tst = track->cluster[i].size / track->cluster[i].entries;
202 if (oldtst != -1 && tst != oldtst)
205 entries += track->cluster[i].entries;
207 if (equalChunks && track->entry) {
208 int sSize = track->entry ? track->cluster[0].size / track->cluster[0].entries : 0;
209 sSize = FFMAX(1, sSize); // adpcm mono case could make sSize == 0
210 avio_wb32(pb, sSize); // sample size
211 avio_wb32(pb, entries); // sample count
213 avio_wb32(pb, 0); // sample size
214 avio_wb32(pb, entries); // sample count
215 for (i = 0; i < track->entry; i++) {
216 for (j = 0; j < track->cluster[i].entries; j++) {
217 avio_wb32(pb, track->cluster[i].size /
218 track->cluster[i].entries);
222 return update_size(pb, pos);
225 /* Sample to chunk atom */
226 static int mov_write_stsc_tag(AVIOContext *pb, MOVTrack *track)
228 int index = 0, oldval = -1, i;
229 int64_t entryPos, curpos;
231 int64_t pos = avio_tell(pb);
232 avio_wb32(pb, 0); /* size */
233 ffio_wfourcc(pb, "stsc");
234 avio_wb32(pb, 0); // version & flags
235 entryPos = avio_tell(pb);
236 avio_wb32(pb, track->chunkCount); // entry count
237 for (i = 0; i < track->entry; i++) {
238 if (oldval != track->cluster[i].samples_in_chunk && track->cluster[i].chunkNum) {
239 avio_wb32(pb, track->cluster[i].chunkNum); // first chunk
240 avio_wb32(pb, track->cluster[i].samples_in_chunk); // samples per chunk
241 avio_wb32(pb, 0x1); // sample description index
242 oldval = track->cluster[i].samples_in_chunk;
246 curpos = avio_tell(pb);
247 avio_seek(pb, entryPos, SEEK_SET);
248 avio_wb32(pb, index); // rewrite size
249 avio_seek(pb, curpos, SEEK_SET);
251 return update_size(pb, pos);
254 /* Sync sample atom */
255 static int mov_write_stss_tag(AVIOContext *pb, MOVTrack *track, uint32_t flag)
257 int64_t curpos, entryPos;
259 int64_t pos = avio_tell(pb);
260 avio_wb32(pb, 0); // size
261 ffio_wfourcc(pb, flag == MOV_SYNC_SAMPLE ? "stss" : "stps");
262 avio_wb32(pb, 0); // version & flags
263 entryPos = avio_tell(pb);
264 avio_wb32(pb, track->entry); // entry count
265 for (i = 0; i < track->entry; i++) {
266 if (track->cluster[i].flags & flag) {
267 avio_wb32(pb, i + 1);
271 curpos = avio_tell(pb);
272 avio_seek(pb, entryPos, SEEK_SET);
273 avio_wb32(pb, index); // rewrite size
274 avio_seek(pb, curpos, SEEK_SET);
275 return update_size(pb, pos);
278 /* Sample dependency atom */
279 static int mov_write_sdtp_tag(AVIOContext *pb, MOVTrack *track)
282 uint8_t leading, dependent, reference, redundancy;
283 int64_t pos = avio_tell(pb);
284 avio_wb32(pb, 0); // size
285 ffio_wfourcc(pb, "sdtp");
286 avio_wb32(pb, 0); // version & flags
287 for (i = 0; i < track->entry; i++) {
288 dependent = MOV_SAMPLE_DEPENDENCY_YES;
289 leading = reference = redundancy = MOV_SAMPLE_DEPENDENCY_UNKNOWN;
290 if (track->cluster[i].flags & MOV_DISPOSABLE_SAMPLE) {
291 reference = MOV_SAMPLE_DEPENDENCY_NO;
293 if (track->cluster[i].flags & MOV_SYNC_SAMPLE) {
294 dependent = MOV_SAMPLE_DEPENDENCY_NO;
296 avio_w8(pb, (leading << 6) | (dependent << 4) |
297 (reference << 2) | redundancy);
299 return update_size(pb, pos);
302 static int mov_write_amr_tag(AVIOContext *pb, MOVTrack *track)
304 avio_wb32(pb, 0x11); /* size */
305 if (track->mode == MODE_MOV) ffio_wfourcc(pb, "samr");
306 else ffio_wfourcc(pb, "damr");
307 ffio_wfourcc(pb, "FFMP");
308 avio_w8(pb, 0); /* decoder version */
310 avio_wb16(pb, 0x81FF); /* Mode set (all modes for AMR_NB) */
311 avio_w8(pb, 0x00); /* Mode change period (no restriction) */
312 avio_w8(pb, 0x01); /* Frames per sample */
316 static int mov_write_ac3_tag(AVIOContext *pb, MOVTrack *track)
321 int fscod, bsid, bsmod, acmod, lfeon, frmsizecod;
323 if (track->vos_len < 7) {
324 av_log(pb, AV_LOG_ERROR,
325 "Cannot write moov atom before AC3 packets."
326 " Set the delay_moov flag to fix this.\n");
327 return AVERROR(EINVAL);
331 ffio_wfourcc(pb, "dac3");
333 init_get_bits(&gbc, track->vos_data + 4, (track->vos_len - 4) * 8);
334 fscod = get_bits(&gbc, 2);
335 frmsizecod = get_bits(&gbc, 6);
336 bsid = get_bits(&gbc, 5);
337 bsmod = get_bits(&gbc, 3);
338 acmod = get_bits(&gbc, 3);
340 skip_bits(&gbc, 2); // dsurmod
342 if ((acmod & 1) && acmod != 1)
343 skip_bits(&gbc, 2); // cmixlev
345 skip_bits(&gbc, 2); // surmixlev
347 lfeon = get_bits1(&gbc);
349 init_put_bits(&pbc, buf, sizeof(buf));
350 put_bits(&pbc, 2, fscod);
351 put_bits(&pbc, 5, bsid);
352 put_bits(&pbc, 3, bsmod);
353 put_bits(&pbc, 3, acmod);
354 put_bits(&pbc, 1, lfeon);
355 put_bits(&pbc, 5, frmsizecod >> 1); // bit_rate_code
356 put_bits(&pbc, 5, 0); // reserved
358 flush_put_bits(&pbc);
359 avio_write(pb, buf, sizeof(buf));
369 /* Layout of the EC3SpecificBox */
370 /* maximum bitrate */
372 /* number of independent substreams */
375 /* sample rate code (see ff_ac3_sample_rate_tab) 2 bits */
377 /* bit stream identification 5 bits */
379 /* one bit reserved */
380 /* audio service mixing (not supported yet) 1 bit */
381 /* bit stream mode 3 bits */
383 /* audio coding mode 3 bits */
385 /* sub woofer on 1 bit */
387 /* 3 bits reserved */
388 /* number of dependent substreams associated with this substream 4 bits */
390 /* channel locations of the dependent substream(s), if any, 9 bits */
392 /* if there is no dependent substream, then one bit reserved instead */
393 } substream[1]; /* TODO: support 8 independent substreams */
396 #if CONFIG_AC3_PARSER
397 static int handle_eac3(MOVMuxContext *mov, AVPacket *pkt, MOVTrack *track)
399 AC3HeaderInfo *hdr = NULL;
400 struct eac3_info *info;
403 if (!track->eac3_priv && !(track->eac3_priv = av_mallocz(sizeof(*info))))
404 return AVERROR(ENOMEM);
405 info = track->eac3_priv;
407 if (avpriv_ac3_parse_header(&hdr, pkt->data, pkt->size) < 0) {
408 /* drop the packets until we see a good one */
410 av_log(mov->fc, AV_LOG_WARNING, "Dropping invalid packet from start of the stream\n");
413 ret = AVERROR_INVALIDDATA;
417 info->data_rate = FFMAX(info->data_rate, hdr->bit_rate / 1000);
418 num_blocks = hdr->num_blocks;
420 if (!info->ec3_done) {
421 /* AC-3 substream must be the first one */
422 if (hdr->bitstream_id <= 10 && hdr->substreamid != 0) {
423 ret = AVERROR(EINVAL);
427 /* this should always be the case, given that our AC-3 parser
428 * concatenates dependent frames to their independent parent */
429 if (hdr->frame_type == EAC3_FRAME_TYPE_INDEPENDENT) {
430 /* substream ids must be incremental */
431 if (hdr->substreamid > info->num_ind_sub + 1) {
432 ret = AVERROR(EINVAL);
436 if (hdr->substreamid == info->num_ind_sub + 1) {
437 //info->num_ind_sub++;
438 avpriv_request_sample(mov->fc, "Multiple independent substreams");
439 ret = AVERROR_PATCHWELCOME;
441 } else if (hdr->substreamid < info->num_ind_sub ||
442 hdr->substreamid == 0 && info->substream[0].bsid) {
447 if (hdr->substreamid != 0) {
448 avpriv_request_sample(mov->fc, "Multiple non EAC3 independent substreams");
449 ret = AVERROR_PATCHWELCOME;
454 /* fill the info needed for the "dec3" atom */
455 info->substream[hdr->substreamid].fscod = hdr->sr_code;
456 info->substream[hdr->substreamid].bsid = hdr->bitstream_id;
457 info->substream[hdr->substreamid].bsmod = hdr->bitstream_mode;
458 info->substream[hdr->substreamid].acmod = hdr->channel_mode;
459 info->substream[hdr->substreamid].lfeon = hdr->lfe_on;
461 /* Parse dependent substream(s), if any */
462 if (pkt->size != hdr->frame_size) {
463 int cumul_size = hdr->frame_size;
464 int parent = hdr->substreamid;
466 while (cumul_size != pkt->size) {
469 ret = avpriv_ac3_parse_header(&hdr, pkt->data + cumul_size, pkt->size - cumul_size);
472 if (hdr->frame_type != EAC3_FRAME_TYPE_DEPENDENT) {
473 ret = AVERROR(EINVAL);
476 info->substream[parent].num_dep_sub++;
479 /* header is parsed up to lfeon, but custom channel map may be needed */
480 init_get_bits8(&gbc, pkt->data + cumul_size + ret, pkt->size - cumul_size - ret);
483 /* skip volume control params */
484 for (i = 0; i < (hdr->channel_mode ? 1 : 2); i++) {
485 skip_bits(&gbc, 5); // skip dialog normalization
486 if (get_bits1(&gbc)) {
487 skip_bits(&gbc, 8); // skip compression gain word
490 /* get the dependent stream channel map, if exists */
492 info->substream[parent].chan_loc |= (get_bits(&gbc, 16) >> 5) & 0x1f;
494 info->substream[parent].chan_loc |= hdr->channel_mode;
495 cumul_size += hdr->frame_size;
501 if (!info->num_blocks && num_blocks == 6) {
505 else if (info->num_blocks + num_blocks > 6) {
506 ret = AVERROR_INVALIDDATA;
510 if (!info->num_blocks) {
511 ret = av_packet_ref(&info->pkt, pkt);
513 info->num_blocks = num_blocks;
516 if ((ret = av_grow_packet(&info->pkt, pkt->size)) < 0)
518 memcpy(info->pkt.data + info->pkt.size - pkt->size, pkt->data, pkt->size);
519 info->num_blocks += num_blocks;
520 info->pkt.duration += pkt->duration;
521 if ((ret = av_copy_packet_side_data(&info->pkt, pkt)) < 0)
523 if (info->num_blocks != 6)
525 av_packet_unref(pkt);
526 av_packet_move_ref(pkt, &info->pkt);
527 info->num_blocks = 0;
538 static int mov_write_eac3_tag(AVIOContext *pb, MOVTrack *track)
542 struct eac3_info *info;
545 if (!track->eac3_priv) {
546 av_log(pb, AV_LOG_ERROR,
547 "Cannot write moov atom before EAC3 packets parsed.\n");
548 return AVERROR(EINVAL);
551 info = track->eac3_priv;
552 size = 2 + ((34 * (info->num_ind_sub + 1) + 7) >> 3);
553 buf = av_malloc(size);
555 return AVERROR(ENOMEM);
558 init_put_bits(&pbc, buf, size);
559 put_bits(&pbc, 13, info->data_rate);
560 put_bits(&pbc, 3, info->num_ind_sub);
561 for (i = 0; i <= info->num_ind_sub; i++) {
562 put_bits(&pbc, 2, info->substream[i].fscod);
563 put_bits(&pbc, 5, info->substream[i].bsid);
564 put_bits(&pbc, 1, 0); /* reserved */
565 put_bits(&pbc, 1, 0); /* asvc */
566 put_bits(&pbc, 3, info->substream[i].bsmod);
567 put_bits(&pbc, 3, info->substream[i].acmod);
568 put_bits(&pbc, 1, info->substream[i].lfeon);
569 put_bits(&pbc, 5, 0); /* reserved */
570 put_bits(&pbc, 4, info->substream[i].num_dep_sub);
571 if (!info->substream[i].num_dep_sub) {
572 put_bits(&pbc, 1, 0); /* reserved */
574 put_bits(&pbc, 9, info->substream[i].chan_loc);
577 flush_put_bits(&pbc);
578 size = put_bits_count(&pbc) >> 3;
580 avio_wb32(pb, size + 8);
581 ffio_wfourcc(pb, "dec3");
582 avio_write(pb, buf, size);
590 * This function writes extradata "as is".
591 * Extradata must be formatted like a valid atom (with size and tag).
593 static int mov_write_extradata_tag(AVIOContext *pb, MOVTrack *track)
595 avio_write(pb, track->par->extradata, track->par->extradata_size);
596 return track->par->extradata_size;
599 static int mov_write_enda_tag(AVIOContext *pb)
602 ffio_wfourcc(pb, "enda");
603 avio_wb16(pb, 1); /* little endian */
607 static int mov_write_enda_tag_be(AVIOContext *pb)
610 ffio_wfourcc(pb, "enda");
611 avio_wb16(pb, 0); /* big endian */
615 static void put_descr(AVIOContext *pb, int tag, unsigned int size)
620 avio_w8(pb, (size >> (7 * i)) | 0x80);
621 avio_w8(pb, size & 0x7F);
624 static unsigned compute_avg_bitrate(MOVTrack *track)
628 if (!track->track_duration)
630 for (i = 0; i < track->entry; i++)
631 size += track->cluster[i].size;
632 return size * 8 * track->timescale / track->track_duration;
635 static int mov_write_esds_tag(AVIOContext *pb, MOVTrack *track) // Basic
637 AVCPBProperties *props;
638 int64_t pos = avio_tell(pb);
639 int decoder_specific_info_len = track->vos_len ? 5 + track->vos_len : 0;
640 unsigned avg_bitrate;
642 avio_wb32(pb, 0); // size
643 ffio_wfourcc(pb, "esds");
644 avio_wb32(pb, 0); // Version
647 put_descr(pb, 0x03, 3 + 5+13 + decoder_specific_info_len + 5+1);
648 avio_wb16(pb, track->track_id);
649 avio_w8(pb, 0x00); // flags (= no flags)
651 // DecoderConfig descriptor
652 put_descr(pb, 0x04, 13 + decoder_specific_info_len);
654 // Object type indication
655 if ((track->par->codec_id == AV_CODEC_ID_MP2 ||
656 track->par->codec_id == AV_CODEC_ID_MP3) &&
657 track->par->sample_rate > 24000)
658 avio_w8(pb, 0x6B); // 11172-3
660 avio_w8(pb, ff_codec_get_tag(ff_mp4_obj_type, track->par->codec_id));
662 // the following fields is made of 6 bits to identify the streamtype (4 for video, 5 for audio)
663 // plus 1 bit to indicate upstream and 1 bit set to 1 (reserved)
664 if (track->par->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
665 avio_w8(pb, (0x38 << 2) | 1); // flags (= NeroSubpicStream)
666 else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
667 avio_w8(pb, 0x15); // flags (= Audiostream)
669 avio_w8(pb, 0x11); // flags (= Visualstream)
671 props = (AVCPBProperties*)av_stream_get_side_data(track->st, AV_PKT_DATA_CPB_PROPERTIES,
674 avio_wb24(pb, props ? props->buffer_size / 8 : 0); // Buffersize DB
676 avg_bitrate = compute_avg_bitrate(track);
677 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)
678 avio_wb32(pb, avg_bitrate);
680 if (track->vos_len) {
681 // DecoderSpecific info descriptor
682 put_descr(pb, 0x05, track->vos_len);
683 avio_write(pb, track->vos_data, track->vos_len);
687 put_descr(pb, 0x06, 1);
689 return update_size(pb, pos);
692 static int mov_pcm_le_gt16(enum AVCodecID codec_id)
694 return codec_id == AV_CODEC_ID_PCM_S24LE ||
695 codec_id == AV_CODEC_ID_PCM_S32LE ||
696 codec_id == AV_CODEC_ID_PCM_F32LE ||
697 codec_id == AV_CODEC_ID_PCM_F64LE;
700 static int mov_pcm_be_gt16(enum AVCodecID codec_id)
702 return codec_id == AV_CODEC_ID_PCM_S24BE ||
703 codec_id == AV_CODEC_ID_PCM_S32BE ||
704 codec_id == AV_CODEC_ID_PCM_F32BE ||
705 codec_id == AV_CODEC_ID_PCM_F64BE;
708 static int mov_write_ms_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
711 int64_t pos = avio_tell(pb);
713 avio_wl32(pb, track->tag); // store it byteswapped
714 track->par->codec_tag = av_bswap16(track->tag >> 16);
715 if ((ret = ff_put_wav_header(s, pb, track->par, 0)) < 0)
717 return update_size(pb, pos);
720 static int mov_write_wfex_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
723 int64_t pos = avio_tell(pb);
725 ffio_wfourcc(pb, "wfex");
726 if ((ret = ff_put_wav_header(s, pb, track->st->codecpar, FF_PUT_WAV_HEADER_FORCE_WAVEFORMATEX)) < 0)
728 return update_size(pb, pos);
731 static int mov_write_dfla_tag(AVIOContext *pb, MOVTrack *track)
733 int64_t pos = avio_tell(pb);
735 ffio_wfourcc(pb, "dfLa");
736 avio_w8(pb, 0); /* version */
737 avio_wb24(pb, 0); /* flags */
739 /* Expect the encoder to pass a METADATA_BLOCK_TYPE_STREAMINFO. */
740 if (track->par->extradata_size != FLAC_STREAMINFO_SIZE)
741 return AVERROR_INVALIDDATA;
743 /* TODO: Write other METADATA_BLOCK_TYPEs if the encoder makes them available. */
744 avio_w8(pb, 1 << 7 | FLAC_METADATA_TYPE_STREAMINFO); /* LastMetadataBlockFlag << 7 | BlockType */
745 avio_wb24(pb, track->par->extradata_size); /* Length */
746 avio_write(pb, track->par->extradata, track->par->extradata_size); /* BlockData[Length] */
748 return update_size(pb, pos);
751 static int mov_write_dops_tag(AVIOContext *pb, MOVTrack *track)
753 int64_t pos = avio_tell(pb);
755 ffio_wfourcc(pb, "dOps");
756 avio_w8(pb, 0); /* Version */
757 if (track->par->extradata_size < 19) {
758 av_log(pb, AV_LOG_ERROR, "invalid extradata size\n");
759 return AVERROR_INVALIDDATA;
761 /* extradata contains an Ogg OpusHead, other than byte-ordering and
762 OpusHead's preceeding magic/version, OpusSpecificBox is currently
764 avio_w8(pb, AV_RB8(track->par->extradata + 9)); /* OuputChannelCount */
765 avio_wb16(pb, AV_RL16(track->par->extradata + 10)); /* PreSkip */
766 avio_wb32(pb, AV_RL32(track->par->extradata + 12)); /* InputSampleRate */
767 avio_wb16(pb, AV_RL16(track->par->extradata + 16)); /* OutputGain */
768 /* Write the rest of the header out without byte-swapping. */
769 avio_write(pb, track->par->extradata + 18, track->par->extradata_size - 18);
771 return update_size(pb, pos);
774 static int mov_write_chan_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
776 uint32_t layout_tag, bitmap;
777 int64_t pos = avio_tell(pb);
779 layout_tag = ff_mov_get_channel_layout_tag(track->par->codec_id,
780 track->par->channel_layout,
783 av_log(s, AV_LOG_WARNING, "not writing 'chan' tag due to "
784 "lack of channel information\n");
788 if (track->multichannel_as_mono)
791 avio_wb32(pb, 0); // Size
792 ffio_wfourcc(pb, "chan"); // Type
793 avio_w8(pb, 0); // Version
794 avio_wb24(pb, 0); // Flags
795 avio_wb32(pb, layout_tag); // mChannelLayoutTag
796 avio_wb32(pb, bitmap); // mChannelBitmap
797 avio_wb32(pb, 0); // mNumberChannelDescriptions
799 return update_size(pb, pos);
802 static int mov_write_wave_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
804 int64_t pos = avio_tell(pb);
806 avio_wb32(pb, 0); /* size */
807 ffio_wfourcc(pb, "wave");
809 if (track->par->codec_id != AV_CODEC_ID_QDM2) {
810 avio_wb32(pb, 12); /* size */
811 ffio_wfourcc(pb, "frma");
812 avio_wl32(pb, track->tag);
815 if (track->par->codec_id == AV_CODEC_ID_AAC) {
816 /* useless atom needed by mplayer, ipod, not needed by quicktime */
817 avio_wb32(pb, 12); /* size */
818 ffio_wfourcc(pb, "mp4a");
820 mov_write_esds_tag(pb, track);
821 } else if (mov_pcm_le_gt16(track->par->codec_id)) {
822 mov_write_enda_tag(pb);
823 } else if (mov_pcm_be_gt16(track->par->codec_id)) {
824 mov_write_enda_tag_be(pb);
825 } else if (track->par->codec_id == AV_CODEC_ID_AMR_NB) {
826 mov_write_amr_tag(pb, track);
827 } else if (track->par->codec_id == AV_CODEC_ID_AC3) {
828 mov_write_ac3_tag(pb, track);
829 } else if (track->par->codec_id == AV_CODEC_ID_EAC3) {
830 mov_write_eac3_tag(pb, track);
831 } else if (track->par->codec_id == AV_CODEC_ID_ALAC ||
832 track->par->codec_id == AV_CODEC_ID_QDM2) {
833 mov_write_extradata_tag(pb, track);
834 } else if (track->par->codec_id == AV_CODEC_ID_ADPCM_MS ||
835 track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) {
836 mov_write_ms_tag(s, pb, track);
839 avio_wb32(pb, 8); /* size */
840 avio_wb32(pb, 0); /* null tag */
842 return update_size(pb, pos);
845 static int mov_write_dvc1_structs(MOVTrack *track, uint8_t *buf)
848 const uint8_t *start, *next, *end = track->vos_data + track->vos_len;
849 int unescaped_size, seq_found = 0;
850 int level = 0, interlace = 0;
851 int packet_seq = track->vc1_info.packet_seq;
852 int packet_entry = track->vc1_info.packet_entry;
853 int slices = track->vc1_info.slices;
856 if (track->start_dts == AV_NOPTS_VALUE) {
857 /* No packets written yet, vc1_info isn't authoritative yet. */
858 /* Assume inline sequence and entry headers. */
859 packet_seq = packet_entry = 1;
860 av_log(NULL, AV_LOG_WARNING,
861 "moov atom written before any packets, unable to write correct "
862 "dvc1 atom. Set the delay_moov flag to fix this.\n");
865 unescaped = av_mallocz(track->vos_len + AV_INPUT_BUFFER_PADDING_SIZE);
867 return AVERROR(ENOMEM);
868 start = find_next_marker(track->vos_data, end);
869 for (next = start; next < end; start = next) {
872 next = find_next_marker(start + 4, end);
873 size = next - start - 4;
876 unescaped_size = vc1_unescape_buffer(start + 4, size, unescaped);
877 init_get_bits(&gb, unescaped, 8 * unescaped_size);
878 if (AV_RB32(start) == VC1_CODE_SEQHDR) {
879 int profile = get_bits(&gb, 2);
880 if (profile != PROFILE_ADVANCED) {
882 return AVERROR(ENOSYS);
885 level = get_bits(&gb, 3);
886 /* chromaformat, frmrtq_postproc, bitrtq_postproc, postprocflag,
888 skip_bits_long(&gb, 2 + 3 + 5 + 1 + 2*12);
889 skip_bits(&gb, 1); /* broadcast */
890 interlace = get_bits1(&gb);
891 skip_bits(&gb, 4); /* tfcntrflag, finterpflag, reserved, psf */
896 return AVERROR(ENOSYS);
899 init_put_bits(&pbc, buf, 7);
900 /* VC1DecSpecStruc */
901 put_bits(&pbc, 4, 12); /* profile - advanced */
902 put_bits(&pbc, 3, level);
903 put_bits(&pbc, 1, 0); /* reserved */
904 /* VC1AdvDecSpecStruc */
905 put_bits(&pbc, 3, level);
906 put_bits(&pbc, 1, 0); /* cbr */
907 put_bits(&pbc, 6, 0); /* reserved */
908 put_bits(&pbc, 1, !interlace); /* no interlace */
909 put_bits(&pbc, 1, !packet_seq); /* no multiple seq */
910 put_bits(&pbc, 1, !packet_entry); /* no multiple entry */
911 put_bits(&pbc, 1, !slices); /* no slice code */
912 put_bits(&pbc, 1, 0); /* no bframe */
913 put_bits(&pbc, 1, 0); /* reserved */
916 if (track->st->avg_frame_rate.num > 0 && track->st->avg_frame_rate.den > 0)
917 put_bits32(&pbc, track->st->avg_frame_rate.num / track->st->avg_frame_rate.den);
919 put_bits32(&pbc, 0xffffffff);
921 flush_put_bits(&pbc);
928 static int mov_write_dvc1_tag(AVIOContext *pb, MOVTrack *track)
930 uint8_t buf[7] = { 0 };
933 if ((ret = mov_write_dvc1_structs(track, buf)) < 0)
936 avio_wb32(pb, track->vos_len + 8 + sizeof(buf));
937 ffio_wfourcc(pb, "dvc1");
938 avio_write(pb, buf, sizeof(buf));
939 avio_write(pb, track->vos_data, track->vos_len);
944 static int mov_write_glbl_tag(AVIOContext *pb, MOVTrack *track)
946 avio_wb32(pb, track->vos_len + 8);
947 ffio_wfourcc(pb, "glbl");
948 avio_write(pb, track->vos_data, track->vos_len);
949 return 8 + track->vos_len;
953 * Compute flags for 'lpcm' tag.
954 * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
956 static int mov_get_lpcm_flags(enum AVCodecID codec_id)
959 case AV_CODEC_ID_PCM_F32BE:
960 case AV_CODEC_ID_PCM_F64BE:
962 case AV_CODEC_ID_PCM_F32LE:
963 case AV_CODEC_ID_PCM_F64LE:
965 case AV_CODEC_ID_PCM_U8:
967 case AV_CODEC_ID_PCM_S16BE:
968 case AV_CODEC_ID_PCM_S24BE:
969 case AV_CODEC_ID_PCM_S32BE:
971 case AV_CODEC_ID_PCM_S8:
972 case AV_CODEC_ID_PCM_S16LE:
973 case AV_CODEC_ID_PCM_S24LE:
974 case AV_CODEC_ID_PCM_S32LE:
981 static int get_cluster_duration(MOVTrack *track, int cluster_idx)
985 if (cluster_idx >= track->entry)
988 if (cluster_idx + 1 == track->entry)
989 next_dts = track->track_duration + track->start_dts;
991 next_dts = track->cluster[cluster_idx + 1].dts;
993 next_dts -= track->cluster[cluster_idx].dts;
995 av_assert0(next_dts >= 0);
996 av_assert0(next_dts <= INT_MAX);
1001 static int get_samples_per_packet(MOVTrack *track)
1003 int i, first_duration;
1005 // return track->par->frame_size;
1007 /* use 1 for raw PCM */
1008 if (!track->audio_vbr)
1011 /* check to see if duration is constant for all clusters */
1014 first_duration = get_cluster_duration(track, 0);
1015 for (i = 1; i < track->entry; i++) {
1016 if (get_cluster_duration(track, i) != first_duration)
1019 return first_duration;
1022 static int mov_write_audio_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
1024 int64_t pos = avio_tell(pb);
1026 uint32_t tag = track->tag;
1029 if (track->mode == MODE_MOV) {
1030 if (track->timescale > UINT16_MAX || !track->par->channels) {
1031 if (mov_get_lpcm_flags(track->par->codec_id))
1032 tag = AV_RL32("lpcm");
1034 } else if (track->audio_vbr || mov_pcm_le_gt16(track->par->codec_id) ||
1035 mov_pcm_be_gt16(track->par->codec_id) ||
1036 track->par->codec_id == AV_CODEC_ID_ADPCM_MS ||
1037 track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
1038 track->par->codec_id == AV_CODEC_ID_QDM2) {
1043 avio_wb32(pb, 0); /* size */
1044 if (mov->encryption_scheme != MOV_ENC_NONE) {
1045 ffio_wfourcc(pb, "enca");
1047 avio_wl32(pb, tag); // store it byteswapped
1049 avio_wb32(pb, 0); /* Reserved */
1050 avio_wb16(pb, 0); /* Reserved */
1051 avio_wb16(pb, 1); /* Data-reference index, XXX == 1 */
1053 /* SoundDescription */
1054 avio_wb16(pb, version); /* Version */
1055 avio_wb16(pb, 0); /* Revision level */
1056 avio_wb32(pb, 0); /* Reserved */
1061 avio_wb16(pb, 0xfffe);
1063 avio_wb32(pb, 0x00010000);
1065 avio_wb64(pb, av_double2int(track->par->sample_rate));
1066 avio_wb32(pb, track->par->channels);
1067 avio_wb32(pb, 0x7F000000);
1068 avio_wb32(pb, av_get_bits_per_sample(track->par->codec_id));
1069 avio_wb32(pb, mov_get_lpcm_flags(track->par->codec_id));
1070 avio_wb32(pb, track->sample_size);
1071 avio_wb32(pb, get_samples_per_packet(track));
1073 if (track->mode == MODE_MOV) {
1074 avio_wb16(pb, track->par->channels);
1075 if (track->par->codec_id == AV_CODEC_ID_PCM_U8 ||
1076 track->par->codec_id == AV_CODEC_ID_PCM_S8)
1077 avio_wb16(pb, 8); /* bits per sample */
1078 else if (track->par->codec_id == AV_CODEC_ID_ADPCM_G726)
1079 avio_wb16(pb, track->par->bits_per_coded_sample);
1082 avio_wb16(pb, track->audio_vbr ? -2 : 0); /* compression ID */
1083 } else { /* reserved for mp4/3gp */
1084 if (track->par->codec_id == AV_CODEC_ID_FLAC ||
1085 track->par->codec_id == AV_CODEC_ID_ALAC ||
1086 track->par->codec_id == AV_CODEC_ID_OPUS) {
1087 avio_wb16(pb, track->par->channels);
1091 if (track->par->codec_id == AV_CODEC_ID_FLAC ||
1092 track->par->codec_id == AV_CODEC_ID_ALAC) {
1093 avio_wb16(pb, track->par->bits_per_raw_sample);
1100 avio_wb16(pb, 0); /* packet size (= 0) */
1101 if (track->par->codec_id == AV_CODEC_ID_OPUS)
1102 avio_wb16(pb, 48000);
1104 avio_wb16(pb, track->par->sample_rate <= UINT16_MAX ?
1105 track->par->sample_rate : 0);
1106 avio_wb16(pb, 0); /* Reserved */
1109 if (version == 1) { /* SoundDescription V1 extended info */
1110 if (mov_pcm_le_gt16(track->par->codec_id) ||
1111 mov_pcm_be_gt16(track->par->codec_id))
1112 avio_wb32(pb, 1); /* must be 1 for uncompressed formats */
1114 avio_wb32(pb, track->par->frame_size); /* Samples per packet */
1115 avio_wb32(pb, track->sample_size / track->par->channels); /* Bytes per packet */
1116 avio_wb32(pb, track->sample_size); /* Bytes per frame */
1117 avio_wb32(pb, 2); /* Bytes per sample */
1120 if (track->mode == MODE_MOV &&
1121 (track->par->codec_id == AV_CODEC_ID_AAC ||
1122 track->par->codec_id == AV_CODEC_ID_AC3 ||
1123 track->par->codec_id == AV_CODEC_ID_EAC3 ||
1124 track->par->codec_id == AV_CODEC_ID_AMR_NB ||
1125 track->par->codec_id == AV_CODEC_ID_ALAC ||
1126 track->par->codec_id == AV_CODEC_ID_ADPCM_MS ||
1127 track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
1128 track->par->codec_id == AV_CODEC_ID_QDM2 ||
1129 (mov_pcm_le_gt16(track->par->codec_id) && version==1) ||
1130 (mov_pcm_be_gt16(track->par->codec_id) && version==1)))
1131 ret = mov_write_wave_tag(s, pb, track);
1132 else if (track->tag == MKTAG('m','p','4','a'))
1133 ret = mov_write_esds_tag(pb, track);
1134 else if (track->par->codec_id == AV_CODEC_ID_AMR_NB)
1135 ret = mov_write_amr_tag(pb, track);
1136 else if (track->par->codec_id == AV_CODEC_ID_AC3)
1137 ret = mov_write_ac3_tag(pb, track);
1138 else if (track->par->codec_id == AV_CODEC_ID_EAC3)
1139 ret = mov_write_eac3_tag(pb, track);
1140 else if (track->par->codec_id == AV_CODEC_ID_ALAC)
1141 ret = mov_write_extradata_tag(pb, track);
1142 else if (track->par->codec_id == AV_CODEC_ID_WMAPRO)
1143 ret = mov_write_wfex_tag(s, pb, track);
1144 else if (track->par->codec_id == AV_CODEC_ID_FLAC)
1145 ret = mov_write_dfla_tag(pb, track);
1146 else if (track->par->codec_id == AV_CODEC_ID_OPUS)
1147 ret = mov_write_dops_tag(pb, track);
1148 else if (track->vos_len > 0)
1149 ret = mov_write_glbl_tag(pb, track);
1154 if (track->mode == MODE_MOV && track->par->codec_type == AVMEDIA_TYPE_AUDIO
1155 && ((ret = mov_write_chan_tag(s, pb, track)) < 0)) {
1159 if (mov->encryption_scheme != MOV_ENC_NONE
1160 && ((ret = ff_mov_cenc_write_sinf_tag(track, pb, mov->encryption_kid)) < 0)) {
1164 ret = update_size(pb, pos);
1168 static int mov_write_d263_tag(AVIOContext *pb)
1170 avio_wb32(pb, 0xf); /* size */
1171 ffio_wfourcc(pb, "d263");
1172 ffio_wfourcc(pb, "FFMP");
1173 avio_w8(pb, 0); /* decoder version */
1174 /* FIXME use AVCodecContext level/profile, when encoder will set values */
1175 avio_w8(pb, 0xa); /* level */
1176 avio_w8(pb, 0); /* profile */
1180 static int mov_write_av1c_tag(AVIOContext *pb, MOVTrack *track)
1182 int64_t pos = avio_tell(pb);
1185 ffio_wfourcc(pb, "av1C");
1186 ff_isom_write_av1c(pb, track->vos_data, track->vos_len);
1187 return update_size(pb, pos);
1190 static int mov_write_avcc_tag(AVIOContext *pb, MOVTrack *track)
1192 int64_t pos = avio_tell(pb);
1195 ffio_wfourcc(pb, "avcC");
1196 ff_isom_write_avcc(pb, track->vos_data, track->vos_len);
1197 return update_size(pb, pos);
1200 static int mov_write_vpcc_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
1202 int64_t pos = avio_tell(pb);
1205 ffio_wfourcc(pb, "vpcC");
1206 avio_w8(pb, 1); /* version */
1207 avio_wb24(pb, 0); /* flags */
1208 ff_isom_write_vpcc(s, pb, track->par);
1209 return update_size(pb, pos);
1212 static int mov_write_hvcc_tag(AVIOContext *pb, MOVTrack *track)
1214 int64_t pos = avio_tell(pb);
1217 ffio_wfourcc(pb, "hvcC");
1218 if (track->tag == MKTAG('h','v','c','1'))
1219 ff_isom_write_hvcc(pb, track->vos_data, track->vos_len, 1);
1221 ff_isom_write_hvcc(pb, track->vos_data, track->vos_len, 0);
1222 return update_size(pb, pos);
1225 /* also used by all avid codecs (dv, imx, meridien) and their variants */
1226 static int mov_write_avid_tag(AVIOContext *pb, MOVTrack *track)
1231 int display_width = track->par->width;
1233 if (track->vos_data && track->vos_len > 0x29) {
1234 if (ff_dnxhd_parse_header_prefix(track->vos_data) != 0) {
1235 /* looks like a DNxHD bit stream */
1236 interlaced = (track->vos_data[5] & 2);
1237 cid = AV_RB32(track->vos_data + 0x28);
1239 av_log(NULL, AV_LOG_WARNING, "Could not locate DNxHD bit stream in vos_data\n");
1243 av_log(NULL, AV_LOG_WARNING, "Could not locate DNxHD bit stream, vos_data too small\n");
1247 avio_wb32(pb, 24); /* size */
1248 ffio_wfourcc(pb, "ACLR");
1249 ffio_wfourcc(pb, "ACLR");
1250 ffio_wfourcc(pb, "0001");
1251 if (track->par->color_range == AVCOL_RANGE_MPEG || /* Legal range (16-235) */
1252 track->par->color_range == AVCOL_RANGE_UNSPECIFIED) {
1253 avio_wb32(pb, 1); /* Corresponds to 709 in official encoder */
1254 } else { /* Full range (0-255) */
1255 avio_wb32(pb, 2); /* Corresponds to RGB in official encoder */
1257 avio_wb32(pb, 0); /* unknown */
1259 if (track->tag == MKTAG('A','V','d','h')) {
1261 ffio_wfourcc(pb, "ADHR");
1262 ffio_wfourcc(pb, "0001");
1264 avio_wb32(pb, 0); /* unknown */
1265 avio_wb32(pb, 1); /* unknown */
1266 avio_wb32(pb, 0); /* unknown */
1267 avio_wb32(pb, 0); /* unknown */
1271 avio_wb32(pb, 24); /* size */
1272 ffio_wfourcc(pb, "APRG");
1273 ffio_wfourcc(pb, "APRG");
1274 ffio_wfourcc(pb, "0001");
1275 avio_wb32(pb, 1); /* unknown */
1276 avio_wb32(pb, 0); /* unknown */
1278 avio_wb32(pb, 120); /* size */
1279 ffio_wfourcc(pb, "ARES");
1280 ffio_wfourcc(pb, "ARES");
1281 ffio_wfourcc(pb, "0001");
1282 avio_wb32(pb, cid); /* dnxhd cid, some id ? */
1283 if ( track->par->sample_aspect_ratio.num > 0
1284 && track->par->sample_aspect_ratio.den > 0)
1285 display_width = display_width * track->par->sample_aspect_ratio.num / track->par->sample_aspect_ratio.den;
1286 avio_wb32(pb, display_width);
1287 /* values below are based on samples created with quicktime and avid codecs */
1289 avio_wb32(pb, track->par->height / 2);
1290 avio_wb32(pb, 2); /* unknown */
1291 avio_wb32(pb, 0); /* unknown */
1292 avio_wb32(pb, 4); /* unknown */
1294 avio_wb32(pb, track->par->height);
1295 avio_wb32(pb, 1); /* unknown */
1296 avio_wb32(pb, 0); /* unknown */
1297 if (track->par->height == 1080)
1298 avio_wb32(pb, 5); /* unknown */
1300 avio_wb32(pb, 6); /* unknown */
1303 for (i = 0; i < 10; i++)
1309 static int mov_write_dpxe_tag(AVIOContext *pb, MOVTrack *track)
1312 ffio_wfourcc(pb, "DpxE");
1313 if (track->par->extradata_size >= 12 &&
1314 !memcmp(&track->par->extradata[4], "DpxE", 4)) {
1315 avio_wb32(pb, track->par->extradata[11]);
1322 static int mov_get_dv_codec_tag(AVFormatContext *s, MOVTrack *track)
1326 if (track->par->width == 720) { /* SD */
1327 if (track->par->height == 480) { /* NTSC */
1328 if (track->par->format == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','n');
1329 else tag = MKTAG('d','v','c',' ');
1330 }else if (track->par->format == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','p');
1331 else if (track->par->format == AV_PIX_FMT_YUV420P) tag = MKTAG('d','v','c','p');
1332 else tag = MKTAG('d','v','p','p');
1333 } else if (track->par->height == 720) { /* HD 720 line */
1334 if (track->st->time_base.den == 50) tag = MKTAG('d','v','h','q');
1335 else tag = MKTAG('d','v','h','p');
1336 } else if (track->par->height == 1080) { /* HD 1080 line */
1337 if (track->st->time_base.den == 25) tag = MKTAG('d','v','h','5');
1338 else tag = MKTAG('d','v','h','6');
1340 av_log(s, AV_LOG_ERROR, "unsupported height for dv codec\n");
1347 static AVRational find_fps(AVFormatContext *s, AVStream *st)
1349 AVRational rate = st->avg_frame_rate;
1351 #if FF_API_LAVF_AVCTX
1352 FF_DISABLE_DEPRECATION_WARNINGS
1353 rate = av_inv_q(st->codec->time_base);
1354 if (av_timecode_check_frame_rate(rate) < 0) {
1355 av_log(s, AV_LOG_DEBUG, "timecode: tbc=%d/%d invalid, fallback on %d/%d\n",
1356 rate.num, rate.den, st->avg_frame_rate.num, st->avg_frame_rate.den);
1357 rate = st->avg_frame_rate;
1359 FF_ENABLE_DEPRECATION_WARNINGS
1365 static int defined_frame_rate(AVFormatContext *s, AVStream *st)
1367 AVRational rational_framerate = find_fps(s, st);
1369 if (rational_framerate.den != 0)
1370 rate = av_q2d(rational_framerate);
1374 static int mov_get_mpeg2_xdcam_codec_tag(AVFormatContext *s, MOVTrack *track)
1376 int tag = track->par->codec_tag;
1377 int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE;
1378 AVStream *st = track->st;
1379 int rate = defined_frame_rate(s, st);
1382 tag = MKTAG('m', '2', 'v', '1'); //fallback tag
1384 if (track->par->format == AV_PIX_FMT_YUV420P) {
1385 if (track->par->width == 1280 && track->par->height == 720) {
1387 if (rate == 24) tag = MKTAG('x','d','v','4');
1388 else if (rate == 25) tag = MKTAG('x','d','v','5');
1389 else if (rate == 30) tag = MKTAG('x','d','v','1');
1390 else if (rate == 50) tag = MKTAG('x','d','v','a');
1391 else if (rate == 60) tag = MKTAG('x','d','v','9');
1393 } else if (track->par->width == 1440 && track->par->height == 1080) {
1395 if (rate == 24) tag = MKTAG('x','d','v','6');
1396 else if (rate == 25) tag = MKTAG('x','d','v','7');
1397 else if (rate == 30) tag = MKTAG('x','d','v','8');
1399 if (rate == 25) tag = MKTAG('x','d','v','3');
1400 else if (rate == 30) tag = MKTAG('x','d','v','2');
1402 } else if (track->par->width == 1920 && track->par->height == 1080) {
1404 if (rate == 24) tag = MKTAG('x','d','v','d');
1405 else if (rate == 25) tag = MKTAG('x','d','v','e');
1406 else if (rate == 30) tag = MKTAG('x','d','v','f');
1408 if (rate == 25) tag = MKTAG('x','d','v','c');
1409 else if (rate == 30) tag = MKTAG('x','d','v','b');
1412 } else if (track->par->format == AV_PIX_FMT_YUV422P) {
1413 if (track->par->width == 1280 && track->par->height == 720) {
1415 if (rate == 24) tag = MKTAG('x','d','5','4');
1416 else if (rate == 25) tag = MKTAG('x','d','5','5');
1417 else if (rate == 30) tag = MKTAG('x','d','5','1');
1418 else if (rate == 50) tag = MKTAG('x','d','5','a');
1419 else if (rate == 60) tag = MKTAG('x','d','5','9');
1421 } else if (track->par->width == 1920 && track->par->height == 1080) {
1423 if (rate == 24) tag = MKTAG('x','d','5','d');
1424 else if (rate == 25) tag = MKTAG('x','d','5','e');
1425 else if (rate == 30) tag = MKTAG('x','d','5','f');
1427 if (rate == 25) tag = MKTAG('x','d','5','c');
1428 else if (rate == 30) tag = MKTAG('x','d','5','b');
1436 static int mov_get_h264_codec_tag(AVFormatContext *s, MOVTrack *track)
1438 int tag = track->par->codec_tag;
1439 int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE;
1440 AVStream *st = track->st;
1441 int rate = defined_frame_rate(s, st);
1444 tag = MKTAG('a', 'v', 'c', 'i'); //fallback tag
1446 if (track->par->format == AV_PIX_FMT_YUV420P10) {
1447 if (track->par->width == 960 && track->par->height == 720) {
1449 if (rate == 24) tag = MKTAG('a','i','5','p');
1450 else if (rate == 25) tag = MKTAG('a','i','5','q');
1451 else if (rate == 30) tag = MKTAG('a','i','5','p');
1452 else if (rate == 50) tag = MKTAG('a','i','5','q');
1453 else if (rate == 60) tag = MKTAG('a','i','5','p');
1455 } else if (track->par->width == 1440 && track->par->height == 1080) {
1457 if (rate == 24) tag = MKTAG('a','i','5','3');
1458 else if (rate == 25) tag = MKTAG('a','i','5','2');
1459 else if (rate == 30) tag = MKTAG('a','i','5','3');
1461 if (rate == 50) tag = MKTAG('a','i','5','5');
1462 else if (rate == 60) tag = MKTAG('a','i','5','6');
1465 } else if (track->par->format == AV_PIX_FMT_YUV422P10) {
1466 if (track->par->width == 1280 && track->par->height == 720) {
1468 if (rate == 24) tag = MKTAG('a','i','1','p');
1469 else if (rate == 25) tag = MKTAG('a','i','1','q');
1470 else if (rate == 30) tag = MKTAG('a','i','1','p');
1471 else if (rate == 50) tag = MKTAG('a','i','1','q');
1472 else if (rate == 60) tag = MKTAG('a','i','1','p');
1474 } else if (track->par->width == 1920 && track->par->height == 1080) {
1476 if (rate == 24) tag = MKTAG('a','i','1','3');
1477 else if (rate == 25) tag = MKTAG('a','i','1','2');
1478 else if (rate == 30) tag = MKTAG('a','i','1','3');
1480 if (rate == 25) tag = MKTAG('a','i','1','5');
1481 else if (rate == 50) tag = MKTAG('a','i','1','5');
1482 else if (rate == 60) tag = MKTAG('a','i','1','6');
1484 } else if ( track->par->width == 4096 && track->par->height == 2160
1485 || track->par->width == 3840 && track->par->height == 2160
1486 || track->par->width == 2048 && track->par->height == 1080) {
1487 tag = MKTAG('a','i','v','x');
1494 static const struct {
1495 enum AVPixelFormat pix_fmt;
1498 } mov_pix_fmt_tags[] = {
1499 { AV_PIX_FMT_YUYV422, MKTAG('y','u','v','2'), 0 },
1500 { AV_PIX_FMT_YUYV422, MKTAG('y','u','v','s'), 0 },
1501 { AV_PIX_FMT_UYVY422, MKTAG('2','v','u','y'), 0 },
1502 { AV_PIX_FMT_RGB555BE,MKTAG('r','a','w',' '), 16 },
1503 { AV_PIX_FMT_RGB555LE,MKTAG('L','5','5','5'), 16 },
1504 { AV_PIX_FMT_RGB565LE,MKTAG('L','5','6','5'), 16 },
1505 { AV_PIX_FMT_RGB565BE,MKTAG('B','5','6','5'), 16 },
1506 { AV_PIX_FMT_GRAY16BE,MKTAG('b','1','6','g'), 16 },
1507 { AV_PIX_FMT_RGB24, MKTAG('r','a','w',' '), 24 },
1508 { AV_PIX_FMT_BGR24, MKTAG('2','4','B','G'), 24 },
1509 { AV_PIX_FMT_ARGB, MKTAG('r','a','w',' '), 32 },
1510 { AV_PIX_FMT_BGRA, MKTAG('B','G','R','A'), 32 },
1511 { AV_PIX_FMT_RGBA, MKTAG('R','G','B','A'), 32 },
1512 { AV_PIX_FMT_ABGR, MKTAG('A','B','G','R'), 32 },
1513 { AV_PIX_FMT_RGB48BE, MKTAG('b','4','8','r'), 48 },
1516 static int mov_get_dnxhd_codec_tag(AVFormatContext *s, MOVTrack *track)
1518 int tag = MKTAG('A','V','d','n');
1519 if (track->par->profile != FF_PROFILE_UNKNOWN &&
1520 track->par->profile != FF_PROFILE_DNXHD)
1521 tag = MKTAG('A','V','d','h');
1525 static int mov_get_rawvideo_codec_tag(AVFormatContext *s, MOVTrack *track)
1527 int tag = track->par->codec_tag;
1529 enum AVPixelFormat pix_fmt;
1531 for (i = 0; i < FF_ARRAY_ELEMS(mov_pix_fmt_tags); i++) {
1532 if (track->par->format == mov_pix_fmt_tags[i].pix_fmt) {
1533 tag = mov_pix_fmt_tags[i].tag;
1534 track->par->bits_per_coded_sample = mov_pix_fmt_tags[i].bps;
1535 if (track->par->codec_tag == mov_pix_fmt_tags[i].tag)
1540 pix_fmt = avpriv_find_pix_fmt(avpriv_pix_fmt_bps_mov,
1541 track->par->bits_per_coded_sample);
1542 if (tag == MKTAG('r','a','w',' ') &&
1543 track->par->format != pix_fmt &&
1544 track->par->format != AV_PIX_FMT_GRAY8 &&
1545 track->par->format != AV_PIX_FMT_NONE)
1546 av_log(s, AV_LOG_ERROR, "%s rawvideo cannot be written to mov, output file will be unreadable\n",
1547 av_get_pix_fmt_name(track->par->format));
1551 static unsigned int mov_get_codec_tag(AVFormatContext *s, MOVTrack *track)
1553 unsigned int tag = track->par->codec_tag;
1555 if (!tag || (s->strict_std_compliance >= FF_COMPLIANCE_NORMAL &&
1556 (track->par->codec_id == AV_CODEC_ID_DVVIDEO ||
1557 track->par->codec_id == AV_CODEC_ID_RAWVIDEO ||
1558 track->par->codec_id == AV_CODEC_ID_H263 ||
1559 track->par->codec_id == AV_CODEC_ID_H264 ||
1560 track->par->codec_id == AV_CODEC_ID_DNXHD ||
1561 track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO ||
1562 av_get_bits_per_sample(track->par->codec_id)))) { // pcm audio
1563 if (track->par->codec_id == AV_CODEC_ID_DVVIDEO)
1564 tag = mov_get_dv_codec_tag(s, track);
1565 else if (track->par->codec_id == AV_CODEC_ID_RAWVIDEO)
1566 tag = mov_get_rawvideo_codec_tag(s, track);
1567 else if (track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO)
1568 tag = mov_get_mpeg2_xdcam_codec_tag(s, track);
1569 else if (track->par->codec_id == AV_CODEC_ID_H264)
1570 tag = mov_get_h264_codec_tag(s, track);
1571 else if (track->par->codec_id == AV_CODEC_ID_DNXHD)
1572 tag = mov_get_dnxhd_codec_tag(s, track);
1573 else if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
1574 tag = ff_codec_get_tag(ff_codec_movvideo_tags, track->par->codec_id);
1575 if (!tag) { // if no mac fcc found, try with Microsoft tags
1576 tag = ff_codec_get_tag(ff_codec_bmp_tags, track->par->codec_id);
1578 av_log(s, AV_LOG_WARNING, "Using MS style video codec tag, "
1579 "the file may be unplayable!\n");
1581 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
1582 tag = ff_codec_get_tag(ff_codec_movaudio_tags, track->par->codec_id);
1583 if (!tag) { // if no mac fcc found, try with Microsoft tags
1584 int ms_tag = ff_codec_get_tag(ff_codec_wav_tags, track->par->codec_id);
1586 tag = MKTAG('m', 's', ((ms_tag >> 8) & 0xff), (ms_tag & 0xff));
1587 av_log(s, AV_LOG_WARNING, "Using MS style audio codec tag, "
1588 "the file may be unplayable!\n");
1591 } else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)
1592 tag = ff_codec_get_tag(ff_codec_movsubtitle_tags, track->par->codec_id);
1598 static const AVCodecTag codec_cover_image_tags[] = {
1599 { AV_CODEC_ID_MJPEG, 0xD },
1600 { AV_CODEC_ID_PNG, 0xE },
1601 { AV_CODEC_ID_BMP, 0x1B },
1602 { AV_CODEC_ID_NONE, 0 },
1605 static unsigned int validate_codec_tag(const AVCodecTag *const *tags,
1606 unsigned int tag, int codec_id)
1611 * Check that tag + id is in the table
1613 for (i = 0; tags && tags[i]; i++) {
1614 const AVCodecTag *codec_tags = tags[i];
1615 while (codec_tags->id != AV_CODEC_ID_NONE) {
1616 if (avpriv_toupper4(codec_tags->tag) == avpriv_toupper4(tag) &&
1617 codec_tags->id == codec_id)
1618 return codec_tags->tag;
1625 static unsigned int mov_find_codec_tag(AVFormatContext *s, MOVTrack *track)
1627 if (is_cover_image(track->st))
1628 return ff_codec_get_tag(codec_cover_image_tags, track->par->codec_id);
1630 if (track->mode == MODE_IPOD)
1631 if (!av_match_ext(s->url, "m4a") &&
1632 !av_match_ext(s->url, "m4v") &&
1633 !av_match_ext(s->url, "m4b"))
1634 av_log(s, AV_LOG_WARNING, "Warning, extension is not .m4a nor .m4v "
1635 "Quicktime/Ipod might not play the file\n");
1637 if (track->mode == MODE_MOV) {
1638 return mov_get_codec_tag(s, track);
1640 return validate_codec_tag(s->oformat->codec_tag, track->par->codec_tag,
1641 track->par->codec_id);
1644 /** Write uuid atom.
1645 * Needed to make file play in iPods running newest firmware
1646 * goes after avcC atom in moov.trak.mdia.minf.stbl.stsd.avc1
1648 static int mov_write_uuid_tag_ipod(AVIOContext *pb)
1651 ffio_wfourcc(pb, "uuid");
1652 avio_wb32(pb, 0x6b6840f2);
1653 avio_wb32(pb, 0x5f244fc5);
1654 avio_wb32(pb, 0xba39a51b);
1655 avio_wb32(pb, 0xcf0323f3);
1660 static const uint16_t fiel_data[] = {
1661 0x0000, 0x0100, 0x0201, 0x0206, 0x0209, 0x020e
1664 static int mov_write_fiel_tag(AVIOContext *pb, MOVTrack *track, int field_order)
1666 unsigned mov_field_order = 0;
1667 if (field_order < FF_ARRAY_ELEMS(fiel_data))
1668 mov_field_order = fiel_data[field_order];
1672 ffio_wfourcc(pb, "fiel");
1673 avio_wb16(pb, mov_field_order);
1677 static int mov_write_subtitle_tag(AVIOContext *pb, MOVTrack *track)
1679 int64_t pos = avio_tell(pb);
1680 avio_wb32(pb, 0); /* size */
1681 avio_wl32(pb, track->tag); // store it byteswapped
1682 avio_wb32(pb, 0); /* Reserved */
1683 avio_wb16(pb, 0); /* Reserved */
1684 avio_wb16(pb, 1); /* Data-reference index */
1686 if (track->par->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
1687 mov_write_esds_tag(pb, track);
1688 else if (track->par->extradata_size)
1689 avio_write(pb, track->par->extradata, track->par->extradata_size);
1691 return update_size(pb, pos);
1694 static int mov_write_st3d_tag(AVIOContext *pb, AVStereo3D *stereo_3d)
1698 if (stereo_3d->flags != 0) {
1699 av_log(pb, AV_LOG_WARNING, "Unsupported stereo_3d flags %x. st3d not written.\n", stereo_3d->flags);
1703 switch (stereo_3d->type) {
1704 case AV_STEREO3D_2D:
1707 case AV_STEREO3D_TOPBOTTOM:
1710 case AV_STEREO3D_SIDEBYSIDE:
1714 av_log(pb, AV_LOG_WARNING, "Unsupported stereo_3d type %s. st3d not written.\n", av_stereo3d_type_name(stereo_3d->type));
1717 avio_wb32(pb, 13); /* size */
1718 ffio_wfourcc(pb, "st3d");
1719 avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1720 avio_w8(pb, stereo_mode);
1724 static int mov_write_sv3d_tag(AVFormatContext *s, AVIOContext *pb, AVSphericalMapping *spherical_mapping)
1726 int64_t sv3d_pos, svhd_pos, proj_pos;
1727 const char* metadata_source = s->flags & AVFMT_FLAG_BITEXACT ? "Lavf" : LIBAVFORMAT_IDENT;
1729 if (spherical_mapping->projection != AV_SPHERICAL_EQUIRECTANGULAR &&
1730 spherical_mapping->projection != AV_SPHERICAL_EQUIRECTANGULAR_TILE &&
1731 spherical_mapping->projection != AV_SPHERICAL_CUBEMAP) {
1732 av_log(pb, AV_LOG_WARNING, "Unsupported projection %d. sv3d not written.\n", spherical_mapping->projection);
1736 sv3d_pos = avio_tell(pb);
1737 avio_wb32(pb, 0); /* size */
1738 ffio_wfourcc(pb, "sv3d");
1740 svhd_pos = avio_tell(pb);
1741 avio_wb32(pb, 0); /* size */
1742 ffio_wfourcc(pb, "svhd");
1743 avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1744 avio_put_str(pb, metadata_source);
1745 update_size(pb, svhd_pos);
1747 proj_pos = avio_tell(pb);
1748 avio_wb32(pb, 0); /* size */
1749 ffio_wfourcc(pb, "proj");
1751 avio_wb32(pb, 24); /* size */
1752 ffio_wfourcc(pb, "prhd");
1753 avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1754 avio_wb32(pb, spherical_mapping->yaw);
1755 avio_wb32(pb, spherical_mapping->pitch);
1756 avio_wb32(pb, spherical_mapping->roll);
1758 switch (spherical_mapping->projection) {
1759 case AV_SPHERICAL_EQUIRECTANGULAR:
1760 case AV_SPHERICAL_EQUIRECTANGULAR_TILE:
1761 avio_wb32(pb, 28); /* size */
1762 ffio_wfourcc(pb, "equi");
1763 avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1764 avio_wb32(pb, spherical_mapping->bound_top);
1765 avio_wb32(pb, spherical_mapping->bound_bottom);
1766 avio_wb32(pb, spherical_mapping->bound_left);
1767 avio_wb32(pb, spherical_mapping->bound_right);
1769 case AV_SPHERICAL_CUBEMAP:
1770 avio_wb32(pb, 20); /* size */
1771 ffio_wfourcc(pb, "cbmp");
1772 avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1773 avio_wb32(pb, 0); /* layout */
1774 avio_wb32(pb, spherical_mapping->padding); /* padding */
1777 update_size(pb, proj_pos);
1779 return update_size(pb, sv3d_pos);
1782 static int mov_write_clap_tag(AVIOContext *pb, MOVTrack *track)
1785 ffio_wfourcc(pb, "clap");
1786 avio_wb32(pb, track->par->width); /* apertureWidth_N */
1787 avio_wb32(pb, 1); /* apertureWidth_D (= 1) */
1788 avio_wb32(pb, track->height); /* apertureHeight_N */
1789 avio_wb32(pb, 1); /* apertureHeight_D (= 1) */
1790 avio_wb32(pb, 0); /* horizOff_N (= 0) */
1791 avio_wb32(pb, 1); /* horizOff_D (= 1) */
1792 avio_wb32(pb, 0); /* vertOff_N (= 0) */
1793 avio_wb32(pb, 1); /* vertOff_D (= 1) */
1797 static int mov_write_pasp_tag(AVIOContext *pb, MOVTrack *track)
1800 av_reduce(&sar.num, &sar.den, track->par->sample_aspect_ratio.num,
1801 track->par->sample_aspect_ratio.den, INT_MAX);
1804 ffio_wfourcc(pb, "pasp");
1805 avio_wb32(pb, sar.num);
1806 avio_wb32(pb, sar.den);
1810 static int mov_write_gama_tag(AVIOContext *pb, MOVTrack *track, double gamma)
1815 gamma = avpriv_get_gamma_from_trc(track->par->color_trc);
1817 av_log(pb, AV_LOG_DEBUG, "gamma value %g\n", gamma);
1820 gama = (uint32_t)lrint((double)(1<<16) * gamma);
1821 av_log(pb, AV_LOG_DEBUG, "writing gama value %"PRId32"\n", gama);
1823 av_assert0(track->mode == MODE_MOV);
1825 ffio_wfourcc(pb, "gama");
1826 avio_wb32(pb, gama);
1830 av_log(pb, AV_LOG_WARNING, "gamma value unknown, unable to write gama atom\n");
1835 static int mov_write_colr_tag(AVIOContext *pb, MOVTrack *track)
1837 // Ref (MOV): https://developer.apple.com/library/mac/technotes/tn2162/_index.html#//apple_ref/doc/uid/DTS40013070-CH1-TNTAG9
1838 // Ref (MP4): ISO/IEC 14496-12:2012
1840 if (track->par->color_primaries == AVCOL_PRI_UNSPECIFIED &&
1841 track->par->color_trc == AVCOL_TRC_UNSPECIFIED &&
1842 track->par->color_space == AVCOL_SPC_UNSPECIFIED) {
1843 if ((track->par->width >= 1920 && track->par->height >= 1080)
1844 || (track->par->width == 1280 && track->par->height == 720)) {
1845 av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming bt709\n");
1846 track->par->color_primaries = AVCOL_PRI_BT709;
1847 } else if (track->par->width == 720 && track->height == 576) {
1848 av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming bt470bg\n");
1849 track->par->color_primaries = AVCOL_PRI_BT470BG;
1850 } else if (track->par->width == 720 &&
1851 (track->height == 486 || track->height == 480)) {
1852 av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming smpte170\n");
1853 track->par->color_primaries = AVCOL_PRI_SMPTE170M;
1855 av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, unable to assume anything\n");
1857 switch (track->par->color_primaries) {
1858 case AVCOL_PRI_BT709:
1859 track->par->color_trc = AVCOL_TRC_BT709;
1860 track->par->color_space = AVCOL_SPC_BT709;
1862 case AVCOL_PRI_SMPTE170M:
1863 case AVCOL_PRI_BT470BG:
1864 track->par->color_trc = AVCOL_TRC_BT709;
1865 track->par->color_space = AVCOL_SPC_SMPTE170M;
1870 /* We should only ever be called by MOV or MP4. */
1871 av_assert0(track->mode == MODE_MOV || track->mode == MODE_MP4);
1873 avio_wb32(pb, 18 + (track->mode == MODE_MP4));
1874 ffio_wfourcc(pb, "colr");
1875 if (track->mode == MODE_MP4)
1876 ffio_wfourcc(pb, "nclx");
1878 ffio_wfourcc(pb, "nclc");
1879 switch (track->par->color_primaries) {
1880 case AVCOL_PRI_BT709: avio_wb16(pb, 1); break;
1881 case AVCOL_PRI_BT470BG: avio_wb16(pb, 5); break;
1882 case AVCOL_PRI_SMPTE170M:
1883 case AVCOL_PRI_SMPTE240M: avio_wb16(pb, 6); break;
1884 case AVCOL_PRI_BT2020: avio_wb16(pb, 9); break;
1885 case AVCOL_PRI_SMPTE431: avio_wb16(pb, 11); break;
1886 case AVCOL_PRI_SMPTE432: avio_wb16(pb, 12); break;
1887 default: avio_wb16(pb, 2);
1889 switch (track->par->color_trc) {
1890 case AVCOL_TRC_BT709: avio_wb16(pb, 1); break;
1891 case AVCOL_TRC_SMPTE170M: avio_wb16(pb, 1); break; // remapped
1892 case AVCOL_TRC_SMPTE240M: avio_wb16(pb, 7); break;
1893 case AVCOL_TRC_SMPTEST2084: avio_wb16(pb, 16); break;
1894 case AVCOL_TRC_SMPTE428: avio_wb16(pb, 17); break;
1895 case AVCOL_TRC_ARIB_STD_B67: avio_wb16(pb, 18); break;
1896 default: avio_wb16(pb, 2);
1898 switch (track->par->color_space) {
1899 case AVCOL_SPC_BT709: avio_wb16(pb, 1); break;
1900 case AVCOL_SPC_BT470BG:
1901 case AVCOL_SPC_SMPTE170M: avio_wb16(pb, 6); break;
1902 case AVCOL_SPC_SMPTE240M: avio_wb16(pb, 7); break;
1903 case AVCOL_SPC_BT2020_NCL: avio_wb16(pb, 9); break;
1904 default: avio_wb16(pb, 2);
1907 if (track->mode == MODE_MP4) {
1908 int full_range = track->par->color_range == AVCOL_RANGE_JPEG;
1909 avio_w8(pb, full_range << 7);
1916 static void find_compressor(char * compressor_name, int len, MOVTrack *track)
1918 AVDictionaryEntry *encoder;
1919 int xdcam_res = (track->par->width == 1280 && track->par->height == 720)
1920 || (track->par->width == 1440 && track->par->height == 1080)
1921 || (track->par->width == 1920 && track->par->height == 1080);
1923 if (track->mode == MODE_MOV &&
1924 (encoder = av_dict_get(track->st->metadata, "encoder", NULL, 0))) {
1925 av_strlcpy(compressor_name, encoder->value, 32);
1926 } else if (track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO && xdcam_res) {
1927 int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE;
1928 AVStream *st = track->st;
1929 int rate = defined_frame_rate(NULL, st);
1930 av_strlcatf(compressor_name, len, "XDCAM");
1931 if (track->par->format == AV_PIX_FMT_YUV422P) {
1932 av_strlcatf(compressor_name, len, " HD422");
1933 } else if(track->par->width == 1440) {
1934 av_strlcatf(compressor_name, len, " HD");
1936 av_strlcatf(compressor_name, len, " EX");
1938 av_strlcatf(compressor_name, len, " %d%c", track->par->height, interlaced ? 'i' : 'p');
1940 av_strlcatf(compressor_name, len, "%d", rate * (interlaced + 1));
1944 static int mov_write_video_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
1946 int64_t pos = avio_tell(pb);
1947 char compressor_name[32] = { 0 };
1950 int uncompressed_ycbcr = ((track->par->codec_id == AV_CODEC_ID_RAWVIDEO && track->par->format == AV_PIX_FMT_UYVY422)
1951 || (track->par->codec_id == AV_CODEC_ID_RAWVIDEO && track->par->format == AV_PIX_FMT_YUYV422)
1952 || track->par->codec_id == AV_CODEC_ID_V308
1953 || track->par->codec_id == AV_CODEC_ID_V408
1954 || track->par->codec_id == AV_CODEC_ID_V410
1955 || track->par->codec_id == AV_CODEC_ID_V210);
1957 avio_wb32(pb, 0); /* size */
1958 if (mov->encryption_scheme != MOV_ENC_NONE) {
1959 ffio_wfourcc(pb, "encv");
1961 avio_wl32(pb, track->tag); // store it byteswapped
1963 avio_wb32(pb, 0); /* Reserved */
1964 avio_wb16(pb, 0); /* Reserved */
1965 avio_wb16(pb, 1); /* Data-reference index */
1967 if (uncompressed_ycbcr) {
1968 avio_wb16(pb, 2); /* Codec stream version */
1970 avio_wb16(pb, 0); /* Codec stream version */
1972 avio_wb16(pb, 0); /* Codec stream revision (=0) */
1973 if (track->mode == MODE_MOV) {
1974 ffio_wfourcc(pb, "FFMP"); /* Vendor */
1975 if (track->par->codec_id == AV_CODEC_ID_RAWVIDEO || uncompressed_ycbcr) {
1976 avio_wb32(pb, 0); /* Temporal Quality */
1977 avio_wb32(pb, 0x400); /* Spatial Quality = lossless*/
1979 avio_wb32(pb, 0x200); /* Temporal Quality = normal */
1980 avio_wb32(pb, 0x200); /* Spatial Quality = normal */
1983 avio_wb32(pb, 0); /* Reserved */
1984 avio_wb32(pb, 0); /* Reserved */
1985 avio_wb32(pb, 0); /* Reserved */
1987 avio_wb16(pb, track->par->width); /* Video width */
1988 avio_wb16(pb, track->height); /* Video height */
1989 avio_wb32(pb, 0x00480000); /* Horizontal resolution 72dpi */
1990 avio_wb32(pb, 0x00480000); /* Vertical resolution 72dpi */
1991 avio_wb32(pb, 0); /* Data size (= 0) */
1992 avio_wb16(pb, 1); /* Frame count (= 1) */
1994 /* FIXME not sure, ISO 14496-1 draft where it shall be set to 0 */
1995 find_compressor(compressor_name, 32, track);
1996 avio_w8(pb, strlen(compressor_name));
1997 avio_write(pb, compressor_name, 31);
1999 if (track->mode == MODE_MOV &&
2000 (track->par->codec_id == AV_CODEC_ID_V410 || track->par->codec_id == AV_CODEC_ID_V210))
2001 avio_wb16(pb, 0x18);
2002 else if (track->mode == MODE_MOV && track->par->bits_per_coded_sample)
2003 avio_wb16(pb, track->par->bits_per_coded_sample |
2004 (track->par->format == AV_PIX_FMT_GRAY8 ? 0x20 : 0));
2006 avio_wb16(pb, 0x18); /* Reserved */
2008 if (track->mode == MODE_MOV && track->par->format == AV_PIX_FMT_PAL8) {
2009 int pal_size = 1 << track->par->bits_per_coded_sample;
2011 avio_wb16(pb, 0); /* Color table ID */
2012 avio_wb32(pb, 0); /* Color table seed */
2013 avio_wb16(pb, 0x8000); /* Color table flags */
2014 avio_wb16(pb, pal_size - 1); /* Color table size (zero-relative) */
2015 for (i = 0; i < pal_size; i++) {
2016 uint32_t rgb = track->palette[i];
2017 uint16_t r = (rgb >> 16) & 0xff;
2018 uint16_t g = (rgb >> 8) & 0xff;
2019 uint16_t b = rgb & 0xff;
2021 avio_wb16(pb, (r << 8) | r);
2022 avio_wb16(pb, (g << 8) | g);
2023 avio_wb16(pb, (b << 8) | b);
2026 avio_wb16(pb, 0xffff); /* Reserved */
2028 if (track->tag == MKTAG('m','p','4','v'))
2029 mov_write_esds_tag(pb, track);
2030 else if (track->par->codec_id == AV_CODEC_ID_H263)
2031 mov_write_d263_tag(pb);
2032 else if (track->par->codec_id == AV_CODEC_ID_AVUI ||
2033 track->par->codec_id == AV_CODEC_ID_SVQ3) {
2034 mov_write_extradata_tag(pb, track);
2036 } else if (track->par->codec_id == AV_CODEC_ID_DNXHD) {
2037 mov_write_avid_tag(pb, track);
2039 } else if (track->par->codec_id == AV_CODEC_ID_HEVC)
2040 mov_write_hvcc_tag(pb, track);
2041 else if (track->par->codec_id == AV_CODEC_ID_H264 && !TAG_IS_AVCI(track->tag)) {
2042 mov_write_avcc_tag(pb, track);
2043 if (track->mode == MODE_IPOD)
2044 mov_write_uuid_tag_ipod(pb);
2045 } else if (track->par->codec_id == AV_CODEC_ID_VP9) {
2046 mov_write_vpcc_tag(mov->fc, pb, track);
2047 } else if (track->par->codec_id == AV_CODEC_ID_AV1) {
2048 mov_write_av1c_tag(pb, track);
2049 } else if (track->par->codec_id == AV_CODEC_ID_VC1 && track->vos_len > 0)
2050 mov_write_dvc1_tag(pb, track);
2051 else if (track->par->codec_id == AV_CODEC_ID_VP6F ||
2052 track->par->codec_id == AV_CODEC_ID_VP6A) {
2053 /* Don't write any potential extradata here - the cropping
2054 * is signalled via the normal width/height fields. */
2055 } else if (track->par->codec_id == AV_CODEC_ID_R10K) {
2056 if (track->par->codec_tag == MKTAG('R','1','0','k'))
2057 mov_write_dpxe_tag(pb, track);
2058 } else if (track->vos_len > 0)
2059 mov_write_glbl_tag(pb, track);
2061 if (track->par->codec_id != AV_CODEC_ID_H264 &&
2062 track->par->codec_id != AV_CODEC_ID_MPEG4 &&
2063 track->par->codec_id != AV_CODEC_ID_DNXHD) {
2064 int field_order = track->par->field_order;
2066 #if FF_API_LAVF_AVCTX
2067 FF_DISABLE_DEPRECATION_WARNINGS
2068 if (field_order != track->st->codec->field_order && track->st->codec->field_order != AV_FIELD_UNKNOWN)
2069 field_order = track->st->codec->field_order;
2070 FF_ENABLE_DEPRECATION_WARNINGS
2073 if (field_order != AV_FIELD_UNKNOWN)
2074 mov_write_fiel_tag(pb, track, field_order);
2077 if (mov->flags & FF_MOV_FLAG_WRITE_GAMA) {
2078 if (track->mode == MODE_MOV)
2079 mov_write_gama_tag(pb, track, mov->gamma);
2081 av_log(mov->fc, AV_LOG_WARNING, "Not writing 'gama' atom. Format is not MOV.\n");
2083 if (mov->flags & FF_MOV_FLAG_WRITE_COLR) {
2084 if (track->mode == MODE_MOV || track->mode == MODE_MP4)
2085 mov_write_colr_tag(pb, track);
2087 av_log(mov->fc, AV_LOG_WARNING, "Not writing 'colr' atom. Format is not MOV or MP4.\n");
2090 if (track->mode == MODE_MP4 && mov->fc->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL) {
2091 AVStereo3D* stereo_3d = (AVStereo3D*) av_stream_get_side_data(track->st, AV_PKT_DATA_STEREO3D, NULL);
2092 AVSphericalMapping* spherical_mapping = (AVSphericalMapping*)av_stream_get_side_data(track->st, AV_PKT_DATA_SPHERICAL, NULL);
2095 mov_write_st3d_tag(pb, stereo_3d);
2096 if (spherical_mapping)
2097 mov_write_sv3d_tag(mov->fc, pb, spherical_mapping);
2100 if (track->par->sample_aspect_ratio.den && track->par->sample_aspect_ratio.num) {
2101 mov_write_pasp_tag(pb, track);
2104 if (uncompressed_ycbcr){
2105 mov_write_clap_tag(pb, track);
2108 if (mov->encryption_scheme != MOV_ENC_NONE) {
2109 ff_mov_cenc_write_sinf_tag(track, pb, mov->encryption_kid);
2112 /* extra padding for avid stsd */
2113 /* https://developer.apple.com/library/mac/documentation/QuickTime/QTFF/QTFFChap2/qtff2.html#//apple_ref/doc/uid/TP40000939-CH204-61112 */
2117 return update_size(pb, pos);
2120 static int mov_write_rtp_tag(AVIOContext *pb, MOVTrack *track)
2122 int64_t pos = avio_tell(pb);
2123 avio_wb32(pb, 0); /* size */
2124 ffio_wfourcc(pb, "rtp ");
2125 avio_wb32(pb, 0); /* Reserved */
2126 avio_wb16(pb, 0); /* Reserved */
2127 avio_wb16(pb, 1); /* Data-reference index */
2129 avio_wb16(pb, 1); /* Hint track version */
2130 avio_wb16(pb, 1); /* Highest compatible version */
2131 avio_wb32(pb, track->max_packet_size); /* Max packet size */
2133 avio_wb32(pb, 12); /* size */
2134 ffio_wfourcc(pb, "tims");
2135 avio_wb32(pb, track->timescale);
2137 return update_size(pb, pos);
2140 static int mov_write_source_reference_tag(AVIOContext *pb, MOVTrack *track, const char *reel_name)
2142 uint64_t str_size =strlen(reel_name);
2143 int64_t pos = avio_tell(pb);
2145 if (str_size >= UINT16_MAX){
2146 av_log(NULL, AV_LOG_ERROR, "reel_name length %"PRIu64" is too large\n", str_size);
2148 return AVERROR(EINVAL);
2151 avio_wb32(pb, 0); /* size */
2152 ffio_wfourcc(pb, "name"); /* Data format */
2153 avio_wb16(pb, str_size); /* string size */
2154 avio_wb16(pb, track->language); /* langcode */
2155 avio_write(pb, reel_name, str_size); /* reel name */
2156 return update_size(pb,pos);
2159 static int mov_write_tmcd_tag(AVIOContext *pb, MOVTrack *track)
2161 int64_t pos = avio_tell(pb);
2165 AVDictionaryEntry *t = NULL;
2167 if (!track->st->avg_frame_rate.num || !track->st->avg_frame_rate.den) {
2168 #if FF_API_LAVF_AVCTX
2169 FF_DISABLE_DEPRECATION_WARNINGS
2170 frame_duration = av_rescale(track->timescale, track->st->codec->time_base.num, track->st->codec->time_base.den);
2171 nb_frames = ROUNDED_DIV(track->st->codec->time_base.den, track->st->codec->time_base.num);
2172 FF_ENABLE_DEPRECATION_WARNINGS
2174 av_log(NULL, AV_LOG_ERROR, "avg_frame_rate not set for tmcd track.\n");
2175 return AVERROR(EINVAL);
2178 frame_duration = av_rescale(track->timescale, track->st->avg_frame_rate.num, track->st->avg_frame_rate.den);
2179 nb_frames = ROUNDED_DIV(track->st->avg_frame_rate.den, track->st->avg_frame_rate.num);
2182 if (nb_frames > 255) {
2183 av_log(NULL, AV_LOG_ERROR, "fps %d is too large\n", nb_frames);
2184 return AVERROR(EINVAL);
2187 avio_wb32(pb, 0); /* size */
2188 ffio_wfourcc(pb, "tmcd"); /* Data format */
2189 avio_wb32(pb, 0); /* Reserved */
2190 avio_wb32(pb, 1); /* Data reference index */
2191 avio_wb32(pb, 0); /* Flags */
2192 avio_wb32(pb, track->timecode_flags); /* Flags (timecode) */
2193 avio_wb32(pb, track->timescale); /* Timescale */
2194 avio_wb32(pb, frame_duration); /* Frame duration */
2195 avio_w8(pb, nb_frames); /* Number of frames */
2196 avio_w8(pb, 0); /* Reserved */
2198 t = av_dict_get(track->st->metadata, "reel_name", NULL, 0);
2199 if (t && utf8len(t->value) && track->mode != MODE_MP4)
2200 mov_write_source_reference_tag(pb, track, t->value);
2202 avio_wb16(pb, 0); /* zero size */
2205 avio_wb32(pb, 0); /* size */
2206 ffio_wfourcc(pb, "tmcd"); /* Data format */
2207 avio_wb32(pb, 0); /* Reserved */
2208 avio_wb32(pb, 1); /* Data reference index */
2209 if (track->par->extradata_size)
2210 avio_write(pb, track->par->extradata, track->par->extradata_size);
2212 return update_size(pb, pos);
2215 static int mov_write_gpmd_tag(AVIOContext *pb, const MOVTrack *track)
2217 int64_t pos = avio_tell(pb);
2218 avio_wb32(pb, 0); /* size */
2219 ffio_wfourcc(pb, "gpmd");
2220 avio_wb32(pb, 0); /* Reserved */
2221 avio_wb16(pb, 0); /* Reserved */
2222 avio_wb16(pb, 1); /* Data-reference index */
2223 avio_wb32(pb, 0); /* Reserved */
2224 return update_size(pb, pos);
2227 static int mov_write_stsd_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
2229 int64_t pos = avio_tell(pb);
2231 avio_wb32(pb, 0); /* size */
2232 ffio_wfourcc(pb, "stsd");
2233 avio_wb32(pb, 0); /* version & flags */
2234 avio_wb32(pb, 1); /* entry count */
2235 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO)
2236 ret = mov_write_video_tag(pb, mov, track);
2237 else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
2238 ret = mov_write_audio_tag(s, pb, mov, track);
2239 else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)
2240 ret = mov_write_subtitle_tag(pb, track);
2241 else if (track->par->codec_tag == MKTAG('r','t','p',' '))
2242 ret = mov_write_rtp_tag(pb, track);
2243 else if (track->par->codec_tag == MKTAG('t','m','c','d'))
2244 ret = mov_write_tmcd_tag(pb, track);
2245 else if (track->par->codec_tag == MKTAG('g','p','m','d'))
2246 ret = mov_write_gpmd_tag(pb, track);
2251 return update_size(pb, pos);
2254 static int mov_write_ctts_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
2256 MOVMuxContext *mov = s->priv_data;
2257 MOVStts *ctts_entries;
2258 uint32_t entries = 0;
2262 ctts_entries = av_malloc_array((track->entry + 1), sizeof(*ctts_entries)); /* worst case */
2264 return AVERROR(ENOMEM);
2265 ctts_entries[0].count = 1;
2266 ctts_entries[0].duration = track->cluster[0].cts;
2267 for (i = 1; i < track->entry; i++) {
2268 if (track->cluster[i].cts == ctts_entries[entries].duration) {
2269 ctts_entries[entries].count++; /* compress */
2272 ctts_entries[entries].duration = track->cluster[i].cts;
2273 ctts_entries[entries].count = 1;
2276 entries++; /* last one */
2277 atom_size = 16 + (entries * 8);
2278 avio_wb32(pb, atom_size); /* size */
2279 ffio_wfourcc(pb, "ctts");
2280 if (mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS)
2281 avio_w8(pb, 1); /* version */
2283 avio_w8(pb, 0); /* version */
2284 avio_wb24(pb, 0); /* flags */
2285 avio_wb32(pb, entries); /* entry count */
2286 for (i = 0; i < entries; i++) {
2287 avio_wb32(pb, ctts_entries[i].count);
2288 avio_wb32(pb, ctts_entries[i].duration);
2290 av_free(ctts_entries);
2294 /* Time to sample atom */
2295 static int mov_write_stts_tag(AVIOContext *pb, MOVTrack *track)
2297 MOVStts *stts_entries = NULL;
2298 uint32_t entries = -1;
2302 if (track->par->codec_type == AVMEDIA_TYPE_AUDIO && !track->audio_vbr) {
2303 stts_entries = av_malloc(sizeof(*stts_entries)); /* one entry */
2305 return AVERROR(ENOMEM);
2306 stts_entries[0].count = track->sample_count;
2307 stts_entries[0].duration = 1;
2311 stts_entries = av_malloc_array(track->entry, sizeof(*stts_entries)); /* worst case */
2313 return AVERROR(ENOMEM);
2315 for (i = 0; i < track->entry; i++) {
2316 int duration = get_cluster_duration(track, i);
2317 if (i && duration == stts_entries[entries].duration) {
2318 stts_entries[entries].count++; /* compress */
2321 stts_entries[entries].duration = duration;
2322 stts_entries[entries].count = 1;
2325 entries++; /* last one */
2327 atom_size = 16 + (entries * 8);
2328 avio_wb32(pb, atom_size); /* size */
2329 ffio_wfourcc(pb, "stts");
2330 avio_wb32(pb, 0); /* version & flags */
2331 avio_wb32(pb, entries); /* entry count */
2332 for (i = 0; i < entries; i++) {
2333 avio_wb32(pb, stts_entries[i].count);
2334 avio_wb32(pb, stts_entries[i].duration);
2336 av_free(stts_entries);
2340 static int mov_write_dref_tag(AVIOContext *pb)
2342 avio_wb32(pb, 28); /* size */
2343 ffio_wfourcc(pb, "dref");
2344 avio_wb32(pb, 0); /* version & flags */
2345 avio_wb32(pb, 1); /* entry count */
2347 avio_wb32(pb, 0xc); /* size */
2348 //FIXME add the alis and rsrc atom
2349 ffio_wfourcc(pb, "url ");
2350 avio_wb32(pb, 1); /* version & flags */
2355 static int mov_preroll_write_stbl_atoms(AVIOContext *pb, MOVTrack *track)
2359 int16_t roll_distance;
2360 int group_description_index;
2363 struct sgpd_entry *sgpd_entries = NULL;
2368 const int OPUS_SEEK_PREROLL_MS = 80;
2369 int roll_samples = av_rescale_q(OPUS_SEEK_PREROLL_MS,
2370 (AVRational){1, 1000},
2371 (AVRational){1, 48000});
2376 sgpd_entries = av_malloc_array(track->entry, sizeof(*sgpd_entries));
2378 return AVERROR(ENOMEM);
2380 av_assert0(track->par->codec_id == AV_CODEC_ID_OPUS || track->par->codec_id == AV_CODEC_ID_AAC);
2382 if (track->par->codec_id == AV_CODEC_ID_OPUS) {
2383 for (i = 0; i < track->entry; i++) {
2384 int roll_samples_remaining = roll_samples;
2386 for (j = i - 1; j >= 0; j--) {
2387 roll_samples_remaining -= get_cluster_duration(track, j);
2389 if (roll_samples_remaining <= 0)
2392 /* We don't have enough preceeding samples to compute a valid
2393 roll_distance here, so this sample can't be independently
2395 if (roll_samples_remaining > 0)
2397 /* Verify distance is a maximum of 32 (2.5ms) packets. */
2399 return AVERROR_INVALIDDATA;
2400 if (i && distance == sgpd_entries[entries].roll_distance) {
2401 sgpd_entries[entries].count++;
2404 sgpd_entries[entries].count = 1;
2405 sgpd_entries[entries].roll_distance = distance;
2406 sgpd_entries[entries].group_description_index = distance ? ++group : 0;
2411 sgpd_entries[entries].count = track->sample_count;
2412 sgpd_entries[entries].roll_distance = 1;
2413 sgpd_entries[entries].group_description_index = ++group;
2418 av_free(sgpd_entries);
2422 /* Write sgpd tag */
2423 avio_wb32(pb, 24 + (group * 2)); /* size */
2424 ffio_wfourcc(pb, "sgpd");
2425 avio_wb32(pb, 1 << 24); /* fullbox */
2426 ffio_wfourcc(pb, "roll");
2427 avio_wb32(pb, 2); /* default_length */
2428 avio_wb32(pb, group); /* entry_count */
2429 for (i = 0; i < entries; i++) {
2430 if (sgpd_entries[i].group_description_index) {
2431 avio_wb16(pb, -sgpd_entries[i].roll_distance); /* roll_distance */
2435 /* Write sbgp tag */
2436 avio_wb32(pb, 20 + (entries * 8)); /* size */
2437 ffio_wfourcc(pb, "sbgp");
2438 avio_wb32(pb, 0); /* fullbox */
2439 ffio_wfourcc(pb, "roll");
2440 avio_wb32(pb, entries); /* entry_count */
2441 for (i = 0; i < entries; i++) {
2442 avio_wb32(pb, sgpd_entries[i].count); /* sample_count */
2443 avio_wb32(pb, sgpd_entries[i].group_description_index); /* group_description_index */
2446 av_free(sgpd_entries);
2450 static int mov_write_stbl_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
2452 int64_t pos = avio_tell(pb);
2455 avio_wb32(pb, 0); /* size */
2456 ffio_wfourcc(pb, "stbl");
2457 if ((ret = mov_write_stsd_tag(s, pb, mov, track)) < 0)
2459 mov_write_stts_tag(pb, track);
2460 if ((track->par->codec_type == AVMEDIA_TYPE_VIDEO ||
2461 track->par->codec_tag == MKTAG('r','t','p',' ')) &&
2462 track->has_keyframes && track->has_keyframes < track->entry)
2463 mov_write_stss_tag(pb, track, MOV_SYNC_SAMPLE);
2464 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO && track->has_disposable)
2465 mov_write_sdtp_tag(pb, track);
2466 if (track->mode == MODE_MOV && track->flags & MOV_TRACK_STPS)
2467 mov_write_stss_tag(pb, track, MOV_PARTIAL_SYNC_SAMPLE);
2468 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO &&
2469 track->flags & MOV_TRACK_CTTS && track->entry) {
2471 if ((ret = mov_write_ctts_tag(s, pb, track)) < 0)
2474 mov_write_stsc_tag(pb, track);
2475 mov_write_stsz_tag(pb, track);
2476 mov_write_stco_tag(pb, track);
2477 if (track->cenc.aes_ctr) {
2478 ff_mov_cenc_write_stbl_atoms(&track->cenc, pb);
2480 if (track->par->codec_id == AV_CODEC_ID_OPUS || track->par->codec_id == AV_CODEC_ID_AAC) {
2481 mov_preroll_write_stbl_atoms(pb, track);
2483 return update_size(pb, pos);
2486 static int mov_write_dinf_tag(AVIOContext *pb)
2488 int64_t pos = avio_tell(pb);
2489 avio_wb32(pb, 0); /* size */
2490 ffio_wfourcc(pb, "dinf");
2491 mov_write_dref_tag(pb);
2492 return update_size(pb, pos);
2495 static int mov_write_nmhd_tag(AVIOContext *pb)
2498 ffio_wfourcc(pb, "nmhd");
2503 static int mov_write_tcmi_tag(AVIOContext *pb, MOVTrack *track)
2505 int64_t pos = avio_tell(pb);
2506 const char *font = "Lucida Grande";
2507 avio_wb32(pb, 0); /* size */
2508 ffio_wfourcc(pb, "tcmi"); /* timecode media information atom */
2509 avio_wb32(pb, 0); /* version & flags */
2510 avio_wb16(pb, 0); /* text font */
2511 avio_wb16(pb, 0); /* text face */
2512 avio_wb16(pb, 12); /* text size */
2513 avio_wb16(pb, 0); /* (unknown, not in the QT specs...) */
2514 avio_wb16(pb, 0x0000); /* text color (red) */
2515 avio_wb16(pb, 0x0000); /* text color (green) */
2516 avio_wb16(pb, 0x0000); /* text color (blue) */
2517 avio_wb16(pb, 0xffff); /* background color (red) */
2518 avio_wb16(pb, 0xffff); /* background color (green) */
2519 avio_wb16(pb, 0xffff); /* background color (blue) */
2520 avio_w8(pb, strlen(font)); /* font len (part of the pascal string) */
2521 avio_write(pb, font, strlen(font)); /* font name */
2522 return update_size(pb, pos);
2525 static int mov_write_gmhd_tag(AVIOContext *pb, MOVTrack *track)
2527 int64_t pos = avio_tell(pb);
2528 avio_wb32(pb, 0); /* size */
2529 ffio_wfourcc(pb, "gmhd");
2530 avio_wb32(pb, 0x18); /* gmin size */
2531 ffio_wfourcc(pb, "gmin");/* generic media info */
2532 avio_wb32(pb, 0); /* version & flags */
2533 avio_wb16(pb, 0x40); /* graphics mode = */
2534 avio_wb16(pb, 0x8000); /* opColor (r?) */
2535 avio_wb16(pb, 0x8000); /* opColor (g?) */
2536 avio_wb16(pb, 0x8000); /* opColor (b?) */
2537 avio_wb16(pb, 0); /* balance */
2538 avio_wb16(pb, 0); /* reserved */
2541 * This special text atom is required for
2542 * Apple Quicktime chapters. The contents
2543 * don't appear to be documented, so the
2544 * bytes are copied verbatim.
2546 if (track->tag != MKTAG('c','6','0','8')) {
2547 avio_wb32(pb, 0x2C); /* size */
2548 ffio_wfourcc(pb, "text");
2549 avio_wb16(pb, 0x01);
2550 avio_wb32(pb, 0x00);
2551 avio_wb32(pb, 0x00);
2552 avio_wb32(pb, 0x00);
2553 avio_wb32(pb, 0x01);
2554 avio_wb32(pb, 0x00);
2555 avio_wb32(pb, 0x00);
2556 avio_wb32(pb, 0x00);
2557 avio_wb32(pb, 0x00004000);
2558 avio_wb16(pb, 0x0000);
2561 if (track->par->codec_tag == MKTAG('t','m','c','d')) {
2562 int64_t tmcd_pos = avio_tell(pb);
2563 avio_wb32(pb, 0); /* size */
2564 ffio_wfourcc(pb, "tmcd");
2565 mov_write_tcmi_tag(pb, track);
2566 update_size(pb, tmcd_pos);
2567 } else if (track->par->codec_tag == MKTAG('g','p','m','d')) {
2568 int64_t gpmd_pos = avio_tell(pb);
2569 avio_wb32(pb, 0); /* size */
2570 ffio_wfourcc(pb, "gpmd");
2571 avio_wb32(pb, 0); /* version */
2572 update_size(pb, gpmd_pos);
2574 return update_size(pb, pos);
2577 static int mov_write_smhd_tag(AVIOContext *pb)
2579 avio_wb32(pb, 16); /* size */
2580 ffio_wfourcc(pb, "smhd");
2581 avio_wb32(pb, 0); /* version & flags */
2582 avio_wb16(pb, 0); /* reserved (balance, normally = 0) */
2583 avio_wb16(pb, 0); /* reserved */
2587 static int mov_write_vmhd_tag(AVIOContext *pb)
2589 avio_wb32(pb, 0x14); /* size (always 0x14) */
2590 ffio_wfourcc(pb, "vmhd");
2591 avio_wb32(pb, 0x01); /* version & flags */
2592 avio_wb64(pb, 0); /* reserved (graphics mode = copy) */
2596 static int is_clcp_track(MOVTrack *track)
2598 return track->tag == MKTAG('c','7','0','8') ||
2599 track->tag == MKTAG('c','6','0','8');
2602 static int mov_write_hdlr_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
2604 MOVMuxContext *mov = s->priv_data;
2605 const char *hdlr, *descr = NULL, *hdlr_type = NULL;
2606 int64_t pos = avio_tell(pb);
2610 descr = "DataHandler";
2613 hdlr = (track->mode == MODE_MOV) ? "mhlr" : "\0\0\0\0";
2614 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
2616 descr = "VideoHandler";
2617 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
2619 descr = "SoundHandler";
2620 } else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE) {
2621 if (is_clcp_track(track)) {
2623 descr = "ClosedCaptionHandler";
2625 if (track->tag == MKTAG('t','x','3','g')) {
2627 } else if (track->tag == MKTAG('m','p','4','s')) {
2632 descr = "SubtitleHandler";
2634 } else if (track->par->codec_tag == MKTAG('r','t','p',' ')) {
2636 descr = "HintHandler";
2637 } else if (track->par->codec_tag == MKTAG('t','m','c','d')) {
2639 descr = "TimeCodeHandler";
2640 } else if (track->par->codec_tag == MKTAG('g','p','m','d')) {
2642 descr = "GoPro MET"; // GoPro Metadata
2644 av_log(s, AV_LOG_WARNING,
2645 "Unknown hldr_type for %s, writing dummy values\n",
2646 av_fourcc2str(track->par->codec_tag));
2649 // hdlr.name is used by some players to identify the content title
2650 // of the track. So if an alternate handler description is
2651 // specified, use it.
2652 AVDictionaryEntry *t;
2653 t = av_dict_get(track->st->metadata, "handler_name", NULL, 0);
2654 if (t && utf8len(t->value))
2659 if (mov->empty_hdlr_name) /* expressly allowed by QTFF and not prohibited in ISO 14496-12 8.4.3.3 */
2662 avio_wb32(pb, 0); /* size */
2663 ffio_wfourcc(pb, "hdlr");
2664 avio_wb32(pb, 0); /* Version & flags */
2665 avio_write(pb, hdlr, 4); /* handler */
2666 ffio_wfourcc(pb, hdlr_type); /* handler type */
2667 avio_wb32(pb, 0); /* reserved */
2668 avio_wb32(pb, 0); /* reserved */
2669 avio_wb32(pb, 0); /* reserved */
2670 if (!track || track->mode == MODE_MOV)
2671 avio_w8(pb, strlen(descr)); /* pascal string */
2672 avio_write(pb, descr, strlen(descr)); /* handler description */
2673 if (track && track->mode != MODE_MOV)
2674 avio_w8(pb, 0); /* c string */
2675 return update_size(pb, pos);
2678 static int mov_write_hmhd_tag(AVIOContext *pb)
2680 /* This atom must be present, but leaving the values at zero
2681 * seems harmless. */
2682 avio_wb32(pb, 28); /* size */
2683 ffio_wfourcc(pb, "hmhd");
2684 avio_wb32(pb, 0); /* version, flags */
2685 avio_wb16(pb, 0); /* maxPDUsize */
2686 avio_wb16(pb, 0); /* avgPDUsize */
2687 avio_wb32(pb, 0); /* maxbitrate */
2688 avio_wb32(pb, 0); /* avgbitrate */
2689 avio_wb32(pb, 0); /* reserved */
2693 static int mov_write_minf_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
2695 int64_t pos = avio_tell(pb);
2698 avio_wb32(pb, 0); /* size */
2699 ffio_wfourcc(pb, "minf");
2700 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO)
2701 mov_write_vmhd_tag(pb);
2702 else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
2703 mov_write_smhd_tag(pb);
2704 else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE) {
2705 if (track->tag == MKTAG('t','e','x','t') || is_clcp_track(track)) {
2706 mov_write_gmhd_tag(pb, track);
2708 mov_write_nmhd_tag(pb);
2710 } else if (track->tag == MKTAG('r','t','p',' ')) {
2711 mov_write_hmhd_tag(pb);
2712 } else if (track->tag == MKTAG('t','m','c','d')) {
2713 if (track->mode != MODE_MOV)
2714 mov_write_nmhd_tag(pb);
2716 mov_write_gmhd_tag(pb, track);
2717 } else if (track->tag == MKTAG('g','p','m','d')) {
2718 mov_write_gmhd_tag(pb, track);
2720 if (track->mode == MODE_MOV) /* ISO 14496-12 8.4.3.1 specifies hdlr only within mdia or meta boxes */
2721 mov_write_hdlr_tag(s, pb, NULL);
2722 mov_write_dinf_tag(pb);
2723 if ((ret = mov_write_stbl_tag(s, pb, mov, track)) < 0)
2725 return update_size(pb, pos);
2728 static int mov_write_mdhd_tag(AVIOContext *pb, MOVMuxContext *mov,
2731 int version = track->track_duration < INT32_MAX ? 0 : 1;
2733 if (track->mode == MODE_ISM)
2736 (version == 1) ? avio_wb32(pb, 44) : avio_wb32(pb, 32); /* size */
2737 ffio_wfourcc(pb, "mdhd");
2738 avio_w8(pb, version);
2739 avio_wb24(pb, 0); /* flags */
2741 avio_wb64(pb, track->time);
2742 avio_wb64(pb, track->time);
2744 avio_wb32(pb, track->time); /* creation time */
2745 avio_wb32(pb, track->time); /* modification time */
2747 avio_wb32(pb, track->timescale); /* time scale (sample rate for audio) */
2748 if (!track->entry && mov->mode == MODE_ISM)
2749 (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
2750 else if (!track->entry)
2751 (version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0);
2753 (version == 1) ? avio_wb64(pb, track->track_duration) : avio_wb32(pb, track->track_duration); /* duration */
2754 avio_wb16(pb, track->language); /* language */
2755 avio_wb16(pb, 0); /* reserved (quality) */
2757 if (version != 0 && track->mode == MODE_MOV) {
2758 av_log(NULL, AV_LOG_ERROR,
2759 "FATAL error, file duration too long for timebase, this file will not be\n"
2760 "playable with QuickTime. Choose a different timebase with "
2761 "-video_track_timescale or a different container format\n");
2767 static int mov_write_mdia_tag(AVFormatContext *s, AVIOContext *pb,
2768 MOVMuxContext *mov, MOVTrack *track)
2770 int64_t pos = avio_tell(pb);
2773 avio_wb32(pb, 0); /* size */
2774 ffio_wfourcc(pb, "mdia");
2775 mov_write_mdhd_tag(pb, mov, track);
2776 mov_write_hdlr_tag(s, pb, track);
2777 if ((ret = mov_write_minf_tag(s, pb, mov, track)) < 0)
2779 return update_size(pb, pos);
2782 /* transformation matrix
2786 static void write_matrix(AVIOContext *pb, int16_t a, int16_t b, int16_t c,
2787 int16_t d, int16_t tx, int16_t ty)
2789 avio_wb32(pb, a << 16); /* 16.16 format */
2790 avio_wb32(pb, b << 16); /* 16.16 format */
2791 avio_wb32(pb, 0); /* u in 2.30 format */
2792 avio_wb32(pb, c << 16); /* 16.16 format */
2793 avio_wb32(pb, d << 16); /* 16.16 format */
2794 avio_wb32(pb, 0); /* v in 2.30 format */
2795 avio_wb32(pb, tx << 16); /* 16.16 format */
2796 avio_wb32(pb, ty << 16); /* 16.16 format */
2797 avio_wb32(pb, 1 << 30); /* w in 2.30 format */
2800 static int mov_write_tkhd_tag(AVIOContext *pb, MOVMuxContext *mov,
2801 MOVTrack *track, AVStream *st)
2803 int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE,
2804 track->timescale, AV_ROUND_UP);
2805 int version = duration < INT32_MAX ? 0 : 1;
2806 int flags = MOV_TKHD_FLAG_IN_MOVIE;
2810 uint32_t *display_matrix = NULL;
2811 int display_matrix_size, i;
2814 if (mov->per_stream_grouping)
2817 group = st->codecpar->codec_type;
2819 display_matrix = (uint32_t*)av_stream_get_side_data(st, AV_PKT_DATA_DISPLAYMATRIX,
2820 &display_matrix_size);
2821 if (display_matrix && display_matrix_size < 9 * sizeof(*display_matrix))
2822 display_matrix = NULL;
2825 if (track->flags & MOV_TRACK_ENABLED)
2826 flags |= MOV_TKHD_FLAG_ENABLED;
2828 if (track->mode == MODE_ISM)
2831 (version == 1) ? avio_wb32(pb, 104) : avio_wb32(pb, 92); /* size */
2832 ffio_wfourcc(pb, "tkhd");
2833 avio_w8(pb, version);
2834 avio_wb24(pb, flags);
2836 avio_wb64(pb, track->time);
2837 avio_wb64(pb, track->time);
2839 avio_wb32(pb, track->time); /* creation time */
2840 avio_wb32(pb, track->time); /* modification time */
2842 avio_wb32(pb, track->track_id); /* track-id */
2843 avio_wb32(pb, 0); /* reserved */
2844 if (!track->entry && mov->mode == MODE_ISM)
2845 (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
2846 else if (!track->entry)
2847 (version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0);
2849 (version == 1) ? avio_wb64(pb, duration) : avio_wb32(pb, duration);
2851 avio_wb32(pb, 0); /* reserved */
2852 avio_wb32(pb, 0); /* reserved */
2853 avio_wb16(pb, 0); /* layer */
2854 avio_wb16(pb, group); /* alternate group) */
2855 /* Volume, only for audio */
2856 if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
2857 avio_wb16(pb, 0x0100);
2860 avio_wb16(pb, 0); /* reserved */
2862 /* Matrix structure */
2863 #if FF_API_OLD_ROTATE_API
2864 if (st && st->metadata) {
2865 AVDictionaryEntry *rot = av_dict_get(st->metadata, "rotate", NULL, 0);
2866 rotation = (rot && rot->value) ? atoi(rot->value) : 0;
2869 if (display_matrix) {
2870 for (i = 0; i < 9; i++)
2871 avio_wb32(pb, display_matrix[i]);
2872 #if FF_API_OLD_ROTATE_API
2873 } else if (rotation == 90) {
2874 write_matrix(pb, 0, 1, -1, 0, track->par->height, 0);
2875 } else if (rotation == 180) {
2876 write_matrix(pb, -1, 0, 0, -1, track->par->width, track->par->height);
2877 } else if (rotation == 270) {
2878 write_matrix(pb, 0, -1, 1, 0, 0, track->par->width);
2881 write_matrix(pb, 1, 0, 0, 1, 0, 0);
2883 /* Track width and height, for visual only */
2884 if (st && (track->par->codec_type == AVMEDIA_TYPE_VIDEO ||
2885 track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)) {
2886 int64_t track_width_1616;
2887 if (track->mode == MODE_MOV) {
2888 track_width_1616 = track->par->width * 0x10000ULL;
2890 track_width_1616 = av_rescale(st->sample_aspect_ratio.num,
2891 track->par->width * 0x10000LL,
2892 st->sample_aspect_ratio.den);
2893 if (!track_width_1616 ||
2894 track->height != track->par->height ||
2895 track_width_1616 > UINT32_MAX)
2896 track_width_1616 = track->par->width * 0x10000ULL;
2898 if (track_width_1616 > UINT32_MAX) {
2899 av_log(mov->fc, AV_LOG_WARNING, "track width is too large\n");
2900 track_width_1616 = 0;
2902 avio_wb32(pb, track_width_1616);
2903 if (track->height > 0xFFFF) {
2904 av_log(mov->fc, AV_LOG_WARNING, "track height is too large\n");
2907 avio_wb32(pb, track->height * 0x10000U);
2915 static int mov_write_tapt_tag(AVIOContext *pb, MOVTrack *track)
2917 int32_t width = av_rescale(track->par->sample_aspect_ratio.num, track->par->width,
2918 track->par->sample_aspect_ratio.den);
2920 int64_t pos = avio_tell(pb);
2922 avio_wb32(pb, 0); /* size */
2923 ffio_wfourcc(pb, "tapt");
2926 ffio_wfourcc(pb, "clef");
2928 avio_wb32(pb, width << 16);
2929 avio_wb32(pb, track->par->height << 16);
2932 ffio_wfourcc(pb, "prof");
2934 avio_wb32(pb, width << 16);
2935 avio_wb32(pb, track->par->height << 16);
2938 ffio_wfourcc(pb, "enof");
2940 avio_wb32(pb, track->par->width << 16);
2941 avio_wb32(pb, track->par->height << 16);
2943 return update_size(pb, pos);
2946 // This box seems important for the psp playback ... without it the movie seems to hang
2947 static int mov_write_edts_tag(AVIOContext *pb, MOVMuxContext *mov,
2950 int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE,
2951 track->timescale, AV_ROUND_UP);
2952 int version = duration < INT32_MAX ? 0 : 1;
2953 int entry_size, entry_count, size;
2954 int64_t delay, start_ct = track->start_cts;
2955 int64_t start_dts = track->start_dts;
2958 if (start_dts != track->cluster[0].dts || start_ct != track->cluster[0].cts) {
2960 av_log(mov->fc, AV_LOG_DEBUG,
2961 "EDTS using dts:%"PRId64" cts:%d instead of dts:%"PRId64" cts:%"PRId64" tid:%d\n",
2962 track->cluster[0].dts, track->cluster[0].cts,
2963 start_dts, start_ct, track->track_id);
2964 start_dts = track->cluster[0].dts;
2965 start_ct = track->cluster[0].cts;
2969 delay = av_rescale_rnd(start_dts + start_ct, MOV_TIMESCALE,
2970 track->timescale, AV_ROUND_DOWN);
2971 version |= delay < INT32_MAX ? 0 : 1;
2973 entry_size = (version == 1) ? 20 : 12;
2974 entry_count = 1 + (delay > 0);
2975 size = 24 + entry_count * entry_size;
2977 /* write the atom data */
2978 avio_wb32(pb, size);
2979 ffio_wfourcc(pb, "edts");
2980 avio_wb32(pb, size - 8);
2981 ffio_wfourcc(pb, "elst");
2982 avio_w8(pb, version);
2983 avio_wb24(pb, 0); /* flags */
2985 avio_wb32(pb, entry_count);
2986 if (delay > 0) { /* add an empty edit to delay presentation */
2987 /* In the positive delay case, the delay includes the cts
2988 * offset, and the second edit list entry below trims out
2989 * the same amount from the actual content. This makes sure
2990 * that the offset last sample is included in the edit
2991 * list duration as well. */
2993 avio_wb64(pb, delay);
2996 avio_wb32(pb, delay);
2999 avio_wb32(pb, 0x00010000);
3001 /* Avoid accidentally ending up with start_ct = -1 which has got a
3002 * special meaning. Normally start_ct should end up positive or zero
3003 * here, but use FFMIN in case dts is a small positive integer
3004 * rounded to 0 when represented in MOV_TIMESCALE units. */
3005 av_assert0(av_rescale_rnd(start_dts, MOV_TIMESCALE, track->timescale, AV_ROUND_DOWN) <= 0);
3006 start_ct = -FFMIN(start_dts, 0);
3007 /* Note, this delay is calculated from the pts of the first sample,
3008 * ensuring that we don't reduce the duration for cases with
3013 /* For fragmented files, we don't know the full length yet. Setting
3014 * duration to 0 allows us to only specify the offset, including
3015 * the rest of the content (from all future fragments) without specifying
3016 * an explicit duration. */
3017 if (mov->flags & FF_MOV_FLAG_FRAGMENT)
3022 avio_wb64(pb, duration);
3023 avio_wb64(pb, start_ct);
3025 avio_wb32(pb, duration);
3026 avio_wb32(pb, start_ct);
3028 avio_wb32(pb, 0x00010000);
3032 static int mov_write_tref_tag(AVIOContext *pb, MOVTrack *track)
3034 avio_wb32(pb, 20); // size
3035 ffio_wfourcc(pb, "tref");
3036 avio_wb32(pb, 12); // size (subatom)
3037 avio_wl32(pb, track->tref_tag);
3038 avio_wb32(pb, track->tref_id);
3042 // goes at the end of each track! ... Critical for PSP playback ("Incompatible data" without it)
3043 static int mov_write_uuid_tag_psp(AVIOContext *pb, MOVTrack *mov)
3045 avio_wb32(pb, 0x34); /* size ... reports as 28 in mp4box! */
3046 ffio_wfourcc(pb, "uuid");
3047 ffio_wfourcc(pb, "USMT");
3048 avio_wb32(pb, 0x21d24fce);
3049 avio_wb32(pb, 0xbb88695c);
3050 avio_wb32(pb, 0xfac9c740);
3051 avio_wb32(pb, 0x1c); // another size here!
3052 ffio_wfourcc(pb, "MTDT");
3053 avio_wb32(pb, 0x00010012);
3054 avio_wb32(pb, 0x0a);
3055 avio_wb32(pb, 0x55c40000);
3061 static int mov_write_udta_sdp(AVIOContext *pb, MOVTrack *track)
3063 AVFormatContext *ctx = track->rtp_ctx;
3064 char buf[1000] = "";
3067 ff_sdp_write_media(buf, sizeof(buf), ctx->streams[0], track->src_track,
3068 NULL, NULL, 0, 0, ctx);
3069 av_strlcatf(buf, sizeof(buf), "a=control:streamid=%d\r\n", track->track_id);
3072 avio_wb32(pb, len + 24);
3073 ffio_wfourcc(pb, "udta");
3074 avio_wb32(pb, len + 16);
3075 ffio_wfourcc(pb, "hnti");
3076 avio_wb32(pb, len + 8);
3077 ffio_wfourcc(pb, "sdp ");
3078 avio_write(pb, buf, len);
3082 static int mov_write_track_metadata(AVIOContext *pb, AVStream *st,
3083 const char *tag, const char *str)
3085 int64_t pos = avio_tell(pb);
3086 AVDictionaryEntry *t = av_dict_get(st->metadata, str, NULL, 0);
3087 if (!t || !utf8len(t->value))
3090 avio_wb32(pb, 0); /* size */
3091 ffio_wfourcc(pb, tag); /* type */
3092 avio_write(pb, t->value, strlen(t->value)); /* UTF8 string value */
3093 return update_size(pb, pos);
3096 static int mov_write_track_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
3099 AVIOContext *pb_buf;
3106 ret = avio_open_dyn_buf(&pb_buf);
3110 if (mov->mode & (MODE_MP4|MODE_MOV))
3111 mov_write_track_metadata(pb_buf, st, "name", "title");
3113 if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) {
3114 avio_wb32(pb, size + 8);
3115 ffio_wfourcc(pb, "udta");
3116 avio_write(pb, buf, size);
3123 static int mov_write_trak_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov,
3124 MOVTrack *track, AVStream *st)
3126 int64_t pos = avio_tell(pb);
3127 int entry_backup = track->entry;
3128 int chunk_backup = track->chunkCount;
3131 /* If we want to have an empty moov, but some samples already have been
3132 * buffered (delay_moov), pretend that no samples have been written yet. */
3133 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV)
3134 track->chunkCount = track->entry = 0;
3136 avio_wb32(pb, 0); /* size */
3137 ffio_wfourcc(pb, "trak");
3138 mov_write_tkhd_tag(pb, mov, track, st);
3140 av_assert2(mov->use_editlist >= 0);
3142 if (track->start_dts != AV_NOPTS_VALUE) {
3143 if (mov->use_editlist)
3144 mov_write_edts_tag(pb, mov, track); // PSP Movies and several other cases require edts box
3145 else if ((track->entry && track->cluster[0].dts) || track->mode == MODE_PSP || is_clcp_track(track))
3146 av_log(mov->fc, AV_LOG_WARNING,
3147 "Not writing any edit list even though one would have been required\n");
3150 if (track->tref_tag)
3151 mov_write_tref_tag(pb, track);
3153 if ((ret = mov_write_mdia_tag(s, pb, mov, track)) < 0)
3155 if (track->mode == MODE_PSP)
3156 mov_write_uuid_tag_psp(pb, track); // PSP Movies require this uuid box
3157 if (track->tag == MKTAG('r','t','p',' '))
3158 mov_write_udta_sdp(pb, track);
3159 if (track->mode == MODE_MOV) {
3160 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
3161 double sample_aspect_ratio = av_q2d(st->sample_aspect_ratio);
3162 if (st->sample_aspect_ratio.num && 1.0 != sample_aspect_ratio) {
3163 mov_write_tapt_tag(pb, track);
3166 if (is_clcp_track(track) && st->sample_aspect_ratio.num) {
3167 mov_write_tapt_tag(pb, track);
3170 mov_write_track_udta_tag(pb, mov, st);
3171 track->entry = entry_backup;
3172 track->chunkCount = chunk_backup;
3173 return update_size(pb, pos);
3176 static int mov_write_iods_tag(AVIOContext *pb, MOVMuxContext *mov)
3178 int i, has_audio = 0, has_video = 0;
3179 int64_t pos = avio_tell(pb);
3180 int audio_profile = mov->iods_audio_profile;
3181 int video_profile = mov->iods_video_profile;
3182 for (i = 0; i < mov->nb_streams; i++) {
3183 if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
3184 has_audio |= mov->tracks[i].par->codec_type == AVMEDIA_TYPE_AUDIO;
3185 has_video |= mov->tracks[i].par->codec_type == AVMEDIA_TYPE_VIDEO;
3188 if (audio_profile < 0)
3189 audio_profile = 0xFF - has_audio;
3190 if (video_profile < 0)
3191 video_profile = 0xFF - has_video;
3192 avio_wb32(pb, 0x0); /* size */
3193 ffio_wfourcc(pb, "iods");
3194 avio_wb32(pb, 0); /* version & flags */
3195 put_descr(pb, 0x10, 7);
3196 avio_wb16(pb, 0x004f);
3199 avio_w8(pb, audio_profile);
3200 avio_w8(pb, video_profile);
3202 return update_size(pb, pos);
3205 static int mov_write_trex_tag(AVIOContext *pb, MOVTrack *track)
3207 avio_wb32(pb, 0x20); /* size */
3208 ffio_wfourcc(pb, "trex");
3209 avio_wb32(pb, 0); /* version & flags */
3210 avio_wb32(pb, track->track_id); /* track ID */
3211 avio_wb32(pb, 1); /* default sample description index */
3212 avio_wb32(pb, 0); /* default sample duration */
3213 avio_wb32(pb, 0); /* default sample size */
3214 avio_wb32(pb, 0); /* default sample flags */
3218 static int mov_write_mvex_tag(AVIOContext *pb, MOVMuxContext *mov)
3220 int64_t pos = avio_tell(pb);
3222 avio_wb32(pb, 0x0); /* size */
3223 ffio_wfourcc(pb, "mvex");
3224 for (i = 0; i < mov->nb_streams; i++)
3225 mov_write_trex_tag(pb, &mov->tracks[i]);
3226 return update_size(pb, pos);
3229 static int mov_write_mvhd_tag(AVIOContext *pb, MOVMuxContext *mov)
3231 int max_track_id = 1, i;
3232 int64_t max_track_len = 0;
3235 for (i = 0; i < mov->nb_streams; i++) {
3236 if (mov->tracks[i].entry > 0 && mov->tracks[i].timescale) {
3237 int64_t max_track_len_temp = av_rescale_rnd(mov->tracks[i].track_duration,
3239 mov->tracks[i].timescale,
3241 if (max_track_len < max_track_len_temp)
3242 max_track_len = max_track_len_temp;
3243 if (max_track_id < mov->tracks[i].track_id)
3244 max_track_id = mov->tracks[i].track_id;
3247 /* If using delay_moov, make sure the output is the same as if no
3248 * samples had been written yet. */
3249 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
3254 version = max_track_len < UINT32_MAX ? 0 : 1;
3255 avio_wb32(pb, version == 1 ? 120 : 108); /* size */
3257 ffio_wfourcc(pb, "mvhd");
3258 avio_w8(pb, version);
3259 avio_wb24(pb, 0); /* flags */
3261 avio_wb64(pb, mov->time);
3262 avio_wb64(pb, mov->time);
3264 avio_wb32(pb, mov->time); /* creation time */
3265 avio_wb32(pb, mov->time); /* modification time */
3267 avio_wb32(pb, MOV_TIMESCALE);
3268 (version == 1) ? avio_wb64(pb, max_track_len) : avio_wb32(pb, max_track_len); /* duration of longest track */
3270 avio_wb32(pb, 0x00010000); /* reserved (preferred rate) 1.0 = normal */
3271 avio_wb16(pb, 0x0100); /* reserved (preferred volume) 1.0 = normal */
3272 avio_wb16(pb, 0); /* reserved */
3273 avio_wb32(pb, 0); /* reserved */
3274 avio_wb32(pb, 0); /* reserved */
3276 /* Matrix structure */
3277 write_matrix(pb, 1, 0, 0, 1, 0, 0);
3279 avio_wb32(pb, 0); /* reserved (preview time) */
3280 avio_wb32(pb, 0); /* reserved (preview duration) */
3281 avio_wb32(pb, 0); /* reserved (poster time) */
3282 avio_wb32(pb, 0); /* reserved (selection time) */
3283 avio_wb32(pb, 0); /* reserved (selection duration) */
3284 avio_wb32(pb, 0); /* reserved (current time) */
3285 avio_wb32(pb, max_track_id + 1); /* Next track id */
3289 static int mov_write_itunes_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov,
3292 avio_wb32(pb, 33); /* size */
3293 ffio_wfourcc(pb, "hdlr");
3296 ffio_wfourcc(pb, "mdir");
3297 ffio_wfourcc(pb, "appl");
3304 /* helper function to write a data tag with the specified string as data */
3305 static int mov_write_string_data_tag(AVIOContext *pb, const char *data, int lang, int long_style)
3308 int size = 16 + strlen(data);
3309 avio_wb32(pb, size); /* size */
3310 ffio_wfourcc(pb, "data");
3313 avio_write(pb, data, strlen(data));
3317 lang = ff_mov_iso639_to_lang("und", 1);
3318 avio_wb16(pb, strlen(data)); /* string length */
3319 avio_wb16(pb, lang);
3320 avio_write(pb, data, strlen(data));
3321 return strlen(data) + 4;
3325 static int mov_write_string_tag(AVIOContext *pb, const char *name,
3326 const char *value, int lang, int long_style)
3329 if (value && value[0]) {
3330 int64_t pos = avio_tell(pb);
3331 avio_wb32(pb, 0); /* size */
3332 ffio_wfourcc(pb, name);
3333 mov_write_string_data_tag(pb, value, lang, long_style);
3334 size = update_size(pb, pos);
3339 static AVDictionaryEntry *get_metadata_lang(AVFormatContext *s,
3340 const char *tag, int *lang)
3343 AVDictionaryEntry *t, *t2 = NULL;
3348 if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
3351 len = strlen(t->key);
3352 snprintf(tag2, sizeof(tag2), "%s-", tag);
3353 while ((t2 = av_dict_get(s->metadata, tag2, t2, AV_DICT_IGNORE_SUFFIX))) {
3354 len2 = strlen(t2->key);
3355 if (len2 == len + 4 && !strcmp(t->value, t2->value)
3356 && (l = ff_mov_iso639_to_lang(&t2->key[len2 - 3], 1)) >= 0) {
3364 static int mov_write_string_metadata(AVFormatContext *s, AVIOContext *pb,
3365 const char *name, const char *tag,
3369 AVDictionaryEntry *t = get_metadata_lang(s, tag, &lang);
3372 return mov_write_string_tag(pb, name, t->value, lang, long_style);
3375 /* iTunes bpm number */
3376 static int mov_write_tmpo_tag(AVIOContext *pb, AVFormatContext *s)
3378 AVDictionaryEntry *t = av_dict_get(s->metadata, "tmpo", NULL, 0);
3379 int size = 0, tmpo = t ? atoi(t->value) : 0;
3382 avio_wb32(pb, size);
3383 ffio_wfourcc(pb, "tmpo");
3384 avio_wb32(pb, size-8); /* size */
3385 ffio_wfourcc(pb, "data");
3386 avio_wb32(pb, 0x15); //type specifier
3388 avio_wb16(pb, tmpo); // data
3393 /* 3GPP TS 26.244 */
3394 static int mov_write_loci_tag(AVFormatContext *s, AVIOContext *pb)
3397 int64_t pos = avio_tell(pb);
3398 double latitude, longitude, altitude;
3399 int32_t latitude_fix, longitude_fix, altitude_fix;
3400 AVDictionaryEntry *t = get_metadata_lang(s, "location", &lang);
3401 const char *ptr, *place = "";
3403 static const char *astronomical_body = "earth";
3408 longitude = strtod(ptr, &end);
3410 av_log(s, AV_LOG_WARNING, "malformed location metadata\n");
3414 latitude = strtod(ptr, &end);
3416 av_log(s, AV_LOG_WARNING, "malformed location metadata\n");
3420 altitude = strtod(ptr, &end);
3421 /* If no altitude was present, the default 0 should be fine */
3425 latitude_fix = (int32_t) ((1 << 16) * latitude);
3426 longitude_fix = (int32_t) ((1 << 16) * longitude);
3427 altitude_fix = (int32_t) ((1 << 16) * altitude);
3429 avio_wb32(pb, 0); /* size */
3430 ffio_wfourcc(pb, "loci"); /* type */
3431 avio_wb32(pb, 0); /* version + flags */
3432 avio_wb16(pb, lang);
3433 avio_write(pb, place, strlen(place) + 1);
3434 avio_w8(pb, 0); /* role of place (0 == shooting location, 1 == real location, 2 == fictional location) */
3435 avio_wb32(pb, latitude_fix);
3436 avio_wb32(pb, longitude_fix);
3437 avio_wb32(pb, altitude_fix);
3438 avio_write(pb, astronomical_body, strlen(astronomical_body) + 1);
3439 avio_w8(pb, 0); /* additional notes, null terminated string */
3441 return update_size(pb, pos);
3444 /* iTunes track or disc number */
3445 static int mov_write_trkn_tag(AVIOContext *pb, MOVMuxContext *mov,
3446 AVFormatContext *s, int disc)
3448 AVDictionaryEntry *t = av_dict_get(s->metadata,
3449 disc ? "disc" : "track",
3451 int size = 0, track = t ? atoi(t->value) : 0;
3454 char *slash = strchr(t->value, '/');
3456 tracks = atoi(slash + 1);
3457 avio_wb32(pb, 32); /* size */
3458 ffio_wfourcc(pb, disc ? "disk" : "trkn");
3459 avio_wb32(pb, 24); /* size */
3460 ffio_wfourcc(pb, "data");
3461 avio_wb32(pb, 0); // 8 bytes empty
3463 avio_wb16(pb, 0); // empty
3464 avio_wb16(pb, track); // track / disc number
3465 avio_wb16(pb, tracks); // total track / disc number
3466 avio_wb16(pb, 0); // empty
3472 static int mov_write_int8_metadata(AVFormatContext *s, AVIOContext *pb,
3473 const char *name, const char *tag,
3476 AVDictionaryEntry *t = NULL;
3478 int size = 24 + len;
3480 if (len != 1 && len != 4)
3483 if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
3485 num = atoi(t->value);
3487 avio_wb32(pb, size);
3488 ffio_wfourcc(pb, name);
3489 avio_wb32(pb, size - 8);
3490 ffio_wfourcc(pb, "data");
3491 avio_wb32(pb, 0x15);
3493 if (len==4) avio_wb32(pb, num);
3494 else avio_w8 (pb, num);
3499 static int mov_write_covr(AVIOContext *pb, AVFormatContext *s)
3501 MOVMuxContext *mov = s->priv_data;
3505 for (i = 0; i < s->nb_streams; i++) {
3506 MOVTrack *trk = &mov->tracks[i];
3508 if (!is_cover_image(trk->st) || trk->cover_image.size <= 0)
3512 pos = avio_tell(pb);
3514 ffio_wfourcc(pb, "covr");
3516 avio_wb32(pb, 16 + trk->cover_image.size);
3517 ffio_wfourcc(pb, "data");
3518 avio_wb32(pb, trk->tag);
3520 avio_write(pb, trk->cover_image.data, trk->cover_image.size);
3523 return pos ? update_size(pb, pos) : 0;
3526 /* iTunes meta data list */
3527 static int mov_write_ilst_tag(AVIOContext *pb, MOVMuxContext *mov,
3530 int64_t pos = avio_tell(pb);
3531 avio_wb32(pb, 0); /* size */
3532 ffio_wfourcc(pb, "ilst");
3533 mov_write_string_metadata(s, pb, "\251nam", "title" , 1);
3534 mov_write_string_metadata(s, pb, "\251ART", "artist" , 1);
3535 mov_write_string_metadata(s, pb, "aART", "album_artist", 1);
3536 mov_write_string_metadata(s, pb, "\251wrt", "composer" , 1);
3537 mov_write_string_metadata(s, pb, "\251alb", "album" , 1);
3538 mov_write_string_metadata(s, pb, "\251day", "date" , 1);
3539 if (!mov_write_string_metadata(s, pb, "\251too", "encoding_tool", 1)) {
3540 if (!(s->flags & AVFMT_FLAG_BITEXACT))
3541 mov_write_string_tag(pb, "\251too", LIBAVFORMAT_IDENT, 0, 1);
3543 mov_write_string_metadata(s, pb, "\251cmt", "comment" , 1);
3544 mov_write_string_metadata(s, pb, "\251gen", "genre" , 1);
3545 mov_write_string_metadata(s, pb, "cprt", "copyright", 1);
3546 mov_write_string_metadata(s, pb, "\251grp", "grouping" , 1);
3547 mov_write_string_metadata(s, pb, "\251lyr", "lyrics" , 1);
3548 mov_write_string_metadata(s, pb, "desc", "description",1);
3549 mov_write_string_metadata(s, pb, "ldes", "synopsis" , 1);
3550 mov_write_string_metadata(s, pb, "tvsh", "show" , 1);
3551 mov_write_string_metadata(s, pb, "tven", "episode_id",1);
3552 mov_write_string_metadata(s, pb, "tvnn", "network" , 1);
3553 mov_write_string_metadata(s, pb, "keyw", "keywords" , 1);
3554 mov_write_int8_metadata (s, pb, "tves", "episode_sort",4);
3555 mov_write_int8_metadata (s, pb, "tvsn", "season_number",4);
3556 mov_write_int8_metadata (s, pb, "stik", "media_type",1);
3557 mov_write_int8_metadata (s, pb, "hdvd", "hd_video", 1);
3558 mov_write_int8_metadata (s, pb, "pgap", "gapless_playback",1);
3559 mov_write_int8_metadata (s, pb, "cpil", "compilation", 1);
3560 mov_write_covr(pb, s);
3561 mov_write_trkn_tag(pb, mov, s, 0); // track number
3562 mov_write_trkn_tag(pb, mov, s, 1); // disc number
3563 mov_write_tmpo_tag(pb, s);
3564 return update_size(pb, pos);
3567 static int mov_write_mdta_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov,
3570 avio_wb32(pb, 33); /* size */
3571 ffio_wfourcc(pb, "hdlr");
3574 ffio_wfourcc(pb, "mdta");
3582 static int mov_write_mdta_keys_tag(AVIOContext *pb, MOVMuxContext *mov,
3585 AVDictionaryEntry *t = NULL;
3586 int64_t pos = avio_tell(pb);
3587 int64_t curpos, entry_pos;
3590 avio_wb32(pb, 0); /* size */
3591 ffio_wfourcc(pb, "keys");
3593 entry_pos = avio_tell(pb);
3594 avio_wb32(pb, 0); /* entry count */
3596 while (t = av_dict_get(s->metadata, "", t, AV_DICT_IGNORE_SUFFIX)) {
3597 avio_wb32(pb, strlen(t->key) + 8);
3598 ffio_wfourcc(pb, "mdta");
3599 avio_write(pb, t->key, strlen(t->key));
3602 curpos = avio_tell(pb);
3603 avio_seek(pb, entry_pos, SEEK_SET);
3604 avio_wb32(pb, count); // rewrite entry count
3605 avio_seek(pb, curpos, SEEK_SET);
3607 return update_size(pb, pos);
3610 static int mov_write_mdta_ilst_tag(AVIOContext *pb, MOVMuxContext *mov,
3613 AVDictionaryEntry *t = NULL;
3614 int64_t pos = avio_tell(pb);
3615 int count = 1; /* keys are 1-index based */
3617 avio_wb32(pb, 0); /* size */
3618 ffio_wfourcc(pb, "ilst");
3620 while (t = av_dict_get(s->metadata, "", t, AV_DICT_IGNORE_SUFFIX)) {
3621 int64_t entry_pos = avio_tell(pb);
3622 avio_wb32(pb, 0); /* size */
3623 avio_wb32(pb, count); /* key */
3624 mov_write_string_data_tag(pb, t->value, 0, 1);
3625 update_size(pb, entry_pos);
3628 return update_size(pb, pos);
3631 /* meta data tags */
3632 static int mov_write_meta_tag(AVIOContext *pb, MOVMuxContext *mov,
3636 int64_t pos = avio_tell(pb);
3637 avio_wb32(pb, 0); /* size */
3638 ffio_wfourcc(pb, "meta");
3640 if (mov->flags & FF_MOV_FLAG_USE_MDTA) {
3641 mov_write_mdta_hdlr_tag(pb, mov, s);
3642 mov_write_mdta_keys_tag(pb, mov, s);
3643 mov_write_mdta_ilst_tag(pb, mov, s);
3646 /* iTunes metadata tag */
3647 mov_write_itunes_hdlr_tag(pb, mov, s);
3648 mov_write_ilst_tag(pb, mov, s);
3650 size = update_size(pb, pos);
3654 static int mov_write_raw_metadata_tag(AVFormatContext *s, AVIOContext *pb,
3655 const char *name, const char *key)
3658 AVDictionaryEntry *t;
3660 if (!(t = av_dict_get(s->metadata, key, NULL, 0)))
3663 len = strlen(t->value);
3666 avio_wb32(pb, size);
3667 ffio_wfourcc(pb, name);
3668 avio_write(pb, t->value, len);
3674 static int ascii_to_wc(AVIOContext *pb, const uint8_t *b)
3678 GET_UTF8(val, *b++, return -1;)
3681 avio_wb16(pb, 0x00);
3685 static uint16_t language_code(const char *str)
3687 return (((str[0] - 0x60) & 0x1F) << 10) +
3688 (((str[1] - 0x60) & 0x1F) << 5) +
3689 (( str[2] - 0x60) & 0x1F);
3692 static int mov_write_3gp_udta_tag(AVIOContext *pb, AVFormatContext *s,
3693 const char *tag, const char *str)
3695 int64_t pos = avio_tell(pb);
3696 AVDictionaryEntry *t = av_dict_get(s->metadata, str, NULL, 0);
3697 if (!t || !utf8len(t->value))
3699 avio_wb32(pb, 0); /* size */
3700 ffio_wfourcc(pb, tag); /* type */
3701 avio_wb32(pb, 0); /* version + flags */
3702 if (!strcmp(tag, "yrrc"))
3703 avio_wb16(pb, atoi(t->value));
3705 avio_wb16(pb, language_code("eng")); /* language */
3706 avio_write(pb, t->value, strlen(t->value) + 1); /* UTF8 string value */
3707 if (!strcmp(tag, "albm") &&
3708 (t = av_dict_get(s->metadata, "track", NULL, 0)))
3709 avio_w8(pb, atoi(t->value));
3711 return update_size(pb, pos);
3714 static int mov_write_chpl_tag(AVIOContext *pb, AVFormatContext *s)
3716 int64_t pos = avio_tell(pb);
3717 int i, nb_chapters = FFMIN(s->nb_chapters, 255);
3719 avio_wb32(pb, 0); // size
3720 ffio_wfourcc(pb, "chpl");
3721 avio_wb32(pb, 0x01000000); // version + flags
3722 avio_wb32(pb, 0); // unknown
3723 avio_w8(pb, nb_chapters);
3725 for (i = 0; i < nb_chapters; i++) {
3726 AVChapter *c = s->chapters[i];
3727 AVDictionaryEntry *t;
3728 avio_wb64(pb, av_rescale_q(c->start, c->time_base, (AVRational){1,10000000}));
3730 if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
3731 int len = FFMIN(strlen(t->value), 255);
3733 avio_write(pb, t->value, len);
3737 return update_size(pb, pos);
3740 static int mov_write_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
3743 AVIOContext *pb_buf;
3747 ret = avio_open_dyn_buf(&pb_buf);
3751 if (mov->mode & MODE_3GP) {
3752 mov_write_3gp_udta_tag(pb_buf, s, "perf", "artist");
3753 mov_write_3gp_udta_tag(pb_buf, s, "titl", "title");
3754 mov_write_3gp_udta_tag(pb_buf, s, "auth", "author");
3755 mov_write_3gp_udta_tag(pb_buf, s, "gnre", "genre");
3756 mov_write_3gp_udta_tag(pb_buf, s, "dscp", "comment");
3757 mov_write_3gp_udta_tag(pb_buf, s, "albm", "album");
3758 mov_write_3gp_udta_tag(pb_buf, s, "cprt", "copyright");
3759 mov_write_3gp_udta_tag(pb_buf, s, "yrrc", "date");
3760 mov_write_loci_tag(s, pb_buf);
3761 } 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
3762 mov_write_string_metadata(s, pb_buf, "\251ART", "artist", 0);
3763 mov_write_string_metadata(s, pb_buf, "\251nam", "title", 0);
3764 mov_write_string_metadata(s, pb_buf, "\251aut", "author", 0);
3765 mov_write_string_metadata(s, pb_buf, "\251alb", "album", 0);
3766 mov_write_string_metadata(s, pb_buf, "\251day", "date", 0);
3767 mov_write_string_metadata(s, pb_buf, "\251swr", "encoder", 0);
3768 // currently ignored by mov.c
3769 mov_write_string_metadata(s, pb_buf, "\251des", "comment", 0);
3770 // add support for libquicktime, this atom is also actually read by mov.c
3771 mov_write_string_metadata(s, pb_buf, "\251cmt", "comment", 0);
3772 mov_write_string_metadata(s, pb_buf, "\251gen", "genre", 0);
3773 mov_write_string_metadata(s, pb_buf, "\251cpy", "copyright", 0);
3774 mov_write_string_metadata(s, pb_buf, "\251mak", "make", 0);
3775 mov_write_string_metadata(s, pb_buf, "\251mod", "model", 0);
3776 mov_write_string_metadata(s, pb_buf, "\251xyz", "location", 0);
3777 mov_write_string_metadata(s, pb_buf, "\251key", "keywords", 0);
3778 mov_write_raw_metadata_tag(s, pb_buf, "XMP_", "xmp");
3780 /* iTunes meta data */
3781 mov_write_meta_tag(pb_buf, mov, s);
3782 mov_write_loci_tag(s, pb_buf);
3785 if (s->nb_chapters && !(mov->flags & FF_MOV_FLAG_DISABLE_CHPL))
3786 mov_write_chpl_tag(pb_buf, s);
3788 if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) {
3789 avio_wb32(pb, size + 8);
3790 ffio_wfourcc(pb, "udta");
3791 avio_write(pb, buf, size);
3798 static void mov_write_psp_udta_tag(AVIOContext *pb,
3799 const char *str, const char *lang, int type)
3801 int len = utf8len(str) + 1;
3804 avio_wb16(pb, len * 2 + 10); /* size */
3805 avio_wb32(pb, type); /* type */
3806 avio_wb16(pb, language_code(lang)); /* language */
3807 avio_wb16(pb, 0x01); /* ? */
3808 ascii_to_wc(pb, str);
3811 static int mov_write_uuidusmt_tag(AVIOContext *pb, AVFormatContext *s)
3813 AVDictionaryEntry *title = av_dict_get(s->metadata, "title", NULL, 0);
3817 pos = avio_tell(pb);
3818 avio_wb32(pb, 0); /* size placeholder*/
3819 ffio_wfourcc(pb, "uuid");
3820 ffio_wfourcc(pb, "USMT");
3821 avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
3822 avio_wb32(pb, 0xbb88695c);
3823 avio_wb32(pb, 0xfac9c740);
3825 pos2 = avio_tell(pb);
3826 avio_wb32(pb, 0); /* size placeholder*/
3827 ffio_wfourcc(pb, "MTDT");
3831 avio_wb16(pb, 0x0C); /* size */
3832 avio_wb32(pb, 0x0B); /* type */
3833 avio_wb16(pb, language_code("und")); /* language */
3834 avio_wb16(pb, 0x0); /* ? */
3835 avio_wb16(pb, 0x021C); /* data */
3837 if (!(s->flags & AVFMT_FLAG_BITEXACT))
3838 mov_write_psp_udta_tag(pb, LIBAVCODEC_IDENT, "eng", 0x04);
3839 mov_write_psp_udta_tag(pb, title->value, "eng", 0x01);
3840 mov_write_psp_udta_tag(pb, "2006/04/01 11:11:11", "und", 0x03);
3842 update_size(pb, pos2);
3843 return update_size(pb, pos);
3849 static void build_chunks(MOVTrack *trk)
3852 MOVIentry *chunk = &trk->cluster[0];
3853 uint64_t chunkSize = chunk->size;
3854 chunk->chunkNum = 1;
3855 if (trk->chunkCount)
3857 trk->chunkCount = 1;
3858 for (i = 1; i<trk->entry; i++){
3859 if (chunk->pos + chunkSize == trk->cluster[i].pos &&
3860 chunkSize + trk->cluster[i].size < (1<<20)){
3861 chunkSize += trk->cluster[i].size;
3862 chunk->samples_in_chunk += trk->cluster[i].entries;
3864 trk->cluster[i].chunkNum = chunk->chunkNum+1;
3865 chunk=&trk->cluster[i];
3866 chunkSize = chunk->size;
3873 * Assign track ids. If option "use_stream_ids_as_track_ids" is set,
3874 * the stream ids are used as track ids.
3876 * This assumes mov->tracks and s->streams are in the same order and
3877 * there are no gaps in either of them (so mov->tracks[n] refers to
3880 * As an exception, there can be more entries in
3881 * s->streams than in mov->tracks, in which case new track ids are
3882 * generated (starting after the largest found stream id).
3884 static int mov_setup_track_ids(MOVMuxContext *mov, AVFormatContext *s)
3888 if (mov->track_ids_ok)
3891 if (mov->use_stream_ids_as_track_ids) {
3892 int next_generated_track_id = 0;
3893 for (i = 0; i < s->nb_streams; i++) {
3894 if (s->streams[i]->id > next_generated_track_id)
3895 next_generated_track_id = s->streams[i]->id;
3898 for (i = 0; i < mov->nb_streams; i++) {
3899 if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
3902 mov->tracks[i].track_id = i >= s->nb_streams ? ++next_generated_track_id : s->streams[i]->id;
3905 for (i = 0; i < mov->nb_streams; i++) {
3906 if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
3909 mov->tracks[i].track_id = i + 1;
3913 mov->track_ids_ok = 1;
3918 static int mov_write_moov_tag(AVIOContext *pb, MOVMuxContext *mov,
3922 int64_t pos = avio_tell(pb);
3923 avio_wb32(pb, 0); /* size placeholder*/
3924 ffio_wfourcc(pb, "moov");
3926 mov_setup_track_ids(mov, s);
3928 for (i = 0; i < mov->nb_streams; i++) {
3929 if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
3932 mov->tracks[i].time = mov->time;
3934 if (mov->tracks[i].entry)
3935 build_chunks(&mov->tracks[i]);
3938 if (mov->chapter_track)
3939 for (i = 0; i < s->nb_streams; i++) {
3940 mov->tracks[i].tref_tag = MKTAG('c','h','a','p');
3941 mov->tracks[i].tref_id = mov->tracks[mov->chapter_track].track_id;
3943 for (i = 0; i < mov->nb_streams; i++) {
3944 MOVTrack *track = &mov->tracks[i];
3945 if (track->tag == MKTAG('r','t','p',' ')) {
3946 track->tref_tag = MKTAG('h','i','n','t');
3947 track->tref_id = mov->tracks[track->src_track].track_id;
3948 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
3949 int * fallback, size;
3950 fallback = (int*)av_stream_get_side_data(track->st,
3951 AV_PKT_DATA_FALLBACK_TRACK,
3953 if (fallback != NULL && size == sizeof(int)) {
3954 if (*fallback >= 0 && *fallback < mov->nb_streams) {
3955 track->tref_tag = MKTAG('f','a','l','l');
3956 track->tref_id = mov->tracks[*fallback].track_id;
3961 for (i = 0; i < mov->nb_streams; i++) {
3962 if (mov->tracks[i].tag == MKTAG('t','m','c','d')) {
3963 int src_trk = mov->tracks[i].src_track;
3964 mov->tracks[src_trk].tref_tag = mov->tracks[i].tag;
3965 mov->tracks[src_trk].tref_id = mov->tracks[i].track_id;
3966 //src_trk may have a different timescale than the tmcd track
3967 mov->tracks[i].track_duration = av_rescale(mov->tracks[src_trk].track_duration,
3968 mov->tracks[i].timescale,
3969 mov->tracks[src_trk].timescale);
3973 mov_write_mvhd_tag(pb, mov);
3974 if (mov->mode != MODE_MOV && !mov->iods_skip)
3975 mov_write_iods_tag(pb, mov);
3976 for (i = 0; i < mov->nb_streams; i++) {
3977 if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_FRAGMENT) {
3978 int ret = mov_write_trak_tag(s, pb, mov, &(mov->tracks[i]), i < s->nb_streams ? s->streams[i] : NULL);
3983 if (mov->flags & FF_MOV_FLAG_FRAGMENT)
3984 mov_write_mvex_tag(pb, mov); /* QuickTime requires trak to precede this */
3986 if (mov->mode == MODE_PSP)
3987 mov_write_uuidusmt_tag(pb, s);
3989 mov_write_udta_tag(pb, mov, s);
3991 return update_size(pb, pos);
3994 static void param_write_int(AVIOContext *pb, const char *name, int value)
3996 avio_printf(pb, "<param name=\"%s\" value=\"%d\" valuetype=\"data\"/>\n", name, value);
3999 static void param_write_string(AVIOContext *pb, const char *name, const char *value)
4001 avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, value);
4004 static void param_write_hex(AVIOContext *pb, const char *name, const uint8_t *value, int len)
4007 len = FFMIN(sizeof(buf) / 2 - 1, len);
4008 ff_data_to_hex(buf, value, len, 0);
4009 buf[2 * len] = '\0';
4010 avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, buf);
4013 static int mov_write_isml_manifest(AVIOContext *pb, MOVMuxContext *mov, AVFormatContext *s)
4015 int64_t pos = avio_tell(pb);
4017 int64_t manifest_bit_rate = 0;
4018 AVCPBProperties *props = NULL;
4020 static const uint8_t uuid[] = {
4021 0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd,
4022 0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66
4026 ffio_wfourcc(pb, "uuid");
4027 avio_write(pb, uuid, sizeof(uuid));
4030 avio_printf(pb, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
4031 avio_printf(pb, "<smil xmlns=\"http://www.w3.org/2001/SMIL20/Language\">\n");
4032 avio_printf(pb, "<head>\n");
4033 if (!(mov->fc->flags & AVFMT_FLAG_BITEXACT))
4034 avio_printf(pb, "<meta name=\"creator\" content=\"%s\" />\n",
4036 avio_printf(pb, "</head>\n");
4037 avio_printf(pb, "<body>\n");
4038 avio_printf(pb, "<switch>\n");
4040 mov_setup_track_ids(mov, s);
4042 for (i = 0; i < mov->nb_streams; i++) {
4043 MOVTrack *track = &mov->tracks[i];
4045 int track_id = track->track_id;
4046 char track_name_buf[32] = { 0 };
4048 AVStream *st = track->st;
4049 AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0);
4051 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO && !is_cover_image(st)) {
4053 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
4059 props = (AVCPBProperties*)av_stream_get_side_data(track->st, AV_PKT_DATA_CPB_PROPERTIES, NULL);
4061 if (track->par->bit_rate) {
4062 manifest_bit_rate = track->par->bit_rate;
4064 manifest_bit_rate = props->max_bitrate;
4067 avio_printf(pb, "<%s systemBitrate=\"%"PRId64"\">\n", type,
4069 param_write_int(pb, "systemBitrate", manifest_bit_rate);
4070 param_write_int(pb, "trackID", track_id);
4071 param_write_string(pb, "systemLanguage", lang ? lang->value : "und");
4073 /* Build track name piece by piece: */
4075 av_strlcat(track_name_buf, type, sizeof(track_name_buf));
4076 /* 2. track language, if available */
4078 av_strlcatf(track_name_buf, sizeof(track_name_buf),
4079 "_%s", lang->value);
4080 /* 3. special type suffix */
4081 /* "_cc" = closed captions, "_ad" = audio_description */
4082 if (st->disposition & AV_DISPOSITION_HEARING_IMPAIRED)
4083 av_strlcat(track_name_buf, "_cc", sizeof(track_name_buf));
4084 else if (st->disposition & AV_DISPOSITION_VISUAL_IMPAIRED)
4085 av_strlcat(track_name_buf, "_ad", sizeof(track_name_buf));
4087 param_write_string(pb, "trackName", track_name_buf);
4089 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
4090 if (track->par->codec_id == AV_CODEC_ID_H264) {
4092 int size = track->par->extradata_size;
4093 if (!ff_avc_write_annexb_extradata(track->par->extradata, &ptr,
4095 param_write_hex(pb, "CodecPrivateData",
4096 ptr ? ptr : track->par->extradata,
4100 param_write_string(pb, "FourCC", "H264");
4101 } else if (track->par->codec_id == AV_CODEC_ID_VC1) {
4102 param_write_string(pb, "FourCC", "WVC1");
4103 param_write_hex(pb, "CodecPrivateData", track->par->extradata,
4104 track->par->extradata_size);
4106 param_write_int(pb, "MaxWidth", track->par->width);
4107 param_write_int(pb, "MaxHeight", track->par->height);
4108 param_write_int(pb, "DisplayWidth", track->par->width);
4109 param_write_int(pb, "DisplayHeight", track->par->height);
4111 if (track->par->codec_id == AV_CODEC_ID_AAC) {
4112 switch (track->par->profile)
4114 case FF_PROFILE_AAC_HE_V2:
4115 param_write_string(pb, "FourCC", "AACP");
4117 case FF_PROFILE_AAC_HE:
4118 param_write_string(pb, "FourCC", "AACH");
4121 param_write_string(pb, "FourCC", "AACL");
4123 } else if (track->par->codec_id == AV_CODEC_ID_WMAPRO) {
4124 param_write_string(pb, "FourCC", "WMAP");
4126 param_write_hex(pb, "CodecPrivateData", track->par->extradata,
4127 track->par->extradata_size);
4128 param_write_int(pb, "AudioTag", ff_codec_get_tag(ff_codec_wav_tags,
4129 track->par->codec_id));
4130 param_write_int(pb, "Channels", track->par->channels);
4131 param_write_int(pb, "SamplingRate", track->par->sample_rate);
4132 param_write_int(pb, "BitsPerSample", 16);
4133 param_write_int(pb, "PacketSize", track->par->block_align ?
4134 track->par->block_align : 4);
4136 avio_printf(pb, "</%s>\n", type);
4138 avio_printf(pb, "</switch>\n");
4139 avio_printf(pb, "</body>\n");
4140 avio_printf(pb, "</smil>\n");
4142 return update_size(pb, pos);
4145 static int mov_write_mfhd_tag(AVIOContext *pb, MOVMuxContext *mov)
4148 ffio_wfourcc(pb, "mfhd");
4150 avio_wb32(pb, mov->fragments);
4154 static uint32_t get_sample_flags(MOVTrack *track, MOVIentry *entry)
4156 return entry->flags & MOV_SYNC_SAMPLE ? MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO :
4157 (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC);
4160 static int mov_write_tfhd_tag(AVIOContext *pb, MOVMuxContext *mov,
4161 MOVTrack *track, int64_t moof_offset)
4163 int64_t pos = avio_tell(pb);
4164 uint32_t flags = MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
4165 MOV_TFHD_BASE_DATA_OFFSET;
4166 if (!track->entry) {
4167 flags |= MOV_TFHD_DURATION_IS_EMPTY;
4169 flags |= MOV_TFHD_DEFAULT_FLAGS;
4171 if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET)
4172 flags &= ~MOV_TFHD_BASE_DATA_OFFSET;
4173 if (mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) {
4174 flags &= ~MOV_TFHD_BASE_DATA_OFFSET;
4175 flags |= MOV_TFHD_DEFAULT_BASE_IS_MOOF;
4178 /* Don't set a default sample size, the silverlight player refuses
4179 * to play files with that set. Don't set a default sample duration,
4180 * WMP freaks out if it is set. Don't set a base data offset, PIFF
4181 * file format says it MUST NOT be set. */
4182 if (track->mode == MODE_ISM)
4183 flags &= ~(MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
4184 MOV_TFHD_BASE_DATA_OFFSET);
4186 avio_wb32(pb, 0); /* size placeholder */
4187 ffio_wfourcc(pb, "tfhd");
4188 avio_w8(pb, 0); /* version */
4189 avio_wb24(pb, flags);
4191 avio_wb32(pb, track->track_id); /* track-id */
4192 if (flags & MOV_TFHD_BASE_DATA_OFFSET)
4193 avio_wb64(pb, moof_offset);
4194 if (flags & MOV_TFHD_DEFAULT_DURATION) {
4195 track->default_duration = get_cluster_duration(track, 0);
4196 avio_wb32(pb, track->default_duration);
4198 if (flags & MOV_TFHD_DEFAULT_SIZE) {
4199 track->default_size = track->entry ? track->cluster[0].size : 1;
4200 avio_wb32(pb, track->default_size);
4202 track->default_size = -1;
4204 if (flags & MOV_TFHD_DEFAULT_FLAGS) {
4205 /* Set the default flags based on the second sample, if available.
4206 * If the first sample is different, that can be signaled via a separate field. */
4207 if (track->entry > 1)
4208 track->default_sample_flags = get_sample_flags(track, &track->cluster[1]);
4210 track->default_sample_flags =
4211 track->par->codec_type == AVMEDIA_TYPE_VIDEO ?
4212 (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC) :
4213 MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO;
4214 avio_wb32(pb, track->default_sample_flags);
4217 return update_size(pb, pos);
4220 static int mov_write_trun_tag(AVIOContext *pb, MOVMuxContext *mov,
4221 MOVTrack *track, int moof_size,
4224 int64_t pos = avio_tell(pb);
4225 uint32_t flags = MOV_TRUN_DATA_OFFSET;
4228 for (i = first; i < end; i++) {
4229 if (get_cluster_duration(track, i) != track->default_duration)
4230 flags |= MOV_TRUN_SAMPLE_DURATION;
4231 if (track->cluster[i].size != track->default_size)
4232 flags |= MOV_TRUN_SAMPLE_SIZE;
4233 if (i > first && get_sample_flags(track, &track->cluster[i]) != track->default_sample_flags)
4234 flags |= MOV_TRUN_SAMPLE_FLAGS;
4236 if (!(flags & MOV_TRUN_SAMPLE_FLAGS) && track->entry > 0 &&
4237 get_sample_flags(track, &track->cluster[0]) != track->default_sample_flags)
4238 flags |= MOV_TRUN_FIRST_SAMPLE_FLAGS;
4239 if (track->flags & MOV_TRACK_CTTS)
4240 flags |= MOV_TRUN_SAMPLE_CTS;
4242 avio_wb32(pb, 0); /* size placeholder */
4243 ffio_wfourcc(pb, "trun");
4244 if (mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS)
4245 avio_w8(pb, 1); /* version */
4247 avio_w8(pb, 0); /* version */
4248 avio_wb24(pb, flags);
4250 avio_wb32(pb, end - first); /* sample count */
4251 if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET &&
4252 !(mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) &&
4254 avio_wb32(pb, 0); /* Later tracks follow immediately after the previous one */
4256 avio_wb32(pb, moof_size + 8 + track->data_offset +
4257 track->cluster[first].pos); /* data offset */
4258 if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS)
4259 avio_wb32(pb, get_sample_flags(track, &track->cluster[first]));
4261 for (i = first; i < end; i++) {
4262 if (flags & MOV_TRUN_SAMPLE_DURATION)
4263 avio_wb32(pb, get_cluster_duration(track, i));
4264 if (flags & MOV_TRUN_SAMPLE_SIZE)
4265 avio_wb32(pb, track->cluster[i].size);
4266 if (flags & MOV_TRUN_SAMPLE_FLAGS)
4267 avio_wb32(pb, get_sample_flags(track, &track->cluster[i]));
4268 if (flags & MOV_TRUN_SAMPLE_CTS)
4269 avio_wb32(pb, track->cluster[i].cts);
4272 mov->first_trun = 0;
4273 return update_size(pb, pos);
4276 static int mov_write_tfxd_tag(AVIOContext *pb, MOVTrack *track)
4278 int64_t pos = avio_tell(pb);
4279 static const uint8_t uuid[] = {
4280 0x6d, 0x1d, 0x9b, 0x05, 0x42, 0xd5, 0x44, 0xe6,
4281 0x80, 0xe2, 0x14, 0x1d, 0xaf, 0xf7, 0x57, 0xb2
4284 avio_wb32(pb, 0); /* size placeholder */
4285 ffio_wfourcc(pb, "uuid");
4286 avio_write(pb, uuid, sizeof(uuid));
4289 avio_wb64(pb, track->start_dts + track->frag_start +
4290 track->cluster[0].cts);
4291 avio_wb64(pb, track->end_pts -
4292 (track->cluster[0].dts + track->cluster[0].cts));
4294 return update_size(pb, pos);
4297 static int mov_write_tfrf_tag(AVIOContext *pb, MOVMuxContext *mov,
4298 MOVTrack *track, int entry)
4300 int n = track->nb_frag_info - 1 - entry, i;
4301 int size = 8 + 16 + 4 + 1 + 16*n;
4302 static const uint8_t uuid[] = {
4303 0xd4, 0x80, 0x7e, 0xf2, 0xca, 0x39, 0x46, 0x95,
4304 0x8e, 0x54, 0x26, 0xcb, 0x9e, 0x46, 0xa7, 0x9f
4310 avio_seek(pb, track->frag_info[entry].tfrf_offset, SEEK_SET);
4311 avio_wb32(pb, size);
4312 ffio_wfourcc(pb, "uuid");
4313 avio_write(pb, uuid, sizeof(uuid));
4317 for (i = 0; i < n; i++) {
4318 int index = entry + 1 + i;
4319 avio_wb64(pb, track->frag_info[index].time);
4320 avio_wb64(pb, track->frag_info[index].duration);
4322 if (n < mov->ism_lookahead) {
4323 int free_size = 16 * (mov->ism_lookahead - n);
4324 avio_wb32(pb, free_size);
4325 ffio_wfourcc(pb, "free");
4326 ffio_fill(pb, 0, free_size - 8);
4332 static int mov_write_tfrf_tags(AVIOContext *pb, MOVMuxContext *mov,
4335 int64_t pos = avio_tell(pb);
4337 for (i = 0; i < mov->ism_lookahead; i++) {
4338 /* Update the tfrf tag for the last ism_lookahead fragments,
4339 * nb_frag_info - 1 is the next fragment to be written. */
4340 mov_write_tfrf_tag(pb, mov, track, track->nb_frag_info - 2 - i);
4342 avio_seek(pb, pos, SEEK_SET);
4346 static int mov_add_tfra_entries(AVIOContext *pb, MOVMuxContext *mov, int tracks,
4350 for (i = 0; i < mov->nb_streams; i++) {
4351 MOVTrack *track = &mov->tracks[i];
4352 MOVFragmentInfo *info;
4353 if ((tracks >= 0 && i != tracks) || !track->entry)
4355 track->nb_frag_info++;
4356 if (track->nb_frag_info >= track->frag_info_capacity) {
4357 unsigned new_capacity = track->nb_frag_info + MOV_FRAG_INFO_ALLOC_INCREMENT;
4358 if (av_reallocp_array(&track->frag_info,
4360 sizeof(*track->frag_info)))
4361 return AVERROR(ENOMEM);
4362 track->frag_info_capacity = new_capacity;
4364 info = &track->frag_info[track->nb_frag_info - 1];
4365 info->offset = avio_tell(pb);
4367 // Try to recreate the original pts for the first packet
4368 // from the fields we have stored
4369 info->time = track->start_dts + track->frag_start +
4370 track->cluster[0].cts;
4371 info->duration = track->end_pts -
4372 (track->cluster[0].dts + track->cluster[0].cts);
4373 // If the pts is less than zero, we will have trimmed
4374 // away parts of the media track using an edit list,
4375 // and the corresponding start presentation time is zero.
4376 if (info->time < 0) {
4377 info->duration += info->time;
4380 info->tfrf_offset = 0;
4381 mov_write_tfrf_tags(pb, mov, track);
4386 static void mov_prune_frag_info(MOVMuxContext *mov, int tracks, int max)
4389 for (i = 0; i < mov->nb_streams; i++) {
4390 MOVTrack *track = &mov->tracks[i];
4391 if ((tracks >= 0 && i != tracks) || !track->entry)
4393 if (track->nb_frag_info > max) {
4394 memmove(track->frag_info, track->frag_info + (track->nb_frag_info - max), max * sizeof(*track->frag_info));
4395 track->nb_frag_info = max;
4400 static int mov_write_tfdt_tag(AVIOContext *pb, MOVTrack *track)
4402 int64_t pos = avio_tell(pb);
4404 avio_wb32(pb, 0); /* size */
4405 ffio_wfourcc(pb, "tfdt");
4406 avio_w8(pb, 1); /* version */
4408 avio_wb64(pb, track->frag_start);
4409 return update_size(pb, pos);
4412 static int mov_write_traf_tag(AVIOContext *pb, MOVMuxContext *mov,
4413 MOVTrack *track, int64_t moof_offset,
4416 int64_t pos = avio_tell(pb);
4418 avio_wb32(pb, 0); /* size placeholder */
4419 ffio_wfourcc(pb, "traf");
4421 mov_write_tfhd_tag(pb, mov, track, moof_offset);
4422 if (mov->mode != MODE_ISM)
4423 mov_write_tfdt_tag(pb, track);
4424 for (i = 1; i < track->entry; i++) {
4425 if (track->cluster[i].pos != track->cluster[i - 1].pos + track->cluster[i - 1].size) {
4426 mov_write_trun_tag(pb, mov, track, moof_size, start, i);
4430 mov_write_trun_tag(pb, mov, track, moof_size, start, track->entry);
4431 if (mov->mode == MODE_ISM) {
4432 mov_write_tfxd_tag(pb, track);
4434 if (mov->ism_lookahead) {
4435 int i, size = 16 + 4 + 1 + 16 * mov->ism_lookahead;
4437 if (track->nb_frag_info > 0) {
4438 MOVFragmentInfo *info = &track->frag_info[track->nb_frag_info - 1];
4439 if (!info->tfrf_offset)
4440 info->tfrf_offset = avio_tell(pb);
4442 avio_wb32(pb, 8 + size);
4443 ffio_wfourcc(pb, "free");
4444 for (i = 0; i < size; i++)
4449 return update_size(pb, pos);
4452 static int mov_write_moof_tag_internal(AVIOContext *pb, MOVMuxContext *mov,
4453 int tracks, int moof_size)
4455 int64_t pos = avio_tell(pb);
4458 avio_wb32(pb, 0); /* size placeholder */
4459 ffio_wfourcc(pb, "moof");
4460 mov->first_trun = 1;
4462 mov_write_mfhd_tag(pb, mov);
4463 for (i = 0; i < mov->nb_streams; i++) {
4464 MOVTrack *track = &mov->tracks[i];
4465 if (tracks >= 0 && i != tracks)
4469 mov_write_traf_tag(pb, mov, track, pos, moof_size);
4472 return update_size(pb, pos);
4475 static int mov_write_sidx_tag(AVIOContext *pb,
4476 MOVTrack *track, int ref_size, int total_sidx_size)
4478 int64_t pos = avio_tell(pb), offset_pos, end_pos;
4479 int64_t presentation_time, duration, offset;
4480 int starts_with_SAP, i, entries;
4484 presentation_time = track->start_dts + track->frag_start +
4485 track->cluster[0].cts;
4486 duration = track->end_pts -
4487 (track->cluster[0].dts + track->cluster[0].cts);
4488 starts_with_SAP = track->cluster[0].flags & MOV_SYNC_SAMPLE;
4490 // pts<0 should be cut away using edts
4491 if (presentation_time < 0) {
4492 duration += presentation_time;
4493 presentation_time = 0;
4496 entries = track->nb_frag_info;
4499 presentation_time = track->frag_info[0].time;
4502 avio_wb32(pb, 0); /* size */
4503 ffio_wfourcc(pb, "sidx");
4504 avio_w8(pb, 1); /* version */
4506 avio_wb32(pb, track->track_id); /* reference_ID */
4507 avio_wb32(pb, track->timescale); /* timescale */
4508 avio_wb64(pb, presentation_time); /* earliest_presentation_time */
4509 offset_pos = avio_tell(pb);
4510 avio_wb64(pb, 0); /* first_offset (offset to referenced moof) */
4511 avio_wb16(pb, 0); /* reserved */
4513 avio_wb16(pb, entries); /* reference_count */
4514 for (i = 0; i < entries; i++) {
4515 if (!track->entry) {
4516 if (i > 1 && track->frag_info[i].offset != track->frag_info[i - 1].offset + track->frag_info[i - 1].size) {
4517 av_log(NULL, AV_LOG_ERROR, "Non-consecutive fragments, writing incorrect sidx\n");
4519 duration = track->frag_info[i].duration;
4520 ref_size = track->frag_info[i].size;
4521 starts_with_SAP = 1;
4523 avio_wb32(pb, (0 << 31) | (ref_size & 0x7fffffff)); /* reference_type (0 = media) | referenced_size */
4524 avio_wb32(pb, duration); /* subsegment_duration */
4525 avio_wb32(pb, (starts_with_SAP << 31) | (0 << 28) | 0); /* starts_with_SAP | SAP_type | SAP_delta_time */
4528 end_pos = avio_tell(pb);
4529 offset = pos + total_sidx_size - end_pos;
4530 avio_seek(pb, offset_pos, SEEK_SET);
4531 avio_wb64(pb, offset);
4532 avio_seek(pb, end_pos, SEEK_SET);
4533 return update_size(pb, pos);
4536 static int mov_write_sidx_tags(AVIOContext *pb, MOVMuxContext *mov,
4537 int tracks, int ref_size)
4540 AVIOContext *avio_buf;
4542 for (round = 0; round < 2; round++) {
4543 // First run one round to calculate the total size of all
4545 // This would be much simpler if we'd only write one sidx
4546 // atom, for the first track in the moof.
4548 if ((ret = ffio_open_null_buf(&avio_buf)) < 0)
4553 for (i = 0; i < mov->nb_streams; i++) {
4554 MOVTrack *track = &mov->tracks[i];
4555 if (tracks >= 0 && i != tracks)
4557 // When writing a sidx for the full file, entry is 0, but
4558 // we want to include all tracks. ref_size is 0 in this case,
4559 // since we read it from frag_info instead.
4560 if (!track->entry && ref_size > 0)
4562 total_size -= mov_write_sidx_tag(avio_buf, track, ref_size,
4566 total_size = ffio_close_null_buf(avio_buf);
4571 static int mov_write_prft_tag(AVIOContext *pb, MOVMuxContext *mov, int tracks)
4573 int64_t pos = avio_tell(pb), pts_us, ntp_ts;
4574 MOVTrack *first_track;
4576 /* PRFT should be associated with at most one track. So, choosing only the
4580 first_track = &(mov->tracks[0]);
4582 if (!first_track->entry) {
4583 av_log(mov->fc, AV_LOG_WARNING, "Unable to write PRFT, no entries in the track\n");
4587 if (first_track->cluster[0].pts == AV_NOPTS_VALUE) {
4588 av_log(mov->fc, AV_LOG_WARNING, "Unable to write PRFT, first PTS is invalid\n");
4592 if (mov->write_prft == MOV_PRFT_SRC_WALLCLOCK) {
4593 ntp_ts = ff_get_formatted_ntp_time(ff_ntp_time());
4594 } else if (mov->write_prft == MOV_PRFT_SRC_PTS) {
4595 pts_us = av_rescale_q(first_track->cluster[0].pts,
4596 first_track->st->time_base, AV_TIME_BASE_Q);
4597 ntp_ts = ff_get_formatted_ntp_time(pts_us + NTP_OFFSET_US);
4599 av_log(mov->fc, AV_LOG_WARNING, "Unsupported PRFT box configuration: %d\n",
4604 avio_wb32(pb, 0); // Size place holder
4605 ffio_wfourcc(pb, "prft"); // Type
4606 avio_w8(pb, 1); // Version
4607 avio_wb24(pb, 0); // Flags
4608 avio_wb32(pb, first_track->track_id); // reference track ID
4609 avio_wb64(pb, ntp_ts); // NTP time stamp
4610 avio_wb64(pb, first_track->cluster[0].pts); //media time
4611 return update_size(pb, pos);
4614 static int mov_write_moof_tag(AVIOContext *pb, MOVMuxContext *mov, int tracks,
4617 AVIOContext *avio_buf;
4620 if ((ret = ffio_open_null_buf(&avio_buf)) < 0)
4622 mov_write_moof_tag_internal(avio_buf, mov, tracks, 0);
4623 moof_size = ffio_close_null_buf(avio_buf);
4625 if (mov->flags & FF_MOV_FLAG_DASH &&
4626 !(mov->flags & (FF_MOV_FLAG_GLOBAL_SIDX | FF_MOV_FLAG_SKIP_SIDX)))
4627 mov_write_sidx_tags(pb, mov, tracks, moof_size + 8 + mdat_size);
4629 if (mov->write_prft > MOV_PRFT_NONE && mov->write_prft < MOV_PRFT_NB)
4630 mov_write_prft_tag(pb, mov, tracks);
4632 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX ||
4633 !(mov->flags & FF_MOV_FLAG_SKIP_TRAILER) ||
4634 mov->ism_lookahead) {
4635 if ((ret = mov_add_tfra_entries(pb, mov, tracks, moof_size + 8 + mdat_size)) < 0)
4637 if (!(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) &&
4638 mov->flags & FF_MOV_FLAG_SKIP_TRAILER) {
4639 mov_prune_frag_info(mov, tracks, mov->ism_lookahead + 1);
4643 return mov_write_moof_tag_internal(pb, mov, tracks, moof_size);
4646 static int mov_write_tfra_tag(AVIOContext *pb, MOVTrack *track)
4648 int64_t pos = avio_tell(pb);
4651 avio_wb32(pb, 0); /* size placeholder */
4652 ffio_wfourcc(pb, "tfra");
4653 avio_w8(pb, 1); /* version */
4656 avio_wb32(pb, track->track_id);
4657 avio_wb32(pb, 0); /* length of traf/trun/sample num */
4658 avio_wb32(pb, track->nb_frag_info);
4659 for (i = 0; i < track->nb_frag_info; i++) {
4660 avio_wb64(pb, track->frag_info[i].time);
4661 avio_wb64(pb, track->frag_info[i].offset + track->data_offset);
4662 avio_w8(pb, 1); /* traf number */
4663 avio_w8(pb, 1); /* trun number */
4664 avio_w8(pb, 1); /* sample number */
4667 return update_size(pb, pos);
4670 static int mov_write_mfra_tag(AVIOContext *pb, MOVMuxContext *mov)
4672 int64_t pos = avio_tell(pb);
4675 avio_wb32(pb, 0); /* size placeholder */
4676 ffio_wfourcc(pb, "mfra");
4677 /* An empty mfra atom is enough to indicate to the publishing point that
4678 * the stream has ended. */
4679 if (mov->flags & FF_MOV_FLAG_ISML)
4680 return update_size(pb, pos);
4682 for (i = 0; i < mov->nb_streams; i++) {
4683 MOVTrack *track = &mov->tracks[i];
4684 if (track->nb_frag_info)
4685 mov_write_tfra_tag(pb, track);
4689 ffio_wfourcc(pb, "mfro");
4690 avio_wb32(pb, 0); /* version + flags */
4691 avio_wb32(pb, avio_tell(pb) + 4 - pos);
4693 return update_size(pb, pos);
4696 static int mov_write_mdat_tag(AVIOContext *pb, MOVMuxContext *mov)
4698 avio_wb32(pb, 8); // placeholder for extended size field (64 bit)
4699 ffio_wfourcc(pb, mov->mode == MODE_MOV ? "wide" : "free");
4701 mov->mdat_pos = avio_tell(pb);
4702 avio_wb32(pb, 0); /* size placeholder*/
4703 ffio_wfourcc(pb, "mdat");
4707 /* TODO: This needs to be more general */
4708 static int mov_write_ftyp_tag(AVIOContext *pb, AVFormatContext *s)
4710 MOVMuxContext *mov = s->priv_data;
4711 int64_t pos = avio_tell(pb);
4712 int has_h264 = 0, has_video = 0;
4716 for (i = 0; i < s->nb_streams; i++) {
4717 AVStream *st = s->streams[i];
4718 if (is_cover_image(st))
4720 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
4722 if (st->codecpar->codec_id == AV_CODEC_ID_H264)
4726 avio_wb32(pb, 0); /* size */
4727 ffio_wfourcc(pb, "ftyp");
4729 if (mov->major_brand && strlen(mov->major_brand) >= 4)
4730 ffio_wfourcc(pb, mov->major_brand);
4731 else if (mov->mode == MODE_3GP) {
4732 ffio_wfourcc(pb, has_h264 ? "3gp6" : "3gp4");
4733 minor = has_h264 ? 0x100 : 0x200;
4734 } else if (mov->mode & MODE_3G2) {
4735 ffio_wfourcc(pb, has_h264 ? "3g2b" : "3g2a");
4736 minor = has_h264 ? 0x20000 : 0x10000;
4737 } else if (mov->mode == MODE_PSP)
4738 ffio_wfourcc(pb, "MSNV");
4739 else if (mov->mode == MODE_MP4 && mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)
4740 ffio_wfourcc(pb, "iso5"); // Required when using default-base-is-moof
4741 else if (mov->mode == MODE_MP4 && mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS)
4742 ffio_wfourcc(pb, "iso4");
4743 else if (mov->mode == MODE_MP4)
4744 ffio_wfourcc(pb, "isom");
4745 else if (mov->mode == MODE_IPOD)
4746 ffio_wfourcc(pb, has_video ? "M4V ":"M4A ");
4747 else if (mov->mode == MODE_ISM)
4748 ffio_wfourcc(pb, "isml");
4749 else if (mov->mode == MODE_F4V)
4750 ffio_wfourcc(pb, "f4v ");
4752 ffio_wfourcc(pb, "qt ");
4754 avio_wb32(pb, minor);
4756 if (mov->mode == MODE_MOV)
4757 ffio_wfourcc(pb, "qt ");
4758 else if (mov->mode == MODE_ISM) {
4759 ffio_wfourcc(pb, "piff");
4760 } else if (!(mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)) {
4761 ffio_wfourcc(pb, "isom");
4762 ffio_wfourcc(pb, "iso2");
4764 ffio_wfourcc(pb, "avc1");
4767 // We add tfdt atoms when fragmenting, signal this with the iso6 compatible
4768 // brand. This is compatible with users that don't understand tfdt.
4769 if (mov->flags & FF_MOV_FLAG_FRAGMENT && mov->mode != MODE_ISM)
4770 ffio_wfourcc(pb, "iso6");
4772 if (mov->mode == MODE_3GP)
4773 ffio_wfourcc(pb, has_h264 ? "3gp6":"3gp4");
4774 else if (mov->mode & MODE_3G2)
4775 ffio_wfourcc(pb, has_h264 ? "3g2b":"3g2a");
4776 else if (mov->mode == MODE_PSP)
4777 ffio_wfourcc(pb, "MSNV");
4778 else if (mov->mode == MODE_MP4)
4779 ffio_wfourcc(pb, "mp41");
4781 if (mov->flags & FF_MOV_FLAG_DASH && mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
4782 ffio_wfourcc(pb, "dash");
4784 return update_size(pb, pos);
4787 static int mov_write_uuidprof_tag(AVIOContext *pb, AVFormatContext *s)
4789 AVStream *video_st = s->streams[0];
4790 AVCodecParameters *video_par = s->streams[0]->codecpar;
4791 AVCodecParameters *audio_par = s->streams[1]->codecpar;
4792 int audio_rate = audio_par->sample_rate;
4793 int64_t frame_rate = video_st->avg_frame_rate.den ?
4794 (video_st->avg_frame_rate.num * 0x10000LL) / video_st->avg_frame_rate.den :
4796 int audio_kbitrate = audio_par->bit_rate / 1000;
4797 int video_kbitrate = FFMIN(video_par->bit_rate / 1000, 800 - audio_kbitrate);
4799 if (frame_rate < 0 || frame_rate > INT32_MAX) {
4800 av_log(s, AV_LOG_ERROR, "Frame rate %f outside supported range\n", frame_rate / (double)0x10000);
4801 return AVERROR(EINVAL);
4804 avio_wb32(pb, 0x94); /* size */
4805 ffio_wfourcc(pb, "uuid");
4806 ffio_wfourcc(pb, "PROF");
4808 avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
4809 avio_wb32(pb, 0xbb88695c);
4810 avio_wb32(pb, 0xfac9c740);
4812 avio_wb32(pb, 0x0); /* ? */
4813 avio_wb32(pb, 0x3); /* 3 sections ? */
4815 avio_wb32(pb, 0x14); /* size */
4816 ffio_wfourcc(pb, "FPRF");
4817 avio_wb32(pb, 0x0); /* ? */
4818 avio_wb32(pb, 0x0); /* ? */
4819 avio_wb32(pb, 0x0); /* ? */
4821 avio_wb32(pb, 0x2c); /* size */
4822 ffio_wfourcc(pb, "APRF"); /* audio */
4824 avio_wb32(pb, 0x2); /* TrackID */
4825 ffio_wfourcc(pb, "mp4a");
4826 avio_wb32(pb, 0x20f);
4828 avio_wb32(pb, audio_kbitrate);
4829 avio_wb32(pb, audio_kbitrate);
4830 avio_wb32(pb, audio_rate);
4831 avio_wb32(pb, audio_par->channels);
4833 avio_wb32(pb, 0x34); /* size */
4834 ffio_wfourcc(pb, "VPRF"); /* video */
4836 avio_wb32(pb, 0x1); /* TrackID */
4837 if (video_par->codec_id == AV_CODEC_ID_H264) {
4838 ffio_wfourcc(pb, "avc1");
4839 avio_wb16(pb, 0x014D);
4840 avio_wb16(pb, 0x0015);
4842 ffio_wfourcc(pb, "mp4v");
4843 avio_wb16(pb, 0x0000);
4844 avio_wb16(pb, 0x0103);
4847 avio_wb32(pb, video_kbitrate);
4848 avio_wb32(pb, video_kbitrate);
4849 avio_wb32(pb, frame_rate);
4850 avio_wb32(pb, frame_rate);
4851 avio_wb16(pb, video_par->width);
4852 avio_wb16(pb, video_par->height);
4853 avio_wb32(pb, 0x010001); /* ? */
4858 static int mov_write_identification(AVIOContext *pb, AVFormatContext *s)
4860 MOVMuxContext *mov = s->priv_data;
4863 mov_write_ftyp_tag(pb,s);
4864 if (mov->mode == MODE_PSP) {
4865 int video_streams_nb = 0, audio_streams_nb = 0, other_streams_nb = 0;
4866 for (i = 0; i < s->nb_streams; i++) {
4867 AVStream *st = s->streams[i];
4868 if (is_cover_image(st))
4870 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
4872 else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
4878 if (video_streams_nb != 1 || audio_streams_nb != 1 || other_streams_nb) {
4879 av_log(s, AV_LOG_ERROR, "PSP mode need one video and one audio stream\n");
4880 return AVERROR(EINVAL);
4882 return mov_write_uuidprof_tag(pb, s);
4887 static int mov_parse_mpeg2_frame(AVPacket *pkt, uint32_t *flags)
4890 int i, closed_gop = 0;
4892 for (i = 0; i < pkt->size - 4; i++) {
4893 c = (c << 8) + pkt->data[i];
4894 if (c == 0x1b8) { // gop
4895 closed_gop = pkt->data[i + 4] >> 6 & 0x01;
4896 } else if (c == 0x100) { // pic
4897 int temp_ref = (pkt->data[i + 1] << 2) | (pkt->data[i + 2] >> 6);
4898 if (!temp_ref || closed_gop) // I picture is not reordered
4899 *flags = MOV_SYNC_SAMPLE;
4901 *flags = MOV_PARTIAL_SYNC_SAMPLE;
4908 static void mov_parse_vc1_frame(AVPacket *pkt, MOVTrack *trk)
4910 const uint8_t *start, *next, *end = pkt->data + pkt->size;
4911 int seq = 0, entry = 0;
4912 int key = pkt->flags & AV_PKT_FLAG_KEY;
4913 start = find_next_marker(pkt->data, end);
4914 for (next = start; next < end; start = next) {
4915 next = find_next_marker(start + 4, end);
4916 switch (AV_RB32(start)) {
4917 case VC1_CODE_SEQHDR:
4920 case VC1_CODE_ENTRYPOINT:
4923 case VC1_CODE_SLICE:
4924 trk->vc1_info.slices = 1;
4928 if (!trk->entry && trk->vc1_info.first_packet_seen)
4929 trk->vc1_info.first_frag_written = 1;
4930 if (!trk->entry && !trk->vc1_info.first_frag_written) {
4931 /* First packet in first fragment */
4932 trk->vc1_info.first_packet_seq = seq;
4933 trk->vc1_info.first_packet_entry = entry;
4934 trk->vc1_info.first_packet_seen = 1;
4935 } else if ((seq && !trk->vc1_info.packet_seq) ||
4936 (entry && !trk->vc1_info.packet_entry)) {
4938 for (i = 0; i < trk->entry; i++)
4939 trk->cluster[i].flags &= ~MOV_SYNC_SAMPLE;
4940 trk->has_keyframes = 0;
4942 trk->vc1_info.packet_seq = 1;
4944 trk->vc1_info.packet_entry = 1;
4945 if (!trk->vc1_info.first_frag_written) {
4946 /* First fragment */
4947 if ((!seq || trk->vc1_info.first_packet_seq) &&
4948 (!entry || trk->vc1_info.first_packet_entry)) {
4949 /* First packet had the same headers as this one, readd the
4950 * sync sample flag. */
4951 trk->cluster[0].flags |= MOV_SYNC_SAMPLE;
4952 trk->has_keyframes = 1;
4956 if (trk->vc1_info.packet_seq && trk->vc1_info.packet_entry)
4958 else if (trk->vc1_info.packet_seq)
4960 else if (trk->vc1_info.packet_entry)
4963 trk->cluster[trk->entry].flags |= MOV_SYNC_SAMPLE;
4964 trk->has_keyframes++;
4968 static int mov_flush_fragment_interleaving(AVFormatContext *s, MOVTrack *track)
4970 MOVMuxContext *mov = s->priv_data;
4975 if (!track->mdat_buf)
4977 if (!mov->mdat_buf) {
4978 if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0)
4981 buf_size = avio_close_dyn_buf(track->mdat_buf, &buf);
4982 track->mdat_buf = NULL;
4984 offset = avio_tell(mov->mdat_buf);
4985 avio_write(mov->mdat_buf, buf, buf_size);
4988 for (i = track->entries_flushed; i < track->entry; i++)
4989 track->cluster[i].pos += offset;
4990 track->entries_flushed = track->entry;
4994 static int mov_flush_fragment(AVFormatContext *s, int force)
4996 MOVMuxContext *mov = s->priv_data;
4997 int i, first_track = -1;
4998 int64_t mdat_size = 0;
5000 int has_video = 0, starts_with_key = 0, first_video_track = 1;
5002 if (!(mov->flags & FF_MOV_FLAG_FRAGMENT))
5005 // Try to fill in the duration of the last packet in each stream
5006 // from queued packets in the interleave queues. If the flushing
5007 // of fragments was triggered automatically by an AVPacket, we
5008 // already have reliable info for the end of that track, but other
5009 // tracks may need to be filled in.
5010 for (i = 0; i < s->nb_streams; i++) {
5011 MOVTrack *track = &mov->tracks[i];
5012 if (!track->end_reliable) {
5014 if (!ff_interleaved_peek(s, i, &pkt, 1)) {
5015 if (track->dts_shift != AV_NOPTS_VALUE)
5016 pkt.dts += track->dts_shift;
5017 track->track_duration = pkt.dts - track->start_dts;
5018 if (pkt.pts != AV_NOPTS_VALUE)
5019 track->end_pts = pkt.pts;
5021 track->end_pts = pkt.dts;
5026 for (i = 0; i < mov->nb_streams; i++) {
5027 MOVTrack *track = &mov->tracks[i];
5028 if (track->entry <= 1)
5030 // Sample durations are calculated as the diff of dts values,
5031 // but for the last sample in a fragment, we don't know the dts
5032 // of the first sample in the next fragment, so we have to rely
5033 // on what was set as duration in the AVPacket. Not all callers
5034 // set this though, so we might want to replace it with an
5035 // estimate if it currently is zero.
5036 if (get_cluster_duration(track, track->entry - 1) != 0)
5038 // Use the duration (i.e. dts diff) of the second last sample for
5039 // the last one. This is a wild guess (and fatal if it turns out
5040 // to be too long), but probably the best we can do - having a zero
5041 // duration is bad as well.
5042 track->track_duration += get_cluster_duration(track, track->entry - 2);
5043 track->end_pts += get_cluster_duration(track, track->entry - 2);
5044 if (!mov->missing_duration_warned) {
5045 av_log(s, AV_LOG_WARNING,
5046 "Estimating the duration of the last packet in a "
5047 "fragment, consider setting the duration field in "
5048 "AVPacket instead.\n");
5049 mov->missing_duration_warned = 1;
5053 if (!mov->moov_written) {
5054 int64_t pos = avio_tell(s->pb);
5056 int buf_size, moov_size;
5058 for (i = 0; i < mov->nb_streams; i++)
5059 if (!mov->tracks[i].entry && !is_cover_image(mov->tracks[i].st))
5061 /* Don't write the initial moov unless all tracks have data */
5062 if (i < mov->nb_streams && !force)
5065 moov_size = get_moov_size(s);
5066 for (i = 0; i < mov->nb_streams; i++)
5067 mov->tracks[i].data_offset = pos + moov_size + 8;
5069 avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_HEADER);
5070 if (mov->flags & FF_MOV_FLAG_DELAY_MOOV)
5071 mov_write_identification(s->pb, s);
5072 if ((ret = mov_write_moov_tag(s->pb, mov, s)) < 0)
5075 if (mov->flags & FF_MOV_FLAG_DELAY_MOOV) {
5076 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
5077 mov->reserved_header_pos = avio_tell(s->pb);
5079 mov->moov_written = 1;
5083 buf_size = avio_close_dyn_buf(mov->mdat_buf, &buf);
5084 mov->mdat_buf = NULL;
5085 avio_wb32(s->pb, buf_size + 8);
5086 ffio_wfourcc(s->pb, "mdat");
5087 avio_write(s->pb, buf, buf_size);
5090 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
5091 mov->reserved_header_pos = avio_tell(s->pb);
5093 mov->moov_written = 1;
5095 for (i = 0; i < mov->nb_streams; i++) {
5096 if (mov->tracks[i].entry)
5097 mov->tracks[i].frag_start += mov->tracks[i].start_dts +
5098 mov->tracks[i].track_duration -
5099 mov->tracks[i].cluster[0].dts;
5100 mov->tracks[i].entry = 0;
5101 mov->tracks[i].end_reliable = 0;
5107 if (mov->frag_interleave) {
5108 for (i = 0; i < mov->nb_streams; i++) {
5109 MOVTrack *track = &mov->tracks[i];
5111 if ((ret = mov_flush_fragment_interleaving(s, track)) < 0)
5117 mdat_size = avio_tell(mov->mdat_buf);
5120 for (i = 0; i < mov->nb_streams; i++) {
5121 MOVTrack *track = &mov->tracks[i];
5122 if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF || mov->frag_interleave)
5123 track->data_offset = 0;
5125 track->data_offset = mdat_size;
5126 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
5128 if (first_video_track) {
5130 starts_with_key = track->cluster[0].flags & MOV_SYNC_SAMPLE;
5131 first_video_track = 0;
5136 if (track->mdat_buf)
5137 mdat_size += avio_tell(track->mdat_buf);
5138 if (first_track < 0)
5145 avio_write_marker(s->pb,
5146 av_rescale(mov->tracks[first_track].cluster[0].dts, AV_TIME_BASE, mov->tracks[first_track].timescale),
5147 (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);
5149 for (i = 0; i < mov->nb_streams; i++) {
5150 MOVTrack *track = &mov->tracks[i];
5151 int buf_size, write_moof = 1, moof_tracks = -1;
5153 int64_t duration = 0;
5156 duration = track->start_dts + track->track_duration -
5157 track->cluster[0].dts;
5158 if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF) {
5159 if (!track->mdat_buf)
5161 mdat_size = avio_tell(track->mdat_buf);
5164 write_moof = i == first_track;
5170 mov_write_moof_tag(s->pb, mov, moof_tracks, mdat_size);
5173 avio_wb32(s->pb, mdat_size + 8);
5174 ffio_wfourcc(s->pb, "mdat");
5178 track->frag_start += duration;
5180 track->entries_flushed = 0;
5181 track->end_reliable = 0;
5182 if (!mov->frag_interleave) {
5183 if (!track->mdat_buf)
5185 buf_size = avio_close_dyn_buf(track->mdat_buf, &buf);
5186 track->mdat_buf = NULL;
5190 buf_size = avio_close_dyn_buf(mov->mdat_buf, &buf);
5191 mov->mdat_buf = NULL;
5194 avio_write(s->pb, buf, buf_size);
5204 static int mov_auto_flush_fragment(AVFormatContext *s, int force)
5206 MOVMuxContext *mov = s->priv_data;
5207 int had_moov = mov->moov_written;
5208 int ret = mov_flush_fragment(s, force);
5211 // If using delay_moov, the first flush only wrote the moov,
5212 // not the actual moof+mdat pair, thus flush once again.
5213 if (!had_moov && mov->flags & FF_MOV_FLAG_DELAY_MOOV)
5214 ret = mov_flush_fragment(s, force);
5218 static int check_pkt(AVFormatContext *s, AVPacket *pkt)
5220 MOVMuxContext *mov = s->priv_data;
5221 MOVTrack *trk = &mov->tracks[pkt->stream_index];
5226 ref = trk->cluster[trk->entry - 1].dts;
5227 } else if ( trk->start_dts != AV_NOPTS_VALUE
5228 && !trk->frag_discont) {
5229 ref = trk->start_dts + trk->track_duration;
5231 ref = pkt->dts; // Skip tests for the first packet
5233 if (trk->dts_shift != AV_NOPTS_VALUE) {
5234 /* With negative CTS offsets we have set an offset to the DTS,
5235 * reverse this for the check. */
5236 ref -= trk->dts_shift;
5239 duration = pkt->dts - ref;
5240 if (pkt->dts < ref || duration >= INT_MAX) {
5241 av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" / timestamp: %"PRId64" is out of range for mov/mp4 format\n",
5246 pkt->pts = AV_NOPTS_VALUE;
5249 if (pkt->duration < 0 || pkt->duration > INT_MAX) {
5250 av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" is invalid\n", pkt->duration);
5251 return AVERROR(EINVAL);
5256 int ff_mov_write_packet(AVFormatContext *s, AVPacket *pkt)
5258 MOVMuxContext *mov = s->priv_data;
5259 AVIOContext *pb = s->pb;
5260 MOVTrack *trk = &mov->tracks[pkt->stream_index];
5261 AVCodecParameters *par = trk->par;
5262 unsigned int samples_in_chunk = 0;
5263 int size = pkt->size, ret = 0;
5264 uint8_t *reformatted_data = NULL;
5266 ret = check_pkt(s, pkt);
5270 if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
5272 if (mov->moov_written || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
5273 if (mov->frag_interleave && mov->fragments > 0) {
5274 if (trk->entry - trk->entries_flushed >= mov->frag_interleave) {
5275 if ((ret = mov_flush_fragment_interleaving(s, trk)) < 0)
5280 if (!trk->mdat_buf) {
5281 if ((ret = avio_open_dyn_buf(&trk->mdat_buf)) < 0)
5286 if (!mov->mdat_buf) {
5287 if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0)
5294 if (par->codec_id == AV_CODEC_ID_AMR_NB) {
5295 /* We must find out how many AMR blocks there are in one packet */
5296 static const uint16_t packed_size[16] =
5297 {13, 14, 16, 18, 20, 21, 27, 32, 6, 0, 0, 0, 0, 0, 0, 1};
5300 while (len < size && samples_in_chunk < 100) {
5301 len += packed_size[(pkt->data[len] >> 3) & 0x0F];
5304 if (samples_in_chunk > 1) {
5305 av_log(s, AV_LOG_ERROR, "fatal error, input is not a single packet, implement a AVParser for it\n");
5308 } else if (par->codec_id == AV_CODEC_ID_ADPCM_MS ||
5309 par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) {
5310 samples_in_chunk = trk->par->frame_size;
5311 } else if (trk->sample_size)
5312 samples_in_chunk = size / trk->sample_size;
5314 samples_in_chunk = 1;
5316 if (samples_in_chunk < 1) {
5317 av_log(s, AV_LOG_ERROR, "fatal error, input packet contains no samples\n");
5318 return AVERROR_PATCHWELCOME;
5321 /* copy extradata if it exists */
5322 if (trk->vos_len == 0 && par->extradata_size > 0 &&
5323 !TAG_IS_AVCI(trk->tag) &&
5324 (par->codec_id != AV_CODEC_ID_DNXHD)) {
5325 trk->vos_len = par->extradata_size;
5326 trk->vos_data = av_malloc(trk->vos_len);
5327 if (!trk->vos_data) {
5328 ret = AVERROR(ENOMEM);
5331 memcpy(trk->vos_data, par->extradata, trk->vos_len);
5334 if (par->codec_id == AV_CODEC_ID_AAC && pkt->size > 2 &&
5335 (AV_RB16(pkt->data) & 0xfff0) == 0xfff0) {
5336 if (!s->streams[pkt->stream_index]->nb_frames) {
5337 av_log(s, AV_LOG_ERROR, "Malformed AAC bitstream detected: "
5338 "use the audio bitstream filter 'aac_adtstoasc' to fix it "
5339 "('-bsf:a aac_adtstoasc' option with ffmpeg)\n");
5342 av_log(s, AV_LOG_WARNING, "aac bitstream error\n");
5344 if (par->codec_id == AV_CODEC_ID_H264 && trk->vos_len > 0 && *(uint8_t *)trk->vos_data != 1 && !TAG_IS_AVCI(trk->tag)) {
5345 /* from x264 or from bytestream H.264 */
5346 /* NAL reformatting needed */
5347 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
5348 ff_avc_parse_nal_units_buf(pkt->data, &reformatted_data,
5350 avio_write(pb, reformatted_data, size);
5352 if (trk->cenc.aes_ctr) {
5353 size = ff_mov_cenc_avc_parse_nal_units(&trk->cenc, pb, pkt->data, size);
5359 size = ff_avc_parse_nal_units(pb, pkt->data, pkt->size);
5362 } else if (par->codec_id == AV_CODEC_ID_HEVC && trk->vos_len > 6 &&
5363 (AV_RB24(trk->vos_data) == 1 || AV_RB32(trk->vos_data) == 1)) {
5364 /* extradata is Annex B, assume the bitstream is too and convert it */
5365 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
5366 ff_hevc_annexb2mp4_buf(pkt->data, &reformatted_data, &size, 0, NULL);
5367 avio_write(pb, reformatted_data, size);
5369 size = ff_hevc_annexb2mp4(pb, pkt->data, pkt->size, 0, NULL);
5371 } else if (par->codec_id == AV_CODEC_ID_AV1) {
5372 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
5373 ff_av1_filter_obus_buf(pkt->data, &reformatted_data, &size);
5374 avio_write(pb, reformatted_data, size);
5376 size = ff_av1_filter_obus(pb, pkt->data, pkt->size);
5378 #if CONFIG_AC3_PARSER
5379 } else if (par->codec_id == AV_CODEC_ID_EAC3) {
5380 size = handle_eac3(mov, pkt, trk);
5385 avio_write(pb, pkt->data, size);
5388 if (trk->cenc.aes_ctr) {
5389 if (par->codec_id == AV_CODEC_ID_H264 && par->extradata_size > 4) {
5390 int nal_size_length = (par->extradata[4] & 0x3) + 1;
5391 ret = ff_mov_cenc_avc_write_nal_units(s, &trk->cenc, nal_size_length, pb, pkt->data, size);
5393 ret = ff_mov_cenc_write_packet(&trk->cenc, pb, pkt->data, size);
5400 avio_write(pb, pkt->data, size);
5404 if ((par->codec_id == AV_CODEC_ID_DNXHD ||
5405 par->codec_id == AV_CODEC_ID_AC3) && !trk->vos_len) {
5406 /* copy frame to create needed atoms */
5407 trk->vos_len = size;
5408 trk->vos_data = av_malloc(size);
5409 if (!trk->vos_data) {
5410 ret = AVERROR(ENOMEM);
5413 memcpy(trk->vos_data, pkt->data, size);
5416 if (trk->entry >= trk->cluster_capacity) {
5417 unsigned new_capacity = 2 * (trk->entry + MOV_INDEX_CLUSTER_SIZE);
5418 if (av_reallocp_array(&trk->cluster, new_capacity,
5419 sizeof(*trk->cluster))) {
5420 ret = AVERROR(ENOMEM);
5423 trk->cluster_capacity = new_capacity;
5426 trk->cluster[trk->entry].pos = avio_tell(pb) - size;
5427 trk->cluster[trk->entry].samples_in_chunk = samples_in_chunk;
5428 trk->cluster[trk->entry].chunkNum = 0;
5429 trk->cluster[trk->entry].size = size;
5430 trk->cluster[trk->entry].entries = samples_in_chunk;
5431 trk->cluster[trk->entry].dts = pkt->dts;
5432 trk->cluster[trk->entry].pts = pkt->pts;
5433 if (!trk->entry && trk->start_dts != AV_NOPTS_VALUE) {
5434 if (!trk->frag_discont) {
5435 /* First packet of a new fragment. We already wrote the duration
5436 * of the last packet of the previous fragment based on track_duration,
5437 * which might not exactly match our dts. Therefore adjust the dts
5438 * of this packet to be what the previous packets duration implies. */
5439 trk->cluster[trk->entry].dts = trk->start_dts + trk->track_duration;
5440 /* We also may have written the pts and the corresponding duration
5441 * in sidx/tfrf/tfxd tags; make sure the sidx pts and duration match up with
5442 * the next fragment. This means the cts of the first sample must
5443 * be the same in all fragments, unless end_pts was updated by
5444 * the packet causing the fragment to be written. */
5445 if ((mov->flags & FF_MOV_FLAG_DASH &&
5446 !(mov->flags & (FF_MOV_FLAG_GLOBAL_SIDX | FF_MOV_FLAG_SKIP_SIDX))) ||
5447 mov->mode == MODE_ISM)
5448 pkt->pts = pkt->dts + trk->end_pts - trk->cluster[trk->entry].dts;
5450 /* New fragment, but discontinuous from previous fragments.
5451 * Pretend the duration sum of the earlier fragments is
5452 * pkt->dts - trk->start_dts. */
5453 trk->frag_start = pkt->dts - trk->start_dts;
5454 trk->end_pts = AV_NOPTS_VALUE;
5455 trk->frag_discont = 0;
5459 if (!trk->entry && trk->start_dts == AV_NOPTS_VALUE && !mov->use_editlist &&
5460 s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO) {
5461 /* Not using edit lists and shifting the first track to start from zero.
5462 * If the other streams start from a later timestamp, we won't be able
5463 * to signal the difference in starting time without an edit list.
5464 * Thus move the timestamp for this first sample to 0, increasing
5465 * its duration instead. */
5466 trk->cluster[trk->entry].dts = trk->start_dts = 0;
5468 if (trk->start_dts == AV_NOPTS_VALUE) {
5469 trk->start_dts = pkt->dts;
5470 if (trk->frag_discont) {
5471 if (mov->use_editlist) {
5472 /* Pretend the whole stream started at pts=0, with earlier fragments
5473 * already written. If the stream started at pts=0, the duration sum
5474 * of earlier fragments would have been pkt->pts. */
5475 trk->frag_start = pkt->pts;
5476 trk->start_dts = pkt->dts - pkt->pts;
5478 /* Pretend the whole stream started at dts=0, with earlier fragments
5479 * already written, with a duration summing up to pkt->dts. */
5480 trk->frag_start = pkt->dts;
5483 trk->frag_discont = 0;
5484 } else if (pkt->dts && mov->moov_written)
5485 av_log(s, AV_LOG_WARNING,
5486 "Track %d starts with a nonzero dts %"PRId64", while the moov "
5487 "already has been written. Set the delay_moov flag to handle "
5489 pkt->stream_index, pkt->dts);
5491 trk->track_duration = pkt->dts - trk->start_dts + pkt->duration;
5492 trk->last_sample_is_subtitle_end = 0;
5494 if (pkt->pts == AV_NOPTS_VALUE) {
5495 av_log(s, AV_LOG_WARNING, "pts has no value\n");
5496 pkt->pts = pkt->dts;
5498 if (pkt->dts != pkt->pts)
5499 trk->flags |= MOV_TRACK_CTTS;
5500 trk->cluster[trk->entry].cts = pkt->pts - pkt->dts;
5501 trk->cluster[trk->entry].flags = 0;
5502 if (trk->start_cts == AV_NOPTS_VALUE)
5503 trk->start_cts = pkt->pts - pkt->dts;
5504 if (trk->end_pts == AV_NOPTS_VALUE)
5505 trk->end_pts = trk->cluster[trk->entry].dts +
5506 trk->cluster[trk->entry].cts + pkt->duration;
5508 trk->end_pts = FFMAX(trk->end_pts, trk->cluster[trk->entry].dts +
5509 trk->cluster[trk->entry].cts +
5512 if (par->codec_id == AV_CODEC_ID_VC1) {
5513 mov_parse_vc1_frame(pkt, trk);
5514 } else if (pkt->flags & AV_PKT_FLAG_KEY) {
5515 if (mov->mode == MODE_MOV && par->codec_id == AV_CODEC_ID_MPEG2VIDEO &&
5516 trk->entry > 0) { // force sync sample for the first key frame
5517 mov_parse_mpeg2_frame(pkt, &trk->cluster[trk->entry].flags);
5518 if (trk->cluster[trk->entry].flags & MOV_PARTIAL_SYNC_SAMPLE)
5519 trk->flags |= MOV_TRACK_STPS;
5521 trk->cluster[trk->entry].flags = MOV_SYNC_SAMPLE;
5523 if (trk->cluster[trk->entry].flags & MOV_SYNC_SAMPLE)
5524 trk->has_keyframes++;
5526 if (pkt->flags & AV_PKT_FLAG_DISPOSABLE) {
5527 trk->cluster[trk->entry].flags |= MOV_DISPOSABLE_SAMPLE;
5528 trk->has_disposable++;
5531 trk->sample_count += samples_in_chunk;
5532 mov->mdat_size += size;
5534 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams)
5535 ff_mov_add_hinted_packet(s, pkt, trk->hint_track, trk->entry,
5536 reformatted_data, size);
5541 av_free(reformatted_data);
5545 static int mov_write_single_packet(AVFormatContext *s, AVPacket *pkt)
5547 MOVMuxContext *mov = s->priv_data;
5548 MOVTrack *trk = &mov->tracks[pkt->stream_index];
5549 AVCodecParameters *par = trk->par;
5550 int64_t frag_duration = 0;
5551 int size = pkt->size;
5553 int ret = check_pkt(s, pkt);
5557 if (mov->flags & FF_MOV_FLAG_FRAG_DISCONT) {
5559 for (i = 0; i < s->nb_streams; i++)
5560 mov->tracks[i].frag_discont = 1;
5561 mov->flags &= ~FF_MOV_FLAG_FRAG_DISCONT;
5564 if (mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS) {
5565 if (trk->dts_shift == AV_NOPTS_VALUE)
5566 trk->dts_shift = pkt->pts - pkt->dts;
5567 pkt->dts += trk->dts_shift;
5570 if (trk->par->codec_id == AV_CODEC_ID_MP4ALS ||
5571 trk->par->codec_id == AV_CODEC_ID_AAC ||
5572 trk->par->codec_id == AV_CODEC_ID_AV1 ||
5573 trk->par->codec_id == AV_CODEC_ID_FLAC) {
5575 uint8_t *side = av_packet_get_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA, &side_size);
5576 if (side && side_size > 0 && (side_size != par->extradata_size || memcmp(side, par->extradata, side_size))) {
5577 void *newextra = av_mallocz(side_size + AV_INPUT_BUFFER_PADDING_SIZE);
5579 return AVERROR(ENOMEM);
5580 av_free(par->extradata);
5581 par->extradata = newextra;
5582 memcpy(par->extradata, side, side_size);
5583 par->extradata_size = side_size;
5584 if (!pkt->size) // Flush packet
5585 mov->need_rewrite_extradata = 1;
5590 if (trk->start_dts == AV_NOPTS_VALUE && trk->frag_discont) {
5591 trk->start_dts = pkt->dts;
5592 if (pkt->pts != AV_NOPTS_VALUE)
5593 trk->start_cts = pkt->pts - pkt->dts;
5598 return 0; /* Discard 0 sized packets */
5601 if (trk->entry && pkt->stream_index < s->nb_streams)
5602 frag_duration = av_rescale_q(pkt->dts - trk->cluster[0].dts,
5603 s->streams[pkt->stream_index]->time_base,
5605 if ((mov->max_fragment_duration &&
5606 frag_duration >= mov->max_fragment_duration) ||
5607 (mov->max_fragment_size && mov->mdat_size + size >= mov->max_fragment_size) ||
5608 (mov->flags & FF_MOV_FLAG_FRAG_KEYFRAME &&
5609 par->codec_type == AVMEDIA_TYPE_VIDEO &&
5610 trk->entry && pkt->flags & AV_PKT_FLAG_KEY) ||
5611 (mov->flags & FF_MOV_FLAG_FRAG_EVERY_FRAME)) {
5612 if (frag_duration >= mov->min_fragment_duration) {
5613 // Set the duration of this track to line up with the next
5614 // sample in this track. This avoids relying on AVPacket
5615 // duration, but only helps for this particular track, not
5616 // for the other ones that are flushed at the same time.
5617 trk->track_duration = pkt->dts - trk->start_dts;
5618 if (pkt->pts != AV_NOPTS_VALUE)
5619 trk->end_pts = pkt->pts;
5621 trk->end_pts = pkt->dts;
5622 trk->end_reliable = 1;
5623 mov_auto_flush_fragment(s, 0);
5627 return ff_mov_write_packet(s, pkt);
5630 static int mov_write_subtitle_end_packet(AVFormatContext *s,
5634 uint8_t data[2] = {0};
5637 av_init_packet(&end);
5638 end.size = sizeof(data);
5643 end.stream_index = stream_index;
5645 ret = mov_write_single_packet(s, &end);
5646 av_packet_unref(&end);
5651 static int mov_write_packet(AVFormatContext *s, AVPacket *pkt)
5653 MOVMuxContext *mov = s->priv_data;
5657 mov_flush_fragment(s, 1);
5661 trk = &mov->tracks[pkt->stream_index];
5663 if (is_cover_image(trk->st)) {
5666 if (trk->st->nb_frames >= 1) {
5667 if (trk->st->nb_frames == 1)
5668 av_log(s, AV_LOG_WARNING, "Got more than one picture in stream %d,"
5669 " ignoring.\n", pkt->stream_index);
5673 if ((ret = av_packet_ref(&trk->cover_image, pkt)) < 0)
5681 return mov_write_single_packet(s, pkt); /* Passthrough. */
5684 * Subtitles require special handling.
5686 * 1) For full complaince, every track must have a sample at
5687 * dts == 0, which is rarely true for subtitles. So, as soon
5688 * as we see any packet with dts > 0, write an empty subtitle
5689 * at dts == 0 for any subtitle track with no samples in it.
5691 * 2) For each subtitle track, check if the current packet's
5692 * dts is past the duration of the last subtitle sample. If
5693 * so, we now need to write an end sample for that subtitle.
5695 * This must be done conditionally to allow for subtitles that
5696 * immediately replace each other, in which case an end sample
5697 * is not needed, and is, in fact, actively harmful.
5699 * 3) See mov_write_trailer for how the final end sample is
5702 for (i = 0; i < mov->nb_streams; i++) {
5703 MOVTrack *trk = &mov->tracks[i];
5706 if (trk->par->codec_id == AV_CODEC_ID_MOV_TEXT &&
5707 trk->track_duration < pkt->dts &&
5708 (trk->entry == 0 || !trk->last_sample_is_subtitle_end)) {
5709 ret = mov_write_subtitle_end_packet(s, i, trk->track_duration);
5710 if (ret < 0) return ret;
5711 trk->last_sample_is_subtitle_end = 1;
5715 if (trk->mode == MODE_MOV && trk->par->codec_type == AVMEDIA_TYPE_VIDEO) {
5716 AVPacket *opkt = pkt;
5717 int reshuffle_ret, ret;
5718 if (trk->is_unaligned_qt_rgb) {
5719 int64_t bpc = trk->par->bits_per_coded_sample != 15 ? trk->par->bits_per_coded_sample : 16;
5720 int expected_stride = ((trk->par->width * bpc + 15) >> 4)*2;
5721 reshuffle_ret = ff_reshuffle_raw_rgb(s, &pkt, trk->par, expected_stride);
5722 if (reshuffle_ret < 0)
5723 return reshuffle_ret;
5726 if (trk->par->format == AV_PIX_FMT_PAL8 && !trk->pal_done) {
5727 ret = ff_get_packet_palette(s, opkt, reshuffle_ret, trk->palette);
5732 } else if (trk->par->codec_id == AV_CODEC_ID_RAWVIDEO &&
5733 (trk->par->format == AV_PIX_FMT_GRAY8 ||
5734 trk->par->format == AV_PIX_FMT_MONOBLACK)) {
5735 for (i = 0; i < pkt->size; i++)
5736 pkt->data[i] = ~pkt->data[i];
5738 if (reshuffle_ret) {
5739 ret = mov_write_single_packet(s, pkt);
5742 av_packet_free(&pkt);
5747 return mov_write_single_packet(s, pkt);
5751 // QuickTime chapters involve an additional text track with the chapter names
5752 // as samples, and a tref pointing from the other tracks to the chapter one.
5753 static int mov_create_chapter_track(AVFormatContext *s, int tracknum)
5757 MOVMuxContext *mov = s->priv_data;
5758 MOVTrack *track = &mov->tracks[tracknum];
5759 AVPacket pkt = { .stream_index = tracknum, .flags = AV_PKT_FLAG_KEY };
5762 track->mode = mov->mode;
5763 track->tag = MKTAG('t','e','x','t');
5764 track->timescale = MOV_TIMESCALE;
5765 track->par = avcodec_parameters_alloc();
5767 return AVERROR(ENOMEM);
5768 track->par->codec_type = AVMEDIA_TYPE_SUBTITLE;
5770 // These properties are required to make QT recognize the chapter track
5771 uint8_t chapter_properties[43] = { 0, 0, 0, 0, 0, 0, 0, 1, };
5772 if (ff_alloc_extradata(track->par, sizeof(chapter_properties)))
5773 return AVERROR(ENOMEM);
5774 memcpy(track->par->extradata, chapter_properties, sizeof(chapter_properties));
5776 if (avio_open_dyn_buf(&pb) >= 0) {
5780 /* Stub header (usually for Quicktime chapter track) */
5782 avio_wb32(pb, 0x01); // displayFlags
5783 avio_w8(pb, 0x00); // horizontal justification
5784 avio_w8(pb, 0x00); // vertical justification
5785 avio_w8(pb, 0x00); // bgColourRed
5786 avio_w8(pb, 0x00); // bgColourGreen
5787 avio_w8(pb, 0x00); // bgColourBlue
5788 avio_w8(pb, 0x00); // bgColourAlpha
5790 avio_wb16(pb, 0x00); // defTextBoxTop
5791 avio_wb16(pb, 0x00); // defTextBoxLeft
5792 avio_wb16(pb, 0x00); // defTextBoxBottom
5793 avio_wb16(pb, 0x00); // defTextBoxRight
5795 avio_wb16(pb, 0x00); // startChar
5796 avio_wb16(pb, 0x00); // endChar
5797 avio_wb16(pb, 0x01); // fontID
5798 avio_w8(pb, 0x00); // fontStyleFlags
5799 avio_w8(pb, 0x00); // fontSize
5800 avio_w8(pb, 0x00); // fgColourRed
5801 avio_w8(pb, 0x00); // fgColourGreen
5802 avio_w8(pb, 0x00); // fgColourBlue
5803 avio_w8(pb, 0x00); // fgColourAlpha
5805 avio_wb32(pb, 0x0D); // box size
5806 ffio_wfourcc(pb, "ftab"); // box atom name
5807 avio_wb16(pb, 0x01); // entry count
5809 avio_wb16(pb, 0x01); // font ID
5810 avio_w8(pb, 0x00); // font name length
5812 if ((size = avio_close_dyn_buf(pb, &buf)) > 0) {
5813 track->par->extradata = buf;
5814 track->par->extradata_size = size;
5821 for (i = 0; i < s->nb_chapters; i++) {
5822 AVChapter *c = s->chapters[i];
5823 AVDictionaryEntry *t;
5825 int64_t end = av_rescale_q(c->end, c->time_base, (AVRational){1,MOV_TIMESCALE});
5826 pkt.pts = pkt.dts = av_rescale_q(c->start, c->time_base, (AVRational){1,MOV_TIMESCALE});
5827 pkt.duration = end - pkt.dts;
5829 if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
5830 static const char encd[12] = {
5831 0x00, 0x00, 0x00, 0x0C,
5833 0x00, 0x00, 0x01, 0x00 };
5834 len = strlen(t->value);
5835 pkt.size = len + 2 + 12;
5836 pkt.data = av_malloc(pkt.size);
5838 return AVERROR(ENOMEM);
5839 AV_WB16(pkt.data, len);
5840 memcpy(pkt.data + 2, t->value, len);
5841 memcpy(pkt.data + len + 2, encd, sizeof(encd));
5842 ff_mov_write_packet(s, &pkt);
5843 av_freep(&pkt.data);
5851 static int mov_check_timecode_track(AVFormatContext *s, AVTimecode *tc, int src_index, const char *tcstr)
5855 /* compute the frame number */
5856 ret = av_timecode_init_from_string(tc, find_fps(s, s->streams[src_index]), tcstr, s);
5860 static int mov_create_timecode_track(AVFormatContext *s, int index, int src_index, AVTimecode tc)
5863 MOVMuxContext *mov = s->priv_data;
5864 MOVTrack *track = &mov->tracks[index];
5865 AVStream *src_st = s->streams[src_index];
5866 AVPacket pkt = {.stream_index = index, .flags = AV_PKT_FLAG_KEY, .size = 4};
5867 AVRational rate = find_fps(s, src_st);
5869 /* tmcd track based on video stream */
5870 track->mode = mov->mode;
5871 track->tag = MKTAG('t','m','c','d');
5872 track->src_track = src_index;
5873 track->timescale = mov->tracks[src_index].timescale;
5874 if (tc.flags & AV_TIMECODE_FLAG_DROPFRAME)
5875 track->timecode_flags |= MOV_TIMECODE_FLAG_DROPFRAME;
5877 /* set st to src_st for metadata access*/
5880 /* encode context: tmcd data stream */
5881 track->par = avcodec_parameters_alloc();
5883 return AVERROR(ENOMEM);
5884 track->par->codec_type = AVMEDIA_TYPE_DATA;
5885 track->par->codec_tag = track->tag;
5886 track->st->avg_frame_rate = av_inv_q(rate);
5888 /* the tmcd track just contains one packet with the frame number */
5889 pkt.data = av_malloc(pkt.size);
5891 return AVERROR(ENOMEM);
5892 AV_WB32(pkt.data, tc.start);
5893 ret = ff_mov_write_packet(s, &pkt);
5899 * st->disposition controls the "enabled" flag in the tkhd tag.
5900 * QuickTime will not play a track if it is not enabled. So make sure
5901 * that one track of each type (audio, video, subtitle) is enabled.
5903 * Subtitles are special. For audio and video, setting "enabled" also
5904 * makes the track "default" (i.e. it is rendered when played). For
5905 * subtitles, an "enabled" subtitle is not rendered by default, but
5906 * if no subtitle is enabled, the subtitle menu in QuickTime will be
5909 static void enable_tracks(AVFormatContext *s)
5911 MOVMuxContext *mov = s->priv_data;
5913 int enabled[AVMEDIA_TYPE_NB];
5914 int first[AVMEDIA_TYPE_NB];
5916 for (i = 0; i < AVMEDIA_TYPE_NB; i++) {
5921 for (i = 0; i < s->nb_streams; i++) {
5922 AVStream *st = s->streams[i];
5924 if (st->codecpar->codec_type <= AVMEDIA_TYPE_UNKNOWN ||
5925 st->codecpar->codec_type >= AVMEDIA_TYPE_NB ||
5929 if (first[st->codecpar->codec_type] < 0)
5930 first[st->codecpar->codec_type] = i;
5931 if (st->disposition & AV_DISPOSITION_DEFAULT) {
5932 mov->tracks[i].flags |= MOV_TRACK_ENABLED;
5933 enabled[st->codecpar->codec_type]++;
5937 for (i = 0; i < AVMEDIA_TYPE_NB; i++) {
5939 case AVMEDIA_TYPE_VIDEO:
5940 case AVMEDIA_TYPE_AUDIO:
5941 case AVMEDIA_TYPE_SUBTITLE:
5943 mov->per_stream_grouping = 1;
5944 if (!enabled[i] && first[i] >= 0)
5945 mov->tracks[first[i]].flags |= MOV_TRACK_ENABLED;
5951 static void mov_free(AVFormatContext *s)
5953 MOVMuxContext *mov = s->priv_data;
5956 if (mov->chapter_track) {
5957 if (mov->tracks[mov->chapter_track].par)
5958 av_freep(&mov->tracks[mov->chapter_track].par->extradata);
5959 av_freep(&mov->tracks[mov->chapter_track].par);
5962 for (i = 0; i < mov->nb_streams; i++) {
5963 if (mov->tracks[i].tag == MKTAG('r','t','p',' '))
5964 ff_mov_close_hinting(&mov->tracks[i]);
5965 else if (mov->tracks[i].tag == MKTAG('t','m','c','d') && mov->nb_meta_tmcd)
5966 av_freep(&mov->tracks[i].par);
5967 av_freep(&mov->tracks[i].cluster);
5968 av_freep(&mov->tracks[i].frag_info);
5969 av_packet_unref(&mov->tracks[i].cover_image);
5971 if (mov->tracks[i].eac3_priv) {
5972 struct eac3_info *info = mov->tracks[i].eac3_priv;
5973 av_packet_unref(&info->pkt);
5974 av_freep(&mov->tracks[i].eac3_priv);
5976 if (mov->tracks[i].vos_len)
5977 av_freep(&mov->tracks[i].vos_data);
5979 ff_mov_cenc_free(&mov->tracks[i].cenc);
5982 av_freep(&mov->tracks);
5985 static uint32_t rgb_to_yuv(uint32_t rgb)
5990 r = (rgb >> 16) & 0xFF;
5991 g = (rgb >> 8) & 0xFF;
5994 y = av_clip_uint8(( 16000 + 257 * r + 504 * g + 98 * b)/1000);
5995 cb = av_clip_uint8((128000 - 148 * r - 291 * g + 439 * b)/1000);
5996 cr = av_clip_uint8((128000 + 439 * r - 368 * g - 71 * b)/1000);
5998 return (y << 16) | (cr << 8) | cb;
6001 static int mov_create_dvd_sub_decoder_specific_info(MOVTrack *track,
6004 int i, width = 720, height = 480;
6005 int have_palette = 0, have_size = 0;
6006 uint32_t palette[16];
6007 char *cur = st->codecpar->extradata;
6009 while (cur && *cur) {
6010 if (strncmp("palette:", cur, 8) == 0) {
6012 count = sscanf(cur + 8,
6013 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
6014 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
6015 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
6016 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32"",
6017 &palette[ 0], &palette[ 1], &palette[ 2], &palette[ 3],
6018 &palette[ 4], &palette[ 5], &palette[ 6], &palette[ 7],
6019 &palette[ 8], &palette[ 9], &palette[10], &palette[11],
6020 &palette[12], &palette[13], &palette[14], &palette[15]);
6022 for (i = 0; i < count; i++) {
6023 palette[i] = rgb_to_yuv(palette[i]);
6026 } else if (!strncmp("size:", cur, 5)) {
6027 sscanf(cur + 5, "%dx%d", &width, &height);
6030 if (have_palette && have_size)
6032 cur += strcspn(cur, "\n\r");
6033 cur += strspn(cur, "\n\r");
6036 track->vos_data = av_malloc(16*4);
6037 if (!track->vos_data)
6038 return AVERROR(ENOMEM);
6039 for (i = 0; i < 16; i++) {
6040 AV_WB32(track->vos_data + i * 4, palette[i]);
6042 track->vos_len = 16 * 4;
6044 st->codecpar->width = width;
6045 st->codecpar->height = track->height = height;
6050 static int mov_init(AVFormatContext *s)
6052 MOVMuxContext *mov = s->priv_data;
6053 AVDictionaryEntry *global_tcr = av_dict_get(s->metadata, "timecode", NULL, 0);
6058 /* Default mode == MP4 */
6059 mov->mode = MODE_MP4;
6062 if (!strcmp("3gp", s->oformat->name)) mov->mode = MODE_3GP;
6063 else if (!strcmp("3g2", s->oformat->name)) mov->mode = MODE_3GP|MODE_3G2;
6064 else if (!strcmp("mov", s->oformat->name)) mov->mode = MODE_MOV;
6065 else if (!strcmp("psp", s->oformat->name)) mov->mode = MODE_PSP;
6066 else if (!strcmp("ipod",s->oformat->name)) mov->mode = MODE_IPOD;
6067 else if (!strcmp("ismv",s->oformat->name)) mov->mode = MODE_ISM;
6068 else if (!strcmp("f4v", s->oformat->name)) mov->mode = MODE_F4V;
6071 if (mov->flags & FF_MOV_FLAG_DELAY_MOOV)
6072 mov->flags |= FF_MOV_FLAG_EMPTY_MOOV;
6074 /* Set the FRAGMENT flag if any of the fragmentation methods are
6076 if (mov->max_fragment_duration || mov->max_fragment_size ||
6077 mov->flags & (FF_MOV_FLAG_EMPTY_MOOV |
6078 FF_MOV_FLAG_FRAG_KEYFRAME |
6079 FF_MOV_FLAG_FRAG_CUSTOM |
6080 FF_MOV_FLAG_FRAG_EVERY_FRAME))
6081 mov->flags |= FF_MOV_FLAG_FRAGMENT;
6083 /* Set other implicit flags immediately */
6084 if (mov->mode == MODE_ISM)
6085 mov->flags |= FF_MOV_FLAG_EMPTY_MOOV | FF_MOV_FLAG_SEPARATE_MOOF |
6086 FF_MOV_FLAG_FRAGMENT | FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS;
6087 if (mov->flags & FF_MOV_FLAG_DASH)
6088 mov->flags |= FF_MOV_FLAG_FRAGMENT | FF_MOV_FLAG_EMPTY_MOOV |
6089 FF_MOV_FLAG_DEFAULT_BASE_MOOF;
6091 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV && s->flags & AVFMT_FLAG_AUTO_BSF) {
6092 av_log(s, AV_LOG_VERBOSE, "Empty MOOV enabled; disabling automatic bitstream filtering\n");
6093 s->flags &= ~AVFMT_FLAG_AUTO_BSF;
6096 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX && mov->flags & FF_MOV_FLAG_SKIP_SIDX) {
6097 av_log(s, AV_LOG_WARNING, "Global SIDX enabled; Ignoring skip_sidx option\n");
6098 mov->flags &= ~FF_MOV_FLAG_SKIP_SIDX;
6101 if (mov->flags & FF_MOV_FLAG_FASTSTART) {
6102 mov->reserved_moov_size = -1;
6105 if (mov->use_editlist < 0) {
6106 mov->use_editlist = 1;
6107 if (mov->flags & FF_MOV_FLAG_FRAGMENT &&
6108 !(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
6109 // If we can avoid needing an edit list by shifting the
6110 // tracks, prefer that over (trying to) write edit lists
6111 // in fragmented output.
6112 if (s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO ||
6113 s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO)
6114 mov->use_editlist = 0;
6117 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV &&
6118 !(mov->flags & FF_MOV_FLAG_DELAY_MOOV) && mov->use_editlist)
6119 av_log(s, AV_LOG_WARNING, "No meaningful edit list will be written when using empty_moov without delay_moov\n");
6121 if (!mov->use_editlist && s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO)
6122 s->avoid_negative_ts = AVFMT_AVOID_NEG_TS_MAKE_ZERO;
6124 /* Clear the omit_tfhd_offset flag if default_base_moof is set;
6125 * if the latter is set that's enough and omit_tfhd_offset doesn't
6126 * add anything extra on top of that. */
6127 if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET &&
6128 mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)
6129 mov->flags &= ~FF_MOV_FLAG_OMIT_TFHD_OFFSET;
6131 if (mov->frag_interleave &&
6132 mov->flags & (FF_MOV_FLAG_OMIT_TFHD_OFFSET | FF_MOV_FLAG_SEPARATE_MOOF)) {
6133 av_log(s, AV_LOG_ERROR,
6134 "Sample interleaving in fragments is mutually exclusive with "
6135 "omit_tfhd_offset and separate_moof\n");
6136 return AVERROR(EINVAL);
6139 /* Non-seekable output is ok if using fragmentation. If ism_lookahead
6140 * is enabled, we don't support non-seekable output at all. */
6141 if (!(s->pb->seekable & AVIO_SEEKABLE_NORMAL) &&
6142 (!(mov->flags & FF_MOV_FLAG_FRAGMENT) || mov->ism_lookahead)) {
6143 av_log(s, AV_LOG_ERROR, "muxer does not support non seekable output\n");
6144 return AVERROR(EINVAL);
6147 mov->nb_streams = s->nb_streams;
6148 if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters)
6149 mov->chapter_track = mov->nb_streams++;
6151 if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
6152 for (i = 0; i < s->nb_streams; i++)
6153 if (rtp_hinting_needed(s->streams[i]))
6157 if ( mov->write_tmcd == -1 && (mov->mode == MODE_MOV || mov->mode == MODE_MP4)
6158 || mov->write_tmcd == 1) {
6159 /* +1 tmcd track for each video stream with a timecode */
6160 for (i = 0; i < s->nb_streams; i++) {
6161 AVStream *st = s->streams[i];
6162 AVDictionaryEntry *t = global_tcr;
6163 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
6164 (t || (t=av_dict_get(st->metadata, "timecode", NULL, 0)))) {
6166 ret = mov_check_timecode_track(s, &tc, i, t->value);
6168 mov->nb_meta_tmcd++;
6172 /* check if there is already a tmcd track to remux */
6173 if (mov->nb_meta_tmcd) {
6174 for (i = 0; i < s->nb_streams; i++) {
6175 AVStream *st = s->streams[i];
6176 if (st->codecpar->codec_tag == MKTAG('t','m','c','d')) {
6177 av_log(s, AV_LOG_WARNING, "You requested a copy of the original timecode track "
6178 "so timecode metadata are now ignored\n");
6179 mov->nb_meta_tmcd = 0;
6184 mov->nb_streams += mov->nb_meta_tmcd;
6187 // Reserve an extra stream for chapters for the case where chapters
6188 // are written in the trailer
6189 mov->tracks = av_mallocz_array((mov->nb_streams + 1), sizeof(*mov->tracks));
6191 return AVERROR(ENOMEM);
6193 if (mov->encryption_scheme_str != NULL && strcmp(mov->encryption_scheme_str, "none") != 0) {
6194 if (strcmp(mov->encryption_scheme_str, "cenc-aes-ctr") == 0) {
6195 mov->encryption_scheme = MOV_ENC_CENC_AES_CTR;
6197 if (mov->encryption_key_len != AES_CTR_KEY_SIZE) {
6198 av_log(s, AV_LOG_ERROR, "Invalid encryption key len %d expected %d\n",
6199 mov->encryption_key_len, AES_CTR_KEY_SIZE);
6200 return AVERROR(EINVAL);
6203 if (mov->encryption_kid_len != CENC_KID_SIZE) {
6204 av_log(s, AV_LOG_ERROR, "Invalid encryption kid len %d expected %d\n",
6205 mov->encryption_kid_len, CENC_KID_SIZE);
6206 return AVERROR(EINVAL);
6209 av_log(s, AV_LOG_ERROR, "unsupported encryption scheme %s\n",
6210 mov->encryption_scheme_str);
6211 return AVERROR(EINVAL);
6215 for (i = 0; i < s->nb_streams; i++) {
6216 AVStream *st= s->streams[i];
6217 MOVTrack *track= &mov->tracks[i];
6218 AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0);
6221 track->par = st->codecpar;
6222 track->language = ff_mov_iso639_to_lang(lang?lang->value:"und", mov->mode!=MODE_MOV);
6223 if (track->language < 0)
6224 track->language = 0;
6225 track->mode = mov->mode;
6226 track->tag = mov_find_codec_tag(s, track);
6228 av_log(s, AV_LOG_ERROR, "Could not find tag for codec %s in stream #%d, "
6229 "codec not currently supported in container\n",
6230 avcodec_get_name(st->codecpar->codec_id), i);
6231 return AVERROR(EINVAL);
6233 /* If hinting of this track is enabled by a later hint track,
6234 * this is updated. */
6235 track->hint_track = -1;
6236 track->start_dts = AV_NOPTS_VALUE;
6237 track->start_cts = AV_NOPTS_VALUE;
6238 track->end_pts = AV_NOPTS_VALUE;
6239 track->dts_shift = AV_NOPTS_VALUE;
6240 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
6241 if (track->tag == MKTAG('m','x','3','p') || track->tag == MKTAG('m','x','3','n') ||
6242 track->tag == MKTAG('m','x','4','p') || track->tag == MKTAG('m','x','4','n') ||
6243 track->tag == MKTAG('m','x','5','p') || track->tag == MKTAG('m','x','5','n')) {
6244 if (st->codecpar->width != 720 || (st->codecpar->height != 608 && st->codecpar->height != 512)) {
6245 av_log(s, AV_LOG_ERROR, "D-10/IMX must use 720x608 or 720x512 video resolution\n");
6246 return AVERROR(EINVAL);
6248 track->height = track->tag >> 24 == 'n' ? 486 : 576;
6250 if (mov->video_track_timescale) {
6251 track->timescale = mov->video_track_timescale;
6253 track->timescale = st->time_base.den;
6254 while(track->timescale < 10000)
6255 track->timescale *= 2;
6257 if (st->codecpar->width > 65535 || st->codecpar->height > 65535) {
6258 av_log(s, AV_LOG_ERROR, "Resolution %dx%d too large for mov/mp4\n", st->codecpar->width, st->codecpar->height);
6259 return AVERROR(EINVAL);
6261 if (track->mode == MODE_MOV && track->timescale > 100000)
6262 av_log(s, AV_LOG_WARNING,
6263 "WARNING codec timebase is very high. If duration is too long,\n"
6264 "file may not be playable by quicktime. Specify a shorter timebase\n"
6265 "or choose different container.\n");
6266 if (track->mode == MODE_MOV &&
6267 track->par->codec_id == AV_CODEC_ID_RAWVIDEO &&
6268 track->tag == MKTAG('r','a','w',' ')) {
6269 enum AVPixelFormat pix_fmt = track->par->format;
6270 if (pix_fmt == AV_PIX_FMT_NONE && track->par->bits_per_coded_sample == 1)
6271 pix_fmt = AV_PIX_FMT_MONOWHITE;
6272 track->is_unaligned_qt_rgb =
6273 pix_fmt == AV_PIX_FMT_RGB24 ||
6274 pix_fmt == AV_PIX_FMT_BGR24 ||
6275 pix_fmt == AV_PIX_FMT_PAL8 ||
6276 pix_fmt == AV_PIX_FMT_GRAY8 ||
6277 pix_fmt == AV_PIX_FMT_MONOWHITE ||
6278 pix_fmt == AV_PIX_FMT_MONOBLACK;
6280 if (track->par->codec_id == AV_CODEC_ID_VP9 ||
6281 track->par->codec_id == AV_CODEC_ID_AV1) {
6282 if (track->mode != MODE_MP4) {
6283 av_log(s, AV_LOG_ERROR, "%s only supported in MP4.\n", avcodec_get_name(track->par->codec_id));
6284 return AVERROR(EINVAL);
6286 } else if (track->par->codec_id == AV_CODEC_ID_VP8) {
6287 /* altref frames handling is not defined in the spec as of version v1.0,
6288 * so just forbid muxing VP8 streams altogether until a new version does */
6289 av_log(s, AV_LOG_ERROR, "VP8 muxing is currently not supported.\n");
6290 return AVERROR_PATCHWELCOME;
6292 } else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
6293 track->timescale = st->codecpar->sample_rate;
6294 if (!st->codecpar->frame_size && !av_get_bits_per_sample(st->codecpar->codec_id)) {
6295 av_log(s, AV_LOG_WARNING, "track %d: codec frame size is not set\n", i);
6296 track->audio_vbr = 1;
6297 }else if (st->codecpar->codec_id == AV_CODEC_ID_ADPCM_MS ||
6298 st->codecpar->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
6299 st->codecpar->codec_id == AV_CODEC_ID_ILBC){
6300 if (!st->codecpar->block_align) {
6301 av_log(s, AV_LOG_ERROR, "track %d: codec block align is not set for adpcm\n", i);
6302 return AVERROR(EINVAL);
6304 track->sample_size = st->codecpar->block_align;
6305 }else if (st->codecpar->frame_size > 1){ /* assume compressed audio */
6306 track->audio_vbr = 1;
6308 track->sample_size = (av_get_bits_per_sample(st->codecpar->codec_id) >> 3) * st->codecpar->channels;
6310 if (st->codecpar->codec_id == AV_CODEC_ID_ILBC ||
6311 st->codecpar->codec_id == AV_CODEC_ID_ADPCM_IMA_QT) {
6312 track->audio_vbr = 1;
6314 if (track->mode != MODE_MOV &&
6315 track->par->codec_id == AV_CODEC_ID_MP3 && track->timescale < 16000) {
6316 if (s->strict_std_compliance >= FF_COMPLIANCE_NORMAL) {
6317 av_log(s, AV_LOG_ERROR, "track %d: muxing mp3 at %dhz is not standard, to mux anyway set strict to -1\n",
6318 i, track->par->sample_rate);
6319 return AVERROR(EINVAL);
6321 av_log(s, AV_LOG_WARNING, "track %d: muxing mp3 at %dhz is not standard in MP4\n",
6322 i, track->par->sample_rate);
6325 if (track->par->codec_id == AV_CODEC_ID_FLAC ||
6326 track->par->codec_id == AV_CODEC_ID_OPUS) {
6327 if (track->mode != MODE_MP4) {
6328 av_log(s, AV_LOG_ERROR, "%s only supported in MP4.\n", avcodec_get_name(track->par->codec_id));
6329 return AVERROR(EINVAL);
6331 if (s->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
6332 av_log(s, AV_LOG_ERROR,
6333 "%s in MP4 support is experimental, add "
6334 "'-strict %d' if you want to use it.\n",
6335 avcodec_get_name(track->par->codec_id), FF_COMPLIANCE_EXPERIMENTAL);
6336 return AVERROR_EXPERIMENTAL;
6339 } else if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) {
6340 track->timescale = st->time_base.den;
6341 } else if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA) {
6342 track->timescale = st->time_base.den;
6344 track->timescale = MOV_TIMESCALE;
6347 track->height = st->codecpar->height;
6348 /* The ism specific timescale isn't mandatory, but is assumed by
6349 * some tools, such as mp4split. */
6350 if (mov->mode == MODE_ISM)
6351 track->timescale = 10000000;
6353 avpriv_set_pts_info(st, 64, 1, track->timescale);
6355 if (mov->encryption_scheme == MOV_ENC_CENC_AES_CTR) {
6356 ret = ff_mov_cenc_init(&track->cenc, mov->encryption_key,
6357 track->par->codec_id == AV_CODEC_ID_H264, s->flags & AVFMT_FLAG_BITEXACT);
6367 static int mov_write_header(AVFormatContext *s)
6369 AVIOContext *pb = s->pb;
6370 MOVMuxContext *mov = s->priv_data;
6371 AVDictionaryEntry *t, *global_tcr = av_dict_get(s->metadata, "timecode", NULL, 0);
6372 int i, ret, hint_track = 0, tmcd_track = 0, nb_tracks = s->nb_streams;
6374 if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters)
6377 if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
6378 hint_track = nb_tracks;
6379 for (i = 0; i < s->nb_streams; i++)
6380 if (rtp_hinting_needed(s->streams[i]))
6384 if (mov->mode == MODE_MOV || mov->mode == MODE_MP4)
6385 tmcd_track = nb_tracks;
6387 for (i = 0; i < s->nb_streams; i++) {
6389 AVStream *st= s->streams[i];
6390 MOVTrack *track= &mov->tracks[i];
6392 /* copy extradata if it exists */
6393 if (st->codecpar->extradata_size) {
6394 if (st->codecpar->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
6395 mov_create_dvd_sub_decoder_specific_info(track, st);
6396 else if (!TAG_IS_AVCI(track->tag) && st->codecpar->codec_id != AV_CODEC_ID_DNXHD) {
6397 track->vos_len = st->codecpar->extradata_size;
6398 track->vos_data = av_malloc(track->vos_len);
6399 if (!track->vos_data) {
6400 return AVERROR(ENOMEM);
6402 memcpy(track->vos_data, st->codecpar->extradata, track->vos_len);
6406 if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ||
6407 track->par->channel_layout != AV_CH_LAYOUT_MONO)
6410 for (j = 0; j < s->nb_streams; j++) {
6411 AVStream *stj= s->streams[j];
6412 MOVTrack *trackj= &mov->tracks[j];
6416 if (stj->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ||
6417 trackj->par->channel_layout != AV_CH_LAYOUT_MONO ||
6418 trackj->language != track->language ||
6419 trackj->tag != track->tag
6422 track->multichannel_as_mono++;
6426 if (!(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
6427 if ((ret = mov_write_identification(pb, s)) < 0)
6431 if (mov->reserved_moov_size){
6432 mov->reserved_header_pos = avio_tell(pb);
6433 if (mov->reserved_moov_size > 0)
6434 avio_skip(pb, mov->reserved_moov_size);
6437 if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
6438 /* If no fragmentation options have been set, set a default. */
6439 if (!(mov->flags & (FF_MOV_FLAG_FRAG_KEYFRAME |
6440 FF_MOV_FLAG_FRAG_CUSTOM |
6441 FF_MOV_FLAG_FRAG_EVERY_FRAME)) &&
6442 !mov->max_fragment_duration && !mov->max_fragment_size)
6443 mov->flags |= FF_MOV_FLAG_FRAG_KEYFRAME;
6445 if (mov->flags & FF_MOV_FLAG_FASTSTART)
6446 mov->reserved_header_pos = avio_tell(pb);
6447 mov_write_mdat_tag(pb, mov);
6450 ff_parse_creation_time_metadata(s, &mov->time, 1);
6452 mov->time += 0x7C25B080; // 1970 based -> 1904 based
6454 if (mov->chapter_track)
6455 if ((ret = mov_create_chapter_track(s, mov->chapter_track)) < 0)
6458 if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
6459 for (i = 0; i < s->nb_streams; i++) {
6460 if (rtp_hinting_needed(s->streams[i])) {
6461 if ((ret = ff_mov_init_hinting(s, hint_track, i)) < 0)
6468 if (mov->nb_meta_tmcd) {
6469 /* Initialize the tmcd tracks */
6470 for (i = 0; i < s->nb_streams; i++) {
6471 AVStream *st = s->streams[i];
6474 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
6477 t = av_dict_get(st->metadata, "timecode", NULL, 0);
6480 if (mov_check_timecode_track(s, &tc, i, t->value) < 0)
6482 if ((ret = mov_create_timecode_track(s, tmcd_track, i, tc)) < 0)
6491 if (mov->flags & FF_MOV_FLAG_ISML)
6492 mov_write_isml_manifest(pb, mov, s);
6494 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV &&
6495 !(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
6496 if ((ret = mov_write_moov_tag(pb, mov, s)) < 0)
6499 mov->moov_written = 1;
6500 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
6501 mov->reserved_header_pos = avio_tell(pb);
6507 static int get_moov_size(AVFormatContext *s)
6510 AVIOContext *moov_buf;
6511 MOVMuxContext *mov = s->priv_data;
6513 if ((ret = ffio_open_null_buf(&moov_buf)) < 0)
6515 if ((ret = mov_write_moov_tag(moov_buf, mov, s)) < 0)
6517 return ffio_close_null_buf(moov_buf);
6520 static int get_sidx_size(AVFormatContext *s)
6524 MOVMuxContext *mov = s->priv_data;
6526 if ((ret = ffio_open_null_buf(&buf)) < 0)
6528 mov_write_sidx_tags(buf, mov, -1, 0);
6529 return ffio_close_null_buf(buf);
6533 * This function gets the moov size if moved to the top of the file: the chunk
6534 * offset table can switch between stco (32-bit entries) to co64 (64-bit
6535 * entries) when the moov is moved to the beginning, so the size of the moov
6536 * would change. It also updates the chunk offset tables.
6538 static int compute_moov_size(AVFormatContext *s)
6540 int i, moov_size, moov_size2;
6541 MOVMuxContext *mov = s->priv_data;
6543 moov_size = get_moov_size(s);
6547 for (i = 0; i < mov->nb_streams; i++)
6548 mov->tracks[i].data_offset += moov_size;
6550 moov_size2 = get_moov_size(s);
6554 /* if the size changed, we just switched from stco to co64 and need to
6555 * update the offsets */
6556 if (moov_size2 != moov_size)
6557 for (i = 0; i < mov->nb_streams; i++)
6558 mov->tracks[i].data_offset += moov_size2 - moov_size;
6563 static int compute_sidx_size(AVFormatContext *s)
6566 MOVMuxContext *mov = s->priv_data;
6568 sidx_size = get_sidx_size(s);
6572 for (i = 0; i < mov->nb_streams; i++)
6573 mov->tracks[i].data_offset += sidx_size;
6578 static int shift_data(AVFormatContext *s)
6580 int ret = 0, moov_size;
6581 MOVMuxContext *mov = s->priv_data;
6582 int64_t pos, pos_end = avio_tell(s->pb);
6583 uint8_t *buf, *read_buf[2];
6584 int read_buf_id = 0;
6586 AVIOContext *read_pb;
6588 if (mov->flags & FF_MOV_FLAG_FRAGMENT)
6589 moov_size = compute_sidx_size(s);
6591 moov_size = compute_moov_size(s);
6595 buf = av_malloc(moov_size * 2);
6597 return AVERROR(ENOMEM);
6599 read_buf[1] = buf + moov_size;
6601 /* Shift the data: the AVIO context of the output can only be used for
6602 * writing, so we re-open the same output, but for reading. It also avoids
6603 * a read/seek/write/seek back and forth. */
6605 ret = s->io_open(s, &read_pb, s->url, AVIO_FLAG_READ, NULL);
6607 av_log(s, AV_LOG_ERROR, "Unable to re-open %s output file for "
6608 "the second pass (faststart)\n", s->url);
6612 /* mark the end of the shift to up to the last data we wrote, and get ready
6614 pos_end = avio_tell(s->pb);
6615 avio_seek(s->pb, mov->reserved_header_pos + moov_size, SEEK_SET);
6617 /* start reading at where the new moov will be placed */
6618 avio_seek(read_pb, mov->reserved_header_pos, SEEK_SET);
6619 pos = avio_tell(read_pb);
6621 #define READ_BLOCK do { \
6622 read_size[read_buf_id] = avio_read(read_pb, read_buf[read_buf_id], moov_size); \
6626 /* shift data by chunk of at most moov_size */
6631 n = read_size[read_buf_id];
6634 avio_write(s->pb, read_buf[read_buf_id], n);
6636 } while (pos < pos_end);
6637 ff_format_io_close(s, &read_pb);
6644 static int mov_write_trailer(AVFormatContext *s)
6646 MOVMuxContext *mov = s->priv_data;
6647 AVIOContext *pb = s->pb;
6652 if (mov->need_rewrite_extradata) {
6653 for (i = 0; i < s->nb_streams; i++) {
6654 MOVTrack *track = &mov->tracks[i];
6655 AVCodecParameters *par = track->par;
6657 track->vos_len = par->extradata_size;
6658 track->vos_data = av_malloc(track->vos_len);
6659 if (!track->vos_data)
6660 return AVERROR(ENOMEM);
6661 memcpy(track->vos_data, par->extradata, track->vos_len);
6663 mov->need_rewrite_extradata = 0;
6667 * Before actually writing the trailer, make sure that there are no
6668 * dangling subtitles, that need a terminating sample.
6670 for (i = 0; i < mov->nb_streams; i++) {
6671 MOVTrack *trk = &mov->tracks[i];
6672 if (trk->par->codec_id == AV_CODEC_ID_MOV_TEXT &&
6673 !trk->last_sample_is_subtitle_end) {
6674 mov_write_subtitle_end_packet(s, i, trk->track_duration);
6675 trk->last_sample_is_subtitle_end = 1;
6679 // If there were no chapters when the header was written, but there
6680 // are chapters now, write them in the trailer. This only works
6681 // when we are not doing fragments.
6682 if (!mov->chapter_track && !(mov->flags & FF_MOV_FLAG_FRAGMENT)) {
6683 if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters) {
6684 mov->chapter_track = mov->nb_streams++;
6685 if ((res = mov_create_chapter_track(s, mov->chapter_track)) < 0)
6690 if (!(mov->flags & FF_MOV_FLAG_FRAGMENT)) {
6691 moov_pos = avio_tell(pb);
6693 /* Write size of mdat tag */
6694 if (mov->mdat_size + 8 <= UINT32_MAX) {
6695 avio_seek(pb, mov->mdat_pos, SEEK_SET);
6696 avio_wb32(pb, mov->mdat_size + 8);
6698 /* overwrite 'wide' placeholder atom */
6699 avio_seek(pb, mov->mdat_pos - 8, SEEK_SET);
6700 /* special value: real atom size will be 64 bit value after
6703 ffio_wfourcc(pb, "mdat");
6704 avio_wb64(pb, mov->mdat_size + 16);
6706 avio_seek(pb, mov->reserved_moov_size > 0 ? mov->reserved_header_pos : moov_pos, SEEK_SET);
6708 if (mov->flags & FF_MOV_FLAG_FASTSTART) {
6709 av_log(s, AV_LOG_INFO, "Starting second pass: moving the moov atom to the beginning of the file\n");
6710 res = shift_data(s);
6713 avio_seek(pb, mov->reserved_header_pos, SEEK_SET);
6714 if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
6716 } else if (mov->reserved_moov_size > 0) {
6718 if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
6720 size = mov->reserved_moov_size - (avio_tell(pb) - mov->reserved_header_pos);
6722 av_log(s, AV_LOG_ERROR, "reserved_moov_size is too small, needed %"PRId64" additional\n", 8-size);
6723 return AVERROR(EINVAL);
6725 avio_wb32(pb, size);
6726 ffio_wfourcc(pb, "free");
6727 ffio_fill(pb, 0, size - 8);
6728 avio_seek(pb, moov_pos, SEEK_SET);
6730 if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
6735 mov_auto_flush_fragment(s, 1);
6736 for (i = 0; i < mov->nb_streams; i++)
6737 mov->tracks[i].data_offset = 0;
6738 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) {
6740 av_log(s, AV_LOG_INFO, "Starting second pass: inserting sidx atoms\n");
6741 res = shift_data(s);
6744 end = avio_tell(pb);
6745 avio_seek(pb, mov->reserved_header_pos, SEEK_SET);
6746 mov_write_sidx_tags(pb, mov, -1, 0);
6747 avio_seek(pb, end, SEEK_SET);
6748 avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_TRAILER);
6749 mov_write_mfra_tag(pb, mov);
6750 } else if (!(mov->flags & FF_MOV_FLAG_SKIP_TRAILER)) {
6751 avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_TRAILER);
6752 mov_write_mfra_tag(pb, mov);
6759 static int mov_check_bitstream(struct AVFormatContext *s, const AVPacket *pkt)
6762 AVStream *st = s->streams[pkt->stream_index];
6764 if (st->codecpar->codec_id == AV_CODEC_ID_AAC) {
6765 if (pkt->size > 2 && (AV_RB16(pkt->data) & 0xfff0) == 0xfff0)
6766 ret = ff_stream_add_bitstream_filter(st, "aac_adtstoasc", NULL);
6767 } else if (st->codecpar->codec_id == AV_CODEC_ID_VP9) {
6768 ret = ff_stream_add_bitstream_filter(st, "vp9_superframe", NULL);
6774 static const AVCodecTag codec_3gp_tags[] = {
6775 { AV_CODEC_ID_H263, MKTAG('s','2','6','3') },
6776 { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
6777 { AV_CODEC_ID_MPEG4, MKTAG('m','p','4','v') },
6778 { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
6779 { AV_CODEC_ID_AMR_NB, MKTAG('s','a','m','r') },
6780 { AV_CODEC_ID_AMR_WB, MKTAG('s','a','w','b') },
6781 { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
6782 { AV_CODEC_ID_NONE, 0 },
6785 const AVCodecTag codec_mp4_tags[] = {
6786 { AV_CODEC_ID_MPEG4 , MKTAG('m', 'p', '4', 'v') },
6787 { AV_CODEC_ID_H264 , MKTAG('a', 'v', 'c', '1') },
6788 { AV_CODEC_ID_H264 , MKTAG('a', 'v', 'c', '3') },
6789 { AV_CODEC_ID_HEVC , MKTAG('h', 'e', 'v', '1') },
6790 { AV_CODEC_ID_HEVC , MKTAG('h', 'v', 'c', '1') },
6791 { AV_CODEC_ID_MPEG2VIDEO , MKTAG('m', 'p', '4', 'v') },
6792 { AV_CODEC_ID_MPEG1VIDEO , MKTAG('m', 'p', '4', 'v') },
6793 { AV_CODEC_ID_MJPEG , MKTAG('m', 'p', '4', 'v') },
6794 { AV_CODEC_ID_PNG , MKTAG('m', 'p', '4', 'v') },
6795 { AV_CODEC_ID_JPEG2000 , MKTAG('m', 'p', '4', 'v') },
6796 { AV_CODEC_ID_VC1 , MKTAG('v', 'c', '-', '1') },
6797 { AV_CODEC_ID_DIRAC , MKTAG('d', 'r', 'a', 'c') },
6798 { AV_CODEC_ID_TSCC2 , MKTAG('m', 'p', '4', 'v') },
6799 { AV_CODEC_ID_VP9 , MKTAG('v', 'p', '0', '9') },
6800 { AV_CODEC_ID_AV1 , MKTAG('a', 'v', '0', '1') },
6801 { AV_CODEC_ID_AAC , MKTAG('m', 'p', '4', 'a') },
6802 { AV_CODEC_ID_MP4ALS , MKTAG('m', 'p', '4', 'a') },
6803 { AV_CODEC_ID_MP3 , MKTAG('m', 'p', '4', 'a') },
6804 { AV_CODEC_ID_MP2 , MKTAG('m', 'p', '4', 'a') },
6805 { AV_CODEC_ID_AC3 , MKTAG('a', 'c', '-', '3') },
6806 { AV_CODEC_ID_EAC3 , MKTAG('e', 'c', '-', '3') },
6807 { AV_CODEC_ID_DTS , MKTAG('m', 'p', '4', 'a') },
6808 { AV_CODEC_ID_FLAC , MKTAG('f', 'L', 'a', 'C') },
6809 { AV_CODEC_ID_OPUS , MKTAG('O', 'p', 'u', 's') },
6810 { AV_CODEC_ID_VORBIS , MKTAG('m', 'p', '4', 'a') },
6811 { AV_CODEC_ID_QCELP , MKTAG('m', 'p', '4', 'a') },
6812 { AV_CODEC_ID_EVRC , MKTAG('m', 'p', '4', 'a') },
6813 { AV_CODEC_ID_DVD_SUBTITLE, MKTAG('m', 'p', '4', 's') },
6814 { AV_CODEC_ID_MOV_TEXT , MKTAG('t', 'x', '3', 'g') },
6815 { AV_CODEC_ID_BIN_DATA , MKTAG('g', 'p', 'm', 'd') },
6816 { AV_CODEC_ID_NONE , 0 },
6819 const AVCodecTag codec_ism_tags[] = {
6820 { AV_CODEC_ID_WMAPRO , MKTAG('w', 'm', 'a', ' ') },
6821 { AV_CODEC_ID_NONE , 0 },
6824 static const AVCodecTag codec_ipod_tags[] = {
6825 { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
6826 { AV_CODEC_ID_MPEG4, MKTAG('m','p','4','v') },
6827 { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
6828 { AV_CODEC_ID_ALAC, MKTAG('a','l','a','c') },
6829 { AV_CODEC_ID_AC3, MKTAG('a','c','-','3') },
6830 { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
6831 { AV_CODEC_ID_MOV_TEXT, MKTAG('t','e','x','t') },
6832 { AV_CODEC_ID_NONE, 0 },
6835 static const AVCodecTag codec_f4v_tags[] = {
6836 { AV_CODEC_ID_MP3, MKTAG('.','m','p','3') },
6837 { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
6838 { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
6839 { AV_CODEC_ID_VP6A, MKTAG('V','P','6','A') },
6840 { AV_CODEC_ID_VP6F, MKTAG('V','P','6','F') },
6841 { AV_CODEC_ID_NONE, 0 },
6844 #if CONFIG_MOV_MUXER
6846 AVOutputFormat ff_mov_muxer = {
6848 .long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
6849 .extensions = "mov",
6850 .priv_data_size = sizeof(MOVMuxContext),
6851 .audio_codec = AV_CODEC_ID_AAC,
6852 .video_codec = CONFIG_LIBX264_ENCODER ?
6853 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
6855 .write_header = mov_write_header,
6856 .write_packet = mov_write_packet,
6857 .write_trailer = mov_write_trailer,
6859 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6860 .codec_tag = (const AVCodecTag* const []){
6861 ff_codec_movvideo_tags, ff_codec_movaudio_tags, ff_codec_movsubtitle_tags, 0
6863 .check_bitstream = mov_check_bitstream,
6864 .priv_class = &mov_muxer_class,
6867 #if CONFIG_TGP_MUXER
6869 AVOutputFormat ff_tgp_muxer = {
6871 .long_name = NULL_IF_CONFIG_SMALL("3GP (3GPP file format)"),
6872 .extensions = "3gp",
6873 .priv_data_size = sizeof(MOVMuxContext),
6874 .audio_codec = AV_CODEC_ID_AMR_NB,
6875 .video_codec = AV_CODEC_ID_H263,
6877 .write_header = mov_write_header,
6878 .write_packet = mov_write_packet,
6879 .write_trailer = mov_write_trailer,
6881 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6882 .codec_tag = (const AVCodecTag* const []){ codec_3gp_tags, 0 },
6883 .check_bitstream = mov_check_bitstream,
6884 .priv_class = &tgp_muxer_class,
6887 #if CONFIG_MP4_MUXER
6889 AVOutputFormat ff_mp4_muxer = {
6891 .long_name = NULL_IF_CONFIG_SMALL("MP4 (MPEG-4 Part 14)"),
6892 .mime_type = "video/mp4",
6893 .extensions = "mp4",
6894 .priv_data_size = sizeof(MOVMuxContext),
6895 .audio_codec = AV_CODEC_ID_AAC,
6896 .video_codec = CONFIG_LIBX264_ENCODER ?
6897 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
6899 .write_header = mov_write_header,
6900 .write_packet = mov_write_packet,
6901 .write_trailer = mov_write_trailer,
6903 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6904 .codec_tag = (const AVCodecTag* const []){ codec_mp4_tags, 0 },
6905 .check_bitstream = mov_check_bitstream,
6906 .priv_class = &mp4_muxer_class,
6909 #if CONFIG_PSP_MUXER
6911 AVOutputFormat ff_psp_muxer = {
6913 .long_name = NULL_IF_CONFIG_SMALL("PSP MP4 (MPEG-4 Part 14)"),
6914 .extensions = "mp4,psp",
6915 .priv_data_size = sizeof(MOVMuxContext),
6916 .audio_codec = AV_CODEC_ID_AAC,
6917 .video_codec = CONFIG_LIBX264_ENCODER ?
6918 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
6920 .write_header = mov_write_header,
6921 .write_packet = mov_write_packet,
6922 .write_trailer = mov_write_trailer,
6924 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6925 .codec_tag = (const AVCodecTag* const []){ codec_mp4_tags, 0 },
6926 .check_bitstream = mov_check_bitstream,
6927 .priv_class = &psp_muxer_class,
6930 #if CONFIG_TG2_MUXER
6932 AVOutputFormat ff_tg2_muxer = {
6934 .long_name = NULL_IF_CONFIG_SMALL("3GP2 (3GPP2 file format)"),
6935 .extensions = "3g2",
6936 .priv_data_size = sizeof(MOVMuxContext),
6937 .audio_codec = AV_CODEC_ID_AMR_NB,
6938 .video_codec = AV_CODEC_ID_H263,
6940 .write_header = mov_write_header,
6941 .write_packet = mov_write_packet,
6942 .write_trailer = mov_write_trailer,
6944 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6945 .codec_tag = (const AVCodecTag* const []){ codec_3gp_tags, 0 },
6946 .check_bitstream = mov_check_bitstream,
6947 .priv_class = &tg2_muxer_class,
6950 #if CONFIG_IPOD_MUXER
6952 AVOutputFormat ff_ipod_muxer = {
6954 .long_name = NULL_IF_CONFIG_SMALL("iPod H.264 MP4 (MPEG-4 Part 14)"),
6955 .mime_type = "video/mp4",
6956 .extensions = "m4v,m4a,m4b",
6957 .priv_data_size = sizeof(MOVMuxContext),
6958 .audio_codec = AV_CODEC_ID_AAC,
6959 .video_codec = AV_CODEC_ID_H264,
6961 .write_header = mov_write_header,
6962 .write_packet = mov_write_packet,
6963 .write_trailer = mov_write_trailer,
6965 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6966 .codec_tag = (const AVCodecTag* const []){ codec_ipod_tags, 0 },
6967 .check_bitstream = mov_check_bitstream,
6968 .priv_class = &ipod_muxer_class,
6971 #if CONFIG_ISMV_MUXER
6973 AVOutputFormat ff_ismv_muxer = {
6975 .long_name = NULL_IF_CONFIG_SMALL("ISMV/ISMA (Smooth Streaming)"),
6976 .mime_type = "video/mp4",
6977 .extensions = "ismv,isma",
6978 .priv_data_size = sizeof(MOVMuxContext),
6979 .audio_codec = AV_CODEC_ID_AAC,
6980 .video_codec = AV_CODEC_ID_H264,
6982 .write_header = mov_write_header,
6983 .write_packet = mov_write_packet,
6984 .write_trailer = mov_write_trailer,
6986 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6987 .codec_tag = (const AVCodecTag* const []){
6988 codec_mp4_tags, codec_ism_tags, 0 },
6989 .check_bitstream = mov_check_bitstream,
6990 .priv_class = &ismv_muxer_class,
6993 #if CONFIG_F4V_MUXER
6995 AVOutputFormat ff_f4v_muxer = {
6997 .long_name = NULL_IF_CONFIG_SMALL("F4V Adobe Flash Video"),
6998 .mime_type = "application/f4v",
6999 .extensions = "f4v",
7000 .priv_data_size = sizeof(MOVMuxContext),
7001 .audio_codec = AV_CODEC_ID_AAC,
7002 .video_codec = AV_CODEC_ID_H264,
7004 .write_header = mov_write_header,
7005 .write_packet = mov_write_packet,
7006 .write_trailer = mov_write_trailer,
7008 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH,
7009 .codec_tag = (const AVCodecTag* const []){ codec_f4v_tags, 0 },
7010 .check_bitstream = mov_check_bitstream,
7011 .priv_class = &f4v_muxer_class,