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 size = AVERROR(ENOMEM);
559 init_put_bits(&pbc, buf, size);
560 put_bits(&pbc, 13, info->data_rate);
561 put_bits(&pbc, 3, info->num_ind_sub);
562 for (i = 0; i <= info->num_ind_sub; i++) {
563 put_bits(&pbc, 2, info->substream[i].fscod);
564 put_bits(&pbc, 5, info->substream[i].bsid);
565 put_bits(&pbc, 1, 0); /* reserved */
566 put_bits(&pbc, 1, 0); /* asvc */
567 put_bits(&pbc, 3, info->substream[i].bsmod);
568 put_bits(&pbc, 3, info->substream[i].acmod);
569 put_bits(&pbc, 1, info->substream[i].lfeon);
570 put_bits(&pbc, 5, 0); /* reserved */
571 put_bits(&pbc, 4, info->substream[i].num_dep_sub);
572 if (!info->substream[i].num_dep_sub) {
573 put_bits(&pbc, 1, 0); /* reserved */
575 put_bits(&pbc, 9, info->substream[i].chan_loc);
578 flush_put_bits(&pbc);
579 size = put_bits_count(&pbc) >> 3;
581 avio_wb32(pb, size + 8);
582 ffio_wfourcc(pb, "dec3");
583 avio_write(pb, buf, size);
588 av_packet_unref(&info->pkt);
589 av_freep(&track->eac3_priv);
595 * This function writes extradata "as is".
596 * Extradata must be formatted like a valid atom (with size and tag).
598 static int mov_write_extradata_tag(AVIOContext *pb, MOVTrack *track)
600 avio_write(pb, track->par->extradata, track->par->extradata_size);
601 return track->par->extradata_size;
604 static int mov_write_enda_tag(AVIOContext *pb)
607 ffio_wfourcc(pb, "enda");
608 avio_wb16(pb, 1); /* little endian */
612 static int mov_write_enda_tag_be(AVIOContext *pb)
615 ffio_wfourcc(pb, "enda");
616 avio_wb16(pb, 0); /* big endian */
620 static void put_descr(AVIOContext *pb, int tag, unsigned int size)
625 avio_w8(pb, (size >> (7 * i)) | 0x80);
626 avio_w8(pb, size & 0x7F);
629 static unsigned compute_avg_bitrate(MOVTrack *track)
633 if (!track->track_duration)
635 for (i = 0; i < track->entry; i++)
636 size += track->cluster[i].size;
637 return size * 8 * track->timescale / track->track_duration;
640 static int mov_write_esds_tag(AVIOContext *pb, MOVTrack *track) // Basic
642 AVCPBProperties *props;
643 int64_t pos = avio_tell(pb);
644 int decoder_specific_info_len = track->vos_len ? 5 + track->vos_len : 0;
645 unsigned avg_bitrate;
647 avio_wb32(pb, 0); // size
648 ffio_wfourcc(pb, "esds");
649 avio_wb32(pb, 0); // Version
652 put_descr(pb, 0x03, 3 + 5+13 + decoder_specific_info_len + 5+1);
653 avio_wb16(pb, track->track_id);
654 avio_w8(pb, 0x00); // flags (= no flags)
656 // DecoderConfig descriptor
657 put_descr(pb, 0x04, 13 + decoder_specific_info_len);
659 // Object type indication
660 if ((track->par->codec_id == AV_CODEC_ID_MP2 ||
661 track->par->codec_id == AV_CODEC_ID_MP3) &&
662 track->par->sample_rate > 24000)
663 avio_w8(pb, 0x6B); // 11172-3
665 avio_w8(pb, ff_codec_get_tag(ff_mp4_obj_type, track->par->codec_id));
667 // the following fields is made of 6 bits to identify the streamtype (4 for video, 5 for audio)
668 // plus 1 bit to indicate upstream and 1 bit set to 1 (reserved)
669 if (track->par->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
670 avio_w8(pb, (0x38 << 2) | 1); // flags (= NeroSubpicStream)
671 else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
672 avio_w8(pb, 0x15); // flags (= Audiostream)
674 avio_w8(pb, 0x11); // flags (= Visualstream)
676 props = (AVCPBProperties*)av_stream_get_side_data(track->st, AV_PKT_DATA_CPB_PROPERTIES,
679 avio_wb24(pb, props ? props->buffer_size / 8 : 0); // Buffersize DB
681 avg_bitrate = compute_avg_bitrate(track);
682 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)
683 avio_wb32(pb, avg_bitrate);
685 if (track->vos_len) {
686 // DecoderSpecific info descriptor
687 put_descr(pb, 0x05, track->vos_len);
688 avio_write(pb, track->vos_data, track->vos_len);
692 put_descr(pb, 0x06, 1);
694 return update_size(pb, pos);
697 static int mov_pcm_le_gt16(enum AVCodecID codec_id)
699 return codec_id == AV_CODEC_ID_PCM_S24LE ||
700 codec_id == AV_CODEC_ID_PCM_S32LE ||
701 codec_id == AV_CODEC_ID_PCM_F32LE ||
702 codec_id == AV_CODEC_ID_PCM_F64LE;
705 static int mov_pcm_be_gt16(enum AVCodecID codec_id)
707 return codec_id == AV_CODEC_ID_PCM_S24BE ||
708 codec_id == AV_CODEC_ID_PCM_S32BE ||
709 codec_id == AV_CODEC_ID_PCM_F32BE ||
710 codec_id == AV_CODEC_ID_PCM_F64BE;
713 static int mov_write_ms_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
716 int64_t pos = avio_tell(pb);
718 avio_wl32(pb, track->tag); // store it byteswapped
719 track->par->codec_tag = av_bswap16(track->tag >> 16);
720 if ((ret = ff_put_wav_header(s, pb, track->par, 0)) < 0)
722 return update_size(pb, pos);
725 static int mov_write_wfex_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
728 int64_t pos = avio_tell(pb);
730 ffio_wfourcc(pb, "wfex");
731 if ((ret = ff_put_wav_header(s, pb, track->st->codecpar, FF_PUT_WAV_HEADER_FORCE_WAVEFORMATEX)) < 0)
733 return update_size(pb, pos);
736 static int mov_write_dfla_tag(AVIOContext *pb, MOVTrack *track)
738 int64_t pos = avio_tell(pb);
740 ffio_wfourcc(pb, "dfLa");
741 avio_w8(pb, 0); /* version */
742 avio_wb24(pb, 0); /* flags */
744 /* Expect the encoder to pass a METADATA_BLOCK_TYPE_STREAMINFO. */
745 if (track->par->extradata_size != FLAC_STREAMINFO_SIZE)
746 return AVERROR_INVALIDDATA;
748 /* TODO: Write other METADATA_BLOCK_TYPEs if the encoder makes them available. */
749 avio_w8(pb, 1 << 7 | FLAC_METADATA_TYPE_STREAMINFO); /* LastMetadataBlockFlag << 7 | BlockType */
750 avio_wb24(pb, track->par->extradata_size); /* Length */
751 avio_write(pb, track->par->extradata, track->par->extradata_size); /* BlockData[Length] */
753 return update_size(pb, pos);
756 static int mov_write_dops_tag(AVIOContext *pb, MOVTrack *track)
758 int64_t pos = avio_tell(pb);
760 ffio_wfourcc(pb, "dOps");
761 avio_w8(pb, 0); /* Version */
762 if (track->par->extradata_size < 19) {
763 av_log(pb, AV_LOG_ERROR, "invalid extradata size\n");
764 return AVERROR_INVALIDDATA;
766 /* extradata contains an Ogg OpusHead, other than byte-ordering and
767 OpusHead's preceeding magic/version, OpusSpecificBox is currently
769 avio_w8(pb, AV_RB8(track->par->extradata + 9)); /* OuputChannelCount */
770 avio_wb16(pb, AV_RL16(track->par->extradata + 10)); /* PreSkip */
771 avio_wb32(pb, AV_RL32(track->par->extradata + 12)); /* InputSampleRate */
772 avio_wb16(pb, AV_RL16(track->par->extradata + 16)); /* OutputGain */
773 /* Write the rest of the header out without byte-swapping. */
774 avio_write(pb, track->par->extradata + 18, track->par->extradata_size - 18);
776 return update_size(pb, pos);
779 static int mov_write_chan_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
781 uint32_t layout_tag, bitmap;
782 int64_t pos = avio_tell(pb);
784 layout_tag = ff_mov_get_channel_layout_tag(track->par->codec_id,
785 track->par->channel_layout,
788 av_log(s, AV_LOG_WARNING, "not writing 'chan' tag due to "
789 "lack of channel information\n");
793 if (track->multichannel_as_mono)
796 avio_wb32(pb, 0); // Size
797 ffio_wfourcc(pb, "chan"); // Type
798 avio_w8(pb, 0); // Version
799 avio_wb24(pb, 0); // Flags
800 avio_wb32(pb, layout_tag); // mChannelLayoutTag
801 avio_wb32(pb, bitmap); // mChannelBitmap
802 avio_wb32(pb, 0); // mNumberChannelDescriptions
804 return update_size(pb, pos);
807 static int mov_write_wave_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
809 int64_t pos = avio_tell(pb);
811 avio_wb32(pb, 0); /* size */
812 ffio_wfourcc(pb, "wave");
814 if (track->par->codec_id != AV_CODEC_ID_QDM2) {
815 avio_wb32(pb, 12); /* size */
816 ffio_wfourcc(pb, "frma");
817 avio_wl32(pb, track->tag);
820 if (track->par->codec_id == AV_CODEC_ID_AAC) {
821 /* useless atom needed by mplayer, ipod, not needed by quicktime */
822 avio_wb32(pb, 12); /* size */
823 ffio_wfourcc(pb, "mp4a");
825 mov_write_esds_tag(pb, track);
826 } else if (mov_pcm_le_gt16(track->par->codec_id)) {
827 mov_write_enda_tag(pb);
828 } else if (mov_pcm_be_gt16(track->par->codec_id)) {
829 mov_write_enda_tag_be(pb);
830 } else if (track->par->codec_id == AV_CODEC_ID_AMR_NB) {
831 mov_write_amr_tag(pb, track);
832 } else if (track->par->codec_id == AV_CODEC_ID_AC3) {
833 mov_write_ac3_tag(pb, track);
834 } else if (track->par->codec_id == AV_CODEC_ID_EAC3) {
835 mov_write_eac3_tag(pb, track);
836 } else if (track->par->codec_id == AV_CODEC_ID_ALAC ||
837 track->par->codec_id == AV_CODEC_ID_QDM2) {
838 mov_write_extradata_tag(pb, track);
839 } else if (track->par->codec_id == AV_CODEC_ID_ADPCM_MS ||
840 track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) {
841 mov_write_ms_tag(s, pb, track);
844 avio_wb32(pb, 8); /* size */
845 avio_wb32(pb, 0); /* null tag */
847 return update_size(pb, pos);
850 static int mov_write_dvc1_structs(MOVTrack *track, uint8_t *buf)
853 const uint8_t *start, *next, *end = track->vos_data + track->vos_len;
854 int unescaped_size, seq_found = 0;
855 int level = 0, interlace = 0;
856 int packet_seq = track->vc1_info.packet_seq;
857 int packet_entry = track->vc1_info.packet_entry;
858 int slices = track->vc1_info.slices;
861 if (track->start_dts == AV_NOPTS_VALUE) {
862 /* No packets written yet, vc1_info isn't authoritative yet. */
863 /* Assume inline sequence and entry headers. */
864 packet_seq = packet_entry = 1;
865 av_log(NULL, AV_LOG_WARNING,
866 "moov atom written before any packets, unable to write correct "
867 "dvc1 atom. Set the delay_moov flag to fix this.\n");
870 unescaped = av_mallocz(track->vos_len + AV_INPUT_BUFFER_PADDING_SIZE);
872 return AVERROR(ENOMEM);
873 start = find_next_marker(track->vos_data, end);
874 for (next = start; next < end; start = next) {
877 next = find_next_marker(start + 4, end);
878 size = next - start - 4;
881 unescaped_size = vc1_unescape_buffer(start + 4, size, unescaped);
882 init_get_bits(&gb, unescaped, 8 * unescaped_size);
883 if (AV_RB32(start) == VC1_CODE_SEQHDR) {
884 int profile = get_bits(&gb, 2);
885 if (profile != PROFILE_ADVANCED) {
887 return AVERROR(ENOSYS);
890 level = get_bits(&gb, 3);
891 /* chromaformat, frmrtq_postproc, bitrtq_postproc, postprocflag,
893 skip_bits_long(&gb, 2 + 3 + 5 + 1 + 2*12);
894 skip_bits(&gb, 1); /* broadcast */
895 interlace = get_bits1(&gb);
896 skip_bits(&gb, 4); /* tfcntrflag, finterpflag, reserved, psf */
901 return AVERROR(ENOSYS);
904 init_put_bits(&pbc, buf, 7);
905 /* VC1DecSpecStruc */
906 put_bits(&pbc, 4, 12); /* profile - advanced */
907 put_bits(&pbc, 3, level);
908 put_bits(&pbc, 1, 0); /* reserved */
909 /* VC1AdvDecSpecStruc */
910 put_bits(&pbc, 3, level);
911 put_bits(&pbc, 1, 0); /* cbr */
912 put_bits(&pbc, 6, 0); /* reserved */
913 put_bits(&pbc, 1, !interlace); /* no interlace */
914 put_bits(&pbc, 1, !packet_seq); /* no multiple seq */
915 put_bits(&pbc, 1, !packet_entry); /* no multiple entry */
916 put_bits(&pbc, 1, !slices); /* no slice code */
917 put_bits(&pbc, 1, 0); /* no bframe */
918 put_bits(&pbc, 1, 0); /* reserved */
921 if (track->st->avg_frame_rate.num > 0 && track->st->avg_frame_rate.den > 0)
922 put_bits32(&pbc, track->st->avg_frame_rate.num / track->st->avg_frame_rate.den);
924 put_bits32(&pbc, 0xffffffff);
926 flush_put_bits(&pbc);
933 static int mov_write_dvc1_tag(AVIOContext *pb, MOVTrack *track)
935 uint8_t buf[7] = { 0 };
938 if ((ret = mov_write_dvc1_structs(track, buf)) < 0)
941 avio_wb32(pb, track->vos_len + 8 + sizeof(buf));
942 ffio_wfourcc(pb, "dvc1");
943 avio_write(pb, buf, sizeof(buf));
944 avio_write(pb, track->vos_data, track->vos_len);
949 static int mov_write_glbl_tag(AVIOContext *pb, MOVTrack *track)
951 avio_wb32(pb, track->vos_len + 8);
952 ffio_wfourcc(pb, "glbl");
953 avio_write(pb, track->vos_data, track->vos_len);
954 return 8 + track->vos_len;
958 * Compute flags for 'lpcm' tag.
959 * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
961 static int mov_get_lpcm_flags(enum AVCodecID codec_id)
964 case AV_CODEC_ID_PCM_F32BE:
965 case AV_CODEC_ID_PCM_F64BE:
967 case AV_CODEC_ID_PCM_F32LE:
968 case AV_CODEC_ID_PCM_F64LE:
970 case AV_CODEC_ID_PCM_U8:
972 case AV_CODEC_ID_PCM_S16BE:
973 case AV_CODEC_ID_PCM_S24BE:
974 case AV_CODEC_ID_PCM_S32BE:
976 case AV_CODEC_ID_PCM_S8:
977 case AV_CODEC_ID_PCM_S16LE:
978 case AV_CODEC_ID_PCM_S24LE:
979 case AV_CODEC_ID_PCM_S32LE:
986 static int get_cluster_duration(MOVTrack *track, int cluster_idx)
990 if (cluster_idx >= track->entry)
993 if (cluster_idx + 1 == track->entry)
994 next_dts = track->track_duration + track->start_dts;
996 next_dts = track->cluster[cluster_idx + 1].dts;
998 next_dts -= track->cluster[cluster_idx].dts;
1000 av_assert0(next_dts >= 0);
1001 av_assert0(next_dts <= INT_MAX);
1006 static int get_samples_per_packet(MOVTrack *track)
1008 int i, first_duration;
1010 // return track->par->frame_size;
1012 /* use 1 for raw PCM */
1013 if (!track->audio_vbr)
1016 /* check to see if duration is constant for all clusters */
1019 first_duration = get_cluster_duration(track, 0);
1020 for (i = 1; i < track->entry; i++) {
1021 if (get_cluster_duration(track, i) != first_duration)
1024 return first_duration;
1027 static int mov_write_audio_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
1029 int64_t pos = avio_tell(pb);
1031 uint32_t tag = track->tag;
1034 if (track->mode == MODE_MOV) {
1035 if (track->timescale > UINT16_MAX || !track->par->channels) {
1036 if (mov_get_lpcm_flags(track->par->codec_id))
1037 tag = AV_RL32("lpcm");
1039 } else if (track->audio_vbr || mov_pcm_le_gt16(track->par->codec_id) ||
1040 mov_pcm_be_gt16(track->par->codec_id) ||
1041 track->par->codec_id == AV_CODEC_ID_ADPCM_MS ||
1042 track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
1043 track->par->codec_id == AV_CODEC_ID_QDM2) {
1048 avio_wb32(pb, 0); /* size */
1049 if (mov->encryption_scheme != MOV_ENC_NONE) {
1050 ffio_wfourcc(pb, "enca");
1052 avio_wl32(pb, tag); // store it byteswapped
1054 avio_wb32(pb, 0); /* Reserved */
1055 avio_wb16(pb, 0); /* Reserved */
1056 avio_wb16(pb, 1); /* Data-reference index, XXX == 1 */
1058 /* SoundDescription */
1059 avio_wb16(pb, version); /* Version */
1060 avio_wb16(pb, 0); /* Revision level */
1061 avio_wb32(pb, 0); /* Reserved */
1066 avio_wb16(pb, 0xfffe);
1068 avio_wb32(pb, 0x00010000);
1070 avio_wb64(pb, av_double2int(track->par->sample_rate));
1071 avio_wb32(pb, track->par->channels);
1072 avio_wb32(pb, 0x7F000000);
1073 avio_wb32(pb, av_get_bits_per_sample(track->par->codec_id));
1074 avio_wb32(pb, mov_get_lpcm_flags(track->par->codec_id));
1075 avio_wb32(pb, track->sample_size);
1076 avio_wb32(pb, get_samples_per_packet(track));
1078 if (track->mode == MODE_MOV) {
1079 avio_wb16(pb, track->par->channels);
1080 if (track->par->codec_id == AV_CODEC_ID_PCM_U8 ||
1081 track->par->codec_id == AV_CODEC_ID_PCM_S8)
1082 avio_wb16(pb, 8); /* bits per sample */
1083 else if (track->par->codec_id == AV_CODEC_ID_ADPCM_G726)
1084 avio_wb16(pb, track->par->bits_per_coded_sample);
1087 avio_wb16(pb, track->audio_vbr ? -2 : 0); /* compression ID */
1088 } else { /* reserved for mp4/3gp */
1089 if (track->par->codec_id == AV_CODEC_ID_FLAC ||
1090 track->par->codec_id == AV_CODEC_ID_ALAC ||
1091 track->par->codec_id == AV_CODEC_ID_OPUS) {
1092 avio_wb16(pb, track->par->channels);
1096 if (track->par->codec_id == AV_CODEC_ID_FLAC ||
1097 track->par->codec_id == AV_CODEC_ID_ALAC) {
1098 avio_wb16(pb, track->par->bits_per_raw_sample);
1105 avio_wb16(pb, 0); /* packet size (= 0) */
1106 if (track->par->codec_id == AV_CODEC_ID_OPUS)
1107 avio_wb16(pb, 48000);
1109 avio_wb16(pb, track->par->sample_rate <= UINT16_MAX ?
1110 track->par->sample_rate : 0);
1111 avio_wb16(pb, 0); /* Reserved */
1114 if (version == 1) { /* SoundDescription V1 extended info */
1115 if (mov_pcm_le_gt16(track->par->codec_id) ||
1116 mov_pcm_be_gt16(track->par->codec_id))
1117 avio_wb32(pb, 1); /* must be 1 for uncompressed formats */
1119 avio_wb32(pb, track->par->frame_size); /* Samples per packet */
1120 avio_wb32(pb, track->sample_size / track->par->channels); /* Bytes per packet */
1121 avio_wb32(pb, track->sample_size); /* Bytes per frame */
1122 avio_wb32(pb, 2); /* Bytes per sample */
1125 if (track->mode == MODE_MOV &&
1126 (track->par->codec_id == AV_CODEC_ID_AAC ||
1127 track->par->codec_id == AV_CODEC_ID_AC3 ||
1128 track->par->codec_id == AV_CODEC_ID_EAC3 ||
1129 track->par->codec_id == AV_CODEC_ID_AMR_NB ||
1130 track->par->codec_id == AV_CODEC_ID_ALAC ||
1131 track->par->codec_id == AV_CODEC_ID_ADPCM_MS ||
1132 track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
1133 track->par->codec_id == AV_CODEC_ID_QDM2 ||
1134 (mov_pcm_le_gt16(track->par->codec_id) && version==1) ||
1135 (mov_pcm_be_gt16(track->par->codec_id) && version==1)))
1136 ret = mov_write_wave_tag(s, pb, track);
1137 else if (track->tag == MKTAG('m','p','4','a'))
1138 ret = mov_write_esds_tag(pb, track);
1139 else if (track->par->codec_id == AV_CODEC_ID_AMR_NB)
1140 ret = mov_write_amr_tag(pb, track);
1141 else if (track->par->codec_id == AV_CODEC_ID_AC3)
1142 ret = mov_write_ac3_tag(pb, track);
1143 else if (track->par->codec_id == AV_CODEC_ID_EAC3)
1144 ret = mov_write_eac3_tag(pb, track);
1145 else if (track->par->codec_id == AV_CODEC_ID_ALAC)
1146 ret = mov_write_extradata_tag(pb, track);
1147 else if (track->par->codec_id == AV_CODEC_ID_WMAPRO)
1148 ret = mov_write_wfex_tag(s, pb, track);
1149 else if (track->par->codec_id == AV_CODEC_ID_FLAC)
1150 ret = mov_write_dfla_tag(pb, track);
1151 else if (track->par->codec_id == AV_CODEC_ID_OPUS)
1152 ret = mov_write_dops_tag(pb, track);
1153 else if (track->vos_len > 0)
1154 ret = mov_write_glbl_tag(pb, track);
1159 if (track->mode == MODE_MOV && track->par->codec_type == AVMEDIA_TYPE_AUDIO
1160 && ((ret = mov_write_chan_tag(s, pb, track)) < 0)) {
1164 if (mov->encryption_scheme != MOV_ENC_NONE
1165 && ((ret = ff_mov_cenc_write_sinf_tag(track, pb, mov->encryption_kid)) < 0)) {
1169 ret = update_size(pb, pos);
1173 static int mov_write_d263_tag(AVIOContext *pb)
1175 avio_wb32(pb, 0xf); /* size */
1176 ffio_wfourcc(pb, "d263");
1177 ffio_wfourcc(pb, "FFMP");
1178 avio_w8(pb, 0); /* decoder version */
1179 /* FIXME use AVCodecContext level/profile, when encoder will set values */
1180 avio_w8(pb, 0xa); /* level */
1181 avio_w8(pb, 0); /* profile */
1185 static int mov_write_av1c_tag(AVIOContext *pb, MOVTrack *track)
1187 int64_t pos = avio_tell(pb);
1190 ffio_wfourcc(pb, "av1C");
1191 ff_isom_write_av1c(pb, track->vos_data, track->vos_len);
1192 return update_size(pb, pos);
1195 static int mov_write_avcc_tag(AVIOContext *pb, MOVTrack *track)
1197 int64_t pos = avio_tell(pb);
1200 ffio_wfourcc(pb, "avcC");
1201 ff_isom_write_avcc(pb, track->vos_data, track->vos_len);
1202 return update_size(pb, pos);
1205 static int mov_write_vpcc_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
1207 int64_t pos = avio_tell(pb);
1210 ffio_wfourcc(pb, "vpcC");
1211 avio_w8(pb, 1); /* version */
1212 avio_wb24(pb, 0); /* flags */
1213 ff_isom_write_vpcc(s, pb, track->par);
1214 return update_size(pb, pos);
1217 static int mov_write_hvcc_tag(AVIOContext *pb, MOVTrack *track)
1219 int64_t pos = avio_tell(pb);
1222 ffio_wfourcc(pb, "hvcC");
1223 if (track->tag == MKTAG('h','v','c','1'))
1224 ff_isom_write_hvcc(pb, track->vos_data, track->vos_len, 1);
1226 ff_isom_write_hvcc(pb, track->vos_data, track->vos_len, 0);
1227 return update_size(pb, pos);
1230 /* also used by all avid codecs (dv, imx, meridien) and their variants */
1231 static int mov_write_avid_tag(AVIOContext *pb, MOVTrack *track)
1236 int display_width = track->par->width;
1238 if (track->vos_data && track->vos_len > 0x29) {
1239 if (ff_dnxhd_parse_header_prefix(track->vos_data) != 0) {
1240 /* looks like a DNxHD bit stream */
1241 interlaced = (track->vos_data[5] & 2);
1242 cid = AV_RB32(track->vos_data + 0x28);
1244 av_log(NULL, AV_LOG_WARNING, "Could not locate DNxHD bit stream in vos_data\n");
1248 av_log(NULL, AV_LOG_WARNING, "Could not locate DNxHD bit stream, vos_data too small\n");
1252 avio_wb32(pb, 24); /* size */
1253 ffio_wfourcc(pb, "ACLR");
1254 ffio_wfourcc(pb, "ACLR");
1255 ffio_wfourcc(pb, "0001");
1256 if (track->par->color_range == AVCOL_RANGE_MPEG || /* Legal range (16-235) */
1257 track->par->color_range == AVCOL_RANGE_UNSPECIFIED) {
1258 avio_wb32(pb, 1); /* Corresponds to 709 in official encoder */
1259 } else { /* Full range (0-255) */
1260 avio_wb32(pb, 2); /* Corresponds to RGB in official encoder */
1262 avio_wb32(pb, 0); /* unknown */
1264 if (track->tag == MKTAG('A','V','d','h')) {
1266 ffio_wfourcc(pb, "ADHR");
1267 ffio_wfourcc(pb, "0001");
1269 avio_wb32(pb, 0); /* unknown */
1270 avio_wb32(pb, 1); /* unknown */
1271 avio_wb32(pb, 0); /* unknown */
1272 avio_wb32(pb, 0); /* unknown */
1276 avio_wb32(pb, 24); /* size */
1277 ffio_wfourcc(pb, "APRG");
1278 ffio_wfourcc(pb, "APRG");
1279 ffio_wfourcc(pb, "0001");
1280 avio_wb32(pb, 1); /* unknown */
1281 avio_wb32(pb, 0); /* unknown */
1283 avio_wb32(pb, 120); /* size */
1284 ffio_wfourcc(pb, "ARES");
1285 ffio_wfourcc(pb, "ARES");
1286 ffio_wfourcc(pb, "0001");
1287 avio_wb32(pb, cid); /* dnxhd cid, some id ? */
1288 if ( track->par->sample_aspect_ratio.num > 0
1289 && track->par->sample_aspect_ratio.den > 0)
1290 display_width = display_width * track->par->sample_aspect_ratio.num / track->par->sample_aspect_ratio.den;
1291 avio_wb32(pb, display_width);
1292 /* values below are based on samples created with quicktime and avid codecs */
1294 avio_wb32(pb, track->par->height / 2);
1295 avio_wb32(pb, 2); /* unknown */
1296 avio_wb32(pb, 0); /* unknown */
1297 avio_wb32(pb, 4); /* unknown */
1299 avio_wb32(pb, track->par->height);
1300 avio_wb32(pb, 1); /* unknown */
1301 avio_wb32(pb, 0); /* unknown */
1302 if (track->par->height == 1080)
1303 avio_wb32(pb, 5); /* unknown */
1305 avio_wb32(pb, 6); /* unknown */
1308 for (i = 0; i < 10; i++)
1314 static int mov_write_dpxe_tag(AVIOContext *pb, MOVTrack *track)
1317 ffio_wfourcc(pb, "DpxE");
1318 if (track->par->extradata_size >= 12 &&
1319 !memcmp(&track->par->extradata[4], "DpxE", 4)) {
1320 avio_wb32(pb, track->par->extradata[11]);
1327 static int mov_get_dv_codec_tag(AVFormatContext *s, MOVTrack *track)
1331 if (track->par->width == 720) { /* SD */
1332 if (track->par->height == 480) { /* NTSC */
1333 if (track->par->format == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','n');
1334 else tag = MKTAG('d','v','c',' ');
1335 }else if (track->par->format == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','p');
1336 else if (track->par->format == AV_PIX_FMT_YUV420P) tag = MKTAG('d','v','c','p');
1337 else tag = MKTAG('d','v','p','p');
1338 } else if (track->par->height == 720) { /* HD 720 line */
1339 if (track->st->time_base.den == 50) tag = MKTAG('d','v','h','q');
1340 else tag = MKTAG('d','v','h','p');
1341 } else if (track->par->height == 1080) { /* HD 1080 line */
1342 if (track->st->time_base.den == 25) tag = MKTAG('d','v','h','5');
1343 else tag = MKTAG('d','v','h','6');
1345 av_log(s, AV_LOG_ERROR, "unsupported height for dv codec\n");
1352 static AVRational find_fps(AVFormatContext *s, AVStream *st)
1354 AVRational rate = st->avg_frame_rate;
1356 #if FF_API_LAVF_AVCTX
1357 FF_DISABLE_DEPRECATION_WARNINGS
1358 rate = av_inv_q(st->codec->time_base);
1359 if (av_timecode_check_frame_rate(rate) < 0) {
1360 av_log(s, AV_LOG_DEBUG, "timecode: tbc=%d/%d invalid, fallback on %d/%d\n",
1361 rate.num, rate.den, st->avg_frame_rate.num, st->avg_frame_rate.den);
1362 rate = st->avg_frame_rate;
1364 FF_ENABLE_DEPRECATION_WARNINGS
1370 static int defined_frame_rate(AVFormatContext *s, AVStream *st)
1372 AVRational rational_framerate = find_fps(s, st);
1374 if (rational_framerate.den != 0)
1375 rate = av_q2d(rational_framerate);
1379 static int mov_get_mpeg2_xdcam_codec_tag(AVFormatContext *s, MOVTrack *track)
1381 int tag = track->par->codec_tag;
1382 int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE;
1383 AVStream *st = track->st;
1384 int rate = defined_frame_rate(s, st);
1387 tag = MKTAG('m', '2', 'v', '1'); //fallback tag
1389 if (track->par->format == AV_PIX_FMT_YUV420P) {
1390 if (track->par->width == 1280 && track->par->height == 720) {
1392 if (rate == 24) tag = MKTAG('x','d','v','4');
1393 else if (rate == 25) tag = MKTAG('x','d','v','5');
1394 else if (rate == 30) tag = MKTAG('x','d','v','1');
1395 else if (rate == 50) tag = MKTAG('x','d','v','a');
1396 else if (rate == 60) tag = MKTAG('x','d','v','9');
1398 } else if (track->par->width == 1440 && track->par->height == 1080) {
1400 if (rate == 24) tag = MKTAG('x','d','v','6');
1401 else if (rate == 25) tag = MKTAG('x','d','v','7');
1402 else if (rate == 30) tag = MKTAG('x','d','v','8');
1404 if (rate == 25) tag = MKTAG('x','d','v','3');
1405 else if (rate == 30) tag = MKTAG('x','d','v','2');
1407 } else if (track->par->width == 1920 && track->par->height == 1080) {
1409 if (rate == 24) tag = MKTAG('x','d','v','d');
1410 else if (rate == 25) tag = MKTAG('x','d','v','e');
1411 else if (rate == 30) tag = MKTAG('x','d','v','f');
1413 if (rate == 25) tag = MKTAG('x','d','v','c');
1414 else if (rate == 30) tag = MKTAG('x','d','v','b');
1417 } else if (track->par->format == AV_PIX_FMT_YUV422P) {
1418 if (track->par->width == 1280 && track->par->height == 720) {
1420 if (rate == 24) tag = MKTAG('x','d','5','4');
1421 else if (rate == 25) tag = MKTAG('x','d','5','5');
1422 else if (rate == 30) tag = MKTAG('x','d','5','1');
1423 else if (rate == 50) tag = MKTAG('x','d','5','a');
1424 else if (rate == 60) tag = MKTAG('x','d','5','9');
1426 } else if (track->par->width == 1920 && track->par->height == 1080) {
1428 if (rate == 24) tag = MKTAG('x','d','5','d');
1429 else if (rate == 25) tag = MKTAG('x','d','5','e');
1430 else if (rate == 30) tag = MKTAG('x','d','5','f');
1432 if (rate == 25) tag = MKTAG('x','d','5','c');
1433 else if (rate == 30) tag = MKTAG('x','d','5','b');
1441 static int mov_get_h264_codec_tag(AVFormatContext *s, MOVTrack *track)
1443 int tag = track->par->codec_tag;
1444 int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE;
1445 AVStream *st = track->st;
1446 int rate = defined_frame_rate(s, st);
1449 tag = MKTAG('a', 'v', 'c', 'i'); //fallback tag
1451 if (track->par->format == AV_PIX_FMT_YUV420P10) {
1452 if (track->par->width == 960 && track->par->height == 720) {
1454 if (rate == 24) tag = MKTAG('a','i','5','p');
1455 else if (rate == 25) tag = MKTAG('a','i','5','q');
1456 else if (rate == 30) tag = MKTAG('a','i','5','p');
1457 else if (rate == 50) tag = MKTAG('a','i','5','q');
1458 else if (rate == 60) tag = MKTAG('a','i','5','p');
1460 } else if (track->par->width == 1440 && track->par->height == 1080) {
1462 if (rate == 24) tag = MKTAG('a','i','5','3');
1463 else if (rate == 25) tag = MKTAG('a','i','5','2');
1464 else if (rate == 30) tag = MKTAG('a','i','5','3');
1466 if (rate == 50) tag = MKTAG('a','i','5','5');
1467 else if (rate == 60) tag = MKTAG('a','i','5','6');
1470 } else if (track->par->format == AV_PIX_FMT_YUV422P10) {
1471 if (track->par->width == 1280 && track->par->height == 720) {
1473 if (rate == 24) tag = MKTAG('a','i','1','p');
1474 else if (rate == 25) tag = MKTAG('a','i','1','q');
1475 else if (rate == 30) tag = MKTAG('a','i','1','p');
1476 else if (rate == 50) tag = MKTAG('a','i','1','q');
1477 else if (rate == 60) tag = MKTAG('a','i','1','p');
1479 } else if (track->par->width == 1920 && track->par->height == 1080) {
1481 if (rate == 24) tag = MKTAG('a','i','1','3');
1482 else if (rate == 25) tag = MKTAG('a','i','1','2');
1483 else if (rate == 30) tag = MKTAG('a','i','1','3');
1485 if (rate == 25) tag = MKTAG('a','i','1','5');
1486 else if (rate == 50) tag = MKTAG('a','i','1','5');
1487 else if (rate == 60) tag = MKTAG('a','i','1','6');
1489 } else if ( track->par->width == 4096 && track->par->height == 2160
1490 || track->par->width == 3840 && track->par->height == 2160
1491 || track->par->width == 2048 && track->par->height == 1080) {
1492 tag = MKTAG('a','i','v','x');
1499 static const struct {
1500 enum AVPixelFormat pix_fmt;
1503 } mov_pix_fmt_tags[] = {
1504 { AV_PIX_FMT_YUYV422, MKTAG('y','u','v','2'), 0 },
1505 { AV_PIX_FMT_YUYV422, MKTAG('y','u','v','s'), 0 },
1506 { AV_PIX_FMT_UYVY422, MKTAG('2','v','u','y'), 0 },
1507 { AV_PIX_FMT_RGB555BE,MKTAG('r','a','w',' '), 16 },
1508 { AV_PIX_FMT_RGB555LE,MKTAG('L','5','5','5'), 16 },
1509 { AV_PIX_FMT_RGB565LE,MKTAG('L','5','6','5'), 16 },
1510 { AV_PIX_FMT_RGB565BE,MKTAG('B','5','6','5'), 16 },
1511 { AV_PIX_FMT_GRAY16BE,MKTAG('b','1','6','g'), 16 },
1512 { AV_PIX_FMT_RGB24, MKTAG('r','a','w',' '), 24 },
1513 { AV_PIX_FMT_BGR24, MKTAG('2','4','B','G'), 24 },
1514 { AV_PIX_FMT_ARGB, MKTAG('r','a','w',' '), 32 },
1515 { AV_PIX_FMT_BGRA, MKTAG('B','G','R','A'), 32 },
1516 { AV_PIX_FMT_RGBA, MKTAG('R','G','B','A'), 32 },
1517 { AV_PIX_FMT_ABGR, MKTAG('A','B','G','R'), 32 },
1518 { AV_PIX_FMT_RGB48BE, MKTAG('b','4','8','r'), 48 },
1521 static int mov_get_dnxhd_codec_tag(AVFormatContext *s, MOVTrack *track)
1523 int tag = MKTAG('A','V','d','n');
1524 if (track->par->profile != FF_PROFILE_UNKNOWN &&
1525 track->par->profile != FF_PROFILE_DNXHD)
1526 tag = MKTAG('A','V','d','h');
1530 static int mov_get_rawvideo_codec_tag(AVFormatContext *s, MOVTrack *track)
1532 int tag = track->par->codec_tag;
1534 enum AVPixelFormat pix_fmt;
1536 for (i = 0; i < FF_ARRAY_ELEMS(mov_pix_fmt_tags); i++) {
1537 if (track->par->format == mov_pix_fmt_tags[i].pix_fmt) {
1538 tag = mov_pix_fmt_tags[i].tag;
1539 track->par->bits_per_coded_sample = mov_pix_fmt_tags[i].bps;
1540 if (track->par->codec_tag == mov_pix_fmt_tags[i].tag)
1545 pix_fmt = avpriv_find_pix_fmt(avpriv_pix_fmt_bps_mov,
1546 track->par->bits_per_coded_sample);
1547 if (tag == MKTAG('r','a','w',' ') &&
1548 track->par->format != pix_fmt &&
1549 track->par->format != AV_PIX_FMT_GRAY8 &&
1550 track->par->format != AV_PIX_FMT_NONE)
1551 av_log(s, AV_LOG_ERROR, "%s rawvideo cannot be written to mov, output file will be unreadable\n",
1552 av_get_pix_fmt_name(track->par->format));
1556 static unsigned int mov_get_codec_tag(AVFormatContext *s, MOVTrack *track)
1558 unsigned int tag = track->par->codec_tag;
1560 if (!tag || (s->strict_std_compliance >= FF_COMPLIANCE_NORMAL &&
1561 (track->par->codec_id == AV_CODEC_ID_DVVIDEO ||
1562 track->par->codec_id == AV_CODEC_ID_RAWVIDEO ||
1563 track->par->codec_id == AV_CODEC_ID_H263 ||
1564 track->par->codec_id == AV_CODEC_ID_H264 ||
1565 track->par->codec_id == AV_CODEC_ID_DNXHD ||
1566 track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO ||
1567 av_get_bits_per_sample(track->par->codec_id)))) { // pcm audio
1568 if (track->par->codec_id == AV_CODEC_ID_DVVIDEO)
1569 tag = mov_get_dv_codec_tag(s, track);
1570 else if (track->par->codec_id == AV_CODEC_ID_RAWVIDEO)
1571 tag = mov_get_rawvideo_codec_tag(s, track);
1572 else if (track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO)
1573 tag = mov_get_mpeg2_xdcam_codec_tag(s, track);
1574 else if (track->par->codec_id == AV_CODEC_ID_H264)
1575 tag = mov_get_h264_codec_tag(s, track);
1576 else if (track->par->codec_id == AV_CODEC_ID_DNXHD)
1577 tag = mov_get_dnxhd_codec_tag(s, track);
1578 else if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
1579 tag = ff_codec_get_tag(ff_codec_movvideo_tags, track->par->codec_id);
1580 if (!tag) { // if no mac fcc found, try with Microsoft tags
1581 tag = ff_codec_get_tag(ff_codec_bmp_tags, track->par->codec_id);
1583 av_log(s, AV_LOG_WARNING, "Using MS style video codec tag, "
1584 "the file may be unplayable!\n");
1586 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
1587 tag = ff_codec_get_tag(ff_codec_movaudio_tags, track->par->codec_id);
1588 if (!tag) { // if no mac fcc found, try with Microsoft tags
1589 int ms_tag = ff_codec_get_tag(ff_codec_wav_tags, track->par->codec_id);
1591 tag = MKTAG('m', 's', ((ms_tag >> 8) & 0xff), (ms_tag & 0xff));
1592 av_log(s, AV_LOG_WARNING, "Using MS style audio codec tag, "
1593 "the file may be unplayable!\n");
1596 } else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)
1597 tag = ff_codec_get_tag(ff_codec_movsubtitle_tags, track->par->codec_id);
1603 static const AVCodecTag codec_cover_image_tags[] = {
1604 { AV_CODEC_ID_MJPEG, 0xD },
1605 { AV_CODEC_ID_PNG, 0xE },
1606 { AV_CODEC_ID_BMP, 0x1B },
1607 { AV_CODEC_ID_NONE, 0 },
1610 static unsigned int validate_codec_tag(const AVCodecTag *const *tags,
1611 unsigned int tag, int codec_id)
1616 * Check that tag + id is in the table
1618 for (i = 0; tags && tags[i]; i++) {
1619 const AVCodecTag *codec_tags = tags[i];
1620 while (codec_tags->id != AV_CODEC_ID_NONE) {
1621 if (avpriv_toupper4(codec_tags->tag) == avpriv_toupper4(tag) &&
1622 codec_tags->id == codec_id)
1623 return codec_tags->tag;
1630 static unsigned int mov_find_codec_tag(AVFormatContext *s, MOVTrack *track)
1632 if (is_cover_image(track->st))
1633 return ff_codec_get_tag(codec_cover_image_tags, track->par->codec_id);
1635 if (track->mode == MODE_IPOD)
1636 if (!av_match_ext(s->url, "m4a") &&
1637 !av_match_ext(s->url, "m4v") &&
1638 !av_match_ext(s->url, "m4b"))
1639 av_log(s, AV_LOG_WARNING, "Warning, extension is not .m4a nor .m4v "
1640 "Quicktime/Ipod might not play the file\n");
1642 if (track->mode == MODE_MOV) {
1643 return mov_get_codec_tag(s, track);
1645 return validate_codec_tag(s->oformat->codec_tag, track->par->codec_tag,
1646 track->par->codec_id);
1649 /** Write uuid atom.
1650 * Needed to make file play in iPods running newest firmware
1651 * goes after avcC atom in moov.trak.mdia.minf.stbl.stsd.avc1
1653 static int mov_write_uuid_tag_ipod(AVIOContext *pb)
1656 ffio_wfourcc(pb, "uuid");
1657 avio_wb32(pb, 0x6b6840f2);
1658 avio_wb32(pb, 0x5f244fc5);
1659 avio_wb32(pb, 0xba39a51b);
1660 avio_wb32(pb, 0xcf0323f3);
1665 static const uint16_t fiel_data[] = {
1666 0x0000, 0x0100, 0x0201, 0x0206, 0x0209, 0x020e
1669 static int mov_write_fiel_tag(AVIOContext *pb, MOVTrack *track, int field_order)
1671 unsigned mov_field_order = 0;
1672 if (field_order < FF_ARRAY_ELEMS(fiel_data))
1673 mov_field_order = fiel_data[field_order];
1677 ffio_wfourcc(pb, "fiel");
1678 avio_wb16(pb, mov_field_order);
1682 static int mov_write_subtitle_tag(AVIOContext *pb, MOVTrack *track)
1684 int64_t pos = avio_tell(pb);
1685 avio_wb32(pb, 0); /* size */
1686 avio_wl32(pb, track->tag); // store it byteswapped
1687 avio_wb32(pb, 0); /* Reserved */
1688 avio_wb16(pb, 0); /* Reserved */
1689 avio_wb16(pb, 1); /* Data-reference index */
1691 if (track->par->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
1692 mov_write_esds_tag(pb, track);
1693 else if (track->par->extradata_size)
1694 avio_write(pb, track->par->extradata, track->par->extradata_size);
1696 return update_size(pb, pos);
1699 static int mov_write_st3d_tag(AVIOContext *pb, AVStereo3D *stereo_3d)
1703 if (stereo_3d->flags != 0) {
1704 av_log(pb, AV_LOG_WARNING, "Unsupported stereo_3d flags %x. st3d not written.\n", stereo_3d->flags);
1708 switch (stereo_3d->type) {
1709 case AV_STEREO3D_2D:
1712 case AV_STEREO3D_TOPBOTTOM:
1715 case AV_STEREO3D_SIDEBYSIDE:
1719 av_log(pb, AV_LOG_WARNING, "Unsupported stereo_3d type %s. st3d not written.\n", av_stereo3d_type_name(stereo_3d->type));
1722 avio_wb32(pb, 13); /* size */
1723 ffio_wfourcc(pb, "st3d");
1724 avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1725 avio_w8(pb, stereo_mode);
1729 static int mov_write_sv3d_tag(AVFormatContext *s, AVIOContext *pb, AVSphericalMapping *spherical_mapping)
1731 int64_t sv3d_pos, svhd_pos, proj_pos;
1732 const char* metadata_source = s->flags & AVFMT_FLAG_BITEXACT ? "Lavf" : LIBAVFORMAT_IDENT;
1734 if (spherical_mapping->projection != AV_SPHERICAL_EQUIRECTANGULAR &&
1735 spherical_mapping->projection != AV_SPHERICAL_EQUIRECTANGULAR_TILE &&
1736 spherical_mapping->projection != AV_SPHERICAL_CUBEMAP) {
1737 av_log(pb, AV_LOG_WARNING, "Unsupported projection %d. sv3d not written.\n", spherical_mapping->projection);
1741 sv3d_pos = avio_tell(pb);
1742 avio_wb32(pb, 0); /* size */
1743 ffio_wfourcc(pb, "sv3d");
1745 svhd_pos = avio_tell(pb);
1746 avio_wb32(pb, 0); /* size */
1747 ffio_wfourcc(pb, "svhd");
1748 avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1749 avio_put_str(pb, metadata_source);
1750 update_size(pb, svhd_pos);
1752 proj_pos = avio_tell(pb);
1753 avio_wb32(pb, 0); /* size */
1754 ffio_wfourcc(pb, "proj");
1756 avio_wb32(pb, 24); /* size */
1757 ffio_wfourcc(pb, "prhd");
1758 avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1759 avio_wb32(pb, spherical_mapping->yaw);
1760 avio_wb32(pb, spherical_mapping->pitch);
1761 avio_wb32(pb, spherical_mapping->roll);
1763 switch (spherical_mapping->projection) {
1764 case AV_SPHERICAL_EQUIRECTANGULAR:
1765 case AV_SPHERICAL_EQUIRECTANGULAR_TILE:
1766 avio_wb32(pb, 28); /* size */
1767 ffio_wfourcc(pb, "equi");
1768 avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1769 avio_wb32(pb, spherical_mapping->bound_top);
1770 avio_wb32(pb, spherical_mapping->bound_bottom);
1771 avio_wb32(pb, spherical_mapping->bound_left);
1772 avio_wb32(pb, spherical_mapping->bound_right);
1774 case AV_SPHERICAL_CUBEMAP:
1775 avio_wb32(pb, 20); /* size */
1776 ffio_wfourcc(pb, "cbmp");
1777 avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1778 avio_wb32(pb, 0); /* layout */
1779 avio_wb32(pb, spherical_mapping->padding); /* padding */
1782 update_size(pb, proj_pos);
1784 return update_size(pb, sv3d_pos);
1787 static int mov_write_clap_tag(AVIOContext *pb, MOVTrack *track)
1790 ffio_wfourcc(pb, "clap");
1791 avio_wb32(pb, track->par->width); /* apertureWidth_N */
1792 avio_wb32(pb, 1); /* apertureWidth_D (= 1) */
1793 avio_wb32(pb, track->height); /* apertureHeight_N */
1794 avio_wb32(pb, 1); /* apertureHeight_D (= 1) */
1795 avio_wb32(pb, 0); /* horizOff_N (= 0) */
1796 avio_wb32(pb, 1); /* horizOff_D (= 1) */
1797 avio_wb32(pb, 0); /* vertOff_N (= 0) */
1798 avio_wb32(pb, 1); /* vertOff_D (= 1) */
1802 static int mov_write_pasp_tag(AVIOContext *pb, MOVTrack *track)
1805 av_reduce(&sar.num, &sar.den, track->par->sample_aspect_ratio.num,
1806 track->par->sample_aspect_ratio.den, INT_MAX);
1809 ffio_wfourcc(pb, "pasp");
1810 avio_wb32(pb, sar.num);
1811 avio_wb32(pb, sar.den);
1815 static int mov_write_gama_tag(AVIOContext *pb, MOVTrack *track, double gamma)
1820 gamma = avpriv_get_gamma_from_trc(track->par->color_trc);
1822 av_log(pb, AV_LOG_DEBUG, "gamma value %g\n", gamma);
1825 gama = (uint32_t)lrint((double)(1<<16) * gamma);
1826 av_log(pb, AV_LOG_DEBUG, "writing gama value %"PRId32"\n", gama);
1828 av_assert0(track->mode == MODE_MOV);
1830 ffio_wfourcc(pb, "gama");
1831 avio_wb32(pb, gama);
1835 av_log(pb, AV_LOG_WARNING, "gamma value unknown, unable to write gama atom\n");
1840 static int mov_write_colr_tag(AVIOContext *pb, MOVTrack *track)
1842 // Ref (MOV): https://developer.apple.com/library/mac/technotes/tn2162/_index.html#//apple_ref/doc/uid/DTS40013070-CH1-TNTAG9
1843 // Ref (MP4): ISO/IEC 14496-12:2012
1845 if (track->par->color_primaries == AVCOL_PRI_UNSPECIFIED &&
1846 track->par->color_trc == AVCOL_TRC_UNSPECIFIED &&
1847 track->par->color_space == AVCOL_SPC_UNSPECIFIED) {
1848 if ((track->par->width >= 1920 && track->par->height >= 1080)
1849 || (track->par->width == 1280 && track->par->height == 720)) {
1850 av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming bt709\n");
1851 track->par->color_primaries = AVCOL_PRI_BT709;
1852 } else if (track->par->width == 720 && track->height == 576) {
1853 av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming bt470bg\n");
1854 track->par->color_primaries = AVCOL_PRI_BT470BG;
1855 } else if (track->par->width == 720 &&
1856 (track->height == 486 || track->height == 480)) {
1857 av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming smpte170\n");
1858 track->par->color_primaries = AVCOL_PRI_SMPTE170M;
1860 av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, unable to assume anything\n");
1862 switch (track->par->color_primaries) {
1863 case AVCOL_PRI_BT709:
1864 track->par->color_trc = AVCOL_TRC_BT709;
1865 track->par->color_space = AVCOL_SPC_BT709;
1867 case AVCOL_PRI_SMPTE170M:
1868 case AVCOL_PRI_BT470BG:
1869 track->par->color_trc = AVCOL_TRC_BT709;
1870 track->par->color_space = AVCOL_SPC_SMPTE170M;
1875 /* We should only ever be called by MOV or MP4. */
1876 av_assert0(track->mode == MODE_MOV || track->mode == MODE_MP4);
1878 avio_wb32(pb, 18 + (track->mode == MODE_MP4));
1879 ffio_wfourcc(pb, "colr");
1880 if (track->mode == MODE_MP4)
1881 ffio_wfourcc(pb, "nclx");
1883 ffio_wfourcc(pb, "nclc");
1884 switch (track->par->color_primaries) {
1885 case AVCOL_PRI_BT709: avio_wb16(pb, 1); break;
1886 case AVCOL_PRI_BT470BG: avio_wb16(pb, 5); break;
1887 case AVCOL_PRI_SMPTE170M:
1888 case AVCOL_PRI_SMPTE240M: avio_wb16(pb, 6); break;
1889 case AVCOL_PRI_BT2020: avio_wb16(pb, 9); break;
1890 case AVCOL_PRI_SMPTE431: avio_wb16(pb, 11); break;
1891 case AVCOL_PRI_SMPTE432: avio_wb16(pb, 12); break;
1892 default: avio_wb16(pb, 2);
1894 switch (track->par->color_trc) {
1895 case AVCOL_TRC_BT709: avio_wb16(pb, 1); break;
1896 case AVCOL_TRC_SMPTE170M: avio_wb16(pb, 1); break; // remapped
1897 case AVCOL_TRC_SMPTE240M: avio_wb16(pb, 7); break;
1898 case AVCOL_TRC_SMPTEST2084: avio_wb16(pb, 16); break;
1899 case AVCOL_TRC_SMPTE428: avio_wb16(pb, 17); break;
1900 case AVCOL_TRC_ARIB_STD_B67: avio_wb16(pb, 18); break;
1901 default: avio_wb16(pb, 2);
1903 switch (track->par->color_space) {
1904 case AVCOL_SPC_BT709: avio_wb16(pb, 1); break;
1905 case AVCOL_SPC_BT470BG:
1906 case AVCOL_SPC_SMPTE170M: avio_wb16(pb, 6); break;
1907 case AVCOL_SPC_SMPTE240M: avio_wb16(pb, 7); break;
1908 case AVCOL_SPC_BT2020_NCL: avio_wb16(pb, 9); break;
1909 default: avio_wb16(pb, 2);
1912 if (track->mode == MODE_MP4) {
1913 int full_range = track->par->color_range == AVCOL_RANGE_JPEG;
1914 avio_w8(pb, full_range << 7);
1921 static void find_compressor(char * compressor_name, int len, MOVTrack *track)
1923 AVDictionaryEntry *encoder;
1924 int xdcam_res = (track->par->width == 1280 && track->par->height == 720)
1925 || (track->par->width == 1440 && track->par->height == 1080)
1926 || (track->par->width == 1920 && track->par->height == 1080);
1928 if (track->mode == MODE_MOV &&
1929 (encoder = av_dict_get(track->st->metadata, "encoder", NULL, 0))) {
1930 av_strlcpy(compressor_name, encoder->value, 32);
1931 } else if (track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO && xdcam_res) {
1932 int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE;
1933 AVStream *st = track->st;
1934 int rate = defined_frame_rate(NULL, st);
1935 av_strlcatf(compressor_name, len, "XDCAM");
1936 if (track->par->format == AV_PIX_FMT_YUV422P) {
1937 av_strlcatf(compressor_name, len, " HD422");
1938 } else if(track->par->width == 1440) {
1939 av_strlcatf(compressor_name, len, " HD");
1941 av_strlcatf(compressor_name, len, " EX");
1943 av_strlcatf(compressor_name, len, " %d%c", track->par->height, interlaced ? 'i' : 'p');
1945 av_strlcatf(compressor_name, len, "%d", rate * (interlaced + 1));
1949 static int mov_write_video_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
1951 int64_t pos = avio_tell(pb);
1952 char compressor_name[32] = { 0 };
1955 int uncompressed_ycbcr = ((track->par->codec_id == AV_CODEC_ID_RAWVIDEO && track->par->format == AV_PIX_FMT_UYVY422)
1956 || (track->par->codec_id == AV_CODEC_ID_RAWVIDEO && track->par->format == AV_PIX_FMT_YUYV422)
1957 || track->par->codec_id == AV_CODEC_ID_V308
1958 || track->par->codec_id == AV_CODEC_ID_V408
1959 || track->par->codec_id == AV_CODEC_ID_V410
1960 || track->par->codec_id == AV_CODEC_ID_V210);
1962 avio_wb32(pb, 0); /* size */
1963 if (mov->encryption_scheme != MOV_ENC_NONE) {
1964 ffio_wfourcc(pb, "encv");
1966 avio_wl32(pb, track->tag); // store it byteswapped
1968 avio_wb32(pb, 0); /* Reserved */
1969 avio_wb16(pb, 0); /* Reserved */
1970 avio_wb16(pb, 1); /* Data-reference index */
1972 if (uncompressed_ycbcr) {
1973 avio_wb16(pb, 2); /* Codec stream version */
1975 avio_wb16(pb, 0); /* Codec stream version */
1977 avio_wb16(pb, 0); /* Codec stream revision (=0) */
1978 if (track->mode == MODE_MOV) {
1979 ffio_wfourcc(pb, "FFMP"); /* Vendor */
1980 if (track->par->codec_id == AV_CODEC_ID_RAWVIDEO || uncompressed_ycbcr) {
1981 avio_wb32(pb, 0); /* Temporal Quality */
1982 avio_wb32(pb, 0x400); /* Spatial Quality = lossless*/
1984 avio_wb32(pb, 0x200); /* Temporal Quality = normal */
1985 avio_wb32(pb, 0x200); /* Spatial Quality = normal */
1988 avio_wb32(pb, 0); /* Reserved */
1989 avio_wb32(pb, 0); /* Reserved */
1990 avio_wb32(pb, 0); /* Reserved */
1992 avio_wb16(pb, track->par->width); /* Video width */
1993 avio_wb16(pb, track->height); /* Video height */
1994 avio_wb32(pb, 0x00480000); /* Horizontal resolution 72dpi */
1995 avio_wb32(pb, 0x00480000); /* Vertical resolution 72dpi */
1996 avio_wb32(pb, 0); /* Data size (= 0) */
1997 avio_wb16(pb, 1); /* Frame count (= 1) */
1999 /* FIXME not sure, ISO 14496-1 draft where it shall be set to 0 */
2000 find_compressor(compressor_name, 32, track);
2001 avio_w8(pb, strlen(compressor_name));
2002 avio_write(pb, compressor_name, 31);
2004 if (track->mode == MODE_MOV &&
2005 (track->par->codec_id == AV_CODEC_ID_V410 || track->par->codec_id == AV_CODEC_ID_V210))
2006 avio_wb16(pb, 0x18);
2007 else if (track->mode == MODE_MOV && track->par->bits_per_coded_sample)
2008 avio_wb16(pb, track->par->bits_per_coded_sample |
2009 (track->par->format == AV_PIX_FMT_GRAY8 ? 0x20 : 0));
2011 avio_wb16(pb, 0x18); /* Reserved */
2013 if (track->mode == MODE_MOV && track->par->format == AV_PIX_FMT_PAL8) {
2014 int pal_size = 1 << track->par->bits_per_coded_sample;
2016 avio_wb16(pb, 0); /* Color table ID */
2017 avio_wb32(pb, 0); /* Color table seed */
2018 avio_wb16(pb, 0x8000); /* Color table flags */
2019 avio_wb16(pb, pal_size - 1); /* Color table size (zero-relative) */
2020 for (i = 0; i < pal_size; i++) {
2021 uint32_t rgb = track->palette[i];
2022 uint16_t r = (rgb >> 16) & 0xff;
2023 uint16_t g = (rgb >> 8) & 0xff;
2024 uint16_t b = rgb & 0xff;
2026 avio_wb16(pb, (r << 8) | r);
2027 avio_wb16(pb, (g << 8) | g);
2028 avio_wb16(pb, (b << 8) | b);
2031 avio_wb16(pb, 0xffff); /* Reserved */
2033 if (track->tag == MKTAG('m','p','4','v'))
2034 mov_write_esds_tag(pb, track);
2035 else if (track->par->codec_id == AV_CODEC_ID_H263)
2036 mov_write_d263_tag(pb);
2037 else if (track->par->codec_id == AV_CODEC_ID_AVUI ||
2038 track->par->codec_id == AV_CODEC_ID_SVQ3) {
2039 mov_write_extradata_tag(pb, track);
2041 } else if (track->par->codec_id == AV_CODEC_ID_DNXHD) {
2042 mov_write_avid_tag(pb, track);
2044 } else if (track->par->codec_id == AV_CODEC_ID_HEVC)
2045 mov_write_hvcc_tag(pb, track);
2046 else if (track->par->codec_id == AV_CODEC_ID_H264 && !TAG_IS_AVCI(track->tag)) {
2047 mov_write_avcc_tag(pb, track);
2048 if (track->mode == MODE_IPOD)
2049 mov_write_uuid_tag_ipod(pb);
2050 } else if (track->par->codec_id == AV_CODEC_ID_VP9) {
2051 mov_write_vpcc_tag(mov->fc, pb, track);
2052 } else if (track->par->codec_id == AV_CODEC_ID_AV1) {
2053 mov_write_av1c_tag(pb, track);
2054 } else if (track->par->codec_id == AV_CODEC_ID_VC1 && track->vos_len > 0)
2055 mov_write_dvc1_tag(pb, track);
2056 else if (track->par->codec_id == AV_CODEC_ID_VP6F ||
2057 track->par->codec_id == AV_CODEC_ID_VP6A) {
2058 /* Don't write any potential extradata here - the cropping
2059 * is signalled via the normal width/height fields. */
2060 } else if (track->par->codec_id == AV_CODEC_ID_R10K) {
2061 if (track->par->codec_tag == MKTAG('R','1','0','k'))
2062 mov_write_dpxe_tag(pb, track);
2063 } else if (track->vos_len > 0)
2064 mov_write_glbl_tag(pb, track);
2066 if (track->par->codec_id != AV_CODEC_ID_H264 &&
2067 track->par->codec_id != AV_CODEC_ID_MPEG4 &&
2068 track->par->codec_id != AV_CODEC_ID_DNXHD) {
2069 int field_order = track->par->field_order;
2071 #if FF_API_LAVF_AVCTX
2072 FF_DISABLE_DEPRECATION_WARNINGS
2073 if (field_order != track->st->codec->field_order && track->st->codec->field_order != AV_FIELD_UNKNOWN)
2074 field_order = track->st->codec->field_order;
2075 FF_ENABLE_DEPRECATION_WARNINGS
2078 if (field_order != AV_FIELD_UNKNOWN)
2079 mov_write_fiel_tag(pb, track, field_order);
2082 if (mov->flags & FF_MOV_FLAG_WRITE_GAMA) {
2083 if (track->mode == MODE_MOV)
2084 mov_write_gama_tag(pb, track, mov->gamma);
2086 av_log(mov->fc, AV_LOG_WARNING, "Not writing 'gama' atom. Format is not MOV.\n");
2088 if (mov->flags & FF_MOV_FLAG_WRITE_COLR) {
2089 if (track->mode == MODE_MOV || track->mode == MODE_MP4)
2090 mov_write_colr_tag(pb, track);
2092 av_log(mov->fc, AV_LOG_WARNING, "Not writing 'colr' atom. Format is not MOV or MP4.\n");
2095 if (track->mode == MODE_MP4 && mov->fc->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL) {
2096 AVStereo3D* stereo_3d = (AVStereo3D*) av_stream_get_side_data(track->st, AV_PKT_DATA_STEREO3D, NULL);
2097 AVSphericalMapping* spherical_mapping = (AVSphericalMapping*)av_stream_get_side_data(track->st, AV_PKT_DATA_SPHERICAL, NULL);
2100 mov_write_st3d_tag(pb, stereo_3d);
2101 if (spherical_mapping)
2102 mov_write_sv3d_tag(mov->fc, pb, spherical_mapping);
2105 if (track->par->sample_aspect_ratio.den && track->par->sample_aspect_ratio.num) {
2106 mov_write_pasp_tag(pb, track);
2109 if (uncompressed_ycbcr){
2110 mov_write_clap_tag(pb, track);
2113 if (mov->encryption_scheme != MOV_ENC_NONE) {
2114 ff_mov_cenc_write_sinf_tag(track, pb, mov->encryption_kid);
2117 /* extra padding for avid stsd */
2118 /* https://developer.apple.com/library/mac/documentation/QuickTime/QTFF/QTFFChap2/qtff2.html#//apple_ref/doc/uid/TP40000939-CH204-61112 */
2122 return update_size(pb, pos);
2125 static int mov_write_rtp_tag(AVIOContext *pb, MOVTrack *track)
2127 int64_t pos = avio_tell(pb);
2128 avio_wb32(pb, 0); /* size */
2129 ffio_wfourcc(pb, "rtp ");
2130 avio_wb32(pb, 0); /* Reserved */
2131 avio_wb16(pb, 0); /* Reserved */
2132 avio_wb16(pb, 1); /* Data-reference index */
2134 avio_wb16(pb, 1); /* Hint track version */
2135 avio_wb16(pb, 1); /* Highest compatible version */
2136 avio_wb32(pb, track->max_packet_size); /* Max packet size */
2138 avio_wb32(pb, 12); /* size */
2139 ffio_wfourcc(pb, "tims");
2140 avio_wb32(pb, track->timescale);
2142 return update_size(pb, pos);
2145 static int mov_write_source_reference_tag(AVIOContext *pb, MOVTrack *track, const char *reel_name)
2147 uint64_t str_size =strlen(reel_name);
2148 int64_t pos = avio_tell(pb);
2150 if (str_size >= UINT16_MAX){
2151 av_log(NULL, AV_LOG_ERROR, "reel_name length %"PRIu64" is too large\n", str_size);
2153 return AVERROR(EINVAL);
2156 avio_wb32(pb, 0); /* size */
2157 ffio_wfourcc(pb, "name"); /* Data format */
2158 avio_wb16(pb, str_size); /* string size */
2159 avio_wb16(pb, track->language); /* langcode */
2160 avio_write(pb, reel_name, str_size); /* reel name */
2161 return update_size(pb,pos);
2164 static int mov_write_tmcd_tag(AVIOContext *pb, MOVTrack *track)
2166 int64_t pos = avio_tell(pb);
2170 AVDictionaryEntry *t = NULL;
2172 if (!track->st->avg_frame_rate.num || !track->st->avg_frame_rate.den) {
2173 #if FF_API_LAVF_AVCTX
2174 FF_DISABLE_DEPRECATION_WARNINGS
2175 frame_duration = av_rescale(track->timescale, track->st->codec->time_base.num, track->st->codec->time_base.den);
2176 nb_frames = ROUNDED_DIV(track->st->codec->time_base.den, track->st->codec->time_base.num);
2177 FF_ENABLE_DEPRECATION_WARNINGS
2179 av_log(NULL, AV_LOG_ERROR, "avg_frame_rate not set for tmcd track.\n");
2180 return AVERROR(EINVAL);
2183 frame_duration = av_rescale(track->timescale, track->st->avg_frame_rate.num, track->st->avg_frame_rate.den);
2184 nb_frames = ROUNDED_DIV(track->st->avg_frame_rate.den, track->st->avg_frame_rate.num);
2187 if (nb_frames > 255) {
2188 av_log(NULL, AV_LOG_ERROR, "fps %d is too large\n", nb_frames);
2189 return AVERROR(EINVAL);
2192 avio_wb32(pb, 0); /* size */
2193 ffio_wfourcc(pb, "tmcd"); /* Data format */
2194 avio_wb32(pb, 0); /* Reserved */
2195 avio_wb32(pb, 1); /* Data reference index */
2196 avio_wb32(pb, 0); /* Flags */
2197 avio_wb32(pb, track->timecode_flags); /* Flags (timecode) */
2198 avio_wb32(pb, track->timescale); /* Timescale */
2199 avio_wb32(pb, frame_duration); /* Frame duration */
2200 avio_w8(pb, nb_frames); /* Number of frames */
2201 avio_w8(pb, 0); /* Reserved */
2203 t = av_dict_get(track->st->metadata, "reel_name", NULL, 0);
2204 if (t && utf8len(t->value) && track->mode != MODE_MP4)
2205 mov_write_source_reference_tag(pb, track, t->value);
2207 avio_wb16(pb, 0); /* zero size */
2210 avio_wb32(pb, 0); /* size */
2211 ffio_wfourcc(pb, "tmcd"); /* Data format */
2212 avio_wb32(pb, 0); /* Reserved */
2213 avio_wb32(pb, 1); /* Data reference index */
2214 if (track->par->extradata_size)
2215 avio_write(pb, track->par->extradata, track->par->extradata_size);
2217 return update_size(pb, pos);
2220 static int mov_write_gpmd_tag(AVIOContext *pb, const MOVTrack *track)
2222 int64_t pos = avio_tell(pb);
2223 avio_wb32(pb, 0); /* size */
2224 ffio_wfourcc(pb, "gpmd");
2225 avio_wb32(pb, 0); /* Reserved */
2226 avio_wb16(pb, 0); /* Reserved */
2227 avio_wb16(pb, 1); /* Data-reference index */
2228 avio_wb32(pb, 0); /* Reserved */
2229 return update_size(pb, pos);
2232 static int mov_write_stsd_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
2234 int64_t pos = avio_tell(pb);
2236 avio_wb32(pb, 0); /* size */
2237 ffio_wfourcc(pb, "stsd");
2238 avio_wb32(pb, 0); /* version & flags */
2239 avio_wb32(pb, 1); /* entry count */
2240 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO)
2241 ret = mov_write_video_tag(pb, mov, track);
2242 else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
2243 ret = mov_write_audio_tag(s, pb, mov, track);
2244 else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)
2245 ret = mov_write_subtitle_tag(pb, track);
2246 else if (track->par->codec_tag == MKTAG('r','t','p',' '))
2247 ret = mov_write_rtp_tag(pb, track);
2248 else if (track->par->codec_tag == MKTAG('t','m','c','d'))
2249 ret = mov_write_tmcd_tag(pb, track);
2250 else if (track->par->codec_tag == MKTAG('g','p','m','d'))
2251 ret = mov_write_gpmd_tag(pb, track);
2256 return update_size(pb, pos);
2259 static int mov_write_ctts_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
2261 MOVMuxContext *mov = s->priv_data;
2262 MOVStts *ctts_entries;
2263 uint32_t entries = 0;
2267 ctts_entries = av_malloc_array((track->entry + 1), sizeof(*ctts_entries)); /* worst case */
2269 return AVERROR(ENOMEM);
2270 ctts_entries[0].count = 1;
2271 ctts_entries[0].duration = track->cluster[0].cts;
2272 for (i = 1; i < track->entry; i++) {
2273 if (track->cluster[i].cts == ctts_entries[entries].duration) {
2274 ctts_entries[entries].count++; /* compress */
2277 ctts_entries[entries].duration = track->cluster[i].cts;
2278 ctts_entries[entries].count = 1;
2281 entries++; /* last one */
2282 atom_size = 16 + (entries * 8);
2283 avio_wb32(pb, atom_size); /* size */
2284 ffio_wfourcc(pb, "ctts");
2285 if (mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS)
2286 avio_w8(pb, 1); /* version */
2288 avio_w8(pb, 0); /* version */
2289 avio_wb24(pb, 0); /* flags */
2290 avio_wb32(pb, entries); /* entry count */
2291 for (i = 0; i < entries; i++) {
2292 avio_wb32(pb, ctts_entries[i].count);
2293 avio_wb32(pb, ctts_entries[i].duration);
2295 av_free(ctts_entries);
2299 /* Time to sample atom */
2300 static int mov_write_stts_tag(AVIOContext *pb, MOVTrack *track)
2302 MOVStts *stts_entries = NULL;
2303 uint32_t entries = -1;
2307 if (track->par->codec_type == AVMEDIA_TYPE_AUDIO && !track->audio_vbr) {
2308 stts_entries = av_malloc(sizeof(*stts_entries)); /* one entry */
2310 return AVERROR(ENOMEM);
2311 stts_entries[0].count = track->sample_count;
2312 stts_entries[0].duration = 1;
2316 stts_entries = av_malloc_array(track->entry, sizeof(*stts_entries)); /* worst case */
2318 return AVERROR(ENOMEM);
2320 for (i = 0; i < track->entry; i++) {
2321 int duration = get_cluster_duration(track, i);
2322 if (i && duration == stts_entries[entries].duration) {
2323 stts_entries[entries].count++; /* compress */
2326 stts_entries[entries].duration = duration;
2327 stts_entries[entries].count = 1;
2330 entries++; /* last one */
2332 atom_size = 16 + (entries * 8);
2333 avio_wb32(pb, atom_size); /* size */
2334 ffio_wfourcc(pb, "stts");
2335 avio_wb32(pb, 0); /* version & flags */
2336 avio_wb32(pb, entries); /* entry count */
2337 for (i = 0; i < entries; i++) {
2338 avio_wb32(pb, stts_entries[i].count);
2339 avio_wb32(pb, stts_entries[i].duration);
2341 av_free(stts_entries);
2345 static int mov_write_dref_tag(AVIOContext *pb)
2347 avio_wb32(pb, 28); /* size */
2348 ffio_wfourcc(pb, "dref");
2349 avio_wb32(pb, 0); /* version & flags */
2350 avio_wb32(pb, 1); /* entry count */
2352 avio_wb32(pb, 0xc); /* size */
2353 //FIXME add the alis and rsrc atom
2354 ffio_wfourcc(pb, "url ");
2355 avio_wb32(pb, 1); /* version & flags */
2360 static int mov_preroll_write_stbl_atoms(AVIOContext *pb, MOVTrack *track)
2364 int16_t roll_distance;
2365 int group_description_index;
2368 struct sgpd_entry *sgpd_entries = NULL;
2373 const int OPUS_SEEK_PREROLL_MS = 80;
2374 int roll_samples = av_rescale_q(OPUS_SEEK_PREROLL_MS,
2375 (AVRational){1, 1000},
2376 (AVRational){1, 48000});
2381 sgpd_entries = av_malloc_array(track->entry, sizeof(*sgpd_entries));
2383 return AVERROR(ENOMEM);
2385 av_assert0(track->par->codec_id == AV_CODEC_ID_OPUS || track->par->codec_id == AV_CODEC_ID_AAC);
2387 if (track->par->codec_id == AV_CODEC_ID_OPUS) {
2388 for (i = 0; i < track->entry; i++) {
2389 int roll_samples_remaining = roll_samples;
2391 for (j = i - 1; j >= 0; j--) {
2392 roll_samples_remaining -= get_cluster_duration(track, j);
2394 if (roll_samples_remaining <= 0)
2397 /* We don't have enough preceeding samples to compute a valid
2398 roll_distance here, so this sample can't be independently
2400 if (roll_samples_remaining > 0)
2402 /* Verify distance is a maximum of 32 (2.5ms) packets. */
2404 return AVERROR_INVALIDDATA;
2405 if (i && distance == sgpd_entries[entries].roll_distance) {
2406 sgpd_entries[entries].count++;
2409 sgpd_entries[entries].count = 1;
2410 sgpd_entries[entries].roll_distance = distance;
2411 sgpd_entries[entries].group_description_index = distance ? ++group : 0;
2416 sgpd_entries[entries].count = track->sample_count;
2417 sgpd_entries[entries].roll_distance = 1;
2418 sgpd_entries[entries].group_description_index = ++group;
2423 av_free(sgpd_entries);
2427 /* Write sgpd tag */
2428 avio_wb32(pb, 24 + (group * 2)); /* size */
2429 ffio_wfourcc(pb, "sgpd");
2430 avio_wb32(pb, 1 << 24); /* fullbox */
2431 ffio_wfourcc(pb, "roll");
2432 avio_wb32(pb, 2); /* default_length */
2433 avio_wb32(pb, group); /* entry_count */
2434 for (i = 0; i < entries; i++) {
2435 if (sgpd_entries[i].group_description_index) {
2436 avio_wb16(pb, -sgpd_entries[i].roll_distance); /* roll_distance */
2440 /* Write sbgp tag */
2441 avio_wb32(pb, 20 + (entries * 8)); /* size */
2442 ffio_wfourcc(pb, "sbgp");
2443 avio_wb32(pb, 0); /* fullbox */
2444 ffio_wfourcc(pb, "roll");
2445 avio_wb32(pb, entries); /* entry_count */
2446 for (i = 0; i < entries; i++) {
2447 avio_wb32(pb, sgpd_entries[i].count); /* sample_count */
2448 avio_wb32(pb, sgpd_entries[i].group_description_index); /* group_description_index */
2451 av_free(sgpd_entries);
2455 static int mov_write_stbl_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
2457 int64_t pos = avio_tell(pb);
2460 avio_wb32(pb, 0); /* size */
2461 ffio_wfourcc(pb, "stbl");
2462 if ((ret = mov_write_stsd_tag(s, pb, mov, track)) < 0)
2464 mov_write_stts_tag(pb, track);
2465 if ((track->par->codec_type == AVMEDIA_TYPE_VIDEO ||
2466 track->par->codec_tag == MKTAG('r','t','p',' ')) &&
2467 track->has_keyframes && track->has_keyframes < track->entry)
2468 mov_write_stss_tag(pb, track, MOV_SYNC_SAMPLE);
2469 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO && track->has_disposable)
2470 mov_write_sdtp_tag(pb, track);
2471 if (track->mode == MODE_MOV && track->flags & MOV_TRACK_STPS)
2472 mov_write_stss_tag(pb, track, MOV_PARTIAL_SYNC_SAMPLE);
2473 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO &&
2474 track->flags & MOV_TRACK_CTTS && track->entry) {
2476 if ((ret = mov_write_ctts_tag(s, pb, track)) < 0)
2479 mov_write_stsc_tag(pb, track);
2480 mov_write_stsz_tag(pb, track);
2481 mov_write_stco_tag(pb, track);
2482 if (track->cenc.aes_ctr) {
2483 ff_mov_cenc_write_stbl_atoms(&track->cenc, pb);
2485 if (track->par->codec_id == AV_CODEC_ID_OPUS || track->par->codec_id == AV_CODEC_ID_AAC) {
2486 mov_preroll_write_stbl_atoms(pb, track);
2488 return update_size(pb, pos);
2491 static int mov_write_dinf_tag(AVIOContext *pb)
2493 int64_t pos = avio_tell(pb);
2494 avio_wb32(pb, 0); /* size */
2495 ffio_wfourcc(pb, "dinf");
2496 mov_write_dref_tag(pb);
2497 return update_size(pb, pos);
2500 static int mov_write_nmhd_tag(AVIOContext *pb)
2503 ffio_wfourcc(pb, "nmhd");
2508 static int mov_write_tcmi_tag(AVIOContext *pb, MOVTrack *track)
2510 int64_t pos = avio_tell(pb);
2511 const char *font = "Lucida Grande";
2512 avio_wb32(pb, 0); /* size */
2513 ffio_wfourcc(pb, "tcmi"); /* timecode media information atom */
2514 avio_wb32(pb, 0); /* version & flags */
2515 avio_wb16(pb, 0); /* text font */
2516 avio_wb16(pb, 0); /* text face */
2517 avio_wb16(pb, 12); /* text size */
2518 avio_wb16(pb, 0); /* (unknown, not in the QT specs...) */
2519 avio_wb16(pb, 0x0000); /* text color (red) */
2520 avio_wb16(pb, 0x0000); /* text color (green) */
2521 avio_wb16(pb, 0x0000); /* text color (blue) */
2522 avio_wb16(pb, 0xffff); /* background color (red) */
2523 avio_wb16(pb, 0xffff); /* background color (green) */
2524 avio_wb16(pb, 0xffff); /* background color (blue) */
2525 avio_w8(pb, strlen(font)); /* font len (part of the pascal string) */
2526 avio_write(pb, font, strlen(font)); /* font name */
2527 return update_size(pb, pos);
2530 static int mov_write_gmhd_tag(AVIOContext *pb, MOVTrack *track)
2532 int64_t pos = avio_tell(pb);
2533 avio_wb32(pb, 0); /* size */
2534 ffio_wfourcc(pb, "gmhd");
2535 avio_wb32(pb, 0x18); /* gmin size */
2536 ffio_wfourcc(pb, "gmin");/* generic media info */
2537 avio_wb32(pb, 0); /* version & flags */
2538 avio_wb16(pb, 0x40); /* graphics mode = */
2539 avio_wb16(pb, 0x8000); /* opColor (r?) */
2540 avio_wb16(pb, 0x8000); /* opColor (g?) */
2541 avio_wb16(pb, 0x8000); /* opColor (b?) */
2542 avio_wb16(pb, 0); /* balance */
2543 avio_wb16(pb, 0); /* reserved */
2546 * This special text atom is required for
2547 * Apple Quicktime chapters. The contents
2548 * don't appear to be documented, so the
2549 * bytes are copied verbatim.
2551 if (track->tag != MKTAG('c','6','0','8')) {
2552 avio_wb32(pb, 0x2C); /* size */
2553 ffio_wfourcc(pb, "text");
2554 avio_wb16(pb, 0x01);
2555 avio_wb32(pb, 0x00);
2556 avio_wb32(pb, 0x00);
2557 avio_wb32(pb, 0x00);
2558 avio_wb32(pb, 0x01);
2559 avio_wb32(pb, 0x00);
2560 avio_wb32(pb, 0x00);
2561 avio_wb32(pb, 0x00);
2562 avio_wb32(pb, 0x00004000);
2563 avio_wb16(pb, 0x0000);
2566 if (track->par->codec_tag == MKTAG('t','m','c','d')) {
2567 int64_t tmcd_pos = avio_tell(pb);
2568 avio_wb32(pb, 0); /* size */
2569 ffio_wfourcc(pb, "tmcd");
2570 mov_write_tcmi_tag(pb, track);
2571 update_size(pb, tmcd_pos);
2572 } else if (track->par->codec_tag == MKTAG('g','p','m','d')) {
2573 int64_t gpmd_pos = avio_tell(pb);
2574 avio_wb32(pb, 0); /* size */
2575 ffio_wfourcc(pb, "gpmd");
2576 avio_wb32(pb, 0); /* version */
2577 update_size(pb, gpmd_pos);
2579 return update_size(pb, pos);
2582 static int mov_write_smhd_tag(AVIOContext *pb)
2584 avio_wb32(pb, 16); /* size */
2585 ffio_wfourcc(pb, "smhd");
2586 avio_wb32(pb, 0); /* version & flags */
2587 avio_wb16(pb, 0); /* reserved (balance, normally = 0) */
2588 avio_wb16(pb, 0); /* reserved */
2592 static int mov_write_vmhd_tag(AVIOContext *pb)
2594 avio_wb32(pb, 0x14); /* size (always 0x14) */
2595 ffio_wfourcc(pb, "vmhd");
2596 avio_wb32(pb, 0x01); /* version & flags */
2597 avio_wb64(pb, 0); /* reserved (graphics mode = copy) */
2601 static int is_clcp_track(MOVTrack *track)
2603 return track->tag == MKTAG('c','7','0','8') ||
2604 track->tag == MKTAG('c','6','0','8');
2607 static int mov_write_hdlr_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
2609 MOVMuxContext *mov = s->priv_data;
2610 const char *hdlr, *descr = NULL, *hdlr_type = NULL;
2611 int64_t pos = avio_tell(pb);
2615 descr = "DataHandler";
2618 hdlr = (track->mode == MODE_MOV) ? "mhlr" : "\0\0\0\0";
2619 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
2621 descr = "VideoHandler";
2622 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
2624 descr = "SoundHandler";
2625 } else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE) {
2626 if (is_clcp_track(track)) {
2628 descr = "ClosedCaptionHandler";
2630 if (track->tag == MKTAG('t','x','3','g')) {
2632 } else if (track->tag == MKTAG('m','p','4','s')) {
2637 descr = "SubtitleHandler";
2639 } else if (track->par->codec_tag == MKTAG('r','t','p',' ')) {
2641 descr = "HintHandler";
2642 } else if (track->par->codec_tag == MKTAG('t','m','c','d')) {
2644 descr = "TimeCodeHandler";
2645 } else if (track->par->codec_tag == MKTAG('g','p','m','d')) {
2647 descr = "GoPro MET"; // GoPro Metadata
2649 av_log(s, AV_LOG_WARNING,
2650 "Unknown hldr_type for %s, writing dummy values\n",
2651 av_fourcc2str(track->par->codec_tag));
2654 // hdlr.name is used by some players to identify the content title
2655 // of the track. So if an alternate handler description is
2656 // specified, use it.
2657 AVDictionaryEntry *t;
2658 t = av_dict_get(track->st->metadata, "handler_name", NULL, 0);
2659 if (t && utf8len(t->value))
2664 if (mov->empty_hdlr_name) /* expressly allowed by QTFF and not prohibited in ISO 14496-12 8.4.3.3 */
2667 avio_wb32(pb, 0); /* size */
2668 ffio_wfourcc(pb, "hdlr");
2669 avio_wb32(pb, 0); /* Version & flags */
2670 avio_write(pb, hdlr, 4); /* handler */
2671 ffio_wfourcc(pb, hdlr_type); /* handler type */
2672 avio_wb32(pb, 0); /* reserved */
2673 avio_wb32(pb, 0); /* reserved */
2674 avio_wb32(pb, 0); /* reserved */
2675 if (!track || track->mode == MODE_MOV)
2676 avio_w8(pb, strlen(descr)); /* pascal string */
2677 avio_write(pb, descr, strlen(descr)); /* handler description */
2678 if (track && track->mode != MODE_MOV)
2679 avio_w8(pb, 0); /* c string */
2680 return update_size(pb, pos);
2683 static int mov_write_hmhd_tag(AVIOContext *pb)
2685 /* This atom must be present, but leaving the values at zero
2686 * seems harmless. */
2687 avio_wb32(pb, 28); /* size */
2688 ffio_wfourcc(pb, "hmhd");
2689 avio_wb32(pb, 0); /* version, flags */
2690 avio_wb16(pb, 0); /* maxPDUsize */
2691 avio_wb16(pb, 0); /* avgPDUsize */
2692 avio_wb32(pb, 0); /* maxbitrate */
2693 avio_wb32(pb, 0); /* avgbitrate */
2694 avio_wb32(pb, 0); /* reserved */
2698 static int mov_write_minf_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
2700 int64_t pos = avio_tell(pb);
2703 avio_wb32(pb, 0); /* size */
2704 ffio_wfourcc(pb, "minf");
2705 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO)
2706 mov_write_vmhd_tag(pb);
2707 else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
2708 mov_write_smhd_tag(pb);
2709 else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE) {
2710 if (track->tag == MKTAG('t','e','x','t') || is_clcp_track(track)) {
2711 mov_write_gmhd_tag(pb, track);
2713 mov_write_nmhd_tag(pb);
2715 } else if (track->tag == MKTAG('r','t','p',' ')) {
2716 mov_write_hmhd_tag(pb);
2717 } else if (track->tag == MKTAG('t','m','c','d')) {
2718 if (track->mode != MODE_MOV)
2719 mov_write_nmhd_tag(pb);
2721 mov_write_gmhd_tag(pb, track);
2722 } else if (track->tag == MKTAG('g','p','m','d')) {
2723 mov_write_gmhd_tag(pb, track);
2725 if (track->mode == MODE_MOV) /* ISO 14496-12 8.4.3.1 specifies hdlr only within mdia or meta boxes */
2726 mov_write_hdlr_tag(s, pb, NULL);
2727 mov_write_dinf_tag(pb);
2728 if ((ret = mov_write_stbl_tag(s, pb, mov, track)) < 0)
2730 return update_size(pb, pos);
2733 static int mov_write_mdhd_tag(AVIOContext *pb, MOVMuxContext *mov,
2736 int version = track->track_duration < INT32_MAX ? 0 : 1;
2738 if (track->mode == MODE_ISM)
2741 (version == 1) ? avio_wb32(pb, 44) : avio_wb32(pb, 32); /* size */
2742 ffio_wfourcc(pb, "mdhd");
2743 avio_w8(pb, version);
2744 avio_wb24(pb, 0); /* flags */
2746 avio_wb64(pb, track->time);
2747 avio_wb64(pb, track->time);
2749 avio_wb32(pb, track->time); /* creation time */
2750 avio_wb32(pb, track->time); /* modification time */
2752 avio_wb32(pb, track->timescale); /* time scale (sample rate for audio) */
2753 if (!track->entry && mov->mode == MODE_ISM)
2754 (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
2755 else if (!track->entry)
2756 (version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0);
2758 (version == 1) ? avio_wb64(pb, track->track_duration) : avio_wb32(pb, track->track_duration); /* duration */
2759 avio_wb16(pb, track->language); /* language */
2760 avio_wb16(pb, 0); /* reserved (quality) */
2762 if (version != 0 && track->mode == MODE_MOV) {
2763 av_log(NULL, AV_LOG_ERROR,
2764 "FATAL error, file duration too long for timebase, this file will not be\n"
2765 "playable with QuickTime. Choose a different timebase with "
2766 "-video_track_timescale or a different container format\n");
2772 static int mov_write_mdia_tag(AVFormatContext *s, AVIOContext *pb,
2773 MOVMuxContext *mov, MOVTrack *track)
2775 int64_t pos = avio_tell(pb);
2778 avio_wb32(pb, 0); /* size */
2779 ffio_wfourcc(pb, "mdia");
2780 mov_write_mdhd_tag(pb, mov, track);
2781 mov_write_hdlr_tag(s, pb, track);
2782 if ((ret = mov_write_minf_tag(s, pb, mov, track)) < 0)
2784 return update_size(pb, pos);
2787 /* transformation matrix
2791 static void write_matrix(AVIOContext *pb, int16_t a, int16_t b, int16_t c,
2792 int16_t d, int16_t tx, int16_t ty)
2794 avio_wb32(pb, a << 16); /* 16.16 format */
2795 avio_wb32(pb, b << 16); /* 16.16 format */
2796 avio_wb32(pb, 0); /* u in 2.30 format */
2797 avio_wb32(pb, c << 16); /* 16.16 format */
2798 avio_wb32(pb, d << 16); /* 16.16 format */
2799 avio_wb32(pb, 0); /* v in 2.30 format */
2800 avio_wb32(pb, tx << 16); /* 16.16 format */
2801 avio_wb32(pb, ty << 16); /* 16.16 format */
2802 avio_wb32(pb, 1 << 30); /* w in 2.30 format */
2805 static int mov_write_tkhd_tag(AVIOContext *pb, MOVMuxContext *mov,
2806 MOVTrack *track, AVStream *st)
2808 int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE,
2809 track->timescale, AV_ROUND_UP);
2810 int version = duration < INT32_MAX ? 0 : 1;
2811 int flags = MOV_TKHD_FLAG_IN_MOVIE;
2815 uint32_t *display_matrix = NULL;
2816 int display_matrix_size, i;
2819 if (mov->per_stream_grouping)
2822 group = st->codecpar->codec_type;
2824 display_matrix = (uint32_t*)av_stream_get_side_data(st, AV_PKT_DATA_DISPLAYMATRIX,
2825 &display_matrix_size);
2826 if (display_matrix && display_matrix_size < 9 * sizeof(*display_matrix))
2827 display_matrix = NULL;
2830 if (track->flags & MOV_TRACK_ENABLED)
2831 flags |= MOV_TKHD_FLAG_ENABLED;
2833 if (track->mode == MODE_ISM)
2836 (version == 1) ? avio_wb32(pb, 104) : avio_wb32(pb, 92); /* size */
2837 ffio_wfourcc(pb, "tkhd");
2838 avio_w8(pb, version);
2839 avio_wb24(pb, flags);
2841 avio_wb64(pb, track->time);
2842 avio_wb64(pb, track->time);
2844 avio_wb32(pb, track->time); /* creation time */
2845 avio_wb32(pb, track->time); /* modification time */
2847 avio_wb32(pb, track->track_id); /* track-id */
2848 avio_wb32(pb, 0); /* reserved */
2849 if (!track->entry && mov->mode == MODE_ISM)
2850 (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
2851 else if (!track->entry)
2852 (version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0);
2854 (version == 1) ? avio_wb64(pb, duration) : avio_wb32(pb, duration);
2856 avio_wb32(pb, 0); /* reserved */
2857 avio_wb32(pb, 0); /* reserved */
2858 avio_wb16(pb, 0); /* layer */
2859 avio_wb16(pb, group); /* alternate group) */
2860 /* Volume, only for audio */
2861 if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
2862 avio_wb16(pb, 0x0100);
2865 avio_wb16(pb, 0); /* reserved */
2867 /* Matrix structure */
2868 #if FF_API_OLD_ROTATE_API
2869 if (st && st->metadata) {
2870 AVDictionaryEntry *rot = av_dict_get(st->metadata, "rotate", NULL, 0);
2871 rotation = (rot && rot->value) ? atoi(rot->value) : 0;
2874 if (display_matrix) {
2875 for (i = 0; i < 9; i++)
2876 avio_wb32(pb, display_matrix[i]);
2877 #if FF_API_OLD_ROTATE_API
2878 } else if (rotation == 90) {
2879 write_matrix(pb, 0, 1, -1, 0, track->par->height, 0);
2880 } else if (rotation == 180) {
2881 write_matrix(pb, -1, 0, 0, -1, track->par->width, track->par->height);
2882 } else if (rotation == 270) {
2883 write_matrix(pb, 0, -1, 1, 0, 0, track->par->width);
2886 write_matrix(pb, 1, 0, 0, 1, 0, 0);
2888 /* Track width and height, for visual only */
2889 if (st && (track->par->codec_type == AVMEDIA_TYPE_VIDEO ||
2890 track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)) {
2891 int64_t track_width_1616;
2892 if (track->mode == MODE_MOV) {
2893 track_width_1616 = track->par->width * 0x10000ULL;
2895 track_width_1616 = av_rescale(st->sample_aspect_ratio.num,
2896 track->par->width * 0x10000LL,
2897 st->sample_aspect_ratio.den);
2898 if (!track_width_1616 ||
2899 track->height != track->par->height ||
2900 track_width_1616 > UINT32_MAX)
2901 track_width_1616 = track->par->width * 0x10000ULL;
2903 if (track_width_1616 > UINT32_MAX) {
2904 av_log(mov->fc, AV_LOG_WARNING, "track width is too large\n");
2905 track_width_1616 = 0;
2907 avio_wb32(pb, track_width_1616);
2908 if (track->height > 0xFFFF) {
2909 av_log(mov->fc, AV_LOG_WARNING, "track height is too large\n");
2912 avio_wb32(pb, track->height * 0x10000U);
2920 static int mov_write_tapt_tag(AVIOContext *pb, MOVTrack *track)
2922 int32_t width = av_rescale(track->par->sample_aspect_ratio.num, track->par->width,
2923 track->par->sample_aspect_ratio.den);
2925 int64_t pos = avio_tell(pb);
2927 avio_wb32(pb, 0); /* size */
2928 ffio_wfourcc(pb, "tapt");
2931 ffio_wfourcc(pb, "clef");
2933 avio_wb32(pb, width << 16);
2934 avio_wb32(pb, track->par->height << 16);
2937 ffio_wfourcc(pb, "prof");
2939 avio_wb32(pb, width << 16);
2940 avio_wb32(pb, track->par->height << 16);
2943 ffio_wfourcc(pb, "enof");
2945 avio_wb32(pb, track->par->width << 16);
2946 avio_wb32(pb, track->par->height << 16);
2948 return update_size(pb, pos);
2951 // This box seems important for the psp playback ... without it the movie seems to hang
2952 static int mov_write_edts_tag(AVIOContext *pb, MOVMuxContext *mov,
2955 int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE,
2956 track->timescale, AV_ROUND_UP);
2957 int version = duration < INT32_MAX ? 0 : 1;
2958 int entry_size, entry_count, size;
2959 int64_t delay, start_ct = track->start_cts;
2960 int64_t start_dts = track->start_dts;
2963 if (start_dts != track->cluster[0].dts || start_ct != track->cluster[0].cts) {
2965 av_log(mov->fc, AV_LOG_DEBUG,
2966 "EDTS using dts:%"PRId64" cts:%d instead of dts:%"PRId64" cts:%"PRId64" tid:%d\n",
2967 track->cluster[0].dts, track->cluster[0].cts,
2968 start_dts, start_ct, track->track_id);
2969 start_dts = track->cluster[0].dts;
2970 start_ct = track->cluster[0].cts;
2974 delay = av_rescale_rnd(start_dts + start_ct, MOV_TIMESCALE,
2975 track->timescale, AV_ROUND_DOWN);
2976 version |= delay < INT32_MAX ? 0 : 1;
2978 entry_size = (version == 1) ? 20 : 12;
2979 entry_count = 1 + (delay > 0);
2980 size = 24 + entry_count * entry_size;
2982 /* write the atom data */
2983 avio_wb32(pb, size);
2984 ffio_wfourcc(pb, "edts");
2985 avio_wb32(pb, size - 8);
2986 ffio_wfourcc(pb, "elst");
2987 avio_w8(pb, version);
2988 avio_wb24(pb, 0); /* flags */
2990 avio_wb32(pb, entry_count);
2991 if (delay > 0) { /* add an empty edit to delay presentation */
2992 /* In the positive delay case, the delay includes the cts
2993 * offset, and the second edit list entry below trims out
2994 * the same amount from the actual content. This makes sure
2995 * that the offset last sample is included in the edit
2996 * list duration as well. */
2998 avio_wb64(pb, delay);
3001 avio_wb32(pb, delay);
3004 avio_wb32(pb, 0x00010000);
3006 /* Avoid accidentally ending up with start_ct = -1 which has got a
3007 * special meaning. Normally start_ct should end up positive or zero
3008 * here, but use FFMIN in case dts is a small positive integer
3009 * rounded to 0 when represented in MOV_TIMESCALE units. */
3010 av_assert0(av_rescale_rnd(start_dts, MOV_TIMESCALE, track->timescale, AV_ROUND_DOWN) <= 0);
3011 start_ct = -FFMIN(start_dts, 0);
3012 /* Note, this delay is calculated from the pts of the first sample,
3013 * ensuring that we don't reduce the duration for cases with
3018 /* For fragmented files, we don't know the full length yet. Setting
3019 * duration to 0 allows us to only specify the offset, including
3020 * the rest of the content (from all future fragments) without specifying
3021 * an explicit duration. */
3022 if (mov->flags & FF_MOV_FLAG_FRAGMENT)
3027 avio_wb64(pb, duration);
3028 avio_wb64(pb, start_ct);
3030 avio_wb32(pb, duration);
3031 avio_wb32(pb, start_ct);
3033 avio_wb32(pb, 0x00010000);
3037 static int mov_write_tref_tag(AVIOContext *pb, MOVTrack *track)
3039 avio_wb32(pb, 20); // size
3040 ffio_wfourcc(pb, "tref");
3041 avio_wb32(pb, 12); // size (subatom)
3042 avio_wl32(pb, track->tref_tag);
3043 avio_wb32(pb, track->tref_id);
3047 // goes at the end of each track! ... Critical for PSP playback ("Incompatible data" without it)
3048 static int mov_write_uuid_tag_psp(AVIOContext *pb, MOVTrack *mov)
3050 avio_wb32(pb, 0x34); /* size ... reports as 28 in mp4box! */
3051 ffio_wfourcc(pb, "uuid");
3052 ffio_wfourcc(pb, "USMT");
3053 avio_wb32(pb, 0x21d24fce);
3054 avio_wb32(pb, 0xbb88695c);
3055 avio_wb32(pb, 0xfac9c740);
3056 avio_wb32(pb, 0x1c); // another size here!
3057 ffio_wfourcc(pb, "MTDT");
3058 avio_wb32(pb, 0x00010012);
3059 avio_wb32(pb, 0x0a);
3060 avio_wb32(pb, 0x55c40000);
3066 static int mov_write_udta_sdp(AVIOContext *pb, MOVTrack *track)
3068 AVFormatContext *ctx = track->rtp_ctx;
3069 char buf[1000] = "";
3072 ff_sdp_write_media(buf, sizeof(buf), ctx->streams[0], track->src_track,
3073 NULL, NULL, 0, 0, ctx);
3074 av_strlcatf(buf, sizeof(buf), "a=control:streamid=%d\r\n", track->track_id);
3077 avio_wb32(pb, len + 24);
3078 ffio_wfourcc(pb, "udta");
3079 avio_wb32(pb, len + 16);
3080 ffio_wfourcc(pb, "hnti");
3081 avio_wb32(pb, len + 8);
3082 ffio_wfourcc(pb, "sdp ");
3083 avio_write(pb, buf, len);
3087 static int mov_write_track_metadata(AVIOContext *pb, AVStream *st,
3088 const char *tag, const char *str)
3090 int64_t pos = avio_tell(pb);
3091 AVDictionaryEntry *t = av_dict_get(st->metadata, str, NULL, 0);
3092 if (!t || !utf8len(t->value))
3095 avio_wb32(pb, 0); /* size */
3096 ffio_wfourcc(pb, tag); /* type */
3097 avio_write(pb, t->value, strlen(t->value)); /* UTF8 string value */
3098 return update_size(pb, pos);
3101 static int mov_write_track_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
3104 AVIOContext *pb_buf;
3111 ret = avio_open_dyn_buf(&pb_buf);
3115 if (mov->mode & (MODE_MP4|MODE_MOV))
3116 mov_write_track_metadata(pb_buf, st, "name", "title");
3118 if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) {
3119 avio_wb32(pb, size + 8);
3120 ffio_wfourcc(pb, "udta");
3121 avio_write(pb, buf, size);
3128 static int mov_write_trak_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov,
3129 MOVTrack *track, AVStream *st)
3131 int64_t pos = avio_tell(pb);
3132 int entry_backup = track->entry;
3133 int chunk_backup = track->chunkCount;
3136 /* If we want to have an empty moov, but some samples already have been
3137 * buffered (delay_moov), pretend that no samples have been written yet. */
3138 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV)
3139 track->chunkCount = track->entry = 0;
3141 avio_wb32(pb, 0); /* size */
3142 ffio_wfourcc(pb, "trak");
3143 mov_write_tkhd_tag(pb, mov, track, st);
3145 av_assert2(mov->use_editlist >= 0);
3147 if (track->start_dts != AV_NOPTS_VALUE) {
3148 if (mov->use_editlist)
3149 mov_write_edts_tag(pb, mov, track); // PSP Movies and several other cases require edts box
3150 else if ((track->entry && track->cluster[0].dts) || track->mode == MODE_PSP || is_clcp_track(track))
3151 av_log(mov->fc, AV_LOG_WARNING,
3152 "Not writing any edit list even though one would have been required\n");
3155 if (track->tref_tag)
3156 mov_write_tref_tag(pb, track);
3158 if ((ret = mov_write_mdia_tag(s, pb, mov, track)) < 0)
3160 if (track->mode == MODE_PSP)
3161 mov_write_uuid_tag_psp(pb, track); // PSP Movies require this uuid box
3162 if (track->tag == MKTAG('r','t','p',' '))
3163 mov_write_udta_sdp(pb, track);
3164 if (track->mode == MODE_MOV) {
3165 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
3166 double sample_aspect_ratio = av_q2d(st->sample_aspect_ratio);
3167 if (st->sample_aspect_ratio.num && 1.0 != sample_aspect_ratio) {
3168 mov_write_tapt_tag(pb, track);
3171 if (is_clcp_track(track) && st->sample_aspect_ratio.num) {
3172 mov_write_tapt_tag(pb, track);
3175 mov_write_track_udta_tag(pb, mov, st);
3176 track->entry = entry_backup;
3177 track->chunkCount = chunk_backup;
3178 return update_size(pb, pos);
3181 static int mov_write_iods_tag(AVIOContext *pb, MOVMuxContext *mov)
3183 int i, has_audio = 0, has_video = 0;
3184 int64_t pos = avio_tell(pb);
3185 int audio_profile = mov->iods_audio_profile;
3186 int video_profile = mov->iods_video_profile;
3187 for (i = 0; i < mov->nb_streams; i++) {
3188 if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
3189 has_audio |= mov->tracks[i].par->codec_type == AVMEDIA_TYPE_AUDIO;
3190 has_video |= mov->tracks[i].par->codec_type == AVMEDIA_TYPE_VIDEO;
3193 if (audio_profile < 0)
3194 audio_profile = 0xFF - has_audio;
3195 if (video_profile < 0)
3196 video_profile = 0xFF - has_video;
3197 avio_wb32(pb, 0x0); /* size */
3198 ffio_wfourcc(pb, "iods");
3199 avio_wb32(pb, 0); /* version & flags */
3200 put_descr(pb, 0x10, 7);
3201 avio_wb16(pb, 0x004f);
3204 avio_w8(pb, audio_profile);
3205 avio_w8(pb, video_profile);
3207 return update_size(pb, pos);
3210 static int mov_write_trex_tag(AVIOContext *pb, MOVTrack *track)
3212 avio_wb32(pb, 0x20); /* size */
3213 ffio_wfourcc(pb, "trex");
3214 avio_wb32(pb, 0); /* version & flags */
3215 avio_wb32(pb, track->track_id); /* track ID */
3216 avio_wb32(pb, 1); /* default sample description index */
3217 avio_wb32(pb, 0); /* default sample duration */
3218 avio_wb32(pb, 0); /* default sample size */
3219 avio_wb32(pb, 0); /* default sample flags */
3223 static int mov_write_mvex_tag(AVIOContext *pb, MOVMuxContext *mov)
3225 int64_t pos = avio_tell(pb);
3227 avio_wb32(pb, 0x0); /* size */
3228 ffio_wfourcc(pb, "mvex");
3229 for (i = 0; i < mov->nb_streams; i++)
3230 mov_write_trex_tag(pb, &mov->tracks[i]);
3231 return update_size(pb, pos);
3234 static int mov_write_mvhd_tag(AVIOContext *pb, MOVMuxContext *mov)
3236 int max_track_id = 1, i;
3237 int64_t max_track_len = 0;
3240 for (i = 0; i < mov->nb_streams; i++) {
3241 if (mov->tracks[i].entry > 0 && mov->tracks[i].timescale) {
3242 int64_t max_track_len_temp = av_rescale_rnd(mov->tracks[i].track_duration,
3244 mov->tracks[i].timescale,
3246 if (max_track_len < max_track_len_temp)
3247 max_track_len = max_track_len_temp;
3248 if (max_track_id < mov->tracks[i].track_id)
3249 max_track_id = mov->tracks[i].track_id;
3252 /* If using delay_moov, make sure the output is the same as if no
3253 * samples had been written yet. */
3254 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
3259 version = max_track_len < UINT32_MAX ? 0 : 1;
3260 avio_wb32(pb, version == 1 ? 120 : 108); /* size */
3262 ffio_wfourcc(pb, "mvhd");
3263 avio_w8(pb, version);
3264 avio_wb24(pb, 0); /* flags */
3266 avio_wb64(pb, mov->time);
3267 avio_wb64(pb, mov->time);
3269 avio_wb32(pb, mov->time); /* creation time */
3270 avio_wb32(pb, mov->time); /* modification time */
3272 avio_wb32(pb, MOV_TIMESCALE);
3273 (version == 1) ? avio_wb64(pb, max_track_len) : avio_wb32(pb, max_track_len); /* duration of longest track */
3275 avio_wb32(pb, 0x00010000); /* reserved (preferred rate) 1.0 = normal */
3276 avio_wb16(pb, 0x0100); /* reserved (preferred volume) 1.0 = normal */
3277 avio_wb16(pb, 0); /* reserved */
3278 avio_wb32(pb, 0); /* reserved */
3279 avio_wb32(pb, 0); /* reserved */
3281 /* Matrix structure */
3282 write_matrix(pb, 1, 0, 0, 1, 0, 0);
3284 avio_wb32(pb, 0); /* reserved (preview time) */
3285 avio_wb32(pb, 0); /* reserved (preview duration) */
3286 avio_wb32(pb, 0); /* reserved (poster time) */
3287 avio_wb32(pb, 0); /* reserved (selection time) */
3288 avio_wb32(pb, 0); /* reserved (selection duration) */
3289 avio_wb32(pb, 0); /* reserved (current time) */
3290 avio_wb32(pb, max_track_id + 1); /* Next track id */
3294 static int mov_write_itunes_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov,
3297 avio_wb32(pb, 33); /* size */
3298 ffio_wfourcc(pb, "hdlr");
3301 ffio_wfourcc(pb, "mdir");
3302 ffio_wfourcc(pb, "appl");
3309 /* helper function to write a data tag with the specified string as data */
3310 static int mov_write_string_data_tag(AVIOContext *pb, const char *data, int lang, int long_style)
3313 int size = 16 + strlen(data);
3314 avio_wb32(pb, size); /* size */
3315 ffio_wfourcc(pb, "data");
3318 avio_write(pb, data, strlen(data));
3322 lang = ff_mov_iso639_to_lang("und", 1);
3323 avio_wb16(pb, strlen(data)); /* string length */
3324 avio_wb16(pb, lang);
3325 avio_write(pb, data, strlen(data));
3326 return strlen(data) + 4;
3330 static int mov_write_string_tag(AVIOContext *pb, const char *name,
3331 const char *value, int lang, int long_style)
3334 if (value && value[0]) {
3335 int64_t pos = avio_tell(pb);
3336 avio_wb32(pb, 0); /* size */
3337 ffio_wfourcc(pb, name);
3338 mov_write_string_data_tag(pb, value, lang, long_style);
3339 size = update_size(pb, pos);
3344 static AVDictionaryEntry *get_metadata_lang(AVFormatContext *s,
3345 const char *tag, int *lang)
3348 AVDictionaryEntry *t, *t2 = NULL;
3353 if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
3356 len = strlen(t->key);
3357 snprintf(tag2, sizeof(tag2), "%s-", tag);
3358 while ((t2 = av_dict_get(s->metadata, tag2, t2, AV_DICT_IGNORE_SUFFIX))) {
3359 len2 = strlen(t2->key);
3360 if (len2 == len + 4 && !strcmp(t->value, t2->value)
3361 && (l = ff_mov_iso639_to_lang(&t2->key[len2 - 3], 1)) >= 0) {
3369 static int mov_write_string_metadata(AVFormatContext *s, AVIOContext *pb,
3370 const char *name, const char *tag,
3374 AVDictionaryEntry *t = get_metadata_lang(s, tag, &lang);
3377 return mov_write_string_tag(pb, name, t->value, lang, long_style);
3380 /* iTunes bpm number */
3381 static int mov_write_tmpo_tag(AVIOContext *pb, AVFormatContext *s)
3383 AVDictionaryEntry *t = av_dict_get(s->metadata, "tmpo", NULL, 0);
3384 int size = 0, tmpo = t ? atoi(t->value) : 0;
3387 avio_wb32(pb, size);
3388 ffio_wfourcc(pb, "tmpo");
3389 avio_wb32(pb, size-8); /* size */
3390 ffio_wfourcc(pb, "data");
3391 avio_wb32(pb, 0x15); //type specifier
3393 avio_wb16(pb, tmpo); // data
3398 /* 3GPP TS 26.244 */
3399 static int mov_write_loci_tag(AVFormatContext *s, AVIOContext *pb)
3402 int64_t pos = avio_tell(pb);
3403 double latitude, longitude, altitude;
3404 int32_t latitude_fix, longitude_fix, altitude_fix;
3405 AVDictionaryEntry *t = get_metadata_lang(s, "location", &lang);
3406 const char *ptr, *place = "";
3408 static const char *astronomical_body = "earth";
3413 longitude = strtod(ptr, &end);
3415 av_log(s, AV_LOG_WARNING, "malformed location metadata\n");
3419 latitude = strtod(ptr, &end);
3421 av_log(s, AV_LOG_WARNING, "malformed location metadata\n");
3425 altitude = strtod(ptr, &end);
3426 /* If no altitude was present, the default 0 should be fine */
3430 latitude_fix = (int32_t) ((1 << 16) * latitude);
3431 longitude_fix = (int32_t) ((1 << 16) * longitude);
3432 altitude_fix = (int32_t) ((1 << 16) * altitude);
3434 avio_wb32(pb, 0); /* size */
3435 ffio_wfourcc(pb, "loci"); /* type */
3436 avio_wb32(pb, 0); /* version + flags */
3437 avio_wb16(pb, lang);
3438 avio_write(pb, place, strlen(place) + 1);
3439 avio_w8(pb, 0); /* role of place (0 == shooting location, 1 == real location, 2 == fictional location) */
3440 avio_wb32(pb, latitude_fix);
3441 avio_wb32(pb, longitude_fix);
3442 avio_wb32(pb, altitude_fix);
3443 avio_write(pb, astronomical_body, strlen(astronomical_body) + 1);
3444 avio_w8(pb, 0); /* additional notes, null terminated string */
3446 return update_size(pb, pos);
3449 /* iTunes track or disc number */
3450 static int mov_write_trkn_tag(AVIOContext *pb, MOVMuxContext *mov,
3451 AVFormatContext *s, int disc)
3453 AVDictionaryEntry *t = av_dict_get(s->metadata,
3454 disc ? "disc" : "track",
3456 int size = 0, track = t ? atoi(t->value) : 0;
3459 char *slash = strchr(t->value, '/');
3461 tracks = atoi(slash + 1);
3462 avio_wb32(pb, 32); /* size */
3463 ffio_wfourcc(pb, disc ? "disk" : "trkn");
3464 avio_wb32(pb, 24); /* size */
3465 ffio_wfourcc(pb, "data");
3466 avio_wb32(pb, 0); // 8 bytes empty
3468 avio_wb16(pb, 0); // empty
3469 avio_wb16(pb, track); // track / disc number
3470 avio_wb16(pb, tracks); // total track / disc number
3471 avio_wb16(pb, 0); // empty
3477 static int mov_write_int8_metadata(AVFormatContext *s, AVIOContext *pb,
3478 const char *name, const char *tag,
3481 AVDictionaryEntry *t = NULL;
3483 int size = 24 + len;
3485 if (len != 1 && len != 4)
3488 if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
3490 num = atoi(t->value);
3492 avio_wb32(pb, size);
3493 ffio_wfourcc(pb, name);
3494 avio_wb32(pb, size - 8);
3495 ffio_wfourcc(pb, "data");
3496 avio_wb32(pb, 0x15);
3498 if (len==4) avio_wb32(pb, num);
3499 else avio_w8 (pb, num);
3504 static int mov_write_covr(AVIOContext *pb, AVFormatContext *s)
3506 MOVMuxContext *mov = s->priv_data;
3510 for (i = 0; i < s->nb_streams; i++) {
3511 MOVTrack *trk = &mov->tracks[i];
3513 if (!is_cover_image(trk->st) || trk->cover_image.size <= 0)
3517 pos = avio_tell(pb);
3519 ffio_wfourcc(pb, "covr");
3521 avio_wb32(pb, 16 + trk->cover_image.size);
3522 ffio_wfourcc(pb, "data");
3523 avio_wb32(pb, trk->tag);
3525 avio_write(pb, trk->cover_image.data, trk->cover_image.size);
3528 return pos ? update_size(pb, pos) : 0;
3531 /* iTunes meta data list */
3532 static int mov_write_ilst_tag(AVIOContext *pb, MOVMuxContext *mov,
3535 int64_t pos = avio_tell(pb);
3536 avio_wb32(pb, 0); /* size */
3537 ffio_wfourcc(pb, "ilst");
3538 mov_write_string_metadata(s, pb, "\251nam", "title" , 1);
3539 mov_write_string_metadata(s, pb, "\251ART", "artist" , 1);
3540 mov_write_string_metadata(s, pb, "aART", "album_artist", 1);
3541 mov_write_string_metadata(s, pb, "\251wrt", "composer" , 1);
3542 mov_write_string_metadata(s, pb, "\251alb", "album" , 1);
3543 mov_write_string_metadata(s, pb, "\251day", "date" , 1);
3544 if (!mov_write_string_metadata(s, pb, "\251too", "encoding_tool", 1)) {
3545 if (!(s->flags & AVFMT_FLAG_BITEXACT))
3546 mov_write_string_tag(pb, "\251too", LIBAVFORMAT_IDENT, 0, 1);
3548 mov_write_string_metadata(s, pb, "\251cmt", "comment" , 1);
3549 mov_write_string_metadata(s, pb, "\251gen", "genre" , 1);
3550 mov_write_string_metadata(s, pb, "cprt", "copyright", 1);
3551 mov_write_string_metadata(s, pb, "\251grp", "grouping" , 1);
3552 mov_write_string_metadata(s, pb, "\251lyr", "lyrics" , 1);
3553 mov_write_string_metadata(s, pb, "desc", "description",1);
3554 mov_write_string_metadata(s, pb, "ldes", "synopsis" , 1);
3555 mov_write_string_metadata(s, pb, "tvsh", "show" , 1);
3556 mov_write_string_metadata(s, pb, "tven", "episode_id",1);
3557 mov_write_string_metadata(s, pb, "tvnn", "network" , 1);
3558 mov_write_string_metadata(s, pb, "keyw", "keywords" , 1);
3559 mov_write_int8_metadata (s, pb, "tves", "episode_sort",4);
3560 mov_write_int8_metadata (s, pb, "tvsn", "season_number",4);
3561 mov_write_int8_metadata (s, pb, "stik", "media_type",1);
3562 mov_write_int8_metadata (s, pb, "hdvd", "hd_video", 1);
3563 mov_write_int8_metadata (s, pb, "pgap", "gapless_playback",1);
3564 mov_write_int8_metadata (s, pb, "cpil", "compilation", 1);
3565 mov_write_covr(pb, s);
3566 mov_write_trkn_tag(pb, mov, s, 0); // track number
3567 mov_write_trkn_tag(pb, mov, s, 1); // disc number
3568 mov_write_tmpo_tag(pb, s);
3569 return update_size(pb, pos);
3572 static int mov_write_mdta_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov,
3575 avio_wb32(pb, 33); /* size */
3576 ffio_wfourcc(pb, "hdlr");
3579 ffio_wfourcc(pb, "mdta");
3587 static int mov_write_mdta_keys_tag(AVIOContext *pb, MOVMuxContext *mov,
3590 AVDictionaryEntry *t = NULL;
3591 int64_t pos = avio_tell(pb);
3592 int64_t curpos, entry_pos;
3595 avio_wb32(pb, 0); /* size */
3596 ffio_wfourcc(pb, "keys");
3598 entry_pos = avio_tell(pb);
3599 avio_wb32(pb, 0); /* entry count */
3601 while (t = av_dict_get(s->metadata, "", t, AV_DICT_IGNORE_SUFFIX)) {
3602 avio_wb32(pb, strlen(t->key) + 8);
3603 ffio_wfourcc(pb, "mdta");
3604 avio_write(pb, t->key, strlen(t->key));
3607 curpos = avio_tell(pb);
3608 avio_seek(pb, entry_pos, SEEK_SET);
3609 avio_wb32(pb, count); // rewrite entry count
3610 avio_seek(pb, curpos, SEEK_SET);
3612 return update_size(pb, pos);
3615 static int mov_write_mdta_ilst_tag(AVIOContext *pb, MOVMuxContext *mov,
3618 AVDictionaryEntry *t = NULL;
3619 int64_t pos = avio_tell(pb);
3620 int count = 1; /* keys are 1-index based */
3622 avio_wb32(pb, 0); /* size */
3623 ffio_wfourcc(pb, "ilst");
3625 while (t = av_dict_get(s->metadata, "", t, AV_DICT_IGNORE_SUFFIX)) {
3626 int64_t entry_pos = avio_tell(pb);
3627 avio_wb32(pb, 0); /* size */
3628 avio_wb32(pb, count); /* key */
3629 mov_write_string_data_tag(pb, t->value, 0, 1);
3630 update_size(pb, entry_pos);
3633 return update_size(pb, pos);
3636 /* meta data tags */
3637 static int mov_write_meta_tag(AVIOContext *pb, MOVMuxContext *mov,
3641 int64_t pos = avio_tell(pb);
3642 avio_wb32(pb, 0); /* size */
3643 ffio_wfourcc(pb, "meta");
3645 if (mov->flags & FF_MOV_FLAG_USE_MDTA) {
3646 mov_write_mdta_hdlr_tag(pb, mov, s);
3647 mov_write_mdta_keys_tag(pb, mov, s);
3648 mov_write_mdta_ilst_tag(pb, mov, s);
3651 /* iTunes metadata tag */
3652 mov_write_itunes_hdlr_tag(pb, mov, s);
3653 mov_write_ilst_tag(pb, mov, s);
3655 size = update_size(pb, pos);
3659 static int mov_write_raw_metadata_tag(AVFormatContext *s, AVIOContext *pb,
3660 const char *name, const char *key)
3663 AVDictionaryEntry *t;
3665 if (!(t = av_dict_get(s->metadata, key, NULL, 0)))
3668 len = strlen(t->value);
3671 avio_wb32(pb, size);
3672 ffio_wfourcc(pb, name);
3673 avio_write(pb, t->value, len);
3679 static int ascii_to_wc(AVIOContext *pb, const uint8_t *b)
3683 GET_UTF8(val, *b++, return -1;)
3686 avio_wb16(pb, 0x00);
3690 static uint16_t language_code(const char *str)
3692 return (((str[0] - 0x60) & 0x1F) << 10) +
3693 (((str[1] - 0x60) & 0x1F) << 5) +
3694 (( str[2] - 0x60) & 0x1F);
3697 static int mov_write_3gp_udta_tag(AVIOContext *pb, AVFormatContext *s,
3698 const char *tag, const char *str)
3700 int64_t pos = avio_tell(pb);
3701 AVDictionaryEntry *t = av_dict_get(s->metadata, str, NULL, 0);
3702 if (!t || !utf8len(t->value))
3704 avio_wb32(pb, 0); /* size */
3705 ffio_wfourcc(pb, tag); /* type */
3706 avio_wb32(pb, 0); /* version + flags */
3707 if (!strcmp(tag, "yrrc"))
3708 avio_wb16(pb, atoi(t->value));
3710 avio_wb16(pb, language_code("eng")); /* language */
3711 avio_write(pb, t->value, strlen(t->value) + 1); /* UTF8 string value */
3712 if (!strcmp(tag, "albm") &&
3713 (t = av_dict_get(s->metadata, "track", NULL, 0)))
3714 avio_w8(pb, atoi(t->value));
3716 return update_size(pb, pos);
3719 static int mov_write_chpl_tag(AVIOContext *pb, AVFormatContext *s)
3721 int64_t pos = avio_tell(pb);
3722 int i, nb_chapters = FFMIN(s->nb_chapters, 255);
3724 avio_wb32(pb, 0); // size
3725 ffio_wfourcc(pb, "chpl");
3726 avio_wb32(pb, 0x01000000); // version + flags
3727 avio_wb32(pb, 0); // unknown
3728 avio_w8(pb, nb_chapters);
3730 for (i = 0; i < nb_chapters; i++) {
3731 AVChapter *c = s->chapters[i];
3732 AVDictionaryEntry *t;
3733 avio_wb64(pb, av_rescale_q(c->start, c->time_base, (AVRational){1,10000000}));
3735 if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
3736 int len = FFMIN(strlen(t->value), 255);
3738 avio_write(pb, t->value, len);
3742 return update_size(pb, pos);
3745 static int mov_write_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
3748 AVIOContext *pb_buf;
3752 ret = avio_open_dyn_buf(&pb_buf);
3756 if (mov->mode & MODE_3GP) {
3757 mov_write_3gp_udta_tag(pb_buf, s, "perf", "artist");
3758 mov_write_3gp_udta_tag(pb_buf, s, "titl", "title");
3759 mov_write_3gp_udta_tag(pb_buf, s, "auth", "author");
3760 mov_write_3gp_udta_tag(pb_buf, s, "gnre", "genre");
3761 mov_write_3gp_udta_tag(pb_buf, s, "dscp", "comment");
3762 mov_write_3gp_udta_tag(pb_buf, s, "albm", "album");
3763 mov_write_3gp_udta_tag(pb_buf, s, "cprt", "copyright");
3764 mov_write_3gp_udta_tag(pb_buf, s, "yrrc", "date");
3765 mov_write_loci_tag(s, pb_buf);
3766 } 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
3767 mov_write_string_metadata(s, pb_buf, "\251ART", "artist", 0);
3768 mov_write_string_metadata(s, pb_buf, "\251nam", "title", 0);
3769 mov_write_string_metadata(s, pb_buf, "\251aut", "author", 0);
3770 mov_write_string_metadata(s, pb_buf, "\251alb", "album", 0);
3771 mov_write_string_metadata(s, pb_buf, "\251day", "date", 0);
3772 mov_write_string_metadata(s, pb_buf, "\251swr", "encoder", 0);
3773 // currently ignored by mov.c
3774 mov_write_string_metadata(s, pb_buf, "\251des", "comment", 0);
3775 // add support for libquicktime, this atom is also actually read by mov.c
3776 mov_write_string_metadata(s, pb_buf, "\251cmt", "comment", 0);
3777 mov_write_string_metadata(s, pb_buf, "\251gen", "genre", 0);
3778 mov_write_string_metadata(s, pb_buf, "\251cpy", "copyright", 0);
3779 mov_write_string_metadata(s, pb_buf, "\251mak", "make", 0);
3780 mov_write_string_metadata(s, pb_buf, "\251mod", "model", 0);
3781 mov_write_string_metadata(s, pb_buf, "\251xyz", "location", 0);
3782 mov_write_string_metadata(s, pb_buf, "\251key", "keywords", 0);
3783 mov_write_raw_metadata_tag(s, pb_buf, "XMP_", "xmp");
3785 /* iTunes meta data */
3786 mov_write_meta_tag(pb_buf, mov, s);
3787 mov_write_loci_tag(s, pb_buf);
3790 if (s->nb_chapters && !(mov->flags & FF_MOV_FLAG_DISABLE_CHPL))
3791 mov_write_chpl_tag(pb_buf, s);
3793 if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) {
3794 avio_wb32(pb, size + 8);
3795 ffio_wfourcc(pb, "udta");
3796 avio_write(pb, buf, size);
3803 static void mov_write_psp_udta_tag(AVIOContext *pb,
3804 const char *str, const char *lang, int type)
3806 int len = utf8len(str) + 1;
3809 avio_wb16(pb, len * 2 + 10); /* size */
3810 avio_wb32(pb, type); /* type */
3811 avio_wb16(pb, language_code(lang)); /* language */
3812 avio_wb16(pb, 0x01); /* ? */
3813 ascii_to_wc(pb, str);
3816 static int mov_write_uuidusmt_tag(AVIOContext *pb, AVFormatContext *s)
3818 AVDictionaryEntry *title = av_dict_get(s->metadata, "title", NULL, 0);
3822 pos = avio_tell(pb);
3823 avio_wb32(pb, 0); /* size placeholder*/
3824 ffio_wfourcc(pb, "uuid");
3825 ffio_wfourcc(pb, "USMT");
3826 avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
3827 avio_wb32(pb, 0xbb88695c);
3828 avio_wb32(pb, 0xfac9c740);
3830 pos2 = avio_tell(pb);
3831 avio_wb32(pb, 0); /* size placeholder*/
3832 ffio_wfourcc(pb, "MTDT");
3836 avio_wb16(pb, 0x0C); /* size */
3837 avio_wb32(pb, 0x0B); /* type */
3838 avio_wb16(pb, language_code("und")); /* language */
3839 avio_wb16(pb, 0x0); /* ? */
3840 avio_wb16(pb, 0x021C); /* data */
3842 if (!(s->flags & AVFMT_FLAG_BITEXACT))
3843 mov_write_psp_udta_tag(pb, LIBAVCODEC_IDENT, "eng", 0x04);
3844 mov_write_psp_udta_tag(pb, title->value, "eng", 0x01);
3845 mov_write_psp_udta_tag(pb, "2006/04/01 11:11:11", "und", 0x03);
3847 update_size(pb, pos2);
3848 return update_size(pb, pos);
3854 static void build_chunks(MOVTrack *trk)
3857 MOVIentry *chunk = &trk->cluster[0];
3858 uint64_t chunkSize = chunk->size;
3859 chunk->chunkNum = 1;
3860 if (trk->chunkCount)
3862 trk->chunkCount = 1;
3863 for (i = 1; i<trk->entry; i++){
3864 if (chunk->pos + chunkSize == trk->cluster[i].pos &&
3865 chunkSize + trk->cluster[i].size < (1<<20)){
3866 chunkSize += trk->cluster[i].size;
3867 chunk->samples_in_chunk += trk->cluster[i].entries;
3869 trk->cluster[i].chunkNum = chunk->chunkNum+1;
3870 chunk=&trk->cluster[i];
3871 chunkSize = chunk->size;
3878 * Assign track ids. If option "use_stream_ids_as_track_ids" is set,
3879 * the stream ids are used as track ids.
3881 * This assumes mov->tracks and s->streams are in the same order and
3882 * there are no gaps in either of them (so mov->tracks[n] refers to
3885 * As an exception, there can be more entries in
3886 * s->streams than in mov->tracks, in which case new track ids are
3887 * generated (starting after the largest found stream id).
3889 static int mov_setup_track_ids(MOVMuxContext *mov, AVFormatContext *s)
3893 if (mov->track_ids_ok)
3896 if (mov->use_stream_ids_as_track_ids) {
3897 int next_generated_track_id = 0;
3898 for (i = 0; i < s->nb_streams; i++) {
3899 if (s->streams[i]->id > next_generated_track_id)
3900 next_generated_track_id = s->streams[i]->id;
3903 for (i = 0; i < mov->nb_streams; i++) {
3904 if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
3907 mov->tracks[i].track_id = i >= s->nb_streams ? ++next_generated_track_id : s->streams[i]->id;
3910 for (i = 0; i < mov->nb_streams; i++) {
3911 if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
3914 mov->tracks[i].track_id = i + 1;
3918 mov->track_ids_ok = 1;
3923 static int mov_write_moov_tag(AVIOContext *pb, MOVMuxContext *mov,
3927 int64_t pos = avio_tell(pb);
3928 avio_wb32(pb, 0); /* size placeholder*/
3929 ffio_wfourcc(pb, "moov");
3931 mov_setup_track_ids(mov, s);
3933 for (i = 0; i < mov->nb_streams; i++) {
3934 if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
3937 mov->tracks[i].time = mov->time;
3939 if (mov->tracks[i].entry)
3940 build_chunks(&mov->tracks[i]);
3943 if (mov->chapter_track)
3944 for (i = 0; i < s->nb_streams; i++) {
3945 mov->tracks[i].tref_tag = MKTAG('c','h','a','p');
3946 mov->tracks[i].tref_id = mov->tracks[mov->chapter_track].track_id;
3948 for (i = 0; i < mov->nb_streams; i++) {
3949 MOVTrack *track = &mov->tracks[i];
3950 if (track->tag == MKTAG('r','t','p',' ')) {
3951 track->tref_tag = MKTAG('h','i','n','t');
3952 track->tref_id = mov->tracks[track->src_track].track_id;
3953 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
3954 int * fallback, size;
3955 fallback = (int*)av_stream_get_side_data(track->st,
3956 AV_PKT_DATA_FALLBACK_TRACK,
3958 if (fallback != NULL && size == sizeof(int)) {
3959 if (*fallback >= 0 && *fallback < mov->nb_streams) {
3960 track->tref_tag = MKTAG('f','a','l','l');
3961 track->tref_id = mov->tracks[*fallback].track_id;
3966 for (i = 0; i < mov->nb_streams; i++) {
3967 if (mov->tracks[i].tag == MKTAG('t','m','c','d')) {
3968 int src_trk = mov->tracks[i].src_track;
3969 mov->tracks[src_trk].tref_tag = mov->tracks[i].tag;
3970 mov->tracks[src_trk].tref_id = mov->tracks[i].track_id;
3971 //src_trk may have a different timescale than the tmcd track
3972 mov->tracks[i].track_duration = av_rescale(mov->tracks[src_trk].track_duration,
3973 mov->tracks[i].timescale,
3974 mov->tracks[src_trk].timescale);
3978 mov_write_mvhd_tag(pb, mov);
3979 if (mov->mode != MODE_MOV && !mov->iods_skip)
3980 mov_write_iods_tag(pb, mov);
3981 for (i = 0; i < mov->nb_streams; i++) {
3982 if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_FRAGMENT) {
3983 int ret = mov_write_trak_tag(s, pb, mov, &(mov->tracks[i]), i < s->nb_streams ? s->streams[i] : NULL);
3988 if (mov->flags & FF_MOV_FLAG_FRAGMENT)
3989 mov_write_mvex_tag(pb, mov); /* QuickTime requires trak to precede this */
3991 if (mov->mode == MODE_PSP)
3992 mov_write_uuidusmt_tag(pb, s);
3994 mov_write_udta_tag(pb, mov, s);
3996 return update_size(pb, pos);
3999 static void param_write_int(AVIOContext *pb, const char *name, int value)
4001 avio_printf(pb, "<param name=\"%s\" value=\"%d\" valuetype=\"data\"/>\n", name, value);
4004 static void param_write_string(AVIOContext *pb, const char *name, const char *value)
4006 avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, value);
4009 static void param_write_hex(AVIOContext *pb, const char *name, const uint8_t *value, int len)
4012 len = FFMIN(sizeof(buf) / 2 - 1, len);
4013 ff_data_to_hex(buf, value, len, 0);
4014 buf[2 * len] = '\0';
4015 avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, buf);
4018 static int mov_write_isml_manifest(AVIOContext *pb, MOVMuxContext *mov, AVFormatContext *s)
4020 int64_t pos = avio_tell(pb);
4022 int64_t manifest_bit_rate = 0;
4023 AVCPBProperties *props = NULL;
4025 static const uint8_t uuid[] = {
4026 0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd,
4027 0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66
4031 ffio_wfourcc(pb, "uuid");
4032 avio_write(pb, uuid, sizeof(uuid));
4035 avio_printf(pb, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
4036 avio_printf(pb, "<smil xmlns=\"http://www.w3.org/2001/SMIL20/Language\">\n");
4037 avio_printf(pb, "<head>\n");
4038 if (!(mov->fc->flags & AVFMT_FLAG_BITEXACT))
4039 avio_printf(pb, "<meta name=\"creator\" content=\"%s\" />\n",
4041 avio_printf(pb, "</head>\n");
4042 avio_printf(pb, "<body>\n");
4043 avio_printf(pb, "<switch>\n");
4045 mov_setup_track_ids(mov, s);
4047 for (i = 0; i < mov->nb_streams; i++) {
4048 MOVTrack *track = &mov->tracks[i];
4050 int track_id = track->track_id;
4051 char track_name_buf[32] = { 0 };
4053 AVStream *st = track->st;
4054 AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0);
4056 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO && !is_cover_image(st)) {
4058 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
4064 props = (AVCPBProperties*)av_stream_get_side_data(track->st, AV_PKT_DATA_CPB_PROPERTIES, NULL);
4066 if (track->par->bit_rate) {
4067 manifest_bit_rate = track->par->bit_rate;
4069 manifest_bit_rate = props->max_bitrate;
4072 avio_printf(pb, "<%s systemBitrate=\"%"PRId64"\">\n", type,
4074 param_write_int(pb, "systemBitrate", manifest_bit_rate);
4075 param_write_int(pb, "trackID", track_id);
4076 param_write_string(pb, "systemLanguage", lang ? lang->value : "und");
4078 /* Build track name piece by piece: */
4080 av_strlcat(track_name_buf, type, sizeof(track_name_buf));
4081 /* 2. track language, if available */
4083 av_strlcatf(track_name_buf, sizeof(track_name_buf),
4084 "_%s", lang->value);
4085 /* 3. special type suffix */
4086 /* "_cc" = closed captions, "_ad" = audio_description */
4087 if (st->disposition & AV_DISPOSITION_HEARING_IMPAIRED)
4088 av_strlcat(track_name_buf, "_cc", sizeof(track_name_buf));
4089 else if (st->disposition & AV_DISPOSITION_VISUAL_IMPAIRED)
4090 av_strlcat(track_name_buf, "_ad", sizeof(track_name_buf));
4092 param_write_string(pb, "trackName", track_name_buf);
4094 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
4095 if (track->par->codec_id == AV_CODEC_ID_H264) {
4097 int size = track->par->extradata_size;
4098 if (!ff_avc_write_annexb_extradata(track->par->extradata, &ptr,
4100 param_write_hex(pb, "CodecPrivateData",
4101 ptr ? ptr : track->par->extradata,
4105 param_write_string(pb, "FourCC", "H264");
4106 } else if (track->par->codec_id == AV_CODEC_ID_VC1) {
4107 param_write_string(pb, "FourCC", "WVC1");
4108 param_write_hex(pb, "CodecPrivateData", track->par->extradata,
4109 track->par->extradata_size);
4111 param_write_int(pb, "MaxWidth", track->par->width);
4112 param_write_int(pb, "MaxHeight", track->par->height);
4113 param_write_int(pb, "DisplayWidth", track->par->width);
4114 param_write_int(pb, "DisplayHeight", track->par->height);
4116 if (track->par->codec_id == AV_CODEC_ID_AAC) {
4117 switch (track->par->profile)
4119 case FF_PROFILE_AAC_HE_V2:
4120 param_write_string(pb, "FourCC", "AACP");
4122 case FF_PROFILE_AAC_HE:
4123 param_write_string(pb, "FourCC", "AACH");
4126 param_write_string(pb, "FourCC", "AACL");
4128 } else if (track->par->codec_id == AV_CODEC_ID_WMAPRO) {
4129 param_write_string(pb, "FourCC", "WMAP");
4131 param_write_hex(pb, "CodecPrivateData", track->par->extradata,
4132 track->par->extradata_size);
4133 param_write_int(pb, "AudioTag", ff_codec_get_tag(ff_codec_wav_tags,
4134 track->par->codec_id));
4135 param_write_int(pb, "Channels", track->par->channels);
4136 param_write_int(pb, "SamplingRate", track->par->sample_rate);
4137 param_write_int(pb, "BitsPerSample", 16);
4138 param_write_int(pb, "PacketSize", track->par->block_align ?
4139 track->par->block_align : 4);
4141 avio_printf(pb, "</%s>\n", type);
4143 avio_printf(pb, "</switch>\n");
4144 avio_printf(pb, "</body>\n");
4145 avio_printf(pb, "</smil>\n");
4147 return update_size(pb, pos);
4150 static int mov_write_mfhd_tag(AVIOContext *pb, MOVMuxContext *mov)
4153 ffio_wfourcc(pb, "mfhd");
4155 avio_wb32(pb, mov->fragments);
4159 static uint32_t get_sample_flags(MOVTrack *track, MOVIentry *entry)
4161 return entry->flags & MOV_SYNC_SAMPLE ? MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO :
4162 (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC);
4165 static int mov_write_tfhd_tag(AVIOContext *pb, MOVMuxContext *mov,
4166 MOVTrack *track, int64_t moof_offset)
4168 int64_t pos = avio_tell(pb);
4169 uint32_t flags = MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
4170 MOV_TFHD_BASE_DATA_OFFSET;
4171 if (!track->entry) {
4172 flags |= MOV_TFHD_DURATION_IS_EMPTY;
4174 flags |= MOV_TFHD_DEFAULT_FLAGS;
4176 if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET)
4177 flags &= ~MOV_TFHD_BASE_DATA_OFFSET;
4178 if (mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) {
4179 flags &= ~MOV_TFHD_BASE_DATA_OFFSET;
4180 flags |= MOV_TFHD_DEFAULT_BASE_IS_MOOF;
4183 /* Don't set a default sample size, the silverlight player refuses
4184 * to play files with that set. Don't set a default sample duration,
4185 * WMP freaks out if it is set. Don't set a base data offset, PIFF
4186 * file format says it MUST NOT be set. */
4187 if (track->mode == MODE_ISM)
4188 flags &= ~(MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
4189 MOV_TFHD_BASE_DATA_OFFSET);
4191 avio_wb32(pb, 0); /* size placeholder */
4192 ffio_wfourcc(pb, "tfhd");
4193 avio_w8(pb, 0); /* version */
4194 avio_wb24(pb, flags);
4196 avio_wb32(pb, track->track_id); /* track-id */
4197 if (flags & MOV_TFHD_BASE_DATA_OFFSET)
4198 avio_wb64(pb, moof_offset);
4199 if (flags & MOV_TFHD_DEFAULT_DURATION) {
4200 track->default_duration = get_cluster_duration(track, 0);
4201 avio_wb32(pb, track->default_duration);
4203 if (flags & MOV_TFHD_DEFAULT_SIZE) {
4204 track->default_size = track->entry ? track->cluster[0].size : 1;
4205 avio_wb32(pb, track->default_size);
4207 track->default_size = -1;
4209 if (flags & MOV_TFHD_DEFAULT_FLAGS) {
4210 /* Set the default flags based on the second sample, if available.
4211 * If the first sample is different, that can be signaled via a separate field. */
4212 if (track->entry > 1)
4213 track->default_sample_flags = get_sample_flags(track, &track->cluster[1]);
4215 track->default_sample_flags =
4216 track->par->codec_type == AVMEDIA_TYPE_VIDEO ?
4217 (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC) :
4218 MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO;
4219 avio_wb32(pb, track->default_sample_flags);
4222 return update_size(pb, pos);
4225 static int mov_write_trun_tag(AVIOContext *pb, MOVMuxContext *mov,
4226 MOVTrack *track, int moof_size,
4229 int64_t pos = avio_tell(pb);
4230 uint32_t flags = MOV_TRUN_DATA_OFFSET;
4233 for (i = first; i < end; i++) {
4234 if (get_cluster_duration(track, i) != track->default_duration)
4235 flags |= MOV_TRUN_SAMPLE_DURATION;
4236 if (track->cluster[i].size != track->default_size)
4237 flags |= MOV_TRUN_SAMPLE_SIZE;
4238 if (i > first && get_sample_flags(track, &track->cluster[i]) != track->default_sample_flags)
4239 flags |= MOV_TRUN_SAMPLE_FLAGS;
4241 if (!(flags & MOV_TRUN_SAMPLE_FLAGS) && track->entry > 0 &&
4242 get_sample_flags(track, &track->cluster[0]) != track->default_sample_flags)
4243 flags |= MOV_TRUN_FIRST_SAMPLE_FLAGS;
4244 if (track->flags & MOV_TRACK_CTTS)
4245 flags |= MOV_TRUN_SAMPLE_CTS;
4247 avio_wb32(pb, 0); /* size placeholder */
4248 ffio_wfourcc(pb, "trun");
4249 if (mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS)
4250 avio_w8(pb, 1); /* version */
4252 avio_w8(pb, 0); /* version */
4253 avio_wb24(pb, flags);
4255 avio_wb32(pb, end - first); /* sample count */
4256 if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET &&
4257 !(mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) &&
4259 avio_wb32(pb, 0); /* Later tracks follow immediately after the previous one */
4261 avio_wb32(pb, moof_size + 8 + track->data_offset +
4262 track->cluster[first].pos); /* data offset */
4263 if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS)
4264 avio_wb32(pb, get_sample_flags(track, &track->cluster[first]));
4266 for (i = first; i < end; i++) {
4267 if (flags & MOV_TRUN_SAMPLE_DURATION)
4268 avio_wb32(pb, get_cluster_duration(track, i));
4269 if (flags & MOV_TRUN_SAMPLE_SIZE)
4270 avio_wb32(pb, track->cluster[i].size);
4271 if (flags & MOV_TRUN_SAMPLE_FLAGS)
4272 avio_wb32(pb, get_sample_flags(track, &track->cluster[i]));
4273 if (flags & MOV_TRUN_SAMPLE_CTS)
4274 avio_wb32(pb, track->cluster[i].cts);
4277 mov->first_trun = 0;
4278 return update_size(pb, pos);
4281 static int mov_write_tfxd_tag(AVIOContext *pb, MOVTrack *track)
4283 int64_t pos = avio_tell(pb);
4284 static const uint8_t uuid[] = {
4285 0x6d, 0x1d, 0x9b, 0x05, 0x42, 0xd5, 0x44, 0xe6,
4286 0x80, 0xe2, 0x14, 0x1d, 0xaf, 0xf7, 0x57, 0xb2
4289 avio_wb32(pb, 0); /* size placeholder */
4290 ffio_wfourcc(pb, "uuid");
4291 avio_write(pb, uuid, sizeof(uuid));
4294 avio_wb64(pb, track->start_dts + track->frag_start +
4295 track->cluster[0].cts);
4296 avio_wb64(pb, track->end_pts -
4297 (track->cluster[0].dts + track->cluster[0].cts));
4299 return update_size(pb, pos);
4302 static int mov_write_tfrf_tag(AVIOContext *pb, MOVMuxContext *mov,
4303 MOVTrack *track, int entry)
4305 int n = track->nb_frag_info - 1 - entry, i;
4306 int size = 8 + 16 + 4 + 1 + 16*n;
4307 static const uint8_t uuid[] = {
4308 0xd4, 0x80, 0x7e, 0xf2, 0xca, 0x39, 0x46, 0x95,
4309 0x8e, 0x54, 0x26, 0xcb, 0x9e, 0x46, 0xa7, 0x9f
4315 avio_seek(pb, track->frag_info[entry].tfrf_offset, SEEK_SET);
4316 avio_wb32(pb, size);
4317 ffio_wfourcc(pb, "uuid");
4318 avio_write(pb, uuid, sizeof(uuid));
4322 for (i = 0; i < n; i++) {
4323 int index = entry + 1 + i;
4324 avio_wb64(pb, track->frag_info[index].time);
4325 avio_wb64(pb, track->frag_info[index].duration);
4327 if (n < mov->ism_lookahead) {
4328 int free_size = 16 * (mov->ism_lookahead - n);
4329 avio_wb32(pb, free_size);
4330 ffio_wfourcc(pb, "free");
4331 ffio_fill(pb, 0, free_size - 8);
4337 static int mov_write_tfrf_tags(AVIOContext *pb, MOVMuxContext *mov,
4340 int64_t pos = avio_tell(pb);
4342 for (i = 0; i < mov->ism_lookahead; i++) {
4343 /* Update the tfrf tag for the last ism_lookahead fragments,
4344 * nb_frag_info - 1 is the next fragment to be written. */
4345 mov_write_tfrf_tag(pb, mov, track, track->nb_frag_info - 2 - i);
4347 avio_seek(pb, pos, SEEK_SET);
4351 static int mov_add_tfra_entries(AVIOContext *pb, MOVMuxContext *mov, int tracks,
4355 for (i = 0; i < mov->nb_streams; i++) {
4356 MOVTrack *track = &mov->tracks[i];
4357 MOVFragmentInfo *info;
4358 if ((tracks >= 0 && i != tracks) || !track->entry)
4360 track->nb_frag_info++;
4361 if (track->nb_frag_info >= track->frag_info_capacity) {
4362 unsigned new_capacity = track->nb_frag_info + MOV_FRAG_INFO_ALLOC_INCREMENT;
4363 if (av_reallocp_array(&track->frag_info,
4365 sizeof(*track->frag_info)))
4366 return AVERROR(ENOMEM);
4367 track->frag_info_capacity = new_capacity;
4369 info = &track->frag_info[track->nb_frag_info - 1];
4370 info->offset = avio_tell(pb);
4372 // Try to recreate the original pts for the first packet
4373 // from the fields we have stored
4374 info->time = track->start_dts + track->frag_start +
4375 track->cluster[0].cts;
4376 info->duration = track->end_pts -
4377 (track->cluster[0].dts + track->cluster[0].cts);
4378 // If the pts is less than zero, we will have trimmed
4379 // away parts of the media track using an edit list,
4380 // and the corresponding start presentation time is zero.
4381 if (info->time < 0) {
4382 info->duration += info->time;
4385 info->tfrf_offset = 0;
4386 mov_write_tfrf_tags(pb, mov, track);
4391 static void mov_prune_frag_info(MOVMuxContext *mov, int tracks, int max)
4394 for (i = 0; i < mov->nb_streams; i++) {
4395 MOVTrack *track = &mov->tracks[i];
4396 if ((tracks >= 0 && i != tracks) || !track->entry)
4398 if (track->nb_frag_info > max) {
4399 memmove(track->frag_info, track->frag_info + (track->nb_frag_info - max), max * sizeof(*track->frag_info));
4400 track->nb_frag_info = max;
4405 static int mov_write_tfdt_tag(AVIOContext *pb, MOVTrack *track)
4407 int64_t pos = avio_tell(pb);
4409 avio_wb32(pb, 0); /* size */
4410 ffio_wfourcc(pb, "tfdt");
4411 avio_w8(pb, 1); /* version */
4413 avio_wb64(pb, track->frag_start);
4414 return update_size(pb, pos);
4417 static int mov_write_traf_tag(AVIOContext *pb, MOVMuxContext *mov,
4418 MOVTrack *track, int64_t moof_offset,
4421 int64_t pos = avio_tell(pb);
4423 avio_wb32(pb, 0); /* size placeholder */
4424 ffio_wfourcc(pb, "traf");
4426 mov_write_tfhd_tag(pb, mov, track, moof_offset);
4427 if (mov->mode != MODE_ISM)
4428 mov_write_tfdt_tag(pb, track);
4429 for (i = 1; i < track->entry; i++) {
4430 if (track->cluster[i].pos != track->cluster[i - 1].pos + track->cluster[i - 1].size) {
4431 mov_write_trun_tag(pb, mov, track, moof_size, start, i);
4435 mov_write_trun_tag(pb, mov, track, moof_size, start, track->entry);
4436 if (mov->mode == MODE_ISM) {
4437 mov_write_tfxd_tag(pb, track);
4439 if (mov->ism_lookahead) {
4440 int i, size = 16 + 4 + 1 + 16 * mov->ism_lookahead;
4442 if (track->nb_frag_info > 0) {
4443 MOVFragmentInfo *info = &track->frag_info[track->nb_frag_info - 1];
4444 if (!info->tfrf_offset)
4445 info->tfrf_offset = avio_tell(pb);
4447 avio_wb32(pb, 8 + size);
4448 ffio_wfourcc(pb, "free");
4449 for (i = 0; i < size; i++)
4454 return update_size(pb, pos);
4457 static int mov_write_moof_tag_internal(AVIOContext *pb, MOVMuxContext *mov,
4458 int tracks, int moof_size)
4460 int64_t pos = avio_tell(pb);
4463 avio_wb32(pb, 0); /* size placeholder */
4464 ffio_wfourcc(pb, "moof");
4465 mov->first_trun = 1;
4467 mov_write_mfhd_tag(pb, mov);
4468 for (i = 0; i < mov->nb_streams; i++) {
4469 MOVTrack *track = &mov->tracks[i];
4470 if (tracks >= 0 && i != tracks)
4474 mov_write_traf_tag(pb, mov, track, pos, moof_size);
4477 return update_size(pb, pos);
4480 static int mov_write_sidx_tag(AVIOContext *pb,
4481 MOVTrack *track, int ref_size, int total_sidx_size)
4483 int64_t pos = avio_tell(pb), offset_pos, end_pos;
4484 int64_t presentation_time, duration, offset;
4485 int starts_with_SAP, i, entries;
4489 presentation_time = track->start_dts + track->frag_start +
4490 track->cluster[0].cts;
4491 duration = track->end_pts -
4492 (track->cluster[0].dts + track->cluster[0].cts);
4493 starts_with_SAP = track->cluster[0].flags & MOV_SYNC_SAMPLE;
4495 // pts<0 should be cut away using edts
4496 if (presentation_time < 0) {
4497 duration += presentation_time;
4498 presentation_time = 0;
4501 entries = track->nb_frag_info;
4504 presentation_time = track->frag_info[0].time;
4507 avio_wb32(pb, 0); /* size */
4508 ffio_wfourcc(pb, "sidx");
4509 avio_w8(pb, 1); /* version */
4511 avio_wb32(pb, track->track_id); /* reference_ID */
4512 avio_wb32(pb, track->timescale); /* timescale */
4513 avio_wb64(pb, presentation_time); /* earliest_presentation_time */
4514 offset_pos = avio_tell(pb);
4515 avio_wb64(pb, 0); /* first_offset (offset to referenced moof) */
4516 avio_wb16(pb, 0); /* reserved */
4518 avio_wb16(pb, entries); /* reference_count */
4519 for (i = 0; i < entries; i++) {
4520 if (!track->entry) {
4521 if (i > 1 && track->frag_info[i].offset != track->frag_info[i - 1].offset + track->frag_info[i - 1].size) {
4522 av_log(NULL, AV_LOG_ERROR, "Non-consecutive fragments, writing incorrect sidx\n");
4524 duration = track->frag_info[i].duration;
4525 ref_size = track->frag_info[i].size;
4526 starts_with_SAP = 1;
4528 avio_wb32(pb, (0 << 31) | (ref_size & 0x7fffffff)); /* reference_type (0 = media) | referenced_size */
4529 avio_wb32(pb, duration); /* subsegment_duration */
4530 avio_wb32(pb, (starts_with_SAP << 31) | (0 << 28) | 0); /* starts_with_SAP | SAP_type | SAP_delta_time */
4533 end_pos = avio_tell(pb);
4534 offset = pos + total_sidx_size - end_pos;
4535 avio_seek(pb, offset_pos, SEEK_SET);
4536 avio_wb64(pb, offset);
4537 avio_seek(pb, end_pos, SEEK_SET);
4538 return update_size(pb, pos);
4541 static int mov_write_sidx_tags(AVIOContext *pb, MOVMuxContext *mov,
4542 int tracks, int ref_size)
4545 AVIOContext *avio_buf;
4547 for (round = 0; round < 2; round++) {
4548 // First run one round to calculate the total size of all
4550 // This would be much simpler if we'd only write one sidx
4551 // atom, for the first track in the moof.
4553 if ((ret = ffio_open_null_buf(&avio_buf)) < 0)
4558 for (i = 0; i < mov->nb_streams; i++) {
4559 MOVTrack *track = &mov->tracks[i];
4560 if (tracks >= 0 && i != tracks)
4562 // When writing a sidx for the full file, entry is 0, but
4563 // we want to include all tracks. ref_size is 0 in this case,
4564 // since we read it from frag_info instead.
4565 if (!track->entry && ref_size > 0)
4567 total_size -= mov_write_sidx_tag(avio_buf, track, ref_size,
4571 total_size = ffio_close_null_buf(avio_buf);
4576 static int mov_write_prft_tag(AVIOContext *pb, MOVMuxContext *mov, int tracks)
4578 int64_t pos = avio_tell(pb), pts_us, ntp_ts;
4579 MOVTrack *first_track;
4581 /* PRFT should be associated with at most one track. So, choosing only the
4585 first_track = &(mov->tracks[0]);
4587 if (!first_track->entry) {
4588 av_log(mov->fc, AV_LOG_WARNING, "Unable to write PRFT, no entries in the track\n");
4592 if (first_track->cluster[0].pts == AV_NOPTS_VALUE) {
4593 av_log(mov->fc, AV_LOG_WARNING, "Unable to write PRFT, first PTS is invalid\n");
4597 if (mov->write_prft == MOV_PRFT_SRC_WALLCLOCK) {
4598 ntp_ts = ff_get_formatted_ntp_time(ff_ntp_time());
4599 } else if (mov->write_prft == MOV_PRFT_SRC_PTS) {
4600 pts_us = av_rescale_q(first_track->cluster[0].pts,
4601 first_track->st->time_base, AV_TIME_BASE_Q);
4602 ntp_ts = ff_get_formatted_ntp_time(pts_us + NTP_OFFSET_US);
4604 av_log(mov->fc, AV_LOG_WARNING, "Unsupported PRFT box configuration: %d\n",
4609 avio_wb32(pb, 0); // Size place holder
4610 ffio_wfourcc(pb, "prft"); // Type
4611 avio_w8(pb, 1); // Version
4612 avio_wb24(pb, 0); // Flags
4613 avio_wb32(pb, first_track->track_id); // reference track ID
4614 avio_wb64(pb, ntp_ts); // NTP time stamp
4615 avio_wb64(pb, first_track->cluster[0].pts); //media time
4616 return update_size(pb, pos);
4619 static int mov_write_moof_tag(AVIOContext *pb, MOVMuxContext *mov, int tracks,
4622 AVIOContext *avio_buf;
4625 if ((ret = ffio_open_null_buf(&avio_buf)) < 0)
4627 mov_write_moof_tag_internal(avio_buf, mov, tracks, 0);
4628 moof_size = ffio_close_null_buf(avio_buf);
4630 if (mov->flags & FF_MOV_FLAG_DASH &&
4631 !(mov->flags & (FF_MOV_FLAG_GLOBAL_SIDX | FF_MOV_FLAG_SKIP_SIDX)))
4632 mov_write_sidx_tags(pb, mov, tracks, moof_size + 8 + mdat_size);
4634 if (mov->write_prft > MOV_PRFT_NONE && mov->write_prft < MOV_PRFT_NB)
4635 mov_write_prft_tag(pb, mov, tracks);
4637 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX ||
4638 !(mov->flags & FF_MOV_FLAG_SKIP_TRAILER) ||
4639 mov->ism_lookahead) {
4640 if ((ret = mov_add_tfra_entries(pb, mov, tracks, moof_size + 8 + mdat_size)) < 0)
4642 if (!(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) &&
4643 mov->flags & FF_MOV_FLAG_SKIP_TRAILER) {
4644 mov_prune_frag_info(mov, tracks, mov->ism_lookahead + 1);
4648 return mov_write_moof_tag_internal(pb, mov, tracks, moof_size);
4651 static int mov_write_tfra_tag(AVIOContext *pb, MOVTrack *track)
4653 int64_t pos = avio_tell(pb);
4656 avio_wb32(pb, 0); /* size placeholder */
4657 ffio_wfourcc(pb, "tfra");
4658 avio_w8(pb, 1); /* version */
4661 avio_wb32(pb, track->track_id);
4662 avio_wb32(pb, 0); /* length of traf/trun/sample num */
4663 avio_wb32(pb, track->nb_frag_info);
4664 for (i = 0; i < track->nb_frag_info; i++) {
4665 avio_wb64(pb, track->frag_info[i].time);
4666 avio_wb64(pb, track->frag_info[i].offset + track->data_offset);
4667 avio_w8(pb, 1); /* traf number */
4668 avio_w8(pb, 1); /* trun number */
4669 avio_w8(pb, 1); /* sample number */
4672 return update_size(pb, pos);
4675 static int mov_write_mfra_tag(AVIOContext *pb, MOVMuxContext *mov)
4677 int64_t pos = avio_tell(pb);
4680 avio_wb32(pb, 0); /* size placeholder */
4681 ffio_wfourcc(pb, "mfra");
4682 /* An empty mfra atom is enough to indicate to the publishing point that
4683 * the stream has ended. */
4684 if (mov->flags & FF_MOV_FLAG_ISML)
4685 return update_size(pb, pos);
4687 for (i = 0; i < mov->nb_streams; i++) {
4688 MOVTrack *track = &mov->tracks[i];
4689 if (track->nb_frag_info)
4690 mov_write_tfra_tag(pb, track);
4694 ffio_wfourcc(pb, "mfro");
4695 avio_wb32(pb, 0); /* version + flags */
4696 avio_wb32(pb, avio_tell(pb) + 4 - pos);
4698 return update_size(pb, pos);
4701 static int mov_write_mdat_tag(AVIOContext *pb, MOVMuxContext *mov)
4703 avio_wb32(pb, 8); // placeholder for extended size field (64 bit)
4704 ffio_wfourcc(pb, mov->mode == MODE_MOV ? "wide" : "free");
4706 mov->mdat_pos = avio_tell(pb);
4707 avio_wb32(pb, 0); /* size placeholder*/
4708 ffio_wfourcc(pb, "mdat");
4712 /* TODO: This needs to be more general */
4713 static int mov_write_ftyp_tag(AVIOContext *pb, AVFormatContext *s)
4715 MOVMuxContext *mov = s->priv_data;
4716 int64_t pos = avio_tell(pb);
4717 int has_h264 = 0, has_video = 0;
4721 for (i = 0; i < s->nb_streams; i++) {
4722 AVStream *st = s->streams[i];
4723 if (is_cover_image(st))
4725 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
4727 if (st->codecpar->codec_id == AV_CODEC_ID_H264)
4731 avio_wb32(pb, 0); /* size */
4732 ffio_wfourcc(pb, "ftyp");
4734 if (mov->major_brand && strlen(mov->major_brand) >= 4)
4735 ffio_wfourcc(pb, mov->major_brand);
4736 else if (mov->mode == MODE_3GP) {
4737 ffio_wfourcc(pb, has_h264 ? "3gp6" : "3gp4");
4738 minor = has_h264 ? 0x100 : 0x200;
4739 } else if (mov->mode & MODE_3G2) {
4740 ffio_wfourcc(pb, has_h264 ? "3g2b" : "3g2a");
4741 minor = has_h264 ? 0x20000 : 0x10000;
4742 } else if (mov->mode == MODE_PSP)
4743 ffio_wfourcc(pb, "MSNV");
4744 else if (mov->mode == MODE_MP4 && mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)
4745 ffio_wfourcc(pb, "iso5"); // Required when using default-base-is-moof
4746 else if (mov->mode == MODE_MP4 && mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS)
4747 ffio_wfourcc(pb, "iso4");
4748 else if (mov->mode == MODE_MP4)
4749 ffio_wfourcc(pb, "isom");
4750 else if (mov->mode == MODE_IPOD)
4751 ffio_wfourcc(pb, has_video ? "M4V ":"M4A ");
4752 else if (mov->mode == MODE_ISM)
4753 ffio_wfourcc(pb, "isml");
4754 else if (mov->mode == MODE_F4V)
4755 ffio_wfourcc(pb, "f4v ");
4757 ffio_wfourcc(pb, "qt ");
4759 avio_wb32(pb, minor);
4761 if (mov->mode == MODE_MOV)
4762 ffio_wfourcc(pb, "qt ");
4763 else if (mov->mode == MODE_ISM) {
4764 ffio_wfourcc(pb, "piff");
4765 } else if (!(mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)) {
4766 ffio_wfourcc(pb, "isom");
4767 ffio_wfourcc(pb, "iso2");
4769 ffio_wfourcc(pb, "avc1");
4772 // We add tfdt atoms when fragmenting, signal this with the iso6 compatible
4773 // brand. This is compatible with users that don't understand tfdt.
4774 if (mov->flags & FF_MOV_FLAG_FRAGMENT && mov->mode != MODE_ISM)
4775 ffio_wfourcc(pb, "iso6");
4777 if (mov->mode == MODE_3GP)
4778 ffio_wfourcc(pb, has_h264 ? "3gp6":"3gp4");
4779 else if (mov->mode & MODE_3G2)
4780 ffio_wfourcc(pb, has_h264 ? "3g2b":"3g2a");
4781 else if (mov->mode == MODE_PSP)
4782 ffio_wfourcc(pb, "MSNV");
4783 else if (mov->mode == MODE_MP4)
4784 ffio_wfourcc(pb, "mp41");
4786 if (mov->flags & FF_MOV_FLAG_DASH && mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
4787 ffio_wfourcc(pb, "dash");
4789 return update_size(pb, pos);
4792 static int mov_write_uuidprof_tag(AVIOContext *pb, AVFormatContext *s)
4794 AVStream *video_st = s->streams[0];
4795 AVCodecParameters *video_par = s->streams[0]->codecpar;
4796 AVCodecParameters *audio_par = s->streams[1]->codecpar;
4797 int audio_rate = audio_par->sample_rate;
4798 int64_t frame_rate = video_st->avg_frame_rate.den ?
4799 (video_st->avg_frame_rate.num * 0x10000LL) / video_st->avg_frame_rate.den :
4801 int audio_kbitrate = audio_par->bit_rate / 1000;
4802 int video_kbitrate = FFMIN(video_par->bit_rate / 1000, 800 - audio_kbitrate);
4804 if (frame_rate < 0 || frame_rate > INT32_MAX) {
4805 av_log(s, AV_LOG_ERROR, "Frame rate %f outside supported range\n", frame_rate / (double)0x10000);
4806 return AVERROR(EINVAL);
4809 avio_wb32(pb, 0x94); /* size */
4810 ffio_wfourcc(pb, "uuid");
4811 ffio_wfourcc(pb, "PROF");
4813 avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
4814 avio_wb32(pb, 0xbb88695c);
4815 avio_wb32(pb, 0xfac9c740);
4817 avio_wb32(pb, 0x0); /* ? */
4818 avio_wb32(pb, 0x3); /* 3 sections ? */
4820 avio_wb32(pb, 0x14); /* size */
4821 ffio_wfourcc(pb, "FPRF");
4822 avio_wb32(pb, 0x0); /* ? */
4823 avio_wb32(pb, 0x0); /* ? */
4824 avio_wb32(pb, 0x0); /* ? */
4826 avio_wb32(pb, 0x2c); /* size */
4827 ffio_wfourcc(pb, "APRF"); /* audio */
4829 avio_wb32(pb, 0x2); /* TrackID */
4830 ffio_wfourcc(pb, "mp4a");
4831 avio_wb32(pb, 0x20f);
4833 avio_wb32(pb, audio_kbitrate);
4834 avio_wb32(pb, audio_kbitrate);
4835 avio_wb32(pb, audio_rate);
4836 avio_wb32(pb, audio_par->channels);
4838 avio_wb32(pb, 0x34); /* size */
4839 ffio_wfourcc(pb, "VPRF"); /* video */
4841 avio_wb32(pb, 0x1); /* TrackID */
4842 if (video_par->codec_id == AV_CODEC_ID_H264) {
4843 ffio_wfourcc(pb, "avc1");
4844 avio_wb16(pb, 0x014D);
4845 avio_wb16(pb, 0x0015);
4847 ffio_wfourcc(pb, "mp4v");
4848 avio_wb16(pb, 0x0000);
4849 avio_wb16(pb, 0x0103);
4852 avio_wb32(pb, video_kbitrate);
4853 avio_wb32(pb, video_kbitrate);
4854 avio_wb32(pb, frame_rate);
4855 avio_wb32(pb, frame_rate);
4856 avio_wb16(pb, video_par->width);
4857 avio_wb16(pb, video_par->height);
4858 avio_wb32(pb, 0x010001); /* ? */
4863 static int mov_write_identification(AVIOContext *pb, AVFormatContext *s)
4865 MOVMuxContext *mov = s->priv_data;
4868 mov_write_ftyp_tag(pb,s);
4869 if (mov->mode == MODE_PSP) {
4870 int video_streams_nb = 0, audio_streams_nb = 0, other_streams_nb = 0;
4871 for (i = 0; i < s->nb_streams; i++) {
4872 AVStream *st = s->streams[i];
4873 if (is_cover_image(st))
4875 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
4877 else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
4883 if (video_streams_nb != 1 || audio_streams_nb != 1 || other_streams_nb) {
4884 av_log(s, AV_LOG_ERROR, "PSP mode need one video and one audio stream\n");
4885 return AVERROR(EINVAL);
4887 return mov_write_uuidprof_tag(pb, s);
4892 static int mov_parse_mpeg2_frame(AVPacket *pkt, uint32_t *flags)
4895 int i, closed_gop = 0;
4897 for (i = 0; i < pkt->size - 4; i++) {
4898 c = (c << 8) + pkt->data[i];
4899 if (c == 0x1b8) { // gop
4900 closed_gop = pkt->data[i + 4] >> 6 & 0x01;
4901 } else if (c == 0x100) { // pic
4902 int temp_ref = (pkt->data[i + 1] << 2) | (pkt->data[i + 2] >> 6);
4903 if (!temp_ref || closed_gop) // I picture is not reordered
4904 *flags = MOV_SYNC_SAMPLE;
4906 *flags = MOV_PARTIAL_SYNC_SAMPLE;
4913 static void mov_parse_vc1_frame(AVPacket *pkt, MOVTrack *trk)
4915 const uint8_t *start, *next, *end = pkt->data + pkt->size;
4916 int seq = 0, entry = 0;
4917 int key = pkt->flags & AV_PKT_FLAG_KEY;
4918 start = find_next_marker(pkt->data, end);
4919 for (next = start; next < end; start = next) {
4920 next = find_next_marker(start + 4, end);
4921 switch (AV_RB32(start)) {
4922 case VC1_CODE_SEQHDR:
4925 case VC1_CODE_ENTRYPOINT:
4928 case VC1_CODE_SLICE:
4929 trk->vc1_info.slices = 1;
4933 if (!trk->entry && trk->vc1_info.first_packet_seen)
4934 trk->vc1_info.first_frag_written = 1;
4935 if (!trk->entry && !trk->vc1_info.first_frag_written) {
4936 /* First packet in first fragment */
4937 trk->vc1_info.first_packet_seq = seq;
4938 trk->vc1_info.first_packet_entry = entry;
4939 trk->vc1_info.first_packet_seen = 1;
4940 } else if ((seq && !trk->vc1_info.packet_seq) ||
4941 (entry && !trk->vc1_info.packet_entry)) {
4943 for (i = 0; i < trk->entry; i++)
4944 trk->cluster[i].flags &= ~MOV_SYNC_SAMPLE;
4945 trk->has_keyframes = 0;
4947 trk->vc1_info.packet_seq = 1;
4949 trk->vc1_info.packet_entry = 1;
4950 if (!trk->vc1_info.first_frag_written) {
4951 /* First fragment */
4952 if ((!seq || trk->vc1_info.first_packet_seq) &&
4953 (!entry || trk->vc1_info.first_packet_entry)) {
4954 /* First packet had the same headers as this one, readd the
4955 * sync sample flag. */
4956 trk->cluster[0].flags |= MOV_SYNC_SAMPLE;
4957 trk->has_keyframes = 1;
4961 if (trk->vc1_info.packet_seq && trk->vc1_info.packet_entry)
4963 else if (trk->vc1_info.packet_seq)
4965 else if (trk->vc1_info.packet_entry)
4968 trk->cluster[trk->entry].flags |= MOV_SYNC_SAMPLE;
4969 trk->has_keyframes++;
4973 static int mov_flush_fragment_interleaving(AVFormatContext *s, MOVTrack *track)
4975 MOVMuxContext *mov = s->priv_data;
4980 if (!track->mdat_buf)
4982 if (!mov->mdat_buf) {
4983 if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0)
4986 buf_size = avio_close_dyn_buf(track->mdat_buf, &buf);
4987 track->mdat_buf = NULL;
4989 offset = avio_tell(mov->mdat_buf);
4990 avio_write(mov->mdat_buf, buf, buf_size);
4993 for (i = track->entries_flushed; i < track->entry; i++)
4994 track->cluster[i].pos += offset;
4995 track->entries_flushed = track->entry;
4999 static int mov_flush_fragment(AVFormatContext *s, int force)
5001 MOVMuxContext *mov = s->priv_data;
5002 int i, first_track = -1;
5003 int64_t mdat_size = 0;
5005 int has_video = 0, starts_with_key = 0, first_video_track = 1;
5007 if (!(mov->flags & FF_MOV_FLAG_FRAGMENT))
5010 // Try to fill in the duration of the last packet in each stream
5011 // from queued packets in the interleave queues. If the flushing
5012 // of fragments was triggered automatically by an AVPacket, we
5013 // already have reliable info for the end of that track, but other
5014 // tracks may need to be filled in.
5015 for (i = 0; i < s->nb_streams; i++) {
5016 MOVTrack *track = &mov->tracks[i];
5017 if (!track->end_reliable) {
5019 if (!ff_interleaved_peek(s, i, &pkt, 1)) {
5020 if (track->dts_shift != AV_NOPTS_VALUE)
5021 pkt.dts += track->dts_shift;
5022 track->track_duration = pkt.dts - track->start_dts;
5023 if (pkt.pts != AV_NOPTS_VALUE)
5024 track->end_pts = pkt.pts;
5026 track->end_pts = pkt.dts;
5031 for (i = 0; i < mov->nb_streams; i++) {
5032 MOVTrack *track = &mov->tracks[i];
5033 if (track->entry <= 1)
5035 // Sample durations are calculated as the diff of dts values,
5036 // but for the last sample in a fragment, we don't know the dts
5037 // of the first sample in the next fragment, so we have to rely
5038 // on what was set as duration in the AVPacket. Not all callers
5039 // set this though, so we might want to replace it with an
5040 // estimate if it currently is zero.
5041 if (get_cluster_duration(track, track->entry - 1) != 0)
5043 // Use the duration (i.e. dts diff) of the second last sample for
5044 // the last one. This is a wild guess (and fatal if it turns out
5045 // to be too long), but probably the best we can do - having a zero
5046 // duration is bad as well.
5047 track->track_duration += get_cluster_duration(track, track->entry - 2);
5048 track->end_pts += get_cluster_duration(track, track->entry - 2);
5049 if (!mov->missing_duration_warned) {
5050 av_log(s, AV_LOG_WARNING,
5051 "Estimating the duration of the last packet in a "
5052 "fragment, consider setting the duration field in "
5053 "AVPacket instead.\n");
5054 mov->missing_duration_warned = 1;
5058 if (!mov->moov_written) {
5059 int64_t pos = avio_tell(s->pb);
5061 int buf_size, moov_size;
5063 for (i = 0; i < mov->nb_streams; i++)
5064 if (!mov->tracks[i].entry && !is_cover_image(mov->tracks[i].st))
5066 /* Don't write the initial moov unless all tracks have data */
5067 if (i < mov->nb_streams && !force)
5070 moov_size = get_moov_size(s);
5071 for (i = 0; i < mov->nb_streams; i++)
5072 mov->tracks[i].data_offset = pos + moov_size + 8;
5074 avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_HEADER);
5075 if (mov->flags & FF_MOV_FLAG_DELAY_MOOV)
5076 mov_write_identification(s->pb, s);
5077 if ((ret = mov_write_moov_tag(s->pb, mov, s)) < 0)
5080 if (mov->flags & FF_MOV_FLAG_DELAY_MOOV) {
5081 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
5082 mov->reserved_header_pos = avio_tell(s->pb);
5084 mov->moov_written = 1;
5088 buf_size = avio_close_dyn_buf(mov->mdat_buf, &buf);
5089 mov->mdat_buf = NULL;
5090 avio_wb32(s->pb, buf_size + 8);
5091 ffio_wfourcc(s->pb, "mdat");
5092 avio_write(s->pb, buf, buf_size);
5095 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
5096 mov->reserved_header_pos = avio_tell(s->pb);
5098 mov->moov_written = 1;
5100 for (i = 0; i < mov->nb_streams; i++) {
5101 if (mov->tracks[i].entry)
5102 mov->tracks[i].frag_start += mov->tracks[i].start_dts +
5103 mov->tracks[i].track_duration -
5104 mov->tracks[i].cluster[0].dts;
5105 mov->tracks[i].entry = 0;
5106 mov->tracks[i].end_reliable = 0;
5112 if (mov->frag_interleave) {
5113 for (i = 0; i < mov->nb_streams; i++) {
5114 MOVTrack *track = &mov->tracks[i];
5116 if ((ret = mov_flush_fragment_interleaving(s, track)) < 0)
5122 mdat_size = avio_tell(mov->mdat_buf);
5125 for (i = 0; i < mov->nb_streams; i++) {
5126 MOVTrack *track = &mov->tracks[i];
5127 if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF || mov->frag_interleave)
5128 track->data_offset = 0;
5130 track->data_offset = mdat_size;
5131 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
5133 if (first_video_track) {
5135 starts_with_key = track->cluster[0].flags & MOV_SYNC_SAMPLE;
5136 first_video_track = 0;
5141 if (track->mdat_buf)
5142 mdat_size += avio_tell(track->mdat_buf);
5143 if (first_track < 0)
5150 avio_write_marker(s->pb,
5151 av_rescale(mov->tracks[first_track].cluster[0].dts, AV_TIME_BASE, mov->tracks[first_track].timescale),
5152 (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);
5154 for (i = 0; i < mov->nb_streams; i++) {
5155 MOVTrack *track = &mov->tracks[i];
5156 int buf_size, write_moof = 1, moof_tracks = -1;
5158 int64_t duration = 0;
5161 duration = track->start_dts + track->track_duration -
5162 track->cluster[0].dts;
5163 if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF) {
5164 if (!track->mdat_buf)
5166 mdat_size = avio_tell(track->mdat_buf);
5169 write_moof = i == first_track;
5175 mov_write_moof_tag(s->pb, mov, moof_tracks, mdat_size);
5178 avio_wb32(s->pb, mdat_size + 8);
5179 ffio_wfourcc(s->pb, "mdat");
5183 track->frag_start += duration;
5185 track->entries_flushed = 0;
5186 track->end_reliable = 0;
5187 if (!mov->frag_interleave) {
5188 if (!track->mdat_buf)
5190 buf_size = avio_close_dyn_buf(track->mdat_buf, &buf);
5191 track->mdat_buf = NULL;
5195 buf_size = avio_close_dyn_buf(mov->mdat_buf, &buf);
5196 mov->mdat_buf = NULL;
5199 avio_write(s->pb, buf, buf_size);
5209 static int mov_auto_flush_fragment(AVFormatContext *s, int force)
5211 MOVMuxContext *mov = s->priv_data;
5212 int had_moov = mov->moov_written;
5213 int ret = mov_flush_fragment(s, force);
5216 // If using delay_moov, the first flush only wrote the moov,
5217 // not the actual moof+mdat pair, thus flush once again.
5218 if (!had_moov && mov->flags & FF_MOV_FLAG_DELAY_MOOV)
5219 ret = mov_flush_fragment(s, force);
5223 static int check_pkt(AVFormatContext *s, AVPacket *pkt)
5225 MOVMuxContext *mov = s->priv_data;
5226 MOVTrack *trk = &mov->tracks[pkt->stream_index];
5231 ref = trk->cluster[trk->entry - 1].dts;
5232 } else if ( trk->start_dts != AV_NOPTS_VALUE
5233 && !trk->frag_discont) {
5234 ref = trk->start_dts + trk->track_duration;
5236 ref = pkt->dts; // Skip tests for the first packet
5238 if (trk->dts_shift != AV_NOPTS_VALUE) {
5239 /* With negative CTS offsets we have set an offset to the DTS,
5240 * reverse this for the check. */
5241 ref -= trk->dts_shift;
5244 duration = pkt->dts - ref;
5245 if (pkt->dts < ref || duration >= INT_MAX) {
5246 av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" / timestamp: %"PRId64" is out of range for mov/mp4 format\n",
5251 pkt->pts = AV_NOPTS_VALUE;
5254 if (pkt->duration < 0 || pkt->duration > INT_MAX) {
5255 av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" is invalid\n", pkt->duration);
5256 return AVERROR(EINVAL);
5261 int ff_mov_write_packet(AVFormatContext *s, AVPacket *pkt)
5263 MOVMuxContext *mov = s->priv_data;
5264 AVIOContext *pb = s->pb;
5265 MOVTrack *trk = &mov->tracks[pkt->stream_index];
5266 AVCodecParameters *par = trk->par;
5267 unsigned int samples_in_chunk = 0;
5268 int size = pkt->size, ret = 0;
5269 uint8_t *reformatted_data = NULL;
5271 ret = check_pkt(s, pkt);
5275 if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
5277 if (mov->moov_written || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
5278 if (mov->frag_interleave && mov->fragments > 0) {
5279 if (trk->entry - trk->entries_flushed >= mov->frag_interleave) {
5280 if ((ret = mov_flush_fragment_interleaving(s, trk)) < 0)
5285 if (!trk->mdat_buf) {
5286 if ((ret = avio_open_dyn_buf(&trk->mdat_buf)) < 0)
5291 if (!mov->mdat_buf) {
5292 if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0)
5299 if (par->codec_id == AV_CODEC_ID_AMR_NB) {
5300 /* We must find out how many AMR blocks there are in one packet */
5301 static const uint16_t packed_size[16] =
5302 {13, 14, 16, 18, 20, 21, 27, 32, 6, 0, 0, 0, 0, 0, 0, 1};
5305 while (len < size && samples_in_chunk < 100) {
5306 len += packed_size[(pkt->data[len] >> 3) & 0x0F];
5309 if (samples_in_chunk > 1) {
5310 av_log(s, AV_LOG_ERROR, "fatal error, input is not a single packet, implement a AVParser for it\n");
5313 } else if (par->codec_id == AV_CODEC_ID_ADPCM_MS ||
5314 par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) {
5315 samples_in_chunk = trk->par->frame_size;
5316 } else if (trk->sample_size)
5317 samples_in_chunk = size / trk->sample_size;
5319 samples_in_chunk = 1;
5321 if (samples_in_chunk < 1) {
5322 av_log(s, AV_LOG_ERROR, "fatal error, input packet contains no samples\n");
5323 return AVERROR_PATCHWELCOME;
5326 /* copy extradata if it exists */
5327 if (trk->vos_len == 0 && par->extradata_size > 0 &&
5328 !TAG_IS_AVCI(trk->tag) &&
5329 (par->codec_id != AV_CODEC_ID_DNXHD)) {
5330 trk->vos_len = par->extradata_size;
5331 trk->vos_data = av_malloc(trk->vos_len);
5332 if (!trk->vos_data) {
5333 ret = AVERROR(ENOMEM);
5336 memcpy(trk->vos_data, par->extradata, trk->vos_len);
5339 if (par->codec_id == AV_CODEC_ID_AAC && pkt->size > 2 &&
5340 (AV_RB16(pkt->data) & 0xfff0) == 0xfff0) {
5341 if (!s->streams[pkt->stream_index]->nb_frames) {
5342 av_log(s, AV_LOG_ERROR, "Malformed AAC bitstream detected: "
5343 "use the audio bitstream filter 'aac_adtstoasc' to fix it "
5344 "('-bsf:a aac_adtstoasc' option with ffmpeg)\n");
5347 av_log(s, AV_LOG_WARNING, "aac bitstream error\n");
5349 if (par->codec_id == AV_CODEC_ID_H264 && trk->vos_len > 0 && *(uint8_t *)trk->vos_data != 1 && !TAG_IS_AVCI(trk->tag)) {
5350 /* from x264 or from bytestream H.264 */
5351 /* NAL reformatting needed */
5352 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
5353 ff_avc_parse_nal_units_buf(pkt->data, &reformatted_data,
5355 avio_write(pb, reformatted_data, size);
5357 if (trk->cenc.aes_ctr) {
5358 size = ff_mov_cenc_avc_parse_nal_units(&trk->cenc, pb, pkt->data, size);
5364 size = ff_avc_parse_nal_units(pb, pkt->data, pkt->size);
5367 } else if (par->codec_id == AV_CODEC_ID_HEVC && trk->vos_len > 6 &&
5368 (AV_RB24(trk->vos_data) == 1 || AV_RB32(trk->vos_data) == 1)) {
5369 /* extradata is Annex B, assume the bitstream is too and convert it */
5370 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
5371 ff_hevc_annexb2mp4_buf(pkt->data, &reformatted_data, &size, 0, NULL);
5372 avio_write(pb, reformatted_data, size);
5374 size = ff_hevc_annexb2mp4(pb, pkt->data, pkt->size, 0, NULL);
5376 } else if (par->codec_id == AV_CODEC_ID_AV1) {
5377 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
5378 ff_av1_filter_obus_buf(pkt->data, &reformatted_data, &size);
5379 avio_write(pb, reformatted_data, size);
5381 size = ff_av1_filter_obus(pb, pkt->data, pkt->size);
5383 #if CONFIG_AC3_PARSER
5384 } else if (par->codec_id == AV_CODEC_ID_EAC3) {
5385 size = handle_eac3(mov, pkt, trk);
5390 avio_write(pb, pkt->data, size);
5393 if (trk->cenc.aes_ctr) {
5394 if (par->codec_id == AV_CODEC_ID_H264 && par->extradata_size > 4) {
5395 int nal_size_length = (par->extradata[4] & 0x3) + 1;
5396 ret = ff_mov_cenc_avc_write_nal_units(s, &trk->cenc, nal_size_length, pb, pkt->data, size);
5398 ret = ff_mov_cenc_write_packet(&trk->cenc, pb, pkt->data, size);
5405 avio_write(pb, pkt->data, size);
5409 if ((par->codec_id == AV_CODEC_ID_DNXHD ||
5410 par->codec_id == AV_CODEC_ID_AC3) && !trk->vos_len) {
5411 /* copy frame to create needed atoms */
5412 trk->vos_len = size;
5413 trk->vos_data = av_malloc(size);
5414 if (!trk->vos_data) {
5415 ret = AVERROR(ENOMEM);
5418 memcpy(trk->vos_data, pkt->data, size);
5421 if (trk->entry >= trk->cluster_capacity) {
5422 unsigned new_capacity = 2 * (trk->entry + MOV_INDEX_CLUSTER_SIZE);
5423 if (av_reallocp_array(&trk->cluster, new_capacity,
5424 sizeof(*trk->cluster))) {
5425 ret = AVERROR(ENOMEM);
5428 trk->cluster_capacity = new_capacity;
5431 trk->cluster[trk->entry].pos = avio_tell(pb) - size;
5432 trk->cluster[trk->entry].samples_in_chunk = samples_in_chunk;
5433 trk->cluster[trk->entry].chunkNum = 0;
5434 trk->cluster[trk->entry].size = size;
5435 trk->cluster[trk->entry].entries = samples_in_chunk;
5436 trk->cluster[trk->entry].dts = pkt->dts;
5437 trk->cluster[trk->entry].pts = pkt->pts;
5438 if (!trk->entry && trk->start_dts != AV_NOPTS_VALUE) {
5439 if (!trk->frag_discont) {
5440 /* First packet of a new fragment. We already wrote the duration
5441 * of the last packet of the previous fragment based on track_duration,
5442 * which might not exactly match our dts. Therefore adjust the dts
5443 * of this packet to be what the previous packets duration implies. */
5444 trk->cluster[trk->entry].dts = trk->start_dts + trk->track_duration;
5445 /* We also may have written the pts and the corresponding duration
5446 * in sidx/tfrf/tfxd tags; make sure the sidx pts and duration match up with
5447 * the next fragment. This means the cts of the first sample must
5448 * be the same in all fragments, unless end_pts was updated by
5449 * the packet causing the fragment to be written. */
5450 if ((mov->flags & FF_MOV_FLAG_DASH &&
5451 !(mov->flags & (FF_MOV_FLAG_GLOBAL_SIDX | FF_MOV_FLAG_SKIP_SIDX))) ||
5452 mov->mode == MODE_ISM)
5453 pkt->pts = pkt->dts + trk->end_pts - trk->cluster[trk->entry].dts;
5455 /* New fragment, but discontinuous from previous fragments.
5456 * Pretend the duration sum of the earlier fragments is
5457 * pkt->dts - trk->start_dts. */
5458 trk->frag_start = pkt->dts - trk->start_dts;
5459 trk->end_pts = AV_NOPTS_VALUE;
5460 trk->frag_discont = 0;
5464 if (!trk->entry && trk->start_dts == AV_NOPTS_VALUE && !mov->use_editlist &&
5465 s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO) {
5466 /* Not using edit lists and shifting the first track to start from zero.
5467 * If the other streams start from a later timestamp, we won't be able
5468 * to signal the difference in starting time without an edit list.
5469 * Thus move the timestamp for this first sample to 0, increasing
5470 * its duration instead. */
5471 trk->cluster[trk->entry].dts = trk->start_dts = 0;
5473 if (trk->start_dts == AV_NOPTS_VALUE) {
5474 trk->start_dts = pkt->dts;
5475 if (trk->frag_discont) {
5476 if (mov->use_editlist) {
5477 /* Pretend the whole stream started at pts=0, with earlier fragments
5478 * already written. If the stream started at pts=0, the duration sum
5479 * of earlier fragments would have been pkt->pts. */
5480 trk->frag_start = pkt->pts;
5481 trk->start_dts = pkt->dts - pkt->pts;
5483 /* Pretend the whole stream started at dts=0, with earlier fragments
5484 * already written, with a duration summing up to pkt->dts. */
5485 trk->frag_start = pkt->dts;
5488 trk->frag_discont = 0;
5489 } else if (pkt->dts && mov->moov_written)
5490 av_log(s, AV_LOG_WARNING,
5491 "Track %d starts with a nonzero dts %"PRId64", while the moov "
5492 "already has been written. Set the delay_moov flag to handle "
5494 pkt->stream_index, pkt->dts);
5496 trk->track_duration = pkt->dts - trk->start_dts + pkt->duration;
5497 trk->last_sample_is_subtitle_end = 0;
5499 if (pkt->pts == AV_NOPTS_VALUE) {
5500 av_log(s, AV_LOG_WARNING, "pts has no value\n");
5501 pkt->pts = pkt->dts;
5503 if (pkt->dts != pkt->pts)
5504 trk->flags |= MOV_TRACK_CTTS;
5505 trk->cluster[trk->entry].cts = pkt->pts - pkt->dts;
5506 trk->cluster[trk->entry].flags = 0;
5507 if (trk->start_cts == AV_NOPTS_VALUE)
5508 trk->start_cts = pkt->pts - pkt->dts;
5509 if (trk->end_pts == AV_NOPTS_VALUE)
5510 trk->end_pts = trk->cluster[trk->entry].dts +
5511 trk->cluster[trk->entry].cts + pkt->duration;
5513 trk->end_pts = FFMAX(trk->end_pts, trk->cluster[trk->entry].dts +
5514 trk->cluster[trk->entry].cts +
5517 if (par->codec_id == AV_CODEC_ID_VC1) {
5518 mov_parse_vc1_frame(pkt, trk);
5519 } else if (pkt->flags & AV_PKT_FLAG_KEY) {
5520 if (mov->mode == MODE_MOV && par->codec_id == AV_CODEC_ID_MPEG2VIDEO &&
5521 trk->entry > 0) { // force sync sample for the first key frame
5522 mov_parse_mpeg2_frame(pkt, &trk->cluster[trk->entry].flags);
5523 if (trk->cluster[trk->entry].flags & MOV_PARTIAL_SYNC_SAMPLE)
5524 trk->flags |= MOV_TRACK_STPS;
5526 trk->cluster[trk->entry].flags = MOV_SYNC_SAMPLE;
5528 if (trk->cluster[trk->entry].flags & MOV_SYNC_SAMPLE)
5529 trk->has_keyframes++;
5531 if (pkt->flags & AV_PKT_FLAG_DISPOSABLE) {
5532 trk->cluster[trk->entry].flags |= MOV_DISPOSABLE_SAMPLE;
5533 trk->has_disposable++;
5536 trk->sample_count += samples_in_chunk;
5537 mov->mdat_size += size;
5539 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams)
5540 ff_mov_add_hinted_packet(s, pkt, trk->hint_track, trk->entry,
5541 reformatted_data, size);
5546 av_free(reformatted_data);
5550 static int mov_write_single_packet(AVFormatContext *s, AVPacket *pkt)
5552 MOVMuxContext *mov = s->priv_data;
5553 MOVTrack *trk = &mov->tracks[pkt->stream_index];
5554 AVCodecParameters *par = trk->par;
5555 int64_t frag_duration = 0;
5556 int size = pkt->size;
5558 int ret = check_pkt(s, pkt);
5562 if (mov->flags & FF_MOV_FLAG_FRAG_DISCONT) {
5564 for (i = 0; i < s->nb_streams; i++)
5565 mov->tracks[i].frag_discont = 1;
5566 mov->flags &= ~FF_MOV_FLAG_FRAG_DISCONT;
5569 if (mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS) {
5570 if (trk->dts_shift == AV_NOPTS_VALUE)
5571 trk->dts_shift = pkt->pts - pkt->dts;
5572 pkt->dts += trk->dts_shift;
5575 if (trk->par->codec_id == AV_CODEC_ID_MP4ALS ||
5576 trk->par->codec_id == AV_CODEC_ID_AAC ||
5577 trk->par->codec_id == AV_CODEC_ID_AV1 ||
5578 trk->par->codec_id == AV_CODEC_ID_FLAC) {
5580 uint8_t *side = av_packet_get_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA, &side_size);
5581 if (side && side_size > 0 && (side_size != par->extradata_size || memcmp(side, par->extradata, side_size))) {
5582 void *newextra = av_mallocz(side_size + AV_INPUT_BUFFER_PADDING_SIZE);
5584 return AVERROR(ENOMEM);
5585 av_free(par->extradata);
5586 par->extradata = newextra;
5587 memcpy(par->extradata, side, side_size);
5588 par->extradata_size = side_size;
5589 if (!pkt->size) // Flush packet
5590 mov->need_rewrite_extradata = 1;
5595 if (trk->start_dts == AV_NOPTS_VALUE && trk->frag_discont) {
5596 trk->start_dts = pkt->dts;
5597 if (pkt->pts != AV_NOPTS_VALUE)
5598 trk->start_cts = pkt->pts - pkt->dts;
5603 return 0; /* Discard 0 sized packets */
5606 if (trk->entry && pkt->stream_index < s->nb_streams)
5607 frag_duration = av_rescale_q(pkt->dts - trk->cluster[0].dts,
5608 s->streams[pkt->stream_index]->time_base,
5610 if ((mov->max_fragment_duration &&
5611 frag_duration >= mov->max_fragment_duration) ||
5612 (mov->max_fragment_size && mov->mdat_size + size >= mov->max_fragment_size) ||
5613 (mov->flags & FF_MOV_FLAG_FRAG_KEYFRAME &&
5614 par->codec_type == AVMEDIA_TYPE_VIDEO &&
5615 trk->entry && pkt->flags & AV_PKT_FLAG_KEY) ||
5616 (mov->flags & FF_MOV_FLAG_FRAG_EVERY_FRAME)) {
5617 if (frag_duration >= mov->min_fragment_duration) {
5618 // Set the duration of this track to line up with the next
5619 // sample in this track. This avoids relying on AVPacket
5620 // duration, but only helps for this particular track, not
5621 // for the other ones that are flushed at the same time.
5622 trk->track_duration = pkt->dts - trk->start_dts;
5623 if (pkt->pts != AV_NOPTS_VALUE)
5624 trk->end_pts = pkt->pts;
5626 trk->end_pts = pkt->dts;
5627 trk->end_reliable = 1;
5628 mov_auto_flush_fragment(s, 0);
5632 return ff_mov_write_packet(s, pkt);
5635 static int mov_write_subtitle_end_packet(AVFormatContext *s,
5639 uint8_t data[2] = {0};
5642 av_init_packet(&end);
5643 end.size = sizeof(data);
5648 end.stream_index = stream_index;
5650 ret = mov_write_single_packet(s, &end);
5651 av_packet_unref(&end);
5656 static int mov_write_packet(AVFormatContext *s, AVPacket *pkt)
5658 MOVMuxContext *mov = s->priv_data;
5662 mov_flush_fragment(s, 1);
5666 trk = &mov->tracks[pkt->stream_index];
5668 if (is_cover_image(trk->st)) {
5671 if (trk->st->nb_frames >= 1) {
5672 if (trk->st->nb_frames == 1)
5673 av_log(s, AV_LOG_WARNING, "Got more than one picture in stream %d,"
5674 " ignoring.\n", pkt->stream_index);
5678 if ((ret = av_packet_ref(&trk->cover_image, pkt)) < 0)
5686 return mov_write_single_packet(s, pkt); /* Passthrough. */
5689 * Subtitles require special handling.
5691 * 1) For full complaince, every track must have a sample at
5692 * dts == 0, which is rarely true for subtitles. So, as soon
5693 * as we see any packet with dts > 0, write an empty subtitle
5694 * at dts == 0 for any subtitle track with no samples in it.
5696 * 2) For each subtitle track, check if the current packet's
5697 * dts is past the duration of the last subtitle sample. If
5698 * so, we now need to write an end sample for that subtitle.
5700 * This must be done conditionally to allow for subtitles that
5701 * immediately replace each other, in which case an end sample
5702 * is not needed, and is, in fact, actively harmful.
5704 * 3) See mov_write_trailer for how the final end sample is
5707 for (i = 0; i < mov->nb_streams; i++) {
5708 MOVTrack *trk = &mov->tracks[i];
5711 if (trk->par->codec_id == AV_CODEC_ID_MOV_TEXT &&
5712 trk->track_duration < pkt->dts &&
5713 (trk->entry == 0 || !trk->last_sample_is_subtitle_end)) {
5714 ret = mov_write_subtitle_end_packet(s, i, trk->track_duration);
5715 if (ret < 0) return ret;
5716 trk->last_sample_is_subtitle_end = 1;
5720 if (trk->mode == MODE_MOV && trk->par->codec_type == AVMEDIA_TYPE_VIDEO) {
5721 AVPacket *opkt = pkt;
5722 int reshuffle_ret, ret;
5723 if (trk->is_unaligned_qt_rgb) {
5724 int64_t bpc = trk->par->bits_per_coded_sample != 15 ? trk->par->bits_per_coded_sample : 16;
5725 int expected_stride = ((trk->par->width * bpc + 15) >> 4)*2;
5726 reshuffle_ret = ff_reshuffle_raw_rgb(s, &pkt, trk->par, expected_stride);
5727 if (reshuffle_ret < 0)
5728 return reshuffle_ret;
5731 if (trk->par->format == AV_PIX_FMT_PAL8 && !trk->pal_done) {
5732 ret = ff_get_packet_palette(s, opkt, reshuffle_ret, trk->palette);
5737 } else if (trk->par->codec_id == AV_CODEC_ID_RAWVIDEO &&
5738 (trk->par->format == AV_PIX_FMT_GRAY8 ||
5739 trk->par->format == AV_PIX_FMT_MONOBLACK)) {
5740 for (i = 0; i < pkt->size; i++)
5741 pkt->data[i] = ~pkt->data[i];
5743 if (reshuffle_ret) {
5744 ret = mov_write_single_packet(s, pkt);
5747 av_packet_free(&pkt);
5752 return mov_write_single_packet(s, pkt);
5756 // QuickTime chapters involve an additional text track with the chapter names
5757 // as samples, and a tref pointing from the other tracks to the chapter one.
5758 static int mov_create_chapter_track(AVFormatContext *s, int tracknum)
5762 MOVMuxContext *mov = s->priv_data;
5763 MOVTrack *track = &mov->tracks[tracknum];
5764 AVPacket pkt = { .stream_index = tracknum, .flags = AV_PKT_FLAG_KEY };
5767 track->mode = mov->mode;
5768 track->tag = MKTAG('t','e','x','t');
5769 track->timescale = MOV_TIMESCALE;
5770 track->par = avcodec_parameters_alloc();
5772 return AVERROR(ENOMEM);
5773 track->par->codec_type = AVMEDIA_TYPE_SUBTITLE;
5775 // These properties are required to make QT recognize the chapter track
5776 uint8_t chapter_properties[43] = { 0, 0, 0, 0, 0, 0, 0, 1, };
5777 if (ff_alloc_extradata(track->par, sizeof(chapter_properties)))
5778 return AVERROR(ENOMEM);
5779 memcpy(track->par->extradata, chapter_properties, sizeof(chapter_properties));
5781 if (avio_open_dyn_buf(&pb) >= 0) {
5785 /* Stub header (usually for Quicktime chapter track) */
5787 avio_wb32(pb, 0x01); // displayFlags
5788 avio_w8(pb, 0x00); // horizontal justification
5789 avio_w8(pb, 0x00); // vertical justification
5790 avio_w8(pb, 0x00); // bgColourRed
5791 avio_w8(pb, 0x00); // bgColourGreen
5792 avio_w8(pb, 0x00); // bgColourBlue
5793 avio_w8(pb, 0x00); // bgColourAlpha
5795 avio_wb16(pb, 0x00); // defTextBoxTop
5796 avio_wb16(pb, 0x00); // defTextBoxLeft
5797 avio_wb16(pb, 0x00); // defTextBoxBottom
5798 avio_wb16(pb, 0x00); // defTextBoxRight
5800 avio_wb16(pb, 0x00); // startChar
5801 avio_wb16(pb, 0x00); // endChar
5802 avio_wb16(pb, 0x01); // fontID
5803 avio_w8(pb, 0x00); // fontStyleFlags
5804 avio_w8(pb, 0x00); // fontSize
5805 avio_w8(pb, 0x00); // fgColourRed
5806 avio_w8(pb, 0x00); // fgColourGreen
5807 avio_w8(pb, 0x00); // fgColourBlue
5808 avio_w8(pb, 0x00); // fgColourAlpha
5810 avio_wb32(pb, 0x0D); // box size
5811 ffio_wfourcc(pb, "ftab"); // box atom name
5812 avio_wb16(pb, 0x01); // entry count
5814 avio_wb16(pb, 0x01); // font ID
5815 avio_w8(pb, 0x00); // font name length
5817 if ((size = avio_close_dyn_buf(pb, &buf)) > 0) {
5818 track->par->extradata = buf;
5819 track->par->extradata_size = size;
5826 for (i = 0; i < s->nb_chapters; i++) {
5827 AVChapter *c = s->chapters[i];
5828 AVDictionaryEntry *t;
5830 int64_t end = av_rescale_q(c->end, c->time_base, (AVRational){1,MOV_TIMESCALE});
5831 pkt.pts = pkt.dts = av_rescale_q(c->start, c->time_base, (AVRational){1,MOV_TIMESCALE});
5832 pkt.duration = end - pkt.dts;
5834 if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
5835 static const char encd[12] = {
5836 0x00, 0x00, 0x00, 0x0C,
5838 0x00, 0x00, 0x01, 0x00 };
5839 len = strlen(t->value);
5840 pkt.size = len + 2 + 12;
5841 pkt.data = av_malloc(pkt.size);
5843 return AVERROR(ENOMEM);
5844 AV_WB16(pkt.data, len);
5845 memcpy(pkt.data + 2, t->value, len);
5846 memcpy(pkt.data + len + 2, encd, sizeof(encd));
5847 ff_mov_write_packet(s, &pkt);
5848 av_freep(&pkt.data);
5856 static int mov_check_timecode_track(AVFormatContext *s, AVTimecode *tc, int src_index, const char *tcstr)
5860 /* compute the frame number */
5861 ret = av_timecode_init_from_string(tc, find_fps(s, s->streams[src_index]), tcstr, s);
5865 static int mov_create_timecode_track(AVFormatContext *s, int index, int src_index, AVTimecode tc)
5868 MOVMuxContext *mov = s->priv_data;
5869 MOVTrack *track = &mov->tracks[index];
5870 AVStream *src_st = s->streams[src_index];
5871 AVPacket pkt = {.stream_index = index, .flags = AV_PKT_FLAG_KEY, .size = 4};
5872 AVRational rate = find_fps(s, src_st);
5874 /* tmcd track based on video stream */
5875 track->mode = mov->mode;
5876 track->tag = MKTAG('t','m','c','d');
5877 track->src_track = src_index;
5878 track->timescale = mov->tracks[src_index].timescale;
5879 if (tc.flags & AV_TIMECODE_FLAG_DROPFRAME)
5880 track->timecode_flags |= MOV_TIMECODE_FLAG_DROPFRAME;
5882 /* set st to src_st for metadata access*/
5885 /* encode context: tmcd data stream */
5886 track->par = avcodec_parameters_alloc();
5888 return AVERROR(ENOMEM);
5889 track->par->codec_type = AVMEDIA_TYPE_DATA;
5890 track->par->codec_tag = track->tag;
5891 track->st->avg_frame_rate = av_inv_q(rate);
5893 /* the tmcd track just contains one packet with the frame number */
5894 pkt.data = av_malloc(pkt.size);
5896 return AVERROR(ENOMEM);
5897 AV_WB32(pkt.data, tc.start);
5898 ret = ff_mov_write_packet(s, &pkt);
5904 * st->disposition controls the "enabled" flag in the tkhd tag.
5905 * QuickTime will not play a track if it is not enabled. So make sure
5906 * that one track of each type (audio, video, subtitle) is enabled.
5908 * Subtitles are special. For audio and video, setting "enabled" also
5909 * makes the track "default" (i.e. it is rendered when played). For
5910 * subtitles, an "enabled" subtitle is not rendered by default, but
5911 * if no subtitle is enabled, the subtitle menu in QuickTime will be
5914 static void enable_tracks(AVFormatContext *s)
5916 MOVMuxContext *mov = s->priv_data;
5918 int enabled[AVMEDIA_TYPE_NB];
5919 int first[AVMEDIA_TYPE_NB];
5921 for (i = 0; i < AVMEDIA_TYPE_NB; i++) {
5926 for (i = 0; i < s->nb_streams; i++) {
5927 AVStream *st = s->streams[i];
5929 if (st->codecpar->codec_type <= AVMEDIA_TYPE_UNKNOWN ||
5930 st->codecpar->codec_type >= AVMEDIA_TYPE_NB ||
5934 if (first[st->codecpar->codec_type] < 0)
5935 first[st->codecpar->codec_type] = i;
5936 if (st->disposition & AV_DISPOSITION_DEFAULT) {
5937 mov->tracks[i].flags |= MOV_TRACK_ENABLED;
5938 enabled[st->codecpar->codec_type]++;
5942 for (i = 0; i < AVMEDIA_TYPE_NB; i++) {
5944 case AVMEDIA_TYPE_VIDEO:
5945 case AVMEDIA_TYPE_AUDIO:
5946 case AVMEDIA_TYPE_SUBTITLE:
5948 mov->per_stream_grouping = 1;
5949 if (!enabled[i] && first[i] >= 0)
5950 mov->tracks[first[i]].flags |= MOV_TRACK_ENABLED;
5956 static void mov_free(AVFormatContext *s)
5958 MOVMuxContext *mov = s->priv_data;
5961 if (mov->chapter_track) {
5962 if (mov->tracks[mov->chapter_track].par)
5963 av_freep(&mov->tracks[mov->chapter_track].par->extradata);
5964 av_freep(&mov->tracks[mov->chapter_track].par);
5967 for (i = 0; i < mov->nb_streams; i++) {
5968 if (mov->tracks[i].tag == MKTAG('r','t','p',' '))
5969 ff_mov_close_hinting(&mov->tracks[i]);
5970 else if (mov->tracks[i].tag == MKTAG('t','m','c','d') && mov->nb_meta_tmcd)
5971 av_freep(&mov->tracks[i].par);
5972 av_freep(&mov->tracks[i].cluster);
5973 av_freep(&mov->tracks[i].frag_info);
5974 av_packet_unref(&mov->tracks[i].cover_image);
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, 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,