3 * Copyright (c) 2003 Thomas Raivio
4 * Copyright (c) 2004 Gildas Bazin <gbazin at videolan dot org>
5 * Copyright (c) 2009 Baptiste Coudurier <baptiste dot coudurier at gmail dot com>
7 * This file is part of FFmpeg.
9 * FFmpeg is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
14 * FFmpeg is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with FFmpeg; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
29 #include "avio_internal.h"
34 #include "libavcodec/ac3_parser.h"
35 #include "libavcodec/dnxhddata.h"
36 #include "libavcodec/flac.h"
37 #include "libavcodec/get_bits.h"
38 #include "libavcodec/put_bits.h"
39 #include "libavcodec/vc1_common.h"
40 #include "libavcodec/raw.h"
42 #include "libavutil/avstring.h"
43 #include "libavutil/intfloat.h"
44 #include "libavutil/mathematics.h"
45 #include "libavutil/libm.h"
46 #include "libavutil/opt.h"
47 #include "libavutil/dict.h"
48 #include "libavutil/pixdesc.h"
49 #include "libavutil/stereo3d.h"
50 #include "libavutil/timecode.h"
51 #include "libavutil/color_utils.h"
57 static const AVOption options[] = {
58 { "movflags", "MOV muxer flags", offsetof(MOVMuxContext, flags), AV_OPT_TYPE_FLAGS, {.i64 = 0}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
59 { "rtphint", "Add RTP hint tracks", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_RTP_HINT}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
60 { "moov_size", "maximum moov size so it can be placed at the begin", offsetof(MOVMuxContext, reserved_moov_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, 0 },
61 { "empty_moov", "Make the initial moov atom empty", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_EMPTY_MOOV}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
62 { "frag_keyframe", "Fragment at video keyframes", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FRAG_KEYFRAME}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
63 { "separate_moof", "Write separate moof/mdat atoms for each track", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_SEPARATE_MOOF}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
64 { "frag_custom", "Flush fragments on caller requests", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FRAG_CUSTOM}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
65 { "isml", "Create a live smooth streaming feed (for pushing to a publishing point)", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_ISML}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
66 { "faststart", "Run a second pass to put the index (moov atom) at the beginning of the file", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FASTSTART}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
67 { "omit_tfhd_offset", "Omit the base data offset in tfhd atoms", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_OMIT_TFHD_OFFSET}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
68 { "disable_chpl", "Disable Nero chapter atom", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_DISABLE_CHPL}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
69 { "default_base_moof", "Set the default-base-is-moof flag in tfhd atoms", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_DEFAULT_BASE_MOOF}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
70 { "dash", "Write DASH compatible fragmented MP4", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_DASH}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
71 { "frag_discont", "Signal that the next fragment is discontinuous from earlier ones", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FRAG_DISCONT}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
72 { "delay_moov", "Delay writing the initial moov until the first fragment is cut, or until the first fragment flush", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_DELAY_MOOV}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
73 { "global_sidx", "Write a global sidx index at the start of the file", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_GLOBAL_SIDX}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
74 { "write_colr", "Write colr atom (Experimental, may be renamed or changed, do not use from scripts)", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_WRITE_COLR}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
75 { "write_gama", "Write deprecated gama atom", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_WRITE_GAMA}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
76 { "use_metadata_tags", "Use mdta atom for metadata.", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_USE_MDTA}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
77 { "skip_trailer", "Skip writing the mfra/tfra/mfro trailer for fragmented files", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_SKIP_TRAILER}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
78 FF_RTP_FLAG_OPTS(MOVMuxContext, rtp_flags),
79 { "skip_iods", "Skip writing iods atom.", offsetof(MOVMuxContext, iods_skip), AV_OPT_TYPE_BOOL, {.i64 = 1}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM},
80 { "iods_audio_profile", "iods audio profile atom.", offsetof(MOVMuxContext, iods_audio_profile), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 255, AV_OPT_FLAG_ENCODING_PARAM},
81 { "iods_video_profile", "iods video profile atom.", offsetof(MOVMuxContext, iods_video_profile), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 255, AV_OPT_FLAG_ENCODING_PARAM},
82 { "frag_duration", "Maximum fragment duration", offsetof(MOVMuxContext, max_fragment_duration), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
83 { "min_frag_duration", "Minimum fragment duration", offsetof(MOVMuxContext, min_fragment_duration), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
84 { "frag_size", "Maximum fragment size", offsetof(MOVMuxContext, max_fragment_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
85 { "ism_lookahead", "Number of lookahead entries for ISM files", offsetof(MOVMuxContext, ism_lookahead), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
86 { "video_track_timescale", "set timescale of all video tracks", offsetof(MOVMuxContext, video_track_timescale), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
87 { "brand", "Override major brand", offsetof(MOVMuxContext, major_brand), AV_OPT_TYPE_STRING, {.str = NULL}, .flags = AV_OPT_FLAG_ENCODING_PARAM },
88 { "use_editlist", "use edit list", offsetof(MOVMuxContext, use_editlist), AV_OPT_TYPE_BOOL, {.i64 = -1}, -1, 1, AV_OPT_FLAG_ENCODING_PARAM},
89 { "fragment_index", "Fragment number of the next fragment", offsetof(MOVMuxContext, fragments), AV_OPT_TYPE_INT, {.i64 = 1}, 1, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
90 { "mov_gamma", "gamma value for gama atom", offsetof(MOVMuxContext, gamma), AV_OPT_TYPE_FLOAT, {.dbl = 0.0 }, 0.0, 10, AV_OPT_FLAG_ENCODING_PARAM},
91 { "frag_interleave", "Interleave samples within fragments (max number of consecutive samples, lower is tighter interleaving, but with more overhead)", offsetof(MOVMuxContext, frag_interleave), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM },
92 { "encryption_scheme", "Configures the encryption scheme, allowed values are none, cenc-aes-ctr", offsetof(MOVMuxContext, encryption_scheme_str), AV_OPT_TYPE_STRING, {.str = NULL}, .flags = AV_OPT_FLAG_ENCODING_PARAM },
93 { "encryption_key", "The media encryption key (hex)", offsetof(MOVMuxContext, encryption_key), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_ENCODING_PARAM },
94 { "encryption_kid", "The media encryption key identifier (hex)", offsetof(MOVMuxContext, encryption_kid), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_ENCODING_PARAM },
95 { "use_stream_ids_as_track_ids", "use stream ids as track ids", offsetof(MOVMuxContext, use_stream_ids_as_track_ids), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM},
96 { "write_tmcd", "force or disable writing tmcd", offsetof(MOVMuxContext, write_tmcd), AV_OPT_TYPE_BOOL, {.i64 = -1}, -1, 1, AV_OPT_FLAG_ENCODING_PARAM},
100 #define MOV_CLASS(flavor)\
101 static const AVClass flavor ## _muxer_class = {\
102 .class_name = #flavor " muxer",\
103 .item_name = av_default_item_name,\
105 .version = LIBAVUTIL_VERSION_INT,\
108 static int get_moov_size(AVFormatContext *s);
110 static int utf8len(const uint8_t *b)
115 GET_UTF8(val, *b++, return -1;)
121 //FIXME support 64 bit variant with wide placeholders
122 static int64_t update_size(AVIOContext *pb, int64_t pos)
124 int64_t curpos = avio_tell(pb);
125 avio_seek(pb, pos, SEEK_SET);
126 avio_wb32(pb, curpos - pos); /* rewrite size */
127 avio_seek(pb, curpos, SEEK_SET);
132 static int co64_required(const MOVTrack *track)
134 if (track->entry > 0 && track->cluster[track->entry - 1].pos + track->data_offset > UINT32_MAX)
139 /* Chunk offset atom */
140 static int mov_write_stco_tag(AVIOContext *pb, MOVTrack *track)
143 int mode64 = co64_required(track); // use 32 bit size variant if possible
144 int64_t pos = avio_tell(pb);
145 avio_wb32(pb, 0); /* size */
147 ffio_wfourcc(pb, "co64");
149 ffio_wfourcc(pb, "stco");
150 avio_wb32(pb, 0); /* version & flags */
151 avio_wb32(pb, track->chunkCount); /* entry count */
152 for (i = 0; i < track->entry; i++) {
153 if (!track->cluster[i].chunkNum)
156 avio_wb64(pb, track->cluster[i].pos + track->data_offset);
158 avio_wb32(pb, track->cluster[i].pos + track->data_offset);
160 return update_size(pb, pos);
163 /* Sample size atom */
164 static int mov_write_stsz_tag(AVIOContext *pb, MOVTrack *track)
167 int i, j, entries = 0, tst = -1, oldtst = -1;
169 int64_t pos = avio_tell(pb);
170 avio_wb32(pb, 0); /* size */
171 ffio_wfourcc(pb, "stsz");
172 avio_wb32(pb, 0); /* version & flags */
174 for (i = 0; i < track->entry; i++) {
175 tst = track->cluster[i].size / track->cluster[i].entries;
176 if (oldtst != -1 && tst != oldtst)
179 entries += track->cluster[i].entries;
181 if (equalChunks && track->entry) {
182 int sSize = track->entry ? track->cluster[0].size / track->cluster[0].entries : 0;
183 sSize = FFMAX(1, sSize); // adpcm mono case could make sSize == 0
184 avio_wb32(pb, sSize); // sample size
185 avio_wb32(pb, entries); // sample count
187 avio_wb32(pb, 0); // sample size
188 avio_wb32(pb, entries); // sample count
189 for (i = 0; i < track->entry; i++) {
190 for (j = 0; j < track->cluster[i].entries; j++) {
191 avio_wb32(pb, track->cluster[i].size /
192 track->cluster[i].entries);
196 return update_size(pb, pos);
199 /* Sample to chunk atom */
200 static int mov_write_stsc_tag(AVIOContext *pb, MOVTrack *track)
202 int index = 0, oldval = -1, i;
203 int64_t entryPos, curpos;
205 int64_t pos = avio_tell(pb);
206 avio_wb32(pb, 0); /* size */
207 ffio_wfourcc(pb, "stsc");
208 avio_wb32(pb, 0); // version & flags
209 entryPos = avio_tell(pb);
210 avio_wb32(pb, track->chunkCount); // entry count
211 for (i = 0; i < track->entry; i++) {
212 if (oldval != track->cluster[i].samples_in_chunk && track->cluster[i].chunkNum) {
213 avio_wb32(pb, track->cluster[i].chunkNum); // first chunk
214 avio_wb32(pb, track->cluster[i].samples_in_chunk); // samples per chunk
215 avio_wb32(pb, 0x1); // sample description index
216 oldval = track->cluster[i].samples_in_chunk;
220 curpos = avio_tell(pb);
221 avio_seek(pb, entryPos, SEEK_SET);
222 avio_wb32(pb, index); // rewrite size
223 avio_seek(pb, curpos, SEEK_SET);
225 return update_size(pb, pos);
228 /* Sync sample atom */
229 static int mov_write_stss_tag(AVIOContext *pb, MOVTrack *track, uint32_t flag)
231 int64_t curpos, entryPos;
233 int64_t pos = avio_tell(pb);
234 avio_wb32(pb, 0); // size
235 ffio_wfourcc(pb, flag == MOV_SYNC_SAMPLE ? "stss" : "stps");
236 avio_wb32(pb, 0); // version & flags
237 entryPos = avio_tell(pb);
238 avio_wb32(pb, track->entry); // entry count
239 for (i = 0; i < track->entry; i++) {
240 if (track->cluster[i].flags & flag) {
241 avio_wb32(pb, i + 1);
245 curpos = avio_tell(pb);
246 avio_seek(pb, entryPos, SEEK_SET);
247 avio_wb32(pb, index); // rewrite size
248 avio_seek(pb, curpos, SEEK_SET);
249 return update_size(pb, pos);
252 static int mov_write_amr_tag(AVIOContext *pb, MOVTrack *track)
254 avio_wb32(pb, 0x11); /* size */
255 if (track->mode == MODE_MOV) ffio_wfourcc(pb, "samr");
256 else ffio_wfourcc(pb, "damr");
257 ffio_wfourcc(pb, "FFMP");
258 avio_w8(pb, 0); /* decoder version */
260 avio_wb16(pb, 0x81FF); /* Mode set (all modes for AMR_NB) */
261 avio_w8(pb, 0x00); /* Mode change period (no restriction) */
262 avio_w8(pb, 0x01); /* Frames per sample */
266 static int mov_write_ac3_tag(AVIOContext *pb, MOVTrack *track)
271 int fscod, bsid, bsmod, acmod, lfeon, frmsizecod;
273 if (track->vos_len < 7)
277 ffio_wfourcc(pb, "dac3");
279 init_get_bits(&gbc, track->vos_data + 4, (track->vos_len - 4) * 8);
280 fscod = get_bits(&gbc, 2);
281 frmsizecod = get_bits(&gbc, 6);
282 bsid = get_bits(&gbc, 5);
283 bsmod = get_bits(&gbc, 3);
284 acmod = get_bits(&gbc, 3);
286 skip_bits(&gbc, 2); // dsurmod
288 if ((acmod & 1) && acmod != 1)
289 skip_bits(&gbc, 2); // cmixlev
291 skip_bits(&gbc, 2); // surmixlev
293 lfeon = get_bits1(&gbc);
295 init_put_bits(&pbc, buf, sizeof(buf));
296 put_bits(&pbc, 2, fscod);
297 put_bits(&pbc, 5, bsid);
298 put_bits(&pbc, 3, bsmod);
299 put_bits(&pbc, 3, acmod);
300 put_bits(&pbc, 1, lfeon);
301 put_bits(&pbc, 5, frmsizecod >> 1); // bit_rate_code
302 put_bits(&pbc, 5, 0); // reserved
304 flush_put_bits(&pbc);
305 avio_write(pb, buf, sizeof(buf));
315 /* Layout of the EC3SpecificBox */
316 /* maximum bitrate */
318 /* number of independent substreams */
321 /* sample rate code (see ff_ac3_sample_rate_tab) 2 bits */
323 /* bit stream identification 5 bits */
325 /* one bit reserved */
326 /* audio service mixing (not supported yet) 1 bit */
327 /* bit stream mode 3 bits */
329 /* audio coding mode 3 bits */
331 /* sub woofer on 1 bit */
333 /* 3 bits reserved */
334 /* number of dependent substreams associated with this substream 4 bits */
336 /* channel locations of the dependent substream(s), if any, 9 bits */
338 /* if there is no dependent substream, then one bit reserved instead */
339 } substream[1]; /* TODO: support 8 independent substreams */
342 #if CONFIG_AC3_PARSER
343 static int handle_eac3(MOVMuxContext *mov, AVPacket *pkt, MOVTrack *track)
346 AC3HeaderInfo tmp, *hdr = &tmp;
347 struct eac3_info *info;
350 if (!track->eac3_priv && !(track->eac3_priv = av_mallocz(sizeof(*info))))
351 return AVERROR(ENOMEM);
352 info = track->eac3_priv;
354 init_get_bits(&gbc, pkt->data, pkt->size * 8);
355 if (avpriv_ac3_parse_header(&gbc, &hdr) < 0) {
356 /* drop the packets until we see a good one */
358 av_log(mov, AV_LOG_WARNING, "Dropping invalid packet from start of the stream\n");
361 return AVERROR_INVALIDDATA;
364 info->data_rate = FFMAX(info->data_rate, hdr->bit_rate / 1000);
365 num_blocks = hdr->num_blocks;
367 if (!info->ec3_done) {
368 /* AC-3 substream must be the first one */
369 if (hdr->bitstream_id <= 10 && hdr->substreamid != 0)
370 return AVERROR(EINVAL);
372 /* this should always be the case, given that our AC-3 parser
373 * concatenates dependent frames to their independent parent */
374 if (hdr->frame_type == EAC3_FRAME_TYPE_INDEPENDENT) {
375 /* substream ids must be incremental */
376 if (hdr->substreamid > info->num_ind_sub + 1)
377 return AVERROR(EINVAL);
379 if (hdr->substreamid == info->num_ind_sub + 1) {
380 //info->num_ind_sub++;
381 avpriv_request_sample(track->par, "Multiple independent substreams");
382 return AVERROR_PATCHWELCOME;
383 } else if (hdr->substreamid < info->num_ind_sub ||
384 hdr->substreamid == 0 && info->substream[0].bsid) {
390 /* fill the info needed for the "dec3" atom */
391 info->substream[hdr->substreamid].fscod = hdr->sr_code;
392 info->substream[hdr->substreamid].bsid = hdr->bitstream_id;
393 info->substream[hdr->substreamid].bsmod = hdr->bitstream_mode;
394 info->substream[hdr->substreamid].acmod = hdr->channel_mode;
395 info->substream[hdr->substreamid].lfeon = hdr->lfe_on;
397 /* Parse dependent substream(s), if any */
398 if (pkt->size != hdr->frame_size) {
399 int cumul_size = hdr->frame_size;
400 int parent = hdr->substreamid;
402 while (cumul_size != pkt->size) {
404 init_get_bits(&gbc, pkt->data + cumul_size, (pkt->size - cumul_size) * 8);
405 if (avpriv_ac3_parse_header(&gbc, &hdr) < 0)
406 return AVERROR_INVALIDDATA;
407 if (hdr->frame_type != EAC3_FRAME_TYPE_DEPENDENT)
408 return AVERROR(EINVAL);
409 cumul_size += hdr->frame_size;
410 info->substream[parent].num_dep_sub++;
412 /* header is parsed up to lfeon, but custom channel map may be needed */
415 /* skip volume control params */
416 for (i = 0; i < (hdr->channel_mode ? 1 : 2); i++) {
417 skip_bits(&gbc, 5); // skip dialog normalization
418 if (get_bits1(&gbc)) {
419 skip_bits(&gbc, 8); // skip compression gain word
422 /* get the dependent stream channel map, if exists */
424 info->substream[parent].chan_loc |= (get_bits(&gbc, 16) >> 5) & 0x1f;
426 info->substream[parent].chan_loc |= hdr->channel_mode;
432 if (!info->num_blocks && num_blocks == 6)
434 else if (info->num_blocks + num_blocks > 6)
435 return AVERROR_INVALIDDATA;
437 if (!info->num_blocks) {
439 if ((ret = av_copy_packet(&info->pkt, pkt)) < 0)
441 info->num_blocks = num_blocks;
445 if ((ret = av_grow_packet(&info->pkt, pkt->size)) < 0)
447 memcpy(info->pkt.data + info->pkt.size - pkt->size, pkt->data, pkt->size);
448 info->num_blocks += num_blocks;
449 info->pkt.duration += pkt->duration;
450 if ((ret = av_copy_packet_side_data(&info->pkt, pkt)) < 0)
452 if (info->num_blocks != 6)
454 av_packet_unref(pkt);
455 if ((ret = av_copy_packet(pkt, &info->pkt)) < 0)
457 av_packet_unref(&info->pkt);
458 info->num_blocks = 0;
465 static int mov_write_eac3_tag(AVIOContext *pb, MOVTrack *track)
469 struct eac3_info *info;
472 if (!track->eac3_priv)
473 return AVERROR(EINVAL);
475 info = track->eac3_priv;
476 size = 2 + 4 * (info->num_ind_sub + 1);
477 buf = av_malloc(size);
479 size = AVERROR(ENOMEM);
483 init_put_bits(&pbc, buf, size);
484 put_bits(&pbc, 13, info->data_rate);
485 put_bits(&pbc, 3, info->num_ind_sub);
486 for (i = 0; i <= info->num_ind_sub; i++) {
487 put_bits(&pbc, 2, info->substream[i].fscod);
488 put_bits(&pbc, 5, info->substream[i].bsid);
489 put_bits(&pbc, 1, 0); /* reserved */
490 put_bits(&pbc, 1, 0); /* asvc */
491 put_bits(&pbc, 3, info->substream[i].bsmod);
492 put_bits(&pbc, 3, info->substream[i].acmod);
493 put_bits(&pbc, 1, info->substream[i].lfeon);
494 put_bits(&pbc, 5, 0); /* reserved */
495 put_bits(&pbc, 4, info->substream[i].num_dep_sub);
496 if (!info->substream[i].num_dep_sub) {
497 put_bits(&pbc, 1, 0); /* reserved */
500 put_bits(&pbc, 9, info->substream[i].chan_loc);
503 flush_put_bits(&pbc);
505 avio_wb32(pb, size + 8);
506 ffio_wfourcc(pb, "dec3");
507 avio_write(pb, buf, size);
512 av_packet_unref(&info->pkt);
513 av_freep(&track->eac3_priv);
519 * This function writes extradata "as is".
520 * Extradata must be formatted like a valid atom (with size and tag).
522 static int mov_write_extradata_tag(AVIOContext *pb, MOVTrack *track)
524 avio_write(pb, track->par->extradata, track->par->extradata_size);
525 return track->par->extradata_size;
528 static int mov_write_enda_tag(AVIOContext *pb)
531 ffio_wfourcc(pb, "enda");
532 avio_wb16(pb, 1); /* little endian */
536 static int mov_write_enda_tag_be(AVIOContext *pb)
539 ffio_wfourcc(pb, "enda");
540 avio_wb16(pb, 0); /* big endian */
544 static void put_descr(AVIOContext *pb, int tag, unsigned int size)
549 avio_w8(pb, (size >> (7 * i)) | 0x80);
550 avio_w8(pb, size & 0x7F);
553 static unsigned compute_avg_bitrate(MOVTrack *track)
557 if (!track->track_duration)
559 for (i = 0; i < track->entry; i++)
560 size += track->cluster[i].size;
561 return size * 8 * track->timescale / track->track_duration;
564 static int mov_write_esds_tag(AVIOContext *pb, MOVTrack *track) // Basic
566 AVCPBProperties *props;
567 int64_t pos = avio_tell(pb);
568 int decoder_specific_info_len = track->vos_len ? 5 + track->vos_len : 0;
569 unsigned avg_bitrate;
571 avio_wb32(pb, 0); // size
572 ffio_wfourcc(pb, "esds");
573 avio_wb32(pb, 0); // Version
576 put_descr(pb, 0x03, 3 + 5+13 + decoder_specific_info_len + 5+1);
577 avio_wb16(pb, track->track_id);
578 avio_w8(pb, 0x00); // flags (= no flags)
580 // DecoderConfig descriptor
581 put_descr(pb, 0x04, 13 + decoder_specific_info_len);
583 // Object type indication
584 if ((track->par->codec_id == AV_CODEC_ID_MP2 ||
585 track->par->codec_id == AV_CODEC_ID_MP3) &&
586 track->par->sample_rate > 24000)
587 avio_w8(pb, 0x6B); // 11172-3
589 avio_w8(pb, ff_codec_get_tag(ff_mp4_obj_type, track->par->codec_id));
591 // the following fields is made of 6 bits to identify the streamtype (4 for video, 5 for audio)
592 // plus 1 bit to indicate upstream and 1 bit set to 1 (reserved)
593 if (track->par->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
594 avio_w8(pb, (0x38 << 2) | 1); // flags (= NeroSubpicStream)
595 else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
596 avio_w8(pb, 0x15); // flags (= Audiostream)
598 avio_w8(pb, 0x11); // flags (= Visualstream)
600 props = (AVCPBProperties*)av_stream_get_side_data(track->st, AV_PKT_DATA_CPB_PROPERTIES,
603 avio_wb24(pb, props ? props->buffer_size / 8 : 0); // Buffersize DB
605 avg_bitrate = compute_avg_bitrate(track);
606 avio_wb32(pb, props ? FFMAX3(props->max_bitrate, props->avg_bitrate, avg_bitrate) : FFMAX(track->par->bit_rate, avg_bitrate)); // maxbitrate (FIXME should be max rate in any 1 sec window)
607 avio_wb32(pb, avg_bitrate);
609 if (track->vos_len) {
610 // DecoderSpecific info descriptor
611 put_descr(pb, 0x05, track->vos_len);
612 avio_write(pb, track->vos_data, track->vos_len);
616 put_descr(pb, 0x06, 1);
618 return update_size(pb, pos);
621 static int mov_pcm_le_gt16(enum AVCodecID codec_id)
623 return codec_id == AV_CODEC_ID_PCM_S24LE ||
624 codec_id == AV_CODEC_ID_PCM_S32LE ||
625 codec_id == AV_CODEC_ID_PCM_F32LE ||
626 codec_id == AV_CODEC_ID_PCM_F64LE;
629 static int mov_pcm_be_gt16(enum AVCodecID codec_id)
631 return codec_id == AV_CODEC_ID_PCM_S24BE ||
632 codec_id == AV_CODEC_ID_PCM_S32BE ||
633 codec_id == AV_CODEC_ID_PCM_F32BE ||
634 codec_id == AV_CODEC_ID_PCM_F64BE;
637 static int mov_write_ms_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
640 int64_t pos = avio_tell(pb);
642 avio_wl32(pb, track->tag); // store it byteswapped
643 track->par->codec_tag = av_bswap16(track->tag >> 16);
644 if ((ret = ff_put_wav_header(s, pb, track->par, 0)) < 0)
646 return update_size(pb, pos);
649 static int mov_write_wfex_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
652 int64_t pos = avio_tell(pb);
654 ffio_wfourcc(pb, "wfex");
655 if ((ret = ff_put_wav_header(s, pb, track->st->codecpar, FF_PUT_WAV_HEADER_FORCE_WAVEFORMATEX)) < 0)
657 return update_size(pb, pos);
660 static int mov_write_dfla_tag(AVIOContext *pb, MOVTrack *track)
662 int64_t pos = avio_tell(pb);
664 ffio_wfourcc(pb, "dfLa");
665 avio_w8(pb, 0); /* version */
666 avio_wb24(pb, 0); /* flags */
668 /* Expect the encoder to pass a METADATA_BLOCK_TYPE_STREAMINFO. */
669 if (track->par->extradata_size != FLAC_STREAMINFO_SIZE)
670 return AVERROR_INVALIDDATA;
672 /* TODO: Write other METADATA_BLOCK_TYPEs if the encoder makes them available. */
673 avio_w8(pb, 1 << 7 | FLAC_METADATA_TYPE_STREAMINFO); /* LastMetadataBlockFlag << 7 | BlockType */
674 avio_wb24(pb, track->par->extradata_size); /* Length */
675 avio_write(pb, track->par->extradata, track->par->extradata_size); /* BlockData[Length] */
677 return update_size(pb, pos);
680 static int mov_write_dops_tag(AVIOContext *pb, MOVTrack *track)
682 int64_t pos = avio_tell(pb);
684 ffio_wfourcc(pb, "dOps");
685 avio_w8(pb, 0); /* Version */
686 if (track->par->extradata_size < 19) {
687 av_log(pb, AV_LOG_ERROR, "invalid extradata size\n");
688 return AVERROR_INVALIDDATA;
690 /* extradata contains an Ogg OpusHead, other than byte-ordering and
691 OpusHead's preceeding magic/version, OpusSpecificBox is currently
693 avio_w8(pb, AV_RB8(track->par->extradata + 9)); /* OuputChannelCount */
694 avio_wb16(pb, AV_RL16(track->par->extradata + 10)); /* PreSkip */
695 avio_wb32(pb, AV_RL32(track->par->extradata + 12)); /* InputSampleRate */
696 avio_wb16(pb, AV_RL16(track->par->extradata + 16)); /* OutputGain */
697 /* Write the rest of the header out without byte-swapping. */
698 avio_write(pb, track->par->extradata + 18, track->par->extradata_size - 18);
700 return update_size(pb, pos);
703 static int mov_write_chan_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
705 uint32_t layout_tag, bitmap;
706 int64_t pos = avio_tell(pb);
708 layout_tag = ff_mov_get_channel_layout_tag(track->par->codec_id,
709 track->par->channel_layout,
712 av_log(s, AV_LOG_WARNING, "not writing 'chan' tag due to "
713 "lack of channel information\n");
717 if (track->multichannel_as_mono)
720 avio_wb32(pb, 0); // Size
721 ffio_wfourcc(pb, "chan"); // Type
722 avio_w8(pb, 0); // Version
723 avio_wb24(pb, 0); // Flags
724 avio_wb32(pb, layout_tag); // mChannelLayoutTag
725 avio_wb32(pb, bitmap); // mChannelBitmap
726 avio_wb32(pb, 0); // mNumberChannelDescriptions
728 return update_size(pb, pos);
731 static int mov_write_wave_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
733 int64_t pos = avio_tell(pb);
735 avio_wb32(pb, 0); /* size */
736 ffio_wfourcc(pb, "wave");
738 if (track->par->codec_id != AV_CODEC_ID_QDM2) {
739 avio_wb32(pb, 12); /* size */
740 ffio_wfourcc(pb, "frma");
741 avio_wl32(pb, track->tag);
744 if (track->par->codec_id == AV_CODEC_ID_AAC) {
745 /* useless atom needed by mplayer, ipod, not needed by quicktime */
746 avio_wb32(pb, 12); /* size */
747 ffio_wfourcc(pb, "mp4a");
749 mov_write_esds_tag(pb, track);
750 } else if (mov_pcm_le_gt16(track->par->codec_id)) {
751 mov_write_enda_tag(pb);
752 } else if (mov_pcm_be_gt16(track->par->codec_id)) {
753 mov_write_enda_tag_be(pb);
754 } else if (track->par->codec_id == AV_CODEC_ID_AMR_NB) {
755 mov_write_amr_tag(pb, track);
756 } else if (track->par->codec_id == AV_CODEC_ID_AC3) {
757 mov_write_ac3_tag(pb, track);
758 } else if (track->par->codec_id == AV_CODEC_ID_EAC3) {
759 mov_write_eac3_tag(pb, track);
760 } else if (track->par->codec_id == AV_CODEC_ID_ALAC ||
761 track->par->codec_id == AV_CODEC_ID_QDM2) {
762 mov_write_extradata_tag(pb, track);
763 } else if (track->par->codec_id == AV_CODEC_ID_ADPCM_MS ||
764 track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) {
765 mov_write_ms_tag(s, pb, track);
768 avio_wb32(pb, 8); /* size */
769 avio_wb32(pb, 0); /* null tag */
771 return update_size(pb, pos);
774 static int mov_write_dvc1_structs(MOVTrack *track, uint8_t *buf)
777 const uint8_t *start, *next, *end = track->vos_data + track->vos_len;
778 int unescaped_size, seq_found = 0;
779 int level = 0, interlace = 0;
780 int packet_seq = track->vc1_info.packet_seq;
781 int packet_entry = track->vc1_info.packet_entry;
782 int slices = track->vc1_info.slices;
785 if (track->start_dts == AV_NOPTS_VALUE) {
786 /* No packets written yet, vc1_info isn't authoritative yet. */
787 /* Assume inline sequence and entry headers. */
788 packet_seq = packet_entry = 1;
789 av_log(NULL, AV_LOG_WARNING,
790 "moov atom written before any packets, unable to write correct "
791 "dvc1 atom. Set the delay_moov flag to fix this.\n");
794 unescaped = av_mallocz(track->vos_len + AV_INPUT_BUFFER_PADDING_SIZE);
796 return AVERROR(ENOMEM);
797 start = find_next_marker(track->vos_data, end);
798 for (next = start; next < end; start = next) {
801 next = find_next_marker(start + 4, end);
802 size = next - start - 4;
805 unescaped_size = vc1_unescape_buffer(start + 4, size, unescaped);
806 init_get_bits(&gb, unescaped, 8 * unescaped_size);
807 if (AV_RB32(start) == VC1_CODE_SEQHDR) {
808 int profile = get_bits(&gb, 2);
809 if (profile != PROFILE_ADVANCED) {
811 return AVERROR(ENOSYS);
814 level = get_bits(&gb, 3);
815 /* chromaformat, frmrtq_postproc, bitrtq_postproc, postprocflag,
817 skip_bits_long(&gb, 2 + 3 + 5 + 1 + 2*12);
818 skip_bits(&gb, 1); /* broadcast */
819 interlace = get_bits1(&gb);
820 skip_bits(&gb, 4); /* tfcntrflag, finterpflag, reserved, psf */
825 return AVERROR(ENOSYS);
828 init_put_bits(&pbc, buf, 7);
829 /* VC1DecSpecStruc */
830 put_bits(&pbc, 4, 12); /* profile - advanced */
831 put_bits(&pbc, 3, level);
832 put_bits(&pbc, 1, 0); /* reserved */
833 /* VC1AdvDecSpecStruc */
834 put_bits(&pbc, 3, level);
835 put_bits(&pbc, 1, 0); /* cbr */
836 put_bits(&pbc, 6, 0); /* reserved */
837 put_bits(&pbc, 1, !interlace); /* no interlace */
838 put_bits(&pbc, 1, !packet_seq); /* no multiple seq */
839 put_bits(&pbc, 1, !packet_entry); /* no multiple entry */
840 put_bits(&pbc, 1, !slices); /* no slice code */
841 put_bits(&pbc, 1, 0); /* no bframe */
842 put_bits(&pbc, 1, 0); /* reserved */
845 if (track->st->avg_frame_rate.num > 0 && track->st->avg_frame_rate.den > 0)
846 put_bits32(&pbc, track->st->avg_frame_rate.num / track->st->avg_frame_rate.den);
848 put_bits32(&pbc, 0xffffffff);
850 flush_put_bits(&pbc);
857 static int mov_write_dvc1_tag(AVIOContext *pb, MOVTrack *track)
859 uint8_t buf[7] = { 0 };
862 if ((ret = mov_write_dvc1_structs(track, buf)) < 0)
865 avio_wb32(pb, track->vos_len + 8 + sizeof(buf));
866 ffio_wfourcc(pb, "dvc1");
867 avio_write(pb, buf, sizeof(buf));
868 avio_write(pb, track->vos_data, track->vos_len);
873 static int mov_write_glbl_tag(AVIOContext *pb, MOVTrack *track)
875 avio_wb32(pb, track->vos_len + 8);
876 ffio_wfourcc(pb, "glbl");
877 avio_write(pb, track->vos_data, track->vos_len);
878 return 8 + track->vos_len;
882 * Compute flags for 'lpcm' tag.
883 * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
885 static int mov_get_lpcm_flags(enum AVCodecID codec_id)
888 case AV_CODEC_ID_PCM_F32BE:
889 case AV_CODEC_ID_PCM_F64BE:
891 case AV_CODEC_ID_PCM_F32LE:
892 case AV_CODEC_ID_PCM_F64LE:
894 case AV_CODEC_ID_PCM_U8:
896 case AV_CODEC_ID_PCM_S16BE:
897 case AV_CODEC_ID_PCM_S24BE:
898 case AV_CODEC_ID_PCM_S32BE:
900 case AV_CODEC_ID_PCM_S8:
901 case AV_CODEC_ID_PCM_S16LE:
902 case AV_CODEC_ID_PCM_S24LE:
903 case AV_CODEC_ID_PCM_S32LE:
910 static int get_cluster_duration(MOVTrack *track, int cluster_idx)
914 if (cluster_idx >= track->entry)
917 if (cluster_idx + 1 == track->entry)
918 next_dts = track->track_duration + track->start_dts;
920 next_dts = track->cluster[cluster_idx + 1].dts;
922 next_dts -= track->cluster[cluster_idx].dts;
924 av_assert0(next_dts >= 0);
925 av_assert0(next_dts <= INT_MAX);
930 static int get_samples_per_packet(MOVTrack *track)
932 int i, first_duration;
934 // return track->par->frame_size;
936 /* use 1 for raw PCM */
937 if (!track->audio_vbr)
940 /* check to see if duration is constant for all clusters */
943 first_duration = get_cluster_duration(track, 0);
944 for (i = 1; i < track->entry; i++) {
945 if (get_cluster_duration(track, i) != first_duration)
948 return first_duration;
951 static int mov_write_audio_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
953 int64_t pos = avio_tell(pb);
955 uint32_t tag = track->tag;
957 if (track->mode == MODE_MOV) {
958 if (track->timescale > UINT16_MAX) {
959 if (mov_get_lpcm_flags(track->par->codec_id))
960 tag = AV_RL32("lpcm");
962 } else if (track->audio_vbr || mov_pcm_le_gt16(track->par->codec_id) ||
963 mov_pcm_be_gt16(track->par->codec_id) ||
964 track->par->codec_id == AV_CODEC_ID_ADPCM_MS ||
965 track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
966 track->par->codec_id == AV_CODEC_ID_QDM2) {
971 avio_wb32(pb, 0); /* size */
972 if (mov->encryption_scheme != MOV_ENC_NONE) {
973 ffio_wfourcc(pb, "enca");
975 avio_wl32(pb, tag); // store it byteswapped
977 avio_wb32(pb, 0); /* Reserved */
978 avio_wb16(pb, 0); /* Reserved */
979 avio_wb16(pb, 1); /* Data-reference index, XXX == 1 */
981 /* SoundDescription */
982 avio_wb16(pb, version); /* Version */
983 avio_wb16(pb, 0); /* Revision level */
984 avio_wb32(pb, 0); /* Reserved */
989 avio_wb16(pb, 0xfffe);
991 avio_wb32(pb, 0x00010000);
993 avio_wb64(pb, av_double2int(track->par->sample_rate));
994 avio_wb32(pb, track->par->channels);
995 avio_wb32(pb, 0x7F000000);
996 avio_wb32(pb, av_get_bits_per_sample(track->par->codec_id));
997 avio_wb32(pb, mov_get_lpcm_flags(track->par->codec_id));
998 avio_wb32(pb, track->sample_size);
999 avio_wb32(pb, get_samples_per_packet(track));
1001 if (track->mode == MODE_MOV) {
1002 avio_wb16(pb, track->par->channels);
1003 if (track->par->codec_id == AV_CODEC_ID_PCM_U8 ||
1004 track->par->codec_id == AV_CODEC_ID_PCM_S8)
1005 avio_wb16(pb, 8); /* bits per sample */
1006 else if (track->par->codec_id == AV_CODEC_ID_ADPCM_G726)
1007 avio_wb16(pb, track->par->bits_per_coded_sample);
1010 avio_wb16(pb, track->audio_vbr ? -2 : 0); /* compression ID */
1011 } else { /* reserved for mp4/3gp */
1012 if (track->par->codec_id == AV_CODEC_ID_FLAC ||
1013 track->par->codec_id == AV_CODEC_ID_OPUS) {
1014 avio_wb16(pb, track->par->channels);
1018 if (track->par->codec_id == AV_CODEC_ID_FLAC) {
1019 avio_wb16(pb, track->par->bits_per_raw_sample);
1026 avio_wb16(pb, 0); /* packet size (= 0) */
1027 if (track->par->codec_id == AV_CODEC_ID_OPUS)
1028 avio_wb16(pb, 48000);
1030 avio_wb16(pb, track->par->sample_rate <= UINT16_MAX ?
1031 track->par->sample_rate : 0);
1032 avio_wb16(pb, 0); /* Reserved */
1035 if (version == 1) { /* SoundDescription V1 extended info */
1036 if (mov_pcm_le_gt16(track->par->codec_id) ||
1037 mov_pcm_be_gt16(track->par->codec_id))
1038 avio_wb32(pb, 1); /* must be 1 for uncompressed formats */
1040 avio_wb32(pb, track->par->frame_size); /* Samples per packet */
1041 avio_wb32(pb, track->sample_size / track->par->channels); /* Bytes per packet */
1042 avio_wb32(pb, track->sample_size); /* Bytes per frame */
1043 avio_wb32(pb, 2); /* Bytes per sample */
1046 if (track->mode == MODE_MOV &&
1047 (track->par->codec_id == AV_CODEC_ID_AAC ||
1048 track->par->codec_id == AV_CODEC_ID_AC3 ||
1049 track->par->codec_id == AV_CODEC_ID_EAC3 ||
1050 track->par->codec_id == AV_CODEC_ID_AMR_NB ||
1051 track->par->codec_id == AV_CODEC_ID_ALAC ||
1052 track->par->codec_id == AV_CODEC_ID_ADPCM_MS ||
1053 track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
1054 track->par->codec_id == AV_CODEC_ID_QDM2 ||
1055 (mov_pcm_le_gt16(track->par->codec_id) && version==1) ||
1056 (mov_pcm_be_gt16(track->par->codec_id) && version==1)))
1057 mov_write_wave_tag(s, pb, track);
1058 else if (track->tag == MKTAG('m','p','4','a'))
1059 mov_write_esds_tag(pb, track);
1060 else if (track->par->codec_id == AV_CODEC_ID_AMR_NB)
1061 mov_write_amr_tag(pb, track);
1062 else if (track->par->codec_id == AV_CODEC_ID_AC3)
1063 mov_write_ac3_tag(pb, track);
1064 else if (track->par->codec_id == AV_CODEC_ID_EAC3)
1065 mov_write_eac3_tag(pb, track);
1066 else if (track->par->codec_id == AV_CODEC_ID_ALAC)
1067 mov_write_extradata_tag(pb, track);
1068 else if (track->par->codec_id == AV_CODEC_ID_WMAPRO)
1069 mov_write_wfex_tag(s, pb, track);
1070 else if (track->par->codec_id == AV_CODEC_ID_FLAC)
1071 mov_write_dfla_tag(pb, track);
1072 else if (track->par->codec_id == AV_CODEC_ID_OPUS)
1073 mov_write_dops_tag(pb, track);
1074 else if (track->vos_len > 0)
1075 mov_write_glbl_tag(pb, track);
1077 if (track->mode == MODE_MOV && track->par->codec_type == AVMEDIA_TYPE_AUDIO)
1078 mov_write_chan_tag(s, pb, track);
1080 if (mov->encryption_scheme != MOV_ENC_NONE) {
1081 ff_mov_cenc_write_sinf_tag(track, pb, mov->encryption_kid);
1084 return update_size(pb, pos);
1087 static int mov_write_d263_tag(AVIOContext *pb)
1089 avio_wb32(pb, 0xf); /* size */
1090 ffio_wfourcc(pb, "d263");
1091 ffio_wfourcc(pb, "FFMP");
1092 avio_w8(pb, 0); /* decoder version */
1093 /* FIXME use AVCodecContext level/profile, when encoder will set values */
1094 avio_w8(pb, 0xa); /* level */
1095 avio_w8(pb, 0); /* profile */
1099 static int mov_write_avcc_tag(AVIOContext *pb, MOVTrack *track)
1101 int64_t pos = avio_tell(pb);
1104 ffio_wfourcc(pb, "avcC");
1105 ff_isom_write_avcc(pb, track->vos_data, track->vos_len);
1106 return update_size(pb, pos);
1109 static int mov_write_vpcc_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
1111 int64_t pos = avio_tell(pb);
1114 ffio_wfourcc(pb, "vpcC");
1115 avio_wb32(pb, 0); /* version & flags */
1116 ff_isom_write_vpcc(s, pb, track->par);
1117 return update_size(pb, pos);
1120 static int mov_write_hvcc_tag(AVIOContext *pb, MOVTrack *track)
1122 int64_t pos = avio_tell(pb);
1125 ffio_wfourcc(pb, "hvcC");
1126 ff_isom_write_hvcc(pb, track->vos_data, track->vos_len, 0);
1127 return update_size(pb, pos);
1130 /* also used by all avid codecs (dv, imx, meridien) and their variants */
1131 static int mov_write_avid_tag(AVIOContext *pb, MOVTrack *track)
1136 int display_width = track->par->width;
1138 if (track->vos_data && track->vos_len > 0x29) {
1139 if (ff_dnxhd_parse_header_prefix(track->vos_data) != 0) {
1140 /* looks like a DNxHD bit stream */
1141 interlaced = (track->vos_data[5] & 2);
1142 cid = AV_RB32(track->vos_data + 0x28);
1144 av_log(NULL, AV_LOG_WARNING, "Could not locate DNxHD bit stream in vos_data\n");
1148 av_log(NULL, AV_LOG_WARNING, "Could not locate DNxHD bit stream, vos_data too small\n");
1152 avio_wb32(pb, 24); /* size */
1153 ffio_wfourcc(pb, "ACLR");
1154 ffio_wfourcc(pb, "ACLR");
1155 ffio_wfourcc(pb, "0001");
1156 if (track->par->color_range == AVCOL_RANGE_MPEG || /* Legal range (16-235) */
1157 track->par->color_range == AVCOL_RANGE_UNSPECIFIED) {
1158 avio_wb32(pb, 1); /* Corresponds to 709 in official encoder */
1159 } else { /* Full range (0-255) */
1160 avio_wb32(pb, 2); /* Corresponds to RGB in official encoder */
1162 avio_wb32(pb, 0); /* unknown */
1164 if (track->tag == MKTAG('A','V','d','h')) {
1166 ffio_wfourcc(pb, "ADHR");
1167 ffio_wfourcc(pb, "0001");
1169 avio_wb32(pb, 0); /* unknown */
1170 avio_wb32(pb, 1); /* unknown */
1171 avio_wb32(pb, 0); /* unknown */
1172 avio_wb32(pb, 0); /* unknown */
1176 avio_wb32(pb, 24); /* size */
1177 ffio_wfourcc(pb, "APRG");
1178 ffio_wfourcc(pb, "APRG");
1179 ffio_wfourcc(pb, "0001");
1180 avio_wb32(pb, 1); /* unknown */
1181 avio_wb32(pb, 0); /* unknown */
1183 avio_wb32(pb, 120); /* size */
1184 ffio_wfourcc(pb, "ARES");
1185 ffio_wfourcc(pb, "ARES");
1186 ffio_wfourcc(pb, "0001");
1187 avio_wb32(pb, cid); /* dnxhd cid, some id ? */
1188 if ( track->par->sample_aspect_ratio.num > 0
1189 && track->par->sample_aspect_ratio.den > 0)
1190 display_width = display_width * track->par->sample_aspect_ratio.num / track->par->sample_aspect_ratio.den;
1191 avio_wb32(pb, display_width);
1192 /* values below are based on samples created with quicktime and avid codecs */
1194 avio_wb32(pb, track->par->height / 2);
1195 avio_wb32(pb, 2); /* unknown */
1196 avio_wb32(pb, 0); /* unknown */
1197 avio_wb32(pb, 4); /* unknown */
1199 avio_wb32(pb, track->par->height);
1200 avio_wb32(pb, 1); /* unknown */
1201 avio_wb32(pb, 0); /* unknown */
1202 if (track->par->height == 1080)
1203 avio_wb32(pb, 5); /* unknown */
1205 avio_wb32(pb, 6); /* unknown */
1208 for (i = 0; i < 10; i++)
1214 static int mov_write_dpxe_tag(AVIOContext *pb, MOVTrack *track)
1217 ffio_wfourcc(pb, "DpxE");
1218 if (track->par->extradata_size >= 12 &&
1219 !memcmp(&track->par->extradata[4], "DpxE", 4)) {
1220 avio_wb32(pb, track->par->extradata[11]);
1227 static int mp4_get_codec_tag(AVFormatContext *s, MOVTrack *track)
1229 int tag = track->par->codec_tag;
1231 if (!ff_codec_get_tag(ff_mp4_obj_type, track->par->codec_id))
1234 if (track->par->codec_id == AV_CODEC_ID_H264) tag = MKTAG('a','v','c','1');
1235 else if (track->par->codec_id == AV_CODEC_ID_HEVC) tag = MKTAG('h','e','v','1');
1236 else if (track->par->codec_id == AV_CODEC_ID_VP9) tag = MKTAG('v','p','0','9');
1237 else if (track->par->codec_id == AV_CODEC_ID_AC3) tag = MKTAG('a','c','-','3');
1238 else if (track->par->codec_id == AV_CODEC_ID_EAC3) tag = MKTAG('e','c','-','3');
1239 else if (track->par->codec_id == AV_CODEC_ID_DIRAC) tag = MKTAG('d','r','a','c');
1240 else if (track->par->codec_id == AV_CODEC_ID_MOV_TEXT) tag = MKTAG('t','x','3','g');
1241 else if (track->par->codec_id == AV_CODEC_ID_VC1) tag = MKTAG('v','c','-','1');
1242 else if (track->par->codec_id == AV_CODEC_ID_FLAC) tag = MKTAG('f','L','a','C');
1243 else if (track->par->codec_id == AV_CODEC_ID_OPUS) tag = MKTAG('O','p','u','s');
1244 else if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) tag = MKTAG('m','p','4','v');
1245 else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) tag = MKTAG('m','p','4','a');
1246 else if (track->par->codec_id == AV_CODEC_ID_DVD_SUBTITLE) tag = MKTAG('m','p','4','s');
1251 static const AVCodecTag codec_ipod_tags[] = {
1252 { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
1253 { AV_CODEC_ID_MPEG4, MKTAG('m','p','4','v') },
1254 { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
1255 { AV_CODEC_ID_ALAC, MKTAG('a','l','a','c') },
1256 { AV_CODEC_ID_AC3, MKTAG('a','c','-','3') },
1257 { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
1258 { AV_CODEC_ID_MOV_TEXT, MKTAG('t','e','x','t') },
1259 { AV_CODEC_ID_NONE, 0 },
1262 static int ipod_get_codec_tag(AVFormatContext *s, MOVTrack *track)
1264 int tag = track->par->codec_tag;
1266 // keep original tag for subs, ipod supports both formats
1267 if (!(track->par->codec_type == AVMEDIA_TYPE_SUBTITLE &&
1268 (tag == MKTAG('t', 'x', '3', 'g') ||
1269 tag == MKTAG('t', 'e', 'x', 't'))))
1270 tag = ff_codec_get_tag(codec_ipod_tags, track->par->codec_id);
1272 if (!av_match_ext(s->filename, "m4a") &&
1273 !av_match_ext(s->filename, "m4b") &&
1274 !av_match_ext(s->filename, "m4v"))
1275 av_log(s, AV_LOG_WARNING, "Warning, extension is not .m4a, .m4v nor .m4b "
1276 "Quicktime/Ipod might not play the file\n");
1281 static int mov_get_dv_codec_tag(AVFormatContext *s, MOVTrack *track)
1285 if (track->par->width == 720) { /* SD */
1286 if (track->par->height == 480) { /* NTSC */
1287 if (track->par->format == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','n');
1288 else tag = MKTAG('d','v','c',' ');
1289 }else if (track->par->format == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','p');
1290 else if (track->par->format == AV_PIX_FMT_YUV420P) tag = MKTAG('d','v','c','p');
1291 else tag = MKTAG('d','v','p','p');
1292 } else if (track->par->height == 720) { /* HD 720 line */
1293 if (track->st->time_base.den == 50) tag = MKTAG('d','v','h','q');
1294 else tag = MKTAG('d','v','h','p');
1295 } else if (track->par->height == 1080) { /* HD 1080 line */
1296 if (track->st->time_base.den == 25) tag = MKTAG('d','v','h','5');
1297 else tag = MKTAG('d','v','h','6');
1299 av_log(s, AV_LOG_ERROR, "unsupported height for dv codec\n");
1306 static AVRational find_fps(AVFormatContext *s, AVStream *st)
1308 AVRational rate = st->avg_frame_rate;
1310 #if FF_API_LAVF_AVCTX
1311 FF_DISABLE_DEPRECATION_WARNINGS
1312 rate = av_inv_q(st->codec->time_base);
1313 if (av_timecode_check_frame_rate(rate) < 0) {
1314 av_log(s, AV_LOG_DEBUG, "timecode: tbc=%d/%d invalid, fallback on %d/%d\n",
1315 rate.num, rate.den, st->avg_frame_rate.num, st->avg_frame_rate.den);
1316 rate = st->avg_frame_rate;
1318 FF_ENABLE_DEPRECATION_WARNINGS
1324 static int defined_frame_rate(AVFormatContext *s, AVStream *st)
1326 AVRational rational_framerate = find_fps(s, st);
1328 if (rational_framerate.den != 0)
1329 rate = av_q2d(rational_framerate);
1333 static int mov_get_mpeg2_xdcam_codec_tag(AVFormatContext *s, MOVTrack *track)
1335 int tag = track->par->codec_tag;
1336 int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE;
1337 AVStream *st = track->st;
1338 int rate = defined_frame_rate(s, st);
1341 tag = MKTAG('m', '2', 'v', '1'); //fallback tag
1343 if (track->par->format == AV_PIX_FMT_YUV420P) {
1344 if (track->par->width == 1280 && track->par->height == 720) {
1346 if (rate == 24) tag = MKTAG('x','d','v','4');
1347 else if (rate == 25) tag = MKTAG('x','d','v','5');
1348 else if (rate == 30) tag = MKTAG('x','d','v','1');
1349 else if (rate == 50) tag = MKTAG('x','d','v','a');
1350 else if (rate == 60) tag = MKTAG('x','d','v','9');
1352 } else if (track->par->width == 1440 && track->par->height == 1080) {
1354 if (rate == 24) tag = MKTAG('x','d','v','6');
1355 else if (rate == 25) tag = MKTAG('x','d','v','7');
1356 else if (rate == 30) tag = MKTAG('x','d','v','8');
1358 if (rate == 25) tag = MKTAG('x','d','v','3');
1359 else if (rate == 30) tag = MKTAG('x','d','v','2');
1361 } else if (track->par->width == 1920 && track->par->height == 1080) {
1363 if (rate == 24) tag = MKTAG('x','d','v','d');
1364 else if (rate == 25) tag = MKTAG('x','d','v','e');
1365 else if (rate == 30) tag = MKTAG('x','d','v','f');
1367 if (rate == 25) tag = MKTAG('x','d','v','c');
1368 else if (rate == 30) tag = MKTAG('x','d','v','b');
1371 } else if (track->par->format == AV_PIX_FMT_YUV422P) {
1372 if (track->par->width == 1280 && track->par->height == 720) {
1374 if (rate == 24) tag = MKTAG('x','d','5','4');
1375 else if (rate == 25) tag = MKTAG('x','d','5','5');
1376 else if (rate == 30) tag = MKTAG('x','d','5','1');
1377 else if (rate == 50) tag = MKTAG('x','d','5','a');
1378 else if (rate == 60) tag = MKTAG('x','d','5','9');
1380 } else if (track->par->width == 1920 && track->par->height == 1080) {
1382 if (rate == 24) tag = MKTAG('x','d','5','d');
1383 else if (rate == 25) tag = MKTAG('x','d','5','e');
1384 else if (rate == 30) tag = MKTAG('x','d','5','f');
1386 if (rate == 25) tag = MKTAG('x','d','5','c');
1387 else if (rate == 30) tag = MKTAG('x','d','5','b');
1395 static int mov_get_h264_codec_tag(AVFormatContext *s, MOVTrack *track)
1397 int tag = track->par->codec_tag;
1398 int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE;
1399 AVStream *st = track->st;
1400 int rate = defined_frame_rate(s, st);
1403 tag = MKTAG('a', 'v', 'c', 'i'); //fallback tag
1405 if (track->par->format == AV_PIX_FMT_YUV420P10) {
1406 if (track->par->width == 960 && track->par->height == 720) {
1408 if (rate == 24) tag = MKTAG('a','i','5','p');
1409 else if (rate == 25) tag = MKTAG('a','i','5','q');
1410 else if (rate == 30) tag = MKTAG('a','i','5','p');
1411 else if (rate == 50) tag = MKTAG('a','i','5','q');
1412 else if (rate == 60) tag = MKTAG('a','i','5','p');
1414 } else if (track->par->width == 1440 && track->par->height == 1080) {
1416 if (rate == 24) tag = MKTAG('a','i','5','3');
1417 else if (rate == 25) tag = MKTAG('a','i','5','2');
1418 else if (rate == 30) tag = MKTAG('a','i','5','3');
1420 if (rate == 50) tag = MKTAG('a','i','5','5');
1421 else if (rate == 60) tag = MKTAG('a','i','5','6');
1424 } else if (track->par->format == AV_PIX_FMT_YUV422P10) {
1425 if (track->par->width == 1280 && track->par->height == 720) {
1427 if (rate == 24) tag = MKTAG('a','i','1','p');
1428 else if (rate == 25) tag = MKTAG('a','i','1','q');
1429 else if (rate == 30) tag = MKTAG('a','i','1','p');
1430 else if (rate == 50) tag = MKTAG('a','i','1','q');
1431 else if (rate == 60) tag = MKTAG('a','i','1','p');
1433 } else if (track->par->width == 1920 && track->par->height == 1080) {
1435 if (rate == 24) tag = MKTAG('a','i','1','3');
1436 else if (rate == 25) tag = MKTAG('a','i','1','2');
1437 else if (rate == 30) tag = MKTAG('a','i','1','3');
1439 if (rate == 25) tag = MKTAG('a','i','1','5');
1440 else if (rate == 50) tag = MKTAG('a','i','1','5');
1441 else if (rate == 60) tag = MKTAG('a','i','1','6');
1443 } else if ( track->par->width == 4096 && track->par->height == 2160
1444 || track->par->width == 3840 && track->par->height == 2160
1445 || track->par->width == 2048 && track->par->height == 1080) {
1446 tag = MKTAG('a','i','v','x');
1453 static const struct {
1454 enum AVPixelFormat pix_fmt;
1457 } mov_pix_fmt_tags[] = {
1458 { AV_PIX_FMT_YUYV422, MKTAG('y','u','v','2'), 0 },
1459 { AV_PIX_FMT_YUYV422, MKTAG('y','u','v','s'), 0 },
1460 { AV_PIX_FMT_UYVY422, MKTAG('2','v','u','y'), 0 },
1461 { AV_PIX_FMT_RGB555BE,MKTAG('r','a','w',' '), 16 },
1462 { AV_PIX_FMT_RGB555LE,MKTAG('L','5','5','5'), 16 },
1463 { AV_PIX_FMT_RGB565LE,MKTAG('L','5','6','5'), 16 },
1464 { AV_PIX_FMT_RGB565BE,MKTAG('B','5','6','5'), 16 },
1465 { AV_PIX_FMT_GRAY16BE,MKTAG('b','1','6','g'), 16 },
1466 { AV_PIX_FMT_RGB24, MKTAG('r','a','w',' '), 24 },
1467 { AV_PIX_FMT_BGR24, MKTAG('2','4','B','G'), 24 },
1468 { AV_PIX_FMT_ARGB, MKTAG('r','a','w',' '), 32 },
1469 { AV_PIX_FMT_BGRA, MKTAG('B','G','R','A'), 32 },
1470 { AV_PIX_FMT_RGBA, MKTAG('R','G','B','A'), 32 },
1471 { AV_PIX_FMT_ABGR, MKTAG('A','B','G','R'), 32 },
1472 { AV_PIX_FMT_RGB48BE, MKTAG('b','4','8','r'), 48 },
1475 static int mov_get_dnxhd_codec_tag(AVFormatContext *s, MOVTrack *track)
1477 int tag = MKTAG('A','V','d','n');
1478 if (track->par->profile != FF_PROFILE_UNKNOWN &&
1479 track->par->profile != FF_PROFILE_DNXHD)
1480 tag = MKTAG('A','V','d','h');
1484 static int mov_get_rawvideo_codec_tag(AVFormatContext *s, MOVTrack *track)
1486 int tag = track->par->codec_tag;
1488 enum AVPixelFormat pix_fmt;
1490 for (i = 0; i < FF_ARRAY_ELEMS(mov_pix_fmt_tags); i++) {
1491 if (track->par->format == mov_pix_fmt_tags[i].pix_fmt) {
1492 tag = mov_pix_fmt_tags[i].tag;
1493 track->par->bits_per_coded_sample = mov_pix_fmt_tags[i].bps;
1494 if (track->par->codec_tag == mov_pix_fmt_tags[i].tag)
1499 pix_fmt = avpriv_find_pix_fmt(avpriv_pix_fmt_bps_mov,
1500 track->par->bits_per_coded_sample);
1501 if (tag == MKTAG('r','a','w',' ') &&
1502 track->par->format != pix_fmt &&
1503 track->par->format != AV_PIX_FMT_GRAY8 &&
1504 track->par->format != AV_PIX_FMT_NONE)
1505 av_log(s, AV_LOG_ERROR, "%s rawvideo cannot be written to mov, output file will be unreadable\n",
1506 av_get_pix_fmt_name(track->par->format));
1510 static int mov_get_codec_tag(AVFormatContext *s, MOVTrack *track)
1512 int tag = track->par->codec_tag;
1514 if (!tag || (s->strict_std_compliance >= FF_COMPLIANCE_NORMAL &&
1515 (track->par->codec_id == AV_CODEC_ID_DVVIDEO ||
1516 track->par->codec_id == AV_CODEC_ID_RAWVIDEO ||
1517 track->par->codec_id == AV_CODEC_ID_H263 ||
1518 track->par->codec_id == AV_CODEC_ID_H264 ||
1519 track->par->codec_id == AV_CODEC_ID_DNXHD ||
1520 track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO ||
1521 av_get_bits_per_sample(track->par->codec_id)))) { // pcm audio
1522 if (track->par->codec_id == AV_CODEC_ID_DVVIDEO)
1523 tag = mov_get_dv_codec_tag(s, track);
1524 else if (track->par->codec_id == AV_CODEC_ID_RAWVIDEO)
1525 tag = mov_get_rawvideo_codec_tag(s, track);
1526 else if (track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO)
1527 tag = mov_get_mpeg2_xdcam_codec_tag(s, track);
1528 else if (track->par->codec_id == AV_CODEC_ID_H264)
1529 tag = mov_get_h264_codec_tag(s, track);
1530 else if (track->par->codec_id == AV_CODEC_ID_DNXHD)
1531 tag = mov_get_dnxhd_codec_tag(s, track);
1532 else if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
1533 tag = ff_codec_get_tag(ff_codec_movvideo_tags, track->par->codec_id);
1534 if (!tag) { // if no mac fcc found, try with Microsoft tags
1535 tag = ff_codec_get_tag(ff_codec_bmp_tags, track->par->codec_id);
1537 av_log(s, AV_LOG_WARNING, "Using MS style video codec tag, "
1538 "the file may be unplayable!\n");
1540 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
1541 tag = ff_codec_get_tag(ff_codec_movaudio_tags, track->par->codec_id);
1542 if (!tag) { // if no mac fcc found, try with Microsoft tags
1543 int ms_tag = ff_codec_get_tag(ff_codec_wav_tags, track->par->codec_id);
1545 tag = MKTAG('m', 's', ((ms_tag >> 8) & 0xff), (ms_tag & 0xff));
1546 av_log(s, AV_LOG_WARNING, "Using MS style audio codec tag, "
1547 "the file may be unplayable!\n");
1550 } else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)
1551 tag = ff_codec_get_tag(ff_codec_movsubtitle_tags, track->par->codec_id);
1557 static const AVCodecTag codec_3gp_tags[] = {
1558 { AV_CODEC_ID_H263, MKTAG('s','2','6','3') },
1559 { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
1560 { AV_CODEC_ID_MPEG4, MKTAG('m','p','4','v') },
1561 { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
1562 { AV_CODEC_ID_AMR_NB, MKTAG('s','a','m','r') },
1563 { AV_CODEC_ID_AMR_WB, MKTAG('s','a','w','b') },
1564 { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
1565 { AV_CODEC_ID_NONE, 0 },
1568 static const AVCodecTag codec_f4v_tags[] = { // XXX: add GIF/PNG/JPEG?
1569 { AV_CODEC_ID_MP3, MKTAG('.','m','p','3') },
1570 { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
1571 { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
1572 { AV_CODEC_ID_VP6A, MKTAG('V','P','6','A') },
1573 { AV_CODEC_ID_VP6F, MKTAG('V','P','6','F') },
1574 { AV_CODEC_ID_NONE, 0 },
1577 static int mov_find_codec_tag(AVFormatContext *s, MOVTrack *track)
1581 if (track->mode == MODE_MP4 || track->mode == MODE_PSP)
1582 tag = mp4_get_codec_tag(s, track);
1583 else if (track->mode == MODE_ISM) {
1584 tag = mp4_get_codec_tag(s, track);
1585 if (!tag && track->par->codec_id == AV_CODEC_ID_WMAPRO)
1586 tag = MKTAG('w', 'm', 'a', ' ');
1587 } else if (track->mode == MODE_IPOD)
1588 tag = ipod_get_codec_tag(s, track);
1589 else if (track->mode & MODE_3GP)
1590 tag = ff_codec_get_tag(codec_3gp_tags, track->par->codec_id);
1591 else if (track->mode == MODE_F4V)
1592 tag = ff_codec_get_tag(codec_f4v_tags, track->par->codec_id);
1594 tag = mov_get_codec_tag(s, track);
1599 /** Write uuid atom.
1600 * Needed to make file play in iPods running newest firmware
1601 * goes after avcC atom in moov.trak.mdia.minf.stbl.stsd.avc1
1603 static int mov_write_uuid_tag_ipod(AVIOContext *pb)
1606 ffio_wfourcc(pb, "uuid");
1607 avio_wb32(pb, 0x6b6840f2);
1608 avio_wb32(pb, 0x5f244fc5);
1609 avio_wb32(pb, 0xba39a51b);
1610 avio_wb32(pb, 0xcf0323f3);
1615 static const uint16_t fiel_data[] = {
1616 0x0000, 0x0100, 0x0201, 0x0206, 0x0209, 0x020e
1619 static int mov_write_fiel_tag(AVIOContext *pb, MOVTrack *track, int field_order)
1621 unsigned mov_field_order = 0;
1622 if (field_order < FF_ARRAY_ELEMS(fiel_data))
1623 mov_field_order = fiel_data[field_order];
1627 ffio_wfourcc(pb, "fiel");
1628 avio_wb16(pb, mov_field_order);
1632 static int mov_write_subtitle_tag(AVIOContext *pb, MOVTrack *track)
1634 int64_t pos = avio_tell(pb);
1635 avio_wb32(pb, 0); /* size */
1636 avio_wl32(pb, track->tag); // store it byteswapped
1637 avio_wb32(pb, 0); /* Reserved */
1638 avio_wb16(pb, 0); /* Reserved */
1639 avio_wb16(pb, 1); /* Data-reference index */
1641 if (track->par->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
1642 mov_write_esds_tag(pb, track);
1643 else if (track->par->extradata_size)
1644 avio_write(pb, track->par->extradata, track->par->extradata_size);
1646 return update_size(pb, pos);
1649 static int mov_write_st3d_tag(AVIOContext *pb, AVStereo3D *stereo_3d)
1653 if (stereo_3d->flags != 0) {
1654 av_log(pb, AV_LOG_WARNING, "Unsupported stereo_3d flags %x. st3d not written.\n", stereo_3d->flags);
1658 switch (stereo_3d->type) {
1659 case AV_STEREO3D_2D:
1662 case AV_STEREO3D_TOPBOTTOM:
1665 case AV_STEREO3D_SIDEBYSIDE:
1669 av_log(pb, AV_LOG_WARNING, "Unsupported stereo_3d type %s. st3d not written.\n", av_stereo3d_type_name(stereo_3d->type));
1672 avio_wb32(pb, 13); /* size */
1673 ffio_wfourcc(pb, "st3d");
1674 avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1675 avio_w8(pb, stereo_mode);
1679 static int mov_write_sv3d_tag(AVFormatContext *s, AVIOContext *pb, AVSphericalMapping *spherical_mapping)
1681 int64_t sv3d_pos, svhd_pos, proj_pos;
1682 const char* metadata_source = s->flags & AVFMT_FLAG_BITEXACT ? "Lavf" : LIBAVFORMAT_IDENT;
1684 if (spherical_mapping->projection != AV_SPHERICAL_EQUIRECTANGULAR &&
1685 spherical_mapping->projection != AV_SPHERICAL_EQUIRECTANGULAR_TILE &&
1686 spherical_mapping->projection != AV_SPHERICAL_CUBEMAP) {
1687 av_log(pb, AV_LOG_WARNING, "Unsupported projection %d. sv3d not written.\n", spherical_mapping->projection);
1691 sv3d_pos = avio_tell(pb);
1692 avio_wb32(pb, 0); /* size */
1693 ffio_wfourcc(pb, "sv3d");
1695 svhd_pos = avio_tell(pb);
1696 avio_wb32(pb, 0); /* size */
1697 ffio_wfourcc(pb, "svhd");
1698 avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1699 avio_put_str(pb, metadata_source);
1700 update_size(pb, svhd_pos);
1702 proj_pos = avio_tell(pb);
1703 avio_wb32(pb, 0); /* size */
1704 ffio_wfourcc(pb, "proj");
1706 avio_wb32(pb, 24); /* size */
1707 ffio_wfourcc(pb, "prhd");
1708 avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1709 avio_wb32(pb, spherical_mapping->yaw);
1710 avio_wb32(pb, spherical_mapping->pitch);
1711 avio_wb32(pb, spherical_mapping->roll);
1713 switch (spherical_mapping->projection) {
1714 case AV_SPHERICAL_EQUIRECTANGULAR:
1715 case AV_SPHERICAL_EQUIRECTANGULAR_TILE:
1716 avio_wb32(pb, 28); /* size */
1717 ffio_wfourcc(pb, "equi");
1718 avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1719 avio_wb32(pb, spherical_mapping->bound_top);
1720 avio_wb32(pb, spherical_mapping->bound_bottom);
1721 avio_wb32(pb, spherical_mapping->bound_left);
1722 avio_wb32(pb, spherical_mapping->bound_right);
1724 case AV_SPHERICAL_CUBEMAP:
1725 avio_wb32(pb, 20); /* size */
1726 ffio_wfourcc(pb, "cbmp");
1727 avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1728 avio_wb32(pb, 0); /* layout */
1729 avio_wb32(pb, spherical_mapping->padding); /* padding */
1732 update_size(pb, proj_pos);
1734 return update_size(pb, sv3d_pos);
1737 static int mov_write_pasp_tag(AVIOContext *pb, MOVTrack *track)
1740 av_reduce(&sar.num, &sar.den, track->par->sample_aspect_ratio.num,
1741 track->par->sample_aspect_ratio.den, INT_MAX);
1744 ffio_wfourcc(pb, "pasp");
1745 avio_wb32(pb, sar.num);
1746 avio_wb32(pb, sar.den);
1750 static int mov_write_gama_tag(AVIOContext *pb, MOVTrack *track, double gamma)
1755 gamma = avpriv_get_gamma_from_trc(track->par->color_trc);
1757 av_log(pb, AV_LOG_DEBUG, "gamma value %g\n", gamma);
1760 gama = (uint32_t)lrint((double)(1<<16) * gamma);
1761 av_log(pb, AV_LOG_DEBUG, "writing gama value %"PRId32"\n", gama);
1763 av_assert0(track->mode == MODE_MOV);
1765 ffio_wfourcc(pb, "gama");
1766 avio_wb32(pb, gama);
1770 av_log(pb, AV_LOG_WARNING, "gamma value unknown, unable to write gama atom\n");
1775 static int mov_write_colr_tag(AVIOContext *pb, MOVTrack *track)
1777 // Ref (MOV): https://developer.apple.com/library/mac/technotes/tn2162/_index.html#//apple_ref/doc/uid/DTS40013070-CH1-TNTAG9
1778 // Ref (MP4): ISO/IEC 14496-12:2012
1780 if (track->par->color_primaries == AVCOL_PRI_UNSPECIFIED &&
1781 track->par->color_trc == AVCOL_TRC_UNSPECIFIED &&
1782 track->par->color_space == AVCOL_SPC_UNSPECIFIED) {
1783 if ((track->par->width >= 1920 && track->par->height >= 1080)
1784 || (track->par->width == 1280 && track->par->height == 720)) {
1785 av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming bt709\n");
1786 track->par->color_primaries = AVCOL_PRI_BT709;
1787 } else if (track->par->width == 720 && track->height == 576) {
1788 av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming bt470bg\n");
1789 track->par->color_primaries = AVCOL_PRI_BT470BG;
1790 } else if (track->par->width == 720 &&
1791 (track->height == 486 || track->height == 480)) {
1792 av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming smpte170\n");
1793 track->par->color_primaries = AVCOL_PRI_SMPTE170M;
1795 av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, unable to assume anything\n");
1797 switch (track->par->color_primaries) {
1798 case AVCOL_PRI_BT709:
1799 track->par->color_trc = AVCOL_TRC_BT709;
1800 track->par->color_space = AVCOL_SPC_BT709;
1802 case AVCOL_PRI_SMPTE170M:
1803 case AVCOL_PRI_BT470BG:
1804 track->par->color_trc = AVCOL_TRC_BT709;
1805 track->par->color_space = AVCOL_SPC_SMPTE170M;
1810 /* We should only ever be called by MOV or MP4. */
1811 av_assert0(track->mode == MODE_MOV || track->mode == MODE_MP4);
1813 avio_wb32(pb, 18 + (track->mode == MODE_MP4));
1814 ffio_wfourcc(pb, "colr");
1815 if (track->mode == MODE_MP4)
1816 ffio_wfourcc(pb, "nclx");
1818 ffio_wfourcc(pb, "nclc");
1819 switch (track->par->color_primaries) {
1820 case AVCOL_PRI_BT709: avio_wb16(pb, 1); break;
1821 case AVCOL_PRI_SMPTE170M:
1822 case AVCOL_PRI_SMPTE240M: avio_wb16(pb, 6); break;
1823 case AVCOL_PRI_BT470BG: avio_wb16(pb, 5); break;
1824 default: avio_wb16(pb, 2);
1826 switch (track->par->color_trc) {
1827 case AVCOL_TRC_BT709: avio_wb16(pb, 1); break;
1828 case AVCOL_TRC_SMPTE170M: avio_wb16(pb, 1); break; // remapped
1829 case AVCOL_TRC_SMPTE240M: avio_wb16(pb, 7); break;
1830 default: avio_wb16(pb, 2);
1832 switch (track->par->color_space) {
1833 case AVCOL_SPC_BT709: avio_wb16(pb, 1); break;
1834 case AVCOL_SPC_BT470BG:
1835 case AVCOL_SPC_SMPTE170M: avio_wb16(pb, 6); break;
1836 case AVCOL_SPC_SMPTE240M: avio_wb16(pb, 7); break;
1837 default: avio_wb16(pb, 2);
1840 if (track->mode == MODE_MP4) {
1841 int full_range = track->par->color_range == AVCOL_RANGE_JPEG;
1842 avio_w8(pb, full_range << 7);
1849 static void find_compressor(char * compressor_name, int len, MOVTrack *track)
1851 AVDictionaryEntry *encoder;
1852 int xdcam_res = (track->par->width == 1280 && track->par->height == 720)
1853 || (track->par->width == 1440 && track->par->height == 1080)
1854 || (track->par->width == 1920 && track->par->height == 1080);
1856 if (track->mode == MODE_MOV &&
1857 (encoder = av_dict_get(track->st->metadata, "encoder", NULL, 0))) {
1858 av_strlcpy(compressor_name, encoder->value, 32);
1859 } else if (track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO && xdcam_res) {
1860 int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE;
1861 AVStream *st = track->st;
1862 int rate = defined_frame_rate(NULL, st);
1863 av_strlcatf(compressor_name, len, "XDCAM");
1864 if (track->par->format == AV_PIX_FMT_YUV422P) {
1865 av_strlcatf(compressor_name, len, " HD422");
1866 } else if(track->par->width == 1440) {
1867 av_strlcatf(compressor_name, len, " HD");
1869 av_strlcatf(compressor_name, len, " EX");
1871 av_strlcatf(compressor_name, len, " %d%c", track->par->height, interlaced ? 'i' : 'p');
1873 av_strlcatf(compressor_name, len, "%d", rate * (interlaced + 1));
1877 static int mov_write_video_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
1879 int64_t pos = avio_tell(pb);
1880 char compressor_name[32] = { 0 };
1883 avio_wb32(pb, 0); /* size */
1884 if (mov->encryption_scheme != MOV_ENC_NONE) {
1885 ffio_wfourcc(pb, "encv");
1887 avio_wl32(pb, track->tag); // store it byteswapped
1889 avio_wb32(pb, 0); /* Reserved */
1890 avio_wb16(pb, 0); /* Reserved */
1891 avio_wb16(pb, 1); /* Data-reference index */
1893 avio_wb16(pb, 0); /* Codec stream version */
1894 avio_wb16(pb, 0); /* Codec stream revision (=0) */
1895 if (track->mode == MODE_MOV) {
1896 ffio_wfourcc(pb, "FFMP"); /* Vendor */
1897 if (track->par->codec_id == AV_CODEC_ID_RAWVIDEO) {
1898 avio_wb32(pb, 0); /* Temporal Quality */
1899 avio_wb32(pb, 0x400); /* Spatial Quality = lossless*/
1901 avio_wb32(pb, 0x200); /* Temporal Quality = normal */
1902 avio_wb32(pb, 0x200); /* Spatial Quality = normal */
1905 avio_wb32(pb, 0); /* Reserved */
1906 avio_wb32(pb, 0); /* Reserved */
1907 avio_wb32(pb, 0); /* Reserved */
1909 avio_wb16(pb, track->par->width); /* Video width */
1910 avio_wb16(pb, track->height); /* Video height */
1911 avio_wb32(pb, 0x00480000); /* Horizontal resolution 72dpi */
1912 avio_wb32(pb, 0x00480000); /* Vertical resolution 72dpi */
1913 avio_wb32(pb, 0); /* Data size (= 0) */
1914 avio_wb16(pb, 1); /* Frame count (= 1) */
1916 /* FIXME not sure, ISO 14496-1 draft where it shall be set to 0 */
1917 find_compressor(compressor_name, 32, track);
1918 avio_w8(pb, strlen(compressor_name));
1919 avio_write(pb, compressor_name, 31);
1921 if (track->mode == MODE_MOV && track->par->bits_per_coded_sample)
1922 avio_wb16(pb, track->par->bits_per_coded_sample |
1923 (track->par->format == AV_PIX_FMT_GRAY8 ? 0x20 : 0));
1925 avio_wb16(pb, 0x18); /* Reserved */
1927 if (track->mode == MODE_MOV && track->par->format == AV_PIX_FMT_PAL8) {
1928 int pal_size = 1 << track->par->bits_per_coded_sample;
1930 avio_wb16(pb, 0); /* Color table ID */
1931 avio_wb32(pb, 0); /* Color table seed */
1932 avio_wb16(pb, 0x8000); /* Color table flags */
1933 avio_wb16(pb, pal_size - 1); /* Color table size (zero-relative) */
1934 for (i = 0; i < pal_size; i++) {
1935 uint32_t rgb = track->palette[i];
1936 uint16_t r = (rgb >> 16) & 0xff;
1937 uint16_t g = (rgb >> 8) & 0xff;
1938 uint16_t b = rgb & 0xff;
1940 avio_wb16(pb, (r << 8) | r);
1941 avio_wb16(pb, (g << 8) | g);
1942 avio_wb16(pb, (b << 8) | b);
1945 avio_wb16(pb, 0xffff); /* Reserved */
1947 if (track->tag == MKTAG('m','p','4','v'))
1948 mov_write_esds_tag(pb, track);
1949 else if (track->par->codec_id == AV_CODEC_ID_H263)
1950 mov_write_d263_tag(pb);
1951 else if (track->par->codec_id == AV_CODEC_ID_AVUI ||
1952 track->par->codec_id == AV_CODEC_ID_SVQ3) {
1953 mov_write_extradata_tag(pb, track);
1955 } else if (track->par->codec_id == AV_CODEC_ID_DNXHD) {
1956 mov_write_avid_tag(pb, track);
1958 } else if (track->par->codec_id == AV_CODEC_ID_HEVC)
1959 mov_write_hvcc_tag(pb, track);
1960 else if (track->par->codec_id == AV_CODEC_ID_H264 && !TAG_IS_AVCI(track->tag)) {
1961 mov_write_avcc_tag(pb, track);
1962 if (track->mode == MODE_IPOD)
1963 mov_write_uuid_tag_ipod(pb);
1964 } else if (track->par->codec_id == AV_CODEC_ID_VP9) {
1965 mov_write_vpcc_tag(mov->fc, pb, track);
1966 } else if (track->par->codec_id == AV_CODEC_ID_VC1 && track->vos_len > 0)
1967 mov_write_dvc1_tag(pb, track);
1968 else if (track->par->codec_id == AV_CODEC_ID_VP6F ||
1969 track->par->codec_id == AV_CODEC_ID_VP6A) {
1970 /* Don't write any potential extradata here - the cropping
1971 * is signalled via the normal width/height fields. */
1972 } else if (track->par->codec_id == AV_CODEC_ID_R10K) {
1973 if (track->par->codec_tag == MKTAG('R','1','0','k'))
1974 mov_write_dpxe_tag(pb, track);
1975 } else if (track->vos_len > 0)
1976 mov_write_glbl_tag(pb, track);
1978 if (track->par->codec_id != AV_CODEC_ID_H264 &&
1979 track->par->codec_id != AV_CODEC_ID_MPEG4 &&
1980 track->par->codec_id != AV_CODEC_ID_DNXHD) {
1981 int field_order = track->par->field_order;
1983 #if FF_API_LAVF_AVCTX
1984 FF_DISABLE_DEPRECATION_WARNINGS
1985 if (field_order != track->st->codec->field_order && track->st->codec->field_order != AV_FIELD_UNKNOWN)
1986 field_order = track->st->codec->field_order;
1987 FF_ENABLE_DEPRECATION_WARNINGS
1990 if (field_order != AV_FIELD_UNKNOWN)
1991 mov_write_fiel_tag(pb, track, field_order);
1994 if (mov->flags & FF_MOV_FLAG_WRITE_GAMA) {
1995 if (track->mode == MODE_MOV)
1996 mov_write_gama_tag(pb, track, mov->gamma);
1998 av_log(mov->fc, AV_LOG_WARNING, "Not writing 'gama' atom. Format is not MOV.\n");
2000 if (mov->flags & FF_MOV_FLAG_WRITE_COLR) {
2001 if (track->mode == MODE_MOV || track->mode == MODE_MP4)
2002 mov_write_colr_tag(pb, track);
2004 av_log(mov->fc, AV_LOG_WARNING, "Not writing 'colr' atom. Format is not MOV or MP4.\n");
2007 if (track->mode == MODE_MP4 && mov->fc->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL) {
2008 AVStereo3D* stereo_3d = (AVStereo3D*) av_stream_get_side_data(track->st, AV_PKT_DATA_STEREO3D, NULL);
2009 AVSphericalMapping* spherical_mapping = (AVSphericalMapping*)av_stream_get_side_data(track->st, AV_PKT_DATA_SPHERICAL, NULL);
2012 mov_write_st3d_tag(pb, stereo_3d);
2013 if (spherical_mapping)
2014 mov_write_sv3d_tag(mov->fc, pb, spherical_mapping);
2017 if (track->par->sample_aspect_ratio.den && track->par->sample_aspect_ratio.num) {
2018 mov_write_pasp_tag(pb, track);
2021 if (mov->encryption_scheme != MOV_ENC_NONE) {
2022 ff_mov_cenc_write_sinf_tag(track, pb, mov->encryption_kid);
2025 /* extra padding for avid stsd */
2026 /* https://developer.apple.com/library/mac/documentation/QuickTime/QTFF/QTFFChap2/qtff2.html#//apple_ref/doc/uid/TP40000939-CH204-61112 */
2030 return update_size(pb, pos);
2033 static int mov_write_rtp_tag(AVIOContext *pb, MOVTrack *track)
2035 int64_t pos = avio_tell(pb);
2036 avio_wb32(pb, 0); /* size */
2037 ffio_wfourcc(pb, "rtp ");
2038 avio_wb32(pb, 0); /* Reserved */
2039 avio_wb16(pb, 0); /* Reserved */
2040 avio_wb16(pb, 1); /* Data-reference index */
2042 avio_wb16(pb, 1); /* Hint track version */
2043 avio_wb16(pb, 1); /* Highest compatible version */
2044 avio_wb32(pb, track->max_packet_size); /* Max packet size */
2046 avio_wb32(pb, 12); /* size */
2047 ffio_wfourcc(pb, "tims");
2048 avio_wb32(pb, track->timescale);
2050 return update_size(pb, pos);
2053 static int mov_write_source_reference_tag(AVIOContext *pb, MOVTrack *track, const char *reel_name)
2055 uint64_t str_size =strlen(reel_name);
2056 int64_t pos = avio_tell(pb);
2058 if (str_size >= UINT16_MAX){
2059 av_log(NULL, AV_LOG_ERROR, "reel_name length %"PRIu64" is too large\n", str_size);
2061 return AVERROR(EINVAL);
2064 avio_wb32(pb, 0); /* size */
2065 ffio_wfourcc(pb, "name"); /* Data format */
2066 avio_wb16(pb, str_size); /* string size */
2067 avio_wb16(pb, track->language); /* langcode */
2068 avio_write(pb, reel_name, str_size); /* reel name */
2069 return update_size(pb,pos);
2072 static int mov_write_tmcd_tag(AVIOContext *pb, MOVTrack *track)
2074 int64_t pos = avio_tell(pb);
2078 AVDictionaryEntry *t = NULL;
2080 if (!track->st->avg_frame_rate.num || !track->st->avg_frame_rate.den) {
2081 #if FF_API_LAVF_AVCTX
2082 FF_DISABLE_DEPRECATION_WARNINGS
2083 frame_duration = av_rescale(track->timescale, track->st->codec->time_base.num, track->st->codec->time_base.den);
2084 nb_frames = ROUNDED_DIV(track->st->codec->time_base.den, track->st->codec->time_base.num);
2085 FF_ENABLE_DEPRECATION_WARNINGS
2087 av_log(NULL, AV_LOG_ERROR, "avg_frame_rate not set for tmcd track.\n");
2088 return AVERROR(EINVAL);
2091 frame_duration = av_rescale(track->timescale, track->st->avg_frame_rate.num, track->st->avg_frame_rate.den);
2092 nb_frames = ROUNDED_DIV(track->st->avg_frame_rate.den, track->st->avg_frame_rate.num);
2095 if (nb_frames > 255) {
2096 av_log(NULL, AV_LOG_ERROR, "fps %d is too large\n", nb_frames);
2097 return AVERROR(EINVAL);
2100 avio_wb32(pb, 0); /* size */
2101 ffio_wfourcc(pb, "tmcd"); /* Data format */
2102 avio_wb32(pb, 0); /* Reserved */
2103 avio_wb32(pb, 1); /* Data reference index */
2104 avio_wb32(pb, 0); /* Flags */
2105 avio_wb32(pb, track->timecode_flags); /* Flags (timecode) */
2106 avio_wb32(pb, track->timescale); /* Timescale */
2107 avio_wb32(pb, frame_duration); /* Frame duration */
2108 avio_w8(pb, nb_frames); /* Number of frames */
2109 avio_w8(pb, 0); /* Reserved */
2111 t = av_dict_get(track->st->metadata, "reel_name", NULL, 0);
2112 if (t && utf8len(t->value) && track->mode != MODE_MP4)
2113 mov_write_source_reference_tag(pb, track, t->value);
2115 avio_wb16(pb, 0); /* zero size */
2118 avio_wb32(pb, 0); /* size */
2119 ffio_wfourcc(pb, "tmcd"); /* Data format */
2120 avio_wb32(pb, 0); /* Reserved */
2121 avio_wb32(pb, 1); /* Data reference index */
2122 if (track->par->extradata_size)
2123 avio_write(pb, track->par->extradata, track->par->extradata_size);
2125 return update_size(pb, pos);
2128 static int mov_write_stsd_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
2130 int64_t pos = avio_tell(pb);
2131 avio_wb32(pb, 0); /* size */
2132 ffio_wfourcc(pb, "stsd");
2133 avio_wb32(pb, 0); /* version & flags */
2134 avio_wb32(pb, 1); /* entry count */
2135 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO)
2136 mov_write_video_tag(pb, mov, track);
2137 else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
2138 mov_write_audio_tag(s, pb, mov, track);
2139 else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)
2140 mov_write_subtitle_tag(pb, track);
2141 else if (track->par->codec_tag == MKTAG('r','t','p',' '))
2142 mov_write_rtp_tag(pb, track);
2143 else if (track->par->codec_tag == MKTAG('t','m','c','d'))
2144 mov_write_tmcd_tag(pb, track);
2145 return update_size(pb, pos);
2148 static int mov_write_ctts_tag(AVIOContext *pb, MOVTrack *track)
2150 MOVStts *ctts_entries;
2151 uint32_t entries = 0;
2155 ctts_entries = av_malloc_array((track->entry + 1), sizeof(*ctts_entries)); /* worst case */
2157 return AVERROR(ENOMEM);
2158 ctts_entries[0].count = 1;
2159 ctts_entries[0].duration = track->cluster[0].cts;
2160 for (i = 1; i < track->entry; i++) {
2161 if (track->cluster[i].cts == ctts_entries[entries].duration) {
2162 ctts_entries[entries].count++; /* compress */
2165 ctts_entries[entries].duration = track->cluster[i].cts;
2166 ctts_entries[entries].count = 1;
2169 entries++; /* last one */
2170 atom_size = 16 + (entries * 8);
2171 avio_wb32(pb, atom_size); /* size */
2172 ffio_wfourcc(pb, "ctts");
2173 avio_wb32(pb, 0); /* version & flags */
2174 avio_wb32(pb, entries); /* entry count */
2175 for (i = 0; i < entries; i++) {
2176 avio_wb32(pb, ctts_entries[i].count);
2177 avio_wb32(pb, ctts_entries[i].duration);
2179 av_free(ctts_entries);
2183 /* Time to sample atom */
2184 static int mov_write_stts_tag(AVIOContext *pb, MOVTrack *track)
2186 MOVStts *stts_entries = NULL;
2187 uint32_t entries = -1;
2191 if (track->par->codec_type == AVMEDIA_TYPE_AUDIO && !track->audio_vbr) {
2192 stts_entries = av_malloc(sizeof(*stts_entries)); /* one entry */
2194 return AVERROR(ENOMEM);
2195 stts_entries[0].count = track->sample_count;
2196 stts_entries[0].duration = 1;
2200 stts_entries = av_malloc_array(track->entry, sizeof(*stts_entries)); /* worst case */
2202 return AVERROR(ENOMEM);
2204 for (i = 0; i < track->entry; i++) {
2205 int duration = get_cluster_duration(track, i);
2206 if (i && duration == stts_entries[entries].duration) {
2207 stts_entries[entries].count++; /* compress */
2210 stts_entries[entries].duration = duration;
2211 stts_entries[entries].count = 1;
2214 entries++; /* last one */
2216 atom_size = 16 + (entries * 8);
2217 avio_wb32(pb, atom_size); /* size */
2218 ffio_wfourcc(pb, "stts");
2219 avio_wb32(pb, 0); /* version & flags */
2220 avio_wb32(pb, entries); /* entry count */
2221 for (i = 0; i < entries; i++) {
2222 avio_wb32(pb, stts_entries[i].count);
2223 avio_wb32(pb, stts_entries[i].duration);
2225 av_free(stts_entries);
2229 static int mov_write_dref_tag(AVIOContext *pb)
2231 avio_wb32(pb, 28); /* size */
2232 ffio_wfourcc(pb, "dref");
2233 avio_wb32(pb, 0); /* version & flags */
2234 avio_wb32(pb, 1); /* entry count */
2236 avio_wb32(pb, 0xc); /* size */
2237 //FIXME add the alis and rsrc atom
2238 ffio_wfourcc(pb, "url ");
2239 avio_wb32(pb, 1); /* version & flags */
2244 static int mov_preroll_write_stbl_atoms(AVIOContext *pb, MOVTrack *track)
2248 int16_t roll_distance;
2249 int group_description_index;
2252 struct sgpd_entry *sgpd_entries = NULL;
2257 const int OPUS_SEEK_PREROLL_MS = 80;
2258 int roll_samples = av_rescale_q(OPUS_SEEK_PREROLL_MS,
2259 (AVRational){1, 1000},
2260 (AVRational){1, 48000});
2263 sgpd_entries = av_malloc_array(track->entry, sizeof(*sgpd_entries));
2265 return AVERROR(ENOMEM);
2268 av_assert0(track->par->codec_id == AV_CODEC_ID_OPUS);
2270 for (i = 0; i < track->entry; i++) {
2271 int roll_samples_remaining = roll_samples;
2273 for (j = i - 1; j >= 0; j--) {
2274 roll_samples_remaining -= get_cluster_duration(track, j);
2276 if (roll_samples_remaining <= 0)
2279 /* We don't have enough preceeding samples to compute a valid
2280 roll_distance here, so this sample can't be independently
2282 if (roll_samples_remaining > 0)
2284 /* Verify distance is a minimum of 2 (60ms) packets and a maximum of
2285 32 (2.5ms) packets. */
2286 av_assert0(distance == 0 || (distance >= 2 && distance <= 32));
2287 if (i && distance == sgpd_entries[entries].roll_distance) {
2288 sgpd_entries[entries].count++;
2291 sgpd_entries[entries].count = 1;
2292 sgpd_entries[entries].roll_distance = distance;
2293 sgpd_entries[entries].group_description_index = distance ? ++group : 0;
2299 av_free(sgpd_entries);
2303 /* Write sgpd tag */
2304 avio_wb32(pb, 24 + (group * 2)); /* size */
2305 ffio_wfourcc(pb, "sgpd");
2306 avio_wb32(pb, 1 << 24); /* fullbox */
2307 ffio_wfourcc(pb, "roll");
2308 avio_wb32(pb, 2); /* default_length */
2309 avio_wb32(pb, group); /* entry_count */
2310 for (i = 0; i < entries; i++) {
2311 if (sgpd_entries[i].group_description_index) {
2312 avio_wb16(pb, -sgpd_entries[i].roll_distance); /* roll_distance */
2316 /* Write sbgp tag */
2317 avio_wb32(pb, 20 + (entries * 8)); /* size */
2318 ffio_wfourcc(pb, "sbgp");
2319 avio_wb32(pb, 0); /* fullbox */
2320 ffio_wfourcc(pb, "roll");
2321 avio_wb32(pb, entries); /* entry_count */
2322 for (i = 0; i < entries; i++) {
2323 avio_wb32(pb, sgpd_entries[i].count); /* sample_count */
2324 avio_wb32(pb, sgpd_entries[i].group_description_index); /* group_description_index */
2327 av_free(sgpd_entries);
2331 static int mov_write_stbl_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
2333 int64_t pos = avio_tell(pb);
2336 avio_wb32(pb, 0); /* size */
2337 ffio_wfourcc(pb, "stbl");
2338 mov_write_stsd_tag(s, pb, mov, track);
2339 mov_write_stts_tag(pb, track);
2340 if ((track->par->codec_type == AVMEDIA_TYPE_VIDEO ||
2341 track->par->codec_tag == MKTAG('r','t','p',' ')) &&
2342 track->has_keyframes && track->has_keyframes < track->entry)
2343 mov_write_stss_tag(pb, track, MOV_SYNC_SAMPLE);
2344 if (track->mode == MODE_MOV && track->flags & MOV_TRACK_STPS)
2345 mov_write_stss_tag(pb, track, MOV_PARTIAL_SYNC_SAMPLE);
2346 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO &&
2347 track->flags & MOV_TRACK_CTTS && track->entry) {
2349 if ((ret = mov_write_ctts_tag(pb, track)) < 0)
2352 mov_write_stsc_tag(pb, track);
2353 mov_write_stsz_tag(pb, track);
2354 mov_write_stco_tag(pb, track);
2355 if (mov->encryption_scheme == MOV_ENC_CENC_AES_CTR) {
2356 ff_mov_cenc_write_stbl_atoms(&track->cenc, pb);
2358 if (track->par->codec_id == AV_CODEC_ID_OPUS) {
2359 mov_preroll_write_stbl_atoms(pb, track);
2361 return update_size(pb, pos);
2364 static int mov_write_dinf_tag(AVIOContext *pb)
2366 int64_t pos = avio_tell(pb);
2367 avio_wb32(pb, 0); /* size */
2368 ffio_wfourcc(pb, "dinf");
2369 mov_write_dref_tag(pb);
2370 return update_size(pb, pos);
2373 static int mov_write_nmhd_tag(AVIOContext *pb)
2376 ffio_wfourcc(pb, "nmhd");
2381 static int mov_write_tcmi_tag(AVIOContext *pb, MOVTrack *track)
2383 int64_t pos = avio_tell(pb);
2384 const char *font = "Lucida Grande";
2385 avio_wb32(pb, 0); /* size */
2386 ffio_wfourcc(pb, "tcmi"); /* timecode media information atom */
2387 avio_wb32(pb, 0); /* version & flags */
2388 avio_wb16(pb, 0); /* text font */
2389 avio_wb16(pb, 0); /* text face */
2390 avio_wb16(pb, 12); /* text size */
2391 avio_wb16(pb, 0); /* (unknown, not in the QT specs...) */
2392 avio_wb16(pb, 0x0000); /* text color (red) */
2393 avio_wb16(pb, 0x0000); /* text color (green) */
2394 avio_wb16(pb, 0x0000); /* text color (blue) */
2395 avio_wb16(pb, 0xffff); /* background color (red) */
2396 avio_wb16(pb, 0xffff); /* background color (green) */
2397 avio_wb16(pb, 0xffff); /* background color (blue) */
2398 avio_w8(pb, strlen(font)); /* font len (part of the pascal string) */
2399 avio_write(pb, font, strlen(font)); /* font name */
2400 return update_size(pb, pos);
2403 static int mov_write_gmhd_tag(AVIOContext *pb, MOVTrack *track)
2405 int64_t pos = avio_tell(pb);
2406 avio_wb32(pb, 0); /* size */
2407 ffio_wfourcc(pb, "gmhd");
2408 avio_wb32(pb, 0x18); /* gmin size */
2409 ffio_wfourcc(pb, "gmin");/* generic media info */
2410 avio_wb32(pb, 0); /* version & flags */
2411 avio_wb16(pb, 0x40); /* graphics mode = */
2412 avio_wb16(pb, 0x8000); /* opColor (r?) */
2413 avio_wb16(pb, 0x8000); /* opColor (g?) */
2414 avio_wb16(pb, 0x8000); /* opColor (b?) */
2415 avio_wb16(pb, 0); /* balance */
2416 avio_wb16(pb, 0); /* reserved */
2419 * This special text atom is required for
2420 * Apple Quicktime chapters. The contents
2421 * don't appear to be documented, so the
2422 * bytes are copied verbatim.
2424 if (track->tag != MKTAG('c','6','0','8')) {
2425 avio_wb32(pb, 0x2C); /* size */
2426 ffio_wfourcc(pb, "text");
2427 avio_wb16(pb, 0x01);
2428 avio_wb32(pb, 0x00);
2429 avio_wb32(pb, 0x00);
2430 avio_wb32(pb, 0x00);
2431 avio_wb32(pb, 0x01);
2432 avio_wb32(pb, 0x00);
2433 avio_wb32(pb, 0x00);
2434 avio_wb32(pb, 0x00);
2435 avio_wb32(pb, 0x00004000);
2436 avio_wb16(pb, 0x0000);
2439 if (track->par->codec_tag == MKTAG('t','m','c','d')) {
2440 int64_t tmcd_pos = avio_tell(pb);
2441 avio_wb32(pb, 0); /* size */
2442 ffio_wfourcc(pb, "tmcd");
2443 mov_write_tcmi_tag(pb, track);
2444 update_size(pb, tmcd_pos);
2446 return update_size(pb, pos);
2449 static int mov_write_smhd_tag(AVIOContext *pb)
2451 avio_wb32(pb, 16); /* size */
2452 ffio_wfourcc(pb, "smhd");
2453 avio_wb32(pb, 0); /* version & flags */
2454 avio_wb16(pb, 0); /* reserved (balance, normally = 0) */
2455 avio_wb16(pb, 0); /* reserved */
2459 static int mov_write_vmhd_tag(AVIOContext *pb)
2461 avio_wb32(pb, 0x14); /* size (always 0x14) */
2462 ffio_wfourcc(pb, "vmhd");
2463 avio_wb32(pb, 0x01); /* version & flags */
2464 avio_wb64(pb, 0); /* reserved (graphics mode = copy) */
2468 static int is_clcp_track(MOVTrack *track)
2470 return track->tag == MKTAG('c','7','0','8') ||
2471 track->tag == MKTAG('c','6','0','8');
2474 static int mov_write_hdlr_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
2476 const char *hdlr, *descr = NULL, *hdlr_type = NULL;
2477 int64_t pos = avio_tell(pb);
2481 descr = "DataHandler";
2484 hdlr = (track->mode == MODE_MOV) ? "mhlr" : "\0\0\0\0";
2485 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
2487 descr = "VideoHandler";
2488 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
2490 descr = "SoundHandler";
2491 } else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE) {
2492 if (is_clcp_track(track)) {
2494 descr = "ClosedCaptionHandler";
2496 if (track->tag == MKTAG('t','x','3','g')) {
2498 } else if (track->tag == MKTAG('m','p','4','s')) {
2503 descr = "SubtitleHandler";
2505 } else if (track->par->codec_tag == MKTAG('r','t','p',' ')) {
2507 descr = "HintHandler";
2508 } else if (track->par->codec_tag == MKTAG('t','m','c','d')) {
2510 descr = "TimeCodeHandler";
2512 av_log(s, AV_LOG_WARNING,
2513 "Unknown hldr_type for %s, writing dummy values\n",
2514 av_fourcc2str(track->par->codec_tag));
2517 // hdlr.name is used by some players to identify the content title
2518 // of the track. So if an alternate handler description is
2519 // specified, use it.
2520 AVDictionaryEntry *t;
2521 t = av_dict_get(track->st->metadata, "handler", NULL, 0);
2522 if (t && utf8len(t->value))
2527 avio_wb32(pb, 0); /* size */
2528 ffio_wfourcc(pb, "hdlr");
2529 avio_wb32(pb, 0); /* Version & flags */
2530 avio_write(pb, hdlr, 4); /* handler */
2531 ffio_wfourcc(pb, hdlr_type); /* handler type */
2532 avio_wb32(pb, 0); /* reserved */
2533 avio_wb32(pb, 0); /* reserved */
2534 avio_wb32(pb, 0); /* reserved */
2535 if (!track || track->mode == MODE_MOV)
2536 avio_w8(pb, strlen(descr)); /* pascal string */
2537 avio_write(pb, descr, strlen(descr)); /* handler description */
2538 if (track && track->mode != MODE_MOV)
2539 avio_w8(pb, 0); /* c string */
2540 return update_size(pb, pos);
2543 static int mov_write_hmhd_tag(AVIOContext *pb)
2545 /* This atom must be present, but leaving the values at zero
2546 * seems harmless. */
2547 avio_wb32(pb, 28); /* size */
2548 ffio_wfourcc(pb, "hmhd");
2549 avio_wb32(pb, 0); /* version, flags */
2550 avio_wb16(pb, 0); /* maxPDUsize */
2551 avio_wb16(pb, 0); /* avgPDUsize */
2552 avio_wb32(pb, 0); /* maxbitrate */
2553 avio_wb32(pb, 0); /* avgbitrate */
2554 avio_wb32(pb, 0); /* reserved */
2558 static int mov_write_minf_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
2560 int64_t pos = avio_tell(pb);
2563 avio_wb32(pb, 0); /* size */
2564 ffio_wfourcc(pb, "minf");
2565 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO)
2566 mov_write_vmhd_tag(pb);
2567 else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
2568 mov_write_smhd_tag(pb);
2569 else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE) {
2570 if (track->tag == MKTAG('t','e','x','t') || is_clcp_track(track)) {
2571 mov_write_gmhd_tag(pb, track);
2573 mov_write_nmhd_tag(pb);
2575 } else if (track->tag == MKTAG('r','t','p',' ')) {
2576 mov_write_hmhd_tag(pb);
2577 } else if (track->tag == MKTAG('t','m','c','d')) {
2578 if (track->mode != MODE_MOV)
2579 mov_write_nmhd_tag(pb);
2581 mov_write_gmhd_tag(pb, track);
2583 if (track->mode == MODE_MOV) /* FIXME: Why do it for MODE_MOV only ? */
2584 mov_write_hdlr_tag(s, pb, NULL);
2585 mov_write_dinf_tag(pb);
2586 if ((ret = mov_write_stbl_tag(s, pb, mov, track)) < 0)
2588 return update_size(pb, pos);
2591 static int mov_write_mdhd_tag(AVIOContext *pb, MOVMuxContext *mov,
2594 int version = track->track_duration < INT32_MAX ? 0 : 1;
2596 if (track->mode == MODE_ISM)
2599 (version == 1) ? avio_wb32(pb, 44) : avio_wb32(pb, 32); /* size */
2600 ffio_wfourcc(pb, "mdhd");
2601 avio_w8(pb, version);
2602 avio_wb24(pb, 0); /* flags */
2604 avio_wb64(pb, track->time);
2605 avio_wb64(pb, track->time);
2607 avio_wb32(pb, track->time); /* creation time */
2608 avio_wb32(pb, track->time); /* modification time */
2610 avio_wb32(pb, track->timescale); /* time scale (sample rate for audio) */
2611 if (!track->entry && mov->mode == MODE_ISM)
2612 (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
2613 else if (!track->entry)
2614 (version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0);
2616 (version == 1) ? avio_wb64(pb, track->track_duration) : avio_wb32(pb, track->track_duration); /* duration */
2617 avio_wb16(pb, track->language); /* language */
2618 avio_wb16(pb, 0); /* reserved (quality) */
2620 if (version != 0 && track->mode == MODE_MOV) {
2621 av_log(NULL, AV_LOG_ERROR,
2622 "FATAL error, file duration too long for timebase, this file will not be\n"
2623 "playable with quicktime. Choose a different timebase or a different\n"
2624 "container format\n");
2630 static int mov_write_mdia_tag(AVFormatContext *s, AVIOContext *pb,
2631 MOVMuxContext *mov, MOVTrack *track)
2633 int64_t pos = avio_tell(pb);
2636 avio_wb32(pb, 0); /* size */
2637 ffio_wfourcc(pb, "mdia");
2638 mov_write_mdhd_tag(pb, mov, track);
2639 mov_write_hdlr_tag(s, pb, track);
2640 if ((ret = mov_write_minf_tag(s, pb, mov, track)) < 0)
2642 return update_size(pb, pos);
2645 /* transformation matrix
2649 static void write_matrix(AVIOContext *pb, int16_t a, int16_t b, int16_t c,
2650 int16_t d, int16_t tx, int16_t ty)
2652 avio_wb32(pb, a << 16); /* 16.16 format */
2653 avio_wb32(pb, b << 16); /* 16.16 format */
2654 avio_wb32(pb, 0); /* u in 2.30 format */
2655 avio_wb32(pb, c << 16); /* 16.16 format */
2656 avio_wb32(pb, d << 16); /* 16.16 format */
2657 avio_wb32(pb, 0); /* v in 2.30 format */
2658 avio_wb32(pb, tx << 16); /* 16.16 format */
2659 avio_wb32(pb, ty << 16); /* 16.16 format */
2660 avio_wb32(pb, 1 << 30); /* w in 2.30 format */
2663 static int mov_write_tkhd_tag(AVIOContext *pb, MOVMuxContext *mov,
2664 MOVTrack *track, AVStream *st)
2666 int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE,
2667 track->timescale, AV_ROUND_UP);
2668 int version = duration < INT32_MAX ? 0 : 1;
2669 int flags = MOV_TKHD_FLAG_IN_MOVIE;
2673 uint32_t *display_matrix = NULL;
2674 int display_matrix_size, i;
2677 if (mov->per_stream_grouping)
2680 group = st->codecpar->codec_type;
2682 display_matrix = (uint32_t*)av_stream_get_side_data(st, AV_PKT_DATA_DISPLAYMATRIX,
2683 &display_matrix_size);
2684 if (display_matrix && display_matrix_size < 9 * sizeof(*display_matrix))
2685 display_matrix = NULL;
2688 if (track->flags & MOV_TRACK_ENABLED)
2689 flags |= MOV_TKHD_FLAG_ENABLED;
2691 if (track->mode == MODE_ISM)
2694 (version == 1) ? avio_wb32(pb, 104) : avio_wb32(pb, 92); /* size */
2695 ffio_wfourcc(pb, "tkhd");
2696 avio_w8(pb, version);
2697 avio_wb24(pb, flags);
2699 avio_wb64(pb, track->time);
2700 avio_wb64(pb, track->time);
2702 avio_wb32(pb, track->time); /* creation time */
2703 avio_wb32(pb, track->time); /* modification time */
2705 avio_wb32(pb, track->track_id); /* track-id */
2706 avio_wb32(pb, 0); /* reserved */
2707 if (!track->entry && mov->mode == MODE_ISM)
2708 (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
2709 else if (!track->entry)
2710 (version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0);
2712 (version == 1) ? avio_wb64(pb, duration) : avio_wb32(pb, duration);
2714 avio_wb32(pb, 0); /* reserved */
2715 avio_wb32(pb, 0); /* reserved */
2716 avio_wb16(pb, 0); /* layer */
2717 avio_wb16(pb, group); /* alternate group) */
2718 /* Volume, only for audio */
2719 if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
2720 avio_wb16(pb, 0x0100);
2723 avio_wb16(pb, 0); /* reserved */
2725 /* Matrix structure */
2726 #if FF_API_OLD_ROTATE_API
2727 if (st && st->metadata) {
2728 AVDictionaryEntry *rot = av_dict_get(st->metadata, "rotate", NULL, 0);
2729 rotation = (rot && rot->value) ? atoi(rot->value) : 0;
2732 if (display_matrix) {
2733 for (i = 0; i < 9; i++)
2734 avio_wb32(pb, display_matrix[i]);
2735 #if FF_API_OLD_ROTATE_API
2736 } else if (rotation == 90) {
2737 write_matrix(pb, 0, 1, -1, 0, track->par->height, 0);
2738 } else if (rotation == 180) {
2739 write_matrix(pb, -1, 0, 0, -1, track->par->width, track->par->height);
2740 } else if (rotation == 270) {
2741 write_matrix(pb, 0, -1, 1, 0, 0, track->par->width);
2744 write_matrix(pb, 1, 0, 0, 1, 0, 0);
2746 /* Track width and height, for visual only */
2747 if (st && (track->par->codec_type == AVMEDIA_TYPE_VIDEO ||
2748 track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)) {
2749 int64_t track_width_1616;
2750 if (track->mode == MODE_MOV) {
2751 track_width_1616 = track->par->width * 0x10000ULL;
2753 track_width_1616 = av_rescale(st->sample_aspect_ratio.num,
2754 track->par->width * 0x10000LL,
2755 st->sample_aspect_ratio.den);
2756 if (!track_width_1616 ||
2757 track->height != track->par->height ||
2758 track_width_1616 > UINT32_MAX)
2759 track_width_1616 = track->par->width * 0x10000ULL;
2761 if (track_width_1616 > UINT32_MAX) {
2762 av_log(mov->fc, AV_LOG_WARNING, "track width is too large\n");
2763 track_width_1616 = 0;
2765 avio_wb32(pb, track_width_1616);
2766 if (track->height > 0xFFFF) {
2767 av_log(mov->fc, AV_LOG_WARNING, "track height is too large\n");
2770 avio_wb32(pb, track->height * 0x10000U);
2778 static int mov_write_tapt_tag(AVIOContext *pb, MOVTrack *track)
2780 int32_t width = av_rescale(track->par->sample_aspect_ratio.num, track->par->width,
2781 track->par->sample_aspect_ratio.den);
2783 int64_t pos = avio_tell(pb);
2785 avio_wb32(pb, 0); /* size */
2786 ffio_wfourcc(pb, "tapt");
2789 ffio_wfourcc(pb, "clef");
2791 avio_wb32(pb, width << 16);
2792 avio_wb32(pb, track->par->height << 16);
2795 ffio_wfourcc(pb, "prof");
2797 avio_wb32(pb, width << 16);
2798 avio_wb32(pb, track->par->height << 16);
2801 ffio_wfourcc(pb, "enof");
2803 avio_wb32(pb, track->par->width << 16);
2804 avio_wb32(pb, track->par->height << 16);
2806 return update_size(pb, pos);
2809 // This box seems important for the psp playback ... without it the movie seems to hang
2810 static int mov_write_edts_tag(AVIOContext *pb, MOVMuxContext *mov,
2813 int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE,
2814 track->timescale, AV_ROUND_UP);
2815 int version = duration < INT32_MAX ? 0 : 1;
2816 int entry_size, entry_count, size;
2817 int64_t delay, start_ct = track->start_cts;
2818 int64_t start_dts = track->start_dts;
2821 if (start_dts != track->cluster[0].dts || start_ct != track->cluster[0].cts) {
2823 av_log(mov->fc, AV_LOG_DEBUG,
2824 "EDTS using dts:%"PRId64" cts:%d instead of dts:%"PRId64" cts:%"PRId64" tid:%d\n",
2825 track->cluster[0].dts, track->cluster[0].cts,
2826 start_dts, start_ct, track->track_id);
2827 start_dts = track->cluster[0].dts;
2828 start_ct = track->cluster[0].cts;
2832 delay = av_rescale_rnd(start_dts + start_ct, MOV_TIMESCALE,
2833 track->timescale, AV_ROUND_DOWN);
2834 version |= delay < INT32_MAX ? 0 : 1;
2836 entry_size = (version == 1) ? 20 : 12;
2837 entry_count = 1 + (delay > 0);
2838 size = 24 + entry_count * entry_size;
2840 /* write the atom data */
2841 avio_wb32(pb, size);
2842 ffio_wfourcc(pb, "edts");
2843 avio_wb32(pb, size - 8);
2844 ffio_wfourcc(pb, "elst");
2845 avio_w8(pb, version);
2846 avio_wb24(pb, 0); /* flags */
2848 avio_wb32(pb, entry_count);
2849 if (delay > 0) { /* add an empty edit to delay presentation */
2850 /* In the positive delay case, the delay includes the cts
2851 * offset, and the second edit list entry below trims out
2852 * the same amount from the actual content. This makes sure
2853 * that the offset last sample is included in the edit
2854 * list duration as well. */
2856 avio_wb64(pb, delay);
2859 avio_wb32(pb, delay);
2862 avio_wb32(pb, 0x00010000);
2864 /* Avoid accidentally ending up with start_ct = -1 which has got a
2865 * special meaning. Normally start_ct should end up positive or zero
2866 * here, but use FFMIN in case dts is a small positive integer
2867 * rounded to 0 when represented in MOV_TIMESCALE units. */
2868 av_assert0(av_rescale_rnd(start_dts, MOV_TIMESCALE, track->timescale, AV_ROUND_DOWN) <= 0);
2869 start_ct = -FFMIN(start_dts, 0);
2870 /* Note, this delay is calculated from the pts of the first sample,
2871 * ensuring that we don't reduce the duration for cases with
2876 /* For fragmented files, we don't know the full length yet. Setting
2877 * duration to 0 allows us to only specify the offset, including
2878 * the rest of the content (from all future fragments) without specifying
2879 * an explicit duration. */
2880 if (mov->flags & FF_MOV_FLAG_FRAGMENT)
2885 avio_wb64(pb, duration);
2886 avio_wb64(pb, start_ct);
2888 avio_wb32(pb, duration);
2889 avio_wb32(pb, start_ct);
2891 avio_wb32(pb, 0x00010000);
2895 static int mov_write_tref_tag(AVIOContext *pb, MOVTrack *track)
2897 avio_wb32(pb, 20); // size
2898 ffio_wfourcc(pb, "tref");
2899 avio_wb32(pb, 12); // size (subatom)
2900 avio_wl32(pb, track->tref_tag);
2901 avio_wb32(pb, track->tref_id);
2905 // goes at the end of each track! ... Critical for PSP playback ("Incompatible data" without it)
2906 static int mov_write_uuid_tag_psp(AVIOContext *pb, MOVTrack *mov)
2908 avio_wb32(pb, 0x34); /* size ... reports as 28 in mp4box! */
2909 ffio_wfourcc(pb, "uuid");
2910 ffio_wfourcc(pb, "USMT");
2911 avio_wb32(pb, 0x21d24fce);
2912 avio_wb32(pb, 0xbb88695c);
2913 avio_wb32(pb, 0xfac9c740);
2914 avio_wb32(pb, 0x1c); // another size here!
2915 ffio_wfourcc(pb, "MTDT");
2916 avio_wb32(pb, 0x00010012);
2917 avio_wb32(pb, 0x0a);
2918 avio_wb32(pb, 0x55c40000);
2924 static int mov_write_udta_sdp(AVIOContext *pb, MOVTrack *track)
2926 AVFormatContext *ctx = track->rtp_ctx;
2927 char buf[1000] = "";
2930 ff_sdp_write_media(buf, sizeof(buf), ctx->streams[0], track->src_track,
2931 NULL, NULL, 0, 0, ctx);
2932 av_strlcatf(buf, sizeof(buf), "a=control:streamid=%d\r\n", track->track_id);
2935 avio_wb32(pb, len + 24);
2936 ffio_wfourcc(pb, "udta");
2937 avio_wb32(pb, len + 16);
2938 ffio_wfourcc(pb, "hnti");
2939 avio_wb32(pb, len + 8);
2940 ffio_wfourcc(pb, "sdp ");
2941 avio_write(pb, buf, len);
2945 static int mov_write_track_metadata(AVIOContext *pb, AVStream *st,
2946 const char *tag, const char *str)
2948 int64_t pos = avio_tell(pb);
2949 AVDictionaryEntry *t = av_dict_get(st->metadata, str, NULL, 0);
2950 if (!t || !utf8len(t->value))
2953 avio_wb32(pb, 0); /* size */
2954 ffio_wfourcc(pb, tag); /* type */
2955 avio_write(pb, t->value, strlen(t->value)); /* UTF8 string value */
2956 return update_size(pb, pos);
2959 static int mov_write_track_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
2962 AVIOContext *pb_buf;
2969 ret = avio_open_dyn_buf(&pb_buf);
2973 if (mov->mode & MODE_MP4)
2974 mov_write_track_metadata(pb_buf, st, "name", "title");
2976 if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) {
2977 avio_wb32(pb, size + 8);
2978 ffio_wfourcc(pb, "udta");
2979 avio_write(pb, buf, size);
2986 static int mov_write_trak_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov,
2987 MOVTrack *track, AVStream *st)
2989 int64_t pos = avio_tell(pb);
2990 int entry_backup = track->entry;
2991 int chunk_backup = track->chunkCount;
2994 /* If we want to have an empty moov, but some samples already have been
2995 * buffered (delay_moov), pretend that no samples have been written yet. */
2996 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV)
2997 track->chunkCount = track->entry = 0;
2999 avio_wb32(pb, 0); /* size */
3000 ffio_wfourcc(pb, "trak");
3001 mov_write_tkhd_tag(pb, mov, track, st);
3003 av_assert2(mov->use_editlist >= 0);
3005 if (track->start_dts != AV_NOPTS_VALUE) {
3006 if (mov->use_editlist)
3007 mov_write_edts_tag(pb, mov, track); // PSP Movies and several other cases require edts box
3008 else if ((track->entry && track->cluster[0].dts) || track->mode == MODE_PSP || is_clcp_track(track))
3009 av_log(mov->fc, AV_LOG_WARNING,
3010 "Not writing any edit list even though one would have been required\n");
3013 if (track->tref_tag)
3014 mov_write_tref_tag(pb, track);
3016 if ((ret = mov_write_mdia_tag(s, pb, mov, track)) < 0)
3018 if (track->mode == MODE_PSP)
3019 mov_write_uuid_tag_psp(pb, track); // PSP Movies require this uuid box
3020 if (track->tag == MKTAG('r','t','p',' '))
3021 mov_write_udta_sdp(pb, track);
3022 if (track->mode == MODE_MOV) {
3023 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
3024 double sample_aspect_ratio = av_q2d(st->sample_aspect_ratio);
3025 if (st->sample_aspect_ratio.num && 1.0 != sample_aspect_ratio) {
3026 mov_write_tapt_tag(pb, track);
3029 if (is_clcp_track(track) && st->sample_aspect_ratio.num) {
3030 mov_write_tapt_tag(pb, track);
3033 mov_write_track_udta_tag(pb, mov, st);
3034 track->entry = entry_backup;
3035 track->chunkCount = chunk_backup;
3036 return update_size(pb, pos);
3039 static int mov_write_iods_tag(AVIOContext *pb, MOVMuxContext *mov)
3041 int i, has_audio = 0, has_video = 0;
3042 int64_t pos = avio_tell(pb);
3043 int audio_profile = mov->iods_audio_profile;
3044 int video_profile = mov->iods_video_profile;
3045 for (i = 0; i < mov->nb_streams; i++) {
3046 if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
3047 has_audio |= mov->tracks[i].par->codec_type == AVMEDIA_TYPE_AUDIO;
3048 has_video |= mov->tracks[i].par->codec_type == AVMEDIA_TYPE_VIDEO;
3051 if (audio_profile < 0)
3052 audio_profile = 0xFF - has_audio;
3053 if (video_profile < 0)
3054 video_profile = 0xFF - has_video;
3055 avio_wb32(pb, 0x0); /* size */
3056 ffio_wfourcc(pb, "iods");
3057 avio_wb32(pb, 0); /* version & flags */
3058 put_descr(pb, 0x10, 7);
3059 avio_wb16(pb, 0x004f);
3062 avio_w8(pb, audio_profile);
3063 avio_w8(pb, video_profile);
3065 return update_size(pb, pos);
3068 static int mov_write_trex_tag(AVIOContext *pb, MOVTrack *track)
3070 avio_wb32(pb, 0x20); /* size */
3071 ffio_wfourcc(pb, "trex");
3072 avio_wb32(pb, 0); /* version & flags */
3073 avio_wb32(pb, track->track_id); /* track ID */
3074 avio_wb32(pb, 1); /* default sample description index */
3075 avio_wb32(pb, 0); /* default sample duration */
3076 avio_wb32(pb, 0); /* default sample size */
3077 avio_wb32(pb, 0); /* default sample flags */
3081 static int mov_write_mvex_tag(AVIOContext *pb, MOVMuxContext *mov)
3083 int64_t pos = avio_tell(pb);
3085 avio_wb32(pb, 0x0); /* size */
3086 ffio_wfourcc(pb, "mvex");
3087 for (i = 0; i < mov->nb_streams; i++)
3088 mov_write_trex_tag(pb, &mov->tracks[i]);
3089 return update_size(pb, pos);
3092 static int mov_write_mvhd_tag(AVIOContext *pb, MOVMuxContext *mov)
3094 int max_track_id = 1, i;
3095 int64_t max_track_len = 0;
3098 for (i = 0; i < mov->nb_streams; i++) {
3099 if (mov->tracks[i].entry > 0 && mov->tracks[i].timescale) {
3100 int64_t max_track_len_temp = av_rescale_rnd(mov->tracks[i].track_duration,
3102 mov->tracks[i].timescale,
3104 if (max_track_len < max_track_len_temp)
3105 max_track_len = max_track_len_temp;
3106 if (max_track_id < mov->tracks[i].track_id)
3107 max_track_id = mov->tracks[i].track_id;
3110 /* If using delay_moov, make sure the output is the same as if no
3111 * samples had been written yet. */
3112 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
3117 version = max_track_len < UINT32_MAX ? 0 : 1;
3118 avio_wb32(pb, version == 1 ? 120 : 108); /* size */
3120 ffio_wfourcc(pb, "mvhd");
3121 avio_w8(pb, version);
3122 avio_wb24(pb, 0); /* flags */
3124 avio_wb64(pb, mov->time);
3125 avio_wb64(pb, mov->time);
3127 avio_wb32(pb, mov->time); /* creation time */
3128 avio_wb32(pb, mov->time); /* modification time */
3130 avio_wb32(pb, MOV_TIMESCALE);
3131 (version == 1) ? avio_wb64(pb, max_track_len) : avio_wb32(pb, max_track_len); /* duration of longest track */
3133 avio_wb32(pb, 0x00010000); /* reserved (preferred rate) 1.0 = normal */
3134 avio_wb16(pb, 0x0100); /* reserved (preferred volume) 1.0 = normal */
3135 avio_wb16(pb, 0); /* reserved */
3136 avio_wb32(pb, 0); /* reserved */
3137 avio_wb32(pb, 0); /* reserved */
3139 /* Matrix structure */
3140 write_matrix(pb, 1, 0, 0, 1, 0, 0);
3142 avio_wb32(pb, 0); /* reserved (preview time) */
3143 avio_wb32(pb, 0); /* reserved (preview duration) */
3144 avio_wb32(pb, 0); /* reserved (poster time) */
3145 avio_wb32(pb, 0); /* reserved (selection time) */
3146 avio_wb32(pb, 0); /* reserved (selection duration) */
3147 avio_wb32(pb, 0); /* reserved (current time) */
3148 avio_wb32(pb, max_track_id + 1); /* Next track id */
3152 static int mov_write_itunes_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov,
3155 avio_wb32(pb, 33); /* size */
3156 ffio_wfourcc(pb, "hdlr");
3159 ffio_wfourcc(pb, "mdir");
3160 ffio_wfourcc(pb, "appl");
3167 /* helper function to write a data tag with the specified string as data */
3168 static int mov_write_string_data_tag(AVIOContext *pb, const char *data, int lang, int long_style)
3171 int size = 16 + strlen(data);
3172 avio_wb32(pb, size); /* size */
3173 ffio_wfourcc(pb, "data");
3176 avio_write(pb, data, strlen(data));
3180 lang = ff_mov_iso639_to_lang("und", 1);
3181 avio_wb16(pb, strlen(data)); /* string length */
3182 avio_wb16(pb, lang);
3183 avio_write(pb, data, strlen(data));
3184 return strlen(data) + 4;
3188 static int mov_write_string_tag(AVIOContext *pb, const char *name,
3189 const char *value, int lang, int long_style)
3192 if (value && value[0]) {
3193 int64_t pos = avio_tell(pb);
3194 avio_wb32(pb, 0); /* size */
3195 ffio_wfourcc(pb, name);
3196 mov_write_string_data_tag(pb, value, lang, long_style);
3197 size = update_size(pb, pos);
3202 static AVDictionaryEntry *get_metadata_lang(AVFormatContext *s,
3203 const char *tag, int *lang)
3206 AVDictionaryEntry *t, *t2 = NULL;
3211 if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
3214 len = strlen(t->key);
3215 snprintf(tag2, sizeof(tag2), "%s-", tag);
3216 while ((t2 = av_dict_get(s->metadata, tag2, t2, AV_DICT_IGNORE_SUFFIX))) {
3217 len2 = strlen(t2->key);
3218 if (len2 == len + 4 && !strcmp(t->value, t2->value)
3219 && (l = ff_mov_iso639_to_lang(&t2->key[len2 - 3], 1)) >= 0) {
3227 static int mov_write_string_metadata(AVFormatContext *s, AVIOContext *pb,
3228 const char *name, const char *tag,
3232 AVDictionaryEntry *t = get_metadata_lang(s, tag, &lang);
3235 return mov_write_string_tag(pb, name, t->value, lang, long_style);
3238 /* iTunes bpm number */
3239 static int mov_write_tmpo_tag(AVIOContext *pb, AVFormatContext *s)
3241 AVDictionaryEntry *t = av_dict_get(s->metadata, "tmpo", NULL, 0);
3242 int size = 0, tmpo = t ? atoi(t->value) : 0;
3245 avio_wb32(pb, size);
3246 ffio_wfourcc(pb, "tmpo");
3247 avio_wb32(pb, size-8); /* size */
3248 ffio_wfourcc(pb, "data");
3249 avio_wb32(pb, 0x15); //type specifier
3251 avio_wb16(pb, tmpo); // data
3256 /* 3GPP TS 26.244 */
3257 static int mov_write_loci_tag(AVFormatContext *s, AVIOContext *pb)
3260 int64_t pos = avio_tell(pb);
3261 double latitude, longitude, altitude;
3262 int32_t latitude_fix, longitude_fix, altitude_fix;
3263 AVDictionaryEntry *t = get_metadata_lang(s, "location", &lang);
3264 const char *ptr, *place = "";
3266 static const char *astronomical_body = "earth";
3271 longitude = strtod(ptr, &end);
3273 av_log(s, AV_LOG_WARNING, "malformed location metadata\n");
3277 latitude = strtod(ptr, &end);
3279 av_log(s, AV_LOG_WARNING, "malformed location metadata\n");
3283 altitude = strtod(ptr, &end);
3284 /* If no altitude was present, the default 0 should be fine */
3288 latitude_fix = (int32_t) ((1 << 16) * latitude);
3289 longitude_fix = (int32_t) ((1 << 16) * longitude);
3290 altitude_fix = (int32_t) ((1 << 16) * altitude);
3292 avio_wb32(pb, 0); /* size */
3293 ffio_wfourcc(pb, "loci"); /* type */
3294 avio_wb32(pb, 0); /* version + flags */
3295 avio_wb16(pb, lang);
3296 avio_write(pb, place, strlen(place) + 1);
3297 avio_w8(pb, 0); /* role of place (0 == shooting location, 1 == real location, 2 == fictional location) */
3298 avio_wb32(pb, latitude_fix);
3299 avio_wb32(pb, longitude_fix);
3300 avio_wb32(pb, altitude_fix);
3301 avio_write(pb, astronomical_body, strlen(astronomical_body) + 1);
3302 avio_w8(pb, 0); /* additional notes, null terminated string */
3304 return update_size(pb, pos);
3307 /* iTunes track or disc number */
3308 static int mov_write_trkn_tag(AVIOContext *pb, MOVMuxContext *mov,
3309 AVFormatContext *s, int disc)
3311 AVDictionaryEntry *t = av_dict_get(s->metadata,
3312 disc ? "disc" : "track",
3314 int size = 0, track = t ? atoi(t->value) : 0;
3317 char *slash = strchr(t->value, '/');
3319 tracks = atoi(slash + 1);
3320 avio_wb32(pb, 32); /* size */
3321 ffio_wfourcc(pb, disc ? "disk" : "trkn");
3322 avio_wb32(pb, 24); /* size */
3323 ffio_wfourcc(pb, "data");
3324 avio_wb32(pb, 0); // 8 bytes empty
3326 avio_wb16(pb, 0); // empty
3327 avio_wb16(pb, track); // track / disc number
3328 avio_wb16(pb, tracks); // total track / disc number
3329 avio_wb16(pb, 0); // empty
3335 static int mov_write_int8_metadata(AVFormatContext *s, AVIOContext *pb,
3336 const char *name, const char *tag,
3339 AVDictionaryEntry *t = NULL;
3341 int size = 24 + len;
3343 if (len != 1 && len != 4)
3346 if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
3348 num = atoi(t->value);
3350 avio_wb32(pb, size);
3351 ffio_wfourcc(pb, name);
3352 avio_wb32(pb, size - 8);
3353 ffio_wfourcc(pb, "data");
3354 avio_wb32(pb, 0x15);
3356 if (len==4) avio_wb32(pb, num);
3357 else avio_w8 (pb, num);
3362 /* iTunes meta data list */
3363 static int mov_write_ilst_tag(AVIOContext *pb, MOVMuxContext *mov,
3366 int64_t pos = avio_tell(pb);
3367 avio_wb32(pb, 0); /* size */
3368 ffio_wfourcc(pb, "ilst");
3369 mov_write_string_metadata(s, pb, "\251nam", "title" , 1);
3370 mov_write_string_metadata(s, pb, "\251ART", "artist" , 1);
3371 mov_write_string_metadata(s, pb, "aART", "album_artist", 1);
3372 mov_write_string_metadata(s, pb, "\251wrt", "composer" , 1);
3373 mov_write_string_metadata(s, pb, "\251alb", "album" , 1);
3374 mov_write_string_metadata(s, pb, "\251day", "date" , 1);
3375 if (!mov_write_string_metadata(s, pb, "\251too", "encoding_tool", 1)) {
3376 if (!(s->flags & AVFMT_FLAG_BITEXACT))
3377 mov_write_string_tag(pb, "\251too", LIBAVFORMAT_IDENT, 0, 1);
3379 mov_write_string_metadata(s, pb, "\251cmt", "comment" , 1);
3380 mov_write_string_metadata(s, pb, "\251gen", "genre" , 1);
3381 mov_write_string_metadata(s, pb, "\251cpy", "copyright", 1);
3382 mov_write_string_metadata(s, pb, "\251grp", "grouping" , 1);
3383 mov_write_string_metadata(s, pb, "\251lyr", "lyrics" , 1);
3384 mov_write_string_metadata(s, pb, "desc", "description",1);
3385 mov_write_string_metadata(s, pb, "ldes", "synopsis" , 1);
3386 mov_write_string_metadata(s, pb, "tvsh", "show" , 1);
3387 mov_write_string_metadata(s, pb, "tven", "episode_id",1);
3388 mov_write_string_metadata(s, pb, "tvnn", "network" , 1);
3389 mov_write_int8_metadata (s, pb, "tves", "episode_sort",4);
3390 mov_write_int8_metadata (s, pb, "tvsn", "season_number",4);
3391 mov_write_int8_metadata (s, pb, "stik", "media_type",1);
3392 mov_write_int8_metadata (s, pb, "hdvd", "hd_video", 1);
3393 mov_write_int8_metadata (s, pb, "pgap", "gapless_playback",1);
3394 mov_write_int8_metadata (s, pb, "cpil", "compilation", 1);
3395 mov_write_trkn_tag(pb, mov, s, 0); // track number
3396 mov_write_trkn_tag(pb, mov, s, 1); // disc number
3397 mov_write_tmpo_tag(pb, s);
3398 return update_size(pb, pos);
3401 static int mov_write_mdta_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov,
3404 avio_wb32(pb, 33); /* size */
3405 ffio_wfourcc(pb, "hdlr");
3408 ffio_wfourcc(pb, "mdta");
3416 static int mov_write_mdta_keys_tag(AVIOContext *pb, MOVMuxContext *mov,
3419 AVDictionaryEntry *t = NULL;
3420 int64_t pos = avio_tell(pb);
3421 int64_t curpos, entry_pos;
3424 avio_wb32(pb, 0); /* size */
3425 ffio_wfourcc(pb, "keys");
3427 entry_pos = avio_tell(pb);
3428 avio_wb32(pb, 0); /* entry count */
3430 while (t = av_dict_get(s->metadata, "", t, AV_DICT_IGNORE_SUFFIX)) {
3431 avio_wb32(pb, strlen(t->key) + 8);
3432 ffio_wfourcc(pb, "mdta");
3433 avio_write(pb, t->key, strlen(t->key));
3436 curpos = avio_tell(pb);
3437 avio_seek(pb, entry_pos, SEEK_SET);
3438 avio_wb32(pb, count); // rewrite entry count
3439 avio_seek(pb, curpos, SEEK_SET);
3441 return update_size(pb, pos);
3444 static int mov_write_mdta_ilst_tag(AVIOContext *pb, MOVMuxContext *mov,
3447 AVDictionaryEntry *t = NULL;
3448 int64_t pos = avio_tell(pb);
3449 int count = 1; /* keys are 1-index based */
3451 avio_wb32(pb, 0); /* size */
3452 ffio_wfourcc(pb, "ilst");
3454 while (t = av_dict_get(s->metadata, "", t, AV_DICT_IGNORE_SUFFIX)) {
3455 int64_t entry_pos = avio_tell(pb);
3456 avio_wb32(pb, 0); /* size */
3457 avio_wb32(pb, count); /* key */
3458 mov_write_string_data_tag(pb, t->value, 0, 1);
3459 update_size(pb, entry_pos);
3462 return update_size(pb, pos);
3465 /* meta data tags */
3466 static int mov_write_meta_tag(AVIOContext *pb, MOVMuxContext *mov,
3470 int64_t pos = avio_tell(pb);
3471 avio_wb32(pb, 0); /* size */
3472 ffio_wfourcc(pb, "meta");
3474 if (mov->flags & FF_MOV_FLAG_USE_MDTA) {
3475 mov_write_mdta_hdlr_tag(pb, mov, s);
3476 mov_write_mdta_keys_tag(pb, mov, s);
3477 mov_write_mdta_ilst_tag(pb, mov, s);
3480 /* iTunes metadata tag */
3481 mov_write_itunes_hdlr_tag(pb, mov, s);
3482 mov_write_ilst_tag(pb, mov, s);
3484 size = update_size(pb, pos);
3488 static int mov_write_raw_metadata_tag(AVFormatContext *s, AVIOContext *pb,
3489 const char *name, const char *key)
3492 AVDictionaryEntry *t;
3494 if (!(t = av_dict_get(s->metadata, key, NULL, 0)))
3497 len = strlen(t->value);
3500 avio_wb32(pb, size);
3501 ffio_wfourcc(pb, name);
3502 avio_write(pb, t->value, len);
3508 static int ascii_to_wc(AVIOContext *pb, const uint8_t *b)
3512 GET_UTF8(val, *b++, return -1;)
3515 avio_wb16(pb, 0x00);
3519 static uint16_t language_code(const char *str)
3521 return (((str[0] - 0x60) & 0x1F) << 10) +
3522 (((str[1] - 0x60) & 0x1F) << 5) +
3523 (( str[2] - 0x60) & 0x1F);
3526 static int mov_write_3gp_udta_tag(AVIOContext *pb, AVFormatContext *s,
3527 const char *tag, const char *str)
3529 int64_t pos = avio_tell(pb);
3530 AVDictionaryEntry *t = av_dict_get(s->metadata, str, NULL, 0);
3531 if (!t || !utf8len(t->value))
3533 avio_wb32(pb, 0); /* size */
3534 ffio_wfourcc(pb, tag); /* type */
3535 avio_wb32(pb, 0); /* version + flags */
3536 if (!strcmp(tag, "yrrc"))
3537 avio_wb16(pb, atoi(t->value));
3539 avio_wb16(pb, language_code("eng")); /* language */
3540 avio_write(pb, t->value, strlen(t->value) + 1); /* UTF8 string value */
3541 if (!strcmp(tag, "albm") &&
3542 (t = av_dict_get(s->metadata, "track", NULL, 0)))
3543 avio_w8(pb, atoi(t->value));
3545 return update_size(pb, pos);
3548 static int mov_write_chpl_tag(AVIOContext *pb, AVFormatContext *s)
3550 int64_t pos = avio_tell(pb);
3551 int i, nb_chapters = FFMIN(s->nb_chapters, 255);
3553 avio_wb32(pb, 0); // size
3554 ffio_wfourcc(pb, "chpl");
3555 avio_wb32(pb, 0x01000000); // version + flags
3556 avio_wb32(pb, 0); // unknown
3557 avio_w8(pb, nb_chapters);
3559 for (i = 0; i < nb_chapters; i++) {
3560 AVChapter *c = s->chapters[i];
3561 AVDictionaryEntry *t;
3562 avio_wb64(pb, av_rescale_q(c->start, c->time_base, (AVRational){1,10000000}));
3564 if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
3565 int len = FFMIN(strlen(t->value), 255);
3567 avio_write(pb, t->value, len);
3571 return update_size(pb, pos);
3574 static int mov_write_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
3577 AVIOContext *pb_buf;
3581 ret = avio_open_dyn_buf(&pb_buf);
3585 if (mov->mode & MODE_3GP) {
3586 mov_write_3gp_udta_tag(pb_buf, s, "perf", "artist");
3587 mov_write_3gp_udta_tag(pb_buf, s, "titl", "title");
3588 mov_write_3gp_udta_tag(pb_buf, s, "auth", "author");
3589 mov_write_3gp_udta_tag(pb_buf, s, "gnre", "genre");
3590 mov_write_3gp_udta_tag(pb_buf, s, "dscp", "comment");
3591 mov_write_3gp_udta_tag(pb_buf, s, "albm", "album");
3592 mov_write_3gp_udta_tag(pb_buf, s, "cprt", "copyright");
3593 mov_write_3gp_udta_tag(pb_buf, s, "yrrc", "date");
3594 mov_write_loci_tag(s, pb_buf);
3595 } 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
3596 mov_write_string_metadata(s, pb_buf, "\251ART", "artist", 0);
3597 mov_write_string_metadata(s, pb_buf, "\251nam", "title", 0);
3598 mov_write_string_metadata(s, pb_buf, "\251aut", "author", 0);
3599 mov_write_string_metadata(s, pb_buf, "\251alb", "album", 0);
3600 mov_write_string_metadata(s, pb_buf, "\251day", "date", 0);
3601 mov_write_string_metadata(s, pb_buf, "\251swr", "encoder", 0);
3602 // currently ignored by mov.c
3603 mov_write_string_metadata(s, pb_buf, "\251des", "comment", 0);
3604 // add support for libquicktime, this atom is also actually read by mov.c
3605 mov_write_string_metadata(s, pb_buf, "\251cmt", "comment", 0);
3606 mov_write_string_metadata(s, pb_buf, "\251gen", "genre", 0);
3607 mov_write_string_metadata(s, pb_buf, "\251cpy", "copyright", 0);
3608 mov_write_string_metadata(s, pb_buf, "\251mak", "make", 0);
3609 mov_write_string_metadata(s, pb_buf, "\251mod", "model", 0);
3610 mov_write_string_metadata(s, pb_buf, "\251xyz", "location", 0);
3611 mov_write_raw_metadata_tag(s, pb_buf, "XMP_", "xmp");
3613 /* iTunes meta data */
3614 mov_write_meta_tag(pb_buf, mov, s);
3615 mov_write_loci_tag(s, pb_buf);
3618 if (s->nb_chapters && !(mov->flags & FF_MOV_FLAG_DISABLE_CHPL))
3619 mov_write_chpl_tag(pb_buf, s);
3621 if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) {
3622 avio_wb32(pb, size + 8);
3623 ffio_wfourcc(pb, "udta");
3624 avio_write(pb, buf, size);
3631 static void mov_write_psp_udta_tag(AVIOContext *pb,
3632 const char *str, const char *lang, int type)
3634 int len = utf8len(str) + 1;
3637 avio_wb16(pb, len * 2 + 10); /* size */
3638 avio_wb32(pb, type); /* type */
3639 avio_wb16(pb, language_code(lang)); /* language */
3640 avio_wb16(pb, 0x01); /* ? */
3641 ascii_to_wc(pb, str);
3644 static int mov_write_uuidusmt_tag(AVIOContext *pb, AVFormatContext *s)
3646 AVDictionaryEntry *title = av_dict_get(s->metadata, "title", NULL, 0);
3650 pos = avio_tell(pb);
3651 avio_wb32(pb, 0); /* size placeholder*/
3652 ffio_wfourcc(pb, "uuid");
3653 ffio_wfourcc(pb, "USMT");
3654 avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
3655 avio_wb32(pb, 0xbb88695c);
3656 avio_wb32(pb, 0xfac9c740);
3658 pos2 = avio_tell(pb);
3659 avio_wb32(pb, 0); /* size placeholder*/
3660 ffio_wfourcc(pb, "MTDT");
3664 avio_wb16(pb, 0x0C); /* size */
3665 avio_wb32(pb, 0x0B); /* type */
3666 avio_wb16(pb, language_code("und")); /* language */
3667 avio_wb16(pb, 0x0); /* ? */
3668 avio_wb16(pb, 0x021C); /* data */
3670 if (!(s->flags & AVFMT_FLAG_BITEXACT))
3671 mov_write_psp_udta_tag(pb, LIBAVCODEC_IDENT, "eng", 0x04);
3672 mov_write_psp_udta_tag(pb, title->value, "eng", 0x01);
3673 mov_write_psp_udta_tag(pb, "2006/04/01 11:11:11", "und", 0x03);
3675 update_size(pb, pos2);
3676 return update_size(pb, pos);
3682 static void build_chunks(MOVTrack *trk)
3685 MOVIentry *chunk = &trk->cluster[0];
3686 uint64_t chunkSize = chunk->size;
3687 chunk->chunkNum = 1;
3688 if (trk->chunkCount)
3690 trk->chunkCount = 1;
3691 for (i = 1; i<trk->entry; i++){
3692 if (chunk->pos + chunkSize == trk->cluster[i].pos &&
3693 chunkSize + trk->cluster[i].size < (1<<20)){
3694 chunkSize += trk->cluster[i].size;
3695 chunk->samples_in_chunk += trk->cluster[i].entries;
3697 trk->cluster[i].chunkNum = chunk->chunkNum+1;
3698 chunk=&trk->cluster[i];
3699 chunkSize = chunk->size;
3706 * Assign track ids. If option "use_stream_ids_as_track_ids" is set,
3707 * the stream ids are used as track ids.
3709 * This assumes mov->tracks and s->streams are in the same order and
3710 * there are no gaps in either of them (so mov->tracks[n] refers to
3713 * As an exception, there can be more entries in
3714 * s->streams than in mov->tracks, in which case new track ids are
3715 * generated (starting after the largest found stream id).
3717 static int mov_setup_track_ids(MOVMuxContext *mov, AVFormatContext *s)
3721 if (mov->track_ids_ok)
3724 if (mov->use_stream_ids_as_track_ids) {
3725 int next_generated_track_id = 0;
3726 for (i = 0; i < s->nb_streams; i++) {
3727 if (s->streams[i]->id > next_generated_track_id)
3728 next_generated_track_id = s->streams[i]->id;
3731 for (i = 0; i < mov->nb_streams; i++) {
3732 if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
3735 mov->tracks[i].track_id = i >= s->nb_streams ? ++next_generated_track_id : s->streams[i]->id;
3738 for (i = 0; i < mov->nb_streams; i++) {
3739 if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
3742 mov->tracks[i].track_id = i + 1;
3746 mov->track_ids_ok = 1;
3751 static int mov_write_moov_tag(AVIOContext *pb, MOVMuxContext *mov,
3755 int64_t pos = avio_tell(pb);
3756 avio_wb32(pb, 0); /* size placeholder*/
3757 ffio_wfourcc(pb, "moov");
3759 mov_setup_track_ids(mov, s);
3761 for (i = 0; i < mov->nb_streams; i++) {
3762 if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
3765 mov->tracks[i].time = mov->time;
3767 if (mov->tracks[i].entry)
3768 build_chunks(&mov->tracks[i]);
3771 if (mov->chapter_track)
3772 for (i = 0; i < s->nb_streams; i++) {
3773 mov->tracks[i].tref_tag = MKTAG('c','h','a','p');
3774 mov->tracks[i].tref_id = mov->tracks[mov->chapter_track].track_id;
3776 for (i = 0; i < mov->nb_streams; i++) {
3777 MOVTrack *track = &mov->tracks[i];
3778 if (track->tag == MKTAG('r','t','p',' ')) {
3779 track->tref_tag = MKTAG('h','i','n','t');
3780 track->tref_id = mov->tracks[track->src_track].track_id;
3781 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
3782 int * fallback, size;
3783 fallback = (int*)av_stream_get_side_data(track->st,
3784 AV_PKT_DATA_FALLBACK_TRACK,
3786 if (fallback != NULL && size == sizeof(int)) {
3787 if (*fallback >= 0 && *fallback < mov->nb_streams) {
3788 track->tref_tag = MKTAG('f','a','l','l');
3789 track->tref_id = mov->tracks[*fallback].track_id;
3794 for (i = 0; i < mov->nb_streams; i++) {
3795 if (mov->tracks[i].tag == MKTAG('t','m','c','d')) {
3796 int src_trk = mov->tracks[i].src_track;
3797 mov->tracks[src_trk].tref_tag = mov->tracks[i].tag;
3798 mov->tracks[src_trk].tref_id = mov->tracks[i].track_id;
3799 //src_trk may have a different timescale than the tmcd track
3800 mov->tracks[i].track_duration = av_rescale(mov->tracks[src_trk].track_duration,
3801 mov->tracks[i].timescale,
3802 mov->tracks[src_trk].timescale);
3806 mov_write_mvhd_tag(pb, mov);
3807 if (mov->mode != MODE_MOV && !mov->iods_skip)
3808 mov_write_iods_tag(pb, mov);
3809 for (i = 0; i < mov->nb_streams; i++) {
3810 if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_FRAGMENT) {
3811 int ret = mov_write_trak_tag(s, pb, mov, &(mov->tracks[i]), i < s->nb_streams ? s->streams[i] : NULL);
3816 if (mov->flags & FF_MOV_FLAG_FRAGMENT)
3817 mov_write_mvex_tag(pb, mov); /* QuickTime requires trak to precede this */
3819 if (mov->mode == MODE_PSP)
3820 mov_write_uuidusmt_tag(pb, s);
3822 mov_write_udta_tag(pb, mov, s);
3824 return update_size(pb, pos);
3827 static void param_write_int(AVIOContext *pb, const char *name, int value)
3829 avio_printf(pb, "<param name=\"%s\" value=\"%d\" valuetype=\"data\"/>\n", name, value);
3832 static void param_write_string(AVIOContext *pb, const char *name, const char *value)
3834 avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, value);
3837 static void param_write_hex(AVIOContext *pb, const char *name, const uint8_t *value, int len)
3840 len = FFMIN(sizeof(buf) / 2 - 1, len);
3841 ff_data_to_hex(buf, value, len, 0);
3842 buf[2 * len] = '\0';
3843 avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, buf);
3846 static int mov_write_isml_manifest(AVIOContext *pb, MOVMuxContext *mov, AVFormatContext *s)
3848 int64_t pos = avio_tell(pb);
3850 int64_t manifest_bit_rate = 0;
3851 AVCPBProperties *props = NULL;
3853 static const uint8_t uuid[] = {
3854 0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd,
3855 0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66
3859 ffio_wfourcc(pb, "uuid");
3860 avio_write(pb, uuid, sizeof(uuid));
3863 avio_printf(pb, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
3864 avio_printf(pb, "<smil xmlns=\"http://www.w3.org/2001/SMIL20/Language\">\n");
3865 avio_printf(pb, "<head>\n");
3866 if (!(mov->fc->flags & AVFMT_FLAG_BITEXACT))
3867 avio_printf(pb, "<meta name=\"creator\" content=\"%s\" />\n",
3869 avio_printf(pb, "</head>\n");
3870 avio_printf(pb, "<body>\n");
3871 avio_printf(pb, "<switch>\n");
3873 mov_setup_track_ids(mov, s);
3875 for (i = 0; i < mov->nb_streams; i++) {
3876 MOVTrack *track = &mov->tracks[i];
3878 int track_id = track->track_id;
3879 char track_name_buf[32] = { 0 };
3881 AVStream *st = track->st;
3882 AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0);
3884 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
3886 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
3892 props = (AVCPBProperties*)av_stream_get_side_data(track->st, AV_PKT_DATA_CPB_PROPERTIES, NULL);
3894 if (track->par->bit_rate) {
3895 manifest_bit_rate = track->par->bit_rate;
3897 manifest_bit_rate = props->max_bitrate;
3900 avio_printf(pb, "<%s systemBitrate=\"%"PRId64"\">\n", type,
3902 param_write_int(pb, "systemBitrate", manifest_bit_rate);
3903 param_write_int(pb, "trackID", track_id);
3904 param_write_string(pb, "systemLanguage", lang ? lang->value : "und");
3906 /* Build track name piece by piece: */
3908 av_strlcat(track_name_buf, type, sizeof(track_name_buf));
3909 /* 2. track language, if available */
3911 av_strlcatf(track_name_buf, sizeof(track_name_buf),
3912 "_%s", lang->value);
3913 /* 3. special type suffix */
3914 /* "_cc" = closed captions, "_ad" = audio_description */
3915 if (st->disposition & AV_DISPOSITION_HEARING_IMPAIRED)
3916 av_strlcat(track_name_buf, "_cc", sizeof(track_name_buf));
3917 else if (st->disposition & AV_DISPOSITION_VISUAL_IMPAIRED)
3918 av_strlcat(track_name_buf, "_ad", sizeof(track_name_buf));
3920 param_write_string(pb, "trackName", track_name_buf);
3922 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
3923 if (track->par->codec_id == AV_CODEC_ID_H264) {
3925 int size = track->par->extradata_size;
3926 if (!ff_avc_write_annexb_extradata(track->par->extradata, &ptr,
3928 param_write_hex(pb, "CodecPrivateData",
3929 ptr ? ptr : track->par->extradata,
3933 param_write_string(pb, "FourCC", "H264");
3934 } else if (track->par->codec_id == AV_CODEC_ID_VC1) {
3935 param_write_string(pb, "FourCC", "WVC1");
3936 param_write_hex(pb, "CodecPrivateData", track->par->extradata,
3937 track->par->extradata_size);
3939 param_write_int(pb, "MaxWidth", track->par->width);
3940 param_write_int(pb, "MaxHeight", track->par->height);
3941 param_write_int(pb, "DisplayWidth", track->par->width);
3942 param_write_int(pb, "DisplayHeight", track->par->height);
3944 if (track->par->codec_id == AV_CODEC_ID_AAC) {
3945 switch (track->par->profile)
3947 case FF_PROFILE_AAC_HE_V2:
3948 param_write_string(pb, "FourCC", "AACP");
3950 case FF_PROFILE_AAC_HE:
3951 param_write_string(pb, "FourCC", "AACH");
3954 param_write_string(pb, "FourCC", "AACL");
3956 } else if (track->par->codec_id == AV_CODEC_ID_WMAPRO) {
3957 param_write_string(pb, "FourCC", "WMAP");
3959 param_write_hex(pb, "CodecPrivateData", track->par->extradata,
3960 track->par->extradata_size);
3961 param_write_int(pb, "AudioTag", ff_codec_get_tag(ff_codec_wav_tags,
3962 track->par->codec_id));
3963 param_write_int(pb, "Channels", track->par->channels);
3964 param_write_int(pb, "SamplingRate", track->par->sample_rate);
3965 param_write_int(pb, "BitsPerSample", 16);
3966 param_write_int(pb, "PacketSize", track->par->block_align ?
3967 track->par->block_align : 4);
3969 avio_printf(pb, "</%s>\n", type);
3971 avio_printf(pb, "</switch>\n");
3972 avio_printf(pb, "</body>\n");
3973 avio_printf(pb, "</smil>\n");
3975 return update_size(pb, pos);
3978 static int mov_write_mfhd_tag(AVIOContext *pb, MOVMuxContext *mov)
3981 ffio_wfourcc(pb, "mfhd");
3983 avio_wb32(pb, mov->fragments);
3987 static uint32_t get_sample_flags(MOVTrack *track, MOVIentry *entry)
3989 return entry->flags & MOV_SYNC_SAMPLE ? MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO :
3990 (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC);
3993 static int mov_write_tfhd_tag(AVIOContext *pb, MOVMuxContext *mov,
3994 MOVTrack *track, int64_t moof_offset)
3996 int64_t pos = avio_tell(pb);
3997 uint32_t flags = MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
3998 MOV_TFHD_BASE_DATA_OFFSET;
3999 if (!track->entry) {
4000 flags |= MOV_TFHD_DURATION_IS_EMPTY;
4002 flags |= MOV_TFHD_DEFAULT_FLAGS;
4004 if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET)
4005 flags &= ~MOV_TFHD_BASE_DATA_OFFSET;
4006 if (mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) {
4007 flags &= ~MOV_TFHD_BASE_DATA_OFFSET;
4008 flags |= MOV_TFHD_DEFAULT_BASE_IS_MOOF;
4011 /* Don't set a default sample size, the silverlight player refuses
4012 * to play files with that set. Don't set a default sample duration,
4013 * WMP freaks out if it is set. Don't set a base data offset, PIFF
4014 * file format says it MUST NOT be set. */
4015 if (track->mode == MODE_ISM)
4016 flags &= ~(MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
4017 MOV_TFHD_BASE_DATA_OFFSET);
4019 avio_wb32(pb, 0); /* size placeholder */
4020 ffio_wfourcc(pb, "tfhd");
4021 avio_w8(pb, 0); /* version */
4022 avio_wb24(pb, flags);
4024 avio_wb32(pb, track->track_id); /* track-id */
4025 if (flags & MOV_TFHD_BASE_DATA_OFFSET)
4026 avio_wb64(pb, moof_offset);
4027 if (flags & MOV_TFHD_DEFAULT_DURATION) {
4028 track->default_duration = get_cluster_duration(track, 0);
4029 avio_wb32(pb, track->default_duration);
4031 if (flags & MOV_TFHD_DEFAULT_SIZE) {
4032 track->default_size = track->entry ? track->cluster[0].size : 1;
4033 avio_wb32(pb, track->default_size);
4035 track->default_size = -1;
4037 if (flags & MOV_TFHD_DEFAULT_FLAGS) {
4038 /* Set the default flags based on the second sample, if available.
4039 * If the first sample is different, that can be signaled via a separate field. */
4040 if (track->entry > 1)
4041 track->default_sample_flags = get_sample_flags(track, &track->cluster[1]);
4043 track->default_sample_flags =
4044 track->par->codec_type == AVMEDIA_TYPE_VIDEO ?
4045 (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC) :
4046 MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO;
4047 avio_wb32(pb, track->default_sample_flags);
4050 return update_size(pb, pos);
4053 static int mov_write_trun_tag(AVIOContext *pb, MOVMuxContext *mov,
4054 MOVTrack *track, int moof_size,
4057 int64_t pos = avio_tell(pb);
4058 uint32_t flags = MOV_TRUN_DATA_OFFSET;
4061 for (i = first; i < end; i++) {
4062 if (get_cluster_duration(track, i) != track->default_duration)
4063 flags |= MOV_TRUN_SAMPLE_DURATION;
4064 if (track->cluster[i].size != track->default_size)
4065 flags |= MOV_TRUN_SAMPLE_SIZE;
4066 if (i > first && get_sample_flags(track, &track->cluster[i]) != track->default_sample_flags)
4067 flags |= MOV_TRUN_SAMPLE_FLAGS;
4069 if (!(flags & MOV_TRUN_SAMPLE_FLAGS) && track->entry > 0 &&
4070 get_sample_flags(track, &track->cluster[0]) != track->default_sample_flags)
4071 flags |= MOV_TRUN_FIRST_SAMPLE_FLAGS;
4072 if (track->flags & MOV_TRACK_CTTS)
4073 flags |= MOV_TRUN_SAMPLE_CTS;
4075 avio_wb32(pb, 0); /* size placeholder */
4076 ffio_wfourcc(pb, "trun");
4077 avio_w8(pb, 0); /* version */
4078 avio_wb24(pb, flags);
4080 avio_wb32(pb, end - first); /* sample count */
4081 if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET &&
4082 !(mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) &&
4084 avio_wb32(pb, 0); /* Later tracks follow immediately after the previous one */
4086 avio_wb32(pb, moof_size + 8 + track->data_offset +
4087 track->cluster[first].pos); /* data offset */
4088 if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS)
4089 avio_wb32(pb, get_sample_flags(track, &track->cluster[first]));
4091 for (i = first; i < end; i++) {
4092 if (flags & MOV_TRUN_SAMPLE_DURATION)
4093 avio_wb32(pb, get_cluster_duration(track, i));
4094 if (flags & MOV_TRUN_SAMPLE_SIZE)
4095 avio_wb32(pb, track->cluster[i].size);
4096 if (flags & MOV_TRUN_SAMPLE_FLAGS)
4097 avio_wb32(pb, get_sample_flags(track, &track->cluster[i]));
4098 if (flags & MOV_TRUN_SAMPLE_CTS)
4099 avio_wb32(pb, track->cluster[i].cts);
4102 mov->first_trun = 0;
4103 return update_size(pb, pos);
4106 static int mov_write_tfxd_tag(AVIOContext *pb, MOVTrack *track)
4108 int64_t pos = avio_tell(pb);
4109 static const uint8_t uuid[] = {
4110 0x6d, 0x1d, 0x9b, 0x05, 0x42, 0xd5, 0x44, 0xe6,
4111 0x80, 0xe2, 0x14, 0x1d, 0xaf, 0xf7, 0x57, 0xb2
4114 avio_wb32(pb, 0); /* size placeholder */
4115 ffio_wfourcc(pb, "uuid");
4116 avio_write(pb, uuid, sizeof(uuid));
4119 avio_wb64(pb, track->start_dts + track->frag_start +
4120 track->cluster[0].cts);
4121 avio_wb64(pb, track->end_pts -
4122 (track->cluster[0].dts + track->cluster[0].cts));
4124 return update_size(pb, pos);
4127 static int mov_write_tfrf_tag(AVIOContext *pb, MOVMuxContext *mov,
4128 MOVTrack *track, int entry)
4130 int n = track->nb_frag_info - 1 - entry, i;
4131 int size = 8 + 16 + 4 + 1 + 16*n;
4132 static const uint8_t uuid[] = {
4133 0xd4, 0x80, 0x7e, 0xf2, 0xca, 0x39, 0x46, 0x95,
4134 0x8e, 0x54, 0x26, 0xcb, 0x9e, 0x46, 0xa7, 0x9f
4140 avio_seek(pb, track->frag_info[entry].tfrf_offset, SEEK_SET);
4141 avio_wb32(pb, size);
4142 ffio_wfourcc(pb, "uuid");
4143 avio_write(pb, uuid, sizeof(uuid));
4147 for (i = 0; i < n; i++) {
4148 int index = entry + 1 + i;
4149 avio_wb64(pb, track->frag_info[index].time);
4150 avio_wb64(pb, track->frag_info[index].duration);
4152 if (n < mov->ism_lookahead) {
4153 int free_size = 16 * (mov->ism_lookahead - n);
4154 avio_wb32(pb, free_size);
4155 ffio_wfourcc(pb, "free");
4156 ffio_fill(pb, 0, free_size - 8);
4162 static int mov_write_tfrf_tags(AVIOContext *pb, MOVMuxContext *mov,
4165 int64_t pos = avio_tell(pb);
4167 for (i = 0; i < mov->ism_lookahead; i++) {
4168 /* Update the tfrf tag for the last ism_lookahead fragments,
4169 * nb_frag_info - 1 is the next fragment to be written. */
4170 mov_write_tfrf_tag(pb, mov, track, track->nb_frag_info - 2 - i);
4172 avio_seek(pb, pos, SEEK_SET);
4176 static int mov_add_tfra_entries(AVIOContext *pb, MOVMuxContext *mov, int tracks,
4180 for (i = 0; i < mov->nb_streams; i++) {
4181 MOVTrack *track = &mov->tracks[i];
4182 MOVFragmentInfo *info;
4183 if ((tracks >= 0 && i != tracks) || !track->entry)
4185 track->nb_frag_info++;
4186 if (track->nb_frag_info >= track->frag_info_capacity) {
4187 unsigned new_capacity = track->nb_frag_info + MOV_FRAG_INFO_ALLOC_INCREMENT;
4188 if (av_reallocp_array(&track->frag_info,
4190 sizeof(*track->frag_info)))
4191 return AVERROR(ENOMEM);
4192 track->frag_info_capacity = new_capacity;
4194 info = &track->frag_info[track->nb_frag_info - 1];
4195 info->offset = avio_tell(pb);
4197 // Try to recreate the original pts for the first packet
4198 // from the fields we have stored
4199 info->time = track->start_dts + track->frag_start +
4200 track->cluster[0].cts;
4201 info->duration = track->end_pts -
4202 (track->cluster[0].dts + track->cluster[0].cts);
4203 // If the pts is less than zero, we will have trimmed
4204 // away parts of the media track using an edit list,
4205 // and the corresponding start presentation time is zero.
4206 if (info->time < 0) {
4207 info->duration += info->time;
4210 info->tfrf_offset = 0;
4211 mov_write_tfrf_tags(pb, mov, track);
4216 static void mov_prune_frag_info(MOVMuxContext *mov, int tracks, int max)
4219 for (i = 0; i < mov->nb_streams; i++) {
4220 MOVTrack *track = &mov->tracks[i];
4221 if ((tracks >= 0 && i != tracks) || !track->entry)
4223 if (track->nb_frag_info > max) {
4224 memmove(track->frag_info, track->frag_info + (track->nb_frag_info - max), max * sizeof(*track->frag_info));
4225 track->nb_frag_info = max;
4230 static int mov_write_tfdt_tag(AVIOContext *pb, MOVTrack *track)
4232 int64_t pos = avio_tell(pb);
4234 avio_wb32(pb, 0); /* size */
4235 ffio_wfourcc(pb, "tfdt");
4236 avio_w8(pb, 1); /* version */
4238 avio_wb64(pb, track->frag_start);
4239 return update_size(pb, pos);
4242 static int mov_write_traf_tag(AVIOContext *pb, MOVMuxContext *mov,
4243 MOVTrack *track, int64_t moof_offset,
4246 int64_t pos = avio_tell(pb);
4248 avio_wb32(pb, 0); /* size placeholder */
4249 ffio_wfourcc(pb, "traf");
4251 mov_write_tfhd_tag(pb, mov, track, moof_offset);
4252 if (mov->mode != MODE_ISM)
4253 mov_write_tfdt_tag(pb, track);
4254 for (i = 1; i < track->entry; i++) {
4255 if (track->cluster[i].pos != track->cluster[i - 1].pos + track->cluster[i - 1].size) {
4256 mov_write_trun_tag(pb, mov, track, moof_size, start, i);
4260 mov_write_trun_tag(pb, mov, track, moof_size, start, track->entry);
4261 if (mov->mode == MODE_ISM) {
4262 mov_write_tfxd_tag(pb, track);
4264 if (mov->ism_lookahead) {
4265 int i, size = 16 + 4 + 1 + 16 * mov->ism_lookahead;
4267 if (track->nb_frag_info > 0) {
4268 MOVFragmentInfo *info = &track->frag_info[track->nb_frag_info - 1];
4269 if (!info->tfrf_offset)
4270 info->tfrf_offset = avio_tell(pb);
4272 avio_wb32(pb, 8 + size);
4273 ffio_wfourcc(pb, "free");
4274 for (i = 0; i < size; i++)
4279 return update_size(pb, pos);
4282 static int mov_write_moof_tag_internal(AVIOContext *pb, MOVMuxContext *mov,
4283 int tracks, int moof_size)
4285 int64_t pos = avio_tell(pb);
4288 avio_wb32(pb, 0); /* size placeholder */
4289 ffio_wfourcc(pb, "moof");
4290 mov->first_trun = 1;
4292 mov_write_mfhd_tag(pb, mov);
4293 for (i = 0; i < mov->nb_streams; i++) {
4294 MOVTrack *track = &mov->tracks[i];
4295 if (tracks >= 0 && i != tracks)
4299 mov_write_traf_tag(pb, mov, track, pos, moof_size);
4302 return update_size(pb, pos);
4305 static int mov_write_sidx_tag(AVIOContext *pb,
4306 MOVTrack *track, int ref_size, int total_sidx_size)
4308 int64_t pos = avio_tell(pb), offset_pos, end_pos;
4309 int64_t presentation_time, duration, offset;
4310 int starts_with_SAP, i, entries;
4314 presentation_time = track->start_dts + track->frag_start +
4315 track->cluster[0].cts;
4316 duration = track->end_pts -
4317 (track->cluster[0].dts + track->cluster[0].cts);
4318 starts_with_SAP = track->cluster[0].flags & MOV_SYNC_SAMPLE;
4320 // pts<0 should be cut away using edts
4321 if (presentation_time < 0) {
4322 duration += presentation_time;
4323 presentation_time = 0;
4326 entries = track->nb_frag_info;
4329 presentation_time = track->frag_info[0].time;
4332 avio_wb32(pb, 0); /* size */
4333 ffio_wfourcc(pb, "sidx");
4334 avio_w8(pb, 1); /* version */
4336 avio_wb32(pb, track->track_id); /* reference_ID */
4337 avio_wb32(pb, track->timescale); /* timescale */
4338 avio_wb64(pb, presentation_time); /* earliest_presentation_time */
4339 offset_pos = avio_tell(pb);
4340 avio_wb64(pb, 0); /* first_offset (offset to referenced moof) */
4341 avio_wb16(pb, 0); /* reserved */
4343 avio_wb16(pb, entries); /* reference_count */
4344 for (i = 0; i < entries; i++) {
4345 if (!track->entry) {
4346 if (i > 1 && track->frag_info[i].offset != track->frag_info[i - 1].offset + track->frag_info[i - 1].size) {
4347 av_log(NULL, AV_LOG_ERROR, "Non-consecutive fragments, writing incorrect sidx\n");
4349 duration = track->frag_info[i].duration;
4350 ref_size = track->frag_info[i].size;
4351 starts_with_SAP = 1;
4353 avio_wb32(pb, (0 << 31) | (ref_size & 0x7fffffff)); /* reference_type (0 = media) | referenced_size */
4354 avio_wb32(pb, duration); /* subsegment_duration */
4355 avio_wb32(pb, (starts_with_SAP << 31) | (0 << 28) | 0); /* starts_with_SAP | SAP_type | SAP_delta_time */
4358 end_pos = avio_tell(pb);
4359 offset = pos + total_sidx_size - end_pos;
4360 avio_seek(pb, offset_pos, SEEK_SET);
4361 avio_wb64(pb, offset);
4362 avio_seek(pb, end_pos, SEEK_SET);
4363 return update_size(pb, pos);
4366 static int mov_write_sidx_tags(AVIOContext *pb, MOVMuxContext *mov,
4367 int tracks, int ref_size)
4370 AVIOContext *avio_buf;
4372 for (round = 0; round < 2; round++) {
4373 // First run one round to calculate the total size of all
4375 // This would be much simpler if we'd only write one sidx
4376 // atom, for the first track in the moof.
4378 if ((ret = ffio_open_null_buf(&avio_buf)) < 0)
4383 for (i = 0; i < mov->nb_streams; i++) {
4384 MOVTrack *track = &mov->tracks[i];
4385 if (tracks >= 0 && i != tracks)
4387 // When writing a sidx for the full file, entry is 0, but
4388 // we want to include all tracks. ref_size is 0 in this case,
4389 // since we read it from frag_info instead.
4390 if (!track->entry && ref_size > 0)
4392 total_size -= mov_write_sidx_tag(avio_buf, track, ref_size,
4396 total_size = ffio_close_null_buf(avio_buf);
4401 static int mov_write_moof_tag(AVIOContext *pb, MOVMuxContext *mov, int tracks,
4404 AVIOContext *avio_buf;
4407 if ((ret = ffio_open_null_buf(&avio_buf)) < 0)
4409 mov_write_moof_tag_internal(avio_buf, mov, tracks, 0);
4410 moof_size = ffio_close_null_buf(avio_buf);
4412 if (mov->flags & FF_MOV_FLAG_DASH && !(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX))
4413 mov_write_sidx_tags(pb, mov, tracks, moof_size + 8 + mdat_size);
4415 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX ||
4416 !(mov->flags & FF_MOV_FLAG_SKIP_TRAILER) ||
4417 mov->ism_lookahead) {
4418 if ((ret = mov_add_tfra_entries(pb, mov, tracks, moof_size + 8 + mdat_size)) < 0)
4420 if (!(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) &&
4421 mov->flags & FF_MOV_FLAG_SKIP_TRAILER) {
4422 mov_prune_frag_info(mov, tracks, mov->ism_lookahead + 1);
4426 return mov_write_moof_tag_internal(pb, mov, tracks, moof_size);
4429 static int mov_write_tfra_tag(AVIOContext *pb, MOVTrack *track)
4431 int64_t pos = avio_tell(pb);
4434 avio_wb32(pb, 0); /* size placeholder */
4435 ffio_wfourcc(pb, "tfra");
4436 avio_w8(pb, 1); /* version */
4439 avio_wb32(pb, track->track_id);
4440 avio_wb32(pb, 0); /* length of traf/trun/sample num */
4441 avio_wb32(pb, track->nb_frag_info);
4442 for (i = 0; i < track->nb_frag_info; i++) {
4443 avio_wb64(pb, track->frag_info[i].time);
4444 avio_wb64(pb, track->frag_info[i].offset + track->data_offset);
4445 avio_w8(pb, 1); /* traf number */
4446 avio_w8(pb, 1); /* trun number */
4447 avio_w8(pb, 1); /* sample number */
4450 return update_size(pb, pos);
4453 static int mov_write_mfra_tag(AVIOContext *pb, MOVMuxContext *mov)
4455 int64_t pos = avio_tell(pb);
4458 avio_wb32(pb, 0); /* size placeholder */
4459 ffio_wfourcc(pb, "mfra");
4460 /* An empty mfra atom is enough to indicate to the publishing point that
4461 * the stream has ended. */
4462 if (mov->flags & FF_MOV_FLAG_ISML)
4463 return update_size(pb, pos);
4465 for (i = 0; i < mov->nb_streams; i++) {
4466 MOVTrack *track = &mov->tracks[i];
4467 if (track->nb_frag_info)
4468 mov_write_tfra_tag(pb, track);
4472 ffio_wfourcc(pb, "mfro");
4473 avio_wb32(pb, 0); /* version + flags */
4474 avio_wb32(pb, avio_tell(pb) + 4 - pos);
4476 return update_size(pb, pos);
4479 static int mov_write_mdat_tag(AVIOContext *pb, MOVMuxContext *mov)
4481 avio_wb32(pb, 8); // placeholder for extended size field (64 bit)
4482 ffio_wfourcc(pb, mov->mode == MODE_MOV ? "wide" : "free");
4484 mov->mdat_pos = avio_tell(pb);
4485 avio_wb32(pb, 0); /* size placeholder*/
4486 ffio_wfourcc(pb, "mdat");
4490 /* TODO: This needs to be more general */
4491 static int mov_write_ftyp_tag(AVIOContext *pb, AVFormatContext *s)
4493 MOVMuxContext *mov = s->priv_data;
4494 int64_t pos = avio_tell(pb);
4495 int has_h264 = 0, has_video = 0;
4499 for (i = 0; i < s->nb_streams; i++) {
4500 AVStream *st = s->streams[i];
4501 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
4503 if (st->codecpar->codec_id == AV_CODEC_ID_H264)
4507 avio_wb32(pb, 0); /* size */
4508 ffio_wfourcc(pb, "ftyp");
4510 if (mov->major_brand && strlen(mov->major_brand) >= 4)
4511 ffio_wfourcc(pb, mov->major_brand);
4512 else if (mov->mode == MODE_3GP) {
4513 ffio_wfourcc(pb, has_h264 ? "3gp6" : "3gp4");
4514 minor = has_h264 ? 0x100 : 0x200;
4515 } else if (mov->mode & MODE_3G2) {
4516 ffio_wfourcc(pb, has_h264 ? "3g2b" : "3g2a");
4517 minor = has_h264 ? 0x20000 : 0x10000;
4518 } else if (mov->mode == MODE_PSP)
4519 ffio_wfourcc(pb, "MSNV");
4520 else if (mov->mode == MODE_MP4 && mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)
4521 ffio_wfourcc(pb, "iso5"); // Required when using default-base-is-moof
4522 else if (mov->mode == MODE_MP4)
4523 ffio_wfourcc(pb, "isom");
4524 else if (mov->mode == MODE_IPOD)
4525 ffio_wfourcc(pb, has_video ? "M4V ":"M4A ");
4526 else if (mov->mode == MODE_ISM)
4527 ffio_wfourcc(pb, "isml");
4528 else if (mov->mode == MODE_F4V)
4529 ffio_wfourcc(pb, "f4v ");
4531 ffio_wfourcc(pb, "qt ");
4533 avio_wb32(pb, minor);
4535 if (mov->mode == MODE_MOV)
4536 ffio_wfourcc(pb, "qt ");
4537 else if (mov->mode == MODE_ISM) {
4538 ffio_wfourcc(pb, "piff");
4539 } else if (!(mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)) {
4540 ffio_wfourcc(pb, "isom");
4541 ffio_wfourcc(pb, "iso2");
4543 ffio_wfourcc(pb, "avc1");
4546 // We add tfdt atoms when fragmenting, signal this with the iso6 compatible
4547 // brand. This is compatible with users that don't understand tfdt.
4548 if (mov->flags & FF_MOV_FLAG_FRAGMENT && mov->mode != MODE_ISM)
4549 ffio_wfourcc(pb, "iso6");
4551 if (mov->mode == MODE_3GP)
4552 ffio_wfourcc(pb, has_h264 ? "3gp6":"3gp4");
4553 else if (mov->mode & MODE_3G2)
4554 ffio_wfourcc(pb, has_h264 ? "3g2b":"3g2a");
4555 else if (mov->mode == MODE_PSP)
4556 ffio_wfourcc(pb, "MSNV");
4557 else if (mov->mode == MODE_MP4)
4558 ffio_wfourcc(pb, "mp41");
4560 if (mov->flags & FF_MOV_FLAG_DASH && mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
4561 ffio_wfourcc(pb, "dash");
4563 return update_size(pb, pos);
4566 static int mov_write_uuidprof_tag(AVIOContext *pb, AVFormatContext *s)
4568 AVStream *video_st = s->streams[0];
4569 AVCodecParameters *video_par = s->streams[0]->codecpar;
4570 AVCodecParameters *audio_par = s->streams[1]->codecpar;
4571 int audio_rate = audio_par->sample_rate;
4572 int64_t frame_rate = video_st->avg_frame_rate.den ?
4573 (video_st->avg_frame_rate.num * 0x10000LL) / video_st->avg_frame_rate.den :
4575 int audio_kbitrate = audio_par->bit_rate / 1000;
4576 int video_kbitrate = FFMIN(video_par->bit_rate / 1000, 800 - audio_kbitrate);
4578 if (frame_rate < 0 || frame_rate > INT32_MAX) {
4579 av_log(s, AV_LOG_ERROR, "Frame rate %f outside supported range\n", frame_rate / (double)0x10000);
4580 return AVERROR(EINVAL);
4583 avio_wb32(pb, 0x94); /* size */
4584 ffio_wfourcc(pb, "uuid");
4585 ffio_wfourcc(pb, "PROF");
4587 avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
4588 avio_wb32(pb, 0xbb88695c);
4589 avio_wb32(pb, 0xfac9c740);
4591 avio_wb32(pb, 0x0); /* ? */
4592 avio_wb32(pb, 0x3); /* 3 sections ? */
4594 avio_wb32(pb, 0x14); /* size */
4595 ffio_wfourcc(pb, "FPRF");
4596 avio_wb32(pb, 0x0); /* ? */
4597 avio_wb32(pb, 0x0); /* ? */
4598 avio_wb32(pb, 0x0); /* ? */
4600 avio_wb32(pb, 0x2c); /* size */
4601 ffio_wfourcc(pb, "APRF"); /* audio */
4603 avio_wb32(pb, 0x2); /* TrackID */
4604 ffio_wfourcc(pb, "mp4a");
4605 avio_wb32(pb, 0x20f);
4607 avio_wb32(pb, audio_kbitrate);
4608 avio_wb32(pb, audio_kbitrate);
4609 avio_wb32(pb, audio_rate);
4610 avio_wb32(pb, audio_par->channels);
4612 avio_wb32(pb, 0x34); /* size */
4613 ffio_wfourcc(pb, "VPRF"); /* video */
4615 avio_wb32(pb, 0x1); /* TrackID */
4616 if (video_par->codec_id == AV_CODEC_ID_H264) {
4617 ffio_wfourcc(pb, "avc1");
4618 avio_wb16(pb, 0x014D);
4619 avio_wb16(pb, 0x0015);
4621 ffio_wfourcc(pb, "mp4v");
4622 avio_wb16(pb, 0x0000);
4623 avio_wb16(pb, 0x0103);
4626 avio_wb32(pb, video_kbitrate);
4627 avio_wb32(pb, video_kbitrate);
4628 avio_wb32(pb, frame_rate);
4629 avio_wb32(pb, frame_rate);
4630 avio_wb16(pb, video_par->width);
4631 avio_wb16(pb, video_par->height);
4632 avio_wb32(pb, 0x010001); /* ? */
4637 static int mov_write_identification(AVIOContext *pb, AVFormatContext *s)
4639 MOVMuxContext *mov = s->priv_data;
4642 mov_write_ftyp_tag(pb,s);
4643 if (mov->mode == MODE_PSP) {
4644 int video_streams_nb = 0, audio_streams_nb = 0, other_streams_nb = 0;
4645 for (i = 0; i < s->nb_streams; i++) {
4646 AVStream *st = s->streams[i];
4647 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
4649 else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
4655 if (video_streams_nb != 1 || audio_streams_nb != 1 || other_streams_nb) {
4656 av_log(s, AV_LOG_ERROR, "PSP mode need one video and one audio stream\n");
4657 return AVERROR(EINVAL);
4659 return mov_write_uuidprof_tag(pb, s);
4664 static int mov_parse_mpeg2_frame(AVPacket *pkt, uint32_t *flags)
4667 int i, closed_gop = 0;
4669 for (i = 0; i < pkt->size - 4; i++) {
4670 c = (c << 8) + pkt->data[i];
4671 if (c == 0x1b8) { // gop
4672 closed_gop = pkt->data[i + 4] >> 6 & 0x01;
4673 } else if (c == 0x100) { // pic
4674 int temp_ref = (pkt->data[i + 1] << 2) | (pkt->data[i + 2] >> 6);
4675 if (!temp_ref || closed_gop) // I picture is not reordered
4676 *flags = MOV_SYNC_SAMPLE;
4678 *flags = MOV_PARTIAL_SYNC_SAMPLE;
4685 static void mov_parse_vc1_frame(AVPacket *pkt, MOVTrack *trk)
4687 const uint8_t *start, *next, *end = pkt->data + pkt->size;
4688 int seq = 0, entry = 0;
4689 int key = pkt->flags & AV_PKT_FLAG_KEY;
4690 start = find_next_marker(pkt->data, end);
4691 for (next = start; next < end; start = next) {
4692 next = find_next_marker(start + 4, end);
4693 switch (AV_RB32(start)) {
4694 case VC1_CODE_SEQHDR:
4697 case VC1_CODE_ENTRYPOINT:
4700 case VC1_CODE_SLICE:
4701 trk->vc1_info.slices = 1;
4705 if (!trk->entry && trk->vc1_info.first_packet_seen)
4706 trk->vc1_info.first_frag_written = 1;
4707 if (!trk->entry && !trk->vc1_info.first_frag_written) {
4708 /* First packet in first fragment */
4709 trk->vc1_info.first_packet_seq = seq;
4710 trk->vc1_info.first_packet_entry = entry;
4711 trk->vc1_info.first_packet_seen = 1;
4712 } else if ((seq && !trk->vc1_info.packet_seq) ||
4713 (entry && !trk->vc1_info.packet_entry)) {
4715 for (i = 0; i < trk->entry; i++)
4716 trk->cluster[i].flags &= ~MOV_SYNC_SAMPLE;
4717 trk->has_keyframes = 0;
4719 trk->vc1_info.packet_seq = 1;
4721 trk->vc1_info.packet_entry = 1;
4722 if (!trk->vc1_info.first_frag_written) {
4723 /* First fragment */
4724 if ((!seq || trk->vc1_info.first_packet_seq) &&
4725 (!entry || trk->vc1_info.first_packet_entry)) {
4726 /* First packet had the same headers as this one, readd the
4727 * sync sample flag. */
4728 trk->cluster[0].flags |= MOV_SYNC_SAMPLE;
4729 trk->has_keyframes = 1;
4733 if (trk->vc1_info.packet_seq && trk->vc1_info.packet_entry)
4735 else if (trk->vc1_info.packet_seq)
4737 else if (trk->vc1_info.packet_entry)
4740 trk->cluster[trk->entry].flags |= MOV_SYNC_SAMPLE;
4741 trk->has_keyframes++;
4745 static int mov_flush_fragment_interleaving(AVFormatContext *s, MOVTrack *track)
4747 MOVMuxContext *mov = s->priv_data;
4752 if (!track->mdat_buf)
4754 if (!mov->mdat_buf) {
4755 if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0)
4758 buf_size = avio_close_dyn_buf(track->mdat_buf, &buf);
4759 track->mdat_buf = NULL;
4761 offset = avio_tell(mov->mdat_buf);
4762 avio_write(mov->mdat_buf, buf, buf_size);
4765 for (i = track->entries_flushed; i < track->entry; i++)
4766 track->cluster[i].pos += offset;
4767 track->entries_flushed = track->entry;
4771 static int mov_flush_fragment(AVFormatContext *s, int force)
4773 MOVMuxContext *mov = s->priv_data;
4774 int i, first_track = -1;
4775 int64_t mdat_size = 0;
4777 int has_video = 0, starts_with_key = 0, first_video_track = 1;
4779 if (!(mov->flags & FF_MOV_FLAG_FRAGMENT))
4782 // Try to fill in the duration of the last packet in each stream
4783 // from queued packets in the interleave queues. If the flushing
4784 // of fragments was triggered automatically by an AVPacket, we
4785 // already have reliable info for the end of that track, but other
4786 // tracks may need to be filled in.
4787 for (i = 0; i < s->nb_streams; i++) {
4788 MOVTrack *track = &mov->tracks[i];
4789 if (!track->end_reliable) {
4791 if (!ff_interleaved_peek(s, i, &pkt, 1)) {
4792 track->track_duration = pkt.dts - track->start_dts;
4793 if (pkt.pts != AV_NOPTS_VALUE)
4794 track->end_pts = pkt.pts;
4796 track->end_pts = pkt.dts;
4801 for (i = 0; i < mov->nb_streams; i++) {
4802 MOVTrack *track = &mov->tracks[i];
4803 if (track->entry <= 1)
4805 // Sample durations are calculated as the diff of dts values,
4806 // but for the last sample in a fragment, we don't know the dts
4807 // of the first sample in the next fragment, so we have to rely
4808 // on what was set as duration in the AVPacket. Not all callers
4809 // set this though, so we might want to replace it with an
4810 // estimate if it currently is zero.
4811 if (get_cluster_duration(track, track->entry - 1) != 0)
4813 // Use the duration (i.e. dts diff) of the second last sample for
4814 // the last one. This is a wild guess (and fatal if it turns out
4815 // to be too long), but probably the best we can do - having a zero
4816 // duration is bad as well.
4817 track->track_duration += get_cluster_duration(track, track->entry - 2);
4818 track->end_pts += get_cluster_duration(track, track->entry - 2);
4819 if (!mov->missing_duration_warned) {
4820 av_log(s, AV_LOG_WARNING,
4821 "Estimating the duration of the last packet in a "
4822 "fragment, consider setting the duration field in "
4823 "AVPacket instead.\n");
4824 mov->missing_duration_warned = 1;
4828 if (!mov->moov_written) {
4829 int64_t pos = avio_tell(s->pb);
4831 int buf_size, moov_size;
4833 for (i = 0; i < mov->nb_streams; i++)
4834 if (!mov->tracks[i].entry)
4836 /* Don't write the initial moov unless all tracks have data */
4837 if (i < mov->nb_streams && !force)
4840 moov_size = get_moov_size(s);
4841 for (i = 0; i < mov->nb_streams; i++)
4842 mov->tracks[i].data_offset = pos + moov_size + 8;
4844 avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_HEADER);
4845 if (mov->flags & FF_MOV_FLAG_DELAY_MOOV)
4846 mov_write_identification(s->pb, s);
4847 if ((ret = mov_write_moov_tag(s->pb, mov, s)) < 0)
4850 if (mov->flags & FF_MOV_FLAG_DELAY_MOOV) {
4851 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
4852 mov->reserved_header_pos = avio_tell(s->pb);
4854 mov->moov_written = 1;
4858 buf_size = avio_close_dyn_buf(mov->mdat_buf, &buf);
4859 mov->mdat_buf = NULL;
4860 avio_wb32(s->pb, buf_size + 8);
4861 ffio_wfourcc(s->pb, "mdat");
4862 avio_write(s->pb, buf, buf_size);
4865 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
4866 mov->reserved_header_pos = avio_tell(s->pb);
4868 mov->moov_written = 1;
4870 for (i = 0; i < mov->nb_streams; i++) {
4871 if (mov->tracks[i].entry)
4872 mov->tracks[i].frag_start += mov->tracks[i].start_dts +
4873 mov->tracks[i].track_duration -
4874 mov->tracks[i].cluster[0].dts;
4875 mov->tracks[i].entry = 0;
4876 mov->tracks[i].end_reliable = 0;
4882 if (mov->frag_interleave) {
4883 for (i = 0; i < mov->nb_streams; i++) {
4884 MOVTrack *track = &mov->tracks[i];
4886 if ((ret = mov_flush_fragment_interleaving(s, track)) < 0)
4892 mdat_size = avio_tell(mov->mdat_buf);
4895 for (i = 0; i < mov->nb_streams; i++) {
4896 MOVTrack *track = &mov->tracks[i];
4897 if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF || mov->frag_interleave)
4898 track->data_offset = 0;
4900 track->data_offset = mdat_size;
4901 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
4903 if (first_video_track) {
4905 starts_with_key = track->cluster[0].flags & MOV_SYNC_SAMPLE;
4906 first_video_track = 0;
4911 if (track->mdat_buf)
4912 mdat_size += avio_tell(track->mdat_buf);
4913 if (first_track < 0)
4920 avio_write_marker(s->pb,
4921 av_rescale(mov->tracks[first_track].cluster[0].dts, AV_TIME_BASE, mov->tracks[first_track].timescale),
4922 (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);
4924 for (i = 0; i < mov->nb_streams; i++) {
4925 MOVTrack *track = &mov->tracks[i];
4926 int buf_size, write_moof = 1, moof_tracks = -1;
4928 int64_t duration = 0;
4931 duration = track->start_dts + track->track_duration -
4932 track->cluster[0].dts;
4933 if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF) {
4934 if (!track->mdat_buf)
4936 mdat_size = avio_tell(track->mdat_buf);
4939 write_moof = i == first_track;
4945 mov_write_moof_tag(s->pb, mov, moof_tracks, mdat_size);
4948 avio_wb32(s->pb, mdat_size + 8);
4949 ffio_wfourcc(s->pb, "mdat");
4953 track->frag_start += duration;
4955 track->entries_flushed = 0;
4956 track->end_reliable = 0;
4957 if (!mov->frag_interleave) {
4958 if (!track->mdat_buf)
4960 buf_size = avio_close_dyn_buf(track->mdat_buf, &buf);
4961 track->mdat_buf = NULL;
4965 buf_size = avio_close_dyn_buf(mov->mdat_buf, &buf);
4966 mov->mdat_buf = NULL;
4969 avio_write(s->pb, buf, buf_size);
4979 static int mov_auto_flush_fragment(AVFormatContext *s, int force)
4981 MOVMuxContext *mov = s->priv_data;
4982 int had_moov = mov->moov_written;
4983 int ret = mov_flush_fragment(s, force);
4986 // If using delay_moov, the first flush only wrote the moov,
4987 // not the actual moof+mdat pair, thus flush once again.
4988 if (!had_moov && mov->flags & FF_MOV_FLAG_DELAY_MOOV)
4989 ret = mov_flush_fragment(s, force);
4993 static int check_pkt(AVFormatContext *s, AVPacket *pkt)
4995 MOVMuxContext *mov = s->priv_data;
4996 MOVTrack *trk = &mov->tracks[pkt->stream_index];
5001 ref = trk->cluster[trk->entry - 1].dts;
5002 } else if ( trk->start_dts != AV_NOPTS_VALUE
5003 && !trk->frag_discont) {
5004 ref = trk->start_dts + trk->track_duration;
5006 ref = pkt->dts; // Skip tests for the first packet
5008 duration = pkt->dts - ref;
5009 if (pkt->dts < ref || duration >= INT_MAX) {
5010 av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" / timestamp: %"PRId64" is out of range for mov/mp4 format\n",
5015 pkt->pts = AV_NOPTS_VALUE;
5018 if (pkt->duration < 0 || pkt->duration > INT_MAX) {
5019 av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" is invalid\n", pkt->duration);
5020 return AVERROR(EINVAL);
5025 int ff_mov_write_packet(AVFormatContext *s, AVPacket *pkt)
5027 MOVMuxContext *mov = s->priv_data;
5028 AVIOContext *pb = s->pb;
5029 MOVTrack *trk = &mov->tracks[pkt->stream_index];
5030 AVCodecParameters *par = trk->par;
5031 unsigned int samples_in_chunk = 0;
5032 int size = pkt->size, ret = 0;
5033 uint8_t *reformatted_data = NULL;
5035 ret = check_pkt(s, pkt);
5039 if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
5041 if (mov->moov_written || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
5042 if (mov->frag_interleave && mov->fragments > 0) {
5043 if (trk->entry - trk->entries_flushed >= mov->frag_interleave) {
5044 if ((ret = mov_flush_fragment_interleaving(s, trk)) < 0)
5049 if (!trk->mdat_buf) {
5050 if ((ret = avio_open_dyn_buf(&trk->mdat_buf)) < 0)
5055 if (!mov->mdat_buf) {
5056 if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0)
5063 if (par->codec_id == AV_CODEC_ID_AMR_NB) {
5064 /* We must find out how many AMR blocks there are in one packet */
5065 static const uint16_t packed_size[16] =
5066 {13, 14, 16, 18, 20, 21, 27, 32, 6, 0, 0, 0, 0, 0, 0, 1};
5069 while (len < size && samples_in_chunk < 100) {
5070 len += packed_size[(pkt->data[len] >> 3) & 0x0F];
5073 if (samples_in_chunk > 1) {
5074 av_log(s, AV_LOG_ERROR, "fatal error, input is not a single packet, implement a AVParser for it\n");
5077 } else if (par->codec_id == AV_CODEC_ID_ADPCM_MS ||
5078 par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) {
5079 samples_in_chunk = trk->par->frame_size;
5080 } else if (trk->sample_size)
5081 samples_in_chunk = size / trk->sample_size;
5083 samples_in_chunk = 1;
5085 /* copy extradata if it exists */
5086 if (trk->vos_len == 0 && par->extradata_size > 0 &&
5087 !TAG_IS_AVCI(trk->tag) &&
5088 (par->codec_id != AV_CODEC_ID_DNXHD)) {
5089 trk->vos_len = par->extradata_size;
5090 trk->vos_data = av_malloc(trk->vos_len);
5091 if (!trk->vos_data) {
5092 ret = AVERROR(ENOMEM);
5095 memcpy(trk->vos_data, par->extradata, trk->vos_len);
5098 if (par->codec_id == AV_CODEC_ID_AAC && pkt->size > 2 &&
5099 (AV_RB16(pkt->data) & 0xfff0) == 0xfff0) {
5100 if (!s->streams[pkt->stream_index]->nb_frames) {
5101 av_log(s, AV_LOG_ERROR, "Malformed AAC bitstream detected: "
5102 "use the audio bitstream filter 'aac_adtstoasc' to fix it "
5103 "('-bsf:a aac_adtstoasc' option with ffmpeg)\n");
5106 av_log(s, AV_LOG_WARNING, "aac bitstream error\n");
5108 if (par->codec_id == AV_CODEC_ID_H264 && trk->vos_len > 0 && *(uint8_t *)trk->vos_data != 1 && !TAG_IS_AVCI(trk->tag)) {
5109 /* from x264 or from bytestream H.264 */
5110 /* NAL reformatting needed */
5111 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
5112 ff_avc_parse_nal_units_buf(pkt->data, &reformatted_data,
5114 avio_write(pb, reformatted_data, size);
5116 if (mov->encryption_scheme == MOV_ENC_CENC_AES_CTR) {
5117 size = ff_mov_cenc_avc_parse_nal_units(&trk->cenc, pb, pkt->data, size);
5123 size = ff_avc_parse_nal_units(pb, pkt->data, pkt->size);
5126 } else if (par->codec_id == AV_CODEC_ID_HEVC && trk->vos_len > 6 &&
5127 (AV_RB24(trk->vos_data) == 1 || AV_RB32(trk->vos_data) == 1)) {
5128 /* extradata is Annex B, assume the bitstream is too and convert it */
5129 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
5130 ff_hevc_annexb2mp4_buf(pkt->data, &reformatted_data, &size, 0, NULL);
5131 avio_write(pb, reformatted_data, size);
5133 size = ff_hevc_annexb2mp4(pb, pkt->data, pkt->size, 0, NULL);
5135 #if CONFIG_AC3_PARSER
5136 } else if (par->codec_id == AV_CODEC_ID_EAC3) {
5137 size = handle_eac3(mov, pkt, trk);
5142 avio_write(pb, pkt->data, size);
5145 if (mov->encryption_scheme == MOV_ENC_CENC_AES_CTR) {
5146 if (par->codec_id == AV_CODEC_ID_H264 && par->extradata_size > 4) {
5147 int nal_size_length = (par->extradata[4] & 0x3) + 1;
5148 ret = ff_mov_cenc_avc_write_nal_units(s, &trk->cenc, nal_size_length, pb, pkt->data, size);
5150 ret = ff_mov_cenc_write_packet(&trk->cenc, pb, pkt->data, size);
5157 avio_write(pb, pkt->data, size);
5161 if ((par->codec_id == AV_CODEC_ID_DNXHD ||
5162 par->codec_id == AV_CODEC_ID_AC3) && !trk->vos_len) {
5163 /* copy frame to create needed atoms */
5164 trk->vos_len = size;
5165 trk->vos_data = av_malloc(size);
5166 if (!trk->vos_data) {
5167 ret = AVERROR(ENOMEM);
5170 memcpy(trk->vos_data, pkt->data, size);
5173 if (trk->entry >= trk->cluster_capacity) {
5174 unsigned new_capacity = 2 * (trk->entry + MOV_INDEX_CLUSTER_SIZE);
5175 if (av_reallocp_array(&trk->cluster, new_capacity,
5176 sizeof(*trk->cluster))) {
5177 ret = AVERROR(ENOMEM);
5180 trk->cluster_capacity = new_capacity;
5183 trk->cluster[trk->entry].pos = avio_tell(pb) - size;
5184 trk->cluster[trk->entry].samples_in_chunk = samples_in_chunk;
5185 trk->cluster[trk->entry].chunkNum = 0;
5186 trk->cluster[trk->entry].size = size;
5187 trk->cluster[trk->entry].entries = samples_in_chunk;
5188 trk->cluster[trk->entry].dts = pkt->dts;
5189 if (!trk->entry && trk->start_dts != AV_NOPTS_VALUE) {
5190 if (!trk->frag_discont) {
5191 /* First packet of a new fragment. We already wrote the duration
5192 * of the last packet of the previous fragment based on track_duration,
5193 * which might not exactly match our dts. Therefore adjust the dts
5194 * of this packet to be what the previous packets duration implies. */
5195 trk->cluster[trk->entry].dts = trk->start_dts + trk->track_duration;
5196 /* We also may have written the pts and the corresponding duration
5197 * in sidx/tfrf/tfxd tags; make sure the sidx pts and duration match up with
5198 * the next fragment. This means the cts of the first sample must
5199 * be the same in all fragments, unless end_pts was updated by
5200 * the packet causing the fragment to be written. */
5201 if ((mov->flags & FF_MOV_FLAG_DASH && !(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)) ||
5202 mov->mode == MODE_ISM)
5203 pkt->pts = pkt->dts + trk->end_pts - trk->cluster[trk->entry].dts;
5205 /* New fragment, but discontinuous from previous fragments.
5206 * Pretend the duration sum of the earlier fragments is
5207 * pkt->dts - trk->start_dts. */
5208 trk->frag_start = pkt->dts - trk->start_dts;
5209 trk->end_pts = AV_NOPTS_VALUE;
5210 trk->frag_discont = 0;
5214 if (!trk->entry && trk->start_dts == AV_NOPTS_VALUE && !mov->use_editlist &&
5215 s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO) {
5216 /* Not using edit lists and shifting the first track to start from zero.
5217 * If the other streams start from a later timestamp, we won't be able
5218 * to signal the difference in starting time without an edit list.
5219 * Thus move the timestamp for this first sample to 0, increasing
5220 * its duration instead. */
5221 trk->cluster[trk->entry].dts = trk->start_dts = 0;
5223 if (trk->start_dts == AV_NOPTS_VALUE) {
5224 trk->start_dts = pkt->dts;
5225 if (trk->frag_discont) {
5226 if (mov->use_editlist) {
5227 /* Pretend the whole stream started at pts=0, with earlier fragments
5228 * already written. If the stream started at pts=0, the duration sum
5229 * of earlier fragments would have been pkt->pts. */
5230 trk->frag_start = pkt->pts;
5231 trk->start_dts = pkt->dts - pkt->pts;
5233 /* Pretend the whole stream started at dts=0, with earlier fragments
5234 * already written, with a duration summing up to pkt->dts. */
5235 trk->frag_start = pkt->dts;
5238 trk->frag_discont = 0;
5239 } else if (pkt->dts && mov->moov_written)
5240 av_log(s, AV_LOG_WARNING,
5241 "Track %d starts with a nonzero dts %"PRId64", while the moov "
5242 "already has been written. Set the delay_moov flag to handle "
5244 pkt->stream_index, pkt->dts);
5246 trk->track_duration = pkt->dts - trk->start_dts + pkt->duration;
5247 trk->last_sample_is_subtitle_end = 0;
5249 if (pkt->pts == AV_NOPTS_VALUE) {
5250 av_log(s, AV_LOG_WARNING, "pts has no value\n");
5251 pkt->pts = pkt->dts;
5253 if (pkt->dts != pkt->pts)
5254 trk->flags |= MOV_TRACK_CTTS;
5255 trk->cluster[trk->entry].cts = pkt->pts - pkt->dts;
5256 trk->cluster[trk->entry].flags = 0;
5257 if (trk->start_cts == AV_NOPTS_VALUE)
5258 trk->start_cts = pkt->pts - pkt->dts;
5259 if (trk->end_pts == AV_NOPTS_VALUE)
5260 trk->end_pts = trk->cluster[trk->entry].dts +
5261 trk->cluster[trk->entry].cts + pkt->duration;
5263 trk->end_pts = FFMAX(trk->end_pts, trk->cluster[trk->entry].dts +
5264 trk->cluster[trk->entry].cts +
5267 if (par->codec_id == AV_CODEC_ID_VC1) {
5268 mov_parse_vc1_frame(pkt, trk);
5269 } else if (pkt->flags & AV_PKT_FLAG_KEY) {
5270 if (mov->mode == MODE_MOV && par->codec_id == AV_CODEC_ID_MPEG2VIDEO &&
5271 trk->entry > 0) { // force sync sample for the first key frame
5272 mov_parse_mpeg2_frame(pkt, &trk->cluster[trk->entry].flags);
5273 if (trk->cluster[trk->entry].flags & MOV_PARTIAL_SYNC_SAMPLE)
5274 trk->flags |= MOV_TRACK_STPS;
5276 trk->cluster[trk->entry].flags = MOV_SYNC_SAMPLE;
5278 if (trk->cluster[trk->entry].flags & MOV_SYNC_SAMPLE)
5279 trk->has_keyframes++;
5282 trk->sample_count += samples_in_chunk;
5283 mov->mdat_size += size;
5285 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams)
5286 ff_mov_add_hinted_packet(s, pkt, trk->hint_track, trk->entry,
5287 reformatted_data, size);
5292 av_free(reformatted_data);
5296 static int mov_write_single_packet(AVFormatContext *s, AVPacket *pkt)
5298 MOVMuxContext *mov = s->priv_data;
5299 MOVTrack *trk = &mov->tracks[pkt->stream_index];
5300 AVCodecParameters *par = trk->par;
5301 int64_t frag_duration = 0;
5302 int size = pkt->size;
5304 int ret = check_pkt(s, pkt);
5308 if (mov->flags & FF_MOV_FLAG_FRAG_DISCONT) {
5310 for (i = 0; i < s->nb_streams; i++)
5311 mov->tracks[i].frag_discont = 1;
5312 mov->flags &= ~FF_MOV_FLAG_FRAG_DISCONT;
5316 if (trk->start_dts == AV_NOPTS_VALUE && trk->frag_discont) {
5317 trk->start_dts = pkt->dts;
5318 if (pkt->pts != AV_NOPTS_VALUE)
5319 trk->start_cts = pkt->pts - pkt->dts;
5324 if (trk->par->codec_id == AV_CODEC_ID_MP4ALS ||
5325 trk->par->codec_id == AV_CODEC_ID_FLAC) {
5327 uint8_t *side = av_packet_get_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA, &side_size);
5328 if (side && side_size > 0 && (side_size != par->extradata_size || memcmp(side, par->extradata, side_size))) {
5329 void *newextra = av_mallocz(side_size + AV_INPUT_BUFFER_PADDING_SIZE);
5331 return AVERROR(ENOMEM);
5332 av_free(par->extradata);
5333 par->extradata = newextra;
5334 memcpy(par->extradata, side, side_size);
5335 par->extradata_size = side_size;
5336 mov->need_rewrite_extradata = 1;
5340 return 0; /* Discard 0 sized packets */
5343 if (trk->entry && pkt->stream_index < s->nb_streams)
5344 frag_duration = av_rescale_q(pkt->dts - trk->cluster[0].dts,
5345 s->streams[pkt->stream_index]->time_base,
5347 if ((mov->max_fragment_duration &&
5348 frag_duration >= mov->max_fragment_duration) ||
5349 (mov->max_fragment_size && mov->mdat_size + size >= mov->max_fragment_size) ||
5350 (mov->flags & FF_MOV_FLAG_FRAG_KEYFRAME &&
5351 par->codec_type == AVMEDIA_TYPE_VIDEO &&
5352 trk->entry && pkt->flags & AV_PKT_FLAG_KEY)) {
5353 if (frag_duration >= mov->min_fragment_duration) {
5354 // Set the duration of this track to line up with the next
5355 // sample in this track. This avoids relying on AVPacket
5356 // duration, but only helps for this particular track, not
5357 // for the other ones that are flushed at the same time.
5358 trk->track_duration = pkt->dts - trk->start_dts;
5359 if (pkt->pts != AV_NOPTS_VALUE)
5360 trk->end_pts = pkt->pts;
5362 trk->end_pts = pkt->dts;
5363 trk->end_reliable = 1;
5364 mov_auto_flush_fragment(s, 0);
5368 return ff_mov_write_packet(s, pkt);
5371 static int mov_write_subtitle_end_packet(AVFormatContext *s,
5375 uint8_t data[2] = {0};
5378 av_init_packet(&end);
5379 end.size = sizeof(data);
5384 end.stream_index = stream_index;
5386 ret = mov_write_single_packet(s, &end);
5387 av_packet_unref(&end);
5392 static int mov_write_packet(AVFormatContext *s, AVPacket *pkt)
5395 mov_flush_fragment(s, 1);
5399 MOVMuxContext *mov = s->priv_data;
5400 MOVTrack *trk = &mov->tracks[pkt->stream_index];
5403 return mov_write_single_packet(s, pkt); /* Passthrough. */
5406 * Subtitles require special handling.
5408 * 1) For full complaince, every track must have a sample at
5409 * dts == 0, which is rarely true for subtitles. So, as soon
5410 * as we see any packet with dts > 0, write an empty subtitle
5411 * at dts == 0 for any subtitle track with no samples in it.
5413 * 2) For each subtitle track, check if the current packet's
5414 * dts is past the duration of the last subtitle sample. If
5415 * so, we now need to write an end sample for that subtitle.
5417 * This must be done conditionally to allow for subtitles that
5418 * immediately replace each other, in which case an end sample
5419 * is not needed, and is, in fact, actively harmful.
5421 * 3) See mov_write_trailer for how the final end sample is
5424 for (i = 0; i < mov->nb_streams; i++) {
5425 MOVTrack *trk = &mov->tracks[i];
5428 if (trk->par->codec_id == AV_CODEC_ID_MOV_TEXT &&
5429 trk->track_duration < pkt->dts &&
5430 (trk->entry == 0 || !trk->last_sample_is_subtitle_end)) {
5431 ret = mov_write_subtitle_end_packet(s, i, trk->track_duration);
5432 if (ret < 0) return ret;
5433 trk->last_sample_is_subtitle_end = 1;
5437 if (trk->mode == MODE_MOV && trk->par->codec_type == AVMEDIA_TYPE_VIDEO) {
5438 AVPacket *opkt = pkt;
5439 int reshuffle_ret, ret;
5440 if (trk->is_unaligned_qt_rgb) {
5441 int64_t bpc = trk->par->bits_per_coded_sample != 15 ? trk->par->bits_per_coded_sample : 16;
5442 int expected_stride = ((trk->par->width * bpc + 15) >> 4)*2;
5443 reshuffle_ret = ff_reshuffle_raw_rgb(s, &pkt, trk->par, expected_stride);
5444 if (reshuffle_ret < 0)
5445 return reshuffle_ret;
5448 if (trk->par->format == AV_PIX_FMT_PAL8 && !trk->pal_done) {
5449 ret = ff_get_packet_palette(s, opkt, reshuffle_ret, trk->palette);
5454 } else if (trk->par->codec_id == AV_CODEC_ID_RAWVIDEO &&
5455 (trk->par->format == AV_PIX_FMT_GRAY8 ||
5456 trk->par->format == AV_PIX_FMT_MONOBLACK)) {
5457 for (i = 0; i < pkt->size; i++)
5458 pkt->data[i] = ~pkt->data[i];
5460 if (reshuffle_ret) {
5461 ret = mov_write_single_packet(s, pkt);
5464 av_packet_free(&pkt);
5469 return mov_write_single_packet(s, pkt);
5473 // QuickTime chapters involve an additional text track with the chapter names
5474 // as samples, and a tref pointing from the other tracks to the chapter one.
5475 static int mov_create_chapter_track(AVFormatContext *s, int tracknum)
5479 MOVMuxContext *mov = s->priv_data;
5480 MOVTrack *track = &mov->tracks[tracknum];
5481 AVPacket pkt = { .stream_index = tracknum, .flags = AV_PKT_FLAG_KEY };
5484 track->mode = mov->mode;
5485 track->tag = MKTAG('t','e','x','t');
5486 track->timescale = MOV_TIMESCALE;
5487 track->par = avcodec_parameters_alloc();
5489 return AVERROR(ENOMEM);
5490 track->par->codec_type = AVMEDIA_TYPE_SUBTITLE;
5492 // These properties are required to make QT recognize the chapter track
5493 uint8_t chapter_properties[43] = { 0, 0, 0, 0, 0, 0, 0, 1, };
5494 if (ff_alloc_extradata(track->par, sizeof(chapter_properties)))
5495 return AVERROR(ENOMEM);
5496 memcpy(track->par->extradata, chapter_properties, sizeof(chapter_properties));
5498 if (avio_open_dyn_buf(&pb) >= 0) {
5502 /* Stub header (usually for Quicktime chapter track) */
5504 avio_wb32(pb, 0x01); // displayFlags
5505 avio_w8(pb, 0x00); // horizontal justification
5506 avio_w8(pb, 0x00); // vertical justification
5507 avio_w8(pb, 0x00); // bgColourRed
5508 avio_w8(pb, 0x00); // bgColourGreen
5509 avio_w8(pb, 0x00); // bgColourBlue
5510 avio_w8(pb, 0x00); // bgColourAlpha
5512 avio_wb16(pb, 0x00); // defTextBoxTop
5513 avio_wb16(pb, 0x00); // defTextBoxLeft
5514 avio_wb16(pb, 0x00); // defTextBoxBottom
5515 avio_wb16(pb, 0x00); // defTextBoxRight
5517 avio_wb16(pb, 0x00); // startChar
5518 avio_wb16(pb, 0x00); // endChar
5519 avio_wb16(pb, 0x01); // fontID
5520 avio_w8(pb, 0x00); // fontStyleFlags
5521 avio_w8(pb, 0x00); // fontSize
5522 avio_w8(pb, 0x00); // fgColourRed
5523 avio_w8(pb, 0x00); // fgColourGreen
5524 avio_w8(pb, 0x00); // fgColourBlue
5525 avio_w8(pb, 0x00); // fgColourAlpha
5527 avio_wb32(pb, 0x0D); // box size
5528 ffio_wfourcc(pb, "ftab"); // box atom name
5529 avio_wb16(pb, 0x01); // entry count
5531 avio_wb16(pb, 0x01); // font ID
5532 avio_w8(pb, 0x00); // font name length
5534 if ((size = avio_close_dyn_buf(pb, &buf)) > 0) {
5535 track->par->extradata = buf;
5536 track->par->extradata_size = size;
5543 for (i = 0; i < s->nb_chapters; i++) {
5544 AVChapter *c = s->chapters[i];
5545 AVDictionaryEntry *t;
5547 int64_t end = av_rescale_q(c->end, c->time_base, (AVRational){1,MOV_TIMESCALE});
5548 pkt.pts = pkt.dts = av_rescale_q(c->start, c->time_base, (AVRational){1,MOV_TIMESCALE});
5549 pkt.duration = end - pkt.dts;
5551 if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
5552 static const char encd[12] = {
5553 0x00, 0x00, 0x00, 0x0C,
5555 0x00, 0x00, 0x01, 0x00 };
5556 len = strlen(t->value);
5557 pkt.size = len + 2 + 12;
5558 pkt.data = av_malloc(pkt.size);
5560 return AVERROR(ENOMEM);
5561 AV_WB16(pkt.data, len);
5562 memcpy(pkt.data + 2, t->value, len);
5563 memcpy(pkt.data + len + 2, encd, sizeof(encd));
5564 ff_mov_write_packet(s, &pkt);
5565 av_freep(&pkt.data);
5573 static int mov_check_timecode_track(AVFormatContext *s, AVTimecode *tc, int src_index, const char *tcstr)
5577 /* compute the frame number */
5578 ret = av_timecode_init_from_string(tc, find_fps(s, s->streams[src_index]), tcstr, s);
5582 static int mov_create_timecode_track(AVFormatContext *s, int index, int src_index, AVTimecode tc)
5585 MOVMuxContext *mov = s->priv_data;
5586 MOVTrack *track = &mov->tracks[index];
5587 AVStream *src_st = s->streams[src_index];
5588 AVPacket pkt = {.stream_index = index, .flags = AV_PKT_FLAG_KEY, .size = 4};
5589 AVRational rate = find_fps(s, src_st);
5591 /* tmcd track based on video stream */
5592 track->mode = mov->mode;
5593 track->tag = MKTAG('t','m','c','d');
5594 track->src_track = src_index;
5595 track->timescale = mov->tracks[src_index].timescale;
5596 if (tc.flags & AV_TIMECODE_FLAG_DROPFRAME)
5597 track->timecode_flags |= MOV_TIMECODE_FLAG_DROPFRAME;
5599 /* set st to src_st for metadata access*/
5602 /* encode context: tmcd data stream */
5603 track->par = avcodec_parameters_alloc();
5605 return AVERROR(ENOMEM);
5606 track->par->codec_type = AVMEDIA_TYPE_DATA;
5607 track->par->codec_tag = track->tag;
5608 track->st->avg_frame_rate = av_inv_q(rate);
5610 /* the tmcd track just contains one packet with the frame number */
5611 pkt.data = av_malloc(pkt.size);
5613 return AVERROR(ENOMEM);
5614 AV_WB32(pkt.data, tc.start);
5615 ret = ff_mov_write_packet(s, &pkt);
5621 * st->disposition controls the "enabled" flag in the tkhd tag.
5622 * QuickTime will not play a track if it is not enabled. So make sure
5623 * that one track of each type (audio, video, subtitle) is enabled.
5625 * Subtitles are special. For audio and video, setting "enabled" also
5626 * makes the track "default" (i.e. it is rendered when played). For
5627 * subtitles, an "enabled" subtitle is not rendered by default, but
5628 * if no subtitle is enabled, the subtitle menu in QuickTime will be
5631 static void enable_tracks(AVFormatContext *s)
5633 MOVMuxContext *mov = s->priv_data;
5635 int enabled[AVMEDIA_TYPE_NB];
5636 int first[AVMEDIA_TYPE_NB];
5638 for (i = 0; i < AVMEDIA_TYPE_NB; i++) {
5643 for (i = 0; i < s->nb_streams; i++) {
5644 AVStream *st = s->streams[i];
5646 if (st->codecpar->codec_type <= AVMEDIA_TYPE_UNKNOWN ||
5647 st->codecpar->codec_type >= AVMEDIA_TYPE_NB)
5650 if (first[st->codecpar->codec_type] < 0)
5651 first[st->codecpar->codec_type] = i;
5652 if (st->disposition & AV_DISPOSITION_DEFAULT) {
5653 mov->tracks[i].flags |= MOV_TRACK_ENABLED;
5654 enabled[st->codecpar->codec_type]++;
5658 for (i = 0; i < AVMEDIA_TYPE_NB; i++) {
5660 case AVMEDIA_TYPE_VIDEO:
5661 case AVMEDIA_TYPE_AUDIO:
5662 case AVMEDIA_TYPE_SUBTITLE:
5664 mov->per_stream_grouping = 1;
5665 if (!enabled[i] && first[i] >= 0)
5666 mov->tracks[first[i]].flags |= MOV_TRACK_ENABLED;
5672 static void mov_free(AVFormatContext *s)
5674 MOVMuxContext *mov = s->priv_data;
5677 if (mov->chapter_track) {
5678 if (mov->tracks[mov->chapter_track].par)
5679 av_freep(&mov->tracks[mov->chapter_track].par->extradata);
5680 av_freep(&mov->tracks[mov->chapter_track].par);
5683 for (i = 0; i < mov->nb_streams; i++) {
5684 if (mov->tracks[i].tag == MKTAG('r','t','p',' '))
5685 ff_mov_close_hinting(&mov->tracks[i]);
5686 else if (mov->tracks[i].tag == MKTAG('t','m','c','d') && mov->nb_meta_tmcd)
5687 av_freep(&mov->tracks[i].par);
5688 av_freep(&mov->tracks[i].cluster);
5689 av_freep(&mov->tracks[i].frag_info);
5691 if (mov->tracks[i].vos_len)
5692 av_freep(&mov->tracks[i].vos_data);
5694 ff_mov_cenc_free(&mov->tracks[i].cenc);
5697 av_freep(&mov->tracks);
5700 static uint32_t rgb_to_yuv(uint32_t rgb)
5705 r = (rgb >> 16) & 0xFF;
5706 g = (rgb >> 8) & 0xFF;
5709 y = av_clip_uint8(( 16000 + 257 * r + 504 * g + 98 * b)/1000);
5710 cb = av_clip_uint8((128000 - 148 * r - 291 * g + 439 * b)/1000);
5711 cr = av_clip_uint8((128000 + 439 * r - 368 * g - 71 * b)/1000);
5713 return (y << 16) | (cr << 8) | cb;
5716 static int mov_create_dvd_sub_decoder_specific_info(MOVTrack *track,
5719 int i, width = 720, height = 480;
5720 int have_palette = 0, have_size = 0;
5721 uint32_t palette[16];
5722 char *cur = st->codecpar->extradata;
5724 while (cur && *cur) {
5725 if (strncmp("palette:", cur, 8) == 0) {
5727 count = sscanf(cur + 8,
5728 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
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 &palette[ 0], &palette[ 1], &palette[ 2], &palette[ 3],
5733 &palette[ 4], &palette[ 5], &palette[ 6], &palette[ 7],
5734 &palette[ 8], &palette[ 9], &palette[10], &palette[11],
5735 &palette[12], &palette[13], &palette[14], &palette[15]);
5737 for (i = 0; i < count; i++) {
5738 palette[i] = rgb_to_yuv(palette[i]);
5741 } else if (!strncmp("size:", cur, 5)) {
5742 sscanf(cur + 5, "%dx%d", &width, &height);
5745 if (have_palette && have_size)
5747 cur += strcspn(cur, "\n\r");
5748 cur += strspn(cur, "\n\r");
5751 track->vos_data = av_malloc(16*4);
5752 if (!track->vos_data)
5753 return AVERROR(ENOMEM);
5754 for (i = 0; i < 16; i++) {
5755 AV_WB32(track->vos_data + i * 4, palette[i]);
5757 track->vos_len = 16 * 4;
5759 st->codecpar->width = width;
5760 st->codecpar->height = track->height = height;
5765 static int mov_init(AVFormatContext *s)
5767 MOVMuxContext *mov = s->priv_data;
5768 AVDictionaryEntry *global_tcr = av_dict_get(s->metadata, "timecode", NULL, 0);
5773 /* Default mode == MP4 */
5774 mov->mode = MODE_MP4;
5777 if (!strcmp("3gp", s->oformat->name)) mov->mode = MODE_3GP;
5778 else if (!strcmp("3g2", s->oformat->name)) mov->mode = MODE_3GP|MODE_3G2;
5779 else if (!strcmp("mov", s->oformat->name)) mov->mode = MODE_MOV;
5780 else if (!strcmp("psp", s->oformat->name)) mov->mode = MODE_PSP;
5781 else if (!strcmp("ipod",s->oformat->name)) mov->mode = MODE_IPOD;
5782 else if (!strcmp("ismv",s->oformat->name)) mov->mode = MODE_ISM;
5783 else if (!strcmp("f4v", s->oformat->name)) mov->mode = MODE_F4V;
5786 if (mov->flags & FF_MOV_FLAG_DELAY_MOOV)
5787 mov->flags |= FF_MOV_FLAG_EMPTY_MOOV;
5789 /* Set the FRAGMENT flag if any of the fragmentation methods are
5791 if (mov->max_fragment_duration || mov->max_fragment_size ||
5792 mov->flags & (FF_MOV_FLAG_EMPTY_MOOV |
5793 FF_MOV_FLAG_FRAG_KEYFRAME |
5794 FF_MOV_FLAG_FRAG_CUSTOM))
5795 mov->flags |= FF_MOV_FLAG_FRAGMENT;
5797 /* Set other implicit flags immediately */
5798 if (mov->mode == MODE_ISM)
5799 mov->flags |= FF_MOV_FLAG_EMPTY_MOOV | FF_MOV_FLAG_SEPARATE_MOOF |
5800 FF_MOV_FLAG_FRAGMENT;
5801 if (mov->flags & FF_MOV_FLAG_DASH)
5802 mov->flags |= FF_MOV_FLAG_FRAGMENT | FF_MOV_FLAG_EMPTY_MOOV |
5803 FF_MOV_FLAG_DEFAULT_BASE_MOOF;
5805 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV && s->flags & AVFMT_FLAG_AUTO_BSF) {
5806 av_log(s, AV_LOG_VERBOSE, "Empty MOOV enabled; disabling automatic bitstream filtering\n");
5807 s->flags &= ~AVFMT_FLAG_AUTO_BSF;
5810 if (mov->flags & FF_MOV_FLAG_FASTSTART) {
5811 mov->reserved_moov_size = -1;
5814 if (mov->use_editlist < 0) {
5815 mov->use_editlist = 1;
5816 if (mov->flags & FF_MOV_FLAG_FRAGMENT &&
5817 !(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
5818 // If we can avoid needing an edit list by shifting the
5819 // tracks, prefer that over (trying to) write edit lists
5820 // in fragmented output.
5821 if (s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO ||
5822 s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO)
5823 mov->use_editlist = 0;
5826 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV &&
5827 !(mov->flags & FF_MOV_FLAG_DELAY_MOOV) && mov->use_editlist)
5828 av_log(s, AV_LOG_WARNING, "No meaningful edit list will be written when using empty_moov without delay_moov\n");
5830 if (!mov->use_editlist && s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO)
5831 s->avoid_negative_ts = AVFMT_AVOID_NEG_TS_MAKE_ZERO;
5833 /* Clear the omit_tfhd_offset flag if default_base_moof is set;
5834 * if the latter is set that's enough and omit_tfhd_offset doesn't
5835 * add anything extra on top of that. */
5836 if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET &&
5837 mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)
5838 mov->flags &= ~FF_MOV_FLAG_OMIT_TFHD_OFFSET;
5840 if (mov->frag_interleave &&
5841 mov->flags & (FF_MOV_FLAG_OMIT_TFHD_OFFSET | FF_MOV_FLAG_SEPARATE_MOOF)) {
5842 av_log(s, AV_LOG_ERROR,
5843 "Sample interleaving in fragments is mutually exclusive with "
5844 "omit_tfhd_offset and separate_moof\n");
5845 return AVERROR(EINVAL);
5848 /* Non-seekable output is ok if using fragmentation. If ism_lookahead
5849 * is enabled, we don't support non-seekable output at all. */
5850 if (!(s->pb->seekable & AVIO_SEEKABLE_NORMAL) &&
5851 (!(mov->flags & FF_MOV_FLAG_FRAGMENT) || mov->ism_lookahead)) {
5852 av_log(s, AV_LOG_ERROR, "muxer does not support non seekable output\n");
5853 return AVERROR(EINVAL);
5856 mov->nb_streams = s->nb_streams;
5857 if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters)
5858 mov->chapter_track = mov->nb_streams++;
5860 if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
5861 /* Add hint tracks for each audio and video stream */
5862 for (i = 0; i < s->nb_streams; i++) {
5863 AVStream *st = s->streams[i];
5864 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ||
5865 st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
5871 if ( mov->write_tmcd == -1 && (mov->mode == MODE_MOV || mov->mode == MODE_MP4)
5872 || mov->write_tmcd == 1) {
5873 /* +1 tmcd track for each video stream with a timecode */
5874 for (i = 0; i < s->nb_streams; i++) {
5875 AVStream *st = s->streams[i];
5876 AVDictionaryEntry *t = global_tcr;
5877 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
5878 (t || (t=av_dict_get(st->metadata, "timecode", NULL, 0)))) {
5880 ret = mov_check_timecode_track(s, &tc, i, t->value);
5882 mov->nb_meta_tmcd++;
5886 /* check if there is already a tmcd track to remux */
5887 if (mov->nb_meta_tmcd) {
5888 for (i = 0; i < s->nb_streams; i++) {
5889 AVStream *st = s->streams[i];
5890 if (st->codecpar->codec_tag == MKTAG('t','m','c','d')) {
5891 av_log(s, AV_LOG_WARNING, "You requested a copy of the original timecode track "
5892 "so timecode metadata are now ignored\n");
5893 mov->nb_meta_tmcd = 0;
5898 mov->nb_streams += mov->nb_meta_tmcd;
5901 // Reserve an extra stream for chapters for the case where chapters
5902 // are written in the trailer
5903 mov->tracks = av_mallocz_array((mov->nb_streams + 1), sizeof(*mov->tracks));
5905 return AVERROR(ENOMEM);
5907 if (mov->encryption_scheme_str != NULL && strcmp(mov->encryption_scheme_str, "none") != 0) {
5908 if (strcmp(mov->encryption_scheme_str, "cenc-aes-ctr") == 0) {
5909 mov->encryption_scheme = MOV_ENC_CENC_AES_CTR;
5911 if (mov->encryption_key_len != AES_CTR_KEY_SIZE) {
5912 av_log(s, AV_LOG_ERROR, "Invalid encryption key len %d expected %d\n",
5913 mov->encryption_key_len, AES_CTR_KEY_SIZE);
5914 return AVERROR(EINVAL);
5917 if (mov->encryption_kid_len != CENC_KID_SIZE) {
5918 av_log(s, AV_LOG_ERROR, "Invalid encryption kid len %d expected %d\n",
5919 mov->encryption_kid_len, CENC_KID_SIZE);
5920 return AVERROR(EINVAL);
5923 av_log(s, AV_LOG_ERROR, "unsupported encryption scheme %s\n",
5924 mov->encryption_scheme_str);
5925 return AVERROR(EINVAL);
5929 for (i = 0; i < s->nb_streams; i++) {
5930 AVStream *st= s->streams[i];
5931 MOVTrack *track= &mov->tracks[i];
5932 AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0);
5935 track->par = st->codecpar;
5936 track->language = ff_mov_iso639_to_lang(lang?lang->value:"und", mov->mode!=MODE_MOV);
5937 if (track->language < 0)
5938 track->language = 0;
5939 track->mode = mov->mode;
5940 track->tag = mov_find_codec_tag(s, track);
5942 av_log(s, AV_LOG_ERROR, "Could not find tag for codec %s in stream #%d, "
5943 "codec not currently supported in container\n",
5944 avcodec_get_name(st->codecpar->codec_id), i);
5945 return AVERROR(EINVAL);
5947 /* If hinting of this track is enabled by a later hint track,
5948 * this is updated. */
5949 track->hint_track = -1;
5950 track->start_dts = AV_NOPTS_VALUE;
5951 track->start_cts = AV_NOPTS_VALUE;
5952 track->end_pts = AV_NOPTS_VALUE;
5953 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
5954 if (track->tag == MKTAG('m','x','3','p') || track->tag == MKTAG('m','x','3','n') ||
5955 track->tag == MKTAG('m','x','4','p') || track->tag == MKTAG('m','x','4','n') ||
5956 track->tag == MKTAG('m','x','5','p') || track->tag == MKTAG('m','x','5','n')) {
5957 if (st->codecpar->width != 720 || (st->codecpar->height != 608 && st->codecpar->height != 512)) {
5958 av_log(s, AV_LOG_ERROR, "D-10/IMX must use 720x608 or 720x512 video resolution\n");
5959 return AVERROR(EINVAL);
5961 track->height = track->tag >> 24 == 'n' ? 486 : 576;
5963 if (mov->video_track_timescale) {
5964 track->timescale = mov->video_track_timescale;
5966 track->timescale = st->time_base.den;
5967 while(track->timescale < 10000)
5968 track->timescale *= 2;
5970 if (st->codecpar->width > 65535 || st->codecpar->height > 65535) {
5971 av_log(s, AV_LOG_ERROR, "Resolution %dx%d too large for mov/mp4\n", st->codecpar->width, st->codecpar->height);
5972 return AVERROR(EINVAL);
5974 if (track->mode == MODE_MOV && track->timescale > 100000)
5975 av_log(s, AV_LOG_WARNING,
5976 "WARNING codec timebase is very high. If duration is too long,\n"
5977 "file may not be playable by quicktime. Specify a shorter timebase\n"
5978 "or choose different container.\n");
5979 if (track->mode == MODE_MOV &&
5980 track->par->codec_id == AV_CODEC_ID_RAWVIDEO &&
5981 track->tag == MKTAG('r','a','w',' ')) {
5982 enum AVPixelFormat pix_fmt = track->par->format;
5983 if (pix_fmt == AV_PIX_FMT_NONE && track->par->bits_per_coded_sample == 1)
5984 pix_fmt = AV_PIX_FMT_MONOWHITE;
5985 track->is_unaligned_qt_rgb =
5986 pix_fmt == AV_PIX_FMT_RGB24 ||
5987 pix_fmt == AV_PIX_FMT_BGR24 ||
5988 pix_fmt == AV_PIX_FMT_PAL8 ||
5989 pix_fmt == AV_PIX_FMT_GRAY8 ||
5990 pix_fmt == AV_PIX_FMT_MONOWHITE ||
5991 pix_fmt == AV_PIX_FMT_MONOBLACK;
5993 if (track->par->codec_id == AV_CODEC_ID_VP9) {
5994 if (track->mode != MODE_MP4) {
5995 av_log(s, AV_LOG_ERROR, "VP9 only supported in MP4.\n");
5996 return AVERROR(EINVAL);
5998 if (s->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
5999 av_log(s, AV_LOG_ERROR,
6000 "VP9 in MP4 support is experimental, add "
6001 "'-strict %d' if you want to use it.\n",
6002 FF_COMPLIANCE_EXPERIMENTAL);
6003 return AVERROR_EXPERIMENTAL;
6006 } else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
6007 track->timescale = st->codecpar->sample_rate;
6008 if (!st->codecpar->frame_size && !av_get_bits_per_sample(st->codecpar->codec_id)) {
6009 av_log(s, AV_LOG_WARNING, "track %d: codec frame size is not set\n", i);
6010 track->audio_vbr = 1;
6011 }else if (st->codecpar->codec_id == AV_CODEC_ID_ADPCM_MS ||
6012 st->codecpar->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
6013 st->codecpar->codec_id == AV_CODEC_ID_ILBC){
6014 if (!st->codecpar->block_align) {
6015 av_log(s, AV_LOG_ERROR, "track %d: codec block align is not set for adpcm\n", i);
6016 return AVERROR(EINVAL);
6018 track->sample_size = st->codecpar->block_align;
6019 }else if (st->codecpar->frame_size > 1){ /* assume compressed audio */
6020 track->audio_vbr = 1;
6022 track->sample_size = (av_get_bits_per_sample(st->codecpar->codec_id) >> 3) * st->codecpar->channels;
6024 if (st->codecpar->codec_id == AV_CODEC_ID_ILBC ||
6025 st->codecpar->codec_id == AV_CODEC_ID_ADPCM_IMA_QT) {
6026 track->audio_vbr = 1;
6028 if (track->mode != MODE_MOV &&
6029 track->par->codec_id == AV_CODEC_ID_MP3 && track->timescale < 16000) {
6030 if (s->strict_std_compliance >= FF_COMPLIANCE_NORMAL) {
6031 av_log(s, AV_LOG_ERROR, "track %d: muxing mp3 at %dhz is not standard, to mux anyway set strict to -1\n",
6032 i, track->par->sample_rate);
6033 return AVERROR(EINVAL);
6035 av_log(s, AV_LOG_WARNING, "track %d: muxing mp3 at %dhz is not standard in MP4\n",
6036 i, track->par->sample_rate);
6039 if (track->par->codec_id == AV_CODEC_ID_FLAC ||
6040 track->par->codec_id == AV_CODEC_ID_OPUS) {
6041 if (track->mode != MODE_MP4) {
6042 av_log(s, AV_LOG_ERROR, "%s only supported in MP4.\n", avcodec_get_name(track->par->codec_id));
6043 return AVERROR(EINVAL);
6045 if (s->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
6046 av_log(s, AV_LOG_ERROR,
6047 "%s in MP4 support is experimental, add "
6048 "'-strict %d' if you want to use it.\n",
6049 avcodec_get_name(track->par->codec_id), FF_COMPLIANCE_EXPERIMENTAL);
6050 return AVERROR_EXPERIMENTAL;
6053 } else if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) {
6054 track->timescale = st->time_base.den;
6055 } else if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA) {
6056 track->timescale = st->time_base.den;
6058 track->timescale = MOV_TIMESCALE;
6061 track->height = st->codecpar->height;
6062 /* The ism specific timescale isn't mandatory, but is assumed by
6063 * some tools, such as mp4split. */
6064 if (mov->mode == MODE_ISM)
6065 track->timescale = 10000000;
6067 avpriv_set_pts_info(st, 64, 1, track->timescale);
6069 if (mov->encryption_scheme == MOV_ENC_CENC_AES_CTR) {
6070 ret = ff_mov_cenc_init(&track->cenc, mov->encryption_key,
6071 track->par->codec_id == AV_CODEC_ID_H264, s->flags & AVFMT_FLAG_BITEXACT);
6081 static int mov_write_header(AVFormatContext *s)
6083 AVIOContext *pb = s->pb;
6084 MOVMuxContext *mov = s->priv_data;
6085 AVDictionaryEntry *t, *global_tcr = av_dict_get(s->metadata, "timecode", NULL, 0);
6086 int i, ret, hint_track = 0, tmcd_track = 0, nb_tracks = s->nb_streams;
6088 if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters)
6091 if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
6092 /* Add hint tracks for each audio and video stream */
6093 hint_track = nb_tracks;
6094 for (i = 0; i < s->nb_streams; i++) {
6095 AVStream *st = s->streams[i];
6096 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ||
6097 st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
6103 if (mov->mode == MODE_MOV || mov->mode == MODE_MP4)
6104 tmcd_track = nb_tracks;
6106 for (i = 0; i < s->nb_streams; i++) {
6108 AVStream *st= s->streams[i];
6109 MOVTrack *track= &mov->tracks[i];
6111 /* copy extradata if it exists */
6112 if (st->codecpar->extradata_size) {
6113 if (st->codecpar->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
6114 mov_create_dvd_sub_decoder_specific_info(track, st);
6115 else if (!TAG_IS_AVCI(track->tag) && st->codecpar->codec_id != AV_CODEC_ID_DNXHD) {
6116 track->vos_len = st->codecpar->extradata_size;
6117 track->vos_data = av_malloc(track->vos_len);
6118 if (!track->vos_data) {
6119 return AVERROR(ENOMEM);
6121 memcpy(track->vos_data, st->codecpar->extradata, track->vos_len);
6125 if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ||
6126 track->par->channel_layout != AV_CH_LAYOUT_MONO)
6129 for (j = 0; j < s->nb_streams; j++) {
6130 AVStream *stj= s->streams[j];
6131 MOVTrack *trackj= &mov->tracks[j];
6135 if (stj->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ||
6136 trackj->par->channel_layout != AV_CH_LAYOUT_MONO ||
6137 trackj->language != track->language ||
6138 trackj->tag != track->tag
6141 track->multichannel_as_mono++;
6145 if (!(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
6146 if ((ret = mov_write_identification(pb, s)) < 0)
6150 if (mov->reserved_moov_size){
6151 mov->reserved_header_pos = avio_tell(pb);
6152 if (mov->reserved_moov_size > 0)
6153 avio_skip(pb, mov->reserved_moov_size);
6156 if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
6157 /* If no fragmentation options have been set, set a default. */
6158 if (!(mov->flags & (FF_MOV_FLAG_FRAG_KEYFRAME |
6159 FF_MOV_FLAG_FRAG_CUSTOM)) &&
6160 !mov->max_fragment_duration && !mov->max_fragment_size)
6161 mov->flags |= FF_MOV_FLAG_FRAG_KEYFRAME;
6163 if (mov->flags & FF_MOV_FLAG_FASTSTART)
6164 mov->reserved_header_pos = avio_tell(pb);
6165 mov_write_mdat_tag(pb, mov);
6168 ff_parse_creation_time_metadata(s, &mov->time, 1);
6170 mov->time += 0x7C25B080; // 1970 based -> 1904 based
6172 if (mov->chapter_track)
6173 if ((ret = mov_create_chapter_track(s, mov->chapter_track)) < 0)
6176 if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
6177 /* Initialize the hint tracks for each audio and video stream */
6178 for (i = 0; i < s->nb_streams; i++) {
6179 AVStream *st = s->streams[i];
6180 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ||
6181 st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
6182 if ((ret = ff_mov_init_hinting(s, hint_track, i)) < 0)
6189 if (mov->nb_meta_tmcd) {
6190 /* Initialize the tmcd tracks */
6191 for (i = 0; i < s->nb_streams; i++) {
6192 AVStream *st = s->streams[i];
6195 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
6198 t = av_dict_get(st->metadata, "timecode", NULL, 0);
6201 if (mov_check_timecode_track(s, &tc, i, t->value) < 0)
6203 if ((ret = mov_create_timecode_track(s, tmcd_track, i, tc)) < 0)
6212 if (mov->flags & FF_MOV_FLAG_ISML)
6213 mov_write_isml_manifest(pb, mov, s);
6215 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV &&
6216 !(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
6217 if ((ret = mov_write_moov_tag(pb, mov, s)) < 0)
6220 mov->moov_written = 1;
6221 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
6222 mov->reserved_header_pos = avio_tell(pb);
6228 static int get_moov_size(AVFormatContext *s)
6231 AVIOContext *moov_buf;
6232 MOVMuxContext *mov = s->priv_data;
6234 if ((ret = ffio_open_null_buf(&moov_buf)) < 0)
6236 if ((ret = mov_write_moov_tag(moov_buf, mov, s)) < 0)
6238 return ffio_close_null_buf(moov_buf);
6241 static int get_sidx_size(AVFormatContext *s)
6245 MOVMuxContext *mov = s->priv_data;
6247 if ((ret = ffio_open_null_buf(&buf)) < 0)
6249 mov_write_sidx_tags(buf, mov, -1, 0);
6250 return ffio_close_null_buf(buf);
6254 * This function gets the moov size if moved to the top of the file: the chunk
6255 * offset table can switch between stco (32-bit entries) to co64 (64-bit
6256 * entries) when the moov is moved to the beginning, so the size of the moov
6257 * would change. It also updates the chunk offset tables.
6259 static int compute_moov_size(AVFormatContext *s)
6261 int i, moov_size, moov_size2;
6262 MOVMuxContext *mov = s->priv_data;
6264 moov_size = get_moov_size(s);
6268 for (i = 0; i < mov->nb_streams; i++)
6269 mov->tracks[i].data_offset += moov_size;
6271 moov_size2 = get_moov_size(s);
6275 /* if the size changed, we just switched from stco to co64 and need to
6276 * update the offsets */
6277 if (moov_size2 != moov_size)
6278 for (i = 0; i < mov->nb_streams; i++)
6279 mov->tracks[i].data_offset += moov_size2 - moov_size;
6284 static int compute_sidx_size(AVFormatContext *s)
6287 MOVMuxContext *mov = s->priv_data;
6289 sidx_size = get_sidx_size(s);
6293 for (i = 0; i < mov->nb_streams; i++)
6294 mov->tracks[i].data_offset += sidx_size;
6299 static int shift_data(AVFormatContext *s)
6301 int ret = 0, moov_size;
6302 MOVMuxContext *mov = s->priv_data;
6303 int64_t pos, pos_end = avio_tell(s->pb);
6304 uint8_t *buf, *read_buf[2];
6305 int read_buf_id = 0;
6307 AVIOContext *read_pb;
6309 if (mov->flags & FF_MOV_FLAG_FRAGMENT)
6310 moov_size = compute_sidx_size(s);
6312 moov_size = compute_moov_size(s);
6316 buf = av_malloc(moov_size * 2);
6318 return AVERROR(ENOMEM);
6320 read_buf[1] = buf + moov_size;
6322 /* Shift the data: the AVIO context of the output can only be used for
6323 * writing, so we re-open the same output, but for reading. It also avoids
6324 * a read/seek/write/seek back and forth. */
6326 ret = s->io_open(s, &read_pb, s->filename, AVIO_FLAG_READ, NULL);
6328 av_log(s, AV_LOG_ERROR, "Unable to re-open %s output file for "
6329 "the second pass (faststart)\n", s->filename);
6333 /* mark the end of the shift to up to the last data we wrote, and get ready
6335 pos_end = avio_tell(s->pb);
6336 avio_seek(s->pb, mov->reserved_header_pos + moov_size, SEEK_SET);
6338 /* start reading at where the new moov will be placed */
6339 avio_seek(read_pb, mov->reserved_header_pos, SEEK_SET);
6340 pos = avio_tell(read_pb);
6342 #define READ_BLOCK do { \
6343 read_size[read_buf_id] = avio_read(read_pb, read_buf[read_buf_id], moov_size); \
6347 /* shift data by chunk of at most moov_size */
6352 n = read_size[read_buf_id];
6355 avio_write(s->pb, read_buf[read_buf_id], n);
6357 } while (pos < pos_end);
6358 ff_format_io_close(s, &read_pb);
6365 static int mov_write_trailer(AVFormatContext *s)
6367 MOVMuxContext *mov = s->priv_data;
6368 AVIOContext *pb = s->pb;
6373 if (mov->need_rewrite_extradata) {
6374 for (i = 0; i < s->nb_streams; i++) {
6375 MOVTrack *track = &mov->tracks[i];
6376 AVCodecParameters *par = track->par;
6378 track->vos_len = par->extradata_size;
6379 track->vos_data = av_malloc(track->vos_len);
6380 if (!track->vos_data)
6381 return AVERROR(ENOMEM);
6382 memcpy(track->vos_data, par->extradata, track->vos_len);
6384 mov->need_rewrite_extradata = 0;
6388 * Before actually writing the trailer, make sure that there are no
6389 * dangling subtitles, that need a terminating sample.
6391 for (i = 0; i < mov->nb_streams; i++) {
6392 MOVTrack *trk = &mov->tracks[i];
6393 if (trk->par->codec_id == AV_CODEC_ID_MOV_TEXT &&
6394 !trk->last_sample_is_subtitle_end) {
6395 mov_write_subtitle_end_packet(s, i, trk->track_duration);
6396 trk->last_sample_is_subtitle_end = 1;
6400 // If there were no chapters when the header was written, but there
6401 // are chapters now, write them in the trailer. This only works
6402 // when we are not doing fragments.
6403 if (!mov->chapter_track && !(mov->flags & FF_MOV_FLAG_FRAGMENT)) {
6404 if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters) {
6405 mov->chapter_track = mov->nb_streams++;
6406 if ((res = mov_create_chapter_track(s, mov->chapter_track)) < 0)
6411 if (!(mov->flags & FF_MOV_FLAG_FRAGMENT)) {
6412 moov_pos = avio_tell(pb);
6414 /* Write size of mdat tag */
6415 if (mov->mdat_size + 8 <= UINT32_MAX) {
6416 avio_seek(pb, mov->mdat_pos, SEEK_SET);
6417 avio_wb32(pb, mov->mdat_size + 8);
6419 /* overwrite 'wide' placeholder atom */
6420 avio_seek(pb, mov->mdat_pos - 8, SEEK_SET);
6421 /* special value: real atom size will be 64 bit value after
6424 ffio_wfourcc(pb, "mdat");
6425 avio_wb64(pb, mov->mdat_size + 16);
6427 avio_seek(pb, mov->reserved_moov_size > 0 ? mov->reserved_header_pos : moov_pos, SEEK_SET);
6429 if (mov->flags & FF_MOV_FLAG_FASTSTART) {
6430 av_log(s, AV_LOG_INFO, "Starting second pass: moving the moov atom to the beginning of the file\n");
6431 res = shift_data(s);
6434 avio_seek(pb, mov->reserved_header_pos, SEEK_SET);
6435 if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
6437 } else if (mov->reserved_moov_size > 0) {
6439 if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
6441 size = mov->reserved_moov_size - (avio_tell(pb) - mov->reserved_header_pos);
6443 av_log(s, AV_LOG_ERROR, "reserved_moov_size is too small, needed %"PRId64" additional\n", 8-size);
6444 return AVERROR(EINVAL);
6446 avio_wb32(pb, size);
6447 ffio_wfourcc(pb, "free");
6448 ffio_fill(pb, 0, size - 8);
6449 avio_seek(pb, moov_pos, SEEK_SET);
6451 if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
6456 mov_auto_flush_fragment(s, 1);
6457 for (i = 0; i < mov->nb_streams; i++)
6458 mov->tracks[i].data_offset = 0;
6459 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) {
6461 av_log(s, AV_LOG_INFO, "Starting second pass: inserting sidx atoms\n");
6462 res = shift_data(s);
6465 end = avio_tell(pb);
6466 avio_seek(pb, mov->reserved_header_pos, SEEK_SET);
6467 mov_write_sidx_tags(pb, mov, -1, 0);
6468 avio_seek(pb, end, SEEK_SET);
6469 avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_TRAILER);
6470 mov_write_mfra_tag(pb, mov);
6471 } else if (!(mov->flags & FF_MOV_FLAG_SKIP_TRAILER)) {
6472 avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_TRAILER);
6473 mov_write_mfra_tag(pb, mov);
6480 static int mov_check_bitstream(struct AVFormatContext *s, const AVPacket *pkt)
6483 AVStream *st = s->streams[pkt->stream_index];
6485 if (st->codecpar->codec_id == AV_CODEC_ID_AAC) {
6486 if (pkt->size > 2 && (AV_RB16(pkt->data) & 0xfff0) == 0xfff0)
6487 ret = ff_stream_add_bitstream_filter(st, "aac_adtstoasc", NULL);
6488 } else if (st->codecpar->codec_id == AV_CODEC_ID_VP9) {
6489 ret = ff_stream_add_bitstream_filter(st, "vp9_superframe", NULL);
6495 #if CONFIG_MOV_MUXER
6497 AVOutputFormat ff_mov_muxer = {
6499 .long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
6500 .extensions = "mov",
6501 .priv_data_size = sizeof(MOVMuxContext),
6502 .audio_codec = AV_CODEC_ID_AAC,
6503 .video_codec = CONFIG_LIBX264_ENCODER ?
6504 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
6506 .write_header = mov_write_header,
6507 .write_packet = mov_write_packet,
6508 .write_trailer = mov_write_trailer,
6510 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6511 .codec_tag = (const AVCodecTag* const []){
6512 ff_codec_movvideo_tags, ff_codec_movaudio_tags, 0
6514 .check_bitstream = mov_check_bitstream,
6515 .priv_class = &mov_muxer_class,
6518 #if CONFIG_TGP_MUXER
6520 AVOutputFormat ff_tgp_muxer = {
6522 .long_name = NULL_IF_CONFIG_SMALL("3GP (3GPP file format)"),
6523 .extensions = "3gp",
6524 .priv_data_size = sizeof(MOVMuxContext),
6525 .audio_codec = AV_CODEC_ID_AMR_NB,
6526 .video_codec = AV_CODEC_ID_H263,
6528 .write_header = mov_write_header,
6529 .write_packet = mov_write_packet,
6530 .write_trailer = mov_write_trailer,
6532 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6533 .codec_tag = (const AVCodecTag* const []){ codec_3gp_tags, 0 },
6534 .check_bitstream = mov_check_bitstream,
6535 .priv_class = &tgp_muxer_class,
6538 #if CONFIG_MP4_MUXER
6540 AVOutputFormat ff_mp4_muxer = {
6542 .long_name = NULL_IF_CONFIG_SMALL("MP4 (MPEG-4 Part 14)"),
6543 .mime_type = "video/mp4",
6544 .extensions = "mp4",
6545 .priv_data_size = sizeof(MOVMuxContext),
6546 .audio_codec = AV_CODEC_ID_AAC,
6547 .video_codec = CONFIG_LIBX264_ENCODER ?
6548 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
6550 .write_header = mov_write_header,
6551 .write_packet = mov_write_packet,
6552 .write_trailer = mov_write_trailer,
6554 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6555 .codec_tag = (const AVCodecTag* const []){ ff_mp4_obj_type, 0 },
6556 .check_bitstream = mov_check_bitstream,
6557 .priv_class = &mp4_muxer_class,
6560 #if CONFIG_PSP_MUXER
6562 AVOutputFormat ff_psp_muxer = {
6564 .long_name = NULL_IF_CONFIG_SMALL("PSP MP4 (MPEG-4 Part 14)"),
6565 .extensions = "mp4,psp",
6566 .priv_data_size = sizeof(MOVMuxContext),
6567 .audio_codec = AV_CODEC_ID_AAC,
6568 .video_codec = CONFIG_LIBX264_ENCODER ?
6569 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
6571 .write_header = mov_write_header,
6572 .write_packet = mov_write_packet,
6573 .write_trailer = mov_write_trailer,
6575 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6576 .codec_tag = (const AVCodecTag* const []){ ff_mp4_obj_type, 0 },
6577 .check_bitstream = mov_check_bitstream,
6578 .priv_class = &psp_muxer_class,
6581 #if CONFIG_TG2_MUXER
6583 AVOutputFormat ff_tg2_muxer = {
6585 .long_name = NULL_IF_CONFIG_SMALL("3GP2 (3GPP2 file format)"),
6586 .extensions = "3g2",
6587 .priv_data_size = sizeof(MOVMuxContext),
6588 .audio_codec = AV_CODEC_ID_AMR_NB,
6589 .video_codec = AV_CODEC_ID_H263,
6591 .write_header = mov_write_header,
6592 .write_packet = mov_write_packet,
6593 .write_trailer = mov_write_trailer,
6595 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6596 .codec_tag = (const AVCodecTag* const []){ codec_3gp_tags, 0 },
6597 .check_bitstream = mov_check_bitstream,
6598 .priv_class = &tg2_muxer_class,
6601 #if CONFIG_IPOD_MUXER
6603 AVOutputFormat ff_ipod_muxer = {
6605 .long_name = NULL_IF_CONFIG_SMALL("iPod H.264 MP4 (MPEG-4 Part 14)"),
6606 .mime_type = "video/mp4",
6607 .extensions = "m4v,m4a",
6608 .priv_data_size = sizeof(MOVMuxContext),
6609 .audio_codec = AV_CODEC_ID_AAC,
6610 .video_codec = AV_CODEC_ID_H264,
6612 .write_header = mov_write_header,
6613 .write_packet = mov_write_packet,
6614 .write_trailer = mov_write_trailer,
6616 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6617 .codec_tag = (const AVCodecTag* const []){ codec_ipod_tags, 0 },
6618 .check_bitstream = mov_check_bitstream,
6619 .priv_class = &ipod_muxer_class,
6622 #if CONFIG_ISMV_MUXER
6624 AVOutputFormat ff_ismv_muxer = {
6626 .long_name = NULL_IF_CONFIG_SMALL("ISMV/ISMA (Smooth Streaming)"),
6627 .mime_type = "video/mp4",
6628 .extensions = "ismv,isma",
6629 .priv_data_size = sizeof(MOVMuxContext),
6630 .audio_codec = AV_CODEC_ID_AAC,
6631 .video_codec = AV_CODEC_ID_H264,
6633 .write_header = mov_write_header,
6634 .write_packet = mov_write_packet,
6635 .write_trailer = mov_write_trailer,
6637 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6638 .codec_tag = (const AVCodecTag* const []){ ff_mp4_obj_type, 0 },
6639 .check_bitstream = mov_check_bitstream,
6640 .priv_class = &ismv_muxer_class,
6643 #if CONFIG_F4V_MUXER
6645 AVOutputFormat ff_f4v_muxer = {
6647 .long_name = NULL_IF_CONFIG_SMALL("F4V Adobe Flash Video"),
6648 .mime_type = "application/f4v",
6649 .extensions = "f4v",
6650 .priv_data_size = sizeof(MOVMuxContext),
6651 .audio_codec = AV_CODEC_ID_AAC,
6652 .video_codec = AV_CODEC_ID_H264,
6654 .write_header = mov_write_header,
6655 .write_packet = mov_write_packet,
6656 .write_trailer = mov_write_trailer,
6658 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH,
6659 .codec_tag = (const AVCodecTag* const []){ codec_f4v_tags, 0 },
6660 .check_bitstream = mov_check_bitstream,
6661 .priv_class = &f4v_muxer_class,