3 * Copyright (c) 2003 Thomas Raivio
4 * Copyright (c) 2004 Gildas Bazin <gbazin at videolan dot org>
5 * Copyright (c) 2009 Baptiste Coudurier <baptiste dot coudurier at gmail dot com>
7 * This file is part of FFmpeg.
9 * FFmpeg is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
14 * FFmpeg is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with FFmpeg; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
29 #include "avio_internal.h"
35 #include "libavcodec/ac3_parser_internal.h"
36 #include "libavcodec/dnxhddata.h"
37 #include "libavcodec/flac.h"
38 #include "libavcodec/get_bits.h"
40 #include "libavcodec/internal.h"
41 #include "libavcodec/put_bits.h"
42 #include "libavcodec/vc1_common.h"
43 #include "libavcodec/raw.h"
45 #include "libavutil/avstring.h"
46 #include "libavutil/intfloat.h"
47 #include "libavutil/mathematics.h"
48 #include "libavutil/libm.h"
49 #include "libavutil/opt.h"
50 #include "libavutil/dict.h"
51 #include "libavutil/pixdesc.h"
52 #include "libavutil/stereo3d.h"
53 #include "libavutil/timecode.h"
54 #include "libavutil/color_utils.h"
60 static const AVOption options[] = {
61 { "movflags", "MOV muxer flags", offsetof(MOVMuxContext, flags), AV_OPT_TYPE_FLAGS, {.i64 = 0}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
62 { "rtphint", "Add RTP hint tracks", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_RTP_HINT}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
63 { "moov_size", "maximum moov size so it can be placed at the begin", offsetof(MOVMuxContext, reserved_moov_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, 0 },
64 { "empty_moov", "Make the initial moov atom empty", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_EMPTY_MOOV}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
65 { "frag_keyframe", "Fragment at video keyframes", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FRAG_KEYFRAME}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
66 { "frag_every_frame", "Fragment at every frame", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FRAG_EVERY_FRAME}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
67 { "separate_moof", "Write separate moof/mdat atoms for each track", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_SEPARATE_MOOF}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
68 { "frag_custom", "Flush fragments on caller requests", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FRAG_CUSTOM}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
69 { "isml", "Create a live smooth streaming feed (for pushing to a publishing point)", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_ISML}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
70 { "faststart", "Run a second pass to put the index (moov atom) at the beginning of the file", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FASTSTART}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
71 { "omit_tfhd_offset", "Omit the base data offset in tfhd atoms", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_OMIT_TFHD_OFFSET}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
72 { "disable_chpl", "Disable Nero chapter atom", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_DISABLE_CHPL}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
73 { "default_base_moof", "Set the default-base-is-moof flag in tfhd atoms", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_DEFAULT_BASE_MOOF}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
74 { "dash", "Write DASH compatible fragmented MP4", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_DASH}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
75 { "frag_discont", "Signal that the next fragment is discontinuous from earlier ones", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FRAG_DISCONT}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
76 { "delay_moov", "Delay writing the initial moov until the first fragment is cut, or until the first fragment flush", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_DELAY_MOOV}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
77 { "global_sidx", "Write a global sidx index at the start of the file", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_GLOBAL_SIDX}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
78 { "write_colr", "Write colr atom (Experimental, may be renamed or changed, do not use from scripts)", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_WRITE_COLR}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
79 { "write_gama", "Write deprecated gama atom", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_WRITE_GAMA}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
80 { "use_metadata_tags", "Use mdta atom for metadata.", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_USE_MDTA}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
81 { "skip_trailer", "Skip writing the mfra/tfra/mfro trailer for fragmented files", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_SKIP_TRAILER}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
82 { "negative_cts_offsets", "Use negative CTS offsets (reducing the need for edit lists)", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
83 FF_RTP_FLAG_OPTS(MOVMuxContext, rtp_flags),
84 { "skip_iods", "Skip writing iods atom.", offsetof(MOVMuxContext, iods_skip), AV_OPT_TYPE_BOOL, {.i64 = 1}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM},
85 { "iods_audio_profile", "iods audio profile atom.", offsetof(MOVMuxContext, iods_audio_profile), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 255, AV_OPT_FLAG_ENCODING_PARAM},
86 { "iods_video_profile", "iods video profile atom.", offsetof(MOVMuxContext, iods_video_profile), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 255, AV_OPT_FLAG_ENCODING_PARAM},
87 { "frag_duration", "Maximum fragment duration", offsetof(MOVMuxContext, max_fragment_duration), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
88 { "min_frag_duration", "Minimum fragment duration", offsetof(MOVMuxContext, min_fragment_duration), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
89 { "frag_size", "Maximum fragment size", offsetof(MOVMuxContext, max_fragment_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
90 { "ism_lookahead", "Number of lookahead entries for ISM files", offsetof(MOVMuxContext, ism_lookahead), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
91 { "video_track_timescale", "set timescale of all video tracks", offsetof(MOVMuxContext, video_track_timescale), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
92 { "brand", "Override major brand", offsetof(MOVMuxContext, major_brand), AV_OPT_TYPE_STRING, {.str = NULL}, .flags = AV_OPT_FLAG_ENCODING_PARAM },
93 { "use_editlist", "use edit list", offsetof(MOVMuxContext, use_editlist), AV_OPT_TYPE_BOOL, {.i64 = -1}, -1, 1, AV_OPT_FLAG_ENCODING_PARAM},
94 { "fragment_index", "Fragment number of the next fragment", offsetof(MOVMuxContext, fragments), AV_OPT_TYPE_INT, {.i64 = 1}, 1, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
95 { "mov_gamma", "gamma value for gama atom", offsetof(MOVMuxContext, gamma), AV_OPT_TYPE_FLOAT, {.dbl = 0.0 }, 0.0, 10, AV_OPT_FLAG_ENCODING_PARAM},
96 { "frag_interleave", "Interleave samples within fragments (max number of consecutive samples, lower is tighter interleaving, but with more overhead)", offsetof(MOVMuxContext, frag_interleave), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM },
97 { "encryption_scheme", "Configures the encryption scheme, allowed values are none, cenc-aes-ctr", offsetof(MOVMuxContext, encryption_scheme_str), AV_OPT_TYPE_STRING, {.str = NULL}, .flags = AV_OPT_FLAG_ENCODING_PARAM },
98 { "encryption_key", "The media encryption key (hex)", offsetof(MOVMuxContext, encryption_key), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_ENCODING_PARAM },
99 { "encryption_kid", "The media encryption key identifier (hex)", offsetof(MOVMuxContext, encryption_kid), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_ENCODING_PARAM },
100 { "use_stream_ids_as_track_ids", "use stream ids as track ids", offsetof(MOVMuxContext, use_stream_ids_as_track_ids), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM},
101 { "write_tmcd", "force or disable writing tmcd", offsetof(MOVMuxContext, write_tmcd), AV_OPT_TYPE_BOOL, {.i64 = -1}, -1, 1, AV_OPT_FLAG_ENCODING_PARAM},
102 { "write_prft", "Write producer reference time box with specified time source", offsetof(MOVMuxContext, write_prft), AV_OPT_TYPE_INT, {.i64 = MOV_PRFT_NONE}, 0, MOV_PRFT_NB-1, AV_OPT_FLAG_ENCODING_PARAM, "prft"},
103 { "wallclock", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = MOV_PRFT_SRC_WALLCLOCK}, 0, 0, AV_OPT_FLAG_ENCODING_PARAM, "prft"},
104 { "pts", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = MOV_PRFT_SRC_PTS}, 0, 0, AV_OPT_FLAG_ENCODING_PARAM, "prft"},
105 { "empty_hdlr_name", "write zero-length name string in hdlr atoms within mdia and minf atoms", offsetof(MOVMuxContext, empty_hdlr_name), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM},
109 #define MOV_CLASS(flavor)\
110 static const AVClass flavor ## _muxer_class = {\
111 .class_name = #flavor " muxer",\
112 .item_name = av_default_item_name,\
114 .version = LIBAVUTIL_VERSION_INT,\
117 static int get_moov_size(AVFormatContext *s);
119 static int utf8len(const uint8_t *b)
124 GET_UTF8(val, *b++, return -1;)
130 //FIXME support 64 bit variant with wide placeholders
131 static int64_t update_size(AVIOContext *pb, int64_t pos)
133 int64_t curpos = avio_tell(pb);
134 avio_seek(pb, pos, SEEK_SET);
135 avio_wb32(pb, curpos - pos); /* rewrite size */
136 avio_seek(pb, curpos, SEEK_SET);
141 static int co64_required(const MOVTrack *track)
143 if (track->entry > 0 && track->cluster[track->entry - 1].pos + track->data_offset > UINT32_MAX)
148 static int is_cover_image(const AVStream *st)
150 /* Eg. AV_DISPOSITION_ATTACHED_PIC | AV_DISPOSITION_TIMED_THUMBNAILS
151 * is encoded as sparse video track */
152 return st && st->disposition == AV_DISPOSITION_ATTACHED_PIC;
155 static int rtp_hinting_needed(const AVStream *st)
157 /* Add hint tracks for each real audio and video stream */
158 if (is_cover_image(st))
160 return st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ||
161 st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO;
164 /* Chunk offset atom */
165 static int mov_write_stco_tag(AVIOContext *pb, MOVTrack *track)
168 int mode64 = co64_required(track); // use 32 bit size variant if possible
169 int64_t pos = avio_tell(pb);
170 avio_wb32(pb, 0); /* size */
172 ffio_wfourcc(pb, "co64");
174 ffio_wfourcc(pb, "stco");
175 avio_wb32(pb, 0); /* version & flags */
176 avio_wb32(pb, track->chunkCount); /* entry count */
177 for (i = 0; i < track->entry; i++) {
178 if (!track->cluster[i].chunkNum)
181 avio_wb64(pb, track->cluster[i].pos + track->data_offset);
183 avio_wb32(pb, track->cluster[i].pos + track->data_offset);
185 return update_size(pb, pos);
188 /* Sample size atom */
189 static int mov_write_stsz_tag(AVIOContext *pb, MOVTrack *track)
192 int i, j, entries = 0, tst = -1, oldtst = -1;
194 int64_t pos = avio_tell(pb);
195 avio_wb32(pb, 0); /* size */
196 ffio_wfourcc(pb, "stsz");
197 avio_wb32(pb, 0); /* version & flags */
199 for (i = 0; i < track->entry; i++) {
200 tst = track->cluster[i].size / track->cluster[i].entries;
201 if (oldtst != -1 && tst != oldtst)
204 entries += track->cluster[i].entries;
206 if (equalChunks && track->entry) {
207 int sSize = track->entry ? track->cluster[0].size / track->cluster[0].entries : 0;
208 sSize = FFMAX(1, sSize); // adpcm mono case could make sSize == 0
209 avio_wb32(pb, sSize); // sample size
210 avio_wb32(pb, entries); // sample count
212 avio_wb32(pb, 0); // sample size
213 avio_wb32(pb, entries); // sample count
214 for (i = 0; i < track->entry; i++) {
215 for (j = 0; j < track->cluster[i].entries; j++) {
216 avio_wb32(pb, track->cluster[i].size /
217 track->cluster[i].entries);
221 return update_size(pb, pos);
224 /* Sample to chunk atom */
225 static int mov_write_stsc_tag(AVIOContext *pb, MOVTrack *track)
227 int index = 0, oldval = -1, i;
228 int64_t entryPos, curpos;
230 int64_t pos = avio_tell(pb);
231 avio_wb32(pb, 0); /* size */
232 ffio_wfourcc(pb, "stsc");
233 avio_wb32(pb, 0); // version & flags
234 entryPos = avio_tell(pb);
235 avio_wb32(pb, track->chunkCount); // entry count
236 for (i = 0; i < track->entry; i++) {
237 if (oldval != track->cluster[i].samples_in_chunk && track->cluster[i].chunkNum) {
238 avio_wb32(pb, track->cluster[i].chunkNum); // first chunk
239 avio_wb32(pb, track->cluster[i].samples_in_chunk); // samples per chunk
240 avio_wb32(pb, 0x1); // sample description index
241 oldval = track->cluster[i].samples_in_chunk;
245 curpos = avio_tell(pb);
246 avio_seek(pb, entryPos, SEEK_SET);
247 avio_wb32(pb, index); // rewrite size
248 avio_seek(pb, curpos, SEEK_SET);
250 return update_size(pb, pos);
253 /* Sync sample atom */
254 static int mov_write_stss_tag(AVIOContext *pb, MOVTrack *track, uint32_t flag)
256 int64_t curpos, entryPos;
258 int64_t pos = avio_tell(pb);
259 avio_wb32(pb, 0); // size
260 ffio_wfourcc(pb, flag == MOV_SYNC_SAMPLE ? "stss" : "stps");
261 avio_wb32(pb, 0); // version & flags
262 entryPos = avio_tell(pb);
263 avio_wb32(pb, track->entry); // entry count
264 for (i = 0; i < track->entry; i++) {
265 if (track->cluster[i].flags & flag) {
266 avio_wb32(pb, i + 1);
270 curpos = avio_tell(pb);
271 avio_seek(pb, entryPos, SEEK_SET);
272 avio_wb32(pb, index); // rewrite size
273 avio_seek(pb, curpos, SEEK_SET);
274 return update_size(pb, pos);
277 /* Sample dependency atom */
278 static int mov_write_sdtp_tag(AVIOContext *pb, MOVTrack *track)
281 uint8_t leading, dependent, reference, redundancy;
282 int64_t pos = avio_tell(pb);
283 avio_wb32(pb, 0); // size
284 ffio_wfourcc(pb, "sdtp");
285 avio_wb32(pb, 0); // version & flags
286 for (i = 0; i < track->entry; i++) {
287 dependent = MOV_SAMPLE_DEPENDENCY_YES;
288 leading = reference = redundancy = MOV_SAMPLE_DEPENDENCY_UNKNOWN;
289 if (track->cluster[i].flags & MOV_DISPOSABLE_SAMPLE) {
290 reference = MOV_SAMPLE_DEPENDENCY_NO;
292 if (track->cluster[i].flags & MOV_SYNC_SAMPLE) {
293 dependent = MOV_SAMPLE_DEPENDENCY_NO;
295 avio_w8(pb, (leading << 6) | (dependent << 4) |
296 (reference << 2) | redundancy);
298 return update_size(pb, pos);
301 static int mov_write_amr_tag(AVIOContext *pb, MOVTrack *track)
303 avio_wb32(pb, 0x11); /* size */
304 if (track->mode == MODE_MOV) ffio_wfourcc(pb, "samr");
305 else ffio_wfourcc(pb, "damr");
306 ffio_wfourcc(pb, "FFMP");
307 avio_w8(pb, 0); /* decoder version */
309 avio_wb16(pb, 0x81FF); /* Mode set (all modes for AMR_NB) */
310 avio_w8(pb, 0x00); /* Mode change period (no restriction) */
311 avio_w8(pb, 0x01); /* Frames per sample */
315 static int mov_write_ac3_tag(AVIOContext *pb, MOVTrack *track)
320 int fscod, bsid, bsmod, acmod, lfeon, frmsizecod;
322 if (track->vos_len < 7)
326 ffio_wfourcc(pb, "dac3");
328 init_get_bits(&gbc, track->vos_data + 4, (track->vos_len - 4) * 8);
329 fscod = get_bits(&gbc, 2);
330 frmsizecod = get_bits(&gbc, 6);
331 bsid = get_bits(&gbc, 5);
332 bsmod = get_bits(&gbc, 3);
333 acmod = get_bits(&gbc, 3);
335 skip_bits(&gbc, 2); // dsurmod
337 if ((acmod & 1) && acmod != 1)
338 skip_bits(&gbc, 2); // cmixlev
340 skip_bits(&gbc, 2); // surmixlev
342 lfeon = get_bits1(&gbc);
344 init_put_bits(&pbc, buf, sizeof(buf));
345 put_bits(&pbc, 2, fscod);
346 put_bits(&pbc, 5, bsid);
347 put_bits(&pbc, 3, bsmod);
348 put_bits(&pbc, 3, acmod);
349 put_bits(&pbc, 1, lfeon);
350 put_bits(&pbc, 5, frmsizecod >> 1); // bit_rate_code
351 put_bits(&pbc, 5, 0); // reserved
353 flush_put_bits(&pbc);
354 avio_write(pb, buf, sizeof(buf));
364 /* Layout of the EC3SpecificBox */
365 /* maximum bitrate */
367 /* number of independent substreams */
370 /* sample rate code (see ff_ac3_sample_rate_tab) 2 bits */
372 /* bit stream identification 5 bits */
374 /* one bit reserved */
375 /* audio service mixing (not supported yet) 1 bit */
376 /* bit stream mode 3 bits */
378 /* audio coding mode 3 bits */
380 /* sub woofer on 1 bit */
382 /* 3 bits reserved */
383 /* number of dependent substreams associated with this substream 4 bits */
385 /* channel locations of the dependent substream(s), if any, 9 bits */
387 /* if there is no dependent substream, then one bit reserved instead */
388 } substream[1]; /* TODO: support 8 independent substreams */
391 #if CONFIG_AC3_PARSER
392 static int handle_eac3(MOVMuxContext *mov, AVPacket *pkt, MOVTrack *track)
394 AC3HeaderInfo *hdr = NULL;
395 struct eac3_info *info;
398 if (!track->eac3_priv && !(track->eac3_priv = av_mallocz(sizeof(*info))))
399 return AVERROR(ENOMEM);
400 info = track->eac3_priv;
402 if (avpriv_ac3_parse_header(&hdr, pkt->data, pkt->size) < 0) {
403 /* drop the packets until we see a good one */
405 av_log(mov->fc, AV_LOG_WARNING, "Dropping invalid packet from start of the stream\n");
408 ret = AVERROR_INVALIDDATA;
412 info->data_rate = FFMAX(info->data_rate, hdr->bit_rate / 1000);
413 num_blocks = hdr->num_blocks;
415 if (!info->ec3_done) {
416 /* AC-3 substream must be the first one */
417 if (hdr->bitstream_id <= 10 && hdr->substreamid != 0) {
418 ret = AVERROR(EINVAL);
422 /* this should always be the case, given that our AC-3 parser
423 * concatenates dependent frames to their independent parent */
424 if (hdr->frame_type == EAC3_FRAME_TYPE_INDEPENDENT) {
425 /* substream ids must be incremental */
426 if (hdr->substreamid > info->num_ind_sub + 1) {
427 ret = AVERROR(EINVAL);
431 if (hdr->substreamid == info->num_ind_sub + 1) {
432 //info->num_ind_sub++;
433 avpriv_request_sample(mov->fc, "Multiple independent substreams");
434 ret = AVERROR_PATCHWELCOME;
436 } else if (hdr->substreamid < info->num_ind_sub ||
437 hdr->substreamid == 0 && info->substream[0].bsid) {
442 if (hdr->substreamid != 0) {
443 avpriv_request_sample(mov->fc, "Multiple non EAC3 independent substreams");
444 ret = AVERROR_PATCHWELCOME;
449 /* fill the info needed for the "dec3" atom */
450 info->substream[hdr->substreamid].fscod = hdr->sr_code;
451 info->substream[hdr->substreamid].bsid = hdr->bitstream_id;
452 info->substream[hdr->substreamid].bsmod = hdr->bitstream_mode;
453 info->substream[hdr->substreamid].acmod = hdr->channel_mode;
454 info->substream[hdr->substreamid].lfeon = hdr->lfe_on;
456 /* Parse dependent substream(s), if any */
457 if (pkt->size != hdr->frame_size) {
458 int cumul_size = hdr->frame_size;
459 int parent = hdr->substreamid;
461 while (cumul_size != pkt->size) {
464 ret = avpriv_ac3_parse_header(&hdr, pkt->data + cumul_size, pkt->size - cumul_size);
467 if (hdr->frame_type != EAC3_FRAME_TYPE_DEPENDENT) {
468 ret = AVERROR(EINVAL);
471 info->substream[parent].num_dep_sub++;
474 /* header is parsed up to lfeon, but custom channel map may be needed */
475 init_get_bits8(&gbc, pkt->data + cumul_size + ret, pkt->size - cumul_size - ret);
478 /* skip volume control params */
479 for (i = 0; i < (hdr->channel_mode ? 1 : 2); i++) {
480 skip_bits(&gbc, 5); // skip dialog normalization
481 if (get_bits1(&gbc)) {
482 skip_bits(&gbc, 8); // skip compression gain word
485 /* get the dependent stream channel map, if exists */
487 info->substream[parent].chan_loc |= (get_bits(&gbc, 16) >> 5) & 0x1f;
489 info->substream[parent].chan_loc |= hdr->channel_mode;
490 cumul_size += hdr->frame_size;
496 if (!info->num_blocks && num_blocks == 6) {
500 else if (info->num_blocks + num_blocks > 6) {
501 ret = AVERROR_INVALIDDATA;
505 if (!info->num_blocks) {
506 ret = av_packet_ref(&info->pkt, pkt);
508 info->num_blocks = num_blocks;
511 if ((ret = av_grow_packet(&info->pkt, pkt->size)) < 0)
513 memcpy(info->pkt.data + info->pkt.size - pkt->size, pkt->data, pkt->size);
514 info->num_blocks += num_blocks;
515 info->pkt.duration += pkt->duration;
516 if ((ret = av_copy_packet_side_data(&info->pkt, pkt)) < 0)
518 if (info->num_blocks != 6)
520 av_packet_unref(pkt);
521 av_packet_move_ref(pkt, &info->pkt);
522 info->num_blocks = 0;
533 static int mov_write_eac3_tag(AVIOContext *pb, MOVTrack *track)
537 struct eac3_info *info;
540 if (!track->eac3_priv)
541 return AVERROR(EINVAL);
543 info = track->eac3_priv;
544 size = 2 + 4 * (info->num_ind_sub + 1);
545 buf = av_malloc(size);
547 size = AVERROR(ENOMEM);
551 init_put_bits(&pbc, buf, size);
552 put_bits(&pbc, 13, info->data_rate);
553 put_bits(&pbc, 3, info->num_ind_sub);
554 for (i = 0; i <= info->num_ind_sub; i++) {
555 put_bits(&pbc, 2, info->substream[i].fscod);
556 put_bits(&pbc, 5, info->substream[i].bsid);
557 put_bits(&pbc, 1, 0); /* reserved */
558 put_bits(&pbc, 1, 0); /* asvc */
559 put_bits(&pbc, 3, info->substream[i].bsmod);
560 put_bits(&pbc, 3, info->substream[i].acmod);
561 put_bits(&pbc, 1, info->substream[i].lfeon);
562 put_bits(&pbc, 5, 0); /* reserved */
563 put_bits(&pbc, 4, info->substream[i].num_dep_sub);
564 if (!info->substream[i].num_dep_sub) {
565 put_bits(&pbc, 1, 0); /* reserved */
568 put_bits(&pbc, 9, info->substream[i].chan_loc);
571 flush_put_bits(&pbc);
573 avio_wb32(pb, size + 8);
574 ffio_wfourcc(pb, "dec3");
575 avio_write(pb, buf, size);
580 av_packet_unref(&info->pkt);
581 av_freep(&track->eac3_priv);
587 * This function writes extradata "as is".
588 * Extradata must be formatted like a valid atom (with size and tag).
590 static int mov_write_extradata_tag(AVIOContext *pb, MOVTrack *track)
592 avio_write(pb, track->par->extradata, track->par->extradata_size);
593 return track->par->extradata_size;
596 static int mov_write_enda_tag(AVIOContext *pb)
599 ffio_wfourcc(pb, "enda");
600 avio_wb16(pb, 1); /* little endian */
604 static int mov_write_enda_tag_be(AVIOContext *pb)
607 ffio_wfourcc(pb, "enda");
608 avio_wb16(pb, 0); /* big endian */
612 static void put_descr(AVIOContext *pb, int tag, unsigned int size)
617 avio_w8(pb, (size >> (7 * i)) | 0x80);
618 avio_w8(pb, size & 0x7F);
621 static unsigned compute_avg_bitrate(MOVTrack *track)
625 if (!track->track_duration)
627 for (i = 0; i < track->entry; i++)
628 size += track->cluster[i].size;
629 return size * 8 * track->timescale / track->track_duration;
632 static int mov_write_esds_tag(AVIOContext *pb, MOVTrack *track) // Basic
634 AVCPBProperties *props;
635 int64_t pos = avio_tell(pb);
636 int decoder_specific_info_len = track->vos_len ? 5 + track->vos_len : 0;
637 unsigned avg_bitrate;
639 avio_wb32(pb, 0); // size
640 ffio_wfourcc(pb, "esds");
641 avio_wb32(pb, 0); // Version
644 put_descr(pb, 0x03, 3 + 5+13 + decoder_specific_info_len + 5+1);
645 avio_wb16(pb, track->track_id);
646 avio_w8(pb, 0x00); // flags (= no flags)
648 // DecoderConfig descriptor
649 put_descr(pb, 0x04, 13 + decoder_specific_info_len);
651 // Object type indication
652 if ((track->par->codec_id == AV_CODEC_ID_MP2 ||
653 track->par->codec_id == AV_CODEC_ID_MP3) &&
654 track->par->sample_rate > 24000)
655 avio_w8(pb, 0x6B); // 11172-3
657 avio_w8(pb, ff_codec_get_tag(ff_mp4_obj_type, track->par->codec_id));
659 // the following fields is made of 6 bits to identify the streamtype (4 for video, 5 for audio)
660 // plus 1 bit to indicate upstream and 1 bit set to 1 (reserved)
661 if (track->par->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
662 avio_w8(pb, (0x38 << 2) | 1); // flags (= NeroSubpicStream)
663 else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
664 avio_w8(pb, 0x15); // flags (= Audiostream)
666 avio_w8(pb, 0x11); // flags (= Visualstream)
668 props = (AVCPBProperties*)av_stream_get_side_data(track->st, AV_PKT_DATA_CPB_PROPERTIES,
671 avio_wb24(pb, props ? props->buffer_size / 8 : 0); // Buffersize DB
673 avg_bitrate = compute_avg_bitrate(track);
674 avio_wb32(pb, props ? FFMAX3(props->max_bitrate, props->avg_bitrate, avg_bitrate) : FFMAX(track->par->bit_rate, avg_bitrate)); // maxbitrate (FIXME should be max rate in any 1 sec window)
675 avio_wb32(pb, avg_bitrate);
677 if (track->vos_len) {
678 // DecoderSpecific info descriptor
679 put_descr(pb, 0x05, track->vos_len);
680 avio_write(pb, track->vos_data, track->vos_len);
684 put_descr(pb, 0x06, 1);
686 return update_size(pb, pos);
689 static int mov_pcm_le_gt16(enum AVCodecID codec_id)
691 return codec_id == AV_CODEC_ID_PCM_S24LE ||
692 codec_id == AV_CODEC_ID_PCM_S32LE ||
693 codec_id == AV_CODEC_ID_PCM_F32LE ||
694 codec_id == AV_CODEC_ID_PCM_F64LE;
697 static int mov_pcm_be_gt16(enum AVCodecID codec_id)
699 return codec_id == AV_CODEC_ID_PCM_S24BE ||
700 codec_id == AV_CODEC_ID_PCM_S32BE ||
701 codec_id == AV_CODEC_ID_PCM_F32BE ||
702 codec_id == AV_CODEC_ID_PCM_F64BE;
705 static int mov_write_ms_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
708 int64_t pos = avio_tell(pb);
710 avio_wl32(pb, track->tag); // store it byteswapped
711 track->par->codec_tag = av_bswap16(track->tag >> 16);
712 if ((ret = ff_put_wav_header(s, pb, track->par, 0)) < 0)
714 return update_size(pb, pos);
717 static int mov_write_wfex_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
720 int64_t pos = avio_tell(pb);
722 ffio_wfourcc(pb, "wfex");
723 if ((ret = ff_put_wav_header(s, pb, track->st->codecpar, FF_PUT_WAV_HEADER_FORCE_WAVEFORMATEX)) < 0)
725 return update_size(pb, pos);
728 static int mov_write_dfla_tag(AVIOContext *pb, MOVTrack *track)
730 int64_t pos = avio_tell(pb);
732 ffio_wfourcc(pb, "dfLa");
733 avio_w8(pb, 0); /* version */
734 avio_wb24(pb, 0); /* flags */
736 /* Expect the encoder to pass a METADATA_BLOCK_TYPE_STREAMINFO. */
737 if (track->par->extradata_size != FLAC_STREAMINFO_SIZE)
738 return AVERROR_INVALIDDATA;
740 /* TODO: Write other METADATA_BLOCK_TYPEs if the encoder makes them available. */
741 avio_w8(pb, 1 << 7 | FLAC_METADATA_TYPE_STREAMINFO); /* LastMetadataBlockFlag << 7 | BlockType */
742 avio_wb24(pb, track->par->extradata_size); /* Length */
743 avio_write(pb, track->par->extradata, track->par->extradata_size); /* BlockData[Length] */
745 return update_size(pb, pos);
748 static int mov_write_dops_tag(AVIOContext *pb, MOVTrack *track)
750 int64_t pos = avio_tell(pb);
752 ffio_wfourcc(pb, "dOps");
753 avio_w8(pb, 0); /* Version */
754 if (track->par->extradata_size < 19) {
755 av_log(pb, AV_LOG_ERROR, "invalid extradata size\n");
756 return AVERROR_INVALIDDATA;
758 /* extradata contains an Ogg OpusHead, other than byte-ordering and
759 OpusHead's preceeding magic/version, OpusSpecificBox is currently
761 avio_w8(pb, AV_RB8(track->par->extradata + 9)); /* OuputChannelCount */
762 avio_wb16(pb, AV_RL16(track->par->extradata + 10)); /* PreSkip */
763 avio_wb32(pb, AV_RL32(track->par->extradata + 12)); /* InputSampleRate */
764 avio_wb16(pb, AV_RL16(track->par->extradata + 16)); /* OutputGain */
765 /* Write the rest of the header out without byte-swapping. */
766 avio_write(pb, track->par->extradata + 18, track->par->extradata_size - 18);
768 return update_size(pb, pos);
771 static int mov_write_chan_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
773 uint32_t layout_tag, bitmap;
774 int64_t pos = avio_tell(pb);
776 layout_tag = ff_mov_get_channel_layout_tag(track->par->codec_id,
777 track->par->channel_layout,
780 av_log(s, AV_LOG_WARNING, "not writing 'chan' tag due to "
781 "lack of channel information\n");
785 if (track->multichannel_as_mono)
788 avio_wb32(pb, 0); // Size
789 ffio_wfourcc(pb, "chan"); // Type
790 avio_w8(pb, 0); // Version
791 avio_wb24(pb, 0); // Flags
792 avio_wb32(pb, layout_tag); // mChannelLayoutTag
793 avio_wb32(pb, bitmap); // mChannelBitmap
794 avio_wb32(pb, 0); // mNumberChannelDescriptions
796 return update_size(pb, pos);
799 static int mov_write_wave_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
801 int64_t pos = avio_tell(pb);
803 avio_wb32(pb, 0); /* size */
804 ffio_wfourcc(pb, "wave");
806 if (track->par->codec_id != AV_CODEC_ID_QDM2) {
807 avio_wb32(pb, 12); /* size */
808 ffio_wfourcc(pb, "frma");
809 avio_wl32(pb, track->tag);
812 if (track->par->codec_id == AV_CODEC_ID_AAC) {
813 /* useless atom needed by mplayer, ipod, not needed by quicktime */
814 avio_wb32(pb, 12); /* size */
815 ffio_wfourcc(pb, "mp4a");
817 mov_write_esds_tag(pb, track);
818 } else if (mov_pcm_le_gt16(track->par->codec_id)) {
819 mov_write_enda_tag(pb);
820 } else if (mov_pcm_be_gt16(track->par->codec_id)) {
821 mov_write_enda_tag_be(pb);
822 } else if (track->par->codec_id == AV_CODEC_ID_AMR_NB) {
823 mov_write_amr_tag(pb, track);
824 } else if (track->par->codec_id == AV_CODEC_ID_AC3) {
825 mov_write_ac3_tag(pb, track);
826 } else if (track->par->codec_id == AV_CODEC_ID_EAC3) {
827 mov_write_eac3_tag(pb, track);
828 } else if (track->par->codec_id == AV_CODEC_ID_ALAC ||
829 track->par->codec_id == AV_CODEC_ID_QDM2) {
830 mov_write_extradata_tag(pb, track);
831 } else if (track->par->codec_id == AV_CODEC_ID_ADPCM_MS ||
832 track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) {
833 mov_write_ms_tag(s, pb, track);
836 avio_wb32(pb, 8); /* size */
837 avio_wb32(pb, 0); /* null tag */
839 return update_size(pb, pos);
842 static int mov_write_dvc1_structs(MOVTrack *track, uint8_t *buf)
845 const uint8_t *start, *next, *end = track->vos_data + track->vos_len;
846 int unescaped_size, seq_found = 0;
847 int level = 0, interlace = 0;
848 int packet_seq = track->vc1_info.packet_seq;
849 int packet_entry = track->vc1_info.packet_entry;
850 int slices = track->vc1_info.slices;
853 if (track->start_dts == AV_NOPTS_VALUE) {
854 /* No packets written yet, vc1_info isn't authoritative yet. */
855 /* Assume inline sequence and entry headers. */
856 packet_seq = packet_entry = 1;
857 av_log(NULL, AV_LOG_WARNING,
858 "moov atom written before any packets, unable to write correct "
859 "dvc1 atom. Set the delay_moov flag to fix this.\n");
862 unescaped = av_mallocz(track->vos_len + AV_INPUT_BUFFER_PADDING_SIZE);
864 return AVERROR(ENOMEM);
865 start = find_next_marker(track->vos_data, end);
866 for (next = start; next < end; start = next) {
869 next = find_next_marker(start + 4, end);
870 size = next - start - 4;
873 unescaped_size = vc1_unescape_buffer(start + 4, size, unescaped);
874 init_get_bits(&gb, unescaped, 8 * unescaped_size);
875 if (AV_RB32(start) == VC1_CODE_SEQHDR) {
876 int profile = get_bits(&gb, 2);
877 if (profile != PROFILE_ADVANCED) {
879 return AVERROR(ENOSYS);
882 level = get_bits(&gb, 3);
883 /* chromaformat, frmrtq_postproc, bitrtq_postproc, postprocflag,
885 skip_bits_long(&gb, 2 + 3 + 5 + 1 + 2*12);
886 skip_bits(&gb, 1); /* broadcast */
887 interlace = get_bits1(&gb);
888 skip_bits(&gb, 4); /* tfcntrflag, finterpflag, reserved, psf */
893 return AVERROR(ENOSYS);
896 init_put_bits(&pbc, buf, 7);
897 /* VC1DecSpecStruc */
898 put_bits(&pbc, 4, 12); /* profile - advanced */
899 put_bits(&pbc, 3, level);
900 put_bits(&pbc, 1, 0); /* reserved */
901 /* VC1AdvDecSpecStruc */
902 put_bits(&pbc, 3, level);
903 put_bits(&pbc, 1, 0); /* cbr */
904 put_bits(&pbc, 6, 0); /* reserved */
905 put_bits(&pbc, 1, !interlace); /* no interlace */
906 put_bits(&pbc, 1, !packet_seq); /* no multiple seq */
907 put_bits(&pbc, 1, !packet_entry); /* no multiple entry */
908 put_bits(&pbc, 1, !slices); /* no slice code */
909 put_bits(&pbc, 1, 0); /* no bframe */
910 put_bits(&pbc, 1, 0); /* reserved */
913 if (track->st->avg_frame_rate.num > 0 && track->st->avg_frame_rate.den > 0)
914 put_bits32(&pbc, track->st->avg_frame_rate.num / track->st->avg_frame_rate.den);
916 put_bits32(&pbc, 0xffffffff);
918 flush_put_bits(&pbc);
925 static int mov_write_dvc1_tag(AVIOContext *pb, MOVTrack *track)
927 uint8_t buf[7] = { 0 };
930 if ((ret = mov_write_dvc1_structs(track, buf)) < 0)
933 avio_wb32(pb, track->vos_len + 8 + sizeof(buf));
934 ffio_wfourcc(pb, "dvc1");
935 avio_write(pb, buf, sizeof(buf));
936 avio_write(pb, track->vos_data, track->vos_len);
941 static int mov_write_glbl_tag(AVIOContext *pb, MOVTrack *track)
943 avio_wb32(pb, track->vos_len + 8);
944 ffio_wfourcc(pb, "glbl");
945 avio_write(pb, track->vos_data, track->vos_len);
946 return 8 + track->vos_len;
950 * Compute flags for 'lpcm' tag.
951 * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
953 static int mov_get_lpcm_flags(enum AVCodecID codec_id)
956 case AV_CODEC_ID_PCM_F32BE:
957 case AV_CODEC_ID_PCM_F64BE:
959 case AV_CODEC_ID_PCM_F32LE:
960 case AV_CODEC_ID_PCM_F64LE:
962 case AV_CODEC_ID_PCM_U8:
964 case AV_CODEC_ID_PCM_S16BE:
965 case AV_CODEC_ID_PCM_S24BE:
966 case AV_CODEC_ID_PCM_S32BE:
968 case AV_CODEC_ID_PCM_S8:
969 case AV_CODEC_ID_PCM_S16LE:
970 case AV_CODEC_ID_PCM_S24LE:
971 case AV_CODEC_ID_PCM_S32LE:
978 static int get_cluster_duration(MOVTrack *track, int cluster_idx)
982 if (cluster_idx >= track->entry)
985 if (cluster_idx + 1 == track->entry)
986 next_dts = track->track_duration + track->start_dts;
988 next_dts = track->cluster[cluster_idx + 1].dts;
990 next_dts -= track->cluster[cluster_idx].dts;
992 av_assert0(next_dts >= 0);
993 av_assert0(next_dts <= INT_MAX);
998 static int get_samples_per_packet(MOVTrack *track)
1000 int i, first_duration;
1002 // return track->par->frame_size;
1004 /* use 1 for raw PCM */
1005 if (!track->audio_vbr)
1008 /* check to see if duration is constant for all clusters */
1011 first_duration = get_cluster_duration(track, 0);
1012 for (i = 1; i < track->entry; i++) {
1013 if (get_cluster_duration(track, i) != first_duration)
1016 return first_duration;
1019 static int mov_write_audio_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
1021 int64_t pos = avio_tell(pb);
1023 uint32_t tag = track->tag;
1025 if (track->mode == MODE_MOV) {
1026 if (track->timescale > UINT16_MAX || !track->par->channels) {
1027 if (mov_get_lpcm_flags(track->par->codec_id))
1028 tag = AV_RL32("lpcm");
1030 } else if (track->audio_vbr || mov_pcm_le_gt16(track->par->codec_id) ||
1031 mov_pcm_be_gt16(track->par->codec_id) ||
1032 track->par->codec_id == AV_CODEC_ID_ADPCM_MS ||
1033 track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
1034 track->par->codec_id == AV_CODEC_ID_QDM2) {
1039 avio_wb32(pb, 0); /* size */
1040 if (mov->encryption_scheme != MOV_ENC_NONE) {
1041 ffio_wfourcc(pb, "enca");
1043 avio_wl32(pb, tag); // store it byteswapped
1045 avio_wb32(pb, 0); /* Reserved */
1046 avio_wb16(pb, 0); /* Reserved */
1047 avio_wb16(pb, 1); /* Data-reference index, XXX == 1 */
1049 /* SoundDescription */
1050 avio_wb16(pb, version); /* Version */
1051 avio_wb16(pb, 0); /* Revision level */
1052 avio_wb32(pb, 0); /* Reserved */
1057 avio_wb16(pb, 0xfffe);
1059 avio_wb32(pb, 0x00010000);
1061 avio_wb64(pb, av_double2int(track->par->sample_rate));
1062 avio_wb32(pb, track->par->channels);
1063 avio_wb32(pb, 0x7F000000);
1064 avio_wb32(pb, av_get_bits_per_sample(track->par->codec_id));
1065 avio_wb32(pb, mov_get_lpcm_flags(track->par->codec_id));
1066 avio_wb32(pb, track->sample_size);
1067 avio_wb32(pb, get_samples_per_packet(track));
1069 if (track->mode == MODE_MOV) {
1070 avio_wb16(pb, track->par->channels);
1071 if (track->par->codec_id == AV_CODEC_ID_PCM_U8 ||
1072 track->par->codec_id == AV_CODEC_ID_PCM_S8)
1073 avio_wb16(pb, 8); /* bits per sample */
1074 else if (track->par->codec_id == AV_CODEC_ID_ADPCM_G726)
1075 avio_wb16(pb, track->par->bits_per_coded_sample);
1078 avio_wb16(pb, track->audio_vbr ? -2 : 0); /* compression ID */
1079 } else { /* reserved for mp4/3gp */
1080 if (track->par->codec_id == AV_CODEC_ID_FLAC ||
1081 track->par->codec_id == AV_CODEC_ID_OPUS) {
1082 avio_wb16(pb, track->par->channels);
1086 if (track->par->codec_id == AV_CODEC_ID_FLAC) {
1087 avio_wb16(pb, track->par->bits_per_raw_sample);
1094 avio_wb16(pb, 0); /* packet size (= 0) */
1095 if (track->par->codec_id == AV_CODEC_ID_OPUS)
1096 avio_wb16(pb, 48000);
1098 avio_wb16(pb, track->par->sample_rate <= UINT16_MAX ?
1099 track->par->sample_rate : 0);
1100 avio_wb16(pb, 0); /* Reserved */
1103 if (version == 1) { /* SoundDescription V1 extended info */
1104 if (mov_pcm_le_gt16(track->par->codec_id) ||
1105 mov_pcm_be_gt16(track->par->codec_id))
1106 avio_wb32(pb, 1); /* must be 1 for uncompressed formats */
1108 avio_wb32(pb, track->par->frame_size); /* Samples per packet */
1109 avio_wb32(pb, track->sample_size / track->par->channels); /* Bytes per packet */
1110 avio_wb32(pb, track->sample_size); /* Bytes per frame */
1111 avio_wb32(pb, 2); /* Bytes per sample */
1114 if (track->mode == MODE_MOV &&
1115 (track->par->codec_id == AV_CODEC_ID_AAC ||
1116 track->par->codec_id == AV_CODEC_ID_AC3 ||
1117 track->par->codec_id == AV_CODEC_ID_EAC3 ||
1118 track->par->codec_id == AV_CODEC_ID_AMR_NB ||
1119 track->par->codec_id == AV_CODEC_ID_ALAC ||
1120 track->par->codec_id == AV_CODEC_ID_ADPCM_MS ||
1121 track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
1122 track->par->codec_id == AV_CODEC_ID_QDM2 ||
1123 (mov_pcm_le_gt16(track->par->codec_id) && version==1) ||
1124 (mov_pcm_be_gt16(track->par->codec_id) && version==1)))
1125 mov_write_wave_tag(s, pb, track);
1126 else if (track->tag == MKTAG('m','p','4','a'))
1127 mov_write_esds_tag(pb, track);
1128 else if (track->par->codec_id == AV_CODEC_ID_AMR_NB)
1129 mov_write_amr_tag(pb, track);
1130 else if (track->par->codec_id == AV_CODEC_ID_AC3)
1131 mov_write_ac3_tag(pb, track);
1132 else if (track->par->codec_id == AV_CODEC_ID_EAC3)
1133 mov_write_eac3_tag(pb, track);
1134 else if (track->par->codec_id == AV_CODEC_ID_ALAC)
1135 mov_write_extradata_tag(pb, track);
1136 else if (track->par->codec_id == AV_CODEC_ID_WMAPRO)
1137 mov_write_wfex_tag(s, pb, track);
1138 else if (track->par->codec_id == AV_CODEC_ID_FLAC)
1139 mov_write_dfla_tag(pb, track);
1140 else if (track->par->codec_id == AV_CODEC_ID_OPUS)
1141 mov_write_dops_tag(pb, track);
1142 else if (track->vos_len > 0)
1143 mov_write_glbl_tag(pb, track);
1145 if (track->mode == MODE_MOV && track->par->codec_type == AVMEDIA_TYPE_AUDIO)
1146 mov_write_chan_tag(s, pb, track);
1148 if (mov->encryption_scheme != MOV_ENC_NONE) {
1149 ff_mov_cenc_write_sinf_tag(track, pb, mov->encryption_kid);
1152 return update_size(pb, pos);
1155 static int mov_write_d263_tag(AVIOContext *pb)
1157 avio_wb32(pb, 0xf); /* size */
1158 ffio_wfourcc(pb, "d263");
1159 ffio_wfourcc(pb, "FFMP");
1160 avio_w8(pb, 0); /* decoder version */
1161 /* FIXME use AVCodecContext level/profile, when encoder will set values */
1162 avio_w8(pb, 0xa); /* level */
1163 avio_w8(pb, 0); /* profile */
1167 static int mov_write_av1c_tag(AVIOContext *pb, MOVTrack *track)
1169 int64_t pos = avio_tell(pb);
1172 ffio_wfourcc(pb, "av1C");
1173 ff_isom_write_av1c(pb, track->vos_data, track->vos_len);
1174 return update_size(pb, pos);
1177 static int mov_write_avcc_tag(AVIOContext *pb, MOVTrack *track)
1179 int64_t pos = avio_tell(pb);
1182 ffio_wfourcc(pb, "avcC");
1183 ff_isom_write_avcc(pb, track->vos_data, track->vos_len);
1184 return update_size(pb, pos);
1187 static int mov_write_vpcc_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
1189 int64_t pos = avio_tell(pb);
1192 ffio_wfourcc(pb, "vpcC");
1193 avio_w8(pb, 1); /* version */
1194 avio_wb24(pb, 0); /* flags */
1195 ff_isom_write_vpcc(s, pb, track->par);
1196 return update_size(pb, pos);
1199 static int mov_write_hvcc_tag(AVIOContext *pb, MOVTrack *track)
1201 int64_t pos = avio_tell(pb);
1204 ffio_wfourcc(pb, "hvcC");
1205 if (track->tag == MKTAG('h','v','c','1'))
1206 ff_isom_write_hvcc(pb, track->vos_data, track->vos_len, 1);
1208 ff_isom_write_hvcc(pb, track->vos_data, track->vos_len, 0);
1209 return update_size(pb, pos);
1212 /* also used by all avid codecs (dv, imx, meridien) and their variants */
1213 static int mov_write_avid_tag(AVIOContext *pb, MOVTrack *track)
1218 int display_width = track->par->width;
1220 if (track->vos_data && track->vos_len > 0x29) {
1221 if (ff_dnxhd_parse_header_prefix(track->vos_data) != 0) {
1222 /* looks like a DNxHD bit stream */
1223 interlaced = (track->vos_data[5] & 2);
1224 cid = AV_RB32(track->vos_data + 0x28);
1226 av_log(NULL, AV_LOG_WARNING, "Could not locate DNxHD bit stream in vos_data\n");
1230 av_log(NULL, AV_LOG_WARNING, "Could not locate DNxHD bit stream, vos_data too small\n");
1234 avio_wb32(pb, 24); /* size */
1235 ffio_wfourcc(pb, "ACLR");
1236 ffio_wfourcc(pb, "ACLR");
1237 ffio_wfourcc(pb, "0001");
1238 if (track->par->color_range == AVCOL_RANGE_MPEG || /* Legal range (16-235) */
1239 track->par->color_range == AVCOL_RANGE_UNSPECIFIED) {
1240 avio_wb32(pb, 1); /* Corresponds to 709 in official encoder */
1241 } else { /* Full range (0-255) */
1242 avio_wb32(pb, 2); /* Corresponds to RGB in official encoder */
1244 avio_wb32(pb, 0); /* unknown */
1246 if (track->tag == MKTAG('A','V','d','h')) {
1248 ffio_wfourcc(pb, "ADHR");
1249 ffio_wfourcc(pb, "0001");
1251 avio_wb32(pb, 0); /* unknown */
1252 avio_wb32(pb, 1); /* unknown */
1253 avio_wb32(pb, 0); /* unknown */
1254 avio_wb32(pb, 0); /* unknown */
1258 avio_wb32(pb, 24); /* size */
1259 ffio_wfourcc(pb, "APRG");
1260 ffio_wfourcc(pb, "APRG");
1261 ffio_wfourcc(pb, "0001");
1262 avio_wb32(pb, 1); /* unknown */
1263 avio_wb32(pb, 0); /* unknown */
1265 avio_wb32(pb, 120); /* size */
1266 ffio_wfourcc(pb, "ARES");
1267 ffio_wfourcc(pb, "ARES");
1268 ffio_wfourcc(pb, "0001");
1269 avio_wb32(pb, cid); /* dnxhd cid, some id ? */
1270 if ( track->par->sample_aspect_ratio.num > 0
1271 && track->par->sample_aspect_ratio.den > 0)
1272 display_width = display_width * track->par->sample_aspect_ratio.num / track->par->sample_aspect_ratio.den;
1273 avio_wb32(pb, display_width);
1274 /* values below are based on samples created with quicktime and avid codecs */
1276 avio_wb32(pb, track->par->height / 2);
1277 avio_wb32(pb, 2); /* unknown */
1278 avio_wb32(pb, 0); /* unknown */
1279 avio_wb32(pb, 4); /* unknown */
1281 avio_wb32(pb, track->par->height);
1282 avio_wb32(pb, 1); /* unknown */
1283 avio_wb32(pb, 0); /* unknown */
1284 if (track->par->height == 1080)
1285 avio_wb32(pb, 5); /* unknown */
1287 avio_wb32(pb, 6); /* unknown */
1290 for (i = 0; i < 10; i++)
1296 static int mov_write_dpxe_tag(AVIOContext *pb, MOVTrack *track)
1299 ffio_wfourcc(pb, "DpxE");
1300 if (track->par->extradata_size >= 12 &&
1301 !memcmp(&track->par->extradata[4], "DpxE", 4)) {
1302 avio_wb32(pb, track->par->extradata[11]);
1309 static int mov_get_dv_codec_tag(AVFormatContext *s, MOVTrack *track)
1313 if (track->par->width == 720) { /* SD */
1314 if (track->par->height == 480) { /* NTSC */
1315 if (track->par->format == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','n');
1316 else tag = MKTAG('d','v','c',' ');
1317 }else if (track->par->format == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','p');
1318 else if (track->par->format == AV_PIX_FMT_YUV420P) tag = MKTAG('d','v','c','p');
1319 else tag = MKTAG('d','v','p','p');
1320 } else if (track->par->height == 720) { /* HD 720 line */
1321 if (track->st->time_base.den == 50) tag = MKTAG('d','v','h','q');
1322 else tag = MKTAG('d','v','h','p');
1323 } else if (track->par->height == 1080) { /* HD 1080 line */
1324 if (track->st->time_base.den == 25) tag = MKTAG('d','v','h','5');
1325 else tag = MKTAG('d','v','h','6');
1327 av_log(s, AV_LOG_ERROR, "unsupported height for dv codec\n");
1334 static AVRational find_fps(AVFormatContext *s, AVStream *st)
1336 AVRational rate = st->avg_frame_rate;
1338 #if FF_API_LAVF_AVCTX
1339 FF_DISABLE_DEPRECATION_WARNINGS
1340 rate = av_inv_q(st->codec->time_base);
1341 if (av_timecode_check_frame_rate(rate) < 0) {
1342 av_log(s, AV_LOG_DEBUG, "timecode: tbc=%d/%d invalid, fallback on %d/%d\n",
1343 rate.num, rate.den, st->avg_frame_rate.num, st->avg_frame_rate.den);
1344 rate = st->avg_frame_rate;
1346 FF_ENABLE_DEPRECATION_WARNINGS
1352 static int defined_frame_rate(AVFormatContext *s, AVStream *st)
1354 AVRational rational_framerate = find_fps(s, st);
1356 if (rational_framerate.den != 0)
1357 rate = av_q2d(rational_framerate);
1361 static int mov_get_mpeg2_xdcam_codec_tag(AVFormatContext *s, MOVTrack *track)
1363 int tag = track->par->codec_tag;
1364 int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE;
1365 AVStream *st = track->st;
1366 int rate = defined_frame_rate(s, st);
1369 tag = MKTAG('m', '2', 'v', '1'); //fallback tag
1371 if (track->par->format == AV_PIX_FMT_YUV420P) {
1372 if (track->par->width == 1280 && track->par->height == 720) {
1374 if (rate == 24) tag = MKTAG('x','d','v','4');
1375 else if (rate == 25) tag = MKTAG('x','d','v','5');
1376 else if (rate == 30) tag = MKTAG('x','d','v','1');
1377 else if (rate == 50) tag = MKTAG('x','d','v','a');
1378 else if (rate == 60) tag = MKTAG('x','d','v','9');
1380 } else if (track->par->width == 1440 && track->par->height == 1080) {
1382 if (rate == 24) tag = MKTAG('x','d','v','6');
1383 else if (rate == 25) tag = MKTAG('x','d','v','7');
1384 else if (rate == 30) tag = MKTAG('x','d','v','8');
1386 if (rate == 25) tag = MKTAG('x','d','v','3');
1387 else if (rate == 30) tag = MKTAG('x','d','v','2');
1389 } else if (track->par->width == 1920 && track->par->height == 1080) {
1391 if (rate == 24) tag = MKTAG('x','d','v','d');
1392 else if (rate == 25) tag = MKTAG('x','d','v','e');
1393 else if (rate == 30) tag = MKTAG('x','d','v','f');
1395 if (rate == 25) tag = MKTAG('x','d','v','c');
1396 else if (rate == 30) tag = MKTAG('x','d','v','b');
1399 } else if (track->par->format == AV_PIX_FMT_YUV422P) {
1400 if (track->par->width == 1280 && track->par->height == 720) {
1402 if (rate == 24) tag = MKTAG('x','d','5','4');
1403 else if (rate == 25) tag = MKTAG('x','d','5','5');
1404 else if (rate == 30) tag = MKTAG('x','d','5','1');
1405 else if (rate == 50) tag = MKTAG('x','d','5','a');
1406 else if (rate == 60) tag = MKTAG('x','d','5','9');
1408 } else if (track->par->width == 1920 && track->par->height == 1080) {
1410 if (rate == 24) tag = MKTAG('x','d','5','d');
1411 else if (rate == 25) tag = MKTAG('x','d','5','e');
1412 else if (rate == 30) tag = MKTAG('x','d','5','f');
1414 if (rate == 25) tag = MKTAG('x','d','5','c');
1415 else if (rate == 30) tag = MKTAG('x','d','5','b');
1423 static int mov_get_h264_codec_tag(AVFormatContext *s, MOVTrack *track)
1425 int tag = track->par->codec_tag;
1426 int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE;
1427 AVStream *st = track->st;
1428 int rate = defined_frame_rate(s, st);
1431 tag = MKTAG('a', 'v', 'c', 'i'); //fallback tag
1433 if (track->par->format == AV_PIX_FMT_YUV420P10) {
1434 if (track->par->width == 960 && track->par->height == 720) {
1436 if (rate == 24) tag = MKTAG('a','i','5','p');
1437 else if (rate == 25) tag = MKTAG('a','i','5','q');
1438 else if (rate == 30) tag = MKTAG('a','i','5','p');
1439 else if (rate == 50) tag = MKTAG('a','i','5','q');
1440 else if (rate == 60) tag = MKTAG('a','i','5','p');
1442 } else if (track->par->width == 1440 && track->par->height == 1080) {
1444 if (rate == 24) tag = MKTAG('a','i','5','3');
1445 else if (rate == 25) tag = MKTAG('a','i','5','2');
1446 else if (rate == 30) tag = MKTAG('a','i','5','3');
1448 if (rate == 50) tag = MKTAG('a','i','5','5');
1449 else if (rate == 60) tag = MKTAG('a','i','5','6');
1452 } else if (track->par->format == AV_PIX_FMT_YUV422P10) {
1453 if (track->par->width == 1280 && track->par->height == 720) {
1455 if (rate == 24) tag = MKTAG('a','i','1','p');
1456 else if (rate == 25) tag = MKTAG('a','i','1','q');
1457 else if (rate == 30) tag = MKTAG('a','i','1','p');
1458 else if (rate == 50) tag = MKTAG('a','i','1','q');
1459 else if (rate == 60) tag = MKTAG('a','i','1','p');
1461 } else if (track->par->width == 1920 && track->par->height == 1080) {
1463 if (rate == 24) tag = MKTAG('a','i','1','3');
1464 else if (rate == 25) tag = MKTAG('a','i','1','2');
1465 else if (rate == 30) tag = MKTAG('a','i','1','3');
1467 if (rate == 25) tag = MKTAG('a','i','1','5');
1468 else if (rate == 50) tag = MKTAG('a','i','1','5');
1469 else if (rate == 60) tag = MKTAG('a','i','1','6');
1471 } else if ( track->par->width == 4096 && track->par->height == 2160
1472 || track->par->width == 3840 && track->par->height == 2160
1473 || track->par->width == 2048 && track->par->height == 1080) {
1474 tag = MKTAG('a','i','v','x');
1481 static const struct {
1482 enum AVPixelFormat pix_fmt;
1485 } mov_pix_fmt_tags[] = {
1486 { AV_PIX_FMT_YUYV422, MKTAG('y','u','v','2'), 0 },
1487 { AV_PIX_FMT_YUYV422, MKTAG('y','u','v','s'), 0 },
1488 { AV_PIX_FMT_UYVY422, MKTAG('2','v','u','y'), 0 },
1489 { AV_PIX_FMT_RGB555BE,MKTAG('r','a','w',' '), 16 },
1490 { AV_PIX_FMT_RGB555LE,MKTAG('L','5','5','5'), 16 },
1491 { AV_PIX_FMT_RGB565LE,MKTAG('L','5','6','5'), 16 },
1492 { AV_PIX_FMT_RGB565BE,MKTAG('B','5','6','5'), 16 },
1493 { AV_PIX_FMT_GRAY16BE,MKTAG('b','1','6','g'), 16 },
1494 { AV_PIX_FMT_RGB24, MKTAG('r','a','w',' '), 24 },
1495 { AV_PIX_FMT_BGR24, MKTAG('2','4','B','G'), 24 },
1496 { AV_PIX_FMT_ARGB, MKTAG('r','a','w',' '), 32 },
1497 { AV_PIX_FMT_BGRA, MKTAG('B','G','R','A'), 32 },
1498 { AV_PIX_FMT_RGBA, MKTAG('R','G','B','A'), 32 },
1499 { AV_PIX_FMT_ABGR, MKTAG('A','B','G','R'), 32 },
1500 { AV_PIX_FMT_RGB48BE, MKTAG('b','4','8','r'), 48 },
1503 static int mov_get_dnxhd_codec_tag(AVFormatContext *s, MOVTrack *track)
1505 int tag = MKTAG('A','V','d','n');
1506 if (track->par->profile != FF_PROFILE_UNKNOWN &&
1507 track->par->profile != FF_PROFILE_DNXHD)
1508 tag = MKTAG('A','V','d','h');
1512 static int mov_get_rawvideo_codec_tag(AVFormatContext *s, MOVTrack *track)
1514 int tag = track->par->codec_tag;
1516 enum AVPixelFormat pix_fmt;
1518 for (i = 0; i < FF_ARRAY_ELEMS(mov_pix_fmt_tags); i++) {
1519 if (track->par->format == mov_pix_fmt_tags[i].pix_fmt) {
1520 tag = mov_pix_fmt_tags[i].tag;
1521 track->par->bits_per_coded_sample = mov_pix_fmt_tags[i].bps;
1522 if (track->par->codec_tag == mov_pix_fmt_tags[i].tag)
1527 pix_fmt = avpriv_find_pix_fmt(avpriv_pix_fmt_bps_mov,
1528 track->par->bits_per_coded_sample);
1529 if (tag == MKTAG('r','a','w',' ') &&
1530 track->par->format != pix_fmt &&
1531 track->par->format != AV_PIX_FMT_GRAY8 &&
1532 track->par->format != AV_PIX_FMT_NONE)
1533 av_log(s, AV_LOG_ERROR, "%s rawvideo cannot be written to mov, output file will be unreadable\n",
1534 av_get_pix_fmt_name(track->par->format));
1538 static 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)
1616 if (is_cover_image(track->st))
1617 return ff_codec_get_tag(codec_cover_image_tags, track->par->codec_id);
1619 if (track->mode == MODE_IPOD)
1620 if (!av_match_ext(s->url, "m4a") &&
1621 !av_match_ext(s->url, "m4v") &&
1622 !av_match_ext(s->url, "m4b"))
1623 av_log(s, AV_LOG_WARNING, "Warning, extension is not .m4a nor .m4v "
1624 "Quicktime/Ipod might not play the file\n");
1626 if (track->mode == MODE_MOV)
1627 tag = mov_get_codec_tag(s, track);
1629 tag = validate_codec_tag(s->oformat->codec_tag, track->par->codec_tag,
1630 track->par->codec_id);
1634 /** Write uuid atom.
1635 * Needed to make file play in iPods running newest firmware
1636 * goes after avcC atom in moov.trak.mdia.minf.stbl.stsd.avc1
1638 static int mov_write_uuid_tag_ipod(AVIOContext *pb)
1641 ffio_wfourcc(pb, "uuid");
1642 avio_wb32(pb, 0x6b6840f2);
1643 avio_wb32(pb, 0x5f244fc5);
1644 avio_wb32(pb, 0xba39a51b);
1645 avio_wb32(pb, 0xcf0323f3);
1650 static const uint16_t fiel_data[] = {
1651 0x0000, 0x0100, 0x0201, 0x0206, 0x0209, 0x020e
1654 static int mov_write_fiel_tag(AVIOContext *pb, MOVTrack *track, int field_order)
1656 unsigned mov_field_order = 0;
1657 if (field_order < FF_ARRAY_ELEMS(fiel_data))
1658 mov_field_order = fiel_data[field_order];
1662 ffio_wfourcc(pb, "fiel");
1663 avio_wb16(pb, mov_field_order);
1667 static int mov_write_subtitle_tag(AVIOContext *pb, MOVTrack *track)
1669 int64_t pos = avio_tell(pb);
1670 avio_wb32(pb, 0); /* size */
1671 avio_wl32(pb, track->tag); // store it byteswapped
1672 avio_wb32(pb, 0); /* Reserved */
1673 avio_wb16(pb, 0); /* Reserved */
1674 avio_wb16(pb, 1); /* Data-reference index */
1676 if (track->par->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
1677 mov_write_esds_tag(pb, track);
1678 else if (track->par->extradata_size)
1679 avio_write(pb, track->par->extradata, track->par->extradata_size);
1681 return update_size(pb, pos);
1684 static int mov_write_st3d_tag(AVIOContext *pb, AVStereo3D *stereo_3d)
1688 if (stereo_3d->flags != 0) {
1689 av_log(pb, AV_LOG_WARNING, "Unsupported stereo_3d flags %x. st3d not written.\n", stereo_3d->flags);
1693 switch (stereo_3d->type) {
1694 case AV_STEREO3D_2D:
1697 case AV_STEREO3D_TOPBOTTOM:
1700 case AV_STEREO3D_SIDEBYSIDE:
1704 av_log(pb, AV_LOG_WARNING, "Unsupported stereo_3d type %s. st3d not written.\n", av_stereo3d_type_name(stereo_3d->type));
1707 avio_wb32(pb, 13); /* size */
1708 ffio_wfourcc(pb, "st3d");
1709 avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1710 avio_w8(pb, stereo_mode);
1714 static int mov_write_sv3d_tag(AVFormatContext *s, AVIOContext *pb, AVSphericalMapping *spherical_mapping)
1716 int64_t sv3d_pos, svhd_pos, proj_pos;
1717 const char* metadata_source = s->flags & AVFMT_FLAG_BITEXACT ? "Lavf" : LIBAVFORMAT_IDENT;
1719 if (spherical_mapping->projection != AV_SPHERICAL_EQUIRECTANGULAR &&
1720 spherical_mapping->projection != AV_SPHERICAL_EQUIRECTANGULAR_TILE &&
1721 spherical_mapping->projection != AV_SPHERICAL_CUBEMAP) {
1722 av_log(pb, AV_LOG_WARNING, "Unsupported projection %d. sv3d not written.\n", spherical_mapping->projection);
1726 sv3d_pos = avio_tell(pb);
1727 avio_wb32(pb, 0); /* size */
1728 ffio_wfourcc(pb, "sv3d");
1730 svhd_pos = avio_tell(pb);
1731 avio_wb32(pb, 0); /* size */
1732 ffio_wfourcc(pb, "svhd");
1733 avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1734 avio_put_str(pb, metadata_source);
1735 update_size(pb, svhd_pos);
1737 proj_pos = avio_tell(pb);
1738 avio_wb32(pb, 0); /* size */
1739 ffio_wfourcc(pb, "proj");
1741 avio_wb32(pb, 24); /* size */
1742 ffio_wfourcc(pb, "prhd");
1743 avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1744 avio_wb32(pb, spherical_mapping->yaw);
1745 avio_wb32(pb, spherical_mapping->pitch);
1746 avio_wb32(pb, spherical_mapping->roll);
1748 switch (spherical_mapping->projection) {
1749 case AV_SPHERICAL_EQUIRECTANGULAR:
1750 case AV_SPHERICAL_EQUIRECTANGULAR_TILE:
1751 avio_wb32(pb, 28); /* size */
1752 ffio_wfourcc(pb, "equi");
1753 avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1754 avio_wb32(pb, spherical_mapping->bound_top);
1755 avio_wb32(pb, spherical_mapping->bound_bottom);
1756 avio_wb32(pb, spherical_mapping->bound_left);
1757 avio_wb32(pb, spherical_mapping->bound_right);
1759 case AV_SPHERICAL_CUBEMAP:
1760 avio_wb32(pb, 20); /* size */
1761 ffio_wfourcc(pb, "cbmp");
1762 avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1763 avio_wb32(pb, 0); /* layout */
1764 avio_wb32(pb, spherical_mapping->padding); /* padding */
1767 update_size(pb, proj_pos);
1769 return update_size(pb, sv3d_pos);
1772 static int mov_write_clap_tag(AVIOContext *pb, MOVTrack *track)
1775 ffio_wfourcc(pb, "clap");
1776 avio_wb32(pb, track->par->width); /* apertureWidth_N */
1777 avio_wb32(pb, 1); /* apertureWidth_D (= 1) */
1778 avio_wb32(pb, track->height); /* apertureHeight_N */
1779 avio_wb32(pb, 1); /* apertureHeight_D (= 1) */
1780 avio_wb32(pb, 0); /* horizOff_N (= 0) */
1781 avio_wb32(pb, 1); /* horizOff_D (= 1) */
1782 avio_wb32(pb, 0); /* vertOff_N (= 0) */
1783 avio_wb32(pb, 1); /* vertOff_D (= 1) */
1787 static int mov_write_pasp_tag(AVIOContext *pb, MOVTrack *track)
1790 av_reduce(&sar.num, &sar.den, track->par->sample_aspect_ratio.num,
1791 track->par->sample_aspect_ratio.den, INT_MAX);
1794 ffio_wfourcc(pb, "pasp");
1795 avio_wb32(pb, sar.num);
1796 avio_wb32(pb, sar.den);
1800 static int mov_write_gama_tag(AVIOContext *pb, MOVTrack *track, double gamma)
1805 gamma = avpriv_get_gamma_from_trc(track->par->color_trc);
1807 av_log(pb, AV_LOG_DEBUG, "gamma value %g\n", gamma);
1810 gama = (uint32_t)lrint((double)(1<<16) * gamma);
1811 av_log(pb, AV_LOG_DEBUG, "writing gama value %"PRId32"\n", gama);
1813 av_assert0(track->mode == MODE_MOV);
1815 ffio_wfourcc(pb, "gama");
1816 avio_wb32(pb, gama);
1820 av_log(pb, AV_LOG_WARNING, "gamma value unknown, unable to write gama atom\n");
1825 static int mov_write_colr_tag(AVIOContext *pb, MOVTrack *track)
1827 // Ref (MOV): https://developer.apple.com/library/mac/technotes/tn2162/_index.html#//apple_ref/doc/uid/DTS40013070-CH1-TNTAG9
1828 // Ref (MP4): ISO/IEC 14496-12:2012
1830 if (track->par->color_primaries == AVCOL_PRI_UNSPECIFIED &&
1831 track->par->color_trc == AVCOL_TRC_UNSPECIFIED &&
1832 track->par->color_space == AVCOL_SPC_UNSPECIFIED) {
1833 if ((track->par->width >= 1920 && track->par->height >= 1080)
1834 || (track->par->width == 1280 && track->par->height == 720)) {
1835 av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming bt709\n");
1836 track->par->color_primaries = AVCOL_PRI_BT709;
1837 } else if (track->par->width == 720 && track->height == 576) {
1838 av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming bt470bg\n");
1839 track->par->color_primaries = AVCOL_PRI_BT470BG;
1840 } else if (track->par->width == 720 &&
1841 (track->height == 486 || track->height == 480)) {
1842 av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming smpte170\n");
1843 track->par->color_primaries = AVCOL_PRI_SMPTE170M;
1845 av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, unable to assume anything\n");
1847 switch (track->par->color_primaries) {
1848 case AVCOL_PRI_BT709:
1849 track->par->color_trc = AVCOL_TRC_BT709;
1850 track->par->color_space = AVCOL_SPC_BT709;
1852 case AVCOL_PRI_SMPTE170M:
1853 case AVCOL_PRI_BT470BG:
1854 track->par->color_trc = AVCOL_TRC_BT709;
1855 track->par->color_space = AVCOL_SPC_SMPTE170M;
1860 /* We should only ever be called by MOV or MP4. */
1861 av_assert0(track->mode == MODE_MOV || track->mode == MODE_MP4);
1863 avio_wb32(pb, 18 + (track->mode == MODE_MP4));
1864 ffio_wfourcc(pb, "colr");
1865 if (track->mode == MODE_MP4)
1866 ffio_wfourcc(pb, "nclx");
1868 ffio_wfourcc(pb, "nclc");
1869 switch (track->par->color_primaries) {
1870 case AVCOL_PRI_BT709: avio_wb16(pb, 1); break;
1871 case AVCOL_PRI_BT470BG: avio_wb16(pb, 5); break;
1872 case AVCOL_PRI_SMPTE170M:
1873 case AVCOL_PRI_SMPTE240M: avio_wb16(pb, 6); break;
1874 case AVCOL_PRI_BT2020: avio_wb16(pb, 9); break;
1875 case AVCOL_PRI_SMPTE431: avio_wb16(pb, 11); break;
1876 case AVCOL_PRI_SMPTE432: avio_wb16(pb, 12); break;
1877 default: avio_wb16(pb, 2);
1879 switch (track->par->color_trc) {
1880 case AVCOL_TRC_BT709: avio_wb16(pb, 1); break;
1881 case AVCOL_TRC_SMPTE170M: avio_wb16(pb, 1); break; // remapped
1882 case AVCOL_TRC_SMPTE240M: avio_wb16(pb, 7); break;
1883 case AVCOL_TRC_SMPTEST2084: avio_wb16(pb, 16); break;
1884 case AVCOL_TRC_SMPTE428: avio_wb16(pb, 17); break;
1885 case AVCOL_TRC_ARIB_STD_B67: avio_wb16(pb, 18); break;
1886 default: avio_wb16(pb, 2);
1888 switch (track->par->color_space) {
1889 case AVCOL_SPC_BT709: avio_wb16(pb, 1); break;
1890 case AVCOL_SPC_BT470BG:
1891 case AVCOL_SPC_SMPTE170M: avio_wb16(pb, 6); break;
1892 case AVCOL_SPC_SMPTE240M: avio_wb16(pb, 7); break;
1893 case AVCOL_SPC_BT2020_NCL: avio_wb16(pb, 9); break;
1894 default: avio_wb16(pb, 2);
1897 if (track->mode == MODE_MP4) {
1898 int full_range = track->par->color_range == AVCOL_RANGE_JPEG;
1899 avio_w8(pb, full_range << 7);
1906 static void find_compressor(char * compressor_name, int len, MOVTrack *track)
1908 AVDictionaryEntry *encoder;
1909 int xdcam_res = (track->par->width == 1280 && track->par->height == 720)
1910 || (track->par->width == 1440 && track->par->height == 1080)
1911 || (track->par->width == 1920 && track->par->height == 1080);
1913 if (track->mode == MODE_MOV &&
1914 (encoder = av_dict_get(track->st->metadata, "encoder", NULL, 0))) {
1915 av_strlcpy(compressor_name, encoder->value, 32);
1916 } else if (track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO && xdcam_res) {
1917 int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE;
1918 AVStream *st = track->st;
1919 int rate = defined_frame_rate(NULL, st);
1920 av_strlcatf(compressor_name, len, "XDCAM");
1921 if (track->par->format == AV_PIX_FMT_YUV422P) {
1922 av_strlcatf(compressor_name, len, " HD422");
1923 } else if(track->par->width == 1440) {
1924 av_strlcatf(compressor_name, len, " HD");
1926 av_strlcatf(compressor_name, len, " EX");
1928 av_strlcatf(compressor_name, len, " %d%c", track->par->height, interlaced ? 'i' : 'p');
1930 av_strlcatf(compressor_name, len, "%d", rate * (interlaced + 1));
1934 static int mov_write_video_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
1936 int64_t pos = avio_tell(pb);
1937 char compressor_name[32] = { 0 };
1940 int uncompressed_ycbcr = ((track->par->codec_id == AV_CODEC_ID_RAWVIDEO && track->par->format == AV_PIX_FMT_UYVY422)
1941 || (track->par->codec_id == AV_CODEC_ID_RAWVIDEO && track->par->format == AV_PIX_FMT_YUYV422)
1942 || track->par->codec_id == AV_CODEC_ID_V308
1943 || track->par->codec_id == AV_CODEC_ID_V408
1944 || track->par->codec_id == AV_CODEC_ID_V410
1945 || track->par->codec_id == AV_CODEC_ID_V210);
1947 avio_wb32(pb, 0); /* size */
1948 if (mov->encryption_scheme != MOV_ENC_NONE) {
1949 ffio_wfourcc(pb, "encv");
1951 avio_wl32(pb, track->tag); // store it byteswapped
1953 avio_wb32(pb, 0); /* Reserved */
1954 avio_wb16(pb, 0); /* Reserved */
1955 avio_wb16(pb, 1); /* Data-reference index */
1957 if (uncompressed_ycbcr) {
1958 avio_wb16(pb, 2); /* Codec stream version */
1960 avio_wb16(pb, 0); /* Codec stream version */
1962 avio_wb16(pb, 0); /* Codec stream revision (=0) */
1963 if (track->mode == MODE_MOV) {
1964 ffio_wfourcc(pb, "FFMP"); /* Vendor */
1965 if (track->par->codec_id == AV_CODEC_ID_RAWVIDEO || uncompressed_ycbcr) {
1966 avio_wb32(pb, 0); /* Temporal Quality */
1967 avio_wb32(pb, 0x400); /* Spatial Quality = lossless*/
1969 avio_wb32(pb, 0x200); /* Temporal Quality = normal */
1970 avio_wb32(pb, 0x200); /* Spatial Quality = normal */
1973 avio_wb32(pb, 0); /* Reserved */
1974 avio_wb32(pb, 0); /* Reserved */
1975 avio_wb32(pb, 0); /* Reserved */
1977 avio_wb16(pb, track->par->width); /* Video width */
1978 avio_wb16(pb, track->height); /* Video height */
1979 avio_wb32(pb, 0x00480000); /* Horizontal resolution 72dpi */
1980 avio_wb32(pb, 0x00480000); /* Vertical resolution 72dpi */
1981 avio_wb32(pb, 0); /* Data size (= 0) */
1982 avio_wb16(pb, 1); /* Frame count (= 1) */
1984 /* FIXME not sure, ISO 14496-1 draft where it shall be set to 0 */
1985 find_compressor(compressor_name, 32, track);
1986 avio_w8(pb, strlen(compressor_name));
1987 avio_write(pb, compressor_name, 31);
1989 if (track->mode == MODE_MOV &&
1990 (track->par->codec_id == AV_CODEC_ID_V410 || track->par->codec_id == AV_CODEC_ID_V210))
1991 avio_wb16(pb, 0x18);
1992 else if (track->mode == MODE_MOV && track->par->bits_per_coded_sample)
1993 avio_wb16(pb, track->par->bits_per_coded_sample |
1994 (track->par->format == AV_PIX_FMT_GRAY8 ? 0x20 : 0));
1996 avio_wb16(pb, 0x18); /* Reserved */
1998 if (track->mode == MODE_MOV && track->par->format == AV_PIX_FMT_PAL8) {
1999 int pal_size = 1 << track->par->bits_per_coded_sample;
2001 avio_wb16(pb, 0); /* Color table ID */
2002 avio_wb32(pb, 0); /* Color table seed */
2003 avio_wb16(pb, 0x8000); /* Color table flags */
2004 avio_wb16(pb, pal_size - 1); /* Color table size (zero-relative) */
2005 for (i = 0; i < pal_size; i++) {
2006 uint32_t rgb = track->palette[i];
2007 uint16_t r = (rgb >> 16) & 0xff;
2008 uint16_t g = (rgb >> 8) & 0xff;
2009 uint16_t b = rgb & 0xff;
2011 avio_wb16(pb, (r << 8) | r);
2012 avio_wb16(pb, (g << 8) | g);
2013 avio_wb16(pb, (b << 8) | b);
2016 avio_wb16(pb, 0xffff); /* Reserved */
2018 if (track->tag == MKTAG('m','p','4','v'))
2019 mov_write_esds_tag(pb, track);
2020 else if (track->par->codec_id == AV_CODEC_ID_H263)
2021 mov_write_d263_tag(pb);
2022 else if (track->par->codec_id == AV_CODEC_ID_AVUI ||
2023 track->par->codec_id == AV_CODEC_ID_SVQ3) {
2024 mov_write_extradata_tag(pb, track);
2026 } else if (track->par->codec_id == AV_CODEC_ID_DNXHD) {
2027 mov_write_avid_tag(pb, track);
2029 } else if (track->par->codec_id == AV_CODEC_ID_HEVC)
2030 mov_write_hvcc_tag(pb, track);
2031 else if (track->par->codec_id == AV_CODEC_ID_H264 && !TAG_IS_AVCI(track->tag)) {
2032 mov_write_avcc_tag(pb, track);
2033 if (track->mode == MODE_IPOD)
2034 mov_write_uuid_tag_ipod(pb);
2035 } else if (track->par->codec_id == AV_CODEC_ID_VP9) {
2036 mov_write_vpcc_tag(mov->fc, pb, track);
2037 } else if (track->par->codec_id == AV_CODEC_ID_AV1) {
2038 mov_write_av1c_tag(pb, track);
2039 } else if (track->par->codec_id == AV_CODEC_ID_VC1 && track->vos_len > 0)
2040 mov_write_dvc1_tag(pb, track);
2041 else if (track->par->codec_id == AV_CODEC_ID_VP6F ||
2042 track->par->codec_id == AV_CODEC_ID_VP6A) {
2043 /* Don't write any potential extradata here - the cropping
2044 * is signalled via the normal width/height fields. */
2045 } else if (track->par->codec_id == AV_CODEC_ID_R10K) {
2046 if (track->par->codec_tag == MKTAG('R','1','0','k'))
2047 mov_write_dpxe_tag(pb, track);
2048 } else if (track->vos_len > 0)
2049 mov_write_glbl_tag(pb, track);
2051 if (track->par->codec_id != AV_CODEC_ID_H264 &&
2052 track->par->codec_id != AV_CODEC_ID_MPEG4 &&
2053 track->par->codec_id != AV_CODEC_ID_DNXHD) {
2054 int field_order = track->par->field_order;
2056 #if FF_API_LAVF_AVCTX
2057 FF_DISABLE_DEPRECATION_WARNINGS
2058 if (field_order != track->st->codec->field_order && track->st->codec->field_order != AV_FIELD_UNKNOWN)
2059 field_order = track->st->codec->field_order;
2060 FF_ENABLE_DEPRECATION_WARNINGS
2063 if (field_order != AV_FIELD_UNKNOWN)
2064 mov_write_fiel_tag(pb, track, field_order);
2067 if (mov->flags & FF_MOV_FLAG_WRITE_GAMA) {
2068 if (track->mode == MODE_MOV)
2069 mov_write_gama_tag(pb, track, mov->gamma);
2071 av_log(mov->fc, AV_LOG_WARNING, "Not writing 'gama' atom. Format is not MOV.\n");
2073 if (mov->flags & FF_MOV_FLAG_WRITE_COLR) {
2074 if (track->mode == MODE_MOV || track->mode == MODE_MP4)
2075 mov_write_colr_tag(pb, track);
2077 av_log(mov->fc, AV_LOG_WARNING, "Not writing 'colr' atom. Format is not MOV or MP4.\n");
2080 if (track->mode == MODE_MP4 && mov->fc->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL) {
2081 AVStereo3D* stereo_3d = (AVStereo3D*) av_stream_get_side_data(track->st, AV_PKT_DATA_STEREO3D, NULL);
2082 AVSphericalMapping* spherical_mapping = (AVSphericalMapping*)av_stream_get_side_data(track->st, AV_PKT_DATA_SPHERICAL, NULL);
2085 mov_write_st3d_tag(pb, stereo_3d);
2086 if (spherical_mapping)
2087 mov_write_sv3d_tag(mov->fc, pb, spherical_mapping);
2090 if (track->par->sample_aspect_ratio.den && track->par->sample_aspect_ratio.num) {
2091 mov_write_pasp_tag(pb, track);
2094 if (uncompressed_ycbcr){
2095 mov_write_clap_tag(pb, track);
2098 if (mov->encryption_scheme != MOV_ENC_NONE) {
2099 ff_mov_cenc_write_sinf_tag(track, pb, mov->encryption_kid);
2102 /* extra padding for avid stsd */
2103 /* https://developer.apple.com/library/mac/documentation/QuickTime/QTFF/QTFFChap2/qtff2.html#//apple_ref/doc/uid/TP40000939-CH204-61112 */
2107 return update_size(pb, pos);
2110 static int mov_write_rtp_tag(AVIOContext *pb, MOVTrack *track)
2112 int64_t pos = avio_tell(pb);
2113 avio_wb32(pb, 0); /* size */
2114 ffio_wfourcc(pb, "rtp ");
2115 avio_wb32(pb, 0); /* Reserved */
2116 avio_wb16(pb, 0); /* Reserved */
2117 avio_wb16(pb, 1); /* Data-reference index */
2119 avio_wb16(pb, 1); /* Hint track version */
2120 avio_wb16(pb, 1); /* Highest compatible version */
2121 avio_wb32(pb, track->max_packet_size); /* Max packet size */
2123 avio_wb32(pb, 12); /* size */
2124 ffio_wfourcc(pb, "tims");
2125 avio_wb32(pb, track->timescale);
2127 return update_size(pb, pos);
2130 static int mov_write_source_reference_tag(AVIOContext *pb, MOVTrack *track, const char *reel_name)
2132 uint64_t str_size =strlen(reel_name);
2133 int64_t pos = avio_tell(pb);
2135 if (str_size >= UINT16_MAX){
2136 av_log(NULL, AV_LOG_ERROR, "reel_name length %"PRIu64" is too large\n", str_size);
2138 return AVERROR(EINVAL);
2141 avio_wb32(pb, 0); /* size */
2142 ffio_wfourcc(pb, "name"); /* Data format */
2143 avio_wb16(pb, str_size); /* string size */
2144 avio_wb16(pb, track->language); /* langcode */
2145 avio_write(pb, reel_name, str_size); /* reel name */
2146 return update_size(pb,pos);
2149 static int mov_write_tmcd_tag(AVIOContext *pb, MOVTrack *track)
2151 int64_t pos = avio_tell(pb);
2155 AVDictionaryEntry *t = NULL;
2157 if (!track->st->avg_frame_rate.num || !track->st->avg_frame_rate.den) {
2158 #if FF_API_LAVF_AVCTX
2159 FF_DISABLE_DEPRECATION_WARNINGS
2160 frame_duration = av_rescale(track->timescale, track->st->codec->time_base.num, track->st->codec->time_base.den);
2161 nb_frames = ROUNDED_DIV(track->st->codec->time_base.den, track->st->codec->time_base.num);
2162 FF_ENABLE_DEPRECATION_WARNINGS
2164 av_log(NULL, AV_LOG_ERROR, "avg_frame_rate not set for tmcd track.\n");
2165 return AVERROR(EINVAL);
2168 frame_duration = av_rescale(track->timescale, track->st->avg_frame_rate.num, track->st->avg_frame_rate.den);
2169 nb_frames = ROUNDED_DIV(track->st->avg_frame_rate.den, track->st->avg_frame_rate.num);
2172 if (nb_frames > 255) {
2173 av_log(NULL, AV_LOG_ERROR, "fps %d is too large\n", nb_frames);
2174 return AVERROR(EINVAL);
2177 avio_wb32(pb, 0); /* size */
2178 ffio_wfourcc(pb, "tmcd"); /* Data format */
2179 avio_wb32(pb, 0); /* Reserved */
2180 avio_wb32(pb, 1); /* Data reference index */
2181 avio_wb32(pb, 0); /* Flags */
2182 avio_wb32(pb, track->timecode_flags); /* Flags (timecode) */
2183 avio_wb32(pb, track->timescale); /* Timescale */
2184 avio_wb32(pb, frame_duration); /* Frame duration */
2185 avio_w8(pb, nb_frames); /* Number of frames */
2186 avio_w8(pb, 0); /* Reserved */
2188 t = av_dict_get(track->st->metadata, "reel_name", NULL, 0);
2189 if (t && utf8len(t->value) && track->mode != MODE_MP4)
2190 mov_write_source_reference_tag(pb, track, t->value);
2192 avio_wb16(pb, 0); /* zero size */
2195 avio_wb32(pb, 0); /* size */
2196 ffio_wfourcc(pb, "tmcd"); /* Data format */
2197 avio_wb32(pb, 0); /* Reserved */
2198 avio_wb32(pb, 1); /* Data reference index */
2199 if (track->par->extradata_size)
2200 avio_write(pb, track->par->extradata, track->par->extradata_size);
2202 return update_size(pb, pos);
2205 static int mov_write_gpmd_tag(AVIOContext *pb, const MOVTrack *track)
2207 int64_t pos = avio_tell(pb);
2208 avio_wb32(pb, 0); /* size */
2209 ffio_wfourcc(pb, "gpmd");
2210 avio_wb32(pb, 0); /* Reserved */
2211 avio_wb16(pb, 0); /* Reserved */
2212 avio_wb16(pb, 1); /* Data-reference index */
2213 avio_wb32(pb, 0); /* Reserved */
2214 return update_size(pb, pos);
2217 static int mov_write_stsd_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
2219 int64_t pos = avio_tell(pb);
2220 avio_wb32(pb, 0); /* size */
2221 ffio_wfourcc(pb, "stsd");
2222 avio_wb32(pb, 0); /* version & flags */
2223 avio_wb32(pb, 1); /* entry count */
2224 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO)
2225 mov_write_video_tag(pb, mov, track);
2226 else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
2227 mov_write_audio_tag(s, pb, mov, track);
2228 else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)
2229 mov_write_subtitle_tag(pb, track);
2230 else if (track->par->codec_tag == MKTAG('r','t','p',' '))
2231 mov_write_rtp_tag(pb, track);
2232 else if (track->par->codec_tag == MKTAG('t','m','c','d'))
2233 mov_write_tmcd_tag(pb, track);
2234 else if (track->par->codec_tag == MKTAG('g','p','m','d'))
2235 mov_write_gpmd_tag(pb, track);
2236 return update_size(pb, pos);
2239 static int mov_write_ctts_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
2241 MOVMuxContext *mov = s->priv_data;
2242 MOVStts *ctts_entries;
2243 uint32_t entries = 0;
2247 ctts_entries = av_malloc_array((track->entry + 1), sizeof(*ctts_entries)); /* worst case */
2249 return AVERROR(ENOMEM);
2250 ctts_entries[0].count = 1;
2251 ctts_entries[0].duration = track->cluster[0].cts;
2252 for (i = 1; i < track->entry; i++) {
2253 if (track->cluster[i].cts == ctts_entries[entries].duration) {
2254 ctts_entries[entries].count++; /* compress */
2257 ctts_entries[entries].duration = track->cluster[i].cts;
2258 ctts_entries[entries].count = 1;
2261 entries++; /* last one */
2262 atom_size = 16 + (entries * 8);
2263 avio_wb32(pb, atom_size); /* size */
2264 ffio_wfourcc(pb, "ctts");
2265 if (mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS)
2266 avio_w8(pb, 1); /* version */
2268 avio_w8(pb, 0); /* version */
2269 avio_wb24(pb, 0); /* flags */
2270 avio_wb32(pb, entries); /* entry count */
2271 for (i = 0; i < entries; i++) {
2272 avio_wb32(pb, ctts_entries[i].count);
2273 avio_wb32(pb, ctts_entries[i].duration);
2275 av_free(ctts_entries);
2279 /* Time to sample atom */
2280 static int mov_write_stts_tag(AVIOContext *pb, MOVTrack *track)
2282 MOVStts *stts_entries = NULL;
2283 uint32_t entries = -1;
2287 if (track->par->codec_type == AVMEDIA_TYPE_AUDIO && !track->audio_vbr) {
2288 stts_entries = av_malloc(sizeof(*stts_entries)); /* one entry */
2290 return AVERROR(ENOMEM);
2291 stts_entries[0].count = track->sample_count;
2292 stts_entries[0].duration = 1;
2296 stts_entries = av_malloc_array(track->entry, sizeof(*stts_entries)); /* worst case */
2298 return AVERROR(ENOMEM);
2300 for (i = 0; i < track->entry; i++) {
2301 int duration = get_cluster_duration(track, i);
2302 if (i && duration == stts_entries[entries].duration) {
2303 stts_entries[entries].count++; /* compress */
2306 stts_entries[entries].duration = duration;
2307 stts_entries[entries].count = 1;
2310 entries++; /* last one */
2312 atom_size = 16 + (entries * 8);
2313 avio_wb32(pb, atom_size); /* size */
2314 ffio_wfourcc(pb, "stts");
2315 avio_wb32(pb, 0); /* version & flags */
2316 avio_wb32(pb, entries); /* entry count */
2317 for (i = 0; i < entries; i++) {
2318 avio_wb32(pb, stts_entries[i].count);
2319 avio_wb32(pb, stts_entries[i].duration);
2321 av_free(stts_entries);
2325 static int mov_write_dref_tag(AVIOContext *pb)
2327 avio_wb32(pb, 28); /* size */
2328 ffio_wfourcc(pb, "dref");
2329 avio_wb32(pb, 0); /* version & flags */
2330 avio_wb32(pb, 1); /* entry count */
2332 avio_wb32(pb, 0xc); /* size */
2333 //FIXME add the alis and rsrc atom
2334 ffio_wfourcc(pb, "url ");
2335 avio_wb32(pb, 1); /* version & flags */
2340 static int mov_preroll_write_stbl_atoms(AVIOContext *pb, MOVTrack *track)
2344 int16_t roll_distance;
2345 int group_description_index;
2348 struct sgpd_entry *sgpd_entries = NULL;
2353 const int OPUS_SEEK_PREROLL_MS = 80;
2354 int roll_samples = av_rescale_q(OPUS_SEEK_PREROLL_MS,
2355 (AVRational){1, 1000},
2356 (AVRational){1, 48000});
2361 sgpd_entries = av_malloc_array(track->entry, sizeof(*sgpd_entries));
2363 return AVERROR(ENOMEM);
2365 av_assert0(track->par->codec_id == AV_CODEC_ID_OPUS || track->par->codec_id == AV_CODEC_ID_AAC);
2367 if (track->par->codec_id == AV_CODEC_ID_OPUS) {
2368 for (i = 0; i < track->entry; i++) {
2369 int roll_samples_remaining = roll_samples;
2371 for (j = i - 1; j >= 0; j--) {
2372 roll_samples_remaining -= get_cluster_duration(track, j);
2374 if (roll_samples_remaining <= 0)
2377 /* We don't have enough preceeding samples to compute a valid
2378 roll_distance here, so this sample can't be independently
2380 if (roll_samples_remaining > 0)
2382 /* Verify distance is a maximum of 32 (2.5ms) packets. */
2384 return AVERROR_INVALIDDATA;
2385 if (i && distance == sgpd_entries[entries].roll_distance) {
2386 sgpd_entries[entries].count++;
2389 sgpd_entries[entries].count = 1;
2390 sgpd_entries[entries].roll_distance = distance;
2391 sgpd_entries[entries].group_description_index = distance ? ++group : 0;
2396 sgpd_entries[entries].count = track->sample_count;
2397 sgpd_entries[entries].roll_distance = 1;
2398 sgpd_entries[entries].group_description_index = ++group;
2403 av_free(sgpd_entries);
2407 /* Write sgpd tag */
2408 avio_wb32(pb, 24 + (group * 2)); /* size */
2409 ffio_wfourcc(pb, "sgpd");
2410 avio_wb32(pb, 1 << 24); /* fullbox */
2411 ffio_wfourcc(pb, "roll");
2412 avio_wb32(pb, 2); /* default_length */
2413 avio_wb32(pb, group); /* entry_count */
2414 for (i = 0; i < entries; i++) {
2415 if (sgpd_entries[i].group_description_index) {
2416 avio_wb16(pb, -sgpd_entries[i].roll_distance); /* roll_distance */
2420 /* Write sbgp tag */
2421 avio_wb32(pb, 20 + (entries * 8)); /* size */
2422 ffio_wfourcc(pb, "sbgp");
2423 avio_wb32(pb, 0); /* fullbox */
2424 ffio_wfourcc(pb, "roll");
2425 avio_wb32(pb, entries); /* entry_count */
2426 for (i = 0; i < entries; i++) {
2427 avio_wb32(pb, sgpd_entries[i].count); /* sample_count */
2428 avio_wb32(pb, sgpd_entries[i].group_description_index); /* group_description_index */
2431 av_free(sgpd_entries);
2435 static int mov_write_stbl_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
2437 int64_t pos = avio_tell(pb);
2440 avio_wb32(pb, 0); /* size */
2441 ffio_wfourcc(pb, "stbl");
2442 mov_write_stsd_tag(s, pb, mov, track);
2443 mov_write_stts_tag(pb, track);
2444 if ((track->par->codec_type == AVMEDIA_TYPE_VIDEO ||
2445 track->par->codec_tag == MKTAG('r','t','p',' ')) &&
2446 track->has_keyframes && track->has_keyframes < track->entry)
2447 mov_write_stss_tag(pb, track, MOV_SYNC_SAMPLE);
2448 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO && track->has_disposable)
2449 mov_write_sdtp_tag(pb, track);
2450 if (track->mode == MODE_MOV && track->flags & MOV_TRACK_STPS)
2451 mov_write_stss_tag(pb, track, MOV_PARTIAL_SYNC_SAMPLE);
2452 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO &&
2453 track->flags & MOV_TRACK_CTTS && track->entry) {
2455 if ((ret = mov_write_ctts_tag(s, pb, track)) < 0)
2458 mov_write_stsc_tag(pb, track);
2459 mov_write_stsz_tag(pb, track);
2460 mov_write_stco_tag(pb, track);
2461 if (track->cenc.aes_ctr) {
2462 ff_mov_cenc_write_stbl_atoms(&track->cenc, pb);
2464 if (track->par->codec_id == AV_CODEC_ID_OPUS || track->par->codec_id == AV_CODEC_ID_AAC) {
2465 mov_preroll_write_stbl_atoms(pb, track);
2467 return update_size(pb, pos);
2470 static int mov_write_dinf_tag(AVIOContext *pb)
2472 int64_t pos = avio_tell(pb);
2473 avio_wb32(pb, 0); /* size */
2474 ffio_wfourcc(pb, "dinf");
2475 mov_write_dref_tag(pb);
2476 return update_size(pb, pos);
2479 static int mov_write_nmhd_tag(AVIOContext *pb)
2482 ffio_wfourcc(pb, "nmhd");
2487 static int mov_write_tcmi_tag(AVIOContext *pb, MOVTrack *track)
2489 int64_t pos = avio_tell(pb);
2490 const char *font = "Lucida Grande";
2491 avio_wb32(pb, 0); /* size */
2492 ffio_wfourcc(pb, "tcmi"); /* timecode media information atom */
2493 avio_wb32(pb, 0); /* version & flags */
2494 avio_wb16(pb, 0); /* text font */
2495 avio_wb16(pb, 0); /* text face */
2496 avio_wb16(pb, 12); /* text size */
2497 avio_wb16(pb, 0); /* (unknown, not in the QT specs...) */
2498 avio_wb16(pb, 0x0000); /* text color (red) */
2499 avio_wb16(pb, 0x0000); /* text color (green) */
2500 avio_wb16(pb, 0x0000); /* text color (blue) */
2501 avio_wb16(pb, 0xffff); /* background color (red) */
2502 avio_wb16(pb, 0xffff); /* background color (green) */
2503 avio_wb16(pb, 0xffff); /* background color (blue) */
2504 avio_w8(pb, strlen(font)); /* font len (part of the pascal string) */
2505 avio_write(pb, font, strlen(font)); /* font name */
2506 return update_size(pb, pos);
2509 static int mov_write_gmhd_tag(AVIOContext *pb, MOVTrack *track)
2511 int64_t pos = avio_tell(pb);
2512 avio_wb32(pb, 0); /* size */
2513 ffio_wfourcc(pb, "gmhd");
2514 avio_wb32(pb, 0x18); /* gmin size */
2515 ffio_wfourcc(pb, "gmin");/* generic media info */
2516 avio_wb32(pb, 0); /* version & flags */
2517 avio_wb16(pb, 0x40); /* graphics mode = */
2518 avio_wb16(pb, 0x8000); /* opColor (r?) */
2519 avio_wb16(pb, 0x8000); /* opColor (g?) */
2520 avio_wb16(pb, 0x8000); /* opColor (b?) */
2521 avio_wb16(pb, 0); /* balance */
2522 avio_wb16(pb, 0); /* reserved */
2525 * This special text atom is required for
2526 * Apple Quicktime chapters. The contents
2527 * don't appear to be documented, so the
2528 * bytes are copied verbatim.
2530 if (track->tag != MKTAG('c','6','0','8')) {
2531 avio_wb32(pb, 0x2C); /* size */
2532 ffio_wfourcc(pb, "text");
2533 avio_wb16(pb, 0x01);
2534 avio_wb32(pb, 0x00);
2535 avio_wb32(pb, 0x00);
2536 avio_wb32(pb, 0x00);
2537 avio_wb32(pb, 0x01);
2538 avio_wb32(pb, 0x00);
2539 avio_wb32(pb, 0x00);
2540 avio_wb32(pb, 0x00);
2541 avio_wb32(pb, 0x00004000);
2542 avio_wb16(pb, 0x0000);
2545 if (track->par->codec_tag == MKTAG('t','m','c','d')) {
2546 int64_t tmcd_pos = avio_tell(pb);
2547 avio_wb32(pb, 0); /* size */
2548 ffio_wfourcc(pb, "tmcd");
2549 mov_write_tcmi_tag(pb, track);
2550 update_size(pb, tmcd_pos);
2551 } else if (track->par->codec_tag == MKTAG('g','p','m','d')) {
2552 int64_t gpmd_pos = avio_tell(pb);
2553 avio_wb32(pb, 0); /* size */
2554 ffio_wfourcc(pb, "gpmd");
2555 avio_wb32(pb, 0); /* version */
2556 update_size(pb, gpmd_pos);
2558 return update_size(pb, pos);
2561 static int mov_write_smhd_tag(AVIOContext *pb)
2563 avio_wb32(pb, 16); /* size */
2564 ffio_wfourcc(pb, "smhd");
2565 avio_wb32(pb, 0); /* version & flags */
2566 avio_wb16(pb, 0); /* reserved (balance, normally = 0) */
2567 avio_wb16(pb, 0); /* reserved */
2571 static int mov_write_vmhd_tag(AVIOContext *pb)
2573 avio_wb32(pb, 0x14); /* size (always 0x14) */
2574 ffio_wfourcc(pb, "vmhd");
2575 avio_wb32(pb, 0x01); /* version & flags */
2576 avio_wb64(pb, 0); /* reserved (graphics mode = copy) */
2580 static int is_clcp_track(MOVTrack *track)
2582 return track->tag == MKTAG('c','7','0','8') ||
2583 track->tag == MKTAG('c','6','0','8');
2586 static int mov_write_hdlr_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
2588 MOVMuxContext *mov = s->priv_data;
2589 const char *hdlr, *descr = NULL, *hdlr_type = NULL;
2590 int64_t pos = avio_tell(pb);
2594 descr = "DataHandler";
2597 hdlr = (track->mode == MODE_MOV) ? "mhlr" : "\0\0\0\0";
2598 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
2600 descr = "VideoHandler";
2601 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
2603 descr = "SoundHandler";
2604 } else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE) {
2605 if (is_clcp_track(track)) {
2607 descr = "ClosedCaptionHandler";
2609 if (track->tag == MKTAG('t','x','3','g')) {
2611 } else if (track->tag == MKTAG('m','p','4','s')) {
2616 descr = "SubtitleHandler";
2618 } else if (track->par->codec_tag == MKTAG('r','t','p',' ')) {
2620 descr = "HintHandler";
2621 } else if (track->par->codec_tag == MKTAG('t','m','c','d')) {
2623 descr = "TimeCodeHandler";
2624 } else if (track->par->codec_tag == MKTAG('g','p','m','d')) {
2626 descr = "GoPro MET"; // GoPro Metadata
2628 av_log(s, AV_LOG_WARNING,
2629 "Unknown hldr_type for %s, writing dummy values\n",
2630 av_fourcc2str(track->par->codec_tag));
2633 // hdlr.name is used by some players to identify the content title
2634 // of the track. So if an alternate handler description is
2635 // specified, use it.
2636 AVDictionaryEntry *t;
2637 t = av_dict_get(track->st->metadata, "handler_name", NULL, 0);
2638 if (t && utf8len(t->value))
2643 if (mov->empty_hdlr_name) /* expressly allowed by QTFF and not prohibited in ISO 14496-12 8.4.3.3 */
2646 avio_wb32(pb, 0); /* size */
2647 ffio_wfourcc(pb, "hdlr");
2648 avio_wb32(pb, 0); /* Version & flags */
2649 avio_write(pb, hdlr, 4); /* handler */
2650 ffio_wfourcc(pb, hdlr_type); /* handler type */
2651 avio_wb32(pb, 0); /* reserved */
2652 avio_wb32(pb, 0); /* reserved */
2653 avio_wb32(pb, 0); /* reserved */
2654 if (!track || track->mode == MODE_MOV)
2655 avio_w8(pb, strlen(descr)); /* pascal string */
2656 avio_write(pb, descr, strlen(descr)); /* handler description */
2657 if (track && track->mode != MODE_MOV)
2658 avio_w8(pb, 0); /* c string */
2659 return update_size(pb, pos);
2662 static int mov_write_hmhd_tag(AVIOContext *pb)
2664 /* This atom must be present, but leaving the values at zero
2665 * seems harmless. */
2666 avio_wb32(pb, 28); /* size */
2667 ffio_wfourcc(pb, "hmhd");
2668 avio_wb32(pb, 0); /* version, flags */
2669 avio_wb16(pb, 0); /* maxPDUsize */
2670 avio_wb16(pb, 0); /* avgPDUsize */
2671 avio_wb32(pb, 0); /* maxbitrate */
2672 avio_wb32(pb, 0); /* avgbitrate */
2673 avio_wb32(pb, 0); /* reserved */
2677 static int mov_write_minf_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
2679 int64_t pos = avio_tell(pb);
2682 avio_wb32(pb, 0); /* size */
2683 ffio_wfourcc(pb, "minf");
2684 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO)
2685 mov_write_vmhd_tag(pb);
2686 else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
2687 mov_write_smhd_tag(pb);
2688 else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE) {
2689 if (track->tag == MKTAG('t','e','x','t') || is_clcp_track(track)) {
2690 mov_write_gmhd_tag(pb, track);
2692 mov_write_nmhd_tag(pb);
2694 } else if (track->tag == MKTAG('r','t','p',' ')) {
2695 mov_write_hmhd_tag(pb);
2696 } else if (track->tag == MKTAG('t','m','c','d')) {
2697 if (track->mode != MODE_MOV)
2698 mov_write_nmhd_tag(pb);
2700 mov_write_gmhd_tag(pb, track);
2701 } else if (track->tag == MKTAG('g','p','m','d')) {
2702 mov_write_gmhd_tag(pb, track);
2704 if (track->mode == MODE_MOV) /* ISO 14496-12 8.4.3.1 specifies hdlr only within mdia or meta boxes */
2705 mov_write_hdlr_tag(s, pb, NULL);
2706 mov_write_dinf_tag(pb);
2707 if ((ret = mov_write_stbl_tag(s, pb, mov, track)) < 0)
2709 return update_size(pb, pos);
2712 static int mov_write_mdhd_tag(AVIOContext *pb, MOVMuxContext *mov,
2715 int version = track->track_duration < INT32_MAX ? 0 : 1;
2717 if (track->mode == MODE_ISM)
2720 (version == 1) ? avio_wb32(pb, 44) : avio_wb32(pb, 32); /* size */
2721 ffio_wfourcc(pb, "mdhd");
2722 avio_w8(pb, version);
2723 avio_wb24(pb, 0); /* flags */
2725 avio_wb64(pb, track->time);
2726 avio_wb64(pb, track->time);
2728 avio_wb32(pb, track->time); /* creation time */
2729 avio_wb32(pb, track->time); /* modification time */
2731 avio_wb32(pb, track->timescale); /* time scale (sample rate for audio) */
2732 if (!track->entry && mov->mode == MODE_ISM)
2733 (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
2734 else if (!track->entry)
2735 (version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0);
2737 (version == 1) ? avio_wb64(pb, track->track_duration) : avio_wb32(pb, track->track_duration); /* duration */
2738 avio_wb16(pb, track->language); /* language */
2739 avio_wb16(pb, 0); /* reserved (quality) */
2741 if (version != 0 && track->mode == MODE_MOV) {
2742 av_log(NULL, AV_LOG_ERROR,
2743 "FATAL error, file duration too long for timebase, this file will not be\n"
2744 "playable with quicktime. Choose a different timebase or a different\n"
2745 "container format\n");
2751 static int mov_write_mdia_tag(AVFormatContext *s, AVIOContext *pb,
2752 MOVMuxContext *mov, MOVTrack *track)
2754 int64_t pos = avio_tell(pb);
2757 avio_wb32(pb, 0); /* size */
2758 ffio_wfourcc(pb, "mdia");
2759 mov_write_mdhd_tag(pb, mov, track);
2760 mov_write_hdlr_tag(s, pb, track);
2761 if ((ret = mov_write_minf_tag(s, pb, mov, track)) < 0)
2763 return update_size(pb, pos);
2766 /* transformation matrix
2770 static void write_matrix(AVIOContext *pb, int16_t a, int16_t b, int16_t c,
2771 int16_t d, int16_t tx, int16_t ty)
2773 avio_wb32(pb, a << 16); /* 16.16 format */
2774 avio_wb32(pb, b << 16); /* 16.16 format */
2775 avio_wb32(pb, 0); /* u in 2.30 format */
2776 avio_wb32(pb, c << 16); /* 16.16 format */
2777 avio_wb32(pb, d << 16); /* 16.16 format */
2778 avio_wb32(pb, 0); /* v in 2.30 format */
2779 avio_wb32(pb, tx << 16); /* 16.16 format */
2780 avio_wb32(pb, ty << 16); /* 16.16 format */
2781 avio_wb32(pb, 1 << 30); /* w in 2.30 format */
2784 static int mov_write_tkhd_tag(AVIOContext *pb, MOVMuxContext *mov,
2785 MOVTrack *track, AVStream *st)
2787 int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE,
2788 track->timescale, AV_ROUND_UP);
2789 int version = duration < INT32_MAX ? 0 : 1;
2790 int flags = MOV_TKHD_FLAG_IN_MOVIE;
2794 uint32_t *display_matrix = NULL;
2795 int display_matrix_size, i;
2798 if (mov->per_stream_grouping)
2801 group = st->codecpar->codec_type;
2803 display_matrix = (uint32_t*)av_stream_get_side_data(st, AV_PKT_DATA_DISPLAYMATRIX,
2804 &display_matrix_size);
2805 if (display_matrix && display_matrix_size < 9 * sizeof(*display_matrix))
2806 display_matrix = NULL;
2809 if (track->flags & MOV_TRACK_ENABLED)
2810 flags |= MOV_TKHD_FLAG_ENABLED;
2812 if (track->mode == MODE_ISM)
2815 (version == 1) ? avio_wb32(pb, 104) : avio_wb32(pb, 92); /* size */
2816 ffio_wfourcc(pb, "tkhd");
2817 avio_w8(pb, version);
2818 avio_wb24(pb, flags);
2820 avio_wb64(pb, track->time);
2821 avio_wb64(pb, track->time);
2823 avio_wb32(pb, track->time); /* creation time */
2824 avio_wb32(pb, track->time); /* modification time */
2826 avio_wb32(pb, track->track_id); /* track-id */
2827 avio_wb32(pb, 0); /* reserved */
2828 if (!track->entry && mov->mode == MODE_ISM)
2829 (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
2830 else if (!track->entry)
2831 (version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0);
2833 (version == 1) ? avio_wb64(pb, duration) : avio_wb32(pb, duration);
2835 avio_wb32(pb, 0); /* reserved */
2836 avio_wb32(pb, 0); /* reserved */
2837 avio_wb16(pb, 0); /* layer */
2838 avio_wb16(pb, group); /* alternate group) */
2839 /* Volume, only for audio */
2840 if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
2841 avio_wb16(pb, 0x0100);
2844 avio_wb16(pb, 0); /* reserved */
2846 /* Matrix structure */
2847 #if FF_API_OLD_ROTATE_API
2848 if (st && st->metadata) {
2849 AVDictionaryEntry *rot = av_dict_get(st->metadata, "rotate", NULL, 0);
2850 rotation = (rot && rot->value) ? atoi(rot->value) : 0;
2853 if (display_matrix) {
2854 for (i = 0; i < 9; i++)
2855 avio_wb32(pb, display_matrix[i]);
2856 #if FF_API_OLD_ROTATE_API
2857 } else if (rotation == 90) {
2858 write_matrix(pb, 0, 1, -1, 0, track->par->height, 0);
2859 } else if (rotation == 180) {
2860 write_matrix(pb, -1, 0, 0, -1, track->par->width, track->par->height);
2861 } else if (rotation == 270) {
2862 write_matrix(pb, 0, -1, 1, 0, 0, track->par->width);
2865 write_matrix(pb, 1, 0, 0, 1, 0, 0);
2867 /* Track width and height, for visual only */
2868 if (st && (track->par->codec_type == AVMEDIA_TYPE_VIDEO ||
2869 track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)) {
2870 int64_t track_width_1616;
2871 if (track->mode == MODE_MOV) {
2872 track_width_1616 = track->par->width * 0x10000ULL;
2874 track_width_1616 = av_rescale(st->sample_aspect_ratio.num,
2875 track->par->width * 0x10000LL,
2876 st->sample_aspect_ratio.den);
2877 if (!track_width_1616 ||
2878 track->height != track->par->height ||
2879 track_width_1616 > UINT32_MAX)
2880 track_width_1616 = track->par->width * 0x10000ULL;
2882 if (track_width_1616 > UINT32_MAX) {
2883 av_log(mov->fc, AV_LOG_WARNING, "track width is too large\n");
2884 track_width_1616 = 0;
2886 avio_wb32(pb, track_width_1616);
2887 if (track->height > 0xFFFF) {
2888 av_log(mov->fc, AV_LOG_WARNING, "track height is too large\n");
2891 avio_wb32(pb, track->height * 0x10000U);
2899 static int mov_write_tapt_tag(AVIOContext *pb, MOVTrack *track)
2901 int32_t width = av_rescale(track->par->sample_aspect_ratio.num, track->par->width,
2902 track->par->sample_aspect_ratio.den);
2904 int64_t pos = avio_tell(pb);
2906 avio_wb32(pb, 0); /* size */
2907 ffio_wfourcc(pb, "tapt");
2910 ffio_wfourcc(pb, "clef");
2912 avio_wb32(pb, width << 16);
2913 avio_wb32(pb, track->par->height << 16);
2916 ffio_wfourcc(pb, "prof");
2918 avio_wb32(pb, width << 16);
2919 avio_wb32(pb, track->par->height << 16);
2922 ffio_wfourcc(pb, "enof");
2924 avio_wb32(pb, track->par->width << 16);
2925 avio_wb32(pb, track->par->height << 16);
2927 return update_size(pb, pos);
2930 // This box seems important for the psp playback ... without it the movie seems to hang
2931 static int mov_write_edts_tag(AVIOContext *pb, MOVMuxContext *mov,
2934 int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE,
2935 track->timescale, AV_ROUND_UP);
2936 int version = duration < INT32_MAX ? 0 : 1;
2937 int entry_size, entry_count, size;
2938 int64_t delay, start_ct = track->start_cts;
2939 int64_t start_dts = track->start_dts;
2942 if (start_dts != track->cluster[0].dts || start_ct != track->cluster[0].cts) {
2944 av_log(mov->fc, AV_LOG_DEBUG,
2945 "EDTS using dts:%"PRId64" cts:%d instead of dts:%"PRId64" cts:%"PRId64" tid:%d\n",
2946 track->cluster[0].dts, track->cluster[0].cts,
2947 start_dts, start_ct, track->track_id);
2948 start_dts = track->cluster[0].dts;
2949 start_ct = track->cluster[0].cts;
2953 delay = av_rescale_rnd(start_dts + start_ct, MOV_TIMESCALE,
2954 track->timescale, AV_ROUND_DOWN);
2955 version |= delay < INT32_MAX ? 0 : 1;
2957 entry_size = (version == 1) ? 20 : 12;
2958 entry_count = 1 + (delay > 0);
2959 size = 24 + entry_count * entry_size;
2961 /* write the atom data */
2962 avio_wb32(pb, size);
2963 ffio_wfourcc(pb, "edts");
2964 avio_wb32(pb, size - 8);
2965 ffio_wfourcc(pb, "elst");
2966 avio_w8(pb, version);
2967 avio_wb24(pb, 0); /* flags */
2969 avio_wb32(pb, entry_count);
2970 if (delay > 0) { /* add an empty edit to delay presentation */
2971 /* In the positive delay case, the delay includes the cts
2972 * offset, and the second edit list entry below trims out
2973 * the same amount from the actual content. This makes sure
2974 * that the offset last sample is included in the edit
2975 * list duration as well. */
2977 avio_wb64(pb, delay);
2980 avio_wb32(pb, delay);
2983 avio_wb32(pb, 0x00010000);
2985 /* Avoid accidentally ending up with start_ct = -1 which has got a
2986 * special meaning. Normally start_ct should end up positive or zero
2987 * here, but use FFMIN in case dts is a small positive integer
2988 * rounded to 0 when represented in MOV_TIMESCALE units. */
2989 av_assert0(av_rescale_rnd(start_dts, MOV_TIMESCALE, track->timescale, AV_ROUND_DOWN) <= 0);
2990 start_ct = -FFMIN(start_dts, 0);
2991 /* Note, this delay is calculated from the pts of the first sample,
2992 * ensuring that we don't reduce the duration for cases with
2997 /* For fragmented files, we don't know the full length yet. Setting
2998 * duration to 0 allows us to only specify the offset, including
2999 * the rest of the content (from all future fragments) without specifying
3000 * an explicit duration. */
3001 if (mov->flags & FF_MOV_FLAG_FRAGMENT)
3006 avio_wb64(pb, duration);
3007 avio_wb64(pb, start_ct);
3009 avio_wb32(pb, duration);
3010 avio_wb32(pb, start_ct);
3012 avio_wb32(pb, 0x00010000);
3016 static int mov_write_tref_tag(AVIOContext *pb, MOVTrack *track)
3018 avio_wb32(pb, 20); // size
3019 ffio_wfourcc(pb, "tref");
3020 avio_wb32(pb, 12); // size (subatom)
3021 avio_wl32(pb, track->tref_tag);
3022 avio_wb32(pb, track->tref_id);
3026 // goes at the end of each track! ... Critical for PSP playback ("Incompatible data" without it)
3027 static int mov_write_uuid_tag_psp(AVIOContext *pb, MOVTrack *mov)
3029 avio_wb32(pb, 0x34); /* size ... reports as 28 in mp4box! */
3030 ffio_wfourcc(pb, "uuid");
3031 ffio_wfourcc(pb, "USMT");
3032 avio_wb32(pb, 0x21d24fce);
3033 avio_wb32(pb, 0xbb88695c);
3034 avio_wb32(pb, 0xfac9c740);
3035 avio_wb32(pb, 0x1c); // another size here!
3036 ffio_wfourcc(pb, "MTDT");
3037 avio_wb32(pb, 0x00010012);
3038 avio_wb32(pb, 0x0a);
3039 avio_wb32(pb, 0x55c40000);
3045 static int mov_write_udta_sdp(AVIOContext *pb, MOVTrack *track)
3047 AVFormatContext *ctx = track->rtp_ctx;
3048 char buf[1000] = "";
3051 ff_sdp_write_media(buf, sizeof(buf), ctx->streams[0], track->src_track,
3052 NULL, NULL, 0, 0, ctx);
3053 av_strlcatf(buf, sizeof(buf), "a=control:streamid=%d\r\n", track->track_id);
3056 avio_wb32(pb, len + 24);
3057 ffio_wfourcc(pb, "udta");
3058 avio_wb32(pb, len + 16);
3059 ffio_wfourcc(pb, "hnti");
3060 avio_wb32(pb, len + 8);
3061 ffio_wfourcc(pb, "sdp ");
3062 avio_write(pb, buf, len);
3066 static int mov_write_track_metadata(AVIOContext *pb, AVStream *st,
3067 const char *tag, const char *str)
3069 int64_t pos = avio_tell(pb);
3070 AVDictionaryEntry *t = av_dict_get(st->metadata, str, NULL, 0);
3071 if (!t || !utf8len(t->value))
3074 avio_wb32(pb, 0); /* size */
3075 ffio_wfourcc(pb, tag); /* type */
3076 avio_write(pb, t->value, strlen(t->value)); /* UTF8 string value */
3077 return update_size(pb, pos);
3080 static int mov_write_track_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
3083 AVIOContext *pb_buf;
3090 ret = avio_open_dyn_buf(&pb_buf);
3094 if (mov->mode & (MODE_MP4|MODE_MOV))
3095 mov_write_track_metadata(pb_buf, st, "name", "title");
3097 if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) {
3098 avio_wb32(pb, size + 8);
3099 ffio_wfourcc(pb, "udta");
3100 avio_write(pb, buf, size);
3107 static int mov_write_trak_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov,
3108 MOVTrack *track, AVStream *st)
3110 int64_t pos = avio_tell(pb);
3111 int entry_backup = track->entry;
3112 int chunk_backup = track->chunkCount;
3115 /* If we want to have an empty moov, but some samples already have been
3116 * buffered (delay_moov), pretend that no samples have been written yet. */
3117 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV)
3118 track->chunkCount = track->entry = 0;
3120 avio_wb32(pb, 0); /* size */
3121 ffio_wfourcc(pb, "trak");
3122 mov_write_tkhd_tag(pb, mov, track, st);
3124 av_assert2(mov->use_editlist >= 0);
3126 if (track->start_dts != AV_NOPTS_VALUE) {
3127 if (mov->use_editlist)
3128 mov_write_edts_tag(pb, mov, track); // PSP Movies and several other cases require edts box
3129 else if ((track->entry && track->cluster[0].dts) || track->mode == MODE_PSP || is_clcp_track(track))
3130 av_log(mov->fc, AV_LOG_WARNING,
3131 "Not writing any edit list even though one would have been required\n");
3134 if (track->tref_tag)
3135 mov_write_tref_tag(pb, track);
3137 if ((ret = mov_write_mdia_tag(s, pb, mov, track)) < 0)
3139 if (track->mode == MODE_PSP)
3140 mov_write_uuid_tag_psp(pb, track); // PSP Movies require this uuid box
3141 if (track->tag == MKTAG('r','t','p',' '))
3142 mov_write_udta_sdp(pb, track);
3143 if (track->mode == MODE_MOV) {
3144 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
3145 double sample_aspect_ratio = av_q2d(st->sample_aspect_ratio);
3146 if (st->sample_aspect_ratio.num && 1.0 != sample_aspect_ratio) {
3147 mov_write_tapt_tag(pb, track);
3150 if (is_clcp_track(track) && st->sample_aspect_ratio.num) {
3151 mov_write_tapt_tag(pb, track);
3154 mov_write_track_udta_tag(pb, mov, st);
3155 track->entry = entry_backup;
3156 track->chunkCount = chunk_backup;
3157 return update_size(pb, pos);
3160 static int mov_write_iods_tag(AVIOContext *pb, MOVMuxContext *mov)
3162 int i, has_audio = 0, has_video = 0;
3163 int64_t pos = avio_tell(pb);
3164 int audio_profile = mov->iods_audio_profile;
3165 int video_profile = mov->iods_video_profile;
3166 for (i = 0; i < mov->nb_streams; i++) {
3167 if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
3168 has_audio |= mov->tracks[i].par->codec_type == AVMEDIA_TYPE_AUDIO;
3169 has_video |= mov->tracks[i].par->codec_type == AVMEDIA_TYPE_VIDEO;
3172 if (audio_profile < 0)
3173 audio_profile = 0xFF - has_audio;
3174 if (video_profile < 0)
3175 video_profile = 0xFF - has_video;
3176 avio_wb32(pb, 0x0); /* size */
3177 ffio_wfourcc(pb, "iods");
3178 avio_wb32(pb, 0); /* version & flags */
3179 put_descr(pb, 0x10, 7);
3180 avio_wb16(pb, 0x004f);
3183 avio_w8(pb, audio_profile);
3184 avio_w8(pb, video_profile);
3186 return update_size(pb, pos);
3189 static int mov_write_trex_tag(AVIOContext *pb, MOVTrack *track)
3191 avio_wb32(pb, 0x20); /* size */
3192 ffio_wfourcc(pb, "trex");
3193 avio_wb32(pb, 0); /* version & flags */
3194 avio_wb32(pb, track->track_id); /* track ID */
3195 avio_wb32(pb, 1); /* default sample description index */
3196 avio_wb32(pb, 0); /* default sample duration */
3197 avio_wb32(pb, 0); /* default sample size */
3198 avio_wb32(pb, 0); /* default sample flags */
3202 static int mov_write_mvex_tag(AVIOContext *pb, MOVMuxContext *mov)
3204 int64_t pos = avio_tell(pb);
3206 avio_wb32(pb, 0x0); /* size */
3207 ffio_wfourcc(pb, "mvex");
3208 for (i = 0; i < mov->nb_streams; i++)
3209 mov_write_trex_tag(pb, &mov->tracks[i]);
3210 return update_size(pb, pos);
3213 static int mov_write_mvhd_tag(AVIOContext *pb, MOVMuxContext *mov)
3215 int max_track_id = 1, i;
3216 int64_t max_track_len = 0;
3219 for (i = 0; i < mov->nb_streams; i++) {
3220 if (mov->tracks[i].entry > 0 && mov->tracks[i].timescale) {
3221 int64_t max_track_len_temp = av_rescale_rnd(mov->tracks[i].track_duration,
3223 mov->tracks[i].timescale,
3225 if (max_track_len < max_track_len_temp)
3226 max_track_len = max_track_len_temp;
3227 if (max_track_id < mov->tracks[i].track_id)
3228 max_track_id = mov->tracks[i].track_id;
3231 /* If using delay_moov, make sure the output is the same as if no
3232 * samples had been written yet. */
3233 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
3238 version = max_track_len < UINT32_MAX ? 0 : 1;
3239 avio_wb32(pb, version == 1 ? 120 : 108); /* size */
3241 ffio_wfourcc(pb, "mvhd");
3242 avio_w8(pb, version);
3243 avio_wb24(pb, 0); /* flags */
3245 avio_wb64(pb, mov->time);
3246 avio_wb64(pb, mov->time);
3248 avio_wb32(pb, mov->time); /* creation time */
3249 avio_wb32(pb, mov->time); /* modification time */
3251 avio_wb32(pb, MOV_TIMESCALE);
3252 (version == 1) ? avio_wb64(pb, max_track_len) : avio_wb32(pb, max_track_len); /* duration of longest track */
3254 avio_wb32(pb, 0x00010000); /* reserved (preferred rate) 1.0 = normal */
3255 avio_wb16(pb, 0x0100); /* reserved (preferred volume) 1.0 = normal */
3256 avio_wb16(pb, 0); /* reserved */
3257 avio_wb32(pb, 0); /* reserved */
3258 avio_wb32(pb, 0); /* reserved */
3260 /* Matrix structure */
3261 write_matrix(pb, 1, 0, 0, 1, 0, 0);
3263 avio_wb32(pb, 0); /* reserved (preview time) */
3264 avio_wb32(pb, 0); /* reserved (preview duration) */
3265 avio_wb32(pb, 0); /* reserved (poster time) */
3266 avio_wb32(pb, 0); /* reserved (selection time) */
3267 avio_wb32(pb, 0); /* reserved (selection duration) */
3268 avio_wb32(pb, 0); /* reserved (current time) */
3269 avio_wb32(pb, max_track_id + 1); /* Next track id */
3273 static int mov_write_itunes_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov,
3276 avio_wb32(pb, 33); /* size */
3277 ffio_wfourcc(pb, "hdlr");
3280 ffio_wfourcc(pb, "mdir");
3281 ffio_wfourcc(pb, "appl");
3288 /* helper function to write a data tag with the specified string as data */
3289 static int mov_write_string_data_tag(AVIOContext *pb, const char *data, int lang, int long_style)
3292 int size = 16 + strlen(data);
3293 avio_wb32(pb, size); /* size */
3294 ffio_wfourcc(pb, "data");
3297 avio_write(pb, data, strlen(data));
3301 lang = ff_mov_iso639_to_lang("und", 1);
3302 avio_wb16(pb, strlen(data)); /* string length */
3303 avio_wb16(pb, lang);
3304 avio_write(pb, data, strlen(data));
3305 return strlen(data) + 4;
3309 static int mov_write_string_tag(AVIOContext *pb, const char *name,
3310 const char *value, int lang, int long_style)
3313 if (value && value[0]) {
3314 int64_t pos = avio_tell(pb);
3315 avio_wb32(pb, 0); /* size */
3316 ffio_wfourcc(pb, name);
3317 mov_write_string_data_tag(pb, value, lang, long_style);
3318 size = update_size(pb, pos);
3323 static AVDictionaryEntry *get_metadata_lang(AVFormatContext *s,
3324 const char *tag, int *lang)
3327 AVDictionaryEntry *t, *t2 = NULL;
3332 if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
3335 len = strlen(t->key);
3336 snprintf(tag2, sizeof(tag2), "%s-", tag);
3337 while ((t2 = av_dict_get(s->metadata, tag2, t2, AV_DICT_IGNORE_SUFFIX))) {
3338 len2 = strlen(t2->key);
3339 if (len2 == len + 4 && !strcmp(t->value, t2->value)
3340 && (l = ff_mov_iso639_to_lang(&t2->key[len2 - 3], 1)) >= 0) {
3348 static int mov_write_string_metadata(AVFormatContext *s, AVIOContext *pb,
3349 const char *name, const char *tag,
3353 AVDictionaryEntry *t = get_metadata_lang(s, tag, &lang);
3356 return mov_write_string_tag(pb, name, t->value, lang, long_style);
3359 /* iTunes bpm number */
3360 static int mov_write_tmpo_tag(AVIOContext *pb, AVFormatContext *s)
3362 AVDictionaryEntry *t = av_dict_get(s->metadata, "tmpo", NULL, 0);
3363 int size = 0, tmpo = t ? atoi(t->value) : 0;
3366 avio_wb32(pb, size);
3367 ffio_wfourcc(pb, "tmpo");
3368 avio_wb32(pb, size-8); /* size */
3369 ffio_wfourcc(pb, "data");
3370 avio_wb32(pb, 0x15); //type specifier
3372 avio_wb16(pb, tmpo); // data
3377 /* 3GPP TS 26.244 */
3378 static int mov_write_loci_tag(AVFormatContext *s, AVIOContext *pb)
3381 int64_t pos = avio_tell(pb);
3382 double latitude, longitude, altitude;
3383 int32_t latitude_fix, longitude_fix, altitude_fix;
3384 AVDictionaryEntry *t = get_metadata_lang(s, "location", &lang);
3385 const char *ptr, *place = "";
3387 static const char *astronomical_body = "earth";
3392 longitude = strtod(ptr, &end);
3394 av_log(s, AV_LOG_WARNING, "malformed location metadata\n");
3398 latitude = strtod(ptr, &end);
3400 av_log(s, AV_LOG_WARNING, "malformed location metadata\n");
3404 altitude = strtod(ptr, &end);
3405 /* If no altitude was present, the default 0 should be fine */
3409 latitude_fix = (int32_t) ((1 << 16) * latitude);
3410 longitude_fix = (int32_t) ((1 << 16) * longitude);
3411 altitude_fix = (int32_t) ((1 << 16) * altitude);
3413 avio_wb32(pb, 0); /* size */
3414 ffio_wfourcc(pb, "loci"); /* type */
3415 avio_wb32(pb, 0); /* version + flags */
3416 avio_wb16(pb, lang);
3417 avio_write(pb, place, strlen(place) + 1);
3418 avio_w8(pb, 0); /* role of place (0 == shooting location, 1 == real location, 2 == fictional location) */
3419 avio_wb32(pb, latitude_fix);
3420 avio_wb32(pb, longitude_fix);
3421 avio_wb32(pb, altitude_fix);
3422 avio_write(pb, astronomical_body, strlen(astronomical_body) + 1);
3423 avio_w8(pb, 0); /* additional notes, null terminated string */
3425 return update_size(pb, pos);
3428 /* iTunes track or disc number */
3429 static int mov_write_trkn_tag(AVIOContext *pb, MOVMuxContext *mov,
3430 AVFormatContext *s, int disc)
3432 AVDictionaryEntry *t = av_dict_get(s->metadata,
3433 disc ? "disc" : "track",
3435 int size = 0, track = t ? atoi(t->value) : 0;
3438 char *slash = strchr(t->value, '/');
3440 tracks = atoi(slash + 1);
3441 avio_wb32(pb, 32); /* size */
3442 ffio_wfourcc(pb, disc ? "disk" : "trkn");
3443 avio_wb32(pb, 24); /* size */
3444 ffio_wfourcc(pb, "data");
3445 avio_wb32(pb, 0); // 8 bytes empty
3447 avio_wb16(pb, 0); // empty
3448 avio_wb16(pb, track); // track / disc number
3449 avio_wb16(pb, tracks); // total track / disc number
3450 avio_wb16(pb, 0); // empty
3456 static int mov_write_int8_metadata(AVFormatContext *s, AVIOContext *pb,
3457 const char *name, const char *tag,
3460 AVDictionaryEntry *t = NULL;
3462 int size = 24 + len;
3464 if (len != 1 && len != 4)
3467 if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
3469 num = atoi(t->value);
3471 avio_wb32(pb, size);
3472 ffio_wfourcc(pb, name);
3473 avio_wb32(pb, size - 8);
3474 ffio_wfourcc(pb, "data");
3475 avio_wb32(pb, 0x15);
3477 if (len==4) avio_wb32(pb, num);
3478 else avio_w8 (pb, num);
3483 static int mov_write_covr(AVIOContext *pb, AVFormatContext *s)
3485 MOVMuxContext *mov = s->priv_data;
3489 for (i = 0; i < s->nb_streams; i++) {
3490 MOVTrack *trk = &mov->tracks[i];
3492 if (!is_cover_image(trk->st) || trk->cover_image.size <= 0)
3496 pos = avio_tell(pb);
3498 ffio_wfourcc(pb, "covr");
3500 avio_wb32(pb, 16 + trk->cover_image.size);
3501 ffio_wfourcc(pb, "data");
3502 avio_wb32(pb, trk->tag);
3504 avio_write(pb, trk->cover_image.data, trk->cover_image.size);
3507 return pos ? update_size(pb, pos) : 0;
3510 /* iTunes meta data list */
3511 static int mov_write_ilst_tag(AVIOContext *pb, MOVMuxContext *mov,
3514 int64_t pos = avio_tell(pb);
3515 avio_wb32(pb, 0); /* size */
3516 ffio_wfourcc(pb, "ilst");
3517 mov_write_string_metadata(s, pb, "\251nam", "title" , 1);
3518 mov_write_string_metadata(s, pb, "\251ART", "artist" , 1);
3519 mov_write_string_metadata(s, pb, "aART", "album_artist", 1);
3520 mov_write_string_metadata(s, pb, "\251wrt", "composer" , 1);
3521 mov_write_string_metadata(s, pb, "\251alb", "album" , 1);
3522 mov_write_string_metadata(s, pb, "\251day", "date" , 1);
3523 if (!mov_write_string_metadata(s, pb, "\251too", "encoding_tool", 1)) {
3524 if (!(s->flags & AVFMT_FLAG_BITEXACT))
3525 mov_write_string_tag(pb, "\251too", LIBAVFORMAT_IDENT, 0, 1);
3527 mov_write_string_metadata(s, pb, "\251cmt", "comment" , 1);
3528 mov_write_string_metadata(s, pb, "\251gen", "genre" , 1);
3529 mov_write_string_metadata(s, pb, "cprt", "copyright", 1);
3530 mov_write_string_metadata(s, pb, "\251grp", "grouping" , 1);
3531 mov_write_string_metadata(s, pb, "\251lyr", "lyrics" , 1);
3532 mov_write_string_metadata(s, pb, "desc", "description",1);
3533 mov_write_string_metadata(s, pb, "ldes", "synopsis" , 1);
3534 mov_write_string_metadata(s, pb, "tvsh", "show" , 1);
3535 mov_write_string_metadata(s, pb, "tven", "episode_id",1);
3536 mov_write_string_metadata(s, pb, "tvnn", "network" , 1);
3537 mov_write_string_metadata(s, pb, "keyw", "keywords" , 1);
3538 mov_write_int8_metadata (s, pb, "tves", "episode_sort",4);
3539 mov_write_int8_metadata (s, pb, "tvsn", "season_number",4);
3540 mov_write_int8_metadata (s, pb, "stik", "media_type",1);
3541 mov_write_int8_metadata (s, pb, "hdvd", "hd_video", 1);
3542 mov_write_int8_metadata (s, pb, "pgap", "gapless_playback",1);
3543 mov_write_int8_metadata (s, pb, "cpil", "compilation", 1);
3544 mov_write_covr(pb, s);
3545 mov_write_trkn_tag(pb, mov, s, 0); // track number
3546 mov_write_trkn_tag(pb, mov, s, 1); // disc number
3547 mov_write_tmpo_tag(pb, s);
3548 return update_size(pb, pos);
3551 static int mov_write_mdta_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov,
3554 avio_wb32(pb, 33); /* size */
3555 ffio_wfourcc(pb, "hdlr");
3558 ffio_wfourcc(pb, "mdta");
3566 static int mov_write_mdta_keys_tag(AVIOContext *pb, MOVMuxContext *mov,
3569 AVDictionaryEntry *t = NULL;
3570 int64_t pos = avio_tell(pb);
3571 int64_t curpos, entry_pos;
3574 avio_wb32(pb, 0); /* size */
3575 ffio_wfourcc(pb, "keys");
3577 entry_pos = avio_tell(pb);
3578 avio_wb32(pb, 0); /* entry count */
3580 while (t = av_dict_get(s->metadata, "", t, AV_DICT_IGNORE_SUFFIX)) {
3581 avio_wb32(pb, strlen(t->key) + 8);
3582 ffio_wfourcc(pb, "mdta");
3583 avio_write(pb, t->key, strlen(t->key));
3586 curpos = avio_tell(pb);
3587 avio_seek(pb, entry_pos, SEEK_SET);
3588 avio_wb32(pb, count); // rewrite entry count
3589 avio_seek(pb, curpos, SEEK_SET);
3591 return update_size(pb, pos);
3594 static int mov_write_mdta_ilst_tag(AVIOContext *pb, MOVMuxContext *mov,
3597 AVDictionaryEntry *t = NULL;
3598 int64_t pos = avio_tell(pb);
3599 int count = 1; /* keys are 1-index based */
3601 avio_wb32(pb, 0); /* size */
3602 ffio_wfourcc(pb, "ilst");
3604 while (t = av_dict_get(s->metadata, "", t, AV_DICT_IGNORE_SUFFIX)) {
3605 int64_t entry_pos = avio_tell(pb);
3606 avio_wb32(pb, 0); /* size */
3607 avio_wb32(pb, count); /* key */
3608 mov_write_string_data_tag(pb, t->value, 0, 1);
3609 update_size(pb, entry_pos);
3612 return update_size(pb, pos);
3615 /* meta data tags */
3616 static int mov_write_meta_tag(AVIOContext *pb, MOVMuxContext *mov,
3620 int64_t pos = avio_tell(pb);
3621 avio_wb32(pb, 0); /* size */
3622 ffio_wfourcc(pb, "meta");
3624 if (mov->flags & FF_MOV_FLAG_USE_MDTA) {
3625 mov_write_mdta_hdlr_tag(pb, mov, s);
3626 mov_write_mdta_keys_tag(pb, mov, s);
3627 mov_write_mdta_ilst_tag(pb, mov, s);
3630 /* iTunes metadata tag */
3631 mov_write_itunes_hdlr_tag(pb, mov, s);
3632 mov_write_ilst_tag(pb, mov, s);
3634 size = update_size(pb, pos);
3638 static int mov_write_raw_metadata_tag(AVFormatContext *s, AVIOContext *pb,
3639 const char *name, const char *key)
3642 AVDictionaryEntry *t;
3644 if (!(t = av_dict_get(s->metadata, key, NULL, 0)))
3647 len = strlen(t->value);
3650 avio_wb32(pb, size);
3651 ffio_wfourcc(pb, name);
3652 avio_write(pb, t->value, len);
3658 static int ascii_to_wc(AVIOContext *pb, const uint8_t *b)
3662 GET_UTF8(val, *b++, return -1;)
3665 avio_wb16(pb, 0x00);
3669 static uint16_t language_code(const char *str)
3671 return (((str[0] - 0x60) & 0x1F) << 10) +
3672 (((str[1] - 0x60) & 0x1F) << 5) +
3673 (( str[2] - 0x60) & 0x1F);
3676 static int mov_write_3gp_udta_tag(AVIOContext *pb, AVFormatContext *s,
3677 const char *tag, const char *str)
3679 int64_t pos = avio_tell(pb);
3680 AVDictionaryEntry *t = av_dict_get(s->metadata, str, NULL, 0);
3681 if (!t || !utf8len(t->value))
3683 avio_wb32(pb, 0); /* size */
3684 ffio_wfourcc(pb, tag); /* type */
3685 avio_wb32(pb, 0); /* version + flags */
3686 if (!strcmp(tag, "yrrc"))
3687 avio_wb16(pb, atoi(t->value));
3689 avio_wb16(pb, language_code("eng")); /* language */
3690 avio_write(pb, t->value, strlen(t->value) + 1); /* UTF8 string value */
3691 if (!strcmp(tag, "albm") &&
3692 (t = av_dict_get(s->metadata, "track", NULL, 0)))
3693 avio_w8(pb, atoi(t->value));
3695 return update_size(pb, pos);
3698 static int mov_write_chpl_tag(AVIOContext *pb, AVFormatContext *s)
3700 int64_t pos = avio_tell(pb);
3701 int i, nb_chapters = FFMIN(s->nb_chapters, 255);
3703 avio_wb32(pb, 0); // size
3704 ffio_wfourcc(pb, "chpl");
3705 avio_wb32(pb, 0x01000000); // version + flags
3706 avio_wb32(pb, 0); // unknown
3707 avio_w8(pb, nb_chapters);
3709 for (i = 0; i < nb_chapters; i++) {
3710 AVChapter *c = s->chapters[i];
3711 AVDictionaryEntry *t;
3712 avio_wb64(pb, av_rescale_q(c->start, c->time_base, (AVRational){1,10000000}));
3714 if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
3715 int len = FFMIN(strlen(t->value), 255);
3717 avio_write(pb, t->value, len);
3721 return update_size(pb, pos);
3724 static int mov_write_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
3727 AVIOContext *pb_buf;
3731 ret = avio_open_dyn_buf(&pb_buf);
3735 if (mov->mode & MODE_3GP) {
3736 mov_write_3gp_udta_tag(pb_buf, s, "perf", "artist");
3737 mov_write_3gp_udta_tag(pb_buf, s, "titl", "title");
3738 mov_write_3gp_udta_tag(pb_buf, s, "auth", "author");
3739 mov_write_3gp_udta_tag(pb_buf, s, "gnre", "genre");
3740 mov_write_3gp_udta_tag(pb_buf, s, "dscp", "comment");
3741 mov_write_3gp_udta_tag(pb_buf, s, "albm", "album");
3742 mov_write_3gp_udta_tag(pb_buf, s, "cprt", "copyright");
3743 mov_write_3gp_udta_tag(pb_buf, s, "yrrc", "date");
3744 mov_write_loci_tag(s, pb_buf);
3745 } 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
3746 mov_write_string_metadata(s, pb_buf, "\251ART", "artist", 0);
3747 mov_write_string_metadata(s, pb_buf, "\251nam", "title", 0);
3748 mov_write_string_metadata(s, pb_buf, "\251aut", "author", 0);
3749 mov_write_string_metadata(s, pb_buf, "\251alb", "album", 0);
3750 mov_write_string_metadata(s, pb_buf, "\251day", "date", 0);
3751 mov_write_string_metadata(s, pb_buf, "\251swr", "encoder", 0);
3752 // currently ignored by mov.c
3753 mov_write_string_metadata(s, pb_buf, "\251des", "comment", 0);
3754 // add support for libquicktime, this atom is also actually read by mov.c
3755 mov_write_string_metadata(s, pb_buf, "\251cmt", "comment", 0);
3756 mov_write_string_metadata(s, pb_buf, "\251gen", "genre", 0);
3757 mov_write_string_metadata(s, pb_buf, "\251cpy", "copyright", 0);
3758 mov_write_string_metadata(s, pb_buf, "\251mak", "make", 0);
3759 mov_write_string_metadata(s, pb_buf, "\251mod", "model", 0);
3760 mov_write_string_metadata(s, pb_buf, "\251xyz", "location", 0);
3761 mov_write_string_metadata(s, pb_buf, "\251key", "keywords", 0);
3762 mov_write_raw_metadata_tag(s, pb_buf, "XMP_", "xmp");
3764 /* iTunes meta data */
3765 mov_write_meta_tag(pb_buf, mov, s);
3766 mov_write_loci_tag(s, pb_buf);
3769 if (s->nb_chapters && !(mov->flags & FF_MOV_FLAG_DISABLE_CHPL))
3770 mov_write_chpl_tag(pb_buf, s);
3772 if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) {
3773 avio_wb32(pb, size + 8);
3774 ffio_wfourcc(pb, "udta");
3775 avio_write(pb, buf, size);
3782 static void mov_write_psp_udta_tag(AVIOContext *pb,
3783 const char *str, const char *lang, int type)
3785 int len = utf8len(str) + 1;
3788 avio_wb16(pb, len * 2 + 10); /* size */
3789 avio_wb32(pb, type); /* type */
3790 avio_wb16(pb, language_code(lang)); /* language */
3791 avio_wb16(pb, 0x01); /* ? */
3792 ascii_to_wc(pb, str);
3795 static int mov_write_uuidusmt_tag(AVIOContext *pb, AVFormatContext *s)
3797 AVDictionaryEntry *title = av_dict_get(s->metadata, "title", NULL, 0);
3801 pos = avio_tell(pb);
3802 avio_wb32(pb, 0); /* size placeholder*/
3803 ffio_wfourcc(pb, "uuid");
3804 ffio_wfourcc(pb, "USMT");
3805 avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
3806 avio_wb32(pb, 0xbb88695c);
3807 avio_wb32(pb, 0xfac9c740);
3809 pos2 = avio_tell(pb);
3810 avio_wb32(pb, 0); /* size placeholder*/
3811 ffio_wfourcc(pb, "MTDT");
3815 avio_wb16(pb, 0x0C); /* size */
3816 avio_wb32(pb, 0x0B); /* type */
3817 avio_wb16(pb, language_code("und")); /* language */
3818 avio_wb16(pb, 0x0); /* ? */
3819 avio_wb16(pb, 0x021C); /* data */
3821 if (!(s->flags & AVFMT_FLAG_BITEXACT))
3822 mov_write_psp_udta_tag(pb, LIBAVCODEC_IDENT, "eng", 0x04);
3823 mov_write_psp_udta_tag(pb, title->value, "eng", 0x01);
3824 mov_write_psp_udta_tag(pb, "2006/04/01 11:11:11", "und", 0x03);
3826 update_size(pb, pos2);
3827 return update_size(pb, pos);
3833 static void build_chunks(MOVTrack *trk)
3836 MOVIentry *chunk = &trk->cluster[0];
3837 uint64_t chunkSize = chunk->size;
3838 chunk->chunkNum = 1;
3839 if (trk->chunkCount)
3841 trk->chunkCount = 1;
3842 for (i = 1; i<trk->entry; i++){
3843 if (chunk->pos + chunkSize == trk->cluster[i].pos &&
3844 chunkSize + trk->cluster[i].size < (1<<20)){
3845 chunkSize += trk->cluster[i].size;
3846 chunk->samples_in_chunk += trk->cluster[i].entries;
3848 trk->cluster[i].chunkNum = chunk->chunkNum+1;
3849 chunk=&trk->cluster[i];
3850 chunkSize = chunk->size;
3857 * Assign track ids. If option "use_stream_ids_as_track_ids" is set,
3858 * the stream ids are used as track ids.
3860 * This assumes mov->tracks and s->streams are in the same order and
3861 * there are no gaps in either of them (so mov->tracks[n] refers to
3864 * As an exception, there can be more entries in
3865 * s->streams than in mov->tracks, in which case new track ids are
3866 * generated (starting after the largest found stream id).
3868 static int mov_setup_track_ids(MOVMuxContext *mov, AVFormatContext *s)
3872 if (mov->track_ids_ok)
3875 if (mov->use_stream_ids_as_track_ids) {
3876 int next_generated_track_id = 0;
3877 for (i = 0; i < s->nb_streams; i++) {
3878 if (s->streams[i]->id > next_generated_track_id)
3879 next_generated_track_id = s->streams[i]->id;
3882 for (i = 0; i < mov->nb_streams; i++) {
3883 if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
3886 mov->tracks[i].track_id = i >= s->nb_streams ? ++next_generated_track_id : s->streams[i]->id;
3889 for (i = 0; i < mov->nb_streams; i++) {
3890 if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
3893 mov->tracks[i].track_id = i + 1;
3897 mov->track_ids_ok = 1;
3902 static int mov_write_moov_tag(AVIOContext *pb, MOVMuxContext *mov,
3906 int64_t pos = avio_tell(pb);
3907 avio_wb32(pb, 0); /* size placeholder*/
3908 ffio_wfourcc(pb, "moov");
3910 mov_setup_track_ids(mov, s);
3912 for (i = 0; i < mov->nb_streams; i++) {
3913 if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
3916 mov->tracks[i].time = mov->time;
3918 if (mov->tracks[i].entry)
3919 build_chunks(&mov->tracks[i]);
3922 if (mov->chapter_track)
3923 for (i = 0; i < s->nb_streams; i++) {
3924 mov->tracks[i].tref_tag = MKTAG('c','h','a','p');
3925 mov->tracks[i].tref_id = mov->tracks[mov->chapter_track].track_id;
3927 for (i = 0; i < mov->nb_streams; i++) {
3928 MOVTrack *track = &mov->tracks[i];
3929 if (track->tag == MKTAG('r','t','p',' ')) {
3930 track->tref_tag = MKTAG('h','i','n','t');
3931 track->tref_id = mov->tracks[track->src_track].track_id;
3932 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
3933 int * fallback, size;
3934 fallback = (int*)av_stream_get_side_data(track->st,
3935 AV_PKT_DATA_FALLBACK_TRACK,
3937 if (fallback != NULL && size == sizeof(int)) {
3938 if (*fallback >= 0 && *fallback < mov->nb_streams) {
3939 track->tref_tag = MKTAG('f','a','l','l');
3940 track->tref_id = mov->tracks[*fallback].track_id;
3945 for (i = 0; i < mov->nb_streams; i++) {
3946 if (mov->tracks[i].tag == MKTAG('t','m','c','d')) {
3947 int src_trk = mov->tracks[i].src_track;
3948 mov->tracks[src_trk].tref_tag = mov->tracks[i].tag;
3949 mov->tracks[src_trk].tref_id = mov->tracks[i].track_id;
3950 //src_trk may have a different timescale than the tmcd track
3951 mov->tracks[i].track_duration = av_rescale(mov->tracks[src_trk].track_duration,
3952 mov->tracks[i].timescale,
3953 mov->tracks[src_trk].timescale);
3957 mov_write_mvhd_tag(pb, mov);
3958 if (mov->mode != MODE_MOV && !mov->iods_skip)
3959 mov_write_iods_tag(pb, mov);
3960 for (i = 0; i < mov->nb_streams; i++) {
3961 if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_FRAGMENT) {
3962 int ret = mov_write_trak_tag(s, pb, mov, &(mov->tracks[i]), i < s->nb_streams ? s->streams[i] : NULL);
3967 if (mov->flags & FF_MOV_FLAG_FRAGMENT)
3968 mov_write_mvex_tag(pb, mov); /* QuickTime requires trak to precede this */
3970 if (mov->mode == MODE_PSP)
3971 mov_write_uuidusmt_tag(pb, s);
3973 mov_write_udta_tag(pb, mov, s);
3975 return update_size(pb, pos);
3978 static void param_write_int(AVIOContext *pb, const char *name, int value)
3980 avio_printf(pb, "<param name=\"%s\" value=\"%d\" valuetype=\"data\"/>\n", name, value);
3983 static void param_write_string(AVIOContext *pb, const char *name, const char *value)
3985 avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, value);
3988 static void param_write_hex(AVIOContext *pb, const char *name, const uint8_t *value, int len)
3991 len = FFMIN(sizeof(buf) / 2 - 1, len);
3992 ff_data_to_hex(buf, value, len, 0);
3993 buf[2 * len] = '\0';
3994 avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, buf);
3997 static int mov_write_isml_manifest(AVIOContext *pb, MOVMuxContext *mov, AVFormatContext *s)
3999 int64_t pos = avio_tell(pb);
4001 int64_t manifest_bit_rate = 0;
4002 AVCPBProperties *props = NULL;
4004 static const uint8_t uuid[] = {
4005 0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd,
4006 0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66
4010 ffio_wfourcc(pb, "uuid");
4011 avio_write(pb, uuid, sizeof(uuid));
4014 avio_printf(pb, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
4015 avio_printf(pb, "<smil xmlns=\"http://www.w3.org/2001/SMIL20/Language\">\n");
4016 avio_printf(pb, "<head>\n");
4017 if (!(mov->fc->flags & AVFMT_FLAG_BITEXACT))
4018 avio_printf(pb, "<meta name=\"creator\" content=\"%s\" />\n",
4020 avio_printf(pb, "</head>\n");
4021 avio_printf(pb, "<body>\n");
4022 avio_printf(pb, "<switch>\n");
4024 mov_setup_track_ids(mov, s);
4026 for (i = 0; i < mov->nb_streams; i++) {
4027 MOVTrack *track = &mov->tracks[i];
4029 int track_id = track->track_id;
4030 char track_name_buf[32] = { 0 };
4032 AVStream *st = track->st;
4033 AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0);
4035 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO && !is_cover_image(st)) {
4037 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
4043 props = (AVCPBProperties*)av_stream_get_side_data(track->st, AV_PKT_DATA_CPB_PROPERTIES, NULL);
4045 if (track->par->bit_rate) {
4046 manifest_bit_rate = track->par->bit_rate;
4048 manifest_bit_rate = props->max_bitrate;
4051 avio_printf(pb, "<%s systemBitrate=\"%"PRId64"\">\n", type,
4053 param_write_int(pb, "systemBitrate", manifest_bit_rate);
4054 param_write_int(pb, "trackID", track_id);
4055 param_write_string(pb, "systemLanguage", lang ? lang->value : "und");
4057 /* Build track name piece by piece: */
4059 av_strlcat(track_name_buf, type, sizeof(track_name_buf));
4060 /* 2. track language, if available */
4062 av_strlcatf(track_name_buf, sizeof(track_name_buf),
4063 "_%s", lang->value);
4064 /* 3. special type suffix */
4065 /* "_cc" = closed captions, "_ad" = audio_description */
4066 if (st->disposition & AV_DISPOSITION_HEARING_IMPAIRED)
4067 av_strlcat(track_name_buf, "_cc", sizeof(track_name_buf));
4068 else if (st->disposition & AV_DISPOSITION_VISUAL_IMPAIRED)
4069 av_strlcat(track_name_buf, "_ad", sizeof(track_name_buf));
4071 param_write_string(pb, "trackName", track_name_buf);
4073 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
4074 if (track->par->codec_id == AV_CODEC_ID_H264) {
4076 int size = track->par->extradata_size;
4077 if (!ff_avc_write_annexb_extradata(track->par->extradata, &ptr,
4079 param_write_hex(pb, "CodecPrivateData",
4080 ptr ? ptr : track->par->extradata,
4084 param_write_string(pb, "FourCC", "H264");
4085 } else if (track->par->codec_id == AV_CODEC_ID_VC1) {
4086 param_write_string(pb, "FourCC", "WVC1");
4087 param_write_hex(pb, "CodecPrivateData", track->par->extradata,
4088 track->par->extradata_size);
4090 param_write_int(pb, "MaxWidth", track->par->width);
4091 param_write_int(pb, "MaxHeight", track->par->height);
4092 param_write_int(pb, "DisplayWidth", track->par->width);
4093 param_write_int(pb, "DisplayHeight", track->par->height);
4095 if (track->par->codec_id == AV_CODEC_ID_AAC) {
4096 switch (track->par->profile)
4098 case FF_PROFILE_AAC_HE_V2:
4099 param_write_string(pb, "FourCC", "AACP");
4101 case FF_PROFILE_AAC_HE:
4102 param_write_string(pb, "FourCC", "AACH");
4105 param_write_string(pb, "FourCC", "AACL");
4107 } else if (track->par->codec_id == AV_CODEC_ID_WMAPRO) {
4108 param_write_string(pb, "FourCC", "WMAP");
4110 param_write_hex(pb, "CodecPrivateData", track->par->extradata,
4111 track->par->extradata_size);
4112 param_write_int(pb, "AudioTag", ff_codec_get_tag(ff_codec_wav_tags,
4113 track->par->codec_id));
4114 param_write_int(pb, "Channels", track->par->channels);
4115 param_write_int(pb, "SamplingRate", track->par->sample_rate);
4116 param_write_int(pb, "BitsPerSample", 16);
4117 param_write_int(pb, "PacketSize", track->par->block_align ?
4118 track->par->block_align : 4);
4120 avio_printf(pb, "</%s>\n", type);
4122 avio_printf(pb, "</switch>\n");
4123 avio_printf(pb, "</body>\n");
4124 avio_printf(pb, "</smil>\n");
4126 return update_size(pb, pos);
4129 static int mov_write_mfhd_tag(AVIOContext *pb, MOVMuxContext *mov)
4132 ffio_wfourcc(pb, "mfhd");
4134 avio_wb32(pb, mov->fragments);
4138 static uint32_t get_sample_flags(MOVTrack *track, MOVIentry *entry)
4140 return entry->flags & MOV_SYNC_SAMPLE ? MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO :
4141 (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC);
4144 static int mov_write_tfhd_tag(AVIOContext *pb, MOVMuxContext *mov,
4145 MOVTrack *track, int64_t moof_offset)
4147 int64_t pos = avio_tell(pb);
4148 uint32_t flags = MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
4149 MOV_TFHD_BASE_DATA_OFFSET;
4150 if (!track->entry) {
4151 flags |= MOV_TFHD_DURATION_IS_EMPTY;
4153 flags |= MOV_TFHD_DEFAULT_FLAGS;
4155 if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET)
4156 flags &= ~MOV_TFHD_BASE_DATA_OFFSET;
4157 if (mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) {
4158 flags &= ~MOV_TFHD_BASE_DATA_OFFSET;
4159 flags |= MOV_TFHD_DEFAULT_BASE_IS_MOOF;
4162 /* Don't set a default sample size, the silverlight player refuses
4163 * to play files with that set. Don't set a default sample duration,
4164 * WMP freaks out if it is set. Don't set a base data offset, PIFF
4165 * file format says it MUST NOT be set. */
4166 if (track->mode == MODE_ISM)
4167 flags &= ~(MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
4168 MOV_TFHD_BASE_DATA_OFFSET);
4170 avio_wb32(pb, 0); /* size placeholder */
4171 ffio_wfourcc(pb, "tfhd");
4172 avio_w8(pb, 0); /* version */
4173 avio_wb24(pb, flags);
4175 avio_wb32(pb, track->track_id); /* track-id */
4176 if (flags & MOV_TFHD_BASE_DATA_OFFSET)
4177 avio_wb64(pb, moof_offset);
4178 if (flags & MOV_TFHD_DEFAULT_DURATION) {
4179 track->default_duration = get_cluster_duration(track, 0);
4180 avio_wb32(pb, track->default_duration);
4182 if (flags & MOV_TFHD_DEFAULT_SIZE) {
4183 track->default_size = track->entry ? track->cluster[0].size : 1;
4184 avio_wb32(pb, track->default_size);
4186 track->default_size = -1;
4188 if (flags & MOV_TFHD_DEFAULT_FLAGS) {
4189 /* Set the default flags based on the second sample, if available.
4190 * If the first sample is different, that can be signaled via a separate field. */
4191 if (track->entry > 1)
4192 track->default_sample_flags = get_sample_flags(track, &track->cluster[1]);
4194 track->default_sample_flags =
4195 track->par->codec_type == AVMEDIA_TYPE_VIDEO ?
4196 (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC) :
4197 MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO;
4198 avio_wb32(pb, track->default_sample_flags);
4201 return update_size(pb, pos);
4204 static int mov_write_trun_tag(AVIOContext *pb, MOVMuxContext *mov,
4205 MOVTrack *track, int moof_size,
4208 int64_t pos = avio_tell(pb);
4209 uint32_t flags = MOV_TRUN_DATA_OFFSET;
4212 for (i = first; i < end; i++) {
4213 if (get_cluster_duration(track, i) != track->default_duration)
4214 flags |= MOV_TRUN_SAMPLE_DURATION;
4215 if (track->cluster[i].size != track->default_size)
4216 flags |= MOV_TRUN_SAMPLE_SIZE;
4217 if (i > first && get_sample_flags(track, &track->cluster[i]) != track->default_sample_flags)
4218 flags |= MOV_TRUN_SAMPLE_FLAGS;
4220 if (!(flags & MOV_TRUN_SAMPLE_FLAGS) && track->entry > 0 &&
4221 get_sample_flags(track, &track->cluster[0]) != track->default_sample_flags)
4222 flags |= MOV_TRUN_FIRST_SAMPLE_FLAGS;
4223 if (track->flags & MOV_TRACK_CTTS)
4224 flags |= MOV_TRUN_SAMPLE_CTS;
4226 avio_wb32(pb, 0); /* size placeholder */
4227 ffio_wfourcc(pb, "trun");
4228 if (mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS)
4229 avio_w8(pb, 1); /* version */
4231 avio_w8(pb, 0); /* version */
4232 avio_wb24(pb, flags);
4234 avio_wb32(pb, end - first); /* sample count */
4235 if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET &&
4236 !(mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) &&
4238 avio_wb32(pb, 0); /* Later tracks follow immediately after the previous one */
4240 avio_wb32(pb, moof_size + 8 + track->data_offset +
4241 track->cluster[first].pos); /* data offset */
4242 if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS)
4243 avio_wb32(pb, get_sample_flags(track, &track->cluster[first]));
4245 for (i = first; i < end; i++) {
4246 if (flags & MOV_TRUN_SAMPLE_DURATION)
4247 avio_wb32(pb, get_cluster_duration(track, i));
4248 if (flags & MOV_TRUN_SAMPLE_SIZE)
4249 avio_wb32(pb, track->cluster[i].size);
4250 if (flags & MOV_TRUN_SAMPLE_FLAGS)
4251 avio_wb32(pb, get_sample_flags(track, &track->cluster[i]));
4252 if (flags & MOV_TRUN_SAMPLE_CTS)
4253 avio_wb32(pb, track->cluster[i].cts);
4256 mov->first_trun = 0;
4257 return update_size(pb, pos);
4260 static int mov_write_tfxd_tag(AVIOContext *pb, MOVTrack *track)
4262 int64_t pos = avio_tell(pb);
4263 static const uint8_t uuid[] = {
4264 0x6d, 0x1d, 0x9b, 0x05, 0x42, 0xd5, 0x44, 0xe6,
4265 0x80, 0xe2, 0x14, 0x1d, 0xaf, 0xf7, 0x57, 0xb2
4268 avio_wb32(pb, 0); /* size placeholder */
4269 ffio_wfourcc(pb, "uuid");
4270 avio_write(pb, uuid, sizeof(uuid));
4273 avio_wb64(pb, track->start_dts + track->frag_start +
4274 track->cluster[0].cts);
4275 avio_wb64(pb, track->end_pts -
4276 (track->cluster[0].dts + track->cluster[0].cts));
4278 return update_size(pb, pos);
4281 static int mov_write_tfrf_tag(AVIOContext *pb, MOVMuxContext *mov,
4282 MOVTrack *track, int entry)
4284 int n = track->nb_frag_info - 1 - entry, i;
4285 int size = 8 + 16 + 4 + 1 + 16*n;
4286 static const uint8_t uuid[] = {
4287 0xd4, 0x80, 0x7e, 0xf2, 0xca, 0x39, 0x46, 0x95,
4288 0x8e, 0x54, 0x26, 0xcb, 0x9e, 0x46, 0xa7, 0x9f
4294 avio_seek(pb, track->frag_info[entry].tfrf_offset, SEEK_SET);
4295 avio_wb32(pb, size);
4296 ffio_wfourcc(pb, "uuid");
4297 avio_write(pb, uuid, sizeof(uuid));
4301 for (i = 0; i < n; i++) {
4302 int index = entry + 1 + i;
4303 avio_wb64(pb, track->frag_info[index].time);
4304 avio_wb64(pb, track->frag_info[index].duration);
4306 if (n < mov->ism_lookahead) {
4307 int free_size = 16 * (mov->ism_lookahead - n);
4308 avio_wb32(pb, free_size);
4309 ffio_wfourcc(pb, "free");
4310 ffio_fill(pb, 0, free_size - 8);
4316 static int mov_write_tfrf_tags(AVIOContext *pb, MOVMuxContext *mov,
4319 int64_t pos = avio_tell(pb);
4321 for (i = 0; i < mov->ism_lookahead; i++) {
4322 /* Update the tfrf tag for the last ism_lookahead fragments,
4323 * nb_frag_info - 1 is the next fragment to be written. */
4324 mov_write_tfrf_tag(pb, mov, track, track->nb_frag_info - 2 - i);
4326 avio_seek(pb, pos, SEEK_SET);
4330 static int mov_add_tfra_entries(AVIOContext *pb, MOVMuxContext *mov, int tracks,
4334 for (i = 0; i < mov->nb_streams; i++) {
4335 MOVTrack *track = &mov->tracks[i];
4336 MOVFragmentInfo *info;
4337 if ((tracks >= 0 && i != tracks) || !track->entry)
4339 track->nb_frag_info++;
4340 if (track->nb_frag_info >= track->frag_info_capacity) {
4341 unsigned new_capacity = track->nb_frag_info + MOV_FRAG_INFO_ALLOC_INCREMENT;
4342 if (av_reallocp_array(&track->frag_info,
4344 sizeof(*track->frag_info)))
4345 return AVERROR(ENOMEM);
4346 track->frag_info_capacity = new_capacity;
4348 info = &track->frag_info[track->nb_frag_info - 1];
4349 info->offset = avio_tell(pb);
4351 // Try to recreate the original pts for the first packet
4352 // from the fields we have stored
4353 info->time = track->start_dts + track->frag_start +
4354 track->cluster[0].cts;
4355 info->duration = track->end_pts -
4356 (track->cluster[0].dts + track->cluster[0].cts);
4357 // If the pts is less than zero, we will have trimmed
4358 // away parts of the media track using an edit list,
4359 // and the corresponding start presentation time is zero.
4360 if (info->time < 0) {
4361 info->duration += info->time;
4364 info->tfrf_offset = 0;
4365 mov_write_tfrf_tags(pb, mov, track);
4370 static void mov_prune_frag_info(MOVMuxContext *mov, int tracks, int max)
4373 for (i = 0; i < mov->nb_streams; i++) {
4374 MOVTrack *track = &mov->tracks[i];
4375 if ((tracks >= 0 && i != tracks) || !track->entry)
4377 if (track->nb_frag_info > max) {
4378 memmove(track->frag_info, track->frag_info + (track->nb_frag_info - max), max * sizeof(*track->frag_info));
4379 track->nb_frag_info = max;
4384 static int mov_write_tfdt_tag(AVIOContext *pb, MOVTrack *track)
4386 int64_t pos = avio_tell(pb);
4388 avio_wb32(pb, 0); /* size */
4389 ffio_wfourcc(pb, "tfdt");
4390 avio_w8(pb, 1); /* version */
4392 avio_wb64(pb, track->frag_start);
4393 return update_size(pb, pos);
4396 static int mov_write_traf_tag(AVIOContext *pb, MOVMuxContext *mov,
4397 MOVTrack *track, int64_t moof_offset,
4400 int64_t pos = avio_tell(pb);
4402 avio_wb32(pb, 0); /* size placeholder */
4403 ffio_wfourcc(pb, "traf");
4405 mov_write_tfhd_tag(pb, mov, track, moof_offset);
4406 if (mov->mode != MODE_ISM)
4407 mov_write_tfdt_tag(pb, track);
4408 for (i = 1; i < track->entry; i++) {
4409 if (track->cluster[i].pos != track->cluster[i - 1].pos + track->cluster[i - 1].size) {
4410 mov_write_trun_tag(pb, mov, track, moof_size, start, i);
4414 mov_write_trun_tag(pb, mov, track, moof_size, start, track->entry);
4415 if (mov->mode == MODE_ISM) {
4416 mov_write_tfxd_tag(pb, track);
4418 if (mov->ism_lookahead) {
4419 int i, size = 16 + 4 + 1 + 16 * mov->ism_lookahead;
4421 if (track->nb_frag_info > 0) {
4422 MOVFragmentInfo *info = &track->frag_info[track->nb_frag_info - 1];
4423 if (!info->tfrf_offset)
4424 info->tfrf_offset = avio_tell(pb);
4426 avio_wb32(pb, 8 + size);
4427 ffio_wfourcc(pb, "free");
4428 for (i = 0; i < size; i++)
4433 return update_size(pb, pos);
4436 static int mov_write_moof_tag_internal(AVIOContext *pb, MOVMuxContext *mov,
4437 int tracks, int moof_size)
4439 int64_t pos = avio_tell(pb);
4442 avio_wb32(pb, 0); /* size placeholder */
4443 ffio_wfourcc(pb, "moof");
4444 mov->first_trun = 1;
4446 mov_write_mfhd_tag(pb, mov);
4447 for (i = 0; i < mov->nb_streams; i++) {
4448 MOVTrack *track = &mov->tracks[i];
4449 if (tracks >= 0 && i != tracks)
4453 mov_write_traf_tag(pb, mov, track, pos, moof_size);
4456 return update_size(pb, pos);
4459 static int mov_write_sidx_tag(AVIOContext *pb,
4460 MOVTrack *track, int ref_size, int total_sidx_size)
4462 int64_t pos = avio_tell(pb), offset_pos, end_pos;
4463 int64_t presentation_time, duration, offset;
4464 int starts_with_SAP, i, entries;
4468 presentation_time = track->start_dts + track->frag_start +
4469 track->cluster[0].cts;
4470 duration = track->end_pts -
4471 (track->cluster[0].dts + track->cluster[0].cts);
4472 starts_with_SAP = track->cluster[0].flags & MOV_SYNC_SAMPLE;
4474 // pts<0 should be cut away using edts
4475 if (presentation_time < 0) {
4476 duration += presentation_time;
4477 presentation_time = 0;
4480 entries = track->nb_frag_info;
4483 presentation_time = track->frag_info[0].time;
4486 avio_wb32(pb, 0); /* size */
4487 ffio_wfourcc(pb, "sidx");
4488 avio_w8(pb, 1); /* version */
4490 avio_wb32(pb, track->track_id); /* reference_ID */
4491 avio_wb32(pb, track->timescale); /* timescale */
4492 avio_wb64(pb, presentation_time); /* earliest_presentation_time */
4493 offset_pos = avio_tell(pb);
4494 avio_wb64(pb, 0); /* first_offset (offset to referenced moof) */
4495 avio_wb16(pb, 0); /* reserved */
4497 avio_wb16(pb, entries); /* reference_count */
4498 for (i = 0; i < entries; i++) {
4499 if (!track->entry) {
4500 if (i > 1 && track->frag_info[i].offset != track->frag_info[i - 1].offset + track->frag_info[i - 1].size) {
4501 av_log(NULL, AV_LOG_ERROR, "Non-consecutive fragments, writing incorrect sidx\n");
4503 duration = track->frag_info[i].duration;
4504 ref_size = track->frag_info[i].size;
4505 starts_with_SAP = 1;
4507 avio_wb32(pb, (0 << 31) | (ref_size & 0x7fffffff)); /* reference_type (0 = media) | referenced_size */
4508 avio_wb32(pb, duration); /* subsegment_duration */
4509 avio_wb32(pb, (starts_with_SAP << 31) | (0 << 28) | 0); /* starts_with_SAP | SAP_type | SAP_delta_time */
4512 end_pos = avio_tell(pb);
4513 offset = pos + total_sidx_size - end_pos;
4514 avio_seek(pb, offset_pos, SEEK_SET);
4515 avio_wb64(pb, offset);
4516 avio_seek(pb, end_pos, SEEK_SET);
4517 return update_size(pb, pos);
4520 static int mov_write_sidx_tags(AVIOContext *pb, MOVMuxContext *mov,
4521 int tracks, int ref_size)
4524 AVIOContext *avio_buf;
4526 for (round = 0; round < 2; round++) {
4527 // First run one round to calculate the total size of all
4529 // This would be much simpler if we'd only write one sidx
4530 // atom, for the first track in the moof.
4532 if ((ret = ffio_open_null_buf(&avio_buf)) < 0)
4537 for (i = 0; i < mov->nb_streams; i++) {
4538 MOVTrack *track = &mov->tracks[i];
4539 if (tracks >= 0 && i != tracks)
4541 // When writing a sidx for the full file, entry is 0, but
4542 // we want to include all tracks. ref_size is 0 in this case,
4543 // since we read it from frag_info instead.
4544 if (!track->entry && ref_size > 0)
4546 total_size -= mov_write_sidx_tag(avio_buf, track, ref_size,
4550 total_size = ffio_close_null_buf(avio_buf);
4555 static int mov_write_prft_tag(AVIOContext *pb, MOVMuxContext *mov, int tracks)
4557 int64_t pos = avio_tell(pb), pts_us, ntp_ts;
4558 MOVTrack *first_track;
4560 /* PRFT should be associated with at most one track. So, choosing only the
4564 first_track = &(mov->tracks[0]);
4566 if (!first_track->entry) {
4567 av_log(mov->fc, AV_LOG_WARNING, "Unable to write PRFT, no entries in the track\n");
4571 if (first_track->cluster[0].pts == AV_NOPTS_VALUE) {
4572 av_log(mov->fc, AV_LOG_WARNING, "Unable to write PRFT, first PTS is invalid\n");
4576 if (mov->write_prft == MOV_PRFT_SRC_WALLCLOCK) {
4577 ntp_ts = ff_get_formatted_ntp_time(ff_ntp_time());
4578 } else if (mov->write_prft == MOV_PRFT_SRC_PTS) {
4579 pts_us = av_rescale_q(first_track->cluster[0].pts,
4580 first_track->st->time_base, AV_TIME_BASE_Q);
4581 ntp_ts = ff_get_formatted_ntp_time(pts_us + NTP_OFFSET_US);
4583 av_log(mov->fc, AV_LOG_WARNING, "Unsupported PRFT box configuration: %d\n",
4588 avio_wb32(pb, 0); // Size place holder
4589 ffio_wfourcc(pb, "prft"); // Type
4590 avio_w8(pb, 1); // Version
4591 avio_wb24(pb, 0); // Flags
4592 avio_wb32(pb, first_track->track_id); // reference track ID
4593 avio_wb64(pb, ntp_ts); // NTP time stamp
4594 avio_wb64(pb, first_track->cluster[0].pts); //media time
4595 return update_size(pb, pos);
4598 static int mov_write_moof_tag(AVIOContext *pb, MOVMuxContext *mov, int tracks,
4601 AVIOContext *avio_buf;
4604 if ((ret = ffio_open_null_buf(&avio_buf)) < 0)
4606 mov_write_moof_tag_internal(avio_buf, mov, tracks, 0);
4607 moof_size = ffio_close_null_buf(avio_buf);
4609 if (mov->flags & FF_MOV_FLAG_DASH && !(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX))
4610 mov_write_sidx_tags(pb, mov, tracks, moof_size + 8 + mdat_size);
4612 if (mov->write_prft > MOV_PRFT_NONE && mov->write_prft < MOV_PRFT_NB)
4613 mov_write_prft_tag(pb, mov, tracks);
4615 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX ||
4616 !(mov->flags & FF_MOV_FLAG_SKIP_TRAILER) ||
4617 mov->ism_lookahead) {
4618 if ((ret = mov_add_tfra_entries(pb, mov, tracks, moof_size + 8 + mdat_size)) < 0)
4620 if (!(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) &&
4621 mov->flags & FF_MOV_FLAG_SKIP_TRAILER) {
4622 mov_prune_frag_info(mov, tracks, mov->ism_lookahead + 1);
4626 return mov_write_moof_tag_internal(pb, mov, tracks, moof_size);
4629 static int mov_write_tfra_tag(AVIOContext *pb, MOVTrack *track)
4631 int64_t pos = avio_tell(pb);
4634 avio_wb32(pb, 0); /* size placeholder */
4635 ffio_wfourcc(pb, "tfra");
4636 avio_w8(pb, 1); /* version */
4639 avio_wb32(pb, track->track_id);
4640 avio_wb32(pb, 0); /* length of traf/trun/sample num */
4641 avio_wb32(pb, track->nb_frag_info);
4642 for (i = 0; i < track->nb_frag_info; i++) {
4643 avio_wb64(pb, track->frag_info[i].time);
4644 avio_wb64(pb, track->frag_info[i].offset + track->data_offset);
4645 avio_w8(pb, 1); /* traf number */
4646 avio_w8(pb, 1); /* trun number */
4647 avio_w8(pb, 1); /* sample number */
4650 return update_size(pb, pos);
4653 static int mov_write_mfra_tag(AVIOContext *pb, MOVMuxContext *mov)
4655 int64_t pos = avio_tell(pb);
4658 avio_wb32(pb, 0); /* size placeholder */
4659 ffio_wfourcc(pb, "mfra");
4660 /* An empty mfra atom is enough to indicate to the publishing point that
4661 * the stream has ended. */
4662 if (mov->flags & FF_MOV_FLAG_ISML)
4663 return update_size(pb, pos);
4665 for (i = 0; i < mov->nb_streams; i++) {
4666 MOVTrack *track = &mov->tracks[i];
4667 if (track->nb_frag_info)
4668 mov_write_tfra_tag(pb, track);
4672 ffio_wfourcc(pb, "mfro");
4673 avio_wb32(pb, 0); /* version + flags */
4674 avio_wb32(pb, avio_tell(pb) + 4 - pos);
4676 return update_size(pb, pos);
4679 static int mov_write_mdat_tag(AVIOContext *pb, MOVMuxContext *mov)
4681 avio_wb32(pb, 8); // placeholder for extended size field (64 bit)
4682 ffio_wfourcc(pb, mov->mode == MODE_MOV ? "wide" : "free");
4684 mov->mdat_pos = avio_tell(pb);
4685 avio_wb32(pb, 0); /* size placeholder*/
4686 ffio_wfourcc(pb, "mdat");
4690 /* TODO: This needs to be more general */
4691 static int mov_write_ftyp_tag(AVIOContext *pb, AVFormatContext *s)
4693 MOVMuxContext *mov = s->priv_data;
4694 int64_t pos = avio_tell(pb);
4695 int has_h264 = 0, has_video = 0;
4699 for (i = 0; i < s->nb_streams; i++) {
4700 AVStream *st = s->streams[i];
4701 if (is_cover_image(st))
4703 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
4705 if (st->codecpar->codec_id == AV_CODEC_ID_H264)
4709 avio_wb32(pb, 0); /* size */
4710 ffio_wfourcc(pb, "ftyp");
4712 if (mov->major_brand && strlen(mov->major_brand) >= 4)
4713 ffio_wfourcc(pb, mov->major_brand);
4714 else if (mov->mode == MODE_3GP) {
4715 ffio_wfourcc(pb, has_h264 ? "3gp6" : "3gp4");
4716 minor = has_h264 ? 0x100 : 0x200;
4717 } else if (mov->mode & MODE_3G2) {
4718 ffio_wfourcc(pb, has_h264 ? "3g2b" : "3g2a");
4719 minor = has_h264 ? 0x20000 : 0x10000;
4720 } else if (mov->mode == MODE_PSP)
4721 ffio_wfourcc(pb, "MSNV");
4722 else if (mov->mode == MODE_MP4 && mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)
4723 ffio_wfourcc(pb, "iso5"); // Required when using default-base-is-moof
4724 else if (mov->mode == MODE_MP4 && mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS)
4725 ffio_wfourcc(pb, "iso4");
4726 else if (mov->mode == MODE_MP4)
4727 ffio_wfourcc(pb, "isom");
4728 else if (mov->mode == MODE_IPOD)
4729 ffio_wfourcc(pb, has_video ? "M4V ":"M4A ");
4730 else if (mov->mode == MODE_ISM)
4731 ffio_wfourcc(pb, "isml");
4732 else if (mov->mode == MODE_F4V)
4733 ffio_wfourcc(pb, "f4v ");
4735 ffio_wfourcc(pb, "qt ");
4737 avio_wb32(pb, minor);
4739 if (mov->mode == MODE_MOV)
4740 ffio_wfourcc(pb, "qt ");
4741 else if (mov->mode == MODE_ISM) {
4742 ffio_wfourcc(pb, "piff");
4743 } else if (!(mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)) {
4744 ffio_wfourcc(pb, "isom");
4745 ffio_wfourcc(pb, "iso2");
4747 ffio_wfourcc(pb, "avc1");
4750 // We add tfdt atoms when fragmenting, signal this with the iso6 compatible
4751 // brand. This is compatible with users that don't understand tfdt.
4752 if (mov->flags & FF_MOV_FLAG_FRAGMENT && mov->mode != MODE_ISM)
4753 ffio_wfourcc(pb, "iso6");
4755 if (mov->mode == MODE_3GP)
4756 ffio_wfourcc(pb, has_h264 ? "3gp6":"3gp4");
4757 else if (mov->mode & MODE_3G2)
4758 ffio_wfourcc(pb, has_h264 ? "3g2b":"3g2a");
4759 else if (mov->mode == MODE_PSP)
4760 ffio_wfourcc(pb, "MSNV");
4761 else if (mov->mode == MODE_MP4)
4762 ffio_wfourcc(pb, "mp41");
4764 if (mov->flags & FF_MOV_FLAG_DASH && mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
4765 ffio_wfourcc(pb, "dash");
4767 return update_size(pb, pos);
4770 static int mov_write_uuidprof_tag(AVIOContext *pb, AVFormatContext *s)
4772 AVStream *video_st = s->streams[0];
4773 AVCodecParameters *video_par = s->streams[0]->codecpar;
4774 AVCodecParameters *audio_par = s->streams[1]->codecpar;
4775 int audio_rate = audio_par->sample_rate;
4776 int64_t frame_rate = video_st->avg_frame_rate.den ?
4777 (video_st->avg_frame_rate.num * 0x10000LL) / video_st->avg_frame_rate.den :
4779 int audio_kbitrate = audio_par->bit_rate / 1000;
4780 int video_kbitrate = FFMIN(video_par->bit_rate / 1000, 800 - audio_kbitrate);
4782 if (frame_rate < 0 || frame_rate > INT32_MAX) {
4783 av_log(s, AV_LOG_ERROR, "Frame rate %f outside supported range\n", frame_rate / (double)0x10000);
4784 return AVERROR(EINVAL);
4787 avio_wb32(pb, 0x94); /* size */
4788 ffio_wfourcc(pb, "uuid");
4789 ffio_wfourcc(pb, "PROF");
4791 avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
4792 avio_wb32(pb, 0xbb88695c);
4793 avio_wb32(pb, 0xfac9c740);
4795 avio_wb32(pb, 0x0); /* ? */
4796 avio_wb32(pb, 0x3); /* 3 sections ? */
4798 avio_wb32(pb, 0x14); /* size */
4799 ffio_wfourcc(pb, "FPRF");
4800 avio_wb32(pb, 0x0); /* ? */
4801 avio_wb32(pb, 0x0); /* ? */
4802 avio_wb32(pb, 0x0); /* ? */
4804 avio_wb32(pb, 0x2c); /* size */
4805 ffio_wfourcc(pb, "APRF"); /* audio */
4807 avio_wb32(pb, 0x2); /* TrackID */
4808 ffio_wfourcc(pb, "mp4a");
4809 avio_wb32(pb, 0x20f);
4811 avio_wb32(pb, audio_kbitrate);
4812 avio_wb32(pb, audio_kbitrate);
4813 avio_wb32(pb, audio_rate);
4814 avio_wb32(pb, audio_par->channels);
4816 avio_wb32(pb, 0x34); /* size */
4817 ffio_wfourcc(pb, "VPRF"); /* video */
4819 avio_wb32(pb, 0x1); /* TrackID */
4820 if (video_par->codec_id == AV_CODEC_ID_H264) {
4821 ffio_wfourcc(pb, "avc1");
4822 avio_wb16(pb, 0x014D);
4823 avio_wb16(pb, 0x0015);
4825 ffio_wfourcc(pb, "mp4v");
4826 avio_wb16(pb, 0x0000);
4827 avio_wb16(pb, 0x0103);
4830 avio_wb32(pb, video_kbitrate);
4831 avio_wb32(pb, video_kbitrate);
4832 avio_wb32(pb, frame_rate);
4833 avio_wb32(pb, frame_rate);
4834 avio_wb16(pb, video_par->width);
4835 avio_wb16(pb, video_par->height);
4836 avio_wb32(pb, 0x010001); /* ? */
4841 static int mov_write_identification(AVIOContext *pb, AVFormatContext *s)
4843 MOVMuxContext *mov = s->priv_data;
4846 mov_write_ftyp_tag(pb,s);
4847 if (mov->mode == MODE_PSP) {
4848 int video_streams_nb = 0, audio_streams_nb = 0, other_streams_nb = 0;
4849 for (i = 0; i < s->nb_streams; i++) {
4850 AVStream *st = s->streams[i];
4851 if (is_cover_image(st))
4853 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
4855 else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
4861 if (video_streams_nb != 1 || audio_streams_nb != 1 || other_streams_nb) {
4862 av_log(s, AV_LOG_ERROR, "PSP mode need one video and one audio stream\n");
4863 return AVERROR(EINVAL);
4865 return mov_write_uuidprof_tag(pb, s);
4870 static int mov_parse_mpeg2_frame(AVPacket *pkt, uint32_t *flags)
4873 int i, closed_gop = 0;
4875 for (i = 0; i < pkt->size - 4; i++) {
4876 c = (c << 8) + pkt->data[i];
4877 if (c == 0x1b8) { // gop
4878 closed_gop = pkt->data[i + 4] >> 6 & 0x01;
4879 } else if (c == 0x100) { // pic
4880 int temp_ref = (pkt->data[i + 1] << 2) | (pkt->data[i + 2] >> 6);
4881 if (!temp_ref || closed_gop) // I picture is not reordered
4882 *flags = MOV_SYNC_SAMPLE;
4884 *flags = MOV_PARTIAL_SYNC_SAMPLE;
4891 static void mov_parse_vc1_frame(AVPacket *pkt, MOVTrack *trk)
4893 const uint8_t *start, *next, *end = pkt->data + pkt->size;
4894 int seq = 0, entry = 0;
4895 int key = pkt->flags & AV_PKT_FLAG_KEY;
4896 start = find_next_marker(pkt->data, end);
4897 for (next = start; next < end; start = next) {
4898 next = find_next_marker(start + 4, end);
4899 switch (AV_RB32(start)) {
4900 case VC1_CODE_SEQHDR:
4903 case VC1_CODE_ENTRYPOINT:
4906 case VC1_CODE_SLICE:
4907 trk->vc1_info.slices = 1;
4911 if (!trk->entry && trk->vc1_info.first_packet_seen)
4912 trk->vc1_info.first_frag_written = 1;
4913 if (!trk->entry && !trk->vc1_info.first_frag_written) {
4914 /* First packet in first fragment */
4915 trk->vc1_info.first_packet_seq = seq;
4916 trk->vc1_info.first_packet_entry = entry;
4917 trk->vc1_info.first_packet_seen = 1;
4918 } else if ((seq && !trk->vc1_info.packet_seq) ||
4919 (entry && !trk->vc1_info.packet_entry)) {
4921 for (i = 0; i < trk->entry; i++)
4922 trk->cluster[i].flags &= ~MOV_SYNC_SAMPLE;
4923 trk->has_keyframes = 0;
4925 trk->vc1_info.packet_seq = 1;
4927 trk->vc1_info.packet_entry = 1;
4928 if (!trk->vc1_info.first_frag_written) {
4929 /* First fragment */
4930 if ((!seq || trk->vc1_info.first_packet_seq) &&
4931 (!entry || trk->vc1_info.first_packet_entry)) {
4932 /* First packet had the same headers as this one, readd the
4933 * sync sample flag. */
4934 trk->cluster[0].flags |= MOV_SYNC_SAMPLE;
4935 trk->has_keyframes = 1;
4939 if (trk->vc1_info.packet_seq && trk->vc1_info.packet_entry)
4941 else if (trk->vc1_info.packet_seq)
4943 else if (trk->vc1_info.packet_entry)
4946 trk->cluster[trk->entry].flags |= MOV_SYNC_SAMPLE;
4947 trk->has_keyframes++;
4951 static int mov_flush_fragment_interleaving(AVFormatContext *s, MOVTrack *track)
4953 MOVMuxContext *mov = s->priv_data;
4958 if (!track->mdat_buf)
4960 if (!mov->mdat_buf) {
4961 if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0)
4964 buf_size = avio_close_dyn_buf(track->mdat_buf, &buf);
4965 track->mdat_buf = NULL;
4967 offset = avio_tell(mov->mdat_buf);
4968 avio_write(mov->mdat_buf, buf, buf_size);
4971 for (i = track->entries_flushed; i < track->entry; i++)
4972 track->cluster[i].pos += offset;
4973 track->entries_flushed = track->entry;
4977 static int mov_flush_fragment(AVFormatContext *s, int force)
4979 MOVMuxContext *mov = s->priv_data;
4980 int i, first_track = -1;
4981 int64_t mdat_size = 0;
4983 int has_video = 0, starts_with_key = 0, first_video_track = 1;
4985 if (!(mov->flags & FF_MOV_FLAG_FRAGMENT))
4988 // Try to fill in the duration of the last packet in each stream
4989 // from queued packets in the interleave queues. If the flushing
4990 // of fragments was triggered automatically by an AVPacket, we
4991 // already have reliable info for the end of that track, but other
4992 // tracks may need to be filled in.
4993 for (i = 0; i < s->nb_streams; i++) {
4994 MOVTrack *track = &mov->tracks[i];
4995 if (!track->end_reliable) {
4997 if (!ff_interleaved_peek(s, i, &pkt, 1)) {
4998 if (track->dts_shift != AV_NOPTS_VALUE)
4999 pkt.dts += track->dts_shift;
5000 track->track_duration = pkt.dts - track->start_dts;
5001 if (pkt.pts != AV_NOPTS_VALUE)
5002 track->end_pts = pkt.pts;
5004 track->end_pts = pkt.dts;
5009 for (i = 0; i < mov->nb_streams; i++) {
5010 MOVTrack *track = &mov->tracks[i];
5011 if (track->entry <= 1)
5013 // Sample durations are calculated as the diff of dts values,
5014 // but for the last sample in a fragment, we don't know the dts
5015 // of the first sample in the next fragment, so we have to rely
5016 // on what was set as duration in the AVPacket. Not all callers
5017 // set this though, so we might want to replace it with an
5018 // estimate if it currently is zero.
5019 if (get_cluster_duration(track, track->entry - 1) != 0)
5021 // Use the duration (i.e. dts diff) of the second last sample for
5022 // the last one. This is a wild guess (and fatal if it turns out
5023 // to be too long), but probably the best we can do - having a zero
5024 // duration is bad as well.
5025 track->track_duration += get_cluster_duration(track, track->entry - 2);
5026 track->end_pts += get_cluster_duration(track, track->entry - 2);
5027 if (!mov->missing_duration_warned) {
5028 av_log(s, AV_LOG_WARNING,
5029 "Estimating the duration of the last packet in a "
5030 "fragment, consider setting the duration field in "
5031 "AVPacket instead.\n");
5032 mov->missing_duration_warned = 1;
5036 if (!mov->moov_written) {
5037 int64_t pos = avio_tell(s->pb);
5039 int buf_size, moov_size;
5041 for (i = 0; i < mov->nb_streams; i++)
5042 if (!mov->tracks[i].entry && !is_cover_image(mov->tracks[i].st))
5044 /* Don't write the initial moov unless all tracks have data */
5045 if (i < mov->nb_streams && !force)
5048 moov_size = get_moov_size(s);
5049 for (i = 0; i < mov->nb_streams; i++)
5050 mov->tracks[i].data_offset = pos + moov_size + 8;
5052 avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_HEADER);
5053 if (mov->flags & FF_MOV_FLAG_DELAY_MOOV)
5054 mov_write_identification(s->pb, s);
5055 if ((ret = mov_write_moov_tag(s->pb, mov, s)) < 0)
5058 if (mov->flags & FF_MOV_FLAG_DELAY_MOOV) {
5059 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
5060 mov->reserved_header_pos = avio_tell(s->pb);
5062 mov->moov_written = 1;
5066 buf_size = avio_close_dyn_buf(mov->mdat_buf, &buf);
5067 mov->mdat_buf = NULL;
5068 avio_wb32(s->pb, buf_size + 8);
5069 ffio_wfourcc(s->pb, "mdat");
5070 avio_write(s->pb, buf, buf_size);
5073 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
5074 mov->reserved_header_pos = avio_tell(s->pb);
5076 mov->moov_written = 1;
5078 for (i = 0; i < mov->nb_streams; i++) {
5079 if (mov->tracks[i].entry)
5080 mov->tracks[i].frag_start += mov->tracks[i].start_dts +
5081 mov->tracks[i].track_duration -
5082 mov->tracks[i].cluster[0].dts;
5083 mov->tracks[i].entry = 0;
5084 mov->tracks[i].end_reliable = 0;
5090 if (mov->frag_interleave) {
5091 for (i = 0; i < mov->nb_streams; i++) {
5092 MOVTrack *track = &mov->tracks[i];
5094 if ((ret = mov_flush_fragment_interleaving(s, track)) < 0)
5100 mdat_size = avio_tell(mov->mdat_buf);
5103 for (i = 0; i < mov->nb_streams; i++) {
5104 MOVTrack *track = &mov->tracks[i];
5105 if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF || mov->frag_interleave)
5106 track->data_offset = 0;
5108 track->data_offset = mdat_size;
5109 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
5111 if (first_video_track) {
5113 starts_with_key = track->cluster[0].flags & MOV_SYNC_SAMPLE;
5114 first_video_track = 0;
5119 if (track->mdat_buf)
5120 mdat_size += avio_tell(track->mdat_buf);
5121 if (first_track < 0)
5128 avio_write_marker(s->pb,
5129 av_rescale(mov->tracks[first_track].cluster[0].dts, AV_TIME_BASE, mov->tracks[first_track].timescale),
5130 (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);
5132 for (i = 0; i < mov->nb_streams; i++) {
5133 MOVTrack *track = &mov->tracks[i];
5134 int buf_size, write_moof = 1, moof_tracks = -1;
5136 int64_t duration = 0;
5139 duration = track->start_dts + track->track_duration -
5140 track->cluster[0].dts;
5141 if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF) {
5142 if (!track->mdat_buf)
5144 mdat_size = avio_tell(track->mdat_buf);
5147 write_moof = i == first_track;
5153 mov_write_moof_tag(s->pb, mov, moof_tracks, mdat_size);
5156 avio_wb32(s->pb, mdat_size + 8);
5157 ffio_wfourcc(s->pb, "mdat");
5161 track->frag_start += duration;
5163 track->entries_flushed = 0;
5164 track->end_reliable = 0;
5165 if (!mov->frag_interleave) {
5166 if (!track->mdat_buf)
5168 buf_size = avio_close_dyn_buf(track->mdat_buf, &buf);
5169 track->mdat_buf = NULL;
5173 buf_size = avio_close_dyn_buf(mov->mdat_buf, &buf);
5174 mov->mdat_buf = NULL;
5177 avio_write(s->pb, buf, buf_size);
5187 static int mov_auto_flush_fragment(AVFormatContext *s, int force)
5189 MOVMuxContext *mov = s->priv_data;
5190 int had_moov = mov->moov_written;
5191 int ret = mov_flush_fragment(s, force);
5194 // If using delay_moov, the first flush only wrote the moov,
5195 // not the actual moof+mdat pair, thus flush once again.
5196 if (!had_moov && mov->flags & FF_MOV_FLAG_DELAY_MOOV)
5197 ret = mov_flush_fragment(s, force);
5201 static int check_pkt(AVFormatContext *s, AVPacket *pkt)
5203 MOVMuxContext *mov = s->priv_data;
5204 MOVTrack *trk = &mov->tracks[pkt->stream_index];
5209 ref = trk->cluster[trk->entry - 1].dts;
5210 } else if ( trk->start_dts != AV_NOPTS_VALUE
5211 && !trk->frag_discont) {
5212 ref = trk->start_dts + trk->track_duration;
5214 ref = pkt->dts; // Skip tests for the first packet
5216 if (trk->dts_shift != AV_NOPTS_VALUE) {
5217 /* With negative CTS offsets we have set an offset to the DTS,
5218 * reverse this for the check. */
5219 ref -= trk->dts_shift;
5222 duration = pkt->dts - ref;
5223 if (pkt->dts < ref || duration >= INT_MAX) {
5224 av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" / timestamp: %"PRId64" is out of range for mov/mp4 format\n",
5229 pkt->pts = AV_NOPTS_VALUE;
5232 if (pkt->duration < 0 || pkt->duration > INT_MAX) {
5233 av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" is invalid\n", pkt->duration);
5234 return AVERROR(EINVAL);
5239 int ff_mov_write_packet(AVFormatContext *s, AVPacket *pkt)
5241 MOVMuxContext *mov = s->priv_data;
5242 AVIOContext *pb = s->pb;
5243 MOVTrack *trk = &mov->tracks[pkt->stream_index];
5244 AVCodecParameters *par = trk->par;
5245 unsigned int samples_in_chunk = 0;
5246 int size = pkt->size, ret = 0;
5247 uint8_t *reformatted_data = NULL;
5249 ret = check_pkt(s, pkt);
5253 if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
5255 if (mov->moov_written || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
5256 if (mov->frag_interleave && mov->fragments > 0) {
5257 if (trk->entry - trk->entries_flushed >= mov->frag_interleave) {
5258 if ((ret = mov_flush_fragment_interleaving(s, trk)) < 0)
5263 if (!trk->mdat_buf) {
5264 if ((ret = avio_open_dyn_buf(&trk->mdat_buf)) < 0)
5269 if (!mov->mdat_buf) {
5270 if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0)
5277 if (par->codec_id == AV_CODEC_ID_AMR_NB) {
5278 /* We must find out how many AMR blocks there are in one packet */
5279 static const uint16_t packed_size[16] =
5280 {13, 14, 16, 18, 20, 21, 27, 32, 6, 0, 0, 0, 0, 0, 0, 1};
5283 while (len < size && samples_in_chunk < 100) {
5284 len += packed_size[(pkt->data[len] >> 3) & 0x0F];
5287 if (samples_in_chunk > 1) {
5288 av_log(s, AV_LOG_ERROR, "fatal error, input is not a single packet, implement a AVParser for it\n");
5291 } else if (par->codec_id == AV_CODEC_ID_ADPCM_MS ||
5292 par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) {
5293 samples_in_chunk = trk->par->frame_size;
5294 } else if (trk->sample_size)
5295 samples_in_chunk = size / trk->sample_size;
5297 samples_in_chunk = 1;
5299 if (samples_in_chunk < 1) {
5300 av_log(s, AV_LOG_ERROR, "fatal error, input packet contains no samples\n");
5301 return AVERROR_PATCHWELCOME;
5304 /* copy extradata if it exists */
5305 if (trk->vos_len == 0 && par->extradata_size > 0 &&
5306 !TAG_IS_AVCI(trk->tag) &&
5307 (par->codec_id != AV_CODEC_ID_DNXHD)) {
5308 trk->vos_len = par->extradata_size;
5309 trk->vos_data = av_malloc(trk->vos_len);
5310 if (!trk->vos_data) {
5311 ret = AVERROR(ENOMEM);
5314 memcpy(trk->vos_data, par->extradata, trk->vos_len);
5317 if (par->codec_id == AV_CODEC_ID_AAC && pkt->size > 2 &&
5318 (AV_RB16(pkt->data) & 0xfff0) == 0xfff0) {
5319 if (!s->streams[pkt->stream_index]->nb_frames) {
5320 av_log(s, AV_LOG_ERROR, "Malformed AAC bitstream detected: "
5321 "use the audio bitstream filter 'aac_adtstoasc' to fix it "
5322 "('-bsf:a aac_adtstoasc' option with ffmpeg)\n");
5325 av_log(s, AV_LOG_WARNING, "aac bitstream error\n");
5327 if (par->codec_id == AV_CODEC_ID_H264 && trk->vos_len > 0 && *(uint8_t *)trk->vos_data != 1 && !TAG_IS_AVCI(trk->tag)) {
5328 /* from x264 or from bytestream H.264 */
5329 /* NAL reformatting needed */
5330 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
5331 ff_avc_parse_nal_units_buf(pkt->data, &reformatted_data,
5333 avio_write(pb, reformatted_data, size);
5335 if (trk->cenc.aes_ctr) {
5336 size = ff_mov_cenc_avc_parse_nal_units(&trk->cenc, pb, pkt->data, size);
5342 size = ff_avc_parse_nal_units(pb, pkt->data, pkt->size);
5345 } else if (par->codec_id == AV_CODEC_ID_HEVC && trk->vos_len > 6 &&
5346 (AV_RB24(trk->vos_data) == 1 || AV_RB32(trk->vos_data) == 1)) {
5347 /* extradata is Annex B, assume the bitstream is too and convert it */
5348 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
5349 ff_hevc_annexb2mp4_buf(pkt->data, &reformatted_data, &size, 0, NULL);
5350 avio_write(pb, reformatted_data, size);
5352 size = ff_hevc_annexb2mp4(pb, pkt->data, pkt->size, 0, NULL);
5354 } else if (par->codec_id == AV_CODEC_ID_AV1) {
5355 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
5356 ff_av1_filter_obus_buf(pkt->data, &reformatted_data, &size);
5357 avio_write(pb, reformatted_data, size);
5359 size = ff_av1_filter_obus(pb, pkt->data, pkt->size);
5361 #if CONFIG_AC3_PARSER
5362 } else if (par->codec_id == AV_CODEC_ID_EAC3) {
5363 size = handle_eac3(mov, pkt, trk);
5368 avio_write(pb, pkt->data, size);
5371 if (trk->cenc.aes_ctr) {
5372 if (par->codec_id == AV_CODEC_ID_H264 && par->extradata_size > 4) {
5373 int nal_size_length = (par->extradata[4] & 0x3) + 1;
5374 ret = ff_mov_cenc_avc_write_nal_units(s, &trk->cenc, nal_size_length, pb, pkt->data, size);
5376 ret = ff_mov_cenc_write_packet(&trk->cenc, pb, pkt->data, size);
5383 avio_write(pb, pkt->data, size);
5387 if ((par->codec_id == AV_CODEC_ID_DNXHD ||
5388 par->codec_id == AV_CODEC_ID_AC3) && !trk->vos_len) {
5389 /* copy frame to create needed atoms */
5390 trk->vos_len = size;
5391 trk->vos_data = av_malloc(size);
5392 if (!trk->vos_data) {
5393 ret = AVERROR(ENOMEM);
5396 memcpy(trk->vos_data, pkt->data, size);
5399 if (trk->entry >= trk->cluster_capacity) {
5400 unsigned new_capacity = 2 * (trk->entry + MOV_INDEX_CLUSTER_SIZE);
5401 if (av_reallocp_array(&trk->cluster, new_capacity,
5402 sizeof(*trk->cluster))) {
5403 ret = AVERROR(ENOMEM);
5406 trk->cluster_capacity = new_capacity;
5409 trk->cluster[trk->entry].pos = avio_tell(pb) - size;
5410 trk->cluster[trk->entry].samples_in_chunk = samples_in_chunk;
5411 trk->cluster[trk->entry].chunkNum = 0;
5412 trk->cluster[trk->entry].size = size;
5413 trk->cluster[trk->entry].entries = samples_in_chunk;
5414 trk->cluster[trk->entry].dts = pkt->dts;
5415 trk->cluster[trk->entry].pts = pkt->pts;
5416 if (!trk->entry && trk->start_dts != AV_NOPTS_VALUE) {
5417 if (!trk->frag_discont) {
5418 /* First packet of a new fragment. We already wrote the duration
5419 * of the last packet of the previous fragment based on track_duration,
5420 * which might not exactly match our dts. Therefore adjust the dts
5421 * of this packet to be what the previous packets duration implies. */
5422 trk->cluster[trk->entry].dts = trk->start_dts + trk->track_duration;
5423 /* We also may have written the pts and the corresponding duration
5424 * in sidx/tfrf/tfxd tags; make sure the sidx pts and duration match up with
5425 * the next fragment. This means the cts of the first sample must
5426 * be the same in all fragments, unless end_pts was updated by
5427 * the packet causing the fragment to be written. */
5428 if ((mov->flags & FF_MOV_FLAG_DASH && !(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)) ||
5429 mov->mode == MODE_ISM)
5430 pkt->pts = pkt->dts + trk->end_pts - trk->cluster[trk->entry].dts;
5432 /* New fragment, but discontinuous from previous fragments.
5433 * Pretend the duration sum of the earlier fragments is
5434 * pkt->dts - trk->start_dts. */
5435 trk->frag_start = pkt->dts - trk->start_dts;
5436 trk->end_pts = AV_NOPTS_VALUE;
5437 trk->frag_discont = 0;
5441 if (!trk->entry && trk->start_dts == AV_NOPTS_VALUE && !mov->use_editlist &&
5442 s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO) {
5443 /* Not using edit lists and shifting the first track to start from zero.
5444 * If the other streams start from a later timestamp, we won't be able
5445 * to signal the difference in starting time without an edit list.
5446 * Thus move the timestamp for this first sample to 0, increasing
5447 * its duration instead. */
5448 trk->cluster[trk->entry].dts = trk->start_dts = 0;
5450 if (trk->start_dts == AV_NOPTS_VALUE) {
5451 trk->start_dts = pkt->dts;
5452 if (trk->frag_discont) {
5453 if (mov->use_editlist) {
5454 /* Pretend the whole stream started at pts=0, with earlier fragments
5455 * already written. If the stream started at pts=0, the duration sum
5456 * of earlier fragments would have been pkt->pts. */
5457 trk->frag_start = pkt->pts;
5458 trk->start_dts = pkt->dts - pkt->pts;
5460 /* Pretend the whole stream started at dts=0, with earlier fragments
5461 * already written, with a duration summing up to pkt->dts. */
5462 trk->frag_start = pkt->dts;
5465 trk->frag_discont = 0;
5466 } else if (pkt->dts && mov->moov_written)
5467 av_log(s, AV_LOG_WARNING,
5468 "Track %d starts with a nonzero dts %"PRId64", while the moov "
5469 "already has been written. Set the delay_moov flag to handle "
5471 pkt->stream_index, pkt->dts);
5473 trk->track_duration = pkt->dts - trk->start_dts + pkt->duration;
5474 trk->last_sample_is_subtitle_end = 0;
5476 if (pkt->pts == AV_NOPTS_VALUE) {
5477 av_log(s, AV_LOG_WARNING, "pts has no value\n");
5478 pkt->pts = pkt->dts;
5480 if (pkt->dts != pkt->pts)
5481 trk->flags |= MOV_TRACK_CTTS;
5482 trk->cluster[trk->entry].cts = pkt->pts - pkt->dts;
5483 trk->cluster[trk->entry].flags = 0;
5484 if (trk->start_cts == AV_NOPTS_VALUE)
5485 trk->start_cts = pkt->pts - pkt->dts;
5486 if (trk->end_pts == AV_NOPTS_VALUE)
5487 trk->end_pts = trk->cluster[trk->entry].dts +
5488 trk->cluster[trk->entry].cts + pkt->duration;
5490 trk->end_pts = FFMAX(trk->end_pts, trk->cluster[trk->entry].dts +
5491 trk->cluster[trk->entry].cts +
5494 if (par->codec_id == AV_CODEC_ID_VC1) {
5495 mov_parse_vc1_frame(pkt, trk);
5496 } else if (pkt->flags & AV_PKT_FLAG_KEY) {
5497 if (mov->mode == MODE_MOV && par->codec_id == AV_CODEC_ID_MPEG2VIDEO &&
5498 trk->entry > 0) { // force sync sample for the first key frame
5499 mov_parse_mpeg2_frame(pkt, &trk->cluster[trk->entry].flags);
5500 if (trk->cluster[trk->entry].flags & MOV_PARTIAL_SYNC_SAMPLE)
5501 trk->flags |= MOV_TRACK_STPS;
5503 trk->cluster[trk->entry].flags = MOV_SYNC_SAMPLE;
5505 if (trk->cluster[trk->entry].flags & MOV_SYNC_SAMPLE)
5506 trk->has_keyframes++;
5508 if (pkt->flags & AV_PKT_FLAG_DISPOSABLE) {
5509 trk->cluster[trk->entry].flags |= MOV_DISPOSABLE_SAMPLE;
5510 trk->has_disposable++;
5513 trk->sample_count += samples_in_chunk;
5514 mov->mdat_size += size;
5516 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams)
5517 ff_mov_add_hinted_packet(s, pkt, trk->hint_track, trk->entry,
5518 reformatted_data, size);
5523 av_free(reformatted_data);
5527 static int mov_write_single_packet(AVFormatContext *s, AVPacket *pkt)
5529 MOVMuxContext *mov = s->priv_data;
5530 MOVTrack *trk = &mov->tracks[pkt->stream_index];
5531 AVCodecParameters *par = trk->par;
5532 int64_t frag_duration = 0;
5533 int size = pkt->size;
5535 int ret = check_pkt(s, pkt);
5539 if (mov->flags & FF_MOV_FLAG_FRAG_DISCONT) {
5541 for (i = 0; i < s->nb_streams; i++)
5542 mov->tracks[i].frag_discont = 1;
5543 mov->flags &= ~FF_MOV_FLAG_FRAG_DISCONT;
5546 if (mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS) {
5547 if (trk->dts_shift == AV_NOPTS_VALUE)
5548 trk->dts_shift = pkt->pts - pkt->dts;
5549 pkt->dts += trk->dts_shift;
5552 if (trk->par->codec_id == AV_CODEC_ID_MP4ALS ||
5553 trk->par->codec_id == AV_CODEC_ID_AAC ||
5554 trk->par->codec_id == AV_CODEC_ID_AV1 ||
5555 trk->par->codec_id == AV_CODEC_ID_FLAC) {
5557 uint8_t *side = av_packet_get_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA, &side_size);
5558 if (side && side_size > 0 && (side_size != par->extradata_size || memcmp(side, par->extradata, side_size))) {
5559 void *newextra = av_mallocz(side_size + AV_INPUT_BUFFER_PADDING_SIZE);
5561 return AVERROR(ENOMEM);
5562 av_free(par->extradata);
5563 par->extradata = newextra;
5564 memcpy(par->extradata, side, side_size);
5565 par->extradata_size = side_size;
5566 if (!pkt->size) // Flush packet
5567 mov->need_rewrite_extradata = 1;
5572 if (trk->start_dts == AV_NOPTS_VALUE && trk->frag_discont) {
5573 trk->start_dts = pkt->dts;
5574 if (pkt->pts != AV_NOPTS_VALUE)
5575 trk->start_cts = pkt->pts - pkt->dts;
5580 return 0; /* Discard 0 sized packets */
5583 if (trk->entry && pkt->stream_index < s->nb_streams)
5584 frag_duration = av_rescale_q(pkt->dts - trk->cluster[0].dts,
5585 s->streams[pkt->stream_index]->time_base,
5587 if ((mov->max_fragment_duration &&
5588 frag_duration >= mov->max_fragment_duration) ||
5589 (mov->max_fragment_size && mov->mdat_size + size >= mov->max_fragment_size) ||
5590 (mov->flags & FF_MOV_FLAG_FRAG_KEYFRAME &&
5591 par->codec_type == AVMEDIA_TYPE_VIDEO &&
5592 trk->entry && pkt->flags & AV_PKT_FLAG_KEY) ||
5593 (mov->flags & FF_MOV_FLAG_FRAG_EVERY_FRAME)) {
5594 if (frag_duration >= mov->min_fragment_duration) {
5595 // Set the duration of this track to line up with the next
5596 // sample in this track. This avoids relying on AVPacket
5597 // duration, but only helps for this particular track, not
5598 // for the other ones that are flushed at the same time.
5599 trk->track_duration = pkt->dts - trk->start_dts;
5600 if (pkt->pts != AV_NOPTS_VALUE)
5601 trk->end_pts = pkt->pts;
5603 trk->end_pts = pkt->dts;
5604 trk->end_reliable = 1;
5605 mov_auto_flush_fragment(s, 0);
5609 return ff_mov_write_packet(s, pkt);
5612 static int mov_write_subtitle_end_packet(AVFormatContext *s,
5616 uint8_t data[2] = {0};
5619 av_init_packet(&end);
5620 end.size = sizeof(data);
5625 end.stream_index = stream_index;
5627 ret = mov_write_single_packet(s, &end);
5628 av_packet_unref(&end);
5633 static int mov_write_packet(AVFormatContext *s, AVPacket *pkt)
5635 MOVMuxContext *mov = s->priv_data;
5639 mov_flush_fragment(s, 1);
5643 trk = &mov->tracks[pkt->stream_index];
5645 if (is_cover_image(trk->st)) {
5648 if (trk->st->nb_frames >= 1) {
5649 if (trk->st->nb_frames == 1)
5650 av_log(s, AV_LOG_WARNING, "Got more than one picture in stream %d,"
5651 " ignoring.\n", pkt->stream_index);
5655 if ((ret = av_packet_ref(&trk->cover_image, pkt)) < 0)
5663 return mov_write_single_packet(s, pkt); /* Passthrough. */
5666 * Subtitles require special handling.
5668 * 1) For full complaince, every track must have a sample at
5669 * dts == 0, which is rarely true for subtitles. So, as soon
5670 * as we see any packet with dts > 0, write an empty subtitle
5671 * at dts == 0 for any subtitle track with no samples in it.
5673 * 2) For each subtitle track, check if the current packet's
5674 * dts is past the duration of the last subtitle sample. If
5675 * so, we now need to write an end sample for that subtitle.
5677 * This must be done conditionally to allow for subtitles that
5678 * immediately replace each other, in which case an end sample
5679 * is not needed, and is, in fact, actively harmful.
5681 * 3) See mov_write_trailer for how the final end sample is
5684 for (i = 0; i < mov->nb_streams; i++) {
5685 MOVTrack *trk = &mov->tracks[i];
5688 if (trk->par->codec_id == AV_CODEC_ID_MOV_TEXT &&
5689 trk->track_duration < pkt->dts &&
5690 (trk->entry == 0 || !trk->last_sample_is_subtitle_end)) {
5691 ret = mov_write_subtitle_end_packet(s, i, trk->track_duration);
5692 if (ret < 0) return ret;
5693 trk->last_sample_is_subtitle_end = 1;
5697 if (trk->mode == MODE_MOV && trk->par->codec_type == AVMEDIA_TYPE_VIDEO) {
5698 AVPacket *opkt = pkt;
5699 int reshuffle_ret, ret;
5700 if (trk->is_unaligned_qt_rgb) {
5701 int64_t bpc = trk->par->bits_per_coded_sample != 15 ? trk->par->bits_per_coded_sample : 16;
5702 int expected_stride = ((trk->par->width * bpc + 15) >> 4)*2;
5703 reshuffle_ret = ff_reshuffle_raw_rgb(s, &pkt, trk->par, expected_stride);
5704 if (reshuffle_ret < 0)
5705 return reshuffle_ret;
5708 if (trk->par->format == AV_PIX_FMT_PAL8 && !trk->pal_done) {
5709 ret = ff_get_packet_palette(s, opkt, reshuffle_ret, trk->palette);
5714 } else if (trk->par->codec_id == AV_CODEC_ID_RAWVIDEO &&
5715 (trk->par->format == AV_PIX_FMT_GRAY8 ||
5716 trk->par->format == AV_PIX_FMT_MONOBLACK)) {
5717 for (i = 0; i < pkt->size; i++)
5718 pkt->data[i] = ~pkt->data[i];
5720 if (reshuffle_ret) {
5721 ret = mov_write_single_packet(s, pkt);
5724 av_packet_free(&pkt);
5729 return mov_write_single_packet(s, pkt);
5733 // QuickTime chapters involve an additional text track with the chapter names
5734 // as samples, and a tref pointing from the other tracks to the chapter one.
5735 static int mov_create_chapter_track(AVFormatContext *s, int tracknum)
5739 MOVMuxContext *mov = s->priv_data;
5740 MOVTrack *track = &mov->tracks[tracknum];
5741 AVPacket pkt = { .stream_index = tracknum, .flags = AV_PKT_FLAG_KEY };
5744 track->mode = mov->mode;
5745 track->tag = MKTAG('t','e','x','t');
5746 track->timescale = MOV_TIMESCALE;
5747 track->par = avcodec_parameters_alloc();
5749 return AVERROR(ENOMEM);
5750 track->par->codec_type = AVMEDIA_TYPE_SUBTITLE;
5752 // These properties are required to make QT recognize the chapter track
5753 uint8_t chapter_properties[43] = { 0, 0, 0, 0, 0, 0, 0, 1, };
5754 if (ff_alloc_extradata(track->par, sizeof(chapter_properties)))
5755 return AVERROR(ENOMEM);
5756 memcpy(track->par->extradata, chapter_properties, sizeof(chapter_properties));
5758 if (avio_open_dyn_buf(&pb) >= 0) {
5762 /* Stub header (usually for Quicktime chapter track) */
5764 avio_wb32(pb, 0x01); // displayFlags
5765 avio_w8(pb, 0x00); // horizontal justification
5766 avio_w8(pb, 0x00); // vertical justification
5767 avio_w8(pb, 0x00); // bgColourRed
5768 avio_w8(pb, 0x00); // bgColourGreen
5769 avio_w8(pb, 0x00); // bgColourBlue
5770 avio_w8(pb, 0x00); // bgColourAlpha
5772 avio_wb16(pb, 0x00); // defTextBoxTop
5773 avio_wb16(pb, 0x00); // defTextBoxLeft
5774 avio_wb16(pb, 0x00); // defTextBoxBottom
5775 avio_wb16(pb, 0x00); // defTextBoxRight
5777 avio_wb16(pb, 0x00); // startChar
5778 avio_wb16(pb, 0x00); // endChar
5779 avio_wb16(pb, 0x01); // fontID
5780 avio_w8(pb, 0x00); // fontStyleFlags
5781 avio_w8(pb, 0x00); // fontSize
5782 avio_w8(pb, 0x00); // fgColourRed
5783 avio_w8(pb, 0x00); // fgColourGreen
5784 avio_w8(pb, 0x00); // fgColourBlue
5785 avio_w8(pb, 0x00); // fgColourAlpha
5787 avio_wb32(pb, 0x0D); // box size
5788 ffio_wfourcc(pb, "ftab"); // box atom name
5789 avio_wb16(pb, 0x01); // entry count
5791 avio_wb16(pb, 0x01); // font ID
5792 avio_w8(pb, 0x00); // font name length
5794 if ((size = avio_close_dyn_buf(pb, &buf)) > 0) {
5795 track->par->extradata = buf;
5796 track->par->extradata_size = size;
5803 for (i = 0; i < s->nb_chapters; i++) {
5804 AVChapter *c = s->chapters[i];
5805 AVDictionaryEntry *t;
5807 int64_t end = av_rescale_q(c->end, c->time_base, (AVRational){1,MOV_TIMESCALE});
5808 pkt.pts = pkt.dts = av_rescale_q(c->start, c->time_base, (AVRational){1,MOV_TIMESCALE});
5809 pkt.duration = end - pkt.dts;
5811 if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
5812 static const char encd[12] = {
5813 0x00, 0x00, 0x00, 0x0C,
5815 0x00, 0x00, 0x01, 0x00 };
5816 len = strlen(t->value);
5817 pkt.size = len + 2 + 12;
5818 pkt.data = av_malloc(pkt.size);
5820 return AVERROR(ENOMEM);
5821 AV_WB16(pkt.data, len);
5822 memcpy(pkt.data + 2, t->value, len);
5823 memcpy(pkt.data + len + 2, encd, sizeof(encd));
5824 ff_mov_write_packet(s, &pkt);
5825 av_freep(&pkt.data);
5833 static int mov_check_timecode_track(AVFormatContext *s, AVTimecode *tc, int src_index, const char *tcstr)
5837 /* compute the frame number */
5838 ret = av_timecode_init_from_string(tc, find_fps(s, s->streams[src_index]), tcstr, s);
5842 static int mov_create_timecode_track(AVFormatContext *s, int index, int src_index, AVTimecode tc)
5845 MOVMuxContext *mov = s->priv_data;
5846 MOVTrack *track = &mov->tracks[index];
5847 AVStream *src_st = s->streams[src_index];
5848 AVPacket pkt = {.stream_index = index, .flags = AV_PKT_FLAG_KEY, .size = 4};
5849 AVRational rate = find_fps(s, src_st);
5851 /* tmcd track based on video stream */
5852 track->mode = mov->mode;
5853 track->tag = MKTAG('t','m','c','d');
5854 track->src_track = src_index;
5855 track->timescale = mov->tracks[src_index].timescale;
5856 if (tc.flags & AV_TIMECODE_FLAG_DROPFRAME)
5857 track->timecode_flags |= MOV_TIMECODE_FLAG_DROPFRAME;
5859 /* set st to src_st for metadata access*/
5862 /* encode context: tmcd data stream */
5863 track->par = avcodec_parameters_alloc();
5865 return AVERROR(ENOMEM);
5866 track->par->codec_type = AVMEDIA_TYPE_DATA;
5867 track->par->codec_tag = track->tag;
5868 track->st->avg_frame_rate = av_inv_q(rate);
5870 /* the tmcd track just contains one packet with the frame number */
5871 pkt.data = av_malloc(pkt.size);
5873 return AVERROR(ENOMEM);
5874 AV_WB32(pkt.data, tc.start);
5875 ret = ff_mov_write_packet(s, &pkt);
5881 * st->disposition controls the "enabled" flag in the tkhd tag.
5882 * QuickTime will not play a track if it is not enabled. So make sure
5883 * that one track of each type (audio, video, subtitle) is enabled.
5885 * Subtitles are special. For audio and video, setting "enabled" also
5886 * makes the track "default" (i.e. it is rendered when played). For
5887 * subtitles, an "enabled" subtitle is not rendered by default, but
5888 * if no subtitle is enabled, the subtitle menu in QuickTime will be
5891 static void enable_tracks(AVFormatContext *s)
5893 MOVMuxContext *mov = s->priv_data;
5895 int enabled[AVMEDIA_TYPE_NB];
5896 int first[AVMEDIA_TYPE_NB];
5898 for (i = 0; i < AVMEDIA_TYPE_NB; i++) {
5903 for (i = 0; i < s->nb_streams; i++) {
5904 AVStream *st = s->streams[i];
5906 if (st->codecpar->codec_type <= AVMEDIA_TYPE_UNKNOWN ||
5907 st->codecpar->codec_type >= AVMEDIA_TYPE_NB ||
5911 if (first[st->codecpar->codec_type] < 0)
5912 first[st->codecpar->codec_type] = i;
5913 if (st->disposition & AV_DISPOSITION_DEFAULT) {
5914 mov->tracks[i].flags |= MOV_TRACK_ENABLED;
5915 enabled[st->codecpar->codec_type]++;
5919 for (i = 0; i < AVMEDIA_TYPE_NB; i++) {
5921 case AVMEDIA_TYPE_VIDEO:
5922 case AVMEDIA_TYPE_AUDIO:
5923 case AVMEDIA_TYPE_SUBTITLE:
5925 mov->per_stream_grouping = 1;
5926 if (!enabled[i] && first[i] >= 0)
5927 mov->tracks[first[i]].flags |= MOV_TRACK_ENABLED;
5933 static void mov_free(AVFormatContext *s)
5935 MOVMuxContext *mov = s->priv_data;
5938 if (mov->chapter_track) {
5939 if (mov->tracks[mov->chapter_track].par)
5940 av_freep(&mov->tracks[mov->chapter_track].par->extradata);
5941 av_freep(&mov->tracks[mov->chapter_track].par);
5944 for (i = 0; i < mov->nb_streams; i++) {
5945 if (mov->tracks[i].tag == MKTAG('r','t','p',' '))
5946 ff_mov_close_hinting(&mov->tracks[i]);
5947 else if (mov->tracks[i].tag == MKTAG('t','m','c','d') && mov->nb_meta_tmcd)
5948 av_freep(&mov->tracks[i].par);
5949 av_freep(&mov->tracks[i].cluster);
5950 av_freep(&mov->tracks[i].frag_info);
5951 av_packet_unref(&mov->tracks[i].cover_image);
5953 if (mov->tracks[i].vos_len)
5954 av_freep(&mov->tracks[i].vos_data);
5956 ff_mov_cenc_free(&mov->tracks[i].cenc);
5959 av_freep(&mov->tracks);
5962 static uint32_t rgb_to_yuv(uint32_t rgb)
5967 r = (rgb >> 16) & 0xFF;
5968 g = (rgb >> 8) & 0xFF;
5971 y = av_clip_uint8(( 16000 + 257 * r + 504 * g + 98 * b)/1000);
5972 cb = av_clip_uint8((128000 - 148 * r - 291 * g + 439 * b)/1000);
5973 cr = av_clip_uint8((128000 + 439 * r - 368 * g - 71 * b)/1000);
5975 return (y << 16) | (cr << 8) | cb;
5978 static int mov_create_dvd_sub_decoder_specific_info(MOVTrack *track,
5981 int i, width = 720, height = 480;
5982 int have_palette = 0, have_size = 0;
5983 uint32_t palette[16];
5984 char *cur = st->codecpar->extradata;
5986 while (cur && *cur) {
5987 if (strncmp("palette:", cur, 8) == 0) {
5989 count = sscanf(cur + 8,
5990 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
5991 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
5992 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
5993 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32"",
5994 &palette[ 0], &palette[ 1], &palette[ 2], &palette[ 3],
5995 &palette[ 4], &palette[ 5], &palette[ 6], &palette[ 7],
5996 &palette[ 8], &palette[ 9], &palette[10], &palette[11],
5997 &palette[12], &palette[13], &palette[14], &palette[15]);
5999 for (i = 0; i < count; i++) {
6000 palette[i] = rgb_to_yuv(palette[i]);
6003 } else if (!strncmp("size:", cur, 5)) {
6004 sscanf(cur + 5, "%dx%d", &width, &height);
6007 if (have_palette && have_size)
6009 cur += strcspn(cur, "\n\r");
6010 cur += strspn(cur, "\n\r");
6013 track->vos_data = av_malloc(16*4);
6014 if (!track->vos_data)
6015 return AVERROR(ENOMEM);
6016 for (i = 0; i < 16; i++) {
6017 AV_WB32(track->vos_data + i * 4, palette[i]);
6019 track->vos_len = 16 * 4;
6021 st->codecpar->width = width;
6022 st->codecpar->height = track->height = height;
6027 static int mov_init(AVFormatContext *s)
6029 MOVMuxContext *mov = s->priv_data;
6030 AVDictionaryEntry *global_tcr = av_dict_get(s->metadata, "timecode", NULL, 0);
6035 /* Default mode == MP4 */
6036 mov->mode = MODE_MP4;
6039 if (!strcmp("3gp", s->oformat->name)) mov->mode = MODE_3GP;
6040 else if (!strcmp("3g2", s->oformat->name)) mov->mode = MODE_3GP|MODE_3G2;
6041 else if (!strcmp("mov", s->oformat->name)) mov->mode = MODE_MOV;
6042 else if (!strcmp("psp", s->oformat->name)) mov->mode = MODE_PSP;
6043 else if (!strcmp("ipod",s->oformat->name)) mov->mode = MODE_IPOD;
6044 else if (!strcmp("ismv",s->oformat->name)) mov->mode = MODE_ISM;
6045 else if (!strcmp("f4v", s->oformat->name)) mov->mode = MODE_F4V;
6048 if (mov->flags & FF_MOV_FLAG_DELAY_MOOV)
6049 mov->flags |= FF_MOV_FLAG_EMPTY_MOOV;
6051 /* Set the FRAGMENT flag if any of the fragmentation methods are
6053 if (mov->max_fragment_duration || mov->max_fragment_size ||
6054 mov->flags & (FF_MOV_FLAG_EMPTY_MOOV |
6055 FF_MOV_FLAG_FRAG_KEYFRAME |
6056 FF_MOV_FLAG_FRAG_CUSTOM |
6057 FF_MOV_FLAG_FRAG_EVERY_FRAME))
6058 mov->flags |= FF_MOV_FLAG_FRAGMENT;
6060 /* Set other implicit flags immediately */
6061 if (mov->mode == MODE_ISM)
6062 mov->flags |= FF_MOV_FLAG_EMPTY_MOOV | FF_MOV_FLAG_SEPARATE_MOOF |
6063 FF_MOV_FLAG_FRAGMENT | FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS;
6064 if (mov->flags & FF_MOV_FLAG_DASH)
6065 mov->flags |= FF_MOV_FLAG_FRAGMENT | FF_MOV_FLAG_EMPTY_MOOV |
6066 FF_MOV_FLAG_DEFAULT_BASE_MOOF;
6068 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV && s->flags & AVFMT_FLAG_AUTO_BSF) {
6069 av_log(s, AV_LOG_VERBOSE, "Empty MOOV enabled; disabling automatic bitstream filtering\n");
6070 s->flags &= ~AVFMT_FLAG_AUTO_BSF;
6073 if (mov->flags & FF_MOV_FLAG_FASTSTART) {
6074 mov->reserved_moov_size = -1;
6077 if (mov->use_editlist < 0) {
6078 mov->use_editlist = 1;
6079 if (mov->flags & FF_MOV_FLAG_FRAGMENT &&
6080 !(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
6081 // If we can avoid needing an edit list by shifting the
6082 // tracks, prefer that over (trying to) write edit lists
6083 // in fragmented output.
6084 if (s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO ||
6085 s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO)
6086 mov->use_editlist = 0;
6089 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV &&
6090 !(mov->flags & FF_MOV_FLAG_DELAY_MOOV) && mov->use_editlist)
6091 av_log(s, AV_LOG_WARNING, "No meaningful edit list will be written when using empty_moov without delay_moov\n");
6093 if (!mov->use_editlist && s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO)
6094 s->avoid_negative_ts = AVFMT_AVOID_NEG_TS_MAKE_ZERO;
6096 /* Clear the omit_tfhd_offset flag if default_base_moof is set;
6097 * if the latter is set that's enough and omit_tfhd_offset doesn't
6098 * add anything extra on top of that. */
6099 if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET &&
6100 mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)
6101 mov->flags &= ~FF_MOV_FLAG_OMIT_TFHD_OFFSET;
6103 if (mov->frag_interleave &&
6104 mov->flags & (FF_MOV_FLAG_OMIT_TFHD_OFFSET | FF_MOV_FLAG_SEPARATE_MOOF)) {
6105 av_log(s, AV_LOG_ERROR,
6106 "Sample interleaving in fragments is mutually exclusive with "
6107 "omit_tfhd_offset and separate_moof\n");
6108 return AVERROR(EINVAL);
6111 /* Non-seekable output is ok if using fragmentation. If ism_lookahead
6112 * is enabled, we don't support non-seekable output at all. */
6113 if (!(s->pb->seekable & AVIO_SEEKABLE_NORMAL) &&
6114 (!(mov->flags & FF_MOV_FLAG_FRAGMENT) || mov->ism_lookahead)) {
6115 av_log(s, AV_LOG_ERROR, "muxer does not support non seekable output\n");
6116 return AVERROR(EINVAL);
6119 mov->nb_streams = s->nb_streams;
6120 if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters)
6121 mov->chapter_track = mov->nb_streams++;
6123 if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
6124 for (i = 0; i < s->nb_streams; i++)
6125 if (rtp_hinting_needed(s->streams[i]))
6129 if ( mov->write_tmcd == -1 && (mov->mode == MODE_MOV || mov->mode == MODE_MP4)
6130 || mov->write_tmcd == 1) {
6131 /* +1 tmcd track for each video stream with a timecode */
6132 for (i = 0; i < s->nb_streams; i++) {
6133 AVStream *st = s->streams[i];
6134 AVDictionaryEntry *t = global_tcr;
6135 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
6136 (t || (t=av_dict_get(st->metadata, "timecode", NULL, 0)))) {
6138 ret = mov_check_timecode_track(s, &tc, i, t->value);
6140 mov->nb_meta_tmcd++;
6144 /* check if there is already a tmcd track to remux */
6145 if (mov->nb_meta_tmcd) {
6146 for (i = 0; i < s->nb_streams; i++) {
6147 AVStream *st = s->streams[i];
6148 if (st->codecpar->codec_tag == MKTAG('t','m','c','d')) {
6149 av_log(s, AV_LOG_WARNING, "You requested a copy of the original timecode track "
6150 "so timecode metadata are now ignored\n");
6151 mov->nb_meta_tmcd = 0;
6156 mov->nb_streams += mov->nb_meta_tmcd;
6159 // Reserve an extra stream for chapters for the case where chapters
6160 // are written in the trailer
6161 mov->tracks = av_mallocz_array((mov->nb_streams + 1), sizeof(*mov->tracks));
6163 return AVERROR(ENOMEM);
6165 if (mov->encryption_scheme_str != NULL && strcmp(mov->encryption_scheme_str, "none") != 0) {
6166 if (strcmp(mov->encryption_scheme_str, "cenc-aes-ctr") == 0) {
6167 mov->encryption_scheme = MOV_ENC_CENC_AES_CTR;
6169 if (mov->encryption_key_len != AES_CTR_KEY_SIZE) {
6170 av_log(s, AV_LOG_ERROR, "Invalid encryption key len %d expected %d\n",
6171 mov->encryption_key_len, AES_CTR_KEY_SIZE);
6172 return AVERROR(EINVAL);
6175 if (mov->encryption_kid_len != CENC_KID_SIZE) {
6176 av_log(s, AV_LOG_ERROR, "Invalid encryption kid len %d expected %d\n",
6177 mov->encryption_kid_len, CENC_KID_SIZE);
6178 return AVERROR(EINVAL);
6181 av_log(s, AV_LOG_ERROR, "unsupported encryption scheme %s\n",
6182 mov->encryption_scheme_str);
6183 return AVERROR(EINVAL);
6187 for (i = 0; i < s->nb_streams; i++) {
6188 AVStream *st= s->streams[i];
6189 MOVTrack *track= &mov->tracks[i];
6190 AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0);
6193 track->par = st->codecpar;
6194 track->language = ff_mov_iso639_to_lang(lang?lang->value:"und", mov->mode!=MODE_MOV);
6195 if (track->language < 0)
6196 track->language = 0;
6197 track->mode = mov->mode;
6198 track->tag = mov_find_codec_tag(s, track);
6200 av_log(s, AV_LOG_ERROR, "Could not find tag for codec %s in stream #%d, "
6201 "codec not currently supported in container\n",
6202 avcodec_get_name(st->codecpar->codec_id), i);
6203 return AVERROR(EINVAL);
6205 /* If hinting of this track is enabled by a later hint track,
6206 * this is updated. */
6207 track->hint_track = -1;
6208 track->start_dts = AV_NOPTS_VALUE;
6209 track->start_cts = AV_NOPTS_VALUE;
6210 track->end_pts = AV_NOPTS_VALUE;
6211 track->dts_shift = AV_NOPTS_VALUE;
6212 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
6213 if (track->tag == MKTAG('m','x','3','p') || track->tag == MKTAG('m','x','3','n') ||
6214 track->tag == MKTAG('m','x','4','p') || track->tag == MKTAG('m','x','4','n') ||
6215 track->tag == MKTAG('m','x','5','p') || track->tag == MKTAG('m','x','5','n')) {
6216 if (st->codecpar->width != 720 || (st->codecpar->height != 608 && st->codecpar->height != 512)) {
6217 av_log(s, AV_LOG_ERROR, "D-10/IMX must use 720x608 or 720x512 video resolution\n");
6218 return AVERROR(EINVAL);
6220 track->height = track->tag >> 24 == 'n' ? 486 : 576;
6222 if (mov->video_track_timescale) {
6223 track->timescale = mov->video_track_timescale;
6225 track->timescale = st->time_base.den;
6226 while(track->timescale < 10000)
6227 track->timescale *= 2;
6229 if (st->codecpar->width > 65535 || st->codecpar->height > 65535) {
6230 av_log(s, AV_LOG_ERROR, "Resolution %dx%d too large for mov/mp4\n", st->codecpar->width, st->codecpar->height);
6231 return AVERROR(EINVAL);
6233 if (track->mode == MODE_MOV && track->timescale > 100000)
6234 av_log(s, AV_LOG_WARNING,
6235 "WARNING codec timebase is very high. If duration is too long,\n"
6236 "file may not be playable by quicktime. Specify a shorter timebase\n"
6237 "or choose different container.\n");
6238 if (track->mode == MODE_MOV &&
6239 track->par->codec_id == AV_CODEC_ID_RAWVIDEO &&
6240 track->tag == MKTAG('r','a','w',' ')) {
6241 enum AVPixelFormat pix_fmt = track->par->format;
6242 if (pix_fmt == AV_PIX_FMT_NONE && track->par->bits_per_coded_sample == 1)
6243 pix_fmt = AV_PIX_FMT_MONOWHITE;
6244 track->is_unaligned_qt_rgb =
6245 pix_fmt == AV_PIX_FMT_RGB24 ||
6246 pix_fmt == AV_PIX_FMT_BGR24 ||
6247 pix_fmt == AV_PIX_FMT_PAL8 ||
6248 pix_fmt == AV_PIX_FMT_GRAY8 ||
6249 pix_fmt == AV_PIX_FMT_MONOWHITE ||
6250 pix_fmt == AV_PIX_FMT_MONOBLACK;
6252 if (track->par->codec_id == AV_CODEC_ID_VP9 ||
6253 track->par->codec_id == AV_CODEC_ID_AV1) {
6254 if (track->mode != MODE_MP4) {
6255 av_log(s, AV_LOG_ERROR, "%s only supported in MP4.\n", avcodec_get_name(track->par->codec_id));
6256 return AVERROR(EINVAL);
6258 if (track->par->codec_id == AV_CODEC_ID_AV1 &&
6259 s->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
6260 av_log(s, AV_LOG_ERROR,
6261 "av1 in MP4 support is experimental, add "
6262 "'-strict %d' if you want to use it.\n",
6263 FF_COMPLIANCE_EXPERIMENTAL);
6264 return AVERROR_EXPERIMENTAL;
6266 } else if (track->par->codec_id == AV_CODEC_ID_VP8) {
6267 /* altref frames handling is not defined in the spec as of version v1.0,
6268 * so just forbid muxing VP8 streams altogether until a new version does */
6269 av_log(s, AV_LOG_ERROR, "VP8 muxing is currently not supported.\n");
6270 return AVERROR_PATCHWELCOME;
6272 } else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
6273 track->timescale = st->codecpar->sample_rate;
6274 if (!st->codecpar->frame_size && !av_get_bits_per_sample(st->codecpar->codec_id)) {
6275 av_log(s, AV_LOG_WARNING, "track %d: codec frame size is not set\n", i);
6276 track->audio_vbr = 1;
6277 }else if (st->codecpar->codec_id == AV_CODEC_ID_ADPCM_MS ||
6278 st->codecpar->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
6279 st->codecpar->codec_id == AV_CODEC_ID_ILBC){
6280 if (!st->codecpar->block_align) {
6281 av_log(s, AV_LOG_ERROR, "track %d: codec block align is not set for adpcm\n", i);
6282 return AVERROR(EINVAL);
6284 track->sample_size = st->codecpar->block_align;
6285 }else if (st->codecpar->frame_size > 1){ /* assume compressed audio */
6286 track->audio_vbr = 1;
6288 track->sample_size = (av_get_bits_per_sample(st->codecpar->codec_id) >> 3) * st->codecpar->channels;
6290 if (st->codecpar->codec_id == AV_CODEC_ID_ILBC ||
6291 st->codecpar->codec_id == AV_CODEC_ID_ADPCM_IMA_QT) {
6292 track->audio_vbr = 1;
6294 if (track->mode != MODE_MOV &&
6295 track->par->codec_id == AV_CODEC_ID_MP3 && track->timescale < 16000) {
6296 if (s->strict_std_compliance >= FF_COMPLIANCE_NORMAL) {
6297 av_log(s, AV_LOG_ERROR, "track %d: muxing mp3 at %dhz is not standard, to mux anyway set strict to -1\n",
6298 i, track->par->sample_rate);
6299 return AVERROR(EINVAL);
6301 av_log(s, AV_LOG_WARNING, "track %d: muxing mp3 at %dhz is not standard in MP4\n",
6302 i, track->par->sample_rate);
6305 if (track->par->codec_id == AV_CODEC_ID_FLAC ||
6306 track->par->codec_id == AV_CODEC_ID_OPUS) {
6307 if (track->mode != MODE_MP4) {
6308 av_log(s, AV_LOG_ERROR, "%s only supported in MP4.\n", avcodec_get_name(track->par->codec_id));
6309 return AVERROR(EINVAL);
6311 if (s->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
6312 av_log(s, AV_LOG_ERROR,
6313 "%s in MP4 support is experimental, add "
6314 "'-strict %d' if you want to use it.\n",
6315 avcodec_get_name(track->par->codec_id), FF_COMPLIANCE_EXPERIMENTAL);
6316 return AVERROR_EXPERIMENTAL;
6319 } else if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) {
6320 track->timescale = st->time_base.den;
6321 } else if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA) {
6322 track->timescale = st->time_base.den;
6324 track->timescale = MOV_TIMESCALE;
6327 track->height = st->codecpar->height;
6328 /* The ism specific timescale isn't mandatory, but is assumed by
6329 * some tools, such as mp4split. */
6330 if (mov->mode == MODE_ISM)
6331 track->timescale = 10000000;
6333 avpriv_set_pts_info(st, 64, 1, track->timescale);
6335 if (mov->encryption_scheme == MOV_ENC_CENC_AES_CTR) {
6336 ret = ff_mov_cenc_init(&track->cenc, mov->encryption_key,
6337 track->par->codec_id == AV_CODEC_ID_H264, s->flags & AVFMT_FLAG_BITEXACT);
6347 static int mov_write_header(AVFormatContext *s)
6349 AVIOContext *pb = s->pb;
6350 MOVMuxContext *mov = s->priv_data;
6351 AVDictionaryEntry *t, *global_tcr = av_dict_get(s->metadata, "timecode", NULL, 0);
6352 int i, ret, hint_track = 0, tmcd_track = 0, nb_tracks = s->nb_streams;
6354 if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters)
6357 if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
6358 hint_track = nb_tracks;
6359 for (i = 0; i < s->nb_streams; i++)
6360 if (rtp_hinting_needed(s->streams[i]))
6364 if (mov->mode == MODE_MOV || mov->mode == MODE_MP4)
6365 tmcd_track = nb_tracks;
6367 for (i = 0; i < s->nb_streams; i++) {
6369 AVStream *st= s->streams[i];
6370 MOVTrack *track= &mov->tracks[i];
6372 /* copy extradata if it exists */
6373 if (st->codecpar->extradata_size) {
6374 if (st->codecpar->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
6375 mov_create_dvd_sub_decoder_specific_info(track, st);
6376 else if (!TAG_IS_AVCI(track->tag) && st->codecpar->codec_id != AV_CODEC_ID_DNXHD) {
6377 track->vos_len = st->codecpar->extradata_size;
6378 track->vos_data = av_malloc(track->vos_len);
6379 if (!track->vos_data) {
6380 return AVERROR(ENOMEM);
6382 memcpy(track->vos_data, st->codecpar->extradata, track->vos_len);
6386 if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ||
6387 track->par->channel_layout != AV_CH_LAYOUT_MONO)
6390 for (j = 0; j < s->nb_streams; j++) {
6391 AVStream *stj= s->streams[j];
6392 MOVTrack *trackj= &mov->tracks[j];
6396 if (stj->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ||
6397 trackj->par->channel_layout != AV_CH_LAYOUT_MONO ||
6398 trackj->language != track->language ||
6399 trackj->tag != track->tag
6402 track->multichannel_as_mono++;
6406 if (!(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
6407 if ((ret = mov_write_identification(pb, s)) < 0)
6411 if (mov->reserved_moov_size){
6412 mov->reserved_header_pos = avio_tell(pb);
6413 if (mov->reserved_moov_size > 0)
6414 avio_skip(pb, mov->reserved_moov_size);
6417 if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
6418 /* If no fragmentation options have been set, set a default. */
6419 if (!(mov->flags & (FF_MOV_FLAG_FRAG_KEYFRAME |
6420 FF_MOV_FLAG_FRAG_CUSTOM |
6421 FF_MOV_FLAG_FRAG_EVERY_FRAME)) &&
6422 !mov->max_fragment_duration && !mov->max_fragment_size)
6423 mov->flags |= FF_MOV_FLAG_FRAG_KEYFRAME;
6425 if (mov->flags & FF_MOV_FLAG_FASTSTART)
6426 mov->reserved_header_pos = avio_tell(pb);
6427 mov_write_mdat_tag(pb, mov);
6430 ff_parse_creation_time_metadata(s, &mov->time, 1);
6432 mov->time += 0x7C25B080; // 1970 based -> 1904 based
6434 if (mov->chapter_track)
6435 if ((ret = mov_create_chapter_track(s, mov->chapter_track)) < 0)
6438 if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
6439 for (i = 0; i < s->nb_streams; i++) {
6440 if (rtp_hinting_needed(s->streams[i])) {
6441 if ((ret = ff_mov_init_hinting(s, hint_track, i)) < 0)
6448 if (mov->nb_meta_tmcd) {
6449 /* Initialize the tmcd tracks */
6450 for (i = 0; i < s->nb_streams; i++) {
6451 AVStream *st = s->streams[i];
6454 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
6457 t = av_dict_get(st->metadata, "timecode", NULL, 0);
6460 if (mov_check_timecode_track(s, &tc, i, t->value) < 0)
6462 if ((ret = mov_create_timecode_track(s, tmcd_track, i, tc)) < 0)
6471 if (mov->flags & FF_MOV_FLAG_ISML)
6472 mov_write_isml_manifest(pb, mov, s);
6474 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV &&
6475 !(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
6476 if ((ret = mov_write_moov_tag(pb, mov, s)) < 0)
6479 mov->moov_written = 1;
6480 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
6481 mov->reserved_header_pos = avio_tell(pb);
6487 static int get_moov_size(AVFormatContext *s)
6490 AVIOContext *moov_buf;
6491 MOVMuxContext *mov = s->priv_data;
6493 if ((ret = ffio_open_null_buf(&moov_buf)) < 0)
6495 if ((ret = mov_write_moov_tag(moov_buf, mov, s)) < 0)
6497 return ffio_close_null_buf(moov_buf);
6500 static int get_sidx_size(AVFormatContext *s)
6504 MOVMuxContext *mov = s->priv_data;
6506 if ((ret = ffio_open_null_buf(&buf)) < 0)
6508 mov_write_sidx_tags(buf, mov, -1, 0);
6509 return ffio_close_null_buf(buf);
6513 * This function gets the moov size if moved to the top of the file: the chunk
6514 * offset table can switch between stco (32-bit entries) to co64 (64-bit
6515 * entries) when the moov is moved to the beginning, so the size of the moov
6516 * would change. It also updates the chunk offset tables.
6518 static int compute_moov_size(AVFormatContext *s)
6520 int i, moov_size, moov_size2;
6521 MOVMuxContext *mov = s->priv_data;
6523 moov_size = get_moov_size(s);
6527 for (i = 0; i < mov->nb_streams; i++)
6528 mov->tracks[i].data_offset += moov_size;
6530 moov_size2 = get_moov_size(s);
6534 /* if the size changed, we just switched from stco to co64 and need to
6535 * update the offsets */
6536 if (moov_size2 != moov_size)
6537 for (i = 0; i < mov->nb_streams; i++)
6538 mov->tracks[i].data_offset += moov_size2 - moov_size;
6543 static int compute_sidx_size(AVFormatContext *s)
6546 MOVMuxContext *mov = s->priv_data;
6548 sidx_size = get_sidx_size(s);
6552 for (i = 0; i < mov->nb_streams; i++)
6553 mov->tracks[i].data_offset += sidx_size;
6558 static int shift_data(AVFormatContext *s)
6560 int ret = 0, moov_size;
6561 MOVMuxContext *mov = s->priv_data;
6562 int64_t pos, pos_end = avio_tell(s->pb);
6563 uint8_t *buf, *read_buf[2];
6564 int read_buf_id = 0;
6566 AVIOContext *read_pb;
6568 if (mov->flags & FF_MOV_FLAG_FRAGMENT)
6569 moov_size = compute_sidx_size(s);
6571 moov_size = compute_moov_size(s);
6575 buf = av_malloc(moov_size * 2);
6577 return AVERROR(ENOMEM);
6579 read_buf[1] = buf + moov_size;
6581 /* Shift the data: the AVIO context of the output can only be used for
6582 * writing, so we re-open the same output, but for reading. It also avoids
6583 * a read/seek/write/seek back and forth. */
6585 ret = s->io_open(s, &read_pb, s->url, AVIO_FLAG_READ, NULL);
6587 av_log(s, AV_LOG_ERROR, "Unable to re-open %s output file for "
6588 "the second pass (faststart)\n", s->url);
6592 /* mark the end of the shift to up to the last data we wrote, and get ready
6594 pos_end = avio_tell(s->pb);
6595 avio_seek(s->pb, mov->reserved_header_pos + moov_size, SEEK_SET);
6597 /* start reading at where the new moov will be placed */
6598 avio_seek(read_pb, mov->reserved_header_pos, SEEK_SET);
6599 pos = avio_tell(read_pb);
6601 #define READ_BLOCK do { \
6602 read_size[read_buf_id] = avio_read(read_pb, read_buf[read_buf_id], moov_size); \
6606 /* shift data by chunk of at most moov_size */
6611 n = read_size[read_buf_id];
6614 avio_write(s->pb, read_buf[read_buf_id], n);
6616 } while (pos < pos_end);
6617 ff_format_io_close(s, &read_pb);
6624 static int mov_write_trailer(AVFormatContext *s)
6626 MOVMuxContext *mov = s->priv_data;
6627 AVIOContext *pb = s->pb;
6632 if (mov->need_rewrite_extradata) {
6633 for (i = 0; i < s->nb_streams; i++) {
6634 MOVTrack *track = &mov->tracks[i];
6635 AVCodecParameters *par = track->par;
6637 track->vos_len = par->extradata_size;
6638 track->vos_data = av_malloc(track->vos_len);
6639 if (!track->vos_data)
6640 return AVERROR(ENOMEM);
6641 memcpy(track->vos_data, par->extradata, track->vos_len);
6643 mov->need_rewrite_extradata = 0;
6647 * Before actually writing the trailer, make sure that there are no
6648 * dangling subtitles, that need a terminating sample.
6650 for (i = 0; i < mov->nb_streams; i++) {
6651 MOVTrack *trk = &mov->tracks[i];
6652 if (trk->par->codec_id == AV_CODEC_ID_MOV_TEXT &&
6653 !trk->last_sample_is_subtitle_end) {
6654 mov_write_subtitle_end_packet(s, i, trk->track_duration);
6655 trk->last_sample_is_subtitle_end = 1;
6659 // If there were no chapters when the header was written, but there
6660 // are chapters now, write them in the trailer. This only works
6661 // when we are not doing fragments.
6662 if (!mov->chapter_track && !(mov->flags & FF_MOV_FLAG_FRAGMENT)) {
6663 if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters) {
6664 mov->chapter_track = mov->nb_streams++;
6665 if ((res = mov_create_chapter_track(s, mov->chapter_track)) < 0)
6670 if (!(mov->flags & FF_MOV_FLAG_FRAGMENT)) {
6671 moov_pos = avio_tell(pb);
6673 /* Write size of mdat tag */
6674 if (mov->mdat_size + 8 <= UINT32_MAX) {
6675 avio_seek(pb, mov->mdat_pos, SEEK_SET);
6676 avio_wb32(pb, mov->mdat_size + 8);
6678 /* overwrite 'wide' placeholder atom */
6679 avio_seek(pb, mov->mdat_pos - 8, SEEK_SET);
6680 /* special value: real atom size will be 64 bit value after
6683 ffio_wfourcc(pb, "mdat");
6684 avio_wb64(pb, mov->mdat_size + 16);
6686 avio_seek(pb, mov->reserved_moov_size > 0 ? mov->reserved_header_pos : moov_pos, SEEK_SET);
6688 if (mov->flags & FF_MOV_FLAG_FASTSTART) {
6689 av_log(s, AV_LOG_INFO, "Starting second pass: moving the moov atom to the beginning of the file\n");
6690 res = shift_data(s);
6693 avio_seek(pb, mov->reserved_header_pos, SEEK_SET);
6694 if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
6696 } else if (mov->reserved_moov_size > 0) {
6698 if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
6700 size = mov->reserved_moov_size - (avio_tell(pb) - mov->reserved_header_pos);
6702 av_log(s, AV_LOG_ERROR, "reserved_moov_size is too small, needed %"PRId64" additional\n", 8-size);
6703 return AVERROR(EINVAL);
6705 avio_wb32(pb, size);
6706 ffio_wfourcc(pb, "free");
6707 ffio_fill(pb, 0, size - 8);
6708 avio_seek(pb, moov_pos, SEEK_SET);
6710 if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
6715 mov_auto_flush_fragment(s, 1);
6716 for (i = 0; i < mov->nb_streams; i++)
6717 mov->tracks[i].data_offset = 0;
6718 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) {
6720 av_log(s, AV_LOG_INFO, "Starting second pass: inserting sidx atoms\n");
6721 res = shift_data(s);
6724 end = avio_tell(pb);
6725 avio_seek(pb, mov->reserved_header_pos, SEEK_SET);
6726 mov_write_sidx_tags(pb, mov, -1, 0);
6727 avio_seek(pb, end, SEEK_SET);
6728 avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_TRAILER);
6729 mov_write_mfra_tag(pb, mov);
6730 } else if (!(mov->flags & FF_MOV_FLAG_SKIP_TRAILER)) {
6731 avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_TRAILER);
6732 mov_write_mfra_tag(pb, mov);
6739 static int mov_check_bitstream(struct AVFormatContext *s, const AVPacket *pkt)
6742 AVStream *st = s->streams[pkt->stream_index];
6744 if (st->codecpar->codec_id == AV_CODEC_ID_AAC) {
6745 if (pkt->size > 2 && (AV_RB16(pkt->data) & 0xfff0) == 0xfff0)
6746 ret = ff_stream_add_bitstream_filter(st, "aac_adtstoasc", NULL);
6747 } else if (st->codecpar->codec_id == AV_CODEC_ID_VP9) {
6748 ret = ff_stream_add_bitstream_filter(st, "vp9_superframe", NULL);
6754 static const AVCodecTag codec_3gp_tags[] = {
6755 { AV_CODEC_ID_H263, MKTAG('s','2','6','3') },
6756 { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
6757 { AV_CODEC_ID_MPEG4, MKTAG('m','p','4','v') },
6758 { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
6759 { AV_CODEC_ID_AMR_NB, MKTAG('s','a','m','r') },
6760 { AV_CODEC_ID_AMR_WB, MKTAG('s','a','w','b') },
6761 { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
6762 { AV_CODEC_ID_NONE, 0 },
6765 const AVCodecTag codec_mp4_tags[] = {
6766 { AV_CODEC_ID_MPEG4 , MKTAG('m', 'p', '4', 'v') },
6767 { AV_CODEC_ID_H264 , MKTAG('a', 'v', 'c', '1') },
6768 { AV_CODEC_ID_H264 , MKTAG('a', 'v', 'c', '3') },
6769 { AV_CODEC_ID_HEVC , MKTAG('h', 'e', 'v', '1') },
6770 { AV_CODEC_ID_HEVC , MKTAG('h', 'v', 'c', '1') },
6771 { AV_CODEC_ID_MPEG2VIDEO , MKTAG('m', 'p', '4', 'v') },
6772 { AV_CODEC_ID_MPEG1VIDEO , MKTAG('m', 'p', '4', 'v') },
6773 { AV_CODEC_ID_MJPEG , MKTAG('m', 'p', '4', 'v') },
6774 { AV_CODEC_ID_PNG , MKTAG('m', 'p', '4', 'v') },
6775 { AV_CODEC_ID_JPEG2000 , MKTAG('m', 'p', '4', 'v') },
6776 { AV_CODEC_ID_VC1 , MKTAG('v', 'c', '-', '1') },
6777 { AV_CODEC_ID_DIRAC , MKTAG('d', 'r', 'a', 'c') },
6778 { AV_CODEC_ID_TSCC2 , MKTAG('m', 'p', '4', 'v') },
6779 { AV_CODEC_ID_VP9 , MKTAG('v', 'p', '0', '9') },
6780 { AV_CODEC_ID_AV1 , MKTAG('a', 'v', '0', '1') },
6781 { AV_CODEC_ID_AAC , MKTAG('m', 'p', '4', 'a') },
6782 { AV_CODEC_ID_MP4ALS , MKTAG('m', 'p', '4', 'a') },
6783 { AV_CODEC_ID_MP3 , MKTAG('m', 'p', '4', 'a') },
6784 { AV_CODEC_ID_MP2 , MKTAG('m', 'p', '4', 'a') },
6785 { AV_CODEC_ID_AC3 , MKTAG('a', 'c', '-', '3') },
6786 { AV_CODEC_ID_EAC3 , MKTAG('e', 'c', '-', '3') },
6787 { AV_CODEC_ID_DTS , MKTAG('m', 'p', '4', 'a') },
6788 { AV_CODEC_ID_FLAC , MKTAG('f', 'L', 'a', 'C') },
6789 { AV_CODEC_ID_OPUS , MKTAG('O', 'p', 'u', 's') },
6790 { AV_CODEC_ID_VORBIS , MKTAG('m', 'p', '4', 'a') },
6791 { AV_CODEC_ID_QCELP , MKTAG('m', 'p', '4', 'a') },
6792 { AV_CODEC_ID_EVRC , MKTAG('m', 'p', '4', 'a') },
6793 { AV_CODEC_ID_DVD_SUBTITLE, MKTAG('m', 'p', '4', 's') },
6794 { AV_CODEC_ID_MOV_TEXT , MKTAG('t', 'x', '3', 'g') },
6795 { AV_CODEC_ID_BIN_DATA , MKTAG('g', 'p', 'm', 'd') },
6796 { AV_CODEC_ID_NONE , 0 },
6799 const AVCodecTag codec_ism_tags[] = {
6800 { AV_CODEC_ID_WMAPRO , MKTAG('w', 'm', 'a', ' ') },
6801 { AV_CODEC_ID_NONE , 0 },
6804 static const AVCodecTag codec_ipod_tags[] = {
6805 { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
6806 { AV_CODEC_ID_MPEG4, MKTAG('m','p','4','v') },
6807 { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
6808 { AV_CODEC_ID_ALAC, MKTAG('a','l','a','c') },
6809 { AV_CODEC_ID_AC3, MKTAG('a','c','-','3') },
6810 { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
6811 { AV_CODEC_ID_MOV_TEXT, MKTAG('t','e','x','t') },
6812 { AV_CODEC_ID_NONE, 0 },
6815 static const AVCodecTag codec_f4v_tags[] = {
6816 { AV_CODEC_ID_MP3, MKTAG('.','m','p','3') },
6817 { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
6818 { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
6819 { AV_CODEC_ID_VP6A, MKTAG('V','P','6','A') },
6820 { AV_CODEC_ID_VP6F, MKTAG('V','P','6','F') },
6821 { AV_CODEC_ID_NONE, 0 },
6824 #if CONFIG_MOV_MUXER
6826 AVOutputFormat ff_mov_muxer = {
6828 .long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
6829 .extensions = "mov",
6830 .priv_data_size = sizeof(MOVMuxContext),
6831 .audio_codec = AV_CODEC_ID_AAC,
6832 .video_codec = CONFIG_LIBX264_ENCODER ?
6833 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
6835 .write_header = mov_write_header,
6836 .write_packet = mov_write_packet,
6837 .write_trailer = mov_write_trailer,
6839 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6840 .codec_tag = (const AVCodecTag* const []){
6841 ff_codec_movvideo_tags, ff_codec_movaudio_tags, 0
6843 .check_bitstream = mov_check_bitstream,
6844 .priv_class = &mov_muxer_class,
6847 #if CONFIG_TGP_MUXER
6849 AVOutputFormat ff_tgp_muxer = {
6851 .long_name = NULL_IF_CONFIG_SMALL("3GP (3GPP file format)"),
6852 .extensions = "3gp",
6853 .priv_data_size = sizeof(MOVMuxContext),
6854 .audio_codec = AV_CODEC_ID_AMR_NB,
6855 .video_codec = AV_CODEC_ID_H263,
6857 .write_header = mov_write_header,
6858 .write_packet = mov_write_packet,
6859 .write_trailer = mov_write_trailer,
6861 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6862 .codec_tag = (const AVCodecTag* const []){ codec_3gp_tags, 0 },
6863 .check_bitstream = mov_check_bitstream,
6864 .priv_class = &tgp_muxer_class,
6867 #if CONFIG_MP4_MUXER
6869 AVOutputFormat ff_mp4_muxer = {
6871 .long_name = NULL_IF_CONFIG_SMALL("MP4 (MPEG-4 Part 14)"),
6872 .mime_type = "video/mp4",
6873 .extensions = "mp4",
6874 .priv_data_size = sizeof(MOVMuxContext),
6875 .audio_codec = AV_CODEC_ID_AAC,
6876 .video_codec = CONFIG_LIBX264_ENCODER ?
6877 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
6879 .write_header = mov_write_header,
6880 .write_packet = mov_write_packet,
6881 .write_trailer = mov_write_trailer,
6883 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6884 .codec_tag = (const AVCodecTag* const []){ codec_mp4_tags, 0 },
6885 .check_bitstream = mov_check_bitstream,
6886 .priv_class = &mp4_muxer_class,
6889 #if CONFIG_PSP_MUXER
6891 AVOutputFormat ff_psp_muxer = {
6893 .long_name = NULL_IF_CONFIG_SMALL("PSP MP4 (MPEG-4 Part 14)"),
6894 .extensions = "mp4,psp",
6895 .priv_data_size = sizeof(MOVMuxContext),
6896 .audio_codec = AV_CODEC_ID_AAC,
6897 .video_codec = CONFIG_LIBX264_ENCODER ?
6898 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
6900 .write_header = mov_write_header,
6901 .write_packet = mov_write_packet,
6902 .write_trailer = mov_write_trailer,
6904 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6905 .codec_tag = (const AVCodecTag* const []){ codec_mp4_tags, 0 },
6906 .check_bitstream = mov_check_bitstream,
6907 .priv_class = &psp_muxer_class,
6910 #if CONFIG_TG2_MUXER
6912 AVOutputFormat ff_tg2_muxer = {
6914 .long_name = NULL_IF_CONFIG_SMALL("3GP2 (3GPP2 file format)"),
6915 .extensions = "3g2",
6916 .priv_data_size = sizeof(MOVMuxContext),
6917 .audio_codec = AV_CODEC_ID_AMR_NB,
6918 .video_codec = AV_CODEC_ID_H263,
6920 .write_header = mov_write_header,
6921 .write_packet = mov_write_packet,
6922 .write_trailer = mov_write_trailer,
6924 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6925 .codec_tag = (const AVCodecTag* const []){ codec_3gp_tags, 0 },
6926 .check_bitstream = mov_check_bitstream,
6927 .priv_class = &tg2_muxer_class,
6930 #if CONFIG_IPOD_MUXER
6932 AVOutputFormat ff_ipod_muxer = {
6934 .long_name = NULL_IF_CONFIG_SMALL("iPod H.264 MP4 (MPEG-4 Part 14)"),
6935 .mime_type = "video/mp4",
6936 .extensions = "m4v,m4a,m4b",
6937 .priv_data_size = sizeof(MOVMuxContext),
6938 .audio_codec = AV_CODEC_ID_AAC,
6939 .video_codec = AV_CODEC_ID_H264,
6941 .write_header = mov_write_header,
6942 .write_packet = mov_write_packet,
6943 .write_trailer = mov_write_trailer,
6945 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6946 .codec_tag = (const AVCodecTag* const []){ codec_ipod_tags, 0 },
6947 .check_bitstream = mov_check_bitstream,
6948 .priv_class = &ipod_muxer_class,
6951 #if CONFIG_ISMV_MUXER
6953 AVOutputFormat ff_ismv_muxer = {
6955 .long_name = NULL_IF_CONFIG_SMALL("ISMV/ISMA (Smooth Streaming)"),
6956 .mime_type = "video/mp4",
6957 .extensions = "ismv,isma",
6958 .priv_data_size = sizeof(MOVMuxContext),
6959 .audio_codec = AV_CODEC_ID_AAC,
6960 .video_codec = AV_CODEC_ID_H264,
6962 .write_header = mov_write_header,
6963 .write_packet = mov_write_packet,
6964 .write_trailer = mov_write_trailer,
6966 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6967 .codec_tag = (const AVCodecTag* const []){
6968 codec_mp4_tags, codec_ism_tags, 0 },
6969 .check_bitstream = mov_check_bitstream,
6970 .priv_class = &ismv_muxer_class,
6973 #if CONFIG_F4V_MUXER
6975 AVOutputFormat ff_f4v_muxer = {
6977 .long_name = NULL_IF_CONFIG_SMALL("F4V Adobe Flash Video"),
6978 .mime_type = "application/f4v",
6979 .extensions = "f4v",
6980 .priv_data_size = sizeof(MOVMuxContext),
6981 .audio_codec = AV_CODEC_ID_AAC,
6982 .video_codec = AV_CODEC_ID_H264,
6984 .write_header = mov_write_header,
6985 .write_packet = mov_write_packet,
6986 .write_trailer = mov_write_trailer,
6988 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH,
6989 .codec_tag = (const AVCodecTag* const []){ codec_f4v_tags, 0 },
6990 .check_bitstream = mov_check_bitstream,
6991 .priv_class = &f4v_muxer_class,