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},
104 #define MOV_CLASS(flavor)\
105 static const AVClass flavor ## _muxer_class = {\
106 .class_name = #flavor " muxer",\
107 .item_name = av_default_item_name,\
109 .version = LIBAVUTIL_VERSION_INT,\
112 static int get_moov_size(AVFormatContext *s);
114 static int utf8len(const uint8_t *b)
119 GET_UTF8(val, *b++, return -1;)
125 //FIXME support 64 bit variant with wide placeholders
126 static int64_t update_size(AVIOContext *pb, int64_t pos)
128 int64_t curpos = avio_tell(pb);
129 avio_seek(pb, pos, SEEK_SET);
130 avio_wb32(pb, curpos - pos); /* rewrite size */
131 avio_seek(pb, curpos, SEEK_SET);
136 static int co64_required(const MOVTrack *track)
138 if (track->entry > 0 && track->cluster[track->entry - 1].pos + track->data_offset > UINT32_MAX)
143 static int rtp_hinting_needed(const AVStream *st)
145 /* Add hint tracks for each audio and video stream */
146 return st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ||
147 st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO;
150 /* Chunk offset atom */
151 static int mov_write_stco_tag(AVIOContext *pb, MOVTrack *track)
154 int mode64 = co64_required(track); // use 32 bit size variant if possible
155 int64_t pos = avio_tell(pb);
156 avio_wb32(pb, 0); /* size */
158 ffio_wfourcc(pb, "co64");
160 ffio_wfourcc(pb, "stco");
161 avio_wb32(pb, 0); /* version & flags */
162 avio_wb32(pb, track->chunkCount); /* entry count */
163 for (i = 0; i < track->entry; i++) {
164 if (!track->cluster[i].chunkNum)
167 avio_wb64(pb, track->cluster[i].pos + track->data_offset);
169 avio_wb32(pb, track->cluster[i].pos + track->data_offset);
171 return update_size(pb, pos);
174 /* Sample size atom */
175 static int mov_write_stsz_tag(AVIOContext *pb, MOVTrack *track)
178 int i, j, entries = 0, tst = -1, oldtst = -1;
180 int64_t pos = avio_tell(pb);
181 avio_wb32(pb, 0); /* size */
182 ffio_wfourcc(pb, "stsz");
183 avio_wb32(pb, 0); /* version & flags */
185 for (i = 0; i < track->entry; i++) {
186 tst = track->cluster[i].size / track->cluster[i].entries;
187 if (oldtst != -1 && tst != oldtst)
190 entries += track->cluster[i].entries;
192 if (equalChunks && track->entry) {
193 int sSize = track->entry ? track->cluster[0].size / track->cluster[0].entries : 0;
194 sSize = FFMAX(1, sSize); // adpcm mono case could make sSize == 0
195 avio_wb32(pb, sSize); // sample size
196 avio_wb32(pb, entries); // sample count
198 avio_wb32(pb, 0); // sample size
199 avio_wb32(pb, entries); // sample count
200 for (i = 0; i < track->entry; i++) {
201 for (j = 0; j < track->cluster[i].entries; j++) {
202 avio_wb32(pb, track->cluster[i].size /
203 track->cluster[i].entries);
207 return update_size(pb, pos);
210 /* Sample to chunk atom */
211 static int mov_write_stsc_tag(AVIOContext *pb, MOVTrack *track)
213 int index = 0, oldval = -1, i;
214 int64_t entryPos, curpos;
216 int64_t pos = avio_tell(pb);
217 avio_wb32(pb, 0); /* size */
218 ffio_wfourcc(pb, "stsc");
219 avio_wb32(pb, 0); // version & flags
220 entryPos = avio_tell(pb);
221 avio_wb32(pb, track->chunkCount); // entry count
222 for (i = 0; i < track->entry; i++) {
223 if (oldval != track->cluster[i].samples_in_chunk && track->cluster[i].chunkNum) {
224 avio_wb32(pb, track->cluster[i].chunkNum); // first chunk
225 avio_wb32(pb, track->cluster[i].samples_in_chunk); // samples per chunk
226 avio_wb32(pb, 0x1); // sample description index
227 oldval = track->cluster[i].samples_in_chunk;
231 curpos = avio_tell(pb);
232 avio_seek(pb, entryPos, SEEK_SET);
233 avio_wb32(pb, index); // rewrite size
234 avio_seek(pb, curpos, SEEK_SET);
236 return update_size(pb, pos);
239 /* Sync sample atom */
240 static int mov_write_stss_tag(AVIOContext *pb, MOVTrack *track, uint32_t flag)
242 int64_t curpos, entryPos;
244 int64_t pos = avio_tell(pb);
245 avio_wb32(pb, 0); // size
246 ffio_wfourcc(pb, flag == MOV_SYNC_SAMPLE ? "stss" : "stps");
247 avio_wb32(pb, 0); // version & flags
248 entryPos = avio_tell(pb);
249 avio_wb32(pb, track->entry); // entry count
250 for (i = 0; i < track->entry; i++) {
251 if (track->cluster[i].flags & flag) {
252 avio_wb32(pb, i + 1);
256 curpos = avio_tell(pb);
257 avio_seek(pb, entryPos, SEEK_SET);
258 avio_wb32(pb, index); // rewrite size
259 avio_seek(pb, curpos, SEEK_SET);
260 return update_size(pb, pos);
263 /* Sample dependency atom */
264 static int mov_write_sdtp_tag(AVIOContext *pb, MOVTrack *track)
267 uint8_t leading, dependent, reference, redundancy;
268 int64_t pos = avio_tell(pb);
269 avio_wb32(pb, 0); // size
270 ffio_wfourcc(pb, "sdtp");
271 avio_wb32(pb, 0); // version & flags
272 for (i = 0; i < track->entry; i++) {
273 dependent = MOV_SAMPLE_DEPENDENCY_YES;
274 leading = reference = redundancy = MOV_SAMPLE_DEPENDENCY_UNKNOWN;
275 if (track->cluster[i].flags & MOV_DISPOSABLE_SAMPLE) {
276 reference = MOV_SAMPLE_DEPENDENCY_NO;
278 if (track->cluster[i].flags & MOV_SYNC_SAMPLE) {
279 dependent = MOV_SAMPLE_DEPENDENCY_NO;
281 avio_w8(pb, (leading << 6) | (dependent << 4) |
282 (reference << 2) | redundancy);
284 return update_size(pb, pos);
287 static int mov_write_amr_tag(AVIOContext *pb, MOVTrack *track)
289 avio_wb32(pb, 0x11); /* size */
290 if (track->mode == MODE_MOV) ffio_wfourcc(pb, "samr");
291 else ffio_wfourcc(pb, "damr");
292 ffio_wfourcc(pb, "FFMP");
293 avio_w8(pb, 0); /* decoder version */
295 avio_wb16(pb, 0x81FF); /* Mode set (all modes for AMR_NB) */
296 avio_w8(pb, 0x00); /* Mode change period (no restriction) */
297 avio_w8(pb, 0x01); /* Frames per sample */
301 static int mov_write_ac3_tag(AVIOContext *pb, MOVTrack *track)
306 int fscod, bsid, bsmod, acmod, lfeon, frmsizecod;
308 if (track->vos_len < 7)
312 ffio_wfourcc(pb, "dac3");
314 init_get_bits(&gbc, track->vos_data + 4, (track->vos_len - 4) * 8);
315 fscod = get_bits(&gbc, 2);
316 frmsizecod = get_bits(&gbc, 6);
317 bsid = get_bits(&gbc, 5);
318 bsmod = get_bits(&gbc, 3);
319 acmod = get_bits(&gbc, 3);
321 skip_bits(&gbc, 2); // dsurmod
323 if ((acmod & 1) && acmod != 1)
324 skip_bits(&gbc, 2); // cmixlev
326 skip_bits(&gbc, 2); // surmixlev
328 lfeon = get_bits1(&gbc);
330 init_put_bits(&pbc, buf, sizeof(buf));
331 put_bits(&pbc, 2, fscod);
332 put_bits(&pbc, 5, bsid);
333 put_bits(&pbc, 3, bsmod);
334 put_bits(&pbc, 3, acmod);
335 put_bits(&pbc, 1, lfeon);
336 put_bits(&pbc, 5, frmsizecod >> 1); // bit_rate_code
337 put_bits(&pbc, 5, 0); // reserved
339 flush_put_bits(&pbc);
340 avio_write(pb, buf, sizeof(buf));
350 /* Layout of the EC3SpecificBox */
351 /* maximum bitrate */
353 /* number of independent substreams */
356 /* sample rate code (see ff_ac3_sample_rate_tab) 2 bits */
358 /* bit stream identification 5 bits */
360 /* one bit reserved */
361 /* audio service mixing (not supported yet) 1 bit */
362 /* bit stream mode 3 bits */
364 /* audio coding mode 3 bits */
366 /* sub woofer on 1 bit */
368 /* 3 bits reserved */
369 /* number of dependent substreams associated with this substream 4 bits */
371 /* channel locations of the dependent substream(s), if any, 9 bits */
373 /* if there is no dependent substream, then one bit reserved instead */
374 } substream[1]; /* TODO: support 8 independent substreams */
377 #if CONFIG_AC3_PARSER
378 static int handle_eac3(MOVMuxContext *mov, AVPacket *pkt, MOVTrack *track)
380 AC3HeaderInfo *hdr = NULL;
381 struct eac3_info *info;
384 if (!track->eac3_priv && !(track->eac3_priv = av_mallocz(sizeof(*info))))
385 return AVERROR(ENOMEM);
386 info = track->eac3_priv;
388 if (avpriv_ac3_parse_header(&hdr, pkt->data, pkt->size) < 0) {
389 /* drop the packets until we see a good one */
391 av_log(mov, AV_LOG_WARNING, "Dropping invalid packet from start of the stream\n");
394 ret = AVERROR_INVALIDDATA;
398 info->data_rate = FFMAX(info->data_rate, hdr->bit_rate / 1000);
399 num_blocks = hdr->num_blocks;
401 if (!info->ec3_done) {
402 /* AC-3 substream must be the first one */
403 if (hdr->bitstream_id <= 10 && hdr->substreamid != 0) {
404 ret = AVERROR(EINVAL);
408 /* this should always be the case, given that our AC-3 parser
409 * concatenates dependent frames to their independent parent */
410 if (hdr->frame_type == EAC3_FRAME_TYPE_INDEPENDENT) {
411 /* substream ids must be incremental */
412 if (hdr->substreamid > info->num_ind_sub + 1) {
413 ret = AVERROR(EINVAL);
417 if (hdr->substreamid == info->num_ind_sub + 1) {
418 //info->num_ind_sub++;
419 avpriv_request_sample(track->par, "Multiple independent substreams");
420 ret = AVERROR_PATCHWELCOME;
422 } else if (hdr->substreamid < info->num_ind_sub ||
423 hdr->substreamid == 0 && info->substream[0].bsid) {
429 /* fill the info needed for the "dec3" atom */
430 info->substream[hdr->substreamid].fscod = hdr->sr_code;
431 info->substream[hdr->substreamid].bsid = hdr->bitstream_id;
432 info->substream[hdr->substreamid].bsmod = hdr->bitstream_mode;
433 info->substream[hdr->substreamid].acmod = hdr->channel_mode;
434 info->substream[hdr->substreamid].lfeon = hdr->lfe_on;
436 /* Parse dependent substream(s), if any */
437 if (pkt->size != hdr->frame_size) {
438 int cumul_size = hdr->frame_size;
439 int parent = hdr->substreamid;
441 while (cumul_size != pkt->size) {
444 ret = avpriv_ac3_parse_header(&hdr, pkt->data + cumul_size, pkt->size - cumul_size);
447 if (hdr->frame_type != EAC3_FRAME_TYPE_DEPENDENT) {
448 ret = AVERROR(EINVAL);
451 info->substream[parent].num_dep_sub++;
454 /* header is parsed up to lfeon, but custom channel map may be needed */
455 init_get_bits8(&gbc, pkt->data + cumul_size + ret, pkt->size - cumul_size - ret);
458 /* skip volume control params */
459 for (i = 0; i < (hdr->channel_mode ? 1 : 2); i++) {
460 skip_bits(&gbc, 5); // skip dialog normalization
461 if (get_bits1(&gbc)) {
462 skip_bits(&gbc, 8); // skip compression gain word
465 /* get the dependent stream channel map, if exists */
467 info->substream[parent].chan_loc |= (get_bits(&gbc, 16) >> 5) & 0x1f;
469 info->substream[parent].chan_loc |= hdr->channel_mode;
470 cumul_size += hdr->frame_size;
476 if (!info->num_blocks && num_blocks == 6) {
480 else if (info->num_blocks + num_blocks > 6) {
481 ret = AVERROR_INVALIDDATA;
485 if (!info->num_blocks) {
486 ret = av_packet_ref(&info->pkt, pkt);
488 info->num_blocks = num_blocks;
491 if ((ret = av_grow_packet(&info->pkt, pkt->size)) < 0)
493 memcpy(info->pkt.data + info->pkt.size - pkt->size, pkt->data, pkt->size);
494 info->num_blocks += num_blocks;
495 info->pkt.duration += pkt->duration;
496 if ((ret = av_copy_packet_side_data(&info->pkt, pkt)) < 0)
498 if (info->num_blocks != 6)
500 av_packet_unref(pkt);
501 av_packet_move_ref(pkt, &info->pkt);
502 info->num_blocks = 0;
513 static int mov_write_eac3_tag(AVIOContext *pb, MOVTrack *track)
517 struct eac3_info *info;
520 if (!track->eac3_priv)
521 return AVERROR(EINVAL);
523 info = track->eac3_priv;
524 size = 2 + 4 * (info->num_ind_sub + 1);
525 buf = av_malloc(size);
527 size = AVERROR(ENOMEM);
531 init_put_bits(&pbc, buf, size);
532 put_bits(&pbc, 13, info->data_rate);
533 put_bits(&pbc, 3, info->num_ind_sub);
534 for (i = 0; i <= info->num_ind_sub; i++) {
535 put_bits(&pbc, 2, info->substream[i].fscod);
536 put_bits(&pbc, 5, info->substream[i].bsid);
537 put_bits(&pbc, 1, 0); /* reserved */
538 put_bits(&pbc, 1, 0); /* asvc */
539 put_bits(&pbc, 3, info->substream[i].bsmod);
540 put_bits(&pbc, 3, info->substream[i].acmod);
541 put_bits(&pbc, 1, info->substream[i].lfeon);
542 put_bits(&pbc, 5, 0); /* reserved */
543 put_bits(&pbc, 4, info->substream[i].num_dep_sub);
544 if (!info->substream[i].num_dep_sub) {
545 put_bits(&pbc, 1, 0); /* reserved */
548 put_bits(&pbc, 9, info->substream[i].chan_loc);
551 flush_put_bits(&pbc);
553 avio_wb32(pb, size + 8);
554 ffio_wfourcc(pb, "dec3");
555 avio_write(pb, buf, size);
560 av_packet_unref(&info->pkt);
561 av_freep(&track->eac3_priv);
567 * This function writes extradata "as is".
568 * Extradata must be formatted like a valid atom (with size and tag).
570 static int mov_write_extradata_tag(AVIOContext *pb, MOVTrack *track)
572 avio_write(pb, track->par->extradata, track->par->extradata_size);
573 return track->par->extradata_size;
576 static int mov_write_enda_tag(AVIOContext *pb)
579 ffio_wfourcc(pb, "enda");
580 avio_wb16(pb, 1); /* little endian */
584 static int mov_write_enda_tag_be(AVIOContext *pb)
587 ffio_wfourcc(pb, "enda");
588 avio_wb16(pb, 0); /* big endian */
592 static void put_descr(AVIOContext *pb, int tag, unsigned int size)
597 avio_w8(pb, (size >> (7 * i)) | 0x80);
598 avio_w8(pb, size & 0x7F);
601 static unsigned compute_avg_bitrate(MOVTrack *track)
605 if (!track->track_duration)
607 for (i = 0; i < track->entry; i++)
608 size += track->cluster[i].size;
609 return size * 8 * track->timescale / track->track_duration;
612 static int mov_write_esds_tag(AVIOContext *pb, MOVTrack *track) // Basic
614 AVCPBProperties *props;
615 int64_t pos = avio_tell(pb);
616 int decoder_specific_info_len = track->vos_len ? 5 + track->vos_len : 0;
617 unsigned avg_bitrate;
619 avio_wb32(pb, 0); // size
620 ffio_wfourcc(pb, "esds");
621 avio_wb32(pb, 0); // Version
624 put_descr(pb, 0x03, 3 + 5+13 + decoder_specific_info_len + 5+1);
625 avio_wb16(pb, track->track_id);
626 avio_w8(pb, 0x00); // flags (= no flags)
628 // DecoderConfig descriptor
629 put_descr(pb, 0x04, 13 + decoder_specific_info_len);
631 // Object type indication
632 if ((track->par->codec_id == AV_CODEC_ID_MP2 ||
633 track->par->codec_id == AV_CODEC_ID_MP3) &&
634 track->par->sample_rate > 24000)
635 avio_w8(pb, 0x6B); // 11172-3
637 avio_w8(pb, ff_codec_get_tag(ff_mp4_obj_type, track->par->codec_id));
639 // the following fields is made of 6 bits to identify the streamtype (4 for video, 5 for audio)
640 // plus 1 bit to indicate upstream and 1 bit set to 1 (reserved)
641 if (track->par->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
642 avio_w8(pb, (0x38 << 2) | 1); // flags (= NeroSubpicStream)
643 else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
644 avio_w8(pb, 0x15); // flags (= Audiostream)
646 avio_w8(pb, 0x11); // flags (= Visualstream)
648 props = (AVCPBProperties*)av_stream_get_side_data(track->st, AV_PKT_DATA_CPB_PROPERTIES,
651 avio_wb24(pb, props ? props->buffer_size / 8 : 0); // Buffersize DB
653 avg_bitrate = compute_avg_bitrate(track);
654 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)
655 avio_wb32(pb, avg_bitrate);
657 if (track->vos_len) {
658 // DecoderSpecific info descriptor
659 put_descr(pb, 0x05, track->vos_len);
660 avio_write(pb, track->vos_data, track->vos_len);
664 put_descr(pb, 0x06, 1);
666 return update_size(pb, pos);
669 static int mov_pcm_le_gt16(enum AVCodecID codec_id)
671 return codec_id == AV_CODEC_ID_PCM_S24LE ||
672 codec_id == AV_CODEC_ID_PCM_S32LE ||
673 codec_id == AV_CODEC_ID_PCM_F32LE ||
674 codec_id == AV_CODEC_ID_PCM_F64LE;
677 static int mov_pcm_be_gt16(enum AVCodecID codec_id)
679 return codec_id == AV_CODEC_ID_PCM_S24BE ||
680 codec_id == AV_CODEC_ID_PCM_S32BE ||
681 codec_id == AV_CODEC_ID_PCM_F32BE ||
682 codec_id == AV_CODEC_ID_PCM_F64BE;
685 static int mov_write_ms_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
688 int64_t pos = avio_tell(pb);
690 avio_wl32(pb, track->tag); // store it byteswapped
691 track->par->codec_tag = av_bswap16(track->tag >> 16);
692 if ((ret = ff_put_wav_header(s, pb, track->par, 0)) < 0)
694 return update_size(pb, pos);
697 static int mov_write_wfex_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
700 int64_t pos = avio_tell(pb);
702 ffio_wfourcc(pb, "wfex");
703 if ((ret = ff_put_wav_header(s, pb, track->st->codecpar, FF_PUT_WAV_HEADER_FORCE_WAVEFORMATEX)) < 0)
705 return update_size(pb, pos);
708 static int mov_write_dfla_tag(AVIOContext *pb, MOVTrack *track)
710 int64_t pos = avio_tell(pb);
712 ffio_wfourcc(pb, "dfLa");
713 avio_w8(pb, 0); /* version */
714 avio_wb24(pb, 0); /* flags */
716 /* Expect the encoder to pass a METADATA_BLOCK_TYPE_STREAMINFO. */
717 if (track->par->extradata_size != FLAC_STREAMINFO_SIZE)
718 return AVERROR_INVALIDDATA;
720 /* TODO: Write other METADATA_BLOCK_TYPEs if the encoder makes them available. */
721 avio_w8(pb, 1 << 7 | FLAC_METADATA_TYPE_STREAMINFO); /* LastMetadataBlockFlag << 7 | BlockType */
722 avio_wb24(pb, track->par->extradata_size); /* Length */
723 avio_write(pb, track->par->extradata, track->par->extradata_size); /* BlockData[Length] */
725 return update_size(pb, pos);
728 static int mov_write_dops_tag(AVIOContext *pb, MOVTrack *track)
730 int64_t pos = avio_tell(pb);
732 ffio_wfourcc(pb, "dOps");
733 avio_w8(pb, 0); /* Version */
734 if (track->par->extradata_size < 19) {
735 av_log(pb, AV_LOG_ERROR, "invalid extradata size\n");
736 return AVERROR_INVALIDDATA;
738 /* extradata contains an Ogg OpusHead, other than byte-ordering and
739 OpusHead's preceeding magic/version, OpusSpecificBox is currently
741 avio_w8(pb, AV_RB8(track->par->extradata + 9)); /* OuputChannelCount */
742 avio_wb16(pb, AV_RL16(track->par->extradata + 10)); /* PreSkip */
743 avio_wb32(pb, AV_RL32(track->par->extradata + 12)); /* InputSampleRate */
744 avio_wb16(pb, AV_RL16(track->par->extradata + 16)); /* OutputGain */
745 /* Write the rest of the header out without byte-swapping. */
746 avio_write(pb, track->par->extradata + 18, track->par->extradata_size - 18);
748 return update_size(pb, pos);
751 static int mov_write_chan_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
753 uint32_t layout_tag, bitmap;
754 int64_t pos = avio_tell(pb);
756 layout_tag = ff_mov_get_channel_layout_tag(track->par->codec_id,
757 track->par->channel_layout,
760 av_log(s, AV_LOG_WARNING, "not writing 'chan' tag due to "
761 "lack of channel information\n");
765 if (track->multichannel_as_mono)
768 avio_wb32(pb, 0); // Size
769 ffio_wfourcc(pb, "chan"); // Type
770 avio_w8(pb, 0); // Version
771 avio_wb24(pb, 0); // Flags
772 avio_wb32(pb, layout_tag); // mChannelLayoutTag
773 avio_wb32(pb, bitmap); // mChannelBitmap
774 avio_wb32(pb, 0); // mNumberChannelDescriptions
776 return update_size(pb, pos);
779 static int mov_write_wave_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
781 int64_t pos = avio_tell(pb);
783 avio_wb32(pb, 0); /* size */
784 ffio_wfourcc(pb, "wave");
786 if (track->par->codec_id != AV_CODEC_ID_QDM2) {
787 avio_wb32(pb, 12); /* size */
788 ffio_wfourcc(pb, "frma");
789 avio_wl32(pb, track->tag);
792 if (track->par->codec_id == AV_CODEC_ID_AAC) {
793 /* useless atom needed by mplayer, ipod, not needed by quicktime */
794 avio_wb32(pb, 12); /* size */
795 ffio_wfourcc(pb, "mp4a");
797 mov_write_esds_tag(pb, track);
798 } else if (mov_pcm_le_gt16(track->par->codec_id)) {
799 mov_write_enda_tag(pb);
800 } else if (mov_pcm_be_gt16(track->par->codec_id)) {
801 mov_write_enda_tag_be(pb);
802 } else if (track->par->codec_id == AV_CODEC_ID_AMR_NB) {
803 mov_write_amr_tag(pb, track);
804 } else if (track->par->codec_id == AV_CODEC_ID_AC3) {
805 mov_write_ac3_tag(pb, track);
806 } else if (track->par->codec_id == AV_CODEC_ID_EAC3) {
807 mov_write_eac3_tag(pb, track);
808 } else if (track->par->codec_id == AV_CODEC_ID_ALAC ||
809 track->par->codec_id == AV_CODEC_ID_QDM2) {
810 mov_write_extradata_tag(pb, track);
811 } else if (track->par->codec_id == AV_CODEC_ID_ADPCM_MS ||
812 track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) {
813 mov_write_ms_tag(s, pb, track);
816 avio_wb32(pb, 8); /* size */
817 avio_wb32(pb, 0); /* null tag */
819 return update_size(pb, pos);
822 static int mov_write_dvc1_structs(MOVTrack *track, uint8_t *buf)
825 const uint8_t *start, *next, *end = track->vos_data + track->vos_len;
826 int unescaped_size, seq_found = 0;
827 int level = 0, interlace = 0;
828 int packet_seq = track->vc1_info.packet_seq;
829 int packet_entry = track->vc1_info.packet_entry;
830 int slices = track->vc1_info.slices;
833 if (track->start_dts == AV_NOPTS_VALUE) {
834 /* No packets written yet, vc1_info isn't authoritative yet. */
835 /* Assume inline sequence and entry headers. */
836 packet_seq = packet_entry = 1;
837 av_log(NULL, AV_LOG_WARNING,
838 "moov atom written before any packets, unable to write correct "
839 "dvc1 atom. Set the delay_moov flag to fix this.\n");
842 unescaped = av_mallocz(track->vos_len + AV_INPUT_BUFFER_PADDING_SIZE);
844 return AVERROR(ENOMEM);
845 start = find_next_marker(track->vos_data, end);
846 for (next = start; next < end; start = next) {
849 next = find_next_marker(start + 4, end);
850 size = next - start - 4;
853 unescaped_size = vc1_unescape_buffer(start + 4, size, unescaped);
854 init_get_bits(&gb, unescaped, 8 * unescaped_size);
855 if (AV_RB32(start) == VC1_CODE_SEQHDR) {
856 int profile = get_bits(&gb, 2);
857 if (profile != PROFILE_ADVANCED) {
859 return AVERROR(ENOSYS);
862 level = get_bits(&gb, 3);
863 /* chromaformat, frmrtq_postproc, bitrtq_postproc, postprocflag,
865 skip_bits_long(&gb, 2 + 3 + 5 + 1 + 2*12);
866 skip_bits(&gb, 1); /* broadcast */
867 interlace = get_bits1(&gb);
868 skip_bits(&gb, 4); /* tfcntrflag, finterpflag, reserved, psf */
873 return AVERROR(ENOSYS);
876 init_put_bits(&pbc, buf, 7);
877 /* VC1DecSpecStruc */
878 put_bits(&pbc, 4, 12); /* profile - advanced */
879 put_bits(&pbc, 3, level);
880 put_bits(&pbc, 1, 0); /* reserved */
881 /* VC1AdvDecSpecStruc */
882 put_bits(&pbc, 3, level);
883 put_bits(&pbc, 1, 0); /* cbr */
884 put_bits(&pbc, 6, 0); /* reserved */
885 put_bits(&pbc, 1, !interlace); /* no interlace */
886 put_bits(&pbc, 1, !packet_seq); /* no multiple seq */
887 put_bits(&pbc, 1, !packet_entry); /* no multiple entry */
888 put_bits(&pbc, 1, !slices); /* no slice code */
889 put_bits(&pbc, 1, 0); /* no bframe */
890 put_bits(&pbc, 1, 0); /* reserved */
893 if (track->st->avg_frame_rate.num > 0 && track->st->avg_frame_rate.den > 0)
894 put_bits32(&pbc, track->st->avg_frame_rate.num / track->st->avg_frame_rate.den);
896 put_bits32(&pbc, 0xffffffff);
898 flush_put_bits(&pbc);
905 static int mov_write_dvc1_tag(AVIOContext *pb, MOVTrack *track)
907 uint8_t buf[7] = { 0 };
910 if ((ret = mov_write_dvc1_structs(track, buf)) < 0)
913 avio_wb32(pb, track->vos_len + 8 + sizeof(buf));
914 ffio_wfourcc(pb, "dvc1");
915 avio_write(pb, buf, sizeof(buf));
916 avio_write(pb, track->vos_data, track->vos_len);
921 static int mov_write_glbl_tag(AVIOContext *pb, MOVTrack *track)
923 avio_wb32(pb, track->vos_len + 8);
924 ffio_wfourcc(pb, "glbl");
925 avio_write(pb, track->vos_data, track->vos_len);
926 return 8 + track->vos_len;
930 * Compute flags for 'lpcm' tag.
931 * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
933 static int mov_get_lpcm_flags(enum AVCodecID codec_id)
936 case AV_CODEC_ID_PCM_F32BE:
937 case AV_CODEC_ID_PCM_F64BE:
939 case AV_CODEC_ID_PCM_F32LE:
940 case AV_CODEC_ID_PCM_F64LE:
942 case AV_CODEC_ID_PCM_U8:
944 case AV_CODEC_ID_PCM_S16BE:
945 case AV_CODEC_ID_PCM_S24BE:
946 case AV_CODEC_ID_PCM_S32BE:
948 case AV_CODEC_ID_PCM_S8:
949 case AV_CODEC_ID_PCM_S16LE:
950 case AV_CODEC_ID_PCM_S24LE:
951 case AV_CODEC_ID_PCM_S32LE:
958 static int get_cluster_duration(MOVTrack *track, int cluster_idx)
962 if (cluster_idx >= track->entry)
965 if (cluster_idx + 1 == track->entry)
966 next_dts = track->track_duration + track->start_dts;
968 next_dts = track->cluster[cluster_idx + 1].dts;
970 next_dts -= track->cluster[cluster_idx].dts;
972 av_assert0(next_dts >= 0);
973 av_assert0(next_dts <= INT_MAX);
978 static int get_samples_per_packet(MOVTrack *track)
980 int i, first_duration;
982 // return track->par->frame_size;
984 /* use 1 for raw PCM */
985 if (!track->audio_vbr)
988 /* check to see if duration is constant for all clusters */
991 first_duration = get_cluster_duration(track, 0);
992 for (i = 1; i < track->entry; i++) {
993 if (get_cluster_duration(track, i) != first_duration)
996 return first_duration;
999 static int mov_write_audio_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
1001 int64_t pos = avio_tell(pb);
1003 uint32_t tag = track->tag;
1005 if (track->mode == MODE_MOV) {
1006 if (track->timescale > UINT16_MAX) {
1007 if (mov_get_lpcm_flags(track->par->codec_id))
1008 tag = AV_RL32("lpcm");
1010 } else if (track->audio_vbr || mov_pcm_le_gt16(track->par->codec_id) ||
1011 mov_pcm_be_gt16(track->par->codec_id) ||
1012 track->par->codec_id == AV_CODEC_ID_ADPCM_MS ||
1013 track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
1014 track->par->codec_id == AV_CODEC_ID_QDM2) {
1019 avio_wb32(pb, 0); /* size */
1020 if (mov->encryption_scheme != MOV_ENC_NONE) {
1021 ffio_wfourcc(pb, "enca");
1023 avio_wl32(pb, tag); // store it byteswapped
1025 avio_wb32(pb, 0); /* Reserved */
1026 avio_wb16(pb, 0); /* Reserved */
1027 avio_wb16(pb, 1); /* Data-reference index, XXX == 1 */
1029 /* SoundDescription */
1030 avio_wb16(pb, version); /* Version */
1031 avio_wb16(pb, 0); /* Revision level */
1032 avio_wb32(pb, 0); /* Reserved */
1037 avio_wb16(pb, 0xfffe);
1039 avio_wb32(pb, 0x00010000);
1041 avio_wb64(pb, av_double2int(track->par->sample_rate));
1042 avio_wb32(pb, track->par->channels);
1043 avio_wb32(pb, 0x7F000000);
1044 avio_wb32(pb, av_get_bits_per_sample(track->par->codec_id));
1045 avio_wb32(pb, mov_get_lpcm_flags(track->par->codec_id));
1046 avio_wb32(pb, track->sample_size);
1047 avio_wb32(pb, get_samples_per_packet(track));
1049 if (track->mode == MODE_MOV) {
1050 avio_wb16(pb, track->par->channels);
1051 if (track->par->codec_id == AV_CODEC_ID_PCM_U8 ||
1052 track->par->codec_id == AV_CODEC_ID_PCM_S8)
1053 avio_wb16(pb, 8); /* bits per sample */
1054 else if (track->par->codec_id == AV_CODEC_ID_ADPCM_G726)
1055 avio_wb16(pb, track->par->bits_per_coded_sample);
1058 avio_wb16(pb, track->audio_vbr ? -2 : 0); /* compression ID */
1059 } else { /* reserved for mp4/3gp */
1060 if (track->par->codec_id == AV_CODEC_ID_FLAC ||
1061 track->par->codec_id == AV_CODEC_ID_OPUS) {
1062 avio_wb16(pb, track->par->channels);
1066 if (track->par->codec_id == AV_CODEC_ID_FLAC) {
1067 avio_wb16(pb, track->par->bits_per_raw_sample);
1074 avio_wb16(pb, 0); /* packet size (= 0) */
1075 if (track->par->codec_id == AV_CODEC_ID_OPUS)
1076 avio_wb16(pb, 48000);
1078 avio_wb16(pb, track->par->sample_rate <= UINT16_MAX ?
1079 track->par->sample_rate : 0);
1080 avio_wb16(pb, 0); /* Reserved */
1083 if (version == 1) { /* SoundDescription V1 extended info */
1084 if (mov_pcm_le_gt16(track->par->codec_id) ||
1085 mov_pcm_be_gt16(track->par->codec_id))
1086 avio_wb32(pb, 1); /* must be 1 for uncompressed formats */
1088 avio_wb32(pb, track->par->frame_size); /* Samples per packet */
1089 avio_wb32(pb, track->sample_size / track->par->channels); /* Bytes per packet */
1090 avio_wb32(pb, track->sample_size); /* Bytes per frame */
1091 avio_wb32(pb, 2); /* Bytes per sample */
1094 if (track->mode == MODE_MOV &&
1095 (track->par->codec_id == AV_CODEC_ID_AAC ||
1096 track->par->codec_id == AV_CODEC_ID_AC3 ||
1097 track->par->codec_id == AV_CODEC_ID_EAC3 ||
1098 track->par->codec_id == AV_CODEC_ID_AMR_NB ||
1099 track->par->codec_id == AV_CODEC_ID_ALAC ||
1100 track->par->codec_id == AV_CODEC_ID_ADPCM_MS ||
1101 track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
1102 track->par->codec_id == AV_CODEC_ID_QDM2 ||
1103 (mov_pcm_le_gt16(track->par->codec_id) && version==1) ||
1104 (mov_pcm_be_gt16(track->par->codec_id) && version==1)))
1105 mov_write_wave_tag(s, pb, track);
1106 else if (track->tag == MKTAG('m','p','4','a'))
1107 mov_write_esds_tag(pb, track);
1108 else if (track->par->codec_id == AV_CODEC_ID_AMR_NB)
1109 mov_write_amr_tag(pb, track);
1110 else if (track->par->codec_id == AV_CODEC_ID_AC3)
1111 mov_write_ac3_tag(pb, track);
1112 else if (track->par->codec_id == AV_CODEC_ID_EAC3)
1113 mov_write_eac3_tag(pb, track);
1114 else if (track->par->codec_id == AV_CODEC_ID_ALAC)
1115 mov_write_extradata_tag(pb, track);
1116 else if (track->par->codec_id == AV_CODEC_ID_WMAPRO)
1117 mov_write_wfex_tag(s, pb, track);
1118 else if (track->par->codec_id == AV_CODEC_ID_FLAC)
1119 mov_write_dfla_tag(pb, track);
1120 else if (track->par->codec_id == AV_CODEC_ID_OPUS)
1121 mov_write_dops_tag(pb, track);
1122 else if (track->vos_len > 0)
1123 mov_write_glbl_tag(pb, track);
1125 if (track->mode == MODE_MOV && track->par->codec_type == AVMEDIA_TYPE_AUDIO)
1126 mov_write_chan_tag(s, pb, track);
1128 if (mov->encryption_scheme != MOV_ENC_NONE) {
1129 ff_mov_cenc_write_sinf_tag(track, pb, mov->encryption_kid);
1132 return update_size(pb, pos);
1135 static int mov_write_d263_tag(AVIOContext *pb)
1137 avio_wb32(pb, 0xf); /* size */
1138 ffio_wfourcc(pb, "d263");
1139 ffio_wfourcc(pb, "FFMP");
1140 avio_w8(pb, 0); /* decoder version */
1141 /* FIXME use AVCodecContext level/profile, when encoder will set values */
1142 avio_w8(pb, 0xa); /* level */
1143 avio_w8(pb, 0); /* profile */
1147 static int mov_write_avcc_tag(AVIOContext *pb, MOVTrack *track)
1149 int64_t pos = avio_tell(pb);
1152 ffio_wfourcc(pb, "avcC");
1153 ff_isom_write_avcc(pb, track->vos_data, track->vos_len);
1154 return update_size(pb, pos);
1157 static int mov_write_vpcc_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
1159 int64_t pos = avio_tell(pb);
1162 ffio_wfourcc(pb, "vpcC");
1163 avio_w8(pb, 1); /* version */
1164 avio_wb24(pb, 0); /* flags */
1165 ff_isom_write_vpcc(s, pb, track->par);
1166 return update_size(pb, pos);
1169 static int mov_write_hvcc_tag(AVIOContext *pb, MOVTrack *track)
1171 int64_t pos = avio_tell(pb);
1174 ffio_wfourcc(pb, "hvcC");
1175 if (track->tag == MKTAG('h','v','c','1'))
1176 ff_isom_write_hvcc(pb, track->vos_data, track->vos_len, 1);
1178 ff_isom_write_hvcc(pb, track->vos_data, track->vos_len, 0);
1179 return update_size(pb, pos);
1182 /* also used by all avid codecs (dv, imx, meridien) and their variants */
1183 static int mov_write_avid_tag(AVIOContext *pb, MOVTrack *track)
1188 int display_width = track->par->width;
1190 if (track->vos_data && track->vos_len > 0x29) {
1191 if (ff_dnxhd_parse_header_prefix(track->vos_data) != 0) {
1192 /* looks like a DNxHD bit stream */
1193 interlaced = (track->vos_data[5] & 2);
1194 cid = AV_RB32(track->vos_data + 0x28);
1196 av_log(NULL, AV_LOG_WARNING, "Could not locate DNxHD bit stream in vos_data\n");
1200 av_log(NULL, AV_LOG_WARNING, "Could not locate DNxHD bit stream, vos_data too small\n");
1204 avio_wb32(pb, 24); /* size */
1205 ffio_wfourcc(pb, "ACLR");
1206 ffio_wfourcc(pb, "ACLR");
1207 ffio_wfourcc(pb, "0001");
1208 if (track->par->color_range == AVCOL_RANGE_MPEG || /* Legal range (16-235) */
1209 track->par->color_range == AVCOL_RANGE_UNSPECIFIED) {
1210 avio_wb32(pb, 1); /* Corresponds to 709 in official encoder */
1211 } else { /* Full range (0-255) */
1212 avio_wb32(pb, 2); /* Corresponds to RGB in official encoder */
1214 avio_wb32(pb, 0); /* unknown */
1216 if (track->tag == MKTAG('A','V','d','h')) {
1218 ffio_wfourcc(pb, "ADHR");
1219 ffio_wfourcc(pb, "0001");
1221 avio_wb32(pb, 0); /* unknown */
1222 avio_wb32(pb, 1); /* unknown */
1223 avio_wb32(pb, 0); /* unknown */
1224 avio_wb32(pb, 0); /* unknown */
1228 avio_wb32(pb, 24); /* size */
1229 ffio_wfourcc(pb, "APRG");
1230 ffio_wfourcc(pb, "APRG");
1231 ffio_wfourcc(pb, "0001");
1232 avio_wb32(pb, 1); /* unknown */
1233 avio_wb32(pb, 0); /* unknown */
1235 avio_wb32(pb, 120); /* size */
1236 ffio_wfourcc(pb, "ARES");
1237 ffio_wfourcc(pb, "ARES");
1238 ffio_wfourcc(pb, "0001");
1239 avio_wb32(pb, cid); /* dnxhd cid, some id ? */
1240 if ( track->par->sample_aspect_ratio.num > 0
1241 && track->par->sample_aspect_ratio.den > 0)
1242 display_width = display_width * track->par->sample_aspect_ratio.num / track->par->sample_aspect_ratio.den;
1243 avio_wb32(pb, display_width);
1244 /* values below are based on samples created with quicktime and avid codecs */
1246 avio_wb32(pb, track->par->height / 2);
1247 avio_wb32(pb, 2); /* unknown */
1248 avio_wb32(pb, 0); /* unknown */
1249 avio_wb32(pb, 4); /* unknown */
1251 avio_wb32(pb, track->par->height);
1252 avio_wb32(pb, 1); /* unknown */
1253 avio_wb32(pb, 0); /* unknown */
1254 if (track->par->height == 1080)
1255 avio_wb32(pb, 5); /* unknown */
1257 avio_wb32(pb, 6); /* unknown */
1260 for (i = 0; i < 10; i++)
1266 static int mov_write_dpxe_tag(AVIOContext *pb, MOVTrack *track)
1269 ffio_wfourcc(pb, "DpxE");
1270 if (track->par->extradata_size >= 12 &&
1271 !memcmp(&track->par->extradata[4], "DpxE", 4)) {
1272 avio_wb32(pb, track->par->extradata[11]);
1279 static int mov_get_dv_codec_tag(AVFormatContext *s, MOVTrack *track)
1283 if (track->par->width == 720) { /* SD */
1284 if (track->par->height == 480) { /* NTSC */
1285 if (track->par->format == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','n');
1286 else tag = MKTAG('d','v','c',' ');
1287 }else if (track->par->format == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','p');
1288 else if (track->par->format == AV_PIX_FMT_YUV420P) tag = MKTAG('d','v','c','p');
1289 else tag = MKTAG('d','v','p','p');
1290 } else if (track->par->height == 720) { /* HD 720 line */
1291 if (track->st->time_base.den == 50) tag = MKTAG('d','v','h','q');
1292 else tag = MKTAG('d','v','h','p');
1293 } else if (track->par->height == 1080) { /* HD 1080 line */
1294 if (track->st->time_base.den == 25) tag = MKTAG('d','v','h','5');
1295 else tag = MKTAG('d','v','h','6');
1297 av_log(s, AV_LOG_ERROR, "unsupported height for dv codec\n");
1304 static AVRational find_fps(AVFormatContext *s, AVStream *st)
1306 AVRational rate = st->avg_frame_rate;
1308 #if FF_API_LAVF_AVCTX
1309 FF_DISABLE_DEPRECATION_WARNINGS
1310 rate = av_inv_q(st->codec->time_base);
1311 if (av_timecode_check_frame_rate(rate) < 0) {
1312 av_log(s, AV_LOG_DEBUG, "timecode: tbc=%d/%d invalid, fallback on %d/%d\n",
1313 rate.num, rate.den, st->avg_frame_rate.num, st->avg_frame_rate.den);
1314 rate = st->avg_frame_rate;
1316 FF_ENABLE_DEPRECATION_WARNINGS
1322 static int defined_frame_rate(AVFormatContext *s, AVStream *st)
1324 AVRational rational_framerate = find_fps(s, st);
1326 if (rational_framerate.den != 0)
1327 rate = av_q2d(rational_framerate);
1331 static int mov_get_mpeg2_xdcam_codec_tag(AVFormatContext *s, MOVTrack *track)
1333 int tag = track->par->codec_tag;
1334 int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE;
1335 AVStream *st = track->st;
1336 int rate = defined_frame_rate(s, st);
1339 tag = MKTAG('m', '2', 'v', '1'); //fallback tag
1341 if (track->par->format == AV_PIX_FMT_YUV420P) {
1342 if (track->par->width == 1280 && track->par->height == 720) {
1344 if (rate == 24) tag = MKTAG('x','d','v','4');
1345 else if (rate == 25) tag = MKTAG('x','d','v','5');
1346 else if (rate == 30) tag = MKTAG('x','d','v','1');
1347 else if (rate == 50) tag = MKTAG('x','d','v','a');
1348 else if (rate == 60) tag = MKTAG('x','d','v','9');
1350 } else if (track->par->width == 1440 && track->par->height == 1080) {
1352 if (rate == 24) tag = MKTAG('x','d','v','6');
1353 else if (rate == 25) tag = MKTAG('x','d','v','7');
1354 else if (rate == 30) tag = MKTAG('x','d','v','8');
1356 if (rate == 25) tag = MKTAG('x','d','v','3');
1357 else if (rate == 30) tag = MKTAG('x','d','v','2');
1359 } else if (track->par->width == 1920 && track->par->height == 1080) {
1361 if (rate == 24) tag = MKTAG('x','d','v','d');
1362 else if (rate == 25) tag = MKTAG('x','d','v','e');
1363 else if (rate == 30) tag = MKTAG('x','d','v','f');
1365 if (rate == 25) tag = MKTAG('x','d','v','c');
1366 else if (rate == 30) tag = MKTAG('x','d','v','b');
1369 } else if (track->par->format == AV_PIX_FMT_YUV422P) {
1370 if (track->par->width == 1280 && track->par->height == 720) {
1372 if (rate == 24) tag = MKTAG('x','d','5','4');
1373 else if (rate == 25) tag = MKTAG('x','d','5','5');
1374 else if (rate == 30) tag = MKTAG('x','d','5','1');
1375 else if (rate == 50) tag = MKTAG('x','d','5','a');
1376 else if (rate == 60) tag = MKTAG('x','d','5','9');
1378 } else if (track->par->width == 1920 && track->par->height == 1080) {
1380 if (rate == 24) tag = MKTAG('x','d','5','d');
1381 else if (rate == 25) tag = MKTAG('x','d','5','e');
1382 else if (rate == 30) tag = MKTAG('x','d','5','f');
1384 if (rate == 25) tag = MKTAG('x','d','5','c');
1385 else if (rate == 30) tag = MKTAG('x','d','5','b');
1393 static int mov_get_h264_codec_tag(AVFormatContext *s, MOVTrack *track)
1395 int tag = track->par->codec_tag;
1396 int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE;
1397 AVStream *st = track->st;
1398 int rate = defined_frame_rate(s, st);
1401 tag = MKTAG('a', 'v', 'c', 'i'); //fallback tag
1403 if (track->par->format == AV_PIX_FMT_YUV420P10) {
1404 if (track->par->width == 960 && track->par->height == 720) {
1406 if (rate == 24) tag = MKTAG('a','i','5','p');
1407 else if (rate == 25) tag = MKTAG('a','i','5','q');
1408 else if (rate == 30) tag = MKTAG('a','i','5','p');
1409 else if (rate == 50) tag = MKTAG('a','i','5','q');
1410 else if (rate == 60) tag = MKTAG('a','i','5','p');
1412 } else if (track->par->width == 1440 && track->par->height == 1080) {
1414 if (rate == 24) tag = MKTAG('a','i','5','3');
1415 else if (rate == 25) tag = MKTAG('a','i','5','2');
1416 else if (rate == 30) tag = MKTAG('a','i','5','3');
1418 if (rate == 50) tag = MKTAG('a','i','5','5');
1419 else if (rate == 60) tag = MKTAG('a','i','5','6');
1422 } else if (track->par->format == AV_PIX_FMT_YUV422P10) {
1423 if (track->par->width == 1280 && track->par->height == 720) {
1425 if (rate == 24) tag = MKTAG('a','i','1','p');
1426 else if (rate == 25) tag = MKTAG('a','i','1','q');
1427 else if (rate == 30) tag = MKTAG('a','i','1','p');
1428 else if (rate == 50) tag = MKTAG('a','i','1','q');
1429 else if (rate == 60) tag = MKTAG('a','i','1','p');
1431 } else if (track->par->width == 1920 && track->par->height == 1080) {
1433 if (rate == 24) tag = MKTAG('a','i','1','3');
1434 else if (rate == 25) tag = MKTAG('a','i','1','2');
1435 else if (rate == 30) tag = MKTAG('a','i','1','3');
1437 if (rate == 25) tag = MKTAG('a','i','1','5');
1438 else if (rate == 50) tag = MKTAG('a','i','1','5');
1439 else if (rate == 60) tag = MKTAG('a','i','1','6');
1441 } else if ( track->par->width == 4096 && track->par->height == 2160
1442 || track->par->width == 3840 && track->par->height == 2160
1443 || track->par->width == 2048 && track->par->height == 1080) {
1444 tag = MKTAG('a','i','v','x');
1451 static const struct {
1452 enum AVPixelFormat pix_fmt;
1455 } mov_pix_fmt_tags[] = {
1456 { AV_PIX_FMT_YUYV422, MKTAG('y','u','v','2'), 0 },
1457 { AV_PIX_FMT_YUYV422, MKTAG('y','u','v','s'), 0 },
1458 { AV_PIX_FMT_UYVY422, MKTAG('2','v','u','y'), 0 },
1459 { AV_PIX_FMT_RGB555BE,MKTAG('r','a','w',' '), 16 },
1460 { AV_PIX_FMT_RGB555LE,MKTAG('L','5','5','5'), 16 },
1461 { AV_PIX_FMT_RGB565LE,MKTAG('L','5','6','5'), 16 },
1462 { AV_PIX_FMT_RGB565BE,MKTAG('B','5','6','5'), 16 },
1463 { AV_PIX_FMT_GRAY16BE,MKTAG('b','1','6','g'), 16 },
1464 { AV_PIX_FMT_RGB24, MKTAG('r','a','w',' '), 24 },
1465 { AV_PIX_FMT_BGR24, MKTAG('2','4','B','G'), 24 },
1466 { AV_PIX_FMT_ARGB, MKTAG('r','a','w',' '), 32 },
1467 { AV_PIX_FMT_BGRA, MKTAG('B','G','R','A'), 32 },
1468 { AV_PIX_FMT_RGBA, MKTAG('R','G','B','A'), 32 },
1469 { AV_PIX_FMT_ABGR, MKTAG('A','B','G','R'), 32 },
1470 { AV_PIX_FMT_RGB48BE, MKTAG('b','4','8','r'), 48 },
1473 static int mov_get_dnxhd_codec_tag(AVFormatContext *s, MOVTrack *track)
1475 int tag = MKTAG('A','V','d','n');
1476 if (track->par->profile != FF_PROFILE_UNKNOWN &&
1477 track->par->profile != FF_PROFILE_DNXHD)
1478 tag = MKTAG('A','V','d','h');
1482 static int mov_get_rawvideo_codec_tag(AVFormatContext *s, MOVTrack *track)
1484 int tag = track->par->codec_tag;
1486 enum AVPixelFormat pix_fmt;
1488 for (i = 0; i < FF_ARRAY_ELEMS(mov_pix_fmt_tags); i++) {
1489 if (track->par->format == mov_pix_fmt_tags[i].pix_fmt) {
1490 tag = mov_pix_fmt_tags[i].tag;
1491 track->par->bits_per_coded_sample = mov_pix_fmt_tags[i].bps;
1492 if (track->par->codec_tag == mov_pix_fmt_tags[i].tag)
1497 pix_fmt = avpriv_find_pix_fmt(avpriv_pix_fmt_bps_mov,
1498 track->par->bits_per_coded_sample);
1499 if (tag == MKTAG('r','a','w',' ') &&
1500 track->par->format != pix_fmt &&
1501 track->par->format != AV_PIX_FMT_GRAY8 &&
1502 track->par->format != AV_PIX_FMT_NONE)
1503 av_log(s, AV_LOG_ERROR, "%s rawvideo cannot be written to mov, output file will be unreadable\n",
1504 av_get_pix_fmt_name(track->par->format));
1508 static int mov_get_codec_tag(AVFormatContext *s, MOVTrack *track)
1510 int tag = track->par->codec_tag;
1512 if (!tag || (s->strict_std_compliance >= FF_COMPLIANCE_NORMAL &&
1513 (track->par->codec_id == AV_CODEC_ID_DVVIDEO ||
1514 track->par->codec_id == AV_CODEC_ID_RAWVIDEO ||
1515 track->par->codec_id == AV_CODEC_ID_H263 ||
1516 track->par->codec_id == AV_CODEC_ID_H264 ||
1517 track->par->codec_id == AV_CODEC_ID_DNXHD ||
1518 track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO ||
1519 av_get_bits_per_sample(track->par->codec_id)))) { // pcm audio
1520 if (track->par->codec_id == AV_CODEC_ID_DVVIDEO)
1521 tag = mov_get_dv_codec_tag(s, track);
1522 else if (track->par->codec_id == AV_CODEC_ID_RAWVIDEO)
1523 tag = mov_get_rawvideo_codec_tag(s, track);
1524 else if (track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO)
1525 tag = mov_get_mpeg2_xdcam_codec_tag(s, track);
1526 else if (track->par->codec_id == AV_CODEC_ID_H264)
1527 tag = mov_get_h264_codec_tag(s, track);
1528 else if (track->par->codec_id == AV_CODEC_ID_DNXHD)
1529 tag = mov_get_dnxhd_codec_tag(s, track);
1530 else if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
1531 tag = ff_codec_get_tag(ff_codec_movvideo_tags, track->par->codec_id);
1532 if (!tag) { // if no mac fcc found, try with Microsoft tags
1533 tag = ff_codec_get_tag(ff_codec_bmp_tags, track->par->codec_id);
1535 av_log(s, AV_LOG_WARNING, "Using MS style video codec tag, "
1536 "the file may be unplayable!\n");
1538 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
1539 tag = ff_codec_get_tag(ff_codec_movaudio_tags, track->par->codec_id);
1540 if (!tag) { // if no mac fcc found, try with Microsoft tags
1541 int ms_tag = ff_codec_get_tag(ff_codec_wav_tags, track->par->codec_id);
1543 tag = MKTAG('m', 's', ((ms_tag >> 8) & 0xff), (ms_tag & 0xff));
1544 av_log(s, AV_LOG_WARNING, "Using MS style audio codec tag, "
1545 "the file may be unplayable!\n");
1548 } else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)
1549 tag = ff_codec_get_tag(ff_codec_movsubtitle_tags, track->par->codec_id);
1555 static int mov_find_codec_tag(AVFormatContext *s, MOVTrack *track)
1559 if (track->mode == MODE_MP4 || track->mode == MODE_PSP)
1560 tag = track->par->codec_tag;
1561 else if (track->mode == MODE_ISM)
1562 tag = track->par->codec_tag;
1563 else if (track->mode == MODE_IPOD) {
1564 if (!av_match_ext(s->url, "m4a") &&
1565 !av_match_ext(s->url, "m4v") &&
1566 !av_match_ext(s->url, "m4b"))
1567 av_log(s, AV_LOG_WARNING, "Warning, extension is not .m4a nor .m4v "
1568 "Quicktime/Ipod might not play the file\n");
1569 tag = track->par->codec_tag;
1570 } else if (track->mode & MODE_3GP)
1571 tag = track->par->codec_tag;
1572 else if (track->mode == MODE_F4V)
1573 tag = track->par->codec_tag;
1575 tag = mov_get_codec_tag(s, track);
1580 /** Write uuid atom.
1581 * Needed to make file play in iPods running newest firmware
1582 * goes after avcC atom in moov.trak.mdia.minf.stbl.stsd.avc1
1584 static int mov_write_uuid_tag_ipod(AVIOContext *pb)
1587 ffio_wfourcc(pb, "uuid");
1588 avio_wb32(pb, 0x6b6840f2);
1589 avio_wb32(pb, 0x5f244fc5);
1590 avio_wb32(pb, 0xba39a51b);
1591 avio_wb32(pb, 0xcf0323f3);
1596 static const uint16_t fiel_data[] = {
1597 0x0000, 0x0100, 0x0201, 0x0206, 0x0209, 0x020e
1600 static int mov_write_fiel_tag(AVIOContext *pb, MOVTrack *track, int field_order)
1602 unsigned mov_field_order = 0;
1603 if (field_order < FF_ARRAY_ELEMS(fiel_data))
1604 mov_field_order = fiel_data[field_order];
1608 ffio_wfourcc(pb, "fiel");
1609 avio_wb16(pb, mov_field_order);
1613 static int mov_write_subtitle_tag(AVIOContext *pb, MOVTrack *track)
1615 int64_t pos = avio_tell(pb);
1616 avio_wb32(pb, 0); /* size */
1617 avio_wl32(pb, track->tag); // store it byteswapped
1618 avio_wb32(pb, 0); /* Reserved */
1619 avio_wb16(pb, 0); /* Reserved */
1620 avio_wb16(pb, 1); /* Data-reference index */
1622 if (track->par->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
1623 mov_write_esds_tag(pb, track);
1624 else if (track->par->extradata_size)
1625 avio_write(pb, track->par->extradata, track->par->extradata_size);
1627 return update_size(pb, pos);
1630 static int mov_write_st3d_tag(AVIOContext *pb, AVStereo3D *stereo_3d)
1634 if (stereo_3d->flags != 0) {
1635 av_log(pb, AV_LOG_WARNING, "Unsupported stereo_3d flags %x. st3d not written.\n", stereo_3d->flags);
1639 switch (stereo_3d->type) {
1640 case AV_STEREO3D_2D:
1643 case AV_STEREO3D_TOPBOTTOM:
1646 case AV_STEREO3D_SIDEBYSIDE:
1650 av_log(pb, AV_LOG_WARNING, "Unsupported stereo_3d type %s. st3d not written.\n", av_stereo3d_type_name(stereo_3d->type));
1653 avio_wb32(pb, 13); /* size */
1654 ffio_wfourcc(pb, "st3d");
1655 avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1656 avio_w8(pb, stereo_mode);
1660 static int mov_write_sv3d_tag(AVFormatContext *s, AVIOContext *pb, AVSphericalMapping *spherical_mapping)
1662 int64_t sv3d_pos, svhd_pos, proj_pos;
1663 const char* metadata_source = s->flags & AVFMT_FLAG_BITEXACT ? "Lavf" : LIBAVFORMAT_IDENT;
1665 if (spherical_mapping->projection != AV_SPHERICAL_EQUIRECTANGULAR &&
1666 spherical_mapping->projection != AV_SPHERICAL_EQUIRECTANGULAR_TILE &&
1667 spherical_mapping->projection != AV_SPHERICAL_CUBEMAP) {
1668 av_log(pb, AV_LOG_WARNING, "Unsupported projection %d. sv3d not written.\n", spherical_mapping->projection);
1672 sv3d_pos = avio_tell(pb);
1673 avio_wb32(pb, 0); /* size */
1674 ffio_wfourcc(pb, "sv3d");
1676 svhd_pos = avio_tell(pb);
1677 avio_wb32(pb, 0); /* size */
1678 ffio_wfourcc(pb, "svhd");
1679 avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1680 avio_put_str(pb, metadata_source);
1681 update_size(pb, svhd_pos);
1683 proj_pos = avio_tell(pb);
1684 avio_wb32(pb, 0); /* size */
1685 ffio_wfourcc(pb, "proj");
1687 avio_wb32(pb, 24); /* size */
1688 ffio_wfourcc(pb, "prhd");
1689 avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1690 avio_wb32(pb, spherical_mapping->yaw);
1691 avio_wb32(pb, spherical_mapping->pitch);
1692 avio_wb32(pb, spherical_mapping->roll);
1694 switch (spherical_mapping->projection) {
1695 case AV_SPHERICAL_EQUIRECTANGULAR:
1696 case AV_SPHERICAL_EQUIRECTANGULAR_TILE:
1697 avio_wb32(pb, 28); /* size */
1698 ffio_wfourcc(pb, "equi");
1699 avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1700 avio_wb32(pb, spherical_mapping->bound_top);
1701 avio_wb32(pb, spherical_mapping->bound_bottom);
1702 avio_wb32(pb, spherical_mapping->bound_left);
1703 avio_wb32(pb, spherical_mapping->bound_right);
1705 case AV_SPHERICAL_CUBEMAP:
1706 avio_wb32(pb, 20); /* size */
1707 ffio_wfourcc(pb, "cbmp");
1708 avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1709 avio_wb32(pb, 0); /* layout */
1710 avio_wb32(pb, spherical_mapping->padding); /* padding */
1713 update_size(pb, proj_pos);
1715 return update_size(pb, sv3d_pos);
1718 static int mov_write_clap_tag(AVIOContext *pb, MOVTrack *track)
1721 ffio_wfourcc(pb, "clap");
1722 avio_wb32(pb, track->par->width); /* apertureWidth_N */
1723 avio_wb32(pb, 1); /* apertureWidth_D (= 1) */
1724 avio_wb32(pb, track->height); /* apertureHeight_N */
1725 avio_wb32(pb, 1); /* apertureHeight_D (= 1) */
1726 avio_wb32(pb, 0); /* horizOff_N (= 0) */
1727 avio_wb32(pb, 1); /* horizOff_D (= 1) */
1728 avio_wb32(pb, 0); /* vertOff_N (= 0) */
1729 avio_wb32(pb, 1); /* vertOff_D (= 1) */
1733 static int mov_write_pasp_tag(AVIOContext *pb, MOVTrack *track)
1736 av_reduce(&sar.num, &sar.den, track->par->sample_aspect_ratio.num,
1737 track->par->sample_aspect_ratio.den, INT_MAX);
1740 ffio_wfourcc(pb, "pasp");
1741 avio_wb32(pb, sar.num);
1742 avio_wb32(pb, sar.den);
1746 static int mov_write_gama_tag(AVIOContext *pb, MOVTrack *track, double gamma)
1751 gamma = avpriv_get_gamma_from_trc(track->par->color_trc);
1753 av_log(pb, AV_LOG_DEBUG, "gamma value %g\n", gamma);
1756 gama = (uint32_t)lrint((double)(1<<16) * gamma);
1757 av_log(pb, AV_LOG_DEBUG, "writing gama value %"PRId32"\n", gama);
1759 av_assert0(track->mode == MODE_MOV);
1761 ffio_wfourcc(pb, "gama");
1762 avio_wb32(pb, gama);
1766 av_log(pb, AV_LOG_WARNING, "gamma value unknown, unable to write gama atom\n");
1771 static int mov_write_colr_tag(AVIOContext *pb, MOVTrack *track)
1773 // Ref (MOV): https://developer.apple.com/library/mac/technotes/tn2162/_index.html#//apple_ref/doc/uid/DTS40013070-CH1-TNTAG9
1774 // Ref (MP4): ISO/IEC 14496-12:2012
1776 if (track->par->color_primaries == AVCOL_PRI_UNSPECIFIED &&
1777 track->par->color_trc == AVCOL_TRC_UNSPECIFIED &&
1778 track->par->color_space == AVCOL_SPC_UNSPECIFIED) {
1779 if ((track->par->width >= 1920 && track->par->height >= 1080)
1780 || (track->par->width == 1280 && track->par->height == 720)) {
1781 av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming bt709\n");
1782 track->par->color_primaries = AVCOL_PRI_BT709;
1783 } else if (track->par->width == 720 && track->height == 576) {
1784 av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming bt470bg\n");
1785 track->par->color_primaries = AVCOL_PRI_BT470BG;
1786 } else if (track->par->width == 720 &&
1787 (track->height == 486 || track->height == 480)) {
1788 av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming smpte170\n");
1789 track->par->color_primaries = AVCOL_PRI_SMPTE170M;
1791 av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, unable to assume anything\n");
1793 switch (track->par->color_primaries) {
1794 case AVCOL_PRI_BT709:
1795 track->par->color_trc = AVCOL_TRC_BT709;
1796 track->par->color_space = AVCOL_SPC_BT709;
1798 case AVCOL_PRI_SMPTE170M:
1799 case AVCOL_PRI_BT470BG:
1800 track->par->color_trc = AVCOL_TRC_BT709;
1801 track->par->color_space = AVCOL_SPC_SMPTE170M;
1806 /* We should only ever be called by MOV or MP4. */
1807 av_assert0(track->mode == MODE_MOV || track->mode == MODE_MP4);
1809 avio_wb32(pb, 18 + (track->mode == MODE_MP4));
1810 ffio_wfourcc(pb, "colr");
1811 if (track->mode == MODE_MP4)
1812 ffio_wfourcc(pb, "nclx");
1814 ffio_wfourcc(pb, "nclc");
1815 switch (track->par->color_primaries) {
1816 case AVCOL_PRI_BT709: avio_wb16(pb, 1); break;
1817 case AVCOL_PRI_BT470BG: avio_wb16(pb, 5); break;
1818 case AVCOL_PRI_SMPTE170M:
1819 case AVCOL_PRI_SMPTE240M: avio_wb16(pb, 6); break;
1820 case AVCOL_PRI_BT2020: avio_wb16(pb, 9); break;
1821 case AVCOL_PRI_SMPTE431: avio_wb16(pb, 11); break;
1822 case AVCOL_PRI_SMPTE432: avio_wb16(pb, 12); break;
1823 default: avio_wb16(pb, 2);
1825 switch (track->par->color_trc) {
1826 case AVCOL_TRC_BT709: avio_wb16(pb, 1); break;
1827 case AVCOL_TRC_SMPTE170M: avio_wb16(pb, 1); break; // remapped
1828 case AVCOL_TRC_SMPTE240M: avio_wb16(pb, 7); break;
1829 case AVCOL_TRC_SMPTEST2084: avio_wb16(pb, 16); break;
1830 case AVCOL_TRC_SMPTE428: avio_wb16(pb, 17); break;
1831 case AVCOL_TRC_ARIB_STD_B67: avio_wb16(pb, 18); break;
1832 default: avio_wb16(pb, 2);
1834 switch (track->par->color_space) {
1835 case AVCOL_SPC_BT709: avio_wb16(pb, 1); break;
1836 case AVCOL_SPC_BT470BG:
1837 case AVCOL_SPC_SMPTE170M: avio_wb16(pb, 6); break;
1838 case AVCOL_SPC_SMPTE240M: avio_wb16(pb, 7); break;
1839 case AVCOL_SPC_BT2020_NCL: avio_wb16(pb, 9); break;
1840 default: avio_wb16(pb, 2);
1843 if (track->mode == MODE_MP4) {
1844 int full_range = track->par->color_range == AVCOL_RANGE_JPEG;
1845 avio_w8(pb, full_range << 7);
1852 static void find_compressor(char * compressor_name, int len, MOVTrack *track)
1854 AVDictionaryEntry *encoder;
1855 int xdcam_res = (track->par->width == 1280 && track->par->height == 720)
1856 || (track->par->width == 1440 && track->par->height == 1080)
1857 || (track->par->width == 1920 && track->par->height == 1080);
1859 if (track->mode == MODE_MOV &&
1860 (encoder = av_dict_get(track->st->metadata, "encoder", NULL, 0))) {
1861 av_strlcpy(compressor_name, encoder->value, 32);
1862 } else if (track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO && xdcam_res) {
1863 int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE;
1864 AVStream *st = track->st;
1865 int rate = defined_frame_rate(NULL, st);
1866 av_strlcatf(compressor_name, len, "XDCAM");
1867 if (track->par->format == AV_PIX_FMT_YUV422P) {
1868 av_strlcatf(compressor_name, len, " HD422");
1869 } else if(track->par->width == 1440) {
1870 av_strlcatf(compressor_name, len, " HD");
1872 av_strlcatf(compressor_name, len, " EX");
1874 av_strlcatf(compressor_name, len, " %d%c", track->par->height, interlaced ? 'i' : 'p');
1876 av_strlcatf(compressor_name, len, "%d", rate * (interlaced + 1));
1880 static int mov_write_video_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
1882 int64_t pos = avio_tell(pb);
1883 char compressor_name[32] = { 0 };
1886 int uncompressed_ycbcr = ((track->par->codec_id == AV_CODEC_ID_RAWVIDEO && track->par->format == AV_PIX_FMT_UYVY422)
1887 || (track->par->codec_id == AV_CODEC_ID_RAWVIDEO && track->par->format == AV_PIX_FMT_YUYV422)
1888 || track->par->codec_id == AV_CODEC_ID_V308
1889 || track->par->codec_id == AV_CODEC_ID_V408
1890 || track->par->codec_id == AV_CODEC_ID_V410
1891 || track->par->codec_id == AV_CODEC_ID_V210);
1893 avio_wb32(pb, 0); /* size */
1894 if (mov->encryption_scheme != MOV_ENC_NONE) {
1895 ffio_wfourcc(pb, "encv");
1897 avio_wl32(pb, track->tag); // store it byteswapped
1899 avio_wb32(pb, 0); /* Reserved */
1900 avio_wb16(pb, 0); /* Reserved */
1901 avio_wb16(pb, 1); /* Data-reference index */
1903 if (uncompressed_ycbcr) {
1904 avio_wb16(pb, 2); /* Codec stream version */
1906 avio_wb16(pb, 0); /* Codec stream version */
1908 avio_wb16(pb, 0); /* Codec stream revision (=0) */
1909 if (track->mode == MODE_MOV) {
1910 ffio_wfourcc(pb, "FFMP"); /* Vendor */
1911 if (track->par->codec_id == AV_CODEC_ID_RAWVIDEO || uncompressed_ycbcr) {
1912 avio_wb32(pb, 0); /* Temporal Quality */
1913 avio_wb32(pb, 0x400); /* Spatial Quality = lossless*/
1915 avio_wb32(pb, 0x200); /* Temporal Quality = normal */
1916 avio_wb32(pb, 0x200); /* Spatial Quality = normal */
1919 avio_wb32(pb, 0); /* Reserved */
1920 avio_wb32(pb, 0); /* Reserved */
1921 avio_wb32(pb, 0); /* Reserved */
1923 avio_wb16(pb, track->par->width); /* Video width */
1924 avio_wb16(pb, track->height); /* Video height */
1925 avio_wb32(pb, 0x00480000); /* Horizontal resolution 72dpi */
1926 avio_wb32(pb, 0x00480000); /* Vertical resolution 72dpi */
1927 avio_wb32(pb, 0); /* Data size (= 0) */
1928 avio_wb16(pb, 1); /* Frame count (= 1) */
1930 /* FIXME not sure, ISO 14496-1 draft where it shall be set to 0 */
1931 find_compressor(compressor_name, 32, track);
1932 avio_w8(pb, strlen(compressor_name));
1933 avio_write(pb, compressor_name, 31);
1935 if (track->mode == MODE_MOV &&
1936 (track->par->codec_id == AV_CODEC_ID_V410 || track->par->codec_id == AV_CODEC_ID_V210))
1937 avio_wb16(pb, 0x18);
1938 else if (track->mode == MODE_MOV && track->par->bits_per_coded_sample)
1939 avio_wb16(pb, track->par->bits_per_coded_sample |
1940 (track->par->format == AV_PIX_FMT_GRAY8 ? 0x20 : 0));
1942 avio_wb16(pb, 0x18); /* Reserved */
1944 if (track->mode == MODE_MOV && track->par->format == AV_PIX_FMT_PAL8) {
1945 int pal_size = 1 << track->par->bits_per_coded_sample;
1947 avio_wb16(pb, 0); /* Color table ID */
1948 avio_wb32(pb, 0); /* Color table seed */
1949 avio_wb16(pb, 0x8000); /* Color table flags */
1950 avio_wb16(pb, pal_size - 1); /* Color table size (zero-relative) */
1951 for (i = 0; i < pal_size; i++) {
1952 uint32_t rgb = track->palette[i];
1953 uint16_t r = (rgb >> 16) & 0xff;
1954 uint16_t g = (rgb >> 8) & 0xff;
1955 uint16_t b = rgb & 0xff;
1957 avio_wb16(pb, (r << 8) | r);
1958 avio_wb16(pb, (g << 8) | g);
1959 avio_wb16(pb, (b << 8) | b);
1962 avio_wb16(pb, 0xffff); /* Reserved */
1964 if (track->tag == MKTAG('m','p','4','v'))
1965 mov_write_esds_tag(pb, track);
1966 else if (track->par->codec_id == AV_CODEC_ID_H263)
1967 mov_write_d263_tag(pb);
1968 else if (track->par->codec_id == AV_CODEC_ID_AVUI ||
1969 track->par->codec_id == AV_CODEC_ID_SVQ3) {
1970 mov_write_extradata_tag(pb, track);
1972 } else if (track->par->codec_id == AV_CODEC_ID_DNXHD) {
1973 mov_write_avid_tag(pb, track);
1975 } else if (track->par->codec_id == AV_CODEC_ID_HEVC)
1976 mov_write_hvcc_tag(pb, track);
1977 else if (track->par->codec_id == AV_CODEC_ID_H264 && !TAG_IS_AVCI(track->tag)) {
1978 mov_write_avcc_tag(pb, track);
1979 if (track->mode == MODE_IPOD)
1980 mov_write_uuid_tag_ipod(pb);
1981 } else if (track->par->codec_id == AV_CODEC_ID_VP9) {
1982 mov_write_vpcc_tag(mov->fc, pb, track);
1983 } else if (track->par->codec_id == AV_CODEC_ID_VC1 && track->vos_len > 0)
1984 mov_write_dvc1_tag(pb, track);
1985 else if (track->par->codec_id == AV_CODEC_ID_VP6F ||
1986 track->par->codec_id == AV_CODEC_ID_VP6A) {
1987 /* Don't write any potential extradata here - the cropping
1988 * is signalled via the normal width/height fields. */
1989 } else if (track->par->codec_id == AV_CODEC_ID_R10K) {
1990 if (track->par->codec_tag == MKTAG('R','1','0','k'))
1991 mov_write_dpxe_tag(pb, track);
1992 } else if (track->vos_len > 0)
1993 mov_write_glbl_tag(pb, track);
1995 if (track->par->codec_id != AV_CODEC_ID_H264 &&
1996 track->par->codec_id != AV_CODEC_ID_MPEG4 &&
1997 track->par->codec_id != AV_CODEC_ID_DNXHD) {
1998 int field_order = track->par->field_order;
2000 #if FF_API_LAVF_AVCTX
2001 FF_DISABLE_DEPRECATION_WARNINGS
2002 if (field_order != track->st->codec->field_order && track->st->codec->field_order != AV_FIELD_UNKNOWN)
2003 field_order = track->st->codec->field_order;
2004 FF_ENABLE_DEPRECATION_WARNINGS
2007 if (field_order != AV_FIELD_UNKNOWN)
2008 mov_write_fiel_tag(pb, track, field_order);
2011 if (mov->flags & FF_MOV_FLAG_WRITE_GAMA) {
2012 if (track->mode == MODE_MOV)
2013 mov_write_gama_tag(pb, track, mov->gamma);
2015 av_log(mov->fc, AV_LOG_WARNING, "Not writing 'gama' atom. Format is not MOV.\n");
2017 if (mov->flags & FF_MOV_FLAG_WRITE_COLR) {
2018 if (track->mode == MODE_MOV || track->mode == MODE_MP4)
2019 mov_write_colr_tag(pb, track);
2021 av_log(mov->fc, AV_LOG_WARNING, "Not writing 'colr' atom. Format is not MOV or MP4.\n");
2024 if (track->mode == MODE_MP4 && mov->fc->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL) {
2025 AVStereo3D* stereo_3d = (AVStereo3D*) av_stream_get_side_data(track->st, AV_PKT_DATA_STEREO3D, NULL);
2026 AVSphericalMapping* spherical_mapping = (AVSphericalMapping*)av_stream_get_side_data(track->st, AV_PKT_DATA_SPHERICAL, NULL);
2029 mov_write_st3d_tag(pb, stereo_3d);
2030 if (spherical_mapping)
2031 mov_write_sv3d_tag(mov->fc, pb, spherical_mapping);
2034 if (track->par->sample_aspect_ratio.den && track->par->sample_aspect_ratio.num) {
2035 mov_write_pasp_tag(pb, track);
2038 if (uncompressed_ycbcr){
2039 mov_write_clap_tag(pb, track);
2042 if (mov->encryption_scheme != MOV_ENC_NONE) {
2043 ff_mov_cenc_write_sinf_tag(track, pb, mov->encryption_kid);
2046 /* extra padding for avid stsd */
2047 /* https://developer.apple.com/library/mac/documentation/QuickTime/QTFF/QTFFChap2/qtff2.html#//apple_ref/doc/uid/TP40000939-CH204-61112 */
2051 return update_size(pb, pos);
2054 static int mov_write_rtp_tag(AVIOContext *pb, MOVTrack *track)
2056 int64_t pos = avio_tell(pb);
2057 avio_wb32(pb, 0); /* size */
2058 ffio_wfourcc(pb, "rtp ");
2059 avio_wb32(pb, 0); /* Reserved */
2060 avio_wb16(pb, 0); /* Reserved */
2061 avio_wb16(pb, 1); /* Data-reference index */
2063 avio_wb16(pb, 1); /* Hint track version */
2064 avio_wb16(pb, 1); /* Highest compatible version */
2065 avio_wb32(pb, track->max_packet_size); /* Max packet size */
2067 avio_wb32(pb, 12); /* size */
2068 ffio_wfourcc(pb, "tims");
2069 avio_wb32(pb, track->timescale);
2071 return update_size(pb, pos);
2074 static int mov_write_source_reference_tag(AVIOContext *pb, MOVTrack *track, const char *reel_name)
2076 uint64_t str_size =strlen(reel_name);
2077 int64_t pos = avio_tell(pb);
2079 if (str_size >= UINT16_MAX){
2080 av_log(NULL, AV_LOG_ERROR, "reel_name length %"PRIu64" is too large\n", str_size);
2082 return AVERROR(EINVAL);
2085 avio_wb32(pb, 0); /* size */
2086 ffio_wfourcc(pb, "name"); /* Data format */
2087 avio_wb16(pb, str_size); /* string size */
2088 avio_wb16(pb, track->language); /* langcode */
2089 avio_write(pb, reel_name, str_size); /* reel name */
2090 return update_size(pb,pos);
2093 static int mov_write_tmcd_tag(AVIOContext *pb, MOVTrack *track)
2095 int64_t pos = avio_tell(pb);
2099 AVDictionaryEntry *t = NULL;
2101 if (!track->st->avg_frame_rate.num || !track->st->avg_frame_rate.den) {
2102 #if FF_API_LAVF_AVCTX
2103 FF_DISABLE_DEPRECATION_WARNINGS
2104 frame_duration = av_rescale(track->timescale, track->st->codec->time_base.num, track->st->codec->time_base.den);
2105 nb_frames = ROUNDED_DIV(track->st->codec->time_base.den, track->st->codec->time_base.num);
2106 FF_ENABLE_DEPRECATION_WARNINGS
2108 av_log(NULL, AV_LOG_ERROR, "avg_frame_rate not set for tmcd track.\n");
2109 return AVERROR(EINVAL);
2112 frame_duration = av_rescale(track->timescale, track->st->avg_frame_rate.num, track->st->avg_frame_rate.den);
2113 nb_frames = ROUNDED_DIV(track->st->avg_frame_rate.den, track->st->avg_frame_rate.num);
2116 if (nb_frames > 255) {
2117 av_log(NULL, AV_LOG_ERROR, "fps %d is too large\n", nb_frames);
2118 return AVERROR(EINVAL);
2121 avio_wb32(pb, 0); /* size */
2122 ffio_wfourcc(pb, "tmcd"); /* Data format */
2123 avio_wb32(pb, 0); /* Reserved */
2124 avio_wb32(pb, 1); /* Data reference index */
2125 avio_wb32(pb, 0); /* Flags */
2126 avio_wb32(pb, track->timecode_flags); /* Flags (timecode) */
2127 avio_wb32(pb, track->timescale); /* Timescale */
2128 avio_wb32(pb, frame_duration); /* Frame duration */
2129 avio_w8(pb, nb_frames); /* Number of frames */
2130 avio_w8(pb, 0); /* Reserved */
2132 t = av_dict_get(track->st->metadata, "reel_name", NULL, 0);
2133 if (t && utf8len(t->value) && track->mode != MODE_MP4)
2134 mov_write_source_reference_tag(pb, track, t->value);
2136 avio_wb16(pb, 0); /* zero size */
2139 avio_wb32(pb, 0); /* size */
2140 ffio_wfourcc(pb, "tmcd"); /* Data format */
2141 avio_wb32(pb, 0); /* Reserved */
2142 avio_wb32(pb, 1); /* Data reference index */
2143 if (track->par->extradata_size)
2144 avio_write(pb, track->par->extradata, track->par->extradata_size);
2146 return update_size(pb, pos);
2149 static int mov_write_gpmd_tag(AVIOContext *pb, const MOVTrack *track)
2151 int64_t pos = avio_tell(pb);
2152 avio_wb32(pb, 0); /* size */
2153 ffio_wfourcc(pb, "gpmd");
2154 avio_wb32(pb, 0); /* Reserved */
2155 avio_wb16(pb, 0); /* Reserved */
2156 avio_wb16(pb, 1); /* Data-reference index */
2157 avio_wb32(pb, 0); /* Reserved */
2158 return update_size(pb, pos);
2161 static int mov_write_stsd_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
2163 int64_t pos = avio_tell(pb);
2164 avio_wb32(pb, 0); /* size */
2165 ffio_wfourcc(pb, "stsd");
2166 avio_wb32(pb, 0); /* version & flags */
2167 avio_wb32(pb, 1); /* entry count */
2168 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO)
2169 mov_write_video_tag(pb, mov, track);
2170 else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
2171 mov_write_audio_tag(s, pb, mov, track);
2172 else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)
2173 mov_write_subtitle_tag(pb, track);
2174 else if (track->par->codec_tag == MKTAG('r','t','p',' '))
2175 mov_write_rtp_tag(pb, track);
2176 else if (track->par->codec_tag == MKTAG('t','m','c','d'))
2177 mov_write_tmcd_tag(pb, track);
2178 else if (track->par->codec_tag == MKTAG('g','p','m','d'))
2179 mov_write_gpmd_tag(pb, track);
2180 return update_size(pb, pos);
2183 static int mov_write_ctts_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
2185 MOVMuxContext *mov = s->priv_data;
2186 MOVStts *ctts_entries;
2187 uint32_t entries = 0;
2191 ctts_entries = av_malloc_array((track->entry + 1), sizeof(*ctts_entries)); /* worst case */
2193 return AVERROR(ENOMEM);
2194 ctts_entries[0].count = 1;
2195 ctts_entries[0].duration = track->cluster[0].cts;
2196 for (i = 1; i < track->entry; i++) {
2197 if (track->cluster[i].cts == ctts_entries[entries].duration) {
2198 ctts_entries[entries].count++; /* compress */
2201 ctts_entries[entries].duration = track->cluster[i].cts;
2202 ctts_entries[entries].count = 1;
2205 entries++; /* last one */
2206 atom_size = 16 + (entries * 8);
2207 avio_wb32(pb, atom_size); /* size */
2208 ffio_wfourcc(pb, "ctts");
2209 if (mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS)
2210 avio_w8(pb, 1); /* version */
2212 avio_w8(pb, 0); /* version */
2213 avio_wb24(pb, 0); /* flags */
2214 avio_wb32(pb, entries); /* entry count */
2215 for (i = 0; i < entries; i++) {
2216 avio_wb32(pb, ctts_entries[i].count);
2217 avio_wb32(pb, ctts_entries[i].duration);
2219 av_free(ctts_entries);
2223 /* Time to sample atom */
2224 static int mov_write_stts_tag(AVIOContext *pb, MOVTrack *track)
2226 MOVStts *stts_entries = NULL;
2227 uint32_t entries = -1;
2231 if (track->par->codec_type == AVMEDIA_TYPE_AUDIO && !track->audio_vbr) {
2232 stts_entries = av_malloc(sizeof(*stts_entries)); /* one entry */
2234 return AVERROR(ENOMEM);
2235 stts_entries[0].count = track->sample_count;
2236 stts_entries[0].duration = 1;
2240 stts_entries = av_malloc_array(track->entry, sizeof(*stts_entries)); /* worst case */
2242 return AVERROR(ENOMEM);
2244 for (i = 0; i < track->entry; i++) {
2245 int duration = get_cluster_duration(track, i);
2246 if (i && duration == stts_entries[entries].duration) {
2247 stts_entries[entries].count++; /* compress */
2250 stts_entries[entries].duration = duration;
2251 stts_entries[entries].count = 1;
2254 entries++; /* last one */
2256 atom_size = 16 + (entries * 8);
2257 avio_wb32(pb, atom_size); /* size */
2258 ffio_wfourcc(pb, "stts");
2259 avio_wb32(pb, 0); /* version & flags */
2260 avio_wb32(pb, entries); /* entry count */
2261 for (i = 0; i < entries; i++) {
2262 avio_wb32(pb, stts_entries[i].count);
2263 avio_wb32(pb, stts_entries[i].duration);
2265 av_free(stts_entries);
2269 static int mov_write_dref_tag(AVIOContext *pb)
2271 avio_wb32(pb, 28); /* size */
2272 ffio_wfourcc(pb, "dref");
2273 avio_wb32(pb, 0); /* version & flags */
2274 avio_wb32(pb, 1); /* entry count */
2276 avio_wb32(pb, 0xc); /* size */
2277 //FIXME add the alis and rsrc atom
2278 ffio_wfourcc(pb, "url ");
2279 avio_wb32(pb, 1); /* version & flags */
2284 static int mov_preroll_write_stbl_atoms(AVIOContext *pb, MOVTrack *track)
2288 int16_t roll_distance;
2289 int group_description_index;
2292 struct sgpd_entry *sgpd_entries = NULL;
2297 const int OPUS_SEEK_PREROLL_MS = 80;
2298 int roll_samples = av_rescale_q(OPUS_SEEK_PREROLL_MS,
2299 (AVRational){1, 1000},
2300 (AVRational){1, 48000});
2305 sgpd_entries = av_malloc_array(track->entry, sizeof(*sgpd_entries));
2307 return AVERROR(ENOMEM);
2309 av_assert0(track->par->codec_id == AV_CODEC_ID_OPUS || track->par->codec_id == AV_CODEC_ID_AAC);
2311 if (track->par->codec_id == AV_CODEC_ID_OPUS) {
2312 for (i = 0; i < track->entry; i++) {
2313 int roll_samples_remaining = roll_samples;
2315 for (j = i - 1; j >= 0; j--) {
2316 roll_samples_remaining -= get_cluster_duration(track, j);
2318 if (roll_samples_remaining <= 0)
2321 /* We don't have enough preceeding samples to compute a valid
2322 roll_distance here, so this sample can't be independently
2324 if (roll_samples_remaining > 0)
2326 /* Verify distance is a minimum of 2 (60ms) packets and a maximum of
2327 32 (2.5ms) packets. */
2328 av_assert0(distance == 0 || (distance >= 2 && distance <= 32));
2329 if (i && distance == sgpd_entries[entries].roll_distance) {
2330 sgpd_entries[entries].count++;
2333 sgpd_entries[entries].count = 1;
2334 sgpd_entries[entries].roll_distance = distance;
2335 sgpd_entries[entries].group_description_index = distance ? ++group : 0;
2340 sgpd_entries[entries].count = track->sample_count;
2341 sgpd_entries[entries].roll_distance = 1;
2342 sgpd_entries[entries].group_description_index = ++group;
2347 av_free(sgpd_entries);
2351 /* Write sgpd tag */
2352 avio_wb32(pb, 24 + (group * 2)); /* size */
2353 ffio_wfourcc(pb, "sgpd");
2354 avio_wb32(pb, 1 << 24); /* fullbox */
2355 ffio_wfourcc(pb, "roll");
2356 avio_wb32(pb, 2); /* default_length */
2357 avio_wb32(pb, group); /* entry_count */
2358 for (i = 0; i < entries; i++) {
2359 if (sgpd_entries[i].group_description_index) {
2360 avio_wb16(pb, -sgpd_entries[i].roll_distance); /* roll_distance */
2364 /* Write sbgp tag */
2365 avio_wb32(pb, 20 + (entries * 8)); /* size */
2366 ffio_wfourcc(pb, "sbgp");
2367 avio_wb32(pb, 0); /* fullbox */
2368 ffio_wfourcc(pb, "roll");
2369 avio_wb32(pb, entries); /* entry_count */
2370 for (i = 0; i < entries; i++) {
2371 avio_wb32(pb, sgpd_entries[i].count); /* sample_count */
2372 avio_wb32(pb, sgpd_entries[i].group_description_index); /* group_description_index */
2375 av_free(sgpd_entries);
2379 static int mov_write_stbl_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
2381 int64_t pos = avio_tell(pb);
2384 avio_wb32(pb, 0); /* size */
2385 ffio_wfourcc(pb, "stbl");
2386 mov_write_stsd_tag(s, pb, mov, track);
2387 mov_write_stts_tag(pb, track);
2388 if ((track->par->codec_type == AVMEDIA_TYPE_VIDEO ||
2389 track->par->codec_tag == MKTAG('r','t','p',' ')) &&
2390 track->has_keyframes && track->has_keyframes < track->entry)
2391 mov_write_stss_tag(pb, track, MOV_SYNC_SAMPLE);
2392 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO && track->has_disposable)
2393 mov_write_sdtp_tag(pb, track);
2394 if (track->mode == MODE_MOV && track->flags & MOV_TRACK_STPS)
2395 mov_write_stss_tag(pb, track, MOV_PARTIAL_SYNC_SAMPLE);
2396 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO &&
2397 track->flags & MOV_TRACK_CTTS && track->entry) {
2399 if ((ret = mov_write_ctts_tag(s, pb, track)) < 0)
2402 mov_write_stsc_tag(pb, track);
2403 mov_write_stsz_tag(pb, track);
2404 mov_write_stco_tag(pb, track);
2405 if (track->cenc.aes_ctr) {
2406 ff_mov_cenc_write_stbl_atoms(&track->cenc, pb);
2408 if (track->par->codec_id == AV_CODEC_ID_OPUS || track->par->codec_id == AV_CODEC_ID_AAC) {
2409 mov_preroll_write_stbl_atoms(pb, track);
2411 return update_size(pb, pos);
2414 static int mov_write_dinf_tag(AVIOContext *pb)
2416 int64_t pos = avio_tell(pb);
2417 avio_wb32(pb, 0); /* size */
2418 ffio_wfourcc(pb, "dinf");
2419 mov_write_dref_tag(pb);
2420 return update_size(pb, pos);
2423 static int mov_write_nmhd_tag(AVIOContext *pb)
2426 ffio_wfourcc(pb, "nmhd");
2431 static int mov_write_tcmi_tag(AVIOContext *pb, MOVTrack *track)
2433 int64_t pos = avio_tell(pb);
2434 const char *font = "Lucida Grande";
2435 avio_wb32(pb, 0); /* size */
2436 ffio_wfourcc(pb, "tcmi"); /* timecode media information atom */
2437 avio_wb32(pb, 0); /* version & flags */
2438 avio_wb16(pb, 0); /* text font */
2439 avio_wb16(pb, 0); /* text face */
2440 avio_wb16(pb, 12); /* text size */
2441 avio_wb16(pb, 0); /* (unknown, not in the QT specs...) */
2442 avio_wb16(pb, 0x0000); /* text color (red) */
2443 avio_wb16(pb, 0x0000); /* text color (green) */
2444 avio_wb16(pb, 0x0000); /* text color (blue) */
2445 avio_wb16(pb, 0xffff); /* background color (red) */
2446 avio_wb16(pb, 0xffff); /* background color (green) */
2447 avio_wb16(pb, 0xffff); /* background color (blue) */
2448 avio_w8(pb, strlen(font)); /* font len (part of the pascal string) */
2449 avio_write(pb, font, strlen(font)); /* font name */
2450 return update_size(pb, pos);
2453 static int mov_write_gmhd_tag(AVIOContext *pb, MOVTrack *track)
2455 int64_t pos = avio_tell(pb);
2456 avio_wb32(pb, 0); /* size */
2457 ffio_wfourcc(pb, "gmhd");
2458 avio_wb32(pb, 0x18); /* gmin size */
2459 ffio_wfourcc(pb, "gmin");/* generic media info */
2460 avio_wb32(pb, 0); /* version & flags */
2461 avio_wb16(pb, 0x40); /* graphics mode = */
2462 avio_wb16(pb, 0x8000); /* opColor (r?) */
2463 avio_wb16(pb, 0x8000); /* opColor (g?) */
2464 avio_wb16(pb, 0x8000); /* opColor (b?) */
2465 avio_wb16(pb, 0); /* balance */
2466 avio_wb16(pb, 0); /* reserved */
2469 * This special text atom is required for
2470 * Apple Quicktime chapters. The contents
2471 * don't appear to be documented, so the
2472 * bytes are copied verbatim.
2474 if (track->tag != MKTAG('c','6','0','8')) {
2475 avio_wb32(pb, 0x2C); /* size */
2476 ffio_wfourcc(pb, "text");
2477 avio_wb16(pb, 0x01);
2478 avio_wb32(pb, 0x00);
2479 avio_wb32(pb, 0x00);
2480 avio_wb32(pb, 0x00);
2481 avio_wb32(pb, 0x01);
2482 avio_wb32(pb, 0x00);
2483 avio_wb32(pb, 0x00);
2484 avio_wb32(pb, 0x00);
2485 avio_wb32(pb, 0x00004000);
2486 avio_wb16(pb, 0x0000);
2489 if (track->par->codec_tag == MKTAG('t','m','c','d')) {
2490 int64_t tmcd_pos = avio_tell(pb);
2491 avio_wb32(pb, 0); /* size */
2492 ffio_wfourcc(pb, "tmcd");
2493 mov_write_tcmi_tag(pb, track);
2494 update_size(pb, tmcd_pos);
2495 } else if (track->par->codec_tag == MKTAG('g','p','m','d')) {
2496 int64_t gpmd_pos = avio_tell(pb);
2497 avio_wb32(pb, 0); /* size */
2498 ffio_wfourcc(pb, "gpmd");
2499 avio_wb32(pb, 0); /* version */
2500 update_size(pb, gpmd_pos);
2502 return update_size(pb, pos);
2505 static int mov_write_smhd_tag(AVIOContext *pb)
2507 avio_wb32(pb, 16); /* size */
2508 ffio_wfourcc(pb, "smhd");
2509 avio_wb32(pb, 0); /* version & flags */
2510 avio_wb16(pb, 0); /* reserved (balance, normally = 0) */
2511 avio_wb16(pb, 0); /* reserved */
2515 static int mov_write_vmhd_tag(AVIOContext *pb)
2517 avio_wb32(pb, 0x14); /* size (always 0x14) */
2518 ffio_wfourcc(pb, "vmhd");
2519 avio_wb32(pb, 0x01); /* version & flags */
2520 avio_wb64(pb, 0); /* reserved (graphics mode = copy) */
2524 static int is_clcp_track(MOVTrack *track)
2526 return track->tag == MKTAG('c','7','0','8') ||
2527 track->tag == MKTAG('c','6','0','8');
2530 static int mov_write_hdlr_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
2532 const char *hdlr, *descr = NULL, *hdlr_type = NULL;
2533 int64_t pos = avio_tell(pb);
2537 descr = "DataHandler";
2540 hdlr = (track->mode == MODE_MOV) ? "mhlr" : "\0\0\0\0";
2541 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
2543 descr = "VideoHandler";
2544 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
2546 descr = "SoundHandler";
2547 } else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE) {
2548 if (is_clcp_track(track)) {
2550 descr = "ClosedCaptionHandler";
2552 if (track->tag == MKTAG('t','x','3','g')) {
2554 } else if (track->tag == MKTAG('m','p','4','s')) {
2559 descr = "SubtitleHandler";
2561 } else if (track->par->codec_tag == MKTAG('r','t','p',' ')) {
2563 descr = "HintHandler";
2564 } else if (track->par->codec_tag == MKTAG('t','m','c','d')) {
2566 descr = "TimeCodeHandler";
2567 } else if (track->par->codec_tag == MKTAG('g','p','m','d')) {
2569 descr = "GoPro MET"; // GoPro Metadata
2571 av_log(s, AV_LOG_WARNING,
2572 "Unknown hldr_type for %s, writing dummy values\n",
2573 av_fourcc2str(track->par->codec_tag));
2576 // hdlr.name is used by some players to identify the content title
2577 // of the track. So if an alternate handler description is
2578 // specified, use it.
2579 AVDictionaryEntry *t;
2580 t = av_dict_get(track->st->metadata, "handler", NULL, 0);
2581 if (t && utf8len(t->value))
2586 avio_wb32(pb, 0); /* size */
2587 ffio_wfourcc(pb, "hdlr");
2588 avio_wb32(pb, 0); /* Version & flags */
2589 avio_write(pb, hdlr, 4); /* handler */
2590 ffio_wfourcc(pb, hdlr_type); /* handler type */
2591 avio_wb32(pb, 0); /* reserved */
2592 avio_wb32(pb, 0); /* reserved */
2593 avio_wb32(pb, 0); /* reserved */
2594 if (!track || track->mode == MODE_MOV)
2595 avio_w8(pb, strlen(descr)); /* pascal string */
2596 avio_write(pb, descr, strlen(descr)); /* handler description */
2597 if (track && track->mode != MODE_MOV)
2598 avio_w8(pb, 0); /* c string */
2599 return update_size(pb, pos);
2602 static int mov_write_hmhd_tag(AVIOContext *pb)
2604 /* This atom must be present, but leaving the values at zero
2605 * seems harmless. */
2606 avio_wb32(pb, 28); /* size */
2607 ffio_wfourcc(pb, "hmhd");
2608 avio_wb32(pb, 0); /* version, flags */
2609 avio_wb16(pb, 0); /* maxPDUsize */
2610 avio_wb16(pb, 0); /* avgPDUsize */
2611 avio_wb32(pb, 0); /* maxbitrate */
2612 avio_wb32(pb, 0); /* avgbitrate */
2613 avio_wb32(pb, 0); /* reserved */
2617 static int mov_write_minf_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
2619 int64_t pos = avio_tell(pb);
2622 avio_wb32(pb, 0); /* size */
2623 ffio_wfourcc(pb, "minf");
2624 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO)
2625 mov_write_vmhd_tag(pb);
2626 else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
2627 mov_write_smhd_tag(pb);
2628 else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE) {
2629 if (track->tag == MKTAG('t','e','x','t') || is_clcp_track(track)) {
2630 mov_write_gmhd_tag(pb, track);
2632 mov_write_nmhd_tag(pb);
2634 } else if (track->tag == MKTAG('r','t','p',' ')) {
2635 mov_write_hmhd_tag(pb);
2636 } else if (track->tag == MKTAG('t','m','c','d')) {
2637 if (track->mode != MODE_MOV)
2638 mov_write_nmhd_tag(pb);
2640 mov_write_gmhd_tag(pb, track);
2641 } else if (track->tag == MKTAG('g','p','m','d')) {
2642 mov_write_gmhd_tag(pb, track);
2644 if (track->mode == MODE_MOV) /* FIXME: Why do it for MODE_MOV only ? */
2645 mov_write_hdlr_tag(s, pb, NULL);
2646 mov_write_dinf_tag(pb);
2647 if ((ret = mov_write_stbl_tag(s, pb, mov, track)) < 0)
2649 return update_size(pb, pos);
2652 static int mov_write_mdhd_tag(AVIOContext *pb, MOVMuxContext *mov,
2655 int version = track->track_duration < INT32_MAX ? 0 : 1;
2657 if (track->mode == MODE_ISM)
2660 (version == 1) ? avio_wb32(pb, 44) : avio_wb32(pb, 32); /* size */
2661 ffio_wfourcc(pb, "mdhd");
2662 avio_w8(pb, version);
2663 avio_wb24(pb, 0); /* flags */
2665 avio_wb64(pb, track->time);
2666 avio_wb64(pb, track->time);
2668 avio_wb32(pb, track->time); /* creation time */
2669 avio_wb32(pb, track->time); /* modification time */
2671 avio_wb32(pb, track->timescale); /* time scale (sample rate for audio) */
2672 if (!track->entry && mov->mode == MODE_ISM)
2673 (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
2674 else if (!track->entry)
2675 (version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0);
2677 (version == 1) ? avio_wb64(pb, track->track_duration) : avio_wb32(pb, track->track_duration); /* duration */
2678 avio_wb16(pb, track->language); /* language */
2679 avio_wb16(pb, 0); /* reserved (quality) */
2681 if (version != 0 && track->mode == MODE_MOV) {
2682 av_log(NULL, AV_LOG_ERROR,
2683 "FATAL error, file duration too long for timebase, this file will not be\n"
2684 "playable with quicktime. Choose a different timebase or a different\n"
2685 "container format\n");
2691 static int mov_write_mdia_tag(AVFormatContext *s, AVIOContext *pb,
2692 MOVMuxContext *mov, MOVTrack *track)
2694 int64_t pos = avio_tell(pb);
2697 avio_wb32(pb, 0); /* size */
2698 ffio_wfourcc(pb, "mdia");
2699 mov_write_mdhd_tag(pb, mov, track);
2700 mov_write_hdlr_tag(s, pb, track);
2701 if ((ret = mov_write_minf_tag(s, pb, mov, track)) < 0)
2703 return update_size(pb, pos);
2706 /* transformation matrix
2710 static void write_matrix(AVIOContext *pb, int16_t a, int16_t b, int16_t c,
2711 int16_t d, int16_t tx, int16_t ty)
2713 avio_wb32(pb, a << 16); /* 16.16 format */
2714 avio_wb32(pb, b << 16); /* 16.16 format */
2715 avio_wb32(pb, 0); /* u in 2.30 format */
2716 avio_wb32(pb, c << 16); /* 16.16 format */
2717 avio_wb32(pb, d << 16); /* 16.16 format */
2718 avio_wb32(pb, 0); /* v in 2.30 format */
2719 avio_wb32(pb, tx << 16); /* 16.16 format */
2720 avio_wb32(pb, ty << 16); /* 16.16 format */
2721 avio_wb32(pb, 1 << 30); /* w in 2.30 format */
2724 static int mov_write_tkhd_tag(AVIOContext *pb, MOVMuxContext *mov,
2725 MOVTrack *track, AVStream *st)
2727 int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE,
2728 track->timescale, AV_ROUND_UP);
2729 int version = duration < INT32_MAX ? 0 : 1;
2730 int flags = MOV_TKHD_FLAG_IN_MOVIE;
2734 uint32_t *display_matrix = NULL;
2735 int display_matrix_size, i;
2738 if (mov->per_stream_grouping)
2741 group = st->codecpar->codec_type;
2743 display_matrix = (uint32_t*)av_stream_get_side_data(st, AV_PKT_DATA_DISPLAYMATRIX,
2744 &display_matrix_size);
2745 if (display_matrix && display_matrix_size < 9 * sizeof(*display_matrix))
2746 display_matrix = NULL;
2749 if (track->flags & MOV_TRACK_ENABLED)
2750 flags |= MOV_TKHD_FLAG_ENABLED;
2752 if (track->mode == MODE_ISM)
2755 (version == 1) ? avio_wb32(pb, 104) : avio_wb32(pb, 92); /* size */
2756 ffio_wfourcc(pb, "tkhd");
2757 avio_w8(pb, version);
2758 avio_wb24(pb, flags);
2760 avio_wb64(pb, track->time);
2761 avio_wb64(pb, track->time);
2763 avio_wb32(pb, track->time); /* creation time */
2764 avio_wb32(pb, track->time); /* modification time */
2766 avio_wb32(pb, track->track_id); /* track-id */
2767 avio_wb32(pb, 0); /* reserved */
2768 if (!track->entry && mov->mode == MODE_ISM)
2769 (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
2770 else if (!track->entry)
2771 (version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0);
2773 (version == 1) ? avio_wb64(pb, duration) : avio_wb32(pb, duration);
2775 avio_wb32(pb, 0); /* reserved */
2776 avio_wb32(pb, 0); /* reserved */
2777 avio_wb16(pb, 0); /* layer */
2778 avio_wb16(pb, group); /* alternate group) */
2779 /* Volume, only for audio */
2780 if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
2781 avio_wb16(pb, 0x0100);
2784 avio_wb16(pb, 0); /* reserved */
2786 /* Matrix structure */
2787 #if FF_API_OLD_ROTATE_API
2788 if (st && st->metadata) {
2789 AVDictionaryEntry *rot = av_dict_get(st->metadata, "rotate", NULL, 0);
2790 rotation = (rot && rot->value) ? atoi(rot->value) : 0;
2793 if (display_matrix) {
2794 for (i = 0; i < 9; i++)
2795 avio_wb32(pb, display_matrix[i]);
2796 #if FF_API_OLD_ROTATE_API
2797 } else if (rotation == 90) {
2798 write_matrix(pb, 0, 1, -1, 0, track->par->height, 0);
2799 } else if (rotation == 180) {
2800 write_matrix(pb, -1, 0, 0, -1, track->par->width, track->par->height);
2801 } else if (rotation == 270) {
2802 write_matrix(pb, 0, -1, 1, 0, 0, track->par->width);
2805 write_matrix(pb, 1, 0, 0, 1, 0, 0);
2807 /* Track width and height, for visual only */
2808 if (st && (track->par->codec_type == AVMEDIA_TYPE_VIDEO ||
2809 track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)) {
2810 int64_t track_width_1616;
2811 if (track->mode == MODE_MOV) {
2812 track_width_1616 = track->par->width * 0x10000ULL;
2814 track_width_1616 = av_rescale(st->sample_aspect_ratio.num,
2815 track->par->width * 0x10000LL,
2816 st->sample_aspect_ratio.den);
2817 if (!track_width_1616 ||
2818 track->height != track->par->height ||
2819 track_width_1616 > UINT32_MAX)
2820 track_width_1616 = track->par->width * 0x10000ULL;
2822 if (track_width_1616 > UINT32_MAX) {
2823 av_log(mov->fc, AV_LOG_WARNING, "track width is too large\n");
2824 track_width_1616 = 0;
2826 avio_wb32(pb, track_width_1616);
2827 if (track->height > 0xFFFF) {
2828 av_log(mov->fc, AV_LOG_WARNING, "track height is too large\n");
2831 avio_wb32(pb, track->height * 0x10000U);
2839 static int mov_write_tapt_tag(AVIOContext *pb, MOVTrack *track)
2841 int32_t width = av_rescale(track->par->sample_aspect_ratio.num, track->par->width,
2842 track->par->sample_aspect_ratio.den);
2844 int64_t pos = avio_tell(pb);
2846 avio_wb32(pb, 0); /* size */
2847 ffio_wfourcc(pb, "tapt");
2850 ffio_wfourcc(pb, "clef");
2852 avio_wb32(pb, width << 16);
2853 avio_wb32(pb, track->par->height << 16);
2856 ffio_wfourcc(pb, "prof");
2858 avio_wb32(pb, width << 16);
2859 avio_wb32(pb, track->par->height << 16);
2862 ffio_wfourcc(pb, "enof");
2864 avio_wb32(pb, track->par->width << 16);
2865 avio_wb32(pb, track->par->height << 16);
2867 return update_size(pb, pos);
2870 // This box seems important for the psp playback ... without it the movie seems to hang
2871 static int mov_write_edts_tag(AVIOContext *pb, MOVMuxContext *mov,
2874 int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE,
2875 track->timescale, AV_ROUND_UP);
2876 int version = duration < INT32_MAX ? 0 : 1;
2877 int entry_size, entry_count, size;
2878 int64_t delay, start_ct = track->start_cts;
2879 int64_t start_dts = track->start_dts;
2882 if (start_dts != track->cluster[0].dts || start_ct != track->cluster[0].cts) {
2884 av_log(mov->fc, AV_LOG_DEBUG,
2885 "EDTS using dts:%"PRId64" cts:%d instead of dts:%"PRId64" cts:%"PRId64" tid:%d\n",
2886 track->cluster[0].dts, track->cluster[0].cts,
2887 start_dts, start_ct, track->track_id);
2888 start_dts = track->cluster[0].dts;
2889 start_ct = track->cluster[0].cts;
2893 delay = av_rescale_rnd(start_dts + start_ct, MOV_TIMESCALE,
2894 track->timescale, AV_ROUND_DOWN);
2895 version |= delay < INT32_MAX ? 0 : 1;
2897 entry_size = (version == 1) ? 20 : 12;
2898 entry_count = 1 + (delay > 0);
2899 size = 24 + entry_count * entry_size;
2901 /* write the atom data */
2902 avio_wb32(pb, size);
2903 ffio_wfourcc(pb, "edts");
2904 avio_wb32(pb, size - 8);
2905 ffio_wfourcc(pb, "elst");
2906 avio_w8(pb, version);
2907 avio_wb24(pb, 0); /* flags */
2909 avio_wb32(pb, entry_count);
2910 if (delay > 0) { /* add an empty edit to delay presentation */
2911 /* In the positive delay case, the delay includes the cts
2912 * offset, and the second edit list entry below trims out
2913 * the same amount from the actual content. This makes sure
2914 * that the offset last sample is included in the edit
2915 * list duration as well. */
2917 avio_wb64(pb, delay);
2920 avio_wb32(pb, delay);
2923 avio_wb32(pb, 0x00010000);
2925 /* Avoid accidentally ending up with start_ct = -1 which has got a
2926 * special meaning. Normally start_ct should end up positive or zero
2927 * here, but use FFMIN in case dts is a small positive integer
2928 * rounded to 0 when represented in MOV_TIMESCALE units. */
2929 av_assert0(av_rescale_rnd(start_dts, MOV_TIMESCALE, track->timescale, AV_ROUND_DOWN) <= 0);
2930 start_ct = -FFMIN(start_dts, 0);
2931 /* Note, this delay is calculated from the pts of the first sample,
2932 * ensuring that we don't reduce the duration for cases with
2937 /* For fragmented files, we don't know the full length yet. Setting
2938 * duration to 0 allows us to only specify the offset, including
2939 * the rest of the content (from all future fragments) without specifying
2940 * an explicit duration. */
2941 if (mov->flags & FF_MOV_FLAG_FRAGMENT)
2946 avio_wb64(pb, duration);
2947 avio_wb64(pb, start_ct);
2949 avio_wb32(pb, duration);
2950 avio_wb32(pb, start_ct);
2952 avio_wb32(pb, 0x00010000);
2956 static int mov_write_tref_tag(AVIOContext *pb, MOVTrack *track)
2958 avio_wb32(pb, 20); // size
2959 ffio_wfourcc(pb, "tref");
2960 avio_wb32(pb, 12); // size (subatom)
2961 avio_wl32(pb, track->tref_tag);
2962 avio_wb32(pb, track->tref_id);
2966 // goes at the end of each track! ... Critical for PSP playback ("Incompatible data" without it)
2967 static int mov_write_uuid_tag_psp(AVIOContext *pb, MOVTrack *mov)
2969 avio_wb32(pb, 0x34); /* size ... reports as 28 in mp4box! */
2970 ffio_wfourcc(pb, "uuid");
2971 ffio_wfourcc(pb, "USMT");
2972 avio_wb32(pb, 0x21d24fce);
2973 avio_wb32(pb, 0xbb88695c);
2974 avio_wb32(pb, 0xfac9c740);
2975 avio_wb32(pb, 0x1c); // another size here!
2976 ffio_wfourcc(pb, "MTDT");
2977 avio_wb32(pb, 0x00010012);
2978 avio_wb32(pb, 0x0a);
2979 avio_wb32(pb, 0x55c40000);
2985 static int mov_write_udta_sdp(AVIOContext *pb, MOVTrack *track)
2987 AVFormatContext *ctx = track->rtp_ctx;
2988 char buf[1000] = "";
2991 ff_sdp_write_media(buf, sizeof(buf), ctx->streams[0], track->src_track,
2992 NULL, NULL, 0, 0, ctx);
2993 av_strlcatf(buf, sizeof(buf), "a=control:streamid=%d\r\n", track->track_id);
2996 avio_wb32(pb, len + 24);
2997 ffio_wfourcc(pb, "udta");
2998 avio_wb32(pb, len + 16);
2999 ffio_wfourcc(pb, "hnti");
3000 avio_wb32(pb, len + 8);
3001 ffio_wfourcc(pb, "sdp ");
3002 avio_write(pb, buf, len);
3006 static int mov_write_track_metadata(AVIOContext *pb, AVStream *st,
3007 const char *tag, const char *str)
3009 int64_t pos = avio_tell(pb);
3010 AVDictionaryEntry *t = av_dict_get(st->metadata, str, NULL, 0);
3011 if (!t || !utf8len(t->value))
3014 avio_wb32(pb, 0); /* size */
3015 ffio_wfourcc(pb, tag); /* type */
3016 avio_write(pb, t->value, strlen(t->value)); /* UTF8 string value */
3017 return update_size(pb, pos);
3020 static int mov_write_track_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
3023 AVIOContext *pb_buf;
3030 ret = avio_open_dyn_buf(&pb_buf);
3034 if (mov->mode & (MODE_MP4|MODE_MOV))
3035 mov_write_track_metadata(pb_buf, st, "name", "title");
3037 if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) {
3038 avio_wb32(pb, size + 8);
3039 ffio_wfourcc(pb, "udta");
3040 avio_write(pb, buf, size);
3047 static int mov_write_trak_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov,
3048 MOVTrack *track, AVStream *st)
3050 int64_t pos = avio_tell(pb);
3051 int entry_backup = track->entry;
3052 int chunk_backup = track->chunkCount;
3055 /* If we want to have an empty moov, but some samples already have been
3056 * buffered (delay_moov), pretend that no samples have been written yet. */
3057 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV)
3058 track->chunkCount = track->entry = 0;
3060 avio_wb32(pb, 0); /* size */
3061 ffio_wfourcc(pb, "trak");
3062 mov_write_tkhd_tag(pb, mov, track, st);
3064 av_assert2(mov->use_editlist >= 0);
3066 if (track->start_dts != AV_NOPTS_VALUE) {
3067 if (mov->use_editlist)
3068 mov_write_edts_tag(pb, mov, track); // PSP Movies and several other cases require edts box
3069 else if ((track->entry && track->cluster[0].dts) || track->mode == MODE_PSP || is_clcp_track(track))
3070 av_log(mov->fc, AV_LOG_WARNING,
3071 "Not writing any edit list even though one would have been required\n");
3074 if (track->tref_tag)
3075 mov_write_tref_tag(pb, track);
3077 if ((ret = mov_write_mdia_tag(s, pb, mov, track)) < 0)
3079 if (track->mode == MODE_PSP)
3080 mov_write_uuid_tag_psp(pb, track); // PSP Movies require this uuid box
3081 if (track->tag == MKTAG('r','t','p',' '))
3082 mov_write_udta_sdp(pb, track);
3083 if (track->mode == MODE_MOV) {
3084 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
3085 double sample_aspect_ratio = av_q2d(st->sample_aspect_ratio);
3086 if (st->sample_aspect_ratio.num && 1.0 != sample_aspect_ratio) {
3087 mov_write_tapt_tag(pb, track);
3090 if (is_clcp_track(track) && st->sample_aspect_ratio.num) {
3091 mov_write_tapt_tag(pb, track);
3094 mov_write_track_udta_tag(pb, mov, st);
3095 track->entry = entry_backup;
3096 track->chunkCount = chunk_backup;
3097 return update_size(pb, pos);
3100 static int mov_write_iods_tag(AVIOContext *pb, MOVMuxContext *mov)
3102 int i, has_audio = 0, has_video = 0;
3103 int64_t pos = avio_tell(pb);
3104 int audio_profile = mov->iods_audio_profile;
3105 int video_profile = mov->iods_video_profile;
3106 for (i = 0; i < mov->nb_streams; i++) {
3107 if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
3108 has_audio |= mov->tracks[i].par->codec_type == AVMEDIA_TYPE_AUDIO;
3109 has_video |= mov->tracks[i].par->codec_type == AVMEDIA_TYPE_VIDEO;
3112 if (audio_profile < 0)
3113 audio_profile = 0xFF - has_audio;
3114 if (video_profile < 0)
3115 video_profile = 0xFF - has_video;
3116 avio_wb32(pb, 0x0); /* size */
3117 ffio_wfourcc(pb, "iods");
3118 avio_wb32(pb, 0); /* version & flags */
3119 put_descr(pb, 0x10, 7);
3120 avio_wb16(pb, 0x004f);
3123 avio_w8(pb, audio_profile);
3124 avio_w8(pb, video_profile);
3126 return update_size(pb, pos);
3129 static int mov_write_trex_tag(AVIOContext *pb, MOVTrack *track)
3131 avio_wb32(pb, 0x20); /* size */
3132 ffio_wfourcc(pb, "trex");
3133 avio_wb32(pb, 0); /* version & flags */
3134 avio_wb32(pb, track->track_id); /* track ID */
3135 avio_wb32(pb, 1); /* default sample description index */
3136 avio_wb32(pb, 0); /* default sample duration */
3137 avio_wb32(pb, 0); /* default sample size */
3138 avio_wb32(pb, 0); /* default sample flags */
3142 static int mov_write_mvex_tag(AVIOContext *pb, MOVMuxContext *mov)
3144 int64_t pos = avio_tell(pb);
3146 avio_wb32(pb, 0x0); /* size */
3147 ffio_wfourcc(pb, "mvex");
3148 for (i = 0; i < mov->nb_streams; i++)
3149 mov_write_trex_tag(pb, &mov->tracks[i]);
3150 return update_size(pb, pos);
3153 static int mov_write_mvhd_tag(AVIOContext *pb, MOVMuxContext *mov)
3155 int max_track_id = 1, i;
3156 int64_t max_track_len = 0;
3159 for (i = 0; i < mov->nb_streams; i++) {
3160 if (mov->tracks[i].entry > 0 && mov->tracks[i].timescale) {
3161 int64_t max_track_len_temp = av_rescale_rnd(mov->tracks[i].track_duration,
3163 mov->tracks[i].timescale,
3165 if (max_track_len < max_track_len_temp)
3166 max_track_len = max_track_len_temp;
3167 if (max_track_id < mov->tracks[i].track_id)
3168 max_track_id = mov->tracks[i].track_id;
3171 /* If using delay_moov, make sure the output is the same as if no
3172 * samples had been written yet. */
3173 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
3178 version = max_track_len < UINT32_MAX ? 0 : 1;
3179 avio_wb32(pb, version == 1 ? 120 : 108); /* size */
3181 ffio_wfourcc(pb, "mvhd");
3182 avio_w8(pb, version);
3183 avio_wb24(pb, 0); /* flags */
3185 avio_wb64(pb, mov->time);
3186 avio_wb64(pb, mov->time);
3188 avio_wb32(pb, mov->time); /* creation time */
3189 avio_wb32(pb, mov->time); /* modification time */
3191 avio_wb32(pb, MOV_TIMESCALE);
3192 (version == 1) ? avio_wb64(pb, max_track_len) : avio_wb32(pb, max_track_len); /* duration of longest track */
3194 avio_wb32(pb, 0x00010000); /* reserved (preferred rate) 1.0 = normal */
3195 avio_wb16(pb, 0x0100); /* reserved (preferred volume) 1.0 = normal */
3196 avio_wb16(pb, 0); /* reserved */
3197 avio_wb32(pb, 0); /* reserved */
3198 avio_wb32(pb, 0); /* reserved */
3200 /* Matrix structure */
3201 write_matrix(pb, 1, 0, 0, 1, 0, 0);
3203 avio_wb32(pb, 0); /* reserved (preview time) */
3204 avio_wb32(pb, 0); /* reserved (preview duration) */
3205 avio_wb32(pb, 0); /* reserved (poster time) */
3206 avio_wb32(pb, 0); /* reserved (selection time) */
3207 avio_wb32(pb, 0); /* reserved (selection duration) */
3208 avio_wb32(pb, 0); /* reserved (current time) */
3209 avio_wb32(pb, max_track_id + 1); /* Next track id */
3213 static int mov_write_itunes_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov,
3216 avio_wb32(pb, 33); /* size */
3217 ffio_wfourcc(pb, "hdlr");
3220 ffio_wfourcc(pb, "mdir");
3221 ffio_wfourcc(pb, "appl");
3228 /* helper function to write a data tag with the specified string as data */
3229 static int mov_write_string_data_tag(AVIOContext *pb, const char *data, int lang, int long_style)
3232 int size = 16 + strlen(data);
3233 avio_wb32(pb, size); /* size */
3234 ffio_wfourcc(pb, "data");
3237 avio_write(pb, data, strlen(data));
3241 lang = ff_mov_iso639_to_lang("und", 1);
3242 avio_wb16(pb, strlen(data)); /* string length */
3243 avio_wb16(pb, lang);
3244 avio_write(pb, data, strlen(data));
3245 return strlen(data) + 4;
3249 static int mov_write_string_tag(AVIOContext *pb, const char *name,
3250 const char *value, int lang, int long_style)
3253 if (value && value[0]) {
3254 int64_t pos = avio_tell(pb);
3255 avio_wb32(pb, 0); /* size */
3256 ffio_wfourcc(pb, name);
3257 mov_write_string_data_tag(pb, value, lang, long_style);
3258 size = update_size(pb, pos);
3263 static AVDictionaryEntry *get_metadata_lang(AVFormatContext *s,
3264 const char *tag, int *lang)
3267 AVDictionaryEntry *t, *t2 = NULL;
3272 if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
3275 len = strlen(t->key);
3276 snprintf(tag2, sizeof(tag2), "%s-", tag);
3277 while ((t2 = av_dict_get(s->metadata, tag2, t2, AV_DICT_IGNORE_SUFFIX))) {
3278 len2 = strlen(t2->key);
3279 if (len2 == len + 4 && !strcmp(t->value, t2->value)
3280 && (l = ff_mov_iso639_to_lang(&t2->key[len2 - 3], 1)) >= 0) {
3288 static int mov_write_string_metadata(AVFormatContext *s, AVIOContext *pb,
3289 const char *name, const char *tag,
3293 AVDictionaryEntry *t = get_metadata_lang(s, tag, &lang);
3296 return mov_write_string_tag(pb, name, t->value, lang, long_style);
3299 /* iTunes bpm number */
3300 static int mov_write_tmpo_tag(AVIOContext *pb, AVFormatContext *s)
3302 AVDictionaryEntry *t = av_dict_get(s->metadata, "tmpo", NULL, 0);
3303 int size = 0, tmpo = t ? atoi(t->value) : 0;
3306 avio_wb32(pb, size);
3307 ffio_wfourcc(pb, "tmpo");
3308 avio_wb32(pb, size-8); /* size */
3309 ffio_wfourcc(pb, "data");
3310 avio_wb32(pb, 0x15); //type specifier
3312 avio_wb16(pb, tmpo); // data
3317 /* 3GPP TS 26.244 */
3318 static int mov_write_loci_tag(AVFormatContext *s, AVIOContext *pb)
3321 int64_t pos = avio_tell(pb);
3322 double latitude, longitude, altitude;
3323 int32_t latitude_fix, longitude_fix, altitude_fix;
3324 AVDictionaryEntry *t = get_metadata_lang(s, "location", &lang);
3325 const char *ptr, *place = "";
3327 static const char *astronomical_body = "earth";
3332 longitude = strtod(ptr, &end);
3334 av_log(s, AV_LOG_WARNING, "malformed location metadata\n");
3338 latitude = strtod(ptr, &end);
3340 av_log(s, AV_LOG_WARNING, "malformed location metadata\n");
3344 altitude = strtod(ptr, &end);
3345 /* If no altitude was present, the default 0 should be fine */
3349 latitude_fix = (int32_t) ((1 << 16) * latitude);
3350 longitude_fix = (int32_t) ((1 << 16) * longitude);
3351 altitude_fix = (int32_t) ((1 << 16) * altitude);
3353 avio_wb32(pb, 0); /* size */
3354 ffio_wfourcc(pb, "loci"); /* type */
3355 avio_wb32(pb, 0); /* version + flags */
3356 avio_wb16(pb, lang);
3357 avio_write(pb, place, strlen(place) + 1);
3358 avio_w8(pb, 0); /* role of place (0 == shooting location, 1 == real location, 2 == fictional location) */
3359 avio_wb32(pb, latitude_fix);
3360 avio_wb32(pb, longitude_fix);
3361 avio_wb32(pb, altitude_fix);
3362 avio_write(pb, astronomical_body, strlen(astronomical_body) + 1);
3363 avio_w8(pb, 0); /* additional notes, null terminated string */
3365 return update_size(pb, pos);
3368 /* iTunes track or disc number */
3369 static int mov_write_trkn_tag(AVIOContext *pb, MOVMuxContext *mov,
3370 AVFormatContext *s, int disc)
3372 AVDictionaryEntry *t = av_dict_get(s->metadata,
3373 disc ? "disc" : "track",
3375 int size = 0, track = t ? atoi(t->value) : 0;
3378 char *slash = strchr(t->value, '/');
3380 tracks = atoi(slash + 1);
3381 avio_wb32(pb, 32); /* size */
3382 ffio_wfourcc(pb, disc ? "disk" : "trkn");
3383 avio_wb32(pb, 24); /* size */
3384 ffio_wfourcc(pb, "data");
3385 avio_wb32(pb, 0); // 8 bytes empty
3387 avio_wb16(pb, 0); // empty
3388 avio_wb16(pb, track); // track / disc number
3389 avio_wb16(pb, tracks); // total track / disc number
3390 avio_wb16(pb, 0); // empty
3396 static int mov_write_int8_metadata(AVFormatContext *s, AVIOContext *pb,
3397 const char *name, const char *tag,
3400 AVDictionaryEntry *t = NULL;
3402 int size = 24 + len;
3404 if (len != 1 && len != 4)
3407 if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
3409 num = atoi(t->value);
3411 avio_wb32(pb, size);
3412 ffio_wfourcc(pb, name);
3413 avio_wb32(pb, size - 8);
3414 ffio_wfourcc(pb, "data");
3415 avio_wb32(pb, 0x15);
3417 if (len==4) avio_wb32(pb, num);
3418 else avio_w8 (pb, num);
3423 /* iTunes meta data list */
3424 static int mov_write_ilst_tag(AVIOContext *pb, MOVMuxContext *mov,
3427 int64_t pos = avio_tell(pb);
3428 avio_wb32(pb, 0); /* size */
3429 ffio_wfourcc(pb, "ilst");
3430 mov_write_string_metadata(s, pb, "\251nam", "title" , 1);
3431 mov_write_string_metadata(s, pb, "\251ART", "artist" , 1);
3432 mov_write_string_metadata(s, pb, "aART", "album_artist", 1);
3433 mov_write_string_metadata(s, pb, "\251wrt", "composer" , 1);
3434 mov_write_string_metadata(s, pb, "\251alb", "album" , 1);
3435 mov_write_string_metadata(s, pb, "\251day", "date" , 1);
3436 if (!mov_write_string_metadata(s, pb, "\251too", "encoding_tool", 1)) {
3437 if (!(s->flags & AVFMT_FLAG_BITEXACT))
3438 mov_write_string_tag(pb, "\251too", LIBAVFORMAT_IDENT, 0, 1);
3440 mov_write_string_metadata(s, pb, "\251cmt", "comment" , 1);
3441 mov_write_string_metadata(s, pb, "\251gen", "genre" , 1);
3442 mov_write_string_metadata(s, pb, "cprt", "copyright", 1);
3443 mov_write_string_metadata(s, pb, "\251grp", "grouping" , 1);
3444 mov_write_string_metadata(s, pb, "\251lyr", "lyrics" , 1);
3445 mov_write_string_metadata(s, pb, "desc", "description",1);
3446 mov_write_string_metadata(s, pb, "ldes", "synopsis" , 1);
3447 mov_write_string_metadata(s, pb, "tvsh", "show" , 1);
3448 mov_write_string_metadata(s, pb, "tven", "episode_id",1);
3449 mov_write_string_metadata(s, pb, "tvnn", "network" , 1);
3450 mov_write_string_metadata(s, pb, "keyw", "keywords" , 1);
3451 mov_write_int8_metadata (s, pb, "tves", "episode_sort",4);
3452 mov_write_int8_metadata (s, pb, "tvsn", "season_number",4);
3453 mov_write_int8_metadata (s, pb, "stik", "media_type",1);
3454 mov_write_int8_metadata (s, pb, "hdvd", "hd_video", 1);
3455 mov_write_int8_metadata (s, pb, "pgap", "gapless_playback",1);
3456 mov_write_int8_metadata (s, pb, "cpil", "compilation", 1);
3457 mov_write_trkn_tag(pb, mov, s, 0); // track number
3458 mov_write_trkn_tag(pb, mov, s, 1); // disc number
3459 mov_write_tmpo_tag(pb, s);
3460 return update_size(pb, pos);
3463 static int mov_write_mdta_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov,
3466 avio_wb32(pb, 33); /* size */
3467 ffio_wfourcc(pb, "hdlr");
3470 ffio_wfourcc(pb, "mdta");
3478 static int mov_write_mdta_keys_tag(AVIOContext *pb, MOVMuxContext *mov,
3481 AVDictionaryEntry *t = NULL;
3482 int64_t pos = avio_tell(pb);
3483 int64_t curpos, entry_pos;
3486 avio_wb32(pb, 0); /* size */
3487 ffio_wfourcc(pb, "keys");
3489 entry_pos = avio_tell(pb);
3490 avio_wb32(pb, 0); /* entry count */
3492 while (t = av_dict_get(s->metadata, "", t, AV_DICT_IGNORE_SUFFIX)) {
3493 avio_wb32(pb, strlen(t->key) + 8);
3494 ffio_wfourcc(pb, "mdta");
3495 avio_write(pb, t->key, strlen(t->key));
3498 curpos = avio_tell(pb);
3499 avio_seek(pb, entry_pos, SEEK_SET);
3500 avio_wb32(pb, count); // rewrite entry count
3501 avio_seek(pb, curpos, SEEK_SET);
3503 return update_size(pb, pos);
3506 static int mov_write_mdta_ilst_tag(AVIOContext *pb, MOVMuxContext *mov,
3509 AVDictionaryEntry *t = NULL;
3510 int64_t pos = avio_tell(pb);
3511 int count = 1; /* keys are 1-index based */
3513 avio_wb32(pb, 0); /* size */
3514 ffio_wfourcc(pb, "ilst");
3516 while (t = av_dict_get(s->metadata, "", t, AV_DICT_IGNORE_SUFFIX)) {
3517 int64_t entry_pos = avio_tell(pb);
3518 avio_wb32(pb, 0); /* size */
3519 avio_wb32(pb, count); /* key */
3520 mov_write_string_data_tag(pb, t->value, 0, 1);
3521 update_size(pb, entry_pos);
3524 return update_size(pb, pos);
3527 /* meta data tags */
3528 static int mov_write_meta_tag(AVIOContext *pb, MOVMuxContext *mov,
3532 int64_t pos = avio_tell(pb);
3533 avio_wb32(pb, 0); /* size */
3534 ffio_wfourcc(pb, "meta");
3536 if (mov->flags & FF_MOV_FLAG_USE_MDTA) {
3537 mov_write_mdta_hdlr_tag(pb, mov, s);
3538 mov_write_mdta_keys_tag(pb, mov, s);
3539 mov_write_mdta_ilst_tag(pb, mov, s);
3542 /* iTunes metadata tag */
3543 mov_write_itunes_hdlr_tag(pb, mov, s);
3544 mov_write_ilst_tag(pb, mov, s);
3546 size = update_size(pb, pos);
3550 static int mov_write_raw_metadata_tag(AVFormatContext *s, AVIOContext *pb,
3551 const char *name, const char *key)
3554 AVDictionaryEntry *t;
3556 if (!(t = av_dict_get(s->metadata, key, NULL, 0)))
3559 len = strlen(t->value);
3562 avio_wb32(pb, size);
3563 ffio_wfourcc(pb, name);
3564 avio_write(pb, t->value, len);
3570 static int ascii_to_wc(AVIOContext *pb, const uint8_t *b)
3574 GET_UTF8(val, *b++, return -1;)
3577 avio_wb16(pb, 0x00);
3581 static uint16_t language_code(const char *str)
3583 return (((str[0] - 0x60) & 0x1F) << 10) +
3584 (((str[1] - 0x60) & 0x1F) << 5) +
3585 (( str[2] - 0x60) & 0x1F);
3588 static int mov_write_3gp_udta_tag(AVIOContext *pb, AVFormatContext *s,
3589 const char *tag, const char *str)
3591 int64_t pos = avio_tell(pb);
3592 AVDictionaryEntry *t = av_dict_get(s->metadata, str, NULL, 0);
3593 if (!t || !utf8len(t->value))
3595 avio_wb32(pb, 0); /* size */
3596 ffio_wfourcc(pb, tag); /* type */
3597 avio_wb32(pb, 0); /* version + flags */
3598 if (!strcmp(tag, "yrrc"))
3599 avio_wb16(pb, atoi(t->value));
3601 avio_wb16(pb, language_code("eng")); /* language */
3602 avio_write(pb, t->value, strlen(t->value) + 1); /* UTF8 string value */
3603 if (!strcmp(tag, "albm") &&
3604 (t = av_dict_get(s->metadata, "track", NULL, 0)))
3605 avio_w8(pb, atoi(t->value));
3607 return update_size(pb, pos);
3610 static int mov_write_chpl_tag(AVIOContext *pb, AVFormatContext *s)
3612 int64_t pos = avio_tell(pb);
3613 int i, nb_chapters = FFMIN(s->nb_chapters, 255);
3615 avio_wb32(pb, 0); // size
3616 ffio_wfourcc(pb, "chpl");
3617 avio_wb32(pb, 0x01000000); // version + flags
3618 avio_wb32(pb, 0); // unknown
3619 avio_w8(pb, nb_chapters);
3621 for (i = 0; i < nb_chapters; i++) {
3622 AVChapter *c = s->chapters[i];
3623 AVDictionaryEntry *t;
3624 avio_wb64(pb, av_rescale_q(c->start, c->time_base, (AVRational){1,10000000}));
3626 if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
3627 int len = FFMIN(strlen(t->value), 255);
3629 avio_write(pb, t->value, len);
3633 return update_size(pb, pos);
3636 static int mov_write_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
3639 AVIOContext *pb_buf;
3643 ret = avio_open_dyn_buf(&pb_buf);
3647 if (mov->mode & MODE_3GP) {
3648 mov_write_3gp_udta_tag(pb_buf, s, "perf", "artist");
3649 mov_write_3gp_udta_tag(pb_buf, s, "titl", "title");
3650 mov_write_3gp_udta_tag(pb_buf, s, "auth", "author");
3651 mov_write_3gp_udta_tag(pb_buf, s, "gnre", "genre");
3652 mov_write_3gp_udta_tag(pb_buf, s, "dscp", "comment");
3653 mov_write_3gp_udta_tag(pb_buf, s, "albm", "album");
3654 mov_write_3gp_udta_tag(pb_buf, s, "cprt", "copyright");
3655 mov_write_3gp_udta_tag(pb_buf, s, "yrrc", "date");
3656 mov_write_loci_tag(s, pb_buf);
3657 } 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
3658 mov_write_string_metadata(s, pb_buf, "\251ART", "artist", 0);
3659 mov_write_string_metadata(s, pb_buf, "\251nam", "title", 0);
3660 mov_write_string_metadata(s, pb_buf, "\251aut", "author", 0);
3661 mov_write_string_metadata(s, pb_buf, "\251alb", "album", 0);
3662 mov_write_string_metadata(s, pb_buf, "\251day", "date", 0);
3663 mov_write_string_metadata(s, pb_buf, "\251swr", "encoder", 0);
3664 // currently ignored by mov.c
3665 mov_write_string_metadata(s, pb_buf, "\251des", "comment", 0);
3666 // add support for libquicktime, this atom is also actually read by mov.c
3667 mov_write_string_metadata(s, pb_buf, "\251cmt", "comment", 0);
3668 mov_write_string_metadata(s, pb_buf, "\251gen", "genre", 0);
3669 mov_write_string_metadata(s, pb_buf, "\251cpy", "copyright", 0);
3670 mov_write_string_metadata(s, pb_buf, "\251mak", "make", 0);
3671 mov_write_string_metadata(s, pb_buf, "\251mod", "model", 0);
3672 mov_write_string_metadata(s, pb_buf, "\251xyz", "location", 0);
3673 mov_write_string_metadata(s, pb_buf, "\251key", "keywords", 0);
3674 mov_write_raw_metadata_tag(s, pb_buf, "XMP_", "xmp");
3676 /* iTunes meta data */
3677 mov_write_meta_tag(pb_buf, mov, s);
3678 mov_write_loci_tag(s, pb_buf);
3681 if (s->nb_chapters && !(mov->flags & FF_MOV_FLAG_DISABLE_CHPL))
3682 mov_write_chpl_tag(pb_buf, s);
3684 if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) {
3685 avio_wb32(pb, size + 8);
3686 ffio_wfourcc(pb, "udta");
3687 avio_write(pb, buf, size);
3694 static void mov_write_psp_udta_tag(AVIOContext *pb,
3695 const char *str, const char *lang, int type)
3697 int len = utf8len(str) + 1;
3700 avio_wb16(pb, len * 2 + 10); /* size */
3701 avio_wb32(pb, type); /* type */
3702 avio_wb16(pb, language_code(lang)); /* language */
3703 avio_wb16(pb, 0x01); /* ? */
3704 ascii_to_wc(pb, str);
3707 static int mov_write_uuidusmt_tag(AVIOContext *pb, AVFormatContext *s)
3709 AVDictionaryEntry *title = av_dict_get(s->metadata, "title", NULL, 0);
3713 pos = avio_tell(pb);
3714 avio_wb32(pb, 0); /* size placeholder*/
3715 ffio_wfourcc(pb, "uuid");
3716 ffio_wfourcc(pb, "USMT");
3717 avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
3718 avio_wb32(pb, 0xbb88695c);
3719 avio_wb32(pb, 0xfac9c740);
3721 pos2 = avio_tell(pb);
3722 avio_wb32(pb, 0); /* size placeholder*/
3723 ffio_wfourcc(pb, "MTDT");
3727 avio_wb16(pb, 0x0C); /* size */
3728 avio_wb32(pb, 0x0B); /* type */
3729 avio_wb16(pb, language_code("und")); /* language */
3730 avio_wb16(pb, 0x0); /* ? */
3731 avio_wb16(pb, 0x021C); /* data */
3733 if (!(s->flags & AVFMT_FLAG_BITEXACT))
3734 mov_write_psp_udta_tag(pb, LIBAVCODEC_IDENT, "eng", 0x04);
3735 mov_write_psp_udta_tag(pb, title->value, "eng", 0x01);
3736 mov_write_psp_udta_tag(pb, "2006/04/01 11:11:11", "und", 0x03);
3738 update_size(pb, pos2);
3739 return update_size(pb, pos);
3745 static void build_chunks(MOVTrack *trk)
3748 MOVIentry *chunk = &trk->cluster[0];
3749 uint64_t chunkSize = chunk->size;
3750 chunk->chunkNum = 1;
3751 if (trk->chunkCount)
3753 trk->chunkCount = 1;
3754 for (i = 1; i<trk->entry; i++){
3755 if (chunk->pos + chunkSize == trk->cluster[i].pos &&
3756 chunkSize + trk->cluster[i].size < (1<<20)){
3757 chunkSize += trk->cluster[i].size;
3758 chunk->samples_in_chunk += trk->cluster[i].entries;
3760 trk->cluster[i].chunkNum = chunk->chunkNum+1;
3761 chunk=&trk->cluster[i];
3762 chunkSize = chunk->size;
3769 * Assign track ids. If option "use_stream_ids_as_track_ids" is set,
3770 * the stream ids are used as track ids.
3772 * This assumes mov->tracks and s->streams are in the same order and
3773 * there are no gaps in either of them (so mov->tracks[n] refers to
3776 * As an exception, there can be more entries in
3777 * s->streams than in mov->tracks, in which case new track ids are
3778 * generated (starting after the largest found stream id).
3780 static int mov_setup_track_ids(MOVMuxContext *mov, AVFormatContext *s)
3784 if (mov->track_ids_ok)
3787 if (mov->use_stream_ids_as_track_ids) {
3788 int next_generated_track_id = 0;
3789 for (i = 0; i < s->nb_streams; i++) {
3790 if (s->streams[i]->id > next_generated_track_id)
3791 next_generated_track_id = s->streams[i]->id;
3794 for (i = 0; i < mov->nb_streams; i++) {
3795 if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
3798 mov->tracks[i].track_id = i >= s->nb_streams ? ++next_generated_track_id : s->streams[i]->id;
3801 for (i = 0; i < mov->nb_streams; i++) {
3802 if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
3805 mov->tracks[i].track_id = i + 1;
3809 mov->track_ids_ok = 1;
3814 static int mov_write_moov_tag(AVIOContext *pb, MOVMuxContext *mov,
3818 int64_t pos = avio_tell(pb);
3819 avio_wb32(pb, 0); /* size placeholder*/
3820 ffio_wfourcc(pb, "moov");
3822 mov_setup_track_ids(mov, s);
3824 for (i = 0; i < mov->nb_streams; i++) {
3825 if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
3828 mov->tracks[i].time = mov->time;
3830 if (mov->tracks[i].entry)
3831 build_chunks(&mov->tracks[i]);
3834 if (mov->chapter_track)
3835 for (i = 0; i < s->nb_streams; i++) {
3836 mov->tracks[i].tref_tag = MKTAG('c','h','a','p');
3837 mov->tracks[i].tref_id = mov->tracks[mov->chapter_track].track_id;
3839 for (i = 0; i < mov->nb_streams; i++) {
3840 MOVTrack *track = &mov->tracks[i];
3841 if (track->tag == MKTAG('r','t','p',' ')) {
3842 track->tref_tag = MKTAG('h','i','n','t');
3843 track->tref_id = mov->tracks[track->src_track].track_id;
3844 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
3845 int * fallback, size;
3846 fallback = (int*)av_stream_get_side_data(track->st,
3847 AV_PKT_DATA_FALLBACK_TRACK,
3849 if (fallback != NULL && size == sizeof(int)) {
3850 if (*fallback >= 0 && *fallback < mov->nb_streams) {
3851 track->tref_tag = MKTAG('f','a','l','l');
3852 track->tref_id = mov->tracks[*fallback].track_id;
3857 for (i = 0; i < mov->nb_streams; i++) {
3858 if (mov->tracks[i].tag == MKTAG('t','m','c','d')) {
3859 int src_trk = mov->tracks[i].src_track;
3860 mov->tracks[src_trk].tref_tag = mov->tracks[i].tag;
3861 mov->tracks[src_trk].tref_id = mov->tracks[i].track_id;
3862 //src_trk may have a different timescale than the tmcd track
3863 mov->tracks[i].track_duration = av_rescale(mov->tracks[src_trk].track_duration,
3864 mov->tracks[i].timescale,
3865 mov->tracks[src_trk].timescale);
3869 mov_write_mvhd_tag(pb, mov);
3870 if (mov->mode != MODE_MOV && !mov->iods_skip)
3871 mov_write_iods_tag(pb, mov);
3872 for (i = 0; i < mov->nb_streams; i++) {
3873 if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_FRAGMENT) {
3874 int ret = mov_write_trak_tag(s, pb, mov, &(mov->tracks[i]), i < s->nb_streams ? s->streams[i] : NULL);
3879 if (mov->flags & FF_MOV_FLAG_FRAGMENT)
3880 mov_write_mvex_tag(pb, mov); /* QuickTime requires trak to precede this */
3882 if (mov->mode == MODE_PSP)
3883 mov_write_uuidusmt_tag(pb, s);
3885 mov_write_udta_tag(pb, mov, s);
3887 return update_size(pb, pos);
3890 static void param_write_int(AVIOContext *pb, const char *name, int value)
3892 avio_printf(pb, "<param name=\"%s\" value=\"%d\" valuetype=\"data\"/>\n", name, value);
3895 static void param_write_string(AVIOContext *pb, const char *name, const char *value)
3897 avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, value);
3900 static void param_write_hex(AVIOContext *pb, const char *name, const uint8_t *value, int len)
3903 len = FFMIN(sizeof(buf) / 2 - 1, len);
3904 ff_data_to_hex(buf, value, len, 0);
3905 buf[2 * len] = '\0';
3906 avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, buf);
3909 static int mov_write_isml_manifest(AVIOContext *pb, MOVMuxContext *mov, AVFormatContext *s)
3911 int64_t pos = avio_tell(pb);
3913 int64_t manifest_bit_rate = 0;
3914 AVCPBProperties *props = NULL;
3916 static const uint8_t uuid[] = {
3917 0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd,
3918 0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66
3922 ffio_wfourcc(pb, "uuid");
3923 avio_write(pb, uuid, sizeof(uuid));
3926 avio_printf(pb, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
3927 avio_printf(pb, "<smil xmlns=\"http://www.w3.org/2001/SMIL20/Language\">\n");
3928 avio_printf(pb, "<head>\n");
3929 if (!(mov->fc->flags & AVFMT_FLAG_BITEXACT))
3930 avio_printf(pb, "<meta name=\"creator\" content=\"%s\" />\n",
3932 avio_printf(pb, "</head>\n");
3933 avio_printf(pb, "<body>\n");
3934 avio_printf(pb, "<switch>\n");
3936 mov_setup_track_ids(mov, s);
3938 for (i = 0; i < mov->nb_streams; i++) {
3939 MOVTrack *track = &mov->tracks[i];
3941 int track_id = track->track_id;
3942 char track_name_buf[32] = { 0 };
3944 AVStream *st = track->st;
3945 AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0);
3947 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
3949 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
3955 props = (AVCPBProperties*)av_stream_get_side_data(track->st, AV_PKT_DATA_CPB_PROPERTIES, NULL);
3957 if (track->par->bit_rate) {
3958 manifest_bit_rate = track->par->bit_rate;
3960 manifest_bit_rate = props->max_bitrate;
3963 avio_printf(pb, "<%s systemBitrate=\"%"PRId64"\">\n", type,
3965 param_write_int(pb, "systemBitrate", manifest_bit_rate);
3966 param_write_int(pb, "trackID", track_id);
3967 param_write_string(pb, "systemLanguage", lang ? lang->value : "und");
3969 /* Build track name piece by piece: */
3971 av_strlcat(track_name_buf, type, sizeof(track_name_buf));
3972 /* 2. track language, if available */
3974 av_strlcatf(track_name_buf, sizeof(track_name_buf),
3975 "_%s", lang->value);
3976 /* 3. special type suffix */
3977 /* "_cc" = closed captions, "_ad" = audio_description */
3978 if (st->disposition & AV_DISPOSITION_HEARING_IMPAIRED)
3979 av_strlcat(track_name_buf, "_cc", sizeof(track_name_buf));
3980 else if (st->disposition & AV_DISPOSITION_VISUAL_IMPAIRED)
3981 av_strlcat(track_name_buf, "_ad", sizeof(track_name_buf));
3983 param_write_string(pb, "trackName", track_name_buf);
3985 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
3986 if (track->par->codec_id == AV_CODEC_ID_H264) {
3988 int size = track->par->extradata_size;
3989 if (!ff_avc_write_annexb_extradata(track->par->extradata, &ptr,
3991 param_write_hex(pb, "CodecPrivateData",
3992 ptr ? ptr : track->par->extradata,
3996 param_write_string(pb, "FourCC", "H264");
3997 } else if (track->par->codec_id == AV_CODEC_ID_VC1) {
3998 param_write_string(pb, "FourCC", "WVC1");
3999 param_write_hex(pb, "CodecPrivateData", track->par->extradata,
4000 track->par->extradata_size);
4002 param_write_int(pb, "MaxWidth", track->par->width);
4003 param_write_int(pb, "MaxHeight", track->par->height);
4004 param_write_int(pb, "DisplayWidth", track->par->width);
4005 param_write_int(pb, "DisplayHeight", track->par->height);
4007 if (track->par->codec_id == AV_CODEC_ID_AAC) {
4008 switch (track->par->profile)
4010 case FF_PROFILE_AAC_HE_V2:
4011 param_write_string(pb, "FourCC", "AACP");
4013 case FF_PROFILE_AAC_HE:
4014 param_write_string(pb, "FourCC", "AACH");
4017 param_write_string(pb, "FourCC", "AACL");
4019 } else if (track->par->codec_id == AV_CODEC_ID_WMAPRO) {
4020 param_write_string(pb, "FourCC", "WMAP");
4022 param_write_hex(pb, "CodecPrivateData", track->par->extradata,
4023 track->par->extradata_size);
4024 param_write_int(pb, "AudioTag", ff_codec_get_tag(ff_codec_wav_tags,
4025 track->par->codec_id));
4026 param_write_int(pb, "Channels", track->par->channels);
4027 param_write_int(pb, "SamplingRate", track->par->sample_rate);
4028 param_write_int(pb, "BitsPerSample", 16);
4029 param_write_int(pb, "PacketSize", track->par->block_align ?
4030 track->par->block_align : 4);
4032 avio_printf(pb, "</%s>\n", type);
4034 avio_printf(pb, "</switch>\n");
4035 avio_printf(pb, "</body>\n");
4036 avio_printf(pb, "</smil>\n");
4038 return update_size(pb, pos);
4041 static int mov_write_mfhd_tag(AVIOContext *pb, MOVMuxContext *mov)
4044 ffio_wfourcc(pb, "mfhd");
4046 avio_wb32(pb, mov->fragments);
4050 static uint32_t get_sample_flags(MOVTrack *track, MOVIentry *entry)
4052 return entry->flags & MOV_SYNC_SAMPLE ? MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO :
4053 (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC);
4056 static int mov_write_tfhd_tag(AVIOContext *pb, MOVMuxContext *mov,
4057 MOVTrack *track, int64_t moof_offset)
4059 int64_t pos = avio_tell(pb);
4060 uint32_t flags = MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
4061 MOV_TFHD_BASE_DATA_OFFSET;
4062 if (!track->entry) {
4063 flags |= MOV_TFHD_DURATION_IS_EMPTY;
4065 flags |= MOV_TFHD_DEFAULT_FLAGS;
4067 if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET)
4068 flags &= ~MOV_TFHD_BASE_DATA_OFFSET;
4069 if (mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) {
4070 flags &= ~MOV_TFHD_BASE_DATA_OFFSET;
4071 flags |= MOV_TFHD_DEFAULT_BASE_IS_MOOF;
4074 /* Don't set a default sample size, the silverlight player refuses
4075 * to play files with that set. Don't set a default sample duration,
4076 * WMP freaks out if it is set. Don't set a base data offset, PIFF
4077 * file format says it MUST NOT be set. */
4078 if (track->mode == MODE_ISM)
4079 flags &= ~(MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
4080 MOV_TFHD_BASE_DATA_OFFSET);
4082 avio_wb32(pb, 0); /* size placeholder */
4083 ffio_wfourcc(pb, "tfhd");
4084 avio_w8(pb, 0); /* version */
4085 avio_wb24(pb, flags);
4087 avio_wb32(pb, track->track_id); /* track-id */
4088 if (flags & MOV_TFHD_BASE_DATA_OFFSET)
4089 avio_wb64(pb, moof_offset);
4090 if (flags & MOV_TFHD_DEFAULT_DURATION) {
4091 track->default_duration = get_cluster_duration(track, 0);
4092 avio_wb32(pb, track->default_duration);
4094 if (flags & MOV_TFHD_DEFAULT_SIZE) {
4095 track->default_size = track->entry ? track->cluster[0].size : 1;
4096 avio_wb32(pb, track->default_size);
4098 track->default_size = -1;
4100 if (flags & MOV_TFHD_DEFAULT_FLAGS) {
4101 /* Set the default flags based on the second sample, if available.
4102 * If the first sample is different, that can be signaled via a separate field. */
4103 if (track->entry > 1)
4104 track->default_sample_flags = get_sample_flags(track, &track->cluster[1]);
4106 track->default_sample_flags =
4107 track->par->codec_type == AVMEDIA_TYPE_VIDEO ?
4108 (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC) :
4109 MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO;
4110 avio_wb32(pb, track->default_sample_flags);
4113 return update_size(pb, pos);
4116 static int mov_write_trun_tag(AVIOContext *pb, MOVMuxContext *mov,
4117 MOVTrack *track, int moof_size,
4120 int64_t pos = avio_tell(pb);
4121 uint32_t flags = MOV_TRUN_DATA_OFFSET;
4124 for (i = first; i < end; i++) {
4125 if (get_cluster_duration(track, i) != track->default_duration)
4126 flags |= MOV_TRUN_SAMPLE_DURATION;
4127 if (track->cluster[i].size != track->default_size)
4128 flags |= MOV_TRUN_SAMPLE_SIZE;
4129 if (i > first && get_sample_flags(track, &track->cluster[i]) != track->default_sample_flags)
4130 flags |= MOV_TRUN_SAMPLE_FLAGS;
4132 if (!(flags & MOV_TRUN_SAMPLE_FLAGS) && track->entry > 0 &&
4133 get_sample_flags(track, &track->cluster[0]) != track->default_sample_flags)
4134 flags |= MOV_TRUN_FIRST_SAMPLE_FLAGS;
4135 if (track->flags & MOV_TRACK_CTTS)
4136 flags |= MOV_TRUN_SAMPLE_CTS;
4138 avio_wb32(pb, 0); /* size placeholder */
4139 ffio_wfourcc(pb, "trun");
4140 if (mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS)
4141 avio_w8(pb, 1); /* version */
4143 avio_w8(pb, 0); /* version */
4144 avio_wb24(pb, flags);
4146 avio_wb32(pb, end - first); /* sample count */
4147 if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET &&
4148 !(mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) &&
4150 avio_wb32(pb, 0); /* Later tracks follow immediately after the previous one */
4152 avio_wb32(pb, moof_size + 8 + track->data_offset +
4153 track->cluster[first].pos); /* data offset */
4154 if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS)
4155 avio_wb32(pb, get_sample_flags(track, &track->cluster[first]));
4157 for (i = first; i < end; i++) {
4158 if (flags & MOV_TRUN_SAMPLE_DURATION)
4159 avio_wb32(pb, get_cluster_duration(track, i));
4160 if (flags & MOV_TRUN_SAMPLE_SIZE)
4161 avio_wb32(pb, track->cluster[i].size);
4162 if (flags & MOV_TRUN_SAMPLE_FLAGS)
4163 avio_wb32(pb, get_sample_flags(track, &track->cluster[i]));
4164 if (flags & MOV_TRUN_SAMPLE_CTS)
4165 avio_wb32(pb, track->cluster[i].cts);
4168 mov->first_trun = 0;
4169 return update_size(pb, pos);
4172 static int mov_write_tfxd_tag(AVIOContext *pb, MOVTrack *track)
4174 int64_t pos = avio_tell(pb);
4175 static const uint8_t uuid[] = {
4176 0x6d, 0x1d, 0x9b, 0x05, 0x42, 0xd5, 0x44, 0xe6,
4177 0x80, 0xe2, 0x14, 0x1d, 0xaf, 0xf7, 0x57, 0xb2
4180 avio_wb32(pb, 0); /* size placeholder */
4181 ffio_wfourcc(pb, "uuid");
4182 avio_write(pb, uuid, sizeof(uuid));
4185 avio_wb64(pb, track->start_dts + track->frag_start +
4186 track->cluster[0].cts);
4187 avio_wb64(pb, track->end_pts -
4188 (track->cluster[0].dts + track->cluster[0].cts));
4190 return update_size(pb, pos);
4193 static int mov_write_tfrf_tag(AVIOContext *pb, MOVMuxContext *mov,
4194 MOVTrack *track, int entry)
4196 int n = track->nb_frag_info - 1 - entry, i;
4197 int size = 8 + 16 + 4 + 1 + 16*n;
4198 static const uint8_t uuid[] = {
4199 0xd4, 0x80, 0x7e, 0xf2, 0xca, 0x39, 0x46, 0x95,
4200 0x8e, 0x54, 0x26, 0xcb, 0x9e, 0x46, 0xa7, 0x9f
4206 avio_seek(pb, track->frag_info[entry].tfrf_offset, SEEK_SET);
4207 avio_wb32(pb, size);
4208 ffio_wfourcc(pb, "uuid");
4209 avio_write(pb, uuid, sizeof(uuid));
4213 for (i = 0; i < n; i++) {
4214 int index = entry + 1 + i;
4215 avio_wb64(pb, track->frag_info[index].time);
4216 avio_wb64(pb, track->frag_info[index].duration);
4218 if (n < mov->ism_lookahead) {
4219 int free_size = 16 * (mov->ism_lookahead - n);
4220 avio_wb32(pb, free_size);
4221 ffio_wfourcc(pb, "free");
4222 ffio_fill(pb, 0, free_size - 8);
4228 static int mov_write_tfrf_tags(AVIOContext *pb, MOVMuxContext *mov,
4231 int64_t pos = avio_tell(pb);
4233 for (i = 0; i < mov->ism_lookahead; i++) {
4234 /* Update the tfrf tag for the last ism_lookahead fragments,
4235 * nb_frag_info - 1 is the next fragment to be written. */
4236 mov_write_tfrf_tag(pb, mov, track, track->nb_frag_info - 2 - i);
4238 avio_seek(pb, pos, SEEK_SET);
4242 static int mov_add_tfra_entries(AVIOContext *pb, MOVMuxContext *mov, int tracks,
4246 for (i = 0; i < mov->nb_streams; i++) {
4247 MOVTrack *track = &mov->tracks[i];
4248 MOVFragmentInfo *info;
4249 if ((tracks >= 0 && i != tracks) || !track->entry)
4251 track->nb_frag_info++;
4252 if (track->nb_frag_info >= track->frag_info_capacity) {
4253 unsigned new_capacity = track->nb_frag_info + MOV_FRAG_INFO_ALLOC_INCREMENT;
4254 if (av_reallocp_array(&track->frag_info,
4256 sizeof(*track->frag_info)))
4257 return AVERROR(ENOMEM);
4258 track->frag_info_capacity = new_capacity;
4260 info = &track->frag_info[track->nb_frag_info - 1];
4261 info->offset = avio_tell(pb);
4263 // Try to recreate the original pts for the first packet
4264 // from the fields we have stored
4265 info->time = track->start_dts + track->frag_start +
4266 track->cluster[0].cts;
4267 info->duration = track->end_pts -
4268 (track->cluster[0].dts + track->cluster[0].cts);
4269 // If the pts is less than zero, we will have trimmed
4270 // away parts of the media track using an edit list,
4271 // and the corresponding start presentation time is zero.
4272 if (info->time < 0) {
4273 info->duration += info->time;
4276 info->tfrf_offset = 0;
4277 mov_write_tfrf_tags(pb, mov, track);
4282 static void mov_prune_frag_info(MOVMuxContext *mov, int tracks, int max)
4285 for (i = 0; i < mov->nb_streams; i++) {
4286 MOVTrack *track = &mov->tracks[i];
4287 if ((tracks >= 0 && i != tracks) || !track->entry)
4289 if (track->nb_frag_info > max) {
4290 memmove(track->frag_info, track->frag_info + (track->nb_frag_info - max), max * sizeof(*track->frag_info));
4291 track->nb_frag_info = max;
4296 static int mov_write_tfdt_tag(AVIOContext *pb, MOVTrack *track)
4298 int64_t pos = avio_tell(pb);
4300 avio_wb32(pb, 0); /* size */
4301 ffio_wfourcc(pb, "tfdt");
4302 avio_w8(pb, 1); /* version */
4304 avio_wb64(pb, track->frag_start);
4305 return update_size(pb, pos);
4308 static int mov_write_traf_tag(AVIOContext *pb, MOVMuxContext *mov,
4309 MOVTrack *track, int64_t moof_offset,
4312 int64_t pos = avio_tell(pb);
4314 avio_wb32(pb, 0); /* size placeholder */
4315 ffio_wfourcc(pb, "traf");
4317 mov_write_tfhd_tag(pb, mov, track, moof_offset);
4318 if (mov->mode != MODE_ISM)
4319 mov_write_tfdt_tag(pb, track);
4320 for (i = 1; i < track->entry; i++) {
4321 if (track->cluster[i].pos != track->cluster[i - 1].pos + track->cluster[i - 1].size) {
4322 mov_write_trun_tag(pb, mov, track, moof_size, start, i);
4326 mov_write_trun_tag(pb, mov, track, moof_size, start, track->entry);
4327 if (mov->mode == MODE_ISM) {
4328 mov_write_tfxd_tag(pb, track);
4330 if (mov->ism_lookahead) {
4331 int i, size = 16 + 4 + 1 + 16 * mov->ism_lookahead;
4333 if (track->nb_frag_info > 0) {
4334 MOVFragmentInfo *info = &track->frag_info[track->nb_frag_info - 1];
4335 if (!info->tfrf_offset)
4336 info->tfrf_offset = avio_tell(pb);
4338 avio_wb32(pb, 8 + size);
4339 ffio_wfourcc(pb, "free");
4340 for (i = 0; i < size; i++)
4345 return update_size(pb, pos);
4348 static int mov_write_moof_tag_internal(AVIOContext *pb, MOVMuxContext *mov,
4349 int tracks, int moof_size)
4351 int64_t pos = avio_tell(pb);
4354 avio_wb32(pb, 0); /* size placeholder */
4355 ffio_wfourcc(pb, "moof");
4356 mov->first_trun = 1;
4358 mov_write_mfhd_tag(pb, mov);
4359 for (i = 0; i < mov->nb_streams; i++) {
4360 MOVTrack *track = &mov->tracks[i];
4361 if (tracks >= 0 && i != tracks)
4365 mov_write_traf_tag(pb, mov, track, pos, moof_size);
4368 return update_size(pb, pos);
4371 static int mov_write_sidx_tag(AVIOContext *pb,
4372 MOVTrack *track, int ref_size, int total_sidx_size)
4374 int64_t pos = avio_tell(pb), offset_pos, end_pos;
4375 int64_t presentation_time, duration, offset;
4376 int starts_with_SAP, i, entries;
4380 presentation_time = track->start_dts + track->frag_start +
4381 track->cluster[0].cts;
4382 duration = track->end_pts -
4383 (track->cluster[0].dts + track->cluster[0].cts);
4384 starts_with_SAP = track->cluster[0].flags & MOV_SYNC_SAMPLE;
4386 // pts<0 should be cut away using edts
4387 if (presentation_time < 0) {
4388 duration += presentation_time;
4389 presentation_time = 0;
4392 entries = track->nb_frag_info;
4395 presentation_time = track->frag_info[0].time;
4398 avio_wb32(pb, 0); /* size */
4399 ffio_wfourcc(pb, "sidx");
4400 avio_w8(pb, 1); /* version */
4402 avio_wb32(pb, track->track_id); /* reference_ID */
4403 avio_wb32(pb, track->timescale); /* timescale */
4404 avio_wb64(pb, presentation_time); /* earliest_presentation_time */
4405 offset_pos = avio_tell(pb);
4406 avio_wb64(pb, 0); /* first_offset (offset to referenced moof) */
4407 avio_wb16(pb, 0); /* reserved */
4409 avio_wb16(pb, entries); /* reference_count */
4410 for (i = 0; i < entries; i++) {
4411 if (!track->entry) {
4412 if (i > 1 && track->frag_info[i].offset != track->frag_info[i - 1].offset + track->frag_info[i - 1].size) {
4413 av_log(NULL, AV_LOG_ERROR, "Non-consecutive fragments, writing incorrect sidx\n");
4415 duration = track->frag_info[i].duration;
4416 ref_size = track->frag_info[i].size;
4417 starts_with_SAP = 1;
4419 avio_wb32(pb, (0 << 31) | (ref_size & 0x7fffffff)); /* reference_type (0 = media) | referenced_size */
4420 avio_wb32(pb, duration); /* subsegment_duration */
4421 avio_wb32(pb, (starts_with_SAP << 31) | (0 << 28) | 0); /* starts_with_SAP | SAP_type | SAP_delta_time */
4424 end_pos = avio_tell(pb);
4425 offset = pos + total_sidx_size - end_pos;
4426 avio_seek(pb, offset_pos, SEEK_SET);
4427 avio_wb64(pb, offset);
4428 avio_seek(pb, end_pos, SEEK_SET);
4429 return update_size(pb, pos);
4432 static int mov_write_sidx_tags(AVIOContext *pb, MOVMuxContext *mov,
4433 int tracks, int ref_size)
4436 AVIOContext *avio_buf;
4438 for (round = 0; round < 2; round++) {
4439 // First run one round to calculate the total size of all
4441 // This would be much simpler if we'd only write one sidx
4442 // atom, for the first track in the moof.
4444 if ((ret = ffio_open_null_buf(&avio_buf)) < 0)
4449 for (i = 0; i < mov->nb_streams; i++) {
4450 MOVTrack *track = &mov->tracks[i];
4451 if (tracks >= 0 && i != tracks)
4453 // When writing a sidx for the full file, entry is 0, but
4454 // we want to include all tracks. ref_size is 0 in this case,
4455 // since we read it from frag_info instead.
4456 if (!track->entry && ref_size > 0)
4458 total_size -= mov_write_sidx_tag(avio_buf, track, ref_size,
4462 total_size = ffio_close_null_buf(avio_buf);
4467 static int mov_write_moof_tag(AVIOContext *pb, MOVMuxContext *mov, int tracks,
4470 AVIOContext *avio_buf;
4473 if ((ret = ffio_open_null_buf(&avio_buf)) < 0)
4475 mov_write_moof_tag_internal(avio_buf, mov, tracks, 0);
4476 moof_size = ffio_close_null_buf(avio_buf);
4478 if (mov->flags & FF_MOV_FLAG_DASH && !(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX))
4479 mov_write_sidx_tags(pb, mov, tracks, moof_size + 8 + mdat_size);
4481 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX ||
4482 !(mov->flags & FF_MOV_FLAG_SKIP_TRAILER) ||
4483 mov->ism_lookahead) {
4484 if ((ret = mov_add_tfra_entries(pb, mov, tracks, moof_size + 8 + mdat_size)) < 0)
4486 if (!(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) &&
4487 mov->flags & FF_MOV_FLAG_SKIP_TRAILER) {
4488 mov_prune_frag_info(mov, tracks, mov->ism_lookahead + 1);
4492 return mov_write_moof_tag_internal(pb, mov, tracks, moof_size);
4495 static int mov_write_tfra_tag(AVIOContext *pb, MOVTrack *track)
4497 int64_t pos = avio_tell(pb);
4500 avio_wb32(pb, 0); /* size placeholder */
4501 ffio_wfourcc(pb, "tfra");
4502 avio_w8(pb, 1); /* version */
4505 avio_wb32(pb, track->track_id);
4506 avio_wb32(pb, 0); /* length of traf/trun/sample num */
4507 avio_wb32(pb, track->nb_frag_info);
4508 for (i = 0; i < track->nb_frag_info; i++) {
4509 avio_wb64(pb, track->frag_info[i].time);
4510 avio_wb64(pb, track->frag_info[i].offset + track->data_offset);
4511 avio_w8(pb, 1); /* traf number */
4512 avio_w8(pb, 1); /* trun number */
4513 avio_w8(pb, 1); /* sample number */
4516 return update_size(pb, pos);
4519 static int mov_write_mfra_tag(AVIOContext *pb, MOVMuxContext *mov)
4521 int64_t pos = avio_tell(pb);
4524 avio_wb32(pb, 0); /* size placeholder */
4525 ffio_wfourcc(pb, "mfra");
4526 /* An empty mfra atom is enough to indicate to the publishing point that
4527 * the stream has ended. */
4528 if (mov->flags & FF_MOV_FLAG_ISML)
4529 return update_size(pb, pos);
4531 for (i = 0; i < mov->nb_streams; i++) {
4532 MOVTrack *track = &mov->tracks[i];
4533 if (track->nb_frag_info)
4534 mov_write_tfra_tag(pb, track);
4538 ffio_wfourcc(pb, "mfro");
4539 avio_wb32(pb, 0); /* version + flags */
4540 avio_wb32(pb, avio_tell(pb) + 4 - pos);
4542 return update_size(pb, pos);
4545 static int mov_write_mdat_tag(AVIOContext *pb, MOVMuxContext *mov)
4547 avio_wb32(pb, 8); // placeholder for extended size field (64 bit)
4548 ffio_wfourcc(pb, mov->mode == MODE_MOV ? "wide" : "free");
4550 mov->mdat_pos = avio_tell(pb);
4551 avio_wb32(pb, 0); /* size placeholder*/
4552 ffio_wfourcc(pb, "mdat");
4556 /* TODO: This needs to be more general */
4557 static int mov_write_ftyp_tag(AVIOContext *pb, AVFormatContext *s)
4559 MOVMuxContext *mov = s->priv_data;
4560 int64_t pos = avio_tell(pb);
4561 int has_h264 = 0, has_video = 0;
4565 for (i = 0; i < s->nb_streams; i++) {
4566 AVStream *st = s->streams[i];
4567 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
4569 if (st->codecpar->codec_id == AV_CODEC_ID_H264)
4573 avio_wb32(pb, 0); /* size */
4574 ffio_wfourcc(pb, "ftyp");
4576 if (mov->major_brand && strlen(mov->major_brand) >= 4)
4577 ffio_wfourcc(pb, mov->major_brand);
4578 else if (mov->mode == MODE_3GP) {
4579 ffio_wfourcc(pb, has_h264 ? "3gp6" : "3gp4");
4580 minor = has_h264 ? 0x100 : 0x200;
4581 } else if (mov->mode & MODE_3G2) {
4582 ffio_wfourcc(pb, has_h264 ? "3g2b" : "3g2a");
4583 minor = has_h264 ? 0x20000 : 0x10000;
4584 } else if (mov->mode == MODE_PSP)
4585 ffio_wfourcc(pb, "MSNV");
4586 else if (mov->mode == MODE_MP4 && mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)
4587 ffio_wfourcc(pb, "iso5"); // Required when using default-base-is-moof
4588 else if (mov->mode == MODE_MP4 && mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS)
4589 ffio_wfourcc(pb, "iso4");
4590 else if (mov->mode == MODE_MP4)
4591 ffio_wfourcc(pb, "isom");
4592 else if (mov->mode == MODE_IPOD)
4593 ffio_wfourcc(pb, has_video ? "M4V ":"M4A ");
4594 else if (mov->mode == MODE_ISM)
4595 ffio_wfourcc(pb, "isml");
4596 else if (mov->mode == MODE_F4V)
4597 ffio_wfourcc(pb, "f4v ");
4599 ffio_wfourcc(pb, "qt ");
4601 avio_wb32(pb, minor);
4603 if (mov->mode == MODE_MOV)
4604 ffio_wfourcc(pb, "qt ");
4605 else if (mov->mode == MODE_ISM) {
4606 ffio_wfourcc(pb, "piff");
4607 } else if (!(mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)) {
4608 ffio_wfourcc(pb, "isom");
4609 ffio_wfourcc(pb, "iso2");
4611 ffio_wfourcc(pb, "avc1");
4614 // We add tfdt atoms when fragmenting, signal this with the iso6 compatible
4615 // brand. This is compatible with users that don't understand tfdt.
4616 if (mov->flags & FF_MOV_FLAG_FRAGMENT && mov->mode != MODE_ISM)
4617 ffio_wfourcc(pb, "iso6");
4619 if (mov->mode == MODE_3GP)
4620 ffio_wfourcc(pb, has_h264 ? "3gp6":"3gp4");
4621 else if (mov->mode & MODE_3G2)
4622 ffio_wfourcc(pb, has_h264 ? "3g2b":"3g2a");
4623 else if (mov->mode == MODE_PSP)
4624 ffio_wfourcc(pb, "MSNV");
4625 else if (mov->mode == MODE_MP4)
4626 ffio_wfourcc(pb, "mp41");
4628 if (mov->flags & FF_MOV_FLAG_DASH && mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
4629 ffio_wfourcc(pb, "dash");
4631 return update_size(pb, pos);
4634 static int mov_write_uuidprof_tag(AVIOContext *pb, AVFormatContext *s)
4636 AVStream *video_st = s->streams[0];
4637 AVCodecParameters *video_par = s->streams[0]->codecpar;
4638 AVCodecParameters *audio_par = s->streams[1]->codecpar;
4639 int audio_rate = audio_par->sample_rate;
4640 int64_t frame_rate = video_st->avg_frame_rate.den ?
4641 (video_st->avg_frame_rate.num * 0x10000LL) / video_st->avg_frame_rate.den :
4643 int audio_kbitrate = audio_par->bit_rate / 1000;
4644 int video_kbitrate = FFMIN(video_par->bit_rate / 1000, 800 - audio_kbitrate);
4646 if (frame_rate < 0 || frame_rate > INT32_MAX) {
4647 av_log(s, AV_LOG_ERROR, "Frame rate %f outside supported range\n", frame_rate / (double)0x10000);
4648 return AVERROR(EINVAL);
4651 avio_wb32(pb, 0x94); /* size */
4652 ffio_wfourcc(pb, "uuid");
4653 ffio_wfourcc(pb, "PROF");
4655 avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
4656 avio_wb32(pb, 0xbb88695c);
4657 avio_wb32(pb, 0xfac9c740);
4659 avio_wb32(pb, 0x0); /* ? */
4660 avio_wb32(pb, 0x3); /* 3 sections ? */
4662 avio_wb32(pb, 0x14); /* size */
4663 ffio_wfourcc(pb, "FPRF");
4664 avio_wb32(pb, 0x0); /* ? */
4665 avio_wb32(pb, 0x0); /* ? */
4666 avio_wb32(pb, 0x0); /* ? */
4668 avio_wb32(pb, 0x2c); /* size */
4669 ffio_wfourcc(pb, "APRF"); /* audio */
4671 avio_wb32(pb, 0x2); /* TrackID */
4672 ffio_wfourcc(pb, "mp4a");
4673 avio_wb32(pb, 0x20f);
4675 avio_wb32(pb, audio_kbitrate);
4676 avio_wb32(pb, audio_kbitrate);
4677 avio_wb32(pb, audio_rate);
4678 avio_wb32(pb, audio_par->channels);
4680 avio_wb32(pb, 0x34); /* size */
4681 ffio_wfourcc(pb, "VPRF"); /* video */
4683 avio_wb32(pb, 0x1); /* TrackID */
4684 if (video_par->codec_id == AV_CODEC_ID_H264) {
4685 ffio_wfourcc(pb, "avc1");
4686 avio_wb16(pb, 0x014D);
4687 avio_wb16(pb, 0x0015);
4689 ffio_wfourcc(pb, "mp4v");
4690 avio_wb16(pb, 0x0000);
4691 avio_wb16(pb, 0x0103);
4694 avio_wb32(pb, video_kbitrate);
4695 avio_wb32(pb, video_kbitrate);
4696 avio_wb32(pb, frame_rate);
4697 avio_wb32(pb, frame_rate);
4698 avio_wb16(pb, video_par->width);
4699 avio_wb16(pb, video_par->height);
4700 avio_wb32(pb, 0x010001); /* ? */
4705 static int mov_write_identification(AVIOContext *pb, AVFormatContext *s)
4707 MOVMuxContext *mov = s->priv_data;
4710 mov_write_ftyp_tag(pb,s);
4711 if (mov->mode == MODE_PSP) {
4712 int video_streams_nb = 0, audio_streams_nb = 0, other_streams_nb = 0;
4713 for (i = 0; i < s->nb_streams; i++) {
4714 AVStream *st = s->streams[i];
4715 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
4717 else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
4723 if (video_streams_nb != 1 || audio_streams_nb != 1 || other_streams_nb) {
4724 av_log(s, AV_LOG_ERROR, "PSP mode need one video and one audio stream\n");
4725 return AVERROR(EINVAL);
4727 return mov_write_uuidprof_tag(pb, s);
4732 static int mov_parse_mpeg2_frame(AVPacket *pkt, uint32_t *flags)
4735 int i, closed_gop = 0;
4737 for (i = 0; i < pkt->size - 4; i++) {
4738 c = (c << 8) + pkt->data[i];
4739 if (c == 0x1b8) { // gop
4740 closed_gop = pkt->data[i + 4] >> 6 & 0x01;
4741 } else if (c == 0x100) { // pic
4742 int temp_ref = (pkt->data[i + 1] << 2) | (pkt->data[i + 2] >> 6);
4743 if (!temp_ref || closed_gop) // I picture is not reordered
4744 *flags = MOV_SYNC_SAMPLE;
4746 *flags = MOV_PARTIAL_SYNC_SAMPLE;
4753 static void mov_parse_vc1_frame(AVPacket *pkt, MOVTrack *trk)
4755 const uint8_t *start, *next, *end = pkt->data + pkt->size;
4756 int seq = 0, entry = 0;
4757 int key = pkt->flags & AV_PKT_FLAG_KEY;
4758 start = find_next_marker(pkt->data, end);
4759 for (next = start; next < end; start = next) {
4760 next = find_next_marker(start + 4, end);
4761 switch (AV_RB32(start)) {
4762 case VC1_CODE_SEQHDR:
4765 case VC1_CODE_ENTRYPOINT:
4768 case VC1_CODE_SLICE:
4769 trk->vc1_info.slices = 1;
4773 if (!trk->entry && trk->vc1_info.first_packet_seen)
4774 trk->vc1_info.first_frag_written = 1;
4775 if (!trk->entry && !trk->vc1_info.first_frag_written) {
4776 /* First packet in first fragment */
4777 trk->vc1_info.first_packet_seq = seq;
4778 trk->vc1_info.first_packet_entry = entry;
4779 trk->vc1_info.first_packet_seen = 1;
4780 } else if ((seq && !trk->vc1_info.packet_seq) ||
4781 (entry && !trk->vc1_info.packet_entry)) {
4783 for (i = 0; i < trk->entry; i++)
4784 trk->cluster[i].flags &= ~MOV_SYNC_SAMPLE;
4785 trk->has_keyframes = 0;
4787 trk->vc1_info.packet_seq = 1;
4789 trk->vc1_info.packet_entry = 1;
4790 if (!trk->vc1_info.first_frag_written) {
4791 /* First fragment */
4792 if ((!seq || trk->vc1_info.first_packet_seq) &&
4793 (!entry || trk->vc1_info.first_packet_entry)) {
4794 /* First packet had the same headers as this one, readd the
4795 * sync sample flag. */
4796 trk->cluster[0].flags |= MOV_SYNC_SAMPLE;
4797 trk->has_keyframes = 1;
4801 if (trk->vc1_info.packet_seq && trk->vc1_info.packet_entry)
4803 else if (trk->vc1_info.packet_seq)
4805 else if (trk->vc1_info.packet_entry)
4808 trk->cluster[trk->entry].flags |= MOV_SYNC_SAMPLE;
4809 trk->has_keyframes++;
4813 static int mov_flush_fragment_interleaving(AVFormatContext *s, MOVTrack *track)
4815 MOVMuxContext *mov = s->priv_data;
4820 if (!track->mdat_buf)
4822 if (!mov->mdat_buf) {
4823 if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0)
4826 buf_size = avio_close_dyn_buf(track->mdat_buf, &buf);
4827 track->mdat_buf = NULL;
4829 offset = avio_tell(mov->mdat_buf);
4830 avio_write(mov->mdat_buf, buf, buf_size);
4833 for (i = track->entries_flushed; i < track->entry; i++)
4834 track->cluster[i].pos += offset;
4835 track->entries_flushed = track->entry;
4839 static int mov_flush_fragment(AVFormatContext *s, int force)
4841 MOVMuxContext *mov = s->priv_data;
4842 int i, first_track = -1;
4843 int64_t mdat_size = 0;
4845 int has_video = 0, starts_with_key = 0, first_video_track = 1;
4847 if (!(mov->flags & FF_MOV_FLAG_FRAGMENT))
4850 // Try to fill in the duration of the last packet in each stream
4851 // from queued packets in the interleave queues. If the flushing
4852 // of fragments was triggered automatically by an AVPacket, we
4853 // already have reliable info for the end of that track, but other
4854 // tracks may need to be filled in.
4855 for (i = 0; i < s->nb_streams; i++) {
4856 MOVTrack *track = &mov->tracks[i];
4857 if (!track->end_reliable) {
4859 if (!ff_interleaved_peek(s, i, &pkt, 1)) {
4860 if (track->dts_shift != AV_NOPTS_VALUE)
4861 pkt.dts += track->dts_shift;
4862 track->track_duration = pkt.dts - track->start_dts;
4863 if (pkt.pts != AV_NOPTS_VALUE)
4864 track->end_pts = pkt.pts;
4866 track->end_pts = pkt.dts;
4871 for (i = 0; i < mov->nb_streams; i++) {
4872 MOVTrack *track = &mov->tracks[i];
4873 if (track->entry <= 1)
4875 // Sample durations are calculated as the diff of dts values,
4876 // but for the last sample in a fragment, we don't know the dts
4877 // of the first sample in the next fragment, so we have to rely
4878 // on what was set as duration in the AVPacket. Not all callers
4879 // set this though, so we might want to replace it with an
4880 // estimate if it currently is zero.
4881 if (get_cluster_duration(track, track->entry - 1) != 0)
4883 // Use the duration (i.e. dts diff) of the second last sample for
4884 // the last one. This is a wild guess (and fatal if it turns out
4885 // to be too long), but probably the best we can do - having a zero
4886 // duration is bad as well.
4887 track->track_duration += get_cluster_duration(track, track->entry - 2);
4888 track->end_pts += get_cluster_duration(track, track->entry - 2);
4889 if (!mov->missing_duration_warned) {
4890 av_log(s, AV_LOG_WARNING,
4891 "Estimating the duration of the last packet in a "
4892 "fragment, consider setting the duration field in "
4893 "AVPacket instead.\n");
4894 mov->missing_duration_warned = 1;
4898 if (!mov->moov_written) {
4899 int64_t pos = avio_tell(s->pb);
4901 int buf_size, moov_size;
4903 for (i = 0; i < mov->nb_streams; i++)
4904 if (!mov->tracks[i].entry)
4906 /* Don't write the initial moov unless all tracks have data */
4907 if (i < mov->nb_streams && !force)
4910 moov_size = get_moov_size(s);
4911 for (i = 0; i < mov->nb_streams; i++)
4912 mov->tracks[i].data_offset = pos + moov_size + 8;
4914 avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_HEADER);
4915 if (mov->flags & FF_MOV_FLAG_DELAY_MOOV)
4916 mov_write_identification(s->pb, s);
4917 if ((ret = mov_write_moov_tag(s->pb, mov, s)) < 0)
4920 if (mov->flags & FF_MOV_FLAG_DELAY_MOOV) {
4921 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
4922 mov->reserved_header_pos = avio_tell(s->pb);
4924 mov->moov_written = 1;
4928 buf_size = avio_close_dyn_buf(mov->mdat_buf, &buf);
4929 mov->mdat_buf = NULL;
4930 avio_wb32(s->pb, buf_size + 8);
4931 ffio_wfourcc(s->pb, "mdat");
4932 avio_write(s->pb, buf, buf_size);
4935 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
4936 mov->reserved_header_pos = avio_tell(s->pb);
4938 mov->moov_written = 1;
4940 for (i = 0; i < mov->nb_streams; i++) {
4941 if (mov->tracks[i].entry)
4942 mov->tracks[i].frag_start += mov->tracks[i].start_dts +
4943 mov->tracks[i].track_duration -
4944 mov->tracks[i].cluster[0].dts;
4945 mov->tracks[i].entry = 0;
4946 mov->tracks[i].end_reliable = 0;
4952 if (mov->frag_interleave) {
4953 for (i = 0; i < mov->nb_streams; i++) {
4954 MOVTrack *track = &mov->tracks[i];
4956 if ((ret = mov_flush_fragment_interleaving(s, track)) < 0)
4962 mdat_size = avio_tell(mov->mdat_buf);
4965 for (i = 0; i < mov->nb_streams; i++) {
4966 MOVTrack *track = &mov->tracks[i];
4967 if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF || mov->frag_interleave)
4968 track->data_offset = 0;
4970 track->data_offset = mdat_size;
4971 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
4973 if (first_video_track) {
4975 starts_with_key = track->cluster[0].flags & MOV_SYNC_SAMPLE;
4976 first_video_track = 0;
4981 if (track->mdat_buf)
4982 mdat_size += avio_tell(track->mdat_buf);
4983 if (first_track < 0)
4990 avio_write_marker(s->pb,
4991 av_rescale(mov->tracks[first_track].cluster[0].dts, AV_TIME_BASE, mov->tracks[first_track].timescale),
4992 (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);
4994 for (i = 0; i < mov->nb_streams; i++) {
4995 MOVTrack *track = &mov->tracks[i];
4996 int buf_size, write_moof = 1, moof_tracks = -1;
4998 int64_t duration = 0;
5001 duration = track->start_dts + track->track_duration -
5002 track->cluster[0].dts;
5003 if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF) {
5004 if (!track->mdat_buf)
5006 mdat_size = avio_tell(track->mdat_buf);
5009 write_moof = i == first_track;
5015 mov_write_moof_tag(s->pb, mov, moof_tracks, mdat_size);
5018 avio_wb32(s->pb, mdat_size + 8);
5019 ffio_wfourcc(s->pb, "mdat");
5023 track->frag_start += duration;
5025 track->entries_flushed = 0;
5026 track->end_reliable = 0;
5027 if (!mov->frag_interleave) {
5028 if (!track->mdat_buf)
5030 buf_size = avio_close_dyn_buf(track->mdat_buf, &buf);
5031 track->mdat_buf = NULL;
5035 buf_size = avio_close_dyn_buf(mov->mdat_buf, &buf);
5036 mov->mdat_buf = NULL;
5039 avio_write(s->pb, buf, buf_size);
5049 static int mov_auto_flush_fragment(AVFormatContext *s, int force)
5051 MOVMuxContext *mov = s->priv_data;
5052 int had_moov = mov->moov_written;
5053 int ret = mov_flush_fragment(s, force);
5056 // If using delay_moov, the first flush only wrote the moov,
5057 // not the actual moof+mdat pair, thus flush once again.
5058 if (!had_moov && mov->flags & FF_MOV_FLAG_DELAY_MOOV)
5059 ret = mov_flush_fragment(s, force);
5063 static int check_pkt(AVFormatContext *s, AVPacket *pkt)
5065 MOVMuxContext *mov = s->priv_data;
5066 MOVTrack *trk = &mov->tracks[pkt->stream_index];
5071 ref = trk->cluster[trk->entry - 1].dts;
5072 } else if ( trk->start_dts != AV_NOPTS_VALUE
5073 && !trk->frag_discont) {
5074 ref = trk->start_dts + trk->track_duration;
5076 ref = pkt->dts; // Skip tests for the first packet
5078 if (trk->dts_shift != AV_NOPTS_VALUE) {
5079 /* With negative CTS offsets we have set an offset to the DTS,
5080 * reverse this for the check. */
5081 ref -= trk->dts_shift;
5084 duration = pkt->dts - ref;
5085 if (pkt->dts < ref || duration >= INT_MAX) {
5086 av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" / timestamp: %"PRId64" is out of range for mov/mp4 format\n",
5091 pkt->pts = AV_NOPTS_VALUE;
5094 if (pkt->duration < 0 || pkt->duration > INT_MAX) {
5095 av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" is invalid\n", pkt->duration);
5096 return AVERROR(EINVAL);
5101 int ff_mov_write_packet(AVFormatContext *s, AVPacket *pkt)
5103 MOVMuxContext *mov = s->priv_data;
5104 AVIOContext *pb = s->pb;
5105 MOVTrack *trk = &mov->tracks[pkt->stream_index];
5106 AVCodecParameters *par = trk->par;
5107 unsigned int samples_in_chunk = 0;
5108 int size = pkt->size, ret = 0;
5109 uint8_t *reformatted_data = NULL;
5111 ret = check_pkt(s, pkt);
5115 if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
5117 if (mov->moov_written || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
5118 if (mov->frag_interleave && mov->fragments > 0) {
5119 if (trk->entry - trk->entries_flushed >= mov->frag_interleave) {
5120 if ((ret = mov_flush_fragment_interleaving(s, trk)) < 0)
5125 if (!trk->mdat_buf) {
5126 if ((ret = avio_open_dyn_buf(&trk->mdat_buf)) < 0)
5131 if (!mov->mdat_buf) {
5132 if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0)
5139 if (par->codec_id == AV_CODEC_ID_AMR_NB) {
5140 /* We must find out how many AMR blocks there are in one packet */
5141 static const uint16_t packed_size[16] =
5142 {13, 14, 16, 18, 20, 21, 27, 32, 6, 0, 0, 0, 0, 0, 0, 1};
5145 while (len < size && samples_in_chunk < 100) {
5146 len += packed_size[(pkt->data[len] >> 3) & 0x0F];
5149 if (samples_in_chunk > 1) {
5150 av_log(s, AV_LOG_ERROR, "fatal error, input is not a single packet, implement a AVParser for it\n");
5153 } else if (par->codec_id == AV_CODEC_ID_ADPCM_MS ||
5154 par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) {
5155 samples_in_chunk = trk->par->frame_size;
5156 } else if (trk->sample_size)
5157 samples_in_chunk = size / trk->sample_size;
5159 samples_in_chunk = 1;
5161 /* copy extradata if it exists */
5162 if (trk->vos_len == 0 && par->extradata_size > 0 &&
5163 !TAG_IS_AVCI(trk->tag) &&
5164 (par->codec_id != AV_CODEC_ID_DNXHD)) {
5165 trk->vos_len = par->extradata_size;
5166 trk->vos_data = av_malloc(trk->vos_len);
5167 if (!trk->vos_data) {
5168 ret = AVERROR(ENOMEM);
5171 memcpy(trk->vos_data, par->extradata, trk->vos_len);
5174 if (par->codec_id == AV_CODEC_ID_AAC && pkt->size > 2 &&
5175 (AV_RB16(pkt->data) & 0xfff0) == 0xfff0) {
5176 if (!s->streams[pkt->stream_index]->nb_frames) {
5177 av_log(s, AV_LOG_ERROR, "Malformed AAC bitstream detected: "
5178 "use the audio bitstream filter 'aac_adtstoasc' to fix it "
5179 "('-bsf:a aac_adtstoasc' option with ffmpeg)\n");
5182 av_log(s, AV_LOG_WARNING, "aac bitstream error\n");
5184 if (par->codec_id == AV_CODEC_ID_H264 && trk->vos_len > 0 && *(uint8_t *)trk->vos_data != 1 && !TAG_IS_AVCI(trk->tag)) {
5185 /* from x264 or from bytestream H.264 */
5186 /* NAL reformatting needed */
5187 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
5188 ff_avc_parse_nal_units_buf(pkt->data, &reformatted_data,
5190 avio_write(pb, reformatted_data, size);
5192 if (trk->cenc.aes_ctr) {
5193 size = ff_mov_cenc_avc_parse_nal_units(&trk->cenc, pb, pkt->data, size);
5199 size = ff_avc_parse_nal_units(pb, pkt->data, pkt->size);
5202 } else if (par->codec_id == AV_CODEC_ID_HEVC && trk->vos_len > 6 &&
5203 (AV_RB24(trk->vos_data) == 1 || AV_RB32(trk->vos_data) == 1)) {
5204 /* extradata is Annex B, assume the bitstream is too and convert it */
5205 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
5206 ff_hevc_annexb2mp4_buf(pkt->data, &reformatted_data, &size, 0, NULL);
5207 avio_write(pb, reformatted_data, size);
5209 size = ff_hevc_annexb2mp4(pb, pkt->data, pkt->size, 0, NULL);
5211 #if CONFIG_AC3_PARSER
5212 } else if (par->codec_id == AV_CODEC_ID_EAC3) {
5213 size = handle_eac3(mov, pkt, trk);
5218 avio_write(pb, pkt->data, size);
5221 if (trk->cenc.aes_ctr) {
5222 if (par->codec_id == AV_CODEC_ID_H264 && par->extradata_size > 4) {
5223 int nal_size_length = (par->extradata[4] & 0x3) + 1;
5224 ret = ff_mov_cenc_avc_write_nal_units(s, &trk->cenc, nal_size_length, pb, pkt->data, size);
5226 ret = ff_mov_cenc_write_packet(&trk->cenc, pb, pkt->data, size);
5233 avio_write(pb, pkt->data, size);
5237 if ((par->codec_id == AV_CODEC_ID_DNXHD ||
5238 par->codec_id == AV_CODEC_ID_AC3) && !trk->vos_len) {
5239 /* copy frame to create needed atoms */
5240 trk->vos_len = size;
5241 trk->vos_data = av_malloc(size);
5242 if (!trk->vos_data) {
5243 ret = AVERROR(ENOMEM);
5246 memcpy(trk->vos_data, pkt->data, size);
5249 if (trk->entry >= trk->cluster_capacity) {
5250 unsigned new_capacity = 2 * (trk->entry + MOV_INDEX_CLUSTER_SIZE);
5251 if (av_reallocp_array(&trk->cluster, new_capacity,
5252 sizeof(*trk->cluster))) {
5253 ret = AVERROR(ENOMEM);
5256 trk->cluster_capacity = new_capacity;
5259 trk->cluster[trk->entry].pos = avio_tell(pb) - size;
5260 trk->cluster[trk->entry].samples_in_chunk = samples_in_chunk;
5261 trk->cluster[trk->entry].chunkNum = 0;
5262 trk->cluster[trk->entry].size = size;
5263 trk->cluster[trk->entry].entries = samples_in_chunk;
5264 trk->cluster[trk->entry].dts = pkt->dts;
5265 if (!trk->entry && trk->start_dts != AV_NOPTS_VALUE) {
5266 if (!trk->frag_discont) {
5267 /* First packet of a new fragment. We already wrote the duration
5268 * of the last packet of the previous fragment based on track_duration,
5269 * which might not exactly match our dts. Therefore adjust the dts
5270 * of this packet to be what the previous packets duration implies. */
5271 trk->cluster[trk->entry].dts = trk->start_dts + trk->track_duration;
5272 /* We also may have written the pts and the corresponding duration
5273 * in sidx/tfrf/tfxd tags; make sure the sidx pts and duration match up with
5274 * the next fragment. This means the cts of the first sample must
5275 * be the same in all fragments, unless end_pts was updated by
5276 * the packet causing the fragment to be written. */
5277 if ((mov->flags & FF_MOV_FLAG_DASH && !(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)) ||
5278 mov->mode == MODE_ISM)
5279 pkt->pts = pkt->dts + trk->end_pts - trk->cluster[trk->entry].dts;
5281 /* New fragment, but discontinuous from previous fragments.
5282 * Pretend the duration sum of the earlier fragments is
5283 * pkt->dts - trk->start_dts. */
5284 trk->frag_start = pkt->dts - trk->start_dts;
5285 trk->end_pts = AV_NOPTS_VALUE;
5286 trk->frag_discont = 0;
5290 if (!trk->entry && trk->start_dts == AV_NOPTS_VALUE && !mov->use_editlist &&
5291 s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO) {
5292 /* Not using edit lists and shifting the first track to start from zero.
5293 * If the other streams start from a later timestamp, we won't be able
5294 * to signal the difference in starting time without an edit list.
5295 * Thus move the timestamp for this first sample to 0, increasing
5296 * its duration instead. */
5297 trk->cluster[trk->entry].dts = trk->start_dts = 0;
5299 if (trk->start_dts == AV_NOPTS_VALUE) {
5300 trk->start_dts = pkt->dts;
5301 if (trk->frag_discont) {
5302 if (mov->use_editlist) {
5303 /* Pretend the whole stream started at pts=0, with earlier fragments
5304 * already written. If the stream started at pts=0, the duration sum
5305 * of earlier fragments would have been pkt->pts. */
5306 trk->frag_start = pkt->pts;
5307 trk->start_dts = pkt->dts - pkt->pts;
5309 /* Pretend the whole stream started at dts=0, with earlier fragments
5310 * already written, with a duration summing up to pkt->dts. */
5311 trk->frag_start = pkt->dts;
5314 trk->frag_discont = 0;
5315 } else if (pkt->dts && mov->moov_written)
5316 av_log(s, AV_LOG_WARNING,
5317 "Track %d starts with a nonzero dts %"PRId64", while the moov "
5318 "already has been written. Set the delay_moov flag to handle "
5320 pkt->stream_index, pkt->dts);
5322 trk->track_duration = pkt->dts - trk->start_dts + pkt->duration;
5323 trk->last_sample_is_subtitle_end = 0;
5325 if (pkt->pts == AV_NOPTS_VALUE) {
5326 av_log(s, AV_LOG_WARNING, "pts has no value\n");
5327 pkt->pts = pkt->dts;
5329 if (pkt->dts != pkt->pts)
5330 trk->flags |= MOV_TRACK_CTTS;
5331 trk->cluster[trk->entry].cts = pkt->pts - pkt->dts;
5332 trk->cluster[trk->entry].flags = 0;
5333 if (trk->start_cts == AV_NOPTS_VALUE)
5334 trk->start_cts = pkt->pts - pkt->dts;
5335 if (trk->end_pts == AV_NOPTS_VALUE)
5336 trk->end_pts = trk->cluster[trk->entry].dts +
5337 trk->cluster[trk->entry].cts + pkt->duration;
5339 trk->end_pts = FFMAX(trk->end_pts, trk->cluster[trk->entry].dts +
5340 trk->cluster[trk->entry].cts +
5343 if (par->codec_id == AV_CODEC_ID_VC1) {
5344 mov_parse_vc1_frame(pkt, trk);
5345 } else if (pkt->flags & AV_PKT_FLAG_KEY) {
5346 if (mov->mode == MODE_MOV && par->codec_id == AV_CODEC_ID_MPEG2VIDEO &&
5347 trk->entry > 0) { // force sync sample for the first key frame
5348 mov_parse_mpeg2_frame(pkt, &trk->cluster[trk->entry].flags);
5349 if (trk->cluster[trk->entry].flags & MOV_PARTIAL_SYNC_SAMPLE)
5350 trk->flags |= MOV_TRACK_STPS;
5352 trk->cluster[trk->entry].flags = MOV_SYNC_SAMPLE;
5354 if (trk->cluster[trk->entry].flags & MOV_SYNC_SAMPLE)
5355 trk->has_keyframes++;
5357 if (pkt->flags & AV_PKT_FLAG_DISPOSABLE) {
5358 trk->cluster[trk->entry].flags |= MOV_DISPOSABLE_SAMPLE;
5359 trk->has_disposable++;
5362 trk->sample_count += samples_in_chunk;
5363 mov->mdat_size += size;
5365 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams)
5366 ff_mov_add_hinted_packet(s, pkt, trk->hint_track, trk->entry,
5367 reformatted_data, size);
5372 av_free(reformatted_data);
5376 static int mov_write_single_packet(AVFormatContext *s, AVPacket *pkt)
5378 MOVMuxContext *mov = s->priv_data;
5379 MOVTrack *trk = &mov->tracks[pkt->stream_index];
5380 AVCodecParameters *par = trk->par;
5381 int64_t frag_duration = 0;
5382 int size = pkt->size;
5384 int ret = check_pkt(s, pkt);
5388 if (mov->flags & FF_MOV_FLAG_FRAG_DISCONT) {
5390 for (i = 0; i < s->nb_streams; i++)
5391 mov->tracks[i].frag_discont = 1;
5392 mov->flags &= ~FF_MOV_FLAG_FRAG_DISCONT;
5395 if (mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS) {
5396 if (trk->dts_shift == AV_NOPTS_VALUE)
5397 trk->dts_shift = pkt->pts - pkt->dts;
5398 pkt->dts += trk->dts_shift;
5401 if (trk->par->codec_id == AV_CODEC_ID_MP4ALS ||
5402 trk->par->codec_id == AV_CODEC_ID_AAC ||
5403 trk->par->codec_id == AV_CODEC_ID_FLAC) {
5405 uint8_t *side = av_packet_get_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA, &side_size);
5406 if (side && side_size > 0 && (side_size != par->extradata_size || memcmp(side, par->extradata, side_size))) {
5407 void *newextra = av_mallocz(side_size + AV_INPUT_BUFFER_PADDING_SIZE);
5409 return AVERROR(ENOMEM);
5410 av_free(par->extradata);
5411 par->extradata = newextra;
5412 memcpy(par->extradata, side, side_size);
5413 par->extradata_size = side_size;
5414 if (!pkt->size) // Flush packet
5415 mov->need_rewrite_extradata = 1;
5420 if (trk->start_dts == AV_NOPTS_VALUE && trk->frag_discont) {
5421 trk->start_dts = pkt->dts;
5422 if (pkt->pts != AV_NOPTS_VALUE)
5423 trk->start_cts = pkt->pts - pkt->dts;
5428 return 0; /* Discard 0 sized packets */
5431 if (trk->entry && pkt->stream_index < s->nb_streams)
5432 frag_duration = av_rescale_q(pkt->dts - trk->cluster[0].dts,
5433 s->streams[pkt->stream_index]->time_base,
5435 if ((mov->max_fragment_duration &&
5436 frag_duration >= mov->max_fragment_duration) ||
5437 (mov->max_fragment_size && mov->mdat_size + size >= mov->max_fragment_size) ||
5438 (mov->flags & FF_MOV_FLAG_FRAG_KEYFRAME &&
5439 par->codec_type == AVMEDIA_TYPE_VIDEO &&
5440 trk->entry && pkt->flags & AV_PKT_FLAG_KEY) ||
5441 (mov->flags & FF_MOV_FLAG_FRAG_EVERY_FRAME)) {
5442 if (frag_duration >= mov->min_fragment_duration) {
5443 // Set the duration of this track to line up with the next
5444 // sample in this track. This avoids relying on AVPacket
5445 // duration, but only helps for this particular track, not
5446 // for the other ones that are flushed at the same time.
5447 trk->track_duration = pkt->dts - trk->start_dts;
5448 if (pkt->pts != AV_NOPTS_VALUE)
5449 trk->end_pts = pkt->pts;
5451 trk->end_pts = pkt->dts;
5452 trk->end_reliable = 1;
5453 mov_auto_flush_fragment(s, 0);
5457 return ff_mov_write_packet(s, pkt);
5460 static int mov_write_subtitle_end_packet(AVFormatContext *s,
5464 uint8_t data[2] = {0};
5467 av_init_packet(&end);
5468 end.size = sizeof(data);
5473 end.stream_index = stream_index;
5475 ret = mov_write_single_packet(s, &end);
5476 av_packet_unref(&end);
5481 static int mov_write_packet(AVFormatContext *s, AVPacket *pkt)
5484 mov_flush_fragment(s, 1);
5488 MOVMuxContext *mov = s->priv_data;
5489 MOVTrack *trk = &mov->tracks[pkt->stream_index];
5492 return mov_write_single_packet(s, pkt); /* Passthrough. */
5495 * Subtitles require special handling.
5497 * 1) For full complaince, every track must have a sample at
5498 * dts == 0, which is rarely true for subtitles. So, as soon
5499 * as we see any packet with dts > 0, write an empty subtitle
5500 * at dts == 0 for any subtitle track with no samples in it.
5502 * 2) For each subtitle track, check if the current packet's
5503 * dts is past the duration of the last subtitle sample. If
5504 * so, we now need to write an end sample for that subtitle.
5506 * This must be done conditionally to allow for subtitles that
5507 * immediately replace each other, in which case an end sample
5508 * is not needed, and is, in fact, actively harmful.
5510 * 3) See mov_write_trailer for how the final end sample is
5513 for (i = 0; i < mov->nb_streams; i++) {
5514 MOVTrack *trk = &mov->tracks[i];
5517 if (trk->par->codec_id == AV_CODEC_ID_MOV_TEXT &&
5518 trk->track_duration < pkt->dts &&
5519 (trk->entry == 0 || !trk->last_sample_is_subtitle_end)) {
5520 ret = mov_write_subtitle_end_packet(s, i, trk->track_duration);
5521 if (ret < 0) return ret;
5522 trk->last_sample_is_subtitle_end = 1;
5526 if (trk->mode == MODE_MOV && trk->par->codec_type == AVMEDIA_TYPE_VIDEO) {
5527 AVPacket *opkt = pkt;
5528 int reshuffle_ret, ret;
5529 if (trk->is_unaligned_qt_rgb) {
5530 int64_t bpc = trk->par->bits_per_coded_sample != 15 ? trk->par->bits_per_coded_sample : 16;
5531 int expected_stride = ((trk->par->width * bpc + 15) >> 4)*2;
5532 reshuffle_ret = ff_reshuffle_raw_rgb(s, &pkt, trk->par, expected_stride);
5533 if (reshuffle_ret < 0)
5534 return reshuffle_ret;
5537 if (trk->par->format == AV_PIX_FMT_PAL8 && !trk->pal_done) {
5538 ret = ff_get_packet_palette(s, opkt, reshuffle_ret, trk->palette);
5543 } else if (trk->par->codec_id == AV_CODEC_ID_RAWVIDEO &&
5544 (trk->par->format == AV_PIX_FMT_GRAY8 ||
5545 trk->par->format == AV_PIX_FMT_MONOBLACK)) {
5546 for (i = 0; i < pkt->size; i++)
5547 pkt->data[i] = ~pkt->data[i];
5549 if (reshuffle_ret) {
5550 ret = mov_write_single_packet(s, pkt);
5553 av_packet_free(&pkt);
5558 return mov_write_single_packet(s, pkt);
5562 // QuickTime chapters involve an additional text track with the chapter names
5563 // as samples, and a tref pointing from the other tracks to the chapter one.
5564 static int mov_create_chapter_track(AVFormatContext *s, int tracknum)
5568 MOVMuxContext *mov = s->priv_data;
5569 MOVTrack *track = &mov->tracks[tracknum];
5570 AVPacket pkt = { .stream_index = tracknum, .flags = AV_PKT_FLAG_KEY };
5573 track->mode = mov->mode;
5574 track->tag = MKTAG('t','e','x','t');
5575 track->timescale = MOV_TIMESCALE;
5576 track->par = avcodec_parameters_alloc();
5578 return AVERROR(ENOMEM);
5579 track->par->codec_type = AVMEDIA_TYPE_SUBTITLE;
5581 // These properties are required to make QT recognize the chapter track
5582 uint8_t chapter_properties[43] = { 0, 0, 0, 0, 0, 0, 0, 1, };
5583 if (ff_alloc_extradata(track->par, sizeof(chapter_properties)))
5584 return AVERROR(ENOMEM);
5585 memcpy(track->par->extradata, chapter_properties, sizeof(chapter_properties));
5587 if (avio_open_dyn_buf(&pb) >= 0) {
5591 /* Stub header (usually for Quicktime chapter track) */
5593 avio_wb32(pb, 0x01); // displayFlags
5594 avio_w8(pb, 0x00); // horizontal justification
5595 avio_w8(pb, 0x00); // vertical justification
5596 avio_w8(pb, 0x00); // bgColourRed
5597 avio_w8(pb, 0x00); // bgColourGreen
5598 avio_w8(pb, 0x00); // bgColourBlue
5599 avio_w8(pb, 0x00); // bgColourAlpha
5601 avio_wb16(pb, 0x00); // defTextBoxTop
5602 avio_wb16(pb, 0x00); // defTextBoxLeft
5603 avio_wb16(pb, 0x00); // defTextBoxBottom
5604 avio_wb16(pb, 0x00); // defTextBoxRight
5606 avio_wb16(pb, 0x00); // startChar
5607 avio_wb16(pb, 0x00); // endChar
5608 avio_wb16(pb, 0x01); // fontID
5609 avio_w8(pb, 0x00); // fontStyleFlags
5610 avio_w8(pb, 0x00); // fontSize
5611 avio_w8(pb, 0x00); // fgColourRed
5612 avio_w8(pb, 0x00); // fgColourGreen
5613 avio_w8(pb, 0x00); // fgColourBlue
5614 avio_w8(pb, 0x00); // fgColourAlpha
5616 avio_wb32(pb, 0x0D); // box size
5617 ffio_wfourcc(pb, "ftab"); // box atom name
5618 avio_wb16(pb, 0x01); // entry count
5620 avio_wb16(pb, 0x01); // font ID
5621 avio_w8(pb, 0x00); // font name length
5623 if ((size = avio_close_dyn_buf(pb, &buf)) > 0) {
5624 track->par->extradata = buf;
5625 track->par->extradata_size = size;
5632 for (i = 0; i < s->nb_chapters; i++) {
5633 AVChapter *c = s->chapters[i];
5634 AVDictionaryEntry *t;
5636 int64_t end = av_rescale_q(c->end, c->time_base, (AVRational){1,MOV_TIMESCALE});
5637 pkt.pts = pkt.dts = av_rescale_q(c->start, c->time_base, (AVRational){1,MOV_TIMESCALE});
5638 pkt.duration = end - pkt.dts;
5640 if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
5641 static const char encd[12] = {
5642 0x00, 0x00, 0x00, 0x0C,
5644 0x00, 0x00, 0x01, 0x00 };
5645 len = strlen(t->value);
5646 pkt.size = len + 2 + 12;
5647 pkt.data = av_malloc(pkt.size);
5649 return AVERROR(ENOMEM);
5650 AV_WB16(pkt.data, len);
5651 memcpy(pkt.data + 2, t->value, len);
5652 memcpy(pkt.data + len + 2, encd, sizeof(encd));
5653 ff_mov_write_packet(s, &pkt);
5654 av_freep(&pkt.data);
5662 static int mov_check_timecode_track(AVFormatContext *s, AVTimecode *tc, int src_index, const char *tcstr)
5666 /* compute the frame number */
5667 ret = av_timecode_init_from_string(tc, find_fps(s, s->streams[src_index]), tcstr, s);
5671 static int mov_create_timecode_track(AVFormatContext *s, int index, int src_index, AVTimecode tc)
5674 MOVMuxContext *mov = s->priv_data;
5675 MOVTrack *track = &mov->tracks[index];
5676 AVStream *src_st = s->streams[src_index];
5677 AVPacket pkt = {.stream_index = index, .flags = AV_PKT_FLAG_KEY, .size = 4};
5678 AVRational rate = find_fps(s, src_st);
5680 /* tmcd track based on video stream */
5681 track->mode = mov->mode;
5682 track->tag = MKTAG('t','m','c','d');
5683 track->src_track = src_index;
5684 track->timescale = mov->tracks[src_index].timescale;
5685 if (tc.flags & AV_TIMECODE_FLAG_DROPFRAME)
5686 track->timecode_flags |= MOV_TIMECODE_FLAG_DROPFRAME;
5688 /* set st to src_st for metadata access*/
5691 /* encode context: tmcd data stream */
5692 track->par = avcodec_parameters_alloc();
5694 return AVERROR(ENOMEM);
5695 track->par->codec_type = AVMEDIA_TYPE_DATA;
5696 track->par->codec_tag = track->tag;
5697 track->st->avg_frame_rate = av_inv_q(rate);
5699 /* the tmcd track just contains one packet with the frame number */
5700 pkt.data = av_malloc(pkt.size);
5702 return AVERROR(ENOMEM);
5703 AV_WB32(pkt.data, tc.start);
5704 ret = ff_mov_write_packet(s, &pkt);
5710 * st->disposition controls the "enabled" flag in the tkhd tag.
5711 * QuickTime will not play a track if it is not enabled. So make sure
5712 * that one track of each type (audio, video, subtitle) is enabled.
5714 * Subtitles are special. For audio and video, setting "enabled" also
5715 * makes the track "default" (i.e. it is rendered when played). For
5716 * subtitles, an "enabled" subtitle is not rendered by default, but
5717 * if no subtitle is enabled, the subtitle menu in QuickTime will be
5720 static void enable_tracks(AVFormatContext *s)
5722 MOVMuxContext *mov = s->priv_data;
5724 int enabled[AVMEDIA_TYPE_NB];
5725 int first[AVMEDIA_TYPE_NB];
5727 for (i = 0; i < AVMEDIA_TYPE_NB; i++) {
5732 for (i = 0; i < s->nb_streams; i++) {
5733 AVStream *st = s->streams[i];
5735 if (st->codecpar->codec_type <= AVMEDIA_TYPE_UNKNOWN ||
5736 st->codecpar->codec_type >= AVMEDIA_TYPE_NB)
5739 if (first[st->codecpar->codec_type] < 0)
5740 first[st->codecpar->codec_type] = i;
5741 if (st->disposition & AV_DISPOSITION_DEFAULT) {
5742 mov->tracks[i].flags |= MOV_TRACK_ENABLED;
5743 enabled[st->codecpar->codec_type]++;
5747 for (i = 0; i < AVMEDIA_TYPE_NB; i++) {
5749 case AVMEDIA_TYPE_VIDEO:
5750 case AVMEDIA_TYPE_AUDIO:
5751 case AVMEDIA_TYPE_SUBTITLE:
5753 mov->per_stream_grouping = 1;
5754 if (!enabled[i] && first[i] >= 0)
5755 mov->tracks[first[i]].flags |= MOV_TRACK_ENABLED;
5761 static void mov_free(AVFormatContext *s)
5763 MOVMuxContext *mov = s->priv_data;
5766 if (mov->chapter_track) {
5767 if (mov->tracks[mov->chapter_track].par)
5768 av_freep(&mov->tracks[mov->chapter_track].par->extradata);
5769 av_freep(&mov->tracks[mov->chapter_track].par);
5772 for (i = 0; i < mov->nb_streams; i++) {
5773 if (mov->tracks[i].tag == MKTAG('r','t','p',' '))
5774 ff_mov_close_hinting(&mov->tracks[i]);
5775 else if (mov->tracks[i].tag == MKTAG('t','m','c','d') && mov->nb_meta_tmcd)
5776 av_freep(&mov->tracks[i].par);
5777 av_freep(&mov->tracks[i].cluster);
5778 av_freep(&mov->tracks[i].frag_info);
5780 if (mov->tracks[i].vos_len)
5781 av_freep(&mov->tracks[i].vos_data);
5783 ff_mov_cenc_free(&mov->tracks[i].cenc);
5786 av_freep(&mov->tracks);
5789 static uint32_t rgb_to_yuv(uint32_t rgb)
5794 r = (rgb >> 16) & 0xFF;
5795 g = (rgb >> 8) & 0xFF;
5798 y = av_clip_uint8(( 16000 + 257 * r + 504 * g + 98 * b)/1000);
5799 cb = av_clip_uint8((128000 - 148 * r - 291 * g + 439 * b)/1000);
5800 cr = av_clip_uint8((128000 + 439 * r - 368 * g - 71 * b)/1000);
5802 return (y << 16) | (cr << 8) | cb;
5805 static int mov_create_dvd_sub_decoder_specific_info(MOVTrack *track,
5808 int i, width = 720, height = 480;
5809 int have_palette = 0, have_size = 0;
5810 uint32_t palette[16];
5811 char *cur = st->codecpar->extradata;
5813 while (cur && *cur) {
5814 if (strncmp("palette:", cur, 8) == 0) {
5816 count = sscanf(cur + 8,
5817 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
5818 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
5819 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
5820 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32"",
5821 &palette[ 0], &palette[ 1], &palette[ 2], &palette[ 3],
5822 &palette[ 4], &palette[ 5], &palette[ 6], &palette[ 7],
5823 &palette[ 8], &palette[ 9], &palette[10], &palette[11],
5824 &palette[12], &palette[13], &palette[14], &palette[15]);
5826 for (i = 0; i < count; i++) {
5827 palette[i] = rgb_to_yuv(palette[i]);
5830 } else if (!strncmp("size:", cur, 5)) {
5831 sscanf(cur + 5, "%dx%d", &width, &height);
5834 if (have_palette && have_size)
5836 cur += strcspn(cur, "\n\r");
5837 cur += strspn(cur, "\n\r");
5840 track->vos_data = av_malloc(16*4);
5841 if (!track->vos_data)
5842 return AVERROR(ENOMEM);
5843 for (i = 0; i < 16; i++) {
5844 AV_WB32(track->vos_data + i * 4, palette[i]);
5846 track->vos_len = 16 * 4;
5848 st->codecpar->width = width;
5849 st->codecpar->height = track->height = height;
5854 static int mov_init(AVFormatContext *s)
5856 MOVMuxContext *mov = s->priv_data;
5857 AVDictionaryEntry *global_tcr = av_dict_get(s->metadata, "timecode", NULL, 0);
5862 /* Default mode == MP4 */
5863 mov->mode = MODE_MP4;
5866 if (!strcmp("3gp", s->oformat->name)) mov->mode = MODE_3GP;
5867 else if (!strcmp("3g2", s->oformat->name)) mov->mode = MODE_3GP|MODE_3G2;
5868 else if (!strcmp("mov", s->oformat->name)) mov->mode = MODE_MOV;
5869 else if (!strcmp("psp", s->oformat->name)) mov->mode = MODE_PSP;
5870 else if (!strcmp("ipod",s->oformat->name)) mov->mode = MODE_IPOD;
5871 else if (!strcmp("ismv",s->oformat->name)) mov->mode = MODE_ISM;
5872 else if (!strcmp("f4v", s->oformat->name)) mov->mode = MODE_F4V;
5875 if (mov->flags & FF_MOV_FLAG_DELAY_MOOV)
5876 mov->flags |= FF_MOV_FLAG_EMPTY_MOOV;
5878 /* Set the FRAGMENT flag if any of the fragmentation methods are
5880 if (mov->max_fragment_duration || mov->max_fragment_size ||
5881 mov->flags & (FF_MOV_FLAG_EMPTY_MOOV |
5882 FF_MOV_FLAG_FRAG_KEYFRAME |
5883 FF_MOV_FLAG_FRAG_CUSTOM |
5884 FF_MOV_FLAG_FRAG_EVERY_FRAME))
5885 mov->flags |= FF_MOV_FLAG_FRAGMENT;
5887 /* Set other implicit flags immediately */
5888 if (mov->mode == MODE_ISM)
5889 mov->flags |= FF_MOV_FLAG_EMPTY_MOOV | FF_MOV_FLAG_SEPARATE_MOOF |
5890 FF_MOV_FLAG_FRAGMENT;
5891 if (mov->flags & FF_MOV_FLAG_DASH)
5892 mov->flags |= FF_MOV_FLAG_FRAGMENT | FF_MOV_FLAG_EMPTY_MOOV |
5893 FF_MOV_FLAG_DEFAULT_BASE_MOOF;
5895 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV && s->flags & AVFMT_FLAG_AUTO_BSF) {
5896 av_log(s, AV_LOG_VERBOSE, "Empty MOOV enabled; disabling automatic bitstream filtering\n");
5897 s->flags &= ~AVFMT_FLAG_AUTO_BSF;
5900 if (mov->flags & FF_MOV_FLAG_FASTSTART) {
5901 mov->reserved_moov_size = -1;
5904 if (mov->use_editlist < 0) {
5905 mov->use_editlist = 1;
5906 if (mov->flags & FF_MOV_FLAG_FRAGMENT &&
5907 !(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
5908 // If we can avoid needing an edit list by shifting the
5909 // tracks, prefer that over (trying to) write edit lists
5910 // in fragmented output.
5911 if (s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO ||
5912 s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO)
5913 mov->use_editlist = 0;
5916 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV &&
5917 !(mov->flags & FF_MOV_FLAG_DELAY_MOOV) && mov->use_editlist)
5918 av_log(s, AV_LOG_WARNING, "No meaningful edit list will be written when using empty_moov without delay_moov\n");
5920 if (!mov->use_editlist && s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO)
5921 s->avoid_negative_ts = AVFMT_AVOID_NEG_TS_MAKE_ZERO;
5923 /* Clear the omit_tfhd_offset flag if default_base_moof is set;
5924 * if the latter is set that's enough and omit_tfhd_offset doesn't
5925 * add anything extra on top of that. */
5926 if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET &&
5927 mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)
5928 mov->flags &= ~FF_MOV_FLAG_OMIT_TFHD_OFFSET;
5930 if (mov->frag_interleave &&
5931 mov->flags & (FF_MOV_FLAG_OMIT_TFHD_OFFSET | FF_MOV_FLAG_SEPARATE_MOOF)) {
5932 av_log(s, AV_LOG_ERROR,
5933 "Sample interleaving in fragments is mutually exclusive with "
5934 "omit_tfhd_offset and separate_moof\n");
5935 return AVERROR(EINVAL);
5938 /* Non-seekable output is ok if using fragmentation. If ism_lookahead
5939 * is enabled, we don't support non-seekable output at all. */
5940 if (!(s->pb->seekable & AVIO_SEEKABLE_NORMAL) &&
5941 (!(mov->flags & FF_MOV_FLAG_FRAGMENT) || mov->ism_lookahead)) {
5942 av_log(s, AV_LOG_ERROR, "muxer does not support non seekable output\n");
5943 return AVERROR(EINVAL);
5946 mov->nb_streams = s->nb_streams;
5947 if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters)
5948 mov->chapter_track = mov->nb_streams++;
5950 if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
5951 for (i = 0; i < s->nb_streams; i++)
5952 if (rtp_hinting_needed(s->streams[i]))
5956 if ( mov->write_tmcd == -1 && (mov->mode == MODE_MOV || mov->mode == MODE_MP4)
5957 || mov->write_tmcd == 1) {
5958 /* +1 tmcd track for each video stream with a timecode */
5959 for (i = 0; i < s->nb_streams; i++) {
5960 AVStream *st = s->streams[i];
5961 AVDictionaryEntry *t = global_tcr;
5962 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
5963 (t || (t=av_dict_get(st->metadata, "timecode", NULL, 0)))) {
5965 ret = mov_check_timecode_track(s, &tc, i, t->value);
5967 mov->nb_meta_tmcd++;
5971 /* check if there is already a tmcd track to remux */
5972 if (mov->nb_meta_tmcd) {
5973 for (i = 0; i < s->nb_streams; i++) {
5974 AVStream *st = s->streams[i];
5975 if (st->codecpar->codec_tag == MKTAG('t','m','c','d')) {
5976 av_log(s, AV_LOG_WARNING, "You requested a copy of the original timecode track "
5977 "so timecode metadata are now ignored\n");
5978 mov->nb_meta_tmcd = 0;
5983 mov->nb_streams += mov->nb_meta_tmcd;
5986 // Reserve an extra stream for chapters for the case where chapters
5987 // are written in the trailer
5988 mov->tracks = av_mallocz_array((mov->nb_streams + 1), sizeof(*mov->tracks));
5990 return AVERROR(ENOMEM);
5992 if (mov->encryption_scheme_str != NULL && strcmp(mov->encryption_scheme_str, "none") != 0) {
5993 if (strcmp(mov->encryption_scheme_str, "cenc-aes-ctr") == 0) {
5994 mov->encryption_scheme = MOV_ENC_CENC_AES_CTR;
5996 if (mov->encryption_key_len != AES_CTR_KEY_SIZE) {
5997 av_log(s, AV_LOG_ERROR, "Invalid encryption key len %d expected %d\n",
5998 mov->encryption_key_len, AES_CTR_KEY_SIZE);
5999 return AVERROR(EINVAL);
6002 if (mov->encryption_kid_len != CENC_KID_SIZE) {
6003 av_log(s, AV_LOG_ERROR, "Invalid encryption kid len %d expected %d\n",
6004 mov->encryption_kid_len, CENC_KID_SIZE);
6005 return AVERROR(EINVAL);
6008 av_log(s, AV_LOG_ERROR, "unsupported encryption scheme %s\n",
6009 mov->encryption_scheme_str);
6010 return AVERROR(EINVAL);
6014 for (i = 0; i < s->nb_streams; i++) {
6015 AVStream *st= s->streams[i];
6016 MOVTrack *track= &mov->tracks[i];
6017 AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0);
6020 track->par = st->codecpar;
6021 track->language = ff_mov_iso639_to_lang(lang?lang->value:"und", mov->mode!=MODE_MOV);
6022 if (track->language < 0)
6023 track->language = 0;
6024 track->mode = mov->mode;
6025 track->tag = mov_find_codec_tag(s, track);
6027 av_log(s, AV_LOG_ERROR, "Could not find tag for codec %s in stream #%d, "
6028 "codec not currently supported in container\n",
6029 avcodec_get_name(st->codecpar->codec_id), i);
6030 return AVERROR(EINVAL);
6032 /* If hinting of this track is enabled by a later hint track,
6033 * this is updated. */
6034 track->hint_track = -1;
6035 track->start_dts = AV_NOPTS_VALUE;
6036 track->start_cts = AV_NOPTS_VALUE;
6037 track->end_pts = AV_NOPTS_VALUE;
6038 track->dts_shift = AV_NOPTS_VALUE;
6039 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
6040 if (track->tag == MKTAG('m','x','3','p') || track->tag == MKTAG('m','x','3','n') ||
6041 track->tag == MKTAG('m','x','4','p') || track->tag == MKTAG('m','x','4','n') ||
6042 track->tag == MKTAG('m','x','5','p') || track->tag == MKTAG('m','x','5','n')) {
6043 if (st->codecpar->width != 720 || (st->codecpar->height != 608 && st->codecpar->height != 512)) {
6044 av_log(s, AV_LOG_ERROR, "D-10/IMX must use 720x608 or 720x512 video resolution\n");
6045 return AVERROR(EINVAL);
6047 track->height = track->tag >> 24 == 'n' ? 486 : 576;
6049 if (mov->video_track_timescale) {
6050 track->timescale = mov->video_track_timescale;
6052 track->timescale = st->time_base.den;
6053 while(track->timescale < 10000)
6054 track->timescale *= 2;
6056 if (st->codecpar->width > 65535 || st->codecpar->height > 65535) {
6057 av_log(s, AV_LOG_ERROR, "Resolution %dx%d too large for mov/mp4\n", st->codecpar->width, st->codecpar->height);
6058 return AVERROR(EINVAL);
6060 if (track->mode == MODE_MOV && track->timescale > 100000)
6061 av_log(s, AV_LOG_WARNING,
6062 "WARNING codec timebase is very high. If duration is too long,\n"
6063 "file may not be playable by quicktime. Specify a shorter timebase\n"
6064 "or choose different container.\n");
6065 if (track->mode == MODE_MOV &&
6066 track->par->codec_id == AV_CODEC_ID_RAWVIDEO &&
6067 track->tag == MKTAG('r','a','w',' ')) {
6068 enum AVPixelFormat pix_fmt = track->par->format;
6069 if (pix_fmt == AV_PIX_FMT_NONE && track->par->bits_per_coded_sample == 1)
6070 pix_fmt = AV_PIX_FMT_MONOWHITE;
6071 track->is_unaligned_qt_rgb =
6072 pix_fmt == AV_PIX_FMT_RGB24 ||
6073 pix_fmt == AV_PIX_FMT_BGR24 ||
6074 pix_fmt == AV_PIX_FMT_PAL8 ||
6075 pix_fmt == AV_PIX_FMT_GRAY8 ||
6076 pix_fmt == AV_PIX_FMT_MONOWHITE ||
6077 pix_fmt == AV_PIX_FMT_MONOBLACK;
6079 if (track->par->codec_id == AV_CODEC_ID_VP9) {
6080 if (track->mode != MODE_MP4) {
6081 av_log(s, AV_LOG_ERROR, "VP9 only supported in MP4.\n");
6082 return AVERROR(EINVAL);
6084 } else if (track->par->codec_id == AV_CODEC_ID_VP8) {
6085 /* altref frames handling is not defined in the spec as of version v1.0,
6086 * so just forbid muxing VP8 streams altogether until a new version does */
6087 av_log(s, AV_LOG_ERROR, "VP8 muxing is currently not supported.\n");
6088 return AVERROR_PATCHWELCOME;
6090 } else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
6091 track->timescale = st->codecpar->sample_rate;
6092 if (!st->codecpar->frame_size && !av_get_bits_per_sample(st->codecpar->codec_id)) {
6093 av_log(s, AV_LOG_WARNING, "track %d: codec frame size is not set\n", i);
6094 track->audio_vbr = 1;
6095 }else if (st->codecpar->codec_id == AV_CODEC_ID_ADPCM_MS ||
6096 st->codecpar->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
6097 st->codecpar->codec_id == AV_CODEC_ID_ILBC){
6098 if (!st->codecpar->block_align) {
6099 av_log(s, AV_LOG_ERROR, "track %d: codec block align is not set for adpcm\n", i);
6100 return AVERROR(EINVAL);
6102 track->sample_size = st->codecpar->block_align;
6103 }else if (st->codecpar->frame_size > 1){ /* assume compressed audio */
6104 track->audio_vbr = 1;
6106 track->sample_size = (av_get_bits_per_sample(st->codecpar->codec_id) >> 3) * st->codecpar->channels;
6108 if (st->codecpar->codec_id == AV_CODEC_ID_ILBC ||
6109 st->codecpar->codec_id == AV_CODEC_ID_ADPCM_IMA_QT) {
6110 track->audio_vbr = 1;
6112 if (track->mode != MODE_MOV &&
6113 track->par->codec_id == AV_CODEC_ID_MP3 && track->timescale < 16000) {
6114 if (s->strict_std_compliance >= FF_COMPLIANCE_NORMAL) {
6115 av_log(s, AV_LOG_ERROR, "track %d: muxing mp3 at %dhz is not standard, to mux anyway set strict to -1\n",
6116 i, track->par->sample_rate);
6117 return AVERROR(EINVAL);
6119 av_log(s, AV_LOG_WARNING, "track %d: muxing mp3 at %dhz is not standard in MP4\n",
6120 i, track->par->sample_rate);
6123 if (track->par->codec_id == AV_CODEC_ID_FLAC ||
6124 track->par->codec_id == AV_CODEC_ID_OPUS) {
6125 if (track->mode != MODE_MP4) {
6126 av_log(s, AV_LOG_ERROR, "%s only supported in MP4.\n", avcodec_get_name(track->par->codec_id));
6127 return AVERROR(EINVAL);
6129 if (s->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
6130 av_log(s, AV_LOG_ERROR,
6131 "%s in MP4 support is experimental, add "
6132 "'-strict %d' if you want to use it.\n",
6133 avcodec_get_name(track->par->codec_id), FF_COMPLIANCE_EXPERIMENTAL);
6134 return AVERROR_EXPERIMENTAL;
6137 } else if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) {
6138 track->timescale = st->time_base.den;
6139 } else if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA) {
6140 track->timescale = st->time_base.den;
6142 track->timescale = MOV_TIMESCALE;
6145 track->height = st->codecpar->height;
6146 /* The ism specific timescale isn't mandatory, but is assumed by
6147 * some tools, such as mp4split. */
6148 if (mov->mode == MODE_ISM)
6149 track->timescale = 10000000;
6151 avpriv_set_pts_info(st, 64, 1, track->timescale);
6153 if (mov->encryption_scheme == MOV_ENC_CENC_AES_CTR) {
6154 ret = ff_mov_cenc_init(&track->cenc, mov->encryption_key,
6155 track->par->codec_id == AV_CODEC_ID_H264, s->flags & AVFMT_FLAG_BITEXACT);
6165 static int mov_write_header(AVFormatContext *s)
6167 AVIOContext *pb = s->pb;
6168 MOVMuxContext *mov = s->priv_data;
6169 AVDictionaryEntry *t, *global_tcr = av_dict_get(s->metadata, "timecode", NULL, 0);
6170 int i, ret, hint_track = 0, tmcd_track = 0, nb_tracks = s->nb_streams;
6172 if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters)
6175 if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
6176 hint_track = nb_tracks;
6177 for (i = 0; i < s->nb_streams; i++)
6178 if (rtp_hinting_needed(s->streams[i]))
6182 if (mov->mode == MODE_MOV || mov->mode == MODE_MP4)
6183 tmcd_track = nb_tracks;
6185 for (i = 0; i < s->nb_streams; i++) {
6187 AVStream *st= s->streams[i];
6188 MOVTrack *track= &mov->tracks[i];
6190 /* copy extradata if it exists */
6191 if (st->codecpar->extradata_size) {
6192 if (st->codecpar->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
6193 mov_create_dvd_sub_decoder_specific_info(track, st);
6194 else if (!TAG_IS_AVCI(track->tag) && st->codecpar->codec_id != AV_CODEC_ID_DNXHD) {
6195 track->vos_len = st->codecpar->extradata_size;
6196 track->vos_data = av_malloc(track->vos_len);
6197 if (!track->vos_data) {
6198 return AVERROR(ENOMEM);
6200 memcpy(track->vos_data, st->codecpar->extradata, track->vos_len);
6204 if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ||
6205 track->par->channel_layout != AV_CH_LAYOUT_MONO)
6208 for (j = 0; j < s->nb_streams; j++) {
6209 AVStream *stj= s->streams[j];
6210 MOVTrack *trackj= &mov->tracks[j];
6214 if (stj->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ||
6215 trackj->par->channel_layout != AV_CH_LAYOUT_MONO ||
6216 trackj->language != track->language ||
6217 trackj->tag != track->tag
6220 track->multichannel_as_mono++;
6224 if (!(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
6225 if ((ret = mov_write_identification(pb, s)) < 0)
6229 if (mov->reserved_moov_size){
6230 mov->reserved_header_pos = avio_tell(pb);
6231 if (mov->reserved_moov_size > 0)
6232 avio_skip(pb, mov->reserved_moov_size);
6235 if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
6236 /* If no fragmentation options have been set, set a default. */
6237 if (!(mov->flags & (FF_MOV_FLAG_FRAG_KEYFRAME |
6238 FF_MOV_FLAG_FRAG_CUSTOM |
6239 FF_MOV_FLAG_FRAG_EVERY_FRAME)) &&
6240 !mov->max_fragment_duration && !mov->max_fragment_size)
6241 mov->flags |= FF_MOV_FLAG_FRAG_KEYFRAME;
6243 if (mov->flags & FF_MOV_FLAG_FASTSTART)
6244 mov->reserved_header_pos = avio_tell(pb);
6245 mov_write_mdat_tag(pb, mov);
6248 ff_parse_creation_time_metadata(s, &mov->time, 1);
6250 mov->time += 0x7C25B080; // 1970 based -> 1904 based
6252 if (mov->chapter_track)
6253 if ((ret = mov_create_chapter_track(s, mov->chapter_track)) < 0)
6256 if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
6257 for (i = 0; i < s->nb_streams; i++) {
6258 if (rtp_hinting_needed(s->streams[i])) {
6259 if ((ret = ff_mov_init_hinting(s, hint_track, i)) < 0)
6266 if (mov->nb_meta_tmcd) {
6267 /* Initialize the tmcd tracks */
6268 for (i = 0; i < s->nb_streams; i++) {
6269 AVStream *st = s->streams[i];
6272 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
6275 t = av_dict_get(st->metadata, "timecode", NULL, 0);
6278 if (mov_check_timecode_track(s, &tc, i, t->value) < 0)
6280 if ((ret = mov_create_timecode_track(s, tmcd_track, i, tc)) < 0)
6289 if (mov->flags & FF_MOV_FLAG_ISML)
6290 mov_write_isml_manifest(pb, mov, s);
6292 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV &&
6293 !(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
6294 if ((ret = mov_write_moov_tag(pb, mov, s)) < 0)
6297 mov->moov_written = 1;
6298 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
6299 mov->reserved_header_pos = avio_tell(pb);
6305 static int get_moov_size(AVFormatContext *s)
6308 AVIOContext *moov_buf;
6309 MOVMuxContext *mov = s->priv_data;
6311 if ((ret = ffio_open_null_buf(&moov_buf)) < 0)
6313 if ((ret = mov_write_moov_tag(moov_buf, mov, s)) < 0)
6315 return ffio_close_null_buf(moov_buf);
6318 static int get_sidx_size(AVFormatContext *s)
6322 MOVMuxContext *mov = s->priv_data;
6324 if ((ret = ffio_open_null_buf(&buf)) < 0)
6326 mov_write_sidx_tags(buf, mov, -1, 0);
6327 return ffio_close_null_buf(buf);
6331 * This function gets the moov size if moved to the top of the file: the chunk
6332 * offset table can switch between stco (32-bit entries) to co64 (64-bit
6333 * entries) when the moov is moved to the beginning, so the size of the moov
6334 * would change. It also updates the chunk offset tables.
6336 static int compute_moov_size(AVFormatContext *s)
6338 int i, moov_size, moov_size2;
6339 MOVMuxContext *mov = s->priv_data;
6341 moov_size = get_moov_size(s);
6345 for (i = 0; i < mov->nb_streams; i++)
6346 mov->tracks[i].data_offset += moov_size;
6348 moov_size2 = get_moov_size(s);
6352 /* if the size changed, we just switched from stco to co64 and need to
6353 * update the offsets */
6354 if (moov_size2 != moov_size)
6355 for (i = 0; i < mov->nb_streams; i++)
6356 mov->tracks[i].data_offset += moov_size2 - moov_size;
6361 static int compute_sidx_size(AVFormatContext *s)
6364 MOVMuxContext *mov = s->priv_data;
6366 sidx_size = get_sidx_size(s);
6370 for (i = 0; i < mov->nb_streams; i++)
6371 mov->tracks[i].data_offset += sidx_size;
6376 static int shift_data(AVFormatContext *s)
6378 int ret = 0, moov_size;
6379 MOVMuxContext *mov = s->priv_data;
6380 int64_t pos, pos_end = avio_tell(s->pb);
6381 uint8_t *buf, *read_buf[2];
6382 int read_buf_id = 0;
6384 AVIOContext *read_pb;
6386 if (mov->flags & FF_MOV_FLAG_FRAGMENT)
6387 moov_size = compute_sidx_size(s);
6389 moov_size = compute_moov_size(s);
6393 buf = av_malloc(moov_size * 2);
6395 return AVERROR(ENOMEM);
6397 read_buf[1] = buf + moov_size;
6399 /* Shift the data: the AVIO context of the output can only be used for
6400 * writing, so we re-open the same output, but for reading. It also avoids
6401 * a read/seek/write/seek back and forth. */
6403 ret = s->io_open(s, &read_pb, s->url, AVIO_FLAG_READ, NULL);
6405 av_log(s, AV_LOG_ERROR, "Unable to re-open %s output file for "
6406 "the second pass (faststart)\n", s->url);
6410 /* mark the end of the shift to up to the last data we wrote, and get ready
6412 pos_end = avio_tell(s->pb);
6413 avio_seek(s->pb, mov->reserved_header_pos + moov_size, SEEK_SET);
6415 /* start reading at where the new moov will be placed */
6416 avio_seek(read_pb, mov->reserved_header_pos, SEEK_SET);
6417 pos = avio_tell(read_pb);
6419 #define READ_BLOCK do { \
6420 read_size[read_buf_id] = avio_read(read_pb, read_buf[read_buf_id], moov_size); \
6424 /* shift data by chunk of at most moov_size */
6429 n = read_size[read_buf_id];
6432 avio_write(s->pb, read_buf[read_buf_id], n);
6434 } while (pos < pos_end);
6435 ff_format_io_close(s, &read_pb);
6442 static int mov_write_trailer(AVFormatContext *s)
6444 MOVMuxContext *mov = s->priv_data;
6445 AVIOContext *pb = s->pb;
6450 if (mov->need_rewrite_extradata) {
6451 for (i = 0; i < s->nb_streams; i++) {
6452 MOVTrack *track = &mov->tracks[i];
6453 AVCodecParameters *par = track->par;
6455 track->vos_len = par->extradata_size;
6456 track->vos_data = av_malloc(track->vos_len);
6457 if (!track->vos_data)
6458 return AVERROR(ENOMEM);
6459 memcpy(track->vos_data, par->extradata, track->vos_len);
6461 mov->need_rewrite_extradata = 0;
6465 * Before actually writing the trailer, make sure that there are no
6466 * dangling subtitles, that need a terminating sample.
6468 for (i = 0; i < mov->nb_streams; i++) {
6469 MOVTrack *trk = &mov->tracks[i];
6470 if (trk->par->codec_id == AV_CODEC_ID_MOV_TEXT &&
6471 !trk->last_sample_is_subtitle_end) {
6472 mov_write_subtitle_end_packet(s, i, trk->track_duration);
6473 trk->last_sample_is_subtitle_end = 1;
6477 // If there were no chapters when the header was written, but there
6478 // are chapters now, write them in the trailer. This only works
6479 // when we are not doing fragments.
6480 if (!mov->chapter_track && !(mov->flags & FF_MOV_FLAG_FRAGMENT)) {
6481 if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters) {
6482 mov->chapter_track = mov->nb_streams++;
6483 if ((res = mov_create_chapter_track(s, mov->chapter_track)) < 0)
6488 if (!(mov->flags & FF_MOV_FLAG_FRAGMENT)) {
6489 moov_pos = avio_tell(pb);
6491 /* Write size of mdat tag */
6492 if (mov->mdat_size + 8 <= UINT32_MAX) {
6493 avio_seek(pb, mov->mdat_pos, SEEK_SET);
6494 avio_wb32(pb, mov->mdat_size + 8);
6496 /* overwrite 'wide' placeholder atom */
6497 avio_seek(pb, mov->mdat_pos - 8, SEEK_SET);
6498 /* special value: real atom size will be 64 bit value after
6501 ffio_wfourcc(pb, "mdat");
6502 avio_wb64(pb, mov->mdat_size + 16);
6504 avio_seek(pb, mov->reserved_moov_size > 0 ? mov->reserved_header_pos : moov_pos, SEEK_SET);
6506 if (mov->flags & FF_MOV_FLAG_FASTSTART) {
6507 av_log(s, AV_LOG_INFO, "Starting second pass: moving the moov atom to the beginning of the file\n");
6508 res = shift_data(s);
6511 avio_seek(pb, mov->reserved_header_pos, SEEK_SET);
6512 if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
6514 } else if (mov->reserved_moov_size > 0) {
6516 if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
6518 size = mov->reserved_moov_size - (avio_tell(pb) - mov->reserved_header_pos);
6520 av_log(s, AV_LOG_ERROR, "reserved_moov_size is too small, needed %"PRId64" additional\n", 8-size);
6521 return AVERROR(EINVAL);
6523 avio_wb32(pb, size);
6524 ffio_wfourcc(pb, "free");
6525 ffio_fill(pb, 0, size - 8);
6526 avio_seek(pb, moov_pos, SEEK_SET);
6528 if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
6533 mov_auto_flush_fragment(s, 1);
6534 for (i = 0; i < mov->nb_streams; i++)
6535 mov->tracks[i].data_offset = 0;
6536 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) {
6538 av_log(s, AV_LOG_INFO, "Starting second pass: inserting sidx atoms\n");
6539 res = shift_data(s);
6542 end = avio_tell(pb);
6543 avio_seek(pb, mov->reserved_header_pos, SEEK_SET);
6544 mov_write_sidx_tags(pb, mov, -1, 0);
6545 avio_seek(pb, end, SEEK_SET);
6546 avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_TRAILER);
6547 mov_write_mfra_tag(pb, mov);
6548 } else if (!(mov->flags & FF_MOV_FLAG_SKIP_TRAILER)) {
6549 avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_TRAILER);
6550 mov_write_mfra_tag(pb, mov);
6557 static int mov_check_bitstream(struct AVFormatContext *s, const AVPacket *pkt)
6560 AVStream *st = s->streams[pkt->stream_index];
6562 if (st->codecpar->codec_id == AV_CODEC_ID_AAC) {
6563 if (pkt->size > 2 && (AV_RB16(pkt->data) & 0xfff0) == 0xfff0)
6564 ret = ff_stream_add_bitstream_filter(st, "aac_adtstoasc", NULL);
6565 } else if (st->codecpar->codec_id == AV_CODEC_ID_VP9) {
6566 ret = ff_stream_add_bitstream_filter(st, "vp9_superframe", NULL);
6572 static const AVCodecTag codec_3gp_tags[] = {
6573 { AV_CODEC_ID_H263, MKTAG('s','2','6','3') },
6574 { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
6575 { AV_CODEC_ID_MPEG4, MKTAG('m','p','4','v') },
6576 { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
6577 { AV_CODEC_ID_AMR_NB, MKTAG('s','a','m','r') },
6578 { AV_CODEC_ID_AMR_WB, MKTAG('s','a','w','b') },
6579 { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
6580 { AV_CODEC_ID_NONE, 0 },
6583 const AVCodecTag codec_mp4_tags[] = {
6584 { AV_CODEC_ID_MPEG4 , MKTAG('m', 'p', '4', 'v') },
6585 { AV_CODEC_ID_H264 , MKTAG('a', 'v', 'c', '1') },
6586 { AV_CODEC_ID_H264 , MKTAG('a', 'v', 'c', '3') },
6587 { AV_CODEC_ID_HEVC , MKTAG('h', 'e', 'v', '1') },
6588 { AV_CODEC_ID_HEVC , MKTAG('h', 'v', 'c', '1') },
6589 { AV_CODEC_ID_MPEG2VIDEO , MKTAG('m', 'p', '4', 'v') },
6590 { AV_CODEC_ID_MPEG1VIDEO , MKTAG('m', 'p', '4', 'v') },
6591 { AV_CODEC_ID_MJPEG , MKTAG('m', 'p', '4', 'v') },
6592 { AV_CODEC_ID_PNG , MKTAG('m', 'p', '4', 'v') },
6593 { AV_CODEC_ID_JPEG2000 , MKTAG('m', 'p', '4', 'v') },
6594 { AV_CODEC_ID_VC1 , MKTAG('v', 'c', '-', '1') },
6595 { AV_CODEC_ID_DIRAC , MKTAG('d', 'r', 'a', 'c') },
6596 { AV_CODEC_ID_TSCC2 , MKTAG('m', 'p', '4', 'v') },
6597 { AV_CODEC_ID_VP9 , MKTAG('v', 'p', '0', '9') },
6598 { AV_CODEC_ID_AAC , MKTAG('m', 'p', '4', 'a') },
6599 { AV_CODEC_ID_MP4ALS , MKTAG('m', 'p', '4', 'a') },
6600 { AV_CODEC_ID_MP3 , MKTAG('m', 'p', '4', 'a') },
6601 { AV_CODEC_ID_MP2 , MKTAG('m', 'p', '4', 'a') },
6602 { AV_CODEC_ID_AC3 , MKTAG('a', 'c', '-', '3') },
6603 { AV_CODEC_ID_EAC3 , MKTAG('e', 'c', '-', '3') },
6604 { AV_CODEC_ID_DTS , MKTAG('m', 'p', '4', 'a') },
6605 { AV_CODEC_ID_FLAC , MKTAG('f', 'L', 'a', 'C') },
6606 { AV_CODEC_ID_OPUS , MKTAG('O', 'p', 'u', 's') },
6607 { AV_CODEC_ID_VORBIS , MKTAG('m', 'p', '4', 'a') },
6608 { AV_CODEC_ID_QCELP , MKTAG('m', 'p', '4', 'a') },
6609 { AV_CODEC_ID_EVRC , MKTAG('m', 'p', '4', 'a') },
6610 { AV_CODEC_ID_DVD_SUBTITLE, MKTAG('m', 'p', '4', 's') },
6611 { AV_CODEC_ID_MOV_TEXT , MKTAG('t', 'x', '3', 'g') },
6612 { AV_CODEC_ID_NONE , 0 },
6615 const AVCodecTag codec_ism_tags[] = {
6616 { AV_CODEC_ID_WMAPRO , MKTAG('w', 'm', 'a', ' ') },
6617 { AV_CODEC_ID_NONE , 0 },
6620 static const AVCodecTag codec_ipod_tags[] = {
6621 { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
6622 { AV_CODEC_ID_MPEG4, MKTAG('m','p','4','v') },
6623 { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
6624 { AV_CODEC_ID_ALAC, MKTAG('a','l','a','c') },
6625 { AV_CODEC_ID_AC3, MKTAG('a','c','-','3') },
6626 { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
6627 { AV_CODEC_ID_MOV_TEXT, MKTAG('t','e','x','t') },
6628 { AV_CODEC_ID_NONE, 0 },
6631 static const AVCodecTag codec_f4v_tags[] = {
6632 { AV_CODEC_ID_MP3, MKTAG('.','m','p','3') },
6633 { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
6634 { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
6635 { AV_CODEC_ID_VP6A, MKTAG('V','P','6','A') },
6636 { AV_CODEC_ID_VP6F, MKTAG('V','P','6','F') },
6637 { AV_CODEC_ID_NONE, 0 },
6640 #if CONFIG_MOV_MUXER
6642 AVOutputFormat ff_mov_muxer = {
6644 .long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
6645 .extensions = "mov",
6646 .priv_data_size = sizeof(MOVMuxContext),
6647 .audio_codec = AV_CODEC_ID_AAC,
6648 .video_codec = CONFIG_LIBX264_ENCODER ?
6649 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
6651 .write_header = mov_write_header,
6652 .write_packet = mov_write_packet,
6653 .write_trailer = mov_write_trailer,
6655 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6656 .codec_tag = (const AVCodecTag* const []){
6657 ff_codec_movvideo_tags, ff_codec_movaudio_tags, 0
6659 .check_bitstream = mov_check_bitstream,
6660 .priv_class = &mov_muxer_class,
6663 #if CONFIG_TGP_MUXER
6665 AVOutputFormat ff_tgp_muxer = {
6667 .long_name = NULL_IF_CONFIG_SMALL("3GP (3GPP file format)"),
6668 .extensions = "3gp",
6669 .priv_data_size = sizeof(MOVMuxContext),
6670 .audio_codec = AV_CODEC_ID_AMR_NB,
6671 .video_codec = AV_CODEC_ID_H263,
6673 .write_header = mov_write_header,
6674 .write_packet = mov_write_packet,
6675 .write_trailer = mov_write_trailer,
6677 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6678 .codec_tag = (const AVCodecTag* const []){ codec_3gp_tags, 0 },
6679 .check_bitstream = mov_check_bitstream,
6680 .priv_class = &tgp_muxer_class,
6683 #if CONFIG_MP4_MUXER
6685 AVOutputFormat ff_mp4_muxer = {
6687 .long_name = NULL_IF_CONFIG_SMALL("MP4 (MPEG-4 Part 14)"),
6688 .mime_type = "video/mp4",
6689 .extensions = "mp4",
6690 .priv_data_size = sizeof(MOVMuxContext),
6691 .audio_codec = AV_CODEC_ID_AAC,
6692 .video_codec = CONFIG_LIBX264_ENCODER ?
6693 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
6695 .write_header = mov_write_header,
6696 .write_packet = mov_write_packet,
6697 .write_trailer = mov_write_trailer,
6699 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6700 .codec_tag = (const AVCodecTag* const []){ codec_mp4_tags, 0 },
6701 .check_bitstream = mov_check_bitstream,
6702 .priv_class = &mp4_muxer_class,
6705 #if CONFIG_PSP_MUXER
6707 AVOutputFormat ff_psp_muxer = {
6709 .long_name = NULL_IF_CONFIG_SMALL("PSP MP4 (MPEG-4 Part 14)"),
6710 .extensions = "mp4,psp",
6711 .priv_data_size = sizeof(MOVMuxContext),
6712 .audio_codec = AV_CODEC_ID_AAC,
6713 .video_codec = CONFIG_LIBX264_ENCODER ?
6714 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
6716 .write_header = mov_write_header,
6717 .write_packet = mov_write_packet,
6718 .write_trailer = mov_write_trailer,
6720 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6721 .codec_tag = (const AVCodecTag* const []){ codec_mp4_tags, 0 },
6722 .check_bitstream = mov_check_bitstream,
6723 .priv_class = &psp_muxer_class,
6726 #if CONFIG_TG2_MUXER
6728 AVOutputFormat ff_tg2_muxer = {
6730 .long_name = NULL_IF_CONFIG_SMALL("3GP2 (3GPP2 file format)"),
6731 .extensions = "3g2",
6732 .priv_data_size = sizeof(MOVMuxContext),
6733 .audio_codec = AV_CODEC_ID_AMR_NB,
6734 .video_codec = AV_CODEC_ID_H263,
6736 .write_header = mov_write_header,
6737 .write_packet = mov_write_packet,
6738 .write_trailer = mov_write_trailer,
6740 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6741 .codec_tag = (const AVCodecTag* const []){ codec_3gp_tags, 0 },
6742 .check_bitstream = mov_check_bitstream,
6743 .priv_class = &tg2_muxer_class,
6746 #if CONFIG_IPOD_MUXER
6748 AVOutputFormat ff_ipod_muxer = {
6750 .long_name = NULL_IF_CONFIG_SMALL("iPod H.264 MP4 (MPEG-4 Part 14)"),
6751 .mime_type = "video/mp4",
6752 .extensions = "m4v,m4a,m4b",
6753 .priv_data_size = sizeof(MOVMuxContext),
6754 .audio_codec = AV_CODEC_ID_AAC,
6755 .video_codec = AV_CODEC_ID_H264,
6757 .write_header = mov_write_header,
6758 .write_packet = mov_write_packet,
6759 .write_trailer = mov_write_trailer,
6761 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6762 .codec_tag = (const AVCodecTag* const []){ codec_ipod_tags, 0 },
6763 .check_bitstream = mov_check_bitstream,
6764 .priv_class = &ipod_muxer_class,
6767 #if CONFIG_ISMV_MUXER
6769 AVOutputFormat ff_ismv_muxer = {
6771 .long_name = NULL_IF_CONFIG_SMALL("ISMV/ISMA (Smooth Streaming)"),
6772 .mime_type = "video/mp4",
6773 .extensions = "ismv,isma",
6774 .priv_data_size = sizeof(MOVMuxContext),
6775 .audio_codec = AV_CODEC_ID_AAC,
6776 .video_codec = AV_CODEC_ID_H264,
6778 .write_header = mov_write_header,
6779 .write_packet = mov_write_packet,
6780 .write_trailer = mov_write_trailer,
6782 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6783 .codec_tag = (const AVCodecTag* const []){
6784 codec_mp4_tags, codec_ism_tags, 0 },
6785 .check_bitstream = mov_check_bitstream,
6786 .priv_class = &ismv_muxer_class,
6789 #if CONFIG_F4V_MUXER
6791 AVOutputFormat ff_f4v_muxer = {
6793 .long_name = NULL_IF_CONFIG_SMALL("F4V Adobe Flash Video"),
6794 .mime_type = "application/f4v",
6795 .extensions = "f4v",
6796 .priv_data_size = sizeof(MOVMuxContext),
6797 .audio_codec = AV_CODEC_ID_AAC,
6798 .video_codec = AV_CODEC_ID_H264,
6800 .write_header = mov_write_header,
6801 .write_packet = mov_write_packet,
6802 .write_trailer = mov_write_trailer,
6804 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH,
6805 .codec_tag = (const AVCodecTag* const []){ codec_f4v_tags, 0 },
6806 .check_bitstream = mov_check_bitstream,
6807 .priv_class = &f4v_muxer_class,