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_w8(pb, 1); /* version */
1116 avio_wb24(pb, 0); /* flags */
1117 ff_isom_write_vpcc(s, pb, track->par);
1118 return update_size(pb, pos);
1121 static int mov_write_hvcc_tag(AVIOContext *pb, MOVTrack *track)
1123 int64_t pos = avio_tell(pb);
1126 ffio_wfourcc(pb, "hvcC");
1127 ff_isom_write_hvcc(pb, track->vos_data, track->vos_len, 0);
1128 return update_size(pb, pos);
1131 /* also used by all avid codecs (dv, imx, meridien) and their variants */
1132 static int mov_write_avid_tag(AVIOContext *pb, MOVTrack *track)
1137 int display_width = track->par->width;
1139 if (track->vos_data && track->vos_len > 0x29) {
1140 if (ff_dnxhd_parse_header_prefix(track->vos_data) != 0) {
1141 /* looks like a DNxHD bit stream */
1142 interlaced = (track->vos_data[5] & 2);
1143 cid = AV_RB32(track->vos_data + 0x28);
1145 av_log(NULL, AV_LOG_WARNING, "Could not locate DNxHD bit stream in vos_data\n");
1149 av_log(NULL, AV_LOG_WARNING, "Could not locate DNxHD bit stream, vos_data too small\n");
1153 avio_wb32(pb, 24); /* size */
1154 ffio_wfourcc(pb, "ACLR");
1155 ffio_wfourcc(pb, "ACLR");
1156 ffio_wfourcc(pb, "0001");
1157 if (track->par->color_range == AVCOL_RANGE_MPEG || /* Legal range (16-235) */
1158 track->par->color_range == AVCOL_RANGE_UNSPECIFIED) {
1159 avio_wb32(pb, 1); /* Corresponds to 709 in official encoder */
1160 } else { /* Full range (0-255) */
1161 avio_wb32(pb, 2); /* Corresponds to RGB in official encoder */
1163 avio_wb32(pb, 0); /* unknown */
1165 if (track->tag == MKTAG('A','V','d','h')) {
1167 ffio_wfourcc(pb, "ADHR");
1168 ffio_wfourcc(pb, "0001");
1170 avio_wb32(pb, 0); /* unknown */
1171 avio_wb32(pb, 1); /* unknown */
1172 avio_wb32(pb, 0); /* unknown */
1173 avio_wb32(pb, 0); /* unknown */
1177 avio_wb32(pb, 24); /* size */
1178 ffio_wfourcc(pb, "APRG");
1179 ffio_wfourcc(pb, "APRG");
1180 ffio_wfourcc(pb, "0001");
1181 avio_wb32(pb, 1); /* unknown */
1182 avio_wb32(pb, 0); /* unknown */
1184 avio_wb32(pb, 120); /* size */
1185 ffio_wfourcc(pb, "ARES");
1186 ffio_wfourcc(pb, "ARES");
1187 ffio_wfourcc(pb, "0001");
1188 avio_wb32(pb, cid); /* dnxhd cid, some id ? */
1189 if ( track->par->sample_aspect_ratio.num > 0
1190 && track->par->sample_aspect_ratio.den > 0)
1191 display_width = display_width * track->par->sample_aspect_ratio.num / track->par->sample_aspect_ratio.den;
1192 avio_wb32(pb, display_width);
1193 /* values below are based on samples created with quicktime and avid codecs */
1195 avio_wb32(pb, track->par->height / 2);
1196 avio_wb32(pb, 2); /* unknown */
1197 avio_wb32(pb, 0); /* unknown */
1198 avio_wb32(pb, 4); /* unknown */
1200 avio_wb32(pb, track->par->height);
1201 avio_wb32(pb, 1); /* unknown */
1202 avio_wb32(pb, 0); /* unknown */
1203 if (track->par->height == 1080)
1204 avio_wb32(pb, 5); /* unknown */
1206 avio_wb32(pb, 6); /* unknown */
1209 for (i = 0; i < 10; i++)
1215 static int mov_write_dpxe_tag(AVIOContext *pb, MOVTrack *track)
1218 ffio_wfourcc(pb, "DpxE");
1219 if (track->par->extradata_size >= 12 &&
1220 !memcmp(&track->par->extradata[4], "DpxE", 4)) {
1221 avio_wb32(pb, track->par->extradata[11]);
1228 static int mp4_get_codec_tag(AVFormatContext *s, MOVTrack *track)
1230 int tag = track->par->codec_tag;
1232 if (!ff_codec_get_tag(ff_mp4_obj_type, track->par->codec_id))
1235 if (track->par->codec_id == AV_CODEC_ID_H264) tag = MKTAG('a','v','c','1');
1236 else if (track->par->codec_id == AV_CODEC_ID_HEVC) tag = MKTAG('h','e','v','1');
1237 else if (track->par->codec_id == AV_CODEC_ID_VP9) tag = MKTAG('v','p','0','9');
1238 else if (track->par->codec_id == AV_CODEC_ID_AC3) tag = MKTAG('a','c','-','3');
1239 else if (track->par->codec_id == AV_CODEC_ID_EAC3) tag = MKTAG('e','c','-','3');
1240 else if (track->par->codec_id == AV_CODEC_ID_DIRAC) tag = MKTAG('d','r','a','c');
1241 else if (track->par->codec_id == AV_CODEC_ID_MOV_TEXT) tag = MKTAG('t','x','3','g');
1242 else if (track->par->codec_id == AV_CODEC_ID_VC1) tag = MKTAG('v','c','-','1');
1243 else if (track->par->codec_id == AV_CODEC_ID_FLAC) tag = MKTAG('f','L','a','C');
1244 else if (track->par->codec_id == AV_CODEC_ID_OPUS) tag = MKTAG('O','p','u','s');
1245 else if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) tag = MKTAG('m','p','4','v');
1246 else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) tag = MKTAG('m','p','4','a');
1247 else if (track->par->codec_id == AV_CODEC_ID_DVD_SUBTITLE) tag = MKTAG('m','p','4','s');
1252 static const AVCodecTag codec_ipod_tags[] = {
1253 { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
1254 { AV_CODEC_ID_MPEG4, MKTAG('m','p','4','v') },
1255 { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
1256 { AV_CODEC_ID_ALAC, MKTAG('a','l','a','c') },
1257 { AV_CODEC_ID_AC3, MKTAG('a','c','-','3') },
1258 { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
1259 { AV_CODEC_ID_MOV_TEXT, MKTAG('t','e','x','t') },
1260 { AV_CODEC_ID_NONE, 0 },
1263 static int ipod_get_codec_tag(AVFormatContext *s, MOVTrack *track)
1265 int tag = track->par->codec_tag;
1267 // keep original tag for subs, ipod supports both formats
1268 if (!(track->par->codec_type == AVMEDIA_TYPE_SUBTITLE &&
1269 (tag == MKTAG('t', 'x', '3', 'g') ||
1270 tag == MKTAG('t', 'e', 'x', 't'))))
1271 tag = ff_codec_get_tag(codec_ipod_tags, track->par->codec_id);
1273 if (!av_match_ext(s->filename, "m4a") &&
1274 !av_match_ext(s->filename, "m4b") &&
1275 !av_match_ext(s->filename, "m4v"))
1276 av_log(s, AV_LOG_WARNING, "Warning, extension is not .m4a, .m4v nor .m4b "
1277 "Quicktime/Ipod might not play the file\n");
1282 static int mov_get_dv_codec_tag(AVFormatContext *s, MOVTrack *track)
1286 if (track->par->width == 720) { /* SD */
1287 if (track->par->height == 480) { /* NTSC */
1288 if (track->par->format == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','n');
1289 else tag = MKTAG('d','v','c',' ');
1290 }else if (track->par->format == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','p');
1291 else if (track->par->format == AV_PIX_FMT_YUV420P) tag = MKTAG('d','v','c','p');
1292 else tag = MKTAG('d','v','p','p');
1293 } else if (track->par->height == 720) { /* HD 720 line */
1294 if (track->st->time_base.den == 50) tag = MKTAG('d','v','h','q');
1295 else tag = MKTAG('d','v','h','p');
1296 } else if (track->par->height == 1080) { /* HD 1080 line */
1297 if (track->st->time_base.den == 25) tag = MKTAG('d','v','h','5');
1298 else tag = MKTAG('d','v','h','6');
1300 av_log(s, AV_LOG_ERROR, "unsupported height for dv codec\n");
1307 static AVRational find_fps(AVFormatContext *s, AVStream *st)
1309 AVRational rate = st->avg_frame_rate;
1311 #if FF_API_LAVF_AVCTX
1312 FF_DISABLE_DEPRECATION_WARNINGS
1313 rate = av_inv_q(st->codec->time_base);
1314 if (av_timecode_check_frame_rate(rate) < 0) {
1315 av_log(s, AV_LOG_DEBUG, "timecode: tbc=%d/%d invalid, fallback on %d/%d\n",
1316 rate.num, rate.den, st->avg_frame_rate.num, st->avg_frame_rate.den);
1317 rate = st->avg_frame_rate;
1319 FF_ENABLE_DEPRECATION_WARNINGS
1325 static int defined_frame_rate(AVFormatContext *s, AVStream *st)
1327 AVRational rational_framerate = find_fps(s, st);
1329 if (rational_framerate.den != 0)
1330 rate = av_q2d(rational_framerate);
1334 static int mov_get_mpeg2_xdcam_codec_tag(AVFormatContext *s, MOVTrack *track)
1336 int tag = track->par->codec_tag;
1337 int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE;
1338 AVStream *st = track->st;
1339 int rate = defined_frame_rate(s, st);
1342 tag = MKTAG('m', '2', 'v', '1'); //fallback tag
1344 if (track->par->format == AV_PIX_FMT_YUV420P) {
1345 if (track->par->width == 1280 && track->par->height == 720) {
1347 if (rate == 24) tag = MKTAG('x','d','v','4');
1348 else if (rate == 25) tag = MKTAG('x','d','v','5');
1349 else if (rate == 30) tag = MKTAG('x','d','v','1');
1350 else if (rate == 50) tag = MKTAG('x','d','v','a');
1351 else if (rate == 60) tag = MKTAG('x','d','v','9');
1353 } else if (track->par->width == 1440 && track->par->height == 1080) {
1355 if (rate == 24) tag = MKTAG('x','d','v','6');
1356 else if (rate == 25) tag = MKTAG('x','d','v','7');
1357 else if (rate == 30) tag = MKTAG('x','d','v','8');
1359 if (rate == 25) tag = MKTAG('x','d','v','3');
1360 else if (rate == 30) tag = MKTAG('x','d','v','2');
1362 } else if (track->par->width == 1920 && track->par->height == 1080) {
1364 if (rate == 24) tag = MKTAG('x','d','v','d');
1365 else if (rate == 25) tag = MKTAG('x','d','v','e');
1366 else if (rate == 30) tag = MKTAG('x','d','v','f');
1368 if (rate == 25) tag = MKTAG('x','d','v','c');
1369 else if (rate == 30) tag = MKTAG('x','d','v','b');
1372 } else if (track->par->format == AV_PIX_FMT_YUV422P) {
1373 if (track->par->width == 1280 && track->par->height == 720) {
1375 if (rate == 24) tag = MKTAG('x','d','5','4');
1376 else if (rate == 25) tag = MKTAG('x','d','5','5');
1377 else if (rate == 30) tag = MKTAG('x','d','5','1');
1378 else if (rate == 50) tag = MKTAG('x','d','5','a');
1379 else if (rate == 60) tag = MKTAG('x','d','5','9');
1381 } else if (track->par->width == 1920 && track->par->height == 1080) {
1383 if (rate == 24) tag = MKTAG('x','d','5','d');
1384 else if (rate == 25) tag = MKTAG('x','d','5','e');
1385 else if (rate == 30) tag = MKTAG('x','d','5','f');
1387 if (rate == 25) tag = MKTAG('x','d','5','c');
1388 else if (rate == 30) tag = MKTAG('x','d','5','b');
1396 static int mov_get_h264_codec_tag(AVFormatContext *s, MOVTrack *track)
1398 int tag = track->par->codec_tag;
1399 int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE;
1400 AVStream *st = track->st;
1401 int rate = defined_frame_rate(s, st);
1404 tag = MKTAG('a', 'v', 'c', 'i'); //fallback tag
1406 if (track->par->format == AV_PIX_FMT_YUV420P10) {
1407 if (track->par->width == 960 && track->par->height == 720) {
1409 if (rate == 24) tag = MKTAG('a','i','5','p');
1410 else if (rate == 25) tag = MKTAG('a','i','5','q');
1411 else if (rate == 30) tag = MKTAG('a','i','5','p');
1412 else if (rate == 50) tag = MKTAG('a','i','5','q');
1413 else if (rate == 60) tag = MKTAG('a','i','5','p');
1415 } else if (track->par->width == 1440 && track->par->height == 1080) {
1417 if (rate == 24) tag = MKTAG('a','i','5','3');
1418 else if (rate == 25) tag = MKTAG('a','i','5','2');
1419 else if (rate == 30) tag = MKTAG('a','i','5','3');
1421 if (rate == 50) tag = MKTAG('a','i','5','5');
1422 else if (rate == 60) tag = MKTAG('a','i','5','6');
1425 } else if (track->par->format == AV_PIX_FMT_YUV422P10) {
1426 if (track->par->width == 1280 && track->par->height == 720) {
1428 if (rate == 24) tag = MKTAG('a','i','1','p');
1429 else if (rate == 25) tag = MKTAG('a','i','1','q');
1430 else if (rate == 30) tag = MKTAG('a','i','1','p');
1431 else if (rate == 50) tag = MKTAG('a','i','1','q');
1432 else if (rate == 60) tag = MKTAG('a','i','1','p');
1434 } else if (track->par->width == 1920 && track->par->height == 1080) {
1436 if (rate == 24) tag = MKTAG('a','i','1','3');
1437 else if (rate == 25) tag = MKTAG('a','i','1','2');
1438 else if (rate == 30) tag = MKTAG('a','i','1','3');
1440 if (rate == 25) tag = MKTAG('a','i','1','5');
1441 else if (rate == 50) tag = MKTAG('a','i','1','5');
1442 else if (rate == 60) tag = MKTAG('a','i','1','6');
1444 } else if ( track->par->width == 4096 && track->par->height == 2160
1445 || track->par->width == 3840 && track->par->height == 2160
1446 || track->par->width == 2048 && track->par->height == 1080) {
1447 tag = MKTAG('a','i','v','x');
1454 static const struct {
1455 enum AVPixelFormat pix_fmt;
1458 } mov_pix_fmt_tags[] = {
1459 { AV_PIX_FMT_YUYV422, MKTAG('y','u','v','2'), 0 },
1460 { AV_PIX_FMT_YUYV422, MKTAG('y','u','v','s'), 0 },
1461 { AV_PIX_FMT_UYVY422, MKTAG('2','v','u','y'), 0 },
1462 { AV_PIX_FMT_RGB555BE,MKTAG('r','a','w',' '), 16 },
1463 { AV_PIX_FMT_RGB555LE,MKTAG('L','5','5','5'), 16 },
1464 { AV_PIX_FMT_RGB565LE,MKTAG('L','5','6','5'), 16 },
1465 { AV_PIX_FMT_RGB565BE,MKTAG('B','5','6','5'), 16 },
1466 { AV_PIX_FMT_GRAY16BE,MKTAG('b','1','6','g'), 16 },
1467 { AV_PIX_FMT_RGB24, MKTAG('r','a','w',' '), 24 },
1468 { AV_PIX_FMT_BGR24, MKTAG('2','4','B','G'), 24 },
1469 { AV_PIX_FMT_ARGB, MKTAG('r','a','w',' '), 32 },
1470 { AV_PIX_FMT_BGRA, MKTAG('B','G','R','A'), 32 },
1471 { AV_PIX_FMT_RGBA, MKTAG('R','G','B','A'), 32 },
1472 { AV_PIX_FMT_ABGR, MKTAG('A','B','G','R'), 32 },
1473 { AV_PIX_FMT_RGB48BE, MKTAG('b','4','8','r'), 48 },
1476 static int mov_get_dnxhd_codec_tag(AVFormatContext *s, MOVTrack *track)
1478 int tag = MKTAG('A','V','d','n');
1479 if (track->par->profile != FF_PROFILE_UNKNOWN &&
1480 track->par->profile != FF_PROFILE_DNXHD)
1481 tag = MKTAG('A','V','d','h');
1485 static int mov_get_rawvideo_codec_tag(AVFormatContext *s, MOVTrack *track)
1487 int tag = track->par->codec_tag;
1489 enum AVPixelFormat pix_fmt;
1491 for (i = 0; i < FF_ARRAY_ELEMS(mov_pix_fmt_tags); i++) {
1492 if (track->par->format == mov_pix_fmt_tags[i].pix_fmt) {
1493 tag = mov_pix_fmt_tags[i].tag;
1494 track->par->bits_per_coded_sample = mov_pix_fmt_tags[i].bps;
1495 if (track->par->codec_tag == mov_pix_fmt_tags[i].tag)
1500 pix_fmt = avpriv_find_pix_fmt(avpriv_pix_fmt_bps_mov,
1501 track->par->bits_per_coded_sample);
1502 if (tag == MKTAG('r','a','w',' ') &&
1503 track->par->format != pix_fmt &&
1504 track->par->format != AV_PIX_FMT_GRAY8 &&
1505 track->par->format != AV_PIX_FMT_NONE)
1506 av_log(s, AV_LOG_ERROR, "%s rawvideo cannot be written to mov, output file will be unreadable\n",
1507 av_get_pix_fmt_name(track->par->format));
1511 static int mov_get_codec_tag(AVFormatContext *s, MOVTrack *track)
1513 int tag = track->par->codec_tag;
1515 if (!tag || (s->strict_std_compliance >= FF_COMPLIANCE_NORMAL &&
1516 (track->par->codec_id == AV_CODEC_ID_DVVIDEO ||
1517 track->par->codec_id == AV_CODEC_ID_RAWVIDEO ||
1518 track->par->codec_id == AV_CODEC_ID_H263 ||
1519 track->par->codec_id == AV_CODEC_ID_H264 ||
1520 track->par->codec_id == AV_CODEC_ID_DNXHD ||
1521 track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO ||
1522 av_get_bits_per_sample(track->par->codec_id)))) { // pcm audio
1523 if (track->par->codec_id == AV_CODEC_ID_DVVIDEO)
1524 tag = mov_get_dv_codec_tag(s, track);
1525 else if (track->par->codec_id == AV_CODEC_ID_RAWVIDEO)
1526 tag = mov_get_rawvideo_codec_tag(s, track);
1527 else if (track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO)
1528 tag = mov_get_mpeg2_xdcam_codec_tag(s, track);
1529 else if (track->par->codec_id == AV_CODEC_ID_H264)
1530 tag = mov_get_h264_codec_tag(s, track);
1531 else if (track->par->codec_id == AV_CODEC_ID_DNXHD)
1532 tag = mov_get_dnxhd_codec_tag(s, track);
1533 else if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
1534 tag = ff_codec_get_tag(ff_codec_movvideo_tags, track->par->codec_id);
1535 if (!tag) { // if no mac fcc found, try with Microsoft tags
1536 tag = ff_codec_get_tag(ff_codec_bmp_tags, track->par->codec_id);
1538 av_log(s, AV_LOG_WARNING, "Using MS style video codec tag, "
1539 "the file may be unplayable!\n");
1541 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
1542 tag = ff_codec_get_tag(ff_codec_movaudio_tags, track->par->codec_id);
1543 if (!tag) { // if no mac fcc found, try with Microsoft tags
1544 int ms_tag = ff_codec_get_tag(ff_codec_wav_tags, track->par->codec_id);
1546 tag = MKTAG('m', 's', ((ms_tag >> 8) & 0xff), (ms_tag & 0xff));
1547 av_log(s, AV_LOG_WARNING, "Using MS style audio codec tag, "
1548 "the file may be unplayable!\n");
1551 } else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)
1552 tag = ff_codec_get_tag(ff_codec_movsubtitle_tags, track->par->codec_id);
1558 static const AVCodecTag codec_3gp_tags[] = {
1559 { AV_CODEC_ID_H263, MKTAG('s','2','6','3') },
1560 { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
1561 { AV_CODEC_ID_MPEG4, MKTAG('m','p','4','v') },
1562 { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
1563 { AV_CODEC_ID_AMR_NB, MKTAG('s','a','m','r') },
1564 { AV_CODEC_ID_AMR_WB, MKTAG('s','a','w','b') },
1565 { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
1566 { AV_CODEC_ID_NONE, 0 },
1569 static const AVCodecTag codec_f4v_tags[] = { // XXX: add GIF/PNG/JPEG?
1570 { AV_CODEC_ID_MP3, MKTAG('.','m','p','3') },
1571 { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
1572 { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
1573 { AV_CODEC_ID_VP6A, MKTAG('V','P','6','A') },
1574 { AV_CODEC_ID_VP6F, MKTAG('V','P','6','F') },
1575 { AV_CODEC_ID_NONE, 0 },
1578 static int mov_find_codec_tag(AVFormatContext *s, MOVTrack *track)
1582 if (track->mode == MODE_MP4 || track->mode == MODE_PSP)
1583 tag = mp4_get_codec_tag(s, track);
1584 else if (track->mode == MODE_ISM) {
1585 tag = mp4_get_codec_tag(s, track);
1586 if (!tag && track->par->codec_id == AV_CODEC_ID_WMAPRO)
1587 tag = MKTAG('w', 'm', 'a', ' ');
1588 } else if (track->mode == MODE_IPOD)
1589 tag = ipod_get_codec_tag(s, track);
1590 else if (track->mode & MODE_3GP)
1591 tag = ff_codec_get_tag(codec_3gp_tags, track->par->codec_id);
1592 else if (track->mode == MODE_F4V)
1593 tag = ff_codec_get_tag(codec_f4v_tags, track->par->codec_id);
1595 tag = mov_get_codec_tag(s, track);
1600 /** Write uuid atom.
1601 * Needed to make file play in iPods running newest firmware
1602 * goes after avcC atom in moov.trak.mdia.minf.stbl.stsd.avc1
1604 static int mov_write_uuid_tag_ipod(AVIOContext *pb)
1607 ffio_wfourcc(pb, "uuid");
1608 avio_wb32(pb, 0x6b6840f2);
1609 avio_wb32(pb, 0x5f244fc5);
1610 avio_wb32(pb, 0xba39a51b);
1611 avio_wb32(pb, 0xcf0323f3);
1616 static const uint16_t fiel_data[] = {
1617 0x0000, 0x0100, 0x0201, 0x0206, 0x0209, 0x020e
1620 static int mov_write_fiel_tag(AVIOContext *pb, MOVTrack *track, int field_order)
1622 unsigned mov_field_order = 0;
1623 if (field_order < FF_ARRAY_ELEMS(fiel_data))
1624 mov_field_order = fiel_data[field_order];
1628 ffio_wfourcc(pb, "fiel");
1629 avio_wb16(pb, mov_field_order);
1633 static int mov_write_subtitle_tag(AVIOContext *pb, MOVTrack *track)
1635 int64_t pos = avio_tell(pb);
1636 avio_wb32(pb, 0); /* size */
1637 avio_wl32(pb, track->tag); // store it byteswapped
1638 avio_wb32(pb, 0); /* Reserved */
1639 avio_wb16(pb, 0); /* Reserved */
1640 avio_wb16(pb, 1); /* Data-reference index */
1642 if (track->par->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
1643 mov_write_esds_tag(pb, track);
1644 else if (track->par->extradata_size)
1645 avio_write(pb, track->par->extradata, track->par->extradata_size);
1647 return update_size(pb, pos);
1650 static int mov_write_st3d_tag(AVIOContext *pb, AVStereo3D *stereo_3d)
1654 if (stereo_3d->flags != 0) {
1655 av_log(pb, AV_LOG_WARNING, "Unsupported stereo_3d flags %x. st3d not written.\n", stereo_3d->flags);
1659 switch (stereo_3d->type) {
1660 case AV_STEREO3D_2D:
1663 case AV_STEREO3D_TOPBOTTOM:
1666 case AV_STEREO3D_SIDEBYSIDE:
1670 av_log(pb, AV_LOG_WARNING, "Unsupported stereo_3d type %s. st3d not written.\n", av_stereo3d_type_name(stereo_3d->type));
1673 avio_wb32(pb, 13); /* size */
1674 ffio_wfourcc(pb, "st3d");
1675 avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1676 avio_w8(pb, stereo_mode);
1680 static int mov_write_sv3d_tag(AVFormatContext *s, AVIOContext *pb, AVSphericalMapping *spherical_mapping)
1682 int64_t sv3d_pos, svhd_pos, proj_pos;
1683 const char* metadata_source = s->flags & AVFMT_FLAG_BITEXACT ? "Lavf" : LIBAVFORMAT_IDENT;
1685 if (spherical_mapping->projection != AV_SPHERICAL_EQUIRECTANGULAR &&
1686 spherical_mapping->projection != AV_SPHERICAL_EQUIRECTANGULAR_TILE &&
1687 spherical_mapping->projection != AV_SPHERICAL_CUBEMAP) {
1688 av_log(pb, AV_LOG_WARNING, "Unsupported projection %d. sv3d not written.\n", spherical_mapping->projection);
1692 sv3d_pos = avio_tell(pb);
1693 avio_wb32(pb, 0); /* size */
1694 ffio_wfourcc(pb, "sv3d");
1696 svhd_pos = avio_tell(pb);
1697 avio_wb32(pb, 0); /* size */
1698 ffio_wfourcc(pb, "svhd");
1699 avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1700 avio_put_str(pb, metadata_source);
1701 update_size(pb, svhd_pos);
1703 proj_pos = avio_tell(pb);
1704 avio_wb32(pb, 0); /* size */
1705 ffio_wfourcc(pb, "proj");
1707 avio_wb32(pb, 24); /* size */
1708 ffio_wfourcc(pb, "prhd");
1709 avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1710 avio_wb32(pb, spherical_mapping->yaw);
1711 avio_wb32(pb, spherical_mapping->pitch);
1712 avio_wb32(pb, spherical_mapping->roll);
1714 switch (spherical_mapping->projection) {
1715 case AV_SPHERICAL_EQUIRECTANGULAR:
1716 case AV_SPHERICAL_EQUIRECTANGULAR_TILE:
1717 avio_wb32(pb, 28); /* size */
1718 ffio_wfourcc(pb, "equi");
1719 avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1720 avio_wb32(pb, spherical_mapping->bound_top);
1721 avio_wb32(pb, spherical_mapping->bound_bottom);
1722 avio_wb32(pb, spherical_mapping->bound_left);
1723 avio_wb32(pb, spherical_mapping->bound_right);
1725 case AV_SPHERICAL_CUBEMAP:
1726 avio_wb32(pb, 20); /* size */
1727 ffio_wfourcc(pb, "cbmp");
1728 avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1729 avio_wb32(pb, 0); /* layout */
1730 avio_wb32(pb, spherical_mapping->padding); /* padding */
1733 update_size(pb, proj_pos);
1735 return update_size(pb, sv3d_pos);
1738 static int mov_write_pasp_tag(AVIOContext *pb, MOVTrack *track)
1741 av_reduce(&sar.num, &sar.den, track->par->sample_aspect_ratio.num,
1742 track->par->sample_aspect_ratio.den, INT_MAX);
1745 ffio_wfourcc(pb, "pasp");
1746 avio_wb32(pb, sar.num);
1747 avio_wb32(pb, sar.den);
1751 static int mov_write_gama_tag(AVIOContext *pb, MOVTrack *track, double gamma)
1756 gamma = avpriv_get_gamma_from_trc(track->par->color_trc);
1758 av_log(pb, AV_LOG_DEBUG, "gamma value %g\n", gamma);
1761 gama = (uint32_t)lrint((double)(1<<16) * gamma);
1762 av_log(pb, AV_LOG_DEBUG, "writing gama value %"PRId32"\n", gama);
1764 av_assert0(track->mode == MODE_MOV);
1766 ffio_wfourcc(pb, "gama");
1767 avio_wb32(pb, gama);
1771 av_log(pb, AV_LOG_WARNING, "gamma value unknown, unable to write gama atom\n");
1776 static int mov_write_colr_tag(AVIOContext *pb, MOVTrack *track)
1778 // Ref (MOV): https://developer.apple.com/library/mac/technotes/tn2162/_index.html#//apple_ref/doc/uid/DTS40013070-CH1-TNTAG9
1779 // Ref (MP4): ISO/IEC 14496-12:2012
1781 if (track->par->color_primaries == AVCOL_PRI_UNSPECIFIED &&
1782 track->par->color_trc == AVCOL_TRC_UNSPECIFIED &&
1783 track->par->color_space == AVCOL_SPC_UNSPECIFIED) {
1784 if ((track->par->width >= 1920 && track->par->height >= 1080)
1785 || (track->par->width == 1280 && track->par->height == 720)) {
1786 av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming bt709\n");
1787 track->par->color_primaries = AVCOL_PRI_BT709;
1788 } else if (track->par->width == 720 && track->height == 576) {
1789 av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming bt470bg\n");
1790 track->par->color_primaries = AVCOL_PRI_BT470BG;
1791 } else if (track->par->width == 720 &&
1792 (track->height == 486 || track->height == 480)) {
1793 av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming smpte170\n");
1794 track->par->color_primaries = AVCOL_PRI_SMPTE170M;
1796 av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, unable to assume anything\n");
1798 switch (track->par->color_primaries) {
1799 case AVCOL_PRI_BT709:
1800 track->par->color_trc = AVCOL_TRC_BT709;
1801 track->par->color_space = AVCOL_SPC_BT709;
1803 case AVCOL_PRI_SMPTE170M:
1804 case AVCOL_PRI_BT470BG:
1805 track->par->color_trc = AVCOL_TRC_BT709;
1806 track->par->color_space = AVCOL_SPC_SMPTE170M;
1811 /* We should only ever be called by MOV or MP4. */
1812 av_assert0(track->mode == MODE_MOV || track->mode == MODE_MP4);
1814 avio_wb32(pb, 18 + (track->mode == MODE_MP4));
1815 ffio_wfourcc(pb, "colr");
1816 if (track->mode == MODE_MP4)
1817 ffio_wfourcc(pb, "nclx");
1819 ffio_wfourcc(pb, "nclc");
1820 switch (track->par->color_primaries) {
1821 case AVCOL_PRI_BT709: avio_wb16(pb, 1); break;
1822 case AVCOL_PRI_SMPTE170M:
1823 case AVCOL_PRI_SMPTE240M: avio_wb16(pb, 6); break;
1824 case AVCOL_PRI_BT470BG: avio_wb16(pb, 5); break;
1825 default: avio_wb16(pb, 2);
1827 switch (track->par->color_trc) {
1828 case AVCOL_TRC_BT709: avio_wb16(pb, 1); break;
1829 case AVCOL_TRC_SMPTE170M: avio_wb16(pb, 1); break; // remapped
1830 case AVCOL_TRC_SMPTE240M: avio_wb16(pb, 7); break;
1831 default: avio_wb16(pb, 2);
1833 switch (track->par->color_space) {
1834 case AVCOL_SPC_BT709: avio_wb16(pb, 1); break;
1835 case AVCOL_SPC_BT470BG:
1836 case AVCOL_SPC_SMPTE170M: avio_wb16(pb, 6); break;
1837 case AVCOL_SPC_SMPTE240M: avio_wb16(pb, 7); break;
1838 default: avio_wb16(pb, 2);
1841 if (track->mode == MODE_MP4) {
1842 int full_range = track->par->color_range == AVCOL_RANGE_JPEG;
1843 avio_w8(pb, full_range << 7);
1850 static void find_compressor(char * compressor_name, int len, MOVTrack *track)
1852 AVDictionaryEntry *encoder;
1853 int xdcam_res = (track->par->width == 1280 && track->par->height == 720)
1854 || (track->par->width == 1440 && track->par->height == 1080)
1855 || (track->par->width == 1920 && track->par->height == 1080);
1857 if (track->mode == MODE_MOV &&
1858 (encoder = av_dict_get(track->st->metadata, "encoder", NULL, 0))) {
1859 av_strlcpy(compressor_name, encoder->value, 32);
1860 } else if (track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO && xdcam_res) {
1861 int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE;
1862 AVStream *st = track->st;
1863 int rate = defined_frame_rate(NULL, st);
1864 av_strlcatf(compressor_name, len, "XDCAM");
1865 if (track->par->format == AV_PIX_FMT_YUV422P) {
1866 av_strlcatf(compressor_name, len, " HD422");
1867 } else if(track->par->width == 1440) {
1868 av_strlcatf(compressor_name, len, " HD");
1870 av_strlcatf(compressor_name, len, " EX");
1872 av_strlcatf(compressor_name, len, " %d%c", track->par->height, interlaced ? 'i' : 'p');
1874 av_strlcatf(compressor_name, len, "%d", rate * (interlaced + 1));
1878 static int mov_write_video_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
1880 int64_t pos = avio_tell(pb);
1881 char compressor_name[32] = { 0 };
1884 avio_wb32(pb, 0); /* size */
1885 if (mov->encryption_scheme != MOV_ENC_NONE) {
1886 ffio_wfourcc(pb, "encv");
1888 avio_wl32(pb, track->tag); // store it byteswapped
1890 avio_wb32(pb, 0); /* Reserved */
1891 avio_wb16(pb, 0); /* Reserved */
1892 avio_wb16(pb, 1); /* Data-reference index */
1894 avio_wb16(pb, 0); /* Codec stream version */
1895 avio_wb16(pb, 0); /* Codec stream revision (=0) */
1896 if (track->mode == MODE_MOV) {
1897 ffio_wfourcc(pb, "FFMP"); /* Vendor */
1898 if (track->par->codec_id == AV_CODEC_ID_RAWVIDEO) {
1899 avio_wb32(pb, 0); /* Temporal Quality */
1900 avio_wb32(pb, 0x400); /* Spatial Quality = lossless*/
1902 avio_wb32(pb, 0x200); /* Temporal Quality = normal */
1903 avio_wb32(pb, 0x200); /* Spatial Quality = normal */
1906 avio_wb32(pb, 0); /* Reserved */
1907 avio_wb32(pb, 0); /* Reserved */
1908 avio_wb32(pb, 0); /* Reserved */
1910 avio_wb16(pb, track->par->width); /* Video width */
1911 avio_wb16(pb, track->height); /* Video height */
1912 avio_wb32(pb, 0x00480000); /* Horizontal resolution 72dpi */
1913 avio_wb32(pb, 0x00480000); /* Vertical resolution 72dpi */
1914 avio_wb32(pb, 0); /* Data size (= 0) */
1915 avio_wb16(pb, 1); /* Frame count (= 1) */
1917 /* FIXME not sure, ISO 14496-1 draft where it shall be set to 0 */
1918 find_compressor(compressor_name, 32, track);
1919 avio_w8(pb, strlen(compressor_name));
1920 avio_write(pb, compressor_name, 31);
1922 if (track->mode == MODE_MOV && track->par->bits_per_coded_sample)
1923 avio_wb16(pb, track->par->bits_per_coded_sample |
1924 (track->par->format == AV_PIX_FMT_GRAY8 ? 0x20 : 0));
1926 avio_wb16(pb, 0x18); /* Reserved */
1928 if (track->mode == MODE_MOV && track->par->format == AV_PIX_FMT_PAL8) {
1929 int pal_size = 1 << track->par->bits_per_coded_sample;
1931 avio_wb16(pb, 0); /* Color table ID */
1932 avio_wb32(pb, 0); /* Color table seed */
1933 avio_wb16(pb, 0x8000); /* Color table flags */
1934 avio_wb16(pb, pal_size - 1); /* Color table size (zero-relative) */
1935 for (i = 0; i < pal_size; i++) {
1936 uint32_t rgb = track->palette[i];
1937 uint16_t r = (rgb >> 16) & 0xff;
1938 uint16_t g = (rgb >> 8) & 0xff;
1939 uint16_t b = rgb & 0xff;
1941 avio_wb16(pb, (r << 8) | r);
1942 avio_wb16(pb, (g << 8) | g);
1943 avio_wb16(pb, (b << 8) | b);
1946 avio_wb16(pb, 0xffff); /* Reserved */
1948 if (track->tag == MKTAG('m','p','4','v'))
1949 mov_write_esds_tag(pb, track);
1950 else if (track->par->codec_id == AV_CODEC_ID_H263)
1951 mov_write_d263_tag(pb);
1952 else if (track->par->codec_id == AV_CODEC_ID_AVUI ||
1953 track->par->codec_id == AV_CODEC_ID_SVQ3) {
1954 mov_write_extradata_tag(pb, track);
1956 } else if (track->par->codec_id == AV_CODEC_ID_DNXHD) {
1957 mov_write_avid_tag(pb, track);
1959 } else if (track->par->codec_id == AV_CODEC_ID_HEVC)
1960 mov_write_hvcc_tag(pb, track);
1961 else if (track->par->codec_id == AV_CODEC_ID_H264 && !TAG_IS_AVCI(track->tag)) {
1962 mov_write_avcc_tag(pb, track);
1963 if (track->mode == MODE_IPOD)
1964 mov_write_uuid_tag_ipod(pb);
1965 } else if (track->par->codec_id == AV_CODEC_ID_VP9) {
1966 mov_write_vpcc_tag(mov->fc, pb, track);
1967 } else if (track->par->codec_id == AV_CODEC_ID_VC1 && track->vos_len > 0)
1968 mov_write_dvc1_tag(pb, track);
1969 else if (track->par->codec_id == AV_CODEC_ID_VP6F ||
1970 track->par->codec_id == AV_CODEC_ID_VP6A) {
1971 /* Don't write any potential extradata here - the cropping
1972 * is signalled via the normal width/height fields. */
1973 } else if (track->par->codec_id == AV_CODEC_ID_R10K) {
1974 if (track->par->codec_tag == MKTAG('R','1','0','k'))
1975 mov_write_dpxe_tag(pb, track);
1976 } else if (track->vos_len > 0)
1977 mov_write_glbl_tag(pb, track);
1979 if (track->par->codec_id != AV_CODEC_ID_H264 &&
1980 track->par->codec_id != AV_CODEC_ID_MPEG4 &&
1981 track->par->codec_id != AV_CODEC_ID_DNXHD) {
1982 int field_order = track->par->field_order;
1984 #if FF_API_LAVF_AVCTX
1985 FF_DISABLE_DEPRECATION_WARNINGS
1986 if (field_order != track->st->codec->field_order && track->st->codec->field_order != AV_FIELD_UNKNOWN)
1987 field_order = track->st->codec->field_order;
1988 FF_ENABLE_DEPRECATION_WARNINGS
1991 if (field_order != AV_FIELD_UNKNOWN)
1992 mov_write_fiel_tag(pb, track, field_order);
1995 if (mov->flags & FF_MOV_FLAG_WRITE_GAMA) {
1996 if (track->mode == MODE_MOV)
1997 mov_write_gama_tag(pb, track, mov->gamma);
1999 av_log(mov->fc, AV_LOG_WARNING, "Not writing 'gama' atom. Format is not MOV.\n");
2001 if (mov->flags & FF_MOV_FLAG_WRITE_COLR) {
2002 if (track->mode == MODE_MOV || track->mode == MODE_MP4)
2003 mov_write_colr_tag(pb, track);
2005 av_log(mov->fc, AV_LOG_WARNING, "Not writing 'colr' atom. Format is not MOV or MP4.\n");
2008 if (track->mode == MODE_MP4 && mov->fc->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL) {
2009 AVStereo3D* stereo_3d = (AVStereo3D*) av_stream_get_side_data(track->st, AV_PKT_DATA_STEREO3D, NULL);
2010 AVSphericalMapping* spherical_mapping = (AVSphericalMapping*)av_stream_get_side_data(track->st, AV_PKT_DATA_SPHERICAL, NULL);
2013 mov_write_st3d_tag(pb, stereo_3d);
2014 if (spherical_mapping)
2015 mov_write_sv3d_tag(mov->fc, pb, spherical_mapping);
2018 if (track->par->sample_aspect_ratio.den && track->par->sample_aspect_ratio.num) {
2019 mov_write_pasp_tag(pb, track);
2022 if (mov->encryption_scheme != MOV_ENC_NONE) {
2023 ff_mov_cenc_write_sinf_tag(track, pb, mov->encryption_kid);
2026 /* extra padding for avid stsd */
2027 /* https://developer.apple.com/library/mac/documentation/QuickTime/QTFF/QTFFChap2/qtff2.html#//apple_ref/doc/uid/TP40000939-CH204-61112 */
2031 return update_size(pb, pos);
2034 static int mov_write_rtp_tag(AVIOContext *pb, MOVTrack *track)
2036 int64_t pos = avio_tell(pb);
2037 avio_wb32(pb, 0); /* size */
2038 ffio_wfourcc(pb, "rtp ");
2039 avio_wb32(pb, 0); /* Reserved */
2040 avio_wb16(pb, 0); /* Reserved */
2041 avio_wb16(pb, 1); /* Data-reference index */
2043 avio_wb16(pb, 1); /* Hint track version */
2044 avio_wb16(pb, 1); /* Highest compatible version */
2045 avio_wb32(pb, track->max_packet_size); /* Max packet size */
2047 avio_wb32(pb, 12); /* size */
2048 ffio_wfourcc(pb, "tims");
2049 avio_wb32(pb, track->timescale);
2051 return update_size(pb, pos);
2054 static int mov_write_source_reference_tag(AVIOContext *pb, MOVTrack *track, const char *reel_name)
2056 uint64_t str_size =strlen(reel_name);
2057 int64_t pos = avio_tell(pb);
2059 if (str_size >= UINT16_MAX){
2060 av_log(NULL, AV_LOG_ERROR, "reel_name length %"PRIu64" is too large\n", str_size);
2062 return AVERROR(EINVAL);
2065 avio_wb32(pb, 0); /* size */
2066 ffio_wfourcc(pb, "name"); /* Data format */
2067 avio_wb16(pb, str_size); /* string size */
2068 avio_wb16(pb, track->language); /* langcode */
2069 avio_write(pb, reel_name, str_size); /* reel name */
2070 return update_size(pb,pos);
2073 static int mov_write_tmcd_tag(AVIOContext *pb, MOVTrack *track)
2075 int64_t pos = avio_tell(pb);
2079 AVDictionaryEntry *t = NULL;
2081 if (!track->st->avg_frame_rate.num || !track->st->avg_frame_rate.den) {
2082 #if FF_API_LAVF_AVCTX
2083 FF_DISABLE_DEPRECATION_WARNINGS
2084 frame_duration = av_rescale(track->timescale, track->st->codec->time_base.num, track->st->codec->time_base.den);
2085 nb_frames = ROUNDED_DIV(track->st->codec->time_base.den, track->st->codec->time_base.num);
2086 FF_ENABLE_DEPRECATION_WARNINGS
2088 av_log(NULL, AV_LOG_ERROR, "avg_frame_rate not set for tmcd track.\n");
2089 return AVERROR(EINVAL);
2092 frame_duration = av_rescale(track->timescale, track->st->avg_frame_rate.num, track->st->avg_frame_rate.den);
2093 nb_frames = ROUNDED_DIV(track->st->avg_frame_rate.den, track->st->avg_frame_rate.num);
2096 if (nb_frames > 255) {
2097 av_log(NULL, AV_LOG_ERROR, "fps %d is too large\n", nb_frames);
2098 return AVERROR(EINVAL);
2101 avio_wb32(pb, 0); /* size */
2102 ffio_wfourcc(pb, "tmcd"); /* Data format */
2103 avio_wb32(pb, 0); /* Reserved */
2104 avio_wb32(pb, 1); /* Data reference index */
2105 avio_wb32(pb, 0); /* Flags */
2106 avio_wb32(pb, track->timecode_flags); /* Flags (timecode) */
2107 avio_wb32(pb, track->timescale); /* Timescale */
2108 avio_wb32(pb, frame_duration); /* Frame duration */
2109 avio_w8(pb, nb_frames); /* Number of frames */
2110 avio_w8(pb, 0); /* Reserved */
2112 t = av_dict_get(track->st->metadata, "reel_name", NULL, 0);
2113 if (t && utf8len(t->value) && track->mode != MODE_MP4)
2114 mov_write_source_reference_tag(pb, track, t->value);
2116 avio_wb16(pb, 0); /* zero size */
2119 avio_wb32(pb, 0); /* size */
2120 ffio_wfourcc(pb, "tmcd"); /* Data format */
2121 avio_wb32(pb, 0); /* Reserved */
2122 avio_wb32(pb, 1); /* Data reference index */
2123 if (track->par->extradata_size)
2124 avio_write(pb, track->par->extradata, track->par->extradata_size);
2126 return update_size(pb, pos);
2129 static int mov_write_stsd_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
2131 int64_t pos = avio_tell(pb);
2132 avio_wb32(pb, 0); /* size */
2133 ffio_wfourcc(pb, "stsd");
2134 avio_wb32(pb, 0); /* version & flags */
2135 avio_wb32(pb, 1); /* entry count */
2136 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO)
2137 mov_write_video_tag(pb, mov, track);
2138 else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
2139 mov_write_audio_tag(s, pb, mov, track);
2140 else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)
2141 mov_write_subtitle_tag(pb, track);
2142 else if (track->par->codec_tag == MKTAG('r','t','p',' '))
2143 mov_write_rtp_tag(pb, track);
2144 else if (track->par->codec_tag == MKTAG('t','m','c','d'))
2145 mov_write_tmcd_tag(pb, track);
2146 return update_size(pb, pos);
2149 static int mov_write_ctts_tag(AVIOContext *pb, MOVTrack *track)
2151 MOVStts *ctts_entries;
2152 uint32_t entries = 0;
2156 ctts_entries = av_malloc_array((track->entry + 1), sizeof(*ctts_entries)); /* worst case */
2158 return AVERROR(ENOMEM);
2159 ctts_entries[0].count = 1;
2160 ctts_entries[0].duration = track->cluster[0].cts;
2161 for (i = 1; i < track->entry; i++) {
2162 if (track->cluster[i].cts == ctts_entries[entries].duration) {
2163 ctts_entries[entries].count++; /* compress */
2166 ctts_entries[entries].duration = track->cluster[i].cts;
2167 ctts_entries[entries].count = 1;
2170 entries++; /* last one */
2171 atom_size = 16 + (entries * 8);
2172 avio_wb32(pb, atom_size); /* size */
2173 ffio_wfourcc(pb, "ctts");
2174 avio_wb32(pb, 0); /* version & flags */
2175 avio_wb32(pb, entries); /* entry count */
2176 for (i = 0; i < entries; i++) {
2177 avio_wb32(pb, ctts_entries[i].count);
2178 avio_wb32(pb, ctts_entries[i].duration);
2180 av_free(ctts_entries);
2184 /* Time to sample atom */
2185 static int mov_write_stts_tag(AVIOContext *pb, MOVTrack *track)
2187 MOVStts *stts_entries = NULL;
2188 uint32_t entries = -1;
2192 if (track->par->codec_type == AVMEDIA_TYPE_AUDIO && !track->audio_vbr) {
2193 stts_entries = av_malloc(sizeof(*stts_entries)); /* one entry */
2195 return AVERROR(ENOMEM);
2196 stts_entries[0].count = track->sample_count;
2197 stts_entries[0].duration = 1;
2201 stts_entries = av_malloc_array(track->entry, sizeof(*stts_entries)); /* worst case */
2203 return AVERROR(ENOMEM);
2205 for (i = 0; i < track->entry; i++) {
2206 int duration = get_cluster_duration(track, i);
2207 if (i && duration == stts_entries[entries].duration) {
2208 stts_entries[entries].count++; /* compress */
2211 stts_entries[entries].duration = duration;
2212 stts_entries[entries].count = 1;
2215 entries++; /* last one */
2217 atom_size = 16 + (entries * 8);
2218 avio_wb32(pb, atom_size); /* size */
2219 ffio_wfourcc(pb, "stts");
2220 avio_wb32(pb, 0); /* version & flags */
2221 avio_wb32(pb, entries); /* entry count */
2222 for (i = 0; i < entries; i++) {
2223 avio_wb32(pb, stts_entries[i].count);
2224 avio_wb32(pb, stts_entries[i].duration);
2226 av_free(stts_entries);
2230 static int mov_write_dref_tag(AVIOContext *pb)
2232 avio_wb32(pb, 28); /* size */
2233 ffio_wfourcc(pb, "dref");
2234 avio_wb32(pb, 0); /* version & flags */
2235 avio_wb32(pb, 1); /* entry count */
2237 avio_wb32(pb, 0xc); /* size */
2238 //FIXME add the alis and rsrc atom
2239 ffio_wfourcc(pb, "url ");
2240 avio_wb32(pb, 1); /* version & flags */
2245 static int mov_preroll_write_stbl_atoms(AVIOContext *pb, MOVTrack *track)
2249 int16_t roll_distance;
2250 int group_description_index;
2253 struct sgpd_entry *sgpd_entries = NULL;
2258 const int OPUS_SEEK_PREROLL_MS = 80;
2259 int roll_samples = av_rescale_q(OPUS_SEEK_PREROLL_MS,
2260 (AVRational){1, 1000},
2261 (AVRational){1, 48000});
2264 sgpd_entries = av_malloc_array(track->entry, sizeof(*sgpd_entries));
2266 return AVERROR(ENOMEM);
2269 av_assert0(track->par->codec_id == AV_CODEC_ID_OPUS);
2271 for (i = 0; i < track->entry; i++) {
2272 int roll_samples_remaining = roll_samples;
2274 for (j = i - 1; j >= 0; j--) {
2275 roll_samples_remaining -= get_cluster_duration(track, j);
2277 if (roll_samples_remaining <= 0)
2280 /* We don't have enough preceeding samples to compute a valid
2281 roll_distance here, so this sample can't be independently
2283 if (roll_samples_remaining > 0)
2285 /* Verify distance is a minimum of 2 (60ms) packets and a maximum of
2286 32 (2.5ms) packets. */
2287 av_assert0(distance == 0 || (distance >= 2 && distance <= 32));
2288 if (i && distance == sgpd_entries[entries].roll_distance) {
2289 sgpd_entries[entries].count++;
2292 sgpd_entries[entries].count = 1;
2293 sgpd_entries[entries].roll_distance = distance;
2294 sgpd_entries[entries].group_description_index = distance ? ++group : 0;
2300 av_free(sgpd_entries);
2304 /* Write sgpd tag */
2305 avio_wb32(pb, 24 + (group * 2)); /* size */
2306 ffio_wfourcc(pb, "sgpd");
2307 avio_wb32(pb, 1 << 24); /* fullbox */
2308 ffio_wfourcc(pb, "roll");
2309 avio_wb32(pb, 2); /* default_length */
2310 avio_wb32(pb, group); /* entry_count */
2311 for (i = 0; i < entries; i++) {
2312 if (sgpd_entries[i].group_description_index) {
2313 avio_wb16(pb, -sgpd_entries[i].roll_distance); /* roll_distance */
2317 /* Write sbgp tag */
2318 avio_wb32(pb, 20 + (entries * 8)); /* size */
2319 ffio_wfourcc(pb, "sbgp");
2320 avio_wb32(pb, 0); /* fullbox */
2321 ffio_wfourcc(pb, "roll");
2322 avio_wb32(pb, entries); /* entry_count */
2323 for (i = 0; i < entries; i++) {
2324 avio_wb32(pb, sgpd_entries[i].count); /* sample_count */
2325 avio_wb32(pb, sgpd_entries[i].group_description_index); /* group_description_index */
2328 av_free(sgpd_entries);
2332 static int mov_write_stbl_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
2334 int64_t pos = avio_tell(pb);
2337 avio_wb32(pb, 0); /* size */
2338 ffio_wfourcc(pb, "stbl");
2339 mov_write_stsd_tag(s, pb, mov, track);
2340 mov_write_stts_tag(pb, track);
2341 if ((track->par->codec_type == AVMEDIA_TYPE_VIDEO ||
2342 track->par->codec_tag == MKTAG('r','t','p',' ')) &&
2343 track->has_keyframes && track->has_keyframes < track->entry)
2344 mov_write_stss_tag(pb, track, MOV_SYNC_SAMPLE);
2345 if (track->mode == MODE_MOV && track->flags & MOV_TRACK_STPS)
2346 mov_write_stss_tag(pb, track, MOV_PARTIAL_SYNC_SAMPLE);
2347 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO &&
2348 track->flags & MOV_TRACK_CTTS && track->entry) {
2350 if ((ret = mov_write_ctts_tag(pb, track)) < 0)
2353 mov_write_stsc_tag(pb, track);
2354 mov_write_stsz_tag(pb, track);
2355 mov_write_stco_tag(pb, track);
2356 if (mov->encryption_scheme == MOV_ENC_CENC_AES_CTR) {
2357 ff_mov_cenc_write_stbl_atoms(&track->cenc, pb);
2359 if (track->par->codec_id == AV_CODEC_ID_OPUS) {
2360 mov_preroll_write_stbl_atoms(pb, track);
2362 return update_size(pb, pos);
2365 static int mov_write_dinf_tag(AVIOContext *pb)
2367 int64_t pos = avio_tell(pb);
2368 avio_wb32(pb, 0); /* size */
2369 ffio_wfourcc(pb, "dinf");
2370 mov_write_dref_tag(pb);
2371 return update_size(pb, pos);
2374 static int mov_write_nmhd_tag(AVIOContext *pb)
2377 ffio_wfourcc(pb, "nmhd");
2382 static int mov_write_tcmi_tag(AVIOContext *pb, MOVTrack *track)
2384 int64_t pos = avio_tell(pb);
2385 const char *font = "Lucida Grande";
2386 avio_wb32(pb, 0); /* size */
2387 ffio_wfourcc(pb, "tcmi"); /* timecode media information atom */
2388 avio_wb32(pb, 0); /* version & flags */
2389 avio_wb16(pb, 0); /* text font */
2390 avio_wb16(pb, 0); /* text face */
2391 avio_wb16(pb, 12); /* text size */
2392 avio_wb16(pb, 0); /* (unknown, not in the QT specs...) */
2393 avio_wb16(pb, 0x0000); /* text color (red) */
2394 avio_wb16(pb, 0x0000); /* text color (green) */
2395 avio_wb16(pb, 0x0000); /* text color (blue) */
2396 avio_wb16(pb, 0xffff); /* background color (red) */
2397 avio_wb16(pb, 0xffff); /* background color (green) */
2398 avio_wb16(pb, 0xffff); /* background color (blue) */
2399 avio_w8(pb, strlen(font)); /* font len (part of the pascal string) */
2400 avio_write(pb, font, strlen(font)); /* font name */
2401 return update_size(pb, pos);
2404 static int mov_write_gmhd_tag(AVIOContext *pb, MOVTrack *track)
2406 int64_t pos = avio_tell(pb);
2407 avio_wb32(pb, 0); /* size */
2408 ffio_wfourcc(pb, "gmhd");
2409 avio_wb32(pb, 0x18); /* gmin size */
2410 ffio_wfourcc(pb, "gmin");/* generic media info */
2411 avio_wb32(pb, 0); /* version & flags */
2412 avio_wb16(pb, 0x40); /* graphics mode = */
2413 avio_wb16(pb, 0x8000); /* opColor (r?) */
2414 avio_wb16(pb, 0x8000); /* opColor (g?) */
2415 avio_wb16(pb, 0x8000); /* opColor (b?) */
2416 avio_wb16(pb, 0); /* balance */
2417 avio_wb16(pb, 0); /* reserved */
2420 * This special text atom is required for
2421 * Apple Quicktime chapters. The contents
2422 * don't appear to be documented, so the
2423 * bytes are copied verbatim.
2425 if (track->tag != MKTAG('c','6','0','8')) {
2426 avio_wb32(pb, 0x2C); /* size */
2427 ffio_wfourcc(pb, "text");
2428 avio_wb16(pb, 0x01);
2429 avio_wb32(pb, 0x00);
2430 avio_wb32(pb, 0x00);
2431 avio_wb32(pb, 0x00);
2432 avio_wb32(pb, 0x01);
2433 avio_wb32(pb, 0x00);
2434 avio_wb32(pb, 0x00);
2435 avio_wb32(pb, 0x00);
2436 avio_wb32(pb, 0x00004000);
2437 avio_wb16(pb, 0x0000);
2440 if (track->par->codec_tag == MKTAG('t','m','c','d')) {
2441 int64_t tmcd_pos = avio_tell(pb);
2442 avio_wb32(pb, 0); /* size */
2443 ffio_wfourcc(pb, "tmcd");
2444 mov_write_tcmi_tag(pb, track);
2445 update_size(pb, tmcd_pos);
2447 return update_size(pb, pos);
2450 static int mov_write_smhd_tag(AVIOContext *pb)
2452 avio_wb32(pb, 16); /* size */
2453 ffio_wfourcc(pb, "smhd");
2454 avio_wb32(pb, 0); /* version & flags */
2455 avio_wb16(pb, 0); /* reserved (balance, normally = 0) */
2456 avio_wb16(pb, 0); /* reserved */
2460 static int mov_write_vmhd_tag(AVIOContext *pb)
2462 avio_wb32(pb, 0x14); /* size (always 0x14) */
2463 ffio_wfourcc(pb, "vmhd");
2464 avio_wb32(pb, 0x01); /* version & flags */
2465 avio_wb64(pb, 0); /* reserved (graphics mode = copy) */
2469 static int is_clcp_track(MOVTrack *track)
2471 return track->tag == MKTAG('c','7','0','8') ||
2472 track->tag == MKTAG('c','6','0','8');
2475 static int mov_write_hdlr_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
2477 const char *hdlr, *descr = NULL, *hdlr_type = NULL;
2478 int64_t pos = avio_tell(pb);
2482 descr = "DataHandler";
2485 hdlr = (track->mode == MODE_MOV) ? "mhlr" : "\0\0\0\0";
2486 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
2488 descr = "VideoHandler";
2489 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
2491 descr = "SoundHandler";
2492 } else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE) {
2493 if (is_clcp_track(track)) {
2495 descr = "ClosedCaptionHandler";
2497 if (track->tag == MKTAG('t','x','3','g')) {
2499 } else if (track->tag == MKTAG('m','p','4','s')) {
2504 descr = "SubtitleHandler";
2506 } else if (track->par->codec_tag == MKTAG('r','t','p',' ')) {
2508 descr = "HintHandler";
2509 } else if (track->par->codec_tag == MKTAG('t','m','c','d')) {
2511 descr = "TimeCodeHandler";
2513 av_log(s, AV_LOG_WARNING,
2514 "Unknown hldr_type for %s, writing dummy values\n",
2515 av_fourcc2str(track->par->codec_tag));
2518 // hdlr.name is used by some players to identify the content title
2519 // of the track. So if an alternate handler description is
2520 // specified, use it.
2521 AVDictionaryEntry *t;
2522 t = av_dict_get(track->st->metadata, "handler", NULL, 0);
2523 if (t && utf8len(t->value))
2528 avio_wb32(pb, 0); /* size */
2529 ffio_wfourcc(pb, "hdlr");
2530 avio_wb32(pb, 0); /* Version & flags */
2531 avio_write(pb, hdlr, 4); /* handler */
2532 ffio_wfourcc(pb, hdlr_type); /* handler type */
2533 avio_wb32(pb, 0); /* reserved */
2534 avio_wb32(pb, 0); /* reserved */
2535 avio_wb32(pb, 0); /* reserved */
2536 if (!track || track->mode == MODE_MOV)
2537 avio_w8(pb, strlen(descr)); /* pascal string */
2538 avio_write(pb, descr, strlen(descr)); /* handler description */
2539 if (track && track->mode != MODE_MOV)
2540 avio_w8(pb, 0); /* c string */
2541 return update_size(pb, pos);
2544 static int mov_write_hmhd_tag(AVIOContext *pb)
2546 /* This atom must be present, but leaving the values at zero
2547 * seems harmless. */
2548 avio_wb32(pb, 28); /* size */
2549 ffio_wfourcc(pb, "hmhd");
2550 avio_wb32(pb, 0); /* version, flags */
2551 avio_wb16(pb, 0); /* maxPDUsize */
2552 avio_wb16(pb, 0); /* avgPDUsize */
2553 avio_wb32(pb, 0); /* maxbitrate */
2554 avio_wb32(pb, 0); /* avgbitrate */
2555 avio_wb32(pb, 0); /* reserved */
2559 static int mov_write_minf_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
2561 int64_t pos = avio_tell(pb);
2564 avio_wb32(pb, 0); /* size */
2565 ffio_wfourcc(pb, "minf");
2566 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO)
2567 mov_write_vmhd_tag(pb);
2568 else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
2569 mov_write_smhd_tag(pb);
2570 else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE) {
2571 if (track->tag == MKTAG('t','e','x','t') || is_clcp_track(track)) {
2572 mov_write_gmhd_tag(pb, track);
2574 mov_write_nmhd_tag(pb);
2576 } else if (track->tag == MKTAG('r','t','p',' ')) {
2577 mov_write_hmhd_tag(pb);
2578 } else if (track->tag == MKTAG('t','m','c','d')) {
2579 if (track->mode != MODE_MOV)
2580 mov_write_nmhd_tag(pb);
2582 mov_write_gmhd_tag(pb, track);
2584 if (track->mode == MODE_MOV) /* FIXME: Why do it for MODE_MOV only ? */
2585 mov_write_hdlr_tag(s, pb, NULL);
2586 mov_write_dinf_tag(pb);
2587 if ((ret = mov_write_stbl_tag(s, pb, mov, track)) < 0)
2589 return update_size(pb, pos);
2592 static int mov_write_mdhd_tag(AVIOContext *pb, MOVMuxContext *mov,
2595 int version = track->track_duration < INT32_MAX ? 0 : 1;
2597 if (track->mode == MODE_ISM)
2600 (version == 1) ? avio_wb32(pb, 44) : avio_wb32(pb, 32); /* size */
2601 ffio_wfourcc(pb, "mdhd");
2602 avio_w8(pb, version);
2603 avio_wb24(pb, 0); /* flags */
2605 avio_wb64(pb, track->time);
2606 avio_wb64(pb, track->time);
2608 avio_wb32(pb, track->time); /* creation time */
2609 avio_wb32(pb, track->time); /* modification time */
2611 avio_wb32(pb, track->timescale); /* time scale (sample rate for audio) */
2612 if (!track->entry && mov->mode == MODE_ISM)
2613 (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
2614 else if (!track->entry)
2615 (version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0);
2617 (version == 1) ? avio_wb64(pb, track->track_duration) : avio_wb32(pb, track->track_duration); /* duration */
2618 avio_wb16(pb, track->language); /* language */
2619 avio_wb16(pb, 0); /* reserved (quality) */
2621 if (version != 0 && track->mode == MODE_MOV) {
2622 av_log(NULL, AV_LOG_ERROR,
2623 "FATAL error, file duration too long for timebase, this file will not be\n"
2624 "playable with quicktime. Choose a different timebase or a different\n"
2625 "container format\n");
2631 static int mov_write_mdia_tag(AVFormatContext *s, AVIOContext *pb,
2632 MOVMuxContext *mov, MOVTrack *track)
2634 int64_t pos = avio_tell(pb);
2637 avio_wb32(pb, 0); /* size */
2638 ffio_wfourcc(pb, "mdia");
2639 mov_write_mdhd_tag(pb, mov, track);
2640 mov_write_hdlr_tag(s, pb, track);
2641 if ((ret = mov_write_minf_tag(s, pb, mov, track)) < 0)
2643 return update_size(pb, pos);
2646 /* transformation matrix
2650 static void write_matrix(AVIOContext *pb, int16_t a, int16_t b, int16_t c,
2651 int16_t d, int16_t tx, int16_t ty)
2653 avio_wb32(pb, a << 16); /* 16.16 format */
2654 avio_wb32(pb, b << 16); /* 16.16 format */
2655 avio_wb32(pb, 0); /* u in 2.30 format */
2656 avio_wb32(pb, c << 16); /* 16.16 format */
2657 avio_wb32(pb, d << 16); /* 16.16 format */
2658 avio_wb32(pb, 0); /* v in 2.30 format */
2659 avio_wb32(pb, tx << 16); /* 16.16 format */
2660 avio_wb32(pb, ty << 16); /* 16.16 format */
2661 avio_wb32(pb, 1 << 30); /* w in 2.30 format */
2664 static int mov_write_tkhd_tag(AVIOContext *pb, MOVMuxContext *mov,
2665 MOVTrack *track, AVStream *st)
2667 int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE,
2668 track->timescale, AV_ROUND_UP);
2669 int version = duration < INT32_MAX ? 0 : 1;
2670 int flags = MOV_TKHD_FLAG_IN_MOVIE;
2674 uint32_t *display_matrix = NULL;
2675 int display_matrix_size, i;
2678 if (mov->per_stream_grouping)
2681 group = st->codecpar->codec_type;
2683 display_matrix = (uint32_t*)av_stream_get_side_data(st, AV_PKT_DATA_DISPLAYMATRIX,
2684 &display_matrix_size);
2685 if (display_matrix && display_matrix_size < 9 * sizeof(*display_matrix))
2686 display_matrix = NULL;
2689 if (track->flags & MOV_TRACK_ENABLED)
2690 flags |= MOV_TKHD_FLAG_ENABLED;
2692 if (track->mode == MODE_ISM)
2695 (version == 1) ? avio_wb32(pb, 104) : avio_wb32(pb, 92); /* size */
2696 ffio_wfourcc(pb, "tkhd");
2697 avio_w8(pb, version);
2698 avio_wb24(pb, flags);
2700 avio_wb64(pb, track->time);
2701 avio_wb64(pb, track->time);
2703 avio_wb32(pb, track->time); /* creation time */
2704 avio_wb32(pb, track->time); /* modification time */
2706 avio_wb32(pb, track->track_id); /* track-id */
2707 avio_wb32(pb, 0); /* reserved */
2708 if (!track->entry && mov->mode == MODE_ISM)
2709 (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
2710 else if (!track->entry)
2711 (version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0);
2713 (version == 1) ? avio_wb64(pb, duration) : avio_wb32(pb, duration);
2715 avio_wb32(pb, 0); /* reserved */
2716 avio_wb32(pb, 0); /* reserved */
2717 avio_wb16(pb, 0); /* layer */
2718 avio_wb16(pb, group); /* alternate group) */
2719 /* Volume, only for audio */
2720 if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
2721 avio_wb16(pb, 0x0100);
2724 avio_wb16(pb, 0); /* reserved */
2726 /* Matrix structure */
2727 #if FF_API_OLD_ROTATE_API
2728 if (st && st->metadata) {
2729 AVDictionaryEntry *rot = av_dict_get(st->metadata, "rotate", NULL, 0);
2730 rotation = (rot && rot->value) ? atoi(rot->value) : 0;
2733 if (display_matrix) {
2734 for (i = 0; i < 9; i++)
2735 avio_wb32(pb, display_matrix[i]);
2736 #if FF_API_OLD_ROTATE_API
2737 } else if (rotation == 90) {
2738 write_matrix(pb, 0, 1, -1, 0, track->par->height, 0);
2739 } else if (rotation == 180) {
2740 write_matrix(pb, -1, 0, 0, -1, track->par->width, track->par->height);
2741 } else if (rotation == 270) {
2742 write_matrix(pb, 0, -1, 1, 0, 0, track->par->width);
2745 write_matrix(pb, 1, 0, 0, 1, 0, 0);
2747 /* Track width and height, for visual only */
2748 if (st && (track->par->codec_type == AVMEDIA_TYPE_VIDEO ||
2749 track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)) {
2750 int64_t track_width_1616;
2751 if (track->mode == MODE_MOV) {
2752 track_width_1616 = track->par->width * 0x10000ULL;
2754 track_width_1616 = av_rescale(st->sample_aspect_ratio.num,
2755 track->par->width * 0x10000LL,
2756 st->sample_aspect_ratio.den);
2757 if (!track_width_1616 ||
2758 track->height != track->par->height ||
2759 track_width_1616 > UINT32_MAX)
2760 track_width_1616 = track->par->width * 0x10000ULL;
2762 if (track_width_1616 > UINT32_MAX) {
2763 av_log(mov->fc, AV_LOG_WARNING, "track width is too large\n");
2764 track_width_1616 = 0;
2766 avio_wb32(pb, track_width_1616);
2767 if (track->height > 0xFFFF) {
2768 av_log(mov->fc, AV_LOG_WARNING, "track height is too large\n");
2771 avio_wb32(pb, track->height * 0x10000U);
2779 static int mov_write_tapt_tag(AVIOContext *pb, MOVTrack *track)
2781 int32_t width = av_rescale(track->par->sample_aspect_ratio.num, track->par->width,
2782 track->par->sample_aspect_ratio.den);
2784 int64_t pos = avio_tell(pb);
2786 avio_wb32(pb, 0); /* size */
2787 ffio_wfourcc(pb, "tapt");
2790 ffio_wfourcc(pb, "clef");
2792 avio_wb32(pb, width << 16);
2793 avio_wb32(pb, track->par->height << 16);
2796 ffio_wfourcc(pb, "prof");
2798 avio_wb32(pb, width << 16);
2799 avio_wb32(pb, track->par->height << 16);
2802 ffio_wfourcc(pb, "enof");
2804 avio_wb32(pb, track->par->width << 16);
2805 avio_wb32(pb, track->par->height << 16);
2807 return update_size(pb, pos);
2810 // This box seems important for the psp playback ... without it the movie seems to hang
2811 static int mov_write_edts_tag(AVIOContext *pb, MOVMuxContext *mov,
2814 int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE,
2815 track->timescale, AV_ROUND_UP);
2816 int version = duration < INT32_MAX ? 0 : 1;
2817 int entry_size, entry_count, size;
2818 int64_t delay, start_ct = track->start_cts;
2819 int64_t start_dts = track->start_dts;
2822 if (start_dts != track->cluster[0].dts || start_ct != track->cluster[0].cts) {
2824 av_log(mov->fc, AV_LOG_DEBUG,
2825 "EDTS using dts:%"PRId64" cts:%d instead of dts:%"PRId64" cts:%"PRId64" tid:%d\n",
2826 track->cluster[0].dts, track->cluster[0].cts,
2827 start_dts, start_ct, track->track_id);
2828 start_dts = track->cluster[0].dts;
2829 start_ct = track->cluster[0].cts;
2833 delay = av_rescale_rnd(start_dts + start_ct, MOV_TIMESCALE,
2834 track->timescale, AV_ROUND_DOWN);
2835 version |= delay < INT32_MAX ? 0 : 1;
2837 entry_size = (version == 1) ? 20 : 12;
2838 entry_count = 1 + (delay > 0);
2839 size = 24 + entry_count * entry_size;
2841 /* write the atom data */
2842 avio_wb32(pb, size);
2843 ffio_wfourcc(pb, "edts");
2844 avio_wb32(pb, size - 8);
2845 ffio_wfourcc(pb, "elst");
2846 avio_w8(pb, version);
2847 avio_wb24(pb, 0); /* flags */
2849 avio_wb32(pb, entry_count);
2850 if (delay > 0) { /* add an empty edit to delay presentation */
2851 /* In the positive delay case, the delay includes the cts
2852 * offset, and the second edit list entry below trims out
2853 * the same amount from the actual content. This makes sure
2854 * that the offset last sample is included in the edit
2855 * list duration as well. */
2857 avio_wb64(pb, delay);
2860 avio_wb32(pb, delay);
2863 avio_wb32(pb, 0x00010000);
2865 /* Avoid accidentally ending up with start_ct = -1 which has got a
2866 * special meaning. Normally start_ct should end up positive or zero
2867 * here, but use FFMIN in case dts is a small positive integer
2868 * rounded to 0 when represented in MOV_TIMESCALE units. */
2869 av_assert0(av_rescale_rnd(start_dts, MOV_TIMESCALE, track->timescale, AV_ROUND_DOWN) <= 0);
2870 start_ct = -FFMIN(start_dts, 0);
2871 /* Note, this delay is calculated from the pts of the first sample,
2872 * ensuring that we don't reduce the duration for cases with
2877 /* For fragmented files, we don't know the full length yet. Setting
2878 * duration to 0 allows us to only specify the offset, including
2879 * the rest of the content (from all future fragments) without specifying
2880 * an explicit duration. */
2881 if (mov->flags & FF_MOV_FLAG_FRAGMENT)
2886 avio_wb64(pb, duration);
2887 avio_wb64(pb, start_ct);
2889 avio_wb32(pb, duration);
2890 avio_wb32(pb, start_ct);
2892 avio_wb32(pb, 0x00010000);
2896 static int mov_write_tref_tag(AVIOContext *pb, MOVTrack *track)
2898 avio_wb32(pb, 20); // size
2899 ffio_wfourcc(pb, "tref");
2900 avio_wb32(pb, 12); // size (subatom)
2901 avio_wl32(pb, track->tref_tag);
2902 avio_wb32(pb, track->tref_id);
2906 // goes at the end of each track! ... Critical for PSP playback ("Incompatible data" without it)
2907 static int mov_write_uuid_tag_psp(AVIOContext *pb, MOVTrack *mov)
2909 avio_wb32(pb, 0x34); /* size ... reports as 28 in mp4box! */
2910 ffio_wfourcc(pb, "uuid");
2911 ffio_wfourcc(pb, "USMT");
2912 avio_wb32(pb, 0x21d24fce);
2913 avio_wb32(pb, 0xbb88695c);
2914 avio_wb32(pb, 0xfac9c740);
2915 avio_wb32(pb, 0x1c); // another size here!
2916 ffio_wfourcc(pb, "MTDT");
2917 avio_wb32(pb, 0x00010012);
2918 avio_wb32(pb, 0x0a);
2919 avio_wb32(pb, 0x55c40000);
2925 static int mov_write_udta_sdp(AVIOContext *pb, MOVTrack *track)
2927 AVFormatContext *ctx = track->rtp_ctx;
2928 char buf[1000] = "";
2931 ff_sdp_write_media(buf, sizeof(buf), ctx->streams[0], track->src_track,
2932 NULL, NULL, 0, 0, ctx);
2933 av_strlcatf(buf, sizeof(buf), "a=control:streamid=%d\r\n", track->track_id);
2936 avio_wb32(pb, len + 24);
2937 ffio_wfourcc(pb, "udta");
2938 avio_wb32(pb, len + 16);
2939 ffio_wfourcc(pb, "hnti");
2940 avio_wb32(pb, len + 8);
2941 ffio_wfourcc(pb, "sdp ");
2942 avio_write(pb, buf, len);
2946 static int mov_write_track_metadata(AVIOContext *pb, AVStream *st,
2947 const char *tag, const char *str)
2949 int64_t pos = avio_tell(pb);
2950 AVDictionaryEntry *t = av_dict_get(st->metadata, str, NULL, 0);
2951 if (!t || !utf8len(t->value))
2954 avio_wb32(pb, 0); /* size */
2955 ffio_wfourcc(pb, tag); /* type */
2956 avio_write(pb, t->value, strlen(t->value)); /* UTF8 string value */
2957 return update_size(pb, pos);
2960 static int mov_write_track_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
2963 AVIOContext *pb_buf;
2970 ret = avio_open_dyn_buf(&pb_buf);
2974 if (mov->mode & MODE_MP4)
2975 mov_write_track_metadata(pb_buf, st, "name", "title");
2977 if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) {
2978 avio_wb32(pb, size + 8);
2979 ffio_wfourcc(pb, "udta");
2980 avio_write(pb, buf, size);
2987 static int mov_write_trak_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov,
2988 MOVTrack *track, AVStream *st)
2990 int64_t pos = avio_tell(pb);
2991 int entry_backup = track->entry;
2992 int chunk_backup = track->chunkCount;
2995 /* If we want to have an empty moov, but some samples already have been
2996 * buffered (delay_moov), pretend that no samples have been written yet. */
2997 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV)
2998 track->chunkCount = track->entry = 0;
3000 avio_wb32(pb, 0); /* size */
3001 ffio_wfourcc(pb, "trak");
3002 mov_write_tkhd_tag(pb, mov, track, st);
3004 av_assert2(mov->use_editlist >= 0);
3006 if (track->start_dts != AV_NOPTS_VALUE) {
3007 if (mov->use_editlist)
3008 mov_write_edts_tag(pb, mov, track); // PSP Movies and several other cases require edts box
3009 else if ((track->entry && track->cluster[0].dts) || track->mode == MODE_PSP || is_clcp_track(track))
3010 av_log(mov->fc, AV_LOG_WARNING,
3011 "Not writing any edit list even though one would have been required\n");
3014 if (track->tref_tag)
3015 mov_write_tref_tag(pb, track);
3017 if ((ret = mov_write_mdia_tag(s, pb, mov, track)) < 0)
3019 if (track->mode == MODE_PSP)
3020 mov_write_uuid_tag_psp(pb, track); // PSP Movies require this uuid box
3021 if (track->tag == MKTAG('r','t','p',' '))
3022 mov_write_udta_sdp(pb, track);
3023 if (track->mode == MODE_MOV) {
3024 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
3025 double sample_aspect_ratio = av_q2d(st->sample_aspect_ratio);
3026 if (st->sample_aspect_ratio.num && 1.0 != sample_aspect_ratio) {
3027 mov_write_tapt_tag(pb, track);
3030 if (is_clcp_track(track) && st->sample_aspect_ratio.num) {
3031 mov_write_tapt_tag(pb, track);
3034 mov_write_track_udta_tag(pb, mov, st);
3035 track->entry = entry_backup;
3036 track->chunkCount = chunk_backup;
3037 return update_size(pb, pos);
3040 static int mov_write_iods_tag(AVIOContext *pb, MOVMuxContext *mov)
3042 int i, has_audio = 0, has_video = 0;
3043 int64_t pos = avio_tell(pb);
3044 int audio_profile = mov->iods_audio_profile;
3045 int video_profile = mov->iods_video_profile;
3046 for (i = 0; i < mov->nb_streams; i++) {
3047 if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
3048 has_audio |= mov->tracks[i].par->codec_type == AVMEDIA_TYPE_AUDIO;
3049 has_video |= mov->tracks[i].par->codec_type == AVMEDIA_TYPE_VIDEO;
3052 if (audio_profile < 0)
3053 audio_profile = 0xFF - has_audio;
3054 if (video_profile < 0)
3055 video_profile = 0xFF - has_video;
3056 avio_wb32(pb, 0x0); /* size */
3057 ffio_wfourcc(pb, "iods");
3058 avio_wb32(pb, 0); /* version & flags */
3059 put_descr(pb, 0x10, 7);
3060 avio_wb16(pb, 0x004f);
3063 avio_w8(pb, audio_profile);
3064 avio_w8(pb, video_profile);
3066 return update_size(pb, pos);
3069 static int mov_write_trex_tag(AVIOContext *pb, MOVTrack *track)
3071 avio_wb32(pb, 0x20); /* size */
3072 ffio_wfourcc(pb, "trex");
3073 avio_wb32(pb, 0); /* version & flags */
3074 avio_wb32(pb, track->track_id); /* track ID */
3075 avio_wb32(pb, 1); /* default sample description index */
3076 avio_wb32(pb, 0); /* default sample duration */
3077 avio_wb32(pb, 0); /* default sample size */
3078 avio_wb32(pb, 0); /* default sample flags */
3082 static int mov_write_mvex_tag(AVIOContext *pb, MOVMuxContext *mov)
3084 int64_t pos = avio_tell(pb);
3086 avio_wb32(pb, 0x0); /* size */
3087 ffio_wfourcc(pb, "mvex");
3088 for (i = 0; i < mov->nb_streams; i++)
3089 mov_write_trex_tag(pb, &mov->tracks[i]);
3090 return update_size(pb, pos);
3093 static int mov_write_mvhd_tag(AVIOContext *pb, MOVMuxContext *mov)
3095 int max_track_id = 1, i;
3096 int64_t max_track_len = 0;
3099 for (i = 0; i < mov->nb_streams; i++) {
3100 if (mov->tracks[i].entry > 0 && mov->tracks[i].timescale) {
3101 int64_t max_track_len_temp = av_rescale_rnd(mov->tracks[i].track_duration,
3103 mov->tracks[i].timescale,
3105 if (max_track_len < max_track_len_temp)
3106 max_track_len = max_track_len_temp;
3107 if (max_track_id < mov->tracks[i].track_id)
3108 max_track_id = mov->tracks[i].track_id;
3111 /* If using delay_moov, make sure the output is the same as if no
3112 * samples had been written yet. */
3113 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
3118 version = max_track_len < UINT32_MAX ? 0 : 1;
3119 avio_wb32(pb, version == 1 ? 120 : 108); /* size */
3121 ffio_wfourcc(pb, "mvhd");
3122 avio_w8(pb, version);
3123 avio_wb24(pb, 0); /* flags */
3125 avio_wb64(pb, mov->time);
3126 avio_wb64(pb, mov->time);
3128 avio_wb32(pb, mov->time); /* creation time */
3129 avio_wb32(pb, mov->time); /* modification time */
3131 avio_wb32(pb, MOV_TIMESCALE);
3132 (version == 1) ? avio_wb64(pb, max_track_len) : avio_wb32(pb, max_track_len); /* duration of longest track */
3134 avio_wb32(pb, 0x00010000); /* reserved (preferred rate) 1.0 = normal */
3135 avio_wb16(pb, 0x0100); /* reserved (preferred volume) 1.0 = normal */
3136 avio_wb16(pb, 0); /* reserved */
3137 avio_wb32(pb, 0); /* reserved */
3138 avio_wb32(pb, 0); /* reserved */
3140 /* Matrix structure */
3141 write_matrix(pb, 1, 0, 0, 1, 0, 0);
3143 avio_wb32(pb, 0); /* reserved (preview time) */
3144 avio_wb32(pb, 0); /* reserved (preview duration) */
3145 avio_wb32(pb, 0); /* reserved (poster time) */
3146 avio_wb32(pb, 0); /* reserved (selection time) */
3147 avio_wb32(pb, 0); /* reserved (selection duration) */
3148 avio_wb32(pb, 0); /* reserved (current time) */
3149 avio_wb32(pb, max_track_id + 1); /* Next track id */
3153 static int mov_write_itunes_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov,
3156 avio_wb32(pb, 33); /* size */
3157 ffio_wfourcc(pb, "hdlr");
3160 ffio_wfourcc(pb, "mdir");
3161 ffio_wfourcc(pb, "appl");
3168 /* helper function to write a data tag with the specified string as data */
3169 static int mov_write_string_data_tag(AVIOContext *pb, const char *data, int lang, int long_style)
3172 int size = 16 + strlen(data);
3173 avio_wb32(pb, size); /* size */
3174 ffio_wfourcc(pb, "data");
3177 avio_write(pb, data, strlen(data));
3181 lang = ff_mov_iso639_to_lang("und", 1);
3182 avio_wb16(pb, strlen(data)); /* string length */
3183 avio_wb16(pb, lang);
3184 avio_write(pb, data, strlen(data));
3185 return strlen(data) + 4;
3189 static int mov_write_string_tag(AVIOContext *pb, const char *name,
3190 const char *value, int lang, int long_style)
3193 if (value && value[0]) {
3194 int64_t pos = avio_tell(pb);
3195 avio_wb32(pb, 0); /* size */
3196 ffio_wfourcc(pb, name);
3197 mov_write_string_data_tag(pb, value, lang, long_style);
3198 size = update_size(pb, pos);
3203 static AVDictionaryEntry *get_metadata_lang(AVFormatContext *s,
3204 const char *tag, int *lang)
3207 AVDictionaryEntry *t, *t2 = NULL;
3212 if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
3215 len = strlen(t->key);
3216 snprintf(tag2, sizeof(tag2), "%s-", tag);
3217 while ((t2 = av_dict_get(s->metadata, tag2, t2, AV_DICT_IGNORE_SUFFIX))) {
3218 len2 = strlen(t2->key);
3219 if (len2 == len + 4 && !strcmp(t->value, t2->value)
3220 && (l = ff_mov_iso639_to_lang(&t2->key[len2 - 3], 1)) >= 0) {
3228 static int mov_write_string_metadata(AVFormatContext *s, AVIOContext *pb,
3229 const char *name, const char *tag,
3233 AVDictionaryEntry *t = get_metadata_lang(s, tag, &lang);
3236 return mov_write_string_tag(pb, name, t->value, lang, long_style);
3239 /* iTunes bpm number */
3240 static int mov_write_tmpo_tag(AVIOContext *pb, AVFormatContext *s)
3242 AVDictionaryEntry *t = av_dict_get(s->metadata, "tmpo", NULL, 0);
3243 int size = 0, tmpo = t ? atoi(t->value) : 0;
3246 avio_wb32(pb, size);
3247 ffio_wfourcc(pb, "tmpo");
3248 avio_wb32(pb, size-8); /* size */
3249 ffio_wfourcc(pb, "data");
3250 avio_wb32(pb, 0x15); //type specifier
3252 avio_wb16(pb, tmpo); // data
3257 /* 3GPP TS 26.244 */
3258 static int mov_write_loci_tag(AVFormatContext *s, AVIOContext *pb)
3261 int64_t pos = avio_tell(pb);
3262 double latitude, longitude, altitude;
3263 int32_t latitude_fix, longitude_fix, altitude_fix;
3264 AVDictionaryEntry *t = get_metadata_lang(s, "location", &lang);
3265 const char *ptr, *place = "";
3267 static const char *astronomical_body = "earth";
3272 longitude = strtod(ptr, &end);
3274 av_log(s, AV_LOG_WARNING, "malformed location metadata\n");
3278 latitude = strtod(ptr, &end);
3280 av_log(s, AV_LOG_WARNING, "malformed location metadata\n");
3284 altitude = strtod(ptr, &end);
3285 /* If no altitude was present, the default 0 should be fine */
3289 latitude_fix = (int32_t) ((1 << 16) * latitude);
3290 longitude_fix = (int32_t) ((1 << 16) * longitude);
3291 altitude_fix = (int32_t) ((1 << 16) * altitude);
3293 avio_wb32(pb, 0); /* size */
3294 ffio_wfourcc(pb, "loci"); /* type */
3295 avio_wb32(pb, 0); /* version + flags */
3296 avio_wb16(pb, lang);
3297 avio_write(pb, place, strlen(place) + 1);
3298 avio_w8(pb, 0); /* role of place (0 == shooting location, 1 == real location, 2 == fictional location) */
3299 avio_wb32(pb, latitude_fix);
3300 avio_wb32(pb, longitude_fix);
3301 avio_wb32(pb, altitude_fix);
3302 avio_write(pb, astronomical_body, strlen(astronomical_body) + 1);
3303 avio_w8(pb, 0); /* additional notes, null terminated string */
3305 return update_size(pb, pos);
3308 /* iTunes track or disc number */
3309 static int mov_write_trkn_tag(AVIOContext *pb, MOVMuxContext *mov,
3310 AVFormatContext *s, int disc)
3312 AVDictionaryEntry *t = av_dict_get(s->metadata,
3313 disc ? "disc" : "track",
3315 int size = 0, track = t ? atoi(t->value) : 0;
3318 char *slash = strchr(t->value, '/');
3320 tracks = atoi(slash + 1);
3321 avio_wb32(pb, 32); /* size */
3322 ffio_wfourcc(pb, disc ? "disk" : "trkn");
3323 avio_wb32(pb, 24); /* size */
3324 ffio_wfourcc(pb, "data");
3325 avio_wb32(pb, 0); // 8 bytes empty
3327 avio_wb16(pb, 0); // empty
3328 avio_wb16(pb, track); // track / disc number
3329 avio_wb16(pb, tracks); // total track / disc number
3330 avio_wb16(pb, 0); // empty
3336 static int mov_write_int8_metadata(AVFormatContext *s, AVIOContext *pb,
3337 const char *name, const char *tag,
3340 AVDictionaryEntry *t = NULL;
3342 int size = 24 + len;
3344 if (len != 1 && len != 4)
3347 if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
3349 num = atoi(t->value);
3351 avio_wb32(pb, size);
3352 ffio_wfourcc(pb, name);
3353 avio_wb32(pb, size - 8);
3354 ffio_wfourcc(pb, "data");
3355 avio_wb32(pb, 0x15);
3357 if (len==4) avio_wb32(pb, num);
3358 else avio_w8 (pb, num);
3363 /* iTunes meta data list */
3364 static int mov_write_ilst_tag(AVIOContext *pb, MOVMuxContext *mov,
3367 int64_t pos = avio_tell(pb);
3368 avio_wb32(pb, 0); /* size */
3369 ffio_wfourcc(pb, "ilst");
3370 mov_write_string_metadata(s, pb, "\251nam", "title" , 1);
3371 mov_write_string_metadata(s, pb, "\251ART", "artist" , 1);
3372 mov_write_string_metadata(s, pb, "aART", "album_artist", 1);
3373 mov_write_string_metadata(s, pb, "\251wrt", "composer" , 1);
3374 mov_write_string_metadata(s, pb, "\251alb", "album" , 1);
3375 mov_write_string_metadata(s, pb, "\251day", "date" , 1);
3376 if (!mov_write_string_metadata(s, pb, "\251too", "encoding_tool", 1)) {
3377 if (!(s->flags & AVFMT_FLAG_BITEXACT))
3378 mov_write_string_tag(pb, "\251too", LIBAVFORMAT_IDENT, 0, 1);
3380 mov_write_string_metadata(s, pb, "\251cmt", "comment" , 1);
3381 mov_write_string_metadata(s, pb, "\251gen", "genre" , 1);
3382 mov_write_string_metadata(s, pb, "\251cpy", "copyright", 1);
3383 mov_write_string_metadata(s, pb, "\251grp", "grouping" , 1);
3384 mov_write_string_metadata(s, pb, "\251lyr", "lyrics" , 1);
3385 mov_write_string_metadata(s, pb, "desc", "description",1);
3386 mov_write_string_metadata(s, pb, "ldes", "synopsis" , 1);
3387 mov_write_string_metadata(s, pb, "tvsh", "show" , 1);
3388 mov_write_string_metadata(s, pb, "tven", "episode_id",1);
3389 mov_write_string_metadata(s, pb, "tvnn", "network" , 1);
3390 mov_write_int8_metadata (s, pb, "tves", "episode_sort",4);
3391 mov_write_int8_metadata (s, pb, "tvsn", "season_number",4);
3392 mov_write_int8_metadata (s, pb, "stik", "media_type",1);
3393 mov_write_int8_metadata (s, pb, "hdvd", "hd_video", 1);
3394 mov_write_int8_metadata (s, pb, "pgap", "gapless_playback",1);
3395 mov_write_int8_metadata (s, pb, "cpil", "compilation", 1);
3396 mov_write_trkn_tag(pb, mov, s, 0); // track number
3397 mov_write_trkn_tag(pb, mov, s, 1); // disc number
3398 mov_write_tmpo_tag(pb, s);
3399 return update_size(pb, pos);
3402 static int mov_write_mdta_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov,
3405 avio_wb32(pb, 33); /* size */
3406 ffio_wfourcc(pb, "hdlr");
3409 ffio_wfourcc(pb, "mdta");
3417 static int mov_write_mdta_keys_tag(AVIOContext *pb, MOVMuxContext *mov,
3420 AVDictionaryEntry *t = NULL;
3421 int64_t pos = avio_tell(pb);
3422 int64_t curpos, entry_pos;
3425 avio_wb32(pb, 0); /* size */
3426 ffio_wfourcc(pb, "keys");
3428 entry_pos = avio_tell(pb);
3429 avio_wb32(pb, 0); /* entry count */
3431 while (t = av_dict_get(s->metadata, "", t, AV_DICT_IGNORE_SUFFIX)) {
3432 avio_wb32(pb, strlen(t->key) + 8);
3433 ffio_wfourcc(pb, "mdta");
3434 avio_write(pb, t->key, strlen(t->key));
3437 curpos = avio_tell(pb);
3438 avio_seek(pb, entry_pos, SEEK_SET);
3439 avio_wb32(pb, count); // rewrite entry count
3440 avio_seek(pb, curpos, SEEK_SET);
3442 return update_size(pb, pos);
3445 static int mov_write_mdta_ilst_tag(AVIOContext *pb, MOVMuxContext *mov,
3448 AVDictionaryEntry *t = NULL;
3449 int64_t pos = avio_tell(pb);
3450 int count = 1; /* keys are 1-index based */
3452 avio_wb32(pb, 0); /* size */
3453 ffio_wfourcc(pb, "ilst");
3455 while (t = av_dict_get(s->metadata, "", t, AV_DICT_IGNORE_SUFFIX)) {
3456 int64_t entry_pos = avio_tell(pb);
3457 avio_wb32(pb, 0); /* size */
3458 avio_wb32(pb, count); /* key */
3459 mov_write_string_data_tag(pb, t->value, 0, 1);
3460 update_size(pb, entry_pos);
3463 return update_size(pb, pos);
3466 /* meta data tags */
3467 static int mov_write_meta_tag(AVIOContext *pb, MOVMuxContext *mov,
3471 int64_t pos = avio_tell(pb);
3472 avio_wb32(pb, 0); /* size */
3473 ffio_wfourcc(pb, "meta");
3475 if (mov->flags & FF_MOV_FLAG_USE_MDTA) {
3476 mov_write_mdta_hdlr_tag(pb, mov, s);
3477 mov_write_mdta_keys_tag(pb, mov, s);
3478 mov_write_mdta_ilst_tag(pb, mov, s);
3481 /* iTunes metadata tag */
3482 mov_write_itunes_hdlr_tag(pb, mov, s);
3483 mov_write_ilst_tag(pb, mov, s);
3485 size = update_size(pb, pos);
3489 static int mov_write_raw_metadata_tag(AVFormatContext *s, AVIOContext *pb,
3490 const char *name, const char *key)
3493 AVDictionaryEntry *t;
3495 if (!(t = av_dict_get(s->metadata, key, NULL, 0)))
3498 len = strlen(t->value);
3501 avio_wb32(pb, size);
3502 ffio_wfourcc(pb, name);
3503 avio_write(pb, t->value, len);
3509 static int ascii_to_wc(AVIOContext *pb, const uint8_t *b)
3513 GET_UTF8(val, *b++, return -1;)
3516 avio_wb16(pb, 0x00);
3520 static uint16_t language_code(const char *str)
3522 return (((str[0] - 0x60) & 0x1F) << 10) +
3523 (((str[1] - 0x60) & 0x1F) << 5) +
3524 (( str[2] - 0x60) & 0x1F);
3527 static int mov_write_3gp_udta_tag(AVIOContext *pb, AVFormatContext *s,
3528 const char *tag, const char *str)
3530 int64_t pos = avio_tell(pb);
3531 AVDictionaryEntry *t = av_dict_get(s->metadata, str, NULL, 0);
3532 if (!t || !utf8len(t->value))
3534 avio_wb32(pb, 0); /* size */
3535 ffio_wfourcc(pb, tag); /* type */
3536 avio_wb32(pb, 0); /* version + flags */
3537 if (!strcmp(tag, "yrrc"))
3538 avio_wb16(pb, atoi(t->value));
3540 avio_wb16(pb, language_code("eng")); /* language */
3541 avio_write(pb, t->value, strlen(t->value) + 1); /* UTF8 string value */
3542 if (!strcmp(tag, "albm") &&
3543 (t = av_dict_get(s->metadata, "track", NULL, 0)))
3544 avio_w8(pb, atoi(t->value));
3546 return update_size(pb, pos);
3549 static int mov_write_chpl_tag(AVIOContext *pb, AVFormatContext *s)
3551 int64_t pos = avio_tell(pb);
3552 int i, nb_chapters = FFMIN(s->nb_chapters, 255);
3554 avio_wb32(pb, 0); // size
3555 ffio_wfourcc(pb, "chpl");
3556 avio_wb32(pb, 0x01000000); // version + flags
3557 avio_wb32(pb, 0); // unknown
3558 avio_w8(pb, nb_chapters);
3560 for (i = 0; i < nb_chapters; i++) {
3561 AVChapter *c = s->chapters[i];
3562 AVDictionaryEntry *t;
3563 avio_wb64(pb, av_rescale_q(c->start, c->time_base, (AVRational){1,10000000}));
3565 if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
3566 int len = FFMIN(strlen(t->value), 255);
3568 avio_write(pb, t->value, len);
3572 return update_size(pb, pos);
3575 static int mov_write_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
3578 AVIOContext *pb_buf;
3582 ret = avio_open_dyn_buf(&pb_buf);
3586 if (mov->mode & MODE_3GP) {
3587 mov_write_3gp_udta_tag(pb_buf, s, "perf", "artist");
3588 mov_write_3gp_udta_tag(pb_buf, s, "titl", "title");
3589 mov_write_3gp_udta_tag(pb_buf, s, "auth", "author");
3590 mov_write_3gp_udta_tag(pb_buf, s, "gnre", "genre");
3591 mov_write_3gp_udta_tag(pb_buf, s, "dscp", "comment");
3592 mov_write_3gp_udta_tag(pb_buf, s, "albm", "album");
3593 mov_write_3gp_udta_tag(pb_buf, s, "cprt", "copyright");
3594 mov_write_3gp_udta_tag(pb_buf, s, "yrrc", "date");
3595 mov_write_loci_tag(s, pb_buf);
3596 } 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
3597 mov_write_string_metadata(s, pb_buf, "\251ART", "artist", 0);
3598 mov_write_string_metadata(s, pb_buf, "\251nam", "title", 0);
3599 mov_write_string_metadata(s, pb_buf, "\251aut", "author", 0);
3600 mov_write_string_metadata(s, pb_buf, "\251alb", "album", 0);
3601 mov_write_string_metadata(s, pb_buf, "\251day", "date", 0);
3602 mov_write_string_metadata(s, pb_buf, "\251swr", "encoder", 0);
3603 // currently ignored by mov.c
3604 mov_write_string_metadata(s, pb_buf, "\251des", "comment", 0);
3605 // add support for libquicktime, this atom is also actually read by mov.c
3606 mov_write_string_metadata(s, pb_buf, "\251cmt", "comment", 0);
3607 mov_write_string_metadata(s, pb_buf, "\251gen", "genre", 0);
3608 mov_write_string_metadata(s, pb_buf, "\251cpy", "copyright", 0);
3609 mov_write_string_metadata(s, pb_buf, "\251mak", "make", 0);
3610 mov_write_string_metadata(s, pb_buf, "\251mod", "model", 0);
3611 mov_write_string_metadata(s, pb_buf, "\251xyz", "location", 0);
3612 mov_write_raw_metadata_tag(s, pb_buf, "XMP_", "xmp");
3614 /* iTunes meta data */
3615 mov_write_meta_tag(pb_buf, mov, s);
3616 mov_write_loci_tag(s, pb_buf);
3619 if (s->nb_chapters && !(mov->flags & FF_MOV_FLAG_DISABLE_CHPL))
3620 mov_write_chpl_tag(pb_buf, s);
3622 if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) {
3623 avio_wb32(pb, size + 8);
3624 ffio_wfourcc(pb, "udta");
3625 avio_write(pb, buf, size);
3632 static void mov_write_psp_udta_tag(AVIOContext *pb,
3633 const char *str, const char *lang, int type)
3635 int len = utf8len(str) + 1;
3638 avio_wb16(pb, len * 2 + 10); /* size */
3639 avio_wb32(pb, type); /* type */
3640 avio_wb16(pb, language_code(lang)); /* language */
3641 avio_wb16(pb, 0x01); /* ? */
3642 ascii_to_wc(pb, str);
3645 static int mov_write_uuidusmt_tag(AVIOContext *pb, AVFormatContext *s)
3647 AVDictionaryEntry *title = av_dict_get(s->metadata, "title", NULL, 0);
3651 pos = avio_tell(pb);
3652 avio_wb32(pb, 0); /* size placeholder*/
3653 ffio_wfourcc(pb, "uuid");
3654 ffio_wfourcc(pb, "USMT");
3655 avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
3656 avio_wb32(pb, 0xbb88695c);
3657 avio_wb32(pb, 0xfac9c740);
3659 pos2 = avio_tell(pb);
3660 avio_wb32(pb, 0); /* size placeholder*/
3661 ffio_wfourcc(pb, "MTDT");
3665 avio_wb16(pb, 0x0C); /* size */
3666 avio_wb32(pb, 0x0B); /* type */
3667 avio_wb16(pb, language_code("und")); /* language */
3668 avio_wb16(pb, 0x0); /* ? */
3669 avio_wb16(pb, 0x021C); /* data */
3671 if (!(s->flags & AVFMT_FLAG_BITEXACT))
3672 mov_write_psp_udta_tag(pb, LIBAVCODEC_IDENT, "eng", 0x04);
3673 mov_write_psp_udta_tag(pb, title->value, "eng", 0x01);
3674 mov_write_psp_udta_tag(pb, "2006/04/01 11:11:11", "und", 0x03);
3676 update_size(pb, pos2);
3677 return update_size(pb, pos);
3683 static void build_chunks(MOVTrack *trk)
3686 MOVIentry *chunk = &trk->cluster[0];
3687 uint64_t chunkSize = chunk->size;
3688 chunk->chunkNum = 1;
3689 if (trk->chunkCount)
3691 trk->chunkCount = 1;
3692 for (i = 1; i<trk->entry; i++){
3693 if (chunk->pos + chunkSize == trk->cluster[i].pos &&
3694 chunkSize + trk->cluster[i].size < (1<<20)){
3695 chunkSize += trk->cluster[i].size;
3696 chunk->samples_in_chunk += trk->cluster[i].entries;
3698 trk->cluster[i].chunkNum = chunk->chunkNum+1;
3699 chunk=&trk->cluster[i];
3700 chunkSize = chunk->size;
3707 * Assign track ids. If option "use_stream_ids_as_track_ids" is set,
3708 * the stream ids are used as track ids.
3710 * This assumes mov->tracks and s->streams are in the same order and
3711 * there are no gaps in either of them (so mov->tracks[n] refers to
3714 * As an exception, there can be more entries in
3715 * s->streams than in mov->tracks, in which case new track ids are
3716 * generated (starting after the largest found stream id).
3718 static int mov_setup_track_ids(MOVMuxContext *mov, AVFormatContext *s)
3722 if (mov->track_ids_ok)
3725 if (mov->use_stream_ids_as_track_ids) {
3726 int next_generated_track_id = 0;
3727 for (i = 0; i < s->nb_streams; i++) {
3728 if (s->streams[i]->id > next_generated_track_id)
3729 next_generated_track_id = s->streams[i]->id;
3732 for (i = 0; i < mov->nb_streams; i++) {
3733 if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
3736 mov->tracks[i].track_id = i >= s->nb_streams ? ++next_generated_track_id : s->streams[i]->id;
3739 for (i = 0; i < mov->nb_streams; i++) {
3740 if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
3743 mov->tracks[i].track_id = i + 1;
3747 mov->track_ids_ok = 1;
3752 static int mov_write_moov_tag(AVIOContext *pb, MOVMuxContext *mov,
3756 int64_t pos = avio_tell(pb);
3757 avio_wb32(pb, 0); /* size placeholder*/
3758 ffio_wfourcc(pb, "moov");
3760 mov_setup_track_ids(mov, s);
3762 for (i = 0; i < mov->nb_streams; i++) {
3763 if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
3766 mov->tracks[i].time = mov->time;
3768 if (mov->tracks[i].entry)
3769 build_chunks(&mov->tracks[i]);
3772 if (mov->chapter_track)
3773 for (i = 0; i < s->nb_streams; i++) {
3774 mov->tracks[i].tref_tag = MKTAG('c','h','a','p');
3775 mov->tracks[i].tref_id = mov->tracks[mov->chapter_track].track_id;
3777 for (i = 0; i < mov->nb_streams; i++) {
3778 MOVTrack *track = &mov->tracks[i];
3779 if (track->tag == MKTAG('r','t','p',' ')) {
3780 track->tref_tag = MKTAG('h','i','n','t');
3781 track->tref_id = mov->tracks[track->src_track].track_id;
3782 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
3783 int * fallback, size;
3784 fallback = (int*)av_stream_get_side_data(track->st,
3785 AV_PKT_DATA_FALLBACK_TRACK,
3787 if (fallback != NULL && size == sizeof(int)) {
3788 if (*fallback >= 0 && *fallback < mov->nb_streams) {
3789 track->tref_tag = MKTAG('f','a','l','l');
3790 track->tref_id = mov->tracks[*fallback].track_id;
3795 for (i = 0; i < mov->nb_streams; i++) {
3796 if (mov->tracks[i].tag == MKTAG('t','m','c','d')) {
3797 int src_trk = mov->tracks[i].src_track;
3798 mov->tracks[src_trk].tref_tag = mov->tracks[i].tag;
3799 mov->tracks[src_trk].tref_id = mov->tracks[i].track_id;
3800 //src_trk may have a different timescale than the tmcd track
3801 mov->tracks[i].track_duration = av_rescale(mov->tracks[src_trk].track_duration,
3802 mov->tracks[i].timescale,
3803 mov->tracks[src_trk].timescale);
3807 mov_write_mvhd_tag(pb, mov);
3808 if (mov->mode != MODE_MOV && !mov->iods_skip)
3809 mov_write_iods_tag(pb, mov);
3810 for (i = 0; i < mov->nb_streams; i++) {
3811 if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_FRAGMENT) {
3812 int ret = mov_write_trak_tag(s, pb, mov, &(mov->tracks[i]), i < s->nb_streams ? s->streams[i] : NULL);
3817 if (mov->flags & FF_MOV_FLAG_FRAGMENT)
3818 mov_write_mvex_tag(pb, mov); /* QuickTime requires trak to precede this */
3820 if (mov->mode == MODE_PSP)
3821 mov_write_uuidusmt_tag(pb, s);
3823 mov_write_udta_tag(pb, mov, s);
3825 return update_size(pb, pos);
3828 static void param_write_int(AVIOContext *pb, const char *name, int value)
3830 avio_printf(pb, "<param name=\"%s\" value=\"%d\" valuetype=\"data\"/>\n", name, value);
3833 static void param_write_string(AVIOContext *pb, const char *name, const char *value)
3835 avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, value);
3838 static void param_write_hex(AVIOContext *pb, const char *name, const uint8_t *value, int len)
3841 len = FFMIN(sizeof(buf) / 2 - 1, len);
3842 ff_data_to_hex(buf, value, len, 0);
3843 buf[2 * len] = '\0';
3844 avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, buf);
3847 static int mov_write_isml_manifest(AVIOContext *pb, MOVMuxContext *mov, AVFormatContext *s)
3849 int64_t pos = avio_tell(pb);
3851 int64_t manifest_bit_rate = 0;
3852 AVCPBProperties *props = NULL;
3854 static const uint8_t uuid[] = {
3855 0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd,
3856 0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66
3860 ffio_wfourcc(pb, "uuid");
3861 avio_write(pb, uuid, sizeof(uuid));
3864 avio_printf(pb, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
3865 avio_printf(pb, "<smil xmlns=\"http://www.w3.org/2001/SMIL20/Language\">\n");
3866 avio_printf(pb, "<head>\n");
3867 if (!(mov->fc->flags & AVFMT_FLAG_BITEXACT))
3868 avio_printf(pb, "<meta name=\"creator\" content=\"%s\" />\n",
3870 avio_printf(pb, "</head>\n");
3871 avio_printf(pb, "<body>\n");
3872 avio_printf(pb, "<switch>\n");
3874 mov_setup_track_ids(mov, s);
3876 for (i = 0; i < mov->nb_streams; i++) {
3877 MOVTrack *track = &mov->tracks[i];
3879 int track_id = track->track_id;
3880 char track_name_buf[32] = { 0 };
3882 AVStream *st = track->st;
3883 AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0);
3885 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
3887 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
3893 props = (AVCPBProperties*)av_stream_get_side_data(track->st, AV_PKT_DATA_CPB_PROPERTIES, NULL);
3895 if (track->par->bit_rate) {
3896 manifest_bit_rate = track->par->bit_rate;
3898 manifest_bit_rate = props->max_bitrate;
3901 avio_printf(pb, "<%s systemBitrate=\"%"PRId64"\">\n", type,
3903 param_write_int(pb, "systemBitrate", manifest_bit_rate);
3904 param_write_int(pb, "trackID", track_id);
3905 param_write_string(pb, "systemLanguage", lang ? lang->value : "und");
3907 /* Build track name piece by piece: */
3909 av_strlcat(track_name_buf, type, sizeof(track_name_buf));
3910 /* 2. track language, if available */
3912 av_strlcatf(track_name_buf, sizeof(track_name_buf),
3913 "_%s", lang->value);
3914 /* 3. special type suffix */
3915 /* "_cc" = closed captions, "_ad" = audio_description */
3916 if (st->disposition & AV_DISPOSITION_HEARING_IMPAIRED)
3917 av_strlcat(track_name_buf, "_cc", sizeof(track_name_buf));
3918 else if (st->disposition & AV_DISPOSITION_VISUAL_IMPAIRED)
3919 av_strlcat(track_name_buf, "_ad", sizeof(track_name_buf));
3921 param_write_string(pb, "trackName", track_name_buf);
3923 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
3924 if (track->par->codec_id == AV_CODEC_ID_H264) {
3926 int size = track->par->extradata_size;
3927 if (!ff_avc_write_annexb_extradata(track->par->extradata, &ptr,
3929 param_write_hex(pb, "CodecPrivateData",
3930 ptr ? ptr : track->par->extradata,
3934 param_write_string(pb, "FourCC", "H264");
3935 } else if (track->par->codec_id == AV_CODEC_ID_VC1) {
3936 param_write_string(pb, "FourCC", "WVC1");
3937 param_write_hex(pb, "CodecPrivateData", track->par->extradata,
3938 track->par->extradata_size);
3940 param_write_int(pb, "MaxWidth", track->par->width);
3941 param_write_int(pb, "MaxHeight", track->par->height);
3942 param_write_int(pb, "DisplayWidth", track->par->width);
3943 param_write_int(pb, "DisplayHeight", track->par->height);
3945 if (track->par->codec_id == AV_CODEC_ID_AAC) {
3946 switch (track->par->profile)
3948 case FF_PROFILE_AAC_HE_V2:
3949 param_write_string(pb, "FourCC", "AACP");
3951 case FF_PROFILE_AAC_HE:
3952 param_write_string(pb, "FourCC", "AACH");
3955 param_write_string(pb, "FourCC", "AACL");
3957 } else if (track->par->codec_id == AV_CODEC_ID_WMAPRO) {
3958 param_write_string(pb, "FourCC", "WMAP");
3960 param_write_hex(pb, "CodecPrivateData", track->par->extradata,
3961 track->par->extradata_size);
3962 param_write_int(pb, "AudioTag", ff_codec_get_tag(ff_codec_wav_tags,
3963 track->par->codec_id));
3964 param_write_int(pb, "Channels", track->par->channels);
3965 param_write_int(pb, "SamplingRate", track->par->sample_rate);
3966 param_write_int(pb, "BitsPerSample", 16);
3967 param_write_int(pb, "PacketSize", track->par->block_align ?
3968 track->par->block_align : 4);
3970 avio_printf(pb, "</%s>\n", type);
3972 avio_printf(pb, "</switch>\n");
3973 avio_printf(pb, "</body>\n");
3974 avio_printf(pb, "</smil>\n");
3976 return update_size(pb, pos);
3979 static int mov_write_mfhd_tag(AVIOContext *pb, MOVMuxContext *mov)
3982 ffio_wfourcc(pb, "mfhd");
3984 avio_wb32(pb, mov->fragments);
3988 static uint32_t get_sample_flags(MOVTrack *track, MOVIentry *entry)
3990 return entry->flags & MOV_SYNC_SAMPLE ? MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO :
3991 (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC);
3994 static int mov_write_tfhd_tag(AVIOContext *pb, MOVMuxContext *mov,
3995 MOVTrack *track, int64_t moof_offset)
3997 int64_t pos = avio_tell(pb);
3998 uint32_t flags = MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
3999 MOV_TFHD_BASE_DATA_OFFSET;
4000 if (!track->entry) {
4001 flags |= MOV_TFHD_DURATION_IS_EMPTY;
4003 flags |= MOV_TFHD_DEFAULT_FLAGS;
4005 if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET)
4006 flags &= ~MOV_TFHD_BASE_DATA_OFFSET;
4007 if (mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) {
4008 flags &= ~MOV_TFHD_BASE_DATA_OFFSET;
4009 flags |= MOV_TFHD_DEFAULT_BASE_IS_MOOF;
4012 /* Don't set a default sample size, the silverlight player refuses
4013 * to play files with that set. Don't set a default sample duration,
4014 * WMP freaks out if it is set. Don't set a base data offset, PIFF
4015 * file format says it MUST NOT be set. */
4016 if (track->mode == MODE_ISM)
4017 flags &= ~(MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
4018 MOV_TFHD_BASE_DATA_OFFSET);
4020 avio_wb32(pb, 0); /* size placeholder */
4021 ffio_wfourcc(pb, "tfhd");
4022 avio_w8(pb, 0); /* version */
4023 avio_wb24(pb, flags);
4025 avio_wb32(pb, track->track_id); /* track-id */
4026 if (flags & MOV_TFHD_BASE_DATA_OFFSET)
4027 avio_wb64(pb, moof_offset);
4028 if (flags & MOV_TFHD_DEFAULT_DURATION) {
4029 track->default_duration = get_cluster_duration(track, 0);
4030 avio_wb32(pb, track->default_duration);
4032 if (flags & MOV_TFHD_DEFAULT_SIZE) {
4033 track->default_size = track->entry ? track->cluster[0].size : 1;
4034 avio_wb32(pb, track->default_size);
4036 track->default_size = -1;
4038 if (flags & MOV_TFHD_DEFAULT_FLAGS) {
4039 /* Set the default flags based on the second sample, if available.
4040 * If the first sample is different, that can be signaled via a separate field. */
4041 if (track->entry > 1)
4042 track->default_sample_flags = get_sample_flags(track, &track->cluster[1]);
4044 track->default_sample_flags =
4045 track->par->codec_type == AVMEDIA_TYPE_VIDEO ?
4046 (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC) :
4047 MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO;
4048 avio_wb32(pb, track->default_sample_flags);
4051 return update_size(pb, pos);
4054 static int mov_write_trun_tag(AVIOContext *pb, MOVMuxContext *mov,
4055 MOVTrack *track, int moof_size,
4058 int64_t pos = avio_tell(pb);
4059 uint32_t flags = MOV_TRUN_DATA_OFFSET;
4062 for (i = first; i < end; i++) {
4063 if (get_cluster_duration(track, i) != track->default_duration)
4064 flags |= MOV_TRUN_SAMPLE_DURATION;
4065 if (track->cluster[i].size != track->default_size)
4066 flags |= MOV_TRUN_SAMPLE_SIZE;
4067 if (i > first && get_sample_flags(track, &track->cluster[i]) != track->default_sample_flags)
4068 flags |= MOV_TRUN_SAMPLE_FLAGS;
4070 if (!(flags & MOV_TRUN_SAMPLE_FLAGS) && track->entry > 0 &&
4071 get_sample_flags(track, &track->cluster[0]) != track->default_sample_flags)
4072 flags |= MOV_TRUN_FIRST_SAMPLE_FLAGS;
4073 if (track->flags & MOV_TRACK_CTTS)
4074 flags |= MOV_TRUN_SAMPLE_CTS;
4076 avio_wb32(pb, 0); /* size placeholder */
4077 ffio_wfourcc(pb, "trun");
4078 avio_w8(pb, 0); /* version */
4079 avio_wb24(pb, flags);
4081 avio_wb32(pb, end - first); /* sample count */
4082 if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET &&
4083 !(mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) &&
4085 avio_wb32(pb, 0); /* Later tracks follow immediately after the previous one */
4087 avio_wb32(pb, moof_size + 8 + track->data_offset +
4088 track->cluster[first].pos); /* data offset */
4089 if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS)
4090 avio_wb32(pb, get_sample_flags(track, &track->cluster[first]));
4092 for (i = first; i < end; i++) {
4093 if (flags & MOV_TRUN_SAMPLE_DURATION)
4094 avio_wb32(pb, get_cluster_duration(track, i));
4095 if (flags & MOV_TRUN_SAMPLE_SIZE)
4096 avio_wb32(pb, track->cluster[i].size);
4097 if (flags & MOV_TRUN_SAMPLE_FLAGS)
4098 avio_wb32(pb, get_sample_flags(track, &track->cluster[i]));
4099 if (flags & MOV_TRUN_SAMPLE_CTS)
4100 avio_wb32(pb, track->cluster[i].cts);
4103 mov->first_trun = 0;
4104 return update_size(pb, pos);
4107 static int mov_write_tfxd_tag(AVIOContext *pb, MOVTrack *track)
4109 int64_t pos = avio_tell(pb);
4110 static const uint8_t uuid[] = {
4111 0x6d, 0x1d, 0x9b, 0x05, 0x42, 0xd5, 0x44, 0xe6,
4112 0x80, 0xe2, 0x14, 0x1d, 0xaf, 0xf7, 0x57, 0xb2
4115 avio_wb32(pb, 0); /* size placeholder */
4116 ffio_wfourcc(pb, "uuid");
4117 avio_write(pb, uuid, sizeof(uuid));
4120 avio_wb64(pb, track->start_dts + track->frag_start +
4121 track->cluster[0].cts);
4122 avio_wb64(pb, track->end_pts -
4123 (track->cluster[0].dts + track->cluster[0].cts));
4125 return update_size(pb, pos);
4128 static int mov_write_tfrf_tag(AVIOContext *pb, MOVMuxContext *mov,
4129 MOVTrack *track, int entry)
4131 int n = track->nb_frag_info - 1 - entry, i;
4132 int size = 8 + 16 + 4 + 1 + 16*n;
4133 static const uint8_t uuid[] = {
4134 0xd4, 0x80, 0x7e, 0xf2, 0xca, 0x39, 0x46, 0x95,
4135 0x8e, 0x54, 0x26, 0xcb, 0x9e, 0x46, 0xa7, 0x9f
4141 avio_seek(pb, track->frag_info[entry].tfrf_offset, SEEK_SET);
4142 avio_wb32(pb, size);
4143 ffio_wfourcc(pb, "uuid");
4144 avio_write(pb, uuid, sizeof(uuid));
4148 for (i = 0; i < n; i++) {
4149 int index = entry + 1 + i;
4150 avio_wb64(pb, track->frag_info[index].time);
4151 avio_wb64(pb, track->frag_info[index].duration);
4153 if (n < mov->ism_lookahead) {
4154 int free_size = 16 * (mov->ism_lookahead - n);
4155 avio_wb32(pb, free_size);
4156 ffio_wfourcc(pb, "free");
4157 ffio_fill(pb, 0, free_size - 8);
4163 static int mov_write_tfrf_tags(AVIOContext *pb, MOVMuxContext *mov,
4166 int64_t pos = avio_tell(pb);
4168 for (i = 0; i < mov->ism_lookahead; i++) {
4169 /* Update the tfrf tag for the last ism_lookahead fragments,
4170 * nb_frag_info - 1 is the next fragment to be written. */
4171 mov_write_tfrf_tag(pb, mov, track, track->nb_frag_info - 2 - i);
4173 avio_seek(pb, pos, SEEK_SET);
4177 static int mov_add_tfra_entries(AVIOContext *pb, MOVMuxContext *mov, int tracks,
4181 for (i = 0; i < mov->nb_streams; i++) {
4182 MOVTrack *track = &mov->tracks[i];
4183 MOVFragmentInfo *info;
4184 if ((tracks >= 0 && i != tracks) || !track->entry)
4186 track->nb_frag_info++;
4187 if (track->nb_frag_info >= track->frag_info_capacity) {
4188 unsigned new_capacity = track->nb_frag_info + MOV_FRAG_INFO_ALLOC_INCREMENT;
4189 if (av_reallocp_array(&track->frag_info,
4191 sizeof(*track->frag_info)))
4192 return AVERROR(ENOMEM);
4193 track->frag_info_capacity = new_capacity;
4195 info = &track->frag_info[track->nb_frag_info - 1];
4196 info->offset = avio_tell(pb);
4198 // Try to recreate the original pts for the first packet
4199 // from the fields we have stored
4200 info->time = track->start_dts + track->frag_start +
4201 track->cluster[0].cts;
4202 info->duration = track->end_pts -
4203 (track->cluster[0].dts + track->cluster[0].cts);
4204 // If the pts is less than zero, we will have trimmed
4205 // away parts of the media track using an edit list,
4206 // and the corresponding start presentation time is zero.
4207 if (info->time < 0) {
4208 info->duration += info->time;
4211 info->tfrf_offset = 0;
4212 mov_write_tfrf_tags(pb, mov, track);
4217 static void mov_prune_frag_info(MOVMuxContext *mov, int tracks, int max)
4220 for (i = 0; i < mov->nb_streams; i++) {
4221 MOVTrack *track = &mov->tracks[i];
4222 if ((tracks >= 0 && i != tracks) || !track->entry)
4224 if (track->nb_frag_info > max) {
4225 memmove(track->frag_info, track->frag_info + (track->nb_frag_info - max), max * sizeof(*track->frag_info));
4226 track->nb_frag_info = max;
4231 static int mov_write_tfdt_tag(AVIOContext *pb, MOVTrack *track)
4233 int64_t pos = avio_tell(pb);
4235 avio_wb32(pb, 0); /* size */
4236 ffio_wfourcc(pb, "tfdt");
4237 avio_w8(pb, 1); /* version */
4239 avio_wb64(pb, track->frag_start);
4240 return update_size(pb, pos);
4243 static int mov_write_traf_tag(AVIOContext *pb, MOVMuxContext *mov,
4244 MOVTrack *track, int64_t moof_offset,
4247 int64_t pos = avio_tell(pb);
4249 avio_wb32(pb, 0); /* size placeholder */
4250 ffio_wfourcc(pb, "traf");
4252 mov_write_tfhd_tag(pb, mov, track, moof_offset);
4253 if (mov->mode != MODE_ISM)
4254 mov_write_tfdt_tag(pb, track);
4255 for (i = 1; i < track->entry; i++) {
4256 if (track->cluster[i].pos != track->cluster[i - 1].pos + track->cluster[i - 1].size) {
4257 mov_write_trun_tag(pb, mov, track, moof_size, start, i);
4261 mov_write_trun_tag(pb, mov, track, moof_size, start, track->entry);
4262 if (mov->mode == MODE_ISM) {
4263 mov_write_tfxd_tag(pb, track);
4265 if (mov->ism_lookahead) {
4266 int i, size = 16 + 4 + 1 + 16 * mov->ism_lookahead;
4268 if (track->nb_frag_info > 0) {
4269 MOVFragmentInfo *info = &track->frag_info[track->nb_frag_info - 1];
4270 if (!info->tfrf_offset)
4271 info->tfrf_offset = avio_tell(pb);
4273 avio_wb32(pb, 8 + size);
4274 ffio_wfourcc(pb, "free");
4275 for (i = 0; i < size; i++)
4280 return update_size(pb, pos);
4283 static int mov_write_moof_tag_internal(AVIOContext *pb, MOVMuxContext *mov,
4284 int tracks, int moof_size)
4286 int64_t pos = avio_tell(pb);
4289 avio_wb32(pb, 0); /* size placeholder */
4290 ffio_wfourcc(pb, "moof");
4291 mov->first_trun = 1;
4293 mov_write_mfhd_tag(pb, mov);
4294 for (i = 0; i < mov->nb_streams; i++) {
4295 MOVTrack *track = &mov->tracks[i];
4296 if (tracks >= 0 && i != tracks)
4300 mov_write_traf_tag(pb, mov, track, pos, moof_size);
4303 return update_size(pb, pos);
4306 static int mov_write_sidx_tag(AVIOContext *pb,
4307 MOVTrack *track, int ref_size, int total_sidx_size)
4309 int64_t pos = avio_tell(pb), offset_pos, end_pos;
4310 int64_t presentation_time, duration, offset;
4311 int starts_with_SAP, i, entries;
4315 presentation_time = track->start_dts + track->frag_start +
4316 track->cluster[0].cts;
4317 duration = track->end_pts -
4318 (track->cluster[0].dts + track->cluster[0].cts);
4319 starts_with_SAP = track->cluster[0].flags & MOV_SYNC_SAMPLE;
4321 // pts<0 should be cut away using edts
4322 if (presentation_time < 0) {
4323 duration += presentation_time;
4324 presentation_time = 0;
4327 entries = track->nb_frag_info;
4330 presentation_time = track->frag_info[0].time;
4333 avio_wb32(pb, 0); /* size */
4334 ffio_wfourcc(pb, "sidx");
4335 avio_w8(pb, 1); /* version */
4337 avio_wb32(pb, track->track_id); /* reference_ID */
4338 avio_wb32(pb, track->timescale); /* timescale */
4339 avio_wb64(pb, presentation_time); /* earliest_presentation_time */
4340 offset_pos = avio_tell(pb);
4341 avio_wb64(pb, 0); /* first_offset (offset to referenced moof) */
4342 avio_wb16(pb, 0); /* reserved */
4344 avio_wb16(pb, entries); /* reference_count */
4345 for (i = 0; i < entries; i++) {
4346 if (!track->entry) {
4347 if (i > 1 && track->frag_info[i].offset != track->frag_info[i - 1].offset + track->frag_info[i - 1].size) {
4348 av_log(NULL, AV_LOG_ERROR, "Non-consecutive fragments, writing incorrect sidx\n");
4350 duration = track->frag_info[i].duration;
4351 ref_size = track->frag_info[i].size;
4352 starts_with_SAP = 1;
4354 avio_wb32(pb, (0 << 31) | (ref_size & 0x7fffffff)); /* reference_type (0 = media) | referenced_size */
4355 avio_wb32(pb, duration); /* subsegment_duration */
4356 avio_wb32(pb, (starts_with_SAP << 31) | (0 << 28) | 0); /* starts_with_SAP | SAP_type | SAP_delta_time */
4359 end_pos = avio_tell(pb);
4360 offset = pos + total_sidx_size - end_pos;
4361 avio_seek(pb, offset_pos, SEEK_SET);
4362 avio_wb64(pb, offset);
4363 avio_seek(pb, end_pos, SEEK_SET);
4364 return update_size(pb, pos);
4367 static int mov_write_sidx_tags(AVIOContext *pb, MOVMuxContext *mov,
4368 int tracks, int ref_size)
4371 AVIOContext *avio_buf;
4373 for (round = 0; round < 2; round++) {
4374 // First run one round to calculate the total size of all
4376 // This would be much simpler if we'd only write one sidx
4377 // atom, for the first track in the moof.
4379 if ((ret = ffio_open_null_buf(&avio_buf)) < 0)
4384 for (i = 0; i < mov->nb_streams; i++) {
4385 MOVTrack *track = &mov->tracks[i];
4386 if (tracks >= 0 && i != tracks)
4388 // When writing a sidx for the full file, entry is 0, but
4389 // we want to include all tracks. ref_size is 0 in this case,
4390 // since we read it from frag_info instead.
4391 if (!track->entry && ref_size > 0)
4393 total_size -= mov_write_sidx_tag(avio_buf, track, ref_size,
4397 total_size = ffio_close_null_buf(avio_buf);
4402 static int mov_write_moof_tag(AVIOContext *pb, MOVMuxContext *mov, int tracks,
4405 AVIOContext *avio_buf;
4408 if ((ret = ffio_open_null_buf(&avio_buf)) < 0)
4410 mov_write_moof_tag_internal(avio_buf, mov, tracks, 0);
4411 moof_size = ffio_close_null_buf(avio_buf);
4413 if (mov->flags & FF_MOV_FLAG_DASH && !(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX))
4414 mov_write_sidx_tags(pb, mov, tracks, moof_size + 8 + mdat_size);
4416 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX ||
4417 !(mov->flags & FF_MOV_FLAG_SKIP_TRAILER) ||
4418 mov->ism_lookahead) {
4419 if ((ret = mov_add_tfra_entries(pb, mov, tracks, moof_size + 8 + mdat_size)) < 0)
4421 if (!(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) &&
4422 mov->flags & FF_MOV_FLAG_SKIP_TRAILER) {
4423 mov_prune_frag_info(mov, tracks, mov->ism_lookahead + 1);
4427 return mov_write_moof_tag_internal(pb, mov, tracks, moof_size);
4430 static int mov_write_tfra_tag(AVIOContext *pb, MOVTrack *track)
4432 int64_t pos = avio_tell(pb);
4435 avio_wb32(pb, 0); /* size placeholder */
4436 ffio_wfourcc(pb, "tfra");
4437 avio_w8(pb, 1); /* version */
4440 avio_wb32(pb, track->track_id);
4441 avio_wb32(pb, 0); /* length of traf/trun/sample num */
4442 avio_wb32(pb, track->nb_frag_info);
4443 for (i = 0; i < track->nb_frag_info; i++) {
4444 avio_wb64(pb, track->frag_info[i].time);
4445 avio_wb64(pb, track->frag_info[i].offset + track->data_offset);
4446 avio_w8(pb, 1); /* traf number */
4447 avio_w8(pb, 1); /* trun number */
4448 avio_w8(pb, 1); /* sample number */
4451 return update_size(pb, pos);
4454 static int mov_write_mfra_tag(AVIOContext *pb, MOVMuxContext *mov)
4456 int64_t pos = avio_tell(pb);
4459 avio_wb32(pb, 0); /* size placeholder */
4460 ffio_wfourcc(pb, "mfra");
4461 /* An empty mfra atom is enough to indicate to the publishing point that
4462 * the stream has ended. */
4463 if (mov->flags & FF_MOV_FLAG_ISML)
4464 return update_size(pb, pos);
4466 for (i = 0; i < mov->nb_streams; i++) {
4467 MOVTrack *track = &mov->tracks[i];
4468 if (track->nb_frag_info)
4469 mov_write_tfra_tag(pb, track);
4473 ffio_wfourcc(pb, "mfro");
4474 avio_wb32(pb, 0); /* version + flags */
4475 avio_wb32(pb, avio_tell(pb) + 4 - pos);
4477 return update_size(pb, pos);
4480 static int mov_write_mdat_tag(AVIOContext *pb, MOVMuxContext *mov)
4482 avio_wb32(pb, 8); // placeholder for extended size field (64 bit)
4483 ffio_wfourcc(pb, mov->mode == MODE_MOV ? "wide" : "free");
4485 mov->mdat_pos = avio_tell(pb);
4486 avio_wb32(pb, 0); /* size placeholder*/
4487 ffio_wfourcc(pb, "mdat");
4491 /* TODO: This needs to be more general */
4492 static int mov_write_ftyp_tag(AVIOContext *pb, AVFormatContext *s)
4494 MOVMuxContext *mov = s->priv_data;
4495 int64_t pos = avio_tell(pb);
4496 int has_h264 = 0, has_video = 0;
4500 for (i = 0; i < s->nb_streams; i++) {
4501 AVStream *st = s->streams[i];
4502 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
4504 if (st->codecpar->codec_id == AV_CODEC_ID_H264)
4508 avio_wb32(pb, 0); /* size */
4509 ffio_wfourcc(pb, "ftyp");
4511 if (mov->major_brand && strlen(mov->major_brand) >= 4)
4512 ffio_wfourcc(pb, mov->major_brand);
4513 else if (mov->mode == MODE_3GP) {
4514 ffio_wfourcc(pb, has_h264 ? "3gp6" : "3gp4");
4515 minor = has_h264 ? 0x100 : 0x200;
4516 } else if (mov->mode & MODE_3G2) {
4517 ffio_wfourcc(pb, has_h264 ? "3g2b" : "3g2a");
4518 minor = has_h264 ? 0x20000 : 0x10000;
4519 } else if (mov->mode == MODE_PSP)
4520 ffio_wfourcc(pb, "MSNV");
4521 else if (mov->mode == MODE_MP4 && mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)
4522 ffio_wfourcc(pb, "iso5"); // Required when using default-base-is-moof
4523 else if (mov->mode == MODE_MP4)
4524 ffio_wfourcc(pb, "isom");
4525 else if (mov->mode == MODE_IPOD)
4526 ffio_wfourcc(pb, has_video ? "M4V ":"M4A ");
4527 else if (mov->mode == MODE_ISM)
4528 ffio_wfourcc(pb, "isml");
4529 else if (mov->mode == MODE_F4V)
4530 ffio_wfourcc(pb, "f4v ");
4532 ffio_wfourcc(pb, "qt ");
4534 avio_wb32(pb, minor);
4536 if (mov->mode == MODE_MOV)
4537 ffio_wfourcc(pb, "qt ");
4538 else if (mov->mode == MODE_ISM) {
4539 ffio_wfourcc(pb, "piff");
4540 } else if (!(mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)) {
4541 ffio_wfourcc(pb, "isom");
4542 ffio_wfourcc(pb, "iso2");
4544 ffio_wfourcc(pb, "avc1");
4547 // We add tfdt atoms when fragmenting, signal this with the iso6 compatible
4548 // brand. This is compatible with users that don't understand tfdt.
4549 if (mov->flags & FF_MOV_FLAG_FRAGMENT && mov->mode != MODE_ISM)
4550 ffio_wfourcc(pb, "iso6");
4552 if (mov->mode == MODE_3GP)
4553 ffio_wfourcc(pb, has_h264 ? "3gp6":"3gp4");
4554 else if (mov->mode & MODE_3G2)
4555 ffio_wfourcc(pb, has_h264 ? "3g2b":"3g2a");
4556 else if (mov->mode == MODE_PSP)
4557 ffio_wfourcc(pb, "MSNV");
4558 else if (mov->mode == MODE_MP4)
4559 ffio_wfourcc(pb, "mp41");
4561 if (mov->flags & FF_MOV_FLAG_DASH && mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
4562 ffio_wfourcc(pb, "dash");
4564 return update_size(pb, pos);
4567 static int mov_write_uuidprof_tag(AVIOContext *pb, AVFormatContext *s)
4569 AVStream *video_st = s->streams[0];
4570 AVCodecParameters *video_par = s->streams[0]->codecpar;
4571 AVCodecParameters *audio_par = s->streams[1]->codecpar;
4572 int audio_rate = audio_par->sample_rate;
4573 int64_t frame_rate = video_st->avg_frame_rate.den ?
4574 (video_st->avg_frame_rate.num * 0x10000LL) / video_st->avg_frame_rate.den :
4576 int audio_kbitrate = audio_par->bit_rate / 1000;
4577 int video_kbitrate = FFMIN(video_par->bit_rate / 1000, 800 - audio_kbitrate);
4579 if (frame_rate < 0 || frame_rate > INT32_MAX) {
4580 av_log(s, AV_LOG_ERROR, "Frame rate %f outside supported range\n", frame_rate / (double)0x10000);
4581 return AVERROR(EINVAL);
4584 avio_wb32(pb, 0x94); /* size */
4585 ffio_wfourcc(pb, "uuid");
4586 ffio_wfourcc(pb, "PROF");
4588 avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
4589 avio_wb32(pb, 0xbb88695c);
4590 avio_wb32(pb, 0xfac9c740);
4592 avio_wb32(pb, 0x0); /* ? */
4593 avio_wb32(pb, 0x3); /* 3 sections ? */
4595 avio_wb32(pb, 0x14); /* size */
4596 ffio_wfourcc(pb, "FPRF");
4597 avio_wb32(pb, 0x0); /* ? */
4598 avio_wb32(pb, 0x0); /* ? */
4599 avio_wb32(pb, 0x0); /* ? */
4601 avio_wb32(pb, 0x2c); /* size */
4602 ffio_wfourcc(pb, "APRF"); /* audio */
4604 avio_wb32(pb, 0x2); /* TrackID */
4605 ffio_wfourcc(pb, "mp4a");
4606 avio_wb32(pb, 0x20f);
4608 avio_wb32(pb, audio_kbitrate);
4609 avio_wb32(pb, audio_kbitrate);
4610 avio_wb32(pb, audio_rate);
4611 avio_wb32(pb, audio_par->channels);
4613 avio_wb32(pb, 0x34); /* size */
4614 ffio_wfourcc(pb, "VPRF"); /* video */
4616 avio_wb32(pb, 0x1); /* TrackID */
4617 if (video_par->codec_id == AV_CODEC_ID_H264) {
4618 ffio_wfourcc(pb, "avc1");
4619 avio_wb16(pb, 0x014D);
4620 avio_wb16(pb, 0x0015);
4622 ffio_wfourcc(pb, "mp4v");
4623 avio_wb16(pb, 0x0000);
4624 avio_wb16(pb, 0x0103);
4627 avio_wb32(pb, video_kbitrate);
4628 avio_wb32(pb, video_kbitrate);
4629 avio_wb32(pb, frame_rate);
4630 avio_wb32(pb, frame_rate);
4631 avio_wb16(pb, video_par->width);
4632 avio_wb16(pb, video_par->height);
4633 avio_wb32(pb, 0x010001); /* ? */
4638 static int mov_write_identification(AVIOContext *pb, AVFormatContext *s)
4640 MOVMuxContext *mov = s->priv_data;
4643 mov_write_ftyp_tag(pb,s);
4644 if (mov->mode == MODE_PSP) {
4645 int video_streams_nb = 0, audio_streams_nb = 0, other_streams_nb = 0;
4646 for (i = 0; i < s->nb_streams; i++) {
4647 AVStream *st = s->streams[i];
4648 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
4650 else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
4656 if (video_streams_nb != 1 || audio_streams_nb != 1 || other_streams_nb) {
4657 av_log(s, AV_LOG_ERROR, "PSP mode need one video and one audio stream\n");
4658 return AVERROR(EINVAL);
4660 return mov_write_uuidprof_tag(pb, s);
4665 static int mov_parse_mpeg2_frame(AVPacket *pkt, uint32_t *flags)
4668 int i, closed_gop = 0;
4670 for (i = 0; i < pkt->size - 4; i++) {
4671 c = (c << 8) + pkt->data[i];
4672 if (c == 0x1b8) { // gop
4673 closed_gop = pkt->data[i + 4] >> 6 & 0x01;
4674 } else if (c == 0x100) { // pic
4675 int temp_ref = (pkt->data[i + 1] << 2) | (pkt->data[i + 2] >> 6);
4676 if (!temp_ref || closed_gop) // I picture is not reordered
4677 *flags = MOV_SYNC_SAMPLE;
4679 *flags = MOV_PARTIAL_SYNC_SAMPLE;
4686 static void mov_parse_vc1_frame(AVPacket *pkt, MOVTrack *trk)
4688 const uint8_t *start, *next, *end = pkt->data + pkt->size;
4689 int seq = 0, entry = 0;
4690 int key = pkt->flags & AV_PKT_FLAG_KEY;
4691 start = find_next_marker(pkt->data, end);
4692 for (next = start; next < end; start = next) {
4693 next = find_next_marker(start + 4, end);
4694 switch (AV_RB32(start)) {
4695 case VC1_CODE_SEQHDR:
4698 case VC1_CODE_ENTRYPOINT:
4701 case VC1_CODE_SLICE:
4702 trk->vc1_info.slices = 1;
4706 if (!trk->entry && trk->vc1_info.first_packet_seen)
4707 trk->vc1_info.first_frag_written = 1;
4708 if (!trk->entry && !trk->vc1_info.first_frag_written) {
4709 /* First packet in first fragment */
4710 trk->vc1_info.first_packet_seq = seq;
4711 trk->vc1_info.first_packet_entry = entry;
4712 trk->vc1_info.first_packet_seen = 1;
4713 } else if ((seq && !trk->vc1_info.packet_seq) ||
4714 (entry && !trk->vc1_info.packet_entry)) {
4716 for (i = 0; i < trk->entry; i++)
4717 trk->cluster[i].flags &= ~MOV_SYNC_SAMPLE;
4718 trk->has_keyframes = 0;
4720 trk->vc1_info.packet_seq = 1;
4722 trk->vc1_info.packet_entry = 1;
4723 if (!trk->vc1_info.first_frag_written) {
4724 /* First fragment */
4725 if ((!seq || trk->vc1_info.first_packet_seq) &&
4726 (!entry || trk->vc1_info.first_packet_entry)) {
4727 /* First packet had the same headers as this one, readd the
4728 * sync sample flag. */
4729 trk->cluster[0].flags |= MOV_SYNC_SAMPLE;
4730 trk->has_keyframes = 1;
4734 if (trk->vc1_info.packet_seq && trk->vc1_info.packet_entry)
4736 else if (trk->vc1_info.packet_seq)
4738 else if (trk->vc1_info.packet_entry)
4741 trk->cluster[trk->entry].flags |= MOV_SYNC_SAMPLE;
4742 trk->has_keyframes++;
4746 static int mov_flush_fragment_interleaving(AVFormatContext *s, MOVTrack *track)
4748 MOVMuxContext *mov = s->priv_data;
4753 if (!track->mdat_buf)
4755 if (!mov->mdat_buf) {
4756 if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0)
4759 buf_size = avio_close_dyn_buf(track->mdat_buf, &buf);
4760 track->mdat_buf = NULL;
4762 offset = avio_tell(mov->mdat_buf);
4763 avio_write(mov->mdat_buf, buf, buf_size);
4766 for (i = track->entries_flushed; i < track->entry; i++)
4767 track->cluster[i].pos += offset;
4768 track->entries_flushed = track->entry;
4772 static int mov_flush_fragment(AVFormatContext *s, int force)
4774 MOVMuxContext *mov = s->priv_data;
4775 int i, first_track = -1;
4776 int64_t mdat_size = 0;
4778 int has_video = 0, starts_with_key = 0, first_video_track = 1;
4780 if (!(mov->flags & FF_MOV_FLAG_FRAGMENT))
4783 // Try to fill in the duration of the last packet in each stream
4784 // from queued packets in the interleave queues. If the flushing
4785 // of fragments was triggered automatically by an AVPacket, we
4786 // already have reliable info for the end of that track, but other
4787 // tracks may need to be filled in.
4788 for (i = 0; i < s->nb_streams; i++) {
4789 MOVTrack *track = &mov->tracks[i];
4790 if (!track->end_reliable) {
4792 if (!ff_interleaved_peek(s, i, &pkt, 1)) {
4793 track->track_duration = pkt.dts - track->start_dts;
4794 if (pkt.pts != AV_NOPTS_VALUE)
4795 track->end_pts = pkt.pts;
4797 track->end_pts = pkt.dts;
4802 for (i = 0; i < mov->nb_streams; i++) {
4803 MOVTrack *track = &mov->tracks[i];
4804 if (track->entry <= 1)
4806 // Sample durations are calculated as the diff of dts values,
4807 // but for the last sample in a fragment, we don't know the dts
4808 // of the first sample in the next fragment, so we have to rely
4809 // on what was set as duration in the AVPacket. Not all callers
4810 // set this though, so we might want to replace it with an
4811 // estimate if it currently is zero.
4812 if (get_cluster_duration(track, track->entry - 1) != 0)
4814 // Use the duration (i.e. dts diff) of the second last sample for
4815 // the last one. This is a wild guess (and fatal if it turns out
4816 // to be too long), but probably the best we can do - having a zero
4817 // duration is bad as well.
4818 track->track_duration += get_cluster_duration(track, track->entry - 2);
4819 track->end_pts += get_cluster_duration(track, track->entry - 2);
4820 if (!mov->missing_duration_warned) {
4821 av_log(s, AV_LOG_WARNING,
4822 "Estimating the duration of the last packet in a "
4823 "fragment, consider setting the duration field in "
4824 "AVPacket instead.\n");
4825 mov->missing_duration_warned = 1;
4829 if (!mov->moov_written) {
4830 int64_t pos = avio_tell(s->pb);
4832 int buf_size, moov_size;
4834 for (i = 0; i < mov->nb_streams; i++)
4835 if (!mov->tracks[i].entry)
4837 /* Don't write the initial moov unless all tracks have data */
4838 if (i < mov->nb_streams && !force)
4841 moov_size = get_moov_size(s);
4842 for (i = 0; i < mov->nb_streams; i++)
4843 mov->tracks[i].data_offset = pos + moov_size + 8;
4845 avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_HEADER);
4846 if (mov->flags & FF_MOV_FLAG_DELAY_MOOV)
4847 mov_write_identification(s->pb, s);
4848 if ((ret = mov_write_moov_tag(s->pb, mov, s)) < 0)
4851 if (mov->flags & FF_MOV_FLAG_DELAY_MOOV) {
4852 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
4853 mov->reserved_header_pos = avio_tell(s->pb);
4855 mov->moov_written = 1;
4859 buf_size = avio_close_dyn_buf(mov->mdat_buf, &buf);
4860 mov->mdat_buf = NULL;
4861 avio_wb32(s->pb, buf_size + 8);
4862 ffio_wfourcc(s->pb, "mdat");
4863 avio_write(s->pb, buf, buf_size);
4866 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
4867 mov->reserved_header_pos = avio_tell(s->pb);
4869 mov->moov_written = 1;
4871 for (i = 0; i < mov->nb_streams; i++) {
4872 if (mov->tracks[i].entry)
4873 mov->tracks[i].frag_start += mov->tracks[i].start_dts +
4874 mov->tracks[i].track_duration -
4875 mov->tracks[i].cluster[0].dts;
4876 mov->tracks[i].entry = 0;
4877 mov->tracks[i].end_reliable = 0;
4883 if (mov->frag_interleave) {
4884 for (i = 0; i < mov->nb_streams; i++) {
4885 MOVTrack *track = &mov->tracks[i];
4887 if ((ret = mov_flush_fragment_interleaving(s, track)) < 0)
4893 mdat_size = avio_tell(mov->mdat_buf);
4896 for (i = 0; i < mov->nb_streams; i++) {
4897 MOVTrack *track = &mov->tracks[i];
4898 if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF || mov->frag_interleave)
4899 track->data_offset = 0;
4901 track->data_offset = mdat_size;
4902 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
4904 if (first_video_track) {
4906 starts_with_key = track->cluster[0].flags & MOV_SYNC_SAMPLE;
4907 first_video_track = 0;
4912 if (track->mdat_buf)
4913 mdat_size += avio_tell(track->mdat_buf);
4914 if (first_track < 0)
4921 avio_write_marker(s->pb,
4922 av_rescale(mov->tracks[first_track].cluster[0].dts, AV_TIME_BASE, mov->tracks[first_track].timescale),
4923 (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);
4925 for (i = 0; i < mov->nb_streams; i++) {
4926 MOVTrack *track = &mov->tracks[i];
4927 int buf_size, write_moof = 1, moof_tracks = -1;
4929 int64_t duration = 0;
4932 duration = track->start_dts + track->track_duration -
4933 track->cluster[0].dts;
4934 if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF) {
4935 if (!track->mdat_buf)
4937 mdat_size = avio_tell(track->mdat_buf);
4940 write_moof = i == first_track;
4946 mov_write_moof_tag(s->pb, mov, moof_tracks, mdat_size);
4949 avio_wb32(s->pb, mdat_size + 8);
4950 ffio_wfourcc(s->pb, "mdat");
4954 track->frag_start += duration;
4956 track->entries_flushed = 0;
4957 track->end_reliable = 0;
4958 if (!mov->frag_interleave) {
4959 if (!track->mdat_buf)
4961 buf_size = avio_close_dyn_buf(track->mdat_buf, &buf);
4962 track->mdat_buf = NULL;
4966 buf_size = avio_close_dyn_buf(mov->mdat_buf, &buf);
4967 mov->mdat_buf = NULL;
4970 avio_write(s->pb, buf, buf_size);
4980 static int mov_auto_flush_fragment(AVFormatContext *s, int force)
4982 MOVMuxContext *mov = s->priv_data;
4983 int had_moov = mov->moov_written;
4984 int ret = mov_flush_fragment(s, force);
4987 // If using delay_moov, the first flush only wrote the moov,
4988 // not the actual moof+mdat pair, thus flush once again.
4989 if (!had_moov && mov->flags & FF_MOV_FLAG_DELAY_MOOV)
4990 ret = mov_flush_fragment(s, force);
4994 static int check_pkt(AVFormatContext *s, AVPacket *pkt)
4996 MOVMuxContext *mov = s->priv_data;
4997 MOVTrack *trk = &mov->tracks[pkt->stream_index];
5002 ref = trk->cluster[trk->entry - 1].dts;
5003 } else if ( trk->start_dts != AV_NOPTS_VALUE
5004 && !trk->frag_discont) {
5005 ref = trk->start_dts + trk->track_duration;
5007 ref = pkt->dts; // Skip tests for the first packet
5009 duration = pkt->dts - ref;
5010 if (pkt->dts < ref || duration >= INT_MAX) {
5011 av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" / timestamp: %"PRId64" is out of range for mov/mp4 format\n",
5016 pkt->pts = AV_NOPTS_VALUE;
5019 if (pkt->duration < 0 || pkt->duration > INT_MAX) {
5020 av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" is invalid\n", pkt->duration);
5021 return AVERROR(EINVAL);
5026 int ff_mov_write_packet(AVFormatContext *s, AVPacket *pkt)
5028 MOVMuxContext *mov = s->priv_data;
5029 AVIOContext *pb = s->pb;
5030 MOVTrack *trk = &mov->tracks[pkt->stream_index];
5031 AVCodecParameters *par = trk->par;
5032 unsigned int samples_in_chunk = 0;
5033 int size = pkt->size, ret = 0;
5034 uint8_t *reformatted_data = NULL;
5036 ret = check_pkt(s, pkt);
5040 if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
5042 if (mov->moov_written || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
5043 if (mov->frag_interleave && mov->fragments > 0) {
5044 if (trk->entry - trk->entries_flushed >= mov->frag_interleave) {
5045 if ((ret = mov_flush_fragment_interleaving(s, trk)) < 0)
5050 if (!trk->mdat_buf) {
5051 if ((ret = avio_open_dyn_buf(&trk->mdat_buf)) < 0)
5056 if (!mov->mdat_buf) {
5057 if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0)
5064 if (par->codec_id == AV_CODEC_ID_AMR_NB) {
5065 /* We must find out how many AMR blocks there are in one packet */
5066 static const uint16_t packed_size[16] =
5067 {13, 14, 16, 18, 20, 21, 27, 32, 6, 0, 0, 0, 0, 0, 0, 1};
5070 while (len < size && samples_in_chunk < 100) {
5071 len += packed_size[(pkt->data[len] >> 3) & 0x0F];
5074 if (samples_in_chunk > 1) {
5075 av_log(s, AV_LOG_ERROR, "fatal error, input is not a single packet, implement a AVParser for it\n");
5078 } else if (par->codec_id == AV_CODEC_ID_ADPCM_MS ||
5079 par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) {
5080 samples_in_chunk = trk->par->frame_size;
5081 } else if (trk->sample_size)
5082 samples_in_chunk = size / trk->sample_size;
5084 samples_in_chunk = 1;
5086 /* copy extradata if it exists */
5087 if (trk->vos_len == 0 && par->extradata_size > 0 &&
5088 !TAG_IS_AVCI(trk->tag) &&
5089 (par->codec_id != AV_CODEC_ID_DNXHD)) {
5090 trk->vos_len = par->extradata_size;
5091 trk->vos_data = av_malloc(trk->vos_len);
5092 if (!trk->vos_data) {
5093 ret = AVERROR(ENOMEM);
5096 memcpy(trk->vos_data, par->extradata, trk->vos_len);
5099 if (par->codec_id == AV_CODEC_ID_AAC && pkt->size > 2 &&
5100 (AV_RB16(pkt->data) & 0xfff0) == 0xfff0) {
5101 if (!s->streams[pkt->stream_index]->nb_frames) {
5102 av_log(s, AV_LOG_ERROR, "Malformed AAC bitstream detected: "
5103 "use the audio bitstream filter 'aac_adtstoasc' to fix it "
5104 "('-bsf:a aac_adtstoasc' option with ffmpeg)\n");
5107 av_log(s, AV_LOG_WARNING, "aac bitstream error\n");
5109 if (par->codec_id == AV_CODEC_ID_H264 && trk->vos_len > 0 && *(uint8_t *)trk->vos_data != 1 && !TAG_IS_AVCI(trk->tag)) {
5110 /* from x264 or from bytestream H.264 */
5111 /* NAL reformatting needed */
5112 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
5113 ff_avc_parse_nal_units_buf(pkt->data, &reformatted_data,
5115 avio_write(pb, reformatted_data, size);
5117 if (mov->encryption_scheme == MOV_ENC_CENC_AES_CTR) {
5118 size = ff_mov_cenc_avc_parse_nal_units(&trk->cenc, pb, pkt->data, size);
5124 size = ff_avc_parse_nal_units(pb, pkt->data, pkt->size);
5127 } else if (par->codec_id == AV_CODEC_ID_HEVC && trk->vos_len > 6 &&
5128 (AV_RB24(trk->vos_data) == 1 || AV_RB32(trk->vos_data) == 1)) {
5129 /* extradata is Annex B, assume the bitstream is too and convert it */
5130 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
5131 ff_hevc_annexb2mp4_buf(pkt->data, &reformatted_data, &size, 0, NULL);
5132 avio_write(pb, reformatted_data, size);
5134 size = ff_hevc_annexb2mp4(pb, pkt->data, pkt->size, 0, NULL);
5136 #if CONFIG_AC3_PARSER
5137 } else if (par->codec_id == AV_CODEC_ID_EAC3) {
5138 size = handle_eac3(mov, pkt, trk);
5143 avio_write(pb, pkt->data, size);
5146 if (mov->encryption_scheme == MOV_ENC_CENC_AES_CTR) {
5147 if (par->codec_id == AV_CODEC_ID_H264 && par->extradata_size > 4) {
5148 int nal_size_length = (par->extradata[4] & 0x3) + 1;
5149 ret = ff_mov_cenc_avc_write_nal_units(s, &trk->cenc, nal_size_length, pb, pkt->data, size);
5151 ret = ff_mov_cenc_write_packet(&trk->cenc, pb, pkt->data, size);
5158 avio_write(pb, pkt->data, size);
5162 if ((par->codec_id == AV_CODEC_ID_DNXHD ||
5163 par->codec_id == AV_CODEC_ID_AC3) && !trk->vos_len) {
5164 /* copy frame to create needed atoms */
5165 trk->vos_len = size;
5166 trk->vos_data = av_malloc(size);
5167 if (!trk->vos_data) {
5168 ret = AVERROR(ENOMEM);
5171 memcpy(trk->vos_data, pkt->data, size);
5174 if (trk->entry >= trk->cluster_capacity) {
5175 unsigned new_capacity = 2 * (trk->entry + MOV_INDEX_CLUSTER_SIZE);
5176 if (av_reallocp_array(&trk->cluster, new_capacity,
5177 sizeof(*trk->cluster))) {
5178 ret = AVERROR(ENOMEM);
5181 trk->cluster_capacity = new_capacity;
5184 trk->cluster[trk->entry].pos = avio_tell(pb) - size;
5185 trk->cluster[trk->entry].samples_in_chunk = samples_in_chunk;
5186 trk->cluster[trk->entry].chunkNum = 0;
5187 trk->cluster[trk->entry].size = size;
5188 trk->cluster[trk->entry].entries = samples_in_chunk;
5189 trk->cluster[trk->entry].dts = pkt->dts;
5190 if (!trk->entry && trk->start_dts != AV_NOPTS_VALUE) {
5191 if (!trk->frag_discont) {
5192 /* First packet of a new fragment. We already wrote the duration
5193 * of the last packet of the previous fragment based on track_duration,
5194 * which might not exactly match our dts. Therefore adjust the dts
5195 * of this packet to be what the previous packets duration implies. */
5196 trk->cluster[trk->entry].dts = trk->start_dts + trk->track_duration;
5197 /* We also may have written the pts and the corresponding duration
5198 * in sidx/tfrf/tfxd tags; make sure the sidx pts and duration match up with
5199 * the next fragment. This means the cts of the first sample must
5200 * be the same in all fragments, unless end_pts was updated by
5201 * the packet causing the fragment to be written. */
5202 if ((mov->flags & FF_MOV_FLAG_DASH && !(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)) ||
5203 mov->mode == MODE_ISM)
5204 pkt->pts = pkt->dts + trk->end_pts - trk->cluster[trk->entry].dts;
5206 /* New fragment, but discontinuous from previous fragments.
5207 * Pretend the duration sum of the earlier fragments is
5208 * pkt->dts - trk->start_dts. */
5209 trk->frag_start = pkt->dts - trk->start_dts;
5210 trk->end_pts = AV_NOPTS_VALUE;
5211 trk->frag_discont = 0;
5215 if (!trk->entry && trk->start_dts == AV_NOPTS_VALUE && !mov->use_editlist &&
5216 s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO) {
5217 /* Not using edit lists and shifting the first track to start from zero.
5218 * If the other streams start from a later timestamp, we won't be able
5219 * to signal the difference in starting time without an edit list.
5220 * Thus move the timestamp for this first sample to 0, increasing
5221 * its duration instead. */
5222 trk->cluster[trk->entry].dts = trk->start_dts = 0;
5224 if (trk->start_dts == AV_NOPTS_VALUE) {
5225 trk->start_dts = pkt->dts;
5226 if (trk->frag_discont) {
5227 if (mov->use_editlist) {
5228 /* Pretend the whole stream started at pts=0, with earlier fragments
5229 * already written. If the stream started at pts=0, the duration sum
5230 * of earlier fragments would have been pkt->pts. */
5231 trk->frag_start = pkt->pts;
5232 trk->start_dts = pkt->dts - pkt->pts;
5234 /* Pretend the whole stream started at dts=0, with earlier fragments
5235 * already written, with a duration summing up to pkt->dts. */
5236 trk->frag_start = pkt->dts;
5239 trk->frag_discont = 0;
5240 } else if (pkt->dts && mov->moov_written)
5241 av_log(s, AV_LOG_WARNING,
5242 "Track %d starts with a nonzero dts %"PRId64", while the moov "
5243 "already has been written. Set the delay_moov flag to handle "
5245 pkt->stream_index, pkt->dts);
5247 trk->track_duration = pkt->dts - trk->start_dts + pkt->duration;
5248 trk->last_sample_is_subtitle_end = 0;
5250 if (pkt->pts == AV_NOPTS_VALUE) {
5251 av_log(s, AV_LOG_WARNING, "pts has no value\n");
5252 pkt->pts = pkt->dts;
5254 if (pkt->dts != pkt->pts)
5255 trk->flags |= MOV_TRACK_CTTS;
5256 trk->cluster[trk->entry].cts = pkt->pts - pkt->dts;
5257 trk->cluster[trk->entry].flags = 0;
5258 if (trk->start_cts == AV_NOPTS_VALUE)
5259 trk->start_cts = pkt->pts - pkt->dts;
5260 if (trk->end_pts == AV_NOPTS_VALUE)
5261 trk->end_pts = trk->cluster[trk->entry].dts +
5262 trk->cluster[trk->entry].cts + pkt->duration;
5264 trk->end_pts = FFMAX(trk->end_pts, trk->cluster[trk->entry].dts +
5265 trk->cluster[trk->entry].cts +
5268 if (par->codec_id == AV_CODEC_ID_VC1) {
5269 mov_parse_vc1_frame(pkt, trk);
5270 } else if (pkt->flags & AV_PKT_FLAG_KEY) {
5271 if (mov->mode == MODE_MOV && par->codec_id == AV_CODEC_ID_MPEG2VIDEO &&
5272 trk->entry > 0) { // force sync sample for the first key frame
5273 mov_parse_mpeg2_frame(pkt, &trk->cluster[trk->entry].flags);
5274 if (trk->cluster[trk->entry].flags & MOV_PARTIAL_SYNC_SAMPLE)
5275 trk->flags |= MOV_TRACK_STPS;
5277 trk->cluster[trk->entry].flags = MOV_SYNC_SAMPLE;
5279 if (trk->cluster[trk->entry].flags & MOV_SYNC_SAMPLE)
5280 trk->has_keyframes++;
5283 trk->sample_count += samples_in_chunk;
5284 mov->mdat_size += size;
5286 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams)
5287 ff_mov_add_hinted_packet(s, pkt, trk->hint_track, trk->entry,
5288 reformatted_data, size);
5293 av_free(reformatted_data);
5297 static int mov_write_single_packet(AVFormatContext *s, AVPacket *pkt)
5299 MOVMuxContext *mov = s->priv_data;
5300 MOVTrack *trk = &mov->tracks[pkt->stream_index];
5301 AVCodecParameters *par = trk->par;
5302 int64_t frag_duration = 0;
5303 int size = pkt->size;
5305 int ret = check_pkt(s, pkt);
5309 if (mov->flags & FF_MOV_FLAG_FRAG_DISCONT) {
5311 for (i = 0; i < s->nb_streams; i++)
5312 mov->tracks[i].frag_discont = 1;
5313 mov->flags &= ~FF_MOV_FLAG_FRAG_DISCONT;
5317 if (trk->start_dts == AV_NOPTS_VALUE && trk->frag_discont) {
5318 trk->start_dts = pkt->dts;
5319 if (pkt->pts != AV_NOPTS_VALUE)
5320 trk->start_cts = pkt->pts - pkt->dts;
5325 if (trk->par->codec_id == AV_CODEC_ID_MP4ALS ||
5326 trk->par->codec_id == AV_CODEC_ID_FLAC) {
5328 uint8_t *side = av_packet_get_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA, &side_size);
5329 if (side && side_size > 0 && (side_size != par->extradata_size || memcmp(side, par->extradata, side_size))) {
5330 void *newextra = av_mallocz(side_size + AV_INPUT_BUFFER_PADDING_SIZE);
5332 return AVERROR(ENOMEM);
5333 av_free(par->extradata);
5334 par->extradata = newextra;
5335 memcpy(par->extradata, side, side_size);
5336 par->extradata_size = side_size;
5337 mov->need_rewrite_extradata = 1;
5341 return 0; /* Discard 0 sized packets */
5344 if (trk->entry && pkt->stream_index < s->nb_streams)
5345 frag_duration = av_rescale_q(pkt->dts - trk->cluster[0].dts,
5346 s->streams[pkt->stream_index]->time_base,
5348 if ((mov->max_fragment_duration &&
5349 frag_duration >= mov->max_fragment_duration) ||
5350 (mov->max_fragment_size && mov->mdat_size + size >= mov->max_fragment_size) ||
5351 (mov->flags & FF_MOV_FLAG_FRAG_KEYFRAME &&
5352 par->codec_type == AVMEDIA_TYPE_VIDEO &&
5353 trk->entry && pkt->flags & AV_PKT_FLAG_KEY)) {
5354 if (frag_duration >= mov->min_fragment_duration) {
5355 // Set the duration of this track to line up with the next
5356 // sample in this track. This avoids relying on AVPacket
5357 // duration, but only helps for this particular track, not
5358 // for the other ones that are flushed at the same time.
5359 trk->track_duration = pkt->dts - trk->start_dts;
5360 if (pkt->pts != AV_NOPTS_VALUE)
5361 trk->end_pts = pkt->pts;
5363 trk->end_pts = pkt->dts;
5364 trk->end_reliable = 1;
5365 mov_auto_flush_fragment(s, 0);
5369 return ff_mov_write_packet(s, pkt);
5372 static int mov_write_subtitle_end_packet(AVFormatContext *s,
5376 uint8_t data[2] = {0};
5379 av_init_packet(&end);
5380 end.size = sizeof(data);
5385 end.stream_index = stream_index;
5387 ret = mov_write_single_packet(s, &end);
5388 av_packet_unref(&end);
5393 static int mov_write_packet(AVFormatContext *s, AVPacket *pkt)
5396 mov_flush_fragment(s, 1);
5400 MOVMuxContext *mov = s->priv_data;
5401 MOVTrack *trk = &mov->tracks[pkt->stream_index];
5404 return mov_write_single_packet(s, pkt); /* Passthrough. */
5407 * Subtitles require special handling.
5409 * 1) For full complaince, every track must have a sample at
5410 * dts == 0, which is rarely true for subtitles. So, as soon
5411 * as we see any packet with dts > 0, write an empty subtitle
5412 * at dts == 0 for any subtitle track with no samples in it.
5414 * 2) For each subtitle track, check if the current packet's
5415 * dts is past the duration of the last subtitle sample. If
5416 * so, we now need to write an end sample for that subtitle.
5418 * This must be done conditionally to allow for subtitles that
5419 * immediately replace each other, in which case an end sample
5420 * is not needed, and is, in fact, actively harmful.
5422 * 3) See mov_write_trailer for how the final end sample is
5425 for (i = 0; i < mov->nb_streams; i++) {
5426 MOVTrack *trk = &mov->tracks[i];
5429 if (trk->par->codec_id == AV_CODEC_ID_MOV_TEXT &&
5430 trk->track_duration < pkt->dts &&
5431 (trk->entry == 0 || !trk->last_sample_is_subtitle_end)) {
5432 ret = mov_write_subtitle_end_packet(s, i, trk->track_duration);
5433 if (ret < 0) return ret;
5434 trk->last_sample_is_subtitle_end = 1;
5438 if (trk->mode == MODE_MOV && trk->par->codec_type == AVMEDIA_TYPE_VIDEO) {
5439 AVPacket *opkt = pkt;
5440 int reshuffle_ret, ret;
5441 if (trk->is_unaligned_qt_rgb) {
5442 int64_t bpc = trk->par->bits_per_coded_sample != 15 ? trk->par->bits_per_coded_sample : 16;
5443 int expected_stride = ((trk->par->width * bpc + 15) >> 4)*2;
5444 reshuffle_ret = ff_reshuffle_raw_rgb(s, &pkt, trk->par, expected_stride);
5445 if (reshuffle_ret < 0)
5446 return reshuffle_ret;
5449 if (trk->par->format == AV_PIX_FMT_PAL8 && !trk->pal_done) {
5450 ret = ff_get_packet_palette(s, opkt, reshuffle_ret, trk->palette);
5455 } else if (trk->par->codec_id == AV_CODEC_ID_RAWVIDEO &&
5456 (trk->par->format == AV_PIX_FMT_GRAY8 ||
5457 trk->par->format == AV_PIX_FMT_MONOBLACK)) {
5458 for (i = 0; i < pkt->size; i++)
5459 pkt->data[i] = ~pkt->data[i];
5461 if (reshuffle_ret) {
5462 ret = mov_write_single_packet(s, pkt);
5465 av_packet_free(&pkt);
5470 return mov_write_single_packet(s, pkt);
5474 // QuickTime chapters involve an additional text track with the chapter names
5475 // as samples, and a tref pointing from the other tracks to the chapter one.
5476 static int mov_create_chapter_track(AVFormatContext *s, int tracknum)
5480 MOVMuxContext *mov = s->priv_data;
5481 MOVTrack *track = &mov->tracks[tracknum];
5482 AVPacket pkt = { .stream_index = tracknum, .flags = AV_PKT_FLAG_KEY };
5485 track->mode = mov->mode;
5486 track->tag = MKTAG('t','e','x','t');
5487 track->timescale = MOV_TIMESCALE;
5488 track->par = avcodec_parameters_alloc();
5490 return AVERROR(ENOMEM);
5491 track->par->codec_type = AVMEDIA_TYPE_SUBTITLE;
5493 // These properties are required to make QT recognize the chapter track
5494 uint8_t chapter_properties[43] = { 0, 0, 0, 0, 0, 0, 0, 1, };
5495 if (ff_alloc_extradata(track->par, sizeof(chapter_properties)))
5496 return AVERROR(ENOMEM);
5497 memcpy(track->par->extradata, chapter_properties, sizeof(chapter_properties));
5499 if (avio_open_dyn_buf(&pb) >= 0) {
5503 /* Stub header (usually for Quicktime chapter track) */
5505 avio_wb32(pb, 0x01); // displayFlags
5506 avio_w8(pb, 0x00); // horizontal justification
5507 avio_w8(pb, 0x00); // vertical justification
5508 avio_w8(pb, 0x00); // bgColourRed
5509 avio_w8(pb, 0x00); // bgColourGreen
5510 avio_w8(pb, 0x00); // bgColourBlue
5511 avio_w8(pb, 0x00); // bgColourAlpha
5513 avio_wb16(pb, 0x00); // defTextBoxTop
5514 avio_wb16(pb, 0x00); // defTextBoxLeft
5515 avio_wb16(pb, 0x00); // defTextBoxBottom
5516 avio_wb16(pb, 0x00); // defTextBoxRight
5518 avio_wb16(pb, 0x00); // startChar
5519 avio_wb16(pb, 0x00); // endChar
5520 avio_wb16(pb, 0x01); // fontID
5521 avio_w8(pb, 0x00); // fontStyleFlags
5522 avio_w8(pb, 0x00); // fontSize
5523 avio_w8(pb, 0x00); // fgColourRed
5524 avio_w8(pb, 0x00); // fgColourGreen
5525 avio_w8(pb, 0x00); // fgColourBlue
5526 avio_w8(pb, 0x00); // fgColourAlpha
5528 avio_wb32(pb, 0x0D); // box size
5529 ffio_wfourcc(pb, "ftab"); // box atom name
5530 avio_wb16(pb, 0x01); // entry count
5532 avio_wb16(pb, 0x01); // font ID
5533 avio_w8(pb, 0x00); // font name length
5535 if ((size = avio_close_dyn_buf(pb, &buf)) > 0) {
5536 track->par->extradata = buf;
5537 track->par->extradata_size = size;
5544 for (i = 0; i < s->nb_chapters; i++) {
5545 AVChapter *c = s->chapters[i];
5546 AVDictionaryEntry *t;
5548 int64_t end = av_rescale_q(c->end, c->time_base, (AVRational){1,MOV_TIMESCALE});
5549 pkt.pts = pkt.dts = av_rescale_q(c->start, c->time_base, (AVRational){1,MOV_TIMESCALE});
5550 pkt.duration = end - pkt.dts;
5552 if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
5553 static const char encd[12] = {
5554 0x00, 0x00, 0x00, 0x0C,
5556 0x00, 0x00, 0x01, 0x00 };
5557 len = strlen(t->value);
5558 pkt.size = len + 2 + 12;
5559 pkt.data = av_malloc(pkt.size);
5561 return AVERROR(ENOMEM);
5562 AV_WB16(pkt.data, len);
5563 memcpy(pkt.data + 2, t->value, len);
5564 memcpy(pkt.data + len + 2, encd, sizeof(encd));
5565 ff_mov_write_packet(s, &pkt);
5566 av_freep(&pkt.data);
5574 static int mov_check_timecode_track(AVFormatContext *s, AVTimecode *tc, int src_index, const char *tcstr)
5578 /* compute the frame number */
5579 ret = av_timecode_init_from_string(tc, find_fps(s, s->streams[src_index]), tcstr, s);
5583 static int mov_create_timecode_track(AVFormatContext *s, int index, int src_index, AVTimecode tc)
5586 MOVMuxContext *mov = s->priv_data;
5587 MOVTrack *track = &mov->tracks[index];
5588 AVStream *src_st = s->streams[src_index];
5589 AVPacket pkt = {.stream_index = index, .flags = AV_PKT_FLAG_KEY, .size = 4};
5590 AVRational rate = find_fps(s, src_st);
5592 /* tmcd track based on video stream */
5593 track->mode = mov->mode;
5594 track->tag = MKTAG('t','m','c','d');
5595 track->src_track = src_index;
5596 track->timescale = mov->tracks[src_index].timescale;
5597 if (tc.flags & AV_TIMECODE_FLAG_DROPFRAME)
5598 track->timecode_flags |= MOV_TIMECODE_FLAG_DROPFRAME;
5600 /* set st to src_st for metadata access*/
5603 /* encode context: tmcd data stream */
5604 track->par = avcodec_parameters_alloc();
5606 return AVERROR(ENOMEM);
5607 track->par->codec_type = AVMEDIA_TYPE_DATA;
5608 track->par->codec_tag = track->tag;
5609 track->st->avg_frame_rate = av_inv_q(rate);
5611 /* the tmcd track just contains one packet with the frame number */
5612 pkt.data = av_malloc(pkt.size);
5614 return AVERROR(ENOMEM);
5615 AV_WB32(pkt.data, tc.start);
5616 ret = ff_mov_write_packet(s, &pkt);
5622 * st->disposition controls the "enabled" flag in the tkhd tag.
5623 * QuickTime will not play a track if it is not enabled. So make sure
5624 * that one track of each type (audio, video, subtitle) is enabled.
5626 * Subtitles are special. For audio and video, setting "enabled" also
5627 * makes the track "default" (i.e. it is rendered when played). For
5628 * subtitles, an "enabled" subtitle is not rendered by default, but
5629 * if no subtitle is enabled, the subtitle menu in QuickTime will be
5632 static void enable_tracks(AVFormatContext *s)
5634 MOVMuxContext *mov = s->priv_data;
5636 int enabled[AVMEDIA_TYPE_NB];
5637 int first[AVMEDIA_TYPE_NB];
5639 for (i = 0; i < AVMEDIA_TYPE_NB; i++) {
5644 for (i = 0; i < s->nb_streams; i++) {
5645 AVStream *st = s->streams[i];
5647 if (st->codecpar->codec_type <= AVMEDIA_TYPE_UNKNOWN ||
5648 st->codecpar->codec_type >= AVMEDIA_TYPE_NB)
5651 if (first[st->codecpar->codec_type] < 0)
5652 first[st->codecpar->codec_type] = i;
5653 if (st->disposition & AV_DISPOSITION_DEFAULT) {
5654 mov->tracks[i].flags |= MOV_TRACK_ENABLED;
5655 enabled[st->codecpar->codec_type]++;
5659 for (i = 0; i < AVMEDIA_TYPE_NB; i++) {
5661 case AVMEDIA_TYPE_VIDEO:
5662 case AVMEDIA_TYPE_AUDIO:
5663 case AVMEDIA_TYPE_SUBTITLE:
5665 mov->per_stream_grouping = 1;
5666 if (!enabled[i] && first[i] >= 0)
5667 mov->tracks[first[i]].flags |= MOV_TRACK_ENABLED;
5673 static void mov_free(AVFormatContext *s)
5675 MOVMuxContext *mov = s->priv_data;
5678 if (mov->chapter_track) {
5679 if (mov->tracks[mov->chapter_track].par)
5680 av_freep(&mov->tracks[mov->chapter_track].par->extradata);
5681 av_freep(&mov->tracks[mov->chapter_track].par);
5684 for (i = 0; i < mov->nb_streams; i++) {
5685 if (mov->tracks[i].tag == MKTAG('r','t','p',' '))
5686 ff_mov_close_hinting(&mov->tracks[i]);
5687 else if (mov->tracks[i].tag == MKTAG('t','m','c','d') && mov->nb_meta_tmcd)
5688 av_freep(&mov->tracks[i].par);
5689 av_freep(&mov->tracks[i].cluster);
5690 av_freep(&mov->tracks[i].frag_info);
5692 if (mov->tracks[i].vos_len)
5693 av_freep(&mov->tracks[i].vos_data);
5695 ff_mov_cenc_free(&mov->tracks[i].cenc);
5698 av_freep(&mov->tracks);
5701 static uint32_t rgb_to_yuv(uint32_t rgb)
5706 r = (rgb >> 16) & 0xFF;
5707 g = (rgb >> 8) & 0xFF;
5710 y = av_clip_uint8(( 16000 + 257 * r + 504 * g + 98 * b)/1000);
5711 cb = av_clip_uint8((128000 - 148 * r - 291 * g + 439 * b)/1000);
5712 cr = av_clip_uint8((128000 + 439 * r - 368 * g - 71 * b)/1000);
5714 return (y << 16) | (cr << 8) | cb;
5717 static int mov_create_dvd_sub_decoder_specific_info(MOVTrack *track,
5720 int i, width = 720, height = 480;
5721 int have_palette = 0, have_size = 0;
5722 uint32_t palette[16];
5723 char *cur = st->codecpar->extradata;
5725 while (cur && *cur) {
5726 if (strncmp("palette:", cur, 8) == 0) {
5728 count = sscanf(cur + 8,
5729 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
5730 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
5731 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
5732 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32"",
5733 &palette[ 0], &palette[ 1], &palette[ 2], &palette[ 3],
5734 &palette[ 4], &palette[ 5], &palette[ 6], &palette[ 7],
5735 &palette[ 8], &palette[ 9], &palette[10], &palette[11],
5736 &palette[12], &palette[13], &palette[14], &palette[15]);
5738 for (i = 0; i < count; i++) {
5739 palette[i] = rgb_to_yuv(palette[i]);
5742 } else if (!strncmp("size:", cur, 5)) {
5743 sscanf(cur + 5, "%dx%d", &width, &height);
5746 if (have_palette && have_size)
5748 cur += strcspn(cur, "\n\r");
5749 cur += strspn(cur, "\n\r");
5752 track->vos_data = av_malloc(16*4);
5753 if (!track->vos_data)
5754 return AVERROR(ENOMEM);
5755 for (i = 0; i < 16; i++) {
5756 AV_WB32(track->vos_data + i * 4, palette[i]);
5758 track->vos_len = 16 * 4;
5760 st->codecpar->width = width;
5761 st->codecpar->height = track->height = height;
5766 static int mov_init(AVFormatContext *s)
5768 MOVMuxContext *mov = s->priv_data;
5769 AVDictionaryEntry *global_tcr = av_dict_get(s->metadata, "timecode", NULL, 0);
5774 /* Default mode == MP4 */
5775 mov->mode = MODE_MP4;
5778 if (!strcmp("3gp", s->oformat->name)) mov->mode = MODE_3GP;
5779 else if (!strcmp("3g2", s->oformat->name)) mov->mode = MODE_3GP|MODE_3G2;
5780 else if (!strcmp("mov", s->oformat->name)) mov->mode = MODE_MOV;
5781 else if (!strcmp("psp", s->oformat->name)) mov->mode = MODE_PSP;
5782 else if (!strcmp("ipod",s->oformat->name)) mov->mode = MODE_IPOD;
5783 else if (!strcmp("ismv",s->oformat->name)) mov->mode = MODE_ISM;
5784 else if (!strcmp("f4v", s->oformat->name)) mov->mode = MODE_F4V;
5787 if (mov->flags & FF_MOV_FLAG_DELAY_MOOV)
5788 mov->flags |= FF_MOV_FLAG_EMPTY_MOOV;
5790 /* Set the FRAGMENT flag if any of the fragmentation methods are
5792 if (mov->max_fragment_duration || mov->max_fragment_size ||
5793 mov->flags & (FF_MOV_FLAG_EMPTY_MOOV |
5794 FF_MOV_FLAG_FRAG_KEYFRAME |
5795 FF_MOV_FLAG_FRAG_CUSTOM))
5796 mov->flags |= FF_MOV_FLAG_FRAGMENT;
5798 /* Set other implicit flags immediately */
5799 if (mov->mode == MODE_ISM)
5800 mov->flags |= FF_MOV_FLAG_EMPTY_MOOV | FF_MOV_FLAG_SEPARATE_MOOF |
5801 FF_MOV_FLAG_FRAGMENT;
5802 if (mov->flags & FF_MOV_FLAG_DASH)
5803 mov->flags |= FF_MOV_FLAG_FRAGMENT | FF_MOV_FLAG_EMPTY_MOOV |
5804 FF_MOV_FLAG_DEFAULT_BASE_MOOF;
5806 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV && s->flags & AVFMT_FLAG_AUTO_BSF) {
5807 av_log(s, AV_LOG_VERBOSE, "Empty MOOV enabled; disabling automatic bitstream filtering\n");
5808 s->flags &= ~AVFMT_FLAG_AUTO_BSF;
5811 if (mov->flags & FF_MOV_FLAG_FASTSTART) {
5812 mov->reserved_moov_size = -1;
5815 if (mov->use_editlist < 0) {
5816 mov->use_editlist = 1;
5817 if (mov->flags & FF_MOV_FLAG_FRAGMENT &&
5818 !(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
5819 // If we can avoid needing an edit list by shifting the
5820 // tracks, prefer that over (trying to) write edit lists
5821 // in fragmented output.
5822 if (s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO ||
5823 s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO)
5824 mov->use_editlist = 0;
5827 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV &&
5828 !(mov->flags & FF_MOV_FLAG_DELAY_MOOV) && mov->use_editlist)
5829 av_log(s, AV_LOG_WARNING, "No meaningful edit list will be written when using empty_moov without delay_moov\n");
5831 if (!mov->use_editlist && s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO)
5832 s->avoid_negative_ts = AVFMT_AVOID_NEG_TS_MAKE_ZERO;
5834 /* Clear the omit_tfhd_offset flag if default_base_moof is set;
5835 * if the latter is set that's enough and omit_tfhd_offset doesn't
5836 * add anything extra on top of that. */
5837 if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET &&
5838 mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)
5839 mov->flags &= ~FF_MOV_FLAG_OMIT_TFHD_OFFSET;
5841 if (mov->frag_interleave &&
5842 mov->flags & (FF_MOV_FLAG_OMIT_TFHD_OFFSET | FF_MOV_FLAG_SEPARATE_MOOF)) {
5843 av_log(s, AV_LOG_ERROR,
5844 "Sample interleaving in fragments is mutually exclusive with "
5845 "omit_tfhd_offset and separate_moof\n");
5846 return AVERROR(EINVAL);
5849 /* Non-seekable output is ok if using fragmentation. If ism_lookahead
5850 * is enabled, we don't support non-seekable output at all. */
5851 if (!(s->pb->seekable & AVIO_SEEKABLE_NORMAL) &&
5852 (!(mov->flags & FF_MOV_FLAG_FRAGMENT) || mov->ism_lookahead)) {
5853 av_log(s, AV_LOG_ERROR, "muxer does not support non seekable output\n");
5854 return AVERROR(EINVAL);
5857 mov->nb_streams = s->nb_streams;
5858 if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters)
5859 mov->chapter_track = mov->nb_streams++;
5861 if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
5862 /* Add hint tracks for each audio and video stream */
5863 for (i = 0; i < s->nb_streams; i++) {
5864 AVStream *st = s->streams[i];
5865 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ||
5866 st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
5872 if ( mov->write_tmcd == -1 && (mov->mode == MODE_MOV || mov->mode == MODE_MP4)
5873 || mov->write_tmcd == 1) {
5874 /* +1 tmcd track for each video stream with a timecode */
5875 for (i = 0; i < s->nb_streams; i++) {
5876 AVStream *st = s->streams[i];
5877 AVDictionaryEntry *t = global_tcr;
5878 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
5879 (t || (t=av_dict_get(st->metadata, "timecode", NULL, 0)))) {
5881 ret = mov_check_timecode_track(s, &tc, i, t->value);
5883 mov->nb_meta_tmcd++;
5887 /* check if there is already a tmcd track to remux */
5888 if (mov->nb_meta_tmcd) {
5889 for (i = 0; i < s->nb_streams; i++) {
5890 AVStream *st = s->streams[i];
5891 if (st->codecpar->codec_tag == MKTAG('t','m','c','d')) {
5892 av_log(s, AV_LOG_WARNING, "You requested a copy of the original timecode track "
5893 "so timecode metadata are now ignored\n");
5894 mov->nb_meta_tmcd = 0;
5899 mov->nb_streams += mov->nb_meta_tmcd;
5902 // Reserve an extra stream for chapters for the case where chapters
5903 // are written in the trailer
5904 mov->tracks = av_mallocz_array((mov->nb_streams + 1), sizeof(*mov->tracks));
5906 return AVERROR(ENOMEM);
5908 if (mov->encryption_scheme_str != NULL && strcmp(mov->encryption_scheme_str, "none") != 0) {
5909 if (strcmp(mov->encryption_scheme_str, "cenc-aes-ctr") == 0) {
5910 mov->encryption_scheme = MOV_ENC_CENC_AES_CTR;
5912 if (mov->encryption_key_len != AES_CTR_KEY_SIZE) {
5913 av_log(s, AV_LOG_ERROR, "Invalid encryption key len %d expected %d\n",
5914 mov->encryption_key_len, AES_CTR_KEY_SIZE);
5915 return AVERROR(EINVAL);
5918 if (mov->encryption_kid_len != CENC_KID_SIZE) {
5919 av_log(s, AV_LOG_ERROR, "Invalid encryption kid len %d expected %d\n",
5920 mov->encryption_kid_len, CENC_KID_SIZE);
5921 return AVERROR(EINVAL);
5924 av_log(s, AV_LOG_ERROR, "unsupported encryption scheme %s\n",
5925 mov->encryption_scheme_str);
5926 return AVERROR(EINVAL);
5930 for (i = 0; i < s->nb_streams; i++) {
5931 AVStream *st= s->streams[i];
5932 MOVTrack *track= &mov->tracks[i];
5933 AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0);
5936 track->par = st->codecpar;
5937 track->language = ff_mov_iso639_to_lang(lang?lang->value:"und", mov->mode!=MODE_MOV);
5938 if (track->language < 0)
5939 track->language = 0;
5940 track->mode = mov->mode;
5941 track->tag = mov_find_codec_tag(s, track);
5943 av_log(s, AV_LOG_ERROR, "Could not find tag for codec %s in stream #%d, "
5944 "codec not currently supported in container\n",
5945 avcodec_get_name(st->codecpar->codec_id), i);
5946 return AVERROR(EINVAL);
5948 /* If hinting of this track is enabled by a later hint track,
5949 * this is updated. */
5950 track->hint_track = -1;
5951 track->start_dts = AV_NOPTS_VALUE;
5952 track->start_cts = AV_NOPTS_VALUE;
5953 track->end_pts = AV_NOPTS_VALUE;
5954 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
5955 if (track->tag == MKTAG('m','x','3','p') || track->tag == MKTAG('m','x','3','n') ||
5956 track->tag == MKTAG('m','x','4','p') || track->tag == MKTAG('m','x','4','n') ||
5957 track->tag == MKTAG('m','x','5','p') || track->tag == MKTAG('m','x','5','n')) {
5958 if (st->codecpar->width != 720 || (st->codecpar->height != 608 && st->codecpar->height != 512)) {
5959 av_log(s, AV_LOG_ERROR, "D-10/IMX must use 720x608 or 720x512 video resolution\n");
5960 return AVERROR(EINVAL);
5962 track->height = track->tag >> 24 == 'n' ? 486 : 576;
5964 if (mov->video_track_timescale) {
5965 track->timescale = mov->video_track_timescale;
5967 track->timescale = st->time_base.den;
5968 while(track->timescale < 10000)
5969 track->timescale *= 2;
5971 if (st->codecpar->width > 65535 || st->codecpar->height > 65535) {
5972 av_log(s, AV_LOG_ERROR, "Resolution %dx%d too large for mov/mp4\n", st->codecpar->width, st->codecpar->height);
5973 return AVERROR(EINVAL);
5975 if (track->mode == MODE_MOV && track->timescale > 100000)
5976 av_log(s, AV_LOG_WARNING,
5977 "WARNING codec timebase is very high. If duration is too long,\n"
5978 "file may not be playable by quicktime. Specify a shorter timebase\n"
5979 "or choose different container.\n");
5980 if (track->mode == MODE_MOV &&
5981 track->par->codec_id == AV_CODEC_ID_RAWVIDEO &&
5982 track->tag == MKTAG('r','a','w',' ')) {
5983 enum AVPixelFormat pix_fmt = track->par->format;
5984 if (pix_fmt == AV_PIX_FMT_NONE && track->par->bits_per_coded_sample == 1)
5985 pix_fmt = AV_PIX_FMT_MONOWHITE;
5986 track->is_unaligned_qt_rgb =
5987 pix_fmt == AV_PIX_FMT_RGB24 ||
5988 pix_fmt == AV_PIX_FMT_BGR24 ||
5989 pix_fmt == AV_PIX_FMT_PAL8 ||
5990 pix_fmt == AV_PIX_FMT_GRAY8 ||
5991 pix_fmt == AV_PIX_FMT_MONOWHITE ||
5992 pix_fmt == AV_PIX_FMT_MONOBLACK;
5994 if (track->par->codec_id == AV_CODEC_ID_VP9) {
5995 if (track->mode != MODE_MP4) {
5996 av_log(s, AV_LOG_ERROR, "VP9 only supported in MP4.\n");
5997 return AVERROR(EINVAL);
6000 } else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
6001 track->timescale = st->codecpar->sample_rate;
6002 if (!st->codecpar->frame_size && !av_get_bits_per_sample(st->codecpar->codec_id)) {
6003 av_log(s, AV_LOG_WARNING, "track %d: codec frame size is not set\n", i);
6004 track->audio_vbr = 1;
6005 }else if (st->codecpar->codec_id == AV_CODEC_ID_ADPCM_MS ||
6006 st->codecpar->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
6007 st->codecpar->codec_id == AV_CODEC_ID_ILBC){
6008 if (!st->codecpar->block_align) {
6009 av_log(s, AV_LOG_ERROR, "track %d: codec block align is not set for adpcm\n", i);
6010 return AVERROR(EINVAL);
6012 track->sample_size = st->codecpar->block_align;
6013 }else if (st->codecpar->frame_size > 1){ /* assume compressed audio */
6014 track->audio_vbr = 1;
6016 track->sample_size = (av_get_bits_per_sample(st->codecpar->codec_id) >> 3) * st->codecpar->channels;
6018 if (st->codecpar->codec_id == AV_CODEC_ID_ILBC ||
6019 st->codecpar->codec_id == AV_CODEC_ID_ADPCM_IMA_QT) {
6020 track->audio_vbr = 1;
6022 if (track->mode != MODE_MOV &&
6023 track->par->codec_id == AV_CODEC_ID_MP3 && track->timescale < 16000) {
6024 if (s->strict_std_compliance >= FF_COMPLIANCE_NORMAL) {
6025 av_log(s, AV_LOG_ERROR, "track %d: muxing mp3 at %dhz is not standard, to mux anyway set strict to -1\n",
6026 i, track->par->sample_rate);
6027 return AVERROR(EINVAL);
6029 av_log(s, AV_LOG_WARNING, "track %d: muxing mp3 at %dhz is not standard in MP4\n",
6030 i, track->par->sample_rate);
6033 if (track->par->codec_id == AV_CODEC_ID_FLAC ||
6034 track->par->codec_id == AV_CODEC_ID_OPUS) {
6035 if (track->mode != MODE_MP4) {
6036 av_log(s, AV_LOG_ERROR, "%s only supported in MP4.\n", avcodec_get_name(track->par->codec_id));
6037 return AVERROR(EINVAL);
6039 if (s->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
6040 av_log(s, AV_LOG_ERROR,
6041 "%s in MP4 support is experimental, add "
6042 "'-strict %d' if you want to use it.\n",
6043 avcodec_get_name(track->par->codec_id), FF_COMPLIANCE_EXPERIMENTAL);
6044 return AVERROR_EXPERIMENTAL;
6047 } else if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) {
6048 track->timescale = st->time_base.den;
6049 } else if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA) {
6050 track->timescale = st->time_base.den;
6052 track->timescale = MOV_TIMESCALE;
6055 track->height = st->codecpar->height;
6056 /* The ism specific timescale isn't mandatory, but is assumed by
6057 * some tools, such as mp4split. */
6058 if (mov->mode == MODE_ISM)
6059 track->timescale = 10000000;
6061 avpriv_set_pts_info(st, 64, 1, track->timescale);
6063 if (mov->encryption_scheme == MOV_ENC_CENC_AES_CTR) {
6064 ret = ff_mov_cenc_init(&track->cenc, mov->encryption_key,
6065 track->par->codec_id == AV_CODEC_ID_H264, s->flags & AVFMT_FLAG_BITEXACT);
6075 static int mov_write_header(AVFormatContext *s)
6077 AVIOContext *pb = s->pb;
6078 MOVMuxContext *mov = s->priv_data;
6079 AVDictionaryEntry *t, *global_tcr = av_dict_get(s->metadata, "timecode", NULL, 0);
6080 int i, ret, hint_track = 0, tmcd_track = 0, nb_tracks = s->nb_streams;
6082 if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters)
6085 if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
6086 /* Add hint tracks for each audio and video stream */
6087 hint_track = nb_tracks;
6088 for (i = 0; i < s->nb_streams; i++) {
6089 AVStream *st = s->streams[i];
6090 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ||
6091 st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
6097 if (mov->mode == MODE_MOV || mov->mode == MODE_MP4)
6098 tmcd_track = nb_tracks;
6100 for (i = 0; i < s->nb_streams; i++) {
6102 AVStream *st= s->streams[i];
6103 MOVTrack *track= &mov->tracks[i];
6105 /* copy extradata if it exists */
6106 if (st->codecpar->extradata_size) {
6107 if (st->codecpar->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
6108 mov_create_dvd_sub_decoder_specific_info(track, st);
6109 else if (!TAG_IS_AVCI(track->tag) && st->codecpar->codec_id != AV_CODEC_ID_DNXHD) {
6110 track->vos_len = st->codecpar->extradata_size;
6111 track->vos_data = av_malloc(track->vos_len);
6112 if (!track->vos_data) {
6113 return AVERROR(ENOMEM);
6115 memcpy(track->vos_data, st->codecpar->extradata, track->vos_len);
6119 if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ||
6120 track->par->channel_layout != AV_CH_LAYOUT_MONO)
6123 for (j = 0; j < s->nb_streams; j++) {
6124 AVStream *stj= s->streams[j];
6125 MOVTrack *trackj= &mov->tracks[j];
6129 if (stj->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ||
6130 trackj->par->channel_layout != AV_CH_LAYOUT_MONO ||
6131 trackj->language != track->language ||
6132 trackj->tag != track->tag
6135 track->multichannel_as_mono++;
6139 if (!(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
6140 if ((ret = mov_write_identification(pb, s)) < 0)
6144 if (mov->reserved_moov_size){
6145 mov->reserved_header_pos = avio_tell(pb);
6146 if (mov->reserved_moov_size > 0)
6147 avio_skip(pb, mov->reserved_moov_size);
6150 if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
6151 /* If no fragmentation options have been set, set a default. */
6152 if (!(mov->flags & (FF_MOV_FLAG_FRAG_KEYFRAME |
6153 FF_MOV_FLAG_FRAG_CUSTOM)) &&
6154 !mov->max_fragment_duration && !mov->max_fragment_size)
6155 mov->flags |= FF_MOV_FLAG_FRAG_KEYFRAME;
6157 if (mov->flags & FF_MOV_FLAG_FASTSTART)
6158 mov->reserved_header_pos = avio_tell(pb);
6159 mov_write_mdat_tag(pb, mov);
6162 ff_parse_creation_time_metadata(s, &mov->time, 1);
6164 mov->time += 0x7C25B080; // 1970 based -> 1904 based
6166 if (mov->chapter_track)
6167 if ((ret = mov_create_chapter_track(s, mov->chapter_track)) < 0)
6170 if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
6171 /* Initialize the hint tracks for each audio and video stream */
6172 for (i = 0; i < s->nb_streams; i++) {
6173 AVStream *st = s->streams[i];
6174 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ||
6175 st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
6176 if ((ret = ff_mov_init_hinting(s, hint_track, i)) < 0)
6183 if (mov->nb_meta_tmcd) {
6184 /* Initialize the tmcd tracks */
6185 for (i = 0; i < s->nb_streams; i++) {
6186 AVStream *st = s->streams[i];
6189 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
6192 t = av_dict_get(st->metadata, "timecode", NULL, 0);
6195 if (mov_check_timecode_track(s, &tc, i, t->value) < 0)
6197 if ((ret = mov_create_timecode_track(s, tmcd_track, i, tc)) < 0)
6206 if (mov->flags & FF_MOV_FLAG_ISML)
6207 mov_write_isml_manifest(pb, mov, s);
6209 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV &&
6210 !(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
6211 if ((ret = mov_write_moov_tag(pb, mov, s)) < 0)
6214 mov->moov_written = 1;
6215 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
6216 mov->reserved_header_pos = avio_tell(pb);
6222 static int get_moov_size(AVFormatContext *s)
6225 AVIOContext *moov_buf;
6226 MOVMuxContext *mov = s->priv_data;
6228 if ((ret = ffio_open_null_buf(&moov_buf)) < 0)
6230 if ((ret = mov_write_moov_tag(moov_buf, mov, s)) < 0)
6232 return ffio_close_null_buf(moov_buf);
6235 static int get_sidx_size(AVFormatContext *s)
6239 MOVMuxContext *mov = s->priv_data;
6241 if ((ret = ffio_open_null_buf(&buf)) < 0)
6243 mov_write_sidx_tags(buf, mov, -1, 0);
6244 return ffio_close_null_buf(buf);
6248 * This function gets the moov size if moved to the top of the file: the chunk
6249 * offset table can switch between stco (32-bit entries) to co64 (64-bit
6250 * entries) when the moov is moved to the beginning, so the size of the moov
6251 * would change. It also updates the chunk offset tables.
6253 static int compute_moov_size(AVFormatContext *s)
6255 int i, moov_size, moov_size2;
6256 MOVMuxContext *mov = s->priv_data;
6258 moov_size = get_moov_size(s);
6262 for (i = 0; i < mov->nb_streams; i++)
6263 mov->tracks[i].data_offset += moov_size;
6265 moov_size2 = get_moov_size(s);
6269 /* if the size changed, we just switched from stco to co64 and need to
6270 * update the offsets */
6271 if (moov_size2 != moov_size)
6272 for (i = 0; i < mov->nb_streams; i++)
6273 mov->tracks[i].data_offset += moov_size2 - moov_size;
6278 static int compute_sidx_size(AVFormatContext *s)
6281 MOVMuxContext *mov = s->priv_data;
6283 sidx_size = get_sidx_size(s);
6287 for (i = 0; i < mov->nb_streams; i++)
6288 mov->tracks[i].data_offset += sidx_size;
6293 static int shift_data(AVFormatContext *s)
6295 int ret = 0, moov_size;
6296 MOVMuxContext *mov = s->priv_data;
6297 int64_t pos, pos_end = avio_tell(s->pb);
6298 uint8_t *buf, *read_buf[2];
6299 int read_buf_id = 0;
6301 AVIOContext *read_pb;
6303 if (mov->flags & FF_MOV_FLAG_FRAGMENT)
6304 moov_size = compute_sidx_size(s);
6306 moov_size = compute_moov_size(s);
6310 buf = av_malloc(moov_size * 2);
6312 return AVERROR(ENOMEM);
6314 read_buf[1] = buf + moov_size;
6316 /* Shift the data: the AVIO context of the output can only be used for
6317 * writing, so we re-open the same output, but for reading. It also avoids
6318 * a read/seek/write/seek back and forth. */
6320 ret = s->io_open(s, &read_pb, s->filename, AVIO_FLAG_READ, NULL);
6322 av_log(s, AV_LOG_ERROR, "Unable to re-open %s output file for "
6323 "the second pass (faststart)\n", s->filename);
6327 /* mark the end of the shift to up to the last data we wrote, and get ready
6329 pos_end = avio_tell(s->pb);
6330 avio_seek(s->pb, mov->reserved_header_pos + moov_size, SEEK_SET);
6332 /* start reading at where the new moov will be placed */
6333 avio_seek(read_pb, mov->reserved_header_pos, SEEK_SET);
6334 pos = avio_tell(read_pb);
6336 #define READ_BLOCK do { \
6337 read_size[read_buf_id] = avio_read(read_pb, read_buf[read_buf_id], moov_size); \
6341 /* shift data by chunk of at most moov_size */
6346 n = read_size[read_buf_id];
6349 avio_write(s->pb, read_buf[read_buf_id], n);
6351 } while (pos < pos_end);
6352 ff_format_io_close(s, &read_pb);
6359 static int mov_write_trailer(AVFormatContext *s)
6361 MOVMuxContext *mov = s->priv_data;
6362 AVIOContext *pb = s->pb;
6367 if (mov->need_rewrite_extradata) {
6368 for (i = 0; i < s->nb_streams; i++) {
6369 MOVTrack *track = &mov->tracks[i];
6370 AVCodecParameters *par = track->par;
6372 track->vos_len = par->extradata_size;
6373 track->vos_data = av_malloc(track->vos_len);
6374 if (!track->vos_data)
6375 return AVERROR(ENOMEM);
6376 memcpy(track->vos_data, par->extradata, track->vos_len);
6378 mov->need_rewrite_extradata = 0;
6382 * Before actually writing the trailer, make sure that there are no
6383 * dangling subtitles, that need a terminating sample.
6385 for (i = 0; i < mov->nb_streams; i++) {
6386 MOVTrack *trk = &mov->tracks[i];
6387 if (trk->par->codec_id == AV_CODEC_ID_MOV_TEXT &&
6388 !trk->last_sample_is_subtitle_end) {
6389 mov_write_subtitle_end_packet(s, i, trk->track_duration);
6390 trk->last_sample_is_subtitle_end = 1;
6394 // If there were no chapters when the header was written, but there
6395 // are chapters now, write them in the trailer. This only works
6396 // when we are not doing fragments.
6397 if (!mov->chapter_track && !(mov->flags & FF_MOV_FLAG_FRAGMENT)) {
6398 if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters) {
6399 mov->chapter_track = mov->nb_streams++;
6400 if ((res = mov_create_chapter_track(s, mov->chapter_track)) < 0)
6405 if (!(mov->flags & FF_MOV_FLAG_FRAGMENT)) {
6406 moov_pos = avio_tell(pb);
6408 /* Write size of mdat tag */
6409 if (mov->mdat_size + 8 <= UINT32_MAX) {
6410 avio_seek(pb, mov->mdat_pos, SEEK_SET);
6411 avio_wb32(pb, mov->mdat_size + 8);
6413 /* overwrite 'wide' placeholder atom */
6414 avio_seek(pb, mov->mdat_pos - 8, SEEK_SET);
6415 /* special value: real atom size will be 64 bit value after
6418 ffio_wfourcc(pb, "mdat");
6419 avio_wb64(pb, mov->mdat_size + 16);
6421 avio_seek(pb, mov->reserved_moov_size > 0 ? mov->reserved_header_pos : moov_pos, SEEK_SET);
6423 if (mov->flags & FF_MOV_FLAG_FASTSTART) {
6424 av_log(s, AV_LOG_INFO, "Starting second pass: moving the moov atom to the beginning of the file\n");
6425 res = shift_data(s);
6428 avio_seek(pb, mov->reserved_header_pos, SEEK_SET);
6429 if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
6431 } else if (mov->reserved_moov_size > 0) {
6433 if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
6435 size = mov->reserved_moov_size - (avio_tell(pb) - mov->reserved_header_pos);
6437 av_log(s, AV_LOG_ERROR, "reserved_moov_size is too small, needed %"PRId64" additional\n", 8-size);
6438 return AVERROR(EINVAL);
6440 avio_wb32(pb, size);
6441 ffio_wfourcc(pb, "free");
6442 ffio_fill(pb, 0, size - 8);
6443 avio_seek(pb, moov_pos, SEEK_SET);
6445 if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
6450 mov_auto_flush_fragment(s, 1);
6451 for (i = 0; i < mov->nb_streams; i++)
6452 mov->tracks[i].data_offset = 0;
6453 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) {
6455 av_log(s, AV_LOG_INFO, "Starting second pass: inserting sidx atoms\n");
6456 res = shift_data(s);
6459 end = avio_tell(pb);
6460 avio_seek(pb, mov->reserved_header_pos, SEEK_SET);
6461 mov_write_sidx_tags(pb, mov, -1, 0);
6462 avio_seek(pb, end, SEEK_SET);
6463 avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_TRAILER);
6464 mov_write_mfra_tag(pb, mov);
6465 } else if (!(mov->flags & FF_MOV_FLAG_SKIP_TRAILER)) {
6466 avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_TRAILER);
6467 mov_write_mfra_tag(pb, mov);
6474 static int mov_check_bitstream(struct AVFormatContext *s, const AVPacket *pkt)
6477 AVStream *st = s->streams[pkt->stream_index];
6479 if (st->codecpar->codec_id == AV_CODEC_ID_AAC) {
6480 if (pkt->size > 2 && (AV_RB16(pkt->data) & 0xfff0) == 0xfff0)
6481 ret = ff_stream_add_bitstream_filter(st, "aac_adtstoasc", NULL);
6482 } else if (st->codecpar->codec_id == AV_CODEC_ID_VP9) {
6483 ret = ff_stream_add_bitstream_filter(st, "vp9_superframe", NULL);
6489 #if CONFIG_MOV_MUXER
6491 AVOutputFormat ff_mov_muxer = {
6493 .long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
6494 .extensions = "mov",
6495 .priv_data_size = sizeof(MOVMuxContext),
6496 .audio_codec = AV_CODEC_ID_AAC,
6497 .video_codec = CONFIG_LIBX264_ENCODER ?
6498 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
6500 .write_header = mov_write_header,
6501 .write_packet = mov_write_packet,
6502 .write_trailer = mov_write_trailer,
6504 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6505 .codec_tag = (const AVCodecTag* const []){
6506 ff_codec_movvideo_tags, ff_codec_movaudio_tags, 0
6508 .check_bitstream = mov_check_bitstream,
6509 .priv_class = &mov_muxer_class,
6512 #if CONFIG_TGP_MUXER
6514 AVOutputFormat ff_tgp_muxer = {
6516 .long_name = NULL_IF_CONFIG_SMALL("3GP (3GPP file format)"),
6517 .extensions = "3gp",
6518 .priv_data_size = sizeof(MOVMuxContext),
6519 .audio_codec = AV_CODEC_ID_AMR_NB,
6520 .video_codec = AV_CODEC_ID_H263,
6522 .write_header = mov_write_header,
6523 .write_packet = mov_write_packet,
6524 .write_trailer = mov_write_trailer,
6526 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6527 .codec_tag = (const AVCodecTag* const []){ codec_3gp_tags, 0 },
6528 .check_bitstream = mov_check_bitstream,
6529 .priv_class = &tgp_muxer_class,
6532 #if CONFIG_MP4_MUXER
6534 AVOutputFormat ff_mp4_muxer = {
6536 .long_name = NULL_IF_CONFIG_SMALL("MP4 (MPEG-4 Part 14)"),
6537 .mime_type = "video/mp4",
6538 .extensions = "mp4",
6539 .priv_data_size = sizeof(MOVMuxContext),
6540 .audio_codec = AV_CODEC_ID_AAC,
6541 .video_codec = CONFIG_LIBX264_ENCODER ?
6542 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
6544 .write_header = mov_write_header,
6545 .write_packet = mov_write_packet,
6546 .write_trailer = mov_write_trailer,
6548 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6549 .codec_tag = (const AVCodecTag* const []){ ff_mp4_obj_type, 0 },
6550 .check_bitstream = mov_check_bitstream,
6551 .priv_class = &mp4_muxer_class,
6554 #if CONFIG_PSP_MUXER
6556 AVOutputFormat ff_psp_muxer = {
6558 .long_name = NULL_IF_CONFIG_SMALL("PSP MP4 (MPEG-4 Part 14)"),
6559 .extensions = "mp4,psp",
6560 .priv_data_size = sizeof(MOVMuxContext),
6561 .audio_codec = AV_CODEC_ID_AAC,
6562 .video_codec = CONFIG_LIBX264_ENCODER ?
6563 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
6565 .write_header = mov_write_header,
6566 .write_packet = mov_write_packet,
6567 .write_trailer = mov_write_trailer,
6569 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6570 .codec_tag = (const AVCodecTag* const []){ ff_mp4_obj_type, 0 },
6571 .check_bitstream = mov_check_bitstream,
6572 .priv_class = &psp_muxer_class,
6575 #if CONFIG_TG2_MUXER
6577 AVOutputFormat ff_tg2_muxer = {
6579 .long_name = NULL_IF_CONFIG_SMALL("3GP2 (3GPP2 file format)"),
6580 .extensions = "3g2",
6581 .priv_data_size = sizeof(MOVMuxContext),
6582 .audio_codec = AV_CODEC_ID_AMR_NB,
6583 .video_codec = AV_CODEC_ID_H263,
6585 .write_header = mov_write_header,
6586 .write_packet = mov_write_packet,
6587 .write_trailer = mov_write_trailer,
6589 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6590 .codec_tag = (const AVCodecTag* const []){ codec_3gp_tags, 0 },
6591 .check_bitstream = mov_check_bitstream,
6592 .priv_class = &tg2_muxer_class,
6595 #if CONFIG_IPOD_MUXER
6597 AVOutputFormat ff_ipod_muxer = {
6599 .long_name = NULL_IF_CONFIG_SMALL("iPod H.264 MP4 (MPEG-4 Part 14)"),
6600 .mime_type = "video/mp4",
6601 .extensions = "m4v,m4a",
6602 .priv_data_size = sizeof(MOVMuxContext),
6603 .audio_codec = AV_CODEC_ID_AAC,
6604 .video_codec = AV_CODEC_ID_H264,
6606 .write_header = mov_write_header,
6607 .write_packet = mov_write_packet,
6608 .write_trailer = mov_write_trailer,
6610 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6611 .codec_tag = (const AVCodecTag* const []){ codec_ipod_tags, 0 },
6612 .check_bitstream = mov_check_bitstream,
6613 .priv_class = &ipod_muxer_class,
6616 #if CONFIG_ISMV_MUXER
6618 AVOutputFormat ff_ismv_muxer = {
6620 .long_name = NULL_IF_CONFIG_SMALL("ISMV/ISMA (Smooth Streaming)"),
6621 .mime_type = "video/mp4",
6622 .extensions = "ismv,isma",
6623 .priv_data_size = sizeof(MOVMuxContext),
6624 .audio_codec = AV_CODEC_ID_AAC,
6625 .video_codec = AV_CODEC_ID_H264,
6627 .write_header = mov_write_header,
6628 .write_packet = mov_write_packet,
6629 .write_trailer = mov_write_trailer,
6631 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6632 .codec_tag = (const AVCodecTag* const []){ ff_mp4_obj_type, 0 },
6633 .check_bitstream = mov_check_bitstream,
6634 .priv_class = &ismv_muxer_class,
6637 #if CONFIG_F4V_MUXER
6639 AVOutputFormat ff_f4v_muxer = {
6641 .long_name = NULL_IF_CONFIG_SMALL("F4V Adobe Flash Video"),
6642 .mime_type = "application/f4v",
6643 .extensions = "f4v",
6644 .priv_data_size = sizeof(MOVMuxContext),
6645 .audio_codec = AV_CODEC_ID_AAC,
6646 .video_codec = AV_CODEC_ID_H264,
6648 .write_header = mov_write_header,
6649 .write_packet = mov_write_packet,
6650 .write_trailer = mov_write_trailer,
6652 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH,
6653 .codec_tag = (const AVCodecTag* const []){ codec_f4v_tags, 0 },
6654 .check_bitstream = mov_check_bitstream,
6655 .priv_class = &f4v_muxer_class,