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 + ((34 * (info->num_ind_sub + 1) + 7) >> 3);
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 unsigned int mov_get_codec_tag(AVFormatContext *s, MOVTrack *track)
1540 unsigned 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 unsigned int validate_codec_tag(const AVCodecTag *const *tags,
1593 unsigned int tag, int codec_id)
1598 * Check that tag + id is in the table
1600 for (i = 0; tags && tags[i]; i++) {
1601 const AVCodecTag *codec_tags = tags[i];
1602 while (codec_tags->id != AV_CODEC_ID_NONE) {
1603 if (avpriv_toupper4(codec_tags->tag) == avpriv_toupper4(tag) &&
1604 codec_tags->id == codec_id)
1605 return codec_tags->tag;
1612 static unsigned int mov_find_codec_tag(AVFormatContext *s, MOVTrack *track)
1614 if (is_cover_image(track->st))
1615 return ff_codec_get_tag(codec_cover_image_tags, track->par->codec_id);
1617 if (track->mode == MODE_IPOD)
1618 if (!av_match_ext(s->url, "m4a") &&
1619 !av_match_ext(s->url, "m4v") &&
1620 !av_match_ext(s->url, "m4b"))
1621 av_log(s, AV_LOG_WARNING, "Warning, extension is not .m4a nor .m4v "
1622 "Quicktime/Ipod might not play the file\n");
1624 if (track->mode == MODE_MOV) {
1625 return mov_get_codec_tag(s, track);
1627 return validate_codec_tag(s->oformat->codec_tag, track->par->codec_tag,
1628 track->par->codec_id);
1631 /** Write uuid atom.
1632 * Needed to make file play in iPods running newest firmware
1633 * goes after avcC atom in moov.trak.mdia.minf.stbl.stsd.avc1
1635 static int mov_write_uuid_tag_ipod(AVIOContext *pb)
1638 ffio_wfourcc(pb, "uuid");
1639 avio_wb32(pb, 0x6b6840f2);
1640 avio_wb32(pb, 0x5f244fc5);
1641 avio_wb32(pb, 0xba39a51b);
1642 avio_wb32(pb, 0xcf0323f3);
1647 static const uint16_t fiel_data[] = {
1648 0x0000, 0x0100, 0x0201, 0x0206, 0x0209, 0x020e
1651 static int mov_write_fiel_tag(AVIOContext *pb, MOVTrack *track, int field_order)
1653 unsigned mov_field_order = 0;
1654 if (field_order < FF_ARRAY_ELEMS(fiel_data))
1655 mov_field_order = fiel_data[field_order];
1659 ffio_wfourcc(pb, "fiel");
1660 avio_wb16(pb, mov_field_order);
1664 static int mov_write_subtitle_tag(AVIOContext *pb, MOVTrack *track)
1666 int64_t pos = avio_tell(pb);
1667 avio_wb32(pb, 0); /* size */
1668 avio_wl32(pb, track->tag); // store it byteswapped
1669 avio_wb32(pb, 0); /* Reserved */
1670 avio_wb16(pb, 0); /* Reserved */
1671 avio_wb16(pb, 1); /* Data-reference index */
1673 if (track->par->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
1674 mov_write_esds_tag(pb, track);
1675 else if (track->par->extradata_size)
1676 avio_write(pb, track->par->extradata, track->par->extradata_size);
1678 return update_size(pb, pos);
1681 static int mov_write_st3d_tag(AVIOContext *pb, AVStereo3D *stereo_3d)
1685 if (stereo_3d->flags != 0) {
1686 av_log(pb, AV_LOG_WARNING, "Unsupported stereo_3d flags %x. st3d not written.\n", stereo_3d->flags);
1690 switch (stereo_3d->type) {
1691 case AV_STEREO3D_2D:
1694 case AV_STEREO3D_TOPBOTTOM:
1697 case AV_STEREO3D_SIDEBYSIDE:
1701 av_log(pb, AV_LOG_WARNING, "Unsupported stereo_3d type %s. st3d not written.\n", av_stereo3d_type_name(stereo_3d->type));
1704 avio_wb32(pb, 13); /* size */
1705 ffio_wfourcc(pb, "st3d");
1706 avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1707 avio_w8(pb, stereo_mode);
1711 static int mov_write_sv3d_tag(AVFormatContext *s, AVIOContext *pb, AVSphericalMapping *spherical_mapping)
1713 int64_t sv3d_pos, svhd_pos, proj_pos;
1714 const char* metadata_source = s->flags & AVFMT_FLAG_BITEXACT ? "Lavf" : LIBAVFORMAT_IDENT;
1716 if (spherical_mapping->projection != AV_SPHERICAL_EQUIRECTANGULAR &&
1717 spherical_mapping->projection != AV_SPHERICAL_EQUIRECTANGULAR_TILE &&
1718 spherical_mapping->projection != AV_SPHERICAL_CUBEMAP) {
1719 av_log(pb, AV_LOG_WARNING, "Unsupported projection %d. sv3d not written.\n", spherical_mapping->projection);
1723 sv3d_pos = avio_tell(pb);
1724 avio_wb32(pb, 0); /* size */
1725 ffio_wfourcc(pb, "sv3d");
1727 svhd_pos = avio_tell(pb);
1728 avio_wb32(pb, 0); /* size */
1729 ffio_wfourcc(pb, "svhd");
1730 avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1731 avio_put_str(pb, metadata_source);
1732 update_size(pb, svhd_pos);
1734 proj_pos = avio_tell(pb);
1735 avio_wb32(pb, 0); /* size */
1736 ffio_wfourcc(pb, "proj");
1738 avio_wb32(pb, 24); /* size */
1739 ffio_wfourcc(pb, "prhd");
1740 avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1741 avio_wb32(pb, spherical_mapping->yaw);
1742 avio_wb32(pb, spherical_mapping->pitch);
1743 avio_wb32(pb, spherical_mapping->roll);
1745 switch (spherical_mapping->projection) {
1746 case AV_SPHERICAL_EQUIRECTANGULAR:
1747 case AV_SPHERICAL_EQUIRECTANGULAR_TILE:
1748 avio_wb32(pb, 28); /* size */
1749 ffio_wfourcc(pb, "equi");
1750 avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1751 avio_wb32(pb, spherical_mapping->bound_top);
1752 avio_wb32(pb, spherical_mapping->bound_bottom);
1753 avio_wb32(pb, spherical_mapping->bound_left);
1754 avio_wb32(pb, spherical_mapping->bound_right);
1756 case AV_SPHERICAL_CUBEMAP:
1757 avio_wb32(pb, 20); /* size */
1758 ffio_wfourcc(pb, "cbmp");
1759 avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1760 avio_wb32(pb, 0); /* layout */
1761 avio_wb32(pb, spherical_mapping->padding); /* padding */
1764 update_size(pb, proj_pos);
1766 return update_size(pb, sv3d_pos);
1769 static int mov_write_clap_tag(AVIOContext *pb, MOVTrack *track)
1772 ffio_wfourcc(pb, "clap");
1773 avio_wb32(pb, track->par->width); /* apertureWidth_N */
1774 avio_wb32(pb, 1); /* apertureWidth_D (= 1) */
1775 avio_wb32(pb, track->height); /* apertureHeight_N */
1776 avio_wb32(pb, 1); /* apertureHeight_D (= 1) */
1777 avio_wb32(pb, 0); /* horizOff_N (= 0) */
1778 avio_wb32(pb, 1); /* horizOff_D (= 1) */
1779 avio_wb32(pb, 0); /* vertOff_N (= 0) */
1780 avio_wb32(pb, 1); /* vertOff_D (= 1) */
1784 static int mov_write_pasp_tag(AVIOContext *pb, MOVTrack *track)
1787 av_reduce(&sar.num, &sar.den, track->par->sample_aspect_ratio.num,
1788 track->par->sample_aspect_ratio.den, INT_MAX);
1791 ffio_wfourcc(pb, "pasp");
1792 avio_wb32(pb, sar.num);
1793 avio_wb32(pb, sar.den);
1797 static int mov_write_gama_tag(AVIOContext *pb, MOVTrack *track, double gamma)
1802 gamma = avpriv_get_gamma_from_trc(track->par->color_trc);
1804 av_log(pb, AV_LOG_DEBUG, "gamma value %g\n", gamma);
1807 gama = (uint32_t)lrint((double)(1<<16) * gamma);
1808 av_log(pb, AV_LOG_DEBUG, "writing gama value %"PRId32"\n", gama);
1810 av_assert0(track->mode == MODE_MOV);
1812 ffio_wfourcc(pb, "gama");
1813 avio_wb32(pb, gama);
1817 av_log(pb, AV_LOG_WARNING, "gamma value unknown, unable to write gama atom\n");
1822 static int mov_write_colr_tag(AVIOContext *pb, MOVTrack *track)
1824 // Ref (MOV): https://developer.apple.com/library/mac/technotes/tn2162/_index.html#//apple_ref/doc/uid/DTS40013070-CH1-TNTAG9
1825 // Ref (MP4): ISO/IEC 14496-12:2012
1827 if (track->par->color_primaries == AVCOL_PRI_UNSPECIFIED &&
1828 track->par->color_trc == AVCOL_TRC_UNSPECIFIED &&
1829 track->par->color_space == AVCOL_SPC_UNSPECIFIED) {
1830 if ((track->par->width >= 1920 && track->par->height >= 1080)
1831 || (track->par->width == 1280 && track->par->height == 720)) {
1832 av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming bt709\n");
1833 track->par->color_primaries = AVCOL_PRI_BT709;
1834 } else if (track->par->width == 720 && track->height == 576) {
1835 av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming bt470bg\n");
1836 track->par->color_primaries = AVCOL_PRI_BT470BG;
1837 } else if (track->par->width == 720 &&
1838 (track->height == 486 || track->height == 480)) {
1839 av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming smpte170\n");
1840 track->par->color_primaries = AVCOL_PRI_SMPTE170M;
1842 av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, unable to assume anything\n");
1844 switch (track->par->color_primaries) {
1845 case AVCOL_PRI_BT709:
1846 track->par->color_trc = AVCOL_TRC_BT709;
1847 track->par->color_space = AVCOL_SPC_BT709;
1849 case AVCOL_PRI_SMPTE170M:
1850 case AVCOL_PRI_BT470BG:
1851 track->par->color_trc = AVCOL_TRC_BT709;
1852 track->par->color_space = AVCOL_SPC_SMPTE170M;
1857 /* We should only ever be called by MOV or MP4. */
1858 av_assert0(track->mode == MODE_MOV || track->mode == MODE_MP4);
1860 avio_wb32(pb, 18 + (track->mode == MODE_MP4));
1861 ffio_wfourcc(pb, "colr");
1862 if (track->mode == MODE_MP4)
1863 ffio_wfourcc(pb, "nclx");
1865 ffio_wfourcc(pb, "nclc");
1866 switch (track->par->color_primaries) {
1867 case AVCOL_PRI_BT709: avio_wb16(pb, 1); break;
1868 case AVCOL_PRI_BT470BG: avio_wb16(pb, 5); break;
1869 case AVCOL_PRI_SMPTE170M:
1870 case AVCOL_PRI_SMPTE240M: avio_wb16(pb, 6); break;
1871 case AVCOL_PRI_BT2020: avio_wb16(pb, 9); break;
1872 case AVCOL_PRI_SMPTE431: avio_wb16(pb, 11); break;
1873 case AVCOL_PRI_SMPTE432: avio_wb16(pb, 12); break;
1874 default: avio_wb16(pb, 2);
1876 switch (track->par->color_trc) {
1877 case AVCOL_TRC_BT709: avio_wb16(pb, 1); break;
1878 case AVCOL_TRC_SMPTE170M: avio_wb16(pb, 1); break; // remapped
1879 case AVCOL_TRC_SMPTE240M: avio_wb16(pb, 7); break;
1880 case AVCOL_TRC_SMPTEST2084: avio_wb16(pb, 16); break;
1881 case AVCOL_TRC_SMPTE428: avio_wb16(pb, 17); break;
1882 case AVCOL_TRC_ARIB_STD_B67: avio_wb16(pb, 18); break;
1883 default: avio_wb16(pb, 2);
1885 switch (track->par->color_space) {
1886 case AVCOL_SPC_BT709: avio_wb16(pb, 1); break;
1887 case AVCOL_SPC_BT470BG:
1888 case AVCOL_SPC_SMPTE170M: avio_wb16(pb, 6); break;
1889 case AVCOL_SPC_SMPTE240M: avio_wb16(pb, 7); break;
1890 case AVCOL_SPC_BT2020_NCL: avio_wb16(pb, 9); break;
1891 default: avio_wb16(pb, 2);
1894 if (track->mode == MODE_MP4) {
1895 int full_range = track->par->color_range == AVCOL_RANGE_JPEG;
1896 avio_w8(pb, full_range << 7);
1903 static void find_compressor(char * compressor_name, int len, MOVTrack *track)
1905 AVDictionaryEntry *encoder;
1906 int xdcam_res = (track->par->width == 1280 && track->par->height == 720)
1907 || (track->par->width == 1440 && track->par->height == 1080)
1908 || (track->par->width == 1920 && track->par->height == 1080);
1910 if (track->mode == MODE_MOV &&
1911 (encoder = av_dict_get(track->st->metadata, "encoder", NULL, 0))) {
1912 av_strlcpy(compressor_name, encoder->value, 32);
1913 } else if (track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO && xdcam_res) {
1914 int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE;
1915 AVStream *st = track->st;
1916 int rate = defined_frame_rate(NULL, st);
1917 av_strlcatf(compressor_name, len, "XDCAM");
1918 if (track->par->format == AV_PIX_FMT_YUV422P) {
1919 av_strlcatf(compressor_name, len, " HD422");
1920 } else if(track->par->width == 1440) {
1921 av_strlcatf(compressor_name, len, " HD");
1923 av_strlcatf(compressor_name, len, " EX");
1925 av_strlcatf(compressor_name, len, " %d%c", track->par->height, interlaced ? 'i' : 'p');
1927 av_strlcatf(compressor_name, len, "%d", rate * (interlaced + 1));
1931 static int mov_write_video_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
1933 int64_t pos = avio_tell(pb);
1934 char compressor_name[32] = { 0 };
1937 int uncompressed_ycbcr = ((track->par->codec_id == AV_CODEC_ID_RAWVIDEO && track->par->format == AV_PIX_FMT_UYVY422)
1938 || (track->par->codec_id == AV_CODEC_ID_RAWVIDEO && track->par->format == AV_PIX_FMT_YUYV422)
1939 || track->par->codec_id == AV_CODEC_ID_V308
1940 || track->par->codec_id == AV_CODEC_ID_V408
1941 || track->par->codec_id == AV_CODEC_ID_V410
1942 || track->par->codec_id == AV_CODEC_ID_V210);
1944 avio_wb32(pb, 0); /* size */
1945 if (mov->encryption_scheme != MOV_ENC_NONE) {
1946 ffio_wfourcc(pb, "encv");
1948 avio_wl32(pb, track->tag); // store it byteswapped
1950 avio_wb32(pb, 0); /* Reserved */
1951 avio_wb16(pb, 0); /* Reserved */
1952 avio_wb16(pb, 1); /* Data-reference index */
1954 if (uncompressed_ycbcr) {
1955 avio_wb16(pb, 2); /* Codec stream version */
1957 avio_wb16(pb, 0); /* Codec stream version */
1959 avio_wb16(pb, 0); /* Codec stream revision (=0) */
1960 if (track->mode == MODE_MOV) {
1961 ffio_wfourcc(pb, "FFMP"); /* Vendor */
1962 if (track->par->codec_id == AV_CODEC_ID_RAWVIDEO || uncompressed_ycbcr) {
1963 avio_wb32(pb, 0); /* Temporal Quality */
1964 avio_wb32(pb, 0x400); /* Spatial Quality = lossless*/
1966 avio_wb32(pb, 0x200); /* Temporal Quality = normal */
1967 avio_wb32(pb, 0x200); /* Spatial Quality = normal */
1970 avio_wb32(pb, 0); /* Reserved */
1971 avio_wb32(pb, 0); /* Reserved */
1972 avio_wb32(pb, 0); /* Reserved */
1974 avio_wb16(pb, track->par->width); /* Video width */
1975 avio_wb16(pb, track->height); /* Video height */
1976 avio_wb32(pb, 0x00480000); /* Horizontal resolution 72dpi */
1977 avio_wb32(pb, 0x00480000); /* Vertical resolution 72dpi */
1978 avio_wb32(pb, 0); /* Data size (= 0) */
1979 avio_wb16(pb, 1); /* Frame count (= 1) */
1981 /* FIXME not sure, ISO 14496-1 draft where it shall be set to 0 */
1982 find_compressor(compressor_name, 32, track);
1983 avio_w8(pb, strlen(compressor_name));
1984 avio_write(pb, compressor_name, 31);
1986 if (track->mode == MODE_MOV &&
1987 (track->par->codec_id == AV_CODEC_ID_V410 || track->par->codec_id == AV_CODEC_ID_V210))
1988 avio_wb16(pb, 0x18);
1989 else if (track->mode == MODE_MOV && track->par->bits_per_coded_sample)
1990 avio_wb16(pb, track->par->bits_per_coded_sample |
1991 (track->par->format == AV_PIX_FMT_GRAY8 ? 0x20 : 0));
1993 avio_wb16(pb, 0x18); /* Reserved */
1995 if (track->mode == MODE_MOV && track->par->format == AV_PIX_FMT_PAL8) {
1996 int pal_size = 1 << track->par->bits_per_coded_sample;
1998 avio_wb16(pb, 0); /* Color table ID */
1999 avio_wb32(pb, 0); /* Color table seed */
2000 avio_wb16(pb, 0x8000); /* Color table flags */
2001 avio_wb16(pb, pal_size - 1); /* Color table size (zero-relative) */
2002 for (i = 0; i < pal_size; i++) {
2003 uint32_t rgb = track->palette[i];
2004 uint16_t r = (rgb >> 16) & 0xff;
2005 uint16_t g = (rgb >> 8) & 0xff;
2006 uint16_t b = rgb & 0xff;
2008 avio_wb16(pb, (r << 8) | r);
2009 avio_wb16(pb, (g << 8) | g);
2010 avio_wb16(pb, (b << 8) | b);
2013 avio_wb16(pb, 0xffff); /* Reserved */
2015 if (track->tag == MKTAG('m','p','4','v'))
2016 mov_write_esds_tag(pb, track);
2017 else if (track->par->codec_id == AV_CODEC_ID_H263)
2018 mov_write_d263_tag(pb);
2019 else if (track->par->codec_id == AV_CODEC_ID_AVUI ||
2020 track->par->codec_id == AV_CODEC_ID_SVQ3) {
2021 mov_write_extradata_tag(pb, track);
2023 } else if (track->par->codec_id == AV_CODEC_ID_DNXHD) {
2024 mov_write_avid_tag(pb, track);
2026 } else if (track->par->codec_id == AV_CODEC_ID_HEVC)
2027 mov_write_hvcc_tag(pb, track);
2028 else if (track->par->codec_id == AV_CODEC_ID_H264 && !TAG_IS_AVCI(track->tag)) {
2029 mov_write_avcc_tag(pb, track);
2030 if (track->mode == MODE_IPOD)
2031 mov_write_uuid_tag_ipod(pb);
2032 } else if (track->par->codec_id == AV_CODEC_ID_VP9) {
2033 mov_write_vpcc_tag(mov->fc, pb, track);
2034 } else if (track->par->codec_id == AV_CODEC_ID_AV1) {
2035 mov_write_av1c_tag(pb, track);
2036 } else if (track->par->codec_id == AV_CODEC_ID_VC1 && track->vos_len > 0)
2037 mov_write_dvc1_tag(pb, track);
2038 else if (track->par->codec_id == AV_CODEC_ID_VP6F ||
2039 track->par->codec_id == AV_CODEC_ID_VP6A) {
2040 /* Don't write any potential extradata here - the cropping
2041 * is signalled via the normal width/height fields. */
2042 } else if (track->par->codec_id == AV_CODEC_ID_R10K) {
2043 if (track->par->codec_tag == MKTAG('R','1','0','k'))
2044 mov_write_dpxe_tag(pb, track);
2045 } else if (track->vos_len > 0)
2046 mov_write_glbl_tag(pb, track);
2048 if (track->par->codec_id != AV_CODEC_ID_H264 &&
2049 track->par->codec_id != AV_CODEC_ID_MPEG4 &&
2050 track->par->codec_id != AV_CODEC_ID_DNXHD) {
2051 int field_order = track->par->field_order;
2053 #if FF_API_LAVF_AVCTX
2054 FF_DISABLE_DEPRECATION_WARNINGS
2055 if (field_order != track->st->codec->field_order && track->st->codec->field_order != AV_FIELD_UNKNOWN)
2056 field_order = track->st->codec->field_order;
2057 FF_ENABLE_DEPRECATION_WARNINGS
2060 if (field_order != AV_FIELD_UNKNOWN)
2061 mov_write_fiel_tag(pb, track, field_order);
2064 if (mov->flags & FF_MOV_FLAG_WRITE_GAMA) {
2065 if (track->mode == MODE_MOV)
2066 mov_write_gama_tag(pb, track, mov->gamma);
2068 av_log(mov->fc, AV_LOG_WARNING, "Not writing 'gama' atom. Format is not MOV.\n");
2070 if (mov->flags & FF_MOV_FLAG_WRITE_COLR) {
2071 if (track->mode == MODE_MOV || track->mode == MODE_MP4)
2072 mov_write_colr_tag(pb, track);
2074 av_log(mov->fc, AV_LOG_WARNING, "Not writing 'colr' atom. Format is not MOV or MP4.\n");
2077 if (track->mode == MODE_MP4 && mov->fc->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL) {
2078 AVStereo3D* stereo_3d = (AVStereo3D*) av_stream_get_side_data(track->st, AV_PKT_DATA_STEREO3D, NULL);
2079 AVSphericalMapping* spherical_mapping = (AVSphericalMapping*)av_stream_get_side_data(track->st, AV_PKT_DATA_SPHERICAL, NULL);
2082 mov_write_st3d_tag(pb, stereo_3d);
2083 if (spherical_mapping)
2084 mov_write_sv3d_tag(mov->fc, pb, spherical_mapping);
2087 if (track->par->sample_aspect_ratio.den && track->par->sample_aspect_ratio.num) {
2088 mov_write_pasp_tag(pb, track);
2091 if (uncompressed_ycbcr){
2092 mov_write_clap_tag(pb, track);
2095 if (mov->encryption_scheme != MOV_ENC_NONE) {
2096 ff_mov_cenc_write_sinf_tag(track, pb, mov->encryption_kid);
2099 /* extra padding for avid stsd */
2100 /* https://developer.apple.com/library/mac/documentation/QuickTime/QTFF/QTFFChap2/qtff2.html#//apple_ref/doc/uid/TP40000939-CH204-61112 */
2104 return update_size(pb, pos);
2107 static int mov_write_rtp_tag(AVIOContext *pb, MOVTrack *track)
2109 int64_t pos = avio_tell(pb);
2110 avio_wb32(pb, 0); /* size */
2111 ffio_wfourcc(pb, "rtp ");
2112 avio_wb32(pb, 0); /* Reserved */
2113 avio_wb16(pb, 0); /* Reserved */
2114 avio_wb16(pb, 1); /* Data-reference index */
2116 avio_wb16(pb, 1); /* Hint track version */
2117 avio_wb16(pb, 1); /* Highest compatible version */
2118 avio_wb32(pb, track->max_packet_size); /* Max packet size */
2120 avio_wb32(pb, 12); /* size */
2121 ffio_wfourcc(pb, "tims");
2122 avio_wb32(pb, track->timescale);
2124 return update_size(pb, pos);
2127 static int mov_write_source_reference_tag(AVIOContext *pb, MOVTrack *track, const char *reel_name)
2129 uint64_t str_size =strlen(reel_name);
2130 int64_t pos = avio_tell(pb);
2132 if (str_size >= UINT16_MAX){
2133 av_log(NULL, AV_LOG_ERROR, "reel_name length %"PRIu64" is too large\n", str_size);
2135 return AVERROR(EINVAL);
2138 avio_wb32(pb, 0); /* size */
2139 ffio_wfourcc(pb, "name"); /* Data format */
2140 avio_wb16(pb, str_size); /* string size */
2141 avio_wb16(pb, track->language); /* langcode */
2142 avio_write(pb, reel_name, str_size); /* reel name */
2143 return update_size(pb,pos);
2146 static int mov_write_tmcd_tag(AVIOContext *pb, MOVTrack *track)
2148 int64_t pos = avio_tell(pb);
2152 AVDictionaryEntry *t = NULL;
2154 if (!track->st->avg_frame_rate.num || !track->st->avg_frame_rate.den) {
2155 #if FF_API_LAVF_AVCTX
2156 FF_DISABLE_DEPRECATION_WARNINGS
2157 frame_duration = av_rescale(track->timescale, track->st->codec->time_base.num, track->st->codec->time_base.den);
2158 nb_frames = ROUNDED_DIV(track->st->codec->time_base.den, track->st->codec->time_base.num);
2159 FF_ENABLE_DEPRECATION_WARNINGS
2161 av_log(NULL, AV_LOG_ERROR, "avg_frame_rate not set for tmcd track.\n");
2162 return AVERROR(EINVAL);
2165 frame_duration = av_rescale(track->timescale, track->st->avg_frame_rate.num, track->st->avg_frame_rate.den);
2166 nb_frames = ROUNDED_DIV(track->st->avg_frame_rate.den, track->st->avg_frame_rate.num);
2169 if (nb_frames > 255) {
2170 av_log(NULL, AV_LOG_ERROR, "fps %d is too large\n", nb_frames);
2171 return AVERROR(EINVAL);
2174 avio_wb32(pb, 0); /* size */
2175 ffio_wfourcc(pb, "tmcd"); /* Data format */
2176 avio_wb32(pb, 0); /* Reserved */
2177 avio_wb32(pb, 1); /* Data reference index */
2178 avio_wb32(pb, 0); /* Flags */
2179 avio_wb32(pb, track->timecode_flags); /* Flags (timecode) */
2180 avio_wb32(pb, track->timescale); /* Timescale */
2181 avio_wb32(pb, frame_duration); /* Frame duration */
2182 avio_w8(pb, nb_frames); /* Number of frames */
2183 avio_w8(pb, 0); /* Reserved */
2185 t = av_dict_get(track->st->metadata, "reel_name", NULL, 0);
2186 if (t && utf8len(t->value) && track->mode != MODE_MP4)
2187 mov_write_source_reference_tag(pb, track, t->value);
2189 avio_wb16(pb, 0); /* zero size */
2192 avio_wb32(pb, 0); /* size */
2193 ffio_wfourcc(pb, "tmcd"); /* Data format */
2194 avio_wb32(pb, 0); /* Reserved */
2195 avio_wb32(pb, 1); /* Data reference index */
2196 if (track->par->extradata_size)
2197 avio_write(pb, track->par->extradata, track->par->extradata_size);
2199 return update_size(pb, pos);
2202 static int mov_write_gpmd_tag(AVIOContext *pb, const MOVTrack *track)
2204 int64_t pos = avio_tell(pb);
2205 avio_wb32(pb, 0); /* size */
2206 ffio_wfourcc(pb, "gpmd");
2207 avio_wb32(pb, 0); /* Reserved */
2208 avio_wb16(pb, 0); /* Reserved */
2209 avio_wb16(pb, 1); /* Data-reference index */
2210 avio_wb32(pb, 0); /* Reserved */
2211 return update_size(pb, pos);
2214 static int mov_write_stsd_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
2216 int64_t pos = avio_tell(pb);
2217 avio_wb32(pb, 0); /* size */
2218 ffio_wfourcc(pb, "stsd");
2219 avio_wb32(pb, 0); /* version & flags */
2220 avio_wb32(pb, 1); /* entry count */
2221 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO)
2222 mov_write_video_tag(pb, mov, track);
2223 else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
2224 mov_write_audio_tag(s, pb, mov, track);
2225 else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)
2226 mov_write_subtitle_tag(pb, track);
2227 else if (track->par->codec_tag == MKTAG('r','t','p',' '))
2228 mov_write_rtp_tag(pb, track);
2229 else if (track->par->codec_tag == MKTAG('t','m','c','d'))
2230 mov_write_tmcd_tag(pb, track);
2231 else if (track->par->codec_tag == MKTAG('g','p','m','d'))
2232 mov_write_gpmd_tag(pb, track);
2233 return update_size(pb, pos);
2236 static int mov_write_ctts_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
2238 MOVMuxContext *mov = s->priv_data;
2239 MOVStts *ctts_entries;
2240 uint32_t entries = 0;
2244 ctts_entries = av_malloc_array((track->entry + 1), sizeof(*ctts_entries)); /* worst case */
2246 return AVERROR(ENOMEM);
2247 ctts_entries[0].count = 1;
2248 ctts_entries[0].duration = track->cluster[0].cts;
2249 for (i = 1; i < track->entry; i++) {
2250 if (track->cluster[i].cts == ctts_entries[entries].duration) {
2251 ctts_entries[entries].count++; /* compress */
2254 ctts_entries[entries].duration = track->cluster[i].cts;
2255 ctts_entries[entries].count = 1;
2258 entries++; /* last one */
2259 atom_size = 16 + (entries * 8);
2260 avio_wb32(pb, atom_size); /* size */
2261 ffio_wfourcc(pb, "ctts");
2262 if (mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS)
2263 avio_w8(pb, 1); /* version */
2265 avio_w8(pb, 0); /* version */
2266 avio_wb24(pb, 0); /* flags */
2267 avio_wb32(pb, entries); /* entry count */
2268 for (i = 0; i < entries; i++) {
2269 avio_wb32(pb, ctts_entries[i].count);
2270 avio_wb32(pb, ctts_entries[i].duration);
2272 av_free(ctts_entries);
2276 /* Time to sample atom */
2277 static int mov_write_stts_tag(AVIOContext *pb, MOVTrack *track)
2279 MOVStts *stts_entries = NULL;
2280 uint32_t entries = -1;
2284 if (track->par->codec_type == AVMEDIA_TYPE_AUDIO && !track->audio_vbr) {
2285 stts_entries = av_malloc(sizeof(*stts_entries)); /* one entry */
2287 return AVERROR(ENOMEM);
2288 stts_entries[0].count = track->sample_count;
2289 stts_entries[0].duration = 1;
2293 stts_entries = av_malloc_array(track->entry, sizeof(*stts_entries)); /* worst case */
2295 return AVERROR(ENOMEM);
2297 for (i = 0; i < track->entry; i++) {
2298 int duration = get_cluster_duration(track, i);
2299 if (i && duration == stts_entries[entries].duration) {
2300 stts_entries[entries].count++; /* compress */
2303 stts_entries[entries].duration = duration;
2304 stts_entries[entries].count = 1;
2307 entries++; /* last one */
2309 atom_size = 16 + (entries * 8);
2310 avio_wb32(pb, atom_size); /* size */
2311 ffio_wfourcc(pb, "stts");
2312 avio_wb32(pb, 0); /* version & flags */
2313 avio_wb32(pb, entries); /* entry count */
2314 for (i = 0; i < entries; i++) {
2315 avio_wb32(pb, stts_entries[i].count);
2316 avio_wb32(pb, stts_entries[i].duration);
2318 av_free(stts_entries);
2322 static int mov_write_dref_tag(AVIOContext *pb)
2324 avio_wb32(pb, 28); /* size */
2325 ffio_wfourcc(pb, "dref");
2326 avio_wb32(pb, 0); /* version & flags */
2327 avio_wb32(pb, 1); /* entry count */
2329 avio_wb32(pb, 0xc); /* size */
2330 //FIXME add the alis and rsrc atom
2331 ffio_wfourcc(pb, "url ");
2332 avio_wb32(pb, 1); /* version & flags */
2337 static int mov_preroll_write_stbl_atoms(AVIOContext *pb, MOVTrack *track)
2341 int16_t roll_distance;
2342 int group_description_index;
2345 struct sgpd_entry *sgpd_entries = NULL;
2350 const int OPUS_SEEK_PREROLL_MS = 80;
2351 int roll_samples = av_rescale_q(OPUS_SEEK_PREROLL_MS,
2352 (AVRational){1, 1000},
2353 (AVRational){1, 48000});
2358 sgpd_entries = av_malloc_array(track->entry, sizeof(*sgpd_entries));
2360 return AVERROR(ENOMEM);
2362 av_assert0(track->par->codec_id == AV_CODEC_ID_OPUS || track->par->codec_id == AV_CODEC_ID_AAC);
2364 if (track->par->codec_id == AV_CODEC_ID_OPUS) {
2365 for (i = 0; i < track->entry; i++) {
2366 int roll_samples_remaining = roll_samples;
2368 for (j = i - 1; j >= 0; j--) {
2369 roll_samples_remaining -= get_cluster_duration(track, j);
2371 if (roll_samples_remaining <= 0)
2374 /* We don't have enough preceeding samples to compute a valid
2375 roll_distance here, so this sample can't be independently
2377 if (roll_samples_remaining > 0)
2379 /* Verify distance is a maximum of 32 (2.5ms) packets. */
2381 return AVERROR_INVALIDDATA;
2382 if (i && distance == sgpd_entries[entries].roll_distance) {
2383 sgpd_entries[entries].count++;
2386 sgpd_entries[entries].count = 1;
2387 sgpd_entries[entries].roll_distance = distance;
2388 sgpd_entries[entries].group_description_index = distance ? ++group : 0;
2393 sgpd_entries[entries].count = track->sample_count;
2394 sgpd_entries[entries].roll_distance = 1;
2395 sgpd_entries[entries].group_description_index = ++group;
2400 av_free(sgpd_entries);
2404 /* Write sgpd tag */
2405 avio_wb32(pb, 24 + (group * 2)); /* size */
2406 ffio_wfourcc(pb, "sgpd");
2407 avio_wb32(pb, 1 << 24); /* fullbox */
2408 ffio_wfourcc(pb, "roll");
2409 avio_wb32(pb, 2); /* default_length */
2410 avio_wb32(pb, group); /* entry_count */
2411 for (i = 0; i < entries; i++) {
2412 if (sgpd_entries[i].group_description_index) {
2413 avio_wb16(pb, -sgpd_entries[i].roll_distance); /* roll_distance */
2417 /* Write sbgp tag */
2418 avio_wb32(pb, 20 + (entries * 8)); /* size */
2419 ffio_wfourcc(pb, "sbgp");
2420 avio_wb32(pb, 0); /* fullbox */
2421 ffio_wfourcc(pb, "roll");
2422 avio_wb32(pb, entries); /* entry_count */
2423 for (i = 0; i < entries; i++) {
2424 avio_wb32(pb, sgpd_entries[i].count); /* sample_count */
2425 avio_wb32(pb, sgpd_entries[i].group_description_index); /* group_description_index */
2428 av_free(sgpd_entries);
2432 static int mov_write_stbl_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
2434 int64_t pos = avio_tell(pb);
2437 avio_wb32(pb, 0); /* size */
2438 ffio_wfourcc(pb, "stbl");
2439 mov_write_stsd_tag(s, pb, mov, track);
2440 mov_write_stts_tag(pb, track);
2441 if ((track->par->codec_type == AVMEDIA_TYPE_VIDEO ||
2442 track->par->codec_tag == MKTAG('r','t','p',' ')) &&
2443 track->has_keyframes && track->has_keyframes < track->entry)
2444 mov_write_stss_tag(pb, track, MOV_SYNC_SAMPLE);
2445 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO && track->has_disposable)
2446 mov_write_sdtp_tag(pb, track);
2447 if (track->mode == MODE_MOV && track->flags & MOV_TRACK_STPS)
2448 mov_write_stss_tag(pb, track, MOV_PARTIAL_SYNC_SAMPLE);
2449 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO &&
2450 track->flags & MOV_TRACK_CTTS && track->entry) {
2452 if ((ret = mov_write_ctts_tag(s, pb, track)) < 0)
2455 mov_write_stsc_tag(pb, track);
2456 mov_write_stsz_tag(pb, track);
2457 mov_write_stco_tag(pb, track);
2458 if (track->cenc.aes_ctr) {
2459 ff_mov_cenc_write_stbl_atoms(&track->cenc, pb);
2461 if (track->par->codec_id == AV_CODEC_ID_OPUS || track->par->codec_id == AV_CODEC_ID_AAC) {
2462 mov_preroll_write_stbl_atoms(pb, track);
2464 return update_size(pb, pos);
2467 static int mov_write_dinf_tag(AVIOContext *pb)
2469 int64_t pos = avio_tell(pb);
2470 avio_wb32(pb, 0); /* size */
2471 ffio_wfourcc(pb, "dinf");
2472 mov_write_dref_tag(pb);
2473 return update_size(pb, pos);
2476 static int mov_write_nmhd_tag(AVIOContext *pb)
2479 ffio_wfourcc(pb, "nmhd");
2484 static int mov_write_tcmi_tag(AVIOContext *pb, MOVTrack *track)
2486 int64_t pos = avio_tell(pb);
2487 const char *font = "Lucida Grande";
2488 avio_wb32(pb, 0); /* size */
2489 ffio_wfourcc(pb, "tcmi"); /* timecode media information atom */
2490 avio_wb32(pb, 0); /* version & flags */
2491 avio_wb16(pb, 0); /* text font */
2492 avio_wb16(pb, 0); /* text face */
2493 avio_wb16(pb, 12); /* text size */
2494 avio_wb16(pb, 0); /* (unknown, not in the QT specs...) */
2495 avio_wb16(pb, 0x0000); /* text color (red) */
2496 avio_wb16(pb, 0x0000); /* text color (green) */
2497 avio_wb16(pb, 0x0000); /* text color (blue) */
2498 avio_wb16(pb, 0xffff); /* background color (red) */
2499 avio_wb16(pb, 0xffff); /* background color (green) */
2500 avio_wb16(pb, 0xffff); /* background color (blue) */
2501 avio_w8(pb, strlen(font)); /* font len (part of the pascal string) */
2502 avio_write(pb, font, strlen(font)); /* font name */
2503 return update_size(pb, pos);
2506 static int mov_write_gmhd_tag(AVIOContext *pb, MOVTrack *track)
2508 int64_t pos = avio_tell(pb);
2509 avio_wb32(pb, 0); /* size */
2510 ffio_wfourcc(pb, "gmhd");
2511 avio_wb32(pb, 0x18); /* gmin size */
2512 ffio_wfourcc(pb, "gmin");/* generic media info */
2513 avio_wb32(pb, 0); /* version & flags */
2514 avio_wb16(pb, 0x40); /* graphics mode = */
2515 avio_wb16(pb, 0x8000); /* opColor (r?) */
2516 avio_wb16(pb, 0x8000); /* opColor (g?) */
2517 avio_wb16(pb, 0x8000); /* opColor (b?) */
2518 avio_wb16(pb, 0); /* balance */
2519 avio_wb16(pb, 0); /* reserved */
2522 * This special text atom is required for
2523 * Apple Quicktime chapters. The contents
2524 * don't appear to be documented, so the
2525 * bytes are copied verbatim.
2527 if (track->tag != MKTAG('c','6','0','8')) {
2528 avio_wb32(pb, 0x2C); /* size */
2529 ffio_wfourcc(pb, "text");
2530 avio_wb16(pb, 0x01);
2531 avio_wb32(pb, 0x00);
2532 avio_wb32(pb, 0x00);
2533 avio_wb32(pb, 0x00);
2534 avio_wb32(pb, 0x01);
2535 avio_wb32(pb, 0x00);
2536 avio_wb32(pb, 0x00);
2537 avio_wb32(pb, 0x00);
2538 avio_wb32(pb, 0x00004000);
2539 avio_wb16(pb, 0x0000);
2542 if (track->par->codec_tag == MKTAG('t','m','c','d')) {
2543 int64_t tmcd_pos = avio_tell(pb);
2544 avio_wb32(pb, 0); /* size */
2545 ffio_wfourcc(pb, "tmcd");
2546 mov_write_tcmi_tag(pb, track);
2547 update_size(pb, tmcd_pos);
2548 } else if (track->par->codec_tag == MKTAG('g','p','m','d')) {
2549 int64_t gpmd_pos = avio_tell(pb);
2550 avio_wb32(pb, 0); /* size */
2551 ffio_wfourcc(pb, "gpmd");
2552 avio_wb32(pb, 0); /* version */
2553 update_size(pb, gpmd_pos);
2555 return update_size(pb, pos);
2558 static int mov_write_smhd_tag(AVIOContext *pb)
2560 avio_wb32(pb, 16); /* size */
2561 ffio_wfourcc(pb, "smhd");
2562 avio_wb32(pb, 0); /* version & flags */
2563 avio_wb16(pb, 0); /* reserved (balance, normally = 0) */
2564 avio_wb16(pb, 0); /* reserved */
2568 static int mov_write_vmhd_tag(AVIOContext *pb)
2570 avio_wb32(pb, 0x14); /* size (always 0x14) */
2571 ffio_wfourcc(pb, "vmhd");
2572 avio_wb32(pb, 0x01); /* version & flags */
2573 avio_wb64(pb, 0); /* reserved (graphics mode = copy) */
2577 static int is_clcp_track(MOVTrack *track)
2579 return track->tag == MKTAG('c','7','0','8') ||
2580 track->tag == MKTAG('c','6','0','8');
2583 static int mov_write_hdlr_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
2585 MOVMuxContext *mov = s->priv_data;
2586 const char *hdlr, *descr = NULL, *hdlr_type = NULL;
2587 int64_t pos = avio_tell(pb);
2591 descr = "DataHandler";
2594 hdlr = (track->mode == MODE_MOV) ? "mhlr" : "\0\0\0\0";
2595 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
2597 descr = "VideoHandler";
2598 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
2600 descr = "SoundHandler";
2601 } else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE) {
2602 if (is_clcp_track(track)) {
2604 descr = "ClosedCaptionHandler";
2606 if (track->tag == MKTAG('t','x','3','g')) {
2608 } else if (track->tag == MKTAG('m','p','4','s')) {
2613 descr = "SubtitleHandler";
2615 } else if (track->par->codec_tag == MKTAG('r','t','p',' ')) {
2617 descr = "HintHandler";
2618 } else if (track->par->codec_tag == MKTAG('t','m','c','d')) {
2620 descr = "TimeCodeHandler";
2621 } else if (track->par->codec_tag == MKTAG('g','p','m','d')) {
2623 descr = "GoPro MET"; // GoPro Metadata
2625 av_log(s, AV_LOG_WARNING,
2626 "Unknown hldr_type for %s, writing dummy values\n",
2627 av_fourcc2str(track->par->codec_tag));
2630 // hdlr.name is used by some players to identify the content title
2631 // of the track. So if an alternate handler description is
2632 // specified, use it.
2633 AVDictionaryEntry *t;
2634 t = av_dict_get(track->st->metadata, "handler_name", NULL, 0);
2635 if (t && utf8len(t->value))
2640 if (mov->empty_hdlr_name) /* expressly allowed by QTFF and not prohibited in ISO 14496-12 8.4.3.3 */
2643 avio_wb32(pb, 0); /* size */
2644 ffio_wfourcc(pb, "hdlr");
2645 avio_wb32(pb, 0); /* Version & flags */
2646 avio_write(pb, hdlr, 4); /* handler */
2647 ffio_wfourcc(pb, hdlr_type); /* handler type */
2648 avio_wb32(pb, 0); /* reserved */
2649 avio_wb32(pb, 0); /* reserved */
2650 avio_wb32(pb, 0); /* reserved */
2651 if (!track || track->mode == MODE_MOV)
2652 avio_w8(pb, strlen(descr)); /* pascal string */
2653 avio_write(pb, descr, strlen(descr)); /* handler description */
2654 if (track && track->mode != MODE_MOV)
2655 avio_w8(pb, 0); /* c string */
2656 return update_size(pb, pos);
2659 static int mov_write_hmhd_tag(AVIOContext *pb)
2661 /* This atom must be present, but leaving the values at zero
2662 * seems harmless. */
2663 avio_wb32(pb, 28); /* size */
2664 ffio_wfourcc(pb, "hmhd");
2665 avio_wb32(pb, 0); /* version, flags */
2666 avio_wb16(pb, 0); /* maxPDUsize */
2667 avio_wb16(pb, 0); /* avgPDUsize */
2668 avio_wb32(pb, 0); /* maxbitrate */
2669 avio_wb32(pb, 0); /* avgbitrate */
2670 avio_wb32(pb, 0); /* reserved */
2674 static int mov_write_minf_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
2676 int64_t pos = avio_tell(pb);
2679 avio_wb32(pb, 0); /* size */
2680 ffio_wfourcc(pb, "minf");
2681 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO)
2682 mov_write_vmhd_tag(pb);
2683 else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
2684 mov_write_smhd_tag(pb);
2685 else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE) {
2686 if (track->tag == MKTAG('t','e','x','t') || is_clcp_track(track)) {
2687 mov_write_gmhd_tag(pb, track);
2689 mov_write_nmhd_tag(pb);
2691 } else if (track->tag == MKTAG('r','t','p',' ')) {
2692 mov_write_hmhd_tag(pb);
2693 } else if (track->tag == MKTAG('t','m','c','d')) {
2694 if (track->mode != MODE_MOV)
2695 mov_write_nmhd_tag(pb);
2697 mov_write_gmhd_tag(pb, track);
2698 } else if (track->tag == MKTAG('g','p','m','d')) {
2699 mov_write_gmhd_tag(pb, track);
2701 if (track->mode == MODE_MOV) /* ISO 14496-12 8.4.3.1 specifies hdlr only within mdia or meta boxes */
2702 mov_write_hdlr_tag(s, pb, NULL);
2703 mov_write_dinf_tag(pb);
2704 if ((ret = mov_write_stbl_tag(s, pb, mov, track)) < 0)
2706 return update_size(pb, pos);
2709 static int mov_write_mdhd_tag(AVIOContext *pb, MOVMuxContext *mov,
2712 int version = track->track_duration < INT32_MAX ? 0 : 1;
2714 if (track->mode == MODE_ISM)
2717 (version == 1) ? avio_wb32(pb, 44) : avio_wb32(pb, 32); /* size */
2718 ffio_wfourcc(pb, "mdhd");
2719 avio_w8(pb, version);
2720 avio_wb24(pb, 0); /* flags */
2722 avio_wb64(pb, track->time);
2723 avio_wb64(pb, track->time);
2725 avio_wb32(pb, track->time); /* creation time */
2726 avio_wb32(pb, track->time); /* modification time */
2728 avio_wb32(pb, track->timescale); /* time scale (sample rate for audio) */
2729 if (!track->entry && mov->mode == MODE_ISM)
2730 (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
2731 else if (!track->entry)
2732 (version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0);
2734 (version == 1) ? avio_wb64(pb, track->track_duration) : avio_wb32(pb, track->track_duration); /* duration */
2735 avio_wb16(pb, track->language); /* language */
2736 avio_wb16(pb, 0); /* reserved (quality) */
2738 if (version != 0 && track->mode == MODE_MOV) {
2739 av_log(NULL, AV_LOG_ERROR,
2740 "FATAL error, file duration too long for timebase, this file will not be\n"
2741 "playable with quicktime. Choose a different timebase or a different\n"
2742 "container format\n");
2748 static int mov_write_mdia_tag(AVFormatContext *s, AVIOContext *pb,
2749 MOVMuxContext *mov, MOVTrack *track)
2751 int64_t pos = avio_tell(pb);
2754 avio_wb32(pb, 0); /* size */
2755 ffio_wfourcc(pb, "mdia");
2756 mov_write_mdhd_tag(pb, mov, track);
2757 mov_write_hdlr_tag(s, pb, track);
2758 if ((ret = mov_write_minf_tag(s, pb, mov, track)) < 0)
2760 return update_size(pb, pos);
2763 /* transformation matrix
2767 static void write_matrix(AVIOContext *pb, int16_t a, int16_t b, int16_t c,
2768 int16_t d, int16_t tx, int16_t ty)
2770 avio_wb32(pb, a << 16); /* 16.16 format */
2771 avio_wb32(pb, b << 16); /* 16.16 format */
2772 avio_wb32(pb, 0); /* u in 2.30 format */
2773 avio_wb32(pb, c << 16); /* 16.16 format */
2774 avio_wb32(pb, d << 16); /* 16.16 format */
2775 avio_wb32(pb, 0); /* v in 2.30 format */
2776 avio_wb32(pb, tx << 16); /* 16.16 format */
2777 avio_wb32(pb, ty << 16); /* 16.16 format */
2778 avio_wb32(pb, 1 << 30); /* w in 2.30 format */
2781 static int mov_write_tkhd_tag(AVIOContext *pb, MOVMuxContext *mov,
2782 MOVTrack *track, AVStream *st)
2784 int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE,
2785 track->timescale, AV_ROUND_UP);
2786 int version = duration < INT32_MAX ? 0 : 1;
2787 int flags = MOV_TKHD_FLAG_IN_MOVIE;
2791 uint32_t *display_matrix = NULL;
2792 int display_matrix_size, i;
2795 if (mov->per_stream_grouping)
2798 group = st->codecpar->codec_type;
2800 display_matrix = (uint32_t*)av_stream_get_side_data(st, AV_PKT_DATA_DISPLAYMATRIX,
2801 &display_matrix_size);
2802 if (display_matrix && display_matrix_size < 9 * sizeof(*display_matrix))
2803 display_matrix = NULL;
2806 if (track->flags & MOV_TRACK_ENABLED)
2807 flags |= MOV_TKHD_FLAG_ENABLED;
2809 if (track->mode == MODE_ISM)
2812 (version == 1) ? avio_wb32(pb, 104) : avio_wb32(pb, 92); /* size */
2813 ffio_wfourcc(pb, "tkhd");
2814 avio_w8(pb, version);
2815 avio_wb24(pb, flags);
2817 avio_wb64(pb, track->time);
2818 avio_wb64(pb, track->time);
2820 avio_wb32(pb, track->time); /* creation time */
2821 avio_wb32(pb, track->time); /* modification time */
2823 avio_wb32(pb, track->track_id); /* track-id */
2824 avio_wb32(pb, 0); /* reserved */
2825 if (!track->entry && mov->mode == MODE_ISM)
2826 (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
2827 else if (!track->entry)
2828 (version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0);
2830 (version == 1) ? avio_wb64(pb, duration) : avio_wb32(pb, duration);
2832 avio_wb32(pb, 0); /* reserved */
2833 avio_wb32(pb, 0); /* reserved */
2834 avio_wb16(pb, 0); /* layer */
2835 avio_wb16(pb, group); /* alternate group) */
2836 /* Volume, only for audio */
2837 if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
2838 avio_wb16(pb, 0x0100);
2841 avio_wb16(pb, 0); /* reserved */
2843 /* Matrix structure */
2844 #if FF_API_OLD_ROTATE_API
2845 if (st && st->metadata) {
2846 AVDictionaryEntry *rot = av_dict_get(st->metadata, "rotate", NULL, 0);
2847 rotation = (rot && rot->value) ? atoi(rot->value) : 0;
2850 if (display_matrix) {
2851 for (i = 0; i < 9; i++)
2852 avio_wb32(pb, display_matrix[i]);
2853 #if FF_API_OLD_ROTATE_API
2854 } else if (rotation == 90) {
2855 write_matrix(pb, 0, 1, -1, 0, track->par->height, 0);
2856 } else if (rotation == 180) {
2857 write_matrix(pb, -1, 0, 0, -1, track->par->width, track->par->height);
2858 } else if (rotation == 270) {
2859 write_matrix(pb, 0, -1, 1, 0, 0, track->par->width);
2862 write_matrix(pb, 1, 0, 0, 1, 0, 0);
2864 /* Track width and height, for visual only */
2865 if (st && (track->par->codec_type == AVMEDIA_TYPE_VIDEO ||
2866 track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)) {
2867 int64_t track_width_1616;
2868 if (track->mode == MODE_MOV) {
2869 track_width_1616 = track->par->width * 0x10000ULL;
2871 track_width_1616 = av_rescale(st->sample_aspect_ratio.num,
2872 track->par->width * 0x10000LL,
2873 st->sample_aspect_ratio.den);
2874 if (!track_width_1616 ||
2875 track->height != track->par->height ||
2876 track_width_1616 > UINT32_MAX)
2877 track_width_1616 = track->par->width * 0x10000ULL;
2879 if (track_width_1616 > UINT32_MAX) {
2880 av_log(mov->fc, AV_LOG_WARNING, "track width is too large\n");
2881 track_width_1616 = 0;
2883 avio_wb32(pb, track_width_1616);
2884 if (track->height > 0xFFFF) {
2885 av_log(mov->fc, AV_LOG_WARNING, "track height is too large\n");
2888 avio_wb32(pb, track->height * 0x10000U);
2896 static int mov_write_tapt_tag(AVIOContext *pb, MOVTrack *track)
2898 int32_t width = av_rescale(track->par->sample_aspect_ratio.num, track->par->width,
2899 track->par->sample_aspect_ratio.den);
2901 int64_t pos = avio_tell(pb);
2903 avio_wb32(pb, 0); /* size */
2904 ffio_wfourcc(pb, "tapt");
2907 ffio_wfourcc(pb, "clef");
2909 avio_wb32(pb, width << 16);
2910 avio_wb32(pb, track->par->height << 16);
2913 ffio_wfourcc(pb, "prof");
2915 avio_wb32(pb, width << 16);
2916 avio_wb32(pb, track->par->height << 16);
2919 ffio_wfourcc(pb, "enof");
2921 avio_wb32(pb, track->par->width << 16);
2922 avio_wb32(pb, track->par->height << 16);
2924 return update_size(pb, pos);
2927 // This box seems important for the psp playback ... without it the movie seems to hang
2928 static int mov_write_edts_tag(AVIOContext *pb, MOVMuxContext *mov,
2931 int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE,
2932 track->timescale, AV_ROUND_UP);
2933 int version = duration < INT32_MAX ? 0 : 1;
2934 int entry_size, entry_count, size;
2935 int64_t delay, start_ct = track->start_cts;
2936 int64_t start_dts = track->start_dts;
2939 if (start_dts != track->cluster[0].dts || start_ct != track->cluster[0].cts) {
2941 av_log(mov->fc, AV_LOG_DEBUG,
2942 "EDTS using dts:%"PRId64" cts:%d instead of dts:%"PRId64" cts:%"PRId64" tid:%d\n",
2943 track->cluster[0].dts, track->cluster[0].cts,
2944 start_dts, start_ct, track->track_id);
2945 start_dts = track->cluster[0].dts;
2946 start_ct = track->cluster[0].cts;
2950 delay = av_rescale_rnd(start_dts + start_ct, MOV_TIMESCALE,
2951 track->timescale, AV_ROUND_DOWN);
2952 version |= delay < INT32_MAX ? 0 : 1;
2954 entry_size = (version == 1) ? 20 : 12;
2955 entry_count = 1 + (delay > 0);
2956 size = 24 + entry_count * entry_size;
2958 /* write the atom data */
2959 avio_wb32(pb, size);
2960 ffio_wfourcc(pb, "edts");
2961 avio_wb32(pb, size - 8);
2962 ffio_wfourcc(pb, "elst");
2963 avio_w8(pb, version);
2964 avio_wb24(pb, 0); /* flags */
2966 avio_wb32(pb, entry_count);
2967 if (delay > 0) { /* add an empty edit to delay presentation */
2968 /* In the positive delay case, the delay includes the cts
2969 * offset, and the second edit list entry below trims out
2970 * the same amount from the actual content. This makes sure
2971 * that the offset last sample is included in the edit
2972 * list duration as well. */
2974 avio_wb64(pb, delay);
2977 avio_wb32(pb, delay);
2980 avio_wb32(pb, 0x00010000);
2982 /* Avoid accidentally ending up with start_ct = -1 which has got a
2983 * special meaning. Normally start_ct should end up positive or zero
2984 * here, but use FFMIN in case dts is a small positive integer
2985 * rounded to 0 when represented in MOV_TIMESCALE units. */
2986 av_assert0(av_rescale_rnd(start_dts, MOV_TIMESCALE, track->timescale, AV_ROUND_DOWN) <= 0);
2987 start_ct = -FFMIN(start_dts, 0);
2988 /* Note, this delay is calculated from the pts of the first sample,
2989 * ensuring that we don't reduce the duration for cases with
2994 /* For fragmented files, we don't know the full length yet. Setting
2995 * duration to 0 allows us to only specify the offset, including
2996 * the rest of the content (from all future fragments) without specifying
2997 * an explicit duration. */
2998 if (mov->flags & FF_MOV_FLAG_FRAGMENT)
3003 avio_wb64(pb, duration);
3004 avio_wb64(pb, start_ct);
3006 avio_wb32(pb, duration);
3007 avio_wb32(pb, start_ct);
3009 avio_wb32(pb, 0x00010000);
3013 static int mov_write_tref_tag(AVIOContext *pb, MOVTrack *track)
3015 avio_wb32(pb, 20); // size
3016 ffio_wfourcc(pb, "tref");
3017 avio_wb32(pb, 12); // size (subatom)
3018 avio_wl32(pb, track->tref_tag);
3019 avio_wb32(pb, track->tref_id);
3023 // goes at the end of each track! ... Critical for PSP playback ("Incompatible data" without it)
3024 static int mov_write_uuid_tag_psp(AVIOContext *pb, MOVTrack *mov)
3026 avio_wb32(pb, 0x34); /* size ... reports as 28 in mp4box! */
3027 ffio_wfourcc(pb, "uuid");
3028 ffio_wfourcc(pb, "USMT");
3029 avio_wb32(pb, 0x21d24fce);
3030 avio_wb32(pb, 0xbb88695c);
3031 avio_wb32(pb, 0xfac9c740);
3032 avio_wb32(pb, 0x1c); // another size here!
3033 ffio_wfourcc(pb, "MTDT");
3034 avio_wb32(pb, 0x00010012);
3035 avio_wb32(pb, 0x0a);
3036 avio_wb32(pb, 0x55c40000);
3042 static int mov_write_udta_sdp(AVIOContext *pb, MOVTrack *track)
3044 AVFormatContext *ctx = track->rtp_ctx;
3045 char buf[1000] = "";
3048 ff_sdp_write_media(buf, sizeof(buf), ctx->streams[0], track->src_track,
3049 NULL, NULL, 0, 0, ctx);
3050 av_strlcatf(buf, sizeof(buf), "a=control:streamid=%d\r\n", track->track_id);
3053 avio_wb32(pb, len + 24);
3054 ffio_wfourcc(pb, "udta");
3055 avio_wb32(pb, len + 16);
3056 ffio_wfourcc(pb, "hnti");
3057 avio_wb32(pb, len + 8);
3058 ffio_wfourcc(pb, "sdp ");
3059 avio_write(pb, buf, len);
3063 static int mov_write_track_metadata(AVIOContext *pb, AVStream *st,
3064 const char *tag, const char *str)
3066 int64_t pos = avio_tell(pb);
3067 AVDictionaryEntry *t = av_dict_get(st->metadata, str, NULL, 0);
3068 if (!t || !utf8len(t->value))
3071 avio_wb32(pb, 0); /* size */
3072 ffio_wfourcc(pb, tag); /* type */
3073 avio_write(pb, t->value, strlen(t->value)); /* UTF8 string value */
3074 return update_size(pb, pos);
3077 static int mov_write_track_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
3080 AVIOContext *pb_buf;
3087 ret = avio_open_dyn_buf(&pb_buf);
3091 if (mov->mode & (MODE_MP4|MODE_MOV))
3092 mov_write_track_metadata(pb_buf, st, "name", "title");
3094 if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) {
3095 avio_wb32(pb, size + 8);
3096 ffio_wfourcc(pb, "udta");
3097 avio_write(pb, buf, size);
3104 static int mov_write_trak_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov,
3105 MOVTrack *track, AVStream *st)
3107 int64_t pos = avio_tell(pb);
3108 int entry_backup = track->entry;
3109 int chunk_backup = track->chunkCount;
3112 /* If we want to have an empty moov, but some samples already have been
3113 * buffered (delay_moov), pretend that no samples have been written yet. */
3114 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV)
3115 track->chunkCount = track->entry = 0;
3117 avio_wb32(pb, 0); /* size */
3118 ffio_wfourcc(pb, "trak");
3119 mov_write_tkhd_tag(pb, mov, track, st);
3121 av_assert2(mov->use_editlist >= 0);
3123 if (track->start_dts != AV_NOPTS_VALUE) {
3124 if (mov->use_editlist)
3125 mov_write_edts_tag(pb, mov, track); // PSP Movies and several other cases require edts box
3126 else if ((track->entry && track->cluster[0].dts) || track->mode == MODE_PSP || is_clcp_track(track))
3127 av_log(mov->fc, AV_LOG_WARNING,
3128 "Not writing any edit list even though one would have been required\n");
3131 if (track->tref_tag)
3132 mov_write_tref_tag(pb, track);
3134 if ((ret = mov_write_mdia_tag(s, pb, mov, track)) < 0)
3136 if (track->mode == MODE_PSP)
3137 mov_write_uuid_tag_psp(pb, track); // PSP Movies require this uuid box
3138 if (track->tag == MKTAG('r','t','p',' '))
3139 mov_write_udta_sdp(pb, track);
3140 if (track->mode == MODE_MOV) {
3141 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
3142 double sample_aspect_ratio = av_q2d(st->sample_aspect_ratio);
3143 if (st->sample_aspect_ratio.num && 1.0 != sample_aspect_ratio) {
3144 mov_write_tapt_tag(pb, track);
3147 if (is_clcp_track(track) && st->sample_aspect_ratio.num) {
3148 mov_write_tapt_tag(pb, track);
3151 mov_write_track_udta_tag(pb, mov, st);
3152 track->entry = entry_backup;
3153 track->chunkCount = chunk_backup;
3154 return update_size(pb, pos);
3157 static int mov_write_iods_tag(AVIOContext *pb, MOVMuxContext *mov)
3159 int i, has_audio = 0, has_video = 0;
3160 int64_t pos = avio_tell(pb);
3161 int audio_profile = mov->iods_audio_profile;
3162 int video_profile = mov->iods_video_profile;
3163 for (i = 0; i < mov->nb_streams; i++) {
3164 if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
3165 has_audio |= mov->tracks[i].par->codec_type == AVMEDIA_TYPE_AUDIO;
3166 has_video |= mov->tracks[i].par->codec_type == AVMEDIA_TYPE_VIDEO;
3169 if (audio_profile < 0)
3170 audio_profile = 0xFF - has_audio;
3171 if (video_profile < 0)
3172 video_profile = 0xFF - has_video;
3173 avio_wb32(pb, 0x0); /* size */
3174 ffio_wfourcc(pb, "iods");
3175 avio_wb32(pb, 0); /* version & flags */
3176 put_descr(pb, 0x10, 7);
3177 avio_wb16(pb, 0x004f);
3180 avio_w8(pb, audio_profile);
3181 avio_w8(pb, video_profile);
3183 return update_size(pb, pos);
3186 static int mov_write_trex_tag(AVIOContext *pb, MOVTrack *track)
3188 avio_wb32(pb, 0x20); /* size */
3189 ffio_wfourcc(pb, "trex");
3190 avio_wb32(pb, 0); /* version & flags */
3191 avio_wb32(pb, track->track_id); /* track ID */
3192 avio_wb32(pb, 1); /* default sample description index */
3193 avio_wb32(pb, 0); /* default sample duration */
3194 avio_wb32(pb, 0); /* default sample size */
3195 avio_wb32(pb, 0); /* default sample flags */
3199 static int mov_write_mvex_tag(AVIOContext *pb, MOVMuxContext *mov)
3201 int64_t pos = avio_tell(pb);
3203 avio_wb32(pb, 0x0); /* size */
3204 ffio_wfourcc(pb, "mvex");
3205 for (i = 0; i < mov->nb_streams; i++)
3206 mov_write_trex_tag(pb, &mov->tracks[i]);
3207 return update_size(pb, pos);
3210 static int mov_write_mvhd_tag(AVIOContext *pb, MOVMuxContext *mov)
3212 int max_track_id = 1, i;
3213 int64_t max_track_len = 0;
3216 for (i = 0; i < mov->nb_streams; i++) {
3217 if (mov->tracks[i].entry > 0 && mov->tracks[i].timescale) {
3218 int64_t max_track_len_temp = av_rescale_rnd(mov->tracks[i].track_duration,
3220 mov->tracks[i].timescale,
3222 if (max_track_len < max_track_len_temp)
3223 max_track_len = max_track_len_temp;
3224 if (max_track_id < mov->tracks[i].track_id)
3225 max_track_id = mov->tracks[i].track_id;
3228 /* If using delay_moov, make sure the output is the same as if no
3229 * samples had been written yet. */
3230 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
3235 version = max_track_len < UINT32_MAX ? 0 : 1;
3236 avio_wb32(pb, version == 1 ? 120 : 108); /* size */
3238 ffio_wfourcc(pb, "mvhd");
3239 avio_w8(pb, version);
3240 avio_wb24(pb, 0); /* flags */
3242 avio_wb64(pb, mov->time);
3243 avio_wb64(pb, mov->time);
3245 avio_wb32(pb, mov->time); /* creation time */
3246 avio_wb32(pb, mov->time); /* modification time */
3248 avio_wb32(pb, MOV_TIMESCALE);
3249 (version == 1) ? avio_wb64(pb, max_track_len) : avio_wb32(pb, max_track_len); /* duration of longest track */
3251 avio_wb32(pb, 0x00010000); /* reserved (preferred rate) 1.0 = normal */
3252 avio_wb16(pb, 0x0100); /* reserved (preferred volume) 1.0 = normal */
3253 avio_wb16(pb, 0); /* reserved */
3254 avio_wb32(pb, 0); /* reserved */
3255 avio_wb32(pb, 0); /* reserved */
3257 /* Matrix structure */
3258 write_matrix(pb, 1, 0, 0, 1, 0, 0);
3260 avio_wb32(pb, 0); /* reserved (preview time) */
3261 avio_wb32(pb, 0); /* reserved (preview duration) */
3262 avio_wb32(pb, 0); /* reserved (poster time) */
3263 avio_wb32(pb, 0); /* reserved (selection time) */
3264 avio_wb32(pb, 0); /* reserved (selection duration) */
3265 avio_wb32(pb, 0); /* reserved (current time) */
3266 avio_wb32(pb, max_track_id + 1); /* Next track id */
3270 static int mov_write_itunes_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov,
3273 avio_wb32(pb, 33); /* size */
3274 ffio_wfourcc(pb, "hdlr");
3277 ffio_wfourcc(pb, "mdir");
3278 ffio_wfourcc(pb, "appl");
3285 /* helper function to write a data tag with the specified string as data */
3286 static int mov_write_string_data_tag(AVIOContext *pb, const char *data, int lang, int long_style)
3289 int size = 16 + strlen(data);
3290 avio_wb32(pb, size); /* size */
3291 ffio_wfourcc(pb, "data");
3294 avio_write(pb, data, strlen(data));
3298 lang = ff_mov_iso639_to_lang("und", 1);
3299 avio_wb16(pb, strlen(data)); /* string length */
3300 avio_wb16(pb, lang);
3301 avio_write(pb, data, strlen(data));
3302 return strlen(data) + 4;
3306 static int mov_write_string_tag(AVIOContext *pb, const char *name,
3307 const char *value, int lang, int long_style)
3310 if (value && value[0]) {
3311 int64_t pos = avio_tell(pb);
3312 avio_wb32(pb, 0); /* size */
3313 ffio_wfourcc(pb, name);
3314 mov_write_string_data_tag(pb, value, lang, long_style);
3315 size = update_size(pb, pos);
3320 static AVDictionaryEntry *get_metadata_lang(AVFormatContext *s,
3321 const char *tag, int *lang)
3324 AVDictionaryEntry *t, *t2 = NULL;
3329 if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
3332 len = strlen(t->key);
3333 snprintf(tag2, sizeof(tag2), "%s-", tag);
3334 while ((t2 = av_dict_get(s->metadata, tag2, t2, AV_DICT_IGNORE_SUFFIX))) {
3335 len2 = strlen(t2->key);
3336 if (len2 == len + 4 && !strcmp(t->value, t2->value)
3337 && (l = ff_mov_iso639_to_lang(&t2->key[len2 - 3], 1)) >= 0) {
3345 static int mov_write_string_metadata(AVFormatContext *s, AVIOContext *pb,
3346 const char *name, const char *tag,
3350 AVDictionaryEntry *t = get_metadata_lang(s, tag, &lang);
3353 return mov_write_string_tag(pb, name, t->value, lang, long_style);
3356 /* iTunes bpm number */
3357 static int mov_write_tmpo_tag(AVIOContext *pb, AVFormatContext *s)
3359 AVDictionaryEntry *t = av_dict_get(s->metadata, "tmpo", NULL, 0);
3360 int size = 0, tmpo = t ? atoi(t->value) : 0;
3363 avio_wb32(pb, size);
3364 ffio_wfourcc(pb, "tmpo");
3365 avio_wb32(pb, size-8); /* size */
3366 ffio_wfourcc(pb, "data");
3367 avio_wb32(pb, 0x15); //type specifier
3369 avio_wb16(pb, tmpo); // data
3374 /* 3GPP TS 26.244 */
3375 static int mov_write_loci_tag(AVFormatContext *s, AVIOContext *pb)
3378 int64_t pos = avio_tell(pb);
3379 double latitude, longitude, altitude;
3380 int32_t latitude_fix, longitude_fix, altitude_fix;
3381 AVDictionaryEntry *t = get_metadata_lang(s, "location", &lang);
3382 const char *ptr, *place = "";
3384 static const char *astronomical_body = "earth";
3389 longitude = strtod(ptr, &end);
3391 av_log(s, AV_LOG_WARNING, "malformed location metadata\n");
3395 latitude = strtod(ptr, &end);
3397 av_log(s, AV_LOG_WARNING, "malformed location metadata\n");
3401 altitude = strtod(ptr, &end);
3402 /* If no altitude was present, the default 0 should be fine */
3406 latitude_fix = (int32_t) ((1 << 16) * latitude);
3407 longitude_fix = (int32_t) ((1 << 16) * longitude);
3408 altitude_fix = (int32_t) ((1 << 16) * altitude);
3410 avio_wb32(pb, 0); /* size */
3411 ffio_wfourcc(pb, "loci"); /* type */
3412 avio_wb32(pb, 0); /* version + flags */
3413 avio_wb16(pb, lang);
3414 avio_write(pb, place, strlen(place) + 1);
3415 avio_w8(pb, 0); /* role of place (0 == shooting location, 1 == real location, 2 == fictional location) */
3416 avio_wb32(pb, latitude_fix);
3417 avio_wb32(pb, longitude_fix);
3418 avio_wb32(pb, altitude_fix);
3419 avio_write(pb, astronomical_body, strlen(astronomical_body) + 1);
3420 avio_w8(pb, 0); /* additional notes, null terminated string */
3422 return update_size(pb, pos);
3425 /* iTunes track or disc number */
3426 static int mov_write_trkn_tag(AVIOContext *pb, MOVMuxContext *mov,
3427 AVFormatContext *s, int disc)
3429 AVDictionaryEntry *t = av_dict_get(s->metadata,
3430 disc ? "disc" : "track",
3432 int size = 0, track = t ? atoi(t->value) : 0;
3435 char *slash = strchr(t->value, '/');
3437 tracks = atoi(slash + 1);
3438 avio_wb32(pb, 32); /* size */
3439 ffio_wfourcc(pb, disc ? "disk" : "trkn");
3440 avio_wb32(pb, 24); /* size */
3441 ffio_wfourcc(pb, "data");
3442 avio_wb32(pb, 0); // 8 bytes empty
3444 avio_wb16(pb, 0); // empty
3445 avio_wb16(pb, track); // track / disc number
3446 avio_wb16(pb, tracks); // total track / disc number
3447 avio_wb16(pb, 0); // empty
3453 static int mov_write_int8_metadata(AVFormatContext *s, AVIOContext *pb,
3454 const char *name, const char *tag,
3457 AVDictionaryEntry *t = NULL;
3459 int size = 24 + len;
3461 if (len != 1 && len != 4)
3464 if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
3466 num = atoi(t->value);
3468 avio_wb32(pb, size);
3469 ffio_wfourcc(pb, name);
3470 avio_wb32(pb, size - 8);
3471 ffio_wfourcc(pb, "data");
3472 avio_wb32(pb, 0x15);
3474 if (len==4) avio_wb32(pb, num);
3475 else avio_w8 (pb, num);
3480 static int mov_write_covr(AVIOContext *pb, AVFormatContext *s)
3482 MOVMuxContext *mov = s->priv_data;
3486 for (i = 0; i < s->nb_streams; i++) {
3487 MOVTrack *trk = &mov->tracks[i];
3489 if (!is_cover_image(trk->st) || trk->cover_image.size <= 0)
3493 pos = avio_tell(pb);
3495 ffio_wfourcc(pb, "covr");
3497 avio_wb32(pb, 16 + trk->cover_image.size);
3498 ffio_wfourcc(pb, "data");
3499 avio_wb32(pb, trk->tag);
3501 avio_write(pb, trk->cover_image.data, trk->cover_image.size);
3504 return pos ? update_size(pb, pos) : 0;
3507 /* iTunes meta data list */
3508 static int mov_write_ilst_tag(AVIOContext *pb, MOVMuxContext *mov,
3511 int64_t pos = avio_tell(pb);
3512 avio_wb32(pb, 0); /* size */
3513 ffio_wfourcc(pb, "ilst");
3514 mov_write_string_metadata(s, pb, "\251nam", "title" , 1);
3515 mov_write_string_metadata(s, pb, "\251ART", "artist" , 1);
3516 mov_write_string_metadata(s, pb, "aART", "album_artist", 1);
3517 mov_write_string_metadata(s, pb, "\251wrt", "composer" , 1);
3518 mov_write_string_metadata(s, pb, "\251alb", "album" , 1);
3519 mov_write_string_metadata(s, pb, "\251day", "date" , 1);
3520 if (!mov_write_string_metadata(s, pb, "\251too", "encoding_tool", 1)) {
3521 if (!(s->flags & AVFMT_FLAG_BITEXACT))
3522 mov_write_string_tag(pb, "\251too", LIBAVFORMAT_IDENT, 0, 1);
3524 mov_write_string_metadata(s, pb, "\251cmt", "comment" , 1);
3525 mov_write_string_metadata(s, pb, "\251gen", "genre" , 1);
3526 mov_write_string_metadata(s, pb, "cprt", "copyright", 1);
3527 mov_write_string_metadata(s, pb, "\251grp", "grouping" , 1);
3528 mov_write_string_metadata(s, pb, "\251lyr", "lyrics" , 1);
3529 mov_write_string_metadata(s, pb, "desc", "description",1);
3530 mov_write_string_metadata(s, pb, "ldes", "synopsis" , 1);
3531 mov_write_string_metadata(s, pb, "tvsh", "show" , 1);
3532 mov_write_string_metadata(s, pb, "tven", "episode_id",1);
3533 mov_write_string_metadata(s, pb, "tvnn", "network" , 1);
3534 mov_write_string_metadata(s, pb, "keyw", "keywords" , 1);
3535 mov_write_int8_metadata (s, pb, "tves", "episode_sort",4);
3536 mov_write_int8_metadata (s, pb, "tvsn", "season_number",4);
3537 mov_write_int8_metadata (s, pb, "stik", "media_type",1);
3538 mov_write_int8_metadata (s, pb, "hdvd", "hd_video", 1);
3539 mov_write_int8_metadata (s, pb, "pgap", "gapless_playback",1);
3540 mov_write_int8_metadata (s, pb, "cpil", "compilation", 1);
3541 mov_write_covr(pb, s);
3542 mov_write_trkn_tag(pb, mov, s, 0); // track number
3543 mov_write_trkn_tag(pb, mov, s, 1); // disc number
3544 mov_write_tmpo_tag(pb, s);
3545 return update_size(pb, pos);
3548 static int mov_write_mdta_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov,
3551 avio_wb32(pb, 33); /* size */
3552 ffio_wfourcc(pb, "hdlr");
3555 ffio_wfourcc(pb, "mdta");
3563 static int mov_write_mdta_keys_tag(AVIOContext *pb, MOVMuxContext *mov,
3566 AVDictionaryEntry *t = NULL;
3567 int64_t pos = avio_tell(pb);
3568 int64_t curpos, entry_pos;
3571 avio_wb32(pb, 0); /* size */
3572 ffio_wfourcc(pb, "keys");
3574 entry_pos = avio_tell(pb);
3575 avio_wb32(pb, 0); /* entry count */
3577 while (t = av_dict_get(s->metadata, "", t, AV_DICT_IGNORE_SUFFIX)) {
3578 avio_wb32(pb, strlen(t->key) + 8);
3579 ffio_wfourcc(pb, "mdta");
3580 avio_write(pb, t->key, strlen(t->key));
3583 curpos = avio_tell(pb);
3584 avio_seek(pb, entry_pos, SEEK_SET);
3585 avio_wb32(pb, count); // rewrite entry count
3586 avio_seek(pb, curpos, SEEK_SET);
3588 return update_size(pb, pos);
3591 static int mov_write_mdta_ilst_tag(AVIOContext *pb, MOVMuxContext *mov,
3594 AVDictionaryEntry *t = NULL;
3595 int64_t pos = avio_tell(pb);
3596 int count = 1; /* keys are 1-index based */
3598 avio_wb32(pb, 0); /* size */
3599 ffio_wfourcc(pb, "ilst");
3601 while (t = av_dict_get(s->metadata, "", t, AV_DICT_IGNORE_SUFFIX)) {
3602 int64_t entry_pos = avio_tell(pb);
3603 avio_wb32(pb, 0); /* size */
3604 avio_wb32(pb, count); /* key */
3605 mov_write_string_data_tag(pb, t->value, 0, 1);
3606 update_size(pb, entry_pos);
3609 return update_size(pb, pos);
3612 /* meta data tags */
3613 static int mov_write_meta_tag(AVIOContext *pb, MOVMuxContext *mov,
3617 int64_t pos = avio_tell(pb);
3618 avio_wb32(pb, 0); /* size */
3619 ffio_wfourcc(pb, "meta");
3621 if (mov->flags & FF_MOV_FLAG_USE_MDTA) {
3622 mov_write_mdta_hdlr_tag(pb, mov, s);
3623 mov_write_mdta_keys_tag(pb, mov, s);
3624 mov_write_mdta_ilst_tag(pb, mov, s);
3627 /* iTunes metadata tag */
3628 mov_write_itunes_hdlr_tag(pb, mov, s);
3629 mov_write_ilst_tag(pb, mov, s);
3631 size = update_size(pb, pos);
3635 static int mov_write_raw_metadata_tag(AVFormatContext *s, AVIOContext *pb,
3636 const char *name, const char *key)
3639 AVDictionaryEntry *t;
3641 if (!(t = av_dict_get(s->metadata, key, NULL, 0)))
3644 len = strlen(t->value);
3647 avio_wb32(pb, size);
3648 ffio_wfourcc(pb, name);
3649 avio_write(pb, t->value, len);
3655 static int ascii_to_wc(AVIOContext *pb, const uint8_t *b)
3659 GET_UTF8(val, *b++, return -1;)
3662 avio_wb16(pb, 0x00);
3666 static uint16_t language_code(const char *str)
3668 return (((str[0] - 0x60) & 0x1F) << 10) +
3669 (((str[1] - 0x60) & 0x1F) << 5) +
3670 (( str[2] - 0x60) & 0x1F);
3673 static int mov_write_3gp_udta_tag(AVIOContext *pb, AVFormatContext *s,
3674 const char *tag, const char *str)
3676 int64_t pos = avio_tell(pb);
3677 AVDictionaryEntry *t = av_dict_get(s->metadata, str, NULL, 0);
3678 if (!t || !utf8len(t->value))
3680 avio_wb32(pb, 0); /* size */
3681 ffio_wfourcc(pb, tag); /* type */
3682 avio_wb32(pb, 0); /* version + flags */
3683 if (!strcmp(tag, "yrrc"))
3684 avio_wb16(pb, atoi(t->value));
3686 avio_wb16(pb, language_code("eng")); /* language */
3687 avio_write(pb, t->value, strlen(t->value) + 1); /* UTF8 string value */
3688 if (!strcmp(tag, "albm") &&
3689 (t = av_dict_get(s->metadata, "track", NULL, 0)))
3690 avio_w8(pb, atoi(t->value));
3692 return update_size(pb, pos);
3695 static int mov_write_chpl_tag(AVIOContext *pb, AVFormatContext *s)
3697 int64_t pos = avio_tell(pb);
3698 int i, nb_chapters = FFMIN(s->nb_chapters, 255);
3700 avio_wb32(pb, 0); // size
3701 ffio_wfourcc(pb, "chpl");
3702 avio_wb32(pb, 0x01000000); // version + flags
3703 avio_wb32(pb, 0); // unknown
3704 avio_w8(pb, nb_chapters);
3706 for (i = 0; i < nb_chapters; i++) {
3707 AVChapter *c = s->chapters[i];
3708 AVDictionaryEntry *t;
3709 avio_wb64(pb, av_rescale_q(c->start, c->time_base, (AVRational){1,10000000}));
3711 if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
3712 int len = FFMIN(strlen(t->value), 255);
3714 avio_write(pb, t->value, len);
3718 return update_size(pb, pos);
3721 static int mov_write_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
3724 AVIOContext *pb_buf;
3728 ret = avio_open_dyn_buf(&pb_buf);
3732 if (mov->mode & MODE_3GP) {
3733 mov_write_3gp_udta_tag(pb_buf, s, "perf", "artist");
3734 mov_write_3gp_udta_tag(pb_buf, s, "titl", "title");
3735 mov_write_3gp_udta_tag(pb_buf, s, "auth", "author");
3736 mov_write_3gp_udta_tag(pb_buf, s, "gnre", "genre");
3737 mov_write_3gp_udta_tag(pb_buf, s, "dscp", "comment");
3738 mov_write_3gp_udta_tag(pb_buf, s, "albm", "album");
3739 mov_write_3gp_udta_tag(pb_buf, s, "cprt", "copyright");
3740 mov_write_3gp_udta_tag(pb_buf, s, "yrrc", "date");
3741 mov_write_loci_tag(s, pb_buf);
3742 } 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
3743 mov_write_string_metadata(s, pb_buf, "\251ART", "artist", 0);
3744 mov_write_string_metadata(s, pb_buf, "\251nam", "title", 0);
3745 mov_write_string_metadata(s, pb_buf, "\251aut", "author", 0);
3746 mov_write_string_metadata(s, pb_buf, "\251alb", "album", 0);
3747 mov_write_string_metadata(s, pb_buf, "\251day", "date", 0);
3748 mov_write_string_metadata(s, pb_buf, "\251swr", "encoder", 0);
3749 // currently ignored by mov.c
3750 mov_write_string_metadata(s, pb_buf, "\251des", "comment", 0);
3751 // add support for libquicktime, this atom is also actually read by mov.c
3752 mov_write_string_metadata(s, pb_buf, "\251cmt", "comment", 0);
3753 mov_write_string_metadata(s, pb_buf, "\251gen", "genre", 0);
3754 mov_write_string_metadata(s, pb_buf, "\251cpy", "copyright", 0);
3755 mov_write_string_metadata(s, pb_buf, "\251mak", "make", 0);
3756 mov_write_string_metadata(s, pb_buf, "\251mod", "model", 0);
3757 mov_write_string_metadata(s, pb_buf, "\251xyz", "location", 0);
3758 mov_write_string_metadata(s, pb_buf, "\251key", "keywords", 0);
3759 mov_write_raw_metadata_tag(s, pb_buf, "XMP_", "xmp");
3761 /* iTunes meta data */
3762 mov_write_meta_tag(pb_buf, mov, s);
3763 mov_write_loci_tag(s, pb_buf);
3766 if (s->nb_chapters && !(mov->flags & FF_MOV_FLAG_DISABLE_CHPL))
3767 mov_write_chpl_tag(pb_buf, s);
3769 if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) {
3770 avio_wb32(pb, size + 8);
3771 ffio_wfourcc(pb, "udta");
3772 avio_write(pb, buf, size);
3779 static void mov_write_psp_udta_tag(AVIOContext *pb,
3780 const char *str, const char *lang, int type)
3782 int len = utf8len(str) + 1;
3785 avio_wb16(pb, len * 2 + 10); /* size */
3786 avio_wb32(pb, type); /* type */
3787 avio_wb16(pb, language_code(lang)); /* language */
3788 avio_wb16(pb, 0x01); /* ? */
3789 ascii_to_wc(pb, str);
3792 static int mov_write_uuidusmt_tag(AVIOContext *pb, AVFormatContext *s)
3794 AVDictionaryEntry *title = av_dict_get(s->metadata, "title", NULL, 0);
3798 pos = avio_tell(pb);
3799 avio_wb32(pb, 0); /* size placeholder*/
3800 ffio_wfourcc(pb, "uuid");
3801 ffio_wfourcc(pb, "USMT");
3802 avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
3803 avio_wb32(pb, 0xbb88695c);
3804 avio_wb32(pb, 0xfac9c740);
3806 pos2 = avio_tell(pb);
3807 avio_wb32(pb, 0); /* size placeholder*/
3808 ffio_wfourcc(pb, "MTDT");
3812 avio_wb16(pb, 0x0C); /* size */
3813 avio_wb32(pb, 0x0B); /* type */
3814 avio_wb16(pb, language_code("und")); /* language */
3815 avio_wb16(pb, 0x0); /* ? */
3816 avio_wb16(pb, 0x021C); /* data */
3818 if (!(s->flags & AVFMT_FLAG_BITEXACT))
3819 mov_write_psp_udta_tag(pb, LIBAVCODEC_IDENT, "eng", 0x04);
3820 mov_write_psp_udta_tag(pb, title->value, "eng", 0x01);
3821 mov_write_psp_udta_tag(pb, "2006/04/01 11:11:11", "und", 0x03);
3823 update_size(pb, pos2);
3824 return update_size(pb, pos);
3830 static void build_chunks(MOVTrack *trk)
3833 MOVIentry *chunk = &trk->cluster[0];
3834 uint64_t chunkSize = chunk->size;
3835 chunk->chunkNum = 1;
3836 if (trk->chunkCount)
3838 trk->chunkCount = 1;
3839 for (i = 1; i<trk->entry; i++){
3840 if (chunk->pos + chunkSize == trk->cluster[i].pos &&
3841 chunkSize + trk->cluster[i].size < (1<<20)){
3842 chunkSize += trk->cluster[i].size;
3843 chunk->samples_in_chunk += trk->cluster[i].entries;
3845 trk->cluster[i].chunkNum = chunk->chunkNum+1;
3846 chunk=&trk->cluster[i];
3847 chunkSize = chunk->size;
3854 * Assign track ids. If option "use_stream_ids_as_track_ids" is set,
3855 * the stream ids are used as track ids.
3857 * This assumes mov->tracks and s->streams are in the same order and
3858 * there are no gaps in either of them (so mov->tracks[n] refers to
3861 * As an exception, there can be more entries in
3862 * s->streams than in mov->tracks, in which case new track ids are
3863 * generated (starting after the largest found stream id).
3865 static int mov_setup_track_ids(MOVMuxContext *mov, AVFormatContext *s)
3869 if (mov->track_ids_ok)
3872 if (mov->use_stream_ids_as_track_ids) {
3873 int next_generated_track_id = 0;
3874 for (i = 0; i < s->nb_streams; i++) {
3875 if (s->streams[i]->id > next_generated_track_id)
3876 next_generated_track_id = s->streams[i]->id;
3879 for (i = 0; i < mov->nb_streams; i++) {
3880 if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
3883 mov->tracks[i].track_id = i >= s->nb_streams ? ++next_generated_track_id : s->streams[i]->id;
3886 for (i = 0; i < mov->nb_streams; i++) {
3887 if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
3890 mov->tracks[i].track_id = i + 1;
3894 mov->track_ids_ok = 1;
3899 static int mov_write_moov_tag(AVIOContext *pb, MOVMuxContext *mov,
3903 int64_t pos = avio_tell(pb);
3904 avio_wb32(pb, 0); /* size placeholder*/
3905 ffio_wfourcc(pb, "moov");
3907 mov_setup_track_ids(mov, s);
3909 for (i = 0; i < mov->nb_streams; i++) {
3910 if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
3913 mov->tracks[i].time = mov->time;
3915 if (mov->tracks[i].entry)
3916 build_chunks(&mov->tracks[i]);
3919 if (mov->chapter_track)
3920 for (i = 0; i < s->nb_streams; i++) {
3921 mov->tracks[i].tref_tag = MKTAG('c','h','a','p');
3922 mov->tracks[i].tref_id = mov->tracks[mov->chapter_track].track_id;
3924 for (i = 0; i < mov->nb_streams; i++) {
3925 MOVTrack *track = &mov->tracks[i];
3926 if (track->tag == MKTAG('r','t','p',' ')) {
3927 track->tref_tag = MKTAG('h','i','n','t');
3928 track->tref_id = mov->tracks[track->src_track].track_id;
3929 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
3930 int * fallback, size;
3931 fallback = (int*)av_stream_get_side_data(track->st,
3932 AV_PKT_DATA_FALLBACK_TRACK,
3934 if (fallback != NULL && size == sizeof(int)) {
3935 if (*fallback >= 0 && *fallback < mov->nb_streams) {
3936 track->tref_tag = MKTAG('f','a','l','l');
3937 track->tref_id = mov->tracks[*fallback].track_id;
3942 for (i = 0; i < mov->nb_streams; i++) {
3943 if (mov->tracks[i].tag == MKTAG('t','m','c','d')) {
3944 int src_trk = mov->tracks[i].src_track;
3945 mov->tracks[src_trk].tref_tag = mov->tracks[i].tag;
3946 mov->tracks[src_trk].tref_id = mov->tracks[i].track_id;
3947 //src_trk may have a different timescale than the tmcd track
3948 mov->tracks[i].track_duration = av_rescale(mov->tracks[src_trk].track_duration,
3949 mov->tracks[i].timescale,
3950 mov->tracks[src_trk].timescale);
3954 mov_write_mvhd_tag(pb, mov);
3955 if (mov->mode != MODE_MOV && !mov->iods_skip)
3956 mov_write_iods_tag(pb, mov);
3957 for (i = 0; i < mov->nb_streams; i++) {
3958 if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_FRAGMENT) {
3959 int ret = mov_write_trak_tag(s, pb, mov, &(mov->tracks[i]), i < s->nb_streams ? s->streams[i] : NULL);
3964 if (mov->flags & FF_MOV_FLAG_FRAGMENT)
3965 mov_write_mvex_tag(pb, mov); /* QuickTime requires trak to precede this */
3967 if (mov->mode == MODE_PSP)
3968 mov_write_uuidusmt_tag(pb, s);
3970 mov_write_udta_tag(pb, mov, s);
3972 return update_size(pb, pos);
3975 static void param_write_int(AVIOContext *pb, const char *name, int value)
3977 avio_printf(pb, "<param name=\"%s\" value=\"%d\" valuetype=\"data\"/>\n", name, value);
3980 static void param_write_string(AVIOContext *pb, const char *name, const char *value)
3982 avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, value);
3985 static void param_write_hex(AVIOContext *pb, const char *name, const uint8_t *value, int len)
3988 len = FFMIN(sizeof(buf) / 2 - 1, len);
3989 ff_data_to_hex(buf, value, len, 0);
3990 buf[2 * len] = '\0';
3991 avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, buf);
3994 static int mov_write_isml_manifest(AVIOContext *pb, MOVMuxContext *mov, AVFormatContext *s)
3996 int64_t pos = avio_tell(pb);
3998 int64_t manifest_bit_rate = 0;
3999 AVCPBProperties *props = NULL;
4001 static const uint8_t uuid[] = {
4002 0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd,
4003 0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66
4007 ffio_wfourcc(pb, "uuid");
4008 avio_write(pb, uuid, sizeof(uuid));
4011 avio_printf(pb, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
4012 avio_printf(pb, "<smil xmlns=\"http://www.w3.org/2001/SMIL20/Language\">\n");
4013 avio_printf(pb, "<head>\n");
4014 if (!(mov->fc->flags & AVFMT_FLAG_BITEXACT))
4015 avio_printf(pb, "<meta name=\"creator\" content=\"%s\" />\n",
4017 avio_printf(pb, "</head>\n");
4018 avio_printf(pb, "<body>\n");
4019 avio_printf(pb, "<switch>\n");
4021 mov_setup_track_ids(mov, s);
4023 for (i = 0; i < mov->nb_streams; i++) {
4024 MOVTrack *track = &mov->tracks[i];
4026 int track_id = track->track_id;
4027 char track_name_buf[32] = { 0 };
4029 AVStream *st = track->st;
4030 AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0);
4032 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO && !is_cover_image(st)) {
4034 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
4040 props = (AVCPBProperties*)av_stream_get_side_data(track->st, AV_PKT_DATA_CPB_PROPERTIES, NULL);
4042 if (track->par->bit_rate) {
4043 manifest_bit_rate = track->par->bit_rate;
4045 manifest_bit_rate = props->max_bitrate;
4048 avio_printf(pb, "<%s systemBitrate=\"%"PRId64"\">\n", type,
4050 param_write_int(pb, "systemBitrate", manifest_bit_rate);
4051 param_write_int(pb, "trackID", track_id);
4052 param_write_string(pb, "systemLanguage", lang ? lang->value : "und");
4054 /* Build track name piece by piece: */
4056 av_strlcat(track_name_buf, type, sizeof(track_name_buf));
4057 /* 2. track language, if available */
4059 av_strlcatf(track_name_buf, sizeof(track_name_buf),
4060 "_%s", lang->value);
4061 /* 3. special type suffix */
4062 /* "_cc" = closed captions, "_ad" = audio_description */
4063 if (st->disposition & AV_DISPOSITION_HEARING_IMPAIRED)
4064 av_strlcat(track_name_buf, "_cc", sizeof(track_name_buf));
4065 else if (st->disposition & AV_DISPOSITION_VISUAL_IMPAIRED)
4066 av_strlcat(track_name_buf, "_ad", sizeof(track_name_buf));
4068 param_write_string(pb, "trackName", track_name_buf);
4070 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
4071 if (track->par->codec_id == AV_CODEC_ID_H264) {
4073 int size = track->par->extradata_size;
4074 if (!ff_avc_write_annexb_extradata(track->par->extradata, &ptr,
4076 param_write_hex(pb, "CodecPrivateData",
4077 ptr ? ptr : track->par->extradata,
4081 param_write_string(pb, "FourCC", "H264");
4082 } else if (track->par->codec_id == AV_CODEC_ID_VC1) {
4083 param_write_string(pb, "FourCC", "WVC1");
4084 param_write_hex(pb, "CodecPrivateData", track->par->extradata,
4085 track->par->extradata_size);
4087 param_write_int(pb, "MaxWidth", track->par->width);
4088 param_write_int(pb, "MaxHeight", track->par->height);
4089 param_write_int(pb, "DisplayWidth", track->par->width);
4090 param_write_int(pb, "DisplayHeight", track->par->height);
4092 if (track->par->codec_id == AV_CODEC_ID_AAC) {
4093 switch (track->par->profile)
4095 case FF_PROFILE_AAC_HE_V2:
4096 param_write_string(pb, "FourCC", "AACP");
4098 case FF_PROFILE_AAC_HE:
4099 param_write_string(pb, "FourCC", "AACH");
4102 param_write_string(pb, "FourCC", "AACL");
4104 } else if (track->par->codec_id == AV_CODEC_ID_WMAPRO) {
4105 param_write_string(pb, "FourCC", "WMAP");
4107 param_write_hex(pb, "CodecPrivateData", track->par->extradata,
4108 track->par->extradata_size);
4109 param_write_int(pb, "AudioTag", ff_codec_get_tag(ff_codec_wav_tags,
4110 track->par->codec_id));
4111 param_write_int(pb, "Channels", track->par->channels);
4112 param_write_int(pb, "SamplingRate", track->par->sample_rate);
4113 param_write_int(pb, "BitsPerSample", 16);
4114 param_write_int(pb, "PacketSize", track->par->block_align ?
4115 track->par->block_align : 4);
4117 avio_printf(pb, "</%s>\n", type);
4119 avio_printf(pb, "</switch>\n");
4120 avio_printf(pb, "</body>\n");
4121 avio_printf(pb, "</smil>\n");
4123 return update_size(pb, pos);
4126 static int mov_write_mfhd_tag(AVIOContext *pb, MOVMuxContext *mov)
4129 ffio_wfourcc(pb, "mfhd");
4131 avio_wb32(pb, mov->fragments);
4135 static uint32_t get_sample_flags(MOVTrack *track, MOVIentry *entry)
4137 return entry->flags & MOV_SYNC_SAMPLE ? MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO :
4138 (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC);
4141 static int mov_write_tfhd_tag(AVIOContext *pb, MOVMuxContext *mov,
4142 MOVTrack *track, int64_t moof_offset)
4144 int64_t pos = avio_tell(pb);
4145 uint32_t flags = MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
4146 MOV_TFHD_BASE_DATA_OFFSET;
4147 if (!track->entry) {
4148 flags |= MOV_TFHD_DURATION_IS_EMPTY;
4150 flags |= MOV_TFHD_DEFAULT_FLAGS;
4152 if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET)
4153 flags &= ~MOV_TFHD_BASE_DATA_OFFSET;
4154 if (mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) {
4155 flags &= ~MOV_TFHD_BASE_DATA_OFFSET;
4156 flags |= MOV_TFHD_DEFAULT_BASE_IS_MOOF;
4159 /* Don't set a default sample size, the silverlight player refuses
4160 * to play files with that set. Don't set a default sample duration,
4161 * WMP freaks out if it is set. Don't set a base data offset, PIFF
4162 * file format says it MUST NOT be set. */
4163 if (track->mode == MODE_ISM)
4164 flags &= ~(MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
4165 MOV_TFHD_BASE_DATA_OFFSET);
4167 avio_wb32(pb, 0); /* size placeholder */
4168 ffio_wfourcc(pb, "tfhd");
4169 avio_w8(pb, 0); /* version */
4170 avio_wb24(pb, flags);
4172 avio_wb32(pb, track->track_id); /* track-id */
4173 if (flags & MOV_TFHD_BASE_DATA_OFFSET)
4174 avio_wb64(pb, moof_offset);
4175 if (flags & MOV_TFHD_DEFAULT_DURATION) {
4176 track->default_duration = get_cluster_duration(track, 0);
4177 avio_wb32(pb, track->default_duration);
4179 if (flags & MOV_TFHD_DEFAULT_SIZE) {
4180 track->default_size = track->entry ? track->cluster[0].size : 1;
4181 avio_wb32(pb, track->default_size);
4183 track->default_size = -1;
4185 if (flags & MOV_TFHD_DEFAULT_FLAGS) {
4186 /* Set the default flags based on the second sample, if available.
4187 * If the first sample is different, that can be signaled via a separate field. */
4188 if (track->entry > 1)
4189 track->default_sample_flags = get_sample_flags(track, &track->cluster[1]);
4191 track->default_sample_flags =
4192 track->par->codec_type == AVMEDIA_TYPE_VIDEO ?
4193 (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC) :
4194 MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO;
4195 avio_wb32(pb, track->default_sample_flags);
4198 return update_size(pb, pos);
4201 static int mov_write_trun_tag(AVIOContext *pb, MOVMuxContext *mov,
4202 MOVTrack *track, int moof_size,
4205 int64_t pos = avio_tell(pb);
4206 uint32_t flags = MOV_TRUN_DATA_OFFSET;
4209 for (i = first; i < end; i++) {
4210 if (get_cluster_duration(track, i) != track->default_duration)
4211 flags |= MOV_TRUN_SAMPLE_DURATION;
4212 if (track->cluster[i].size != track->default_size)
4213 flags |= MOV_TRUN_SAMPLE_SIZE;
4214 if (i > first && get_sample_flags(track, &track->cluster[i]) != track->default_sample_flags)
4215 flags |= MOV_TRUN_SAMPLE_FLAGS;
4217 if (!(flags & MOV_TRUN_SAMPLE_FLAGS) && track->entry > 0 &&
4218 get_sample_flags(track, &track->cluster[0]) != track->default_sample_flags)
4219 flags |= MOV_TRUN_FIRST_SAMPLE_FLAGS;
4220 if (track->flags & MOV_TRACK_CTTS)
4221 flags |= MOV_TRUN_SAMPLE_CTS;
4223 avio_wb32(pb, 0); /* size placeholder */
4224 ffio_wfourcc(pb, "trun");
4225 if (mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS)
4226 avio_w8(pb, 1); /* version */
4228 avio_w8(pb, 0); /* version */
4229 avio_wb24(pb, flags);
4231 avio_wb32(pb, end - first); /* sample count */
4232 if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET &&
4233 !(mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) &&
4235 avio_wb32(pb, 0); /* Later tracks follow immediately after the previous one */
4237 avio_wb32(pb, moof_size + 8 + track->data_offset +
4238 track->cluster[first].pos); /* data offset */
4239 if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS)
4240 avio_wb32(pb, get_sample_flags(track, &track->cluster[first]));
4242 for (i = first; i < end; i++) {
4243 if (flags & MOV_TRUN_SAMPLE_DURATION)
4244 avio_wb32(pb, get_cluster_duration(track, i));
4245 if (flags & MOV_TRUN_SAMPLE_SIZE)
4246 avio_wb32(pb, track->cluster[i].size);
4247 if (flags & MOV_TRUN_SAMPLE_FLAGS)
4248 avio_wb32(pb, get_sample_flags(track, &track->cluster[i]));
4249 if (flags & MOV_TRUN_SAMPLE_CTS)
4250 avio_wb32(pb, track->cluster[i].cts);
4253 mov->first_trun = 0;
4254 return update_size(pb, pos);
4257 static int mov_write_tfxd_tag(AVIOContext *pb, MOVTrack *track)
4259 int64_t pos = avio_tell(pb);
4260 static const uint8_t uuid[] = {
4261 0x6d, 0x1d, 0x9b, 0x05, 0x42, 0xd5, 0x44, 0xe6,
4262 0x80, 0xe2, 0x14, 0x1d, 0xaf, 0xf7, 0x57, 0xb2
4265 avio_wb32(pb, 0); /* size placeholder */
4266 ffio_wfourcc(pb, "uuid");
4267 avio_write(pb, uuid, sizeof(uuid));
4270 avio_wb64(pb, track->start_dts + track->frag_start +
4271 track->cluster[0].cts);
4272 avio_wb64(pb, track->end_pts -
4273 (track->cluster[0].dts + track->cluster[0].cts));
4275 return update_size(pb, pos);
4278 static int mov_write_tfrf_tag(AVIOContext *pb, MOVMuxContext *mov,
4279 MOVTrack *track, int entry)
4281 int n = track->nb_frag_info - 1 - entry, i;
4282 int size = 8 + 16 + 4 + 1 + 16*n;
4283 static const uint8_t uuid[] = {
4284 0xd4, 0x80, 0x7e, 0xf2, 0xca, 0x39, 0x46, 0x95,
4285 0x8e, 0x54, 0x26, 0xcb, 0x9e, 0x46, 0xa7, 0x9f
4291 avio_seek(pb, track->frag_info[entry].tfrf_offset, SEEK_SET);
4292 avio_wb32(pb, size);
4293 ffio_wfourcc(pb, "uuid");
4294 avio_write(pb, uuid, sizeof(uuid));
4298 for (i = 0; i < n; i++) {
4299 int index = entry + 1 + i;
4300 avio_wb64(pb, track->frag_info[index].time);
4301 avio_wb64(pb, track->frag_info[index].duration);
4303 if (n < mov->ism_lookahead) {
4304 int free_size = 16 * (mov->ism_lookahead - n);
4305 avio_wb32(pb, free_size);
4306 ffio_wfourcc(pb, "free");
4307 ffio_fill(pb, 0, free_size - 8);
4313 static int mov_write_tfrf_tags(AVIOContext *pb, MOVMuxContext *mov,
4316 int64_t pos = avio_tell(pb);
4318 for (i = 0; i < mov->ism_lookahead; i++) {
4319 /* Update the tfrf tag for the last ism_lookahead fragments,
4320 * nb_frag_info - 1 is the next fragment to be written. */
4321 mov_write_tfrf_tag(pb, mov, track, track->nb_frag_info - 2 - i);
4323 avio_seek(pb, pos, SEEK_SET);
4327 static int mov_add_tfra_entries(AVIOContext *pb, MOVMuxContext *mov, int tracks,
4331 for (i = 0; i < mov->nb_streams; i++) {
4332 MOVTrack *track = &mov->tracks[i];
4333 MOVFragmentInfo *info;
4334 if ((tracks >= 0 && i != tracks) || !track->entry)
4336 track->nb_frag_info++;
4337 if (track->nb_frag_info >= track->frag_info_capacity) {
4338 unsigned new_capacity = track->nb_frag_info + MOV_FRAG_INFO_ALLOC_INCREMENT;
4339 if (av_reallocp_array(&track->frag_info,
4341 sizeof(*track->frag_info)))
4342 return AVERROR(ENOMEM);
4343 track->frag_info_capacity = new_capacity;
4345 info = &track->frag_info[track->nb_frag_info - 1];
4346 info->offset = avio_tell(pb);
4348 // Try to recreate the original pts for the first packet
4349 // from the fields we have stored
4350 info->time = track->start_dts + track->frag_start +
4351 track->cluster[0].cts;
4352 info->duration = track->end_pts -
4353 (track->cluster[0].dts + track->cluster[0].cts);
4354 // If the pts is less than zero, we will have trimmed
4355 // away parts of the media track using an edit list,
4356 // and the corresponding start presentation time is zero.
4357 if (info->time < 0) {
4358 info->duration += info->time;
4361 info->tfrf_offset = 0;
4362 mov_write_tfrf_tags(pb, mov, track);
4367 static void mov_prune_frag_info(MOVMuxContext *mov, int tracks, int max)
4370 for (i = 0; i < mov->nb_streams; i++) {
4371 MOVTrack *track = &mov->tracks[i];
4372 if ((tracks >= 0 && i != tracks) || !track->entry)
4374 if (track->nb_frag_info > max) {
4375 memmove(track->frag_info, track->frag_info + (track->nb_frag_info - max), max * sizeof(*track->frag_info));
4376 track->nb_frag_info = max;
4381 static int mov_write_tfdt_tag(AVIOContext *pb, MOVTrack *track)
4383 int64_t pos = avio_tell(pb);
4385 avio_wb32(pb, 0); /* size */
4386 ffio_wfourcc(pb, "tfdt");
4387 avio_w8(pb, 1); /* version */
4389 avio_wb64(pb, track->frag_start);
4390 return update_size(pb, pos);
4393 static int mov_write_traf_tag(AVIOContext *pb, MOVMuxContext *mov,
4394 MOVTrack *track, int64_t moof_offset,
4397 int64_t pos = avio_tell(pb);
4399 avio_wb32(pb, 0); /* size placeholder */
4400 ffio_wfourcc(pb, "traf");
4402 mov_write_tfhd_tag(pb, mov, track, moof_offset);
4403 if (mov->mode != MODE_ISM)
4404 mov_write_tfdt_tag(pb, track);
4405 for (i = 1; i < track->entry; i++) {
4406 if (track->cluster[i].pos != track->cluster[i - 1].pos + track->cluster[i - 1].size) {
4407 mov_write_trun_tag(pb, mov, track, moof_size, start, i);
4411 mov_write_trun_tag(pb, mov, track, moof_size, start, track->entry);
4412 if (mov->mode == MODE_ISM) {
4413 mov_write_tfxd_tag(pb, track);
4415 if (mov->ism_lookahead) {
4416 int i, size = 16 + 4 + 1 + 16 * mov->ism_lookahead;
4418 if (track->nb_frag_info > 0) {
4419 MOVFragmentInfo *info = &track->frag_info[track->nb_frag_info - 1];
4420 if (!info->tfrf_offset)
4421 info->tfrf_offset = avio_tell(pb);
4423 avio_wb32(pb, 8 + size);
4424 ffio_wfourcc(pb, "free");
4425 for (i = 0; i < size; i++)
4430 return update_size(pb, pos);
4433 static int mov_write_moof_tag_internal(AVIOContext *pb, MOVMuxContext *mov,
4434 int tracks, int moof_size)
4436 int64_t pos = avio_tell(pb);
4439 avio_wb32(pb, 0); /* size placeholder */
4440 ffio_wfourcc(pb, "moof");
4441 mov->first_trun = 1;
4443 mov_write_mfhd_tag(pb, mov);
4444 for (i = 0; i < mov->nb_streams; i++) {
4445 MOVTrack *track = &mov->tracks[i];
4446 if (tracks >= 0 && i != tracks)
4450 mov_write_traf_tag(pb, mov, track, pos, moof_size);
4453 return update_size(pb, pos);
4456 static int mov_write_sidx_tag(AVIOContext *pb,
4457 MOVTrack *track, int ref_size, int total_sidx_size)
4459 int64_t pos = avio_tell(pb), offset_pos, end_pos;
4460 int64_t presentation_time, duration, offset;
4461 int starts_with_SAP, i, entries;
4465 presentation_time = track->start_dts + track->frag_start +
4466 track->cluster[0].cts;
4467 duration = track->end_pts -
4468 (track->cluster[0].dts + track->cluster[0].cts);
4469 starts_with_SAP = track->cluster[0].flags & MOV_SYNC_SAMPLE;
4471 // pts<0 should be cut away using edts
4472 if (presentation_time < 0) {
4473 duration += presentation_time;
4474 presentation_time = 0;
4477 entries = track->nb_frag_info;
4480 presentation_time = track->frag_info[0].time;
4483 avio_wb32(pb, 0); /* size */
4484 ffio_wfourcc(pb, "sidx");
4485 avio_w8(pb, 1); /* version */
4487 avio_wb32(pb, track->track_id); /* reference_ID */
4488 avio_wb32(pb, track->timescale); /* timescale */
4489 avio_wb64(pb, presentation_time); /* earliest_presentation_time */
4490 offset_pos = avio_tell(pb);
4491 avio_wb64(pb, 0); /* first_offset (offset to referenced moof) */
4492 avio_wb16(pb, 0); /* reserved */
4494 avio_wb16(pb, entries); /* reference_count */
4495 for (i = 0; i < entries; i++) {
4496 if (!track->entry) {
4497 if (i > 1 && track->frag_info[i].offset != track->frag_info[i - 1].offset + track->frag_info[i - 1].size) {
4498 av_log(NULL, AV_LOG_ERROR, "Non-consecutive fragments, writing incorrect sidx\n");
4500 duration = track->frag_info[i].duration;
4501 ref_size = track->frag_info[i].size;
4502 starts_with_SAP = 1;
4504 avio_wb32(pb, (0 << 31) | (ref_size & 0x7fffffff)); /* reference_type (0 = media) | referenced_size */
4505 avio_wb32(pb, duration); /* subsegment_duration */
4506 avio_wb32(pb, (starts_with_SAP << 31) | (0 << 28) | 0); /* starts_with_SAP | SAP_type | SAP_delta_time */
4509 end_pos = avio_tell(pb);
4510 offset = pos + total_sidx_size - end_pos;
4511 avio_seek(pb, offset_pos, SEEK_SET);
4512 avio_wb64(pb, offset);
4513 avio_seek(pb, end_pos, SEEK_SET);
4514 return update_size(pb, pos);
4517 static int mov_write_sidx_tags(AVIOContext *pb, MOVMuxContext *mov,
4518 int tracks, int ref_size)
4521 AVIOContext *avio_buf;
4523 for (round = 0; round < 2; round++) {
4524 // First run one round to calculate the total size of all
4526 // This would be much simpler if we'd only write one sidx
4527 // atom, for the first track in the moof.
4529 if ((ret = ffio_open_null_buf(&avio_buf)) < 0)
4534 for (i = 0; i < mov->nb_streams; i++) {
4535 MOVTrack *track = &mov->tracks[i];
4536 if (tracks >= 0 && i != tracks)
4538 // When writing a sidx for the full file, entry is 0, but
4539 // we want to include all tracks. ref_size is 0 in this case,
4540 // since we read it from frag_info instead.
4541 if (!track->entry && ref_size > 0)
4543 total_size -= mov_write_sidx_tag(avio_buf, track, ref_size,
4547 total_size = ffio_close_null_buf(avio_buf);
4552 static int mov_write_prft_tag(AVIOContext *pb, MOVMuxContext *mov, int tracks)
4554 int64_t pos = avio_tell(pb), pts_us, ntp_ts;
4555 MOVTrack *first_track;
4557 /* PRFT should be associated with at most one track. So, choosing only the
4561 first_track = &(mov->tracks[0]);
4563 if (!first_track->entry) {
4564 av_log(mov->fc, AV_LOG_WARNING, "Unable to write PRFT, no entries in the track\n");
4568 if (first_track->cluster[0].pts == AV_NOPTS_VALUE) {
4569 av_log(mov->fc, AV_LOG_WARNING, "Unable to write PRFT, first PTS is invalid\n");
4573 if (mov->write_prft == MOV_PRFT_SRC_WALLCLOCK) {
4574 ntp_ts = ff_get_formatted_ntp_time(ff_ntp_time());
4575 } else if (mov->write_prft == MOV_PRFT_SRC_PTS) {
4576 pts_us = av_rescale_q(first_track->cluster[0].pts,
4577 first_track->st->time_base, AV_TIME_BASE_Q);
4578 ntp_ts = ff_get_formatted_ntp_time(pts_us + NTP_OFFSET_US);
4580 av_log(mov->fc, AV_LOG_WARNING, "Unsupported PRFT box configuration: %d\n",
4585 avio_wb32(pb, 0); // Size place holder
4586 ffio_wfourcc(pb, "prft"); // Type
4587 avio_w8(pb, 1); // Version
4588 avio_wb24(pb, 0); // Flags
4589 avio_wb32(pb, first_track->track_id); // reference track ID
4590 avio_wb64(pb, ntp_ts); // NTP time stamp
4591 avio_wb64(pb, first_track->cluster[0].pts); //media time
4592 return update_size(pb, pos);
4595 static int mov_write_moof_tag(AVIOContext *pb, MOVMuxContext *mov, int tracks,
4598 AVIOContext *avio_buf;
4601 if ((ret = ffio_open_null_buf(&avio_buf)) < 0)
4603 mov_write_moof_tag_internal(avio_buf, mov, tracks, 0);
4604 moof_size = ffio_close_null_buf(avio_buf);
4606 if (mov->flags & FF_MOV_FLAG_DASH && !(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX))
4607 mov_write_sidx_tags(pb, mov, tracks, moof_size + 8 + mdat_size);
4609 if (mov->write_prft > MOV_PRFT_NONE && mov->write_prft < MOV_PRFT_NB)
4610 mov_write_prft_tag(pb, mov, tracks);
4612 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX ||
4613 !(mov->flags & FF_MOV_FLAG_SKIP_TRAILER) ||
4614 mov->ism_lookahead) {
4615 if ((ret = mov_add_tfra_entries(pb, mov, tracks, moof_size + 8 + mdat_size)) < 0)
4617 if (!(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) &&
4618 mov->flags & FF_MOV_FLAG_SKIP_TRAILER) {
4619 mov_prune_frag_info(mov, tracks, mov->ism_lookahead + 1);
4623 return mov_write_moof_tag_internal(pb, mov, tracks, moof_size);
4626 static int mov_write_tfra_tag(AVIOContext *pb, MOVTrack *track)
4628 int64_t pos = avio_tell(pb);
4631 avio_wb32(pb, 0); /* size placeholder */
4632 ffio_wfourcc(pb, "tfra");
4633 avio_w8(pb, 1); /* version */
4636 avio_wb32(pb, track->track_id);
4637 avio_wb32(pb, 0); /* length of traf/trun/sample num */
4638 avio_wb32(pb, track->nb_frag_info);
4639 for (i = 0; i < track->nb_frag_info; i++) {
4640 avio_wb64(pb, track->frag_info[i].time);
4641 avio_wb64(pb, track->frag_info[i].offset + track->data_offset);
4642 avio_w8(pb, 1); /* traf number */
4643 avio_w8(pb, 1); /* trun number */
4644 avio_w8(pb, 1); /* sample number */
4647 return update_size(pb, pos);
4650 static int mov_write_mfra_tag(AVIOContext *pb, MOVMuxContext *mov)
4652 int64_t pos = avio_tell(pb);
4655 avio_wb32(pb, 0); /* size placeholder */
4656 ffio_wfourcc(pb, "mfra");
4657 /* An empty mfra atom is enough to indicate to the publishing point that
4658 * the stream has ended. */
4659 if (mov->flags & FF_MOV_FLAG_ISML)
4660 return update_size(pb, pos);
4662 for (i = 0; i < mov->nb_streams; i++) {
4663 MOVTrack *track = &mov->tracks[i];
4664 if (track->nb_frag_info)
4665 mov_write_tfra_tag(pb, track);
4669 ffio_wfourcc(pb, "mfro");
4670 avio_wb32(pb, 0); /* version + flags */
4671 avio_wb32(pb, avio_tell(pb) + 4 - pos);
4673 return update_size(pb, pos);
4676 static int mov_write_mdat_tag(AVIOContext *pb, MOVMuxContext *mov)
4678 avio_wb32(pb, 8); // placeholder for extended size field (64 bit)
4679 ffio_wfourcc(pb, mov->mode == MODE_MOV ? "wide" : "free");
4681 mov->mdat_pos = avio_tell(pb);
4682 avio_wb32(pb, 0); /* size placeholder*/
4683 ffio_wfourcc(pb, "mdat");
4687 /* TODO: This needs to be more general */
4688 static int mov_write_ftyp_tag(AVIOContext *pb, AVFormatContext *s)
4690 MOVMuxContext *mov = s->priv_data;
4691 int64_t pos = avio_tell(pb);
4692 int has_h264 = 0, has_video = 0;
4696 for (i = 0; i < s->nb_streams; i++) {
4697 AVStream *st = s->streams[i];
4698 if (is_cover_image(st))
4700 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
4702 if (st->codecpar->codec_id == AV_CODEC_ID_H264)
4706 avio_wb32(pb, 0); /* size */
4707 ffio_wfourcc(pb, "ftyp");
4709 if (mov->major_brand && strlen(mov->major_brand) >= 4)
4710 ffio_wfourcc(pb, mov->major_brand);
4711 else if (mov->mode == MODE_3GP) {
4712 ffio_wfourcc(pb, has_h264 ? "3gp6" : "3gp4");
4713 minor = has_h264 ? 0x100 : 0x200;
4714 } else if (mov->mode & MODE_3G2) {
4715 ffio_wfourcc(pb, has_h264 ? "3g2b" : "3g2a");
4716 minor = has_h264 ? 0x20000 : 0x10000;
4717 } else if (mov->mode == MODE_PSP)
4718 ffio_wfourcc(pb, "MSNV");
4719 else if (mov->mode == MODE_MP4 && mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)
4720 ffio_wfourcc(pb, "iso5"); // Required when using default-base-is-moof
4721 else if (mov->mode == MODE_MP4 && mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS)
4722 ffio_wfourcc(pb, "iso4");
4723 else if (mov->mode == MODE_MP4)
4724 ffio_wfourcc(pb, "isom");
4725 else if (mov->mode == MODE_IPOD)
4726 ffio_wfourcc(pb, has_video ? "M4V ":"M4A ");
4727 else if (mov->mode == MODE_ISM)
4728 ffio_wfourcc(pb, "isml");
4729 else if (mov->mode == MODE_F4V)
4730 ffio_wfourcc(pb, "f4v ");
4732 ffio_wfourcc(pb, "qt ");
4734 avio_wb32(pb, minor);
4736 if (mov->mode == MODE_MOV)
4737 ffio_wfourcc(pb, "qt ");
4738 else if (mov->mode == MODE_ISM) {
4739 ffio_wfourcc(pb, "piff");
4740 } else if (!(mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)) {
4741 ffio_wfourcc(pb, "isom");
4742 ffio_wfourcc(pb, "iso2");
4744 ffio_wfourcc(pb, "avc1");
4747 // We add tfdt atoms when fragmenting, signal this with the iso6 compatible
4748 // brand. This is compatible with users that don't understand tfdt.
4749 if (mov->flags & FF_MOV_FLAG_FRAGMENT && mov->mode != MODE_ISM)
4750 ffio_wfourcc(pb, "iso6");
4752 if (mov->mode == MODE_3GP)
4753 ffio_wfourcc(pb, has_h264 ? "3gp6":"3gp4");
4754 else if (mov->mode & MODE_3G2)
4755 ffio_wfourcc(pb, has_h264 ? "3g2b":"3g2a");
4756 else if (mov->mode == MODE_PSP)
4757 ffio_wfourcc(pb, "MSNV");
4758 else if (mov->mode == MODE_MP4)
4759 ffio_wfourcc(pb, "mp41");
4761 if (mov->flags & FF_MOV_FLAG_DASH && mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
4762 ffio_wfourcc(pb, "dash");
4764 return update_size(pb, pos);
4767 static int mov_write_uuidprof_tag(AVIOContext *pb, AVFormatContext *s)
4769 AVStream *video_st = s->streams[0];
4770 AVCodecParameters *video_par = s->streams[0]->codecpar;
4771 AVCodecParameters *audio_par = s->streams[1]->codecpar;
4772 int audio_rate = audio_par->sample_rate;
4773 int64_t frame_rate = video_st->avg_frame_rate.den ?
4774 (video_st->avg_frame_rate.num * 0x10000LL) / video_st->avg_frame_rate.den :
4776 int audio_kbitrate = audio_par->bit_rate / 1000;
4777 int video_kbitrate = FFMIN(video_par->bit_rate / 1000, 800 - audio_kbitrate);
4779 if (frame_rate < 0 || frame_rate > INT32_MAX) {
4780 av_log(s, AV_LOG_ERROR, "Frame rate %f outside supported range\n", frame_rate / (double)0x10000);
4781 return AVERROR(EINVAL);
4784 avio_wb32(pb, 0x94); /* size */
4785 ffio_wfourcc(pb, "uuid");
4786 ffio_wfourcc(pb, "PROF");
4788 avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
4789 avio_wb32(pb, 0xbb88695c);
4790 avio_wb32(pb, 0xfac9c740);
4792 avio_wb32(pb, 0x0); /* ? */
4793 avio_wb32(pb, 0x3); /* 3 sections ? */
4795 avio_wb32(pb, 0x14); /* size */
4796 ffio_wfourcc(pb, "FPRF");
4797 avio_wb32(pb, 0x0); /* ? */
4798 avio_wb32(pb, 0x0); /* ? */
4799 avio_wb32(pb, 0x0); /* ? */
4801 avio_wb32(pb, 0x2c); /* size */
4802 ffio_wfourcc(pb, "APRF"); /* audio */
4804 avio_wb32(pb, 0x2); /* TrackID */
4805 ffio_wfourcc(pb, "mp4a");
4806 avio_wb32(pb, 0x20f);
4808 avio_wb32(pb, audio_kbitrate);
4809 avio_wb32(pb, audio_kbitrate);
4810 avio_wb32(pb, audio_rate);
4811 avio_wb32(pb, audio_par->channels);
4813 avio_wb32(pb, 0x34); /* size */
4814 ffio_wfourcc(pb, "VPRF"); /* video */
4816 avio_wb32(pb, 0x1); /* TrackID */
4817 if (video_par->codec_id == AV_CODEC_ID_H264) {
4818 ffio_wfourcc(pb, "avc1");
4819 avio_wb16(pb, 0x014D);
4820 avio_wb16(pb, 0x0015);
4822 ffio_wfourcc(pb, "mp4v");
4823 avio_wb16(pb, 0x0000);
4824 avio_wb16(pb, 0x0103);
4827 avio_wb32(pb, video_kbitrate);
4828 avio_wb32(pb, video_kbitrate);
4829 avio_wb32(pb, frame_rate);
4830 avio_wb32(pb, frame_rate);
4831 avio_wb16(pb, video_par->width);
4832 avio_wb16(pb, video_par->height);
4833 avio_wb32(pb, 0x010001); /* ? */
4838 static int mov_write_identification(AVIOContext *pb, AVFormatContext *s)
4840 MOVMuxContext *mov = s->priv_data;
4843 mov_write_ftyp_tag(pb,s);
4844 if (mov->mode == MODE_PSP) {
4845 int video_streams_nb = 0, audio_streams_nb = 0, other_streams_nb = 0;
4846 for (i = 0; i < s->nb_streams; i++) {
4847 AVStream *st = s->streams[i];
4848 if (is_cover_image(st))
4850 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
4852 else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
4858 if (video_streams_nb != 1 || audio_streams_nb != 1 || other_streams_nb) {
4859 av_log(s, AV_LOG_ERROR, "PSP mode need one video and one audio stream\n");
4860 return AVERROR(EINVAL);
4862 return mov_write_uuidprof_tag(pb, s);
4867 static int mov_parse_mpeg2_frame(AVPacket *pkt, uint32_t *flags)
4870 int i, closed_gop = 0;
4872 for (i = 0; i < pkt->size - 4; i++) {
4873 c = (c << 8) + pkt->data[i];
4874 if (c == 0x1b8) { // gop
4875 closed_gop = pkt->data[i + 4] >> 6 & 0x01;
4876 } else if (c == 0x100) { // pic
4877 int temp_ref = (pkt->data[i + 1] << 2) | (pkt->data[i + 2] >> 6);
4878 if (!temp_ref || closed_gop) // I picture is not reordered
4879 *flags = MOV_SYNC_SAMPLE;
4881 *flags = MOV_PARTIAL_SYNC_SAMPLE;
4888 static void mov_parse_vc1_frame(AVPacket *pkt, MOVTrack *trk)
4890 const uint8_t *start, *next, *end = pkt->data + pkt->size;
4891 int seq = 0, entry = 0;
4892 int key = pkt->flags & AV_PKT_FLAG_KEY;
4893 start = find_next_marker(pkt->data, end);
4894 for (next = start; next < end; start = next) {
4895 next = find_next_marker(start + 4, end);
4896 switch (AV_RB32(start)) {
4897 case VC1_CODE_SEQHDR:
4900 case VC1_CODE_ENTRYPOINT:
4903 case VC1_CODE_SLICE:
4904 trk->vc1_info.slices = 1;
4908 if (!trk->entry && trk->vc1_info.first_packet_seen)
4909 trk->vc1_info.first_frag_written = 1;
4910 if (!trk->entry && !trk->vc1_info.first_frag_written) {
4911 /* First packet in first fragment */
4912 trk->vc1_info.first_packet_seq = seq;
4913 trk->vc1_info.first_packet_entry = entry;
4914 trk->vc1_info.first_packet_seen = 1;
4915 } else if ((seq && !trk->vc1_info.packet_seq) ||
4916 (entry && !trk->vc1_info.packet_entry)) {
4918 for (i = 0; i < trk->entry; i++)
4919 trk->cluster[i].flags &= ~MOV_SYNC_SAMPLE;
4920 trk->has_keyframes = 0;
4922 trk->vc1_info.packet_seq = 1;
4924 trk->vc1_info.packet_entry = 1;
4925 if (!trk->vc1_info.first_frag_written) {
4926 /* First fragment */
4927 if ((!seq || trk->vc1_info.first_packet_seq) &&
4928 (!entry || trk->vc1_info.first_packet_entry)) {
4929 /* First packet had the same headers as this one, readd the
4930 * sync sample flag. */
4931 trk->cluster[0].flags |= MOV_SYNC_SAMPLE;
4932 trk->has_keyframes = 1;
4936 if (trk->vc1_info.packet_seq && trk->vc1_info.packet_entry)
4938 else if (trk->vc1_info.packet_seq)
4940 else if (trk->vc1_info.packet_entry)
4943 trk->cluster[trk->entry].flags |= MOV_SYNC_SAMPLE;
4944 trk->has_keyframes++;
4948 static int mov_flush_fragment_interleaving(AVFormatContext *s, MOVTrack *track)
4950 MOVMuxContext *mov = s->priv_data;
4955 if (!track->mdat_buf)
4957 if (!mov->mdat_buf) {
4958 if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0)
4961 buf_size = avio_close_dyn_buf(track->mdat_buf, &buf);
4962 track->mdat_buf = NULL;
4964 offset = avio_tell(mov->mdat_buf);
4965 avio_write(mov->mdat_buf, buf, buf_size);
4968 for (i = track->entries_flushed; i < track->entry; i++)
4969 track->cluster[i].pos += offset;
4970 track->entries_flushed = track->entry;
4974 static int mov_flush_fragment(AVFormatContext *s, int force)
4976 MOVMuxContext *mov = s->priv_data;
4977 int i, first_track = -1;
4978 int64_t mdat_size = 0;
4980 int has_video = 0, starts_with_key = 0, first_video_track = 1;
4982 if (!(mov->flags & FF_MOV_FLAG_FRAGMENT))
4985 // Try to fill in the duration of the last packet in each stream
4986 // from queued packets in the interleave queues. If the flushing
4987 // of fragments was triggered automatically by an AVPacket, we
4988 // already have reliable info for the end of that track, but other
4989 // tracks may need to be filled in.
4990 for (i = 0; i < s->nb_streams; i++) {
4991 MOVTrack *track = &mov->tracks[i];
4992 if (!track->end_reliable) {
4994 if (!ff_interleaved_peek(s, i, &pkt, 1)) {
4995 if (track->dts_shift != AV_NOPTS_VALUE)
4996 pkt.dts += track->dts_shift;
4997 track->track_duration = pkt.dts - track->start_dts;
4998 if (pkt.pts != AV_NOPTS_VALUE)
4999 track->end_pts = pkt.pts;
5001 track->end_pts = pkt.dts;
5006 for (i = 0; i < mov->nb_streams; i++) {
5007 MOVTrack *track = &mov->tracks[i];
5008 if (track->entry <= 1)
5010 // Sample durations are calculated as the diff of dts values,
5011 // but for the last sample in a fragment, we don't know the dts
5012 // of the first sample in the next fragment, so we have to rely
5013 // on what was set as duration in the AVPacket. Not all callers
5014 // set this though, so we might want to replace it with an
5015 // estimate if it currently is zero.
5016 if (get_cluster_duration(track, track->entry - 1) != 0)
5018 // Use the duration (i.e. dts diff) of the second last sample for
5019 // the last one. This is a wild guess (and fatal if it turns out
5020 // to be too long), but probably the best we can do - having a zero
5021 // duration is bad as well.
5022 track->track_duration += get_cluster_duration(track, track->entry - 2);
5023 track->end_pts += get_cluster_duration(track, track->entry - 2);
5024 if (!mov->missing_duration_warned) {
5025 av_log(s, AV_LOG_WARNING,
5026 "Estimating the duration of the last packet in a "
5027 "fragment, consider setting the duration field in "
5028 "AVPacket instead.\n");
5029 mov->missing_duration_warned = 1;
5033 if (!mov->moov_written) {
5034 int64_t pos = avio_tell(s->pb);
5036 int buf_size, moov_size;
5038 for (i = 0; i < mov->nb_streams; i++)
5039 if (!mov->tracks[i].entry && !is_cover_image(mov->tracks[i].st))
5041 /* Don't write the initial moov unless all tracks have data */
5042 if (i < mov->nb_streams && !force)
5045 moov_size = get_moov_size(s);
5046 for (i = 0; i < mov->nb_streams; i++)
5047 mov->tracks[i].data_offset = pos + moov_size + 8;
5049 avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_HEADER);
5050 if (mov->flags & FF_MOV_FLAG_DELAY_MOOV)
5051 mov_write_identification(s->pb, s);
5052 if ((ret = mov_write_moov_tag(s->pb, mov, s)) < 0)
5055 if (mov->flags & FF_MOV_FLAG_DELAY_MOOV) {
5056 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
5057 mov->reserved_header_pos = avio_tell(s->pb);
5059 mov->moov_written = 1;
5063 buf_size = avio_close_dyn_buf(mov->mdat_buf, &buf);
5064 mov->mdat_buf = NULL;
5065 avio_wb32(s->pb, buf_size + 8);
5066 ffio_wfourcc(s->pb, "mdat");
5067 avio_write(s->pb, buf, buf_size);
5070 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
5071 mov->reserved_header_pos = avio_tell(s->pb);
5073 mov->moov_written = 1;
5075 for (i = 0; i < mov->nb_streams; i++) {
5076 if (mov->tracks[i].entry)
5077 mov->tracks[i].frag_start += mov->tracks[i].start_dts +
5078 mov->tracks[i].track_duration -
5079 mov->tracks[i].cluster[0].dts;
5080 mov->tracks[i].entry = 0;
5081 mov->tracks[i].end_reliable = 0;
5087 if (mov->frag_interleave) {
5088 for (i = 0; i < mov->nb_streams; i++) {
5089 MOVTrack *track = &mov->tracks[i];
5091 if ((ret = mov_flush_fragment_interleaving(s, track)) < 0)
5097 mdat_size = avio_tell(mov->mdat_buf);
5100 for (i = 0; i < mov->nb_streams; i++) {
5101 MOVTrack *track = &mov->tracks[i];
5102 if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF || mov->frag_interleave)
5103 track->data_offset = 0;
5105 track->data_offset = mdat_size;
5106 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
5108 if (first_video_track) {
5110 starts_with_key = track->cluster[0].flags & MOV_SYNC_SAMPLE;
5111 first_video_track = 0;
5116 if (track->mdat_buf)
5117 mdat_size += avio_tell(track->mdat_buf);
5118 if (first_track < 0)
5125 avio_write_marker(s->pb,
5126 av_rescale(mov->tracks[first_track].cluster[0].dts, AV_TIME_BASE, mov->tracks[first_track].timescale),
5127 (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);
5129 for (i = 0; i < mov->nb_streams; i++) {
5130 MOVTrack *track = &mov->tracks[i];
5131 int buf_size, write_moof = 1, moof_tracks = -1;
5133 int64_t duration = 0;
5136 duration = track->start_dts + track->track_duration -
5137 track->cluster[0].dts;
5138 if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF) {
5139 if (!track->mdat_buf)
5141 mdat_size = avio_tell(track->mdat_buf);
5144 write_moof = i == first_track;
5150 mov_write_moof_tag(s->pb, mov, moof_tracks, mdat_size);
5153 avio_wb32(s->pb, mdat_size + 8);
5154 ffio_wfourcc(s->pb, "mdat");
5158 track->frag_start += duration;
5160 track->entries_flushed = 0;
5161 track->end_reliable = 0;
5162 if (!mov->frag_interleave) {
5163 if (!track->mdat_buf)
5165 buf_size = avio_close_dyn_buf(track->mdat_buf, &buf);
5166 track->mdat_buf = NULL;
5170 buf_size = avio_close_dyn_buf(mov->mdat_buf, &buf);
5171 mov->mdat_buf = NULL;
5174 avio_write(s->pb, buf, buf_size);
5184 static int mov_auto_flush_fragment(AVFormatContext *s, int force)
5186 MOVMuxContext *mov = s->priv_data;
5187 int had_moov = mov->moov_written;
5188 int ret = mov_flush_fragment(s, force);
5191 // If using delay_moov, the first flush only wrote the moov,
5192 // not the actual moof+mdat pair, thus flush once again.
5193 if (!had_moov && mov->flags & FF_MOV_FLAG_DELAY_MOOV)
5194 ret = mov_flush_fragment(s, force);
5198 static int check_pkt(AVFormatContext *s, AVPacket *pkt)
5200 MOVMuxContext *mov = s->priv_data;
5201 MOVTrack *trk = &mov->tracks[pkt->stream_index];
5206 ref = trk->cluster[trk->entry - 1].dts;
5207 } else if ( trk->start_dts != AV_NOPTS_VALUE
5208 && !trk->frag_discont) {
5209 ref = trk->start_dts + trk->track_duration;
5211 ref = pkt->dts; // Skip tests for the first packet
5213 if (trk->dts_shift != AV_NOPTS_VALUE) {
5214 /* With negative CTS offsets we have set an offset to the DTS,
5215 * reverse this for the check. */
5216 ref -= trk->dts_shift;
5219 duration = pkt->dts - ref;
5220 if (pkt->dts < ref || duration >= INT_MAX) {
5221 av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" / timestamp: %"PRId64" is out of range for mov/mp4 format\n",
5226 pkt->pts = AV_NOPTS_VALUE;
5229 if (pkt->duration < 0 || pkt->duration > INT_MAX) {
5230 av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" is invalid\n", pkt->duration);
5231 return AVERROR(EINVAL);
5236 int ff_mov_write_packet(AVFormatContext *s, AVPacket *pkt)
5238 MOVMuxContext *mov = s->priv_data;
5239 AVIOContext *pb = s->pb;
5240 MOVTrack *trk = &mov->tracks[pkt->stream_index];
5241 AVCodecParameters *par = trk->par;
5242 unsigned int samples_in_chunk = 0;
5243 int size = pkt->size, ret = 0;
5244 uint8_t *reformatted_data = NULL;
5246 ret = check_pkt(s, pkt);
5250 if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
5252 if (mov->moov_written || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
5253 if (mov->frag_interleave && mov->fragments > 0) {
5254 if (trk->entry - trk->entries_flushed >= mov->frag_interleave) {
5255 if ((ret = mov_flush_fragment_interleaving(s, trk)) < 0)
5260 if (!trk->mdat_buf) {
5261 if ((ret = avio_open_dyn_buf(&trk->mdat_buf)) < 0)
5266 if (!mov->mdat_buf) {
5267 if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0)
5274 if (par->codec_id == AV_CODEC_ID_AMR_NB) {
5275 /* We must find out how many AMR blocks there are in one packet */
5276 static const uint16_t packed_size[16] =
5277 {13, 14, 16, 18, 20, 21, 27, 32, 6, 0, 0, 0, 0, 0, 0, 1};
5280 while (len < size && samples_in_chunk < 100) {
5281 len += packed_size[(pkt->data[len] >> 3) & 0x0F];
5284 if (samples_in_chunk > 1) {
5285 av_log(s, AV_LOG_ERROR, "fatal error, input is not a single packet, implement a AVParser for it\n");
5288 } else if (par->codec_id == AV_CODEC_ID_ADPCM_MS ||
5289 par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) {
5290 samples_in_chunk = trk->par->frame_size;
5291 } else if (trk->sample_size)
5292 samples_in_chunk = size / trk->sample_size;
5294 samples_in_chunk = 1;
5296 if (samples_in_chunk < 1) {
5297 av_log(s, AV_LOG_ERROR, "fatal error, input packet contains no samples\n");
5298 return AVERROR_PATCHWELCOME;
5301 /* copy extradata if it exists */
5302 if (trk->vos_len == 0 && par->extradata_size > 0 &&
5303 !TAG_IS_AVCI(trk->tag) &&
5304 (par->codec_id != AV_CODEC_ID_DNXHD)) {
5305 trk->vos_len = par->extradata_size;
5306 trk->vos_data = av_malloc(trk->vos_len);
5307 if (!trk->vos_data) {
5308 ret = AVERROR(ENOMEM);
5311 memcpy(trk->vos_data, par->extradata, trk->vos_len);
5314 if (par->codec_id == AV_CODEC_ID_AAC && pkt->size > 2 &&
5315 (AV_RB16(pkt->data) & 0xfff0) == 0xfff0) {
5316 if (!s->streams[pkt->stream_index]->nb_frames) {
5317 av_log(s, AV_LOG_ERROR, "Malformed AAC bitstream detected: "
5318 "use the audio bitstream filter 'aac_adtstoasc' to fix it "
5319 "('-bsf:a aac_adtstoasc' option with ffmpeg)\n");
5322 av_log(s, AV_LOG_WARNING, "aac bitstream error\n");
5324 if (par->codec_id == AV_CODEC_ID_H264 && trk->vos_len > 0 && *(uint8_t *)trk->vos_data != 1 && !TAG_IS_AVCI(trk->tag)) {
5325 /* from x264 or from bytestream H.264 */
5326 /* NAL reformatting needed */
5327 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
5328 ff_avc_parse_nal_units_buf(pkt->data, &reformatted_data,
5330 avio_write(pb, reformatted_data, size);
5332 if (trk->cenc.aes_ctr) {
5333 size = ff_mov_cenc_avc_parse_nal_units(&trk->cenc, pb, pkt->data, size);
5339 size = ff_avc_parse_nal_units(pb, pkt->data, pkt->size);
5342 } else if (par->codec_id == AV_CODEC_ID_HEVC && trk->vos_len > 6 &&
5343 (AV_RB24(trk->vos_data) == 1 || AV_RB32(trk->vos_data) == 1)) {
5344 /* extradata is Annex B, assume the bitstream is too and convert it */
5345 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
5346 ff_hevc_annexb2mp4_buf(pkt->data, &reformatted_data, &size, 0, NULL);
5347 avio_write(pb, reformatted_data, size);
5349 size = ff_hevc_annexb2mp4(pb, pkt->data, pkt->size, 0, NULL);
5351 } else if (par->codec_id == AV_CODEC_ID_AV1) {
5352 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
5353 ff_av1_filter_obus_buf(pkt->data, &reformatted_data, &size);
5354 avio_write(pb, reformatted_data, size);
5356 size = ff_av1_filter_obus(pb, pkt->data, pkt->size);
5358 #if CONFIG_AC3_PARSER
5359 } else if (par->codec_id == AV_CODEC_ID_EAC3) {
5360 size = handle_eac3(mov, pkt, trk);
5365 avio_write(pb, pkt->data, size);
5368 if (trk->cenc.aes_ctr) {
5369 if (par->codec_id == AV_CODEC_ID_H264 && par->extradata_size > 4) {
5370 int nal_size_length = (par->extradata[4] & 0x3) + 1;
5371 ret = ff_mov_cenc_avc_write_nal_units(s, &trk->cenc, nal_size_length, pb, pkt->data, size);
5373 ret = ff_mov_cenc_write_packet(&trk->cenc, pb, pkt->data, size);
5380 avio_write(pb, pkt->data, size);
5384 if ((par->codec_id == AV_CODEC_ID_DNXHD ||
5385 par->codec_id == AV_CODEC_ID_AC3) && !trk->vos_len) {
5386 /* copy frame to create needed atoms */
5387 trk->vos_len = size;
5388 trk->vos_data = av_malloc(size);
5389 if (!trk->vos_data) {
5390 ret = AVERROR(ENOMEM);
5393 memcpy(trk->vos_data, pkt->data, size);
5396 if (trk->entry >= trk->cluster_capacity) {
5397 unsigned new_capacity = 2 * (trk->entry + MOV_INDEX_CLUSTER_SIZE);
5398 if (av_reallocp_array(&trk->cluster, new_capacity,
5399 sizeof(*trk->cluster))) {
5400 ret = AVERROR(ENOMEM);
5403 trk->cluster_capacity = new_capacity;
5406 trk->cluster[trk->entry].pos = avio_tell(pb) - size;
5407 trk->cluster[trk->entry].samples_in_chunk = samples_in_chunk;
5408 trk->cluster[trk->entry].chunkNum = 0;
5409 trk->cluster[trk->entry].size = size;
5410 trk->cluster[trk->entry].entries = samples_in_chunk;
5411 trk->cluster[trk->entry].dts = pkt->dts;
5412 trk->cluster[trk->entry].pts = pkt->pts;
5413 if (!trk->entry && trk->start_dts != AV_NOPTS_VALUE) {
5414 if (!trk->frag_discont) {
5415 /* First packet of a new fragment. We already wrote the duration
5416 * of the last packet of the previous fragment based on track_duration,
5417 * which might not exactly match our dts. Therefore adjust the dts
5418 * of this packet to be what the previous packets duration implies. */
5419 trk->cluster[trk->entry].dts = trk->start_dts + trk->track_duration;
5420 /* We also may have written the pts and the corresponding duration
5421 * in sidx/tfrf/tfxd tags; make sure the sidx pts and duration match up with
5422 * the next fragment. This means the cts of the first sample must
5423 * be the same in all fragments, unless end_pts was updated by
5424 * the packet causing the fragment to be written. */
5425 if ((mov->flags & FF_MOV_FLAG_DASH && !(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)) ||
5426 mov->mode == MODE_ISM)
5427 pkt->pts = pkt->dts + trk->end_pts - trk->cluster[trk->entry].dts;
5429 /* New fragment, but discontinuous from previous fragments.
5430 * Pretend the duration sum of the earlier fragments is
5431 * pkt->dts - trk->start_dts. */
5432 trk->frag_start = pkt->dts - trk->start_dts;
5433 trk->end_pts = AV_NOPTS_VALUE;
5434 trk->frag_discont = 0;
5438 if (!trk->entry && trk->start_dts == AV_NOPTS_VALUE && !mov->use_editlist &&
5439 s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO) {
5440 /* Not using edit lists and shifting the first track to start from zero.
5441 * If the other streams start from a later timestamp, we won't be able
5442 * to signal the difference in starting time without an edit list.
5443 * Thus move the timestamp for this first sample to 0, increasing
5444 * its duration instead. */
5445 trk->cluster[trk->entry].dts = trk->start_dts = 0;
5447 if (trk->start_dts == AV_NOPTS_VALUE) {
5448 trk->start_dts = pkt->dts;
5449 if (trk->frag_discont) {
5450 if (mov->use_editlist) {
5451 /* Pretend the whole stream started at pts=0, with earlier fragments
5452 * already written. If the stream started at pts=0, the duration sum
5453 * of earlier fragments would have been pkt->pts. */
5454 trk->frag_start = pkt->pts;
5455 trk->start_dts = pkt->dts - pkt->pts;
5457 /* Pretend the whole stream started at dts=0, with earlier fragments
5458 * already written, with a duration summing up to pkt->dts. */
5459 trk->frag_start = pkt->dts;
5462 trk->frag_discont = 0;
5463 } else if (pkt->dts && mov->moov_written)
5464 av_log(s, AV_LOG_WARNING,
5465 "Track %d starts with a nonzero dts %"PRId64", while the moov "
5466 "already has been written. Set the delay_moov flag to handle "
5468 pkt->stream_index, pkt->dts);
5470 trk->track_duration = pkt->dts - trk->start_dts + pkt->duration;
5471 trk->last_sample_is_subtitle_end = 0;
5473 if (pkt->pts == AV_NOPTS_VALUE) {
5474 av_log(s, AV_LOG_WARNING, "pts has no value\n");
5475 pkt->pts = pkt->dts;
5477 if (pkt->dts != pkt->pts)
5478 trk->flags |= MOV_TRACK_CTTS;
5479 trk->cluster[trk->entry].cts = pkt->pts - pkt->dts;
5480 trk->cluster[trk->entry].flags = 0;
5481 if (trk->start_cts == AV_NOPTS_VALUE)
5482 trk->start_cts = pkt->pts - pkt->dts;
5483 if (trk->end_pts == AV_NOPTS_VALUE)
5484 trk->end_pts = trk->cluster[trk->entry].dts +
5485 trk->cluster[trk->entry].cts + pkt->duration;
5487 trk->end_pts = FFMAX(trk->end_pts, trk->cluster[trk->entry].dts +
5488 trk->cluster[trk->entry].cts +
5491 if (par->codec_id == AV_CODEC_ID_VC1) {
5492 mov_parse_vc1_frame(pkt, trk);
5493 } else if (pkt->flags & AV_PKT_FLAG_KEY) {
5494 if (mov->mode == MODE_MOV && par->codec_id == AV_CODEC_ID_MPEG2VIDEO &&
5495 trk->entry > 0) { // force sync sample for the first key frame
5496 mov_parse_mpeg2_frame(pkt, &trk->cluster[trk->entry].flags);
5497 if (trk->cluster[trk->entry].flags & MOV_PARTIAL_SYNC_SAMPLE)
5498 trk->flags |= MOV_TRACK_STPS;
5500 trk->cluster[trk->entry].flags = MOV_SYNC_SAMPLE;
5502 if (trk->cluster[trk->entry].flags & MOV_SYNC_SAMPLE)
5503 trk->has_keyframes++;
5505 if (pkt->flags & AV_PKT_FLAG_DISPOSABLE) {
5506 trk->cluster[trk->entry].flags |= MOV_DISPOSABLE_SAMPLE;
5507 trk->has_disposable++;
5510 trk->sample_count += samples_in_chunk;
5511 mov->mdat_size += size;
5513 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams)
5514 ff_mov_add_hinted_packet(s, pkt, trk->hint_track, trk->entry,
5515 reformatted_data, size);
5520 av_free(reformatted_data);
5524 static int mov_write_single_packet(AVFormatContext *s, AVPacket *pkt)
5526 MOVMuxContext *mov = s->priv_data;
5527 MOVTrack *trk = &mov->tracks[pkt->stream_index];
5528 AVCodecParameters *par = trk->par;
5529 int64_t frag_duration = 0;
5530 int size = pkt->size;
5532 int ret = check_pkt(s, pkt);
5536 if (mov->flags & FF_MOV_FLAG_FRAG_DISCONT) {
5538 for (i = 0; i < s->nb_streams; i++)
5539 mov->tracks[i].frag_discont = 1;
5540 mov->flags &= ~FF_MOV_FLAG_FRAG_DISCONT;
5543 if (mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS) {
5544 if (trk->dts_shift == AV_NOPTS_VALUE)
5545 trk->dts_shift = pkt->pts - pkt->dts;
5546 pkt->dts += trk->dts_shift;
5549 if (trk->par->codec_id == AV_CODEC_ID_MP4ALS ||
5550 trk->par->codec_id == AV_CODEC_ID_AAC ||
5551 trk->par->codec_id == AV_CODEC_ID_AV1 ||
5552 trk->par->codec_id == AV_CODEC_ID_FLAC) {
5554 uint8_t *side = av_packet_get_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA, &side_size);
5555 if (side && side_size > 0 && (side_size != par->extradata_size || memcmp(side, par->extradata, side_size))) {
5556 void *newextra = av_mallocz(side_size + AV_INPUT_BUFFER_PADDING_SIZE);
5558 return AVERROR(ENOMEM);
5559 av_free(par->extradata);
5560 par->extradata = newextra;
5561 memcpy(par->extradata, side, side_size);
5562 par->extradata_size = side_size;
5563 if (!pkt->size) // Flush packet
5564 mov->need_rewrite_extradata = 1;
5569 if (trk->start_dts == AV_NOPTS_VALUE && trk->frag_discont) {
5570 trk->start_dts = pkt->dts;
5571 if (pkt->pts != AV_NOPTS_VALUE)
5572 trk->start_cts = pkt->pts - pkt->dts;
5577 return 0; /* Discard 0 sized packets */
5580 if (trk->entry && pkt->stream_index < s->nb_streams)
5581 frag_duration = av_rescale_q(pkt->dts - trk->cluster[0].dts,
5582 s->streams[pkt->stream_index]->time_base,
5584 if ((mov->max_fragment_duration &&
5585 frag_duration >= mov->max_fragment_duration) ||
5586 (mov->max_fragment_size && mov->mdat_size + size >= mov->max_fragment_size) ||
5587 (mov->flags & FF_MOV_FLAG_FRAG_KEYFRAME &&
5588 par->codec_type == AVMEDIA_TYPE_VIDEO &&
5589 trk->entry && pkt->flags & AV_PKT_FLAG_KEY) ||
5590 (mov->flags & FF_MOV_FLAG_FRAG_EVERY_FRAME)) {
5591 if (frag_duration >= mov->min_fragment_duration) {
5592 // Set the duration of this track to line up with the next
5593 // sample in this track. This avoids relying on AVPacket
5594 // duration, but only helps for this particular track, not
5595 // for the other ones that are flushed at the same time.
5596 trk->track_duration = pkt->dts - trk->start_dts;
5597 if (pkt->pts != AV_NOPTS_VALUE)
5598 trk->end_pts = pkt->pts;
5600 trk->end_pts = pkt->dts;
5601 trk->end_reliable = 1;
5602 mov_auto_flush_fragment(s, 0);
5606 return ff_mov_write_packet(s, pkt);
5609 static int mov_write_subtitle_end_packet(AVFormatContext *s,
5613 uint8_t data[2] = {0};
5616 av_init_packet(&end);
5617 end.size = sizeof(data);
5622 end.stream_index = stream_index;
5624 ret = mov_write_single_packet(s, &end);
5625 av_packet_unref(&end);
5630 static int mov_write_packet(AVFormatContext *s, AVPacket *pkt)
5632 MOVMuxContext *mov = s->priv_data;
5636 mov_flush_fragment(s, 1);
5640 trk = &mov->tracks[pkt->stream_index];
5642 if (is_cover_image(trk->st)) {
5645 if (trk->st->nb_frames >= 1) {
5646 if (trk->st->nb_frames == 1)
5647 av_log(s, AV_LOG_WARNING, "Got more than one picture in stream %d,"
5648 " ignoring.\n", pkt->stream_index);
5652 if ((ret = av_packet_ref(&trk->cover_image, pkt)) < 0)
5660 return mov_write_single_packet(s, pkt); /* Passthrough. */
5663 * Subtitles require special handling.
5665 * 1) For full complaince, every track must have a sample at
5666 * dts == 0, which is rarely true for subtitles. So, as soon
5667 * as we see any packet with dts > 0, write an empty subtitle
5668 * at dts == 0 for any subtitle track with no samples in it.
5670 * 2) For each subtitle track, check if the current packet's
5671 * dts is past the duration of the last subtitle sample. If
5672 * so, we now need to write an end sample for that subtitle.
5674 * This must be done conditionally to allow for subtitles that
5675 * immediately replace each other, in which case an end sample
5676 * is not needed, and is, in fact, actively harmful.
5678 * 3) See mov_write_trailer for how the final end sample is
5681 for (i = 0; i < mov->nb_streams; i++) {
5682 MOVTrack *trk = &mov->tracks[i];
5685 if (trk->par->codec_id == AV_CODEC_ID_MOV_TEXT &&
5686 trk->track_duration < pkt->dts &&
5687 (trk->entry == 0 || !trk->last_sample_is_subtitle_end)) {
5688 ret = mov_write_subtitle_end_packet(s, i, trk->track_duration);
5689 if (ret < 0) return ret;
5690 trk->last_sample_is_subtitle_end = 1;
5694 if (trk->mode == MODE_MOV && trk->par->codec_type == AVMEDIA_TYPE_VIDEO) {
5695 AVPacket *opkt = pkt;
5696 int reshuffle_ret, ret;
5697 if (trk->is_unaligned_qt_rgb) {
5698 int64_t bpc = trk->par->bits_per_coded_sample != 15 ? trk->par->bits_per_coded_sample : 16;
5699 int expected_stride = ((trk->par->width * bpc + 15) >> 4)*2;
5700 reshuffle_ret = ff_reshuffle_raw_rgb(s, &pkt, trk->par, expected_stride);
5701 if (reshuffle_ret < 0)
5702 return reshuffle_ret;
5705 if (trk->par->format == AV_PIX_FMT_PAL8 && !trk->pal_done) {
5706 ret = ff_get_packet_palette(s, opkt, reshuffle_ret, trk->palette);
5711 } else if (trk->par->codec_id == AV_CODEC_ID_RAWVIDEO &&
5712 (trk->par->format == AV_PIX_FMT_GRAY8 ||
5713 trk->par->format == AV_PIX_FMT_MONOBLACK)) {
5714 for (i = 0; i < pkt->size; i++)
5715 pkt->data[i] = ~pkt->data[i];
5717 if (reshuffle_ret) {
5718 ret = mov_write_single_packet(s, pkt);
5721 av_packet_free(&pkt);
5726 return mov_write_single_packet(s, pkt);
5730 // QuickTime chapters involve an additional text track with the chapter names
5731 // as samples, and a tref pointing from the other tracks to the chapter one.
5732 static int mov_create_chapter_track(AVFormatContext *s, int tracknum)
5736 MOVMuxContext *mov = s->priv_data;
5737 MOVTrack *track = &mov->tracks[tracknum];
5738 AVPacket pkt = { .stream_index = tracknum, .flags = AV_PKT_FLAG_KEY };
5741 track->mode = mov->mode;
5742 track->tag = MKTAG('t','e','x','t');
5743 track->timescale = MOV_TIMESCALE;
5744 track->par = avcodec_parameters_alloc();
5746 return AVERROR(ENOMEM);
5747 track->par->codec_type = AVMEDIA_TYPE_SUBTITLE;
5749 // These properties are required to make QT recognize the chapter track
5750 uint8_t chapter_properties[43] = { 0, 0, 0, 0, 0, 0, 0, 1, };
5751 if (ff_alloc_extradata(track->par, sizeof(chapter_properties)))
5752 return AVERROR(ENOMEM);
5753 memcpy(track->par->extradata, chapter_properties, sizeof(chapter_properties));
5755 if (avio_open_dyn_buf(&pb) >= 0) {
5759 /* Stub header (usually for Quicktime chapter track) */
5761 avio_wb32(pb, 0x01); // displayFlags
5762 avio_w8(pb, 0x00); // horizontal justification
5763 avio_w8(pb, 0x00); // vertical justification
5764 avio_w8(pb, 0x00); // bgColourRed
5765 avio_w8(pb, 0x00); // bgColourGreen
5766 avio_w8(pb, 0x00); // bgColourBlue
5767 avio_w8(pb, 0x00); // bgColourAlpha
5769 avio_wb16(pb, 0x00); // defTextBoxTop
5770 avio_wb16(pb, 0x00); // defTextBoxLeft
5771 avio_wb16(pb, 0x00); // defTextBoxBottom
5772 avio_wb16(pb, 0x00); // defTextBoxRight
5774 avio_wb16(pb, 0x00); // startChar
5775 avio_wb16(pb, 0x00); // endChar
5776 avio_wb16(pb, 0x01); // fontID
5777 avio_w8(pb, 0x00); // fontStyleFlags
5778 avio_w8(pb, 0x00); // fontSize
5779 avio_w8(pb, 0x00); // fgColourRed
5780 avio_w8(pb, 0x00); // fgColourGreen
5781 avio_w8(pb, 0x00); // fgColourBlue
5782 avio_w8(pb, 0x00); // fgColourAlpha
5784 avio_wb32(pb, 0x0D); // box size
5785 ffio_wfourcc(pb, "ftab"); // box atom name
5786 avio_wb16(pb, 0x01); // entry count
5788 avio_wb16(pb, 0x01); // font ID
5789 avio_w8(pb, 0x00); // font name length
5791 if ((size = avio_close_dyn_buf(pb, &buf)) > 0) {
5792 track->par->extradata = buf;
5793 track->par->extradata_size = size;
5800 for (i = 0; i < s->nb_chapters; i++) {
5801 AVChapter *c = s->chapters[i];
5802 AVDictionaryEntry *t;
5804 int64_t end = av_rescale_q(c->end, c->time_base, (AVRational){1,MOV_TIMESCALE});
5805 pkt.pts = pkt.dts = av_rescale_q(c->start, c->time_base, (AVRational){1,MOV_TIMESCALE});
5806 pkt.duration = end - pkt.dts;
5808 if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
5809 static const char encd[12] = {
5810 0x00, 0x00, 0x00, 0x0C,
5812 0x00, 0x00, 0x01, 0x00 };
5813 len = strlen(t->value);
5814 pkt.size = len + 2 + 12;
5815 pkt.data = av_malloc(pkt.size);
5817 return AVERROR(ENOMEM);
5818 AV_WB16(pkt.data, len);
5819 memcpy(pkt.data + 2, t->value, len);
5820 memcpy(pkt.data + len + 2, encd, sizeof(encd));
5821 ff_mov_write_packet(s, &pkt);
5822 av_freep(&pkt.data);
5830 static int mov_check_timecode_track(AVFormatContext *s, AVTimecode *tc, int src_index, const char *tcstr)
5834 /* compute the frame number */
5835 ret = av_timecode_init_from_string(tc, find_fps(s, s->streams[src_index]), tcstr, s);
5839 static int mov_create_timecode_track(AVFormatContext *s, int index, int src_index, AVTimecode tc)
5842 MOVMuxContext *mov = s->priv_data;
5843 MOVTrack *track = &mov->tracks[index];
5844 AVStream *src_st = s->streams[src_index];
5845 AVPacket pkt = {.stream_index = index, .flags = AV_PKT_FLAG_KEY, .size = 4};
5846 AVRational rate = find_fps(s, src_st);
5848 /* tmcd track based on video stream */
5849 track->mode = mov->mode;
5850 track->tag = MKTAG('t','m','c','d');
5851 track->src_track = src_index;
5852 track->timescale = mov->tracks[src_index].timescale;
5853 if (tc.flags & AV_TIMECODE_FLAG_DROPFRAME)
5854 track->timecode_flags |= MOV_TIMECODE_FLAG_DROPFRAME;
5856 /* set st to src_st for metadata access*/
5859 /* encode context: tmcd data stream */
5860 track->par = avcodec_parameters_alloc();
5862 return AVERROR(ENOMEM);
5863 track->par->codec_type = AVMEDIA_TYPE_DATA;
5864 track->par->codec_tag = track->tag;
5865 track->st->avg_frame_rate = av_inv_q(rate);
5867 /* the tmcd track just contains one packet with the frame number */
5868 pkt.data = av_malloc(pkt.size);
5870 return AVERROR(ENOMEM);
5871 AV_WB32(pkt.data, tc.start);
5872 ret = ff_mov_write_packet(s, &pkt);
5878 * st->disposition controls the "enabled" flag in the tkhd tag.
5879 * QuickTime will not play a track if it is not enabled. So make sure
5880 * that one track of each type (audio, video, subtitle) is enabled.
5882 * Subtitles are special. For audio and video, setting "enabled" also
5883 * makes the track "default" (i.e. it is rendered when played). For
5884 * subtitles, an "enabled" subtitle is not rendered by default, but
5885 * if no subtitle is enabled, the subtitle menu in QuickTime will be
5888 static void enable_tracks(AVFormatContext *s)
5890 MOVMuxContext *mov = s->priv_data;
5892 int enabled[AVMEDIA_TYPE_NB];
5893 int first[AVMEDIA_TYPE_NB];
5895 for (i = 0; i < AVMEDIA_TYPE_NB; i++) {
5900 for (i = 0; i < s->nb_streams; i++) {
5901 AVStream *st = s->streams[i];
5903 if (st->codecpar->codec_type <= AVMEDIA_TYPE_UNKNOWN ||
5904 st->codecpar->codec_type >= AVMEDIA_TYPE_NB ||
5908 if (first[st->codecpar->codec_type] < 0)
5909 first[st->codecpar->codec_type] = i;
5910 if (st->disposition & AV_DISPOSITION_DEFAULT) {
5911 mov->tracks[i].flags |= MOV_TRACK_ENABLED;
5912 enabled[st->codecpar->codec_type]++;
5916 for (i = 0; i < AVMEDIA_TYPE_NB; i++) {
5918 case AVMEDIA_TYPE_VIDEO:
5919 case AVMEDIA_TYPE_AUDIO:
5920 case AVMEDIA_TYPE_SUBTITLE:
5922 mov->per_stream_grouping = 1;
5923 if (!enabled[i] && first[i] >= 0)
5924 mov->tracks[first[i]].flags |= MOV_TRACK_ENABLED;
5930 static void mov_free(AVFormatContext *s)
5932 MOVMuxContext *mov = s->priv_data;
5935 if (mov->chapter_track) {
5936 if (mov->tracks[mov->chapter_track].par)
5937 av_freep(&mov->tracks[mov->chapter_track].par->extradata);
5938 av_freep(&mov->tracks[mov->chapter_track].par);
5941 for (i = 0; i < mov->nb_streams; i++) {
5942 if (mov->tracks[i].tag == MKTAG('r','t','p',' '))
5943 ff_mov_close_hinting(&mov->tracks[i]);
5944 else if (mov->tracks[i].tag == MKTAG('t','m','c','d') && mov->nb_meta_tmcd)
5945 av_freep(&mov->tracks[i].par);
5946 av_freep(&mov->tracks[i].cluster);
5947 av_freep(&mov->tracks[i].frag_info);
5948 av_packet_unref(&mov->tracks[i].cover_image);
5950 if (mov->tracks[i].vos_len)
5951 av_freep(&mov->tracks[i].vos_data);
5953 ff_mov_cenc_free(&mov->tracks[i].cenc);
5956 av_freep(&mov->tracks);
5959 static uint32_t rgb_to_yuv(uint32_t rgb)
5964 r = (rgb >> 16) & 0xFF;
5965 g = (rgb >> 8) & 0xFF;
5968 y = av_clip_uint8(( 16000 + 257 * r + 504 * g + 98 * b)/1000);
5969 cb = av_clip_uint8((128000 - 148 * r - 291 * g + 439 * b)/1000);
5970 cr = av_clip_uint8((128000 + 439 * r - 368 * g - 71 * b)/1000);
5972 return (y << 16) | (cr << 8) | cb;
5975 static int mov_create_dvd_sub_decoder_specific_info(MOVTrack *track,
5978 int i, width = 720, height = 480;
5979 int have_palette = 0, have_size = 0;
5980 uint32_t palette[16];
5981 char *cur = st->codecpar->extradata;
5983 while (cur && *cur) {
5984 if (strncmp("palette:", cur, 8) == 0) {
5986 count = sscanf(cur + 8,
5987 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
5988 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
5989 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
5990 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32"",
5991 &palette[ 0], &palette[ 1], &palette[ 2], &palette[ 3],
5992 &palette[ 4], &palette[ 5], &palette[ 6], &palette[ 7],
5993 &palette[ 8], &palette[ 9], &palette[10], &palette[11],
5994 &palette[12], &palette[13], &palette[14], &palette[15]);
5996 for (i = 0; i < count; i++) {
5997 palette[i] = rgb_to_yuv(palette[i]);
6000 } else if (!strncmp("size:", cur, 5)) {
6001 sscanf(cur + 5, "%dx%d", &width, &height);
6004 if (have_palette && have_size)
6006 cur += strcspn(cur, "\n\r");
6007 cur += strspn(cur, "\n\r");
6010 track->vos_data = av_malloc(16*4);
6011 if (!track->vos_data)
6012 return AVERROR(ENOMEM);
6013 for (i = 0; i < 16; i++) {
6014 AV_WB32(track->vos_data + i * 4, palette[i]);
6016 track->vos_len = 16 * 4;
6018 st->codecpar->width = width;
6019 st->codecpar->height = track->height = height;
6024 static int mov_init(AVFormatContext *s)
6026 MOVMuxContext *mov = s->priv_data;
6027 AVDictionaryEntry *global_tcr = av_dict_get(s->metadata, "timecode", NULL, 0);
6032 /* Default mode == MP4 */
6033 mov->mode = MODE_MP4;
6036 if (!strcmp("3gp", s->oformat->name)) mov->mode = MODE_3GP;
6037 else if (!strcmp("3g2", s->oformat->name)) mov->mode = MODE_3GP|MODE_3G2;
6038 else if (!strcmp("mov", s->oformat->name)) mov->mode = MODE_MOV;
6039 else if (!strcmp("psp", s->oformat->name)) mov->mode = MODE_PSP;
6040 else if (!strcmp("ipod",s->oformat->name)) mov->mode = MODE_IPOD;
6041 else if (!strcmp("ismv",s->oformat->name)) mov->mode = MODE_ISM;
6042 else if (!strcmp("f4v", s->oformat->name)) mov->mode = MODE_F4V;
6045 if (mov->flags & FF_MOV_FLAG_DELAY_MOOV)
6046 mov->flags |= FF_MOV_FLAG_EMPTY_MOOV;
6048 /* Set the FRAGMENT flag if any of the fragmentation methods are
6050 if (mov->max_fragment_duration || mov->max_fragment_size ||
6051 mov->flags & (FF_MOV_FLAG_EMPTY_MOOV |
6052 FF_MOV_FLAG_FRAG_KEYFRAME |
6053 FF_MOV_FLAG_FRAG_CUSTOM |
6054 FF_MOV_FLAG_FRAG_EVERY_FRAME))
6055 mov->flags |= FF_MOV_FLAG_FRAGMENT;
6057 /* Set other implicit flags immediately */
6058 if (mov->mode == MODE_ISM)
6059 mov->flags |= FF_MOV_FLAG_EMPTY_MOOV | FF_MOV_FLAG_SEPARATE_MOOF |
6060 FF_MOV_FLAG_FRAGMENT | FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS;
6061 if (mov->flags & FF_MOV_FLAG_DASH)
6062 mov->flags |= FF_MOV_FLAG_FRAGMENT | FF_MOV_FLAG_EMPTY_MOOV |
6063 FF_MOV_FLAG_DEFAULT_BASE_MOOF;
6065 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV && s->flags & AVFMT_FLAG_AUTO_BSF) {
6066 av_log(s, AV_LOG_VERBOSE, "Empty MOOV enabled; disabling automatic bitstream filtering\n");
6067 s->flags &= ~AVFMT_FLAG_AUTO_BSF;
6070 if (mov->flags & FF_MOV_FLAG_FASTSTART) {
6071 mov->reserved_moov_size = -1;
6074 if (mov->use_editlist < 0) {
6075 mov->use_editlist = 1;
6076 if (mov->flags & FF_MOV_FLAG_FRAGMENT &&
6077 !(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
6078 // If we can avoid needing an edit list by shifting the
6079 // tracks, prefer that over (trying to) write edit lists
6080 // in fragmented output.
6081 if (s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO ||
6082 s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO)
6083 mov->use_editlist = 0;
6086 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV &&
6087 !(mov->flags & FF_MOV_FLAG_DELAY_MOOV) && mov->use_editlist)
6088 av_log(s, AV_LOG_WARNING, "No meaningful edit list will be written when using empty_moov without delay_moov\n");
6090 if (!mov->use_editlist && s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO)
6091 s->avoid_negative_ts = AVFMT_AVOID_NEG_TS_MAKE_ZERO;
6093 /* Clear the omit_tfhd_offset flag if default_base_moof is set;
6094 * if the latter is set that's enough and omit_tfhd_offset doesn't
6095 * add anything extra on top of that. */
6096 if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET &&
6097 mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)
6098 mov->flags &= ~FF_MOV_FLAG_OMIT_TFHD_OFFSET;
6100 if (mov->frag_interleave &&
6101 mov->flags & (FF_MOV_FLAG_OMIT_TFHD_OFFSET | FF_MOV_FLAG_SEPARATE_MOOF)) {
6102 av_log(s, AV_LOG_ERROR,
6103 "Sample interleaving in fragments is mutually exclusive with "
6104 "omit_tfhd_offset and separate_moof\n");
6105 return AVERROR(EINVAL);
6108 /* Non-seekable output is ok if using fragmentation. If ism_lookahead
6109 * is enabled, we don't support non-seekable output at all. */
6110 if (!(s->pb->seekable & AVIO_SEEKABLE_NORMAL) &&
6111 (!(mov->flags & FF_MOV_FLAG_FRAGMENT) || mov->ism_lookahead)) {
6112 av_log(s, AV_LOG_ERROR, "muxer does not support non seekable output\n");
6113 return AVERROR(EINVAL);
6116 mov->nb_streams = s->nb_streams;
6117 if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters)
6118 mov->chapter_track = mov->nb_streams++;
6120 if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
6121 for (i = 0; i < s->nb_streams; i++)
6122 if (rtp_hinting_needed(s->streams[i]))
6126 if ( mov->write_tmcd == -1 && (mov->mode == MODE_MOV || mov->mode == MODE_MP4)
6127 || mov->write_tmcd == 1) {
6128 /* +1 tmcd track for each video stream with a timecode */
6129 for (i = 0; i < s->nb_streams; i++) {
6130 AVStream *st = s->streams[i];
6131 AVDictionaryEntry *t = global_tcr;
6132 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
6133 (t || (t=av_dict_get(st->metadata, "timecode", NULL, 0)))) {
6135 ret = mov_check_timecode_track(s, &tc, i, t->value);
6137 mov->nb_meta_tmcd++;
6141 /* check if there is already a tmcd track to remux */
6142 if (mov->nb_meta_tmcd) {
6143 for (i = 0; i < s->nb_streams; i++) {
6144 AVStream *st = s->streams[i];
6145 if (st->codecpar->codec_tag == MKTAG('t','m','c','d')) {
6146 av_log(s, AV_LOG_WARNING, "You requested a copy of the original timecode track "
6147 "so timecode metadata are now ignored\n");
6148 mov->nb_meta_tmcd = 0;
6153 mov->nb_streams += mov->nb_meta_tmcd;
6156 // Reserve an extra stream for chapters for the case where chapters
6157 // are written in the trailer
6158 mov->tracks = av_mallocz_array((mov->nb_streams + 1), sizeof(*mov->tracks));
6160 return AVERROR(ENOMEM);
6162 if (mov->encryption_scheme_str != NULL && strcmp(mov->encryption_scheme_str, "none") != 0) {
6163 if (strcmp(mov->encryption_scheme_str, "cenc-aes-ctr") == 0) {
6164 mov->encryption_scheme = MOV_ENC_CENC_AES_CTR;
6166 if (mov->encryption_key_len != AES_CTR_KEY_SIZE) {
6167 av_log(s, AV_LOG_ERROR, "Invalid encryption key len %d expected %d\n",
6168 mov->encryption_key_len, AES_CTR_KEY_SIZE);
6169 return AVERROR(EINVAL);
6172 if (mov->encryption_kid_len != CENC_KID_SIZE) {
6173 av_log(s, AV_LOG_ERROR, "Invalid encryption kid len %d expected %d\n",
6174 mov->encryption_kid_len, CENC_KID_SIZE);
6175 return AVERROR(EINVAL);
6178 av_log(s, AV_LOG_ERROR, "unsupported encryption scheme %s\n",
6179 mov->encryption_scheme_str);
6180 return AVERROR(EINVAL);
6184 for (i = 0; i < s->nb_streams; i++) {
6185 AVStream *st= s->streams[i];
6186 MOVTrack *track= &mov->tracks[i];
6187 AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0);
6190 track->par = st->codecpar;
6191 track->language = ff_mov_iso639_to_lang(lang?lang->value:"und", mov->mode!=MODE_MOV);
6192 if (track->language < 0)
6193 track->language = 0;
6194 track->mode = mov->mode;
6195 track->tag = mov_find_codec_tag(s, track);
6197 av_log(s, AV_LOG_ERROR, "Could not find tag for codec %s in stream #%d, "
6198 "codec not currently supported in container\n",
6199 avcodec_get_name(st->codecpar->codec_id), i);
6200 return AVERROR(EINVAL);
6202 /* If hinting of this track is enabled by a later hint track,
6203 * this is updated. */
6204 track->hint_track = -1;
6205 track->start_dts = AV_NOPTS_VALUE;
6206 track->start_cts = AV_NOPTS_VALUE;
6207 track->end_pts = AV_NOPTS_VALUE;
6208 track->dts_shift = AV_NOPTS_VALUE;
6209 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
6210 if (track->tag == MKTAG('m','x','3','p') || track->tag == MKTAG('m','x','3','n') ||
6211 track->tag == MKTAG('m','x','4','p') || track->tag == MKTAG('m','x','4','n') ||
6212 track->tag == MKTAG('m','x','5','p') || track->tag == MKTAG('m','x','5','n')) {
6213 if (st->codecpar->width != 720 || (st->codecpar->height != 608 && st->codecpar->height != 512)) {
6214 av_log(s, AV_LOG_ERROR, "D-10/IMX must use 720x608 or 720x512 video resolution\n");
6215 return AVERROR(EINVAL);
6217 track->height = track->tag >> 24 == 'n' ? 486 : 576;
6219 if (mov->video_track_timescale) {
6220 track->timescale = mov->video_track_timescale;
6222 track->timescale = st->time_base.den;
6223 while(track->timescale < 10000)
6224 track->timescale *= 2;
6226 if (st->codecpar->width > 65535 || st->codecpar->height > 65535) {
6227 av_log(s, AV_LOG_ERROR, "Resolution %dx%d too large for mov/mp4\n", st->codecpar->width, st->codecpar->height);
6228 return AVERROR(EINVAL);
6230 if (track->mode == MODE_MOV && track->timescale > 100000)
6231 av_log(s, AV_LOG_WARNING,
6232 "WARNING codec timebase is very high. If duration is too long,\n"
6233 "file may not be playable by quicktime. Specify a shorter timebase\n"
6234 "or choose different container.\n");
6235 if (track->mode == MODE_MOV &&
6236 track->par->codec_id == AV_CODEC_ID_RAWVIDEO &&
6237 track->tag == MKTAG('r','a','w',' ')) {
6238 enum AVPixelFormat pix_fmt = track->par->format;
6239 if (pix_fmt == AV_PIX_FMT_NONE && track->par->bits_per_coded_sample == 1)
6240 pix_fmt = AV_PIX_FMT_MONOWHITE;
6241 track->is_unaligned_qt_rgb =
6242 pix_fmt == AV_PIX_FMT_RGB24 ||
6243 pix_fmt == AV_PIX_FMT_BGR24 ||
6244 pix_fmt == AV_PIX_FMT_PAL8 ||
6245 pix_fmt == AV_PIX_FMT_GRAY8 ||
6246 pix_fmt == AV_PIX_FMT_MONOWHITE ||
6247 pix_fmt == AV_PIX_FMT_MONOBLACK;
6249 if (track->par->codec_id == AV_CODEC_ID_VP9 ||
6250 track->par->codec_id == AV_CODEC_ID_AV1) {
6251 if (track->mode != MODE_MP4) {
6252 av_log(s, AV_LOG_ERROR, "%s only supported in MP4.\n", avcodec_get_name(track->par->codec_id));
6253 return AVERROR(EINVAL);
6255 } else if (track->par->codec_id == AV_CODEC_ID_VP8) {
6256 /* altref frames handling is not defined in the spec as of version v1.0,
6257 * so just forbid muxing VP8 streams altogether until a new version does */
6258 av_log(s, AV_LOG_ERROR, "VP8 muxing is currently not supported.\n");
6259 return AVERROR_PATCHWELCOME;
6261 } else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
6262 track->timescale = st->codecpar->sample_rate;
6263 if (!st->codecpar->frame_size && !av_get_bits_per_sample(st->codecpar->codec_id)) {
6264 av_log(s, AV_LOG_WARNING, "track %d: codec frame size is not set\n", i);
6265 track->audio_vbr = 1;
6266 }else if (st->codecpar->codec_id == AV_CODEC_ID_ADPCM_MS ||
6267 st->codecpar->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
6268 st->codecpar->codec_id == AV_CODEC_ID_ILBC){
6269 if (!st->codecpar->block_align) {
6270 av_log(s, AV_LOG_ERROR, "track %d: codec block align is not set for adpcm\n", i);
6271 return AVERROR(EINVAL);
6273 track->sample_size = st->codecpar->block_align;
6274 }else if (st->codecpar->frame_size > 1){ /* assume compressed audio */
6275 track->audio_vbr = 1;
6277 track->sample_size = (av_get_bits_per_sample(st->codecpar->codec_id) >> 3) * st->codecpar->channels;
6279 if (st->codecpar->codec_id == AV_CODEC_ID_ILBC ||
6280 st->codecpar->codec_id == AV_CODEC_ID_ADPCM_IMA_QT) {
6281 track->audio_vbr = 1;
6283 if (track->mode != MODE_MOV &&
6284 track->par->codec_id == AV_CODEC_ID_MP3 && track->timescale < 16000) {
6285 if (s->strict_std_compliance >= FF_COMPLIANCE_NORMAL) {
6286 av_log(s, AV_LOG_ERROR, "track %d: muxing mp3 at %dhz is not standard, to mux anyway set strict to -1\n",
6287 i, track->par->sample_rate);
6288 return AVERROR(EINVAL);
6290 av_log(s, AV_LOG_WARNING, "track %d: muxing mp3 at %dhz is not standard in MP4\n",
6291 i, track->par->sample_rate);
6294 if (track->par->codec_id == AV_CODEC_ID_FLAC ||
6295 track->par->codec_id == AV_CODEC_ID_OPUS) {
6296 if (track->mode != MODE_MP4) {
6297 av_log(s, AV_LOG_ERROR, "%s only supported in MP4.\n", avcodec_get_name(track->par->codec_id));
6298 return AVERROR(EINVAL);
6300 if (s->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
6301 av_log(s, AV_LOG_ERROR,
6302 "%s in MP4 support is experimental, add "
6303 "'-strict %d' if you want to use it.\n",
6304 avcodec_get_name(track->par->codec_id), FF_COMPLIANCE_EXPERIMENTAL);
6305 return AVERROR_EXPERIMENTAL;
6308 } else if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) {
6309 track->timescale = st->time_base.den;
6310 } else if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA) {
6311 track->timescale = st->time_base.den;
6313 track->timescale = MOV_TIMESCALE;
6316 track->height = st->codecpar->height;
6317 /* The ism specific timescale isn't mandatory, but is assumed by
6318 * some tools, such as mp4split. */
6319 if (mov->mode == MODE_ISM)
6320 track->timescale = 10000000;
6322 avpriv_set_pts_info(st, 64, 1, track->timescale);
6324 if (mov->encryption_scheme == MOV_ENC_CENC_AES_CTR) {
6325 ret = ff_mov_cenc_init(&track->cenc, mov->encryption_key,
6326 track->par->codec_id == AV_CODEC_ID_H264, s->flags & AVFMT_FLAG_BITEXACT);
6336 static int mov_write_header(AVFormatContext *s)
6338 AVIOContext *pb = s->pb;
6339 MOVMuxContext *mov = s->priv_data;
6340 AVDictionaryEntry *t, *global_tcr = av_dict_get(s->metadata, "timecode", NULL, 0);
6341 int i, ret, hint_track = 0, tmcd_track = 0, nb_tracks = s->nb_streams;
6343 if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters)
6346 if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
6347 hint_track = nb_tracks;
6348 for (i = 0; i < s->nb_streams; i++)
6349 if (rtp_hinting_needed(s->streams[i]))
6353 if (mov->mode == MODE_MOV || mov->mode == MODE_MP4)
6354 tmcd_track = nb_tracks;
6356 for (i = 0; i < s->nb_streams; i++) {
6358 AVStream *st= s->streams[i];
6359 MOVTrack *track= &mov->tracks[i];
6361 /* copy extradata if it exists */
6362 if (st->codecpar->extradata_size) {
6363 if (st->codecpar->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
6364 mov_create_dvd_sub_decoder_specific_info(track, st);
6365 else if (!TAG_IS_AVCI(track->tag) && st->codecpar->codec_id != AV_CODEC_ID_DNXHD) {
6366 track->vos_len = st->codecpar->extradata_size;
6367 track->vos_data = av_malloc(track->vos_len);
6368 if (!track->vos_data) {
6369 return AVERROR(ENOMEM);
6371 memcpy(track->vos_data, st->codecpar->extradata, track->vos_len);
6375 if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ||
6376 track->par->channel_layout != AV_CH_LAYOUT_MONO)
6379 for (j = 0; j < s->nb_streams; j++) {
6380 AVStream *stj= s->streams[j];
6381 MOVTrack *trackj= &mov->tracks[j];
6385 if (stj->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ||
6386 trackj->par->channel_layout != AV_CH_LAYOUT_MONO ||
6387 trackj->language != track->language ||
6388 trackj->tag != track->tag
6391 track->multichannel_as_mono++;
6395 if (!(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
6396 if ((ret = mov_write_identification(pb, s)) < 0)
6400 if (mov->reserved_moov_size){
6401 mov->reserved_header_pos = avio_tell(pb);
6402 if (mov->reserved_moov_size > 0)
6403 avio_skip(pb, mov->reserved_moov_size);
6406 if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
6407 /* If no fragmentation options have been set, set a default. */
6408 if (!(mov->flags & (FF_MOV_FLAG_FRAG_KEYFRAME |
6409 FF_MOV_FLAG_FRAG_CUSTOM |
6410 FF_MOV_FLAG_FRAG_EVERY_FRAME)) &&
6411 !mov->max_fragment_duration && !mov->max_fragment_size)
6412 mov->flags |= FF_MOV_FLAG_FRAG_KEYFRAME;
6414 if (mov->flags & FF_MOV_FLAG_FASTSTART)
6415 mov->reserved_header_pos = avio_tell(pb);
6416 mov_write_mdat_tag(pb, mov);
6419 ff_parse_creation_time_metadata(s, &mov->time, 1);
6421 mov->time += 0x7C25B080; // 1970 based -> 1904 based
6423 if (mov->chapter_track)
6424 if ((ret = mov_create_chapter_track(s, mov->chapter_track)) < 0)
6427 if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
6428 for (i = 0; i < s->nb_streams; i++) {
6429 if (rtp_hinting_needed(s->streams[i])) {
6430 if ((ret = ff_mov_init_hinting(s, hint_track, i)) < 0)
6437 if (mov->nb_meta_tmcd) {
6438 /* Initialize the tmcd tracks */
6439 for (i = 0; i < s->nb_streams; i++) {
6440 AVStream *st = s->streams[i];
6443 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
6446 t = av_dict_get(st->metadata, "timecode", NULL, 0);
6449 if (mov_check_timecode_track(s, &tc, i, t->value) < 0)
6451 if ((ret = mov_create_timecode_track(s, tmcd_track, i, tc)) < 0)
6460 if (mov->flags & FF_MOV_FLAG_ISML)
6461 mov_write_isml_manifest(pb, mov, s);
6463 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV &&
6464 !(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
6465 if ((ret = mov_write_moov_tag(pb, mov, s)) < 0)
6468 mov->moov_written = 1;
6469 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
6470 mov->reserved_header_pos = avio_tell(pb);
6476 static int get_moov_size(AVFormatContext *s)
6479 AVIOContext *moov_buf;
6480 MOVMuxContext *mov = s->priv_data;
6482 if ((ret = ffio_open_null_buf(&moov_buf)) < 0)
6484 if ((ret = mov_write_moov_tag(moov_buf, mov, s)) < 0)
6486 return ffio_close_null_buf(moov_buf);
6489 static int get_sidx_size(AVFormatContext *s)
6493 MOVMuxContext *mov = s->priv_data;
6495 if ((ret = ffio_open_null_buf(&buf)) < 0)
6497 mov_write_sidx_tags(buf, mov, -1, 0);
6498 return ffio_close_null_buf(buf);
6502 * This function gets the moov size if moved to the top of the file: the chunk
6503 * offset table can switch between stco (32-bit entries) to co64 (64-bit
6504 * entries) when the moov is moved to the beginning, so the size of the moov
6505 * would change. It also updates the chunk offset tables.
6507 static int compute_moov_size(AVFormatContext *s)
6509 int i, moov_size, moov_size2;
6510 MOVMuxContext *mov = s->priv_data;
6512 moov_size = get_moov_size(s);
6516 for (i = 0; i < mov->nb_streams; i++)
6517 mov->tracks[i].data_offset += moov_size;
6519 moov_size2 = get_moov_size(s);
6523 /* if the size changed, we just switched from stco to co64 and need to
6524 * update the offsets */
6525 if (moov_size2 != moov_size)
6526 for (i = 0; i < mov->nb_streams; i++)
6527 mov->tracks[i].data_offset += moov_size2 - moov_size;
6532 static int compute_sidx_size(AVFormatContext *s)
6535 MOVMuxContext *mov = s->priv_data;
6537 sidx_size = get_sidx_size(s);
6541 for (i = 0; i < mov->nb_streams; i++)
6542 mov->tracks[i].data_offset += sidx_size;
6547 static int shift_data(AVFormatContext *s)
6549 int ret = 0, moov_size;
6550 MOVMuxContext *mov = s->priv_data;
6551 int64_t pos, pos_end = avio_tell(s->pb);
6552 uint8_t *buf, *read_buf[2];
6553 int read_buf_id = 0;
6555 AVIOContext *read_pb;
6557 if (mov->flags & FF_MOV_FLAG_FRAGMENT)
6558 moov_size = compute_sidx_size(s);
6560 moov_size = compute_moov_size(s);
6564 buf = av_malloc(moov_size * 2);
6566 return AVERROR(ENOMEM);
6568 read_buf[1] = buf + moov_size;
6570 /* Shift the data: the AVIO context of the output can only be used for
6571 * writing, so we re-open the same output, but for reading. It also avoids
6572 * a read/seek/write/seek back and forth. */
6574 ret = s->io_open(s, &read_pb, s->url, AVIO_FLAG_READ, NULL);
6576 av_log(s, AV_LOG_ERROR, "Unable to re-open %s output file for "
6577 "the second pass (faststart)\n", s->url);
6581 /* mark the end of the shift to up to the last data we wrote, and get ready
6583 pos_end = avio_tell(s->pb);
6584 avio_seek(s->pb, mov->reserved_header_pos + moov_size, SEEK_SET);
6586 /* start reading at where the new moov will be placed */
6587 avio_seek(read_pb, mov->reserved_header_pos, SEEK_SET);
6588 pos = avio_tell(read_pb);
6590 #define READ_BLOCK do { \
6591 read_size[read_buf_id] = avio_read(read_pb, read_buf[read_buf_id], moov_size); \
6595 /* shift data by chunk of at most moov_size */
6600 n = read_size[read_buf_id];
6603 avio_write(s->pb, read_buf[read_buf_id], n);
6605 } while (pos < pos_end);
6606 ff_format_io_close(s, &read_pb);
6613 static int mov_write_trailer(AVFormatContext *s)
6615 MOVMuxContext *mov = s->priv_data;
6616 AVIOContext *pb = s->pb;
6621 if (mov->need_rewrite_extradata) {
6622 for (i = 0; i < s->nb_streams; i++) {
6623 MOVTrack *track = &mov->tracks[i];
6624 AVCodecParameters *par = track->par;
6626 track->vos_len = par->extradata_size;
6627 track->vos_data = av_malloc(track->vos_len);
6628 if (!track->vos_data)
6629 return AVERROR(ENOMEM);
6630 memcpy(track->vos_data, par->extradata, track->vos_len);
6632 mov->need_rewrite_extradata = 0;
6636 * Before actually writing the trailer, make sure that there are no
6637 * dangling subtitles, that need a terminating sample.
6639 for (i = 0; i < mov->nb_streams; i++) {
6640 MOVTrack *trk = &mov->tracks[i];
6641 if (trk->par->codec_id == AV_CODEC_ID_MOV_TEXT &&
6642 !trk->last_sample_is_subtitle_end) {
6643 mov_write_subtitle_end_packet(s, i, trk->track_duration);
6644 trk->last_sample_is_subtitle_end = 1;
6648 // If there were no chapters when the header was written, but there
6649 // are chapters now, write them in the trailer. This only works
6650 // when we are not doing fragments.
6651 if (!mov->chapter_track && !(mov->flags & FF_MOV_FLAG_FRAGMENT)) {
6652 if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters) {
6653 mov->chapter_track = mov->nb_streams++;
6654 if ((res = mov_create_chapter_track(s, mov->chapter_track)) < 0)
6659 if (!(mov->flags & FF_MOV_FLAG_FRAGMENT)) {
6660 moov_pos = avio_tell(pb);
6662 /* Write size of mdat tag */
6663 if (mov->mdat_size + 8 <= UINT32_MAX) {
6664 avio_seek(pb, mov->mdat_pos, SEEK_SET);
6665 avio_wb32(pb, mov->mdat_size + 8);
6667 /* overwrite 'wide' placeholder atom */
6668 avio_seek(pb, mov->mdat_pos - 8, SEEK_SET);
6669 /* special value: real atom size will be 64 bit value after
6672 ffio_wfourcc(pb, "mdat");
6673 avio_wb64(pb, mov->mdat_size + 16);
6675 avio_seek(pb, mov->reserved_moov_size > 0 ? mov->reserved_header_pos : moov_pos, SEEK_SET);
6677 if (mov->flags & FF_MOV_FLAG_FASTSTART) {
6678 av_log(s, AV_LOG_INFO, "Starting second pass: moving the moov atom to the beginning of the file\n");
6679 res = shift_data(s);
6682 avio_seek(pb, mov->reserved_header_pos, SEEK_SET);
6683 if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
6685 } else if (mov->reserved_moov_size > 0) {
6687 if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
6689 size = mov->reserved_moov_size - (avio_tell(pb) - mov->reserved_header_pos);
6691 av_log(s, AV_LOG_ERROR, "reserved_moov_size is too small, needed %"PRId64" additional\n", 8-size);
6692 return AVERROR(EINVAL);
6694 avio_wb32(pb, size);
6695 ffio_wfourcc(pb, "free");
6696 ffio_fill(pb, 0, size - 8);
6697 avio_seek(pb, moov_pos, SEEK_SET);
6699 if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
6704 mov_auto_flush_fragment(s, 1);
6705 for (i = 0; i < mov->nb_streams; i++)
6706 mov->tracks[i].data_offset = 0;
6707 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) {
6709 av_log(s, AV_LOG_INFO, "Starting second pass: inserting sidx atoms\n");
6710 res = shift_data(s);
6713 end = avio_tell(pb);
6714 avio_seek(pb, mov->reserved_header_pos, SEEK_SET);
6715 mov_write_sidx_tags(pb, mov, -1, 0);
6716 avio_seek(pb, end, SEEK_SET);
6717 avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_TRAILER);
6718 mov_write_mfra_tag(pb, mov);
6719 } else if (!(mov->flags & FF_MOV_FLAG_SKIP_TRAILER)) {
6720 avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_TRAILER);
6721 mov_write_mfra_tag(pb, mov);
6728 static int mov_check_bitstream(struct AVFormatContext *s, const AVPacket *pkt)
6731 AVStream *st = s->streams[pkt->stream_index];
6733 if (st->codecpar->codec_id == AV_CODEC_ID_AAC) {
6734 if (pkt->size > 2 && (AV_RB16(pkt->data) & 0xfff0) == 0xfff0)
6735 ret = ff_stream_add_bitstream_filter(st, "aac_adtstoasc", NULL);
6736 } else if (st->codecpar->codec_id == AV_CODEC_ID_VP9) {
6737 ret = ff_stream_add_bitstream_filter(st, "vp9_superframe", NULL);
6743 static const AVCodecTag codec_3gp_tags[] = {
6744 { AV_CODEC_ID_H263, MKTAG('s','2','6','3') },
6745 { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
6746 { AV_CODEC_ID_MPEG4, MKTAG('m','p','4','v') },
6747 { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
6748 { AV_CODEC_ID_AMR_NB, MKTAG('s','a','m','r') },
6749 { AV_CODEC_ID_AMR_WB, MKTAG('s','a','w','b') },
6750 { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
6751 { AV_CODEC_ID_NONE, 0 },
6754 const AVCodecTag codec_mp4_tags[] = {
6755 { AV_CODEC_ID_MPEG4 , MKTAG('m', 'p', '4', 'v') },
6756 { AV_CODEC_ID_H264 , MKTAG('a', 'v', 'c', '1') },
6757 { AV_CODEC_ID_H264 , MKTAG('a', 'v', 'c', '3') },
6758 { AV_CODEC_ID_HEVC , MKTAG('h', 'e', 'v', '1') },
6759 { AV_CODEC_ID_HEVC , MKTAG('h', 'v', 'c', '1') },
6760 { AV_CODEC_ID_MPEG2VIDEO , MKTAG('m', 'p', '4', 'v') },
6761 { AV_CODEC_ID_MPEG1VIDEO , MKTAG('m', 'p', '4', 'v') },
6762 { AV_CODEC_ID_MJPEG , MKTAG('m', 'p', '4', 'v') },
6763 { AV_CODEC_ID_PNG , MKTAG('m', 'p', '4', 'v') },
6764 { AV_CODEC_ID_JPEG2000 , MKTAG('m', 'p', '4', 'v') },
6765 { AV_CODEC_ID_VC1 , MKTAG('v', 'c', '-', '1') },
6766 { AV_CODEC_ID_DIRAC , MKTAG('d', 'r', 'a', 'c') },
6767 { AV_CODEC_ID_TSCC2 , MKTAG('m', 'p', '4', 'v') },
6768 { AV_CODEC_ID_VP9 , MKTAG('v', 'p', '0', '9') },
6769 { AV_CODEC_ID_AV1 , MKTAG('a', 'v', '0', '1') },
6770 { AV_CODEC_ID_AAC , MKTAG('m', 'p', '4', 'a') },
6771 { AV_CODEC_ID_MP4ALS , MKTAG('m', 'p', '4', 'a') },
6772 { AV_CODEC_ID_MP3 , MKTAG('m', 'p', '4', 'a') },
6773 { AV_CODEC_ID_MP2 , MKTAG('m', 'p', '4', 'a') },
6774 { AV_CODEC_ID_AC3 , MKTAG('a', 'c', '-', '3') },
6775 { AV_CODEC_ID_EAC3 , MKTAG('e', 'c', '-', '3') },
6776 { AV_CODEC_ID_DTS , MKTAG('m', 'p', '4', 'a') },
6777 { AV_CODEC_ID_FLAC , MKTAG('f', 'L', 'a', 'C') },
6778 { AV_CODEC_ID_OPUS , MKTAG('O', 'p', 'u', 's') },
6779 { AV_CODEC_ID_VORBIS , MKTAG('m', 'p', '4', 'a') },
6780 { AV_CODEC_ID_QCELP , MKTAG('m', 'p', '4', 'a') },
6781 { AV_CODEC_ID_EVRC , MKTAG('m', 'p', '4', 'a') },
6782 { AV_CODEC_ID_DVD_SUBTITLE, MKTAG('m', 'p', '4', 's') },
6783 { AV_CODEC_ID_MOV_TEXT , MKTAG('t', 'x', '3', 'g') },
6784 { AV_CODEC_ID_BIN_DATA , MKTAG('g', 'p', 'm', 'd') },
6785 { AV_CODEC_ID_NONE , 0 },
6788 const AVCodecTag codec_ism_tags[] = {
6789 { AV_CODEC_ID_WMAPRO , MKTAG('w', 'm', 'a', ' ') },
6790 { AV_CODEC_ID_NONE , 0 },
6793 static const AVCodecTag codec_ipod_tags[] = {
6794 { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
6795 { AV_CODEC_ID_MPEG4, MKTAG('m','p','4','v') },
6796 { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
6797 { AV_CODEC_ID_ALAC, MKTAG('a','l','a','c') },
6798 { AV_CODEC_ID_AC3, MKTAG('a','c','-','3') },
6799 { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
6800 { AV_CODEC_ID_MOV_TEXT, MKTAG('t','e','x','t') },
6801 { AV_CODEC_ID_NONE, 0 },
6804 static const AVCodecTag codec_f4v_tags[] = {
6805 { AV_CODEC_ID_MP3, MKTAG('.','m','p','3') },
6806 { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
6807 { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
6808 { AV_CODEC_ID_VP6A, MKTAG('V','P','6','A') },
6809 { AV_CODEC_ID_VP6F, MKTAG('V','P','6','F') },
6810 { AV_CODEC_ID_NONE, 0 },
6813 #if CONFIG_MOV_MUXER
6815 AVOutputFormat ff_mov_muxer = {
6817 .long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
6818 .extensions = "mov",
6819 .priv_data_size = sizeof(MOVMuxContext),
6820 .audio_codec = AV_CODEC_ID_AAC,
6821 .video_codec = CONFIG_LIBX264_ENCODER ?
6822 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
6824 .write_header = mov_write_header,
6825 .write_packet = mov_write_packet,
6826 .write_trailer = mov_write_trailer,
6828 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6829 .codec_tag = (const AVCodecTag* const []){
6830 ff_codec_movvideo_tags, ff_codec_movaudio_tags, 0
6832 .check_bitstream = mov_check_bitstream,
6833 .priv_class = &mov_muxer_class,
6836 #if CONFIG_TGP_MUXER
6838 AVOutputFormat ff_tgp_muxer = {
6840 .long_name = NULL_IF_CONFIG_SMALL("3GP (3GPP file format)"),
6841 .extensions = "3gp",
6842 .priv_data_size = sizeof(MOVMuxContext),
6843 .audio_codec = AV_CODEC_ID_AMR_NB,
6844 .video_codec = AV_CODEC_ID_H263,
6846 .write_header = mov_write_header,
6847 .write_packet = mov_write_packet,
6848 .write_trailer = mov_write_trailer,
6850 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6851 .codec_tag = (const AVCodecTag* const []){ codec_3gp_tags, 0 },
6852 .check_bitstream = mov_check_bitstream,
6853 .priv_class = &tgp_muxer_class,
6856 #if CONFIG_MP4_MUXER
6858 AVOutputFormat ff_mp4_muxer = {
6860 .long_name = NULL_IF_CONFIG_SMALL("MP4 (MPEG-4 Part 14)"),
6861 .mime_type = "video/mp4",
6862 .extensions = "mp4",
6863 .priv_data_size = sizeof(MOVMuxContext),
6864 .audio_codec = AV_CODEC_ID_AAC,
6865 .video_codec = CONFIG_LIBX264_ENCODER ?
6866 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
6868 .write_header = mov_write_header,
6869 .write_packet = mov_write_packet,
6870 .write_trailer = mov_write_trailer,
6872 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6873 .codec_tag = (const AVCodecTag* const []){ codec_mp4_tags, 0 },
6874 .check_bitstream = mov_check_bitstream,
6875 .priv_class = &mp4_muxer_class,
6878 #if CONFIG_PSP_MUXER
6880 AVOutputFormat ff_psp_muxer = {
6882 .long_name = NULL_IF_CONFIG_SMALL("PSP MP4 (MPEG-4 Part 14)"),
6883 .extensions = "mp4,psp",
6884 .priv_data_size = sizeof(MOVMuxContext),
6885 .audio_codec = AV_CODEC_ID_AAC,
6886 .video_codec = CONFIG_LIBX264_ENCODER ?
6887 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
6889 .write_header = mov_write_header,
6890 .write_packet = mov_write_packet,
6891 .write_trailer = mov_write_trailer,
6893 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6894 .codec_tag = (const AVCodecTag* const []){ codec_mp4_tags, 0 },
6895 .check_bitstream = mov_check_bitstream,
6896 .priv_class = &psp_muxer_class,
6899 #if CONFIG_TG2_MUXER
6901 AVOutputFormat ff_tg2_muxer = {
6903 .long_name = NULL_IF_CONFIG_SMALL("3GP2 (3GPP2 file format)"),
6904 .extensions = "3g2",
6905 .priv_data_size = sizeof(MOVMuxContext),
6906 .audio_codec = AV_CODEC_ID_AMR_NB,
6907 .video_codec = AV_CODEC_ID_H263,
6909 .write_header = mov_write_header,
6910 .write_packet = mov_write_packet,
6911 .write_trailer = mov_write_trailer,
6913 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6914 .codec_tag = (const AVCodecTag* const []){ codec_3gp_tags, 0 },
6915 .check_bitstream = mov_check_bitstream,
6916 .priv_class = &tg2_muxer_class,
6919 #if CONFIG_IPOD_MUXER
6921 AVOutputFormat ff_ipod_muxer = {
6923 .long_name = NULL_IF_CONFIG_SMALL("iPod H.264 MP4 (MPEG-4 Part 14)"),
6924 .mime_type = "video/mp4",
6925 .extensions = "m4v,m4a,m4b",
6926 .priv_data_size = sizeof(MOVMuxContext),
6927 .audio_codec = AV_CODEC_ID_AAC,
6928 .video_codec = AV_CODEC_ID_H264,
6930 .write_header = mov_write_header,
6931 .write_packet = mov_write_packet,
6932 .write_trailer = mov_write_trailer,
6934 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6935 .codec_tag = (const AVCodecTag* const []){ codec_ipod_tags, 0 },
6936 .check_bitstream = mov_check_bitstream,
6937 .priv_class = &ipod_muxer_class,
6940 #if CONFIG_ISMV_MUXER
6942 AVOutputFormat ff_ismv_muxer = {
6944 .long_name = NULL_IF_CONFIG_SMALL("ISMV/ISMA (Smooth Streaming)"),
6945 .mime_type = "video/mp4",
6946 .extensions = "ismv,isma",
6947 .priv_data_size = sizeof(MOVMuxContext),
6948 .audio_codec = AV_CODEC_ID_AAC,
6949 .video_codec = AV_CODEC_ID_H264,
6951 .write_header = mov_write_header,
6952 .write_packet = mov_write_packet,
6953 .write_trailer = mov_write_trailer,
6955 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6956 .codec_tag = (const AVCodecTag* const []){
6957 codec_mp4_tags, codec_ism_tags, 0 },
6958 .check_bitstream = mov_check_bitstream,
6959 .priv_class = &ismv_muxer_class,
6962 #if CONFIG_F4V_MUXER
6964 AVOutputFormat ff_f4v_muxer = {
6966 .long_name = NULL_IF_CONFIG_SMALL("F4V Adobe Flash Video"),
6967 .mime_type = "application/f4v",
6968 .extensions = "f4v",
6969 .priv_data_size = sizeof(MOVMuxContext),
6970 .audio_codec = AV_CODEC_ID_AAC,
6971 .video_codec = AV_CODEC_ID_H264,
6973 .write_header = mov_write_header,
6974 .write_packet = mov_write_packet,
6975 .write_trailer = mov_write_trailer,
6977 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH,
6978 .codec_tag = (const AVCodecTag* const []){ codec_f4v_tags, 0 },
6979 .check_bitstream = mov_check_bitstream,
6980 .priv_class = &f4v_muxer_class,