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.h"
35 #include "libavcodec/dnxhddata.h"
36 #include "libavcodec/flac.h"
37 #include "libavcodec/get_bits.h"
38 #include "libavcodec/put_bits.h"
39 #include "libavcodec/vc1_common.h"
40 #include "libavcodec/raw.h"
42 #include "libavutil/avstring.h"
43 #include "libavutil/intfloat.h"
44 #include "libavutil/mathematics.h"
45 #include "libavutil/libm.h"
46 #include "libavutil/opt.h"
47 #include "libavutil/dict.h"
48 #include "libavutil/pixdesc.h"
49 #include "libavutil/stereo3d.h"
50 #include "libavutil/timecode.h"
51 #include "libavutil/color_utils.h"
57 static const AVOption options[] = {
58 { "movflags", "MOV muxer flags", offsetof(MOVMuxContext, flags), AV_OPT_TYPE_FLAGS, {.i64 = 0}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
59 { "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" },
60 { "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 },
61 { "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" },
62 { "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" },
63 { "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" },
64 { "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" },
65 { "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" },
66 { "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" },
67 { "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" },
68 { "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" },
69 { "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" },
70 { "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" },
71 { "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" },
72 { "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" },
73 { "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" },
74 { "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" },
75 { "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" },
76 { "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" },
77 { "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" },
78 FF_RTP_FLAG_OPTS(MOVMuxContext, rtp_flags),
79 { "skip_iods", "Skip writing iods atom.", offsetof(MOVMuxContext, iods_skip), AV_OPT_TYPE_BOOL, {.i64 = 1}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM},
80 { "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},
81 { "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},
82 { "frag_duration", "Maximum fragment duration", offsetof(MOVMuxContext, max_fragment_duration), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
83 { "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},
84 { "frag_size", "Maximum fragment size", offsetof(MOVMuxContext, max_fragment_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
85 { "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},
86 { "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},
87 { "brand", "Override major brand", offsetof(MOVMuxContext, major_brand), AV_OPT_TYPE_STRING, {.str = NULL}, .flags = AV_OPT_FLAG_ENCODING_PARAM },
88 { "use_editlist", "use edit list", offsetof(MOVMuxContext, use_editlist), AV_OPT_TYPE_BOOL, {.i64 = -1}, -1, 1, AV_OPT_FLAG_ENCODING_PARAM},
89 { "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},
90 { "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},
91 { "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 },
92 { "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 },
93 { "encryption_key", "The media encryption key (hex)", offsetof(MOVMuxContext, encryption_key), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_ENCODING_PARAM },
94 { "encryption_kid", "The media encryption key identifier (hex)", offsetof(MOVMuxContext, encryption_kid), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_ENCODING_PARAM },
95 { "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},
96 { "write_tmcd", "force or disable writing tmcd", offsetof(MOVMuxContext, write_tmcd), AV_OPT_TYPE_BOOL, {.i64 = -1}, -1, 1, AV_OPT_FLAG_ENCODING_PARAM},
100 #define MOV_CLASS(flavor)\
101 static const AVClass flavor ## _muxer_class = {\
102 .class_name = #flavor " muxer",\
103 .item_name = av_default_item_name,\
105 .version = LIBAVUTIL_VERSION_INT,\
108 static int get_moov_size(AVFormatContext *s);
110 static int utf8len(const uint8_t *b)
115 GET_UTF8(val, *b++, return -1;)
121 //FIXME support 64 bit variant with wide placeholders
122 static int64_t update_size(AVIOContext *pb, int64_t pos)
124 int64_t curpos = avio_tell(pb);
125 avio_seek(pb, pos, SEEK_SET);
126 avio_wb32(pb, curpos - pos); /* rewrite size */
127 avio_seek(pb, curpos, SEEK_SET);
132 static int co64_required(const MOVTrack *track)
134 if (track->entry > 0 && track->cluster[track->entry - 1].pos + track->data_offset > UINT32_MAX)
139 /* Chunk offset atom */
140 static int mov_write_stco_tag(AVIOContext *pb, MOVTrack *track)
143 int mode64 = co64_required(track); // use 32 bit size variant if possible
144 int64_t pos = avio_tell(pb);
145 avio_wb32(pb, 0); /* size */
147 ffio_wfourcc(pb, "co64");
149 ffio_wfourcc(pb, "stco");
150 avio_wb32(pb, 0); /* version & flags */
151 avio_wb32(pb, track->chunkCount); /* entry count */
152 for (i = 0; i < track->entry; i++) {
153 if (!track->cluster[i].chunkNum)
156 avio_wb64(pb, track->cluster[i].pos + track->data_offset);
158 avio_wb32(pb, track->cluster[i].pos + track->data_offset);
160 return update_size(pb, pos);
163 /* Sample size atom */
164 static int mov_write_stsz_tag(AVIOContext *pb, MOVTrack *track)
167 int i, j, entries = 0, tst = -1, oldtst = -1;
169 int64_t pos = avio_tell(pb);
170 avio_wb32(pb, 0); /* size */
171 ffio_wfourcc(pb, "stsz");
172 avio_wb32(pb, 0); /* version & flags */
174 for (i = 0; i < track->entry; i++) {
175 tst = track->cluster[i].size / track->cluster[i].entries;
176 if (oldtst != -1 && tst != oldtst)
179 entries += track->cluster[i].entries;
181 if (equalChunks && track->entry) {
182 int sSize = track->entry ? track->cluster[0].size / track->cluster[0].entries : 0;
183 sSize = FFMAX(1, sSize); // adpcm mono case could make sSize == 0
184 avio_wb32(pb, sSize); // sample size
185 avio_wb32(pb, entries); // sample count
187 avio_wb32(pb, 0); // sample size
188 avio_wb32(pb, entries); // sample count
189 for (i = 0; i < track->entry; i++) {
190 for (j = 0; j < track->cluster[i].entries; j++) {
191 avio_wb32(pb, track->cluster[i].size /
192 track->cluster[i].entries);
196 return update_size(pb, pos);
199 /* Sample to chunk atom */
200 static int mov_write_stsc_tag(AVIOContext *pb, MOVTrack *track)
202 int index = 0, oldval = -1, i;
203 int64_t entryPos, curpos;
205 int64_t pos = avio_tell(pb);
206 avio_wb32(pb, 0); /* size */
207 ffio_wfourcc(pb, "stsc");
208 avio_wb32(pb, 0); // version & flags
209 entryPos = avio_tell(pb);
210 avio_wb32(pb, track->chunkCount); // entry count
211 for (i = 0; i < track->entry; i++) {
212 if (oldval != track->cluster[i].samples_in_chunk && track->cluster[i].chunkNum) {
213 avio_wb32(pb, track->cluster[i].chunkNum); // first chunk
214 avio_wb32(pb, track->cluster[i].samples_in_chunk); // samples per chunk
215 avio_wb32(pb, 0x1); // sample description index
216 oldval = track->cluster[i].samples_in_chunk;
220 curpos = avio_tell(pb);
221 avio_seek(pb, entryPos, SEEK_SET);
222 avio_wb32(pb, index); // rewrite size
223 avio_seek(pb, curpos, SEEK_SET);
225 return update_size(pb, pos);
228 /* Sync sample atom */
229 static int mov_write_stss_tag(AVIOContext *pb, MOVTrack *track, uint32_t flag)
231 int64_t curpos, entryPos;
233 int64_t pos = avio_tell(pb);
234 avio_wb32(pb, 0); // size
235 ffio_wfourcc(pb, flag == MOV_SYNC_SAMPLE ? "stss" : "stps");
236 avio_wb32(pb, 0); // version & flags
237 entryPos = avio_tell(pb);
238 avio_wb32(pb, track->entry); // entry count
239 for (i = 0; i < track->entry; i++) {
240 if (track->cluster[i].flags & flag) {
241 avio_wb32(pb, i + 1);
245 curpos = avio_tell(pb);
246 avio_seek(pb, entryPos, SEEK_SET);
247 avio_wb32(pb, index); // rewrite size
248 avio_seek(pb, curpos, SEEK_SET);
249 return update_size(pb, pos);
252 static int mov_write_amr_tag(AVIOContext *pb, MOVTrack *track)
254 avio_wb32(pb, 0x11); /* size */
255 if (track->mode == MODE_MOV) ffio_wfourcc(pb, "samr");
256 else ffio_wfourcc(pb, "damr");
257 ffio_wfourcc(pb, "FFMP");
258 avio_w8(pb, 0); /* decoder version */
260 avio_wb16(pb, 0x81FF); /* Mode set (all modes for AMR_NB) */
261 avio_w8(pb, 0x00); /* Mode change period (no restriction) */
262 avio_w8(pb, 0x01); /* Frames per sample */
266 static int mov_write_ac3_tag(AVIOContext *pb, MOVTrack *track)
271 int fscod, bsid, bsmod, acmod, lfeon, frmsizecod;
273 if (track->vos_len < 7)
277 ffio_wfourcc(pb, "dac3");
279 init_get_bits(&gbc, track->vos_data + 4, (track->vos_len - 4) * 8);
280 fscod = get_bits(&gbc, 2);
281 frmsizecod = get_bits(&gbc, 6);
282 bsid = get_bits(&gbc, 5);
283 bsmod = get_bits(&gbc, 3);
284 acmod = get_bits(&gbc, 3);
286 skip_bits(&gbc, 2); // dsurmod
288 if ((acmod & 1) && acmod != 1)
289 skip_bits(&gbc, 2); // cmixlev
291 skip_bits(&gbc, 2); // surmixlev
293 lfeon = get_bits1(&gbc);
295 init_put_bits(&pbc, buf, sizeof(buf));
296 put_bits(&pbc, 2, fscod);
297 put_bits(&pbc, 5, bsid);
298 put_bits(&pbc, 3, bsmod);
299 put_bits(&pbc, 3, acmod);
300 put_bits(&pbc, 1, lfeon);
301 put_bits(&pbc, 5, frmsizecod >> 1); // bit_rate_code
302 put_bits(&pbc, 5, 0); // reserved
304 flush_put_bits(&pbc);
305 avio_write(pb, buf, sizeof(buf));
315 /* Layout of the EC3SpecificBox */
316 /* maximum bitrate */
318 /* number of independent substreams */
321 /* sample rate code (see ff_ac3_sample_rate_tab) 2 bits */
323 /* bit stream identification 5 bits */
325 /* one bit reserved */
326 /* audio service mixing (not supported yet) 1 bit */
327 /* bit stream mode 3 bits */
329 /* audio coding mode 3 bits */
331 /* sub woofer on 1 bit */
333 /* 3 bits reserved */
334 /* number of dependent substreams associated with this substream 4 bits */
336 /* channel locations of the dependent substream(s), if any, 9 bits */
338 /* if there is no dependent substream, then one bit reserved instead */
339 } substream[1]; /* TODO: support 8 independent substreams */
342 #if CONFIG_AC3_PARSER
343 static int handle_eac3(MOVMuxContext *mov, AVPacket *pkt, MOVTrack *track)
346 AC3HeaderInfo tmp, *hdr = &tmp;
347 struct eac3_info *info;
350 if (!track->eac3_priv && !(track->eac3_priv = av_mallocz(sizeof(*info))))
351 return AVERROR(ENOMEM);
352 info = track->eac3_priv;
354 init_get_bits(&gbc, pkt->data, pkt->size * 8);
355 if (avpriv_ac3_parse_header(&gbc, &hdr) < 0) {
356 /* drop the packets until we see a good one */
358 av_log(mov, AV_LOG_WARNING, "Dropping invalid packet from start of the stream\n");
361 return AVERROR_INVALIDDATA;
364 info->data_rate = FFMAX(info->data_rate, hdr->bit_rate / 1000);
365 num_blocks = hdr->num_blocks;
367 if (!info->ec3_done) {
368 /* AC-3 substream must be the first one */
369 if (hdr->bitstream_id <= 10 && hdr->substreamid != 0)
370 return AVERROR(EINVAL);
372 /* this should always be the case, given that our AC-3 parser
373 * concatenates dependent frames to their independent parent */
374 if (hdr->frame_type == EAC3_FRAME_TYPE_INDEPENDENT) {
375 /* substream ids must be incremental */
376 if (hdr->substreamid > info->num_ind_sub + 1)
377 return AVERROR(EINVAL);
379 if (hdr->substreamid == info->num_ind_sub + 1) {
380 //info->num_ind_sub++;
381 avpriv_request_sample(track->par, "Multiple independent substreams");
382 return AVERROR_PATCHWELCOME;
383 } else if (hdr->substreamid < info->num_ind_sub ||
384 hdr->substreamid == 0 && info->substream[0].bsid) {
390 /* fill the info needed for the "dec3" atom */
391 info->substream[hdr->substreamid].fscod = hdr->sr_code;
392 info->substream[hdr->substreamid].bsid = hdr->bitstream_id;
393 info->substream[hdr->substreamid].bsmod = hdr->bitstream_mode;
394 info->substream[hdr->substreamid].acmod = hdr->channel_mode;
395 info->substream[hdr->substreamid].lfeon = hdr->lfe_on;
397 /* Parse dependent substream(s), if any */
398 if (pkt->size != hdr->frame_size) {
399 int cumul_size = hdr->frame_size;
400 int parent = hdr->substreamid;
402 while (cumul_size != pkt->size) {
404 init_get_bits(&gbc, pkt->data + cumul_size, (pkt->size - cumul_size) * 8);
405 if (avpriv_ac3_parse_header(&gbc, &hdr) < 0)
406 return AVERROR_INVALIDDATA;
407 if (hdr->frame_type != EAC3_FRAME_TYPE_DEPENDENT)
408 return AVERROR(EINVAL);
409 cumul_size += hdr->frame_size;
410 info->substream[parent].num_dep_sub++;
412 /* header is parsed up to lfeon, but custom channel map may be needed */
415 /* skip volume control params */
416 for (i = 0; i < (hdr->channel_mode ? 1 : 2); i++) {
417 skip_bits(&gbc, 5); // skip dialog normalization
418 if (get_bits1(&gbc)) {
419 skip_bits(&gbc, 8); // skip compression gain word
422 /* get the dependent stream channel map, if exists */
424 info->substream[parent].chan_loc |= (get_bits(&gbc, 16) >> 5) & 0x1f;
426 info->substream[parent].chan_loc |= hdr->channel_mode;
432 if (!info->num_blocks && num_blocks == 6)
434 else if (info->num_blocks + num_blocks > 6)
435 return AVERROR_INVALIDDATA;
437 if (!info->num_blocks) {
439 if ((ret = av_copy_packet(&info->pkt, pkt)) < 0)
441 info->num_blocks = num_blocks;
445 if ((ret = av_grow_packet(&info->pkt, pkt->size)) < 0)
447 memcpy(info->pkt.data + info->pkt.size - pkt->size, pkt->data, pkt->size);
448 info->num_blocks += num_blocks;
449 info->pkt.duration += pkt->duration;
450 if ((ret = av_copy_packet_side_data(&info->pkt, pkt)) < 0)
452 if (info->num_blocks != 6)
454 av_packet_unref(pkt);
455 if ((ret = av_copy_packet(pkt, &info->pkt)) < 0)
457 av_packet_unref(&info->pkt);
458 info->num_blocks = 0;
465 static int mov_write_eac3_tag(AVIOContext *pb, MOVTrack *track)
469 struct eac3_info *info;
472 if (!track->eac3_priv)
473 return AVERROR(EINVAL);
475 info = track->eac3_priv;
476 size = 2 + 4 * (info->num_ind_sub + 1);
477 buf = av_malloc(size);
479 size = AVERROR(ENOMEM);
483 init_put_bits(&pbc, buf, size);
484 put_bits(&pbc, 13, info->data_rate);
485 put_bits(&pbc, 3, info->num_ind_sub);
486 for (i = 0; i <= info->num_ind_sub; i++) {
487 put_bits(&pbc, 2, info->substream[i].fscod);
488 put_bits(&pbc, 5, info->substream[i].bsid);
489 put_bits(&pbc, 1, 0); /* reserved */
490 put_bits(&pbc, 1, 0); /* asvc */
491 put_bits(&pbc, 3, info->substream[i].bsmod);
492 put_bits(&pbc, 3, info->substream[i].acmod);
493 put_bits(&pbc, 1, info->substream[i].lfeon);
494 put_bits(&pbc, 5, 0); /* reserved */
495 put_bits(&pbc, 4, info->substream[i].num_dep_sub);
496 if (!info->substream[i].num_dep_sub) {
497 put_bits(&pbc, 1, 0); /* reserved */
500 put_bits(&pbc, 9, info->substream[i].chan_loc);
503 flush_put_bits(&pbc);
505 avio_wb32(pb, size + 8);
506 ffio_wfourcc(pb, "dec3");
507 avio_write(pb, buf, size);
512 av_packet_unref(&info->pkt);
513 av_freep(&track->eac3_priv);
519 * This function writes extradata "as is".
520 * Extradata must be formatted like a valid atom (with size and tag).
522 static int mov_write_extradata_tag(AVIOContext *pb, MOVTrack *track)
524 avio_write(pb, track->par->extradata, track->par->extradata_size);
525 return track->par->extradata_size;
528 static int mov_write_enda_tag(AVIOContext *pb)
531 ffio_wfourcc(pb, "enda");
532 avio_wb16(pb, 1); /* little endian */
536 static int mov_write_enda_tag_be(AVIOContext *pb)
539 ffio_wfourcc(pb, "enda");
540 avio_wb16(pb, 0); /* big endian */
544 static void put_descr(AVIOContext *pb, int tag, unsigned int size)
549 avio_w8(pb, (size >> (7 * i)) | 0x80);
550 avio_w8(pb, size & 0x7F);
553 static unsigned compute_avg_bitrate(MOVTrack *track)
557 if (!track->track_duration)
559 for (i = 0; i < track->entry; i++)
560 size += track->cluster[i].size;
561 return size * 8 * track->timescale / track->track_duration;
564 static int mov_write_esds_tag(AVIOContext *pb, MOVTrack *track) // Basic
566 AVCPBProperties *props;
567 int64_t pos = avio_tell(pb);
568 int decoder_specific_info_len = track->vos_len ? 5 + track->vos_len : 0;
569 unsigned avg_bitrate;
571 avio_wb32(pb, 0); // size
572 ffio_wfourcc(pb, "esds");
573 avio_wb32(pb, 0); // Version
576 put_descr(pb, 0x03, 3 + 5+13 + decoder_specific_info_len + 5+1);
577 avio_wb16(pb, track->track_id);
578 avio_w8(pb, 0x00); // flags (= no flags)
580 // DecoderConfig descriptor
581 put_descr(pb, 0x04, 13 + decoder_specific_info_len);
583 // Object type indication
584 if ((track->par->codec_id == AV_CODEC_ID_MP2 ||
585 track->par->codec_id == AV_CODEC_ID_MP3) &&
586 track->par->sample_rate > 24000)
587 avio_w8(pb, 0x6B); // 11172-3
589 avio_w8(pb, ff_codec_get_tag(ff_mp4_obj_type, track->par->codec_id));
591 // the following fields is made of 6 bits to identify the streamtype (4 for video, 5 for audio)
592 // plus 1 bit to indicate upstream and 1 bit set to 1 (reserved)
593 if (track->par->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
594 avio_w8(pb, (0x38 << 2) | 1); // flags (= NeroSubpicStream)
595 else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
596 avio_w8(pb, 0x15); // flags (= Audiostream)
598 avio_w8(pb, 0x11); // flags (= Visualstream)
600 props = (AVCPBProperties*)av_stream_get_side_data(track->st, AV_PKT_DATA_CPB_PROPERTIES,
603 avio_wb24(pb, props ? props->buffer_size / 8 : 0); // Buffersize DB
605 avg_bitrate = compute_avg_bitrate(track);
606 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)
607 avio_wb32(pb, avg_bitrate);
609 if (track->vos_len) {
610 // DecoderSpecific info descriptor
611 put_descr(pb, 0x05, track->vos_len);
612 avio_write(pb, track->vos_data, track->vos_len);
616 put_descr(pb, 0x06, 1);
618 return update_size(pb, pos);
621 static int mov_pcm_le_gt16(enum AVCodecID codec_id)
623 return codec_id == AV_CODEC_ID_PCM_S24LE ||
624 codec_id == AV_CODEC_ID_PCM_S32LE ||
625 codec_id == AV_CODEC_ID_PCM_F32LE ||
626 codec_id == AV_CODEC_ID_PCM_F64LE;
629 static int mov_pcm_be_gt16(enum AVCodecID codec_id)
631 return codec_id == AV_CODEC_ID_PCM_S24BE ||
632 codec_id == AV_CODEC_ID_PCM_S32BE ||
633 codec_id == AV_CODEC_ID_PCM_F32BE ||
634 codec_id == AV_CODEC_ID_PCM_F64BE;
637 static int mov_write_ms_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
640 int64_t pos = avio_tell(pb);
642 avio_wl32(pb, track->tag); // store it byteswapped
643 track->par->codec_tag = av_bswap16(track->tag >> 16);
644 if ((ret = ff_put_wav_header(s, pb, track->par, 0)) < 0)
646 return update_size(pb, pos);
649 static int mov_write_wfex_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
652 int64_t pos = avio_tell(pb);
654 ffio_wfourcc(pb, "wfex");
655 if ((ret = ff_put_wav_header(s, pb, track->st->codecpar, FF_PUT_WAV_HEADER_FORCE_WAVEFORMATEX)) < 0)
657 return update_size(pb, pos);
660 static int mov_write_dfla_tag(AVIOContext *pb, MOVTrack *track)
662 int64_t pos = avio_tell(pb);
664 ffio_wfourcc(pb, "dfLa");
665 avio_w8(pb, 0); /* version */
666 avio_wb24(pb, 0); /* flags */
668 /* Expect the encoder to pass a METADATA_BLOCK_TYPE_STREAMINFO. */
669 if (track->par->extradata_size != FLAC_STREAMINFO_SIZE)
670 return AVERROR_INVALIDDATA;
672 /* TODO: Write other METADATA_BLOCK_TYPEs if the encoder makes them available. */
673 avio_w8(pb, 1 << 7 | FLAC_METADATA_TYPE_STREAMINFO); /* LastMetadataBlockFlag << 7 | BlockType */
674 avio_wb24(pb, track->par->extradata_size); /* Length */
675 avio_write(pb, track->par->extradata, track->par->extradata_size); /* BlockData[Length] */
677 return update_size(pb, pos);
680 static int mov_write_dops_tag(AVIOContext *pb, MOVTrack *track)
682 int64_t pos = avio_tell(pb);
684 ffio_wfourcc(pb, "dOps");
685 avio_w8(pb, 0); /* Version */
686 if (track->par->extradata_size < 19) {
687 av_log(pb, AV_LOG_ERROR, "invalid extradata size\n");
688 return AVERROR_INVALIDDATA;
690 /* extradata contains an Ogg OpusHead, other than byte-ordering and
691 OpusHead's preceeding magic/version, OpusSpecificBox is currently
693 avio_w8(pb, AV_RB8(track->par->extradata + 9)); /* OuputChannelCount */
694 avio_wb16(pb, AV_RL16(track->par->extradata + 10)); /* PreSkip */
695 avio_wb32(pb, AV_RL32(track->par->extradata + 12)); /* InputSampleRate */
696 avio_wb16(pb, AV_RL16(track->par->extradata + 16)); /* OutputGain */
697 /* Write the rest of the header out without byte-swapping. */
698 avio_write(pb, track->par->extradata + 18, track->par->extradata_size - 18);
700 return update_size(pb, pos);
703 static int mov_write_chan_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
705 uint32_t layout_tag, bitmap;
706 int64_t pos = avio_tell(pb);
708 layout_tag = ff_mov_get_channel_layout_tag(track->par->codec_id,
709 track->par->channel_layout,
712 av_log(s, AV_LOG_WARNING, "not writing 'chan' tag due to "
713 "lack of channel information\n");
717 if (track->multichannel_as_mono)
720 avio_wb32(pb, 0); // Size
721 ffio_wfourcc(pb, "chan"); // Type
722 avio_w8(pb, 0); // Version
723 avio_wb24(pb, 0); // Flags
724 avio_wb32(pb, layout_tag); // mChannelLayoutTag
725 avio_wb32(pb, bitmap); // mChannelBitmap
726 avio_wb32(pb, 0); // mNumberChannelDescriptions
728 return update_size(pb, pos);
731 static int mov_write_wave_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
733 int64_t pos = avio_tell(pb);
735 avio_wb32(pb, 0); /* size */
736 ffio_wfourcc(pb, "wave");
738 if (track->par->codec_id != AV_CODEC_ID_QDM2) {
739 avio_wb32(pb, 12); /* size */
740 ffio_wfourcc(pb, "frma");
741 avio_wl32(pb, track->tag);
744 if (track->par->codec_id == AV_CODEC_ID_AAC) {
745 /* useless atom needed by mplayer, ipod, not needed by quicktime */
746 avio_wb32(pb, 12); /* size */
747 ffio_wfourcc(pb, "mp4a");
749 mov_write_esds_tag(pb, track);
750 } else if (mov_pcm_le_gt16(track->par->codec_id)) {
751 mov_write_enda_tag(pb);
752 } else if (mov_pcm_be_gt16(track->par->codec_id)) {
753 mov_write_enda_tag_be(pb);
754 } else if (track->par->codec_id == AV_CODEC_ID_AMR_NB) {
755 mov_write_amr_tag(pb, track);
756 } else if (track->par->codec_id == AV_CODEC_ID_AC3) {
757 mov_write_ac3_tag(pb, track);
758 } else if (track->par->codec_id == AV_CODEC_ID_EAC3) {
759 mov_write_eac3_tag(pb, track);
760 } else if (track->par->codec_id == AV_CODEC_ID_ALAC ||
761 track->par->codec_id == AV_CODEC_ID_QDM2) {
762 mov_write_extradata_tag(pb, track);
763 } else if (track->par->codec_id == AV_CODEC_ID_ADPCM_MS ||
764 track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) {
765 mov_write_ms_tag(s, pb, track);
768 avio_wb32(pb, 8); /* size */
769 avio_wb32(pb, 0); /* null tag */
771 return update_size(pb, pos);
774 static int mov_write_dvc1_structs(MOVTrack *track, uint8_t *buf)
777 const uint8_t *start, *next, *end = track->vos_data + track->vos_len;
778 int unescaped_size, seq_found = 0;
779 int level = 0, interlace = 0;
780 int packet_seq = track->vc1_info.packet_seq;
781 int packet_entry = track->vc1_info.packet_entry;
782 int slices = track->vc1_info.slices;
785 if (track->start_dts == AV_NOPTS_VALUE) {
786 /* No packets written yet, vc1_info isn't authoritative yet. */
787 /* Assume inline sequence and entry headers. */
788 packet_seq = packet_entry = 1;
789 av_log(NULL, AV_LOG_WARNING,
790 "moov atom written before any packets, unable to write correct "
791 "dvc1 atom. Set the delay_moov flag to fix this.\n");
794 unescaped = av_mallocz(track->vos_len + AV_INPUT_BUFFER_PADDING_SIZE);
796 return AVERROR(ENOMEM);
797 start = find_next_marker(track->vos_data, end);
798 for (next = start; next < end; start = next) {
801 next = find_next_marker(start + 4, end);
802 size = next - start - 4;
805 unescaped_size = vc1_unescape_buffer(start + 4, size, unescaped);
806 init_get_bits(&gb, unescaped, 8 * unescaped_size);
807 if (AV_RB32(start) == VC1_CODE_SEQHDR) {
808 int profile = get_bits(&gb, 2);
809 if (profile != PROFILE_ADVANCED) {
811 return AVERROR(ENOSYS);
814 level = get_bits(&gb, 3);
815 /* chromaformat, frmrtq_postproc, bitrtq_postproc, postprocflag,
817 skip_bits_long(&gb, 2 + 3 + 5 + 1 + 2*12);
818 skip_bits(&gb, 1); /* broadcast */
819 interlace = get_bits1(&gb);
820 skip_bits(&gb, 4); /* tfcntrflag, finterpflag, reserved, psf */
825 return AVERROR(ENOSYS);
828 init_put_bits(&pbc, buf, 7);
829 /* VC1DecSpecStruc */
830 put_bits(&pbc, 4, 12); /* profile - advanced */
831 put_bits(&pbc, 3, level);
832 put_bits(&pbc, 1, 0); /* reserved */
833 /* VC1AdvDecSpecStruc */
834 put_bits(&pbc, 3, level);
835 put_bits(&pbc, 1, 0); /* cbr */
836 put_bits(&pbc, 6, 0); /* reserved */
837 put_bits(&pbc, 1, !interlace); /* no interlace */
838 put_bits(&pbc, 1, !packet_seq); /* no multiple seq */
839 put_bits(&pbc, 1, !packet_entry); /* no multiple entry */
840 put_bits(&pbc, 1, !slices); /* no slice code */
841 put_bits(&pbc, 1, 0); /* no bframe */
842 put_bits(&pbc, 1, 0); /* reserved */
845 if (track->st->avg_frame_rate.num > 0 && track->st->avg_frame_rate.den > 0)
846 put_bits32(&pbc, track->st->avg_frame_rate.num / track->st->avg_frame_rate.den);
848 put_bits32(&pbc, 0xffffffff);
850 flush_put_bits(&pbc);
857 static int mov_write_dvc1_tag(AVIOContext *pb, MOVTrack *track)
859 uint8_t buf[7] = { 0 };
862 if ((ret = mov_write_dvc1_structs(track, buf)) < 0)
865 avio_wb32(pb, track->vos_len + 8 + sizeof(buf));
866 ffio_wfourcc(pb, "dvc1");
867 avio_write(pb, buf, sizeof(buf));
868 avio_write(pb, track->vos_data, track->vos_len);
873 static int mov_write_glbl_tag(AVIOContext *pb, MOVTrack *track)
875 avio_wb32(pb, track->vos_len + 8);
876 ffio_wfourcc(pb, "glbl");
877 avio_write(pb, track->vos_data, track->vos_len);
878 return 8 + track->vos_len;
882 * Compute flags for 'lpcm' tag.
883 * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
885 static int mov_get_lpcm_flags(enum AVCodecID codec_id)
888 case AV_CODEC_ID_PCM_F32BE:
889 case AV_CODEC_ID_PCM_F64BE:
891 case AV_CODEC_ID_PCM_F32LE:
892 case AV_CODEC_ID_PCM_F64LE:
894 case AV_CODEC_ID_PCM_U8:
896 case AV_CODEC_ID_PCM_S16BE:
897 case AV_CODEC_ID_PCM_S24BE:
898 case AV_CODEC_ID_PCM_S32BE:
900 case AV_CODEC_ID_PCM_S8:
901 case AV_CODEC_ID_PCM_S16LE:
902 case AV_CODEC_ID_PCM_S24LE:
903 case AV_CODEC_ID_PCM_S32LE:
910 static int get_cluster_duration(MOVTrack *track, int cluster_idx)
914 if (cluster_idx >= track->entry)
917 if (cluster_idx + 1 == track->entry)
918 next_dts = track->track_duration + track->start_dts;
920 next_dts = track->cluster[cluster_idx + 1].dts;
922 next_dts -= track->cluster[cluster_idx].dts;
924 av_assert0(next_dts >= 0);
925 av_assert0(next_dts <= INT_MAX);
930 static int get_samples_per_packet(MOVTrack *track)
932 int i, first_duration;
934 // return track->par->frame_size;
936 /* use 1 for raw PCM */
937 if (!track->audio_vbr)
940 /* check to see if duration is constant for all clusters */
943 first_duration = get_cluster_duration(track, 0);
944 for (i = 1; i < track->entry; i++) {
945 if (get_cluster_duration(track, i) != first_duration)
948 return first_duration;
951 static int mov_write_audio_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
953 int64_t pos = avio_tell(pb);
955 uint32_t tag = track->tag;
957 if (track->mode == MODE_MOV) {
958 if (track->timescale > UINT16_MAX) {
959 if (mov_get_lpcm_flags(track->par->codec_id))
960 tag = AV_RL32("lpcm");
962 } else if (track->audio_vbr || mov_pcm_le_gt16(track->par->codec_id) ||
963 mov_pcm_be_gt16(track->par->codec_id) ||
964 track->par->codec_id == AV_CODEC_ID_ADPCM_MS ||
965 track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
966 track->par->codec_id == AV_CODEC_ID_QDM2) {
971 avio_wb32(pb, 0); /* size */
972 if (mov->encryption_scheme != MOV_ENC_NONE) {
973 ffio_wfourcc(pb, "enca");
975 avio_wl32(pb, tag); // store it byteswapped
977 avio_wb32(pb, 0); /* Reserved */
978 avio_wb16(pb, 0); /* Reserved */
979 avio_wb16(pb, 1); /* Data-reference index, XXX == 1 */
981 /* SoundDescription */
982 avio_wb16(pb, version); /* Version */
983 avio_wb16(pb, 0); /* Revision level */
984 avio_wb32(pb, 0); /* Reserved */
989 avio_wb16(pb, 0xfffe);
991 avio_wb32(pb, 0x00010000);
993 avio_wb64(pb, av_double2int(track->par->sample_rate));
994 avio_wb32(pb, track->par->channels);
995 avio_wb32(pb, 0x7F000000);
996 avio_wb32(pb, av_get_bits_per_sample(track->par->codec_id));
997 avio_wb32(pb, mov_get_lpcm_flags(track->par->codec_id));
998 avio_wb32(pb, track->sample_size);
999 avio_wb32(pb, get_samples_per_packet(track));
1001 if (track->mode == MODE_MOV) {
1002 avio_wb16(pb, track->par->channels);
1003 if (track->par->codec_id == AV_CODEC_ID_PCM_U8 ||
1004 track->par->codec_id == AV_CODEC_ID_PCM_S8)
1005 avio_wb16(pb, 8); /* bits per sample */
1006 else if (track->par->codec_id == AV_CODEC_ID_ADPCM_G726)
1007 avio_wb16(pb, track->par->bits_per_coded_sample);
1010 avio_wb16(pb, track->audio_vbr ? -2 : 0); /* compression ID */
1011 } else { /* reserved for mp4/3gp */
1012 if (track->par->codec_id == AV_CODEC_ID_FLAC ||
1013 track->par->codec_id == AV_CODEC_ID_OPUS) {
1014 avio_wb16(pb, track->par->channels);
1018 if (track->par->codec_id == AV_CODEC_ID_FLAC) {
1019 avio_wb16(pb, track->par->bits_per_raw_sample);
1026 avio_wb16(pb, 0); /* packet size (= 0) */
1027 if (track->par->codec_id == AV_CODEC_ID_OPUS)
1028 avio_wb16(pb, 48000);
1030 avio_wb16(pb, track->par->sample_rate <= UINT16_MAX ?
1031 track->par->sample_rate : 0);
1032 avio_wb16(pb, 0); /* Reserved */
1035 if (version == 1) { /* SoundDescription V1 extended info */
1036 if (mov_pcm_le_gt16(track->par->codec_id) ||
1037 mov_pcm_be_gt16(track->par->codec_id))
1038 avio_wb32(pb, 1); /* must be 1 for uncompressed formats */
1040 avio_wb32(pb, track->par->frame_size); /* Samples per packet */
1041 avio_wb32(pb, track->sample_size / track->par->channels); /* Bytes per packet */
1042 avio_wb32(pb, track->sample_size); /* Bytes per frame */
1043 avio_wb32(pb, 2); /* Bytes per sample */
1046 if (track->mode == MODE_MOV &&
1047 (track->par->codec_id == AV_CODEC_ID_AAC ||
1048 track->par->codec_id == AV_CODEC_ID_AC3 ||
1049 track->par->codec_id == AV_CODEC_ID_EAC3 ||
1050 track->par->codec_id == AV_CODEC_ID_AMR_NB ||
1051 track->par->codec_id == AV_CODEC_ID_ALAC ||
1052 track->par->codec_id == AV_CODEC_ID_ADPCM_MS ||
1053 track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
1054 track->par->codec_id == AV_CODEC_ID_QDM2 ||
1055 (mov_pcm_le_gt16(track->par->codec_id) && version==1) ||
1056 (mov_pcm_be_gt16(track->par->codec_id) && version==1)))
1057 mov_write_wave_tag(s, pb, track);
1058 else if (track->tag == MKTAG('m','p','4','a'))
1059 mov_write_esds_tag(pb, track);
1060 else if (track->par->codec_id == AV_CODEC_ID_AMR_NB)
1061 mov_write_amr_tag(pb, track);
1062 else if (track->par->codec_id == AV_CODEC_ID_AC3)
1063 mov_write_ac3_tag(pb, track);
1064 else if (track->par->codec_id == AV_CODEC_ID_EAC3)
1065 mov_write_eac3_tag(pb, track);
1066 else if (track->par->codec_id == AV_CODEC_ID_ALAC)
1067 mov_write_extradata_tag(pb, track);
1068 else if (track->par->codec_id == AV_CODEC_ID_WMAPRO)
1069 mov_write_wfex_tag(s, pb, track);
1070 else if (track->par->codec_id == AV_CODEC_ID_FLAC)
1071 mov_write_dfla_tag(pb, track);
1072 else if (track->par->codec_id == AV_CODEC_ID_OPUS)
1073 mov_write_dops_tag(pb, track);
1074 else if (track->vos_len > 0)
1075 mov_write_glbl_tag(pb, track);
1077 if (track->mode == MODE_MOV && track->par->codec_type == AVMEDIA_TYPE_AUDIO)
1078 mov_write_chan_tag(s, pb, track);
1080 if (mov->encryption_scheme != MOV_ENC_NONE) {
1081 ff_mov_cenc_write_sinf_tag(track, pb, mov->encryption_kid);
1084 return update_size(pb, pos);
1087 static int mov_write_d263_tag(AVIOContext *pb)
1089 avio_wb32(pb, 0xf); /* size */
1090 ffio_wfourcc(pb, "d263");
1091 ffio_wfourcc(pb, "FFMP");
1092 avio_w8(pb, 0); /* decoder version */
1093 /* FIXME use AVCodecContext level/profile, when encoder will set values */
1094 avio_w8(pb, 0xa); /* level */
1095 avio_w8(pb, 0); /* profile */
1099 static int mov_write_avcc_tag(AVIOContext *pb, MOVTrack *track)
1101 int64_t pos = avio_tell(pb);
1104 ffio_wfourcc(pb, "avcC");
1105 ff_isom_write_avcc(pb, track->vos_data, track->vos_len);
1106 return update_size(pb, pos);
1109 static int mov_write_vpcc_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
1111 int64_t pos = avio_tell(pb);
1114 ffio_wfourcc(pb, "vpcC");
1115 avio_wb32(pb, 0); /* version & flags */
1116 ff_isom_write_vpcc(s, pb, track->par);
1117 return update_size(pb, pos);
1120 static int mov_write_hvcc_tag(AVIOContext *pb, MOVTrack *track)
1122 int64_t pos = avio_tell(pb);
1125 ffio_wfourcc(pb, "hvcC");
1126 ff_isom_write_hvcc(pb, track->vos_data, track->vos_len, 0);
1127 return update_size(pb, pos);
1130 /* also used by all avid codecs (dv, imx, meridien) and their variants */
1131 static int mov_write_avid_tag(AVIOContext *pb, MOVTrack *track)
1136 int display_width = track->par->width;
1138 if (track->vos_data && track->vos_len > 0x29) {
1139 if (ff_dnxhd_parse_header_prefix(track->vos_data) != 0) {
1140 /* looks like a DNxHD bit stream */
1141 interlaced = (track->vos_data[5] & 2);
1142 cid = AV_RB32(track->vos_data + 0x28);
1144 av_log(NULL, AV_LOG_WARNING, "Could not locate DNxHD bit stream in vos_data\n");
1148 av_log(NULL, AV_LOG_WARNING, "Could not locate DNxHD bit stream, vos_data too small\n");
1152 avio_wb32(pb, 24); /* size */
1153 ffio_wfourcc(pb, "ACLR");
1154 ffio_wfourcc(pb, "ACLR");
1155 ffio_wfourcc(pb, "0001");
1156 if (track->par->color_range == AVCOL_RANGE_MPEG || /* Legal range (16-235) */
1157 track->par->color_range == AVCOL_RANGE_UNSPECIFIED) {
1158 avio_wb32(pb, 1); /* Corresponds to 709 in official encoder */
1159 } else { /* Full range (0-255) */
1160 avio_wb32(pb, 2); /* Corresponds to RGB in official encoder */
1162 avio_wb32(pb, 0); /* unknown */
1164 if (track->tag == MKTAG('A','V','d','h')) {
1166 ffio_wfourcc(pb, "ADHR");
1167 ffio_wfourcc(pb, "0001");
1169 avio_wb32(pb, 0); /* unknown */
1170 avio_wb32(pb, 1); /* unknown */
1171 avio_wb32(pb, 0); /* unknown */
1172 avio_wb32(pb, 0); /* unknown */
1176 avio_wb32(pb, 24); /* size */
1177 ffio_wfourcc(pb, "APRG");
1178 ffio_wfourcc(pb, "APRG");
1179 ffio_wfourcc(pb, "0001");
1180 avio_wb32(pb, 1); /* unknown */
1181 avio_wb32(pb, 0); /* unknown */
1183 avio_wb32(pb, 120); /* size */
1184 ffio_wfourcc(pb, "ARES");
1185 ffio_wfourcc(pb, "ARES");
1186 ffio_wfourcc(pb, "0001");
1187 avio_wb32(pb, cid); /* dnxhd cid, some id ? */
1188 if ( track->par->sample_aspect_ratio.num > 0
1189 && track->par->sample_aspect_ratio.den > 0)
1190 display_width = display_width * track->par->sample_aspect_ratio.num / track->par->sample_aspect_ratio.den;
1191 avio_wb32(pb, display_width);
1192 /* values below are based on samples created with quicktime and avid codecs */
1194 avio_wb32(pb, track->par->height / 2);
1195 avio_wb32(pb, 2); /* unknown */
1196 avio_wb32(pb, 0); /* unknown */
1197 avio_wb32(pb, 4); /* unknown */
1199 avio_wb32(pb, track->par->height);
1200 avio_wb32(pb, 1); /* unknown */
1201 avio_wb32(pb, 0); /* unknown */
1202 if (track->par->height == 1080)
1203 avio_wb32(pb, 5); /* unknown */
1205 avio_wb32(pb, 6); /* unknown */
1208 for (i = 0; i < 10; i++)
1214 static int mov_write_dpxe_tag(AVIOContext *pb, MOVTrack *track)
1217 ffio_wfourcc(pb, "DpxE");
1218 if (track->par->extradata_size >= 12 &&
1219 !memcmp(&track->par->extradata[4], "DpxE", 4)) {
1220 avio_wb32(pb, track->par->extradata[11]);
1227 static int mp4_get_codec_tag(AVFormatContext *s, MOVTrack *track)
1229 int tag = track->par->codec_tag;
1231 if (!ff_codec_get_tag(ff_mp4_obj_type, track->par->codec_id))
1234 if (track->par->codec_id == AV_CODEC_ID_H264) tag = MKTAG('a','v','c','1');
1235 else if (track->par->codec_id == AV_CODEC_ID_HEVC) tag = MKTAG('h','e','v','1');
1236 else if (track->par->codec_id == AV_CODEC_ID_VP9) tag = MKTAG('v','p','0','9');
1237 else if (track->par->codec_id == AV_CODEC_ID_AC3) tag = MKTAG('a','c','-','3');
1238 else if (track->par->codec_id == AV_CODEC_ID_EAC3) tag = MKTAG('e','c','-','3');
1239 else if (track->par->codec_id == AV_CODEC_ID_DIRAC) tag = MKTAG('d','r','a','c');
1240 else if (track->par->codec_id == AV_CODEC_ID_MOV_TEXT) tag = MKTAG('t','x','3','g');
1241 else if (track->par->codec_id == AV_CODEC_ID_VC1) tag = MKTAG('v','c','-','1');
1242 else if (track->par->codec_id == AV_CODEC_ID_FLAC) tag = MKTAG('f','L','a','C');
1243 else if (track->par->codec_id == AV_CODEC_ID_OPUS) tag = MKTAG('O','p','u','s');
1244 else if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) tag = MKTAG('m','p','4','v');
1245 else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) tag = MKTAG('m','p','4','a');
1246 else if (track->par->codec_id == AV_CODEC_ID_DVD_SUBTITLE) tag = MKTAG('m','p','4','s');
1251 static const AVCodecTag codec_ipod_tags[] = {
1252 { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
1253 { AV_CODEC_ID_MPEG4, MKTAG('m','p','4','v') },
1254 { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
1255 { AV_CODEC_ID_ALAC, MKTAG('a','l','a','c') },
1256 { AV_CODEC_ID_AC3, MKTAG('a','c','-','3') },
1257 { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
1258 { AV_CODEC_ID_MOV_TEXT, MKTAG('t','e','x','t') },
1259 { AV_CODEC_ID_NONE, 0 },
1262 static int ipod_get_codec_tag(AVFormatContext *s, MOVTrack *track)
1264 int tag = track->par->codec_tag;
1266 // keep original tag for subs, ipod supports both formats
1267 if (!(track->par->codec_type == AVMEDIA_TYPE_SUBTITLE &&
1268 (tag == MKTAG('t', 'x', '3', 'g') ||
1269 tag == MKTAG('t', 'e', 'x', 't'))))
1270 tag = ff_codec_get_tag(codec_ipod_tags, track->par->codec_id);
1272 if (!av_match_ext(s->filename, "m4a") &&
1273 !av_match_ext(s->filename, "m4b") &&
1274 !av_match_ext(s->filename, "m4v"))
1275 av_log(s, AV_LOG_WARNING, "Warning, extension is not .m4a, .m4v nor .m4b "
1276 "Quicktime/Ipod might not play the file\n");
1281 static int mov_get_dv_codec_tag(AVFormatContext *s, MOVTrack *track)
1285 if (track->par->width == 720) { /* SD */
1286 if (track->par->height == 480) { /* NTSC */
1287 if (track->par->format == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','n');
1288 else tag = MKTAG('d','v','c',' ');
1289 }else if (track->par->format == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','p');
1290 else if (track->par->format == AV_PIX_FMT_YUV420P) tag = MKTAG('d','v','c','p');
1291 else tag = MKTAG('d','v','p','p');
1292 } else if (track->par->height == 720) { /* HD 720 line */
1293 if (track->st->time_base.den == 50) tag = MKTAG('d','v','h','q');
1294 else tag = MKTAG('d','v','h','p');
1295 } else if (track->par->height == 1080) { /* HD 1080 line */
1296 if (track->st->time_base.den == 25) tag = MKTAG('d','v','h','5');
1297 else tag = MKTAG('d','v','h','6');
1299 av_log(s, AV_LOG_ERROR, "unsupported height for dv codec\n");
1306 static AVRational find_fps(AVFormatContext *s, AVStream *st)
1308 AVRational rate = st->avg_frame_rate;
1310 #if FF_API_LAVF_AVCTX
1311 FF_DISABLE_DEPRECATION_WARNINGS
1312 rate = av_inv_q(st->codec->time_base);
1313 if (av_timecode_check_frame_rate(rate) < 0) {
1314 av_log(s, AV_LOG_DEBUG, "timecode: tbc=%d/%d invalid, fallback on %d/%d\n",
1315 rate.num, rate.den, st->avg_frame_rate.num, st->avg_frame_rate.den);
1316 rate = st->avg_frame_rate;
1318 FF_ENABLE_DEPRECATION_WARNINGS
1324 static int mov_get_mpeg2_xdcam_codec_tag(AVFormatContext *s, MOVTrack *track)
1326 int tag = track->par->codec_tag;
1327 int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE;
1328 AVStream *st = track->st;
1329 int rate = av_q2d(find_fps(s, st));
1332 tag = MKTAG('m', '2', 'v', '1'); //fallback tag
1334 if (track->par->format == AV_PIX_FMT_YUV420P) {
1335 if (track->par->width == 1280 && track->par->height == 720) {
1337 if (rate == 24) tag = MKTAG('x','d','v','4');
1338 else if (rate == 25) tag = MKTAG('x','d','v','5');
1339 else if (rate == 30) tag = MKTAG('x','d','v','1');
1340 else if (rate == 50) tag = MKTAG('x','d','v','a');
1341 else if (rate == 60) tag = MKTAG('x','d','v','9');
1343 } else if (track->par->width == 1440 && track->par->height == 1080) {
1345 if (rate == 24) tag = MKTAG('x','d','v','6');
1346 else if (rate == 25) tag = MKTAG('x','d','v','7');
1347 else if (rate == 30) tag = MKTAG('x','d','v','8');
1349 if (rate == 25) tag = MKTAG('x','d','v','3');
1350 else if (rate == 30) tag = MKTAG('x','d','v','2');
1352 } else if (track->par->width == 1920 && track->par->height == 1080) {
1354 if (rate == 24) tag = MKTAG('x','d','v','d');
1355 else if (rate == 25) tag = MKTAG('x','d','v','e');
1356 else if (rate == 30) tag = MKTAG('x','d','v','f');
1358 if (rate == 25) tag = MKTAG('x','d','v','c');
1359 else if (rate == 30) tag = MKTAG('x','d','v','b');
1362 } else if (track->par->format == AV_PIX_FMT_YUV422P) {
1363 if (track->par->width == 1280 && track->par->height == 720) {
1365 if (rate == 24) tag = MKTAG('x','d','5','4');
1366 else if (rate == 25) tag = MKTAG('x','d','5','5');
1367 else if (rate == 30) tag = MKTAG('x','d','5','1');
1368 else if (rate == 50) tag = MKTAG('x','d','5','a');
1369 else if (rate == 60) tag = MKTAG('x','d','5','9');
1371 } else if (track->par->width == 1920 && track->par->height == 1080) {
1373 if (rate == 24) tag = MKTAG('x','d','5','d');
1374 else if (rate == 25) tag = MKTAG('x','d','5','e');
1375 else if (rate == 30) tag = MKTAG('x','d','5','f');
1377 if (rate == 25) tag = MKTAG('x','d','5','c');
1378 else if (rate == 30) tag = MKTAG('x','d','5','b');
1386 static int mov_get_h264_codec_tag(AVFormatContext *s, MOVTrack *track)
1388 int tag = track->par->codec_tag;
1389 int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE;
1390 AVStream *st = track->st;
1391 int rate = av_q2d(find_fps(s, st));
1394 tag = MKTAG('a', 'v', 'c', 'i'); //fallback tag
1396 if (track->par->format == AV_PIX_FMT_YUV420P10) {
1397 if (track->par->width == 960 && track->par->height == 720) {
1399 if (rate == 24) tag = MKTAG('a','i','5','p');
1400 else if (rate == 25) tag = MKTAG('a','i','5','q');
1401 else if (rate == 30) tag = MKTAG('a','i','5','p');
1402 else if (rate == 50) tag = MKTAG('a','i','5','q');
1403 else if (rate == 60) tag = MKTAG('a','i','5','p');
1405 } else if (track->par->width == 1440 && track->par->height == 1080) {
1407 if (rate == 24) tag = MKTAG('a','i','5','3');
1408 else if (rate == 25) tag = MKTAG('a','i','5','2');
1409 else if (rate == 30) tag = MKTAG('a','i','5','3');
1411 if (rate == 50) tag = MKTAG('a','i','5','5');
1412 else if (rate == 60) tag = MKTAG('a','i','5','6');
1415 } else if (track->par->format == AV_PIX_FMT_YUV422P10) {
1416 if (track->par->width == 1280 && track->par->height == 720) {
1418 if (rate == 24) tag = MKTAG('a','i','1','p');
1419 else if (rate == 25) tag = MKTAG('a','i','1','q');
1420 else if (rate == 30) tag = MKTAG('a','i','1','p');
1421 else if (rate == 50) tag = MKTAG('a','i','1','q');
1422 else if (rate == 60) tag = MKTAG('a','i','1','p');
1424 } else if (track->par->width == 1920 && track->par->height == 1080) {
1426 if (rate == 24) tag = MKTAG('a','i','1','3');
1427 else if (rate == 25) tag = MKTAG('a','i','1','2');
1428 else if (rate == 30) tag = MKTAG('a','i','1','3');
1430 if (rate == 25) tag = MKTAG('a','i','1','5');
1431 else if (rate == 50) tag = MKTAG('a','i','1','5');
1432 else if (rate == 60) tag = MKTAG('a','i','1','6');
1434 } else if ( track->par->width == 4096 && track->par->height == 2160
1435 || track->par->width == 3840 && track->par->height == 2160
1436 || track->par->width == 2048 && track->par->height == 1080) {
1437 tag = MKTAG('a','i','v','x');
1444 static const struct {
1445 enum AVPixelFormat pix_fmt;
1448 } mov_pix_fmt_tags[] = {
1449 { AV_PIX_FMT_YUYV422, MKTAG('y','u','v','2'), 0 },
1450 { AV_PIX_FMT_YUYV422, MKTAG('y','u','v','s'), 0 },
1451 { AV_PIX_FMT_UYVY422, MKTAG('2','v','u','y'), 0 },
1452 { AV_PIX_FMT_RGB555BE,MKTAG('r','a','w',' '), 16 },
1453 { AV_PIX_FMT_RGB555LE,MKTAG('L','5','5','5'), 16 },
1454 { AV_PIX_FMT_RGB565LE,MKTAG('L','5','6','5'), 16 },
1455 { AV_PIX_FMT_RGB565BE,MKTAG('B','5','6','5'), 16 },
1456 { AV_PIX_FMT_GRAY16BE,MKTAG('b','1','6','g'), 16 },
1457 { AV_PIX_FMT_RGB24, MKTAG('r','a','w',' '), 24 },
1458 { AV_PIX_FMT_BGR24, MKTAG('2','4','B','G'), 24 },
1459 { AV_PIX_FMT_ARGB, MKTAG('r','a','w',' '), 32 },
1460 { AV_PIX_FMT_BGRA, MKTAG('B','G','R','A'), 32 },
1461 { AV_PIX_FMT_RGBA, MKTAG('R','G','B','A'), 32 },
1462 { AV_PIX_FMT_ABGR, MKTAG('A','B','G','R'), 32 },
1463 { AV_PIX_FMT_RGB48BE, MKTAG('b','4','8','r'), 48 },
1466 static int mov_get_dnxhd_codec_tag(AVFormatContext *s, MOVTrack *track)
1468 int tag = MKTAG('A','V','d','n');
1469 if (track->par->profile != FF_PROFILE_UNKNOWN &&
1470 track->par->profile != FF_PROFILE_DNXHD)
1471 tag = MKTAG('A','V','d','h');
1475 static int mov_get_rawvideo_codec_tag(AVFormatContext *s, MOVTrack *track)
1477 int tag = track->par->codec_tag;
1479 enum AVPixelFormat pix_fmt;
1481 for (i = 0; i < FF_ARRAY_ELEMS(mov_pix_fmt_tags); i++) {
1482 if (track->par->format == mov_pix_fmt_tags[i].pix_fmt) {
1483 tag = mov_pix_fmt_tags[i].tag;
1484 track->par->bits_per_coded_sample = mov_pix_fmt_tags[i].bps;
1485 if (track->par->codec_tag == mov_pix_fmt_tags[i].tag)
1490 pix_fmt = avpriv_find_pix_fmt(avpriv_pix_fmt_bps_mov,
1491 track->par->bits_per_coded_sample);
1492 if (tag == MKTAG('r','a','w',' ') &&
1493 track->par->format != pix_fmt &&
1494 track->par->format != AV_PIX_FMT_GRAY8 &&
1495 track->par->format != AV_PIX_FMT_NONE)
1496 av_log(s, AV_LOG_ERROR, "%s rawvideo cannot be written to mov, output file will be unreadable\n",
1497 av_get_pix_fmt_name(track->par->format));
1501 static int mov_get_codec_tag(AVFormatContext *s, MOVTrack *track)
1503 int tag = track->par->codec_tag;
1505 if (!tag || (s->strict_std_compliance >= FF_COMPLIANCE_NORMAL &&
1506 (track->par->codec_id == AV_CODEC_ID_DVVIDEO ||
1507 track->par->codec_id == AV_CODEC_ID_RAWVIDEO ||
1508 track->par->codec_id == AV_CODEC_ID_H263 ||
1509 track->par->codec_id == AV_CODEC_ID_H264 ||
1510 track->par->codec_id == AV_CODEC_ID_DNXHD ||
1511 track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO ||
1512 av_get_bits_per_sample(track->par->codec_id)))) { // pcm audio
1513 if (track->par->codec_id == AV_CODEC_ID_DVVIDEO)
1514 tag = mov_get_dv_codec_tag(s, track);
1515 else if (track->par->codec_id == AV_CODEC_ID_RAWVIDEO)
1516 tag = mov_get_rawvideo_codec_tag(s, track);
1517 else if (track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO)
1518 tag = mov_get_mpeg2_xdcam_codec_tag(s, track);
1519 else if (track->par->codec_id == AV_CODEC_ID_H264)
1520 tag = mov_get_h264_codec_tag(s, track);
1521 else if (track->par->codec_id == AV_CODEC_ID_DNXHD)
1522 tag = mov_get_dnxhd_codec_tag(s, track);
1523 else if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
1524 tag = ff_codec_get_tag(ff_codec_movvideo_tags, track->par->codec_id);
1525 if (!tag) { // if no mac fcc found, try with Microsoft tags
1526 tag = ff_codec_get_tag(ff_codec_bmp_tags, track->par->codec_id);
1528 av_log(s, AV_LOG_WARNING, "Using MS style video codec tag, "
1529 "the file may be unplayable!\n");
1531 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
1532 tag = ff_codec_get_tag(ff_codec_movaudio_tags, track->par->codec_id);
1533 if (!tag) { // if no mac fcc found, try with Microsoft tags
1534 int ms_tag = ff_codec_get_tag(ff_codec_wav_tags, track->par->codec_id);
1536 tag = MKTAG('m', 's', ((ms_tag >> 8) & 0xff), (ms_tag & 0xff));
1537 av_log(s, AV_LOG_WARNING, "Using MS style audio codec tag, "
1538 "the file may be unplayable!\n");
1541 } else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)
1542 tag = ff_codec_get_tag(ff_codec_movsubtitle_tags, track->par->codec_id);
1548 static const AVCodecTag codec_3gp_tags[] = {
1549 { AV_CODEC_ID_H263, MKTAG('s','2','6','3') },
1550 { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
1551 { AV_CODEC_ID_MPEG4, MKTAG('m','p','4','v') },
1552 { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
1553 { AV_CODEC_ID_AMR_NB, MKTAG('s','a','m','r') },
1554 { AV_CODEC_ID_AMR_WB, MKTAG('s','a','w','b') },
1555 { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
1556 { AV_CODEC_ID_NONE, 0 },
1559 static const AVCodecTag codec_f4v_tags[] = { // XXX: add GIF/PNG/JPEG?
1560 { AV_CODEC_ID_MP3, MKTAG('.','m','p','3') },
1561 { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
1562 { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
1563 { AV_CODEC_ID_VP6A, MKTAG('V','P','6','A') },
1564 { AV_CODEC_ID_VP6F, MKTAG('V','P','6','F') },
1565 { AV_CODEC_ID_NONE, 0 },
1568 static int mov_find_codec_tag(AVFormatContext *s, MOVTrack *track)
1572 if (track->mode == MODE_MP4 || track->mode == MODE_PSP)
1573 tag = mp4_get_codec_tag(s, track);
1574 else if (track->mode == MODE_ISM) {
1575 tag = mp4_get_codec_tag(s, track);
1576 if (!tag && track->par->codec_id == AV_CODEC_ID_WMAPRO)
1577 tag = MKTAG('w', 'm', 'a', ' ');
1578 } else if (track->mode == MODE_IPOD)
1579 tag = ipod_get_codec_tag(s, track);
1580 else if (track->mode & MODE_3GP)
1581 tag = ff_codec_get_tag(codec_3gp_tags, track->par->codec_id);
1582 else if (track->mode == MODE_F4V)
1583 tag = ff_codec_get_tag(codec_f4v_tags, track->par->codec_id);
1585 tag = mov_get_codec_tag(s, track);
1590 /** Write uuid atom.
1591 * Needed to make file play in iPods running newest firmware
1592 * goes after avcC atom in moov.trak.mdia.minf.stbl.stsd.avc1
1594 static int mov_write_uuid_tag_ipod(AVIOContext *pb)
1597 ffio_wfourcc(pb, "uuid");
1598 avio_wb32(pb, 0x6b6840f2);
1599 avio_wb32(pb, 0x5f244fc5);
1600 avio_wb32(pb, 0xba39a51b);
1601 avio_wb32(pb, 0xcf0323f3);
1606 static const uint16_t fiel_data[] = {
1607 0x0000, 0x0100, 0x0201, 0x0206, 0x0209, 0x020e
1610 static int mov_write_fiel_tag(AVIOContext *pb, MOVTrack *track, int field_order)
1612 unsigned mov_field_order = 0;
1613 if (field_order < FF_ARRAY_ELEMS(fiel_data))
1614 mov_field_order = fiel_data[field_order];
1618 ffio_wfourcc(pb, "fiel");
1619 avio_wb16(pb, mov_field_order);
1623 static int mov_write_subtitle_tag(AVIOContext *pb, MOVTrack *track)
1625 int64_t pos = avio_tell(pb);
1626 avio_wb32(pb, 0); /* size */
1627 avio_wl32(pb, track->tag); // store it byteswapped
1628 avio_wb32(pb, 0); /* Reserved */
1629 avio_wb16(pb, 0); /* Reserved */
1630 avio_wb16(pb, 1); /* Data-reference index */
1632 if (track->par->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
1633 mov_write_esds_tag(pb, track);
1634 else if (track->par->extradata_size)
1635 avio_write(pb, track->par->extradata, track->par->extradata_size);
1637 return update_size(pb, pos);
1640 static int mov_write_st3d_tag(AVIOContext *pb, AVStereo3D *stereo_3d)
1644 if (stereo_3d->flags != 0) {
1645 av_log(pb, AV_LOG_WARNING, "Unsupported stereo_3d flags %x. st3d not written.\n", stereo_3d->flags);
1649 switch (stereo_3d->type) {
1650 case AV_STEREO3D_2D:
1653 case AV_STEREO3D_TOPBOTTOM:
1656 case AV_STEREO3D_SIDEBYSIDE:
1660 av_log(pb, AV_LOG_WARNING, "Unsupported stereo_3d type %s. st3d not written.\n", av_stereo3d_type_name(stereo_3d->type));
1663 avio_wb32(pb, 13); /* size */
1664 ffio_wfourcc(pb, "st3d");
1665 avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1666 avio_w8(pb, stereo_mode);
1670 static int mov_write_sv3d_tag(AVFormatContext *s, AVIOContext *pb, AVSphericalMapping *spherical_mapping)
1672 int64_t sv3d_pos, svhd_pos, proj_pos;
1673 const char* metadata_source = s->flags & AVFMT_FLAG_BITEXACT ? "Lavf" : LIBAVFORMAT_IDENT;
1675 if (spherical_mapping->projection != AV_SPHERICAL_EQUIRECTANGULAR &&
1676 spherical_mapping->projection != AV_SPHERICAL_EQUIRECTANGULAR_TILE &&
1677 spherical_mapping->projection != AV_SPHERICAL_CUBEMAP) {
1678 av_log(pb, AV_LOG_WARNING, "Unsupported projection %d. sv3d not written.\n", spherical_mapping->projection);
1682 sv3d_pos = avio_tell(pb);
1683 avio_wb32(pb, 0); /* size */
1684 ffio_wfourcc(pb, "sv3d");
1686 svhd_pos = avio_tell(pb);
1687 avio_wb32(pb, 0); /* size */
1688 ffio_wfourcc(pb, "svhd");
1689 avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1690 avio_put_str(pb, metadata_source);
1691 update_size(pb, svhd_pos);
1693 proj_pos = avio_tell(pb);
1694 avio_wb32(pb, 0); /* size */
1695 ffio_wfourcc(pb, "proj");
1697 avio_wb32(pb, 24); /* size */
1698 ffio_wfourcc(pb, "prhd");
1699 avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1700 avio_wb32(pb, spherical_mapping->yaw);
1701 avio_wb32(pb, spherical_mapping->pitch);
1702 avio_wb32(pb, spherical_mapping->roll);
1704 switch (spherical_mapping->projection) {
1705 case AV_SPHERICAL_EQUIRECTANGULAR:
1706 case AV_SPHERICAL_EQUIRECTANGULAR_TILE:
1707 avio_wb32(pb, 28); /* size */
1708 ffio_wfourcc(pb, "equi");
1709 avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1710 avio_wb32(pb, spherical_mapping->bound_top);
1711 avio_wb32(pb, spherical_mapping->bound_bottom);
1712 avio_wb32(pb, spherical_mapping->bound_left);
1713 avio_wb32(pb, spherical_mapping->bound_right);
1715 case AV_SPHERICAL_CUBEMAP:
1716 avio_wb32(pb, 20); /* size */
1717 ffio_wfourcc(pb, "cbmp");
1718 avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1719 avio_wb32(pb, 0); /* layout */
1720 avio_wb32(pb, spherical_mapping->padding); /* padding */
1723 update_size(pb, proj_pos);
1725 return update_size(pb, sv3d_pos);
1728 static int mov_write_pasp_tag(AVIOContext *pb, MOVTrack *track)
1731 av_reduce(&sar.num, &sar.den, track->par->sample_aspect_ratio.num,
1732 track->par->sample_aspect_ratio.den, INT_MAX);
1735 ffio_wfourcc(pb, "pasp");
1736 avio_wb32(pb, sar.num);
1737 avio_wb32(pb, sar.den);
1741 static int mov_write_gama_tag(AVIOContext *pb, MOVTrack *track, double gamma)
1746 gamma = avpriv_get_gamma_from_trc(track->par->color_trc);
1748 av_log(pb, AV_LOG_DEBUG, "gamma value %g\n", gamma);
1751 gama = (uint32_t)lrint((double)(1<<16) * gamma);
1752 av_log(pb, AV_LOG_DEBUG, "writing gama value %"PRId32"\n", gama);
1754 av_assert0(track->mode == MODE_MOV);
1756 ffio_wfourcc(pb, "gama");
1757 avio_wb32(pb, gama);
1761 av_log(pb, AV_LOG_WARNING, "gamma value unknown, unable to write gama atom\n");
1766 static int mov_write_colr_tag(AVIOContext *pb, MOVTrack *track)
1768 // Ref (MOV): https://developer.apple.com/library/mac/technotes/tn2162/_index.html#//apple_ref/doc/uid/DTS40013070-CH1-TNTAG9
1769 // Ref (MP4): ISO/IEC 14496-12:2012
1771 if (track->par->color_primaries == AVCOL_PRI_UNSPECIFIED &&
1772 track->par->color_trc == AVCOL_TRC_UNSPECIFIED &&
1773 track->par->color_space == AVCOL_SPC_UNSPECIFIED) {
1774 if ((track->par->width >= 1920 && track->par->height >= 1080)
1775 || (track->par->width == 1280 && track->par->height == 720)) {
1776 av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming bt709\n");
1777 track->par->color_primaries = AVCOL_PRI_BT709;
1778 } else if (track->par->width == 720 && track->height == 576) {
1779 av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming bt470bg\n");
1780 track->par->color_primaries = AVCOL_PRI_BT470BG;
1781 } else if (track->par->width == 720 &&
1782 (track->height == 486 || track->height == 480)) {
1783 av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming smpte170\n");
1784 track->par->color_primaries = AVCOL_PRI_SMPTE170M;
1786 av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, unable to assume anything\n");
1788 switch (track->par->color_primaries) {
1789 case AVCOL_PRI_BT709:
1790 track->par->color_trc = AVCOL_TRC_BT709;
1791 track->par->color_space = AVCOL_SPC_BT709;
1793 case AVCOL_PRI_SMPTE170M:
1794 case AVCOL_PRI_BT470BG:
1795 track->par->color_trc = AVCOL_TRC_BT709;
1796 track->par->color_space = AVCOL_SPC_SMPTE170M;
1801 /* We should only ever be called by MOV or MP4. */
1802 av_assert0(track->mode == MODE_MOV || track->mode == MODE_MP4);
1804 avio_wb32(pb, 18 + (track->mode == MODE_MP4));
1805 ffio_wfourcc(pb, "colr");
1806 if (track->mode == MODE_MP4)
1807 ffio_wfourcc(pb, "nclx");
1809 ffio_wfourcc(pb, "nclc");
1810 switch (track->par->color_primaries) {
1811 case AVCOL_PRI_BT709: avio_wb16(pb, 1); break;
1812 case AVCOL_PRI_SMPTE170M:
1813 case AVCOL_PRI_SMPTE240M: avio_wb16(pb, 6); break;
1814 case AVCOL_PRI_BT470BG: avio_wb16(pb, 5); break;
1815 default: avio_wb16(pb, 2);
1817 switch (track->par->color_trc) {
1818 case AVCOL_TRC_BT709: avio_wb16(pb, 1); break;
1819 case AVCOL_TRC_SMPTE170M: avio_wb16(pb, 1); break; // remapped
1820 case AVCOL_TRC_SMPTE240M: avio_wb16(pb, 7); break;
1821 default: avio_wb16(pb, 2);
1823 switch (track->par->color_space) {
1824 case AVCOL_SPC_BT709: avio_wb16(pb, 1); break;
1825 case AVCOL_SPC_BT470BG:
1826 case AVCOL_SPC_SMPTE170M: avio_wb16(pb, 6); break;
1827 case AVCOL_SPC_SMPTE240M: avio_wb16(pb, 7); break;
1828 default: avio_wb16(pb, 2);
1831 if (track->mode == MODE_MP4) {
1832 int full_range = track->par->color_range == AVCOL_RANGE_JPEG;
1833 avio_w8(pb, full_range << 7);
1840 static void find_compressor(char * compressor_name, int len, MOVTrack *track)
1842 AVDictionaryEntry *encoder;
1843 int xdcam_res = (track->par->width == 1280 && track->par->height == 720)
1844 || (track->par->width == 1440 && track->par->height == 1080)
1845 || (track->par->width == 1920 && track->par->height == 1080);
1847 if (track->mode == MODE_MOV &&
1848 (encoder = av_dict_get(track->st->metadata, "encoder", NULL, 0))) {
1849 av_strlcpy(compressor_name, encoder->value, 32);
1850 } else if (track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO && xdcam_res) {
1851 int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE;
1852 AVStream *st = track->st;
1853 int rate = av_q2d(find_fps(NULL, st));
1854 av_strlcatf(compressor_name, len, "XDCAM");
1855 if (track->par->format == AV_PIX_FMT_YUV422P) {
1856 av_strlcatf(compressor_name, len, " HD422");
1857 } else if(track->par->width == 1440) {
1858 av_strlcatf(compressor_name, len, " HD");
1860 av_strlcatf(compressor_name, len, " EX");
1862 av_strlcatf(compressor_name, len, " %d%c", track->par->height, interlaced ? 'i' : 'p');
1864 av_strlcatf(compressor_name, len, "%d", rate * (interlaced + 1));
1868 static int mov_write_video_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
1870 int64_t pos = avio_tell(pb);
1871 char compressor_name[32] = { 0 };
1874 avio_wb32(pb, 0); /* size */
1875 if (mov->encryption_scheme != MOV_ENC_NONE) {
1876 ffio_wfourcc(pb, "encv");
1878 avio_wl32(pb, track->tag); // store it byteswapped
1880 avio_wb32(pb, 0); /* Reserved */
1881 avio_wb16(pb, 0); /* Reserved */
1882 avio_wb16(pb, 1); /* Data-reference index */
1884 avio_wb16(pb, 0); /* Codec stream version */
1885 avio_wb16(pb, 0); /* Codec stream revision (=0) */
1886 if (track->mode == MODE_MOV) {
1887 ffio_wfourcc(pb, "FFMP"); /* Vendor */
1888 if (track->par->codec_id == AV_CODEC_ID_RAWVIDEO) {
1889 avio_wb32(pb, 0); /* Temporal Quality */
1890 avio_wb32(pb, 0x400); /* Spatial Quality = lossless*/
1892 avio_wb32(pb, 0x200); /* Temporal Quality = normal */
1893 avio_wb32(pb, 0x200); /* Spatial Quality = normal */
1896 avio_wb32(pb, 0); /* Reserved */
1897 avio_wb32(pb, 0); /* Reserved */
1898 avio_wb32(pb, 0); /* Reserved */
1900 avio_wb16(pb, track->par->width); /* Video width */
1901 avio_wb16(pb, track->height); /* Video height */
1902 avio_wb32(pb, 0x00480000); /* Horizontal resolution 72dpi */
1903 avio_wb32(pb, 0x00480000); /* Vertical resolution 72dpi */
1904 avio_wb32(pb, 0); /* Data size (= 0) */
1905 avio_wb16(pb, 1); /* Frame count (= 1) */
1907 /* FIXME not sure, ISO 14496-1 draft where it shall be set to 0 */
1908 find_compressor(compressor_name, 32, track);
1909 avio_w8(pb, strlen(compressor_name));
1910 avio_write(pb, compressor_name, 31);
1912 if (track->mode == MODE_MOV && track->par->bits_per_coded_sample)
1913 avio_wb16(pb, track->par->bits_per_coded_sample |
1914 (track->par->format == AV_PIX_FMT_GRAY8 ? 0x20 : 0));
1916 avio_wb16(pb, 0x18); /* Reserved */
1918 if (track->mode == MODE_MOV && track->par->format == AV_PIX_FMT_PAL8) {
1919 int pal_size = 1 << track->par->bits_per_coded_sample;
1921 avio_wb16(pb, 0); /* Color table ID */
1922 avio_wb32(pb, 0); /* Color table seed */
1923 avio_wb16(pb, 0x8000); /* Color table flags */
1924 avio_wb16(pb, pal_size - 1); /* Color table size (zero-relative) */
1925 for (i = 0; i < pal_size; i++) {
1926 uint32_t rgb = track->palette[i];
1927 uint16_t r = (rgb >> 16) & 0xff;
1928 uint16_t g = (rgb >> 8) & 0xff;
1929 uint16_t b = rgb & 0xff;
1931 avio_wb16(pb, (r << 8) | r);
1932 avio_wb16(pb, (g << 8) | g);
1933 avio_wb16(pb, (b << 8) | b);
1936 avio_wb16(pb, 0xffff); /* Reserved */
1938 if (track->tag == MKTAG('m','p','4','v'))
1939 mov_write_esds_tag(pb, track);
1940 else if (track->par->codec_id == AV_CODEC_ID_H263)
1941 mov_write_d263_tag(pb);
1942 else if (track->par->codec_id == AV_CODEC_ID_AVUI ||
1943 track->par->codec_id == AV_CODEC_ID_SVQ3) {
1944 mov_write_extradata_tag(pb, track);
1946 } else if (track->par->codec_id == AV_CODEC_ID_DNXHD) {
1947 mov_write_avid_tag(pb, track);
1949 } else if (track->par->codec_id == AV_CODEC_ID_HEVC)
1950 mov_write_hvcc_tag(pb, track);
1951 else if (track->par->codec_id == AV_CODEC_ID_H264 && !TAG_IS_AVCI(track->tag)) {
1952 mov_write_avcc_tag(pb, track);
1953 if (track->mode == MODE_IPOD)
1954 mov_write_uuid_tag_ipod(pb);
1955 } else if (track->par->codec_id == AV_CODEC_ID_VP9) {
1956 mov_write_vpcc_tag(mov->fc, pb, track);
1957 } else if (track->par->codec_id == AV_CODEC_ID_VC1 && track->vos_len > 0)
1958 mov_write_dvc1_tag(pb, track);
1959 else if (track->par->codec_id == AV_CODEC_ID_VP6F ||
1960 track->par->codec_id == AV_CODEC_ID_VP6A) {
1961 /* Don't write any potential extradata here - the cropping
1962 * is signalled via the normal width/height fields. */
1963 } else if (track->par->codec_id == AV_CODEC_ID_R10K) {
1964 if (track->par->codec_tag == MKTAG('R','1','0','k'))
1965 mov_write_dpxe_tag(pb, track);
1966 } else if (track->vos_len > 0)
1967 mov_write_glbl_tag(pb, track);
1969 if (track->par->codec_id != AV_CODEC_ID_H264 &&
1970 track->par->codec_id != AV_CODEC_ID_MPEG4 &&
1971 track->par->codec_id != AV_CODEC_ID_DNXHD) {
1972 int field_order = track->par->field_order;
1974 #if FF_API_LAVF_AVCTX
1975 FF_DISABLE_DEPRECATION_WARNINGS
1976 if (field_order != track->st->codec->field_order && track->st->codec->field_order != AV_FIELD_UNKNOWN)
1977 field_order = track->st->codec->field_order;
1978 FF_ENABLE_DEPRECATION_WARNINGS
1981 if (field_order != AV_FIELD_UNKNOWN)
1982 mov_write_fiel_tag(pb, track, field_order);
1985 if (mov->flags & FF_MOV_FLAG_WRITE_GAMA) {
1986 if (track->mode == MODE_MOV)
1987 mov_write_gama_tag(pb, track, mov->gamma);
1989 av_log(mov->fc, AV_LOG_WARNING, "Not writing 'gama' atom. Format is not MOV.\n");
1991 if (mov->flags & FF_MOV_FLAG_WRITE_COLR) {
1992 if (track->mode == MODE_MOV || track->mode == MODE_MP4)
1993 mov_write_colr_tag(pb, track);
1995 av_log(mov->fc, AV_LOG_WARNING, "Not writing 'colr' atom. Format is not MOV or MP4.\n");
1998 if (track->mode == MODE_MP4 && mov->fc->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL) {
1999 AVStereo3D* stereo_3d = (AVStereo3D*) av_stream_get_side_data(track->st, AV_PKT_DATA_STEREO3D, NULL);
2000 AVSphericalMapping* spherical_mapping = (AVSphericalMapping*)av_stream_get_side_data(track->st, AV_PKT_DATA_SPHERICAL, NULL);
2003 mov_write_st3d_tag(pb, stereo_3d);
2004 if (spherical_mapping)
2005 mov_write_sv3d_tag(mov->fc, pb, spherical_mapping);
2008 if (track->par->sample_aspect_ratio.den && track->par->sample_aspect_ratio.num) {
2009 mov_write_pasp_tag(pb, track);
2012 if (mov->encryption_scheme != MOV_ENC_NONE) {
2013 ff_mov_cenc_write_sinf_tag(track, pb, mov->encryption_kid);
2016 /* extra padding for avid stsd */
2017 /* https://developer.apple.com/library/mac/documentation/QuickTime/QTFF/QTFFChap2/qtff2.html#//apple_ref/doc/uid/TP40000939-CH204-61112 */
2021 return update_size(pb, pos);
2024 static int mov_write_rtp_tag(AVIOContext *pb, MOVTrack *track)
2026 int64_t pos = avio_tell(pb);
2027 avio_wb32(pb, 0); /* size */
2028 ffio_wfourcc(pb, "rtp ");
2029 avio_wb32(pb, 0); /* Reserved */
2030 avio_wb16(pb, 0); /* Reserved */
2031 avio_wb16(pb, 1); /* Data-reference index */
2033 avio_wb16(pb, 1); /* Hint track version */
2034 avio_wb16(pb, 1); /* Highest compatible version */
2035 avio_wb32(pb, track->max_packet_size); /* Max packet size */
2037 avio_wb32(pb, 12); /* size */
2038 ffio_wfourcc(pb, "tims");
2039 avio_wb32(pb, track->timescale);
2041 return update_size(pb, pos);
2044 static int mov_write_source_reference_tag(AVIOContext *pb, MOVTrack *track, const char *reel_name)
2046 uint64_t str_size =strlen(reel_name);
2047 int64_t pos = avio_tell(pb);
2049 if (str_size >= UINT16_MAX){
2050 av_log(NULL, AV_LOG_ERROR, "reel_name length %"PRIu64" is too large\n", str_size);
2052 return AVERROR(EINVAL);
2055 avio_wb32(pb, 0); /* size */
2056 ffio_wfourcc(pb, "name"); /* Data format */
2057 avio_wb16(pb, str_size); /* string size */
2058 avio_wb16(pb, track->language); /* langcode */
2059 avio_write(pb, reel_name, str_size); /* reel name */
2060 return update_size(pb,pos);
2063 static int mov_write_tmcd_tag(AVIOContext *pb, MOVTrack *track)
2065 int64_t pos = avio_tell(pb);
2069 AVDictionaryEntry *t = NULL;
2071 if (!track->st->avg_frame_rate.num || !track->st->avg_frame_rate.den) {
2072 #if FF_API_LAVF_AVCTX
2073 FF_DISABLE_DEPRECATION_WARNINGS
2074 frame_duration = av_rescale(track->timescale, track->st->codec->time_base.num, track->st->codec->time_base.den);
2075 nb_frames = ROUNDED_DIV(track->st->codec->time_base.den, track->st->codec->time_base.num);
2076 FF_ENABLE_DEPRECATION_WARNINGS
2078 av_log(NULL, AV_LOG_ERROR, "avg_frame_rate not set for tmcd track.\n");
2079 return AVERROR(EINVAL);
2082 frame_duration = av_rescale(track->timescale, track->st->avg_frame_rate.num, track->st->avg_frame_rate.den);
2083 nb_frames = ROUNDED_DIV(track->st->avg_frame_rate.den, track->st->avg_frame_rate.num);
2086 if (nb_frames > 255) {
2087 av_log(NULL, AV_LOG_ERROR, "fps %d is too large\n", nb_frames);
2088 return AVERROR(EINVAL);
2091 avio_wb32(pb, 0); /* size */
2092 ffio_wfourcc(pb, "tmcd"); /* Data format */
2093 avio_wb32(pb, 0); /* Reserved */
2094 avio_wb32(pb, 1); /* Data reference index */
2095 avio_wb32(pb, 0); /* Flags */
2096 avio_wb32(pb, track->timecode_flags); /* Flags (timecode) */
2097 avio_wb32(pb, track->timescale); /* Timescale */
2098 avio_wb32(pb, frame_duration); /* Frame duration */
2099 avio_w8(pb, nb_frames); /* Number of frames */
2100 avio_w8(pb, 0); /* Reserved */
2102 t = av_dict_get(track->st->metadata, "reel_name", NULL, 0);
2103 if (t && utf8len(t->value) && track->mode != MODE_MP4)
2104 mov_write_source_reference_tag(pb, track, t->value);
2106 avio_wb16(pb, 0); /* zero size */
2109 avio_wb32(pb, 0); /* size */
2110 ffio_wfourcc(pb, "tmcd"); /* Data format */
2111 avio_wb32(pb, 0); /* Reserved */
2112 avio_wb32(pb, 1); /* Data reference index */
2113 if (track->par->extradata_size)
2114 avio_write(pb, track->par->extradata, track->par->extradata_size);
2116 return update_size(pb, pos);
2119 static int mov_write_stsd_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
2121 int64_t pos = avio_tell(pb);
2122 avio_wb32(pb, 0); /* size */
2123 ffio_wfourcc(pb, "stsd");
2124 avio_wb32(pb, 0); /* version & flags */
2125 avio_wb32(pb, 1); /* entry count */
2126 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO)
2127 mov_write_video_tag(pb, mov, track);
2128 else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
2129 mov_write_audio_tag(s, pb, mov, track);
2130 else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)
2131 mov_write_subtitle_tag(pb, track);
2132 else if (track->par->codec_tag == MKTAG('r','t','p',' '))
2133 mov_write_rtp_tag(pb, track);
2134 else if (track->par->codec_tag == MKTAG('t','m','c','d'))
2135 mov_write_tmcd_tag(pb, track);
2136 return update_size(pb, pos);
2139 static int mov_write_ctts_tag(AVIOContext *pb, MOVTrack *track)
2141 MOVStts *ctts_entries;
2142 uint32_t entries = 0;
2146 ctts_entries = av_malloc_array((track->entry + 1), sizeof(*ctts_entries)); /* worst case */
2148 return AVERROR(ENOMEM);
2149 ctts_entries[0].count = 1;
2150 ctts_entries[0].duration = track->cluster[0].cts;
2151 for (i = 1; i < track->entry; i++) {
2152 if (track->cluster[i].cts == ctts_entries[entries].duration) {
2153 ctts_entries[entries].count++; /* compress */
2156 ctts_entries[entries].duration = track->cluster[i].cts;
2157 ctts_entries[entries].count = 1;
2160 entries++; /* last one */
2161 atom_size = 16 + (entries * 8);
2162 avio_wb32(pb, atom_size); /* size */
2163 ffio_wfourcc(pb, "ctts");
2164 avio_wb32(pb, 0); /* version & flags */
2165 avio_wb32(pb, entries); /* entry count */
2166 for (i = 0; i < entries; i++) {
2167 avio_wb32(pb, ctts_entries[i].count);
2168 avio_wb32(pb, ctts_entries[i].duration);
2170 av_free(ctts_entries);
2174 /* Time to sample atom */
2175 static int mov_write_stts_tag(AVIOContext *pb, MOVTrack *track)
2177 MOVStts *stts_entries = NULL;
2178 uint32_t entries = -1;
2182 if (track->par->codec_type == AVMEDIA_TYPE_AUDIO && !track->audio_vbr) {
2183 stts_entries = av_malloc(sizeof(*stts_entries)); /* one entry */
2185 return AVERROR(ENOMEM);
2186 stts_entries[0].count = track->sample_count;
2187 stts_entries[0].duration = 1;
2191 stts_entries = av_malloc_array(track->entry, sizeof(*stts_entries)); /* worst case */
2193 return AVERROR(ENOMEM);
2195 for (i = 0; i < track->entry; i++) {
2196 int duration = get_cluster_duration(track, i);
2197 if (i && duration == stts_entries[entries].duration) {
2198 stts_entries[entries].count++; /* compress */
2201 stts_entries[entries].duration = duration;
2202 stts_entries[entries].count = 1;
2205 entries++; /* last one */
2207 atom_size = 16 + (entries * 8);
2208 avio_wb32(pb, atom_size); /* size */
2209 ffio_wfourcc(pb, "stts");
2210 avio_wb32(pb, 0); /* version & flags */
2211 avio_wb32(pb, entries); /* entry count */
2212 for (i = 0; i < entries; i++) {
2213 avio_wb32(pb, stts_entries[i].count);
2214 avio_wb32(pb, stts_entries[i].duration);
2216 av_free(stts_entries);
2220 static int mov_write_dref_tag(AVIOContext *pb)
2222 avio_wb32(pb, 28); /* size */
2223 ffio_wfourcc(pb, "dref");
2224 avio_wb32(pb, 0); /* version & flags */
2225 avio_wb32(pb, 1); /* entry count */
2227 avio_wb32(pb, 0xc); /* size */
2228 //FIXME add the alis and rsrc atom
2229 ffio_wfourcc(pb, "url ");
2230 avio_wb32(pb, 1); /* version & flags */
2235 static int mov_preroll_write_stbl_atoms(AVIOContext *pb, MOVTrack *track)
2239 int16_t roll_distance;
2240 int group_description_index;
2243 struct sgpd_entry *sgpd_entries = NULL;
2248 const int OPUS_SEEK_PREROLL_MS = 80;
2249 int roll_samples = av_rescale_q(OPUS_SEEK_PREROLL_MS,
2250 (AVRational){1, 1000},
2251 (AVRational){1, 48000});
2254 sgpd_entries = av_malloc_array(track->entry, sizeof(*sgpd_entries));
2256 return AVERROR(ENOMEM);
2259 av_assert0(track->par->codec_id == AV_CODEC_ID_OPUS);
2261 for (i = 0; i < track->entry; i++) {
2262 int roll_samples_remaining = roll_samples;
2264 for (j = i - 1; j >= 0; j--) {
2265 roll_samples_remaining -= get_cluster_duration(track, j);
2267 if (roll_samples_remaining <= 0)
2270 /* We don't have enough preceeding samples to compute a valid
2271 roll_distance here, so this sample can't be independently
2273 if (roll_samples_remaining > 0)
2275 /* Verify distance is a minimum of 2 (60ms) packets and a maximum of
2276 32 (2.5ms) packets. */
2277 av_assert0(distance == 0 || (distance >= 2 && distance <= 32));
2278 if (i && distance == sgpd_entries[entries].roll_distance) {
2279 sgpd_entries[entries].count++;
2282 sgpd_entries[entries].count = 1;
2283 sgpd_entries[entries].roll_distance = distance;
2284 sgpd_entries[entries].group_description_index = distance ? ++group : 0;
2290 av_free(sgpd_entries);
2294 /* Write sgpd tag */
2295 avio_wb32(pb, 24 + (group * 2)); /* size */
2296 ffio_wfourcc(pb, "sgpd");
2297 avio_wb32(pb, 1 << 24); /* fullbox */
2298 ffio_wfourcc(pb, "roll");
2299 avio_wb32(pb, 2); /* default_length */
2300 avio_wb32(pb, group); /* entry_count */
2301 for (i = 0; i < entries; i++) {
2302 if (sgpd_entries[i].group_description_index) {
2303 avio_wb16(pb, -sgpd_entries[i].roll_distance); /* roll_distance */
2307 /* Write sbgp tag */
2308 avio_wb32(pb, 20 + (entries * 8)); /* size */
2309 ffio_wfourcc(pb, "sbgp");
2310 avio_wb32(pb, 0); /* fullbox */
2311 ffio_wfourcc(pb, "roll");
2312 avio_wb32(pb, entries); /* entry_count */
2313 for (i = 0; i < entries; i++) {
2314 avio_wb32(pb, sgpd_entries[i].count); /* sample_count */
2315 avio_wb32(pb, sgpd_entries[i].group_description_index); /* group_description_index */
2318 av_free(sgpd_entries);
2322 static int mov_write_stbl_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
2324 int64_t pos = avio_tell(pb);
2327 avio_wb32(pb, 0); /* size */
2328 ffio_wfourcc(pb, "stbl");
2329 mov_write_stsd_tag(s, pb, mov, track);
2330 mov_write_stts_tag(pb, track);
2331 if ((track->par->codec_type == AVMEDIA_TYPE_VIDEO ||
2332 track->par->codec_tag == MKTAG('r','t','p',' ')) &&
2333 track->has_keyframes && track->has_keyframes < track->entry)
2334 mov_write_stss_tag(pb, track, MOV_SYNC_SAMPLE);
2335 if (track->mode == MODE_MOV && track->flags & MOV_TRACK_STPS)
2336 mov_write_stss_tag(pb, track, MOV_PARTIAL_SYNC_SAMPLE);
2337 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO &&
2338 track->flags & MOV_TRACK_CTTS && track->entry) {
2340 if ((ret = mov_write_ctts_tag(pb, track)) < 0)
2343 mov_write_stsc_tag(pb, track);
2344 mov_write_stsz_tag(pb, track);
2345 mov_write_stco_tag(pb, track);
2346 if (mov->encryption_scheme == MOV_ENC_CENC_AES_CTR) {
2347 ff_mov_cenc_write_stbl_atoms(&track->cenc, pb);
2349 if (track->par->codec_id == AV_CODEC_ID_OPUS) {
2350 mov_preroll_write_stbl_atoms(pb, track);
2352 return update_size(pb, pos);
2355 static int mov_write_dinf_tag(AVIOContext *pb)
2357 int64_t pos = avio_tell(pb);
2358 avio_wb32(pb, 0); /* size */
2359 ffio_wfourcc(pb, "dinf");
2360 mov_write_dref_tag(pb);
2361 return update_size(pb, pos);
2364 static int mov_write_nmhd_tag(AVIOContext *pb)
2367 ffio_wfourcc(pb, "nmhd");
2372 static int mov_write_tcmi_tag(AVIOContext *pb, MOVTrack *track)
2374 int64_t pos = avio_tell(pb);
2375 const char *font = "Lucida Grande";
2376 avio_wb32(pb, 0); /* size */
2377 ffio_wfourcc(pb, "tcmi"); /* timecode media information atom */
2378 avio_wb32(pb, 0); /* version & flags */
2379 avio_wb16(pb, 0); /* text font */
2380 avio_wb16(pb, 0); /* text face */
2381 avio_wb16(pb, 12); /* text size */
2382 avio_wb16(pb, 0); /* (unknown, not in the QT specs...) */
2383 avio_wb16(pb, 0x0000); /* text color (red) */
2384 avio_wb16(pb, 0x0000); /* text color (green) */
2385 avio_wb16(pb, 0x0000); /* text color (blue) */
2386 avio_wb16(pb, 0xffff); /* background color (red) */
2387 avio_wb16(pb, 0xffff); /* background color (green) */
2388 avio_wb16(pb, 0xffff); /* background color (blue) */
2389 avio_w8(pb, strlen(font)); /* font len (part of the pascal string) */
2390 avio_write(pb, font, strlen(font)); /* font name */
2391 return update_size(pb, pos);
2394 static int mov_write_gmhd_tag(AVIOContext *pb, MOVTrack *track)
2396 int64_t pos = avio_tell(pb);
2397 avio_wb32(pb, 0); /* size */
2398 ffio_wfourcc(pb, "gmhd");
2399 avio_wb32(pb, 0x18); /* gmin size */
2400 ffio_wfourcc(pb, "gmin");/* generic media info */
2401 avio_wb32(pb, 0); /* version & flags */
2402 avio_wb16(pb, 0x40); /* graphics mode = */
2403 avio_wb16(pb, 0x8000); /* opColor (r?) */
2404 avio_wb16(pb, 0x8000); /* opColor (g?) */
2405 avio_wb16(pb, 0x8000); /* opColor (b?) */
2406 avio_wb16(pb, 0); /* balance */
2407 avio_wb16(pb, 0); /* reserved */
2410 * This special text atom is required for
2411 * Apple Quicktime chapters. The contents
2412 * don't appear to be documented, so the
2413 * bytes are copied verbatim.
2415 if (track->tag != MKTAG('c','6','0','8')) {
2416 avio_wb32(pb, 0x2C); /* size */
2417 ffio_wfourcc(pb, "text");
2418 avio_wb16(pb, 0x01);
2419 avio_wb32(pb, 0x00);
2420 avio_wb32(pb, 0x00);
2421 avio_wb32(pb, 0x00);
2422 avio_wb32(pb, 0x01);
2423 avio_wb32(pb, 0x00);
2424 avio_wb32(pb, 0x00);
2425 avio_wb32(pb, 0x00);
2426 avio_wb32(pb, 0x00004000);
2427 avio_wb16(pb, 0x0000);
2430 if (track->par->codec_tag == MKTAG('t','m','c','d')) {
2431 int64_t tmcd_pos = avio_tell(pb);
2432 avio_wb32(pb, 0); /* size */
2433 ffio_wfourcc(pb, "tmcd");
2434 mov_write_tcmi_tag(pb, track);
2435 update_size(pb, tmcd_pos);
2437 return update_size(pb, pos);
2440 static int mov_write_smhd_tag(AVIOContext *pb)
2442 avio_wb32(pb, 16); /* size */
2443 ffio_wfourcc(pb, "smhd");
2444 avio_wb32(pb, 0); /* version & flags */
2445 avio_wb16(pb, 0); /* reserved (balance, normally = 0) */
2446 avio_wb16(pb, 0); /* reserved */
2450 static int mov_write_vmhd_tag(AVIOContext *pb)
2452 avio_wb32(pb, 0x14); /* size (always 0x14) */
2453 ffio_wfourcc(pb, "vmhd");
2454 avio_wb32(pb, 0x01); /* version & flags */
2455 avio_wb64(pb, 0); /* reserved (graphics mode = copy) */
2459 static int is_clcp_track(MOVTrack *track)
2461 return track->tag == MKTAG('c','7','0','8') ||
2462 track->tag == MKTAG('c','6','0','8');
2465 static int mov_write_hdlr_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
2467 const char *hdlr, *descr = NULL, *hdlr_type = NULL;
2468 int64_t pos = avio_tell(pb);
2472 descr = "DataHandler";
2475 hdlr = (track->mode == MODE_MOV) ? "mhlr" : "\0\0\0\0";
2476 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
2478 descr = "VideoHandler";
2479 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
2481 descr = "SoundHandler";
2482 } else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE) {
2483 if (is_clcp_track(track)) {
2485 descr = "ClosedCaptionHandler";
2487 if (track->tag == MKTAG('t','x','3','g')) {
2489 } else if (track->tag == MKTAG('m','p','4','s')) {
2494 descr = "SubtitleHandler";
2496 } else if (track->par->codec_tag == MKTAG('r','t','p',' ')) {
2498 descr = "HintHandler";
2499 } else if (track->par->codec_tag == MKTAG('t','m','c','d')) {
2501 descr = "TimeCodeHandler";
2503 av_log(s, AV_LOG_WARNING,
2504 "Unknown hldr_type for %s, writing dummy values\n",
2505 av_fourcc2str(track->par->codec_tag));
2508 // hdlr.name is used by some players to identify the content title
2509 // of the track. So if an alternate handler description is
2510 // specified, use it.
2511 AVDictionaryEntry *t;
2512 t = av_dict_get(track->st->metadata, "handler", NULL, 0);
2513 if (t && utf8len(t->value))
2518 avio_wb32(pb, 0); /* size */
2519 ffio_wfourcc(pb, "hdlr");
2520 avio_wb32(pb, 0); /* Version & flags */
2521 avio_write(pb, hdlr, 4); /* handler */
2522 ffio_wfourcc(pb, hdlr_type); /* handler type */
2523 avio_wb32(pb, 0); /* reserved */
2524 avio_wb32(pb, 0); /* reserved */
2525 avio_wb32(pb, 0); /* reserved */
2526 if (!track || track->mode == MODE_MOV)
2527 avio_w8(pb, strlen(descr)); /* pascal string */
2528 avio_write(pb, descr, strlen(descr)); /* handler description */
2529 if (track && track->mode != MODE_MOV)
2530 avio_w8(pb, 0); /* c string */
2531 return update_size(pb, pos);
2534 static int mov_write_hmhd_tag(AVIOContext *pb)
2536 /* This atom must be present, but leaving the values at zero
2537 * seems harmless. */
2538 avio_wb32(pb, 28); /* size */
2539 ffio_wfourcc(pb, "hmhd");
2540 avio_wb32(pb, 0); /* version, flags */
2541 avio_wb16(pb, 0); /* maxPDUsize */
2542 avio_wb16(pb, 0); /* avgPDUsize */
2543 avio_wb32(pb, 0); /* maxbitrate */
2544 avio_wb32(pb, 0); /* avgbitrate */
2545 avio_wb32(pb, 0); /* reserved */
2549 static int mov_write_minf_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
2551 int64_t pos = avio_tell(pb);
2554 avio_wb32(pb, 0); /* size */
2555 ffio_wfourcc(pb, "minf");
2556 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO)
2557 mov_write_vmhd_tag(pb);
2558 else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
2559 mov_write_smhd_tag(pb);
2560 else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE) {
2561 if (track->tag == MKTAG('t','e','x','t') || is_clcp_track(track)) {
2562 mov_write_gmhd_tag(pb, track);
2564 mov_write_nmhd_tag(pb);
2566 } else if (track->tag == MKTAG('r','t','p',' ')) {
2567 mov_write_hmhd_tag(pb);
2568 } else if (track->tag == MKTAG('t','m','c','d')) {
2569 if (track->mode != MODE_MOV)
2570 mov_write_nmhd_tag(pb);
2572 mov_write_gmhd_tag(pb, track);
2574 if (track->mode == MODE_MOV) /* FIXME: Why do it for MODE_MOV only ? */
2575 mov_write_hdlr_tag(s, pb, NULL);
2576 mov_write_dinf_tag(pb);
2577 if ((ret = mov_write_stbl_tag(s, pb, mov, track)) < 0)
2579 return update_size(pb, pos);
2582 static int mov_write_mdhd_tag(AVIOContext *pb, MOVMuxContext *mov,
2585 int version = track->track_duration < INT32_MAX ? 0 : 1;
2587 if (track->mode == MODE_ISM)
2590 (version == 1) ? avio_wb32(pb, 44) : avio_wb32(pb, 32); /* size */
2591 ffio_wfourcc(pb, "mdhd");
2592 avio_w8(pb, version);
2593 avio_wb24(pb, 0); /* flags */
2595 avio_wb64(pb, track->time);
2596 avio_wb64(pb, track->time);
2598 avio_wb32(pb, track->time); /* creation time */
2599 avio_wb32(pb, track->time); /* modification time */
2601 avio_wb32(pb, track->timescale); /* time scale (sample rate for audio) */
2602 if (!track->entry && mov->mode == MODE_ISM)
2603 (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
2604 else if (!track->entry)
2605 (version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0);
2607 (version == 1) ? avio_wb64(pb, track->track_duration) : avio_wb32(pb, track->track_duration); /* duration */
2608 avio_wb16(pb, track->language); /* language */
2609 avio_wb16(pb, 0); /* reserved (quality) */
2611 if (version != 0 && track->mode == MODE_MOV) {
2612 av_log(NULL, AV_LOG_ERROR,
2613 "FATAL error, file duration too long for timebase, this file will not be\n"
2614 "playable with quicktime. Choose a different timebase or a different\n"
2615 "container format\n");
2621 static int mov_write_mdia_tag(AVFormatContext *s, AVIOContext *pb,
2622 MOVMuxContext *mov, MOVTrack *track)
2624 int64_t pos = avio_tell(pb);
2627 avio_wb32(pb, 0); /* size */
2628 ffio_wfourcc(pb, "mdia");
2629 mov_write_mdhd_tag(pb, mov, track);
2630 mov_write_hdlr_tag(s, pb, track);
2631 if ((ret = mov_write_minf_tag(s, pb, mov, track)) < 0)
2633 return update_size(pb, pos);
2636 /* transformation matrix
2640 static void write_matrix(AVIOContext *pb, int16_t a, int16_t b, int16_t c,
2641 int16_t d, int16_t tx, int16_t ty)
2643 avio_wb32(pb, a << 16); /* 16.16 format */
2644 avio_wb32(pb, b << 16); /* 16.16 format */
2645 avio_wb32(pb, 0); /* u in 2.30 format */
2646 avio_wb32(pb, c << 16); /* 16.16 format */
2647 avio_wb32(pb, d << 16); /* 16.16 format */
2648 avio_wb32(pb, 0); /* v in 2.30 format */
2649 avio_wb32(pb, tx << 16); /* 16.16 format */
2650 avio_wb32(pb, ty << 16); /* 16.16 format */
2651 avio_wb32(pb, 1 << 30); /* w in 2.30 format */
2654 static int mov_write_tkhd_tag(AVIOContext *pb, MOVMuxContext *mov,
2655 MOVTrack *track, AVStream *st)
2657 int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE,
2658 track->timescale, AV_ROUND_UP);
2659 int version = duration < INT32_MAX ? 0 : 1;
2660 int flags = MOV_TKHD_FLAG_IN_MOVIE;
2664 uint32_t *display_matrix = NULL;
2665 int display_matrix_size, i;
2668 if (mov->per_stream_grouping)
2671 group = st->codecpar->codec_type;
2673 display_matrix = (uint32_t*)av_stream_get_side_data(st, AV_PKT_DATA_DISPLAYMATRIX,
2674 &display_matrix_size);
2675 if (display_matrix && display_matrix_size < 9 * sizeof(*display_matrix))
2676 display_matrix = NULL;
2679 if (track->flags & MOV_TRACK_ENABLED)
2680 flags |= MOV_TKHD_FLAG_ENABLED;
2682 if (track->mode == MODE_ISM)
2685 (version == 1) ? avio_wb32(pb, 104) : avio_wb32(pb, 92); /* size */
2686 ffio_wfourcc(pb, "tkhd");
2687 avio_w8(pb, version);
2688 avio_wb24(pb, flags);
2690 avio_wb64(pb, track->time);
2691 avio_wb64(pb, track->time);
2693 avio_wb32(pb, track->time); /* creation time */
2694 avio_wb32(pb, track->time); /* modification time */
2696 avio_wb32(pb, track->track_id); /* track-id */
2697 avio_wb32(pb, 0); /* reserved */
2698 if (!track->entry && mov->mode == MODE_ISM)
2699 (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
2700 else if (!track->entry)
2701 (version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0);
2703 (version == 1) ? avio_wb64(pb, duration) : avio_wb32(pb, duration);
2705 avio_wb32(pb, 0); /* reserved */
2706 avio_wb32(pb, 0); /* reserved */
2707 avio_wb16(pb, 0); /* layer */
2708 avio_wb16(pb, group); /* alternate group) */
2709 /* Volume, only for audio */
2710 if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
2711 avio_wb16(pb, 0x0100);
2714 avio_wb16(pb, 0); /* reserved */
2716 /* Matrix structure */
2717 #if FF_API_OLD_ROTATE_API
2718 if (st && st->metadata) {
2719 AVDictionaryEntry *rot = av_dict_get(st->metadata, "rotate", NULL, 0);
2720 rotation = (rot && rot->value) ? atoi(rot->value) : 0;
2723 if (display_matrix) {
2724 for (i = 0; i < 9; i++)
2725 avio_wb32(pb, display_matrix[i]);
2726 #if FF_API_OLD_ROTATE_API
2727 } else if (rotation == 90) {
2728 write_matrix(pb, 0, 1, -1, 0, track->par->height, 0);
2729 } else if (rotation == 180) {
2730 write_matrix(pb, -1, 0, 0, -1, track->par->width, track->par->height);
2731 } else if (rotation == 270) {
2732 write_matrix(pb, 0, -1, 1, 0, 0, track->par->width);
2735 write_matrix(pb, 1, 0, 0, 1, 0, 0);
2737 /* Track width and height, for visual only */
2738 if (st && (track->par->codec_type == AVMEDIA_TYPE_VIDEO ||
2739 track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)) {
2740 int64_t track_width_1616;
2741 if (track->mode == MODE_MOV) {
2742 track_width_1616 = track->par->width * 0x10000ULL;
2744 track_width_1616 = av_rescale(st->sample_aspect_ratio.num,
2745 track->par->width * 0x10000LL,
2746 st->sample_aspect_ratio.den);
2747 if (!track_width_1616 ||
2748 track->height != track->par->height ||
2749 track_width_1616 > UINT32_MAX)
2750 track_width_1616 = track->par->width * 0x10000ULL;
2752 if (track_width_1616 > UINT32_MAX) {
2753 av_log(mov->fc, AV_LOG_WARNING, "track width is too large\n");
2754 track_width_1616 = 0;
2756 avio_wb32(pb, track_width_1616);
2757 if (track->height > 0xFFFF) {
2758 av_log(mov->fc, AV_LOG_WARNING, "track height is too large\n");
2761 avio_wb32(pb, track->height * 0x10000U);
2769 static int mov_write_tapt_tag(AVIOContext *pb, MOVTrack *track)
2771 int32_t width = av_rescale(track->par->sample_aspect_ratio.num, track->par->width,
2772 track->par->sample_aspect_ratio.den);
2774 int64_t pos = avio_tell(pb);
2776 avio_wb32(pb, 0); /* size */
2777 ffio_wfourcc(pb, "tapt");
2780 ffio_wfourcc(pb, "clef");
2782 avio_wb32(pb, width << 16);
2783 avio_wb32(pb, track->par->height << 16);
2786 ffio_wfourcc(pb, "prof");
2788 avio_wb32(pb, width << 16);
2789 avio_wb32(pb, track->par->height << 16);
2792 ffio_wfourcc(pb, "enof");
2794 avio_wb32(pb, track->par->width << 16);
2795 avio_wb32(pb, track->par->height << 16);
2797 return update_size(pb, pos);
2800 // This box seems important for the psp playback ... without it the movie seems to hang
2801 static int mov_write_edts_tag(AVIOContext *pb, MOVMuxContext *mov,
2804 int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE,
2805 track->timescale, AV_ROUND_UP);
2806 int version = duration < INT32_MAX ? 0 : 1;
2807 int entry_size, entry_count, size;
2808 int64_t delay, start_ct = track->start_cts;
2809 int64_t start_dts = track->start_dts;
2812 if (start_dts != track->cluster[0].dts || start_ct != track->cluster[0].cts) {
2814 av_log(mov->fc, AV_LOG_DEBUG,
2815 "EDTS using dts:%"PRId64" cts:%d instead of dts:%"PRId64" cts:%"PRId64" tid:%d\n",
2816 track->cluster[0].dts, track->cluster[0].cts,
2817 start_dts, start_ct, track->track_id);
2818 start_dts = track->cluster[0].dts;
2819 start_ct = track->cluster[0].cts;
2823 delay = av_rescale_rnd(start_dts + start_ct, MOV_TIMESCALE,
2824 track->timescale, AV_ROUND_DOWN);
2825 version |= delay < INT32_MAX ? 0 : 1;
2827 entry_size = (version == 1) ? 20 : 12;
2828 entry_count = 1 + (delay > 0);
2829 size = 24 + entry_count * entry_size;
2831 /* write the atom data */
2832 avio_wb32(pb, size);
2833 ffio_wfourcc(pb, "edts");
2834 avio_wb32(pb, size - 8);
2835 ffio_wfourcc(pb, "elst");
2836 avio_w8(pb, version);
2837 avio_wb24(pb, 0); /* flags */
2839 avio_wb32(pb, entry_count);
2840 if (delay > 0) { /* add an empty edit to delay presentation */
2841 /* In the positive delay case, the delay includes the cts
2842 * offset, and the second edit list entry below trims out
2843 * the same amount from the actual content. This makes sure
2844 * that the offset last sample is included in the edit
2845 * list duration as well. */
2847 avio_wb64(pb, delay);
2850 avio_wb32(pb, delay);
2853 avio_wb32(pb, 0x00010000);
2855 /* Avoid accidentally ending up with start_ct = -1 which has got a
2856 * special meaning. Normally start_ct should end up positive or zero
2857 * here, but use FFMIN in case dts is a small positive integer
2858 * rounded to 0 when represented in MOV_TIMESCALE units. */
2859 av_assert0(av_rescale_rnd(start_dts, MOV_TIMESCALE, track->timescale, AV_ROUND_DOWN) <= 0);
2860 start_ct = -FFMIN(start_dts, 0);
2861 /* Note, this delay is calculated from the pts of the first sample,
2862 * ensuring that we don't reduce the duration for cases with
2867 /* For fragmented files, we don't know the full length yet. Setting
2868 * duration to 0 allows us to only specify the offset, including
2869 * the rest of the content (from all future fragments) without specifying
2870 * an explicit duration. */
2871 if (mov->flags & FF_MOV_FLAG_FRAGMENT)
2876 avio_wb64(pb, duration);
2877 avio_wb64(pb, start_ct);
2879 avio_wb32(pb, duration);
2880 avio_wb32(pb, start_ct);
2882 avio_wb32(pb, 0x00010000);
2886 static int mov_write_tref_tag(AVIOContext *pb, MOVTrack *track)
2888 avio_wb32(pb, 20); // size
2889 ffio_wfourcc(pb, "tref");
2890 avio_wb32(pb, 12); // size (subatom)
2891 avio_wl32(pb, track->tref_tag);
2892 avio_wb32(pb, track->tref_id);
2896 // goes at the end of each track! ... Critical for PSP playback ("Incompatible data" without it)
2897 static int mov_write_uuid_tag_psp(AVIOContext *pb, MOVTrack *mov)
2899 avio_wb32(pb, 0x34); /* size ... reports as 28 in mp4box! */
2900 ffio_wfourcc(pb, "uuid");
2901 ffio_wfourcc(pb, "USMT");
2902 avio_wb32(pb, 0x21d24fce);
2903 avio_wb32(pb, 0xbb88695c);
2904 avio_wb32(pb, 0xfac9c740);
2905 avio_wb32(pb, 0x1c); // another size here!
2906 ffio_wfourcc(pb, "MTDT");
2907 avio_wb32(pb, 0x00010012);
2908 avio_wb32(pb, 0x0a);
2909 avio_wb32(pb, 0x55c40000);
2915 static int mov_write_udta_sdp(AVIOContext *pb, MOVTrack *track)
2917 AVFormatContext *ctx = track->rtp_ctx;
2918 char buf[1000] = "";
2921 ff_sdp_write_media(buf, sizeof(buf), ctx->streams[0], track->src_track,
2922 NULL, NULL, 0, 0, ctx);
2923 av_strlcatf(buf, sizeof(buf), "a=control:streamid=%d\r\n", track->track_id);
2926 avio_wb32(pb, len + 24);
2927 ffio_wfourcc(pb, "udta");
2928 avio_wb32(pb, len + 16);
2929 ffio_wfourcc(pb, "hnti");
2930 avio_wb32(pb, len + 8);
2931 ffio_wfourcc(pb, "sdp ");
2932 avio_write(pb, buf, len);
2936 static int mov_write_track_metadata(AVIOContext *pb, AVStream *st,
2937 const char *tag, const char *str)
2939 int64_t pos = avio_tell(pb);
2940 AVDictionaryEntry *t = av_dict_get(st->metadata, str, NULL, 0);
2941 if (!t || !utf8len(t->value))
2944 avio_wb32(pb, 0); /* size */
2945 ffio_wfourcc(pb, tag); /* type */
2946 avio_write(pb, t->value, strlen(t->value)); /* UTF8 string value */
2947 return update_size(pb, pos);
2950 static int mov_write_track_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
2953 AVIOContext *pb_buf;
2960 ret = avio_open_dyn_buf(&pb_buf);
2964 if (mov->mode & MODE_MP4)
2965 mov_write_track_metadata(pb_buf, st, "name", "title");
2967 if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) {
2968 avio_wb32(pb, size + 8);
2969 ffio_wfourcc(pb, "udta");
2970 avio_write(pb, buf, size);
2977 static int mov_write_trak_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov,
2978 MOVTrack *track, AVStream *st)
2980 int64_t pos = avio_tell(pb);
2981 int entry_backup = track->entry;
2982 int chunk_backup = track->chunkCount;
2985 /* If we want to have an empty moov, but some samples already have been
2986 * buffered (delay_moov), pretend that no samples have been written yet. */
2987 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV)
2988 track->chunkCount = track->entry = 0;
2990 avio_wb32(pb, 0); /* size */
2991 ffio_wfourcc(pb, "trak");
2992 mov_write_tkhd_tag(pb, mov, track, st);
2994 av_assert2(mov->use_editlist >= 0);
2996 if (track->start_dts != AV_NOPTS_VALUE) {
2997 if (mov->use_editlist)
2998 mov_write_edts_tag(pb, mov, track); // PSP Movies and several other cases require edts box
2999 else if ((track->entry && track->cluster[0].dts) || track->mode == MODE_PSP || is_clcp_track(track))
3000 av_log(mov->fc, AV_LOG_WARNING,
3001 "Not writing any edit list even though one would have been required\n");
3004 if (track->tref_tag)
3005 mov_write_tref_tag(pb, track);
3007 if ((ret = mov_write_mdia_tag(s, pb, mov, track)) < 0)
3009 if (track->mode == MODE_PSP)
3010 mov_write_uuid_tag_psp(pb, track); // PSP Movies require this uuid box
3011 if (track->tag == MKTAG('r','t','p',' '))
3012 mov_write_udta_sdp(pb, track);
3013 if (track->mode == MODE_MOV) {
3014 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
3015 double sample_aspect_ratio = av_q2d(st->sample_aspect_ratio);
3016 if (st->sample_aspect_ratio.num && 1.0 != sample_aspect_ratio) {
3017 mov_write_tapt_tag(pb, track);
3020 if (is_clcp_track(track) && st->sample_aspect_ratio.num) {
3021 mov_write_tapt_tag(pb, track);
3024 mov_write_track_udta_tag(pb, mov, st);
3025 track->entry = entry_backup;
3026 track->chunkCount = chunk_backup;
3027 return update_size(pb, pos);
3030 static int mov_write_iods_tag(AVIOContext *pb, MOVMuxContext *mov)
3032 int i, has_audio = 0, has_video = 0;
3033 int64_t pos = avio_tell(pb);
3034 int audio_profile = mov->iods_audio_profile;
3035 int video_profile = mov->iods_video_profile;
3036 for (i = 0; i < mov->nb_streams; i++) {
3037 if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
3038 has_audio |= mov->tracks[i].par->codec_type == AVMEDIA_TYPE_AUDIO;
3039 has_video |= mov->tracks[i].par->codec_type == AVMEDIA_TYPE_VIDEO;
3042 if (audio_profile < 0)
3043 audio_profile = 0xFF - has_audio;
3044 if (video_profile < 0)
3045 video_profile = 0xFF - has_video;
3046 avio_wb32(pb, 0x0); /* size */
3047 ffio_wfourcc(pb, "iods");
3048 avio_wb32(pb, 0); /* version & flags */
3049 put_descr(pb, 0x10, 7);
3050 avio_wb16(pb, 0x004f);
3053 avio_w8(pb, audio_profile);
3054 avio_w8(pb, video_profile);
3056 return update_size(pb, pos);
3059 static int mov_write_trex_tag(AVIOContext *pb, MOVTrack *track)
3061 avio_wb32(pb, 0x20); /* size */
3062 ffio_wfourcc(pb, "trex");
3063 avio_wb32(pb, 0); /* version & flags */
3064 avio_wb32(pb, track->track_id); /* track ID */
3065 avio_wb32(pb, 1); /* default sample description index */
3066 avio_wb32(pb, 0); /* default sample duration */
3067 avio_wb32(pb, 0); /* default sample size */
3068 avio_wb32(pb, 0); /* default sample flags */
3072 static int mov_write_mvex_tag(AVIOContext *pb, MOVMuxContext *mov)
3074 int64_t pos = avio_tell(pb);
3076 avio_wb32(pb, 0x0); /* size */
3077 ffio_wfourcc(pb, "mvex");
3078 for (i = 0; i < mov->nb_streams; i++)
3079 mov_write_trex_tag(pb, &mov->tracks[i]);
3080 return update_size(pb, pos);
3083 static int mov_write_mvhd_tag(AVIOContext *pb, MOVMuxContext *mov)
3085 int max_track_id = 1, i;
3086 int64_t max_track_len = 0;
3089 for (i = 0; i < mov->nb_streams; i++) {
3090 if (mov->tracks[i].entry > 0 && mov->tracks[i].timescale) {
3091 int64_t max_track_len_temp = av_rescale_rnd(mov->tracks[i].track_duration,
3093 mov->tracks[i].timescale,
3095 if (max_track_len < max_track_len_temp)
3096 max_track_len = max_track_len_temp;
3097 if (max_track_id < mov->tracks[i].track_id)
3098 max_track_id = mov->tracks[i].track_id;
3101 /* If using delay_moov, make sure the output is the same as if no
3102 * samples had been written yet. */
3103 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
3108 version = max_track_len < UINT32_MAX ? 0 : 1;
3109 avio_wb32(pb, version == 1 ? 120 : 108); /* size */
3111 ffio_wfourcc(pb, "mvhd");
3112 avio_w8(pb, version);
3113 avio_wb24(pb, 0); /* flags */
3115 avio_wb64(pb, mov->time);
3116 avio_wb64(pb, mov->time);
3118 avio_wb32(pb, mov->time); /* creation time */
3119 avio_wb32(pb, mov->time); /* modification time */
3121 avio_wb32(pb, MOV_TIMESCALE);
3122 (version == 1) ? avio_wb64(pb, max_track_len) : avio_wb32(pb, max_track_len); /* duration of longest track */
3124 avio_wb32(pb, 0x00010000); /* reserved (preferred rate) 1.0 = normal */
3125 avio_wb16(pb, 0x0100); /* reserved (preferred volume) 1.0 = normal */
3126 avio_wb16(pb, 0); /* reserved */
3127 avio_wb32(pb, 0); /* reserved */
3128 avio_wb32(pb, 0); /* reserved */
3130 /* Matrix structure */
3131 write_matrix(pb, 1, 0, 0, 1, 0, 0);
3133 avio_wb32(pb, 0); /* reserved (preview time) */
3134 avio_wb32(pb, 0); /* reserved (preview duration) */
3135 avio_wb32(pb, 0); /* reserved (poster time) */
3136 avio_wb32(pb, 0); /* reserved (selection time) */
3137 avio_wb32(pb, 0); /* reserved (selection duration) */
3138 avio_wb32(pb, 0); /* reserved (current time) */
3139 avio_wb32(pb, max_track_id + 1); /* Next track id */
3143 static int mov_write_itunes_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov,
3146 avio_wb32(pb, 33); /* size */
3147 ffio_wfourcc(pb, "hdlr");
3150 ffio_wfourcc(pb, "mdir");
3151 ffio_wfourcc(pb, "appl");
3158 /* helper function to write a data tag with the specified string as data */
3159 static int mov_write_string_data_tag(AVIOContext *pb, const char *data, int lang, int long_style)
3162 int size = 16 + strlen(data);
3163 avio_wb32(pb, size); /* size */
3164 ffio_wfourcc(pb, "data");
3167 avio_write(pb, data, strlen(data));
3171 lang = ff_mov_iso639_to_lang("und", 1);
3172 avio_wb16(pb, strlen(data)); /* string length */
3173 avio_wb16(pb, lang);
3174 avio_write(pb, data, strlen(data));
3175 return strlen(data) + 4;
3179 static int mov_write_string_tag(AVIOContext *pb, const char *name,
3180 const char *value, int lang, int long_style)
3183 if (value && value[0]) {
3184 int64_t pos = avio_tell(pb);
3185 avio_wb32(pb, 0); /* size */
3186 ffio_wfourcc(pb, name);
3187 mov_write_string_data_tag(pb, value, lang, long_style);
3188 size = update_size(pb, pos);
3193 static AVDictionaryEntry *get_metadata_lang(AVFormatContext *s,
3194 const char *tag, int *lang)
3197 AVDictionaryEntry *t, *t2 = NULL;
3202 if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
3205 len = strlen(t->key);
3206 snprintf(tag2, sizeof(tag2), "%s-", tag);
3207 while ((t2 = av_dict_get(s->metadata, tag2, t2, AV_DICT_IGNORE_SUFFIX))) {
3208 len2 = strlen(t2->key);
3209 if (len2 == len + 4 && !strcmp(t->value, t2->value)
3210 && (l = ff_mov_iso639_to_lang(&t2->key[len2 - 3], 1)) >= 0) {
3218 static int mov_write_string_metadata(AVFormatContext *s, AVIOContext *pb,
3219 const char *name, const char *tag,
3223 AVDictionaryEntry *t = get_metadata_lang(s, tag, &lang);
3226 return mov_write_string_tag(pb, name, t->value, lang, long_style);
3229 /* iTunes bpm number */
3230 static int mov_write_tmpo_tag(AVIOContext *pb, AVFormatContext *s)
3232 AVDictionaryEntry *t = av_dict_get(s->metadata, "tmpo", NULL, 0);
3233 int size = 0, tmpo = t ? atoi(t->value) : 0;
3236 avio_wb32(pb, size);
3237 ffio_wfourcc(pb, "tmpo");
3238 avio_wb32(pb, size-8); /* size */
3239 ffio_wfourcc(pb, "data");
3240 avio_wb32(pb, 0x15); //type specifier
3242 avio_wb16(pb, tmpo); // data
3247 /* 3GPP TS 26.244 */
3248 static int mov_write_loci_tag(AVFormatContext *s, AVIOContext *pb)
3251 int64_t pos = avio_tell(pb);
3252 double latitude, longitude, altitude;
3253 int32_t latitude_fix, longitude_fix, altitude_fix;
3254 AVDictionaryEntry *t = get_metadata_lang(s, "location", &lang);
3255 const char *ptr, *place = "";
3257 static const char *astronomical_body = "earth";
3262 longitude = strtod(ptr, &end);
3264 av_log(s, AV_LOG_WARNING, "malformed location metadata\n");
3268 latitude = strtod(ptr, &end);
3270 av_log(s, AV_LOG_WARNING, "malformed location metadata\n");
3274 altitude = strtod(ptr, &end);
3275 /* If no altitude was present, the default 0 should be fine */
3279 latitude_fix = (int32_t) ((1 << 16) * latitude);
3280 longitude_fix = (int32_t) ((1 << 16) * longitude);
3281 altitude_fix = (int32_t) ((1 << 16) * altitude);
3283 avio_wb32(pb, 0); /* size */
3284 ffio_wfourcc(pb, "loci"); /* type */
3285 avio_wb32(pb, 0); /* version + flags */
3286 avio_wb16(pb, lang);
3287 avio_write(pb, place, strlen(place) + 1);
3288 avio_w8(pb, 0); /* role of place (0 == shooting location, 1 == real location, 2 == fictional location) */
3289 avio_wb32(pb, latitude_fix);
3290 avio_wb32(pb, longitude_fix);
3291 avio_wb32(pb, altitude_fix);
3292 avio_write(pb, astronomical_body, strlen(astronomical_body) + 1);
3293 avio_w8(pb, 0); /* additional notes, null terminated string */
3295 return update_size(pb, pos);
3298 /* iTunes track or disc number */
3299 static int mov_write_trkn_tag(AVIOContext *pb, MOVMuxContext *mov,
3300 AVFormatContext *s, int disc)
3302 AVDictionaryEntry *t = av_dict_get(s->metadata,
3303 disc ? "disc" : "track",
3305 int size = 0, track = t ? atoi(t->value) : 0;
3308 char *slash = strchr(t->value, '/');
3310 tracks = atoi(slash + 1);
3311 avio_wb32(pb, 32); /* size */
3312 ffio_wfourcc(pb, disc ? "disk" : "trkn");
3313 avio_wb32(pb, 24); /* size */
3314 ffio_wfourcc(pb, "data");
3315 avio_wb32(pb, 0); // 8 bytes empty
3317 avio_wb16(pb, 0); // empty
3318 avio_wb16(pb, track); // track / disc number
3319 avio_wb16(pb, tracks); // total track / disc number
3320 avio_wb16(pb, 0); // empty
3326 static int mov_write_int8_metadata(AVFormatContext *s, AVIOContext *pb,
3327 const char *name, const char *tag,
3330 AVDictionaryEntry *t = NULL;
3332 int size = 24 + len;
3334 if (len != 1 && len != 4)
3337 if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
3339 num = atoi(t->value);
3341 avio_wb32(pb, size);
3342 ffio_wfourcc(pb, name);
3343 avio_wb32(pb, size - 8);
3344 ffio_wfourcc(pb, "data");
3345 avio_wb32(pb, 0x15);
3347 if (len==4) avio_wb32(pb, num);
3348 else avio_w8 (pb, num);
3353 /* iTunes meta data list */
3354 static int mov_write_ilst_tag(AVIOContext *pb, MOVMuxContext *mov,
3357 int64_t pos = avio_tell(pb);
3358 avio_wb32(pb, 0); /* size */
3359 ffio_wfourcc(pb, "ilst");
3360 mov_write_string_metadata(s, pb, "\251nam", "title" , 1);
3361 mov_write_string_metadata(s, pb, "\251ART", "artist" , 1);
3362 mov_write_string_metadata(s, pb, "aART", "album_artist", 1);
3363 mov_write_string_metadata(s, pb, "\251wrt", "composer" , 1);
3364 mov_write_string_metadata(s, pb, "\251alb", "album" , 1);
3365 mov_write_string_metadata(s, pb, "\251day", "date" , 1);
3366 if (!mov_write_string_metadata(s, pb, "\251too", "encoding_tool", 1)) {
3367 if (!(s->flags & AVFMT_FLAG_BITEXACT))
3368 mov_write_string_tag(pb, "\251too", LIBAVFORMAT_IDENT, 0, 1);
3370 mov_write_string_metadata(s, pb, "\251cmt", "comment" , 1);
3371 mov_write_string_metadata(s, pb, "\251gen", "genre" , 1);
3372 mov_write_string_metadata(s, pb, "\251cpy", "copyright", 1);
3373 mov_write_string_metadata(s, pb, "\251grp", "grouping" , 1);
3374 mov_write_string_metadata(s, pb, "\251lyr", "lyrics" , 1);
3375 mov_write_string_metadata(s, pb, "desc", "description",1);
3376 mov_write_string_metadata(s, pb, "ldes", "synopsis" , 1);
3377 mov_write_string_metadata(s, pb, "tvsh", "show" , 1);
3378 mov_write_string_metadata(s, pb, "tven", "episode_id",1);
3379 mov_write_string_metadata(s, pb, "tvnn", "network" , 1);
3380 mov_write_int8_metadata (s, pb, "tves", "episode_sort",4);
3381 mov_write_int8_metadata (s, pb, "tvsn", "season_number",4);
3382 mov_write_int8_metadata (s, pb, "stik", "media_type",1);
3383 mov_write_int8_metadata (s, pb, "hdvd", "hd_video", 1);
3384 mov_write_int8_metadata (s, pb, "pgap", "gapless_playback",1);
3385 mov_write_int8_metadata (s, pb, "cpil", "compilation", 1);
3386 mov_write_trkn_tag(pb, mov, s, 0); // track number
3387 mov_write_trkn_tag(pb, mov, s, 1); // disc number
3388 mov_write_tmpo_tag(pb, s);
3389 return update_size(pb, pos);
3392 static int mov_write_mdta_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov,
3395 avio_wb32(pb, 33); /* size */
3396 ffio_wfourcc(pb, "hdlr");
3399 ffio_wfourcc(pb, "mdta");
3407 static int mov_write_mdta_keys_tag(AVIOContext *pb, MOVMuxContext *mov,
3410 AVDictionaryEntry *t = NULL;
3411 int64_t pos = avio_tell(pb);
3412 int64_t curpos, entry_pos;
3415 avio_wb32(pb, 0); /* size */
3416 ffio_wfourcc(pb, "keys");
3418 entry_pos = avio_tell(pb);
3419 avio_wb32(pb, 0); /* entry count */
3421 while (t = av_dict_get(s->metadata, "", t, AV_DICT_IGNORE_SUFFIX)) {
3422 avio_wb32(pb, strlen(t->key) + 8);
3423 ffio_wfourcc(pb, "mdta");
3424 avio_write(pb, t->key, strlen(t->key));
3427 curpos = avio_tell(pb);
3428 avio_seek(pb, entry_pos, SEEK_SET);
3429 avio_wb32(pb, count); // rewrite entry count
3430 avio_seek(pb, curpos, SEEK_SET);
3432 return update_size(pb, pos);
3435 static int mov_write_mdta_ilst_tag(AVIOContext *pb, MOVMuxContext *mov,
3438 AVDictionaryEntry *t = NULL;
3439 int64_t pos = avio_tell(pb);
3440 int count = 1; /* keys are 1-index based */
3442 avio_wb32(pb, 0); /* size */
3443 ffio_wfourcc(pb, "ilst");
3445 while (t = av_dict_get(s->metadata, "", t, AV_DICT_IGNORE_SUFFIX)) {
3446 int64_t entry_pos = avio_tell(pb);
3447 avio_wb32(pb, 0); /* size */
3448 avio_wb32(pb, count); /* key */
3449 mov_write_string_data_tag(pb, t->value, 0, 1);
3450 update_size(pb, entry_pos);
3453 return update_size(pb, pos);
3456 /* meta data tags */
3457 static int mov_write_meta_tag(AVIOContext *pb, MOVMuxContext *mov,
3461 int64_t pos = avio_tell(pb);
3462 avio_wb32(pb, 0); /* size */
3463 ffio_wfourcc(pb, "meta");
3465 if (mov->flags & FF_MOV_FLAG_USE_MDTA) {
3466 mov_write_mdta_hdlr_tag(pb, mov, s);
3467 mov_write_mdta_keys_tag(pb, mov, s);
3468 mov_write_mdta_ilst_tag(pb, mov, s);
3471 /* iTunes metadata tag */
3472 mov_write_itunes_hdlr_tag(pb, mov, s);
3473 mov_write_ilst_tag(pb, mov, s);
3475 size = update_size(pb, pos);
3479 static int mov_write_raw_metadata_tag(AVFormatContext *s, AVIOContext *pb,
3480 const char *name, const char *key)
3483 AVDictionaryEntry *t;
3485 if (!(t = av_dict_get(s->metadata, key, NULL, 0)))
3488 len = strlen(t->value);
3491 avio_wb32(pb, size);
3492 ffio_wfourcc(pb, name);
3493 avio_write(pb, t->value, len);
3499 static int ascii_to_wc(AVIOContext *pb, const uint8_t *b)
3503 GET_UTF8(val, *b++, return -1;)
3506 avio_wb16(pb, 0x00);
3510 static uint16_t language_code(const char *str)
3512 return (((str[0] - 0x60) & 0x1F) << 10) +
3513 (((str[1] - 0x60) & 0x1F) << 5) +
3514 (( str[2] - 0x60) & 0x1F);
3517 static int mov_write_3gp_udta_tag(AVIOContext *pb, AVFormatContext *s,
3518 const char *tag, const char *str)
3520 int64_t pos = avio_tell(pb);
3521 AVDictionaryEntry *t = av_dict_get(s->metadata, str, NULL, 0);
3522 if (!t || !utf8len(t->value))
3524 avio_wb32(pb, 0); /* size */
3525 ffio_wfourcc(pb, tag); /* type */
3526 avio_wb32(pb, 0); /* version + flags */
3527 if (!strcmp(tag, "yrrc"))
3528 avio_wb16(pb, atoi(t->value));
3530 avio_wb16(pb, language_code("eng")); /* language */
3531 avio_write(pb, t->value, strlen(t->value) + 1); /* UTF8 string value */
3532 if (!strcmp(tag, "albm") &&
3533 (t = av_dict_get(s->metadata, "track", NULL, 0)))
3534 avio_w8(pb, atoi(t->value));
3536 return update_size(pb, pos);
3539 static int mov_write_chpl_tag(AVIOContext *pb, AVFormatContext *s)
3541 int64_t pos = avio_tell(pb);
3542 int i, nb_chapters = FFMIN(s->nb_chapters, 255);
3544 avio_wb32(pb, 0); // size
3545 ffio_wfourcc(pb, "chpl");
3546 avio_wb32(pb, 0x01000000); // version + flags
3547 avio_wb32(pb, 0); // unknown
3548 avio_w8(pb, nb_chapters);
3550 for (i = 0; i < nb_chapters; i++) {
3551 AVChapter *c = s->chapters[i];
3552 AVDictionaryEntry *t;
3553 avio_wb64(pb, av_rescale_q(c->start, c->time_base, (AVRational){1,10000000}));
3555 if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
3556 int len = FFMIN(strlen(t->value), 255);
3558 avio_write(pb, t->value, len);
3562 return update_size(pb, pos);
3565 static int mov_write_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
3568 AVIOContext *pb_buf;
3572 ret = avio_open_dyn_buf(&pb_buf);
3576 if (mov->mode & MODE_3GP) {
3577 mov_write_3gp_udta_tag(pb_buf, s, "perf", "artist");
3578 mov_write_3gp_udta_tag(pb_buf, s, "titl", "title");
3579 mov_write_3gp_udta_tag(pb_buf, s, "auth", "author");
3580 mov_write_3gp_udta_tag(pb_buf, s, "gnre", "genre");
3581 mov_write_3gp_udta_tag(pb_buf, s, "dscp", "comment");
3582 mov_write_3gp_udta_tag(pb_buf, s, "albm", "album");
3583 mov_write_3gp_udta_tag(pb_buf, s, "cprt", "copyright");
3584 mov_write_3gp_udta_tag(pb_buf, s, "yrrc", "date");
3585 mov_write_loci_tag(s, pb_buf);
3586 } 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
3587 mov_write_string_metadata(s, pb_buf, "\251ART", "artist", 0);
3588 mov_write_string_metadata(s, pb_buf, "\251nam", "title", 0);
3589 mov_write_string_metadata(s, pb_buf, "\251aut", "author", 0);
3590 mov_write_string_metadata(s, pb_buf, "\251alb", "album", 0);
3591 mov_write_string_metadata(s, pb_buf, "\251day", "date", 0);
3592 mov_write_string_metadata(s, pb_buf, "\251swr", "encoder", 0);
3593 // currently ignored by mov.c
3594 mov_write_string_metadata(s, pb_buf, "\251des", "comment", 0);
3595 // add support for libquicktime, this atom is also actually read by mov.c
3596 mov_write_string_metadata(s, pb_buf, "\251cmt", "comment", 0);
3597 mov_write_string_metadata(s, pb_buf, "\251gen", "genre", 0);
3598 mov_write_string_metadata(s, pb_buf, "\251cpy", "copyright", 0);
3599 mov_write_string_metadata(s, pb_buf, "\251mak", "make", 0);
3600 mov_write_string_metadata(s, pb_buf, "\251mod", "model", 0);
3601 mov_write_string_metadata(s, pb_buf, "\251xyz", "location", 0);
3602 mov_write_raw_metadata_tag(s, pb_buf, "XMP_", "xmp");
3604 /* iTunes meta data */
3605 mov_write_meta_tag(pb_buf, mov, s);
3606 mov_write_loci_tag(s, pb_buf);
3609 if (s->nb_chapters && !(mov->flags & FF_MOV_FLAG_DISABLE_CHPL))
3610 mov_write_chpl_tag(pb_buf, s);
3612 if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) {
3613 avio_wb32(pb, size + 8);
3614 ffio_wfourcc(pb, "udta");
3615 avio_write(pb, buf, size);
3622 static void mov_write_psp_udta_tag(AVIOContext *pb,
3623 const char *str, const char *lang, int type)
3625 int len = utf8len(str) + 1;
3628 avio_wb16(pb, len * 2 + 10); /* size */
3629 avio_wb32(pb, type); /* type */
3630 avio_wb16(pb, language_code(lang)); /* language */
3631 avio_wb16(pb, 0x01); /* ? */
3632 ascii_to_wc(pb, str);
3635 static int mov_write_uuidusmt_tag(AVIOContext *pb, AVFormatContext *s)
3637 AVDictionaryEntry *title = av_dict_get(s->metadata, "title", NULL, 0);
3641 pos = avio_tell(pb);
3642 avio_wb32(pb, 0); /* size placeholder*/
3643 ffio_wfourcc(pb, "uuid");
3644 ffio_wfourcc(pb, "USMT");
3645 avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
3646 avio_wb32(pb, 0xbb88695c);
3647 avio_wb32(pb, 0xfac9c740);
3649 pos2 = avio_tell(pb);
3650 avio_wb32(pb, 0); /* size placeholder*/
3651 ffio_wfourcc(pb, "MTDT");
3655 avio_wb16(pb, 0x0C); /* size */
3656 avio_wb32(pb, 0x0B); /* type */
3657 avio_wb16(pb, language_code("und")); /* language */
3658 avio_wb16(pb, 0x0); /* ? */
3659 avio_wb16(pb, 0x021C); /* data */
3661 if (!(s->flags & AVFMT_FLAG_BITEXACT))
3662 mov_write_psp_udta_tag(pb, LIBAVCODEC_IDENT, "eng", 0x04);
3663 mov_write_psp_udta_tag(pb, title->value, "eng", 0x01);
3664 mov_write_psp_udta_tag(pb, "2006/04/01 11:11:11", "und", 0x03);
3666 update_size(pb, pos2);
3667 return update_size(pb, pos);
3673 static void build_chunks(MOVTrack *trk)
3676 MOVIentry *chunk = &trk->cluster[0];
3677 uint64_t chunkSize = chunk->size;
3678 chunk->chunkNum = 1;
3679 if (trk->chunkCount)
3681 trk->chunkCount = 1;
3682 for (i = 1; i<trk->entry; i++){
3683 if (chunk->pos + chunkSize == trk->cluster[i].pos &&
3684 chunkSize + trk->cluster[i].size < (1<<20)){
3685 chunkSize += trk->cluster[i].size;
3686 chunk->samples_in_chunk += trk->cluster[i].entries;
3688 trk->cluster[i].chunkNum = chunk->chunkNum+1;
3689 chunk=&trk->cluster[i];
3690 chunkSize = chunk->size;
3697 * Assign track ids. If option "use_stream_ids_as_track_ids" is set,
3698 * the stream ids are used as track ids.
3700 * This assumes mov->tracks and s->streams are in the same order and
3701 * there are no gaps in either of them (so mov->tracks[n] refers to
3704 * As an exception, there can be more entries in
3705 * s->streams than in mov->tracks, in which case new track ids are
3706 * generated (starting after the largest found stream id).
3708 static int mov_setup_track_ids(MOVMuxContext *mov, AVFormatContext *s)
3712 if (mov->track_ids_ok)
3715 if (mov->use_stream_ids_as_track_ids) {
3716 int next_generated_track_id = 0;
3717 for (i = 0; i < s->nb_streams; i++) {
3718 if (s->streams[i]->id > next_generated_track_id)
3719 next_generated_track_id = s->streams[i]->id;
3722 for (i = 0; i < mov->nb_streams; i++) {
3723 if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
3726 mov->tracks[i].track_id = i >= s->nb_streams ? ++next_generated_track_id : s->streams[i]->id;
3729 for (i = 0; i < mov->nb_streams; i++) {
3730 if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
3733 mov->tracks[i].track_id = i + 1;
3737 mov->track_ids_ok = 1;
3742 static int mov_write_moov_tag(AVIOContext *pb, MOVMuxContext *mov,
3746 int64_t pos = avio_tell(pb);
3747 avio_wb32(pb, 0); /* size placeholder*/
3748 ffio_wfourcc(pb, "moov");
3750 mov_setup_track_ids(mov, s);
3752 for (i = 0; i < mov->nb_streams; i++) {
3753 if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
3756 mov->tracks[i].time = mov->time;
3758 if (mov->tracks[i].entry)
3759 build_chunks(&mov->tracks[i]);
3762 if (mov->chapter_track)
3763 for (i = 0; i < s->nb_streams; i++) {
3764 mov->tracks[i].tref_tag = MKTAG('c','h','a','p');
3765 mov->tracks[i].tref_id = mov->tracks[mov->chapter_track].track_id;
3767 for (i = 0; i < mov->nb_streams; i++) {
3768 MOVTrack *track = &mov->tracks[i];
3769 if (track->tag == MKTAG('r','t','p',' ')) {
3770 track->tref_tag = MKTAG('h','i','n','t');
3771 track->tref_id = mov->tracks[track->src_track].track_id;
3772 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
3773 int * fallback, size;
3774 fallback = (int*)av_stream_get_side_data(track->st,
3775 AV_PKT_DATA_FALLBACK_TRACK,
3777 if (fallback != NULL && size == sizeof(int)) {
3778 if (*fallback >= 0 && *fallback < mov->nb_streams) {
3779 track->tref_tag = MKTAG('f','a','l','l');
3780 track->tref_id = mov->tracks[*fallback].track_id;
3785 for (i = 0; i < mov->nb_streams; i++) {
3786 if (mov->tracks[i].tag == MKTAG('t','m','c','d')) {
3787 int src_trk = mov->tracks[i].src_track;
3788 mov->tracks[src_trk].tref_tag = mov->tracks[i].tag;
3789 mov->tracks[src_trk].tref_id = mov->tracks[i].track_id;
3790 //src_trk may have a different timescale than the tmcd track
3791 mov->tracks[i].track_duration = av_rescale(mov->tracks[src_trk].track_duration,
3792 mov->tracks[i].timescale,
3793 mov->tracks[src_trk].timescale);
3797 mov_write_mvhd_tag(pb, mov);
3798 if (mov->mode != MODE_MOV && !mov->iods_skip)
3799 mov_write_iods_tag(pb, mov);
3800 for (i = 0; i < mov->nb_streams; i++) {
3801 if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_FRAGMENT) {
3802 int ret = mov_write_trak_tag(s, pb, mov, &(mov->tracks[i]), i < s->nb_streams ? s->streams[i] : NULL);
3807 if (mov->flags & FF_MOV_FLAG_FRAGMENT)
3808 mov_write_mvex_tag(pb, mov); /* QuickTime requires trak to precede this */
3810 if (mov->mode == MODE_PSP)
3811 mov_write_uuidusmt_tag(pb, s);
3813 mov_write_udta_tag(pb, mov, s);
3815 return update_size(pb, pos);
3818 static void param_write_int(AVIOContext *pb, const char *name, int value)
3820 avio_printf(pb, "<param name=\"%s\" value=\"%d\" valuetype=\"data\"/>\n", name, value);
3823 static void param_write_string(AVIOContext *pb, const char *name, const char *value)
3825 avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, value);
3828 static void param_write_hex(AVIOContext *pb, const char *name, const uint8_t *value, int len)
3831 len = FFMIN(sizeof(buf) / 2 - 1, len);
3832 ff_data_to_hex(buf, value, len, 0);
3833 buf[2 * len] = '\0';
3834 avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, buf);
3837 static int mov_write_isml_manifest(AVIOContext *pb, MOVMuxContext *mov, AVFormatContext *s)
3839 int64_t pos = avio_tell(pb);
3841 int64_t manifest_bit_rate = 0;
3842 AVCPBProperties *props = NULL;
3844 static const uint8_t uuid[] = {
3845 0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd,
3846 0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66
3850 ffio_wfourcc(pb, "uuid");
3851 avio_write(pb, uuid, sizeof(uuid));
3854 avio_printf(pb, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
3855 avio_printf(pb, "<smil xmlns=\"http://www.w3.org/2001/SMIL20/Language\">\n");
3856 avio_printf(pb, "<head>\n");
3857 if (!(mov->fc->flags & AVFMT_FLAG_BITEXACT))
3858 avio_printf(pb, "<meta name=\"creator\" content=\"%s\" />\n",
3860 avio_printf(pb, "</head>\n");
3861 avio_printf(pb, "<body>\n");
3862 avio_printf(pb, "<switch>\n");
3864 mov_setup_track_ids(mov, s);
3866 for (i = 0; i < mov->nb_streams; i++) {
3867 MOVTrack *track = &mov->tracks[i];
3869 int track_id = track->track_id;
3870 char track_name_buf[32] = { 0 };
3872 AVStream *st = track->st;
3873 AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0);
3875 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
3877 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
3883 props = (AVCPBProperties*)av_stream_get_side_data(track->st, AV_PKT_DATA_CPB_PROPERTIES, NULL);
3885 if (track->par->bit_rate) {
3886 manifest_bit_rate = track->par->bit_rate;
3888 manifest_bit_rate = props->max_bitrate;
3891 avio_printf(pb, "<%s systemBitrate=\"%"PRId64"\">\n", type,
3893 param_write_int(pb, "systemBitrate", manifest_bit_rate);
3894 param_write_int(pb, "trackID", track_id);
3895 param_write_string(pb, "systemLanguage", lang ? lang->value : "und");
3897 /* Build track name piece by piece: */
3899 av_strlcat(track_name_buf, type, sizeof(track_name_buf));
3900 /* 2. track language, if available */
3902 av_strlcatf(track_name_buf, sizeof(track_name_buf),
3903 "_%s", lang->value);
3904 /* 3. special type suffix */
3905 /* "_cc" = closed captions, "_ad" = audio_description */
3906 if (st->disposition & AV_DISPOSITION_HEARING_IMPAIRED)
3907 av_strlcat(track_name_buf, "_cc", sizeof(track_name_buf));
3908 else if (st->disposition & AV_DISPOSITION_VISUAL_IMPAIRED)
3909 av_strlcat(track_name_buf, "_ad", sizeof(track_name_buf));
3911 param_write_string(pb, "trackName", track_name_buf);
3913 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
3914 if (track->par->codec_id == AV_CODEC_ID_H264) {
3916 int size = track->par->extradata_size;
3917 if (!ff_avc_write_annexb_extradata(track->par->extradata, &ptr,
3919 param_write_hex(pb, "CodecPrivateData",
3920 ptr ? ptr : track->par->extradata,
3924 param_write_string(pb, "FourCC", "H264");
3925 } else if (track->par->codec_id == AV_CODEC_ID_VC1) {
3926 param_write_string(pb, "FourCC", "WVC1");
3927 param_write_hex(pb, "CodecPrivateData", track->par->extradata,
3928 track->par->extradata_size);
3930 param_write_int(pb, "MaxWidth", track->par->width);
3931 param_write_int(pb, "MaxHeight", track->par->height);
3932 param_write_int(pb, "DisplayWidth", track->par->width);
3933 param_write_int(pb, "DisplayHeight", track->par->height);
3935 if (track->par->codec_id == AV_CODEC_ID_AAC) {
3936 switch (track->par->profile)
3938 case FF_PROFILE_AAC_HE_V2:
3939 param_write_string(pb, "FourCC", "AACP");
3941 case FF_PROFILE_AAC_HE:
3942 param_write_string(pb, "FourCC", "AACH");
3945 param_write_string(pb, "FourCC", "AACL");
3947 } else if (track->par->codec_id == AV_CODEC_ID_WMAPRO) {
3948 param_write_string(pb, "FourCC", "WMAP");
3950 param_write_hex(pb, "CodecPrivateData", track->par->extradata,
3951 track->par->extradata_size);
3952 param_write_int(pb, "AudioTag", ff_codec_get_tag(ff_codec_wav_tags,
3953 track->par->codec_id));
3954 param_write_int(pb, "Channels", track->par->channels);
3955 param_write_int(pb, "SamplingRate", track->par->sample_rate);
3956 param_write_int(pb, "BitsPerSample", 16);
3957 param_write_int(pb, "PacketSize", track->par->block_align ?
3958 track->par->block_align : 4);
3960 avio_printf(pb, "</%s>\n", type);
3962 avio_printf(pb, "</switch>\n");
3963 avio_printf(pb, "</body>\n");
3964 avio_printf(pb, "</smil>\n");
3966 return update_size(pb, pos);
3969 static int mov_write_mfhd_tag(AVIOContext *pb, MOVMuxContext *mov)
3972 ffio_wfourcc(pb, "mfhd");
3974 avio_wb32(pb, mov->fragments);
3978 static uint32_t get_sample_flags(MOVTrack *track, MOVIentry *entry)
3980 return entry->flags & MOV_SYNC_SAMPLE ? MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO :
3981 (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC);
3984 static int mov_write_tfhd_tag(AVIOContext *pb, MOVMuxContext *mov,
3985 MOVTrack *track, int64_t moof_offset)
3987 int64_t pos = avio_tell(pb);
3988 uint32_t flags = MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
3989 MOV_TFHD_BASE_DATA_OFFSET;
3990 if (!track->entry) {
3991 flags |= MOV_TFHD_DURATION_IS_EMPTY;
3993 flags |= MOV_TFHD_DEFAULT_FLAGS;
3995 if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET)
3996 flags &= ~MOV_TFHD_BASE_DATA_OFFSET;
3997 if (mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) {
3998 flags &= ~MOV_TFHD_BASE_DATA_OFFSET;
3999 flags |= MOV_TFHD_DEFAULT_BASE_IS_MOOF;
4002 /* Don't set a default sample size, the silverlight player refuses
4003 * to play files with that set. Don't set a default sample duration,
4004 * WMP freaks out if it is set. Don't set a base data offset, PIFF
4005 * file format says it MUST NOT be set. */
4006 if (track->mode == MODE_ISM)
4007 flags &= ~(MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
4008 MOV_TFHD_BASE_DATA_OFFSET);
4010 avio_wb32(pb, 0); /* size placeholder */
4011 ffio_wfourcc(pb, "tfhd");
4012 avio_w8(pb, 0); /* version */
4013 avio_wb24(pb, flags);
4015 avio_wb32(pb, track->track_id); /* track-id */
4016 if (flags & MOV_TFHD_BASE_DATA_OFFSET)
4017 avio_wb64(pb, moof_offset);
4018 if (flags & MOV_TFHD_DEFAULT_DURATION) {
4019 track->default_duration = get_cluster_duration(track, 0);
4020 avio_wb32(pb, track->default_duration);
4022 if (flags & MOV_TFHD_DEFAULT_SIZE) {
4023 track->default_size = track->entry ? track->cluster[0].size : 1;
4024 avio_wb32(pb, track->default_size);
4026 track->default_size = -1;
4028 if (flags & MOV_TFHD_DEFAULT_FLAGS) {
4029 /* Set the default flags based on the second sample, if available.
4030 * If the first sample is different, that can be signaled via a separate field. */
4031 if (track->entry > 1)
4032 track->default_sample_flags = get_sample_flags(track, &track->cluster[1]);
4034 track->default_sample_flags =
4035 track->par->codec_type == AVMEDIA_TYPE_VIDEO ?
4036 (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC) :
4037 MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO;
4038 avio_wb32(pb, track->default_sample_flags);
4041 return update_size(pb, pos);
4044 static int mov_write_trun_tag(AVIOContext *pb, MOVMuxContext *mov,
4045 MOVTrack *track, int moof_size,
4048 int64_t pos = avio_tell(pb);
4049 uint32_t flags = MOV_TRUN_DATA_OFFSET;
4052 for (i = first; i < end; i++) {
4053 if (get_cluster_duration(track, i) != track->default_duration)
4054 flags |= MOV_TRUN_SAMPLE_DURATION;
4055 if (track->cluster[i].size != track->default_size)
4056 flags |= MOV_TRUN_SAMPLE_SIZE;
4057 if (i > first && get_sample_flags(track, &track->cluster[i]) != track->default_sample_flags)
4058 flags |= MOV_TRUN_SAMPLE_FLAGS;
4060 if (!(flags & MOV_TRUN_SAMPLE_FLAGS) && track->entry > 0 &&
4061 get_sample_flags(track, &track->cluster[0]) != track->default_sample_flags)
4062 flags |= MOV_TRUN_FIRST_SAMPLE_FLAGS;
4063 if (track->flags & MOV_TRACK_CTTS)
4064 flags |= MOV_TRUN_SAMPLE_CTS;
4066 avio_wb32(pb, 0); /* size placeholder */
4067 ffio_wfourcc(pb, "trun");
4068 avio_w8(pb, 0); /* version */
4069 avio_wb24(pb, flags);
4071 avio_wb32(pb, end - first); /* sample count */
4072 if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET &&
4073 !(mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) &&
4075 avio_wb32(pb, 0); /* Later tracks follow immediately after the previous one */
4077 avio_wb32(pb, moof_size + 8 + track->data_offset +
4078 track->cluster[first].pos); /* data offset */
4079 if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS)
4080 avio_wb32(pb, get_sample_flags(track, &track->cluster[first]));
4082 for (i = first; i < end; i++) {
4083 if (flags & MOV_TRUN_SAMPLE_DURATION)
4084 avio_wb32(pb, get_cluster_duration(track, i));
4085 if (flags & MOV_TRUN_SAMPLE_SIZE)
4086 avio_wb32(pb, track->cluster[i].size);
4087 if (flags & MOV_TRUN_SAMPLE_FLAGS)
4088 avio_wb32(pb, get_sample_flags(track, &track->cluster[i]));
4089 if (flags & MOV_TRUN_SAMPLE_CTS)
4090 avio_wb32(pb, track->cluster[i].cts);
4093 mov->first_trun = 0;
4094 return update_size(pb, pos);
4097 static int mov_write_tfxd_tag(AVIOContext *pb, MOVTrack *track)
4099 int64_t pos = avio_tell(pb);
4100 static const uint8_t uuid[] = {
4101 0x6d, 0x1d, 0x9b, 0x05, 0x42, 0xd5, 0x44, 0xe6,
4102 0x80, 0xe2, 0x14, 0x1d, 0xaf, 0xf7, 0x57, 0xb2
4105 avio_wb32(pb, 0); /* size placeholder */
4106 ffio_wfourcc(pb, "uuid");
4107 avio_write(pb, uuid, sizeof(uuid));
4110 avio_wb64(pb, track->start_dts + track->frag_start +
4111 track->cluster[0].cts);
4112 avio_wb64(pb, track->end_pts -
4113 (track->cluster[0].dts + track->cluster[0].cts));
4115 return update_size(pb, pos);
4118 static int mov_write_tfrf_tag(AVIOContext *pb, MOVMuxContext *mov,
4119 MOVTrack *track, int entry)
4121 int n = track->nb_frag_info - 1 - entry, i;
4122 int size = 8 + 16 + 4 + 1 + 16*n;
4123 static const uint8_t uuid[] = {
4124 0xd4, 0x80, 0x7e, 0xf2, 0xca, 0x39, 0x46, 0x95,
4125 0x8e, 0x54, 0x26, 0xcb, 0x9e, 0x46, 0xa7, 0x9f
4131 avio_seek(pb, track->frag_info[entry].tfrf_offset, SEEK_SET);
4132 avio_wb32(pb, size);
4133 ffio_wfourcc(pb, "uuid");
4134 avio_write(pb, uuid, sizeof(uuid));
4138 for (i = 0; i < n; i++) {
4139 int index = entry + 1 + i;
4140 avio_wb64(pb, track->frag_info[index].time);
4141 avio_wb64(pb, track->frag_info[index].duration);
4143 if (n < mov->ism_lookahead) {
4144 int free_size = 16 * (mov->ism_lookahead - n);
4145 avio_wb32(pb, free_size);
4146 ffio_wfourcc(pb, "free");
4147 ffio_fill(pb, 0, free_size - 8);
4153 static int mov_write_tfrf_tags(AVIOContext *pb, MOVMuxContext *mov,
4156 int64_t pos = avio_tell(pb);
4158 for (i = 0; i < mov->ism_lookahead; i++) {
4159 /* Update the tfrf tag for the last ism_lookahead fragments,
4160 * nb_frag_info - 1 is the next fragment to be written. */
4161 mov_write_tfrf_tag(pb, mov, track, track->nb_frag_info - 2 - i);
4163 avio_seek(pb, pos, SEEK_SET);
4167 static int mov_add_tfra_entries(AVIOContext *pb, MOVMuxContext *mov, int tracks,
4171 for (i = 0; i < mov->nb_streams; i++) {
4172 MOVTrack *track = &mov->tracks[i];
4173 MOVFragmentInfo *info;
4174 if ((tracks >= 0 && i != tracks) || !track->entry)
4176 track->nb_frag_info++;
4177 if (track->nb_frag_info >= track->frag_info_capacity) {
4178 unsigned new_capacity = track->nb_frag_info + MOV_FRAG_INFO_ALLOC_INCREMENT;
4179 if (av_reallocp_array(&track->frag_info,
4181 sizeof(*track->frag_info)))
4182 return AVERROR(ENOMEM);
4183 track->frag_info_capacity = new_capacity;
4185 info = &track->frag_info[track->nb_frag_info - 1];
4186 info->offset = avio_tell(pb);
4188 // Try to recreate the original pts for the first packet
4189 // from the fields we have stored
4190 info->time = track->start_dts + track->frag_start +
4191 track->cluster[0].cts;
4192 info->duration = track->end_pts -
4193 (track->cluster[0].dts + track->cluster[0].cts);
4194 // If the pts is less than zero, we will have trimmed
4195 // away parts of the media track using an edit list,
4196 // and the corresponding start presentation time is zero.
4197 if (info->time < 0) {
4198 info->duration += info->time;
4201 info->tfrf_offset = 0;
4202 mov_write_tfrf_tags(pb, mov, track);
4207 static void mov_prune_frag_info(MOVMuxContext *mov, int tracks, int max)
4210 for (i = 0; i < mov->nb_streams; i++) {
4211 MOVTrack *track = &mov->tracks[i];
4212 if ((tracks >= 0 && i != tracks) || !track->entry)
4214 if (track->nb_frag_info > max) {
4215 memmove(track->frag_info, track->frag_info + (track->nb_frag_info - max), max * sizeof(*track->frag_info));
4216 track->nb_frag_info = max;
4221 static int mov_write_tfdt_tag(AVIOContext *pb, MOVTrack *track)
4223 int64_t pos = avio_tell(pb);
4225 avio_wb32(pb, 0); /* size */
4226 ffio_wfourcc(pb, "tfdt");
4227 avio_w8(pb, 1); /* version */
4229 avio_wb64(pb, track->frag_start);
4230 return update_size(pb, pos);
4233 static int mov_write_traf_tag(AVIOContext *pb, MOVMuxContext *mov,
4234 MOVTrack *track, int64_t moof_offset,
4237 int64_t pos = avio_tell(pb);
4239 avio_wb32(pb, 0); /* size placeholder */
4240 ffio_wfourcc(pb, "traf");
4242 mov_write_tfhd_tag(pb, mov, track, moof_offset);
4243 if (mov->mode != MODE_ISM)
4244 mov_write_tfdt_tag(pb, track);
4245 for (i = 1; i < track->entry; i++) {
4246 if (track->cluster[i].pos != track->cluster[i - 1].pos + track->cluster[i - 1].size) {
4247 mov_write_trun_tag(pb, mov, track, moof_size, start, i);
4251 mov_write_trun_tag(pb, mov, track, moof_size, start, track->entry);
4252 if (mov->mode == MODE_ISM) {
4253 mov_write_tfxd_tag(pb, track);
4255 if (mov->ism_lookahead) {
4256 int i, size = 16 + 4 + 1 + 16 * mov->ism_lookahead;
4258 if (track->nb_frag_info > 0) {
4259 MOVFragmentInfo *info = &track->frag_info[track->nb_frag_info - 1];
4260 if (!info->tfrf_offset)
4261 info->tfrf_offset = avio_tell(pb);
4263 avio_wb32(pb, 8 + size);
4264 ffio_wfourcc(pb, "free");
4265 for (i = 0; i < size; i++)
4270 return update_size(pb, pos);
4273 static int mov_write_moof_tag_internal(AVIOContext *pb, MOVMuxContext *mov,
4274 int tracks, int moof_size)
4276 int64_t pos = avio_tell(pb);
4279 avio_wb32(pb, 0); /* size placeholder */
4280 ffio_wfourcc(pb, "moof");
4281 mov->first_trun = 1;
4283 mov_write_mfhd_tag(pb, mov);
4284 for (i = 0; i < mov->nb_streams; i++) {
4285 MOVTrack *track = &mov->tracks[i];
4286 if (tracks >= 0 && i != tracks)
4290 mov_write_traf_tag(pb, mov, track, pos, moof_size);
4293 return update_size(pb, pos);
4296 static int mov_write_sidx_tag(AVIOContext *pb,
4297 MOVTrack *track, int ref_size, int total_sidx_size)
4299 int64_t pos = avio_tell(pb), offset_pos, end_pos;
4300 int64_t presentation_time, duration, offset;
4301 int starts_with_SAP, i, entries;
4305 presentation_time = track->start_dts + track->frag_start +
4306 track->cluster[0].cts;
4307 duration = track->end_pts -
4308 (track->cluster[0].dts + track->cluster[0].cts);
4309 starts_with_SAP = track->cluster[0].flags & MOV_SYNC_SAMPLE;
4311 // pts<0 should be cut away using edts
4312 if (presentation_time < 0) {
4313 duration += presentation_time;
4314 presentation_time = 0;
4317 entries = track->nb_frag_info;
4320 presentation_time = track->frag_info[0].time;
4323 avio_wb32(pb, 0); /* size */
4324 ffio_wfourcc(pb, "sidx");
4325 avio_w8(pb, 1); /* version */
4327 avio_wb32(pb, track->track_id); /* reference_ID */
4328 avio_wb32(pb, track->timescale); /* timescale */
4329 avio_wb64(pb, presentation_time); /* earliest_presentation_time */
4330 offset_pos = avio_tell(pb);
4331 avio_wb64(pb, 0); /* first_offset (offset to referenced moof) */
4332 avio_wb16(pb, 0); /* reserved */
4334 avio_wb16(pb, entries); /* reference_count */
4335 for (i = 0; i < entries; i++) {
4336 if (!track->entry) {
4337 if (i > 1 && track->frag_info[i].offset != track->frag_info[i - 1].offset + track->frag_info[i - 1].size) {
4338 av_log(NULL, AV_LOG_ERROR, "Non-consecutive fragments, writing incorrect sidx\n");
4340 duration = track->frag_info[i].duration;
4341 ref_size = track->frag_info[i].size;
4342 starts_with_SAP = 1;
4344 avio_wb32(pb, (0 << 31) | (ref_size & 0x7fffffff)); /* reference_type (0 = media) | referenced_size */
4345 avio_wb32(pb, duration); /* subsegment_duration */
4346 avio_wb32(pb, (starts_with_SAP << 31) | (0 << 28) | 0); /* starts_with_SAP | SAP_type | SAP_delta_time */
4349 end_pos = avio_tell(pb);
4350 offset = pos + total_sidx_size - end_pos;
4351 avio_seek(pb, offset_pos, SEEK_SET);
4352 avio_wb64(pb, offset);
4353 avio_seek(pb, end_pos, SEEK_SET);
4354 return update_size(pb, pos);
4357 static int mov_write_sidx_tags(AVIOContext *pb, MOVMuxContext *mov,
4358 int tracks, int ref_size)
4361 AVIOContext *avio_buf;
4363 for (round = 0; round < 2; round++) {
4364 // First run one round to calculate the total size of all
4366 // This would be much simpler if we'd only write one sidx
4367 // atom, for the first track in the moof.
4369 if ((ret = ffio_open_null_buf(&avio_buf)) < 0)
4374 for (i = 0; i < mov->nb_streams; i++) {
4375 MOVTrack *track = &mov->tracks[i];
4376 if (tracks >= 0 && i != tracks)
4378 // When writing a sidx for the full file, entry is 0, but
4379 // we want to include all tracks. ref_size is 0 in this case,
4380 // since we read it from frag_info instead.
4381 if (!track->entry && ref_size > 0)
4383 total_size -= mov_write_sidx_tag(avio_buf, track, ref_size,
4387 total_size = ffio_close_null_buf(avio_buf);
4392 static int mov_write_moof_tag(AVIOContext *pb, MOVMuxContext *mov, int tracks,
4395 AVIOContext *avio_buf;
4398 if ((ret = ffio_open_null_buf(&avio_buf)) < 0)
4400 mov_write_moof_tag_internal(avio_buf, mov, tracks, 0);
4401 moof_size = ffio_close_null_buf(avio_buf);
4403 if (mov->flags & FF_MOV_FLAG_DASH && !(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX))
4404 mov_write_sidx_tags(pb, mov, tracks, moof_size + 8 + mdat_size);
4406 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX ||
4407 !(mov->flags & FF_MOV_FLAG_SKIP_TRAILER) ||
4408 mov->ism_lookahead) {
4409 if ((ret = mov_add_tfra_entries(pb, mov, tracks, moof_size + 8 + mdat_size)) < 0)
4411 if (!(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) &&
4412 mov->flags & FF_MOV_FLAG_SKIP_TRAILER) {
4413 mov_prune_frag_info(mov, tracks, mov->ism_lookahead + 1);
4417 return mov_write_moof_tag_internal(pb, mov, tracks, moof_size);
4420 static int mov_write_tfra_tag(AVIOContext *pb, MOVTrack *track)
4422 int64_t pos = avio_tell(pb);
4425 avio_wb32(pb, 0); /* size placeholder */
4426 ffio_wfourcc(pb, "tfra");
4427 avio_w8(pb, 1); /* version */
4430 avio_wb32(pb, track->track_id);
4431 avio_wb32(pb, 0); /* length of traf/trun/sample num */
4432 avio_wb32(pb, track->nb_frag_info);
4433 for (i = 0; i < track->nb_frag_info; i++) {
4434 avio_wb64(pb, track->frag_info[i].time);
4435 avio_wb64(pb, track->frag_info[i].offset + track->data_offset);
4436 avio_w8(pb, 1); /* traf number */
4437 avio_w8(pb, 1); /* trun number */
4438 avio_w8(pb, 1); /* sample number */
4441 return update_size(pb, pos);
4444 static int mov_write_mfra_tag(AVIOContext *pb, MOVMuxContext *mov)
4446 int64_t pos = avio_tell(pb);
4449 avio_wb32(pb, 0); /* size placeholder */
4450 ffio_wfourcc(pb, "mfra");
4451 /* An empty mfra atom is enough to indicate to the publishing point that
4452 * the stream has ended. */
4453 if (mov->flags & FF_MOV_FLAG_ISML)
4454 return update_size(pb, pos);
4456 for (i = 0; i < mov->nb_streams; i++) {
4457 MOVTrack *track = &mov->tracks[i];
4458 if (track->nb_frag_info)
4459 mov_write_tfra_tag(pb, track);
4463 ffio_wfourcc(pb, "mfro");
4464 avio_wb32(pb, 0); /* version + flags */
4465 avio_wb32(pb, avio_tell(pb) + 4 - pos);
4467 return update_size(pb, pos);
4470 static int mov_write_mdat_tag(AVIOContext *pb, MOVMuxContext *mov)
4472 avio_wb32(pb, 8); // placeholder for extended size field (64 bit)
4473 ffio_wfourcc(pb, mov->mode == MODE_MOV ? "wide" : "free");
4475 mov->mdat_pos = avio_tell(pb);
4476 avio_wb32(pb, 0); /* size placeholder*/
4477 ffio_wfourcc(pb, "mdat");
4481 /* TODO: This needs to be more general */
4482 static int mov_write_ftyp_tag(AVIOContext *pb, AVFormatContext *s)
4484 MOVMuxContext *mov = s->priv_data;
4485 int64_t pos = avio_tell(pb);
4486 int has_h264 = 0, has_video = 0;
4490 for (i = 0; i < s->nb_streams; i++) {
4491 AVStream *st = s->streams[i];
4492 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
4494 if (st->codecpar->codec_id == AV_CODEC_ID_H264)
4498 avio_wb32(pb, 0); /* size */
4499 ffio_wfourcc(pb, "ftyp");
4501 if (mov->major_brand && strlen(mov->major_brand) >= 4)
4502 ffio_wfourcc(pb, mov->major_brand);
4503 else if (mov->mode == MODE_3GP) {
4504 ffio_wfourcc(pb, has_h264 ? "3gp6" : "3gp4");
4505 minor = has_h264 ? 0x100 : 0x200;
4506 } else if (mov->mode & MODE_3G2) {
4507 ffio_wfourcc(pb, has_h264 ? "3g2b" : "3g2a");
4508 minor = has_h264 ? 0x20000 : 0x10000;
4509 } else if (mov->mode == MODE_PSP)
4510 ffio_wfourcc(pb, "MSNV");
4511 else if (mov->mode == MODE_MP4 && mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)
4512 ffio_wfourcc(pb, "iso5"); // Required when using default-base-is-moof
4513 else if (mov->mode == MODE_MP4)
4514 ffio_wfourcc(pb, "isom");
4515 else if (mov->mode == MODE_IPOD)
4516 ffio_wfourcc(pb, has_video ? "M4V ":"M4A ");
4517 else if (mov->mode == MODE_ISM)
4518 ffio_wfourcc(pb, "isml");
4519 else if (mov->mode == MODE_F4V)
4520 ffio_wfourcc(pb, "f4v ");
4522 ffio_wfourcc(pb, "qt ");
4524 avio_wb32(pb, minor);
4526 if (mov->mode == MODE_MOV)
4527 ffio_wfourcc(pb, "qt ");
4528 else if (mov->mode == MODE_ISM) {
4529 ffio_wfourcc(pb, "piff");
4530 } else if (!(mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)) {
4531 ffio_wfourcc(pb, "isom");
4532 ffio_wfourcc(pb, "iso2");
4534 ffio_wfourcc(pb, "avc1");
4537 // We add tfdt atoms when fragmenting, signal this with the iso6 compatible
4538 // brand. This is compatible with users that don't understand tfdt.
4539 if (mov->flags & FF_MOV_FLAG_FRAGMENT && mov->mode != MODE_ISM)
4540 ffio_wfourcc(pb, "iso6");
4542 if (mov->mode == MODE_3GP)
4543 ffio_wfourcc(pb, has_h264 ? "3gp6":"3gp4");
4544 else if (mov->mode & MODE_3G2)
4545 ffio_wfourcc(pb, has_h264 ? "3g2b":"3g2a");
4546 else if (mov->mode == MODE_PSP)
4547 ffio_wfourcc(pb, "MSNV");
4548 else if (mov->mode == MODE_MP4)
4549 ffio_wfourcc(pb, "mp41");
4551 if (mov->flags & FF_MOV_FLAG_DASH && mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
4552 ffio_wfourcc(pb, "dash");
4554 return update_size(pb, pos);
4557 static int mov_write_uuidprof_tag(AVIOContext *pb, AVFormatContext *s)
4559 AVStream *video_st = s->streams[0];
4560 AVCodecParameters *video_par = s->streams[0]->codecpar;
4561 AVCodecParameters *audio_par = s->streams[1]->codecpar;
4562 int audio_rate = audio_par->sample_rate;
4563 int64_t frame_rate = video_st->avg_frame_rate.den ?
4564 (video_st->avg_frame_rate.num * 0x10000LL) / video_st->avg_frame_rate.den :
4566 int audio_kbitrate = audio_par->bit_rate / 1000;
4567 int video_kbitrate = FFMIN(video_par->bit_rate / 1000, 800 - audio_kbitrate);
4569 if (frame_rate < 0 || frame_rate > INT32_MAX) {
4570 av_log(s, AV_LOG_ERROR, "Frame rate %f outside supported range\n", frame_rate / (double)0x10000);
4571 return AVERROR(EINVAL);
4574 avio_wb32(pb, 0x94); /* size */
4575 ffio_wfourcc(pb, "uuid");
4576 ffio_wfourcc(pb, "PROF");
4578 avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
4579 avio_wb32(pb, 0xbb88695c);
4580 avio_wb32(pb, 0xfac9c740);
4582 avio_wb32(pb, 0x0); /* ? */
4583 avio_wb32(pb, 0x3); /* 3 sections ? */
4585 avio_wb32(pb, 0x14); /* size */
4586 ffio_wfourcc(pb, "FPRF");
4587 avio_wb32(pb, 0x0); /* ? */
4588 avio_wb32(pb, 0x0); /* ? */
4589 avio_wb32(pb, 0x0); /* ? */
4591 avio_wb32(pb, 0x2c); /* size */
4592 ffio_wfourcc(pb, "APRF"); /* audio */
4594 avio_wb32(pb, 0x2); /* TrackID */
4595 ffio_wfourcc(pb, "mp4a");
4596 avio_wb32(pb, 0x20f);
4598 avio_wb32(pb, audio_kbitrate);
4599 avio_wb32(pb, audio_kbitrate);
4600 avio_wb32(pb, audio_rate);
4601 avio_wb32(pb, audio_par->channels);
4603 avio_wb32(pb, 0x34); /* size */
4604 ffio_wfourcc(pb, "VPRF"); /* video */
4606 avio_wb32(pb, 0x1); /* TrackID */
4607 if (video_par->codec_id == AV_CODEC_ID_H264) {
4608 ffio_wfourcc(pb, "avc1");
4609 avio_wb16(pb, 0x014D);
4610 avio_wb16(pb, 0x0015);
4612 ffio_wfourcc(pb, "mp4v");
4613 avio_wb16(pb, 0x0000);
4614 avio_wb16(pb, 0x0103);
4617 avio_wb32(pb, video_kbitrate);
4618 avio_wb32(pb, video_kbitrate);
4619 avio_wb32(pb, frame_rate);
4620 avio_wb32(pb, frame_rate);
4621 avio_wb16(pb, video_par->width);
4622 avio_wb16(pb, video_par->height);
4623 avio_wb32(pb, 0x010001); /* ? */
4628 static int mov_write_identification(AVIOContext *pb, AVFormatContext *s)
4630 MOVMuxContext *mov = s->priv_data;
4633 mov_write_ftyp_tag(pb,s);
4634 if (mov->mode == MODE_PSP) {
4635 int video_streams_nb = 0, audio_streams_nb = 0, other_streams_nb = 0;
4636 for (i = 0; i < s->nb_streams; i++) {
4637 AVStream *st = s->streams[i];
4638 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
4640 else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
4646 if (video_streams_nb != 1 || audio_streams_nb != 1 || other_streams_nb) {
4647 av_log(s, AV_LOG_ERROR, "PSP mode need one video and one audio stream\n");
4648 return AVERROR(EINVAL);
4650 return mov_write_uuidprof_tag(pb, s);
4655 static int mov_parse_mpeg2_frame(AVPacket *pkt, uint32_t *flags)
4658 int i, closed_gop = 0;
4660 for (i = 0; i < pkt->size - 4; i++) {
4661 c = (c << 8) + pkt->data[i];
4662 if (c == 0x1b8) { // gop
4663 closed_gop = pkt->data[i + 4] >> 6 & 0x01;
4664 } else if (c == 0x100) { // pic
4665 int temp_ref = (pkt->data[i + 1] << 2) | (pkt->data[i + 2] >> 6);
4666 if (!temp_ref || closed_gop) // I picture is not reordered
4667 *flags = MOV_SYNC_SAMPLE;
4669 *flags = MOV_PARTIAL_SYNC_SAMPLE;
4676 static void mov_parse_vc1_frame(AVPacket *pkt, MOVTrack *trk)
4678 const uint8_t *start, *next, *end = pkt->data + pkt->size;
4679 int seq = 0, entry = 0;
4680 int key = pkt->flags & AV_PKT_FLAG_KEY;
4681 start = find_next_marker(pkt->data, end);
4682 for (next = start; next < end; start = next) {
4683 next = find_next_marker(start + 4, end);
4684 switch (AV_RB32(start)) {
4685 case VC1_CODE_SEQHDR:
4688 case VC1_CODE_ENTRYPOINT:
4691 case VC1_CODE_SLICE:
4692 trk->vc1_info.slices = 1;
4696 if (!trk->entry && trk->vc1_info.first_packet_seen)
4697 trk->vc1_info.first_frag_written = 1;
4698 if (!trk->entry && !trk->vc1_info.first_frag_written) {
4699 /* First packet in first fragment */
4700 trk->vc1_info.first_packet_seq = seq;
4701 trk->vc1_info.first_packet_entry = entry;
4702 trk->vc1_info.first_packet_seen = 1;
4703 } else if ((seq && !trk->vc1_info.packet_seq) ||
4704 (entry && !trk->vc1_info.packet_entry)) {
4706 for (i = 0; i < trk->entry; i++)
4707 trk->cluster[i].flags &= ~MOV_SYNC_SAMPLE;
4708 trk->has_keyframes = 0;
4710 trk->vc1_info.packet_seq = 1;
4712 trk->vc1_info.packet_entry = 1;
4713 if (!trk->vc1_info.first_frag_written) {
4714 /* First fragment */
4715 if ((!seq || trk->vc1_info.first_packet_seq) &&
4716 (!entry || trk->vc1_info.first_packet_entry)) {
4717 /* First packet had the same headers as this one, readd the
4718 * sync sample flag. */
4719 trk->cluster[0].flags |= MOV_SYNC_SAMPLE;
4720 trk->has_keyframes = 1;
4724 if (trk->vc1_info.packet_seq && trk->vc1_info.packet_entry)
4726 else if (trk->vc1_info.packet_seq)
4728 else if (trk->vc1_info.packet_entry)
4731 trk->cluster[trk->entry].flags |= MOV_SYNC_SAMPLE;
4732 trk->has_keyframes++;
4736 static int mov_flush_fragment_interleaving(AVFormatContext *s, MOVTrack *track)
4738 MOVMuxContext *mov = s->priv_data;
4743 if (!track->mdat_buf)
4745 if (!mov->mdat_buf) {
4746 if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0)
4749 buf_size = avio_close_dyn_buf(track->mdat_buf, &buf);
4750 track->mdat_buf = NULL;
4752 offset = avio_tell(mov->mdat_buf);
4753 avio_write(mov->mdat_buf, buf, buf_size);
4756 for (i = track->entries_flushed; i < track->entry; i++)
4757 track->cluster[i].pos += offset;
4758 track->entries_flushed = track->entry;
4762 static int mov_flush_fragment(AVFormatContext *s, int force)
4764 MOVMuxContext *mov = s->priv_data;
4765 int i, first_track = -1;
4766 int64_t mdat_size = 0;
4768 int has_video = 0, starts_with_key = 0, first_video_track = 1;
4770 if (!(mov->flags & FF_MOV_FLAG_FRAGMENT))
4773 // Try to fill in the duration of the last packet in each stream
4774 // from queued packets in the interleave queues. If the flushing
4775 // of fragments was triggered automatically by an AVPacket, we
4776 // already have reliable info for the end of that track, but other
4777 // tracks may need to be filled in.
4778 for (i = 0; i < s->nb_streams; i++) {
4779 MOVTrack *track = &mov->tracks[i];
4780 if (!track->end_reliable) {
4782 if (!ff_interleaved_peek(s, i, &pkt, 1)) {
4783 track->track_duration = pkt.dts - track->start_dts;
4784 if (pkt.pts != AV_NOPTS_VALUE)
4785 track->end_pts = pkt.pts;
4787 track->end_pts = pkt.dts;
4792 for (i = 0; i < mov->nb_streams; i++) {
4793 MOVTrack *track = &mov->tracks[i];
4794 if (track->entry <= 1)
4796 // Sample durations are calculated as the diff of dts values,
4797 // but for the last sample in a fragment, we don't know the dts
4798 // of the first sample in the next fragment, so we have to rely
4799 // on what was set as duration in the AVPacket. Not all callers
4800 // set this though, so we might want to replace it with an
4801 // estimate if it currently is zero.
4802 if (get_cluster_duration(track, track->entry - 1) != 0)
4804 // Use the duration (i.e. dts diff) of the second last sample for
4805 // the last one. This is a wild guess (and fatal if it turns out
4806 // to be too long), but probably the best we can do - having a zero
4807 // duration is bad as well.
4808 track->track_duration += get_cluster_duration(track, track->entry - 2);
4809 track->end_pts += get_cluster_duration(track, track->entry - 2);
4810 if (!mov->missing_duration_warned) {
4811 av_log(s, AV_LOG_WARNING,
4812 "Estimating the duration of the last packet in a "
4813 "fragment, consider setting the duration field in "
4814 "AVPacket instead.\n");
4815 mov->missing_duration_warned = 1;
4819 if (!mov->moov_written) {
4820 int64_t pos = avio_tell(s->pb);
4822 int buf_size, moov_size;
4824 for (i = 0; i < mov->nb_streams; i++)
4825 if (!mov->tracks[i].entry)
4827 /* Don't write the initial moov unless all tracks have data */
4828 if (i < mov->nb_streams && !force)
4831 moov_size = get_moov_size(s);
4832 for (i = 0; i < mov->nb_streams; i++)
4833 mov->tracks[i].data_offset = pos + moov_size + 8;
4835 avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_HEADER);
4836 if (mov->flags & FF_MOV_FLAG_DELAY_MOOV)
4837 mov_write_identification(s->pb, s);
4838 if ((ret = mov_write_moov_tag(s->pb, mov, s)) < 0)
4841 if (mov->flags & FF_MOV_FLAG_DELAY_MOOV) {
4842 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
4843 mov->reserved_header_pos = avio_tell(s->pb);
4845 mov->moov_written = 1;
4849 buf_size = avio_close_dyn_buf(mov->mdat_buf, &buf);
4850 mov->mdat_buf = NULL;
4851 avio_wb32(s->pb, buf_size + 8);
4852 ffio_wfourcc(s->pb, "mdat");
4853 avio_write(s->pb, buf, buf_size);
4856 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
4857 mov->reserved_header_pos = avio_tell(s->pb);
4859 mov->moov_written = 1;
4861 for (i = 0; i < mov->nb_streams; i++) {
4862 if (mov->tracks[i].entry)
4863 mov->tracks[i].frag_start += mov->tracks[i].start_dts +
4864 mov->tracks[i].track_duration -
4865 mov->tracks[i].cluster[0].dts;
4866 mov->tracks[i].entry = 0;
4867 mov->tracks[i].end_reliable = 0;
4873 if (mov->frag_interleave) {
4874 for (i = 0; i < mov->nb_streams; i++) {
4875 MOVTrack *track = &mov->tracks[i];
4877 if ((ret = mov_flush_fragment_interleaving(s, track)) < 0)
4883 mdat_size = avio_tell(mov->mdat_buf);
4886 for (i = 0; i < mov->nb_streams; i++) {
4887 MOVTrack *track = &mov->tracks[i];
4888 if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF || mov->frag_interleave)
4889 track->data_offset = 0;
4891 track->data_offset = mdat_size;
4892 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
4894 if (first_video_track) {
4896 starts_with_key = track->cluster[0].flags & MOV_SYNC_SAMPLE;
4897 first_video_track = 0;
4902 if (track->mdat_buf)
4903 mdat_size += avio_tell(track->mdat_buf);
4904 if (first_track < 0)
4911 avio_write_marker(s->pb,
4912 av_rescale(mov->tracks[first_track].cluster[0].dts, AV_TIME_BASE, mov->tracks[first_track].timescale),
4913 (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);
4915 for (i = 0; i < mov->nb_streams; i++) {
4916 MOVTrack *track = &mov->tracks[i];
4917 int buf_size, write_moof = 1, moof_tracks = -1;
4919 int64_t duration = 0;
4922 duration = track->start_dts + track->track_duration -
4923 track->cluster[0].dts;
4924 if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF) {
4925 if (!track->mdat_buf)
4927 mdat_size = avio_tell(track->mdat_buf);
4930 write_moof = i == first_track;
4936 mov_write_moof_tag(s->pb, mov, moof_tracks, mdat_size);
4939 avio_wb32(s->pb, mdat_size + 8);
4940 ffio_wfourcc(s->pb, "mdat");
4944 track->frag_start += duration;
4946 track->entries_flushed = 0;
4947 track->end_reliable = 0;
4948 if (!mov->frag_interleave) {
4949 if (!track->mdat_buf)
4951 buf_size = avio_close_dyn_buf(track->mdat_buf, &buf);
4952 track->mdat_buf = NULL;
4956 buf_size = avio_close_dyn_buf(mov->mdat_buf, &buf);
4957 mov->mdat_buf = NULL;
4960 avio_write(s->pb, buf, buf_size);
4970 static int mov_auto_flush_fragment(AVFormatContext *s, int force)
4972 MOVMuxContext *mov = s->priv_data;
4973 int had_moov = mov->moov_written;
4974 int ret = mov_flush_fragment(s, force);
4977 // If using delay_moov, the first flush only wrote the moov,
4978 // not the actual moof+mdat pair, thus flush once again.
4979 if (!had_moov && mov->flags & FF_MOV_FLAG_DELAY_MOOV)
4980 ret = mov_flush_fragment(s, force);
4984 static int check_pkt(AVFormatContext *s, AVPacket *pkt)
4986 MOVMuxContext *mov = s->priv_data;
4987 MOVTrack *trk = &mov->tracks[pkt->stream_index];
4992 ref = trk->cluster[trk->entry - 1].dts;
4993 } else if ( trk->start_dts != AV_NOPTS_VALUE
4994 && !trk->frag_discont) {
4995 ref = trk->start_dts + trk->track_duration;
4997 ref = pkt->dts; // Skip tests for the first packet
4999 duration = pkt->dts - ref;
5000 if (pkt->dts < ref || duration >= INT_MAX) {
5001 av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" / timestamp: %"PRId64" is out of range for mov/mp4 format\n",
5006 pkt->pts = AV_NOPTS_VALUE;
5009 if (pkt->duration < 0 || pkt->duration > INT_MAX) {
5010 av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" is invalid\n", pkt->duration);
5011 return AVERROR(EINVAL);
5016 int ff_mov_write_packet(AVFormatContext *s, AVPacket *pkt)
5018 MOVMuxContext *mov = s->priv_data;
5019 AVIOContext *pb = s->pb;
5020 MOVTrack *trk = &mov->tracks[pkt->stream_index];
5021 AVCodecParameters *par = trk->par;
5022 unsigned int samples_in_chunk = 0;
5023 int size = pkt->size, ret = 0;
5024 uint8_t *reformatted_data = NULL;
5026 ret = check_pkt(s, pkt);
5030 if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
5032 if (mov->moov_written || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
5033 if (mov->frag_interleave && mov->fragments > 0) {
5034 if (trk->entry - trk->entries_flushed >= mov->frag_interleave) {
5035 if ((ret = mov_flush_fragment_interleaving(s, trk)) < 0)
5040 if (!trk->mdat_buf) {
5041 if ((ret = avio_open_dyn_buf(&trk->mdat_buf)) < 0)
5046 if (!mov->mdat_buf) {
5047 if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0)
5054 if (par->codec_id == AV_CODEC_ID_AMR_NB) {
5055 /* We must find out how many AMR blocks there are in one packet */
5056 static const uint16_t packed_size[16] =
5057 {13, 14, 16, 18, 20, 21, 27, 32, 6, 0, 0, 0, 0, 0, 0, 1};
5060 while (len < size && samples_in_chunk < 100) {
5061 len += packed_size[(pkt->data[len] >> 3) & 0x0F];
5064 if (samples_in_chunk > 1) {
5065 av_log(s, AV_LOG_ERROR, "fatal error, input is not a single packet, implement a AVParser for it\n");
5068 } else if (par->codec_id == AV_CODEC_ID_ADPCM_MS ||
5069 par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) {
5070 samples_in_chunk = trk->par->frame_size;
5071 } else if (trk->sample_size)
5072 samples_in_chunk = size / trk->sample_size;
5074 samples_in_chunk = 1;
5076 /* copy extradata if it exists */
5077 if (trk->vos_len == 0 && par->extradata_size > 0 &&
5078 !TAG_IS_AVCI(trk->tag) &&
5079 (par->codec_id != AV_CODEC_ID_DNXHD)) {
5080 trk->vos_len = par->extradata_size;
5081 trk->vos_data = av_malloc(trk->vos_len);
5082 if (!trk->vos_data) {
5083 ret = AVERROR(ENOMEM);
5086 memcpy(trk->vos_data, par->extradata, trk->vos_len);
5089 if (par->codec_id == AV_CODEC_ID_AAC && pkt->size > 2 &&
5090 (AV_RB16(pkt->data) & 0xfff0) == 0xfff0) {
5091 if (!s->streams[pkt->stream_index]->nb_frames) {
5092 av_log(s, AV_LOG_ERROR, "Malformed AAC bitstream detected: "
5093 "use the audio bitstream filter 'aac_adtstoasc' to fix it "
5094 "('-bsf:a aac_adtstoasc' option with ffmpeg)\n");
5097 av_log(s, AV_LOG_WARNING, "aac bitstream error\n");
5099 if (par->codec_id == AV_CODEC_ID_H264 && trk->vos_len > 0 && *(uint8_t *)trk->vos_data != 1 && !TAG_IS_AVCI(trk->tag)) {
5100 /* from x264 or from bytestream H.264 */
5101 /* NAL reformatting needed */
5102 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
5103 ff_avc_parse_nal_units_buf(pkt->data, &reformatted_data,
5105 avio_write(pb, reformatted_data, size);
5107 if (mov->encryption_scheme == MOV_ENC_CENC_AES_CTR) {
5108 size = ff_mov_cenc_avc_parse_nal_units(&trk->cenc, pb, pkt->data, size);
5114 size = ff_avc_parse_nal_units(pb, pkt->data, pkt->size);
5117 } else if (par->codec_id == AV_CODEC_ID_HEVC && trk->vos_len > 6 &&
5118 (AV_RB24(trk->vos_data) == 1 || AV_RB32(trk->vos_data) == 1)) {
5119 /* extradata is Annex B, assume the bitstream is too and convert it */
5120 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
5121 ff_hevc_annexb2mp4_buf(pkt->data, &reformatted_data, &size, 0, NULL);
5122 avio_write(pb, reformatted_data, size);
5124 size = ff_hevc_annexb2mp4(pb, pkt->data, pkt->size, 0, NULL);
5126 #if CONFIG_AC3_PARSER
5127 } else if (par->codec_id == AV_CODEC_ID_EAC3) {
5128 size = handle_eac3(mov, pkt, trk);
5133 avio_write(pb, pkt->data, size);
5136 if (mov->encryption_scheme == MOV_ENC_CENC_AES_CTR) {
5137 if (par->codec_id == AV_CODEC_ID_H264 && par->extradata_size > 4) {
5138 int nal_size_length = (par->extradata[4] & 0x3) + 1;
5139 ret = ff_mov_cenc_avc_write_nal_units(s, &trk->cenc, nal_size_length, pb, pkt->data, size);
5141 ret = ff_mov_cenc_write_packet(&trk->cenc, pb, pkt->data, size);
5148 avio_write(pb, pkt->data, size);
5152 if ((par->codec_id == AV_CODEC_ID_DNXHD ||
5153 par->codec_id == AV_CODEC_ID_AC3) && !trk->vos_len) {
5154 /* copy frame to create needed atoms */
5155 trk->vos_len = size;
5156 trk->vos_data = av_malloc(size);
5157 if (!trk->vos_data) {
5158 ret = AVERROR(ENOMEM);
5161 memcpy(trk->vos_data, pkt->data, size);
5164 if (trk->entry >= trk->cluster_capacity) {
5165 unsigned new_capacity = 2 * (trk->entry + MOV_INDEX_CLUSTER_SIZE);
5166 if (av_reallocp_array(&trk->cluster, new_capacity,
5167 sizeof(*trk->cluster))) {
5168 ret = AVERROR(ENOMEM);
5171 trk->cluster_capacity = new_capacity;
5174 trk->cluster[trk->entry].pos = avio_tell(pb) - size;
5175 trk->cluster[trk->entry].samples_in_chunk = samples_in_chunk;
5176 trk->cluster[trk->entry].chunkNum = 0;
5177 trk->cluster[trk->entry].size = size;
5178 trk->cluster[trk->entry].entries = samples_in_chunk;
5179 trk->cluster[trk->entry].dts = pkt->dts;
5180 if (!trk->entry && trk->start_dts != AV_NOPTS_VALUE) {
5181 if (!trk->frag_discont) {
5182 /* First packet of a new fragment. We already wrote the duration
5183 * of the last packet of the previous fragment based on track_duration,
5184 * which might not exactly match our dts. Therefore adjust the dts
5185 * of this packet to be what the previous packets duration implies. */
5186 trk->cluster[trk->entry].dts = trk->start_dts + trk->track_duration;
5187 /* We also may have written the pts and the corresponding duration
5188 * in sidx/tfrf/tfxd tags; make sure the sidx pts and duration match up with
5189 * the next fragment. This means the cts of the first sample must
5190 * be the same in all fragments, unless end_pts was updated by
5191 * the packet causing the fragment to be written. */
5192 if ((mov->flags & FF_MOV_FLAG_DASH && !(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)) ||
5193 mov->mode == MODE_ISM)
5194 pkt->pts = pkt->dts + trk->end_pts - trk->cluster[trk->entry].dts;
5196 /* New fragment, but discontinuous from previous fragments.
5197 * Pretend the duration sum of the earlier fragments is
5198 * pkt->dts - trk->start_dts. */
5199 trk->frag_start = pkt->dts - trk->start_dts;
5200 trk->end_pts = AV_NOPTS_VALUE;
5201 trk->frag_discont = 0;
5205 if (!trk->entry && trk->start_dts == AV_NOPTS_VALUE && !mov->use_editlist &&
5206 s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO) {
5207 /* Not using edit lists and shifting the first track to start from zero.
5208 * If the other streams start from a later timestamp, we won't be able
5209 * to signal the difference in starting time without an edit list.
5210 * Thus move the timestamp for this first sample to 0, increasing
5211 * its duration instead. */
5212 trk->cluster[trk->entry].dts = trk->start_dts = 0;
5214 if (trk->start_dts == AV_NOPTS_VALUE) {
5215 trk->start_dts = pkt->dts;
5216 if (trk->frag_discont) {
5217 if (mov->use_editlist) {
5218 /* Pretend the whole stream started at pts=0, with earlier fragments
5219 * already written. If the stream started at pts=0, the duration sum
5220 * of earlier fragments would have been pkt->pts. */
5221 trk->frag_start = pkt->pts;
5222 trk->start_dts = pkt->dts - pkt->pts;
5224 /* Pretend the whole stream started at dts=0, with earlier fragments
5225 * already written, with a duration summing up to pkt->dts. */
5226 trk->frag_start = pkt->dts;
5229 trk->frag_discont = 0;
5230 } else if (pkt->dts && mov->moov_written)
5231 av_log(s, AV_LOG_WARNING,
5232 "Track %d starts with a nonzero dts %"PRId64", while the moov "
5233 "already has been written. Set the delay_moov flag to handle "
5235 pkt->stream_index, pkt->dts);
5237 trk->track_duration = pkt->dts - trk->start_dts + pkt->duration;
5238 trk->last_sample_is_subtitle_end = 0;
5240 if (pkt->pts == AV_NOPTS_VALUE) {
5241 av_log(s, AV_LOG_WARNING, "pts has no value\n");
5242 pkt->pts = pkt->dts;
5244 if (pkt->dts != pkt->pts)
5245 trk->flags |= MOV_TRACK_CTTS;
5246 trk->cluster[trk->entry].cts = pkt->pts - pkt->dts;
5247 trk->cluster[trk->entry].flags = 0;
5248 if (trk->start_cts == AV_NOPTS_VALUE)
5249 trk->start_cts = pkt->pts - pkt->dts;
5250 if (trk->end_pts == AV_NOPTS_VALUE)
5251 trk->end_pts = trk->cluster[trk->entry].dts +
5252 trk->cluster[trk->entry].cts + pkt->duration;
5254 trk->end_pts = FFMAX(trk->end_pts, trk->cluster[trk->entry].dts +
5255 trk->cluster[trk->entry].cts +
5258 if (par->codec_id == AV_CODEC_ID_VC1) {
5259 mov_parse_vc1_frame(pkt, trk);
5260 } else if (pkt->flags & AV_PKT_FLAG_KEY) {
5261 if (mov->mode == MODE_MOV && par->codec_id == AV_CODEC_ID_MPEG2VIDEO &&
5262 trk->entry > 0) { // force sync sample for the first key frame
5263 mov_parse_mpeg2_frame(pkt, &trk->cluster[trk->entry].flags);
5264 if (trk->cluster[trk->entry].flags & MOV_PARTIAL_SYNC_SAMPLE)
5265 trk->flags |= MOV_TRACK_STPS;
5267 trk->cluster[trk->entry].flags = MOV_SYNC_SAMPLE;
5269 if (trk->cluster[trk->entry].flags & MOV_SYNC_SAMPLE)
5270 trk->has_keyframes++;
5273 trk->sample_count += samples_in_chunk;
5274 mov->mdat_size += size;
5276 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams)
5277 ff_mov_add_hinted_packet(s, pkt, trk->hint_track, trk->entry,
5278 reformatted_data, size);
5283 av_free(reformatted_data);
5287 static int mov_write_single_packet(AVFormatContext *s, AVPacket *pkt)
5289 MOVMuxContext *mov = s->priv_data;
5290 MOVTrack *trk = &mov->tracks[pkt->stream_index];
5291 AVCodecParameters *par = trk->par;
5292 int64_t frag_duration = 0;
5293 int size = pkt->size;
5295 int ret = check_pkt(s, pkt);
5299 if (mov->flags & FF_MOV_FLAG_FRAG_DISCONT) {
5301 for (i = 0; i < s->nb_streams; i++)
5302 mov->tracks[i].frag_discont = 1;
5303 mov->flags &= ~FF_MOV_FLAG_FRAG_DISCONT;
5307 if (trk->start_dts == AV_NOPTS_VALUE && trk->frag_discont) {
5308 trk->start_dts = pkt->dts;
5309 if (pkt->pts != AV_NOPTS_VALUE)
5310 trk->start_cts = pkt->pts - pkt->dts;
5315 if (trk->par->codec_id == AV_CODEC_ID_MP4ALS ||
5316 trk->par->codec_id == AV_CODEC_ID_FLAC) {
5318 uint8_t *side = av_packet_get_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA, &side_size);
5319 if (side && side_size > 0 && (side_size != par->extradata_size || memcmp(side, par->extradata, side_size))) {
5320 void *newextra = av_mallocz(side_size + AV_INPUT_BUFFER_PADDING_SIZE);
5322 return AVERROR(ENOMEM);
5323 av_free(par->extradata);
5324 par->extradata = newextra;
5325 memcpy(par->extradata, side, side_size);
5326 par->extradata_size = side_size;
5327 mov->need_rewrite_extradata = 1;
5331 return 0; /* Discard 0 sized packets */
5334 if (trk->entry && pkt->stream_index < s->nb_streams)
5335 frag_duration = av_rescale_q(pkt->dts - trk->cluster[0].dts,
5336 s->streams[pkt->stream_index]->time_base,
5338 if ((mov->max_fragment_duration &&
5339 frag_duration >= mov->max_fragment_duration) ||
5340 (mov->max_fragment_size && mov->mdat_size + size >= mov->max_fragment_size) ||
5341 (mov->flags & FF_MOV_FLAG_FRAG_KEYFRAME &&
5342 par->codec_type == AVMEDIA_TYPE_VIDEO &&
5343 trk->entry && pkt->flags & AV_PKT_FLAG_KEY)) {
5344 if (frag_duration >= mov->min_fragment_duration) {
5345 // Set the duration of this track to line up with the next
5346 // sample in this track. This avoids relying on AVPacket
5347 // duration, but only helps for this particular track, not
5348 // for the other ones that are flushed at the same time.
5349 trk->track_duration = pkt->dts - trk->start_dts;
5350 if (pkt->pts != AV_NOPTS_VALUE)
5351 trk->end_pts = pkt->pts;
5353 trk->end_pts = pkt->dts;
5354 trk->end_reliable = 1;
5355 mov_auto_flush_fragment(s, 0);
5359 return ff_mov_write_packet(s, pkt);
5362 static int mov_write_subtitle_end_packet(AVFormatContext *s,
5366 uint8_t data[2] = {0};
5369 av_init_packet(&end);
5370 end.size = sizeof(data);
5375 end.stream_index = stream_index;
5377 ret = mov_write_single_packet(s, &end);
5378 av_packet_unref(&end);
5383 static int mov_write_packet(AVFormatContext *s, AVPacket *pkt)
5386 mov_flush_fragment(s, 1);
5390 MOVMuxContext *mov = s->priv_data;
5391 MOVTrack *trk = &mov->tracks[pkt->stream_index];
5394 return mov_write_single_packet(s, pkt); /* Passthrough. */
5397 * Subtitles require special handling.
5399 * 1) For full complaince, every track must have a sample at
5400 * dts == 0, which is rarely true for subtitles. So, as soon
5401 * as we see any packet with dts > 0, write an empty subtitle
5402 * at dts == 0 for any subtitle track with no samples in it.
5404 * 2) For each subtitle track, check if the current packet's
5405 * dts is past the duration of the last subtitle sample. If
5406 * so, we now need to write an end sample for that subtitle.
5408 * This must be done conditionally to allow for subtitles that
5409 * immediately replace each other, in which case an end sample
5410 * is not needed, and is, in fact, actively harmful.
5412 * 3) See mov_write_trailer for how the final end sample is
5415 for (i = 0; i < mov->nb_streams; i++) {
5416 MOVTrack *trk = &mov->tracks[i];
5419 if (trk->par->codec_id == AV_CODEC_ID_MOV_TEXT &&
5420 trk->track_duration < pkt->dts &&
5421 (trk->entry == 0 || !trk->last_sample_is_subtitle_end)) {
5422 ret = mov_write_subtitle_end_packet(s, i, trk->track_duration);
5423 if (ret < 0) return ret;
5424 trk->last_sample_is_subtitle_end = 1;
5428 if (trk->mode == MODE_MOV && trk->par->codec_type == AVMEDIA_TYPE_VIDEO) {
5429 AVPacket *opkt = pkt;
5430 int reshuffle_ret, ret;
5431 if (trk->is_unaligned_qt_rgb) {
5432 int64_t bpc = trk->par->bits_per_coded_sample != 15 ? trk->par->bits_per_coded_sample : 16;
5433 int expected_stride = ((trk->par->width * bpc + 15) >> 4)*2;
5434 reshuffle_ret = ff_reshuffle_raw_rgb(s, &pkt, trk->par, expected_stride);
5435 if (reshuffle_ret < 0)
5436 return reshuffle_ret;
5439 if (trk->par->format == AV_PIX_FMT_PAL8 && !trk->pal_done) {
5440 ret = ff_get_packet_palette(s, opkt, reshuffle_ret, trk->palette);
5445 } else if (trk->par->codec_id == AV_CODEC_ID_RAWVIDEO &&
5446 (trk->par->format == AV_PIX_FMT_GRAY8 ||
5447 trk->par->format == AV_PIX_FMT_MONOBLACK)) {
5448 for (i = 0; i < pkt->size; i++)
5449 pkt->data[i] = ~pkt->data[i];
5451 if (reshuffle_ret) {
5452 ret = mov_write_single_packet(s, pkt);
5455 av_packet_free(&pkt);
5460 return mov_write_single_packet(s, pkt);
5464 // QuickTime chapters involve an additional text track with the chapter names
5465 // as samples, and a tref pointing from the other tracks to the chapter one.
5466 static int mov_create_chapter_track(AVFormatContext *s, int tracknum)
5470 MOVMuxContext *mov = s->priv_data;
5471 MOVTrack *track = &mov->tracks[tracknum];
5472 AVPacket pkt = { .stream_index = tracknum, .flags = AV_PKT_FLAG_KEY };
5475 track->mode = mov->mode;
5476 track->tag = MKTAG('t','e','x','t');
5477 track->timescale = MOV_TIMESCALE;
5478 track->par = avcodec_parameters_alloc();
5480 return AVERROR(ENOMEM);
5481 track->par->codec_type = AVMEDIA_TYPE_SUBTITLE;
5483 // These properties are required to make QT recognize the chapter track
5484 uint8_t chapter_properties[43] = { 0, 0, 0, 0, 0, 0, 0, 1, };
5485 if (ff_alloc_extradata(track->par, sizeof(chapter_properties)))
5486 return AVERROR(ENOMEM);
5487 memcpy(track->par->extradata, chapter_properties, sizeof(chapter_properties));
5489 if (avio_open_dyn_buf(&pb) >= 0) {
5493 /* Stub header (usually for Quicktime chapter track) */
5495 avio_wb32(pb, 0x01); // displayFlags
5496 avio_w8(pb, 0x00); // horizontal justification
5497 avio_w8(pb, 0x00); // vertical justification
5498 avio_w8(pb, 0x00); // bgColourRed
5499 avio_w8(pb, 0x00); // bgColourGreen
5500 avio_w8(pb, 0x00); // bgColourBlue
5501 avio_w8(pb, 0x00); // bgColourAlpha
5503 avio_wb16(pb, 0x00); // defTextBoxTop
5504 avio_wb16(pb, 0x00); // defTextBoxLeft
5505 avio_wb16(pb, 0x00); // defTextBoxBottom
5506 avio_wb16(pb, 0x00); // defTextBoxRight
5508 avio_wb16(pb, 0x00); // startChar
5509 avio_wb16(pb, 0x00); // endChar
5510 avio_wb16(pb, 0x01); // fontID
5511 avio_w8(pb, 0x00); // fontStyleFlags
5512 avio_w8(pb, 0x00); // fontSize
5513 avio_w8(pb, 0x00); // fgColourRed
5514 avio_w8(pb, 0x00); // fgColourGreen
5515 avio_w8(pb, 0x00); // fgColourBlue
5516 avio_w8(pb, 0x00); // fgColourAlpha
5518 avio_wb32(pb, 0x0D); // box size
5519 ffio_wfourcc(pb, "ftab"); // box atom name
5520 avio_wb16(pb, 0x01); // entry count
5522 avio_wb16(pb, 0x01); // font ID
5523 avio_w8(pb, 0x00); // font name length
5525 if ((size = avio_close_dyn_buf(pb, &buf)) > 0) {
5526 track->par->extradata = buf;
5527 track->par->extradata_size = size;
5534 for (i = 0; i < s->nb_chapters; i++) {
5535 AVChapter *c = s->chapters[i];
5536 AVDictionaryEntry *t;
5538 int64_t end = av_rescale_q(c->end, c->time_base, (AVRational){1,MOV_TIMESCALE});
5539 pkt.pts = pkt.dts = av_rescale_q(c->start, c->time_base, (AVRational){1,MOV_TIMESCALE});
5540 pkt.duration = end - pkt.dts;
5542 if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
5543 static const char encd[12] = {
5544 0x00, 0x00, 0x00, 0x0C,
5546 0x00, 0x00, 0x01, 0x00 };
5547 len = strlen(t->value);
5548 pkt.size = len + 2 + 12;
5549 pkt.data = av_malloc(pkt.size);
5551 return AVERROR(ENOMEM);
5552 AV_WB16(pkt.data, len);
5553 memcpy(pkt.data + 2, t->value, len);
5554 memcpy(pkt.data + len + 2, encd, sizeof(encd));
5555 ff_mov_write_packet(s, &pkt);
5556 av_freep(&pkt.data);
5564 static int mov_check_timecode_track(AVFormatContext *s, AVTimecode *tc, int src_index, const char *tcstr)
5568 /* compute the frame number */
5569 ret = av_timecode_init_from_string(tc, find_fps(s, s->streams[src_index]), tcstr, s);
5573 static int mov_create_timecode_track(AVFormatContext *s, int index, int src_index, AVTimecode tc)
5576 MOVMuxContext *mov = s->priv_data;
5577 MOVTrack *track = &mov->tracks[index];
5578 AVStream *src_st = s->streams[src_index];
5579 AVPacket pkt = {.stream_index = index, .flags = AV_PKT_FLAG_KEY, .size = 4};
5580 AVRational rate = find_fps(s, src_st);
5582 /* tmcd track based on video stream */
5583 track->mode = mov->mode;
5584 track->tag = MKTAG('t','m','c','d');
5585 track->src_track = src_index;
5586 track->timescale = mov->tracks[src_index].timescale;
5587 if (tc.flags & AV_TIMECODE_FLAG_DROPFRAME)
5588 track->timecode_flags |= MOV_TIMECODE_FLAG_DROPFRAME;
5590 /* set st to src_st for metadata access*/
5593 /* encode context: tmcd data stream */
5594 track->par = avcodec_parameters_alloc();
5596 return AVERROR(ENOMEM);
5597 track->par->codec_type = AVMEDIA_TYPE_DATA;
5598 track->par->codec_tag = track->tag;
5599 track->st->avg_frame_rate = av_inv_q(rate);
5601 /* the tmcd track just contains one packet with the frame number */
5602 pkt.data = av_malloc(pkt.size);
5604 return AVERROR(ENOMEM);
5605 AV_WB32(pkt.data, tc.start);
5606 ret = ff_mov_write_packet(s, &pkt);
5612 * st->disposition controls the "enabled" flag in the tkhd tag.
5613 * QuickTime will not play a track if it is not enabled. So make sure
5614 * that one track of each type (audio, video, subtitle) is enabled.
5616 * Subtitles are special. For audio and video, setting "enabled" also
5617 * makes the track "default" (i.e. it is rendered when played). For
5618 * subtitles, an "enabled" subtitle is not rendered by default, but
5619 * if no subtitle is enabled, the subtitle menu in QuickTime will be
5622 static void enable_tracks(AVFormatContext *s)
5624 MOVMuxContext *mov = s->priv_data;
5626 int enabled[AVMEDIA_TYPE_NB];
5627 int first[AVMEDIA_TYPE_NB];
5629 for (i = 0; i < AVMEDIA_TYPE_NB; i++) {
5634 for (i = 0; i < s->nb_streams; i++) {
5635 AVStream *st = s->streams[i];
5637 if (st->codecpar->codec_type <= AVMEDIA_TYPE_UNKNOWN ||
5638 st->codecpar->codec_type >= AVMEDIA_TYPE_NB)
5641 if (first[st->codecpar->codec_type] < 0)
5642 first[st->codecpar->codec_type] = i;
5643 if (st->disposition & AV_DISPOSITION_DEFAULT) {
5644 mov->tracks[i].flags |= MOV_TRACK_ENABLED;
5645 enabled[st->codecpar->codec_type]++;
5649 for (i = 0; i < AVMEDIA_TYPE_NB; i++) {
5651 case AVMEDIA_TYPE_VIDEO:
5652 case AVMEDIA_TYPE_AUDIO:
5653 case AVMEDIA_TYPE_SUBTITLE:
5655 mov->per_stream_grouping = 1;
5656 if (!enabled[i] && first[i] >= 0)
5657 mov->tracks[first[i]].flags |= MOV_TRACK_ENABLED;
5663 static void mov_free(AVFormatContext *s)
5665 MOVMuxContext *mov = s->priv_data;
5668 if (mov->chapter_track) {
5669 if (mov->tracks[mov->chapter_track].par)
5670 av_freep(&mov->tracks[mov->chapter_track].par->extradata);
5671 av_freep(&mov->tracks[mov->chapter_track].par);
5674 for (i = 0; i < mov->nb_streams; i++) {
5675 if (mov->tracks[i].tag == MKTAG('r','t','p',' '))
5676 ff_mov_close_hinting(&mov->tracks[i]);
5677 else if (mov->tracks[i].tag == MKTAG('t','m','c','d') && mov->nb_meta_tmcd)
5678 av_freep(&mov->tracks[i].par);
5679 av_freep(&mov->tracks[i].cluster);
5680 av_freep(&mov->tracks[i].frag_info);
5682 if (mov->tracks[i].vos_len)
5683 av_freep(&mov->tracks[i].vos_data);
5685 ff_mov_cenc_free(&mov->tracks[i].cenc);
5688 av_freep(&mov->tracks);
5691 static uint32_t rgb_to_yuv(uint32_t rgb)
5696 r = (rgb >> 16) & 0xFF;
5697 g = (rgb >> 8) & 0xFF;
5700 y = av_clip_uint8(( 16000 + 257 * r + 504 * g + 98 * b)/1000);
5701 cb = av_clip_uint8((128000 - 148 * r - 291 * g + 439 * b)/1000);
5702 cr = av_clip_uint8((128000 + 439 * r - 368 * g - 71 * b)/1000);
5704 return (y << 16) | (cr << 8) | cb;
5707 static int mov_create_dvd_sub_decoder_specific_info(MOVTrack *track,
5710 int i, width = 720, height = 480;
5711 int have_palette = 0, have_size = 0;
5712 uint32_t palette[16];
5713 char *cur = st->codecpar->extradata;
5715 while (cur && *cur) {
5716 if (strncmp("palette:", cur, 8) == 0) {
5718 count = sscanf(cur + 8,
5719 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
5720 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
5721 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
5722 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32"",
5723 &palette[ 0], &palette[ 1], &palette[ 2], &palette[ 3],
5724 &palette[ 4], &palette[ 5], &palette[ 6], &palette[ 7],
5725 &palette[ 8], &palette[ 9], &palette[10], &palette[11],
5726 &palette[12], &palette[13], &palette[14], &palette[15]);
5728 for (i = 0; i < count; i++) {
5729 palette[i] = rgb_to_yuv(palette[i]);
5732 } else if (!strncmp("size:", cur, 5)) {
5733 sscanf(cur + 5, "%dx%d", &width, &height);
5736 if (have_palette && have_size)
5738 cur += strcspn(cur, "\n\r");
5739 cur += strspn(cur, "\n\r");
5742 track->vos_data = av_malloc(16*4);
5743 if (!track->vos_data)
5744 return AVERROR(ENOMEM);
5745 for (i = 0; i < 16; i++) {
5746 AV_WB32(track->vos_data + i * 4, palette[i]);
5748 track->vos_len = 16 * 4;
5750 st->codecpar->width = width;
5751 st->codecpar->height = track->height = height;
5756 static int mov_init(AVFormatContext *s)
5758 MOVMuxContext *mov = s->priv_data;
5759 AVDictionaryEntry *global_tcr = av_dict_get(s->metadata, "timecode", NULL, 0);
5764 /* Default mode == MP4 */
5765 mov->mode = MODE_MP4;
5768 if (!strcmp("3gp", s->oformat->name)) mov->mode = MODE_3GP;
5769 else if (!strcmp("3g2", s->oformat->name)) mov->mode = MODE_3GP|MODE_3G2;
5770 else if (!strcmp("mov", s->oformat->name)) mov->mode = MODE_MOV;
5771 else if (!strcmp("psp", s->oformat->name)) mov->mode = MODE_PSP;
5772 else if (!strcmp("ipod",s->oformat->name)) mov->mode = MODE_IPOD;
5773 else if (!strcmp("ismv",s->oformat->name)) mov->mode = MODE_ISM;
5774 else if (!strcmp("f4v", s->oformat->name)) mov->mode = MODE_F4V;
5777 if (mov->flags & FF_MOV_FLAG_DELAY_MOOV)
5778 mov->flags |= FF_MOV_FLAG_EMPTY_MOOV;
5780 /* Set the FRAGMENT flag if any of the fragmentation methods are
5782 if (mov->max_fragment_duration || mov->max_fragment_size ||
5783 mov->flags & (FF_MOV_FLAG_EMPTY_MOOV |
5784 FF_MOV_FLAG_FRAG_KEYFRAME |
5785 FF_MOV_FLAG_FRAG_CUSTOM))
5786 mov->flags |= FF_MOV_FLAG_FRAGMENT;
5788 /* Set other implicit flags immediately */
5789 if (mov->mode == MODE_ISM)
5790 mov->flags |= FF_MOV_FLAG_EMPTY_MOOV | FF_MOV_FLAG_SEPARATE_MOOF |
5791 FF_MOV_FLAG_FRAGMENT;
5792 if (mov->flags & FF_MOV_FLAG_DASH)
5793 mov->flags |= FF_MOV_FLAG_FRAGMENT | FF_MOV_FLAG_EMPTY_MOOV |
5794 FF_MOV_FLAG_DEFAULT_BASE_MOOF;
5796 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV && s->flags & AVFMT_FLAG_AUTO_BSF) {
5797 av_log(s, AV_LOG_VERBOSE, "Empty MOOV enabled; disabling automatic bitstream filtering\n");
5798 s->flags &= ~AVFMT_FLAG_AUTO_BSF;
5801 if (mov->flags & FF_MOV_FLAG_FASTSTART) {
5802 mov->reserved_moov_size = -1;
5805 if (mov->use_editlist < 0) {
5806 mov->use_editlist = 1;
5807 if (mov->flags & FF_MOV_FLAG_FRAGMENT &&
5808 !(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
5809 // If we can avoid needing an edit list by shifting the
5810 // tracks, prefer that over (trying to) write edit lists
5811 // in fragmented output.
5812 if (s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO ||
5813 s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO)
5814 mov->use_editlist = 0;
5817 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV &&
5818 !(mov->flags & FF_MOV_FLAG_DELAY_MOOV) && mov->use_editlist)
5819 av_log(s, AV_LOG_WARNING, "No meaningful edit list will be written when using empty_moov without delay_moov\n");
5821 if (!mov->use_editlist && s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO)
5822 s->avoid_negative_ts = AVFMT_AVOID_NEG_TS_MAKE_ZERO;
5824 /* Clear the omit_tfhd_offset flag if default_base_moof is set;
5825 * if the latter is set that's enough and omit_tfhd_offset doesn't
5826 * add anything extra on top of that. */
5827 if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET &&
5828 mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)
5829 mov->flags &= ~FF_MOV_FLAG_OMIT_TFHD_OFFSET;
5831 if (mov->frag_interleave &&
5832 mov->flags & (FF_MOV_FLAG_OMIT_TFHD_OFFSET | FF_MOV_FLAG_SEPARATE_MOOF)) {
5833 av_log(s, AV_LOG_ERROR,
5834 "Sample interleaving in fragments is mutually exclusive with "
5835 "omit_tfhd_offset and separate_moof\n");
5836 return AVERROR(EINVAL);
5839 /* Non-seekable output is ok if using fragmentation. If ism_lookahead
5840 * is enabled, we don't support non-seekable output at all. */
5841 if (!(s->pb->seekable & AVIO_SEEKABLE_NORMAL) &&
5842 (!(mov->flags & FF_MOV_FLAG_FRAGMENT) || mov->ism_lookahead)) {
5843 av_log(s, AV_LOG_ERROR, "muxer does not support non seekable output\n");
5844 return AVERROR(EINVAL);
5847 mov->nb_streams = s->nb_streams;
5848 if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters)
5849 mov->chapter_track = mov->nb_streams++;
5851 if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
5852 /* Add hint tracks for each audio and video stream */
5853 for (i = 0; i < s->nb_streams; i++) {
5854 AVStream *st = s->streams[i];
5855 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ||
5856 st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
5862 if ( mov->write_tmcd == -1 && (mov->mode == MODE_MOV || mov->mode == MODE_MP4)
5863 || mov->write_tmcd == 1) {
5864 /* +1 tmcd track for each video stream with a timecode */
5865 for (i = 0; i < s->nb_streams; i++) {
5866 AVStream *st = s->streams[i];
5867 AVDictionaryEntry *t = global_tcr;
5868 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
5869 (t || (t=av_dict_get(st->metadata, "timecode", NULL, 0)))) {
5871 ret = mov_check_timecode_track(s, &tc, i, t->value);
5873 mov->nb_meta_tmcd++;
5877 /* check if there is already a tmcd track to remux */
5878 if (mov->nb_meta_tmcd) {
5879 for (i = 0; i < s->nb_streams; i++) {
5880 AVStream *st = s->streams[i];
5881 if (st->codecpar->codec_tag == MKTAG('t','m','c','d')) {
5882 av_log(s, AV_LOG_WARNING, "You requested a copy of the original timecode track "
5883 "so timecode metadata are now ignored\n");
5884 mov->nb_meta_tmcd = 0;
5889 mov->nb_streams += mov->nb_meta_tmcd;
5892 // Reserve an extra stream for chapters for the case where chapters
5893 // are written in the trailer
5894 mov->tracks = av_mallocz_array((mov->nb_streams + 1), sizeof(*mov->tracks));
5896 return AVERROR(ENOMEM);
5898 if (mov->encryption_scheme_str != NULL && strcmp(mov->encryption_scheme_str, "none") != 0) {
5899 if (strcmp(mov->encryption_scheme_str, "cenc-aes-ctr") == 0) {
5900 mov->encryption_scheme = MOV_ENC_CENC_AES_CTR;
5902 if (mov->encryption_key_len != AES_CTR_KEY_SIZE) {
5903 av_log(s, AV_LOG_ERROR, "Invalid encryption key len %d expected %d\n",
5904 mov->encryption_key_len, AES_CTR_KEY_SIZE);
5905 return AVERROR(EINVAL);
5908 if (mov->encryption_kid_len != CENC_KID_SIZE) {
5909 av_log(s, AV_LOG_ERROR, "Invalid encryption kid len %d expected %d\n",
5910 mov->encryption_kid_len, CENC_KID_SIZE);
5911 return AVERROR(EINVAL);
5914 av_log(s, AV_LOG_ERROR, "unsupported encryption scheme %s\n",
5915 mov->encryption_scheme_str);
5916 return AVERROR(EINVAL);
5920 for (i = 0; i < s->nb_streams; i++) {
5921 AVStream *st= s->streams[i];
5922 MOVTrack *track= &mov->tracks[i];
5923 AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0);
5926 track->par = st->codecpar;
5927 track->language = ff_mov_iso639_to_lang(lang?lang->value:"und", mov->mode!=MODE_MOV);
5928 if (track->language < 0)
5929 track->language = 0;
5930 track->mode = mov->mode;
5931 track->tag = mov_find_codec_tag(s, track);
5933 av_log(s, AV_LOG_ERROR, "Could not find tag for codec %s in stream #%d, "
5934 "codec not currently supported in container\n",
5935 avcodec_get_name(st->codecpar->codec_id), i);
5936 return AVERROR(EINVAL);
5938 /* If hinting of this track is enabled by a later hint track,
5939 * this is updated. */
5940 track->hint_track = -1;
5941 track->start_dts = AV_NOPTS_VALUE;
5942 track->start_cts = AV_NOPTS_VALUE;
5943 track->end_pts = AV_NOPTS_VALUE;
5944 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
5945 if (track->tag == MKTAG('m','x','3','p') || track->tag == MKTAG('m','x','3','n') ||
5946 track->tag == MKTAG('m','x','4','p') || track->tag == MKTAG('m','x','4','n') ||
5947 track->tag == MKTAG('m','x','5','p') || track->tag == MKTAG('m','x','5','n')) {
5948 if (st->codecpar->width != 720 || (st->codecpar->height != 608 && st->codecpar->height != 512)) {
5949 av_log(s, AV_LOG_ERROR, "D-10/IMX must use 720x608 or 720x512 video resolution\n");
5950 return AVERROR(EINVAL);
5952 track->height = track->tag >> 24 == 'n' ? 486 : 576;
5954 if (mov->video_track_timescale) {
5955 track->timescale = mov->video_track_timescale;
5957 track->timescale = st->time_base.den;
5958 while(track->timescale < 10000)
5959 track->timescale *= 2;
5961 if (st->codecpar->width > 65535 || st->codecpar->height > 65535) {
5962 av_log(s, AV_LOG_ERROR, "Resolution %dx%d too large for mov/mp4\n", st->codecpar->width, st->codecpar->height);
5963 return AVERROR(EINVAL);
5965 if (track->mode == MODE_MOV && track->timescale > 100000)
5966 av_log(s, AV_LOG_WARNING,
5967 "WARNING codec timebase is very high. If duration is too long,\n"
5968 "file may not be playable by quicktime. Specify a shorter timebase\n"
5969 "or choose different container.\n");
5970 if (track->mode == MODE_MOV &&
5971 track->par->codec_id == AV_CODEC_ID_RAWVIDEO &&
5972 track->tag == MKTAG('r','a','w',' ')) {
5973 enum AVPixelFormat pix_fmt = track->par->format;
5974 if (pix_fmt == AV_PIX_FMT_NONE && track->par->bits_per_coded_sample == 1)
5975 pix_fmt = AV_PIX_FMT_MONOWHITE;
5976 track->is_unaligned_qt_rgb =
5977 pix_fmt == AV_PIX_FMT_RGB24 ||
5978 pix_fmt == AV_PIX_FMT_BGR24 ||
5979 pix_fmt == AV_PIX_FMT_PAL8 ||
5980 pix_fmt == AV_PIX_FMT_GRAY8 ||
5981 pix_fmt == AV_PIX_FMT_MONOWHITE ||
5982 pix_fmt == AV_PIX_FMT_MONOBLACK;
5984 if (track->par->codec_id == AV_CODEC_ID_VP9) {
5985 if (track->mode != MODE_MP4) {
5986 av_log(s, AV_LOG_ERROR, "VP9 only supported in MP4.\n");
5987 return AVERROR(EINVAL);
5989 if (s->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
5990 av_log(s, AV_LOG_ERROR,
5991 "VP9 in MP4 support is experimental, add "
5992 "'-strict %d' if you want to use it.\n",
5993 FF_COMPLIANCE_EXPERIMENTAL);
5994 return AVERROR_EXPERIMENTAL;
5997 } else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
5998 track->timescale = st->codecpar->sample_rate;
5999 if (!st->codecpar->frame_size && !av_get_bits_per_sample(st->codecpar->codec_id)) {
6000 av_log(s, AV_LOG_WARNING, "track %d: codec frame size is not set\n", i);
6001 track->audio_vbr = 1;
6002 }else if (st->codecpar->codec_id == AV_CODEC_ID_ADPCM_MS ||
6003 st->codecpar->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
6004 st->codecpar->codec_id == AV_CODEC_ID_ILBC){
6005 if (!st->codecpar->block_align) {
6006 av_log(s, AV_LOG_ERROR, "track %d: codec block align is not set for adpcm\n", i);
6007 return AVERROR(EINVAL);
6009 track->sample_size = st->codecpar->block_align;
6010 }else if (st->codecpar->frame_size > 1){ /* assume compressed audio */
6011 track->audio_vbr = 1;
6013 track->sample_size = (av_get_bits_per_sample(st->codecpar->codec_id) >> 3) * st->codecpar->channels;
6015 if (st->codecpar->codec_id == AV_CODEC_ID_ILBC ||
6016 st->codecpar->codec_id == AV_CODEC_ID_ADPCM_IMA_QT) {
6017 track->audio_vbr = 1;
6019 if (track->mode != MODE_MOV &&
6020 track->par->codec_id == AV_CODEC_ID_MP3 && track->timescale < 16000) {
6021 if (s->strict_std_compliance >= FF_COMPLIANCE_NORMAL) {
6022 av_log(s, AV_LOG_ERROR, "track %d: muxing mp3 at %dhz is not standard, to mux anyway set strict to -1\n",
6023 i, track->par->sample_rate);
6024 return AVERROR(EINVAL);
6026 av_log(s, AV_LOG_WARNING, "track %d: muxing mp3 at %dhz is not standard in MP4\n",
6027 i, track->par->sample_rate);
6030 if (track->par->codec_id == AV_CODEC_ID_FLAC ||
6031 track->par->codec_id == AV_CODEC_ID_OPUS) {
6032 if (track->mode != MODE_MP4) {
6033 av_log(s, AV_LOG_ERROR, "%s only supported in MP4.\n", avcodec_get_name(track->par->codec_id));
6034 return AVERROR(EINVAL);
6036 if (s->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
6037 av_log(s, AV_LOG_ERROR,
6038 "%s in MP4 support is experimental, add "
6039 "'-strict %d' if you want to use it.\n",
6040 avcodec_get_name(track->par->codec_id), FF_COMPLIANCE_EXPERIMENTAL);
6041 return AVERROR_EXPERIMENTAL;
6044 } else if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) {
6045 track->timescale = st->time_base.den;
6046 } else if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA) {
6047 track->timescale = st->time_base.den;
6049 track->timescale = MOV_TIMESCALE;
6052 track->height = st->codecpar->height;
6053 /* The ism specific timescale isn't mandatory, but is assumed by
6054 * some tools, such as mp4split. */
6055 if (mov->mode == MODE_ISM)
6056 track->timescale = 10000000;
6058 avpriv_set_pts_info(st, 64, 1, track->timescale);
6060 if (mov->encryption_scheme == MOV_ENC_CENC_AES_CTR) {
6061 ret = ff_mov_cenc_init(&track->cenc, mov->encryption_key,
6062 track->par->codec_id == AV_CODEC_ID_H264, s->flags & AVFMT_FLAG_BITEXACT);
6072 static int mov_write_header(AVFormatContext *s)
6074 AVIOContext *pb = s->pb;
6075 MOVMuxContext *mov = s->priv_data;
6076 AVDictionaryEntry *t, *global_tcr = av_dict_get(s->metadata, "timecode", NULL, 0);
6077 int i, ret, hint_track = 0, tmcd_track = 0, nb_tracks = s->nb_streams;
6079 if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters)
6082 if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
6083 /* Add hint tracks for each audio and video stream */
6084 hint_track = nb_tracks;
6085 for (i = 0; i < s->nb_streams; i++) {
6086 AVStream *st = s->streams[i];
6087 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ||
6088 st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
6094 if (mov->mode == MODE_MOV || mov->mode == MODE_MP4)
6095 tmcd_track = nb_tracks;
6097 for (i = 0; i < s->nb_streams; i++) {
6099 AVStream *st= s->streams[i];
6100 MOVTrack *track= &mov->tracks[i];
6102 /* copy extradata if it exists */
6103 if (st->codecpar->extradata_size) {
6104 if (st->codecpar->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
6105 mov_create_dvd_sub_decoder_specific_info(track, st);
6106 else if (!TAG_IS_AVCI(track->tag) && st->codecpar->codec_id != AV_CODEC_ID_DNXHD) {
6107 track->vos_len = st->codecpar->extradata_size;
6108 track->vos_data = av_malloc(track->vos_len);
6109 if (!track->vos_data) {
6110 return AVERROR(ENOMEM);
6112 memcpy(track->vos_data, st->codecpar->extradata, track->vos_len);
6116 if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ||
6117 track->par->channel_layout != AV_CH_LAYOUT_MONO)
6120 for (j = 0; j < s->nb_streams; j++) {
6121 AVStream *stj= s->streams[j];
6122 MOVTrack *trackj= &mov->tracks[j];
6126 if (stj->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ||
6127 trackj->par->channel_layout != AV_CH_LAYOUT_MONO ||
6128 trackj->language != track->language ||
6129 trackj->tag != track->tag
6132 track->multichannel_as_mono++;
6136 if (!(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
6137 if ((ret = mov_write_identification(pb, s)) < 0)
6141 if (mov->reserved_moov_size){
6142 mov->reserved_header_pos = avio_tell(pb);
6143 if (mov->reserved_moov_size > 0)
6144 avio_skip(pb, mov->reserved_moov_size);
6147 if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
6148 /* If no fragmentation options have been set, set a default. */
6149 if (!(mov->flags & (FF_MOV_FLAG_FRAG_KEYFRAME |
6150 FF_MOV_FLAG_FRAG_CUSTOM)) &&
6151 !mov->max_fragment_duration && !mov->max_fragment_size)
6152 mov->flags |= FF_MOV_FLAG_FRAG_KEYFRAME;
6154 if (mov->flags & FF_MOV_FLAG_FASTSTART)
6155 mov->reserved_header_pos = avio_tell(pb);
6156 mov_write_mdat_tag(pb, mov);
6159 ff_parse_creation_time_metadata(s, &mov->time, 1);
6161 mov->time += 0x7C25B080; // 1970 based -> 1904 based
6163 if (mov->chapter_track)
6164 if ((ret = mov_create_chapter_track(s, mov->chapter_track)) < 0)
6167 if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
6168 /* Initialize the hint tracks for each audio and video stream */
6169 for (i = 0; i < s->nb_streams; i++) {
6170 AVStream *st = s->streams[i];
6171 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ||
6172 st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
6173 if ((ret = ff_mov_init_hinting(s, hint_track, i)) < 0)
6180 if (mov->nb_meta_tmcd) {
6181 /* Initialize the tmcd tracks */
6182 for (i = 0; i < s->nb_streams; i++) {
6183 AVStream *st = s->streams[i];
6186 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
6189 t = av_dict_get(st->metadata, "timecode", NULL, 0);
6192 if (mov_check_timecode_track(s, &tc, i, t->value) < 0)
6194 if ((ret = mov_create_timecode_track(s, tmcd_track, i, tc)) < 0)
6203 if (mov->flags & FF_MOV_FLAG_ISML)
6204 mov_write_isml_manifest(pb, mov, s);
6206 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV &&
6207 !(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
6208 if ((ret = mov_write_moov_tag(pb, mov, s)) < 0)
6211 mov->moov_written = 1;
6212 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
6213 mov->reserved_header_pos = avio_tell(pb);
6219 static int get_moov_size(AVFormatContext *s)
6222 AVIOContext *moov_buf;
6223 MOVMuxContext *mov = s->priv_data;
6225 if ((ret = ffio_open_null_buf(&moov_buf)) < 0)
6227 if ((ret = mov_write_moov_tag(moov_buf, mov, s)) < 0)
6229 return ffio_close_null_buf(moov_buf);
6232 static int get_sidx_size(AVFormatContext *s)
6236 MOVMuxContext *mov = s->priv_data;
6238 if ((ret = ffio_open_null_buf(&buf)) < 0)
6240 mov_write_sidx_tags(buf, mov, -1, 0);
6241 return ffio_close_null_buf(buf);
6245 * This function gets the moov size if moved to the top of the file: the chunk
6246 * offset table can switch between stco (32-bit entries) to co64 (64-bit
6247 * entries) when the moov is moved to the beginning, so the size of the moov
6248 * would change. It also updates the chunk offset tables.
6250 static int compute_moov_size(AVFormatContext *s)
6252 int i, moov_size, moov_size2;
6253 MOVMuxContext *mov = s->priv_data;
6255 moov_size = get_moov_size(s);
6259 for (i = 0; i < mov->nb_streams; i++)
6260 mov->tracks[i].data_offset += moov_size;
6262 moov_size2 = get_moov_size(s);
6266 /* if the size changed, we just switched from stco to co64 and need to
6267 * update the offsets */
6268 if (moov_size2 != moov_size)
6269 for (i = 0; i < mov->nb_streams; i++)
6270 mov->tracks[i].data_offset += moov_size2 - moov_size;
6275 static int compute_sidx_size(AVFormatContext *s)
6278 MOVMuxContext *mov = s->priv_data;
6280 sidx_size = get_sidx_size(s);
6284 for (i = 0; i < mov->nb_streams; i++)
6285 mov->tracks[i].data_offset += sidx_size;
6290 static int shift_data(AVFormatContext *s)
6292 int ret = 0, moov_size;
6293 MOVMuxContext *mov = s->priv_data;
6294 int64_t pos, pos_end = avio_tell(s->pb);
6295 uint8_t *buf, *read_buf[2];
6296 int read_buf_id = 0;
6298 AVIOContext *read_pb;
6300 if (mov->flags & FF_MOV_FLAG_FRAGMENT)
6301 moov_size = compute_sidx_size(s);
6303 moov_size = compute_moov_size(s);
6307 buf = av_malloc(moov_size * 2);
6309 return AVERROR(ENOMEM);
6311 read_buf[1] = buf + moov_size;
6313 /* Shift the data: the AVIO context of the output can only be used for
6314 * writing, so we re-open the same output, but for reading. It also avoids
6315 * a read/seek/write/seek back and forth. */
6317 ret = s->io_open(s, &read_pb, s->filename, AVIO_FLAG_READ, NULL);
6319 av_log(s, AV_LOG_ERROR, "Unable to re-open %s output file for "
6320 "the second pass (faststart)\n", s->filename);
6324 /* mark the end of the shift to up to the last data we wrote, and get ready
6326 pos_end = avio_tell(s->pb);
6327 avio_seek(s->pb, mov->reserved_header_pos + moov_size, SEEK_SET);
6329 /* start reading at where the new moov will be placed */
6330 avio_seek(read_pb, mov->reserved_header_pos, SEEK_SET);
6331 pos = avio_tell(read_pb);
6333 #define READ_BLOCK do { \
6334 read_size[read_buf_id] = avio_read(read_pb, read_buf[read_buf_id], moov_size); \
6338 /* shift data by chunk of at most moov_size */
6343 n = read_size[read_buf_id];
6346 avio_write(s->pb, read_buf[read_buf_id], n);
6348 } while (pos < pos_end);
6349 ff_format_io_close(s, &read_pb);
6356 static int mov_write_trailer(AVFormatContext *s)
6358 MOVMuxContext *mov = s->priv_data;
6359 AVIOContext *pb = s->pb;
6364 if (mov->need_rewrite_extradata) {
6365 for (i = 0; i < s->nb_streams; i++) {
6366 MOVTrack *track = &mov->tracks[i];
6367 AVCodecParameters *par = track->par;
6369 track->vos_len = par->extradata_size;
6370 track->vos_data = av_malloc(track->vos_len);
6371 if (!track->vos_data)
6372 return AVERROR(ENOMEM);
6373 memcpy(track->vos_data, par->extradata, track->vos_len);
6375 mov->need_rewrite_extradata = 0;
6379 * Before actually writing the trailer, make sure that there are no
6380 * dangling subtitles, that need a terminating sample.
6382 for (i = 0; i < mov->nb_streams; i++) {
6383 MOVTrack *trk = &mov->tracks[i];
6384 if (trk->par->codec_id == AV_CODEC_ID_MOV_TEXT &&
6385 !trk->last_sample_is_subtitle_end) {
6386 mov_write_subtitle_end_packet(s, i, trk->track_duration);
6387 trk->last_sample_is_subtitle_end = 1;
6391 // If there were no chapters when the header was written, but there
6392 // are chapters now, write them in the trailer. This only works
6393 // when we are not doing fragments.
6394 if (!mov->chapter_track && !(mov->flags & FF_MOV_FLAG_FRAGMENT)) {
6395 if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters) {
6396 mov->chapter_track = mov->nb_streams++;
6397 if ((res = mov_create_chapter_track(s, mov->chapter_track)) < 0)
6402 if (!(mov->flags & FF_MOV_FLAG_FRAGMENT)) {
6403 moov_pos = avio_tell(pb);
6405 /* Write size of mdat tag */
6406 if (mov->mdat_size + 8 <= UINT32_MAX) {
6407 avio_seek(pb, mov->mdat_pos, SEEK_SET);
6408 avio_wb32(pb, mov->mdat_size + 8);
6410 /* overwrite 'wide' placeholder atom */
6411 avio_seek(pb, mov->mdat_pos - 8, SEEK_SET);
6412 /* special value: real atom size will be 64 bit value after
6415 ffio_wfourcc(pb, "mdat");
6416 avio_wb64(pb, mov->mdat_size + 16);
6418 avio_seek(pb, mov->reserved_moov_size > 0 ? mov->reserved_header_pos : moov_pos, SEEK_SET);
6420 if (mov->flags & FF_MOV_FLAG_FASTSTART) {
6421 av_log(s, AV_LOG_INFO, "Starting second pass: moving the moov atom to the beginning of the file\n");
6422 res = shift_data(s);
6425 avio_seek(pb, mov->reserved_header_pos, SEEK_SET);
6426 if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
6428 } else if (mov->reserved_moov_size > 0) {
6430 if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
6432 size = mov->reserved_moov_size - (avio_tell(pb) - mov->reserved_header_pos);
6434 av_log(s, AV_LOG_ERROR, "reserved_moov_size is too small, needed %"PRId64" additional\n", 8-size);
6435 return AVERROR(EINVAL);
6437 avio_wb32(pb, size);
6438 ffio_wfourcc(pb, "free");
6439 ffio_fill(pb, 0, size - 8);
6440 avio_seek(pb, moov_pos, SEEK_SET);
6442 if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
6447 mov_auto_flush_fragment(s, 1);
6448 for (i = 0; i < mov->nb_streams; i++)
6449 mov->tracks[i].data_offset = 0;
6450 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) {
6452 av_log(s, AV_LOG_INFO, "Starting second pass: inserting sidx atoms\n");
6453 res = shift_data(s);
6456 end = avio_tell(pb);
6457 avio_seek(pb, mov->reserved_header_pos, SEEK_SET);
6458 mov_write_sidx_tags(pb, mov, -1, 0);
6459 avio_seek(pb, end, SEEK_SET);
6460 avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_TRAILER);
6461 mov_write_mfra_tag(pb, mov);
6462 } else if (!(mov->flags & FF_MOV_FLAG_SKIP_TRAILER)) {
6463 avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_TRAILER);
6464 mov_write_mfra_tag(pb, mov);
6471 static int mov_check_bitstream(struct AVFormatContext *s, const AVPacket *pkt)
6474 AVStream *st = s->streams[pkt->stream_index];
6476 if (st->codecpar->codec_id == AV_CODEC_ID_AAC) {
6477 if (pkt->size > 2 && (AV_RB16(pkt->data) & 0xfff0) == 0xfff0)
6478 ret = ff_stream_add_bitstream_filter(st, "aac_adtstoasc", NULL);
6479 } else if (st->codecpar->codec_id == AV_CODEC_ID_VP9) {
6480 ret = ff_stream_add_bitstream_filter(st, "vp9_superframe", NULL);
6486 #if CONFIG_MOV_MUXER
6488 AVOutputFormat ff_mov_muxer = {
6490 .long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
6491 .extensions = "mov",
6492 .priv_data_size = sizeof(MOVMuxContext),
6493 .audio_codec = AV_CODEC_ID_AAC,
6494 .video_codec = CONFIG_LIBX264_ENCODER ?
6495 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
6497 .write_header = mov_write_header,
6498 .write_packet = mov_write_packet,
6499 .write_trailer = mov_write_trailer,
6501 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6502 .codec_tag = (const AVCodecTag* const []){
6503 ff_codec_movvideo_tags, ff_codec_movaudio_tags, 0
6505 .check_bitstream = mov_check_bitstream,
6506 .priv_class = &mov_muxer_class,
6509 #if CONFIG_TGP_MUXER
6511 AVOutputFormat ff_tgp_muxer = {
6513 .long_name = NULL_IF_CONFIG_SMALL("3GP (3GPP file format)"),
6514 .extensions = "3gp",
6515 .priv_data_size = sizeof(MOVMuxContext),
6516 .audio_codec = AV_CODEC_ID_AMR_NB,
6517 .video_codec = AV_CODEC_ID_H263,
6519 .write_header = mov_write_header,
6520 .write_packet = mov_write_packet,
6521 .write_trailer = mov_write_trailer,
6523 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6524 .codec_tag = (const AVCodecTag* const []){ codec_3gp_tags, 0 },
6525 .check_bitstream = mov_check_bitstream,
6526 .priv_class = &tgp_muxer_class,
6529 #if CONFIG_MP4_MUXER
6531 AVOutputFormat ff_mp4_muxer = {
6533 .long_name = NULL_IF_CONFIG_SMALL("MP4 (MPEG-4 Part 14)"),
6534 .mime_type = "video/mp4",
6535 .extensions = "mp4",
6536 .priv_data_size = sizeof(MOVMuxContext),
6537 .audio_codec = AV_CODEC_ID_AAC,
6538 .video_codec = CONFIG_LIBX264_ENCODER ?
6539 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
6541 .write_header = mov_write_header,
6542 .write_packet = mov_write_packet,
6543 .write_trailer = mov_write_trailer,
6545 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6546 .codec_tag = (const AVCodecTag* const []){ ff_mp4_obj_type, 0 },
6547 .check_bitstream = mov_check_bitstream,
6548 .priv_class = &mp4_muxer_class,
6551 #if CONFIG_PSP_MUXER
6553 AVOutputFormat ff_psp_muxer = {
6555 .long_name = NULL_IF_CONFIG_SMALL("PSP MP4 (MPEG-4 Part 14)"),
6556 .extensions = "mp4,psp",
6557 .priv_data_size = sizeof(MOVMuxContext),
6558 .audio_codec = AV_CODEC_ID_AAC,
6559 .video_codec = CONFIG_LIBX264_ENCODER ?
6560 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
6562 .write_header = mov_write_header,
6563 .write_packet = mov_write_packet,
6564 .write_trailer = mov_write_trailer,
6566 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6567 .codec_tag = (const AVCodecTag* const []){ ff_mp4_obj_type, 0 },
6568 .check_bitstream = mov_check_bitstream,
6569 .priv_class = &psp_muxer_class,
6572 #if CONFIG_TG2_MUXER
6574 AVOutputFormat ff_tg2_muxer = {
6576 .long_name = NULL_IF_CONFIG_SMALL("3GP2 (3GPP2 file format)"),
6577 .extensions = "3g2",
6578 .priv_data_size = sizeof(MOVMuxContext),
6579 .audio_codec = AV_CODEC_ID_AMR_NB,
6580 .video_codec = AV_CODEC_ID_H263,
6582 .write_header = mov_write_header,
6583 .write_packet = mov_write_packet,
6584 .write_trailer = mov_write_trailer,
6586 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6587 .codec_tag = (const AVCodecTag* const []){ codec_3gp_tags, 0 },
6588 .check_bitstream = mov_check_bitstream,
6589 .priv_class = &tg2_muxer_class,
6592 #if CONFIG_IPOD_MUXER
6594 AVOutputFormat ff_ipod_muxer = {
6596 .long_name = NULL_IF_CONFIG_SMALL("iPod H.264 MP4 (MPEG-4 Part 14)"),
6597 .mime_type = "video/mp4",
6598 .extensions = "m4v,m4a",
6599 .priv_data_size = sizeof(MOVMuxContext),
6600 .audio_codec = AV_CODEC_ID_AAC,
6601 .video_codec = AV_CODEC_ID_H264,
6603 .write_header = mov_write_header,
6604 .write_packet = mov_write_packet,
6605 .write_trailer = mov_write_trailer,
6607 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6608 .codec_tag = (const AVCodecTag* const []){ codec_ipod_tags, 0 },
6609 .check_bitstream = mov_check_bitstream,
6610 .priv_class = &ipod_muxer_class,
6613 #if CONFIG_ISMV_MUXER
6615 AVOutputFormat ff_ismv_muxer = {
6617 .long_name = NULL_IF_CONFIG_SMALL("ISMV/ISMA (Smooth Streaming)"),
6618 .mime_type = "video/mp4",
6619 .extensions = "ismv,isma",
6620 .priv_data_size = sizeof(MOVMuxContext),
6621 .audio_codec = AV_CODEC_ID_AAC,
6622 .video_codec = AV_CODEC_ID_H264,
6624 .write_header = mov_write_header,
6625 .write_packet = mov_write_packet,
6626 .write_trailer = mov_write_trailer,
6628 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6629 .codec_tag = (const AVCodecTag* const []){ ff_mp4_obj_type, 0 },
6630 .check_bitstream = mov_check_bitstream,
6631 .priv_class = &ismv_muxer_class,
6634 #if CONFIG_F4V_MUXER
6636 AVOutputFormat ff_f4v_muxer = {
6638 .long_name = NULL_IF_CONFIG_SMALL("F4V Adobe Flash Video"),
6639 .mime_type = "application/f4v",
6640 .extensions = "f4v",
6641 .priv_data_size = sizeof(MOVMuxContext),
6642 .audio_codec = AV_CODEC_ID_AAC,
6643 .video_codec = AV_CODEC_ID_H264,
6645 .write_header = mov_write_header,
6646 .write_packet = mov_write_packet,
6647 .write_trailer = mov_write_trailer,
6649 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH,
6650 .codec_tag = (const AVCodecTag* const []){ codec_f4v_tags, 0 },
6651 .check_bitstream = mov_check_bitstream,
6652 .priv_class = &f4v_muxer_class,