3 * Copyright (c) 2003 Thomas Raivio
4 * Copyright (c) 2004 Gildas Bazin <gbazin at videolan dot org>
5 * Copyright (c) 2009 Baptiste Coudurier <baptiste dot coudurier at gmail dot com>
7 * This file is part of FFmpeg.
9 * FFmpeg is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
14 * FFmpeg is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with FFmpeg; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
29 #include "avio_internal.h"
34 #include "libavcodec/ac3_parser_internal.h"
35 #include "libavcodec/dnxhddata.h"
36 #include "libavcodec/flac.h"
37 #include "libavcodec/get_bits.h"
39 #include "libavcodec/internal.h"
40 #include "libavcodec/put_bits.h"
41 #include "libavcodec/vc1_common.h"
42 #include "libavcodec/raw.h"
44 #include "libavutil/avstring.h"
45 #include "libavutil/intfloat.h"
46 #include "libavutil/mathematics.h"
47 #include "libavutil/libm.h"
48 #include "libavutil/opt.h"
49 #include "libavutil/dict.h"
50 #include "libavutil/pixdesc.h"
51 #include "libavutil/stereo3d.h"
52 #include "libavutil/timecode.h"
53 #include "libavutil/color_utils.h"
59 static const AVOption options[] = {
60 { "movflags", "MOV muxer flags", offsetof(MOVMuxContext, flags), AV_OPT_TYPE_FLAGS, {.i64 = 0}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
61 { "rtphint", "Add RTP hint tracks", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_RTP_HINT}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
62 { "moov_size", "maximum moov size so it can be placed at the begin", offsetof(MOVMuxContext, reserved_moov_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, 0 },
63 { "empty_moov", "Make the initial moov atom empty", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_EMPTY_MOOV}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
64 { "frag_keyframe", "Fragment at video keyframes", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FRAG_KEYFRAME}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
65 { "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 { "negative_cts_offsets", "Use negative CTS offsets (reducing the need for edit lists)", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
81 FF_RTP_FLAG_OPTS(MOVMuxContext, rtp_flags),
82 { "skip_iods", "Skip writing iods atom.", offsetof(MOVMuxContext, iods_skip), AV_OPT_TYPE_BOOL, {.i64 = 1}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM},
83 { "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},
84 { "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},
85 { "frag_duration", "Maximum fragment duration", offsetof(MOVMuxContext, max_fragment_duration), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
86 { "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},
87 { "frag_size", "Maximum fragment size", offsetof(MOVMuxContext, max_fragment_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
88 { "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},
89 { "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},
90 { "brand", "Override major brand", offsetof(MOVMuxContext, major_brand), AV_OPT_TYPE_STRING, {.str = NULL}, .flags = AV_OPT_FLAG_ENCODING_PARAM },
91 { "use_editlist", "use edit list", offsetof(MOVMuxContext, use_editlist), AV_OPT_TYPE_BOOL, {.i64 = -1}, -1, 1, AV_OPT_FLAG_ENCODING_PARAM},
92 { "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},
93 { "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},
94 { "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 },
95 { "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 },
96 { "encryption_key", "The media encryption key (hex)", offsetof(MOVMuxContext, encryption_key), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_ENCODING_PARAM },
97 { "encryption_kid", "The media encryption key identifier (hex)", offsetof(MOVMuxContext, encryption_kid), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_ENCODING_PARAM },
98 { "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},
99 { "write_tmcd", "force or disable writing tmcd", offsetof(MOVMuxContext, write_tmcd), AV_OPT_TYPE_BOOL, {.i64 = -1}, -1, 1, AV_OPT_FLAG_ENCODING_PARAM},
103 #define MOV_CLASS(flavor)\
104 static const AVClass flavor ## _muxer_class = {\
105 .class_name = #flavor " muxer",\
106 .item_name = av_default_item_name,\
108 .version = LIBAVUTIL_VERSION_INT,\
111 static int get_moov_size(AVFormatContext *s);
113 static int utf8len(const uint8_t *b)
118 GET_UTF8(val, *b++, return -1;)
124 //FIXME support 64 bit variant with wide placeholders
125 static int64_t update_size(AVIOContext *pb, int64_t pos)
127 int64_t curpos = avio_tell(pb);
128 avio_seek(pb, pos, SEEK_SET);
129 avio_wb32(pb, curpos - pos); /* rewrite size */
130 avio_seek(pb, curpos, SEEK_SET);
135 static int co64_required(const MOVTrack *track)
137 if (track->entry > 0 && track->cluster[track->entry - 1].pos + track->data_offset > UINT32_MAX)
142 /* Chunk offset atom */
143 static int mov_write_stco_tag(AVIOContext *pb, MOVTrack *track)
146 int mode64 = co64_required(track); // use 32 bit size variant if possible
147 int64_t pos = avio_tell(pb);
148 avio_wb32(pb, 0); /* size */
150 ffio_wfourcc(pb, "co64");
152 ffio_wfourcc(pb, "stco");
153 avio_wb32(pb, 0); /* version & flags */
154 avio_wb32(pb, track->chunkCount); /* entry count */
155 for (i = 0; i < track->entry; i++) {
156 if (!track->cluster[i].chunkNum)
159 avio_wb64(pb, track->cluster[i].pos + track->data_offset);
161 avio_wb32(pb, track->cluster[i].pos + track->data_offset);
163 return update_size(pb, pos);
166 /* Sample size atom */
167 static int mov_write_stsz_tag(AVIOContext *pb, MOVTrack *track)
170 int i, j, entries = 0, tst = -1, oldtst = -1;
172 int64_t pos = avio_tell(pb);
173 avio_wb32(pb, 0); /* size */
174 ffio_wfourcc(pb, "stsz");
175 avio_wb32(pb, 0); /* version & flags */
177 for (i = 0; i < track->entry; i++) {
178 tst = track->cluster[i].size / track->cluster[i].entries;
179 if (oldtst != -1 && tst != oldtst)
182 entries += track->cluster[i].entries;
184 if (equalChunks && track->entry) {
185 int sSize = track->entry ? track->cluster[0].size / track->cluster[0].entries : 0;
186 sSize = FFMAX(1, sSize); // adpcm mono case could make sSize == 0
187 avio_wb32(pb, sSize); // sample size
188 avio_wb32(pb, entries); // sample count
190 avio_wb32(pb, 0); // sample size
191 avio_wb32(pb, entries); // sample count
192 for (i = 0; i < track->entry; i++) {
193 for (j = 0; j < track->cluster[i].entries; j++) {
194 avio_wb32(pb, track->cluster[i].size /
195 track->cluster[i].entries);
199 return update_size(pb, pos);
202 /* Sample to chunk atom */
203 static int mov_write_stsc_tag(AVIOContext *pb, MOVTrack *track)
205 int index = 0, oldval = -1, i;
206 int64_t entryPos, curpos;
208 int64_t pos = avio_tell(pb);
209 avio_wb32(pb, 0); /* size */
210 ffio_wfourcc(pb, "stsc");
211 avio_wb32(pb, 0); // version & flags
212 entryPos = avio_tell(pb);
213 avio_wb32(pb, track->chunkCount); // entry count
214 for (i = 0; i < track->entry; i++) {
215 if (oldval != track->cluster[i].samples_in_chunk && track->cluster[i].chunkNum) {
216 avio_wb32(pb, track->cluster[i].chunkNum); // first chunk
217 avio_wb32(pb, track->cluster[i].samples_in_chunk); // samples per chunk
218 avio_wb32(pb, 0x1); // sample description index
219 oldval = track->cluster[i].samples_in_chunk;
223 curpos = avio_tell(pb);
224 avio_seek(pb, entryPos, SEEK_SET);
225 avio_wb32(pb, index); // rewrite size
226 avio_seek(pb, curpos, SEEK_SET);
228 return update_size(pb, pos);
231 /* Sync sample atom */
232 static int mov_write_stss_tag(AVIOContext *pb, MOVTrack *track, uint32_t flag)
234 int64_t curpos, entryPos;
236 int64_t pos = avio_tell(pb);
237 avio_wb32(pb, 0); // size
238 ffio_wfourcc(pb, flag == MOV_SYNC_SAMPLE ? "stss" : "stps");
239 avio_wb32(pb, 0); // version & flags
240 entryPos = avio_tell(pb);
241 avio_wb32(pb, track->entry); // entry count
242 for (i = 0; i < track->entry; i++) {
243 if (track->cluster[i].flags & flag) {
244 avio_wb32(pb, i + 1);
248 curpos = avio_tell(pb);
249 avio_seek(pb, entryPos, SEEK_SET);
250 avio_wb32(pb, index); // rewrite size
251 avio_seek(pb, curpos, SEEK_SET);
252 return update_size(pb, pos);
255 static int mov_write_amr_tag(AVIOContext *pb, MOVTrack *track)
257 avio_wb32(pb, 0x11); /* size */
258 if (track->mode == MODE_MOV) ffio_wfourcc(pb, "samr");
259 else ffio_wfourcc(pb, "damr");
260 ffio_wfourcc(pb, "FFMP");
261 avio_w8(pb, 0); /* decoder version */
263 avio_wb16(pb, 0x81FF); /* Mode set (all modes for AMR_NB) */
264 avio_w8(pb, 0x00); /* Mode change period (no restriction) */
265 avio_w8(pb, 0x01); /* Frames per sample */
269 static int mov_write_ac3_tag(AVIOContext *pb, MOVTrack *track)
274 int fscod, bsid, bsmod, acmod, lfeon, frmsizecod;
276 if (track->vos_len < 7)
280 ffio_wfourcc(pb, "dac3");
282 init_get_bits(&gbc, track->vos_data + 4, (track->vos_len - 4) * 8);
283 fscod = get_bits(&gbc, 2);
284 frmsizecod = get_bits(&gbc, 6);
285 bsid = get_bits(&gbc, 5);
286 bsmod = get_bits(&gbc, 3);
287 acmod = get_bits(&gbc, 3);
289 skip_bits(&gbc, 2); // dsurmod
291 if ((acmod & 1) && acmod != 1)
292 skip_bits(&gbc, 2); // cmixlev
294 skip_bits(&gbc, 2); // surmixlev
296 lfeon = get_bits1(&gbc);
298 init_put_bits(&pbc, buf, sizeof(buf));
299 put_bits(&pbc, 2, fscod);
300 put_bits(&pbc, 5, bsid);
301 put_bits(&pbc, 3, bsmod);
302 put_bits(&pbc, 3, acmod);
303 put_bits(&pbc, 1, lfeon);
304 put_bits(&pbc, 5, frmsizecod >> 1); // bit_rate_code
305 put_bits(&pbc, 5, 0); // reserved
307 flush_put_bits(&pbc);
308 avio_write(pb, buf, sizeof(buf));
318 /* Layout of the EC3SpecificBox */
319 /* maximum bitrate */
321 /* number of independent substreams */
324 /* sample rate code (see ff_ac3_sample_rate_tab) 2 bits */
326 /* bit stream identification 5 bits */
328 /* one bit reserved */
329 /* audio service mixing (not supported yet) 1 bit */
330 /* bit stream mode 3 bits */
332 /* audio coding mode 3 bits */
334 /* sub woofer on 1 bit */
336 /* 3 bits reserved */
337 /* number of dependent substreams associated with this substream 4 bits */
339 /* channel locations of the dependent substream(s), if any, 9 bits */
341 /* if there is no dependent substream, then one bit reserved instead */
342 } substream[1]; /* TODO: support 8 independent substreams */
345 #if CONFIG_AC3_PARSER
346 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 if (avpriv_ac3_parse_header(&hdr, pkt->data, pkt->size) < 0) {
357 /* drop the packets until we see a good one */
359 av_log(mov, AV_LOG_WARNING, "Dropping invalid packet from start of the stream\n");
362 return AVERROR_INVALIDDATA;
365 info->data_rate = FFMAX(info->data_rate, hdr->bit_rate / 1000);
366 num_blocks = hdr->num_blocks;
368 if (!info->ec3_done) {
369 /* AC-3 substream must be the first one */
370 if (hdr->bitstream_id <= 10 && hdr->substreamid != 0)
371 return AVERROR(EINVAL);
373 /* this should always be the case, given that our AC-3 parser
374 * concatenates dependent frames to their independent parent */
375 if (hdr->frame_type == EAC3_FRAME_TYPE_INDEPENDENT) {
376 /* substream ids must be incremental */
377 if (hdr->substreamid > info->num_ind_sub + 1)
378 return AVERROR(EINVAL);
380 if (hdr->substreamid == info->num_ind_sub + 1) {
381 //info->num_ind_sub++;
382 avpriv_request_sample(track->par, "Multiple independent substreams");
383 return AVERROR_PATCHWELCOME;
384 } else if (hdr->substreamid < info->num_ind_sub ||
385 hdr->substreamid == 0 && info->substream[0].bsid) {
391 /* fill the info needed for the "dec3" atom */
392 info->substream[hdr->substreamid].fscod = hdr->sr_code;
393 info->substream[hdr->substreamid].bsid = hdr->bitstream_id;
394 info->substream[hdr->substreamid].bsmod = hdr->bitstream_mode;
395 info->substream[hdr->substreamid].acmod = hdr->channel_mode;
396 info->substream[hdr->substreamid].lfeon = hdr->lfe_on;
398 /* Parse dependent substream(s), if any */
399 if (pkt->size != hdr->frame_size) {
400 int cumul_size = hdr->frame_size;
401 int parent = hdr->substreamid;
403 while (cumul_size != pkt->size) {
406 ret = avpriv_ac3_parse_header(&hdr, pkt->data + cumul_size, pkt->size - cumul_size);
408 return AVERROR_INVALIDDATA;
409 if (hdr->frame_type != EAC3_FRAME_TYPE_DEPENDENT)
410 return AVERROR(EINVAL);
411 info->substream[parent].num_dep_sub++;
414 /* header is parsed up to lfeon, but custom channel map may be needed */
415 init_get_bits8(&gbc, pkt->data + cumul_size + ret, pkt->size - cumul_size - ret);
418 /* skip volume control params */
419 for (i = 0; i < (hdr->channel_mode ? 1 : 2); i++) {
420 skip_bits(&gbc, 5); // skip dialog normalization
421 if (get_bits1(&gbc)) {
422 skip_bits(&gbc, 8); // skip compression gain word
425 /* get the dependent stream channel map, if exists */
427 info->substream[parent].chan_loc |= (get_bits(&gbc, 16) >> 5) & 0x1f;
429 info->substream[parent].chan_loc |= hdr->channel_mode;
430 cumul_size += hdr->frame_size;
436 if (!info->num_blocks && num_blocks == 6)
438 else if (info->num_blocks + num_blocks > 6)
439 return AVERROR_INVALIDDATA;
441 if (!info->num_blocks) {
442 int ret = av_packet_ref(&info->pkt, pkt);
445 info->num_blocks = num_blocks;
449 if ((ret = av_grow_packet(&info->pkt, pkt->size)) < 0)
451 memcpy(info->pkt.data + info->pkt.size - pkt->size, pkt->data, pkt->size);
452 info->num_blocks += num_blocks;
453 info->pkt.duration += pkt->duration;
454 if ((ret = av_copy_packet_side_data(&info->pkt, pkt)) < 0)
456 if (info->num_blocks != 6)
458 av_packet_unref(pkt);
459 ret = av_packet_ref(pkt, &info->pkt);
462 av_packet_unref(&info->pkt);
463 info->num_blocks = 0;
470 static int mov_write_eac3_tag(AVIOContext *pb, MOVTrack *track)
474 struct eac3_info *info;
477 if (!track->eac3_priv)
478 return AVERROR(EINVAL);
480 info = track->eac3_priv;
481 size = 2 + 4 * (info->num_ind_sub + 1);
482 buf = av_malloc(size);
484 size = AVERROR(ENOMEM);
488 init_put_bits(&pbc, buf, size);
489 put_bits(&pbc, 13, info->data_rate);
490 put_bits(&pbc, 3, info->num_ind_sub);
491 for (i = 0; i <= info->num_ind_sub; i++) {
492 put_bits(&pbc, 2, info->substream[i].fscod);
493 put_bits(&pbc, 5, info->substream[i].bsid);
494 put_bits(&pbc, 1, 0); /* reserved */
495 put_bits(&pbc, 1, 0); /* asvc */
496 put_bits(&pbc, 3, info->substream[i].bsmod);
497 put_bits(&pbc, 3, info->substream[i].acmod);
498 put_bits(&pbc, 1, info->substream[i].lfeon);
499 put_bits(&pbc, 5, 0); /* reserved */
500 put_bits(&pbc, 4, info->substream[i].num_dep_sub);
501 if (!info->substream[i].num_dep_sub) {
502 put_bits(&pbc, 1, 0); /* reserved */
505 put_bits(&pbc, 9, info->substream[i].chan_loc);
508 flush_put_bits(&pbc);
510 avio_wb32(pb, size + 8);
511 ffio_wfourcc(pb, "dec3");
512 avio_write(pb, buf, size);
517 av_packet_unref(&info->pkt);
518 av_freep(&track->eac3_priv);
524 * This function writes extradata "as is".
525 * Extradata must be formatted like a valid atom (with size and tag).
527 static int mov_write_extradata_tag(AVIOContext *pb, MOVTrack *track)
529 avio_write(pb, track->par->extradata, track->par->extradata_size);
530 return track->par->extradata_size;
533 static int mov_write_enda_tag(AVIOContext *pb)
536 ffio_wfourcc(pb, "enda");
537 avio_wb16(pb, 1); /* little endian */
541 static int mov_write_enda_tag_be(AVIOContext *pb)
544 ffio_wfourcc(pb, "enda");
545 avio_wb16(pb, 0); /* big endian */
549 static void put_descr(AVIOContext *pb, int tag, unsigned int size)
554 avio_w8(pb, (size >> (7 * i)) | 0x80);
555 avio_w8(pb, size & 0x7F);
558 static unsigned compute_avg_bitrate(MOVTrack *track)
562 if (!track->track_duration)
564 for (i = 0; i < track->entry; i++)
565 size += track->cluster[i].size;
566 return size * 8 * track->timescale / track->track_duration;
569 static int mov_write_esds_tag(AVIOContext *pb, MOVTrack *track) // Basic
571 AVCPBProperties *props;
572 int64_t pos = avio_tell(pb);
573 int decoder_specific_info_len = track->vos_len ? 5 + track->vos_len : 0;
574 unsigned avg_bitrate;
576 avio_wb32(pb, 0); // size
577 ffio_wfourcc(pb, "esds");
578 avio_wb32(pb, 0); // Version
581 put_descr(pb, 0x03, 3 + 5+13 + decoder_specific_info_len + 5+1);
582 avio_wb16(pb, track->track_id);
583 avio_w8(pb, 0x00); // flags (= no flags)
585 // DecoderConfig descriptor
586 put_descr(pb, 0x04, 13 + decoder_specific_info_len);
588 // Object type indication
589 if ((track->par->codec_id == AV_CODEC_ID_MP2 ||
590 track->par->codec_id == AV_CODEC_ID_MP3) &&
591 track->par->sample_rate > 24000)
592 avio_w8(pb, 0x6B); // 11172-3
594 avio_w8(pb, ff_codec_get_tag(ff_mp4_obj_type, track->par->codec_id));
596 // the following fields is made of 6 bits to identify the streamtype (4 for video, 5 for audio)
597 // plus 1 bit to indicate upstream and 1 bit set to 1 (reserved)
598 if (track->par->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
599 avio_w8(pb, (0x38 << 2) | 1); // flags (= NeroSubpicStream)
600 else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
601 avio_w8(pb, 0x15); // flags (= Audiostream)
603 avio_w8(pb, 0x11); // flags (= Visualstream)
605 props = (AVCPBProperties*)av_stream_get_side_data(track->st, AV_PKT_DATA_CPB_PROPERTIES,
608 avio_wb24(pb, props ? props->buffer_size / 8 : 0); // Buffersize DB
610 avg_bitrate = compute_avg_bitrate(track);
611 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)
612 avio_wb32(pb, avg_bitrate);
614 if (track->vos_len) {
615 // DecoderSpecific info descriptor
616 put_descr(pb, 0x05, track->vos_len);
617 avio_write(pb, track->vos_data, track->vos_len);
621 put_descr(pb, 0x06, 1);
623 return update_size(pb, pos);
626 static int mov_pcm_le_gt16(enum AVCodecID codec_id)
628 return codec_id == AV_CODEC_ID_PCM_S24LE ||
629 codec_id == AV_CODEC_ID_PCM_S32LE ||
630 codec_id == AV_CODEC_ID_PCM_F32LE ||
631 codec_id == AV_CODEC_ID_PCM_F64LE;
634 static int mov_pcm_be_gt16(enum AVCodecID codec_id)
636 return codec_id == AV_CODEC_ID_PCM_S24BE ||
637 codec_id == AV_CODEC_ID_PCM_S32BE ||
638 codec_id == AV_CODEC_ID_PCM_F32BE ||
639 codec_id == AV_CODEC_ID_PCM_F64BE;
642 static int mov_write_ms_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
645 int64_t pos = avio_tell(pb);
647 avio_wl32(pb, track->tag); // store it byteswapped
648 track->par->codec_tag = av_bswap16(track->tag >> 16);
649 if ((ret = ff_put_wav_header(s, pb, track->par, 0)) < 0)
651 return update_size(pb, pos);
654 static int mov_write_wfex_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
657 int64_t pos = avio_tell(pb);
659 ffio_wfourcc(pb, "wfex");
660 if ((ret = ff_put_wav_header(s, pb, track->st->codecpar, FF_PUT_WAV_HEADER_FORCE_WAVEFORMATEX)) < 0)
662 return update_size(pb, pos);
665 static int mov_write_dfla_tag(AVIOContext *pb, MOVTrack *track)
667 int64_t pos = avio_tell(pb);
669 ffio_wfourcc(pb, "dfLa");
670 avio_w8(pb, 0); /* version */
671 avio_wb24(pb, 0); /* flags */
673 /* Expect the encoder to pass a METADATA_BLOCK_TYPE_STREAMINFO. */
674 if (track->par->extradata_size != FLAC_STREAMINFO_SIZE)
675 return AVERROR_INVALIDDATA;
677 /* TODO: Write other METADATA_BLOCK_TYPEs if the encoder makes them available. */
678 avio_w8(pb, 1 << 7 | FLAC_METADATA_TYPE_STREAMINFO); /* LastMetadataBlockFlag << 7 | BlockType */
679 avio_wb24(pb, track->par->extradata_size); /* Length */
680 avio_write(pb, track->par->extradata, track->par->extradata_size); /* BlockData[Length] */
682 return update_size(pb, pos);
685 static int mov_write_dops_tag(AVIOContext *pb, MOVTrack *track)
687 int64_t pos = avio_tell(pb);
689 ffio_wfourcc(pb, "dOps");
690 avio_w8(pb, 0); /* Version */
691 if (track->par->extradata_size < 19) {
692 av_log(pb, AV_LOG_ERROR, "invalid extradata size\n");
693 return AVERROR_INVALIDDATA;
695 /* extradata contains an Ogg OpusHead, other than byte-ordering and
696 OpusHead's preceeding magic/version, OpusSpecificBox is currently
698 avio_w8(pb, AV_RB8(track->par->extradata + 9)); /* OuputChannelCount */
699 avio_wb16(pb, AV_RL16(track->par->extradata + 10)); /* PreSkip */
700 avio_wb32(pb, AV_RL32(track->par->extradata + 12)); /* InputSampleRate */
701 avio_wb16(pb, AV_RL16(track->par->extradata + 16)); /* OutputGain */
702 /* Write the rest of the header out without byte-swapping. */
703 avio_write(pb, track->par->extradata + 18, track->par->extradata_size - 18);
705 return update_size(pb, pos);
708 static int mov_write_chan_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
710 uint32_t layout_tag, bitmap;
711 int64_t pos = avio_tell(pb);
713 layout_tag = ff_mov_get_channel_layout_tag(track->par->codec_id,
714 track->par->channel_layout,
717 av_log(s, AV_LOG_WARNING, "not writing 'chan' tag due to "
718 "lack of channel information\n");
722 if (track->multichannel_as_mono)
725 avio_wb32(pb, 0); // Size
726 ffio_wfourcc(pb, "chan"); // Type
727 avio_w8(pb, 0); // Version
728 avio_wb24(pb, 0); // Flags
729 avio_wb32(pb, layout_tag); // mChannelLayoutTag
730 avio_wb32(pb, bitmap); // mChannelBitmap
731 avio_wb32(pb, 0); // mNumberChannelDescriptions
733 return update_size(pb, pos);
736 static int mov_write_wave_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
738 int64_t pos = avio_tell(pb);
740 avio_wb32(pb, 0); /* size */
741 ffio_wfourcc(pb, "wave");
743 if (track->par->codec_id != AV_CODEC_ID_QDM2) {
744 avio_wb32(pb, 12); /* size */
745 ffio_wfourcc(pb, "frma");
746 avio_wl32(pb, track->tag);
749 if (track->par->codec_id == AV_CODEC_ID_AAC) {
750 /* useless atom needed by mplayer, ipod, not needed by quicktime */
751 avio_wb32(pb, 12); /* size */
752 ffio_wfourcc(pb, "mp4a");
754 mov_write_esds_tag(pb, track);
755 } else if (mov_pcm_le_gt16(track->par->codec_id)) {
756 mov_write_enda_tag(pb);
757 } else if (mov_pcm_be_gt16(track->par->codec_id)) {
758 mov_write_enda_tag_be(pb);
759 } else if (track->par->codec_id == AV_CODEC_ID_AMR_NB) {
760 mov_write_amr_tag(pb, track);
761 } else if (track->par->codec_id == AV_CODEC_ID_AC3) {
762 mov_write_ac3_tag(pb, track);
763 } else if (track->par->codec_id == AV_CODEC_ID_EAC3) {
764 mov_write_eac3_tag(pb, track);
765 } else if (track->par->codec_id == AV_CODEC_ID_ALAC ||
766 track->par->codec_id == AV_CODEC_ID_QDM2) {
767 mov_write_extradata_tag(pb, track);
768 } else if (track->par->codec_id == AV_CODEC_ID_ADPCM_MS ||
769 track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) {
770 mov_write_ms_tag(s, pb, track);
773 avio_wb32(pb, 8); /* size */
774 avio_wb32(pb, 0); /* null tag */
776 return update_size(pb, pos);
779 static int mov_write_dvc1_structs(MOVTrack *track, uint8_t *buf)
782 const uint8_t *start, *next, *end = track->vos_data + track->vos_len;
783 int unescaped_size, seq_found = 0;
784 int level = 0, interlace = 0;
785 int packet_seq = track->vc1_info.packet_seq;
786 int packet_entry = track->vc1_info.packet_entry;
787 int slices = track->vc1_info.slices;
790 if (track->start_dts == AV_NOPTS_VALUE) {
791 /* No packets written yet, vc1_info isn't authoritative yet. */
792 /* Assume inline sequence and entry headers. */
793 packet_seq = packet_entry = 1;
794 av_log(NULL, AV_LOG_WARNING,
795 "moov atom written before any packets, unable to write correct "
796 "dvc1 atom. Set the delay_moov flag to fix this.\n");
799 unescaped = av_mallocz(track->vos_len + AV_INPUT_BUFFER_PADDING_SIZE);
801 return AVERROR(ENOMEM);
802 start = find_next_marker(track->vos_data, end);
803 for (next = start; next < end; start = next) {
806 next = find_next_marker(start + 4, end);
807 size = next - start - 4;
810 unescaped_size = vc1_unescape_buffer(start + 4, size, unescaped);
811 init_get_bits(&gb, unescaped, 8 * unescaped_size);
812 if (AV_RB32(start) == VC1_CODE_SEQHDR) {
813 int profile = get_bits(&gb, 2);
814 if (profile != PROFILE_ADVANCED) {
816 return AVERROR(ENOSYS);
819 level = get_bits(&gb, 3);
820 /* chromaformat, frmrtq_postproc, bitrtq_postproc, postprocflag,
822 skip_bits_long(&gb, 2 + 3 + 5 + 1 + 2*12);
823 skip_bits(&gb, 1); /* broadcast */
824 interlace = get_bits1(&gb);
825 skip_bits(&gb, 4); /* tfcntrflag, finterpflag, reserved, psf */
830 return AVERROR(ENOSYS);
833 init_put_bits(&pbc, buf, 7);
834 /* VC1DecSpecStruc */
835 put_bits(&pbc, 4, 12); /* profile - advanced */
836 put_bits(&pbc, 3, level);
837 put_bits(&pbc, 1, 0); /* reserved */
838 /* VC1AdvDecSpecStruc */
839 put_bits(&pbc, 3, level);
840 put_bits(&pbc, 1, 0); /* cbr */
841 put_bits(&pbc, 6, 0); /* reserved */
842 put_bits(&pbc, 1, !interlace); /* no interlace */
843 put_bits(&pbc, 1, !packet_seq); /* no multiple seq */
844 put_bits(&pbc, 1, !packet_entry); /* no multiple entry */
845 put_bits(&pbc, 1, !slices); /* no slice code */
846 put_bits(&pbc, 1, 0); /* no bframe */
847 put_bits(&pbc, 1, 0); /* reserved */
850 if (track->st->avg_frame_rate.num > 0 && track->st->avg_frame_rate.den > 0)
851 put_bits32(&pbc, track->st->avg_frame_rate.num / track->st->avg_frame_rate.den);
853 put_bits32(&pbc, 0xffffffff);
855 flush_put_bits(&pbc);
862 static int mov_write_dvc1_tag(AVIOContext *pb, MOVTrack *track)
864 uint8_t buf[7] = { 0 };
867 if ((ret = mov_write_dvc1_structs(track, buf)) < 0)
870 avio_wb32(pb, track->vos_len + 8 + sizeof(buf));
871 ffio_wfourcc(pb, "dvc1");
872 avio_write(pb, buf, sizeof(buf));
873 avio_write(pb, track->vos_data, track->vos_len);
878 static int mov_write_glbl_tag(AVIOContext *pb, MOVTrack *track)
880 avio_wb32(pb, track->vos_len + 8);
881 ffio_wfourcc(pb, "glbl");
882 avio_write(pb, track->vos_data, track->vos_len);
883 return 8 + track->vos_len;
887 * Compute flags for 'lpcm' tag.
888 * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
890 static int mov_get_lpcm_flags(enum AVCodecID codec_id)
893 case AV_CODEC_ID_PCM_F32BE:
894 case AV_CODEC_ID_PCM_F64BE:
896 case AV_CODEC_ID_PCM_F32LE:
897 case AV_CODEC_ID_PCM_F64LE:
899 case AV_CODEC_ID_PCM_U8:
901 case AV_CODEC_ID_PCM_S16BE:
902 case AV_CODEC_ID_PCM_S24BE:
903 case AV_CODEC_ID_PCM_S32BE:
905 case AV_CODEC_ID_PCM_S8:
906 case AV_CODEC_ID_PCM_S16LE:
907 case AV_CODEC_ID_PCM_S24LE:
908 case AV_CODEC_ID_PCM_S32LE:
915 static int get_cluster_duration(MOVTrack *track, int cluster_idx)
919 if (cluster_idx >= track->entry)
922 if (cluster_idx + 1 == track->entry)
923 next_dts = track->track_duration + track->start_dts;
925 next_dts = track->cluster[cluster_idx + 1].dts;
927 next_dts -= track->cluster[cluster_idx].dts;
929 av_assert0(next_dts >= 0);
930 av_assert0(next_dts <= INT_MAX);
935 static int get_samples_per_packet(MOVTrack *track)
937 int i, first_duration;
939 // return track->par->frame_size;
941 /* use 1 for raw PCM */
942 if (!track->audio_vbr)
945 /* check to see if duration is constant for all clusters */
948 first_duration = get_cluster_duration(track, 0);
949 for (i = 1; i < track->entry; i++) {
950 if (get_cluster_duration(track, i) != first_duration)
953 return first_duration;
956 static int mov_write_audio_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
958 int64_t pos = avio_tell(pb);
960 uint32_t tag = track->tag;
962 if (track->mode == MODE_MOV) {
963 if (track->timescale > UINT16_MAX) {
964 if (mov_get_lpcm_flags(track->par->codec_id))
965 tag = AV_RL32("lpcm");
967 } else if (track->audio_vbr || mov_pcm_le_gt16(track->par->codec_id) ||
968 mov_pcm_be_gt16(track->par->codec_id) ||
969 track->par->codec_id == AV_CODEC_ID_ADPCM_MS ||
970 track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
971 track->par->codec_id == AV_CODEC_ID_QDM2) {
976 avio_wb32(pb, 0); /* size */
977 if (mov->encryption_scheme != MOV_ENC_NONE) {
978 ffio_wfourcc(pb, "enca");
980 avio_wl32(pb, tag); // store it byteswapped
982 avio_wb32(pb, 0); /* Reserved */
983 avio_wb16(pb, 0); /* Reserved */
984 avio_wb16(pb, 1); /* Data-reference index, XXX == 1 */
986 /* SoundDescription */
987 avio_wb16(pb, version); /* Version */
988 avio_wb16(pb, 0); /* Revision level */
989 avio_wb32(pb, 0); /* Reserved */
994 avio_wb16(pb, 0xfffe);
996 avio_wb32(pb, 0x00010000);
998 avio_wb64(pb, av_double2int(track->par->sample_rate));
999 avio_wb32(pb, track->par->channels);
1000 avio_wb32(pb, 0x7F000000);
1001 avio_wb32(pb, av_get_bits_per_sample(track->par->codec_id));
1002 avio_wb32(pb, mov_get_lpcm_flags(track->par->codec_id));
1003 avio_wb32(pb, track->sample_size);
1004 avio_wb32(pb, get_samples_per_packet(track));
1006 if (track->mode == MODE_MOV) {
1007 avio_wb16(pb, track->par->channels);
1008 if (track->par->codec_id == AV_CODEC_ID_PCM_U8 ||
1009 track->par->codec_id == AV_CODEC_ID_PCM_S8)
1010 avio_wb16(pb, 8); /* bits per sample */
1011 else if (track->par->codec_id == AV_CODEC_ID_ADPCM_G726)
1012 avio_wb16(pb, track->par->bits_per_coded_sample);
1015 avio_wb16(pb, track->audio_vbr ? -2 : 0); /* compression ID */
1016 } else { /* reserved for mp4/3gp */
1017 if (track->par->codec_id == AV_CODEC_ID_FLAC ||
1018 track->par->codec_id == AV_CODEC_ID_OPUS) {
1019 avio_wb16(pb, track->par->channels);
1023 if (track->par->codec_id == AV_CODEC_ID_FLAC) {
1024 avio_wb16(pb, track->par->bits_per_raw_sample);
1031 avio_wb16(pb, 0); /* packet size (= 0) */
1032 if (track->par->codec_id == AV_CODEC_ID_OPUS)
1033 avio_wb16(pb, 48000);
1035 avio_wb16(pb, track->par->sample_rate <= UINT16_MAX ?
1036 track->par->sample_rate : 0);
1037 avio_wb16(pb, 0); /* Reserved */
1040 if (version == 1) { /* SoundDescription V1 extended info */
1041 if (mov_pcm_le_gt16(track->par->codec_id) ||
1042 mov_pcm_be_gt16(track->par->codec_id))
1043 avio_wb32(pb, 1); /* must be 1 for uncompressed formats */
1045 avio_wb32(pb, track->par->frame_size); /* Samples per packet */
1046 avio_wb32(pb, track->sample_size / track->par->channels); /* Bytes per packet */
1047 avio_wb32(pb, track->sample_size); /* Bytes per frame */
1048 avio_wb32(pb, 2); /* Bytes per sample */
1051 if (track->mode == MODE_MOV &&
1052 (track->par->codec_id == AV_CODEC_ID_AAC ||
1053 track->par->codec_id == AV_CODEC_ID_AC3 ||
1054 track->par->codec_id == AV_CODEC_ID_EAC3 ||
1055 track->par->codec_id == AV_CODEC_ID_AMR_NB ||
1056 track->par->codec_id == AV_CODEC_ID_ALAC ||
1057 track->par->codec_id == AV_CODEC_ID_ADPCM_MS ||
1058 track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
1059 track->par->codec_id == AV_CODEC_ID_QDM2 ||
1060 (mov_pcm_le_gt16(track->par->codec_id) && version==1) ||
1061 (mov_pcm_be_gt16(track->par->codec_id) && version==1)))
1062 mov_write_wave_tag(s, pb, track);
1063 else if (track->tag == MKTAG('m','p','4','a'))
1064 mov_write_esds_tag(pb, track);
1065 else if (track->par->codec_id == AV_CODEC_ID_AMR_NB)
1066 mov_write_amr_tag(pb, track);
1067 else if (track->par->codec_id == AV_CODEC_ID_AC3)
1068 mov_write_ac3_tag(pb, track);
1069 else if (track->par->codec_id == AV_CODEC_ID_EAC3)
1070 mov_write_eac3_tag(pb, track);
1071 else if (track->par->codec_id == AV_CODEC_ID_ALAC)
1072 mov_write_extradata_tag(pb, track);
1073 else if (track->par->codec_id == AV_CODEC_ID_WMAPRO)
1074 mov_write_wfex_tag(s, pb, track);
1075 else if (track->par->codec_id == AV_CODEC_ID_FLAC)
1076 mov_write_dfla_tag(pb, track);
1077 else if (track->par->codec_id == AV_CODEC_ID_OPUS)
1078 mov_write_dops_tag(pb, track);
1079 else if (track->vos_len > 0)
1080 mov_write_glbl_tag(pb, track);
1082 if (track->mode == MODE_MOV && track->par->codec_type == AVMEDIA_TYPE_AUDIO)
1083 mov_write_chan_tag(s, pb, track);
1085 if (mov->encryption_scheme != MOV_ENC_NONE) {
1086 ff_mov_cenc_write_sinf_tag(track, pb, mov->encryption_kid);
1089 return update_size(pb, pos);
1092 static int mov_write_d263_tag(AVIOContext *pb)
1094 avio_wb32(pb, 0xf); /* size */
1095 ffio_wfourcc(pb, "d263");
1096 ffio_wfourcc(pb, "FFMP");
1097 avio_w8(pb, 0); /* decoder version */
1098 /* FIXME use AVCodecContext level/profile, when encoder will set values */
1099 avio_w8(pb, 0xa); /* level */
1100 avio_w8(pb, 0); /* profile */
1104 static int mov_write_avcc_tag(AVIOContext *pb, MOVTrack *track)
1106 int64_t pos = avio_tell(pb);
1109 ffio_wfourcc(pb, "avcC");
1110 ff_isom_write_avcc(pb, track->vos_data, track->vos_len);
1111 return update_size(pb, pos);
1114 static int mov_write_vpcc_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
1116 int64_t pos = avio_tell(pb);
1119 ffio_wfourcc(pb, "vpcC");
1120 avio_w8(pb, 1); /* version */
1121 avio_wb24(pb, 0); /* flags */
1122 ff_isom_write_vpcc(s, pb, track->par);
1123 return update_size(pb, pos);
1126 static int mov_write_hvcc_tag(AVIOContext *pb, MOVTrack *track)
1128 int64_t pos = avio_tell(pb);
1131 ffio_wfourcc(pb, "hvcC");
1132 if (track->tag == MKTAG('h','v','c','1'))
1133 ff_isom_write_hvcc(pb, track->vos_data, track->vos_len, 1);
1135 ff_isom_write_hvcc(pb, track->vos_data, track->vos_len, 0);
1136 return update_size(pb, pos);
1139 /* also used by all avid codecs (dv, imx, meridien) and their variants */
1140 static int mov_write_avid_tag(AVIOContext *pb, MOVTrack *track)
1145 int display_width = track->par->width;
1147 if (track->vos_data && track->vos_len > 0x29) {
1148 if (ff_dnxhd_parse_header_prefix(track->vos_data) != 0) {
1149 /* looks like a DNxHD bit stream */
1150 interlaced = (track->vos_data[5] & 2);
1151 cid = AV_RB32(track->vos_data + 0x28);
1153 av_log(NULL, AV_LOG_WARNING, "Could not locate DNxHD bit stream in vos_data\n");
1157 av_log(NULL, AV_LOG_WARNING, "Could not locate DNxHD bit stream, vos_data too small\n");
1161 avio_wb32(pb, 24); /* size */
1162 ffio_wfourcc(pb, "ACLR");
1163 ffio_wfourcc(pb, "ACLR");
1164 ffio_wfourcc(pb, "0001");
1165 if (track->par->color_range == AVCOL_RANGE_MPEG || /* Legal range (16-235) */
1166 track->par->color_range == AVCOL_RANGE_UNSPECIFIED) {
1167 avio_wb32(pb, 1); /* Corresponds to 709 in official encoder */
1168 } else { /* Full range (0-255) */
1169 avio_wb32(pb, 2); /* Corresponds to RGB in official encoder */
1171 avio_wb32(pb, 0); /* unknown */
1173 if (track->tag == MKTAG('A','V','d','h')) {
1175 ffio_wfourcc(pb, "ADHR");
1176 ffio_wfourcc(pb, "0001");
1178 avio_wb32(pb, 0); /* unknown */
1179 avio_wb32(pb, 1); /* unknown */
1180 avio_wb32(pb, 0); /* unknown */
1181 avio_wb32(pb, 0); /* unknown */
1185 avio_wb32(pb, 24); /* size */
1186 ffio_wfourcc(pb, "APRG");
1187 ffio_wfourcc(pb, "APRG");
1188 ffio_wfourcc(pb, "0001");
1189 avio_wb32(pb, 1); /* unknown */
1190 avio_wb32(pb, 0); /* unknown */
1192 avio_wb32(pb, 120); /* size */
1193 ffio_wfourcc(pb, "ARES");
1194 ffio_wfourcc(pb, "ARES");
1195 ffio_wfourcc(pb, "0001");
1196 avio_wb32(pb, cid); /* dnxhd cid, some id ? */
1197 if ( track->par->sample_aspect_ratio.num > 0
1198 && track->par->sample_aspect_ratio.den > 0)
1199 display_width = display_width * track->par->sample_aspect_ratio.num / track->par->sample_aspect_ratio.den;
1200 avio_wb32(pb, display_width);
1201 /* values below are based on samples created with quicktime and avid codecs */
1203 avio_wb32(pb, track->par->height / 2);
1204 avio_wb32(pb, 2); /* unknown */
1205 avio_wb32(pb, 0); /* unknown */
1206 avio_wb32(pb, 4); /* unknown */
1208 avio_wb32(pb, track->par->height);
1209 avio_wb32(pb, 1); /* unknown */
1210 avio_wb32(pb, 0); /* unknown */
1211 if (track->par->height == 1080)
1212 avio_wb32(pb, 5); /* unknown */
1214 avio_wb32(pb, 6); /* unknown */
1217 for (i = 0; i < 10; i++)
1223 static int mov_write_dpxe_tag(AVIOContext *pb, MOVTrack *track)
1226 ffio_wfourcc(pb, "DpxE");
1227 if (track->par->extradata_size >= 12 &&
1228 !memcmp(&track->par->extradata[4], "DpxE", 4)) {
1229 avio_wb32(pb, track->par->extradata[11]);
1236 static int mov_get_dv_codec_tag(AVFormatContext *s, MOVTrack *track)
1240 if (track->par->width == 720) { /* SD */
1241 if (track->par->height == 480) { /* NTSC */
1242 if (track->par->format == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','n');
1243 else tag = MKTAG('d','v','c',' ');
1244 }else if (track->par->format == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','p');
1245 else if (track->par->format == AV_PIX_FMT_YUV420P) tag = MKTAG('d','v','c','p');
1246 else tag = MKTAG('d','v','p','p');
1247 } else if (track->par->height == 720) { /* HD 720 line */
1248 if (track->st->time_base.den == 50) tag = MKTAG('d','v','h','q');
1249 else tag = MKTAG('d','v','h','p');
1250 } else if (track->par->height == 1080) { /* HD 1080 line */
1251 if (track->st->time_base.den == 25) tag = MKTAG('d','v','h','5');
1252 else tag = MKTAG('d','v','h','6');
1254 av_log(s, AV_LOG_ERROR, "unsupported height for dv codec\n");
1261 static AVRational find_fps(AVFormatContext *s, AVStream *st)
1263 AVRational rate = st->avg_frame_rate;
1265 #if FF_API_LAVF_AVCTX
1266 FF_DISABLE_DEPRECATION_WARNINGS
1267 rate = av_inv_q(st->codec->time_base);
1268 if (av_timecode_check_frame_rate(rate) < 0) {
1269 av_log(s, AV_LOG_DEBUG, "timecode: tbc=%d/%d invalid, fallback on %d/%d\n",
1270 rate.num, rate.den, st->avg_frame_rate.num, st->avg_frame_rate.den);
1271 rate = st->avg_frame_rate;
1273 FF_ENABLE_DEPRECATION_WARNINGS
1279 static int defined_frame_rate(AVFormatContext *s, AVStream *st)
1281 AVRational rational_framerate = find_fps(s, st);
1283 if (rational_framerate.den != 0)
1284 rate = av_q2d(rational_framerate);
1288 static int mov_get_mpeg2_xdcam_codec_tag(AVFormatContext *s, MOVTrack *track)
1290 int tag = track->par->codec_tag;
1291 int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE;
1292 AVStream *st = track->st;
1293 int rate = defined_frame_rate(s, st);
1296 tag = MKTAG('m', '2', 'v', '1'); //fallback tag
1298 if (track->par->format == AV_PIX_FMT_YUV420P) {
1299 if (track->par->width == 1280 && track->par->height == 720) {
1301 if (rate == 24) tag = MKTAG('x','d','v','4');
1302 else if (rate == 25) tag = MKTAG('x','d','v','5');
1303 else if (rate == 30) tag = MKTAG('x','d','v','1');
1304 else if (rate == 50) tag = MKTAG('x','d','v','a');
1305 else if (rate == 60) tag = MKTAG('x','d','v','9');
1307 } else if (track->par->width == 1440 && track->par->height == 1080) {
1309 if (rate == 24) tag = MKTAG('x','d','v','6');
1310 else if (rate == 25) tag = MKTAG('x','d','v','7');
1311 else if (rate == 30) tag = MKTAG('x','d','v','8');
1313 if (rate == 25) tag = MKTAG('x','d','v','3');
1314 else if (rate == 30) tag = MKTAG('x','d','v','2');
1316 } else if (track->par->width == 1920 && track->par->height == 1080) {
1318 if (rate == 24) tag = MKTAG('x','d','v','d');
1319 else if (rate == 25) tag = MKTAG('x','d','v','e');
1320 else if (rate == 30) tag = MKTAG('x','d','v','f');
1322 if (rate == 25) tag = MKTAG('x','d','v','c');
1323 else if (rate == 30) tag = MKTAG('x','d','v','b');
1326 } else if (track->par->format == AV_PIX_FMT_YUV422P) {
1327 if (track->par->width == 1280 && track->par->height == 720) {
1329 if (rate == 24) tag = MKTAG('x','d','5','4');
1330 else if (rate == 25) tag = MKTAG('x','d','5','5');
1331 else if (rate == 30) tag = MKTAG('x','d','5','1');
1332 else if (rate == 50) tag = MKTAG('x','d','5','a');
1333 else if (rate == 60) tag = MKTAG('x','d','5','9');
1335 } else if (track->par->width == 1920 && track->par->height == 1080) {
1337 if (rate == 24) tag = MKTAG('x','d','5','d');
1338 else if (rate == 25) tag = MKTAG('x','d','5','e');
1339 else if (rate == 30) tag = MKTAG('x','d','5','f');
1341 if (rate == 25) tag = MKTAG('x','d','5','c');
1342 else if (rate == 30) tag = MKTAG('x','d','5','b');
1350 static int mov_get_h264_codec_tag(AVFormatContext *s, MOVTrack *track)
1352 int tag = track->par->codec_tag;
1353 int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE;
1354 AVStream *st = track->st;
1355 int rate = defined_frame_rate(s, st);
1358 tag = MKTAG('a', 'v', 'c', 'i'); //fallback tag
1360 if (track->par->format == AV_PIX_FMT_YUV420P10) {
1361 if (track->par->width == 960 && track->par->height == 720) {
1363 if (rate == 24) tag = MKTAG('a','i','5','p');
1364 else if (rate == 25) tag = MKTAG('a','i','5','q');
1365 else if (rate == 30) tag = MKTAG('a','i','5','p');
1366 else if (rate == 50) tag = MKTAG('a','i','5','q');
1367 else if (rate == 60) tag = MKTAG('a','i','5','p');
1369 } else if (track->par->width == 1440 && track->par->height == 1080) {
1371 if (rate == 24) tag = MKTAG('a','i','5','3');
1372 else if (rate == 25) tag = MKTAG('a','i','5','2');
1373 else if (rate == 30) tag = MKTAG('a','i','5','3');
1375 if (rate == 50) tag = MKTAG('a','i','5','5');
1376 else if (rate == 60) tag = MKTAG('a','i','5','6');
1379 } else if (track->par->format == AV_PIX_FMT_YUV422P10) {
1380 if (track->par->width == 1280 && track->par->height == 720) {
1382 if (rate == 24) tag = MKTAG('a','i','1','p');
1383 else if (rate == 25) tag = MKTAG('a','i','1','q');
1384 else if (rate == 30) tag = MKTAG('a','i','1','p');
1385 else if (rate == 50) tag = MKTAG('a','i','1','q');
1386 else if (rate == 60) tag = MKTAG('a','i','1','p');
1388 } else if (track->par->width == 1920 && track->par->height == 1080) {
1390 if (rate == 24) tag = MKTAG('a','i','1','3');
1391 else if (rate == 25) tag = MKTAG('a','i','1','2');
1392 else if (rate == 30) tag = MKTAG('a','i','1','3');
1394 if (rate == 25) tag = MKTAG('a','i','1','5');
1395 else if (rate == 50) tag = MKTAG('a','i','1','5');
1396 else if (rate == 60) tag = MKTAG('a','i','1','6');
1398 } else if ( track->par->width == 4096 && track->par->height == 2160
1399 || track->par->width == 3840 && track->par->height == 2160
1400 || track->par->width == 2048 && track->par->height == 1080) {
1401 tag = MKTAG('a','i','v','x');
1408 static const struct {
1409 enum AVPixelFormat pix_fmt;
1412 } mov_pix_fmt_tags[] = {
1413 { AV_PIX_FMT_YUYV422, MKTAG('y','u','v','2'), 0 },
1414 { AV_PIX_FMT_YUYV422, MKTAG('y','u','v','s'), 0 },
1415 { AV_PIX_FMT_UYVY422, MKTAG('2','v','u','y'), 0 },
1416 { AV_PIX_FMT_RGB555BE,MKTAG('r','a','w',' '), 16 },
1417 { AV_PIX_FMT_RGB555LE,MKTAG('L','5','5','5'), 16 },
1418 { AV_PIX_FMT_RGB565LE,MKTAG('L','5','6','5'), 16 },
1419 { AV_PIX_FMT_RGB565BE,MKTAG('B','5','6','5'), 16 },
1420 { AV_PIX_FMT_GRAY16BE,MKTAG('b','1','6','g'), 16 },
1421 { AV_PIX_FMT_RGB24, MKTAG('r','a','w',' '), 24 },
1422 { AV_PIX_FMT_BGR24, MKTAG('2','4','B','G'), 24 },
1423 { AV_PIX_FMT_ARGB, MKTAG('r','a','w',' '), 32 },
1424 { AV_PIX_FMT_BGRA, MKTAG('B','G','R','A'), 32 },
1425 { AV_PIX_FMT_RGBA, MKTAG('R','G','B','A'), 32 },
1426 { AV_PIX_FMT_ABGR, MKTAG('A','B','G','R'), 32 },
1427 { AV_PIX_FMT_RGB48BE, MKTAG('b','4','8','r'), 48 },
1430 static int mov_get_dnxhd_codec_tag(AVFormatContext *s, MOVTrack *track)
1432 int tag = MKTAG('A','V','d','n');
1433 if (track->par->profile != FF_PROFILE_UNKNOWN &&
1434 track->par->profile != FF_PROFILE_DNXHD)
1435 tag = MKTAG('A','V','d','h');
1439 static int mov_get_rawvideo_codec_tag(AVFormatContext *s, MOVTrack *track)
1441 int tag = track->par->codec_tag;
1443 enum AVPixelFormat pix_fmt;
1445 for (i = 0; i < FF_ARRAY_ELEMS(mov_pix_fmt_tags); i++) {
1446 if (track->par->format == mov_pix_fmt_tags[i].pix_fmt) {
1447 tag = mov_pix_fmt_tags[i].tag;
1448 track->par->bits_per_coded_sample = mov_pix_fmt_tags[i].bps;
1449 if (track->par->codec_tag == mov_pix_fmt_tags[i].tag)
1454 pix_fmt = avpriv_find_pix_fmt(avpriv_pix_fmt_bps_mov,
1455 track->par->bits_per_coded_sample);
1456 if (tag == MKTAG('r','a','w',' ') &&
1457 track->par->format != pix_fmt &&
1458 track->par->format != AV_PIX_FMT_GRAY8 &&
1459 track->par->format != AV_PIX_FMT_NONE)
1460 av_log(s, AV_LOG_ERROR, "%s rawvideo cannot be written to mov, output file will be unreadable\n",
1461 av_get_pix_fmt_name(track->par->format));
1465 static int mov_get_codec_tag(AVFormatContext *s, MOVTrack *track)
1467 int tag = track->par->codec_tag;
1469 if (!tag || (s->strict_std_compliance >= FF_COMPLIANCE_NORMAL &&
1470 (track->par->codec_id == AV_CODEC_ID_DVVIDEO ||
1471 track->par->codec_id == AV_CODEC_ID_RAWVIDEO ||
1472 track->par->codec_id == AV_CODEC_ID_H263 ||
1473 track->par->codec_id == AV_CODEC_ID_H264 ||
1474 track->par->codec_id == AV_CODEC_ID_DNXHD ||
1475 track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO ||
1476 av_get_bits_per_sample(track->par->codec_id)))) { // pcm audio
1477 if (track->par->codec_id == AV_CODEC_ID_DVVIDEO)
1478 tag = mov_get_dv_codec_tag(s, track);
1479 else if (track->par->codec_id == AV_CODEC_ID_RAWVIDEO)
1480 tag = mov_get_rawvideo_codec_tag(s, track);
1481 else if (track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO)
1482 tag = mov_get_mpeg2_xdcam_codec_tag(s, track);
1483 else if (track->par->codec_id == AV_CODEC_ID_H264)
1484 tag = mov_get_h264_codec_tag(s, track);
1485 else if (track->par->codec_id == AV_CODEC_ID_DNXHD)
1486 tag = mov_get_dnxhd_codec_tag(s, track);
1487 else if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
1488 tag = ff_codec_get_tag(ff_codec_movvideo_tags, track->par->codec_id);
1489 if (!tag) { // if no mac fcc found, try with Microsoft tags
1490 tag = ff_codec_get_tag(ff_codec_bmp_tags, track->par->codec_id);
1492 av_log(s, AV_LOG_WARNING, "Using MS style video codec tag, "
1493 "the file may be unplayable!\n");
1495 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
1496 tag = ff_codec_get_tag(ff_codec_movaudio_tags, track->par->codec_id);
1497 if (!tag) { // if no mac fcc found, try with Microsoft tags
1498 int ms_tag = ff_codec_get_tag(ff_codec_wav_tags, track->par->codec_id);
1500 tag = MKTAG('m', 's', ((ms_tag >> 8) & 0xff), (ms_tag & 0xff));
1501 av_log(s, AV_LOG_WARNING, "Using MS style audio codec tag, "
1502 "the file may be unplayable!\n");
1505 } else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)
1506 tag = ff_codec_get_tag(ff_codec_movsubtitle_tags, track->par->codec_id);
1512 static int mov_find_codec_tag(AVFormatContext *s, MOVTrack *track)
1516 if (track->mode == MODE_MP4 || track->mode == MODE_PSP)
1517 tag = track->par->codec_tag;
1518 else if (track->mode == MODE_ISM)
1519 tag = track->par->codec_tag;
1520 else if (track->mode == MODE_IPOD) {
1521 if (!av_match_ext(s->filename, "m4a") &&
1522 !av_match_ext(s->filename, "m4v") &&
1523 !av_match_ext(s->filename, "m4b"))
1524 av_log(s, AV_LOG_WARNING, "Warning, extension is not .m4a nor .m4v "
1525 "Quicktime/Ipod might not play the file\n");
1526 tag = track->par->codec_tag;
1527 } else if (track->mode & MODE_3GP)
1528 tag = track->par->codec_tag;
1529 else if (track->mode == MODE_F4V)
1530 tag = track->par->codec_tag;
1532 tag = mov_get_codec_tag(s, track);
1537 /** Write uuid atom.
1538 * Needed to make file play in iPods running newest firmware
1539 * goes after avcC atom in moov.trak.mdia.minf.stbl.stsd.avc1
1541 static int mov_write_uuid_tag_ipod(AVIOContext *pb)
1544 ffio_wfourcc(pb, "uuid");
1545 avio_wb32(pb, 0x6b6840f2);
1546 avio_wb32(pb, 0x5f244fc5);
1547 avio_wb32(pb, 0xba39a51b);
1548 avio_wb32(pb, 0xcf0323f3);
1553 static const uint16_t fiel_data[] = {
1554 0x0000, 0x0100, 0x0201, 0x0206, 0x0209, 0x020e
1557 static int mov_write_fiel_tag(AVIOContext *pb, MOVTrack *track, int field_order)
1559 unsigned mov_field_order = 0;
1560 if (field_order < FF_ARRAY_ELEMS(fiel_data))
1561 mov_field_order = fiel_data[field_order];
1565 ffio_wfourcc(pb, "fiel");
1566 avio_wb16(pb, mov_field_order);
1570 static int mov_write_subtitle_tag(AVIOContext *pb, MOVTrack *track)
1572 int64_t pos = avio_tell(pb);
1573 avio_wb32(pb, 0); /* size */
1574 avio_wl32(pb, track->tag); // store it byteswapped
1575 avio_wb32(pb, 0); /* Reserved */
1576 avio_wb16(pb, 0); /* Reserved */
1577 avio_wb16(pb, 1); /* Data-reference index */
1579 if (track->par->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
1580 mov_write_esds_tag(pb, track);
1581 else if (track->par->extradata_size)
1582 avio_write(pb, track->par->extradata, track->par->extradata_size);
1584 return update_size(pb, pos);
1587 static int mov_write_st3d_tag(AVIOContext *pb, AVStereo3D *stereo_3d)
1591 if (stereo_3d->flags != 0) {
1592 av_log(pb, AV_LOG_WARNING, "Unsupported stereo_3d flags %x. st3d not written.\n", stereo_3d->flags);
1596 switch (stereo_3d->type) {
1597 case AV_STEREO3D_2D:
1600 case AV_STEREO3D_TOPBOTTOM:
1603 case AV_STEREO3D_SIDEBYSIDE:
1607 av_log(pb, AV_LOG_WARNING, "Unsupported stereo_3d type %s. st3d not written.\n", av_stereo3d_type_name(stereo_3d->type));
1610 avio_wb32(pb, 13); /* size */
1611 ffio_wfourcc(pb, "st3d");
1612 avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1613 avio_w8(pb, stereo_mode);
1617 static int mov_write_sv3d_tag(AVFormatContext *s, AVIOContext *pb, AVSphericalMapping *spherical_mapping)
1619 int64_t sv3d_pos, svhd_pos, proj_pos;
1620 const char* metadata_source = s->flags & AVFMT_FLAG_BITEXACT ? "Lavf" : LIBAVFORMAT_IDENT;
1622 if (spherical_mapping->projection != AV_SPHERICAL_EQUIRECTANGULAR &&
1623 spherical_mapping->projection != AV_SPHERICAL_EQUIRECTANGULAR_TILE &&
1624 spherical_mapping->projection != AV_SPHERICAL_CUBEMAP) {
1625 av_log(pb, AV_LOG_WARNING, "Unsupported projection %d. sv3d not written.\n", spherical_mapping->projection);
1629 sv3d_pos = avio_tell(pb);
1630 avio_wb32(pb, 0); /* size */
1631 ffio_wfourcc(pb, "sv3d");
1633 svhd_pos = avio_tell(pb);
1634 avio_wb32(pb, 0); /* size */
1635 ffio_wfourcc(pb, "svhd");
1636 avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1637 avio_put_str(pb, metadata_source);
1638 update_size(pb, svhd_pos);
1640 proj_pos = avio_tell(pb);
1641 avio_wb32(pb, 0); /* size */
1642 ffio_wfourcc(pb, "proj");
1644 avio_wb32(pb, 24); /* size */
1645 ffio_wfourcc(pb, "prhd");
1646 avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1647 avio_wb32(pb, spherical_mapping->yaw);
1648 avio_wb32(pb, spherical_mapping->pitch);
1649 avio_wb32(pb, spherical_mapping->roll);
1651 switch (spherical_mapping->projection) {
1652 case AV_SPHERICAL_EQUIRECTANGULAR:
1653 case AV_SPHERICAL_EQUIRECTANGULAR_TILE:
1654 avio_wb32(pb, 28); /* size */
1655 ffio_wfourcc(pb, "equi");
1656 avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1657 avio_wb32(pb, spherical_mapping->bound_top);
1658 avio_wb32(pb, spherical_mapping->bound_bottom);
1659 avio_wb32(pb, spherical_mapping->bound_left);
1660 avio_wb32(pb, spherical_mapping->bound_right);
1662 case AV_SPHERICAL_CUBEMAP:
1663 avio_wb32(pb, 20); /* size */
1664 ffio_wfourcc(pb, "cbmp");
1665 avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1666 avio_wb32(pb, 0); /* layout */
1667 avio_wb32(pb, spherical_mapping->padding); /* padding */
1670 update_size(pb, proj_pos);
1672 return update_size(pb, sv3d_pos);
1675 static int mov_write_pasp_tag(AVIOContext *pb, MOVTrack *track)
1678 av_reduce(&sar.num, &sar.den, track->par->sample_aspect_ratio.num,
1679 track->par->sample_aspect_ratio.den, INT_MAX);
1682 ffio_wfourcc(pb, "pasp");
1683 avio_wb32(pb, sar.num);
1684 avio_wb32(pb, sar.den);
1688 static int mov_write_gama_tag(AVIOContext *pb, MOVTrack *track, double gamma)
1693 gamma = avpriv_get_gamma_from_trc(track->par->color_trc);
1695 av_log(pb, AV_LOG_DEBUG, "gamma value %g\n", gamma);
1698 gama = (uint32_t)lrint((double)(1<<16) * gamma);
1699 av_log(pb, AV_LOG_DEBUG, "writing gama value %"PRId32"\n", gama);
1701 av_assert0(track->mode == MODE_MOV);
1703 ffio_wfourcc(pb, "gama");
1704 avio_wb32(pb, gama);
1708 av_log(pb, AV_LOG_WARNING, "gamma value unknown, unable to write gama atom\n");
1713 static int mov_write_colr_tag(AVIOContext *pb, MOVTrack *track)
1715 // Ref (MOV): https://developer.apple.com/library/mac/technotes/tn2162/_index.html#//apple_ref/doc/uid/DTS40013070-CH1-TNTAG9
1716 // Ref (MP4): ISO/IEC 14496-12:2012
1718 if (track->par->color_primaries == AVCOL_PRI_UNSPECIFIED &&
1719 track->par->color_trc == AVCOL_TRC_UNSPECIFIED &&
1720 track->par->color_space == AVCOL_SPC_UNSPECIFIED) {
1721 if ((track->par->width >= 1920 && track->par->height >= 1080)
1722 || (track->par->width == 1280 && track->par->height == 720)) {
1723 av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming bt709\n");
1724 track->par->color_primaries = AVCOL_PRI_BT709;
1725 } else if (track->par->width == 720 && track->height == 576) {
1726 av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming bt470bg\n");
1727 track->par->color_primaries = AVCOL_PRI_BT470BG;
1728 } else if (track->par->width == 720 &&
1729 (track->height == 486 || track->height == 480)) {
1730 av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming smpte170\n");
1731 track->par->color_primaries = AVCOL_PRI_SMPTE170M;
1733 av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, unable to assume anything\n");
1735 switch (track->par->color_primaries) {
1736 case AVCOL_PRI_BT709:
1737 track->par->color_trc = AVCOL_TRC_BT709;
1738 track->par->color_space = AVCOL_SPC_BT709;
1740 case AVCOL_PRI_SMPTE170M:
1741 case AVCOL_PRI_BT470BG:
1742 track->par->color_trc = AVCOL_TRC_BT709;
1743 track->par->color_space = AVCOL_SPC_SMPTE170M;
1748 /* We should only ever be called by MOV or MP4. */
1749 av_assert0(track->mode == MODE_MOV || track->mode == MODE_MP4);
1751 avio_wb32(pb, 18 + (track->mode == MODE_MP4));
1752 ffio_wfourcc(pb, "colr");
1753 if (track->mode == MODE_MP4)
1754 ffio_wfourcc(pb, "nclx");
1756 ffio_wfourcc(pb, "nclc");
1757 switch (track->par->color_primaries) {
1758 case AVCOL_PRI_BT709: avio_wb16(pb, 1); break;
1759 case AVCOL_PRI_SMPTE170M:
1760 case AVCOL_PRI_SMPTE240M: avio_wb16(pb, 6); break;
1761 case AVCOL_PRI_BT470BG: avio_wb16(pb, 5); break;
1762 default: avio_wb16(pb, 2);
1764 switch (track->par->color_trc) {
1765 case AVCOL_TRC_BT709: avio_wb16(pb, 1); break;
1766 case AVCOL_TRC_SMPTE170M: avio_wb16(pb, 1); break; // remapped
1767 case AVCOL_TRC_SMPTE240M: avio_wb16(pb, 7); break;
1768 default: avio_wb16(pb, 2);
1770 switch (track->par->color_space) {
1771 case AVCOL_SPC_BT709: avio_wb16(pb, 1); break;
1772 case AVCOL_SPC_BT470BG:
1773 case AVCOL_SPC_SMPTE170M: avio_wb16(pb, 6); break;
1774 case AVCOL_SPC_SMPTE240M: avio_wb16(pb, 7); break;
1775 default: avio_wb16(pb, 2);
1778 if (track->mode == MODE_MP4) {
1779 int full_range = track->par->color_range == AVCOL_RANGE_JPEG;
1780 avio_w8(pb, full_range << 7);
1787 static void find_compressor(char * compressor_name, int len, MOVTrack *track)
1789 AVDictionaryEntry *encoder;
1790 int xdcam_res = (track->par->width == 1280 && track->par->height == 720)
1791 || (track->par->width == 1440 && track->par->height == 1080)
1792 || (track->par->width == 1920 && track->par->height == 1080);
1794 if (track->mode == MODE_MOV &&
1795 (encoder = av_dict_get(track->st->metadata, "encoder", NULL, 0))) {
1796 av_strlcpy(compressor_name, encoder->value, 32);
1797 } else if (track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO && xdcam_res) {
1798 int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE;
1799 AVStream *st = track->st;
1800 int rate = defined_frame_rate(NULL, st);
1801 av_strlcatf(compressor_name, len, "XDCAM");
1802 if (track->par->format == AV_PIX_FMT_YUV422P) {
1803 av_strlcatf(compressor_name, len, " HD422");
1804 } else if(track->par->width == 1440) {
1805 av_strlcatf(compressor_name, len, " HD");
1807 av_strlcatf(compressor_name, len, " EX");
1809 av_strlcatf(compressor_name, len, " %d%c", track->par->height, interlaced ? 'i' : 'p');
1811 av_strlcatf(compressor_name, len, "%d", rate * (interlaced + 1));
1815 static int mov_write_video_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
1817 int64_t pos = avio_tell(pb);
1818 char compressor_name[32] = { 0 };
1821 avio_wb32(pb, 0); /* size */
1822 if (mov->encryption_scheme != MOV_ENC_NONE) {
1823 ffio_wfourcc(pb, "encv");
1825 avio_wl32(pb, track->tag); // store it byteswapped
1827 avio_wb32(pb, 0); /* Reserved */
1828 avio_wb16(pb, 0); /* Reserved */
1829 avio_wb16(pb, 1); /* Data-reference index */
1831 avio_wb16(pb, 0); /* Codec stream version */
1832 avio_wb16(pb, 0); /* Codec stream revision (=0) */
1833 if (track->mode == MODE_MOV) {
1834 ffio_wfourcc(pb, "FFMP"); /* Vendor */
1835 if (track->par->codec_id == AV_CODEC_ID_RAWVIDEO) {
1836 avio_wb32(pb, 0); /* Temporal Quality */
1837 avio_wb32(pb, 0x400); /* Spatial Quality = lossless*/
1839 avio_wb32(pb, 0x200); /* Temporal Quality = normal */
1840 avio_wb32(pb, 0x200); /* Spatial Quality = normal */
1843 avio_wb32(pb, 0); /* Reserved */
1844 avio_wb32(pb, 0); /* Reserved */
1845 avio_wb32(pb, 0); /* Reserved */
1847 avio_wb16(pb, track->par->width); /* Video width */
1848 avio_wb16(pb, track->height); /* Video height */
1849 avio_wb32(pb, 0x00480000); /* Horizontal resolution 72dpi */
1850 avio_wb32(pb, 0x00480000); /* Vertical resolution 72dpi */
1851 avio_wb32(pb, 0); /* Data size (= 0) */
1852 avio_wb16(pb, 1); /* Frame count (= 1) */
1854 /* FIXME not sure, ISO 14496-1 draft where it shall be set to 0 */
1855 find_compressor(compressor_name, 32, track);
1856 avio_w8(pb, strlen(compressor_name));
1857 avio_write(pb, compressor_name, 31);
1859 if (track->mode == MODE_MOV && track->par->bits_per_coded_sample)
1860 avio_wb16(pb, track->par->bits_per_coded_sample |
1861 (track->par->format == AV_PIX_FMT_GRAY8 ? 0x20 : 0));
1863 avio_wb16(pb, 0x18); /* Reserved */
1865 if (track->mode == MODE_MOV && track->par->format == AV_PIX_FMT_PAL8) {
1866 int pal_size = 1 << track->par->bits_per_coded_sample;
1868 avio_wb16(pb, 0); /* Color table ID */
1869 avio_wb32(pb, 0); /* Color table seed */
1870 avio_wb16(pb, 0x8000); /* Color table flags */
1871 avio_wb16(pb, pal_size - 1); /* Color table size (zero-relative) */
1872 for (i = 0; i < pal_size; i++) {
1873 uint32_t rgb = track->palette[i];
1874 uint16_t r = (rgb >> 16) & 0xff;
1875 uint16_t g = (rgb >> 8) & 0xff;
1876 uint16_t b = rgb & 0xff;
1878 avio_wb16(pb, (r << 8) | r);
1879 avio_wb16(pb, (g << 8) | g);
1880 avio_wb16(pb, (b << 8) | b);
1883 avio_wb16(pb, 0xffff); /* Reserved */
1885 if (track->tag == MKTAG('m','p','4','v'))
1886 mov_write_esds_tag(pb, track);
1887 else if (track->par->codec_id == AV_CODEC_ID_H263)
1888 mov_write_d263_tag(pb);
1889 else if (track->par->codec_id == AV_CODEC_ID_AVUI ||
1890 track->par->codec_id == AV_CODEC_ID_SVQ3) {
1891 mov_write_extradata_tag(pb, track);
1893 } else if (track->par->codec_id == AV_CODEC_ID_DNXHD) {
1894 mov_write_avid_tag(pb, track);
1896 } else if (track->par->codec_id == AV_CODEC_ID_HEVC)
1897 mov_write_hvcc_tag(pb, track);
1898 else if (track->par->codec_id == AV_CODEC_ID_H264 && !TAG_IS_AVCI(track->tag)) {
1899 mov_write_avcc_tag(pb, track);
1900 if (track->mode == MODE_IPOD)
1901 mov_write_uuid_tag_ipod(pb);
1902 } else if (track->par->codec_id == AV_CODEC_ID_VP9) {
1903 mov_write_vpcc_tag(mov->fc, pb, track);
1904 } else if (track->par->codec_id == AV_CODEC_ID_VC1 && track->vos_len > 0)
1905 mov_write_dvc1_tag(pb, track);
1906 else if (track->par->codec_id == AV_CODEC_ID_VP6F ||
1907 track->par->codec_id == AV_CODEC_ID_VP6A) {
1908 /* Don't write any potential extradata here - the cropping
1909 * is signalled via the normal width/height fields. */
1910 } else if (track->par->codec_id == AV_CODEC_ID_R10K) {
1911 if (track->par->codec_tag == MKTAG('R','1','0','k'))
1912 mov_write_dpxe_tag(pb, track);
1913 } else if (track->vos_len > 0)
1914 mov_write_glbl_tag(pb, track);
1916 if (track->par->codec_id != AV_CODEC_ID_H264 &&
1917 track->par->codec_id != AV_CODEC_ID_MPEG4 &&
1918 track->par->codec_id != AV_CODEC_ID_DNXHD) {
1919 int field_order = track->par->field_order;
1921 #if FF_API_LAVF_AVCTX
1922 FF_DISABLE_DEPRECATION_WARNINGS
1923 if (field_order != track->st->codec->field_order && track->st->codec->field_order != AV_FIELD_UNKNOWN)
1924 field_order = track->st->codec->field_order;
1925 FF_ENABLE_DEPRECATION_WARNINGS
1928 if (field_order != AV_FIELD_UNKNOWN)
1929 mov_write_fiel_tag(pb, track, field_order);
1932 if (mov->flags & FF_MOV_FLAG_WRITE_GAMA) {
1933 if (track->mode == MODE_MOV)
1934 mov_write_gama_tag(pb, track, mov->gamma);
1936 av_log(mov->fc, AV_LOG_WARNING, "Not writing 'gama' atom. Format is not MOV.\n");
1938 if (mov->flags & FF_MOV_FLAG_WRITE_COLR) {
1939 if (track->mode == MODE_MOV || track->mode == MODE_MP4)
1940 mov_write_colr_tag(pb, track);
1942 av_log(mov->fc, AV_LOG_WARNING, "Not writing 'colr' atom. Format is not MOV or MP4.\n");
1945 if (track->mode == MODE_MP4 && mov->fc->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL) {
1946 AVStereo3D* stereo_3d = (AVStereo3D*) av_stream_get_side_data(track->st, AV_PKT_DATA_STEREO3D, NULL);
1947 AVSphericalMapping* spherical_mapping = (AVSphericalMapping*)av_stream_get_side_data(track->st, AV_PKT_DATA_SPHERICAL, NULL);
1950 mov_write_st3d_tag(pb, stereo_3d);
1951 if (spherical_mapping)
1952 mov_write_sv3d_tag(mov->fc, pb, spherical_mapping);
1955 if (track->par->sample_aspect_ratio.den && track->par->sample_aspect_ratio.num) {
1956 mov_write_pasp_tag(pb, track);
1959 if (mov->encryption_scheme != MOV_ENC_NONE) {
1960 ff_mov_cenc_write_sinf_tag(track, pb, mov->encryption_kid);
1963 /* extra padding for avid stsd */
1964 /* https://developer.apple.com/library/mac/documentation/QuickTime/QTFF/QTFFChap2/qtff2.html#//apple_ref/doc/uid/TP40000939-CH204-61112 */
1968 return update_size(pb, pos);
1971 static int mov_write_rtp_tag(AVIOContext *pb, MOVTrack *track)
1973 int64_t pos = avio_tell(pb);
1974 avio_wb32(pb, 0); /* size */
1975 ffio_wfourcc(pb, "rtp ");
1976 avio_wb32(pb, 0); /* Reserved */
1977 avio_wb16(pb, 0); /* Reserved */
1978 avio_wb16(pb, 1); /* Data-reference index */
1980 avio_wb16(pb, 1); /* Hint track version */
1981 avio_wb16(pb, 1); /* Highest compatible version */
1982 avio_wb32(pb, track->max_packet_size); /* Max packet size */
1984 avio_wb32(pb, 12); /* size */
1985 ffio_wfourcc(pb, "tims");
1986 avio_wb32(pb, track->timescale);
1988 return update_size(pb, pos);
1991 static int mov_write_source_reference_tag(AVIOContext *pb, MOVTrack *track, const char *reel_name)
1993 uint64_t str_size =strlen(reel_name);
1994 int64_t pos = avio_tell(pb);
1996 if (str_size >= UINT16_MAX){
1997 av_log(NULL, AV_LOG_ERROR, "reel_name length %"PRIu64" is too large\n", str_size);
1999 return AVERROR(EINVAL);
2002 avio_wb32(pb, 0); /* size */
2003 ffio_wfourcc(pb, "name"); /* Data format */
2004 avio_wb16(pb, str_size); /* string size */
2005 avio_wb16(pb, track->language); /* langcode */
2006 avio_write(pb, reel_name, str_size); /* reel name */
2007 return update_size(pb,pos);
2010 static int mov_write_tmcd_tag(AVIOContext *pb, MOVTrack *track)
2012 int64_t pos = avio_tell(pb);
2016 AVDictionaryEntry *t = NULL;
2018 if (!track->st->avg_frame_rate.num || !track->st->avg_frame_rate.den) {
2019 #if FF_API_LAVF_AVCTX
2020 FF_DISABLE_DEPRECATION_WARNINGS
2021 frame_duration = av_rescale(track->timescale, track->st->codec->time_base.num, track->st->codec->time_base.den);
2022 nb_frames = ROUNDED_DIV(track->st->codec->time_base.den, track->st->codec->time_base.num);
2023 FF_ENABLE_DEPRECATION_WARNINGS
2025 av_log(NULL, AV_LOG_ERROR, "avg_frame_rate not set for tmcd track.\n");
2026 return AVERROR(EINVAL);
2029 frame_duration = av_rescale(track->timescale, track->st->avg_frame_rate.num, track->st->avg_frame_rate.den);
2030 nb_frames = ROUNDED_DIV(track->st->avg_frame_rate.den, track->st->avg_frame_rate.num);
2033 if (nb_frames > 255) {
2034 av_log(NULL, AV_LOG_ERROR, "fps %d is too large\n", nb_frames);
2035 return AVERROR(EINVAL);
2038 avio_wb32(pb, 0); /* size */
2039 ffio_wfourcc(pb, "tmcd"); /* Data format */
2040 avio_wb32(pb, 0); /* Reserved */
2041 avio_wb32(pb, 1); /* Data reference index */
2042 avio_wb32(pb, 0); /* Flags */
2043 avio_wb32(pb, track->timecode_flags); /* Flags (timecode) */
2044 avio_wb32(pb, track->timescale); /* Timescale */
2045 avio_wb32(pb, frame_duration); /* Frame duration */
2046 avio_w8(pb, nb_frames); /* Number of frames */
2047 avio_w8(pb, 0); /* Reserved */
2049 t = av_dict_get(track->st->metadata, "reel_name", NULL, 0);
2050 if (t && utf8len(t->value) && track->mode != MODE_MP4)
2051 mov_write_source_reference_tag(pb, track, t->value);
2053 avio_wb16(pb, 0); /* zero size */
2056 avio_wb32(pb, 0); /* size */
2057 ffio_wfourcc(pb, "tmcd"); /* Data format */
2058 avio_wb32(pb, 0); /* Reserved */
2059 avio_wb32(pb, 1); /* Data reference index */
2060 if (track->par->extradata_size)
2061 avio_write(pb, track->par->extradata, track->par->extradata_size);
2063 return update_size(pb, pos);
2066 static int mov_write_gpmd_tag(AVIOContext *pb, const MOVTrack *track)
2068 int64_t pos = avio_tell(pb);
2069 avio_wb32(pb, 0); /* size */
2070 ffio_wfourcc(pb, "gpmd");
2071 avio_wb32(pb, 0); /* Reserved */
2072 avio_wb16(pb, 0); /* Reserved */
2073 avio_wb16(pb, 1); /* Data-reference index */
2074 avio_wb32(pb, 0); /* Reserved */
2075 return update_size(pb, pos);
2078 static int mov_write_stsd_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
2080 int64_t pos = avio_tell(pb);
2081 avio_wb32(pb, 0); /* size */
2082 ffio_wfourcc(pb, "stsd");
2083 avio_wb32(pb, 0); /* version & flags */
2084 avio_wb32(pb, 1); /* entry count */
2085 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO)
2086 mov_write_video_tag(pb, mov, track);
2087 else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
2088 mov_write_audio_tag(s, pb, mov, track);
2089 else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)
2090 mov_write_subtitle_tag(pb, track);
2091 else if (track->par->codec_tag == MKTAG('r','t','p',' '))
2092 mov_write_rtp_tag(pb, track);
2093 else if (track->par->codec_tag == MKTAG('t','m','c','d'))
2094 mov_write_tmcd_tag(pb, track);
2095 else if (track->par->codec_tag == MKTAG('g','p','m','d'))
2096 mov_write_gpmd_tag(pb, track);
2097 return update_size(pb, pos);
2100 static int mov_write_ctts_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
2102 MOVMuxContext *mov = s->priv_data;
2103 MOVStts *ctts_entries;
2104 uint32_t entries = 0;
2108 ctts_entries = av_malloc_array((track->entry + 1), sizeof(*ctts_entries)); /* worst case */
2110 return AVERROR(ENOMEM);
2111 ctts_entries[0].count = 1;
2112 ctts_entries[0].duration = track->cluster[0].cts;
2113 for (i = 1; i < track->entry; i++) {
2114 if (track->cluster[i].cts == ctts_entries[entries].duration) {
2115 ctts_entries[entries].count++; /* compress */
2118 ctts_entries[entries].duration = track->cluster[i].cts;
2119 ctts_entries[entries].count = 1;
2122 entries++; /* last one */
2123 atom_size = 16 + (entries * 8);
2124 avio_wb32(pb, atom_size); /* size */
2125 ffio_wfourcc(pb, "ctts");
2126 if (mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS)
2127 avio_w8(pb, 1); /* version */
2129 avio_w8(pb, 0); /* version */
2130 avio_wb24(pb, 0); /* flags */
2131 avio_wb32(pb, entries); /* entry count */
2132 for (i = 0; i < entries; i++) {
2133 avio_wb32(pb, ctts_entries[i].count);
2134 avio_wb32(pb, ctts_entries[i].duration);
2136 av_free(ctts_entries);
2140 /* Time to sample atom */
2141 static int mov_write_stts_tag(AVIOContext *pb, MOVTrack *track)
2143 MOVStts *stts_entries = NULL;
2144 uint32_t entries = -1;
2148 if (track->par->codec_type == AVMEDIA_TYPE_AUDIO && !track->audio_vbr) {
2149 stts_entries = av_malloc(sizeof(*stts_entries)); /* one entry */
2151 return AVERROR(ENOMEM);
2152 stts_entries[0].count = track->sample_count;
2153 stts_entries[0].duration = 1;
2157 stts_entries = av_malloc_array(track->entry, sizeof(*stts_entries)); /* worst case */
2159 return AVERROR(ENOMEM);
2161 for (i = 0; i < track->entry; i++) {
2162 int duration = get_cluster_duration(track, i);
2163 if (i && duration == stts_entries[entries].duration) {
2164 stts_entries[entries].count++; /* compress */
2167 stts_entries[entries].duration = duration;
2168 stts_entries[entries].count = 1;
2171 entries++; /* last one */
2173 atom_size = 16 + (entries * 8);
2174 avio_wb32(pb, atom_size); /* size */
2175 ffio_wfourcc(pb, "stts");
2176 avio_wb32(pb, 0); /* version & flags */
2177 avio_wb32(pb, entries); /* entry count */
2178 for (i = 0; i < entries; i++) {
2179 avio_wb32(pb, stts_entries[i].count);
2180 avio_wb32(pb, stts_entries[i].duration);
2182 av_free(stts_entries);
2186 static int mov_write_dref_tag(AVIOContext *pb)
2188 avio_wb32(pb, 28); /* size */
2189 ffio_wfourcc(pb, "dref");
2190 avio_wb32(pb, 0); /* version & flags */
2191 avio_wb32(pb, 1); /* entry count */
2193 avio_wb32(pb, 0xc); /* size */
2194 //FIXME add the alis and rsrc atom
2195 ffio_wfourcc(pb, "url ");
2196 avio_wb32(pb, 1); /* version & flags */
2201 static int mov_preroll_write_stbl_atoms(AVIOContext *pb, MOVTrack *track)
2205 int16_t roll_distance;
2206 int group_description_index;
2209 struct sgpd_entry *sgpd_entries = NULL;
2214 const int OPUS_SEEK_PREROLL_MS = 80;
2215 int roll_samples = av_rescale_q(OPUS_SEEK_PREROLL_MS,
2216 (AVRational){1, 1000},
2217 (AVRational){1, 48000});
2222 sgpd_entries = av_malloc_array(track->entry, sizeof(*sgpd_entries));
2224 return AVERROR(ENOMEM);
2226 av_assert0(track->par->codec_id == AV_CODEC_ID_OPUS || track->par->codec_id == AV_CODEC_ID_AAC);
2228 if (track->par->codec_id == AV_CODEC_ID_OPUS) {
2229 for (i = 0; i < track->entry; i++) {
2230 int roll_samples_remaining = roll_samples;
2232 for (j = i - 1; j >= 0; j--) {
2233 roll_samples_remaining -= get_cluster_duration(track, j);
2235 if (roll_samples_remaining <= 0)
2238 /* We don't have enough preceeding samples to compute a valid
2239 roll_distance here, so this sample can't be independently
2241 if (roll_samples_remaining > 0)
2243 /* Verify distance is a minimum of 2 (60ms) packets and a maximum of
2244 32 (2.5ms) packets. */
2245 av_assert0(distance == 0 || (distance >= 2 && distance <= 32));
2246 if (i && distance == sgpd_entries[entries].roll_distance) {
2247 sgpd_entries[entries].count++;
2250 sgpd_entries[entries].count = 1;
2251 sgpd_entries[entries].roll_distance = distance;
2252 sgpd_entries[entries].group_description_index = distance ? ++group : 0;
2257 sgpd_entries[entries].count = track->sample_count;
2258 sgpd_entries[entries].roll_distance = 1;
2259 sgpd_entries[entries].group_description_index = ++group;
2264 av_free(sgpd_entries);
2268 /* Write sgpd tag */
2269 avio_wb32(pb, 24 + (group * 2)); /* size */
2270 ffio_wfourcc(pb, "sgpd");
2271 avio_wb32(pb, 1 << 24); /* fullbox */
2272 ffio_wfourcc(pb, "roll");
2273 avio_wb32(pb, 2); /* default_length */
2274 avio_wb32(pb, group); /* entry_count */
2275 for (i = 0; i < entries; i++) {
2276 if (sgpd_entries[i].group_description_index) {
2277 avio_wb16(pb, -sgpd_entries[i].roll_distance); /* roll_distance */
2281 /* Write sbgp tag */
2282 avio_wb32(pb, 20 + (entries * 8)); /* size */
2283 ffio_wfourcc(pb, "sbgp");
2284 avio_wb32(pb, 0); /* fullbox */
2285 ffio_wfourcc(pb, "roll");
2286 avio_wb32(pb, entries); /* entry_count */
2287 for (i = 0; i < entries; i++) {
2288 avio_wb32(pb, sgpd_entries[i].count); /* sample_count */
2289 avio_wb32(pb, sgpd_entries[i].group_description_index); /* group_description_index */
2292 av_free(sgpd_entries);
2296 static int mov_write_stbl_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
2298 int64_t pos = avio_tell(pb);
2301 avio_wb32(pb, 0); /* size */
2302 ffio_wfourcc(pb, "stbl");
2303 mov_write_stsd_tag(s, pb, mov, track);
2304 mov_write_stts_tag(pb, track);
2305 if ((track->par->codec_type == AVMEDIA_TYPE_VIDEO ||
2306 track->par->codec_tag == MKTAG('r','t','p',' ')) &&
2307 track->has_keyframes && track->has_keyframes < track->entry)
2308 mov_write_stss_tag(pb, track, MOV_SYNC_SAMPLE);
2309 if (track->mode == MODE_MOV && track->flags & MOV_TRACK_STPS)
2310 mov_write_stss_tag(pb, track, MOV_PARTIAL_SYNC_SAMPLE);
2311 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO &&
2312 track->flags & MOV_TRACK_CTTS && track->entry) {
2314 if ((ret = mov_write_ctts_tag(s, pb, track)) < 0)
2317 mov_write_stsc_tag(pb, track);
2318 mov_write_stsz_tag(pb, track);
2319 mov_write_stco_tag(pb, track);
2320 if (track->cenc.aes_ctr) {
2321 ff_mov_cenc_write_stbl_atoms(&track->cenc, pb);
2323 if (track->par->codec_id == AV_CODEC_ID_OPUS || track->par->codec_id == AV_CODEC_ID_AAC) {
2324 mov_preroll_write_stbl_atoms(pb, track);
2326 return update_size(pb, pos);
2329 static int mov_write_dinf_tag(AVIOContext *pb)
2331 int64_t pos = avio_tell(pb);
2332 avio_wb32(pb, 0); /* size */
2333 ffio_wfourcc(pb, "dinf");
2334 mov_write_dref_tag(pb);
2335 return update_size(pb, pos);
2338 static int mov_write_nmhd_tag(AVIOContext *pb)
2341 ffio_wfourcc(pb, "nmhd");
2346 static int mov_write_tcmi_tag(AVIOContext *pb, MOVTrack *track)
2348 int64_t pos = avio_tell(pb);
2349 const char *font = "Lucida Grande";
2350 avio_wb32(pb, 0); /* size */
2351 ffio_wfourcc(pb, "tcmi"); /* timecode media information atom */
2352 avio_wb32(pb, 0); /* version & flags */
2353 avio_wb16(pb, 0); /* text font */
2354 avio_wb16(pb, 0); /* text face */
2355 avio_wb16(pb, 12); /* text size */
2356 avio_wb16(pb, 0); /* (unknown, not in the QT specs...) */
2357 avio_wb16(pb, 0x0000); /* text color (red) */
2358 avio_wb16(pb, 0x0000); /* text color (green) */
2359 avio_wb16(pb, 0x0000); /* text color (blue) */
2360 avio_wb16(pb, 0xffff); /* background color (red) */
2361 avio_wb16(pb, 0xffff); /* background color (green) */
2362 avio_wb16(pb, 0xffff); /* background color (blue) */
2363 avio_w8(pb, strlen(font)); /* font len (part of the pascal string) */
2364 avio_write(pb, font, strlen(font)); /* font name */
2365 return update_size(pb, pos);
2368 static int mov_write_gmhd_tag(AVIOContext *pb, MOVTrack *track)
2370 int64_t pos = avio_tell(pb);
2371 avio_wb32(pb, 0); /* size */
2372 ffio_wfourcc(pb, "gmhd");
2373 avio_wb32(pb, 0x18); /* gmin size */
2374 ffio_wfourcc(pb, "gmin");/* generic media info */
2375 avio_wb32(pb, 0); /* version & flags */
2376 avio_wb16(pb, 0x40); /* graphics mode = */
2377 avio_wb16(pb, 0x8000); /* opColor (r?) */
2378 avio_wb16(pb, 0x8000); /* opColor (g?) */
2379 avio_wb16(pb, 0x8000); /* opColor (b?) */
2380 avio_wb16(pb, 0); /* balance */
2381 avio_wb16(pb, 0); /* reserved */
2384 * This special text atom is required for
2385 * Apple Quicktime chapters. The contents
2386 * don't appear to be documented, so the
2387 * bytes are copied verbatim.
2389 if (track->tag != MKTAG('c','6','0','8')) {
2390 avio_wb32(pb, 0x2C); /* size */
2391 ffio_wfourcc(pb, "text");
2392 avio_wb16(pb, 0x01);
2393 avio_wb32(pb, 0x00);
2394 avio_wb32(pb, 0x00);
2395 avio_wb32(pb, 0x00);
2396 avio_wb32(pb, 0x01);
2397 avio_wb32(pb, 0x00);
2398 avio_wb32(pb, 0x00);
2399 avio_wb32(pb, 0x00);
2400 avio_wb32(pb, 0x00004000);
2401 avio_wb16(pb, 0x0000);
2404 if (track->par->codec_tag == MKTAG('t','m','c','d')) {
2405 int64_t tmcd_pos = avio_tell(pb);
2406 avio_wb32(pb, 0); /* size */
2407 ffio_wfourcc(pb, "tmcd");
2408 mov_write_tcmi_tag(pb, track);
2409 update_size(pb, tmcd_pos);
2410 } else if (track->par->codec_tag == MKTAG('g','p','m','d')) {
2411 int64_t gpmd_pos = avio_tell(pb);
2412 avio_wb32(pb, 0); /* size */
2413 ffio_wfourcc(pb, "gpmd");
2414 avio_wb32(pb, 0); /* version */
2415 update_size(pb, gpmd_pos);
2417 return update_size(pb, pos);
2420 static int mov_write_smhd_tag(AVIOContext *pb)
2422 avio_wb32(pb, 16); /* size */
2423 ffio_wfourcc(pb, "smhd");
2424 avio_wb32(pb, 0); /* version & flags */
2425 avio_wb16(pb, 0); /* reserved (balance, normally = 0) */
2426 avio_wb16(pb, 0); /* reserved */
2430 static int mov_write_vmhd_tag(AVIOContext *pb)
2432 avio_wb32(pb, 0x14); /* size (always 0x14) */
2433 ffio_wfourcc(pb, "vmhd");
2434 avio_wb32(pb, 0x01); /* version & flags */
2435 avio_wb64(pb, 0); /* reserved (graphics mode = copy) */
2439 static int is_clcp_track(MOVTrack *track)
2441 return track->tag == MKTAG('c','7','0','8') ||
2442 track->tag == MKTAG('c','6','0','8');
2445 static int mov_write_hdlr_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
2447 const char *hdlr, *descr = NULL, *hdlr_type = NULL;
2448 int64_t pos = avio_tell(pb);
2452 descr = "DataHandler";
2455 hdlr = (track->mode == MODE_MOV) ? "mhlr" : "\0\0\0\0";
2456 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
2458 descr = "VideoHandler";
2459 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
2461 descr = "SoundHandler";
2462 } else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE) {
2463 if (is_clcp_track(track)) {
2465 descr = "ClosedCaptionHandler";
2467 if (track->tag == MKTAG('t','x','3','g')) {
2469 } else if (track->tag == MKTAG('m','p','4','s')) {
2474 descr = "SubtitleHandler";
2476 } else if (track->par->codec_tag == MKTAG('r','t','p',' ')) {
2478 descr = "HintHandler";
2479 } else if (track->par->codec_tag == MKTAG('t','m','c','d')) {
2481 descr = "TimeCodeHandler";
2482 } else if (track->par->codec_tag == MKTAG('g','p','m','d')) {
2484 descr = "GoPro MET"; // GoPro Metadata
2486 av_log(s, AV_LOG_WARNING,
2487 "Unknown hldr_type for %s, writing dummy values\n",
2488 av_fourcc2str(track->par->codec_tag));
2491 // hdlr.name is used by some players to identify the content title
2492 // of the track. So if an alternate handler description is
2493 // specified, use it.
2494 AVDictionaryEntry *t;
2495 t = av_dict_get(track->st->metadata, "handler", NULL, 0);
2496 if (t && utf8len(t->value))
2501 avio_wb32(pb, 0); /* size */
2502 ffio_wfourcc(pb, "hdlr");
2503 avio_wb32(pb, 0); /* Version & flags */
2504 avio_write(pb, hdlr, 4); /* handler */
2505 ffio_wfourcc(pb, hdlr_type); /* handler type */
2506 avio_wb32(pb, 0); /* reserved */
2507 avio_wb32(pb, 0); /* reserved */
2508 avio_wb32(pb, 0); /* reserved */
2509 if (!track || track->mode == MODE_MOV)
2510 avio_w8(pb, strlen(descr)); /* pascal string */
2511 avio_write(pb, descr, strlen(descr)); /* handler description */
2512 if (track && track->mode != MODE_MOV)
2513 avio_w8(pb, 0); /* c string */
2514 return update_size(pb, pos);
2517 static int mov_write_hmhd_tag(AVIOContext *pb)
2519 /* This atom must be present, but leaving the values at zero
2520 * seems harmless. */
2521 avio_wb32(pb, 28); /* size */
2522 ffio_wfourcc(pb, "hmhd");
2523 avio_wb32(pb, 0); /* version, flags */
2524 avio_wb16(pb, 0); /* maxPDUsize */
2525 avio_wb16(pb, 0); /* avgPDUsize */
2526 avio_wb32(pb, 0); /* maxbitrate */
2527 avio_wb32(pb, 0); /* avgbitrate */
2528 avio_wb32(pb, 0); /* reserved */
2532 static int mov_write_minf_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
2534 int64_t pos = avio_tell(pb);
2537 avio_wb32(pb, 0); /* size */
2538 ffio_wfourcc(pb, "minf");
2539 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO)
2540 mov_write_vmhd_tag(pb);
2541 else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
2542 mov_write_smhd_tag(pb);
2543 else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE) {
2544 if (track->tag == MKTAG('t','e','x','t') || is_clcp_track(track)) {
2545 mov_write_gmhd_tag(pb, track);
2547 mov_write_nmhd_tag(pb);
2549 } else if (track->tag == MKTAG('r','t','p',' ')) {
2550 mov_write_hmhd_tag(pb);
2551 } else if (track->tag == MKTAG('t','m','c','d')) {
2552 if (track->mode != MODE_MOV)
2553 mov_write_nmhd_tag(pb);
2555 mov_write_gmhd_tag(pb, track);
2556 } else if (track->tag == MKTAG('g','p','m','d')) {
2557 mov_write_gmhd_tag(pb, track);
2559 if (track->mode == MODE_MOV) /* FIXME: Why do it for MODE_MOV only ? */
2560 mov_write_hdlr_tag(s, pb, NULL);
2561 mov_write_dinf_tag(pb);
2562 if ((ret = mov_write_stbl_tag(s, pb, mov, track)) < 0)
2564 return update_size(pb, pos);
2567 static int mov_write_mdhd_tag(AVIOContext *pb, MOVMuxContext *mov,
2570 int version = track->track_duration < INT32_MAX ? 0 : 1;
2572 if (track->mode == MODE_ISM)
2575 (version == 1) ? avio_wb32(pb, 44) : avio_wb32(pb, 32); /* size */
2576 ffio_wfourcc(pb, "mdhd");
2577 avio_w8(pb, version);
2578 avio_wb24(pb, 0); /* flags */
2580 avio_wb64(pb, track->time);
2581 avio_wb64(pb, track->time);
2583 avio_wb32(pb, track->time); /* creation time */
2584 avio_wb32(pb, track->time); /* modification time */
2586 avio_wb32(pb, track->timescale); /* time scale (sample rate for audio) */
2587 if (!track->entry && mov->mode == MODE_ISM)
2588 (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
2589 else if (!track->entry)
2590 (version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0);
2592 (version == 1) ? avio_wb64(pb, track->track_duration) : avio_wb32(pb, track->track_duration); /* duration */
2593 avio_wb16(pb, track->language); /* language */
2594 avio_wb16(pb, 0); /* reserved (quality) */
2596 if (version != 0 && track->mode == MODE_MOV) {
2597 av_log(NULL, AV_LOG_ERROR,
2598 "FATAL error, file duration too long for timebase, this file will not be\n"
2599 "playable with quicktime. Choose a different timebase or a different\n"
2600 "container format\n");
2606 static int mov_write_mdia_tag(AVFormatContext *s, AVIOContext *pb,
2607 MOVMuxContext *mov, MOVTrack *track)
2609 int64_t pos = avio_tell(pb);
2612 avio_wb32(pb, 0); /* size */
2613 ffio_wfourcc(pb, "mdia");
2614 mov_write_mdhd_tag(pb, mov, track);
2615 mov_write_hdlr_tag(s, pb, track);
2616 if ((ret = mov_write_minf_tag(s, pb, mov, track)) < 0)
2618 return update_size(pb, pos);
2621 /* transformation matrix
2625 static void write_matrix(AVIOContext *pb, int16_t a, int16_t b, int16_t c,
2626 int16_t d, int16_t tx, int16_t ty)
2628 avio_wb32(pb, a << 16); /* 16.16 format */
2629 avio_wb32(pb, b << 16); /* 16.16 format */
2630 avio_wb32(pb, 0); /* u in 2.30 format */
2631 avio_wb32(pb, c << 16); /* 16.16 format */
2632 avio_wb32(pb, d << 16); /* 16.16 format */
2633 avio_wb32(pb, 0); /* v in 2.30 format */
2634 avio_wb32(pb, tx << 16); /* 16.16 format */
2635 avio_wb32(pb, ty << 16); /* 16.16 format */
2636 avio_wb32(pb, 1 << 30); /* w in 2.30 format */
2639 static int mov_write_tkhd_tag(AVIOContext *pb, MOVMuxContext *mov,
2640 MOVTrack *track, AVStream *st)
2642 int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE,
2643 track->timescale, AV_ROUND_UP);
2644 int version = duration < INT32_MAX ? 0 : 1;
2645 int flags = MOV_TKHD_FLAG_IN_MOVIE;
2649 uint32_t *display_matrix = NULL;
2650 int display_matrix_size, i;
2653 if (mov->per_stream_grouping)
2656 group = st->codecpar->codec_type;
2658 display_matrix = (uint32_t*)av_stream_get_side_data(st, AV_PKT_DATA_DISPLAYMATRIX,
2659 &display_matrix_size);
2660 if (display_matrix && display_matrix_size < 9 * sizeof(*display_matrix))
2661 display_matrix = NULL;
2664 if (track->flags & MOV_TRACK_ENABLED)
2665 flags |= MOV_TKHD_FLAG_ENABLED;
2667 if (track->mode == MODE_ISM)
2670 (version == 1) ? avio_wb32(pb, 104) : avio_wb32(pb, 92); /* size */
2671 ffio_wfourcc(pb, "tkhd");
2672 avio_w8(pb, version);
2673 avio_wb24(pb, flags);
2675 avio_wb64(pb, track->time);
2676 avio_wb64(pb, track->time);
2678 avio_wb32(pb, track->time); /* creation time */
2679 avio_wb32(pb, track->time); /* modification time */
2681 avio_wb32(pb, track->track_id); /* track-id */
2682 avio_wb32(pb, 0); /* reserved */
2683 if (!track->entry && mov->mode == MODE_ISM)
2684 (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
2685 else if (!track->entry)
2686 (version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0);
2688 (version == 1) ? avio_wb64(pb, duration) : avio_wb32(pb, duration);
2690 avio_wb32(pb, 0); /* reserved */
2691 avio_wb32(pb, 0); /* reserved */
2692 avio_wb16(pb, 0); /* layer */
2693 avio_wb16(pb, group); /* alternate group) */
2694 /* Volume, only for audio */
2695 if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
2696 avio_wb16(pb, 0x0100);
2699 avio_wb16(pb, 0); /* reserved */
2701 /* Matrix structure */
2702 #if FF_API_OLD_ROTATE_API
2703 if (st && st->metadata) {
2704 AVDictionaryEntry *rot = av_dict_get(st->metadata, "rotate", NULL, 0);
2705 rotation = (rot && rot->value) ? atoi(rot->value) : 0;
2708 if (display_matrix) {
2709 for (i = 0; i < 9; i++)
2710 avio_wb32(pb, display_matrix[i]);
2711 #if FF_API_OLD_ROTATE_API
2712 } else if (rotation == 90) {
2713 write_matrix(pb, 0, 1, -1, 0, track->par->height, 0);
2714 } else if (rotation == 180) {
2715 write_matrix(pb, -1, 0, 0, -1, track->par->width, track->par->height);
2716 } else if (rotation == 270) {
2717 write_matrix(pb, 0, -1, 1, 0, 0, track->par->width);
2720 write_matrix(pb, 1, 0, 0, 1, 0, 0);
2722 /* Track width and height, for visual only */
2723 if (st && (track->par->codec_type == AVMEDIA_TYPE_VIDEO ||
2724 track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)) {
2725 int64_t track_width_1616;
2726 if (track->mode == MODE_MOV) {
2727 track_width_1616 = track->par->width * 0x10000ULL;
2729 track_width_1616 = av_rescale(st->sample_aspect_ratio.num,
2730 track->par->width * 0x10000LL,
2731 st->sample_aspect_ratio.den);
2732 if (!track_width_1616 ||
2733 track->height != track->par->height ||
2734 track_width_1616 > UINT32_MAX)
2735 track_width_1616 = track->par->width * 0x10000ULL;
2737 if (track_width_1616 > UINT32_MAX) {
2738 av_log(mov->fc, AV_LOG_WARNING, "track width is too large\n");
2739 track_width_1616 = 0;
2741 avio_wb32(pb, track_width_1616);
2742 if (track->height > 0xFFFF) {
2743 av_log(mov->fc, AV_LOG_WARNING, "track height is too large\n");
2746 avio_wb32(pb, track->height * 0x10000U);
2754 static int mov_write_tapt_tag(AVIOContext *pb, MOVTrack *track)
2756 int32_t width = av_rescale(track->par->sample_aspect_ratio.num, track->par->width,
2757 track->par->sample_aspect_ratio.den);
2759 int64_t pos = avio_tell(pb);
2761 avio_wb32(pb, 0); /* size */
2762 ffio_wfourcc(pb, "tapt");
2765 ffio_wfourcc(pb, "clef");
2767 avio_wb32(pb, width << 16);
2768 avio_wb32(pb, track->par->height << 16);
2771 ffio_wfourcc(pb, "prof");
2773 avio_wb32(pb, width << 16);
2774 avio_wb32(pb, track->par->height << 16);
2777 ffio_wfourcc(pb, "enof");
2779 avio_wb32(pb, track->par->width << 16);
2780 avio_wb32(pb, track->par->height << 16);
2782 return update_size(pb, pos);
2785 // This box seems important for the psp playback ... without it the movie seems to hang
2786 static int mov_write_edts_tag(AVIOContext *pb, MOVMuxContext *mov,
2789 int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE,
2790 track->timescale, AV_ROUND_UP);
2791 int version = duration < INT32_MAX ? 0 : 1;
2792 int entry_size, entry_count, size;
2793 int64_t delay, start_ct = track->start_cts;
2794 int64_t start_dts = track->start_dts;
2797 if (start_dts != track->cluster[0].dts || start_ct != track->cluster[0].cts) {
2799 av_log(mov->fc, AV_LOG_DEBUG,
2800 "EDTS using dts:%"PRId64" cts:%d instead of dts:%"PRId64" cts:%"PRId64" tid:%d\n",
2801 track->cluster[0].dts, track->cluster[0].cts,
2802 start_dts, start_ct, track->track_id);
2803 start_dts = track->cluster[0].dts;
2804 start_ct = track->cluster[0].cts;
2808 delay = av_rescale_rnd(start_dts + start_ct, MOV_TIMESCALE,
2809 track->timescale, AV_ROUND_DOWN);
2810 version |= delay < INT32_MAX ? 0 : 1;
2812 entry_size = (version == 1) ? 20 : 12;
2813 entry_count = 1 + (delay > 0);
2814 size = 24 + entry_count * entry_size;
2816 /* write the atom data */
2817 avio_wb32(pb, size);
2818 ffio_wfourcc(pb, "edts");
2819 avio_wb32(pb, size - 8);
2820 ffio_wfourcc(pb, "elst");
2821 avio_w8(pb, version);
2822 avio_wb24(pb, 0); /* flags */
2824 avio_wb32(pb, entry_count);
2825 if (delay > 0) { /* add an empty edit to delay presentation */
2826 /* In the positive delay case, the delay includes the cts
2827 * offset, and the second edit list entry below trims out
2828 * the same amount from the actual content. This makes sure
2829 * that the offset last sample is included in the edit
2830 * list duration as well. */
2832 avio_wb64(pb, delay);
2835 avio_wb32(pb, delay);
2838 avio_wb32(pb, 0x00010000);
2840 /* Avoid accidentally ending up with start_ct = -1 which has got a
2841 * special meaning. Normally start_ct should end up positive or zero
2842 * here, but use FFMIN in case dts is a small positive integer
2843 * rounded to 0 when represented in MOV_TIMESCALE units. */
2844 av_assert0(av_rescale_rnd(start_dts, MOV_TIMESCALE, track->timescale, AV_ROUND_DOWN) <= 0);
2845 start_ct = -FFMIN(start_dts, 0);
2846 /* Note, this delay is calculated from the pts of the first sample,
2847 * ensuring that we don't reduce the duration for cases with
2852 /* For fragmented files, we don't know the full length yet. Setting
2853 * duration to 0 allows us to only specify the offset, including
2854 * the rest of the content (from all future fragments) without specifying
2855 * an explicit duration. */
2856 if (mov->flags & FF_MOV_FLAG_FRAGMENT)
2861 avio_wb64(pb, duration);
2862 avio_wb64(pb, start_ct);
2864 avio_wb32(pb, duration);
2865 avio_wb32(pb, start_ct);
2867 avio_wb32(pb, 0x00010000);
2871 static int mov_write_tref_tag(AVIOContext *pb, MOVTrack *track)
2873 avio_wb32(pb, 20); // size
2874 ffio_wfourcc(pb, "tref");
2875 avio_wb32(pb, 12); // size (subatom)
2876 avio_wl32(pb, track->tref_tag);
2877 avio_wb32(pb, track->tref_id);
2881 // goes at the end of each track! ... Critical for PSP playback ("Incompatible data" without it)
2882 static int mov_write_uuid_tag_psp(AVIOContext *pb, MOVTrack *mov)
2884 avio_wb32(pb, 0x34); /* size ... reports as 28 in mp4box! */
2885 ffio_wfourcc(pb, "uuid");
2886 ffio_wfourcc(pb, "USMT");
2887 avio_wb32(pb, 0x21d24fce);
2888 avio_wb32(pb, 0xbb88695c);
2889 avio_wb32(pb, 0xfac9c740);
2890 avio_wb32(pb, 0x1c); // another size here!
2891 ffio_wfourcc(pb, "MTDT");
2892 avio_wb32(pb, 0x00010012);
2893 avio_wb32(pb, 0x0a);
2894 avio_wb32(pb, 0x55c40000);
2900 static int mov_write_udta_sdp(AVIOContext *pb, MOVTrack *track)
2902 AVFormatContext *ctx = track->rtp_ctx;
2903 char buf[1000] = "";
2906 ff_sdp_write_media(buf, sizeof(buf), ctx->streams[0], track->src_track,
2907 NULL, NULL, 0, 0, ctx);
2908 av_strlcatf(buf, sizeof(buf), "a=control:streamid=%d\r\n", track->track_id);
2911 avio_wb32(pb, len + 24);
2912 ffio_wfourcc(pb, "udta");
2913 avio_wb32(pb, len + 16);
2914 ffio_wfourcc(pb, "hnti");
2915 avio_wb32(pb, len + 8);
2916 ffio_wfourcc(pb, "sdp ");
2917 avio_write(pb, buf, len);
2921 static int mov_write_track_metadata(AVIOContext *pb, AVStream *st,
2922 const char *tag, const char *str)
2924 int64_t pos = avio_tell(pb);
2925 AVDictionaryEntry *t = av_dict_get(st->metadata, str, NULL, 0);
2926 if (!t || !utf8len(t->value))
2929 avio_wb32(pb, 0); /* size */
2930 ffio_wfourcc(pb, tag); /* type */
2931 avio_write(pb, t->value, strlen(t->value)); /* UTF8 string value */
2932 return update_size(pb, pos);
2935 static int mov_write_track_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
2938 AVIOContext *pb_buf;
2945 ret = avio_open_dyn_buf(&pb_buf);
2949 if (mov->mode & MODE_MP4)
2950 mov_write_track_metadata(pb_buf, st, "name", "title");
2952 if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) {
2953 avio_wb32(pb, size + 8);
2954 ffio_wfourcc(pb, "udta");
2955 avio_write(pb, buf, size);
2962 static int mov_write_trak_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov,
2963 MOVTrack *track, AVStream *st)
2965 int64_t pos = avio_tell(pb);
2966 int entry_backup = track->entry;
2967 int chunk_backup = track->chunkCount;
2970 /* If we want to have an empty moov, but some samples already have been
2971 * buffered (delay_moov), pretend that no samples have been written yet. */
2972 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV)
2973 track->chunkCount = track->entry = 0;
2975 avio_wb32(pb, 0); /* size */
2976 ffio_wfourcc(pb, "trak");
2977 mov_write_tkhd_tag(pb, mov, track, st);
2979 av_assert2(mov->use_editlist >= 0);
2981 if (track->start_dts != AV_NOPTS_VALUE) {
2982 if (mov->use_editlist)
2983 mov_write_edts_tag(pb, mov, track); // PSP Movies and several other cases require edts box
2984 else if ((track->entry && track->cluster[0].dts) || track->mode == MODE_PSP || is_clcp_track(track))
2985 av_log(mov->fc, AV_LOG_WARNING,
2986 "Not writing any edit list even though one would have been required\n");
2989 if (track->tref_tag)
2990 mov_write_tref_tag(pb, track);
2992 if ((ret = mov_write_mdia_tag(s, pb, mov, track)) < 0)
2994 if (track->mode == MODE_PSP)
2995 mov_write_uuid_tag_psp(pb, track); // PSP Movies require this uuid box
2996 if (track->tag == MKTAG('r','t','p',' '))
2997 mov_write_udta_sdp(pb, track);
2998 if (track->mode == MODE_MOV) {
2999 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
3000 double sample_aspect_ratio = av_q2d(st->sample_aspect_ratio);
3001 if (st->sample_aspect_ratio.num && 1.0 != sample_aspect_ratio) {
3002 mov_write_tapt_tag(pb, track);
3005 if (is_clcp_track(track) && st->sample_aspect_ratio.num) {
3006 mov_write_tapt_tag(pb, track);
3009 mov_write_track_udta_tag(pb, mov, st);
3010 track->entry = entry_backup;
3011 track->chunkCount = chunk_backup;
3012 return update_size(pb, pos);
3015 static int mov_write_iods_tag(AVIOContext *pb, MOVMuxContext *mov)
3017 int i, has_audio = 0, has_video = 0;
3018 int64_t pos = avio_tell(pb);
3019 int audio_profile = mov->iods_audio_profile;
3020 int video_profile = mov->iods_video_profile;
3021 for (i = 0; i < mov->nb_streams; i++) {
3022 if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
3023 has_audio |= mov->tracks[i].par->codec_type == AVMEDIA_TYPE_AUDIO;
3024 has_video |= mov->tracks[i].par->codec_type == AVMEDIA_TYPE_VIDEO;
3027 if (audio_profile < 0)
3028 audio_profile = 0xFF - has_audio;
3029 if (video_profile < 0)
3030 video_profile = 0xFF - has_video;
3031 avio_wb32(pb, 0x0); /* size */
3032 ffio_wfourcc(pb, "iods");
3033 avio_wb32(pb, 0); /* version & flags */
3034 put_descr(pb, 0x10, 7);
3035 avio_wb16(pb, 0x004f);
3038 avio_w8(pb, audio_profile);
3039 avio_w8(pb, video_profile);
3041 return update_size(pb, pos);
3044 static int mov_write_trex_tag(AVIOContext *pb, MOVTrack *track)
3046 avio_wb32(pb, 0x20); /* size */
3047 ffio_wfourcc(pb, "trex");
3048 avio_wb32(pb, 0); /* version & flags */
3049 avio_wb32(pb, track->track_id); /* track ID */
3050 avio_wb32(pb, 1); /* default sample description index */
3051 avio_wb32(pb, 0); /* default sample duration */
3052 avio_wb32(pb, 0); /* default sample size */
3053 avio_wb32(pb, 0); /* default sample flags */
3057 static int mov_write_mvex_tag(AVIOContext *pb, MOVMuxContext *mov)
3059 int64_t pos = avio_tell(pb);
3061 avio_wb32(pb, 0x0); /* size */
3062 ffio_wfourcc(pb, "mvex");
3063 for (i = 0; i < mov->nb_streams; i++)
3064 mov_write_trex_tag(pb, &mov->tracks[i]);
3065 return update_size(pb, pos);
3068 static int mov_write_mvhd_tag(AVIOContext *pb, MOVMuxContext *mov)
3070 int max_track_id = 1, i;
3071 int64_t max_track_len = 0;
3074 for (i = 0; i < mov->nb_streams; i++) {
3075 if (mov->tracks[i].entry > 0 && mov->tracks[i].timescale) {
3076 int64_t max_track_len_temp = av_rescale_rnd(mov->tracks[i].track_duration,
3078 mov->tracks[i].timescale,
3080 if (max_track_len < max_track_len_temp)
3081 max_track_len = max_track_len_temp;
3082 if (max_track_id < mov->tracks[i].track_id)
3083 max_track_id = mov->tracks[i].track_id;
3086 /* If using delay_moov, make sure the output is the same as if no
3087 * samples had been written yet. */
3088 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
3093 version = max_track_len < UINT32_MAX ? 0 : 1;
3094 avio_wb32(pb, version == 1 ? 120 : 108); /* size */
3096 ffio_wfourcc(pb, "mvhd");
3097 avio_w8(pb, version);
3098 avio_wb24(pb, 0); /* flags */
3100 avio_wb64(pb, mov->time);
3101 avio_wb64(pb, mov->time);
3103 avio_wb32(pb, mov->time); /* creation time */
3104 avio_wb32(pb, mov->time); /* modification time */
3106 avio_wb32(pb, MOV_TIMESCALE);
3107 (version == 1) ? avio_wb64(pb, max_track_len) : avio_wb32(pb, max_track_len); /* duration of longest track */
3109 avio_wb32(pb, 0x00010000); /* reserved (preferred rate) 1.0 = normal */
3110 avio_wb16(pb, 0x0100); /* reserved (preferred volume) 1.0 = normal */
3111 avio_wb16(pb, 0); /* reserved */
3112 avio_wb32(pb, 0); /* reserved */
3113 avio_wb32(pb, 0); /* reserved */
3115 /* Matrix structure */
3116 write_matrix(pb, 1, 0, 0, 1, 0, 0);
3118 avio_wb32(pb, 0); /* reserved (preview time) */
3119 avio_wb32(pb, 0); /* reserved (preview duration) */
3120 avio_wb32(pb, 0); /* reserved (poster time) */
3121 avio_wb32(pb, 0); /* reserved (selection time) */
3122 avio_wb32(pb, 0); /* reserved (selection duration) */
3123 avio_wb32(pb, 0); /* reserved (current time) */
3124 avio_wb32(pb, max_track_id + 1); /* Next track id */
3128 static int mov_write_itunes_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov,
3131 avio_wb32(pb, 33); /* size */
3132 ffio_wfourcc(pb, "hdlr");
3135 ffio_wfourcc(pb, "mdir");
3136 ffio_wfourcc(pb, "appl");
3143 /* helper function to write a data tag with the specified string as data */
3144 static int mov_write_string_data_tag(AVIOContext *pb, const char *data, int lang, int long_style)
3147 int size = 16 + strlen(data);
3148 avio_wb32(pb, size); /* size */
3149 ffio_wfourcc(pb, "data");
3152 avio_write(pb, data, strlen(data));
3156 lang = ff_mov_iso639_to_lang("und", 1);
3157 avio_wb16(pb, strlen(data)); /* string length */
3158 avio_wb16(pb, lang);
3159 avio_write(pb, data, strlen(data));
3160 return strlen(data) + 4;
3164 static int mov_write_string_tag(AVIOContext *pb, const char *name,
3165 const char *value, int lang, int long_style)
3168 if (value && value[0]) {
3169 int64_t pos = avio_tell(pb);
3170 avio_wb32(pb, 0); /* size */
3171 ffio_wfourcc(pb, name);
3172 mov_write_string_data_tag(pb, value, lang, long_style);
3173 size = update_size(pb, pos);
3178 static AVDictionaryEntry *get_metadata_lang(AVFormatContext *s,
3179 const char *tag, int *lang)
3182 AVDictionaryEntry *t, *t2 = NULL;
3187 if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
3190 len = strlen(t->key);
3191 snprintf(tag2, sizeof(tag2), "%s-", tag);
3192 while ((t2 = av_dict_get(s->metadata, tag2, t2, AV_DICT_IGNORE_SUFFIX))) {
3193 len2 = strlen(t2->key);
3194 if (len2 == len + 4 && !strcmp(t->value, t2->value)
3195 && (l = ff_mov_iso639_to_lang(&t2->key[len2 - 3], 1)) >= 0) {
3203 static int mov_write_string_metadata(AVFormatContext *s, AVIOContext *pb,
3204 const char *name, const char *tag,
3208 AVDictionaryEntry *t = get_metadata_lang(s, tag, &lang);
3211 return mov_write_string_tag(pb, name, t->value, lang, long_style);
3214 /* iTunes bpm number */
3215 static int mov_write_tmpo_tag(AVIOContext *pb, AVFormatContext *s)
3217 AVDictionaryEntry *t = av_dict_get(s->metadata, "tmpo", NULL, 0);
3218 int size = 0, tmpo = t ? atoi(t->value) : 0;
3221 avio_wb32(pb, size);
3222 ffio_wfourcc(pb, "tmpo");
3223 avio_wb32(pb, size-8); /* size */
3224 ffio_wfourcc(pb, "data");
3225 avio_wb32(pb, 0x15); //type specifier
3227 avio_wb16(pb, tmpo); // data
3232 /* 3GPP TS 26.244 */
3233 static int mov_write_loci_tag(AVFormatContext *s, AVIOContext *pb)
3236 int64_t pos = avio_tell(pb);
3237 double latitude, longitude, altitude;
3238 int32_t latitude_fix, longitude_fix, altitude_fix;
3239 AVDictionaryEntry *t = get_metadata_lang(s, "location", &lang);
3240 const char *ptr, *place = "";
3242 static const char *astronomical_body = "earth";
3247 longitude = strtod(ptr, &end);
3249 av_log(s, AV_LOG_WARNING, "malformed location metadata\n");
3253 latitude = strtod(ptr, &end);
3255 av_log(s, AV_LOG_WARNING, "malformed location metadata\n");
3259 altitude = strtod(ptr, &end);
3260 /* If no altitude was present, the default 0 should be fine */
3264 latitude_fix = (int32_t) ((1 << 16) * latitude);
3265 longitude_fix = (int32_t) ((1 << 16) * longitude);
3266 altitude_fix = (int32_t) ((1 << 16) * altitude);
3268 avio_wb32(pb, 0); /* size */
3269 ffio_wfourcc(pb, "loci"); /* type */
3270 avio_wb32(pb, 0); /* version + flags */
3271 avio_wb16(pb, lang);
3272 avio_write(pb, place, strlen(place) + 1);
3273 avio_w8(pb, 0); /* role of place (0 == shooting location, 1 == real location, 2 == fictional location) */
3274 avio_wb32(pb, latitude_fix);
3275 avio_wb32(pb, longitude_fix);
3276 avio_wb32(pb, altitude_fix);
3277 avio_write(pb, astronomical_body, strlen(astronomical_body) + 1);
3278 avio_w8(pb, 0); /* additional notes, null terminated string */
3280 return update_size(pb, pos);
3283 /* iTunes track or disc number */
3284 static int mov_write_trkn_tag(AVIOContext *pb, MOVMuxContext *mov,
3285 AVFormatContext *s, int disc)
3287 AVDictionaryEntry *t = av_dict_get(s->metadata,
3288 disc ? "disc" : "track",
3290 int size = 0, track = t ? atoi(t->value) : 0;
3293 char *slash = strchr(t->value, '/');
3295 tracks = atoi(slash + 1);
3296 avio_wb32(pb, 32); /* size */
3297 ffio_wfourcc(pb, disc ? "disk" : "trkn");
3298 avio_wb32(pb, 24); /* size */
3299 ffio_wfourcc(pb, "data");
3300 avio_wb32(pb, 0); // 8 bytes empty
3302 avio_wb16(pb, 0); // empty
3303 avio_wb16(pb, track); // track / disc number
3304 avio_wb16(pb, tracks); // total track / disc number
3305 avio_wb16(pb, 0); // empty
3311 static int mov_write_int8_metadata(AVFormatContext *s, AVIOContext *pb,
3312 const char *name, const char *tag,
3315 AVDictionaryEntry *t = NULL;
3317 int size = 24 + len;
3319 if (len != 1 && len != 4)
3322 if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
3324 num = atoi(t->value);
3326 avio_wb32(pb, size);
3327 ffio_wfourcc(pb, name);
3328 avio_wb32(pb, size - 8);
3329 ffio_wfourcc(pb, "data");
3330 avio_wb32(pb, 0x15);
3332 if (len==4) avio_wb32(pb, num);
3333 else avio_w8 (pb, num);
3338 /* iTunes meta data list */
3339 static int mov_write_ilst_tag(AVIOContext *pb, MOVMuxContext *mov,
3342 int64_t pos = avio_tell(pb);
3343 avio_wb32(pb, 0); /* size */
3344 ffio_wfourcc(pb, "ilst");
3345 mov_write_string_metadata(s, pb, "\251nam", "title" , 1);
3346 mov_write_string_metadata(s, pb, "\251ART", "artist" , 1);
3347 mov_write_string_metadata(s, pb, "aART", "album_artist", 1);
3348 mov_write_string_metadata(s, pb, "\251wrt", "composer" , 1);
3349 mov_write_string_metadata(s, pb, "\251alb", "album" , 1);
3350 mov_write_string_metadata(s, pb, "\251day", "date" , 1);
3351 if (!mov_write_string_metadata(s, pb, "\251too", "encoding_tool", 1)) {
3352 if (!(s->flags & AVFMT_FLAG_BITEXACT))
3353 mov_write_string_tag(pb, "\251too", LIBAVFORMAT_IDENT, 0, 1);
3355 mov_write_string_metadata(s, pb, "\251cmt", "comment" , 1);
3356 mov_write_string_metadata(s, pb, "\251gen", "genre" , 1);
3357 mov_write_string_metadata(s, pb, "\251cpy", "copyright", 1);
3358 mov_write_string_metadata(s, pb, "\251grp", "grouping" , 1);
3359 mov_write_string_metadata(s, pb, "\251lyr", "lyrics" , 1);
3360 mov_write_string_metadata(s, pb, "desc", "description",1);
3361 mov_write_string_metadata(s, pb, "ldes", "synopsis" , 1);
3362 mov_write_string_metadata(s, pb, "tvsh", "show" , 1);
3363 mov_write_string_metadata(s, pb, "tven", "episode_id",1);
3364 mov_write_string_metadata(s, pb, "tvnn", "network" , 1);
3365 mov_write_string_metadata(s, pb, "keyw", "keywords" , 1);
3366 mov_write_int8_metadata (s, pb, "tves", "episode_sort",4);
3367 mov_write_int8_metadata (s, pb, "tvsn", "season_number",4);
3368 mov_write_int8_metadata (s, pb, "stik", "media_type",1);
3369 mov_write_int8_metadata (s, pb, "hdvd", "hd_video", 1);
3370 mov_write_int8_metadata (s, pb, "pgap", "gapless_playback",1);
3371 mov_write_int8_metadata (s, pb, "cpil", "compilation", 1);
3372 mov_write_trkn_tag(pb, mov, s, 0); // track number
3373 mov_write_trkn_tag(pb, mov, s, 1); // disc number
3374 mov_write_tmpo_tag(pb, s);
3375 return update_size(pb, pos);
3378 static int mov_write_mdta_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov,
3381 avio_wb32(pb, 33); /* size */
3382 ffio_wfourcc(pb, "hdlr");
3385 ffio_wfourcc(pb, "mdta");
3393 static int mov_write_mdta_keys_tag(AVIOContext *pb, MOVMuxContext *mov,
3396 AVDictionaryEntry *t = NULL;
3397 int64_t pos = avio_tell(pb);
3398 int64_t curpos, entry_pos;
3401 avio_wb32(pb, 0); /* size */
3402 ffio_wfourcc(pb, "keys");
3404 entry_pos = avio_tell(pb);
3405 avio_wb32(pb, 0); /* entry count */
3407 while (t = av_dict_get(s->metadata, "", t, AV_DICT_IGNORE_SUFFIX)) {
3408 avio_wb32(pb, strlen(t->key) + 8);
3409 ffio_wfourcc(pb, "mdta");
3410 avio_write(pb, t->key, strlen(t->key));
3413 curpos = avio_tell(pb);
3414 avio_seek(pb, entry_pos, SEEK_SET);
3415 avio_wb32(pb, count); // rewrite entry count
3416 avio_seek(pb, curpos, SEEK_SET);
3418 return update_size(pb, pos);
3421 static int mov_write_mdta_ilst_tag(AVIOContext *pb, MOVMuxContext *mov,
3424 AVDictionaryEntry *t = NULL;
3425 int64_t pos = avio_tell(pb);
3426 int count = 1; /* keys are 1-index based */
3428 avio_wb32(pb, 0); /* size */
3429 ffio_wfourcc(pb, "ilst");
3431 while (t = av_dict_get(s->metadata, "", t, AV_DICT_IGNORE_SUFFIX)) {
3432 int64_t entry_pos = avio_tell(pb);
3433 avio_wb32(pb, 0); /* size */
3434 avio_wb32(pb, count); /* key */
3435 mov_write_string_data_tag(pb, t->value, 0, 1);
3436 update_size(pb, entry_pos);
3439 return update_size(pb, pos);
3442 /* meta data tags */
3443 static int mov_write_meta_tag(AVIOContext *pb, MOVMuxContext *mov,
3447 int64_t pos = avio_tell(pb);
3448 avio_wb32(pb, 0); /* size */
3449 ffio_wfourcc(pb, "meta");
3451 if (mov->flags & FF_MOV_FLAG_USE_MDTA) {
3452 mov_write_mdta_hdlr_tag(pb, mov, s);
3453 mov_write_mdta_keys_tag(pb, mov, s);
3454 mov_write_mdta_ilst_tag(pb, mov, s);
3457 /* iTunes metadata tag */
3458 mov_write_itunes_hdlr_tag(pb, mov, s);
3459 mov_write_ilst_tag(pb, mov, s);
3461 size = update_size(pb, pos);
3465 static int mov_write_raw_metadata_tag(AVFormatContext *s, AVIOContext *pb,
3466 const char *name, const char *key)
3469 AVDictionaryEntry *t;
3471 if (!(t = av_dict_get(s->metadata, key, NULL, 0)))
3474 len = strlen(t->value);
3477 avio_wb32(pb, size);
3478 ffio_wfourcc(pb, name);
3479 avio_write(pb, t->value, len);
3485 static int ascii_to_wc(AVIOContext *pb, const uint8_t *b)
3489 GET_UTF8(val, *b++, return -1;)
3492 avio_wb16(pb, 0x00);
3496 static uint16_t language_code(const char *str)
3498 return (((str[0] - 0x60) & 0x1F) << 10) +
3499 (((str[1] - 0x60) & 0x1F) << 5) +
3500 (( str[2] - 0x60) & 0x1F);
3503 static int mov_write_3gp_udta_tag(AVIOContext *pb, AVFormatContext *s,
3504 const char *tag, const char *str)
3506 int64_t pos = avio_tell(pb);
3507 AVDictionaryEntry *t = av_dict_get(s->metadata, str, NULL, 0);
3508 if (!t || !utf8len(t->value))
3510 avio_wb32(pb, 0); /* size */
3511 ffio_wfourcc(pb, tag); /* type */
3512 avio_wb32(pb, 0); /* version + flags */
3513 if (!strcmp(tag, "yrrc"))
3514 avio_wb16(pb, atoi(t->value));
3516 avio_wb16(pb, language_code("eng")); /* language */
3517 avio_write(pb, t->value, strlen(t->value) + 1); /* UTF8 string value */
3518 if (!strcmp(tag, "albm") &&
3519 (t = av_dict_get(s->metadata, "track", NULL, 0)))
3520 avio_w8(pb, atoi(t->value));
3522 return update_size(pb, pos);
3525 static int mov_write_chpl_tag(AVIOContext *pb, AVFormatContext *s)
3527 int64_t pos = avio_tell(pb);
3528 int i, nb_chapters = FFMIN(s->nb_chapters, 255);
3530 avio_wb32(pb, 0); // size
3531 ffio_wfourcc(pb, "chpl");
3532 avio_wb32(pb, 0x01000000); // version + flags
3533 avio_wb32(pb, 0); // unknown
3534 avio_w8(pb, nb_chapters);
3536 for (i = 0; i < nb_chapters; i++) {
3537 AVChapter *c = s->chapters[i];
3538 AVDictionaryEntry *t;
3539 avio_wb64(pb, av_rescale_q(c->start, c->time_base, (AVRational){1,10000000}));
3541 if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
3542 int len = FFMIN(strlen(t->value), 255);
3544 avio_write(pb, t->value, len);
3548 return update_size(pb, pos);
3551 static int mov_write_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
3554 AVIOContext *pb_buf;
3558 ret = avio_open_dyn_buf(&pb_buf);
3562 if (mov->mode & MODE_3GP) {
3563 mov_write_3gp_udta_tag(pb_buf, s, "perf", "artist");
3564 mov_write_3gp_udta_tag(pb_buf, s, "titl", "title");
3565 mov_write_3gp_udta_tag(pb_buf, s, "auth", "author");
3566 mov_write_3gp_udta_tag(pb_buf, s, "gnre", "genre");
3567 mov_write_3gp_udta_tag(pb_buf, s, "dscp", "comment");
3568 mov_write_3gp_udta_tag(pb_buf, s, "albm", "album");
3569 mov_write_3gp_udta_tag(pb_buf, s, "cprt", "copyright");
3570 mov_write_3gp_udta_tag(pb_buf, s, "yrrc", "date");
3571 mov_write_loci_tag(s, pb_buf);
3572 } 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
3573 mov_write_string_metadata(s, pb_buf, "\251ART", "artist", 0);
3574 mov_write_string_metadata(s, pb_buf, "\251nam", "title", 0);
3575 mov_write_string_metadata(s, pb_buf, "\251aut", "author", 0);
3576 mov_write_string_metadata(s, pb_buf, "\251alb", "album", 0);
3577 mov_write_string_metadata(s, pb_buf, "\251day", "date", 0);
3578 mov_write_string_metadata(s, pb_buf, "\251swr", "encoder", 0);
3579 // currently ignored by mov.c
3580 mov_write_string_metadata(s, pb_buf, "\251des", "comment", 0);
3581 // add support for libquicktime, this atom is also actually read by mov.c
3582 mov_write_string_metadata(s, pb_buf, "\251cmt", "comment", 0);
3583 mov_write_string_metadata(s, pb_buf, "\251gen", "genre", 0);
3584 mov_write_string_metadata(s, pb_buf, "\251cpy", "copyright", 0);
3585 mov_write_string_metadata(s, pb_buf, "\251mak", "make", 0);
3586 mov_write_string_metadata(s, pb_buf, "\251mod", "model", 0);
3587 mov_write_string_metadata(s, pb_buf, "\251xyz", "location", 0);
3588 mov_write_string_metadata(s, pb_buf, "\251key", "keywords", 0);
3589 mov_write_raw_metadata_tag(s, pb_buf, "XMP_", "xmp");
3591 /* iTunes meta data */
3592 mov_write_meta_tag(pb_buf, mov, s);
3593 mov_write_loci_tag(s, pb_buf);
3596 if (s->nb_chapters && !(mov->flags & FF_MOV_FLAG_DISABLE_CHPL))
3597 mov_write_chpl_tag(pb_buf, s);
3599 if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) {
3600 avio_wb32(pb, size + 8);
3601 ffio_wfourcc(pb, "udta");
3602 avio_write(pb, buf, size);
3609 static void mov_write_psp_udta_tag(AVIOContext *pb,
3610 const char *str, const char *lang, int type)
3612 int len = utf8len(str) + 1;
3615 avio_wb16(pb, len * 2 + 10); /* size */
3616 avio_wb32(pb, type); /* type */
3617 avio_wb16(pb, language_code(lang)); /* language */
3618 avio_wb16(pb, 0x01); /* ? */
3619 ascii_to_wc(pb, str);
3622 static int mov_write_uuidusmt_tag(AVIOContext *pb, AVFormatContext *s)
3624 AVDictionaryEntry *title = av_dict_get(s->metadata, "title", NULL, 0);
3628 pos = avio_tell(pb);
3629 avio_wb32(pb, 0); /* size placeholder*/
3630 ffio_wfourcc(pb, "uuid");
3631 ffio_wfourcc(pb, "USMT");
3632 avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
3633 avio_wb32(pb, 0xbb88695c);
3634 avio_wb32(pb, 0xfac9c740);
3636 pos2 = avio_tell(pb);
3637 avio_wb32(pb, 0); /* size placeholder*/
3638 ffio_wfourcc(pb, "MTDT");
3642 avio_wb16(pb, 0x0C); /* size */
3643 avio_wb32(pb, 0x0B); /* type */
3644 avio_wb16(pb, language_code("und")); /* language */
3645 avio_wb16(pb, 0x0); /* ? */
3646 avio_wb16(pb, 0x021C); /* data */
3648 if (!(s->flags & AVFMT_FLAG_BITEXACT))
3649 mov_write_psp_udta_tag(pb, LIBAVCODEC_IDENT, "eng", 0x04);
3650 mov_write_psp_udta_tag(pb, title->value, "eng", 0x01);
3651 mov_write_psp_udta_tag(pb, "2006/04/01 11:11:11", "und", 0x03);
3653 update_size(pb, pos2);
3654 return update_size(pb, pos);
3660 static void build_chunks(MOVTrack *trk)
3663 MOVIentry *chunk = &trk->cluster[0];
3664 uint64_t chunkSize = chunk->size;
3665 chunk->chunkNum = 1;
3666 if (trk->chunkCount)
3668 trk->chunkCount = 1;
3669 for (i = 1; i<trk->entry; i++){
3670 if (chunk->pos + chunkSize == trk->cluster[i].pos &&
3671 chunkSize + trk->cluster[i].size < (1<<20)){
3672 chunkSize += trk->cluster[i].size;
3673 chunk->samples_in_chunk += trk->cluster[i].entries;
3675 trk->cluster[i].chunkNum = chunk->chunkNum+1;
3676 chunk=&trk->cluster[i];
3677 chunkSize = chunk->size;
3684 * Assign track ids. If option "use_stream_ids_as_track_ids" is set,
3685 * the stream ids are used as track ids.
3687 * This assumes mov->tracks and s->streams are in the same order and
3688 * there are no gaps in either of them (so mov->tracks[n] refers to
3691 * As an exception, there can be more entries in
3692 * s->streams than in mov->tracks, in which case new track ids are
3693 * generated (starting after the largest found stream id).
3695 static int mov_setup_track_ids(MOVMuxContext *mov, AVFormatContext *s)
3699 if (mov->track_ids_ok)
3702 if (mov->use_stream_ids_as_track_ids) {
3703 int next_generated_track_id = 0;
3704 for (i = 0; i < s->nb_streams; i++) {
3705 if (s->streams[i]->id > next_generated_track_id)
3706 next_generated_track_id = s->streams[i]->id;
3709 for (i = 0; i < mov->nb_streams; i++) {
3710 if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
3713 mov->tracks[i].track_id = i >= s->nb_streams ? ++next_generated_track_id : s->streams[i]->id;
3716 for (i = 0; i < mov->nb_streams; i++) {
3717 if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
3720 mov->tracks[i].track_id = i + 1;
3724 mov->track_ids_ok = 1;
3729 static int mov_write_moov_tag(AVIOContext *pb, MOVMuxContext *mov,
3733 int64_t pos = avio_tell(pb);
3734 avio_wb32(pb, 0); /* size placeholder*/
3735 ffio_wfourcc(pb, "moov");
3737 mov_setup_track_ids(mov, s);
3739 for (i = 0; i < mov->nb_streams; i++) {
3740 if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
3743 mov->tracks[i].time = mov->time;
3745 if (mov->tracks[i].entry)
3746 build_chunks(&mov->tracks[i]);
3749 if (mov->chapter_track)
3750 for (i = 0; i < s->nb_streams; i++) {
3751 mov->tracks[i].tref_tag = MKTAG('c','h','a','p');
3752 mov->tracks[i].tref_id = mov->tracks[mov->chapter_track].track_id;
3754 for (i = 0; i < mov->nb_streams; i++) {
3755 MOVTrack *track = &mov->tracks[i];
3756 if (track->tag == MKTAG('r','t','p',' ')) {
3757 track->tref_tag = MKTAG('h','i','n','t');
3758 track->tref_id = mov->tracks[track->src_track].track_id;
3759 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
3760 int * fallback, size;
3761 fallback = (int*)av_stream_get_side_data(track->st,
3762 AV_PKT_DATA_FALLBACK_TRACK,
3764 if (fallback != NULL && size == sizeof(int)) {
3765 if (*fallback >= 0 && *fallback < mov->nb_streams) {
3766 track->tref_tag = MKTAG('f','a','l','l');
3767 track->tref_id = mov->tracks[*fallback].track_id;
3772 for (i = 0; i < mov->nb_streams; i++) {
3773 if (mov->tracks[i].tag == MKTAG('t','m','c','d')) {
3774 int src_trk = mov->tracks[i].src_track;
3775 mov->tracks[src_trk].tref_tag = mov->tracks[i].tag;
3776 mov->tracks[src_trk].tref_id = mov->tracks[i].track_id;
3777 //src_trk may have a different timescale than the tmcd track
3778 mov->tracks[i].track_duration = av_rescale(mov->tracks[src_trk].track_duration,
3779 mov->tracks[i].timescale,
3780 mov->tracks[src_trk].timescale);
3784 mov_write_mvhd_tag(pb, mov);
3785 if (mov->mode != MODE_MOV && !mov->iods_skip)
3786 mov_write_iods_tag(pb, mov);
3787 for (i = 0; i < mov->nb_streams; i++) {
3788 if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_FRAGMENT) {
3789 int ret = mov_write_trak_tag(s, pb, mov, &(mov->tracks[i]), i < s->nb_streams ? s->streams[i] : NULL);
3794 if (mov->flags & FF_MOV_FLAG_FRAGMENT)
3795 mov_write_mvex_tag(pb, mov); /* QuickTime requires trak to precede this */
3797 if (mov->mode == MODE_PSP)
3798 mov_write_uuidusmt_tag(pb, s);
3800 mov_write_udta_tag(pb, mov, s);
3802 return update_size(pb, pos);
3805 static void param_write_int(AVIOContext *pb, const char *name, int value)
3807 avio_printf(pb, "<param name=\"%s\" value=\"%d\" valuetype=\"data\"/>\n", name, value);
3810 static void param_write_string(AVIOContext *pb, const char *name, const char *value)
3812 avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, value);
3815 static void param_write_hex(AVIOContext *pb, const char *name, const uint8_t *value, int len)
3818 len = FFMIN(sizeof(buf) / 2 - 1, len);
3819 ff_data_to_hex(buf, value, len, 0);
3820 buf[2 * len] = '\0';
3821 avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, buf);
3824 static int mov_write_isml_manifest(AVIOContext *pb, MOVMuxContext *mov, AVFormatContext *s)
3826 int64_t pos = avio_tell(pb);
3828 int64_t manifest_bit_rate = 0;
3829 AVCPBProperties *props = NULL;
3831 static const uint8_t uuid[] = {
3832 0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd,
3833 0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66
3837 ffio_wfourcc(pb, "uuid");
3838 avio_write(pb, uuid, sizeof(uuid));
3841 avio_printf(pb, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
3842 avio_printf(pb, "<smil xmlns=\"http://www.w3.org/2001/SMIL20/Language\">\n");
3843 avio_printf(pb, "<head>\n");
3844 if (!(mov->fc->flags & AVFMT_FLAG_BITEXACT))
3845 avio_printf(pb, "<meta name=\"creator\" content=\"%s\" />\n",
3847 avio_printf(pb, "</head>\n");
3848 avio_printf(pb, "<body>\n");
3849 avio_printf(pb, "<switch>\n");
3851 mov_setup_track_ids(mov, s);
3853 for (i = 0; i < mov->nb_streams; i++) {
3854 MOVTrack *track = &mov->tracks[i];
3856 int track_id = track->track_id;
3857 char track_name_buf[32] = { 0 };
3859 AVStream *st = track->st;
3860 AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0);
3862 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
3864 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
3870 props = (AVCPBProperties*)av_stream_get_side_data(track->st, AV_PKT_DATA_CPB_PROPERTIES, NULL);
3872 if (track->par->bit_rate) {
3873 manifest_bit_rate = track->par->bit_rate;
3875 manifest_bit_rate = props->max_bitrate;
3878 avio_printf(pb, "<%s systemBitrate=\"%"PRId64"\">\n", type,
3880 param_write_int(pb, "systemBitrate", manifest_bit_rate);
3881 param_write_int(pb, "trackID", track_id);
3882 param_write_string(pb, "systemLanguage", lang ? lang->value : "und");
3884 /* Build track name piece by piece: */
3886 av_strlcat(track_name_buf, type, sizeof(track_name_buf));
3887 /* 2. track language, if available */
3889 av_strlcatf(track_name_buf, sizeof(track_name_buf),
3890 "_%s", lang->value);
3891 /* 3. special type suffix */
3892 /* "_cc" = closed captions, "_ad" = audio_description */
3893 if (st->disposition & AV_DISPOSITION_HEARING_IMPAIRED)
3894 av_strlcat(track_name_buf, "_cc", sizeof(track_name_buf));
3895 else if (st->disposition & AV_DISPOSITION_VISUAL_IMPAIRED)
3896 av_strlcat(track_name_buf, "_ad", sizeof(track_name_buf));
3898 param_write_string(pb, "trackName", track_name_buf);
3900 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
3901 if (track->par->codec_id == AV_CODEC_ID_H264) {
3903 int size = track->par->extradata_size;
3904 if (!ff_avc_write_annexb_extradata(track->par->extradata, &ptr,
3906 param_write_hex(pb, "CodecPrivateData",
3907 ptr ? ptr : track->par->extradata,
3911 param_write_string(pb, "FourCC", "H264");
3912 } else if (track->par->codec_id == AV_CODEC_ID_VC1) {
3913 param_write_string(pb, "FourCC", "WVC1");
3914 param_write_hex(pb, "CodecPrivateData", track->par->extradata,
3915 track->par->extradata_size);
3917 param_write_int(pb, "MaxWidth", track->par->width);
3918 param_write_int(pb, "MaxHeight", track->par->height);
3919 param_write_int(pb, "DisplayWidth", track->par->width);
3920 param_write_int(pb, "DisplayHeight", track->par->height);
3922 if (track->par->codec_id == AV_CODEC_ID_AAC) {
3923 switch (track->par->profile)
3925 case FF_PROFILE_AAC_HE_V2:
3926 param_write_string(pb, "FourCC", "AACP");
3928 case FF_PROFILE_AAC_HE:
3929 param_write_string(pb, "FourCC", "AACH");
3932 param_write_string(pb, "FourCC", "AACL");
3934 } else if (track->par->codec_id == AV_CODEC_ID_WMAPRO) {
3935 param_write_string(pb, "FourCC", "WMAP");
3937 param_write_hex(pb, "CodecPrivateData", track->par->extradata,
3938 track->par->extradata_size);
3939 param_write_int(pb, "AudioTag", ff_codec_get_tag(ff_codec_wav_tags,
3940 track->par->codec_id));
3941 param_write_int(pb, "Channels", track->par->channels);
3942 param_write_int(pb, "SamplingRate", track->par->sample_rate);
3943 param_write_int(pb, "BitsPerSample", 16);
3944 param_write_int(pb, "PacketSize", track->par->block_align ?
3945 track->par->block_align : 4);
3947 avio_printf(pb, "</%s>\n", type);
3949 avio_printf(pb, "</switch>\n");
3950 avio_printf(pb, "</body>\n");
3951 avio_printf(pb, "</smil>\n");
3953 return update_size(pb, pos);
3956 static int mov_write_mfhd_tag(AVIOContext *pb, MOVMuxContext *mov)
3959 ffio_wfourcc(pb, "mfhd");
3961 avio_wb32(pb, mov->fragments);
3965 static uint32_t get_sample_flags(MOVTrack *track, MOVIentry *entry)
3967 return entry->flags & MOV_SYNC_SAMPLE ? MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO :
3968 (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC);
3971 static int mov_write_tfhd_tag(AVIOContext *pb, MOVMuxContext *mov,
3972 MOVTrack *track, int64_t moof_offset)
3974 int64_t pos = avio_tell(pb);
3975 uint32_t flags = MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
3976 MOV_TFHD_BASE_DATA_OFFSET;
3977 if (!track->entry) {
3978 flags |= MOV_TFHD_DURATION_IS_EMPTY;
3980 flags |= MOV_TFHD_DEFAULT_FLAGS;
3982 if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET)
3983 flags &= ~MOV_TFHD_BASE_DATA_OFFSET;
3984 if (mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) {
3985 flags &= ~MOV_TFHD_BASE_DATA_OFFSET;
3986 flags |= MOV_TFHD_DEFAULT_BASE_IS_MOOF;
3989 /* Don't set a default sample size, the silverlight player refuses
3990 * to play files with that set. Don't set a default sample duration,
3991 * WMP freaks out if it is set. Don't set a base data offset, PIFF
3992 * file format says it MUST NOT be set. */
3993 if (track->mode == MODE_ISM)
3994 flags &= ~(MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
3995 MOV_TFHD_BASE_DATA_OFFSET);
3997 avio_wb32(pb, 0); /* size placeholder */
3998 ffio_wfourcc(pb, "tfhd");
3999 avio_w8(pb, 0); /* version */
4000 avio_wb24(pb, flags);
4002 avio_wb32(pb, track->track_id); /* track-id */
4003 if (flags & MOV_TFHD_BASE_DATA_OFFSET)
4004 avio_wb64(pb, moof_offset);
4005 if (flags & MOV_TFHD_DEFAULT_DURATION) {
4006 track->default_duration = get_cluster_duration(track, 0);
4007 avio_wb32(pb, track->default_duration);
4009 if (flags & MOV_TFHD_DEFAULT_SIZE) {
4010 track->default_size = track->entry ? track->cluster[0].size : 1;
4011 avio_wb32(pb, track->default_size);
4013 track->default_size = -1;
4015 if (flags & MOV_TFHD_DEFAULT_FLAGS) {
4016 /* Set the default flags based on the second sample, if available.
4017 * If the first sample is different, that can be signaled via a separate field. */
4018 if (track->entry > 1)
4019 track->default_sample_flags = get_sample_flags(track, &track->cluster[1]);
4021 track->default_sample_flags =
4022 track->par->codec_type == AVMEDIA_TYPE_VIDEO ?
4023 (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC) :
4024 MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO;
4025 avio_wb32(pb, track->default_sample_flags);
4028 return update_size(pb, pos);
4031 static int mov_write_trun_tag(AVIOContext *pb, MOVMuxContext *mov,
4032 MOVTrack *track, int moof_size,
4035 int64_t pos = avio_tell(pb);
4036 uint32_t flags = MOV_TRUN_DATA_OFFSET;
4039 for (i = first; i < end; i++) {
4040 if (get_cluster_duration(track, i) != track->default_duration)
4041 flags |= MOV_TRUN_SAMPLE_DURATION;
4042 if (track->cluster[i].size != track->default_size)
4043 flags |= MOV_TRUN_SAMPLE_SIZE;
4044 if (i > first && get_sample_flags(track, &track->cluster[i]) != track->default_sample_flags)
4045 flags |= MOV_TRUN_SAMPLE_FLAGS;
4047 if (!(flags & MOV_TRUN_SAMPLE_FLAGS) && track->entry > 0 &&
4048 get_sample_flags(track, &track->cluster[0]) != track->default_sample_flags)
4049 flags |= MOV_TRUN_FIRST_SAMPLE_FLAGS;
4050 if (track->flags & MOV_TRACK_CTTS)
4051 flags |= MOV_TRUN_SAMPLE_CTS;
4053 avio_wb32(pb, 0); /* size placeholder */
4054 ffio_wfourcc(pb, "trun");
4055 if (mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS)
4056 avio_w8(pb, 1); /* version */
4058 avio_w8(pb, 0); /* version */
4059 avio_wb24(pb, flags);
4061 avio_wb32(pb, end - first); /* sample count */
4062 if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET &&
4063 !(mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) &&
4065 avio_wb32(pb, 0); /* Later tracks follow immediately after the previous one */
4067 avio_wb32(pb, moof_size + 8 + track->data_offset +
4068 track->cluster[first].pos); /* data offset */
4069 if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS)
4070 avio_wb32(pb, get_sample_flags(track, &track->cluster[first]));
4072 for (i = first; i < end; i++) {
4073 if (flags & MOV_TRUN_SAMPLE_DURATION)
4074 avio_wb32(pb, get_cluster_duration(track, i));
4075 if (flags & MOV_TRUN_SAMPLE_SIZE)
4076 avio_wb32(pb, track->cluster[i].size);
4077 if (flags & MOV_TRUN_SAMPLE_FLAGS)
4078 avio_wb32(pb, get_sample_flags(track, &track->cluster[i]));
4079 if (flags & MOV_TRUN_SAMPLE_CTS)
4080 avio_wb32(pb, track->cluster[i].cts);
4083 mov->first_trun = 0;
4084 return update_size(pb, pos);
4087 static int mov_write_tfxd_tag(AVIOContext *pb, MOVTrack *track)
4089 int64_t pos = avio_tell(pb);
4090 static const uint8_t uuid[] = {
4091 0x6d, 0x1d, 0x9b, 0x05, 0x42, 0xd5, 0x44, 0xe6,
4092 0x80, 0xe2, 0x14, 0x1d, 0xaf, 0xf7, 0x57, 0xb2
4095 avio_wb32(pb, 0); /* size placeholder */
4096 ffio_wfourcc(pb, "uuid");
4097 avio_write(pb, uuid, sizeof(uuid));
4100 avio_wb64(pb, track->start_dts + track->frag_start +
4101 track->cluster[0].cts);
4102 avio_wb64(pb, track->end_pts -
4103 (track->cluster[0].dts + track->cluster[0].cts));
4105 return update_size(pb, pos);
4108 static int mov_write_tfrf_tag(AVIOContext *pb, MOVMuxContext *mov,
4109 MOVTrack *track, int entry)
4111 int n = track->nb_frag_info - 1 - entry, i;
4112 int size = 8 + 16 + 4 + 1 + 16*n;
4113 static const uint8_t uuid[] = {
4114 0xd4, 0x80, 0x7e, 0xf2, 0xca, 0x39, 0x46, 0x95,
4115 0x8e, 0x54, 0x26, 0xcb, 0x9e, 0x46, 0xa7, 0x9f
4121 avio_seek(pb, track->frag_info[entry].tfrf_offset, SEEK_SET);
4122 avio_wb32(pb, size);
4123 ffio_wfourcc(pb, "uuid");
4124 avio_write(pb, uuid, sizeof(uuid));
4128 for (i = 0; i < n; i++) {
4129 int index = entry + 1 + i;
4130 avio_wb64(pb, track->frag_info[index].time);
4131 avio_wb64(pb, track->frag_info[index].duration);
4133 if (n < mov->ism_lookahead) {
4134 int free_size = 16 * (mov->ism_lookahead - n);
4135 avio_wb32(pb, free_size);
4136 ffio_wfourcc(pb, "free");
4137 ffio_fill(pb, 0, free_size - 8);
4143 static int mov_write_tfrf_tags(AVIOContext *pb, MOVMuxContext *mov,
4146 int64_t pos = avio_tell(pb);
4148 for (i = 0; i < mov->ism_lookahead; i++) {
4149 /* Update the tfrf tag for the last ism_lookahead fragments,
4150 * nb_frag_info - 1 is the next fragment to be written. */
4151 mov_write_tfrf_tag(pb, mov, track, track->nb_frag_info - 2 - i);
4153 avio_seek(pb, pos, SEEK_SET);
4157 static int mov_add_tfra_entries(AVIOContext *pb, MOVMuxContext *mov, int tracks,
4161 for (i = 0; i < mov->nb_streams; i++) {
4162 MOVTrack *track = &mov->tracks[i];
4163 MOVFragmentInfo *info;
4164 if ((tracks >= 0 && i != tracks) || !track->entry)
4166 track->nb_frag_info++;
4167 if (track->nb_frag_info >= track->frag_info_capacity) {
4168 unsigned new_capacity = track->nb_frag_info + MOV_FRAG_INFO_ALLOC_INCREMENT;
4169 if (av_reallocp_array(&track->frag_info,
4171 sizeof(*track->frag_info)))
4172 return AVERROR(ENOMEM);
4173 track->frag_info_capacity = new_capacity;
4175 info = &track->frag_info[track->nb_frag_info - 1];
4176 info->offset = avio_tell(pb);
4178 // Try to recreate the original pts for the first packet
4179 // from the fields we have stored
4180 info->time = track->start_dts + track->frag_start +
4181 track->cluster[0].cts;
4182 info->duration = track->end_pts -
4183 (track->cluster[0].dts + track->cluster[0].cts);
4184 // If the pts is less than zero, we will have trimmed
4185 // away parts of the media track using an edit list,
4186 // and the corresponding start presentation time is zero.
4187 if (info->time < 0) {
4188 info->duration += info->time;
4191 info->tfrf_offset = 0;
4192 mov_write_tfrf_tags(pb, mov, track);
4197 static void mov_prune_frag_info(MOVMuxContext *mov, int tracks, int max)
4200 for (i = 0; i < mov->nb_streams; i++) {
4201 MOVTrack *track = &mov->tracks[i];
4202 if ((tracks >= 0 && i != tracks) || !track->entry)
4204 if (track->nb_frag_info > max) {
4205 memmove(track->frag_info, track->frag_info + (track->nb_frag_info - max), max * sizeof(*track->frag_info));
4206 track->nb_frag_info = max;
4211 static int mov_write_tfdt_tag(AVIOContext *pb, MOVTrack *track)
4213 int64_t pos = avio_tell(pb);
4215 avio_wb32(pb, 0); /* size */
4216 ffio_wfourcc(pb, "tfdt");
4217 avio_w8(pb, 1); /* version */
4219 avio_wb64(pb, track->frag_start);
4220 return update_size(pb, pos);
4223 static int mov_write_traf_tag(AVIOContext *pb, MOVMuxContext *mov,
4224 MOVTrack *track, int64_t moof_offset,
4227 int64_t pos = avio_tell(pb);
4229 avio_wb32(pb, 0); /* size placeholder */
4230 ffio_wfourcc(pb, "traf");
4232 mov_write_tfhd_tag(pb, mov, track, moof_offset);
4233 if (mov->mode != MODE_ISM)
4234 mov_write_tfdt_tag(pb, track);
4235 for (i = 1; i < track->entry; i++) {
4236 if (track->cluster[i].pos != track->cluster[i - 1].pos + track->cluster[i - 1].size) {
4237 mov_write_trun_tag(pb, mov, track, moof_size, start, i);
4241 mov_write_trun_tag(pb, mov, track, moof_size, start, track->entry);
4242 if (mov->mode == MODE_ISM) {
4243 mov_write_tfxd_tag(pb, track);
4245 if (mov->ism_lookahead) {
4246 int i, size = 16 + 4 + 1 + 16 * mov->ism_lookahead;
4248 if (track->nb_frag_info > 0) {
4249 MOVFragmentInfo *info = &track->frag_info[track->nb_frag_info - 1];
4250 if (!info->tfrf_offset)
4251 info->tfrf_offset = avio_tell(pb);
4253 avio_wb32(pb, 8 + size);
4254 ffio_wfourcc(pb, "free");
4255 for (i = 0; i < size; i++)
4260 return update_size(pb, pos);
4263 static int mov_write_moof_tag_internal(AVIOContext *pb, MOVMuxContext *mov,
4264 int tracks, int moof_size)
4266 int64_t pos = avio_tell(pb);
4269 avio_wb32(pb, 0); /* size placeholder */
4270 ffio_wfourcc(pb, "moof");
4271 mov->first_trun = 1;
4273 mov_write_mfhd_tag(pb, mov);
4274 for (i = 0; i < mov->nb_streams; i++) {
4275 MOVTrack *track = &mov->tracks[i];
4276 if (tracks >= 0 && i != tracks)
4280 mov_write_traf_tag(pb, mov, track, pos, moof_size);
4283 return update_size(pb, pos);
4286 static int mov_write_sidx_tag(AVIOContext *pb,
4287 MOVTrack *track, int ref_size, int total_sidx_size)
4289 int64_t pos = avio_tell(pb), offset_pos, end_pos;
4290 int64_t presentation_time, duration, offset;
4291 int starts_with_SAP, i, entries;
4295 presentation_time = track->start_dts + track->frag_start +
4296 track->cluster[0].cts;
4297 duration = track->end_pts -
4298 (track->cluster[0].dts + track->cluster[0].cts);
4299 starts_with_SAP = track->cluster[0].flags & MOV_SYNC_SAMPLE;
4301 // pts<0 should be cut away using edts
4302 if (presentation_time < 0) {
4303 duration += presentation_time;
4304 presentation_time = 0;
4307 entries = track->nb_frag_info;
4310 presentation_time = track->frag_info[0].time;
4313 avio_wb32(pb, 0); /* size */
4314 ffio_wfourcc(pb, "sidx");
4315 avio_w8(pb, 1); /* version */
4317 avio_wb32(pb, track->track_id); /* reference_ID */
4318 avio_wb32(pb, track->timescale); /* timescale */
4319 avio_wb64(pb, presentation_time); /* earliest_presentation_time */
4320 offset_pos = avio_tell(pb);
4321 avio_wb64(pb, 0); /* first_offset (offset to referenced moof) */
4322 avio_wb16(pb, 0); /* reserved */
4324 avio_wb16(pb, entries); /* reference_count */
4325 for (i = 0; i < entries; i++) {
4326 if (!track->entry) {
4327 if (i > 1 && track->frag_info[i].offset != track->frag_info[i - 1].offset + track->frag_info[i - 1].size) {
4328 av_log(NULL, AV_LOG_ERROR, "Non-consecutive fragments, writing incorrect sidx\n");
4330 duration = track->frag_info[i].duration;
4331 ref_size = track->frag_info[i].size;
4332 starts_with_SAP = 1;
4334 avio_wb32(pb, (0 << 31) | (ref_size & 0x7fffffff)); /* reference_type (0 = media) | referenced_size */
4335 avio_wb32(pb, duration); /* subsegment_duration */
4336 avio_wb32(pb, (starts_with_SAP << 31) | (0 << 28) | 0); /* starts_with_SAP | SAP_type | SAP_delta_time */
4339 end_pos = avio_tell(pb);
4340 offset = pos + total_sidx_size - end_pos;
4341 avio_seek(pb, offset_pos, SEEK_SET);
4342 avio_wb64(pb, offset);
4343 avio_seek(pb, end_pos, SEEK_SET);
4344 return update_size(pb, pos);
4347 static int mov_write_sidx_tags(AVIOContext *pb, MOVMuxContext *mov,
4348 int tracks, int ref_size)
4351 AVIOContext *avio_buf;
4353 for (round = 0; round < 2; round++) {
4354 // First run one round to calculate the total size of all
4356 // This would be much simpler if we'd only write one sidx
4357 // atom, for the first track in the moof.
4359 if ((ret = ffio_open_null_buf(&avio_buf)) < 0)
4364 for (i = 0; i < mov->nb_streams; i++) {
4365 MOVTrack *track = &mov->tracks[i];
4366 if (tracks >= 0 && i != tracks)
4368 // When writing a sidx for the full file, entry is 0, but
4369 // we want to include all tracks. ref_size is 0 in this case,
4370 // since we read it from frag_info instead.
4371 if (!track->entry && ref_size > 0)
4373 total_size -= mov_write_sidx_tag(avio_buf, track, ref_size,
4377 total_size = ffio_close_null_buf(avio_buf);
4382 static int mov_write_moof_tag(AVIOContext *pb, MOVMuxContext *mov, int tracks,
4385 AVIOContext *avio_buf;
4388 if ((ret = ffio_open_null_buf(&avio_buf)) < 0)
4390 mov_write_moof_tag_internal(avio_buf, mov, tracks, 0);
4391 moof_size = ffio_close_null_buf(avio_buf);
4393 if (mov->flags & FF_MOV_FLAG_DASH && !(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX))
4394 mov_write_sidx_tags(pb, mov, tracks, moof_size + 8 + mdat_size);
4396 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX ||
4397 !(mov->flags & FF_MOV_FLAG_SKIP_TRAILER) ||
4398 mov->ism_lookahead) {
4399 if ((ret = mov_add_tfra_entries(pb, mov, tracks, moof_size + 8 + mdat_size)) < 0)
4401 if (!(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) &&
4402 mov->flags & FF_MOV_FLAG_SKIP_TRAILER) {
4403 mov_prune_frag_info(mov, tracks, mov->ism_lookahead + 1);
4407 return mov_write_moof_tag_internal(pb, mov, tracks, moof_size);
4410 static int mov_write_tfra_tag(AVIOContext *pb, MOVTrack *track)
4412 int64_t pos = avio_tell(pb);
4415 avio_wb32(pb, 0); /* size placeholder */
4416 ffio_wfourcc(pb, "tfra");
4417 avio_w8(pb, 1); /* version */
4420 avio_wb32(pb, track->track_id);
4421 avio_wb32(pb, 0); /* length of traf/trun/sample num */
4422 avio_wb32(pb, track->nb_frag_info);
4423 for (i = 0; i < track->nb_frag_info; i++) {
4424 avio_wb64(pb, track->frag_info[i].time);
4425 avio_wb64(pb, track->frag_info[i].offset + track->data_offset);
4426 avio_w8(pb, 1); /* traf number */
4427 avio_w8(pb, 1); /* trun number */
4428 avio_w8(pb, 1); /* sample number */
4431 return update_size(pb, pos);
4434 static int mov_write_mfra_tag(AVIOContext *pb, MOVMuxContext *mov)
4436 int64_t pos = avio_tell(pb);
4439 avio_wb32(pb, 0); /* size placeholder */
4440 ffio_wfourcc(pb, "mfra");
4441 /* An empty mfra atom is enough to indicate to the publishing point that
4442 * the stream has ended. */
4443 if (mov->flags & FF_MOV_FLAG_ISML)
4444 return update_size(pb, pos);
4446 for (i = 0; i < mov->nb_streams; i++) {
4447 MOVTrack *track = &mov->tracks[i];
4448 if (track->nb_frag_info)
4449 mov_write_tfra_tag(pb, track);
4453 ffio_wfourcc(pb, "mfro");
4454 avio_wb32(pb, 0); /* version + flags */
4455 avio_wb32(pb, avio_tell(pb) + 4 - pos);
4457 return update_size(pb, pos);
4460 static int mov_write_mdat_tag(AVIOContext *pb, MOVMuxContext *mov)
4462 avio_wb32(pb, 8); // placeholder for extended size field (64 bit)
4463 ffio_wfourcc(pb, mov->mode == MODE_MOV ? "wide" : "free");
4465 mov->mdat_pos = avio_tell(pb);
4466 avio_wb32(pb, 0); /* size placeholder*/
4467 ffio_wfourcc(pb, "mdat");
4471 /* TODO: This needs to be more general */
4472 static int mov_write_ftyp_tag(AVIOContext *pb, AVFormatContext *s)
4474 MOVMuxContext *mov = s->priv_data;
4475 int64_t pos = avio_tell(pb);
4476 int has_h264 = 0, has_video = 0;
4480 for (i = 0; i < s->nb_streams; i++) {
4481 AVStream *st = s->streams[i];
4482 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
4484 if (st->codecpar->codec_id == AV_CODEC_ID_H264)
4488 avio_wb32(pb, 0); /* size */
4489 ffio_wfourcc(pb, "ftyp");
4491 if (mov->major_brand && strlen(mov->major_brand) >= 4)
4492 ffio_wfourcc(pb, mov->major_brand);
4493 else if (mov->mode == MODE_3GP) {
4494 ffio_wfourcc(pb, has_h264 ? "3gp6" : "3gp4");
4495 minor = has_h264 ? 0x100 : 0x200;
4496 } else if (mov->mode & MODE_3G2) {
4497 ffio_wfourcc(pb, has_h264 ? "3g2b" : "3g2a");
4498 minor = has_h264 ? 0x20000 : 0x10000;
4499 } else if (mov->mode == MODE_PSP)
4500 ffio_wfourcc(pb, "MSNV");
4501 else if (mov->mode == MODE_MP4 && mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)
4502 ffio_wfourcc(pb, "iso5"); // Required when using default-base-is-moof
4503 else if (mov->mode == MODE_MP4 && mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS)
4504 ffio_wfourcc(pb, "iso4");
4505 else if (mov->mode == MODE_MP4)
4506 ffio_wfourcc(pb, "isom");
4507 else if (mov->mode == MODE_IPOD)
4508 ffio_wfourcc(pb, has_video ? "M4V ":"M4A ");
4509 else if (mov->mode == MODE_ISM)
4510 ffio_wfourcc(pb, "isml");
4511 else if (mov->mode == MODE_F4V)
4512 ffio_wfourcc(pb, "f4v ");
4514 ffio_wfourcc(pb, "qt ");
4516 avio_wb32(pb, minor);
4518 if (mov->mode == MODE_MOV)
4519 ffio_wfourcc(pb, "qt ");
4520 else if (mov->mode == MODE_ISM) {
4521 ffio_wfourcc(pb, "piff");
4522 } else if (!(mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)) {
4523 ffio_wfourcc(pb, "isom");
4524 ffio_wfourcc(pb, "iso2");
4526 ffio_wfourcc(pb, "avc1");
4529 // We add tfdt atoms when fragmenting, signal this with the iso6 compatible
4530 // brand. This is compatible with users that don't understand tfdt.
4531 if (mov->flags & FF_MOV_FLAG_FRAGMENT && mov->mode != MODE_ISM)
4532 ffio_wfourcc(pb, "iso6");
4534 if (mov->mode == MODE_3GP)
4535 ffio_wfourcc(pb, has_h264 ? "3gp6":"3gp4");
4536 else if (mov->mode & MODE_3G2)
4537 ffio_wfourcc(pb, has_h264 ? "3g2b":"3g2a");
4538 else if (mov->mode == MODE_PSP)
4539 ffio_wfourcc(pb, "MSNV");
4540 else if (mov->mode == MODE_MP4)
4541 ffio_wfourcc(pb, "mp41");
4543 if (mov->flags & FF_MOV_FLAG_DASH && mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
4544 ffio_wfourcc(pb, "dash");
4546 return update_size(pb, pos);
4549 static int mov_write_uuidprof_tag(AVIOContext *pb, AVFormatContext *s)
4551 AVStream *video_st = s->streams[0];
4552 AVCodecParameters *video_par = s->streams[0]->codecpar;
4553 AVCodecParameters *audio_par = s->streams[1]->codecpar;
4554 int audio_rate = audio_par->sample_rate;
4555 int64_t frame_rate = video_st->avg_frame_rate.den ?
4556 (video_st->avg_frame_rate.num * 0x10000LL) / video_st->avg_frame_rate.den :
4558 int audio_kbitrate = audio_par->bit_rate / 1000;
4559 int video_kbitrate = FFMIN(video_par->bit_rate / 1000, 800 - audio_kbitrate);
4561 if (frame_rate < 0 || frame_rate > INT32_MAX) {
4562 av_log(s, AV_LOG_ERROR, "Frame rate %f outside supported range\n", frame_rate / (double)0x10000);
4563 return AVERROR(EINVAL);
4566 avio_wb32(pb, 0x94); /* size */
4567 ffio_wfourcc(pb, "uuid");
4568 ffio_wfourcc(pb, "PROF");
4570 avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
4571 avio_wb32(pb, 0xbb88695c);
4572 avio_wb32(pb, 0xfac9c740);
4574 avio_wb32(pb, 0x0); /* ? */
4575 avio_wb32(pb, 0x3); /* 3 sections ? */
4577 avio_wb32(pb, 0x14); /* size */
4578 ffio_wfourcc(pb, "FPRF");
4579 avio_wb32(pb, 0x0); /* ? */
4580 avio_wb32(pb, 0x0); /* ? */
4581 avio_wb32(pb, 0x0); /* ? */
4583 avio_wb32(pb, 0x2c); /* size */
4584 ffio_wfourcc(pb, "APRF"); /* audio */
4586 avio_wb32(pb, 0x2); /* TrackID */
4587 ffio_wfourcc(pb, "mp4a");
4588 avio_wb32(pb, 0x20f);
4590 avio_wb32(pb, audio_kbitrate);
4591 avio_wb32(pb, audio_kbitrate);
4592 avio_wb32(pb, audio_rate);
4593 avio_wb32(pb, audio_par->channels);
4595 avio_wb32(pb, 0x34); /* size */
4596 ffio_wfourcc(pb, "VPRF"); /* video */
4598 avio_wb32(pb, 0x1); /* TrackID */
4599 if (video_par->codec_id == AV_CODEC_ID_H264) {
4600 ffio_wfourcc(pb, "avc1");
4601 avio_wb16(pb, 0x014D);
4602 avio_wb16(pb, 0x0015);
4604 ffio_wfourcc(pb, "mp4v");
4605 avio_wb16(pb, 0x0000);
4606 avio_wb16(pb, 0x0103);
4609 avio_wb32(pb, video_kbitrate);
4610 avio_wb32(pb, video_kbitrate);
4611 avio_wb32(pb, frame_rate);
4612 avio_wb32(pb, frame_rate);
4613 avio_wb16(pb, video_par->width);
4614 avio_wb16(pb, video_par->height);
4615 avio_wb32(pb, 0x010001); /* ? */
4620 static int mov_write_identification(AVIOContext *pb, AVFormatContext *s)
4622 MOVMuxContext *mov = s->priv_data;
4625 mov_write_ftyp_tag(pb,s);
4626 if (mov->mode == MODE_PSP) {
4627 int video_streams_nb = 0, audio_streams_nb = 0, other_streams_nb = 0;
4628 for (i = 0; i < s->nb_streams; i++) {
4629 AVStream *st = s->streams[i];
4630 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
4632 else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
4638 if (video_streams_nb != 1 || audio_streams_nb != 1 || other_streams_nb) {
4639 av_log(s, AV_LOG_ERROR, "PSP mode need one video and one audio stream\n");
4640 return AVERROR(EINVAL);
4642 return mov_write_uuidprof_tag(pb, s);
4647 static int mov_parse_mpeg2_frame(AVPacket *pkt, uint32_t *flags)
4650 int i, closed_gop = 0;
4652 for (i = 0; i < pkt->size - 4; i++) {
4653 c = (c << 8) + pkt->data[i];
4654 if (c == 0x1b8) { // gop
4655 closed_gop = pkt->data[i + 4] >> 6 & 0x01;
4656 } else if (c == 0x100) { // pic
4657 int temp_ref = (pkt->data[i + 1] << 2) | (pkt->data[i + 2] >> 6);
4658 if (!temp_ref || closed_gop) // I picture is not reordered
4659 *flags = MOV_SYNC_SAMPLE;
4661 *flags = MOV_PARTIAL_SYNC_SAMPLE;
4668 static void mov_parse_vc1_frame(AVPacket *pkt, MOVTrack *trk)
4670 const uint8_t *start, *next, *end = pkt->data + pkt->size;
4671 int seq = 0, entry = 0;
4672 int key = pkt->flags & AV_PKT_FLAG_KEY;
4673 start = find_next_marker(pkt->data, end);
4674 for (next = start; next < end; start = next) {
4675 next = find_next_marker(start + 4, end);
4676 switch (AV_RB32(start)) {
4677 case VC1_CODE_SEQHDR:
4680 case VC1_CODE_ENTRYPOINT:
4683 case VC1_CODE_SLICE:
4684 trk->vc1_info.slices = 1;
4688 if (!trk->entry && trk->vc1_info.first_packet_seen)
4689 trk->vc1_info.first_frag_written = 1;
4690 if (!trk->entry && !trk->vc1_info.first_frag_written) {
4691 /* First packet in first fragment */
4692 trk->vc1_info.first_packet_seq = seq;
4693 trk->vc1_info.first_packet_entry = entry;
4694 trk->vc1_info.first_packet_seen = 1;
4695 } else if ((seq && !trk->vc1_info.packet_seq) ||
4696 (entry && !trk->vc1_info.packet_entry)) {
4698 for (i = 0; i < trk->entry; i++)
4699 trk->cluster[i].flags &= ~MOV_SYNC_SAMPLE;
4700 trk->has_keyframes = 0;
4702 trk->vc1_info.packet_seq = 1;
4704 trk->vc1_info.packet_entry = 1;
4705 if (!trk->vc1_info.first_frag_written) {
4706 /* First fragment */
4707 if ((!seq || trk->vc1_info.first_packet_seq) &&
4708 (!entry || trk->vc1_info.first_packet_entry)) {
4709 /* First packet had the same headers as this one, readd the
4710 * sync sample flag. */
4711 trk->cluster[0].flags |= MOV_SYNC_SAMPLE;
4712 trk->has_keyframes = 1;
4716 if (trk->vc1_info.packet_seq && trk->vc1_info.packet_entry)
4718 else if (trk->vc1_info.packet_seq)
4720 else if (trk->vc1_info.packet_entry)
4723 trk->cluster[trk->entry].flags |= MOV_SYNC_SAMPLE;
4724 trk->has_keyframes++;
4728 static int mov_flush_fragment_interleaving(AVFormatContext *s, MOVTrack *track)
4730 MOVMuxContext *mov = s->priv_data;
4735 if (!track->mdat_buf)
4737 if (!mov->mdat_buf) {
4738 if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0)
4741 buf_size = avio_close_dyn_buf(track->mdat_buf, &buf);
4742 track->mdat_buf = NULL;
4744 offset = avio_tell(mov->mdat_buf);
4745 avio_write(mov->mdat_buf, buf, buf_size);
4748 for (i = track->entries_flushed; i < track->entry; i++)
4749 track->cluster[i].pos += offset;
4750 track->entries_flushed = track->entry;
4754 static int mov_flush_fragment(AVFormatContext *s, int force)
4756 MOVMuxContext *mov = s->priv_data;
4757 int i, first_track = -1;
4758 int64_t mdat_size = 0;
4760 int has_video = 0, starts_with_key = 0, first_video_track = 1;
4762 if (!(mov->flags & FF_MOV_FLAG_FRAGMENT))
4765 // Try to fill in the duration of the last packet in each stream
4766 // from queued packets in the interleave queues. If the flushing
4767 // of fragments was triggered automatically by an AVPacket, we
4768 // already have reliable info for the end of that track, but other
4769 // tracks may need to be filled in.
4770 for (i = 0; i < s->nb_streams; i++) {
4771 MOVTrack *track = &mov->tracks[i];
4772 if (!track->end_reliable) {
4774 if (!ff_interleaved_peek(s, i, &pkt, 1)) {
4775 if (track->dts_shift != AV_NOPTS_VALUE)
4776 pkt.dts += track->dts_shift;
4777 track->track_duration = pkt.dts - track->start_dts;
4778 if (pkt.pts != AV_NOPTS_VALUE)
4779 track->end_pts = pkt.pts;
4781 track->end_pts = pkt.dts;
4786 for (i = 0; i < mov->nb_streams; i++) {
4787 MOVTrack *track = &mov->tracks[i];
4788 if (track->entry <= 1)
4790 // Sample durations are calculated as the diff of dts values,
4791 // but for the last sample in a fragment, we don't know the dts
4792 // of the first sample in the next fragment, so we have to rely
4793 // on what was set as duration in the AVPacket. Not all callers
4794 // set this though, so we might want to replace it with an
4795 // estimate if it currently is zero.
4796 if (get_cluster_duration(track, track->entry - 1) != 0)
4798 // Use the duration (i.e. dts diff) of the second last sample for
4799 // the last one. This is a wild guess (and fatal if it turns out
4800 // to be too long), but probably the best we can do - having a zero
4801 // duration is bad as well.
4802 track->track_duration += get_cluster_duration(track, track->entry - 2);
4803 track->end_pts += get_cluster_duration(track, track->entry - 2);
4804 if (!mov->missing_duration_warned) {
4805 av_log(s, AV_LOG_WARNING,
4806 "Estimating the duration of the last packet in a "
4807 "fragment, consider setting the duration field in "
4808 "AVPacket instead.\n");
4809 mov->missing_duration_warned = 1;
4813 if (!mov->moov_written) {
4814 int64_t pos = avio_tell(s->pb);
4816 int buf_size, moov_size;
4818 for (i = 0; i < mov->nb_streams; i++)
4819 if (!mov->tracks[i].entry)
4821 /* Don't write the initial moov unless all tracks have data */
4822 if (i < mov->nb_streams && !force)
4825 moov_size = get_moov_size(s);
4826 for (i = 0; i < mov->nb_streams; i++)
4827 mov->tracks[i].data_offset = pos + moov_size + 8;
4829 avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_HEADER);
4830 if (mov->flags & FF_MOV_FLAG_DELAY_MOOV)
4831 mov_write_identification(s->pb, s);
4832 if ((ret = mov_write_moov_tag(s->pb, mov, s)) < 0)
4835 if (mov->flags & FF_MOV_FLAG_DELAY_MOOV) {
4836 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
4837 mov->reserved_header_pos = avio_tell(s->pb);
4839 mov->moov_written = 1;
4843 buf_size = avio_close_dyn_buf(mov->mdat_buf, &buf);
4844 mov->mdat_buf = NULL;
4845 avio_wb32(s->pb, buf_size + 8);
4846 ffio_wfourcc(s->pb, "mdat");
4847 avio_write(s->pb, buf, buf_size);
4850 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
4851 mov->reserved_header_pos = avio_tell(s->pb);
4853 mov->moov_written = 1;
4855 for (i = 0; i < mov->nb_streams; i++) {
4856 if (mov->tracks[i].entry)
4857 mov->tracks[i].frag_start += mov->tracks[i].start_dts +
4858 mov->tracks[i].track_duration -
4859 mov->tracks[i].cluster[0].dts;
4860 mov->tracks[i].entry = 0;
4861 mov->tracks[i].end_reliable = 0;
4867 if (mov->frag_interleave) {
4868 for (i = 0; i < mov->nb_streams; i++) {
4869 MOVTrack *track = &mov->tracks[i];
4871 if ((ret = mov_flush_fragment_interleaving(s, track)) < 0)
4877 mdat_size = avio_tell(mov->mdat_buf);
4880 for (i = 0; i < mov->nb_streams; i++) {
4881 MOVTrack *track = &mov->tracks[i];
4882 if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF || mov->frag_interleave)
4883 track->data_offset = 0;
4885 track->data_offset = mdat_size;
4886 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
4888 if (first_video_track) {
4890 starts_with_key = track->cluster[0].flags & MOV_SYNC_SAMPLE;
4891 first_video_track = 0;
4896 if (track->mdat_buf)
4897 mdat_size += avio_tell(track->mdat_buf);
4898 if (first_track < 0)
4905 avio_write_marker(s->pb,
4906 av_rescale(mov->tracks[first_track].cluster[0].dts, AV_TIME_BASE, mov->tracks[first_track].timescale),
4907 (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);
4909 for (i = 0; i < mov->nb_streams; i++) {
4910 MOVTrack *track = &mov->tracks[i];
4911 int buf_size, write_moof = 1, moof_tracks = -1;
4913 int64_t duration = 0;
4916 duration = track->start_dts + track->track_duration -
4917 track->cluster[0].dts;
4918 if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF) {
4919 if (!track->mdat_buf)
4921 mdat_size = avio_tell(track->mdat_buf);
4924 write_moof = i == first_track;
4930 mov_write_moof_tag(s->pb, mov, moof_tracks, mdat_size);
4933 avio_wb32(s->pb, mdat_size + 8);
4934 ffio_wfourcc(s->pb, "mdat");
4938 track->frag_start += duration;
4940 track->entries_flushed = 0;
4941 track->end_reliable = 0;
4942 if (!mov->frag_interleave) {
4943 if (!track->mdat_buf)
4945 buf_size = avio_close_dyn_buf(track->mdat_buf, &buf);
4946 track->mdat_buf = NULL;
4950 buf_size = avio_close_dyn_buf(mov->mdat_buf, &buf);
4951 mov->mdat_buf = NULL;
4954 avio_write(s->pb, buf, buf_size);
4964 static int mov_auto_flush_fragment(AVFormatContext *s, int force)
4966 MOVMuxContext *mov = s->priv_data;
4967 int had_moov = mov->moov_written;
4968 int ret = mov_flush_fragment(s, force);
4971 // If using delay_moov, the first flush only wrote the moov,
4972 // not the actual moof+mdat pair, thus flush once again.
4973 if (!had_moov && mov->flags & FF_MOV_FLAG_DELAY_MOOV)
4974 ret = mov_flush_fragment(s, force);
4978 static int check_pkt(AVFormatContext *s, AVPacket *pkt)
4980 MOVMuxContext *mov = s->priv_data;
4981 MOVTrack *trk = &mov->tracks[pkt->stream_index];
4986 ref = trk->cluster[trk->entry - 1].dts;
4987 } else if ( trk->start_dts != AV_NOPTS_VALUE
4988 && !trk->frag_discont) {
4989 ref = trk->start_dts + trk->track_duration;
4991 ref = pkt->dts; // Skip tests for the first packet
4993 if (trk->dts_shift != AV_NOPTS_VALUE) {
4994 /* With negative CTS offsets we have set an offset to the DTS,
4995 * reverse this for the check. */
4996 ref -= trk->dts_shift;
4999 duration = pkt->dts - ref;
5000 if (pkt->dts < ref || duration >= INT_MAX) {
5001 av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" / timestamp: %"PRId64" is out of range for mov/mp4 format\n",
5006 pkt->pts = AV_NOPTS_VALUE;
5009 if (pkt->duration < 0 || pkt->duration > INT_MAX) {
5010 av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" is invalid\n", pkt->duration);
5011 return AVERROR(EINVAL);
5016 int ff_mov_write_packet(AVFormatContext *s, AVPacket *pkt)
5018 MOVMuxContext *mov = s->priv_data;
5019 AVIOContext *pb = s->pb;
5020 MOVTrack *trk = &mov->tracks[pkt->stream_index];
5021 AVCodecParameters *par = trk->par;
5022 unsigned int samples_in_chunk = 0;
5023 int size = pkt->size, ret = 0;
5024 uint8_t *reformatted_data = NULL;
5026 ret = check_pkt(s, pkt);
5030 if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
5032 if (mov->moov_written || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
5033 if (mov->frag_interleave && mov->fragments > 0) {
5034 if (trk->entry - trk->entries_flushed >= mov->frag_interleave) {
5035 if ((ret = mov_flush_fragment_interleaving(s, trk)) < 0)
5040 if (!trk->mdat_buf) {
5041 if ((ret = avio_open_dyn_buf(&trk->mdat_buf)) < 0)
5046 if (!mov->mdat_buf) {
5047 if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0)
5054 if (par->codec_id == AV_CODEC_ID_AMR_NB) {
5055 /* We must find out how many AMR blocks there are in one packet */
5056 static const uint16_t packed_size[16] =
5057 {13, 14, 16, 18, 20, 21, 27, 32, 6, 0, 0, 0, 0, 0, 0, 1};
5060 while (len < size && samples_in_chunk < 100) {
5061 len += packed_size[(pkt->data[len] >> 3) & 0x0F];
5064 if (samples_in_chunk > 1) {
5065 av_log(s, AV_LOG_ERROR, "fatal error, input is not a single packet, implement a AVParser for it\n");
5068 } else if (par->codec_id == AV_CODEC_ID_ADPCM_MS ||
5069 par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) {
5070 samples_in_chunk = trk->par->frame_size;
5071 } else if (trk->sample_size)
5072 samples_in_chunk = size / trk->sample_size;
5074 samples_in_chunk = 1;
5076 /* copy extradata if it exists */
5077 if (trk->vos_len == 0 && par->extradata_size > 0 &&
5078 !TAG_IS_AVCI(trk->tag) &&
5079 (par->codec_id != AV_CODEC_ID_DNXHD)) {
5080 trk->vos_len = par->extradata_size;
5081 trk->vos_data = av_malloc(trk->vos_len);
5082 if (!trk->vos_data) {
5083 ret = AVERROR(ENOMEM);
5086 memcpy(trk->vos_data, par->extradata, trk->vos_len);
5089 if (par->codec_id == AV_CODEC_ID_AAC && pkt->size > 2 &&
5090 (AV_RB16(pkt->data) & 0xfff0) == 0xfff0) {
5091 if (!s->streams[pkt->stream_index]->nb_frames) {
5092 av_log(s, AV_LOG_ERROR, "Malformed AAC bitstream detected: "
5093 "use the audio bitstream filter 'aac_adtstoasc' to fix it "
5094 "('-bsf:a aac_adtstoasc' option with ffmpeg)\n");
5097 av_log(s, AV_LOG_WARNING, "aac bitstream error\n");
5099 if (par->codec_id == AV_CODEC_ID_H264 && trk->vos_len > 0 && *(uint8_t *)trk->vos_data != 1 && !TAG_IS_AVCI(trk->tag)) {
5100 /* from x264 or from bytestream H.264 */
5101 /* NAL reformatting needed */
5102 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
5103 ff_avc_parse_nal_units_buf(pkt->data, &reformatted_data,
5105 avio_write(pb, reformatted_data, size);
5107 if (trk->cenc.aes_ctr) {
5108 size = ff_mov_cenc_avc_parse_nal_units(&trk->cenc, pb, pkt->data, size);
5114 size = ff_avc_parse_nal_units(pb, pkt->data, pkt->size);
5117 } else if (par->codec_id == AV_CODEC_ID_HEVC && trk->vos_len > 6 &&
5118 (AV_RB24(trk->vos_data) == 1 || AV_RB32(trk->vos_data) == 1)) {
5119 /* extradata is Annex B, assume the bitstream is too and convert it */
5120 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
5121 ff_hevc_annexb2mp4_buf(pkt->data, &reformatted_data, &size, 0, NULL);
5122 avio_write(pb, reformatted_data, size);
5124 size = ff_hevc_annexb2mp4(pb, pkt->data, pkt->size, 0, NULL);
5126 #if CONFIG_AC3_PARSER
5127 } else if (par->codec_id == AV_CODEC_ID_EAC3) {
5128 size = handle_eac3(mov, pkt, trk);
5133 avio_write(pb, pkt->data, size);
5136 if (trk->cenc.aes_ctr) {
5137 if (par->codec_id == AV_CODEC_ID_H264 && par->extradata_size > 4) {
5138 int nal_size_length = (par->extradata[4] & 0x3) + 1;
5139 ret = ff_mov_cenc_avc_write_nal_units(s, &trk->cenc, nal_size_length, pb, pkt->data, size);
5141 ret = ff_mov_cenc_write_packet(&trk->cenc, pb, pkt->data, size);
5148 avio_write(pb, pkt->data, size);
5152 if ((par->codec_id == AV_CODEC_ID_DNXHD ||
5153 par->codec_id == AV_CODEC_ID_AC3) && !trk->vos_len) {
5154 /* copy frame to create needed atoms */
5155 trk->vos_len = size;
5156 trk->vos_data = av_malloc(size);
5157 if (!trk->vos_data) {
5158 ret = AVERROR(ENOMEM);
5161 memcpy(trk->vos_data, pkt->data, size);
5164 if (trk->entry >= trk->cluster_capacity) {
5165 unsigned new_capacity = 2 * (trk->entry + MOV_INDEX_CLUSTER_SIZE);
5166 if (av_reallocp_array(&trk->cluster, new_capacity,
5167 sizeof(*trk->cluster))) {
5168 ret = AVERROR(ENOMEM);
5171 trk->cluster_capacity = new_capacity;
5174 trk->cluster[trk->entry].pos = avio_tell(pb) - size;
5175 trk->cluster[trk->entry].samples_in_chunk = samples_in_chunk;
5176 trk->cluster[trk->entry].chunkNum = 0;
5177 trk->cluster[trk->entry].size = size;
5178 trk->cluster[trk->entry].entries = samples_in_chunk;
5179 trk->cluster[trk->entry].dts = pkt->dts;
5180 if (!trk->entry && trk->start_dts != AV_NOPTS_VALUE) {
5181 if (!trk->frag_discont) {
5182 /* First packet of a new fragment. We already wrote the duration
5183 * of the last packet of the previous fragment based on track_duration,
5184 * which might not exactly match our dts. Therefore adjust the dts
5185 * of this packet to be what the previous packets duration implies. */
5186 trk->cluster[trk->entry].dts = trk->start_dts + trk->track_duration;
5187 /* We also may have written the pts and the corresponding duration
5188 * in sidx/tfrf/tfxd tags; make sure the sidx pts and duration match up with
5189 * the next fragment. This means the cts of the first sample must
5190 * be the same in all fragments, unless end_pts was updated by
5191 * the packet causing the fragment to be written. */
5192 if ((mov->flags & FF_MOV_FLAG_DASH && !(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)) ||
5193 mov->mode == MODE_ISM)
5194 pkt->pts = pkt->dts + trk->end_pts - trk->cluster[trk->entry].dts;
5196 /* New fragment, but discontinuous from previous fragments.
5197 * Pretend the duration sum of the earlier fragments is
5198 * pkt->dts - trk->start_dts. */
5199 trk->frag_start = pkt->dts - trk->start_dts;
5200 trk->end_pts = AV_NOPTS_VALUE;
5201 trk->frag_discont = 0;
5205 if (!trk->entry && trk->start_dts == AV_NOPTS_VALUE && !mov->use_editlist &&
5206 s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO) {
5207 /* Not using edit lists and shifting the first track to start from zero.
5208 * If the other streams start from a later timestamp, we won't be able
5209 * to signal the difference in starting time without an edit list.
5210 * Thus move the timestamp for this first sample to 0, increasing
5211 * its duration instead. */
5212 trk->cluster[trk->entry].dts = trk->start_dts = 0;
5214 if (trk->start_dts == AV_NOPTS_VALUE) {
5215 trk->start_dts = pkt->dts;
5216 if (trk->frag_discont) {
5217 if (mov->use_editlist) {
5218 /* Pretend the whole stream started at pts=0, with earlier fragments
5219 * already written. If the stream started at pts=0, the duration sum
5220 * of earlier fragments would have been pkt->pts. */
5221 trk->frag_start = pkt->pts;
5222 trk->start_dts = pkt->dts - pkt->pts;
5224 /* Pretend the whole stream started at dts=0, with earlier fragments
5225 * already written, with a duration summing up to pkt->dts. */
5226 trk->frag_start = pkt->dts;
5229 trk->frag_discont = 0;
5230 } else if (pkt->dts && mov->moov_written)
5231 av_log(s, AV_LOG_WARNING,
5232 "Track %d starts with a nonzero dts %"PRId64", while the moov "
5233 "already has been written. Set the delay_moov flag to handle "
5235 pkt->stream_index, pkt->dts);
5237 trk->track_duration = pkt->dts - trk->start_dts + pkt->duration;
5238 trk->last_sample_is_subtitle_end = 0;
5240 if (pkt->pts == AV_NOPTS_VALUE) {
5241 av_log(s, AV_LOG_WARNING, "pts has no value\n");
5242 pkt->pts = pkt->dts;
5244 if (pkt->dts != pkt->pts)
5245 trk->flags |= MOV_TRACK_CTTS;
5246 trk->cluster[trk->entry].cts = pkt->pts - pkt->dts;
5247 trk->cluster[trk->entry].flags = 0;
5248 if (trk->start_cts == AV_NOPTS_VALUE)
5249 trk->start_cts = pkt->pts - pkt->dts;
5250 if (trk->end_pts == AV_NOPTS_VALUE)
5251 trk->end_pts = trk->cluster[trk->entry].dts +
5252 trk->cluster[trk->entry].cts + pkt->duration;
5254 trk->end_pts = FFMAX(trk->end_pts, trk->cluster[trk->entry].dts +
5255 trk->cluster[trk->entry].cts +
5258 if (par->codec_id == AV_CODEC_ID_VC1) {
5259 mov_parse_vc1_frame(pkt, trk);
5260 } else if (pkt->flags & AV_PKT_FLAG_KEY) {
5261 if (mov->mode == MODE_MOV && par->codec_id == AV_CODEC_ID_MPEG2VIDEO &&
5262 trk->entry > 0) { // force sync sample for the first key frame
5263 mov_parse_mpeg2_frame(pkt, &trk->cluster[trk->entry].flags);
5264 if (trk->cluster[trk->entry].flags & MOV_PARTIAL_SYNC_SAMPLE)
5265 trk->flags |= MOV_TRACK_STPS;
5267 trk->cluster[trk->entry].flags = MOV_SYNC_SAMPLE;
5269 if (trk->cluster[trk->entry].flags & MOV_SYNC_SAMPLE)
5270 trk->has_keyframes++;
5273 trk->sample_count += samples_in_chunk;
5274 mov->mdat_size += size;
5276 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams)
5277 ff_mov_add_hinted_packet(s, pkt, trk->hint_track, trk->entry,
5278 reformatted_data, size);
5283 av_free(reformatted_data);
5287 static int mov_write_single_packet(AVFormatContext *s, AVPacket *pkt)
5289 MOVMuxContext *mov = s->priv_data;
5290 MOVTrack *trk = &mov->tracks[pkt->stream_index];
5291 AVCodecParameters *par = trk->par;
5292 int64_t frag_duration = 0;
5293 int size = pkt->size;
5295 int ret = check_pkt(s, pkt);
5299 if (mov->flags & FF_MOV_FLAG_FRAG_DISCONT) {
5301 for (i = 0; i < s->nb_streams; i++)
5302 mov->tracks[i].frag_discont = 1;
5303 mov->flags &= ~FF_MOV_FLAG_FRAG_DISCONT;
5306 if (mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS) {
5307 if (trk->dts_shift == AV_NOPTS_VALUE)
5308 trk->dts_shift = pkt->pts - pkt->dts;
5309 pkt->dts += trk->dts_shift;
5312 if (trk->par->codec_id == AV_CODEC_ID_MP4ALS ||
5313 trk->par->codec_id == AV_CODEC_ID_AAC ||
5314 trk->par->codec_id == AV_CODEC_ID_FLAC) {
5316 uint8_t *side = av_packet_get_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA, &side_size);
5317 if (side && side_size > 0 && (side_size != par->extradata_size || memcmp(side, par->extradata, side_size))) {
5318 void *newextra = av_mallocz(side_size + AV_INPUT_BUFFER_PADDING_SIZE);
5320 return AVERROR(ENOMEM);
5321 av_free(par->extradata);
5322 par->extradata = newextra;
5323 memcpy(par->extradata, side, side_size);
5324 par->extradata_size = side_size;
5325 if (!pkt->size) // Flush packet
5326 mov->need_rewrite_extradata = 1;
5331 if (trk->start_dts == AV_NOPTS_VALUE && trk->frag_discont) {
5332 trk->start_dts = pkt->dts;
5333 if (pkt->pts != AV_NOPTS_VALUE)
5334 trk->start_cts = pkt->pts - pkt->dts;
5339 return 0; /* Discard 0 sized packets */
5342 if (trk->entry && pkt->stream_index < s->nb_streams)
5343 frag_duration = av_rescale_q(pkt->dts - trk->cluster[0].dts,
5344 s->streams[pkt->stream_index]->time_base,
5346 if ((mov->max_fragment_duration &&
5347 frag_duration >= mov->max_fragment_duration) ||
5348 (mov->max_fragment_size && mov->mdat_size + size >= mov->max_fragment_size) ||
5349 (mov->flags & FF_MOV_FLAG_FRAG_KEYFRAME &&
5350 par->codec_type == AVMEDIA_TYPE_VIDEO &&
5351 trk->entry && pkt->flags & AV_PKT_FLAG_KEY)) {
5352 if (frag_duration >= mov->min_fragment_duration) {
5353 // Set the duration of this track to line up with the next
5354 // sample in this track. This avoids relying on AVPacket
5355 // duration, but only helps for this particular track, not
5356 // for the other ones that are flushed at the same time.
5357 trk->track_duration = pkt->dts - trk->start_dts;
5358 if (pkt->pts != AV_NOPTS_VALUE)
5359 trk->end_pts = pkt->pts;
5361 trk->end_pts = pkt->dts;
5362 trk->end_reliable = 1;
5363 mov_auto_flush_fragment(s, 0);
5367 return ff_mov_write_packet(s, pkt);
5370 static int mov_write_subtitle_end_packet(AVFormatContext *s,
5374 uint8_t data[2] = {0};
5377 av_init_packet(&end);
5378 end.size = sizeof(data);
5383 end.stream_index = stream_index;
5385 ret = mov_write_single_packet(s, &end);
5386 av_packet_unref(&end);
5391 static int mov_write_packet(AVFormatContext *s, AVPacket *pkt)
5394 mov_flush_fragment(s, 1);
5398 MOVMuxContext *mov = s->priv_data;
5399 MOVTrack *trk = &mov->tracks[pkt->stream_index];
5402 return mov_write_single_packet(s, pkt); /* Passthrough. */
5405 * Subtitles require special handling.
5407 * 1) For full complaince, every track must have a sample at
5408 * dts == 0, which is rarely true for subtitles. So, as soon
5409 * as we see any packet with dts > 0, write an empty subtitle
5410 * at dts == 0 for any subtitle track with no samples in it.
5412 * 2) For each subtitle track, check if the current packet's
5413 * dts is past the duration of the last subtitle sample. If
5414 * so, we now need to write an end sample for that subtitle.
5416 * This must be done conditionally to allow for subtitles that
5417 * immediately replace each other, in which case an end sample
5418 * is not needed, and is, in fact, actively harmful.
5420 * 3) See mov_write_trailer for how the final end sample is
5423 for (i = 0; i < mov->nb_streams; i++) {
5424 MOVTrack *trk = &mov->tracks[i];
5427 if (trk->par->codec_id == AV_CODEC_ID_MOV_TEXT &&
5428 trk->track_duration < pkt->dts &&
5429 (trk->entry == 0 || !trk->last_sample_is_subtitle_end)) {
5430 ret = mov_write_subtitle_end_packet(s, i, trk->track_duration);
5431 if (ret < 0) return ret;
5432 trk->last_sample_is_subtitle_end = 1;
5436 if (trk->mode == MODE_MOV && trk->par->codec_type == AVMEDIA_TYPE_VIDEO) {
5437 AVPacket *opkt = pkt;
5438 int reshuffle_ret, ret;
5439 if (trk->is_unaligned_qt_rgb) {
5440 int64_t bpc = trk->par->bits_per_coded_sample != 15 ? trk->par->bits_per_coded_sample : 16;
5441 int expected_stride = ((trk->par->width * bpc + 15) >> 4)*2;
5442 reshuffle_ret = ff_reshuffle_raw_rgb(s, &pkt, trk->par, expected_stride);
5443 if (reshuffle_ret < 0)
5444 return reshuffle_ret;
5447 if (trk->par->format == AV_PIX_FMT_PAL8 && !trk->pal_done) {
5448 ret = ff_get_packet_palette(s, opkt, reshuffle_ret, trk->palette);
5453 } else if (trk->par->codec_id == AV_CODEC_ID_RAWVIDEO &&
5454 (trk->par->format == AV_PIX_FMT_GRAY8 ||
5455 trk->par->format == AV_PIX_FMT_MONOBLACK)) {
5456 for (i = 0; i < pkt->size; i++)
5457 pkt->data[i] = ~pkt->data[i];
5459 if (reshuffle_ret) {
5460 ret = mov_write_single_packet(s, pkt);
5463 av_packet_free(&pkt);
5468 return mov_write_single_packet(s, pkt);
5472 // QuickTime chapters involve an additional text track with the chapter names
5473 // as samples, and a tref pointing from the other tracks to the chapter one.
5474 static int mov_create_chapter_track(AVFormatContext *s, int tracknum)
5478 MOVMuxContext *mov = s->priv_data;
5479 MOVTrack *track = &mov->tracks[tracknum];
5480 AVPacket pkt = { .stream_index = tracknum, .flags = AV_PKT_FLAG_KEY };
5483 track->mode = mov->mode;
5484 track->tag = MKTAG('t','e','x','t');
5485 track->timescale = MOV_TIMESCALE;
5486 track->par = avcodec_parameters_alloc();
5488 return AVERROR(ENOMEM);
5489 track->par->codec_type = AVMEDIA_TYPE_SUBTITLE;
5491 // These properties are required to make QT recognize the chapter track
5492 uint8_t chapter_properties[43] = { 0, 0, 0, 0, 0, 0, 0, 1, };
5493 if (ff_alloc_extradata(track->par, sizeof(chapter_properties)))
5494 return AVERROR(ENOMEM);
5495 memcpy(track->par->extradata, chapter_properties, sizeof(chapter_properties));
5497 if (avio_open_dyn_buf(&pb) >= 0) {
5501 /* Stub header (usually for Quicktime chapter track) */
5503 avio_wb32(pb, 0x01); // displayFlags
5504 avio_w8(pb, 0x00); // horizontal justification
5505 avio_w8(pb, 0x00); // vertical justification
5506 avio_w8(pb, 0x00); // bgColourRed
5507 avio_w8(pb, 0x00); // bgColourGreen
5508 avio_w8(pb, 0x00); // bgColourBlue
5509 avio_w8(pb, 0x00); // bgColourAlpha
5511 avio_wb16(pb, 0x00); // defTextBoxTop
5512 avio_wb16(pb, 0x00); // defTextBoxLeft
5513 avio_wb16(pb, 0x00); // defTextBoxBottom
5514 avio_wb16(pb, 0x00); // defTextBoxRight
5516 avio_wb16(pb, 0x00); // startChar
5517 avio_wb16(pb, 0x00); // endChar
5518 avio_wb16(pb, 0x01); // fontID
5519 avio_w8(pb, 0x00); // fontStyleFlags
5520 avio_w8(pb, 0x00); // fontSize
5521 avio_w8(pb, 0x00); // fgColourRed
5522 avio_w8(pb, 0x00); // fgColourGreen
5523 avio_w8(pb, 0x00); // fgColourBlue
5524 avio_w8(pb, 0x00); // fgColourAlpha
5526 avio_wb32(pb, 0x0D); // box size
5527 ffio_wfourcc(pb, "ftab"); // box atom name
5528 avio_wb16(pb, 0x01); // entry count
5530 avio_wb16(pb, 0x01); // font ID
5531 avio_w8(pb, 0x00); // font name length
5533 if ((size = avio_close_dyn_buf(pb, &buf)) > 0) {
5534 track->par->extradata = buf;
5535 track->par->extradata_size = size;
5542 for (i = 0; i < s->nb_chapters; i++) {
5543 AVChapter *c = s->chapters[i];
5544 AVDictionaryEntry *t;
5546 int64_t end = av_rescale_q(c->end, c->time_base, (AVRational){1,MOV_TIMESCALE});
5547 pkt.pts = pkt.dts = av_rescale_q(c->start, c->time_base, (AVRational){1,MOV_TIMESCALE});
5548 pkt.duration = end - pkt.dts;
5550 if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
5551 static const char encd[12] = {
5552 0x00, 0x00, 0x00, 0x0C,
5554 0x00, 0x00, 0x01, 0x00 };
5555 len = strlen(t->value);
5556 pkt.size = len + 2 + 12;
5557 pkt.data = av_malloc(pkt.size);
5559 return AVERROR(ENOMEM);
5560 AV_WB16(pkt.data, len);
5561 memcpy(pkt.data + 2, t->value, len);
5562 memcpy(pkt.data + len + 2, encd, sizeof(encd));
5563 ff_mov_write_packet(s, &pkt);
5564 av_freep(&pkt.data);
5572 static int mov_check_timecode_track(AVFormatContext *s, AVTimecode *tc, int src_index, const char *tcstr)
5576 /* compute the frame number */
5577 ret = av_timecode_init_from_string(tc, find_fps(s, s->streams[src_index]), tcstr, s);
5581 static int mov_create_timecode_track(AVFormatContext *s, int index, int src_index, AVTimecode tc)
5584 MOVMuxContext *mov = s->priv_data;
5585 MOVTrack *track = &mov->tracks[index];
5586 AVStream *src_st = s->streams[src_index];
5587 AVPacket pkt = {.stream_index = index, .flags = AV_PKT_FLAG_KEY, .size = 4};
5588 AVRational rate = find_fps(s, src_st);
5590 /* tmcd track based on video stream */
5591 track->mode = mov->mode;
5592 track->tag = MKTAG('t','m','c','d');
5593 track->src_track = src_index;
5594 track->timescale = mov->tracks[src_index].timescale;
5595 if (tc.flags & AV_TIMECODE_FLAG_DROPFRAME)
5596 track->timecode_flags |= MOV_TIMECODE_FLAG_DROPFRAME;
5598 /* set st to src_st for metadata access*/
5601 /* encode context: tmcd data stream */
5602 track->par = avcodec_parameters_alloc();
5604 return AVERROR(ENOMEM);
5605 track->par->codec_type = AVMEDIA_TYPE_DATA;
5606 track->par->codec_tag = track->tag;
5607 track->st->avg_frame_rate = av_inv_q(rate);
5609 /* the tmcd track just contains one packet with the frame number */
5610 pkt.data = av_malloc(pkt.size);
5612 return AVERROR(ENOMEM);
5613 AV_WB32(pkt.data, tc.start);
5614 ret = ff_mov_write_packet(s, &pkt);
5620 * st->disposition controls the "enabled" flag in the tkhd tag.
5621 * QuickTime will not play a track if it is not enabled. So make sure
5622 * that one track of each type (audio, video, subtitle) is enabled.
5624 * Subtitles are special. For audio and video, setting "enabled" also
5625 * makes the track "default" (i.e. it is rendered when played). For
5626 * subtitles, an "enabled" subtitle is not rendered by default, but
5627 * if no subtitle is enabled, the subtitle menu in QuickTime will be
5630 static void enable_tracks(AVFormatContext *s)
5632 MOVMuxContext *mov = s->priv_data;
5634 int enabled[AVMEDIA_TYPE_NB];
5635 int first[AVMEDIA_TYPE_NB];
5637 for (i = 0; i < AVMEDIA_TYPE_NB; i++) {
5642 for (i = 0; i < s->nb_streams; i++) {
5643 AVStream *st = s->streams[i];
5645 if (st->codecpar->codec_type <= AVMEDIA_TYPE_UNKNOWN ||
5646 st->codecpar->codec_type >= AVMEDIA_TYPE_NB)
5649 if (first[st->codecpar->codec_type] < 0)
5650 first[st->codecpar->codec_type] = i;
5651 if (st->disposition & AV_DISPOSITION_DEFAULT) {
5652 mov->tracks[i].flags |= MOV_TRACK_ENABLED;
5653 enabled[st->codecpar->codec_type]++;
5657 for (i = 0; i < AVMEDIA_TYPE_NB; i++) {
5659 case AVMEDIA_TYPE_VIDEO:
5660 case AVMEDIA_TYPE_AUDIO:
5661 case AVMEDIA_TYPE_SUBTITLE:
5663 mov->per_stream_grouping = 1;
5664 if (!enabled[i] && first[i] >= 0)
5665 mov->tracks[first[i]].flags |= MOV_TRACK_ENABLED;
5671 static void mov_free(AVFormatContext *s)
5673 MOVMuxContext *mov = s->priv_data;
5676 if (mov->chapter_track) {
5677 if (mov->tracks[mov->chapter_track].par)
5678 av_freep(&mov->tracks[mov->chapter_track].par->extradata);
5679 av_freep(&mov->tracks[mov->chapter_track].par);
5682 for (i = 0; i < mov->nb_streams; i++) {
5683 if (mov->tracks[i].tag == MKTAG('r','t','p',' '))
5684 ff_mov_close_hinting(&mov->tracks[i]);
5685 else if (mov->tracks[i].tag == MKTAG('t','m','c','d') && mov->nb_meta_tmcd)
5686 av_freep(&mov->tracks[i].par);
5687 av_freep(&mov->tracks[i].cluster);
5688 av_freep(&mov->tracks[i].frag_info);
5690 if (mov->tracks[i].vos_len)
5691 av_freep(&mov->tracks[i].vos_data);
5693 ff_mov_cenc_free(&mov->tracks[i].cenc);
5696 av_freep(&mov->tracks);
5699 static uint32_t rgb_to_yuv(uint32_t rgb)
5704 r = (rgb >> 16) & 0xFF;
5705 g = (rgb >> 8) & 0xFF;
5708 y = av_clip_uint8(( 16000 + 257 * r + 504 * g + 98 * b)/1000);
5709 cb = av_clip_uint8((128000 - 148 * r - 291 * g + 439 * b)/1000);
5710 cr = av_clip_uint8((128000 + 439 * r - 368 * g - 71 * b)/1000);
5712 return (y << 16) | (cr << 8) | cb;
5715 static int mov_create_dvd_sub_decoder_specific_info(MOVTrack *track,
5718 int i, width = 720, height = 480;
5719 int have_palette = 0, have_size = 0;
5720 uint32_t palette[16];
5721 char *cur = st->codecpar->extradata;
5723 while (cur && *cur) {
5724 if (strncmp("palette:", cur, 8) == 0) {
5726 count = sscanf(cur + 8,
5727 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
5728 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
5729 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
5730 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32"",
5731 &palette[ 0], &palette[ 1], &palette[ 2], &palette[ 3],
5732 &palette[ 4], &palette[ 5], &palette[ 6], &palette[ 7],
5733 &palette[ 8], &palette[ 9], &palette[10], &palette[11],
5734 &palette[12], &palette[13], &palette[14], &palette[15]);
5736 for (i = 0; i < count; i++) {
5737 palette[i] = rgb_to_yuv(palette[i]);
5740 } else if (!strncmp("size:", cur, 5)) {
5741 sscanf(cur + 5, "%dx%d", &width, &height);
5744 if (have_palette && have_size)
5746 cur += strcspn(cur, "\n\r");
5747 cur += strspn(cur, "\n\r");
5750 track->vos_data = av_malloc(16*4);
5751 if (!track->vos_data)
5752 return AVERROR(ENOMEM);
5753 for (i = 0; i < 16; i++) {
5754 AV_WB32(track->vos_data + i * 4, palette[i]);
5756 track->vos_len = 16 * 4;
5758 st->codecpar->width = width;
5759 st->codecpar->height = track->height = height;
5764 static int mov_init(AVFormatContext *s)
5766 MOVMuxContext *mov = s->priv_data;
5767 AVDictionaryEntry *global_tcr = av_dict_get(s->metadata, "timecode", NULL, 0);
5772 /* Default mode == MP4 */
5773 mov->mode = MODE_MP4;
5776 if (!strcmp("3gp", s->oformat->name)) mov->mode = MODE_3GP;
5777 else if (!strcmp("3g2", s->oformat->name)) mov->mode = MODE_3GP|MODE_3G2;
5778 else if (!strcmp("mov", s->oformat->name)) mov->mode = MODE_MOV;
5779 else if (!strcmp("psp", s->oformat->name)) mov->mode = MODE_PSP;
5780 else if (!strcmp("ipod",s->oformat->name)) mov->mode = MODE_IPOD;
5781 else if (!strcmp("ismv",s->oformat->name)) mov->mode = MODE_ISM;
5782 else if (!strcmp("f4v", s->oformat->name)) mov->mode = MODE_F4V;
5785 if (mov->flags & FF_MOV_FLAG_DELAY_MOOV)
5786 mov->flags |= FF_MOV_FLAG_EMPTY_MOOV;
5788 /* Set the FRAGMENT flag if any of the fragmentation methods are
5790 if (mov->max_fragment_duration || mov->max_fragment_size ||
5791 mov->flags & (FF_MOV_FLAG_EMPTY_MOOV |
5792 FF_MOV_FLAG_FRAG_KEYFRAME |
5793 FF_MOV_FLAG_FRAG_CUSTOM))
5794 mov->flags |= FF_MOV_FLAG_FRAGMENT;
5796 /* Set other implicit flags immediately */
5797 if (mov->mode == MODE_ISM)
5798 mov->flags |= FF_MOV_FLAG_EMPTY_MOOV | FF_MOV_FLAG_SEPARATE_MOOF |
5799 FF_MOV_FLAG_FRAGMENT;
5800 if (mov->flags & FF_MOV_FLAG_DASH)
5801 mov->flags |= FF_MOV_FLAG_FRAGMENT | FF_MOV_FLAG_EMPTY_MOOV |
5802 FF_MOV_FLAG_DEFAULT_BASE_MOOF;
5804 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV && s->flags & AVFMT_FLAG_AUTO_BSF) {
5805 av_log(s, AV_LOG_VERBOSE, "Empty MOOV enabled; disabling automatic bitstream filtering\n");
5806 s->flags &= ~AVFMT_FLAG_AUTO_BSF;
5809 if (mov->flags & FF_MOV_FLAG_FASTSTART) {
5810 mov->reserved_moov_size = -1;
5813 if (mov->use_editlist < 0) {
5814 mov->use_editlist = 1;
5815 if (mov->flags & FF_MOV_FLAG_FRAGMENT &&
5816 !(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
5817 // If we can avoid needing an edit list by shifting the
5818 // tracks, prefer that over (trying to) write edit lists
5819 // in fragmented output.
5820 if (s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO ||
5821 s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO)
5822 mov->use_editlist = 0;
5825 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV &&
5826 !(mov->flags & FF_MOV_FLAG_DELAY_MOOV) && mov->use_editlist)
5827 av_log(s, AV_LOG_WARNING, "No meaningful edit list will be written when using empty_moov without delay_moov\n");
5829 if (!mov->use_editlist && s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO)
5830 s->avoid_negative_ts = AVFMT_AVOID_NEG_TS_MAKE_ZERO;
5832 /* Clear the omit_tfhd_offset flag if default_base_moof is set;
5833 * if the latter is set that's enough and omit_tfhd_offset doesn't
5834 * add anything extra on top of that. */
5835 if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET &&
5836 mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)
5837 mov->flags &= ~FF_MOV_FLAG_OMIT_TFHD_OFFSET;
5839 if (mov->frag_interleave &&
5840 mov->flags & (FF_MOV_FLAG_OMIT_TFHD_OFFSET | FF_MOV_FLAG_SEPARATE_MOOF)) {
5841 av_log(s, AV_LOG_ERROR,
5842 "Sample interleaving in fragments is mutually exclusive with "
5843 "omit_tfhd_offset and separate_moof\n");
5844 return AVERROR(EINVAL);
5847 /* Non-seekable output is ok if using fragmentation. If ism_lookahead
5848 * is enabled, we don't support non-seekable output at all. */
5849 if (!(s->pb->seekable & AVIO_SEEKABLE_NORMAL) &&
5850 (!(mov->flags & FF_MOV_FLAG_FRAGMENT) || mov->ism_lookahead)) {
5851 av_log(s, AV_LOG_ERROR, "muxer does not support non seekable output\n");
5852 return AVERROR(EINVAL);
5855 mov->nb_streams = s->nb_streams;
5856 if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters)
5857 mov->chapter_track = mov->nb_streams++;
5859 if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
5860 /* Add hint tracks for each audio and video stream */
5861 for (i = 0; i < s->nb_streams; i++) {
5862 AVStream *st = s->streams[i];
5863 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ||
5864 st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
5870 if ( mov->write_tmcd == -1 && (mov->mode == MODE_MOV || mov->mode == MODE_MP4)
5871 || mov->write_tmcd == 1) {
5872 /* +1 tmcd track for each video stream with a timecode */
5873 for (i = 0; i < s->nb_streams; i++) {
5874 AVStream *st = s->streams[i];
5875 AVDictionaryEntry *t = global_tcr;
5876 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
5877 (t || (t=av_dict_get(st->metadata, "timecode", NULL, 0)))) {
5879 ret = mov_check_timecode_track(s, &tc, i, t->value);
5881 mov->nb_meta_tmcd++;
5885 /* check if there is already a tmcd track to remux */
5886 if (mov->nb_meta_tmcd) {
5887 for (i = 0; i < s->nb_streams; i++) {
5888 AVStream *st = s->streams[i];
5889 if (st->codecpar->codec_tag == MKTAG('t','m','c','d')) {
5890 av_log(s, AV_LOG_WARNING, "You requested a copy of the original timecode track "
5891 "so timecode metadata are now ignored\n");
5892 mov->nb_meta_tmcd = 0;
5897 mov->nb_streams += mov->nb_meta_tmcd;
5900 // Reserve an extra stream for chapters for the case where chapters
5901 // are written in the trailer
5902 mov->tracks = av_mallocz_array((mov->nb_streams + 1), sizeof(*mov->tracks));
5904 return AVERROR(ENOMEM);
5906 if (mov->encryption_scheme_str != NULL && strcmp(mov->encryption_scheme_str, "none") != 0) {
5907 if (strcmp(mov->encryption_scheme_str, "cenc-aes-ctr") == 0) {
5908 mov->encryption_scheme = MOV_ENC_CENC_AES_CTR;
5910 if (mov->encryption_key_len != AES_CTR_KEY_SIZE) {
5911 av_log(s, AV_LOG_ERROR, "Invalid encryption key len %d expected %d\n",
5912 mov->encryption_key_len, AES_CTR_KEY_SIZE);
5913 return AVERROR(EINVAL);
5916 if (mov->encryption_kid_len != CENC_KID_SIZE) {
5917 av_log(s, AV_LOG_ERROR, "Invalid encryption kid len %d expected %d\n",
5918 mov->encryption_kid_len, CENC_KID_SIZE);
5919 return AVERROR(EINVAL);
5922 av_log(s, AV_LOG_ERROR, "unsupported encryption scheme %s\n",
5923 mov->encryption_scheme_str);
5924 return AVERROR(EINVAL);
5928 for (i = 0; i < s->nb_streams; i++) {
5929 AVStream *st= s->streams[i];
5930 MOVTrack *track= &mov->tracks[i];
5931 AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0);
5934 track->par = st->codecpar;
5935 track->language = ff_mov_iso639_to_lang(lang?lang->value:"und", mov->mode!=MODE_MOV);
5936 if (track->language < 0)
5937 track->language = 0;
5938 track->mode = mov->mode;
5939 track->tag = mov_find_codec_tag(s, track);
5941 av_log(s, AV_LOG_ERROR, "Could not find tag for codec %s in stream #%d, "
5942 "codec not currently supported in container\n",
5943 avcodec_get_name(st->codecpar->codec_id), i);
5944 return AVERROR(EINVAL);
5946 /* If hinting of this track is enabled by a later hint track,
5947 * this is updated. */
5948 track->hint_track = -1;
5949 track->start_dts = AV_NOPTS_VALUE;
5950 track->start_cts = AV_NOPTS_VALUE;
5951 track->end_pts = AV_NOPTS_VALUE;
5952 track->dts_shift = AV_NOPTS_VALUE;
5953 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
5954 if (track->tag == MKTAG('m','x','3','p') || track->tag == MKTAG('m','x','3','n') ||
5955 track->tag == MKTAG('m','x','4','p') || track->tag == MKTAG('m','x','4','n') ||
5956 track->tag == MKTAG('m','x','5','p') || track->tag == MKTAG('m','x','5','n')) {
5957 if (st->codecpar->width != 720 || (st->codecpar->height != 608 && st->codecpar->height != 512)) {
5958 av_log(s, AV_LOG_ERROR, "D-10/IMX must use 720x608 or 720x512 video resolution\n");
5959 return AVERROR(EINVAL);
5961 track->height = track->tag >> 24 == 'n' ? 486 : 576;
5963 if (mov->video_track_timescale) {
5964 track->timescale = mov->video_track_timescale;
5966 track->timescale = st->time_base.den;
5967 while(track->timescale < 10000)
5968 track->timescale *= 2;
5970 if (st->codecpar->width > 65535 || st->codecpar->height > 65535) {
5971 av_log(s, AV_LOG_ERROR, "Resolution %dx%d too large for mov/mp4\n", st->codecpar->width, st->codecpar->height);
5972 return AVERROR(EINVAL);
5974 if (track->mode == MODE_MOV && track->timescale > 100000)
5975 av_log(s, AV_LOG_WARNING,
5976 "WARNING codec timebase is very high. If duration is too long,\n"
5977 "file may not be playable by quicktime. Specify a shorter timebase\n"
5978 "or choose different container.\n");
5979 if (track->mode == MODE_MOV &&
5980 track->par->codec_id == AV_CODEC_ID_RAWVIDEO &&
5981 track->tag == MKTAG('r','a','w',' ')) {
5982 enum AVPixelFormat pix_fmt = track->par->format;
5983 if (pix_fmt == AV_PIX_FMT_NONE && track->par->bits_per_coded_sample == 1)
5984 pix_fmt = AV_PIX_FMT_MONOWHITE;
5985 track->is_unaligned_qt_rgb =
5986 pix_fmt == AV_PIX_FMT_RGB24 ||
5987 pix_fmt == AV_PIX_FMT_BGR24 ||
5988 pix_fmt == AV_PIX_FMT_PAL8 ||
5989 pix_fmt == AV_PIX_FMT_GRAY8 ||
5990 pix_fmt == AV_PIX_FMT_MONOWHITE ||
5991 pix_fmt == AV_PIX_FMT_MONOBLACK;
5993 if (track->par->codec_id == AV_CODEC_ID_VP9) {
5994 if (track->mode != MODE_MP4) {
5995 av_log(s, AV_LOG_ERROR, "VP9 only supported in MP4.\n");
5996 return AVERROR(EINVAL);
5999 } else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
6000 track->timescale = st->codecpar->sample_rate;
6001 if (!st->codecpar->frame_size && !av_get_bits_per_sample(st->codecpar->codec_id)) {
6002 av_log(s, AV_LOG_WARNING, "track %d: codec frame size is not set\n", i);
6003 track->audio_vbr = 1;
6004 }else if (st->codecpar->codec_id == AV_CODEC_ID_ADPCM_MS ||
6005 st->codecpar->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
6006 st->codecpar->codec_id == AV_CODEC_ID_ILBC){
6007 if (!st->codecpar->block_align) {
6008 av_log(s, AV_LOG_ERROR, "track %d: codec block align is not set for adpcm\n", i);
6009 return AVERROR(EINVAL);
6011 track->sample_size = st->codecpar->block_align;
6012 }else if (st->codecpar->frame_size > 1){ /* assume compressed audio */
6013 track->audio_vbr = 1;
6015 track->sample_size = (av_get_bits_per_sample(st->codecpar->codec_id) >> 3) * st->codecpar->channels;
6017 if (st->codecpar->codec_id == AV_CODEC_ID_ILBC ||
6018 st->codecpar->codec_id == AV_CODEC_ID_ADPCM_IMA_QT) {
6019 track->audio_vbr = 1;
6021 if (track->mode != MODE_MOV &&
6022 track->par->codec_id == AV_CODEC_ID_MP3 && track->timescale < 16000) {
6023 if (s->strict_std_compliance >= FF_COMPLIANCE_NORMAL) {
6024 av_log(s, AV_LOG_ERROR, "track %d: muxing mp3 at %dhz is not standard, to mux anyway set strict to -1\n",
6025 i, track->par->sample_rate);
6026 return AVERROR(EINVAL);
6028 av_log(s, AV_LOG_WARNING, "track %d: muxing mp3 at %dhz is not standard in MP4\n",
6029 i, track->par->sample_rate);
6032 if (track->par->codec_id == AV_CODEC_ID_FLAC ||
6033 track->par->codec_id == AV_CODEC_ID_OPUS) {
6034 if (track->mode != MODE_MP4) {
6035 av_log(s, AV_LOG_ERROR, "%s only supported in MP4.\n", avcodec_get_name(track->par->codec_id));
6036 return AVERROR(EINVAL);
6038 if (s->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
6039 av_log(s, AV_LOG_ERROR,
6040 "%s in MP4 support is experimental, add "
6041 "'-strict %d' if you want to use it.\n",
6042 avcodec_get_name(track->par->codec_id), FF_COMPLIANCE_EXPERIMENTAL);
6043 return AVERROR_EXPERIMENTAL;
6046 } else if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) {
6047 track->timescale = st->time_base.den;
6048 } else if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA) {
6049 track->timescale = st->time_base.den;
6051 track->timescale = MOV_TIMESCALE;
6054 track->height = st->codecpar->height;
6055 /* The ism specific timescale isn't mandatory, but is assumed by
6056 * some tools, such as mp4split. */
6057 if (mov->mode == MODE_ISM)
6058 track->timescale = 10000000;
6060 avpriv_set_pts_info(st, 64, 1, track->timescale);
6062 if (mov->encryption_scheme == MOV_ENC_CENC_AES_CTR) {
6063 ret = ff_mov_cenc_init(&track->cenc, mov->encryption_key,
6064 track->par->codec_id == AV_CODEC_ID_H264, s->flags & AVFMT_FLAG_BITEXACT);
6074 static int mov_write_header(AVFormatContext *s)
6076 AVIOContext *pb = s->pb;
6077 MOVMuxContext *mov = s->priv_data;
6078 AVDictionaryEntry *t, *global_tcr = av_dict_get(s->metadata, "timecode", NULL, 0);
6079 int i, ret, hint_track = 0, tmcd_track = 0, nb_tracks = s->nb_streams;
6081 if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters)
6084 if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
6085 /* Add hint tracks for each audio and video stream */
6086 hint_track = nb_tracks;
6087 for (i = 0; i < s->nb_streams; i++) {
6088 AVStream *st = s->streams[i];
6089 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ||
6090 st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
6096 if (mov->mode == MODE_MOV || mov->mode == MODE_MP4)
6097 tmcd_track = nb_tracks;
6099 for (i = 0; i < s->nb_streams; i++) {
6101 AVStream *st= s->streams[i];
6102 MOVTrack *track= &mov->tracks[i];
6104 /* copy extradata if it exists */
6105 if (st->codecpar->extradata_size) {
6106 if (st->codecpar->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
6107 mov_create_dvd_sub_decoder_specific_info(track, st);
6108 else if (!TAG_IS_AVCI(track->tag) && st->codecpar->codec_id != AV_CODEC_ID_DNXHD) {
6109 track->vos_len = st->codecpar->extradata_size;
6110 track->vos_data = av_malloc(track->vos_len);
6111 if (!track->vos_data) {
6112 return AVERROR(ENOMEM);
6114 memcpy(track->vos_data, st->codecpar->extradata, track->vos_len);
6118 if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ||
6119 track->par->channel_layout != AV_CH_LAYOUT_MONO)
6122 for (j = 0; j < s->nb_streams; j++) {
6123 AVStream *stj= s->streams[j];
6124 MOVTrack *trackj= &mov->tracks[j];
6128 if (stj->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ||
6129 trackj->par->channel_layout != AV_CH_LAYOUT_MONO ||
6130 trackj->language != track->language ||
6131 trackj->tag != track->tag
6134 track->multichannel_as_mono++;
6138 if (!(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
6139 if ((ret = mov_write_identification(pb, s)) < 0)
6143 if (mov->reserved_moov_size){
6144 mov->reserved_header_pos = avio_tell(pb);
6145 if (mov->reserved_moov_size > 0)
6146 avio_skip(pb, mov->reserved_moov_size);
6149 if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
6150 /* If no fragmentation options have been set, set a default. */
6151 if (!(mov->flags & (FF_MOV_FLAG_FRAG_KEYFRAME |
6152 FF_MOV_FLAG_FRAG_CUSTOM)) &&
6153 !mov->max_fragment_duration && !mov->max_fragment_size)
6154 mov->flags |= FF_MOV_FLAG_FRAG_KEYFRAME;
6156 if (mov->flags & FF_MOV_FLAG_FASTSTART)
6157 mov->reserved_header_pos = avio_tell(pb);
6158 mov_write_mdat_tag(pb, mov);
6161 ff_parse_creation_time_metadata(s, &mov->time, 1);
6163 mov->time += 0x7C25B080; // 1970 based -> 1904 based
6165 if (mov->chapter_track)
6166 if ((ret = mov_create_chapter_track(s, mov->chapter_track)) < 0)
6169 if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
6170 /* Initialize the hint tracks for each audio and video stream */
6171 for (i = 0; i < s->nb_streams; i++) {
6172 AVStream *st = s->streams[i];
6173 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ||
6174 st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
6175 if ((ret = ff_mov_init_hinting(s, hint_track, i)) < 0)
6182 if (mov->nb_meta_tmcd) {
6183 /* Initialize the tmcd tracks */
6184 for (i = 0; i < s->nb_streams; i++) {
6185 AVStream *st = s->streams[i];
6188 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
6191 t = av_dict_get(st->metadata, "timecode", NULL, 0);
6194 if (mov_check_timecode_track(s, &tc, i, t->value) < 0)
6196 if ((ret = mov_create_timecode_track(s, tmcd_track, i, tc)) < 0)
6205 if (mov->flags & FF_MOV_FLAG_ISML)
6206 mov_write_isml_manifest(pb, mov, s);
6208 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV &&
6209 !(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
6210 if ((ret = mov_write_moov_tag(pb, mov, s)) < 0)
6213 mov->moov_written = 1;
6214 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
6215 mov->reserved_header_pos = avio_tell(pb);
6221 static int get_moov_size(AVFormatContext *s)
6224 AVIOContext *moov_buf;
6225 MOVMuxContext *mov = s->priv_data;
6227 if ((ret = ffio_open_null_buf(&moov_buf)) < 0)
6229 if ((ret = mov_write_moov_tag(moov_buf, mov, s)) < 0)
6231 return ffio_close_null_buf(moov_buf);
6234 static int get_sidx_size(AVFormatContext *s)
6238 MOVMuxContext *mov = s->priv_data;
6240 if ((ret = ffio_open_null_buf(&buf)) < 0)
6242 mov_write_sidx_tags(buf, mov, -1, 0);
6243 return ffio_close_null_buf(buf);
6247 * This function gets the moov size if moved to the top of the file: the chunk
6248 * offset table can switch between stco (32-bit entries) to co64 (64-bit
6249 * entries) when the moov is moved to the beginning, so the size of the moov
6250 * would change. It also updates the chunk offset tables.
6252 static int compute_moov_size(AVFormatContext *s)
6254 int i, moov_size, moov_size2;
6255 MOVMuxContext *mov = s->priv_data;
6257 moov_size = get_moov_size(s);
6261 for (i = 0; i < mov->nb_streams; i++)
6262 mov->tracks[i].data_offset += moov_size;
6264 moov_size2 = get_moov_size(s);
6268 /* if the size changed, we just switched from stco to co64 and need to
6269 * update the offsets */
6270 if (moov_size2 != moov_size)
6271 for (i = 0; i < mov->nb_streams; i++)
6272 mov->tracks[i].data_offset += moov_size2 - moov_size;
6277 static int compute_sidx_size(AVFormatContext *s)
6280 MOVMuxContext *mov = s->priv_data;
6282 sidx_size = get_sidx_size(s);
6286 for (i = 0; i < mov->nb_streams; i++)
6287 mov->tracks[i].data_offset += sidx_size;
6292 static int shift_data(AVFormatContext *s)
6294 int ret = 0, moov_size;
6295 MOVMuxContext *mov = s->priv_data;
6296 int64_t pos, pos_end = avio_tell(s->pb);
6297 uint8_t *buf, *read_buf[2];
6298 int read_buf_id = 0;
6300 AVIOContext *read_pb;
6302 if (mov->flags & FF_MOV_FLAG_FRAGMENT)
6303 moov_size = compute_sidx_size(s);
6305 moov_size = compute_moov_size(s);
6309 buf = av_malloc(moov_size * 2);
6311 return AVERROR(ENOMEM);
6313 read_buf[1] = buf + moov_size;
6315 /* Shift the data: the AVIO context of the output can only be used for
6316 * writing, so we re-open the same output, but for reading. It also avoids
6317 * a read/seek/write/seek back and forth. */
6319 ret = s->io_open(s, &read_pb, s->filename, AVIO_FLAG_READ, NULL);
6321 av_log(s, AV_LOG_ERROR, "Unable to re-open %s output file for "
6322 "the second pass (faststart)\n", s->filename);
6326 /* mark the end of the shift to up to the last data we wrote, and get ready
6328 pos_end = avio_tell(s->pb);
6329 avio_seek(s->pb, mov->reserved_header_pos + moov_size, SEEK_SET);
6331 /* start reading at where the new moov will be placed */
6332 avio_seek(read_pb, mov->reserved_header_pos, SEEK_SET);
6333 pos = avio_tell(read_pb);
6335 #define READ_BLOCK do { \
6336 read_size[read_buf_id] = avio_read(read_pb, read_buf[read_buf_id], moov_size); \
6340 /* shift data by chunk of at most moov_size */
6345 n = read_size[read_buf_id];
6348 avio_write(s->pb, read_buf[read_buf_id], n);
6350 } while (pos < pos_end);
6351 ff_format_io_close(s, &read_pb);
6358 static int mov_write_trailer(AVFormatContext *s)
6360 MOVMuxContext *mov = s->priv_data;
6361 AVIOContext *pb = s->pb;
6366 if (mov->need_rewrite_extradata) {
6367 for (i = 0; i < s->nb_streams; i++) {
6368 MOVTrack *track = &mov->tracks[i];
6369 AVCodecParameters *par = track->par;
6371 track->vos_len = par->extradata_size;
6372 track->vos_data = av_malloc(track->vos_len);
6373 if (!track->vos_data)
6374 return AVERROR(ENOMEM);
6375 memcpy(track->vos_data, par->extradata, track->vos_len);
6377 mov->need_rewrite_extradata = 0;
6381 * Before actually writing the trailer, make sure that there are no
6382 * dangling subtitles, that need a terminating sample.
6384 for (i = 0; i < mov->nb_streams; i++) {
6385 MOVTrack *trk = &mov->tracks[i];
6386 if (trk->par->codec_id == AV_CODEC_ID_MOV_TEXT &&
6387 !trk->last_sample_is_subtitle_end) {
6388 mov_write_subtitle_end_packet(s, i, trk->track_duration);
6389 trk->last_sample_is_subtitle_end = 1;
6393 // If there were no chapters when the header was written, but there
6394 // are chapters now, write them in the trailer. This only works
6395 // when we are not doing fragments.
6396 if (!mov->chapter_track && !(mov->flags & FF_MOV_FLAG_FRAGMENT)) {
6397 if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters) {
6398 mov->chapter_track = mov->nb_streams++;
6399 if ((res = mov_create_chapter_track(s, mov->chapter_track)) < 0)
6404 if (!(mov->flags & FF_MOV_FLAG_FRAGMENT)) {
6405 moov_pos = avio_tell(pb);
6407 /* Write size of mdat tag */
6408 if (mov->mdat_size + 8 <= UINT32_MAX) {
6409 avio_seek(pb, mov->mdat_pos, SEEK_SET);
6410 avio_wb32(pb, mov->mdat_size + 8);
6412 /* overwrite 'wide' placeholder atom */
6413 avio_seek(pb, mov->mdat_pos - 8, SEEK_SET);
6414 /* special value: real atom size will be 64 bit value after
6417 ffio_wfourcc(pb, "mdat");
6418 avio_wb64(pb, mov->mdat_size + 16);
6420 avio_seek(pb, mov->reserved_moov_size > 0 ? mov->reserved_header_pos : moov_pos, SEEK_SET);
6422 if (mov->flags & FF_MOV_FLAG_FASTSTART) {
6423 av_log(s, AV_LOG_INFO, "Starting second pass: moving the moov atom to the beginning of the file\n");
6424 res = shift_data(s);
6427 avio_seek(pb, mov->reserved_header_pos, SEEK_SET);
6428 if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
6430 } else if (mov->reserved_moov_size > 0) {
6432 if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
6434 size = mov->reserved_moov_size - (avio_tell(pb) - mov->reserved_header_pos);
6436 av_log(s, AV_LOG_ERROR, "reserved_moov_size is too small, needed %"PRId64" additional\n", 8-size);
6437 return AVERROR(EINVAL);
6439 avio_wb32(pb, size);
6440 ffio_wfourcc(pb, "free");
6441 ffio_fill(pb, 0, size - 8);
6442 avio_seek(pb, moov_pos, SEEK_SET);
6444 if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
6449 mov_auto_flush_fragment(s, 1);
6450 for (i = 0; i < mov->nb_streams; i++)
6451 mov->tracks[i].data_offset = 0;
6452 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) {
6454 av_log(s, AV_LOG_INFO, "Starting second pass: inserting sidx atoms\n");
6455 res = shift_data(s);
6458 end = avio_tell(pb);
6459 avio_seek(pb, mov->reserved_header_pos, SEEK_SET);
6460 mov_write_sidx_tags(pb, mov, -1, 0);
6461 avio_seek(pb, end, SEEK_SET);
6462 avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_TRAILER);
6463 mov_write_mfra_tag(pb, mov);
6464 } else if (!(mov->flags & FF_MOV_FLAG_SKIP_TRAILER)) {
6465 avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_TRAILER);
6466 mov_write_mfra_tag(pb, mov);
6473 static int mov_check_bitstream(struct AVFormatContext *s, const AVPacket *pkt)
6476 AVStream *st = s->streams[pkt->stream_index];
6478 if (st->codecpar->codec_id == AV_CODEC_ID_AAC) {
6479 if (pkt->size > 2 && (AV_RB16(pkt->data) & 0xfff0) == 0xfff0)
6480 ret = ff_stream_add_bitstream_filter(st, "aac_adtstoasc", NULL);
6481 } else if (st->codecpar->codec_id == AV_CODEC_ID_VP9) {
6482 ret = ff_stream_add_bitstream_filter(st, "vp9_superframe", NULL);
6488 static const AVCodecTag codec_3gp_tags[] = {
6489 { AV_CODEC_ID_H263, MKTAG('s','2','6','3') },
6490 { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
6491 { AV_CODEC_ID_MPEG4, MKTAG('m','p','4','v') },
6492 { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
6493 { AV_CODEC_ID_AMR_NB, MKTAG('s','a','m','r') },
6494 { AV_CODEC_ID_AMR_WB, MKTAG('s','a','w','b') },
6495 { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
6496 { AV_CODEC_ID_NONE, 0 },
6499 const AVCodecTag codec_mp4_tags[] = {
6500 { AV_CODEC_ID_MPEG4 , MKTAG('m', 'p', '4', 'v') },
6501 { AV_CODEC_ID_H264 , MKTAG('a', 'v', 'c', '1') },
6502 { AV_CODEC_ID_HEVC , MKTAG('h', 'e', 'v', '1') },
6503 { AV_CODEC_ID_HEVC , MKTAG('h', 'v', 'c', '1') },
6504 { AV_CODEC_ID_MPEG2VIDEO , MKTAG('m', 'p', '4', 'v') },
6505 { AV_CODEC_ID_MPEG1VIDEO , MKTAG('m', 'p', '4', 'v') },
6506 { AV_CODEC_ID_MJPEG , MKTAG('m', 'p', '4', 'v') },
6507 { AV_CODEC_ID_PNG , MKTAG('m', 'p', '4', 'v') },
6508 { AV_CODEC_ID_JPEG2000 , MKTAG('m', 'p', '4', 'v') },
6509 { AV_CODEC_ID_VC1 , MKTAG('v', 'c', '-', '1') },
6510 { AV_CODEC_ID_DIRAC , MKTAG('d', 'r', 'a', 'c') },
6511 { AV_CODEC_ID_TSCC2 , MKTAG('m', 'p', '4', 'v') },
6512 { AV_CODEC_ID_VP9 , MKTAG('v', 'p', '0', '9') },
6513 { AV_CODEC_ID_AAC , MKTAG('m', 'p', '4', 'a') },
6514 { AV_CODEC_ID_MP4ALS , MKTAG('m', 'p', '4', 'a') },
6515 { AV_CODEC_ID_MP3 , MKTAG('m', 'p', '4', 'a') },
6516 { AV_CODEC_ID_MP2 , MKTAG('m', 'p', '4', 'a') },
6517 { AV_CODEC_ID_AC3 , MKTAG('a', 'c', '-', '3') },
6518 { AV_CODEC_ID_EAC3 , MKTAG('e', 'c', '-', '3') },
6519 { AV_CODEC_ID_DTS , MKTAG('m', 'p', '4', 'a') },
6520 { AV_CODEC_ID_FLAC , MKTAG('f', 'L', 'a', 'C') },
6521 { AV_CODEC_ID_OPUS , MKTAG('O', 'p', 'u', 's') },
6522 { AV_CODEC_ID_VORBIS , MKTAG('m', 'p', '4', 'a') },
6523 { AV_CODEC_ID_QCELP , MKTAG('m', 'p', '4', 'a') },
6524 { AV_CODEC_ID_EVRC , MKTAG('m', 'p', '4', 'a') },
6525 { AV_CODEC_ID_DVD_SUBTITLE, MKTAG('m', 'p', '4', 's') },
6526 { AV_CODEC_ID_MOV_TEXT , MKTAG('t', 'x', '3', 'g') },
6527 { AV_CODEC_ID_NONE , 0 },
6530 const AVCodecTag codec_ism_tags[] = {
6531 { AV_CODEC_ID_WMAPRO , MKTAG('w', 'm', 'a', ' ') },
6532 { AV_CODEC_ID_NONE , 0 },
6535 static const AVCodecTag codec_ipod_tags[] = {
6536 { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
6537 { AV_CODEC_ID_MPEG4, MKTAG('m','p','4','v') },
6538 { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
6539 { AV_CODEC_ID_ALAC, MKTAG('a','l','a','c') },
6540 { AV_CODEC_ID_AC3, MKTAG('a','c','-','3') },
6541 { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
6542 { AV_CODEC_ID_MOV_TEXT, MKTAG('t','e','x','t') },
6543 { AV_CODEC_ID_NONE, 0 },
6546 static const AVCodecTag codec_f4v_tags[] = {
6547 { AV_CODEC_ID_MP3, MKTAG('.','m','p','3') },
6548 { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
6549 { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
6550 { AV_CODEC_ID_VP6A, MKTAG('V','P','6','A') },
6551 { AV_CODEC_ID_VP6F, MKTAG('V','P','6','F') },
6552 { AV_CODEC_ID_NONE, 0 },
6555 #if CONFIG_MOV_MUXER
6557 AVOutputFormat ff_mov_muxer = {
6559 .long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
6560 .extensions = "mov",
6561 .priv_data_size = sizeof(MOVMuxContext),
6562 .audio_codec = AV_CODEC_ID_AAC,
6563 .video_codec = CONFIG_LIBX264_ENCODER ?
6564 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
6566 .write_header = mov_write_header,
6567 .write_packet = mov_write_packet,
6568 .write_trailer = mov_write_trailer,
6570 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6571 .codec_tag = (const AVCodecTag* const []){
6572 ff_codec_movvideo_tags, ff_codec_movaudio_tags, 0
6574 .check_bitstream = mov_check_bitstream,
6575 .priv_class = &mov_muxer_class,
6578 #if CONFIG_TGP_MUXER
6580 AVOutputFormat ff_tgp_muxer = {
6582 .long_name = NULL_IF_CONFIG_SMALL("3GP (3GPP file format)"),
6583 .extensions = "3gp",
6584 .priv_data_size = sizeof(MOVMuxContext),
6585 .audio_codec = AV_CODEC_ID_AMR_NB,
6586 .video_codec = AV_CODEC_ID_H263,
6588 .write_header = mov_write_header,
6589 .write_packet = mov_write_packet,
6590 .write_trailer = mov_write_trailer,
6592 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6593 .codec_tag = (const AVCodecTag* const []){ codec_3gp_tags, 0 },
6594 .check_bitstream = mov_check_bitstream,
6595 .priv_class = &tgp_muxer_class,
6598 #if CONFIG_MP4_MUXER
6600 AVOutputFormat ff_mp4_muxer = {
6602 .long_name = NULL_IF_CONFIG_SMALL("MP4 (MPEG-4 Part 14)"),
6603 .mime_type = "video/mp4",
6604 .extensions = "mp4",
6605 .priv_data_size = sizeof(MOVMuxContext),
6606 .audio_codec = AV_CODEC_ID_AAC,
6607 .video_codec = CONFIG_LIBX264_ENCODER ?
6608 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
6610 .write_header = mov_write_header,
6611 .write_packet = mov_write_packet,
6612 .write_trailer = mov_write_trailer,
6614 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6615 .codec_tag = (const AVCodecTag* const []){ codec_mp4_tags, 0 },
6616 .check_bitstream = mov_check_bitstream,
6617 .priv_class = &mp4_muxer_class,
6620 #if CONFIG_PSP_MUXER
6622 AVOutputFormat ff_psp_muxer = {
6624 .long_name = NULL_IF_CONFIG_SMALL("PSP MP4 (MPEG-4 Part 14)"),
6625 .extensions = "mp4,psp",
6626 .priv_data_size = sizeof(MOVMuxContext),
6627 .audio_codec = AV_CODEC_ID_AAC,
6628 .video_codec = CONFIG_LIBX264_ENCODER ?
6629 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
6631 .write_header = mov_write_header,
6632 .write_packet = mov_write_packet,
6633 .write_trailer = mov_write_trailer,
6635 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6636 .codec_tag = (const AVCodecTag* const []){ codec_mp4_tags, 0 },
6637 .check_bitstream = mov_check_bitstream,
6638 .priv_class = &psp_muxer_class,
6641 #if CONFIG_TG2_MUXER
6643 AVOutputFormat ff_tg2_muxer = {
6645 .long_name = NULL_IF_CONFIG_SMALL("3GP2 (3GPP2 file format)"),
6646 .extensions = "3g2",
6647 .priv_data_size = sizeof(MOVMuxContext),
6648 .audio_codec = AV_CODEC_ID_AMR_NB,
6649 .video_codec = AV_CODEC_ID_H263,
6651 .write_header = mov_write_header,
6652 .write_packet = mov_write_packet,
6653 .write_trailer = mov_write_trailer,
6655 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6656 .codec_tag = (const AVCodecTag* const []){ codec_3gp_tags, 0 },
6657 .check_bitstream = mov_check_bitstream,
6658 .priv_class = &tg2_muxer_class,
6661 #if CONFIG_IPOD_MUXER
6663 AVOutputFormat ff_ipod_muxer = {
6665 .long_name = NULL_IF_CONFIG_SMALL("iPod H.264 MP4 (MPEG-4 Part 14)"),
6666 .mime_type = "video/mp4",
6667 .extensions = "m4v,m4a",
6668 .priv_data_size = sizeof(MOVMuxContext),
6669 .audio_codec = AV_CODEC_ID_AAC,
6670 .video_codec = AV_CODEC_ID_H264,
6672 .write_header = mov_write_header,
6673 .write_packet = mov_write_packet,
6674 .write_trailer = mov_write_trailer,
6676 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6677 .codec_tag = (const AVCodecTag* const []){ codec_ipod_tags, 0 },
6678 .check_bitstream = mov_check_bitstream,
6679 .priv_class = &ipod_muxer_class,
6682 #if CONFIG_ISMV_MUXER
6684 AVOutputFormat ff_ismv_muxer = {
6686 .long_name = NULL_IF_CONFIG_SMALL("ISMV/ISMA (Smooth Streaming)"),
6687 .mime_type = "video/mp4",
6688 .extensions = "ismv,isma",
6689 .priv_data_size = sizeof(MOVMuxContext),
6690 .audio_codec = AV_CODEC_ID_AAC,
6691 .video_codec = AV_CODEC_ID_H264,
6693 .write_header = mov_write_header,
6694 .write_packet = mov_write_packet,
6695 .write_trailer = mov_write_trailer,
6697 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6698 .codec_tag = (const AVCodecTag* const []){
6699 codec_mp4_tags, codec_ism_tags, 0 },
6700 .check_bitstream = mov_check_bitstream,
6701 .priv_class = &ismv_muxer_class,
6704 #if CONFIG_F4V_MUXER
6706 AVOutputFormat ff_f4v_muxer = {
6708 .long_name = NULL_IF_CONFIG_SMALL("F4V Adobe Flash Video"),
6709 .mime_type = "application/f4v",
6710 .extensions = "f4v",
6711 .priv_data_size = sizeof(MOVMuxContext),
6712 .audio_codec = AV_CODEC_ID_AAC,
6713 .video_codec = AV_CODEC_ID_H264,
6715 .write_header = mov_write_header,
6716 .write_packet = mov_write_packet,
6717 .write_trailer = mov_write_trailer,
6719 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH,
6720 .codec_tag = (const AVCodecTag* const []){ codec_f4v_tags, 0 },
6721 .check_bitstream = mov_check_bitstream,
6722 .priv_class = &f4v_muxer_class,