3 * Copyright (c) 2003 Thomas Raivio
4 * Copyright (c) 2004 Gildas Bazin <gbazin at videolan dot org>
5 * Copyright (c) 2009 Baptiste Coudurier <baptiste dot coudurier at gmail dot com>
7 * This file is part of FFmpeg.
9 * FFmpeg is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
14 * FFmpeg is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with FFmpeg; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
29 #include "avio_internal.h"
35 #include "libavcodec/ac3_parser_internal.h"
36 #include "libavcodec/dnxhddata.h"
37 #include "libavcodec/flac.h"
38 #include "libavcodec/get_bits.h"
40 #include "libavcodec/internal.h"
41 #include "libavcodec/put_bits.h"
42 #include "libavcodec/vc1_common.h"
43 #include "libavcodec/raw.h"
45 #include "libavutil/avstring.h"
46 #include "libavutil/intfloat.h"
47 #include "libavutil/mathematics.h"
48 #include "libavutil/libm.h"
49 #include "libavutil/opt.h"
50 #include "libavutil/dict.h"
51 #include "libavutil/pixdesc.h"
52 #include "libavutil/stereo3d.h"
53 #include "libavutil/timecode.h"
54 #include "libavutil/color_utils.h"
60 static const AVOption options[] = {
61 { "movflags", "MOV muxer flags", offsetof(MOVMuxContext, flags), AV_OPT_TYPE_FLAGS, {.i64 = 0}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
62 { "rtphint", "Add RTP hint tracks", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_RTP_HINT}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
63 { "moov_size", "maximum moov size so it can be placed at the begin", offsetof(MOVMuxContext, reserved_moov_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, 0 },
64 { "empty_moov", "Make the initial moov atom empty", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_EMPTY_MOOV}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
65 { "frag_keyframe", "Fragment at video keyframes", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FRAG_KEYFRAME}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
66 { "frag_every_frame", "Fragment at every frame", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FRAG_EVERY_FRAME}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
67 { "separate_moof", "Write separate moof/mdat atoms for each track", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_SEPARATE_MOOF}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
68 { "frag_custom", "Flush fragments on caller requests", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FRAG_CUSTOM}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
69 { "isml", "Create a live smooth streaming feed (for pushing to a publishing point)", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_ISML}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
70 { "faststart", "Run a second pass to put the index (moov atom) at the beginning of the file", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FASTSTART}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
71 { "omit_tfhd_offset", "Omit the base data offset in tfhd atoms", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_OMIT_TFHD_OFFSET}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
72 { "disable_chpl", "Disable Nero chapter atom", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_DISABLE_CHPL}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
73 { "default_base_moof", "Set the default-base-is-moof flag in tfhd atoms", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_DEFAULT_BASE_MOOF}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
74 { "dash", "Write DASH compatible fragmented MP4", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_DASH}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
75 { "frag_discont", "Signal that the next fragment is discontinuous from earlier ones", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FRAG_DISCONT}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
76 { "delay_moov", "Delay writing the initial moov until the first fragment is cut, or until the first fragment flush", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_DELAY_MOOV}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
77 { "global_sidx", "Write a global sidx index at the start of the file", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_GLOBAL_SIDX}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
78 { "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" },
79 { "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" },
80 { "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" },
81 { "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" },
82 { "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" },
83 FF_RTP_FLAG_OPTS(MOVMuxContext, rtp_flags),
84 { "skip_iods", "Skip writing iods atom.", offsetof(MOVMuxContext, iods_skip), AV_OPT_TYPE_BOOL, {.i64 = 1}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM},
85 { "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},
86 { "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},
87 { "frag_duration", "Maximum fragment duration", offsetof(MOVMuxContext, max_fragment_duration), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
88 { "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},
89 { "frag_size", "Maximum fragment size", offsetof(MOVMuxContext, max_fragment_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
90 { "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},
91 { "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},
92 { "brand", "Override major brand", offsetof(MOVMuxContext, major_brand), AV_OPT_TYPE_STRING, {.str = NULL}, .flags = AV_OPT_FLAG_ENCODING_PARAM },
93 { "use_editlist", "use edit list", offsetof(MOVMuxContext, use_editlist), AV_OPT_TYPE_BOOL, {.i64 = -1}, -1, 1, AV_OPT_FLAG_ENCODING_PARAM},
94 { "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},
95 { "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},
96 { "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 },
97 { "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 },
98 { "encryption_key", "The media encryption key (hex)", offsetof(MOVMuxContext, encryption_key), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_ENCODING_PARAM },
99 { "encryption_kid", "The media encryption key identifier (hex)", offsetof(MOVMuxContext, encryption_kid), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_ENCODING_PARAM },
100 { "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},
101 { "write_tmcd", "force or disable writing tmcd", offsetof(MOVMuxContext, write_tmcd), AV_OPT_TYPE_BOOL, {.i64 = -1}, -1, 1, AV_OPT_FLAG_ENCODING_PARAM},
102 { "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"},
103 { "wallclock", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = MOV_PRFT_SRC_WALLCLOCK}, 0, 0, AV_OPT_FLAG_ENCODING_PARAM, "prft"},
104 { "pts", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = MOV_PRFT_SRC_PTS}, 0, 0, AV_OPT_FLAG_ENCODING_PARAM, "prft"},
105 { "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},
109 #define MOV_CLASS(flavor)\
110 static const AVClass flavor ## _muxer_class = {\
111 .class_name = #flavor " muxer",\
112 .item_name = av_default_item_name,\
114 .version = LIBAVUTIL_VERSION_INT,\
117 static int get_moov_size(AVFormatContext *s);
119 static int utf8len(const uint8_t *b)
124 GET_UTF8(val, *b++, return -1;)
130 //FIXME support 64 bit variant with wide placeholders
131 static int64_t update_size(AVIOContext *pb, int64_t pos)
133 int64_t curpos = avio_tell(pb);
134 avio_seek(pb, pos, SEEK_SET);
135 avio_wb32(pb, curpos - pos); /* rewrite size */
136 avio_seek(pb, curpos, SEEK_SET);
141 static int co64_required(const MOVTrack *track)
143 if (track->entry > 0 && track->cluster[track->entry - 1].pos + track->data_offset > UINT32_MAX)
148 static int is_cover_image(const AVStream *st)
150 /* Eg. AV_DISPOSITION_ATTACHED_PIC | AV_DISPOSITION_TIMED_THUMBNAILS
151 * is encoded as sparse video track */
152 return st && st->disposition == AV_DISPOSITION_ATTACHED_PIC;
155 static int rtp_hinting_needed(const AVStream *st)
157 /* Add hint tracks for each real audio and video stream */
158 if (is_cover_image(st))
160 return st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ||
161 st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO;
164 /* Chunk offset atom */
165 static int mov_write_stco_tag(AVIOContext *pb, MOVTrack *track)
168 int mode64 = co64_required(track); // use 32 bit size variant if possible
169 int64_t pos = avio_tell(pb);
170 avio_wb32(pb, 0); /* size */
172 ffio_wfourcc(pb, "co64");
174 ffio_wfourcc(pb, "stco");
175 avio_wb32(pb, 0); /* version & flags */
176 avio_wb32(pb, track->chunkCount); /* entry count */
177 for (i = 0; i < track->entry; i++) {
178 if (!track->cluster[i].chunkNum)
181 avio_wb64(pb, track->cluster[i].pos + track->data_offset);
183 avio_wb32(pb, track->cluster[i].pos + track->data_offset);
185 return update_size(pb, pos);
188 /* Sample size atom */
189 static int mov_write_stsz_tag(AVIOContext *pb, MOVTrack *track)
192 int i, j, entries = 0, tst = -1, oldtst = -1;
194 int64_t pos = avio_tell(pb);
195 avio_wb32(pb, 0); /* size */
196 ffio_wfourcc(pb, "stsz");
197 avio_wb32(pb, 0); /* version & flags */
199 for (i = 0; i < track->entry; i++) {
200 tst = track->cluster[i].size / track->cluster[i].entries;
201 if (oldtst != -1 && tst != oldtst)
204 entries += track->cluster[i].entries;
206 if (equalChunks && track->entry) {
207 int sSize = track->entry ? track->cluster[0].size / track->cluster[0].entries : 0;
208 sSize = FFMAX(1, sSize); // adpcm mono case could make sSize == 0
209 avio_wb32(pb, sSize); // sample size
210 avio_wb32(pb, entries); // sample count
212 avio_wb32(pb, 0); // sample size
213 avio_wb32(pb, entries); // sample count
214 for (i = 0; i < track->entry; i++) {
215 for (j = 0; j < track->cluster[i].entries; j++) {
216 avio_wb32(pb, track->cluster[i].size /
217 track->cluster[i].entries);
221 return update_size(pb, pos);
224 /* Sample to chunk atom */
225 static int mov_write_stsc_tag(AVIOContext *pb, MOVTrack *track)
227 int index = 0, oldval = -1, i;
228 int64_t entryPos, curpos;
230 int64_t pos = avio_tell(pb);
231 avio_wb32(pb, 0); /* size */
232 ffio_wfourcc(pb, "stsc");
233 avio_wb32(pb, 0); // version & flags
234 entryPos = avio_tell(pb);
235 avio_wb32(pb, track->chunkCount); // entry count
236 for (i = 0; i < track->entry; i++) {
237 if (oldval != track->cluster[i].samples_in_chunk && track->cluster[i].chunkNum) {
238 avio_wb32(pb, track->cluster[i].chunkNum); // first chunk
239 avio_wb32(pb, track->cluster[i].samples_in_chunk); // samples per chunk
240 avio_wb32(pb, 0x1); // sample description index
241 oldval = track->cluster[i].samples_in_chunk;
245 curpos = avio_tell(pb);
246 avio_seek(pb, entryPos, SEEK_SET);
247 avio_wb32(pb, index); // rewrite size
248 avio_seek(pb, curpos, SEEK_SET);
250 return update_size(pb, pos);
253 /* Sync sample atom */
254 static int mov_write_stss_tag(AVIOContext *pb, MOVTrack *track, uint32_t flag)
256 int64_t curpos, entryPos;
258 int64_t pos = avio_tell(pb);
259 avio_wb32(pb, 0); // size
260 ffio_wfourcc(pb, flag == MOV_SYNC_SAMPLE ? "stss" : "stps");
261 avio_wb32(pb, 0); // version & flags
262 entryPos = avio_tell(pb);
263 avio_wb32(pb, track->entry); // entry count
264 for (i = 0; i < track->entry; i++) {
265 if (track->cluster[i].flags & flag) {
266 avio_wb32(pb, i + 1);
270 curpos = avio_tell(pb);
271 avio_seek(pb, entryPos, SEEK_SET);
272 avio_wb32(pb, index); // rewrite size
273 avio_seek(pb, curpos, SEEK_SET);
274 return update_size(pb, pos);
277 /* Sample dependency atom */
278 static int mov_write_sdtp_tag(AVIOContext *pb, MOVTrack *track)
281 uint8_t leading, dependent, reference, redundancy;
282 int64_t pos = avio_tell(pb);
283 avio_wb32(pb, 0); // size
284 ffio_wfourcc(pb, "sdtp");
285 avio_wb32(pb, 0); // version & flags
286 for (i = 0; i < track->entry; i++) {
287 dependent = MOV_SAMPLE_DEPENDENCY_YES;
288 leading = reference = redundancy = MOV_SAMPLE_DEPENDENCY_UNKNOWN;
289 if (track->cluster[i].flags & MOV_DISPOSABLE_SAMPLE) {
290 reference = MOV_SAMPLE_DEPENDENCY_NO;
292 if (track->cluster[i].flags & MOV_SYNC_SAMPLE) {
293 dependent = MOV_SAMPLE_DEPENDENCY_NO;
295 avio_w8(pb, (leading << 6) | (dependent << 4) |
296 (reference << 2) | redundancy);
298 return update_size(pb, pos);
301 static int mov_write_amr_tag(AVIOContext *pb, MOVTrack *track)
303 avio_wb32(pb, 0x11); /* size */
304 if (track->mode == MODE_MOV) ffio_wfourcc(pb, "samr");
305 else ffio_wfourcc(pb, "damr");
306 ffio_wfourcc(pb, "FFMP");
307 avio_w8(pb, 0); /* decoder version */
309 avio_wb16(pb, 0x81FF); /* Mode set (all modes for AMR_NB) */
310 avio_w8(pb, 0x00); /* Mode change period (no restriction) */
311 avio_w8(pb, 0x01); /* Frames per sample */
315 static int mov_write_ac3_tag(AVIOContext *pb, MOVTrack *track)
320 int fscod, bsid, bsmod, acmod, lfeon, frmsizecod;
322 if (track->vos_len < 7)
326 ffio_wfourcc(pb, "dac3");
328 init_get_bits(&gbc, track->vos_data + 4, (track->vos_len - 4) * 8);
329 fscod = get_bits(&gbc, 2);
330 frmsizecod = get_bits(&gbc, 6);
331 bsid = get_bits(&gbc, 5);
332 bsmod = get_bits(&gbc, 3);
333 acmod = get_bits(&gbc, 3);
335 skip_bits(&gbc, 2); // dsurmod
337 if ((acmod & 1) && acmod != 1)
338 skip_bits(&gbc, 2); // cmixlev
340 skip_bits(&gbc, 2); // surmixlev
342 lfeon = get_bits1(&gbc);
344 init_put_bits(&pbc, buf, sizeof(buf));
345 put_bits(&pbc, 2, fscod);
346 put_bits(&pbc, 5, bsid);
347 put_bits(&pbc, 3, bsmod);
348 put_bits(&pbc, 3, acmod);
349 put_bits(&pbc, 1, lfeon);
350 put_bits(&pbc, 5, frmsizecod >> 1); // bit_rate_code
351 put_bits(&pbc, 5, 0); // reserved
353 flush_put_bits(&pbc);
354 avio_write(pb, buf, sizeof(buf));
364 /* Layout of the EC3SpecificBox */
365 /* maximum bitrate */
367 /* number of independent substreams */
370 /* sample rate code (see ff_ac3_sample_rate_tab) 2 bits */
372 /* bit stream identification 5 bits */
374 /* one bit reserved */
375 /* audio service mixing (not supported yet) 1 bit */
376 /* bit stream mode 3 bits */
378 /* audio coding mode 3 bits */
380 /* sub woofer on 1 bit */
382 /* 3 bits reserved */
383 /* number of dependent substreams associated with this substream 4 bits */
385 /* channel locations of the dependent substream(s), if any, 9 bits */
387 /* if there is no dependent substream, then one bit reserved instead */
388 } substream[1]; /* TODO: support 8 independent substreams */
391 #if CONFIG_AC3_PARSER
392 static int handle_eac3(MOVMuxContext *mov, AVPacket *pkt, MOVTrack *track)
394 AC3HeaderInfo *hdr = NULL;
395 struct eac3_info *info;
398 if (!track->eac3_priv && !(track->eac3_priv = av_mallocz(sizeof(*info))))
399 return AVERROR(ENOMEM);
400 info = track->eac3_priv;
402 if (avpriv_ac3_parse_header(&hdr, pkt->data, pkt->size) < 0) {
403 /* drop the packets until we see a good one */
405 av_log(mov->fc, AV_LOG_WARNING, "Dropping invalid packet from start of the stream\n");
408 ret = AVERROR_INVALIDDATA;
412 info->data_rate = FFMAX(info->data_rate, hdr->bit_rate / 1000);
413 num_blocks = hdr->num_blocks;
415 if (!info->ec3_done) {
416 /* AC-3 substream must be the first one */
417 if (hdr->bitstream_id <= 10 && hdr->substreamid != 0) {
418 ret = AVERROR(EINVAL);
422 /* this should always be the case, given that our AC-3 parser
423 * concatenates dependent frames to their independent parent */
424 if (hdr->frame_type == EAC3_FRAME_TYPE_INDEPENDENT) {
425 /* substream ids must be incremental */
426 if (hdr->substreamid > info->num_ind_sub + 1) {
427 ret = AVERROR(EINVAL);
431 if (hdr->substreamid == info->num_ind_sub + 1) {
432 //info->num_ind_sub++;
433 avpriv_request_sample(mov->fc, "Multiple independent substreams");
434 ret = AVERROR_PATCHWELCOME;
436 } else if (hdr->substreamid < info->num_ind_sub ||
437 hdr->substreamid == 0 && info->substream[0].bsid) {
442 if (hdr->substreamid != 0) {
443 avpriv_request_sample(mov->fc, "Multiple non EAC3 independent substreams");
444 ret = AVERROR_PATCHWELCOME;
449 /* fill the info needed for the "dec3" atom */
450 info->substream[hdr->substreamid].fscod = hdr->sr_code;
451 info->substream[hdr->substreamid].bsid = hdr->bitstream_id;
452 info->substream[hdr->substreamid].bsmod = hdr->bitstream_mode;
453 info->substream[hdr->substreamid].acmod = hdr->channel_mode;
454 info->substream[hdr->substreamid].lfeon = hdr->lfe_on;
456 /* Parse dependent substream(s), if any */
457 if (pkt->size != hdr->frame_size) {
458 int cumul_size = hdr->frame_size;
459 int parent = hdr->substreamid;
461 while (cumul_size != pkt->size) {
464 ret = avpriv_ac3_parse_header(&hdr, pkt->data + cumul_size, pkt->size - cumul_size);
467 if (hdr->frame_type != EAC3_FRAME_TYPE_DEPENDENT) {
468 ret = AVERROR(EINVAL);
471 info->substream[parent].num_dep_sub++;
474 /* header is parsed up to lfeon, but custom channel map may be needed */
475 init_get_bits8(&gbc, pkt->data + cumul_size + ret, pkt->size - cumul_size - ret);
478 /* skip volume control params */
479 for (i = 0; i < (hdr->channel_mode ? 1 : 2); i++) {
480 skip_bits(&gbc, 5); // skip dialog normalization
481 if (get_bits1(&gbc)) {
482 skip_bits(&gbc, 8); // skip compression gain word
485 /* get the dependent stream channel map, if exists */
487 info->substream[parent].chan_loc |= (get_bits(&gbc, 16) >> 5) & 0x1f;
489 info->substream[parent].chan_loc |= hdr->channel_mode;
490 cumul_size += hdr->frame_size;
496 if (!info->num_blocks && num_blocks == 6) {
500 else if (info->num_blocks + num_blocks > 6) {
501 ret = AVERROR_INVALIDDATA;
505 if (!info->num_blocks) {
506 ret = av_packet_ref(&info->pkt, pkt);
508 info->num_blocks = num_blocks;
511 if ((ret = av_grow_packet(&info->pkt, pkt->size)) < 0)
513 memcpy(info->pkt.data + info->pkt.size - pkt->size, pkt->data, pkt->size);
514 info->num_blocks += num_blocks;
515 info->pkt.duration += pkt->duration;
516 if ((ret = av_copy_packet_side_data(&info->pkt, pkt)) < 0)
518 if (info->num_blocks != 6)
520 av_packet_unref(pkt);
521 av_packet_move_ref(pkt, &info->pkt);
522 info->num_blocks = 0;
533 static int mov_write_eac3_tag(AVIOContext *pb, MOVTrack *track)
537 struct eac3_info *info;
540 if (!track->eac3_priv)
541 return AVERROR(EINVAL);
543 info = track->eac3_priv;
544 size = 2 + 4 * (info->num_ind_sub + 1);
545 buf = av_malloc(size);
547 size = AVERROR(ENOMEM);
551 init_put_bits(&pbc, buf, size);
552 put_bits(&pbc, 13, info->data_rate);
553 put_bits(&pbc, 3, info->num_ind_sub);
554 for (i = 0; i <= info->num_ind_sub; i++) {
555 put_bits(&pbc, 2, info->substream[i].fscod);
556 put_bits(&pbc, 5, info->substream[i].bsid);
557 put_bits(&pbc, 1, 0); /* reserved */
558 put_bits(&pbc, 1, 0); /* asvc */
559 put_bits(&pbc, 3, info->substream[i].bsmod);
560 put_bits(&pbc, 3, info->substream[i].acmod);
561 put_bits(&pbc, 1, info->substream[i].lfeon);
562 put_bits(&pbc, 5, 0); /* reserved */
563 put_bits(&pbc, 4, info->substream[i].num_dep_sub);
564 if (!info->substream[i].num_dep_sub) {
565 put_bits(&pbc, 1, 0); /* reserved */
568 put_bits(&pbc, 9, info->substream[i].chan_loc);
571 flush_put_bits(&pbc);
573 avio_wb32(pb, size + 8);
574 ffio_wfourcc(pb, "dec3");
575 avio_write(pb, buf, size);
580 av_packet_unref(&info->pkt);
581 av_freep(&track->eac3_priv);
587 * This function writes extradata "as is".
588 * Extradata must be formatted like a valid atom (with size and tag).
590 static int mov_write_extradata_tag(AVIOContext *pb, MOVTrack *track)
592 avio_write(pb, track->par->extradata, track->par->extradata_size);
593 return track->par->extradata_size;
596 static int mov_write_enda_tag(AVIOContext *pb)
599 ffio_wfourcc(pb, "enda");
600 avio_wb16(pb, 1); /* little endian */
604 static int mov_write_enda_tag_be(AVIOContext *pb)
607 ffio_wfourcc(pb, "enda");
608 avio_wb16(pb, 0); /* big endian */
612 static void put_descr(AVIOContext *pb, int tag, unsigned int size)
617 avio_w8(pb, (size >> (7 * i)) | 0x80);
618 avio_w8(pb, size & 0x7F);
621 static unsigned compute_avg_bitrate(MOVTrack *track)
625 if (!track->track_duration)
627 for (i = 0; i < track->entry; i++)
628 size += track->cluster[i].size;
629 return size * 8 * track->timescale / track->track_duration;
632 static int mov_write_esds_tag(AVIOContext *pb, MOVTrack *track) // Basic
634 AVCPBProperties *props;
635 int64_t pos = avio_tell(pb);
636 int decoder_specific_info_len = track->vos_len ? 5 + track->vos_len : 0;
637 unsigned avg_bitrate;
639 avio_wb32(pb, 0); // size
640 ffio_wfourcc(pb, "esds");
641 avio_wb32(pb, 0); // Version
644 put_descr(pb, 0x03, 3 + 5+13 + decoder_specific_info_len + 5+1);
645 avio_wb16(pb, track->track_id);
646 avio_w8(pb, 0x00); // flags (= no flags)
648 // DecoderConfig descriptor
649 put_descr(pb, 0x04, 13 + decoder_specific_info_len);
651 // Object type indication
652 if ((track->par->codec_id == AV_CODEC_ID_MP2 ||
653 track->par->codec_id == AV_CODEC_ID_MP3) &&
654 track->par->sample_rate > 24000)
655 avio_w8(pb, 0x6B); // 11172-3
657 avio_w8(pb, ff_codec_get_tag(ff_mp4_obj_type, track->par->codec_id));
659 // the following fields is made of 6 bits to identify the streamtype (4 for video, 5 for audio)
660 // plus 1 bit to indicate upstream and 1 bit set to 1 (reserved)
661 if (track->par->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
662 avio_w8(pb, (0x38 << 2) | 1); // flags (= NeroSubpicStream)
663 else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
664 avio_w8(pb, 0x15); // flags (= Audiostream)
666 avio_w8(pb, 0x11); // flags (= Visualstream)
668 props = (AVCPBProperties*)av_stream_get_side_data(track->st, AV_PKT_DATA_CPB_PROPERTIES,
671 avio_wb24(pb, props ? props->buffer_size / 8 : 0); // Buffersize DB
673 avg_bitrate = compute_avg_bitrate(track);
674 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)
675 avio_wb32(pb, avg_bitrate);
677 if (track->vos_len) {
678 // DecoderSpecific info descriptor
679 put_descr(pb, 0x05, track->vos_len);
680 avio_write(pb, track->vos_data, track->vos_len);
684 put_descr(pb, 0x06, 1);
686 return update_size(pb, pos);
689 static int mov_pcm_le_gt16(enum AVCodecID codec_id)
691 return codec_id == AV_CODEC_ID_PCM_S24LE ||
692 codec_id == AV_CODEC_ID_PCM_S32LE ||
693 codec_id == AV_CODEC_ID_PCM_F32LE ||
694 codec_id == AV_CODEC_ID_PCM_F64LE;
697 static int mov_pcm_be_gt16(enum AVCodecID codec_id)
699 return codec_id == AV_CODEC_ID_PCM_S24BE ||
700 codec_id == AV_CODEC_ID_PCM_S32BE ||
701 codec_id == AV_CODEC_ID_PCM_F32BE ||
702 codec_id == AV_CODEC_ID_PCM_F64BE;
705 static int mov_write_ms_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
708 int64_t pos = avio_tell(pb);
710 avio_wl32(pb, track->tag); // store it byteswapped
711 track->par->codec_tag = av_bswap16(track->tag >> 16);
712 if ((ret = ff_put_wav_header(s, pb, track->par, 0)) < 0)
714 return update_size(pb, pos);
717 static int mov_write_wfex_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
720 int64_t pos = avio_tell(pb);
722 ffio_wfourcc(pb, "wfex");
723 if ((ret = ff_put_wav_header(s, pb, track->st->codecpar, FF_PUT_WAV_HEADER_FORCE_WAVEFORMATEX)) < 0)
725 return update_size(pb, pos);
728 static int mov_write_dfla_tag(AVIOContext *pb, MOVTrack *track)
730 int64_t pos = avio_tell(pb);
732 ffio_wfourcc(pb, "dfLa");
733 avio_w8(pb, 0); /* version */
734 avio_wb24(pb, 0); /* flags */
736 /* Expect the encoder to pass a METADATA_BLOCK_TYPE_STREAMINFO. */
737 if (track->par->extradata_size != FLAC_STREAMINFO_SIZE)
738 return AVERROR_INVALIDDATA;
740 /* TODO: Write other METADATA_BLOCK_TYPEs if the encoder makes them available. */
741 avio_w8(pb, 1 << 7 | FLAC_METADATA_TYPE_STREAMINFO); /* LastMetadataBlockFlag << 7 | BlockType */
742 avio_wb24(pb, track->par->extradata_size); /* Length */
743 avio_write(pb, track->par->extradata, track->par->extradata_size); /* BlockData[Length] */
745 return update_size(pb, pos);
748 static int mov_write_dops_tag(AVIOContext *pb, MOVTrack *track)
750 int64_t pos = avio_tell(pb);
752 ffio_wfourcc(pb, "dOps");
753 avio_w8(pb, 0); /* Version */
754 if (track->par->extradata_size < 19) {
755 av_log(pb, AV_LOG_ERROR, "invalid extradata size\n");
756 return AVERROR_INVALIDDATA;
758 /* extradata contains an Ogg OpusHead, other than byte-ordering and
759 OpusHead's preceeding magic/version, OpusSpecificBox is currently
761 avio_w8(pb, AV_RB8(track->par->extradata + 9)); /* OuputChannelCount */
762 avio_wb16(pb, AV_RL16(track->par->extradata + 10)); /* PreSkip */
763 avio_wb32(pb, AV_RL32(track->par->extradata + 12)); /* InputSampleRate */
764 avio_wb16(pb, AV_RL16(track->par->extradata + 16)); /* OutputGain */
765 /* Write the rest of the header out without byte-swapping. */
766 avio_write(pb, track->par->extradata + 18, track->par->extradata_size - 18);
768 return update_size(pb, pos);
771 static int mov_write_chan_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
773 uint32_t layout_tag, bitmap;
774 int64_t pos = avio_tell(pb);
776 layout_tag = ff_mov_get_channel_layout_tag(track->par->codec_id,
777 track->par->channel_layout,
780 av_log(s, AV_LOG_WARNING, "not writing 'chan' tag due to "
781 "lack of channel information\n");
785 if (track->multichannel_as_mono)
788 avio_wb32(pb, 0); // Size
789 ffio_wfourcc(pb, "chan"); // Type
790 avio_w8(pb, 0); // Version
791 avio_wb24(pb, 0); // Flags
792 avio_wb32(pb, layout_tag); // mChannelLayoutTag
793 avio_wb32(pb, bitmap); // mChannelBitmap
794 avio_wb32(pb, 0); // mNumberChannelDescriptions
796 return update_size(pb, pos);
799 static int mov_write_wave_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
801 int64_t pos = avio_tell(pb);
803 avio_wb32(pb, 0); /* size */
804 ffio_wfourcc(pb, "wave");
806 if (track->par->codec_id != AV_CODEC_ID_QDM2) {
807 avio_wb32(pb, 12); /* size */
808 ffio_wfourcc(pb, "frma");
809 avio_wl32(pb, track->tag);
812 if (track->par->codec_id == AV_CODEC_ID_AAC) {
813 /* useless atom needed by mplayer, ipod, not needed by quicktime */
814 avio_wb32(pb, 12); /* size */
815 ffio_wfourcc(pb, "mp4a");
817 mov_write_esds_tag(pb, track);
818 } else if (mov_pcm_le_gt16(track->par->codec_id)) {
819 mov_write_enda_tag(pb);
820 } else if (mov_pcm_be_gt16(track->par->codec_id)) {
821 mov_write_enda_tag_be(pb);
822 } else if (track->par->codec_id == AV_CODEC_ID_AMR_NB) {
823 mov_write_amr_tag(pb, track);
824 } else if (track->par->codec_id == AV_CODEC_ID_AC3) {
825 mov_write_ac3_tag(pb, track);
826 } else if (track->par->codec_id == AV_CODEC_ID_EAC3) {
827 mov_write_eac3_tag(pb, track);
828 } else if (track->par->codec_id == AV_CODEC_ID_ALAC ||
829 track->par->codec_id == AV_CODEC_ID_QDM2) {
830 mov_write_extradata_tag(pb, track);
831 } else if (track->par->codec_id == AV_CODEC_ID_ADPCM_MS ||
832 track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) {
833 mov_write_ms_tag(s, pb, track);
836 avio_wb32(pb, 8); /* size */
837 avio_wb32(pb, 0); /* null tag */
839 return update_size(pb, pos);
842 static int mov_write_dvc1_structs(MOVTrack *track, uint8_t *buf)
845 const uint8_t *start, *next, *end = track->vos_data + track->vos_len;
846 int unescaped_size, seq_found = 0;
847 int level = 0, interlace = 0;
848 int packet_seq = track->vc1_info.packet_seq;
849 int packet_entry = track->vc1_info.packet_entry;
850 int slices = track->vc1_info.slices;
853 if (track->start_dts == AV_NOPTS_VALUE) {
854 /* No packets written yet, vc1_info isn't authoritative yet. */
855 /* Assume inline sequence and entry headers. */
856 packet_seq = packet_entry = 1;
857 av_log(NULL, AV_LOG_WARNING,
858 "moov atom written before any packets, unable to write correct "
859 "dvc1 atom. Set the delay_moov flag to fix this.\n");
862 unescaped = av_mallocz(track->vos_len + AV_INPUT_BUFFER_PADDING_SIZE);
864 return AVERROR(ENOMEM);
865 start = find_next_marker(track->vos_data, end);
866 for (next = start; next < end; start = next) {
869 next = find_next_marker(start + 4, end);
870 size = next - start - 4;
873 unescaped_size = vc1_unescape_buffer(start + 4, size, unescaped);
874 init_get_bits(&gb, unescaped, 8 * unescaped_size);
875 if (AV_RB32(start) == VC1_CODE_SEQHDR) {
876 int profile = get_bits(&gb, 2);
877 if (profile != PROFILE_ADVANCED) {
879 return AVERROR(ENOSYS);
882 level = get_bits(&gb, 3);
883 /* chromaformat, frmrtq_postproc, bitrtq_postproc, postprocflag,
885 skip_bits_long(&gb, 2 + 3 + 5 + 1 + 2*12);
886 skip_bits(&gb, 1); /* broadcast */
887 interlace = get_bits1(&gb);
888 skip_bits(&gb, 4); /* tfcntrflag, finterpflag, reserved, psf */
893 return AVERROR(ENOSYS);
896 init_put_bits(&pbc, buf, 7);
897 /* VC1DecSpecStruc */
898 put_bits(&pbc, 4, 12); /* profile - advanced */
899 put_bits(&pbc, 3, level);
900 put_bits(&pbc, 1, 0); /* reserved */
901 /* VC1AdvDecSpecStruc */
902 put_bits(&pbc, 3, level);
903 put_bits(&pbc, 1, 0); /* cbr */
904 put_bits(&pbc, 6, 0); /* reserved */
905 put_bits(&pbc, 1, !interlace); /* no interlace */
906 put_bits(&pbc, 1, !packet_seq); /* no multiple seq */
907 put_bits(&pbc, 1, !packet_entry); /* no multiple entry */
908 put_bits(&pbc, 1, !slices); /* no slice code */
909 put_bits(&pbc, 1, 0); /* no bframe */
910 put_bits(&pbc, 1, 0); /* reserved */
913 if (track->st->avg_frame_rate.num > 0 && track->st->avg_frame_rate.den > 0)
914 put_bits32(&pbc, track->st->avg_frame_rate.num / track->st->avg_frame_rate.den);
916 put_bits32(&pbc, 0xffffffff);
918 flush_put_bits(&pbc);
925 static int mov_write_dvc1_tag(AVIOContext *pb, MOVTrack *track)
927 uint8_t buf[7] = { 0 };
930 if ((ret = mov_write_dvc1_structs(track, buf)) < 0)
933 avio_wb32(pb, track->vos_len + 8 + sizeof(buf));
934 ffio_wfourcc(pb, "dvc1");
935 avio_write(pb, buf, sizeof(buf));
936 avio_write(pb, track->vos_data, track->vos_len);
941 static int mov_write_glbl_tag(AVIOContext *pb, MOVTrack *track)
943 avio_wb32(pb, track->vos_len + 8);
944 ffio_wfourcc(pb, "glbl");
945 avio_write(pb, track->vos_data, track->vos_len);
946 return 8 + track->vos_len;
950 * Compute flags for 'lpcm' tag.
951 * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
953 static int mov_get_lpcm_flags(enum AVCodecID codec_id)
956 case AV_CODEC_ID_PCM_F32BE:
957 case AV_CODEC_ID_PCM_F64BE:
959 case AV_CODEC_ID_PCM_F32LE:
960 case AV_CODEC_ID_PCM_F64LE:
962 case AV_CODEC_ID_PCM_U8:
964 case AV_CODEC_ID_PCM_S16BE:
965 case AV_CODEC_ID_PCM_S24BE:
966 case AV_CODEC_ID_PCM_S32BE:
968 case AV_CODEC_ID_PCM_S8:
969 case AV_CODEC_ID_PCM_S16LE:
970 case AV_CODEC_ID_PCM_S24LE:
971 case AV_CODEC_ID_PCM_S32LE:
978 static int get_cluster_duration(MOVTrack *track, int cluster_idx)
982 if (cluster_idx >= track->entry)
985 if (cluster_idx + 1 == track->entry)
986 next_dts = track->track_duration + track->start_dts;
988 next_dts = track->cluster[cluster_idx + 1].dts;
990 next_dts -= track->cluster[cluster_idx].dts;
992 av_assert0(next_dts >= 0);
993 av_assert0(next_dts <= INT_MAX);
998 static int get_samples_per_packet(MOVTrack *track)
1000 int i, first_duration;
1002 // return track->par->frame_size;
1004 /* use 1 for raw PCM */
1005 if (!track->audio_vbr)
1008 /* check to see if duration is constant for all clusters */
1011 first_duration = get_cluster_duration(track, 0);
1012 for (i = 1; i < track->entry; i++) {
1013 if (get_cluster_duration(track, i) != first_duration)
1016 return first_duration;
1019 static int mov_write_audio_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
1021 int64_t pos = avio_tell(pb);
1023 uint32_t tag = track->tag;
1025 if (track->mode == MODE_MOV) {
1026 if (track->timescale > UINT16_MAX || !track->par->channels) {
1027 if (mov_get_lpcm_flags(track->par->codec_id))
1028 tag = AV_RL32("lpcm");
1030 } else if (track->audio_vbr || mov_pcm_le_gt16(track->par->codec_id) ||
1031 mov_pcm_be_gt16(track->par->codec_id) ||
1032 track->par->codec_id == AV_CODEC_ID_ADPCM_MS ||
1033 track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
1034 track->par->codec_id == AV_CODEC_ID_QDM2) {
1039 avio_wb32(pb, 0); /* size */
1040 if (mov->encryption_scheme != MOV_ENC_NONE) {
1041 ffio_wfourcc(pb, "enca");
1043 avio_wl32(pb, tag); // store it byteswapped
1045 avio_wb32(pb, 0); /* Reserved */
1046 avio_wb16(pb, 0); /* Reserved */
1047 avio_wb16(pb, 1); /* Data-reference index, XXX == 1 */
1049 /* SoundDescription */
1050 avio_wb16(pb, version); /* Version */
1051 avio_wb16(pb, 0); /* Revision level */
1052 avio_wb32(pb, 0); /* Reserved */
1057 avio_wb16(pb, 0xfffe);
1059 avio_wb32(pb, 0x00010000);
1061 avio_wb64(pb, av_double2int(track->par->sample_rate));
1062 avio_wb32(pb, track->par->channels);
1063 avio_wb32(pb, 0x7F000000);
1064 avio_wb32(pb, av_get_bits_per_sample(track->par->codec_id));
1065 avio_wb32(pb, mov_get_lpcm_flags(track->par->codec_id));
1066 avio_wb32(pb, track->sample_size);
1067 avio_wb32(pb, get_samples_per_packet(track));
1069 if (track->mode == MODE_MOV) {
1070 avio_wb16(pb, track->par->channels);
1071 if (track->par->codec_id == AV_CODEC_ID_PCM_U8 ||
1072 track->par->codec_id == AV_CODEC_ID_PCM_S8)
1073 avio_wb16(pb, 8); /* bits per sample */
1074 else if (track->par->codec_id == AV_CODEC_ID_ADPCM_G726)
1075 avio_wb16(pb, track->par->bits_per_coded_sample);
1078 avio_wb16(pb, track->audio_vbr ? -2 : 0); /* compression ID */
1079 } else { /* reserved for mp4/3gp */
1080 if (track->par->codec_id == AV_CODEC_ID_FLAC ||
1081 track->par->codec_id == AV_CODEC_ID_OPUS) {
1082 avio_wb16(pb, track->par->channels);
1086 if (track->par->codec_id == AV_CODEC_ID_FLAC) {
1087 avio_wb16(pb, track->par->bits_per_raw_sample);
1094 avio_wb16(pb, 0); /* packet size (= 0) */
1095 if (track->par->codec_id == AV_CODEC_ID_OPUS)
1096 avio_wb16(pb, 48000);
1098 avio_wb16(pb, track->par->sample_rate <= UINT16_MAX ?
1099 track->par->sample_rate : 0);
1100 avio_wb16(pb, 0); /* Reserved */
1103 if (version == 1) { /* SoundDescription V1 extended info */
1104 if (mov_pcm_le_gt16(track->par->codec_id) ||
1105 mov_pcm_be_gt16(track->par->codec_id))
1106 avio_wb32(pb, 1); /* must be 1 for uncompressed formats */
1108 avio_wb32(pb, track->par->frame_size); /* Samples per packet */
1109 avio_wb32(pb, track->sample_size / track->par->channels); /* Bytes per packet */
1110 avio_wb32(pb, track->sample_size); /* Bytes per frame */
1111 avio_wb32(pb, 2); /* Bytes per sample */
1114 if (track->mode == MODE_MOV &&
1115 (track->par->codec_id == AV_CODEC_ID_AAC ||
1116 track->par->codec_id == AV_CODEC_ID_AC3 ||
1117 track->par->codec_id == AV_CODEC_ID_EAC3 ||
1118 track->par->codec_id == AV_CODEC_ID_AMR_NB ||
1119 track->par->codec_id == AV_CODEC_ID_ALAC ||
1120 track->par->codec_id == AV_CODEC_ID_ADPCM_MS ||
1121 track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
1122 track->par->codec_id == AV_CODEC_ID_QDM2 ||
1123 (mov_pcm_le_gt16(track->par->codec_id) && version==1) ||
1124 (mov_pcm_be_gt16(track->par->codec_id) && version==1)))
1125 mov_write_wave_tag(s, pb, track);
1126 else if (track->tag == MKTAG('m','p','4','a'))
1127 mov_write_esds_tag(pb, track);
1128 else if (track->par->codec_id == AV_CODEC_ID_AMR_NB)
1129 mov_write_amr_tag(pb, track);
1130 else if (track->par->codec_id == AV_CODEC_ID_AC3)
1131 mov_write_ac3_tag(pb, track);
1132 else if (track->par->codec_id == AV_CODEC_ID_EAC3)
1133 mov_write_eac3_tag(pb, track);
1134 else if (track->par->codec_id == AV_CODEC_ID_ALAC)
1135 mov_write_extradata_tag(pb, track);
1136 else if (track->par->codec_id == AV_CODEC_ID_WMAPRO)
1137 mov_write_wfex_tag(s, pb, track);
1138 else if (track->par->codec_id == AV_CODEC_ID_FLAC)
1139 mov_write_dfla_tag(pb, track);
1140 else if (track->par->codec_id == AV_CODEC_ID_OPUS)
1141 mov_write_dops_tag(pb, track);
1142 else if (track->vos_len > 0)
1143 mov_write_glbl_tag(pb, track);
1145 if (track->mode == MODE_MOV && track->par->codec_type == AVMEDIA_TYPE_AUDIO)
1146 mov_write_chan_tag(s, pb, track);
1148 if (mov->encryption_scheme != MOV_ENC_NONE) {
1149 ff_mov_cenc_write_sinf_tag(track, pb, mov->encryption_kid);
1152 return update_size(pb, pos);
1155 static int mov_write_d263_tag(AVIOContext *pb)
1157 avio_wb32(pb, 0xf); /* size */
1158 ffio_wfourcc(pb, "d263");
1159 ffio_wfourcc(pb, "FFMP");
1160 avio_w8(pb, 0); /* decoder version */
1161 /* FIXME use AVCodecContext level/profile, when encoder will set values */
1162 avio_w8(pb, 0xa); /* level */
1163 avio_w8(pb, 0); /* profile */
1167 static int mov_write_av1c_tag(AVIOContext *pb, MOVTrack *track)
1169 int64_t pos = avio_tell(pb);
1172 ffio_wfourcc(pb, "av1C");
1173 ff_isom_write_av1c(pb, track->vos_data, track->vos_len);
1174 return update_size(pb, pos);
1177 static int mov_write_avcc_tag(AVIOContext *pb, MOVTrack *track)
1179 int64_t pos = avio_tell(pb);
1182 ffio_wfourcc(pb, "avcC");
1183 ff_isom_write_avcc(pb, track->vos_data, track->vos_len);
1184 return update_size(pb, pos);
1187 static int mov_write_vpcc_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
1189 int64_t pos = avio_tell(pb);
1192 ffio_wfourcc(pb, "vpcC");
1193 avio_w8(pb, 1); /* version */
1194 avio_wb24(pb, 0); /* flags */
1195 ff_isom_write_vpcc(s, pb, track->par);
1196 return update_size(pb, pos);
1199 static int mov_write_hvcc_tag(AVIOContext *pb, MOVTrack *track)
1201 int64_t pos = avio_tell(pb);
1204 ffio_wfourcc(pb, "hvcC");
1205 if (track->tag == MKTAG('h','v','c','1'))
1206 ff_isom_write_hvcc(pb, track->vos_data, track->vos_len, 1);
1208 ff_isom_write_hvcc(pb, track->vos_data, track->vos_len, 0);
1209 return update_size(pb, pos);
1212 /* also used by all avid codecs (dv, imx, meridien) and their variants */
1213 static int mov_write_avid_tag(AVIOContext *pb, MOVTrack *track)
1218 int display_width = track->par->width;
1220 if (track->vos_data && track->vos_len > 0x29) {
1221 if (ff_dnxhd_parse_header_prefix(track->vos_data) != 0) {
1222 /* looks like a DNxHD bit stream */
1223 interlaced = (track->vos_data[5] & 2);
1224 cid = AV_RB32(track->vos_data + 0x28);
1226 av_log(NULL, AV_LOG_WARNING, "Could not locate DNxHD bit stream in vos_data\n");
1230 av_log(NULL, AV_LOG_WARNING, "Could not locate DNxHD bit stream, vos_data too small\n");
1234 avio_wb32(pb, 24); /* size */
1235 ffio_wfourcc(pb, "ACLR");
1236 ffio_wfourcc(pb, "ACLR");
1237 ffio_wfourcc(pb, "0001");
1238 if (track->par->color_range == AVCOL_RANGE_MPEG || /* Legal range (16-235) */
1239 track->par->color_range == AVCOL_RANGE_UNSPECIFIED) {
1240 avio_wb32(pb, 1); /* Corresponds to 709 in official encoder */
1241 } else { /* Full range (0-255) */
1242 avio_wb32(pb, 2); /* Corresponds to RGB in official encoder */
1244 avio_wb32(pb, 0); /* unknown */
1246 if (track->tag == MKTAG('A','V','d','h')) {
1248 ffio_wfourcc(pb, "ADHR");
1249 ffio_wfourcc(pb, "0001");
1251 avio_wb32(pb, 0); /* unknown */
1252 avio_wb32(pb, 1); /* unknown */
1253 avio_wb32(pb, 0); /* unknown */
1254 avio_wb32(pb, 0); /* unknown */
1258 avio_wb32(pb, 24); /* size */
1259 ffio_wfourcc(pb, "APRG");
1260 ffio_wfourcc(pb, "APRG");
1261 ffio_wfourcc(pb, "0001");
1262 avio_wb32(pb, 1); /* unknown */
1263 avio_wb32(pb, 0); /* unknown */
1265 avio_wb32(pb, 120); /* size */
1266 ffio_wfourcc(pb, "ARES");
1267 ffio_wfourcc(pb, "ARES");
1268 ffio_wfourcc(pb, "0001");
1269 avio_wb32(pb, cid); /* dnxhd cid, some id ? */
1270 if ( track->par->sample_aspect_ratio.num > 0
1271 && track->par->sample_aspect_ratio.den > 0)
1272 display_width = display_width * track->par->sample_aspect_ratio.num / track->par->sample_aspect_ratio.den;
1273 avio_wb32(pb, display_width);
1274 /* values below are based on samples created with quicktime and avid codecs */
1276 avio_wb32(pb, track->par->height / 2);
1277 avio_wb32(pb, 2); /* unknown */
1278 avio_wb32(pb, 0); /* unknown */
1279 avio_wb32(pb, 4); /* unknown */
1281 avio_wb32(pb, track->par->height);
1282 avio_wb32(pb, 1); /* unknown */
1283 avio_wb32(pb, 0); /* unknown */
1284 if (track->par->height == 1080)
1285 avio_wb32(pb, 5); /* unknown */
1287 avio_wb32(pb, 6); /* unknown */
1290 for (i = 0; i < 10; i++)
1296 static int mov_write_dpxe_tag(AVIOContext *pb, MOVTrack *track)
1299 ffio_wfourcc(pb, "DpxE");
1300 if (track->par->extradata_size >= 12 &&
1301 !memcmp(&track->par->extradata[4], "DpxE", 4)) {
1302 avio_wb32(pb, track->par->extradata[11]);
1309 static int mov_get_dv_codec_tag(AVFormatContext *s, MOVTrack *track)
1313 if (track->par->width == 720) { /* SD */
1314 if (track->par->height == 480) { /* NTSC */
1315 if (track->par->format == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','n');
1316 else tag = MKTAG('d','v','c',' ');
1317 }else if (track->par->format == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','p');
1318 else if (track->par->format == AV_PIX_FMT_YUV420P) tag = MKTAG('d','v','c','p');
1319 else tag = MKTAG('d','v','p','p');
1320 } else if (track->par->height == 720) { /* HD 720 line */
1321 if (track->st->time_base.den == 50) tag = MKTAG('d','v','h','q');
1322 else tag = MKTAG('d','v','h','p');
1323 } else if (track->par->height == 1080) { /* HD 1080 line */
1324 if (track->st->time_base.den == 25) tag = MKTAG('d','v','h','5');
1325 else tag = MKTAG('d','v','h','6');
1327 av_log(s, AV_LOG_ERROR, "unsupported height for dv codec\n");
1334 static AVRational find_fps(AVFormatContext *s, AVStream *st)
1336 AVRational rate = st->avg_frame_rate;
1338 #if FF_API_LAVF_AVCTX
1339 FF_DISABLE_DEPRECATION_WARNINGS
1340 rate = av_inv_q(st->codec->time_base);
1341 if (av_timecode_check_frame_rate(rate) < 0) {
1342 av_log(s, AV_LOG_DEBUG, "timecode: tbc=%d/%d invalid, fallback on %d/%d\n",
1343 rate.num, rate.den, st->avg_frame_rate.num, st->avg_frame_rate.den);
1344 rate = st->avg_frame_rate;
1346 FF_ENABLE_DEPRECATION_WARNINGS
1352 static int defined_frame_rate(AVFormatContext *s, AVStream *st)
1354 AVRational rational_framerate = find_fps(s, st);
1356 if (rational_framerate.den != 0)
1357 rate = av_q2d(rational_framerate);
1361 static int mov_get_mpeg2_xdcam_codec_tag(AVFormatContext *s, MOVTrack *track)
1363 int tag = track->par->codec_tag;
1364 int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE;
1365 AVStream *st = track->st;
1366 int rate = defined_frame_rate(s, st);
1369 tag = MKTAG('m', '2', 'v', '1'); //fallback tag
1371 if (track->par->format == AV_PIX_FMT_YUV420P) {
1372 if (track->par->width == 1280 && track->par->height == 720) {
1374 if (rate == 24) tag = MKTAG('x','d','v','4');
1375 else if (rate == 25) tag = MKTAG('x','d','v','5');
1376 else if (rate == 30) tag = MKTAG('x','d','v','1');
1377 else if (rate == 50) tag = MKTAG('x','d','v','a');
1378 else if (rate == 60) tag = MKTAG('x','d','v','9');
1380 } else if (track->par->width == 1440 && track->par->height == 1080) {
1382 if (rate == 24) tag = MKTAG('x','d','v','6');
1383 else if (rate == 25) tag = MKTAG('x','d','v','7');
1384 else if (rate == 30) tag = MKTAG('x','d','v','8');
1386 if (rate == 25) tag = MKTAG('x','d','v','3');
1387 else if (rate == 30) tag = MKTAG('x','d','v','2');
1389 } else if (track->par->width == 1920 && track->par->height == 1080) {
1391 if (rate == 24) tag = MKTAG('x','d','v','d');
1392 else if (rate == 25) tag = MKTAG('x','d','v','e');
1393 else if (rate == 30) tag = MKTAG('x','d','v','f');
1395 if (rate == 25) tag = MKTAG('x','d','v','c');
1396 else if (rate == 30) tag = MKTAG('x','d','v','b');
1399 } else if (track->par->format == AV_PIX_FMT_YUV422P) {
1400 if (track->par->width == 1280 && track->par->height == 720) {
1402 if (rate == 24) tag = MKTAG('x','d','5','4');
1403 else if (rate == 25) tag = MKTAG('x','d','5','5');
1404 else if (rate == 30) tag = MKTAG('x','d','5','1');
1405 else if (rate == 50) tag = MKTAG('x','d','5','a');
1406 else if (rate == 60) tag = MKTAG('x','d','5','9');
1408 } else if (track->par->width == 1920 && track->par->height == 1080) {
1410 if (rate == 24) tag = MKTAG('x','d','5','d');
1411 else if (rate == 25) tag = MKTAG('x','d','5','e');
1412 else if (rate == 30) tag = MKTAG('x','d','5','f');
1414 if (rate == 25) tag = MKTAG('x','d','5','c');
1415 else if (rate == 30) tag = MKTAG('x','d','5','b');
1423 static int mov_get_h264_codec_tag(AVFormatContext *s, MOVTrack *track)
1425 int tag = track->par->codec_tag;
1426 int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE;
1427 AVStream *st = track->st;
1428 int rate = defined_frame_rate(s, st);
1431 tag = MKTAG('a', 'v', 'c', 'i'); //fallback tag
1433 if (track->par->format == AV_PIX_FMT_YUV420P10) {
1434 if (track->par->width == 960 && track->par->height == 720) {
1436 if (rate == 24) tag = MKTAG('a','i','5','p');
1437 else if (rate == 25) tag = MKTAG('a','i','5','q');
1438 else if (rate == 30) tag = MKTAG('a','i','5','p');
1439 else if (rate == 50) tag = MKTAG('a','i','5','q');
1440 else if (rate == 60) tag = MKTAG('a','i','5','p');
1442 } else if (track->par->width == 1440 && track->par->height == 1080) {
1444 if (rate == 24) tag = MKTAG('a','i','5','3');
1445 else if (rate == 25) tag = MKTAG('a','i','5','2');
1446 else if (rate == 30) tag = MKTAG('a','i','5','3');
1448 if (rate == 50) tag = MKTAG('a','i','5','5');
1449 else if (rate == 60) tag = MKTAG('a','i','5','6');
1452 } else if (track->par->format == AV_PIX_FMT_YUV422P10) {
1453 if (track->par->width == 1280 && track->par->height == 720) {
1455 if (rate == 24) tag = MKTAG('a','i','1','p');
1456 else if (rate == 25) tag = MKTAG('a','i','1','q');
1457 else if (rate == 30) tag = MKTAG('a','i','1','p');
1458 else if (rate == 50) tag = MKTAG('a','i','1','q');
1459 else if (rate == 60) tag = MKTAG('a','i','1','p');
1461 } else if (track->par->width == 1920 && track->par->height == 1080) {
1463 if (rate == 24) tag = MKTAG('a','i','1','3');
1464 else if (rate == 25) tag = MKTAG('a','i','1','2');
1465 else if (rate == 30) tag = MKTAG('a','i','1','3');
1467 if (rate == 25) tag = MKTAG('a','i','1','5');
1468 else if (rate == 50) tag = MKTAG('a','i','1','5');
1469 else if (rate == 60) tag = MKTAG('a','i','1','6');
1471 } else if ( track->par->width == 4096 && track->par->height == 2160
1472 || track->par->width == 3840 && track->par->height == 2160
1473 || track->par->width == 2048 && track->par->height == 1080) {
1474 tag = MKTAG('a','i','v','x');
1481 static const struct {
1482 enum AVPixelFormat pix_fmt;
1485 } mov_pix_fmt_tags[] = {
1486 { AV_PIX_FMT_YUYV422, MKTAG('y','u','v','2'), 0 },
1487 { AV_PIX_FMT_YUYV422, MKTAG('y','u','v','s'), 0 },
1488 { AV_PIX_FMT_UYVY422, MKTAG('2','v','u','y'), 0 },
1489 { AV_PIX_FMT_RGB555BE,MKTAG('r','a','w',' '), 16 },
1490 { AV_PIX_FMT_RGB555LE,MKTAG('L','5','5','5'), 16 },
1491 { AV_PIX_FMT_RGB565LE,MKTAG('L','5','6','5'), 16 },
1492 { AV_PIX_FMT_RGB565BE,MKTAG('B','5','6','5'), 16 },
1493 { AV_PIX_FMT_GRAY16BE,MKTAG('b','1','6','g'), 16 },
1494 { AV_PIX_FMT_RGB24, MKTAG('r','a','w',' '), 24 },
1495 { AV_PIX_FMT_BGR24, MKTAG('2','4','B','G'), 24 },
1496 { AV_PIX_FMT_ARGB, MKTAG('r','a','w',' '), 32 },
1497 { AV_PIX_FMT_BGRA, MKTAG('B','G','R','A'), 32 },
1498 { AV_PIX_FMT_RGBA, MKTAG('R','G','B','A'), 32 },
1499 { AV_PIX_FMT_ABGR, MKTAG('A','B','G','R'), 32 },
1500 { AV_PIX_FMT_RGB48BE, MKTAG('b','4','8','r'), 48 },
1503 static int mov_get_dnxhd_codec_tag(AVFormatContext *s, MOVTrack *track)
1505 int tag = MKTAG('A','V','d','n');
1506 if (track->par->profile != FF_PROFILE_UNKNOWN &&
1507 track->par->profile != FF_PROFILE_DNXHD)
1508 tag = MKTAG('A','V','d','h');
1512 static int mov_get_rawvideo_codec_tag(AVFormatContext *s, MOVTrack *track)
1514 int tag = track->par->codec_tag;
1516 enum AVPixelFormat pix_fmt;
1518 for (i = 0; i < FF_ARRAY_ELEMS(mov_pix_fmt_tags); i++) {
1519 if (track->par->format == mov_pix_fmt_tags[i].pix_fmt) {
1520 tag = mov_pix_fmt_tags[i].tag;
1521 track->par->bits_per_coded_sample = mov_pix_fmt_tags[i].bps;
1522 if (track->par->codec_tag == mov_pix_fmt_tags[i].tag)
1527 pix_fmt = avpriv_find_pix_fmt(avpriv_pix_fmt_bps_mov,
1528 track->par->bits_per_coded_sample);
1529 if (tag == MKTAG('r','a','w',' ') &&
1530 track->par->format != pix_fmt &&
1531 track->par->format != AV_PIX_FMT_GRAY8 &&
1532 track->par->format != AV_PIX_FMT_NONE)
1533 av_log(s, AV_LOG_ERROR, "%s rawvideo cannot be written to mov, output file will be unreadable\n",
1534 av_get_pix_fmt_name(track->par->format));
1538 static int mov_get_codec_tag(AVFormatContext *s, MOVTrack *track)
1540 int tag = track->par->codec_tag;
1542 if (!tag || (s->strict_std_compliance >= FF_COMPLIANCE_NORMAL &&
1543 (track->par->codec_id == AV_CODEC_ID_DVVIDEO ||
1544 track->par->codec_id == AV_CODEC_ID_RAWVIDEO ||
1545 track->par->codec_id == AV_CODEC_ID_H263 ||
1546 track->par->codec_id == AV_CODEC_ID_H264 ||
1547 track->par->codec_id == AV_CODEC_ID_DNXHD ||
1548 track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO ||
1549 av_get_bits_per_sample(track->par->codec_id)))) { // pcm audio
1550 if (track->par->codec_id == AV_CODEC_ID_DVVIDEO)
1551 tag = mov_get_dv_codec_tag(s, track);
1552 else if (track->par->codec_id == AV_CODEC_ID_RAWVIDEO)
1553 tag = mov_get_rawvideo_codec_tag(s, track);
1554 else if (track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO)
1555 tag = mov_get_mpeg2_xdcam_codec_tag(s, track);
1556 else if (track->par->codec_id == AV_CODEC_ID_H264)
1557 tag = mov_get_h264_codec_tag(s, track);
1558 else if (track->par->codec_id == AV_CODEC_ID_DNXHD)
1559 tag = mov_get_dnxhd_codec_tag(s, track);
1560 else if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
1561 tag = ff_codec_get_tag(ff_codec_movvideo_tags, track->par->codec_id);
1562 if (!tag) { // if no mac fcc found, try with Microsoft tags
1563 tag = ff_codec_get_tag(ff_codec_bmp_tags, track->par->codec_id);
1565 av_log(s, AV_LOG_WARNING, "Using MS style video codec tag, "
1566 "the file may be unplayable!\n");
1568 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
1569 tag = ff_codec_get_tag(ff_codec_movaudio_tags, track->par->codec_id);
1570 if (!tag) { // if no mac fcc found, try with Microsoft tags
1571 int ms_tag = ff_codec_get_tag(ff_codec_wav_tags, track->par->codec_id);
1573 tag = MKTAG('m', 's', ((ms_tag >> 8) & 0xff), (ms_tag & 0xff));
1574 av_log(s, AV_LOG_WARNING, "Using MS style audio codec tag, "
1575 "the file may be unplayable!\n");
1578 } else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)
1579 tag = ff_codec_get_tag(ff_codec_movsubtitle_tags, track->par->codec_id);
1585 static const AVCodecTag codec_cover_image_tags[] = {
1586 { AV_CODEC_ID_MJPEG, 0xD },
1587 { AV_CODEC_ID_PNG, 0xE },
1588 { AV_CODEC_ID_BMP, 0x1B },
1589 { AV_CODEC_ID_NONE, 0 },
1592 static int mov_find_codec_tag(AVFormatContext *s, MOVTrack *track)
1596 if (is_cover_image(track->st))
1597 return ff_codec_get_tag(codec_cover_image_tags, track->par->codec_id);
1599 if (track->mode == MODE_MP4 || track->mode == MODE_PSP)
1600 tag = track->par->codec_tag;
1601 else if (track->mode == MODE_ISM)
1602 tag = track->par->codec_tag;
1603 else if (track->mode == MODE_IPOD) {
1604 if (!av_match_ext(s->url, "m4a") &&
1605 !av_match_ext(s->url, "m4v") &&
1606 !av_match_ext(s->url, "m4b"))
1607 av_log(s, AV_LOG_WARNING, "Warning, extension is not .m4a nor .m4v "
1608 "Quicktime/Ipod might not play the file\n");
1609 tag = track->par->codec_tag;
1610 } else if (track->mode & MODE_3GP)
1611 tag = track->par->codec_tag;
1612 else if (track->mode == MODE_F4V)
1613 tag = track->par->codec_tag;
1615 tag = mov_get_codec_tag(s, track);
1620 /** Write uuid atom.
1621 * Needed to make file play in iPods running newest firmware
1622 * goes after avcC atom in moov.trak.mdia.minf.stbl.stsd.avc1
1624 static int mov_write_uuid_tag_ipod(AVIOContext *pb)
1627 ffio_wfourcc(pb, "uuid");
1628 avio_wb32(pb, 0x6b6840f2);
1629 avio_wb32(pb, 0x5f244fc5);
1630 avio_wb32(pb, 0xba39a51b);
1631 avio_wb32(pb, 0xcf0323f3);
1636 static const uint16_t fiel_data[] = {
1637 0x0000, 0x0100, 0x0201, 0x0206, 0x0209, 0x020e
1640 static int mov_write_fiel_tag(AVIOContext *pb, MOVTrack *track, int field_order)
1642 unsigned mov_field_order = 0;
1643 if (field_order < FF_ARRAY_ELEMS(fiel_data))
1644 mov_field_order = fiel_data[field_order];
1648 ffio_wfourcc(pb, "fiel");
1649 avio_wb16(pb, mov_field_order);
1653 static int mov_write_subtitle_tag(AVIOContext *pb, MOVTrack *track)
1655 int64_t pos = avio_tell(pb);
1656 avio_wb32(pb, 0); /* size */
1657 avio_wl32(pb, track->tag); // store it byteswapped
1658 avio_wb32(pb, 0); /* Reserved */
1659 avio_wb16(pb, 0); /* Reserved */
1660 avio_wb16(pb, 1); /* Data-reference index */
1662 if (track->par->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
1663 mov_write_esds_tag(pb, track);
1664 else if (track->par->extradata_size)
1665 avio_write(pb, track->par->extradata, track->par->extradata_size);
1667 return update_size(pb, pos);
1670 static int mov_write_st3d_tag(AVIOContext *pb, AVStereo3D *stereo_3d)
1674 if (stereo_3d->flags != 0) {
1675 av_log(pb, AV_LOG_WARNING, "Unsupported stereo_3d flags %x. st3d not written.\n", stereo_3d->flags);
1679 switch (stereo_3d->type) {
1680 case AV_STEREO3D_2D:
1683 case AV_STEREO3D_TOPBOTTOM:
1686 case AV_STEREO3D_SIDEBYSIDE:
1690 av_log(pb, AV_LOG_WARNING, "Unsupported stereo_3d type %s. st3d not written.\n", av_stereo3d_type_name(stereo_3d->type));
1693 avio_wb32(pb, 13); /* size */
1694 ffio_wfourcc(pb, "st3d");
1695 avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1696 avio_w8(pb, stereo_mode);
1700 static int mov_write_sv3d_tag(AVFormatContext *s, AVIOContext *pb, AVSphericalMapping *spherical_mapping)
1702 int64_t sv3d_pos, svhd_pos, proj_pos;
1703 const char* metadata_source = s->flags & AVFMT_FLAG_BITEXACT ? "Lavf" : LIBAVFORMAT_IDENT;
1705 if (spherical_mapping->projection != AV_SPHERICAL_EQUIRECTANGULAR &&
1706 spherical_mapping->projection != AV_SPHERICAL_EQUIRECTANGULAR_TILE &&
1707 spherical_mapping->projection != AV_SPHERICAL_CUBEMAP) {
1708 av_log(pb, AV_LOG_WARNING, "Unsupported projection %d. sv3d not written.\n", spherical_mapping->projection);
1712 sv3d_pos = avio_tell(pb);
1713 avio_wb32(pb, 0); /* size */
1714 ffio_wfourcc(pb, "sv3d");
1716 svhd_pos = avio_tell(pb);
1717 avio_wb32(pb, 0); /* size */
1718 ffio_wfourcc(pb, "svhd");
1719 avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1720 avio_put_str(pb, metadata_source);
1721 update_size(pb, svhd_pos);
1723 proj_pos = avio_tell(pb);
1724 avio_wb32(pb, 0); /* size */
1725 ffio_wfourcc(pb, "proj");
1727 avio_wb32(pb, 24); /* size */
1728 ffio_wfourcc(pb, "prhd");
1729 avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1730 avio_wb32(pb, spherical_mapping->yaw);
1731 avio_wb32(pb, spherical_mapping->pitch);
1732 avio_wb32(pb, spherical_mapping->roll);
1734 switch (spherical_mapping->projection) {
1735 case AV_SPHERICAL_EQUIRECTANGULAR:
1736 case AV_SPHERICAL_EQUIRECTANGULAR_TILE:
1737 avio_wb32(pb, 28); /* size */
1738 ffio_wfourcc(pb, "equi");
1739 avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1740 avio_wb32(pb, spherical_mapping->bound_top);
1741 avio_wb32(pb, spherical_mapping->bound_bottom);
1742 avio_wb32(pb, spherical_mapping->bound_left);
1743 avio_wb32(pb, spherical_mapping->bound_right);
1745 case AV_SPHERICAL_CUBEMAP:
1746 avio_wb32(pb, 20); /* size */
1747 ffio_wfourcc(pb, "cbmp");
1748 avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1749 avio_wb32(pb, 0); /* layout */
1750 avio_wb32(pb, spherical_mapping->padding); /* padding */
1753 update_size(pb, proj_pos);
1755 return update_size(pb, sv3d_pos);
1758 static int mov_write_clap_tag(AVIOContext *pb, MOVTrack *track)
1761 ffio_wfourcc(pb, "clap");
1762 avio_wb32(pb, track->par->width); /* apertureWidth_N */
1763 avio_wb32(pb, 1); /* apertureWidth_D (= 1) */
1764 avio_wb32(pb, track->height); /* apertureHeight_N */
1765 avio_wb32(pb, 1); /* apertureHeight_D (= 1) */
1766 avio_wb32(pb, 0); /* horizOff_N (= 0) */
1767 avio_wb32(pb, 1); /* horizOff_D (= 1) */
1768 avio_wb32(pb, 0); /* vertOff_N (= 0) */
1769 avio_wb32(pb, 1); /* vertOff_D (= 1) */
1773 static int mov_write_pasp_tag(AVIOContext *pb, MOVTrack *track)
1776 av_reduce(&sar.num, &sar.den, track->par->sample_aspect_ratio.num,
1777 track->par->sample_aspect_ratio.den, INT_MAX);
1780 ffio_wfourcc(pb, "pasp");
1781 avio_wb32(pb, sar.num);
1782 avio_wb32(pb, sar.den);
1786 static int mov_write_gama_tag(AVIOContext *pb, MOVTrack *track, double gamma)
1791 gamma = avpriv_get_gamma_from_trc(track->par->color_trc);
1793 av_log(pb, AV_LOG_DEBUG, "gamma value %g\n", gamma);
1796 gama = (uint32_t)lrint((double)(1<<16) * gamma);
1797 av_log(pb, AV_LOG_DEBUG, "writing gama value %"PRId32"\n", gama);
1799 av_assert0(track->mode == MODE_MOV);
1801 ffio_wfourcc(pb, "gama");
1802 avio_wb32(pb, gama);
1806 av_log(pb, AV_LOG_WARNING, "gamma value unknown, unable to write gama atom\n");
1811 static int mov_write_colr_tag(AVIOContext *pb, MOVTrack *track)
1813 // Ref (MOV): https://developer.apple.com/library/mac/technotes/tn2162/_index.html#//apple_ref/doc/uid/DTS40013070-CH1-TNTAG9
1814 // Ref (MP4): ISO/IEC 14496-12:2012
1816 if (track->par->color_primaries == AVCOL_PRI_UNSPECIFIED &&
1817 track->par->color_trc == AVCOL_TRC_UNSPECIFIED &&
1818 track->par->color_space == AVCOL_SPC_UNSPECIFIED) {
1819 if ((track->par->width >= 1920 && track->par->height >= 1080)
1820 || (track->par->width == 1280 && track->par->height == 720)) {
1821 av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming bt709\n");
1822 track->par->color_primaries = AVCOL_PRI_BT709;
1823 } else if (track->par->width == 720 && track->height == 576) {
1824 av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming bt470bg\n");
1825 track->par->color_primaries = AVCOL_PRI_BT470BG;
1826 } else if (track->par->width == 720 &&
1827 (track->height == 486 || track->height == 480)) {
1828 av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming smpte170\n");
1829 track->par->color_primaries = AVCOL_PRI_SMPTE170M;
1831 av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, unable to assume anything\n");
1833 switch (track->par->color_primaries) {
1834 case AVCOL_PRI_BT709:
1835 track->par->color_trc = AVCOL_TRC_BT709;
1836 track->par->color_space = AVCOL_SPC_BT709;
1838 case AVCOL_PRI_SMPTE170M:
1839 case AVCOL_PRI_BT470BG:
1840 track->par->color_trc = AVCOL_TRC_BT709;
1841 track->par->color_space = AVCOL_SPC_SMPTE170M;
1846 /* We should only ever be called by MOV or MP4. */
1847 av_assert0(track->mode == MODE_MOV || track->mode == MODE_MP4);
1849 avio_wb32(pb, 18 + (track->mode == MODE_MP4));
1850 ffio_wfourcc(pb, "colr");
1851 if (track->mode == MODE_MP4)
1852 ffio_wfourcc(pb, "nclx");
1854 ffio_wfourcc(pb, "nclc");
1855 switch (track->par->color_primaries) {
1856 case AVCOL_PRI_BT709: avio_wb16(pb, 1); break;
1857 case AVCOL_PRI_BT470BG: avio_wb16(pb, 5); break;
1858 case AVCOL_PRI_SMPTE170M:
1859 case AVCOL_PRI_SMPTE240M: avio_wb16(pb, 6); break;
1860 case AVCOL_PRI_BT2020: avio_wb16(pb, 9); break;
1861 case AVCOL_PRI_SMPTE431: avio_wb16(pb, 11); break;
1862 case AVCOL_PRI_SMPTE432: avio_wb16(pb, 12); break;
1863 default: avio_wb16(pb, 2);
1865 switch (track->par->color_trc) {
1866 case AVCOL_TRC_BT709: avio_wb16(pb, 1); break;
1867 case AVCOL_TRC_SMPTE170M: avio_wb16(pb, 1); break; // remapped
1868 case AVCOL_TRC_SMPTE240M: avio_wb16(pb, 7); break;
1869 case AVCOL_TRC_SMPTEST2084: avio_wb16(pb, 16); break;
1870 case AVCOL_TRC_SMPTE428: avio_wb16(pb, 17); break;
1871 case AVCOL_TRC_ARIB_STD_B67: avio_wb16(pb, 18); break;
1872 default: avio_wb16(pb, 2);
1874 switch (track->par->color_space) {
1875 case AVCOL_SPC_BT709: avio_wb16(pb, 1); break;
1876 case AVCOL_SPC_BT470BG:
1877 case AVCOL_SPC_SMPTE170M: avio_wb16(pb, 6); break;
1878 case AVCOL_SPC_SMPTE240M: avio_wb16(pb, 7); break;
1879 case AVCOL_SPC_BT2020_NCL: avio_wb16(pb, 9); break;
1880 default: avio_wb16(pb, 2);
1883 if (track->mode == MODE_MP4) {
1884 int full_range = track->par->color_range == AVCOL_RANGE_JPEG;
1885 avio_w8(pb, full_range << 7);
1892 static void find_compressor(char * compressor_name, int len, MOVTrack *track)
1894 AVDictionaryEntry *encoder;
1895 int xdcam_res = (track->par->width == 1280 && track->par->height == 720)
1896 || (track->par->width == 1440 && track->par->height == 1080)
1897 || (track->par->width == 1920 && track->par->height == 1080);
1899 if (track->mode == MODE_MOV &&
1900 (encoder = av_dict_get(track->st->metadata, "encoder", NULL, 0))) {
1901 av_strlcpy(compressor_name, encoder->value, 32);
1902 } else if (track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO && xdcam_res) {
1903 int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE;
1904 AVStream *st = track->st;
1905 int rate = defined_frame_rate(NULL, st);
1906 av_strlcatf(compressor_name, len, "XDCAM");
1907 if (track->par->format == AV_PIX_FMT_YUV422P) {
1908 av_strlcatf(compressor_name, len, " HD422");
1909 } else if(track->par->width == 1440) {
1910 av_strlcatf(compressor_name, len, " HD");
1912 av_strlcatf(compressor_name, len, " EX");
1914 av_strlcatf(compressor_name, len, " %d%c", track->par->height, interlaced ? 'i' : 'p');
1916 av_strlcatf(compressor_name, len, "%d", rate * (interlaced + 1));
1920 static int mov_write_video_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
1922 int64_t pos = avio_tell(pb);
1923 char compressor_name[32] = { 0 };
1926 int uncompressed_ycbcr = ((track->par->codec_id == AV_CODEC_ID_RAWVIDEO && track->par->format == AV_PIX_FMT_UYVY422)
1927 || (track->par->codec_id == AV_CODEC_ID_RAWVIDEO && track->par->format == AV_PIX_FMT_YUYV422)
1928 || track->par->codec_id == AV_CODEC_ID_V308
1929 || track->par->codec_id == AV_CODEC_ID_V408
1930 || track->par->codec_id == AV_CODEC_ID_V410
1931 || track->par->codec_id == AV_CODEC_ID_V210);
1933 avio_wb32(pb, 0); /* size */
1934 if (mov->encryption_scheme != MOV_ENC_NONE) {
1935 ffio_wfourcc(pb, "encv");
1937 avio_wl32(pb, track->tag); // store it byteswapped
1939 avio_wb32(pb, 0); /* Reserved */
1940 avio_wb16(pb, 0); /* Reserved */
1941 avio_wb16(pb, 1); /* Data-reference index */
1943 if (uncompressed_ycbcr) {
1944 avio_wb16(pb, 2); /* Codec stream version */
1946 avio_wb16(pb, 0); /* Codec stream version */
1948 avio_wb16(pb, 0); /* Codec stream revision (=0) */
1949 if (track->mode == MODE_MOV) {
1950 ffio_wfourcc(pb, "FFMP"); /* Vendor */
1951 if (track->par->codec_id == AV_CODEC_ID_RAWVIDEO || uncompressed_ycbcr) {
1952 avio_wb32(pb, 0); /* Temporal Quality */
1953 avio_wb32(pb, 0x400); /* Spatial Quality = lossless*/
1955 avio_wb32(pb, 0x200); /* Temporal Quality = normal */
1956 avio_wb32(pb, 0x200); /* Spatial Quality = normal */
1959 avio_wb32(pb, 0); /* Reserved */
1960 avio_wb32(pb, 0); /* Reserved */
1961 avio_wb32(pb, 0); /* Reserved */
1963 avio_wb16(pb, track->par->width); /* Video width */
1964 avio_wb16(pb, track->height); /* Video height */
1965 avio_wb32(pb, 0x00480000); /* Horizontal resolution 72dpi */
1966 avio_wb32(pb, 0x00480000); /* Vertical resolution 72dpi */
1967 avio_wb32(pb, 0); /* Data size (= 0) */
1968 avio_wb16(pb, 1); /* Frame count (= 1) */
1970 /* FIXME not sure, ISO 14496-1 draft where it shall be set to 0 */
1971 find_compressor(compressor_name, 32, track);
1972 avio_w8(pb, strlen(compressor_name));
1973 avio_write(pb, compressor_name, 31);
1975 if (track->mode == MODE_MOV &&
1976 (track->par->codec_id == AV_CODEC_ID_V410 || track->par->codec_id == AV_CODEC_ID_V210))
1977 avio_wb16(pb, 0x18);
1978 else if (track->mode == MODE_MOV && track->par->bits_per_coded_sample)
1979 avio_wb16(pb, track->par->bits_per_coded_sample |
1980 (track->par->format == AV_PIX_FMT_GRAY8 ? 0x20 : 0));
1982 avio_wb16(pb, 0x18); /* Reserved */
1984 if (track->mode == MODE_MOV && track->par->format == AV_PIX_FMT_PAL8) {
1985 int pal_size = 1 << track->par->bits_per_coded_sample;
1987 avio_wb16(pb, 0); /* Color table ID */
1988 avio_wb32(pb, 0); /* Color table seed */
1989 avio_wb16(pb, 0x8000); /* Color table flags */
1990 avio_wb16(pb, pal_size - 1); /* Color table size (zero-relative) */
1991 for (i = 0; i < pal_size; i++) {
1992 uint32_t rgb = track->palette[i];
1993 uint16_t r = (rgb >> 16) & 0xff;
1994 uint16_t g = (rgb >> 8) & 0xff;
1995 uint16_t b = rgb & 0xff;
1997 avio_wb16(pb, (r << 8) | r);
1998 avio_wb16(pb, (g << 8) | g);
1999 avio_wb16(pb, (b << 8) | b);
2002 avio_wb16(pb, 0xffff); /* Reserved */
2004 if (track->tag == MKTAG('m','p','4','v'))
2005 mov_write_esds_tag(pb, track);
2006 else if (track->par->codec_id == AV_CODEC_ID_H263)
2007 mov_write_d263_tag(pb);
2008 else if (track->par->codec_id == AV_CODEC_ID_AVUI ||
2009 track->par->codec_id == AV_CODEC_ID_SVQ3) {
2010 mov_write_extradata_tag(pb, track);
2012 } else if (track->par->codec_id == AV_CODEC_ID_DNXHD) {
2013 mov_write_avid_tag(pb, track);
2015 } else if (track->par->codec_id == AV_CODEC_ID_HEVC)
2016 mov_write_hvcc_tag(pb, track);
2017 else if (track->par->codec_id == AV_CODEC_ID_H264 && !TAG_IS_AVCI(track->tag)) {
2018 mov_write_avcc_tag(pb, track);
2019 if (track->mode == MODE_IPOD)
2020 mov_write_uuid_tag_ipod(pb);
2021 } else if (track->par->codec_id == AV_CODEC_ID_VP9) {
2022 mov_write_vpcc_tag(mov->fc, pb, track);
2023 } else if (track->par->codec_id == AV_CODEC_ID_AV1) {
2024 mov_write_av1c_tag(pb, track);
2025 } else if (track->par->codec_id == AV_CODEC_ID_VC1 && track->vos_len > 0)
2026 mov_write_dvc1_tag(pb, track);
2027 else if (track->par->codec_id == AV_CODEC_ID_VP6F ||
2028 track->par->codec_id == AV_CODEC_ID_VP6A) {
2029 /* Don't write any potential extradata here - the cropping
2030 * is signalled via the normal width/height fields. */
2031 } else if (track->par->codec_id == AV_CODEC_ID_R10K) {
2032 if (track->par->codec_tag == MKTAG('R','1','0','k'))
2033 mov_write_dpxe_tag(pb, track);
2034 } else if (track->vos_len > 0)
2035 mov_write_glbl_tag(pb, track);
2037 if (track->par->codec_id != AV_CODEC_ID_H264 &&
2038 track->par->codec_id != AV_CODEC_ID_MPEG4 &&
2039 track->par->codec_id != AV_CODEC_ID_DNXHD) {
2040 int field_order = track->par->field_order;
2042 #if FF_API_LAVF_AVCTX
2043 FF_DISABLE_DEPRECATION_WARNINGS
2044 if (field_order != track->st->codec->field_order && track->st->codec->field_order != AV_FIELD_UNKNOWN)
2045 field_order = track->st->codec->field_order;
2046 FF_ENABLE_DEPRECATION_WARNINGS
2049 if (field_order != AV_FIELD_UNKNOWN)
2050 mov_write_fiel_tag(pb, track, field_order);
2053 if (mov->flags & FF_MOV_FLAG_WRITE_GAMA) {
2054 if (track->mode == MODE_MOV)
2055 mov_write_gama_tag(pb, track, mov->gamma);
2057 av_log(mov->fc, AV_LOG_WARNING, "Not writing 'gama' atom. Format is not MOV.\n");
2059 if (mov->flags & FF_MOV_FLAG_WRITE_COLR) {
2060 if (track->mode == MODE_MOV || track->mode == MODE_MP4)
2061 mov_write_colr_tag(pb, track);
2063 av_log(mov->fc, AV_LOG_WARNING, "Not writing 'colr' atom. Format is not MOV or MP4.\n");
2066 if (track->mode == MODE_MP4 && mov->fc->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL) {
2067 AVStereo3D* stereo_3d = (AVStereo3D*) av_stream_get_side_data(track->st, AV_PKT_DATA_STEREO3D, NULL);
2068 AVSphericalMapping* spherical_mapping = (AVSphericalMapping*)av_stream_get_side_data(track->st, AV_PKT_DATA_SPHERICAL, NULL);
2071 mov_write_st3d_tag(pb, stereo_3d);
2072 if (spherical_mapping)
2073 mov_write_sv3d_tag(mov->fc, pb, spherical_mapping);
2076 if (track->par->sample_aspect_ratio.den && track->par->sample_aspect_ratio.num) {
2077 mov_write_pasp_tag(pb, track);
2080 if (uncompressed_ycbcr){
2081 mov_write_clap_tag(pb, track);
2084 if (mov->encryption_scheme != MOV_ENC_NONE) {
2085 ff_mov_cenc_write_sinf_tag(track, pb, mov->encryption_kid);
2088 /* extra padding for avid stsd */
2089 /* https://developer.apple.com/library/mac/documentation/QuickTime/QTFF/QTFFChap2/qtff2.html#//apple_ref/doc/uid/TP40000939-CH204-61112 */
2093 return update_size(pb, pos);
2096 static int mov_write_rtp_tag(AVIOContext *pb, MOVTrack *track)
2098 int64_t pos = avio_tell(pb);
2099 avio_wb32(pb, 0); /* size */
2100 ffio_wfourcc(pb, "rtp ");
2101 avio_wb32(pb, 0); /* Reserved */
2102 avio_wb16(pb, 0); /* Reserved */
2103 avio_wb16(pb, 1); /* Data-reference index */
2105 avio_wb16(pb, 1); /* Hint track version */
2106 avio_wb16(pb, 1); /* Highest compatible version */
2107 avio_wb32(pb, track->max_packet_size); /* Max packet size */
2109 avio_wb32(pb, 12); /* size */
2110 ffio_wfourcc(pb, "tims");
2111 avio_wb32(pb, track->timescale);
2113 return update_size(pb, pos);
2116 static int mov_write_source_reference_tag(AVIOContext *pb, MOVTrack *track, const char *reel_name)
2118 uint64_t str_size =strlen(reel_name);
2119 int64_t pos = avio_tell(pb);
2121 if (str_size >= UINT16_MAX){
2122 av_log(NULL, AV_LOG_ERROR, "reel_name length %"PRIu64" is too large\n", str_size);
2124 return AVERROR(EINVAL);
2127 avio_wb32(pb, 0); /* size */
2128 ffio_wfourcc(pb, "name"); /* Data format */
2129 avio_wb16(pb, str_size); /* string size */
2130 avio_wb16(pb, track->language); /* langcode */
2131 avio_write(pb, reel_name, str_size); /* reel name */
2132 return update_size(pb,pos);
2135 static int mov_write_tmcd_tag(AVIOContext *pb, MOVTrack *track)
2137 int64_t pos = avio_tell(pb);
2141 AVDictionaryEntry *t = NULL;
2143 if (!track->st->avg_frame_rate.num || !track->st->avg_frame_rate.den) {
2144 #if FF_API_LAVF_AVCTX
2145 FF_DISABLE_DEPRECATION_WARNINGS
2146 frame_duration = av_rescale(track->timescale, track->st->codec->time_base.num, track->st->codec->time_base.den);
2147 nb_frames = ROUNDED_DIV(track->st->codec->time_base.den, track->st->codec->time_base.num);
2148 FF_ENABLE_DEPRECATION_WARNINGS
2150 av_log(NULL, AV_LOG_ERROR, "avg_frame_rate not set for tmcd track.\n");
2151 return AVERROR(EINVAL);
2154 frame_duration = av_rescale(track->timescale, track->st->avg_frame_rate.num, track->st->avg_frame_rate.den);
2155 nb_frames = ROUNDED_DIV(track->st->avg_frame_rate.den, track->st->avg_frame_rate.num);
2158 if (nb_frames > 255) {
2159 av_log(NULL, AV_LOG_ERROR, "fps %d is too large\n", nb_frames);
2160 return AVERROR(EINVAL);
2163 avio_wb32(pb, 0); /* size */
2164 ffio_wfourcc(pb, "tmcd"); /* Data format */
2165 avio_wb32(pb, 0); /* Reserved */
2166 avio_wb32(pb, 1); /* Data reference index */
2167 avio_wb32(pb, 0); /* Flags */
2168 avio_wb32(pb, track->timecode_flags); /* Flags (timecode) */
2169 avio_wb32(pb, track->timescale); /* Timescale */
2170 avio_wb32(pb, frame_duration); /* Frame duration */
2171 avio_w8(pb, nb_frames); /* Number of frames */
2172 avio_w8(pb, 0); /* Reserved */
2174 t = av_dict_get(track->st->metadata, "reel_name", NULL, 0);
2175 if (t && utf8len(t->value) && track->mode != MODE_MP4)
2176 mov_write_source_reference_tag(pb, track, t->value);
2178 avio_wb16(pb, 0); /* zero size */
2181 avio_wb32(pb, 0); /* size */
2182 ffio_wfourcc(pb, "tmcd"); /* Data format */
2183 avio_wb32(pb, 0); /* Reserved */
2184 avio_wb32(pb, 1); /* Data reference index */
2185 if (track->par->extradata_size)
2186 avio_write(pb, track->par->extradata, track->par->extradata_size);
2188 return update_size(pb, pos);
2191 static int mov_write_gpmd_tag(AVIOContext *pb, const MOVTrack *track)
2193 int64_t pos = avio_tell(pb);
2194 avio_wb32(pb, 0); /* size */
2195 ffio_wfourcc(pb, "gpmd");
2196 avio_wb32(pb, 0); /* Reserved */
2197 avio_wb16(pb, 0); /* Reserved */
2198 avio_wb16(pb, 1); /* Data-reference index */
2199 avio_wb32(pb, 0); /* Reserved */
2200 return update_size(pb, pos);
2203 static int mov_write_stsd_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
2205 int64_t pos = avio_tell(pb);
2206 avio_wb32(pb, 0); /* size */
2207 ffio_wfourcc(pb, "stsd");
2208 avio_wb32(pb, 0); /* version & flags */
2209 avio_wb32(pb, 1); /* entry count */
2210 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO)
2211 mov_write_video_tag(pb, mov, track);
2212 else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
2213 mov_write_audio_tag(s, pb, mov, track);
2214 else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)
2215 mov_write_subtitle_tag(pb, track);
2216 else if (track->par->codec_tag == MKTAG('r','t','p',' '))
2217 mov_write_rtp_tag(pb, track);
2218 else if (track->par->codec_tag == MKTAG('t','m','c','d'))
2219 mov_write_tmcd_tag(pb, track);
2220 else if (track->par->codec_tag == MKTAG('g','p','m','d'))
2221 mov_write_gpmd_tag(pb, track);
2222 return update_size(pb, pos);
2225 static int mov_write_ctts_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
2227 MOVMuxContext *mov = s->priv_data;
2228 MOVStts *ctts_entries;
2229 uint32_t entries = 0;
2233 ctts_entries = av_malloc_array((track->entry + 1), sizeof(*ctts_entries)); /* worst case */
2235 return AVERROR(ENOMEM);
2236 ctts_entries[0].count = 1;
2237 ctts_entries[0].duration = track->cluster[0].cts;
2238 for (i = 1; i < track->entry; i++) {
2239 if (track->cluster[i].cts == ctts_entries[entries].duration) {
2240 ctts_entries[entries].count++; /* compress */
2243 ctts_entries[entries].duration = track->cluster[i].cts;
2244 ctts_entries[entries].count = 1;
2247 entries++; /* last one */
2248 atom_size = 16 + (entries * 8);
2249 avio_wb32(pb, atom_size); /* size */
2250 ffio_wfourcc(pb, "ctts");
2251 if (mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS)
2252 avio_w8(pb, 1); /* version */
2254 avio_w8(pb, 0); /* version */
2255 avio_wb24(pb, 0); /* flags */
2256 avio_wb32(pb, entries); /* entry count */
2257 for (i = 0; i < entries; i++) {
2258 avio_wb32(pb, ctts_entries[i].count);
2259 avio_wb32(pb, ctts_entries[i].duration);
2261 av_free(ctts_entries);
2265 /* Time to sample atom */
2266 static int mov_write_stts_tag(AVIOContext *pb, MOVTrack *track)
2268 MOVStts *stts_entries = NULL;
2269 uint32_t entries = -1;
2273 if (track->par->codec_type == AVMEDIA_TYPE_AUDIO && !track->audio_vbr) {
2274 stts_entries = av_malloc(sizeof(*stts_entries)); /* one entry */
2276 return AVERROR(ENOMEM);
2277 stts_entries[0].count = track->sample_count;
2278 stts_entries[0].duration = 1;
2282 stts_entries = av_malloc_array(track->entry, sizeof(*stts_entries)); /* worst case */
2284 return AVERROR(ENOMEM);
2286 for (i = 0; i < track->entry; i++) {
2287 int duration = get_cluster_duration(track, i);
2288 if (i && duration == stts_entries[entries].duration) {
2289 stts_entries[entries].count++; /* compress */
2292 stts_entries[entries].duration = duration;
2293 stts_entries[entries].count = 1;
2296 entries++; /* last one */
2298 atom_size = 16 + (entries * 8);
2299 avio_wb32(pb, atom_size); /* size */
2300 ffio_wfourcc(pb, "stts");
2301 avio_wb32(pb, 0); /* version & flags */
2302 avio_wb32(pb, entries); /* entry count */
2303 for (i = 0; i < entries; i++) {
2304 avio_wb32(pb, stts_entries[i].count);
2305 avio_wb32(pb, stts_entries[i].duration);
2307 av_free(stts_entries);
2311 static int mov_write_dref_tag(AVIOContext *pb)
2313 avio_wb32(pb, 28); /* size */
2314 ffio_wfourcc(pb, "dref");
2315 avio_wb32(pb, 0); /* version & flags */
2316 avio_wb32(pb, 1); /* entry count */
2318 avio_wb32(pb, 0xc); /* size */
2319 //FIXME add the alis and rsrc atom
2320 ffio_wfourcc(pb, "url ");
2321 avio_wb32(pb, 1); /* version & flags */
2326 static int mov_preroll_write_stbl_atoms(AVIOContext *pb, MOVTrack *track)
2330 int16_t roll_distance;
2331 int group_description_index;
2334 struct sgpd_entry *sgpd_entries = NULL;
2339 const int OPUS_SEEK_PREROLL_MS = 80;
2340 int roll_samples = av_rescale_q(OPUS_SEEK_PREROLL_MS,
2341 (AVRational){1, 1000},
2342 (AVRational){1, 48000});
2347 sgpd_entries = av_malloc_array(track->entry, sizeof(*sgpd_entries));
2349 return AVERROR(ENOMEM);
2351 av_assert0(track->par->codec_id == AV_CODEC_ID_OPUS || track->par->codec_id == AV_CODEC_ID_AAC);
2353 if (track->par->codec_id == AV_CODEC_ID_OPUS) {
2354 for (i = 0; i < track->entry; i++) {
2355 int roll_samples_remaining = roll_samples;
2357 for (j = i - 1; j >= 0; j--) {
2358 roll_samples_remaining -= get_cluster_duration(track, j);
2360 if (roll_samples_remaining <= 0)
2363 /* We don't have enough preceeding samples to compute a valid
2364 roll_distance here, so this sample can't be independently
2366 if (roll_samples_remaining > 0)
2368 /* Verify distance is a maximum of 32 (2.5ms) packets. */
2370 return AVERROR_INVALIDDATA;
2371 if (i && distance == sgpd_entries[entries].roll_distance) {
2372 sgpd_entries[entries].count++;
2375 sgpd_entries[entries].count = 1;
2376 sgpd_entries[entries].roll_distance = distance;
2377 sgpd_entries[entries].group_description_index = distance ? ++group : 0;
2382 sgpd_entries[entries].count = track->sample_count;
2383 sgpd_entries[entries].roll_distance = 1;
2384 sgpd_entries[entries].group_description_index = ++group;
2389 av_free(sgpd_entries);
2393 /* Write sgpd tag */
2394 avio_wb32(pb, 24 + (group * 2)); /* size */
2395 ffio_wfourcc(pb, "sgpd");
2396 avio_wb32(pb, 1 << 24); /* fullbox */
2397 ffio_wfourcc(pb, "roll");
2398 avio_wb32(pb, 2); /* default_length */
2399 avio_wb32(pb, group); /* entry_count */
2400 for (i = 0; i < entries; i++) {
2401 if (sgpd_entries[i].group_description_index) {
2402 avio_wb16(pb, -sgpd_entries[i].roll_distance); /* roll_distance */
2406 /* Write sbgp tag */
2407 avio_wb32(pb, 20 + (entries * 8)); /* size */
2408 ffio_wfourcc(pb, "sbgp");
2409 avio_wb32(pb, 0); /* fullbox */
2410 ffio_wfourcc(pb, "roll");
2411 avio_wb32(pb, entries); /* entry_count */
2412 for (i = 0; i < entries; i++) {
2413 avio_wb32(pb, sgpd_entries[i].count); /* sample_count */
2414 avio_wb32(pb, sgpd_entries[i].group_description_index); /* group_description_index */
2417 av_free(sgpd_entries);
2421 static int mov_write_stbl_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
2423 int64_t pos = avio_tell(pb);
2426 avio_wb32(pb, 0); /* size */
2427 ffio_wfourcc(pb, "stbl");
2428 mov_write_stsd_tag(s, pb, mov, track);
2429 mov_write_stts_tag(pb, track);
2430 if ((track->par->codec_type == AVMEDIA_TYPE_VIDEO ||
2431 track->par->codec_tag == MKTAG('r','t','p',' ')) &&
2432 track->has_keyframes && track->has_keyframes < track->entry)
2433 mov_write_stss_tag(pb, track, MOV_SYNC_SAMPLE);
2434 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO && track->has_disposable)
2435 mov_write_sdtp_tag(pb, track);
2436 if (track->mode == MODE_MOV && track->flags & MOV_TRACK_STPS)
2437 mov_write_stss_tag(pb, track, MOV_PARTIAL_SYNC_SAMPLE);
2438 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO &&
2439 track->flags & MOV_TRACK_CTTS && track->entry) {
2441 if ((ret = mov_write_ctts_tag(s, pb, track)) < 0)
2444 mov_write_stsc_tag(pb, track);
2445 mov_write_stsz_tag(pb, track);
2446 mov_write_stco_tag(pb, track);
2447 if (track->cenc.aes_ctr) {
2448 ff_mov_cenc_write_stbl_atoms(&track->cenc, pb);
2450 if (track->par->codec_id == AV_CODEC_ID_OPUS || track->par->codec_id == AV_CODEC_ID_AAC) {
2451 mov_preroll_write_stbl_atoms(pb, track);
2453 return update_size(pb, pos);
2456 static int mov_write_dinf_tag(AVIOContext *pb)
2458 int64_t pos = avio_tell(pb);
2459 avio_wb32(pb, 0); /* size */
2460 ffio_wfourcc(pb, "dinf");
2461 mov_write_dref_tag(pb);
2462 return update_size(pb, pos);
2465 static int mov_write_nmhd_tag(AVIOContext *pb)
2468 ffio_wfourcc(pb, "nmhd");
2473 static int mov_write_tcmi_tag(AVIOContext *pb, MOVTrack *track)
2475 int64_t pos = avio_tell(pb);
2476 const char *font = "Lucida Grande";
2477 avio_wb32(pb, 0); /* size */
2478 ffio_wfourcc(pb, "tcmi"); /* timecode media information atom */
2479 avio_wb32(pb, 0); /* version & flags */
2480 avio_wb16(pb, 0); /* text font */
2481 avio_wb16(pb, 0); /* text face */
2482 avio_wb16(pb, 12); /* text size */
2483 avio_wb16(pb, 0); /* (unknown, not in the QT specs...) */
2484 avio_wb16(pb, 0x0000); /* text color (red) */
2485 avio_wb16(pb, 0x0000); /* text color (green) */
2486 avio_wb16(pb, 0x0000); /* text color (blue) */
2487 avio_wb16(pb, 0xffff); /* background color (red) */
2488 avio_wb16(pb, 0xffff); /* background color (green) */
2489 avio_wb16(pb, 0xffff); /* background color (blue) */
2490 avio_w8(pb, strlen(font)); /* font len (part of the pascal string) */
2491 avio_write(pb, font, strlen(font)); /* font name */
2492 return update_size(pb, pos);
2495 static int mov_write_gmhd_tag(AVIOContext *pb, MOVTrack *track)
2497 int64_t pos = avio_tell(pb);
2498 avio_wb32(pb, 0); /* size */
2499 ffio_wfourcc(pb, "gmhd");
2500 avio_wb32(pb, 0x18); /* gmin size */
2501 ffio_wfourcc(pb, "gmin");/* generic media info */
2502 avio_wb32(pb, 0); /* version & flags */
2503 avio_wb16(pb, 0x40); /* graphics mode = */
2504 avio_wb16(pb, 0x8000); /* opColor (r?) */
2505 avio_wb16(pb, 0x8000); /* opColor (g?) */
2506 avio_wb16(pb, 0x8000); /* opColor (b?) */
2507 avio_wb16(pb, 0); /* balance */
2508 avio_wb16(pb, 0); /* reserved */
2511 * This special text atom is required for
2512 * Apple Quicktime chapters. The contents
2513 * don't appear to be documented, so the
2514 * bytes are copied verbatim.
2516 if (track->tag != MKTAG('c','6','0','8')) {
2517 avio_wb32(pb, 0x2C); /* size */
2518 ffio_wfourcc(pb, "text");
2519 avio_wb16(pb, 0x01);
2520 avio_wb32(pb, 0x00);
2521 avio_wb32(pb, 0x00);
2522 avio_wb32(pb, 0x00);
2523 avio_wb32(pb, 0x01);
2524 avio_wb32(pb, 0x00);
2525 avio_wb32(pb, 0x00);
2526 avio_wb32(pb, 0x00);
2527 avio_wb32(pb, 0x00004000);
2528 avio_wb16(pb, 0x0000);
2531 if (track->par->codec_tag == MKTAG('t','m','c','d')) {
2532 int64_t tmcd_pos = avio_tell(pb);
2533 avio_wb32(pb, 0); /* size */
2534 ffio_wfourcc(pb, "tmcd");
2535 mov_write_tcmi_tag(pb, track);
2536 update_size(pb, tmcd_pos);
2537 } else if (track->par->codec_tag == MKTAG('g','p','m','d')) {
2538 int64_t gpmd_pos = avio_tell(pb);
2539 avio_wb32(pb, 0); /* size */
2540 ffio_wfourcc(pb, "gpmd");
2541 avio_wb32(pb, 0); /* version */
2542 update_size(pb, gpmd_pos);
2544 return update_size(pb, pos);
2547 static int mov_write_smhd_tag(AVIOContext *pb)
2549 avio_wb32(pb, 16); /* size */
2550 ffio_wfourcc(pb, "smhd");
2551 avio_wb32(pb, 0); /* version & flags */
2552 avio_wb16(pb, 0); /* reserved (balance, normally = 0) */
2553 avio_wb16(pb, 0); /* reserved */
2557 static int mov_write_vmhd_tag(AVIOContext *pb)
2559 avio_wb32(pb, 0x14); /* size (always 0x14) */
2560 ffio_wfourcc(pb, "vmhd");
2561 avio_wb32(pb, 0x01); /* version & flags */
2562 avio_wb64(pb, 0); /* reserved (graphics mode = copy) */
2566 static int is_clcp_track(MOVTrack *track)
2568 return track->tag == MKTAG('c','7','0','8') ||
2569 track->tag == MKTAG('c','6','0','8');
2572 static int mov_write_hdlr_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
2574 MOVMuxContext *mov = s->priv_data;
2575 const char *hdlr, *descr = NULL, *hdlr_type = NULL;
2576 int64_t pos = avio_tell(pb);
2580 descr = "DataHandler";
2583 hdlr = (track->mode == MODE_MOV) ? "mhlr" : "\0\0\0\0";
2584 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
2586 descr = "VideoHandler";
2587 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
2589 descr = "SoundHandler";
2590 } else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE) {
2591 if (is_clcp_track(track)) {
2593 descr = "ClosedCaptionHandler";
2595 if (track->tag == MKTAG('t','x','3','g')) {
2597 } else if (track->tag == MKTAG('m','p','4','s')) {
2602 descr = "SubtitleHandler";
2604 } else if (track->par->codec_tag == MKTAG('r','t','p',' ')) {
2606 descr = "HintHandler";
2607 } else if (track->par->codec_tag == MKTAG('t','m','c','d')) {
2609 descr = "TimeCodeHandler";
2610 } else if (track->par->codec_tag == MKTAG('g','p','m','d')) {
2612 descr = "GoPro MET"; // GoPro Metadata
2614 av_log(s, AV_LOG_WARNING,
2615 "Unknown hldr_type for %s, writing dummy values\n",
2616 av_fourcc2str(track->par->codec_tag));
2619 // hdlr.name is used by some players to identify the content title
2620 // of the track. So if an alternate handler description is
2621 // specified, use it.
2622 AVDictionaryEntry *t;
2623 t = av_dict_get(track->st->metadata, "handler_name", NULL, 0);
2624 if (t && utf8len(t->value))
2629 if (mov->empty_hdlr_name) /* expressly allowed by QTFF and not prohibited in ISO 14496-12 8.4.3.3 */
2632 avio_wb32(pb, 0); /* size */
2633 ffio_wfourcc(pb, "hdlr");
2634 avio_wb32(pb, 0); /* Version & flags */
2635 avio_write(pb, hdlr, 4); /* handler */
2636 ffio_wfourcc(pb, hdlr_type); /* handler type */
2637 avio_wb32(pb, 0); /* reserved */
2638 avio_wb32(pb, 0); /* reserved */
2639 avio_wb32(pb, 0); /* reserved */
2640 if (!track || track->mode == MODE_MOV)
2641 avio_w8(pb, strlen(descr)); /* pascal string */
2642 avio_write(pb, descr, strlen(descr)); /* handler description */
2643 if (track && track->mode != MODE_MOV)
2644 avio_w8(pb, 0); /* c string */
2645 return update_size(pb, pos);
2648 static int mov_write_hmhd_tag(AVIOContext *pb)
2650 /* This atom must be present, but leaving the values at zero
2651 * seems harmless. */
2652 avio_wb32(pb, 28); /* size */
2653 ffio_wfourcc(pb, "hmhd");
2654 avio_wb32(pb, 0); /* version, flags */
2655 avio_wb16(pb, 0); /* maxPDUsize */
2656 avio_wb16(pb, 0); /* avgPDUsize */
2657 avio_wb32(pb, 0); /* maxbitrate */
2658 avio_wb32(pb, 0); /* avgbitrate */
2659 avio_wb32(pb, 0); /* reserved */
2663 static int mov_write_minf_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
2665 int64_t pos = avio_tell(pb);
2668 avio_wb32(pb, 0); /* size */
2669 ffio_wfourcc(pb, "minf");
2670 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO)
2671 mov_write_vmhd_tag(pb);
2672 else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
2673 mov_write_smhd_tag(pb);
2674 else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE) {
2675 if (track->tag == MKTAG('t','e','x','t') || is_clcp_track(track)) {
2676 mov_write_gmhd_tag(pb, track);
2678 mov_write_nmhd_tag(pb);
2680 } else if (track->tag == MKTAG('r','t','p',' ')) {
2681 mov_write_hmhd_tag(pb);
2682 } else if (track->tag == MKTAG('t','m','c','d')) {
2683 if (track->mode != MODE_MOV)
2684 mov_write_nmhd_tag(pb);
2686 mov_write_gmhd_tag(pb, track);
2687 } else if (track->tag == MKTAG('g','p','m','d')) {
2688 mov_write_gmhd_tag(pb, track);
2690 if (track->mode == MODE_MOV) /* ISO 14496-12 8.4.3.1 specifies hdlr only within mdia or meta boxes */
2691 mov_write_hdlr_tag(s, pb, NULL);
2692 mov_write_dinf_tag(pb);
2693 if ((ret = mov_write_stbl_tag(s, pb, mov, track)) < 0)
2695 return update_size(pb, pos);
2698 static int mov_write_mdhd_tag(AVIOContext *pb, MOVMuxContext *mov,
2701 int version = track->track_duration < INT32_MAX ? 0 : 1;
2703 if (track->mode == MODE_ISM)
2706 (version == 1) ? avio_wb32(pb, 44) : avio_wb32(pb, 32); /* size */
2707 ffio_wfourcc(pb, "mdhd");
2708 avio_w8(pb, version);
2709 avio_wb24(pb, 0); /* flags */
2711 avio_wb64(pb, track->time);
2712 avio_wb64(pb, track->time);
2714 avio_wb32(pb, track->time); /* creation time */
2715 avio_wb32(pb, track->time); /* modification time */
2717 avio_wb32(pb, track->timescale); /* time scale (sample rate for audio) */
2718 if (!track->entry && mov->mode == MODE_ISM)
2719 (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
2720 else if (!track->entry)
2721 (version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0);
2723 (version == 1) ? avio_wb64(pb, track->track_duration) : avio_wb32(pb, track->track_duration); /* duration */
2724 avio_wb16(pb, track->language); /* language */
2725 avio_wb16(pb, 0); /* reserved (quality) */
2727 if (version != 0 && track->mode == MODE_MOV) {
2728 av_log(NULL, AV_LOG_ERROR,
2729 "FATAL error, file duration too long for timebase, this file will not be\n"
2730 "playable with quicktime. Choose a different timebase or a different\n"
2731 "container format\n");
2737 static int mov_write_mdia_tag(AVFormatContext *s, AVIOContext *pb,
2738 MOVMuxContext *mov, MOVTrack *track)
2740 int64_t pos = avio_tell(pb);
2743 avio_wb32(pb, 0); /* size */
2744 ffio_wfourcc(pb, "mdia");
2745 mov_write_mdhd_tag(pb, mov, track);
2746 mov_write_hdlr_tag(s, pb, track);
2747 if ((ret = mov_write_minf_tag(s, pb, mov, track)) < 0)
2749 return update_size(pb, pos);
2752 /* transformation matrix
2756 static void write_matrix(AVIOContext *pb, int16_t a, int16_t b, int16_t c,
2757 int16_t d, int16_t tx, int16_t ty)
2759 avio_wb32(pb, a << 16); /* 16.16 format */
2760 avio_wb32(pb, b << 16); /* 16.16 format */
2761 avio_wb32(pb, 0); /* u in 2.30 format */
2762 avio_wb32(pb, c << 16); /* 16.16 format */
2763 avio_wb32(pb, d << 16); /* 16.16 format */
2764 avio_wb32(pb, 0); /* v in 2.30 format */
2765 avio_wb32(pb, tx << 16); /* 16.16 format */
2766 avio_wb32(pb, ty << 16); /* 16.16 format */
2767 avio_wb32(pb, 1 << 30); /* w in 2.30 format */
2770 static int mov_write_tkhd_tag(AVIOContext *pb, MOVMuxContext *mov,
2771 MOVTrack *track, AVStream *st)
2773 int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE,
2774 track->timescale, AV_ROUND_UP);
2775 int version = duration < INT32_MAX ? 0 : 1;
2776 int flags = MOV_TKHD_FLAG_IN_MOVIE;
2780 uint32_t *display_matrix = NULL;
2781 int display_matrix_size, i;
2784 if (mov->per_stream_grouping)
2787 group = st->codecpar->codec_type;
2789 display_matrix = (uint32_t*)av_stream_get_side_data(st, AV_PKT_DATA_DISPLAYMATRIX,
2790 &display_matrix_size);
2791 if (display_matrix && display_matrix_size < 9 * sizeof(*display_matrix))
2792 display_matrix = NULL;
2795 if (track->flags & MOV_TRACK_ENABLED)
2796 flags |= MOV_TKHD_FLAG_ENABLED;
2798 if (track->mode == MODE_ISM)
2801 (version == 1) ? avio_wb32(pb, 104) : avio_wb32(pb, 92); /* size */
2802 ffio_wfourcc(pb, "tkhd");
2803 avio_w8(pb, version);
2804 avio_wb24(pb, flags);
2806 avio_wb64(pb, track->time);
2807 avio_wb64(pb, track->time);
2809 avio_wb32(pb, track->time); /* creation time */
2810 avio_wb32(pb, track->time); /* modification time */
2812 avio_wb32(pb, track->track_id); /* track-id */
2813 avio_wb32(pb, 0); /* reserved */
2814 if (!track->entry && mov->mode == MODE_ISM)
2815 (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
2816 else if (!track->entry)
2817 (version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0);
2819 (version == 1) ? avio_wb64(pb, duration) : avio_wb32(pb, duration);
2821 avio_wb32(pb, 0); /* reserved */
2822 avio_wb32(pb, 0); /* reserved */
2823 avio_wb16(pb, 0); /* layer */
2824 avio_wb16(pb, group); /* alternate group) */
2825 /* Volume, only for audio */
2826 if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
2827 avio_wb16(pb, 0x0100);
2830 avio_wb16(pb, 0); /* reserved */
2832 /* Matrix structure */
2833 #if FF_API_OLD_ROTATE_API
2834 if (st && st->metadata) {
2835 AVDictionaryEntry *rot = av_dict_get(st->metadata, "rotate", NULL, 0);
2836 rotation = (rot && rot->value) ? atoi(rot->value) : 0;
2839 if (display_matrix) {
2840 for (i = 0; i < 9; i++)
2841 avio_wb32(pb, display_matrix[i]);
2842 #if FF_API_OLD_ROTATE_API
2843 } else if (rotation == 90) {
2844 write_matrix(pb, 0, 1, -1, 0, track->par->height, 0);
2845 } else if (rotation == 180) {
2846 write_matrix(pb, -1, 0, 0, -1, track->par->width, track->par->height);
2847 } else if (rotation == 270) {
2848 write_matrix(pb, 0, -1, 1, 0, 0, track->par->width);
2851 write_matrix(pb, 1, 0, 0, 1, 0, 0);
2853 /* Track width and height, for visual only */
2854 if (st && (track->par->codec_type == AVMEDIA_TYPE_VIDEO ||
2855 track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)) {
2856 int64_t track_width_1616;
2857 if (track->mode == MODE_MOV) {
2858 track_width_1616 = track->par->width * 0x10000ULL;
2860 track_width_1616 = av_rescale(st->sample_aspect_ratio.num,
2861 track->par->width * 0x10000LL,
2862 st->sample_aspect_ratio.den);
2863 if (!track_width_1616 ||
2864 track->height != track->par->height ||
2865 track_width_1616 > UINT32_MAX)
2866 track_width_1616 = track->par->width * 0x10000ULL;
2868 if (track_width_1616 > UINT32_MAX) {
2869 av_log(mov->fc, AV_LOG_WARNING, "track width is too large\n");
2870 track_width_1616 = 0;
2872 avio_wb32(pb, track_width_1616);
2873 if (track->height > 0xFFFF) {
2874 av_log(mov->fc, AV_LOG_WARNING, "track height is too large\n");
2877 avio_wb32(pb, track->height * 0x10000U);
2885 static int mov_write_tapt_tag(AVIOContext *pb, MOVTrack *track)
2887 int32_t width = av_rescale(track->par->sample_aspect_ratio.num, track->par->width,
2888 track->par->sample_aspect_ratio.den);
2890 int64_t pos = avio_tell(pb);
2892 avio_wb32(pb, 0); /* size */
2893 ffio_wfourcc(pb, "tapt");
2896 ffio_wfourcc(pb, "clef");
2898 avio_wb32(pb, width << 16);
2899 avio_wb32(pb, track->par->height << 16);
2902 ffio_wfourcc(pb, "prof");
2904 avio_wb32(pb, width << 16);
2905 avio_wb32(pb, track->par->height << 16);
2908 ffio_wfourcc(pb, "enof");
2910 avio_wb32(pb, track->par->width << 16);
2911 avio_wb32(pb, track->par->height << 16);
2913 return update_size(pb, pos);
2916 // This box seems important for the psp playback ... without it the movie seems to hang
2917 static int mov_write_edts_tag(AVIOContext *pb, MOVMuxContext *mov,
2920 int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE,
2921 track->timescale, AV_ROUND_UP);
2922 int version = duration < INT32_MAX ? 0 : 1;
2923 int entry_size, entry_count, size;
2924 int64_t delay, start_ct = track->start_cts;
2925 int64_t start_dts = track->start_dts;
2928 if (start_dts != track->cluster[0].dts || start_ct != track->cluster[0].cts) {
2930 av_log(mov->fc, AV_LOG_DEBUG,
2931 "EDTS using dts:%"PRId64" cts:%d instead of dts:%"PRId64" cts:%"PRId64" tid:%d\n",
2932 track->cluster[0].dts, track->cluster[0].cts,
2933 start_dts, start_ct, track->track_id);
2934 start_dts = track->cluster[0].dts;
2935 start_ct = track->cluster[0].cts;
2939 delay = av_rescale_rnd(start_dts + start_ct, MOV_TIMESCALE,
2940 track->timescale, AV_ROUND_DOWN);
2941 version |= delay < INT32_MAX ? 0 : 1;
2943 entry_size = (version == 1) ? 20 : 12;
2944 entry_count = 1 + (delay > 0);
2945 size = 24 + entry_count * entry_size;
2947 /* write the atom data */
2948 avio_wb32(pb, size);
2949 ffio_wfourcc(pb, "edts");
2950 avio_wb32(pb, size - 8);
2951 ffio_wfourcc(pb, "elst");
2952 avio_w8(pb, version);
2953 avio_wb24(pb, 0); /* flags */
2955 avio_wb32(pb, entry_count);
2956 if (delay > 0) { /* add an empty edit to delay presentation */
2957 /* In the positive delay case, the delay includes the cts
2958 * offset, and the second edit list entry below trims out
2959 * the same amount from the actual content. This makes sure
2960 * that the offset last sample is included in the edit
2961 * list duration as well. */
2963 avio_wb64(pb, delay);
2966 avio_wb32(pb, delay);
2969 avio_wb32(pb, 0x00010000);
2971 /* Avoid accidentally ending up with start_ct = -1 which has got a
2972 * special meaning. Normally start_ct should end up positive or zero
2973 * here, but use FFMIN in case dts is a small positive integer
2974 * rounded to 0 when represented in MOV_TIMESCALE units. */
2975 av_assert0(av_rescale_rnd(start_dts, MOV_TIMESCALE, track->timescale, AV_ROUND_DOWN) <= 0);
2976 start_ct = -FFMIN(start_dts, 0);
2977 /* Note, this delay is calculated from the pts of the first sample,
2978 * ensuring that we don't reduce the duration for cases with
2983 /* For fragmented files, we don't know the full length yet. Setting
2984 * duration to 0 allows us to only specify the offset, including
2985 * the rest of the content (from all future fragments) without specifying
2986 * an explicit duration. */
2987 if (mov->flags & FF_MOV_FLAG_FRAGMENT)
2992 avio_wb64(pb, duration);
2993 avio_wb64(pb, start_ct);
2995 avio_wb32(pb, duration);
2996 avio_wb32(pb, start_ct);
2998 avio_wb32(pb, 0x00010000);
3002 static int mov_write_tref_tag(AVIOContext *pb, MOVTrack *track)
3004 avio_wb32(pb, 20); // size
3005 ffio_wfourcc(pb, "tref");
3006 avio_wb32(pb, 12); // size (subatom)
3007 avio_wl32(pb, track->tref_tag);
3008 avio_wb32(pb, track->tref_id);
3012 // goes at the end of each track! ... Critical for PSP playback ("Incompatible data" without it)
3013 static int mov_write_uuid_tag_psp(AVIOContext *pb, MOVTrack *mov)
3015 avio_wb32(pb, 0x34); /* size ... reports as 28 in mp4box! */
3016 ffio_wfourcc(pb, "uuid");
3017 ffio_wfourcc(pb, "USMT");
3018 avio_wb32(pb, 0x21d24fce);
3019 avio_wb32(pb, 0xbb88695c);
3020 avio_wb32(pb, 0xfac9c740);
3021 avio_wb32(pb, 0x1c); // another size here!
3022 ffio_wfourcc(pb, "MTDT");
3023 avio_wb32(pb, 0x00010012);
3024 avio_wb32(pb, 0x0a);
3025 avio_wb32(pb, 0x55c40000);
3031 static int mov_write_udta_sdp(AVIOContext *pb, MOVTrack *track)
3033 AVFormatContext *ctx = track->rtp_ctx;
3034 char buf[1000] = "";
3037 ff_sdp_write_media(buf, sizeof(buf), ctx->streams[0], track->src_track,
3038 NULL, NULL, 0, 0, ctx);
3039 av_strlcatf(buf, sizeof(buf), "a=control:streamid=%d\r\n", track->track_id);
3042 avio_wb32(pb, len + 24);
3043 ffio_wfourcc(pb, "udta");
3044 avio_wb32(pb, len + 16);
3045 ffio_wfourcc(pb, "hnti");
3046 avio_wb32(pb, len + 8);
3047 ffio_wfourcc(pb, "sdp ");
3048 avio_write(pb, buf, len);
3052 static int mov_write_track_metadata(AVIOContext *pb, AVStream *st,
3053 const char *tag, const char *str)
3055 int64_t pos = avio_tell(pb);
3056 AVDictionaryEntry *t = av_dict_get(st->metadata, str, NULL, 0);
3057 if (!t || !utf8len(t->value))
3060 avio_wb32(pb, 0); /* size */
3061 ffio_wfourcc(pb, tag); /* type */
3062 avio_write(pb, t->value, strlen(t->value)); /* UTF8 string value */
3063 return update_size(pb, pos);
3066 static int mov_write_track_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
3069 AVIOContext *pb_buf;
3076 ret = avio_open_dyn_buf(&pb_buf);
3080 if (mov->mode & (MODE_MP4|MODE_MOV))
3081 mov_write_track_metadata(pb_buf, st, "name", "title");
3083 if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) {
3084 avio_wb32(pb, size + 8);
3085 ffio_wfourcc(pb, "udta");
3086 avio_write(pb, buf, size);
3093 static int mov_write_trak_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov,
3094 MOVTrack *track, AVStream *st)
3096 int64_t pos = avio_tell(pb);
3097 int entry_backup = track->entry;
3098 int chunk_backup = track->chunkCount;
3101 /* If we want to have an empty moov, but some samples already have been
3102 * buffered (delay_moov), pretend that no samples have been written yet. */
3103 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV)
3104 track->chunkCount = track->entry = 0;
3106 avio_wb32(pb, 0); /* size */
3107 ffio_wfourcc(pb, "trak");
3108 mov_write_tkhd_tag(pb, mov, track, st);
3110 av_assert2(mov->use_editlist >= 0);
3112 if (track->start_dts != AV_NOPTS_VALUE) {
3113 if (mov->use_editlist)
3114 mov_write_edts_tag(pb, mov, track); // PSP Movies and several other cases require edts box
3115 else if ((track->entry && track->cluster[0].dts) || track->mode == MODE_PSP || is_clcp_track(track))
3116 av_log(mov->fc, AV_LOG_WARNING,
3117 "Not writing any edit list even though one would have been required\n");
3120 if (track->tref_tag)
3121 mov_write_tref_tag(pb, track);
3123 if ((ret = mov_write_mdia_tag(s, pb, mov, track)) < 0)
3125 if (track->mode == MODE_PSP)
3126 mov_write_uuid_tag_psp(pb, track); // PSP Movies require this uuid box
3127 if (track->tag == MKTAG('r','t','p',' '))
3128 mov_write_udta_sdp(pb, track);
3129 if (track->mode == MODE_MOV) {
3130 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
3131 double sample_aspect_ratio = av_q2d(st->sample_aspect_ratio);
3132 if (st->sample_aspect_ratio.num && 1.0 != sample_aspect_ratio) {
3133 mov_write_tapt_tag(pb, track);
3136 if (is_clcp_track(track) && st->sample_aspect_ratio.num) {
3137 mov_write_tapt_tag(pb, track);
3140 mov_write_track_udta_tag(pb, mov, st);
3141 track->entry = entry_backup;
3142 track->chunkCount = chunk_backup;
3143 return update_size(pb, pos);
3146 static int mov_write_iods_tag(AVIOContext *pb, MOVMuxContext *mov)
3148 int i, has_audio = 0, has_video = 0;
3149 int64_t pos = avio_tell(pb);
3150 int audio_profile = mov->iods_audio_profile;
3151 int video_profile = mov->iods_video_profile;
3152 for (i = 0; i < mov->nb_streams; i++) {
3153 if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
3154 has_audio |= mov->tracks[i].par->codec_type == AVMEDIA_TYPE_AUDIO;
3155 has_video |= mov->tracks[i].par->codec_type == AVMEDIA_TYPE_VIDEO;
3158 if (audio_profile < 0)
3159 audio_profile = 0xFF - has_audio;
3160 if (video_profile < 0)
3161 video_profile = 0xFF - has_video;
3162 avio_wb32(pb, 0x0); /* size */
3163 ffio_wfourcc(pb, "iods");
3164 avio_wb32(pb, 0); /* version & flags */
3165 put_descr(pb, 0x10, 7);
3166 avio_wb16(pb, 0x004f);
3169 avio_w8(pb, audio_profile);
3170 avio_w8(pb, video_profile);
3172 return update_size(pb, pos);
3175 static int mov_write_trex_tag(AVIOContext *pb, MOVTrack *track)
3177 avio_wb32(pb, 0x20); /* size */
3178 ffio_wfourcc(pb, "trex");
3179 avio_wb32(pb, 0); /* version & flags */
3180 avio_wb32(pb, track->track_id); /* track ID */
3181 avio_wb32(pb, 1); /* default sample description index */
3182 avio_wb32(pb, 0); /* default sample duration */
3183 avio_wb32(pb, 0); /* default sample size */
3184 avio_wb32(pb, 0); /* default sample flags */
3188 static int mov_write_mvex_tag(AVIOContext *pb, MOVMuxContext *mov)
3190 int64_t pos = avio_tell(pb);
3192 avio_wb32(pb, 0x0); /* size */
3193 ffio_wfourcc(pb, "mvex");
3194 for (i = 0; i < mov->nb_streams; i++)
3195 mov_write_trex_tag(pb, &mov->tracks[i]);
3196 return update_size(pb, pos);
3199 static int mov_write_mvhd_tag(AVIOContext *pb, MOVMuxContext *mov)
3201 int max_track_id = 1, i;
3202 int64_t max_track_len = 0;
3205 for (i = 0; i < mov->nb_streams; i++) {
3206 if (mov->tracks[i].entry > 0 && mov->tracks[i].timescale) {
3207 int64_t max_track_len_temp = av_rescale_rnd(mov->tracks[i].track_duration,
3209 mov->tracks[i].timescale,
3211 if (max_track_len < max_track_len_temp)
3212 max_track_len = max_track_len_temp;
3213 if (max_track_id < mov->tracks[i].track_id)
3214 max_track_id = mov->tracks[i].track_id;
3217 /* If using delay_moov, make sure the output is the same as if no
3218 * samples had been written yet. */
3219 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
3224 version = max_track_len < UINT32_MAX ? 0 : 1;
3225 avio_wb32(pb, version == 1 ? 120 : 108); /* size */
3227 ffio_wfourcc(pb, "mvhd");
3228 avio_w8(pb, version);
3229 avio_wb24(pb, 0); /* flags */
3231 avio_wb64(pb, mov->time);
3232 avio_wb64(pb, mov->time);
3234 avio_wb32(pb, mov->time); /* creation time */
3235 avio_wb32(pb, mov->time); /* modification time */
3237 avio_wb32(pb, MOV_TIMESCALE);
3238 (version == 1) ? avio_wb64(pb, max_track_len) : avio_wb32(pb, max_track_len); /* duration of longest track */
3240 avio_wb32(pb, 0x00010000); /* reserved (preferred rate) 1.0 = normal */
3241 avio_wb16(pb, 0x0100); /* reserved (preferred volume) 1.0 = normal */
3242 avio_wb16(pb, 0); /* reserved */
3243 avio_wb32(pb, 0); /* reserved */
3244 avio_wb32(pb, 0); /* reserved */
3246 /* Matrix structure */
3247 write_matrix(pb, 1, 0, 0, 1, 0, 0);
3249 avio_wb32(pb, 0); /* reserved (preview time) */
3250 avio_wb32(pb, 0); /* reserved (preview duration) */
3251 avio_wb32(pb, 0); /* reserved (poster time) */
3252 avio_wb32(pb, 0); /* reserved (selection time) */
3253 avio_wb32(pb, 0); /* reserved (selection duration) */
3254 avio_wb32(pb, 0); /* reserved (current time) */
3255 avio_wb32(pb, max_track_id + 1); /* Next track id */
3259 static int mov_write_itunes_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov,
3262 avio_wb32(pb, 33); /* size */
3263 ffio_wfourcc(pb, "hdlr");
3266 ffio_wfourcc(pb, "mdir");
3267 ffio_wfourcc(pb, "appl");
3274 /* helper function to write a data tag with the specified string as data */
3275 static int mov_write_string_data_tag(AVIOContext *pb, const char *data, int lang, int long_style)
3278 int size = 16 + strlen(data);
3279 avio_wb32(pb, size); /* size */
3280 ffio_wfourcc(pb, "data");
3283 avio_write(pb, data, strlen(data));
3287 lang = ff_mov_iso639_to_lang("und", 1);
3288 avio_wb16(pb, strlen(data)); /* string length */
3289 avio_wb16(pb, lang);
3290 avio_write(pb, data, strlen(data));
3291 return strlen(data) + 4;
3295 static int mov_write_string_tag(AVIOContext *pb, const char *name,
3296 const char *value, int lang, int long_style)
3299 if (value && value[0]) {
3300 int64_t pos = avio_tell(pb);
3301 avio_wb32(pb, 0); /* size */
3302 ffio_wfourcc(pb, name);
3303 mov_write_string_data_tag(pb, value, lang, long_style);
3304 size = update_size(pb, pos);
3309 static AVDictionaryEntry *get_metadata_lang(AVFormatContext *s,
3310 const char *tag, int *lang)
3313 AVDictionaryEntry *t, *t2 = NULL;
3318 if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
3321 len = strlen(t->key);
3322 snprintf(tag2, sizeof(tag2), "%s-", tag);
3323 while ((t2 = av_dict_get(s->metadata, tag2, t2, AV_DICT_IGNORE_SUFFIX))) {
3324 len2 = strlen(t2->key);
3325 if (len2 == len + 4 && !strcmp(t->value, t2->value)
3326 && (l = ff_mov_iso639_to_lang(&t2->key[len2 - 3], 1)) >= 0) {
3334 static int mov_write_string_metadata(AVFormatContext *s, AVIOContext *pb,
3335 const char *name, const char *tag,
3339 AVDictionaryEntry *t = get_metadata_lang(s, tag, &lang);
3342 return mov_write_string_tag(pb, name, t->value, lang, long_style);
3345 /* iTunes bpm number */
3346 static int mov_write_tmpo_tag(AVIOContext *pb, AVFormatContext *s)
3348 AVDictionaryEntry *t = av_dict_get(s->metadata, "tmpo", NULL, 0);
3349 int size = 0, tmpo = t ? atoi(t->value) : 0;
3352 avio_wb32(pb, size);
3353 ffio_wfourcc(pb, "tmpo");
3354 avio_wb32(pb, size-8); /* size */
3355 ffio_wfourcc(pb, "data");
3356 avio_wb32(pb, 0x15); //type specifier
3358 avio_wb16(pb, tmpo); // data
3363 /* 3GPP TS 26.244 */
3364 static int mov_write_loci_tag(AVFormatContext *s, AVIOContext *pb)
3367 int64_t pos = avio_tell(pb);
3368 double latitude, longitude, altitude;
3369 int32_t latitude_fix, longitude_fix, altitude_fix;
3370 AVDictionaryEntry *t = get_metadata_lang(s, "location", &lang);
3371 const char *ptr, *place = "";
3373 static const char *astronomical_body = "earth";
3378 longitude = strtod(ptr, &end);
3380 av_log(s, AV_LOG_WARNING, "malformed location metadata\n");
3384 latitude = strtod(ptr, &end);
3386 av_log(s, AV_LOG_WARNING, "malformed location metadata\n");
3390 altitude = strtod(ptr, &end);
3391 /* If no altitude was present, the default 0 should be fine */
3395 latitude_fix = (int32_t) ((1 << 16) * latitude);
3396 longitude_fix = (int32_t) ((1 << 16) * longitude);
3397 altitude_fix = (int32_t) ((1 << 16) * altitude);
3399 avio_wb32(pb, 0); /* size */
3400 ffio_wfourcc(pb, "loci"); /* type */
3401 avio_wb32(pb, 0); /* version + flags */
3402 avio_wb16(pb, lang);
3403 avio_write(pb, place, strlen(place) + 1);
3404 avio_w8(pb, 0); /* role of place (0 == shooting location, 1 == real location, 2 == fictional location) */
3405 avio_wb32(pb, latitude_fix);
3406 avio_wb32(pb, longitude_fix);
3407 avio_wb32(pb, altitude_fix);
3408 avio_write(pb, astronomical_body, strlen(astronomical_body) + 1);
3409 avio_w8(pb, 0); /* additional notes, null terminated string */
3411 return update_size(pb, pos);
3414 /* iTunes track or disc number */
3415 static int mov_write_trkn_tag(AVIOContext *pb, MOVMuxContext *mov,
3416 AVFormatContext *s, int disc)
3418 AVDictionaryEntry *t = av_dict_get(s->metadata,
3419 disc ? "disc" : "track",
3421 int size = 0, track = t ? atoi(t->value) : 0;
3424 char *slash = strchr(t->value, '/');
3426 tracks = atoi(slash + 1);
3427 avio_wb32(pb, 32); /* size */
3428 ffio_wfourcc(pb, disc ? "disk" : "trkn");
3429 avio_wb32(pb, 24); /* size */
3430 ffio_wfourcc(pb, "data");
3431 avio_wb32(pb, 0); // 8 bytes empty
3433 avio_wb16(pb, 0); // empty
3434 avio_wb16(pb, track); // track / disc number
3435 avio_wb16(pb, tracks); // total track / disc number
3436 avio_wb16(pb, 0); // empty
3442 static int mov_write_int8_metadata(AVFormatContext *s, AVIOContext *pb,
3443 const char *name, const char *tag,
3446 AVDictionaryEntry *t = NULL;
3448 int size = 24 + len;
3450 if (len != 1 && len != 4)
3453 if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
3455 num = atoi(t->value);
3457 avio_wb32(pb, size);
3458 ffio_wfourcc(pb, name);
3459 avio_wb32(pb, size - 8);
3460 ffio_wfourcc(pb, "data");
3461 avio_wb32(pb, 0x15);
3463 if (len==4) avio_wb32(pb, num);
3464 else avio_w8 (pb, num);
3469 static int mov_write_covr(AVIOContext *pb, AVFormatContext *s)
3471 MOVMuxContext *mov = s->priv_data;
3475 for (i = 0; i < s->nb_streams; i++) {
3476 MOVTrack *trk = &mov->tracks[i];
3478 if (!is_cover_image(trk->st) || trk->cover_image.size <= 0)
3482 pos = avio_tell(pb);
3484 ffio_wfourcc(pb, "covr");
3486 avio_wb32(pb, 16 + trk->cover_image.size);
3487 ffio_wfourcc(pb, "data");
3488 avio_wb32(pb, trk->tag);
3490 avio_write(pb, trk->cover_image.data, trk->cover_image.size);
3493 return pos ? update_size(pb, pos) : 0;
3496 /* iTunes meta data list */
3497 static int mov_write_ilst_tag(AVIOContext *pb, MOVMuxContext *mov,
3500 int64_t pos = avio_tell(pb);
3501 avio_wb32(pb, 0); /* size */
3502 ffio_wfourcc(pb, "ilst");
3503 mov_write_string_metadata(s, pb, "\251nam", "title" , 1);
3504 mov_write_string_metadata(s, pb, "\251ART", "artist" , 1);
3505 mov_write_string_metadata(s, pb, "aART", "album_artist", 1);
3506 mov_write_string_metadata(s, pb, "\251wrt", "composer" , 1);
3507 mov_write_string_metadata(s, pb, "\251alb", "album" , 1);
3508 mov_write_string_metadata(s, pb, "\251day", "date" , 1);
3509 if (!mov_write_string_metadata(s, pb, "\251too", "encoding_tool", 1)) {
3510 if (!(s->flags & AVFMT_FLAG_BITEXACT))
3511 mov_write_string_tag(pb, "\251too", LIBAVFORMAT_IDENT, 0, 1);
3513 mov_write_string_metadata(s, pb, "\251cmt", "comment" , 1);
3514 mov_write_string_metadata(s, pb, "\251gen", "genre" , 1);
3515 mov_write_string_metadata(s, pb, "cprt", "copyright", 1);
3516 mov_write_string_metadata(s, pb, "\251grp", "grouping" , 1);
3517 mov_write_string_metadata(s, pb, "\251lyr", "lyrics" , 1);
3518 mov_write_string_metadata(s, pb, "desc", "description",1);
3519 mov_write_string_metadata(s, pb, "ldes", "synopsis" , 1);
3520 mov_write_string_metadata(s, pb, "tvsh", "show" , 1);
3521 mov_write_string_metadata(s, pb, "tven", "episode_id",1);
3522 mov_write_string_metadata(s, pb, "tvnn", "network" , 1);
3523 mov_write_string_metadata(s, pb, "keyw", "keywords" , 1);
3524 mov_write_int8_metadata (s, pb, "tves", "episode_sort",4);
3525 mov_write_int8_metadata (s, pb, "tvsn", "season_number",4);
3526 mov_write_int8_metadata (s, pb, "stik", "media_type",1);
3527 mov_write_int8_metadata (s, pb, "hdvd", "hd_video", 1);
3528 mov_write_int8_metadata (s, pb, "pgap", "gapless_playback",1);
3529 mov_write_int8_metadata (s, pb, "cpil", "compilation", 1);
3530 mov_write_covr(pb, s);
3531 mov_write_trkn_tag(pb, mov, s, 0); // track number
3532 mov_write_trkn_tag(pb, mov, s, 1); // disc number
3533 mov_write_tmpo_tag(pb, s);
3534 return update_size(pb, pos);
3537 static int mov_write_mdta_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov,
3540 avio_wb32(pb, 33); /* size */
3541 ffio_wfourcc(pb, "hdlr");
3544 ffio_wfourcc(pb, "mdta");
3552 static int mov_write_mdta_keys_tag(AVIOContext *pb, MOVMuxContext *mov,
3555 AVDictionaryEntry *t = NULL;
3556 int64_t pos = avio_tell(pb);
3557 int64_t curpos, entry_pos;
3560 avio_wb32(pb, 0); /* size */
3561 ffio_wfourcc(pb, "keys");
3563 entry_pos = avio_tell(pb);
3564 avio_wb32(pb, 0); /* entry count */
3566 while (t = av_dict_get(s->metadata, "", t, AV_DICT_IGNORE_SUFFIX)) {
3567 avio_wb32(pb, strlen(t->key) + 8);
3568 ffio_wfourcc(pb, "mdta");
3569 avio_write(pb, t->key, strlen(t->key));
3572 curpos = avio_tell(pb);
3573 avio_seek(pb, entry_pos, SEEK_SET);
3574 avio_wb32(pb, count); // rewrite entry count
3575 avio_seek(pb, curpos, SEEK_SET);
3577 return update_size(pb, pos);
3580 static int mov_write_mdta_ilst_tag(AVIOContext *pb, MOVMuxContext *mov,
3583 AVDictionaryEntry *t = NULL;
3584 int64_t pos = avio_tell(pb);
3585 int count = 1; /* keys are 1-index based */
3587 avio_wb32(pb, 0); /* size */
3588 ffio_wfourcc(pb, "ilst");
3590 while (t = av_dict_get(s->metadata, "", t, AV_DICT_IGNORE_SUFFIX)) {
3591 int64_t entry_pos = avio_tell(pb);
3592 avio_wb32(pb, 0); /* size */
3593 avio_wb32(pb, count); /* key */
3594 mov_write_string_data_tag(pb, t->value, 0, 1);
3595 update_size(pb, entry_pos);
3598 return update_size(pb, pos);
3601 /* meta data tags */
3602 static int mov_write_meta_tag(AVIOContext *pb, MOVMuxContext *mov,
3606 int64_t pos = avio_tell(pb);
3607 avio_wb32(pb, 0); /* size */
3608 ffio_wfourcc(pb, "meta");
3610 if (mov->flags & FF_MOV_FLAG_USE_MDTA) {
3611 mov_write_mdta_hdlr_tag(pb, mov, s);
3612 mov_write_mdta_keys_tag(pb, mov, s);
3613 mov_write_mdta_ilst_tag(pb, mov, s);
3616 /* iTunes metadata tag */
3617 mov_write_itunes_hdlr_tag(pb, mov, s);
3618 mov_write_ilst_tag(pb, mov, s);
3620 size = update_size(pb, pos);
3624 static int mov_write_raw_metadata_tag(AVFormatContext *s, AVIOContext *pb,
3625 const char *name, const char *key)
3628 AVDictionaryEntry *t;
3630 if (!(t = av_dict_get(s->metadata, key, NULL, 0)))
3633 len = strlen(t->value);
3636 avio_wb32(pb, size);
3637 ffio_wfourcc(pb, name);
3638 avio_write(pb, t->value, len);
3644 static int ascii_to_wc(AVIOContext *pb, const uint8_t *b)
3648 GET_UTF8(val, *b++, return -1;)
3651 avio_wb16(pb, 0x00);
3655 static uint16_t language_code(const char *str)
3657 return (((str[0] - 0x60) & 0x1F) << 10) +
3658 (((str[1] - 0x60) & 0x1F) << 5) +
3659 (( str[2] - 0x60) & 0x1F);
3662 static int mov_write_3gp_udta_tag(AVIOContext *pb, AVFormatContext *s,
3663 const char *tag, const char *str)
3665 int64_t pos = avio_tell(pb);
3666 AVDictionaryEntry *t = av_dict_get(s->metadata, str, NULL, 0);
3667 if (!t || !utf8len(t->value))
3669 avio_wb32(pb, 0); /* size */
3670 ffio_wfourcc(pb, tag); /* type */
3671 avio_wb32(pb, 0); /* version + flags */
3672 if (!strcmp(tag, "yrrc"))
3673 avio_wb16(pb, atoi(t->value));
3675 avio_wb16(pb, language_code("eng")); /* language */
3676 avio_write(pb, t->value, strlen(t->value) + 1); /* UTF8 string value */
3677 if (!strcmp(tag, "albm") &&
3678 (t = av_dict_get(s->metadata, "track", NULL, 0)))
3679 avio_w8(pb, atoi(t->value));
3681 return update_size(pb, pos);
3684 static int mov_write_chpl_tag(AVIOContext *pb, AVFormatContext *s)
3686 int64_t pos = avio_tell(pb);
3687 int i, nb_chapters = FFMIN(s->nb_chapters, 255);
3689 avio_wb32(pb, 0); // size
3690 ffio_wfourcc(pb, "chpl");
3691 avio_wb32(pb, 0x01000000); // version + flags
3692 avio_wb32(pb, 0); // unknown
3693 avio_w8(pb, nb_chapters);
3695 for (i = 0; i < nb_chapters; i++) {
3696 AVChapter *c = s->chapters[i];
3697 AVDictionaryEntry *t;
3698 avio_wb64(pb, av_rescale_q(c->start, c->time_base, (AVRational){1,10000000}));
3700 if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
3701 int len = FFMIN(strlen(t->value), 255);
3703 avio_write(pb, t->value, len);
3707 return update_size(pb, pos);
3710 static int mov_write_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
3713 AVIOContext *pb_buf;
3717 ret = avio_open_dyn_buf(&pb_buf);
3721 if (mov->mode & MODE_3GP) {
3722 mov_write_3gp_udta_tag(pb_buf, s, "perf", "artist");
3723 mov_write_3gp_udta_tag(pb_buf, s, "titl", "title");
3724 mov_write_3gp_udta_tag(pb_buf, s, "auth", "author");
3725 mov_write_3gp_udta_tag(pb_buf, s, "gnre", "genre");
3726 mov_write_3gp_udta_tag(pb_buf, s, "dscp", "comment");
3727 mov_write_3gp_udta_tag(pb_buf, s, "albm", "album");
3728 mov_write_3gp_udta_tag(pb_buf, s, "cprt", "copyright");
3729 mov_write_3gp_udta_tag(pb_buf, s, "yrrc", "date");
3730 mov_write_loci_tag(s, pb_buf);
3731 } 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
3732 mov_write_string_metadata(s, pb_buf, "\251ART", "artist", 0);
3733 mov_write_string_metadata(s, pb_buf, "\251nam", "title", 0);
3734 mov_write_string_metadata(s, pb_buf, "\251aut", "author", 0);
3735 mov_write_string_metadata(s, pb_buf, "\251alb", "album", 0);
3736 mov_write_string_metadata(s, pb_buf, "\251day", "date", 0);
3737 mov_write_string_metadata(s, pb_buf, "\251swr", "encoder", 0);
3738 // currently ignored by mov.c
3739 mov_write_string_metadata(s, pb_buf, "\251des", "comment", 0);
3740 // add support for libquicktime, this atom is also actually read by mov.c
3741 mov_write_string_metadata(s, pb_buf, "\251cmt", "comment", 0);
3742 mov_write_string_metadata(s, pb_buf, "\251gen", "genre", 0);
3743 mov_write_string_metadata(s, pb_buf, "\251cpy", "copyright", 0);
3744 mov_write_string_metadata(s, pb_buf, "\251mak", "make", 0);
3745 mov_write_string_metadata(s, pb_buf, "\251mod", "model", 0);
3746 mov_write_string_metadata(s, pb_buf, "\251xyz", "location", 0);
3747 mov_write_string_metadata(s, pb_buf, "\251key", "keywords", 0);
3748 mov_write_raw_metadata_tag(s, pb_buf, "XMP_", "xmp");
3750 /* iTunes meta data */
3751 mov_write_meta_tag(pb_buf, mov, s);
3752 mov_write_loci_tag(s, pb_buf);
3755 if (s->nb_chapters && !(mov->flags & FF_MOV_FLAG_DISABLE_CHPL))
3756 mov_write_chpl_tag(pb_buf, s);
3758 if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) {
3759 avio_wb32(pb, size + 8);
3760 ffio_wfourcc(pb, "udta");
3761 avio_write(pb, buf, size);
3768 static void mov_write_psp_udta_tag(AVIOContext *pb,
3769 const char *str, const char *lang, int type)
3771 int len = utf8len(str) + 1;
3774 avio_wb16(pb, len * 2 + 10); /* size */
3775 avio_wb32(pb, type); /* type */
3776 avio_wb16(pb, language_code(lang)); /* language */
3777 avio_wb16(pb, 0x01); /* ? */
3778 ascii_to_wc(pb, str);
3781 static int mov_write_uuidusmt_tag(AVIOContext *pb, AVFormatContext *s)
3783 AVDictionaryEntry *title = av_dict_get(s->metadata, "title", NULL, 0);
3787 pos = avio_tell(pb);
3788 avio_wb32(pb, 0); /* size placeholder*/
3789 ffio_wfourcc(pb, "uuid");
3790 ffio_wfourcc(pb, "USMT");
3791 avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
3792 avio_wb32(pb, 0xbb88695c);
3793 avio_wb32(pb, 0xfac9c740);
3795 pos2 = avio_tell(pb);
3796 avio_wb32(pb, 0); /* size placeholder*/
3797 ffio_wfourcc(pb, "MTDT");
3801 avio_wb16(pb, 0x0C); /* size */
3802 avio_wb32(pb, 0x0B); /* type */
3803 avio_wb16(pb, language_code("und")); /* language */
3804 avio_wb16(pb, 0x0); /* ? */
3805 avio_wb16(pb, 0x021C); /* data */
3807 if (!(s->flags & AVFMT_FLAG_BITEXACT))
3808 mov_write_psp_udta_tag(pb, LIBAVCODEC_IDENT, "eng", 0x04);
3809 mov_write_psp_udta_tag(pb, title->value, "eng", 0x01);
3810 mov_write_psp_udta_tag(pb, "2006/04/01 11:11:11", "und", 0x03);
3812 update_size(pb, pos2);
3813 return update_size(pb, pos);
3819 static void build_chunks(MOVTrack *trk)
3822 MOVIentry *chunk = &trk->cluster[0];
3823 uint64_t chunkSize = chunk->size;
3824 chunk->chunkNum = 1;
3825 if (trk->chunkCount)
3827 trk->chunkCount = 1;
3828 for (i = 1; i<trk->entry; i++){
3829 if (chunk->pos + chunkSize == trk->cluster[i].pos &&
3830 chunkSize + trk->cluster[i].size < (1<<20)){
3831 chunkSize += trk->cluster[i].size;
3832 chunk->samples_in_chunk += trk->cluster[i].entries;
3834 trk->cluster[i].chunkNum = chunk->chunkNum+1;
3835 chunk=&trk->cluster[i];
3836 chunkSize = chunk->size;
3843 * Assign track ids. If option "use_stream_ids_as_track_ids" is set,
3844 * the stream ids are used as track ids.
3846 * This assumes mov->tracks and s->streams are in the same order and
3847 * there are no gaps in either of them (so mov->tracks[n] refers to
3850 * As an exception, there can be more entries in
3851 * s->streams than in mov->tracks, in which case new track ids are
3852 * generated (starting after the largest found stream id).
3854 static int mov_setup_track_ids(MOVMuxContext *mov, AVFormatContext *s)
3858 if (mov->track_ids_ok)
3861 if (mov->use_stream_ids_as_track_ids) {
3862 int next_generated_track_id = 0;
3863 for (i = 0; i < s->nb_streams; i++) {
3864 if (s->streams[i]->id > next_generated_track_id)
3865 next_generated_track_id = s->streams[i]->id;
3868 for (i = 0; i < mov->nb_streams; i++) {
3869 if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
3872 mov->tracks[i].track_id = i >= s->nb_streams ? ++next_generated_track_id : s->streams[i]->id;
3875 for (i = 0; i < mov->nb_streams; i++) {
3876 if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
3879 mov->tracks[i].track_id = i + 1;
3883 mov->track_ids_ok = 1;
3888 static int mov_write_moov_tag(AVIOContext *pb, MOVMuxContext *mov,
3892 int64_t pos = avio_tell(pb);
3893 avio_wb32(pb, 0); /* size placeholder*/
3894 ffio_wfourcc(pb, "moov");
3896 mov_setup_track_ids(mov, s);
3898 for (i = 0; i < mov->nb_streams; i++) {
3899 if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
3902 mov->tracks[i].time = mov->time;
3904 if (mov->tracks[i].entry)
3905 build_chunks(&mov->tracks[i]);
3908 if (mov->chapter_track)
3909 for (i = 0; i < s->nb_streams; i++) {
3910 mov->tracks[i].tref_tag = MKTAG('c','h','a','p');
3911 mov->tracks[i].tref_id = mov->tracks[mov->chapter_track].track_id;
3913 for (i = 0; i < mov->nb_streams; i++) {
3914 MOVTrack *track = &mov->tracks[i];
3915 if (track->tag == MKTAG('r','t','p',' ')) {
3916 track->tref_tag = MKTAG('h','i','n','t');
3917 track->tref_id = mov->tracks[track->src_track].track_id;
3918 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
3919 int * fallback, size;
3920 fallback = (int*)av_stream_get_side_data(track->st,
3921 AV_PKT_DATA_FALLBACK_TRACK,
3923 if (fallback != NULL && size == sizeof(int)) {
3924 if (*fallback >= 0 && *fallback < mov->nb_streams) {
3925 track->tref_tag = MKTAG('f','a','l','l');
3926 track->tref_id = mov->tracks[*fallback].track_id;
3931 for (i = 0; i < mov->nb_streams; i++) {
3932 if (mov->tracks[i].tag == MKTAG('t','m','c','d')) {
3933 int src_trk = mov->tracks[i].src_track;
3934 mov->tracks[src_trk].tref_tag = mov->tracks[i].tag;
3935 mov->tracks[src_trk].tref_id = mov->tracks[i].track_id;
3936 //src_trk may have a different timescale than the tmcd track
3937 mov->tracks[i].track_duration = av_rescale(mov->tracks[src_trk].track_duration,
3938 mov->tracks[i].timescale,
3939 mov->tracks[src_trk].timescale);
3943 mov_write_mvhd_tag(pb, mov);
3944 if (mov->mode != MODE_MOV && !mov->iods_skip)
3945 mov_write_iods_tag(pb, mov);
3946 for (i = 0; i < mov->nb_streams; i++) {
3947 if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_FRAGMENT) {
3948 int ret = mov_write_trak_tag(s, pb, mov, &(mov->tracks[i]), i < s->nb_streams ? s->streams[i] : NULL);
3953 if (mov->flags & FF_MOV_FLAG_FRAGMENT)
3954 mov_write_mvex_tag(pb, mov); /* QuickTime requires trak to precede this */
3956 if (mov->mode == MODE_PSP)
3957 mov_write_uuidusmt_tag(pb, s);
3959 mov_write_udta_tag(pb, mov, s);
3961 return update_size(pb, pos);
3964 static void param_write_int(AVIOContext *pb, const char *name, int value)
3966 avio_printf(pb, "<param name=\"%s\" value=\"%d\" valuetype=\"data\"/>\n", name, value);
3969 static void param_write_string(AVIOContext *pb, const char *name, const char *value)
3971 avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, value);
3974 static void param_write_hex(AVIOContext *pb, const char *name, const uint8_t *value, int len)
3977 len = FFMIN(sizeof(buf) / 2 - 1, len);
3978 ff_data_to_hex(buf, value, len, 0);
3979 buf[2 * len] = '\0';
3980 avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, buf);
3983 static int mov_write_isml_manifest(AVIOContext *pb, MOVMuxContext *mov, AVFormatContext *s)
3985 int64_t pos = avio_tell(pb);
3987 int64_t manifest_bit_rate = 0;
3988 AVCPBProperties *props = NULL;
3990 static const uint8_t uuid[] = {
3991 0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd,
3992 0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66
3996 ffio_wfourcc(pb, "uuid");
3997 avio_write(pb, uuid, sizeof(uuid));
4000 avio_printf(pb, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
4001 avio_printf(pb, "<smil xmlns=\"http://www.w3.org/2001/SMIL20/Language\">\n");
4002 avio_printf(pb, "<head>\n");
4003 if (!(mov->fc->flags & AVFMT_FLAG_BITEXACT))
4004 avio_printf(pb, "<meta name=\"creator\" content=\"%s\" />\n",
4006 avio_printf(pb, "</head>\n");
4007 avio_printf(pb, "<body>\n");
4008 avio_printf(pb, "<switch>\n");
4010 mov_setup_track_ids(mov, s);
4012 for (i = 0; i < mov->nb_streams; i++) {
4013 MOVTrack *track = &mov->tracks[i];
4015 int track_id = track->track_id;
4016 char track_name_buf[32] = { 0 };
4018 AVStream *st = track->st;
4019 AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0);
4021 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO && !is_cover_image(st)) {
4023 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
4029 props = (AVCPBProperties*)av_stream_get_side_data(track->st, AV_PKT_DATA_CPB_PROPERTIES, NULL);
4031 if (track->par->bit_rate) {
4032 manifest_bit_rate = track->par->bit_rate;
4034 manifest_bit_rate = props->max_bitrate;
4037 avio_printf(pb, "<%s systemBitrate=\"%"PRId64"\">\n", type,
4039 param_write_int(pb, "systemBitrate", manifest_bit_rate);
4040 param_write_int(pb, "trackID", track_id);
4041 param_write_string(pb, "systemLanguage", lang ? lang->value : "und");
4043 /* Build track name piece by piece: */
4045 av_strlcat(track_name_buf, type, sizeof(track_name_buf));
4046 /* 2. track language, if available */
4048 av_strlcatf(track_name_buf, sizeof(track_name_buf),
4049 "_%s", lang->value);
4050 /* 3. special type suffix */
4051 /* "_cc" = closed captions, "_ad" = audio_description */
4052 if (st->disposition & AV_DISPOSITION_HEARING_IMPAIRED)
4053 av_strlcat(track_name_buf, "_cc", sizeof(track_name_buf));
4054 else if (st->disposition & AV_DISPOSITION_VISUAL_IMPAIRED)
4055 av_strlcat(track_name_buf, "_ad", sizeof(track_name_buf));
4057 param_write_string(pb, "trackName", track_name_buf);
4059 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
4060 if (track->par->codec_id == AV_CODEC_ID_H264) {
4062 int size = track->par->extradata_size;
4063 if (!ff_avc_write_annexb_extradata(track->par->extradata, &ptr,
4065 param_write_hex(pb, "CodecPrivateData",
4066 ptr ? ptr : track->par->extradata,
4070 param_write_string(pb, "FourCC", "H264");
4071 } else if (track->par->codec_id == AV_CODEC_ID_VC1) {
4072 param_write_string(pb, "FourCC", "WVC1");
4073 param_write_hex(pb, "CodecPrivateData", track->par->extradata,
4074 track->par->extradata_size);
4076 param_write_int(pb, "MaxWidth", track->par->width);
4077 param_write_int(pb, "MaxHeight", track->par->height);
4078 param_write_int(pb, "DisplayWidth", track->par->width);
4079 param_write_int(pb, "DisplayHeight", track->par->height);
4081 if (track->par->codec_id == AV_CODEC_ID_AAC) {
4082 switch (track->par->profile)
4084 case FF_PROFILE_AAC_HE_V2:
4085 param_write_string(pb, "FourCC", "AACP");
4087 case FF_PROFILE_AAC_HE:
4088 param_write_string(pb, "FourCC", "AACH");
4091 param_write_string(pb, "FourCC", "AACL");
4093 } else if (track->par->codec_id == AV_CODEC_ID_WMAPRO) {
4094 param_write_string(pb, "FourCC", "WMAP");
4096 param_write_hex(pb, "CodecPrivateData", track->par->extradata,
4097 track->par->extradata_size);
4098 param_write_int(pb, "AudioTag", ff_codec_get_tag(ff_codec_wav_tags,
4099 track->par->codec_id));
4100 param_write_int(pb, "Channels", track->par->channels);
4101 param_write_int(pb, "SamplingRate", track->par->sample_rate);
4102 param_write_int(pb, "BitsPerSample", 16);
4103 param_write_int(pb, "PacketSize", track->par->block_align ?
4104 track->par->block_align : 4);
4106 avio_printf(pb, "</%s>\n", type);
4108 avio_printf(pb, "</switch>\n");
4109 avio_printf(pb, "</body>\n");
4110 avio_printf(pb, "</smil>\n");
4112 return update_size(pb, pos);
4115 static int mov_write_mfhd_tag(AVIOContext *pb, MOVMuxContext *mov)
4118 ffio_wfourcc(pb, "mfhd");
4120 avio_wb32(pb, mov->fragments);
4124 static uint32_t get_sample_flags(MOVTrack *track, MOVIentry *entry)
4126 return entry->flags & MOV_SYNC_SAMPLE ? MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO :
4127 (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC);
4130 static int mov_write_tfhd_tag(AVIOContext *pb, MOVMuxContext *mov,
4131 MOVTrack *track, int64_t moof_offset)
4133 int64_t pos = avio_tell(pb);
4134 uint32_t flags = MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
4135 MOV_TFHD_BASE_DATA_OFFSET;
4136 if (!track->entry) {
4137 flags |= MOV_TFHD_DURATION_IS_EMPTY;
4139 flags |= MOV_TFHD_DEFAULT_FLAGS;
4141 if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET)
4142 flags &= ~MOV_TFHD_BASE_DATA_OFFSET;
4143 if (mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) {
4144 flags &= ~MOV_TFHD_BASE_DATA_OFFSET;
4145 flags |= MOV_TFHD_DEFAULT_BASE_IS_MOOF;
4148 /* Don't set a default sample size, the silverlight player refuses
4149 * to play files with that set. Don't set a default sample duration,
4150 * WMP freaks out if it is set. Don't set a base data offset, PIFF
4151 * file format says it MUST NOT be set. */
4152 if (track->mode == MODE_ISM)
4153 flags &= ~(MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
4154 MOV_TFHD_BASE_DATA_OFFSET);
4156 avio_wb32(pb, 0); /* size placeholder */
4157 ffio_wfourcc(pb, "tfhd");
4158 avio_w8(pb, 0); /* version */
4159 avio_wb24(pb, flags);
4161 avio_wb32(pb, track->track_id); /* track-id */
4162 if (flags & MOV_TFHD_BASE_DATA_OFFSET)
4163 avio_wb64(pb, moof_offset);
4164 if (flags & MOV_TFHD_DEFAULT_DURATION) {
4165 track->default_duration = get_cluster_duration(track, 0);
4166 avio_wb32(pb, track->default_duration);
4168 if (flags & MOV_TFHD_DEFAULT_SIZE) {
4169 track->default_size = track->entry ? track->cluster[0].size : 1;
4170 avio_wb32(pb, track->default_size);
4172 track->default_size = -1;
4174 if (flags & MOV_TFHD_DEFAULT_FLAGS) {
4175 /* Set the default flags based on the second sample, if available.
4176 * If the first sample is different, that can be signaled via a separate field. */
4177 if (track->entry > 1)
4178 track->default_sample_flags = get_sample_flags(track, &track->cluster[1]);
4180 track->default_sample_flags =
4181 track->par->codec_type == AVMEDIA_TYPE_VIDEO ?
4182 (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC) :
4183 MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO;
4184 avio_wb32(pb, track->default_sample_flags);
4187 return update_size(pb, pos);
4190 static int mov_write_trun_tag(AVIOContext *pb, MOVMuxContext *mov,
4191 MOVTrack *track, int moof_size,
4194 int64_t pos = avio_tell(pb);
4195 uint32_t flags = MOV_TRUN_DATA_OFFSET;
4198 for (i = first; i < end; i++) {
4199 if (get_cluster_duration(track, i) != track->default_duration)
4200 flags |= MOV_TRUN_SAMPLE_DURATION;
4201 if (track->cluster[i].size != track->default_size)
4202 flags |= MOV_TRUN_SAMPLE_SIZE;
4203 if (i > first && get_sample_flags(track, &track->cluster[i]) != track->default_sample_flags)
4204 flags |= MOV_TRUN_SAMPLE_FLAGS;
4206 if (!(flags & MOV_TRUN_SAMPLE_FLAGS) && track->entry > 0 &&
4207 get_sample_flags(track, &track->cluster[0]) != track->default_sample_flags)
4208 flags |= MOV_TRUN_FIRST_SAMPLE_FLAGS;
4209 if (track->flags & MOV_TRACK_CTTS)
4210 flags |= MOV_TRUN_SAMPLE_CTS;
4212 avio_wb32(pb, 0); /* size placeholder */
4213 ffio_wfourcc(pb, "trun");
4214 if (mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS)
4215 avio_w8(pb, 1); /* version */
4217 avio_w8(pb, 0); /* version */
4218 avio_wb24(pb, flags);
4220 avio_wb32(pb, end - first); /* sample count */
4221 if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET &&
4222 !(mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) &&
4224 avio_wb32(pb, 0); /* Later tracks follow immediately after the previous one */
4226 avio_wb32(pb, moof_size + 8 + track->data_offset +
4227 track->cluster[first].pos); /* data offset */
4228 if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS)
4229 avio_wb32(pb, get_sample_flags(track, &track->cluster[first]));
4231 for (i = first; i < end; i++) {
4232 if (flags & MOV_TRUN_SAMPLE_DURATION)
4233 avio_wb32(pb, get_cluster_duration(track, i));
4234 if (flags & MOV_TRUN_SAMPLE_SIZE)
4235 avio_wb32(pb, track->cluster[i].size);
4236 if (flags & MOV_TRUN_SAMPLE_FLAGS)
4237 avio_wb32(pb, get_sample_flags(track, &track->cluster[i]));
4238 if (flags & MOV_TRUN_SAMPLE_CTS)
4239 avio_wb32(pb, track->cluster[i].cts);
4242 mov->first_trun = 0;
4243 return update_size(pb, pos);
4246 static int mov_write_tfxd_tag(AVIOContext *pb, MOVTrack *track)
4248 int64_t pos = avio_tell(pb);
4249 static const uint8_t uuid[] = {
4250 0x6d, 0x1d, 0x9b, 0x05, 0x42, 0xd5, 0x44, 0xe6,
4251 0x80, 0xe2, 0x14, 0x1d, 0xaf, 0xf7, 0x57, 0xb2
4254 avio_wb32(pb, 0); /* size placeholder */
4255 ffio_wfourcc(pb, "uuid");
4256 avio_write(pb, uuid, sizeof(uuid));
4259 avio_wb64(pb, track->start_dts + track->frag_start +
4260 track->cluster[0].cts);
4261 avio_wb64(pb, track->end_pts -
4262 (track->cluster[0].dts + track->cluster[0].cts));
4264 return update_size(pb, pos);
4267 static int mov_write_tfrf_tag(AVIOContext *pb, MOVMuxContext *mov,
4268 MOVTrack *track, int entry)
4270 int n = track->nb_frag_info - 1 - entry, i;
4271 int size = 8 + 16 + 4 + 1 + 16*n;
4272 static const uint8_t uuid[] = {
4273 0xd4, 0x80, 0x7e, 0xf2, 0xca, 0x39, 0x46, 0x95,
4274 0x8e, 0x54, 0x26, 0xcb, 0x9e, 0x46, 0xa7, 0x9f
4280 avio_seek(pb, track->frag_info[entry].tfrf_offset, SEEK_SET);
4281 avio_wb32(pb, size);
4282 ffio_wfourcc(pb, "uuid");
4283 avio_write(pb, uuid, sizeof(uuid));
4287 for (i = 0; i < n; i++) {
4288 int index = entry + 1 + i;
4289 avio_wb64(pb, track->frag_info[index].time);
4290 avio_wb64(pb, track->frag_info[index].duration);
4292 if (n < mov->ism_lookahead) {
4293 int free_size = 16 * (mov->ism_lookahead - n);
4294 avio_wb32(pb, free_size);
4295 ffio_wfourcc(pb, "free");
4296 ffio_fill(pb, 0, free_size - 8);
4302 static int mov_write_tfrf_tags(AVIOContext *pb, MOVMuxContext *mov,
4305 int64_t pos = avio_tell(pb);
4307 for (i = 0; i < mov->ism_lookahead; i++) {
4308 /* Update the tfrf tag for the last ism_lookahead fragments,
4309 * nb_frag_info - 1 is the next fragment to be written. */
4310 mov_write_tfrf_tag(pb, mov, track, track->nb_frag_info - 2 - i);
4312 avio_seek(pb, pos, SEEK_SET);
4316 static int mov_add_tfra_entries(AVIOContext *pb, MOVMuxContext *mov, int tracks,
4320 for (i = 0; i < mov->nb_streams; i++) {
4321 MOVTrack *track = &mov->tracks[i];
4322 MOVFragmentInfo *info;
4323 if ((tracks >= 0 && i != tracks) || !track->entry)
4325 track->nb_frag_info++;
4326 if (track->nb_frag_info >= track->frag_info_capacity) {
4327 unsigned new_capacity = track->nb_frag_info + MOV_FRAG_INFO_ALLOC_INCREMENT;
4328 if (av_reallocp_array(&track->frag_info,
4330 sizeof(*track->frag_info)))
4331 return AVERROR(ENOMEM);
4332 track->frag_info_capacity = new_capacity;
4334 info = &track->frag_info[track->nb_frag_info - 1];
4335 info->offset = avio_tell(pb);
4337 // Try to recreate the original pts for the first packet
4338 // from the fields we have stored
4339 info->time = track->start_dts + track->frag_start +
4340 track->cluster[0].cts;
4341 info->duration = track->end_pts -
4342 (track->cluster[0].dts + track->cluster[0].cts);
4343 // If the pts is less than zero, we will have trimmed
4344 // away parts of the media track using an edit list,
4345 // and the corresponding start presentation time is zero.
4346 if (info->time < 0) {
4347 info->duration += info->time;
4350 info->tfrf_offset = 0;
4351 mov_write_tfrf_tags(pb, mov, track);
4356 static void mov_prune_frag_info(MOVMuxContext *mov, int tracks, int max)
4359 for (i = 0; i < mov->nb_streams; i++) {
4360 MOVTrack *track = &mov->tracks[i];
4361 if ((tracks >= 0 && i != tracks) || !track->entry)
4363 if (track->nb_frag_info > max) {
4364 memmove(track->frag_info, track->frag_info + (track->nb_frag_info - max), max * sizeof(*track->frag_info));
4365 track->nb_frag_info = max;
4370 static int mov_write_tfdt_tag(AVIOContext *pb, MOVTrack *track)
4372 int64_t pos = avio_tell(pb);
4374 avio_wb32(pb, 0); /* size */
4375 ffio_wfourcc(pb, "tfdt");
4376 avio_w8(pb, 1); /* version */
4378 avio_wb64(pb, track->frag_start);
4379 return update_size(pb, pos);
4382 static int mov_write_traf_tag(AVIOContext *pb, MOVMuxContext *mov,
4383 MOVTrack *track, int64_t moof_offset,
4386 int64_t pos = avio_tell(pb);
4388 avio_wb32(pb, 0); /* size placeholder */
4389 ffio_wfourcc(pb, "traf");
4391 mov_write_tfhd_tag(pb, mov, track, moof_offset);
4392 if (mov->mode != MODE_ISM)
4393 mov_write_tfdt_tag(pb, track);
4394 for (i = 1; i < track->entry; i++) {
4395 if (track->cluster[i].pos != track->cluster[i - 1].pos + track->cluster[i - 1].size) {
4396 mov_write_trun_tag(pb, mov, track, moof_size, start, i);
4400 mov_write_trun_tag(pb, mov, track, moof_size, start, track->entry);
4401 if (mov->mode == MODE_ISM) {
4402 mov_write_tfxd_tag(pb, track);
4404 if (mov->ism_lookahead) {
4405 int i, size = 16 + 4 + 1 + 16 * mov->ism_lookahead;
4407 if (track->nb_frag_info > 0) {
4408 MOVFragmentInfo *info = &track->frag_info[track->nb_frag_info - 1];
4409 if (!info->tfrf_offset)
4410 info->tfrf_offset = avio_tell(pb);
4412 avio_wb32(pb, 8 + size);
4413 ffio_wfourcc(pb, "free");
4414 for (i = 0; i < size; i++)
4419 return update_size(pb, pos);
4422 static int mov_write_moof_tag_internal(AVIOContext *pb, MOVMuxContext *mov,
4423 int tracks, int moof_size)
4425 int64_t pos = avio_tell(pb);
4428 avio_wb32(pb, 0); /* size placeholder */
4429 ffio_wfourcc(pb, "moof");
4430 mov->first_trun = 1;
4432 mov_write_mfhd_tag(pb, mov);
4433 for (i = 0; i < mov->nb_streams; i++) {
4434 MOVTrack *track = &mov->tracks[i];
4435 if (tracks >= 0 && i != tracks)
4439 mov_write_traf_tag(pb, mov, track, pos, moof_size);
4442 return update_size(pb, pos);
4445 static int mov_write_sidx_tag(AVIOContext *pb,
4446 MOVTrack *track, int ref_size, int total_sidx_size)
4448 int64_t pos = avio_tell(pb), offset_pos, end_pos;
4449 int64_t presentation_time, duration, offset;
4450 int starts_with_SAP, i, entries;
4454 presentation_time = track->start_dts + track->frag_start +
4455 track->cluster[0].cts;
4456 duration = track->end_pts -
4457 (track->cluster[0].dts + track->cluster[0].cts);
4458 starts_with_SAP = track->cluster[0].flags & MOV_SYNC_SAMPLE;
4460 // pts<0 should be cut away using edts
4461 if (presentation_time < 0) {
4462 duration += presentation_time;
4463 presentation_time = 0;
4466 entries = track->nb_frag_info;
4469 presentation_time = track->frag_info[0].time;
4472 avio_wb32(pb, 0); /* size */
4473 ffio_wfourcc(pb, "sidx");
4474 avio_w8(pb, 1); /* version */
4476 avio_wb32(pb, track->track_id); /* reference_ID */
4477 avio_wb32(pb, track->timescale); /* timescale */
4478 avio_wb64(pb, presentation_time); /* earliest_presentation_time */
4479 offset_pos = avio_tell(pb);
4480 avio_wb64(pb, 0); /* first_offset (offset to referenced moof) */
4481 avio_wb16(pb, 0); /* reserved */
4483 avio_wb16(pb, entries); /* reference_count */
4484 for (i = 0; i < entries; i++) {
4485 if (!track->entry) {
4486 if (i > 1 && track->frag_info[i].offset != track->frag_info[i - 1].offset + track->frag_info[i - 1].size) {
4487 av_log(NULL, AV_LOG_ERROR, "Non-consecutive fragments, writing incorrect sidx\n");
4489 duration = track->frag_info[i].duration;
4490 ref_size = track->frag_info[i].size;
4491 starts_with_SAP = 1;
4493 avio_wb32(pb, (0 << 31) | (ref_size & 0x7fffffff)); /* reference_type (0 = media) | referenced_size */
4494 avio_wb32(pb, duration); /* subsegment_duration */
4495 avio_wb32(pb, (starts_with_SAP << 31) | (0 << 28) | 0); /* starts_with_SAP | SAP_type | SAP_delta_time */
4498 end_pos = avio_tell(pb);
4499 offset = pos + total_sidx_size - end_pos;
4500 avio_seek(pb, offset_pos, SEEK_SET);
4501 avio_wb64(pb, offset);
4502 avio_seek(pb, end_pos, SEEK_SET);
4503 return update_size(pb, pos);
4506 static int mov_write_sidx_tags(AVIOContext *pb, MOVMuxContext *mov,
4507 int tracks, int ref_size)
4510 AVIOContext *avio_buf;
4512 for (round = 0; round < 2; round++) {
4513 // First run one round to calculate the total size of all
4515 // This would be much simpler if we'd only write one sidx
4516 // atom, for the first track in the moof.
4518 if ((ret = ffio_open_null_buf(&avio_buf)) < 0)
4523 for (i = 0; i < mov->nb_streams; i++) {
4524 MOVTrack *track = &mov->tracks[i];
4525 if (tracks >= 0 && i != tracks)
4527 // When writing a sidx for the full file, entry is 0, but
4528 // we want to include all tracks. ref_size is 0 in this case,
4529 // since we read it from frag_info instead.
4530 if (!track->entry && ref_size > 0)
4532 total_size -= mov_write_sidx_tag(avio_buf, track, ref_size,
4536 total_size = ffio_close_null_buf(avio_buf);
4541 static int mov_write_prft_tag(AVIOContext *pb, MOVMuxContext *mov, int tracks)
4543 int64_t pos = avio_tell(pb), pts_us, ntp_ts;
4544 MOVTrack *first_track;
4546 /* PRFT should be associated with at most one track. So, choosing only the
4550 first_track = &(mov->tracks[0]);
4552 if (!first_track->entry) {
4553 av_log(mov->fc, AV_LOG_WARNING, "Unable to write PRFT, no entries in the track\n");
4557 if (first_track->cluster[0].pts == AV_NOPTS_VALUE) {
4558 av_log(mov->fc, AV_LOG_WARNING, "Unable to write PRFT, first PTS is invalid\n");
4562 if (mov->write_prft == MOV_PRFT_SRC_WALLCLOCK) {
4563 ntp_ts = ff_get_formatted_ntp_time(ff_ntp_time());
4564 } else if (mov->write_prft == MOV_PRFT_SRC_PTS) {
4565 pts_us = av_rescale_q(first_track->cluster[0].pts,
4566 first_track->st->time_base, AV_TIME_BASE_Q);
4567 ntp_ts = ff_get_formatted_ntp_time(pts_us + NTP_OFFSET_US);
4569 av_log(mov->fc, AV_LOG_WARNING, "Unsupported PRFT box configuration: %d\n",
4574 avio_wb32(pb, 0); // Size place holder
4575 ffio_wfourcc(pb, "prft"); // Type
4576 avio_w8(pb, 1); // Version
4577 avio_wb24(pb, 0); // Flags
4578 avio_wb32(pb, first_track->track_id); // reference track ID
4579 avio_wb64(pb, ntp_ts); // NTP time stamp
4580 avio_wb64(pb, first_track->cluster[0].pts); //media time
4581 return update_size(pb, pos);
4584 static int mov_write_moof_tag(AVIOContext *pb, MOVMuxContext *mov, int tracks,
4587 AVIOContext *avio_buf;
4590 if ((ret = ffio_open_null_buf(&avio_buf)) < 0)
4592 mov_write_moof_tag_internal(avio_buf, mov, tracks, 0);
4593 moof_size = ffio_close_null_buf(avio_buf);
4595 if (mov->flags & FF_MOV_FLAG_DASH && !(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX))
4596 mov_write_sidx_tags(pb, mov, tracks, moof_size + 8 + mdat_size);
4598 if (mov->write_prft > MOV_PRFT_NONE && mov->write_prft < MOV_PRFT_NB)
4599 mov_write_prft_tag(pb, mov, tracks);
4601 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX ||
4602 !(mov->flags & FF_MOV_FLAG_SKIP_TRAILER) ||
4603 mov->ism_lookahead) {
4604 if ((ret = mov_add_tfra_entries(pb, mov, tracks, moof_size + 8 + mdat_size)) < 0)
4606 if (!(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) &&
4607 mov->flags & FF_MOV_FLAG_SKIP_TRAILER) {
4608 mov_prune_frag_info(mov, tracks, mov->ism_lookahead + 1);
4612 return mov_write_moof_tag_internal(pb, mov, tracks, moof_size);
4615 static int mov_write_tfra_tag(AVIOContext *pb, MOVTrack *track)
4617 int64_t pos = avio_tell(pb);
4620 avio_wb32(pb, 0); /* size placeholder */
4621 ffio_wfourcc(pb, "tfra");
4622 avio_w8(pb, 1); /* version */
4625 avio_wb32(pb, track->track_id);
4626 avio_wb32(pb, 0); /* length of traf/trun/sample num */
4627 avio_wb32(pb, track->nb_frag_info);
4628 for (i = 0; i < track->nb_frag_info; i++) {
4629 avio_wb64(pb, track->frag_info[i].time);
4630 avio_wb64(pb, track->frag_info[i].offset + track->data_offset);
4631 avio_w8(pb, 1); /* traf number */
4632 avio_w8(pb, 1); /* trun number */
4633 avio_w8(pb, 1); /* sample number */
4636 return update_size(pb, pos);
4639 static int mov_write_mfra_tag(AVIOContext *pb, MOVMuxContext *mov)
4641 int64_t pos = avio_tell(pb);
4644 avio_wb32(pb, 0); /* size placeholder */
4645 ffio_wfourcc(pb, "mfra");
4646 /* An empty mfra atom is enough to indicate to the publishing point that
4647 * the stream has ended. */
4648 if (mov->flags & FF_MOV_FLAG_ISML)
4649 return update_size(pb, pos);
4651 for (i = 0; i < mov->nb_streams; i++) {
4652 MOVTrack *track = &mov->tracks[i];
4653 if (track->nb_frag_info)
4654 mov_write_tfra_tag(pb, track);
4658 ffio_wfourcc(pb, "mfro");
4659 avio_wb32(pb, 0); /* version + flags */
4660 avio_wb32(pb, avio_tell(pb) + 4 - pos);
4662 return update_size(pb, pos);
4665 static int mov_write_mdat_tag(AVIOContext *pb, MOVMuxContext *mov)
4667 avio_wb32(pb, 8); // placeholder for extended size field (64 bit)
4668 ffio_wfourcc(pb, mov->mode == MODE_MOV ? "wide" : "free");
4670 mov->mdat_pos = avio_tell(pb);
4671 avio_wb32(pb, 0); /* size placeholder*/
4672 ffio_wfourcc(pb, "mdat");
4676 /* TODO: This needs to be more general */
4677 static int mov_write_ftyp_tag(AVIOContext *pb, AVFormatContext *s)
4679 MOVMuxContext *mov = s->priv_data;
4680 int64_t pos = avio_tell(pb);
4681 int has_h264 = 0, has_video = 0;
4685 for (i = 0; i < s->nb_streams; i++) {
4686 AVStream *st = s->streams[i];
4687 if (is_cover_image(st))
4689 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
4691 if (st->codecpar->codec_id == AV_CODEC_ID_H264)
4695 avio_wb32(pb, 0); /* size */
4696 ffio_wfourcc(pb, "ftyp");
4698 if (mov->major_brand && strlen(mov->major_brand) >= 4)
4699 ffio_wfourcc(pb, mov->major_brand);
4700 else if (mov->mode == MODE_3GP) {
4701 ffio_wfourcc(pb, has_h264 ? "3gp6" : "3gp4");
4702 minor = has_h264 ? 0x100 : 0x200;
4703 } else if (mov->mode & MODE_3G2) {
4704 ffio_wfourcc(pb, has_h264 ? "3g2b" : "3g2a");
4705 minor = has_h264 ? 0x20000 : 0x10000;
4706 } else if (mov->mode == MODE_PSP)
4707 ffio_wfourcc(pb, "MSNV");
4708 else if (mov->mode == MODE_MP4 && mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)
4709 ffio_wfourcc(pb, "iso5"); // Required when using default-base-is-moof
4710 else if (mov->mode == MODE_MP4 && mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS)
4711 ffio_wfourcc(pb, "iso4");
4712 else if (mov->mode == MODE_MP4)
4713 ffio_wfourcc(pb, "isom");
4714 else if (mov->mode == MODE_IPOD)
4715 ffio_wfourcc(pb, has_video ? "M4V ":"M4A ");
4716 else if (mov->mode == MODE_ISM)
4717 ffio_wfourcc(pb, "isml");
4718 else if (mov->mode == MODE_F4V)
4719 ffio_wfourcc(pb, "f4v ");
4721 ffio_wfourcc(pb, "qt ");
4723 avio_wb32(pb, minor);
4725 if (mov->mode == MODE_MOV)
4726 ffio_wfourcc(pb, "qt ");
4727 else if (mov->mode == MODE_ISM) {
4728 ffio_wfourcc(pb, "piff");
4729 } else if (!(mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)) {
4730 ffio_wfourcc(pb, "isom");
4731 ffio_wfourcc(pb, "iso2");
4733 ffio_wfourcc(pb, "avc1");
4736 // We add tfdt atoms when fragmenting, signal this with the iso6 compatible
4737 // brand. This is compatible with users that don't understand tfdt.
4738 if (mov->flags & FF_MOV_FLAG_FRAGMENT && mov->mode != MODE_ISM)
4739 ffio_wfourcc(pb, "iso6");
4741 if (mov->mode == MODE_3GP)
4742 ffio_wfourcc(pb, has_h264 ? "3gp6":"3gp4");
4743 else if (mov->mode & MODE_3G2)
4744 ffio_wfourcc(pb, has_h264 ? "3g2b":"3g2a");
4745 else if (mov->mode == MODE_PSP)
4746 ffio_wfourcc(pb, "MSNV");
4747 else if (mov->mode == MODE_MP4)
4748 ffio_wfourcc(pb, "mp41");
4750 if (mov->flags & FF_MOV_FLAG_DASH && mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
4751 ffio_wfourcc(pb, "dash");
4753 return update_size(pb, pos);
4756 static int mov_write_uuidprof_tag(AVIOContext *pb, AVFormatContext *s)
4758 AVStream *video_st = s->streams[0];
4759 AVCodecParameters *video_par = s->streams[0]->codecpar;
4760 AVCodecParameters *audio_par = s->streams[1]->codecpar;
4761 int audio_rate = audio_par->sample_rate;
4762 int64_t frame_rate = video_st->avg_frame_rate.den ?
4763 (video_st->avg_frame_rate.num * 0x10000LL) / video_st->avg_frame_rate.den :
4765 int audio_kbitrate = audio_par->bit_rate / 1000;
4766 int video_kbitrate = FFMIN(video_par->bit_rate / 1000, 800 - audio_kbitrate);
4768 if (frame_rate < 0 || frame_rate > INT32_MAX) {
4769 av_log(s, AV_LOG_ERROR, "Frame rate %f outside supported range\n", frame_rate / (double)0x10000);
4770 return AVERROR(EINVAL);
4773 avio_wb32(pb, 0x94); /* size */
4774 ffio_wfourcc(pb, "uuid");
4775 ffio_wfourcc(pb, "PROF");
4777 avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
4778 avio_wb32(pb, 0xbb88695c);
4779 avio_wb32(pb, 0xfac9c740);
4781 avio_wb32(pb, 0x0); /* ? */
4782 avio_wb32(pb, 0x3); /* 3 sections ? */
4784 avio_wb32(pb, 0x14); /* size */
4785 ffio_wfourcc(pb, "FPRF");
4786 avio_wb32(pb, 0x0); /* ? */
4787 avio_wb32(pb, 0x0); /* ? */
4788 avio_wb32(pb, 0x0); /* ? */
4790 avio_wb32(pb, 0x2c); /* size */
4791 ffio_wfourcc(pb, "APRF"); /* audio */
4793 avio_wb32(pb, 0x2); /* TrackID */
4794 ffio_wfourcc(pb, "mp4a");
4795 avio_wb32(pb, 0x20f);
4797 avio_wb32(pb, audio_kbitrate);
4798 avio_wb32(pb, audio_kbitrate);
4799 avio_wb32(pb, audio_rate);
4800 avio_wb32(pb, audio_par->channels);
4802 avio_wb32(pb, 0x34); /* size */
4803 ffio_wfourcc(pb, "VPRF"); /* video */
4805 avio_wb32(pb, 0x1); /* TrackID */
4806 if (video_par->codec_id == AV_CODEC_ID_H264) {
4807 ffio_wfourcc(pb, "avc1");
4808 avio_wb16(pb, 0x014D);
4809 avio_wb16(pb, 0x0015);
4811 ffio_wfourcc(pb, "mp4v");
4812 avio_wb16(pb, 0x0000);
4813 avio_wb16(pb, 0x0103);
4816 avio_wb32(pb, video_kbitrate);
4817 avio_wb32(pb, video_kbitrate);
4818 avio_wb32(pb, frame_rate);
4819 avio_wb32(pb, frame_rate);
4820 avio_wb16(pb, video_par->width);
4821 avio_wb16(pb, video_par->height);
4822 avio_wb32(pb, 0x010001); /* ? */
4827 static int mov_write_identification(AVIOContext *pb, AVFormatContext *s)
4829 MOVMuxContext *mov = s->priv_data;
4832 mov_write_ftyp_tag(pb,s);
4833 if (mov->mode == MODE_PSP) {
4834 int video_streams_nb = 0, audio_streams_nb = 0, other_streams_nb = 0;
4835 for (i = 0; i < s->nb_streams; i++) {
4836 AVStream *st = s->streams[i];
4837 if (is_cover_image(st))
4839 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
4841 else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
4847 if (video_streams_nb != 1 || audio_streams_nb != 1 || other_streams_nb) {
4848 av_log(s, AV_LOG_ERROR, "PSP mode need one video and one audio stream\n");
4849 return AVERROR(EINVAL);
4851 return mov_write_uuidprof_tag(pb, s);
4856 static int mov_parse_mpeg2_frame(AVPacket *pkt, uint32_t *flags)
4859 int i, closed_gop = 0;
4861 for (i = 0; i < pkt->size - 4; i++) {
4862 c = (c << 8) + pkt->data[i];
4863 if (c == 0x1b8) { // gop
4864 closed_gop = pkt->data[i + 4] >> 6 & 0x01;
4865 } else if (c == 0x100) { // pic
4866 int temp_ref = (pkt->data[i + 1] << 2) | (pkt->data[i + 2] >> 6);
4867 if (!temp_ref || closed_gop) // I picture is not reordered
4868 *flags = MOV_SYNC_SAMPLE;
4870 *flags = MOV_PARTIAL_SYNC_SAMPLE;
4877 static void mov_parse_vc1_frame(AVPacket *pkt, MOVTrack *trk)
4879 const uint8_t *start, *next, *end = pkt->data + pkt->size;
4880 int seq = 0, entry = 0;
4881 int key = pkt->flags & AV_PKT_FLAG_KEY;
4882 start = find_next_marker(pkt->data, end);
4883 for (next = start; next < end; start = next) {
4884 next = find_next_marker(start + 4, end);
4885 switch (AV_RB32(start)) {
4886 case VC1_CODE_SEQHDR:
4889 case VC1_CODE_ENTRYPOINT:
4892 case VC1_CODE_SLICE:
4893 trk->vc1_info.slices = 1;
4897 if (!trk->entry && trk->vc1_info.first_packet_seen)
4898 trk->vc1_info.first_frag_written = 1;
4899 if (!trk->entry && !trk->vc1_info.first_frag_written) {
4900 /* First packet in first fragment */
4901 trk->vc1_info.first_packet_seq = seq;
4902 trk->vc1_info.first_packet_entry = entry;
4903 trk->vc1_info.first_packet_seen = 1;
4904 } else if ((seq && !trk->vc1_info.packet_seq) ||
4905 (entry && !trk->vc1_info.packet_entry)) {
4907 for (i = 0; i < trk->entry; i++)
4908 trk->cluster[i].flags &= ~MOV_SYNC_SAMPLE;
4909 trk->has_keyframes = 0;
4911 trk->vc1_info.packet_seq = 1;
4913 trk->vc1_info.packet_entry = 1;
4914 if (!trk->vc1_info.first_frag_written) {
4915 /* First fragment */
4916 if ((!seq || trk->vc1_info.first_packet_seq) &&
4917 (!entry || trk->vc1_info.first_packet_entry)) {
4918 /* First packet had the same headers as this one, readd the
4919 * sync sample flag. */
4920 trk->cluster[0].flags |= MOV_SYNC_SAMPLE;
4921 trk->has_keyframes = 1;
4925 if (trk->vc1_info.packet_seq && trk->vc1_info.packet_entry)
4927 else if (trk->vc1_info.packet_seq)
4929 else if (trk->vc1_info.packet_entry)
4932 trk->cluster[trk->entry].flags |= MOV_SYNC_SAMPLE;
4933 trk->has_keyframes++;
4937 static int mov_flush_fragment_interleaving(AVFormatContext *s, MOVTrack *track)
4939 MOVMuxContext *mov = s->priv_data;
4944 if (!track->mdat_buf)
4946 if (!mov->mdat_buf) {
4947 if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0)
4950 buf_size = avio_close_dyn_buf(track->mdat_buf, &buf);
4951 track->mdat_buf = NULL;
4953 offset = avio_tell(mov->mdat_buf);
4954 avio_write(mov->mdat_buf, buf, buf_size);
4957 for (i = track->entries_flushed; i < track->entry; i++)
4958 track->cluster[i].pos += offset;
4959 track->entries_flushed = track->entry;
4963 static int mov_flush_fragment(AVFormatContext *s, int force)
4965 MOVMuxContext *mov = s->priv_data;
4966 int i, first_track = -1;
4967 int64_t mdat_size = 0;
4969 int has_video = 0, starts_with_key = 0, first_video_track = 1;
4971 if (!(mov->flags & FF_MOV_FLAG_FRAGMENT))
4974 // Try to fill in the duration of the last packet in each stream
4975 // from queued packets in the interleave queues. If the flushing
4976 // of fragments was triggered automatically by an AVPacket, we
4977 // already have reliable info for the end of that track, but other
4978 // tracks may need to be filled in.
4979 for (i = 0; i < s->nb_streams; i++) {
4980 MOVTrack *track = &mov->tracks[i];
4981 if (!track->end_reliable) {
4983 if (!ff_interleaved_peek(s, i, &pkt, 1)) {
4984 if (track->dts_shift != AV_NOPTS_VALUE)
4985 pkt.dts += track->dts_shift;
4986 track->track_duration = pkt.dts - track->start_dts;
4987 if (pkt.pts != AV_NOPTS_VALUE)
4988 track->end_pts = pkt.pts;
4990 track->end_pts = pkt.dts;
4995 for (i = 0; i < mov->nb_streams; i++) {
4996 MOVTrack *track = &mov->tracks[i];
4997 if (track->entry <= 1)
4999 // Sample durations are calculated as the diff of dts values,
5000 // but for the last sample in a fragment, we don't know the dts
5001 // of the first sample in the next fragment, so we have to rely
5002 // on what was set as duration in the AVPacket. Not all callers
5003 // set this though, so we might want to replace it with an
5004 // estimate if it currently is zero.
5005 if (get_cluster_duration(track, track->entry - 1) != 0)
5007 // Use the duration (i.e. dts diff) of the second last sample for
5008 // the last one. This is a wild guess (and fatal if it turns out
5009 // to be too long), but probably the best we can do - having a zero
5010 // duration is bad as well.
5011 track->track_duration += get_cluster_duration(track, track->entry - 2);
5012 track->end_pts += get_cluster_duration(track, track->entry - 2);
5013 if (!mov->missing_duration_warned) {
5014 av_log(s, AV_LOG_WARNING,
5015 "Estimating the duration of the last packet in a "
5016 "fragment, consider setting the duration field in "
5017 "AVPacket instead.\n");
5018 mov->missing_duration_warned = 1;
5022 if (!mov->moov_written) {
5023 int64_t pos = avio_tell(s->pb);
5025 int buf_size, moov_size;
5027 for (i = 0; i < mov->nb_streams; i++)
5028 if (!mov->tracks[i].entry && !is_cover_image(mov->tracks[i].st))
5030 /* Don't write the initial moov unless all tracks have data */
5031 if (i < mov->nb_streams && !force)
5034 moov_size = get_moov_size(s);
5035 for (i = 0; i < mov->nb_streams; i++)
5036 mov->tracks[i].data_offset = pos + moov_size + 8;
5038 avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_HEADER);
5039 if (mov->flags & FF_MOV_FLAG_DELAY_MOOV)
5040 mov_write_identification(s->pb, s);
5041 if ((ret = mov_write_moov_tag(s->pb, mov, s)) < 0)
5044 if (mov->flags & FF_MOV_FLAG_DELAY_MOOV) {
5045 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
5046 mov->reserved_header_pos = avio_tell(s->pb);
5048 mov->moov_written = 1;
5052 buf_size = avio_close_dyn_buf(mov->mdat_buf, &buf);
5053 mov->mdat_buf = NULL;
5054 avio_wb32(s->pb, buf_size + 8);
5055 ffio_wfourcc(s->pb, "mdat");
5056 avio_write(s->pb, buf, buf_size);
5059 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
5060 mov->reserved_header_pos = avio_tell(s->pb);
5062 mov->moov_written = 1;
5064 for (i = 0; i < mov->nb_streams; i++) {
5065 if (mov->tracks[i].entry)
5066 mov->tracks[i].frag_start += mov->tracks[i].start_dts +
5067 mov->tracks[i].track_duration -
5068 mov->tracks[i].cluster[0].dts;
5069 mov->tracks[i].entry = 0;
5070 mov->tracks[i].end_reliable = 0;
5076 if (mov->frag_interleave) {
5077 for (i = 0; i < mov->nb_streams; i++) {
5078 MOVTrack *track = &mov->tracks[i];
5080 if ((ret = mov_flush_fragment_interleaving(s, track)) < 0)
5086 mdat_size = avio_tell(mov->mdat_buf);
5089 for (i = 0; i < mov->nb_streams; i++) {
5090 MOVTrack *track = &mov->tracks[i];
5091 if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF || mov->frag_interleave)
5092 track->data_offset = 0;
5094 track->data_offset = mdat_size;
5095 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
5097 if (first_video_track) {
5099 starts_with_key = track->cluster[0].flags & MOV_SYNC_SAMPLE;
5100 first_video_track = 0;
5105 if (track->mdat_buf)
5106 mdat_size += avio_tell(track->mdat_buf);
5107 if (first_track < 0)
5114 avio_write_marker(s->pb,
5115 av_rescale(mov->tracks[first_track].cluster[0].dts, AV_TIME_BASE, mov->tracks[first_track].timescale),
5116 (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);
5118 for (i = 0; i < mov->nb_streams; i++) {
5119 MOVTrack *track = &mov->tracks[i];
5120 int buf_size, write_moof = 1, moof_tracks = -1;
5122 int64_t duration = 0;
5125 duration = track->start_dts + track->track_duration -
5126 track->cluster[0].dts;
5127 if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF) {
5128 if (!track->mdat_buf)
5130 mdat_size = avio_tell(track->mdat_buf);
5133 write_moof = i == first_track;
5139 mov_write_moof_tag(s->pb, mov, moof_tracks, mdat_size);
5142 avio_wb32(s->pb, mdat_size + 8);
5143 ffio_wfourcc(s->pb, "mdat");
5147 track->frag_start += duration;
5149 track->entries_flushed = 0;
5150 track->end_reliable = 0;
5151 if (!mov->frag_interleave) {
5152 if (!track->mdat_buf)
5154 buf_size = avio_close_dyn_buf(track->mdat_buf, &buf);
5155 track->mdat_buf = NULL;
5159 buf_size = avio_close_dyn_buf(mov->mdat_buf, &buf);
5160 mov->mdat_buf = NULL;
5163 avio_write(s->pb, buf, buf_size);
5173 static int mov_auto_flush_fragment(AVFormatContext *s, int force)
5175 MOVMuxContext *mov = s->priv_data;
5176 int had_moov = mov->moov_written;
5177 int ret = mov_flush_fragment(s, force);
5180 // If using delay_moov, the first flush only wrote the moov,
5181 // not the actual moof+mdat pair, thus flush once again.
5182 if (!had_moov && mov->flags & FF_MOV_FLAG_DELAY_MOOV)
5183 ret = mov_flush_fragment(s, force);
5187 static int check_pkt(AVFormatContext *s, AVPacket *pkt)
5189 MOVMuxContext *mov = s->priv_data;
5190 MOVTrack *trk = &mov->tracks[pkt->stream_index];
5195 ref = trk->cluster[trk->entry - 1].dts;
5196 } else if ( trk->start_dts != AV_NOPTS_VALUE
5197 && !trk->frag_discont) {
5198 ref = trk->start_dts + trk->track_duration;
5200 ref = pkt->dts; // Skip tests for the first packet
5202 if (trk->dts_shift != AV_NOPTS_VALUE) {
5203 /* With negative CTS offsets we have set an offset to the DTS,
5204 * reverse this for the check. */
5205 ref -= trk->dts_shift;
5208 duration = pkt->dts - ref;
5209 if (pkt->dts < ref || duration >= INT_MAX) {
5210 av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" / timestamp: %"PRId64" is out of range for mov/mp4 format\n",
5215 pkt->pts = AV_NOPTS_VALUE;
5218 if (pkt->duration < 0 || pkt->duration > INT_MAX) {
5219 av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" is invalid\n", pkt->duration);
5220 return AVERROR(EINVAL);
5225 int ff_mov_write_packet(AVFormatContext *s, AVPacket *pkt)
5227 MOVMuxContext *mov = s->priv_data;
5228 AVIOContext *pb = s->pb;
5229 MOVTrack *trk = &mov->tracks[pkt->stream_index];
5230 AVCodecParameters *par = trk->par;
5231 unsigned int samples_in_chunk = 0;
5232 int size = pkt->size, ret = 0;
5233 uint8_t *reformatted_data = NULL;
5235 ret = check_pkt(s, pkt);
5239 if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
5241 if (mov->moov_written || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
5242 if (mov->frag_interleave && mov->fragments > 0) {
5243 if (trk->entry - trk->entries_flushed >= mov->frag_interleave) {
5244 if ((ret = mov_flush_fragment_interleaving(s, trk)) < 0)
5249 if (!trk->mdat_buf) {
5250 if ((ret = avio_open_dyn_buf(&trk->mdat_buf)) < 0)
5255 if (!mov->mdat_buf) {
5256 if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0)
5263 if (par->codec_id == AV_CODEC_ID_AMR_NB) {
5264 /* We must find out how many AMR blocks there are in one packet */
5265 static const uint16_t packed_size[16] =
5266 {13, 14, 16, 18, 20, 21, 27, 32, 6, 0, 0, 0, 0, 0, 0, 1};
5269 while (len < size && samples_in_chunk < 100) {
5270 len += packed_size[(pkt->data[len] >> 3) & 0x0F];
5273 if (samples_in_chunk > 1) {
5274 av_log(s, AV_LOG_ERROR, "fatal error, input is not a single packet, implement a AVParser for it\n");
5277 } else if (par->codec_id == AV_CODEC_ID_ADPCM_MS ||
5278 par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) {
5279 samples_in_chunk = trk->par->frame_size;
5280 } else if (trk->sample_size)
5281 samples_in_chunk = size / trk->sample_size;
5283 samples_in_chunk = 1;
5285 if (samples_in_chunk < 1) {
5286 av_log(s, AV_LOG_ERROR, "fatal error, input packet contains no samples\n");
5287 return AVERROR_PATCHWELCOME;
5290 /* copy extradata if it exists */
5291 if (trk->vos_len == 0 && par->extradata_size > 0 &&
5292 !TAG_IS_AVCI(trk->tag) &&
5293 (par->codec_id != AV_CODEC_ID_DNXHD)) {
5294 trk->vos_len = par->extradata_size;
5295 trk->vos_data = av_malloc(trk->vos_len);
5296 if (!trk->vos_data) {
5297 ret = AVERROR(ENOMEM);
5300 memcpy(trk->vos_data, par->extradata, trk->vos_len);
5303 if (par->codec_id == AV_CODEC_ID_AAC && pkt->size > 2 &&
5304 (AV_RB16(pkt->data) & 0xfff0) == 0xfff0) {
5305 if (!s->streams[pkt->stream_index]->nb_frames) {
5306 av_log(s, AV_LOG_ERROR, "Malformed AAC bitstream detected: "
5307 "use the audio bitstream filter 'aac_adtstoasc' to fix it "
5308 "('-bsf:a aac_adtstoasc' option with ffmpeg)\n");
5311 av_log(s, AV_LOG_WARNING, "aac bitstream error\n");
5313 if (par->codec_id == AV_CODEC_ID_H264 && trk->vos_len > 0 && *(uint8_t *)trk->vos_data != 1 && !TAG_IS_AVCI(trk->tag)) {
5314 /* from x264 or from bytestream H.264 */
5315 /* NAL reformatting needed */
5316 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
5317 ff_avc_parse_nal_units_buf(pkt->data, &reformatted_data,
5319 avio_write(pb, reformatted_data, size);
5321 if (trk->cenc.aes_ctr) {
5322 size = ff_mov_cenc_avc_parse_nal_units(&trk->cenc, pb, pkt->data, size);
5328 size = ff_avc_parse_nal_units(pb, pkt->data, pkt->size);
5331 } else if (par->codec_id == AV_CODEC_ID_HEVC && trk->vos_len > 6 &&
5332 (AV_RB24(trk->vos_data) == 1 || AV_RB32(trk->vos_data) == 1)) {
5333 /* extradata is Annex B, assume the bitstream is too and convert it */
5334 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
5335 ff_hevc_annexb2mp4_buf(pkt->data, &reformatted_data, &size, 0, NULL);
5336 avio_write(pb, reformatted_data, size);
5338 size = ff_hevc_annexb2mp4(pb, pkt->data, pkt->size, 0, NULL);
5340 } else if (par->codec_id == AV_CODEC_ID_AV1) {
5341 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
5342 ff_av1_filter_obus_buf(pkt->data, &reformatted_data, &size);
5343 avio_write(pb, reformatted_data, size);
5345 size = ff_av1_filter_obus(pb, pkt->data, pkt->size);
5347 #if CONFIG_AC3_PARSER
5348 } else if (par->codec_id == AV_CODEC_ID_EAC3) {
5349 size = handle_eac3(mov, pkt, trk);
5354 avio_write(pb, pkt->data, size);
5357 if (trk->cenc.aes_ctr) {
5358 if (par->codec_id == AV_CODEC_ID_H264 && par->extradata_size > 4) {
5359 int nal_size_length = (par->extradata[4] & 0x3) + 1;
5360 ret = ff_mov_cenc_avc_write_nal_units(s, &trk->cenc, nal_size_length, pb, pkt->data, size);
5362 ret = ff_mov_cenc_write_packet(&trk->cenc, pb, pkt->data, size);
5369 avio_write(pb, pkt->data, size);
5373 if ((par->codec_id == AV_CODEC_ID_DNXHD ||
5374 par->codec_id == AV_CODEC_ID_AC3) && !trk->vos_len) {
5375 /* copy frame to create needed atoms */
5376 trk->vos_len = size;
5377 trk->vos_data = av_malloc(size);
5378 if (!trk->vos_data) {
5379 ret = AVERROR(ENOMEM);
5382 memcpy(trk->vos_data, pkt->data, size);
5385 if (trk->entry >= trk->cluster_capacity) {
5386 unsigned new_capacity = 2 * (trk->entry + MOV_INDEX_CLUSTER_SIZE);
5387 if (av_reallocp_array(&trk->cluster, new_capacity,
5388 sizeof(*trk->cluster))) {
5389 ret = AVERROR(ENOMEM);
5392 trk->cluster_capacity = new_capacity;
5395 trk->cluster[trk->entry].pos = avio_tell(pb) - size;
5396 trk->cluster[trk->entry].samples_in_chunk = samples_in_chunk;
5397 trk->cluster[trk->entry].chunkNum = 0;
5398 trk->cluster[trk->entry].size = size;
5399 trk->cluster[trk->entry].entries = samples_in_chunk;
5400 trk->cluster[trk->entry].dts = pkt->dts;
5401 trk->cluster[trk->entry].pts = pkt->pts;
5402 if (!trk->entry && trk->start_dts != AV_NOPTS_VALUE) {
5403 if (!trk->frag_discont) {
5404 /* First packet of a new fragment. We already wrote the duration
5405 * of the last packet of the previous fragment based on track_duration,
5406 * which might not exactly match our dts. Therefore adjust the dts
5407 * of this packet to be what the previous packets duration implies. */
5408 trk->cluster[trk->entry].dts = trk->start_dts + trk->track_duration;
5409 /* We also may have written the pts and the corresponding duration
5410 * in sidx/tfrf/tfxd tags; make sure the sidx pts and duration match up with
5411 * the next fragment. This means the cts of the first sample must
5412 * be the same in all fragments, unless end_pts was updated by
5413 * the packet causing the fragment to be written. */
5414 if ((mov->flags & FF_MOV_FLAG_DASH && !(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)) ||
5415 mov->mode == MODE_ISM)
5416 pkt->pts = pkt->dts + trk->end_pts - trk->cluster[trk->entry].dts;
5418 /* New fragment, but discontinuous from previous fragments.
5419 * Pretend the duration sum of the earlier fragments is
5420 * pkt->dts - trk->start_dts. */
5421 trk->frag_start = pkt->dts - trk->start_dts;
5422 trk->end_pts = AV_NOPTS_VALUE;
5423 trk->frag_discont = 0;
5427 if (!trk->entry && trk->start_dts == AV_NOPTS_VALUE && !mov->use_editlist &&
5428 s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO) {
5429 /* Not using edit lists and shifting the first track to start from zero.
5430 * If the other streams start from a later timestamp, we won't be able
5431 * to signal the difference in starting time without an edit list.
5432 * Thus move the timestamp for this first sample to 0, increasing
5433 * its duration instead. */
5434 trk->cluster[trk->entry].dts = trk->start_dts = 0;
5436 if (trk->start_dts == AV_NOPTS_VALUE) {
5437 trk->start_dts = pkt->dts;
5438 if (trk->frag_discont) {
5439 if (mov->use_editlist) {
5440 /* Pretend the whole stream started at pts=0, with earlier fragments
5441 * already written. If the stream started at pts=0, the duration sum
5442 * of earlier fragments would have been pkt->pts. */
5443 trk->frag_start = pkt->pts;
5444 trk->start_dts = pkt->dts - pkt->pts;
5446 /* Pretend the whole stream started at dts=0, with earlier fragments
5447 * already written, with a duration summing up to pkt->dts. */
5448 trk->frag_start = pkt->dts;
5451 trk->frag_discont = 0;
5452 } else if (pkt->dts && mov->moov_written)
5453 av_log(s, AV_LOG_WARNING,
5454 "Track %d starts with a nonzero dts %"PRId64", while the moov "
5455 "already has been written. Set the delay_moov flag to handle "
5457 pkt->stream_index, pkt->dts);
5459 trk->track_duration = pkt->dts - trk->start_dts + pkt->duration;
5460 trk->last_sample_is_subtitle_end = 0;
5462 if (pkt->pts == AV_NOPTS_VALUE) {
5463 av_log(s, AV_LOG_WARNING, "pts has no value\n");
5464 pkt->pts = pkt->dts;
5466 if (pkt->dts != pkt->pts)
5467 trk->flags |= MOV_TRACK_CTTS;
5468 trk->cluster[trk->entry].cts = pkt->pts - pkt->dts;
5469 trk->cluster[trk->entry].flags = 0;
5470 if (trk->start_cts == AV_NOPTS_VALUE)
5471 trk->start_cts = pkt->pts - pkt->dts;
5472 if (trk->end_pts == AV_NOPTS_VALUE)
5473 trk->end_pts = trk->cluster[trk->entry].dts +
5474 trk->cluster[trk->entry].cts + pkt->duration;
5476 trk->end_pts = FFMAX(trk->end_pts, trk->cluster[trk->entry].dts +
5477 trk->cluster[trk->entry].cts +
5480 if (par->codec_id == AV_CODEC_ID_VC1) {
5481 mov_parse_vc1_frame(pkt, trk);
5482 } else if (pkt->flags & AV_PKT_FLAG_KEY) {
5483 if (mov->mode == MODE_MOV && par->codec_id == AV_CODEC_ID_MPEG2VIDEO &&
5484 trk->entry > 0) { // force sync sample for the first key frame
5485 mov_parse_mpeg2_frame(pkt, &trk->cluster[trk->entry].flags);
5486 if (trk->cluster[trk->entry].flags & MOV_PARTIAL_SYNC_SAMPLE)
5487 trk->flags |= MOV_TRACK_STPS;
5489 trk->cluster[trk->entry].flags = MOV_SYNC_SAMPLE;
5491 if (trk->cluster[trk->entry].flags & MOV_SYNC_SAMPLE)
5492 trk->has_keyframes++;
5494 if (pkt->flags & AV_PKT_FLAG_DISPOSABLE) {
5495 trk->cluster[trk->entry].flags |= MOV_DISPOSABLE_SAMPLE;
5496 trk->has_disposable++;
5499 trk->sample_count += samples_in_chunk;
5500 mov->mdat_size += size;
5502 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams)
5503 ff_mov_add_hinted_packet(s, pkt, trk->hint_track, trk->entry,
5504 reformatted_data, size);
5509 av_free(reformatted_data);
5513 static int mov_write_single_packet(AVFormatContext *s, AVPacket *pkt)
5515 MOVMuxContext *mov = s->priv_data;
5516 MOVTrack *trk = &mov->tracks[pkt->stream_index];
5517 AVCodecParameters *par = trk->par;
5518 int64_t frag_duration = 0;
5519 int size = pkt->size;
5521 int ret = check_pkt(s, pkt);
5525 if (mov->flags & FF_MOV_FLAG_FRAG_DISCONT) {
5527 for (i = 0; i < s->nb_streams; i++)
5528 mov->tracks[i].frag_discont = 1;
5529 mov->flags &= ~FF_MOV_FLAG_FRAG_DISCONT;
5532 if (mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS) {
5533 if (trk->dts_shift == AV_NOPTS_VALUE)
5534 trk->dts_shift = pkt->pts - pkt->dts;
5535 pkt->dts += trk->dts_shift;
5538 if (trk->par->codec_id == AV_CODEC_ID_MP4ALS ||
5539 trk->par->codec_id == AV_CODEC_ID_AAC ||
5540 trk->par->codec_id == AV_CODEC_ID_AV1 ||
5541 trk->par->codec_id == AV_CODEC_ID_FLAC) {
5543 uint8_t *side = av_packet_get_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA, &side_size);
5544 if (side && side_size > 0 && (side_size != par->extradata_size || memcmp(side, par->extradata, side_size))) {
5545 void *newextra = av_mallocz(side_size + AV_INPUT_BUFFER_PADDING_SIZE);
5547 return AVERROR(ENOMEM);
5548 av_free(par->extradata);
5549 par->extradata = newextra;
5550 memcpy(par->extradata, side, side_size);
5551 par->extradata_size = side_size;
5552 if (!pkt->size) // Flush packet
5553 mov->need_rewrite_extradata = 1;
5558 if (trk->start_dts == AV_NOPTS_VALUE && trk->frag_discont) {
5559 trk->start_dts = pkt->dts;
5560 if (pkt->pts != AV_NOPTS_VALUE)
5561 trk->start_cts = pkt->pts - pkt->dts;
5566 return 0; /* Discard 0 sized packets */
5569 if (trk->entry && pkt->stream_index < s->nb_streams)
5570 frag_duration = av_rescale_q(pkt->dts - trk->cluster[0].dts,
5571 s->streams[pkt->stream_index]->time_base,
5573 if ((mov->max_fragment_duration &&
5574 frag_duration >= mov->max_fragment_duration) ||
5575 (mov->max_fragment_size && mov->mdat_size + size >= mov->max_fragment_size) ||
5576 (mov->flags & FF_MOV_FLAG_FRAG_KEYFRAME &&
5577 par->codec_type == AVMEDIA_TYPE_VIDEO &&
5578 trk->entry && pkt->flags & AV_PKT_FLAG_KEY) ||
5579 (mov->flags & FF_MOV_FLAG_FRAG_EVERY_FRAME)) {
5580 if (frag_duration >= mov->min_fragment_duration) {
5581 // Set the duration of this track to line up with the next
5582 // sample in this track. This avoids relying on AVPacket
5583 // duration, but only helps for this particular track, not
5584 // for the other ones that are flushed at the same time.
5585 trk->track_duration = pkt->dts - trk->start_dts;
5586 if (pkt->pts != AV_NOPTS_VALUE)
5587 trk->end_pts = pkt->pts;
5589 trk->end_pts = pkt->dts;
5590 trk->end_reliable = 1;
5591 mov_auto_flush_fragment(s, 0);
5595 return ff_mov_write_packet(s, pkt);
5598 static int mov_write_subtitle_end_packet(AVFormatContext *s,
5602 uint8_t data[2] = {0};
5605 av_init_packet(&end);
5606 end.size = sizeof(data);
5611 end.stream_index = stream_index;
5613 ret = mov_write_single_packet(s, &end);
5614 av_packet_unref(&end);
5619 static int mov_write_packet(AVFormatContext *s, AVPacket *pkt)
5621 MOVMuxContext *mov = s->priv_data;
5625 mov_flush_fragment(s, 1);
5629 trk = &mov->tracks[pkt->stream_index];
5631 if (is_cover_image(trk->st)) {
5634 if (trk->st->nb_frames >= 1) {
5635 if (trk->st->nb_frames == 1)
5636 av_log(s, AV_LOG_WARNING, "Got more than one picture in stream %d,"
5637 " ignoring.\n", pkt->stream_index);
5641 if ((ret = av_packet_ref(&trk->cover_image, pkt)) < 0)
5649 return mov_write_single_packet(s, pkt); /* Passthrough. */
5652 * Subtitles require special handling.
5654 * 1) For full complaince, every track must have a sample at
5655 * dts == 0, which is rarely true for subtitles. So, as soon
5656 * as we see any packet with dts > 0, write an empty subtitle
5657 * at dts == 0 for any subtitle track with no samples in it.
5659 * 2) For each subtitle track, check if the current packet's
5660 * dts is past the duration of the last subtitle sample. If
5661 * so, we now need to write an end sample for that subtitle.
5663 * This must be done conditionally to allow for subtitles that
5664 * immediately replace each other, in which case an end sample
5665 * is not needed, and is, in fact, actively harmful.
5667 * 3) See mov_write_trailer for how the final end sample is
5670 for (i = 0; i < mov->nb_streams; i++) {
5671 MOVTrack *trk = &mov->tracks[i];
5674 if (trk->par->codec_id == AV_CODEC_ID_MOV_TEXT &&
5675 trk->track_duration < pkt->dts &&
5676 (trk->entry == 0 || !trk->last_sample_is_subtitle_end)) {
5677 ret = mov_write_subtitle_end_packet(s, i, trk->track_duration);
5678 if (ret < 0) return ret;
5679 trk->last_sample_is_subtitle_end = 1;
5683 if (trk->mode == MODE_MOV && trk->par->codec_type == AVMEDIA_TYPE_VIDEO) {
5684 AVPacket *opkt = pkt;
5685 int reshuffle_ret, ret;
5686 if (trk->is_unaligned_qt_rgb) {
5687 int64_t bpc = trk->par->bits_per_coded_sample != 15 ? trk->par->bits_per_coded_sample : 16;
5688 int expected_stride = ((trk->par->width * bpc + 15) >> 4)*2;
5689 reshuffle_ret = ff_reshuffle_raw_rgb(s, &pkt, trk->par, expected_stride);
5690 if (reshuffle_ret < 0)
5691 return reshuffle_ret;
5694 if (trk->par->format == AV_PIX_FMT_PAL8 && !trk->pal_done) {
5695 ret = ff_get_packet_palette(s, opkt, reshuffle_ret, trk->palette);
5700 } else if (trk->par->codec_id == AV_CODEC_ID_RAWVIDEO &&
5701 (trk->par->format == AV_PIX_FMT_GRAY8 ||
5702 trk->par->format == AV_PIX_FMT_MONOBLACK)) {
5703 for (i = 0; i < pkt->size; i++)
5704 pkt->data[i] = ~pkt->data[i];
5706 if (reshuffle_ret) {
5707 ret = mov_write_single_packet(s, pkt);
5710 av_packet_free(&pkt);
5715 return mov_write_single_packet(s, pkt);
5719 // QuickTime chapters involve an additional text track with the chapter names
5720 // as samples, and a tref pointing from the other tracks to the chapter one.
5721 static int mov_create_chapter_track(AVFormatContext *s, int tracknum)
5725 MOVMuxContext *mov = s->priv_data;
5726 MOVTrack *track = &mov->tracks[tracknum];
5727 AVPacket pkt = { .stream_index = tracknum, .flags = AV_PKT_FLAG_KEY };
5730 track->mode = mov->mode;
5731 track->tag = MKTAG('t','e','x','t');
5732 track->timescale = MOV_TIMESCALE;
5733 track->par = avcodec_parameters_alloc();
5735 return AVERROR(ENOMEM);
5736 track->par->codec_type = AVMEDIA_TYPE_SUBTITLE;
5738 // These properties are required to make QT recognize the chapter track
5739 uint8_t chapter_properties[43] = { 0, 0, 0, 0, 0, 0, 0, 1, };
5740 if (ff_alloc_extradata(track->par, sizeof(chapter_properties)))
5741 return AVERROR(ENOMEM);
5742 memcpy(track->par->extradata, chapter_properties, sizeof(chapter_properties));
5744 if (avio_open_dyn_buf(&pb) >= 0) {
5748 /* Stub header (usually for Quicktime chapter track) */
5750 avio_wb32(pb, 0x01); // displayFlags
5751 avio_w8(pb, 0x00); // horizontal justification
5752 avio_w8(pb, 0x00); // vertical justification
5753 avio_w8(pb, 0x00); // bgColourRed
5754 avio_w8(pb, 0x00); // bgColourGreen
5755 avio_w8(pb, 0x00); // bgColourBlue
5756 avio_w8(pb, 0x00); // bgColourAlpha
5758 avio_wb16(pb, 0x00); // defTextBoxTop
5759 avio_wb16(pb, 0x00); // defTextBoxLeft
5760 avio_wb16(pb, 0x00); // defTextBoxBottom
5761 avio_wb16(pb, 0x00); // defTextBoxRight
5763 avio_wb16(pb, 0x00); // startChar
5764 avio_wb16(pb, 0x00); // endChar
5765 avio_wb16(pb, 0x01); // fontID
5766 avio_w8(pb, 0x00); // fontStyleFlags
5767 avio_w8(pb, 0x00); // fontSize
5768 avio_w8(pb, 0x00); // fgColourRed
5769 avio_w8(pb, 0x00); // fgColourGreen
5770 avio_w8(pb, 0x00); // fgColourBlue
5771 avio_w8(pb, 0x00); // fgColourAlpha
5773 avio_wb32(pb, 0x0D); // box size
5774 ffio_wfourcc(pb, "ftab"); // box atom name
5775 avio_wb16(pb, 0x01); // entry count
5777 avio_wb16(pb, 0x01); // font ID
5778 avio_w8(pb, 0x00); // font name length
5780 if ((size = avio_close_dyn_buf(pb, &buf)) > 0) {
5781 track->par->extradata = buf;
5782 track->par->extradata_size = size;
5789 for (i = 0; i < s->nb_chapters; i++) {
5790 AVChapter *c = s->chapters[i];
5791 AVDictionaryEntry *t;
5793 int64_t end = av_rescale_q(c->end, c->time_base, (AVRational){1,MOV_TIMESCALE});
5794 pkt.pts = pkt.dts = av_rescale_q(c->start, c->time_base, (AVRational){1,MOV_TIMESCALE});
5795 pkt.duration = end - pkt.dts;
5797 if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
5798 static const char encd[12] = {
5799 0x00, 0x00, 0x00, 0x0C,
5801 0x00, 0x00, 0x01, 0x00 };
5802 len = strlen(t->value);
5803 pkt.size = len + 2 + 12;
5804 pkt.data = av_malloc(pkt.size);
5806 return AVERROR(ENOMEM);
5807 AV_WB16(pkt.data, len);
5808 memcpy(pkt.data + 2, t->value, len);
5809 memcpy(pkt.data + len + 2, encd, sizeof(encd));
5810 ff_mov_write_packet(s, &pkt);
5811 av_freep(&pkt.data);
5819 static int mov_check_timecode_track(AVFormatContext *s, AVTimecode *tc, int src_index, const char *tcstr)
5823 /* compute the frame number */
5824 ret = av_timecode_init_from_string(tc, find_fps(s, s->streams[src_index]), tcstr, s);
5828 static int mov_create_timecode_track(AVFormatContext *s, int index, int src_index, AVTimecode tc)
5831 MOVMuxContext *mov = s->priv_data;
5832 MOVTrack *track = &mov->tracks[index];
5833 AVStream *src_st = s->streams[src_index];
5834 AVPacket pkt = {.stream_index = index, .flags = AV_PKT_FLAG_KEY, .size = 4};
5835 AVRational rate = find_fps(s, src_st);
5837 /* tmcd track based on video stream */
5838 track->mode = mov->mode;
5839 track->tag = MKTAG('t','m','c','d');
5840 track->src_track = src_index;
5841 track->timescale = mov->tracks[src_index].timescale;
5842 if (tc.flags & AV_TIMECODE_FLAG_DROPFRAME)
5843 track->timecode_flags |= MOV_TIMECODE_FLAG_DROPFRAME;
5845 /* set st to src_st for metadata access*/
5848 /* encode context: tmcd data stream */
5849 track->par = avcodec_parameters_alloc();
5851 return AVERROR(ENOMEM);
5852 track->par->codec_type = AVMEDIA_TYPE_DATA;
5853 track->par->codec_tag = track->tag;
5854 track->st->avg_frame_rate = av_inv_q(rate);
5856 /* the tmcd track just contains one packet with the frame number */
5857 pkt.data = av_malloc(pkt.size);
5859 return AVERROR(ENOMEM);
5860 AV_WB32(pkt.data, tc.start);
5861 ret = ff_mov_write_packet(s, &pkt);
5867 * st->disposition controls the "enabled" flag in the tkhd tag.
5868 * QuickTime will not play a track if it is not enabled. So make sure
5869 * that one track of each type (audio, video, subtitle) is enabled.
5871 * Subtitles are special. For audio and video, setting "enabled" also
5872 * makes the track "default" (i.e. it is rendered when played). For
5873 * subtitles, an "enabled" subtitle is not rendered by default, but
5874 * if no subtitle is enabled, the subtitle menu in QuickTime will be
5877 static void enable_tracks(AVFormatContext *s)
5879 MOVMuxContext *mov = s->priv_data;
5881 int enabled[AVMEDIA_TYPE_NB];
5882 int first[AVMEDIA_TYPE_NB];
5884 for (i = 0; i < AVMEDIA_TYPE_NB; i++) {
5889 for (i = 0; i < s->nb_streams; i++) {
5890 AVStream *st = s->streams[i];
5892 if (st->codecpar->codec_type <= AVMEDIA_TYPE_UNKNOWN ||
5893 st->codecpar->codec_type >= AVMEDIA_TYPE_NB ||
5897 if (first[st->codecpar->codec_type] < 0)
5898 first[st->codecpar->codec_type] = i;
5899 if (st->disposition & AV_DISPOSITION_DEFAULT) {
5900 mov->tracks[i].flags |= MOV_TRACK_ENABLED;
5901 enabled[st->codecpar->codec_type]++;
5905 for (i = 0; i < AVMEDIA_TYPE_NB; i++) {
5907 case AVMEDIA_TYPE_VIDEO:
5908 case AVMEDIA_TYPE_AUDIO:
5909 case AVMEDIA_TYPE_SUBTITLE:
5911 mov->per_stream_grouping = 1;
5912 if (!enabled[i] && first[i] >= 0)
5913 mov->tracks[first[i]].flags |= MOV_TRACK_ENABLED;
5919 static void mov_free(AVFormatContext *s)
5921 MOVMuxContext *mov = s->priv_data;
5924 if (mov->chapter_track) {
5925 if (mov->tracks[mov->chapter_track].par)
5926 av_freep(&mov->tracks[mov->chapter_track].par->extradata);
5927 av_freep(&mov->tracks[mov->chapter_track].par);
5930 for (i = 0; i < mov->nb_streams; i++) {
5931 if (mov->tracks[i].tag == MKTAG('r','t','p',' '))
5932 ff_mov_close_hinting(&mov->tracks[i]);
5933 else if (mov->tracks[i].tag == MKTAG('t','m','c','d') && mov->nb_meta_tmcd)
5934 av_freep(&mov->tracks[i].par);
5935 av_freep(&mov->tracks[i].cluster);
5936 av_freep(&mov->tracks[i].frag_info);
5937 av_packet_unref(&mov->tracks[i].cover_image);
5939 if (mov->tracks[i].vos_len)
5940 av_freep(&mov->tracks[i].vos_data);
5942 ff_mov_cenc_free(&mov->tracks[i].cenc);
5945 av_freep(&mov->tracks);
5948 static uint32_t rgb_to_yuv(uint32_t rgb)
5953 r = (rgb >> 16) & 0xFF;
5954 g = (rgb >> 8) & 0xFF;
5957 y = av_clip_uint8(( 16000 + 257 * r + 504 * g + 98 * b)/1000);
5958 cb = av_clip_uint8((128000 - 148 * r - 291 * g + 439 * b)/1000);
5959 cr = av_clip_uint8((128000 + 439 * r - 368 * g - 71 * b)/1000);
5961 return (y << 16) | (cr << 8) | cb;
5964 static int mov_create_dvd_sub_decoder_specific_info(MOVTrack *track,
5967 int i, width = 720, height = 480;
5968 int have_palette = 0, have_size = 0;
5969 uint32_t palette[16];
5970 char *cur = st->codecpar->extradata;
5972 while (cur && *cur) {
5973 if (strncmp("palette:", cur, 8) == 0) {
5975 count = sscanf(cur + 8,
5976 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
5977 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
5978 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
5979 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32"",
5980 &palette[ 0], &palette[ 1], &palette[ 2], &palette[ 3],
5981 &palette[ 4], &palette[ 5], &palette[ 6], &palette[ 7],
5982 &palette[ 8], &palette[ 9], &palette[10], &palette[11],
5983 &palette[12], &palette[13], &palette[14], &palette[15]);
5985 for (i = 0; i < count; i++) {
5986 palette[i] = rgb_to_yuv(palette[i]);
5989 } else if (!strncmp("size:", cur, 5)) {
5990 sscanf(cur + 5, "%dx%d", &width, &height);
5993 if (have_palette && have_size)
5995 cur += strcspn(cur, "\n\r");
5996 cur += strspn(cur, "\n\r");
5999 track->vos_data = av_malloc(16*4);
6000 if (!track->vos_data)
6001 return AVERROR(ENOMEM);
6002 for (i = 0; i < 16; i++) {
6003 AV_WB32(track->vos_data + i * 4, palette[i]);
6005 track->vos_len = 16 * 4;
6007 st->codecpar->width = width;
6008 st->codecpar->height = track->height = height;
6013 static int mov_init(AVFormatContext *s)
6015 MOVMuxContext *mov = s->priv_data;
6016 AVDictionaryEntry *global_tcr = av_dict_get(s->metadata, "timecode", NULL, 0);
6021 /* Default mode == MP4 */
6022 mov->mode = MODE_MP4;
6025 if (!strcmp("3gp", s->oformat->name)) mov->mode = MODE_3GP;
6026 else if (!strcmp("3g2", s->oformat->name)) mov->mode = MODE_3GP|MODE_3G2;
6027 else if (!strcmp("mov", s->oformat->name)) mov->mode = MODE_MOV;
6028 else if (!strcmp("psp", s->oformat->name)) mov->mode = MODE_PSP;
6029 else if (!strcmp("ipod",s->oformat->name)) mov->mode = MODE_IPOD;
6030 else if (!strcmp("ismv",s->oformat->name)) mov->mode = MODE_ISM;
6031 else if (!strcmp("f4v", s->oformat->name)) mov->mode = MODE_F4V;
6034 if (mov->flags & FF_MOV_FLAG_DELAY_MOOV)
6035 mov->flags |= FF_MOV_FLAG_EMPTY_MOOV;
6037 /* Set the FRAGMENT flag if any of the fragmentation methods are
6039 if (mov->max_fragment_duration || mov->max_fragment_size ||
6040 mov->flags & (FF_MOV_FLAG_EMPTY_MOOV |
6041 FF_MOV_FLAG_FRAG_KEYFRAME |
6042 FF_MOV_FLAG_FRAG_CUSTOM |
6043 FF_MOV_FLAG_FRAG_EVERY_FRAME))
6044 mov->flags |= FF_MOV_FLAG_FRAGMENT;
6046 /* Set other implicit flags immediately */
6047 if (mov->mode == MODE_ISM)
6048 mov->flags |= FF_MOV_FLAG_EMPTY_MOOV | FF_MOV_FLAG_SEPARATE_MOOF |
6049 FF_MOV_FLAG_FRAGMENT | FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS;
6050 if (mov->flags & FF_MOV_FLAG_DASH)
6051 mov->flags |= FF_MOV_FLAG_FRAGMENT | FF_MOV_FLAG_EMPTY_MOOV |
6052 FF_MOV_FLAG_DEFAULT_BASE_MOOF;
6054 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV && s->flags & AVFMT_FLAG_AUTO_BSF) {
6055 av_log(s, AV_LOG_VERBOSE, "Empty MOOV enabled; disabling automatic bitstream filtering\n");
6056 s->flags &= ~AVFMT_FLAG_AUTO_BSF;
6059 if (mov->flags & FF_MOV_FLAG_FASTSTART) {
6060 mov->reserved_moov_size = -1;
6063 if (mov->use_editlist < 0) {
6064 mov->use_editlist = 1;
6065 if (mov->flags & FF_MOV_FLAG_FRAGMENT &&
6066 !(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
6067 // If we can avoid needing an edit list by shifting the
6068 // tracks, prefer that over (trying to) write edit lists
6069 // in fragmented output.
6070 if (s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO ||
6071 s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO)
6072 mov->use_editlist = 0;
6075 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV &&
6076 !(mov->flags & FF_MOV_FLAG_DELAY_MOOV) && mov->use_editlist)
6077 av_log(s, AV_LOG_WARNING, "No meaningful edit list will be written when using empty_moov without delay_moov\n");
6079 if (!mov->use_editlist && s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO)
6080 s->avoid_negative_ts = AVFMT_AVOID_NEG_TS_MAKE_ZERO;
6082 /* Clear the omit_tfhd_offset flag if default_base_moof is set;
6083 * if the latter is set that's enough and omit_tfhd_offset doesn't
6084 * add anything extra on top of that. */
6085 if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET &&
6086 mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)
6087 mov->flags &= ~FF_MOV_FLAG_OMIT_TFHD_OFFSET;
6089 if (mov->frag_interleave &&
6090 mov->flags & (FF_MOV_FLAG_OMIT_TFHD_OFFSET | FF_MOV_FLAG_SEPARATE_MOOF)) {
6091 av_log(s, AV_LOG_ERROR,
6092 "Sample interleaving in fragments is mutually exclusive with "
6093 "omit_tfhd_offset and separate_moof\n");
6094 return AVERROR(EINVAL);
6097 /* Non-seekable output is ok if using fragmentation. If ism_lookahead
6098 * is enabled, we don't support non-seekable output at all. */
6099 if (!(s->pb->seekable & AVIO_SEEKABLE_NORMAL) &&
6100 (!(mov->flags & FF_MOV_FLAG_FRAGMENT) || mov->ism_lookahead)) {
6101 av_log(s, AV_LOG_ERROR, "muxer does not support non seekable output\n");
6102 return AVERROR(EINVAL);
6105 mov->nb_streams = s->nb_streams;
6106 if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters)
6107 mov->chapter_track = mov->nb_streams++;
6109 if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
6110 for (i = 0; i < s->nb_streams; i++)
6111 if (rtp_hinting_needed(s->streams[i]))
6115 if ( mov->write_tmcd == -1 && (mov->mode == MODE_MOV || mov->mode == MODE_MP4)
6116 || mov->write_tmcd == 1) {
6117 /* +1 tmcd track for each video stream with a timecode */
6118 for (i = 0; i < s->nb_streams; i++) {
6119 AVStream *st = s->streams[i];
6120 AVDictionaryEntry *t = global_tcr;
6121 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
6122 (t || (t=av_dict_get(st->metadata, "timecode", NULL, 0)))) {
6124 ret = mov_check_timecode_track(s, &tc, i, t->value);
6126 mov->nb_meta_tmcd++;
6130 /* check if there is already a tmcd track to remux */
6131 if (mov->nb_meta_tmcd) {
6132 for (i = 0; i < s->nb_streams; i++) {
6133 AVStream *st = s->streams[i];
6134 if (st->codecpar->codec_tag == MKTAG('t','m','c','d')) {
6135 av_log(s, AV_LOG_WARNING, "You requested a copy of the original timecode track "
6136 "so timecode metadata are now ignored\n");
6137 mov->nb_meta_tmcd = 0;
6142 mov->nb_streams += mov->nb_meta_tmcd;
6145 // Reserve an extra stream for chapters for the case where chapters
6146 // are written in the trailer
6147 mov->tracks = av_mallocz_array((mov->nb_streams + 1), sizeof(*mov->tracks));
6149 return AVERROR(ENOMEM);
6151 if (mov->encryption_scheme_str != NULL && strcmp(mov->encryption_scheme_str, "none") != 0) {
6152 if (strcmp(mov->encryption_scheme_str, "cenc-aes-ctr") == 0) {
6153 mov->encryption_scheme = MOV_ENC_CENC_AES_CTR;
6155 if (mov->encryption_key_len != AES_CTR_KEY_SIZE) {
6156 av_log(s, AV_LOG_ERROR, "Invalid encryption key len %d expected %d\n",
6157 mov->encryption_key_len, AES_CTR_KEY_SIZE);
6158 return AVERROR(EINVAL);
6161 if (mov->encryption_kid_len != CENC_KID_SIZE) {
6162 av_log(s, AV_LOG_ERROR, "Invalid encryption kid len %d expected %d\n",
6163 mov->encryption_kid_len, CENC_KID_SIZE);
6164 return AVERROR(EINVAL);
6167 av_log(s, AV_LOG_ERROR, "unsupported encryption scheme %s\n",
6168 mov->encryption_scheme_str);
6169 return AVERROR(EINVAL);
6173 for (i = 0; i < s->nb_streams; i++) {
6174 AVStream *st= s->streams[i];
6175 MOVTrack *track= &mov->tracks[i];
6176 AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0);
6179 track->par = st->codecpar;
6180 track->language = ff_mov_iso639_to_lang(lang?lang->value:"und", mov->mode!=MODE_MOV);
6181 if (track->language < 0)
6182 track->language = 0;
6183 track->mode = mov->mode;
6184 track->tag = mov_find_codec_tag(s, track);
6186 av_log(s, AV_LOG_ERROR, "Could not find tag for codec %s in stream #%d, "
6187 "codec not currently supported in container\n",
6188 avcodec_get_name(st->codecpar->codec_id), i);
6189 return AVERROR(EINVAL);
6191 /* If hinting of this track is enabled by a later hint track,
6192 * this is updated. */
6193 track->hint_track = -1;
6194 track->start_dts = AV_NOPTS_VALUE;
6195 track->start_cts = AV_NOPTS_VALUE;
6196 track->end_pts = AV_NOPTS_VALUE;
6197 track->dts_shift = AV_NOPTS_VALUE;
6198 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
6199 if (track->tag == MKTAG('m','x','3','p') || track->tag == MKTAG('m','x','3','n') ||
6200 track->tag == MKTAG('m','x','4','p') || track->tag == MKTAG('m','x','4','n') ||
6201 track->tag == MKTAG('m','x','5','p') || track->tag == MKTAG('m','x','5','n')) {
6202 if (st->codecpar->width != 720 || (st->codecpar->height != 608 && st->codecpar->height != 512)) {
6203 av_log(s, AV_LOG_ERROR, "D-10/IMX must use 720x608 or 720x512 video resolution\n");
6204 return AVERROR(EINVAL);
6206 track->height = track->tag >> 24 == 'n' ? 486 : 576;
6208 if (mov->video_track_timescale) {
6209 track->timescale = mov->video_track_timescale;
6211 track->timescale = st->time_base.den;
6212 while(track->timescale < 10000)
6213 track->timescale *= 2;
6215 if (st->codecpar->width > 65535 || st->codecpar->height > 65535) {
6216 av_log(s, AV_LOG_ERROR, "Resolution %dx%d too large for mov/mp4\n", st->codecpar->width, st->codecpar->height);
6217 return AVERROR(EINVAL);
6219 if (track->mode == MODE_MOV && track->timescale > 100000)
6220 av_log(s, AV_LOG_WARNING,
6221 "WARNING codec timebase is very high. If duration is too long,\n"
6222 "file may not be playable by quicktime. Specify a shorter timebase\n"
6223 "or choose different container.\n");
6224 if (track->mode == MODE_MOV &&
6225 track->par->codec_id == AV_CODEC_ID_RAWVIDEO &&
6226 track->tag == MKTAG('r','a','w',' ')) {
6227 enum AVPixelFormat pix_fmt = track->par->format;
6228 if (pix_fmt == AV_PIX_FMT_NONE && track->par->bits_per_coded_sample == 1)
6229 pix_fmt = AV_PIX_FMT_MONOWHITE;
6230 track->is_unaligned_qt_rgb =
6231 pix_fmt == AV_PIX_FMT_RGB24 ||
6232 pix_fmt == AV_PIX_FMT_BGR24 ||
6233 pix_fmt == AV_PIX_FMT_PAL8 ||
6234 pix_fmt == AV_PIX_FMT_GRAY8 ||
6235 pix_fmt == AV_PIX_FMT_MONOWHITE ||
6236 pix_fmt == AV_PIX_FMT_MONOBLACK;
6238 if (track->par->codec_id == AV_CODEC_ID_VP9 ||
6239 track->par->codec_id == AV_CODEC_ID_AV1) {
6240 if (track->mode != MODE_MP4) {
6241 av_log(s, AV_LOG_ERROR, "%s only supported in MP4.\n", avcodec_get_name(track->par->codec_id));
6242 return AVERROR(EINVAL);
6244 if (track->par->codec_id == AV_CODEC_ID_AV1 &&
6245 s->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
6246 av_log(s, AV_LOG_ERROR,
6247 "av1 in MP4 support is experimental, add "
6248 "'-strict %d' if you want to use it.\n",
6249 FF_COMPLIANCE_EXPERIMENTAL);
6250 return AVERROR_EXPERIMENTAL;
6252 } else if (track->par->codec_id == AV_CODEC_ID_VP8) {
6253 /* altref frames handling is not defined in the spec as of version v1.0,
6254 * so just forbid muxing VP8 streams altogether until a new version does */
6255 av_log(s, AV_LOG_ERROR, "VP8 muxing is currently not supported.\n");
6256 return AVERROR_PATCHWELCOME;
6258 } else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
6259 track->timescale = st->codecpar->sample_rate;
6260 if (!st->codecpar->frame_size && !av_get_bits_per_sample(st->codecpar->codec_id)) {
6261 av_log(s, AV_LOG_WARNING, "track %d: codec frame size is not set\n", i);
6262 track->audio_vbr = 1;
6263 }else if (st->codecpar->codec_id == AV_CODEC_ID_ADPCM_MS ||
6264 st->codecpar->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
6265 st->codecpar->codec_id == AV_CODEC_ID_ILBC){
6266 if (!st->codecpar->block_align) {
6267 av_log(s, AV_LOG_ERROR, "track %d: codec block align is not set for adpcm\n", i);
6268 return AVERROR(EINVAL);
6270 track->sample_size = st->codecpar->block_align;
6271 }else if (st->codecpar->frame_size > 1){ /* assume compressed audio */
6272 track->audio_vbr = 1;
6274 track->sample_size = (av_get_bits_per_sample(st->codecpar->codec_id) >> 3) * st->codecpar->channels;
6276 if (st->codecpar->codec_id == AV_CODEC_ID_ILBC ||
6277 st->codecpar->codec_id == AV_CODEC_ID_ADPCM_IMA_QT) {
6278 track->audio_vbr = 1;
6280 if (track->mode != MODE_MOV &&
6281 track->par->codec_id == AV_CODEC_ID_MP3 && track->timescale < 16000) {
6282 if (s->strict_std_compliance >= FF_COMPLIANCE_NORMAL) {
6283 av_log(s, AV_LOG_ERROR, "track %d: muxing mp3 at %dhz is not standard, to mux anyway set strict to -1\n",
6284 i, track->par->sample_rate);
6285 return AVERROR(EINVAL);
6287 av_log(s, AV_LOG_WARNING, "track %d: muxing mp3 at %dhz is not standard in MP4\n",
6288 i, track->par->sample_rate);
6291 if (track->par->codec_id == AV_CODEC_ID_FLAC ||
6292 track->par->codec_id == AV_CODEC_ID_OPUS) {
6293 if (track->mode != MODE_MP4) {
6294 av_log(s, AV_LOG_ERROR, "%s only supported in MP4.\n", avcodec_get_name(track->par->codec_id));
6295 return AVERROR(EINVAL);
6297 if (s->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
6298 av_log(s, AV_LOG_ERROR,
6299 "%s in MP4 support is experimental, add "
6300 "'-strict %d' if you want to use it.\n",
6301 avcodec_get_name(track->par->codec_id), FF_COMPLIANCE_EXPERIMENTAL);
6302 return AVERROR_EXPERIMENTAL;
6305 } else if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) {
6306 track->timescale = st->time_base.den;
6307 } else if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA) {
6308 track->timescale = st->time_base.den;
6310 track->timescale = MOV_TIMESCALE;
6313 track->height = st->codecpar->height;
6314 /* The ism specific timescale isn't mandatory, but is assumed by
6315 * some tools, such as mp4split. */
6316 if (mov->mode == MODE_ISM)
6317 track->timescale = 10000000;
6319 avpriv_set_pts_info(st, 64, 1, track->timescale);
6321 if (mov->encryption_scheme == MOV_ENC_CENC_AES_CTR) {
6322 ret = ff_mov_cenc_init(&track->cenc, mov->encryption_key,
6323 track->par->codec_id == AV_CODEC_ID_H264, s->flags & AVFMT_FLAG_BITEXACT);
6333 static int mov_write_header(AVFormatContext *s)
6335 AVIOContext *pb = s->pb;
6336 MOVMuxContext *mov = s->priv_data;
6337 AVDictionaryEntry *t, *global_tcr = av_dict_get(s->metadata, "timecode", NULL, 0);
6338 int i, ret, hint_track = 0, tmcd_track = 0, nb_tracks = s->nb_streams;
6340 if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters)
6343 if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
6344 hint_track = nb_tracks;
6345 for (i = 0; i < s->nb_streams; i++)
6346 if (rtp_hinting_needed(s->streams[i]))
6350 if (mov->mode == MODE_MOV || mov->mode == MODE_MP4)
6351 tmcd_track = nb_tracks;
6353 for (i = 0; i < s->nb_streams; i++) {
6355 AVStream *st= s->streams[i];
6356 MOVTrack *track= &mov->tracks[i];
6358 /* copy extradata if it exists */
6359 if (st->codecpar->extradata_size) {
6360 if (st->codecpar->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
6361 mov_create_dvd_sub_decoder_specific_info(track, st);
6362 else if (!TAG_IS_AVCI(track->tag) && st->codecpar->codec_id != AV_CODEC_ID_DNXHD) {
6363 track->vos_len = st->codecpar->extradata_size;
6364 track->vos_data = av_malloc(track->vos_len);
6365 if (!track->vos_data) {
6366 return AVERROR(ENOMEM);
6368 memcpy(track->vos_data, st->codecpar->extradata, track->vos_len);
6372 if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ||
6373 track->par->channel_layout != AV_CH_LAYOUT_MONO)
6376 for (j = 0; j < s->nb_streams; j++) {
6377 AVStream *stj= s->streams[j];
6378 MOVTrack *trackj= &mov->tracks[j];
6382 if (stj->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ||
6383 trackj->par->channel_layout != AV_CH_LAYOUT_MONO ||
6384 trackj->language != track->language ||
6385 trackj->tag != track->tag
6388 track->multichannel_as_mono++;
6392 if (!(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
6393 if ((ret = mov_write_identification(pb, s)) < 0)
6397 if (mov->reserved_moov_size){
6398 mov->reserved_header_pos = avio_tell(pb);
6399 if (mov->reserved_moov_size > 0)
6400 avio_skip(pb, mov->reserved_moov_size);
6403 if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
6404 /* If no fragmentation options have been set, set a default. */
6405 if (!(mov->flags & (FF_MOV_FLAG_FRAG_KEYFRAME |
6406 FF_MOV_FLAG_FRAG_CUSTOM |
6407 FF_MOV_FLAG_FRAG_EVERY_FRAME)) &&
6408 !mov->max_fragment_duration && !mov->max_fragment_size)
6409 mov->flags |= FF_MOV_FLAG_FRAG_KEYFRAME;
6411 if (mov->flags & FF_MOV_FLAG_FASTSTART)
6412 mov->reserved_header_pos = avio_tell(pb);
6413 mov_write_mdat_tag(pb, mov);
6416 ff_parse_creation_time_metadata(s, &mov->time, 1);
6418 mov->time += 0x7C25B080; // 1970 based -> 1904 based
6420 if (mov->chapter_track)
6421 if ((ret = mov_create_chapter_track(s, mov->chapter_track)) < 0)
6424 if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
6425 for (i = 0; i < s->nb_streams; i++) {
6426 if (rtp_hinting_needed(s->streams[i])) {
6427 if ((ret = ff_mov_init_hinting(s, hint_track, i)) < 0)
6434 if (mov->nb_meta_tmcd) {
6435 /* Initialize the tmcd tracks */
6436 for (i = 0; i < s->nb_streams; i++) {
6437 AVStream *st = s->streams[i];
6440 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
6443 t = av_dict_get(st->metadata, "timecode", NULL, 0);
6446 if (mov_check_timecode_track(s, &tc, i, t->value) < 0)
6448 if ((ret = mov_create_timecode_track(s, tmcd_track, i, tc)) < 0)
6457 if (mov->flags & FF_MOV_FLAG_ISML)
6458 mov_write_isml_manifest(pb, mov, s);
6460 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV &&
6461 !(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
6462 if ((ret = mov_write_moov_tag(pb, mov, s)) < 0)
6465 mov->moov_written = 1;
6466 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
6467 mov->reserved_header_pos = avio_tell(pb);
6473 static int get_moov_size(AVFormatContext *s)
6476 AVIOContext *moov_buf;
6477 MOVMuxContext *mov = s->priv_data;
6479 if ((ret = ffio_open_null_buf(&moov_buf)) < 0)
6481 if ((ret = mov_write_moov_tag(moov_buf, mov, s)) < 0)
6483 return ffio_close_null_buf(moov_buf);
6486 static int get_sidx_size(AVFormatContext *s)
6490 MOVMuxContext *mov = s->priv_data;
6492 if ((ret = ffio_open_null_buf(&buf)) < 0)
6494 mov_write_sidx_tags(buf, mov, -1, 0);
6495 return ffio_close_null_buf(buf);
6499 * This function gets the moov size if moved to the top of the file: the chunk
6500 * offset table can switch between stco (32-bit entries) to co64 (64-bit
6501 * entries) when the moov is moved to the beginning, so the size of the moov
6502 * would change. It also updates the chunk offset tables.
6504 static int compute_moov_size(AVFormatContext *s)
6506 int i, moov_size, moov_size2;
6507 MOVMuxContext *mov = s->priv_data;
6509 moov_size = get_moov_size(s);
6513 for (i = 0; i < mov->nb_streams; i++)
6514 mov->tracks[i].data_offset += moov_size;
6516 moov_size2 = get_moov_size(s);
6520 /* if the size changed, we just switched from stco to co64 and need to
6521 * update the offsets */
6522 if (moov_size2 != moov_size)
6523 for (i = 0; i < mov->nb_streams; i++)
6524 mov->tracks[i].data_offset += moov_size2 - moov_size;
6529 static int compute_sidx_size(AVFormatContext *s)
6532 MOVMuxContext *mov = s->priv_data;
6534 sidx_size = get_sidx_size(s);
6538 for (i = 0; i < mov->nb_streams; i++)
6539 mov->tracks[i].data_offset += sidx_size;
6544 static int shift_data(AVFormatContext *s)
6546 int ret = 0, moov_size;
6547 MOVMuxContext *mov = s->priv_data;
6548 int64_t pos, pos_end = avio_tell(s->pb);
6549 uint8_t *buf, *read_buf[2];
6550 int read_buf_id = 0;
6552 AVIOContext *read_pb;
6554 if (mov->flags & FF_MOV_FLAG_FRAGMENT)
6555 moov_size = compute_sidx_size(s);
6557 moov_size = compute_moov_size(s);
6561 buf = av_malloc(moov_size * 2);
6563 return AVERROR(ENOMEM);
6565 read_buf[1] = buf + moov_size;
6567 /* Shift the data: the AVIO context of the output can only be used for
6568 * writing, so we re-open the same output, but for reading. It also avoids
6569 * a read/seek/write/seek back and forth. */
6571 ret = s->io_open(s, &read_pb, s->url, AVIO_FLAG_READ, NULL);
6573 av_log(s, AV_LOG_ERROR, "Unable to re-open %s output file for "
6574 "the second pass (faststart)\n", s->url);
6578 /* mark the end of the shift to up to the last data we wrote, and get ready
6580 pos_end = avio_tell(s->pb);
6581 avio_seek(s->pb, mov->reserved_header_pos + moov_size, SEEK_SET);
6583 /* start reading at where the new moov will be placed */
6584 avio_seek(read_pb, mov->reserved_header_pos, SEEK_SET);
6585 pos = avio_tell(read_pb);
6587 #define READ_BLOCK do { \
6588 read_size[read_buf_id] = avio_read(read_pb, read_buf[read_buf_id], moov_size); \
6592 /* shift data by chunk of at most moov_size */
6597 n = read_size[read_buf_id];
6600 avio_write(s->pb, read_buf[read_buf_id], n);
6602 } while (pos < pos_end);
6603 ff_format_io_close(s, &read_pb);
6610 static int mov_write_trailer(AVFormatContext *s)
6612 MOVMuxContext *mov = s->priv_data;
6613 AVIOContext *pb = s->pb;
6618 if (mov->need_rewrite_extradata) {
6619 for (i = 0; i < s->nb_streams; i++) {
6620 MOVTrack *track = &mov->tracks[i];
6621 AVCodecParameters *par = track->par;
6623 track->vos_len = par->extradata_size;
6624 track->vos_data = av_malloc(track->vos_len);
6625 if (!track->vos_data)
6626 return AVERROR(ENOMEM);
6627 memcpy(track->vos_data, par->extradata, track->vos_len);
6629 mov->need_rewrite_extradata = 0;
6633 * Before actually writing the trailer, make sure that there are no
6634 * dangling subtitles, that need a terminating sample.
6636 for (i = 0; i < mov->nb_streams; i++) {
6637 MOVTrack *trk = &mov->tracks[i];
6638 if (trk->par->codec_id == AV_CODEC_ID_MOV_TEXT &&
6639 !trk->last_sample_is_subtitle_end) {
6640 mov_write_subtitle_end_packet(s, i, trk->track_duration);
6641 trk->last_sample_is_subtitle_end = 1;
6645 // If there were no chapters when the header was written, but there
6646 // are chapters now, write them in the trailer. This only works
6647 // when we are not doing fragments.
6648 if (!mov->chapter_track && !(mov->flags & FF_MOV_FLAG_FRAGMENT)) {
6649 if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters) {
6650 mov->chapter_track = mov->nb_streams++;
6651 if ((res = mov_create_chapter_track(s, mov->chapter_track)) < 0)
6656 if (!(mov->flags & FF_MOV_FLAG_FRAGMENT)) {
6657 moov_pos = avio_tell(pb);
6659 /* Write size of mdat tag */
6660 if (mov->mdat_size + 8 <= UINT32_MAX) {
6661 avio_seek(pb, mov->mdat_pos, SEEK_SET);
6662 avio_wb32(pb, mov->mdat_size + 8);
6664 /* overwrite 'wide' placeholder atom */
6665 avio_seek(pb, mov->mdat_pos - 8, SEEK_SET);
6666 /* special value: real atom size will be 64 bit value after
6669 ffio_wfourcc(pb, "mdat");
6670 avio_wb64(pb, mov->mdat_size + 16);
6672 avio_seek(pb, mov->reserved_moov_size > 0 ? mov->reserved_header_pos : moov_pos, SEEK_SET);
6674 if (mov->flags & FF_MOV_FLAG_FASTSTART) {
6675 av_log(s, AV_LOG_INFO, "Starting second pass: moving the moov atom to the beginning of the file\n");
6676 res = shift_data(s);
6679 avio_seek(pb, mov->reserved_header_pos, SEEK_SET);
6680 if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
6682 } else if (mov->reserved_moov_size > 0) {
6684 if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
6686 size = mov->reserved_moov_size - (avio_tell(pb) - mov->reserved_header_pos);
6688 av_log(s, AV_LOG_ERROR, "reserved_moov_size is too small, needed %"PRId64" additional\n", 8-size);
6689 return AVERROR(EINVAL);
6691 avio_wb32(pb, size);
6692 ffio_wfourcc(pb, "free");
6693 ffio_fill(pb, 0, size - 8);
6694 avio_seek(pb, moov_pos, SEEK_SET);
6696 if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
6701 mov_auto_flush_fragment(s, 1);
6702 for (i = 0; i < mov->nb_streams; i++)
6703 mov->tracks[i].data_offset = 0;
6704 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) {
6706 av_log(s, AV_LOG_INFO, "Starting second pass: inserting sidx atoms\n");
6707 res = shift_data(s);
6710 end = avio_tell(pb);
6711 avio_seek(pb, mov->reserved_header_pos, SEEK_SET);
6712 mov_write_sidx_tags(pb, mov, -1, 0);
6713 avio_seek(pb, end, SEEK_SET);
6714 avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_TRAILER);
6715 mov_write_mfra_tag(pb, mov);
6716 } else if (!(mov->flags & FF_MOV_FLAG_SKIP_TRAILER)) {
6717 avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_TRAILER);
6718 mov_write_mfra_tag(pb, mov);
6725 static int mov_check_bitstream(struct AVFormatContext *s, const AVPacket *pkt)
6728 AVStream *st = s->streams[pkt->stream_index];
6730 if (st->codecpar->codec_id == AV_CODEC_ID_AAC) {
6731 if (pkt->size > 2 && (AV_RB16(pkt->data) & 0xfff0) == 0xfff0)
6732 ret = ff_stream_add_bitstream_filter(st, "aac_adtstoasc", NULL);
6733 } else if (st->codecpar->codec_id == AV_CODEC_ID_VP9) {
6734 ret = ff_stream_add_bitstream_filter(st, "vp9_superframe", NULL);
6740 static const AVCodecTag codec_3gp_tags[] = {
6741 { AV_CODEC_ID_H263, MKTAG('s','2','6','3') },
6742 { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
6743 { AV_CODEC_ID_MPEG4, MKTAG('m','p','4','v') },
6744 { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
6745 { AV_CODEC_ID_AMR_NB, MKTAG('s','a','m','r') },
6746 { AV_CODEC_ID_AMR_WB, MKTAG('s','a','w','b') },
6747 { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
6748 { AV_CODEC_ID_NONE, 0 },
6751 const AVCodecTag codec_mp4_tags[] = {
6752 { AV_CODEC_ID_MPEG4 , MKTAG('m', 'p', '4', 'v') },
6753 { AV_CODEC_ID_H264 , MKTAG('a', 'v', 'c', '1') },
6754 { AV_CODEC_ID_H264 , MKTAG('a', 'v', 'c', '3') },
6755 { AV_CODEC_ID_HEVC , MKTAG('h', 'e', 'v', '1') },
6756 { AV_CODEC_ID_HEVC , MKTAG('h', 'v', 'c', '1') },
6757 { AV_CODEC_ID_MPEG2VIDEO , MKTAG('m', 'p', '4', 'v') },
6758 { AV_CODEC_ID_MPEG1VIDEO , MKTAG('m', 'p', '4', 'v') },
6759 { AV_CODEC_ID_MJPEG , MKTAG('m', 'p', '4', 'v') },
6760 { AV_CODEC_ID_PNG , MKTAG('m', 'p', '4', 'v') },
6761 { AV_CODEC_ID_JPEG2000 , MKTAG('m', 'p', '4', 'v') },
6762 { AV_CODEC_ID_VC1 , MKTAG('v', 'c', '-', '1') },
6763 { AV_CODEC_ID_DIRAC , MKTAG('d', 'r', 'a', 'c') },
6764 { AV_CODEC_ID_TSCC2 , MKTAG('m', 'p', '4', 'v') },
6765 { AV_CODEC_ID_VP9 , MKTAG('v', 'p', '0', '9') },
6766 { AV_CODEC_ID_AV1 , MKTAG('a', 'v', '0', '1') },
6767 { AV_CODEC_ID_AAC , MKTAG('m', 'p', '4', 'a') },
6768 { AV_CODEC_ID_MP4ALS , MKTAG('m', 'p', '4', 'a') },
6769 { AV_CODEC_ID_MP3 , MKTAG('m', 'p', '4', 'a') },
6770 { AV_CODEC_ID_MP2 , MKTAG('m', 'p', '4', 'a') },
6771 { AV_CODEC_ID_AC3 , MKTAG('a', 'c', '-', '3') },
6772 { AV_CODEC_ID_EAC3 , MKTAG('e', 'c', '-', '3') },
6773 { AV_CODEC_ID_DTS , MKTAG('m', 'p', '4', 'a') },
6774 { AV_CODEC_ID_FLAC , MKTAG('f', 'L', 'a', 'C') },
6775 { AV_CODEC_ID_OPUS , MKTAG('O', 'p', 'u', 's') },
6776 { AV_CODEC_ID_VORBIS , MKTAG('m', 'p', '4', 'a') },
6777 { AV_CODEC_ID_QCELP , MKTAG('m', 'p', '4', 'a') },
6778 { AV_CODEC_ID_EVRC , MKTAG('m', 'p', '4', 'a') },
6779 { AV_CODEC_ID_DVD_SUBTITLE, MKTAG('m', 'p', '4', 's') },
6780 { AV_CODEC_ID_MOV_TEXT , MKTAG('t', 'x', '3', 'g') },
6781 { AV_CODEC_ID_NONE , 0 },
6784 const AVCodecTag codec_ism_tags[] = {
6785 { AV_CODEC_ID_WMAPRO , MKTAG('w', 'm', 'a', ' ') },
6786 { AV_CODEC_ID_NONE , 0 },
6789 static const AVCodecTag codec_ipod_tags[] = {
6790 { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
6791 { AV_CODEC_ID_MPEG4, MKTAG('m','p','4','v') },
6792 { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
6793 { AV_CODEC_ID_ALAC, MKTAG('a','l','a','c') },
6794 { AV_CODEC_ID_AC3, MKTAG('a','c','-','3') },
6795 { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
6796 { AV_CODEC_ID_MOV_TEXT, MKTAG('t','e','x','t') },
6797 { AV_CODEC_ID_NONE, 0 },
6800 static const AVCodecTag codec_f4v_tags[] = {
6801 { AV_CODEC_ID_MP3, MKTAG('.','m','p','3') },
6802 { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
6803 { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
6804 { AV_CODEC_ID_VP6A, MKTAG('V','P','6','A') },
6805 { AV_CODEC_ID_VP6F, MKTAG('V','P','6','F') },
6806 { AV_CODEC_ID_NONE, 0 },
6809 #if CONFIG_MOV_MUXER
6811 AVOutputFormat ff_mov_muxer = {
6813 .long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
6814 .extensions = "mov",
6815 .priv_data_size = sizeof(MOVMuxContext),
6816 .audio_codec = AV_CODEC_ID_AAC,
6817 .video_codec = CONFIG_LIBX264_ENCODER ?
6818 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
6820 .write_header = mov_write_header,
6821 .write_packet = mov_write_packet,
6822 .write_trailer = mov_write_trailer,
6824 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6825 .codec_tag = (const AVCodecTag* const []){
6826 ff_codec_movvideo_tags, ff_codec_movaudio_tags, 0
6828 .check_bitstream = mov_check_bitstream,
6829 .priv_class = &mov_muxer_class,
6832 #if CONFIG_TGP_MUXER
6834 AVOutputFormat ff_tgp_muxer = {
6836 .long_name = NULL_IF_CONFIG_SMALL("3GP (3GPP file format)"),
6837 .extensions = "3gp",
6838 .priv_data_size = sizeof(MOVMuxContext),
6839 .audio_codec = AV_CODEC_ID_AMR_NB,
6840 .video_codec = AV_CODEC_ID_H263,
6842 .write_header = mov_write_header,
6843 .write_packet = mov_write_packet,
6844 .write_trailer = mov_write_trailer,
6846 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6847 .codec_tag = (const AVCodecTag* const []){ codec_3gp_tags, 0 },
6848 .check_bitstream = mov_check_bitstream,
6849 .priv_class = &tgp_muxer_class,
6852 #if CONFIG_MP4_MUXER
6854 AVOutputFormat ff_mp4_muxer = {
6856 .long_name = NULL_IF_CONFIG_SMALL("MP4 (MPEG-4 Part 14)"),
6857 .mime_type = "video/mp4",
6858 .extensions = "mp4",
6859 .priv_data_size = sizeof(MOVMuxContext),
6860 .audio_codec = AV_CODEC_ID_AAC,
6861 .video_codec = CONFIG_LIBX264_ENCODER ?
6862 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
6864 .write_header = mov_write_header,
6865 .write_packet = mov_write_packet,
6866 .write_trailer = mov_write_trailer,
6868 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6869 .codec_tag = (const AVCodecTag* const []){ codec_mp4_tags, 0 },
6870 .check_bitstream = mov_check_bitstream,
6871 .priv_class = &mp4_muxer_class,
6874 #if CONFIG_PSP_MUXER
6876 AVOutputFormat ff_psp_muxer = {
6878 .long_name = NULL_IF_CONFIG_SMALL("PSP MP4 (MPEG-4 Part 14)"),
6879 .extensions = "mp4,psp",
6880 .priv_data_size = sizeof(MOVMuxContext),
6881 .audio_codec = AV_CODEC_ID_AAC,
6882 .video_codec = CONFIG_LIBX264_ENCODER ?
6883 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
6885 .write_header = mov_write_header,
6886 .write_packet = mov_write_packet,
6887 .write_trailer = mov_write_trailer,
6889 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6890 .codec_tag = (const AVCodecTag* const []){ codec_mp4_tags, 0 },
6891 .check_bitstream = mov_check_bitstream,
6892 .priv_class = &psp_muxer_class,
6895 #if CONFIG_TG2_MUXER
6897 AVOutputFormat ff_tg2_muxer = {
6899 .long_name = NULL_IF_CONFIG_SMALL("3GP2 (3GPP2 file format)"),
6900 .extensions = "3g2",
6901 .priv_data_size = sizeof(MOVMuxContext),
6902 .audio_codec = AV_CODEC_ID_AMR_NB,
6903 .video_codec = AV_CODEC_ID_H263,
6905 .write_header = mov_write_header,
6906 .write_packet = mov_write_packet,
6907 .write_trailer = mov_write_trailer,
6909 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6910 .codec_tag = (const AVCodecTag* const []){ codec_3gp_tags, 0 },
6911 .check_bitstream = mov_check_bitstream,
6912 .priv_class = &tg2_muxer_class,
6915 #if CONFIG_IPOD_MUXER
6917 AVOutputFormat ff_ipod_muxer = {
6919 .long_name = NULL_IF_CONFIG_SMALL("iPod H.264 MP4 (MPEG-4 Part 14)"),
6920 .mime_type = "video/mp4",
6921 .extensions = "m4v,m4a,m4b",
6922 .priv_data_size = sizeof(MOVMuxContext),
6923 .audio_codec = AV_CODEC_ID_AAC,
6924 .video_codec = AV_CODEC_ID_H264,
6926 .write_header = mov_write_header,
6927 .write_packet = mov_write_packet,
6928 .write_trailer = mov_write_trailer,
6930 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6931 .codec_tag = (const AVCodecTag* const []){ codec_ipod_tags, 0 },
6932 .check_bitstream = mov_check_bitstream,
6933 .priv_class = &ipod_muxer_class,
6936 #if CONFIG_ISMV_MUXER
6938 AVOutputFormat ff_ismv_muxer = {
6940 .long_name = NULL_IF_CONFIG_SMALL("ISMV/ISMA (Smooth Streaming)"),
6941 .mime_type = "video/mp4",
6942 .extensions = "ismv,isma",
6943 .priv_data_size = sizeof(MOVMuxContext),
6944 .audio_codec = AV_CODEC_ID_AAC,
6945 .video_codec = AV_CODEC_ID_H264,
6947 .write_header = mov_write_header,
6948 .write_packet = mov_write_packet,
6949 .write_trailer = mov_write_trailer,
6951 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6952 .codec_tag = (const AVCodecTag* const []){
6953 codec_mp4_tags, codec_ism_tags, 0 },
6954 .check_bitstream = mov_check_bitstream,
6955 .priv_class = &ismv_muxer_class,
6958 #if CONFIG_F4V_MUXER
6960 AVOutputFormat ff_f4v_muxer = {
6962 .long_name = NULL_IF_CONFIG_SMALL("F4V Adobe Flash Video"),
6963 .mime_type = "application/f4v",
6964 .extensions = "f4v",
6965 .priv_data_size = sizeof(MOVMuxContext),
6966 .audio_codec = AV_CODEC_ID_AAC,
6967 .video_codec = AV_CODEC_ID_H264,
6969 .write_header = mov_write_header,
6970 .write_packet = mov_write_packet,
6971 .write_trailer = mov_write_trailer,
6973 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH,
6974 .codec_tag = (const AVCodecTag* const []){ codec_f4v_tags, 0 },
6975 .check_bitstream = mov_check_bitstream,
6976 .priv_class = &f4v_muxer_class,