3 * Copyright (c) 2003 Thomas Raivio
4 * Copyright (c) 2004 Gildas Bazin <gbazin at videolan dot org>
5 * Copyright (c) 2009 Baptiste Coudurier <baptiste dot coudurier at gmail dot com>
7 * This file is part of FFmpeg.
9 * FFmpeg is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
14 * FFmpeg is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with FFmpeg; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
29 #include "avio_internal.h"
35 #include "libavcodec/ac3_parser_internal.h"
36 #include "libavcodec/dnxhddata.h"
37 #include "libavcodec/flac.h"
38 #include "libavcodec/get_bits.h"
40 #include "libavcodec/internal.h"
41 #include "libavcodec/put_bits.h"
42 #include "libavcodec/vc1_common.h"
43 #include "libavcodec/raw.h"
45 #include "libavutil/avstring.h"
46 #include "libavutil/intfloat.h"
47 #include "libavutil/mathematics.h"
48 #include "libavutil/libm.h"
49 #include "libavutil/opt.h"
50 #include "libavutil/dict.h"
51 #include "libavutil/pixdesc.h"
52 #include "libavutil/stereo3d.h"
53 #include "libavutil/timecode.h"
54 #include "libavutil/color_utils.h"
60 static const AVOption options[] = {
61 { "movflags", "MOV muxer flags", offsetof(MOVMuxContext, flags), AV_OPT_TYPE_FLAGS, {.i64 = 0}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
62 { "rtphint", "Add RTP hint tracks", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_RTP_HINT}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
63 { "moov_size", "maximum moov size so it can be placed at the begin", offsetof(MOVMuxContext, reserved_moov_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, 0 },
64 { "empty_moov", "Make the initial moov atom empty", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_EMPTY_MOOV}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
65 { "frag_keyframe", "Fragment at video keyframes", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FRAG_KEYFRAME}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
66 { "frag_every_frame", "Fragment at every frame", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FRAG_EVERY_FRAME}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
67 { "separate_moof", "Write separate moof/mdat atoms for each track", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_SEPARATE_MOOF}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
68 { "frag_custom", "Flush fragments on caller requests", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FRAG_CUSTOM}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
69 { "isml", "Create a live smooth streaming feed (for pushing to a publishing point)", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_ISML}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
70 { "faststart", "Run a second pass to put the index (moov atom) at the beginning of the file", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FASTSTART}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
71 { "omit_tfhd_offset", "Omit the base data offset in tfhd atoms", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_OMIT_TFHD_OFFSET}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
72 { "disable_chpl", "Disable Nero chapter atom", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_DISABLE_CHPL}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
73 { "default_base_moof", "Set the default-base-is-moof flag in tfhd atoms", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_DEFAULT_BASE_MOOF}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
74 { "dash", "Write DASH compatible fragmented MP4", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_DASH}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
75 { "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" },
76 { "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" },
77 { "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" },
78 { "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" },
79 { "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" },
80 { "write_colr", "Write colr atom (Experimental, may be renamed or changed, do not use from scripts)", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_WRITE_COLR}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
81 { "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" },
82 { "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" },
83 { "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" },
84 { "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" },
85 { "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" },
86 FF_RTP_FLAG_OPTS(MOVMuxContext, rtp_flags),
87 { "skip_iods", "Skip writing iods atom.", offsetof(MOVMuxContext, iods_skip), AV_OPT_TYPE_BOOL, {.i64 = 1}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM},
88 { "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},
89 { "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},
90 { "frag_duration", "Maximum fragment duration", offsetof(MOVMuxContext, max_fragment_duration), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
91 { "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},
92 { "frag_size", "Maximum fragment size", offsetof(MOVMuxContext, max_fragment_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
93 { "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},
94 { "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},
95 { "brand", "Override major brand", offsetof(MOVMuxContext, major_brand), AV_OPT_TYPE_STRING, {.str = NULL}, .flags = AV_OPT_FLAG_ENCODING_PARAM },
96 { "use_editlist", "use edit list", offsetof(MOVMuxContext, use_editlist), AV_OPT_TYPE_BOOL, {.i64 = -1}, -1, 1, AV_OPT_FLAG_ENCODING_PARAM},
97 { "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},
98 { "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},
99 { "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 },
100 { "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 },
101 { "encryption_key", "The media encryption key (hex)", offsetof(MOVMuxContext, encryption_key), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_ENCODING_PARAM },
102 { "encryption_kid", "The media encryption key identifier (hex)", offsetof(MOVMuxContext, encryption_kid), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_ENCODING_PARAM },
103 { "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},
104 { "write_tmcd", "force or disable writing tmcd", offsetof(MOVMuxContext, write_tmcd), AV_OPT_TYPE_BOOL, {.i64 = -1}, -1, 1, AV_OPT_FLAG_ENCODING_PARAM},
105 { "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"},
106 { "wallclock", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = MOV_PRFT_SRC_WALLCLOCK}, 0, 0, AV_OPT_FLAG_ENCODING_PARAM, "prft"},
107 { "pts", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = MOV_PRFT_SRC_PTS}, 0, 0, AV_OPT_FLAG_ENCODING_PARAM, "prft"},
108 { "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},
112 #define MOV_CLASS(flavor)\
113 static const AVClass flavor ## _muxer_class = {\
114 .class_name = #flavor " muxer",\
115 .item_name = av_default_item_name,\
117 .version = LIBAVUTIL_VERSION_INT,\
120 static int get_moov_size(AVFormatContext *s);
122 static int utf8len(const uint8_t *b)
127 GET_UTF8(val, *b++, return -1;)
133 //FIXME support 64 bit variant with wide placeholders
134 static int64_t update_size(AVIOContext *pb, int64_t pos)
136 int64_t curpos = avio_tell(pb);
137 avio_seek(pb, pos, SEEK_SET);
138 avio_wb32(pb, curpos - pos); /* rewrite size */
139 avio_seek(pb, curpos, SEEK_SET);
144 static int co64_required(const MOVTrack *track)
146 if (track->entry > 0 && track->cluster[track->entry - 1].pos + track->data_offset > UINT32_MAX)
151 static int is_cover_image(const AVStream *st)
153 /* Eg. AV_DISPOSITION_ATTACHED_PIC | AV_DISPOSITION_TIMED_THUMBNAILS
154 * is encoded as sparse video track */
155 return st && st->disposition == AV_DISPOSITION_ATTACHED_PIC;
158 static int rtp_hinting_needed(const AVStream *st)
160 /* Add hint tracks for each real audio and video stream */
161 if (is_cover_image(st))
163 return st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ||
164 st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO;
167 /* Chunk offset atom */
168 static int mov_write_stco_tag(AVIOContext *pb, MOVTrack *track)
171 int mode64 = co64_required(track); // use 32 bit size variant if possible
172 int64_t pos = avio_tell(pb);
173 avio_wb32(pb, 0); /* size */
175 ffio_wfourcc(pb, "co64");
177 ffio_wfourcc(pb, "stco");
178 avio_wb32(pb, 0); /* version & flags */
179 avio_wb32(pb, track->chunkCount); /* entry count */
180 for (i = 0; i < track->entry; i++) {
181 if (!track->cluster[i].chunkNum)
184 avio_wb64(pb, track->cluster[i].pos + track->data_offset);
186 avio_wb32(pb, track->cluster[i].pos + track->data_offset);
188 return update_size(pb, pos);
191 /* Sample size atom */
192 static int mov_write_stsz_tag(AVIOContext *pb, MOVTrack *track)
195 int i, j, entries = 0, tst = -1, oldtst = -1;
197 int64_t pos = avio_tell(pb);
198 avio_wb32(pb, 0); /* size */
199 ffio_wfourcc(pb, "stsz");
200 avio_wb32(pb, 0); /* version & flags */
202 for (i = 0; i < track->entry; i++) {
203 tst = track->cluster[i].size / track->cluster[i].entries;
204 if (oldtst != -1 && tst != oldtst)
207 entries += track->cluster[i].entries;
209 if (equalChunks && track->entry) {
210 int sSize = track->entry ? track->cluster[0].size / track->cluster[0].entries : 0;
211 sSize = FFMAX(1, sSize); // adpcm mono case could make sSize == 0
212 avio_wb32(pb, sSize); // sample size
213 avio_wb32(pb, entries); // sample count
215 avio_wb32(pb, 0); // sample size
216 avio_wb32(pb, entries); // sample count
217 for (i = 0; i < track->entry; i++) {
218 for (j = 0; j < track->cluster[i].entries; j++) {
219 avio_wb32(pb, track->cluster[i].size /
220 track->cluster[i].entries);
224 return update_size(pb, pos);
227 /* Sample to chunk atom */
228 static int mov_write_stsc_tag(AVIOContext *pb, MOVTrack *track)
230 int index = 0, oldval = -1, i;
231 int64_t entryPos, curpos;
233 int64_t pos = avio_tell(pb);
234 avio_wb32(pb, 0); /* size */
235 ffio_wfourcc(pb, "stsc");
236 avio_wb32(pb, 0); // version & flags
237 entryPos = avio_tell(pb);
238 avio_wb32(pb, track->chunkCount); // entry count
239 for (i = 0; i < track->entry; i++) {
240 if (oldval != track->cluster[i].samples_in_chunk && track->cluster[i].chunkNum) {
241 avio_wb32(pb, track->cluster[i].chunkNum); // first chunk
242 avio_wb32(pb, track->cluster[i].samples_in_chunk); // samples per chunk
243 avio_wb32(pb, 0x1); // sample description index
244 oldval = track->cluster[i].samples_in_chunk;
248 curpos = avio_tell(pb);
249 avio_seek(pb, entryPos, SEEK_SET);
250 avio_wb32(pb, index); // rewrite size
251 avio_seek(pb, curpos, SEEK_SET);
253 return update_size(pb, pos);
256 /* Sync sample atom */
257 static int mov_write_stss_tag(AVIOContext *pb, MOVTrack *track, uint32_t flag)
259 int64_t curpos, entryPos;
261 int64_t pos = avio_tell(pb);
262 avio_wb32(pb, 0); // size
263 ffio_wfourcc(pb, flag == MOV_SYNC_SAMPLE ? "stss" : "stps");
264 avio_wb32(pb, 0); // version & flags
265 entryPos = avio_tell(pb);
266 avio_wb32(pb, track->entry); // entry count
267 for (i = 0; i < track->entry; i++) {
268 if (track->cluster[i].flags & flag) {
269 avio_wb32(pb, i + 1);
273 curpos = avio_tell(pb);
274 avio_seek(pb, entryPos, SEEK_SET);
275 avio_wb32(pb, index); // rewrite size
276 avio_seek(pb, curpos, SEEK_SET);
277 return update_size(pb, pos);
280 /* Sample dependency atom */
281 static int mov_write_sdtp_tag(AVIOContext *pb, MOVTrack *track)
284 uint8_t leading, dependent, reference, redundancy;
285 int64_t pos = avio_tell(pb);
286 avio_wb32(pb, 0); // size
287 ffio_wfourcc(pb, "sdtp");
288 avio_wb32(pb, 0); // version & flags
289 for (i = 0; i < track->entry; i++) {
290 dependent = MOV_SAMPLE_DEPENDENCY_YES;
291 leading = reference = redundancy = MOV_SAMPLE_DEPENDENCY_UNKNOWN;
292 if (track->cluster[i].flags & MOV_DISPOSABLE_SAMPLE) {
293 reference = MOV_SAMPLE_DEPENDENCY_NO;
295 if (track->cluster[i].flags & MOV_SYNC_SAMPLE) {
296 dependent = MOV_SAMPLE_DEPENDENCY_NO;
298 avio_w8(pb, (leading << 6) | (dependent << 4) |
299 (reference << 2) | redundancy);
301 return update_size(pb, pos);
304 static int mov_write_amr_tag(AVIOContext *pb, MOVTrack *track)
306 avio_wb32(pb, 0x11); /* size */
307 if (track->mode == MODE_MOV) ffio_wfourcc(pb, "samr");
308 else ffio_wfourcc(pb, "damr");
309 ffio_wfourcc(pb, "FFMP");
310 avio_w8(pb, 0); /* decoder version */
312 avio_wb16(pb, 0x81FF); /* Mode set (all modes for AMR_NB) */
313 avio_w8(pb, 0x00); /* Mode change period (no restriction) */
314 avio_w8(pb, 0x01); /* Frames per sample */
318 static int mov_write_ac3_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
323 int fscod, bsid, bsmod, acmod, lfeon, frmsizecod;
325 if (track->vos_len < 7) {
326 av_log(s, AV_LOG_ERROR,
327 "Cannot write moov atom before AC3 packets."
328 " Set the delay_moov flag to fix this.\n");
329 return AVERROR(EINVAL);
333 ffio_wfourcc(pb, "dac3");
335 init_get_bits(&gbc, track->vos_data + 4, (track->vos_len - 4) * 8);
336 fscod = get_bits(&gbc, 2);
337 frmsizecod = get_bits(&gbc, 6);
338 bsid = get_bits(&gbc, 5);
339 bsmod = get_bits(&gbc, 3);
340 acmod = get_bits(&gbc, 3);
342 skip_bits(&gbc, 2); // dsurmod
344 if ((acmod & 1) && acmod != 1)
345 skip_bits(&gbc, 2); // cmixlev
347 skip_bits(&gbc, 2); // surmixlev
349 lfeon = get_bits1(&gbc);
351 init_put_bits(&pbc, buf, sizeof(buf));
352 put_bits(&pbc, 2, fscod);
353 put_bits(&pbc, 5, bsid);
354 put_bits(&pbc, 3, bsmod);
355 put_bits(&pbc, 3, acmod);
356 put_bits(&pbc, 1, lfeon);
357 put_bits(&pbc, 5, frmsizecod >> 1); // bit_rate_code
358 put_bits(&pbc, 5, 0); // reserved
360 flush_put_bits(&pbc);
361 avio_write(pb, buf, sizeof(buf));
371 /* Layout of the EC3SpecificBox */
372 /* maximum bitrate */
374 /* number of independent substreams */
377 /* sample rate code (see ff_ac3_sample_rate_tab) 2 bits */
379 /* bit stream identification 5 bits */
381 /* one bit reserved */
382 /* audio service mixing (not supported yet) 1 bit */
383 /* bit stream mode 3 bits */
385 /* audio coding mode 3 bits */
387 /* sub woofer on 1 bit */
389 /* 3 bits reserved */
390 /* number of dependent substreams associated with this substream 4 bits */
392 /* channel locations of the dependent substream(s), if any, 9 bits */
394 /* if there is no dependent substream, then one bit reserved instead */
395 } substream[1]; /* TODO: support 8 independent substreams */
398 #if CONFIG_AC3_PARSER
399 static int handle_eac3(MOVMuxContext *mov, AVPacket *pkt, MOVTrack *track)
401 AC3HeaderInfo *hdr = NULL;
402 struct eac3_info *info;
405 if (!track->eac3_priv && !(track->eac3_priv = av_mallocz(sizeof(*info))))
406 return AVERROR(ENOMEM);
407 info = track->eac3_priv;
409 if (avpriv_ac3_parse_header(&hdr, pkt->data, pkt->size) < 0) {
410 /* drop the packets until we see a good one */
412 av_log(mov->fc, AV_LOG_WARNING, "Dropping invalid packet from start of the stream\n");
415 ret = AVERROR_INVALIDDATA;
419 info->data_rate = FFMAX(info->data_rate, hdr->bit_rate / 1000);
420 num_blocks = hdr->num_blocks;
422 if (!info->ec3_done) {
423 /* AC-3 substream must be the first one */
424 if (hdr->bitstream_id <= 10 && hdr->substreamid != 0) {
425 ret = AVERROR(EINVAL);
429 /* this should always be the case, given that our AC-3 parser
430 * concatenates dependent frames to their independent parent */
431 if (hdr->frame_type == EAC3_FRAME_TYPE_INDEPENDENT) {
432 /* substream ids must be incremental */
433 if (hdr->substreamid > info->num_ind_sub + 1) {
434 ret = AVERROR(EINVAL);
438 if (hdr->substreamid == info->num_ind_sub + 1) {
439 //info->num_ind_sub++;
440 avpriv_request_sample(mov->fc, "Multiple independent substreams");
441 ret = AVERROR_PATCHWELCOME;
443 } else if (hdr->substreamid < info->num_ind_sub ||
444 hdr->substreamid == 0 && info->substream[0].bsid) {
449 if (hdr->substreamid != 0) {
450 avpriv_request_sample(mov->fc, "Multiple non EAC3 independent substreams");
451 ret = AVERROR_PATCHWELCOME;
456 /* fill the info needed for the "dec3" atom */
457 info->substream[hdr->substreamid].fscod = hdr->sr_code;
458 info->substream[hdr->substreamid].bsid = hdr->bitstream_id;
459 info->substream[hdr->substreamid].bsmod = hdr->bitstream_mode;
460 info->substream[hdr->substreamid].acmod = hdr->channel_mode;
461 info->substream[hdr->substreamid].lfeon = hdr->lfe_on;
463 /* Parse dependent substream(s), if any */
464 if (pkt->size != hdr->frame_size) {
465 int cumul_size = hdr->frame_size;
466 int parent = hdr->substreamid;
468 while (cumul_size != pkt->size) {
471 ret = avpriv_ac3_parse_header(&hdr, pkt->data + cumul_size, pkt->size - cumul_size);
474 if (hdr->frame_type != EAC3_FRAME_TYPE_DEPENDENT) {
475 ret = AVERROR(EINVAL);
478 info->substream[parent].num_dep_sub++;
481 /* header is parsed up to lfeon, but custom channel map may be needed */
482 init_get_bits8(&gbc, pkt->data + cumul_size + ret, pkt->size - cumul_size - ret);
485 /* skip volume control params */
486 for (i = 0; i < (hdr->channel_mode ? 1 : 2); i++) {
487 skip_bits(&gbc, 5); // skip dialog normalization
488 if (get_bits1(&gbc)) {
489 skip_bits(&gbc, 8); // skip compression gain word
492 /* get the dependent stream channel map, if exists */
494 info->substream[parent].chan_loc |= (get_bits(&gbc, 16) >> 5) & 0x1f;
496 info->substream[parent].chan_loc |= hdr->channel_mode;
497 cumul_size += hdr->frame_size;
503 if (!info->num_blocks && num_blocks == 6) {
507 else if (info->num_blocks + num_blocks > 6) {
508 ret = AVERROR_INVALIDDATA;
512 if (!info->num_blocks) {
513 ret = av_packet_ref(&info->pkt, pkt);
515 info->num_blocks = num_blocks;
518 if ((ret = av_grow_packet(&info->pkt, pkt->size)) < 0)
520 memcpy(info->pkt.data + info->pkt.size - pkt->size, pkt->data, pkt->size);
521 info->num_blocks += num_blocks;
522 info->pkt.duration += pkt->duration;
523 if ((ret = av_copy_packet_side_data(&info->pkt, pkt)) < 0)
525 if (info->num_blocks != 6)
527 av_packet_unref(pkt);
528 av_packet_move_ref(pkt, &info->pkt);
529 info->num_blocks = 0;
540 static int mov_write_eac3_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
544 struct eac3_info *info;
547 if (!track->eac3_priv) {
548 av_log(s, AV_LOG_ERROR,
549 "Cannot write moov atom before EAC3 packets parsed.\n");
550 return AVERROR(EINVAL);
553 info = track->eac3_priv;
554 size = 2 + ((34 * (info->num_ind_sub + 1) + 7) >> 3);
555 buf = av_malloc(size);
557 return AVERROR(ENOMEM);
560 init_put_bits(&pbc, buf, size);
561 put_bits(&pbc, 13, info->data_rate);
562 put_bits(&pbc, 3, info->num_ind_sub);
563 for (i = 0; i <= info->num_ind_sub; i++) {
564 put_bits(&pbc, 2, info->substream[i].fscod);
565 put_bits(&pbc, 5, info->substream[i].bsid);
566 put_bits(&pbc, 1, 0); /* reserved */
567 put_bits(&pbc, 1, 0); /* asvc */
568 put_bits(&pbc, 3, info->substream[i].bsmod);
569 put_bits(&pbc, 3, info->substream[i].acmod);
570 put_bits(&pbc, 1, info->substream[i].lfeon);
571 put_bits(&pbc, 5, 0); /* reserved */
572 put_bits(&pbc, 4, info->substream[i].num_dep_sub);
573 if (!info->substream[i].num_dep_sub) {
574 put_bits(&pbc, 1, 0); /* reserved */
576 put_bits(&pbc, 9, info->substream[i].chan_loc);
579 flush_put_bits(&pbc);
580 size = put_bits_count(&pbc) >> 3;
582 avio_wb32(pb, size + 8);
583 ffio_wfourcc(pb, "dec3");
584 avio_write(pb, buf, size);
592 * This function writes extradata "as is".
593 * Extradata must be formatted like a valid atom (with size and tag).
595 static int mov_write_extradata_tag(AVIOContext *pb, MOVTrack *track)
597 avio_write(pb, track->par->extradata, track->par->extradata_size);
598 return track->par->extradata_size;
601 static int mov_write_enda_tag(AVIOContext *pb)
604 ffio_wfourcc(pb, "enda");
605 avio_wb16(pb, 1); /* little endian */
609 static int mov_write_enda_tag_be(AVIOContext *pb)
612 ffio_wfourcc(pb, "enda");
613 avio_wb16(pb, 0); /* big endian */
617 static void put_descr(AVIOContext *pb, int tag, unsigned int size)
622 avio_w8(pb, (size >> (7 * i)) | 0x80);
623 avio_w8(pb, size & 0x7F);
626 static unsigned compute_avg_bitrate(MOVTrack *track)
630 if (!track->track_duration)
632 for (i = 0; i < track->entry; i++)
633 size += track->cluster[i].size;
634 return size * 8 * track->timescale / track->track_duration;
637 static int mov_write_esds_tag(AVIOContext *pb, MOVTrack *track) // Basic
639 AVCPBProperties *props;
640 int64_t pos = avio_tell(pb);
641 int decoder_specific_info_len = track->vos_len ? 5 + track->vos_len : 0;
642 unsigned avg_bitrate;
644 avio_wb32(pb, 0); // size
645 ffio_wfourcc(pb, "esds");
646 avio_wb32(pb, 0); // Version
649 put_descr(pb, 0x03, 3 + 5+13 + decoder_specific_info_len + 5+1);
650 avio_wb16(pb, track->track_id);
651 avio_w8(pb, 0x00); // flags (= no flags)
653 // DecoderConfig descriptor
654 put_descr(pb, 0x04, 13 + decoder_specific_info_len);
656 // Object type indication
657 if ((track->par->codec_id == AV_CODEC_ID_MP2 ||
658 track->par->codec_id == AV_CODEC_ID_MP3) &&
659 track->par->sample_rate > 24000)
660 avio_w8(pb, 0x6B); // 11172-3
662 avio_w8(pb, ff_codec_get_tag(ff_mp4_obj_type, track->par->codec_id));
664 // the following fields is made of 6 bits to identify the streamtype (4 for video, 5 for audio)
665 // plus 1 bit to indicate upstream and 1 bit set to 1 (reserved)
666 if (track->par->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
667 avio_w8(pb, (0x38 << 2) | 1); // flags (= NeroSubpicStream)
668 else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
669 avio_w8(pb, 0x15); // flags (= Audiostream)
671 avio_w8(pb, 0x11); // flags (= Visualstream)
673 props = (AVCPBProperties*)av_stream_get_side_data(track->st, AV_PKT_DATA_CPB_PROPERTIES,
676 avio_wb24(pb, props ? props->buffer_size / 8 : 0); // Buffersize DB
678 avg_bitrate = compute_avg_bitrate(track);
679 avio_wb32(pb, props ? FFMAX3(props->max_bitrate, props->avg_bitrate, avg_bitrate) : FFMAX(track->par->bit_rate, avg_bitrate)); // maxbitrate (FIXME should be max rate in any 1 sec window)
680 avio_wb32(pb, avg_bitrate);
682 if (track->vos_len) {
683 // DecoderSpecific info descriptor
684 put_descr(pb, 0x05, track->vos_len);
685 avio_write(pb, track->vos_data, track->vos_len);
689 put_descr(pb, 0x06, 1);
691 return update_size(pb, pos);
694 static int mov_pcm_le_gt16(enum AVCodecID codec_id)
696 return codec_id == AV_CODEC_ID_PCM_S24LE ||
697 codec_id == AV_CODEC_ID_PCM_S32LE ||
698 codec_id == AV_CODEC_ID_PCM_F32LE ||
699 codec_id == AV_CODEC_ID_PCM_F64LE;
702 static int mov_pcm_be_gt16(enum AVCodecID codec_id)
704 return codec_id == AV_CODEC_ID_PCM_S24BE ||
705 codec_id == AV_CODEC_ID_PCM_S32BE ||
706 codec_id == AV_CODEC_ID_PCM_F32BE ||
707 codec_id == AV_CODEC_ID_PCM_F64BE;
710 static int mov_write_ms_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
713 int64_t pos = avio_tell(pb);
715 avio_wl32(pb, track->tag); // store it byteswapped
716 track->par->codec_tag = av_bswap16(track->tag >> 16);
717 if ((ret = ff_put_wav_header(s, pb, track->par, 0)) < 0)
719 return update_size(pb, pos);
722 static int mov_write_wfex_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
725 int64_t pos = avio_tell(pb);
727 ffio_wfourcc(pb, "wfex");
728 if ((ret = ff_put_wav_header(s, pb, track->st->codecpar, FF_PUT_WAV_HEADER_FORCE_WAVEFORMATEX)) < 0)
730 return update_size(pb, pos);
733 static int mov_write_dfla_tag(AVIOContext *pb, MOVTrack *track)
735 int64_t pos = avio_tell(pb);
737 ffio_wfourcc(pb, "dfLa");
738 avio_w8(pb, 0); /* version */
739 avio_wb24(pb, 0); /* flags */
741 /* Expect the encoder to pass a METADATA_BLOCK_TYPE_STREAMINFO. */
742 if (track->par->extradata_size != FLAC_STREAMINFO_SIZE)
743 return AVERROR_INVALIDDATA;
745 /* TODO: Write other METADATA_BLOCK_TYPEs if the encoder makes them available. */
746 avio_w8(pb, 1 << 7 | FLAC_METADATA_TYPE_STREAMINFO); /* LastMetadataBlockFlag << 7 | BlockType */
747 avio_wb24(pb, track->par->extradata_size); /* Length */
748 avio_write(pb, track->par->extradata, track->par->extradata_size); /* BlockData[Length] */
750 return update_size(pb, pos);
753 static int mov_write_dops_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
755 int64_t pos = avio_tell(pb);
757 ffio_wfourcc(pb, "dOps");
758 avio_w8(pb, 0); /* Version */
759 if (track->par->extradata_size < 19) {
760 av_log(s, AV_LOG_ERROR, "invalid extradata size\n");
761 return AVERROR_INVALIDDATA;
763 /* extradata contains an Ogg OpusHead, other than byte-ordering and
764 OpusHead's preceeding magic/version, OpusSpecificBox is currently
766 avio_w8(pb, AV_RB8(track->par->extradata + 9)); /* OuputChannelCount */
767 avio_wb16(pb, AV_RL16(track->par->extradata + 10)); /* PreSkip */
768 avio_wb32(pb, AV_RL32(track->par->extradata + 12)); /* InputSampleRate */
769 avio_wb16(pb, AV_RL16(track->par->extradata + 16)); /* OutputGain */
770 /* Write the rest of the header out without byte-swapping. */
771 avio_write(pb, track->par->extradata + 18, track->par->extradata_size - 18);
773 return update_size(pb, pos);
776 static int mov_write_dmlp_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
778 int64_t pos = avio_tell(pb);
781 ffio_wfourcc(pb, "dmlp");
783 if (track->vos_len < 20) {
784 av_log(s, AV_LOG_ERROR,
785 "Cannot write moov atom before TrueHD packets."
786 " Set the delay_moov flag to fix this.\n");
787 return AVERROR(EINVAL);
790 length = (AV_RB16(track->vos_data) & 0xFFF) * 2;
791 if (length < 20 || length > track->vos_len)
792 return AVERROR_INVALIDDATA;
794 // Only TrueHD is supported
795 if (AV_RB32(track->vos_data + 4) != 0xF8726FBA)
796 return AVERROR_INVALIDDATA;
798 avio_wb32(pb, AV_RB32(track->vos_data + 8)); /* format_info */
799 avio_wb16(pb, AV_RB16(track->vos_data + 18) << 1); /* peak_data_rate */
800 avio_wb32(pb, 0); /* reserved */
802 return update_size(pb, pos);
805 static int mov_write_chan_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
807 uint32_t layout_tag, bitmap;
808 int64_t pos = avio_tell(pb);
810 layout_tag = ff_mov_get_channel_layout_tag(track->par->codec_id,
811 track->par->channel_layout,
814 av_log(s, AV_LOG_WARNING, "not writing 'chan' tag due to "
815 "lack of channel information\n");
819 if (track->multichannel_as_mono)
822 avio_wb32(pb, 0); // Size
823 ffio_wfourcc(pb, "chan"); // Type
824 avio_w8(pb, 0); // Version
825 avio_wb24(pb, 0); // Flags
826 avio_wb32(pb, layout_tag); // mChannelLayoutTag
827 avio_wb32(pb, bitmap); // mChannelBitmap
828 avio_wb32(pb, 0); // mNumberChannelDescriptions
830 return update_size(pb, pos);
833 static int mov_write_wave_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
835 int64_t pos = avio_tell(pb);
837 avio_wb32(pb, 0); /* size */
838 ffio_wfourcc(pb, "wave");
840 if (track->par->codec_id != AV_CODEC_ID_QDM2) {
841 avio_wb32(pb, 12); /* size */
842 ffio_wfourcc(pb, "frma");
843 avio_wl32(pb, track->tag);
846 if (track->par->codec_id == AV_CODEC_ID_AAC) {
847 /* useless atom needed by mplayer, ipod, not needed by quicktime */
848 avio_wb32(pb, 12); /* size */
849 ffio_wfourcc(pb, "mp4a");
851 mov_write_esds_tag(pb, track);
852 } else if (mov_pcm_le_gt16(track->par->codec_id)) {
853 mov_write_enda_tag(pb);
854 } else if (mov_pcm_be_gt16(track->par->codec_id)) {
855 mov_write_enda_tag_be(pb);
856 } else if (track->par->codec_id == AV_CODEC_ID_AMR_NB) {
857 mov_write_amr_tag(pb, track);
858 } else if (track->par->codec_id == AV_CODEC_ID_AC3) {
859 mov_write_ac3_tag(s, pb, track);
860 } else if (track->par->codec_id == AV_CODEC_ID_EAC3) {
861 mov_write_eac3_tag(s, pb, track);
862 } else if (track->par->codec_id == AV_CODEC_ID_ALAC ||
863 track->par->codec_id == AV_CODEC_ID_QDM2) {
864 mov_write_extradata_tag(pb, track);
865 } else if (track->par->codec_id == AV_CODEC_ID_ADPCM_MS ||
866 track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) {
867 mov_write_ms_tag(s, pb, track);
870 avio_wb32(pb, 8); /* size */
871 avio_wb32(pb, 0); /* null tag */
873 return update_size(pb, pos);
876 static int mov_write_dvc1_structs(MOVTrack *track, uint8_t *buf)
879 const uint8_t *start, *next, *end = track->vos_data + track->vos_len;
880 int unescaped_size, seq_found = 0;
881 int level = 0, interlace = 0;
882 int packet_seq = track->vc1_info.packet_seq;
883 int packet_entry = track->vc1_info.packet_entry;
884 int slices = track->vc1_info.slices;
887 if (track->start_dts == AV_NOPTS_VALUE) {
888 /* No packets written yet, vc1_info isn't authoritative yet. */
889 /* Assume inline sequence and entry headers. */
890 packet_seq = packet_entry = 1;
891 av_log(NULL, AV_LOG_WARNING,
892 "moov atom written before any packets, unable to write correct "
893 "dvc1 atom. Set the delay_moov flag to fix this.\n");
896 unescaped = av_mallocz(track->vos_len + AV_INPUT_BUFFER_PADDING_SIZE);
898 return AVERROR(ENOMEM);
899 start = find_next_marker(track->vos_data, end);
900 for (next = start; next < end; start = next) {
903 next = find_next_marker(start + 4, end);
904 size = next - start - 4;
907 unescaped_size = vc1_unescape_buffer(start + 4, size, unescaped);
908 init_get_bits(&gb, unescaped, 8 * unescaped_size);
909 if (AV_RB32(start) == VC1_CODE_SEQHDR) {
910 int profile = get_bits(&gb, 2);
911 if (profile != PROFILE_ADVANCED) {
913 return AVERROR(ENOSYS);
916 level = get_bits(&gb, 3);
917 /* chromaformat, frmrtq_postproc, bitrtq_postproc, postprocflag,
919 skip_bits_long(&gb, 2 + 3 + 5 + 1 + 2*12);
920 skip_bits(&gb, 1); /* broadcast */
921 interlace = get_bits1(&gb);
922 skip_bits(&gb, 4); /* tfcntrflag, finterpflag, reserved, psf */
927 return AVERROR(ENOSYS);
930 init_put_bits(&pbc, buf, 7);
931 /* VC1DecSpecStruc */
932 put_bits(&pbc, 4, 12); /* profile - advanced */
933 put_bits(&pbc, 3, level);
934 put_bits(&pbc, 1, 0); /* reserved */
935 /* VC1AdvDecSpecStruc */
936 put_bits(&pbc, 3, level);
937 put_bits(&pbc, 1, 0); /* cbr */
938 put_bits(&pbc, 6, 0); /* reserved */
939 put_bits(&pbc, 1, !interlace); /* no interlace */
940 put_bits(&pbc, 1, !packet_seq); /* no multiple seq */
941 put_bits(&pbc, 1, !packet_entry); /* no multiple entry */
942 put_bits(&pbc, 1, !slices); /* no slice code */
943 put_bits(&pbc, 1, 0); /* no bframe */
944 put_bits(&pbc, 1, 0); /* reserved */
947 if (track->st->avg_frame_rate.num > 0 && track->st->avg_frame_rate.den > 0)
948 put_bits32(&pbc, track->st->avg_frame_rate.num / track->st->avg_frame_rate.den);
950 put_bits32(&pbc, 0xffffffff);
952 flush_put_bits(&pbc);
959 static int mov_write_dvc1_tag(AVIOContext *pb, MOVTrack *track)
961 uint8_t buf[7] = { 0 };
964 if ((ret = mov_write_dvc1_structs(track, buf)) < 0)
967 avio_wb32(pb, track->vos_len + 8 + sizeof(buf));
968 ffio_wfourcc(pb, "dvc1");
969 avio_write(pb, buf, sizeof(buf));
970 avio_write(pb, track->vos_data, track->vos_len);
975 static int mov_write_glbl_tag(AVIOContext *pb, MOVTrack *track)
977 avio_wb32(pb, track->vos_len + 8);
978 ffio_wfourcc(pb, "glbl");
979 avio_write(pb, track->vos_data, track->vos_len);
980 return 8 + track->vos_len;
984 * Compute flags for 'lpcm' tag.
985 * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
987 static int mov_get_lpcm_flags(enum AVCodecID codec_id)
990 case AV_CODEC_ID_PCM_F32BE:
991 case AV_CODEC_ID_PCM_F64BE:
993 case AV_CODEC_ID_PCM_F32LE:
994 case AV_CODEC_ID_PCM_F64LE:
996 case AV_CODEC_ID_PCM_U8:
998 case AV_CODEC_ID_PCM_S16BE:
999 case AV_CODEC_ID_PCM_S24BE:
1000 case AV_CODEC_ID_PCM_S32BE:
1002 case AV_CODEC_ID_PCM_S8:
1003 case AV_CODEC_ID_PCM_S16LE:
1004 case AV_CODEC_ID_PCM_S24LE:
1005 case AV_CODEC_ID_PCM_S32LE:
1012 static int get_cluster_duration(MOVTrack *track, int cluster_idx)
1016 if (cluster_idx >= track->entry)
1019 if (cluster_idx + 1 == track->entry)
1020 next_dts = track->track_duration + track->start_dts;
1022 next_dts = track->cluster[cluster_idx + 1].dts;
1024 next_dts -= track->cluster[cluster_idx].dts;
1026 av_assert0(next_dts >= 0);
1027 av_assert0(next_dts <= INT_MAX);
1032 static int get_samples_per_packet(MOVTrack *track)
1034 int i, first_duration;
1036 // return track->par->frame_size;
1038 /* use 1 for raw PCM */
1039 if (!track->audio_vbr)
1042 /* check to see if duration is constant for all clusters */
1045 first_duration = get_cluster_duration(track, 0);
1046 for (i = 1; i < track->entry; i++) {
1047 if (get_cluster_duration(track, i) != first_duration)
1050 return first_duration;
1053 static int mov_write_audio_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
1055 int64_t pos = avio_tell(pb);
1057 uint32_t tag = track->tag;
1060 if (track->mode == MODE_MOV) {
1061 if (track->timescale > UINT16_MAX || !track->par->channels) {
1062 if (mov_get_lpcm_flags(track->par->codec_id))
1063 tag = AV_RL32("lpcm");
1065 } else if (track->audio_vbr || mov_pcm_le_gt16(track->par->codec_id) ||
1066 mov_pcm_be_gt16(track->par->codec_id) ||
1067 track->par->codec_id == AV_CODEC_ID_ADPCM_MS ||
1068 track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
1069 track->par->codec_id == AV_CODEC_ID_QDM2) {
1074 avio_wb32(pb, 0); /* size */
1075 if (mov->encryption_scheme != MOV_ENC_NONE) {
1076 ffio_wfourcc(pb, "enca");
1078 avio_wl32(pb, tag); // store it byteswapped
1080 avio_wb32(pb, 0); /* Reserved */
1081 avio_wb16(pb, 0); /* Reserved */
1082 avio_wb16(pb, 1); /* Data-reference index, XXX == 1 */
1084 /* SoundDescription */
1085 avio_wb16(pb, version); /* Version */
1086 avio_wb16(pb, 0); /* Revision level */
1087 avio_wb32(pb, 0); /* Reserved */
1092 avio_wb16(pb, 0xfffe);
1094 avio_wb32(pb, 0x00010000);
1096 avio_wb64(pb, av_double2int(track->par->sample_rate));
1097 avio_wb32(pb, track->par->channels);
1098 avio_wb32(pb, 0x7F000000);
1099 avio_wb32(pb, av_get_bits_per_sample(track->par->codec_id));
1100 avio_wb32(pb, mov_get_lpcm_flags(track->par->codec_id));
1101 avio_wb32(pb, track->sample_size);
1102 avio_wb32(pb, get_samples_per_packet(track));
1104 if (track->mode == MODE_MOV) {
1105 avio_wb16(pb, track->par->channels);
1106 if (track->par->codec_id == AV_CODEC_ID_PCM_U8 ||
1107 track->par->codec_id == AV_CODEC_ID_PCM_S8)
1108 avio_wb16(pb, 8); /* bits per sample */
1109 else if (track->par->codec_id == AV_CODEC_ID_ADPCM_G726)
1110 avio_wb16(pb, track->par->bits_per_coded_sample);
1113 avio_wb16(pb, track->audio_vbr ? -2 : 0); /* compression ID */
1114 } else { /* reserved for mp4/3gp */
1115 if (track->par->codec_id == AV_CODEC_ID_FLAC ||
1116 track->par->codec_id == AV_CODEC_ID_ALAC ||
1117 track->par->codec_id == AV_CODEC_ID_OPUS) {
1118 avio_wb16(pb, track->par->channels);
1122 if (track->par->codec_id == AV_CODEC_ID_FLAC ||
1123 track->par->codec_id == AV_CODEC_ID_ALAC) {
1124 avio_wb16(pb, track->par->bits_per_raw_sample);
1131 avio_wb16(pb, 0); /* packet size (= 0) */
1132 if (track->par->codec_id == AV_CODEC_ID_OPUS)
1133 avio_wb16(pb, 48000);
1134 else if (track->par->codec_id == AV_CODEC_ID_TRUEHD)
1135 avio_wb32(pb, track->par->sample_rate);
1137 avio_wb16(pb, track->par->sample_rate <= UINT16_MAX ?
1138 track->par->sample_rate : 0);
1140 if (track->par->codec_id != AV_CODEC_ID_TRUEHD)
1141 avio_wb16(pb, 0); /* Reserved */
1144 if (version == 1) { /* SoundDescription V1 extended info */
1145 if (mov_pcm_le_gt16(track->par->codec_id) ||
1146 mov_pcm_be_gt16(track->par->codec_id))
1147 avio_wb32(pb, 1); /* must be 1 for uncompressed formats */
1149 avio_wb32(pb, track->par->frame_size); /* Samples per packet */
1150 avio_wb32(pb, track->sample_size / track->par->channels); /* Bytes per packet */
1151 avio_wb32(pb, track->sample_size); /* Bytes per frame */
1152 avio_wb32(pb, 2); /* Bytes per sample */
1155 if (track->mode == MODE_MOV &&
1156 (track->par->codec_id == AV_CODEC_ID_AAC ||
1157 track->par->codec_id == AV_CODEC_ID_AC3 ||
1158 track->par->codec_id == AV_CODEC_ID_EAC3 ||
1159 track->par->codec_id == AV_CODEC_ID_AMR_NB ||
1160 track->par->codec_id == AV_CODEC_ID_ALAC ||
1161 track->par->codec_id == AV_CODEC_ID_ADPCM_MS ||
1162 track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
1163 track->par->codec_id == AV_CODEC_ID_QDM2 ||
1164 (mov_pcm_le_gt16(track->par->codec_id) && version==1) ||
1165 (mov_pcm_be_gt16(track->par->codec_id) && version==1)))
1166 ret = mov_write_wave_tag(s, pb, track);
1167 else if (track->tag == MKTAG('m','p','4','a'))
1168 ret = mov_write_esds_tag(pb, track);
1169 else if (track->par->codec_id == AV_CODEC_ID_AMR_NB)
1170 ret = mov_write_amr_tag(pb, track);
1171 else if (track->par->codec_id == AV_CODEC_ID_AC3)
1172 ret = mov_write_ac3_tag(s, pb, track);
1173 else if (track->par->codec_id == AV_CODEC_ID_EAC3)
1174 ret = mov_write_eac3_tag(s, pb, track);
1175 else if (track->par->codec_id == AV_CODEC_ID_ALAC)
1176 ret = mov_write_extradata_tag(pb, track);
1177 else if (track->par->codec_id == AV_CODEC_ID_WMAPRO)
1178 ret = mov_write_wfex_tag(s, pb, track);
1179 else if (track->par->codec_id == AV_CODEC_ID_FLAC)
1180 ret = mov_write_dfla_tag(pb, track);
1181 else if (track->par->codec_id == AV_CODEC_ID_OPUS)
1182 ret = mov_write_dops_tag(s, pb, track);
1183 else if (track->par->codec_id == AV_CODEC_ID_TRUEHD)
1184 ret = mov_write_dmlp_tag(s, pb, track);
1185 else if (track->vos_len > 0)
1186 ret = mov_write_glbl_tag(pb, track);
1191 if (track->mode == MODE_MOV && track->par->codec_type == AVMEDIA_TYPE_AUDIO
1192 && ((ret = mov_write_chan_tag(s, pb, track)) < 0)) {
1196 if (mov->encryption_scheme != MOV_ENC_NONE
1197 && ((ret = ff_mov_cenc_write_sinf_tag(track, pb, mov->encryption_kid)) < 0)) {
1201 ret = update_size(pb, pos);
1205 static int mov_write_d263_tag(AVIOContext *pb)
1207 avio_wb32(pb, 0xf); /* size */
1208 ffio_wfourcc(pb, "d263");
1209 ffio_wfourcc(pb, "FFMP");
1210 avio_w8(pb, 0); /* decoder version */
1211 /* FIXME use AVCodecContext level/profile, when encoder will set values */
1212 avio_w8(pb, 0xa); /* level */
1213 avio_w8(pb, 0); /* profile */
1217 static int mov_write_av1c_tag(AVIOContext *pb, MOVTrack *track)
1219 int64_t pos = avio_tell(pb);
1222 ffio_wfourcc(pb, "av1C");
1223 ff_isom_write_av1c(pb, track->vos_data, track->vos_len);
1224 return update_size(pb, pos);
1227 static int mov_write_avcc_tag(AVIOContext *pb, MOVTrack *track)
1229 int64_t pos = avio_tell(pb);
1232 ffio_wfourcc(pb, "avcC");
1233 ff_isom_write_avcc(pb, track->vos_data, track->vos_len);
1234 return update_size(pb, pos);
1237 static int mov_write_vpcc_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
1239 int64_t pos = avio_tell(pb);
1242 ffio_wfourcc(pb, "vpcC");
1243 avio_w8(pb, 1); /* version */
1244 avio_wb24(pb, 0); /* flags */
1245 ff_isom_write_vpcc(s, pb, track->par);
1246 return update_size(pb, pos);
1249 static int mov_write_hvcc_tag(AVIOContext *pb, MOVTrack *track)
1251 int64_t pos = avio_tell(pb);
1254 ffio_wfourcc(pb, "hvcC");
1255 if (track->tag == MKTAG('h','v','c','1'))
1256 ff_isom_write_hvcc(pb, track->vos_data, track->vos_len, 1);
1258 ff_isom_write_hvcc(pb, track->vos_data, track->vos_len, 0);
1259 return update_size(pb, pos);
1262 /* also used by all avid codecs (dv, imx, meridien) and their variants */
1263 static int mov_write_avid_tag(AVIOContext *pb, MOVTrack *track)
1268 int display_width = track->par->width;
1270 if (track->vos_data && track->vos_len > 0x29) {
1271 if (ff_dnxhd_parse_header_prefix(track->vos_data) != 0) {
1272 /* looks like a DNxHD bit stream */
1273 interlaced = (track->vos_data[5] & 2);
1274 cid = AV_RB32(track->vos_data + 0x28);
1276 av_log(NULL, AV_LOG_WARNING, "Could not locate DNxHD bit stream in vos_data\n");
1280 av_log(NULL, AV_LOG_WARNING, "Could not locate DNxHD bit stream, vos_data too small\n");
1284 avio_wb32(pb, 24); /* size */
1285 ffio_wfourcc(pb, "ACLR");
1286 ffio_wfourcc(pb, "ACLR");
1287 ffio_wfourcc(pb, "0001");
1288 if (track->par->color_range == AVCOL_RANGE_MPEG || /* Legal range (16-235) */
1289 track->par->color_range == AVCOL_RANGE_UNSPECIFIED) {
1290 avio_wb32(pb, 1); /* Corresponds to 709 in official encoder */
1291 } else { /* Full range (0-255) */
1292 avio_wb32(pb, 2); /* Corresponds to RGB in official encoder */
1294 avio_wb32(pb, 0); /* unknown */
1296 if (track->tag == MKTAG('A','V','d','h')) {
1298 ffio_wfourcc(pb, "ADHR");
1299 ffio_wfourcc(pb, "0001");
1301 avio_wb32(pb, 0); /* unknown */
1302 avio_wb32(pb, 1); /* unknown */
1303 avio_wb32(pb, 0); /* unknown */
1304 avio_wb32(pb, 0); /* unknown */
1308 avio_wb32(pb, 24); /* size */
1309 ffio_wfourcc(pb, "APRG");
1310 ffio_wfourcc(pb, "APRG");
1311 ffio_wfourcc(pb, "0001");
1312 avio_wb32(pb, 1); /* unknown */
1313 avio_wb32(pb, 0); /* unknown */
1315 avio_wb32(pb, 120); /* size */
1316 ffio_wfourcc(pb, "ARES");
1317 ffio_wfourcc(pb, "ARES");
1318 ffio_wfourcc(pb, "0001");
1319 avio_wb32(pb, cid); /* dnxhd cid, some id ? */
1320 if ( track->par->sample_aspect_ratio.num > 0
1321 && track->par->sample_aspect_ratio.den > 0)
1322 display_width = display_width * track->par->sample_aspect_ratio.num / track->par->sample_aspect_ratio.den;
1323 avio_wb32(pb, display_width);
1324 /* values below are based on samples created with quicktime and avid codecs */
1326 avio_wb32(pb, track->par->height / 2);
1327 avio_wb32(pb, 2); /* unknown */
1328 avio_wb32(pb, 0); /* unknown */
1329 avio_wb32(pb, 4); /* unknown */
1331 avio_wb32(pb, track->par->height);
1332 avio_wb32(pb, 1); /* unknown */
1333 avio_wb32(pb, 0); /* unknown */
1334 if (track->par->height == 1080)
1335 avio_wb32(pb, 5); /* unknown */
1337 avio_wb32(pb, 6); /* unknown */
1340 for (i = 0; i < 10; i++)
1346 static int mov_write_dpxe_tag(AVIOContext *pb, MOVTrack *track)
1349 ffio_wfourcc(pb, "DpxE");
1350 if (track->par->extradata_size >= 12 &&
1351 !memcmp(&track->par->extradata[4], "DpxE", 4)) {
1352 avio_wb32(pb, track->par->extradata[11]);
1359 static int mov_get_dv_codec_tag(AVFormatContext *s, MOVTrack *track)
1363 if (track->par->width == 720) { /* SD */
1364 if (track->par->height == 480) { /* NTSC */
1365 if (track->par->format == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','n');
1366 else tag = MKTAG('d','v','c',' ');
1367 }else if (track->par->format == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','p');
1368 else if (track->par->format == AV_PIX_FMT_YUV420P) tag = MKTAG('d','v','c','p');
1369 else tag = MKTAG('d','v','p','p');
1370 } else if (track->par->height == 720) { /* HD 720 line */
1371 if (track->st->time_base.den == 50) tag = MKTAG('d','v','h','q');
1372 else tag = MKTAG('d','v','h','p');
1373 } else if (track->par->height == 1080) { /* HD 1080 line */
1374 if (track->st->time_base.den == 25) tag = MKTAG('d','v','h','5');
1375 else tag = MKTAG('d','v','h','6');
1377 av_log(s, AV_LOG_ERROR, "unsupported height for dv codec\n");
1384 static AVRational find_fps(AVFormatContext *s, AVStream *st)
1386 AVRational rate = st->avg_frame_rate;
1388 #if FF_API_LAVF_AVCTX
1389 FF_DISABLE_DEPRECATION_WARNINGS
1390 rate = av_inv_q(st->codec->time_base);
1391 if (av_timecode_check_frame_rate(rate) < 0) {
1392 av_log(s, AV_LOG_DEBUG, "timecode: tbc=%d/%d invalid, fallback on %d/%d\n",
1393 rate.num, rate.den, st->avg_frame_rate.num, st->avg_frame_rate.den);
1394 rate = st->avg_frame_rate;
1396 FF_ENABLE_DEPRECATION_WARNINGS
1402 static int defined_frame_rate(AVFormatContext *s, AVStream *st)
1404 AVRational rational_framerate = find_fps(s, st);
1406 if (rational_framerate.den != 0)
1407 rate = av_q2d(rational_framerate);
1411 static int mov_get_mpeg2_xdcam_codec_tag(AVFormatContext *s, MOVTrack *track)
1413 int tag = track->par->codec_tag;
1414 int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE;
1415 AVStream *st = track->st;
1416 int rate = defined_frame_rate(s, st);
1419 tag = MKTAG('m', '2', 'v', '1'); //fallback tag
1421 if (track->par->format == AV_PIX_FMT_YUV420P) {
1422 if (track->par->width == 1280 && track->par->height == 720) {
1424 if (rate == 24) tag = MKTAG('x','d','v','4');
1425 else if (rate == 25) tag = MKTAG('x','d','v','5');
1426 else if (rate == 30) tag = MKTAG('x','d','v','1');
1427 else if (rate == 50) tag = MKTAG('x','d','v','a');
1428 else if (rate == 60) tag = MKTAG('x','d','v','9');
1430 } else if (track->par->width == 1440 && track->par->height == 1080) {
1432 if (rate == 24) tag = MKTAG('x','d','v','6');
1433 else if (rate == 25) tag = MKTAG('x','d','v','7');
1434 else if (rate == 30) tag = MKTAG('x','d','v','8');
1436 if (rate == 25) tag = MKTAG('x','d','v','3');
1437 else if (rate == 30) tag = MKTAG('x','d','v','2');
1439 } else if (track->par->width == 1920 && track->par->height == 1080) {
1441 if (rate == 24) tag = MKTAG('x','d','v','d');
1442 else if (rate == 25) tag = MKTAG('x','d','v','e');
1443 else if (rate == 30) tag = MKTAG('x','d','v','f');
1445 if (rate == 25) tag = MKTAG('x','d','v','c');
1446 else if (rate == 30) tag = MKTAG('x','d','v','b');
1449 } else if (track->par->format == AV_PIX_FMT_YUV422P) {
1450 if (track->par->width == 1280 && track->par->height == 720) {
1452 if (rate == 24) tag = MKTAG('x','d','5','4');
1453 else if (rate == 25) tag = MKTAG('x','d','5','5');
1454 else if (rate == 30) tag = MKTAG('x','d','5','1');
1455 else if (rate == 50) tag = MKTAG('x','d','5','a');
1456 else if (rate == 60) tag = MKTAG('x','d','5','9');
1458 } else if (track->par->width == 1920 && track->par->height == 1080) {
1460 if (rate == 24) tag = MKTAG('x','d','5','d');
1461 else if (rate == 25) tag = MKTAG('x','d','5','e');
1462 else if (rate == 30) tag = MKTAG('x','d','5','f');
1464 if (rate == 25) tag = MKTAG('x','d','5','c');
1465 else if (rate == 30) tag = MKTAG('x','d','5','b');
1473 static int mov_get_h264_codec_tag(AVFormatContext *s, MOVTrack *track)
1475 int tag = track->par->codec_tag;
1476 int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE;
1477 AVStream *st = track->st;
1478 int rate = defined_frame_rate(s, st);
1481 tag = MKTAG('a', 'v', 'c', 'i'); //fallback tag
1483 if (track->par->format == AV_PIX_FMT_YUV420P10) {
1484 if (track->par->width == 960 && track->par->height == 720) {
1486 if (rate == 24) tag = MKTAG('a','i','5','p');
1487 else if (rate == 25) tag = MKTAG('a','i','5','q');
1488 else if (rate == 30) tag = MKTAG('a','i','5','p');
1489 else if (rate == 50) tag = MKTAG('a','i','5','q');
1490 else if (rate == 60) tag = MKTAG('a','i','5','p');
1492 } else if (track->par->width == 1440 && track->par->height == 1080) {
1494 if (rate == 24) tag = MKTAG('a','i','5','3');
1495 else if (rate == 25) tag = MKTAG('a','i','5','2');
1496 else if (rate == 30) tag = MKTAG('a','i','5','3');
1498 if (rate == 50) tag = MKTAG('a','i','5','5');
1499 else if (rate == 60) tag = MKTAG('a','i','5','6');
1502 } else if (track->par->format == AV_PIX_FMT_YUV422P10) {
1503 if (track->par->width == 1280 && track->par->height == 720) {
1505 if (rate == 24) tag = MKTAG('a','i','1','p');
1506 else if (rate == 25) tag = MKTAG('a','i','1','q');
1507 else if (rate == 30) tag = MKTAG('a','i','1','p');
1508 else if (rate == 50) tag = MKTAG('a','i','1','q');
1509 else if (rate == 60) tag = MKTAG('a','i','1','p');
1511 } else if (track->par->width == 1920 && track->par->height == 1080) {
1513 if (rate == 24) tag = MKTAG('a','i','1','3');
1514 else if (rate == 25) tag = MKTAG('a','i','1','2');
1515 else if (rate == 30) tag = MKTAG('a','i','1','3');
1517 if (rate == 25) tag = MKTAG('a','i','1','5');
1518 else if (rate == 50) tag = MKTAG('a','i','1','5');
1519 else if (rate == 60) tag = MKTAG('a','i','1','6');
1521 } else if ( track->par->width == 4096 && track->par->height == 2160
1522 || track->par->width == 3840 && track->par->height == 2160
1523 || track->par->width == 2048 && track->par->height == 1080) {
1524 tag = MKTAG('a','i','v','x');
1531 static const struct {
1532 enum AVPixelFormat pix_fmt;
1535 } mov_pix_fmt_tags[] = {
1536 { AV_PIX_FMT_YUYV422, MKTAG('y','u','v','2'), 0 },
1537 { AV_PIX_FMT_YUYV422, MKTAG('y','u','v','s'), 0 },
1538 { AV_PIX_FMT_UYVY422, MKTAG('2','v','u','y'), 0 },
1539 { AV_PIX_FMT_RGB555BE,MKTAG('r','a','w',' '), 16 },
1540 { AV_PIX_FMT_RGB555LE,MKTAG('L','5','5','5'), 16 },
1541 { AV_PIX_FMT_RGB565LE,MKTAG('L','5','6','5'), 16 },
1542 { AV_PIX_FMT_RGB565BE,MKTAG('B','5','6','5'), 16 },
1543 { AV_PIX_FMT_GRAY16BE,MKTAG('b','1','6','g'), 16 },
1544 { AV_PIX_FMT_RGB24, MKTAG('r','a','w',' '), 24 },
1545 { AV_PIX_FMT_BGR24, MKTAG('2','4','B','G'), 24 },
1546 { AV_PIX_FMT_ARGB, MKTAG('r','a','w',' '), 32 },
1547 { AV_PIX_FMT_BGRA, MKTAG('B','G','R','A'), 32 },
1548 { AV_PIX_FMT_RGBA, MKTAG('R','G','B','A'), 32 },
1549 { AV_PIX_FMT_ABGR, MKTAG('A','B','G','R'), 32 },
1550 { AV_PIX_FMT_RGB48BE, MKTAG('b','4','8','r'), 48 },
1553 static int mov_get_dnxhd_codec_tag(AVFormatContext *s, MOVTrack *track)
1555 int tag = MKTAG('A','V','d','n');
1556 if (track->par->profile != FF_PROFILE_UNKNOWN &&
1557 track->par->profile != FF_PROFILE_DNXHD)
1558 tag = MKTAG('A','V','d','h');
1562 static int mov_get_rawvideo_codec_tag(AVFormatContext *s, MOVTrack *track)
1564 int tag = track->par->codec_tag;
1566 enum AVPixelFormat pix_fmt;
1568 for (i = 0; i < FF_ARRAY_ELEMS(mov_pix_fmt_tags); i++) {
1569 if (track->par->format == mov_pix_fmt_tags[i].pix_fmt) {
1570 tag = mov_pix_fmt_tags[i].tag;
1571 track->par->bits_per_coded_sample = mov_pix_fmt_tags[i].bps;
1572 if (track->par->codec_tag == mov_pix_fmt_tags[i].tag)
1577 pix_fmt = avpriv_find_pix_fmt(avpriv_pix_fmt_bps_mov,
1578 track->par->bits_per_coded_sample);
1579 if (tag == MKTAG('r','a','w',' ') &&
1580 track->par->format != pix_fmt &&
1581 track->par->format != AV_PIX_FMT_GRAY8 &&
1582 track->par->format != AV_PIX_FMT_NONE)
1583 av_log(s, AV_LOG_ERROR, "%s rawvideo cannot be written to mov, output file will be unreadable\n",
1584 av_get_pix_fmt_name(track->par->format));
1588 static unsigned int mov_get_codec_tag(AVFormatContext *s, MOVTrack *track)
1590 unsigned int tag = track->par->codec_tag;
1592 if (!tag || (s->strict_std_compliance >= FF_COMPLIANCE_NORMAL &&
1593 (track->par->codec_id == AV_CODEC_ID_DVVIDEO ||
1594 track->par->codec_id == AV_CODEC_ID_RAWVIDEO ||
1595 track->par->codec_id == AV_CODEC_ID_H263 ||
1596 track->par->codec_id == AV_CODEC_ID_H264 ||
1597 track->par->codec_id == AV_CODEC_ID_DNXHD ||
1598 track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO ||
1599 av_get_bits_per_sample(track->par->codec_id)))) { // pcm audio
1600 if (track->par->codec_id == AV_CODEC_ID_DVVIDEO)
1601 tag = mov_get_dv_codec_tag(s, track);
1602 else if (track->par->codec_id == AV_CODEC_ID_RAWVIDEO)
1603 tag = mov_get_rawvideo_codec_tag(s, track);
1604 else if (track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO)
1605 tag = mov_get_mpeg2_xdcam_codec_tag(s, track);
1606 else if (track->par->codec_id == AV_CODEC_ID_H264)
1607 tag = mov_get_h264_codec_tag(s, track);
1608 else if (track->par->codec_id == AV_CODEC_ID_DNXHD)
1609 tag = mov_get_dnxhd_codec_tag(s, track);
1610 else if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
1611 tag = ff_codec_get_tag(ff_codec_movvideo_tags, track->par->codec_id);
1612 if (!tag) { // if no mac fcc found, try with Microsoft tags
1613 tag = ff_codec_get_tag(ff_codec_bmp_tags, track->par->codec_id);
1615 av_log(s, AV_LOG_WARNING, "Using MS style video codec tag, "
1616 "the file may be unplayable!\n");
1618 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
1619 tag = ff_codec_get_tag(ff_codec_movaudio_tags, track->par->codec_id);
1620 if (!tag) { // if no mac fcc found, try with Microsoft tags
1621 int ms_tag = ff_codec_get_tag(ff_codec_wav_tags, track->par->codec_id);
1623 tag = MKTAG('m', 's', ((ms_tag >> 8) & 0xff), (ms_tag & 0xff));
1624 av_log(s, AV_LOG_WARNING, "Using MS style audio codec tag, "
1625 "the file may be unplayable!\n");
1628 } else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)
1629 tag = ff_codec_get_tag(ff_codec_movsubtitle_tags, track->par->codec_id);
1635 static const AVCodecTag codec_cover_image_tags[] = {
1636 { AV_CODEC_ID_MJPEG, 0xD },
1637 { AV_CODEC_ID_PNG, 0xE },
1638 { AV_CODEC_ID_BMP, 0x1B },
1639 { AV_CODEC_ID_NONE, 0 },
1642 static unsigned int validate_codec_tag(const AVCodecTag *const *tags,
1643 unsigned int tag, int codec_id)
1648 * Check that tag + id is in the table
1650 for (i = 0; tags && tags[i]; i++) {
1651 const AVCodecTag *codec_tags = tags[i];
1652 while (codec_tags->id != AV_CODEC_ID_NONE) {
1653 if (avpriv_toupper4(codec_tags->tag) == avpriv_toupper4(tag) &&
1654 codec_tags->id == codec_id)
1655 return codec_tags->tag;
1662 static unsigned int mov_find_codec_tag(AVFormatContext *s, MOVTrack *track)
1664 if (is_cover_image(track->st))
1665 return ff_codec_get_tag(codec_cover_image_tags, track->par->codec_id);
1667 if (track->mode == MODE_IPOD)
1668 if (!av_match_ext(s->url, "m4a") &&
1669 !av_match_ext(s->url, "m4v") &&
1670 !av_match_ext(s->url, "m4b"))
1671 av_log(s, AV_LOG_WARNING, "Warning, extension is not .m4a nor .m4v "
1672 "Quicktime/Ipod might not play the file\n");
1674 if (track->mode == MODE_MOV) {
1675 return mov_get_codec_tag(s, track);
1677 return validate_codec_tag(s->oformat->codec_tag, track->par->codec_tag,
1678 track->par->codec_id);
1681 /** Write uuid atom.
1682 * Needed to make file play in iPods running newest firmware
1683 * goes after avcC atom in moov.trak.mdia.minf.stbl.stsd.avc1
1685 static int mov_write_uuid_tag_ipod(AVIOContext *pb)
1688 ffio_wfourcc(pb, "uuid");
1689 avio_wb32(pb, 0x6b6840f2);
1690 avio_wb32(pb, 0x5f244fc5);
1691 avio_wb32(pb, 0xba39a51b);
1692 avio_wb32(pb, 0xcf0323f3);
1697 static const uint16_t fiel_data[] = {
1698 0x0000, 0x0100, 0x0201, 0x0206, 0x0209, 0x020e
1701 static int mov_write_fiel_tag(AVIOContext *pb, MOVTrack *track, int field_order)
1703 unsigned mov_field_order = 0;
1704 if (field_order < FF_ARRAY_ELEMS(fiel_data))
1705 mov_field_order = fiel_data[field_order];
1709 ffio_wfourcc(pb, "fiel");
1710 avio_wb16(pb, mov_field_order);
1714 static int mov_write_subtitle_tag(AVIOContext *pb, MOVTrack *track)
1716 int64_t pos = avio_tell(pb);
1717 avio_wb32(pb, 0); /* size */
1718 avio_wl32(pb, track->tag); // store it byteswapped
1719 avio_wb32(pb, 0); /* Reserved */
1720 avio_wb16(pb, 0); /* Reserved */
1721 avio_wb16(pb, 1); /* Data-reference index */
1723 if (track->par->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
1724 mov_write_esds_tag(pb, track);
1725 else if (track->par->extradata_size)
1726 avio_write(pb, track->par->extradata, track->par->extradata_size);
1728 return update_size(pb, pos);
1731 static int mov_write_st3d_tag(AVFormatContext *s, AVIOContext *pb, AVStereo3D *stereo_3d)
1735 if (stereo_3d->flags != 0) {
1736 av_log(s, AV_LOG_WARNING, "Unsupported stereo_3d flags %x. st3d not written.\n", stereo_3d->flags);
1740 switch (stereo_3d->type) {
1741 case AV_STEREO3D_2D:
1744 case AV_STEREO3D_TOPBOTTOM:
1747 case AV_STEREO3D_SIDEBYSIDE:
1751 av_log(s, AV_LOG_WARNING, "Unsupported stereo_3d type %s. st3d not written.\n", av_stereo3d_type_name(stereo_3d->type));
1754 avio_wb32(pb, 13); /* size */
1755 ffio_wfourcc(pb, "st3d");
1756 avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1757 avio_w8(pb, stereo_mode);
1761 static int mov_write_sv3d_tag(AVFormatContext *s, AVIOContext *pb, AVSphericalMapping *spherical_mapping)
1763 int64_t sv3d_pos, svhd_pos, proj_pos;
1764 const char* metadata_source = s->flags & AVFMT_FLAG_BITEXACT ? "Lavf" : LIBAVFORMAT_IDENT;
1766 if (spherical_mapping->projection != AV_SPHERICAL_EQUIRECTANGULAR &&
1767 spherical_mapping->projection != AV_SPHERICAL_EQUIRECTANGULAR_TILE &&
1768 spherical_mapping->projection != AV_SPHERICAL_CUBEMAP) {
1769 av_log(s, AV_LOG_WARNING, "Unsupported projection %d. sv3d not written.\n", spherical_mapping->projection);
1773 sv3d_pos = avio_tell(pb);
1774 avio_wb32(pb, 0); /* size */
1775 ffio_wfourcc(pb, "sv3d");
1777 svhd_pos = avio_tell(pb);
1778 avio_wb32(pb, 0); /* size */
1779 ffio_wfourcc(pb, "svhd");
1780 avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1781 avio_put_str(pb, metadata_source);
1782 update_size(pb, svhd_pos);
1784 proj_pos = avio_tell(pb);
1785 avio_wb32(pb, 0); /* size */
1786 ffio_wfourcc(pb, "proj");
1788 avio_wb32(pb, 24); /* size */
1789 ffio_wfourcc(pb, "prhd");
1790 avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1791 avio_wb32(pb, spherical_mapping->yaw);
1792 avio_wb32(pb, spherical_mapping->pitch);
1793 avio_wb32(pb, spherical_mapping->roll);
1795 switch (spherical_mapping->projection) {
1796 case AV_SPHERICAL_EQUIRECTANGULAR:
1797 case AV_SPHERICAL_EQUIRECTANGULAR_TILE:
1798 avio_wb32(pb, 28); /* size */
1799 ffio_wfourcc(pb, "equi");
1800 avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1801 avio_wb32(pb, spherical_mapping->bound_top);
1802 avio_wb32(pb, spherical_mapping->bound_bottom);
1803 avio_wb32(pb, spherical_mapping->bound_left);
1804 avio_wb32(pb, spherical_mapping->bound_right);
1806 case AV_SPHERICAL_CUBEMAP:
1807 avio_wb32(pb, 20); /* size */
1808 ffio_wfourcc(pb, "cbmp");
1809 avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1810 avio_wb32(pb, 0); /* layout */
1811 avio_wb32(pb, spherical_mapping->padding); /* padding */
1814 update_size(pb, proj_pos);
1816 return update_size(pb, sv3d_pos);
1819 static int mov_write_clap_tag(AVIOContext *pb, MOVTrack *track)
1822 ffio_wfourcc(pb, "clap");
1823 avio_wb32(pb, track->par->width); /* apertureWidth_N */
1824 avio_wb32(pb, 1); /* apertureWidth_D (= 1) */
1825 avio_wb32(pb, track->height); /* apertureHeight_N */
1826 avio_wb32(pb, 1); /* apertureHeight_D (= 1) */
1827 avio_wb32(pb, 0); /* horizOff_N (= 0) */
1828 avio_wb32(pb, 1); /* horizOff_D (= 1) */
1829 avio_wb32(pb, 0); /* vertOff_N (= 0) */
1830 avio_wb32(pb, 1); /* vertOff_D (= 1) */
1834 static int mov_write_pasp_tag(AVIOContext *pb, MOVTrack *track)
1837 av_reduce(&sar.num, &sar.den, track->par->sample_aspect_ratio.num,
1838 track->par->sample_aspect_ratio.den, INT_MAX);
1841 ffio_wfourcc(pb, "pasp");
1842 avio_wb32(pb, sar.num);
1843 avio_wb32(pb, sar.den);
1847 static int mov_write_gama_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track, double gamma)
1851 gamma = avpriv_get_gamma_from_trc(track->par->color_trc);
1853 av_log(s, AV_LOG_DEBUG, "gamma value %g\n", gamma);
1856 gama = (uint32_t)lrint((double)(1<<16) * gamma);
1857 av_log(s, AV_LOG_DEBUG, "writing gama value %"PRId32"\n", gama);
1859 av_assert0(track->mode == MODE_MOV);
1861 ffio_wfourcc(pb, "gama");
1862 avio_wb32(pb, gama);
1865 av_log(s, AV_LOG_WARNING, "gamma value unknown, unable to write gama atom\n");
1870 static int mov_write_colr_tag(AVIOContext *pb, MOVTrack *track, int prefer_icc)
1872 int64_t pos = avio_tell(pb);
1874 // Ref (MOV): https://developer.apple.com/library/mac/technotes/tn2162/_index.html#//apple_ref/doc/uid/DTS40013070-CH1-TNTAG9
1875 // Ref (MP4): ISO/IEC 14496-12:2012
1877 const uint8_t *icc_profile;
1878 int icc_profile_size;
1881 icc_profile = av_stream_get_side_data(track->st, AV_PKT_DATA_ICC_PROFILE, &icc_profile_size);
1884 avio_wb32(pb, 12 + icc_profile_size);
1885 ffio_wfourcc(pb, "colr");
1886 ffio_wfourcc(pb, "prof");
1887 avio_write(pb, icc_profile, icc_profile_size);
1888 return 12 + icc_profile_size;
1891 av_log(NULL, AV_LOG_INFO, "no ICC profile found, will write nclx/nclc colour info instead\n");
1895 if (track->par->color_primaries == AVCOL_PRI_UNSPECIFIED &&
1896 track->par->color_trc == AVCOL_TRC_UNSPECIFIED &&
1897 track->par->color_space == AVCOL_SPC_UNSPECIFIED) {
1898 if ((track->par->width >= 1920 && track->par->height >= 1080)
1899 || (track->par->width == 1280 && track->par->height == 720)) {
1900 av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming bt709\n");
1901 track->par->color_primaries = AVCOL_PRI_BT709;
1902 } else if (track->par->width == 720 && track->height == 576) {
1903 av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming bt470bg\n");
1904 track->par->color_primaries = AVCOL_PRI_BT470BG;
1905 } else if (track->par->width == 720 &&
1906 (track->height == 486 || track->height == 480)) {
1907 av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming smpte170\n");
1908 track->par->color_primaries = AVCOL_PRI_SMPTE170M;
1910 av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, unable to assume anything\n");
1912 switch (track->par->color_primaries) {
1913 case AVCOL_PRI_BT709:
1914 track->par->color_trc = AVCOL_TRC_BT709;
1915 track->par->color_space = AVCOL_SPC_BT709;
1917 case AVCOL_PRI_SMPTE170M:
1918 case AVCOL_PRI_BT470BG:
1919 track->par->color_trc = AVCOL_TRC_BT709;
1920 track->par->color_space = AVCOL_SPC_SMPTE170M;
1925 /* We should only ever be called by MOV or MP4. */
1926 av_assert0(track->mode == MODE_MOV || track->mode == MODE_MP4);
1928 avio_wb32(pb, 0); /* size */
1929 ffio_wfourcc(pb, "colr");
1930 if (track->mode == MODE_MP4)
1931 ffio_wfourcc(pb, "nclx");
1933 ffio_wfourcc(pb, "nclc");
1934 switch (track->par->color_primaries) {
1935 case AVCOL_PRI_BT709: avio_wb16(pb, 1); break;
1936 case AVCOL_PRI_BT470BG: avio_wb16(pb, 5); break;
1937 case AVCOL_PRI_SMPTE170M:
1938 case AVCOL_PRI_SMPTE240M: avio_wb16(pb, 6); break;
1939 case AVCOL_PRI_BT2020: avio_wb16(pb, 9); break;
1940 case AVCOL_PRI_SMPTE431: avio_wb16(pb, 11); break;
1941 case AVCOL_PRI_SMPTE432: avio_wb16(pb, 12); break;
1942 default: avio_wb16(pb, 2);
1944 switch (track->par->color_trc) {
1945 case AVCOL_TRC_BT709: avio_wb16(pb, 1); break;
1946 case AVCOL_TRC_SMPTE170M: avio_wb16(pb, 1); break; // remapped
1947 case AVCOL_TRC_SMPTE240M: avio_wb16(pb, 7); break;
1948 case AVCOL_TRC_SMPTEST2084: avio_wb16(pb, 16); break;
1949 case AVCOL_TRC_SMPTE428: avio_wb16(pb, 17); break;
1950 case AVCOL_TRC_ARIB_STD_B67: avio_wb16(pb, 18); break;
1951 default: avio_wb16(pb, 2);
1953 switch (track->par->color_space) {
1954 case AVCOL_SPC_BT709: avio_wb16(pb, 1); break;
1955 case AVCOL_SPC_BT470BG:
1956 case AVCOL_SPC_SMPTE170M: avio_wb16(pb, 6); break;
1957 case AVCOL_SPC_SMPTE240M: avio_wb16(pb, 7); break;
1958 case AVCOL_SPC_BT2020_NCL: avio_wb16(pb, 9); break;
1959 default: avio_wb16(pb, 2);
1962 if (track->mode == MODE_MP4) {
1963 int full_range = track->par->color_range == AVCOL_RANGE_JPEG;
1964 avio_w8(pb, full_range << 7);
1967 return update_size(pb, pos);
1970 static void find_compressor(char * compressor_name, int len, MOVTrack *track)
1972 AVDictionaryEntry *encoder;
1973 int xdcam_res = (track->par->width == 1280 && track->par->height == 720)
1974 || (track->par->width == 1440 && track->par->height == 1080)
1975 || (track->par->width == 1920 && track->par->height == 1080);
1977 if (track->mode == MODE_MOV &&
1978 (encoder = av_dict_get(track->st->metadata, "encoder", NULL, 0))) {
1979 av_strlcpy(compressor_name, encoder->value, 32);
1980 } else if (track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO && xdcam_res) {
1981 int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE;
1982 AVStream *st = track->st;
1983 int rate = defined_frame_rate(NULL, st);
1984 av_strlcatf(compressor_name, len, "XDCAM");
1985 if (track->par->format == AV_PIX_FMT_YUV422P) {
1986 av_strlcatf(compressor_name, len, " HD422");
1987 } else if(track->par->width == 1440) {
1988 av_strlcatf(compressor_name, len, " HD");
1990 av_strlcatf(compressor_name, len, " EX");
1992 av_strlcatf(compressor_name, len, " %d%c", track->par->height, interlaced ? 'i' : 'p');
1994 av_strlcatf(compressor_name, len, "%d", rate * (interlaced + 1));
1998 static int mov_write_video_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
2000 int64_t pos = avio_tell(pb);
2001 char compressor_name[32] = { 0 };
2004 int uncompressed_ycbcr = ((track->par->codec_id == AV_CODEC_ID_RAWVIDEO && track->par->format == AV_PIX_FMT_UYVY422)
2005 || (track->par->codec_id == AV_CODEC_ID_RAWVIDEO && track->par->format == AV_PIX_FMT_YUYV422)
2006 || track->par->codec_id == AV_CODEC_ID_V308
2007 || track->par->codec_id == AV_CODEC_ID_V408
2008 || track->par->codec_id == AV_CODEC_ID_V410
2009 || track->par->codec_id == AV_CODEC_ID_V210);
2011 avio_wb32(pb, 0); /* size */
2012 if (mov->encryption_scheme != MOV_ENC_NONE) {
2013 ffio_wfourcc(pb, "encv");
2015 avio_wl32(pb, track->tag); // store it byteswapped
2017 avio_wb32(pb, 0); /* Reserved */
2018 avio_wb16(pb, 0); /* Reserved */
2019 avio_wb16(pb, 1); /* Data-reference index */
2021 if (uncompressed_ycbcr) {
2022 avio_wb16(pb, 2); /* Codec stream version */
2024 avio_wb16(pb, 0); /* Codec stream version */
2026 avio_wb16(pb, 0); /* Codec stream revision (=0) */
2027 if (track->mode == MODE_MOV) {
2028 ffio_wfourcc(pb, "FFMP"); /* Vendor */
2029 if (track->par->codec_id == AV_CODEC_ID_RAWVIDEO || uncompressed_ycbcr) {
2030 avio_wb32(pb, 0); /* Temporal Quality */
2031 avio_wb32(pb, 0x400); /* Spatial Quality = lossless*/
2033 avio_wb32(pb, 0x200); /* Temporal Quality = normal */
2034 avio_wb32(pb, 0x200); /* Spatial Quality = normal */
2037 avio_wb32(pb, 0); /* Reserved */
2038 avio_wb32(pb, 0); /* Reserved */
2039 avio_wb32(pb, 0); /* Reserved */
2041 avio_wb16(pb, track->par->width); /* Video width */
2042 avio_wb16(pb, track->height); /* Video height */
2043 avio_wb32(pb, 0x00480000); /* Horizontal resolution 72dpi */
2044 avio_wb32(pb, 0x00480000); /* Vertical resolution 72dpi */
2045 avio_wb32(pb, 0); /* Data size (= 0) */
2046 avio_wb16(pb, 1); /* Frame count (= 1) */
2048 /* FIXME not sure, ISO 14496-1 draft where it shall be set to 0 */
2049 find_compressor(compressor_name, 32, track);
2050 avio_w8(pb, strlen(compressor_name));
2051 avio_write(pb, compressor_name, 31);
2053 if (track->mode == MODE_MOV &&
2054 (track->par->codec_id == AV_CODEC_ID_V410 || track->par->codec_id == AV_CODEC_ID_V210))
2055 avio_wb16(pb, 0x18);
2056 else if (track->mode == MODE_MOV && track->par->bits_per_coded_sample)
2057 avio_wb16(pb, track->par->bits_per_coded_sample |
2058 (track->par->format == AV_PIX_FMT_GRAY8 ? 0x20 : 0));
2060 avio_wb16(pb, 0x18); /* Reserved */
2062 if (track->mode == MODE_MOV && track->par->format == AV_PIX_FMT_PAL8) {
2063 int pal_size = 1 << track->par->bits_per_coded_sample;
2065 avio_wb16(pb, 0); /* Color table ID */
2066 avio_wb32(pb, 0); /* Color table seed */
2067 avio_wb16(pb, 0x8000); /* Color table flags */
2068 avio_wb16(pb, pal_size - 1); /* Color table size (zero-relative) */
2069 for (i = 0; i < pal_size; i++) {
2070 uint32_t rgb = track->palette[i];
2071 uint16_t r = (rgb >> 16) & 0xff;
2072 uint16_t g = (rgb >> 8) & 0xff;
2073 uint16_t b = rgb & 0xff;
2075 avio_wb16(pb, (r << 8) | r);
2076 avio_wb16(pb, (g << 8) | g);
2077 avio_wb16(pb, (b << 8) | b);
2080 avio_wb16(pb, 0xffff); /* Reserved */
2082 if (track->tag == MKTAG('m','p','4','v'))
2083 mov_write_esds_tag(pb, track);
2084 else if (track->par->codec_id == AV_CODEC_ID_H263)
2085 mov_write_d263_tag(pb);
2086 else if (track->par->codec_id == AV_CODEC_ID_AVUI ||
2087 track->par->codec_id == AV_CODEC_ID_SVQ3) {
2088 mov_write_extradata_tag(pb, track);
2090 } else if (track->par->codec_id == AV_CODEC_ID_DNXHD) {
2091 mov_write_avid_tag(pb, track);
2093 } else if (track->par->codec_id == AV_CODEC_ID_HEVC)
2094 mov_write_hvcc_tag(pb, track);
2095 else if (track->par->codec_id == AV_CODEC_ID_H264 && !TAG_IS_AVCI(track->tag)) {
2096 mov_write_avcc_tag(pb, track);
2097 if (track->mode == MODE_IPOD)
2098 mov_write_uuid_tag_ipod(pb);
2099 } else if (track->par->codec_id == AV_CODEC_ID_VP9) {
2100 mov_write_vpcc_tag(mov->fc, pb, track);
2101 } else if (track->par->codec_id == AV_CODEC_ID_AV1) {
2102 mov_write_av1c_tag(pb, track);
2103 } else if (track->par->codec_id == AV_CODEC_ID_VC1 && track->vos_len > 0)
2104 mov_write_dvc1_tag(pb, track);
2105 else if (track->par->codec_id == AV_CODEC_ID_VP6F ||
2106 track->par->codec_id == AV_CODEC_ID_VP6A) {
2107 /* Don't write any potential extradata here - the cropping
2108 * is signalled via the normal width/height fields. */
2109 } else if (track->par->codec_id == AV_CODEC_ID_R10K) {
2110 if (track->par->codec_tag == MKTAG('R','1','0','k'))
2111 mov_write_dpxe_tag(pb, track);
2112 } else if (track->vos_len > 0)
2113 mov_write_glbl_tag(pb, track);
2115 if (track->par->codec_id != AV_CODEC_ID_H264 &&
2116 track->par->codec_id != AV_CODEC_ID_MPEG4 &&
2117 track->par->codec_id != AV_CODEC_ID_DNXHD) {
2118 int field_order = track->par->field_order;
2120 #if FF_API_LAVF_AVCTX
2121 FF_DISABLE_DEPRECATION_WARNINGS
2122 if (field_order != track->st->codec->field_order && track->st->codec->field_order != AV_FIELD_UNKNOWN)
2123 field_order = track->st->codec->field_order;
2124 FF_ENABLE_DEPRECATION_WARNINGS
2127 if (field_order != AV_FIELD_UNKNOWN)
2128 mov_write_fiel_tag(pb, track, field_order);
2131 if (mov->flags & FF_MOV_FLAG_WRITE_GAMA) {
2132 if (track->mode == MODE_MOV)
2133 mov_write_gama_tag(s, pb, track, mov->gamma);
2135 av_log(mov->fc, AV_LOG_WARNING, "Not writing 'gama' atom. Format is not MOV.\n");
2137 if (mov->flags & FF_MOV_FLAG_WRITE_COLR) {
2138 if (track->mode == MODE_MOV || track->mode == MODE_MP4)
2139 mov_write_colr_tag(pb, track, mov->flags & FF_MOV_FLAG_PREFER_ICC);
2141 av_log(mov->fc, AV_LOG_WARNING, "Not writing 'colr' atom. Format is not MOV or MP4.\n");
2144 if (track->mode == MODE_MP4 && mov->fc->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL) {
2145 AVStereo3D* stereo_3d = (AVStereo3D*) av_stream_get_side_data(track->st, AV_PKT_DATA_STEREO3D, NULL);
2146 AVSphericalMapping* spherical_mapping = (AVSphericalMapping*)av_stream_get_side_data(track->st, AV_PKT_DATA_SPHERICAL, NULL);
2149 mov_write_st3d_tag(s, pb, stereo_3d);
2150 if (spherical_mapping)
2151 mov_write_sv3d_tag(mov->fc, pb, spherical_mapping);
2154 if (track->par->sample_aspect_ratio.den && track->par->sample_aspect_ratio.num) {
2155 mov_write_pasp_tag(pb, track);
2158 if (uncompressed_ycbcr){
2159 mov_write_clap_tag(pb, track);
2162 if (mov->encryption_scheme != MOV_ENC_NONE) {
2163 ff_mov_cenc_write_sinf_tag(track, pb, mov->encryption_kid);
2166 /* extra padding for avid stsd */
2167 /* https://developer.apple.com/library/mac/documentation/QuickTime/QTFF/QTFFChap2/qtff2.html#//apple_ref/doc/uid/TP40000939-CH204-61112 */
2171 return update_size(pb, pos);
2174 static int mov_write_rtp_tag(AVIOContext *pb, MOVTrack *track)
2176 int64_t pos = avio_tell(pb);
2177 avio_wb32(pb, 0); /* size */
2178 ffio_wfourcc(pb, "rtp ");
2179 avio_wb32(pb, 0); /* Reserved */
2180 avio_wb16(pb, 0); /* Reserved */
2181 avio_wb16(pb, 1); /* Data-reference index */
2183 avio_wb16(pb, 1); /* Hint track version */
2184 avio_wb16(pb, 1); /* Highest compatible version */
2185 avio_wb32(pb, track->max_packet_size); /* Max packet size */
2187 avio_wb32(pb, 12); /* size */
2188 ffio_wfourcc(pb, "tims");
2189 avio_wb32(pb, track->timescale);
2191 return update_size(pb, pos);
2194 static int mov_write_source_reference_tag(AVIOContext *pb, MOVTrack *track, const char *reel_name)
2196 uint64_t str_size =strlen(reel_name);
2197 int64_t pos = avio_tell(pb);
2199 if (str_size >= UINT16_MAX){
2200 av_log(NULL, AV_LOG_ERROR, "reel_name length %"PRIu64" is too large\n", str_size);
2202 return AVERROR(EINVAL);
2205 avio_wb32(pb, 0); /* size */
2206 ffio_wfourcc(pb, "name"); /* Data format */
2207 avio_wb16(pb, str_size); /* string size */
2208 avio_wb16(pb, track->language); /* langcode */
2209 avio_write(pb, reel_name, str_size); /* reel name */
2210 return update_size(pb,pos);
2213 static int mov_write_tmcd_tag(AVIOContext *pb, MOVTrack *track)
2215 int64_t pos = avio_tell(pb);
2219 AVDictionaryEntry *t = NULL;
2221 if (!track->st->avg_frame_rate.num || !track->st->avg_frame_rate.den) {
2222 #if FF_API_LAVF_AVCTX
2223 FF_DISABLE_DEPRECATION_WARNINGS
2224 frame_duration = av_rescale(track->timescale, track->st->codec->time_base.num, track->st->codec->time_base.den);
2225 nb_frames = ROUNDED_DIV(track->st->codec->time_base.den, track->st->codec->time_base.num);
2226 FF_ENABLE_DEPRECATION_WARNINGS
2228 av_log(NULL, AV_LOG_ERROR, "avg_frame_rate not set for tmcd track.\n");
2229 return AVERROR(EINVAL);
2232 frame_duration = av_rescale(track->timescale, track->st->avg_frame_rate.num, track->st->avg_frame_rate.den);
2233 nb_frames = ROUNDED_DIV(track->st->avg_frame_rate.den, track->st->avg_frame_rate.num);
2236 if (nb_frames > 255) {
2237 av_log(NULL, AV_LOG_ERROR, "fps %d is too large\n", nb_frames);
2238 return AVERROR(EINVAL);
2241 avio_wb32(pb, 0); /* size */
2242 ffio_wfourcc(pb, "tmcd"); /* Data format */
2243 avio_wb32(pb, 0); /* Reserved */
2244 avio_wb32(pb, 1); /* Data reference index */
2245 avio_wb32(pb, 0); /* Flags */
2246 avio_wb32(pb, track->timecode_flags); /* Flags (timecode) */
2247 avio_wb32(pb, track->timescale); /* Timescale */
2248 avio_wb32(pb, frame_duration); /* Frame duration */
2249 avio_w8(pb, nb_frames); /* Number of frames */
2250 avio_w8(pb, 0); /* Reserved */
2252 t = av_dict_get(track->st->metadata, "reel_name", NULL, 0);
2253 if (t && utf8len(t->value) && track->mode != MODE_MP4)
2254 mov_write_source_reference_tag(pb, track, t->value);
2256 avio_wb16(pb, 0); /* zero size */
2259 avio_wb32(pb, 0); /* size */
2260 ffio_wfourcc(pb, "tmcd"); /* Data format */
2261 avio_wb32(pb, 0); /* Reserved */
2262 avio_wb32(pb, 1); /* Data reference index */
2263 if (track->par->extradata_size)
2264 avio_write(pb, track->par->extradata, track->par->extradata_size);
2266 return update_size(pb, pos);
2269 static int mov_write_gpmd_tag(AVIOContext *pb, const MOVTrack *track)
2271 int64_t pos = avio_tell(pb);
2272 avio_wb32(pb, 0); /* size */
2273 ffio_wfourcc(pb, "gpmd");
2274 avio_wb32(pb, 0); /* Reserved */
2275 avio_wb16(pb, 0); /* Reserved */
2276 avio_wb16(pb, 1); /* Data-reference index */
2277 avio_wb32(pb, 0); /* Reserved */
2278 return update_size(pb, pos);
2281 static int mov_write_stsd_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
2283 int64_t pos = avio_tell(pb);
2285 avio_wb32(pb, 0); /* size */
2286 ffio_wfourcc(pb, "stsd");
2287 avio_wb32(pb, 0); /* version & flags */
2288 avio_wb32(pb, 1); /* entry count */
2289 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO)
2290 ret = mov_write_video_tag(s, pb, mov, track);
2291 else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
2292 ret = mov_write_audio_tag(s, pb, mov, track);
2293 else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)
2294 ret = mov_write_subtitle_tag(pb, track);
2295 else if (track->par->codec_tag == MKTAG('r','t','p',' '))
2296 ret = mov_write_rtp_tag(pb, track);
2297 else if (track->par->codec_tag == MKTAG('t','m','c','d'))
2298 ret = mov_write_tmcd_tag(pb, track);
2299 else if (track->par->codec_tag == MKTAG('g','p','m','d'))
2300 ret = mov_write_gpmd_tag(pb, track);
2305 return update_size(pb, pos);
2308 static int mov_write_ctts_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
2310 MOVMuxContext *mov = s->priv_data;
2311 MOVStts *ctts_entries;
2312 uint32_t entries = 0;
2316 ctts_entries = av_malloc_array((track->entry + 1), sizeof(*ctts_entries)); /* worst case */
2318 return AVERROR(ENOMEM);
2319 ctts_entries[0].count = 1;
2320 ctts_entries[0].duration = track->cluster[0].cts;
2321 for (i = 1; i < track->entry; i++) {
2322 if (track->cluster[i].cts == ctts_entries[entries].duration) {
2323 ctts_entries[entries].count++; /* compress */
2326 ctts_entries[entries].duration = track->cluster[i].cts;
2327 ctts_entries[entries].count = 1;
2330 entries++; /* last one */
2331 atom_size = 16 + (entries * 8);
2332 avio_wb32(pb, atom_size); /* size */
2333 ffio_wfourcc(pb, "ctts");
2334 if (mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS)
2335 avio_w8(pb, 1); /* version */
2337 avio_w8(pb, 0); /* version */
2338 avio_wb24(pb, 0); /* flags */
2339 avio_wb32(pb, entries); /* entry count */
2340 for (i = 0; i < entries; i++) {
2341 avio_wb32(pb, ctts_entries[i].count);
2342 avio_wb32(pb, ctts_entries[i].duration);
2344 av_free(ctts_entries);
2348 /* Time to sample atom */
2349 static int mov_write_stts_tag(AVIOContext *pb, MOVTrack *track)
2351 MOVStts *stts_entries = NULL;
2352 uint32_t entries = -1;
2356 if (track->par->codec_type == AVMEDIA_TYPE_AUDIO && !track->audio_vbr) {
2357 stts_entries = av_malloc(sizeof(*stts_entries)); /* one entry */
2359 return AVERROR(ENOMEM);
2360 stts_entries[0].count = track->sample_count;
2361 stts_entries[0].duration = 1;
2365 stts_entries = av_malloc_array(track->entry, sizeof(*stts_entries)); /* worst case */
2367 return AVERROR(ENOMEM);
2369 for (i = 0; i < track->entry; i++) {
2370 int duration = get_cluster_duration(track, i);
2371 if (i && duration == stts_entries[entries].duration) {
2372 stts_entries[entries].count++; /* compress */
2375 stts_entries[entries].duration = duration;
2376 stts_entries[entries].count = 1;
2379 entries++; /* last one */
2381 atom_size = 16 + (entries * 8);
2382 avio_wb32(pb, atom_size); /* size */
2383 ffio_wfourcc(pb, "stts");
2384 avio_wb32(pb, 0); /* version & flags */
2385 avio_wb32(pb, entries); /* entry count */
2386 for (i = 0; i < entries; i++) {
2387 avio_wb32(pb, stts_entries[i].count);
2388 avio_wb32(pb, stts_entries[i].duration);
2390 av_free(stts_entries);
2394 static int mov_write_dref_tag(AVIOContext *pb)
2396 avio_wb32(pb, 28); /* size */
2397 ffio_wfourcc(pb, "dref");
2398 avio_wb32(pb, 0); /* version & flags */
2399 avio_wb32(pb, 1); /* entry count */
2401 avio_wb32(pb, 0xc); /* size */
2402 //FIXME add the alis and rsrc atom
2403 ffio_wfourcc(pb, "url ");
2404 avio_wb32(pb, 1); /* version & flags */
2409 static int mov_preroll_write_stbl_atoms(AVIOContext *pb, MOVTrack *track)
2413 int16_t roll_distance;
2414 int group_description_index;
2417 struct sgpd_entry *sgpd_entries = NULL;
2422 const int OPUS_SEEK_PREROLL_MS = 80;
2423 int roll_samples = av_rescale_q(OPUS_SEEK_PREROLL_MS,
2424 (AVRational){1, 1000},
2425 (AVRational){1, 48000});
2430 sgpd_entries = av_malloc_array(track->entry, sizeof(*sgpd_entries));
2432 return AVERROR(ENOMEM);
2434 av_assert0(track->par->codec_id == AV_CODEC_ID_OPUS || track->par->codec_id == AV_CODEC_ID_AAC);
2436 if (track->par->codec_id == AV_CODEC_ID_OPUS) {
2437 for (i = 0; i < track->entry; i++) {
2438 int roll_samples_remaining = roll_samples;
2440 for (j = i - 1; j >= 0; j--) {
2441 roll_samples_remaining -= get_cluster_duration(track, j);
2443 if (roll_samples_remaining <= 0)
2446 /* We don't have enough preceeding samples to compute a valid
2447 roll_distance here, so this sample can't be independently
2449 if (roll_samples_remaining > 0)
2451 /* Verify distance is a maximum of 32 (2.5ms) packets. */
2453 return AVERROR_INVALIDDATA;
2454 if (i && distance == sgpd_entries[entries].roll_distance) {
2455 sgpd_entries[entries].count++;
2458 sgpd_entries[entries].count = 1;
2459 sgpd_entries[entries].roll_distance = distance;
2460 sgpd_entries[entries].group_description_index = distance ? ++group : 0;
2465 sgpd_entries[entries].count = track->sample_count;
2466 sgpd_entries[entries].roll_distance = 1;
2467 sgpd_entries[entries].group_description_index = ++group;
2472 av_free(sgpd_entries);
2476 /* Write sgpd tag */
2477 avio_wb32(pb, 24 + (group * 2)); /* size */
2478 ffio_wfourcc(pb, "sgpd");
2479 avio_wb32(pb, 1 << 24); /* fullbox */
2480 ffio_wfourcc(pb, "roll");
2481 avio_wb32(pb, 2); /* default_length */
2482 avio_wb32(pb, group); /* entry_count */
2483 for (i = 0; i < entries; i++) {
2484 if (sgpd_entries[i].group_description_index) {
2485 avio_wb16(pb, -sgpd_entries[i].roll_distance); /* roll_distance */
2489 /* Write sbgp tag */
2490 avio_wb32(pb, 20 + (entries * 8)); /* size */
2491 ffio_wfourcc(pb, "sbgp");
2492 avio_wb32(pb, 0); /* fullbox */
2493 ffio_wfourcc(pb, "roll");
2494 avio_wb32(pb, entries); /* entry_count */
2495 for (i = 0; i < entries; i++) {
2496 avio_wb32(pb, sgpd_entries[i].count); /* sample_count */
2497 avio_wb32(pb, sgpd_entries[i].group_description_index); /* group_description_index */
2500 av_free(sgpd_entries);
2504 static int mov_write_stbl_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
2506 int64_t pos = avio_tell(pb);
2509 avio_wb32(pb, 0); /* size */
2510 ffio_wfourcc(pb, "stbl");
2511 if ((ret = mov_write_stsd_tag(s, pb, mov, track)) < 0)
2513 mov_write_stts_tag(pb, track);
2514 if ((track->par->codec_type == AVMEDIA_TYPE_VIDEO ||
2515 track->par->codec_id == AV_CODEC_ID_TRUEHD ||
2516 track->par->codec_id == AV_CODEC_ID_MPEGH_3D_AUDIO ||
2517 track->par->codec_tag == MKTAG('r','t','p',' ')) &&
2518 track->has_keyframes && track->has_keyframes < track->entry)
2519 mov_write_stss_tag(pb, track, MOV_SYNC_SAMPLE);
2520 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO && track->has_disposable)
2521 mov_write_sdtp_tag(pb, track);
2522 if (track->mode == MODE_MOV && track->flags & MOV_TRACK_STPS)
2523 mov_write_stss_tag(pb, track, MOV_PARTIAL_SYNC_SAMPLE);
2524 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO &&
2525 track->flags & MOV_TRACK_CTTS && track->entry) {
2527 if ((ret = mov_write_ctts_tag(s, pb, track)) < 0)
2530 mov_write_stsc_tag(pb, track);
2531 mov_write_stsz_tag(pb, track);
2532 mov_write_stco_tag(pb, track);
2533 if (track->cenc.aes_ctr) {
2534 ff_mov_cenc_write_stbl_atoms(&track->cenc, pb);
2536 if (track->par->codec_id == AV_CODEC_ID_OPUS || track->par->codec_id == AV_CODEC_ID_AAC) {
2537 mov_preroll_write_stbl_atoms(pb, track);
2539 return update_size(pb, pos);
2542 static int mov_write_dinf_tag(AVIOContext *pb)
2544 int64_t pos = avio_tell(pb);
2545 avio_wb32(pb, 0); /* size */
2546 ffio_wfourcc(pb, "dinf");
2547 mov_write_dref_tag(pb);
2548 return update_size(pb, pos);
2551 static int mov_write_nmhd_tag(AVIOContext *pb)
2554 ffio_wfourcc(pb, "nmhd");
2559 static int mov_write_tcmi_tag(AVIOContext *pb, MOVTrack *track)
2561 int64_t pos = avio_tell(pb);
2562 const char *font = "Lucida Grande";
2563 avio_wb32(pb, 0); /* size */
2564 ffio_wfourcc(pb, "tcmi"); /* timecode media information atom */
2565 avio_wb32(pb, 0); /* version & flags */
2566 avio_wb16(pb, 0); /* text font */
2567 avio_wb16(pb, 0); /* text face */
2568 avio_wb16(pb, 12); /* text size */
2569 avio_wb16(pb, 0); /* (unknown, not in the QT specs...) */
2570 avio_wb16(pb, 0x0000); /* text color (red) */
2571 avio_wb16(pb, 0x0000); /* text color (green) */
2572 avio_wb16(pb, 0x0000); /* text color (blue) */
2573 avio_wb16(pb, 0xffff); /* background color (red) */
2574 avio_wb16(pb, 0xffff); /* background color (green) */
2575 avio_wb16(pb, 0xffff); /* background color (blue) */
2576 avio_w8(pb, strlen(font)); /* font len (part of the pascal string) */
2577 avio_write(pb, font, strlen(font)); /* font name */
2578 return update_size(pb, pos);
2581 static int mov_write_gmhd_tag(AVIOContext *pb, MOVTrack *track)
2583 int64_t pos = avio_tell(pb);
2584 avio_wb32(pb, 0); /* size */
2585 ffio_wfourcc(pb, "gmhd");
2586 avio_wb32(pb, 0x18); /* gmin size */
2587 ffio_wfourcc(pb, "gmin");/* generic media info */
2588 avio_wb32(pb, 0); /* version & flags */
2589 avio_wb16(pb, 0x40); /* graphics mode = */
2590 avio_wb16(pb, 0x8000); /* opColor (r?) */
2591 avio_wb16(pb, 0x8000); /* opColor (g?) */
2592 avio_wb16(pb, 0x8000); /* opColor (b?) */
2593 avio_wb16(pb, 0); /* balance */
2594 avio_wb16(pb, 0); /* reserved */
2597 * This special text atom is required for
2598 * Apple Quicktime chapters. The contents
2599 * don't appear to be documented, so the
2600 * bytes are copied verbatim.
2602 if (track->tag != MKTAG('c','6','0','8')) {
2603 avio_wb32(pb, 0x2C); /* size */
2604 ffio_wfourcc(pb, "text");
2605 avio_wb16(pb, 0x01);
2606 avio_wb32(pb, 0x00);
2607 avio_wb32(pb, 0x00);
2608 avio_wb32(pb, 0x00);
2609 avio_wb32(pb, 0x01);
2610 avio_wb32(pb, 0x00);
2611 avio_wb32(pb, 0x00);
2612 avio_wb32(pb, 0x00);
2613 avio_wb32(pb, 0x00004000);
2614 avio_wb16(pb, 0x0000);
2617 if (track->par->codec_tag == MKTAG('t','m','c','d')) {
2618 int64_t tmcd_pos = avio_tell(pb);
2619 avio_wb32(pb, 0); /* size */
2620 ffio_wfourcc(pb, "tmcd");
2621 mov_write_tcmi_tag(pb, track);
2622 update_size(pb, tmcd_pos);
2623 } else if (track->par->codec_tag == MKTAG('g','p','m','d')) {
2624 int64_t gpmd_pos = avio_tell(pb);
2625 avio_wb32(pb, 0); /* size */
2626 ffio_wfourcc(pb, "gpmd");
2627 avio_wb32(pb, 0); /* version */
2628 update_size(pb, gpmd_pos);
2630 return update_size(pb, pos);
2633 static int mov_write_smhd_tag(AVIOContext *pb)
2635 avio_wb32(pb, 16); /* size */
2636 ffio_wfourcc(pb, "smhd");
2637 avio_wb32(pb, 0); /* version & flags */
2638 avio_wb16(pb, 0); /* reserved (balance, normally = 0) */
2639 avio_wb16(pb, 0); /* reserved */
2643 static int mov_write_vmhd_tag(AVIOContext *pb)
2645 avio_wb32(pb, 0x14); /* size (always 0x14) */
2646 ffio_wfourcc(pb, "vmhd");
2647 avio_wb32(pb, 0x01); /* version & flags */
2648 avio_wb64(pb, 0); /* reserved (graphics mode = copy) */
2652 static int is_clcp_track(MOVTrack *track)
2654 return track->tag == MKTAG('c','7','0','8') ||
2655 track->tag == MKTAG('c','6','0','8');
2658 static int mov_write_hdlr_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
2660 MOVMuxContext *mov = s->priv_data;
2661 const char *hdlr, *descr = NULL, *hdlr_type = NULL;
2662 int64_t pos = avio_tell(pb);
2666 descr = "DataHandler";
2669 hdlr = (track->mode == MODE_MOV) ? "mhlr" : "\0\0\0\0";
2670 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
2672 descr = "VideoHandler";
2673 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
2675 descr = "SoundHandler";
2676 } else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE) {
2677 if (is_clcp_track(track)) {
2679 descr = "ClosedCaptionHandler";
2681 if (track->tag == MKTAG('t','x','3','g')) {
2683 } else if (track->tag == MKTAG('m','p','4','s')) {
2688 descr = "SubtitleHandler";
2690 } else if (track->par->codec_tag == MKTAG('r','t','p',' ')) {
2692 descr = "HintHandler";
2693 } else if (track->par->codec_tag == MKTAG('t','m','c','d')) {
2695 descr = "TimeCodeHandler";
2696 } else if (track->par->codec_tag == MKTAG('g','p','m','d')) {
2698 descr = "GoPro MET"; // GoPro Metadata
2700 av_log(s, AV_LOG_WARNING,
2701 "Unknown hldr_type for %s, writing dummy values\n",
2702 av_fourcc2str(track->par->codec_tag));
2705 // hdlr.name is used by some players to identify the content title
2706 // of the track. So if an alternate handler description is
2707 // specified, use it.
2708 AVDictionaryEntry *t;
2709 t = av_dict_get(track->st->metadata, "handler_name", NULL, 0);
2710 if (t && utf8len(t->value))
2715 if (mov->empty_hdlr_name) /* expressly allowed by QTFF and not prohibited in ISO 14496-12 8.4.3.3 */
2718 avio_wb32(pb, 0); /* size */
2719 ffio_wfourcc(pb, "hdlr");
2720 avio_wb32(pb, 0); /* Version & flags */
2721 avio_write(pb, hdlr, 4); /* handler */
2722 ffio_wfourcc(pb, hdlr_type); /* handler type */
2723 avio_wb32(pb, 0); /* reserved */
2724 avio_wb32(pb, 0); /* reserved */
2725 avio_wb32(pb, 0); /* reserved */
2726 if (!track || track->mode == MODE_MOV)
2727 avio_w8(pb, strlen(descr)); /* pascal string */
2728 avio_write(pb, descr, strlen(descr)); /* handler description */
2729 if (track && track->mode != MODE_MOV)
2730 avio_w8(pb, 0); /* c string */
2731 return update_size(pb, pos);
2734 static int mov_write_hmhd_tag(AVIOContext *pb)
2736 /* This atom must be present, but leaving the values at zero
2737 * seems harmless. */
2738 avio_wb32(pb, 28); /* size */
2739 ffio_wfourcc(pb, "hmhd");
2740 avio_wb32(pb, 0); /* version, flags */
2741 avio_wb16(pb, 0); /* maxPDUsize */
2742 avio_wb16(pb, 0); /* avgPDUsize */
2743 avio_wb32(pb, 0); /* maxbitrate */
2744 avio_wb32(pb, 0); /* avgbitrate */
2745 avio_wb32(pb, 0); /* reserved */
2749 static int mov_write_minf_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
2751 int64_t pos = avio_tell(pb);
2754 avio_wb32(pb, 0); /* size */
2755 ffio_wfourcc(pb, "minf");
2756 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO)
2757 mov_write_vmhd_tag(pb);
2758 else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
2759 mov_write_smhd_tag(pb);
2760 else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE) {
2761 if (track->tag == MKTAG('t','e','x','t') || is_clcp_track(track)) {
2762 mov_write_gmhd_tag(pb, track);
2764 mov_write_nmhd_tag(pb);
2766 } else if (track->tag == MKTAG('r','t','p',' ')) {
2767 mov_write_hmhd_tag(pb);
2768 } else if (track->tag == MKTAG('t','m','c','d')) {
2769 if (track->mode != MODE_MOV)
2770 mov_write_nmhd_tag(pb);
2772 mov_write_gmhd_tag(pb, track);
2773 } else if (track->tag == MKTAG('g','p','m','d')) {
2774 mov_write_gmhd_tag(pb, track);
2776 if (track->mode == MODE_MOV) /* ISO 14496-12 8.4.3.1 specifies hdlr only within mdia or meta boxes */
2777 mov_write_hdlr_tag(s, pb, NULL);
2778 mov_write_dinf_tag(pb);
2779 if ((ret = mov_write_stbl_tag(s, pb, mov, track)) < 0)
2781 return update_size(pb, pos);
2784 static int64_t calc_pts_duration(MOVMuxContext *mov, MOVTrack *track)
2786 if (track->tag == MKTAG('t','m','c','d')) {
2787 // tmcd tracks gets track_duration set in mov_write_moov_tag from
2788 // another track's duration, while the end_pts may be left at zero.
2789 // Calculate the pts duration for that track instead.
2790 return av_rescale(calc_pts_duration(mov, &mov->tracks[track->src_track]),
2791 track->timescale, mov->tracks[track->src_track].timescale);
2793 if (track->end_pts != AV_NOPTS_VALUE &&
2794 track->start_dts != AV_NOPTS_VALUE &&
2795 track->start_cts != AV_NOPTS_VALUE) {
2796 return track->end_pts - (track->start_dts + track->start_cts);
2798 return track->track_duration;
2801 static int mov_write_mdhd_tag(AVIOContext *pb, MOVMuxContext *mov,
2804 int64_t duration = calc_pts_duration(mov, track);
2805 int version = duration < INT32_MAX ? 0 : 1;
2807 if (track->mode == MODE_ISM)
2810 (version == 1) ? avio_wb32(pb, 44) : avio_wb32(pb, 32); /* size */
2811 ffio_wfourcc(pb, "mdhd");
2812 avio_w8(pb, version);
2813 avio_wb24(pb, 0); /* flags */
2815 avio_wb64(pb, track->time);
2816 avio_wb64(pb, track->time);
2818 avio_wb32(pb, track->time); /* creation time */
2819 avio_wb32(pb, track->time); /* modification time */
2821 avio_wb32(pb, track->timescale); /* time scale (sample rate for audio) */
2822 if (!track->entry && mov->mode == MODE_ISM)
2823 (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
2824 else if (!track->entry)
2825 (version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0);
2827 (version == 1) ? avio_wb64(pb, duration) : avio_wb32(pb, duration); /* duration */
2828 avio_wb16(pb, track->language); /* language */
2829 avio_wb16(pb, 0); /* reserved (quality) */
2831 if (version != 0 && track->mode == MODE_MOV) {
2832 av_log(NULL, AV_LOG_ERROR,
2833 "FATAL error, file duration too long for timebase, this file will not be\n"
2834 "playable with QuickTime. Choose a different timebase with "
2835 "-video_track_timescale or a different container format\n");
2841 static int mov_write_mdia_tag(AVFormatContext *s, AVIOContext *pb,
2842 MOVMuxContext *mov, MOVTrack *track)
2844 int64_t pos = avio_tell(pb);
2847 avio_wb32(pb, 0); /* size */
2848 ffio_wfourcc(pb, "mdia");
2849 mov_write_mdhd_tag(pb, mov, track);
2850 mov_write_hdlr_tag(s, pb, track);
2851 if ((ret = mov_write_minf_tag(s, pb, mov, track)) < 0)
2853 return update_size(pb, pos);
2856 /* transformation matrix
2860 static void write_matrix(AVIOContext *pb, int16_t a, int16_t b, int16_t c,
2861 int16_t d, int16_t tx, int16_t ty)
2863 avio_wb32(pb, a << 16); /* 16.16 format */
2864 avio_wb32(pb, b << 16); /* 16.16 format */
2865 avio_wb32(pb, 0); /* u in 2.30 format */
2866 avio_wb32(pb, c << 16); /* 16.16 format */
2867 avio_wb32(pb, d << 16); /* 16.16 format */
2868 avio_wb32(pb, 0); /* v in 2.30 format */
2869 avio_wb32(pb, tx << 16); /* 16.16 format */
2870 avio_wb32(pb, ty << 16); /* 16.16 format */
2871 avio_wb32(pb, 1 << 30); /* w in 2.30 format */
2874 static int mov_write_tkhd_tag(AVIOContext *pb, MOVMuxContext *mov,
2875 MOVTrack *track, AVStream *st)
2877 int64_t duration = av_rescale_rnd(calc_pts_duration(mov, track),
2878 MOV_TIMESCALE, track->timescale,
2880 int version = duration < INT32_MAX ? 0 : 1;
2881 int flags = MOV_TKHD_FLAG_IN_MOVIE;
2885 uint32_t *display_matrix = NULL;
2886 int display_matrix_size, i;
2889 if (mov->per_stream_grouping)
2892 group = st->codecpar->codec_type;
2894 display_matrix = (uint32_t*)av_stream_get_side_data(st, AV_PKT_DATA_DISPLAYMATRIX,
2895 &display_matrix_size);
2896 if (display_matrix && display_matrix_size < 9 * sizeof(*display_matrix))
2897 display_matrix = NULL;
2900 if (track->flags & MOV_TRACK_ENABLED)
2901 flags |= MOV_TKHD_FLAG_ENABLED;
2903 if (track->mode == MODE_ISM)
2906 (version == 1) ? avio_wb32(pb, 104) : avio_wb32(pb, 92); /* size */
2907 ffio_wfourcc(pb, "tkhd");
2908 avio_w8(pb, version);
2909 avio_wb24(pb, flags);
2911 avio_wb64(pb, track->time);
2912 avio_wb64(pb, track->time);
2914 avio_wb32(pb, track->time); /* creation time */
2915 avio_wb32(pb, track->time); /* modification time */
2917 avio_wb32(pb, track->track_id); /* track-id */
2918 avio_wb32(pb, 0); /* reserved */
2919 if (!track->entry && mov->mode == MODE_ISM)
2920 (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
2921 else if (!track->entry)
2922 (version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0);
2924 (version == 1) ? avio_wb64(pb, duration) : avio_wb32(pb, duration);
2926 avio_wb32(pb, 0); /* reserved */
2927 avio_wb32(pb, 0); /* reserved */
2928 avio_wb16(pb, 0); /* layer */
2929 avio_wb16(pb, group); /* alternate group) */
2930 /* Volume, only for audio */
2931 if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
2932 avio_wb16(pb, 0x0100);
2935 avio_wb16(pb, 0); /* reserved */
2937 /* Matrix structure */
2938 #if FF_API_OLD_ROTATE_API
2939 if (st && st->metadata) {
2940 AVDictionaryEntry *rot = av_dict_get(st->metadata, "rotate", NULL, 0);
2941 rotation = (rot && rot->value) ? atoi(rot->value) : 0;
2944 if (display_matrix) {
2945 for (i = 0; i < 9; i++)
2946 avio_wb32(pb, display_matrix[i]);
2947 #if FF_API_OLD_ROTATE_API
2948 } else if (rotation == 90) {
2949 write_matrix(pb, 0, 1, -1, 0, track->par->height, 0);
2950 } else if (rotation == 180) {
2951 write_matrix(pb, -1, 0, 0, -1, track->par->width, track->par->height);
2952 } else if (rotation == 270) {
2953 write_matrix(pb, 0, -1, 1, 0, 0, track->par->width);
2956 write_matrix(pb, 1, 0, 0, 1, 0, 0);
2958 /* Track width and height, for visual only */
2959 if (st && (track->par->codec_type == AVMEDIA_TYPE_VIDEO ||
2960 track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)) {
2961 int64_t track_width_1616;
2962 if (track->mode == MODE_MOV) {
2963 track_width_1616 = track->par->width * 0x10000ULL;
2965 track_width_1616 = av_rescale(st->sample_aspect_ratio.num,
2966 track->par->width * 0x10000LL,
2967 st->sample_aspect_ratio.den);
2968 if (!track_width_1616 ||
2969 track->height != track->par->height ||
2970 track_width_1616 > UINT32_MAX)
2971 track_width_1616 = track->par->width * 0x10000ULL;
2973 if (track_width_1616 > UINT32_MAX) {
2974 av_log(mov->fc, AV_LOG_WARNING, "track width is too large\n");
2975 track_width_1616 = 0;
2977 avio_wb32(pb, track_width_1616);
2978 if (track->height > 0xFFFF) {
2979 av_log(mov->fc, AV_LOG_WARNING, "track height is too large\n");
2982 avio_wb32(pb, track->height * 0x10000U);
2990 static int mov_write_tapt_tag(AVIOContext *pb, MOVTrack *track)
2992 int32_t width = av_rescale(track->par->sample_aspect_ratio.num, track->par->width,
2993 track->par->sample_aspect_ratio.den);
2995 int64_t pos = avio_tell(pb);
2997 avio_wb32(pb, 0); /* size */
2998 ffio_wfourcc(pb, "tapt");
3001 ffio_wfourcc(pb, "clef");
3003 avio_wb32(pb, width << 16);
3004 avio_wb32(pb, track->par->height << 16);
3007 ffio_wfourcc(pb, "prof");
3009 avio_wb32(pb, width << 16);
3010 avio_wb32(pb, track->par->height << 16);
3013 ffio_wfourcc(pb, "enof");
3015 avio_wb32(pb, track->par->width << 16);
3016 avio_wb32(pb, track->par->height << 16);
3018 return update_size(pb, pos);
3021 // This box seems important for the psp playback ... without it the movie seems to hang
3022 static int mov_write_edts_tag(AVIOContext *pb, MOVMuxContext *mov,
3025 int64_t duration = av_rescale_rnd(calc_pts_duration(mov, track),
3026 MOV_TIMESCALE, track->timescale,
3028 int version = duration < INT32_MAX ? 0 : 1;
3029 int entry_size, entry_count, size;
3030 int64_t delay, start_ct = track->start_cts;
3031 int64_t start_dts = track->start_dts;
3034 if (start_dts != track->cluster[0].dts || start_ct != track->cluster[0].cts) {
3036 av_log(mov->fc, AV_LOG_DEBUG,
3037 "EDTS using dts:%"PRId64" cts:%d instead of dts:%"PRId64" cts:%"PRId64" tid:%d\n",
3038 track->cluster[0].dts, track->cluster[0].cts,
3039 start_dts, start_ct, track->track_id);
3040 start_dts = track->cluster[0].dts;
3041 start_ct = track->cluster[0].cts;
3045 delay = av_rescale_rnd(start_dts + start_ct, MOV_TIMESCALE,
3046 track->timescale, AV_ROUND_DOWN);
3047 version |= delay < INT32_MAX ? 0 : 1;
3049 entry_size = (version == 1) ? 20 : 12;
3050 entry_count = 1 + (delay > 0);
3051 size = 24 + entry_count * entry_size;
3053 /* write the atom data */
3054 avio_wb32(pb, size);
3055 ffio_wfourcc(pb, "edts");
3056 avio_wb32(pb, size - 8);
3057 ffio_wfourcc(pb, "elst");
3058 avio_w8(pb, version);
3059 avio_wb24(pb, 0); /* flags */
3061 avio_wb32(pb, entry_count);
3062 if (delay > 0) { /* add an empty edit to delay presentation */
3063 /* In the positive delay case, the delay includes the cts
3064 * offset, and the second edit list entry below trims out
3065 * the same amount from the actual content. This makes sure
3066 * that the offset last sample is included in the edit
3067 * list duration as well. */
3069 avio_wb64(pb, delay);
3072 avio_wb32(pb, delay);
3075 avio_wb32(pb, 0x00010000);
3077 /* Avoid accidentally ending up with start_ct = -1 which has got a
3078 * special meaning. Normally start_ct should end up positive or zero
3079 * here, but use FFMIN in case dts is a small positive integer
3080 * rounded to 0 when represented in MOV_TIMESCALE units. */
3081 av_assert0(av_rescale_rnd(start_dts, MOV_TIMESCALE, track->timescale, AV_ROUND_DOWN) <= 0);
3082 start_ct = -FFMIN(start_dts, 0);
3083 /* Note, this delay is calculated from the pts of the first sample,
3084 * ensuring that we don't reduce the duration for cases with
3089 /* For fragmented files, we don't know the full length yet. Setting
3090 * duration to 0 allows us to only specify the offset, including
3091 * the rest of the content (from all future fragments) without specifying
3092 * an explicit duration. */
3093 if (mov->flags & FF_MOV_FLAG_FRAGMENT)
3098 avio_wb64(pb, duration);
3099 avio_wb64(pb, start_ct);
3101 avio_wb32(pb, duration);
3102 avio_wb32(pb, start_ct);
3104 avio_wb32(pb, 0x00010000);
3108 static int mov_write_tref_tag(AVIOContext *pb, MOVTrack *track)
3110 avio_wb32(pb, 20); // size
3111 ffio_wfourcc(pb, "tref");
3112 avio_wb32(pb, 12); // size (subatom)
3113 avio_wl32(pb, track->tref_tag);
3114 avio_wb32(pb, track->tref_id);
3118 // goes at the end of each track! ... Critical for PSP playback ("Incompatible data" without it)
3119 static int mov_write_uuid_tag_psp(AVIOContext *pb, MOVTrack *mov)
3121 avio_wb32(pb, 0x34); /* size ... reports as 28 in mp4box! */
3122 ffio_wfourcc(pb, "uuid");
3123 ffio_wfourcc(pb, "USMT");
3124 avio_wb32(pb, 0x21d24fce);
3125 avio_wb32(pb, 0xbb88695c);
3126 avio_wb32(pb, 0xfac9c740);
3127 avio_wb32(pb, 0x1c); // another size here!
3128 ffio_wfourcc(pb, "MTDT");
3129 avio_wb32(pb, 0x00010012);
3130 avio_wb32(pb, 0x0a);
3131 avio_wb32(pb, 0x55c40000);
3137 static int mov_write_udta_sdp(AVIOContext *pb, MOVTrack *track)
3139 AVFormatContext *ctx = track->rtp_ctx;
3140 char buf[1000] = "";
3143 ff_sdp_write_media(buf, sizeof(buf), ctx->streams[0], track->src_track,
3144 NULL, NULL, 0, 0, ctx);
3145 av_strlcatf(buf, sizeof(buf), "a=control:streamid=%d\r\n", track->track_id);
3148 avio_wb32(pb, len + 24);
3149 ffio_wfourcc(pb, "udta");
3150 avio_wb32(pb, len + 16);
3151 ffio_wfourcc(pb, "hnti");
3152 avio_wb32(pb, len + 8);
3153 ffio_wfourcc(pb, "sdp ");
3154 avio_write(pb, buf, len);
3158 static int mov_write_track_metadata(AVIOContext *pb, AVStream *st,
3159 const char *tag, const char *str)
3161 int64_t pos = avio_tell(pb);
3162 AVDictionaryEntry *t = av_dict_get(st->metadata, str, NULL, 0);
3163 if (!t || !utf8len(t->value))
3166 avio_wb32(pb, 0); /* size */
3167 ffio_wfourcc(pb, tag); /* type */
3168 avio_write(pb, t->value, strlen(t->value)); /* UTF8 string value */
3169 return update_size(pb, pos);
3172 static int mov_write_track_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
3175 AVIOContext *pb_buf;
3182 ret = avio_open_dyn_buf(&pb_buf);
3186 if (mov->mode & (MODE_MP4|MODE_MOV))
3187 mov_write_track_metadata(pb_buf, st, "name", "title");
3189 if ((size = avio_get_dyn_buf(pb_buf, &buf)) > 0) {
3190 avio_wb32(pb, size + 8);
3191 ffio_wfourcc(pb, "udta");
3192 avio_write(pb, buf, size);
3194 ffio_free_dyn_buf(&pb_buf);
3199 static int mov_write_trak_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov,
3200 MOVTrack *track, AVStream *st)
3202 int64_t pos = avio_tell(pb);
3203 int entry_backup = track->entry;
3204 int chunk_backup = track->chunkCount;
3207 /* If we want to have an empty moov, but some samples already have been
3208 * buffered (delay_moov), pretend that no samples have been written yet. */
3209 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV)
3210 track->chunkCount = track->entry = 0;
3212 avio_wb32(pb, 0); /* size */
3213 ffio_wfourcc(pb, "trak");
3214 mov_write_tkhd_tag(pb, mov, track, st);
3216 av_assert2(mov->use_editlist >= 0);
3218 if (track->start_dts != AV_NOPTS_VALUE) {
3219 if (mov->use_editlist)
3220 mov_write_edts_tag(pb, mov, track); // PSP Movies and several other cases require edts box
3221 else if ((track->entry && track->cluster[0].dts) || track->mode == MODE_PSP || is_clcp_track(track))
3222 av_log(mov->fc, AV_LOG_WARNING,
3223 "Not writing any edit list even though one would have been required\n");
3226 if (track->tref_tag)
3227 mov_write_tref_tag(pb, track);
3229 if ((ret = mov_write_mdia_tag(s, pb, mov, track)) < 0)
3231 if (track->mode == MODE_PSP)
3232 mov_write_uuid_tag_psp(pb, track); // PSP Movies require this uuid box
3233 if (track->tag == MKTAG('r','t','p',' '))
3234 mov_write_udta_sdp(pb, track);
3235 if (track->mode == MODE_MOV) {
3236 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
3237 double sample_aspect_ratio = av_q2d(st->sample_aspect_ratio);
3238 if (st->sample_aspect_ratio.num && 1.0 != sample_aspect_ratio) {
3239 mov_write_tapt_tag(pb, track);
3242 if (is_clcp_track(track) && st->sample_aspect_ratio.num) {
3243 mov_write_tapt_tag(pb, track);
3246 mov_write_track_udta_tag(pb, mov, st);
3247 track->entry = entry_backup;
3248 track->chunkCount = chunk_backup;
3249 return update_size(pb, pos);
3252 static int mov_write_iods_tag(AVIOContext *pb, MOVMuxContext *mov)
3254 int i, has_audio = 0, has_video = 0;
3255 int64_t pos = avio_tell(pb);
3256 int audio_profile = mov->iods_audio_profile;
3257 int video_profile = mov->iods_video_profile;
3258 for (i = 0; i < mov->nb_streams; i++) {
3259 if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
3260 has_audio |= mov->tracks[i].par->codec_type == AVMEDIA_TYPE_AUDIO;
3261 has_video |= mov->tracks[i].par->codec_type == AVMEDIA_TYPE_VIDEO;
3264 if (audio_profile < 0)
3265 audio_profile = 0xFF - has_audio;
3266 if (video_profile < 0)
3267 video_profile = 0xFF - has_video;
3268 avio_wb32(pb, 0x0); /* size */
3269 ffio_wfourcc(pb, "iods");
3270 avio_wb32(pb, 0); /* version & flags */
3271 put_descr(pb, 0x10, 7);
3272 avio_wb16(pb, 0x004f);
3275 avio_w8(pb, audio_profile);
3276 avio_w8(pb, video_profile);
3278 return update_size(pb, pos);
3281 static int mov_write_trex_tag(AVIOContext *pb, MOVTrack *track)
3283 avio_wb32(pb, 0x20); /* size */
3284 ffio_wfourcc(pb, "trex");
3285 avio_wb32(pb, 0); /* version & flags */
3286 avio_wb32(pb, track->track_id); /* track ID */
3287 avio_wb32(pb, 1); /* default sample description index */
3288 avio_wb32(pb, 0); /* default sample duration */
3289 avio_wb32(pb, 0); /* default sample size */
3290 avio_wb32(pb, 0); /* default sample flags */
3294 static int mov_write_mvex_tag(AVIOContext *pb, MOVMuxContext *mov)
3296 int64_t pos = avio_tell(pb);
3298 avio_wb32(pb, 0x0); /* size */
3299 ffio_wfourcc(pb, "mvex");
3300 for (i = 0; i < mov->nb_streams; i++)
3301 mov_write_trex_tag(pb, &mov->tracks[i]);
3302 return update_size(pb, pos);
3305 static int mov_write_mvhd_tag(AVIOContext *pb, MOVMuxContext *mov)
3307 int max_track_id = 1, i;
3308 int64_t max_track_len = 0;
3311 for (i = 0; i < mov->nb_streams; i++) {
3312 if (mov->tracks[i].entry > 0 && mov->tracks[i].timescale) {
3313 int64_t max_track_len_temp = av_rescale_rnd(
3314 calc_pts_duration(mov, &mov->tracks[i]),
3316 mov->tracks[i].timescale,
3318 if (max_track_len < max_track_len_temp)
3319 max_track_len = max_track_len_temp;
3320 if (max_track_id < mov->tracks[i].track_id)
3321 max_track_id = mov->tracks[i].track_id;
3324 /* If using delay_moov, make sure the output is the same as if no
3325 * samples had been written yet. */
3326 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
3331 version = max_track_len < UINT32_MAX ? 0 : 1;
3332 avio_wb32(pb, version == 1 ? 120 : 108); /* size */
3334 ffio_wfourcc(pb, "mvhd");
3335 avio_w8(pb, version);
3336 avio_wb24(pb, 0); /* flags */
3338 avio_wb64(pb, mov->time);
3339 avio_wb64(pb, mov->time);
3341 avio_wb32(pb, mov->time); /* creation time */
3342 avio_wb32(pb, mov->time); /* modification time */
3344 avio_wb32(pb, MOV_TIMESCALE);
3345 (version == 1) ? avio_wb64(pb, max_track_len) : avio_wb32(pb, max_track_len); /* duration of longest track */
3347 avio_wb32(pb, 0x00010000); /* reserved (preferred rate) 1.0 = normal */
3348 avio_wb16(pb, 0x0100); /* reserved (preferred volume) 1.0 = normal */
3349 avio_wb16(pb, 0); /* reserved */
3350 avio_wb32(pb, 0); /* reserved */
3351 avio_wb32(pb, 0); /* reserved */
3353 /* Matrix structure */
3354 write_matrix(pb, 1, 0, 0, 1, 0, 0);
3356 avio_wb32(pb, 0); /* reserved (preview time) */
3357 avio_wb32(pb, 0); /* reserved (preview duration) */
3358 avio_wb32(pb, 0); /* reserved (poster time) */
3359 avio_wb32(pb, 0); /* reserved (selection time) */
3360 avio_wb32(pb, 0); /* reserved (selection duration) */
3361 avio_wb32(pb, 0); /* reserved (current time) */
3362 avio_wb32(pb, max_track_id + 1); /* Next track id */
3366 static int mov_write_itunes_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov,
3369 avio_wb32(pb, 33); /* size */
3370 ffio_wfourcc(pb, "hdlr");
3373 ffio_wfourcc(pb, "mdir");
3374 ffio_wfourcc(pb, "appl");
3381 /* helper function to write a data tag with the specified string as data */
3382 static int mov_write_string_data_tag(AVIOContext *pb, const char *data, int lang, int long_style)
3385 int size = 16 + strlen(data);
3386 avio_wb32(pb, size); /* size */
3387 ffio_wfourcc(pb, "data");
3390 avio_write(pb, data, strlen(data));
3394 lang = ff_mov_iso639_to_lang("und", 1);
3395 avio_wb16(pb, strlen(data)); /* string length */
3396 avio_wb16(pb, lang);
3397 avio_write(pb, data, strlen(data));
3398 return strlen(data) + 4;
3402 static int mov_write_string_tag(AVIOContext *pb, const char *name,
3403 const char *value, int lang, int long_style)
3406 if (value && value[0]) {
3407 int64_t pos = avio_tell(pb);
3408 avio_wb32(pb, 0); /* size */
3409 ffio_wfourcc(pb, name);
3410 mov_write_string_data_tag(pb, value, lang, long_style);
3411 size = update_size(pb, pos);
3416 static AVDictionaryEntry *get_metadata_lang(AVFormatContext *s,
3417 const char *tag, int *lang)
3420 AVDictionaryEntry *t, *t2 = NULL;
3425 if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
3428 len = strlen(t->key);
3429 snprintf(tag2, sizeof(tag2), "%s-", tag);
3430 while ((t2 = av_dict_get(s->metadata, tag2, t2, AV_DICT_IGNORE_SUFFIX))) {
3431 len2 = strlen(t2->key);
3432 if (len2 == len + 4 && !strcmp(t->value, t2->value)
3433 && (l = ff_mov_iso639_to_lang(&t2->key[len2 - 3], 1)) >= 0) {
3441 static int mov_write_string_metadata(AVFormatContext *s, AVIOContext *pb,
3442 const char *name, const char *tag,
3446 AVDictionaryEntry *t = get_metadata_lang(s, tag, &lang);
3449 return mov_write_string_tag(pb, name, t->value, lang, long_style);
3452 /* iTunes bpm number */
3453 static int mov_write_tmpo_tag(AVIOContext *pb, AVFormatContext *s)
3455 AVDictionaryEntry *t = av_dict_get(s->metadata, "tmpo", NULL, 0);
3456 int size = 0, tmpo = t ? atoi(t->value) : 0;
3459 avio_wb32(pb, size);
3460 ffio_wfourcc(pb, "tmpo");
3461 avio_wb32(pb, size-8); /* size */
3462 ffio_wfourcc(pb, "data");
3463 avio_wb32(pb, 0x15); //type specifier
3465 avio_wb16(pb, tmpo); // data
3470 /* 3GPP TS 26.244 */
3471 static int mov_write_loci_tag(AVFormatContext *s, AVIOContext *pb)
3474 int64_t pos = avio_tell(pb);
3475 double latitude, longitude, altitude;
3476 int32_t latitude_fix, longitude_fix, altitude_fix;
3477 AVDictionaryEntry *t = get_metadata_lang(s, "location", &lang);
3478 const char *ptr, *place = "";
3480 static const char *astronomical_body = "earth";
3485 longitude = strtod(ptr, &end);
3487 av_log(s, AV_LOG_WARNING, "malformed location metadata\n");
3491 latitude = strtod(ptr, &end);
3493 av_log(s, AV_LOG_WARNING, "malformed location metadata\n");
3497 altitude = strtod(ptr, &end);
3498 /* If no altitude was present, the default 0 should be fine */
3502 latitude_fix = (int32_t) ((1 << 16) * latitude);
3503 longitude_fix = (int32_t) ((1 << 16) * longitude);
3504 altitude_fix = (int32_t) ((1 << 16) * altitude);
3506 avio_wb32(pb, 0); /* size */
3507 ffio_wfourcc(pb, "loci"); /* type */
3508 avio_wb32(pb, 0); /* version + flags */
3509 avio_wb16(pb, lang);
3510 avio_write(pb, place, strlen(place) + 1);
3511 avio_w8(pb, 0); /* role of place (0 == shooting location, 1 == real location, 2 == fictional location) */
3512 avio_wb32(pb, latitude_fix);
3513 avio_wb32(pb, longitude_fix);
3514 avio_wb32(pb, altitude_fix);
3515 avio_write(pb, astronomical_body, strlen(astronomical_body) + 1);
3516 avio_w8(pb, 0); /* additional notes, null terminated string */
3518 return update_size(pb, pos);
3521 /* iTunes track or disc number */
3522 static int mov_write_trkn_tag(AVIOContext *pb, MOVMuxContext *mov,
3523 AVFormatContext *s, int disc)
3525 AVDictionaryEntry *t = av_dict_get(s->metadata,
3526 disc ? "disc" : "track",
3528 int size = 0, track = t ? atoi(t->value) : 0;
3531 char *slash = strchr(t->value, '/');
3533 tracks = atoi(slash + 1);
3534 avio_wb32(pb, 32); /* size */
3535 ffio_wfourcc(pb, disc ? "disk" : "trkn");
3536 avio_wb32(pb, 24); /* size */
3537 ffio_wfourcc(pb, "data");
3538 avio_wb32(pb, 0); // 8 bytes empty
3540 avio_wb16(pb, 0); // empty
3541 avio_wb16(pb, track); // track / disc number
3542 avio_wb16(pb, tracks); // total track / disc number
3543 avio_wb16(pb, 0); // empty
3549 static int mov_write_int8_metadata(AVFormatContext *s, AVIOContext *pb,
3550 const char *name, const char *tag,
3553 AVDictionaryEntry *t = NULL;
3555 int size = 24 + len;
3557 if (len != 1 && len != 4)
3560 if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
3562 num = atoi(t->value);
3564 avio_wb32(pb, size);
3565 ffio_wfourcc(pb, name);
3566 avio_wb32(pb, size - 8);
3567 ffio_wfourcc(pb, "data");
3568 avio_wb32(pb, 0x15);
3570 if (len==4) avio_wb32(pb, num);
3571 else avio_w8 (pb, num);
3576 static int mov_write_covr(AVIOContext *pb, AVFormatContext *s)
3578 MOVMuxContext *mov = s->priv_data;
3582 for (i = 0; i < s->nb_streams; i++) {
3583 MOVTrack *trk = &mov->tracks[i];
3585 if (!is_cover_image(trk->st) || trk->cover_image.size <= 0)
3589 pos = avio_tell(pb);
3591 ffio_wfourcc(pb, "covr");
3593 avio_wb32(pb, 16 + trk->cover_image.size);
3594 ffio_wfourcc(pb, "data");
3595 avio_wb32(pb, trk->tag);
3597 avio_write(pb, trk->cover_image.data, trk->cover_image.size);
3600 return pos ? update_size(pb, pos) : 0;
3603 /* iTunes meta data list */
3604 static int mov_write_ilst_tag(AVIOContext *pb, MOVMuxContext *mov,
3607 int64_t pos = avio_tell(pb);
3608 avio_wb32(pb, 0); /* size */
3609 ffio_wfourcc(pb, "ilst");
3610 mov_write_string_metadata(s, pb, "\251nam", "title" , 1);
3611 mov_write_string_metadata(s, pb, "\251ART", "artist" , 1);
3612 mov_write_string_metadata(s, pb, "aART", "album_artist", 1);
3613 mov_write_string_metadata(s, pb, "\251wrt", "composer" , 1);
3614 mov_write_string_metadata(s, pb, "\251alb", "album" , 1);
3615 mov_write_string_metadata(s, pb, "\251day", "date" , 1);
3616 if (!mov_write_string_metadata(s, pb, "\251too", "encoding_tool", 1)) {
3617 if (!(s->flags & AVFMT_FLAG_BITEXACT))
3618 mov_write_string_tag(pb, "\251too", LIBAVFORMAT_IDENT, 0, 1);
3620 mov_write_string_metadata(s, pb, "\251cmt", "comment" , 1);
3621 mov_write_string_metadata(s, pb, "\251gen", "genre" , 1);
3622 mov_write_string_metadata(s, pb, "cprt", "copyright", 1);
3623 mov_write_string_metadata(s, pb, "\251grp", "grouping" , 1);
3624 mov_write_string_metadata(s, pb, "\251lyr", "lyrics" , 1);
3625 mov_write_string_metadata(s, pb, "desc", "description",1);
3626 mov_write_string_metadata(s, pb, "ldes", "synopsis" , 1);
3627 mov_write_string_metadata(s, pb, "tvsh", "show" , 1);
3628 mov_write_string_metadata(s, pb, "tven", "episode_id",1);
3629 mov_write_string_metadata(s, pb, "tvnn", "network" , 1);
3630 mov_write_string_metadata(s, pb, "keyw", "keywords" , 1);
3631 mov_write_int8_metadata (s, pb, "tves", "episode_sort",4);
3632 mov_write_int8_metadata (s, pb, "tvsn", "season_number",4);
3633 mov_write_int8_metadata (s, pb, "stik", "media_type",1);
3634 mov_write_int8_metadata (s, pb, "hdvd", "hd_video", 1);
3635 mov_write_int8_metadata (s, pb, "pgap", "gapless_playback",1);
3636 mov_write_int8_metadata (s, pb, "cpil", "compilation", 1);
3637 mov_write_covr(pb, s);
3638 mov_write_trkn_tag(pb, mov, s, 0); // track number
3639 mov_write_trkn_tag(pb, mov, s, 1); // disc number
3640 mov_write_tmpo_tag(pb, s);
3641 return update_size(pb, pos);
3644 static int mov_write_mdta_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov,
3647 avio_wb32(pb, 33); /* size */
3648 ffio_wfourcc(pb, "hdlr");
3651 ffio_wfourcc(pb, "mdta");
3659 static int mov_write_mdta_keys_tag(AVIOContext *pb, MOVMuxContext *mov,
3662 AVDictionaryEntry *t = NULL;
3663 int64_t pos = avio_tell(pb);
3664 int64_t curpos, entry_pos;
3667 avio_wb32(pb, 0); /* size */
3668 ffio_wfourcc(pb, "keys");
3670 entry_pos = avio_tell(pb);
3671 avio_wb32(pb, 0); /* entry count */
3673 while (t = av_dict_get(s->metadata, "", t, AV_DICT_IGNORE_SUFFIX)) {
3674 avio_wb32(pb, strlen(t->key) + 8);
3675 ffio_wfourcc(pb, "mdta");
3676 avio_write(pb, t->key, strlen(t->key));
3679 curpos = avio_tell(pb);
3680 avio_seek(pb, entry_pos, SEEK_SET);
3681 avio_wb32(pb, count); // rewrite entry count
3682 avio_seek(pb, curpos, SEEK_SET);
3684 return update_size(pb, pos);
3687 static int mov_write_mdta_ilst_tag(AVIOContext *pb, MOVMuxContext *mov,
3690 AVDictionaryEntry *t = NULL;
3691 int64_t pos = avio_tell(pb);
3692 int count = 1; /* keys are 1-index based */
3694 avio_wb32(pb, 0); /* size */
3695 ffio_wfourcc(pb, "ilst");
3697 while (t = av_dict_get(s->metadata, "", t, AV_DICT_IGNORE_SUFFIX)) {
3698 int64_t entry_pos = avio_tell(pb);
3699 avio_wb32(pb, 0); /* size */
3700 avio_wb32(pb, count); /* key */
3701 mov_write_string_data_tag(pb, t->value, 0, 1);
3702 update_size(pb, entry_pos);
3705 return update_size(pb, pos);
3708 /* meta data tags */
3709 static int mov_write_meta_tag(AVIOContext *pb, MOVMuxContext *mov,
3713 int64_t pos = avio_tell(pb);
3714 avio_wb32(pb, 0); /* size */
3715 ffio_wfourcc(pb, "meta");
3717 if (mov->flags & FF_MOV_FLAG_USE_MDTA) {
3718 mov_write_mdta_hdlr_tag(pb, mov, s);
3719 mov_write_mdta_keys_tag(pb, mov, s);
3720 mov_write_mdta_ilst_tag(pb, mov, s);
3723 /* iTunes metadata tag */
3724 mov_write_itunes_hdlr_tag(pb, mov, s);
3725 mov_write_ilst_tag(pb, mov, s);
3727 size = update_size(pb, pos);
3731 static int mov_write_raw_metadata_tag(AVFormatContext *s, AVIOContext *pb,
3732 const char *name, const char *key)
3735 AVDictionaryEntry *t;
3737 if (!(t = av_dict_get(s->metadata, key, NULL, 0)))
3740 len = strlen(t->value);
3743 avio_wb32(pb, size);
3744 ffio_wfourcc(pb, name);
3745 avio_write(pb, t->value, len);
3751 static int ascii_to_wc(AVIOContext *pb, const uint8_t *b)
3755 GET_UTF8(val, *b++, return -1;)
3758 avio_wb16(pb, 0x00);
3762 static uint16_t language_code(const char *str)
3764 return (((str[0] - 0x60) & 0x1F) << 10) +
3765 (((str[1] - 0x60) & 0x1F) << 5) +
3766 (( str[2] - 0x60) & 0x1F);
3769 static int mov_write_3gp_udta_tag(AVIOContext *pb, AVFormatContext *s,
3770 const char *tag, const char *str)
3772 int64_t pos = avio_tell(pb);
3773 AVDictionaryEntry *t = av_dict_get(s->metadata, str, NULL, 0);
3774 if (!t || !utf8len(t->value))
3776 avio_wb32(pb, 0); /* size */
3777 ffio_wfourcc(pb, tag); /* type */
3778 avio_wb32(pb, 0); /* version + flags */
3779 if (!strcmp(tag, "yrrc"))
3780 avio_wb16(pb, atoi(t->value));
3782 avio_wb16(pb, language_code("eng")); /* language */
3783 avio_write(pb, t->value, strlen(t->value) + 1); /* UTF8 string value */
3784 if (!strcmp(tag, "albm") &&
3785 (t = av_dict_get(s->metadata, "track", NULL, 0)))
3786 avio_w8(pb, atoi(t->value));
3788 return update_size(pb, pos);
3791 static int mov_write_chpl_tag(AVIOContext *pb, AVFormatContext *s)
3793 int64_t pos = avio_tell(pb);
3794 int i, nb_chapters = FFMIN(s->nb_chapters, 255);
3796 avio_wb32(pb, 0); // size
3797 ffio_wfourcc(pb, "chpl");
3798 avio_wb32(pb, 0x01000000); // version + flags
3799 avio_wb32(pb, 0); // unknown
3800 avio_w8(pb, nb_chapters);
3802 for (i = 0; i < nb_chapters; i++) {
3803 AVChapter *c = s->chapters[i];
3804 AVDictionaryEntry *t;
3805 avio_wb64(pb, av_rescale_q(c->start, c->time_base, (AVRational){1,10000000}));
3807 if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
3808 int len = FFMIN(strlen(t->value), 255);
3810 avio_write(pb, t->value, len);
3814 return update_size(pb, pos);
3817 static int mov_write_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
3820 AVIOContext *pb_buf;
3824 ret = avio_open_dyn_buf(&pb_buf);
3828 if (mov->mode & MODE_3GP) {
3829 mov_write_3gp_udta_tag(pb_buf, s, "perf", "artist");
3830 mov_write_3gp_udta_tag(pb_buf, s, "titl", "title");
3831 mov_write_3gp_udta_tag(pb_buf, s, "auth", "author");
3832 mov_write_3gp_udta_tag(pb_buf, s, "gnre", "genre");
3833 mov_write_3gp_udta_tag(pb_buf, s, "dscp", "comment");
3834 mov_write_3gp_udta_tag(pb_buf, s, "albm", "album");
3835 mov_write_3gp_udta_tag(pb_buf, s, "cprt", "copyright");
3836 mov_write_3gp_udta_tag(pb_buf, s, "yrrc", "date");
3837 mov_write_loci_tag(s, pb_buf);
3838 } 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
3839 mov_write_string_metadata(s, pb_buf, "\251ART", "artist", 0);
3840 mov_write_string_metadata(s, pb_buf, "\251nam", "title", 0);
3841 mov_write_string_metadata(s, pb_buf, "\251aut", "author", 0);
3842 mov_write_string_metadata(s, pb_buf, "\251alb", "album", 0);
3843 mov_write_string_metadata(s, pb_buf, "\251day", "date", 0);
3844 mov_write_string_metadata(s, pb_buf, "\251swr", "encoder", 0);
3845 // currently ignored by mov.c
3846 mov_write_string_metadata(s, pb_buf, "\251des", "comment", 0);
3847 // add support for libquicktime, this atom is also actually read by mov.c
3848 mov_write_string_metadata(s, pb_buf, "\251cmt", "comment", 0);
3849 mov_write_string_metadata(s, pb_buf, "\251gen", "genre", 0);
3850 mov_write_string_metadata(s, pb_buf, "\251cpy", "copyright", 0);
3851 mov_write_string_metadata(s, pb_buf, "\251mak", "make", 0);
3852 mov_write_string_metadata(s, pb_buf, "\251mod", "model", 0);
3853 mov_write_string_metadata(s, pb_buf, "\251xyz", "location", 0);
3854 mov_write_string_metadata(s, pb_buf, "\251key", "keywords", 0);
3855 mov_write_raw_metadata_tag(s, pb_buf, "XMP_", "xmp");
3857 /* iTunes meta data */
3858 mov_write_meta_tag(pb_buf, mov, s);
3859 mov_write_loci_tag(s, pb_buf);
3862 if (s->nb_chapters && !(mov->flags & FF_MOV_FLAG_DISABLE_CHPL))
3863 mov_write_chpl_tag(pb_buf, s);
3865 if ((size = avio_get_dyn_buf(pb_buf, &buf)) > 0) {
3866 avio_wb32(pb, size + 8);
3867 ffio_wfourcc(pb, "udta");
3868 avio_write(pb, buf, size);
3870 ffio_free_dyn_buf(&pb_buf);
3875 static void mov_write_psp_udta_tag(AVIOContext *pb,
3876 const char *str, const char *lang, int type)
3878 int len = utf8len(str) + 1;
3881 avio_wb16(pb, len * 2 + 10); /* size */
3882 avio_wb32(pb, type); /* type */
3883 avio_wb16(pb, language_code(lang)); /* language */
3884 avio_wb16(pb, 0x01); /* ? */
3885 ascii_to_wc(pb, str);
3888 static int mov_write_uuidusmt_tag(AVIOContext *pb, AVFormatContext *s)
3890 AVDictionaryEntry *title = av_dict_get(s->metadata, "title", NULL, 0);
3894 pos = avio_tell(pb);
3895 avio_wb32(pb, 0); /* size placeholder*/
3896 ffio_wfourcc(pb, "uuid");
3897 ffio_wfourcc(pb, "USMT");
3898 avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
3899 avio_wb32(pb, 0xbb88695c);
3900 avio_wb32(pb, 0xfac9c740);
3902 pos2 = avio_tell(pb);
3903 avio_wb32(pb, 0); /* size placeholder*/
3904 ffio_wfourcc(pb, "MTDT");
3908 avio_wb16(pb, 0x0C); /* size */
3909 avio_wb32(pb, 0x0B); /* type */
3910 avio_wb16(pb, language_code("und")); /* language */
3911 avio_wb16(pb, 0x0); /* ? */
3912 avio_wb16(pb, 0x021C); /* data */
3914 if (!(s->flags & AVFMT_FLAG_BITEXACT))
3915 mov_write_psp_udta_tag(pb, LIBAVCODEC_IDENT, "eng", 0x04);
3916 mov_write_psp_udta_tag(pb, title->value, "eng", 0x01);
3917 mov_write_psp_udta_tag(pb, "2006/04/01 11:11:11", "und", 0x03);
3919 update_size(pb, pos2);
3920 return update_size(pb, pos);
3926 static void build_chunks(MOVTrack *trk)
3929 MOVIentry *chunk = &trk->cluster[0];
3930 uint64_t chunkSize = chunk->size;
3931 chunk->chunkNum = 1;
3932 if (trk->chunkCount)
3934 trk->chunkCount = 1;
3935 for (i = 1; i<trk->entry; i++){
3936 if (chunk->pos + chunkSize == trk->cluster[i].pos &&
3937 chunkSize + trk->cluster[i].size < (1<<20)){
3938 chunkSize += trk->cluster[i].size;
3939 chunk->samples_in_chunk += trk->cluster[i].entries;
3941 trk->cluster[i].chunkNum = chunk->chunkNum+1;
3942 chunk=&trk->cluster[i];
3943 chunkSize = chunk->size;
3950 * Assign track ids. If option "use_stream_ids_as_track_ids" is set,
3951 * the stream ids are used as track ids.
3953 * This assumes mov->tracks and s->streams are in the same order and
3954 * there are no gaps in either of them (so mov->tracks[n] refers to
3957 * As an exception, there can be more entries in
3958 * s->streams than in mov->tracks, in which case new track ids are
3959 * generated (starting after the largest found stream id).
3961 static int mov_setup_track_ids(MOVMuxContext *mov, AVFormatContext *s)
3965 if (mov->track_ids_ok)
3968 if (mov->use_stream_ids_as_track_ids) {
3969 int next_generated_track_id = 0;
3970 for (i = 0; i < s->nb_streams; i++) {
3971 if (s->streams[i]->id > next_generated_track_id)
3972 next_generated_track_id = s->streams[i]->id;
3975 for (i = 0; i < mov->nb_streams; i++) {
3976 if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
3979 mov->tracks[i].track_id = i >= s->nb_streams ? ++next_generated_track_id : s->streams[i]->id;
3982 for (i = 0; i < mov->nb_streams; i++) {
3983 if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
3986 mov->tracks[i].track_id = i + 1;
3990 mov->track_ids_ok = 1;
3995 static int mov_write_moov_tag(AVIOContext *pb, MOVMuxContext *mov,
3999 int64_t pos = avio_tell(pb);
4000 avio_wb32(pb, 0); /* size placeholder*/
4001 ffio_wfourcc(pb, "moov");
4003 mov_setup_track_ids(mov, s);
4005 for (i = 0; i < mov->nb_streams; i++) {
4006 if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
4009 mov->tracks[i].time = mov->time;
4011 if (mov->tracks[i].entry)
4012 build_chunks(&mov->tracks[i]);
4015 if (mov->chapter_track)
4016 for (i = 0; i < s->nb_streams; i++) {
4017 mov->tracks[i].tref_tag = MKTAG('c','h','a','p');
4018 mov->tracks[i].tref_id = mov->tracks[mov->chapter_track].track_id;
4020 for (i = 0; i < mov->nb_streams; i++) {
4021 MOVTrack *track = &mov->tracks[i];
4022 if (track->tag == MKTAG('r','t','p',' ')) {
4023 track->tref_tag = MKTAG('h','i','n','t');
4024 track->tref_id = mov->tracks[track->src_track].track_id;
4025 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
4026 int * fallback, size;
4027 fallback = (int*)av_stream_get_side_data(track->st,
4028 AV_PKT_DATA_FALLBACK_TRACK,
4030 if (fallback != NULL && size == sizeof(int)) {
4031 if (*fallback >= 0 && *fallback < mov->nb_streams) {
4032 track->tref_tag = MKTAG('f','a','l','l');
4033 track->tref_id = mov->tracks[*fallback].track_id;
4038 for (i = 0; i < mov->nb_streams; i++) {
4039 if (mov->tracks[i].tag == MKTAG('t','m','c','d')) {
4040 int src_trk = mov->tracks[i].src_track;
4041 mov->tracks[src_trk].tref_tag = mov->tracks[i].tag;
4042 mov->tracks[src_trk].tref_id = mov->tracks[i].track_id;
4043 //src_trk may have a different timescale than the tmcd track
4044 mov->tracks[i].track_duration = av_rescale(mov->tracks[src_trk].track_duration,
4045 mov->tracks[i].timescale,
4046 mov->tracks[src_trk].timescale);
4050 mov_write_mvhd_tag(pb, mov);
4051 if (mov->mode != MODE_MOV && !mov->iods_skip)
4052 mov_write_iods_tag(pb, mov);
4053 for (i = 0; i < mov->nb_streams; i++) {
4054 if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_FRAGMENT) {
4055 int ret = mov_write_trak_tag(s, pb, mov, &(mov->tracks[i]), i < s->nb_streams ? s->streams[i] : NULL);
4060 if (mov->flags & FF_MOV_FLAG_FRAGMENT)
4061 mov_write_mvex_tag(pb, mov); /* QuickTime requires trak to precede this */
4063 if (mov->mode == MODE_PSP)
4064 mov_write_uuidusmt_tag(pb, s);
4066 mov_write_udta_tag(pb, mov, s);
4068 return update_size(pb, pos);
4071 static void param_write_int(AVIOContext *pb, const char *name, int value)
4073 avio_printf(pb, "<param name=\"%s\" value=\"%d\" valuetype=\"data\"/>\n", name, value);
4076 static void param_write_string(AVIOContext *pb, const char *name, const char *value)
4078 avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, value);
4081 static void param_write_hex(AVIOContext *pb, const char *name, const uint8_t *value, int len)
4084 len = FFMIN(sizeof(buf) / 2 - 1, len);
4085 ff_data_to_hex(buf, value, len, 0);
4086 buf[2 * len] = '\0';
4087 avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, buf);
4090 static int mov_write_isml_manifest(AVIOContext *pb, MOVMuxContext *mov, AVFormatContext *s)
4092 int64_t pos = avio_tell(pb);
4094 int64_t manifest_bit_rate = 0;
4095 AVCPBProperties *props = NULL;
4097 static const uint8_t uuid[] = {
4098 0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd,
4099 0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66
4103 ffio_wfourcc(pb, "uuid");
4104 avio_write(pb, uuid, sizeof(uuid));
4107 avio_printf(pb, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
4108 avio_printf(pb, "<smil xmlns=\"http://www.w3.org/2001/SMIL20/Language\">\n");
4109 avio_printf(pb, "<head>\n");
4110 if (!(mov->fc->flags & AVFMT_FLAG_BITEXACT))
4111 avio_printf(pb, "<meta name=\"creator\" content=\"%s\" />\n",
4113 avio_printf(pb, "</head>\n");
4114 avio_printf(pb, "<body>\n");
4115 avio_printf(pb, "<switch>\n");
4117 mov_setup_track_ids(mov, s);
4119 for (i = 0; i < mov->nb_streams; i++) {
4120 MOVTrack *track = &mov->tracks[i];
4122 int track_id = track->track_id;
4123 char track_name_buf[32] = { 0 };
4125 AVStream *st = track->st;
4126 AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0);
4128 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO && !is_cover_image(st)) {
4130 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
4136 props = (AVCPBProperties*)av_stream_get_side_data(track->st, AV_PKT_DATA_CPB_PROPERTIES, NULL);
4138 if (track->par->bit_rate) {
4139 manifest_bit_rate = track->par->bit_rate;
4141 manifest_bit_rate = props->max_bitrate;
4144 avio_printf(pb, "<%s systemBitrate=\"%"PRId64"\">\n", type,
4146 param_write_int(pb, "systemBitrate", manifest_bit_rate);
4147 param_write_int(pb, "trackID", track_id);
4148 param_write_string(pb, "systemLanguage", lang ? lang->value : "und");
4150 /* Build track name piece by piece: */
4152 av_strlcat(track_name_buf, type, sizeof(track_name_buf));
4153 /* 2. track language, if available */
4155 av_strlcatf(track_name_buf, sizeof(track_name_buf),
4156 "_%s", lang->value);
4157 /* 3. special type suffix */
4158 /* "_cc" = closed captions, "_ad" = audio_description */
4159 if (st->disposition & AV_DISPOSITION_HEARING_IMPAIRED)
4160 av_strlcat(track_name_buf, "_cc", sizeof(track_name_buf));
4161 else if (st->disposition & AV_DISPOSITION_VISUAL_IMPAIRED)
4162 av_strlcat(track_name_buf, "_ad", sizeof(track_name_buf));
4164 param_write_string(pb, "trackName", track_name_buf);
4166 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
4167 if (track->par->codec_id == AV_CODEC_ID_H264) {
4169 int size = track->par->extradata_size;
4170 if (!ff_avc_write_annexb_extradata(track->par->extradata, &ptr,
4172 param_write_hex(pb, "CodecPrivateData",
4173 ptr ? ptr : track->par->extradata,
4177 param_write_string(pb, "FourCC", "H264");
4178 } else if (track->par->codec_id == AV_CODEC_ID_VC1) {
4179 param_write_string(pb, "FourCC", "WVC1");
4180 param_write_hex(pb, "CodecPrivateData", track->par->extradata,
4181 track->par->extradata_size);
4183 param_write_int(pb, "MaxWidth", track->par->width);
4184 param_write_int(pb, "MaxHeight", track->par->height);
4185 param_write_int(pb, "DisplayWidth", track->par->width);
4186 param_write_int(pb, "DisplayHeight", track->par->height);
4188 if (track->par->codec_id == AV_CODEC_ID_AAC) {
4189 switch (track->par->profile)
4191 case FF_PROFILE_AAC_HE_V2:
4192 param_write_string(pb, "FourCC", "AACP");
4194 case FF_PROFILE_AAC_HE:
4195 param_write_string(pb, "FourCC", "AACH");
4198 param_write_string(pb, "FourCC", "AACL");
4200 } else if (track->par->codec_id == AV_CODEC_ID_WMAPRO) {
4201 param_write_string(pb, "FourCC", "WMAP");
4203 param_write_hex(pb, "CodecPrivateData", track->par->extradata,
4204 track->par->extradata_size);
4205 param_write_int(pb, "AudioTag", ff_codec_get_tag(ff_codec_wav_tags,
4206 track->par->codec_id));
4207 param_write_int(pb, "Channels", track->par->channels);
4208 param_write_int(pb, "SamplingRate", track->par->sample_rate);
4209 param_write_int(pb, "BitsPerSample", 16);
4210 param_write_int(pb, "PacketSize", track->par->block_align ?
4211 track->par->block_align : 4);
4213 avio_printf(pb, "</%s>\n", type);
4215 avio_printf(pb, "</switch>\n");
4216 avio_printf(pb, "</body>\n");
4217 avio_printf(pb, "</smil>\n");
4219 return update_size(pb, pos);
4222 static int mov_write_mfhd_tag(AVIOContext *pb, MOVMuxContext *mov)
4225 ffio_wfourcc(pb, "mfhd");
4227 avio_wb32(pb, mov->fragments);
4231 static uint32_t get_sample_flags(MOVTrack *track, MOVIentry *entry)
4233 return entry->flags & MOV_SYNC_SAMPLE ? MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO :
4234 (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC);
4237 static int mov_write_tfhd_tag(AVIOContext *pb, MOVMuxContext *mov,
4238 MOVTrack *track, int64_t moof_offset)
4240 int64_t pos = avio_tell(pb);
4241 uint32_t flags = MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
4242 MOV_TFHD_BASE_DATA_OFFSET;
4243 if (!track->entry) {
4244 flags |= MOV_TFHD_DURATION_IS_EMPTY;
4246 flags |= MOV_TFHD_DEFAULT_FLAGS;
4248 if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET)
4249 flags &= ~MOV_TFHD_BASE_DATA_OFFSET;
4250 if (mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) {
4251 flags &= ~MOV_TFHD_BASE_DATA_OFFSET;
4252 flags |= MOV_TFHD_DEFAULT_BASE_IS_MOOF;
4254 /* CMAF requires all values to be explicit in tfhd atoms */
4255 if (mov->flags & FF_MOV_FLAG_CMAF)
4256 flags |= MOV_TFHD_STSD_ID;
4258 /* Don't set a default sample size, the silverlight player refuses
4259 * to play files with that set. Don't set a default sample duration,
4260 * WMP freaks out if it is set. Don't set a base data offset, PIFF
4261 * file format says it MUST NOT be set. */
4262 if (track->mode == MODE_ISM)
4263 flags &= ~(MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
4264 MOV_TFHD_BASE_DATA_OFFSET | MOV_TFHD_STSD_ID);
4266 avio_wb32(pb, 0); /* size placeholder */
4267 ffio_wfourcc(pb, "tfhd");
4268 avio_w8(pb, 0); /* version */
4269 avio_wb24(pb, flags);
4271 avio_wb32(pb, track->track_id); /* track-id */
4272 if (flags & MOV_TFHD_BASE_DATA_OFFSET)
4273 avio_wb64(pb, moof_offset);
4274 if (flags & MOV_TFHD_STSD_ID) {
4277 if (flags & MOV_TFHD_DEFAULT_DURATION) {
4278 track->default_duration = get_cluster_duration(track, 0);
4279 avio_wb32(pb, track->default_duration);
4281 if (flags & MOV_TFHD_DEFAULT_SIZE) {
4282 track->default_size = track->entry ? track->cluster[0].size : 1;
4283 avio_wb32(pb, track->default_size);
4285 track->default_size = -1;
4287 if (flags & MOV_TFHD_DEFAULT_FLAGS) {
4288 /* Set the default flags based on the second sample, if available.
4289 * If the first sample is different, that can be signaled via a separate field. */
4290 if (track->entry > 1)
4291 track->default_sample_flags = get_sample_flags(track, &track->cluster[1]);
4293 track->default_sample_flags =
4294 track->par->codec_type == AVMEDIA_TYPE_VIDEO ?
4295 (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC) :
4296 MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO;
4297 avio_wb32(pb, track->default_sample_flags);
4300 return update_size(pb, pos);
4303 static int mov_write_trun_tag(AVIOContext *pb, MOVMuxContext *mov,
4304 MOVTrack *track, int moof_size,
4307 int64_t pos = avio_tell(pb);
4308 uint32_t flags = MOV_TRUN_DATA_OFFSET;
4311 for (i = first; i < end; i++) {
4312 if (get_cluster_duration(track, i) != track->default_duration)
4313 flags |= MOV_TRUN_SAMPLE_DURATION;
4314 if (track->cluster[i].size != track->default_size)
4315 flags |= MOV_TRUN_SAMPLE_SIZE;
4316 if (i > first && get_sample_flags(track, &track->cluster[i]) != track->default_sample_flags)
4317 flags |= MOV_TRUN_SAMPLE_FLAGS;
4319 if (!(flags & MOV_TRUN_SAMPLE_FLAGS) && track->entry > 0 &&
4320 get_sample_flags(track, &track->cluster[0]) != track->default_sample_flags)
4321 flags |= MOV_TRUN_FIRST_SAMPLE_FLAGS;
4322 if (track->flags & MOV_TRACK_CTTS)
4323 flags |= MOV_TRUN_SAMPLE_CTS;
4325 avio_wb32(pb, 0); /* size placeholder */
4326 ffio_wfourcc(pb, "trun");
4327 if (mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS)
4328 avio_w8(pb, 1); /* version */
4330 avio_w8(pb, 0); /* version */
4331 avio_wb24(pb, flags);
4333 avio_wb32(pb, end - first); /* sample count */
4334 if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET &&
4335 !(mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) &&
4337 avio_wb32(pb, 0); /* Later tracks follow immediately after the previous one */
4339 avio_wb32(pb, moof_size + 8 + track->data_offset +
4340 track->cluster[first].pos); /* data offset */
4341 if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS)
4342 avio_wb32(pb, get_sample_flags(track, &track->cluster[first]));
4344 for (i = first; i < end; i++) {
4345 if (flags & MOV_TRUN_SAMPLE_DURATION)
4346 avio_wb32(pb, get_cluster_duration(track, i));
4347 if (flags & MOV_TRUN_SAMPLE_SIZE)
4348 avio_wb32(pb, track->cluster[i].size);
4349 if (flags & MOV_TRUN_SAMPLE_FLAGS)
4350 avio_wb32(pb, get_sample_flags(track, &track->cluster[i]));
4351 if (flags & MOV_TRUN_SAMPLE_CTS)
4352 avio_wb32(pb, track->cluster[i].cts);
4355 mov->first_trun = 0;
4356 return update_size(pb, pos);
4359 static int mov_write_tfxd_tag(AVIOContext *pb, MOVTrack *track)
4361 int64_t pos = avio_tell(pb);
4362 static const uint8_t uuid[] = {
4363 0x6d, 0x1d, 0x9b, 0x05, 0x42, 0xd5, 0x44, 0xe6,
4364 0x80, 0xe2, 0x14, 0x1d, 0xaf, 0xf7, 0x57, 0xb2
4367 avio_wb32(pb, 0); /* size placeholder */
4368 ffio_wfourcc(pb, "uuid");
4369 avio_write(pb, uuid, sizeof(uuid));
4372 avio_wb64(pb, track->start_dts + track->frag_start +
4373 track->cluster[0].cts);
4374 avio_wb64(pb, track->end_pts -
4375 (track->cluster[0].dts + track->cluster[0].cts));
4377 return update_size(pb, pos);
4380 static int mov_write_tfrf_tag(AVIOContext *pb, MOVMuxContext *mov,
4381 MOVTrack *track, int entry)
4383 int n = track->nb_frag_info - 1 - entry, i;
4384 int size = 8 + 16 + 4 + 1 + 16*n;
4385 static const uint8_t uuid[] = {
4386 0xd4, 0x80, 0x7e, 0xf2, 0xca, 0x39, 0x46, 0x95,
4387 0x8e, 0x54, 0x26, 0xcb, 0x9e, 0x46, 0xa7, 0x9f
4393 avio_seek(pb, track->frag_info[entry].tfrf_offset, SEEK_SET);
4394 avio_wb32(pb, size);
4395 ffio_wfourcc(pb, "uuid");
4396 avio_write(pb, uuid, sizeof(uuid));
4400 for (i = 0; i < n; i++) {
4401 int index = entry + 1 + i;
4402 avio_wb64(pb, track->frag_info[index].time);
4403 avio_wb64(pb, track->frag_info[index].duration);
4405 if (n < mov->ism_lookahead) {
4406 int free_size = 16 * (mov->ism_lookahead - n);
4407 avio_wb32(pb, free_size);
4408 ffio_wfourcc(pb, "free");
4409 ffio_fill(pb, 0, free_size - 8);
4415 static int mov_write_tfrf_tags(AVIOContext *pb, MOVMuxContext *mov,
4418 int64_t pos = avio_tell(pb);
4420 for (i = 0; i < mov->ism_lookahead; i++) {
4421 /* Update the tfrf tag for the last ism_lookahead fragments,
4422 * nb_frag_info - 1 is the next fragment to be written. */
4423 mov_write_tfrf_tag(pb, mov, track, track->nb_frag_info - 2 - i);
4425 avio_seek(pb, pos, SEEK_SET);
4429 static int mov_add_tfra_entries(AVIOContext *pb, MOVMuxContext *mov, int tracks,
4433 for (i = 0; i < mov->nb_streams; i++) {
4434 MOVTrack *track = &mov->tracks[i];
4435 MOVFragmentInfo *info;
4436 if ((tracks >= 0 && i != tracks) || !track->entry)
4438 track->nb_frag_info++;
4439 if (track->nb_frag_info >= track->frag_info_capacity) {
4440 unsigned new_capacity = track->nb_frag_info + MOV_FRAG_INFO_ALLOC_INCREMENT;
4441 if (av_reallocp_array(&track->frag_info,
4443 sizeof(*track->frag_info)))
4444 return AVERROR(ENOMEM);
4445 track->frag_info_capacity = new_capacity;
4447 info = &track->frag_info[track->nb_frag_info - 1];
4448 info->offset = avio_tell(pb);
4450 // Try to recreate the original pts for the first packet
4451 // from the fields we have stored
4452 info->time = track->start_dts + track->frag_start +
4453 track->cluster[0].cts;
4454 info->duration = track->end_pts -
4455 (track->cluster[0].dts + track->cluster[0].cts);
4456 // If the pts is less than zero, we will have trimmed
4457 // away parts of the media track using an edit list,
4458 // and the corresponding start presentation time is zero.
4459 if (info->time < 0) {
4460 info->duration += info->time;
4463 info->tfrf_offset = 0;
4464 mov_write_tfrf_tags(pb, mov, track);
4469 static void mov_prune_frag_info(MOVMuxContext *mov, int tracks, int max)
4472 for (i = 0; i < mov->nb_streams; i++) {
4473 MOVTrack *track = &mov->tracks[i];
4474 if ((tracks >= 0 && i != tracks) || !track->entry)
4476 if (track->nb_frag_info > max) {
4477 memmove(track->frag_info, track->frag_info + (track->nb_frag_info - max), max * sizeof(*track->frag_info));
4478 track->nb_frag_info = max;
4483 static int mov_write_tfdt_tag(AVIOContext *pb, MOVTrack *track)
4485 int64_t pos = avio_tell(pb);
4487 avio_wb32(pb, 0); /* size */
4488 ffio_wfourcc(pb, "tfdt");
4489 avio_w8(pb, 1); /* version */
4491 avio_wb64(pb, track->frag_start);
4492 return update_size(pb, pos);
4495 static int mov_write_traf_tag(AVIOContext *pb, MOVMuxContext *mov,
4496 MOVTrack *track, int64_t moof_offset,
4499 int64_t pos = avio_tell(pb);
4501 avio_wb32(pb, 0); /* size placeholder */
4502 ffio_wfourcc(pb, "traf");
4504 mov_write_tfhd_tag(pb, mov, track, moof_offset);
4505 if (mov->mode != MODE_ISM)
4506 mov_write_tfdt_tag(pb, track);
4507 for (i = 1; i < track->entry; i++) {
4508 if (track->cluster[i].pos != track->cluster[i - 1].pos + track->cluster[i - 1].size) {
4509 mov_write_trun_tag(pb, mov, track, moof_size, start, i);
4513 mov_write_trun_tag(pb, mov, track, moof_size, start, track->entry);
4514 if (mov->mode == MODE_ISM) {
4515 mov_write_tfxd_tag(pb, track);
4517 if (mov->ism_lookahead) {
4518 int i, size = 16 + 4 + 1 + 16 * mov->ism_lookahead;
4520 if (track->nb_frag_info > 0) {
4521 MOVFragmentInfo *info = &track->frag_info[track->nb_frag_info - 1];
4522 if (!info->tfrf_offset)
4523 info->tfrf_offset = avio_tell(pb);
4525 avio_wb32(pb, 8 + size);
4526 ffio_wfourcc(pb, "free");
4527 for (i = 0; i < size; i++)
4532 return update_size(pb, pos);
4535 static int mov_write_moof_tag_internal(AVIOContext *pb, MOVMuxContext *mov,
4536 int tracks, int moof_size)
4538 int64_t pos = avio_tell(pb);
4541 avio_wb32(pb, 0); /* size placeholder */
4542 ffio_wfourcc(pb, "moof");
4543 mov->first_trun = 1;
4545 mov_write_mfhd_tag(pb, mov);
4546 for (i = 0; i < mov->nb_streams; i++) {
4547 MOVTrack *track = &mov->tracks[i];
4548 if (tracks >= 0 && i != tracks)
4552 mov_write_traf_tag(pb, mov, track, pos, moof_size);
4555 return update_size(pb, pos);
4558 static int mov_write_sidx_tag(AVIOContext *pb,
4559 MOVTrack *track, int ref_size, int total_sidx_size)
4561 int64_t pos = avio_tell(pb), offset_pos, end_pos;
4562 int64_t presentation_time, duration, offset;
4563 unsigned starts_with_SAP;
4568 presentation_time = track->start_dts + track->frag_start +
4569 track->cluster[0].cts;
4570 duration = track->end_pts -
4571 (track->cluster[0].dts + track->cluster[0].cts);
4572 starts_with_SAP = track->cluster[0].flags & MOV_SYNC_SAMPLE;
4574 // pts<0 should be cut away using edts
4575 if (presentation_time < 0) {
4576 duration += presentation_time;
4577 presentation_time = 0;
4580 entries = track->nb_frag_info;
4583 presentation_time = track->frag_info[0].time;
4586 avio_wb32(pb, 0); /* size */
4587 ffio_wfourcc(pb, "sidx");
4588 avio_w8(pb, 1); /* version */
4590 avio_wb32(pb, track->track_id); /* reference_ID */
4591 avio_wb32(pb, track->timescale); /* timescale */
4592 avio_wb64(pb, presentation_time); /* earliest_presentation_time */
4593 offset_pos = avio_tell(pb);
4594 avio_wb64(pb, 0); /* first_offset (offset to referenced moof) */
4595 avio_wb16(pb, 0); /* reserved */
4597 avio_wb16(pb, entries); /* reference_count */
4598 for (i = 0; i < entries; i++) {
4599 if (!track->entry) {
4600 if (i > 1 && track->frag_info[i].offset != track->frag_info[i - 1].offset + track->frag_info[i - 1].size) {
4601 av_log(NULL, AV_LOG_ERROR, "Non-consecutive fragments, writing incorrect sidx\n");
4603 duration = track->frag_info[i].duration;
4604 ref_size = track->frag_info[i].size;
4605 starts_with_SAP = 1;
4607 avio_wb32(pb, (0 << 31) | (ref_size & 0x7fffffff)); /* reference_type (0 = media) | referenced_size */
4608 avio_wb32(pb, duration); /* subsegment_duration */
4609 avio_wb32(pb, (starts_with_SAP << 31) | (0 << 28) | 0); /* starts_with_SAP | SAP_type | SAP_delta_time */
4612 end_pos = avio_tell(pb);
4613 offset = pos + total_sidx_size - end_pos;
4614 avio_seek(pb, offset_pos, SEEK_SET);
4615 avio_wb64(pb, offset);
4616 avio_seek(pb, end_pos, SEEK_SET);
4617 return update_size(pb, pos);
4620 static int mov_write_sidx_tags(AVIOContext *pb, MOVMuxContext *mov,
4621 int tracks, int ref_size)
4624 AVIOContext *avio_buf;
4626 for (round = 0; round < 2; round++) {
4627 // First run one round to calculate the total size of all
4629 // This would be much simpler if we'd only write one sidx
4630 // atom, for the first track in the moof.
4632 if ((ret = ffio_open_null_buf(&avio_buf)) < 0)
4637 for (i = 0; i < mov->nb_streams; i++) {
4638 MOVTrack *track = &mov->tracks[i];
4639 if (tracks >= 0 && i != tracks)
4641 // When writing a sidx for the full file, entry is 0, but
4642 // we want to include all tracks. ref_size is 0 in this case,
4643 // since we read it from frag_info instead.
4644 if (!track->entry && ref_size > 0)
4646 total_size -= mov_write_sidx_tag(avio_buf, track, ref_size,
4650 total_size = ffio_close_null_buf(avio_buf);
4655 static int mov_write_prft_tag(AVIOContext *pb, MOVMuxContext *mov, int tracks)
4657 int64_t pos = avio_tell(pb), pts_us, ntp_ts;
4658 MOVTrack *first_track;
4661 /* PRFT should be associated with at most one track. So, choosing only the
4665 first_track = &(mov->tracks[0]);
4667 if (!first_track->entry) {
4668 av_log(mov->fc, AV_LOG_WARNING, "Unable to write PRFT, no entries in the track\n");
4672 if (first_track->cluster[0].pts == AV_NOPTS_VALUE) {
4673 av_log(mov->fc, AV_LOG_WARNING, "Unable to write PRFT, first PTS is invalid\n");
4677 if (mov->write_prft == MOV_PRFT_SRC_WALLCLOCK) {
4678 if (first_track->cluster[0].prft.wallclock) {
4679 /* Round the NTP time to whole milliseconds. */
4680 ntp_ts = ff_get_formatted_ntp_time((first_track->cluster[0].prft.wallclock / 1000) * 1000 +
4682 flags = first_track->cluster[0].prft.flags;
4684 ntp_ts = ff_get_formatted_ntp_time(ff_ntp_time());
4685 } else if (mov->write_prft == MOV_PRFT_SRC_PTS) {
4686 pts_us = av_rescale_q(first_track->cluster[0].pts,
4687 first_track->st->time_base, AV_TIME_BASE_Q);
4688 ntp_ts = ff_get_formatted_ntp_time(pts_us + NTP_OFFSET_US);
4690 av_log(mov->fc, AV_LOG_WARNING, "Unsupported PRFT box configuration: %d\n",
4695 avio_wb32(pb, 0); // Size place holder
4696 ffio_wfourcc(pb, "prft"); // Type
4697 avio_w8(pb, 1); // Version
4698 avio_wb24(pb, flags); // Flags
4699 avio_wb32(pb, first_track->track_id); // reference track ID
4700 avio_wb64(pb, ntp_ts); // NTP time stamp
4701 avio_wb64(pb, first_track->cluster[0].pts); //media time
4702 return update_size(pb, pos);
4705 static int mov_write_moof_tag(AVIOContext *pb, MOVMuxContext *mov, int tracks,
4708 AVIOContext *avio_buf;
4711 if ((ret = ffio_open_null_buf(&avio_buf)) < 0)
4713 mov_write_moof_tag_internal(avio_buf, mov, tracks, 0);
4714 moof_size = ffio_close_null_buf(avio_buf);
4716 if (mov->flags & FF_MOV_FLAG_DASH &&
4717 !(mov->flags & (FF_MOV_FLAG_GLOBAL_SIDX | FF_MOV_FLAG_SKIP_SIDX)))
4718 mov_write_sidx_tags(pb, mov, tracks, moof_size + 8 + mdat_size);
4720 if (mov->write_prft > MOV_PRFT_NONE && mov->write_prft < MOV_PRFT_NB)
4721 mov_write_prft_tag(pb, mov, tracks);
4723 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX ||
4724 !(mov->flags & FF_MOV_FLAG_SKIP_TRAILER) ||
4725 mov->ism_lookahead) {
4726 if ((ret = mov_add_tfra_entries(pb, mov, tracks, moof_size + 8 + mdat_size)) < 0)
4728 if (!(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) &&
4729 mov->flags & FF_MOV_FLAG_SKIP_TRAILER) {
4730 mov_prune_frag_info(mov, tracks, mov->ism_lookahead + 1);
4734 return mov_write_moof_tag_internal(pb, mov, tracks, moof_size);
4737 static int mov_write_tfra_tag(AVIOContext *pb, MOVTrack *track)
4739 int64_t pos = avio_tell(pb);
4742 avio_wb32(pb, 0); /* size placeholder */
4743 ffio_wfourcc(pb, "tfra");
4744 avio_w8(pb, 1); /* version */
4747 avio_wb32(pb, track->track_id);
4748 avio_wb32(pb, 0); /* length of traf/trun/sample num */
4749 avio_wb32(pb, track->nb_frag_info);
4750 for (i = 0; i < track->nb_frag_info; i++) {
4751 avio_wb64(pb, track->frag_info[i].time);
4752 avio_wb64(pb, track->frag_info[i].offset + track->data_offset);
4753 avio_w8(pb, 1); /* traf number */
4754 avio_w8(pb, 1); /* trun number */
4755 avio_w8(pb, 1); /* sample number */
4758 return update_size(pb, pos);
4761 static int mov_write_mfra_tag(AVIOContext *pb, MOVMuxContext *mov)
4763 int64_t pos = avio_tell(pb);
4766 avio_wb32(pb, 0); /* size placeholder */
4767 ffio_wfourcc(pb, "mfra");
4768 /* An empty mfra atom is enough to indicate to the publishing point that
4769 * the stream has ended. */
4770 if (mov->flags & FF_MOV_FLAG_ISML)
4771 return update_size(pb, pos);
4773 for (i = 0; i < mov->nb_streams; i++) {
4774 MOVTrack *track = &mov->tracks[i];
4775 if (track->nb_frag_info)
4776 mov_write_tfra_tag(pb, track);
4780 ffio_wfourcc(pb, "mfro");
4781 avio_wb32(pb, 0); /* version + flags */
4782 avio_wb32(pb, avio_tell(pb) + 4 - pos);
4784 return update_size(pb, pos);
4787 static int mov_write_mdat_tag(AVIOContext *pb, MOVMuxContext *mov)
4789 avio_wb32(pb, 8); // placeholder for extended size field (64 bit)
4790 ffio_wfourcc(pb, mov->mode == MODE_MOV ? "wide" : "free");
4792 mov->mdat_pos = avio_tell(pb);
4793 avio_wb32(pb, 0); /* size placeholder*/
4794 ffio_wfourcc(pb, "mdat");
4798 static void mov_write_ftyp_tag_internal(AVIOContext *pb, AVFormatContext *s,
4799 int has_h264, int has_video, int write_minor)
4801 MOVMuxContext *mov = s->priv_data;
4804 if (mov->major_brand && strlen(mov->major_brand) >= 4)
4805 ffio_wfourcc(pb, mov->major_brand);
4806 else if (mov->mode == MODE_3GP) {
4807 ffio_wfourcc(pb, has_h264 ? "3gp6" : "3gp4");
4808 minor = has_h264 ? 0x100 : 0x200;
4809 } else if (mov->mode & MODE_3G2) {
4810 ffio_wfourcc(pb, has_h264 ? "3g2b" : "3g2a");
4811 minor = has_h264 ? 0x20000 : 0x10000;
4812 } else if (mov->mode == MODE_PSP)
4813 ffio_wfourcc(pb, "MSNV");
4814 else if (mov->mode == MODE_MP4 && mov->flags & FF_MOV_FLAG_FRAGMENT &&
4815 mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS)
4816 ffio_wfourcc(pb, "iso6"); // Required when using signed CTS offsets in trun boxes
4817 else if (mov->mode == MODE_MP4 && mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)
4818 ffio_wfourcc(pb, "iso5"); // Required when using default-base-is-moof
4819 else if (mov->mode == MODE_MP4 && mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS)
4820 ffio_wfourcc(pb, "iso4");
4821 else if (mov->mode == MODE_MP4)
4822 ffio_wfourcc(pb, "isom");
4823 else if (mov->mode == MODE_IPOD)
4824 ffio_wfourcc(pb, has_video ? "M4V ":"M4A ");
4825 else if (mov->mode == MODE_ISM)
4826 ffio_wfourcc(pb, "isml");
4827 else if (mov->mode == MODE_F4V)
4828 ffio_wfourcc(pb, "f4v ");
4830 ffio_wfourcc(pb, "qt ");
4833 avio_wb32(pb, minor);
4836 static int mov_write_ftyp_tag(AVIOContext *pb, AVFormatContext *s)
4838 MOVMuxContext *mov = s->priv_data;
4839 int64_t pos = avio_tell(pb);
4840 int has_h264 = 0, has_video = 0;
4843 for (i = 0; i < s->nb_streams; i++) {
4844 AVStream *st = s->streams[i];
4845 if (is_cover_image(st))
4847 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
4849 if (st->codecpar->codec_id == AV_CODEC_ID_H264)
4853 avio_wb32(pb, 0); /* size */
4854 ffio_wfourcc(pb, "ftyp");
4856 // Write major brand
4857 mov_write_ftyp_tag_internal(pb, s, has_h264, has_video, 1);
4858 // Write the major brand as the first compatible brand as well
4859 mov_write_ftyp_tag_internal(pb, s, has_h264, has_video, 0);
4861 // Write compatible brands, ensuring that we don't write the major brand as a
4862 // compatible brand a second time.
4863 if (mov->mode == MODE_ISM) {
4864 ffio_wfourcc(pb, "piff");
4865 } else if (mov->mode != MODE_MOV) {
4866 // We add tfdt atoms when fragmenting, signal this with the iso6 compatible
4867 // brand, if not already the major brand. This is compatible with users that
4868 // don't understand tfdt.
4869 if (mov->mode == MODE_MP4) {
4870 if (mov->flags & FF_MOV_FLAG_CMAF)
4871 ffio_wfourcc(pb, "cmfc");
4872 if (mov->flags & FF_MOV_FLAG_FRAGMENT && !(mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS))
4873 ffio_wfourcc(pb, "iso6");
4875 if (mov->flags & FF_MOV_FLAG_FRAGMENT)
4876 ffio_wfourcc(pb, "iso6");
4877 if (mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)
4878 ffio_wfourcc(pb, "iso5");
4879 else if (mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS)
4880 ffio_wfourcc(pb, "iso4");
4882 // Brands prior to iso5 can't be signaled when using default-base-is-moof
4883 if (!(mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)) {
4884 // write isom for mp4 only if it it's not the major brand already.
4885 if (mov->mode != MODE_MP4 || mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS)
4886 ffio_wfourcc(pb, "isom");
4887 ffio_wfourcc(pb, "iso2");
4889 ffio_wfourcc(pb, "avc1");
4893 if (mov->mode == MODE_MP4)
4894 ffio_wfourcc(pb, "mp41");
4896 if (mov->flags & FF_MOV_FLAG_DASH && mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
4897 ffio_wfourcc(pb, "dash");
4899 return update_size(pb, pos);
4902 static int mov_write_uuidprof_tag(AVIOContext *pb, AVFormatContext *s)
4904 AVStream *video_st = s->streams[0];
4905 AVCodecParameters *video_par = s->streams[0]->codecpar;
4906 AVCodecParameters *audio_par = s->streams[1]->codecpar;
4907 int audio_rate = audio_par->sample_rate;
4908 int64_t frame_rate = video_st->avg_frame_rate.den ?
4909 (video_st->avg_frame_rate.num * 0x10000LL) / video_st->avg_frame_rate.den :
4911 int audio_kbitrate = audio_par->bit_rate / 1000;
4912 int video_kbitrate = FFMIN(video_par->bit_rate / 1000, 800 - audio_kbitrate);
4914 if (frame_rate < 0 || frame_rate > INT32_MAX) {
4915 av_log(s, AV_LOG_ERROR, "Frame rate %f outside supported range\n", frame_rate / (double)0x10000);
4916 return AVERROR(EINVAL);
4919 avio_wb32(pb, 0x94); /* size */
4920 ffio_wfourcc(pb, "uuid");
4921 ffio_wfourcc(pb, "PROF");
4923 avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
4924 avio_wb32(pb, 0xbb88695c);
4925 avio_wb32(pb, 0xfac9c740);
4927 avio_wb32(pb, 0x0); /* ? */
4928 avio_wb32(pb, 0x3); /* 3 sections ? */
4930 avio_wb32(pb, 0x14); /* size */
4931 ffio_wfourcc(pb, "FPRF");
4932 avio_wb32(pb, 0x0); /* ? */
4933 avio_wb32(pb, 0x0); /* ? */
4934 avio_wb32(pb, 0x0); /* ? */
4936 avio_wb32(pb, 0x2c); /* size */
4937 ffio_wfourcc(pb, "APRF"); /* audio */
4939 avio_wb32(pb, 0x2); /* TrackID */
4940 ffio_wfourcc(pb, "mp4a");
4941 avio_wb32(pb, 0x20f);
4943 avio_wb32(pb, audio_kbitrate);
4944 avio_wb32(pb, audio_kbitrate);
4945 avio_wb32(pb, audio_rate);
4946 avio_wb32(pb, audio_par->channels);
4948 avio_wb32(pb, 0x34); /* size */
4949 ffio_wfourcc(pb, "VPRF"); /* video */
4951 avio_wb32(pb, 0x1); /* TrackID */
4952 if (video_par->codec_id == AV_CODEC_ID_H264) {
4953 ffio_wfourcc(pb, "avc1");
4954 avio_wb16(pb, 0x014D);
4955 avio_wb16(pb, 0x0015);
4957 ffio_wfourcc(pb, "mp4v");
4958 avio_wb16(pb, 0x0000);
4959 avio_wb16(pb, 0x0103);
4962 avio_wb32(pb, video_kbitrate);
4963 avio_wb32(pb, video_kbitrate);
4964 avio_wb32(pb, frame_rate);
4965 avio_wb32(pb, frame_rate);
4966 avio_wb16(pb, video_par->width);
4967 avio_wb16(pb, video_par->height);
4968 avio_wb32(pb, 0x010001); /* ? */
4973 static int mov_write_identification(AVIOContext *pb, AVFormatContext *s)
4975 MOVMuxContext *mov = s->priv_data;
4978 mov_write_ftyp_tag(pb,s);
4979 if (mov->mode == MODE_PSP) {
4980 int video_streams_nb = 0, audio_streams_nb = 0, other_streams_nb = 0;
4981 for (i = 0; i < s->nb_streams; i++) {
4982 AVStream *st = s->streams[i];
4983 if (is_cover_image(st))
4985 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
4987 else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
4993 if (video_streams_nb != 1 || audio_streams_nb != 1 || other_streams_nb) {
4994 av_log(s, AV_LOG_ERROR, "PSP mode need one video and one audio stream\n");
4995 return AVERROR(EINVAL);
4997 return mov_write_uuidprof_tag(pb, s);
5002 static int mov_parse_mpeg2_frame(AVPacket *pkt, uint32_t *flags)
5005 int i, closed_gop = 0;
5007 for (i = 0; i < pkt->size - 4; i++) {
5008 c = (c << 8) + pkt->data[i];
5009 if (c == 0x1b8) { // gop
5010 closed_gop = pkt->data[i + 4] >> 6 & 0x01;
5011 } else if (c == 0x100) { // pic
5012 int temp_ref = (pkt->data[i + 1] << 2) | (pkt->data[i + 2] >> 6);
5013 if (!temp_ref || closed_gop) // I picture is not reordered
5014 *flags = MOV_SYNC_SAMPLE;
5016 *flags = MOV_PARTIAL_SYNC_SAMPLE;
5023 static void mov_parse_vc1_frame(AVPacket *pkt, MOVTrack *trk)
5025 const uint8_t *start, *next, *end = pkt->data + pkt->size;
5026 int seq = 0, entry = 0;
5027 int key = pkt->flags & AV_PKT_FLAG_KEY;
5028 start = find_next_marker(pkt->data, end);
5029 for (next = start; next < end; start = next) {
5030 next = find_next_marker(start + 4, end);
5031 switch (AV_RB32(start)) {
5032 case VC1_CODE_SEQHDR:
5035 case VC1_CODE_ENTRYPOINT:
5038 case VC1_CODE_SLICE:
5039 trk->vc1_info.slices = 1;
5043 if (!trk->entry && trk->vc1_info.first_packet_seen)
5044 trk->vc1_info.first_frag_written = 1;
5045 if (!trk->entry && !trk->vc1_info.first_frag_written) {
5046 /* First packet in first fragment */
5047 trk->vc1_info.first_packet_seq = seq;
5048 trk->vc1_info.first_packet_entry = entry;
5049 trk->vc1_info.first_packet_seen = 1;
5050 } else if ((seq && !trk->vc1_info.packet_seq) ||
5051 (entry && !trk->vc1_info.packet_entry)) {
5053 for (i = 0; i < trk->entry; i++)
5054 trk->cluster[i].flags &= ~MOV_SYNC_SAMPLE;
5055 trk->has_keyframes = 0;
5057 trk->vc1_info.packet_seq = 1;
5059 trk->vc1_info.packet_entry = 1;
5060 if (!trk->vc1_info.first_frag_written) {
5061 /* First fragment */
5062 if ((!seq || trk->vc1_info.first_packet_seq) &&
5063 (!entry || trk->vc1_info.first_packet_entry)) {
5064 /* First packet had the same headers as this one, readd the
5065 * sync sample flag. */
5066 trk->cluster[0].flags |= MOV_SYNC_SAMPLE;
5067 trk->has_keyframes = 1;
5071 if (trk->vc1_info.packet_seq && trk->vc1_info.packet_entry)
5073 else if (trk->vc1_info.packet_seq)
5075 else if (trk->vc1_info.packet_entry)
5078 trk->cluster[trk->entry].flags |= MOV_SYNC_SAMPLE;
5079 trk->has_keyframes++;
5083 static void mov_parse_truehd_frame(AVPacket *pkt, MOVTrack *trk)
5090 length = (AV_RB16(pkt->data) & 0xFFF) * 2;
5091 if (length < 8 || length > pkt->size)
5094 if (AV_RB32(pkt->data + 4) == 0xF8726FBA) {
5095 trk->cluster[trk->entry].flags |= MOV_SYNC_SAMPLE;
5096 trk->has_keyframes++;
5102 static int mov_flush_fragment_interleaving(AVFormatContext *s, MOVTrack *track)
5104 MOVMuxContext *mov = s->priv_data;
5109 if (!track->mdat_buf)
5111 if (!mov->mdat_buf) {
5112 if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0)
5115 buf_size = avio_get_dyn_buf(track->mdat_buf, &buf);
5117 offset = avio_tell(mov->mdat_buf);
5118 avio_write(mov->mdat_buf, buf, buf_size);
5119 ffio_free_dyn_buf(&track->mdat_buf);
5121 for (i = track->entries_flushed; i < track->entry; i++)
5122 track->cluster[i].pos += offset;
5123 track->entries_flushed = track->entry;
5127 static int mov_flush_fragment(AVFormatContext *s, int force)
5129 MOVMuxContext *mov = s->priv_data;
5130 int i, first_track = -1;
5131 int64_t mdat_size = 0;
5133 int has_video = 0, starts_with_key = 0, first_video_track = 1;
5135 if (!(mov->flags & FF_MOV_FLAG_FRAGMENT))
5138 // Try to fill in the duration of the last packet in each stream
5139 // from queued packets in the interleave queues. If the flushing
5140 // of fragments was triggered automatically by an AVPacket, we
5141 // already have reliable info for the end of that track, but other
5142 // tracks may need to be filled in.
5143 for (i = 0; i < s->nb_streams; i++) {
5144 MOVTrack *track = &mov->tracks[i];
5145 if (!track->end_reliable) {
5147 if (!ff_interleaved_peek(s, i, &pkt, 1)) {
5148 if (track->dts_shift != AV_NOPTS_VALUE)
5149 pkt.dts += track->dts_shift;
5150 track->track_duration = pkt.dts - track->start_dts;
5151 if (pkt.pts != AV_NOPTS_VALUE)
5152 track->end_pts = pkt.pts;
5154 track->end_pts = pkt.dts;
5159 for (i = 0; i < mov->nb_streams; i++) {
5160 MOVTrack *track = &mov->tracks[i];
5161 if (track->entry <= 1)
5163 // Sample durations are calculated as the diff of dts values,
5164 // but for the last sample in a fragment, we don't know the dts
5165 // of the first sample in the next fragment, so we have to rely
5166 // on what was set as duration in the AVPacket. Not all callers
5167 // set this though, so we might want to replace it with an
5168 // estimate if it currently is zero.
5169 if (get_cluster_duration(track, track->entry - 1) != 0)
5171 // Use the duration (i.e. dts diff) of the second last sample for
5172 // the last one. This is a wild guess (and fatal if it turns out
5173 // to be too long), but probably the best we can do - having a zero
5174 // duration is bad as well.
5175 track->track_duration += get_cluster_duration(track, track->entry - 2);
5176 track->end_pts += get_cluster_duration(track, track->entry - 2);
5177 if (!mov->missing_duration_warned) {
5178 av_log(s, AV_LOG_WARNING,
5179 "Estimating the duration of the last packet in a "
5180 "fragment, consider setting the duration field in "
5181 "AVPacket instead.\n");
5182 mov->missing_duration_warned = 1;
5186 if (!mov->moov_written) {
5187 int64_t pos = avio_tell(s->pb);
5189 int buf_size, moov_size;
5191 for (i = 0; i < mov->nb_streams; i++)
5192 if (!mov->tracks[i].entry && !is_cover_image(mov->tracks[i].st))
5194 /* Don't write the initial moov unless all tracks have data */
5195 if (i < mov->nb_streams && !force)
5198 moov_size = get_moov_size(s);
5199 for (i = 0; i < mov->nb_streams; i++)
5200 mov->tracks[i].data_offset = pos + moov_size + 8;
5202 avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_HEADER);
5203 if (mov->flags & FF_MOV_FLAG_DELAY_MOOV)
5204 mov_write_identification(s->pb, s);
5205 if ((ret = mov_write_moov_tag(s->pb, mov, s)) < 0)
5208 if (mov->flags & FF_MOV_FLAG_DELAY_MOOV) {
5209 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
5210 mov->reserved_header_pos = avio_tell(s->pb);
5211 avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_FLUSH_POINT);
5212 mov->moov_written = 1;
5216 buf_size = avio_get_dyn_buf(mov->mdat_buf, &buf);
5217 avio_wb32(s->pb, buf_size + 8);
5218 ffio_wfourcc(s->pb, "mdat");
5219 avio_write(s->pb, buf, buf_size);
5220 ffio_free_dyn_buf(&mov->mdat_buf);
5222 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
5223 mov->reserved_header_pos = avio_tell(s->pb);
5225 mov->moov_written = 1;
5227 for (i = 0; i < mov->nb_streams; i++) {
5228 if (mov->tracks[i].entry)
5229 mov->tracks[i].frag_start += mov->tracks[i].start_dts +
5230 mov->tracks[i].track_duration -
5231 mov->tracks[i].cluster[0].dts;
5232 mov->tracks[i].entry = 0;
5233 mov->tracks[i].end_reliable = 0;
5235 avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_FLUSH_POINT);
5239 if (mov->frag_interleave) {
5240 for (i = 0; i < mov->nb_streams; i++) {
5241 MOVTrack *track = &mov->tracks[i];
5243 if ((ret = mov_flush_fragment_interleaving(s, track)) < 0)
5249 mdat_size = avio_tell(mov->mdat_buf);
5252 for (i = 0; i < mov->nb_streams; i++) {
5253 MOVTrack *track = &mov->tracks[i];
5254 if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF || mov->frag_interleave)
5255 track->data_offset = 0;
5257 track->data_offset = mdat_size;
5258 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
5260 if (first_video_track) {
5262 starts_with_key = track->cluster[0].flags & MOV_SYNC_SAMPLE;
5263 first_video_track = 0;
5268 if (track->mdat_buf)
5269 mdat_size += avio_tell(track->mdat_buf);
5270 if (first_track < 0)
5277 avio_write_marker(s->pb,
5278 av_rescale(mov->tracks[first_track].cluster[0].dts, AV_TIME_BASE, mov->tracks[first_track].timescale),
5279 (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);
5281 for (i = 0; i < mov->nb_streams; i++) {
5282 MOVTrack *track = &mov->tracks[i];
5283 int buf_size, write_moof = 1, moof_tracks = -1;
5285 int64_t duration = 0;
5288 duration = track->start_dts + track->track_duration -
5289 track->cluster[0].dts;
5290 if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF) {
5291 if (!track->mdat_buf)
5293 mdat_size = avio_tell(track->mdat_buf);
5296 write_moof = i == first_track;
5300 avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_FLUSH_POINT);
5302 mov_write_moof_tag(s->pb, mov, moof_tracks, mdat_size);
5305 avio_wb32(s->pb, mdat_size + 8);
5306 ffio_wfourcc(s->pb, "mdat");
5310 track->frag_start += duration;
5312 track->entries_flushed = 0;
5313 track->end_reliable = 0;
5314 if (!mov->frag_interleave) {
5315 if (!track->mdat_buf)
5317 buf_size = avio_close_dyn_buf(track->mdat_buf, &buf);
5318 track->mdat_buf = NULL;
5322 buf_size = avio_close_dyn_buf(mov->mdat_buf, &buf);
5323 mov->mdat_buf = NULL;
5326 avio_write(s->pb, buf, buf_size);
5332 avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_FLUSH_POINT);
5336 static int mov_auto_flush_fragment(AVFormatContext *s, int force)
5338 MOVMuxContext *mov = s->priv_data;
5339 int had_moov = mov->moov_written;
5340 int ret = mov_flush_fragment(s, force);
5343 // If using delay_moov, the first flush only wrote the moov,
5344 // not the actual moof+mdat pair, thus flush once again.
5345 if (!had_moov && mov->flags & FF_MOV_FLAG_DELAY_MOOV)
5346 ret = mov_flush_fragment(s, force);
5350 static int check_pkt(AVFormatContext *s, AVPacket *pkt)
5352 MOVMuxContext *mov = s->priv_data;
5353 MOVTrack *trk = &mov->tracks[pkt->stream_index];
5358 ref = trk->cluster[trk->entry - 1].dts;
5359 } else if ( trk->start_dts != AV_NOPTS_VALUE
5360 && !trk->frag_discont) {
5361 ref = trk->start_dts + trk->track_duration;
5363 ref = pkt->dts; // Skip tests for the first packet
5365 if (trk->dts_shift != AV_NOPTS_VALUE) {
5366 /* With negative CTS offsets we have set an offset to the DTS,
5367 * reverse this for the check. */
5368 ref -= trk->dts_shift;
5371 duration = pkt->dts - ref;
5372 if (pkt->dts < ref || duration >= INT_MAX) {
5373 av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" / timestamp: %"PRId64" is out of range for mov/mp4 format\n",
5378 pkt->pts = AV_NOPTS_VALUE;
5381 if (pkt->duration < 0 || pkt->duration > INT_MAX) {
5382 av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" is invalid\n", pkt->duration);
5383 return AVERROR(EINVAL);
5388 int ff_mov_write_packet(AVFormatContext *s, AVPacket *pkt)
5390 MOVMuxContext *mov = s->priv_data;
5391 AVIOContext *pb = s->pb;
5392 MOVTrack *trk = &mov->tracks[pkt->stream_index];
5393 AVCodecParameters *par = trk->par;
5394 AVProducerReferenceTime *prft;
5395 unsigned int samples_in_chunk = 0;
5396 int size = pkt->size, ret = 0, offset = 0;
5398 uint8_t *reformatted_data = NULL;
5400 ret = check_pkt(s, pkt);
5404 if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
5406 if (mov->moov_written || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
5407 if (mov->frag_interleave && mov->fragments > 0) {
5408 if (trk->entry - trk->entries_flushed >= mov->frag_interleave) {
5409 if ((ret = mov_flush_fragment_interleaving(s, trk)) < 0)
5414 if (!trk->mdat_buf) {
5415 if ((ret = avio_open_dyn_buf(&trk->mdat_buf)) < 0)
5420 if (!mov->mdat_buf) {
5421 if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0)
5428 if (par->codec_id == AV_CODEC_ID_AMR_NB) {
5429 /* We must find out how many AMR blocks there are in one packet */
5430 static const uint16_t packed_size[16] =
5431 {13, 14, 16, 18, 20, 21, 27, 32, 6, 0, 0, 0, 0, 0, 0, 1};
5434 while (len < size && samples_in_chunk < 100) {
5435 len += packed_size[(pkt->data[len] >> 3) & 0x0F];
5438 if (samples_in_chunk > 1) {
5439 av_log(s, AV_LOG_ERROR, "fatal error, input is not a single packet, implement a AVParser for it\n");
5442 } else if (par->codec_id == AV_CODEC_ID_ADPCM_MS ||
5443 par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) {
5444 samples_in_chunk = trk->par->frame_size;
5445 } else if (trk->sample_size)
5446 samples_in_chunk = size / trk->sample_size;
5448 samples_in_chunk = 1;
5450 if (samples_in_chunk < 1) {
5451 av_log(s, AV_LOG_ERROR, "fatal error, input packet contains no samples\n");
5452 return AVERROR_PATCHWELCOME;
5455 /* copy extradata if it exists */
5456 if (trk->vos_len == 0 && par->extradata_size > 0 &&
5457 !TAG_IS_AVCI(trk->tag) &&
5458 (par->codec_id != AV_CODEC_ID_DNXHD)) {
5459 trk->vos_len = par->extradata_size;
5460 trk->vos_data = av_malloc(trk->vos_len + AV_INPUT_BUFFER_PADDING_SIZE);
5461 if (!trk->vos_data) {
5462 ret = AVERROR(ENOMEM);
5465 memcpy(trk->vos_data, par->extradata, trk->vos_len);
5466 memset(trk->vos_data + trk->vos_len, 0, AV_INPUT_BUFFER_PADDING_SIZE);
5469 if (par->codec_id == AV_CODEC_ID_AAC && pkt->size > 2 &&
5470 (AV_RB16(pkt->data) & 0xfff0) == 0xfff0) {
5471 if (!s->streams[pkt->stream_index]->nb_frames) {
5472 av_log(s, AV_LOG_ERROR, "Malformed AAC bitstream detected: "
5473 "use the audio bitstream filter 'aac_adtstoasc' to fix it "
5474 "('-bsf:a aac_adtstoasc' option with ffmpeg)\n");
5477 av_log(s, AV_LOG_WARNING, "aac bitstream error\n");
5479 if (par->codec_id == AV_CODEC_ID_H264 && trk->vos_len > 0 && *(uint8_t *)trk->vos_data != 1 && !TAG_IS_AVCI(trk->tag)) {
5480 /* from x264 or from bytestream H.264 */
5481 /* NAL reformatting needed */
5482 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
5483 ret = ff_avc_parse_nal_units_buf(pkt->data, &reformatted_data,
5487 avio_write(pb, reformatted_data, size);
5489 if (trk->cenc.aes_ctr) {
5490 size = ff_mov_cenc_avc_parse_nal_units(&trk->cenc, pb, pkt->data, size);
5496 size = ff_avc_parse_nal_units(pb, pkt->data, pkt->size);
5499 } else if (par->codec_id == AV_CODEC_ID_HEVC && trk->vos_len > 6 &&
5500 (AV_RB24(trk->vos_data) == 1 || AV_RB32(trk->vos_data) == 1)) {
5501 /* extradata is Annex B, assume the bitstream is too and convert it */
5502 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
5503 ret = ff_hevc_annexb2mp4_buf(pkt->data, &reformatted_data,
5507 avio_write(pb, reformatted_data, size);
5509 size = ff_hevc_annexb2mp4(pb, pkt->data, pkt->size, 0, NULL);
5511 } else if (par->codec_id == AV_CODEC_ID_AV1) {
5512 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
5513 ret = ff_av1_filter_obus_buf(pkt->data, &reformatted_data,
5517 avio_write(pb, reformatted_data, size);
5519 size = ff_av1_filter_obus(pb, pkt->data, pkt->size);
5521 #if CONFIG_AC3_PARSER
5522 } else if (par->codec_id == AV_CODEC_ID_EAC3) {
5523 size = handle_eac3(mov, pkt, trk);
5528 avio_write(pb, pkt->data, size);
5531 if (trk->cenc.aes_ctr) {
5532 if (par->codec_id == AV_CODEC_ID_H264 && par->extradata_size > 4) {
5533 int nal_size_length = (par->extradata[4] & 0x3) + 1;
5534 ret = ff_mov_cenc_avc_write_nal_units(s, &trk->cenc, nal_size_length, pb, pkt->data, size);
5536 ret = ff_mov_cenc_write_packet(&trk->cenc, pb, pkt->data, size);
5543 avio_write(pb, pkt->data, size);
5547 if ((par->codec_id == AV_CODEC_ID_DNXHD ||
5548 par->codec_id == AV_CODEC_ID_TRUEHD ||
5549 par->codec_id == AV_CODEC_ID_AC3) && !trk->vos_len) {
5550 /* copy frame to create needed atoms */
5551 trk->vos_len = size;
5552 trk->vos_data = av_malloc(size + AV_INPUT_BUFFER_PADDING_SIZE);
5553 if (!trk->vos_data) {
5554 ret = AVERROR(ENOMEM);
5557 memcpy(trk->vos_data, pkt->data, size);
5558 memset(trk->vos_data + size, 0, AV_INPUT_BUFFER_PADDING_SIZE);
5561 if (trk->entry >= trk->cluster_capacity) {
5562 unsigned new_capacity = 2 * (trk->entry + MOV_INDEX_CLUSTER_SIZE);
5563 if (av_reallocp_array(&trk->cluster, new_capacity,
5564 sizeof(*trk->cluster))) {
5565 ret = AVERROR(ENOMEM);
5568 trk->cluster_capacity = new_capacity;
5571 trk->cluster[trk->entry].pos = avio_tell(pb) - size;
5572 trk->cluster[trk->entry].samples_in_chunk = samples_in_chunk;
5573 trk->cluster[trk->entry].chunkNum = 0;
5574 trk->cluster[trk->entry].size = size;
5575 trk->cluster[trk->entry].entries = samples_in_chunk;
5576 trk->cluster[trk->entry].dts = pkt->dts;
5577 trk->cluster[trk->entry].pts = pkt->pts;
5578 if (!trk->entry && trk->start_dts != AV_NOPTS_VALUE) {
5579 if (!trk->frag_discont) {
5580 /* First packet of a new fragment. We already wrote the duration
5581 * of the last packet of the previous fragment based on track_duration,
5582 * which might not exactly match our dts. Therefore adjust the dts
5583 * of this packet to be what the previous packets duration implies. */
5584 trk->cluster[trk->entry].dts = trk->start_dts + trk->track_duration;
5585 /* We also may have written the pts and the corresponding duration
5586 * in sidx/tfrf/tfxd tags; make sure the sidx pts and duration match up with
5587 * the next fragment. This means the cts of the first sample must
5588 * be the same in all fragments, unless end_pts was updated by
5589 * the packet causing the fragment to be written. */
5590 if ((mov->flags & FF_MOV_FLAG_DASH &&
5591 !(mov->flags & (FF_MOV_FLAG_GLOBAL_SIDX | FF_MOV_FLAG_SKIP_SIDX))) ||
5592 mov->mode == MODE_ISM)
5593 pkt->pts = pkt->dts + trk->end_pts - trk->cluster[trk->entry].dts;
5595 /* New fragment, but discontinuous from previous fragments.
5596 * Pretend the duration sum of the earlier fragments is
5597 * pkt->dts - trk->start_dts. */
5598 trk->frag_start = pkt->dts - trk->start_dts;
5599 trk->end_pts = AV_NOPTS_VALUE;
5600 trk->frag_discont = 0;
5604 if (!trk->entry && trk->start_dts == AV_NOPTS_VALUE && !mov->use_editlist &&
5605 s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO) {
5606 /* Not using edit lists and shifting the first track to start from zero.
5607 * If the other streams start from a later timestamp, we won't be able
5608 * to signal the difference in starting time without an edit list.
5609 * Thus move the timestamp for this first sample to 0, increasing
5610 * its duration instead. */
5611 trk->cluster[trk->entry].dts = trk->start_dts = 0;
5613 if (trk->start_dts == AV_NOPTS_VALUE) {
5614 trk->start_dts = pkt->dts;
5615 if (trk->frag_discont) {
5616 if (mov->use_editlist) {
5617 /* Pretend the whole stream started at pts=0, with earlier fragments
5618 * already written. If the stream started at pts=0, the duration sum
5619 * of earlier fragments would have been pkt->pts. */
5620 trk->frag_start = pkt->pts;
5621 trk->start_dts = pkt->dts - pkt->pts;
5623 /* Pretend the whole stream started at dts=0, with earlier fragments
5624 * already written, with a duration summing up to pkt->dts. */
5625 trk->frag_start = pkt->dts;
5628 trk->frag_discont = 0;
5629 } else if (pkt->dts && mov->moov_written)
5630 av_log(s, AV_LOG_WARNING,
5631 "Track %d starts with a nonzero dts %"PRId64", while the moov "
5632 "already has been written. Set the delay_moov flag to handle "
5634 pkt->stream_index, pkt->dts);
5636 trk->track_duration = pkt->dts - trk->start_dts + pkt->duration;
5637 trk->last_sample_is_subtitle_end = 0;
5639 if (pkt->pts == AV_NOPTS_VALUE) {
5640 av_log(s, AV_LOG_WARNING, "pts has no value\n");
5641 pkt->pts = pkt->dts;
5643 if (pkt->dts != pkt->pts)
5644 trk->flags |= MOV_TRACK_CTTS;
5645 trk->cluster[trk->entry].cts = pkt->pts - pkt->dts;
5646 trk->cluster[trk->entry].flags = 0;
5647 if (trk->start_cts == AV_NOPTS_VALUE)
5648 trk->start_cts = pkt->pts - pkt->dts;
5649 if (trk->end_pts == AV_NOPTS_VALUE)
5650 trk->end_pts = trk->cluster[trk->entry].dts +
5651 trk->cluster[trk->entry].cts + pkt->duration;
5653 trk->end_pts = FFMAX(trk->end_pts, trk->cluster[trk->entry].dts +
5654 trk->cluster[trk->entry].cts +
5657 if (par->codec_id == AV_CODEC_ID_VC1) {
5658 mov_parse_vc1_frame(pkt, trk);
5659 } else if (par->codec_id == AV_CODEC_ID_TRUEHD) {
5660 mov_parse_truehd_frame(pkt, trk);
5661 } else if (pkt->flags & AV_PKT_FLAG_KEY) {
5662 if (mov->mode == MODE_MOV && par->codec_id == AV_CODEC_ID_MPEG2VIDEO &&
5663 trk->entry > 0) { // force sync sample for the first key frame
5664 mov_parse_mpeg2_frame(pkt, &trk->cluster[trk->entry].flags);
5665 if (trk->cluster[trk->entry].flags & MOV_PARTIAL_SYNC_SAMPLE)
5666 trk->flags |= MOV_TRACK_STPS;
5668 trk->cluster[trk->entry].flags = MOV_SYNC_SAMPLE;
5670 if (trk->cluster[trk->entry].flags & MOV_SYNC_SAMPLE)
5671 trk->has_keyframes++;
5673 if (pkt->flags & AV_PKT_FLAG_DISPOSABLE) {
5674 trk->cluster[trk->entry].flags |= MOV_DISPOSABLE_SAMPLE;
5675 trk->has_disposable++;
5678 prft = (AVProducerReferenceTime *)av_packet_get_side_data(pkt, AV_PKT_DATA_PRFT, &prft_size);
5679 if (prft && prft_size == sizeof(AVProducerReferenceTime))
5680 memcpy(&trk->cluster[trk->entry].prft, prft, prft_size);
5682 memset(&trk->cluster[trk->entry].prft, 0, sizeof(AVProducerReferenceTime));
5685 trk->sample_count += samples_in_chunk;
5686 mov->mdat_size += size;
5688 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams)
5689 ff_mov_add_hinted_packet(s, pkt, trk->hint_track, trk->entry,
5690 reformatted_data ? reformatted_data + offset
5696 if (pkt->data != reformatted_data)
5697 av_free(reformatted_data);
5701 static int mov_write_single_packet(AVFormatContext *s, AVPacket *pkt)
5703 MOVMuxContext *mov = s->priv_data;
5704 MOVTrack *trk = &mov->tracks[pkt->stream_index];
5705 AVCodecParameters *par = trk->par;
5706 int64_t frag_duration = 0;
5707 int size = pkt->size;
5709 int ret = check_pkt(s, pkt);
5713 if (mov->flags & FF_MOV_FLAG_FRAG_DISCONT) {
5715 for (i = 0; i < s->nb_streams; i++)
5716 mov->tracks[i].frag_discont = 1;
5717 mov->flags &= ~FF_MOV_FLAG_FRAG_DISCONT;
5720 if (mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS) {
5721 if (trk->dts_shift == AV_NOPTS_VALUE)
5722 trk->dts_shift = pkt->pts - pkt->dts;
5723 pkt->dts += trk->dts_shift;
5726 if (trk->par->codec_id == AV_CODEC_ID_MP4ALS ||
5727 trk->par->codec_id == AV_CODEC_ID_AAC ||
5728 trk->par->codec_id == AV_CODEC_ID_AV1 ||
5729 trk->par->codec_id == AV_CODEC_ID_FLAC) {
5731 uint8_t *side = av_packet_get_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA, &side_size);
5732 if (side && side_size > 0 && (side_size != par->extradata_size || memcmp(side, par->extradata, side_size))) {
5733 void *newextra = av_mallocz(side_size + AV_INPUT_BUFFER_PADDING_SIZE);
5735 return AVERROR(ENOMEM);
5736 av_free(par->extradata);
5737 par->extradata = newextra;
5738 memcpy(par->extradata, side, side_size);
5739 par->extradata_size = side_size;
5740 if (!pkt->size) // Flush packet
5741 mov->need_rewrite_extradata = 1;
5746 if (trk->start_dts == AV_NOPTS_VALUE && trk->frag_discont) {
5747 trk->start_dts = pkt->dts;
5748 if (pkt->pts != AV_NOPTS_VALUE)
5749 trk->start_cts = pkt->pts - pkt->dts;
5754 return 0; /* Discard 0 sized packets */
5757 if (trk->entry && pkt->stream_index < s->nb_streams)
5758 frag_duration = av_rescale_q(pkt->dts - trk->cluster[0].dts,
5759 s->streams[pkt->stream_index]->time_base,
5761 if ((mov->max_fragment_duration &&
5762 frag_duration >= mov->max_fragment_duration) ||
5763 (mov->max_fragment_size && mov->mdat_size + size >= mov->max_fragment_size) ||
5764 (mov->flags & FF_MOV_FLAG_FRAG_KEYFRAME &&
5765 par->codec_type == AVMEDIA_TYPE_VIDEO &&
5766 trk->entry && pkt->flags & AV_PKT_FLAG_KEY) ||
5767 (mov->flags & FF_MOV_FLAG_FRAG_EVERY_FRAME)) {
5768 if (frag_duration >= mov->min_fragment_duration) {
5769 // Set the duration of this track to line up with the next
5770 // sample in this track. This avoids relying on AVPacket
5771 // duration, but only helps for this particular track, not
5772 // for the other ones that are flushed at the same time.
5773 trk->track_duration = pkt->dts - trk->start_dts;
5774 if (pkt->pts != AV_NOPTS_VALUE)
5775 trk->end_pts = pkt->pts;
5777 trk->end_pts = pkt->dts;
5778 trk->end_reliable = 1;
5779 mov_auto_flush_fragment(s, 0);
5783 return ff_mov_write_packet(s, pkt);
5786 static int mov_write_subtitle_end_packet(AVFormatContext *s,
5790 uint8_t data[2] = {0};
5793 av_init_packet(&end);
5794 end.size = sizeof(data);
5799 end.stream_index = stream_index;
5801 ret = mov_write_single_packet(s, &end);
5802 av_packet_unref(&end);
5807 static int mov_write_packet(AVFormatContext *s, AVPacket *pkt)
5809 MOVMuxContext *mov = s->priv_data;
5813 mov_flush_fragment(s, 1);
5817 trk = &mov->tracks[pkt->stream_index];
5819 if (is_cover_image(trk->st)) {
5822 if (trk->st->nb_frames >= 1) {
5823 if (trk->st->nb_frames == 1)
5824 av_log(s, AV_LOG_WARNING, "Got more than one picture in stream %d,"
5825 " ignoring.\n", pkt->stream_index);
5829 if ((ret = av_packet_ref(&trk->cover_image, pkt)) < 0)
5837 return mov_write_single_packet(s, pkt); /* Passthrough. */
5840 * Subtitles require special handling.
5842 * 1) For full complaince, every track must have a sample at
5843 * dts == 0, which is rarely true for subtitles. So, as soon
5844 * as we see any packet with dts > 0, write an empty subtitle
5845 * at dts == 0 for any subtitle track with no samples in it.
5847 * 2) For each subtitle track, check if the current packet's
5848 * dts is past the duration of the last subtitle sample. If
5849 * so, we now need to write an end sample for that subtitle.
5851 * This must be done conditionally to allow for subtitles that
5852 * immediately replace each other, in which case an end sample
5853 * is not needed, and is, in fact, actively harmful.
5855 * 3) See mov_write_trailer for how the final end sample is
5858 for (i = 0; i < mov->nb_streams; i++) {
5859 MOVTrack *trk = &mov->tracks[i];
5862 if (trk->par->codec_id == AV_CODEC_ID_MOV_TEXT &&
5863 trk->track_duration < pkt->dts &&
5864 (trk->entry == 0 || !trk->last_sample_is_subtitle_end)) {
5865 ret = mov_write_subtitle_end_packet(s, i, trk->track_duration);
5866 if (ret < 0) return ret;
5867 trk->last_sample_is_subtitle_end = 1;
5871 if (trk->mode == MODE_MOV && trk->par->codec_type == AVMEDIA_TYPE_VIDEO) {
5872 AVPacket *opkt = pkt;
5873 int reshuffle_ret, ret;
5874 if (trk->is_unaligned_qt_rgb) {
5875 int64_t bpc = trk->par->bits_per_coded_sample != 15 ? trk->par->bits_per_coded_sample : 16;
5876 int expected_stride = ((trk->par->width * bpc + 15) >> 4)*2;
5877 reshuffle_ret = ff_reshuffle_raw_rgb(s, &pkt, trk->par, expected_stride);
5878 if (reshuffle_ret < 0)
5879 return reshuffle_ret;
5882 if (trk->par->format == AV_PIX_FMT_PAL8 && !trk->pal_done) {
5883 ret = ff_get_packet_palette(s, opkt, reshuffle_ret, trk->palette);
5888 } else if (trk->par->codec_id == AV_CODEC_ID_RAWVIDEO &&
5889 (trk->par->format == AV_PIX_FMT_GRAY8 ||
5890 trk->par->format == AV_PIX_FMT_MONOBLACK)) {
5891 for (i = 0; i < pkt->size; i++)
5892 pkt->data[i] = ~pkt->data[i];
5894 if (reshuffle_ret) {
5895 ret = mov_write_single_packet(s, pkt);
5898 av_packet_free(&pkt);
5903 return mov_write_single_packet(s, pkt);
5907 // QuickTime chapters involve an additional text track with the chapter names
5908 // as samples, and a tref pointing from the other tracks to the chapter one.
5909 static int mov_create_chapter_track(AVFormatContext *s, int tracknum)
5913 MOVMuxContext *mov = s->priv_data;
5914 MOVTrack *track = &mov->tracks[tracknum];
5915 AVPacket pkt = { .stream_index = tracknum, .flags = AV_PKT_FLAG_KEY };
5918 track->mode = mov->mode;
5919 track->tag = MKTAG('t','e','x','t');
5920 track->timescale = MOV_TIMESCALE;
5921 track->par = avcodec_parameters_alloc();
5923 return AVERROR(ENOMEM);
5924 track->par->codec_type = AVMEDIA_TYPE_SUBTITLE;
5926 // These properties are required to make QT recognize the chapter track
5927 uint8_t chapter_properties[43] = { 0, 0, 0, 0, 0, 0, 0, 1, };
5928 if (ff_alloc_extradata(track->par, sizeof(chapter_properties)))
5929 return AVERROR(ENOMEM);
5930 memcpy(track->par->extradata, chapter_properties, sizeof(chapter_properties));
5932 if (avio_open_dyn_buf(&pb) >= 0) {
5936 /* Stub header (usually for Quicktime chapter track) */
5938 avio_wb32(pb, 0x01); // displayFlags
5939 avio_w8(pb, 0x00); // horizontal justification
5940 avio_w8(pb, 0x00); // vertical justification
5941 avio_w8(pb, 0x00); // bgColourRed
5942 avio_w8(pb, 0x00); // bgColourGreen
5943 avio_w8(pb, 0x00); // bgColourBlue
5944 avio_w8(pb, 0x00); // bgColourAlpha
5946 avio_wb16(pb, 0x00); // defTextBoxTop
5947 avio_wb16(pb, 0x00); // defTextBoxLeft
5948 avio_wb16(pb, 0x00); // defTextBoxBottom
5949 avio_wb16(pb, 0x00); // defTextBoxRight
5951 avio_wb16(pb, 0x00); // startChar
5952 avio_wb16(pb, 0x00); // endChar
5953 avio_wb16(pb, 0x01); // fontID
5954 avio_w8(pb, 0x00); // fontStyleFlags
5955 avio_w8(pb, 0x00); // fontSize
5956 avio_w8(pb, 0x00); // fgColourRed
5957 avio_w8(pb, 0x00); // fgColourGreen
5958 avio_w8(pb, 0x00); // fgColourBlue
5959 avio_w8(pb, 0x00); // fgColourAlpha
5961 avio_wb32(pb, 0x0D); // box size
5962 ffio_wfourcc(pb, "ftab"); // box atom name
5963 avio_wb16(pb, 0x01); // entry count
5965 avio_wb16(pb, 0x01); // font ID
5966 avio_w8(pb, 0x00); // font name length
5968 if ((size = avio_close_dyn_buf(pb, &buf)) > 0) {
5969 track->par->extradata = buf;
5970 track->par->extradata_size = size;
5977 for (i = 0; i < s->nb_chapters; i++) {
5978 AVChapter *c = s->chapters[i];
5979 AVDictionaryEntry *t;
5981 int64_t end = av_rescale_q(c->end, c->time_base, (AVRational){1,MOV_TIMESCALE});
5982 pkt.pts = pkt.dts = av_rescale_q(c->start, c->time_base, (AVRational){1,MOV_TIMESCALE});
5983 pkt.duration = end - pkt.dts;
5985 if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
5986 static const char encd[12] = {
5987 0x00, 0x00, 0x00, 0x0C,
5989 0x00, 0x00, 0x01, 0x00 };
5990 len = strlen(t->value);
5991 pkt.size = len + 2 + 12;
5992 pkt.data = av_malloc(pkt.size);
5994 return AVERROR(ENOMEM);
5995 AV_WB16(pkt.data, len);
5996 memcpy(pkt.data + 2, t->value, len);
5997 memcpy(pkt.data + len + 2, encd, sizeof(encd));
5998 ff_mov_write_packet(s, &pkt);
5999 av_freep(&pkt.data);
6007 static int mov_check_timecode_track(AVFormatContext *s, AVTimecode *tc, int src_index, const char *tcstr)
6011 /* compute the frame number */
6012 ret = av_timecode_init_from_string(tc, find_fps(s, s->streams[src_index]), tcstr, s);
6016 static int mov_create_timecode_track(AVFormatContext *s, int index, int src_index, AVTimecode tc)
6019 MOVMuxContext *mov = s->priv_data;
6020 MOVTrack *track = &mov->tracks[index];
6021 AVStream *src_st = s->streams[src_index];
6022 AVPacket pkt = {.stream_index = index, .flags = AV_PKT_FLAG_KEY, .size = 4};
6023 AVRational rate = find_fps(s, src_st);
6025 /* tmcd track based on video stream */
6026 track->mode = mov->mode;
6027 track->tag = MKTAG('t','m','c','d');
6028 track->src_track = src_index;
6029 track->timescale = mov->tracks[src_index].timescale;
6030 if (tc.flags & AV_TIMECODE_FLAG_DROPFRAME)
6031 track->timecode_flags |= MOV_TIMECODE_FLAG_DROPFRAME;
6033 /* set st to src_st for metadata access*/
6036 /* encode context: tmcd data stream */
6037 track->par = avcodec_parameters_alloc();
6039 return AVERROR(ENOMEM);
6040 track->par->codec_type = AVMEDIA_TYPE_DATA;
6041 track->par->codec_tag = track->tag;
6042 track->st->avg_frame_rate = av_inv_q(rate);
6044 /* the tmcd track just contains one packet with the frame number */
6045 pkt.data = av_malloc(pkt.size);
6047 return AVERROR(ENOMEM);
6048 AV_WB32(pkt.data, tc.start);
6049 ret = ff_mov_write_packet(s, &pkt);
6055 * st->disposition controls the "enabled" flag in the tkhd tag.
6056 * QuickTime will not play a track if it is not enabled. So make sure
6057 * that one track of each type (audio, video, subtitle) is enabled.
6059 * Subtitles are special. For audio and video, setting "enabled" also
6060 * makes the track "default" (i.e. it is rendered when played). For
6061 * subtitles, an "enabled" subtitle is not rendered by default, but
6062 * if no subtitle is enabled, the subtitle menu in QuickTime will be
6065 static void enable_tracks(AVFormatContext *s)
6067 MOVMuxContext *mov = s->priv_data;
6069 int enabled[AVMEDIA_TYPE_NB];
6070 int first[AVMEDIA_TYPE_NB];
6072 for (i = 0; i < AVMEDIA_TYPE_NB; i++) {
6077 for (i = 0; i < s->nb_streams; i++) {
6078 AVStream *st = s->streams[i];
6080 if (st->codecpar->codec_type <= AVMEDIA_TYPE_UNKNOWN ||
6081 st->codecpar->codec_type >= AVMEDIA_TYPE_NB ||
6085 if (first[st->codecpar->codec_type] < 0)
6086 first[st->codecpar->codec_type] = i;
6087 if (st->disposition & AV_DISPOSITION_DEFAULT) {
6088 mov->tracks[i].flags |= MOV_TRACK_ENABLED;
6089 enabled[st->codecpar->codec_type]++;
6093 for (i = 0; i < AVMEDIA_TYPE_NB; i++) {
6095 case AVMEDIA_TYPE_VIDEO:
6096 case AVMEDIA_TYPE_AUDIO:
6097 case AVMEDIA_TYPE_SUBTITLE:
6099 mov->per_stream_grouping = 1;
6100 if (!enabled[i] && first[i] >= 0)
6101 mov->tracks[first[i]].flags |= MOV_TRACK_ENABLED;
6107 static void mov_free(AVFormatContext *s)
6109 MOVMuxContext *mov = s->priv_data;
6112 if (mov->chapter_track) {
6113 if (mov->tracks[mov->chapter_track].par)
6114 av_freep(&mov->tracks[mov->chapter_track].par->extradata);
6115 av_freep(&mov->tracks[mov->chapter_track].par);
6118 for (i = 0; i < mov->nb_streams; i++) {
6119 if (mov->tracks[i].tag == MKTAG('r','t','p',' '))
6120 ff_mov_close_hinting(&mov->tracks[i]);
6121 else if (mov->tracks[i].tag == MKTAG('t','m','c','d') && mov->nb_meta_tmcd)
6122 av_freep(&mov->tracks[i].par);
6123 av_freep(&mov->tracks[i].cluster);
6124 av_freep(&mov->tracks[i].frag_info);
6125 av_packet_unref(&mov->tracks[i].cover_image);
6127 if (mov->tracks[i].eac3_priv) {
6128 struct eac3_info *info = mov->tracks[i].eac3_priv;
6129 av_packet_unref(&info->pkt);
6130 av_freep(&mov->tracks[i].eac3_priv);
6132 if (mov->tracks[i].vos_len)
6133 av_freep(&mov->tracks[i].vos_data);
6135 ff_mov_cenc_free(&mov->tracks[i].cenc);
6138 av_freep(&mov->tracks);
6141 static uint32_t rgb_to_yuv(uint32_t rgb)
6146 r = (rgb >> 16) & 0xFF;
6147 g = (rgb >> 8) & 0xFF;
6150 y = av_clip_uint8(( 16000 + 257 * r + 504 * g + 98 * b)/1000);
6151 cb = av_clip_uint8((128000 - 148 * r - 291 * g + 439 * b)/1000);
6152 cr = av_clip_uint8((128000 + 439 * r - 368 * g - 71 * b)/1000);
6154 return (y << 16) | (cr << 8) | cb;
6157 static int mov_create_dvd_sub_decoder_specific_info(MOVTrack *track,
6160 int i, width = 720, height = 480;
6161 int have_palette = 0, have_size = 0;
6162 uint32_t palette[16];
6163 char *cur = st->codecpar->extradata;
6165 while (cur && *cur) {
6166 if (strncmp("palette:", cur, 8) == 0) {
6168 count = sscanf(cur + 8,
6169 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
6170 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
6171 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
6172 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32"",
6173 &palette[ 0], &palette[ 1], &palette[ 2], &palette[ 3],
6174 &palette[ 4], &palette[ 5], &palette[ 6], &palette[ 7],
6175 &palette[ 8], &palette[ 9], &palette[10], &palette[11],
6176 &palette[12], &palette[13], &palette[14], &palette[15]);
6178 for (i = 0; i < count; i++) {
6179 palette[i] = rgb_to_yuv(palette[i]);
6182 } else if (!strncmp("size:", cur, 5)) {
6183 sscanf(cur + 5, "%dx%d", &width, &height);
6186 if (have_palette && have_size)
6188 cur += strcspn(cur, "\n\r");
6189 cur += strspn(cur, "\n\r");
6192 track->vos_data = av_malloc(16*4 + AV_INPUT_BUFFER_PADDING_SIZE);
6193 if (!track->vos_data)
6194 return AVERROR(ENOMEM);
6195 for (i = 0; i < 16; i++) {
6196 AV_WB32(track->vos_data + i * 4, palette[i]);
6198 memset(track->vos_data + 16*4, 0, AV_INPUT_BUFFER_PADDING_SIZE);
6199 track->vos_len = 16 * 4;
6201 st->codecpar->width = width;
6202 st->codecpar->height = track->height = height;
6207 static int mov_init(AVFormatContext *s)
6209 MOVMuxContext *mov = s->priv_data;
6210 AVDictionaryEntry *global_tcr = av_dict_get(s->metadata, "timecode", NULL, 0);
6215 /* Default mode == MP4 */
6216 mov->mode = MODE_MP4;
6219 if (!strcmp("3gp", s->oformat->name)) mov->mode = MODE_3GP;
6220 else if (!strcmp("3g2", s->oformat->name)) mov->mode = MODE_3GP|MODE_3G2;
6221 else if (!strcmp("mov", s->oformat->name)) mov->mode = MODE_MOV;
6222 else if (!strcmp("psp", s->oformat->name)) mov->mode = MODE_PSP;
6223 else if (!strcmp("ipod",s->oformat->name)) mov->mode = MODE_IPOD;
6224 else if (!strcmp("ismv",s->oformat->name)) mov->mode = MODE_ISM;
6225 else if (!strcmp("f4v", s->oformat->name)) mov->mode = MODE_F4V;
6228 if (mov->flags & FF_MOV_FLAG_DELAY_MOOV)
6229 mov->flags |= FF_MOV_FLAG_EMPTY_MOOV;
6231 /* Set the FRAGMENT flag if any of the fragmentation methods are
6233 if (mov->max_fragment_duration || mov->max_fragment_size ||
6234 mov->flags & (FF_MOV_FLAG_EMPTY_MOOV |
6235 FF_MOV_FLAG_FRAG_KEYFRAME |
6236 FF_MOV_FLAG_FRAG_CUSTOM |
6237 FF_MOV_FLAG_FRAG_EVERY_FRAME))
6238 mov->flags |= FF_MOV_FLAG_FRAGMENT;
6240 /* Set other implicit flags immediately */
6241 if (mov->mode == MODE_ISM)
6242 mov->flags |= FF_MOV_FLAG_EMPTY_MOOV | FF_MOV_FLAG_SEPARATE_MOOF |
6243 FF_MOV_FLAG_FRAGMENT | FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS;
6244 if (mov->flags & FF_MOV_FLAG_DASH)
6245 mov->flags |= FF_MOV_FLAG_FRAGMENT | FF_MOV_FLAG_EMPTY_MOOV |
6246 FF_MOV_FLAG_DEFAULT_BASE_MOOF;
6247 if (mov->flags & FF_MOV_FLAG_CMAF)
6248 mov->flags |= FF_MOV_FLAG_FRAGMENT | FF_MOV_FLAG_EMPTY_MOOV |
6249 FF_MOV_FLAG_DEFAULT_BASE_MOOF | FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS;
6251 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV && s->flags & AVFMT_FLAG_AUTO_BSF) {
6252 av_log(s, AV_LOG_VERBOSE, "Empty MOOV enabled; disabling automatic bitstream filtering\n");
6253 s->flags &= ~AVFMT_FLAG_AUTO_BSF;
6256 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX && mov->flags & FF_MOV_FLAG_SKIP_SIDX) {
6257 av_log(s, AV_LOG_WARNING, "Global SIDX enabled; Ignoring skip_sidx option\n");
6258 mov->flags &= ~FF_MOV_FLAG_SKIP_SIDX;
6261 if (mov->flags & FF_MOV_FLAG_FASTSTART) {
6262 mov->reserved_moov_size = -1;
6265 if (mov->use_editlist < 0) {
6266 mov->use_editlist = 1;
6267 if (mov->flags & FF_MOV_FLAG_FRAGMENT &&
6268 !(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
6269 // If we can avoid needing an edit list by shifting the
6270 // tracks, prefer that over (trying to) write edit lists
6271 // in fragmented output.
6272 if (s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO ||
6273 s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO)
6274 mov->use_editlist = 0;
6276 if (mov->flags & FF_MOV_FLAG_CMAF) {
6277 // CMAF Track requires negative cts offsets without edit lists
6278 mov->use_editlist = 0;
6281 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV &&
6282 !(mov->flags & FF_MOV_FLAG_DELAY_MOOV) && mov->use_editlist)
6283 av_log(s, AV_LOG_WARNING, "No meaningful edit list will be written when using empty_moov without delay_moov\n");
6285 if (mov->flags & FF_MOV_FLAG_CMAF && mov->use_editlist) {
6286 av_log(s, AV_LOG_WARNING, "Edit list enabled; Assuming writing CMAF Track File\n");
6287 mov->flags &= ~FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS;
6289 if (!mov->use_editlist && s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO &&
6290 !(mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS))
6291 s->avoid_negative_ts = AVFMT_AVOID_NEG_TS_MAKE_ZERO;
6293 /* Clear the omit_tfhd_offset flag if default_base_moof is set;
6294 * if the latter is set that's enough and omit_tfhd_offset doesn't
6295 * add anything extra on top of that. */
6296 if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET &&
6297 mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)
6298 mov->flags &= ~FF_MOV_FLAG_OMIT_TFHD_OFFSET;
6300 if (mov->frag_interleave &&
6301 mov->flags & (FF_MOV_FLAG_OMIT_TFHD_OFFSET | FF_MOV_FLAG_SEPARATE_MOOF)) {
6302 av_log(s, AV_LOG_ERROR,
6303 "Sample interleaving in fragments is mutually exclusive with "
6304 "omit_tfhd_offset and separate_moof\n");
6305 return AVERROR(EINVAL);
6308 /* Non-seekable output is ok if using fragmentation. If ism_lookahead
6309 * is enabled, we don't support non-seekable output at all. */
6310 if (!(s->pb->seekable & AVIO_SEEKABLE_NORMAL) &&
6311 (!(mov->flags & FF_MOV_FLAG_FRAGMENT) || mov->ism_lookahead)) {
6312 av_log(s, AV_LOG_ERROR, "muxer does not support non seekable output\n");
6313 return AVERROR(EINVAL);
6316 mov->nb_streams = s->nb_streams;
6317 if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters)
6318 mov->chapter_track = mov->nb_streams++;
6320 if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
6321 for (i = 0; i < s->nb_streams; i++)
6322 if (rtp_hinting_needed(s->streams[i]))
6326 if ( mov->write_tmcd == -1 && (mov->mode == MODE_MOV || mov->mode == MODE_MP4)
6327 || mov->write_tmcd == 1) {
6328 /* +1 tmcd track for each video stream with a timecode */
6329 for (i = 0; i < s->nb_streams; i++) {
6330 AVStream *st = s->streams[i];
6331 AVDictionaryEntry *t = global_tcr;
6332 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
6333 (t || (t=av_dict_get(st->metadata, "timecode", NULL, 0)))) {
6335 ret = mov_check_timecode_track(s, &tc, i, t->value);
6337 mov->nb_meta_tmcd++;
6341 /* check if there is already a tmcd track to remux */
6342 if (mov->nb_meta_tmcd) {
6343 for (i = 0; i < s->nb_streams; i++) {
6344 AVStream *st = s->streams[i];
6345 if (st->codecpar->codec_tag == MKTAG('t','m','c','d')) {
6346 av_log(s, AV_LOG_WARNING, "You requested a copy of the original timecode track "
6347 "so timecode metadata are now ignored\n");
6348 mov->nb_meta_tmcd = 0;
6353 mov->nb_streams += mov->nb_meta_tmcd;
6356 // Reserve an extra stream for chapters for the case where chapters
6357 // are written in the trailer
6358 mov->tracks = av_mallocz_array((mov->nb_streams + 1), sizeof(*mov->tracks));
6360 return AVERROR(ENOMEM);
6362 if (mov->encryption_scheme_str != NULL && strcmp(mov->encryption_scheme_str, "none") != 0) {
6363 if (strcmp(mov->encryption_scheme_str, "cenc-aes-ctr") == 0) {
6364 mov->encryption_scheme = MOV_ENC_CENC_AES_CTR;
6366 if (mov->encryption_key_len != AES_CTR_KEY_SIZE) {
6367 av_log(s, AV_LOG_ERROR, "Invalid encryption key len %d expected %d\n",
6368 mov->encryption_key_len, AES_CTR_KEY_SIZE);
6369 return AVERROR(EINVAL);
6372 if (mov->encryption_kid_len != CENC_KID_SIZE) {
6373 av_log(s, AV_LOG_ERROR, "Invalid encryption kid len %d expected %d\n",
6374 mov->encryption_kid_len, CENC_KID_SIZE);
6375 return AVERROR(EINVAL);
6378 av_log(s, AV_LOG_ERROR, "unsupported encryption scheme %s\n",
6379 mov->encryption_scheme_str);
6380 return AVERROR(EINVAL);
6384 for (i = 0; i < s->nb_streams; i++) {
6385 AVStream *st= s->streams[i];
6386 MOVTrack *track= &mov->tracks[i];
6387 AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0);
6390 track->par = st->codecpar;
6391 track->language = ff_mov_iso639_to_lang(lang?lang->value:"und", mov->mode!=MODE_MOV);
6392 if (track->language < 0)
6393 track->language = 32767; // Unspecified Macintosh language code
6394 track->mode = mov->mode;
6395 track->tag = mov_find_codec_tag(s, track);
6397 av_log(s, AV_LOG_ERROR, "Could not find tag for codec %s in stream #%d, "
6398 "codec not currently supported in container\n",
6399 avcodec_get_name(st->codecpar->codec_id), i);
6400 return AVERROR(EINVAL);
6402 /* If hinting of this track is enabled by a later hint track,
6403 * this is updated. */
6404 track->hint_track = -1;
6405 track->start_dts = AV_NOPTS_VALUE;
6406 track->start_cts = AV_NOPTS_VALUE;
6407 track->end_pts = AV_NOPTS_VALUE;
6408 track->dts_shift = AV_NOPTS_VALUE;
6409 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
6410 if (track->tag == MKTAG('m','x','3','p') || track->tag == MKTAG('m','x','3','n') ||
6411 track->tag == MKTAG('m','x','4','p') || track->tag == MKTAG('m','x','4','n') ||
6412 track->tag == MKTAG('m','x','5','p') || track->tag == MKTAG('m','x','5','n')) {
6413 if (st->codecpar->width != 720 || (st->codecpar->height != 608 && st->codecpar->height != 512)) {
6414 av_log(s, AV_LOG_ERROR, "D-10/IMX must use 720x608 or 720x512 video resolution\n");
6415 return AVERROR(EINVAL);
6417 track->height = track->tag >> 24 == 'n' ? 486 : 576;
6419 if (mov->video_track_timescale) {
6420 track->timescale = mov->video_track_timescale;
6421 if (mov->mode == MODE_ISM && mov->video_track_timescale != 10000000)
6422 av_log(s, AV_LOG_WARNING, "Warning: some tools, like mp4split, assume a timescale of 10000000 for ISMV.\n");
6424 track->timescale = st->time_base.den;
6425 while(track->timescale < 10000)
6426 track->timescale *= 2;
6428 if (st->codecpar->width > 65535 || st->codecpar->height > 65535) {
6429 av_log(s, AV_LOG_ERROR, "Resolution %dx%d too large for mov/mp4\n", st->codecpar->width, st->codecpar->height);
6430 return AVERROR(EINVAL);
6432 if (track->mode == MODE_MOV && track->timescale > 100000)
6433 av_log(s, AV_LOG_WARNING,
6434 "WARNING codec timebase is very high. If duration is too long,\n"
6435 "file may not be playable by quicktime. Specify a shorter timebase\n"
6436 "or choose different container.\n");
6437 if (track->mode == MODE_MOV &&
6438 track->par->codec_id == AV_CODEC_ID_RAWVIDEO &&
6439 track->tag == MKTAG('r','a','w',' ')) {
6440 enum AVPixelFormat pix_fmt = track->par->format;
6441 if (pix_fmt == AV_PIX_FMT_NONE && track->par->bits_per_coded_sample == 1)
6442 pix_fmt = AV_PIX_FMT_MONOWHITE;
6443 track->is_unaligned_qt_rgb =
6444 pix_fmt == AV_PIX_FMT_RGB24 ||
6445 pix_fmt == AV_PIX_FMT_BGR24 ||
6446 pix_fmt == AV_PIX_FMT_PAL8 ||
6447 pix_fmt == AV_PIX_FMT_GRAY8 ||
6448 pix_fmt == AV_PIX_FMT_MONOWHITE ||
6449 pix_fmt == AV_PIX_FMT_MONOBLACK;
6451 if (track->par->codec_id == AV_CODEC_ID_VP9 ||
6452 track->par->codec_id == AV_CODEC_ID_AV1) {
6453 if (track->mode != MODE_MP4) {
6454 av_log(s, AV_LOG_ERROR, "%s only supported in MP4.\n", avcodec_get_name(track->par->codec_id));
6455 return AVERROR(EINVAL);
6457 } else if (track->par->codec_id == AV_CODEC_ID_VP8) {
6458 /* altref frames handling is not defined in the spec as of version v1.0,
6459 * so just forbid muxing VP8 streams altogether until a new version does */
6460 av_log(s, AV_LOG_ERROR, "VP8 muxing is currently not supported.\n");
6461 return AVERROR_PATCHWELCOME;
6463 } else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
6464 track->timescale = st->codecpar->sample_rate;
6465 if (!st->codecpar->frame_size && !av_get_bits_per_sample(st->codecpar->codec_id)) {
6466 av_log(s, AV_LOG_WARNING, "track %d: codec frame size is not set\n", i);
6467 track->audio_vbr = 1;
6468 }else if (st->codecpar->codec_id == AV_CODEC_ID_ADPCM_MS ||
6469 st->codecpar->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
6470 st->codecpar->codec_id == AV_CODEC_ID_ILBC){
6471 if (!st->codecpar->block_align) {
6472 av_log(s, AV_LOG_ERROR, "track %d: codec block align is not set for adpcm\n", i);
6473 return AVERROR(EINVAL);
6475 track->sample_size = st->codecpar->block_align;
6476 }else if (st->codecpar->frame_size > 1){ /* assume compressed audio */
6477 track->audio_vbr = 1;
6479 track->sample_size = (av_get_bits_per_sample(st->codecpar->codec_id) >> 3) * st->codecpar->channels;
6481 if (st->codecpar->codec_id == AV_CODEC_ID_ILBC ||
6482 st->codecpar->codec_id == AV_CODEC_ID_ADPCM_IMA_QT) {
6483 track->audio_vbr = 1;
6485 if (track->mode != MODE_MOV &&
6486 track->par->codec_id == AV_CODEC_ID_MP3 && track->timescale < 16000) {
6487 if (s->strict_std_compliance >= FF_COMPLIANCE_NORMAL) {
6488 av_log(s, AV_LOG_ERROR, "track %d: muxing mp3 at %dhz is not standard, to mux anyway set strict to -1\n",
6489 i, track->par->sample_rate);
6490 return AVERROR(EINVAL);
6492 av_log(s, AV_LOG_WARNING, "track %d: muxing mp3 at %dhz is not standard in MP4\n",
6493 i, track->par->sample_rate);
6496 if (track->par->codec_id == AV_CODEC_ID_FLAC ||
6497 track->par->codec_id == AV_CODEC_ID_TRUEHD ||
6498 track->par->codec_id == AV_CODEC_ID_OPUS) {
6499 if (track->mode != MODE_MP4) {
6500 av_log(s, AV_LOG_ERROR, "%s only supported in MP4.\n", avcodec_get_name(track->par->codec_id));
6501 return AVERROR(EINVAL);
6503 if (s->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
6504 av_log(s, AV_LOG_ERROR,
6505 "%s in MP4 support is experimental, add "
6506 "'-strict %d' if you want to use it.\n",
6507 avcodec_get_name(track->par->codec_id), FF_COMPLIANCE_EXPERIMENTAL);
6508 return AVERROR_EXPERIMENTAL;
6511 } else if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) {
6512 track->timescale = st->time_base.den;
6513 } else if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA) {
6514 track->timescale = st->time_base.den;
6516 track->timescale = MOV_TIMESCALE;
6519 track->height = st->codecpar->height;
6520 /* The Protected Interoperable File Format (PIFF) standard, used by ISMV recommends but
6521 doesn't mandate a track timescale of 10,000,000. The muxer allows a custom timescale
6522 for video tracks, so if user-set, it isn't overwritten */
6523 if (mov->mode == MODE_ISM &&
6524 (st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO ||
6525 (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && !mov->video_track_timescale))) {
6526 track->timescale = 10000000;
6529 avpriv_set_pts_info(st, 64, 1, track->timescale);
6531 if (mov->encryption_scheme == MOV_ENC_CENC_AES_CTR) {
6532 ret = ff_mov_cenc_init(&track->cenc, mov->encryption_key,
6533 track->par->codec_id == AV_CODEC_ID_H264, s->flags & AVFMT_FLAG_BITEXACT);
6543 static int mov_write_header(AVFormatContext *s)
6545 AVIOContext *pb = s->pb;
6546 MOVMuxContext *mov = s->priv_data;
6547 AVDictionaryEntry *t, *global_tcr = av_dict_get(s->metadata, "timecode", NULL, 0);
6548 int i, ret, hint_track = 0, tmcd_track = 0, nb_tracks = s->nb_streams;
6550 if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters)
6553 if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
6554 hint_track = nb_tracks;
6555 for (i = 0; i < s->nb_streams; i++)
6556 if (rtp_hinting_needed(s->streams[i]))
6560 if (mov->nb_meta_tmcd)
6561 tmcd_track = nb_tracks;
6563 for (i = 0; i < s->nb_streams; i++) {
6565 AVStream *st= s->streams[i];
6566 MOVTrack *track= &mov->tracks[i];
6568 /* copy extradata if it exists */
6569 if (st->codecpar->extradata_size) {
6570 if (st->codecpar->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
6571 mov_create_dvd_sub_decoder_specific_info(track, st);
6572 else if (!TAG_IS_AVCI(track->tag) && st->codecpar->codec_id != AV_CODEC_ID_DNXHD) {
6573 track->vos_len = st->codecpar->extradata_size;
6574 track->vos_data = av_malloc(track->vos_len + AV_INPUT_BUFFER_PADDING_SIZE);
6575 if (!track->vos_data) {
6576 return AVERROR(ENOMEM);
6578 memcpy(track->vos_data, st->codecpar->extradata, track->vos_len);
6579 memset(track->vos_data + track->vos_len, 0, AV_INPUT_BUFFER_PADDING_SIZE);
6583 if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ||
6584 track->par->channel_layout != AV_CH_LAYOUT_MONO)
6587 for (j = 0; j < s->nb_streams; j++) {
6588 AVStream *stj= s->streams[j];
6589 MOVTrack *trackj= &mov->tracks[j];
6593 if (stj->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ||
6594 trackj->par->channel_layout != AV_CH_LAYOUT_MONO ||
6595 trackj->language != track->language ||
6596 trackj->tag != track->tag
6599 track->multichannel_as_mono++;
6603 if (!(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
6604 if ((ret = mov_write_identification(pb, s)) < 0)
6608 if (mov->reserved_moov_size){
6609 mov->reserved_header_pos = avio_tell(pb);
6610 if (mov->reserved_moov_size > 0)
6611 avio_skip(pb, mov->reserved_moov_size);
6614 if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
6615 /* If no fragmentation options have been set, set a default. */
6616 if (!(mov->flags & (FF_MOV_FLAG_FRAG_KEYFRAME |
6617 FF_MOV_FLAG_FRAG_CUSTOM |
6618 FF_MOV_FLAG_FRAG_EVERY_FRAME)) &&
6619 !mov->max_fragment_duration && !mov->max_fragment_size)
6620 mov->flags |= FF_MOV_FLAG_FRAG_KEYFRAME;
6622 if (mov->flags & FF_MOV_FLAG_FASTSTART)
6623 mov->reserved_header_pos = avio_tell(pb);
6624 mov_write_mdat_tag(pb, mov);
6627 ff_parse_creation_time_metadata(s, &mov->time, 1);
6629 mov->time += 0x7C25B080; // 1970 based -> 1904 based
6631 if (mov->chapter_track)
6632 if ((ret = mov_create_chapter_track(s, mov->chapter_track)) < 0)
6635 if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
6636 for (i = 0; i < s->nb_streams; i++) {
6637 if (rtp_hinting_needed(s->streams[i])) {
6638 if ((ret = ff_mov_init_hinting(s, hint_track, i)) < 0)
6645 if (mov->nb_meta_tmcd) {
6646 /* Initialize the tmcd tracks */
6647 for (i = 0; i < s->nb_streams; i++) {
6648 AVStream *st = s->streams[i];
6651 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
6654 t = av_dict_get(st->metadata, "timecode", NULL, 0);
6657 if (mov_check_timecode_track(s, &tc, i, t->value) < 0)
6659 if ((ret = mov_create_timecode_track(s, tmcd_track, i, tc)) < 0)
6668 if (mov->flags & FF_MOV_FLAG_ISML)
6669 mov_write_isml_manifest(pb, mov, s);
6671 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV &&
6672 !(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
6673 if ((ret = mov_write_moov_tag(pb, mov, s)) < 0)
6675 mov->moov_written = 1;
6676 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
6677 mov->reserved_header_pos = avio_tell(pb);
6683 static int get_moov_size(AVFormatContext *s)
6686 AVIOContext *moov_buf;
6687 MOVMuxContext *mov = s->priv_data;
6689 if ((ret = ffio_open_null_buf(&moov_buf)) < 0)
6691 if ((ret = mov_write_moov_tag(moov_buf, mov, s)) < 0)
6693 return ffio_close_null_buf(moov_buf);
6696 static int get_sidx_size(AVFormatContext *s)
6700 MOVMuxContext *mov = s->priv_data;
6702 if ((ret = ffio_open_null_buf(&buf)) < 0)
6704 mov_write_sidx_tags(buf, mov, -1, 0);
6705 return ffio_close_null_buf(buf);
6709 * This function gets the moov size if moved to the top of the file: the chunk
6710 * offset table can switch between stco (32-bit entries) to co64 (64-bit
6711 * entries) when the moov is moved to the beginning, so the size of the moov
6712 * would change. It also updates the chunk offset tables.
6714 static int compute_moov_size(AVFormatContext *s)
6716 int i, moov_size, moov_size2;
6717 MOVMuxContext *mov = s->priv_data;
6719 moov_size = get_moov_size(s);
6723 for (i = 0; i < mov->nb_streams; i++)
6724 mov->tracks[i].data_offset += moov_size;
6726 moov_size2 = get_moov_size(s);
6730 /* if the size changed, we just switched from stco to co64 and need to
6731 * update the offsets */
6732 if (moov_size2 != moov_size)
6733 for (i = 0; i < mov->nb_streams; i++)
6734 mov->tracks[i].data_offset += moov_size2 - moov_size;
6739 static int compute_sidx_size(AVFormatContext *s)
6742 MOVMuxContext *mov = s->priv_data;
6744 sidx_size = get_sidx_size(s);
6748 for (i = 0; i < mov->nb_streams; i++)
6749 mov->tracks[i].data_offset += sidx_size;
6754 static int shift_data(AVFormatContext *s)
6756 int ret = 0, moov_size;
6757 MOVMuxContext *mov = s->priv_data;
6758 int64_t pos, pos_end;
6759 uint8_t *buf, *read_buf[2];
6760 int read_buf_id = 0;
6762 AVIOContext *read_pb;
6764 if (mov->flags & FF_MOV_FLAG_FRAGMENT)
6765 moov_size = compute_sidx_size(s);
6767 moov_size = compute_moov_size(s);
6771 buf = av_malloc(moov_size * 2);
6773 return AVERROR(ENOMEM);
6775 read_buf[1] = buf + moov_size;
6777 /* Shift the data: the AVIO context of the output can only be used for
6778 * writing, so we re-open the same output, but for reading. It also avoids
6779 * a read/seek/write/seek back and forth. */
6781 ret = s->io_open(s, &read_pb, s->url, AVIO_FLAG_READ, NULL);
6783 av_log(s, AV_LOG_ERROR, "Unable to re-open %s output file for "
6784 "the second pass (faststart)\n", s->url);
6788 /* mark the end of the shift to up to the last data we wrote, and get ready
6790 pos_end = avio_tell(s->pb);
6791 avio_seek(s->pb, mov->reserved_header_pos + moov_size, SEEK_SET);
6793 /* start reading at where the new moov will be placed */
6794 avio_seek(read_pb, mov->reserved_header_pos, SEEK_SET);
6795 pos = avio_tell(read_pb);
6797 #define READ_BLOCK do { \
6798 read_size[read_buf_id] = avio_read(read_pb, read_buf[read_buf_id], moov_size); \
6802 /* shift data by chunk of at most moov_size */
6807 n = read_size[read_buf_id];
6810 avio_write(s->pb, read_buf[read_buf_id], n);
6812 } while (pos < pos_end);
6813 ff_format_io_close(s, &read_pb);
6820 static int mov_write_trailer(AVFormatContext *s)
6822 MOVMuxContext *mov = s->priv_data;
6823 AVIOContext *pb = s->pb;
6828 if (mov->need_rewrite_extradata) {
6829 for (i = 0; i < s->nb_streams; i++) {
6830 MOVTrack *track = &mov->tracks[i];
6831 AVCodecParameters *par = track->par;
6833 track->vos_len = par->extradata_size;
6834 track->vos_data = av_malloc(track->vos_len + AV_INPUT_BUFFER_PADDING_SIZE);
6835 if (!track->vos_data)
6836 return AVERROR(ENOMEM);
6837 memcpy(track->vos_data, par->extradata, track->vos_len);
6838 memset(track->vos_data + track->vos_len, 0, AV_INPUT_BUFFER_PADDING_SIZE);
6840 mov->need_rewrite_extradata = 0;
6844 * Before actually writing the trailer, make sure that there are no
6845 * dangling subtitles, that need a terminating sample.
6847 for (i = 0; i < mov->nb_streams; i++) {
6848 MOVTrack *trk = &mov->tracks[i];
6849 if (trk->par->codec_id == AV_CODEC_ID_MOV_TEXT &&
6850 !trk->last_sample_is_subtitle_end) {
6851 mov_write_subtitle_end_packet(s, i, trk->track_duration);
6852 trk->last_sample_is_subtitle_end = 1;
6856 // If there were no chapters when the header was written, but there
6857 // are chapters now, write them in the trailer. This only works
6858 // when we are not doing fragments.
6859 if (!mov->chapter_track && !(mov->flags & FF_MOV_FLAG_FRAGMENT)) {
6860 if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters) {
6861 mov->chapter_track = mov->nb_streams++;
6862 if ((res = mov_create_chapter_track(s, mov->chapter_track)) < 0)
6867 if (!(mov->flags & FF_MOV_FLAG_FRAGMENT)) {
6868 moov_pos = avio_tell(pb);
6870 /* Write size of mdat tag */
6871 if (mov->mdat_size + 8 <= UINT32_MAX) {
6872 avio_seek(pb, mov->mdat_pos, SEEK_SET);
6873 avio_wb32(pb, mov->mdat_size + 8);
6875 /* overwrite 'wide' placeholder atom */
6876 avio_seek(pb, mov->mdat_pos - 8, SEEK_SET);
6877 /* special value: real atom size will be 64 bit value after
6880 ffio_wfourcc(pb, "mdat");
6881 avio_wb64(pb, mov->mdat_size + 16);
6883 avio_seek(pb, mov->reserved_moov_size > 0 ? mov->reserved_header_pos : moov_pos, SEEK_SET);
6885 if (mov->flags & FF_MOV_FLAG_FASTSTART) {
6886 av_log(s, AV_LOG_INFO, "Starting second pass: moving the moov atom to the beginning of the file\n");
6887 res = shift_data(s);
6890 avio_seek(pb, mov->reserved_header_pos, SEEK_SET);
6891 if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
6893 } else if (mov->reserved_moov_size > 0) {
6895 if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
6897 size = mov->reserved_moov_size - (avio_tell(pb) - mov->reserved_header_pos);
6899 av_log(s, AV_LOG_ERROR, "reserved_moov_size is too small, needed %"PRId64" additional\n", 8-size);
6900 return AVERROR(EINVAL);
6902 avio_wb32(pb, size);
6903 ffio_wfourcc(pb, "free");
6904 ffio_fill(pb, 0, size - 8);
6905 avio_seek(pb, moov_pos, SEEK_SET);
6907 if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
6912 mov_auto_flush_fragment(s, 1);
6913 for (i = 0; i < mov->nb_streams; i++)
6914 mov->tracks[i].data_offset = 0;
6915 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) {
6917 av_log(s, AV_LOG_INFO, "Starting second pass: inserting sidx atoms\n");
6918 res = shift_data(s);
6921 end = avio_tell(pb);
6922 avio_seek(pb, mov->reserved_header_pos, SEEK_SET);
6923 mov_write_sidx_tags(pb, mov, -1, 0);
6924 avio_seek(pb, end, SEEK_SET);
6926 if (!(mov->flags & FF_MOV_FLAG_SKIP_TRAILER)) {
6927 avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_TRAILER);
6928 mov_write_mfra_tag(pb, mov);
6935 static int mov_check_bitstream(struct AVFormatContext *s, const AVPacket *pkt)
6938 AVStream *st = s->streams[pkt->stream_index];
6940 if (st->codecpar->codec_id == AV_CODEC_ID_AAC) {
6941 if (pkt->size > 2 && (AV_RB16(pkt->data) & 0xfff0) == 0xfff0)
6942 ret = ff_stream_add_bitstream_filter(st, "aac_adtstoasc", NULL);
6943 } else if (st->codecpar->codec_id == AV_CODEC_ID_VP9) {
6944 ret = ff_stream_add_bitstream_filter(st, "vp9_superframe", NULL);
6950 static const AVCodecTag codec_3gp_tags[] = {
6951 { AV_CODEC_ID_H263, MKTAG('s','2','6','3') },
6952 { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
6953 { AV_CODEC_ID_MPEG4, MKTAG('m','p','4','v') },
6954 { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
6955 { AV_CODEC_ID_AMR_NB, MKTAG('s','a','m','r') },
6956 { AV_CODEC_ID_AMR_WB, MKTAG('s','a','w','b') },
6957 { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
6958 { AV_CODEC_ID_NONE, 0 },
6961 const AVCodecTag codec_mp4_tags[] = {
6962 { AV_CODEC_ID_MPEG4, MKTAG('m', 'p', '4', 'v') },
6963 { AV_CODEC_ID_H264, MKTAG('a', 'v', 'c', '1') },
6964 { AV_CODEC_ID_H264, MKTAG('a', 'v', 'c', '3') },
6965 { AV_CODEC_ID_HEVC, MKTAG('h', 'e', 'v', '1') },
6966 { AV_CODEC_ID_HEVC, MKTAG('h', 'v', 'c', '1') },
6967 { AV_CODEC_ID_MPEG2VIDEO, MKTAG('m', 'p', '4', 'v') },
6968 { AV_CODEC_ID_MPEG1VIDEO, MKTAG('m', 'p', '4', 'v') },
6969 { AV_CODEC_ID_MJPEG, MKTAG('m', 'p', '4', 'v') },
6970 { AV_CODEC_ID_PNG, MKTAG('m', 'p', '4', 'v') },
6971 { AV_CODEC_ID_JPEG2000, MKTAG('m', 'p', '4', 'v') },
6972 { AV_CODEC_ID_VC1, MKTAG('v', 'c', '-', '1') },
6973 { AV_CODEC_ID_DIRAC, MKTAG('d', 'r', 'a', 'c') },
6974 { AV_CODEC_ID_TSCC2, MKTAG('m', 'p', '4', 'v') },
6975 { AV_CODEC_ID_VP9, MKTAG('v', 'p', '0', '9') },
6976 { AV_CODEC_ID_AV1, MKTAG('a', 'v', '0', '1') },
6977 { AV_CODEC_ID_AAC, MKTAG('m', 'p', '4', 'a') },
6978 { AV_CODEC_ID_MP4ALS, MKTAG('m', 'p', '4', 'a') },
6979 { AV_CODEC_ID_MP3, MKTAG('m', 'p', '4', 'a') },
6980 { AV_CODEC_ID_MP2, MKTAG('m', 'p', '4', 'a') },
6981 { AV_CODEC_ID_AC3, MKTAG('a', 'c', '-', '3') },
6982 { AV_CODEC_ID_EAC3, MKTAG('e', 'c', '-', '3') },
6983 { AV_CODEC_ID_DTS, MKTAG('m', 'p', '4', 'a') },
6984 { AV_CODEC_ID_TRUEHD, MKTAG('m', 'l', 'p', 'a') },
6985 { AV_CODEC_ID_FLAC, MKTAG('f', 'L', 'a', 'C') },
6986 { AV_CODEC_ID_OPUS, MKTAG('O', 'p', 'u', 's') },
6987 { AV_CODEC_ID_VORBIS, MKTAG('m', 'p', '4', 'a') },
6988 { AV_CODEC_ID_QCELP, MKTAG('m', 'p', '4', 'a') },
6989 { AV_CODEC_ID_EVRC, MKTAG('m', 'p', '4', 'a') },
6990 { AV_CODEC_ID_DVD_SUBTITLE, MKTAG('m', 'p', '4', 's') },
6991 { AV_CODEC_ID_MOV_TEXT, MKTAG('t', 'x', '3', 'g') },
6992 { AV_CODEC_ID_BIN_DATA, MKTAG('g', 'p', 'm', 'd') },
6993 { AV_CODEC_ID_MPEGH_3D_AUDIO, MKTAG('m', 'h', 'm', '1') },
6994 { AV_CODEC_ID_NONE, 0 },
6997 const AVCodecTag codec_ism_tags[] = {
6998 { AV_CODEC_ID_WMAPRO , MKTAG('w', 'm', 'a', ' ') },
6999 { AV_CODEC_ID_NONE , 0 },
7002 static const AVCodecTag codec_ipod_tags[] = {
7003 { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
7004 { AV_CODEC_ID_MPEG4, MKTAG('m','p','4','v') },
7005 { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
7006 { AV_CODEC_ID_ALAC, MKTAG('a','l','a','c') },
7007 { AV_CODEC_ID_AC3, MKTAG('a','c','-','3') },
7008 { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
7009 { AV_CODEC_ID_MOV_TEXT, MKTAG('t','e','x','t') },
7010 { AV_CODEC_ID_NONE, 0 },
7013 static const AVCodecTag codec_f4v_tags[] = {
7014 { AV_CODEC_ID_MP3, MKTAG('.','m','p','3') },
7015 { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
7016 { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
7017 { AV_CODEC_ID_VP6A, MKTAG('V','P','6','A') },
7018 { AV_CODEC_ID_VP6F, MKTAG('V','P','6','F') },
7019 { AV_CODEC_ID_NONE, 0 },
7022 #if CONFIG_MOV_MUXER
7024 AVOutputFormat ff_mov_muxer = {
7026 .long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
7027 .extensions = "mov",
7028 .priv_data_size = sizeof(MOVMuxContext),
7029 .audio_codec = AV_CODEC_ID_AAC,
7030 .video_codec = CONFIG_LIBX264_ENCODER ?
7031 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
7033 .write_header = mov_write_header,
7034 .write_packet = mov_write_packet,
7035 .write_trailer = mov_write_trailer,
7037 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
7038 .codec_tag = (const AVCodecTag* const []){
7039 ff_codec_movvideo_tags, ff_codec_movaudio_tags, ff_codec_movsubtitle_tags, 0
7041 .check_bitstream = mov_check_bitstream,
7042 .priv_class = &mov_muxer_class,
7045 #if CONFIG_TGP_MUXER
7047 AVOutputFormat ff_tgp_muxer = {
7049 .long_name = NULL_IF_CONFIG_SMALL("3GP (3GPP file format)"),
7050 .extensions = "3gp",
7051 .priv_data_size = sizeof(MOVMuxContext),
7052 .audio_codec = AV_CODEC_ID_AMR_NB,
7053 .video_codec = AV_CODEC_ID_H263,
7055 .write_header = mov_write_header,
7056 .write_packet = mov_write_packet,
7057 .write_trailer = mov_write_trailer,
7059 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
7060 .codec_tag = (const AVCodecTag* const []){ codec_3gp_tags, 0 },
7061 .check_bitstream = mov_check_bitstream,
7062 .priv_class = &tgp_muxer_class,
7065 #if CONFIG_MP4_MUXER
7067 AVOutputFormat ff_mp4_muxer = {
7069 .long_name = NULL_IF_CONFIG_SMALL("MP4 (MPEG-4 Part 14)"),
7070 .mime_type = "video/mp4",
7071 .extensions = "mp4",
7072 .priv_data_size = sizeof(MOVMuxContext),
7073 .audio_codec = AV_CODEC_ID_AAC,
7074 .video_codec = CONFIG_LIBX264_ENCODER ?
7075 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
7077 .write_header = mov_write_header,
7078 .write_packet = mov_write_packet,
7079 .write_trailer = mov_write_trailer,
7081 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
7082 .codec_tag = (const AVCodecTag* const []){ codec_mp4_tags, 0 },
7083 .check_bitstream = mov_check_bitstream,
7084 .priv_class = &mp4_muxer_class,
7087 #if CONFIG_PSP_MUXER
7089 AVOutputFormat ff_psp_muxer = {
7091 .long_name = NULL_IF_CONFIG_SMALL("PSP MP4 (MPEG-4 Part 14)"),
7092 .extensions = "mp4,psp",
7093 .priv_data_size = sizeof(MOVMuxContext),
7094 .audio_codec = AV_CODEC_ID_AAC,
7095 .video_codec = CONFIG_LIBX264_ENCODER ?
7096 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
7098 .write_header = mov_write_header,
7099 .write_packet = mov_write_packet,
7100 .write_trailer = mov_write_trailer,
7102 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
7103 .codec_tag = (const AVCodecTag* const []){ codec_mp4_tags, 0 },
7104 .check_bitstream = mov_check_bitstream,
7105 .priv_class = &psp_muxer_class,
7108 #if CONFIG_TG2_MUXER
7110 AVOutputFormat ff_tg2_muxer = {
7112 .long_name = NULL_IF_CONFIG_SMALL("3GP2 (3GPP2 file format)"),
7113 .extensions = "3g2",
7114 .priv_data_size = sizeof(MOVMuxContext),
7115 .audio_codec = AV_CODEC_ID_AMR_NB,
7116 .video_codec = AV_CODEC_ID_H263,
7118 .write_header = mov_write_header,
7119 .write_packet = mov_write_packet,
7120 .write_trailer = mov_write_trailer,
7122 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
7123 .codec_tag = (const AVCodecTag* const []){ codec_3gp_tags, 0 },
7124 .check_bitstream = mov_check_bitstream,
7125 .priv_class = &tg2_muxer_class,
7128 #if CONFIG_IPOD_MUXER
7130 AVOutputFormat ff_ipod_muxer = {
7132 .long_name = NULL_IF_CONFIG_SMALL("iPod H.264 MP4 (MPEG-4 Part 14)"),
7133 .mime_type = "video/mp4",
7134 .extensions = "m4v,m4a,m4b",
7135 .priv_data_size = sizeof(MOVMuxContext),
7136 .audio_codec = AV_CODEC_ID_AAC,
7137 .video_codec = AV_CODEC_ID_H264,
7139 .write_header = mov_write_header,
7140 .write_packet = mov_write_packet,
7141 .write_trailer = mov_write_trailer,
7143 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
7144 .codec_tag = (const AVCodecTag* const []){ codec_ipod_tags, 0 },
7145 .check_bitstream = mov_check_bitstream,
7146 .priv_class = &ipod_muxer_class,
7149 #if CONFIG_ISMV_MUXER
7151 AVOutputFormat ff_ismv_muxer = {
7153 .long_name = NULL_IF_CONFIG_SMALL("ISMV/ISMA (Smooth Streaming)"),
7154 .mime_type = "video/mp4",
7155 .extensions = "ismv,isma",
7156 .priv_data_size = sizeof(MOVMuxContext),
7157 .audio_codec = AV_CODEC_ID_AAC,
7158 .video_codec = AV_CODEC_ID_H264,
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 []){
7166 codec_mp4_tags, codec_ism_tags, 0 },
7167 .check_bitstream = mov_check_bitstream,
7168 .priv_class = &ismv_muxer_class,
7171 #if CONFIG_F4V_MUXER
7173 AVOutputFormat ff_f4v_muxer = {
7175 .long_name = NULL_IF_CONFIG_SMALL("F4V Adobe Flash Video"),
7176 .mime_type = "application/f4v",
7177 .extensions = "f4v",
7178 .priv_data_size = sizeof(MOVMuxContext),
7179 .audio_codec = AV_CODEC_ID_AAC,
7180 .video_codec = AV_CODEC_ID_H264,
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,
7187 .codec_tag = (const AVCodecTag* const []){ codec_f4v_tags, 0 },
7188 .check_bitstream = mov_check_bitstream,
7189 .priv_class = &f4v_muxer_class,