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/dovi_meta.h"
55 #include "libavutil/color_utils.h"
61 static const AVOption options[] = {
62 { "movflags", "MOV muxer flags", offsetof(MOVMuxContext, flags), AV_OPT_TYPE_FLAGS, {.i64 = 0}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
63 { "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" },
64 { "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 },
65 { "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" },
66 { "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" },
67 { "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" },
68 { "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" },
69 { "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" },
70 { "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" },
71 { "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" },
72 { "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" },
73 { "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" },
74 { "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" },
75 { "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" },
76 { "cmaf", "Write CMAF compatible fragmented MP4", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_CMAF}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
77 { "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" },
78 { "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" },
79 { "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" },
80 { "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" },
81 { "write_colr", "Write colr atom even if the color info is unspecified (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" },
82 { "prefer_icc", "If writing colr atom prioritise usage of ICC profile if it exists in stream packet side data", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_PREFER_ICC}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
83 { "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" },
84 { "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" },
85 { "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" },
86 { "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" },
87 FF_RTP_FLAG_OPTS(MOVMuxContext, rtp_flags),
88 { "skip_iods", "Skip writing iods atom.", offsetof(MOVMuxContext, iods_skip), AV_OPT_TYPE_BOOL, {.i64 = 1}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM},
89 { "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},
90 { "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},
91 { "frag_duration", "Maximum fragment duration", offsetof(MOVMuxContext, max_fragment_duration), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
92 { "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},
93 { "frag_size", "Maximum fragment size", offsetof(MOVMuxContext, max_fragment_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
94 { "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},
95 { "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},
96 { "brand", "Override major brand", offsetof(MOVMuxContext, major_brand), AV_OPT_TYPE_STRING, {.str = NULL}, .flags = AV_OPT_FLAG_ENCODING_PARAM },
97 { "use_editlist", "use edit list", offsetof(MOVMuxContext, use_editlist), AV_OPT_TYPE_BOOL, {.i64 = -1}, -1, 1, AV_OPT_FLAG_ENCODING_PARAM},
98 { "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},
99 { "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},
100 { "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 },
101 { "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 },
102 { "encryption_key", "The media encryption key (hex)", offsetof(MOVMuxContext, encryption_key), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_ENCODING_PARAM },
103 { "encryption_kid", "The media encryption key identifier (hex)", offsetof(MOVMuxContext, encryption_kid), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_ENCODING_PARAM },
104 { "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},
105 { "write_tmcd", "force or disable writing tmcd", offsetof(MOVMuxContext, write_tmcd), AV_OPT_TYPE_BOOL, {.i64 = -1}, -1, 1, AV_OPT_FLAG_ENCODING_PARAM},
106 { "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"},
107 { "wallclock", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = MOV_PRFT_SRC_WALLCLOCK}, 0, 0, AV_OPT_FLAG_ENCODING_PARAM, "prft"},
108 { "pts", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = MOV_PRFT_SRC_PTS}, 0, 0, AV_OPT_FLAG_ENCODING_PARAM, "prft"},
109 { "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},
113 #define MOV_CLASS(flavor)\
114 static const AVClass flavor ## _muxer_class = {\
115 .class_name = #flavor " muxer",\
116 .item_name = av_default_item_name,\
118 .version = LIBAVUTIL_VERSION_INT,\
121 static int get_moov_size(AVFormatContext *s);
123 static int utf8len(const uint8_t *b)
128 GET_UTF8(val, *b++, return -1;)
134 //FIXME support 64 bit variant with wide placeholders
135 static int64_t update_size(AVIOContext *pb, int64_t pos)
137 int64_t curpos = avio_tell(pb);
138 avio_seek(pb, pos, SEEK_SET);
139 avio_wb32(pb, curpos - pos); /* rewrite size */
140 avio_seek(pb, curpos, SEEK_SET);
145 static int co64_required(const MOVTrack *track)
147 if (track->entry > 0 && track->cluster[track->entry - 1].pos + track->data_offset > UINT32_MAX)
152 static int is_cover_image(const AVStream *st)
154 /* Eg. AV_DISPOSITION_ATTACHED_PIC | AV_DISPOSITION_TIMED_THUMBNAILS
155 * is encoded as sparse video track */
156 return st && st->disposition == AV_DISPOSITION_ATTACHED_PIC;
159 static int rtp_hinting_needed(const AVStream *st)
161 /* Add hint tracks for each real audio and video stream */
162 if (is_cover_image(st))
164 return st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ||
165 st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO;
168 /* Chunk offset atom */
169 static int mov_write_stco_tag(AVIOContext *pb, MOVTrack *track)
172 int mode64 = co64_required(track); // use 32 bit size variant if possible
173 int64_t pos = avio_tell(pb);
174 avio_wb32(pb, 0); /* size */
176 ffio_wfourcc(pb, "co64");
178 ffio_wfourcc(pb, "stco");
179 avio_wb32(pb, 0); /* version & flags */
180 avio_wb32(pb, track->chunkCount); /* entry count */
181 for (i = 0; i < track->entry; i++) {
182 if (!track->cluster[i].chunkNum)
185 avio_wb64(pb, track->cluster[i].pos + track->data_offset);
187 avio_wb32(pb, track->cluster[i].pos + track->data_offset);
189 return update_size(pb, pos);
192 /* Sample size atom */
193 static int mov_write_stsz_tag(AVIOContext *pb, MOVTrack *track)
196 int i, j, entries = 0, tst = -1, oldtst = -1;
198 int64_t pos = avio_tell(pb);
199 avio_wb32(pb, 0); /* size */
200 ffio_wfourcc(pb, "stsz");
201 avio_wb32(pb, 0); /* version & flags */
203 for (i = 0; i < track->entry; i++) {
204 tst = track->cluster[i].size / track->cluster[i].entries;
205 if (oldtst != -1 && tst != oldtst)
208 entries += track->cluster[i].entries;
210 if (equalChunks && track->entry) {
211 int sSize = track->entry ? track->cluster[0].size / track->cluster[0].entries : 0;
212 sSize = FFMAX(1, sSize); // adpcm mono case could make sSize == 0
213 avio_wb32(pb, sSize); // sample size
214 avio_wb32(pb, entries); // sample count
216 avio_wb32(pb, 0); // sample size
217 avio_wb32(pb, entries); // sample count
218 for (i = 0; i < track->entry; i++) {
219 for (j = 0; j < track->cluster[i].entries; j++) {
220 avio_wb32(pb, track->cluster[i].size /
221 track->cluster[i].entries);
225 return update_size(pb, pos);
228 /* Sample to chunk atom */
229 static int mov_write_stsc_tag(AVIOContext *pb, MOVTrack *track)
231 int index = 0, oldval = -1, i;
232 int64_t entryPos, curpos;
234 int64_t pos = avio_tell(pb);
235 avio_wb32(pb, 0); /* size */
236 ffio_wfourcc(pb, "stsc");
237 avio_wb32(pb, 0); // version & flags
238 entryPos = avio_tell(pb);
239 avio_wb32(pb, track->chunkCount); // entry count
240 for (i = 0; i < track->entry; i++) {
241 if (oldval != track->cluster[i].samples_in_chunk && track->cluster[i].chunkNum) {
242 avio_wb32(pb, track->cluster[i].chunkNum); // first chunk
243 avio_wb32(pb, track->cluster[i].samples_in_chunk); // samples per chunk
244 avio_wb32(pb, 0x1); // sample description index
245 oldval = track->cluster[i].samples_in_chunk;
249 curpos = avio_tell(pb);
250 avio_seek(pb, entryPos, SEEK_SET);
251 avio_wb32(pb, index); // rewrite size
252 avio_seek(pb, curpos, SEEK_SET);
254 return update_size(pb, pos);
257 /* Sync sample atom */
258 static int mov_write_stss_tag(AVIOContext *pb, MOVTrack *track, uint32_t flag)
260 int64_t curpos, entryPos;
262 int64_t pos = avio_tell(pb);
263 avio_wb32(pb, 0); // size
264 ffio_wfourcc(pb, flag == MOV_SYNC_SAMPLE ? "stss" : "stps");
265 avio_wb32(pb, 0); // version & flags
266 entryPos = avio_tell(pb);
267 avio_wb32(pb, track->entry); // entry count
268 for (i = 0; i < track->entry; i++) {
269 if (track->cluster[i].flags & flag) {
270 avio_wb32(pb, i + 1);
274 curpos = avio_tell(pb);
275 avio_seek(pb, entryPos, SEEK_SET);
276 avio_wb32(pb, index); // rewrite size
277 avio_seek(pb, curpos, SEEK_SET);
278 return update_size(pb, pos);
281 /* Sample dependency atom */
282 static int mov_write_sdtp_tag(AVIOContext *pb, MOVTrack *track)
285 uint8_t leading, dependent, reference, redundancy;
286 int64_t pos = avio_tell(pb);
287 avio_wb32(pb, 0); // size
288 ffio_wfourcc(pb, "sdtp");
289 avio_wb32(pb, 0); // version & flags
290 for (i = 0; i < track->entry; i++) {
291 dependent = MOV_SAMPLE_DEPENDENCY_YES;
292 leading = reference = redundancy = MOV_SAMPLE_DEPENDENCY_UNKNOWN;
293 if (track->cluster[i].flags & MOV_DISPOSABLE_SAMPLE) {
294 reference = MOV_SAMPLE_DEPENDENCY_NO;
296 if (track->cluster[i].flags & MOV_SYNC_SAMPLE) {
297 dependent = MOV_SAMPLE_DEPENDENCY_NO;
299 avio_w8(pb, (leading << 6) | (dependent << 4) |
300 (reference << 2) | redundancy);
302 return update_size(pb, pos);
305 static int mov_write_amr_tag(AVIOContext *pb, MOVTrack *track)
307 avio_wb32(pb, 0x11); /* size */
308 if (track->mode == MODE_MOV) ffio_wfourcc(pb, "samr");
309 else ffio_wfourcc(pb, "damr");
310 ffio_wfourcc(pb, "FFMP");
311 avio_w8(pb, 0); /* decoder version */
313 avio_wb16(pb, 0x81FF); /* Mode set (all modes for AMR_NB) */
314 avio_w8(pb, 0x00); /* Mode change period (no restriction) */
315 avio_w8(pb, 0x01); /* Frames per sample */
319 static int mov_write_ac3_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
324 int fscod, bsid, bsmod, acmod, lfeon, frmsizecod;
326 if (track->vos_len < 7) {
327 av_log(s, AV_LOG_ERROR,
328 "Cannot write moov atom before AC3 packets."
329 " Set the delay_moov flag to fix this.\n");
330 return AVERROR(EINVAL);
334 ffio_wfourcc(pb, "dac3");
336 init_get_bits(&gbc, track->vos_data + 4, (track->vos_len - 4) * 8);
337 fscod = get_bits(&gbc, 2);
338 frmsizecod = get_bits(&gbc, 6);
339 bsid = get_bits(&gbc, 5);
340 bsmod = get_bits(&gbc, 3);
341 acmod = get_bits(&gbc, 3);
343 skip_bits(&gbc, 2); // dsurmod
345 if ((acmod & 1) && acmod != 1)
346 skip_bits(&gbc, 2); // cmixlev
348 skip_bits(&gbc, 2); // surmixlev
350 lfeon = get_bits1(&gbc);
352 init_put_bits(&pbc, buf, sizeof(buf));
353 put_bits(&pbc, 2, fscod);
354 put_bits(&pbc, 5, bsid);
355 put_bits(&pbc, 3, bsmod);
356 put_bits(&pbc, 3, acmod);
357 put_bits(&pbc, 1, lfeon);
358 put_bits(&pbc, 5, frmsizecod >> 1); // bit_rate_code
359 put_bits(&pbc, 5, 0); // reserved
361 flush_put_bits(&pbc);
362 avio_write(pb, buf, sizeof(buf));
372 /* Layout of the EC3SpecificBox */
373 /* maximum bitrate */
375 /* number of independent substreams */
378 /* sample rate code (see ff_ac3_sample_rate_tab) 2 bits */
380 /* bit stream identification 5 bits */
382 /* one bit reserved */
383 /* audio service mixing (not supported yet) 1 bit */
384 /* bit stream mode 3 bits */
386 /* audio coding mode 3 bits */
388 /* sub woofer on 1 bit */
390 /* 3 bits reserved */
391 /* number of dependent substreams associated with this substream 4 bits */
393 /* channel locations of the dependent substream(s), if any, 9 bits */
395 /* if there is no dependent substream, then one bit reserved instead */
396 } substream[1]; /* TODO: support 8 independent substreams */
399 #if CONFIG_AC3_PARSER
400 static int handle_eac3(MOVMuxContext *mov, AVPacket *pkt, MOVTrack *track)
402 AC3HeaderInfo *hdr = NULL;
403 struct eac3_info *info;
406 if (!track->eac3_priv && !(track->eac3_priv = av_mallocz(sizeof(*info))))
407 return AVERROR(ENOMEM);
408 info = track->eac3_priv;
410 if (avpriv_ac3_parse_header(&hdr, pkt->data, pkt->size) < 0) {
411 /* drop the packets until we see a good one */
413 av_log(mov->fc, AV_LOG_WARNING, "Dropping invalid packet from start of the stream\n");
416 ret = AVERROR_INVALIDDATA;
420 info->data_rate = FFMAX(info->data_rate, hdr->bit_rate / 1000);
421 num_blocks = hdr->num_blocks;
423 if (!info->ec3_done) {
424 /* AC-3 substream must be the first one */
425 if (hdr->bitstream_id <= 10 && hdr->substreamid != 0) {
426 ret = AVERROR(EINVAL);
430 /* this should always be the case, given that our AC-3 parser
431 * concatenates dependent frames to their independent parent */
432 if (hdr->frame_type == EAC3_FRAME_TYPE_INDEPENDENT) {
433 /* substream ids must be incremental */
434 if (hdr->substreamid > info->num_ind_sub + 1) {
435 ret = AVERROR(EINVAL);
439 if (hdr->substreamid == info->num_ind_sub + 1) {
440 //info->num_ind_sub++;
441 avpriv_request_sample(mov->fc, "Multiple independent substreams");
442 ret = AVERROR_PATCHWELCOME;
444 } else if (hdr->substreamid < info->num_ind_sub ||
445 hdr->substreamid == 0 && info->substream[0].bsid) {
450 if (hdr->substreamid != 0) {
451 avpriv_request_sample(mov->fc, "Multiple non EAC3 independent substreams");
452 ret = AVERROR_PATCHWELCOME;
457 /* fill the info needed for the "dec3" atom */
458 info->substream[hdr->substreamid].fscod = hdr->sr_code;
459 info->substream[hdr->substreamid].bsid = hdr->bitstream_id;
460 info->substream[hdr->substreamid].bsmod = hdr->bitstream_mode;
461 info->substream[hdr->substreamid].acmod = hdr->channel_mode;
462 info->substream[hdr->substreamid].lfeon = hdr->lfe_on;
464 /* Parse dependent substream(s), if any */
465 if (pkt->size != hdr->frame_size) {
466 int cumul_size = hdr->frame_size;
467 int parent = hdr->substreamid;
469 while (cumul_size != pkt->size) {
472 ret = avpriv_ac3_parse_header(&hdr, pkt->data + cumul_size, pkt->size - cumul_size);
475 if (hdr->frame_type != EAC3_FRAME_TYPE_DEPENDENT) {
476 ret = AVERROR(EINVAL);
479 info->substream[parent].num_dep_sub++;
482 /* header is parsed up to lfeon, but custom channel map may be needed */
483 init_get_bits8(&gbc, pkt->data + cumul_size + ret, pkt->size - cumul_size - ret);
486 /* skip volume control params */
487 for (i = 0; i < (hdr->channel_mode ? 1 : 2); i++) {
488 skip_bits(&gbc, 5); // skip dialog normalization
489 if (get_bits1(&gbc)) {
490 skip_bits(&gbc, 8); // skip compression gain word
493 /* get the dependent stream channel map, if exists */
495 info->substream[parent].chan_loc |= (get_bits(&gbc, 16) >> 5) & 0x1f;
497 info->substream[parent].chan_loc |= hdr->channel_mode;
498 cumul_size += hdr->frame_size;
504 if (!info->num_blocks && num_blocks == 6) {
508 else if (info->num_blocks + num_blocks > 6) {
509 ret = AVERROR_INVALIDDATA;
513 if (!info->num_blocks) {
514 ret = av_packet_ref(&info->pkt, pkt);
516 info->num_blocks = num_blocks;
519 if ((ret = av_grow_packet(&info->pkt, pkt->size)) < 0)
521 memcpy(info->pkt.data + info->pkt.size - pkt->size, pkt->data, pkt->size);
522 info->num_blocks += num_blocks;
523 info->pkt.duration += pkt->duration;
524 if (info->num_blocks != 6)
526 av_packet_unref(pkt);
527 av_packet_move_ref(pkt, &info->pkt);
528 info->num_blocks = 0;
539 static int mov_write_eac3_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
543 struct eac3_info *info;
546 if (!track->eac3_priv) {
547 av_log(s, AV_LOG_ERROR,
548 "Cannot write moov atom before EAC3 packets parsed.\n");
549 return AVERROR(EINVAL);
552 info = track->eac3_priv;
553 size = 2 + ((34 * (info->num_ind_sub + 1) + 7) >> 3);
554 buf = av_malloc(size);
556 return 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);
591 * This function writes extradata "as is".
592 * Extradata must be formatted like a valid atom (with size and tag).
594 static int mov_write_extradata_tag(AVIOContext *pb, MOVTrack *track)
596 avio_write(pb, track->par->extradata, track->par->extradata_size);
597 return track->par->extradata_size;
600 static int mov_write_enda_tag(AVIOContext *pb)
603 ffio_wfourcc(pb, "enda");
604 avio_wb16(pb, 1); /* little endian */
608 static int mov_write_enda_tag_be(AVIOContext *pb)
611 ffio_wfourcc(pb, "enda");
612 avio_wb16(pb, 0); /* big endian */
616 static void put_descr(AVIOContext *pb, int tag, unsigned int size)
621 avio_w8(pb, (size >> (7 * i)) | 0x80);
622 avio_w8(pb, size & 0x7F);
625 static unsigned compute_avg_bitrate(MOVTrack *track)
629 if (!track->track_duration)
631 for (i = 0; i < track->entry; i++)
632 size += track->cluster[i].size;
633 return size * 8 * track->timescale / track->track_duration;
636 struct mpeg4_bit_rate_values {
637 uint32_t buffer_size; ///< Size of the decoding buffer for the elementary stream in bytes.
638 uint32_t max_bit_rate; ///< Maximum rate in bits/second over any window of one second.
639 uint32_t avg_bit_rate; ///< Average rate in bits/second over the entire presentation.
642 static struct mpeg4_bit_rate_values calculate_mpeg4_bit_rates(MOVTrack *track)
644 AVCPBProperties *props =
645 (AVCPBProperties*)av_stream_get_side_data(track->st,
646 AV_PKT_DATA_CPB_PROPERTIES,
648 struct mpeg4_bit_rate_values bit_rates = { 0 };
650 bit_rates.avg_bit_rate = compute_avg_bitrate(track);
652 // (FIXME should be max rate in any 1 sec window)
653 bit_rates.max_bit_rate = FFMAX(track->par->bit_rate,
654 bit_rates.avg_bit_rate);
656 // utilize values from properties if we have them available
658 bit_rates.max_bit_rate = FFMAX(bit_rates.max_bit_rate,
660 bit_rates.buffer_size = props->buffer_size / 8;
666 static int mov_write_esds_tag(AVIOContext *pb, MOVTrack *track) // Basic
668 struct mpeg4_bit_rate_values bit_rates = calculate_mpeg4_bit_rates(track);
669 int64_t pos = avio_tell(pb);
670 int decoder_specific_info_len = track->vos_len ? 5 + track->vos_len : 0;
672 avio_wb32(pb, 0); // size
673 ffio_wfourcc(pb, "esds");
674 avio_wb32(pb, 0); // Version
677 put_descr(pb, 0x03, 3 + 5+13 + decoder_specific_info_len + 5+1);
678 avio_wb16(pb, track->track_id);
679 avio_w8(pb, 0x00); // flags (= no flags)
681 // DecoderConfig descriptor
682 put_descr(pb, 0x04, 13 + decoder_specific_info_len);
684 // Object type indication
685 if ((track->par->codec_id == AV_CODEC_ID_MP2 ||
686 track->par->codec_id == AV_CODEC_ID_MP3) &&
687 track->par->sample_rate > 24000)
688 avio_w8(pb, 0x6B); // 11172-3
690 avio_w8(pb, ff_codec_get_tag(ff_mp4_obj_type, track->par->codec_id));
692 // the following fields is made of 6 bits to identify the streamtype (4 for video, 5 for audio)
693 // plus 1 bit to indicate upstream and 1 bit set to 1 (reserved)
694 if (track->par->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
695 avio_w8(pb, (0x38 << 2) | 1); // flags (= NeroSubpicStream)
696 else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
697 avio_w8(pb, 0x15); // flags (= Audiostream)
699 avio_w8(pb, 0x11); // flags (= Visualstream)
701 avio_wb24(pb, bit_rates.buffer_size); // Buffersize DB
702 avio_wb32(pb, bit_rates.max_bit_rate); // maxbitrate
703 avio_wb32(pb, bit_rates.avg_bit_rate);
705 if (track->vos_len) {
706 // DecoderSpecific info descriptor
707 put_descr(pb, 0x05, track->vos_len);
708 avio_write(pb, track->vos_data, track->vos_len);
712 put_descr(pb, 0x06, 1);
714 return update_size(pb, pos);
717 static int mov_pcm_le_gt16(enum AVCodecID codec_id)
719 return codec_id == AV_CODEC_ID_PCM_S24LE ||
720 codec_id == AV_CODEC_ID_PCM_S32LE ||
721 codec_id == AV_CODEC_ID_PCM_F32LE ||
722 codec_id == AV_CODEC_ID_PCM_F64LE;
725 static int mov_pcm_be_gt16(enum AVCodecID codec_id)
727 return codec_id == AV_CODEC_ID_PCM_S24BE ||
728 codec_id == AV_CODEC_ID_PCM_S32BE ||
729 codec_id == AV_CODEC_ID_PCM_F32BE ||
730 codec_id == AV_CODEC_ID_PCM_F64BE;
733 static int mov_write_ms_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
736 int64_t pos = avio_tell(pb);
738 avio_wl32(pb, track->tag); // store it byteswapped
739 track->par->codec_tag = av_bswap16(track->tag >> 16);
740 if ((ret = ff_put_wav_header(s, pb, track->par, 0)) < 0)
742 return update_size(pb, pos);
745 static int mov_write_wfex_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
748 int64_t pos = avio_tell(pb);
750 ffio_wfourcc(pb, "wfex");
751 if ((ret = ff_put_wav_header(s, pb, track->st->codecpar, FF_PUT_WAV_HEADER_FORCE_WAVEFORMATEX)) < 0)
753 return update_size(pb, pos);
756 static int mov_write_dfla_tag(AVIOContext *pb, MOVTrack *track)
758 int64_t pos = avio_tell(pb);
760 ffio_wfourcc(pb, "dfLa");
761 avio_w8(pb, 0); /* version */
762 avio_wb24(pb, 0); /* flags */
764 /* Expect the encoder to pass a METADATA_BLOCK_TYPE_STREAMINFO. */
765 if (track->par->extradata_size != FLAC_STREAMINFO_SIZE)
766 return AVERROR_INVALIDDATA;
768 /* TODO: Write other METADATA_BLOCK_TYPEs if the encoder makes them available. */
769 avio_w8(pb, 1 << 7 | FLAC_METADATA_TYPE_STREAMINFO); /* LastMetadataBlockFlag << 7 | BlockType */
770 avio_wb24(pb, track->par->extradata_size); /* Length */
771 avio_write(pb, track->par->extradata, track->par->extradata_size); /* BlockData[Length] */
773 return update_size(pb, pos);
776 static int mov_write_dops_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
778 int64_t pos = avio_tell(pb);
780 ffio_wfourcc(pb, "dOps");
781 avio_w8(pb, 0); /* Version */
782 if (track->par->extradata_size < 19) {
783 av_log(s, AV_LOG_ERROR, "invalid extradata size\n");
784 return AVERROR_INVALIDDATA;
786 /* extradata contains an Ogg OpusHead, other than byte-ordering and
787 OpusHead's preceeding magic/version, OpusSpecificBox is currently
789 avio_w8(pb, AV_RB8(track->par->extradata + 9)); /* OuputChannelCount */
790 avio_wb16(pb, AV_RL16(track->par->extradata + 10)); /* PreSkip */
791 avio_wb32(pb, AV_RL32(track->par->extradata + 12)); /* InputSampleRate */
792 avio_wb16(pb, AV_RL16(track->par->extradata + 16)); /* OutputGain */
793 /* Write the rest of the header out without byte-swapping. */
794 avio_write(pb, track->par->extradata + 18, track->par->extradata_size - 18);
796 return update_size(pb, pos);
799 static int mov_write_dmlp_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
801 int64_t pos = avio_tell(pb);
804 ffio_wfourcc(pb, "dmlp");
806 if (track->vos_len < 20) {
807 av_log(s, AV_LOG_ERROR,
808 "Cannot write moov atom before TrueHD packets."
809 " Set the delay_moov flag to fix this.\n");
810 return AVERROR(EINVAL);
813 length = (AV_RB16(track->vos_data) & 0xFFF) * 2;
814 if (length < 20 || length > track->vos_len)
815 return AVERROR_INVALIDDATA;
817 // Only TrueHD is supported
818 if (AV_RB32(track->vos_data + 4) != 0xF8726FBA)
819 return AVERROR_INVALIDDATA;
821 avio_wb32(pb, AV_RB32(track->vos_data + 8)); /* format_info */
822 avio_wb16(pb, AV_RB16(track->vos_data + 18) << 1); /* peak_data_rate */
823 avio_wb32(pb, 0); /* reserved */
825 return update_size(pb, pos);
828 static int mov_write_chan_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
830 uint32_t layout_tag, bitmap;
831 int64_t pos = avio_tell(pb);
833 layout_tag = ff_mov_get_channel_layout_tag(track->par->codec_id,
834 track->par->channel_layout,
837 av_log(s, AV_LOG_WARNING, "not writing 'chan' tag due to "
838 "lack of channel information\n");
842 if (track->multichannel_as_mono)
845 avio_wb32(pb, 0); // Size
846 ffio_wfourcc(pb, "chan"); // Type
847 avio_w8(pb, 0); // Version
848 avio_wb24(pb, 0); // Flags
849 avio_wb32(pb, layout_tag); // mChannelLayoutTag
850 avio_wb32(pb, bitmap); // mChannelBitmap
851 avio_wb32(pb, 0); // mNumberChannelDescriptions
853 return update_size(pb, pos);
856 static int mov_write_wave_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
858 int64_t pos = avio_tell(pb);
860 avio_wb32(pb, 0); /* size */
861 ffio_wfourcc(pb, "wave");
863 if (track->par->codec_id != AV_CODEC_ID_QDM2) {
864 avio_wb32(pb, 12); /* size */
865 ffio_wfourcc(pb, "frma");
866 avio_wl32(pb, track->tag);
869 if (track->par->codec_id == AV_CODEC_ID_AAC) {
870 /* useless atom needed by mplayer, ipod, not needed by quicktime */
871 avio_wb32(pb, 12); /* size */
872 ffio_wfourcc(pb, "mp4a");
874 mov_write_esds_tag(pb, track);
875 } else if (mov_pcm_le_gt16(track->par->codec_id)) {
876 mov_write_enda_tag(pb);
877 } else if (mov_pcm_be_gt16(track->par->codec_id)) {
878 mov_write_enda_tag_be(pb);
879 } else if (track->par->codec_id == AV_CODEC_ID_AMR_NB) {
880 mov_write_amr_tag(pb, track);
881 } else if (track->par->codec_id == AV_CODEC_ID_AC3) {
882 mov_write_ac3_tag(s, pb, track);
883 } else if (track->par->codec_id == AV_CODEC_ID_EAC3) {
884 mov_write_eac3_tag(s, pb, track);
885 } else if (track->par->codec_id == AV_CODEC_ID_ALAC ||
886 track->par->codec_id == AV_CODEC_ID_QDM2) {
887 mov_write_extradata_tag(pb, track);
888 } else if (track->par->codec_id == AV_CODEC_ID_ADPCM_MS ||
889 track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) {
890 mov_write_ms_tag(s, pb, track);
893 avio_wb32(pb, 8); /* size */
894 avio_wb32(pb, 0); /* null tag */
896 return update_size(pb, pos);
899 static int mov_write_dvc1_structs(MOVTrack *track, uint8_t *buf)
902 const uint8_t *start, *next, *end = track->vos_data + track->vos_len;
903 int unescaped_size, seq_found = 0;
904 int level = 0, interlace = 0;
905 int packet_seq = track->vc1_info.packet_seq;
906 int packet_entry = track->vc1_info.packet_entry;
907 int slices = track->vc1_info.slices;
910 if (track->start_dts == AV_NOPTS_VALUE) {
911 /* No packets written yet, vc1_info isn't authoritative yet. */
912 /* Assume inline sequence and entry headers. */
913 packet_seq = packet_entry = 1;
914 av_log(NULL, AV_LOG_WARNING,
915 "moov atom written before any packets, unable to write correct "
916 "dvc1 atom. Set the delay_moov flag to fix this.\n");
919 unescaped = av_mallocz(track->vos_len + AV_INPUT_BUFFER_PADDING_SIZE);
921 return AVERROR(ENOMEM);
922 start = find_next_marker(track->vos_data, end);
923 for (next = start; next < end; start = next) {
926 next = find_next_marker(start + 4, end);
927 size = next - start - 4;
930 unescaped_size = vc1_unescape_buffer(start + 4, size, unescaped);
931 init_get_bits(&gb, unescaped, 8 * unescaped_size);
932 if (AV_RB32(start) == VC1_CODE_SEQHDR) {
933 int profile = get_bits(&gb, 2);
934 if (profile != PROFILE_ADVANCED) {
936 return AVERROR(ENOSYS);
939 level = get_bits(&gb, 3);
940 /* chromaformat, frmrtq_postproc, bitrtq_postproc, postprocflag,
942 skip_bits_long(&gb, 2 + 3 + 5 + 1 + 2*12);
943 skip_bits(&gb, 1); /* broadcast */
944 interlace = get_bits1(&gb);
945 skip_bits(&gb, 4); /* tfcntrflag, finterpflag, reserved, psf */
950 return AVERROR(ENOSYS);
953 init_put_bits(&pbc, buf, 7);
954 /* VC1DecSpecStruc */
955 put_bits(&pbc, 4, 12); /* profile - advanced */
956 put_bits(&pbc, 3, level);
957 put_bits(&pbc, 1, 0); /* reserved */
958 /* VC1AdvDecSpecStruc */
959 put_bits(&pbc, 3, level);
960 put_bits(&pbc, 1, 0); /* cbr */
961 put_bits(&pbc, 6, 0); /* reserved */
962 put_bits(&pbc, 1, !interlace); /* no interlace */
963 put_bits(&pbc, 1, !packet_seq); /* no multiple seq */
964 put_bits(&pbc, 1, !packet_entry); /* no multiple entry */
965 put_bits(&pbc, 1, !slices); /* no slice code */
966 put_bits(&pbc, 1, 0); /* no bframe */
967 put_bits(&pbc, 1, 0); /* reserved */
970 if (track->st->avg_frame_rate.num > 0 && track->st->avg_frame_rate.den > 0)
971 put_bits32(&pbc, track->st->avg_frame_rate.num / track->st->avg_frame_rate.den);
973 put_bits32(&pbc, 0xffffffff);
975 flush_put_bits(&pbc);
982 static int mov_write_dvc1_tag(AVIOContext *pb, MOVTrack *track)
984 uint8_t buf[7] = { 0 };
987 if ((ret = mov_write_dvc1_structs(track, buf)) < 0)
990 avio_wb32(pb, track->vos_len + 8 + sizeof(buf));
991 ffio_wfourcc(pb, "dvc1");
992 avio_write(pb, buf, sizeof(buf));
993 avio_write(pb, track->vos_data, track->vos_len);
998 static int mov_write_glbl_tag(AVIOContext *pb, MOVTrack *track)
1000 avio_wb32(pb, track->vos_len + 8);
1001 ffio_wfourcc(pb, "glbl");
1002 avio_write(pb, track->vos_data, track->vos_len);
1003 return 8 + track->vos_len;
1007 * Compute flags for 'lpcm' tag.
1008 * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
1010 static int mov_get_lpcm_flags(enum AVCodecID codec_id)
1013 case AV_CODEC_ID_PCM_F32BE:
1014 case AV_CODEC_ID_PCM_F64BE:
1016 case AV_CODEC_ID_PCM_F32LE:
1017 case AV_CODEC_ID_PCM_F64LE:
1019 case AV_CODEC_ID_PCM_U8:
1021 case AV_CODEC_ID_PCM_S16BE:
1022 case AV_CODEC_ID_PCM_S24BE:
1023 case AV_CODEC_ID_PCM_S32BE:
1025 case AV_CODEC_ID_PCM_S8:
1026 case AV_CODEC_ID_PCM_S16LE:
1027 case AV_CODEC_ID_PCM_S24LE:
1028 case AV_CODEC_ID_PCM_S32LE:
1035 static int get_cluster_duration(MOVTrack *track, int cluster_idx)
1039 if (cluster_idx >= track->entry)
1042 if (cluster_idx + 1 == track->entry)
1043 next_dts = track->track_duration + track->start_dts;
1045 next_dts = track->cluster[cluster_idx + 1].dts;
1047 next_dts -= track->cluster[cluster_idx].dts;
1049 av_assert0(next_dts >= 0);
1050 av_assert0(next_dts <= INT_MAX);
1055 static int get_samples_per_packet(MOVTrack *track)
1057 int i, first_duration;
1059 // return track->par->frame_size;
1061 /* use 1 for raw PCM */
1062 if (!track->audio_vbr)
1065 /* check to see if duration is constant for all clusters */
1068 first_duration = get_cluster_duration(track, 0);
1069 for (i = 1; i < track->entry; i++) {
1070 if (get_cluster_duration(track, i) != first_duration)
1073 return first_duration;
1076 static int mov_write_audio_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
1078 int64_t pos = avio_tell(pb);
1080 uint32_t tag = track->tag;
1083 if (track->mode == MODE_MOV) {
1084 if (track->timescale > UINT16_MAX || !track->par->channels) {
1085 if (mov_get_lpcm_flags(track->par->codec_id))
1086 tag = AV_RL32("lpcm");
1088 } else if (track->audio_vbr || mov_pcm_le_gt16(track->par->codec_id) ||
1089 mov_pcm_be_gt16(track->par->codec_id) ||
1090 track->par->codec_id == AV_CODEC_ID_ADPCM_MS ||
1091 track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
1092 track->par->codec_id == AV_CODEC_ID_QDM2) {
1097 avio_wb32(pb, 0); /* size */
1098 if (mov->encryption_scheme != MOV_ENC_NONE) {
1099 ffio_wfourcc(pb, "enca");
1101 avio_wl32(pb, tag); // store it byteswapped
1103 avio_wb32(pb, 0); /* Reserved */
1104 avio_wb16(pb, 0); /* Reserved */
1105 avio_wb16(pb, 1); /* Data-reference index, XXX == 1 */
1107 /* SoundDescription */
1108 avio_wb16(pb, version); /* Version */
1109 avio_wb16(pb, 0); /* Revision level */
1110 avio_wb32(pb, 0); /* Reserved */
1115 avio_wb16(pb, 0xfffe);
1117 avio_wb32(pb, 0x00010000);
1119 avio_wb64(pb, av_double2int(track->par->sample_rate));
1120 avio_wb32(pb, track->par->channels);
1121 avio_wb32(pb, 0x7F000000);
1122 avio_wb32(pb, av_get_bits_per_sample(track->par->codec_id));
1123 avio_wb32(pb, mov_get_lpcm_flags(track->par->codec_id));
1124 avio_wb32(pb, track->sample_size);
1125 avio_wb32(pb, get_samples_per_packet(track));
1127 if (track->mode == MODE_MOV) {
1128 avio_wb16(pb, track->par->channels);
1129 if (track->par->codec_id == AV_CODEC_ID_PCM_U8 ||
1130 track->par->codec_id == AV_CODEC_ID_PCM_S8)
1131 avio_wb16(pb, 8); /* bits per sample */
1132 else if (track->par->codec_id == AV_CODEC_ID_ADPCM_G726)
1133 avio_wb16(pb, track->par->bits_per_coded_sample);
1136 avio_wb16(pb, track->audio_vbr ? -2 : 0); /* compression ID */
1137 } else { /* reserved for mp4/3gp */
1138 if (track->par->codec_id == AV_CODEC_ID_FLAC ||
1139 track->par->codec_id == AV_CODEC_ID_ALAC ||
1140 track->par->codec_id == AV_CODEC_ID_OPUS) {
1141 avio_wb16(pb, track->par->channels);
1145 if (track->par->codec_id == AV_CODEC_ID_FLAC ||
1146 track->par->codec_id == AV_CODEC_ID_ALAC) {
1147 avio_wb16(pb, track->par->bits_per_raw_sample);
1154 avio_wb16(pb, 0); /* packet size (= 0) */
1155 if (track->par->codec_id == AV_CODEC_ID_OPUS)
1156 avio_wb16(pb, 48000);
1157 else if (track->par->codec_id == AV_CODEC_ID_TRUEHD)
1158 avio_wb32(pb, track->par->sample_rate);
1160 avio_wb16(pb, track->par->sample_rate <= UINT16_MAX ?
1161 track->par->sample_rate : 0);
1163 if (track->par->codec_id != AV_CODEC_ID_TRUEHD)
1164 avio_wb16(pb, 0); /* Reserved */
1167 if (version == 1) { /* SoundDescription V1 extended info */
1168 if (mov_pcm_le_gt16(track->par->codec_id) ||
1169 mov_pcm_be_gt16(track->par->codec_id))
1170 avio_wb32(pb, 1); /* must be 1 for uncompressed formats */
1172 avio_wb32(pb, track->par->frame_size); /* Samples per packet */
1173 avio_wb32(pb, track->sample_size / track->par->channels); /* Bytes per packet */
1174 avio_wb32(pb, track->sample_size); /* Bytes per frame */
1175 avio_wb32(pb, 2); /* Bytes per sample */
1178 if (track->mode == MODE_MOV &&
1179 (track->par->codec_id == AV_CODEC_ID_AAC ||
1180 track->par->codec_id == AV_CODEC_ID_AC3 ||
1181 track->par->codec_id == AV_CODEC_ID_EAC3 ||
1182 track->par->codec_id == AV_CODEC_ID_AMR_NB ||
1183 track->par->codec_id == AV_CODEC_ID_ALAC ||
1184 track->par->codec_id == AV_CODEC_ID_ADPCM_MS ||
1185 track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
1186 track->par->codec_id == AV_CODEC_ID_QDM2 ||
1187 (mov_pcm_le_gt16(track->par->codec_id) && version==1) ||
1188 (mov_pcm_be_gt16(track->par->codec_id) && version==1)))
1189 ret = mov_write_wave_tag(s, pb, track);
1190 else if (track->tag == MKTAG('m','p','4','a'))
1191 ret = mov_write_esds_tag(pb, track);
1192 else if (track->par->codec_id == AV_CODEC_ID_AMR_NB)
1193 ret = mov_write_amr_tag(pb, track);
1194 else if (track->par->codec_id == AV_CODEC_ID_AC3)
1195 ret = mov_write_ac3_tag(s, pb, track);
1196 else if (track->par->codec_id == AV_CODEC_ID_EAC3)
1197 ret = mov_write_eac3_tag(s, pb, track);
1198 else if (track->par->codec_id == AV_CODEC_ID_ALAC)
1199 ret = mov_write_extradata_tag(pb, track);
1200 else if (track->par->codec_id == AV_CODEC_ID_WMAPRO)
1201 ret = mov_write_wfex_tag(s, pb, track);
1202 else if (track->par->codec_id == AV_CODEC_ID_FLAC)
1203 ret = mov_write_dfla_tag(pb, track);
1204 else if (track->par->codec_id == AV_CODEC_ID_OPUS)
1205 ret = mov_write_dops_tag(s, pb, track);
1206 else if (track->par->codec_id == AV_CODEC_ID_TRUEHD)
1207 ret = mov_write_dmlp_tag(s, pb, track);
1208 else if (track->vos_len > 0)
1209 ret = mov_write_glbl_tag(pb, track);
1214 if (track->mode == MODE_MOV && track->par->codec_type == AVMEDIA_TYPE_AUDIO
1215 && ((ret = mov_write_chan_tag(s, pb, track)) < 0)) {
1219 if (mov->encryption_scheme != MOV_ENC_NONE
1220 && ((ret = ff_mov_cenc_write_sinf_tag(track, pb, mov->encryption_kid)) < 0)) {
1224 ret = update_size(pb, pos);
1228 static int mov_write_d263_tag(AVIOContext *pb)
1230 avio_wb32(pb, 0xf); /* size */
1231 ffio_wfourcc(pb, "d263");
1232 ffio_wfourcc(pb, "FFMP");
1233 avio_w8(pb, 0); /* decoder version */
1234 /* FIXME use AVCodecContext level/profile, when encoder will set values */
1235 avio_w8(pb, 0xa); /* level */
1236 avio_w8(pb, 0); /* profile */
1240 static int mov_write_av1c_tag(AVIOContext *pb, MOVTrack *track)
1242 int64_t pos = avio_tell(pb);
1245 ffio_wfourcc(pb, "av1C");
1246 ff_isom_write_av1c(pb, track->vos_data, track->vos_len);
1247 return update_size(pb, pos);
1250 static int mov_write_avcc_tag(AVIOContext *pb, MOVTrack *track)
1252 int64_t pos = avio_tell(pb);
1255 ffio_wfourcc(pb, "avcC");
1256 ff_isom_write_avcc(pb, track->vos_data, track->vos_len);
1257 return update_size(pb, pos);
1260 static int mov_write_vpcc_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
1262 int64_t pos = avio_tell(pb);
1265 ffio_wfourcc(pb, "vpcC");
1266 avio_w8(pb, 1); /* version */
1267 avio_wb24(pb, 0); /* flags */
1268 ff_isom_write_vpcc(s, pb, track->par);
1269 return update_size(pb, pos);
1272 static int mov_write_hvcc_tag(AVIOContext *pb, MOVTrack *track)
1274 int64_t pos = avio_tell(pb);
1277 ffio_wfourcc(pb, "hvcC");
1278 if (track->tag == MKTAG('h','v','c','1'))
1279 ff_isom_write_hvcc(pb, track->vos_data, track->vos_len, 1);
1281 ff_isom_write_hvcc(pb, track->vos_data, track->vos_len, 0);
1282 return update_size(pb, pos);
1285 /* also used by all avid codecs (dv, imx, meridien) and their variants */
1286 static int mov_write_avid_tag(AVIOContext *pb, MOVTrack *track)
1291 int display_width = track->par->width;
1293 if (track->vos_data && track->vos_len > 0x29) {
1294 if (ff_dnxhd_parse_header_prefix(track->vos_data) != 0) {
1295 /* looks like a DNxHD bit stream */
1296 interlaced = (track->vos_data[5] & 2);
1297 cid = AV_RB32(track->vos_data + 0x28);
1299 av_log(NULL, AV_LOG_WARNING, "Could not locate DNxHD bit stream in vos_data\n");
1303 av_log(NULL, AV_LOG_WARNING, "Could not locate DNxHD bit stream, vos_data too small\n");
1307 avio_wb32(pb, 24); /* size */
1308 ffio_wfourcc(pb, "ACLR");
1309 ffio_wfourcc(pb, "ACLR");
1310 ffio_wfourcc(pb, "0001");
1311 if (track->par->color_range == AVCOL_RANGE_MPEG || /* Legal range (16-235) */
1312 track->par->color_range == AVCOL_RANGE_UNSPECIFIED) {
1313 avio_wb32(pb, 1); /* Corresponds to 709 in official encoder */
1314 } else { /* Full range (0-255) */
1315 avio_wb32(pb, 2); /* Corresponds to RGB in official encoder */
1317 avio_wb32(pb, 0); /* unknown */
1319 if (track->tag == MKTAG('A','V','d','h')) {
1321 ffio_wfourcc(pb, "ADHR");
1322 ffio_wfourcc(pb, "0001");
1324 avio_wb32(pb, 0); /* unknown */
1325 avio_wb32(pb, 1); /* unknown */
1326 avio_wb32(pb, 0); /* unknown */
1327 avio_wb32(pb, 0); /* unknown */
1331 avio_wb32(pb, 24); /* size */
1332 ffio_wfourcc(pb, "APRG");
1333 ffio_wfourcc(pb, "APRG");
1334 ffio_wfourcc(pb, "0001");
1335 avio_wb32(pb, 1); /* unknown */
1336 avio_wb32(pb, 0); /* unknown */
1338 avio_wb32(pb, 120); /* size */
1339 ffio_wfourcc(pb, "ARES");
1340 ffio_wfourcc(pb, "ARES");
1341 ffio_wfourcc(pb, "0001");
1342 avio_wb32(pb, cid); /* dnxhd cid, some id ? */
1343 if ( track->par->sample_aspect_ratio.num > 0
1344 && track->par->sample_aspect_ratio.den > 0)
1345 display_width = display_width * track->par->sample_aspect_ratio.num / track->par->sample_aspect_ratio.den;
1346 avio_wb32(pb, display_width);
1347 /* values below are based on samples created with quicktime and avid codecs */
1349 avio_wb32(pb, track->par->height / 2);
1350 avio_wb32(pb, 2); /* unknown */
1351 avio_wb32(pb, 0); /* unknown */
1352 avio_wb32(pb, 4); /* unknown */
1354 avio_wb32(pb, track->par->height);
1355 avio_wb32(pb, 1); /* unknown */
1356 avio_wb32(pb, 0); /* unknown */
1357 if (track->par->height == 1080)
1358 avio_wb32(pb, 5); /* unknown */
1360 avio_wb32(pb, 6); /* unknown */
1363 for (i = 0; i < 10; i++)
1369 static int mov_write_dpxe_tag(AVIOContext *pb, MOVTrack *track)
1372 ffio_wfourcc(pb, "DpxE");
1373 if (track->par->extradata_size >= 12 &&
1374 !memcmp(&track->par->extradata[4], "DpxE", 4)) {
1375 avio_wb32(pb, track->par->extradata[11]);
1382 static int mov_get_dv_codec_tag(AVFormatContext *s, MOVTrack *track)
1386 if (track->par->width == 720) { /* SD */
1387 if (track->par->height == 480) { /* NTSC */
1388 if (track->par->format == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','n');
1389 else tag = MKTAG('d','v','c',' ');
1390 }else if (track->par->format == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','p');
1391 else if (track->par->format == AV_PIX_FMT_YUV420P) tag = MKTAG('d','v','c','p');
1392 else tag = MKTAG('d','v','p','p');
1393 } else if (track->par->height == 720) { /* HD 720 line */
1394 if (track->st->time_base.den == 50) tag = MKTAG('d','v','h','q');
1395 else tag = MKTAG('d','v','h','p');
1396 } else if (track->par->height == 1080) { /* HD 1080 line */
1397 if (track->st->time_base.den == 25) tag = MKTAG('d','v','h','5');
1398 else tag = MKTAG('d','v','h','6');
1400 av_log(s, AV_LOG_ERROR, "unsupported height for dv codec\n");
1407 static AVRational find_fps(AVFormatContext *s, AVStream *st)
1409 AVRational rate = st->avg_frame_rate;
1411 #if FF_API_LAVF_AVCTX
1412 FF_DISABLE_DEPRECATION_WARNINGS
1413 rate = av_inv_q(st->codec->time_base);
1414 if (av_timecode_check_frame_rate(rate) < 0) {
1415 av_log(s, AV_LOG_DEBUG, "timecode: tbc=%d/%d invalid, fallback on %d/%d\n",
1416 rate.num, rate.den, st->avg_frame_rate.num, st->avg_frame_rate.den);
1417 rate = st->avg_frame_rate;
1419 FF_ENABLE_DEPRECATION_WARNINGS
1425 static int defined_frame_rate(AVFormatContext *s, AVStream *st)
1427 AVRational rational_framerate = find_fps(s, st);
1429 if (rational_framerate.den != 0)
1430 rate = av_q2d(rational_framerate);
1434 static int mov_get_mpeg2_xdcam_codec_tag(AVFormatContext *s, MOVTrack *track)
1436 int tag = track->par->codec_tag;
1437 int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE;
1438 AVStream *st = track->st;
1439 int rate = defined_frame_rate(s, st);
1442 tag = MKTAG('m', '2', 'v', '1'); //fallback tag
1444 if (track->par->format == AV_PIX_FMT_YUV420P) {
1445 if (track->par->width == 1280 && track->par->height == 720) {
1447 if (rate == 24) tag = MKTAG('x','d','v','4');
1448 else if (rate == 25) tag = MKTAG('x','d','v','5');
1449 else if (rate == 30) tag = MKTAG('x','d','v','1');
1450 else if (rate == 50) tag = MKTAG('x','d','v','a');
1451 else if (rate == 60) tag = MKTAG('x','d','v','9');
1453 } else if (track->par->width == 1440 && track->par->height == 1080) {
1455 if (rate == 24) tag = MKTAG('x','d','v','6');
1456 else if (rate == 25) tag = MKTAG('x','d','v','7');
1457 else if (rate == 30) tag = MKTAG('x','d','v','8');
1459 if (rate == 25) tag = MKTAG('x','d','v','3');
1460 else if (rate == 30) tag = MKTAG('x','d','v','2');
1462 } else if (track->par->width == 1920 && track->par->height == 1080) {
1464 if (rate == 24) tag = MKTAG('x','d','v','d');
1465 else if (rate == 25) tag = MKTAG('x','d','v','e');
1466 else if (rate == 30) tag = MKTAG('x','d','v','f');
1468 if (rate == 25) tag = MKTAG('x','d','v','c');
1469 else if (rate == 30) tag = MKTAG('x','d','v','b');
1472 } else if (track->par->format == AV_PIX_FMT_YUV422P) {
1473 if (track->par->width == 1280 && track->par->height == 720) {
1475 if (rate == 24) tag = MKTAG('x','d','5','4');
1476 else if (rate == 25) tag = MKTAG('x','d','5','5');
1477 else if (rate == 30) tag = MKTAG('x','d','5','1');
1478 else if (rate == 50) tag = MKTAG('x','d','5','a');
1479 else if (rate == 60) tag = MKTAG('x','d','5','9');
1481 } else if (track->par->width == 1920 && track->par->height == 1080) {
1483 if (rate == 24) tag = MKTAG('x','d','5','d');
1484 else if (rate == 25) tag = MKTAG('x','d','5','e');
1485 else if (rate == 30) tag = MKTAG('x','d','5','f');
1487 if (rate == 25) tag = MKTAG('x','d','5','c');
1488 else if (rate == 30) tag = MKTAG('x','d','5','b');
1496 static int mov_get_h264_codec_tag(AVFormatContext *s, MOVTrack *track)
1498 int tag = track->par->codec_tag;
1499 int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE;
1500 AVStream *st = track->st;
1501 int rate = defined_frame_rate(s, st);
1504 tag = MKTAG('a', 'v', 'c', 'i'); //fallback tag
1506 if (track->par->format == AV_PIX_FMT_YUV420P10) {
1507 if (track->par->width == 960 && track->par->height == 720) {
1509 if (rate == 24) tag = MKTAG('a','i','5','p');
1510 else if (rate == 25) tag = MKTAG('a','i','5','q');
1511 else if (rate == 30) tag = MKTAG('a','i','5','p');
1512 else if (rate == 50) tag = MKTAG('a','i','5','q');
1513 else if (rate == 60) tag = MKTAG('a','i','5','p');
1515 } else if (track->par->width == 1440 && track->par->height == 1080) {
1517 if (rate == 24) tag = MKTAG('a','i','5','3');
1518 else if (rate == 25) tag = MKTAG('a','i','5','2');
1519 else if (rate == 30) tag = MKTAG('a','i','5','3');
1521 if (rate == 50) tag = MKTAG('a','i','5','5');
1522 else if (rate == 60) tag = MKTAG('a','i','5','6');
1525 } else if (track->par->format == AV_PIX_FMT_YUV422P10) {
1526 if (track->par->width == 1280 && track->par->height == 720) {
1528 if (rate == 24) tag = MKTAG('a','i','1','p');
1529 else if (rate == 25) tag = MKTAG('a','i','1','q');
1530 else if (rate == 30) tag = MKTAG('a','i','1','p');
1531 else if (rate == 50) tag = MKTAG('a','i','1','q');
1532 else if (rate == 60) tag = MKTAG('a','i','1','p');
1534 } else if (track->par->width == 1920 && track->par->height == 1080) {
1536 if (rate == 24) tag = MKTAG('a','i','1','3');
1537 else if (rate == 25) tag = MKTAG('a','i','1','2');
1538 else if (rate == 30) tag = MKTAG('a','i','1','3');
1540 if (rate == 25) tag = MKTAG('a','i','1','5');
1541 else if (rate == 50) tag = MKTAG('a','i','1','5');
1542 else if (rate == 60) tag = MKTAG('a','i','1','6');
1544 } else if ( track->par->width == 4096 && track->par->height == 2160
1545 || track->par->width == 3840 && track->par->height == 2160
1546 || track->par->width == 2048 && track->par->height == 1080) {
1547 tag = MKTAG('a','i','v','x');
1554 static const struct {
1555 enum AVPixelFormat pix_fmt;
1558 } mov_pix_fmt_tags[] = {
1559 { AV_PIX_FMT_YUYV422, MKTAG('y','u','v','2'), 0 },
1560 { AV_PIX_FMT_YUYV422, MKTAG('y','u','v','s'), 0 },
1561 { AV_PIX_FMT_UYVY422, MKTAG('2','v','u','y'), 0 },
1562 { AV_PIX_FMT_RGB555BE,MKTAG('r','a','w',' '), 16 },
1563 { AV_PIX_FMT_RGB555LE,MKTAG('L','5','5','5'), 16 },
1564 { AV_PIX_FMT_RGB565LE,MKTAG('L','5','6','5'), 16 },
1565 { AV_PIX_FMT_RGB565BE,MKTAG('B','5','6','5'), 16 },
1566 { AV_PIX_FMT_GRAY16BE,MKTAG('b','1','6','g'), 16 },
1567 { AV_PIX_FMT_RGB24, MKTAG('r','a','w',' '), 24 },
1568 { AV_PIX_FMT_BGR24, MKTAG('2','4','B','G'), 24 },
1569 { AV_PIX_FMT_ARGB, MKTAG('r','a','w',' '), 32 },
1570 { AV_PIX_FMT_BGRA, MKTAG('B','G','R','A'), 32 },
1571 { AV_PIX_FMT_RGBA, MKTAG('R','G','B','A'), 32 },
1572 { AV_PIX_FMT_ABGR, MKTAG('A','B','G','R'), 32 },
1573 { AV_PIX_FMT_RGB48BE, MKTAG('b','4','8','r'), 48 },
1576 static int mov_get_dnxhd_codec_tag(AVFormatContext *s, MOVTrack *track)
1578 int tag = MKTAG('A','V','d','n');
1579 if (track->par->profile != FF_PROFILE_UNKNOWN &&
1580 track->par->profile != FF_PROFILE_DNXHD)
1581 tag = MKTAG('A','V','d','h');
1585 static int mov_get_rawvideo_codec_tag(AVFormatContext *s, MOVTrack *track)
1587 int tag = track->par->codec_tag;
1589 enum AVPixelFormat pix_fmt;
1591 for (i = 0; i < FF_ARRAY_ELEMS(mov_pix_fmt_tags); i++) {
1592 if (track->par->format == mov_pix_fmt_tags[i].pix_fmt) {
1593 tag = mov_pix_fmt_tags[i].tag;
1594 track->par->bits_per_coded_sample = mov_pix_fmt_tags[i].bps;
1595 if (track->par->codec_tag == mov_pix_fmt_tags[i].tag)
1600 pix_fmt = avpriv_find_pix_fmt(avpriv_pix_fmt_bps_mov,
1601 track->par->bits_per_coded_sample);
1602 if (tag == MKTAG('r','a','w',' ') &&
1603 track->par->format != pix_fmt &&
1604 track->par->format != AV_PIX_FMT_GRAY8 &&
1605 track->par->format != AV_PIX_FMT_NONE)
1606 av_log(s, AV_LOG_ERROR, "%s rawvideo cannot be written to mov, output file will be unreadable\n",
1607 av_get_pix_fmt_name(track->par->format));
1611 static unsigned int mov_get_codec_tag(AVFormatContext *s, MOVTrack *track)
1613 unsigned int tag = track->par->codec_tag;
1615 if (!tag || (s->strict_std_compliance >= FF_COMPLIANCE_NORMAL &&
1616 (track->par->codec_id == AV_CODEC_ID_DVVIDEO ||
1617 track->par->codec_id == AV_CODEC_ID_RAWVIDEO ||
1618 track->par->codec_id == AV_CODEC_ID_H263 ||
1619 track->par->codec_id == AV_CODEC_ID_H264 ||
1620 track->par->codec_id == AV_CODEC_ID_DNXHD ||
1621 track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO ||
1622 av_get_bits_per_sample(track->par->codec_id)))) { // pcm audio
1623 if (track->par->codec_id == AV_CODEC_ID_DVVIDEO)
1624 tag = mov_get_dv_codec_tag(s, track);
1625 else if (track->par->codec_id == AV_CODEC_ID_RAWVIDEO)
1626 tag = mov_get_rawvideo_codec_tag(s, track);
1627 else if (track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO)
1628 tag = mov_get_mpeg2_xdcam_codec_tag(s, track);
1629 else if (track->par->codec_id == AV_CODEC_ID_H264)
1630 tag = mov_get_h264_codec_tag(s, track);
1631 else if (track->par->codec_id == AV_CODEC_ID_DNXHD)
1632 tag = mov_get_dnxhd_codec_tag(s, track);
1633 else if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
1634 tag = ff_codec_get_tag(ff_codec_movvideo_tags, track->par->codec_id);
1635 if (!tag) { // if no mac fcc found, try with Microsoft tags
1636 tag = ff_codec_get_tag(ff_codec_bmp_tags, track->par->codec_id);
1638 av_log(s, AV_LOG_WARNING, "Using MS style video codec tag, "
1639 "the file may be unplayable!\n");
1641 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
1642 tag = ff_codec_get_tag(ff_codec_movaudio_tags, track->par->codec_id);
1643 if (!tag) { // if no mac fcc found, try with Microsoft tags
1644 int ms_tag = ff_codec_get_tag(ff_codec_wav_tags, track->par->codec_id);
1646 tag = MKTAG('m', 's', ((ms_tag >> 8) & 0xff), (ms_tag & 0xff));
1647 av_log(s, AV_LOG_WARNING, "Using MS style audio codec tag, "
1648 "the file may be unplayable!\n");
1651 } else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)
1652 tag = ff_codec_get_tag(ff_codec_movsubtitle_tags, track->par->codec_id);
1658 static const AVCodecTag codec_cover_image_tags[] = {
1659 { AV_CODEC_ID_MJPEG, 0xD },
1660 { AV_CODEC_ID_PNG, 0xE },
1661 { AV_CODEC_ID_BMP, 0x1B },
1662 { AV_CODEC_ID_NONE, 0 },
1665 static unsigned int validate_codec_tag(const AVCodecTag *const *tags,
1666 unsigned int tag, int codec_id)
1671 * Check that tag + id is in the table
1673 for (i = 0; tags && tags[i]; i++) {
1674 const AVCodecTag *codec_tags = tags[i];
1675 while (codec_tags->id != AV_CODEC_ID_NONE) {
1676 if (avpriv_toupper4(codec_tags->tag) == avpriv_toupper4(tag) &&
1677 codec_tags->id == codec_id)
1678 return codec_tags->tag;
1685 static unsigned int mov_find_codec_tag(AVFormatContext *s, MOVTrack *track)
1687 if (is_cover_image(track->st))
1688 return ff_codec_get_tag(codec_cover_image_tags, track->par->codec_id);
1690 if (track->mode == MODE_IPOD)
1691 if (!av_match_ext(s->url, "m4a") &&
1692 !av_match_ext(s->url, "m4v") &&
1693 !av_match_ext(s->url, "m4b"))
1694 av_log(s, AV_LOG_WARNING, "Warning, extension is not .m4a nor .m4v "
1695 "Quicktime/Ipod might not play the file\n");
1697 if (track->mode == MODE_MOV) {
1698 return mov_get_codec_tag(s, track);
1700 return validate_codec_tag(s->oformat->codec_tag, track->par->codec_tag,
1701 track->par->codec_id);
1704 /** Write uuid atom.
1705 * Needed to make file play in iPods running newest firmware
1706 * goes after avcC atom in moov.trak.mdia.minf.stbl.stsd.avc1
1708 static int mov_write_uuid_tag_ipod(AVIOContext *pb)
1711 ffio_wfourcc(pb, "uuid");
1712 avio_wb32(pb, 0x6b6840f2);
1713 avio_wb32(pb, 0x5f244fc5);
1714 avio_wb32(pb, 0xba39a51b);
1715 avio_wb32(pb, 0xcf0323f3);
1720 static const uint16_t fiel_data[] = {
1721 0x0000, 0x0100, 0x0201, 0x0206, 0x0209, 0x020e
1724 static int mov_write_fiel_tag(AVIOContext *pb, MOVTrack *track, int field_order)
1726 unsigned mov_field_order = 0;
1727 if (field_order < FF_ARRAY_ELEMS(fiel_data))
1728 mov_field_order = fiel_data[field_order];
1732 ffio_wfourcc(pb, "fiel");
1733 avio_wb16(pb, mov_field_order);
1737 static int mov_write_subtitle_tag(AVIOContext *pb, MOVTrack *track)
1739 int64_t pos = avio_tell(pb);
1740 avio_wb32(pb, 0); /* size */
1741 avio_wl32(pb, track->tag); // store it byteswapped
1742 avio_wb32(pb, 0); /* Reserved */
1743 avio_wb16(pb, 0); /* Reserved */
1744 avio_wb16(pb, 1); /* Data-reference index */
1746 if (track->par->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
1747 mov_write_esds_tag(pb, track);
1748 else if (track->par->extradata_size)
1749 avio_write(pb, track->par->extradata, track->par->extradata_size);
1751 return update_size(pb, pos);
1754 static int mov_write_st3d_tag(AVFormatContext *s, AVIOContext *pb, AVStereo3D *stereo_3d)
1758 if (stereo_3d->flags != 0) {
1759 av_log(s, AV_LOG_WARNING, "Unsupported stereo_3d flags %x. st3d not written.\n", stereo_3d->flags);
1763 switch (stereo_3d->type) {
1764 case AV_STEREO3D_2D:
1767 case AV_STEREO3D_TOPBOTTOM:
1770 case AV_STEREO3D_SIDEBYSIDE:
1774 av_log(s, AV_LOG_WARNING, "Unsupported stereo_3d type %s. st3d not written.\n", av_stereo3d_type_name(stereo_3d->type));
1777 avio_wb32(pb, 13); /* size */
1778 ffio_wfourcc(pb, "st3d");
1779 avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1780 avio_w8(pb, stereo_mode);
1784 static int mov_write_sv3d_tag(AVFormatContext *s, AVIOContext *pb, AVSphericalMapping *spherical_mapping)
1786 int64_t sv3d_pos, svhd_pos, proj_pos;
1787 const char* metadata_source = s->flags & AVFMT_FLAG_BITEXACT ? "Lavf" : LIBAVFORMAT_IDENT;
1789 if (spherical_mapping->projection != AV_SPHERICAL_EQUIRECTANGULAR &&
1790 spherical_mapping->projection != AV_SPHERICAL_EQUIRECTANGULAR_TILE &&
1791 spherical_mapping->projection != AV_SPHERICAL_CUBEMAP) {
1792 av_log(s, AV_LOG_WARNING, "Unsupported projection %d. sv3d not written.\n", spherical_mapping->projection);
1796 sv3d_pos = avio_tell(pb);
1797 avio_wb32(pb, 0); /* size */
1798 ffio_wfourcc(pb, "sv3d");
1800 svhd_pos = avio_tell(pb);
1801 avio_wb32(pb, 0); /* size */
1802 ffio_wfourcc(pb, "svhd");
1803 avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1804 avio_put_str(pb, metadata_source);
1805 update_size(pb, svhd_pos);
1807 proj_pos = avio_tell(pb);
1808 avio_wb32(pb, 0); /* size */
1809 ffio_wfourcc(pb, "proj");
1811 avio_wb32(pb, 24); /* size */
1812 ffio_wfourcc(pb, "prhd");
1813 avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1814 avio_wb32(pb, spherical_mapping->yaw);
1815 avio_wb32(pb, spherical_mapping->pitch);
1816 avio_wb32(pb, spherical_mapping->roll);
1818 switch (spherical_mapping->projection) {
1819 case AV_SPHERICAL_EQUIRECTANGULAR:
1820 case AV_SPHERICAL_EQUIRECTANGULAR_TILE:
1821 avio_wb32(pb, 28); /* size */
1822 ffio_wfourcc(pb, "equi");
1823 avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1824 avio_wb32(pb, spherical_mapping->bound_top);
1825 avio_wb32(pb, spherical_mapping->bound_bottom);
1826 avio_wb32(pb, spherical_mapping->bound_left);
1827 avio_wb32(pb, spherical_mapping->bound_right);
1829 case AV_SPHERICAL_CUBEMAP:
1830 avio_wb32(pb, 20); /* size */
1831 ffio_wfourcc(pb, "cbmp");
1832 avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1833 avio_wb32(pb, 0); /* layout */
1834 avio_wb32(pb, spherical_mapping->padding); /* padding */
1837 update_size(pb, proj_pos);
1839 return update_size(pb, sv3d_pos);
1842 static int mov_write_dvcc_dvvc_tag(AVFormatContext *s, AVIOContext *pb, AVDOVIDecoderConfigurationRecord *dovi)
1844 avio_wb32(pb, 32); /* size = 8 + 24 */
1845 if (dovi->dv_profile > 7)
1846 ffio_wfourcc(pb, "dvvC");
1848 ffio_wfourcc(pb, "dvcC");
1849 avio_w8(pb, dovi->dv_version_major);
1850 avio_w8(pb, dovi->dv_version_minor);
1851 avio_wb16(pb, (dovi->dv_profile << 9) | (dovi->dv_level << 3) |
1852 (dovi->rpu_present_flag << 2) | (dovi->el_present_flag << 1) |
1853 dovi->bl_present_flag);
1854 avio_wb32(pb, (dovi->dv_bl_signal_compatibility_id << 28) | 0);
1856 avio_wb32(pb, 0); /* reserved */
1857 avio_wb32(pb, 0); /* reserved */
1858 avio_wb32(pb, 0); /* reserved */
1859 avio_wb32(pb, 0); /* reserved */
1860 av_log(s, AV_LOG_DEBUG, "DOVI in %s box, version: %d.%d, profile: %d, level: %d, "
1861 "rpu flag: %d, el flag: %d, bl flag: %d, compatibility id: %d\n",
1862 dovi->dv_profile > 7 ? "dvvC" : "dvcC",
1863 dovi->dv_version_major, dovi->dv_version_minor,
1864 dovi->dv_profile, dovi->dv_level,
1865 dovi->rpu_present_flag,
1866 dovi->el_present_flag,
1867 dovi->bl_present_flag,
1868 dovi->dv_bl_signal_compatibility_id);
1869 return 32; /* 8 + 24 */
1872 static int mov_write_clap_tag(AVIOContext *pb, MOVTrack *track)
1875 ffio_wfourcc(pb, "clap");
1876 avio_wb32(pb, track->par->width); /* apertureWidth_N */
1877 avio_wb32(pb, 1); /* apertureWidth_D (= 1) */
1878 avio_wb32(pb, track->height); /* apertureHeight_N */
1879 avio_wb32(pb, 1); /* apertureHeight_D (= 1) */
1880 avio_wb32(pb, 0); /* horizOff_N (= 0) */
1881 avio_wb32(pb, 1); /* horizOff_D (= 1) */
1882 avio_wb32(pb, 0); /* vertOff_N (= 0) */
1883 avio_wb32(pb, 1); /* vertOff_D (= 1) */
1887 static int mov_write_pasp_tag(AVIOContext *pb, MOVTrack *track)
1890 av_reduce(&sar.num, &sar.den, track->par->sample_aspect_ratio.num,
1891 track->par->sample_aspect_ratio.den, INT_MAX);
1894 ffio_wfourcc(pb, "pasp");
1895 avio_wb32(pb, sar.num);
1896 avio_wb32(pb, sar.den);
1900 static int mov_write_gama_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track, double gamma)
1904 gamma = avpriv_get_gamma_from_trc(track->par->color_trc);
1906 av_log(s, AV_LOG_DEBUG, "gamma value %g\n", gamma);
1909 gama = (uint32_t)lrint((double)(1<<16) * gamma);
1910 av_log(s, AV_LOG_DEBUG, "writing gama value %"PRId32"\n", gama);
1912 av_assert0(track->mode == MODE_MOV);
1914 ffio_wfourcc(pb, "gama");
1915 avio_wb32(pb, gama);
1918 av_log(s, AV_LOG_WARNING, "gamma value unknown, unable to write gama atom\n");
1923 static int mov_write_colr_tag(AVIOContext *pb, MOVTrack *track, int prefer_icc)
1925 int64_t pos = avio_tell(pb);
1927 // Ref (MOV): https://developer.apple.com/library/mac/technotes/tn2162/_index.html#//apple_ref/doc/uid/DTS40013070-CH1-TNTAG9
1928 // Ref (MP4): ISO/IEC 14496-12:2012
1930 const uint8_t *icc_profile;
1931 int icc_profile_size;
1934 icc_profile = av_stream_get_side_data(track->st, AV_PKT_DATA_ICC_PROFILE, &icc_profile_size);
1937 avio_wb32(pb, 12 + icc_profile_size);
1938 ffio_wfourcc(pb, "colr");
1939 ffio_wfourcc(pb, "prof");
1940 avio_write(pb, icc_profile, icc_profile_size);
1941 return 12 + icc_profile_size;
1944 av_log(NULL, AV_LOG_INFO, "no ICC profile found, will write nclx/nclc colour info instead\n");
1948 /* We should only ever be called by MOV or MP4. */
1949 av_assert0(track->mode == MODE_MOV || track->mode == MODE_MP4);
1951 avio_wb32(pb, 0); /* size */
1952 ffio_wfourcc(pb, "colr");
1953 if (track->mode == MODE_MP4)
1954 ffio_wfourcc(pb, "nclx");
1956 ffio_wfourcc(pb, "nclc");
1957 // Do not try to guess the color info if it is AVCOL_PRI_UNSPECIFIED.
1958 // e.g., Dolby Vision for Apple devices should be set to AVCOL_PRI_UNSPECIFIED. See
1959 // https://developer.apple.com/av-foundation/High-Dynamic-Range-Metadata-for-Apple-Devices.pdf
1960 avio_wb16(pb, track->par->color_primaries);
1961 avio_wb16(pb, track->par->color_trc);
1962 avio_wb16(pb, track->par->color_space);
1963 if (track->mode == MODE_MP4) {
1964 int full_range = track->par->color_range == AVCOL_RANGE_JPEG;
1965 avio_w8(pb, full_range << 7);
1968 return update_size(pb, pos);
1971 static int mov_write_clli_tag(AVIOContext *pb, MOVTrack *track)
1973 const uint8_t *side_data;
1974 const AVContentLightMetadata *content_light_metadata;
1976 side_data = av_stream_get_side_data(track->st, AV_PKT_DATA_CONTENT_LIGHT_LEVEL, NULL);
1978 av_log(NULL, AV_LOG_VERBOSE, "Not writing 'clli' atom. No content light level info.\n");
1981 content_light_metadata = (const AVContentLightMetadata*)side_data;
1983 avio_wb32(pb, 12); // size
1984 ffio_wfourcc(pb, "clli");
1985 avio_wb16(pb, content_light_metadata->MaxCLL);
1986 avio_wb16(pb, content_light_metadata->MaxFALL);
1990 static inline int64_t rescale_mdcv(AVRational q, int b)
1992 return av_rescale(q.num, b, q.den);
1995 static int mov_write_mdcv_tag(AVIOContext *pb, MOVTrack *track)
1997 const int chroma_den = 50000;
1998 const int luma_den = 10000;
1999 const uint8_t *side_data;
2000 const AVMasteringDisplayMetadata *metadata;
2002 side_data = av_stream_get_side_data(track->st, AV_PKT_DATA_MASTERING_DISPLAY_METADATA, NULL);
2003 metadata = (const AVMasteringDisplayMetadata*)side_data;
2004 if (!metadata || !metadata->has_primaries || !metadata->has_luminance) {
2005 av_log(NULL, AV_LOG_VERBOSE, "Not writing 'mdcv' atom. Missing mastering metadata.\n");
2009 avio_wb32(pb, 32); // size
2010 ffio_wfourcc(pb, "mdcv");
2011 avio_wb16(pb, rescale_mdcv(metadata->display_primaries[1][0], chroma_den));
2012 avio_wb16(pb, rescale_mdcv(metadata->display_primaries[1][1], chroma_den));
2013 avio_wb16(pb, rescale_mdcv(metadata->display_primaries[2][0], chroma_den));
2014 avio_wb16(pb, rescale_mdcv(metadata->display_primaries[2][1], chroma_den));
2015 avio_wb16(pb, rescale_mdcv(metadata->display_primaries[0][0], chroma_den));
2016 avio_wb16(pb, rescale_mdcv(metadata->display_primaries[0][1], chroma_den));
2017 avio_wb16(pb, rescale_mdcv(metadata->white_point[0], chroma_den));
2018 avio_wb16(pb, rescale_mdcv(metadata->white_point[1], chroma_den));
2019 avio_wb32(pb, rescale_mdcv(metadata->max_luminance, luma_den));
2020 avio_wb32(pb, rescale_mdcv(metadata->min_luminance, luma_den));
2024 static void find_compressor(char * compressor_name, int len, MOVTrack *track)
2026 AVDictionaryEntry *encoder;
2027 int xdcam_res = (track->par->width == 1280 && track->par->height == 720)
2028 || (track->par->width == 1440 && track->par->height == 1080)
2029 || (track->par->width == 1920 && track->par->height == 1080);
2031 if (track->mode == MODE_MOV &&
2032 (encoder = av_dict_get(track->st->metadata, "encoder", NULL, 0))) {
2033 av_strlcpy(compressor_name, encoder->value, 32);
2034 } else if (track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO && xdcam_res) {
2035 int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE;
2036 AVStream *st = track->st;
2037 int rate = defined_frame_rate(NULL, st);
2038 av_strlcatf(compressor_name, len, "XDCAM");
2039 if (track->par->format == AV_PIX_FMT_YUV422P) {
2040 av_strlcatf(compressor_name, len, " HD422");
2041 } else if(track->par->width == 1440) {
2042 av_strlcatf(compressor_name, len, " HD");
2044 av_strlcatf(compressor_name, len, " EX");
2046 av_strlcatf(compressor_name, len, " %d%c", track->par->height, interlaced ? 'i' : 'p');
2048 av_strlcatf(compressor_name, len, "%d", rate * (interlaced + 1));
2052 static int mov_write_video_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
2054 int64_t pos = avio_tell(pb);
2055 char compressor_name[32] = { 0 };
2058 int uncompressed_ycbcr = ((track->par->codec_id == AV_CODEC_ID_RAWVIDEO && track->par->format == AV_PIX_FMT_UYVY422)
2059 || (track->par->codec_id == AV_CODEC_ID_RAWVIDEO && track->par->format == AV_PIX_FMT_YUYV422)
2060 || track->par->codec_id == AV_CODEC_ID_V308
2061 || track->par->codec_id == AV_CODEC_ID_V408
2062 || track->par->codec_id == AV_CODEC_ID_V410
2063 || track->par->codec_id == AV_CODEC_ID_V210);
2065 avio_wb32(pb, 0); /* size */
2066 if (mov->encryption_scheme != MOV_ENC_NONE) {
2067 ffio_wfourcc(pb, "encv");
2069 avio_wl32(pb, track->tag); // store it byteswapped
2071 avio_wb32(pb, 0); /* Reserved */
2072 avio_wb16(pb, 0); /* Reserved */
2073 avio_wb16(pb, 1); /* Data-reference index */
2075 if (uncompressed_ycbcr) {
2076 avio_wb16(pb, 2); /* Codec stream version */
2078 avio_wb16(pb, 0); /* Codec stream version */
2080 avio_wb16(pb, 0); /* Codec stream revision (=0) */
2081 if (track->mode == MODE_MOV) {
2082 ffio_wfourcc(pb, "FFMP"); /* Vendor */
2083 if (track->par->codec_id == AV_CODEC_ID_RAWVIDEO || uncompressed_ycbcr) {
2084 avio_wb32(pb, 0); /* Temporal Quality */
2085 avio_wb32(pb, 0x400); /* Spatial Quality = lossless*/
2087 avio_wb32(pb, 0x200); /* Temporal Quality = normal */
2088 avio_wb32(pb, 0x200); /* Spatial Quality = normal */
2091 avio_wb32(pb, 0); /* Reserved */
2092 avio_wb32(pb, 0); /* Reserved */
2093 avio_wb32(pb, 0); /* Reserved */
2095 avio_wb16(pb, track->par->width); /* Video width */
2096 avio_wb16(pb, track->height); /* Video height */
2097 avio_wb32(pb, 0x00480000); /* Horizontal resolution 72dpi */
2098 avio_wb32(pb, 0x00480000); /* Vertical resolution 72dpi */
2099 avio_wb32(pb, 0); /* Data size (= 0) */
2100 avio_wb16(pb, 1); /* Frame count (= 1) */
2102 /* FIXME not sure, ISO 14496-1 draft where it shall be set to 0 */
2103 find_compressor(compressor_name, 32, track);
2104 avio_w8(pb, strlen(compressor_name));
2105 avio_write(pb, compressor_name, 31);
2107 if (track->mode == MODE_MOV &&
2108 (track->par->codec_id == AV_CODEC_ID_V410 || track->par->codec_id == AV_CODEC_ID_V210))
2109 avio_wb16(pb, 0x18);
2110 else if (track->mode == MODE_MOV && track->par->bits_per_coded_sample)
2111 avio_wb16(pb, track->par->bits_per_coded_sample |
2112 (track->par->format == AV_PIX_FMT_GRAY8 ? 0x20 : 0));
2114 avio_wb16(pb, 0x18); /* Reserved */
2116 if (track->mode == MODE_MOV && track->par->format == AV_PIX_FMT_PAL8) {
2117 int pal_size = 1 << track->par->bits_per_coded_sample;
2119 avio_wb16(pb, 0); /* Color table ID */
2120 avio_wb32(pb, 0); /* Color table seed */
2121 avio_wb16(pb, 0x8000); /* Color table flags */
2122 avio_wb16(pb, pal_size - 1); /* Color table size (zero-relative) */
2123 for (i = 0; i < pal_size; i++) {
2124 uint32_t rgb = track->palette[i];
2125 uint16_t r = (rgb >> 16) & 0xff;
2126 uint16_t g = (rgb >> 8) & 0xff;
2127 uint16_t b = rgb & 0xff;
2129 avio_wb16(pb, (r << 8) | r);
2130 avio_wb16(pb, (g << 8) | g);
2131 avio_wb16(pb, (b << 8) | b);
2134 avio_wb16(pb, 0xffff); /* Reserved */
2136 if (track->tag == MKTAG('m','p','4','v'))
2137 mov_write_esds_tag(pb, track);
2138 else if (track->par->codec_id == AV_CODEC_ID_H263)
2139 mov_write_d263_tag(pb);
2140 else if (track->par->codec_id == AV_CODEC_ID_AVUI ||
2141 track->par->codec_id == AV_CODEC_ID_SVQ3) {
2142 mov_write_extradata_tag(pb, track);
2144 } else if (track->par->codec_id == AV_CODEC_ID_DNXHD) {
2145 mov_write_avid_tag(pb, track);
2147 } else if (track->par->codec_id == AV_CODEC_ID_HEVC)
2148 mov_write_hvcc_tag(pb, track);
2149 else if (track->par->codec_id == AV_CODEC_ID_H264 && !TAG_IS_AVCI(track->tag)) {
2150 mov_write_avcc_tag(pb, track);
2151 if (track->mode == MODE_IPOD)
2152 mov_write_uuid_tag_ipod(pb);
2153 } else if (track->par->codec_id == AV_CODEC_ID_VP9) {
2154 mov_write_vpcc_tag(mov->fc, pb, track);
2155 } else if (track->par->codec_id == AV_CODEC_ID_AV1) {
2156 mov_write_av1c_tag(pb, track);
2157 } else if (track->par->codec_id == AV_CODEC_ID_VC1 && track->vos_len > 0)
2158 mov_write_dvc1_tag(pb, track);
2159 else if (track->par->codec_id == AV_CODEC_ID_VP6F ||
2160 track->par->codec_id == AV_CODEC_ID_VP6A) {
2161 /* Don't write any potential extradata here - the cropping
2162 * is signalled via the normal width/height fields. */
2163 } else if (track->par->codec_id == AV_CODEC_ID_R10K) {
2164 if (track->par->codec_tag == MKTAG('R','1','0','k'))
2165 mov_write_dpxe_tag(pb, track);
2166 } else if (track->vos_len > 0)
2167 mov_write_glbl_tag(pb, track);
2169 if (track->par->codec_id != AV_CODEC_ID_H264 &&
2170 track->par->codec_id != AV_CODEC_ID_MPEG4 &&
2171 track->par->codec_id != AV_CODEC_ID_DNXHD) {
2172 int field_order = track->par->field_order;
2174 #if FF_API_LAVF_AVCTX
2175 FF_DISABLE_DEPRECATION_WARNINGS
2176 if (field_order != track->st->codec->field_order && track->st->codec->field_order != AV_FIELD_UNKNOWN)
2177 field_order = track->st->codec->field_order;
2178 FF_ENABLE_DEPRECATION_WARNINGS
2181 if (field_order != AV_FIELD_UNKNOWN)
2182 mov_write_fiel_tag(pb, track, field_order);
2185 if (mov->flags & FF_MOV_FLAG_WRITE_GAMA) {
2186 if (track->mode == MODE_MOV)
2187 mov_write_gama_tag(s, pb, track, mov->gamma);
2189 av_log(mov->fc, AV_LOG_WARNING, "Not writing 'gama' atom. Format is not MOV.\n");
2191 if (track->mode == MODE_MOV || track->mode == MODE_MP4) {
2192 int has_color_info = track->par->color_primaries != AVCOL_PRI_UNSPECIFIED &&
2193 track->par->color_trc != AVCOL_TRC_UNSPECIFIED &&
2194 track->par->color_space != AVCOL_SPC_UNSPECIFIED;
2195 if (has_color_info || mov->flags & FF_MOV_FLAG_WRITE_COLR ||
2196 av_stream_get_side_data(track->st, AV_PKT_DATA_ICC_PROFILE, NULL)) {
2197 int prefer_icc = mov->flags & FF_MOV_FLAG_PREFER_ICC || !has_color_info;
2198 mov_write_colr_tag(pb, track, prefer_icc);
2199 } else if (mov->flags & FF_MOV_FLAG_WRITE_COLR) {
2200 av_log(mov->fc, AV_LOG_WARNING, "Not writing 'colr' atom. Format is not MOV or MP4.\n");
2203 if (track->mode == MODE_MOV || track->mode == MODE_MP4) {
2204 mov_write_clli_tag(pb, track);
2205 mov_write_mdcv_tag(pb, track);
2208 if (track->mode == MODE_MP4 && mov->fc->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL) {
2209 AVStereo3D* stereo_3d = (AVStereo3D*) av_stream_get_side_data(track->st, AV_PKT_DATA_STEREO3D, NULL);
2210 AVSphericalMapping* spherical_mapping = (AVSphericalMapping*)av_stream_get_side_data(track->st, AV_PKT_DATA_SPHERICAL, NULL);
2211 AVDOVIDecoderConfigurationRecord *dovi = (AVDOVIDecoderConfigurationRecord *)
2212 av_stream_get_side_data(track->st, AV_PKT_DATA_DOVI_CONF, NULL);;
2215 mov_write_st3d_tag(s, pb, stereo_3d);
2216 if (spherical_mapping)
2217 mov_write_sv3d_tag(mov->fc, pb, spherical_mapping);
2219 mov_write_dvcc_dvvc_tag(s, pb, dovi);
2222 if (track->par->sample_aspect_ratio.den && track->par->sample_aspect_ratio.num) {
2223 mov_write_pasp_tag(pb, track);
2226 if (uncompressed_ycbcr){
2227 mov_write_clap_tag(pb, track);
2230 if (mov->encryption_scheme != MOV_ENC_NONE) {
2231 ff_mov_cenc_write_sinf_tag(track, pb, mov->encryption_kid);
2234 /* extra padding for avid stsd */
2235 /* https://developer.apple.com/library/mac/documentation/QuickTime/QTFF/QTFFChap2/qtff2.html#//apple_ref/doc/uid/TP40000939-CH204-61112 */
2239 return update_size(pb, pos);
2242 static int mov_write_rtp_tag(AVIOContext *pb, MOVTrack *track)
2244 int64_t pos = avio_tell(pb);
2245 avio_wb32(pb, 0); /* size */
2246 ffio_wfourcc(pb, "rtp ");
2247 avio_wb32(pb, 0); /* Reserved */
2248 avio_wb16(pb, 0); /* Reserved */
2249 avio_wb16(pb, 1); /* Data-reference index */
2251 avio_wb16(pb, 1); /* Hint track version */
2252 avio_wb16(pb, 1); /* Highest compatible version */
2253 avio_wb32(pb, track->max_packet_size); /* Max packet size */
2255 avio_wb32(pb, 12); /* size */
2256 ffio_wfourcc(pb, "tims");
2257 avio_wb32(pb, track->timescale);
2259 return update_size(pb, pos);
2262 static int mov_write_source_reference_tag(AVIOContext *pb, MOVTrack *track, const char *reel_name)
2264 uint64_t str_size =strlen(reel_name);
2265 int64_t pos = avio_tell(pb);
2267 if (str_size >= UINT16_MAX){
2268 av_log(NULL, AV_LOG_ERROR, "reel_name length %"PRIu64" is too large\n", str_size);
2270 return AVERROR(EINVAL);
2273 avio_wb32(pb, 0); /* size */
2274 ffio_wfourcc(pb, "name"); /* Data format */
2275 avio_wb16(pb, str_size); /* string size */
2276 avio_wb16(pb, track->language); /* langcode */
2277 avio_write(pb, reel_name, str_size); /* reel name */
2278 return update_size(pb,pos);
2281 static int mov_write_tmcd_tag(AVIOContext *pb, MOVTrack *track)
2283 int64_t pos = avio_tell(pb);
2287 AVDictionaryEntry *t = NULL;
2289 if (!track->st->avg_frame_rate.num || !track->st->avg_frame_rate.den) {
2290 #if FF_API_LAVF_AVCTX
2291 FF_DISABLE_DEPRECATION_WARNINGS
2292 frame_duration = av_rescale(track->timescale, track->st->codec->time_base.num, track->st->codec->time_base.den);
2293 nb_frames = ROUNDED_DIV(track->st->codec->time_base.den, track->st->codec->time_base.num);
2294 FF_ENABLE_DEPRECATION_WARNINGS
2296 av_log(NULL, AV_LOG_ERROR, "avg_frame_rate not set for tmcd track.\n");
2297 return AVERROR(EINVAL);
2300 frame_duration = av_rescale(track->timescale, track->st->avg_frame_rate.num, track->st->avg_frame_rate.den);
2301 nb_frames = ROUNDED_DIV(track->st->avg_frame_rate.den, track->st->avg_frame_rate.num);
2304 if (nb_frames > 255) {
2305 av_log(NULL, AV_LOG_ERROR, "fps %d is too large\n", nb_frames);
2306 return AVERROR(EINVAL);
2309 avio_wb32(pb, 0); /* size */
2310 ffio_wfourcc(pb, "tmcd"); /* Data format */
2311 avio_wb32(pb, 0); /* Reserved */
2312 avio_wb32(pb, 1); /* Data reference index */
2313 avio_wb32(pb, 0); /* Flags */
2314 avio_wb32(pb, track->timecode_flags); /* Flags (timecode) */
2315 avio_wb32(pb, track->timescale); /* Timescale */
2316 avio_wb32(pb, frame_duration); /* Frame duration */
2317 avio_w8(pb, nb_frames); /* Number of frames */
2318 avio_w8(pb, 0); /* Reserved */
2320 t = av_dict_get(track->st->metadata, "reel_name", NULL, 0);
2321 if (t && utf8len(t->value) && track->mode != MODE_MP4)
2322 mov_write_source_reference_tag(pb, track, t->value);
2324 avio_wb16(pb, 0); /* zero size */
2327 avio_wb32(pb, 0); /* size */
2328 ffio_wfourcc(pb, "tmcd"); /* Data format */
2329 avio_wb32(pb, 0); /* Reserved */
2330 avio_wb32(pb, 1); /* Data reference index */
2331 if (track->par->extradata_size)
2332 avio_write(pb, track->par->extradata, track->par->extradata_size);
2334 return update_size(pb, pos);
2337 static int mov_write_gpmd_tag(AVIOContext *pb, const MOVTrack *track)
2339 int64_t pos = avio_tell(pb);
2340 avio_wb32(pb, 0); /* size */
2341 ffio_wfourcc(pb, "gpmd");
2342 avio_wb32(pb, 0); /* Reserved */
2343 avio_wb16(pb, 0); /* Reserved */
2344 avio_wb16(pb, 1); /* Data-reference index */
2345 avio_wb32(pb, 0); /* Reserved */
2346 return update_size(pb, pos);
2349 static int mov_write_stsd_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
2351 int64_t pos = avio_tell(pb);
2353 avio_wb32(pb, 0); /* size */
2354 ffio_wfourcc(pb, "stsd");
2355 avio_wb32(pb, 0); /* version & flags */
2356 avio_wb32(pb, 1); /* entry count */
2357 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO)
2358 ret = mov_write_video_tag(s, pb, mov, track);
2359 else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
2360 ret = mov_write_audio_tag(s, pb, mov, track);
2361 else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)
2362 ret = mov_write_subtitle_tag(pb, track);
2363 else if (track->par->codec_tag == MKTAG('r','t','p',' '))
2364 ret = mov_write_rtp_tag(pb, track);
2365 else if (track->par->codec_tag == MKTAG('t','m','c','d'))
2366 ret = mov_write_tmcd_tag(pb, track);
2367 else if (track->par->codec_tag == MKTAG('g','p','m','d'))
2368 ret = mov_write_gpmd_tag(pb, track);
2373 return update_size(pb, pos);
2376 static int mov_write_ctts_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
2378 MOVMuxContext *mov = s->priv_data;
2379 MOVStts *ctts_entries;
2380 uint32_t entries = 0;
2384 ctts_entries = av_malloc_array((track->entry + 1), sizeof(*ctts_entries)); /* worst case */
2386 return AVERROR(ENOMEM);
2387 ctts_entries[0].count = 1;
2388 ctts_entries[0].duration = track->cluster[0].cts;
2389 for (i = 1; i < track->entry; i++) {
2390 if (track->cluster[i].cts == ctts_entries[entries].duration) {
2391 ctts_entries[entries].count++; /* compress */
2394 ctts_entries[entries].duration = track->cluster[i].cts;
2395 ctts_entries[entries].count = 1;
2398 entries++; /* last one */
2399 atom_size = 16 + (entries * 8);
2400 avio_wb32(pb, atom_size); /* size */
2401 ffio_wfourcc(pb, "ctts");
2402 if (mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS)
2403 avio_w8(pb, 1); /* version */
2405 avio_w8(pb, 0); /* version */
2406 avio_wb24(pb, 0); /* flags */
2407 avio_wb32(pb, entries); /* entry count */
2408 for (i = 0; i < entries; i++) {
2409 avio_wb32(pb, ctts_entries[i].count);
2410 avio_wb32(pb, ctts_entries[i].duration);
2412 av_free(ctts_entries);
2416 /* Time to sample atom */
2417 static int mov_write_stts_tag(AVIOContext *pb, MOVTrack *track)
2419 MOVStts *stts_entries = NULL;
2420 uint32_t entries = -1;
2424 if (track->par->codec_type == AVMEDIA_TYPE_AUDIO && !track->audio_vbr) {
2425 stts_entries = av_malloc(sizeof(*stts_entries)); /* one entry */
2427 return AVERROR(ENOMEM);
2428 stts_entries[0].count = track->sample_count;
2429 stts_entries[0].duration = 1;
2433 stts_entries = av_malloc_array(track->entry, sizeof(*stts_entries)); /* worst case */
2435 return AVERROR(ENOMEM);
2437 for (i = 0; i < track->entry; i++) {
2438 int duration = get_cluster_duration(track, i);
2439 if (i && duration == stts_entries[entries].duration) {
2440 stts_entries[entries].count++; /* compress */
2443 stts_entries[entries].duration = duration;
2444 stts_entries[entries].count = 1;
2447 entries++; /* last one */
2449 atom_size = 16 + (entries * 8);
2450 avio_wb32(pb, atom_size); /* size */
2451 ffio_wfourcc(pb, "stts");
2452 avio_wb32(pb, 0); /* version & flags */
2453 avio_wb32(pb, entries); /* entry count */
2454 for (i = 0; i < entries; i++) {
2455 avio_wb32(pb, stts_entries[i].count);
2456 avio_wb32(pb, stts_entries[i].duration);
2458 av_free(stts_entries);
2462 static int mov_write_dref_tag(AVIOContext *pb)
2464 avio_wb32(pb, 28); /* size */
2465 ffio_wfourcc(pb, "dref");
2466 avio_wb32(pb, 0); /* version & flags */
2467 avio_wb32(pb, 1); /* entry count */
2469 avio_wb32(pb, 0xc); /* size */
2470 //FIXME add the alis and rsrc atom
2471 ffio_wfourcc(pb, "url ");
2472 avio_wb32(pb, 1); /* version & flags */
2477 static int mov_preroll_write_stbl_atoms(AVIOContext *pb, MOVTrack *track)
2481 int16_t roll_distance;
2482 int group_description_index;
2485 struct sgpd_entry *sgpd_entries = NULL;
2490 const int OPUS_SEEK_PREROLL_MS = 80;
2491 int roll_samples = av_rescale_q(OPUS_SEEK_PREROLL_MS,
2492 (AVRational){1, 1000},
2493 (AVRational){1, 48000});
2498 sgpd_entries = av_malloc_array(track->entry, sizeof(*sgpd_entries));
2500 return AVERROR(ENOMEM);
2502 av_assert0(track->par->codec_id == AV_CODEC_ID_OPUS || track->par->codec_id == AV_CODEC_ID_AAC);
2504 if (track->par->codec_id == AV_CODEC_ID_OPUS) {
2505 for (i = 0; i < track->entry; i++) {
2506 int roll_samples_remaining = roll_samples;
2508 for (j = i - 1; j >= 0; j--) {
2509 roll_samples_remaining -= get_cluster_duration(track, j);
2511 if (roll_samples_remaining <= 0)
2514 /* We don't have enough preceeding samples to compute a valid
2515 roll_distance here, so this sample can't be independently
2517 if (roll_samples_remaining > 0)
2519 /* Verify distance is a maximum of 32 (2.5ms) packets. */
2521 return AVERROR_INVALIDDATA;
2522 if (i && distance == sgpd_entries[entries].roll_distance) {
2523 sgpd_entries[entries].count++;
2526 sgpd_entries[entries].count = 1;
2527 sgpd_entries[entries].roll_distance = distance;
2528 sgpd_entries[entries].group_description_index = distance ? ++group : 0;
2533 sgpd_entries[entries].count = track->sample_count;
2534 sgpd_entries[entries].roll_distance = 1;
2535 sgpd_entries[entries].group_description_index = ++group;
2540 av_free(sgpd_entries);
2544 /* Write sgpd tag */
2545 avio_wb32(pb, 24 + (group * 2)); /* size */
2546 ffio_wfourcc(pb, "sgpd");
2547 avio_wb32(pb, 1 << 24); /* fullbox */
2548 ffio_wfourcc(pb, "roll");
2549 avio_wb32(pb, 2); /* default_length */
2550 avio_wb32(pb, group); /* entry_count */
2551 for (i = 0; i < entries; i++) {
2552 if (sgpd_entries[i].group_description_index) {
2553 avio_wb16(pb, -sgpd_entries[i].roll_distance); /* roll_distance */
2557 /* Write sbgp tag */
2558 avio_wb32(pb, 20 + (entries * 8)); /* size */
2559 ffio_wfourcc(pb, "sbgp");
2560 avio_wb32(pb, 0); /* fullbox */
2561 ffio_wfourcc(pb, "roll");
2562 avio_wb32(pb, entries); /* entry_count */
2563 for (i = 0; i < entries; i++) {
2564 avio_wb32(pb, sgpd_entries[i].count); /* sample_count */
2565 avio_wb32(pb, sgpd_entries[i].group_description_index); /* group_description_index */
2568 av_free(sgpd_entries);
2572 static int mov_write_stbl_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
2574 int64_t pos = avio_tell(pb);
2577 avio_wb32(pb, 0); /* size */
2578 ffio_wfourcc(pb, "stbl");
2579 if ((ret = mov_write_stsd_tag(s, pb, mov, track)) < 0)
2581 mov_write_stts_tag(pb, track);
2582 if ((track->par->codec_type == AVMEDIA_TYPE_VIDEO ||
2583 track->par->codec_id == AV_CODEC_ID_TRUEHD ||
2584 track->par->codec_id == AV_CODEC_ID_MPEGH_3D_AUDIO ||
2585 track->par->codec_tag == MKTAG('r','t','p',' ')) &&
2586 track->has_keyframes && track->has_keyframes < track->entry)
2587 mov_write_stss_tag(pb, track, MOV_SYNC_SAMPLE);
2588 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO && track->has_disposable)
2589 mov_write_sdtp_tag(pb, track);
2590 if (track->mode == MODE_MOV && track->flags & MOV_TRACK_STPS)
2591 mov_write_stss_tag(pb, track, MOV_PARTIAL_SYNC_SAMPLE);
2592 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO &&
2593 track->flags & MOV_TRACK_CTTS && track->entry) {
2595 if ((ret = mov_write_ctts_tag(s, pb, track)) < 0)
2598 mov_write_stsc_tag(pb, track);
2599 mov_write_stsz_tag(pb, track);
2600 mov_write_stco_tag(pb, track);
2601 if (track->cenc.aes_ctr) {
2602 ff_mov_cenc_write_stbl_atoms(&track->cenc, pb);
2604 if (track->par->codec_id == AV_CODEC_ID_OPUS || track->par->codec_id == AV_CODEC_ID_AAC) {
2605 mov_preroll_write_stbl_atoms(pb, track);
2607 return update_size(pb, pos);
2610 static int mov_write_dinf_tag(AVIOContext *pb)
2612 int64_t pos = avio_tell(pb);
2613 avio_wb32(pb, 0); /* size */
2614 ffio_wfourcc(pb, "dinf");
2615 mov_write_dref_tag(pb);
2616 return update_size(pb, pos);
2619 static int mov_write_nmhd_tag(AVIOContext *pb)
2622 ffio_wfourcc(pb, "nmhd");
2627 static int mov_write_tcmi_tag(AVIOContext *pb, MOVTrack *track)
2629 int64_t pos = avio_tell(pb);
2630 const char *font = "Lucida Grande";
2631 avio_wb32(pb, 0); /* size */
2632 ffio_wfourcc(pb, "tcmi"); /* timecode media information atom */
2633 avio_wb32(pb, 0); /* version & flags */
2634 avio_wb16(pb, 0); /* text font */
2635 avio_wb16(pb, 0); /* text face */
2636 avio_wb16(pb, 12); /* text size */
2637 avio_wb16(pb, 0); /* (unknown, not in the QT specs...) */
2638 avio_wb16(pb, 0x0000); /* text color (red) */
2639 avio_wb16(pb, 0x0000); /* text color (green) */
2640 avio_wb16(pb, 0x0000); /* text color (blue) */
2641 avio_wb16(pb, 0xffff); /* background color (red) */
2642 avio_wb16(pb, 0xffff); /* background color (green) */
2643 avio_wb16(pb, 0xffff); /* background color (blue) */
2644 avio_w8(pb, strlen(font)); /* font len (part of the pascal string) */
2645 avio_write(pb, font, strlen(font)); /* font name */
2646 return update_size(pb, pos);
2649 static int mov_write_gmhd_tag(AVIOContext *pb, MOVTrack *track)
2651 int64_t pos = avio_tell(pb);
2652 avio_wb32(pb, 0); /* size */
2653 ffio_wfourcc(pb, "gmhd");
2654 avio_wb32(pb, 0x18); /* gmin size */
2655 ffio_wfourcc(pb, "gmin");/* generic media info */
2656 avio_wb32(pb, 0); /* version & flags */
2657 avio_wb16(pb, 0x40); /* graphics mode = */
2658 avio_wb16(pb, 0x8000); /* opColor (r?) */
2659 avio_wb16(pb, 0x8000); /* opColor (g?) */
2660 avio_wb16(pb, 0x8000); /* opColor (b?) */
2661 avio_wb16(pb, 0); /* balance */
2662 avio_wb16(pb, 0); /* reserved */
2665 * This special text atom is required for
2666 * Apple Quicktime chapters. The contents
2667 * don't appear to be documented, so the
2668 * bytes are copied verbatim.
2670 if (track->tag != MKTAG('c','6','0','8')) {
2671 avio_wb32(pb, 0x2C); /* size */
2672 ffio_wfourcc(pb, "text");
2673 avio_wb16(pb, 0x01);
2674 avio_wb32(pb, 0x00);
2675 avio_wb32(pb, 0x00);
2676 avio_wb32(pb, 0x00);
2677 avio_wb32(pb, 0x01);
2678 avio_wb32(pb, 0x00);
2679 avio_wb32(pb, 0x00);
2680 avio_wb32(pb, 0x00);
2681 avio_wb32(pb, 0x00004000);
2682 avio_wb16(pb, 0x0000);
2685 if (track->par->codec_tag == MKTAG('t','m','c','d')) {
2686 int64_t tmcd_pos = avio_tell(pb);
2687 avio_wb32(pb, 0); /* size */
2688 ffio_wfourcc(pb, "tmcd");
2689 mov_write_tcmi_tag(pb, track);
2690 update_size(pb, tmcd_pos);
2691 } else if (track->par->codec_tag == MKTAG('g','p','m','d')) {
2692 int64_t gpmd_pos = avio_tell(pb);
2693 avio_wb32(pb, 0); /* size */
2694 ffio_wfourcc(pb, "gpmd");
2695 avio_wb32(pb, 0); /* version */
2696 update_size(pb, gpmd_pos);
2698 return update_size(pb, pos);
2701 static int mov_write_smhd_tag(AVIOContext *pb)
2703 avio_wb32(pb, 16); /* size */
2704 ffio_wfourcc(pb, "smhd");
2705 avio_wb32(pb, 0); /* version & flags */
2706 avio_wb16(pb, 0); /* reserved (balance, normally = 0) */
2707 avio_wb16(pb, 0); /* reserved */
2711 static int mov_write_vmhd_tag(AVIOContext *pb)
2713 avio_wb32(pb, 0x14); /* size (always 0x14) */
2714 ffio_wfourcc(pb, "vmhd");
2715 avio_wb32(pb, 0x01); /* version & flags */
2716 avio_wb64(pb, 0); /* reserved (graphics mode = copy) */
2720 static int is_clcp_track(MOVTrack *track)
2722 return track->tag == MKTAG('c','7','0','8') ||
2723 track->tag == MKTAG('c','6','0','8');
2726 static int mov_write_hdlr_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
2728 MOVMuxContext *mov = s->priv_data;
2729 const char *hdlr, *descr = NULL, *hdlr_type = NULL;
2730 int64_t pos = avio_tell(pb);
2734 descr = "DataHandler";
2737 hdlr = (track->mode == MODE_MOV) ? "mhlr" : "\0\0\0\0";
2738 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
2740 descr = "VideoHandler";
2741 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
2743 descr = "SoundHandler";
2744 } else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE) {
2745 if (is_clcp_track(track)) {
2747 descr = "ClosedCaptionHandler";
2749 if (track->tag == MKTAG('t','x','3','g')) {
2751 } else if (track->tag == MKTAG('m','p','4','s')) {
2756 descr = "SubtitleHandler";
2758 } else if (track->par->codec_tag == MKTAG('r','t','p',' ')) {
2760 descr = "HintHandler";
2761 } else if (track->par->codec_tag == MKTAG('t','m','c','d')) {
2763 descr = "TimeCodeHandler";
2764 } else if (track->par->codec_tag == MKTAG('g','p','m','d')) {
2766 descr = "GoPro MET"; // GoPro Metadata
2768 av_log(s, AV_LOG_WARNING,
2769 "Unknown hldr_type for %s, writing dummy values\n",
2770 av_fourcc2str(track->par->codec_tag));
2773 // hdlr.name is used by some players to identify the content title
2774 // of the track. So if an alternate handler description is
2775 // specified, use it.
2776 AVDictionaryEntry *t;
2777 t = av_dict_get(track->st->metadata, "handler_name", NULL, 0);
2778 if (t && utf8len(t->value))
2783 if (mov->empty_hdlr_name) /* expressly allowed by QTFF and not prohibited in ISO 14496-12 8.4.3.3 */
2786 avio_wb32(pb, 0); /* size */
2787 ffio_wfourcc(pb, "hdlr");
2788 avio_wb32(pb, 0); /* Version & flags */
2789 avio_write(pb, hdlr, 4); /* handler */
2790 ffio_wfourcc(pb, hdlr_type); /* handler type */
2791 avio_wb32(pb, 0); /* reserved */
2792 avio_wb32(pb, 0); /* reserved */
2793 avio_wb32(pb, 0); /* reserved */
2794 if (!track || track->mode == MODE_MOV)
2795 avio_w8(pb, strlen(descr)); /* pascal string */
2796 avio_write(pb, descr, strlen(descr)); /* handler description */
2797 if (track && track->mode != MODE_MOV)
2798 avio_w8(pb, 0); /* c string */
2799 return update_size(pb, pos);
2802 static int mov_write_hmhd_tag(AVIOContext *pb)
2804 /* This atom must be present, but leaving the values at zero
2805 * seems harmless. */
2806 avio_wb32(pb, 28); /* size */
2807 ffio_wfourcc(pb, "hmhd");
2808 avio_wb32(pb, 0); /* version, flags */
2809 avio_wb16(pb, 0); /* maxPDUsize */
2810 avio_wb16(pb, 0); /* avgPDUsize */
2811 avio_wb32(pb, 0); /* maxbitrate */
2812 avio_wb32(pb, 0); /* avgbitrate */
2813 avio_wb32(pb, 0); /* reserved */
2817 static int mov_write_minf_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
2819 int64_t pos = avio_tell(pb);
2822 avio_wb32(pb, 0); /* size */
2823 ffio_wfourcc(pb, "minf");
2824 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO)
2825 mov_write_vmhd_tag(pb);
2826 else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
2827 mov_write_smhd_tag(pb);
2828 else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE) {
2829 if (track->tag == MKTAG('t','e','x','t') || is_clcp_track(track)) {
2830 mov_write_gmhd_tag(pb, track);
2832 mov_write_nmhd_tag(pb);
2834 } else if (track->tag == MKTAG('r','t','p',' ')) {
2835 mov_write_hmhd_tag(pb);
2836 } else if (track->tag == MKTAG('t','m','c','d')) {
2837 if (track->mode != MODE_MOV)
2838 mov_write_nmhd_tag(pb);
2840 mov_write_gmhd_tag(pb, track);
2841 } else if (track->tag == MKTAG('g','p','m','d')) {
2842 mov_write_gmhd_tag(pb, track);
2844 if (track->mode == MODE_MOV) /* ISO 14496-12 8.4.3.1 specifies hdlr only within mdia or meta boxes */
2845 mov_write_hdlr_tag(s, pb, NULL);
2846 mov_write_dinf_tag(pb);
2847 if ((ret = mov_write_stbl_tag(s, pb, mov, track)) < 0)
2849 return update_size(pb, pos);
2852 static int64_t calc_pts_duration(MOVMuxContext *mov, MOVTrack *track)
2854 if (track->tag == MKTAG('t','m','c','d')) {
2855 // tmcd tracks gets track_duration set in mov_write_moov_tag from
2856 // another track's duration, while the end_pts may be left at zero.
2857 // Calculate the pts duration for that track instead.
2858 return av_rescale(calc_pts_duration(mov, &mov->tracks[track->src_track]),
2859 track->timescale, mov->tracks[track->src_track].timescale);
2861 if (track->end_pts != AV_NOPTS_VALUE &&
2862 track->start_dts != AV_NOPTS_VALUE &&
2863 track->start_cts != AV_NOPTS_VALUE) {
2864 return track->end_pts - (track->start_dts + track->start_cts);
2866 return track->track_duration;
2869 static int mov_write_mdhd_tag(AVIOContext *pb, MOVMuxContext *mov,
2872 int64_t duration = calc_pts_duration(mov, track);
2873 int version = duration < INT32_MAX ? 0 : 1;
2875 if (track->mode == MODE_ISM)
2878 (version == 1) ? avio_wb32(pb, 44) : avio_wb32(pb, 32); /* size */
2879 ffio_wfourcc(pb, "mdhd");
2880 avio_w8(pb, version);
2881 avio_wb24(pb, 0); /* flags */
2883 avio_wb64(pb, track->time);
2884 avio_wb64(pb, track->time);
2886 avio_wb32(pb, track->time); /* creation time */
2887 avio_wb32(pb, track->time); /* modification time */
2889 avio_wb32(pb, track->timescale); /* time scale (sample rate for audio) */
2890 if (!track->entry && mov->mode == MODE_ISM)
2891 (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
2892 else if (!track->entry)
2893 (version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0);
2895 (version == 1) ? avio_wb64(pb, duration) : avio_wb32(pb, duration); /* duration */
2896 avio_wb16(pb, track->language); /* language */
2897 avio_wb16(pb, 0); /* reserved (quality) */
2899 if (version != 0 && track->mode == MODE_MOV) {
2900 av_log(NULL, AV_LOG_ERROR,
2901 "FATAL error, file duration too long for timebase, this file will not be\n"
2902 "playable with QuickTime. Choose a different timebase with "
2903 "-video_track_timescale or a different container format\n");
2909 static int mov_write_mdia_tag(AVFormatContext *s, AVIOContext *pb,
2910 MOVMuxContext *mov, MOVTrack *track)
2912 int64_t pos = avio_tell(pb);
2915 avio_wb32(pb, 0); /* size */
2916 ffio_wfourcc(pb, "mdia");
2917 mov_write_mdhd_tag(pb, mov, track);
2918 mov_write_hdlr_tag(s, pb, track);
2919 if ((ret = mov_write_minf_tag(s, pb, mov, track)) < 0)
2921 return update_size(pb, pos);
2924 /* transformation matrix
2928 static void write_matrix(AVIOContext *pb, int16_t a, int16_t b, int16_t c,
2929 int16_t d, int16_t tx, int16_t ty)
2931 avio_wb32(pb, a << 16); /* 16.16 format */
2932 avio_wb32(pb, b << 16); /* 16.16 format */
2933 avio_wb32(pb, 0); /* u in 2.30 format */
2934 avio_wb32(pb, c << 16); /* 16.16 format */
2935 avio_wb32(pb, d << 16); /* 16.16 format */
2936 avio_wb32(pb, 0); /* v in 2.30 format */
2937 avio_wb32(pb, tx << 16); /* 16.16 format */
2938 avio_wb32(pb, ty << 16); /* 16.16 format */
2939 avio_wb32(pb, 1 << 30); /* w in 2.30 format */
2942 static int mov_write_tkhd_tag(AVIOContext *pb, MOVMuxContext *mov,
2943 MOVTrack *track, AVStream *st)
2945 int64_t duration = av_rescale_rnd(calc_pts_duration(mov, track),
2946 MOV_TIMESCALE, track->timescale,
2948 int version = duration < INT32_MAX ? 0 : 1;
2949 int flags = MOV_TKHD_FLAG_IN_MOVIE;
2953 uint32_t *display_matrix = NULL;
2954 int display_matrix_size, i;
2957 if (mov->per_stream_grouping)
2960 group = st->codecpar->codec_type;
2962 display_matrix = (uint32_t*)av_stream_get_side_data(st, AV_PKT_DATA_DISPLAYMATRIX,
2963 &display_matrix_size);
2964 if (display_matrix && display_matrix_size < 9 * sizeof(*display_matrix))
2965 display_matrix = NULL;
2968 if (track->flags & MOV_TRACK_ENABLED)
2969 flags |= MOV_TKHD_FLAG_ENABLED;
2971 if (track->mode == MODE_ISM)
2974 (version == 1) ? avio_wb32(pb, 104) : avio_wb32(pb, 92); /* size */
2975 ffio_wfourcc(pb, "tkhd");
2976 avio_w8(pb, version);
2977 avio_wb24(pb, flags);
2979 avio_wb64(pb, track->time);
2980 avio_wb64(pb, track->time);
2982 avio_wb32(pb, track->time); /* creation time */
2983 avio_wb32(pb, track->time); /* modification time */
2985 avio_wb32(pb, track->track_id); /* track-id */
2986 avio_wb32(pb, 0); /* reserved */
2987 if (!track->entry && mov->mode == MODE_ISM)
2988 (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
2989 else if (!track->entry)
2990 (version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0);
2992 (version == 1) ? avio_wb64(pb, duration) : avio_wb32(pb, duration);
2994 avio_wb32(pb, 0); /* reserved */
2995 avio_wb32(pb, 0); /* reserved */
2996 avio_wb16(pb, 0); /* layer */
2997 avio_wb16(pb, group); /* alternate group) */
2998 /* Volume, only for audio */
2999 if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
3000 avio_wb16(pb, 0x0100);
3003 avio_wb16(pb, 0); /* reserved */
3005 /* Matrix structure */
3006 #if FF_API_OLD_ROTATE_API
3007 if (st && st->metadata) {
3008 AVDictionaryEntry *rot = av_dict_get(st->metadata, "rotate", NULL, 0);
3009 rotation = (rot && rot->value) ? atoi(rot->value) : 0;
3012 if (display_matrix) {
3013 for (i = 0; i < 9; i++)
3014 avio_wb32(pb, display_matrix[i]);
3015 #if FF_API_OLD_ROTATE_API
3016 } else if (rotation == 90) {
3017 write_matrix(pb, 0, 1, -1, 0, track->par->height, 0);
3018 } else if (rotation == 180) {
3019 write_matrix(pb, -1, 0, 0, -1, track->par->width, track->par->height);
3020 } else if (rotation == 270) {
3021 write_matrix(pb, 0, -1, 1, 0, 0, track->par->width);
3024 write_matrix(pb, 1, 0, 0, 1, 0, 0);
3026 /* Track width and height, for visual only */
3027 if (st && (track->par->codec_type == AVMEDIA_TYPE_VIDEO ||
3028 track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)) {
3029 int64_t track_width_1616;
3030 if (track->mode == MODE_MOV) {
3031 track_width_1616 = track->par->width * 0x10000ULL;
3033 track_width_1616 = av_rescale(st->sample_aspect_ratio.num,
3034 track->par->width * 0x10000LL,
3035 st->sample_aspect_ratio.den);
3036 if (!track_width_1616 ||
3037 track->height != track->par->height ||
3038 track_width_1616 > UINT32_MAX)
3039 track_width_1616 = track->par->width * 0x10000ULL;
3041 if (track_width_1616 > UINT32_MAX) {
3042 av_log(mov->fc, AV_LOG_WARNING, "track width is too large\n");
3043 track_width_1616 = 0;
3045 avio_wb32(pb, track_width_1616);
3046 if (track->height > 0xFFFF) {
3047 av_log(mov->fc, AV_LOG_WARNING, "track height is too large\n");
3050 avio_wb32(pb, track->height * 0x10000U);
3058 static int mov_write_tapt_tag(AVIOContext *pb, MOVTrack *track)
3060 int32_t width = av_rescale(track->par->sample_aspect_ratio.num, track->par->width,
3061 track->par->sample_aspect_ratio.den);
3063 int64_t pos = avio_tell(pb);
3065 avio_wb32(pb, 0); /* size */
3066 ffio_wfourcc(pb, "tapt");
3069 ffio_wfourcc(pb, "clef");
3071 avio_wb32(pb, width << 16);
3072 avio_wb32(pb, track->par->height << 16);
3075 ffio_wfourcc(pb, "prof");
3077 avio_wb32(pb, width << 16);
3078 avio_wb32(pb, track->par->height << 16);
3081 ffio_wfourcc(pb, "enof");
3083 avio_wb32(pb, track->par->width << 16);
3084 avio_wb32(pb, track->par->height << 16);
3086 return update_size(pb, pos);
3089 // This box seems important for the psp playback ... without it the movie seems to hang
3090 static int mov_write_edts_tag(AVIOContext *pb, MOVMuxContext *mov,
3093 int64_t duration = av_rescale_rnd(calc_pts_duration(mov, track),
3094 MOV_TIMESCALE, track->timescale,
3096 int version = duration < INT32_MAX ? 0 : 1;
3097 int entry_size, entry_count, size;
3098 int64_t delay, start_ct = track->start_cts;
3099 int64_t start_dts = track->start_dts;
3102 if (start_dts != track->cluster[0].dts || start_ct != track->cluster[0].cts) {
3104 av_log(mov->fc, AV_LOG_DEBUG,
3105 "EDTS using dts:%"PRId64" cts:%d instead of dts:%"PRId64" cts:%"PRId64" tid:%d\n",
3106 track->cluster[0].dts, track->cluster[0].cts,
3107 start_dts, start_ct, track->track_id);
3108 start_dts = track->cluster[0].dts;
3109 start_ct = track->cluster[0].cts;
3113 delay = av_rescale_rnd(start_dts + start_ct, MOV_TIMESCALE,
3114 track->timescale, AV_ROUND_DOWN);
3115 version |= delay < INT32_MAX ? 0 : 1;
3117 entry_size = (version == 1) ? 20 : 12;
3118 entry_count = 1 + (delay > 0);
3119 size = 24 + entry_count * entry_size;
3121 /* write the atom data */
3122 avio_wb32(pb, size);
3123 ffio_wfourcc(pb, "edts");
3124 avio_wb32(pb, size - 8);
3125 ffio_wfourcc(pb, "elst");
3126 avio_w8(pb, version);
3127 avio_wb24(pb, 0); /* flags */
3129 avio_wb32(pb, entry_count);
3130 if (delay > 0) { /* add an empty edit to delay presentation */
3131 /* In the positive delay case, the delay includes the cts
3132 * offset, and the second edit list entry below trims out
3133 * the same amount from the actual content. This makes sure
3134 * that the offset last sample is included in the edit
3135 * list duration as well. */
3137 avio_wb64(pb, delay);
3140 avio_wb32(pb, delay);
3143 avio_wb32(pb, 0x00010000);
3145 /* Avoid accidentally ending up with start_ct = -1 which has got a
3146 * special meaning. Normally start_ct should end up positive or zero
3147 * here, but use FFMIN in case dts is a small positive integer
3148 * rounded to 0 when represented in MOV_TIMESCALE units. */
3149 av_assert0(av_rescale_rnd(start_dts, MOV_TIMESCALE, track->timescale, AV_ROUND_DOWN) <= 0);
3150 start_ct = -FFMIN(start_dts, 0);
3151 /* Note, this delay is calculated from the pts of the first sample,
3152 * ensuring that we don't reduce the duration for cases with
3157 /* For fragmented files, we don't know the full length yet. Setting
3158 * duration to 0 allows us to only specify the offset, including
3159 * the rest of the content (from all future fragments) without specifying
3160 * an explicit duration. */
3161 if (mov->flags & FF_MOV_FLAG_FRAGMENT)
3166 avio_wb64(pb, duration);
3167 avio_wb64(pb, start_ct);
3169 avio_wb32(pb, duration);
3170 avio_wb32(pb, start_ct);
3172 avio_wb32(pb, 0x00010000);
3176 static int mov_write_tref_tag(AVIOContext *pb, MOVTrack *track)
3178 avio_wb32(pb, 20); // size
3179 ffio_wfourcc(pb, "tref");
3180 avio_wb32(pb, 12); // size (subatom)
3181 avio_wl32(pb, track->tref_tag);
3182 avio_wb32(pb, track->tref_id);
3186 // goes at the end of each track! ... Critical for PSP playback ("Incompatible data" without it)
3187 static int mov_write_uuid_tag_psp(AVIOContext *pb, MOVTrack *mov)
3189 avio_wb32(pb, 0x34); /* size ... reports as 28 in mp4box! */
3190 ffio_wfourcc(pb, "uuid");
3191 ffio_wfourcc(pb, "USMT");
3192 avio_wb32(pb, 0x21d24fce);
3193 avio_wb32(pb, 0xbb88695c);
3194 avio_wb32(pb, 0xfac9c740);
3195 avio_wb32(pb, 0x1c); // another size here!
3196 ffio_wfourcc(pb, "MTDT");
3197 avio_wb32(pb, 0x00010012);
3198 avio_wb32(pb, 0x0a);
3199 avio_wb32(pb, 0x55c40000);
3205 static int mov_write_udta_sdp(AVIOContext *pb, MOVTrack *track)
3207 AVFormatContext *ctx = track->rtp_ctx;
3208 char buf[1000] = "";
3211 ff_sdp_write_media(buf, sizeof(buf), ctx->streams[0], track->src_track,
3212 NULL, NULL, 0, 0, ctx);
3213 av_strlcatf(buf, sizeof(buf), "a=control:streamid=%d\r\n", track->track_id);
3216 avio_wb32(pb, len + 24);
3217 ffio_wfourcc(pb, "udta");
3218 avio_wb32(pb, len + 16);
3219 ffio_wfourcc(pb, "hnti");
3220 avio_wb32(pb, len + 8);
3221 ffio_wfourcc(pb, "sdp ");
3222 avio_write(pb, buf, len);
3226 static int mov_write_track_metadata(AVIOContext *pb, AVStream *st,
3227 const char *tag, const char *str)
3229 int64_t pos = avio_tell(pb);
3230 AVDictionaryEntry *t = av_dict_get(st->metadata, str, NULL, 0);
3231 if (!t || !utf8len(t->value))
3234 avio_wb32(pb, 0); /* size */
3235 ffio_wfourcc(pb, tag); /* type */
3236 avio_write(pb, t->value, strlen(t->value)); /* UTF8 string value */
3237 return update_size(pb, pos);
3240 static int mov_write_track_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
3243 AVIOContext *pb_buf;
3250 ret = avio_open_dyn_buf(&pb_buf);
3254 if (mov->mode & (MODE_MP4|MODE_MOV))
3255 mov_write_track_metadata(pb_buf, st, "name", "title");
3257 if ((size = avio_get_dyn_buf(pb_buf, &buf)) > 0) {
3258 avio_wb32(pb, size + 8);
3259 ffio_wfourcc(pb, "udta");
3260 avio_write(pb, buf, size);
3262 ffio_free_dyn_buf(&pb_buf);
3267 static int mov_write_trak_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov,
3268 MOVTrack *track, AVStream *st)
3270 int64_t pos = avio_tell(pb);
3271 int entry_backup = track->entry;
3272 int chunk_backup = track->chunkCount;
3275 /* If we want to have an empty moov, but some samples already have been
3276 * buffered (delay_moov), pretend that no samples have been written yet. */
3277 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV)
3278 track->chunkCount = track->entry = 0;
3280 avio_wb32(pb, 0); /* size */
3281 ffio_wfourcc(pb, "trak");
3282 mov_write_tkhd_tag(pb, mov, track, st);
3284 av_assert2(mov->use_editlist >= 0);
3286 if (track->start_dts != AV_NOPTS_VALUE) {
3287 if (mov->use_editlist)
3288 mov_write_edts_tag(pb, mov, track); // PSP Movies and several other cases require edts box
3289 else if ((track->entry && track->cluster[0].dts) || track->mode == MODE_PSP || is_clcp_track(track))
3290 av_log(mov->fc, AV_LOG_WARNING,
3291 "Not writing any edit list even though one would have been required\n");
3294 if (track->tref_tag)
3295 mov_write_tref_tag(pb, track);
3297 if ((ret = mov_write_mdia_tag(s, pb, mov, track)) < 0)
3299 if (track->mode == MODE_PSP)
3300 mov_write_uuid_tag_psp(pb, track); // PSP Movies require this uuid box
3301 if (track->tag == MKTAG('r','t','p',' '))
3302 mov_write_udta_sdp(pb, track);
3303 if (track->mode == MODE_MOV) {
3304 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
3305 double sample_aspect_ratio = av_q2d(st->sample_aspect_ratio);
3306 if (st->sample_aspect_ratio.num && 1.0 != sample_aspect_ratio) {
3307 mov_write_tapt_tag(pb, track);
3310 if (is_clcp_track(track) && st->sample_aspect_ratio.num) {
3311 mov_write_tapt_tag(pb, track);
3314 mov_write_track_udta_tag(pb, mov, st);
3315 track->entry = entry_backup;
3316 track->chunkCount = chunk_backup;
3317 return update_size(pb, pos);
3320 static int mov_write_iods_tag(AVIOContext *pb, MOVMuxContext *mov)
3322 int i, has_audio = 0, has_video = 0;
3323 int64_t pos = avio_tell(pb);
3324 int audio_profile = mov->iods_audio_profile;
3325 int video_profile = mov->iods_video_profile;
3326 for (i = 0; i < mov->nb_streams; i++) {
3327 if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
3328 has_audio |= mov->tracks[i].par->codec_type == AVMEDIA_TYPE_AUDIO;
3329 has_video |= mov->tracks[i].par->codec_type == AVMEDIA_TYPE_VIDEO;
3332 if (audio_profile < 0)
3333 audio_profile = 0xFF - has_audio;
3334 if (video_profile < 0)
3335 video_profile = 0xFF - has_video;
3336 avio_wb32(pb, 0x0); /* size */
3337 ffio_wfourcc(pb, "iods");
3338 avio_wb32(pb, 0); /* version & flags */
3339 put_descr(pb, 0x10, 7);
3340 avio_wb16(pb, 0x004f);
3343 avio_w8(pb, audio_profile);
3344 avio_w8(pb, video_profile);
3346 return update_size(pb, pos);
3349 static int mov_write_trex_tag(AVIOContext *pb, MOVTrack *track)
3351 avio_wb32(pb, 0x20); /* size */
3352 ffio_wfourcc(pb, "trex");
3353 avio_wb32(pb, 0); /* version & flags */
3354 avio_wb32(pb, track->track_id); /* track ID */
3355 avio_wb32(pb, 1); /* default sample description index */
3356 avio_wb32(pb, 0); /* default sample duration */
3357 avio_wb32(pb, 0); /* default sample size */
3358 avio_wb32(pb, 0); /* default sample flags */
3362 static int mov_write_mvex_tag(AVIOContext *pb, MOVMuxContext *mov)
3364 int64_t pos = avio_tell(pb);
3366 avio_wb32(pb, 0x0); /* size */
3367 ffio_wfourcc(pb, "mvex");
3368 for (i = 0; i < mov->nb_streams; i++)
3369 mov_write_trex_tag(pb, &mov->tracks[i]);
3370 return update_size(pb, pos);
3373 static int mov_write_mvhd_tag(AVIOContext *pb, MOVMuxContext *mov)
3375 int max_track_id = 1, i;
3376 int64_t max_track_len = 0;
3379 for (i = 0; i < mov->nb_streams; i++) {
3380 if (mov->tracks[i].entry > 0 && mov->tracks[i].timescale) {
3381 int64_t max_track_len_temp = av_rescale_rnd(
3382 calc_pts_duration(mov, &mov->tracks[i]),
3384 mov->tracks[i].timescale,
3386 if (max_track_len < max_track_len_temp)
3387 max_track_len = max_track_len_temp;
3388 if (max_track_id < mov->tracks[i].track_id)
3389 max_track_id = mov->tracks[i].track_id;
3392 /* If using delay_moov, make sure the output is the same as if no
3393 * samples had been written yet. */
3394 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
3399 version = max_track_len < UINT32_MAX ? 0 : 1;
3400 avio_wb32(pb, version == 1 ? 120 : 108); /* size */
3402 ffio_wfourcc(pb, "mvhd");
3403 avio_w8(pb, version);
3404 avio_wb24(pb, 0); /* flags */
3406 avio_wb64(pb, mov->time);
3407 avio_wb64(pb, mov->time);
3409 avio_wb32(pb, mov->time); /* creation time */
3410 avio_wb32(pb, mov->time); /* modification time */
3412 avio_wb32(pb, MOV_TIMESCALE);
3413 (version == 1) ? avio_wb64(pb, max_track_len) : avio_wb32(pb, max_track_len); /* duration of longest track */
3415 avio_wb32(pb, 0x00010000); /* reserved (preferred rate) 1.0 = normal */
3416 avio_wb16(pb, 0x0100); /* reserved (preferred volume) 1.0 = normal */
3417 avio_wb16(pb, 0); /* reserved */
3418 avio_wb32(pb, 0); /* reserved */
3419 avio_wb32(pb, 0); /* reserved */
3421 /* Matrix structure */
3422 write_matrix(pb, 1, 0, 0, 1, 0, 0);
3424 avio_wb32(pb, 0); /* reserved (preview time) */
3425 avio_wb32(pb, 0); /* reserved (preview duration) */
3426 avio_wb32(pb, 0); /* reserved (poster time) */
3427 avio_wb32(pb, 0); /* reserved (selection time) */
3428 avio_wb32(pb, 0); /* reserved (selection duration) */
3429 avio_wb32(pb, 0); /* reserved (current time) */
3430 avio_wb32(pb, max_track_id + 1); /* Next track id */
3434 static int mov_write_itunes_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov,
3437 avio_wb32(pb, 33); /* size */
3438 ffio_wfourcc(pb, "hdlr");
3441 ffio_wfourcc(pb, "mdir");
3442 ffio_wfourcc(pb, "appl");
3449 /* helper function to write a data tag with the specified string as data */
3450 static int mov_write_string_data_tag(AVIOContext *pb, const char *data, int lang, int long_style)
3453 int size = 16 + strlen(data);
3454 avio_wb32(pb, size); /* size */
3455 ffio_wfourcc(pb, "data");
3458 avio_write(pb, data, strlen(data));
3462 lang = ff_mov_iso639_to_lang("und", 1);
3463 avio_wb16(pb, strlen(data)); /* string length */
3464 avio_wb16(pb, lang);
3465 avio_write(pb, data, strlen(data));
3466 return strlen(data) + 4;
3470 static int mov_write_string_tag(AVIOContext *pb, const char *name,
3471 const char *value, int lang, int long_style)
3474 if (value && value[0]) {
3475 int64_t pos = avio_tell(pb);
3476 avio_wb32(pb, 0); /* size */
3477 ffio_wfourcc(pb, name);
3478 mov_write_string_data_tag(pb, value, lang, long_style);
3479 size = update_size(pb, pos);
3484 static AVDictionaryEntry *get_metadata_lang(AVFormatContext *s,
3485 const char *tag, int *lang)
3488 AVDictionaryEntry *t, *t2 = NULL;
3493 if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
3496 len = strlen(t->key);
3497 snprintf(tag2, sizeof(tag2), "%s-", tag);
3498 while ((t2 = av_dict_get(s->metadata, tag2, t2, AV_DICT_IGNORE_SUFFIX))) {
3499 len2 = strlen(t2->key);
3500 if (len2 == len + 4 && !strcmp(t->value, t2->value)
3501 && (l = ff_mov_iso639_to_lang(&t2->key[len2 - 3], 1)) >= 0) {
3509 static int mov_write_string_metadata(AVFormatContext *s, AVIOContext *pb,
3510 const char *name, const char *tag,
3514 AVDictionaryEntry *t = get_metadata_lang(s, tag, &lang);
3517 return mov_write_string_tag(pb, name, t->value, lang, long_style);
3520 /* iTunes bpm number */
3521 static int mov_write_tmpo_tag(AVIOContext *pb, AVFormatContext *s)
3523 AVDictionaryEntry *t = av_dict_get(s->metadata, "tmpo", NULL, 0);
3524 int size = 0, tmpo = t ? atoi(t->value) : 0;
3527 avio_wb32(pb, size);
3528 ffio_wfourcc(pb, "tmpo");
3529 avio_wb32(pb, size-8); /* size */
3530 ffio_wfourcc(pb, "data");
3531 avio_wb32(pb, 0x15); //type specifier
3533 avio_wb16(pb, tmpo); // data
3538 /* 3GPP TS 26.244 */
3539 static int mov_write_loci_tag(AVFormatContext *s, AVIOContext *pb)
3542 int64_t pos = avio_tell(pb);
3543 double latitude, longitude, altitude;
3544 int32_t latitude_fix, longitude_fix, altitude_fix;
3545 AVDictionaryEntry *t = get_metadata_lang(s, "location", &lang);
3546 const char *ptr, *place = "";
3548 static const char *astronomical_body = "earth";
3553 longitude = strtod(ptr, &end);
3555 av_log(s, AV_LOG_WARNING, "malformed location metadata\n");
3559 latitude = strtod(ptr, &end);
3561 av_log(s, AV_LOG_WARNING, "malformed location metadata\n");
3565 altitude = strtod(ptr, &end);
3566 /* If no altitude was present, the default 0 should be fine */
3570 latitude_fix = (int32_t) ((1 << 16) * latitude);
3571 longitude_fix = (int32_t) ((1 << 16) * longitude);
3572 altitude_fix = (int32_t) ((1 << 16) * altitude);
3574 avio_wb32(pb, 0); /* size */
3575 ffio_wfourcc(pb, "loci"); /* type */
3576 avio_wb32(pb, 0); /* version + flags */
3577 avio_wb16(pb, lang);
3578 avio_write(pb, place, strlen(place) + 1);
3579 avio_w8(pb, 0); /* role of place (0 == shooting location, 1 == real location, 2 == fictional location) */
3580 avio_wb32(pb, latitude_fix);
3581 avio_wb32(pb, longitude_fix);
3582 avio_wb32(pb, altitude_fix);
3583 avio_write(pb, astronomical_body, strlen(astronomical_body) + 1);
3584 avio_w8(pb, 0); /* additional notes, null terminated string */
3586 return update_size(pb, pos);
3589 /* iTunes track or disc number */
3590 static int mov_write_trkn_tag(AVIOContext *pb, MOVMuxContext *mov,
3591 AVFormatContext *s, int disc)
3593 AVDictionaryEntry *t = av_dict_get(s->metadata,
3594 disc ? "disc" : "track",
3596 int size = 0, track = t ? atoi(t->value) : 0;
3599 char *slash = strchr(t->value, '/');
3601 tracks = atoi(slash + 1);
3602 avio_wb32(pb, 32); /* size */
3603 ffio_wfourcc(pb, disc ? "disk" : "trkn");
3604 avio_wb32(pb, 24); /* size */
3605 ffio_wfourcc(pb, "data");
3606 avio_wb32(pb, 0); // 8 bytes empty
3608 avio_wb16(pb, 0); // empty
3609 avio_wb16(pb, track); // track / disc number
3610 avio_wb16(pb, tracks); // total track / disc number
3611 avio_wb16(pb, 0); // empty
3617 static int mov_write_int8_metadata(AVFormatContext *s, AVIOContext *pb,
3618 const char *name, const char *tag,
3621 AVDictionaryEntry *t = NULL;
3623 int size = 24 + len;
3625 if (len != 1 && len != 4)
3628 if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
3630 num = atoi(t->value);
3632 avio_wb32(pb, size);
3633 ffio_wfourcc(pb, name);
3634 avio_wb32(pb, size - 8);
3635 ffio_wfourcc(pb, "data");
3636 avio_wb32(pb, 0x15);
3638 if (len==4) avio_wb32(pb, num);
3639 else avio_w8 (pb, num);
3644 static int mov_write_covr(AVIOContext *pb, AVFormatContext *s)
3646 MOVMuxContext *mov = s->priv_data;
3650 for (i = 0; i < s->nb_streams; i++) {
3651 MOVTrack *trk = &mov->tracks[i];
3653 if (!is_cover_image(trk->st) || trk->cover_image.size <= 0)
3657 pos = avio_tell(pb);
3659 ffio_wfourcc(pb, "covr");
3661 avio_wb32(pb, 16 + trk->cover_image.size);
3662 ffio_wfourcc(pb, "data");
3663 avio_wb32(pb, trk->tag);
3665 avio_write(pb, trk->cover_image.data, trk->cover_image.size);
3668 return pos ? update_size(pb, pos) : 0;
3671 /* iTunes meta data list */
3672 static int mov_write_ilst_tag(AVIOContext *pb, MOVMuxContext *mov,
3675 int64_t pos = avio_tell(pb);
3676 avio_wb32(pb, 0); /* size */
3677 ffio_wfourcc(pb, "ilst");
3678 mov_write_string_metadata(s, pb, "\251nam", "title" , 1);
3679 mov_write_string_metadata(s, pb, "\251ART", "artist" , 1);
3680 mov_write_string_metadata(s, pb, "aART", "album_artist", 1);
3681 mov_write_string_metadata(s, pb, "\251wrt", "composer" , 1);
3682 mov_write_string_metadata(s, pb, "\251alb", "album" , 1);
3683 mov_write_string_metadata(s, pb, "\251day", "date" , 1);
3684 if (!mov_write_string_metadata(s, pb, "\251too", "encoding_tool", 1)) {
3685 if (!(s->flags & AVFMT_FLAG_BITEXACT))
3686 mov_write_string_tag(pb, "\251too", LIBAVFORMAT_IDENT, 0, 1);
3688 mov_write_string_metadata(s, pb, "\251cmt", "comment" , 1);
3689 mov_write_string_metadata(s, pb, "\251gen", "genre" , 1);
3690 mov_write_string_metadata(s, pb, "cprt", "copyright", 1);
3691 mov_write_string_metadata(s, pb, "\251grp", "grouping" , 1);
3692 mov_write_string_metadata(s, pb, "\251lyr", "lyrics" , 1);
3693 mov_write_string_metadata(s, pb, "desc", "description",1);
3694 mov_write_string_metadata(s, pb, "ldes", "synopsis" , 1);
3695 mov_write_string_metadata(s, pb, "tvsh", "show" , 1);
3696 mov_write_string_metadata(s, pb, "tven", "episode_id",1);
3697 mov_write_string_metadata(s, pb, "tvnn", "network" , 1);
3698 mov_write_string_metadata(s, pb, "keyw", "keywords" , 1);
3699 mov_write_int8_metadata (s, pb, "tves", "episode_sort",4);
3700 mov_write_int8_metadata (s, pb, "tvsn", "season_number",4);
3701 mov_write_int8_metadata (s, pb, "stik", "media_type",1);
3702 mov_write_int8_metadata (s, pb, "hdvd", "hd_video", 1);
3703 mov_write_int8_metadata (s, pb, "pgap", "gapless_playback",1);
3704 mov_write_int8_metadata (s, pb, "cpil", "compilation", 1);
3705 mov_write_covr(pb, s);
3706 mov_write_trkn_tag(pb, mov, s, 0); // track number
3707 mov_write_trkn_tag(pb, mov, s, 1); // disc number
3708 mov_write_tmpo_tag(pb, s);
3709 return update_size(pb, pos);
3712 static int mov_write_mdta_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov,
3715 avio_wb32(pb, 33); /* size */
3716 ffio_wfourcc(pb, "hdlr");
3719 ffio_wfourcc(pb, "mdta");
3727 static int mov_write_mdta_keys_tag(AVIOContext *pb, MOVMuxContext *mov,
3730 AVDictionaryEntry *t = NULL;
3731 int64_t pos = avio_tell(pb);
3732 int64_t curpos, entry_pos;
3735 avio_wb32(pb, 0); /* size */
3736 ffio_wfourcc(pb, "keys");
3738 entry_pos = avio_tell(pb);
3739 avio_wb32(pb, 0); /* entry count */
3741 while (t = av_dict_get(s->metadata, "", t, AV_DICT_IGNORE_SUFFIX)) {
3742 avio_wb32(pb, strlen(t->key) + 8);
3743 ffio_wfourcc(pb, "mdta");
3744 avio_write(pb, t->key, strlen(t->key));
3747 curpos = avio_tell(pb);
3748 avio_seek(pb, entry_pos, SEEK_SET);
3749 avio_wb32(pb, count); // rewrite entry count
3750 avio_seek(pb, curpos, SEEK_SET);
3752 return update_size(pb, pos);
3755 static int mov_write_mdta_ilst_tag(AVIOContext *pb, MOVMuxContext *mov,
3758 AVDictionaryEntry *t = NULL;
3759 int64_t pos = avio_tell(pb);
3760 int count = 1; /* keys are 1-index based */
3762 avio_wb32(pb, 0); /* size */
3763 ffio_wfourcc(pb, "ilst");
3765 while (t = av_dict_get(s->metadata, "", t, AV_DICT_IGNORE_SUFFIX)) {
3766 int64_t entry_pos = avio_tell(pb);
3767 avio_wb32(pb, 0); /* size */
3768 avio_wb32(pb, count); /* key */
3769 mov_write_string_data_tag(pb, t->value, 0, 1);
3770 update_size(pb, entry_pos);
3773 return update_size(pb, pos);
3776 /* meta data tags */
3777 static int mov_write_meta_tag(AVIOContext *pb, MOVMuxContext *mov,
3781 int64_t pos = avio_tell(pb);
3782 avio_wb32(pb, 0); /* size */
3783 ffio_wfourcc(pb, "meta");
3785 if (mov->flags & FF_MOV_FLAG_USE_MDTA) {
3786 mov_write_mdta_hdlr_tag(pb, mov, s);
3787 mov_write_mdta_keys_tag(pb, mov, s);
3788 mov_write_mdta_ilst_tag(pb, mov, s);
3791 /* iTunes metadata tag */
3792 mov_write_itunes_hdlr_tag(pb, mov, s);
3793 mov_write_ilst_tag(pb, mov, s);
3795 size = update_size(pb, pos);
3799 static int mov_write_raw_metadata_tag(AVFormatContext *s, AVIOContext *pb,
3800 const char *name, const char *key)
3803 AVDictionaryEntry *t;
3805 if (!(t = av_dict_get(s->metadata, key, NULL, 0)))
3808 len = strlen(t->value);
3811 avio_wb32(pb, size);
3812 ffio_wfourcc(pb, name);
3813 avio_write(pb, t->value, len);
3819 static int ascii_to_wc(AVIOContext *pb, const uint8_t *b)
3823 GET_UTF8(val, *b++, return -1;)
3826 avio_wb16(pb, 0x00);
3830 static uint16_t language_code(const char *str)
3832 return (((str[0] - 0x60) & 0x1F) << 10) +
3833 (((str[1] - 0x60) & 0x1F) << 5) +
3834 (( str[2] - 0x60) & 0x1F);
3837 static int mov_write_3gp_udta_tag(AVIOContext *pb, AVFormatContext *s,
3838 const char *tag, const char *str)
3840 int64_t pos = avio_tell(pb);
3841 AVDictionaryEntry *t = av_dict_get(s->metadata, str, NULL, 0);
3842 if (!t || !utf8len(t->value))
3844 avio_wb32(pb, 0); /* size */
3845 ffio_wfourcc(pb, tag); /* type */
3846 avio_wb32(pb, 0); /* version + flags */
3847 if (!strcmp(tag, "yrrc"))
3848 avio_wb16(pb, atoi(t->value));
3850 avio_wb16(pb, language_code("eng")); /* language */
3851 avio_write(pb, t->value, strlen(t->value) + 1); /* UTF8 string value */
3852 if (!strcmp(tag, "albm") &&
3853 (t = av_dict_get(s->metadata, "track", NULL, 0)))
3854 avio_w8(pb, atoi(t->value));
3856 return update_size(pb, pos);
3859 static int mov_write_chpl_tag(AVIOContext *pb, AVFormatContext *s)
3861 int64_t pos = avio_tell(pb);
3862 int i, nb_chapters = FFMIN(s->nb_chapters, 255);
3864 avio_wb32(pb, 0); // size
3865 ffio_wfourcc(pb, "chpl");
3866 avio_wb32(pb, 0x01000000); // version + flags
3867 avio_wb32(pb, 0); // unknown
3868 avio_w8(pb, nb_chapters);
3870 for (i = 0; i < nb_chapters; i++) {
3871 AVChapter *c = s->chapters[i];
3872 AVDictionaryEntry *t;
3873 avio_wb64(pb, av_rescale_q(c->start, c->time_base, (AVRational){1,10000000}));
3875 if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
3876 int len = FFMIN(strlen(t->value), 255);
3878 avio_write(pb, t->value, len);
3882 return update_size(pb, pos);
3885 static int mov_write_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
3888 AVIOContext *pb_buf;
3892 ret = avio_open_dyn_buf(&pb_buf);
3896 if (mov->mode & MODE_3GP) {
3897 mov_write_3gp_udta_tag(pb_buf, s, "perf", "artist");
3898 mov_write_3gp_udta_tag(pb_buf, s, "titl", "title");
3899 mov_write_3gp_udta_tag(pb_buf, s, "auth", "author");
3900 mov_write_3gp_udta_tag(pb_buf, s, "gnre", "genre");
3901 mov_write_3gp_udta_tag(pb_buf, s, "dscp", "comment");
3902 mov_write_3gp_udta_tag(pb_buf, s, "albm", "album");
3903 mov_write_3gp_udta_tag(pb_buf, s, "cprt", "copyright");
3904 mov_write_3gp_udta_tag(pb_buf, s, "yrrc", "date");
3905 mov_write_loci_tag(s, pb_buf);
3906 } 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
3907 mov_write_string_metadata(s, pb_buf, "\251ART", "artist", 0);
3908 mov_write_string_metadata(s, pb_buf, "\251nam", "title", 0);
3909 mov_write_string_metadata(s, pb_buf, "\251aut", "author", 0);
3910 mov_write_string_metadata(s, pb_buf, "\251alb", "album", 0);
3911 mov_write_string_metadata(s, pb_buf, "\251day", "date", 0);
3912 mov_write_string_metadata(s, pb_buf, "\251swr", "encoder", 0);
3913 // currently ignored by mov.c
3914 mov_write_string_metadata(s, pb_buf, "\251des", "comment", 0);
3915 // add support for libquicktime, this atom is also actually read by mov.c
3916 mov_write_string_metadata(s, pb_buf, "\251cmt", "comment", 0);
3917 mov_write_string_metadata(s, pb_buf, "\251gen", "genre", 0);
3918 mov_write_string_metadata(s, pb_buf, "\251cpy", "copyright", 0);
3919 mov_write_string_metadata(s, pb_buf, "\251mak", "make", 0);
3920 mov_write_string_metadata(s, pb_buf, "\251mod", "model", 0);
3921 mov_write_string_metadata(s, pb_buf, "\251xyz", "location", 0);
3922 mov_write_string_metadata(s, pb_buf, "\251key", "keywords", 0);
3923 mov_write_raw_metadata_tag(s, pb_buf, "XMP_", "xmp");
3925 /* iTunes meta data */
3926 mov_write_meta_tag(pb_buf, mov, s);
3927 mov_write_loci_tag(s, pb_buf);
3930 if (s->nb_chapters && !(mov->flags & FF_MOV_FLAG_DISABLE_CHPL))
3931 mov_write_chpl_tag(pb_buf, s);
3933 if ((size = avio_get_dyn_buf(pb_buf, &buf)) > 0) {
3934 avio_wb32(pb, size + 8);
3935 ffio_wfourcc(pb, "udta");
3936 avio_write(pb, buf, size);
3938 ffio_free_dyn_buf(&pb_buf);
3943 static void mov_write_psp_udta_tag(AVIOContext *pb,
3944 const char *str, const char *lang, int type)
3946 int len = utf8len(str) + 1;
3949 avio_wb16(pb, len * 2 + 10); /* size */
3950 avio_wb32(pb, type); /* type */
3951 avio_wb16(pb, language_code(lang)); /* language */
3952 avio_wb16(pb, 0x01); /* ? */
3953 ascii_to_wc(pb, str);
3956 static int mov_write_uuidusmt_tag(AVIOContext *pb, AVFormatContext *s)
3958 AVDictionaryEntry *title = av_dict_get(s->metadata, "title", NULL, 0);
3962 pos = avio_tell(pb);
3963 avio_wb32(pb, 0); /* size placeholder*/
3964 ffio_wfourcc(pb, "uuid");
3965 ffio_wfourcc(pb, "USMT");
3966 avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
3967 avio_wb32(pb, 0xbb88695c);
3968 avio_wb32(pb, 0xfac9c740);
3970 pos2 = avio_tell(pb);
3971 avio_wb32(pb, 0); /* size placeholder*/
3972 ffio_wfourcc(pb, "MTDT");
3976 avio_wb16(pb, 0x0C); /* size */
3977 avio_wb32(pb, 0x0B); /* type */
3978 avio_wb16(pb, language_code("und")); /* language */
3979 avio_wb16(pb, 0x0); /* ? */
3980 avio_wb16(pb, 0x021C); /* data */
3982 if (!(s->flags & AVFMT_FLAG_BITEXACT))
3983 mov_write_psp_udta_tag(pb, LIBAVCODEC_IDENT, "eng", 0x04);
3984 mov_write_psp_udta_tag(pb, title->value, "eng", 0x01);
3985 mov_write_psp_udta_tag(pb, "2006/04/01 11:11:11", "und", 0x03);
3987 update_size(pb, pos2);
3988 return update_size(pb, pos);
3994 static void build_chunks(MOVTrack *trk)
3997 MOVIentry *chunk = &trk->cluster[0];
3998 uint64_t chunkSize = chunk->size;
3999 chunk->chunkNum = 1;
4000 if (trk->chunkCount)
4002 trk->chunkCount = 1;
4003 for (i = 1; i<trk->entry; i++){
4004 if (chunk->pos + chunkSize == trk->cluster[i].pos &&
4005 chunkSize + trk->cluster[i].size < (1<<20)){
4006 chunkSize += trk->cluster[i].size;
4007 chunk->samples_in_chunk += trk->cluster[i].entries;
4009 trk->cluster[i].chunkNum = chunk->chunkNum+1;
4010 chunk=&trk->cluster[i];
4011 chunkSize = chunk->size;
4018 * Assign track ids. If option "use_stream_ids_as_track_ids" is set,
4019 * the stream ids are used as track ids.
4021 * This assumes mov->tracks and s->streams are in the same order and
4022 * there are no gaps in either of them (so mov->tracks[n] refers to
4025 * As an exception, there can be more entries in
4026 * s->streams than in mov->tracks, in which case new track ids are
4027 * generated (starting after the largest found stream id).
4029 static int mov_setup_track_ids(MOVMuxContext *mov, AVFormatContext *s)
4033 if (mov->track_ids_ok)
4036 if (mov->use_stream_ids_as_track_ids) {
4037 int next_generated_track_id = 0;
4038 for (i = 0; i < s->nb_streams; i++) {
4039 if (s->streams[i]->id > next_generated_track_id)
4040 next_generated_track_id = s->streams[i]->id;
4043 for (i = 0; i < mov->nb_streams; i++) {
4044 if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
4047 mov->tracks[i].track_id = i >= s->nb_streams ? ++next_generated_track_id : s->streams[i]->id;
4050 for (i = 0; i < mov->nb_streams; i++) {
4051 if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
4054 mov->tracks[i].track_id = i + 1;
4058 mov->track_ids_ok = 1;
4063 static int mov_write_moov_tag(AVIOContext *pb, MOVMuxContext *mov,
4067 int64_t pos = avio_tell(pb);
4068 avio_wb32(pb, 0); /* size placeholder*/
4069 ffio_wfourcc(pb, "moov");
4071 mov_setup_track_ids(mov, s);
4073 for (i = 0; i < mov->nb_streams; i++) {
4074 if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
4077 mov->tracks[i].time = mov->time;
4079 if (mov->tracks[i].entry)
4080 build_chunks(&mov->tracks[i]);
4083 if (mov->chapter_track)
4084 for (i = 0; i < s->nb_streams; i++) {
4085 mov->tracks[i].tref_tag = MKTAG('c','h','a','p');
4086 mov->tracks[i].tref_id = mov->tracks[mov->chapter_track].track_id;
4088 for (i = 0; i < mov->nb_streams; i++) {
4089 MOVTrack *track = &mov->tracks[i];
4090 if (track->tag == MKTAG('r','t','p',' ')) {
4091 track->tref_tag = MKTAG('h','i','n','t');
4092 track->tref_id = mov->tracks[track->src_track].track_id;
4093 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
4094 int * fallback, size;
4095 fallback = (int*)av_stream_get_side_data(track->st,
4096 AV_PKT_DATA_FALLBACK_TRACK,
4098 if (fallback != NULL && size == sizeof(int)) {
4099 if (*fallback >= 0 && *fallback < mov->nb_streams) {
4100 track->tref_tag = MKTAG('f','a','l','l');
4101 track->tref_id = mov->tracks[*fallback].track_id;
4106 for (i = 0; i < mov->nb_streams; i++) {
4107 if (mov->tracks[i].tag == MKTAG('t','m','c','d')) {
4108 int src_trk = mov->tracks[i].src_track;
4109 mov->tracks[src_trk].tref_tag = mov->tracks[i].tag;
4110 mov->tracks[src_trk].tref_id = mov->tracks[i].track_id;
4111 //src_trk may have a different timescale than the tmcd track
4112 mov->tracks[i].track_duration = av_rescale(mov->tracks[src_trk].track_duration,
4113 mov->tracks[i].timescale,
4114 mov->tracks[src_trk].timescale);
4118 mov_write_mvhd_tag(pb, mov);
4119 if (mov->mode != MODE_MOV && !mov->iods_skip)
4120 mov_write_iods_tag(pb, mov);
4121 for (i = 0; i < mov->nb_streams; i++) {
4122 if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_FRAGMENT) {
4123 int ret = mov_write_trak_tag(s, pb, mov, &(mov->tracks[i]), i < s->nb_streams ? s->streams[i] : NULL);
4128 if (mov->flags & FF_MOV_FLAG_FRAGMENT)
4129 mov_write_mvex_tag(pb, mov); /* QuickTime requires trak to precede this */
4131 if (mov->mode == MODE_PSP)
4132 mov_write_uuidusmt_tag(pb, s);
4134 mov_write_udta_tag(pb, mov, s);
4136 return update_size(pb, pos);
4139 static void param_write_int(AVIOContext *pb, const char *name, int value)
4141 avio_printf(pb, "<param name=\"%s\" value=\"%d\" valuetype=\"data\"/>\n", name, value);
4144 static void param_write_string(AVIOContext *pb, const char *name, const char *value)
4146 avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, value);
4149 static void param_write_hex(AVIOContext *pb, const char *name, const uint8_t *value, int len)
4152 len = FFMIN(sizeof(buf) / 2 - 1, len);
4153 ff_data_to_hex(buf, value, len, 0);
4154 buf[2 * len] = '\0';
4155 avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, buf);
4158 static int mov_write_isml_manifest(AVIOContext *pb, MOVMuxContext *mov, AVFormatContext *s)
4160 int64_t pos = avio_tell(pb);
4162 int64_t manifest_bit_rate = 0;
4164 static const uint8_t uuid[] = {
4165 0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd,
4166 0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66
4170 ffio_wfourcc(pb, "uuid");
4171 avio_write(pb, uuid, sizeof(uuid));
4174 avio_printf(pb, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
4175 avio_printf(pb, "<smil xmlns=\"http://www.w3.org/2001/SMIL20/Language\">\n");
4176 avio_printf(pb, "<head>\n");
4177 if (!(mov->fc->flags & AVFMT_FLAG_BITEXACT))
4178 avio_printf(pb, "<meta name=\"creator\" content=\"%s\" />\n",
4180 avio_printf(pb, "</head>\n");
4181 avio_printf(pb, "<body>\n");
4182 avio_printf(pb, "<switch>\n");
4184 mov_setup_track_ids(mov, s);
4186 for (i = 0; i < mov->nb_streams; i++) {
4187 MOVTrack *track = &mov->tracks[i];
4188 struct mpeg4_bit_rate_values bit_rates =
4189 calculate_mpeg4_bit_rates(track);
4191 int track_id = track->track_id;
4192 char track_name_buf[32] = { 0 };
4194 AVStream *st = track->st;
4195 AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0);
4197 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO && !is_cover_image(st)) {
4199 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
4205 if (track->par->bit_rate) {
4206 manifest_bit_rate = track->par->bit_rate;
4208 manifest_bit_rate = bit_rates.max_bit_rate;
4211 avio_printf(pb, "<%s systemBitrate=\"%"PRId64"\">\n", type,
4213 param_write_int(pb, "systemBitrate", manifest_bit_rate);
4214 param_write_int(pb, "trackID", track_id);
4215 param_write_string(pb, "systemLanguage", lang ? lang->value : "und");
4217 /* Build track name piece by piece: */
4219 av_strlcat(track_name_buf, type, sizeof(track_name_buf));
4220 /* 2. track language, if available */
4222 av_strlcatf(track_name_buf, sizeof(track_name_buf),
4223 "_%s", lang->value);
4224 /* 3. special type suffix */
4225 /* "_cc" = closed captions, "_ad" = audio_description */
4226 if (st->disposition & AV_DISPOSITION_HEARING_IMPAIRED)
4227 av_strlcat(track_name_buf, "_cc", sizeof(track_name_buf));
4228 else if (st->disposition & AV_DISPOSITION_VISUAL_IMPAIRED)
4229 av_strlcat(track_name_buf, "_ad", sizeof(track_name_buf));
4231 param_write_string(pb, "trackName", track_name_buf);
4233 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
4234 if (track->par->codec_id == AV_CODEC_ID_H264) {
4236 int size = track->par->extradata_size;
4237 if (!ff_avc_write_annexb_extradata(track->par->extradata, &ptr,
4239 param_write_hex(pb, "CodecPrivateData",
4240 ptr ? ptr : track->par->extradata,
4244 param_write_string(pb, "FourCC", "H264");
4245 } else if (track->par->codec_id == AV_CODEC_ID_VC1) {
4246 param_write_string(pb, "FourCC", "WVC1");
4247 param_write_hex(pb, "CodecPrivateData", track->par->extradata,
4248 track->par->extradata_size);
4250 param_write_int(pb, "MaxWidth", track->par->width);
4251 param_write_int(pb, "MaxHeight", track->par->height);
4252 param_write_int(pb, "DisplayWidth", track->par->width);
4253 param_write_int(pb, "DisplayHeight", track->par->height);
4255 if (track->par->codec_id == AV_CODEC_ID_AAC) {
4256 switch (track->par->profile)
4258 case FF_PROFILE_AAC_HE_V2:
4259 param_write_string(pb, "FourCC", "AACP");
4261 case FF_PROFILE_AAC_HE:
4262 param_write_string(pb, "FourCC", "AACH");
4265 param_write_string(pb, "FourCC", "AACL");
4267 } else if (track->par->codec_id == AV_CODEC_ID_WMAPRO) {
4268 param_write_string(pb, "FourCC", "WMAP");
4270 param_write_hex(pb, "CodecPrivateData", track->par->extradata,
4271 track->par->extradata_size);
4272 param_write_int(pb, "AudioTag", ff_codec_get_tag(ff_codec_wav_tags,
4273 track->par->codec_id));
4274 param_write_int(pb, "Channels", track->par->channels);
4275 param_write_int(pb, "SamplingRate", track->par->sample_rate);
4276 param_write_int(pb, "BitsPerSample", 16);
4277 param_write_int(pb, "PacketSize", track->par->block_align ?
4278 track->par->block_align : 4);
4280 avio_printf(pb, "</%s>\n", type);
4282 avio_printf(pb, "</switch>\n");
4283 avio_printf(pb, "</body>\n");
4284 avio_printf(pb, "</smil>\n");
4286 return update_size(pb, pos);
4289 static int mov_write_mfhd_tag(AVIOContext *pb, MOVMuxContext *mov)
4292 ffio_wfourcc(pb, "mfhd");
4294 avio_wb32(pb, mov->fragments);
4298 static uint32_t get_sample_flags(MOVTrack *track, MOVIentry *entry)
4300 return entry->flags & MOV_SYNC_SAMPLE ? MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO :
4301 (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC);
4304 static int mov_write_tfhd_tag(AVIOContext *pb, MOVMuxContext *mov,
4305 MOVTrack *track, int64_t moof_offset)
4307 int64_t pos = avio_tell(pb);
4308 uint32_t flags = MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
4309 MOV_TFHD_BASE_DATA_OFFSET;
4310 if (!track->entry) {
4311 flags |= MOV_TFHD_DURATION_IS_EMPTY;
4313 flags |= MOV_TFHD_DEFAULT_FLAGS;
4315 if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET)
4316 flags &= ~MOV_TFHD_BASE_DATA_OFFSET;
4317 if (mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) {
4318 flags &= ~MOV_TFHD_BASE_DATA_OFFSET;
4319 flags |= MOV_TFHD_DEFAULT_BASE_IS_MOOF;
4321 /* CMAF requires all values to be explicit in tfhd atoms */
4322 if (mov->flags & FF_MOV_FLAG_CMAF)
4323 flags |= MOV_TFHD_STSD_ID;
4325 /* Don't set a default sample size, the silverlight player refuses
4326 * to play files with that set. Don't set a default sample duration,
4327 * WMP freaks out if it is set. Don't set a base data offset, PIFF
4328 * file format says it MUST NOT be set. */
4329 if (track->mode == MODE_ISM)
4330 flags &= ~(MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
4331 MOV_TFHD_BASE_DATA_OFFSET | MOV_TFHD_STSD_ID);
4333 avio_wb32(pb, 0); /* size placeholder */
4334 ffio_wfourcc(pb, "tfhd");
4335 avio_w8(pb, 0); /* version */
4336 avio_wb24(pb, flags);
4338 avio_wb32(pb, track->track_id); /* track-id */
4339 if (flags & MOV_TFHD_BASE_DATA_OFFSET)
4340 avio_wb64(pb, moof_offset);
4341 if (flags & MOV_TFHD_STSD_ID) {
4344 if (flags & MOV_TFHD_DEFAULT_DURATION) {
4345 track->default_duration = get_cluster_duration(track, 0);
4346 avio_wb32(pb, track->default_duration);
4348 if (flags & MOV_TFHD_DEFAULT_SIZE) {
4349 track->default_size = track->entry ? track->cluster[0].size : 1;
4350 avio_wb32(pb, track->default_size);
4352 track->default_size = -1;
4354 if (flags & MOV_TFHD_DEFAULT_FLAGS) {
4355 /* Set the default flags based on the second sample, if available.
4356 * If the first sample is different, that can be signaled via a separate field. */
4357 if (track->entry > 1)
4358 track->default_sample_flags = get_sample_flags(track, &track->cluster[1]);
4360 track->default_sample_flags =
4361 track->par->codec_type == AVMEDIA_TYPE_VIDEO ?
4362 (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC) :
4363 MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO;
4364 avio_wb32(pb, track->default_sample_flags);
4367 return update_size(pb, pos);
4370 static int mov_write_trun_tag(AVIOContext *pb, MOVMuxContext *mov,
4371 MOVTrack *track, int moof_size,
4374 int64_t pos = avio_tell(pb);
4375 uint32_t flags = MOV_TRUN_DATA_OFFSET;
4378 for (i = first; i < end; i++) {
4379 if (get_cluster_duration(track, i) != track->default_duration)
4380 flags |= MOV_TRUN_SAMPLE_DURATION;
4381 if (track->cluster[i].size != track->default_size)
4382 flags |= MOV_TRUN_SAMPLE_SIZE;
4383 if (i > first && get_sample_flags(track, &track->cluster[i]) != track->default_sample_flags)
4384 flags |= MOV_TRUN_SAMPLE_FLAGS;
4386 if (!(flags & MOV_TRUN_SAMPLE_FLAGS) && track->entry > 0 &&
4387 get_sample_flags(track, &track->cluster[0]) != track->default_sample_flags)
4388 flags |= MOV_TRUN_FIRST_SAMPLE_FLAGS;
4389 if (track->flags & MOV_TRACK_CTTS)
4390 flags |= MOV_TRUN_SAMPLE_CTS;
4392 avio_wb32(pb, 0); /* size placeholder */
4393 ffio_wfourcc(pb, "trun");
4394 if (mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS)
4395 avio_w8(pb, 1); /* version */
4397 avio_w8(pb, 0); /* version */
4398 avio_wb24(pb, flags);
4400 avio_wb32(pb, end - first); /* sample count */
4401 if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET &&
4402 !(mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) &&
4404 avio_wb32(pb, 0); /* Later tracks follow immediately after the previous one */
4406 avio_wb32(pb, moof_size + 8 + track->data_offset +
4407 track->cluster[first].pos); /* data offset */
4408 if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS)
4409 avio_wb32(pb, get_sample_flags(track, &track->cluster[first]));
4411 for (i = first; i < end; i++) {
4412 if (flags & MOV_TRUN_SAMPLE_DURATION)
4413 avio_wb32(pb, get_cluster_duration(track, i));
4414 if (flags & MOV_TRUN_SAMPLE_SIZE)
4415 avio_wb32(pb, track->cluster[i].size);
4416 if (flags & MOV_TRUN_SAMPLE_FLAGS)
4417 avio_wb32(pb, get_sample_flags(track, &track->cluster[i]));
4418 if (flags & MOV_TRUN_SAMPLE_CTS)
4419 avio_wb32(pb, track->cluster[i].cts);
4422 mov->first_trun = 0;
4423 return update_size(pb, pos);
4426 static int mov_write_tfxd_tag(AVIOContext *pb, MOVTrack *track)
4428 int64_t pos = avio_tell(pb);
4429 static const uint8_t uuid[] = {
4430 0x6d, 0x1d, 0x9b, 0x05, 0x42, 0xd5, 0x44, 0xe6,
4431 0x80, 0xe2, 0x14, 0x1d, 0xaf, 0xf7, 0x57, 0xb2
4434 avio_wb32(pb, 0); /* size placeholder */
4435 ffio_wfourcc(pb, "uuid");
4436 avio_write(pb, uuid, sizeof(uuid));
4439 avio_wb64(pb, track->start_dts + track->frag_start +
4440 track->cluster[0].cts);
4441 avio_wb64(pb, track->end_pts -
4442 (track->cluster[0].dts + track->cluster[0].cts));
4444 return update_size(pb, pos);
4447 static int mov_write_tfrf_tag(AVIOContext *pb, MOVMuxContext *mov,
4448 MOVTrack *track, int entry)
4450 int n = track->nb_frag_info - 1 - entry, i;
4451 int size = 8 + 16 + 4 + 1 + 16*n;
4452 static const uint8_t uuid[] = {
4453 0xd4, 0x80, 0x7e, 0xf2, 0xca, 0x39, 0x46, 0x95,
4454 0x8e, 0x54, 0x26, 0xcb, 0x9e, 0x46, 0xa7, 0x9f
4460 avio_seek(pb, track->frag_info[entry].tfrf_offset, SEEK_SET);
4461 avio_wb32(pb, size);
4462 ffio_wfourcc(pb, "uuid");
4463 avio_write(pb, uuid, sizeof(uuid));
4467 for (i = 0; i < n; i++) {
4468 int index = entry + 1 + i;
4469 avio_wb64(pb, track->frag_info[index].time);
4470 avio_wb64(pb, track->frag_info[index].duration);
4472 if (n < mov->ism_lookahead) {
4473 int free_size = 16 * (mov->ism_lookahead - n);
4474 avio_wb32(pb, free_size);
4475 ffio_wfourcc(pb, "free");
4476 ffio_fill(pb, 0, free_size - 8);
4482 static int mov_write_tfrf_tags(AVIOContext *pb, MOVMuxContext *mov,
4485 int64_t pos = avio_tell(pb);
4487 for (i = 0; i < mov->ism_lookahead; i++) {
4488 /* Update the tfrf tag for the last ism_lookahead fragments,
4489 * nb_frag_info - 1 is the next fragment to be written. */
4490 mov_write_tfrf_tag(pb, mov, track, track->nb_frag_info - 2 - i);
4492 avio_seek(pb, pos, SEEK_SET);
4496 static int mov_add_tfra_entries(AVIOContext *pb, MOVMuxContext *mov, int tracks,
4500 for (i = 0; i < mov->nb_streams; i++) {
4501 MOVTrack *track = &mov->tracks[i];
4502 MOVFragmentInfo *info;
4503 if ((tracks >= 0 && i != tracks) || !track->entry)
4505 track->nb_frag_info++;
4506 if (track->nb_frag_info >= track->frag_info_capacity) {
4507 unsigned new_capacity = track->nb_frag_info + MOV_FRAG_INFO_ALLOC_INCREMENT;
4508 if (av_reallocp_array(&track->frag_info,
4510 sizeof(*track->frag_info)))
4511 return AVERROR(ENOMEM);
4512 track->frag_info_capacity = new_capacity;
4514 info = &track->frag_info[track->nb_frag_info - 1];
4515 info->offset = avio_tell(pb);
4517 // Try to recreate the original pts for the first packet
4518 // from the fields we have stored
4519 info->time = track->start_dts + track->frag_start +
4520 track->cluster[0].cts;
4521 info->duration = track->end_pts -
4522 (track->cluster[0].dts + track->cluster[0].cts);
4523 // If the pts is less than zero, we will have trimmed
4524 // away parts of the media track using an edit list,
4525 // and the corresponding start presentation time is zero.
4526 if (info->time < 0) {
4527 info->duration += info->time;
4530 info->tfrf_offset = 0;
4531 mov_write_tfrf_tags(pb, mov, track);
4536 static void mov_prune_frag_info(MOVMuxContext *mov, int tracks, int max)
4539 for (i = 0; i < mov->nb_streams; i++) {
4540 MOVTrack *track = &mov->tracks[i];
4541 if ((tracks >= 0 && i != tracks) || !track->entry)
4543 if (track->nb_frag_info > max) {
4544 memmove(track->frag_info, track->frag_info + (track->nb_frag_info - max), max * sizeof(*track->frag_info));
4545 track->nb_frag_info = max;
4550 static int mov_write_tfdt_tag(AVIOContext *pb, MOVTrack *track)
4552 int64_t pos = avio_tell(pb);
4554 avio_wb32(pb, 0); /* size */
4555 ffio_wfourcc(pb, "tfdt");
4556 avio_w8(pb, 1); /* version */
4558 avio_wb64(pb, track->frag_start);
4559 return update_size(pb, pos);
4562 static int mov_write_traf_tag(AVIOContext *pb, MOVMuxContext *mov,
4563 MOVTrack *track, int64_t moof_offset,
4566 int64_t pos = avio_tell(pb);
4568 avio_wb32(pb, 0); /* size placeholder */
4569 ffio_wfourcc(pb, "traf");
4571 mov_write_tfhd_tag(pb, mov, track, moof_offset);
4572 if (mov->mode != MODE_ISM)
4573 mov_write_tfdt_tag(pb, track);
4574 for (i = 1; i < track->entry; i++) {
4575 if (track->cluster[i].pos != track->cluster[i - 1].pos + track->cluster[i - 1].size) {
4576 mov_write_trun_tag(pb, mov, track, moof_size, start, i);
4580 mov_write_trun_tag(pb, mov, track, moof_size, start, track->entry);
4581 if (mov->mode == MODE_ISM) {
4582 mov_write_tfxd_tag(pb, track);
4584 if (mov->ism_lookahead) {
4585 int i, size = 16 + 4 + 1 + 16 * mov->ism_lookahead;
4587 if (track->nb_frag_info > 0) {
4588 MOVFragmentInfo *info = &track->frag_info[track->nb_frag_info - 1];
4589 if (!info->tfrf_offset)
4590 info->tfrf_offset = avio_tell(pb);
4592 avio_wb32(pb, 8 + size);
4593 ffio_wfourcc(pb, "free");
4594 for (i = 0; i < size; i++)
4599 return update_size(pb, pos);
4602 static int mov_write_moof_tag_internal(AVIOContext *pb, MOVMuxContext *mov,
4603 int tracks, int moof_size)
4605 int64_t pos = avio_tell(pb);
4608 avio_wb32(pb, 0); /* size placeholder */
4609 ffio_wfourcc(pb, "moof");
4610 mov->first_trun = 1;
4612 mov_write_mfhd_tag(pb, mov);
4613 for (i = 0; i < mov->nb_streams; i++) {
4614 MOVTrack *track = &mov->tracks[i];
4615 if (tracks >= 0 && i != tracks)
4619 mov_write_traf_tag(pb, mov, track, pos, moof_size);
4622 return update_size(pb, pos);
4625 static int mov_write_sidx_tag(AVIOContext *pb,
4626 MOVTrack *track, int ref_size, int total_sidx_size)
4628 int64_t pos = avio_tell(pb), offset_pos, end_pos;
4629 int64_t presentation_time, duration, offset;
4630 unsigned starts_with_SAP;
4635 presentation_time = track->start_dts + track->frag_start +
4636 track->cluster[0].cts;
4637 duration = track->end_pts -
4638 (track->cluster[0].dts + track->cluster[0].cts);
4639 starts_with_SAP = track->cluster[0].flags & MOV_SYNC_SAMPLE;
4641 // pts<0 should be cut away using edts
4642 if (presentation_time < 0) {
4643 duration += presentation_time;
4644 presentation_time = 0;
4647 entries = track->nb_frag_info;
4650 presentation_time = track->frag_info[0].time;
4653 avio_wb32(pb, 0); /* size */
4654 ffio_wfourcc(pb, "sidx");
4655 avio_w8(pb, 1); /* version */
4657 avio_wb32(pb, track->track_id); /* reference_ID */
4658 avio_wb32(pb, track->timescale); /* timescale */
4659 avio_wb64(pb, presentation_time); /* earliest_presentation_time */
4660 offset_pos = avio_tell(pb);
4661 avio_wb64(pb, 0); /* first_offset (offset to referenced moof) */
4662 avio_wb16(pb, 0); /* reserved */
4664 avio_wb16(pb, entries); /* reference_count */
4665 for (i = 0; i < entries; i++) {
4666 if (!track->entry) {
4667 if (i > 1 && track->frag_info[i].offset != track->frag_info[i - 1].offset + track->frag_info[i - 1].size) {
4668 av_log(NULL, AV_LOG_ERROR, "Non-consecutive fragments, writing incorrect sidx\n");
4670 duration = track->frag_info[i].duration;
4671 ref_size = track->frag_info[i].size;
4672 starts_with_SAP = 1;
4674 avio_wb32(pb, (0 << 31) | (ref_size & 0x7fffffff)); /* reference_type (0 = media) | referenced_size */
4675 avio_wb32(pb, duration); /* subsegment_duration */
4676 avio_wb32(pb, (starts_with_SAP << 31) | (0 << 28) | 0); /* starts_with_SAP | SAP_type | SAP_delta_time */
4679 end_pos = avio_tell(pb);
4680 offset = pos + total_sidx_size - end_pos;
4681 avio_seek(pb, offset_pos, SEEK_SET);
4682 avio_wb64(pb, offset);
4683 avio_seek(pb, end_pos, SEEK_SET);
4684 return update_size(pb, pos);
4687 static int mov_write_sidx_tags(AVIOContext *pb, MOVMuxContext *mov,
4688 int tracks, int ref_size)
4691 AVIOContext *avio_buf;
4693 for (round = 0; round < 2; round++) {
4694 // First run one round to calculate the total size of all
4696 // This would be much simpler if we'd only write one sidx
4697 // atom, for the first track in the moof.
4699 if ((ret = ffio_open_null_buf(&avio_buf)) < 0)
4704 for (i = 0; i < mov->nb_streams; i++) {
4705 MOVTrack *track = &mov->tracks[i];
4706 if (tracks >= 0 && i != tracks)
4708 // When writing a sidx for the full file, entry is 0, but
4709 // we want to include all tracks. ref_size is 0 in this case,
4710 // since we read it from frag_info instead.
4711 if (!track->entry && ref_size > 0)
4713 total_size -= mov_write_sidx_tag(avio_buf, track, ref_size,
4717 total_size = ffio_close_null_buf(avio_buf);
4722 static int mov_write_prft_tag(AVIOContext *pb, MOVMuxContext *mov, int tracks)
4724 int64_t pos = avio_tell(pb), pts_us, ntp_ts;
4725 MOVTrack *first_track;
4728 /* PRFT should be associated with at most one track. So, choosing only the
4732 first_track = &(mov->tracks[0]);
4734 if (!first_track->entry) {
4735 av_log(mov->fc, AV_LOG_WARNING, "Unable to write PRFT, no entries in the track\n");
4739 if (first_track->cluster[0].pts == AV_NOPTS_VALUE) {
4740 av_log(mov->fc, AV_LOG_WARNING, "Unable to write PRFT, first PTS is invalid\n");
4744 if (mov->write_prft == MOV_PRFT_SRC_WALLCLOCK) {
4745 if (first_track->cluster[0].prft.wallclock) {
4746 /* Round the NTP time to whole milliseconds. */
4747 ntp_ts = ff_get_formatted_ntp_time((first_track->cluster[0].prft.wallclock / 1000) * 1000 +
4749 flags = first_track->cluster[0].prft.flags;
4751 ntp_ts = ff_get_formatted_ntp_time(ff_ntp_time());
4752 } else if (mov->write_prft == MOV_PRFT_SRC_PTS) {
4753 pts_us = av_rescale_q(first_track->cluster[0].pts,
4754 first_track->st->time_base, AV_TIME_BASE_Q);
4755 ntp_ts = ff_get_formatted_ntp_time(pts_us + NTP_OFFSET_US);
4757 av_log(mov->fc, AV_LOG_WARNING, "Unsupported PRFT box configuration: %d\n",
4762 avio_wb32(pb, 0); // Size place holder
4763 ffio_wfourcc(pb, "prft"); // Type
4764 avio_w8(pb, 1); // Version
4765 avio_wb24(pb, flags); // Flags
4766 avio_wb32(pb, first_track->track_id); // reference track ID
4767 avio_wb64(pb, ntp_ts); // NTP time stamp
4768 avio_wb64(pb, first_track->cluster[0].pts); //media time
4769 return update_size(pb, pos);
4772 static int mov_write_moof_tag(AVIOContext *pb, MOVMuxContext *mov, int tracks,
4775 AVIOContext *avio_buf;
4778 if ((ret = ffio_open_null_buf(&avio_buf)) < 0)
4780 mov_write_moof_tag_internal(avio_buf, mov, tracks, 0);
4781 moof_size = ffio_close_null_buf(avio_buf);
4783 if (mov->flags & FF_MOV_FLAG_DASH &&
4784 !(mov->flags & (FF_MOV_FLAG_GLOBAL_SIDX | FF_MOV_FLAG_SKIP_SIDX)))
4785 mov_write_sidx_tags(pb, mov, tracks, moof_size + 8 + mdat_size);
4787 if (mov->write_prft > MOV_PRFT_NONE && mov->write_prft < MOV_PRFT_NB)
4788 mov_write_prft_tag(pb, mov, tracks);
4790 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX ||
4791 !(mov->flags & FF_MOV_FLAG_SKIP_TRAILER) ||
4792 mov->ism_lookahead) {
4793 if ((ret = mov_add_tfra_entries(pb, mov, tracks, moof_size + 8 + mdat_size)) < 0)
4795 if (!(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) &&
4796 mov->flags & FF_MOV_FLAG_SKIP_TRAILER) {
4797 mov_prune_frag_info(mov, tracks, mov->ism_lookahead + 1);
4801 return mov_write_moof_tag_internal(pb, mov, tracks, moof_size);
4804 static int mov_write_tfra_tag(AVIOContext *pb, MOVTrack *track)
4806 int64_t pos = avio_tell(pb);
4809 avio_wb32(pb, 0); /* size placeholder */
4810 ffio_wfourcc(pb, "tfra");
4811 avio_w8(pb, 1); /* version */
4814 avio_wb32(pb, track->track_id);
4815 avio_wb32(pb, 0); /* length of traf/trun/sample num */
4816 avio_wb32(pb, track->nb_frag_info);
4817 for (i = 0; i < track->nb_frag_info; i++) {
4818 avio_wb64(pb, track->frag_info[i].time);
4819 avio_wb64(pb, track->frag_info[i].offset + track->data_offset);
4820 avio_w8(pb, 1); /* traf number */
4821 avio_w8(pb, 1); /* trun number */
4822 avio_w8(pb, 1); /* sample number */
4825 return update_size(pb, pos);
4828 static int mov_write_mfra_tag(AVIOContext *pb, MOVMuxContext *mov)
4830 AVIOContext *mfra_pb;
4834 ret = avio_open_dyn_buf(&mfra_pb);
4838 avio_wb32(mfra_pb, 0); /* size placeholder */
4839 ffio_wfourcc(mfra_pb, "mfra");
4840 /* An empty mfra atom is enough to indicate to the publishing point that
4841 * the stream has ended. */
4842 if (mov->flags & FF_MOV_FLAG_ISML)
4845 for (i = 0; i < mov->nb_streams; i++) {
4846 MOVTrack *track = &mov->tracks[i];
4847 if (track->nb_frag_info)
4848 mov_write_tfra_tag(mfra_pb, track);
4851 avio_wb32(mfra_pb, 16);
4852 ffio_wfourcc(mfra_pb, "mfro");
4853 avio_wb32(mfra_pb, 0); /* version + flags */
4854 avio_wb32(mfra_pb, avio_tell(mfra_pb) + 4);
4858 sz = update_size(mfra_pb, 0);
4859 ret = avio_get_dyn_buf(mfra_pb, &buf);
4860 avio_write(pb, buf, ret);
4861 ffio_free_dyn_buf(&mfra_pb);
4866 static int mov_write_mdat_tag(AVIOContext *pb, MOVMuxContext *mov)
4868 avio_wb32(pb, 8); // placeholder for extended size field (64 bit)
4869 ffio_wfourcc(pb, mov->mode == MODE_MOV ? "wide" : "free");
4871 mov->mdat_pos = avio_tell(pb);
4872 avio_wb32(pb, 0); /* size placeholder*/
4873 ffio_wfourcc(pb, "mdat");
4877 static void mov_write_ftyp_tag_internal(AVIOContext *pb, AVFormatContext *s,
4878 int has_h264, int has_video, int write_minor)
4880 MOVMuxContext *mov = s->priv_data;
4883 if (mov->major_brand && strlen(mov->major_brand) >= 4)
4884 ffio_wfourcc(pb, mov->major_brand);
4885 else if (mov->mode == MODE_3GP) {
4886 ffio_wfourcc(pb, has_h264 ? "3gp6" : "3gp4");
4887 minor = has_h264 ? 0x100 : 0x200;
4888 } else if (mov->mode & MODE_3G2) {
4889 ffio_wfourcc(pb, has_h264 ? "3g2b" : "3g2a");
4890 minor = has_h264 ? 0x20000 : 0x10000;
4891 } else if (mov->mode == MODE_PSP)
4892 ffio_wfourcc(pb, "MSNV");
4893 else if (mov->mode == MODE_MP4 && mov->flags & FF_MOV_FLAG_FRAGMENT &&
4894 mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS)
4895 ffio_wfourcc(pb, "iso6"); // Required when using signed CTS offsets in trun boxes
4896 else if (mov->mode == MODE_MP4 && mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)
4897 ffio_wfourcc(pb, "iso5"); // Required when using default-base-is-moof
4898 else if (mov->mode == MODE_MP4 && mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS)
4899 ffio_wfourcc(pb, "iso4");
4900 else if (mov->mode == MODE_MP4)
4901 ffio_wfourcc(pb, "isom");
4902 else if (mov->mode == MODE_IPOD)
4903 ffio_wfourcc(pb, has_video ? "M4V ":"M4A ");
4904 else if (mov->mode == MODE_ISM)
4905 ffio_wfourcc(pb, "isml");
4906 else if (mov->mode == MODE_F4V)
4907 ffio_wfourcc(pb, "f4v ");
4909 ffio_wfourcc(pb, "qt ");
4912 avio_wb32(pb, minor);
4915 static int mov_write_ftyp_tag(AVIOContext *pb, AVFormatContext *s)
4917 MOVMuxContext *mov = s->priv_data;
4918 int64_t pos = avio_tell(pb);
4919 int has_h264 = 0, has_av1 = 0, has_video = 0;
4922 for (i = 0; i < s->nb_streams; i++) {
4923 AVStream *st = s->streams[i];
4924 if (is_cover_image(st))
4926 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
4928 if (st->codecpar->codec_id == AV_CODEC_ID_H264)
4930 if (st->codecpar->codec_id == AV_CODEC_ID_AV1)
4934 avio_wb32(pb, 0); /* size */
4935 ffio_wfourcc(pb, "ftyp");
4937 // Write major brand
4938 mov_write_ftyp_tag_internal(pb, s, has_h264, has_video, 1);
4939 // Write the major brand as the first compatible brand as well
4940 mov_write_ftyp_tag_internal(pb, s, has_h264, has_video, 0);
4942 // Write compatible brands, ensuring that we don't write the major brand as a
4943 // compatible brand a second time.
4944 if (mov->mode == MODE_ISM) {
4945 ffio_wfourcc(pb, "piff");
4946 } else if (mov->mode != MODE_MOV) {
4947 // We add tfdt atoms when fragmenting, signal this with the iso6 compatible
4948 // brand, if not already the major brand. This is compatible with users that
4949 // don't understand tfdt.
4950 if (mov->mode == MODE_MP4) {
4951 if (mov->flags & FF_MOV_FLAG_CMAF)
4952 ffio_wfourcc(pb, "cmfc");
4953 if (mov->flags & FF_MOV_FLAG_FRAGMENT && !(mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS))
4954 ffio_wfourcc(pb, "iso6");
4956 ffio_wfourcc(pb, "av01");
4958 if (mov->flags & FF_MOV_FLAG_FRAGMENT)
4959 ffio_wfourcc(pb, "iso6");
4960 if (mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)
4961 ffio_wfourcc(pb, "iso5");
4962 else if (mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS)
4963 ffio_wfourcc(pb, "iso4");
4965 // Brands prior to iso5 can't be signaled when using default-base-is-moof
4966 if (!(mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)) {
4967 // write isom for mp4 only if it it's not the major brand already.
4968 if (mov->mode != MODE_MP4 || mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS)
4969 ffio_wfourcc(pb, "isom");
4970 ffio_wfourcc(pb, "iso2");
4972 ffio_wfourcc(pb, "avc1");
4976 if (mov->mode == MODE_MP4)
4977 ffio_wfourcc(pb, "mp41");
4979 if (mov->flags & FF_MOV_FLAG_DASH && mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
4980 ffio_wfourcc(pb, "dash");
4982 return update_size(pb, pos);
4985 static int mov_write_uuidprof_tag(AVIOContext *pb, AVFormatContext *s)
4987 AVStream *video_st = s->streams[0];
4988 AVCodecParameters *video_par = s->streams[0]->codecpar;
4989 AVCodecParameters *audio_par = s->streams[1]->codecpar;
4990 int audio_rate = audio_par->sample_rate;
4991 int64_t frame_rate = video_st->avg_frame_rate.den ?
4992 (video_st->avg_frame_rate.num * 0x10000LL) / video_st->avg_frame_rate.den :
4994 int audio_kbitrate = audio_par->bit_rate / 1000;
4995 int video_kbitrate = FFMIN(video_par->bit_rate / 1000, 800 - audio_kbitrate);
4997 if (frame_rate < 0 || frame_rate > INT32_MAX) {
4998 av_log(s, AV_LOG_ERROR, "Frame rate %f outside supported range\n", frame_rate / (double)0x10000);
4999 return AVERROR(EINVAL);
5002 avio_wb32(pb, 0x94); /* size */
5003 ffio_wfourcc(pb, "uuid");
5004 ffio_wfourcc(pb, "PROF");
5006 avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
5007 avio_wb32(pb, 0xbb88695c);
5008 avio_wb32(pb, 0xfac9c740);
5010 avio_wb32(pb, 0x0); /* ? */
5011 avio_wb32(pb, 0x3); /* 3 sections ? */
5013 avio_wb32(pb, 0x14); /* size */
5014 ffio_wfourcc(pb, "FPRF");
5015 avio_wb32(pb, 0x0); /* ? */
5016 avio_wb32(pb, 0x0); /* ? */
5017 avio_wb32(pb, 0x0); /* ? */
5019 avio_wb32(pb, 0x2c); /* size */
5020 ffio_wfourcc(pb, "APRF"); /* audio */
5022 avio_wb32(pb, 0x2); /* TrackID */
5023 ffio_wfourcc(pb, "mp4a");
5024 avio_wb32(pb, 0x20f);
5026 avio_wb32(pb, audio_kbitrate);
5027 avio_wb32(pb, audio_kbitrate);
5028 avio_wb32(pb, audio_rate);
5029 avio_wb32(pb, audio_par->channels);
5031 avio_wb32(pb, 0x34); /* size */
5032 ffio_wfourcc(pb, "VPRF"); /* video */
5034 avio_wb32(pb, 0x1); /* TrackID */
5035 if (video_par->codec_id == AV_CODEC_ID_H264) {
5036 ffio_wfourcc(pb, "avc1");
5037 avio_wb16(pb, 0x014D);
5038 avio_wb16(pb, 0x0015);
5040 ffio_wfourcc(pb, "mp4v");
5041 avio_wb16(pb, 0x0000);
5042 avio_wb16(pb, 0x0103);
5045 avio_wb32(pb, video_kbitrate);
5046 avio_wb32(pb, video_kbitrate);
5047 avio_wb32(pb, frame_rate);
5048 avio_wb32(pb, frame_rate);
5049 avio_wb16(pb, video_par->width);
5050 avio_wb16(pb, video_par->height);
5051 avio_wb32(pb, 0x010001); /* ? */
5056 static int mov_write_identification(AVIOContext *pb, AVFormatContext *s)
5058 MOVMuxContext *mov = s->priv_data;
5061 mov_write_ftyp_tag(pb,s);
5062 if (mov->mode == MODE_PSP) {
5063 int video_streams_nb = 0, audio_streams_nb = 0, other_streams_nb = 0;
5064 for (i = 0; i < s->nb_streams; i++) {
5065 AVStream *st = s->streams[i];
5066 if (is_cover_image(st))
5068 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
5070 else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
5076 if (video_streams_nb != 1 || audio_streams_nb != 1 || other_streams_nb) {
5077 av_log(s, AV_LOG_ERROR, "PSP mode need one video and one audio stream\n");
5078 return AVERROR(EINVAL);
5080 return mov_write_uuidprof_tag(pb, s);
5085 static int mov_parse_mpeg2_frame(AVPacket *pkt, uint32_t *flags)
5088 int i, closed_gop = 0;
5090 for (i = 0; i < pkt->size - 4; i++) {
5091 c = (c << 8) + pkt->data[i];
5092 if (c == 0x1b8) { // gop
5093 closed_gop = pkt->data[i + 4] >> 6 & 0x01;
5094 } else if (c == 0x100) { // pic
5095 int temp_ref = (pkt->data[i + 1] << 2) | (pkt->data[i + 2] >> 6);
5096 if (!temp_ref || closed_gop) // I picture is not reordered
5097 *flags = MOV_SYNC_SAMPLE;
5099 *flags = MOV_PARTIAL_SYNC_SAMPLE;
5106 static void mov_parse_vc1_frame(AVPacket *pkt, MOVTrack *trk)
5108 const uint8_t *start, *next, *end = pkt->data + pkt->size;
5109 int seq = 0, entry = 0;
5110 int key = pkt->flags & AV_PKT_FLAG_KEY;
5111 start = find_next_marker(pkt->data, end);
5112 for (next = start; next < end; start = next) {
5113 next = find_next_marker(start + 4, end);
5114 switch (AV_RB32(start)) {
5115 case VC1_CODE_SEQHDR:
5118 case VC1_CODE_ENTRYPOINT:
5121 case VC1_CODE_SLICE:
5122 trk->vc1_info.slices = 1;
5126 if (!trk->entry && trk->vc1_info.first_packet_seen)
5127 trk->vc1_info.first_frag_written = 1;
5128 if (!trk->entry && !trk->vc1_info.first_frag_written) {
5129 /* First packet in first fragment */
5130 trk->vc1_info.first_packet_seq = seq;
5131 trk->vc1_info.first_packet_entry = entry;
5132 trk->vc1_info.first_packet_seen = 1;
5133 } else if ((seq && !trk->vc1_info.packet_seq) ||
5134 (entry && !trk->vc1_info.packet_entry)) {
5136 for (i = 0; i < trk->entry; i++)
5137 trk->cluster[i].flags &= ~MOV_SYNC_SAMPLE;
5138 trk->has_keyframes = 0;
5140 trk->vc1_info.packet_seq = 1;
5142 trk->vc1_info.packet_entry = 1;
5143 if (!trk->vc1_info.first_frag_written) {
5144 /* First fragment */
5145 if ((!seq || trk->vc1_info.first_packet_seq) &&
5146 (!entry || trk->vc1_info.first_packet_entry)) {
5147 /* First packet had the same headers as this one, readd the
5148 * sync sample flag. */
5149 trk->cluster[0].flags |= MOV_SYNC_SAMPLE;
5150 trk->has_keyframes = 1;
5154 if (trk->vc1_info.packet_seq && trk->vc1_info.packet_entry)
5156 else if (trk->vc1_info.packet_seq)
5158 else if (trk->vc1_info.packet_entry)
5161 trk->cluster[trk->entry].flags |= MOV_SYNC_SAMPLE;
5162 trk->has_keyframes++;
5166 static void mov_parse_truehd_frame(AVPacket *pkt, MOVTrack *trk)
5173 length = (AV_RB16(pkt->data) & 0xFFF) * 2;
5174 if (length < 8 || length > pkt->size)
5177 if (AV_RB32(pkt->data + 4) == 0xF8726FBA) {
5178 trk->cluster[trk->entry].flags |= MOV_SYNC_SAMPLE;
5179 trk->has_keyframes++;
5185 static int mov_flush_fragment_interleaving(AVFormatContext *s, MOVTrack *track)
5187 MOVMuxContext *mov = s->priv_data;
5192 if (!track->mdat_buf)
5194 if (!mov->mdat_buf) {
5195 if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0)
5198 buf_size = avio_get_dyn_buf(track->mdat_buf, &buf);
5200 offset = avio_tell(mov->mdat_buf);
5201 avio_write(mov->mdat_buf, buf, buf_size);
5202 ffio_free_dyn_buf(&track->mdat_buf);
5204 for (i = track->entries_flushed; i < track->entry; i++)
5205 track->cluster[i].pos += offset;
5206 track->entries_flushed = track->entry;
5210 static int mov_flush_fragment(AVFormatContext *s, int force)
5212 MOVMuxContext *mov = s->priv_data;
5213 int i, first_track = -1;
5214 int64_t mdat_size = 0;
5216 int has_video = 0, starts_with_key = 0, first_video_track = 1;
5218 if (!(mov->flags & FF_MOV_FLAG_FRAGMENT))
5221 // Try to fill in the duration of the last packet in each stream
5222 // from queued packets in the interleave queues. If the flushing
5223 // of fragments was triggered automatically by an AVPacket, we
5224 // already have reliable info for the end of that track, but other
5225 // tracks may need to be filled in.
5226 for (i = 0; i < s->nb_streams; i++) {
5227 MOVTrack *track = &mov->tracks[i];
5228 if (!track->end_reliable) {
5230 if (!ff_interleaved_peek(s, i, &pkt, 1)) {
5231 if (track->dts_shift != AV_NOPTS_VALUE)
5232 pkt.dts += track->dts_shift;
5233 track->track_duration = pkt.dts - track->start_dts;
5234 if (pkt.pts != AV_NOPTS_VALUE)
5235 track->end_pts = pkt.pts;
5237 track->end_pts = pkt.dts;
5242 for (i = 0; i < mov->nb_streams; i++) {
5243 MOVTrack *track = &mov->tracks[i];
5244 if (track->entry <= 1)
5246 // Sample durations are calculated as the diff of dts values,
5247 // but for the last sample in a fragment, we don't know the dts
5248 // of the first sample in the next fragment, so we have to rely
5249 // on what was set as duration in the AVPacket. Not all callers
5250 // set this though, so we might want to replace it with an
5251 // estimate if it currently is zero.
5252 if (get_cluster_duration(track, track->entry - 1) != 0)
5254 // Use the duration (i.e. dts diff) of the second last sample for
5255 // the last one. This is a wild guess (and fatal if it turns out
5256 // to be too long), but probably the best we can do - having a zero
5257 // duration is bad as well.
5258 track->track_duration += get_cluster_duration(track, track->entry - 2);
5259 track->end_pts += get_cluster_duration(track, track->entry - 2);
5260 if (!mov->missing_duration_warned) {
5261 av_log(s, AV_LOG_WARNING,
5262 "Estimating the duration of the last packet in a "
5263 "fragment, consider setting the duration field in "
5264 "AVPacket instead.\n");
5265 mov->missing_duration_warned = 1;
5269 if (!mov->moov_written) {
5270 int64_t pos = avio_tell(s->pb);
5272 int buf_size, moov_size;
5274 for (i = 0; i < mov->nb_streams; i++)
5275 if (!mov->tracks[i].entry && !is_cover_image(mov->tracks[i].st))
5277 /* Don't write the initial moov unless all tracks have data */
5278 if (i < mov->nb_streams && !force)
5281 moov_size = get_moov_size(s);
5282 for (i = 0; i < mov->nb_streams; i++)
5283 mov->tracks[i].data_offset = pos + moov_size + 8;
5285 avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_HEADER);
5286 if (mov->flags & FF_MOV_FLAG_DELAY_MOOV)
5287 mov_write_identification(s->pb, s);
5288 if ((ret = mov_write_moov_tag(s->pb, mov, s)) < 0)
5291 if (mov->flags & FF_MOV_FLAG_DELAY_MOOV) {
5292 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
5293 mov->reserved_header_pos = avio_tell(s->pb);
5294 avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_FLUSH_POINT);
5295 mov->moov_written = 1;
5299 buf_size = avio_get_dyn_buf(mov->mdat_buf, &buf);
5300 avio_wb32(s->pb, buf_size + 8);
5301 ffio_wfourcc(s->pb, "mdat");
5302 avio_write(s->pb, buf, buf_size);
5303 ffio_free_dyn_buf(&mov->mdat_buf);
5305 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
5306 mov->reserved_header_pos = avio_tell(s->pb);
5308 mov->moov_written = 1;
5310 for (i = 0; i < mov->nb_streams; i++) {
5311 if (mov->tracks[i].entry)
5312 mov->tracks[i].frag_start += mov->tracks[i].start_dts +
5313 mov->tracks[i].track_duration -
5314 mov->tracks[i].cluster[0].dts;
5315 mov->tracks[i].entry = 0;
5316 mov->tracks[i].end_reliable = 0;
5318 avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_FLUSH_POINT);
5322 if (mov->frag_interleave) {
5323 for (i = 0; i < mov->nb_streams; i++) {
5324 MOVTrack *track = &mov->tracks[i];
5326 if ((ret = mov_flush_fragment_interleaving(s, track)) < 0)
5332 mdat_size = avio_tell(mov->mdat_buf);
5335 for (i = 0; i < mov->nb_streams; i++) {
5336 MOVTrack *track = &mov->tracks[i];
5337 if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF || mov->frag_interleave)
5338 track->data_offset = 0;
5340 track->data_offset = mdat_size;
5341 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
5343 if (first_video_track) {
5345 starts_with_key = track->cluster[0].flags & MOV_SYNC_SAMPLE;
5346 first_video_track = 0;
5351 if (track->mdat_buf)
5352 mdat_size += avio_tell(track->mdat_buf);
5353 if (first_track < 0)
5360 avio_write_marker(s->pb,
5361 av_rescale(mov->tracks[first_track].cluster[0].dts, AV_TIME_BASE, mov->tracks[first_track].timescale),
5362 (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);
5364 for (i = 0; i < mov->nb_streams; i++) {
5365 MOVTrack *track = &mov->tracks[i];
5366 int buf_size, write_moof = 1, moof_tracks = -1;
5368 int64_t duration = 0;
5371 duration = track->start_dts + track->track_duration -
5372 track->cluster[0].dts;
5373 if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF) {
5374 if (!track->mdat_buf)
5376 mdat_size = avio_tell(track->mdat_buf);
5379 write_moof = i == first_track;
5383 avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_FLUSH_POINT);
5385 mov_write_moof_tag(s->pb, mov, moof_tracks, mdat_size);
5388 avio_wb32(s->pb, mdat_size + 8);
5389 ffio_wfourcc(s->pb, "mdat");
5393 track->frag_start += duration;
5395 track->entries_flushed = 0;
5396 track->end_reliable = 0;
5397 if (!mov->frag_interleave) {
5398 if (!track->mdat_buf)
5400 buf_size = avio_close_dyn_buf(track->mdat_buf, &buf);
5401 track->mdat_buf = NULL;
5405 buf_size = avio_close_dyn_buf(mov->mdat_buf, &buf);
5406 mov->mdat_buf = NULL;
5409 avio_write(s->pb, buf, buf_size);
5415 avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_FLUSH_POINT);
5419 static int mov_auto_flush_fragment(AVFormatContext *s, int force)
5421 MOVMuxContext *mov = s->priv_data;
5422 int had_moov = mov->moov_written;
5423 int ret = mov_flush_fragment(s, force);
5426 // If using delay_moov, the first flush only wrote the moov,
5427 // not the actual moof+mdat pair, thus flush once again.
5428 if (!had_moov && mov->flags & FF_MOV_FLAG_DELAY_MOOV)
5429 ret = mov_flush_fragment(s, force);
5433 static int check_pkt(AVFormatContext *s, AVPacket *pkt)
5435 MOVMuxContext *mov = s->priv_data;
5436 MOVTrack *trk = &mov->tracks[pkt->stream_index];
5441 ref = trk->cluster[trk->entry - 1].dts;
5442 } else if ( trk->start_dts != AV_NOPTS_VALUE
5443 && !trk->frag_discont) {
5444 ref = trk->start_dts + trk->track_duration;
5446 ref = pkt->dts; // Skip tests for the first packet
5448 if (trk->dts_shift != AV_NOPTS_VALUE) {
5449 /* With negative CTS offsets we have set an offset to the DTS,
5450 * reverse this for the check. */
5451 ref -= trk->dts_shift;
5454 duration = pkt->dts - ref;
5455 if (pkt->dts < ref || duration >= INT_MAX) {
5456 av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" / timestamp: %"PRId64" is out of range for mov/mp4 format\n",
5461 pkt->pts = AV_NOPTS_VALUE;
5464 if (pkt->duration < 0 || pkt->duration > INT_MAX) {
5465 av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" is invalid\n", pkt->duration);
5466 return AVERROR(EINVAL);
5471 int ff_mov_write_packet(AVFormatContext *s, AVPacket *pkt)
5473 MOVMuxContext *mov = s->priv_data;
5474 AVIOContext *pb = s->pb;
5475 MOVTrack *trk = &mov->tracks[pkt->stream_index];
5476 AVCodecParameters *par = trk->par;
5477 AVProducerReferenceTime *prft;
5478 unsigned int samples_in_chunk = 0;
5479 int size = pkt->size, ret = 0, offset = 0;
5481 uint8_t *reformatted_data = NULL;
5483 ret = check_pkt(s, pkt);
5487 if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
5489 if (mov->moov_written || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
5490 if (mov->frag_interleave && mov->fragments > 0) {
5491 if (trk->entry - trk->entries_flushed >= mov->frag_interleave) {
5492 if ((ret = mov_flush_fragment_interleaving(s, trk)) < 0)
5497 if (!trk->mdat_buf) {
5498 if ((ret = avio_open_dyn_buf(&trk->mdat_buf)) < 0)
5503 if (!mov->mdat_buf) {
5504 if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0)
5511 if (par->codec_id == AV_CODEC_ID_AMR_NB) {
5512 /* We must find out how many AMR blocks there are in one packet */
5513 static const uint16_t packed_size[16] =
5514 {13, 14, 16, 18, 20, 21, 27, 32, 6, 0, 0, 0, 0, 0, 0, 1};
5517 while (len < size && samples_in_chunk < 100) {
5518 len += packed_size[(pkt->data[len] >> 3) & 0x0F];
5521 if (samples_in_chunk > 1) {
5522 av_log(s, AV_LOG_ERROR, "fatal error, input is not a single packet, implement a AVParser for it\n");
5525 } else if (par->codec_id == AV_CODEC_ID_ADPCM_MS ||
5526 par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) {
5527 samples_in_chunk = trk->par->frame_size;
5528 } else if (trk->sample_size)
5529 samples_in_chunk = size / trk->sample_size;
5531 samples_in_chunk = 1;
5533 if (samples_in_chunk < 1) {
5534 av_log(s, AV_LOG_ERROR, "fatal error, input packet contains no samples\n");
5535 return AVERROR_PATCHWELCOME;
5538 /* copy extradata if it exists */
5539 if (trk->vos_len == 0 && par->extradata_size > 0 &&
5540 !TAG_IS_AVCI(trk->tag) &&
5541 (par->codec_id != AV_CODEC_ID_DNXHD)) {
5542 trk->vos_len = par->extradata_size;
5543 trk->vos_data = av_malloc(trk->vos_len + AV_INPUT_BUFFER_PADDING_SIZE);
5544 if (!trk->vos_data) {
5545 ret = AVERROR(ENOMEM);
5548 memcpy(trk->vos_data, par->extradata, trk->vos_len);
5549 memset(trk->vos_data + trk->vos_len, 0, AV_INPUT_BUFFER_PADDING_SIZE);
5552 if ((par->codec_id == AV_CODEC_ID_DNXHD ||
5553 par->codec_id == AV_CODEC_ID_H264 ||
5554 par->codec_id == AV_CODEC_ID_HEVC ||
5555 par->codec_id == AV_CODEC_ID_TRUEHD ||
5556 par->codec_id == AV_CODEC_ID_AC3) && !trk->vos_len &&
5557 !TAG_IS_AVCI(trk->tag)) {
5558 /* copy frame to create needed atoms */
5559 trk->vos_len = size;
5560 trk->vos_data = av_malloc(size + AV_INPUT_BUFFER_PADDING_SIZE);
5561 if (!trk->vos_data) {
5562 ret = AVERROR(ENOMEM);
5565 memcpy(trk->vos_data, pkt->data, size);
5566 memset(trk->vos_data + size, 0, AV_INPUT_BUFFER_PADDING_SIZE);
5569 if (par->codec_id == AV_CODEC_ID_AAC && pkt->size > 2 &&
5570 (AV_RB16(pkt->data) & 0xfff0) == 0xfff0) {
5571 if (!s->streams[pkt->stream_index]->nb_frames) {
5572 av_log(s, AV_LOG_ERROR, "Malformed AAC bitstream detected: "
5573 "use the audio bitstream filter 'aac_adtstoasc' to fix it "
5574 "('-bsf:a aac_adtstoasc' option with ffmpeg)\n");
5577 av_log(s, AV_LOG_WARNING, "aac bitstream error\n");
5579 if (par->codec_id == AV_CODEC_ID_H264 && trk->vos_len > 0 && *(uint8_t *)trk->vos_data != 1 && !TAG_IS_AVCI(trk->tag)) {
5580 /* from x264 or from bytestream H.264 */
5581 /* NAL reformatting needed */
5582 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
5583 ret = ff_avc_parse_nal_units_buf(pkt->data, &reformatted_data,
5587 avio_write(pb, reformatted_data, size);
5589 if (trk->cenc.aes_ctr) {
5590 size = ff_mov_cenc_avc_parse_nal_units(&trk->cenc, pb, pkt->data, size);
5596 size = ff_avc_parse_nal_units(pb, pkt->data, pkt->size);
5599 } else if (par->codec_id == AV_CODEC_ID_HEVC && trk->vos_len > 6 &&
5600 (AV_RB24(trk->vos_data) == 1 || AV_RB32(trk->vos_data) == 1)) {
5601 /* extradata is Annex B, assume the bitstream is too and convert it */
5602 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
5603 ret = ff_hevc_annexb2mp4_buf(pkt->data, &reformatted_data,
5607 avio_write(pb, reformatted_data, size);
5609 size = ff_hevc_annexb2mp4(pb, pkt->data, pkt->size, 0, NULL);
5611 } else if (par->codec_id == AV_CODEC_ID_AV1) {
5612 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
5613 ret = ff_av1_filter_obus_buf(pkt->data, &reformatted_data,
5617 avio_write(pb, reformatted_data, size);
5619 size = ff_av1_filter_obus(pb, pkt->data, pkt->size);
5621 #if CONFIG_AC3_PARSER
5622 } else if (par->codec_id == AV_CODEC_ID_EAC3) {
5623 size = handle_eac3(mov, pkt, trk);
5628 avio_write(pb, pkt->data, size);
5630 } else if (par->codec_id == AV_CODEC_ID_EIA_608) {
5633 for (int i = 0; i < pkt->size; i += 3) {
5634 if (pkt->data[i] == 0xFC) {
5638 avio_wb32(pb, size);
5639 ffio_wfourcc(pb, "cdat");
5640 for (int i = 0; i < pkt->size; i += 3) {
5641 if (pkt->data[i] == 0xFC) {
5642 avio_w8(pb, pkt->data[i + 1]);
5643 avio_w8(pb, pkt->data[i + 2]);
5647 if (trk->cenc.aes_ctr) {
5648 if (par->codec_id == AV_CODEC_ID_H264 && par->extradata_size > 4) {
5649 int nal_size_length = (par->extradata[4] & 0x3) + 1;
5650 ret = ff_mov_cenc_avc_write_nal_units(s, &trk->cenc, nal_size_length, pb, pkt->data, size);
5652 ret = ff_mov_cenc_write_packet(&trk->cenc, pb, pkt->data, size);
5659 avio_write(pb, pkt->data, size);
5663 if (trk->entry >= trk->cluster_capacity) {
5664 unsigned new_capacity = trk->entry + MOV_INDEX_CLUSTER_SIZE;
5665 if (av_reallocp_array(&trk->cluster, new_capacity,
5666 sizeof(*trk->cluster))) {
5667 ret = AVERROR(ENOMEM);
5670 trk->cluster_capacity = new_capacity;
5673 trk->cluster[trk->entry].pos = avio_tell(pb) - size;
5674 trk->cluster[trk->entry].samples_in_chunk = samples_in_chunk;
5675 trk->cluster[trk->entry].chunkNum = 0;
5676 trk->cluster[trk->entry].size = size;
5677 trk->cluster[trk->entry].entries = samples_in_chunk;
5678 trk->cluster[trk->entry].dts = pkt->dts;
5679 trk->cluster[trk->entry].pts = pkt->pts;
5680 if (!trk->entry && trk->start_dts != AV_NOPTS_VALUE) {
5681 if (!trk->frag_discont) {
5682 /* First packet of a new fragment. We already wrote the duration
5683 * of the last packet of the previous fragment based on track_duration,
5684 * which might not exactly match our dts. Therefore adjust the dts
5685 * of this packet to be what the previous packets duration implies. */
5686 trk->cluster[trk->entry].dts = trk->start_dts + trk->track_duration;
5687 /* We also may have written the pts and the corresponding duration
5688 * in sidx/tfrf/tfxd tags; make sure the sidx pts and duration match up with
5689 * the next fragment. This means the cts of the first sample must
5690 * be the same in all fragments, unless end_pts was updated by
5691 * the packet causing the fragment to be written. */
5692 if ((mov->flags & FF_MOV_FLAG_DASH &&
5693 !(mov->flags & (FF_MOV_FLAG_GLOBAL_SIDX | FF_MOV_FLAG_SKIP_SIDX))) ||
5694 mov->mode == MODE_ISM)
5695 pkt->pts = pkt->dts + trk->end_pts - trk->cluster[trk->entry].dts;
5697 /* New fragment, but discontinuous from previous fragments.
5698 * Pretend the duration sum of the earlier fragments is
5699 * pkt->dts - trk->start_dts. */
5700 trk->frag_start = pkt->dts - trk->start_dts;
5701 trk->end_pts = AV_NOPTS_VALUE;
5702 trk->frag_discont = 0;
5706 if (!trk->entry && trk->start_dts == AV_NOPTS_VALUE && !mov->use_editlist &&
5707 s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO) {
5708 /* Not using edit lists and shifting the first track to start from zero.
5709 * If the other streams start from a later timestamp, we won't be able
5710 * to signal the difference in starting time without an edit list.
5711 * Thus move the timestamp for this first sample to 0, increasing
5712 * its duration instead. */
5713 trk->cluster[trk->entry].dts = trk->start_dts = 0;
5715 if (trk->start_dts == AV_NOPTS_VALUE) {
5716 trk->start_dts = pkt->dts;
5717 if (trk->frag_discont) {
5718 if (mov->use_editlist) {
5719 /* Pretend the whole stream started at pts=0, with earlier fragments
5720 * already written. If the stream started at pts=0, the duration sum
5721 * of earlier fragments would have been pkt->pts. */
5722 trk->frag_start = pkt->pts;
5723 trk->start_dts = pkt->dts - pkt->pts;
5725 /* Pretend the whole stream started at dts=0, with earlier fragments
5726 * already written, with a duration summing up to pkt->dts. */
5727 trk->frag_start = pkt->dts;
5730 trk->frag_discont = 0;
5731 } else if (pkt->dts && mov->moov_written)
5732 av_log(s, AV_LOG_WARNING,
5733 "Track %d starts with a nonzero dts %"PRId64", while the moov "
5734 "already has been written. Set the delay_moov flag to handle "
5736 pkt->stream_index, pkt->dts);
5738 trk->track_duration = pkt->dts - trk->start_dts + pkt->duration;
5739 trk->last_sample_is_subtitle_end = 0;
5741 if (pkt->pts == AV_NOPTS_VALUE) {
5742 av_log(s, AV_LOG_WARNING, "pts has no value\n");
5743 pkt->pts = pkt->dts;
5745 if (pkt->dts != pkt->pts)
5746 trk->flags |= MOV_TRACK_CTTS;
5747 trk->cluster[trk->entry].cts = pkt->pts - pkt->dts;
5748 trk->cluster[trk->entry].flags = 0;
5749 if (trk->start_cts == AV_NOPTS_VALUE)
5750 trk->start_cts = pkt->pts - pkt->dts;
5751 if (trk->end_pts == AV_NOPTS_VALUE)
5752 trk->end_pts = trk->cluster[trk->entry].dts +
5753 trk->cluster[trk->entry].cts + pkt->duration;
5755 trk->end_pts = FFMAX(trk->end_pts, trk->cluster[trk->entry].dts +
5756 trk->cluster[trk->entry].cts +
5759 if (par->codec_id == AV_CODEC_ID_VC1) {
5760 mov_parse_vc1_frame(pkt, trk);
5761 } else if (par->codec_id == AV_CODEC_ID_TRUEHD) {
5762 mov_parse_truehd_frame(pkt, trk);
5763 } else if (pkt->flags & AV_PKT_FLAG_KEY) {
5764 if (mov->mode == MODE_MOV && par->codec_id == AV_CODEC_ID_MPEG2VIDEO &&
5765 trk->entry > 0) { // force sync sample for the first key frame
5766 mov_parse_mpeg2_frame(pkt, &trk->cluster[trk->entry].flags);
5767 if (trk->cluster[trk->entry].flags & MOV_PARTIAL_SYNC_SAMPLE)
5768 trk->flags |= MOV_TRACK_STPS;
5770 trk->cluster[trk->entry].flags = MOV_SYNC_SAMPLE;
5772 if (trk->cluster[trk->entry].flags & MOV_SYNC_SAMPLE)
5773 trk->has_keyframes++;
5775 if (pkt->flags & AV_PKT_FLAG_DISPOSABLE) {
5776 trk->cluster[trk->entry].flags |= MOV_DISPOSABLE_SAMPLE;
5777 trk->has_disposable++;
5780 prft = (AVProducerReferenceTime *)av_packet_get_side_data(pkt, AV_PKT_DATA_PRFT, &prft_size);
5781 if (prft && prft_size == sizeof(AVProducerReferenceTime))
5782 memcpy(&trk->cluster[trk->entry].prft, prft, prft_size);
5784 memset(&trk->cluster[trk->entry].prft, 0, sizeof(AVProducerReferenceTime));
5787 trk->sample_count += samples_in_chunk;
5788 mov->mdat_size += size;
5790 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams)
5791 ff_mov_add_hinted_packet(s, pkt, trk->hint_track, trk->entry,
5792 reformatted_data ? reformatted_data + offset
5798 if (pkt->data != reformatted_data)
5799 av_free(reformatted_data);
5803 static int mov_write_single_packet(AVFormatContext *s, AVPacket *pkt)
5805 MOVMuxContext *mov = s->priv_data;
5806 MOVTrack *trk = &mov->tracks[pkt->stream_index];
5807 AVCodecParameters *par = trk->par;
5808 int64_t frag_duration = 0;
5809 int size = pkt->size;
5811 int ret = check_pkt(s, pkt);
5815 if (mov->flags & FF_MOV_FLAG_FRAG_DISCONT) {
5817 for (i = 0; i < s->nb_streams; i++)
5818 mov->tracks[i].frag_discont = 1;
5819 mov->flags &= ~FF_MOV_FLAG_FRAG_DISCONT;
5822 if (mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS) {
5823 if (trk->dts_shift == AV_NOPTS_VALUE)
5824 trk->dts_shift = pkt->pts - pkt->dts;
5825 pkt->dts += trk->dts_shift;
5828 if (trk->par->codec_id == AV_CODEC_ID_MP4ALS ||
5829 trk->par->codec_id == AV_CODEC_ID_AAC ||
5830 trk->par->codec_id == AV_CODEC_ID_AV1 ||
5831 trk->par->codec_id == AV_CODEC_ID_FLAC) {
5833 uint8_t *side = av_packet_get_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA, &side_size);
5834 if (side && side_size > 0 && (side_size != par->extradata_size || memcmp(side, par->extradata, side_size))) {
5835 void *newextra = av_mallocz(side_size + AV_INPUT_BUFFER_PADDING_SIZE);
5837 return AVERROR(ENOMEM);
5838 av_free(par->extradata);
5839 par->extradata = newextra;
5840 memcpy(par->extradata, side, side_size);
5841 par->extradata_size = side_size;
5842 if (!pkt->size) // Flush packet
5843 mov->need_rewrite_extradata = 1;
5848 if (trk->start_dts == AV_NOPTS_VALUE && trk->frag_discont) {
5849 trk->start_dts = pkt->dts;
5850 if (pkt->pts != AV_NOPTS_VALUE)
5851 trk->start_cts = pkt->pts - pkt->dts;
5856 return 0; /* Discard 0 sized packets */
5859 if (trk->entry && pkt->stream_index < s->nb_streams)
5860 frag_duration = av_rescale_q(pkt->dts - trk->cluster[0].dts,
5861 s->streams[pkt->stream_index]->time_base,
5863 if ((mov->max_fragment_duration &&
5864 frag_duration >= mov->max_fragment_duration) ||
5865 (mov->max_fragment_size && mov->mdat_size + size >= mov->max_fragment_size) ||
5866 (mov->flags & FF_MOV_FLAG_FRAG_KEYFRAME &&
5867 par->codec_type == AVMEDIA_TYPE_VIDEO &&
5868 trk->entry && pkt->flags & AV_PKT_FLAG_KEY) ||
5869 (mov->flags & FF_MOV_FLAG_FRAG_EVERY_FRAME)) {
5870 if (frag_duration >= mov->min_fragment_duration) {
5871 // Set the duration of this track to line up with the next
5872 // sample in this track. This avoids relying on AVPacket
5873 // duration, but only helps for this particular track, not
5874 // for the other ones that are flushed at the same time.
5875 trk->track_duration = pkt->dts - trk->start_dts;
5876 if (pkt->pts != AV_NOPTS_VALUE)
5877 trk->end_pts = pkt->pts;
5879 trk->end_pts = pkt->dts;
5880 trk->end_reliable = 1;
5881 mov_auto_flush_fragment(s, 0);
5885 return ff_mov_write_packet(s, pkt);
5888 static int mov_write_subtitle_end_packet(AVFormatContext *s,
5892 uint8_t data[2] = {0};
5895 av_init_packet(&end);
5896 end.size = sizeof(data);
5901 end.stream_index = stream_index;
5903 ret = mov_write_single_packet(s, &end);
5904 av_packet_unref(&end);
5909 static int mov_write_packet(AVFormatContext *s, AVPacket *pkt)
5911 MOVMuxContext *mov = s->priv_data;
5915 mov_flush_fragment(s, 1);
5919 trk = &mov->tracks[pkt->stream_index];
5921 if (is_cover_image(trk->st)) {
5924 if (trk->st->nb_frames >= 1) {
5925 if (trk->st->nb_frames == 1)
5926 av_log(s, AV_LOG_WARNING, "Got more than one picture in stream %d,"
5927 " ignoring.\n", pkt->stream_index);
5931 if ((ret = av_packet_ref(&trk->cover_image, pkt)) < 0)
5939 return mov_write_single_packet(s, pkt); /* Passthrough. */
5942 * Subtitles require special handling.
5944 * 1) For full complaince, every track must have a sample at
5945 * dts == 0, which is rarely true for subtitles. So, as soon
5946 * as we see any packet with dts > 0, write an empty subtitle
5947 * at dts == 0 for any subtitle track with no samples in it.
5949 * 2) For each subtitle track, check if the current packet's
5950 * dts is past the duration of the last subtitle sample. If
5951 * so, we now need to write an end sample for that subtitle.
5953 * This must be done conditionally to allow for subtitles that
5954 * immediately replace each other, in which case an end sample
5955 * is not needed, and is, in fact, actively harmful.
5957 * 3) See mov_write_trailer for how the final end sample is
5960 for (i = 0; i < mov->nb_streams; i++) {
5961 MOVTrack *trk = &mov->tracks[i];
5964 if (trk->par->codec_id == AV_CODEC_ID_MOV_TEXT &&
5965 trk->track_duration < pkt->dts &&
5966 (trk->entry == 0 || !trk->last_sample_is_subtitle_end)) {
5967 ret = mov_write_subtitle_end_packet(s, i, trk->track_duration);
5968 if (ret < 0) return ret;
5969 trk->last_sample_is_subtitle_end = 1;
5973 if (trk->mode == MODE_MOV && trk->par->codec_type == AVMEDIA_TYPE_VIDEO) {
5974 AVPacket *opkt = pkt;
5975 int reshuffle_ret, ret;
5976 if (trk->is_unaligned_qt_rgb) {
5977 int64_t bpc = trk->par->bits_per_coded_sample != 15 ? trk->par->bits_per_coded_sample : 16;
5978 int expected_stride = ((trk->par->width * bpc + 15) >> 4)*2;
5979 reshuffle_ret = ff_reshuffle_raw_rgb(s, &pkt, trk->par, expected_stride);
5980 if (reshuffle_ret < 0)
5981 return reshuffle_ret;
5984 if (trk->par->format == AV_PIX_FMT_PAL8 && !trk->pal_done) {
5985 ret = ff_get_packet_palette(s, opkt, reshuffle_ret, trk->palette);
5990 } else if (trk->par->codec_id == AV_CODEC_ID_RAWVIDEO &&
5991 (trk->par->format == AV_PIX_FMT_GRAY8 ||
5992 trk->par->format == AV_PIX_FMT_MONOBLACK)) {
5993 for (i = 0; i < pkt->size; i++)
5994 pkt->data[i] = ~pkt->data[i];
5996 if (reshuffle_ret) {
5997 ret = mov_write_single_packet(s, pkt);
6000 av_packet_free(&pkt);
6005 return mov_write_single_packet(s, pkt);
6009 // QuickTime chapters involve an additional text track with the chapter names
6010 // as samples, and a tref pointing from the other tracks to the chapter one.
6011 static int mov_create_chapter_track(AVFormatContext *s, int tracknum)
6015 MOVMuxContext *mov = s->priv_data;
6016 MOVTrack *track = &mov->tracks[tracknum];
6017 AVPacket pkt = { .stream_index = tracknum, .flags = AV_PKT_FLAG_KEY };
6020 track->mode = mov->mode;
6021 track->tag = MKTAG('t','e','x','t');
6022 track->timescale = MOV_TIMESCALE;
6023 track->par = avcodec_parameters_alloc();
6025 return AVERROR(ENOMEM);
6026 track->par->codec_type = AVMEDIA_TYPE_SUBTITLE;
6028 // These properties are required to make QT recognize the chapter track
6029 uint8_t chapter_properties[43] = { 0, 0, 0, 0, 0, 0, 0, 1, };
6030 if (ff_alloc_extradata(track->par, sizeof(chapter_properties)))
6031 return AVERROR(ENOMEM);
6032 memcpy(track->par->extradata, chapter_properties, sizeof(chapter_properties));
6034 if (avio_open_dyn_buf(&pb) >= 0) {
6038 /* Stub header (usually for Quicktime chapter track) */
6040 avio_wb32(pb, 0x01); // displayFlags
6041 avio_w8(pb, 0x00); // horizontal justification
6042 avio_w8(pb, 0x00); // vertical justification
6043 avio_w8(pb, 0x00); // bgColourRed
6044 avio_w8(pb, 0x00); // bgColourGreen
6045 avio_w8(pb, 0x00); // bgColourBlue
6046 avio_w8(pb, 0x00); // bgColourAlpha
6048 avio_wb16(pb, 0x00); // defTextBoxTop
6049 avio_wb16(pb, 0x00); // defTextBoxLeft
6050 avio_wb16(pb, 0x00); // defTextBoxBottom
6051 avio_wb16(pb, 0x00); // defTextBoxRight
6053 avio_wb16(pb, 0x00); // startChar
6054 avio_wb16(pb, 0x00); // endChar
6055 avio_wb16(pb, 0x01); // fontID
6056 avio_w8(pb, 0x00); // fontStyleFlags
6057 avio_w8(pb, 0x00); // fontSize
6058 avio_w8(pb, 0x00); // fgColourRed
6059 avio_w8(pb, 0x00); // fgColourGreen
6060 avio_w8(pb, 0x00); // fgColourBlue
6061 avio_w8(pb, 0x00); // fgColourAlpha
6063 avio_wb32(pb, 0x0D); // box size
6064 ffio_wfourcc(pb, "ftab"); // box atom name
6065 avio_wb16(pb, 0x01); // entry count
6067 avio_wb16(pb, 0x01); // font ID
6068 avio_w8(pb, 0x00); // font name length
6070 if ((size = avio_close_dyn_buf(pb, &buf)) > 0) {
6071 track->par->extradata = buf;
6072 track->par->extradata_size = size;
6079 for (i = 0; i < s->nb_chapters; i++) {
6080 AVChapter *c = s->chapters[i];
6081 AVDictionaryEntry *t;
6083 int64_t end = av_rescale_q(c->end, c->time_base, (AVRational){1,MOV_TIMESCALE});
6084 pkt.pts = pkt.dts = av_rescale_q(c->start, c->time_base, (AVRational){1,MOV_TIMESCALE});
6085 pkt.duration = end - pkt.dts;
6087 if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
6088 static const char encd[12] = {
6089 0x00, 0x00, 0x00, 0x0C,
6091 0x00, 0x00, 0x01, 0x00 };
6092 len = strlen(t->value);
6093 pkt.size = len + 2 + 12;
6094 pkt.data = av_malloc(pkt.size);
6096 return AVERROR(ENOMEM);
6097 AV_WB16(pkt.data, len);
6098 memcpy(pkt.data + 2, t->value, len);
6099 memcpy(pkt.data + len + 2, encd, sizeof(encd));
6100 ff_mov_write_packet(s, &pkt);
6101 av_freep(&pkt.data);
6109 static int mov_check_timecode_track(AVFormatContext *s, AVTimecode *tc, int src_index, const char *tcstr)
6113 /* compute the frame number */
6114 ret = av_timecode_init_from_string(tc, find_fps(s, s->streams[src_index]), tcstr, s);
6118 static int mov_create_timecode_track(AVFormatContext *s, int index, int src_index, AVTimecode tc)
6121 MOVMuxContext *mov = s->priv_data;
6122 MOVTrack *track = &mov->tracks[index];
6123 AVStream *src_st = s->streams[src_index];
6124 AVPacket pkt = {.stream_index = index, .flags = AV_PKT_FLAG_KEY, .size = 4};
6125 AVRational rate = find_fps(s, src_st);
6127 /* tmcd track based on video stream */
6128 track->mode = mov->mode;
6129 track->tag = MKTAG('t','m','c','d');
6130 track->src_track = src_index;
6131 track->timescale = mov->tracks[src_index].timescale;
6132 if (tc.flags & AV_TIMECODE_FLAG_DROPFRAME)
6133 track->timecode_flags |= MOV_TIMECODE_FLAG_DROPFRAME;
6135 /* set st to src_st for metadata access*/
6138 /* encode context: tmcd data stream */
6139 track->par = avcodec_parameters_alloc();
6141 return AVERROR(ENOMEM);
6142 track->par->codec_type = AVMEDIA_TYPE_DATA;
6143 track->par->codec_tag = track->tag;
6144 track->st->avg_frame_rate = av_inv_q(rate);
6146 /* the tmcd track just contains one packet with the frame number */
6147 pkt.data = av_malloc(pkt.size);
6149 return AVERROR(ENOMEM);
6150 AV_WB32(pkt.data, tc.start);
6151 ret = ff_mov_write_packet(s, &pkt);
6157 * st->disposition controls the "enabled" flag in the tkhd tag.
6158 * QuickTime will not play a track if it is not enabled. So make sure
6159 * that one track of each type (audio, video, subtitle) is enabled.
6161 * Subtitles are special. For audio and video, setting "enabled" also
6162 * makes the track "default" (i.e. it is rendered when played). For
6163 * subtitles, an "enabled" subtitle is not rendered by default, but
6164 * if no subtitle is enabled, the subtitle menu in QuickTime will be
6167 static void enable_tracks(AVFormatContext *s)
6169 MOVMuxContext *mov = s->priv_data;
6171 int enabled[AVMEDIA_TYPE_NB];
6172 int first[AVMEDIA_TYPE_NB];
6174 for (i = 0; i < AVMEDIA_TYPE_NB; i++) {
6179 for (i = 0; i < s->nb_streams; i++) {
6180 AVStream *st = s->streams[i];
6182 if (st->codecpar->codec_type <= AVMEDIA_TYPE_UNKNOWN ||
6183 st->codecpar->codec_type >= AVMEDIA_TYPE_NB ||
6187 if (first[st->codecpar->codec_type] < 0)
6188 first[st->codecpar->codec_type] = i;
6189 if (st->disposition & AV_DISPOSITION_DEFAULT) {
6190 mov->tracks[i].flags |= MOV_TRACK_ENABLED;
6191 enabled[st->codecpar->codec_type]++;
6195 for (i = 0; i < AVMEDIA_TYPE_NB; i++) {
6197 case AVMEDIA_TYPE_VIDEO:
6198 case AVMEDIA_TYPE_AUDIO:
6199 case AVMEDIA_TYPE_SUBTITLE:
6201 mov->per_stream_grouping = 1;
6202 if (!enabled[i] && first[i] >= 0)
6203 mov->tracks[first[i]].flags |= MOV_TRACK_ENABLED;
6209 static void mov_free(AVFormatContext *s)
6211 MOVMuxContext *mov = s->priv_data;
6214 if (mov->chapter_track) {
6215 if (mov->tracks[mov->chapter_track].par)
6216 av_freep(&mov->tracks[mov->chapter_track].par->extradata);
6217 av_freep(&mov->tracks[mov->chapter_track].par);
6220 for (i = 0; i < mov->nb_streams; i++) {
6221 if (mov->tracks[i].tag == MKTAG('r','t','p',' '))
6222 ff_mov_close_hinting(&mov->tracks[i]);
6223 else if (mov->tracks[i].tag == MKTAG('t','m','c','d') && mov->nb_meta_tmcd)
6224 av_freep(&mov->tracks[i].par);
6225 av_freep(&mov->tracks[i].cluster);
6226 av_freep(&mov->tracks[i].frag_info);
6227 av_packet_unref(&mov->tracks[i].cover_image);
6229 if (mov->tracks[i].eac3_priv) {
6230 struct eac3_info *info = mov->tracks[i].eac3_priv;
6231 av_packet_unref(&info->pkt);
6232 av_freep(&mov->tracks[i].eac3_priv);
6234 if (mov->tracks[i].vos_len)
6235 av_freep(&mov->tracks[i].vos_data);
6237 ff_mov_cenc_free(&mov->tracks[i].cenc);
6240 av_freep(&mov->tracks);
6243 static uint32_t rgb_to_yuv(uint32_t rgb)
6248 r = (rgb >> 16) & 0xFF;
6249 g = (rgb >> 8) & 0xFF;
6252 y = av_clip_uint8(( 16000 + 257 * r + 504 * g + 98 * b)/1000);
6253 cb = av_clip_uint8((128000 - 148 * r - 291 * g + 439 * b)/1000);
6254 cr = av_clip_uint8((128000 + 439 * r - 368 * g - 71 * b)/1000);
6256 return (y << 16) | (cr << 8) | cb;
6259 static int mov_create_dvd_sub_decoder_specific_info(MOVTrack *track,
6262 int i, width = 720, height = 480;
6263 int have_palette = 0, have_size = 0;
6264 uint32_t palette[16];
6265 char *cur = st->codecpar->extradata;
6267 while (cur && *cur) {
6268 if (strncmp("palette:", cur, 8) == 0) {
6270 count = sscanf(cur + 8,
6271 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
6272 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
6273 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
6274 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32"",
6275 &palette[ 0], &palette[ 1], &palette[ 2], &palette[ 3],
6276 &palette[ 4], &palette[ 5], &palette[ 6], &palette[ 7],
6277 &palette[ 8], &palette[ 9], &palette[10], &palette[11],
6278 &palette[12], &palette[13], &palette[14], &palette[15]);
6280 for (i = 0; i < count; i++) {
6281 palette[i] = rgb_to_yuv(palette[i]);
6284 } else if (!strncmp("size:", cur, 5)) {
6285 sscanf(cur + 5, "%dx%d", &width, &height);
6288 if (have_palette && have_size)
6290 cur += strcspn(cur, "\n\r");
6291 cur += strspn(cur, "\n\r");
6294 track->vos_data = av_malloc(16*4 + AV_INPUT_BUFFER_PADDING_SIZE);
6295 if (!track->vos_data)
6296 return AVERROR(ENOMEM);
6297 for (i = 0; i < 16; i++) {
6298 AV_WB32(track->vos_data + i * 4, palette[i]);
6300 memset(track->vos_data + 16*4, 0, AV_INPUT_BUFFER_PADDING_SIZE);
6301 track->vos_len = 16 * 4;
6303 st->codecpar->width = width;
6304 st->codecpar->height = track->height = height;
6309 static int mov_init(AVFormatContext *s)
6311 MOVMuxContext *mov = s->priv_data;
6312 AVDictionaryEntry *global_tcr = av_dict_get(s->metadata, "timecode", NULL, 0);
6317 /* Default mode == MP4 */
6318 mov->mode = MODE_MP4;
6321 if (!strcmp("3gp", s->oformat->name)) mov->mode = MODE_3GP;
6322 else if (!strcmp("3g2", s->oformat->name)) mov->mode = MODE_3GP|MODE_3G2;
6323 else if (!strcmp("mov", s->oformat->name)) mov->mode = MODE_MOV;
6324 else if (!strcmp("psp", s->oformat->name)) mov->mode = MODE_PSP;
6325 else if (!strcmp("ipod",s->oformat->name)) mov->mode = MODE_IPOD;
6326 else if (!strcmp("ismv",s->oformat->name)) mov->mode = MODE_ISM;
6327 else if (!strcmp("f4v", s->oformat->name)) mov->mode = MODE_F4V;
6330 if (mov->flags & FF_MOV_FLAG_DELAY_MOOV)
6331 mov->flags |= FF_MOV_FLAG_EMPTY_MOOV;
6333 /* Set the FRAGMENT flag if any of the fragmentation methods are
6335 if (mov->max_fragment_duration || mov->max_fragment_size ||
6336 mov->flags & (FF_MOV_FLAG_EMPTY_MOOV |
6337 FF_MOV_FLAG_FRAG_KEYFRAME |
6338 FF_MOV_FLAG_FRAG_CUSTOM |
6339 FF_MOV_FLAG_FRAG_EVERY_FRAME))
6340 mov->flags |= FF_MOV_FLAG_FRAGMENT;
6342 /* Set other implicit flags immediately */
6343 if (mov->mode == MODE_ISM)
6344 mov->flags |= FF_MOV_FLAG_EMPTY_MOOV | FF_MOV_FLAG_SEPARATE_MOOF |
6345 FF_MOV_FLAG_FRAGMENT | FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS;
6346 if (mov->flags & FF_MOV_FLAG_DASH)
6347 mov->flags |= FF_MOV_FLAG_FRAGMENT | FF_MOV_FLAG_EMPTY_MOOV |
6348 FF_MOV_FLAG_DEFAULT_BASE_MOOF;
6349 if (mov->flags & FF_MOV_FLAG_CMAF)
6350 mov->flags |= FF_MOV_FLAG_FRAGMENT | FF_MOV_FLAG_EMPTY_MOOV |
6351 FF_MOV_FLAG_DEFAULT_BASE_MOOF | FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS;
6353 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV && s->flags & AVFMT_FLAG_AUTO_BSF) {
6354 av_log(s, AV_LOG_VERBOSE, "Empty MOOV enabled; disabling automatic bitstream filtering\n");
6355 s->flags &= ~AVFMT_FLAG_AUTO_BSF;
6358 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX && mov->flags & FF_MOV_FLAG_SKIP_SIDX) {
6359 av_log(s, AV_LOG_WARNING, "Global SIDX enabled; Ignoring skip_sidx option\n");
6360 mov->flags &= ~FF_MOV_FLAG_SKIP_SIDX;
6363 if (mov->flags & FF_MOV_FLAG_FASTSTART) {
6364 mov->reserved_moov_size = -1;
6367 if (mov->use_editlist < 0) {
6368 mov->use_editlist = 1;
6369 if (mov->flags & FF_MOV_FLAG_FRAGMENT &&
6370 !(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
6371 // If we can avoid needing an edit list by shifting the
6372 // tracks, prefer that over (trying to) write edit lists
6373 // in fragmented output.
6374 if (s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO ||
6375 s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO)
6376 mov->use_editlist = 0;
6378 if (mov->flags & FF_MOV_FLAG_CMAF) {
6379 // CMAF Track requires negative cts offsets without edit lists
6380 mov->use_editlist = 0;
6383 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV &&
6384 !(mov->flags & FF_MOV_FLAG_DELAY_MOOV) && mov->use_editlist)
6385 av_log(s, AV_LOG_WARNING, "No meaningful edit list will be written when using empty_moov without delay_moov\n");
6387 if (mov->flags & FF_MOV_FLAG_CMAF && mov->use_editlist) {
6388 av_log(s, AV_LOG_WARNING, "Edit list enabled; Assuming writing CMAF Track File\n");
6389 mov->flags &= ~FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS;
6391 if (!mov->use_editlist && s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO &&
6392 !(mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS))
6393 s->avoid_negative_ts = AVFMT_AVOID_NEG_TS_MAKE_ZERO;
6395 /* Clear the omit_tfhd_offset flag if default_base_moof is set;
6396 * if the latter is set that's enough and omit_tfhd_offset doesn't
6397 * add anything extra on top of that. */
6398 if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET &&
6399 mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)
6400 mov->flags &= ~FF_MOV_FLAG_OMIT_TFHD_OFFSET;
6402 if (mov->frag_interleave &&
6403 mov->flags & (FF_MOV_FLAG_OMIT_TFHD_OFFSET | FF_MOV_FLAG_SEPARATE_MOOF)) {
6404 av_log(s, AV_LOG_ERROR,
6405 "Sample interleaving in fragments is mutually exclusive with "
6406 "omit_tfhd_offset and separate_moof\n");
6407 return AVERROR(EINVAL);
6410 /* Non-seekable output is ok if using fragmentation. If ism_lookahead
6411 * is enabled, we don't support non-seekable output at all. */
6412 if (!(s->pb->seekable & AVIO_SEEKABLE_NORMAL) &&
6413 (!(mov->flags & FF_MOV_FLAG_FRAGMENT) || mov->ism_lookahead)) {
6414 av_log(s, AV_LOG_ERROR, "muxer does not support non seekable output\n");
6415 return AVERROR(EINVAL);
6418 mov->nb_streams = s->nb_streams;
6419 if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters)
6420 mov->chapter_track = mov->nb_streams++;
6422 if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
6423 for (i = 0; i < s->nb_streams; i++)
6424 if (rtp_hinting_needed(s->streams[i]))
6428 if ( mov->write_tmcd == -1 && (mov->mode == MODE_MOV || mov->mode == MODE_MP4)
6429 || mov->write_tmcd == 1) {
6430 /* +1 tmcd track for each video stream with a timecode */
6431 for (i = 0; i < s->nb_streams; i++) {
6432 AVStream *st = s->streams[i];
6433 AVDictionaryEntry *t = global_tcr;
6434 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
6435 (t || (t=av_dict_get(st->metadata, "timecode", NULL, 0)))) {
6437 ret = mov_check_timecode_track(s, &tc, i, t->value);
6439 mov->nb_meta_tmcd++;
6443 /* check if there is already a tmcd track to remux */
6444 if (mov->nb_meta_tmcd) {
6445 for (i = 0; i < s->nb_streams; i++) {
6446 AVStream *st = s->streams[i];
6447 if (st->codecpar->codec_tag == MKTAG('t','m','c','d')) {
6448 av_log(s, AV_LOG_WARNING, "You requested a copy of the original timecode track "
6449 "so timecode metadata are now ignored\n");
6450 mov->nb_meta_tmcd = 0;
6455 mov->nb_streams += mov->nb_meta_tmcd;
6458 // Reserve an extra stream for chapters for the case where chapters
6459 // are written in the trailer
6460 mov->tracks = av_mallocz_array((mov->nb_streams + 1), sizeof(*mov->tracks));
6462 return AVERROR(ENOMEM);
6464 if (mov->encryption_scheme_str != NULL && strcmp(mov->encryption_scheme_str, "none") != 0) {
6465 if (strcmp(mov->encryption_scheme_str, "cenc-aes-ctr") == 0) {
6466 mov->encryption_scheme = MOV_ENC_CENC_AES_CTR;
6468 if (mov->encryption_key_len != AES_CTR_KEY_SIZE) {
6469 av_log(s, AV_LOG_ERROR, "Invalid encryption key len %d expected %d\n",
6470 mov->encryption_key_len, AES_CTR_KEY_SIZE);
6471 return AVERROR(EINVAL);
6474 if (mov->encryption_kid_len != CENC_KID_SIZE) {
6475 av_log(s, AV_LOG_ERROR, "Invalid encryption kid len %d expected %d\n",
6476 mov->encryption_kid_len, CENC_KID_SIZE);
6477 return AVERROR(EINVAL);
6480 av_log(s, AV_LOG_ERROR, "unsupported encryption scheme %s\n",
6481 mov->encryption_scheme_str);
6482 return AVERROR(EINVAL);
6486 for (i = 0; i < s->nb_streams; i++) {
6487 AVStream *st= s->streams[i];
6488 MOVTrack *track= &mov->tracks[i];
6489 AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0);
6492 track->par = st->codecpar;
6493 track->language = ff_mov_iso639_to_lang(lang?lang->value:"und", mov->mode!=MODE_MOV);
6494 if (track->language < 0)
6495 track->language = 32767; // Unspecified Macintosh language code
6496 track->mode = mov->mode;
6497 track->tag = mov_find_codec_tag(s, track);
6499 av_log(s, AV_LOG_ERROR, "Could not find tag for codec %s in stream #%d, "
6500 "codec not currently supported in container\n",
6501 avcodec_get_name(st->codecpar->codec_id), i);
6502 return AVERROR(EINVAL);
6504 /* If hinting of this track is enabled by a later hint track,
6505 * this is updated. */
6506 track->hint_track = -1;
6507 track->start_dts = AV_NOPTS_VALUE;
6508 track->start_cts = AV_NOPTS_VALUE;
6509 track->end_pts = AV_NOPTS_VALUE;
6510 track->dts_shift = AV_NOPTS_VALUE;
6511 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
6512 if (track->tag == MKTAG('m','x','3','p') || track->tag == MKTAG('m','x','3','n') ||
6513 track->tag == MKTAG('m','x','4','p') || track->tag == MKTAG('m','x','4','n') ||
6514 track->tag == MKTAG('m','x','5','p') || track->tag == MKTAG('m','x','5','n')) {
6515 if (st->codecpar->width != 720 || (st->codecpar->height != 608 && st->codecpar->height != 512)) {
6516 av_log(s, AV_LOG_ERROR, "D-10/IMX must use 720x608 or 720x512 video resolution\n");
6517 return AVERROR(EINVAL);
6519 track->height = track->tag >> 24 == 'n' ? 486 : 576;
6521 if (mov->video_track_timescale) {
6522 track->timescale = mov->video_track_timescale;
6523 if (mov->mode == MODE_ISM && mov->video_track_timescale != 10000000)
6524 av_log(s, AV_LOG_WARNING, "Warning: some tools, like mp4split, assume a timescale of 10000000 for ISMV.\n");
6526 track->timescale = st->time_base.den;
6527 while(track->timescale < 10000)
6528 track->timescale *= 2;
6530 if (st->codecpar->width > 65535 || st->codecpar->height > 65535) {
6531 av_log(s, AV_LOG_ERROR, "Resolution %dx%d too large for mov/mp4\n", st->codecpar->width, st->codecpar->height);
6532 return AVERROR(EINVAL);
6534 if (track->mode == MODE_MOV && track->timescale > 100000)
6535 av_log(s, AV_LOG_WARNING,
6536 "WARNING codec timebase is very high. If duration is too long,\n"
6537 "file may not be playable by quicktime. Specify a shorter timebase\n"
6538 "or choose different container.\n");
6539 if (track->mode == MODE_MOV &&
6540 track->par->codec_id == AV_CODEC_ID_RAWVIDEO &&
6541 track->tag == MKTAG('r','a','w',' ')) {
6542 enum AVPixelFormat pix_fmt = track->par->format;
6543 if (pix_fmt == AV_PIX_FMT_NONE && track->par->bits_per_coded_sample == 1)
6544 pix_fmt = AV_PIX_FMT_MONOWHITE;
6545 track->is_unaligned_qt_rgb =
6546 pix_fmt == AV_PIX_FMT_RGB24 ||
6547 pix_fmt == AV_PIX_FMT_BGR24 ||
6548 pix_fmt == AV_PIX_FMT_PAL8 ||
6549 pix_fmt == AV_PIX_FMT_GRAY8 ||
6550 pix_fmt == AV_PIX_FMT_MONOWHITE ||
6551 pix_fmt == AV_PIX_FMT_MONOBLACK;
6553 if (track->par->codec_id == AV_CODEC_ID_VP9 ||
6554 track->par->codec_id == AV_CODEC_ID_AV1) {
6555 if (track->mode != MODE_MP4) {
6556 av_log(s, AV_LOG_ERROR, "%s only supported in MP4.\n", avcodec_get_name(track->par->codec_id));
6557 return AVERROR(EINVAL);
6559 } else if (track->par->codec_id == AV_CODEC_ID_VP8) {
6560 /* altref frames handling is not defined in the spec as of version v1.0,
6561 * so just forbid muxing VP8 streams altogether until a new version does */
6562 av_log(s, AV_LOG_ERROR, "VP8 muxing is currently not supported.\n");
6563 return AVERROR_PATCHWELCOME;
6565 } else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
6566 track->timescale = st->codecpar->sample_rate;
6567 if (!st->codecpar->frame_size && !av_get_bits_per_sample(st->codecpar->codec_id)) {
6568 av_log(s, AV_LOG_WARNING, "track %d: codec frame size is not set\n", i);
6569 track->audio_vbr = 1;
6570 }else if (st->codecpar->codec_id == AV_CODEC_ID_ADPCM_MS ||
6571 st->codecpar->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
6572 st->codecpar->codec_id == AV_CODEC_ID_ILBC){
6573 if (!st->codecpar->block_align) {
6574 av_log(s, AV_LOG_ERROR, "track %d: codec block align is not set for adpcm\n", i);
6575 return AVERROR(EINVAL);
6577 track->sample_size = st->codecpar->block_align;
6578 }else if (st->codecpar->frame_size > 1){ /* assume compressed audio */
6579 track->audio_vbr = 1;
6581 track->sample_size = (av_get_bits_per_sample(st->codecpar->codec_id) >> 3) * st->codecpar->channels;
6583 if (st->codecpar->codec_id == AV_CODEC_ID_ILBC ||
6584 st->codecpar->codec_id == AV_CODEC_ID_ADPCM_IMA_QT) {
6585 track->audio_vbr = 1;
6587 if (track->mode != MODE_MOV &&
6588 track->par->codec_id == AV_CODEC_ID_MP3 && track->timescale < 16000) {
6589 if (s->strict_std_compliance >= FF_COMPLIANCE_NORMAL) {
6590 av_log(s, AV_LOG_ERROR, "track %d: muxing mp3 at %dhz is not standard, to mux anyway set strict to -1\n",
6591 i, track->par->sample_rate);
6592 return AVERROR(EINVAL);
6594 av_log(s, AV_LOG_WARNING, "track %d: muxing mp3 at %dhz is not standard in MP4\n",
6595 i, track->par->sample_rate);
6598 if (track->par->codec_id == AV_CODEC_ID_FLAC ||
6599 track->par->codec_id == AV_CODEC_ID_TRUEHD ||
6600 track->par->codec_id == AV_CODEC_ID_OPUS) {
6601 if (track->mode != MODE_MP4) {
6602 av_log(s, AV_LOG_ERROR, "%s only supported in MP4.\n", avcodec_get_name(track->par->codec_id));
6603 return AVERROR(EINVAL);
6605 if (track->par->codec_id != AV_CODEC_ID_OPUS &&
6606 s->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
6607 av_log(s, AV_LOG_ERROR,
6608 "%s in MP4 support is experimental, add "
6609 "'-strict %d' if you want to use it.\n",
6610 avcodec_get_name(track->par->codec_id), FF_COMPLIANCE_EXPERIMENTAL);
6611 return AVERROR_EXPERIMENTAL;
6614 } else if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) {
6615 track->timescale = st->time_base.den;
6616 } else if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA) {
6617 track->timescale = st->time_base.den;
6619 track->timescale = MOV_TIMESCALE;
6622 track->height = st->codecpar->height;
6623 /* The Protected Interoperable File Format (PIFF) standard, used by ISMV recommends but
6624 doesn't mandate a track timescale of 10,000,000. The muxer allows a custom timescale
6625 for video tracks, so if user-set, it isn't overwritten */
6626 if (mov->mode == MODE_ISM &&
6627 (st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO ||
6628 (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && !mov->video_track_timescale))) {
6629 track->timescale = 10000000;
6632 avpriv_set_pts_info(st, 64, 1, track->timescale);
6634 if (mov->encryption_scheme == MOV_ENC_CENC_AES_CTR) {
6635 ret = ff_mov_cenc_init(&track->cenc, mov->encryption_key,
6636 track->par->codec_id == AV_CODEC_ID_H264, s->flags & AVFMT_FLAG_BITEXACT);
6646 static int mov_write_header(AVFormatContext *s)
6648 AVIOContext *pb = s->pb;
6649 MOVMuxContext *mov = s->priv_data;
6650 AVDictionaryEntry *t, *global_tcr = av_dict_get(s->metadata, "timecode", NULL, 0);
6651 int i, ret, hint_track = 0, tmcd_track = 0, nb_tracks = s->nb_streams;
6653 if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters)
6656 if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
6657 hint_track = nb_tracks;
6658 for (i = 0; i < s->nb_streams; i++)
6659 if (rtp_hinting_needed(s->streams[i]))
6663 if (mov->nb_meta_tmcd)
6664 tmcd_track = nb_tracks;
6666 for (i = 0; i < s->nb_streams; i++) {
6668 AVStream *st= s->streams[i];
6669 MOVTrack *track= &mov->tracks[i];
6671 /* copy extradata if it exists */
6672 if (st->codecpar->extradata_size) {
6673 if (st->codecpar->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
6674 mov_create_dvd_sub_decoder_specific_info(track, st);
6675 else if (!TAG_IS_AVCI(track->tag) && st->codecpar->codec_id != AV_CODEC_ID_DNXHD) {
6676 track->vos_len = st->codecpar->extradata_size;
6677 track->vos_data = av_malloc(track->vos_len + AV_INPUT_BUFFER_PADDING_SIZE);
6678 if (!track->vos_data) {
6679 return AVERROR(ENOMEM);
6681 memcpy(track->vos_data, st->codecpar->extradata, track->vos_len);
6682 memset(track->vos_data + track->vos_len, 0, AV_INPUT_BUFFER_PADDING_SIZE);
6686 if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ||
6687 track->par->channel_layout != AV_CH_LAYOUT_MONO)
6690 for (j = 0; j < s->nb_streams; j++) {
6691 AVStream *stj= s->streams[j];
6692 MOVTrack *trackj= &mov->tracks[j];
6696 if (stj->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ||
6697 trackj->par->channel_layout != AV_CH_LAYOUT_MONO ||
6698 trackj->language != track->language ||
6699 trackj->tag != track->tag
6702 track->multichannel_as_mono++;
6706 if (!(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
6707 if ((ret = mov_write_identification(pb, s)) < 0)
6711 if (mov->reserved_moov_size){
6712 mov->reserved_header_pos = avio_tell(pb);
6713 if (mov->reserved_moov_size > 0)
6714 avio_skip(pb, mov->reserved_moov_size);
6717 if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
6718 /* If no fragmentation options have been set, set a default. */
6719 if (!(mov->flags & (FF_MOV_FLAG_FRAG_KEYFRAME |
6720 FF_MOV_FLAG_FRAG_CUSTOM |
6721 FF_MOV_FLAG_FRAG_EVERY_FRAME)) &&
6722 !mov->max_fragment_duration && !mov->max_fragment_size)
6723 mov->flags |= FF_MOV_FLAG_FRAG_KEYFRAME;
6725 if (mov->flags & FF_MOV_FLAG_FASTSTART)
6726 mov->reserved_header_pos = avio_tell(pb);
6727 mov_write_mdat_tag(pb, mov);
6730 ff_parse_creation_time_metadata(s, &mov->time, 1);
6732 mov->time += 0x7C25B080; // 1970 based -> 1904 based
6734 if (mov->chapter_track)
6735 if ((ret = mov_create_chapter_track(s, mov->chapter_track)) < 0)
6738 if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
6739 for (i = 0; i < s->nb_streams; i++) {
6740 if (rtp_hinting_needed(s->streams[i])) {
6741 if ((ret = ff_mov_init_hinting(s, hint_track, i)) < 0)
6748 if (mov->nb_meta_tmcd) {
6749 /* Initialize the tmcd tracks */
6750 for (i = 0; i < s->nb_streams; i++) {
6751 AVStream *st = s->streams[i];
6754 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
6757 t = av_dict_get(st->metadata, "timecode", NULL, 0);
6760 if (mov_check_timecode_track(s, &tc, i, t->value) < 0)
6762 if ((ret = mov_create_timecode_track(s, tmcd_track, i, tc)) < 0)
6771 if (mov->flags & FF_MOV_FLAG_ISML)
6772 mov_write_isml_manifest(pb, mov, s);
6774 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV &&
6775 !(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
6776 if ((ret = mov_write_moov_tag(pb, mov, s)) < 0)
6778 mov->moov_written = 1;
6779 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
6780 mov->reserved_header_pos = avio_tell(pb);
6786 static int get_moov_size(AVFormatContext *s)
6789 AVIOContext *moov_buf;
6790 MOVMuxContext *mov = s->priv_data;
6792 if ((ret = ffio_open_null_buf(&moov_buf)) < 0)
6794 if ((ret = mov_write_moov_tag(moov_buf, mov, s)) < 0)
6796 return ffio_close_null_buf(moov_buf);
6799 static int get_sidx_size(AVFormatContext *s)
6803 MOVMuxContext *mov = s->priv_data;
6805 if ((ret = ffio_open_null_buf(&buf)) < 0)
6807 mov_write_sidx_tags(buf, mov, -1, 0);
6808 return ffio_close_null_buf(buf);
6812 * This function gets the moov size if moved to the top of the file: the chunk
6813 * offset table can switch between stco (32-bit entries) to co64 (64-bit
6814 * entries) when the moov is moved to the beginning, so the size of the moov
6815 * would change. It also updates the chunk offset tables.
6817 static int compute_moov_size(AVFormatContext *s)
6819 int i, moov_size, moov_size2;
6820 MOVMuxContext *mov = s->priv_data;
6822 moov_size = get_moov_size(s);
6826 for (i = 0; i < mov->nb_streams; i++)
6827 mov->tracks[i].data_offset += moov_size;
6829 moov_size2 = get_moov_size(s);
6833 /* if the size changed, we just switched from stco to co64 and need to
6834 * update the offsets */
6835 if (moov_size2 != moov_size)
6836 for (i = 0; i < mov->nb_streams; i++)
6837 mov->tracks[i].data_offset += moov_size2 - moov_size;
6842 static int compute_sidx_size(AVFormatContext *s)
6845 MOVMuxContext *mov = s->priv_data;
6847 sidx_size = get_sidx_size(s);
6851 for (i = 0; i < mov->nb_streams; i++)
6852 mov->tracks[i].data_offset += sidx_size;
6857 static int shift_data(AVFormatContext *s)
6859 int ret = 0, moov_size;
6860 MOVMuxContext *mov = s->priv_data;
6861 int64_t pos, pos_end;
6862 uint8_t *buf, *read_buf[2];
6863 int read_buf_id = 0;
6865 AVIOContext *read_pb;
6867 if (mov->flags & FF_MOV_FLAG_FRAGMENT)
6868 moov_size = compute_sidx_size(s);
6870 moov_size = compute_moov_size(s);
6874 buf = av_malloc(moov_size * 2);
6876 return AVERROR(ENOMEM);
6878 read_buf[1] = buf + moov_size;
6880 /* Shift the data: the AVIO context of the output can only be used for
6881 * writing, so we re-open the same output, but for reading. It also avoids
6882 * a read/seek/write/seek back and forth. */
6884 ret = s->io_open(s, &read_pb, s->url, AVIO_FLAG_READ, NULL);
6886 av_log(s, AV_LOG_ERROR, "Unable to re-open %s output file for "
6887 "the second pass (faststart)\n", s->url);
6891 /* mark the end of the shift to up to the last data we wrote, and get ready
6893 pos_end = avio_tell(s->pb);
6894 avio_seek(s->pb, mov->reserved_header_pos + moov_size, SEEK_SET);
6896 /* start reading at where the new moov will be placed */
6897 avio_seek(read_pb, mov->reserved_header_pos, SEEK_SET);
6898 pos = avio_tell(read_pb);
6900 #define READ_BLOCK do { \
6901 read_size[read_buf_id] = avio_read(read_pb, read_buf[read_buf_id], moov_size); \
6905 /* shift data by chunk of at most moov_size */
6910 n = read_size[read_buf_id];
6913 avio_write(s->pb, read_buf[read_buf_id], n);
6915 } while (pos < pos_end);
6916 ff_format_io_close(s, &read_pb);
6923 static int mov_write_trailer(AVFormatContext *s)
6925 MOVMuxContext *mov = s->priv_data;
6926 AVIOContext *pb = s->pb;
6931 if (mov->need_rewrite_extradata) {
6932 for (i = 0; i < s->nb_streams; i++) {
6933 MOVTrack *track = &mov->tracks[i];
6934 AVCodecParameters *par = track->par;
6936 track->vos_len = par->extradata_size;
6937 track->vos_data = av_malloc(track->vos_len + AV_INPUT_BUFFER_PADDING_SIZE);
6938 if (!track->vos_data)
6939 return AVERROR(ENOMEM);
6940 memcpy(track->vos_data, par->extradata, track->vos_len);
6941 memset(track->vos_data + track->vos_len, 0, AV_INPUT_BUFFER_PADDING_SIZE);
6943 mov->need_rewrite_extradata = 0;
6947 * Before actually writing the trailer, make sure that there are no
6948 * dangling subtitles, that need a terminating sample.
6950 for (i = 0; i < mov->nb_streams; i++) {
6951 MOVTrack *trk = &mov->tracks[i];
6952 if (trk->par->codec_id == AV_CODEC_ID_MOV_TEXT &&
6953 !trk->last_sample_is_subtitle_end) {
6954 mov_write_subtitle_end_packet(s, i, trk->track_duration);
6955 trk->last_sample_is_subtitle_end = 1;
6959 // If there were no chapters when the header was written, but there
6960 // are chapters now, write them in the trailer. This only works
6961 // when we are not doing fragments.
6962 if (!mov->chapter_track && !(mov->flags & FF_MOV_FLAG_FRAGMENT)) {
6963 if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters) {
6964 mov->chapter_track = mov->nb_streams++;
6965 if ((res = mov_create_chapter_track(s, mov->chapter_track)) < 0)
6970 if (!(mov->flags & FF_MOV_FLAG_FRAGMENT)) {
6971 moov_pos = avio_tell(pb);
6973 /* Write size of mdat tag */
6974 if (mov->mdat_size + 8 <= UINT32_MAX) {
6975 avio_seek(pb, mov->mdat_pos, SEEK_SET);
6976 avio_wb32(pb, mov->mdat_size + 8);
6978 /* overwrite 'wide' placeholder atom */
6979 avio_seek(pb, mov->mdat_pos - 8, SEEK_SET);
6980 /* special value: real atom size will be 64 bit value after
6983 ffio_wfourcc(pb, "mdat");
6984 avio_wb64(pb, mov->mdat_size + 16);
6986 avio_seek(pb, mov->reserved_moov_size > 0 ? mov->reserved_header_pos : moov_pos, SEEK_SET);
6988 if (mov->flags & FF_MOV_FLAG_FASTSTART) {
6989 av_log(s, AV_LOG_INFO, "Starting second pass: moving the moov atom to the beginning of the file\n");
6990 res = shift_data(s);
6993 avio_seek(pb, mov->reserved_header_pos, SEEK_SET);
6994 if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
6996 } else if (mov->reserved_moov_size > 0) {
6998 if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
7000 size = mov->reserved_moov_size - (avio_tell(pb) - mov->reserved_header_pos);
7002 av_log(s, AV_LOG_ERROR, "reserved_moov_size is too small, needed %"PRId64" additional\n", 8-size);
7003 return AVERROR(EINVAL);
7005 avio_wb32(pb, size);
7006 ffio_wfourcc(pb, "free");
7007 ffio_fill(pb, 0, size - 8);
7008 avio_seek(pb, moov_pos, SEEK_SET);
7010 if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
7015 mov_auto_flush_fragment(s, 1);
7016 for (i = 0; i < mov->nb_streams; i++)
7017 mov->tracks[i].data_offset = 0;
7018 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) {
7020 av_log(s, AV_LOG_INFO, "Starting second pass: inserting sidx atoms\n");
7021 res = shift_data(s);
7024 end = avio_tell(pb);
7025 avio_seek(pb, mov->reserved_header_pos, SEEK_SET);
7026 mov_write_sidx_tags(pb, mov, -1, 0);
7027 avio_seek(pb, end, SEEK_SET);
7029 if (!(mov->flags & FF_MOV_FLAG_SKIP_TRAILER)) {
7030 avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_TRAILER);
7031 res = mov_write_mfra_tag(pb, mov);
7040 static int mov_check_bitstream(struct AVFormatContext *s, const AVPacket *pkt)
7043 AVStream *st = s->streams[pkt->stream_index];
7045 if (st->codecpar->codec_id == AV_CODEC_ID_AAC) {
7046 if (pkt->size > 2 && (AV_RB16(pkt->data) & 0xfff0) == 0xfff0)
7047 ret = ff_stream_add_bitstream_filter(st, "aac_adtstoasc", NULL);
7048 } else if (st->codecpar->codec_id == AV_CODEC_ID_VP9) {
7049 ret = ff_stream_add_bitstream_filter(st, "vp9_superframe", NULL);
7055 static const AVCodecTag codec_3gp_tags[] = {
7056 { AV_CODEC_ID_H263, MKTAG('s','2','6','3') },
7057 { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
7058 { AV_CODEC_ID_MPEG4, MKTAG('m','p','4','v') },
7059 { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
7060 { AV_CODEC_ID_AMR_NB, MKTAG('s','a','m','r') },
7061 { AV_CODEC_ID_AMR_WB, MKTAG('s','a','w','b') },
7062 { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
7063 { AV_CODEC_ID_NONE, 0 },
7066 const AVCodecTag codec_mp4_tags[] = {
7067 { AV_CODEC_ID_MPEG4, MKTAG('m', 'p', '4', 'v') },
7068 { AV_CODEC_ID_H264, MKTAG('a', 'v', 'c', '1') },
7069 { AV_CODEC_ID_H264, MKTAG('a', 'v', 'c', '3') },
7070 { AV_CODEC_ID_HEVC, MKTAG('h', 'e', 'v', '1') },
7071 { AV_CODEC_ID_HEVC, MKTAG('h', 'v', 'c', '1') },
7072 { AV_CODEC_ID_MPEG2VIDEO, MKTAG('m', 'p', '4', 'v') },
7073 { AV_CODEC_ID_MPEG1VIDEO, MKTAG('m', 'p', '4', 'v') },
7074 { AV_CODEC_ID_MJPEG, MKTAG('m', 'p', '4', 'v') },
7075 { AV_CODEC_ID_PNG, MKTAG('m', 'p', '4', 'v') },
7076 { AV_CODEC_ID_JPEG2000, MKTAG('m', 'p', '4', 'v') },
7077 { AV_CODEC_ID_VC1, MKTAG('v', 'c', '-', '1') },
7078 { AV_CODEC_ID_DIRAC, MKTAG('d', 'r', 'a', 'c') },
7079 { AV_CODEC_ID_TSCC2, MKTAG('m', 'p', '4', 'v') },
7080 { AV_CODEC_ID_VP9, MKTAG('v', 'p', '0', '9') },
7081 { AV_CODEC_ID_AV1, MKTAG('a', 'v', '0', '1') },
7082 { AV_CODEC_ID_AAC, MKTAG('m', 'p', '4', 'a') },
7083 { AV_CODEC_ID_MP4ALS, MKTAG('m', 'p', '4', 'a') },
7084 { AV_CODEC_ID_MP3, MKTAG('m', 'p', '4', 'a') },
7085 { AV_CODEC_ID_MP2, MKTAG('m', 'p', '4', 'a') },
7086 { AV_CODEC_ID_AC3, MKTAG('a', 'c', '-', '3') },
7087 { AV_CODEC_ID_EAC3, MKTAG('e', 'c', '-', '3') },
7088 { AV_CODEC_ID_DTS, MKTAG('m', 'p', '4', 'a') },
7089 { AV_CODEC_ID_TRUEHD, MKTAG('m', 'l', 'p', 'a') },
7090 { AV_CODEC_ID_FLAC, MKTAG('f', 'L', 'a', 'C') },
7091 { AV_CODEC_ID_OPUS, MKTAG('O', 'p', 'u', 's') },
7092 { AV_CODEC_ID_VORBIS, MKTAG('m', 'p', '4', 'a') },
7093 { AV_CODEC_ID_QCELP, MKTAG('m', 'p', '4', 'a') },
7094 { AV_CODEC_ID_EVRC, MKTAG('m', 'p', '4', 'a') },
7095 { AV_CODEC_ID_DVD_SUBTITLE, MKTAG('m', 'p', '4', 's') },
7096 { AV_CODEC_ID_MOV_TEXT, MKTAG('t', 'x', '3', 'g') },
7097 { AV_CODEC_ID_BIN_DATA, MKTAG('g', 'p', 'm', 'd') },
7098 { AV_CODEC_ID_MPEGH_3D_AUDIO, MKTAG('m', 'h', 'm', '1') },
7099 { AV_CODEC_ID_NONE, 0 },
7102 const AVCodecTag codec_ism_tags[] = {
7103 { AV_CODEC_ID_WMAPRO , MKTAG('w', 'm', 'a', ' ') },
7104 { AV_CODEC_ID_NONE , 0 },
7107 static const AVCodecTag codec_ipod_tags[] = {
7108 { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
7109 { AV_CODEC_ID_MPEG4, MKTAG('m','p','4','v') },
7110 { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
7111 { AV_CODEC_ID_ALAC, MKTAG('a','l','a','c') },
7112 { AV_CODEC_ID_AC3, MKTAG('a','c','-','3') },
7113 { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
7114 { AV_CODEC_ID_MOV_TEXT, MKTAG('t','e','x','t') },
7115 { AV_CODEC_ID_NONE, 0 },
7118 static const AVCodecTag codec_f4v_tags[] = {
7119 { AV_CODEC_ID_MP3, MKTAG('.','m','p','3') },
7120 { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
7121 { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
7122 { AV_CODEC_ID_VP6A, MKTAG('V','P','6','A') },
7123 { AV_CODEC_ID_VP6F, MKTAG('V','P','6','F') },
7124 { AV_CODEC_ID_NONE, 0 },
7127 #if CONFIG_MOV_MUXER
7129 AVOutputFormat ff_mov_muxer = {
7131 .long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
7132 .extensions = "mov",
7133 .priv_data_size = sizeof(MOVMuxContext),
7134 .audio_codec = AV_CODEC_ID_AAC,
7135 .video_codec = CONFIG_LIBX264_ENCODER ?
7136 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
7138 .write_header = mov_write_header,
7139 .write_packet = mov_write_packet,
7140 .write_trailer = mov_write_trailer,
7142 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
7143 .codec_tag = (const AVCodecTag* const []){
7144 ff_codec_movvideo_tags, ff_codec_movaudio_tags, ff_codec_movsubtitle_tags, 0
7146 .check_bitstream = mov_check_bitstream,
7147 .priv_class = &mov_muxer_class,
7150 #if CONFIG_TGP_MUXER
7152 AVOutputFormat ff_tgp_muxer = {
7154 .long_name = NULL_IF_CONFIG_SMALL("3GP (3GPP file format)"),
7155 .extensions = "3gp",
7156 .priv_data_size = sizeof(MOVMuxContext),
7157 .audio_codec = AV_CODEC_ID_AMR_NB,
7158 .video_codec = AV_CODEC_ID_H263,
7160 .write_header = mov_write_header,
7161 .write_packet = mov_write_packet,
7162 .write_trailer = mov_write_trailer,
7164 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
7165 .codec_tag = (const AVCodecTag* const []){ codec_3gp_tags, 0 },
7166 .check_bitstream = mov_check_bitstream,
7167 .priv_class = &tgp_muxer_class,
7170 #if CONFIG_MP4_MUXER
7172 AVOutputFormat ff_mp4_muxer = {
7174 .long_name = NULL_IF_CONFIG_SMALL("MP4 (MPEG-4 Part 14)"),
7175 .mime_type = "video/mp4",
7176 .extensions = "mp4",
7177 .priv_data_size = sizeof(MOVMuxContext),
7178 .audio_codec = AV_CODEC_ID_AAC,
7179 .video_codec = CONFIG_LIBX264_ENCODER ?
7180 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
7182 .write_header = mov_write_header,
7183 .write_packet = mov_write_packet,
7184 .write_trailer = mov_write_trailer,
7186 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
7187 .codec_tag = (const AVCodecTag* const []){ codec_mp4_tags, 0 },
7188 .check_bitstream = mov_check_bitstream,
7189 .priv_class = &mp4_muxer_class,
7192 #if CONFIG_PSP_MUXER
7194 AVOutputFormat ff_psp_muxer = {
7196 .long_name = NULL_IF_CONFIG_SMALL("PSP MP4 (MPEG-4 Part 14)"),
7197 .extensions = "mp4,psp",
7198 .priv_data_size = sizeof(MOVMuxContext),
7199 .audio_codec = AV_CODEC_ID_AAC,
7200 .video_codec = CONFIG_LIBX264_ENCODER ?
7201 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
7203 .write_header = mov_write_header,
7204 .write_packet = mov_write_packet,
7205 .write_trailer = mov_write_trailer,
7207 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
7208 .codec_tag = (const AVCodecTag* const []){ codec_mp4_tags, 0 },
7209 .check_bitstream = mov_check_bitstream,
7210 .priv_class = &psp_muxer_class,
7213 #if CONFIG_TG2_MUXER
7215 AVOutputFormat ff_tg2_muxer = {
7217 .long_name = NULL_IF_CONFIG_SMALL("3GP2 (3GPP2 file format)"),
7218 .extensions = "3g2",
7219 .priv_data_size = sizeof(MOVMuxContext),
7220 .audio_codec = AV_CODEC_ID_AMR_NB,
7221 .video_codec = AV_CODEC_ID_H263,
7223 .write_header = mov_write_header,
7224 .write_packet = mov_write_packet,
7225 .write_trailer = mov_write_trailer,
7227 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
7228 .codec_tag = (const AVCodecTag* const []){ codec_3gp_tags, 0 },
7229 .check_bitstream = mov_check_bitstream,
7230 .priv_class = &tg2_muxer_class,
7233 #if CONFIG_IPOD_MUXER
7235 AVOutputFormat ff_ipod_muxer = {
7237 .long_name = NULL_IF_CONFIG_SMALL("iPod H.264 MP4 (MPEG-4 Part 14)"),
7238 .mime_type = "video/mp4",
7239 .extensions = "m4v,m4a,m4b",
7240 .priv_data_size = sizeof(MOVMuxContext),
7241 .audio_codec = AV_CODEC_ID_AAC,
7242 .video_codec = AV_CODEC_ID_H264,
7244 .write_header = mov_write_header,
7245 .write_packet = mov_write_packet,
7246 .write_trailer = mov_write_trailer,
7248 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
7249 .codec_tag = (const AVCodecTag* const []){ codec_ipod_tags, 0 },
7250 .check_bitstream = mov_check_bitstream,
7251 .priv_class = &ipod_muxer_class,
7254 #if CONFIG_ISMV_MUXER
7256 AVOutputFormat ff_ismv_muxer = {
7258 .long_name = NULL_IF_CONFIG_SMALL("ISMV/ISMA (Smooth Streaming)"),
7259 .mime_type = "video/mp4",
7260 .extensions = "ismv,isma",
7261 .priv_data_size = sizeof(MOVMuxContext),
7262 .audio_codec = AV_CODEC_ID_AAC,
7263 .video_codec = AV_CODEC_ID_H264,
7265 .write_header = mov_write_header,
7266 .write_packet = mov_write_packet,
7267 .write_trailer = mov_write_trailer,
7269 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
7270 .codec_tag = (const AVCodecTag* const []){
7271 codec_mp4_tags, codec_ism_tags, 0 },
7272 .check_bitstream = mov_check_bitstream,
7273 .priv_class = &ismv_muxer_class,
7276 #if CONFIG_F4V_MUXER
7278 AVOutputFormat ff_f4v_muxer = {
7280 .long_name = NULL_IF_CONFIG_SMALL("F4V Adobe Flash Video"),
7281 .mime_type = "application/f4v",
7282 .extensions = "f4v",
7283 .priv_data_size = sizeof(MOVMuxContext),
7284 .audio_codec = AV_CODEC_ID_AAC,
7285 .video_codec = AV_CODEC_ID_H264,
7287 .write_header = mov_write_header,
7288 .write_packet = mov_write_packet,
7289 .write_trailer = mov_write_trailer,
7291 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH,
7292 .codec_tag = (const AVCodecTag* const []){ codec_f4v_tags, 0 },
7293 .check_bitstream = mov_check_bitstream,
7294 .priv_class = &f4v_muxer_class,