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"
34 #include "libavcodec/ac3_parser_internal.h"
35 #include "libavcodec/dnxhddata.h"
36 #include "libavcodec/flac.h"
37 #include "libavcodec/get_bits.h"
39 #include "libavcodec/internal.h"
40 #include "libavcodec/put_bits.h"
41 #include "libavcodec/vc1_common.h"
42 #include "libavcodec/raw.h"
44 #include "libavutil/avstring.h"
45 #include "libavutil/intfloat.h"
46 #include "libavutil/mathematics.h"
47 #include "libavutil/libm.h"
48 #include "libavutil/opt.h"
49 #include "libavutil/dict.h"
50 #include "libavutil/pixdesc.h"
51 #include "libavutil/stereo3d.h"
52 #include "libavutil/timecode.h"
53 #include "libavutil/color_utils.h"
59 static const AVOption options[] = {
60 { "movflags", "MOV muxer flags", offsetof(MOVMuxContext, flags), AV_OPT_TYPE_FLAGS, {.i64 = 0}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
61 { "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" },
62 { "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 },
63 { "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" },
64 { "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" },
65 { "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" },
66 { "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" },
67 { "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" },
68 { "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" },
69 { "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" },
70 { "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" },
71 { "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" },
72 { "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" },
73 { "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" },
74 { "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" },
75 { "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" },
76 { "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" },
77 { "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" },
78 { "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" },
79 { "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" },
80 { "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" },
81 { "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" },
82 FF_RTP_FLAG_OPTS(MOVMuxContext, rtp_flags),
83 { "skip_iods", "Skip writing iods atom.", offsetof(MOVMuxContext, iods_skip), AV_OPT_TYPE_BOOL, {.i64 = 1}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM},
84 { "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},
85 { "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},
86 { "frag_duration", "Maximum fragment duration", offsetof(MOVMuxContext, max_fragment_duration), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
87 { "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},
88 { "frag_size", "Maximum fragment size", offsetof(MOVMuxContext, max_fragment_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
89 { "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},
90 { "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},
91 { "brand", "Override major brand", offsetof(MOVMuxContext, major_brand), AV_OPT_TYPE_STRING, {.str = NULL}, .flags = AV_OPT_FLAG_ENCODING_PARAM },
92 { "use_editlist", "use edit list", offsetof(MOVMuxContext, use_editlist), AV_OPT_TYPE_BOOL, {.i64 = -1}, -1, 1, AV_OPT_FLAG_ENCODING_PARAM},
93 { "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},
94 { "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},
95 { "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 },
96 { "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 },
97 { "encryption_key", "The media encryption key (hex)", offsetof(MOVMuxContext, encryption_key), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_ENCODING_PARAM },
98 { "encryption_kid", "The media encryption key identifier (hex)", offsetof(MOVMuxContext, encryption_kid), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_ENCODING_PARAM },
99 { "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},
100 { "write_tmcd", "force or disable writing tmcd", offsetof(MOVMuxContext, write_tmcd), AV_OPT_TYPE_BOOL, {.i64 = -1}, -1, 1, AV_OPT_FLAG_ENCODING_PARAM},
101 { "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"},
102 { "wallclock", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = MOV_PRFT_SRC_WALLCLOCK}, 0, 0, AV_OPT_FLAG_ENCODING_PARAM, "prft"},
103 { "pts", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = MOV_PRFT_SRC_PTS}, 0, 0, AV_OPT_FLAG_ENCODING_PARAM, "prft"},
104 { "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},
108 #define MOV_CLASS(flavor)\
109 static const AVClass flavor ## _muxer_class = {\
110 .class_name = #flavor " muxer",\
111 .item_name = av_default_item_name,\
113 .version = LIBAVUTIL_VERSION_INT,\
116 static int get_moov_size(AVFormatContext *s);
118 static int utf8len(const uint8_t *b)
123 GET_UTF8(val, *b++, return -1;)
129 //FIXME support 64 bit variant with wide placeholders
130 static int64_t update_size(AVIOContext *pb, int64_t pos)
132 int64_t curpos = avio_tell(pb);
133 avio_seek(pb, pos, SEEK_SET);
134 avio_wb32(pb, curpos - pos); /* rewrite size */
135 avio_seek(pb, curpos, SEEK_SET);
140 static int co64_required(const MOVTrack *track)
142 if (track->entry > 0 && track->cluster[track->entry - 1].pos + track->data_offset > UINT32_MAX)
147 static int is_cover_image(const AVStream *st)
149 /* Eg. AV_DISPOSITION_ATTACHED_PIC | AV_DISPOSITION_TIMED_THUMBNAILS
150 * is encoded as sparse video track */
151 return st && st->disposition == AV_DISPOSITION_ATTACHED_PIC;
154 static int rtp_hinting_needed(const AVStream *st)
156 /* Add hint tracks for each real audio and video stream */
157 if (is_cover_image(st))
159 return st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ||
160 st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO;
163 /* Chunk offset atom */
164 static int mov_write_stco_tag(AVIOContext *pb, MOVTrack *track)
167 int mode64 = co64_required(track); // use 32 bit size variant if possible
168 int64_t pos = avio_tell(pb);
169 avio_wb32(pb, 0); /* size */
171 ffio_wfourcc(pb, "co64");
173 ffio_wfourcc(pb, "stco");
174 avio_wb32(pb, 0); /* version & flags */
175 avio_wb32(pb, track->chunkCount); /* entry count */
176 for (i = 0; i < track->entry; i++) {
177 if (!track->cluster[i].chunkNum)
180 avio_wb64(pb, track->cluster[i].pos + track->data_offset);
182 avio_wb32(pb, track->cluster[i].pos + track->data_offset);
184 return update_size(pb, pos);
187 /* Sample size atom */
188 static int mov_write_stsz_tag(AVIOContext *pb, MOVTrack *track)
191 int i, j, entries = 0, tst = -1, oldtst = -1;
193 int64_t pos = avio_tell(pb);
194 avio_wb32(pb, 0); /* size */
195 ffio_wfourcc(pb, "stsz");
196 avio_wb32(pb, 0); /* version & flags */
198 for (i = 0; i < track->entry; i++) {
199 tst = track->cluster[i].size / track->cluster[i].entries;
200 if (oldtst != -1 && tst != oldtst)
203 entries += track->cluster[i].entries;
205 if (equalChunks && track->entry) {
206 int sSize = track->entry ? track->cluster[0].size / track->cluster[0].entries : 0;
207 sSize = FFMAX(1, sSize); // adpcm mono case could make sSize == 0
208 avio_wb32(pb, sSize); // sample size
209 avio_wb32(pb, entries); // sample count
211 avio_wb32(pb, 0); // sample size
212 avio_wb32(pb, entries); // sample count
213 for (i = 0; i < track->entry; i++) {
214 for (j = 0; j < track->cluster[i].entries; j++) {
215 avio_wb32(pb, track->cluster[i].size /
216 track->cluster[i].entries);
220 return update_size(pb, pos);
223 /* Sample to chunk atom */
224 static int mov_write_stsc_tag(AVIOContext *pb, MOVTrack *track)
226 int index = 0, oldval = -1, i;
227 int64_t entryPos, curpos;
229 int64_t pos = avio_tell(pb);
230 avio_wb32(pb, 0); /* size */
231 ffio_wfourcc(pb, "stsc");
232 avio_wb32(pb, 0); // version & flags
233 entryPos = avio_tell(pb);
234 avio_wb32(pb, track->chunkCount); // entry count
235 for (i = 0; i < track->entry; i++) {
236 if (oldval != track->cluster[i].samples_in_chunk && track->cluster[i].chunkNum) {
237 avio_wb32(pb, track->cluster[i].chunkNum); // first chunk
238 avio_wb32(pb, track->cluster[i].samples_in_chunk); // samples per chunk
239 avio_wb32(pb, 0x1); // sample description index
240 oldval = track->cluster[i].samples_in_chunk;
244 curpos = avio_tell(pb);
245 avio_seek(pb, entryPos, SEEK_SET);
246 avio_wb32(pb, index); // rewrite size
247 avio_seek(pb, curpos, SEEK_SET);
249 return update_size(pb, pos);
252 /* Sync sample atom */
253 static int mov_write_stss_tag(AVIOContext *pb, MOVTrack *track, uint32_t flag)
255 int64_t curpos, entryPos;
257 int64_t pos = avio_tell(pb);
258 avio_wb32(pb, 0); // size
259 ffio_wfourcc(pb, flag == MOV_SYNC_SAMPLE ? "stss" : "stps");
260 avio_wb32(pb, 0); // version & flags
261 entryPos = avio_tell(pb);
262 avio_wb32(pb, track->entry); // entry count
263 for (i = 0; i < track->entry; i++) {
264 if (track->cluster[i].flags & flag) {
265 avio_wb32(pb, i + 1);
269 curpos = avio_tell(pb);
270 avio_seek(pb, entryPos, SEEK_SET);
271 avio_wb32(pb, index); // rewrite size
272 avio_seek(pb, curpos, SEEK_SET);
273 return update_size(pb, pos);
276 /* Sample dependency atom */
277 static int mov_write_sdtp_tag(AVIOContext *pb, MOVTrack *track)
280 uint8_t leading, dependent, reference, redundancy;
281 int64_t pos = avio_tell(pb);
282 avio_wb32(pb, 0); // size
283 ffio_wfourcc(pb, "sdtp");
284 avio_wb32(pb, 0); // version & flags
285 for (i = 0; i < track->entry; i++) {
286 dependent = MOV_SAMPLE_DEPENDENCY_YES;
287 leading = reference = redundancy = MOV_SAMPLE_DEPENDENCY_UNKNOWN;
288 if (track->cluster[i].flags & MOV_DISPOSABLE_SAMPLE) {
289 reference = MOV_SAMPLE_DEPENDENCY_NO;
291 if (track->cluster[i].flags & MOV_SYNC_SAMPLE) {
292 dependent = MOV_SAMPLE_DEPENDENCY_NO;
294 avio_w8(pb, (leading << 6) | (dependent << 4) |
295 (reference << 2) | redundancy);
297 return update_size(pb, pos);
300 static int mov_write_amr_tag(AVIOContext *pb, MOVTrack *track)
302 avio_wb32(pb, 0x11); /* size */
303 if (track->mode == MODE_MOV) ffio_wfourcc(pb, "samr");
304 else ffio_wfourcc(pb, "damr");
305 ffio_wfourcc(pb, "FFMP");
306 avio_w8(pb, 0); /* decoder version */
308 avio_wb16(pb, 0x81FF); /* Mode set (all modes for AMR_NB) */
309 avio_w8(pb, 0x00); /* Mode change period (no restriction) */
310 avio_w8(pb, 0x01); /* Frames per sample */
314 static int mov_write_ac3_tag(AVIOContext *pb, MOVTrack *track)
319 int fscod, bsid, bsmod, acmod, lfeon, frmsizecod;
321 if (track->vos_len < 7)
325 ffio_wfourcc(pb, "dac3");
327 init_get_bits(&gbc, track->vos_data + 4, (track->vos_len - 4) * 8);
328 fscod = get_bits(&gbc, 2);
329 frmsizecod = get_bits(&gbc, 6);
330 bsid = get_bits(&gbc, 5);
331 bsmod = get_bits(&gbc, 3);
332 acmod = get_bits(&gbc, 3);
334 skip_bits(&gbc, 2); // dsurmod
336 if ((acmod & 1) && acmod != 1)
337 skip_bits(&gbc, 2); // cmixlev
339 skip_bits(&gbc, 2); // surmixlev
341 lfeon = get_bits1(&gbc);
343 init_put_bits(&pbc, buf, sizeof(buf));
344 put_bits(&pbc, 2, fscod);
345 put_bits(&pbc, 5, bsid);
346 put_bits(&pbc, 3, bsmod);
347 put_bits(&pbc, 3, acmod);
348 put_bits(&pbc, 1, lfeon);
349 put_bits(&pbc, 5, frmsizecod >> 1); // bit_rate_code
350 put_bits(&pbc, 5, 0); // reserved
352 flush_put_bits(&pbc);
353 avio_write(pb, buf, sizeof(buf));
363 /* Layout of the EC3SpecificBox */
364 /* maximum bitrate */
366 /* number of independent substreams */
369 /* sample rate code (see ff_ac3_sample_rate_tab) 2 bits */
371 /* bit stream identification 5 bits */
373 /* one bit reserved */
374 /* audio service mixing (not supported yet) 1 bit */
375 /* bit stream mode 3 bits */
377 /* audio coding mode 3 bits */
379 /* sub woofer on 1 bit */
381 /* 3 bits reserved */
382 /* number of dependent substreams associated with this substream 4 bits */
384 /* channel locations of the dependent substream(s), if any, 9 bits */
386 /* if there is no dependent substream, then one bit reserved instead */
387 } substream[1]; /* TODO: support 8 independent substreams */
390 #if CONFIG_AC3_PARSER
391 static int handle_eac3(MOVMuxContext *mov, AVPacket *pkt, MOVTrack *track)
393 AC3HeaderInfo *hdr = NULL;
394 struct eac3_info *info;
397 if (!track->eac3_priv && !(track->eac3_priv = av_mallocz(sizeof(*info))))
398 return AVERROR(ENOMEM);
399 info = track->eac3_priv;
401 if (avpriv_ac3_parse_header(&hdr, pkt->data, pkt->size) < 0) {
402 /* drop the packets until we see a good one */
404 av_log(mov, AV_LOG_WARNING, "Dropping invalid packet from start of the stream\n");
407 ret = AVERROR_INVALIDDATA;
411 info->data_rate = FFMAX(info->data_rate, hdr->bit_rate / 1000);
412 num_blocks = hdr->num_blocks;
414 if (!info->ec3_done) {
415 /* AC-3 substream must be the first one */
416 if (hdr->bitstream_id <= 10 && hdr->substreamid != 0) {
417 ret = AVERROR(EINVAL);
421 /* this should always be the case, given that our AC-3 parser
422 * concatenates dependent frames to their independent parent */
423 if (hdr->frame_type == EAC3_FRAME_TYPE_INDEPENDENT) {
424 /* substream ids must be incremental */
425 if (hdr->substreamid > info->num_ind_sub + 1) {
426 ret = AVERROR(EINVAL);
430 if (hdr->substreamid == info->num_ind_sub + 1) {
431 //info->num_ind_sub++;
432 avpriv_request_sample(track->par, "Multiple independent substreams");
433 ret = AVERROR_PATCHWELCOME;
435 } else if (hdr->substreamid < info->num_ind_sub ||
436 hdr->substreamid == 0 && info->substream[0].bsid) {
442 /* fill the info needed for the "dec3" atom */
443 info->substream[hdr->substreamid].fscod = hdr->sr_code;
444 info->substream[hdr->substreamid].bsid = hdr->bitstream_id;
445 info->substream[hdr->substreamid].bsmod = hdr->bitstream_mode;
446 info->substream[hdr->substreamid].acmod = hdr->channel_mode;
447 info->substream[hdr->substreamid].lfeon = hdr->lfe_on;
449 /* Parse dependent substream(s), if any */
450 if (pkt->size != hdr->frame_size) {
451 int cumul_size = hdr->frame_size;
452 int parent = hdr->substreamid;
454 while (cumul_size != pkt->size) {
457 ret = avpriv_ac3_parse_header(&hdr, pkt->data + cumul_size, pkt->size - cumul_size);
460 if (hdr->frame_type != EAC3_FRAME_TYPE_DEPENDENT) {
461 ret = AVERROR(EINVAL);
464 info->substream[parent].num_dep_sub++;
467 /* header is parsed up to lfeon, but custom channel map may be needed */
468 init_get_bits8(&gbc, pkt->data + cumul_size + ret, pkt->size - cumul_size - ret);
471 /* skip volume control params */
472 for (i = 0; i < (hdr->channel_mode ? 1 : 2); i++) {
473 skip_bits(&gbc, 5); // skip dialog normalization
474 if (get_bits1(&gbc)) {
475 skip_bits(&gbc, 8); // skip compression gain word
478 /* get the dependent stream channel map, if exists */
480 info->substream[parent].chan_loc |= (get_bits(&gbc, 16) >> 5) & 0x1f;
482 info->substream[parent].chan_loc |= hdr->channel_mode;
483 cumul_size += hdr->frame_size;
489 if (!info->num_blocks && num_blocks == 6) {
493 else if (info->num_blocks + num_blocks > 6) {
494 ret = AVERROR_INVALIDDATA;
498 if (!info->num_blocks) {
499 ret = av_packet_ref(&info->pkt, pkt);
501 info->num_blocks = num_blocks;
504 if ((ret = av_grow_packet(&info->pkt, pkt->size)) < 0)
506 memcpy(info->pkt.data + info->pkt.size - pkt->size, pkt->data, pkt->size);
507 info->num_blocks += num_blocks;
508 info->pkt.duration += pkt->duration;
509 if ((ret = av_copy_packet_side_data(&info->pkt, pkt)) < 0)
511 if (info->num_blocks != 6)
513 av_packet_unref(pkt);
514 av_packet_move_ref(pkt, &info->pkt);
515 info->num_blocks = 0;
526 static int mov_write_eac3_tag(AVIOContext *pb, MOVTrack *track)
530 struct eac3_info *info;
533 if (!track->eac3_priv)
534 return AVERROR(EINVAL);
536 info = track->eac3_priv;
537 size = 2 + 4 * (info->num_ind_sub + 1);
538 buf = av_malloc(size);
540 size = AVERROR(ENOMEM);
544 init_put_bits(&pbc, buf, size);
545 put_bits(&pbc, 13, info->data_rate);
546 put_bits(&pbc, 3, info->num_ind_sub);
547 for (i = 0; i <= info->num_ind_sub; i++) {
548 put_bits(&pbc, 2, info->substream[i].fscod);
549 put_bits(&pbc, 5, info->substream[i].bsid);
550 put_bits(&pbc, 1, 0); /* reserved */
551 put_bits(&pbc, 1, 0); /* asvc */
552 put_bits(&pbc, 3, info->substream[i].bsmod);
553 put_bits(&pbc, 3, info->substream[i].acmod);
554 put_bits(&pbc, 1, info->substream[i].lfeon);
555 put_bits(&pbc, 5, 0); /* reserved */
556 put_bits(&pbc, 4, info->substream[i].num_dep_sub);
557 if (!info->substream[i].num_dep_sub) {
558 put_bits(&pbc, 1, 0); /* reserved */
561 put_bits(&pbc, 9, info->substream[i].chan_loc);
564 flush_put_bits(&pbc);
566 avio_wb32(pb, size + 8);
567 ffio_wfourcc(pb, "dec3");
568 avio_write(pb, buf, size);
573 av_packet_unref(&info->pkt);
574 av_freep(&track->eac3_priv);
580 * This function writes extradata "as is".
581 * Extradata must be formatted like a valid atom (with size and tag).
583 static int mov_write_extradata_tag(AVIOContext *pb, MOVTrack *track)
585 avio_write(pb, track->par->extradata, track->par->extradata_size);
586 return track->par->extradata_size;
589 static int mov_write_enda_tag(AVIOContext *pb)
592 ffio_wfourcc(pb, "enda");
593 avio_wb16(pb, 1); /* little endian */
597 static int mov_write_enda_tag_be(AVIOContext *pb)
600 ffio_wfourcc(pb, "enda");
601 avio_wb16(pb, 0); /* big endian */
605 static void put_descr(AVIOContext *pb, int tag, unsigned int size)
610 avio_w8(pb, (size >> (7 * i)) | 0x80);
611 avio_w8(pb, size & 0x7F);
614 static unsigned compute_avg_bitrate(MOVTrack *track)
618 if (!track->track_duration)
620 for (i = 0; i < track->entry; i++)
621 size += track->cluster[i].size;
622 return size * 8 * track->timescale / track->track_duration;
625 static int mov_write_esds_tag(AVIOContext *pb, MOVTrack *track) // Basic
627 AVCPBProperties *props;
628 int64_t pos = avio_tell(pb);
629 int decoder_specific_info_len = track->vos_len ? 5 + track->vos_len : 0;
630 unsigned avg_bitrate;
632 avio_wb32(pb, 0); // size
633 ffio_wfourcc(pb, "esds");
634 avio_wb32(pb, 0); // Version
637 put_descr(pb, 0x03, 3 + 5+13 + decoder_specific_info_len + 5+1);
638 avio_wb16(pb, track->track_id);
639 avio_w8(pb, 0x00); // flags (= no flags)
641 // DecoderConfig descriptor
642 put_descr(pb, 0x04, 13 + decoder_specific_info_len);
644 // Object type indication
645 if ((track->par->codec_id == AV_CODEC_ID_MP2 ||
646 track->par->codec_id == AV_CODEC_ID_MP3) &&
647 track->par->sample_rate > 24000)
648 avio_w8(pb, 0x6B); // 11172-3
650 avio_w8(pb, ff_codec_get_tag(ff_mp4_obj_type, track->par->codec_id));
652 // the following fields is made of 6 bits to identify the streamtype (4 for video, 5 for audio)
653 // plus 1 bit to indicate upstream and 1 bit set to 1 (reserved)
654 if (track->par->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
655 avio_w8(pb, (0x38 << 2) | 1); // flags (= NeroSubpicStream)
656 else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
657 avio_w8(pb, 0x15); // flags (= Audiostream)
659 avio_w8(pb, 0x11); // flags (= Visualstream)
661 props = (AVCPBProperties*)av_stream_get_side_data(track->st, AV_PKT_DATA_CPB_PROPERTIES,
664 avio_wb24(pb, props ? props->buffer_size / 8 : 0); // Buffersize DB
666 avg_bitrate = compute_avg_bitrate(track);
667 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)
668 avio_wb32(pb, avg_bitrate);
670 if (track->vos_len) {
671 // DecoderSpecific info descriptor
672 put_descr(pb, 0x05, track->vos_len);
673 avio_write(pb, track->vos_data, track->vos_len);
677 put_descr(pb, 0x06, 1);
679 return update_size(pb, pos);
682 static int mov_pcm_le_gt16(enum AVCodecID codec_id)
684 return codec_id == AV_CODEC_ID_PCM_S24LE ||
685 codec_id == AV_CODEC_ID_PCM_S32LE ||
686 codec_id == AV_CODEC_ID_PCM_F32LE ||
687 codec_id == AV_CODEC_ID_PCM_F64LE;
690 static int mov_pcm_be_gt16(enum AVCodecID codec_id)
692 return codec_id == AV_CODEC_ID_PCM_S24BE ||
693 codec_id == AV_CODEC_ID_PCM_S32BE ||
694 codec_id == AV_CODEC_ID_PCM_F32BE ||
695 codec_id == AV_CODEC_ID_PCM_F64BE;
698 static int mov_write_ms_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
701 int64_t pos = avio_tell(pb);
703 avio_wl32(pb, track->tag); // store it byteswapped
704 track->par->codec_tag = av_bswap16(track->tag >> 16);
705 if ((ret = ff_put_wav_header(s, pb, track->par, 0)) < 0)
707 return update_size(pb, pos);
710 static int mov_write_wfex_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
713 int64_t pos = avio_tell(pb);
715 ffio_wfourcc(pb, "wfex");
716 if ((ret = ff_put_wav_header(s, pb, track->st->codecpar, FF_PUT_WAV_HEADER_FORCE_WAVEFORMATEX)) < 0)
718 return update_size(pb, pos);
721 static int mov_write_dfla_tag(AVIOContext *pb, MOVTrack *track)
723 int64_t pos = avio_tell(pb);
725 ffio_wfourcc(pb, "dfLa");
726 avio_w8(pb, 0); /* version */
727 avio_wb24(pb, 0); /* flags */
729 /* Expect the encoder to pass a METADATA_BLOCK_TYPE_STREAMINFO. */
730 if (track->par->extradata_size != FLAC_STREAMINFO_SIZE)
731 return AVERROR_INVALIDDATA;
733 /* TODO: Write other METADATA_BLOCK_TYPEs if the encoder makes them available. */
734 avio_w8(pb, 1 << 7 | FLAC_METADATA_TYPE_STREAMINFO); /* LastMetadataBlockFlag << 7 | BlockType */
735 avio_wb24(pb, track->par->extradata_size); /* Length */
736 avio_write(pb, track->par->extradata, track->par->extradata_size); /* BlockData[Length] */
738 return update_size(pb, pos);
741 static int mov_write_dops_tag(AVIOContext *pb, MOVTrack *track)
743 int64_t pos = avio_tell(pb);
745 ffio_wfourcc(pb, "dOps");
746 avio_w8(pb, 0); /* Version */
747 if (track->par->extradata_size < 19) {
748 av_log(pb, AV_LOG_ERROR, "invalid extradata size\n");
749 return AVERROR_INVALIDDATA;
751 /* extradata contains an Ogg OpusHead, other than byte-ordering and
752 OpusHead's preceeding magic/version, OpusSpecificBox is currently
754 avio_w8(pb, AV_RB8(track->par->extradata + 9)); /* OuputChannelCount */
755 avio_wb16(pb, AV_RL16(track->par->extradata + 10)); /* PreSkip */
756 avio_wb32(pb, AV_RL32(track->par->extradata + 12)); /* InputSampleRate */
757 avio_wb16(pb, AV_RL16(track->par->extradata + 16)); /* OutputGain */
758 /* Write the rest of the header out without byte-swapping. */
759 avio_write(pb, track->par->extradata + 18, track->par->extradata_size - 18);
761 return update_size(pb, pos);
764 static int mov_write_chan_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
766 uint32_t layout_tag, bitmap;
767 int64_t pos = avio_tell(pb);
769 layout_tag = ff_mov_get_channel_layout_tag(track->par->codec_id,
770 track->par->channel_layout,
773 av_log(s, AV_LOG_WARNING, "not writing 'chan' tag due to "
774 "lack of channel information\n");
778 if (track->multichannel_as_mono)
781 avio_wb32(pb, 0); // Size
782 ffio_wfourcc(pb, "chan"); // Type
783 avio_w8(pb, 0); // Version
784 avio_wb24(pb, 0); // Flags
785 avio_wb32(pb, layout_tag); // mChannelLayoutTag
786 avio_wb32(pb, bitmap); // mChannelBitmap
787 avio_wb32(pb, 0); // mNumberChannelDescriptions
789 return update_size(pb, pos);
792 static int mov_write_wave_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
794 int64_t pos = avio_tell(pb);
796 avio_wb32(pb, 0); /* size */
797 ffio_wfourcc(pb, "wave");
799 if (track->par->codec_id != AV_CODEC_ID_QDM2) {
800 avio_wb32(pb, 12); /* size */
801 ffio_wfourcc(pb, "frma");
802 avio_wl32(pb, track->tag);
805 if (track->par->codec_id == AV_CODEC_ID_AAC) {
806 /* useless atom needed by mplayer, ipod, not needed by quicktime */
807 avio_wb32(pb, 12); /* size */
808 ffio_wfourcc(pb, "mp4a");
810 mov_write_esds_tag(pb, track);
811 } else if (mov_pcm_le_gt16(track->par->codec_id)) {
812 mov_write_enda_tag(pb);
813 } else if (mov_pcm_be_gt16(track->par->codec_id)) {
814 mov_write_enda_tag_be(pb);
815 } else if (track->par->codec_id == AV_CODEC_ID_AMR_NB) {
816 mov_write_amr_tag(pb, track);
817 } else if (track->par->codec_id == AV_CODEC_ID_AC3) {
818 mov_write_ac3_tag(pb, track);
819 } else if (track->par->codec_id == AV_CODEC_ID_EAC3) {
820 mov_write_eac3_tag(pb, track);
821 } else if (track->par->codec_id == AV_CODEC_ID_ALAC ||
822 track->par->codec_id == AV_CODEC_ID_QDM2) {
823 mov_write_extradata_tag(pb, track);
824 } else if (track->par->codec_id == AV_CODEC_ID_ADPCM_MS ||
825 track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) {
826 mov_write_ms_tag(s, pb, track);
829 avio_wb32(pb, 8); /* size */
830 avio_wb32(pb, 0); /* null tag */
832 return update_size(pb, pos);
835 static int mov_write_dvc1_structs(MOVTrack *track, uint8_t *buf)
838 const uint8_t *start, *next, *end = track->vos_data + track->vos_len;
839 int unescaped_size, seq_found = 0;
840 int level = 0, interlace = 0;
841 int packet_seq = track->vc1_info.packet_seq;
842 int packet_entry = track->vc1_info.packet_entry;
843 int slices = track->vc1_info.slices;
846 if (track->start_dts == AV_NOPTS_VALUE) {
847 /* No packets written yet, vc1_info isn't authoritative yet. */
848 /* Assume inline sequence and entry headers. */
849 packet_seq = packet_entry = 1;
850 av_log(NULL, AV_LOG_WARNING,
851 "moov atom written before any packets, unable to write correct "
852 "dvc1 atom. Set the delay_moov flag to fix this.\n");
855 unescaped = av_mallocz(track->vos_len + AV_INPUT_BUFFER_PADDING_SIZE);
857 return AVERROR(ENOMEM);
858 start = find_next_marker(track->vos_data, end);
859 for (next = start; next < end; start = next) {
862 next = find_next_marker(start + 4, end);
863 size = next - start - 4;
866 unescaped_size = vc1_unescape_buffer(start + 4, size, unescaped);
867 init_get_bits(&gb, unescaped, 8 * unescaped_size);
868 if (AV_RB32(start) == VC1_CODE_SEQHDR) {
869 int profile = get_bits(&gb, 2);
870 if (profile != PROFILE_ADVANCED) {
872 return AVERROR(ENOSYS);
875 level = get_bits(&gb, 3);
876 /* chromaformat, frmrtq_postproc, bitrtq_postproc, postprocflag,
878 skip_bits_long(&gb, 2 + 3 + 5 + 1 + 2*12);
879 skip_bits(&gb, 1); /* broadcast */
880 interlace = get_bits1(&gb);
881 skip_bits(&gb, 4); /* tfcntrflag, finterpflag, reserved, psf */
886 return AVERROR(ENOSYS);
889 init_put_bits(&pbc, buf, 7);
890 /* VC1DecSpecStruc */
891 put_bits(&pbc, 4, 12); /* profile - advanced */
892 put_bits(&pbc, 3, level);
893 put_bits(&pbc, 1, 0); /* reserved */
894 /* VC1AdvDecSpecStruc */
895 put_bits(&pbc, 3, level);
896 put_bits(&pbc, 1, 0); /* cbr */
897 put_bits(&pbc, 6, 0); /* reserved */
898 put_bits(&pbc, 1, !interlace); /* no interlace */
899 put_bits(&pbc, 1, !packet_seq); /* no multiple seq */
900 put_bits(&pbc, 1, !packet_entry); /* no multiple entry */
901 put_bits(&pbc, 1, !slices); /* no slice code */
902 put_bits(&pbc, 1, 0); /* no bframe */
903 put_bits(&pbc, 1, 0); /* reserved */
906 if (track->st->avg_frame_rate.num > 0 && track->st->avg_frame_rate.den > 0)
907 put_bits32(&pbc, track->st->avg_frame_rate.num / track->st->avg_frame_rate.den);
909 put_bits32(&pbc, 0xffffffff);
911 flush_put_bits(&pbc);
918 static int mov_write_dvc1_tag(AVIOContext *pb, MOVTrack *track)
920 uint8_t buf[7] = { 0 };
923 if ((ret = mov_write_dvc1_structs(track, buf)) < 0)
926 avio_wb32(pb, track->vos_len + 8 + sizeof(buf));
927 ffio_wfourcc(pb, "dvc1");
928 avio_write(pb, buf, sizeof(buf));
929 avio_write(pb, track->vos_data, track->vos_len);
934 static int mov_write_glbl_tag(AVIOContext *pb, MOVTrack *track)
936 avio_wb32(pb, track->vos_len + 8);
937 ffio_wfourcc(pb, "glbl");
938 avio_write(pb, track->vos_data, track->vos_len);
939 return 8 + track->vos_len;
943 * Compute flags for 'lpcm' tag.
944 * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
946 static int mov_get_lpcm_flags(enum AVCodecID codec_id)
949 case AV_CODEC_ID_PCM_F32BE:
950 case AV_CODEC_ID_PCM_F64BE:
952 case AV_CODEC_ID_PCM_F32LE:
953 case AV_CODEC_ID_PCM_F64LE:
955 case AV_CODEC_ID_PCM_U8:
957 case AV_CODEC_ID_PCM_S16BE:
958 case AV_CODEC_ID_PCM_S24BE:
959 case AV_CODEC_ID_PCM_S32BE:
961 case AV_CODEC_ID_PCM_S8:
962 case AV_CODEC_ID_PCM_S16LE:
963 case AV_CODEC_ID_PCM_S24LE:
964 case AV_CODEC_ID_PCM_S32LE:
971 static int get_cluster_duration(MOVTrack *track, int cluster_idx)
975 if (cluster_idx >= track->entry)
978 if (cluster_idx + 1 == track->entry)
979 next_dts = track->track_duration + track->start_dts;
981 next_dts = track->cluster[cluster_idx + 1].dts;
983 next_dts -= track->cluster[cluster_idx].dts;
985 av_assert0(next_dts >= 0);
986 av_assert0(next_dts <= INT_MAX);
991 static int get_samples_per_packet(MOVTrack *track)
993 int i, first_duration;
995 // return track->par->frame_size;
997 /* use 1 for raw PCM */
998 if (!track->audio_vbr)
1001 /* check to see if duration is constant for all clusters */
1004 first_duration = get_cluster_duration(track, 0);
1005 for (i = 1; i < track->entry; i++) {
1006 if (get_cluster_duration(track, i) != first_duration)
1009 return first_duration;
1012 static int mov_write_audio_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
1014 int64_t pos = avio_tell(pb);
1016 uint32_t tag = track->tag;
1018 if (track->mode == MODE_MOV) {
1019 if (track->timescale > UINT16_MAX) {
1020 if (mov_get_lpcm_flags(track->par->codec_id))
1021 tag = AV_RL32("lpcm");
1023 } else if (track->audio_vbr || mov_pcm_le_gt16(track->par->codec_id) ||
1024 mov_pcm_be_gt16(track->par->codec_id) ||
1025 track->par->codec_id == AV_CODEC_ID_ADPCM_MS ||
1026 track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
1027 track->par->codec_id == AV_CODEC_ID_QDM2) {
1032 avio_wb32(pb, 0); /* size */
1033 if (mov->encryption_scheme != MOV_ENC_NONE) {
1034 ffio_wfourcc(pb, "enca");
1036 avio_wl32(pb, tag); // store it byteswapped
1038 avio_wb32(pb, 0); /* Reserved */
1039 avio_wb16(pb, 0); /* Reserved */
1040 avio_wb16(pb, 1); /* Data-reference index, XXX == 1 */
1042 /* SoundDescription */
1043 avio_wb16(pb, version); /* Version */
1044 avio_wb16(pb, 0); /* Revision level */
1045 avio_wb32(pb, 0); /* Reserved */
1050 avio_wb16(pb, 0xfffe);
1052 avio_wb32(pb, 0x00010000);
1054 avio_wb64(pb, av_double2int(track->par->sample_rate));
1055 avio_wb32(pb, track->par->channels);
1056 avio_wb32(pb, 0x7F000000);
1057 avio_wb32(pb, av_get_bits_per_sample(track->par->codec_id));
1058 avio_wb32(pb, mov_get_lpcm_flags(track->par->codec_id));
1059 avio_wb32(pb, track->sample_size);
1060 avio_wb32(pb, get_samples_per_packet(track));
1062 if (track->mode == MODE_MOV) {
1063 avio_wb16(pb, track->par->channels);
1064 if (track->par->codec_id == AV_CODEC_ID_PCM_U8 ||
1065 track->par->codec_id == AV_CODEC_ID_PCM_S8)
1066 avio_wb16(pb, 8); /* bits per sample */
1067 else if (track->par->codec_id == AV_CODEC_ID_ADPCM_G726)
1068 avio_wb16(pb, track->par->bits_per_coded_sample);
1071 avio_wb16(pb, track->audio_vbr ? -2 : 0); /* compression ID */
1072 } else { /* reserved for mp4/3gp */
1073 if (track->par->codec_id == AV_CODEC_ID_FLAC ||
1074 track->par->codec_id == AV_CODEC_ID_OPUS) {
1075 avio_wb16(pb, track->par->channels);
1079 if (track->par->codec_id == AV_CODEC_ID_FLAC) {
1080 avio_wb16(pb, track->par->bits_per_raw_sample);
1087 avio_wb16(pb, 0); /* packet size (= 0) */
1088 if (track->par->codec_id == AV_CODEC_ID_OPUS)
1089 avio_wb16(pb, 48000);
1091 avio_wb16(pb, track->par->sample_rate <= UINT16_MAX ?
1092 track->par->sample_rate : 0);
1093 avio_wb16(pb, 0); /* Reserved */
1096 if (version == 1) { /* SoundDescription V1 extended info */
1097 if (mov_pcm_le_gt16(track->par->codec_id) ||
1098 mov_pcm_be_gt16(track->par->codec_id))
1099 avio_wb32(pb, 1); /* must be 1 for uncompressed formats */
1101 avio_wb32(pb, track->par->frame_size); /* Samples per packet */
1102 avio_wb32(pb, track->sample_size / track->par->channels); /* Bytes per packet */
1103 avio_wb32(pb, track->sample_size); /* Bytes per frame */
1104 avio_wb32(pb, 2); /* Bytes per sample */
1107 if (track->mode == MODE_MOV &&
1108 (track->par->codec_id == AV_CODEC_ID_AAC ||
1109 track->par->codec_id == AV_CODEC_ID_AC3 ||
1110 track->par->codec_id == AV_CODEC_ID_EAC3 ||
1111 track->par->codec_id == AV_CODEC_ID_AMR_NB ||
1112 track->par->codec_id == AV_CODEC_ID_ALAC ||
1113 track->par->codec_id == AV_CODEC_ID_ADPCM_MS ||
1114 track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
1115 track->par->codec_id == AV_CODEC_ID_QDM2 ||
1116 (mov_pcm_le_gt16(track->par->codec_id) && version==1) ||
1117 (mov_pcm_be_gt16(track->par->codec_id) && version==1)))
1118 mov_write_wave_tag(s, pb, track);
1119 else if (track->tag == MKTAG('m','p','4','a'))
1120 mov_write_esds_tag(pb, track);
1121 else if (track->par->codec_id == AV_CODEC_ID_AMR_NB)
1122 mov_write_amr_tag(pb, track);
1123 else if (track->par->codec_id == AV_CODEC_ID_AC3)
1124 mov_write_ac3_tag(pb, track);
1125 else if (track->par->codec_id == AV_CODEC_ID_EAC3)
1126 mov_write_eac3_tag(pb, track);
1127 else if (track->par->codec_id == AV_CODEC_ID_ALAC)
1128 mov_write_extradata_tag(pb, track);
1129 else if (track->par->codec_id == AV_CODEC_ID_WMAPRO)
1130 mov_write_wfex_tag(s, pb, track);
1131 else if (track->par->codec_id == AV_CODEC_ID_FLAC)
1132 mov_write_dfla_tag(pb, track);
1133 else if (track->par->codec_id == AV_CODEC_ID_OPUS)
1134 mov_write_dops_tag(pb, track);
1135 else if (track->vos_len > 0)
1136 mov_write_glbl_tag(pb, track);
1138 if (track->mode == MODE_MOV && track->par->codec_type == AVMEDIA_TYPE_AUDIO)
1139 mov_write_chan_tag(s, pb, track);
1141 if (mov->encryption_scheme != MOV_ENC_NONE) {
1142 ff_mov_cenc_write_sinf_tag(track, pb, mov->encryption_kid);
1145 return update_size(pb, pos);
1148 static int mov_write_d263_tag(AVIOContext *pb)
1150 avio_wb32(pb, 0xf); /* size */
1151 ffio_wfourcc(pb, "d263");
1152 ffio_wfourcc(pb, "FFMP");
1153 avio_w8(pb, 0); /* decoder version */
1154 /* FIXME use AVCodecContext level/profile, when encoder will set values */
1155 avio_w8(pb, 0xa); /* level */
1156 avio_w8(pb, 0); /* profile */
1160 static int mov_write_avcc_tag(AVIOContext *pb, MOVTrack *track)
1162 int64_t pos = avio_tell(pb);
1165 ffio_wfourcc(pb, "avcC");
1166 ff_isom_write_avcc(pb, track->vos_data, track->vos_len);
1167 return update_size(pb, pos);
1170 static int mov_write_vpcc_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
1172 int64_t pos = avio_tell(pb);
1175 ffio_wfourcc(pb, "vpcC");
1176 avio_w8(pb, 1); /* version */
1177 avio_wb24(pb, 0); /* flags */
1178 ff_isom_write_vpcc(s, pb, track->par);
1179 return update_size(pb, pos);
1182 static int mov_write_hvcc_tag(AVIOContext *pb, MOVTrack *track)
1184 int64_t pos = avio_tell(pb);
1187 ffio_wfourcc(pb, "hvcC");
1188 if (track->tag == MKTAG('h','v','c','1'))
1189 ff_isom_write_hvcc(pb, track->vos_data, track->vos_len, 1);
1191 ff_isom_write_hvcc(pb, track->vos_data, track->vos_len, 0);
1192 return update_size(pb, pos);
1195 /* also used by all avid codecs (dv, imx, meridien) and their variants */
1196 static int mov_write_avid_tag(AVIOContext *pb, MOVTrack *track)
1201 int display_width = track->par->width;
1203 if (track->vos_data && track->vos_len > 0x29) {
1204 if (ff_dnxhd_parse_header_prefix(track->vos_data) != 0) {
1205 /* looks like a DNxHD bit stream */
1206 interlaced = (track->vos_data[5] & 2);
1207 cid = AV_RB32(track->vos_data + 0x28);
1209 av_log(NULL, AV_LOG_WARNING, "Could not locate DNxHD bit stream in vos_data\n");
1213 av_log(NULL, AV_LOG_WARNING, "Could not locate DNxHD bit stream, vos_data too small\n");
1217 avio_wb32(pb, 24); /* size */
1218 ffio_wfourcc(pb, "ACLR");
1219 ffio_wfourcc(pb, "ACLR");
1220 ffio_wfourcc(pb, "0001");
1221 if (track->par->color_range == AVCOL_RANGE_MPEG || /* Legal range (16-235) */
1222 track->par->color_range == AVCOL_RANGE_UNSPECIFIED) {
1223 avio_wb32(pb, 1); /* Corresponds to 709 in official encoder */
1224 } else { /* Full range (0-255) */
1225 avio_wb32(pb, 2); /* Corresponds to RGB in official encoder */
1227 avio_wb32(pb, 0); /* unknown */
1229 if (track->tag == MKTAG('A','V','d','h')) {
1231 ffio_wfourcc(pb, "ADHR");
1232 ffio_wfourcc(pb, "0001");
1234 avio_wb32(pb, 0); /* unknown */
1235 avio_wb32(pb, 1); /* unknown */
1236 avio_wb32(pb, 0); /* unknown */
1237 avio_wb32(pb, 0); /* unknown */
1241 avio_wb32(pb, 24); /* size */
1242 ffio_wfourcc(pb, "APRG");
1243 ffio_wfourcc(pb, "APRG");
1244 ffio_wfourcc(pb, "0001");
1245 avio_wb32(pb, 1); /* unknown */
1246 avio_wb32(pb, 0); /* unknown */
1248 avio_wb32(pb, 120); /* size */
1249 ffio_wfourcc(pb, "ARES");
1250 ffio_wfourcc(pb, "ARES");
1251 ffio_wfourcc(pb, "0001");
1252 avio_wb32(pb, cid); /* dnxhd cid, some id ? */
1253 if ( track->par->sample_aspect_ratio.num > 0
1254 && track->par->sample_aspect_ratio.den > 0)
1255 display_width = display_width * track->par->sample_aspect_ratio.num / track->par->sample_aspect_ratio.den;
1256 avio_wb32(pb, display_width);
1257 /* values below are based on samples created with quicktime and avid codecs */
1259 avio_wb32(pb, track->par->height / 2);
1260 avio_wb32(pb, 2); /* unknown */
1261 avio_wb32(pb, 0); /* unknown */
1262 avio_wb32(pb, 4); /* unknown */
1264 avio_wb32(pb, track->par->height);
1265 avio_wb32(pb, 1); /* unknown */
1266 avio_wb32(pb, 0); /* unknown */
1267 if (track->par->height == 1080)
1268 avio_wb32(pb, 5); /* unknown */
1270 avio_wb32(pb, 6); /* unknown */
1273 for (i = 0; i < 10; i++)
1279 static int mov_write_dpxe_tag(AVIOContext *pb, MOVTrack *track)
1282 ffio_wfourcc(pb, "DpxE");
1283 if (track->par->extradata_size >= 12 &&
1284 !memcmp(&track->par->extradata[4], "DpxE", 4)) {
1285 avio_wb32(pb, track->par->extradata[11]);
1292 static int mov_get_dv_codec_tag(AVFormatContext *s, MOVTrack *track)
1296 if (track->par->width == 720) { /* SD */
1297 if (track->par->height == 480) { /* NTSC */
1298 if (track->par->format == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','n');
1299 else tag = MKTAG('d','v','c',' ');
1300 }else if (track->par->format == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','p');
1301 else if (track->par->format == AV_PIX_FMT_YUV420P) tag = MKTAG('d','v','c','p');
1302 else tag = MKTAG('d','v','p','p');
1303 } else if (track->par->height == 720) { /* HD 720 line */
1304 if (track->st->time_base.den == 50) tag = MKTAG('d','v','h','q');
1305 else tag = MKTAG('d','v','h','p');
1306 } else if (track->par->height == 1080) { /* HD 1080 line */
1307 if (track->st->time_base.den == 25) tag = MKTAG('d','v','h','5');
1308 else tag = MKTAG('d','v','h','6');
1310 av_log(s, AV_LOG_ERROR, "unsupported height for dv codec\n");
1317 static AVRational find_fps(AVFormatContext *s, AVStream *st)
1319 AVRational rate = st->avg_frame_rate;
1321 #if FF_API_LAVF_AVCTX
1322 FF_DISABLE_DEPRECATION_WARNINGS
1323 rate = av_inv_q(st->codec->time_base);
1324 if (av_timecode_check_frame_rate(rate) < 0) {
1325 av_log(s, AV_LOG_DEBUG, "timecode: tbc=%d/%d invalid, fallback on %d/%d\n",
1326 rate.num, rate.den, st->avg_frame_rate.num, st->avg_frame_rate.den);
1327 rate = st->avg_frame_rate;
1329 FF_ENABLE_DEPRECATION_WARNINGS
1335 static int defined_frame_rate(AVFormatContext *s, AVStream *st)
1337 AVRational rational_framerate = find_fps(s, st);
1339 if (rational_framerate.den != 0)
1340 rate = av_q2d(rational_framerate);
1344 static int mov_get_mpeg2_xdcam_codec_tag(AVFormatContext *s, MOVTrack *track)
1346 int tag = track->par->codec_tag;
1347 int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE;
1348 AVStream *st = track->st;
1349 int rate = defined_frame_rate(s, st);
1352 tag = MKTAG('m', '2', 'v', '1'); //fallback tag
1354 if (track->par->format == AV_PIX_FMT_YUV420P) {
1355 if (track->par->width == 1280 && track->par->height == 720) {
1357 if (rate == 24) tag = MKTAG('x','d','v','4');
1358 else if (rate == 25) tag = MKTAG('x','d','v','5');
1359 else if (rate == 30) tag = MKTAG('x','d','v','1');
1360 else if (rate == 50) tag = MKTAG('x','d','v','a');
1361 else if (rate == 60) tag = MKTAG('x','d','v','9');
1363 } else if (track->par->width == 1440 && track->par->height == 1080) {
1365 if (rate == 24) tag = MKTAG('x','d','v','6');
1366 else if (rate == 25) tag = MKTAG('x','d','v','7');
1367 else if (rate == 30) tag = MKTAG('x','d','v','8');
1369 if (rate == 25) tag = MKTAG('x','d','v','3');
1370 else if (rate == 30) tag = MKTAG('x','d','v','2');
1372 } else if (track->par->width == 1920 && track->par->height == 1080) {
1374 if (rate == 24) tag = MKTAG('x','d','v','d');
1375 else if (rate == 25) tag = MKTAG('x','d','v','e');
1376 else if (rate == 30) tag = MKTAG('x','d','v','f');
1378 if (rate == 25) tag = MKTAG('x','d','v','c');
1379 else if (rate == 30) tag = MKTAG('x','d','v','b');
1382 } else if (track->par->format == AV_PIX_FMT_YUV422P) {
1383 if (track->par->width == 1280 && track->par->height == 720) {
1385 if (rate == 24) tag = MKTAG('x','d','5','4');
1386 else if (rate == 25) tag = MKTAG('x','d','5','5');
1387 else if (rate == 30) tag = MKTAG('x','d','5','1');
1388 else if (rate == 50) tag = MKTAG('x','d','5','a');
1389 else if (rate == 60) tag = MKTAG('x','d','5','9');
1391 } else if (track->par->width == 1920 && track->par->height == 1080) {
1393 if (rate == 24) tag = MKTAG('x','d','5','d');
1394 else if (rate == 25) tag = MKTAG('x','d','5','e');
1395 else if (rate == 30) tag = MKTAG('x','d','5','f');
1397 if (rate == 25) tag = MKTAG('x','d','5','c');
1398 else if (rate == 30) tag = MKTAG('x','d','5','b');
1406 static int mov_get_h264_codec_tag(AVFormatContext *s, MOVTrack *track)
1408 int tag = track->par->codec_tag;
1409 int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE;
1410 AVStream *st = track->st;
1411 int rate = defined_frame_rate(s, st);
1414 tag = MKTAG('a', 'v', 'c', 'i'); //fallback tag
1416 if (track->par->format == AV_PIX_FMT_YUV420P10) {
1417 if (track->par->width == 960 && track->par->height == 720) {
1419 if (rate == 24) tag = MKTAG('a','i','5','p');
1420 else if (rate == 25) tag = MKTAG('a','i','5','q');
1421 else if (rate == 30) tag = MKTAG('a','i','5','p');
1422 else if (rate == 50) tag = MKTAG('a','i','5','q');
1423 else if (rate == 60) tag = MKTAG('a','i','5','p');
1425 } else if (track->par->width == 1440 && track->par->height == 1080) {
1427 if (rate == 24) tag = MKTAG('a','i','5','3');
1428 else if (rate == 25) tag = MKTAG('a','i','5','2');
1429 else if (rate == 30) tag = MKTAG('a','i','5','3');
1431 if (rate == 50) tag = MKTAG('a','i','5','5');
1432 else if (rate == 60) tag = MKTAG('a','i','5','6');
1435 } else if (track->par->format == AV_PIX_FMT_YUV422P10) {
1436 if (track->par->width == 1280 && track->par->height == 720) {
1438 if (rate == 24) tag = MKTAG('a','i','1','p');
1439 else if (rate == 25) tag = MKTAG('a','i','1','q');
1440 else if (rate == 30) tag = MKTAG('a','i','1','p');
1441 else if (rate == 50) tag = MKTAG('a','i','1','q');
1442 else if (rate == 60) tag = MKTAG('a','i','1','p');
1444 } else if (track->par->width == 1920 && track->par->height == 1080) {
1446 if (rate == 24) tag = MKTAG('a','i','1','3');
1447 else if (rate == 25) tag = MKTAG('a','i','1','2');
1448 else if (rate == 30) tag = MKTAG('a','i','1','3');
1450 if (rate == 25) tag = MKTAG('a','i','1','5');
1451 else if (rate == 50) tag = MKTAG('a','i','1','5');
1452 else if (rate == 60) tag = MKTAG('a','i','1','6');
1454 } else if ( track->par->width == 4096 && track->par->height == 2160
1455 || track->par->width == 3840 && track->par->height == 2160
1456 || track->par->width == 2048 && track->par->height == 1080) {
1457 tag = MKTAG('a','i','v','x');
1464 static const struct {
1465 enum AVPixelFormat pix_fmt;
1468 } mov_pix_fmt_tags[] = {
1469 { AV_PIX_FMT_YUYV422, MKTAG('y','u','v','2'), 0 },
1470 { AV_PIX_FMT_YUYV422, MKTAG('y','u','v','s'), 0 },
1471 { AV_PIX_FMT_UYVY422, MKTAG('2','v','u','y'), 0 },
1472 { AV_PIX_FMT_RGB555BE,MKTAG('r','a','w',' '), 16 },
1473 { AV_PIX_FMT_RGB555LE,MKTAG('L','5','5','5'), 16 },
1474 { AV_PIX_FMT_RGB565LE,MKTAG('L','5','6','5'), 16 },
1475 { AV_PIX_FMT_RGB565BE,MKTAG('B','5','6','5'), 16 },
1476 { AV_PIX_FMT_GRAY16BE,MKTAG('b','1','6','g'), 16 },
1477 { AV_PIX_FMT_RGB24, MKTAG('r','a','w',' '), 24 },
1478 { AV_PIX_FMT_BGR24, MKTAG('2','4','B','G'), 24 },
1479 { AV_PIX_FMT_ARGB, MKTAG('r','a','w',' '), 32 },
1480 { AV_PIX_FMT_BGRA, MKTAG('B','G','R','A'), 32 },
1481 { AV_PIX_FMT_RGBA, MKTAG('R','G','B','A'), 32 },
1482 { AV_PIX_FMT_ABGR, MKTAG('A','B','G','R'), 32 },
1483 { AV_PIX_FMT_RGB48BE, MKTAG('b','4','8','r'), 48 },
1486 static int mov_get_dnxhd_codec_tag(AVFormatContext *s, MOVTrack *track)
1488 int tag = MKTAG('A','V','d','n');
1489 if (track->par->profile != FF_PROFILE_UNKNOWN &&
1490 track->par->profile != FF_PROFILE_DNXHD)
1491 tag = MKTAG('A','V','d','h');
1495 static int mov_get_rawvideo_codec_tag(AVFormatContext *s, MOVTrack *track)
1497 int tag = track->par->codec_tag;
1499 enum AVPixelFormat pix_fmt;
1501 for (i = 0; i < FF_ARRAY_ELEMS(mov_pix_fmt_tags); i++) {
1502 if (track->par->format == mov_pix_fmt_tags[i].pix_fmt) {
1503 tag = mov_pix_fmt_tags[i].tag;
1504 track->par->bits_per_coded_sample = mov_pix_fmt_tags[i].bps;
1505 if (track->par->codec_tag == mov_pix_fmt_tags[i].tag)
1510 pix_fmt = avpriv_find_pix_fmt(avpriv_pix_fmt_bps_mov,
1511 track->par->bits_per_coded_sample);
1512 if (tag == MKTAG('r','a','w',' ') &&
1513 track->par->format != pix_fmt &&
1514 track->par->format != AV_PIX_FMT_GRAY8 &&
1515 track->par->format != AV_PIX_FMT_NONE)
1516 av_log(s, AV_LOG_ERROR, "%s rawvideo cannot be written to mov, output file will be unreadable\n",
1517 av_get_pix_fmt_name(track->par->format));
1521 static int mov_get_codec_tag(AVFormatContext *s, MOVTrack *track)
1523 int tag = track->par->codec_tag;
1525 if (!tag || (s->strict_std_compliance >= FF_COMPLIANCE_NORMAL &&
1526 (track->par->codec_id == AV_CODEC_ID_DVVIDEO ||
1527 track->par->codec_id == AV_CODEC_ID_RAWVIDEO ||
1528 track->par->codec_id == AV_CODEC_ID_H263 ||
1529 track->par->codec_id == AV_CODEC_ID_H264 ||
1530 track->par->codec_id == AV_CODEC_ID_DNXHD ||
1531 track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO ||
1532 av_get_bits_per_sample(track->par->codec_id)))) { // pcm audio
1533 if (track->par->codec_id == AV_CODEC_ID_DVVIDEO)
1534 tag = mov_get_dv_codec_tag(s, track);
1535 else if (track->par->codec_id == AV_CODEC_ID_RAWVIDEO)
1536 tag = mov_get_rawvideo_codec_tag(s, track);
1537 else if (track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO)
1538 tag = mov_get_mpeg2_xdcam_codec_tag(s, track);
1539 else if (track->par->codec_id == AV_CODEC_ID_H264)
1540 tag = mov_get_h264_codec_tag(s, track);
1541 else if (track->par->codec_id == AV_CODEC_ID_DNXHD)
1542 tag = mov_get_dnxhd_codec_tag(s, track);
1543 else if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
1544 tag = ff_codec_get_tag(ff_codec_movvideo_tags, track->par->codec_id);
1545 if (!tag) { // if no mac fcc found, try with Microsoft tags
1546 tag = ff_codec_get_tag(ff_codec_bmp_tags, track->par->codec_id);
1548 av_log(s, AV_LOG_WARNING, "Using MS style video codec tag, "
1549 "the file may be unplayable!\n");
1551 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
1552 tag = ff_codec_get_tag(ff_codec_movaudio_tags, track->par->codec_id);
1553 if (!tag) { // if no mac fcc found, try with Microsoft tags
1554 int ms_tag = ff_codec_get_tag(ff_codec_wav_tags, track->par->codec_id);
1556 tag = MKTAG('m', 's', ((ms_tag >> 8) & 0xff), (ms_tag & 0xff));
1557 av_log(s, AV_LOG_WARNING, "Using MS style audio codec tag, "
1558 "the file may be unplayable!\n");
1561 } else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)
1562 tag = ff_codec_get_tag(ff_codec_movsubtitle_tags, track->par->codec_id);
1568 static const AVCodecTag codec_cover_image_tags[] = {
1569 { AV_CODEC_ID_MJPEG, 0xD },
1570 { AV_CODEC_ID_PNG, 0xE },
1571 { AV_CODEC_ID_BMP, 0x1B },
1572 { AV_CODEC_ID_NONE, 0 },
1575 static int mov_find_codec_tag(AVFormatContext *s, MOVTrack *track)
1579 if (is_cover_image(track->st))
1580 return ff_codec_get_tag(codec_cover_image_tags, track->par->codec_id);
1582 if (track->mode == MODE_MP4 || track->mode == MODE_PSP)
1583 tag = track->par->codec_tag;
1584 else if (track->mode == MODE_ISM)
1585 tag = track->par->codec_tag;
1586 else if (track->mode == MODE_IPOD) {
1587 if (!av_match_ext(s->url, "m4a") &&
1588 !av_match_ext(s->url, "m4v") &&
1589 !av_match_ext(s->url, "m4b"))
1590 av_log(s, AV_LOG_WARNING, "Warning, extension is not .m4a nor .m4v "
1591 "Quicktime/Ipod might not play the file\n");
1592 tag = track->par->codec_tag;
1593 } else if (track->mode & MODE_3GP)
1594 tag = track->par->codec_tag;
1595 else if (track->mode == MODE_F4V)
1596 tag = track->par->codec_tag;
1598 tag = mov_get_codec_tag(s, track);
1603 /** Write uuid atom.
1604 * Needed to make file play in iPods running newest firmware
1605 * goes after avcC atom in moov.trak.mdia.minf.stbl.stsd.avc1
1607 static int mov_write_uuid_tag_ipod(AVIOContext *pb)
1610 ffio_wfourcc(pb, "uuid");
1611 avio_wb32(pb, 0x6b6840f2);
1612 avio_wb32(pb, 0x5f244fc5);
1613 avio_wb32(pb, 0xba39a51b);
1614 avio_wb32(pb, 0xcf0323f3);
1619 static const uint16_t fiel_data[] = {
1620 0x0000, 0x0100, 0x0201, 0x0206, 0x0209, 0x020e
1623 static int mov_write_fiel_tag(AVIOContext *pb, MOVTrack *track, int field_order)
1625 unsigned mov_field_order = 0;
1626 if (field_order < FF_ARRAY_ELEMS(fiel_data))
1627 mov_field_order = fiel_data[field_order];
1631 ffio_wfourcc(pb, "fiel");
1632 avio_wb16(pb, mov_field_order);
1636 static int mov_write_subtitle_tag(AVIOContext *pb, MOVTrack *track)
1638 int64_t pos = avio_tell(pb);
1639 avio_wb32(pb, 0); /* size */
1640 avio_wl32(pb, track->tag); // store it byteswapped
1641 avio_wb32(pb, 0); /* Reserved */
1642 avio_wb16(pb, 0); /* Reserved */
1643 avio_wb16(pb, 1); /* Data-reference index */
1645 if (track->par->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
1646 mov_write_esds_tag(pb, track);
1647 else if (track->par->extradata_size)
1648 avio_write(pb, track->par->extradata, track->par->extradata_size);
1650 return update_size(pb, pos);
1653 static int mov_write_st3d_tag(AVIOContext *pb, AVStereo3D *stereo_3d)
1657 if (stereo_3d->flags != 0) {
1658 av_log(pb, AV_LOG_WARNING, "Unsupported stereo_3d flags %x. st3d not written.\n", stereo_3d->flags);
1662 switch (stereo_3d->type) {
1663 case AV_STEREO3D_2D:
1666 case AV_STEREO3D_TOPBOTTOM:
1669 case AV_STEREO3D_SIDEBYSIDE:
1673 av_log(pb, AV_LOG_WARNING, "Unsupported stereo_3d type %s. st3d not written.\n", av_stereo3d_type_name(stereo_3d->type));
1676 avio_wb32(pb, 13); /* size */
1677 ffio_wfourcc(pb, "st3d");
1678 avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1679 avio_w8(pb, stereo_mode);
1683 static int mov_write_sv3d_tag(AVFormatContext *s, AVIOContext *pb, AVSphericalMapping *spherical_mapping)
1685 int64_t sv3d_pos, svhd_pos, proj_pos;
1686 const char* metadata_source = s->flags & AVFMT_FLAG_BITEXACT ? "Lavf" : LIBAVFORMAT_IDENT;
1688 if (spherical_mapping->projection != AV_SPHERICAL_EQUIRECTANGULAR &&
1689 spherical_mapping->projection != AV_SPHERICAL_EQUIRECTANGULAR_TILE &&
1690 spherical_mapping->projection != AV_SPHERICAL_CUBEMAP) {
1691 av_log(pb, AV_LOG_WARNING, "Unsupported projection %d. sv3d not written.\n", spherical_mapping->projection);
1695 sv3d_pos = avio_tell(pb);
1696 avio_wb32(pb, 0); /* size */
1697 ffio_wfourcc(pb, "sv3d");
1699 svhd_pos = avio_tell(pb);
1700 avio_wb32(pb, 0); /* size */
1701 ffio_wfourcc(pb, "svhd");
1702 avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1703 avio_put_str(pb, metadata_source);
1704 update_size(pb, svhd_pos);
1706 proj_pos = avio_tell(pb);
1707 avio_wb32(pb, 0); /* size */
1708 ffio_wfourcc(pb, "proj");
1710 avio_wb32(pb, 24); /* size */
1711 ffio_wfourcc(pb, "prhd");
1712 avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1713 avio_wb32(pb, spherical_mapping->yaw);
1714 avio_wb32(pb, spherical_mapping->pitch);
1715 avio_wb32(pb, spherical_mapping->roll);
1717 switch (spherical_mapping->projection) {
1718 case AV_SPHERICAL_EQUIRECTANGULAR:
1719 case AV_SPHERICAL_EQUIRECTANGULAR_TILE:
1720 avio_wb32(pb, 28); /* size */
1721 ffio_wfourcc(pb, "equi");
1722 avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1723 avio_wb32(pb, spherical_mapping->bound_top);
1724 avio_wb32(pb, spherical_mapping->bound_bottom);
1725 avio_wb32(pb, spherical_mapping->bound_left);
1726 avio_wb32(pb, spherical_mapping->bound_right);
1728 case AV_SPHERICAL_CUBEMAP:
1729 avio_wb32(pb, 20); /* size */
1730 ffio_wfourcc(pb, "cbmp");
1731 avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1732 avio_wb32(pb, 0); /* layout */
1733 avio_wb32(pb, spherical_mapping->padding); /* padding */
1736 update_size(pb, proj_pos);
1738 return update_size(pb, sv3d_pos);
1741 static int mov_write_clap_tag(AVIOContext *pb, MOVTrack *track)
1744 ffio_wfourcc(pb, "clap");
1745 avio_wb32(pb, track->par->width); /* apertureWidth_N */
1746 avio_wb32(pb, 1); /* apertureWidth_D (= 1) */
1747 avio_wb32(pb, track->height); /* apertureHeight_N */
1748 avio_wb32(pb, 1); /* apertureHeight_D (= 1) */
1749 avio_wb32(pb, 0); /* horizOff_N (= 0) */
1750 avio_wb32(pb, 1); /* horizOff_D (= 1) */
1751 avio_wb32(pb, 0); /* vertOff_N (= 0) */
1752 avio_wb32(pb, 1); /* vertOff_D (= 1) */
1756 static int mov_write_pasp_tag(AVIOContext *pb, MOVTrack *track)
1759 av_reduce(&sar.num, &sar.den, track->par->sample_aspect_ratio.num,
1760 track->par->sample_aspect_ratio.den, INT_MAX);
1763 ffio_wfourcc(pb, "pasp");
1764 avio_wb32(pb, sar.num);
1765 avio_wb32(pb, sar.den);
1769 static int mov_write_gama_tag(AVIOContext *pb, MOVTrack *track, double gamma)
1774 gamma = avpriv_get_gamma_from_trc(track->par->color_trc);
1776 av_log(pb, AV_LOG_DEBUG, "gamma value %g\n", gamma);
1779 gama = (uint32_t)lrint((double)(1<<16) * gamma);
1780 av_log(pb, AV_LOG_DEBUG, "writing gama value %"PRId32"\n", gama);
1782 av_assert0(track->mode == MODE_MOV);
1784 ffio_wfourcc(pb, "gama");
1785 avio_wb32(pb, gama);
1789 av_log(pb, AV_LOG_WARNING, "gamma value unknown, unable to write gama atom\n");
1794 static int mov_write_colr_tag(AVIOContext *pb, MOVTrack *track)
1796 // Ref (MOV): https://developer.apple.com/library/mac/technotes/tn2162/_index.html#//apple_ref/doc/uid/DTS40013070-CH1-TNTAG9
1797 // Ref (MP4): ISO/IEC 14496-12:2012
1799 if (track->par->color_primaries == AVCOL_PRI_UNSPECIFIED &&
1800 track->par->color_trc == AVCOL_TRC_UNSPECIFIED &&
1801 track->par->color_space == AVCOL_SPC_UNSPECIFIED) {
1802 if ((track->par->width >= 1920 && track->par->height >= 1080)
1803 || (track->par->width == 1280 && track->par->height == 720)) {
1804 av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming bt709\n");
1805 track->par->color_primaries = AVCOL_PRI_BT709;
1806 } else if (track->par->width == 720 && track->height == 576) {
1807 av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming bt470bg\n");
1808 track->par->color_primaries = AVCOL_PRI_BT470BG;
1809 } else if (track->par->width == 720 &&
1810 (track->height == 486 || track->height == 480)) {
1811 av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming smpte170\n");
1812 track->par->color_primaries = AVCOL_PRI_SMPTE170M;
1814 av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, unable to assume anything\n");
1816 switch (track->par->color_primaries) {
1817 case AVCOL_PRI_BT709:
1818 track->par->color_trc = AVCOL_TRC_BT709;
1819 track->par->color_space = AVCOL_SPC_BT709;
1821 case AVCOL_PRI_SMPTE170M:
1822 case AVCOL_PRI_BT470BG:
1823 track->par->color_trc = AVCOL_TRC_BT709;
1824 track->par->color_space = AVCOL_SPC_SMPTE170M;
1829 /* We should only ever be called by MOV or MP4. */
1830 av_assert0(track->mode == MODE_MOV || track->mode == MODE_MP4);
1832 avio_wb32(pb, 18 + (track->mode == MODE_MP4));
1833 ffio_wfourcc(pb, "colr");
1834 if (track->mode == MODE_MP4)
1835 ffio_wfourcc(pb, "nclx");
1837 ffio_wfourcc(pb, "nclc");
1838 switch (track->par->color_primaries) {
1839 case AVCOL_PRI_BT709: avio_wb16(pb, 1); break;
1840 case AVCOL_PRI_BT470BG: avio_wb16(pb, 5); break;
1841 case AVCOL_PRI_SMPTE170M:
1842 case AVCOL_PRI_SMPTE240M: avio_wb16(pb, 6); break;
1843 case AVCOL_PRI_BT2020: avio_wb16(pb, 9); break;
1844 case AVCOL_PRI_SMPTE431: avio_wb16(pb, 11); break;
1845 case AVCOL_PRI_SMPTE432: avio_wb16(pb, 12); break;
1846 default: avio_wb16(pb, 2);
1848 switch (track->par->color_trc) {
1849 case AVCOL_TRC_BT709: avio_wb16(pb, 1); break;
1850 case AVCOL_TRC_SMPTE170M: avio_wb16(pb, 1); break; // remapped
1851 case AVCOL_TRC_SMPTE240M: avio_wb16(pb, 7); break;
1852 case AVCOL_TRC_SMPTEST2084: avio_wb16(pb, 16); break;
1853 case AVCOL_TRC_SMPTE428: avio_wb16(pb, 17); break;
1854 case AVCOL_TRC_ARIB_STD_B67: avio_wb16(pb, 18); break;
1855 default: avio_wb16(pb, 2);
1857 switch (track->par->color_space) {
1858 case AVCOL_SPC_BT709: avio_wb16(pb, 1); break;
1859 case AVCOL_SPC_BT470BG:
1860 case AVCOL_SPC_SMPTE170M: avio_wb16(pb, 6); break;
1861 case AVCOL_SPC_SMPTE240M: avio_wb16(pb, 7); break;
1862 case AVCOL_SPC_BT2020_NCL: avio_wb16(pb, 9); break;
1863 default: avio_wb16(pb, 2);
1866 if (track->mode == MODE_MP4) {
1867 int full_range = track->par->color_range == AVCOL_RANGE_JPEG;
1868 avio_w8(pb, full_range << 7);
1875 static void find_compressor(char * compressor_name, int len, MOVTrack *track)
1877 AVDictionaryEntry *encoder;
1878 int xdcam_res = (track->par->width == 1280 && track->par->height == 720)
1879 || (track->par->width == 1440 && track->par->height == 1080)
1880 || (track->par->width == 1920 && track->par->height == 1080);
1882 if (track->mode == MODE_MOV &&
1883 (encoder = av_dict_get(track->st->metadata, "encoder", NULL, 0))) {
1884 av_strlcpy(compressor_name, encoder->value, 32);
1885 } else if (track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO && xdcam_res) {
1886 int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE;
1887 AVStream *st = track->st;
1888 int rate = defined_frame_rate(NULL, st);
1889 av_strlcatf(compressor_name, len, "XDCAM");
1890 if (track->par->format == AV_PIX_FMT_YUV422P) {
1891 av_strlcatf(compressor_name, len, " HD422");
1892 } else if(track->par->width == 1440) {
1893 av_strlcatf(compressor_name, len, " HD");
1895 av_strlcatf(compressor_name, len, " EX");
1897 av_strlcatf(compressor_name, len, " %d%c", track->par->height, interlaced ? 'i' : 'p');
1899 av_strlcatf(compressor_name, len, "%d", rate * (interlaced + 1));
1903 static int mov_write_video_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
1905 int64_t pos = avio_tell(pb);
1906 char compressor_name[32] = { 0 };
1909 int uncompressed_ycbcr = ((track->par->codec_id == AV_CODEC_ID_RAWVIDEO && track->par->format == AV_PIX_FMT_UYVY422)
1910 || (track->par->codec_id == AV_CODEC_ID_RAWVIDEO && track->par->format == AV_PIX_FMT_YUYV422)
1911 || track->par->codec_id == AV_CODEC_ID_V308
1912 || track->par->codec_id == AV_CODEC_ID_V408
1913 || track->par->codec_id == AV_CODEC_ID_V410
1914 || track->par->codec_id == AV_CODEC_ID_V210);
1916 avio_wb32(pb, 0); /* size */
1917 if (mov->encryption_scheme != MOV_ENC_NONE) {
1918 ffio_wfourcc(pb, "encv");
1920 avio_wl32(pb, track->tag); // store it byteswapped
1922 avio_wb32(pb, 0); /* Reserved */
1923 avio_wb16(pb, 0); /* Reserved */
1924 avio_wb16(pb, 1); /* Data-reference index */
1926 if (uncompressed_ycbcr) {
1927 avio_wb16(pb, 2); /* Codec stream version */
1929 avio_wb16(pb, 0); /* Codec stream version */
1931 avio_wb16(pb, 0); /* Codec stream revision (=0) */
1932 if (track->mode == MODE_MOV) {
1933 ffio_wfourcc(pb, "FFMP"); /* Vendor */
1934 if (track->par->codec_id == AV_CODEC_ID_RAWVIDEO || uncompressed_ycbcr) {
1935 avio_wb32(pb, 0); /* Temporal Quality */
1936 avio_wb32(pb, 0x400); /* Spatial Quality = lossless*/
1938 avio_wb32(pb, 0x200); /* Temporal Quality = normal */
1939 avio_wb32(pb, 0x200); /* Spatial Quality = normal */
1942 avio_wb32(pb, 0); /* Reserved */
1943 avio_wb32(pb, 0); /* Reserved */
1944 avio_wb32(pb, 0); /* Reserved */
1946 avio_wb16(pb, track->par->width); /* Video width */
1947 avio_wb16(pb, track->height); /* Video height */
1948 avio_wb32(pb, 0x00480000); /* Horizontal resolution 72dpi */
1949 avio_wb32(pb, 0x00480000); /* Vertical resolution 72dpi */
1950 avio_wb32(pb, 0); /* Data size (= 0) */
1951 avio_wb16(pb, 1); /* Frame count (= 1) */
1953 /* FIXME not sure, ISO 14496-1 draft where it shall be set to 0 */
1954 find_compressor(compressor_name, 32, track);
1955 avio_w8(pb, strlen(compressor_name));
1956 avio_write(pb, compressor_name, 31);
1958 if (track->mode == MODE_MOV &&
1959 (track->par->codec_id == AV_CODEC_ID_V410 || track->par->codec_id == AV_CODEC_ID_V210))
1960 avio_wb16(pb, 0x18);
1961 else if (track->mode == MODE_MOV && track->par->bits_per_coded_sample)
1962 avio_wb16(pb, track->par->bits_per_coded_sample |
1963 (track->par->format == AV_PIX_FMT_GRAY8 ? 0x20 : 0));
1965 avio_wb16(pb, 0x18); /* Reserved */
1967 if (track->mode == MODE_MOV && track->par->format == AV_PIX_FMT_PAL8) {
1968 int pal_size = 1 << track->par->bits_per_coded_sample;
1970 avio_wb16(pb, 0); /* Color table ID */
1971 avio_wb32(pb, 0); /* Color table seed */
1972 avio_wb16(pb, 0x8000); /* Color table flags */
1973 avio_wb16(pb, pal_size - 1); /* Color table size (zero-relative) */
1974 for (i = 0; i < pal_size; i++) {
1975 uint32_t rgb = track->palette[i];
1976 uint16_t r = (rgb >> 16) & 0xff;
1977 uint16_t g = (rgb >> 8) & 0xff;
1978 uint16_t b = rgb & 0xff;
1980 avio_wb16(pb, (r << 8) | r);
1981 avio_wb16(pb, (g << 8) | g);
1982 avio_wb16(pb, (b << 8) | b);
1985 avio_wb16(pb, 0xffff); /* Reserved */
1987 if (track->tag == MKTAG('m','p','4','v'))
1988 mov_write_esds_tag(pb, track);
1989 else if (track->par->codec_id == AV_CODEC_ID_H263)
1990 mov_write_d263_tag(pb);
1991 else if (track->par->codec_id == AV_CODEC_ID_AVUI ||
1992 track->par->codec_id == AV_CODEC_ID_SVQ3) {
1993 mov_write_extradata_tag(pb, track);
1995 } else if (track->par->codec_id == AV_CODEC_ID_DNXHD) {
1996 mov_write_avid_tag(pb, track);
1998 } else if (track->par->codec_id == AV_CODEC_ID_HEVC)
1999 mov_write_hvcc_tag(pb, track);
2000 else if (track->par->codec_id == AV_CODEC_ID_H264 && !TAG_IS_AVCI(track->tag)) {
2001 mov_write_avcc_tag(pb, track);
2002 if (track->mode == MODE_IPOD)
2003 mov_write_uuid_tag_ipod(pb);
2004 } else if (track->par->codec_id == AV_CODEC_ID_VP9) {
2005 mov_write_vpcc_tag(mov->fc, pb, track);
2006 } else if (track->par->codec_id == AV_CODEC_ID_VC1 && track->vos_len > 0)
2007 mov_write_dvc1_tag(pb, track);
2008 else if (track->par->codec_id == AV_CODEC_ID_VP6F ||
2009 track->par->codec_id == AV_CODEC_ID_VP6A) {
2010 /* Don't write any potential extradata here - the cropping
2011 * is signalled via the normal width/height fields. */
2012 } else if (track->par->codec_id == AV_CODEC_ID_R10K) {
2013 if (track->par->codec_tag == MKTAG('R','1','0','k'))
2014 mov_write_dpxe_tag(pb, track);
2015 } else if (track->vos_len > 0)
2016 mov_write_glbl_tag(pb, track);
2018 if (track->par->codec_id != AV_CODEC_ID_H264 &&
2019 track->par->codec_id != AV_CODEC_ID_MPEG4 &&
2020 track->par->codec_id != AV_CODEC_ID_DNXHD) {
2021 int field_order = track->par->field_order;
2023 #if FF_API_LAVF_AVCTX
2024 FF_DISABLE_DEPRECATION_WARNINGS
2025 if (field_order != track->st->codec->field_order && track->st->codec->field_order != AV_FIELD_UNKNOWN)
2026 field_order = track->st->codec->field_order;
2027 FF_ENABLE_DEPRECATION_WARNINGS
2030 if (field_order != AV_FIELD_UNKNOWN)
2031 mov_write_fiel_tag(pb, track, field_order);
2034 if (mov->flags & FF_MOV_FLAG_WRITE_GAMA) {
2035 if (track->mode == MODE_MOV)
2036 mov_write_gama_tag(pb, track, mov->gamma);
2038 av_log(mov->fc, AV_LOG_WARNING, "Not writing 'gama' atom. Format is not MOV.\n");
2040 if (mov->flags & FF_MOV_FLAG_WRITE_COLR) {
2041 if (track->mode == MODE_MOV || track->mode == MODE_MP4)
2042 mov_write_colr_tag(pb, track);
2044 av_log(mov->fc, AV_LOG_WARNING, "Not writing 'colr' atom. Format is not MOV or MP4.\n");
2047 if (track->mode == MODE_MP4 && mov->fc->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL) {
2048 AVStereo3D* stereo_3d = (AVStereo3D*) av_stream_get_side_data(track->st, AV_PKT_DATA_STEREO3D, NULL);
2049 AVSphericalMapping* spherical_mapping = (AVSphericalMapping*)av_stream_get_side_data(track->st, AV_PKT_DATA_SPHERICAL, NULL);
2052 mov_write_st3d_tag(pb, stereo_3d);
2053 if (spherical_mapping)
2054 mov_write_sv3d_tag(mov->fc, pb, spherical_mapping);
2057 if (track->par->sample_aspect_ratio.den && track->par->sample_aspect_ratio.num) {
2058 mov_write_pasp_tag(pb, track);
2061 if (uncompressed_ycbcr){
2062 mov_write_clap_tag(pb, track);
2065 if (mov->encryption_scheme != MOV_ENC_NONE) {
2066 ff_mov_cenc_write_sinf_tag(track, pb, mov->encryption_kid);
2069 /* extra padding for avid stsd */
2070 /* https://developer.apple.com/library/mac/documentation/QuickTime/QTFF/QTFFChap2/qtff2.html#//apple_ref/doc/uid/TP40000939-CH204-61112 */
2074 return update_size(pb, pos);
2077 static int mov_write_rtp_tag(AVIOContext *pb, MOVTrack *track)
2079 int64_t pos = avio_tell(pb);
2080 avio_wb32(pb, 0); /* size */
2081 ffio_wfourcc(pb, "rtp ");
2082 avio_wb32(pb, 0); /* Reserved */
2083 avio_wb16(pb, 0); /* Reserved */
2084 avio_wb16(pb, 1); /* Data-reference index */
2086 avio_wb16(pb, 1); /* Hint track version */
2087 avio_wb16(pb, 1); /* Highest compatible version */
2088 avio_wb32(pb, track->max_packet_size); /* Max packet size */
2090 avio_wb32(pb, 12); /* size */
2091 ffio_wfourcc(pb, "tims");
2092 avio_wb32(pb, track->timescale);
2094 return update_size(pb, pos);
2097 static int mov_write_source_reference_tag(AVIOContext *pb, MOVTrack *track, const char *reel_name)
2099 uint64_t str_size =strlen(reel_name);
2100 int64_t pos = avio_tell(pb);
2102 if (str_size >= UINT16_MAX){
2103 av_log(NULL, AV_LOG_ERROR, "reel_name length %"PRIu64" is too large\n", str_size);
2105 return AVERROR(EINVAL);
2108 avio_wb32(pb, 0); /* size */
2109 ffio_wfourcc(pb, "name"); /* Data format */
2110 avio_wb16(pb, str_size); /* string size */
2111 avio_wb16(pb, track->language); /* langcode */
2112 avio_write(pb, reel_name, str_size); /* reel name */
2113 return update_size(pb,pos);
2116 static int mov_write_tmcd_tag(AVIOContext *pb, MOVTrack *track)
2118 int64_t pos = avio_tell(pb);
2122 AVDictionaryEntry *t = NULL;
2124 if (!track->st->avg_frame_rate.num || !track->st->avg_frame_rate.den) {
2125 #if FF_API_LAVF_AVCTX
2126 FF_DISABLE_DEPRECATION_WARNINGS
2127 frame_duration = av_rescale(track->timescale, track->st->codec->time_base.num, track->st->codec->time_base.den);
2128 nb_frames = ROUNDED_DIV(track->st->codec->time_base.den, track->st->codec->time_base.num);
2129 FF_ENABLE_DEPRECATION_WARNINGS
2131 av_log(NULL, AV_LOG_ERROR, "avg_frame_rate not set for tmcd track.\n");
2132 return AVERROR(EINVAL);
2135 frame_duration = av_rescale(track->timescale, track->st->avg_frame_rate.num, track->st->avg_frame_rate.den);
2136 nb_frames = ROUNDED_DIV(track->st->avg_frame_rate.den, track->st->avg_frame_rate.num);
2139 if (nb_frames > 255) {
2140 av_log(NULL, AV_LOG_ERROR, "fps %d is too large\n", nb_frames);
2141 return AVERROR(EINVAL);
2144 avio_wb32(pb, 0); /* size */
2145 ffio_wfourcc(pb, "tmcd"); /* Data format */
2146 avio_wb32(pb, 0); /* Reserved */
2147 avio_wb32(pb, 1); /* Data reference index */
2148 avio_wb32(pb, 0); /* Flags */
2149 avio_wb32(pb, track->timecode_flags); /* Flags (timecode) */
2150 avio_wb32(pb, track->timescale); /* Timescale */
2151 avio_wb32(pb, frame_duration); /* Frame duration */
2152 avio_w8(pb, nb_frames); /* Number of frames */
2153 avio_w8(pb, 0); /* Reserved */
2155 t = av_dict_get(track->st->metadata, "reel_name", NULL, 0);
2156 if (t && utf8len(t->value) && track->mode != MODE_MP4)
2157 mov_write_source_reference_tag(pb, track, t->value);
2159 avio_wb16(pb, 0); /* zero size */
2162 avio_wb32(pb, 0); /* size */
2163 ffio_wfourcc(pb, "tmcd"); /* Data format */
2164 avio_wb32(pb, 0); /* Reserved */
2165 avio_wb32(pb, 1); /* Data reference index */
2166 if (track->par->extradata_size)
2167 avio_write(pb, track->par->extradata, track->par->extradata_size);
2169 return update_size(pb, pos);
2172 static int mov_write_gpmd_tag(AVIOContext *pb, const MOVTrack *track)
2174 int64_t pos = avio_tell(pb);
2175 avio_wb32(pb, 0); /* size */
2176 ffio_wfourcc(pb, "gpmd");
2177 avio_wb32(pb, 0); /* Reserved */
2178 avio_wb16(pb, 0); /* Reserved */
2179 avio_wb16(pb, 1); /* Data-reference index */
2180 avio_wb32(pb, 0); /* Reserved */
2181 return update_size(pb, pos);
2184 static int mov_write_stsd_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
2186 int64_t pos = avio_tell(pb);
2187 avio_wb32(pb, 0); /* size */
2188 ffio_wfourcc(pb, "stsd");
2189 avio_wb32(pb, 0); /* version & flags */
2190 avio_wb32(pb, 1); /* entry count */
2191 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO)
2192 mov_write_video_tag(pb, mov, track);
2193 else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
2194 mov_write_audio_tag(s, pb, mov, track);
2195 else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)
2196 mov_write_subtitle_tag(pb, track);
2197 else if (track->par->codec_tag == MKTAG('r','t','p',' '))
2198 mov_write_rtp_tag(pb, track);
2199 else if (track->par->codec_tag == MKTAG('t','m','c','d'))
2200 mov_write_tmcd_tag(pb, track);
2201 else if (track->par->codec_tag == MKTAG('g','p','m','d'))
2202 mov_write_gpmd_tag(pb, track);
2203 return update_size(pb, pos);
2206 static int mov_write_ctts_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
2208 MOVMuxContext *mov = s->priv_data;
2209 MOVStts *ctts_entries;
2210 uint32_t entries = 0;
2214 ctts_entries = av_malloc_array((track->entry + 1), sizeof(*ctts_entries)); /* worst case */
2216 return AVERROR(ENOMEM);
2217 ctts_entries[0].count = 1;
2218 ctts_entries[0].duration = track->cluster[0].cts;
2219 for (i = 1; i < track->entry; i++) {
2220 if (track->cluster[i].cts == ctts_entries[entries].duration) {
2221 ctts_entries[entries].count++; /* compress */
2224 ctts_entries[entries].duration = track->cluster[i].cts;
2225 ctts_entries[entries].count = 1;
2228 entries++; /* last one */
2229 atom_size = 16 + (entries * 8);
2230 avio_wb32(pb, atom_size); /* size */
2231 ffio_wfourcc(pb, "ctts");
2232 if (mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS)
2233 avio_w8(pb, 1); /* version */
2235 avio_w8(pb, 0); /* version */
2236 avio_wb24(pb, 0); /* flags */
2237 avio_wb32(pb, entries); /* entry count */
2238 for (i = 0; i < entries; i++) {
2239 avio_wb32(pb, ctts_entries[i].count);
2240 avio_wb32(pb, ctts_entries[i].duration);
2242 av_free(ctts_entries);
2246 /* Time to sample atom */
2247 static int mov_write_stts_tag(AVIOContext *pb, MOVTrack *track)
2249 MOVStts *stts_entries = NULL;
2250 uint32_t entries = -1;
2254 if (track->par->codec_type == AVMEDIA_TYPE_AUDIO && !track->audio_vbr) {
2255 stts_entries = av_malloc(sizeof(*stts_entries)); /* one entry */
2257 return AVERROR(ENOMEM);
2258 stts_entries[0].count = track->sample_count;
2259 stts_entries[0].duration = 1;
2263 stts_entries = av_malloc_array(track->entry, sizeof(*stts_entries)); /* worst case */
2265 return AVERROR(ENOMEM);
2267 for (i = 0; i < track->entry; i++) {
2268 int duration = get_cluster_duration(track, i);
2269 if (i && duration == stts_entries[entries].duration) {
2270 stts_entries[entries].count++; /* compress */
2273 stts_entries[entries].duration = duration;
2274 stts_entries[entries].count = 1;
2277 entries++; /* last one */
2279 atom_size = 16 + (entries * 8);
2280 avio_wb32(pb, atom_size); /* size */
2281 ffio_wfourcc(pb, "stts");
2282 avio_wb32(pb, 0); /* version & flags */
2283 avio_wb32(pb, entries); /* entry count */
2284 for (i = 0; i < entries; i++) {
2285 avio_wb32(pb, stts_entries[i].count);
2286 avio_wb32(pb, stts_entries[i].duration);
2288 av_free(stts_entries);
2292 static int mov_write_dref_tag(AVIOContext *pb)
2294 avio_wb32(pb, 28); /* size */
2295 ffio_wfourcc(pb, "dref");
2296 avio_wb32(pb, 0); /* version & flags */
2297 avio_wb32(pb, 1); /* entry count */
2299 avio_wb32(pb, 0xc); /* size */
2300 //FIXME add the alis and rsrc atom
2301 ffio_wfourcc(pb, "url ");
2302 avio_wb32(pb, 1); /* version & flags */
2307 static int mov_preroll_write_stbl_atoms(AVIOContext *pb, MOVTrack *track)
2311 int16_t roll_distance;
2312 int group_description_index;
2315 struct sgpd_entry *sgpd_entries = NULL;
2320 const int OPUS_SEEK_PREROLL_MS = 80;
2321 int roll_samples = av_rescale_q(OPUS_SEEK_PREROLL_MS,
2322 (AVRational){1, 1000},
2323 (AVRational){1, 48000});
2328 sgpd_entries = av_malloc_array(track->entry, sizeof(*sgpd_entries));
2330 return AVERROR(ENOMEM);
2332 av_assert0(track->par->codec_id == AV_CODEC_ID_OPUS || track->par->codec_id == AV_CODEC_ID_AAC);
2334 if (track->par->codec_id == AV_CODEC_ID_OPUS) {
2335 for (i = 0; i < track->entry; i++) {
2336 int roll_samples_remaining = roll_samples;
2338 for (j = i - 1; j >= 0; j--) {
2339 roll_samples_remaining -= get_cluster_duration(track, j);
2341 if (roll_samples_remaining <= 0)
2344 /* We don't have enough preceeding samples to compute a valid
2345 roll_distance here, so this sample can't be independently
2347 if (roll_samples_remaining > 0)
2349 /* Verify distance is a minimum of 2 (60ms) packets and a maximum of
2350 32 (2.5ms) packets. */
2351 av_assert0(distance == 0 || (distance >= 2 && distance <= 32));
2352 if (i && distance == sgpd_entries[entries].roll_distance) {
2353 sgpd_entries[entries].count++;
2356 sgpd_entries[entries].count = 1;
2357 sgpd_entries[entries].roll_distance = distance;
2358 sgpd_entries[entries].group_description_index = distance ? ++group : 0;
2363 sgpd_entries[entries].count = track->sample_count;
2364 sgpd_entries[entries].roll_distance = 1;
2365 sgpd_entries[entries].group_description_index = ++group;
2370 av_free(sgpd_entries);
2374 /* Write sgpd tag */
2375 avio_wb32(pb, 24 + (group * 2)); /* size */
2376 ffio_wfourcc(pb, "sgpd");
2377 avio_wb32(pb, 1 << 24); /* fullbox */
2378 ffio_wfourcc(pb, "roll");
2379 avio_wb32(pb, 2); /* default_length */
2380 avio_wb32(pb, group); /* entry_count */
2381 for (i = 0; i < entries; i++) {
2382 if (sgpd_entries[i].group_description_index) {
2383 avio_wb16(pb, -sgpd_entries[i].roll_distance); /* roll_distance */
2387 /* Write sbgp tag */
2388 avio_wb32(pb, 20 + (entries * 8)); /* size */
2389 ffio_wfourcc(pb, "sbgp");
2390 avio_wb32(pb, 0); /* fullbox */
2391 ffio_wfourcc(pb, "roll");
2392 avio_wb32(pb, entries); /* entry_count */
2393 for (i = 0; i < entries; i++) {
2394 avio_wb32(pb, sgpd_entries[i].count); /* sample_count */
2395 avio_wb32(pb, sgpd_entries[i].group_description_index); /* group_description_index */
2398 av_free(sgpd_entries);
2402 static int mov_write_stbl_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
2404 int64_t pos = avio_tell(pb);
2407 avio_wb32(pb, 0); /* size */
2408 ffio_wfourcc(pb, "stbl");
2409 mov_write_stsd_tag(s, pb, mov, track);
2410 mov_write_stts_tag(pb, track);
2411 if ((track->par->codec_type == AVMEDIA_TYPE_VIDEO ||
2412 track->par->codec_tag == MKTAG('r','t','p',' ')) &&
2413 track->has_keyframes && track->has_keyframes < track->entry)
2414 mov_write_stss_tag(pb, track, MOV_SYNC_SAMPLE);
2415 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO && track->has_disposable)
2416 mov_write_sdtp_tag(pb, track);
2417 if (track->mode == MODE_MOV && track->flags & MOV_TRACK_STPS)
2418 mov_write_stss_tag(pb, track, MOV_PARTIAL_SYNC_SAMPLE);
2419 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO &&
2420 track->flags & MOV_TRACK_CTTS && track->entry) {
2422 if ((ret = mov_write_ctts_tag(s, pb, track)) < 0)
2425 mov_write_stsc_tag(pb, track);
2426 mov_write_stsz_tag(pb, track);
2427 mov_write_stco_tag(pb, track);
2428 if (track->cenc.aes_ctr) {
2429 ff_mov_cenc_write_stbl_atoms(&track->cenc, pb);
2431 if (track->par->codec_id == AV_CODEC_ID_OPUS || track->par->codec_id == AV_CODEC_ID_AAC) {
2432 mov_preroll_write_stbl_atoms(pb, track);
2434 return update_size(pb, pos);
2437 static int mov_write_dinf_tag(AVIOContext *pb)
2439 int64_t pos = avio_tell(pb);
2440 avio_wb32(pb, 0); /* size */
2441 ffio_wfourcc(pb, "dinf");
2442 mov_write_dref_tag(pb);
2443 return update_size(pb, pos);
2446 static int mov_write_nmhd_tag(AVIOContext *pb)
2449 ffio_wfourcc(pb, "nmhd");
2454 static int mov_write_tcmi_tag(AVIOContext *pb, MOVTrack *track)
2456 int64_t pos = avio_tell(pb);
2457 const char *font = "Lucida Grande";
2458 avio_wb32(pb, 0); /* size */
2459 ffio_wfourcc(pb, "tcmi"); /* timecode media information atom */
2460 avio_wb32(pb, 0); /* version & flags */
2461 avio_wb16(pb, 0); /* text font */
2462 avio_wb16(pb, 0); /* text face */
2463 avio_wb16(pb, 12); /* text size */
2464 avio_wb16(pb, 0); /* (unknown, not in the QT specs...) */
2465 avio_wb16(pb, 0x0000); /* text color (red) */
2466 avio_wb16(pb, 0x0000); /* text color (green) */
2467 avio_wb16(pb, 0x0000); /* text color (blue) */
2468 avio_wb16(pb, 0xffff); /* background color (red) */
2469 avio_wb16(pb, 0xffff); /* background color (green) */
2470 avio_wb16(pb, 0xffff); /* background color (blue) */
2471 avio_w8(pb, strlen(font)); /* font len (part of the pascal string) */
2472 avio_write(pb, font, strlen(font)); /* font name */
2473 return update_size(pb, pos);
2476 static int mov_write_gmhd_tag(AVIOContext *pb, MOVTrack *track)
2478 int64_t pos = avio_tell(pb);
2479 avio_wb32(pb, 0); /* size */
2480 ffio_wfourcc(pb, "gmhd");
2481 avio_wb32(pb, 0x18); /* gmin size */
2482 ffio_wfourcc(pb, "gmin");/* generic media info */
2483 avio_wb32(pb, 0); /* version & flags */
2484 avio_wb16(pb, 0x40); /* graphics mode = */
2485 avio_wb16(pb, 0x8000); /* opColor (r?) */
2486 avio_wb16(pb, 0x8000); /* opColor (g?) */
2487 avio_wb16(pb, 0x8000); /* opColor (b?) */
2488 avio_wb16(pb, 0); /* balance */
2489 avio_wb16(pb, 0); /* reserved */
2492 * This special text atom is required for
2493 * Apple Quicktime chapters. The contents
2494 * don't appear to be documented, so the
2495 * bytes are copied verbatim.
2497 if (track->tag != MKTAG('c','6','0','8')) {
2498 avio_wb32(pb, 0x2C); /* size */
2499 ffio_wfourcc(pb, "text");
2500 avio_wb16(pb, 0x01);
2501 avio_wb32(pb, 0x00);
2502 avio_wb32(pb, 0x00);
2503 avio_wb32(pb, 0x00);
2504 avio_wb32(pb, 0x01);
2505 avio_wb32(pb, 0x00);
2506 avio_wb32(pb, 0x00);
2507 avio_wb32(pb, 0x00);
2508 avio_wb32(pb, 0x00004000);
2509 avio_wb16(pb, 0x0000);
2512 if (track->par->codec_tag == MKTAG('t','m','c','d')) {
2513 int64_t tmcd_pos = avio_tell(pb);
2514 avio_wb32(pb, 0); /* size */
2515 ffio_wfourcc(pb, "tmcd");
2516 mov_write_tcmi_tag(pb, track);
2517 update_size(pb, tmcd_pos);
2518 } else if (track->par->codec_tag == MKTAG('g','p','m','d')) {
2519 int64_t gpmd_pos = avio_tell(pb);
2520 avio_wb32(pb, 0); /* size */
2521 ffio_wfourcc(pb, "gpmd");
2522 avio_wb32(pb, 0); /* version */
2523 update_size(pb, gpmd_pos);
2525 return update_size(pb, pos);
2528 static int mov_write_smhd_tag(AVIOContext *pb)
2530 avio_wb32(pb, 16); /* size */
2531 ffio_wfourcc(pb, "smhd");
2532 avio_wb32(pb, 0); /* version & flags */
2533 avio_wb16(pb, 0); /* reserved (balance, normally = 0) */
2534 avio_wb16(pb, 0); /* reserved */
2538 static int mov_write_vmhd_tag(AVIOContext *pb)
2540 avio_wb32(pb, 0x14); /* size (always 0x14) */
2541 ffio_wfourcc(pb, "vmhd");
2542 avio_wb32(pb, 0x01); /* version & flags */
2543 avio_wb64(pb, 0); /* reserved (graphics mode = copy) */
2547 static int is_clcp_track(MOVTrack *track)
2549 return track->tag == MKTAG('c','7','0','8') ||
2550 track->tag == MKTAG('c','6','0','8');
2553 static int mov_write_hdlr_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
2555 MOVMuxContext *mov = s->priv_data;
2556 const char *hdlr, *descr = NULL, *hdlr_type = NULL;
2557 int64_t pos = avio_tell(pb);
2561 descr = "DataHandler";
2564 hdlr = (track->mode == MODE_MOV) ? "mhlr" : "\0\0\0\0";
2565 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
2567 descr = "VideoHandler";
2568 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
2570 descr = "SoundHandler";
2571 } else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE) {
2572 if (is_clcp_track(track)) {
2574 descr = "ClosedCaptionHandler";
2576 if (track->tag == MKTAG('t','x','3','g')) {
2578 } else if (track->tag == MKTAG('m','p','4','s')) {
2583 descr = "SubtitleHandler";
2585 } else if (track->par->codec_tag == MKTAG('r','t','p',' ')) {
2587 descr = "HintHandler";
2588 } else if (track->par->codec_tag == MKTAG('t','m','c','d')) {
2590 descr = "TimeCodeHandler";
2591 } else if (track->par->codec_tag == MKTAG('g','p','m','d')) {
2593 descr = "GoPro MET"; // GoPro Metadata
2595 av_log(s, AV_LOG_WARNING,
2596 "Unknown hldr_type for %s, writing dummy values\n",
2597 av_fourcc2str(track->par->codec_tag));
2600 // hdlr.name is used by some players to identify the content title
2601 // of the track. So if an alternate handler description is
2602 // specified, use it.
2603 AVDictionaryEntry *t;
2604 t = av_dict_get(track->st->metadata, "handler_name", NULL, 0);
2605 if (t && utf8len(t->value))
2610 if (mov->empty_hdlr_name) /* expressly allowed by QTFF and not prohibited in ISO 14496-12 8.4.3.3 */
2613 avio_wb32(pb, 0); /* size */
2614 ffio_wfourcc(pb, "hdlr");
2615 avio_wb32(pb, 0); /* Version & flags */
2616 avio_write(pb, hdlr, 4); /* handler */
2617 ffio_wfourcc(pb, hdlr_type); /* handler type */
2618 avio_wb32(pb, 0); /* reserved */
2619 avio_wb32(pb, 0); /* reserved */
2620 avio_wb32(pb, 0); /* reserved */
2621 if (!track || track->mode == MODE_MOV)
2622 avio_w8(pb, strlen(descr)); /* pascal string */
2623 avio_write(pb, descr, strlen(descr)); /* handler description */
2624 if (track && track->mode != MODE_MOV)
2625 avio_w8(pb, 0); /* c string */
2626 return update_size(pb, pos);
2629 static int mov_write_hmhd_tag(AVIOContext *pb)
2631 /* This atom must be present, but leaving the values at zero
2632 * seems harmless. */
2633 avio_wb32(pb, 28); /* size */
2634 ffio_wfourcc(pb, "hmhd");
2635 avio_wb32(pb, 0); /* version, flags */
2636 avio_wb16(pb, 0); /* maxPDUsize */
2637 avio_wb16(pb, 0); /* avgPDUsize */
2638 avio_wb32(pb, 0); /* maxbitrate */
2639 avio_wb32(pb, 0); /* avgbitrate */
2640 avio_wb32(pb, 0); /* reserved */
2644 static int mov_write_minf_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
2646 int64_t pos = avio_tell(pb);
2649 avio_wb32(pb, 0); /* size */
2650 ffio_wfourcc(pb, "minf");
2651 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO)
2652 mov_write_vmhd_tag(pb);
2653 else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
2654 mov_write_smhd_tag(pb);
2655 else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE) {
2656 if (track->tag == MKTAG('t','e','x','t') || is_clcp_track(track)) {
2657 mov_write_gmhd_tag(pb, track);
2659 mov_write_nmhd_tag(pb);
2661 } else if (track->tag == MKTAG('r','t','p',' ')) {
2662 mov_write_hmhd_tag(pb);
2663 } else if (track->tag == MKTAG('t','m','c','d')) {
2664 if (track->mode != MODE_MOV)
2665 mov_write_nmhd_tag(pb);
2667 mov_write_gmhd_tag(pb, track);
2668 } else if (track->tag == MKTAG('g','p','m','d')) {
2669 mov_write_gmhd_tag(pb, track);
2671 if (track->mode == MODE_MOV) /* FIXME: Why do it for MODE_MOV only ? */
2672 mov_write_hdlr_tag(s, pb, NULL);
2673 mov_write_dinf_tag(pb);
2674 if ((ret = mov_write_stbl_tag(s, pb, mov, track)) < 0)
2676 return update_size(pb, pos);
2679 static int mov_write_mdhd_tag(AVIOContext *pb, MOVMuxContext *mov,
2682 int version = track->track_duration < INT32_MAX ? 0 : 1;
2684 if (track->mode == MODE_ISM)
2687 (version == 1) ? avio_wb32(pb, 44) : avio_wb32(pb, 32); /* size */
2688 ffio_wfourcc(pb, "mdhd");
2689 avio_w8(pb, version);
2690 avio_wb24(pb, 0); /* flags */
2692 avio_wb64(pb, track->time);
2693 avio_wb64(pb, track->time);
2695 avio_wb32(pb, track->time); /* creation time */
2696 avio_wb32(pb, track->time); /* modification time */
2698 avio_wb32(pb, track->timescale); /* time scale (sample rate for audio) */
2699 if (!track->entry && mov->mode == MODE_ISM)
2700 (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
2701 else if (!track->entry)
2702 (version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0);
2704 (version == 1) ? avio_wb64(pb, track->track_duration) : avio_wb32(pb, track->track_duration); /* duration */
2705 avio_wb16(pb, track->language); /* language */
2706 avio_wb16(pb, 0); /* reserved (quality) */
2708 if (version != 0 && track->mode == MODE_MOV) {
2709 av_log(NULL, AV_LOG_ERROR,
2710 "FATAL error, file duration too long for timebase, this file will not be\n"
2711 "playable with quicktime. Choose a different timebase or a different\n"
2712 "container format\n");
2718 static int mov_write_mdia_tag(AVFormatContext *s, AVIOContext *pb,
2719 MOVMuxContext *mov, MOVTrack *track)
2721 int64_t pos = avio_tell(pb);
2724 avio_wb32(pb, 0); /* size */
2725 ffio_wfourcc(pb, "mdia");
2726 mov_write_mdhd_tag(pb, mov, track);
2727 mov_write_hdlr_tag(s, pb, track);
2728 if ((ret = mov_write_minf_tag(s, pb, mov, track)) < 0)
2730 return update_size(pb, pos);
2733 /* transformation matrix
2737 static void write_matrix(AVIOContext *pb, int16_t a, int16_t b, int16_t c,
2738 int16_t d, int16_t tx, int16_t ty)
2740 avio_wb32(pb, a << 16); /* 16.16 format */
2741 avio_wb32(pb, b << 16); /* 16.16 format */
2742 avio_wb32(pb, 0); /* u in 2.30 format */
2743 avio_wb32(pb, c << 16); /* 16.16 format */
2744 avio_wb32(pb, d << 16); /* 16.16 format */
2745 avio_wb32(pb, 0); /* v in 2.30 format */
2746 avio_wb32(pb, tx << 16); /* 16.16 format */
2747 avio_wb32(pb, ty << 16); /* 16.16 format */
2748 avio_wb32(pb, 1 << 30); /* w in 2.30 format */
2751 static int mov_write_tkhd_tag(AVIOContext *pb, MOVMuxContext *mov,
2752 MOVTrack *track, AVStream *st)
2754 int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE,
2755 track->timescale, AV_ROUND_UP);
2756 int version = duration < INT32_MAX ? 0 : 1;
2757 int flags = MOV_TKHD_FLAG_IN_MOVIE;
2761 uint32_t *display_matrix = NULL;
2762 int display_matrix_size, i;
2765 if (mov->per_stream_grouping)
2768 group = st->codecpar->codec_type;
2770 display_matrix = (uint32_t*)av_stream_get_side_data(st, AV_PKT_DATA_DISPLAYMATRIX,
2771 &display_matrix_size);
2772 if (display_matrix && display_matrix_size < 9 * sizeof(*display_matrix))
2773 display_matrix = NULL;
2776 if (track->flags & MOV_TRACK_ENABLED)
2777 flags |= MOV_TKHD_FLAG_ENABLED;
2779 if (track->mode == MODE_ISM)
2782 (version == 1) ? avio_wb32(pb, 104) : avio_wb32(pb, 92); /* size */
2783 ffio_wfourcc(pb, "tkhd");
2784 avio_w8(pb, version);
2785 avio_wb24(pb, flags);
2787 avio_wb64(pb, track->time);
2788 avio_wb64(pb, track->time);
2790 avio_wb32(pb, track->time); /* creation time */
2791 avio_wb32(pb, track->time); /* modification time */
2793 avio_wb32(pb, track->track_id); /* track-id */
2794 avio_wb32(pb, 0); /* reserved */
2795 if (!track->entry && mov->mode == MODE_ISM)
2796 (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
2797 else if (!track->entry)
2798 (version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0);
2800 (version == 1) ? avio_wb64(pb, duration) : avio_wb32(pb, duration);
2802 avio_wb32(pb, 0); /* reserved */
2803 avio_wb32(pb, 0); /* reserved */
2804 avio_wb16(pb, 0); /* layer */
2805 avio_wb16(pb, group); /* alternate group) */
2806 /* Volume, only for audio */
2807 if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
2808 avio_wb16(pb, 0x0100);
2811 avio_wb16(pb, 0); /* reserved */
2813 /* Matrix structure */
2814 #if FF_API_OLD_ROTATE_API
2815 if (st && st->metadata) {
2816 AVDictionaryEntry *rot = av_dict_get(st->metadata, "rotate", NULL, 0);
2817 rotation = (rot && rot->value) ? atoi(rot->value) : 0;
2820 if (display_matrix) {
2821 for (i = 0; i < 9; i++)
2822 avio_wb32(pb, display_matrix[i]);
2823 #if FF_API_OLD_ROTATE_API
2824 } else if (rotation == 90) {
2825 write_matrix(pb, 0, 1, -1, 0, track->par->height, 0);
2826 } else if (rotation == 180) {
2827 write_matrix(pb, -1, 0, 0, -1, track->par->width, track->par->height);
2828 } else if (rotation == 270) {
2829 write_matrix(pb, 0, -1, 1, 0, 0, track->par->width);
2832 write_matrix(pb, 1, 0, 0, 1, 0, 0);
2834 /* Track width and height, for visual only */
2835 if (st && (track->par->codec_type == AVMEDIA_TYPE_VIDEO ||
2836 track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)) {
2837 int64_t track_width_1616;
2838 if (track->mode == MODE_MOV) {
2839 track_width_1616 = track->par->width * 0x10000ULL;
2841 track_width_1616 = av_rescale(st->sample_aspect_ratio.num,
2842 track->par->width * 0x10000LL,
2843 st->sample_aspect_ratio.den);
2844 if (!track_width_1616 ||
2845 track->height != track->par->height ||
2846 track_width_1616 > UINT32_MAX)
2847 track_width_1616 = track->par->width * 0x10000ULL;
2849 if (track_width_1616 > UINT32_MAX) {
2850 av_log(mov->fc, AV_LOG_WARNING, "track width is too large\n");
2851 track_width_1616 = 0;
2853 avio_wb32(pb, track_width_1616);
2854 if (track->height > 0xFFFF) {
2855 av_log(mov->fc, AV_LOG_WARNING, "track height is too large\n");
2858 avio_wb32(pb, track->height * 0x10000U);
2866 static int mov_write_tapt_tag(AVIOContext *pb, MOVTrack *track)
2868 int32_t width = av_rescale(track->par->sample_aspect_ratio.num, track->par->width,
2869 track->par->sample_aspect_ratio.den);
2871 int64_t pos = avio_tell(pb);
2873 avio_wb32(pb, 0); /* size */
2874 ffio_wfourcc(pb, "tapt");
2877 ffio_wfourcc(pb, "clef");
2879 avio_wb32(pb, width << 16);
2880 avio_wb32(pb, track->par->height << 16);
2883 ffio_wfourcc(pb, "prof");
2885 avio_wb32(pb, width << 16);
2886 avio_wb32(pb, track->par->height << 16);
2889 ffio_wfourcc(pb, "enof");
2891 avio_wb32(pb, track->par->width << 16);
2892 avio_wb32(pb, track->par->height << 16);
2894 return update_size(pb, pos);
2897 // This box seems important for the psp playback ... without it the movie seems to hang
2898 static int mov_write_edts_tag(AVIOContext *pb, MOVMuxContext *mov,
2901 int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE,
2902 track->timescale, AV_ROUND_UP);
2903 int version = duration < INT32_MAX ? 0 : 1;
2904 int entry_size, entry_count, size;
2905 int64_t delay, start_ct = track->start_cts;
2906 int64_t start_dts = track->start_dts;
2909 if (start_dts != track->cluster[0].dts || start_ct != track->cluster[0].cts) {
2911 av_log(mov->fc, AV_LOG_DEBUG,
2912 "EDTS using dts:%"PRId64" cts:%d instead of dts:%"PRId64" cts:%"PRId64" tid:%d\n",
2913 track->cluster[0].dts, track->cluster[0].cts,
2914 start_dts, start_ct, track->track_id);
2915 start_dts = track->cluster[0].dts;
2916 start_ct = track->cluster[0].cts;
2920 delay = av_rescale_rnd(start_dts + start_ct, MOV_TIMESCALE,
2921 track->timescale, AV_ROUND_DOWN);
2922 version |= delay < INT32_MAX ? 0 : 1;
2924 entry_size = (version == 1) ? 20 : 12;
2925 entry_count = 1 + (delay > 0);
2926 size = 24 + entry_count * entry_size;
2928 /* write the atom data */
2929 avio_wb32(pb, size);
2930 ffio_wfourcc(pb, "edts");
2931 avio_wb32(pb, size - 8);
2932 ffio_wfourcc(pb, "elst");
2933 avio_w8(pb, version);
2934 avio_wb24(pb, 0); /* flags */
2936 avio_wb32(pb, entry_count);
2937 if (delay > 0) { /* add an empty edit to delay presentation */
2938 /* In the positive delay case, the delay includes the cts
2939 * offset, and the second edit list entry below trims out
2940 * the same amount from the actual content. This makes sure
2941 * that the offset last sample is included in the edit
2942 * list duration as well. */
2944 avio_wb64(pb, delay);
2947 avio_wb32(pb, delay);
2950 avio_wb32(pb, 0x00010000);
2952 /* Avoid accidentally ending up with start_ct = -1 which has got a
2953 * special meaning. Normally start_ct should end up positive or zero
2954 * here, but use FFMIN in case dts is a small positive integer
2955 * rounded to 0 when represented in MOV_TIMESCALE units. */
2956 av_assert0(av_rescale_rnd(start_dts, MOV_TIMESCALE, track->timescale, AV_ROUND_DOWN) <= 0);
2957 start_ct = -FFMIN(start_dts, 0);
2958 /* Note, this delay is calculated from the pts of the first sample,
2959 * ensuring that we don't reduce the duration for cases with
2964 /* For fragmented files, we don't know the full length yet. Setting
2965 * duration to 0 allows us to only specify the offset, including
2966 * the rest of the content (from all future fragments) without specifying
2967 * an explicit duration. */
2968 if (mov->flags & FF_MOV_FLAG_FRAGMENT)
2973 avio_wb64(pb, duration);
2974 avio_wb64(pb, start_ct);
2976 avio_wb32(pb, duration);
2977 avio_wb32(pb, start_ct);
2979 avio_wb32(pb, 0x00010000);
2983 static int mov_write_tref_tag(AVIOContext *pb, MOVTrack *track)
2985 avio_wb32(pb, 20); // size
2986 ffio_wfourcc(pb, "tref");
2987 avio_wb32(pb, 12); // size (subatom)
2988 avio_wl32(pb, track->tref_tag);
2989 avio_wb32(pb, track->tref_id);
2993 // goes at the end of each track! ... Critical for PSP playback ("Incompatible data" without it)
2994 static int mov_write_uuid_tag_psp(AVIOContext *pb, MOVTrack *mov)
2996 avio_wb32(pb, 0x34); /* size ... reports as 28 in mp4box! */
2997 ffio_wfourcc(pb, "uuid");
2998 ffio_wfourcc(pb, "USMT");
2999 avio_wb32(pb, 0x21d24fce);
3000 avio_wb32(pb, 0xbb88695c);
3001 avio_wb32(pb, 0xfac9c740);
3002 avio_wb32(pb, 0x1c); // another size here!
3003 ffio_wfourcc(pb, "MTDT");
3004 avio_wb32(pb, 0x00010012);
3005 avio_wb32(pb, 0x0a);
3006 avio_wb32(pb, 0x55c40000);
3012 static int mov_write_udta_sdp(AVIOContext *pb, MOVTrack *track)
3014 AVFormatContext *ctx = track->rtp_ctx;
3015 char buf[1000] = "";
3018 ff_sdp_write_media(buf, sizeof(buf), ctx->streams[0], track->src_track,
3019 NULL, NULL, 0, 0, ctx);
3020 av_strlcatf(buf, sizeof(buf), "a=control:streamid=%d\r\n", track->track_id);
3023 avio_wb32(pb, len + 24);
3024 ffio_wfourcc(pb, "udta");
3025 avio_wb32(pb, len + 16);
3026 ffio_wfourcc(pb, "hnti");
3027 avio_wb32(pb, len + 8);
3028 ffio_wfourcc(pb, "sdp ");
3029 avio_write(pb, buf, len);
3033 static int mov_write_track_metadata(AVIOContext *pb, AVStream *st,
3034 const char *tag, const char *str)
3036 int64_t pos = avio_tell(pb);
3037 AVDictionaryEntry *t = av_dict_get(st->metadata, str, NULL, 0);
3038 if (!t || !utf8len(t->value))
3041 avio_wb32(pb, 0); /* size */
3042 ffio_wfourcc(pb, tag); /* type */
3043 avio_write(pb, t->value, strlen(t->value)); /* UTF8 string value */
3044 return update_size(pb, pos);
3047 static int mov_write_track_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
3050 AVIOContext *pb_buf;
3057 ret = avio_open_dyn_buf(&pb_buf);
3061 if (mov->mode & (MODE_MP4|MODE_MOV))
3062 mov_write_track_metadata(pb_buf, st, "name", "title");
3064 if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) {
3065 avio_wb32(pb, size + 8);
3066 ffio_wfourcc(pb, "udta");
3067 avio_write(pb, buf, size);
3074 static int mov_write_trak_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov,
3075 MOVTrack *track, AVStream *st)
3077 int64_t pos = avio_tell(pb);
3078 int entry_backup = track->entry;
3079 int chunk_backup = track->chunkCount;
3082 /* If we want to have an empty moov, but some samples already have been
3083 * buffered (delay_moov), pretend that no samples have been written yet. */
3084 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV)
3085 track->chunkCount = track->entry = 0;
3087 avio_wb32(pb, 0); /* size */
3088 ffio_wfourcc(pb, "trak");
3089 mov_write_tkhd_tag(pb, mov, track, st);
3091 av_assert2(mov->use_editlist >= 0);
3093 if (track->start_dts != AV_NOPTS_VALUE) {
3094 if (mov->use_editlist)
3095 mov_write_edts_tag(pb, mov, track); // PSP Movies and several other cases require edts box
3096 else if ((track->entry && track->cluster[0].dts) || track->mode == MODE_PSP || is_clcp_track(track))
3097 av_log(mov->fc, AV_LOG_WARNING,
3098 "Not writing any edit list even though one would have been required\n");
3101 if (track->tref_tag)
3102 mov_write_tref_tag(pb, track);
3104 if ((ret = mov_write_mdia_tag(s, pb, mov, track)) < 0)
3106 if (track->mode == MODE_PSP)
3107 mov_write_uuid_tag_psp(pb, track); // PSP Movies require this uuid box
3108 if (track->tag == MKTAG('r','t','p',' '))
3109 mov_write_udta_sdp(pb, track);
3110 if (track->mode == MODE_MOV) {
3111 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
3112 double sample_aspect_ratio = av_q2d(st->sample_aspect_ratio);
3113 if (st->sample_aspect_ratio.num && 1.0 != sample_aspect_ratio) {
3114 mov_write_tapt_tag(pb, track);
3117 if (is_clcp_track(track) && st->sample_aspect_ratio.num) {
3118 mov_write_tapt_tag(pb, track);
3121 mov_write_track_udta_tag(pb, mov, st);
3122 track->entry = entry_backup;
3123 track->chunkCount = chunk_backup;
3124 return update_size(pb, pos);
3127 static int mov_write_iods_tag(AVIOContext *pb, MOVMuxContext *mov)
3129 int i, has_audio = 0, has_video = 0;
3130 int64_t pos = avio_tell(pb);
3131 int audio_profile = mov->iods_audio_profile;
3132 int video_profile = mov->iods_video_profile;
3133 for (i = 0; i < mov->nb_streams; i++) {
3134 if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
3135 has_audio |= mov->tracks[i].par->codec_type == AVMEDIA_TYPE_AUDIO;
3136 has_video |= mov->tracks[i].par->codec_type == AVMEDIA_TYPE_VIDEO;
3139 if (audio_profile < 0)
3140 audio_profile = 0xFF - has_audio;
3141 if (video_profile < 0)
3142 video_profile = 0xFF - has_video;
3143 avio_wb32(pb, 0x0); /* size */
3144 ffio_wfourcc(pb, "iods");
3145 avio_wb32(pb, 0); /* version & flags */
3146 put_descr(pb, 0x10, 7);
3147 avio_wb16(pb, 0x004f);
3150 avio_w8(pb, audio_profile);
3151 avio_w8(pb, video_profile);
3153 return update_size(pb, pos);
3156 static int mov_write_trex_tag(AVIOContext *pb, MOVTrack *track)
3158 avio_wb32(pb, 0x20); /* size */
3159 ffio_wfourcc(pb, "trex");
3160 avio_wb32(pb, 0); /* version & flags */
3161 avio_wb32(pb, track->track_id); /* track ID */
3162 avio_wb32(pb, 1); /* default sample description index */
3163 avio_wb32(pb, 0); /* default sample duration */
3164 avio_wb32(pb, 0); /* default sample size */
3165 avio_wb32(pb, 0); /* default sample flags */
3169 static int mov_write_mvex_tag(AVIOContext *pb, MOVMuxContext *mov)
3171 int64_t pos = avio_tell(pb);
3173 avio_wb32(pb, 0x0); /* size */
3174 ffio_wfourcc(pb, "mvex");
3175 for (i = 0; i < mov->nb_streams; i++)
3176 mov_write_trex_tag(pb, &mov->tracks[i]);
3177 return update_size(pb, pos);
3180 static int mov_write_mvhd_tag(AVIOContext *pb, MOVMuxContext *mov)
3182 int max_track_id = 1, i;
3183 int64_t max_track_len = 0;
3186 for (i = 0; i < mov->nb_streams; i++) {
3187 if (mov->tracks[i].entry > 0 && mov->tracks[i].timescale) {
3188 int64_t max_track_len_temp = av_rescale_rnd(mov->tracks[i].track_duration,
3190 mov->tracks[i].timescale,
3192 if (max_track_len < max_track_len_temp)
3193 max_track_len = max_track_len_temp;
3194 if (max_track_id < mov->tracks[i].track_id)
3195 max_track_id = mov->tracks[i].track_id;
3198 /* If using delay_moov, make sure the output is the same as if no
3199 * samples had been written yet. */
3200 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
3205 version = max_track_len < UINT32_MAX ? 0 : 1;
3206 avio_wb32(pb, version == 1 ? 120 : 108); /* size */
3208 ffio_wfourcc(pb, "mvhd");
3209 avio_w8(pb, version);
3210 avio_wb24(pb, 0); /* flags */
3212 avio_wb64(pb, mov->time);
3213 avio_wb64(pb, mov->time);
3215 avio_wb32(pb, mov->time); /* creation time */
3216 avio_wb32(pb, mov->time); /* modification time */
3218 avio_wb32(pb, MOV_TIMESCALE);
3219 (version == 1) ? avio_wb64(pb, max_track_len) : avio_wb32(pb, max_track_len); /* duration of longest track */
3221 avio_wb32(pb, 0x00010000); /* reserved (preferred rate) 1.0 = normal */
3222 avio_wb16(pb, 0x0100); /* reserved (preferred volume) 1.0 = normal */
3223 avio_wb16(pb, 0); /* reserved */
3224 avio_wb32(pb, 0); /* reserved */
3225 avio_wb32(pb, 0); /* reserved */
3227 /* Matrix structure */
3228 write_matrix(pb, 1, 0, 0, 1, 0, 0);
3230 avio_wb32(pb, 0); /* reserved (preview time) */
3231 avio_wb32(pb, 0); /* reserved (preview duration) */
3232 avio_wb32(pb, 0); /* reserved (poster time) */
3233 avio_wb32(pb, 0); /* reserved (selection time) */
3234 avio_wb32(pb, 0); /* reserved (selection duration) */
3235 avio_wb32(pb, 0); /* reserved (current time) */
3236 avio_wb32(pb, max_track_id + 1); /* Next track id */
3240 static int mov_write_itunes_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov,
3243 avio_wb32(pb, 33); /* size */
3244 ffio_wfourcc(pb, "hdlr");
3247 ffio_wfourcc(pb, "mdir");
3248 ffio_wfourcc(pb, "appl");
3255 /* helper function to write a data tag with the specified string as data */
3256 static int mov_write_string_data_tag(AVIOContext *pb, const char *data, int lang, int long_style)
3259 int size = 16 + strlen(data);
3260 avio_wb32(pb, size); /* size */
3261 ffio_wfourcc(pb, "data");
3264 avio_write(pb, data, strlen(data));
3268 lang = ff_mov_iso639_to_lang("und", 1);
3269 avio_wb16(pb, strlen(data)); /* string length */
3270 avio_wb16(pb, lang);
3271 avio_write(pb, data, strlen(data));
3272 return strlen(data) + 4;
3276 static int mov_write_string_tag(AVIOContext *pb, const char *name,
3277 const char *value, int lang, int long_style)
3280 if (value && value[0]) {
3281 int64_t pos = avio_tell(pb);
3282 avio_wb32(pb, 0); /* size */
3283 ffio_wfourcc(pb, name);
3284 mov_write_string_data_tag(pb, value, lang, long_style);
3285 size = update_size(pb, pos);
3290 static AVDictionaryEntry *get_metadata_lang(AVFormatContext *s,
3291 const char *tag, int *lang)
3294 AVDictionaryEntry *t, *t2 = NULL;
3299 if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
3302 len = strlen(t->key);
3303 snprintf(tag2, sizeof(tag2), "%s-", tag);
3304 while ((t2 = av_dict_get(s->metadata, tag2, t2, AV_DICT_IGNORE_SUFFIX))) {
3305 len2 = strlen(t2->key);
3306 if (len2 == len + 4 && !strcmp(t->value, t2->value)
3307 && (l = ff_mov_iso639_to_lang(&t2->key[len2 - 3], 1)) >= 0) {
3315 static int mov_write_string_metadata(AVFormatContext *s, AVIOContext *pb,
3316 const char *name, const char *tag,
3320 AVDictionaryEntry *t = get_metadata_lang(s, tag, &lang);
3323 return mov_write_string_tag(pb, name, t->value, lang, long_style);
3326 /* iTunes bpm number */
3327 static int mov_write_tmpo_tag(AVIOContext *pb, AVFormatContext *s)
3329 AVDictionaryEntry *t = av_dict_get(s->metadata, "tmpo", NULL, 0);
3330 int size = 0, tmpo = t ? atoi(t->value) : 0;
3333 avio_wb32(pb, size);
3334 ffio_wfourcc(pb, "tmpo");
3335 avio_wb32(pb, size-8); /* size */
3336 ffio_wfourcc(pb, "data");
3337 avio_wb32(pb, 0x15); //type specifier
3339 avio_wb16(pb, tmpo); // data
3344 /* 3GPP TS 26.244 */
3345 static int mov_write_loci_tag(AVFormatContext *s, AVIOContext *pb)
3348 int64_t pos = avio_tell(pb);
3349 double latitude, longitude, altitude;
3350 int32_t latitude_fix, longitude_fix, altitude_fix;
3351 AVDictionaryEntry *t = get_metadata_lang(s, "location", &lang);
3352 const char *ptr, *place = "";
3354 static const char *astronomical_body = "earth";
3359 longitude = strtod(ptr, &end);
3361 av_log(s, AV_LOG_WARNING, "malformed location metadata\n");
3365 latitude = strtod(ptr, &end);
3367 av_log(s, AV_LOG_WARNING, "malformed location metadata\n");
3371 altitude = strtod(ptr, &end);
3372 /* If no altitude was present, the default 0 should be fine */
3376 latitude_fix = (int32_t) ((1 << 16) * latitude);
3377 longitude_fix = (int32_t) ((1 << 16) * longitude);
3378 altitude_fix = (int32_t) ((1 << 16) * altitude);
3380 avio_wb32(pb, 0); /* size */
3381 ffio_wfourcc(pb, "loci"); /* type */
3382 avio_wb32(pb, 0); /* version + flags */
3383 avio_wb16(pb, lang);
3384 avio_write(pb, place, strlen(place) + 1);
3385 avio_w8(pb, 0); /* role of place (0 == shooting location, 1 == real location, 2 == fictional location) */
3386 avio_wb32(pb, latitude_fix);
3387 avio_wb32(pb, longitude_fix);
3388 avio_wb32(pb, altitude_fix);
3389 avio_write(pb, astronomical_body, strlen(astronomical_body) + 1);
3390 avio_w8(pb, 0); /* additional notes, null terminated string */
3392 return update_size(pb, pos);
3395 /* iTunes track or disc number */
3396 static int mov_write_trkn_tag(AVIOContext *pb, MOVMuxContext *mov,
3397 AVFormatContext *s, int disc)
3399 AVDictionaryEntry *t = av_dict_get(s->metadata,
3400 disc ? "disc" : "track",
3402 int size = 0, track = t ? atoi(t->value) : 0;
3405 char *slash = strchr(t->value, '/');
3407 tracks = atoi(slash + 1);
3408 avio_wb32(pb, 32); /* size */
3409 ffio_wfourcc(pb, disc ? "disk" : "trkn");
3410 avio_wb32(pb, 24); /* size */
3411 ffio_wfourcc(pb, "data");
3412 avio_wb32(pb, 0); // 8 bytes empty
3414 avio_wb16(pb, 0); // empty
3415 avio_wb16(pb, track); // track / disc number
3416 avio_wb16(pb, tracks); // total track / disc number
3417 avio_wb16(pb, 0); // empty
3423 static int mov_write_int8_metadata(AVFormatContext *s, AVIOContext *pb,
3424 const char *name, const char *tag,
3427 AVDictionaryEntry *t = NULL;
3429 int size = 24 + len;
3431 if (len != 1 && len != 4)
3434 if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
3436 num = atoi(t->value);
3438 avio_wb32(pb, size);
3439 ffio_wfourcc(pb, name);
3440 avio_wb32(pb, size - 8);
3441 ffio_wfourcc(pb, "data");
3442 avio_wb32(pb, 0x15);
3444 if (len==4) avio_wb32(pb, num);
3445 else avio_w8 (pb, num);
3450 static int mov_write_covr(AVIOContext *pb, AVFormatContext *s)
3452 MOVMuxContext *mov = s->priv_data;
3456 for (i = 0; i < s->nb_streams; i++) {
3457 MOVTrack *trk = &mov->tracks[i];
3459 if (!is_cover_image(trk->st) || trk->cover_image.size <= 0)
3463 pos = avio_tell(pb);
3465 ffio_wfourcc(pb, "covr");
3467 avio_wb32(pb, 16 + trk->cover_image.size);
3468 ffio_wfourcc(pb, "data");
3469 avio_wb32(pb, trk->tag);
3471 avio_write(pb, trk->cover_image.data, trk->cover_image.size);
3474 return pos ? update_size(pb, pos) : 0;
3477 /* iTunes meta data list */
3478 static int mov_write_ilst_tag(AVIOContext *pb, MOVMuxContext *mov,
3481 int64_t pos = avio_tell(pb);
3482 avio_wb32(pb, 0); /* size */
3483 ffio_wfourcc(pb, "ilst");
3484 mov_write_string_metadata(s, pb, "\251nam", "title" , 1);
3485 mov_write_string_metadata(s, pb, "\251ART", "artist" , 1);
3486 mov_write_string_metadata(s, pb, "aART", "album_artist", 1);
3487 mov_write_string_metadata(s, pb, "\251wrt", "composer" , 1);
3488 mov_write_string_metadata(s, pb, "\251alb", "album" , 1);
3489 mov_write_string_metadata(s, pb, "\251day", "date" , 1);
3490 if (!mov_write_string_metadata(s, pb, "\251too", "encoding_tool", 1)) {
3491 if (!(s->flags & AVFMT_FLAG_BITEXACT))
3492 mov_write_string_tag(pb, "\251too", LIBAVFORMAT_IDENT, 0, 1);
3494 mov_write_string_metadata(s, pb, "\251cmt", "comment" , 1);
3495 mov_write_string_metadata(s, pb, "\251gen", "genre" , 1);
3496 mov_write_string_metadata(s, pb, "cprt", "copyright", 1);
3497 mov_write_string_metadata(s, pb, "\251grp", "grouping" , 1);
3498 mov_write_string_metadata(s, pb, "\251lyr", "lyrics" , 1);
3499 mov_write_string_metadata(s, pb, "desc", "description",1);
3500 mov_write_string_metadata(s, pb, "ldes", "synopsis" , 1);
3501 mov_write_string_metadata(s, pb, "tvsh", "show" , 1);
3502 mov_write_string_metadata(s, pb, "tven", "episode_id",1);
3503 mov_write_string_metadata(s, pb, "tvnn", "network" , 1);
3504 mov_write_string_metadata(s, pb, "keyw", "keywords" , 1);
3505 mov_write_int8_metadata (s, pb, "tves", "episode_sort",4);
3506 mov_write_int8_metadata (s, pb, "tvsn", "season_number",4);
3507 mov_write_int8_metadata (s, pb, "stik", "media_type",1);
3508 mov_write_int8_metadata (s, pb, "hdvd", "hd_video", 1);
3509 mov_write_int8_metadata (s, pb, "pgap", "gapless_playback",1);
3510 mov_write_int8_metadata (s, pb, "cpil", "compilation", 1);
3511 mov_write_covr(pb, s);
3512 mov_write_trkn_tag(pb, mov, s, 0); // track number
3513 mov_write_trkn_tag(pb, mov, s, 1); // disc number
3514 mov_write_tmpo_tag(pb, s);
3515 return update_size(pb, pos);
3518 static int mov_write_mdta_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov,
3521 avio_wb32(pb, 33); /* size */
3522 ffio_wfourcc(pb, "hdlr");
3525 ffio_wfourcc(pb, "mdta");
3533 static int mov_write_mdta_keys_tag(AVIOContext *pb, MOVMuxContext *mov,
3536 AVDictionaryEntry *t = NULL;
3537 int64_t pos = avio_tell(pb);
3538 int64_t curpos, entry_pos;
3541 avio_wb32(pb, 0); /* size */
3542 ffio_wfourcc(pb, "keys");
3544 entry_pos = avio_tell(pb);
3545 avio_wb32(pb, 0); /* entry count */
3547 while (t = av_dict_get(s->metadata, "", t, AV_DICT_IGNORE_SUFFIX)) {
3548 avio_wb32(pb, strlen(t->key) + 8);
3549 ffio_wfourcc(pb, "mdta");
3550 avio_write(pb, t->key, strlen(t->key));
3553 curpos = avio_tell(pb);
3554 avio_seek(pb, entry_pos, SEEK_SET);
3555 avio_wb32(pb, count); // rewrite entry count
3556 avio_seek(pb, curpos, SEEK_SET);
3558 return update_size(pb, pos);
3561 static int mov_write_mdta_ilst_tag(AVIOContext *pb, MOVMuxContext *mov,
3564 AVDictionaryEntry *t = NULL;
3565 int64_t pos = avio_tell(pb);
3566 int count = 1; /* keys are 1-index based */
3568 avio_wb32(pb, 0); /* size */
3569 ffio_wfourcc(pb, "ilst");
3571 while (t = av_dict_get(s->metadata, "", t, AV_DICT_IGNORE_SUFFIX)) {
3572 int64_t entry_pos = avio_tell(pb);
3573 avio_wb32(pb, 0); /* size */
3574 avio_wb32(pb, count); /* key */
3575 mov_write_string_data_tag(pb, t->value, 0, 1);
3576 update_size(pb, entry_pos);
3579 return update_size(pb, pos);
3582 /* meta data tags */
3583 static int mov_write_meta_tag(AVIOContext *pb, MOVMuxContext *mov,
3587 int64_t pos = avio_tell(pb);
3588 avio_wb32(pb, 0); /* size */
3589 ffio_wfourcc(pb, "meta");
3591 if (mov->flags & FF_MOV_FLAG_USE_MDTA) {
3592 mov_write_mdta_hdlr_tag(pb, mov, s);
3593 mov_write_mdta_keys_tag(pb, mov, s);
3594 mov_write_mdta_ilst_tag(pb, mov, s);
3597 /* iTunes metadata tag */
3598 mov_write_itunes_hdlr_tag(pb, mov, s);
3599 mov_write_ilst_tag(pb, mov, s);
3601 size = update_size(pb, pos);
3605 static int mov_write_raw_metadata_tag(AVFormatContext *s, AVIOContext *pb,
3606 const char *name, const char *key)
3609 AVDictionaryEntry *t;
3611 if (!(t = av_dict_get(s->metadata, key, NULL, 0)))
3614 len = strlen(t->value);
3617 avio_wb32(pb, size);
3618 ffio_wfourcc(pb, name);
3619 avio_write(pb, t->value, len);
3625 static int ascii_to_wc(AVIOContext *pb, const uint8_t *b)
3629 GET_UTF8(val, *b++, return -1;)
3632 avio_wb16(pb, 0x00);
3636 static uint16_t language_code(const char *str)
3638 return (((str[0] - 0x60) & 0x1F) << 10) +
3639 (((str[1] - 0x60) & 0x1F) << 5) +
3640 (( str[2] - 0x60) & 0x1F);
3643 static int mov_write_3gp_udta_tag(AVIOContext *pb, AVFormatContext *s,
3644 const char *tag, const char *str)
3646 int64_t pos = avio_tell(pb);
3647 AVDictionaryEntry *t = av_dict_get(s->metadata, str, NULL, 0);
3648 if (!t || !utf8len(t->value))
3650 avio_wb32(pb, 0); /* size */
3651 ffio_wfourcc(pb, tag); /* type */
3652 avio_wb32(pb, 0); /* version + flags */
3653 if (!strcmp(tag, "yrrc"))
3654 avio_wb16(pb, atoi(t->value));
3656 avio_wb16(pb, language_code("eng")); /* language */
3657 avio_write(pb, t->value, strlen(t->value) + 1); /* UTF8 string value */
3658 if (!strcmp(tag, "albm") &&
3659 (t = av_dict_get(s->metadata, "track", NULL, 0)))
3660 avio_w8(pb, atoi(t->value));
3662 return update_size(pb, pos);
3665 static int mov_write_chpl_tag(AVIOContext *pb, AVFormatContext *s)
3667 int64_t pos = avio_tell(pb);
3668 int i, nb_chapters = FFMIN(s->nb_chapters, 255);
3670 avio_wb32(pb, 0); // size
3671 ffio_wfourcc(pb, "chpl");
3672 avio_wb32(pb, 0x01000000); // version + flags
3673 avio_wb32(pb, 0); // unknown
3674 avio_w8(pb, nb_chapters);
3676 for (i = 0; i < nb_chapters; i++) {
3677 AVChapter *c = s->chapters[i];
3678 AVDictionaryEntry *t;
3679 avio_wb64(pb, av_rescale_q(c->start, c->time_base, (AVRational){1,10000000}));
3681 if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
3682 int len = FFMIN(strlen(t->value), 255);
3684 avio_write(pb, t->value, len);
3688 return update_size(pb, pos);
3691 static int mov_write_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
3694 AVIOContext *pb_buf;
3698 ret = avio_open_dyn_buf(&pb_buf);
3702 if (mov->mode & MODE_3GP) {
3703 mov_write_3gp_udta_tag(pb_buf, s, "perf", "artist");
3704 mov_write_3gp_udta_tag(pb_buf, s, "titl", "title");
3705 mov_write_3gp_udta_tag(pb_buf, s, "auth", "author");
3706 mov_write_3gp_udta_tag(pb_buf, s, "gnre", "genre");
3707 mov_write_3gp_udta_tag(pb_buf, s, "dscp", "comment");
3708 mov_write_3gp_udta_tag(pb_buf, s, "albm", "album");
3709 mov_write_3gp_udta_tag(pb_buf, s, "cprt", "copyright");
3710 mov_write_3gp_udta_tag(pb_buf, s, "yrrc", "date");
3711 mov_write_loci_tag(s, pb_buf);
3712 } 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
3713 mov_write_string_metadata(s, pb_buf, "\251ART", "artist", 0);
3714 mov_write_string_metadata(s, pb_buf, "\251nam", "title", 0);
3715 mov_write_string_metadata(s, pb_buf, "\251aut", "author", 0);
3716 mov_write_string_metadata(s, pb_buf, "\251alb", "album", 0);
3717 mov_write_string_metadata(s, pb_buf, "\251day", "date", 0);
3718 mov_write_string_metadata(s, pb_buf, "\251swr", "encoder", 0);
3719 // currently ignored by mov.c
3720 mov_write_string_metadata(s, pb_buf, "\251des", "comment", 0);
3721 // add support for libquicktime, this atom is also actually read by mov.c
3722 mov_write_string_metadata(s, pb_buf, "\251cmt", "comment", 0);
3723 mov_write_string_metadata(s, pb_buf, "\251gen", "genre", 0);
3724 mov_write_string_metadata(s, pb_buf, "\251cpy", "copyright", 0);
3725 mov_write_string_metadata(s, pb_buf, "\251mak", "make", 0);
3726 mov_write_string_metadata(s, pb_buf, "\251mod", "model", 0);
3727 mov_write_string_metadata(s, pb_buf, "\251xyz", "location", 0);
3728 mov_write_string_metadata(s, pb_buf, "\251key", "keywords", 0);
3729 mov_write_raw_metadata_tag(s, pb_buf, "XMP_", "xmp");
3731 /* iTunes meta data */
3732 mov_write_meta_tag(pb_buf, mov, s);
3733 mov_write_loci_tag(s, pb_buf);
3736 if (s->nb_chapters && !(mov->flags & FF_MOV_FLAG_DISABLE_CHPL))
3737 mov_write_chpl_tag(pb_buf, s);
3739 if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) {
3740 avio_wb32(pb, size + 8);
3741 ffio_wfourcc(pb, "udta");
3742 avio_write(pb, buf, size);
3749 static void mov_write_psp_udta_tag(AVIOContext *pb,
3750 const char *str, const char *lang, int type)
3752 int len = utf8len(str) + 1;
3755 avio_wb16(pb, len * 2 + 10); /* size */
3756 avio_wb32(pb, type); /* type */
3757 avio_wb16(pb, language_code(lang)); /* language */
3758 avio_wb16(pb, 0x01); /* ? */
3759 ascii_to_wc(pb, str);
3762 static int mov_write_uuidusmt_tag(AVIOContext *pb, AVFormatContext *s)
3764 AVDictionaryEntry *title = av_dict_get(s->metadata, "title", NULL, 0);
3768 pos = avio_tell(pb);
3769 avio_wb32(pb, 0); /* size placeholder*/
3770 ffio_wfourcc(pb, "uuid");
3771 ffio_wfourcc(pb, "USMT");
3772 avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
3773 avio_wb32(pb, 0xbb88695c);
3774 avio_wb32(pb, 0xfac9c740);
3776 pos2 = avio_tell(pb);
3777 avio_wb32(pb, 0); /* size placeholder*/
3778 ffio_wfourcc(pb, "MTDT");
3782 avio_wb16(pb, 0x0C); /* size */
3783 avio_wb32(pb, 0x0B); /* type */
3784 avio_wb16(pb, language_code("und")); /* language */
3785 avio_wb16(pb, 0x0); /* ? */
3786 avio_wb16(pb, 0x021C); /* data */
3788 if (!(s->flags & AVFMT_FLAG_BITEXACT))
3789 mov_write_psp_udta_tag(pb, LIBAVCODEC_IDENT, "eng", 0x04);
3790 mov_write_psp_udta_tag(pb, title->value, "eng", 0x01);
3791 mov_write_psp_udta_tag(pb, "2006/04/01 11:11:11", "und", 0x03);
3793 update_size(pb, pos2);
3794 return update_size(pb, pos);
3800 static void build_chunks(MOVTrack *trk)
3803 MOVIentry *chunk = &trk->cluster[0];
3804 uint64_t chunkSize = chunk->size;
3805 chunk->chunkNum = 1;
3806 if (trk->chunkCount)
3808 trk->chunkCount = 1;
3809 for (i = 1; i<trk->entry; i++){
3810 if (chunk->pos + chunkSize == trk->cluster[i].pos &&
3811 chunkSize + trk->cluster[i].size < (1<<20)){
3812 chunkSize += trk->cluster[i].size;
3813 chunk->samples_in_chunk += trk->cluster[i].entries;
3815 trk->cluster[i].chunkNum = chunk->chunkNum+1;
3816 chunk=&trk->cluster[i];
3817 chunkSize = chunk->size;
3824 * Assign track ids. If option "use_stream_ids_as_track_ids" is set,
3825 * the stream ids are used as track ids.
3827 * This assumes mov->tracks and s->streams are in the same order and
3828 * there are no gaps in either of them (so mov->tracks[n] refers to
3831 * As an exception, there can be more entries in
3832 * s->streams than in mov->tracks, in which case new track ids are
3833 * generated (starting after the largest found stream id).
3835 static int mov_setup_track_ids(MOVMuxContext *mov, AVFormatContext *s)
3839 if (mov->track_ids_ok)
3842 if (mov->use_stream_ids_as_track_ids) {
3843 int next_generated_track_id = 0;
3844 for (i = 0; i < s->nb_streams; i++) {
3845 if (s->streams[i]->id > next_generated_track_id)
3846 next_generated_track_id = s->streams[i]->id;
3849 for (i = 0; i < mov->nb_streams; i++) {
3850 if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
3853 mov->tracks[i].track_id = i >= s->nb_streams ? ++next_generated_track_id : s->streams[i]->id;
3856 for (i = 0; i < mov->nb_streams; i++) {
3857 if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
3860 mov->tracks[i].track_id = i + 1;
3864 mov->track_ids_ok = 1;
3869 static int mov_write_moov_tag(AVIOContext *pb, MOVMuxContext *mov,
3873 int64_t pos = avio_tell(pb);
3874 avio_wb32(pb, 0); /* size placeholder*/
3875 ffio_wfourcc(pb, "moov");
3877 mov_setup_track_ids(mov, s);
3879 for (i = 0; i < mov->nb_streams; i++) {
3880 if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
3883 mov->tracks[i].time = mov->time;
3885 if (mov->tracks[i].entry)
3886 build_chunks(&mov->tracks[i]);
3889 if (mov->chapter_track)
3890 for (i = 0; i < s->nb_streams; i++) {
3891 mov->tracks[i].tref_tag = MKTAG('c','h','a','p');
3892 mov->tracks[i].tref_id = mov->tracks[mov->chapter_track].track_id;
3894 for (i = 0; i < mov->nb_streams; i++) {
3895 MOVTrack *track = &mov->tracks[i];
3896 if (track->tag == MKTAG('r','t','p',' ')) {
3897 track->tref_tag = MKTAG('h','i','n','t');
3898 track->tref_id = mov->tracks[track->src_track].track_id;
3899 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
3900 int * fallback, size;
3901 fallback = (int*)av_stream_get_side_data(track->st,
3902 AV_PKT_DATA_FALLBACK_TRACK,
3904 if (fallback != NULL && size == sizeof(int)) {
3905 if (*fallback >= 0 && *fallback < mov->nb_streams) {
3906 track->tref_tag = MKTAG('f','a','l','l');
3907 track->tref_id = mov->tracks[*fallback].track_id;
3912 for (i = 0; i < mov->nb_streams; i++) {
3913 if (mov->tracks[i].tag == MKTAG('t','m','c','d')) {
3914 int src_trk = mov->tracks[i].src_track;
3915 mov->tracks[src_trk].tref_tag = mov->tracks[i].tag;
3916 mov->tracks[src_trk].tref_id = mov->tracks[i].track_id;
3917 //src_trk may have a different timescale than the tmcd track
3918 mov->tracks[i].track_duration = av_rescale(mov->tracks[src_trk].track_duration,
3919 mov->tracks[i].timescale,
3920 mov->tracks[src_trk].timescale);
3924 mov_write_mvhd_tag(pb, mov);
3925 if (mov->mode != MODE_MOV && !mov->iods_skip)
3926 mov_write_iods_tag(pb, mov);
3927 for (i = 0; i < mov->nb_streams; i++) {
3928 if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_FRAGMENT) {
3929 int ret = mov_write_trak_tag(s, pb, mov, &(mov->tracks[i]), i < s->nb_streams ? s->streams[i] : NULL);
3934 if (mov->flags & FF_MOV_FLAG_FRAGMENT)
3935 mov_write_mvex_tag(pb, mov); /* QuickTime requires trak to precede this */
3937 if (mov->mode == MODE_PSP)
3938 mov_write_uuidusmt_tag(pb, s);
3940 mov_write_udta_tag(pb, mov, s);
3942 return update_size(pb, pos);
3945 static void param_write_int(AVIOContext *pb, const char *name, int value)
3947 avio_printf(pb, "<param name=\"%s\" value=\"%d\" valuetype=\"data\"/>\n", name, value);
3950 static void param_write_string(AVIOContext *pb, const char *name, const char *value)
3952 avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, value);
3955 static void param_write_hex(AVIOContext *pb, const char *name, const uint8_t *value, int len)
3958 len = FFMIN(sizeof(buf) / 2 - 1, len);
3959 ff_data_to_hex(buf, value, len, 0);
3960 buf[2 * len] = '\0';
3961 avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, buf);
3964 static int mov_write_isml_manifest(AVIOContext *pb, MOVMuxContext *mov, AVFormatContext *s)
3966 int64_t pos = avio_tell(pb);
3968 int64_t manifest_bit_rate = 0;
3969 AVCPBProperties *props = NULL;
3971 static const uint8_t uuid[] = {
3972 0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd,
3973 0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66
3977 ffio_wfourcc(pb, "uuid");
3978 avio_write(pb, uuid, sizeof(uuid));
3981 avio_printf(pb, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
3982 avio_printf(pb, "<smil xmlns=\"http://www.w3.org/2001/SMIL20/Language\">\n");
3983 avio_printf(pb, "<head>\n");
3984 if (!(mov->fc->flags & AVFMT_FLAG_BITEXACT))
3985 avio_printf(pb, "<meta name=\"creator\" content=\"%s\" />\n",
3987 avio_printf(pb, "</head>\n");
3988 avio_printf(pb, "<body>\n");
3989 avio_printf(pb, "<switch>\n");
3991 mov_setup_track_ids(mov, s);
3993 for (i = 0; i < mov->nb_streams; i++) {
3994 MOVTrack *track = &mov->tracks[i];
3996 int track_id = track->track_id;
3997 char track_name_buf[32] = { 0 };
3999 AVStream *st = track->st;
4000 AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0);
4002 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO && !is_cover_image(st)) {
4004 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
4010 props = (AVCPBProperties*)av_stream_get_side_data(track->st, AV_PKT_DATA_CPB_PROPERTIES, NULL);
4012 if (track->par->bit_rate) {
4013 manifest_bit_rate = track->par->bit_rate;
4015 manifest_bit_rate = props->max_bitrate;
4018 avio_printf(pb, "<%s systemBitrate=\"%"PRId64"\">\n", type,
4020 param_write_int(pb, "systemBitrate", manifest_bit_rate);
4021 param_write_int(pb, "trackID", track_id);
4022 param_write_string(pb, "systemLanguage", lang ? lang->value : "und");
4024 /* Build track name piece by piece: */
4026 av_strlcat(track_name_buf, type, sizeof(track_name_buf));
4027 /* 2. track language, if available */
4029 av_strlcatf(track_name_buf, sizeof(track_name_buf),
4030 "_%s", lang->value);
4031 /* 3. special type suffix */
4032 /* "_cc" = closed captions, "_ad" = audio_description */
4033 if (st->disposition & AV_DISPOSITION_HEARING_IMPAIRED)
4034 av_strlcat(track_name_buf, "_cc", sizeof(track_name_buf));
4035 else if (st->disposition & AV_DISPOSITION_VISUAL_IMPAIRED)
4036 av_strlcat(track_name_buf, "_ad", sizeof(track_name_buf));
4038 param_write_string(pb, "trackName", track_name_buf);
4040 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
4041 if (track->par->codec_id == AV_CODEC_ID_H264) {
4043 int size = track->par->extradata_size;
4044 if (!ff_avc_write_annexb_extradata(track->par->extradata, &ptr,
4046 param_write_hex(pb, "CodecPrivateData",
4047 ptr ? ptr : track->par->extradata,
4051 param_write_string(pb, "FourCC", "H264");
4052 } else if (track->par->codec_id == AV_CODEC_ID_VC1) {
4053 param_write_string(pb, "FourCC", "WVC1");
4054 param_write_hex(pb, "CodecPrivateData", track->par->extradata,
4055 track->par->extradata_size);
4057 param_write_int(pb, "MaxWidth", track->par->width);
4058 param_write_int(pb, "MaxHeight", track->par->height);
4059 param_write_int(pb, "DisplayWidth", track->par->width);
4060 param_write_int(pb, "DisplayHeight", track->par->height);
4062 if (track->par->codec_id == AV_CODEC_ID_AAC) {
4063 switch (track->par->profile)
4065 case FF_PROFILE_AAC_HE_V2:
4066 param_write_string(pb, "FourCC", "AACP");
4068 case FF_PROFILE_AAC_HE:
4069 param_write_string(pb, "FourCC", "AACH");
4072 param_write_string(pb, "FourCC", "AACL");
4074 } else if (track->par->codec_id == AV_CODEC_ID_WMAPRO) {
4075 param_write_string(pb, "FourCC", "WMAP");
4077 param_write_hex(pb, "CodecPrivateData", track->par->extradata,
4078 track->par->extradata_size);
4079 param_write_int(pb, "AudioTag", ff_codec_get_tag(ff_codec_wav_tags,
4080 track->par->codec_id));
4081 param_write_int(pb, "Channels", track->par->channels);
4082 param_write_int(pb, "SamplingRate", track->par->sample_rate);
4083 param_write_int(pb, "BitsPerSample", 16);
4084 param_write_int(pb, "PacketSize", track->par->block_align ?
4085 track->par->block_align : 4);
4087 avio_printf(pb, "</%s>\n", type);
4089 avio_printf(pb, "</switch>\n");
4090 avio_printf(pb, "</body>\n");
4091 avio_printf(pb, "</smil>\n");
4093 return update_size(pb, pos);
4096 static int mov_write_mfhd_tag(AVIOContext *pb, MOVMuxContext *mov)
4099 ffio_wfourcc(pb, "mfhd");
4101 avio_wb32(pb, mov->fragments);
4105 static uint32_t get_sample_flags(MOVTrack *track, MOVIentry *entry)
4107 return entry->flags & MOV_SYNC_SAMPLE ? MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO :
4108 (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC);
4111 static int mov_write_tfhd_tag(AVIOContext *pb, MOVMuxContext *mov,
4112 MOVTrack *track, int64_t moof_offset)
4114 int64_t pos = avio_tell(pb);
4115 uint32_t flags = MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
4116 MOV_TFHD_BASE_DATA_OFFSET;
4117 if (!track->entry) {
4118 flags |= MOV_TFHD_DURATION_IS_EMPTY;
4120 flags |= MOV_TFHD_DEFAULT_FLAGS;
4122 if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET)
4123 flags &= ~MOV_TFHD_BASE_DATA_OFFSET;
4124 if (mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) {
4125 flags &= ~MOV_TFHD_BASE_DATA_OFFSET;
4126 flags |= MOV_TFHD_DEFAULT_BASE_IS_MOOF;
4129 /* Don't set a default sample size, the silverlight player refuses
4130 * to play files with that set. Don't set a default sample duration,
4131 * WMP freaks out if it is set. Don't set a base data offset, PIFF
4132 * file format says it MUST NOT be set. */
4133 if (track->mode == MODE_ISM)
4134 flags &= ~(MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
4135 MOV_TFHD_BASE_DATA_OFFSET);
4137 avio_wb32(pb, 0); /* size placeholder */
4138 ffio_wfourcc(pb, "tfhd");
4139 avio_w8(pb, 0); /* version */
4140 avio_wb24(pb, flags);
4142 avio_wb32(pb, track->track_id); /* track-id */
4143 if (flags & MOV_TFHD_BASE_DATA_OFFSET)
4144 avio_wb64(pb, moof_offset);
4145 if (flags & MOV_TFHD_DEFAULT_DURATION) {
4146 track->default_duration = get_cluster_duration(track, 0);
4147 avio_wb32(pb, track->default_duration);
4149 if (flags & MOV_TFHD_DEFAULT_SIZE) {
4150 track->default_size = track->entry ? track->cluster[0].size : 1;
4151 avio_wb32(pb, track->default_size);
4153 track->default_size = -1;
4155 if (flags & MOV_TFHD_DEFAULT_FLAGS) {
4156 /* Set the default flags based on the second sample, if available.
4157 * If the first sample is different, that can be signaled via a separate field. */
4158 if (track->entry > 1)
4159 track->default_sample_flags = get_sample_flags(track, &track->cluster[1]);
4161 track->default_sample_flags =
4162 track->par->codec_type == AVMEDIA_TYPE_VIDEO ?
4163 (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC) :
4164 MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO;
4165 avio_wb32(pb, track->default_sample_flags);
4168 return update_size(pb, pos);
4171 static int mov_write_trun_tag(AVIOContext *pb, MOVMuxContext *mov,
4172 MOVTrack *track, int moof_size,
4175 int64_t pos = avio_tell(pb);
4176 uint32_t flags = MOV_TRUN_DATA_OFFSET;
4179 for (i = first; i < end; i++) {
4180 if (get_cluster_duration(track, i) != track->default_duration)
4181 flags |= MOV_TRUN_SAMPLE_DURATION;
4182 if (track->cluster[i].size != track->default_size)
4183 flags |= MOV_TRUN_SAMPLE_SIZE;
4184 if (i > first && get_sample_flags(track, &track->cluster[i]) != track->default_sample_flags)
4185 flags |= MOV_TRUN_SAMPLE_FLAGS;
4187 if (!(flags & MOV_TRUN_SAMPLE_FLAGS) && track->entry > 0 &&
4188 get_sample_flags(track, &track->cluster[0]) != track->default_sample_flags)
4189 flags |= MOV_TRUN_FIRST_SAMPLE_FLAGS;
4190 if (track->flags & MOV_TRACK_CTTS)
4191 flags |= MOV_TRUN_SAMPLE_CTS;
4193 avio_wb32(pb, 0); /* size placeholder */
4194 ffio_wfourcc(pb, "trun");
4195 if (mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS)
4196 avio_w8(pb, 1); /* version */
4198 avio_w8(pb, 0); /* version */
4199 avio_wb24(pb, flags);
4201 avio_wb32(pb, end - first); /* sample count */
4202 if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET &&
4203 !(mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) &&
4205 avio_wb32(pb, 0); /* Later tracks follow immediately after the previous one */
4207 avio_wb32(pb, moof_size + 8 + track->data_offset +
4208 track->cluster[first].pos); /* data offset */
4209 if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS)
4210 avio_wb32(pb, get_sample_flags(track, &track->cluster[first]));
4212 for (i = first; i < end; i++) {
4213 if (flags & MOV_TRUN_SAMPLE_DURATION)
4214 avio_wb32(pb, get_cluster_duration(track, i));
4215 if (flags & MOV_TRUN_SAMPLE_SIZE)
4216 avio_wb32(pb, track->cluster[i].size);
4217 if (flags & MOV_TRUN_SAMPLE_FLAGS)
4218 avio_wb32(pb, get_sample_flags(track, &track->cluster[i]));
4219 if (flags & MOV_TRUN_SAMPLE_CTS)
4220 avio_wb32(pb, track->cluster[i].cts);
4223 mov->first_trun = 0;
4224 return update_size(pb, pos);
4227 static int mov_write_tfxd_tag(AVIOContext *pb, MOVTrack *track)
4229 int64_t pos = avio_tell(pb);
4230 static const uint8_t uuid[] = {
4231 0x6d, 0x1d, 0x9b, 0x05, 0x42, 0xd5, 0x44, 0xe6,
4232 0x80, 0xe2, 0x14, 0x1d, 0xaf, 0xf7, 0x57, 0xb2
4235 avio_wb32(pb, 0); /* size placeholder */
4236 ffio_wfourcc(pb, "uuid");
4237 avio_write(pb, uuid, sizeof(uuid));
4240 avio_wb64(pb, track->start_dts + track->frag_start +
4241 track->cluster[0].cts);
4242 avio_wb64(pb, track->end_pts -
4243 (track->cluster[0].dts + track->cluster[0].cts));
4245 return update_size(pb, pos);
4248 static int mov_write_tfrf_tag(AVIOContext *pb, MOVMuxContext *mov,
4249 MOVTrack *track, int entry)
4251 int n = track->nb_frag_info - 1 - entry, i;
4252 int size = 8 + 16 + 4 + 1 + 16*n;
4253 static const uint8_t uuid[] = {
4254 0xd4, 0x80, 0x7e, 0xf2, 0xca, 0x39, 0x46, 0x95,
4255 0x8e, 0x54, 0x26, 0xcb, 0x9e, 0x46, 0xa7, 0x9f
4261 avio_seek(pb, track->frag_info[entry].tfrf_offset, SEEK_SET);
4262 avio_wb32(pb, size);
4263 ffio_wfourcc(pb, "uuid");
4264 avio_write(pb, uuid, sizeof(uuid));
4268 for (i = 0; i < n; i++) {
4269 int index = entry + 1 + i;
4270 avio_wb64(pb, track->frag_info[index].time);
4271 avio_wb64(pb, track->frag_info[index].duration);
4273 if (n < mov->ism_lookahead) {
4274 int free_size = 16 * (mov->ism_lookahead - n);
4275 avio_wb32(pb, free_size);
4276 ffio_wfourcc(pb, "free");
4277 ffio_fill(pb, 0, free_size - 8);
4283 static int mov_write_tfrf_tags(AVIOContext *pb, MOVMuxContext *mov,
4286 int64_t pos = avio_tell(pb);
4288 for (i = 0; i < mov->ism_lookahead; i++) {
4289 /* Update the tfrf tag for the last ism_lookahead fragments,
4290 * nb_frag_info - 1 is the next fragment to be written. */
4291 mov_write_tfrf_tag(pb, mov, track, track->nb_frag_info - 2 - i);
4293 avio_seek(pb, pos, SEEK_SET);
4297 static int mov_add_tfra_entries(AVIOContext *pb, MOVMuxContext *mov, int tracks,
4301 for (i = 0; i < mov->nb_streams; i++) {
4302 MOVTrack *track = &mov->tracks[i];
4303 MOVFragmentInfo *info;
4304 if ((tracks >= 0 && i != tracks) || !track->entry)
4306 track->nb_frag_info++;
4307 if (track->nb_frag_info >= track->frag_info_capacity) {
4308 unsigned new_capacity = track->nb_frag_info + MOV_FRAG_INFO_ALLOC_INCREMENT;
4309 if (av_reallocp_array(&track->frag_info,
4311 sizeof(*track->frag_info)))
4312 return AVERROR(ENOMEM);
4313 track->frag_info_capacity = new_capacity;
4315 info = &track->frag_info[track->nb_frag_info - 1];
4316 info->offset = avio_tell(pb);
4318 // Try to recreate the original pts for the first packet
4319 // from the fields we have stored
4320 info->time = track->start_dts + track->frag_start +
4321 track->cluster[0].cts;
4322 info->duration = track->end_pts -
4323 (track->cluster[0].dts + track->cluster[0].cts);
4324 // If the pts is less than zero, we will have trimmed
4325 // away parts of the media track using an edit list,
4326 // and the corresponding start presentation time is zero.
4327 if (info->time < 0) {
4328 info->duration += info->time;
4331 info->tfrf_offset = 0;
4332 mov_write_tfrf_tags(pb, mov, track);
4337 static void mov_prune_frag_info(MOVMuxContext *mov, int tracks, int max)
4340 for (i = 0; i < mov->nb_streams; i++) {
4341 MOVTrack *track = &mov->tracks[i];
4342 if ((tracks >= 0 && i != tracks) || !track->entry)
4344 if (track->nb_frag_info > max) {
4345 memmove(track->frag_info, track->frag_info + (track->nb_frag_info - max), max * sizeof(*track->frag_info));
4346 track->nb_frag_info = max;
4351 static int mov_write_tfdt_tag(AVIOContext *pb, MOVTrack *track)
4353 int64_t pos = avio_tell(pb);
4355 avio_wb32(pb, 0); /* size */
4356 ffio_wfourcc(pb, "tfdt");
4357 avio_w8(pb, 1); /* version */
4359 avio_wb64(pb, track->frag_start);
4360 return update_size(pb, pos);
4363 static int mov_write_traf_tag(AVIOContext *pb, MOVMuxContext *mov,
4364 MOVTrack *track, int64_t moof_offset,
4367 int64_t pos = avio_tell(pb);
4369 avio_wb32(pb, 0); /* size placeholder */
4370 ffio_wfourcc(pb, "traf");
4372 mov_write_tfhd_tag(pb, mov, track, moof_offset);
4373 if (mov->mode != MODE_ISM)
4374 mov_write_tfdt_tag(pb, track);
4375 for (i = 1; i < track->entry; i++) {
4376 if (track->cluster[i].pos != track->cluster[i - 1].pos + track->cluster[i - 1].size) {
4377 mov_write_trun_tag(pb, mov, track, moof_size, start, i);
4381 mov_write_trun_tag(pb, mov, track, moof_size, start, track->entry);
4382 if (mov->mode == MODE_ISM) {
4383 mov_write_tfxd_tag(pb, track);
4385 if (mov->ism_lookahead) {
4386 int i, size = 16 + 4 + 1 + 16 * mov->ism_lookahead;
4388 if (track->nb_frag_info > 0) {
4389 MOVFragmentInfo *info = &track->frag_info[track->nb_frag_info - 1];
4390 if (!info->tfrf_offset)
4391 info->tfrf_offset = avio_tell(pb);
4393 avio_wb32(pb, 8 + size);
4394 ffio_wfourcc(pb, "free");
4395 for (i = 0; i < size; i++)
4400 return update_size(pb, pos);
4403 static int mov_write_moof_tag_internal(AVIOContext *pb, MOVMuxContext *mov,
4404 int tracks, int moof_size)
4406 int64_t pos = avio_tell(pb);
4409 avio_wb32(pb, 0); /* size placeholder */
4410 ffio_wfourcc(pb, "moof");
4411 mov->first_trun = 1;
4413 mov_write_mfhd_tag(pb, mov);
4414 for (i = 0; i < mov->nb_streams; i++) {
4415 MOVTrack *track = &mov->tracks[i];
4416 if (tracks >= 0 && i != tracks)
4420 mov_write_traf_tag(pb, mov, track, pos, moof_size);
4423 return update_size(pb, pos);
4426 static int mov_write_sidx_tag(AVIOContext *pb,
4427 MOVTrack *track, int ref_size, int total_sidx_size)
4429 int64_t pos = avio_tell(pb), offset_pos, end_pos;
4430 int64_t presentation_time, duration, offset;
4431 int starts_with_SAP, i, entries;
4435 presentation_time = track->start_dts + track->frag_start +
4436 track->cluster[0].cts;
4437 duration = track->end_pts -
4438 (track->cluster[0].dts + track->cluster[0].cts);
4439 starts_with_SAP = track->cluster[0].flags & MOV_SYNC_SAMPLE;
4441 // pts<0 should be cut away using edts
4442 if (presentation_time < 0) {
4443 duration += presentation_time;
4444 presentation_time = 0;
4447 entries = track->nb_frag_info;
4450 presentation_time = track->frag_info[0].time;
4453 avio_wb32(pb, 0); /* size */
4454 ffio_wfourcc(pb, "sidx");
4455 avio_w8(pb, 1); /* version */
4457 avio_wb32(pb, track->track_id); /* reference_ID */
4458 avio_wb32(pb, track->timescale); /* timescale */
4459 avio_wb64(pb, presentation_time); /* earliest_presentation_time */
4460 offset_pos = avio_tell(pb);
4461 avio_wb64(pb, 0); /* first_offset (offset to referenced moof) */
4462 avio_wb16(pb, 0); /* reserved */
4464 avio_wb16(pb, entries); /* reference_count */
4465 for (i = 0; i < entries; i++) {
4466 if (!track->entry) {
4467 if (i > 1 && track->frag_info[i].offset != track->frag_info[i - 1].offset + track->frag_info[i - 1].size) {
4468 av_log(NULL, AV_LOG_ERROR, "Non-consecutive fragments, writing incorrect sidx\n");
4470 duration = track->frag_info[i].duration;
4471 ref_size = track->frag_info[i].size;
4472 starts_with_SAP = 1;
4474 avio_wb32(pb, (0 << 31) | (ref_size & 0x7fffffff)); /* reference_type (0 = media) | referenced_size */
4475 avio_wb32(pb, duration); /* subsegment_duration */
4476 avio_wb32(pb, (starts_with_SAP << 31) | (0 << 28) | 0); /* starts_with_SAP | SAP_type | SAP_delta_time */
4479 end_pos = avio_tell(pb);
4480 offset = pos + total_sidx_size - end_pos;
4481 avio_seek(pb, offset_pos, SEEK_SET);
4482 avio_wb64(pb, offset);
4483 avio_seek(pb, end_pos, SEEK_SET);
4484 return update_size(pb, pos);
4487 static int mov_write_sidx_tags(AVIOContext *pb, MOVMuxContext *mov,
4488 int tracks, int ref_size)
4491 AVIOContext *avio_buf;
4493 for (round = 0; round < 2; round++) {
4494 // First run one round to calculate the total size of all
4496 // This would be much simpler if we'd only write one sidx
4497 // atom, for the first track in the moof.
4499 if ((ret = ffio_open_null_buf(&avio_buf)) < 0)
4504 for (i = 0; i < mov->nb_streams; i++) {
4505 MOVTrack *track = &mov->tracks[i];
4506 if (tracks >= 0 && i != tracks)
4508 // When writing a sidx for the full file, entry is 0, but
4509 // we want to include all tracks. ref_size is 0 in this case,
4510 // since we read it from frag_info instead.
4511 if (!track->entry && ref_size > 0)
4513 total_size -= mov_write_sidx_tag(avio_buf, track, ref_size,
4517 total_size = ffio_close_null_buf(avio_buf);
4522 static int mov_write_prft_tag(AVIOContext *pb, MOVMuxContext *mov, int tracks)
4524 int64_t pos = avio_tell(pb), pts_us, ntp_ts;
4525 MOVTrack *first_track;
4527 /* PRFT should be associated with at most one track. So, choosing only the
4531 first_track = &(mov->tracks[0]);
4533 if (!first_track->entry) {
4534 av_log(mov->fc, AV_LOG_WARNING, "Unable to write PRFT, no entries in the track\n");
4538 if (first_track->cluster[0].pts == AV_NOPTS_VALUE) {
4539 av_log(mov->fc, AV_LOG_WARNING, "Unable to write PRFT, first PTS is invalid\n");
4543 if (mov->write_prft == MOV_PRFT_SRC_WALLCLOCK) {
4544 ntp_ts = ff_get_formatted_ntp_time(ff_ntp_time());
4545 } else if (mov->write_prft == MOV_PRFT_SRC_PTS) {
4546 pts_us = av_rescale_q(first_track->cluster[0].pts,
4547 first_track->st->time_base, AV_TIME_BASE_Q);
4548 ntp_ts = ff_get_formatted_ntp_time(pts_us + NTP_OFFSET_US);
4550 av_log(mov->fc, AV_LOG_WARNING, "Unsupported PRFT box configuration: %d\n",
4555 avio_wb32(pb, 0); // Size place holder
4556 ffio_wfourcc(pb, "prft"); // Type
4557 avio_w8(pb, 1); // Version
4558 avio_wb24(pb, 0); // Flags
4559 avio_wb32(pb, first_track->track_id); // reference track ID
4560 avio_wb64(pb, ntp_ts); // NTP time stamp
4561 avio_wb64(pb, first_track->cluster[0].pts); //media time
4562 return update_size(pb, pos);
4565 static int mov_write_moof_tag(AVIOContext *pb, MOVMuxContext *mov, int tracks,
4568 AVIOContext *avio_buf;
4571 if ((ret = ffio_open_null_buf(&avio_buf)) < 0)
4573 mov_write_moof_tag_internal(avio_buf, mov, tracks, 0);
4574 moof_size = ffio_close_null_buf(avio_buf);
4576 if (mov->flags & FF_MOV_FLAG_DASH && !(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX))
4577 mov_write_sidx_tags(pb, mov, tracks, moof_size + 8 + mdat_size);
4579 if (mov->write_prft > MOV_PRFT_NONE && mov->write_prft < MOV_PRFT_NB)
4580 mov_write_prft_tag(pb, mov, tracks);
4582 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX ||
4583 !(mov->flags & FF_MOV_FLAG_SKIP_TRAILER) ||
4584 mov->ism_lookahead) {
4585 if ((ret = mov_add_tfra_entries(pb, mov, tracks, moof_size + 8 + mdat_size)) < 0)
4587 if (!(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) &&
4588 mov->flags & FF_MOV_FLAG_SKIP_TRAILER) {
4589 mov_prune_frag_info(mov, tracks, mov->ism_lookahead + 1);
4593 return mov_write_moof_tag_internal(pb, mov, tracks, moof_size);
4596 static int mov_write_tfra_tag(AVIOContext *pb, MOVTrack *track)
4598 int64_t pos = avio_tell(pb);
4601 avio_wb32(pb, 0); /* size placeholder */
4602 ffio_wfourcc(pb, "tfra");
4603 avio_w8(pb, 1); /* version */
4606 avio_wb32(pb, track->track_id);
4607 avio_wb32(pb, 0); /* length of traf/trun/sample num */
4608 avio_wb32(pb, track->nb_frag_info);
4609 for (i = 0; i < track->nb_frag_info; i++) {
4610 avio_wb64(pb, track->frag_info[i].time);
4611 avio_wb64(pb, track->frag_info[i].offset + track->data_offset);
4612 avio_w8(pb, 1); /* traf number */
4613 avio_w8(pb, 1); /* trun number */
4614 avio_w8(pb, 1); /* sample number */
4617 return update_size(pb, pos);
4620 static int mov_write_mfra_tag(AVIOContext *pb, MOVMuxContext *mov)
4622 int64_t pos = avio_tell(pb);
4625 avio_wb32(pb, 0); /* size placeholder */
4626 ffio_wfourcc(pb, "mfra");
4627 /* An empty mfra atom is enough to indicate to the publishing point that
4628 * the stream has ended. */
4629 if (mov->flags & FF_MOV_FLAG_ISML)
4630 return update_size(pb, pos);
4632 for (i = 0; i < mov->nb_streams; i++) {
4633 MOVTrack *track = &mov->tracks[i];
4634 if (track->nb_frag_info)
4635 mov_write_tfra_tag(pb, track);
4639 ffio_wfourcc(pb, "mfro");
4640 avio_wb32(pb, 0); /* version + flags */
4641 avio_wb32(pb, avio_tell(pb) + 4 - pos);
4643 return update_size(pb, pos);
4646 static int mov_write_mdat_tag(AVIOContext *pb, MOVMuxContext *mov)
4648 avio_wb32(pb, 8); // placeholder for extended size field (64 bit)
4649 ffio_wfourcc(pb, mov->mode == MODE_MOV ? "wide" : "free");
4651 mov->mdat_pos = avio_tell(pb);
4652 avio_wb32(pb, 0); /* size placeholder*/
4653 ffio_wfourcc(pb, "mdat");
4657 /* TODO: This needs to be more general */
4658 static int mov_write_ftyp_tag(AVIOContext *pb, AVFormatContext *s)
4660 MOVMuxContext *mov = s->priv_data;
4661 int64_t pos = avio_tell(pb);
4662 int has_h264 = 0, has_video = 0;
4666 for (i = 0; i < s->nb_streams; i++) {
4667 AVStream *st = s->streams[i];
4668 if (is_cover_image(st))
4670 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
4672 if (st->codecpar->codec_id == AV_CODEC_ID_H264)
4676 avio_wb32(pb, 0); /* size */
4677 ffio_wfourcc(pb, "ftyp");
4679 if (mov->major_brand && strlen(mov->major_brand) >= 4)
4680 ffio_wfourcc(pb, mov->major_brand);
4681 else if (mov->mode == MODE_3GP) {
4682 ffio_wfourcc(pb, has_h264 ? "3gp6" : "3gp4");
4683 minor = has_h264 ? 0x100 : 0x200;
4684 } else if (mov->mode & MODE_3G2) {
4685 ffio_wfourcc(pb, has_h264 ? "3g2b" : "3g2a");
4686 minor = has_h264 ? 0x20000 : 0x10000;
4687 } else if (mov->mode == MODE_PSP)
4688 ffio_wfourcc(pb, "MSNV");
4689 else if (mov->mode == MODE_MP4 && mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)
4690 ffio_wfourcc(pb, "iso5"); // Required when using default-base-is-moof
4691 else if (mov->mode == MODE_MP4 && mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS)
4692 ffio_wfourcc(pb, "iso4");
4693 else if (mov->mode == MODE_MP4)
4694 ffio_wfourcc(pb, "isom");
4695 else if (mov->mode == MODE_IPOD)
4696 ffio_wfourcc(pb, has_video ? "M4V ":"M4A ");
4697 else if (mov->mode == MODE_ISM)
4698 ffio_wfourcc(pb, "isml");
4699 else if (mov->mode == MODE_F4V)
4700 ffio_wfourcc(pb, "f4v ");
4702 ffio_wfourcc(pb, "qt ");
4704 avio_wb32(pb, minor);
4706 if (mov->mode == MODE_MOV)
4707 ffio_wfourcc(pb, "qt ");
4708 else if (mov->mode == MODE_ISM) {
4709 ffio_wfourcc(pb, "piff");
4710 } else if (!(mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)) {
4711 ffio_wfourcc(pb, "isom");
4712 ffio_wfourcc(pb, "iso2");
4714 ffio_wfourcc(pb, "avc1");
4717 // We add tfdt atoms when fragmenting, signal this with the iso6 compatible
4718 // brand. This is compatible with users that don't understand tfdt.
4719 if (mov->flags & FF_MOV_FLAG_FRAGMENT && mov->mode != MODE_ISM)
4720 ffio_wfourcc(pb, "iso6");
4722 if (mov->mode == MODE_3GP)
4723 ffio_wfourcc(pb, has_h264 ? "3gp6":"3gp4");
4724 else if (mov->mode & MODE_3G2)
4725 ffio_wfourcc(pb, has_h264 ? "3g2b":"3g2a");
4726 else if (mov->mode == MODE_PSP)
4727 ffio_wfourcc(pb, "MSNV");
4728 else if (mov->mode == MODE_MP4)
4729 ffio_wfourcc(pb, "mp41");
4731 if (mov->flags & FF_MOV_FLAG_DASH && mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
4732 ffio_wfourcc(pb, "dash");
4734 return update_size(pb, pos);
4737 static int mov_write_uuidprof_tag(AVIOContext *pb, AVFormatContext *s)
4739 AVStream *video_st = s->streams[0];
4740 AVCodecParameters *video_par = s->streams[0]->codecpar;
4741 AVCodecParameters *audio_par = s->streams[1]->codecpar;
4742 int audio_rate = audio_par->sample_rate;
4743 int64_t frame_rate = video_st->avg_frame_rate.den ?
4744 (video_st->avg_frame_rate.num * 0x10000LL) / video_st->avg_frame_rate.den :
4746 int audio_kbitrate = audio_par->bit_rate / 1000;
4747 int video_kbitrate = FFMIN(video_par->bit_rate / 1000, 800 - audio_kbitrate);
4749 if (frame_rate < 0 || frame_rate > INT32_MAX) {
4750 av_log(s, AV_LOG_ERROR, "Frame rate %f outside supported range\n", frame_rate / (double)0x10000);
4751 return AVERROR(EINVAL);
4754 avio_wb32(pb, 0x94); /* size */
4755 ffio_wfourcc(pb, "uuid");
4756 ffio_wfourcc(pb, "PROF");
4758 avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
4759 avio_wb32(pb, 0xbb88695c);
4760 avio_wb32(pb, 0xfac9c740);
4762 avio_wb32(pb, 0x0); /* ? */
4763 avio_wb32(pb, 0x3); /* 3 sections ? */
4765 avio_wb32(pb, 0x14); /* size */
4766 ffio_wfourcc(pb, "FPRF");
4767 avio_wb32(pb, 0x0); /* ? */
4768 avio_wb32(pb, 0x0); /* ? */
4769 avio_wb32(pb, 0x0); /* ? */
4771 avio_wb32(pb, 0x2c); /* size */
4772 ffio_wfourcc(pb, "APRF"); /* audio */
4774 avio_wb32(pb, 0x2); /* TrackID */
4775 ffio_wfourcc(pb, "mp4a");
4776 avio_wb32(pb, 0x20f);
4778 avio_wb32(pb, audio_kbitrate);
4779 avio_wb32(pb, audio_kbitrate);
4780 avio_wb32(pb, audio_rate);
4781 avio_wb32(pb, audio_par->channels);
4783 avio_wb32(pb, 0x34); /* size */
4784 ffio_wfourcc(pb, "VPRF"); /* video */
4786 avio_wb32(pb, 0x1); /* TrackID */
4787 if (video_par->codec_id == AV_CODEC_ID_H264) {
4788 ffio_wfourcc(pb, "avc1");
4789 avio_wb16(pb, 0x014D);
4790 avio_wb16(pb, 0x0015);
4792 ffio_wfourcc(pb, "mp4v");
4793 avio_wb16(pb, 0x0000);
4794 avio_wb16(pb, 0x0103);
4797 avio_wb32(pb, video_kbitrate);
4798 avio_wb32(pb, video_kbitrate);
4799 avio_wb32(pb, frame_rate);
4800 avio_wb32(pb, frame_rate);
4801 avio_wb16(pb, video_par->width);
4802 avio_wb16(pb, video_par->height);
4803 avio_wb32(pb, 0x010001); /* ? */
4808 static int mov_write_identification(AVIOContext *pb, AVFormatContext *s)
4810 MOVMuxContext *mov = s->priv_data;
4813 mov_write_ftyp_tag(pb,s);
4814 if (mov->mode == MODE_PSP) {
4815 int video_streams_nb = 0, audio_streams_nb = 0, other_streams_nb = 0;
4816 for (i = 0; i < s->nb_streams; i++) {
4817 AVStream *st = s->streams[i];
4818 if (is_cover_image(st))
4820 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
4822 else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
4828 if (video_streams_nb != 1 || audio_streams_nb != 1 || other_streams_nb) {
4829 av_log(s, AV_LOG_ERROR, "PSP mode need one video and one audio stream\n");
4830 return AVERROR(EINVAL);
4832 return mov_write_uuidprof_tag(pb, s);
4837 static int mov_parse_mpeg2_frame(AVPacket *pkt, uint32_t *flags)
4840 int i, closed_gop = 0;
4842 for (i = 0; i < pkt->size - 4; i++) {
4843 c = (c << 8) + pkt->data[i];
4844 if (c == 0x1b8) { // gop
4845 closed_gop = pkt->data[i + 4] >> 6 & 0x01;
4846 } else if (c == 0x100) { // pic
4847 int temp_ref = (pkt->data[i + 1] << 2) | (pkt->data[i + 2] >> 6);
4848 if (!temp_ref || closed_gop) // I picture is not reordered
4849 *flags = MOV_SYNC_SAMPLE;
4851 *flags = MOV_PARTIAL_SYNC_SAMPLE;
4858 static void mov_parse_vc1_frame(AVPacket *pkt, MOVTrack *trk)
4860 const uint8_t *start, *next, *end = pkt->data + pkt->size;
4861 int seq = 0, entry = 0;
4862 int key = pkt->flags & AV_PKT_FLAG_KEY;
4863 start = find_next_marker(pkt->data, end);
4864 for (next = start; next < end; start = next) {
4865 next = find_next_marker(start + 4, end);
4866 switch (AV_RB32(start)) {
4867 case VC1_CODE_SEQHDR:
4870 case VC1_CODE_ENTRYPOINT:
4873 case VC1_CODE_SLICE:
4874 trk->vc1_info.slices = 1;
4878 if (!trk->entry && trk->vc1_info.first_packet_seen)
4879 trk->vc1_info.first_frag_written = 1;
4880 if (!trk->entry && !trk->vc1_info.first_frag_written) {
4881 /* First packet in first fragment */
4882 trk->vc1_info.first_packet_seq = seq;
4883 trk->vc1_info.first_packet_entry = entry;
4884 trk->vc1_info.first_packet_seen = 1;
4885 } else if ((seq && !trk->vc1_info.packet_seq) ||
4886 (entry && !trk->vc1_info.packet_entry)) {
4888 for (i = 0; i < trk->entry; i++)
4889 trk->cluster[i].flags &= ~MOV_SYNC_SAMPLE;
4890 trk->has_keyframes = 0;
4892 trk->vc1_info.packet_seq = 1;
4894 trk->vc1_info.packet_entry = 1;
4895 if (!trk->vc1_info.first_frag_written) {
4896 /* First fragment */
4897 if ((!seq || trk->vc1_info.first_packet_seq) &&
4898 (!entry || trk->vc1_info.first_packet_entry)) {
4899 /* First packet had the same headers as this one, readd the
4900 * sync sample flag. */
4901 trk->cluster[0].flags |= MOV_SYNC_SAMPLE;
4902 trk->has_keyframes = 1;
4906 if (trk->vc1_info.packet_seq && trk->vc1_info.packet_entry)
4908 else if (trk->vc1_info.packet_seq)
4910 else if (trk->vc1_info.packet_entry)
4913 trk->cluster[trk->entry].flags |= MOV_SYNC_SAMPLE;
4914 trk->has_keyframes++;
4918 static int mov_flush_fragment_interleaving(AVFormatContext *s, MOVTrack *track)
4920 MOVMuxContext *mov = s->priv_data;
4925 if (!track->mdat_buf)
4927 if (!mov->mdat_buf) {
4928 if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0)
4931 buf_size = avio_close_dyn_buf(track->mdat_buf, &buf);
4932 track->mdat_buf = NULL;
4934 offset = avio_tell(mov->mdat_buf);
4935 avio_write(mov->mdat_buf, buf, buf_size);
4938 for (i = track->entries_flushed; i < track->entry; i++)
4939 track->cluster[i].pos += offset;
4940 track->entries_flushed = track->entry;
4944 static int mov_flush_fragment(AVFormatContext *s, int force)
4946 MOVMuxContext *mov = s->priv_data;
4947 int i, first_track = -1;
4948 int64_t mdat_size = 0;
4950 int has_video = 0, starts_with_key = 0, first_video_track = 1;
4952 if (!(mov->flags & FF_MOV_FLAG_FRAGMENT))
4955 // Try to fill in the duration of the last packet in each stream
4956 // from queued packets in the interleave queues. If the flushing
4957 // of fragments was triggered automatically by an AVPacket, we
4958 // already have reliable info for the end of that track, but other
4959 // tracks may need to be filled in.
4960 for (i = 0; i < s->nb_streams; i++) {
4961 MOVTrack *track = &mov->tracks[i];
4962 if (!track->end_reliable) {
4964 if (!ff_interleaved_peek(s, i, &pkt, 1)) {
4965 if (track->dts_shift != AV_NOPTS_VALUE)
4966 pkt.dts += track->dts_shift;
4967 track->track_duration = pkt.dts - track->start_dts;
4968 if (pkt.pts != AV_NOPTS_VALUE)
4969 track->end_pts = pkt.pts;
4971 track->end_pts = pkt.dts;
4976 for (i = 0; i < mov->nb_streams; i++) {
4977 MOVTrack *track = &mov->tracks[i];
4978 if (track->entry <= 1)
4980 // Sample durations are calculated as the diff of dts values,
4981 // but for the last sample in a fragment, we don't know the dts
4982 // of the first sample in the next fragment, so we have to rely
4983 // on what was set as duration in the AVPacket. Not all callers
4984 // set this though, so we might want to replace it with an
4985 // estimate if it currently is zero.
4986 if (get_cluster_duration(track, track->entry - 1) != 0)
4988 // Use the duration (i.e. dts diff) of the second last sample for
4989 // the last one. This is a wild guess (and fatal if it turns out
4990 // to be too long), but probably the best we can do - having a zero
4991 // duration is bad as well.
4992 track->track_duration += get_cluster_duration(track, track->entry - 2);
4993 track->end_pts += get_cluster_duration(track, track->entry - 2);
4994 if (!mov->missing_duration_warned) {
4995 av_log(s, AV_LOG_WARNING,
4996 "Estimating the duration of the last packet in a "
4997 "fragment, consider setting the duration field in "
4998 "AVPacket instead.\n");
4999 mov->missing_duration_warned = 1;
5003 if (!mov->moov_written) {
5004 int64_t pos = avio_tell(s->pb);
5006 int buf_size, moov_size;
5008 for (i = 0; i < mov->nb_streams; i++)
5009 if (!mov->tracks[i].entry && !is_cover_image(mov->tracks[i].st))
5011 /* Don't write the initial moov unless all tracks have data */
5012 if (i < mov->nb_streams && !force)
5015 moov_size = get_moov_size(s);
5016 for (i = 0; i < mov->nb_streams; i++)
5017 mov->tracks[i].data_offset = pos + moov_size + 8;
5019 avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_HEADER);
5020 if (mov->flags & FF_MOV_FLAG_DELAY_MOOV)
5021 mov_write_identification(s->pb, s);
5022 if ((ret = mov_write_moov_tag(s->pb, mov, s)) < 0)
5025 if (mov->flags & FF_MOV_FLAG_DELAY_MOOV) {
5026 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
5027 mov->reserved_header_pos = avio_tell(s->pb);
5029 mov->moov_written = 1;
5033 buf_size = avio_close_dyn_buf(mov->mdat_buf, &buf);
5034 mov->mdat_buf = NULL;
5035 avio_wb32(s->pb, buf_size + 8);
5036 ffio_wfourcc(s->pb, "mdat");
5037 avio_write(s->pb, buf, buf_size);
5040 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
5041 mov->reserved_header_pos = avio_tell(s->pb);
5043 mov->moov_written = 1;
5045 for (i = 0; i < mov->nb_streams; i++) {
5046 if (mov->tracks[i].entry)
5047 mov->tracks[i].frag_start += mov->tracks[i].start_dts +
5048 mov->tracks[i].track_duration -
5049 mov->tracks[i].cluster[0].dts;
5050 mov->tracks[i].entry = 0;
5051 mov->tracks[i].end_reliable = 0;
5057 if (mov->frag_interleave) {
5058 for (i = 0; i < mov->nb_streams; i++) {
5059 MOVTrack *track = &mov->tracks[i];
5061 if ((ret = mov_flush_fragment_interleaving(s, track)) < 0)
5067 mdat_size = avio_tell(mov->mdat_buf);
5070 for (i = 0; i < mov->nb_streams; i++) {
5071 MOVTrack *track = &mov->tracks[i];
5072 if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF || mov->frag_interleave)
5073 track->data_offset = 0;
5075 track->data_offset = mdat_size;
5076 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
5078 if (first_video_track) {
5080 starts_with_key = track->cluster[0].flags & MOV_SYNC_SAMPLE;
5081 first_video_track = 0;
5086 if (track->mdat_buf)
5087 mdat_size += avio_tell(track->mdat_buf);
5088 if (first_track < 0)
5095 avio_write_marker(s->pb,
5096 av_rescale(mov->tracks[first_track].cluster[0].dts, AV_TIME_BASE, mov->tracks[first_track].timescale),
5097 (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);
5099 for (i = 0; i < mov->nb_streams; i++) {
5100 MOVTrack *track = &mov->tracks[i];
5101 int buf_size, write_moof = 1, moof_tracks = -1;
5103 int64_t duration = 0;
5106 duration = track->start_dts + track->track_duration -
5107 track->cluster[0].dts;
5108 if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF) {
5109 if (!track->mdat_buf)
5111 mdat_size = avio_tell(track->mdat_buf);
5114 write_moof = i == first_track;
5120 mov_write_moof_tag(s->pb, mov, moof_tracks, mdat_size);
5123 avio_wb32(s->pb, mdat_size + 8);
5124 ffio_wfourcc(s->pb, "mdat");
5128 track->frag_start += duration;
5130 track->entries_flushed = 0;
5131 track->end_reliable = 0;
5132 if (!mov->frag_interleave) {
5133 if (!track->mdat_buf)
5135 buf_size = avio_close_dyn_buf(track->mdat_buf, &buf);
5136 track->mdat_buf = NULL;
5140 buf_size = avio_close_dyn_buf(mov->mdat_buf, &buf);
5141 mov->mdat_buf = NULL;
5144 avio_write(s->pb, buf, buf_size);
5154 static int mov_auto_flush_fragment(AVFormatContext *s, int force)
5156 MOVMuxContext *mov = s->priv_data;
5157 int had_moov = mov->moov_written;
5158 int ret = mov_flush_fragment(s, force);
5161 // If using delay_moov, the first flush only wrote the moov,
5162 // not the actual moof+mdat pair, thus flush once again.
5163 if (!had_moov && mov->flags & FF_MOV_FLAG_DELAY_MOOV)
5164 ret = mov_flush_fragment(s, force);
5168 static int check_pkt(AVFormatContext *s, AVPacket *pkt)
5170 MOVMuxContext *mov = s->priv_data;
5171 MOVTrack *trk = &mov->tracks[pkt->stream_index];
5176 ref = trk->cluster[trk->entry - 1].dts;
5177 } else if ( trk->start_dts != AV_NOPTS_VALUE
5178 && !trk->frag_discont) {
5179 ref = trk->start_dts + trk->track_duration;
5181 ref = pkt->dts; // Skip tests for the first packet
5183 if (trk->dts_shift != AV_NOPTS_VALUE) {
5184 /* With negative CTS offsets we have set an offset to the DTS,
5185 * reverse this for the check. */
5186 ref -= trk->dts_shift;
5189 duration = pkt->dts - ref;
5190 if (pkt->dts < ref || duration >= INT_MAX) {
5191 av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" / timestamp: %"PRId64" is out of range for mov/mp4 format\n",
5196 pkt->pts = AV_NOPTS_VALUE;
5199 if (pkt->duration < 0 || pkt->duration > INT_MAX) {
5200 av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" is invalid\n", pkt->duration);
5201 return AVERROR(EINVAL);
5206 int ff_mov_write_packet(AVFormatContext *s, AVPacket *pkt)
5208 MOVMuxContext *mov = s->priv_data;
5209 AVIOContext *pb = s->pb;
5210 MOVTrack *trk = &mov->tracks[pkt->stream_index];
5211 AVCodecParameters *par = trk->par;
5212 unsigned int samples_in_chunk = 0;
5213 int size = pkt->size, ret = 0;
5214 uint8_t *reformatted_data = NULL;
5216 ret = check_pkt(s, pkt);
5220 if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
5222 if (mov->moov_written || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
5223 if (mov->frag_interleave && mov->fragments > 0) {
5224 if (trk->entry - trk->entries_flushed >= mov->frag_interleave) {
5225 if ((ret = mov_flush_fragment_interleaving(s, trk)) < 0)
5230 if (!trk->mdat_buf) {
5231 if ((ret = avio_open_dyn_buf(&trk->mdat_buf)) < 0)
5236 if (!mov->mdat_buf) {
5237 if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0)
5244 if (par->codec_id == AV_CODEC_ID_AMR_NB) {
5245 /* We must find out how many AMR blocks there are in one packet */
5246 static const uint16_t packed_size[16] =
5247 {13, 14, 16, 18, 20, 21, 27, 32, 6, 0, 0, 0, 0, 0, 0, 1};
5250 while (len < size && samples_in_chunk < 100) {
5251 len += packed_size[(pkt->data[len] >> 3) & 0x0F];
5254 if (samples_in_chunk > 1) {
5255 av_log(s, AV_LOG_ERROR, "fatal error, input is not a single packet, implement a AVParser for it\n");
5258 } else if (par->codec_id == AV_CODEC_ID_ADPCM_MS ||
5259 par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) {
5260 samples_in_chunk = trk->par->frame_size;
5261 } else if (trk->sample_size)
5262 samples_in_chunk = size / trk->sample_size;
5264 samples_in_chunk = 1;
5266 /* copy extradata if it exists */
5267 if (trk->vos_len == 0 && par->extradata_size > 0 &&
5268 !TAG_IS_AVCI(trk->tag) &&
5269 (par->codec_id != AV_CODEC_ID_DNXHD)) {
5270 trk->vos_len = par->extradata_size;
5271 trk->vos_data = av_malloc(trk->vos_len);
5272 if (!trk->vos_data) {
5273 ret = AVERROR(ENOMEM);
5276 memcpy(trk->vos_data, par->extradata, trk->vos_len);
5279 if (par->codec_id == AV_CODEC_ID_AAC && pkt->size > 2 &&
5280 (AV_RB16(pkt->data) & 0xfff0) == 0xfff0) {
5281 if (!s->streams[pkt->stream_index]->nb_frames) {
5282 av_log(s, AV_LOG_ERROR, "Malformed AAC bitstream detected: "
5283 "use the audio bitstream filter 'aac_adtstoasc' to fix it "
5284 "('-bsf:a aac_adtstoasc' option with ffmpeg)\n");
5287 av_log(s, AV_LOG_WARNING, "aac bitstream error\n");
5289 if (par->codec_id == AV_CODEC_ID_H264 && trk->vos_len > 0 && *(uint8_t *)trk->vos_data != 1 && !TAG_IS_AVCI(trk->tag)) {
5290 /* from x264 or from bytestream H.264 */
5291 /* NAL reformatting needed */
5292 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
5293 ff_avc_parse_nal_units_buf(pkt->data, &reformatted_data,
5295 avio_write(pb, reformatted_data, size);
5297 if (trk->cenc.aes_ctr) {
5298 size = ff_mov_cenc_avc_parse_nal_units(&trk->cenc, pb, pkt->data, size);
5304 size = ff_avc_parse_nal_units(pb, pkt->data, pkt->size);
5307 } else if (par->codec_id == AV_CODEC_ID_HEVC && trk->vos_len > 6 &&
5308 (AV_RB24(trk->vos_data) == 1 || AV_RB32(trk->vos_data) == 1)) {
5309 /* extradata is Annex B, assume the bitstream is too and convert it */
5310 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
5311 ff_hevc_annexb2mp4_buf(pkt->data, &reformatted_data, &size, 0, NULL);
5312 avio_write(pb, reformatted_data, size);
5314 size = ff_hevc_annexb2mp4(pb, pkt->data, pkt->size, 0, NULL);
5316 #if CONFIG_AC3_PARSER
5317 } else if (par->codec_id == AV_CODEC_ID_EAC3) {
5318 size = handle_eac3(mov, pkt, trk);
5323 avio_write(pb, pkt->data, size);
5326 if (trk->cenc.aes_ctr) {
5327 if (par->codec_id == AV_CODEC_ID_H264 && par->extradata_size > 4) {
5328 int nal_size_length = (par->extradata[4] & 0x3) + 1;
5329 ret = ff_mov_cenc_avc_write_nal_units(s, &trk->cenc, nal_size_length, pb, pkt->data, size);
5331 ret = ff_mov_cenc_write_packet(&trk->cenc, pb, pkt->data, size);
5338 avio_write(pb, pkt->data, size);
5342 if ((par->codec_id == AV_CODEC_ID_DNXHD ||
5343 par->codec_id == AV_CODEC_ID_AC3) && !trk->vos_len) {
5344 /* copy frame to create needed atoms */
5345 trk->vos_len = size;
5346 trk->vos_data = av_malloc(size);
5347 if (!trk->vos_data) {
5348 ret = AVERROR(ENOMEM);
5351 memcpy(trk->vos_data, pkt->data, size);
5354 if (trk->entry >= trk->cluster_capacity) {
5355 unsigned new_capacity = 2 * (trk->entry + MOV_INDEX_CLUSTER_SIZE);
5356 if (av_reallocp_array(&trk->cluster, new_capacity,
5357 sizeof(*trk->cluster))) {
5358 ret = AVERROR(ENOMEM);
5361 trk->cluster_capacity = new_capacity;
5364 trk->cluster[trk->entry].pos = avio_tell(pb) - size;
5365 trk->cluster[trk->entry].samples_in_chunk = samples_in_chunk;
5366 trk->cluster[trk->entry].chunkNum = 0;
5367 trk->cluster[trk->entry].size = size;
5368 trk->cluster[trk->entry].entries = samples_in_chunk;
5369 trk->cluster[trk->entry].dts = pkt->dts;
5370 trk->cluster[trk->entry].pts = pkt->pts;
5371 if (!trk->entry && trk->start_dts != AV_NOPTS_VALUE) {
5372 if (!trk->frag_discont) {
5373 /* First packet of a new fragment. We already wrote the duration
5374 * of the last packet of the previous fragment based on track_duration,
5375 * which might not exactly match our dts. Therefore adjust the dts
5376 * of this packet to be what the previous packets duration implies. */
5377 trk->cluster[trk->entry].dts = trk->start_dts + trk->track_duration;
5378 /* We also may have written the pts and the corresponding duration
5379 * in sidx/tfrf/tfxd tags; make sure the sidx pts and duration match up with
5380 * the next fragment. This means the cts of the first sample must
5381 * be the same in all fragments, unless end_pts was updated by
5382 * the packet causing the fragment to be written. */
5383 if ((mov->flags & FF_MOV_FLAG_DASH && !(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)) ||
5384 mov->mode == MODE_ISM)
5385 pkt->pts = pkt->dts + trk->end_pts - trk->cluster[trk->entry].dts;
5387 /* New fragment, but discontinuous from previous fragments.
5388 * Pretend the duration sum of the earlier fragments is
5389 * pkt->dts - trk->start_dts. */
5390 trk->frag_start = pkt->dts - trk->start_dts;
5391 trk->end_pts = AV_NOPTS_VALUE;
5392 trk->frag_discont = 0;
5396 if (!trk->entry && trk->start_dts == AV_NOPTS_VALUE && !mov->use_editlist &&
5397 s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO) {
5398 /* Not using edit lists and shifting the first track to start from zero.
5399 * If the other streams start from a later timestamp, we won't be able
5400 * to signal the difference in starting time without an edit list.
5401 * Thus move the timestamp for this first sample to 0, increasing
5402 * its duration instead. */
5403 trk->cluster[trk->entry].dts = trk->start_dts = 0;
5405 if (trk->start_dts == AV_NOPTS_VALUE) {
5406 trk->start_dts = pkt->dts;
5407 if (trk->frag_discont) {
5408 if (mov->use_editlist) {
5409 /* Pretend the whole stream started at pts=0, with earlier fragments
5410 * already written. If the stream started at pts=0, the duration sum
5411 * of earlier fragments would have been pkt->pts. */
5412 trk->frag_start = pkt->pts;
5413 trk->start_dts = pkt->dts - pkt->pts;
5415 /* Pretend the whole stream started at dts=0, with earlier fragments
5416 * already written, with a duration summing up to pkt->dts. */
5417 trk->frag_start = pkt->dts;
5420 trk->frag_discont = 0;
5421 } else if (pkt->dts && mov->moov_written)
5422 av_log(s, AV_LOG_WARNING,
5423 "Track %d starts with a nonzero dts %"PRId64", while the moov "
5424 "already has been written. Set the delay_moov flag to handle "
5426 pkt->stream_index, pkt->dts);
5428 trk->track_duration = pkt->dts - trk->start_dts + pkt->duration;
5429 trk->last_sample_is_subtitle_end = 0;
5431 if (pkt->pts == AV_NOPTS_VALUE) {
5432 av_log(s, AV_LOG_WARNING, "pts has no value\n");
5433 pkt->pts = pkt->dts;
5435 if (pkt->dts != pkt->pts)
5436 trk->flags |= MOV_TRACK_CTTS;
5437 trk->cluster[trk->entry].cts = pkt->pts - pkt->dts;
5438 trk->cluster[trk->entry].flags = 0;
5439 if (trk->start_cts == AV_NOPTS_VALUE)
5440 trk->start_cts = pkt->pts - pkt->dts;
5441 if (trk->end_pts == AV_NOPTS_VALUE)
5442 trk->end_pts = trk->cluster[trk->entry].dts +
5443 trk->cluster[trk->entry].cts + pkt->duration;
5445 trk->end_pts = FFMAX(trk->end_pts, trk->cluster[trk->entry].dts +
5446 trk->cluster[trk->entry].cts +
5449 if (par->codec_id == AV_CODEC_ID_VC1) {
5450 mov_parse_vc1_frame(pkt, trk);
5451 } else if (pkt->flags & AV_PKT_FLAG_KEY) {
5452 if (mov->mode == MODE_MOV && par->codec_id == AV_CODEC_ID_MPEG2VIDEO &&
5453 trk->entry > 0) { // force sync sample for the first key frame
5454 mov_parse_mpeg2_frame(pkt, &trk->cluster[trk->entry].flags);
5455 if (trk->cluster[trk->entry].flags & MOV_PARTIAL_SYNC_SAMPLE)
5456 trk->flags |= MOV_TRACK_STPS;
5458 trk->cluster[trk->entry].flags = MOV_SYNC_SAMPLE;
5460 if (trk->cluster[trk->entry].flags & MOV_SYNC_SAMPLE)
5461 trk->has_keyframes++;
5463 if (pkt->flags & AV_PKT_FLAG_DISPOSABLE) {
5464 trk->cluster[trk->entry].flags |= MOV_DISPOSABLE_SAMPLE;
5465 trk->has_disposable++;
5468 trk->sample_count += samples_in_chunk;
5469 mov->mdat_size += size;
5471 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams)
5472 ff_mov_add_hinted_packet(s, pkt, trk->hint_track, trk->entry,
5473 reformatted_data, size);
5478 av_free(reformatted_data);
5482 static int mov_write_single_packet(AVFormatContext *s, AVPacket *pkt)
5484 MOVMuxContext *mov = s->priv_data;
5485 MOVTrack *trk = &mov->tracks[pkt->stream_index];
5486 AVCodecParameters *par = trk->par;
5487 int64_t frag_duration = 0;
5488 int size = pkt->size;
5490 int ret = check_pkt(s, pkt);
5494 if (mov->flags & FF_MOV_FLAG_FRAG_DISCONT) {
5496 for (i = 0; i < s->nb_streams; i++)
5497 mov->tracks[i].frag_discont = 1;
5498 mov->flags &= ~FF_MOV_FLAG_FRAG_DISCONT;
5501 if (mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS) {
5502 if (trk->dts_shift == AV_NOPTS_VALUE)
5503 trk->dts_shift = pkt->pts - pkt->dts;
5504 pkt->dts += trk->dts_shift;
5507 if (trk->par->codec_id == AV_CODEC_ID_MP4ALS ||
5508 trk->par->codec_id == AV_CODEC_ID_AAC ||
5509 trk->par->codec_id == AV_CODEC_ID_FLAC) {
5511 uint8_t *side = av_packet_get_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA, &side_size);
5512 if (side && side_size > 0 && (side_size != par->extradata_size || memcmp(side, par->extradata, side_size))) {
5513 void *newextra = av_mallocz(side_size + AV_INPUT_BUFFER_PADDING_SIZE);
5515 return AVERROR(ENOMEM);
5516 av_free(par->extradata);
5517 par->extradata = newextra;
5518 memcpy(par->extradata, side, side_size);
5519 par->extradata_size = side_size;
5520 if (!pkt->size) // Flush packet
5521 mov->need_rewrite_extradata = 1;
5526 if (trk->start_dts == AV_NOPTS_VALUE && trk->frag_discont) {
5527 trk->start_dts = pkt->dts;
5528 if (pkt->pts != AV_NOPTS_VALUE)
5529 trk->start_cts = pkt->pts - pkt->dts;
5534 return 0; /* Discard 0 sized packets */
5537 if (trk->entry && pkt->stream_index < s->nb_streams)
5538 frag_duration = av_rescale_q(pkt->dts - trk->cluster[0].dts,
5539 s->streams[pkt->stream_index]->time_base,
5541 if ((mov->max_fragment_duration &&
5542 frag_duration >= mov->max_fragment_duration) ||
5543 (mov->max_fragment_size && mov->mdat_size + size >= mov->max_fragment_size) ||
5544 (mov->flags & FF_MOV_FLAG_FRAG_KEYFRAME &&
5545 par->codec_type == AVMEDIA_TYPE_VIDEO &&
5546 trk->entry && pkt->flags & AV_PKT_FLAG_KEY) ||
5547 (mov->flags & FF_MOV_FLAG_FRAG_EVERY_FRAME)) {
5548 if (frag_duration >= mov->min_fragment_duration) {
5549 // Set the duration of this track to line up with the next
5550 // sample in this track. This avoids relying on AVPacket
5551 // duration, but only helps for this particular track, not
5552 // for the other ones that are flushed at the same time.
5553 trk->track_duration = pkt->dts - trk->start_dts;
5554 if (pkt->pts != AV_NOPTS_VALUE)
5555 trk->end_pts = pkt->pts;
5557 trk->end_pts = pkt->dts;
5558 trk->end_reliable = 1;
5559 mov_auto_flush_fragment(s, 0);
5563 return ff_mov_write_packet(s, pkt);
5566 static int mov_write_subtitle_end_packet(AVFormatContext *s,
5570 uint8_t data[2] = {0};
5573 av_init_packet(&end);
5574 end.size = sizeof(data);
5579 end.stream_index = stream_index;
5581 ret = mov_write_single_packet(s, &end);
5582 av_packet_unref(&end);
5587 static int mov_write_packet(AVFormatContext *s, AVPacket *pkt)
5589 MOVMuxContext *mov = s->priv_data;
5593 mov_flush_fragment(s, 1);
5597 trk = &mov->tracks[pkt->stream_index];
5599 if (is_cover_image(trk->st)) {
5602 if (trk->st->nb_frames >= 1) {
5603 if (trk->st->nb_frames == 1)
5604 av_log(s, AV_LOG_WARNING, "Got more than one picture in stream %d,"
5605 " ignoring.\n", pkt->stream_index);
5609 if ((ret = av_packet_ref(&trk->cover_image, pkt)) < 0)
5617 return mov_write_single_packet(s, pkt); /* Passthrough. */
5620 * Subtitles require special handling.
5622 * 1) For full complaince, every track must have a sample at
5623 * dts == 0, which is rarely true for subtitles. So, as soon
5624 * as we see any packet with dts > 0, write an empty subtitle
5625 * at dts == 0 for any subtitle track with no samples in it.
5627 * 2) For each subtitle track, check if the current packet's
5628 * dts is past the duration of the last subtitle sample. If
5629 * so, we now need to write an end sample for that subtitle.
5631 * This must be done conditionally to allow for subtitles that
5632 * immediately replace each other, in which case an end sample
5633 * is not needed, and is, in fact, actively harmful.
5635 * 3) See mov_write_trailer for how the final end sample is
5638 for (i = 0; i < mov->nb_streams; i++) {
5639 MOVTrack *trk = &mov->tracks[i];
5642 if (trk->par->codec_id == AV_CODEC_ID_MOV_TEXT &&
5643 trk->track_duration < pkt->dts &&
5644 (trk->entry == 0 || !trk->last_sample_is_subtitle_end)) {
5645 ret = mov_write_subtitle_end_packet(s, i, trk->track_duration);
5646 if (ret < 0) return ret;
5647 trk->last_sample_is_subtitle_end = 1;
5651 if (trk->mode == MODE_MOV && trk->par->codec_type == AVMEDIA_TYPE_VIDEO) {
5652 AVPacket *opkt = pkt;
5653 int reshuffle_ret, ret;
5654 if (trk->is_unaligned_qt_rgb) {
5655 int64_t bpc = trk->par->bits_per_coded_sample != 15 ? trk->par->bits_per_coded_sample : 16;
5656 int expected_stride = ((trk->par->width * bpc + 15) >> 4)*2;
5657 reshuffle_ret = ff_reshuffle_raw_rgb(s, &pkt, trk->par, expected_stride);
5658 if (reshuffle_ret < 0)
5659 return reshuffle_ret;
5662 if (trk->par->format == AV_PIX_FMT_PAL8 && !trk->pal_done) {
5663 ret = ff_get_packet_palette(s, opkt, reshuffle_ret, trk->palette);
5668 } else if (trk->par->codec_id == AV_CODEC_ID_RAWVIDEO &&
5669 (trk->par->format == AV_PIX_FMT_GRAY8 ||
5670 trk->par->format == AV_PIX_FMT_MONOBLACK)) {
5671 for (i = 0; i < pkt->size; i++)
5672 pkt->data[i] = ~pkt->data[i];
5674 if (reshuffle_ret) {
5675 ret = mov_write_single_packet(s, pkt);
5678 av_packet_free(&pkt);
5683 return mov_write_single_packet(s, pkt);
5687 // QuickTime chapters involve an additional text track with the chapter names
5688 // as samples, and a tref pointing from the other tracks to the chapter one.
5689 static int mov_create_chapter_track(AVFormatContext *s, int tracknum)
5693 MOVMuxContext *mov = s->priv_data;
5694 MOVTrack *track = &mov->tracks[tracknum];
5695 AVPacket pkt = { .stream_index = tracknum, .flags = AV_PKT_FLAG_KEY };
5698 track->mode = mov->mode;
5699 track->tag = MKTAG('t','e','x','t');
5700 track->timescale = MOV_TIMESCALE;
5701 track->par = avcodec_parameters_alloc();
5703 return AVERROR(ENOMEM);
5704 track->par->codec_type = AVMEDIA_TYPE_SUBTITLE;
5706 // These properties are required to make QT recognize the chapter track
5707 uint8_t chapter_properties[43] = { 0, 0, 0, 0, 0, 0, 0, 1, };
5708 if (ff_alloc_extradata(track->par, sizeof(chapter_properties)))
5709 return AVERROR(ENOMEM);
5710 memcpy(track->par->extradata, chapter_properties, sizeof(chapter_properties));
5712 if (avio_open_dyn_buf(&pb) >= 0) {
5716 /* Stub header (usually for Quicktime chapter track) */
5718 avio_wb32(pb, 0x01); // displayFlags
5719 avio_w8(pb, 0x00); // horizontal justification
5720 avio_w8(pb, 0x00); // vertical justification
5721 avio_w8(pb, 0x00); // bgColourRed
5722 avio_w8(pb, 0x00); // bgColourGreen
5723 avio_w8(pb, 0x00); // bgColourBlue
5724 avio_w8(pb, 0x00); // bgColourAlpha
5726 avio_wb16(pb, 0x00); // defTextBoxTop
5727 avio_wb16(pb, 0x00); // defTextBoxLeft
5728 avio_wb16(pb, 0x00); // defTextBoxBottom
5729 avio_wb16(pb, 0x00); // defTextBoxRight
5731 avio_wb16(pb, 0x00); // startChar
5732 avio_wb16(pb, 0x00); // endChar
5733 avio_wb16(pb, 0x01); // fontID
5734 avio_w8(pb, 0x00); // fontStyleFlags
5735 avio_w8(pb, 0x00); // fontSize
5736 avio_w8(pb, 0x00); // fgColourRed
5737 avio_w8(pb, 0x00); // fgColourGreen
5738 avio_w8(pb, 0x00); // fgColourBlue
5739 avio_w8(pb, 0x00); // fgColourAlpha
5741 avio_wb32(pb, 0x0D); // box size
5742 ffio_wfourcc(pb, "ftab"); // box atom name
5743 avio_wb16(pb, 0x01); // entry count
5745 avio_wb16(pb, 0x01); // font ID
5746 avio_w8(pb, 0x00); // font name length
5748 if ((size = avio_close_dyn_buf(pb, &buf)) > 0) {
5749 track->par->extradata = buf;
5750 track->par->extradata_size = size;
5757 for (i = 0; i < s->nb_chapters; i++) {
5758 AVChapter *c = s->chapters[i];
5759 AVDictionaryEntry *t;
5761 int64_t end = av_rescale_q(c->end, c->time_base, (AVRational){1,MOV_TIMESCALE});
5762 pkt.pts = pkt.dts = av_rescale_q(c->start, c->time_base, (AVRational){1,MOV_TIMESCALE});
5763 pkt.duration = end - pkt.dts;
5765 if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
5766 static const char encd[12] = {
5767 0x00, 0x00, 0x00, 0x0C,
5769 0x00, 0x00, 0x01, 0x00 };
5770 len = strlen(t->value);
5771 pkt.size = len + 2 + 12;
5772 pkt.data = av_malloc(pkt.size);
5774 return AVERROR(ENOMEM);
5775 AV_WB16(pkt.data, len);
5776 memcpy(pkt.data + 2, t->value, len);
5777 memcpy(pkt.data + len + 2, encd, sizeof(encd));
5778 ff_mov_write_packet(s, &pkt);
5779 av_freep(&pkt.data);
5787 static int mov_check_timecode_track(AVFormatContext *s, AVTimecode *tc, int src_index, const char *tcstr)
5791 /* compute the frame number */
5792 ret = av_timecode_init_from_string(tc, find_fps(s, s->streams[src_index]), tcstr, s);
5796 static int mov_create_timecode_track(AVFormatContext *s, int index, int src_index, AVTimecode tc)
5799 MOVMuxContext *mov = s->priv_data;
5800 MOVTrack *track = &mov->tracks[index];
5801 AVStream *src_st = s->streams[src_index];
5802 AVPacket pkt = {.stream_index = index, .flags = AV_PKT_FLAG_KEY, .size = 4};
5803 AVRational rate = find_fps(s, src_st);
5805 /* tmcd track based on video stream */
5806 track->mode = mov->mode;
5807 track->tag = MKTAG('t','m','c','d');
5808 track->src_track = src_index;
5809 track->timescale = mov->tracks[src_index].timescale;
5810 if (tc.flags & AV_TIMECODE_FLAG_DROPFRAME)
5811 track->timecode_flags |= MOV_TIMECODE_FLAG_DROPFRAME;
5813 /* set st to src_st for metadata access*/
5816 /* encode context: tmcd data stream */
5817 track->par = avcodec_parameters_alloc();
5819 return AVERROR(ENOMEM);
5820 track->par->codec_type = AVMEDIA_TYPE_DATA;
5821 track->par->codec_tag = track->tag;
5822 track->st->avg_frame_rate = av_inv_q(rate);
5824 /* the tmcd track just contains one packet with the frame number */
5825 pkt.data = av_malloc(pkt.size);
5827 return AVERROR(ENOMEM);
5828 AV_WB32(pkt.data, tc.start);
5829 ret = ff_mov_write_packet(s, &pkt);
5835 * st->disposition controls the "enabled" flag in the tkhd tag.
5836 * QuickTime will not play a track if it is not enabled. So make sure
5837 * that one track of each type (audio, video, subtitle) is enabled.
5839 * Subtitles are special. For audio and video, setting "enabled" also
5840 * makes the track "default" (i.e. it is rendered when played). For
5841 * subtitles, an "enabled" subtitle is not rendered by default, but
5842 * if no subtitle is enabled, the subtitle menu in QuickTime will be
5845 static void enable_tracks(AVFormatContext *s)
5847 MOVMuxContext *mov = s->priv_data;
5849 int enabled[AVMEDIA_TYPE_NB];
5850 int first[AVMEDIA_TYPE_NB];
5852 for (i = 0; i < AVMEDIA_TYPE_NB; i++) {
5857 for (i = 0; i < s->nb_streams; i++) {
5858 AVStream *st = s->streams[i];
5860 if (st->codecpar->codec_type <= AVMEDIA_TYPE_UNKNOWN ||
5861 st->codecpar->codec_type >= AVMEDIA_TYPE_NB ||
5865 if (first[st->codecpar->codec_type] < 0)
5866 first[st->codecpar->codec_type] = i;
5867 if (st->disposition & AV_DISPOSITION_DEFAULT) {
5868 mov->tracks[i].flags |= MOV_TRACK_ENABLED;
5869 enabled[st->codecpar->codec_type]++;
5873 for (i = 0; i < AVMEDIA_TYPE_NB; i++) {
5875 case AVMEDIA_TYPE_VIDEO:
5876 case AVMEDIA_TYPE_AUDIO:
5877 case AVMEDIA_TYPE_SUBTITLE:
5879 mov->per_stream_grouping = 1;
5880 if (!enabled[i] && first[i] >= 0)
5881 mov->tracks[first[i]].flags |= MOV_TRACK_ENABLED;
5887 static void mov_free(AVFormatContext *s)
5889 MOVMuxContext *mov = s->priv_data;
5892 if (mov->chapter_track) {
5893 if (mov->tracks[mov->chapter_track].par)
5894 av_freep(&mov->tracks[mov->chapter_track].par->extradata);
5895 av_freep(&mov->tracks[mov->chapter_track].par);
5898 for (i = 0; i < mov->nb_streams; i++) {
5899 if (mov->tracks[i].tag == MKTAG('r','t','p',' '))
5900 ff_mov_close_hinting(&mov->tracks[i]);
5901 else if (mov->tracks[i].tag == MKTAG('t','m','c','d') && mov->nb_meta_tmcd)
5902 av_freep(&mov->tracks[i].par);
5903 av_freep(&mov->tracks[i].cluster);
5904 av_freep(&mov->tracks[i].frag_info);
5905 av_packet_unref(&mov->tracks[i].cover_image);
5907 if (mov->tracks[i].vos_len)
5908 av_freep(&mov->tracks[i].vos_data);
5910 ff_mov_cenc_free(&mov->tracks[i].cenc);
5913 av_freep(&mov->tracks);
5916 static uint32_t rgb_to_yuv(uint32_t rgb)
5921 r = (rgb >> 16) & 0xFF;
5922 g = (rgb >> 8) & 0xFF;
5925 y = av_clip_uint8(( 16000 + 257 * r + 504 * g + 98 * b)/1000);
5926 cb = av_clip_uint8((128000 - 148 * r - 291 * g + 439 * b)/1000);
5927 cr = av_clip_uint8((128000 + 439 * r - 368 * g - 71 * b)/1000);
5929 return (y << 16) | (cr << 8) | cb;
5932 static int mov_create_dvd_sub_decoder_specific_info(MOVTrack *track,
5935 int i, width = 720, height = 480;
5936 int have_palette = 0, have_size = 0;
5937 uint32_t palette[16];
5938 char *cur = st->codecpar->extradata;
5940 while (cur && *cur) {
5941 if (strncmp("palette:", cur, 8) == 0) {
5943 count = sscanf(cur + 8,
5944 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
5945 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
5946 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
5947 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32"",
5948 &palette[ 0], &palette[ 1], &palette[ 2], &palette[ 3],
5949 &palette[ 4], &palette[ 5], &palette[ 6], &palette[ 7],
5950 &palette[ 8], &palette[ 9], &palette[10], &palette[11],
5951 &palette[12], &palette[13], &palette[14], &palette[15]);
5953 for (i = 0; i < count; i++) {
5954 palette[i] = rgb_to_yuv(palette[i]);
5957 } else if (!strncmp("size:", cur, 5)) {
5958 sscanf(cur + 5, "%dx%d", &width, &height);
5961 if (have_palette && have_size)
5963 cur += strcspn(cur, "\n\r");
5964 cur += strspn(cur, "\n\r");
5967 track->vos_data = av_malloc(16*4);
5968 if (!track->vos_data)
5969 return AVERROR(ENOMEM);
5970 for (i = 0; i < 16; i++) {
5971 AV_WB32(track->vos_data + i * 4, palette[i]);
5973 track->vos_len = 16 * 4;
5975 st->codecpar->width = width;
5976 st->codecpar->height = track->height = height;
5981 static int mov_init(AVFormatContext *s)
5983 MOVMuxContext *mov = s->priv_data;
5984 AVDictionaryEntry *global_tcr = av_dict_get(s->metadata, "timecode", NULL, 0);
5989 /* Default mode == MP4 */
5990 mov->mode = MODE_MP4;
5993 if (!strcmp("3gp", s->oformat->name)) mov->mode = MODE_3GP;
5994 else if (!strcmp("3g2", s->oformat->name)) mov->mode = MODE_3GP|MODE_3G2;
5995 else if (!strcmp("mov", s->oformat->name)) mov->mode = MODE_MOV;
5996 else if (!strcmp("psp", s->oformat->name)) mov->mode = MODE_PSP;
5997 else if (!strcmp("ipod",s->oformat->name)) mov->mode = MODE_IPOD;
5998 else if (!strcmp("ismv",s->oformat->name)) mov->mode = MODE_ISM;
5999 else if (!strcmp("f4v", s->oformat->name)) mov->mode = MODE_F4V;
6002 if (mov->flags & FF_MOV_FLAG_DELAY_MOOV)
6003 mov->flags |= FF_MOV_FLAG_EMPTY_MOOV;
6005 /* Set the FRAGMENT flag if any of the fragmentation methods are
6007 if (mov->max_fragment_duration || mov->max_fragment_size ||
6008 mov->flags & (FF_MOV_FLAG_EMPTY_MOOV |
6009 FF_MOV_FLAG_FRAG_KEYFRAME |
6010 FF_MOV_FLAG_FRAG_CUSTOM |
6011 FF_MOV_FLAG_FRAG_EVERY_FRAME))
6012 mov->flags |= FF_MOV_FLAG_FRAGMENT;
6014 /* Set other implicit flags immediately */
6015 if (mov->mode == MODE_ISM)
6016 mov->flags |= FF_MOV_FLAG_EMPTY_MOOV | FF_MOV_FLAG_SEPARATE_MOOF |
6017 FF_MOV_FLAG_FRAGMENT;
6018 if (mov->flags & FF_MOV_FLAG_DASH)
6019 mov->flags |= FF_MOV_FLAG_FRAGMENT | FF_MOV_FLAG_EMPTY_MOOV |
6020 FF_MOV_FLAG_DEFAULT_BASE_MOOF;
6022 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV && s->flags & AVFMT_FLAG_AUTO_BSF) {
6023 av_log(s, AV_LOG_VERBOSE, "Empty MOOV enabled; disabling automatic bitstream filtering\n");
6024 s->flags &= ~AVFMT_FLAG_AUTO_BSF;
6027 if (mov->flags & FF_MOV_FLAG_FASTSTART) {
6028 mov->reserved_moov_size = -1;
6031 if (mov->use_editlist < 0) {
6032 mov->use_editlist = 1;
6033 if (mov->flags & FF_MOV_FLAG_FRAGMENT &&
6034 !(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
6035 // If we can avoid needing an edit list by shifting the
6036 // tracks, prefer that over (trying to) write edit lists
6037 // in fragmented output.
6038 if (s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO ||
6039 s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO)
6040 mov->use_editlist = 0;
6043 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV &&
6044 !(mov->flags & FF_MOV_FLAG_DELAY_MOOV) && mov->use_editlist)
6045 av_log(s, AV_LOG_WARNING, "No meaningful edit list will be written when using empty_moov without delay_moov\n");
6047 if (!mov->use_editlist && s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO)
6048 s->avoid_negative_ts = AVFMT_AVOID_NEG_TS_MAKE_ZERO;
6050 /* Clear the omit_tfhd_offset flag if default_base_moof is set;
6051 * if the latter is set that's enough and omit_tfhd_offset doesn't
6052 * add anything extra on top of that. */
6053 if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET &&
6054 mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)
6055 mov->flags &= ~FF_MOV_FLAG_OMIT_TFHD_OFFSET;
6057 if (mov->frag_interleave &&
6058 mov->flags & (FF_MOV_FLAG_OMIT_TFHD_OFFSET | FF_MOV_FLAG_SEPARATE_MOOF)) {
6059 av_log(s, AV_LOG_ERROR,
6060 "Sample interleaving in fragments is mutually exclusive with "
6061 "omit_tfhd_offset and separate_moof\n");
6062 return AVERROR(EINVAL);
6065 /* Non-seekable output is ok if using fragmentation. If ism_lookahead
6066 * is enabled, we don't support non-seekable output at all. */
6067 if (!(s->pb->seekable & AVIO_SEEKABLE_NORMAL) &&
6068 (!(mov->flags & FF_MOV_FLAG_FRAGMENT) || mov->ism_lookahead)) {
6069 av_log(s, AV_LOG_ERROR, "muxer does not support non seekable output\n");
6070 return AVERROR(EINVAL);
6073 mov->nb_streams = s->nb_streams;
6074 if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters)
6075 mov->chapter_track = mov->nb_streams++;
6077 if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
6078 for (i = 0; i < s->nb_streams; i++)
6079 if (rtp_hinting_needed(s->streams[i]))
6083 if ( mov->write_tmcd == -1 && (mov->mode == MODE_MOV || mov->mode == MODE_MP4)
6084 || mov->write_tmcd == 1) {
6085 /* +1 tmcd track for each video stream with a timecode */
6086 for (i = 0; i < s->nb_streams; i++) {
6087 AVStream *st = s->streams[i];
6088 AVDictionaryEntry *t = global_tcr;
6089 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
6090 (t || (t=av_dict_get(st->metadata, "timecode", NULL, 0)))) {
6092 ret = mov_check_timecode_track(s, &tc, i, t->value);
6094 mov->nb_meta_tmcd++;
6098 /* check if there is already a tmcd track to remux */
6099 if (mov->nb_meta_tmcd) {
6100 for (i = 0; i < s->nb_streams; i++) {
6101 AVStream *st = s->streams[i];
6102 if (st->codecpar->codec_tag == MKTAG('t','m','c','d')) {
6103 av_log(s, AV_LOG_WARNING, "You requested a copy of the original timecode track "
6104 "so timecode metadata are now ignored\n");
6105 mov->nb_meta_tmcd = 0;
6110 mov->nb_streams += mov->nb_meta_tmcd;
6113 // Reserve an extra stream for chapters for the case where chapters
6114 // are written in the trailer
6115 mov->tracks = av_mallocz_array((mov->nb_streams + 1), sizeof(*mov->tracks));
6117 return AVERROR(ENOMEM);
6119 if (mov->encryption_scheme_str != NULL && strcmp(mov->encryption_scheme_str, "none") != 0) {
6120 if (strcmp(mov->encryption_scheme_str, "cenc-aes-ctr") == 0) {
6121 mov->encryption_scheme = MOV_ENC_CENC_AES_CTR;
6123 if (mov->encryption_key_len != AES_CTR_KEY_SIZE) {
6124 av_log(s, AV_LOG_ERROR, "Invalid encryption key len %d expected %d\n",
6125 mov->encryption_key_len, AES_CTR_KEY_SIZE);
6126 return AVERROR(EINVAL);
6129 if (mov->encryption_kid_len != CENC_KID_SIZE) {
6130 av_log(s, AV_LOG_ERROR, "Invalid encryption kid len %d expected %d\n",
6131 mov->encryption_kid_len, CENC_KID_SIZE);
6132 return AVERROR(EINVAL);
6135 av_log(s, AV_LOG_ERROR, "unsupported encryption scheme %s\n",
6136 mov->encryption_scheme_str);
6137 return AVERROR(EINVAL);
6141 for (i = 0; i < s->nb_streams; i++) {
6142 AVStream *st= s->streams[i];
6143 MOVTrack *track= &mov->tracks[i];
6144 AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0);
6147 track->par = st->codecpar;
6148 track->language = ff_mov_iso639_to_lang(lang?lang->value:"und", mov->mode!=MODE_MOV);
6149 if (track->language < 0)
6150 track->language = 0;
6151 track->mode = mov->mode;
6152 track->tag = mov_find_codec_tag(s, track);
6154 av_log(s, AV_LOG_ERROR, "Could not find tag for codec %s in stream #%d, "
6155 "codec not currently supported in container\n",
6156 avcodec_get_name(st->codecpar->codec_id), i);
6157 return AVERROR(EINVAL);
6159 /* If hinting of this track is enabled by a later hint track,
6160 * this is updated. */
6161 track->hint_track = -1;
6162 track->start_dts = AV_NOPTS_VALUE;
6163 track->start_cts = AV_NOPTS_VALUE;
6164 track->end_pts = AV_NOPTS_VALUE;
6165 track->dts_shift = AV_NOPTS_VALUE;
6166 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
6167 if (track->tag == MKTAG('m','x','3','p') || track->tag == MKTAG('m','x','3','n') ||
6168 track->tag == MKTAG('m','x','4','p') || track->tag == MKTAG('m','x','4','n') ||
6169 track->tag == MKTAG('m','x','5','p') || track->tag == MKTAG('m','x','5','n')) {
6170 if (st->codecpar->width != 720 || (st->codecpar->height != 608 && st->codecpar->height != 512)) {
6171 av_log(s, AV_LOG_ERROR, "D-10/IMX must use 720x608 or 720x512 video resolution\n");
6172 return AVERROR(EINVAL);
6174 track->height = track->tag >> 24 == 'n' ? 486 : 576;
6176 if (mov->video_track_timescale) {
6177 track->timescale = mov->video_track_timescale;
6179 track->timescale = st->time_base.den;
6180 while(track->timescale < 10000)
6181 track->timescale *= 2;
6183 if (st->codecpar->width > 65535 || st->codecpar->height > 65535) {
6184 av_log(s, AV_LOG_ERROR, "Resolution %dx%d too large for mov/mp4\n", st->codecpar->width, st->codecpar->height);
6185 return AVERROR(EINVAL);
6187 if (track->mode == MODE_MOV && track->timescale > 100000)
6188 av_log(s, AV_LOG_WARNING,
6189 "WARNING codec timebase is very high. If duration is too long,\n"
6190 "file may not be playable by quicktime. Specify a shorter timebase\n"
6191 "or choose different container.\n");
6192 if (track->mode == MODE_MOV &&
6193 track->par->codec_id == AV_CODEC_ID_RAWVIDEO &&
6194 track->tag == MKTAG('r','a','w',' ')) {
6195 enum AVPixelFormat pix_fmt = track->par->format;
6196 if (pix_fmt == AV_PIX_FMT_NONE && track->par->bits_per_coded_sample == 1)
6197 pix_fmt = AV_PIX_FMT_MONOWHITE;
6198 track->is_unaligned_qt_rgb =
6199 pix_fmt == AV_PIX_FMT_RGB24 ||
6200 pix_fmt == AV_PIX_FMT_BGR24 ||
6201 pix_fmt == AV_PIX_FMT_PAL8 ||
6202 pix_fmt == AV_PIX_FMT_GRAY8 ||
6203 pix_fmt == AV_PIX_FMT_MONOWHITE ||
6204 pix_fmt == AV_PIX_FMT_MONOBLACK;
6206 if (track->par->codec_id == AV_CODEC_ID_VP9) {
6207 if (track->mode != MODE_MP4) {
6208 av_log(s, AV_LOG_ERROR, "VP9 only supported in MP4.\n");
6209 return AVERROR(EINVAL);
6211 } else if (track->par->codec_id == AV_CODEC_ID_AV1) {
6212 /* spec is not finished, so forbid for now */
6213 av_log(s, AV_LOG_ERROR, "AV1 muxing is currently not supported.\n");
6214 return AVERROR_PATCHWELCOME;
6215 } else if (track->par->codec_id == AV_CODEC_ID_VP8) {
6216 /* altref frames handling is not defined in the spec as of version v1.0,
6217 * so just forbid muxing VP8 streams altogether until a new version does */
6218 av_log(s, AV_LOG_ERROR, "VP8 muxing is currently not supported.\n");
6219 return AVERROR_PATCHWELCOME;
6221 } else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
6222 track->timescale = st->codecpar->sample_rate;
6223 if (!st->codecpar->frame_size && !av_get_bits_per_sample(st->codecpar->codec_id)) {
6224 av_log(s, AV_LOG_WARNING, "track %d: codec frame size is not set\n", i);
6225 track->audio_vbr = 1;
6226 }else if (st->codecpar->codec_id == AV_CODEC_ID_ADPCM_MS ||
6227 st->codecpar->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
6228 st->codecpar->codec_id == AV_CODEC_ID_ILBC){
6229 if (!st->codecpar->block_align) {
6230 av_log(s, AV_LOG_ERROR, "track %d: codec block align is not set for adpcm\n", i);
6231 return AVERROR(EINVAL);
6233 track->sample_size = st->codecpar->block_align;
6234 }else if (st->codecpar->frame_size > 1){ /* assume compressed audio */
6235 track->audio_vbr = 1;
6237 track->sample_size = (av_get_bits_per_sample(st->codecpar->codec_id) >> 3) * st->codecpar->channels;
6239 if (st->codecpar->codec_id == AV_CODEC_ID_ILBC ||
6240 st->codecpar->codec_id == AV_CODEC_ID_ADPCM_IMA_QT) {
6241 track->audio_vbr = 1;
6243 if (track->mode != MODE_MOV &&
6244 track->par->codec_id == AV_CODEC_ID_MP3 && track->timescale < 16000) {
6245 if (s->strict_std_compliance >= FF_COMPLIANCE_NORMAL) {
6246 av_log(s, AV_LOG_ERROR, "track %d: muxing mp3 at %dhz is not standard, to mux anyway set strict to -1\n",
6247 i, track->par->sample_rate);
6248 return AVERROR(EINVAL);
6250 av_log(s, AV_LOG_WARNING, "track %d: muxing mp3 at %dhz is not standard in MP4\n",
6251 i, track->par->sample_rate);
6254 if (track->par->codec_id == AV_CODEC_ID_FLAC ||
6255 track->par->codec_id == AV_CODEC_ID_OPUS) {
6256 if (track->mode != MODE_MP4) {
6257 av_log(s, AV_LOG_ERROR, "%s only supported in MP4.\n", avcodec_get_name(track->par->codec_id));
6258 return AVERROR(EINVAL);
6260 if (s->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
6261 av_log(s, AV_LOG_ERROR,
6262 "%s in MP4 support is experimental, add "
6263 "'-strict %d' if you want to use it.\n",
6264 avcodec_get_name(track->par->codec_id), FF_COMPLIANCE_EXPERIMENTAL);
6265 return AVERROR_EXPERIMENTAL;
6268 } else if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) {
6269 track->timescale = st->time_base.den;
6270 } else if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA) {
6271 track->timescale = st->time_base.den;
6273 track->timescale = MOV_TIMESCALE;
6276 track->height = st->codecpar->height;
6277 /* The ism specific timescale isn't mandatory, but is assumed by
6278 * some tools, such as mp4split. */
6279 if (mov->mode == MODE_ISM)
6280 track->timescale = 10000000;
6282 avpriv_set_pts_info(st, 64, 1, track->timescale);
6284 if (mov->encryption_scheme == MOV_ENC_CENC_AES_CTR) {
6285 ret = ff_mov_cenc_init(&track->cenc, mov->encryption_key,
6286 track->par->codec_id == AV_CODEC_ID_H264, s->flags & AVFMT_FLAG_BITEXACT);
6296 static int mov_write_header(AVFormatContext *s)
6298 AVIOContext *pb = s->pb;
6299 MOVMuxContext *mov = s->priv_data;
6300 AVDictionaryEntry *t, *global_tcr = av_dict_get(s->metadata, "timecode", NULL, 0);
6301 int i, ret, hint_track = 0, tmcd_track = 0, nb_tracks = s->nb_streams;
6303 if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters)
6306 if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
6307 hint_track = nb_tracks;
6308 for (i = 0; i < s->nb_streams; i++)
6309 if (rtp_hinting_needed(s->streams[i]))
6313 if (mov->mode == MODE_MOV || mov->mode == MODE_MP4)
6314 tmcd_track = nb_tracks;
6316 for (i = 0; i < s->nb_streams; i++) {
6318 AVStream *st= s->streams[i];
6319 MOVTrack *track= &mov->tracks[i];
6321 /* copy extradata if it exists */
6322 if (st->codecpar->extradata_size) {
6323 if (st->codecpar->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
6324 mov_create_dvd_sub_decoder_specific_info(track, st);
6325 else if (!TAG_IS_AVCI(track->tag) && st->codecpar->codec_id != AV_CODEC_ID_DNXHD) {
6326 track->vos_len = st->codecpar->extradata_size;
6327 track->vos_data = av_malloc(track->vos_len);
6328 if (!track->vos_data) {
6329 return AVERROR(ENOMEM);
6331 memcpy(track->vos_data, st->codecpar->extradata, track->vos_len);
6335 if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ||
6336 track->par->channel_layout != AV_CH_LAYOUT_MONO)
6339 for (j = 0; j < s->nb_streams; j++) {
6340 AVStream *stj= s->streams[j];
6341 MOVTrack *trackj= &mov->tracks[j];
6345 if (stj->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ||
6346 trackj->par->channel_layout != AV_CH_LAYOUT_MONO ||
6347 trackj->language != track->language ||
6348 trackj->tag != track->tag
6351 track->multichannel_as_mono++;
6355 if (!(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
6356 if ((ret = mov_write_identification(pb, s)) < 0)
6360 if (mov->reserved_moov_size){
6361 mov->reserved_header_pos = avio_tell(pb);
6362 if (mov->reserved_moov_size > 0)
6363 avio_skip(pb, mov->reserved_moov_size);
6366 if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
6367 /* If no fragmentation options have been set, set a default. */
6368 if (!(mov->flags & (FF_MOV_FLAG_FRAG_KEYFRAME |
6369 FF_MOV_FLAG_FRAG_CUSTOM |
6370 FF_MOV_FLAG_FRAG_EVERY_FRAME)) &&
6371 !mov->max_fragment_duration && !mov->max_fragment_size)
6372 mov->flags |= FF_MOV_FLAG_FRAG_KEYFRAME;
6374 if (mov->flags & FF_MOV_FLAG_FASTSTART)
6375 mov->reserved_header_pos = avio_tell(pb);
6376 mov_write_mdat_tag(pb, mov);
6379 ff_parse_creation_time_metadata(s, &mov->time, 1);
6381 mov->time += 0x7C25B080; // 1970 based -> 1904 based
6383 if (mov->chapter_track)
6384 if ((ret = mov_create_chapter_track(s, mov->chapter_track)) < 0)
6387 if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
6388 for (i = 0; i < s->nb_streams; i++) {
6389 if (rtp_hinting_needed(s->streams[i])) {
6390 if ((ret = ff_mov_init_hinting(s, hint_track, i)) < 0)
6397 if (mov->nb_meta_tmcd) {
6398 /* Initialize the tmcd tracks */
6399 for (i = 0; i < s->nb_streams; i++) {
6400 AVStream *st = s->streams[i];
6403 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
6406 t = av_dict_get(st->metadata, "timecode", NULL, 0);
6409 if (mov_check_timecode_track(s, &tc, i, t->value) < 0)
6411 if ((ret = mov_create_timecode_track(s, tmcd_track, i, tc)) < 0)
6420 if (mov->flags & FF_MOV_FLAG_ISML)
6421 mov_write_isml_manifest(pb, mov, s);
6423 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV &&
6424 !(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
6425 if ((ret = mov_write_moov_tag(pb, mov, s)) < 0)
6428 mov->moov_written = 1;
6429 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
6430 mov->reserved_header_pos = avio_tell(pb);
6436 static int get_moov_size(AVFormatContext *s)
6439 AVIOContext *moov_buf;
6440 MOVMuxContext *mov = s->priv_data;
6442 if ((ret = ffio_open_null_buf(&moov_buf)) < 0)
6444 if ((ret = mov_write_moov_tag(moov_buf, mov, s)) < 0)
6446 return ffio_close_null_buf(moov_buf);
6449 static int get_sidx_size(AVFormatContext *s)
6453 MOVMuxContext *mov = s->priv_data;
6455 if ((ret = ffio_open_null_buf(&buf)) < 0)
6457 mov_write_sidx_tags(buf, mov, -1, 0);
6458 return ffio_close_null_buf(buf);
6462 * This function gets the moov size if moved to the top of the file: the chunk
6463 * offset table can switch between stco (32-bit entries) to co64 (64-bit
6464 * entries) when the moov is moved to the beginning, so the size of the moov
6465 * would change. It also updates the chunk offset tables.
6467 static int compute_moov_size(AVFormatContext *s)
6469 int i, moov_size, moov_size2;
6470 MOVMuxContext *mov = s->priv_data;
6472 moov_size = get_moov_size(s);
6476 for (i = 0; i < mov->nb_streams; i++)
6477 mov->tracks[i].data_offset += moov_size;
6479 moov_size2 = get_moov_size(s);
6483 /* if the size changed, we just switched from stco to co64 and need to
6484 * update the offsets */
6485 if (moov_size2 != moov_size)
6486 for (i = 0; i < mov->nb_streams; i++)
6487 mov->tracks[i].data_offset += moov_size2 - moov_size;
6492 static int compute_sidx_size(AVFormatContext *s)
6495 MOVMuxContext *mov = s->priv_data;
6497 sidx_size = get_sidx_size(s);
6501 for (i = 0; i < mov->nb_streams; i++)
6502 mov->tracks[i].data_offset += sidx_size;
6507 static int shift_data(AVFormatContext *s)
6509 int ret = 0, moov_size;
6510 MOVMuxContext *mov = s->priv_data;
6511 int64_t pos, pos_end = avio_tell(s->pb);
6512 uint8_t *buf, *read_buf[2];
6513 int read_buf_id = 0;
6515 AVIOContext *read_pb;
6517 if (mov->flags & FF_MOV_FLAG_FRAGMENT)
6518 moov_size = compute_sidx_size(s);
6520 moov_size = compute_moov_size(s);
6524 buf = av_malloc(moov_size * 2);
6526 return AVERROR(ENOMEM);
6528 read_buf[1] = buf + moov_size;
6530 /* Shift the data: the AVIO context of the output can only be used for
6531 * writing, so we re-open the same output, but for reading. It also avoids
6532 * a read/seek/write/seek back and forth. */
6534 ret = s->io_open(s, &read_pb, s->url, AVIO_FLAG_READ, NULL);
6536 av_log(s, AV_LOG_ERROR, "Unable to re-open %s output file for "
6537 "the second pass (faststart)\n", s->url);
6541 /* mark the end of the shift to up to the last data we wrote, and get ready
6543 pos_end = avio_tell(s->pb);
6544 avio_seek(s->pb, mov->reserved_header_pos + moov_size, SEEK_SET);
6546 /* start reading at where the new moov will be placed */
6547 avio_seek(read_pb, mov->reserved_header_pos, SEEK_SET);
6548 pos = avio_tell(read_pb);
6550 #define READ_BLOCK do { \
6551 read_size[read_buf_id] = avio_read(read_pb, read_buf[read_buf_id], moov_size); \
6555 /* shift data by chunk of at most moov_size */
6560 n = read_size[read_buf_id];
6563 avio_write(s->pb, read_buf[read_buf_id], n);
6565 } while (pos < pos_end);
6566 ff_format_io_close(s, &read_pb);
6573 static int mov_write_trailer(AVFormatContext *s)
6575 MOVMuxContext *mov = s->priv_data;
6576 AVIOContext *pb = s->pb;
6581 if (mov->need_rewrite_extradata) {
6582 for (i = 0; i < s->nb_streams; i++) {
6583 MOVTrack *track = &mov->tracks[i];
6584 AVCodecParameters *par = track->par;
6586 track->vos_len = par->extradata_size;
6587 track->vos_data = av_malloc(track->vos_len);
6588 if (!track->vos_data)
6589 return AVERROR(ENOMEM);
6590 memcpy(track->vos_data, par->extradata, track->vos_len);
6592 mov->need_rewrite_extradata = 0;
6596 * Before actually writing the trailer, make sure that there are no
6597 * dangling subtitles, that need a terminating sample.
6599 for (i = 0; i < mov->nb_streams; i++) {
6600 MOVTrack *trk = &mov->tracks[i];
6601 if (trk->par->codec_id == AV_CODEC_ID_MOV_TEXT &&
6602 !trk->last_sample_is_subtitle_end) {
6603 mov_write_subtitle_end_packet(s, i, trk->track_duration);
6604 trk->last_sample_is_subtitle_end = 1;
6608 // If there were no chapters when the header was written, but there
6609 // are chapters now, write them in the trailer. This only works
6610 // when we are not doing fragments.
6611 if (!mov->chapter_track && !(mov->flags & FF_MOV_FLAG_FRAGMENT)) {
6612 if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters) {
6613 mov->chapter_track = mov->nb_streams++;
6614 if ((res = mov_create_chapter_track(s, mov->chapter_track)) < 0)
6619 if (!(mov->flags & FF_MOV_FLAG_FRAGMENT)) {
6620 moov_pos = avio_tell(pb);
6622 /* Write size of mdat tag */
6623 if (mov->mdat_size + 8 <= UINT32_MAX) {
6624 avio_seek(pb, mov->mdat_pos, SEEK_SET);
6625 avio_wb32(pb, mov->mdat_size + 8);
6627 /* overwrite 'wide' placeholder atom */
6628 avio_seek(pb, mov->mdat_pos - 8, SEEK_SET);
6629 /* special value: real atom size will be 64 bit value after
6632 ffio_wfourcc(pb, "mdat");
6633 avio_wb64(pb, mov->mdat_size + 16);
6635 avio_seek(pb, mov->reserved_moov_size > 0 ? mov->reserved_header_pos : moov_pos, SEEK_SET);
6637 if (mov->flags & FF_MOV_FLAG_FASTSTART) {
6638 av_log(s, AV_LOG_INFO, "Starting second pass: moving the moov atom to the beginning of the file\n");
6639 res = shift_data(s);
6642 avio_seek(pb, mov->reserved_header_pos, SEEK_SET);
6643 if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
6645 } else if (mov->reserved_moov_size > 0) {
6647 if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
6649 size = mov->reserved_moov_size - (avio_tell(pb) - mov->reserved_header_pos);
6651 av_log(s, AV_LOG_ERROR, "reserved_moov_size is too small, needed %"PRId64" additional\n", 8-size);
6652 return AVERROR(EINVAL);
6654 avio_wb32(pb, size);
6655 ffio_wfourcc(pb, "free");
6656 ffio_fill(pb, 0, size - 8);
6657 avio_seek(pb, moov_pos, SEEK_SET);
6659 if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
6664 mov_auto_flush_fragment(s, 1);
6665 for (i = 0; i < mov->nb_streams; i++)
6666 mov->tracks[i].data_offset = 0;
6667 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) {
6669 av_log(s, AV_LOG_INFO, "Starting second pass: inserting sidx atoms\n");
6670 res = shift_data(s);
6673 end = avio_tell(pb);
6674 avio_seek(pb, mov->reserved_header_pos, SEEK_SET);
6675 mov_write_sidx_tags(pb, mov, -1, 0);
6676 avio_seek(pb, end, SEEK_SET);
6677 avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_TRAILER);
6678 mov_write_mfra_tag(pb, mov);
6679 } else if (!(mov->flags & FF_MOV_FLAG_SKIP_TRAILER)) {
6680 avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_TRAILER);
6681 mov_write_mfra_tag(pb, mov);
6688 static int mov_check_bitstream(struct AVFormatContext *s, const AVPacket *pkt)
6691 AVStream *st = s->streams[pkt->stream_index];
6693 if (st->codecpar->codec_id == AV_CODEC_ID_AAC) {
6694 if (pkt->size > 2 && (AV_RB16(pkt->data) & 0xfff0) == 0xfff0)
6695 ret = ff_stream_add_bitstream_filter(st, "aac_adtstoasc", NULL);
6696 } else if (st->codecpar->codec_id == AV_CODEC_ID_VP9) {
6697 ret = ff_stream_add_bitstream_filter(st, "vp9_superframe", NULL);
6703 static const AVCodecTag codec_3gp_tags[] = {
6704 { AV_CODEC_ID_H263, MKTAG('s','2','6','3') },
6705 { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
6706 { AV_CODEC_ID_MPEG4, MKTAG('m','p','4','v') },
6707 { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
6708 { AV_CODEC_ID_AMR_NB, MKTAG('s','a','m','r') },
6709 { AV_CODEC_ID_AMR_WB, MKTAG('s','a','w','b') },
6710 { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
6711 { AV_CODEC_ID_NONE, 0 },
6714 const AVCodecTag codec_mp4_tags[] = {
6715 { AV_CODEC_ID_MPEG4 , MKTAG('m', 'p', '4', 'v') },
6716 { AV_CODEC_ID_H264 , MKTAG('a', 'v', 'c', '1') },
6717 { AV_CODEC_ID_H264 , MKTAG('a', 'v', 'c', '3') },
6718 { AV_CODEC_ID_HEVC , MKTAG('h', 'e', 'v', '1') },
6719 { AV_CODEC_ID_HEVC , MKTAG('h', 'v', 'c', '1') },
6720 { AV_CODEC_ID_MPEG2VIDEO , MKTAG('m', 'p', '4', 'v') },
6721 { AV_CODEC_ID_MPEG1VIDEO , MKTAG('m', 'p', '4', 'v') },
6722 { AV_CODEC_ID_MJPEG , MKTAG('m', 'p', '4', 'v') },
6723 { AV_CODEC_ID_PNG , MKTAG('m', 'p', '4', 'v') },
6724 { AV_CODEC_ID_JPEG2000 , MKTAG('m', 'p', '4', 'v') },
6725 { AV_CODEC_ID_VC1 , MKTAG('v', 'c', '-', '1') },
6726 { AV_CODEC_ID_DIRAC , MKTAG('d', 'r', 'a', 'c') },
6727 { AV_CODEC_ID_TSCC2 , MKTAG('m', 'p', '4', 'v') },
6728 { AV_CODEC_ID_VP9 , MKTAG('v', 'p', '0', '9') },
6729 { AV_CODEC_ID_AAC , MKTAG('m', 'p', '4', 'a') },
6730 { AV_CODEC_ID_MP4ALS , MKTAG('m', 'p', '4', 'a') },
6731 { AV_CODEC_ID_MP3 , MKTAG('m', 'p', '4', 'a') },
6732 { AV_CODEC_ID_MP2 , MKTAG('m', 'p', '4', 'a') },
6733 { AV_CODEC_ID_AC3 , MKTAG('a', 'c', '-', '3') },
6734 { AV_CODEC_ID_EAC3 , MKTAG('e', 'c', '-', '3') },
6735 { AV_CODEC_ID_DTS , MKTAG('m', 'p', '4', 'a') },
6736 { AV_CODEC_ID_FLAC , MKTAG('f', 'L', 'a', 'C') },
6737 { AV_CODEC_ID_OPUS , MKTAG('O', 'p', 'u', 's') },
6738 { AV_CODEC_ID_VORBIS , MKTAG('m', 'p', '4', 'a') },
6739 { AV_CODEC_ID_QCELP , MKTAG('m', 'p', '4', 'a') },
6740 { AV_CODEC_ID_EVRC , MKTAG('m', 'p', '4', 'a') },
6741 { AV_CODEC_ID_DVD_SUBTITLE, MKTAG('m', 'p', '4', 's') },
6742 { AV_CODEC_ID_MOV_TEXT , MKTAG('t', 'x', '3', 'g') },
6743 { AV_CODEC_ID_NONE , 0 },
6746 const AVCodecTag codec_ism_tags[] = {
6747 { AV_CODEC_ID_WMAPRO , MKTAG('w', 'm', 'a', ' ') },
6748 { AV_CODEC_ID_NONE , 0 },
6751 static const AVCodecTag codec_ipod_tags[] = {
6752 { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
6753 { AV_CODEC_ID_MPEG4, MKTAG('m','p','4','v') },
6754 { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
6755 { AV_CODEC_ID_ALAC, MKTAG('a','l','a','c') },
6756 { AV_CODEC_ID_AC3, MKTAG('a','c','-','3') },
6757 { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
6758 { AV_CODEC_ID_MOV_TEXT, MKTAG('t','e','x','t') },
6759 { AV_CODEC_ID_NONE, 0 },
6762 static const AVCodecTag codec_f4v_tags[] = {
6763 { AV_CODEC_ID_MP3, MKTAG('.','m','p','3') },
6764 { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
6765 { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
6766 { AV_CODEC_ID_VP6A, MKTAG('V','P','6','A') },
6767 { AV_CODEC_ID_VP6F, MKTAG('V','P','6','F') },
6768 { AV_CODEC_ID_NONE, 0 },
6771 #if CONFIG_MOV_MUXER
6773 AVOutputFormat ff_mov_muxer = {
6775 .long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
6776 .extensions = "mov",
6777 .priv_data_size = sizeof(MOVMuxContext),
6778 .audio_codec = AV_CODEC_ID_AAC,
6779 .video_codec = CONFIG_LIBX264_ENCODER ?
6780 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
6782 .write_header = mov_write_header,
6783 .write_packet = mov_write_packet,
6784 .write_trailer = mov_write_trailer,
6786 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6787 .codec_tag = (const AVCodecTag* const []){
6788 ff_codec_movvideo_tags, ff_codec_movaudio_tags, 0
6790 .check_bitstream = mov_check_bitstream,
6791 .priv_class = &mov_muxer_class,
6794 #if CONFIG_TGP_MUXER
6796 AVOutputFormat ff_tgp_muxer = {
6798 .long_name = NULL_IF_CONFIG_SMALL("3GP (3GPP file format)"),
6799 .extensions = "3gp",
6800 .priv_data_size = sizeof(MOVMuxContext),
6801 .audio_codec = AV_CODEC_ID_AMR_NB,
6802 .video_codec = AV_CODEC_ID_H263,
6804 .write_header = mov_write_header,
6805 .write_packet = mov_write_packet,
6806 .write_trailer = mov_write_trailer,
6808 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6809 .codec_tag = (const AVCodecTag* const []){ codec_3gp_tags, 0 },
6810 .check_bitstream = mov_check_bitstream,
6811 .priv_class = &tgp_muxer_class,
6814 #if CONFIG_MP4_MUXER
6816 AVOutputFormat ff_mp4_muxer = {
6818 .long_name = NULL_IF_CONFIG_SMALL("MP4 (MPEG-4 Part 14)"),
6819 .mime_type = "video/mp4",
6820 .extensions = "mp4",
6821 .priv_data_size = sizeof(MOVMuxContext),
6822 .audio_codec = AV_CODEC_ID_AAC,
6823 .video_codec = CONFIG_LIBX264_ENCODER ?
6824 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
6826 .write_header = mov_write_header,
6827 .write_packet = mov_write_packet,
6828 .write_trailer = mov_write_trailer,
6830 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6831 .codec_tag = (const AVCodecTag* const []){ codec_mp4_tags, 0 },
6832 .check_bitstream = mov_check_bitstream,
6833 .priv_class = &mp4_muxer_class,
6836 #if CONFIG_PSP_MUXER
6838 AVOutputFormat ff_psp_muxer = {
6840 .long_name = NULL_IF_CONFIG_SMALL("PSP MP4 (MPEG-4 Part 14)"),
6841 .extensions = "mp4,psp",
6842 .priv_data_size = sizeof(MOVMuxContext),
6843 .audio_codec = AV_CODEC_ID_AAC,
6844 .video_codec = CONFIG_LIBX264_ENCODER ?
6845 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
6847 .write_header = mov_write_header,
6848 .write_packet = mov_write_packet,
6849 .write_trailer = mov_write_trailer,
6851 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6852 .codec_tag = (const AVCodecTag* const []){ codec_mp4_tags, 0 },
6853 .check_bitstream = mov_check_bitstream,
6854 .priv_class = &psp_muxer_class,
6857 #if CONFIG_TG2_MUXER
6859 AVOutputFormat ff_tg2_muxer = {
6861 .long_name = NULL_IF_CONFIG_SMALL("3GP2 (3GPP2 file format)"),
6862 .extensions = "3g2",
6863 .priv_data_size = sizeof(MOVMuxContext),
6864 .audio_codec = AV_CODEC_ID_AMR_NB,
6865 .video_codec = AV_CODEC_ID_H263,
6867 .write_header = mov_write_header,
6868 .write_packet = mov_write_packet,
6869 .write_trailer = mov_write_trailer,
6871 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6872 .codec_tag = (const AVCodecTag* const []){ codec_3gp_tags, 0 },
6873 .check_bitstream = mov_check_bitstream,
6874 .priv_class = &tg2_muxer_class,
6877 #if CONFIG_IPOD_MUXER
6879 AVOutputFormat ff_ipod_muxer = {
6881 .long_name = NULL_IF_CONFIG_SMALL("iPod H.264 MP4 (MPEG-4 Part 14)"),
6882 .mime_type = "video/mp4",
6883 .extensions = "m4v,m4a,m4b",
6884 .priv_data_size = sizeof(MOVMuxContext),
6885 .audio_codec = AV_CODEC_ID_AAC,
6886 .video_codec = AV_CODEC_ID_H264,
6888 .write_header = mov_write_header,
6889 .write_packet = mov_write_packet,
6890 .write_trailer = mov_write_trailer,
6892 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6893 .codec_tag = (const AVCodecTag* const []){ codec_ipod_tags, 0 },
6894 .check_bitstream = mov_check_bitstream,
6895 .priv_class = &ipod_muxer_class,
6898 #if CONFIG_ISMV_MUXER
6900 AVOutputFormat ff_ismv_muxer = {
6902 .long_name = NULL_IF_CONFIG_SMALL("ISMV/ISMA (Smooth Streaming)"),
6903 .mime_type = "video/mp4",
6904 .extensions = "ismv,isma",
6905 .priv_data_size = sizeof(MOVMuxContext),
6906 .audio_codec = AV_CODEC_ID_AAC,
6907 .video_codec = AV_CODEC_ID_H264,
6909 .write_header = mov_write_header,
6910 .write_packet = mov_write_packet,
6911 .write_trailer = mov_write_trailer,
6913 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6914 .codec_tag = (const AVCodecTag* const []){
6915 codec_mp4_tags, codec_ism_tags, 0 },
6916 .check_bitstream = mov_check_bitstream,
6917 .priv_class = &ismv_muxer_class,
6920 #if CONFIG_F4V_MUXER
6922 AVOutputFormat ff_f4v_muxer = {
6924 .long_name = NULL_IF_CONFIG_SMALL("F4V Adobe Flash Video"),
6925 .mime_type = "application/f4v",
6926 .extensions = "f4v",
6927 .priv_data_size = sizeof(MOVMuxContext),
6928 .audio_codec = AV_CODEC_ID_AAC,
6929 .video_codec = AV_CODEC_ID_H264,
6931 .write_header = mov_write_header,
6932 .write_packet = mov_write_packet,
6933 .write_trailer = mov_write_trailer,
6935 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH,
6936 .codec_tag = (const AVCodecTag* const []){ codec_f4v_tags, 0 },
6937 .check_bitstream = mov_check_bitstream,
6938 .priv_class = &f4v_muxer_class,