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"
39 #include "libavcodec/internal.h"
40 #include "libavcodec/put_bits.h"
41 #include "libavcodec/vc1_common.h"
42 #include "libavcodec/raw.h"
44 #include "libavutil/avstring.h"
45 #include "libavutil/intfloat.h"
46 #include "libavutil/mathematics.h"
47 #include "libavutil/libm.h"
48 #include "libavutil/opt.h"
49 #include "libavutil/dict.h"
50 #include "libavutil/pixdesc.h"
51 #include "libavutil/stereo3d.h"
52 #include "libavutil/timecode.h"
53 #include "libavutil/color_utils.h"
59 static const AVOption options[] = {
60 { "movflags", "MOV muxer flags", offsetof(MOVMuxContext, flags), AV_OPT_TYPE_FLAGS, {.i64 = 0}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
61 { "rtphint", "Add RTP hint tracks", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_RTP_HINT}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
62 { "moov_size", "maximum moov size so it can be placed at the begin", offsetof(MOVMuxContext, reserved_moov_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, 0 },
63 { "empty_moov", "Make the initial moov atom empty", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_EMPTY_MOOV}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
64 { "frag_keyframe", "Fragment at video keyframes", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FRAG_KEYFRAME}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
65 { "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" },
66 { "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" },
67 { "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" },
68 { "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" },
69 { "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" },
70 { "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" },
71 { "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" },
72 { "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" },
73 { "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" },
74 { "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" },
75 { "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" },
76 { "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" },
77 { "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" },
78 { "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" },
79 { "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" },
80 FF_RTP_FLAG_OPTS(MOVMuxContext, rtp_flags),
81 { "skip_iods", "Skip writing iods atom.", offsetof(MOVMuxContext, iods_skip), AV_OPT_TYPE_BOOL, {.i64 = 1}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM},
82 { "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},
83 { "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},
84 { "frag_duration", "Maximum fragment duration", offsetof(MOVMuxContext, max_fragment_duration), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
85 { "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},
86 { "frag_size", "Maximum fragment size", offsetof(MOVMuxContext, max_fragment_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
87 { "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},
88 { "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},
89 { "brand", "Override major brand", offsetof(MOVMuxContext, major_brand), AV_OPT_TYPE_STRING, {.str = NULL}, .flags = AV_OPT_FLAG_ENCODING_PARAM },
90 { "use_editlist", "use edit list", offsetof(MOVMuxContext, use_editlist), AV_OPT_TYPE_BOOL, {.i64 = -1}, -1, 1, AV_OPT_FLAG_ENCODING_PARAM},
91 { "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},
92 { "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},
93 { "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 },
94 { "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 },
95 { "encryption_key", "The media encryption key (hex)", offsetof(MOVMuxContext, encryption_key), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_ENCODING_PARAM },
96 { "encryption_kid", "The media encryption key identifier (hex)", offsetof(MOVMuxContext, encryption_kid), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_ENCODING_PARAM },
97 { "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},
98 { "write_tmcd", "force or disable writing tmcd", offsetof(MOVMuxContext, write_tmcd), AV_OPT_TYPE_BOOL, {.i64 = -1}, -1, 1, AV_OPT_FLAG_ENCODING_PARAM},
102 #define MOV_CLASS(flavor)\
103 static const AVClass flavor ## _muxer_class = {\
104 .class_name = #flavor " muxer",\
105 .item_name = av_default_item_name,\
107 .version = LIBAVUTIL_VERSION_INT,\
110 static int get_moov_size(AVFormatContext *s);
112 static int utf8len(const uint8_t *b)
117 GET_UTF8(val, *b++, return -1;)
123 //FIXME support 64 bit variant with wide placeholders
124 static int64_t update_size(AVIOContext *pb, int64_t pos)
126 int64_t curpos = avio_tell(pb);
127 avio_seek(pb, pos, SEEK_SET);
128 avio_wb32(pb, curpos - pos); /* rewrite size */
129 avio_seek(pb, curpos, SEEK_SET);
134 static int co64_required(const MOVTrack *track)
136 if (track->entry > 0 && track->cluster[track->entry - 1].pos + track->data_offset > UINT32_MAX)
141 /* Chunk offset atom */
142 static int mov_write_stco_tag(AVIOContext *pb, MOVTrack *track)
145 int mode64 = co64_required(track); // use 32 bit size variant if possible
146 int64_t pos = avio_tell(pb);
147 avio_wb32(pb, 0); /* size */
149 ffio_wfourcc(pb, "co64");
151 ffio_wfourcc(pb, "stco");
152 avio_wb32(pb, 0); /* version & flags */
153 avio_wb32(pb, track->chunkCount); /* entry count */
154 for (i = 0; i < track->entry; i++) {
155 if (!track->cluster[i].chunkNum)
158 avio_wb64(pb, track->cluster[i].pos + track->data_offset);
160 avio_wb32(pb, track->cluster[i].pos + track->data_offset);
162 return update_size(pb, pos);
165 /* Sample size atom */
166 static int mov_write_stsz_tag(AVIOContext *pb, MOVTrack *track)
169 int i, j, entries = 0, tst = -1, oldtst = -1;
171 int64_t pos = avio_tell(pb);
172 avio_wb32(pb, 0); /* size */
173 ffio_wfourcc(pb, "stsz");
174 avio_wb32(pb, 0); /* version & flags */
176 for (i = 0; i < track->entry; i++) {
177 tst = track->cluster[i].size / track->cluster[i].entries;
178 if (oldtst != -1 && tst != oldtst)
181 entries += track->cluster[i].entries;
183 if (equalChunks && track->entry) {
184 int sSize = track->entry ? track->cluster[0].size / track->cluster[0].entries : 0;
185 sSize = FFMAX(1, sSize); // adpcm mono case could make sSize == 0
186 avio_wb32(pb, sSize); // sample size
187 avio_wb32(pb, entries); // sample count
189 avio_wb32(pb, 0); // sample size
190 avio_wb32(pb, entries); // sample count
191 for (i = 0; i < track->entry; i++) {
192 for (j = 0; j < track->cluster[i].entries; j++) {
193 avio_wb32(pb, track->cluster[i].size /
194 track->cluster[i].entries);
198 return update_size(pb, pos);
201 /* Sample to chunk atom */
202 static int mov_write_stsc_tag(AVIOContext *pb, MOVTrack *track)
204 int index = 0, oldval = -1, i;
205 int64_t entryPos, curpos;
207 int64_t pos = avio_tell(pb);
208 avio_wb32(pb, 0); /* size */
209 ffio_wfourcc(pb, "stsc");
210 avio_wb32(pb, 0); // version & flags
211 entryPos = avio_tell(pb);
212 avio_wb32(pb, track->chunkCount); // entry count
213 for (i = 0; i < track->entry; i++) {
214 if (oldval != track->cluster[i].samples_in_chunk && track->cluster[i].chunkNum) {
215 avio_wb32(pb, track->cluster[i].chunkNum); // first chunk
216 avio_wb32(pb, track->cluster[i].samples_in_chunk); // samples per chunk
217 avio_wb32(pb, 0x1); // sample description index
218 oldval = track->cluster[i].samples_in_chunk;
222 curpos = avio_tell(pb);
223 avio_seek(pb, entryPos, SEEK_SET);
224 avio_wb32(pb, index); // rewrite size
225 avio_seek(pb, curpos, SEEK_SET);
227 return update_size(pb, pos);
230 /* Sync sample atom */
231 static int mov_write_stss_tag(AVIOContext *pb, MOVTrack *track, uint32_t flag)
233 int64_t curpos, entryPos;
235 int64_t pos = avio_tell(pb);
236 avio_wb32(pb, 0); // size
237 ffio_wfourcc(pb, flag == MOV_SYNC_SAMPLE ? "stss" : "stps");
238 avio_wb32(pb, 0); // version & flags
239 entryPos = avio_tell(pb);
240 avio_wb32(pb, track->entry); // entry count
241 for (i = 0; i < track->entry; i++) {
242 if (track->cluster[i].flags & flag) {
243 avio_wb32(pb, i + 1);
247 curpos = avio_tell(pb);
248 avio_seek(pb, entryPos, SEEK_SET);
249 avio_wb32(pb, index); // rewrite size
250 avio_seek(pb, curpos, SEEK_SET);
251 return update_size(pb, pos);
254 static int mov_write_amr_tag(AVIOContext *pb, MOVTrack *track)
256 avio_wb32(pb, 0x11); /* size */
257 if (track->mode == MODE_MOV) ffio_wfourcc(pb, "samr");
258 else ffio_wfourcc(pb, "damr");
259 ffio_wfourcc(pb, "FFMP");
260 avio_w8(pb, 0); /* decoder version */
262 avio_wb16(pb, 0x81FF); /* Mode set (all modes for AMR_NB) */
263 avio_w8(pb, 0x00); /* Mode change period (no restriction) */
264 avio_w8(pb, 0x01); /* Frames per sample */
268 static int mov_write_ac3_tag(AVIOContext *pb, MOVTrack *track)
273 int fscod, bsid, bsmod, acmod, lfeon, frmsizecod;
275 if (track->vos_len < 7)
279 ffio_wfourcc(pb, "dac3");
281 init_get_bits(&gbc, track->vos_data + 4, (track->vos_len - 4) * 8);
282 fscod = get_bits(&gbc, 2);
283 frmsizecod = get_bits(&gbc, 6);
284 bsid = get_bits(&gbc, 5);
285 bsmod = get_bits(&gbc, 3);
286 acmod = get_bits(&gbc, 3);
288 skip_bits(&gbc, 2); // dsurmod
290 if ((acmod & 1) && acmod != 1)
291 skip_bits(&gbc, 2); // cmixlev
293 skip_bits(&gbc, 2); // surmixlev
295 lfeon = get_bits1(&gbc);
297 init_put_bits(&pbc, buf, sizeof(buf));
298 put_bits(&pbc, 2, fscod);
299 put_bits(&pbc, 5, bsid);
300 put_bits(&pbc, 3, bsmod);
301 put_bits(&pbc, 3, acmod);
302 put_bits(&pbc, 1, lfeon);
303 put_bits(&pbc, 5, frmsizecod >> 1); // bit_rate_code
304 put_bits(&pbc, 5, 0); // reserved
306 flush_put_bits(&pbc);
307 avio_write(pb, buf, sizeof(buf));
317 /* Layout of the EC3SpecificBox */
318 /* maximum bitrate */
320 /* number of independent substreams */
323 /* sample rate code (see ff_ac3_sample_rate_tab) 2 bits */
325 /* bit stream identification 5 bits */
327 /* one bit reserved */
328 /* audio service mixing (not supported yet) 1 bit */
329 /* bit stream mode 3 bits */
331 /* audio coding mode 3 bits */
333 /* sub woofer on 1 bit */
335 /* 3 bits reserved */
336 /* number of dependent substreams associated with this substream 4 bits */
338 /* channel locations of the dependent substream(s), if any, 9 bits */
340 /* if there is no dependent substream, then one bit reserved instead */
341 } substream[1]; /* TODO: support 8 independent substreams */
344 #if CONFIG_AC3_PARSER
345 static int handle_eac3(MOVMuxContext *mov, AVPacket *pkt, MOVTrack *track)
348 AC3HeaderInfo tmp, *hdr = &tmp;
349 struct eac3_info *info;
352 if (!track->eac3_priv && !(track->eac3_priv = av_mallocz(sizeof(*info))))
353 return AVERROR(ENOMEM);
354 info = track->eac3_priv;
356 init_get_bits(&gbc, pkt->data, pkt->size * 8);
357 if (avpriv_ac3_parse_header(&gbc, &hdr) < 0) {
358 /* drop the packets until we see a good one */
360 av_log(mov, AV_LOG_WARNING, "Dropping invalid packet from start of the stream\n");
363 return AVERROR_INVALIDDATA;
366 info->data_rate = FFMAX(info->data_rate, hdr->bit_rate / 1000);
367 num_blocks = hdr->num_blocks;
369 if (!info->ec3_done) {
370 /* AC-3 substream must be the first one */
371 if (hdr->bitstream_id <= 10 && hdr->substreamid != 0)
372 return AVERROR(EINVAL);
374 /* this should always be the case, given that our AC-3 parser
375 * concatenates dependent frames to their independent parent */
376 if (hdr->frame_type == EAC3_FRAME_TYPE_INDEPENDENT) {
377 /* substream ids must be incremental */
378 if (hdr->substreamid > info->num_ind_sub + 1)
379 return AVERROR(EINVAL);
381 if (hdr->substreamid == info->num_ind_sub + 1) {
382 //info->num_ind_sub++;
383 avpriv_request_sample(track->par, "Multiple independent substreams");
384 return AVERROR_PATCHWELCOME;
385 } else if (hdr->substreamid < info->num_ind_sub ||
386 hdr->substreamid == 0 && info->substream[0].bsid) {
392 /* fill the info needed for the "dec3" atom */
393 info->substream[hdr->substreamid].fscod = hdr->sr_code;
394 info->substream[hdr->substreamid].bsid = hdr->bitstream_id;
395 info->substream[hdr->substreamid].bsmod = hdr->bitstream_mode;
396 info->substream[hdr->substreamid].acmod = hdr->channel_mode;
397 info->substream[hdr->substreamid].lfeon = hdr->lfe_on;
399 /* Parse dependent substream(s), if any */
400 if (pkt->size != hdr->frame_size) {
401 int cumul_size = hdr->frame_size;
402 int parent = hdr->substreamid;
404 while (cumul_size != pkt->size) {
406 init_get_bits(&gbc, pkt->data + cumul_size, (pkt->size - cumul_size) * 8);
407 if (avpriv_ac3_parse_header(&gbc, &hdr) < 0)
408 return AVERROR_INVALIDDATA;
409 if (hdr->frame_type != EAC3_FRAME_TYPE_DEPENDENT)
410 return AVERROR(EINVAL);
411 cumul_size += hdr->frame_size;
412 info->substream[parent].num_dep_sub++;
414 /* header is parsed up to lfeon, but custom channel map may be needed */
417 /* skip volume control params */
418 for (i = 0; i < (hdr->channel_mode ? 1 : 2); i++) {
419 skip_bits(&gbc, 5); // skip dialog normalization
420 if (get_bits1(&gbc)) {
421 skip_bits(&gbc, 8); // skip compression gain word
424 /* get the dependent stream channel map, if exists */
426 info->substream[parent].chan_loc |= (get_bits(&gbc, 16) >> 5) & 0x1f;
428 info->substream[parent].chan_loc |= hdr->channel_mode;
434 if (!info->num_blocks && num_blocks == 6)
436 else if (info->num_blocks + num_blocks > 6)
437 return AVERROR_INVALIDDATA;
439 if (!info->num_blocks) {
441 if ((ret = av_copy_packet(&info->pkt, pkt)) < 0)
443 info->num_blocks = num_blocks;
447 if ((ret = av_grow_packet(&info->pkt, pkt->size)) < 0)
449 memcpy(info->pkt.data + info->pkt.size - pkt->size, pkt->data, pkt->size);
450 info->num_blocks += num_blocks;
451 info->pkt.duration += pkt->duration;
452 if ((ret = av_copy_packet_side_data(&info->pkt, pkt)) < 0)
454 if (info->num_blocks != 6)
456 av_packet_unref(pkt);
457 if ((ret = av_copy_packet(pkt, &info->pkt)) < 0)
459 av_packet_unref(&info->pkt);
460 info->num_blocks = 0;
467 static int mov_write_eac3_tag(AVIOContext *pb, MOVTrack *track)
471 struct eac3_info *info;
474 if (!track->eac3_priv)
475 return AVERROR(EINVAL);
477 info = track->eac3_priv;
478 size = 2 + 4 * (info->num_ind_sub + 1);
479 buf = av_malloc(size);
481 size = AVERROR(ENOMEM);
485 init_put_bits(&pbc, buf, size);
486 put_bits(&pbc, 13, info->data_rate);
487 put_bits(&pbc, 3, info->num_ind_sub);
488 for (i = 0; i <= info->num_ind_sub; i++) {
489 put_bits(&pbc, 2, info->substream[i].fscod);
490 put_bits(&pbc, 5, info->substream[i].bsid);
491 put_bits(&pbc, 1, 0); /* reserved */
492 put_bits(&pbc, 1, 0); /* asvc */
493 put_bits(&pbc, 3, info->substream[i].bsmod);
494 put_bits(&pbc, 3, info->substream[i].acmod);
495 put_bits(&pbc, 1, info->substream[i].lfeon);
496 put_bits(&pbc, 5, 0); /* reserved */
497 put_bits(&pbc, 4, info->substream[i].num_dep_sub);
498 if (!info->substream[i].num_dep_sub) {
499 put_bits(&pbc, 1, 0); /* reserved */
502 put_bits(&pbc, 9, info->substream[i].chan_loc);
505 flush_put_bits(&pbc);
507 avio_wb32(pb, size + 8);
508 ffio_wfourcc(pb, "dec3");
509 avio_write(pb, buf, size);
514 av_packet_unref(&info->pkt);
515 av_freep(&track->eac3_priv);
521 * This function writes extradata "as is".
522 * Extradata must be formatted like a valid atom (with size and tag).
524 static int mov_write_extradata_tag(AVIOContext *pb, MOVTrack *track)
526 avio_write(pb, track->par->extradata, track->par->extradata_size);
527 return track->par->extradata_size;
530 static int mov_write_enda_tag(AVIOContext *pb)
533 ffio_wfourcc(pb, "enda");
534 avio_wb16(pb, 1); /* little endian */
538 static int mov_write_enda_tag_be(AVIOContext *pb)
541 ffio_wfourcc(pb, "enda");
542 avio_wb16(pb, 0); /* big endian */
546 static void put_descr(AVIOContext *pb, int tag, unsigned int size)
551 avio_w8(pb, (size >> (7 * i)) | 0x80);
552 avio_w8(pb, size & 0x7F);
555 static unsigned compute_avg_bitrate(MOVTrack *track)
559 if (!track->track_duration)
561 for (i = 0; i < track->entry; i++)
562 size += track->cluster[i].size;
563 return size * 8 * track->timescale / track->track_duration;
566 static int mov_write_esds_tag(AVIOContext *pb, MOVTrack *track) // Basic
568 AVCPBProperties *props;
569 int64_t pos = avio_tell(pb);
570 int decoder_specific_info_len = track->vos_len ? 5 + track->vos_len : 0;
571 unsigned avg_bitrate;
573 avio_wb32(pb, 0); // size
574 ffio_wfourcc(pb, "esds");
575 avio_wb32(pb, 0); // Version
578 put_descr(pb, 0x03, 3 + 5+13 + decoder_specific_info_len + 5+1);
579 avio_wb16(pb, track->track_id);
580 avio_w8(pb, 0x00); // flags (= no flags)
582 // DecoderConfig descriptor
583 put_descr(pb, 0x04, 13 + decoder_specific_info_len);
585 // Object type indication
586 if ((track->par->codec_id == AV_CODEC_ID_MP2 ||
587 track->par->codec_id == AV_CODEC_ID_MP3) &&
588 track->par->sample_rate > 24000)
589 avio_w8(pb, 0x6B); // 11172-3
591 avio_w8(pb, ff_codec_get_tag(ff_mp4_obj_type, track->par->codec_id));
593 // the following fields is made of 6 bits to identify the streamtype (4 for video, 5 for audio)
594 // plus 1 bit to indicate upstream and 1 bit set to 1 (reserved)
595 if (track->par->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
596 avio_w8(pb, (0x38 << 2) | 1); // flags (= NeroSubpicStream)
597 else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
598 avio_w8(pb, 0x15); // flags (= Audiostream)
600 avio_w8(pb, 0x11); // flags (= Visualstream)
602 props = (AVCPBProperties*)av_stream_get_side_data(track->st, AV_PKT_DATA_CPB_PROPERTIES,
605 avio_wb24(pb, props ? props->buffer_size / 8 : 0); // Buffersize DB
607 avg_bitrate = compute_avg_bitrate(track);
608 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)
609 avio_wb32(pb, avg_bitrate);
611 if (track->vos_len) {
612 // DecoderSpecific info descriptor
613 put_descr(pb, 0x05, track->vos_len);
614 avio_write(pb, track->vos_data, track->vos_len);
618 put_descr(pb, 0x06, 1);
620 return update_size(pb, pos);
623 static int mov_pcm_le_gt16(enum AVCodecID codec_id)
625 return codec_id == AV_CODEC_ID_PCM_S24LE ||
626 codec_id == AV_CODEC_ID_PCM_S32LE ||
627 codec_id == AV_CODEC_ID_PCM_F32LE ||
628 codec_id == AV_CODEC_ID_PCM_F64LE;
631 static int mov_pcm_be_gt16(enum AVCodecID codec_id)
633 return codec_id == AV_CODEC_ID_PCM_S24BE ||
634 codec_id == AV_CODEC_ID_PCM_S32BE ||
635 codec_id == AV_CODEC_ID_PCM_F32BE ||
636 codec_id == AV_CODEC_ID_PCM_F64BE;
639 static int mov_write_ms_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
642 int64_t pos = avio_tell(pb);
644 avio_wl32(pb, track->tag); // store it byteswapped
645 track->par->codec_tag = av_bswap16(track->tag >> 16);
646 if ((ret = ff_put_wav_header(s, pb, track->par, 0)) < 0)
648 return update_size(pb, pos);
651 static int mov_write_wfex_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
654 int64_t pos = avio_tell(pb);
656 ffio_wfourcc(pb, "wfex");
657 if ((ret = ff_put_wav_header(s, pb, track->st->codecpar, FF_PUT_WAV_HEADER_FORCE_WAVEFORMATEX)) < 0)
659 return update_size(pb, pos);
662 static int mov_write_dfla_tag(AVIOContext *pb, MOVTrack *track)
664 int64_t pos = avio_tell(pb);
666 ffio_wfourcc(pb, "dfLa");
667 avio_w8(pb, 0); /* version */
668 avio_wb24(pb, 0); /* flags */
670 /* Expect the encoder to pass a METADATA_BLOCK_TYPE_STREAMINFO. */
671 if (track->par->extradata_size != FLAC_STREAMINFO_SIZE)
672 return AVERROR_INVALIDDATA;
674 /* TODO: Write other METADATA_BLOCK_TYPEs if the encoder makes them available. */
675 avio_w8(pb, 1 << 7 | FLAC_METADATA_TYPE_STREAMINFO); /* LastMetadataBlockFlag << 7 | BlockType */
676 avio_wb24(pb, track->par->extradata_size); /* Length */
677 avio_write(pb, track->par->extradata, track->par->extradata_size); /* BlockData[Length] */
679 return update_size(pb, pos);
682 static int mov_write_dops_tag(AVIOContext *pb, MOVTrack *track)
684 int64_t pos = avio_tell(pb);
686 ffio_wfourcc(pb, "dOps");
687 avio_w8(pb, 0); /* Version */
688 if (track->par->extradata_size < 19) {
689 av_log(pb, AV_LOG_ERROR, "invalid extradata size\n");
690 return AVERROR_INVALIDDATA;
692 /* extradata contains an Ogg OpusHead, other than byte-ordering and
693 OpusHead's preceeding magic/version, OpusSpecificBox is currently
695 avio_w8(pb, AV_RB8(track->par->extradata + 9)); /* OuputChannelCount */
696 avio_wb16(pb, AV_RL16(track->par->extradata + 10)); /* PreSkip */
697 avio_wb32(pb, AV_RL32(track->par->extradata + 12)); /* InputSampleRate */
698 avio_wb16(pb, AV_RL16(track->par->extradata + 16)); /* OutputGain */
699 /* Write the rest of the header out without byte-swapping. */
700 avio_write(pb, track->par->extradata + 18, track->par->extradata_size - 18);
702 return update_size(pb, pos);
705 static int mov_write_chan_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
707 uint32_t layout_tag, bitmap;
708 int64_t pos = avio_tell(pb);
710 layout_tag = ff_mov_get_channel_layout_tag(track->par->codec_id,
711 track->par->channel_layout,
714 av_log(s, AV_LOG_WARNING, "not writing 'chan' tag due to "
715 "lack of channel information\n");
719 if (track->multichannel_as_mono)
722 avio_wb32(pb, 0); // Size
723 ffio_wfourcc(pb, "chan"); // Type
724 avio_w8(pb, 0); // Version
725 avio_wb24(pb, 0); // Flags
726 avio_wb32(pb, layout_tag); // mChannelLayoutTag
727 avio_wb32(pb, bitmap); // mChannelBitmap
728 avio_wb32(pb, 0); // mNumberChannelDescriptions
730 return update_size(pb, pos);
733 static int mov_write_wave_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
735 int64_t pos = avio_tell(pb);
737 avio_wb32(pb, 0); /* size */
738 ffio_wfourcc(pb, "wave");
740 if (track->par->codec_id != AV_CODEC_ID_QDM2) {
741 avio_wb32(pb, 12); /* size */
742 ffio_wfourcc(pb, "frma");
743 avio_wl32(pb, track->tag);
746 if (track->par->codec_id == AV_CODEC_ID_AAC) {
747 /* useless atom needed by mplayer, ipod, not needed by quicktime */
748 avio_wb32(pb, 12); /* size */
749 ffio_wfourcc(pb, "mp4a");
751 mov_write_esds_tag(pb, track);
752 } else if (mov_pcm_le_gt16(track->par->codec_id)) {
753 mov_write_enda_tag(pb);
754 } else if (mov_pcm_be_gt16(track->par->codec_id)) {
755 mov_write_enda_tag_be(pb);
756 } else if (track->par->codec_id == AV_CODEC_ID_AMR_NB) {
757 mov_write_amr_tag(pb, track);
758 } else if (track->par->codec_id == AV_CODEC_ID_AC3) {
759 mov_write_ac3_tag(pb, track);
760 } else if (track->par->codec_id == AV_CODEC_ID_EAC3) {
761 mov_write_eac3_tag(pb, track);
762 } else if (track->par->codec_id == AV_CODEC_ID_ALAC ||
763 track->par->codec_id == AV_CODEC_ID_QDM2) {
764 mov_write_extradata_tag(pb, track);
765 } else if (track->par->codec_id == AV_CODEC_ID_ADPCM_MS ||
766 track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) {
767 mov_write_ms_tag(s, pb, track);
770 avio_wb32(pb, 8); /* size */
771 avio_wb32(pb, 0); /* null tag */
773 return update_size(pb, pos);
776 static int mov_write_dvc1_structs(MOVTrack *track, uint8_t *buf)
779 const uint8_t *start, *next, *end = track->vos_data + track->vos_len;
780 int unescaped_size, seq_found = 0;
781 int level = 0, interlace = 0;
782 int packet_seq = track->vc1_info.packet_seq;
783 int packet_entry = track->vc1_info.packet_entry;
784 int slices = track->vc1_info.slices;
787 if (track->start_dts == AV_NOPTS_VALUE) {
788 /* No packets written yet, vc1_info isn't authoritative yet. */
789 /* Assume inline sequence and entry headers. */
790 packet_seq = packet_entry = 1;
791 av_log(NULL, AV_LOG_WARNING,
792 "moov atom written before any packets, unable to write correct "
793 "dvc1 atom. Set the delay_moov flag to fix this.\n");
796 unescaped = av_mallocz(track->vos_len + AV_INPUT_BUFFER_PADDING_SIZE);
798 return AVERROR(ENOMEM);
799 start = find_next_marker(track->vos_data, end);
800 for (next = start; next < end; start = next) {
803 next = find_next_marker(start + 4, end);
804 size = next - start - 4;
807 unescaped_size = vc1_unescape_buffer(start + 4, size, unescaped);
808 init_get_bits(&gb, unescaped, 8 * unescaped_size);
809 if (AV_RB32(start) == VC1_CODE_SEQHDR) {
810 int profile = get_bits(&gb, 2);
811 if (profile != PROFILE_ADVANCED) {
813 return AVERROR(ENOSYS);
816 level = get_bits(&gb, 3);
817 /* chromaformat, frmrtq_postproc, bitrtq_postproc, postprocflag,
819 skip_bits_long(&gb, 2 + 3 + 5 + 1 + 2*12);
820 skip_bits(&gb, 1); /* broadcast */
821 interlace = get_bits1(&gb);
822 skip_bits(&gb, 4); /* tfcntrflag, finterpflag, reserved, psf */
827 return AVERROR(ENOSYS);
830 init_put_bits(&pbc, buf, 7);
831 /* VC1DecSpecStruc */
832 put_bits(&pbc, 4, 12); /* profile - advanced */
833 put_bits(&pbc, 3, level);
834 put_bits(&pbc, 1, 0); /* reserved */
835 /* VC1AdvDecSpecStruc */
836 put_bits(&pbc, 3, level);
837 put_bits(&pbc, 1, 0); /* cbr */
838 put_bits(&pbc, 6, 0); /* reserved */
839 put_bits(&pbc, 1, !interlace); /* no interlace */
840 put_bits(&pbc, 1, !packet_seq); /* no multiple seq */
841 put_bits(&pbc, 1, !packet_entry); /* no multiple entry */
842 put_bits(&pbc, 1, !slices); /* no slice code */
843 put_bits(&pbc, 1, 0); /* no bframe */
844 put_bits(&pbc, 1, 0); /* reserved */
847 if (track->st->avg_frame_rate.num > 0 && track->st->avg_frame_rate.den > 0)
848 put_bits32(&pbc, track->st->avg_frame_rate.num / track->st->avg_frame_rate.den);
850 put_bits32(&pbc, 0xffffffff);
852 flush_put_bits(&pbc);
859 static int mov_write_dvc1_tag(AVIOContext *pb, MOVTrack *track)
861 uint8_t buf[7] = { 0 };
864 if ((ret = mov_write_dvc1_structs(track, buf)) < 0)
867 avio_wb32(pb, track->vos_len + 8 + sizeof(buf));
868 ffio_wfourcc(pb, "dvc1");
869 avio_write(pb, buf, sizeof(buf));
870 avio_write(pb, track->vos_data, track->vos_len);
875 static int mov_write_glbl_tag(AVIOContext *pb, MOVTrack *track)
877 avio_wb32(pb, track->vos_len + 8);
878 ffio_wfourcc(pb, "glbl");
879 avio_write(pb, track->vos_data, track->vos_len);
880 return 8 + track->vos_len;
884 * Compute flags for 'lpcm' tag.
885 * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
887 static int mov_get_lpcm_flags(enum AVCodecID codec_id)
890 case AV_CODEC_ID_PCM_F32BE:
891 case AV_CODEC_ID_PCM_F64BE:
893 case AV_CODEC_ID_PCM_F32LE:
894 case AV_CODEC_ID_PCM_F64LE:
896 case AV_CODEC_ID_PCM_U8:
898 case AV_CODEC_ID_PCM_S16BE:
899 case AV_CODEC_ID_PCM_S24BE:
900 case AV_CODEC_ID_PCM_S32BE:
902 case AV_CODEC_ID_PCM_S8:
903 case AV_CODEC_ID_PCM_S16LE:
904 case AV_CODEC_ID_PCM_S24LE:
905 case AV_CODEC_ID_PCM_S32LE:
912 static int get_cluster_duration(MOVTrack *track, int cluster_idx)
916 if (cluster_idx >= track->entry)
919 if (cluster_idx + 1 == track->entry)
920 next_dts = track->track_duration + track->start_dts;
922 next_dts = track->cluster[cluster_idx + 1].dts;
924 next_dts -= track->cluster[cluster_idx].dts;
926 av_assert0(next_dts >= 0);
927 av_assert0(next_dts <= INT_MAX);
932 static int get_samples_per_packet(MOVTrack *track)
934 int i, first_duration;
936 // return track->par->frame_size;
938 /* use 1 for raw PCM */
939 if (!track->audio_vbr)
942 /* check to see if duration is constant for all clusters */
945 first_duration = get_cluster_duration(track, 0);
946 for (i = 1; i < track->entry; i++) {
947 if (get_cluster_duration(track, i) != first_duration)
950 return first_duration;
953 static int mov_write_audio_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
955 int64_t pos = avio_tell(pb);
957 uint32_t tag = track->tag;
959 if (track->mode == MODE_MOV) {
960 if (track->timescale > UINT16_MAX) {
961 if (mov_get_lpcm_flags(track->par->codec_id))
962 tag = AV_RL32("lpcm");
964 } else if (track->audio_vbr || mov_pcm_le_gt16(track->par->codec_id) ||
965 mov_pcm_be_gt16(track->par->codec_id) ||
966 track->par->codec_id == AV_CODEC_ID_ADPCM_MS ||
967 track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
968 track->par->codec_id == AV_CODEC_ID_QDM2) {
973 avio_wb32(pb, 0); /* size */
974 if (mov->encryption_scheme != MOV_ENC_NONE) {
975 ffio_wfourcc(pb, "enca");
977 avio_wl32(pb, tag); // store it byteswapped
979 avio_wb32(pb, 0); /* Reserved */
980 avio_wb16(pb, 0); /* Reserved */
981 avio_wb16(pb, 1); /* Data-reference index, XXX == 1 */
983 /* SoundDescription */
984 avio_wb16(pb, version); /* Version */
985 avio_wb16(pb, 0); /* Revision level */
986 avio_wb32(pb, 0); /* Reserved */
991 avio_wb16(pb, 0xfffe);
993 avio_wb32(pb, 0x00010000);
995 avio_wb64(pb, av_double2int(track->par->sample_rate));
996 avio_wb32(pb, track->par->channels);
997 avio_wb32(pb, 0x7F000000);
998 avio_wb32(pb, av_get_bits_per_sample(track->par->codec_id));
999 avio_wb32(pb, mov_get_lpcm_flags(track->par->codec_id));
1000 avio_wb32(pb, track->sample_size);
1001 avio_wb32(pb, get_samples_per_packet(track));
1003 if (track->mode == MODE_MOV) {
1004 avio_wb16(pb, track->par->channels);
1005 if (track->par->codec_id == AV_CODEC_ID_PCM_U8 ||
1006 track->par->codec_id == AV_CODEC_ID_PCM_S8)
1007 avio_wb16(pb, 8); /* bits per sample */
1008 else if (track->par->codec_id == AV_CODEC_ID_ADPCM_G726)
1009 avio_wb16(pb, track->par->bits_per_coded_sample);
1012 avio_wb16(pb, track->audio_vbr ? -2 : 0); /* compression ID */
1013 } else { /* reserved for mp4/3gp */
1014 if (track->par->codec_id == AV_CODEC_ID_FLAC ||
1015 track->par->codec_id == AV_CODEC_ID_OPUS) {
1016 avio_wb16(pb, track->par->channels);
1020 if (track->par->codec_id == AV_CODEC_ID_FLAC) {
1021 avio_wb16(pb, track->par->bits_per_raw_sample);
1028 avio_wb16(pb, 0); /* packet size (= 0) */
1029 if (track->par->codec_id == AV_CODEC_ID_OPUS)
1030 avio_wb16(pb, 48000);
1032 avio_wb16(pb, track->par->sample_rate <= UINT16_MAX ?
1033 track->par->sample_rate : 0);
1034 avio_wb16(pb, 0); /* Reserved */
1037 if (version == 1) { /* SoundDescription V1 extended info */
1038 if (mov_pcm_le_gt16(track->par->codec_id) ||
1039 mov_pcm_be_gt16(track->par->codec_id))
1040 avio_wb32(pb, 1); /* must be 1 for uncompressed formats */
1042 avio_wb32(pb, track->par->frame_size); /* Samples per packet */
1043 avio_wb32(pb, track->sample_size / track->par->channels); /* Bytes per packet */
1044 avio_wb32(pb, track->sample_size); /* Bytes per frame */
1045 avio_wb32(pb, 2); /* Bytes per sample */
1048 if (track->mode == MODE_MOV &&
1049 (track->par->codec_id == AV_CODEC_ID_AAC ||
1050 track->par->codec_id == AV_CODEC_ID_AC3 ||
1051 track->par->codec_id == AV_CODEC_ID_EAC3 ||
1052 track->par->codec_id == AV_CODEC_ID_AMR_NB ||
1053 track->par->codec_id == AV_CODEC_ID_ALAC ||
1054 track->par->codec_id == AV_CODEC_ID_ADPCM_MS ||
1055 track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
1056 track->par->codec_id == AV_CODEC_ID_QDM2 ||
1057 (mov_pcm_le_gt16(track->par->codec_id) && version==1) ||
1058 (mov_pcm_be_gt16(track->par->codec_id) && version==1)))
1059 mov_write_wave_tag(s, pb, track);
1060 else if (track->tag == MKTAG('m','p','4','a'))
1061 mov_write_esds_tag(pb, track);
1062 else if (track->par->codec_id == AV_CODEC_ID_AMR_NB)
1063 mov_write_amr_tag(pb, track);
1064 else if (track->par->codec_id == AV_CODEC_ID_AC3)
1065 mov_write_ac3_tag(pb, track);
1066 else if (track->par->codec_id == AV_CODEC_ID_EAC3)
1067 mov_write_eac3_tag(pb, track);
1068 else if (track->par->codec_id == AV_CODEC_ID_ALAC)
1069 mov_write_extradata_tag(pb, track);
1070 else if (track->par->codec_id == AV_CODEC_ID_WMAPRO)
1071 mov_write_wfex_tag(s, pb, track);
1072 else if (track->par->codec_id == AV_CODEC_ID_FLAC)
1073 mov_write_dfla_tag(pb, track);
1074 else if (track->par->codec_id == AV_CODEC_ID_OPUS)
1075 mov_write_dops_tag(pb, track);
1076 else if (track->vos_len > 0)
1077 mov_write_glbl_tag(pb, track);
1079 if (track->mode == MODE_MOV && track->par->codec_type == AVMEDIA_TYPE_AUDIO)
1080 mov_write_chan_tag(s, pb, track);
1082 if (mov->encryption_scheme != MOV_ENC_NONE) {
1083 ff_mov_cenc_write_sinf_tag(track, pb, mov->encryption_kid);
1086 return update_size(pb, pos);
1089 static int mov_write_d263_tag(AVIOContext *pb)
1091 avio_wb32(pb, 0xf); /* size */
1092 ffio_wfourcc(pb, "d263");
1093 ffio_wfourcc(pb, "FFMP");
1094 avio_w8(pb, 0); /* decoder version */
1095 /* FIXME use AVCodecContext level/profile, when encoder will set values */
1096 avio_w8(pb, 0xa); /* level */
1097 avio_w8(pb, 0); /* profile */
1101 static int mov_write_avcc_tag(AVIOContext *pb, MOVTrack *track)
1103 int64_t pos = avio_tell(pb);
1106 ffio_wfourcc(pb, "avcC");
1107 ff_isom_write_avcc(pb, track->vos_data, track->vos_len);
1108 return update_size(pb, pos);
1111 static int mov_write_vpcc_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
1113 int64_t pos = avio_tell(pb);
1116 ffio_wfourcc(pb, "vpcC");
1117 avio_w8(pb, 1); /* version */
1118 avio_wb24(pb, 0); /* flags */
1119 ff_isom_write_vpcc(s, pb, track->par);
1120 return update_size(pb, pos);
1123 static int mov_write_hvcc_tag(AVIOContext *pb, MOVTrack *track)
1125 int64_t pos = avio_tell(pb);
1128 ffio_wfourcc(pb, "hvcC");
1129 if (track->tag == MKTAG('h','v','c','1'))
1130 ff_isom_write_hvcc(pb, track->vos_data, track->vos_len, 1);
1132 ff_isom_write_hvcc(pb, track->vos_data, track->vos_len, 0);
1133 return update_size(pb, pos);
1136 /* also used by all avid codecs (dv, imx, meridien) and their variants */
1137 static int mov_write_avid_tag(AVIOContext *pb, MOVTrack *track)
1142 int display_width = track->par->width;
1144 if (track->vos_data && track->vos_len > 0x29) {
1145 if (ff_dnxhd_parse_header_prefix(track->vos_data) != 0) {
1146 /* looks like a DNxHD bit stream */
1147 interlaced = (track->vos_data[5] & 2);
1148 cid = AV_RB32(track->vos_data + 0x28);
1150 av_log(NULL, AV_LOG_WARNING, "Could not locate DNxHD bit stream in vos_data\n");
1154 av_log(NULL, AV_LOG_WARNING, "Could not locate DNxHD bit stream, vos_data too small\n");
1158 avio_wb32(pb, 24); /* size */
1159 ffio_wfourcc(pb, "ACLR");
1160 ffio_wfourcc(pb, "ACLR");
1161 ffio_wfourcc(pb, "0001");
1162 if (track->par->color_range == AVCOL_RANGE_MPEG || /* Legal range (16-235) */
1163 track->par->color_range == AVCOL_RANGE_UNSPECIFIED) {
1164 avio_wb32(pb, 1); /* Corresponds to 709 in official encoder */
1165 } else { /* Full range (0-255) */
1166 avio_wb32(pb, 2); /* Corresponds to RGB in official encoder */
1168 avio_wb32(pb, 0); /* unknown */
1170 if (track->tag == MKTAG('A','V','d','h')) {
1172 ffio_wfourcc(pb, "ADHR");
1173 ffio_wfourcc(pb, "0001");
1175 avio_wb32(pb, 0); /* unknown */
1176 avio_wb32(pb, 1); /* unknown */
1177 avio_wb32(pb, 0); /* unknown */
1178 avio_wb32(pb, 0); /* unknown */
1182 avio_wb32(pb, 24); /* size */
1183 ffio_wfourcc(pb, "APRG");
1184 ffio_wfourcc(pb, "APRG");
1185 ffio_wfourcc(pb, "0001");
1186 avio_wb32(pb, 1); /* unknown */
1187 avio_wb32(pb, 0); /* unknown */
1189 avio_wb32(pb, 120); /* size */
1190 ffio_wfourcc(pb, "ARES");
1191 ffio_wfourcc(pb, "ARES");
1192 ffio_wfourcc(pb, "0001");
1193 avio_wb32(pb, cid); /* dnxhd cid, some id ? */
1194 if ( track->par->sample_aspect_ratio.num > 0
1195 && track->par->sample_aspect_ratio.den > 0)
1196 display_width = display_width * track->par->sample_aspect_ratio.num / track->par->sample_aspect_ratio.den;
1197 avio_wb32(pb, display_width);
1198 /* values below are based on samples created with quicktime and avid codecs */
1200 avio_wb32(pb, track->par->height / 2);
1201 avio_wb32(pb, 2); /* unknown */
1202 avio_wb32(pb, 0); /* unknown */
1203 avio_wb32(pb, 4); /* unknown */
1205 avio_wb32(pb, track->par->height);
1206 avio_wb32(pb, 1); /* unknown */
1207 avio_wb32(pb, 0); /* unknown */
1208 if (track->par->height == 1080)
1209 avio_wb32(pb, 5); /* unknown */
1211 avio_wb32(pb, 6); /* unknown */
1214 for (i = 0; i < 10; i++)
1220 static int mov_write_dpxe_tag(AVIOContext *pb, MOVTrack *track)
1223 ffio_wfourcc(pb, "DpxE");
1224 if (track->par->extradata_size >= 12 &&
1225 !memcmp(&track->par->extradata[4], "DpxE", 4)) {
1226 avio_wb32(pb, track->par->extradata[11]);
1233 static int mov_get_dv_codec_tag(AVFormatContext *s, MOVTrack *track)
1237 if (track->par->width == 720) { /* SD */
1238 if (track->par->height == 480) { /* NTSC */
1239 if (track->par->format == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','n');
1240 else tag = MKTAG('d','v','c',' ');
1241 }else if (track->par->format == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','p');
1242 else if (track->par->format == AV_PIX_FMT_YUV420P) tag = MKTAG('d','v','c','p');
1243 else tag = MKTAG('d','v','p','p');
1244 } else if (track->par->height == 720) { /* HD 720 line */
1245 if (track->st->time_base.den == 50) tag = MKTAG('d','v','h','q');
1246 else tag = MKTAG('d','v','h','p');
1247 } else if (track->par->height == 1080) { /* HD 1080 line */
1248 if (track->st->time_base.den == 25) tag = MKTAG('d','v','h','5');
1249 else tag = MKTAG('d','v','h','6');
1251 av_log(s, AV_LOG_ERROR, "unsupported height for dv codec\n");
1258 static AVRational find_fps(AVFormatContext *s, AVStream *st)
1260 AVRational rate = st->avg_frame_rate;
1262 #if FF_API_LAVF_AVCTX
1263 FF_DISABLE_DEPRECATION_WARNINGS
1264 rate = av_inv_q(st->codec->time_base);
1265 if (av_timecode_check_frame_rate(rate) < 0) {
1266 av_log(s, AV_LOG_DEBUG, "timecode: tbc=%d/%d invalid, fallback on %d/%d\n",
1267 rate.num, rate.den, st->avg_frame_rate.num, st->avg_frame_rate.den);
1268 rate = st->avg_frame_rate;
1270 FF_ENABLE_DEPRECATION_WARNINGS
1276 static int defined_frame_rate(AVFormatContext *s, AVStream *st)
1278 AVRational rational_framerate = find_fps(s, st);
1280 if (rational_framerate.den != 0)
1281 rate = av_q2d(rational_framerate);
1285 static int mov_get_mpeg2_xdcam_codec_tag(AVFormatContext *s, MOVTrack *track)
1287 int tag = track->par->codec_tag;
1288 int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE;
1289 AVStream *st = track->st;
1290 int rate = defined_frame_rate(s, st);
1293 tag = MKTAG('m', '2', 'v', '1'); //fallback tag
1295 if (track->par->format == AV_PIX_FMT_YUV420P) {
1296 if (track->par->width == 1280 && track->par->height == 720) {
1298 if (rate == 24) tag = MKTAG('x','d','v','4');
1299 else if (rate == 25) tag = MKTAG('x','d','v','5');
1300 else if (rate == 30) tag = MKTAG('x','d','v','1');
1301 else if (rate == 50) tag = MKTAG('x','d','v','a');
1302 else if (rate == 60) tag = MKTAG('x','d','v','9');
1304 } else if (track->par->width == 1440 && track->par->height == 1080) {
1306 if (rate == 24) tag = MKTAG('x','d','v','6');
1307 else if (rate == 25) tag = MKTAG('x','d','v','7');
1308 else if (rate == 30) tag = MKTAG('x','d','v','8');
1310 if (rate == 25) tag = MKTAG('x','d','v','3');
1311 else if (rate == 30) tag = MKTAG('x','d','v','2');
1313 } else if (track->par->width == 1920 && track->par->height == 1080) {
1315 if (rate == 24) tag = MKTAG('x','d','v','d');
1316 else if (rate == 25) tag = MKTAG('x','d','v','e');
1317 else if (rate == 30) tag = MKTAG('x','d','v','f');
1319 if (rate == 25) tag = MKTAG('x','d','v','c');
1320 else if (rate == 30) tag = MKTAG('x','d','v','b');
1323 } else if (track->par->format == AV_PIX_FMT_YUV422P) {
1324 if (track->par->width == 1280 && track->par->height == 720) {
1326 if (rate == 24) tag = MKTAG('x','d','5','4');
1327 else if (rate == 25) tag = MKTAG('x','d','5','5');
1328 else if (rate == 30) tag = MKTAG('x','d','5','1');
1329 else if (rate == 50) tag = MKTAG('x','d','5','a');
1330 else if (rate == 60) tag = MKTAG('x','d','5','9');
1332 } else if (track->par->width == 1920 && track->par->height == 1080) {
1334 if (rate == 24) tag = MKTAG('x','d','5','d');
1335 else if (rate == 25) tag = MKTAG('x','d','5','e');
1336 else if (rate == 30) tag = MKTAG('x','d','5','f');
1338 if (rate == 25) tag = MKTAG('x','d','5','c');
1339 else if (rate == 30) tag = MKTAG('x','d','5','b');
1347 static int mov_get_h264_codec_tag(AVFormatContext *s, MOVTrack *track)
1349 int tag = track->par->codec_tag;
1350 int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE;
1351 AVStream *st = track->st;
1352 int rate = defined_frame_rate(s, st);
1355 tag = MKTAG('a', 'v', 'c', 'i'); //fallback tag
1357 if (track->par->format == AV_PIX_FMT_YUV420P10) {
1358 if (track->par->width == 960 && track->par->height == 720) {
1360 if (rate == 24) tag = MKTAG('a','i','5','p');
1361 else if (rate == 25) tag = MKTAG('a','i','5','q');
1362 else if (rate == 30) tag = MKTAG('a','i','5','p');
1363 else if (rate == 50) tag = MKTAG('a','i','5','q');
1364 else if (rate == 60) tag = MKTAG('a','i','5','p');
1366 } else if (track->par->width == 1440 && track->par->height == 1080) {
1368 if (rate == 24) tag = MKTAG('a','i','5','3');
1369 else if (rate == 25) tag = MKTAG('a','i','5','2');
1370 else if (rate == 30) tag = MKTAG('a','i','5','3');
1372 if (rate == 50) tag = MKTAG('a','i','5','5');
1373 else if (rate == 60) tag = MKTAG('a','i','5','6');
1376 } else if (track->par->format == AV_PIX_FMT_YUV422P10) {
1377 if (track->par->width == 1280 && track->par->height == 720) {
1379 if (rate == 24) tag = MKTAG('a','i','1','p');
1380 else if (rate == 25) tag = MKTAG('a','i','1','q');
1381 else if (rate == 30) tag = MKTAG('a','i','1','p');
1382 else if (rate == 50) tag = MKTAG('a','i','1','q');
1383 else if (rate == 60) tag = MKTAG('a','i','1','p');
1385 } else if (track->par->width == 1920 && track->par->height == 1080) {
1387 if (rate == 24) tag = MKTAG('a','i','1','3');
1388 else if (rate == 25) tag = MKTAG('a','i','1','2');
1389 else if (rate == 30) tag = MKTAG('a','i','1','3');
1391 if (rate == 25) tag = MKTAG('a','i','1','5');
1392 else if (rate == 50) tag = MKTAG('a','i','1','5');
1393 else if (rate == 60) tag = MKTAG('a','i','1','6');
1395 } else if ( track->par->width == 4096 && track->par->height == 2160
1396 || track->par->width == 3840 && track->par->height == 2160
1397 || track->par->width == 2048 && track->par->height == 1080) {
1398 tag = MKTAG('a','i','v','x');
1405 static const struct {
1406 enum AVPixelFormat pix_fmt;
1409 } mov_pix_fmt_tags[] = {
1410 { AV_PIX_FMT_YUYV422, MKTAG('y','u','v','2'), 0 },
1411 { AV_PIX_FMT_YUYV422, MKTAG('y','u','v','s'), 0 },
1412 { AV_PIX_FMT_UYVY422, MKTAG('2','v','u','y'), 0 },
1413 { AV_PIX_FMT_RGB555BE,MKTAG('r','a','w',' '), 16 },
1414 { AV_PIX_FMT_RGB555LE,MKTAG('L','5','5','5'), 16 },
1415 { AV_PIX_FMT_RGB565LE,MKTAG('L','5','6','5'), 16 },
1416 { AV_PIX_FMT_RGB565BE,MKTAG('B','5','6','5'), 16 },
1417 { AV_PIX_FMT_GRAY16BE,MKTAG('b','1','6','g'), 16 },
1418 { AV_PIX_FMT_RGB24, MKTAG('r','a','w',' '), 24 },
1419 { AV_PIX_FMT_BGR24, MKTAG('2','4','B','G'), 24 },
1420 { AV_PIX_FMT_ARGB, MKTAG('r','a','w',' '), 32 },
1421 { AV_PIX_FMT_BGRA, MKTAG('B','G','R','A'), 32 },
1422 { AV_PIX_FMT_RGBA, MKTAG('R','G','B','A'), 32 },
1423 { AV_PIX_FMT_ABGR, MKTAG('A','B','G','R'), 32 },
1424 { AV_PIX_FMT_RGB48BE, MKTAG('b','4','8','r'), 48 },
1427 static int mov_get_dnxhd_codec_tag(AVFormatContext *s, MOVTrack *track)
1429 int tag = MKTAG('A','V','d','n');
1430 if (track->par->profile != FF_PROFILE_UNKNOWN &&
1431 track->par->profile != FF_PROFILE_DNXHD)
1432 tag = MKTAG('A','V','d','h');
1436 static int mov_get_rawvideo_codec_tag(AVFormatContext *s, MOVTrack *track)
1438 int tag = track->par->codec_tag;
1440 enum AVPixelFormat pix_fmt;
1442 for (i = 0; i < FF_ARRAY_ELEMS(mov_pix_fmt_tags); i++) {
1443 if (track->par->format == mov_pix_fmt_tags[i].pix_fmt) {
1444 tag = mov_pix_fmt_tags[i].tag;
1445 track->par->bits_per_coded_sample = mov_pix_fmt_tags[i].bps;
1446 if (track->par->codec_tag == mov_pix_fmt_tags[i].tag)
1451 pix_fmt = avpriv_find_pix_fmt(avpriv_pix_fmt_bps_mov,
1452 track->par->bits_per_coded_sample);
1453 if (tag == MKTAG('r','a','w',' ') &&
1454 track->par->format != pix_fmt &&
1455 track->par->format != AV_PIX_FMT_GRAY8 &&
1456 track->par->format != AV_PIX_FMT_NONE)
1457 av_log(s, AV_LOG_ERROR, "%s rawvideo cannot be written to mov, output file will be unreadable\n",
1458 av_get_pix_fmt_name(track->par->format));
1462 static int mov_get_codec_tag(AVFormatContext *s, MOVTrack *track)
1464 int tag = track->par->codec_tag;
1466 if (!tag || (s->strict_std_compliance >= FF_COMPLIANCE_NORMAL &&
1467 (track->par->codec_id == AV_CODEC_ID_DVVIDEO ||
1468 track->par->codec_id == AV_CODEC_ID_RAWVIDEO ||
1469 track->par->codec_id == AV_CODEC_ID_H263 ||
1470 track->par->codec_id == AV_CODEC_ID_H264 ||
1471 track->par->codec_id == AV_CODEC_ID_DNXHD ||
1472 track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO ||
1473 av_get_bits_per_sample(track->par->codec_id)))) { // pcm audio
1474 if (track->par->codec_id == AV_CODEC_ID_DVVIDEO)
1475 tag = mov_get_dv_codec_tag(s, track);
1476 else if (track->par->codec_id == AV_CODEC_ID_RAWVIDEO)
1477 tag = mov_get_rawvideo_codec_tag(s, track);
1478 else if (track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO)
1479 tag = mov_get_mpeg2_xdcam_codec_tag(s, track);
1480 else if (track->par->codec_id == AV_CODEC_ID_H264)
1481 tag = mov_get_h264_codec_tag(s, track);
1482 else if (track->par->codec_id == AV_CODEC_ID_DNXHD)
1483 tag = mov_get_dnxhd_codec_tag(s, track);
1484 else if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
1485 tag = ff_codec_get_tag(ff_codec_movvideo_tags, track->par->codec_id);
1486 if (!tag) { // if no mac fcc found, try with Microsoft tags
1487 tag = ff_codec_get_tag(ff_codec_bmp_tags, track->par->codec_id);
1489 av_log(s, AV_LOG_WARNING, "Using MS style video codec tag, "
1490 "the file may be unplayable!\n");
1492 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
1493 tag = ff_codec_get_tag(ff_codec_movaudio_tags, track->par->codec_id);
1494 if (!tag) { // if no mac fcc found, try with Microsoft tags
1495 int ms_tag = ff_codec_get_tag(ff_codec_wav_tags, track->par->codec_id);
1497 tag = MKTAG('m', 's', ((ms_tag >> 8) & 0xff), (ms_tag & 0xff));
1498 av_log(s, AV_LOG_WARNING, "Using MS style audio codec tag, "
1499 "the file may be unplayable!\n");
1502 } else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)
1503 tag = ff_codec_get_tag(ff_codec_movsubtitle_tags, track->par->codec_id);
1509 static int mov_find_codec_tag(AVFormatContext *s, MOVTrack *track)
1513 if (track->mode == MODE_MP4 || track->mode == MODE_PSP)
1514 tag = track->par->codec_tag;
1515 else if (track->mode == MODE_ISM)
1516 tag = track->par->codec_tag;
1517 else if (track->mode == MODE_IPOD) {
1518 if (!av_match_ext(s->filename, "m4a") &&
1519 !av_match_ext(s->filename, "m4v") &&
1520 !av_match_ext(s->filename, "m4b"))
1521 av_log(s, AV_LOG_WARNING, "Warning, extension is not .m4a nor .m4v "
1522 "Quicktime/Ipod might not play the file\n");
1523 tag = track->par->codec_tag;
1524 } else if (track->mode & MODE_3GP)
1525 tag = track->par->codec_tag;
1526 else if (track->mode == MODE_F4V)
1527 tag = track->par->codec_tag;
1529 tag = mov_get_codec_tag(s, track);
1534 /** Write uuid atom.
1535 * Needed to make file play in iPods running newest firmware
1536 * goes after avcC atom in moov.trak.mdia.minf.stbl.stsd.avc1
1538 static int mov_write_uuid_tag_ipod(AVIOContext *pb)
1541 ffio_wfourcc(pb, "uuid");
1542 avio_wb32(pb, 0x6b6840f2);
1543 avio_wb32(pb, 0x5f244fc5);
1544 avio_wb32(pb, 0xba39a51b);
1545 avio_wb32(pb, 0xcf0323f3);
1550 static const uint16_t fiel_data[] = {
1551 0x0000, 0x0100, 0x0201, 0x0206, 0x0209, 0x020e
1554 static int mov_write_fiel_tag(AVIOContext *pb, MOVTrack *track, int field_order)
1556 unsigned mov_field_order = 0;
1557 if (field_order < FF_ARRAY_ELEMS(fiel_data))
1558 mov_field_order = fiel_data[field_order];
1562 ffio_wfourcc(pb, "fiel");
1563 avio_wb16(pb, mov_field_order);
1567 static int mov_write_subtitle_tag(AVIOContext *pb, MOVTrack *track)
1569 int64_t pos = avio_tell(pb);
1570 avio_wb32(pb, 0); /* size */
1571 avio_wl32(pb, track->tag); // store it byteswapped
1572 avio_wb32(pb, 0); /* Reserved */
1573 avio_wb16(pb, 0); /* Reserved */
1574 avio_wb16(pb, 1); /* Data-reference index */
1576 if (track->par->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
1577 mov_write_esds_tag(pb, track);
1578 else if (track->par->extradata_size)
1579 avio_write(pb, track->par->extradata, track->par->extradata_size);
1581 return update_size(pb, pos);
1584 static int mov_write_st3d_tag(AVIOContext *pb, AVStereo3D *stereo_3d)
1588 if (stereo_3d->flags != 0) {
1589 av_log(pb, AV_LOG_WARNING, "Unsupported stereo_3d flags %x. st3d not written.\n", stereo_3d->flags);
1593 switch (stereo_3d->type) {
1594 case AV_STEREO3D_2D:
1597 case AV_STEREO3D_TOPBOTTOM:
1600 case AV_STEREO3D_SIDEBYSIDE:
1604 av_log(pb, AV_LOG_WARNING, "Unsupported stereo_3d type %s. st3d not written.\n", av_stereo3d_type_name(stereo_3d->type));
1607 avio_wb32(pb, 13); /* size */
1608 ffio_wfourcc(pb, "st3d");
1609 avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1610 avio_w8(pb, stereo_mode);
1614 static int mov_write_sv3d_tag(AVFormatContext *s, AVIOContext *pb, AVSphericalMapping *spherical_mapping)
1616 int64_t sv3d_pos, svhd_pos, proj_pos;
1617 const char* metadata_source = s->flags & AVFMT_FLAG_BITEXACT ? "Lavf" : LIBAVFORMAT_IDENT;
1619 if (spherical_mapping->projection != AV_SPHERICAL_EQUIRECTANGULAR &&
1620 spherical_mapping->projection != AV_SPHERICAL_EQUIRECTANGULAR_TILE &&
1621 spherical_mapping->projection != AV_SPHERICAL_CUBEMAP) {
1622 av_log(pb, AV_LOG_WARNING, "Unsupported projection %d. sv3d not written.\n", spherical_mapping->projection);
1626 sv3d_pos = avio_tell(pb);
1627 avio_wb32(pb, 0); /* size */
1628 ffio_wfourcc(pb, "sv3d");
1630 svhd_pos = avio_tell(pb);
1631 avio_wb32(pb, 0); /* size */
1632 ffio_wfourcc(pb, "svhd");
1633 avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1634 avio_put_str(pb, metadata_source);
1635 update_size(pb, svhd_pos);
1637 proj_pos = avio_tell(pb);
1638 avio_wb32(pb, 0); /* size */
1639 ffio_wfourcc(pb, "proj");
1641 avio_wb32(pb, 24); /* size */
1642 ffio_wfourcc(pb, "prhd");
1643 avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1644 avio_wb32(pb, spherical_mapping->yaw);
1645 avio_wb32(pb, spherical_mapping->pitch);
1646 avio_wb32(pb, spherical_mapping->roll);
1648 switch (spherical_mapping->projection) {
1649 case AV_SPHERICAL_EQUIRECTANGULAR:
1650 case AV_SPHERICAL_EQUIRECTANGULAR_TILE:
1651 avio_wb32(pb, 28); /* size */
1652 ffio_wfourcc(pb, "equi");
1653 avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1654 avio_wb32(pb, spherical_mapping->bound_top);
1655 avio_wb32(pb, spherical_mapping->bound_bottom);
1656 avio_wb32(pb, spherical_mapping->bound_left);
1657 avio_wb32(pb, spherical_mapping->bound_right);
1659 case AV_SPHERICAL_CUBEMAP:
1660 avio_wb32(pb, 20); /* size */
1661 ffio_wfourcc(pb, "cbmp");
1662 avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1663 avio_wb32(pb, 0); /* layout */
1664 avio_wb32(pb, spherical_mapping->padding); /* padding */
1667 update_size(pb, proj_pos);
1669 return update_size(pb, sv3d_pos);
1672 static int mov_write_pasp_tag(AVIOContext *pb, MOVTrack *track)
1675 av_reduce(&sar.num, &sar.den, track->par->sample_aspect_ratio.num,
1676 track->par->sample_aspect_ratio.den, INT_MAX);
1679 ffio_wfourcc(pb, "pasp");
1680 avio_wb32(pb, sar.num);
1681 avio_wb32(pb, sar.den);
1685 static int mov_write_gama_tag(AVIOContext *pb, MOVTrack *track, double gamma)
1690 gamma = avpriv_get_gamma_from_trc(track->par->color_trc);
1692 av_log(pb, AV_LOG_DEBUG, "gamma value %g\n", gamma);
1695 gama = (uint32_t)lrint((double)(1<<16) * gamma);
1696 av_log(pb, AV_LOG_DEBUG, "writing gama value %"PRId32"\n", gama);
1698 av_assert0(track->mode == MODE_MOV);
1700 ffio_wfourcc(pb, "gama");
1701 avio_wb32(pb, gama);
1705 av_log(pb, AV_LOG_WARNING, "gamma value unknown, unable to write gama atom\n");
1710 static int mov_write_colr_tag(AVIOContext *pb, MOVTrack *track)
1712 // Ref (MOV): https://developer.apple.com/library/mac/technotes/tn2162/_index.html#//apple_ref/doc/uid/DTS40013070-CH1-TNTAG9
1713 // Ref (MP4): ISO/IEC 14496-12:2012
1715 if (track->par->color_primaries == AVCOL_PRI_UNSPECIFIED &&
1716 track->par->color_trc == AVCOL_TRC_UNSPECIFIED &&
1717 track->par->color_space == AVCOL_SPC_UNSPECIFIED) {
1718 if ((track->par->width >= 1920 && track->par->height >= 1080)
1719 || (track->par->width == 1280 && track->par->height == 720)) {
1720 av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming bt709\n");
1721 track->par->color_primaries = AVCOL_PRI_BT709;
1722 } else if (track->par->width == 720 && track->height == 576) {
1723 av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming bt470bg\n");
1724 track->par->color_primaries = AVCOL_PRI_BT470BG;
1725 } else if (track->par->width == 720 &&
1726 (track->height == 486 || track->height == 480)) {
1727 av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming smpte170\n");
1728 track->par->color_primaries = AVCOL_PRI_SMPTE170M;
1730 av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, unable to assume anything\n");
1732 switch (track->par->color_primaries) {
1733 case AVCOL_PRI_BT709:
1734 track->par->color_trc = AVCOL_TRC_BT709;
1735 track->par->color_space = AVCOL_SPC_BT709;
1737 case AVCOL_PRI_SMPTE170M:
1738 case AVCOL_PRI_BT470BG:
1739 track->par->color_trc = AVCOL_TRC_BT709;
1740 track->par->color_space = AVCOL_SPC_SMPTE170M;
1745 /* We should only ever be called by MOV or MP4. */
1746 av_assert0(track->mode == MODE_MOV || track->mode == MODE_MP4);
1748 avio_wb32(pb, 18 + (track->mode == MODE_MP4));
1749 ffio_wfourcc(pb, "colr");
1750 if (track->mode == MODE_MP4)
1751 ffio_wfourcc(pb, "nclx");
1753 ffio_wfourcc(pb, "nclc");
1754 switch (track->par->color_primaries) {
1755 case AVCOL_PRI_BT709: avio_wb16(pb, 1); break;
1756 case AVCOL_PRI_SMPTE170M:
1757 case AVCOL_PRI_SMPTE240M: avio_wb16(pb, 6); break;
1758 case AVCOL_PRI_BT470BG: avio_wb16(pb, 5); break;
1759 default: avio_wb16(pb, 2);
1761 switch (track->par->color_trc) {
1762 case AVCOL_TRC_BT709: avio_wb16(pb, 1); break;
1763 case AVCOL_TRC_SMPTE170M: avio_wb16(pb, 1); break; // remapped
1764 case AVCOL_TRC_SMPTE240M: avio_wb16(pb, 7); break;
1765 default: avio_wb16(pb, 2);
1767 switch (track->par->color_space) {
1768 case AVCOL_SPC_BT709: avio_wb16(pb, 1); break;
1769 case AVCOL_SPC_BT470BG:
1770 case AVCOL_SPC_SMPTE170M: avio_wb16(pb, 6); break;
1771 case AVCOL_SPC_SMPTE240M: avio_wb16(pb, 7); break;
1772 default: avio_wb16(pb, 2);
1775 if (track->mode == MODE_MP4) {
1776 int full_range = track->par->color_range == AVCOL_RANGE_JPEG;
1777 avio_w8(pb, full_range << 7);
1784 static void find_compressor(char * compressor_name, int len, MOVTrack *track)
1786 AVDictionaryEntry *encoder;
1787 int xdcam_res = (track->par->width == 1280 && track->par->height == 720)
1788 || (track->par->width == 1440 && track->par->height == 1080)
1789 || (track->par->width == 1920 && track->par->height == 1080);
1791 if (track->mode == MODE_MOV &&
1792 (encoder = av_dict_get(track->st->metadata, "encoder", NULL, 0))) {
1793 av_strlcpy(compressor_name, encoder->value, 32);
1794 } else if (track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO && xdcam_res) {
1795 int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE;
1796 AVStream *st = track->st;
1797 int rate = defined_frame_rate(NULL, st);
1798 av_strlcatf(compressor_name, len, "XDCAM");
1799 if (track->par->format == AV_PIX_FMT_YUV422P) {
1800 av_strlcatf(compressor_name, len, " HD422");
1801 } else if(track->par->width == 1440) {
1802 av_strlcatf(compressor_name, len, " HD");
1804 av_strlcatf(compressor_name, len, " EX");
1806 av_strlcatf(compressor_name, len, " %d%c", track->par->height, interlaced ? 'i' : 'p');
1808 av_strlcatf(compressor_name, len, "%d", rate * (interlaced + 1));
1812 static int mov_write_video_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
1814 int64_t pos = avio_tell(pb);
1815 char compressor_name[32] = { 0 };
1818 avio_wb32(pb, 0); /* size */
1819 if (mov->encryption_scheme != MOV_ENC_NONE) {
1820 ffio_wfourcc(pb, "encv");
1822 avio_wl32(pb, track->tag); // store it byteswapped
1824 avio_wb32(pb, 0); /* Reserved */
1825 avio_wb16(pb, 0); /* Reserved */
1826 avio_wb16(pb, 1); /* Data-reference index */
1828 avio_wb16(pb, 0); /* Codec stream version */
1829 avio_wb16(pb, 0); /* Codec stream revision (=0) */
1830 if (track->mode == MODE_MOV) {
1831 ffio_wfourcc(pb, "FFMP"); /* Vendor */
1832 if (track->par->codec_id == AV_CODEC_ID_RAWVIDEO) {
1833 avio_wb32(pb, 0); /* Temporal Quality */
1834 avio_wb32(pb, 0x400); /* Spatial Quality = lossless*/
1836 avio_wb32(pb, 0x200); /* Temporal Quality = normal */
1837 avio_wb32(pb, 0x200); /* Spatial Quality = normal */
1840 avio_wb32(pb, 0); /* Reserved */
1841 avio_wb32(pb, 0); /* Reserved */
1842 avio_wb32(pb, 0); /* Reserved */
1844 avio_wb16(pb, track->par->width); /* Video width */
1845 avio_wb16(pb, track->height); /* Video height */
1846 avio_wb32(pb, 0x00480000); /* Horizontal resolution 72dpi */
1847 avio_wb32(pb, 0x00480000); /* Vertical resolution 72dpi */
1848 avio_wb32(pb, 0); /* Data size (= 0) */
1849 avio_wb16(pb, 1); /* Frame count (= 1) */
1851 /* FIXME not sure, ISO 14496-1 draft where it shall be set to 0 */
1852 find_compressor(compressor_name, 32, track);
1853 avio_w8(pb, strlen(compressor_name));
1854 avio_write(pb, compressor_name, 31);
1856 if (track->mode == MODE_MOV && track->par->bits_per_coded_sample)
1857 avio_wb16(pb, track->par->bits_per_coded_sample |
1858 (track->par->format == AV_PIX_FMT_GRAY8 ? 0x20 : 0));
1860 avio_wb16(pb, 0x18); /* Reserved */
1862 if (track->mode == MODE_MOV && track->par->format == AV_PIX_FMT_PAL8) {
1863 int pal_size = 1 << track->par->bits_per_coded_sample;
1865 avio_wb16(pb, 0); /* Color table ID */
1866 avio_wb32(pb, 0); /* Color table seed */
1867 avio_wb16(pb, 0x8000); /* Color table flags */
1868 avio_wb16(pb, pal_size - 1); /* Color table size (zero-relative) */
1869 for (i = 0; i < pal_size; i++) {
1870 uint32_t rgb = track->palette[i];
1871 uint16_t r = (rgb >> 16) & 0xff;
1872 uint16_t g = (rgb >> 8) & 0xff;
1873 uint16_t b = rgb & 0xff;
1875 avio_wb16(pb, (r << 8) | r);
1876 avio_wb16(pb, (g << 8) | g);
1877 avio_wb16(pb, (b << 8) | b);
1880 avio_wb16(pb, 0xffff); /* Reserved */
1882 if (track->tag == MKTAG('m','p','4','v'))
1883 mov_write_esds_tag(pb, track);
1884 else if (track->par->codec_id == AV_CODEC_ID_H263)
1885 mov_write_d263_tag(pb);
1886 else if (track->par->codec_id == AV_CODEC_ID_AVUI ||
1887 track->par->codec_id == AV_CODEC_ID_SVQ3) {
1888 mov_write_extradata_tag(pb, track);
1890 } else if (track->par->codec_id == AV_CODEC_ID_DNXHD) {
1891 mov_write_avid_tag(pb, track);
1893 } else if (track->par->codec_id == AV_CODEC_ID_HEVC)
1894 mov_write_hvcc_tag(pb, track);
1895 else if (track->par->codec_id == AV_CODEC_ID_H264 && !TAG_IS_AVCI(track->tag)) {
1896 mov_write_avcc_tag(pb, track);
1897 if (track->mode == MODE_IPOD)
1898 mov_write_uuid_tag_ipod(pb);
1899 } else if (track->par->codec_id == AV_CODEC_ID_VP9) {
1900 mov_write_vpcc_tag(mov->fc, pb, track);
1901 } else if (track->par->codec_id == AV_CODEC_ID_VC1 && track->vos_len > 0)
1902 mov_write_dvc1_tag(pb, track);
1903 else if (track->par->codec_id == AV_CODEC_ID_VP6F ||
1904 track->par->codec_id == AV_CODEC_ID_VP6A) {
1905 /* Don't write any potential extradata here - the cropping
1906 * is signalled via the normal width/height fields. */
1907 } else if (track->par->codec_id == AV_CODEC_ID_R10K) {
1908 if (track->par->codec_tag == MKTAG('R','1','0','k'))
1909 mov_write_dpxe_tag(pb, track);
1910 } else if (track->vos_len > 0)
1911 mov_write_glbl_tag(pb, track);
1913 if (track->par->codec_id != AV_CODEC_ID_H264 &&
1914 track->par->codec_id != AV_CODEC_ID_MPEG4 &&
1915 track->par->codec_id != AV_CODEC_ID_DNXHD) {
1916 int field_order = track->par->field_order;
1918 #if FF_API_LAVF_AVCTX
1919 FF_DISABLE_DEPRECATION_WARNINGS
1920 if (field_order != track->st->codec->field_order && track->st->codec->field_order != AV_FIELD_UNKNOWN)
1921 field_order = track->st->codec->field_order;
1922 FF_ENABLE_DEPRECATION_WARNINGS
1925 if (field_order != AV_FIELD_UNKNOWN)
1926 mov_write_fiel_tag(pb, track, field_order);
1929 if (mov->flags & FF_MOV_FLAG_WRITE_GAMA) {
1930 if (track->mode == MODE_MOV)
1931 mov_write_gama_tag(pb, track, mov->gamma);
1933 av_log(mov->fc, AV_LOG_WARNING, "Not writing 'gama' atom. Format is not MOV.\n");
1935 if (mov->flags & FF_MOV_FLAG_WRITE_COLR) {
1936 if (track->mode == MODE_MOV || track->mode == MODE_MP4)
1937 mov_write_colr_tag(pb, track);
1939 av_log(mov->fc, AV_LOG_WARNING, "Not writing 'colr' atom. Format is not MOV or MP4.\n");
1942 if (track->mode == MODE_MP4 && mov->fc->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL) {
1943 AVStereo3D* stereo_3d = (AVStereo3D*) av_stream_get_side_data(track->st, AV_PKT_DATA_STEREO3D, NULL);
1944 AVSphericalMapping* spherical_mapping = (AVSphericalMapping*)av_stream_get_side_data(track->st, AV_PKT_DATA_SPHERICAL, NULL);
1947 mov_write_st3d_tag(pb, stereo_3d);
1948 if (spherical_mapping)
1949 mov_write_sv3d_tag(mov->fc, pb, spherical_mapping);
1952 if (track->par->sample_aspect_ratio.den && track->par->sample_aspect_ratio.num) {
1953 mov_write_pasp_tag(pb, track);
1956 if (mov->encryption_scheme != MOV_ENC_NONE) {
1957 ff_mov_cenc_write_sinf_tag(track, pb, mov->encryption_kid);
1960 /* extra padding for avid stsd */
1961 /* https://developer.apple.com/library/mac/documentation/QuickTime/QTFF/QTFFChap2/qtff2.html#//apple_ref/doc/uid/TP40000939-CH204-61112 */
1965 return update_size(pb, pos);
1968 static int mov_write_rtp_tag(AVIOContext *pb, MOVTrack *track)
1970 int64_t pos = avio_tell(pb);
1971 avio_wb32(pb, 0); /* size */
1972 ffio_wfourcc(pb, "rtp ");
1973 avio_wb32(pb, 0); /* Reserved */
1974 avio_wb16(pb, 0); /* Reserved */
1975 avio_wb16(pb, 1); /* Data-reference index */
1977 avio_wb16(pb, 1); /* Hint track version */
1978 avio_wb16(pb, 1); /* Highest compatible version */
1979 avio_wb32(pb, track->max_packet_size); /* Max packet size */
1981 avio_wb32(pb, 12); /* size */
1982 ffio_wfourcc(pb, "tims");
1983 avio_wb32(pb, track->timescale);
1985 return update_size(pb, pos);
1988 static int mov_write_source_reference_tag(AVIOContext *pb, MOVTrack *track, const char *reel_name)
1990 uint64_t str_size =strlen(reel_name);
1991 int64_t pos = avio_tell(pb);
1993 if (str_size >= UINT16_MAX){
1994 av_log(NULL, AV_LOG_ERROR, "reel_name length %"PRIu64" is too large\n", str_size);
1996 return AVERROR(EINVAL);
1999 avio_wb32(pb, 0); /* size */
2000 ffio_wfourcc(pb, "name"); /* Data format */
2001 avio_wb16(pb, str_size); /* string size */
2002 avio_wb16(pb, track->language); /* langcode */
2003 avio_write(pb, reel_name, str_size); /* reel name */
2004 return update_size(pb,pos);
2007 static int mov_write_tmcd_tag(AVIOContext *pb, MOVTrack *track)
2009 int64_t pos = avio_tell(pb);
2013 AVDictionaryEntry *t = NULL;
2015 if (!track->st->avg_frame_rate.num || !track->st->avg_frame_rate.den) {
2016 #if FF_API_LAVF_AVCTX
2017 FF_DISABLE_DEPRECATION_WARNINGS
2018 frame_duration = av_rescale(track->timescale, track->st->codec->time_base.num, track->st->codec->time_base.den);
2019 nb_frames = ROUNDED_DIV(track->st->codec->time_base.den, track->st->codec->time_base.num);
2020 FF_ENABLE_DEPRECATION_WARNINGS
2022 av_log(NULL, AV_LOG_ERROR, "avg_frame_rate not set for tmcd track.\n");
2023 return AVERROR(EINVAL);
2026 frame_duration = av_rescale(track->timescale, track->st->avg_frame_rate.num, track->st->avg_frame_rate.den);
2027 nb_frames = ROUNDED_DIV(track->st->avg_frame_rate.den, track->st->avg_frame_rate.num);
2030 if (nb_frames > 255) {
2031 av_log(NULL, AV_LOG_ERROR, "fps %d is too large\n", nb_frames);
2032 return AVERROR(EINVAL);
2035 avio_wb32(pb, 0); /* size */
2036 ffio_wfourcc(pb, "tmcd"); /* Data format */
2037 avio_wb32(pb, 0); /* Reserved */
2038 avio_wb32(pb, 1); /* Data reference index */
2039 avio_wb32(pb, 0); /* Flags */
2040 avio_wb32(pb, track->timecode_flags); /* Flags (timecode) */
2041 avio_wb32(pb, track->timescale); /* Timescale */
2042 avio_wb32(pb, frame_duration); /* Frame duration */
2043 avio_w8(pb, nb_frames); /* Number of frames */
2044 avio_w8(pb, 0); /* Reserved */
2046 t = av_dict_get(track->st->metadata, "reel_name", NULL, 0);
2047 if (t && utf8len(t->value) && track->mode != MODE_MP4)
2048 mov_write_source_reference_tag(pb, track, t->value);
2050 avio_wb16(pb, 0); /* zero size */
2053 avio_wb32(pb, 0); /* size */
2054 ffio_wfourcc(pb, "tmcd"); /* Data format */
2055 avio_wb32(pb, 0); /* Reserved */
2056 avio_wb32(pb, 1); /* Data reference index */
2057 if (track->par->extradata_size)
2058 avio_write(pb, track->par->extradata, track->par->extradata_size);
2060 return update_size(pb, pos);
2063 static int mov_write_stsd_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
2065 int64_t pos = avio_tell(pb);
2066 avio_wb32(pb, 0); /* size */
2067 ffio_wfourcc(pb, "stsd");
2068 avio_wb32(pb, 0); /* version & flags */
2069 avio_wb32(pb, 1); /* entry count */
2070 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO)
2071 mov_write_video_tag(pb, mov, track);
2072 else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
2073 mov_write_audio_tag(s, pb, mov, track);
2074 else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)
2075 mov_write_subtitle_tag(pb, track);
2076 else if (track->par->codec_tag == MKTAG('r','t','p',' '))
2077 mov_write_rtp_tag(pb, track);
2078 else if (track->par->codec_tag == MKTAG('t','m','c','d'))
2079 mov_write_tmcd_tag(pb, track);
2080 return update_size(pb, pos);
2083 static int mov_write_ctts_tag(AVIOContext *pb, MOVTrack *track)
2085 MOVStts *ctts_entries;
2086 uint32_t entries = 0;
2090 ctts_entries = av_malloc_array((track->entry + 1), sizeof(*ctts_entries)); /* worst case */
2092 return AVERROR(ENOMEM);
2093 ctts_entries[0].count = 1;
2094 ctts_entries[0].duration = track->cluster[0].cts;
2095 for (i = 1; i < track->entry; i++) {
2096 if (track->cluster[i].cts == ctts_entries[entries].duration) {
2097 ctts_entries[entries].count++; /* compress */
2100 ctts_entries[entries].duration = track->cluster[i].cts;
2101 ctts_entries[entries].count = 1;
2104 entries++; /* last one */
2105 atom_size = 16 + (entries * 8);
2106 avio_wb32(pb, atom_size); /* size */
2107 ffio_wfourcc(pb, "ctts");
2108 avio_wb32(pb, 0); /* version & flags */
2109 avio_wb32(pb, entries); /* entry count */
2110 for (i = 0; i < entries; i++) {
2111 avio_wb32(pb, ctts_entries[i].count);
2112 avio_wb32(pb, ctts_entries[i].duration);
2114 av_free(ctts_entries);
2118 /* Time to sample atom */
2119 static int mov_write_stts_tag(AVIOContext *pb, MOVTrack *track)
2121 MOVStts *stts_entries = NULL;
2122 uint32_t entries = -1;
2126 if (track->par->codec_type == AVMEDIA_TYPE_AUDIO && !track->audio_vbr) {
2127 stts_entries = av_malloc(sizeof(*stts_entries)); /* one entry */
2129 return AVERROR(ENOMEM);
2130 stts_entries[0].count = track->sample_count;
2131 stts_entries[0].duration = 1;
2135 stts_entries = av_malloc_array(track->entry, sizeof(*stts_entries)); /* worst case */
2137 return AVERROR(ENOMEM);
2139 for (i = 0; i < track->entry; i++) {
2140 int duration = get_cluster_duration(track, i);
2141 if (i && duration == stts_entries[entries].duration) {
2142 stts_entries[entries].count++; /* compress */
2145 stts_entries[entries].duration = duration;
2146 stts_entries[entries].count = 1;
2149 entries++; /* last one */
2151 atom_size = 16 + (entries * 8);
2152 avio_wb32(pb, atom_size); /* size */
2153 ffio_wfourcc(pb, "stts");
2154 avio_wb32(pb, 0); /* version & flags */
2155 avio_wb32(pb, entries); /* entry count */
2156 for (i = 0; i < entries; i++) {
2157 avio_wb32(pb, stts_entries[i].count);
2158 avio_wb32(pb, stts_entries[i].duration);
2160 av_free(stts_entries);
2164 static int mov_write_dref_tag(AVIOContext *pb)
2166 avio_wb32(pb, 28); /* size */
2167 ffio_wfourcc(pb, "dref");
2168 avio_wb32(pb, 0); /* version & flags */
2169 avio_wb32(pb, 1); /* entry count */
2171 avio_wb32(pb, 0xc); /* size */
2172 //FIXME add the alis and rsrc atom
2173 ffio_wfourcc(pb, "url ");
2174 avio_wb32(pb, 1); /* version & flags */
2179 static int mov_preroll_write_stbl_atoms(AVIOContext *pb, MOVTrack *track)
2183 int16_t roll_distance;
2184 int group_description_index;
2187 struct sgpd_entry *sgpd_entries = NULL;
2192 const int OPUS_SEEK_PREROLL_MS = 80;
2193 int roll_samples = av_rescale_q(OPUS_SEEK_PREROLL_MS,
2194 (AVRational){1, 1000},
2195 (AVRational){1, 48000});
2198 sgpd_entries = av_malloc_array(track->entry, sizeof(*sgpd_entries));
2200 return AVERROR(ENOMEM);
2203 av_assert0(track->par->codec_id == AV_CODEC_ID_OPUS);
2205 for (i = 0; i < track->entry; i++) {
2206 int roll_samples_remaining = roll_samples;
2208 for (j = i - 1; j >= 0; j--) {
2209 roll_samples_remaining -= get_cluster_duration(track, j);
2211 if (roll_samples_remaining <= 0)
2214 /* We don't have enough preceeding samples to compute a valid
2215 roll_distance here, so this sample can't be independently
2217 if (roll_samples_remaining > 0)
2219 /* Verify distance is a minimum of 2 (60ms) packets and a maximum of
2220 32 (2.5ms) packets. */
2221 av_assert0(distance == 0 || (distance >= 2 && distance <= 32));
2222 if (i && distance == sgpd_entries[entries].roll_distance) {
2223 sgpd_entries[entries].count++;
2226 sgpd_entries[entries].count = 1;
2227 sgpd_entries[entries].roll_distance = distance;
2228 sgpd_entries[entries].group_description_index = distance ? ++group : 0;
2234 av_free(sgpd_entries);
2238 /* Write sgpd tag */
2239 avio_wb32(pb, 24 + (group * 2)); /* size */
2240 ffio_wfourcc(pb, "sgpd");
2241 avio_wb32(pb, 1 << 24); /* fullbox */
2242 ffio_wfourcc(pb, "roll");
2243 avio_wb32(pb, 2); /* default_length */
2244 avio_wb32(pb, group); /* entry_count */
2245 for (i = 0; i < entries; i++) {
2246 if (sgpd_entries[i].group_description_index) {
2247 avio_wb16(pb, -sgpd_entries[i].roll_distance); /* roll_distance */
2251 /* Write sbgp tag */
2252 avio_wb32(pb, 20 + (entries * 8)); /* size */
2253 ffio_wfourcc(pb, "sbgp");
2254 avio_wb32(pb, 0); /* fullbox */
2255 ffio_wfourcc(pb, "roll");
2256 avio_wb32(pb, entries); /* entry_count */
2257 for (i = 0; i < entries; i++) {
2258 avio_wb32(pb, sgpd_entries[i].count); /* sample_count */
2259 avio_wb32(pb, sgpd_entries[i].group_description_index); /* group_description_index */
2262 av_free(sgpd_entries);
2266 static int mov_write_stbl_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
2268 int64_t pos = avio_tell(pb);
2271 avio_wb32(pb, 0); /* size */
2272 ffio_wfourcc(pb, "stbl");
2273 mov_write_stsd_tag(s, pb, mov, track);
2274 mov_write_stts_tag(pb, track);
2275 if ((track->par->codec_type == AVMEDIA_TYPE_VIDEO ||
2276 track->par->codec_tag == MKTAG('r','t','p',' ')) &&
2277 track->has_keyframes && track->has_keyframes < track->entry)
2278 mov_write_stss_tag(pb, track, MOV_SYNC_SAMPLE);
2279 if (track->mode == MODE_MOV && track->flags & MOV_TRACK_STPS)
2280 mov_write_stss_tag(pb, track, MOV_PARTIAL_SYNC_SAMPLE);
2281 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO &&
2282 track->flags & MOV_TRACK_CTTS && track->entry) {
2284 if ((ret = mov_write_ctts_tag(pb, track)) < 0)
2287 mov_write_stsc_tag(pb, track);
2288 mov_write_stsz_tag(pb, track);
2289 mov_write_stco_tag(pb, track);
2290 if (track->cenc.aes_ctr) {
2291 ff_mov_cenc_write_stbl_atoms(&track->cenc, pb);
2293 if (track->par->codec_id == AV_CODEC_ID_OPUS) {
2294 mov_preroll_write_stbl_atoms(pb, track);
2296 return update_size(pb, pos);
2299 static int mov_write_dinf_tag(AVIOContext *pb)
2301 int64_t pos = avio_tell(pb);
2302 avio_wb32(pb, 0); /* size */
2303 ffio_wfourcc(pb, "dinf");
2304 mov_write_dref_tag(pb);
2305 return update_size(pb, pos);
2308 static int mov_write_nmhd_tag(AVIOContext *pb)
2311 ffio_wfourcc(pb, "nmhd");
2316 static int mov_write_tcmi_tag(AVIOContext *pb, MOVTrack *track)
2318 int64_t pos = avio_tell(pb);
2319 const char *font = "Lucida Grande";
2320 avio_wb32(pb, 0); /* size */
2321 ffio_wfourcc(pb, "tcmi"); /* timecode media information atom */
2322 avio_wb32(pb, 0); /* version & flags */
2323 avio_wb16(pb, 0); /* text font */
2324 avio_wb16(pb, 0); /* text face */
2325 avio_wb16(pb, 12); /* text size */
2326 avio_wb16(pb, 0); /* (unknown, not in the QT specs...) */
2327 avio_wb16(pb, 0x0000); /* text color (red) */
2328 avio_wb16(pb, 0x0000); /* text color (green) */
2329 avio_wb16(pb, 0x0000); /* text color (blue) */
2330 avio_wb16(pb, 0xffff); /* background color (red) */
2331 avio_wb16(pb, 0xffff); /* background color (green) */
2332 avio_wb16(pb, 0xffff); /* background color (blue) */
2333 avio_w8(pb, strlen(font)); /* font len (part of the pascal string) */
2334 avio_write(pb, font, strlen(font)); /* font name */
2335 return update_size(pb, pos);
2338 static int mov_write_gmhd_tag(AVIOContext *pb, MOVTrack *track)
2340 int64_t pos = avio_tell(pb);
2341 avio_wb32(pb, 0); /* size */
2342 ffio_wfourcc(pb, "gmhd");
2343 avio_wb32(pb, 0x18); /* gmin size */
2344 ffio_wfourcc(pb, "gmin");/* generic media info */
2345 avio_wb32(pb, 0); /* version & flags */
2346 avio_wb16(pb, 0x40); /* graphics mode = */
2347 avio_wb16(pb, 0x8000); /* opColor (r?) */
2348 avio_wb16(pb, 0x8000); /* opColor (g?) */
2349 avio_wb16(pb, 0x8000); /* opColor (b?) */
2350 avio_wb16(pb, 0); /* balance */
2351 avio_wb16(pb, 0); /* reserved */
2354 * This special text atom is required for
2355 * Apple Quicktime chapters. The contents
2356 * don't appear to be documented, so the
2357 * bytes are copied verbatim.
2359 if (track->tag != MKTAG('c','6','0','8')) {
2360 avio_wb32(pb, 0x2C); /* size */
2361 ffio_wfourcc(pb, "text");
2362 avio_wb16(pb, 0x01);
2363 avio_wb32(pb, 0x00);
2364 avio_wb32(pb, 0x00);
2365 avio_wb32(pb, 0x00);
2366 avio_wb32(pb, 0x01);
2367 avio_wb32(pb, 0x00);
2368 avio_wb32(pb, 0x00);
2369 avio_wb32(pb, 0x00);
2370 avio_wb32(pb, 0x00004000);
2371 avio_wb16(pb, 0x0000);
2374 if (track->par->codec_tag == MKTAG('t','m','c','d')) {
2375 int64_t tmcd_pos = avio_tell(pb);
2376 avio_wb32(pb, 0); /* size */
2377 ffio_wfourcc(pb, "tmcd");
2378 mov_write_tcmi_tag(pb, track);
2379 update_size(pb, tmcd_pos);
2381 return update_size(pb, pos);
2384 static int mov_write_smhd_tag(AVIOContext *pb)
2386 avio_wb32(pb, 16); /* size */
2387 ffio_wfourcc(pb, "smhd");
2388 avio_wb32(pb, 0); /* version & flags */
2389 avio_wb16(pb, 0); /* reserved (balance, normally = 0) */
2390 avio_wb16(pb, 0); /* reserved */
2394 static int mov_write_vmhd_tag(AVIOContext *pb)
2396 avio_wb32(pb, 0x14); /* size (always 0x14) */
2397 ffio_wfourcc(pb, "vmhd");
2398 avio_wb32(pb, 0x01); /* version & flags */
2399 avio_wb64(pb, 0); /* reserved (graphics mode = copy) */
2403 static int is_clcp_track(MOVTrack *track)
2405 return track->tag == MKTAG('c','7','0','8') ||
2406 track->tag == MKTAG('c','6','0','8');
2409 static int mov_write_hdlr_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
2411 const char *hdlr, *descr = NULL, *hdlr_type = NULL;
2412 int64_t pos = avio_tell(pb);
2416 descr = "DataHandler";
2419 hdlr = (track->mode == MODE_MOV) ? "mhlr" : "\0\0\0\0";
2420 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
2422 descr = "VideoHandler";
2423 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
2425 descr = "SoundHandler";
2426 } else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE) {
2427 if (is_clcp_track(track)) {
2429 descr = "ClosedCaptionHandler";
2431 if (track->tag == MKTAG('t','x','3','g')) {
2433 } else if (track->tag == MKTAG('m','p','4','s')) {
2438 descr = "SubtitleHandler";
2440 } else if (track->par->codec_tag == MKTAG('r','t','p',' ')) {
2442 descr = "HintHandler";
2443 } else if (track->par->codec_tag == MKTAG('t','m','c','d')) {
2445 descr = "TimeCodeHandler";
2447 av_log(s, AV_LOG_WARNING,
2448 "Unknown hldr_type for %s, writing dummy values\n",
2449 av_fourcc2str(track->par->codec_tag));
2452 // hdlr.name is used by some players to identify the content title
2453 // of the track. So if an alternate handler description is
2454 // specified, use it.
2455 AVDictionaryEntry *t;
2456 t = av_dict_get(track->st->metadata, "handler", NULL, 0);
2457 if (t && utf8len(t->value))
2462 avio_wb32(pb, 0); /* size */
2463 ffio_wfourcc(pb, "hdlr");
2464 avio_wb32(pb, 0); /* Version & flags */
2465 avio_write(pb, hdlr, 4); /* handler */
2466 ffio_wfourcc(pb, hdlr_type); /* handler type */
2467 avio_wb32(pb, 0); /* reserved */
2468 avio_wb32(pb, 0); /* reserved */
2469 avio_wb32(pb, 0); /* reserved */
2470 if (!track || track->mode == MODE_MOV)
2471 avio_w8(pb, strlen(descr)); /* pascal string */
2472 avio_write(pb, descr, strlen(descr)); /* handler description */
2473 if (track && track->mode != MODE_MOV)
2474 avio_w8(pb, 0); /* c string */
2475 return update_size(pb, pos);
2478 static int mov_write_hmhd_tag(AVIOContext *pb)
2480 /* This atom must be present, but leaving the values at zero
2481 * seems harmless. */
2482 avio_wb32(pb, 28); /* size */
2483 ffio_wfourcc(pb, "hmhd");
2484 avio_wb32(pb, 0); /* version, flags */
2485 avio_wb16(pb, 0); /* maxPDUsize */
2486 avio_wb16(pb, 0); /* avgPDUsize */
2487 avio_wb32(pb, 0); /* maxbitrate */
2488 avio_wb32(pb, 0); /* avgbitrate */
2489 avio_wb32(pb, 0); /* reserved */
2493 static int mov_write_minf_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
2495 int64_t pos = avio_tell(pb);
2498 avio_wb32(pb, 0); /* size */
2499 ffio_wfourcc(pb, "minf");
2500 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO)
2501 mov_write_vmhd_tag(pb);
2502 else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
2503 mov_write_smhd_tag(pb);
2504 else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE) {
2505 if (track->tag == MKTAG('t','e','x','t') || is_clcp_track(track)) {
2506 mov_write_gmhd_tag(pb, track);
2508 mov_write_nmhd_tag(pb);
2510 } else if (track->tag == MKTAG('r','t','p',' ')) {
2511 mov_write_hmhd_tag(pb);
2512 } else if (track->tag == MKTAG('t','m','c','d')) {
2513 if (track->mode != MODE_MOV)
2514 mov_write_nmhd_tag(pb);
2516 mov_write_gmhd_tag(pb, track);
2518 if (track->mode == MODE_MOV) /* FIXME: Why do it for MODE_MOV only ? */
2519 mov_write_hdlr_tag(s, pb, NULL);
2520 mov_write_dinf_tag(pb);
2521 if ((ret = mov_write_stbl_tag(s, pb, mov, track)) < 0)
2523 return update_size(pb, pos);
2526 static int mov_write_mdhd_tag(AVIOContext *pb, MOVMuxContext *mov,
2529 int version = track->track_duration < INT32_MAX ? 0 : 1;
2531 if (track->mode == MODE_ISM)
2534 (version == 1) ? avio_wb32(pb, 44) : avio_wb32(pb, 32); /* size */
2535 ffio_wfourcc(pb, "mdhd");
2536 avio_w8(pb, version);
2537 avio_wb24(pb, 0); /* flags */
2539 avio_wb64(pb, track->time);
2540 avio_wb64(pb, track->time);
2542 avio_wb32(pb, track->time); /* creation time */
2543 avio_wb32(pb, track->time); /* modification time */
2545 avio_wb32(pb, track->timescale); /* time scale (sample rate for audio) */
2546 if (!track->entry && mov->mode == MODE_ISM)
2547 (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
2548 else if (!track->entry)
2549 (version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0);
2551 (version == 1) ? avio_wb64(pb, track->track_duration) : avio_wb32(pb, track->track_duration); /* duration */
2552 avio_wb16(pb, track->language); /* language */
2553 avio_wb16(pb, 0); /* reserved (quality) */
2555 if (version != 0 && track->mode == MODE_MOV) {
2556 av_log(NULL, AV_LOG_ERROR,
2557 "FATAL error, file duration too long for timebase, this file will not be\n"
2558 "playable with quicktime. Choose a different timebase or a different\n"
2559 "container format\n");
2565 static int mov_write_mdia_tag(AVFormatContext *s, AVIOContext *pb,
2566 MOVMuxContext *mov, MOVTrack *track)
2568 int64_t pos = avio_tell(pb);
2571 avio_wb32(pb, 0); /* size */
2572 ffio_wfourcc(pb, "mdia");
2573 mov_write_mdhd_tag(pb, mov, track);
2574 mov_write_hdlr_tag(s, pb, track);
2575 if ((ret = mov_write_minf_tag(s, pb, mov, track)) < 0)
2577 return update_size(pb, pos);
2580 /* transformation matrix
2584 static void write_matrix(AVIOContext *pb, int16_t a, int16_t b, int16_t c,
2585 int16_t d, int16_t tx, int16_t ty)
2587 avio_wb32(pb, a << 16); /* 16.16 format */
2588 avio_wb32(pb, b << 16); /* 16.16 format */
2589 avio_wb32(pb, 0); /* u in 2.30 format */
2590 avio_wb32(pb, c << 16); /* 16.16 format */
2591 avio_wb32(pb, d << 16); /* 16.16 format */
2592 avio_wb32(pb, 0); /* v in 2.30 format */
2593 avio_wb32(pb, tx << 16); /* 16.16 format */
2594 avio_wb32(pb, ty << 16); /* 16.16 format */
2595 avio_wb32(pb, 1 << 30); /* w in 2.30 format */
2598 static int mov_write_tkhd_tag(AVIOContext *pb, MOVMuxContext *mov,
2599 MOVTrack *track, AVStream *st)
2601 int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE,
2602 track->timescale, AV_ROUND_UP);
2603 int version = duration < INT32_MAX ? 0 : 1;
2604 int flags = MOV_TKHD_FLAG_IN_MOVIE;
2608 uint32_t *display_matrix = NULL;
2609 int display_matrix_size, i;
2612 if (mov->per_stream_grouping)
2615 group = st->codecpar->codec_type;
2617 display_matrix = (uint32_t*)av_stream_get_side_data(st, AV_PKT_DATA_DISPLAYMATRIX,
2618 &display_matrix_size);
2619 if (display_matrix && display_matrix_size < 9 * sizeof(*display_matrix))
2620 display_matrix = NULL;
2623 if (track->flags & MOV_TRACK_ENABLED)
2624 flags |= MOV_TKHD_FLAG_ENABLED;
2626 if (track->mode == MODE_ISM)
2629 (version == 1) ? avio_wb32(pb, 104) : avio_wb32(pb, 92); /* size */
2630 ffio_wfourcc(pb, "tkhd");
2631 avio_w8(pb, version);
2632 avio_wb24(pb, flags);
2634 avio_wb64(pb, track->time);
2635 avio_wb64(pb, track->time);
2637 avio_wb32(pb, track->time); /* creation time */
2638 avio_wb32(pb, track->time); /* modification time */
2640 avio_wb32(pb, track->track_id); /* track-id */
2641 avio_wb32(pb, 0); /* reserved */
2642 if (!track->entry && mov->mode == MODE_ISM)
2643 (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
2644 else if (!track->entry)
2645 (version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0);
2647 (version == 1) ? avio_wb64(pb, duration) : avio_wb32(pb, duration);
2649 avio_wb32(pb, 0); /* reserved */
2650 avio_wb32(pb, 0); /* reserved */
2651 avio_wb16(pb, 0); /* layer */
2652 avio_wb16(pb, group); /* alternate group) */
2653 /* Volume, only for audio */
2654 if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
2655 avio_wb16(pb, 0x0100);
2658 avio_wb16(pb, 0); /* reserved */
2660 /* Matrix structure */
2661 #if FF_API_OLD_ROTATE_API
2662 if (st && st->metadata) {
2663 AVDictionaryEntry *rot = av_dict_get(st->metadata, "rotate", NULL, 0);
2664 rotation = (rot && rot->value) ? atoi(rot->value) : 0;
2667 if (display_matrix) {
2668 for (i = 0; i < 9; i++)
2669 avio_wb32(pb, display_matrix[i]);
2670 #if FF_API_OLD_ROTATE_API
2671 } else if (rotation == 90) {
2672 write_matrix(pb, 0, 1, -1, 0, track->par->height, 0);
2673 } else if (rotation == 180) {
2674 write_matrix(pb, -1, 0, 0, -1, track->par->width, track->par->height);
2675 } else if (rotation == 270) {
2676 write_matrix(pb, 0, -1, 1, 0, 0, track->par->width);
2679 write_matrix(pb, 1, 0, 0, 1, 0, 0);
2681 /* Track width and height, for visual only */
2682 if (st && (track->par->codec_type == AVMEDIA_TYPE_VIDEO ||
2683 track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)) {
2684 int64_t track_width_1616;
2685 if (track->mode == MODE_MOV) {
2686 track_width_1616 = track->par->width * 0x10000ULL;
2688 track_width_1616 = av_rescale(st->sample_aspect_ratio.num,
2689 track->par->width * 0x10000LL,
2690 st->sample_aspect_ratio.den);
2691 if (!track_width_1616 ||
2692 track->height != track->par->height ||
2693 track_width_1616 > UINT32_MAX)
2694 track_width_1616 = track->par->width * 0x10000ULL;
2696 if (track_width_1616 > UINT32_MAX) {
2697 av_log(mov->fc, AV_LOG_WARNING, "track width is too large\n");
2698 track_width_1616 = 0;
2700 avio_wb32(pb, track_width_1616);
2701 if (track->height > 0xFFFF) {
2702 av_log(mov->fc, AV_LOG_WARNING, "track height is too large\n");
2705 avio_wb32(pb, track->height * 0x10000U);
2713 static int mov_write_tapt_tag(AVIOContext *pb, MOVTrack *track)
2715 int32_t width = av_rescale(track->par->sample_aspect_ratio.num, track->par->width,
2716 track->par->sample_aspect_ratio.den);
2718 int64_t pos = avio_tell(pb);
2720 avio_wb32(pb, 0); /* size */
2721 ffio_wfourcc(pb, "tapt");
2724 ffio_wfourcc(pb, "clef");
2726 avio_wb32(pb, width << 16);
2727 avio_wb32(pb, track->par->height << 16);
2730 ffio_wfourcc(pb, "prof");
2732 avio_wb32(pb, width << 16);
2733 avio_wb32(pb, track->par->height << 16);
2736 ffio_wfourcc(pb, "enof");
2738 avio_wb32(pb, track->par->width << 16);
2739 avio_wb32(pb, track->par->height << 16);
2741 return update_size(pb, pos);
2744 // This box seems important for the psp playback ... without it the movie seems to hang
2745 static int mov_write_edts_tag(AVIOContext *pb, MOVMuxContext *mov,
2748 int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE,
2749 track->timescale, AV_ROUND_UP);
2750 int version = duration < INT32_MAX ? 0 : 1;
2751 int entry_size, entry_count, size;
2752 int64_t delay, start_ct = track->start_cts;
2753 int64_t start_dts = track->start_dts;
2756 if (start_dts != track->cluster[0].dts || start_ct != track->cluster[0].cts) {
2758 av_log(mov->fc, AV_LOG_DEBUG,
2759 "EDTS using dts:%"PRId64" cts:%d instead of dts:%"PRId64" cts:%"PRId64" tid:%d\n",
2760 track->cluster[0].dts, track->cluster[0].cts,
2761 start_dts, start_ct, track->track_id);
2762 start_dts = track->cluster[0].dts;
2763 start_ct = track->cluster[0].cts;
2767 delay = av_rescale_rnd(start_dts + start_ct, MOV_TIMESCALE,
2768 track->timescale, AV_ROUND_DOWN);
2769 version |= delay < INT32_MAX ? 0 : 1;
2771 entry_size = (version == 1) ? 20 : 12;
2772 entry_count = 1 + (delay > 0);
2773 size = 24 + entry_count * entry_size;
2775 /* write the atom data */
2776 avio_wb32(pb, size);
2777 ffio_wfourcc(pb, "edts");
2778 avio_wb32(pb, size - 8);
2779 ffio_wfourcc(pb, "elst");
2780 avio_w8(pb, version);
2781 avio_wb24(pb, 0); /* flags */
2783 avio_wb32(pb, entry_count);
2784 if (delay > 0) { /* add an empty edit to delay presentation */
2785 /* In the positive delay case, the delay includes the cts
2786 * offset, and the second edit list entry below trims out
2787 * the same amount from the actual content. This makes sure
2788 * that the offset last sample is included in the edit
2789 * list duration as well. */
2791 avio_wb64(pb, delay);
2794 avio_wb32(pb, delay);
2797 avio_wb32(pb, 0x00010000);
2799 /* Avoid accidentally ending up with start_ct = -1 which has got a
2800 * special meaning. Normally start_ct should end up positive or zero
2801 * here, but use FFMIN in case dts is a small positive integer
2802 * rounded to 0 when represented in MOV_TIMESCALE units. */
2803 av_assert0(av_rescale_rnd(start_dts, MOV_TIMESCALE, track->timescale, AV_ROUND_DOWN) <= 0);
2804 start_ct = -FFMIN(start_dts, 0);
2805 /* Note, this delay is calculated from the pts of the first sample,
2806 * ensuring that we don't reduce the duration for cases with
2811 /* For fragmented files, we don't know the full length yet. Setting
2812 * duration to 0 allows us to only specify the offset, including
2813 * the rest of the content (from all future fragments) without specifying
2814 * an explicit duration. */
2815 if (mov->flags & FF_MOV_FLAG_FRAGMENT)
2820 avio_wb64(pb, duration);
2821 avio_wb64(pb, start_ct);
2823 avio_wb32(pb, duration);
2824 avio_wb32(pb, start_ct);
2826 avio_wb32(pb, 0x00010000);
2830 static int mov_write_tref_tag(AVIOContext *pb, MOVTrack *track)
2832 avio_wb32(pb, 20); // size
2833 ffio_wfourcc(pb, "tref");
2834 avio_wb32(pb, 12); // size (subatom)
2835 avio_wl32(pb, track->tref_tag);
2836 avio_wb32(pb, track->tref_id);
2840 // goes at the end of each track! ... Critical for PSP playback ("Incompatible data" without it)
2841 static int mov_write_uuid_tag_psp(AVIOContext *pb, MOVTrack *mov)
2843 avio_wb32(pb, 0x34); /* size ... reports as 28 in mp4box! */
2844 ffio_wfourcc(pb, "uuid");
2845 ffio_wfourcc(pb, "USMT");
2846 avio_wb32(pb, 0x21d24fce);
2847 avio_wb32(pb, 0xbb88695c);
2848 avio_wb32(pb, 0xfac9c740);
2849 avio_wb32(pb, 0x1c); // another size here!
2850 ffio_wfourcc(pb, "MTDT");
2851 avio_wb32(pb, 0x00010012);
2852 avio_wb32(pb, 0x0a);
2853 avio_wb32(pb, 0x55c40000);
2859 static int mov_write_udta_sdp(AVIOContext *pb, MOVTrack *track)
2861 AVFormatContext *ctx = track->rtp_ctx;
2862 char buf[1000] = "";
2865 ff_sdp_write_media(buf, sizeof(buf), ctx->streams[0], track->src_track,
2866 NULL, NULL, 0, 0, ctx);
2867 av_strlcatf(buf, sizeof(buf), "a=control:streamid=%d\r\n", track->track_id);
2870 avio_wb32(pb, len + 24);
2871 ffio_wfourcc(pb, "udta");
2872 avio_wb32(pb, len + 16);
2873 ffio_wfourcc(pb, "hnti");
2874 avio_wb32(pb, len + 8);
2875 ffio_wfourcc(pb, "sdp ");
2876 avio_write(pb, buf, len);
2880 static int mov_write_track_metadata(AVIOContext *pb, AVStream *st,
2881 const char *tag, const char *str)
2883 int64_t pos = avio_tell(pb);
2884 AVDictionaryEntry *t = av_dict_get(st->metadata, str, NULL, 0);
2885 if (!t || !utf8len(t->value))
2888 avio_wb32(pb, 0); /* size */
2889 ffio_wfourcc(pb, tag); /* type */
2890 avio_write(pb, t->value, strlen(t->value)); /* UTF8 string value */
2891 return update_size(pb, pos);
2894 static int mov_write_track_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
2897 AVIOContext *pb_buf;
2904 ret = avio_open_dyn_buf(&pb_buf);
2908 if (mov->mode & MODE_MP4)
2909 mov_write_track_metadata(pb_buf, st, "name", "title");
2911 if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) {
2912 avio_wb32(pb, size + 8);
2913 ffio_wfourcc(pb, "udta");
2914 avio_write(pb, buf, size);
2921 static int mov_write_trak_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov,
2922 MOVTrack *track, AVStream *st)
2924 int64_t pos = avio_tell(pb);
2925 int entry_backup = track->entry;
2926 int chunk_backup = track->chunkCount;
2929 /* If we want to have an empty moov, but some samples already have been
2930 * buffered (delay_moov), pretend that no samples have been written yet. */
2931 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV)
2932 track->chunkCount = track->entry = 0;
2934 avio_wb32(pb, 0); /* size */
2935 ffio_wfourcc(pb, "trak");
2936 mov_write_tkhd_tag(pb, mov, track, st);
2938 av_assert2(mov->use_editlist >= 0);
2940 if (track->start_dts != AV_NOPTS_VALUE) {
2941 if (mov->use_editlist)
2942 mov_write_edts_tag(pb, mov, track); // PSP Movies and several other cases require edts box
2943 else if ((track->entry && track->cluster[0].dts) || track->mode == MODE_PSP || is_clcp_track(track))
2944 av_log(mov->fc, AV_LOG_WARNING,
2945 "Not writing any edit list even though one would have been required\n");
2948 if (track->tref_tag)
2949 mov_write_tref_tag(pb, track);
2951 if ((ret = mov_write_mdia_tag(s, pb, mov, track)) < 0)
2953 if (track->mode == MODE_PSP)
2954 mov_write_uuid_tag_psp(pb, track); // PSP Movies require this uuid box
2955 if (track->tag == MKTAG('r','t','p',' '))
2956 mov_write_udta_sdp(pb, track);
2957 if (track->mode == MODE_MOV) {
2958 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
2959 double sample_aspect_ratio = av_q2d(st->sample_aspect_ratio);
2960 if (st->sample_aspect_ratio.num && 1.0 != sample_aspect_ratio) {
2961 mov_write_tapt_tag(pb, track);
2964 if (is_clcp_track(track) && st->sample_aspect_ratio.num) {
2965 mov_write_tapt_tag(pb, track);
2968 mov_write_track_udta_tag(pb, mov, st);
2969 track->entry = entry_backup;
2970 track->chunkCount = chunk_backup;
2971 return update_size(pb, pos);
2974 static int mov_write_iods_tag(AVIOContext *pb, MOVMuxContext *mov)
2976 int i, has_audio = 0, has_video = 0;
2977 int64_t pos = avio_tell(pb);
2978 int audio_profile = mov->iods_audio_profile;
2979 int video_profile = mov->iods_video_profile;
2980 for (i = 0; i < mov->nb_streams; i++) {
2981 if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
2982 has_audio |= mov->tracks[i].par->codec_type == AVMEDIA_TYPE_AUDIO;
2983 has_video |= mov->tracks[i].par->codec_type == AVMEDIA_TYPE_VIDEO;
2986 if (audio_profile < 0)
2987 audio_profile = 0xFF - has_audio;
2988 if (video_profile < 0)
2989 video_profile = 0xFF - has_video;
2990 avio_wb32(pb, 0x0); /* size */
2991 ffio_wfourcc(pb, "iods");
2992 avio_wb32(pb, 0); /* version & flags */
2993 put_descr(pb, 0x10, 7);
2994 avio_wb16(pb, 0x004f);
2997 avio_w8(pb, audio_profile);
2998 avio_w8(pb, video_profile);
3000 return update_size(pb, pos);
3003 static int mov_write_trex_tag(AVIOContext *pb, MOVTrack *track)
3005 avio_wb32(pb, 0x20); /* size */
3006 ffio_wfourcc(pb, "trex");
3007 avio_wb32(pb, 0); /* version & flags */
3008 avio_wb32(pb, track->track_id); /* track ID */
3009 avio_wb32(pb, 1); /* default sample description index */
3010 avio_wb32(pb, 0); /* default sample duration */
3011 avio_wb32(pb, 0); /* default sample size */
3012 avio_wb32(pb, 0); /* default sample flags */
3016 static int mov_write_mvex_tag(AVIOContext *pb, MOVMuxContext *mov)
3018 int64_t pos = avio_tell(pb);
3020 avio_wb32(pb, 0x0); /* size */
3021 ffio_wfourcc(pb, "mvex");
3022 for (i = 0; i < mov->nb_streams; i++)
3023 mov_write_trex_tag(pb, &mov->tracks[i]);
3024 return update_size(pb, pos);
3027 static int mov_write_mvhd_tag(AVIOContext *pb, MOVMuxContext *mov)
3029 int max_track_id = 1, i;
3030 int64_t max_track_len = 0;
3033 for (i = 0; i < mov->nb_streams; i++) {
3034 if (mov->tracks[i].entry > 0 && mov->tracks[i].timescale) {
3035 int64_t max_track_len_temp = av_rescale_rnd(mov->tracks[i].track_duration,
3037 mov->tracks[i].timescale,
3039 if (max_track_len < max_track_len_temp)
3040 max_track_len = max_track_len_temp;
3041 if (max_track_id < mov->tracks[i].track_id)
3042 max_track_id = mov->tracks[i].track_id;
3045 /* If using delay_moov, make sure the output is the same as if no
3046 * samples had been written yet. */
3047 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
3052 version = max_track_len < UINT32_MAX ? 0 : 1;
3053 avio_wb32(pb, version == 1 ? 120 : 108); /* size */
3055 ffio_wfourcc(pb, "mvhd");
3056 avio_w8(pb, version);
3057 avio_wb24(pb, 0); /* flags */
3059 avio_wb64(pb, mov->time);
3060 avio_wb64(pb, mov->time);
3062 avio_wb32(pb, mov->time); /* creation time */
3063 avio_wb32(pb, mov->time); /* modification time */
3065 avio_wb32(pb, MOV_TIMESCALE);
3066 (version == 1) ? avio_wb64(pb, max_track_len) : avio_wb32(pb, max_track_len); /* duration of longest track */
3068 avio_wb32(pb, 0x00010000); /* reserved (preferred rate) 1.0 = normal */
3069 avio_wb16(pb, 0x0100); /* reserved (preferred volume) 1.0 = normal */
3070 avio_wb16(pb, 0); /* reserved */
3071 avio_wb32(pb, 0); /* reserved */
3072 avio_wb32(pb, 0); /* reserved */
3074 /* Matrix structure */
3075 write_matrix(pb, 1, 0, 0, 1, 0, 0);
3077 avio_wb32(pb, 0); /* reserved (preview time) */
3078 avio_wb32(pb, 0); /* reserved (preview duration) */
3079 avio_wb32(pb, 0); /* reserved (poster time) */
3080 avio_wb32(pb, 0); /* reserved (selection time) */
3081 avio_wb32(pb, 0); /* reserved (selection duration) */
3082 avio_wb32(pb, 0); /* reserved (current time) */
3083 avio_wb32(pb, max_track_id + 1); /* Next track id */
3087 static int mov_write_itunes_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov,
3090 avio_wb32(pb, 33); /* size */
3091 ffio_wfourcc(pb, "hdlr");
3094 ffio_wfourcc(pb, "mdir");
3095 ffio_wfourcc(pb, "appl");
3102 /* helper function to write a data tag with the specified string as data */
3103 static int mov_write_string_data_tag(AVIOContext *pb, const char *data, int lang, int long_style)
3106 int size = 16 + strlen(data);
3107 avio_wb32(pb, size); /* size */
3108 ffio_wfourcc(pb, "data");
3111 avio_write(pb, data, strlen(data));
3115 lang = ff_mov_iso639_to_lang("und", 1);
3116 avio_wb16(pb, strlen(data)); /* string length */
3117 avio_wb16(pb, lang);
3118 avio_write(pb, data, strlen(data));
3119 return strlen(data) + 4;
3123 static int mov_write_string_tag(AVIOContext *pb, const char *name,
3124 const char *value, int lang, int long_style)
3127 if (value && value[0]) {
3128 int64_t pos = avio_tell(pb);
3129 avio_wb32(pb, 0); /* size */
3130 ffio_wfourcc(pb, name);
3131 mov_write_string_data_tag(pb, value, lang, long_style);
3132 size = update_size(pb, pos);
3137 static AVDictionaryEntry *get_metadata_lang(AVFormatContext *s,
3138 const char *tag, int *lang)
3141 AVDictionaryEntry *t, *t2 = NULL;
3146 if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
3149 len = strlen(t->key);
3150 snprintf(tag2, sizeof(tag2), "%s-", tag);
3151 while ((t2 = av_dict_get(s->metadata, tag2, t2, AV_DICT_IGNORE_SUFFIX))) {
3152 len2 = strlen(t2->key);
3153 if (len2 == len + 4 && !strcmp(t->value, t2->value)
3154 && (l = ff_mov_iso639_to_lang(&t2->key[len2 - 3], 1)) >= 0) {
3162 static int mov_write_string_metadata(AVFormatContext *s, AVIOContext *pb,
3163 const char *name, const char *tag,
3167 AVDictionaryEntry *t = get_metadata_lang(s, tag, &lang);
3170 return mov_write_string_tag(pb, name, t->value, lang, long_style);
3173 /* iTunes bpm number */
3174 static int mov_write_tmpo_tag(AVIOContext *pb, AVFormatContext *s)
3176 AVDictionaryEntry *t = av_dict_get(s->metadata, "tmpo", NULL, 0);
3177 int size = 0, tmpo = t ? atoi(t->value) : 0;
3180 avio_wb32(pb, size);
3181 ffio_wfourcc(pb, "tmpo");
3182 avio_wb32(pb, size-8); /* size */
3183 ffio_wfourcc(pb, "data");
3184 avio_wb32(pb, 0x15); //type specifier
3186 avio_wb16(pb, tmpo); // data
3191 /* 3GPP TS 26.244 */
3192 static int mov_write_loci_tag(AVFormatContext *s, AVIOContext *pb)
3195 int64_t pos = avio_tell(pb);
3196 double latitude, longitude, altitude;
3197 int32_t latitude_fix, longitude_fix, altitude_fix;
3198 AVDictionaryEntry *t = get_metadata_lang(s, "location", &lang);
3199 const char *ptr, *place = "";
3201 static const char *astronomical_body = "earth";
3206 longitude = strtod(ptr, &end);
3208 av_log(s, AV_LOG_WARNING, "malformed location metadata\n");
3212 latitude = strtod(ptr, &end);
3214 av_log(s, AV_LOG_WARNING, "malformed location metadata\n");
3218 altitude = strtod(ptr, &end);
3219 /* If no altitude was present, the default 0 should be fine */
3223 latitude_fix = (int32_t) ((1 << 16) * latitude);
3224 longitude_fix = (int32_t) ((1 << 16) * longitude);
3225 altitude_fix = (int32_t) ((1 << 16) * altitude);
3227 avio_wb32(pb, 0); /* size */
3228 ffio_wfourcc(pb, "loci"); /* type */
3229 avio_wb32(pb, 0); /* version + flags */
3230 avio_wb16(pb, lang);
3231 avio_write(pb, place, strlen(place) + 1);
3232 avio_w8(pb, 0); /* role of place (0 == shooting location, 1 == real location, 2 == fictional location) */
3233 avio_wb32(pb, latitude_fix);
3234 avio_wb32(pb, longitude_fix);
3235 avio_wb32(pb, altitude_fix);
3236 avio_write(pb, astronomical_body, strlen(astronomical_body) + 1);
3237 avio_w8(pb, 0); /* additional notes, null terminated string */
3239 return update_size(pb, pos);
3242 /* iTunes track or disc number */
3243 static int mov_write_trkn_tag(AVIOContext *pb, MOVMuxContext *mov,
3244 AVFormatContext *s, int disc)
3246 AVDictionaryEntry *t = av_dict_get(s->metadata,
3247 disc ? "disc" : "track",
3249 int size = 0, track = t ? atoi(t->value) : 0;
3252 char *slash = strchr(t->value, '/');
3254 tracks = atoi(slash + 1);
3255 avio_wb32(pb, 32); /* size */
3256 ffio_wfourcc(pb, disc ? "disk" : "trkn");
3257 avio_wb32(pb, 24); /* size */
3258 ffio_wfourcc(pb, "data");
3259 avio_wb32(pb, 0); // 8 bytes empty
3261 avio_wb16(pb, 0); // empty
3262 avio_wb16(pb, track); // track / disc number
3263 avio_wb16(pb, tracks); // total track / disc number
3264 avio_wb16(pb, 0); // empty
3270 static int mov_write_int8_metadata(AVFormatContext *s, AVIOContext *pb,
3271 const char *name, const char *tag,
3274 AVDictionaryEntry *t = NULL;
3276 int size = 24 + len;
3278 if (len != 1 && len != 4)
3281 if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
3283 num = atoi(t->value);
3285 avio_wb32(pb, size);
3286 ffio_wfourcc(pb, name);
3287 avio_wb32(pb, size - 8);
3288 ffio_wfourcc(pb, "data");
3289 avio_wb32(pb, 0x15);
3291 if (len==4) avio_wb32(pb, num);
3292 else avio_w8 (pb, num);
3297 /* iTunes meta data list */
3298 static int mov_write_ilst_tag(AVIOContext *pb, MOVMuxContext *mov,
3301 int64_t pos = avio_tell(pb);
3302 avio_wb32(pb, 0); /* size */
3303 ffio_wfourcc(pb, "ilst");
3304 mov_write_string_metadata(s, pb, "\251nam", "title" , 1);
3305 mov_write_string_metadata(s, pb, "\251ART", "artist" , 1);
3306 mov_write_string_metadata(s, pb, "aART", "album_artist", 1);
3307 mov_write_string_metadata(s, pb, "\251wrt", "composer" , 1);
3308 mov_write_string_metadata(s, pb, "\251alb", "album" , 1);
3309 mov_write_string_metadata(s, pb, "\251day", "date" , 1);
3310 if (!mov_write_string_metadata(s, pb, "\251too", "encoding_tool", 1)) {
3311 if (!(s->flags & AVFMT_FLAG_BITEXACT))
3312 mov_write_string_tag(pb, "\251too", LIBAVFORMAT_IDENT, 0, 1);
3314 mov_write_string_metadata(s, pb, "\251cmt", "comment" , 1);
3315 mov_write_string_metadata(s, pb, "\251gen", "genre" , 1);
3316 mov_write_string_metadata(s, pb, "\251cpy", "copyright", 1);
3317 mov_write_string_metadata(s, pb, "\251grp", "grouping" , 1);
3318 mov_write_string_metadata(s, pb, "\251lyr", "lyrics" , 1);
3319 mov_write_string_metadata(s, pb, "desc", "description",1);
3320 mov_write_string_metadata(s, pb, "ldes", "synopsis" , 1);
3321 mov_write_string_metadata(s, pb, "tvsh", "show" , 1);
3322 mov_write_string_metadata(s, pb, "tven", "episode_id",1);
3323 mov_write_string_metadata(s, pb, "tvnn", "network" , 1);
3324 mov_write_string_metadata(s, pb, "keyw", "keywords" , 1);
3325 mov_write_int8_metadata (s, pb, "tves", "episode_sort",4);
3326 mov_write_int8_metadata (s, pb, "tvsn", "season_number",4);
3327 mov_write_int8_metadata (s, pb, "stik", "media_type",1);
3328 mov_write_int8_metadata (s, pb, "hdvd", "hd_video", 1);
3329 mov_write_int8_metadata (s, pb, "pgap", "gapless_playback",1);
3330 mov_write_int8_metadata (s, pb, "cpil", "compilation", 1);
3331 mov_write_trkn_tag(pb, mov, s, 0); // track number
3332 mov_write_trkn_tag(pb, mov, s, 1); // disc number
3333 mov_write_tmpo_tag(pb, s);
3334 return update_size(pb, pos);
3337 static int mov_write_mdta_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov,
3340 avio_wb32(pb, 33); /* size */
3341 ffio_wfourcc(pb, "hdlr");
3344 ffio_wfourcc(pb, "mdta");
3352 static int mov_write_mdta_keys_tag(AVIOContext *pb, MOVMuxContext *mov,
3355 AVDictionaryEntry *t = NULL;
3356 int64_t pos = avio_tell(pb);
3357 int64_t curpos, entry_pos;
3360 avio_wb32(pb, 0); /* size */
3361 ffio_wfourcc(pb, "keys");
3363 entry_pos = avio_tell(pb);
3364 avio_wb32(pb, 0); /* entry count */
3366 while (t = av_dict_get(s->metadata, "", t, AV_DICT_IGNORE_SUFFIX)) {
3367 avio_wb32(pb, strlen(t->key) + 8);
3368 ffio_wfourcc(pb, "mdta");
3369 avio_write(pb, t->key, strlen(t->key));
3372 curpos = avio_tell(pb);
3373 avio_seek(pb, entry_pos, SEEK_SET);
3374 avio_wb32(pb, count); // rewrite entry count
3375 avio_seek(pb, curpos, SEEK_SET);
3377 return update_size(pb, pos);
3380 static int mov_write_mdta_ilst_tag(AVIOContext *pb, MOVMuxContext *mov,
3383 AVDictionaryEntry *t = NULL;
3384 int64_t pos = avio_tell(pb);
3385 int count = 1; /* keys are 1-index based */
3387 avio_wb32(pb, 0); /* size */
3388 ffio_wfourcc(pb, "ilst");
3390 while (t = av_dict_get(s->metadata, "", t, AV_DICT_IGNORE_SUFFIX)) {
3391 int64_t entry_pos = avio_tell(pb);
3392 avio_wb32(pb, 0); /* size */
3393 avio_wb32(pb, count); /* key */
3394 mov_write_string_data_tag(pb, t->value, 0, 1);
3395 update_size(pb, entry_pos);
3398 return update_size(pb, pos);
3401 /* meta data tags */
3402 static int mov_write_meta_tag(AVIOContext *pb, MOVMuxContext *mov,
3406 int64_t pos = avio_tell(pb);
3407 avio_wb32(pb, 0); /* size */
3408 ffio_wfourcc(pb, "meta");
3410 if (mov->flags & FF_MOV_FLAG_USE_MDTA) {
3411 mov_write_mdta_hdlr_tag(pb, mov, s);
3412 mov_write_mdta_keys_tag(pb, mov, s);
3413 mov_write_mdta_ilst_tag(pb, mov, s);
3416 /* iTunes metadata tag */
3417 mov_write_itunes_hdlr_tag(pb, mov, s);
3418 mov_write_ilst_tag(pb, mov, s);
3420 size = update_size(pb, pos);
3424 static int mov_write_raw_metadata_tag(AVFormatContext *s, AVIOContext *pb,
3425 const char *name, const char *key)
3428 AVDictionaryEntry *t;
3430 if (!(t = av_dict_get(s->metadata, key, NULL, 0)))
3433 len = strlen(t->value);
3436 avio_wb32(pb, size);
3437 ffio_wfourcc(pb, name);
3438 avio_write(pb, t->value, len);
3444 static int ascii_to_wc(AVIOContext *pb, const uint8_t *b)
3448 GET_UTF8(val, *b++, return -1;)
3451 avio_wb16(pb, 0x00);
3455 static uint16_t language_code(const char *str)
3457 return (((str[0] - 0x60) & 0x1F) << 10) +
3458 (((str[1] - 0x60) & 0x1F) << 5) +
3459 (( str[2] - 0x60) & 0x1F);
3462 static int mov_write_3gp_udta_tag(AVIOContext *pb, AVFormatContext *s,
3463 const char *tag, const char *str)
3465 int64_t pos = avio_tell(pb);
3466 AVDictionaryEntry *t = av_dict_get(s->metadata, str, NULL, 0);
3467 if (!t || !utf8len(t->value))
3469 avio_wb32(pb, 0); /* size */
3470 ffio_wfourcc(pb, tag); /* type */
3471 avio_wb32(pb, 0); /* version + flags */
3472 if (!strcmp(tag, "yrrc"))
3473 avio_wb16(pb, atoi(t->value));
3475 avio_wb16(pb, language_code("eng")); /* language */
3476 avio_write(pb, t->value, strlen(t->value) + 1); /* UTF8 string value */
3477 if (!strcmp(tag, "albm") &&
3478 (t = av_dict_get(s->metadata, "track", NULL, 0)))
3479 avio_w8(pb, atoi(t->value));
3481 return update_size(pb, pos);
3484 static int mov_write_chpl_tag(AVIOContext *pb, AVFormatContext *s)
3486 int64_t pos = avio_tell(pb);
3487 int i, nb_chapters = FFMIN(s->nb_chapters, 255);
3489 avio_wb32(pb, 0); // size
3490 ffio_wfourcc(pb, "chpl");
3491 avio_wb32(pb, 0x01000000); // version + flags
3492 avio_wb32(pb, 0); // unknown
3493 avio_w8(pb, nb_chapters);
3495 for (i = 0; i < nb_chapters; i++) {
3496 AVChapter *c = s->chapters[i];
3497 AVDictionaryEntry *t;
3498 avio_wb64(pb, av_rescale_q(c->start, c->time_base, (AVRational){1,10000000}));
3500 if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
3501 int len = FFMIN(strlen(t->value), 255);
3503 avio_write(pb, t->value, len);
3507 return update_size(pb, pos);
3510 static int mov_write_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
3513 AVIOContext *pb_buf;
3517 ret = avio_open_dyn_buf(&pb_buf);
3521 if (mov->mode & MODE_3GP) {
3522 mov_write_3gp_udta_tag(pb_buf, s, "perf", "artist");
3523 mov_write_3gp_udta_tag(pb_buf, s, "titl", "title");
3524 mov_write_3gp_udta_tag(pb_buf, s, "auth", "author");
3525 mov_write_3gp_udta_tag(pb_buf, s, "gnre", "genre");
3526 mov_write_3gp_udta_tag(pb_buf, s, "dscp", "comment");
3527 mov_write_3gp_udta_tag(pb_buf, s, "albm", "album");
3528 mov_write_3gp_udta_tag(pb_buf, s, "cprt", "copyright");
3529 mov_write_3gp_udta_tag(pb_buf, s, "yrrc", "date");
3530 mov_write_loci_tag(s, pb_buf);
3531 } 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
3532 mov_write_string_metadata(s, pb_buf, "\251ART", "artist", 0);
3533 mov_write_string_metadata(s, pb_buf, "\251nam", "title", 0);
3534 mov_write_string_metadata(s, pb_buf, "\251aut", "author", 0);
3535 mov_write_string_metadata(s, pb_buf, "\251alb", "album", 0);
3536 mov_write_string_metadata(s, pb_buf, "\251day", "date", 0);
3537 mov_write_string_metadata(s, pb_buf, "\251swr", "encoder", 0);
3538 // currently ignored by mov.c
3539 mov_write_string_metadata(s, pb_buf, "\251des", "comment", 0);
3540 // add support for libquicktime, this atom is also actually read by mov.c
3541 mov_write_string_metadata(s, pb_buf, "\251cmt", "comment", 0);
3542 mov_write_string_metadata(s, pb_buf, "\251gen", "genre", 0);
3543 mov_write_string_metadata(s, pb_buf, "\251cpy", "copyright", 0);
3544 mov_write_string_metadata(s, pb_buf, "\251mak", "make", 0);
3545 mov_write_string_metadata(s, pb_buf, "\251mod", "model", 0);
3546 mov_write_string_metadata(s, pb_buf, "\251xyz", "location", 0);
3547 mov_write_string_metadata(s, pb_buf, "\251key", "keywords", 0);
3548 mov_write_raw_metadata_tag(s, pb_buf, "XMP_", "xmp");
3550 /* iTunes meta data */
3551 mov_write_meta_tag(pb_buf, mov, s);
3552 mov_write_loci_tag(s, pb_buf);
3555 if (s->nb_chapters && !(mov->flags & FF_MOV_FLAG_DISABLE_CHPL))
3556 mov_write_chpl_tag(pb_buf, s);
3558 if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) {
3559 avio_wb32(pb, size + 8);
3560 ffio_wfourcc(pb, "udta");
3561 avio_write(pb, buf, size);
3568 static void mov_write_psp_udta_tag(AVIOContext *pb,
3569 const char *str, const char *lang, int type)
3571 int len = utf8len(str) + 1;
3574 avio_wb16(pb, len * 2 + 10); /* size */
3575 avio_wb32(pb, type); /* type */
3576 avio_wb16(pb, language_code(lang)); /* language */
3577 avio_wb16(pb, 0x01); /* ? */
3578 ascii_to_wc(pb, str);
3581 static int mov_write_uuidusmt_tag(AVIOContext *pb, AVFormatContext *s)
3583 AVDictionaryEntry *title = av_dict_get(s->metadata, "title", NULL, 0);
3587 pos = avio_tell(pb);
3588 avio_wb32(pb, 0); /* size placeholder*/
3589 ffio_wfourcc(pb, "uuid");
3590 ffio_wfourcc(pb, "USMT");
3591 avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
3592 avio_wb32(pb, 0xbb88695c);
3593 avio_wb32(pb, 0xfac9c740);
3595 pos2 = avio_tell(pb);
3596 avio_wb32(pb, 0); /* size placeholder*/
3597 ffio_wfourcc(pb, "MTDT");
3601 avio_wb16(pb, 0x0C); /* size */
3602 avio_wb32(pb, 0x0B); /* type */
3603 avio_wb16(pb, language_code("und")); /* language */
3604 avio_wb16(pb, 0x0); /* ? */
3605 avio_wb16(pb, 0x021C); /* data */
3607 if (!(s->flags & AVFMT_FLAG_BITEXACT))
3608 mov_write_psp_udta_tag(pb, LIBAVCODEC_IDENT, "eng", 0x04);
3609 mov_write_psp_udta_tag(pb, title->value, "eng", 0x01);
3610 mov_write_psp_udta_tag(pb, "2006/04/01 11:11:11", "und", 0x03);
3612 update_size(pb, pos2);
3613 return update_size(pb, pos);
3619 static void build_chunks(MOVTrack *trk)
3622 MOVIentry *chunk = &trk->cluster[0];
3623 uint64_t chunkSize = chunk->size;
3624 chunk->chunkNum = 1;
3625 if (trk->chunkCount)
3627 trk->chunkCount = 1;
3628 for (i = 1; i<trk->entry; i++){
3629 if (chunk->pos + chunkSize == trk->cluster[i].pos &&
3630 chunkSize + trk->cluster[i].size < (1<<20)){
3631 chunkSize += trk->cluster[i].size;
3632 chunk->samples_in_chunk += trk->cluster[i].entries;
3634 trk->cluster[i].chunkNum = chunk->chunkNum+1;
3635 chunk=&trk->cluster[i];
3636 chunkSize = chunk->size;
3643 * Assign track ids. If option "use_stream_ids_as_track_ids" is set,
3644 * the stream ids are used as track ids.
3646 * This assumes mov->tracks and s->streams are in the same order and
3647 * there are no gaps in either of them (so mov->tracks[n] refers to
3650 * As an exception, there can be more entries in
3651 * s->streams than in mov->tracks, in which case new track ids are
3652 * generated (starting after the largest found stream id).
3654 static int mov_setup_track_ids(MOVMuxContext *mov, AVFormatContext *s)
3658 if (mov->track_ids_ok)
3661 if (mov->use_stream_ids_as_track_ids) {
3662 int next_generated_track_id = 0;
3663 for (i = 0; i < s->nb_streams; i++) {
3664 if (s->streams[i]->id > next_generated_track_id)
3665 next_generated_track_id = s->streams[i]->id;
3668 for (i = 0; i < mov->nb_streams; i++) {
3669 if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
3672 mov->tracks[i].track_id = i >= s->nb_streams ? ++next_generated_track_id : s->streams[i]->id;
3675 for (i = 0; i < mov->nb_streams; i++) {
3676 if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
3679 mov->tracks[i].track_id = i + 1;
3683 mov->track_ids_ok = 1;
3688 static int mov_write_moov_tag(AVIOContext *pb, MOVMuxContext *mov,
3692 int64_t pos = avio_tell(pb);
3693 avio_wb32(pb, 0); /* size placeholder*/
3694 ffio_wfourcc(pb, "moov");
3696 mov_setup_track_ids(mov, s);
3698 for (i = 0; i < mov->nb_streams; i++) {
3699 if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
3702 mov->tracks[i].time = mov->time;
3704 if (mov->tracks[i].entry)
3705 build_chunks(&mov->tracks[i]);
3708 if (mov->chapter_track)
3709 for (i = 0; i < s->nb_streams; i++) {
3710 mov->tracks[i].tref_tag = MKTAG('c','h','a','p');
3711 mov->tracks[i].tref_id = mov->tracks[mov->chapter_track].track_id;
3713 for (i = 0; i < mov->nb_streams; i++) {
3714 MOVTrack *track = &mov->tracks[i];
3715 if (track->tag == MKTAG('r','t','p',' ')) {
3716 track->tref_tag = MKTAG('h','i','n','t');
3717 track->tref_id = mov->tracks[track->src_track].track_id;
3718 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
3719 int * fallback, size;
3720 fallback = (int*)av_stream_get_side_data(track->st,
3721 AV_PKT_DATA_FALLBACK_TRACK,
3723 if (fallback != NULL && size == sizeof(int)) {
3724 if (*fallback >= 0 && *fallback < mov->nb_streams) {
3725 track->tref_tag = MKTAG('f','a','l','l');
3726 track->tref_id = mov->tracks[*fallback].track_id;
3731 for (i = 0; i < mov->nb_streams; i++) {
3732 if (mov->tracks[i].tag == MKTAG('t','m','c','d')) {
3733 int src_trk = mov->tracks[i].src_track;
3734 mov->tracks[src_trk].tref_tag = mov->tracks[i].tag;
3735 mov->tracks[src_trk].tref_id = mov->tracks[i].track_id;
3736 //src_trk may have a different timescale than the tmcd track
3737 mov->tracks[i].track_duration = av_rescale(mov->tracks[src_trk].track_duration,
3738 mov->tracks[i].timescale,
3739 mov->tracks[src_trk].timescale);
3743 mov_write_mvhd_tag(pb, mov);
3744 if (mov->mode != MODE_MOV && !mov->iods_skip)
3745 mov_write_iods_tag(pb, mov);
3746 for (i = 0; i < mov->nb_streams; i++) {
3747 if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_FRAGMENT) {
3748 int ret = mov_write_trak_tag(s, pb, mov, &(mov->tracks[i]), i < s->nb_streams ? s->streams[i] : NULL);
3753 if (mov->flags & FF_MOV_FLAG_FRAGMENT)
3754 mov_write_mvex_tag(pb, mov); /* QuickTime requires trak to precede this */
3756 if (mov->mode == MODE_PSP)
3757 mov_write_uuidusmt_tag(pb, s);
3759 mov_write_udta_tag(pb, mov, s);
3761 return update_size(pb, pos);
3764 static void param_write_int(AVIOContext *pb, const char *name, int value)
3766 avio_printf(pb, "<param name=\"%s\" value=\"%d\" valuetype=\"data\"/>\n", name, value);
3769 static void param_write_string(AVIOContext *pb, const char *name, const char *value)
3771 avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, value);
3774 static void param_write_hex(AVIOContext *pb, const char *name, const uint8_t *value, int len)
3777 len = FFMIN(sizeof(buf) / 2 - 1, len);
3778 ff_data_to_hex(buf, value, len, 0);
3779 buf[2 * len] = '\0';
3780 avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, buf);
3783 static int mov_write_isml_manifest(AVIOContext *pb, MOVMuxContext *mov, AVFormatContext *s)
3785 int64_t pos = avio_tell(pb);
3787 int64_t manifest_bit_rate = 0;
3788 AVCPBProperties *props = NULL;
3790 static const uint8_t uuid[] = {
3791 0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd,
3792 0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66
3796 ffio_wfourcc(pb, "uuid");
3797 avio_write(pb, uuid, sizeof(uuid));
3800 avio_printf(pb, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
3801 avio_printf(pb, "<smil xmlns=\"http://www.w3.org/2001/SMIL20/Language\">\n");
3802 avio_printf(pb, "<head>\n");
3803 if (!(mov->fc->flags & AVFMT_FLAG_BITEXACT))
3804 avio_printf(pb, "<meta name=\"creator\" content=\"%s\" />\n",
3806 avio_printf(pb, "</head>\n");
3807 avio_printf(pb, "<body>\n");
3808 avio_printf(pb, "<switch>\n");
3810 mov_setup_track_ids(mov, s);
3812 for (i = 0; i < mov->nb_streams; i++) {
3813 MOVTrack *track = &mov->tracks[i];
3815 int track_id = track->track_id;
3816 char track_name_buf[32] = { 0 };
3818 AVStream *st = track->st;
3819 AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0);
3821 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
3823 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
3829 props = (AVCPBProperties*)av_stream_get_side_data(track->st, AV_PKT_DATA_CPB_PROPERTIES, NULL);
3831 if (track->par->bit_rate) {
3832 manifest_bit_rate = track->par->bit_rate;
3834 manifest_bit_rate = props->max_bitrate;
3837 avio_printf(pb, "<%s systemBitrate=\"%"PRId64"\">\n", type,
3839 param_write_int(pb, "systemBitrate", manifest_bit_rate);
3840 param_write_int(pb, "trackID", track_id);
3841 param_write_string(pb, "systemLanguage", lang ? lang->value : "und");
3843 /* Build track name piece by piece: */
3845 av_strlcat(track_name_buf, type, sizeof(track_name_buf));
3846 /* 2. track language, if available */
3848 av_strlcatf(track_name_buf, sizeof(track_name_buf),
3849 "_%s", lang->value);
3850 /* 3. special type suffix */
3851 /* "_cc" = closed captions, "_ad" = audio_description */
3852 if (st->disposition & AV_DISPOSITION_HEARING_IMPAIRED)
3853 av_strlcat(track_name_buf, "_cc", sizeof(track_name_buf));
3854 else if (st->disposition & AV_DISPOSITION_VISUAL_IMPAIRED)
3855 av_strlcat(track_name_buf, "_ad", sizeof(track_name_buf));
3857 param_write_string(pb, "trackName", track_name_buf);
3859 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
3860 if (track->par->codec_id == AV_CODEC_ID_H264) {
3862 int size = track->par->extradata_size;
3863 if (!ff_avc_write_annexb_extradata(track->par->extradata, &ptr,
3865 param_write_hex(pb, "CodecPrivateData",
3866 ptr ? ptr : track->par->extradata,
3870 param_write_string(pb, "FourCC", "H264");
3871 } else if (track->par->codec_id == AV_CODEC_ID_VC1) {
3872 param_write_string(pb, "FourCC", "WVC1");
3873 param_write_hex(pb, "CodecPrivateData", track->par->extradata,
3874 track->par->extradata_size);
3876 param_write_int(pb, "MaxWidth", track->par->width);
3877 param_write_int(pb, "MaxHeight", track->par->height);
3878 param_write_int(pb, "DisplayWidth", track->par->width);
3879 param_write_int(pb, "DisplayHeight", track->par->height);
3881 if (track->par->codec_id == AV_CODEC_ID_AAC) {
3882 switch (track->par->profile)
3884 case FF_PROFILE_AAC_HE_V2:
3885 param_write_string(pb, "FourCC", "AACP");
3887 case FF_PROFILE_AAC_HE:
3888 param_write_string(pb, "FourCC", "AACH");
3891 param_write_string(pb, "FourCC", "AACL");
3893 } else if (track->par->codec_id == AV_CODEC_ID_WMAPRO) {
3894 param_write_string(pb, "FourCC", "WMAP");
3896 param_write_hex(pb, "CodecPrivateData", track->par->extradata,
3897 track->par->extradata_size);
3898 param_write_int(pb, "AudioTag", ff_codec_get_tag(ff_codec_wav_tags,
3899 track->par->codec_id));
3900 param_write_int(pb, "Channels", track->par->channels);
3901 param_write_int(pb, "SamplingRate", track->par->sample_rate);
3902 param_write_int(pb, "BitsPerSample", 16);
3903 param_write_int(pb, "PacketSize", track->par->block_align ?
3904 track->par->block_align : 4);
3906 avio_printf(pb, "</%s>\n", type);
3908 avio_printf(pb, "</switch>\n");
3909 avio_printf(pb, "</body>\n");
3910 avio_printf(pb, "</smil>\n");
3912 return update_size(pb, pos);
3915 static int mov_write_mfhd_tag(AVIOContext *pb, MOVMuxContext *mov)
3918 ffio_wfourcc(pb, "mfhd");
3920 avio_wb32(pb, mov->fragments);
3924 static uint32_t get_sample_flags(MOVTrack *track, MOVIentry *entry)
3926 return entry->flags & MOV_SYNC_SAMPLE ? MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO :
3927 (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC);
3930 static int mov_write_tfhd_tag(AVIOContext *pb, MOVMuxContext *mov,
3931 MOVTrack *track, int64_t moof_offset)
3933 int64_t pos = avio_tell(pb);
3934 uint32_t flags = MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
3935 MOV_TFHD_BASE_DATA_OFFSET;
3936 if (!track->entry) {
3937 flags |= MOV_TFHD_DURATION_IS_EMPTY;
3939 flags |= MOV_TFHD_DEFAULT_FLAGS;
3941 if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET)
3942 flags &= ~MOV_TFHD_BASE_DATA_OFFSET;
3943 if (mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) {
3944 flags &= ~MOV_TFHD_BASE_DATA_OFFSET;
3945 flags |= MOV_TFHD_DEFAULT_BASE_IS_MOOF;
3948 /* Don't set a default sample size, the silverlight player refuses
3949 * to play files with that set. Don't set a default sample duration,
3950 * WMP freaks out if it is set. Don't set a base data offset, PIFF
3951 * file format says it MUST NOT be set. */
3952 if (track->mode == MODE_ISM)
3953 flags &= ~(MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
3954 MOV_TFHD_BASE_DATA_OFFSET);
3956 avio_wb32(pb, 0); /* size placeholder */
3957 ffio_wfourcc(pb, "tfhd");
3958 avio_w8(pb, 0); /* version */
3959 avio_wb24(pb, flags);
3961 avio_wb32(pb, track->track_id); /* track-id */
3962 if (flags & MOV_TFHD_BASE_DATA_OFFSET)
3963 avio_wb64(pb, moof_offset);
3964 if (flags & MOV_TFHD_DEFAULT_DURATION) {
3965 track->default_duration = get_cluster_duration(track, 0);
3966 avio_wb32(pb, track->default_duration);
3968 if (flags & MOV_TFHD_DEFAULT_SIZE) {
3969 track->default_size = track->entry ? track->cluster[0].size : 1;
3970 avio_wb32(pb, track->default_size);
3972 track->default_size = -1;
3974 if (flags & MOV_TFHD_DEFAULT_FLAGS) {
3975 /* Set the default flags based on the second sample, if available.
3976 * If the first sample is different, that can be signaled via a separate field. */
3977 if (track->entry > 1)
3978 track->default_sample_flags = get_sample_flags(track, &track->cluster[1]);
3980 track->default_sample_flags =
3981 track->par->codec_type == AVMEDIA_TYPE_VIDEO ?
3982 (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC) :
3983 MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO;
3984 avio_wb32(pb, track->default_sample_flags);
3987 return update_size(pb, pos);
3990 static int mov_write_trun_tag(AVIOContext *pb, MOVMuxContext *mov,
3991 MOVTrack *track, int moof_size,
3994 int64_t pos = avio_tell(pb);
3995 uint32_t flags = MOV_TRUN_DATA_OFFSET;
3998 for (i = first; i < end; i++) {
3999 if (get_cluster_duration(track, i) != track->default_duration)
4000 flags |= MOV_TRUN_SAMPLE_DURATION;
4001 if (track->cluster[i].size != track->default_size)
4002 flags |= MOV_TRUN_SAMPLE_SIZE;
4003 if (i > first && get_sample_flags(track, &track->cluster[i]) != track->default_sample_flags)
4004 flags |= MOV_TRUN_SAMPLE_FLAGS;
4006 if (!(flags & MOV_TRUN_SAMPLE_FLAGS) && track->entry > 0 &&
4007 get_sample_flags(track, &track->cluster[0]) != track->default_sample_flags)
4008 flags |= MOV_TRUN_FIRST_SAMPLE_FLAGS;
4009 if (track->flags & MOV_TRACK_CTTS)
4010 flags |= MOV_TRUN_SAMPLE_CTS;
4012 avio_wb32(pb, 0); /* size placeholder */
4013 ffio_wfourcc(pb, "trun");
4014 avio_w8(pb, 0); /* version */
4015 avio_wb24(pb, flags);
4017 avio_wb32(pb, end - first); /* sample count */
4018 if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET &&
4019 !(mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) &&
4021 avio_wb32(pb, 0); /* Later tracks follow immediately after the previous one */
4023 avio_wb32(pb, moof_size + 8 + track->data_offset +
4024 track->cluster[first].pos); /* data offset */
4025 if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS)
4026 avio_wb32(pb, get_sample_flags(track, &track->cluster[first]));
4028 for (i = first; i < end; i++) {
4029 if (flags & MOV_TRUN_SAMPLE_DURATION)
4030 avio_wb32(pb, get_cluster_duration(track, i));
4031 if (flags & MOV_TRUN_SAMPLE_SIZE)
4032 avio_wb32(pb, track->cluster[i].size);
4033 if (flags & MOV_TRUN_SAMPLE_FLAGS)
4034 avio_wb32(pb, get_sample_flags(track, &track->cluster[i]));
4035 if (flags & MOV_TRUN_SAMPLE_CTS)
4036 avio_wb32(pb, track->cluster[i].cts);
4039 mov->first_trun = 0;
4040 return update_size(pb, pos);
4043 static int mov_write_tfxd_tag(AVIOContext *pb, MOVTrack *track)
4045 int64_t pos = avio_tell(pb);
4046 static const uint8_t uuid[] = {
4047 0x6d, 0x1d, 0x9b, 0x05, 0x42, 0xd5, 0x44, 0xe6,
4048 0x80, 0xe2, 0x14, 0x1d, 0xaf, 0xf7, 0x57, 0xb2
4051 avio_wb32(pb, 0); /* size placeholder */
4052 ffio_wfourcc(pb, "uuid");
4053 avio_write(pb, uuid, sizeof(uuid));
4056 avio_wb64(pb, track->start_dts + track->frag_start +
4057 track->cluster[0].cts);
4058 avio_wb64(pb, track->end_pts -
4059 (track->cluster[0].dts + track->cluster[0].cts));
4061 return update_size(pb, pos);
4064 static int mov_write_tfrf_tag(AVIOContext *pb, MOVMuxContext *mov,
4065 MOVTrack *track, int entry)
4067 int n = track->nb_frag_info - 1 - entry, i;
4068 int size = 8 + 16 + 4 + 1 + 16*n;
4069 static const uint8_t uuid[] = {
4070 0xd4, 0x80, 0x7e, 0xf2, 0xca, 0x39, 0x46, 0x95,
4071 0x8e, 0x54, 0x26, 0xcb, 0x9e, 0x46, 0xa7, 0x9f
4077 avio_seek(pb, track->frag_info[entry].tfrf_offset, SEEK_SET);
4078 avio_wb32(pb, size);
4079 ffio_wfourcc(pb, "uuid");
4080 avio_write(pb, uuid, sizeof(uuid));
4084 for (i = 0; i < n; i++) {
4085 int index = entry + 1 + i;
4086 avio_wb64(pb, track->frag_info[index].time);
4087 avio_wb64(pb, track->frag_info[index].duration);
4089 if (n < mov->ism_lookahead) {
4090 int free_size = 16 * (mov->ism_lookahead - n);
4091 avio_wb32(pb, free_size);
4092 ffio_wfourcc(pb, "free");
4093 ffio_fill(pb, 0, free_size - 8);
4099 static int mov_write_tfrf_tags(AVIOContext *pb, MOVMuxContext *mov,
4102 int64_t pos = avio_tell(pb);
4104 for (i = 0; i < mov->ism_lookahead; i++) {
4105 /* Update the tfrf tag for the last ism_lookahead fragments,
4106 * nb_frag_info - 1 is the next fragment to be written. */
4107 mov_write_tfrf_tag(pb, mov, track, track->nb_frag_info - 2 - i);
4109 avio_seek(pb, pos, SEEK_SET);
4113 static int mov_add_tfra_entries(AVIOContext *pb, MOVMuxContext *mov, int tracks,
4117 for (i = 0; i < mov->nb_streams; i++) {
4118 MOVTrack *track = &mov->tracks[i];
4119 MOVFragmentInfo *info;
4120 if ((tracks >= 0 && i != tracks) || !track->entry)
4122 track->nb_frag_info++;
4123 if (track->nb_frag_info >= track->frag_info_capacity) {
4124 unsigned new_capacity = track->nb_frag_info + MOV_FRAG_INFO_ALLOC_INCREMENT;
4125 if (av_reallocp_array(&track->frag_info,
4127 sizeof(*track->frag_info)))
4128 return AVERROR(ENOMEM);
4129 track->frag_info_capacity = new_capacity;
4131 info = &track->frag_info[track->nb_frag_info - 1];
4132 info->offset = avio_tell(pb);
4134 // Try to recreate the original pts for the first packet
4135 // from the fields we have stored
4136 info->time = track->start_dts + track->frag_start +
4137 track->cluster[0].cts;
4138 info->duration = track->end_pts -
4139 (track->cluster[0].dts + track->cluster[0].cts);
4140 // If the pts is less than zero, we will have trimmed
4141 // away parts of the media track using an edit list,
4142 // and the corresponding start presentation time is zero.
4143 if (info->time < 0) {
4144 info->duration += info->time;
4147 info->tfrf_offset = 0;
4148 mov_write_tfrf_tags(pb, mov, track);
4153 static void mov_prune_frag_info(MOVMuxContext *mov, int tracks, int max)
4156 for (i = 0; i < mov->nb_streams; i++) {
4157 MOVTrack *track = &mov->tracks[i];
4158 if ((tracks >= 0 && i != tracks) || !track->entry)
4160 if (track->nb_frag_info > max) {
4161 memmove(track->frag_info, track->frag_info + (track->nb_frag_info - max), max * sizeof(*track->frag_info));
4162 track->nb_frag_info = max;
4167 static int mov_write_tfdt_tag(AVIOContext *pb, MOVTrack *track)
4169 int64_t pos = avio_tell(pb);
4171 avio_wb32(pb, 0); /* size */
4172 ffio_wfourcc(pb, "tfdt");
4173 avio_w8(pb, 1); /* version */
4175 avio_wb64(pb, track->frag_start);
4176 return update_size(pb, pos);
4179 static int mov_write_traf_tag(AVIOContext *pb, MOVMuxContext *mov,
4180 MOVTrack *track, int64_t moof_offset,
4183 int64_t pos = avio_tell(pb);
4185 avio_wb32(pb, 0); /* size placeholder */
4186 ffio_wfourcc(pb, "traf");
4188 mov_write_tfhd_tag(pb, mov, track, moof_offset);
4189 if (mov->mode != MODE_ISM)
4190 mov_write_tfdt_tag(pb, track);
4191 for (i = 1; i < track->entry; i++) {
4192 if (track->cluster[i].pos != track->cluster[i - 1].pos + track->cluster[i - 1].size) {
4193 mov_write_trun_tag(pb, mov, track, moof_size, start, i);
4197 mov_write_trun_tag(pb, mov, track, moof_size, start, track->entry);
4198 if (mov->mode == MODE_ISM) {
4199 mov_write_tfxd_tag(pb, track);
4201 if (mov->ism_lookahead) {
4202 int i, size = 16 + 4 + 1 + 16 * mov->ism_lookahead;
4204 if (track->nb_frag_info > 0) {
4205 MOVFragmentInfo *info = &track->frag_info[track->nb_frag_info - 1];
4206 if (!info->tfrf_offset)
4207 info->tfrf_offset = avio_tell(pb);
4209 avio_wb32(pb, 8 + size);
4210 ffio_wfourcc(pb, "free");
4211 for (i = 0; i < size; i++)
4216 return update_size(pb, pos);
4219 static int mov_write_moof_tag_internal(AVIOContext *pb, MOVMuxContext *mov,
4220 int tracks, int moof_size)
4222 int64_t pos = avio_tell(pb);
4225 avio_wb32(pb, 0); /* size placeholder */
4226 ffio_wfourcc(pb, "moof");
4227 mov->first_trun = 1;
4229 mov_write_mfhd_tag(pb, mov);
4230 for (i = 0; i < mov->nb_streams; i++) {
4231 MOVTrack *track = &mov->tracks[i];
4232 if (tracks >= 0 && i != tracks)
4236 mov_write_traf_tag(pb, mov, track, pos, moof_size);
4239 return update_size(pb, pos);
4242 static int mov_write_sidx_tag(AVIOContext *pb,
4243 MOVTrack *track, int ref_size, int total_sidx_size)
4245 int64_t pos = avio_tell(pb), offset_pos, end_pos;
4246 int64_t presentation_time, duration, offset;
4247 int starts_with_SAP, i, entries;
4251 presentation_time = track->start_dts + track->frag_start +
4252 track->cluster[0].cts;
4253 duration = track->end_pts -
4254 (track->cluster[0].dts + track->cluster[0].cts);
4255 starts_with_SAP = track->cluster[0].flags & MOV_SYNC_SAMPLE;
4257 // pts<0 should be cut away using edts
4258 if (presentation_time < 0) {
4259 duration += presentation_time;
4260 presentation_time = 0;
4263 entries = track->nb_frag_info;
4266 presentation_time = track->frag_info[0].time;
4269 avio_wb32(pb, 0); /* size */
4270 ffio_wfourcc(pb, "sidx");
4271 avio_w8(pb, 1); /* version */
4273 avio_wb32(pb, track->track_id); /* reference_ID */
4274 avio_wb32(pb, track->timescale); /* timescale */
4275 avio_wb64(pb, presentation_time); /* earliest_presentation_time */
4276 offset_pos = avio_tell(pb);
4277 avio_wb64(pb, 0); /* first_offset (offset to referenced moof) */
4278 avio_wb16(pb, 0); /* reserved */
4280 avio_wb16(pb, entries); /* reference_count */
4281 for (i = 0; i < entries; i++) {
4282 if (!track->entry) {
4283 if (i > 1 && track->frag_info[i].offset != track->frag_info[i - 1].offset + track->frag_info[i - 1].size) {
4284 av_log(NULL, AV_LOG_ERROR, "Non-consecutive fragments, writing incorrect sidx\n");
4286 duration = track->frag_info[i].duration;
4287 ref_size = track->frag_info[i].size;
4288 starts_with_SAP = 1;
4290 avio_wb32(pb, (0 << 31) | (ref_size & 0x7fffffff)); /* reference_type (0 = media) | referenced_size */
4291 avio_wb32(pb, duration); /* subsegment_duration */
4292 avio_wb32(pb, (starts_with_SAP << 31) | (0 << 28) | 0); /* starts_with_SAP | SAP_type | SAP_delta_time */
4295 end_pos = avio_tell(pb);
4296 offset = pos + total_sidx_size - end_pos;
4297 avio_seek(pb, offset_pos, SEEK_SET);
4298 avio_wb64(pb, offset);
4299 avio_seek(pb, end_pos, SEEK_SET);
4300 return update_size(pb, pos);
4303 static int mov_write_sidx_tags(AVIOContext *pb, MOVMuxContext *mov,
4304 int tracks, int ref_size)
4307 AVIOContext *avio_buf;
4309 for (round = 0; round < 2; round++) {
4310 // First run one round to calculate the total size of all
4312 // This would be much simpler if we'd only write one sidx
4313 // atom, for the first track in the moof.
4315 if ((ret = ffio_open_null_buf(&avio_buf)) < 0)
4320 for (i = 0; i < mov->nb_streams; i++) {
4321 MOVTrack *track = &mov->tracks[i];
4322 if (tracks >= 0 && i != tracks)
4324 // When writing a sidx for the full file, entry is 0, but
4325 // we want to include all tracks. ref_size is 0 in this case,
4326 // since we read it from frag_info instead.
4327 if (!track->entry && ref_size > 0)
4329 total_size -= mov_write_sidx_tag(avio_buf, track, ref_size,
4333 total_size = ffio_close_null_buf(avio_buf);
4338 static int mov_write_moof_tag(AVIOContext *pb, MOVMuxContext *mov, int tracks,
4341 AVIOContext *avio_buf;
4344 if ((ret = ffio_open_null_buf(&avio_buf)) < 0)
4346 mov_write_moof_tag_internal(avio_buf, mov, tracks, 0);
4347 moof_size = ffio_close_null_buf(avio_buf);
4349 if (mov->flags & FF_MOV_FLAG_DASH && !(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX))
4350 mov_write_sidx_tags(pb, mov, tracks, moof_size + 8 + mdat_size);
4352 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX ||
4353 !(mov->flags & FF_MOV_FLAG_SKIP_TRAILER) ||
4354 mov->ism_lookahead) {
4355 if ((ret = mov_add_tfra_entries(pb, mov, tracks, moof_size + 8 + mdat_size)) < 0)
4357 if (!(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) &&
4358 mov->flags & FF_MOV_FLAG_SKIP_TRAILER) {
4359 mov_prune_frag_info(mov, tracks, mov->ism_lookahead + 1);
4363 return mov_write_moof_tag_internal(pb, mov, tracks, moof_size);
4366 static int mov_write_tfra_tag(AVIOContext *pb, MOVTrack *track)
4368 int64_t pos = avio_tell(pb);
4371 avio_wb32(pb, 0); /* size placeholder */
4372 ffio_wfourcc(pb, "tfra");
4373 avio_w8(pb, 1); /* version */
4376 avio_wb32(pb, track->track_id);
4377 avio_wb32(pb, 0); /* length of traf/trun/sample num */
4378 avio_wb32(pb, track->nb_frag_info);
4379 for (i = 0; i < track->nb_frag_info; i++) {
4380 avio_wb64(pb, track->frag_info[i].time);
4381 avio_wb64(pb, track->frag_info[i].offset + track->data_offset);
4382 avio_w8(pb, 1); /* traf number */
4383 avio_w8(pb, 1); /* trun number */
4384 avio_w8(pb, 1); /* sample number */
4387 return update_size(pb, pos);
4390 static int mov_write_mfra_tag(AVIOContext *pb, MOVMuxContext *mov)
4392 int64_t pos = avio_tell(pb);
4395 avio_wb32(pb, 0); /* size placeholder */
4396 ffio_wfourcc(pb, "mfra");
4397 /* An empty mfra atom is enough to indicate to the publishing point that
4398 * the stream has ended. */
4399 if (mov->flags & FF_MOV_FLAG_ISML)
4400 return update_size(pb, pos);
4402 for (i = 0; i < mov->nb_streams; i++) {
4403 MOVTrack *track = &mov->tracks[i];
4404 if (track->nb_frag_info)
4405 mov_write_tfra_tag(pb, track);
4409 ffio_wfourcc(pb, "mfro");
4410 avio_wb32(pb, 0); /* version + flags */
4411 avio_wb32(pb, avio_tell(pb) + 4 - pos);
4413 return update_size(pb, pos);
4416 static int mov_write_mdat_tag(AVIOContext *pb, MOVMuxContext *mov)
4418 avio_wb32(pb, 8); // placeholder for extended size field (64 bit)
4419 ffio_wfourcc(pb, mov->mode == MODE_MOV ? "wide" : "free");
4421 mov->mdat_pos = avio_tell(pb);
4422 avio_wb32(pb, 0); /* size placeholder*/
4423 ffio_wfourcc(pb, "mdat");
4427 /* TODO: This needs to be more general */
4428 static int mov_write_ftyp_tag(AVIOContext *pb, AVFormatContext *s)
4430 MOVMuxContext *mov = s->priv_data;
4431 int64_t pos = avio_tell(pb);
4432 int has_h264 = 0, has_video = 0;
4436 for (i = 0; i < s->nb_streams; i++) {
4437 AVStream *st = s->streams[i];
4438 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
4440 if (st->codecpar->codec_id == AV_CODEC_ID_H264)
4444 avio_wb32(pb, 0); /* size */
4445 ffio_wfourcc(pb, "ftyp");
4447 if (mov->major_brand && strlen(mov->major_brand) >= 4)
4448 ffio_wfourcc(pb, mov->major_brand);
4449 else if (mov->mode == MODE_3GP) {
4450 ffio_wfourcc(pb, has_h264 ? "3gp6" : "3gp4");
4451 minor = has_h264 ? 0x100 : 0x200;
4452 } else if (mov->mode & MODE_3G2) {
4453 ffio_wfourcc(pb, has_h264 ? "3g2b" : "3g2a");
4454 minor = has_h264 ? 0x20000 : 0x10000;
4455 } else if (mov->mode == MODE_PSP)
4456 ffio_wfourcc(pb, "MSNV");
4457 else if (mov->mode == MODE_MP4 && mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)
4458 ffio_wfourcc(pb, "iso5"); // Required when using default-base-is-moof
4459 else if (mov->mode == MODE_MP4)
4460 ffio_wfourcc(pb, "isom");
4461 else if (mov->mode == MODE_IPOD)
4462 ffio_wfourcc(pb, has_video ? "M4V ":"M4A ");
4463 else if (mov->mode == MODE_ISM)
4464 ffio_wfourcc(pb, "isml");
4465 else if (mov->mode == MODE_F4V)
4466 ffio_wfourcc(pb, "f4v ");
4468 ffio_wfourcc(pb, "qt ");
4470 avio_wb32(pb, minor);
4472 if (mov->mode == MODE_MOV)
4473 ffio_wfourcc(pb, "qt ");
4474 else if (mov->mode == MODE_ISM) {
4475 ffio_wfourcc(pb, "piff");
4476 } else if (!(mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)) {
4477 ffio_wfourcc(pb, "isom");
4478 ffio_wfourcc(pb, "iso2");
4480 ffio_wfourcc(pb, "avc1");
4483 // We add tfdt atoms when fragmenting, signal this with the iso6 compatible
4484 // brand. This is compatible with users that don't understand tfdt.
4485 if (mov->flags & FF_MOV_FLAG_FRAGMENT && mov->mode != MODE_ISM)
4486 ffio_wfourcc(pb, "iso6");
4488 if (mov->mode == MODE_3GP)
4489 ffio_wfourcc(pb, has_h264 ? "3gp6":"3gp4");
4490 else if (mov->mode & MODE_3G2)
4491 ffio_wfourcc(pb, has_h264 ? "3g2b":"3g2a");
4492 else if (mov->mode == MODE_PSP)
4493 ffio_wfourcc(pb, "MSNV");
4494 else if (mov->mode == MODE_MP4)
4495 ffio_wfourcc(pb, "mp41");
4497 if (mov->flags & FF_MOV_FLAG_DASH && mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
4498 ffio_wfourcc(pb, "dash");
4500 return update_size(pb, pos);
4503 static int mov_write_uuidprof_tag(AVIOContext *pb, AVFormatContext *s)
4505 AVStream *video_st = s->streams[0];
4506 AVCodecParameters *video_par = s->streams[0]->codecpar;
4507 AVCodecParameters *audio_par = s->streams[1]->codecpar;
4508 int audio_rate = audio_par->sample_rate;
4509 int64_t frame_rate = video_st->avg_frame_rate.den ?
4510 (video_st->avg_frame_rate.num * 0x10000LL) / video_st->avg_frame_rate.den :
4512 int audio_kbitrate = audio_par->bit_rate / 1000;
4513 int video_kbitrate = FFMIN(video_par->bit_rate / 1000, 800 - audio_kbitrate);
4515 if (frame_rate < 0 || frame_rate > INT32_MAX) {
4516 av_log(s, AV_LOG_ERROR, "Frame rate %f outside supported range\n", frame_rate / (double)0x10000);
4517 return AVERROR(EINVAL);
4520 avio_wb32(pb, 0x94); /* size */
4521 ffio_wfourcc(pb, "uuid");
4522 ffio_wfourcc(pb, "PROF");
4524 avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
4525 avio_wb32(pb, 0xbb88695c);
4526 avio_wb32(pb, 0xfac9c740);
4528 avio_wb32(pb, 0x0); /* ? */
4529 avio_wb32(pb, 0x3); /* 3 sections ? */
4531 avio_wb32(pb, 0x14); /* size */
4532 ffio_wfourcc(pb, "FPRF");
4533 avio_wb32(pb, 0x0); /* ? */
4534 avio_wb32(pb, 0x0); /* ? */
4535 avio_wb32(pb, 0x0); /* ? */
4537 avio_wb32(pb, 0x2c); /* size */
4538 ffio_wfourcc(pb, "APRF"); /* audio */
4540 avio_wb32(pb, 0x2); /* TrackID */
4541 ffio_wfourcc(pb, "mp4a");
4542 avio_wb32(pb, 0x20f);
4544 avio_wb32(pb, audio_kbitrate);
4545 avio_wb32(pb, audio_kbitrate);
4546 avio_wb32(pb, audio_rate);
4547 avio_wb32(pb, audio_par->channels);
4549 avio_wb32(pb, 0x34); /* size */
4550 ffio_wfourcc(pb, "VPRF"); /* video */
4552 avio_wb32(pb, 0x1); /* TrackID */
4553 if (video_par->codec_id == AV_CODEC_ID_H264) {
4554 ffio_wfourcc(pb, "avc1");
4555 avio_wb16(pb, 0x014D);
4556 avio_wb16(pb, 0x0015);
4558 ffio_wfourcc(pb, "mp4v");
4559 avio_wb16(pb, 0x0000);
4560 avio_wb16(pb, 0x0103);
4563 avio_wb32(pb, video_kbitrate);
4564 avio_wb32(pb, video_kbitrate);
4565 avio_wb32(pb, frame_rate);
4566 avio_wb32(pb, frame_rate);
4567 avio_wb16(pb, video_par->width);
4568 avio_wb16(pb, video_par->height);
4569 avio_wb32(pb, 0x010001); /* ? */
4574 static int mov_write_identification(AVIOContext *pb, AVFormatContext *s)
4576 MOVMuxContext *mov = s->priv_data;
4579 mov_write_ftyp_tag(pb,s);
4580 if (mov->mode == MODE_PSP) {
4581 int video_streams_nb = 0, audio_streams_nb = 0, other_streams_nb = 0;
4582 for (i = 0; i < s->nb_streams; i++) {
4583 AVStream *st = s->streams[i];
4584 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
4586 else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
4592 if (video_streams_nb != 1 || audio_streams_nb != 1 || other_streams_nb) {
4593 av_log(s, AV_LOG_ERROR, "PSP mode need one video and one audio stream\n");
4594 return AVERROR(EINVAL);
4596 return mov_write_uuidprof_tag(pb, s);
4601 static int mov_parse_mpeg2_frame(AVPacket *pkt, uint32_t *flags)
4604 int i, closed_gop = 0;
4606 for (i = 0; i < pkt->size - 4; i++) {
4607 c = (c << 8) + pkt->data[i];
4608 if (c == 0x1b8) { // gop
4609 closed_gop = pkt->data[i + 4] >> 6 & 0x01;
4610 } else if (c == 0x100) { // pic
4611 int temp_ref = (pkt->data[i + 1] << 2) | (pkt->data[i + 2] >> 6);
4612 if (!temp_ref || closed_gop) // I picture is not reordered
4613 *flags = MOV_SYNC_SAMPLE;
4615 *flags = MOV_PARTIAL_SYNC_SAMPLE;
4622 static void mov_parse_vc1_frame(AVPacket *pkt, MOVTrack *trk)
4624 const uint8_t *start, *next, *end = pkt->data + pkt->size;
4625 int seq = 0, entry = 0;
4626 int key = pkt->flags & AV_PKT_FLAG_KEY;
4627 start = find_next_marker(pkt->data, end);
4628 for (next = start; next < end; start = next) {
4629 next = find_next_marker(start + 4, end);
4630 switch (AV_RB32(start)) {
4631 case VC1_CODE_SEQHDR:
4634 case VC1_CODE_ENTRYPOINT:
4637 case VC1_CODE_SLICE:
4638 trk->vc1_info.slices = 1;
4642 if (!trk->entry && trk->vc1_info.first_packet_seen)
4643 trk->vc1_info.first_frag_written = 1;
4644 if (!trk->entry && !trk->vc1_info.first_frag_written) {
4645 /* First packet in first fragment */
4646 trk->vc1_info.first_packet_seq = seq;
4647 trk->vc1_info.first_packet_entry = entry;
4648 trk->vc1_info.first_packet_seen = 1;
4649 } else if ((seq && !trk->vc1_info.packet_seq) ||
4650 (entry && !trk->vc1_info.packet_entry)) {
4652 for (i = 0; i < trk->entry; i++)
4653 trk->cluster[i].flags &= ~MOV_SYNC_SAMPLE;
4654 trk->has_keyframes = 0;
4656 trk->vc1_info.packet_seq = 1;
4658 trk->vc1_info.packet_entry = 1;
4659 if (!trk->vc1_info.first_frag_written) {
4660 /* First fragment */
4661 if ((!seq || trk->vc1_info.first_packet_seq) &&
4662 (!entry || trk->vc1_info.first_packet_entry)) {
4663 /* First packet had the same headers as this one, readd the
4664 * sync sample flag. */
4665 trk->cluster[0].flags |= MOV_SYNC_SAMPLE;
4666 trk->has_keyframes = 1;
4670 if (trk->vc1_info.packet_seq && trk->vc1_info.packet_entry)
4672 else if (trk->vc1_info.packet_seq)
4674 else if (trk->vc1_info.packet_entry)
4677 trk->cluster[trk->entry].flags |= MOV_SYNC_SAMPLE;
4678 trk->has_keyframes++;
4682 static int mov_flush_fragment_interleaving(AVFormatContext *s, MOVTrack *track)
4684 MOVMuxContext *mov = s->priv_data;
4689 if (!track->mdat_buf)
4691 if (!mov->mdat_buf) {
4692 if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0)
4695 buf_size = avio_close_dyn_buf(track->mdat_buf, &buf);
4696 track->mdat_buf = NULL;
4698 offset = avio_tell(mov->mdat_buf);
4699 avio_write(mov->mdat_buf, buf, buf_size);
4702 for (i = track->entries_flushed; i < track->entry; i++)
4703 track->cluster[i].pos += offset;
4704 track->entries_flushed = track->entry;
4708 static int mov_flush_fragment(AVFormatContext *s, int force)
4710 MOVMuxContext *mov = s->priv_data;
4711 int i, first_track = -1;
4712 int64_t mdat_size = 0;
4714 int has_video = 0, starts_with_key = 0, first_video_track = 1;
4716 if (!(mov->flags & FF_MOV_FLAG_FRAGMENT))
4719 // Try to fill in the duration of the last packet in each stream
4720 // from queued packets in the interleave queues. If the flushing
4721 // of fragments was triggered automatically by an AVPacket, we
4722 // already have reliable info for the end of that track, but other
4723 // tracks may need to be filled in.
4724 for (i = 0; i < s->nb_streams; i++) {
4725 MOVTrack *track = &mov->tracks[i];
4726 if (!track->end_reliable) {
4728 if (!ff_interleaved_peek(s, i, &pkt, 1)) {
4729 track->track_duration = pkt.dts - track->start_dts;
4730 if (pkt.pts != AV_NOPTS_VALUE)
4731 track->end_pts = pkt.pts;
4733 track->end_pts = pkt.dts;
4738 for (i = 0; i < mov->nb_streams; i++) {
4739 MOVTrack *track = &mov->tracks[i];
4740 if (track->entry <= 1)
4742 // Sample durations are calculated as the diff of dts values,
4743 // but for the last sample in a fragment, we don't know the dts
4744 // of the first sample in the next fragment, so we have to rely
4745 // on what was set as duration in the AVPacket. Not all callers
4746 // set this though, so we might want to replace it with an
4747 // estimate if it currently is zero.
4748 if (get_cluster_duration(track, track->entry - 1) != 0)
4750 // Use the duration (i.e. dts diff) of the second last sample for
4751 // the last one. This is a wild guess (and fatal if it turns out
4752 // to be too long), but probably the best we can do - having a zero
4753 // duration is bad as well.
4754 track->track_duration += get_cluster_duration(track, track->entry - 2);
4755 track->end_pts += get_cluster_duration(track, track->entry - 2);
4756 if (!mov->missing_duration_warned) {
4757 av_log(s, AV_LOG_WARNING,
4758 "Estimating the duration of the last packet in a "
4759 "fragment, consider setting the duration field in "
4760 "AVPacket instead.\n");
4761 mov->missing_duration_warned = 1;
4765 if (!mov->moov_written) {
4766 int64_t pos = avio_tell(s->pb);
4768 int buf_size, moov_size;
4770 for (i = 0; i < mov->nb_streams; i++)
4771 if (!mov->tracks[i].entry)
4773 /* Don't write the initial moov unless all tracks have data */
4774 if (i < mov->nb_streams && !force)
4777 moov_size = get_moov_size(s);
4778 for (i = 0; i < mov->nb_streams; i++)
4779 mov->tracks[i].data_offset = pos + moov_size + 8;
4781 avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_HEADER);
4782 if (mov->flags & FF_MOV_FLAG_DELAY_MOOV)
4783 mov_write_identification(s->pb, s);
4784 if ((ret = mov_write_moov_tag(s->pb, mov, s)) < 0)
4787 if (mov->flags & FF_MOV_FLAG_DELAY_MOOV) {
4788 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
4789 mov->reserved_header_pos = avio_tell(s->pb);
4791 mov->moov_written = 1;
4795 buf_size = avio_close_dyn_buf(mov->mdat_buf, &buf);
4796 mov->mdat_buf = NULL;
4797 avio_wb32(s->pb, buf_size + 8);
4798 ffio_wfourcc(s->pb, "mdat");
4799 avio_write(s->pb, buf, buf_size);
4802 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
4803 mov->reserved_header_pos = avio_tell(s->pb);
4805 mov->moov_written = 1;
4807 for (i = 0; i < mov->nb_streams; i++) {
4808 if (mov->tracks[i].entry)
4809 mov->tracks[i].frag_start += mov->tracks[i].start_dts +
4810 mov->tracks[i].track_duration -
4811 mov->tracks[i].cluster[0].dts;
4812 mov->tracks[i].entry = 0;
4813 mov->tracks[i].end_reliable = 0;
4819 if (mov->frag_interleave) {
4820 for (i = 0; i < mov->nb_streams; i++) {
4821 MOVTrack *track = &mov->tracks[i];
4823 if ((ret = mov_flush_fragment_interleaving(s, track)) < 0)
4829 mdat_size = avio_tell(mov->mdat_buf);
4832 for (i = 0; i < mov->nb_streams; i++) {
4833 MOVTrack *track = &mov->tracks[i];
4834 if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF || mov->frag_interleave)
4835 track->data_offset = 0;
4837 track->data_offset = mdat_size;
4838 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
4840 if (first_video_track) {
4842 starts_with_key = track->cluster[0].flags & MOV_SYNC_SAMPLE;
4843 first_video_track = 0;
4848 if (track->mdat_buf)
4849 mdat_size += avio_tell(track->mdat_buf);
4850 if (first_track < 0)
4857 avio_write_marker(s->pb,
4858 av_rescale(mov->tracks[first_track].cluster[0].dts, AV_TIME_BASE, mov->tracks[first_track].timescale),
4859 (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);
4861 for (i = 0; i < mov->nb_streams; i++) {
4862 MOVTrack *track = &mov->tracks[i];
4863 int buf_size, write_moof = 1, moof_tracks = -1;
4865 int64_t duration = 0;
4868 duration = track->start_dts + track->track_duration -
4869 track->cluster[0].dts;
4870 if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF) {
4871 if (!track->mdat_buf)
4873 mdat_size = avio_tell(track->mdat_buf);
4876 write_moof = i == first_track;
4882 mov_write_moof_tag(s->pb, mov, moof_tracks, mdat_size);
4885 avio_wb32(s->pb, mdat_size + 8);
4886 ffio_wfourcc(s->pb, "mdat");
4890 track->frag_start += duration;
4892 track->entries_flushed = 0;
4893 track->end_reliable = 0;
4894 if (!mov->frag_interleave) {
4895 if (!track->mdat_buf)
4897 buf_size = avio_close_dyn_buf(track->mdat_buf, &buf);
4898 track->mdat_buf = NULL;
4902 buf_size = avio_close_dyn_buf(mov->mdat_buf, &buf);
4903 mov->mdat_buf = NULL;
4906 avio_write(s->pb, buf, buf_size);
4916 static int mov_auto_flush_fragment(AVFormatContext *s, int force)
4918 MOVMuxContext *mov = s->priv_data;
4919 int had_moov = mov->moov_written;
4920 int ret = mov_flush_fragment(s, force);
4923 // If using delay_moov, the first flush only wrote the moov,
4924 // not the actual moof+mdat pair, thus flush once again.
4925 if (!had_moov && mov->flags & FF_MOV_FLAG_DELAY_MOOV)
4926 ret = mov_flush_fragment(s, force);
4930 static int check_pkt(AVFormatContext *s, AVPacket *pkt)
4932 MOVMuxContext *mov = s->priv_data;
4933 MOVTrack *trk = &mov->tracks[pkt->stream_index];
4938 ref = trk->cluster[trk->entry - 1].dts;
4939 } else if ( trk->start_dts != AV_NOPTS_VALUE
4940 && !trk->frag_discont) {
4941 ref = trk->start_dts + trk->track_duration;
4943 ref = pkt->dts; // Skip tests for the first packet
4945 duration = pkt->dts - ref;
4946 if (pkt->dts < ref || duration >= INT_MAX) {
4947 av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" / timestamp: %"PRId64" is out of range for mov/mp4 format\n",
4952 pkt->pts = AV_NOPTS_VALUE;
4955 if (pkt->duration < 0 || pkt->duration > INT_MAX) {
4956 av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" is invalid\n", pkt->duration);
4957 return AVERROR(EINVAL);
4962 int ff_mov_write_packet(AVFormatContext *s, AVPacket *pkt)
4964 MOVMuxContext *mov = s->priv_data;
4965 AVIOContext *pb = s->pb;
4966 MOVTrack *trk = &mov->tracks[pkt->stream_index];
4967 AVCodecParameters *par = trk->par;
4968 unsigned int samples_in_chunk = 0;
4969 int size = pkt->size, ret = 0;
4970 uint8_t *reformatted_data = NULL;
4972 ret = check_pkt(s, pkt);
4976 if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
4978 if (mov->moov_written || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
4979 if (mov->frag_interleave && mov->fragments > 0) {
4980 if (trk->entry - trk->entries_flushed >= mov->frag_interleave) {
4981 if ((ret = mov_flush_fragment_interleaving(s, trk)) < 0)
4986 if (!trk->mdat_buf) {
4987 if ((ret = avio_open_dyn_buf(&trk->mdat_buf)) < 0)
4992 if (!mov->mdat_buf) {
4993 if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0)
5000 if (par->codec_id == AV_CODEC_ID_AMR_NB) {
5001 /* We must find out how many AMR blocks there are in one packet */
5002 static const uint16_t packed_size[16] =
5003 {13, 14, 16, 18, 20, 21, 27, 32, 6, 0, 0, 0, 0, 0, 0, 1};
5006 while (len < size && samples_in_chunk < 100) {
5007 len += packed_size[(pkt->data[len] >> 3) & 0x0F];
5010 if (samples_in_chunk > 1) {
5011 av_log(s, AV_LOG_ERROR, "fatal error, input is not a single packet, implement a AVParser for it\n");
5014 } else if (par->codec_id == AV_CODEC_ID_ADPCM_MS ||
5015 par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) {
5016 samples_in_chunk = trk->par->frame_size;
5017 } else if (trk->sample_size)
5018 samples_in_chunk = size / trk->sample_size;
5020 samples_in_chunk = 1;
5022 /* copy extradata if it exists */
5023 if (trk->vos_len == 0 && par->extradata_size > 0 &&
5024 !TAG_IS_AVCI(trk->tag) &&
5025 (par->codec_id != AV_CODEC_ID_DNXHD)) {
5026 trk->vos_len = par->extradata_size;
5027 trk->vos_data = av_malloc(trk->vos_len);
5028 if (!trk->vos_data) {
5029 ret = AVERROR(ENOMEM);
5032 memcpy(trk->vos_data, par->extradata, trk->vos_len);
5035 if (par->codec_id == AV_CODEC_ID_AAC && pkt->size > 2 &&
5036 (AV_RB16(pkt->data) & 0xfff0) == 0xfff0) {
5037 if (!s->streams[pkt->stream_index]->nb_frames) {
5038 av_log(s, AV_LOG_ERROR, "Malformed AAC bitstream detected: "
5039 "use the audio bitstream filter 'aac_adtstoasc' to fix it "
5040 "('-bsf:a aac_adtstoasc' option with ffmpeg)\n");
5043 av_log(s, AV_LOG_WARNING, "aac bitstream error\n");
5045 if (par->codec_id == AV_CODEC_ID_H264 && trk->vos_len > 0 && *(uint8_t *)trk->vos_data != 1 && !TAG_IS_AVCI(trk->tag)) {
5046 /* from x264 or from bytestream H.264 */
5047 /* NAL reformatting needed */
5048 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
5049 ff_avc_parse_nal_units_buf(pkt->data, &reformatted_data,
5051 avio_write(pb, reformatted_data, size);
5053 if (trk->cenc.aes_ctr) {
5054 size = ff_mov_cenc_avc_parse_nal_units(&trk->cenc, pb, pkt->data, size);
5060 size = ff_avc_parse_nal_units(pb, pkt->data, pkt->size);
5063 } else if (par->codec_id == AV_CODEC_ID_HEVC && trk->vos_len > 6 &&
5064 (AV_RB24(trk->vos_data) == 1 || AV_RB32(trk->vos_data) == 1)) {
5065 /* extradata is Annex B, assume the bitstream is too and convert it */
5066 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
5067 ff_hevc_annexb2mp4_buf(pkt->data, &reformatted_data, &size, 0, NULL);
5068 avio_write(pb, reformatted_data, size);
5070 size = ff_hevc_annexb2mp4(pb, pkt->data, pkt->size, 0, NULL);
5072 #if CONFIG_AC3_PARSER
5073 } else if (par->codec_id == AV_CODEC_ID_EAC3) {
5074 size = handle_eac3(mov, pkt, trk);
5079 avio_write(pb, pkt->data, size);
5082 if (trk->cenc.aes_ctr) {
5083 if (par->codec_id == AV_CODEC_ID_H264 && par->extradata_size > 4) {
5084 int nal_size_length = (par->extradata[4] & 0x3) + 1;
5085 ret = ff_mov_cenc_avc_write_nal_units(s, &trk->cenc, nal_size_length, pb, pkt->data, size);
5087 ret = ff_mov_cenc_write_packet(&trk->cenc, pb, pkt->data, size);
5094 avio_write(pb, pkt->data, size);
5098 if ((par->codec_id == AV_CODEC_ID_DNXHD ||
5099 par->codec_id == AV_CODEC_ID_AC3) && !trk->vos_len) {
5100 /* copy frame to create needed atoms */
5101 trk->vos_len = size;
5102 trk->vos_data = av_malloc(size);
5103 if (!trk->vos_data) {
5104 ret = AVERROR(ENOMEM);
5107 memcpy(trk->vos_data, pkt->data, size);
5110 if (trk->entry >= trk->cluster_capacity) {
5111 unsigned new_capacity = 2 * (trk->entry + MOV_INDEX_CLUSTER_SIZE);
5112 if (av_reallocp_array(&trk->cluster, new_capacity,
5113 sizeof(*trk->cluster))) {
5114 ret = AVERROR(ENOMEM);
5117 trk->cluster_capacity = new_capacity;
5120 trk->cluster[trk->entry].pos = avio_tell(pb) - size;
5121 trk->cluster[trk->entry].samples_in_chunk = samples_in_chunk;
5122 trk->cluster[trk->entry].chunkNum = 0;
5123 trk->cluster[trk->entry].size = size;
5124 trk->cluster[trk->entry].entries = samples_in_chunk;
5125 trk->cluster[trk->entry].dts = pkt->dts;
5126 if (!trk->entry && trk->start_dts != AV_NOPTS_VALUE) {
5127 if (!trk->frag_discont) {
5128 /* First packet of a new fragment. We already wrote the duration
5129 * of the last packet of the previous fragment based on track_duration,
5130 * which might not exactly match our dts. Therefore adjust the dts
5131 * of this packet to be what the previous packets duration implies. */
5132 trk->cluster[trk->entry].dts = trk->start_dts + trk->track_duration;
5133 /* We also may have written the pts and the corresponding duration
5134 * in sidx/tfrf/tfxd tags; make sure the sidx pts and duration match up with
5135 * the next fragment. This means the cts of the first sample must
5136 * be the same in all fragments, unless end_pts was updated by
5137 * the packet causing the fragment to be written. */
5138 if ((mov->flags & FF_MOV_FLAG_DASH && !(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)) ||
5139 mov->mode == MODE_ISM)
5140 pkt->pts = pkt->dts + trk->end_pts - trk->cluster[trk->entry].dts;
5142 /* New fragment, but discontinuous from previous fragments.
5143 * Pretend the duration sum of the earlier fragments is
5144 * pkt->dts - trk->start_dts. */
5145 trk->frag_start = pkt->dts - trk->start_dts;
5146 trk->end_pts = AV_NOPTS_VALUE;
5147 trk->frag_discont = 0;
5151 if (!trk->entry && trk->start_dts == AV_NOPTS_VALUE && !mov->use_editlist &&
5152 s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO) {
5153 /* Not using edit lists and shifting the first track to start from zero.
5154 * If the other streams start from a later timestamp, we won't be able
5155 * to signal the difference in starting time without an edit list.
5156 * Thus move the timestamp for this first sample to 0, increasing
5157 * its duration instead. */
5158 trk->cluster[trk->entry].dts = trk->start_dts = 0;
5160 if (trk->start_dts == AV_NOPTS_VALUE) {
5161 trk->start_dts = pkt->dts;
5162 if (trk->frag_discont) {
5163 if (mov->use_editlist) {
5164 /* Pretend the whole stream started at pts=0, with earlier fragments
5165 * already written. If the stream started at pts=0, the duration sum
5166 * of earlier fragments would have been pkt->pts. */
5167 trk->frag_start = pkt->pts;
5168 trk->start_dts = pkt->dts - pkt->pts;
5170 /* Pretend the whole stream started at dts=0, with earlier fragments
5171 * already written, with a duration summing up to pkt->dts. */
5172 trk->frag_start = pkt->dts;
5175 trk->frag_discont = 0;
5176 } else if (pkt->dts && mov->moov_written)
5177 av_log(s, AV_LOG_WARNING,
5178 "Track %d starts with a nonzero dts %"PRId64", while the moov "
5179 "already has been written. Set the delay_moov flag to handle "
5181 pkt->stream_index, pkt->dts);
5183 trk->track_duration = pkt->dts - trk->start_dts + pkt->duration;
5184 trk->last_sample_is_subtitle_end = 0;
5186 if (pkt->pts == AV_NOPTS_VALUE) {
5187 av_log(s, AV_LOG_WARNING, "pts has no value\n");
5188 pkt->pts = pkt->dts;
5190 if (pkt->dts != pkt->pts)
5191 trk->flags |= MOV_TRACK_CTTS;
5192 trk->cluster[trk->entry].cts = pkt->pts - pkt->dts;
5193 trk->cluster[trk->entry].flags = 0;
5194 if (trk->start_cts == AV_NOPTS_VALUE)
5195 trk->start_cts = pkt->pts - pkt->dts;
5196 if (trk->end_pts == AV_NOPTS_VALUE)
5197 trk->end_pts = trk->cluster[trk->entry].dts +
5198 trk->cluster[trk->entry].cts + pkt->duration;
5200 trk->end_pts = FFMAX(trk->end_pts, trk->cluster[trk->entry].dts +
5201 trk->cluster[trk->entry].cts +
5204 if (par->codec_id == AV_CODEC_ID_VC1) {
5205 mov_parse_vc1_frame(pkt, trk);
5206 } else if (pkt->flags & AV_PKT_FLAG_KEY) {
5207 if (mov->mode == MODE_MOV && par->codec_id == AV_CODEC_ID_MPEG2VIDEO &&
5208 trk->entry > 0) { // force sync sample for the first key frame
5209 mov_parse_mpeg2_frame(pkt, &trk->cluster[trk->entry].flags);
5210 if (trk->cluster[trk->entry].flags & MOV_PARTIAL_SYNC_SAMPLE)
5211 trk->flags |= MOV_TRACK_STPS;
5213 trk->cluster[trk->entry].flags = MOV_SYNC_SAMPLE;
5215 if (trk->cluster[trk->entry].flags & MOV_SYNC_SAMPLE)
5216 trk->has_keyframes++;
5219 trk->sample_count += samples_in_chunk;
5220 mov->mdat_size += size;
5222 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams)
5223 ff_mov_add_hinted_packet(s, pkt, trk->hint_track, trk->entry,
5224 reformatted_data, size);
5229 av_free(reformatted_data);
5233 static int mov_write_single_packet(AVFormatContext *s, AVPacket *pkt)
5235 MOVMuxContext *mov = s->priv_data;
5236 MOVTrack *trk = &mov->tracks[pkt->stream_index];
5237 AVCodecParameters *par = trk->par;
5238 int64_t frag_duration = 0;
5239 int size = pkt->size;
5241 int ret = check_pkt(s, pkt);
5245 if (mov->flags & FF_MOV_FLAG_FRAG_DISCONT) {
5247 for (i = 0; i < s->nb_streams; i++)
5248 mov->tracks[i].frag_discont = 1;
5249 mov->flags &= ~FF_MOV_FLAG_FRAG_DISCONT;
5252 if (trk->par->codec_id == AV_CODEC_ID_MP4ALS ||
5253 trk->par->codec_id == AV_CODEC_ID_AAC ||
5254 trk->par->codec_id == AV_CODEC_ID_FLAC) {
5256 uint8_t *side = av_packet_get_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA, &side_size);
5257 if (side && side_size > 0 && (side_size != par->extradata_size || memcmp(side, par->extradata, side_size))) {
5258 void *newextra = av_mallocz(side_size + AV_INPUT_BUFFER_PADDING_SIZE);
5260 return AVERROR(ENOMEM);
5261 av_free(par->extradata);
5262 par->extradata = newextra;
5263 memcpy(par->extradata, side, side_size);
5264 par->extradata_size = side_size;
5265 if (!pkt->size) // Flush packet
5266 mov->need_rewrite_extradata = 1;
5271 if (trk->start_dts == AV_NOPTS_VALUE && trk->frag_discont) {
5272 trk->start_dts = pkt->dts;
5273 if (pkt->pts != AV_NOPTS_VALUE)
5274 trk->start_cts = pkt->pts - pkt->dts;
5279 return 0; /* Discard 0 sized packets */
5282 if (trk->entry && pkt->stream_index < s->nb_streams)
5283 frag_duration = av_rescale_q(pkt->dts - trk->cluster[0].dts,
5284 s->streams[pkt->stream_index]->time_base,
5286 if ((mov->max_fragment_duration &&
5287 frag_duration >= mov->max_fragment_duration) ||
5288 (mov->max_fragment_size && mov->mdat_size + size >= mov->max_fragment_size) ||
5289 (mov->flags & FF_MOV_FLAG_FRAG_KEYFRAME &&
5290 par->codec_type == AVMEDIA_TYPE_VIDEO &&
5291 trk->entry && pkt->flags & AV_PKT_FLAG_KEY)) {
5292 if (frag_duration >= mov->min_fragment_duration) {
5293 // Set the duration of this track to line up with the next
5294 // sample in this track. This avoids relying on AVPacket
5295 // duration, but only helps for this particular track, not
5296 // for the other ones that are flushed at the same time.
5297 trk->track_duration = pkt->dts - trk->start_dts;
5298 if (pkt->pts != AV_NOPTS_VALUE)
5299 trk->end_pts = pkt->pts;
5301 trk->end_pts = pkt->dts;
5302 trk->end_reliable = 1;
5303 mov_auto_flush_fragment(s, 0);
5307 return ff_mov_write_packet(s, pkt);
5310 static int mov_write_subtitle_end_packet(AVFormatContext *s,
5314 uint8_t data[2] = {0};
5317 av_init_packet(&end);
5318 end.size = sizeof(data);
5323 end.stream_index = stream_index;
5325 ret = mov_write_single_packet(s, &end);
5326 av_packet_unref(&end);
5331 static int mov_write_packet(AVFormatContext *s, AVPacket *pkt)
5334 mov_flush_fragment(s, 1);
5338 MOVMuxContext *mov = s->priv_data;
5339 MOVTrack *trk = &mov->tracks[pkt->stream_index];
5342 return mov_write_single_packet(s, pkt); /* Passthrough. */
5345 * Subtitles require special handling.
5347 * 1) For full complaince, every track must have a sample at
5348 * dts == 0, which is rarely true for subtitles. So, as soon
5349 * as we see any packet with dts > 0, write an empty subtitle
5350 * at dts == 0 for any subtitle track with no samples in it.
5352 * 2) For each subtitle track, check if the current packet's
5353 * dts is past the duration of the last subtitle sample. If
5354 * so, we now need to write an end sample for that subtitle.
5356 * This must be done conditionally to allow for subtitles that
5357 * immediately replace each other, in which case an end sample
5358 * is not needed, and is, in fact, actively harmful.
5360 * 3) See mov_write_trailer for how the final end sample is
5363 for (i = 0; i < mov->nb_streams; i++) {
5364 MOVTrack *trk = &mov->tracks[i];
5367 if (trk->par->codec_id == AV_CODEC_ID_MOV_TEXT &&
5368 trk->track_duration < pkt->dts &&
5369 (trk->entry == 0 || !trk->last_sample_is_subtitle_end)) {
5370 ret = mov_write_subtitle_end_packet(s, i, trk->track_duration);
5371 if (ret < 0) return ret;
5372 trk->last_sample_is_subtitle_end = 1;
5376 if (trk->mode == MODE_MOV && trk->par->codec_type == AVMEDIA_TYPE_VIDEO) {
5377 AVPacket *opkt = pkt;
5378 int reshuffle_ret, ret;
5379 if (trk->is_unaligned_qt_rgb) {
5380 int64_t bpc = trk->par->bits_per_coded_sample != 15 ? trk->par->bits_per_coded_sample : 16;
5381 int expected_stride = ((trk->par->width * bpc + 15) >> 4)*2;
5382 reshuffle_ret = ff_reshuffle_raw_rgb(s, &pkt, trk->par, expected_stride);
5383 if (reshuffle_ret < 0)
5384 return reshuffle_ret;
5387 if (trk->par->format == AV_PIX_FMT_PAL8 && !trk->pal_done) {
5388 ret = ff_get_packet_palette(s, opkt, reshuffle_ret, trk->palette);
5393 } else if (trk->par->codec_id == AV_CODEC_ID_RAWVIDEO &&
5394 (trk->par->format == AV_PIX_FMT_GRAY8 ||
5395 trk->par->format == AV_PIX_FMT_MONOBLACK)) {
5396 for (i = 0; i < pkt->size; i++)
5397 pkt->data[i] = ~pkt->data[i];
5399 if (reshuffle_ret) {
5400 ret = mov_write_single_packet(s, pkt);
5403 av_packet_free(&pkt);
5408 return mov_write_single_packet(s, pkt);
5412 // QuickTime chapters involve an additional text track with the chapter names
5413 // as samples, and a tref pointing from the other tracks to the chapter one.
5414 static int mov_create_chapter_track(AVFormatContext *s, int tracknum)
5418 MOVMuxContext *mov = s->priv_data;
5419 MOVTrack *track = &mov->tracks[tracknum];
5420 AVPacket pkt = { .stream_index = tracknum, .flags = AV_PKT_FLAG_KEY };
5423 track->mode = mov->mode;
5424 track->tag = MKTAG('t','e','x','t');
5425 track->timescale = MOV_TIMESCALE;
5426 track->par = avcodec_parameters_alloc();
5428 return AVERROR(ENOMEM);
5429 track->par->codec_type = AVMEDIA_TYPE_SUBTITLE;
5431 // These properties are required to make QT recognize the chapter track
5432 uint8_t chapter_properties[43] = { 0, 0, 0, 0, 0, 0, 0, 1, };
5433 if (ff_alloc_extradata(track->par, sizeof(chapter_properties)))
5434 return AVERROR(ENOMEM);
5435 memcpy(track->par->extradata, chapter_properties, sizeof(chapter_properties));
5437 if (avio_open_dyn_buf(&pb) >= 0) {
5441 /* Stub header (usually for Quicktime chapter track) */
5443 avio_wb32(pb, 0x01); // displayFlags
5444 avio_w8(pb, 0x00); // horizontal justification
5445 avio_w8(pb, 0x00); // vertical justification
5446 avio_w8(pb, 0x00); // bgColourRed
5447 avio_w8(pb, 0x00); // bgColourGreen
5448 avio_w8(pb, 0x00); // bgColourBlue
5449 avio_w8(pb, 0x00); // bgColourAlpha
5451 avio_wb16(pb, 0x00); // defTextBoxTop
5452 avio_wb16(pb, 0x00); // defTextBoxLeft
5453 avio_wb16(pb, 0x00); // defTextBoxBottom
5454 avio_wb16(pb, 0x00); // defTextBoxRight
5456 avio_wb16(pb, 0x00); // startChar
5457 avio_wb16(pb, 0x00); // endChar
5458 avio_wb16(pb, 0x01); // fontID
5459 avio_w8(pb, 0x00); // fontStyleFlags
5460 avio_w8(pb, 0x00); // fontSize
5461 avio_w8(pb, 0x00); // fgColourRed
5462 avio_w8(pb, 0x00); // fgColourGreen
5463 avio_w8(pb, 0x00); // fgColourBlue
5464 avio_w8(pb, 0x00); // fgColourAlpha
5466 avio_wb32(pb, 0x0D); // box size
5467 ffio_wfourcc(pb, "ftab"); // box atom name
5468 avio_wb16(pb, 0x01); // entry count
5470 avio_wb16(pb, 0x01); // font ID
5471 avio_w8(pb, 0x00); // font name length
5473 if ((size = avio_close_dyn_buf(pb, &buf)) > 0) {
5474 track->par->extradata = buf;
5475 track->par->extradata_size = size;
5482 for (i = 0; i < s->nb_chapters; i++) {
5483 AVChapter *c = s->chapters[i];
5484 AVDictionaryEntry *t;
5486 int64_t end = av_rescale_q(c->end, c->time_base, (AVRational){1,MOV_TIMESCALE});
5487 pkt.pts = pkt.dts = av_rescale_q(c->start, c->time_base, (AVRational){1,MOV_TIMESCALE});
5488 pkt.duration = end - pkt.dts;
5490 if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
5491 static const char encd[12] = {
5492 0x00, 0x00, 0x00, 0x0C,
5494 0x00, 0x00, 0x01, 0x00 };
5495 len = strlen(t->value);
5496 pkt.size = len + 2 + 12;
5497 pkt.data = av_malloc(pkt.size);
5499 return AVERROR(ENOMEM);
5500 AV_WB16(pkt.data, len);
5501 memcpy(pkt.data + 2, t->value, len);
5502 memcpy(pkt.data + len + 2, encd, sizeof(encd));
5503 ff_mov_write_packet(s, &pkt);
5504 av_freep(&pkt.data);
5512 static int mov_check_timecode_track(AVFormatContext *s, AVTimecode *tc, int src_index, const char *tcstr)
5516 /* compute the frame number */
5517 ret = av_timecode_init_from_string(tc, find_fps(s, s->streams[src_index]), tcstr, s);
5521 static int mov_create_timecode_track(AVFormatContext *s, int index, int src_index, AVTimecode tc)
5524 MOVMuxContext *mov = s->priv_data;
5525 MOVTrack *track = &mov->tracks[index];
5526 AVStream *src_st = s->streams[src_index];
5527 AVPacket pkt = {.stream_index = index, .flags = AV_PKT_FLAG_KEY, .size = 4};
5528 AVRational rate = find_fps(s, src_st);
5530 /* tmcd track based on video stream */
5531 track->mode = mov->mode;
5532 track->tag = MKTAG('t','m','c','d');
5533 track->src_track = src_index;
5534 track->timescale = mov->tracks[src_index].timescale;
5535 if (tc.flags & AV_TIMECODE_FLAG_DROPFRAME)
5536 track->timecode_flags |= MOV_TIMECODE_FLAG_DROPFRAME;
5538 /* set st to src_st for metadata access*/
5541 /* encode context: tmcd data stream */
5542 track->par = avcodec_parameters_alloc();
5544 return AVERROR(ENOMEM);
5545 track->par->codec_type = AVMEDIA_TYPE_DATA;
5546 track->par->codec_tag = track->tag;
5547 track->st->avg_frame_rate = av_inv_q(rate);
5549 /* the tmcd track just contains one packet with the frame number */
5550 pkt.data = av_malloc(pkt.size);
5552 return AVERROR(ENOMEM);
5553 AV_WB32(pkt.data, tc.start);
5554 ret = ff_mov_write_packet(s, &pkt);
5560 * st->disposition controls the "enabled" flag in the tkhd tag.
5561 * QuickTime will not play a track if it is not enabled. So make sure
5562 * that one track of each type (audio, video, subtitle) is enabled.
5564 * Subtitles are special. For audio and video, setting "enabled" also
5565 * makes the track "default" (i.e. it is rendered when played). For
5566 * subtitles, an "enabled" subtitle is not rendered by default, but
5567 * if no subtitle is enabled, the subtitle menu in QuickTime will be
5570 static void enable_tracks(AVFormatContext *s)
5572 MOVMuxContext *mov = s->priv_data;
5574 int enabled[AVMEDIA_TYPE_NB];
5575 int first[AVMEDIA_TYPE_NB];
5577 for (i = 0; i < AVMEDIA_TYPE_NB; i++) {
5582 for (i = 0; i < s->nb_streams; i++) {
5583 AVStream *st = s->streams[i];
5585 if (st->codecpar->codec_type <= AVMEDIA_TYPE_UNKNOWN ||
5586 st->codecpar->codec_type >= AVMEDIA_TYPE_NB)
5589 if (first[st->codecpar->codec_type] < 0)
5590 first[st->codecpar->codec_type] = i;
5591 if (st->disposition & AV_DISPOSITION_DEFAULT) {
5592 mov->tracks[i].flags |= MOV_TRACK_ENABLED;
5593 enabled[st->codecpar->codec_type]++;
5597 for (i = 0; i < AVMEDIA_TYPE_NB; i++) {
5599 case AVMEDIA_TYPE_VIDEO:
5600 case AVMEDIA_TYPE_AUDIO:
5601 case AVMEDIA_TYPE_SUBTITLE:
5603 mov->per_stream_grouping = 1;
5604 if (!enabled[i] && first[i] >= 0)
5605 mov->tracks[first[i]].flags |= MOV_TRACK_ENABLED;
5611 static void mov_free(AVFormatContext *s)
5613 MOVMuxContext *mov = s->priv_data;
5616 if (mov->chapter_track) {
5617 if (mov->tracks[mov->chapter_track].par)
5618 av_freep(&mov->tracks[mov->chapter_track].par->extradata);
5619 av_freep(&mov->tracks[mov->chapter_track].par);
5622 for (i = 0; i < mov->nb_streams; i++) {
5623 if (mov->tracks[i].tag == MKTAG('r','t','p',' '))
5624 ff_mov_close_hinting(&mov->tracks[i]);
5625 else if (mov->tracks[i].tag == MKTAG('t','m','c','d') && mov->nb_meta_tmcd)
5626 av_freep(&mov->tracks[i].par);
5627 av_freep(&mov->tracks[i].cluster);
5628 av_freep(&mov->tracks[i].frag_info);
5630 if (mov->tracks[i].vos_len)
5631 av_freep(&mov->tracks[i].vos_data);
5633 ff_mov_cenc_free(&mov->tracks[i].cenc);
5636 av_freep(&mov->tracks);
5639 static uint32_t rgb_to_yuv(uint32_t rgb)
5644 r = (rgb >> 16) & 0xFF;
5645 g = (rgb >> 8) & 0xFF;
5648 y = av_clip_uint8(( 16000 + 257 * r + 504 * g + 98 * b)/1000);
5649 cb = av_clip_uint8((128000 - 148 * r - 291 * g + 439 * b)/1000);
5650 cr = av_clip_uint8((128000 + 439 * r - 368 * g - 71 * b)/1000);
5652 return (y << 16) | (cr << 8) | cb;
5655 static int mov_create_dvd_sub_decoder_specific_info(MOVTrack *track,
5658 int i, width = 720, height = 480;
5659 int have_palette = 0, have_size = 0;
5660 uint32_t palette[16];
5661 char *cur = st->codecpar->extradata;
5663 while (cur && *cur) {
5664 if (strncmp("palette:", cur, 8) == 0) {
5666 count = sscanf(cur + 8,
5667 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
5668 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
5669 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
5670 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32"",
5671 &palette[ 0], &palette[ 1], &palette[ 2], &palette[ 3],
5672 &palette[ 4], &palette[ 5], &palette[ 6], &palette[ 7],
5673 &palette[ 8], &palette[ 9], &palette[10], &palette[11],
5674 &palette[12], &palette[13], &palette[14], &palette[15]);
5676 for (i = 0; i < count; i++) {
5677 palette[i] = rgb_to_yuv(palette[i]);
5680 } else if (!strncmp("size:", cur, 5)) {
5681 sscanf(cur + 5, "%dx%d", &width, &height);
5684 if (have_palette && have_size)
5686 cur += strcspn(cur, "\n\r");
5687 cur += strspn(cur, "\n\r");
5690 track->vos_data = av_malloc(16*4);
5691 if (!track->vos_data)
5692 return AVERROR(ENOMEM);
5693 for (i = 0; i < 16; i++) {
5694 AV_WB32(track->vos_data + i * 4, palette[i]);
5696 track->vos_len = 16 * 4;
5698 st->codecpar->width = width;
5699 st->codecpar->height = track->height = height;
5704 static int mov_init(AVFormatContext *s)
5706 MOVMuxContext *mov = s->priv_data;
5707 AVDictionaryEntry *global_tcr = av_dict_get(s->metadata, "timecode", NULL, 0);
5712 /* Default mode == MP4 */
5713 mov->mode = MODE_MP4;
5716 if (!strcmp("3gp", s->oformat->name)) mov->mode = MODE_3GP;
5717 else if (!strcmp("3g2", s->oformat->name)) mov->mode = MODE_3GP|MODE_3G2;
5718 else if (!strcmp("mov", s->oformat->name)) mov->mode = MODE_MOV;
5719 else if (!strcmp("psp", s->oformat->name)) mov->mode = MODE_PSP;
5720 else if (!strcmp("ipod",s->oformat->name)) mov->mode = MODE_IPOD;
5721 else if (!strcmp("ismv",s->oformat->name)) mov->mode = MODE_ISM;
5722 else if (!strcmp("f4v", s->oformat->name)) mov->mode = MODE_F4V;
5725 if (mov->flags & FF_MOV_FLAG_DELAY_MOOV)
5726 mov->flags |= FF_MOV_FLAG_EMPTY_MOOV;
5728 /* Set the FRAGMENT flag if any of the fragmentation methods are
5730 if (mov->max_fragment_duration || mov->max_fragment_size ||
5731 mov->flags & (FF_MOV_FLAG_EMPTY_MOOV |
5732 FF_MOV_FLAG_FRAG_KEYFRAME |
5733 FF_MOV_FLAG_FRAG_CUSTOM))
5734 mov->flags |= FF_MOV_FLAG_FRAGMENT;
5736 /* Set other implicit flags immediately */
5737 if (mov->mode == MODE_ISM)
5738 mov->flags |= FF_MOV_FLAG_EMPTY_MOOV | FF_MOV_FLAG_SEPARATE_MOOF |
5739 FF_MOV_FLAG_FRAGMENT;
5740 if (mov->flags & FF_MOV_FLAG_DASH)
5741 mov->flags |= FF_MOV_FLAG_FRAGMENT | FF_MOV_FLAG_EMPTY_MOOV |
5742 FF_MOV_FLAG_DEFAULT_BASE_MOOF;
5744 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV && s->flags & AVFMT_FLAG_AUTO_BSF) {
5745 av_log(s, AV_LOG_VERBOSE, "Empty MOOV enabled; disabling automatic bitstream filtering\n");
5746 s->flags &= ~AVFMT_FLAG_AUTO_BSF;
5749 if (mov->flags & FF_MOV_FLAG_FASTSTART) {
5750 mov->reserved_moov_size = -1;
5753 if (mov->use_editlist < 0) {
5754 mov->use_editlist = 1;
5755 if (mov->flags & FF_MOV_FLAG_FRAGMENT &&
5756 !(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
5757 // If we can avoid needing an edit list by shifting the
5758 // tracks, prefer that over (trying to) write edit lists
5759 // in fragmented output.
5760 if (s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO ||
5761 s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO)
5762 mov->use_editlist = 0;
5765 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV &&
5766 !(mov->flags & FF_MOV_FLAG_DELAY_MOOV) && mov->use_editlist)
5767 av_log(s, AV_LOG_WARNING, "No meaningful edit list will be written when using empty_moov without delay_moov\n");
5769 if (!mov->use_editlist && s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO)
5770 s->avoid_negative_ts = AVFMT_AVOID_NEG_TS_MAKE_ZERO;
5772 /* Clear the omit_tfhd_offset flag if default_base_moof is set;
5773 * if the latter is set that's enough and omit_tfhd_offset doesn't
5774 * add anything extra on top of that. */
5775 if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET &&
5776 mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)
5777 mov->flags &= ~FF_MOV_FLAG_OMIT_TFHD_OFFSET;
5779 if (mov->frag_interleave &&
5780 mov->flags & (FF_MOV_FLAG_OMIT_TFHD_OFFSET | FF_MOV_FLAG_SEPARATE_MOOF)) {
5781 av_log(s, AV_LOG_ERROR,
5782 "Sample interleaving in fragments is mutually exclusive with "
5783 "omit_tfhd_offset and separate_moof\n");
5784 return AVERROR(EINVAL);
5787 /* Non-seekable output is ok if using fragmentation. If ism_lookahead
5788 * is enabled, we don't support non-seekable output at all. */
5789 if (!(s->pb->seekable & AVIO_SEEKABLE_NORMAL) &&
5790 (!(mov->flags & FF_MOV_FLAG_FRAGMENT) || mov->ism_lookahead)) {
5791 av_log(s, AV_LOG_ERROR, "muxer does not support non seekable output\n");
5792 return AVERROR(EINVAL);
5795 mov->nb_streams = s->nb_streams;
5796 if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters)
5797 mov->chapter_track = mov->nb_streams++;
5799 if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
5800 /* Add hint tracks for each audio and video stream */
5801 for (i = 0; i < s->nb_streams; i++) {
5802 AVStream *st = s->streams[i];
5803 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ||
5804 st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
5810 if ( mov->write_tmcd == -1 && (mov->mode == MODE_MOV || mov->mode == MODE_MP4)
5811 || mov->write_tmcd == 1) {
5812 /* +1 tmcd track for each video stream with a timecode */
5813 for (i = 0; i < s->nb_streams; i++) {
5814 AVStream *st = s->streams[i];
5815 AVDictionaryEntry *t = global_tcr;
5816 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
5817 (t || (t=av_dict_get(st->metadata, "timecode", NULL, 0)))) {
5819 ret = mov_check_timecode_track(s, &tc, i, t->value);
5821 mov->nb_meta_tmcd++;
5825 /* check if there is already a tmcd track to remux */
5826 if (mov->nb_meta_tmcd) {
5827 for (i = 0; i < s->nb_streams; i++) {
5828 AVStream *st = s->streams[i];
5829 if (st->codecpar->codec_tag == MKTAG('t','m','c','d')) {
5830 av_log(s, AV_LOG_WARNING, "You requested a copy of the original timecode track "
5831 "so timecode metadata are now ignored\n");
5832 mov->nb_meta_tmcd = 0;
5837 mov->nb_streams += mov->nb_meta_tmcd;
5840 // Reserve an extra stream for chapters for the case where chapters
5841 // are written in the trailer
5842 mov->tracks = av_mallocz_array((mov->nb_streams + 1), sizeof(*mov->tracks));
5844 return AVERROR(ENOMEM);
5846 if (mov->encryption_scheme_str != NULL && strcmp(mov->encryption_scheme_str, "none") != 0) {
5847 if (strcmp(mov->encryption_scheme_str, "cenc-aes-ctr") == 0) {
5848 mov->encryption_scheme = MOV_ENC_CENC_AES_CTR;
5850 if (mov->encryption_key_len != AES_CTR_KEY_SIZE) {
5851 av_log(s, AV_LOG_ERROR, "Invalid encryption key len %d expected %d\n",
5852 mov->encryption_key_len, AES_CTR_KEY_SIZE);
5853 return AVERROR(EINVAL);
5856 if (mov->encryption_kid_len != CENC_KID_SIZE) {
5857 av_log(s, AV_LOG_ERROR, "Invalid encryption kid len %d expected %d\n",
5858 mov->encryption_kid_len, CENC_KID_SIZE);
5859 return AVERROR(EINVAL);
5862 av_log(s, AV_LOG_ERROR, "unsupported encryption scheme %s\n",
5863 mov->encryption_scheme_str);
5864 return AVERROR(EINVAL);
5868 for (i = 0; i < s->nb_streams; i++) {
5869 AVStream *st= s->streams[i];
5870 MOVTrack *track= &mov->tracks[i];
5871 AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0);
5874 track->par = st->codecpar;
5875 track->language = ff_mov_iso639_to_lang(lang?lang->value:"und", mov->mode!=MODE_MOV);
5876 if (track->language < 0)
5877 track->language = 0;
5878 track->mode = mov->mode;
5879 track->tag = mov_find_codec_tag(s, track);
5881 av_log(s, AV_LOG_ERROR, "Could not find tag for codec %s in stream #%d, "
5882 "codec not currently supported in container\n",
5883 avcodec_get_name(st->codecpar->codec_id), i);
5884 return AVERROR(EINVAL);
5886 /* If hinting of this track is enabled by a later hint track,
5887 * this is updated. */
5888 track->hint_track = -1;
5889 track->start_dts = AV_NOPTS_VALUE;
5890 track->start_cts = AV_NOPTS_VALUE;
5891 track->end_pts = AV_NOPTS_VALUE;
5892 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
5893 if (track->tag == MKTAG('m','x','3','p') || track->tag == MKTAG('m','x','3','n') ||
5894 track->tag == MKTAG('m','x','4','p') || track->tag == MKTAG('m','x','4','n') ||
5895 track->tag == MKTAG('m','x','5','p') || track->tag == MKTAG('m','x','5','n')) {
5896 if (st->codecpar->width != 720 || (st->codecpar->height != 608 && st->codecpar->height != 512)) {
5897 av_log(s, AV_LOG_ERROR, "D-10/IMX must use 720x608 or 720x512 video resolution\n");
5898 return AVERROR(EINVAL);
5900 track->height = track->tag >> 24 == 'n' ? 486 : 576;
5902 if (mov->video_track_timescale) {
5903 track->timescale = mov->video_track_timescale;
5905 track->timescale = st->time_base.den;
5906 while(track->timescale < 10000)
5907 track->timescale *= 2;
5909 if (st->codecpar->width > 65535 || st->codecpar->height > 65535) {
5910 av_log(s, AV_LOG_ERROR, "Resolution %dx%d too large for mov/mp4\n", st->codecpar->width, st->codecpar->height);
5911 return AVERROR(EINVAL);
5913 if (track->mode == MODE_MOV && track->timescale > 100000)
5914 av_log(s, AV_LOG_WARNING,
5915 "WARNING codec timebase is very high. If duration is too long,\n"
5916 "file may not be playable by quicktime. Specify a shorter timebase\n"
5917 "or choose different container.\n");
5918 if (track->mode == MODE_MOV &&
5919 track->par->codec_id == AV_CODEC_ID_RAWVIDEO &&
5920 track->tag == MKTAG('r','a','w',' ')) {
5921 enum AVPixelFormat pix_fmt = track->par->format;
5922 if (pix_fmt == AV_PIX_FMT_NONE && track->par->bits_per_coded_sample == 1)
5923 pix_fmt = AV_PIX_FMT_MONOWHITE;
5924 track->is_unaligned_qt_rgb =
5925 pix_fmt == AV_PIX_FMT_RGB24 ||
5926 pix_fmt == AV_PIX_FMT_BGR24 ||
5927 pix_fmt == AV_PIX_FMT_PAL8 ||
5928 pix_fmt == AV_PIX_FMT_GRAY8 ||
5929 pix_fmt == AV_PIX_FMT_MONOWHITE ||
5930 pix_fmt == AV_PIX_FMT_MONOBLACK;
5932 if (track->par->codec_id == AV_CODEC_ID_VP9) {
5933 if (track->mode != MODE_MP4) {
5934 av_log(s, AV_LOG_ERROR, "VP9 only supported in MP4.\n");
5935 return AVERROR(EINVAL);
5938 } else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
5939 track->timescale = st->codecpar->sample_rate;
5940 if (!st->codecpar->frame_size && !av_get_bits_per_sample(st->codecpar->codec_id)) {
5941 av_log(s, AV_LOG_WARNING, "track %d: codec frame size is not set\n", i);
5942 track->audio_vbr = 1;
5943 }else if (st->codecpar->codec_id == AV_CODEC_ID_ADPCM_MS ||
5944 st->codecpar->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
5945 st->codecpar->codec_id == AV_CODEC_ID_ILBC){
5946 if (!st->codecpar->block_align) {
5947 av_log(s, AV_LOG_ERROR, "track %d: codec block align is not set for adpcm\n", i);
5948 return AVERROR(EINVAL);
5950 track->sample_size = st->codecpar->block_align;
5951 }else if (st->codecpar->frame_size > 1){ /* assume compressed audio */
5952 track->audio_vbr = 1;
5954 track->sample_size = (av_get_bits_per_sample(st->codecpar->codec_id) >> 3) * st->codecpar->channels;
5956 if (st->codecpar->codec_id == AV_CODEC_ID_ILBC ||
5957 st->codecpar->codec_id == AV_CODEC_ID_ADPCM_IMA_QT) {
5958 track->audio_vbr = 1;
5960 if (track->mode != MODE_MOV &&
5961 track->par->codec_id == AV_CODEC_ID_MP3 && track->timescale < 16000) {
5962 if (s->strict_std_compliance >= FF_COMPLIANCE_NORMAL) {
5963 av_log(s, AV_LOG_ERROR, "track %d: muxing mp3 at %dhz is not standard, to mux anyway set strict to -1\n",
5964 i, track->par->sample_rate);
5965 return AVERROR(EINVAL);
5967 av_log(s, AV_LOG_WARNING, "track %d: muxing mp3 at %dhz is not standard in MP4\n",
5968 i, track->par->sample_rate);
5971 if (track->par->codec_id == AV_CODEC_ID_FLAC ||
5972 track->par->codec_id == AV_CODEC_ID_OPUS) {
5973 if (track->mode != MODE_MP4) {
5974 av_log(s, AV_LOG_ERROR, "%s only supported in MP4.\n", avcodec_get_name(track->par->codec_id));
5975 return AVERROR(EINVAL);
5977 if (s->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
5978 av_log(s, AV_LOG_ERROR,
5979 "%s in MP4 support is experimental, add "
5980 "'-strict %d' if you want to use it.\n",
5981 avcodec_get_name(track->par->codec_id), FF_COMPLIANCE_EXPERIMENTAL);
5982 return AVERROR_EXPERIMENTAL;
5985 } else if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) {
5986 track->timescale = st->time_base.den;
5987 } else if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA) {
5988 track->timescale = st->time_base.den;
5990 track->timescale = MOV_TIMESCALE;
5993 track->height = st->codecpar->height;
5994 /* The ism specific timescale isn't mandatory, but is assumed by
5995 * some tools, such as mp4split. */
5996 if (mov->mode == MODE_ISM)
5997 track->timescale = 10000000;
5999 avpriv_set_pts_info(st, 64, 1, track->timescale);
6001 if (mov->encryption_scheme == MOV_ENC_CENC_AES_CTR) {
6002 ret = ff_mov_cenc_init(&track->cenc, mov->encryption_key,
6003 track->par->codec_id == AV_CODEC_ID_H264, s->flags & AVFMT_FLAG_BITEXACT);
6013 static int mov_write_header(AVFormatContext *s)
6015 AVIOContext *pb = s->pb;
6016 MOVMuxContext *mov = s->priv_data;
6017 AVDictionaryEntry *t, *global_tcr = av_dict_get(s->metadata, "timecode", NULL, 0);
6018 int i, ret, hint_track = 0, tmcd_track = 0, nb_tracks = s->nb_streams;
6020 if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters)
6023 if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
6024 /* Add hint tracks for each audio and video stream */
6025 hint_track = nb_tracks;
6026 for (i = 0; i < s->nb_streams; i++) {
6027 AVStream *st = s->streams[i];
6028 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ||
6029 st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
6035 if (mov->mode == MODE_MOV || mov->mode == MODE_MP4)
6036 tmcd_track = nb_tracks;
6038 for (i = 0; i < s->nb_streams; i++) {
6040 AVStream *st= s->streams[i];
6041 MOVTrack *track= &mov->tracks[i];
6043 /* copy extradata if it exists */
6044 if (st->codecpar->extradata_size) {
6045 if (st->codecpar->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
6046 mov_create_dvd_sub_decoder_specific_info(track, st);
6047 else if (!TAG_IS_AVCI(track->tag) && st->codecpar->codec_id != AV_CODEC_ID_DNXHD) {
6048 track->vos_len = st->codecpar->extradata_size;
6049 track->vos_data = av_malloc(track->vos_len);
6050 if (!track->vos_data) {
6051 return AVERROR(ENOMEM);
6053 memcpy(track->vos_data, st->codecpar->extradata, track->vos_len);
6057 if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ||
6058 track->par->channel_layout != AV_CH_LAYOUT_MONO)
6061 for (j = 0; j < s->nb_streams; j++) {
6062 AVStream *stj= s->streams[j];
6063 MOVTrack *trackj= &mov->tracks[j];
6067 if (stj->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ||
6068 trackj->par->channel_layout != AV_CH_LAYOUT_MONO ||
6069 trackj->language != track->language ||
6070 trackj->tag != track->tag
6073 track->multichannel_as_mono++;
6077 if (!(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
6078 if ((ret = mov_write_identification(pb, s)) < 0)
6082 if (mov->reserved_moov_size){
6083 mov->reserved_header_pos = avio_tell(pb);
6084 if (mov->reserved_moov_size > 0)
6085 avio_skip(pb, mov->reserved_moov_size);
6088 if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
6089 /* If no fragmentation options have been set, set a default. */
6090 if (!(mov->flags & (FF_MOV_FLAG_FRAG_KEYFRAME |
6091 FF_MOV_FLAG_FRAG_CUSTOM)) &&
6092 !mov->max_fragment_duration && !mov->max_fragment_size)
6093 mov->flags |= FF_MOV_FLAG_FRAG_KEYFRAME;
6095 if (mov->flags & FF_MOV_FLAG_FASTSTART)
6096 mov->reserved_header_pos = avio_tell(pb);
6097 mov_write_mdat_tag(pb, mov);
6100 ff_parse_creation_time_metadata(s, &mov->time, 1);
6102 mov->time += 0x7C25B080; // 1970 based -> 1904 based
6104 if (mov->chapter_track)
6105 if ((ret = mov_create_chapter_track(s, mov->chapter_track)) < 0)
6108 if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
6109 /* Initialize the hint tracks for each audio and video stream */
6110 for (i = 0; i < s->nb_streams; i++) {
6111 AVStream *st = s->streams[i];
6112 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ||
6113 st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
6114 if ((ret = ff_mov_init_hinting(s, hint_track, i)) < 0)
6121 if (mov->nb_meta_tmcd) {
6122 /* Initialize the tmcd tracks */
6123 for (i = 0; i < s->nb_streams; i++) {
6124 AVStream *st = s->streams[i];
6127 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
6130 t = av_dict_get(st->metadata, "timecode", NULL, 0);
6133 if (mov_check_timecode_track(s, &tc, i, t->value) < 0)
6135 if ((ret = mov_create_timecode_track(s, tmcd_track, i, tc)) < 0)
6144 if (mov->flags & FF_MOV_FLAG_ISML)
6145 mov_write_isml_manifest(pb, mov, s);
6147 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV &&
6148 !(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
6149 if ((ret = mov_write_moov_tag(pb, mov, s)) < 0)
6152 mov->moov_written = 1;
6153 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
6154 mov->reserved_header_pos = avio_tell(pb);
6160 static int get_moov_size(AVFormatContext *s)
6163 AVIOContext *moov_buf;
6164 MOVMuxContext *mov = s->priv_data;
6166 if ((ret = ffio_open_null_buf(&moov_buf)) < 0)
6168 if ((ret = mov_write_moov_tag(moov_buf, mov, s)) < 0)
6170 return ffio_close_null_buf(moov_buf);
6173 static int get_sidx_size(AVFormatContext *s)
6177 MOVMuxContext *mov = s->priv_data;
6179 if ((ret = ffio_open_null_buf(&buf)) < 0)
6181 mov_write_sidx_tags(buf, mov, -1, 0);
6182 return ffio_close_null_buf(buf);
6186 * This function gets the moov size if moved to the top of the file: the chunk
6187 * offset table can switch between stco (32-bit entries) to co64 (64-bit
6188 * entries) when the moov is moved to the beginning, so the size of the moov
6189 * would change. It also updates the chunk offset tables.
6191 static int compute_moov_size(AVFormatContext *s)
6193 int i, moov_size, moov_size2;
6194 MOVMuxContext *mov = s->priv_data;
6196 moov_size = get_moov_size(s);
6200 for (i = 0; i < mov->nb_streams; i++)
6201 mov->tracks[i].data_offset += moov_size;
6203 moov_size2 = get_moov_size(s);
6207 /* if the size changed, we just switched from stco to co64 and need to
6208 * update the offsets */
6209 if (moov_size2 != moov_size)
6210 for (i = 0; i < mov->nb_streams; i++)
6211 mov->tracks[i].data_offset += moov_size2 - moov_size;
6216 static int compute_sidx_size(AVFormatContext *s)
6219 MOVMuxContext *mov = s->priv_data;
6221 sidx_size = get_sidx_size(s);
6225 for (i = 0; i < mov->nb_streams; i++)
6226 mov->tracks[i].data_offset += sidx_size;
6231 static int shift_data(AVFormatContext *s)
6233 int ret = 0, moov_size;
6234 MOVMuxContext *mov = s->priv_data;
6235 int64_t pos, pos_end = avio_tell(s->pb);
6236 uint8_t *buf, *read_buf[2];
6237 int read_buf_id = 0;
6239 AVIOContext *read_pb;
6241 if (mov->flags & FF_MOV_FLAG_FRAGMENT)
6242 moov_size = compute_sidx_size(s);
6244 moov_size = compute_moov_size(s);
6248 buf = av_malloc(moov_size * 2);
6250 return AVERROR(ENOMEM);
6252 read_buf[1] = buf + moov_size;
6254 /* Shift the data: the AVIO context of the output can only be used for
6255 * writing, so we re-open the same output, but for reading. It also avoids
6256 * a read/seek/write/seek back and forth. */
6258 ret = s->io_open(s, &read_pb, s->filename, AVIO_FLAG_READ, NULL);
6260 av_log(s, AV_LOG_ERROR, "Unable to re-open %s output file for "
6261 "the second pass (faststart)\n", s->filename);
6265 /* mark the end of the shift to up to the last data we wrote, and get ready
6267 pos_end = avio_tell(s->pb);
6268 avio_seek(s->pb, mov->reserved_header_pos + moov_size, SEEK_SET);
6270 /* start reading at where the new moov will be placed */
6271 avio_seek(read_pb, mov->reserved_header_pos, SEEK_SET);
6272 pos = avio_tell(read_pb);
6274 #define READ_BLOCK do { \
6275 read_size[read_buf_id] = avio_read(read_pb, read_buf[read_buf_id], moov_size); \
6279 /* shift data by chunk of at most moov_size */
6284 n = read_size[read_buf_id];
6287 avio_write(s->pb, read_buf[read_buf_id], n);
6289 } while (pos < pos_end);
6290 ff_format_io_close(s, &read_pb);
6297 static int mov_write_trailer(AVFormatContext *s)
6299 MOVMuxContext *mov = s->priv_data;
6300 AVIOContext *pb = s->pb;
6305 if (mov->need_rewrite_extradata) {
6306 for (i = 0; i < s->nb_streams; i++) {
6307 MOVTrack *track = &mov->tracks[i];
6308 AVCodecParameters *par = track->par;
6310 track->vos_len = par->extradata_size;
6311 track->vos_data = av_malloc(track->vos_len);
6312 if (!track->vos_data)
6313 return AVERROR(ENOMEM);
6314 memcpy(track->vos_data, par->extradata, track->vos_len);
6316 mov->need_rewrite_extradata = 0;
6320 * Before actually writing the trailer, make sure that there are no
6321 * dangling subtitles, that need a terminating sample.
6323 for (i = 0; i < mov->nb_streams; i++) {
6324 MOVTrack *trk = &mov->tracks[i];
6325 if (trk->par->codec_id == AV_CODEC_ID_MOV_TEXT &&
6326 !trk->last_sample_is_subtitle_end) {
6327 mov_write_subtitle_end_packet(s, i, trk->track_duration);
6328 trk->last_sample_is_subtitle_end = 1;
6332 // If there were no chapters when the header was written, but there
6333 // are chapters now, write them in the trailer. This only works
6334 // when we are not doing fragments.
6335 if (!mov->chapter_track && !(mov->flags & FF_MOV_FLAG_FRAGMENT)) {
6336 if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters) {
6337 mov->chapter_track = mov->nb_streams++;
6338 if ((res = mov_create_chapter_track(s, mov->chapter_track)) < 0)
6343 if (!(mov->flags & FF_MOV_FLAG_FRAGMENT)) {
6344 moov_pos = avio_tell(pb);
6346 /* Write size of mdat tag */
6347 if (mov->mdat_size + 8 <= UINT32_MAX) {
6348 avio_seek(pb, mov->mdat_pos, SEEK_SET);
6349 avio_wb32(pb, mov->mdat_size + 8);
6351 /* overwrite 'wide' placeholder atom */
6352 avio_seek(pb, mov->mdat_pos - 8, SEEK_SET);
6353 /* special value: real atom size will be 64 bit value after
6356 ffio_wfourcc(pb, "mdat");
6357 avio_wb64(pb, mov->mdat_size + 16);
6359 avio_seek(pb, mov->reserved_moov_size > 0 ? mov->reserved_header_pos : moov_pos, SEEK_SET);
6361 if (mov->flags & FF_MOV_FLAG_FASTSTART) {
6362 av_log(s, AV_LOG_INFO, "Starting second pass: moving the moov atom to the beginning of the file\n");
6363 res = shift_data(s);
6366 avio_seek(pb, mov->reserved_header_pos, SEEK_SET);
6367 if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
6369 } else if (mov->reserved_moov_size > 0) {
6371 if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
6373 size = mov->reserved_moov_size - (avio_tell(pb) - mov->reserved_header_pos);
6375 av_log(s, AV_LOG_ERROR, "reserved_moov_size is too small, needed %"PRId64" additional\n", 8-size);
6376 return AVERROR(EINVAL);
6378 avio_wb32(pb, size);
6379 ffio_wfourcc(pb, "free");
6380 ffio_fill(pb, 0, size - 8);
6381 avio_seek(pb, moov_pos, SEEK_SET);
6383 if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
6388 mov_auto_flush_fragment(s, 1);
6389 for (i = 0; i < mov->nb_streams; i++)
6390 mov->tracks[i].data_offset = 0;
6391 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) {
6393 av_log(s, AV_LOG_INFO, "Starting second pass: inserting sidx atoms\n");
6394 res = shift_data(s);
6397 end = avio_tell(pb);
6398 avio_seek(pb, mov->reserved_header_pos, SEEK_SET);
6399 mov_write_sidx_tags(pb, mov, -1, 0);
6400 avio_seek(pb, end, SEEK_SET);
6401 avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_TRAILER);
6402 mov_write_mfra_tag(pb, mov);
6403 } else if (!(mov->flags & FF_MOV_FLAG_SKIP_TRAILER)) {
6404 avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_TRAILER);
6405 mov_write_mfra_tag(pb, mov);
6412 static int mov_check_bitstream(struct AVFormatContext *s, const AVPacket *pkt)
6415 AVStream *st = s->streams[pkt->stream_index];
6417 if (st->codecpar->codec_id == AV_CODEC_ID_AAC) {
6418 if (pkt->size > 2 && (AV_RB16(pkt->data) & 0xfff0) == 0xfff0)
6419 ret = ff_stream_add_bitstream_filter(st, "aac_adtstoasc", NULL);
6420 } else if (st->codecpar->codec_id == AV_CODEC_ID_VP9) {
6421 ret = ff_stream_add_bitstream_filter(st, "vp9_superframe", NULL);
6427 static const AVCodecTag codec_3gp_tags[] = {
6428 { AV_CODEC_ID_H263, MKTAG('s','2','6','3') },
6429 { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
6430 { AV_CODEC_ID_MPEG4, MKTAG('m','p','4','v') },
6431 { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
6432 { AV_CODEC_ID_AMR_NB, MKTAG('s','a','m','r') },
6433 { AV_CODEC_ID_AMR_WB, MKTAG('s','a','w','b') },
6434 { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
6435 { AV_CODEC_ID_NONE, 0 },
6438 const AVCodecTag codec_mp4_tags[] = {
6439 { AV_CODEC_ID_MPEG4 , MKTAG('m', 'p', '4', 'v') },
6440 { AV_CODEC_ID_H264 , MKTAG('a', 'v', 'c', '1') },
6441 { AV_CODEC_ID_HEVC , MKTAG('h', 'e', 'v', '1') },
6442 { AV_CODEC_ID_HEVC , MKTAG('h', 'v', 'c', '1') },
6443 { AV_CODEC_ID_MPEG2VIDEO , MKTAG('m', 'p', '4', 'v') },
6444 { AV_CODEC_ID_MPEG1VIDEO , MKTAG('m', 'p', '4', 'v') },
6445 { AV_CODEC_ID_MJPEG , MKTAG('m', 'p', '4', 'v') },
6446 { AV_CODEC_ID_PNG , MKTAG('m', 'p', '4', 'v') },
6447 { AV_CODEC_ID_JPEG2000 , MKTAG('m', 'p', '4', 'v') },
6448 { AV_CODEC_ID_VC1 , MKTAG('v', 'c', '-', '1') },
6449 { AV_CODEC_ID_DIRAC , MKTAG('d', 'r', 'a', 'c') },
6450 { AV_CODEC_ID_TSCC2 , MKTAG('m', 'p', '4', 'v') },
6451 { AV_CODEC_ID_VP9 , MKTAG('v', 'p', '0', '9') },
6452 { AV_CODEC_ID_AAC , MKTAG('m', 'p', '4', 'a') },
6453 { AV_CODEC_ID_MP4ALS , MKTAG('m', 'p', '4', 'a') },
6454 { AV_CODEC_ID_MP3 , MKTAG('m', 'p', '4', 'a') },
6455 { AV_CODEC_ID_MP2 , MKTAG('m', 'p', '4', 'a') },
6456 { AV_CODEC_ID_AC3 , MKTAG('a', 'c', '-', '3') },
6457 { AV_CODEC_ID_EAC3 , MKTAG('e', 'c', '-', '3') },
6458 { AV_CODEC_ID_DTS , MKTAG('m', 'p', '4', 'a') },
6459 { AV_CODEC_ID_FLAC , MKTAG('f', 'L', 'a', 'C') },
6460 { AV_CODEC_ID_OPUS , MKTAG('O', 'p', 'u', 's') },
6461 { AV_CODEC_ID_VORBIS , MKTAG('m', 'p', '4', 'a') },
6462 { AV_CODEC_ID_QCELP , MKTAG('m', 'p', '4', 'a') },
6463 { AV_CODEC_ID_EVRC , MKTAG('m', 'p', '4', 'a') },
6464 { AV_CODEC_ID_DVD_SUBTITLE, MKTAG('m', 'p', '4', 's') },
6465 { AV_CODEC_ID_MOV_TEXT , MKTAG('t', 'x', '3', 'g') },
6466 { AV_CODEC_ID_NONE , 0 },
6469 const AVCodecTag codec_ism_tags[] = {
6470 { AV_CODEC_ID_WMAPRO , MKTAG('w', 'm', 'a', ' ') },
6471 { AV_CODEC_ID_NONE , 0 },
6474 static const AVCodecTag codec_ipod_tags[] = {
6475 { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
6476 { AV_CODEC_ID_MPEG4, MKTAG('m','p','4','v') },
6477 { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
6478 { AV_CODEC_ID_ALAC, MKTAG('a','l','a','c') },
6479 { AV_CODEC_ID_AC3, MKTAG('a','c','-','3') },
6480 { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
6481 { AV_CODEC_ID_MOV_TEXT, MKTAG('t','e','x','t') },
6482 { AV_CODEC_ID_NONE, 0 },
6485 static const AVCodecTag codec_f4v_tags[] = {
6486 { AV_CODEC_ID_MP3, MKTAG('.','m','p','3') },
6487 { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
6488 { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
6489 { AV_CODEC_ID_VP6A, MKTAG('V','P','6','A') },
6490 { AV_CODEC_ID_VP6F, MKTAG('V','P','6','F') },
6491 { AV_CODEC_ID_NONE, 0 },
6494 #if CONFIG_MOV_MUXER
6496 AVOutputFormat ff_mov_muxer = {
6498 .long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
6499 .extensions = "mov",
6500 .priv_data_size = sizeof(MOVMuxContext),
6501 .audio_codec = AV_CODEC_ID_AAC,
6502 .video_codec = CONFIG_LIBX264_ENCODER ?
6503 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
6505 .write_header = mov_write_header,
6506 .write_packet = mov_write_packet,
6507 .write_trailer = mov_write_trailer,
6509 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6510 .codec_tag = (const AVCodecTag* const []){
6511 ff_codec_movvideo_tags, ff_codec_movaudio_tags, 0
6513 .check_bitstream = mov_check_bitstream,
6514 .priv_class = &mov_muxer_class,
6517 #if CONFIG_TGP_MUXER
6519 AVOutputFormat ff_tgp_muxer = {
6521 .long_name = NULL_IF_CONFIG_SMALL("3GP (3GPP file format)"),
6522 .extensions = "3gp",
6523 .priv_data_size = sizeof(MOVMuxContext),
6524 .audio_codec = AV_CODEC_ID_AMR_NB,
6525 .video_codec = AV_CODEC_ID_H263,
6527 .write_header = mov_write_header,
6528 .write_packet = mov_write_packet,
6529 .write_trailer = mov_write_trailer,
6531 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6532 .codec_tag = (const AVCodecTag* const []){ codec_3gp_tags, 0 },
6533 .check_bitstream = mov_check_bitstream,
6534 .priv_class = &tgp_muxer_class,
6537 #if CONFIG_MP4_MUXER
6539 AVOutputFormat ff_mp4_muxer = {
6541 .long_name = NULL_IF_CONFIG_SMALL("MP4 (MPEG-4 Part 14)"),
6542 .mime_type = "video/mp4",
6543 .extensions = "mp4",
6544 .priv_data_size = sizeof(MOVMuxContext),
6545 .audio_codec = AV_CODEC_ID_AAC,
6546 .video_codec = CONFIG_LIBX264_ENCODER ?
6547 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
6549 .write_header = mov_write_header,
6550 .write_packet = mov_write_packet,
6551 .write_trailer = mov_write_trailer,
6553 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6554 .codec_tag = (const AVCodecTag* const []){ codec_mp4_tags, 0 },
6555 .check_bitstream = mov_check_bitstream,
6556 .priv_class = &mp4_muxer_class,
6559 #if CONFIG_PSP_MUXER
6561 AVOutputFormat ff_psp_muxer = {
6563 .long_name = NULL_IF_CONFIG_SMALL("PSP MP4 (MPEG-4 Part 14)"),
6564 .extensions = "mp4,psp",
6565 .priv_data_size = sizeof(MOVMuxContext),
6566 .audio_codec = AV_CODEC_ID_AAC,
6567 .video_codec = CONFIG_LIBX264_ENCODER ?
6568 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
6570 .write_header = mov_write_header,
6571 .write_packet = mov_write_packet,
6572 .write_trailer = mov_write_trailer,
6574 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6575 .codec_tag = (const AVCodecTag* const []){ codec_mp4_tags, 0 },
6576 .check_bitstream = mov_check_bitstream,
6577 .priv_class = &psp_muxer_class,
6580 #if CONFIG_TG2_MUXER
6582 AVOutputFormat ff_tg2_muxer = {
6584 .long_name = NULL_IF_CONFIG_SMALL("3GP2 (3GPP2 file format)"),
6585 .extensions = "3g2",
6586 .priv_data_size = sizeof(MOVMuxContext),
6587 .audio_codec = AV_CODEC_ID_AMR_NB,
6588 .video_codec = AV_CODEC_ID_H263,
6590 .write_header = mov_write_header,
6591 .write_packet = mov_write_packet,
6592 .write_trailer = mov_write_trailer,
6594 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6595 .codec_tag = (const AVCodecTag* const []){ codec_3gp_tags, 0 },
6596 .check_bitstream = mov_check_bitstream,
6597 .priv_class = &tg2_muxer_class,
6600 #if CONFIG_IPOD_MUXER
6602 AVOutputFormat ff_ipod_muxer = {
6604 .long_name = NULL_IF_CONFIG_SMALL("iPod H.264 MP4 (MPEG-4 Part 14)"),
6605 .mime_type = "video/mp4",
6606 .extensions = "m4v,m4a",
6607 .priv_data_size = sizeof(MOVMuxContext),
6608 .audio_codec = AV_CODEC_ID_AAC,
6609 .video_codec = AV_CODEC_ID_H264,
6611 .write_header = mov_write_header,
6612 .write_packet = mov_write_packet,
6613 .write_trailer = mov_write_trailer,
6615 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6616 .codec_tag = (const AVCodecTag* const []){ codec_ipod_tags, 0 },
6617 .check_bitstream = mov_check_bitstream,
6618 .priv_class = &ipod_muxer_class,
6621 #if CONFIG_ISMV_MUXER
6623 AVOutputFormat ff_ismv_muxer = {
6625 .long_name = NULL_IF_CONFIG_SMALL("ISMV/ISMA (Smooth Streaming)"),
6626 .mime_type = "video/mp4",
6627 .extensions = "ismv,isma",
6628 .priv_data_size = sizeof(MOVMuxContext),
6629 .audio_codec = AV_CODEC_ID_AAC,
6630 .video_codec = AV_CODEC_ID_H264,
6632 .write_header = mov_write_header,
6633 .write_packet = mov_write_packet,
6634 .write_trailer = mov_write_trailer,
6636 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6637 .codec_tag = (const AVCodecTag* const []){
6638 codec_mp4_tags, codec_ism_tags, 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,