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 *hdr = NULL;
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 ret = AVERROR_INVALIDDATA;
366 info->data_rate = FFMAX(info->data_rate, hdr->bit_rate / 1000);
367 num_blocks = hdr->num_blocks;
369 if (!info->ec3_done) {
370 /* AC-3 substream must be the first one */
371 if (hdr->bitstream_id <= 10 && hdr->substreamid != 0) {
372 ret = AVERROR(EINVAL);
376 /* this should always be the case, given that our AC-3 parser
377 * concatenates dependent frames to their independent parent */
378 if (hdr->frame_type == EAC3_FRAME_TYPE_INDEPENDENT) {
379 /* substream ids must be incremental */
380 if (hdr->substreamid > info->num_ind_sub + 1) {
381 ret = AVERROR(EINVAL);
385 if (hdr->substreamid == info->num_ind_sub + 1) {
386 //info->num_ind_sub++;
387 avpriv_request_sample(track->par, "Multiple independent substreams");
388 ret = AVERROR_PATCHWELCOME;
390 } else if (hdr->substreamid < info->num_ind_sub ||
391 hdr->substreamid == 0 && info->substream[0].bsid) {
397 /* fill the info needed for the "dec3" atom */
398 info->substream[hdr->substreamid].fscod = hdr->sr_code;
399 info->substream[hdr->substreamid].bsid = hdr->bitstream_id;
400 info->substream[hdr->substreamid].bsmod = hdr->bitstream_mode;
401 info->substream[hdr->substreamid].acmod = hdr->channel_mode;
402 info->substream[hdr->substreamid].lfeon = hdr->lfe_on;
404 /* Parse dependent substream(s), if any */
405 if (pkt->size != hdr->frame_size) {
406 int cumul_size = hdr->frame_size;
407 int parent = hdr->substreamid;
409 while (cumul_size != pkt->size) {
412 ret = avpriv_ac3_parse_header(&hdr, pkt->data + cumul_size, pkt->size - cumul_size);
415 if (hdr->frame_type != EAC3_FRAME_TYPE_DEPENDENT) {
416 ret = AVERROR(EINVAL);
419 info->substream[parent].num_dep_sub++;
422 /* header is parsed up to lfeon, but custom channel map may be needed */
423 init_get_bits8(&gbc, pkt->data + cumul_size + ret, pkt->size - cumul_size - ret);
426 /* skip volume control params */
427 for (i = 0; i < (hdr->channel_mode ? 1 : 2); i++) {
428 skip_bits(&gbc, 5); // skip dialog normalization
429 if (get_bits1(&gbc)) {
430 skip_bits(&gbc, 8); // skip compression gain word
433 /* get the dependent stream channel map, if exists */
435 info->substream[parent].chan_loc |= (get_bits(&gbc, 16) >> 5) & 0x1f;
437 info->substream[parent].chan_loc |= hdr->channel_mode;
438 cumul_size += hdr->frame_size;
444 if (!info->num_blocks && num_blocks == 6) {
448 else if (info->num_blocks + num_blocks > 6) {
449 ret = AVERROR_INVALIDDATA;
453 if (!info->num_blocks) {
454 ret = av_packet_ref(&info->pkt, pkt);
456 info->num_blocks = num_blocks;
459 if ((ret = av_grow_packet(&info->pkt, pkt->size)) < 0)
461 memcpy(info->pkt.data + info->pkt.size - pkt->size, pkt->data, pkt->size);
462 info->num_blocks += num_blocks;
463 info->pkt.duration += pkt->duration;
464 if ((ret = av_copy_packet_side_data(&info->pkt, pkt)) < 0)
466 if (info->num_blocks != 6)
468 av_packet_unref(pkt);
469 ret = av_packet_ref(pkt, &info->pkt);
472 av_packet_unref(&info->pkt);
473 info->num_blocks = 0;
484 static int mov_write_eac3_tag(AVIOContext *pb, MOVTrack *track)
488 struct eac3_info *info;
491 if (!track->eac3_priv)
492 return AVERROR(EINVAL);
494 info = track->eac3_priv;
495 size = 2 + 4 * (info->num_ind_sub + 1);
496 buf = av_malloc(size);
498 size = AVERROR(ENOMEM);
502 init_put_bits(&pbc, buf, size);
503 put_bits(&pbc, 13, info->data_rate);
504 put_bits(&pbc, 3, info->num_ind_sub);
505 for (i = 0; i <= info->num_ind_sub; i++) {
506 put_bits(&pbc, 2, info->substream[i].fscod);
507 put_bits(&pbc, 5, info->substream[i].bsid);
508 put_bits(&pbc, 1, 0); /* reserved */
509 put_bits(&pbc, 1, 0); /* asvc */
510 put_bits(&pbc, 3, info->substream[i].bsmod);
511 put_bits(&pbc, 3, info->substream[i].acmod);
512 put_bits(&pbc, 1, info->substream[i].lfeon);
513 put_bits(&pbc, 5, 0); /* reserved */
514 put_bits(&pbc, 4, info->substream[i].num_dep_sub);
515 if (!info->substream[i].num_dep_sub) {
516 put_bits(&pbc, 1, 0); /* reserved */
519 put_bits(&pbc, 9, info->substream[i].chan_loc);
522 flush_put_bits(&pbc);
524 avio_wb32(pb, size + 8);
525 ffio_wfourcc(pb, "dec3");
526 avio_write(pb, buf, size);
531 av_packet_unref(&info->pkt);
532 av_freep(&track->eac3_priv);
538 * This function writes extradata "as is".
539 * Extradata must be formatted like a valid atom (with size and tag).
541 static int mov_write_extradata_tag(AVIOContext *pb, MOVTrack *track)
543 avio_write(pb, track->par->extradata, track->par->extradata_size);
544 return track->par->extradata_size;
547 static int mov_write_enda_tag(AVIOContext *pb)
550 ffio_wfourcc(pb, "enda");
551 avio_wb16(pb, 1); /* little endian */
555 static int mov_write_enda_tag_be(AVIOContext *pb)
558 ffio_wfourcc(pb, "enda");
559 avio_wb16(pb, 0); /* big endian */
563 static void put_descr(AVIOContext *pb, int tag, unsigned int size)
568 avio_w8(pb, (size >> (7 * i)) | 0x80);
569 avio_w8(pb, size & 0x7F);
572 static unsigned compute_avg_bitrate(MOVTrack *track)
576 if (!track->track_duration)
578 for (i = 0; i < track->entry; i++)
579 size += track->cluster[i].size;
580 return size * 8 * track->timescale / track->track_duration;
583 static int mov_write_esds_tag(AVIOContext *pb, MOVTrack *track) // Basic
585 AVCPBProperties *props;
586 int64_t pos = avio_tell(pb);
587 int decoder_specific_info_len = track->vos_len ? 5 + track->vos_len : 0;
588 unsigned avg_bitrate;
590 avio_wb32(pb, 0); // size
591 ffio_wfourcc(pb, "esds");
592 avio_wb32(pb, 0); // Version
595 put_descr(pb, 0x03, 3 + 5+13 + decoder_specific_info_len + 5+1);
596 avio_wb16(pb, track->track_id);
597 avio_w8(pb, 0x00); // flags (= no flags)
599 // DecoderConfig descriptor
600 put_descr(pb, 0x04, 13 + decoder_specific_info_len);
602 // Object type indication
603 if ((track->par->codec_id == AV_CODEC_ID_MP2 ||
604 track->par->codec_id == AV_CODEC_ID_MP3) &&
605 track->par->sample_rate > 24000)
606 avio_w8(pb, 0x6B); // 11172-3
608 avio_w8(pb, ff_codec_get_tag(ff_mp4_obj_type, track->par->codec_id));
610 // the following fields is made of 6 bits to identify the streamtype (4 for video, 5 for audio)
611 // plus 1 bit to indicate upstream and 1 bit set to 1 (reserved)
612 if (track->par->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
613 avio_w8(pb, (0x38 << 2) | 1); // flags (= NeroSubpicStream)
614 else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
615 avio_w8(pb, 0x15); // flags (= Audiostream)
617 avio_w8(pb, 0x11); // flags (= Visualstream)
619 props = (AVCPBProperties*)av_stream_get_side_data(track->st, AV_PKT_DATA_CPB_PROPERTIES,
622 avio_wb24(pb, props ? props->buffer_size / 8 : 0); // Buffersize DB
624 avg_bitrate = compute_avg_bitrate(track);
625 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)
626 avio_wb32(pb, avg_bitrate);
628 if (track->vos_len) {
629 // DecoderSpecific info descriptor
630 put_descr(pb, 0x05, track->vos_len);
631 avio_write(pb, track->vos_data, track->vos_len);
635 put_descr(pb, 0x06, 1);
637 return update_size(pb, pos);
640 static int mov_pcm_le_gt16(enum AVCodecID codec_id)
642 return codec_id == AV_CODEC_ID_PCM_S24LE ||
643 codec_id == AV_CODEC_ID_PCM_S32LE ||
644 codec_id == AV_CODEC_ID_PCM_F32LE ||
645 codec_id == AV_CODEC_ID_PCM_F64LE;
648 static int mov_pcm_be_gt16(enum AVCodecID codec_id)
650 return codec_id == AV_CODEC_ID_PCM_S24BE ||
651 codec_id == AV_CODEC_ID_PCM_S32BE ||
652 codec_id == AV_CODEC_ID_PCM_F32BE ||
653 codec_id == AV_CODEC_ID_PCM_F64BE;
656 static int mov_write_ms_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
659 int64_t pos = avio_tell(pb);
661 avio_wl32(pb, track->tag); // store it byteswapped
662 track->par->codec_tag = av_bswap16(track->tag >> 16);
663 if ((ret = ff_put_wav_header(s, pb, track->par, 0)) < 0)
665 return update_size(pb, pos);
668 static int mov_write_wfex_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
671 int64_t pos = avio_tell(pb);
673 ffio_wfourcc(pb, "wfex");
674 if ((ret = ff_put_wav_header(s, pb, track->st->codecpar, FF_PUT_WAV_HEADER_FORCE_WAVEFORMATEX)) < 0)
676 return update_size(pb, pos);
679 static int mov_write_dfla_tag(AVIOContext *pb, MOVTrack *track)
681 int64_t pos = avio_tell(pb);
683 ffio_wfourcc(pb, "dfLa");
684 avio_w8(pb, 0); /* version */
685 avio_wb24(pb, 0); /* flags */
687 /* Expect the encoder to pass a METADATA_BLOCK_TYPE_STREAMINFO. */
688 if (track->par->extradata_size != FLAC_STREAMINFO_SIZE)
689 return AVERROR_INVALIDDATA;
691 /* TODO: Write other METADATA_BLOCK_TYPEs if the encoder makes them available. */
692 avio_w8(pb, 1 << 7 | FLAC_METADATA_TYPE_STREAMINFO); /* LastMetadataBlockFlag << 7 | BlockType */
693 avio_wb24(pb, track->par->extradata_size); /* Length */
694 avio_write(pb, track->par->extradata, track->par->extradata_size); /* BlockData[Length] */
696 return update_size(pb, pos);
699 static int mov_write_dops_tag(AVIOContext *pb, MOVTrack *track)
701 int64_t pos = avio_tell(pb);
703 ffio_wfourcc(pb, "dOps");
704 avio_w8(pb, 0); /* Version */
705 if (track->par->extradata_size < 19) {
706 av_log(pb, AV_LOG_ERROR, "invalid extradata size\n");
707 return AVERROR_INVALIDDATA;
709 /* extradata contains an Ogg OpusHead, other than byte-ordering and
710 OpusHead's preceeding magic/version, OpusSpecificBox is currently
712 avio_w8(pb, AV_RB8(track->par->extradata + 9)); /* OuputChannelCount */
713 avio_wb16(pb, AV_RL16(track->par->extradata + 10)); /* PreSkip */
714 avio_wb32(pb, AV_RL32(track->par->extradata + 12)); /* InputSampleRate */
715 avio_wb16(pb, AV_RL16(track->par->extradata + 16)); /* OutputGain */
716 /* Write the rest of the header out without byte-swapping. */
717 avio_write(pb, track->par->extradata + 18, track->par->extradata_size - 18);
719 return update_size(pb, pos);
722 static int mov_write_chan_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
724 uint32_t layout_tag, bitmap;
725 int64_t pos = avio_tell(pb);
727 layout_tag = ff_mov_get_channel_layout_tag(track->par->codec_id,
728 track->par->channel_layout,
731 av_log(s, AV_LOG_WARNING, "not writing 'chan' tag due to "
732 "lack of channel information\n");
736 if (track->multichannel_as_mono)
739 avio_wb32(pb, 0); // Size
740 ffio_wfourcc(pb, "chan"); // Type
741 avio_w8(pb, 0); // Version
742 avio_wb24(pb, 0); // Flags
743 avio_wb32(pb, layout_tag); // mChannelLayoutTag
744 avio_wb32(pb, bitmap); // mChannelBitmap
745 avio_wb32(pb, 0); // mNumberChannelDescriptions
747 return update_size(pb, pos);
750 static int mov_write_wave_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
752 int64_t pos = avio_tell(pb);
754 avio_wb32(pb, 0); /* size */
755 ffio_wfourcc(pb, "wave");
757 if (track->par->codec_id != AV_CODEC_ID_QDM2) {
758 avio_wb32(pb, 12); /* size */
759 ffio_wfourcc(pb, "frma");
760 avio_wl32(pb, track->tag);
763 if (track->par->codec_id == AV_CODEC_ID_AAC) {
764 /* useless atom needed by mplayer, ipod, not needed by quicktime */
765 avio_wb32(pb, 12); /* size */
766 ffio_wfourcc(pb, "mp4a");
768 mov_write_esds_tag(pb, track);
769 } else if (mov_pcm_le_gt16(track->par->codec_id)) {
770 mov_write_enda_tag(pb);
771 } else if (mov_pcm_be_gt16(track->par->codec_id)) {
772 mov_write_enda_tag_be(pb);
773 } else if (track->par->codec_id == AV_CODEC_ID_AMR_NB) {
774 mov_write_amr_tag(pb, track);
775 } else if (track->par->codec_id == AV_CODEC_ID_AC3) {
776 mov_write_ac3_tag(pb, track);
777 } else if (track->par->codec_id == AV_CODEC_ID_EAC3) {
778 mov_write_eac3_tag(pb, track);
779 } else if (track->par->codec_id == AV_CODEC_ID_ALAC ||
780 track->par->codec_id == AV_CODEC_ID_QDM2) {
781 mov_write_extradata_tag(pb, track);
782 } else if (track->par->codec_id == AV_CODEC_ID_ADPCM_MS ||
783 track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) {
784 mov_write_ms_tag(s, pb, track);
787 avio_wb32(pb, 8); /* size */
788 avio_wb32(pb, 0); /* null tag */
790 return update_size(pb, pos);
793 static int mov_write_dvc1_structs(MOVTrack *track, uint8_t *buf)
796 const uint8_t *start, *next, *end = track->vos_data + track->vos_len;
797 int unescaped_size, seq_found = 0;
798 int level = 0, interlace = 0;
799 int packet_seq = track->vc1_info.packet_seq;
800 int packet_entry = track->vc1_info.packet_entry;
801 int slices = track->vc1_info.slices;
804 if (track->start_dts == AV_NOPTS_VALUE) {
805 /* No packets written yet, vc1_info isn't authoritative yet. */
806 /* Assume inline sequence and entry headers. */
807 packet_seq = packet_entry = 1;
808 av_log(NULL, AV_LOG_WARNING,
809 "moov atom written before any packets, unable to write correct "
810 "dvc1 atom. Set the delay_moov flag to fix this.\n");
813 unescaped = av_mallocz(track->vos_len + AV_INPUT_BUFFER_PADDING_SIZE);
815 return AVERROR(ENOMEM);
816 start = find_next_marker(track->vos_data, end);
817 for (next = start; next < end; start = next) {
820 next = find_next_marker(start + 4, end);
821 size = next - start - 4;
824 unescaped_size = vc1_unescape_buffer(start + 4, size, unescaped);
825 init_get_bits(&gb, unescaped, 8 * unescaped_size);
826 if (AV_RB32(start) == VC1_CODE_SEQHDR) {
827 int profile = get_bits(&gb, 2);
828 if (profile != PROFILE_ADVANCED) {
830 return AVERROR(ENOSYS);
833 level = get_bits(&gb, 3);
834 /* chromaformat, frmrtq_postproc, bitrtq_postproc, postprocflag,
836 skip_bits_long(&gb, 2 + 3 + 5 + 1 + 2*12);
837 skip_bits(&gb, 1); /* broadcast */
838 interlace = get_bits1(&gb);
839 skip_bits(&gb, 4); /* tfcntrflag, finterpflag, reserved, psf */
844 return AVERROR(ENOSYS);
847 init_put_bits(&pbc, buf, 7);
848 /* VC1DecSpecStruc */
849 put_bits(&pbc, 4, 12); /* profile - advanced */
850 put_bits(&pbc, 3, level);
851 put_bits(&pbc, 1, 0); /* reserved */
852 /* VC1AdvDecSpecStruc */
853 put_bits(&pbc, 3, level);
854 put_bits(&pbc, 1, 0); /* cbr */
855 put_bits(&pbc, 6, 0); /* reserved */
856 put_bits(&pbc, 1, !interlace); /* no interlace */
857 put_bits(&pbc, 1, !packet_seq); /* no multiple seq */
858 put_bits(&pbc, 1, !packet_entry); /* no multiple entry */
859 put_bits(&pbc, 1, !slices); /* no slice code */
860 put_bits(&pbc, 1, 0); /* no bframe */
861 put_bits(&pbc, 1, 0); /* reserved */
864 if (track->st->avg_frame_rate.num > 0 && track->st->avg_frame_rate.den > 0)
865 put_bits32(&pbc, track->st->avg_frame_rate.num / track->st->avg_frame_rate.den);
867 put_bits32(&pbc, 0xffffffff);
869 flush_put_bits(&pbc);
876 static int mov_write_dvc1_tag(AVIOContext *pb, MOVTrack *track)
878 uint8_t buf[7] = { 0 };
881 if ((ret = mov_write_dvc1_structs(track, buf)) < 0)
884 avio_wb32(pb, track->vos_len + 8 + sizeof(buf));
885 ffio_wfourcc(pb, "dvc1");
886 avio_write(pb, buf, sizeof(buf));
887 avio_write(pb, track->vos_data, track->vos_len);
892 static int mov_write_glbl_tag(AVIOContext *pb, MOVTrack *track)
894 avio_wb32(pb, track->vos_len + 8);
895 ffio_wfourcc(pb, "glbl");
896 avio_write(pb, track->vos_data, track->vos_len);
897 return 8 + track->vos_len;
901 * Compute flags for 'lpcm' tag.
902 * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
904 static int mov_get_lpcm_flags(enum AVCodecID codec_id)
907 case AV_CODEC_ID_PCM_F32BE:
908 case AV_CODEC_ID_PCM_F64BE:
910 case AV_CODEC_ID_PCM_F32LE:
911 case AV_CODEC_ID_PCM_F64LE:
913 case AV_CODEC_ID_PCM_U8:
915 case AV_CODEC_ID_PCM_S16BE:
916 case AV_CODEC_ID_PCM_S24BE:
917 case AV_CODEC_ID_PCM_S32BE:
919 case AV_CODEC_ID_PCM_S8:
920 case AV_CODEC_ID_PCM_S16LE:
921 case AV_CODEC_ID_PCM_S24LE:
922 case AV_CODEC_ID_PCM_S32LE:
929 static int get_cluster_duration(MOVTrack *track, int cluster_idx)
933 if (cluster_idx >= track->entry)
936 if (cluster_idx + 1 == track->entry)
937 next_dts = track->track_duration + track->start_dts;
939 next_dts = track->cluster[cluster_idx + 1].dts;
941 next_dts -= track->cluster[cluster_idx].dts;
943 av_assert0(next_dts >= 0);
944 av_assert0(next_dts <= INT_MAX);
949 static int get_samples_per_packet(MOVTrack *track)
951 int i, first_duration;
953 // return track->par->frame_size;
955 /* use 1 for raw PCM */
956 if (!track->audio_vbr)
959 /* check to see if duration is constant for all clusters */
962 first_duration = get_cluster_duration(track, 0);
963 for (i = 1; i < track->entry; i++) {
964 if (get_cluster_duration(track, i) != first_duration)
967 return first_duration;
970 static int mov_write_audio_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
972 int64_t pos = avio_tell(pb);
974 uint32_t tag = track->tag;
976 if (track->mode == MODE_MOV) {
977 if (track->timescale > UINT16_MAX) {
978 if (mov_get_lpcm_flags(track->par->codec_id))
979 tag = AV_RL32("lpcm");
981 } else if (track->audio_vbr || mov_pcm_le_gt16(track->par->codec_id) ||
982 mov_pcm_be_gt16(track->par->codec_id) ||
983 track->par->codec_id == AV_CODEC_ID_ADPCM_MS ||
984 track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
985 track->par->codec_id == AV_CODEC_ID_QDM2) {
990 avio_wb32(pb, 0); /* size */
991 if (mov->encryption_scheme != MOV_ENC_NONE) {
992 ffio_wfourcc(pb, "enca");
994 avio_wl32(pb, tag); // store it byteswapped
996 avio_wb32(pb, 0); /* Reserved */
997 avio_wb16(pb, 0); /* Reserved */
998 avio_wb16(pb, 1); /* Data-reference index, XXX == 1 */
1000 /* SoundDescription */
1001 avio_wb16(pb, version); /* Version */
1002 avio_wb16(pb, 0); /* Revision level */
1003 avio_wb32(pb, 0); /* Reserved */
1008 avio_wb16(pb, 0xfffe);
1010 avio_wb32(pb, 0x00010000);
1012 avio_wb64(pb, av_double2int(track->par->sample_rate));
1013 avio_wb32(pb, track->par->channels);
1014 avio_wb32(pb, 0x7F000000);
1015 avio_wb32(pb, av_get_bits_per_sample(track->par->codec_id));
1016 avio_wb32(pb, mov_get_lpcm_flags(track->par->codec_id));
1017 avio_wb32(pb, track->sample_size);
1018 avio_wb32(pb, get_samples_per_packet(track));
1020 if (track->mode == MODE_MOV) {
1021 avio_wb16(pb, track->par->channels);
1022 if (track->par->codec_id == AV_CODEC_ID_PCM_U8 ||
1023 track->par->codec_id == AV_CODEC_ID_PCM_S8)
1024 avio_wb16(pb, 8); /* bits per sample */
1025 else if (track->par->codec_id == AV_CODEC_ID_ADPCM_G726)
1026 avio_wb16(pb, track->par->bits_per_coded_sample);
1029 avio_wb16(pb, track->audio_vbr ? -2 : 0); /* compression ID */
1030 } else { /* reserved for mp4/3gp */
1031 if (track->par->codec_id == AV_CODEC_ID_FLAC ||
1032 track->par->codec_id == AV_CODEC_ID_OPUS) {
1033 avio_wb16(pb, track->par->channels);
1037 if (track->par->codec_id == AV_CODEC_ID_FLAC) {
1038 avio_wb16(pb, track->par->bits_per_raw_sample);
1045 avio_wb16(pb, 0); /* packet size (= 0) */
1046 if (track->par->codec_id == AV_CODEC_ID_OPUS)
1047 avio_wb16(pb, 48000);
1049 avio_wb16(pb, track->par->sample_rate <= UINT16_MAX ?
1050 track->par->sample_rate : 0);
1051 avio_wb16(pb, 0); /* Reserved */
1054 if (version == 1) { /* SoundDescription V1 extended info */
1055 if (mov_pcm_le_gt16(track->par->codec_id) ||
1056 mov_pcm_be_gt16(track->par->codec_id))
1057 avio_wb32(pb, 1); /* must be 1 for uncompressed formats */
1059 avio_wb32(pb, track->par->frame_size); /* Samples per packet */
1060 avio_wb32(pb, track->sample_size / track->par->channels); /* Bytes per packet */
1061 avio_wb32(pb, track->sample_size); /* Bytes per frame */
1062 avio_wb32(pb, 2); /* Bytes per sample */
1065 if (track->mode == MODE_MOV &&
1066 (track->par->codec_id == AV_CODEC_ID_AAC ||
1067 track->par->codec_id == AV_CODEC_ID_AC3 ||
1068 track->par->codec_id == AV_CODEC_ID_EAC3 ||
1069 track->par->codec_id == AV_CODEC_ID_AMR_NB ||
1070 track->par->codec_id == AV_CODEC_ID_ALAC ||
1071 track->par->codec_id == AV_CODEC_ID_ADPCM_MS ||
1072 track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
1073 track->par->codec_id == AV_CODEC_ID_QDM2 ||
1074 (mov_pcm_le_gt16(track->par->codec_id) && version==1) ||
1075 (mov_pcm_be_gt16(track->par->codec_id) && version==1)))
1076 mov_write_wave_tag(s, pb, track);
1077 else if (track->tag == MKTAG('m','p','4','a'))
1078 mov_write_esds_tag(pb, track);
1079 else if (track->par->codec_id == AV_CODEC_ID_AMR_NB)
1080 mov_write_amr_tag(pb, track);
1081 else if (track->par->codec_id == AV_CODEC_ID_AC3)
1082 mov_write_ac3_tag(pb, track);
1083 else if (track->par->codec_id == AV_CODEC_ID_EAC3)
1084 mov_write_eac3_tag(pb, track);
1085 else if (track->par->codec_id == AV_CODEC_ID_ALAC)
1086 mov_write_extradata_tag(pb, track);
1087 else if (track->par->codec_id == AV_CODEC_ID_WMAPRO)
1088 mov_write_wfex_tag(s, pb, track);
1089 else if (track->par->codec_id == AV_CODEC_ID_FLAC)
1090 mov_write_dfla_tag(pb, track);
1091 else if (track->par->codec_id == AV_CODEC_ID_OPUS)
1092 mov_write_dops_tag(pb, track);
1093 else if (track->vos_len > 0)
1094 mov_write_glbl_tag(pb, track);
1096 if (track->mode == MODE_MOV && track->par->codec_type == AVMEDIA_TYPE_AUDIO)
1097 mov_write_chan_tag(s, pb, track);
1099 if (mov->encryption_scheme != MOV_ENC_NONE) {
1100 ff_mov_cenc_write_sinf_tag(track, pb, mov->encryption_kid);
1103 return update_size(pb, pos);
1106 static int mov_write_d263_tag(AVIOContext *pb)
1108 avio_wb32(pb, 0xf); /* size */
1109 ffio_wfourcc(pb, "d263");
1110 ffio_wfourcc(pb, "FFMP");
1111 avio_w8(pb, 0); /* decoder version */
1112 /* FIXME use AVCodecContext level/profile, when encoder will set values */
1113 avio_w8(pb, 0xa); /* level */
1114 avio_w8(pb, 0); /* profile */
1118 static int mov_write_avcc_tag(AVIOContext *pb, MOVTrack *track)
1120 int64_t pos = avio_tell(pb);
1123 ffio_wfourcc(pb, "avcC");
1124 ff_isom_write_avcc(pb, track->vos_data, track->vos_len);
1125 return update_size(pb, pos);
1128 static int mov_write_vpcc_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
1130 int64_t pos = avio_tell(pb);
1133 ffio_wfourcc(pb, "vpcC");
1134 avio_w8(pb, 1); /* version */
1135 avio_wb24(pb, 0); /* flags */
1136 ff_isom_write_vpcc(s, pb, track->par);
1137 return update_size(pb, pos);
1140 static int mov_write_hvcc_tag(AVIOContext *pb, MOVTrack *track)
1142 int64_t pos = avio_tell(pb);
1145 ffio_wfourcc(pb, "hvcC");
1146 if (track->tag == MKTAG('h','v','c','1'))
1147 ff_isom_write_hvcc(pb, track->vos_data, track->vos_len, 1);
1149 ff_isom_write_hvcc(pb, track->vos_data, track->vos_len, 0);
1150 return update_size(pb, pos);
1153 /* also used by all avid codecs (dv, imx, meridien) and their variants */
1154 static int mov_write_avid_tag(AVIOContext *pb, MOVTrack *track)
1159 int display_width = track->par->width;
1161 if (track->vos_data && track->vos_len > 0x29) {
1162 if (ff_dnxhd_parse_header_prefix(track->vos_data) != 0) {
1163 /* looks like a DNxHD bit stream */
1164 interlaced = (track->vos_data[5] & 2);
1165 cid = AV_RB32(track->vos_data + 0x28);
1167 av_log(NULL, AV_LOG_WARNING, "Could not locate DNxHD bit stream in vos_data\n");
1171 av_log(NULL, AV_LOG_WARNING, "Could not locate DNxHD bit stream, vos_data too small\n");
1175 avio_wb32(pb, 24); /* size */
1176 ffio_wfourcc(pb, "ACLR");
1177 ffio_wfourcc(pb, "ACLR");
1178 ffio_wfourcc(pb, "0001");
1179 if (track->par->color_range == AVCOL_RANGE_MPEG || /* Legal range (16-235) */
1180 track->par->color_range == AVCOL_RANGE_UNSPECIFIED) {
1181 avio_wb32(pb, 1); /* Corresponds to 709 in official encoder */
1182 } else { /* Full range (0-255) */
1183 avio_wb32(pb, 2); /* Corresponds to RGB in official encoder */
1185 avio_wb32(pb, 0); /* unknown */
1187 if (track->tag == MKTAG('A','V','d','h')) {
1189 ffio_wfourcc(pb, "ADHR");
1190 ffio_wfourcc(pb, "0001");
1192 avio_wb32(pb, 0); /* unknown */
1193 avio_wb32(pb, 1); /* unknown */
1194 avio_wb32(pb, 0); /* unknown */
1195 avio_wb32(pb, 0); /* unknown */
1199 avio_wb32(pb, 24); /* size */
1200 ffio_wfourcc(pb, "APRG");
1201 ffio_wfourcc(pb, "APRG");
1202 ffio_wfourcc(pb, "0001");
1203 avio_wb32(pb, 1); /* unknown */
1204 avio_wb32(pb, 0); /* unknown */
1206 avio_wb32(pb, 120); /* size */
1207 ffio_wfourcc(pb, "ARES");
1208 ffio_wfourcc(pb, "ARES");
1209 ffio_wfourcc(pb, "0001");
1210 avio_wb32(pb, cid); /* dnxhd cid, some id ? */
1211 if ( track->par->sample_aspect_ratio.num > 0
1212 && track->par->sample_aspect_ratio.den > 0)
1213 display_width = display_width * track->par->sample_aspect_ratio.num / track->par->sample_aspect_ratio.den;
1214 avio_wb32(pb, display_width);
1215 /* values below are based on samples created with quicktime and avid codecs */
1217 avio_wb32(pb, track->par->height / 2);
1218 avio_wb32(pb, 2); /* unknown */
1219 avio_wb32(pb, 0); /* unknown */
1220 avio_wb32(pb, 4); /* unknown */
1222 avio_wb32(pb, track->par->height);
1223 avio_wb32(pb, 1); /* unknown */
1224 avio_wb32(pb, 0); /* unknown */
1225 if (track->par->height == 1080)
1226 avio_wb32(pb, 5); /* unknown */
1228 avio_wb32(pb, 6); /* unknown */
1231 for (i = 0; i < 10; i++)
1237 static int mov_write_dpxe_tag(AVIOContext *pb, MOVTrack *track)
1240 ffio_wfourcc(pb, "DpxE");
1241 if (track->par->extradata_size >= 12 &&
1242 !memcmp(&track->par->extradata[4], "DpxE", 4)) {
1243 avio_wb32(pb, track->par->extradata[11]);
1250 static int mov_get_dv_codec_tag(AVFormatContext *s, MOVTrack *track)
1254 if (track->par->width == 720) { /* SD */
1255 if (track->par->height == 480) { /* NTSC */
1256 if (track->par->format == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','n');
1257 else tag = MKTAG('d','v','c',' ');
1258 }else if (track->par->format == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','p');
1259 else if (track->par->format == AV_PIX_FMT_YUV420P) tag = MKTAG('d','v','c','p');
1260 else tag = MKTAG('d','v','p','p');
1261 } else if (track->par->height == 720) { /* HD 720 line */
1262 if (track->st->time_base.den == 50) tag = MKTAG('d','v','h','q');
1263 else tag = MKTAG('d','v','h','p');
1264 } else if (track->par->height == 1080) { /* HD 1080 line */
1265 if (track->st->time_base.den == 25) tag = MKTAG('d','v','h','5');
1266 else tag = MKTAG('d','v','h','6');
1268 av_log(s, AV_LOG_ERROR, "unsupported height for dv codec\n");
1275 static AVRational find_fps(AVFormatContext *s, AVStream *st)
1277 AVRational rate = st->avg_frame_rate;
1279 #if FF_API_LAVF_AVCTX
1280 FF_DISABLE_DEPRECATION_WARNINGS
1281 rate = av_inv_q(st->codec->time_base);
1282 if (av_timecode_check_frame_rate(rate) < 0) {
1283 av_log(s, AV_LOG_DEBUG, "timecode: tbc=%d/%d invalid, fallback on %d/%d\n",
1284 rate.num, rate.den, st->avg_frame_rate.num, st->avg_frame_rate.den);
1285 rate = st->avg_frame_rate;
1287 FF_ENABLE_DEPRECATION_WARNINGS
1293 static int defined_frame_rate(AVFormatContext *s, AVStream *st)
1295 AVRational rational_framerate = find_fps(s, st);
1297 if (rational_framerate.den != 0)
1298 rate = av_q2d(rational_framerate);
1302 static int mov_get_mpeg2_xdcam_codec_tag(AVFormatContext *s, MOVTrack *track)
1304 int tag = track->par->codec_tag;
1305 int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE;
1306 AVStream *st = track->st;
1307 int rate = defined_frame_rate(s, st);
1310 tag = MKTAG('m', '2', 'v', '1'); //fallback tag
1312 if (track->par->format == AV_PIX_FMT_YUV420P) {
1313 if (track->par->width == 1280 && track->par->height == 720) {
1315 if (rate == 24) tag = MKTAG('x','d','v','4');
1316 else if (rate == 25) tag = MKTAG('x','d','v','5');
1317 else if (rate == 30) tag = MKTAG('x','d','v','1');
1318 else if (rate == 50) tag = MKTAG('x','d','v','a');
1319 else if (rate == 60) tag = MKTAG('x','d','v','9');
1321 } else if (track->par->width == 1440 && track->par->height == 1080) {
1323 if (rate == 24) tag = MKTAG('x','d','v','6');
1324 else if (rate == 25) tag = MKTAG('x','d','v','7');
1325 else if (rate == 30) tag = MKTAG('x','d','v','8');
1327 if (rate == 25) tag = MKTAG('x','d','v','3');
1328 else if (rate == 30) tag = MKTAG('x','d','v','2');
1330 } else if (track->par->width == 1920 && track->par->height == 1080) {
1332 if (rate == 24) tag = MKTAG('x','d','v','d');
1333 else if (rate == 25) tag = MKTAG('x','d','v','e');
1334 else if (rate == 30) tag = MKTAG('x','d','v','f');
1336 if (rate == 25) tag = MKTAG('x','d','v','c');
1337 else if (rate == 30) tag = MKTAG('x','d','v','b');
1340 } else if (track->par->format == AV_PIX_FMT_YUV422P) {
1341 if (track->par->width == 1280 && track->par->height == 720) {
1343 if (rate == 24) tag = MKTAG('x','d','5','4');
1344 else if (rate == 25) tag = MKTAG('x','d','5','5');
1345 else if (rate == 30) tag = MKTAG('x','d','5','1');
1346 else if (rate == 50) tag = MKTAG('x','d','5','a');
1347 else if (rate == 60) tag = MKTAG('x','d','5','9');
1349 } else if (track->par->width == 1920 && track->par->height == 1080) {
1351 if (rate == 24) tag = MKTAG('x','d','5','d');
1352 else if (rate == 25) tag = MKTAG('x','d','5','e');
1353 else if (rate == 30) tag = MKTAG('x','d','5','f');
1355 if (rate == 25) tag = MKTAG('x','d','5','c');
1356 else if (rate == 30) tag = MKTAG('x','d','5','b');
1364 static int mov_get_h264_codec_tag(AVFormatContext *s, MOVTrack *track)
1366 int tag = track->par->codec_tag;
1367 int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE;
1368 AVStream *st = track->st;
1369 int rate = defined_frame_rate(s, st);
1372 tag = MKTAG('a', 'v', 'c', 'i'); //fallback tag
1374 if (track->par->format == AV_PIX_FMT_YUV420P10) {
1375 if (track->par->width == 960 && track->par->height == 720) {
1377 if (rate == 24) tag = MKTAG('a','i','5','p');
1378 else if (rate == 25) tag = MKTAG('a','i','5','q');
1379 else if (rate == 30) tag = MKTAG('a','i','5','p');
1380 else if (rate == 50) tag = MKTAG('a','i','5','q');
1381 else if (rate == 60) tag = MKTAG('a','i','5','p');
1383 } else if (track->par->width == 1440 && track->par->height == 1080) {
1385 if (rate == 24) tag = MKTAG('a','i','5','3');
1386 else if (rate == 25) tag = MKTAG('a','i','5','2');
1387 else if (rate == 30) tag = MKTAG('a','i','5','3');
1389 if (rate == 50) tag = MKTAG('a','i','5','5');
1390 else if (rate == 60) tag = MKTAG('a','i','5','6');
1393 } else if (track->par->format == AV_PIX_FMT_YUV422P10) {
1394 if (track->par->width == 1280 && track->par->height == 720) {
1396 if (rate == 24) tag = MKTAG('a','i','1','p');
1397 else if (rate == 25) tag = MKTAG('a','i','1','q');
1398 else if (rate == 30) tag = MKTAG('a','i','1','p');
1399 else if (rate == 50) tag = MKTAG('a','i','1','q');
1400 else if (rate == 60) tag = MKTAG('a','i','1','p');
1402 } else if (track->par->width == 1920 && track->par->height == 1080) {
1404 if (rate == 24) tag = MKTAG('a','i','1','3');
1405 else if (rate == 25) tag = MKTAG('a','i','1','2');
1406 else if (rate == 30) tag = MKTAG('a','i','1','3');
1408 if (rate == 25) tag = MKTAG('a','i','1','5');
1409 else if (rate == 50) tag = MKTAG('a','i','1','5');
1410 else if (rate == 60) tag = MKTAG('a','i','1','6');
1412 } else if ( track->par->width == 4096 && track->par->height == 2160
1413 || track->par->width == 3840 && track->par->height == 2160
1414 || track->par->width == 2048 && track->par->height == 1080) {
1415 tag = MKTAG('a','i','v','x');
1422 static const struct {
1423 enum AVPixelFormat pix_fmt;
1426 } mov_pix_fmt_tags[] = {
1427 { AV_PIX_FMT_YUYV422, MKTAG('y','u','v','2'), 0 },
1428 { AV_PIX_FMT_YUYV422, MKTAG('y','u','v','s'), 0 },
1429 { AV_PIX_FMT_UYVY422, MKTAG('2','v','u','y'), 0 },
1430 { AV_PIX_FMT_RGB555BE,MKTAG('r','a','w',' '), 16 },
1431 { AV_PIX_FMT_RGB555LE,MKTAG('L','5','5','5'), 16 },
1432 { AV_PIX_FMT_RGB565LE,MKTAG('L','5','6','5'), 16 },
1433 { AV_PIX_FMT_RGB565BE,MKTAG('B','5','6','5'), 16 },
1434 { AV_PIX_FMT_GRAY16BE,MKTAG('b','1','6','g'), 16 },
1435 { AV_PIX_FMT_RGB24, MKTAG('r','a','w',' '), 24 },
1436 { AV_PIX_FMT_BGR24, MKTAG('2','4','B','G'), 24 },
1437 { AV_PIX_FMT_ARGB, MKTAG('r','a','w',' '), 32 },
1438 { AV_PIX_FMT_BGRA, MKTAG('B','G','R','A'), 32 },
1439 { AV_PIX_FMT_RGBA, MKTAG('R','G','B','A'), 32 },
1440 { AV_PIX_FMT_ABGR, MKTAG('A','B','G','R'), 32 },
1441 { AV_PIX_FMT_RGB48BE, MKTAG('b','4','8','r'), 48 },
1444 static int mov_get_dnxhd_codec_tag(AVFormatContext *s, MOVTrack *track)
1446 int tag = MKTAG('A','V','d','n');
1447 if (track->par->profile != FF_PROFILE_UNKNOWN &&
1448 track->par->profile != FF_PROFILE_DNXHD)
1449 tag = MKTAG('A','V','d','h');
1453 static int mov_get_rawvideo_codec_tag(AVFormatContext *s, MOVTrack *track)
1455 int tag = track->par->codec_tag;
1457 enum AVPixelFormat pix_fmt;
1459 for (i = 0; i < FF_ARRAY_ELEMS(mov_pix_fmt_tags); i++) {
1460 if (track->par->format == mov_pix_fmt_tags[i].pix_fmt) {
1461 tag = mov_pix_fmt_tags[i].tag;
1462 track->par->bits_per_coded_sample = mov_pix_fmt_tags[i].bps;
1463 if (track->par->codec_tag == mov_pix_fmt_tags[i].tag)
1468 pix_fmt = avpriv_find_pix_fmt(avpriv_pix_fmt_bps_mov,
1469 track->par->bits_per_coded_sample);
1470 if (tag == MKTAG('r','a','w',' ') &&
1471 track->par->format != pix_fmt &&
1472 track->par->format != AV_PIX_FMT_GRAY8 &&
1473 track->par->format != AV_PIX_FMT_NONE)
1474 av_log(s, AV_LOG_ERROR, "%s rawvideo cannot be written to mov, output file will be unreadable\n",
1475 av_get_pix_fmt_name(track->par->format));
1479 static int mov_get_codec_tag(AVFormatContext *s, MOVTrack *track)
1481 int tag = track->par->codec_tag;
1483 if (!tag || (s->strict_std_compliance >= FF_COMPLIANCE_NORMAL &&
1484 (track->par->codec_id == AV_CODEC_ID_DVVIDEO ||
1485 track->par->codec_id == AV_CODEC_ID_RAWVIDEO ||
1486 track->par->codec_id == AV_CODEC_ID_H263 ||
1487 track->par->codec_id == AV_CODEC_ID_H264 ||
1488 track->par->codec_id == AV_CODEC_ID_DNXHD ||
1489 track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO ||
1490 av_get_bits_per_sample(track->par->codec_id)))) { // pcm audio
1491 if (track->par->codec_id == AV_CODEC_ID_DVVIDEO)
1492 tag = mov_get_dv_codec_tag(s, track);
1493 else if (track->par->codec_id == AV_CODEC_ID_RAWVIDEO)
1494 tag = mov_get_rawvideo_codec_tag(s, track);
1495 else if (track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO)
1496 tag = mov_get_mpeg2_xdcam_codec_tag(s, track);
1497 else if (track->par->codec_id == AV_CODEC_ID_H264)
1498 tag = mov_get_h264_codec_tag(s, track);
1499 else if (track->par->codec_id == AV_CODEC_ID_DNXHD)
1500 tag = mov_get_dnxhd_codec_tag(s, track);
1501 else if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
1502 tag = ff_codec_get_tag(ff_codec_movvideo_tags, track->par->codec_id);
1503 if (!tag) { // if no mac fcc found, try with Microsoft tags
1504 tag = ff_codec_get_tag(ff_codec_bmp_tags, track->par->codec_id);
1506 av_log(s, AV_LOG_WARNING, "Using MS style video codec tag, "
1507 "the file may be unplayable!\n");
1509 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
1510 tag = ff_codec_get_tag(ff_codec_movaudio_tags, track->par->codec_id);
1511 if (!tag) { // if no mac fcc found, try with Microsoft tags
1512 int ms_tag = ff_codec_get_tag(ff_codec_wav_tags, track->par->codec_id);
1514 tag = MKTAG('m', 's', ((ms_tag >> 8) & 0xff), (ms_tag & 0xff));
1515 av_log(s, AV_LOG_WARNING, "Using MS style audio codec tag, "
1516 "the file may be unplayable!\n");
1519 } else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)
1520 tag = ff_codec_get_tag(ff_codec_movsubtitle_tags, track->par->codec_id);
1526 static int mov_find_codec_tag(AVFormatContext *s, MOVTrack *track)
1530 if (track->mode == MODE_MP4 || track->mode == MODE_PSP)
1531 tag = track->par->codec_tag;
1532 else if (track->mode == MODE_ISM)
1533 tag = track->par->codec_tag;
1534 else if (track->mode == MODE_IPOD) {
1535 if (!av_match_ext(s->filename, "m4a") &&
1536 !av_match_ext(s->filename, "m4v") &&
1537 !av_match_ext(s->filename, "m4b"))
1538 av_log(s, AV_LOG_WARNING, "Warning, extension is not .m4a nor .m4v "
1539 "Quicktime/Ipod might not play the file\n");
1540 tag = track->par->codec_tag;
1541 } else if (track->mode & MODE_3GP)
1542 tag = track->par->codec_tag;
1543 else if (track->mode == MODE_F4V)
1544 tag = track->par->codec_tag;
1546 tag = mov_get_codec_tag(s, track);
1551 /** Write uuid atom.
1552 * Needed to make file play in iPods running newest firmware
1553 * goes after avcC atom in moov.trak.mdia.minf.stbl.stsd.avc1
1555 static int mov_write_uuid_tag_ipod(AVIOContext *pb)
1558 ffio_wfourcc(pb, "uuid");
1559 avio_wb32(pb, 0x6b6840f2);
1560 avio_wb32(pb, 0x5f244fc5);
1561 avio_wb32(pb, 0xba39a51b);
1562 avio_wb32(pb, 0xcf0323f3);
1567 static const uint16_t fiel_data[] = {
1568 0x0000, 0x0100, 0x0201, 0x0206, 0x0209, 0x020e
1571 static int mov_write_fiel_tag(AVIOContext *pb, MOVTrack *track, int field_order)
1573 unsigned mov_field_order = 0;
1574 if (field_order < FF_ARRAY_ELEMS(fiel_data))
1575 mov_field_order = fiel_data[field_order];
1579 ffio_wfourcc(pb, "fiel");
1580 avio_wb16(pb, mov_field_order);
1584 static int mov_write_subtitle_tag(AVIOContext *pb, MOVTrack *track)
1586 int64_t pos = avio_tell(pb);
1587 avio_wb32(pb, 0); /* size */
1588 avio_wl32(pb, track->tag); // store it byteswapped
1589 avio_wb32(pb, 0); /* Reserved */
1590 avio_wb16(pb, 0); /* Reserved */
1591 avio_wb16(pb, 1); /* Data-reference index */
1593 if (track->par->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
1594 mov_write_esds_tag(pb, track);
1595 else if (track->par->extradata_size)
1596 avio_write(pb, track->par->extradata, track->par->extradata_size);
1598 return update_size(pb, pos);
1601 static int mov_write_st3d_tag(AVIOContext *pb, AVStereo3D *stereo_3d)
1605 if (stereo_3d->flags != 0) {
1606 av_log(pb, AV_LOG_WARNING, "Unsupported stereo_3d flags %x. st3d not written.\n", stereo_3d->flags);
1610 switch (stereo_3d->type) {
1611 case AV_STEREO3D_2D:
1614 case AV_STEREO3D_TOPBOTTOM:
1617 case AV_STEREO3D_SIDEBYSIDE:
1621 av_log(pb, AV_LOG_WARNING, "Unsupported stereo_3d type %s. st3d not written.\n", av_stereo3d_type_name(stereo_3d->type));
1624 avio_wb32(pb, 13); /* size */
1625 ffio_wfourcc(pb, "st3d");
1626 avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1627 avio_w8(pb, stereo_mode);
1631 static int mov_write_sv3d_tag(AVFormatContext *s, AVIOContext *pb, AVSphericalMapping *spherical_mapping)
1633 int64_t sv3d_pos, svhd_pos, proj_pos;
1634 const char* metadata_source = s->flags & AVFMT_FLAG_BITEXACT ? "Lavf" : LIBAVFORMAT_IDENT;
1636 if (spherical_mapping->projection != AV_SPHERICAL_EQUIRECTANGULAR &&
1637 spherical_mapping->projection != AV_SPHERICAL_EQUIRECTANGULAR_TILE &&
1638 spherical_mapping->projection != AV_SPHERICAL_CUBEMAP) {
1639 av_log(pb, AV_LOG_WARNING, "Unsupported projection %d. sv3d not written.\n", spherical_mapping->projection);
1643 sv3d_pos = avio_tell(pb);
1644 avio_wb32(pb, 0); /* size */
1645 ffio_wfourcc(pb, "sv3d");
1647 svhd_pos = avio_tell(pb);
1648 avio_wb32(pb, 0); /* size */
1649 ffio_wfourcc(pb, "svhd");
1650 avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1651 avio_put_str(pb, metadata_source);
1652 update_size(pb, svhd_pos);
1654 proj_pos = avio_tell(pb);
1655 avio_wb32(pb, 0); /* size */
1656 ffio_wfourcc(pb, "proj");
1658 avio_wb32(pb, 24); /* size */
1659 ffio_wfourcc(pb, "prhd");
1660 avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1661 avio_wb32(pb, spherical_mapping->yaw);
1662 avio_wb32(pb, spherical_mapping->pitch);
1663 avio_wb32(pb, spherical_mapping->roll);
1665 switch (spherical_mapping->projection) {
1666 case AV_SPHERICAL_EQUIRECTANGULAR:
1667 case AV_SPHERICAL_EQUIRECTANGULAR_TILE:
1668 avio_wb32(pb, 28); /* size */
1669 ffio_wfourcc(pb, "equi");
1670 avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1671 avio_wb32(pb, spherical_mapping->bound_top);
1672 avio_wb32(pb, spherical_mapping->bound_bottom);
1673 avio_wb32(pb, spherical_mapping->bound_left);
1674 avio_wb32(pb, spherical_mapping->bound_right);
1676 case AV_SPHERICAL_CUBEMAP:
1677 avio_wb32(pb, 20); /* size */
1678 ffio_wfourcc(pb, "cbmp");
1679 avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1680 avio_wb32(pb, 0); /* layout */
1681 avio_wb32(pb, spherical_mapping->padding); /* padding */
1684 update_size(pb, proj_pos);
1686 return update_size(pb, sv3d_pos);
1689 static int mov_write_pasp_tag(AVIOContext *pb, MOVTrack *track)
1692 av_reduce(&sar.num, &sar.den, track->par->sample_aspect_ratio.num,
1693 track->par->sample_aspect_ratio.den, INT_MAX);
1696 ffio_wfourcc(pb, "pasp");
1697 avio_wb32(pb, sar.num);
1698 avio_wb32(pb, sar.den);
1702 static int mov_write_gama_tag(AVIOContext *pb, MOVTrack *track, double gamma)
1707 gamma = avpriv_get_gamma_from_trc(track->par->color_trc);
1709 av_log(pb, AV_LOG_DEBUG, "gamma value %g\n", gamma);
1712 gama = (uint32_t)lrint((double)(1<<16) * gamma);
1713 av_log(pb, AV_LOG_DEBUG, "writing gama value %"PRId32"\n", gama);
1715 av_assert0(track->mode == MODE_MOV);
1717 ffio_wfourcc(pb, "gama");
1718 avio_wb32(pb, gama);
1722 av_log(pb, AV_LOG_WARNING, "gamma value unknown, unable to write gama atom\n");
1727 static int mov_write_colr_tag(AVIOContext *pb, MOVTrack *track)
1729 // Ref (MOV): https://developer.apple.com/library/mac/technotes/tn2162/_index.html#//apple_ref/doc/uid/DTS40013070-CH1-TNTAG9
1730 // Ref (MP4): ISO/IEC 14496-12:2012
1732 if (track->par->color_primaries == AVCOL_PRI_UNSPECIFIED &&
1733 track->par->color_trc == AVCOL_TRC_UNSPECIFIED &&
1734 track->par->color_space == AVCOL_SPC_UNSPECIFIED) {
1735 if ((track->par->width >= 1920 && track->par->height >= 1080)
1736 || (track->par->width == 1280 && track->par->height == 720)) {
1737 av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming bt709\n");
1738 track->par->color_primaries = AVCOL_PRI_BT709;
1739 } else if (track->par->width == 720 && track->height == 576) {
1740 av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming bt470bg\n");
1741 track->par->color_primaries = AVCOL_PRI_BT470BG;
1742 } else if (track->par->width == 720 &&
1743 (track->height == 486 || track->height == 480)) {
1744 av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming smpte170\n");
1745 track->par->color_primaries = AVCOL_PRI_SMPTE170M;
1747 av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, unable to assume anything\n");
1749 switch (track->par->color_primaries) {
1750 case AVCOL_PRI_BT709:
1751 track->par->color_trc = AVCOL_TRC_BT709;
1752 track->par->color_space = AVCOL_SPC_BT709;
1754 case AVCOL_PRI_SMPTE170M:
1755 case AVCOL_PRI_BT470BG:
1756 track->par->color_trc = AVCOL_TRC_BT709;
1757 track->par->color_space = AVCOL_SPC_SMPTE170M;
1762 /* We should only ever be called by MOV or MP4. */
1763 av_assert0(track->mode == MODE_MOV || track->mode == MODE_MP4);
1765 avio_wb32(pb, 18 + (track->mode == MODE_MP4));
1766 ffio_wfourcc(pb, "colr");
1767 if (track->mode == MODE_MP4)
1768 ffio_wfourcc(pb, "nclx");
1770 ffio_wfourcc(pb, "nclc");
1771 switch (track->par->color_primaries) {
1772 case AVCOL_PRI_BT709: avio_wb16(pb, 1); break;
1773 case AVCOL_PRI_SMPTE170M:
1774 case AVCOL_PRI_SMPTE240M: avio_wb16(pb, 6); break;
1775 case AVCOL_PRI_BT470BG: avio_wb16(pb, 5); break;
1776 default: avio_wb16(pb, 2);
1778 switch (track->par->color_trc) {
1779 case AVCOL_TRC_BT709: avio_wb16(pb, 1); break;
1780 case AVCOL_TRC_SMPTE170M: avio_wb16(pb, 1); break; // remapped
1781 case AVCOL_TRC_SMPTE240M: avio_wb16(pb, 7); break;
1782 default: avio_wb16(pb, 2);
1784 switch (track->par->color_space) {
1785 case AVCOL_SPC_BT709: avio_wb16(pb, 1); break;
1786 case AVCOL_SPC_BT470BG:
1787 case AVCOL_SPC_SMPTE170M: avio_wb16(pb, 6); break;
1788 case AVCOL_SPC_SMPTE240M: avio_wb16(pb, 7); break;
1789 default: avio_wb16(pb, 2);
1792 if (track->mode == MODE_MP4) {
1793 int full_range = track->par->color_range == AVCOL_RANGE_JPEG;
1794 avio_w8(pb, full_range << 7);
1801 static void find_compressor(char * compressor_name, int len, MOVTrack *track)
1803 AVDictionaryEntry *encoder;
1804 int xdcam_res = (track->par->width == 1280 && track->par->height == 720)
1805 || (track->par->width == 1440 && track->par->height == 1080)
1806 || (track->par->width == 1920 && track->par->height == 1080);
1808 if (track->mode == MODE_MOV &&
1809 (encoder = av_dict_get(track->st->metadata, "encoder", NULL, 0))) {
1810 av_strlcpy(compressor_name, encoder->value, 32);
1811 } else if (track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO && xdcam_res) {
1812 int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE;
1813 AVStream *st = track->st;
1814 int rate = defined_frame_rate(NULL, st);
1815 av_strlcatf(compressor_name, len, "XDCAM");
1816 if (track->par->format == AV_PIX_FMT_YUV422P) {
1817 av_strlcatf(compressor_name, len, " HD422");
1818 } else if(track->par->width == 1440) {
1819 av_strlcatf(compressor_name, len, " HD");
1821 av_strlcatf(compressor_name, len, " EX");
1823 av_strlcatf(compressor_name, len, " %d%c", track->par->height, interlaced ? 'i' : 'p');
1825 av_strlcatf(compressor_name, len, "%d", rate * (interlaced + 1));
1829 static int mov_write_video_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
1831 int64_t pos = avio_tell(pb);
1832 char compressor_name[32] = { 0 };
1835 avio_wb32(pb, 0); /* size */
1836 if (mov->encryption_scheme != MOV_ENC_NONE) {
1837 ffio_wfourcc(pb, "encv");
1839 avio_wl32(pb, track->tag); // store it byteswapped
1841 avio_wb32(pb, 0); /* Reserved */
1842 avio_wb16(pb, 0); /* Reserved */
1843 avio_wb16(pb, 1); /* Data-reference index */
1845 avio_wb16(pb, 0); /* Codec stream version */
1846 avio_wb16(pb, 0); /* Codec stream revision (=0) */
1847 if (track->mode == MODE_MOV) {
1848 ffio_wfourcc(pb, "FFMP"); /* Vendor */
1849 if (track->par->codec_id == AV_CODEC_ID_RAWVIDEO) {
1850 avio_wb32(pb, 0); /* Temporal Quality */
1851 avio_wb32(pb, 0x400); /* Spatial Quality = lossless*/
1853 avio_wb32(pb, 0x200); /* Temporal Quality = normal */
1854 avio_wb32(pb, 0x200); /* Spatial Quality = normal */
1857 avio_wb32(pb, 0); /* Reserved */
1858 avio_wb32(pb, 0); /* Reserved */
1859 avio_wb32(pb, 0); /* Reserved */
1861 avio_wb16(pb, track->par->width); /* Video width */
1862 avio_wb16(pb, track->height); /* Video height */
1863 avio_wb32(pb, 0x00480000); /* Horizontal resolution 72dpi */
1864 avio_wb32(pb, 0x00480000); /* Vertical resolution 72dpi */
1865 avio_wb32(pb, 0); /* Data size (= 0) */
1866 avio_wb16(pb, 1); /* Frame count (= 1) */
1868 /* FIXME not sure, ISO 14496-1 draft where it shall be set to 0 */
1869 find_compressor(compressor_name, 32, track);
1870 avio_w8(pb, strlen(compressor_name));
1871 avio_write(pb, compressor_name, 31);
1873 if (track->mode == MODE_MOV && track->par->bits_per_coded_sample)
1874 avio_wb16(pb, track->par->bits_per_coded_sample |
1875 (track->par->format == AV_PIX_FMT_GRAY8 ? 0x20 : 0));
1877 avio_wb16(pb, 0x18); /* Reserved */
1879 if (track->mode == MODE_MOV && track->par->format == AV_PIX_FMT_PAL8) {
1880 int pal_size = 1 << track->par->bits_per_coded_sample;
1882 avio_wb16(pb, 0); /* Color table ID */
1883 avio_wb32(pb, 0); /* Color table seed */
1884 avio_wb16(pb, 0x8000); /* Color table flags */
1885 avio_wb16(pb, pal_size - 1); /* Color table size (zero-relative) */
1886 for (i = 0; i < pal_size; i++) {
1887 uint32_t rgb = track->palette[i];
1888 uint16_t r = (rgb >> 16) & 0xff;
1889 uint16_t g = (rgb >> 8) & 0xff;
1890 uint16_t b = rgb & 0xff;
1892 avio_wb16(pb, (r << 8) | r);
1893 avio_wb16(pb, (g << 8) | g);
1894 avio_wb16(pb, (b << 8) | b);
1897 avio_wb16(pb, 0xffff); /* Reserved */
1899 if (track->tag == MKTAG('m','p','4','v'))
1900 mov_write_esds_tag(pb, track);
1901 else if (track->par->codec_id == AV_CODEC_ID_H263)
1902 mov_write_d263_tag(pb);
1903 else if (track->par->codec_id == AV_CODEC_ID_AVUI ||
1904 track->par->codec_id == AV_CODEC_ID_SVQ3) {
1905 mov_write_extradata_tag(pb, track);
1907 } else if (track->par->codec_id == AV_CODEC_ID_DNXHD) {
1908 mov_write_avid_tag(pb, track);
1910 } else if (track->par->codec_id == AV_CODEC_ID_HEVC)
1911 mov_write_hvcc_tag(pb, track);
1912 else if (track->par->codec_id == AV_CODEC_ID_H264 && !TAG_IS_AVCI(track->tag)) {
1913 mov_write_avcc_tag(pb, track);
1914 if (track->mode == MODE_IPOD)
1915 mov_write_uuid_tag_ipod(pb);
1916 } else if (track->par->codec_id == AV_CODEC_ID_VP9) {
1917 mov_write_vpcc_tag(mov->fc, pb, track);
1918 } else if (track->par->codec_id == AV_CODEC_ID_VC1 && track->vos_len > 0)
1919 mov_write_dvc1_tag(pb, track);
1920 else if (track->par->codec_id == AV_CODEC_ID_VP6F ||
1921 track->par->codec_id == AV_CODEC_ID_VP6A) {
1922 /* Don't write any potential extradata here - the cropping
1923 * is signalled via the normal width/height fields. */
1924 } else if (track->par->codec_id == AV_CODEC_ID_R10K) {
1925 if (track->par->codec_tag == MKTAG('R','1','0','k'))
1926 mov_write_dpxe_tag(pb, track);
1927 } else if (track->vos_len > 0)
1928 mov_write_glbl_tag(pb, track);
1930 if (track->par->codec_id != AV_CODEC_ID_H264 &&
1931 track->par->codec_id != AV_CODEC_ID_MPEG4 &&
1932 track->par->codec_id != AV_CODEC_ID_DNXHD) {
1933 int field_order = track->par->field_order;
1935 #if FF_API_LAVF_AVCTX
1936 FF_DISABLE_DEPRECATION_WARNINGS
1937 if (field_order != track->st->codec->field_order && track->st->codec->field_order != AV_FIELD_UNKNOWN)
1938 field_order = track->st->codec->field_order;
1939 FF_ENABLE_DEPRECATION_WARNINGS
1942 if (field_order != AV_FIELD_UNKNOWN)
1943 mov_write_fiel_tag(pb, track, field_order);
1946 if (mov->flags & FF_MOV_FLAG_WRITE_GAMA) {
1947 if (track->mode == MODE_MOV)
1948 mov_write_gama_tag(pb, track, mov->gamma);
1950 av_log(mov->fc, AV_LOG_WARNING, "Not writing 'gama' atom. Format is not MOV.\n");
1952 if (mov->flags & FF_MOV_FLAG_WRITE_COLR) {
1953 if (track->mode == MODE_MOV || track->mode == MODE_MP4)
1954 mov_write_colr_tag(pb, track);
1956 av_log(mov->fc, AV_LOG_WARNING, "Not writing 'colr' atom. Format is not MOV or MP4.\n");
1959 if (track->mode == MODE_MP4 && mov->fc->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL) {
1960 AVStereo3D* stereo_3d = (AVStereo3D*) av_stream_get_side_data(track->st, AV_PKT_DATA_STEREO3D, NULL);
1961 AVSphericalMapping* spherical_mapping = (AVSphericalMapping*)av_stream_get_side_data(track->st, AV_PKT_DATA_SPHERICAL, NULL);
1964 mov_write_st3d_tag(pb, stereo_3d);
1965 if (spherical_mapping)
1966 mov_write_sv3d_tag(mov->fc, pb, spherical_mapping);
1969 if (track->par->sample_aspect_ratio.den && track->par->sample_aspect_ratio.num) {
1970 mov_write_pasp_tag(pb, track);
1973 if (mov->encryption_scheme != MOV_ENC_NONE) {
1974 ff_mov_cenc_write_sinf_tag(track, pb, mov->encryption_kid);
1977 /* extra padding for avid stsd */
1978 /* https://developer.apple.com/library/mac/documentation/QuickTime/QTFF/QTFFChap2/qtff2.html#//apple_ref/doc/uid/TP40000939-CH204-61112 */
1982 return update_size(pb, pos);
1985 static int mov_write_rtp_tag(AVIOContext *pb, MOVTrack *track)
1987 int64_t pos = avio_tell(pb);
1988 avio_wb32(pb, 0); /* size */
1989 ffio_wfourcc(pb, "rtp ");
1990 avio_wb32(pb, 0); /* Reserved */
1991 avio_wb16(pb, 0); /* Reserved */
1992 avio_wb16(pb, 1); /* Data-reference index */
1994 avio_wb16(pb, 1); /* Hint track version */
1995 avio_wb16(pb, 1); /* Highest compatible version */
1996 avio_wb32(pb, track->max_packet_size); /* Max packet size */
1998 avio_wb32(pb, 12); /* size */
1999 ffio_wfourcc(pb, "tims");
2000 avio_wb32(pb, track->timescale);
2002 return update_size(pb, pos);
2005 static int mov_write_source_reference_tag(AVIOContext *pb, MOVTrack *track, const char *reel_name)
2007 uint64_t str_size =strlen(reel_name);
2008 int64_t pos = avio_tell(pb);
2010 if (str_size >= UINT16_MAX){
2011 av_log(NULL, AV_LOG_ERROR, "reel_name length %"PRIu64" is too large\n", str_size);
2013 return AVERROR(EINVAL);
2016 avio_wb32(pb, 0); /* size */
2017 ffio_wfourcc(pb, "name"); /* Data format */
2018 avio_wb16(pb, str_size); /* string size */
2019 avio_wb16(pb, track->language); /* langcode */
2020 avio_write(pb, reel_name, str_size); /* reel name */
2021 return update_size(pb,pos);
2024 static int mov_write_tmcd_tag(AVIOContext *pb, MOVTrack *track)
2026 int64_t pos = avio_tell(pb);
2030 AVDictionaryEntry *t = NULL;
2032 if (!track->st->avg_frame_rate.num || !track->st->avg_frame_rate.den) {
2033 #if FF_API_LAVF_AVCTX
2034 FF_DISABLE_DEPRECATION_WARNINGS
2035 frame_duration = av_rescale(track->timescale, track->st->codec->time_base.num, track->st->codec->time_base.den);
2036 nb_frames = ROUNDED_DIV(track->st->codec->time_base.den, track->st->codec->time_base.num);
2037 FF_ENABLE_DEPRECATION_WARNINGS
2039 av_log(NULL, AV_LOG_ERROR, "avg_frame_rate not set for tmcd track.\n");
2040 return AVERROR(EINVAL);
2043 frame_duration = av_rescale(track->timescale, track->st->avg_frame_rate.num, track->st->avg_frame_rate.den);
2044 nb_frames = ROUNDED_DIV(track->st->avg_frame_rate.den, track->st->avg_frame_rate.num);
2047 if (nb_frames > 255) {
2048 av_log(NULL, AV_LOG_ERROR, "fps %d is too large\n", nb_frames);
2049 return AVERROR(EINVAL);
2052 avio_wb32(pb, 0); /* size */
2053 ffio_wfourcc(pb, "tmcd"); /* Data format */
2054 avio_wb32(pb, 0); /* Reserved */
2055 avio_wb32(pb, 1); /* Data reference index */
2056 avio_wb32(pb, 0); /* Flags */
2057 avio_wb32(pb, track->timecode_flags); /* Flags (timecode) */
2058 avio_wb32(pb, track->timescale); /* Timescale */
2059 avio_wb32(pb, frame_duration); /* Frame duration */
2060 avio_w8(pb, nb_frames); /* Number of frames */
2061 avio_w8(pb, 0); /* Reserved */
2063 t = av_dict_get(track->st->metadata, "reel_name", NULL, 0);
2064 if (t && utf8len(t->value) && track->mode != MODE_MP4)
2065 mov_write_source_reference_tag(pb, track, t->value);
2067 avio_wb16(pb, 0); /* zero size */
2070 avio_wb32(pb, 0); /* size */
2071 ffio_wfourcc(pb, "tmcd"); /* Data format */
2072 avio_wb32(pb, 0); /* Reserved */
2073 avio_wb32(pb, 1); /* Data reference index */
2074 if (track->par->extradata_size)
2075 avio_write(pb, track->par->extradata, track->par->extradata_size);
2077 return update_size(pb, pos);
2080 static int mov_write_gpmd_tag(AVIOContext *pb, const MOVTrack *track)
2082 int64_t pos = avio_tell(pb);
2083 avio_wb32(pb, 0); /* size */
2084 ffio_wfourcc(pb, "gpmd");
2085 avio_wb32(pb, 0); /* Reserved */
2086 avio_wb16(pb, 0); /* Reserved */
2087 avio_wb16(pb, 1); /* Data-reference index */
2088 avio_wb32(pb, 0); /* Reserved */
2089 return update_size(pb, pos);
2092 static int mov_write_stsd_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
2094 int64_t pos = avio_tell(pb);
2095 avio_wb32(pb, 0); /* size */
2096 ffio_wfourcc(pb, "stsd");
2097 avio_wb32(pb, 0); /* version & flags */
2098 avio_wb32(pb, 1); /* entry count */
2099 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO)
2100 mov_write_video_tag(pb, mov, track);
2101 else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
2102 mov_write_audio_tag(s, pb, mov, track);
2103 else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)
2104 mov_write_subtitle_tag(pb, track);
2105 else if (track->par->codec_tag == MKTAG('r','t','p',' '))
2106 mov_write_rtp_tag(pb, track);
2107 else if (track->par->codec_tag == MKTAG('t','m','c','d'))
2108 mov_write_tmcd_tag(pb, track);
2109 else if (track->par->codec_tag == MKTAG('g','p','m','d'))
2110 mov_write_gpmd_tag(pb, track);
2111 return update_size(pb, pos);
2114 static int mov_write_ctts_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
2116 MOVMuxContext *mov = s->priv_data;
2117 MOVStts *ctts_entries;
2118 uint32_t entries = 0;
2122 ctts_entries = av_malloc_array((track->entry + 1), sizeof(*ctts_entries)); /* worst case */
2124 return AVERROR(ENOMEM);
2125 ctts_entries[0].count = 1;
2126 ctts_entries[0].duration = track->cluster[0].cts;
2127 for (i = 1; i < track->entry; i++) {
2128 if (track->cluster[i].cts == ctts_entries[entries].duration) {
2129 ctts_entries[entries].count++; /* compress */
2132 ctts_entries[entries].duration = track->cluster[i].cts;
2133 ctts_entries[entries].count = 1;
2136 entries++; /* last one */
2137 atom_size = 16 + (entries * 8);
2138 avio_wb32(pb, atom_size); /* size */
2139 ffio_wfourcc(pb, "ctts");
2140 if (mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS)
2141 avio_w8(pb, 1); /* version */
2143 avio_w8(pb, 0); /* version */
2144 avio_wb24(pb, 0); /* flags */
2145 avio_wb32(pb, entries); /* entry count */
2146 for (i = 0; i < entries; i++) {
2147 avio_wb32(pb, ctts_entries[i].count);
2148 avio_wb32(pb, ctts_entries[i].duration);
2150 av_free(ctts_entries);
2154 /* Time to sample atom */
2155 static int mov_write_stts_tag(AVIOContext *pb, MOVTrack *track)
2157 MOVStts *stts_entries = NULL;
2158 uint32_t entries = -1;
2162 if (track->par->codec_type == AVMEDIA_TYPE_AUDIO && !track->audio_vbr) {
2163 stts_entries = av_malloc(sizeof(*stts_entries)); /* one entry */
2165 return AVERROR(ENOMEM);
2166 stts_entries[0].count = track->sample_count;
2167 stts_entries[0].duration = 1;
2171 stts_entries = av_malloc_array(track->entry, sizeof(*stts_entries)); /* worst case */
2173 return AVERROR(ENOMEM);
2175 for (i = 0; i < track->entry; i++) {
2176 int duration = get_cluster_duration(track, i);
2177 if (i && duration == stts_entries[entries].duration) {
2178 stts_entries[entries].count++; /* compress */
2181 stts_entries[entries].duration = duration;
2182 stts_entries[entries].count = 1;
2185 entries++; /* last one */
2187 atom_size = 16 + (entries * 8);
2188 avio_wb32(pb, atom_size); /* size */
2189 ffio_wfourcc(pb, "stts");
2190 avio_wb32(pb, 0); /* version & flags */
2191 avio_wb32(pb, entries); /* entry count */
2192 for (i = 0; i < entries; i++) {
2193 avio_wb32(pb, stts_entries[i].count);
2194 avio_wb32(pb, stts_entries[i].duration);
2196 av_free(stts_entries);
2200 static int mov_write_dref_tag(AVIOContext *pb)
2202 avio_wb32(pb, 28); /* size */
2203 ffio_wfourcc(pb, "dref");
2204 avio_wb32(pb, 0); /* version & flags */
2205 avio_wb32(pb, 1); /* entry count */
2207 avio_wb32(pb, 0xc); /* size */
2208 //FIXME add the alis and rsrc atom
2209 ffio_wfourcc(pb, "url ");
2210 avio_wb32(pb, 1); /* version & flags */
2215 static int mov_preroll_write_stbl_atoms(AVIOContext *pb, MOVTrack *track)
2219 int16_t roll_distance;
2220 int group_description_index;
2223 struct sgpd_entry *sgpd_entries = NULL;
2228 const int OPUS_SEEK_PREROLL_MS = 80;
2229 int roll_samples = av_rescale_q(OPUS_SEEK_PREROLL_MS,
2230 (AVRational){1, 1000},
2231 (AVRational){1, 48000});
2236 sgpd_entries = av_malloc_array(track->entry, sizeof(*sgpd_entries));
2238 return AVERROR(ENOMEM);
2240 av_assert0(track->par->codec_id == AV_CODEC_ID_OPUS || track->par->codec_id == AV_CODEC_ID_AAC);
2242 if (track->par->codec_id == AV_CODEC_ID_OPUS) {
2243 for (i = 0; i < track->entry; i++) {
2244 int roll_samples_remaining = roll_samples;
2246 for (j = i - 1; j >= 0; j--) {
2247 roll_samples_remaining -= get_cluster_duration(track, j);
2249 if (roll_samples_remaining <= 0)
2252 /* We don't have enough preceeding samples to compute a valid
2253 roll_distance here, so this sample can't be independently
2255 if (roll_samples_remaining > 0)
2257 /* Verify distance is a minimum of 2 (60ms) packets and a maximum of
2258 32 (2.5ms) packets. */
2259 av_assert0(distance == 0 || (distance >= 2 && distance <= 32));
2260 if (i && distance == sgpd_entries[entries].roll_distance) {
2261 sgpd_entries[entries].count++;
2264 sgpd_entries[entries].count = 1;
2265 sgpd_entries[entries].roll_distance = distance;
2266 sgpd_entries[entries].group_description_index = distance ? ++group : 0;
2271 sgpd_entries[entries].count = track->sample_count;
2272 sgpd_entries[entries].roll_distance = 1;
2273 sgpd_entries[entries].group_description_index = ++group;
2278 av_free(sgpd_entries);
2282 /* Write sgpd tag */
2283 avio_wb32(pb, 24 + (group * 2)); /* size */
2284 ffio_wfourcc(pb, "sgpd");
2285 avio_wb32(pb, 1 << 24); /* fullbox */
2286 ffio_wfourcc(pb, "roll");
2287 avio_wb32(pb, 2); /* default_length */
2288 avio_wb32(pb, group); /* entry_count */
2289 for (i = 0; i < entries; i++) {
2290 if (sgpd_entries[i].group_description_index) {
2291 avio_wb16(pb, -sgpd_entries[i].roll_distance); /* roll_distance */
2295 /* Write sbgp tag */
2296 avio_wb32(pb, 20 + (entries * 8)); /* size */
2297 ffio_wfourcc(pb, "sbgp");
2298 avio_wb32(pb, 0); /* fullbox */
2299 ffio_wfourcc(pb, "roll");
2300 avio_wb32(pb, entries); /* entry_count */
2301 for (i = 0; i < entries; i++) {
2302 avio_wb32(pb, sgpd_entries[i].count); /* sample_count */
2303 avio_wb32(pb, sgpd_entries[i].group_description_index); /* group_description_index */
2306 av_free(sgpd_entries);
2310 static int mov_write_stbl_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
2312 int64_t pos = avio_tell(pb);
2315 avio_wb32(pb, 0); /* size */
2316 ffio_wfourcc(pb, "stbl");
2317 mov_write_stsd_tag(s, pb, mov, track);
2318 mov_write_stts_tag(pb, track);
2319 if ((track->par->codec_type == AVMEDIA_TYPE_VIDEO ||
2320 track->par->codec_tag == MKTAG('r','t','p',' ')) &&
2321 track->has_keyframes && track->has_keyframes < track->entry)
2322 mov_write_stss_tag(pb, track, MOV_SYNC_SAMPLE);
2323 if (track->mode == MODE_MOV && track->flags & MOV_TRACK_STPS)
2324 mov_write_stss_tag(pb, track, MOV_PARTIAL_SYNC_SAMPLE);
2325 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO &&
2326 track->flags & MOV_TRACK_CTTS && track->entry) {
2328 if ((ret = mov_write_ctts_tag(s, pb, track)) < 0)
2331 mov_write_stsc_tag(pb, track);
2332 mov_write_stsz_tag(pb, track);
2333 mov_write_stco_tag(pb, track);
2334 if (track->cenc.aes_ctr) {
2335 ff_mov_cenc_write_stbl_atoms(&track->cenc, pb);
2337 if (track->par->codec_id == AV_CODEC_ID_OPUS || track->par->codec_id == AV_CODEC_ID_AAC) {
2338 mov_preroll_write_stbl_atoms(pb, track);
2340 return update_size(pb, pos);
2343 static int mov_write_dinf_tag(AVIOContext *pb)
2345 int64_t pos = avio_tell(pb);
2346 avio_wb32(pb, 0); /* size */
2347 ffio_wfourcc(pb, "dinf");
2348 mov_write_dref_tag(pb);
2349 return update_size(pb, pos);
2352 static int mov_write_nmhd_tag(AVIOContext *pb)
2355 ffio_wfourcc(pb, "nmhd");
2360 static int mov_write_tcmi_tag(AVIOContext *pb, MOVTrack *track)
2362 int64_t pos = avio_tell(pb);
2363 const char *font = "Lucida Grande";
2364 avio_wb32(pb, 0); /* size */
2365 ffio_wfourcc(pb, "tcmi"); /* timecode media information atom */
2366 avio_wb32(pb, 0); /* version & flags */
2367 avio_wb16(pb, 0); /* text font */
2368 avio_wb16(pb, 0); /* text face */
2369 avio_wb16(pb, 12); /* text size */
2370 avio_wb16(pb, 0); /* (unknown, not in the QT specs...) */
2371 avio_wb16(pb, 0x0000); /* text color (red) */
2372 avio_wb16(pb, 0x0000); /* text color (green) */
2373 avio_wb16(pb, 0x0000); /* text color (blue) */
2374 avio_wb16(pb, 0xffff); /* background color (red) */
2375 avio_wb16(pb, 0xffff); /* background color (green) */
2376 avio_wb16(pb, 0xffff); /* background color (blue) */
2377 avio_w8(pb, strlen(font)); /* font len (part of the pascal string) */
2378 avio_write(pb, font, strlen(font)); /* font name */
2379 return update_size(pb, pos);
2382 static int mov_write_gmhd_tag(AVIOContext *pb, MOVTrack *track)
2384 int64_t pos = avio_tell(pb);
2385 avio_wb32(pb, 0); /* size */
2386 ffio_wfourcc(pb, "gmhd");
2387 avio_wb32(pb, 0x18); /* gmin size */
2388 ffio_wfourcc(pb, "gmin");/* generic media info */
2389 avio_wb32(pb, 0); /* version & flags */
2390 avio_wb16(pb, 0x40); /* graphics mode = */
2391 avio_wb16(pb, 0x8000); /* opColor (r?) */
2392 avio_wb16(pb, 0x8000); /* opColor (g?) */
2393 avio_wb16(pb, 0x8000); /* opColor (b?) */
2394 avio_wb16(pb, 0); /* balance */
2395 avio_wb16(pb, 0); /* reserved */
2398 * This special text atom is required for
2399 * Apple Quicktime chapters. The contents
2400 * don't appear to be documented, so the
2401 * bytes are copied verbatim.
2403 if (track->tag != MKTAG('c','6','0','8')) {
2404 avio_wb32(pb, 0x2C); /* size */
2405 ffio_wfourcc(pb, "text");
2406 avio_wb16(pb, 0x01);
2407 avio_wb32(pb, 0x00);
2408 avio_wb32(pb, 0x00);
2409 avio_wb32(pb, 0x00);
2410 avio_wb32(pb, 0x01);
2411 avio_wb32(pb, 0x00);
2412 avio_wb32(pb, 0x00);
2413 avio_wb32(pb, 0x00);
2414 avio_wb32(pb, 0x00004000);
2415 avio_wb16(pb, 0x0000);
2418 if (track->par->codec_tag == MKTAG('t','m','c','d')) {
2419 int64_t tmcd_pos = avio_tell(pb);
2420 avio_wb32(pb, 0); /* size */
2421 ffio_wfourcc(pb, "tmcd");
2422 mov_write_tcmi_tag(pb, track);
2423 update_size(pb, tmcd_pos);
2424 } else if (track->par->codec_tag == MKTAG('g','p','m','d')) {
2425 int64_t gpmd_pos = avio_tell(pb);
2426 avio_wb32(pb, 0); /* size */
2427 ffio_wfourcc(pb, "gpmd");
2428 avio_wb32(pb, 0); /* version */
2429 update_size(pb, gpmd_pos);
2431 return update_size(pb, pos);
2434 static int mov_write_smhd_tag(AVIOContext *pb)
2436 avio_wb32(pb, 16); /* size */
2437 ffio_wfourcc(pb, "smhd");
2438 avio_wb32(pb, 0); /* version & flags */
2439 avio_wb16(pb, 0); /* reserved (balance, normally = 0) */
2440 avio_wb16(pb, 0); /* reserved */
2444 static int mov_write_vmhd_tag(AVIOContext *pb)
2446 avio_wb32(pb, 0x14); /* size (always 0x14) */
2447 ffio_wfourcc(pb, "vmhd");
2448 avio_wb32(pb, 0x01); /* version & flags */
2449 avio_wb64(pb, 0); /* reserved (graphics mode = copy) */
2453 static int is_clcp_track(MOVTrack *track)
2455 return track->tag == MKTAG('c','7','0','8') ||
2456 track->tag == MKTAG('c','6','0','8');
2459 static int mov_write_hdlr_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
2461 const char *hdlr, *descr = NULL, *hdlr_type = NULL;
2462 int64_t pos = avio_tell(pb);
2466 descr = "DataHandler";
2469 hdlr = (track->mode == MODE_MOV) ? "mhlr" : "\0\0\0\0";
2470 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
2472 descr = "VideoHandler";
2473 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
2475 descr = "SoundHandler";
2476 } else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE) {
2477 if (is_clcp_track(track)) {
2479 descr = "ClosedCaptionHandler";
2481 if (track->tag == MKTAG('t','x','3','g')) {
2483 } else if (track->tag == MKTAG('m','p','4','s')) {
2488 descr = "SubtitleHandler";
2490 } else if (track->par->codec_tag == MKTAG('r','t','p',' ')) {
2492 descr = "HintHandler";
2493 } else if (track->par->codec_tag == MKTAG('t','m','c','d')) {
2495 descr = "TimeCodeHandler";
2496 } else if (track->par->codec_tag == MKTAG('g','p','m','d')) {
2498 descr = "GoPro MET"; // GoPro Metadata
2500 av_log(s, AV_LOG_WARNING,
2501 "Unknown hldr_type for %s, writing dummy values\n",
2502 av_fourcc2str(track->par->codec_tag));
2505 // hdlr.name is used by some players to identify the content title
2506 // of the track. So if an alternate handler description is
2507 // specified, use it.
2508 AVDictionaryEntry *t;
2509 t = av_dict_get(track->st->metadata, "handler", NULL, 0);
2510 if (t && utf8len(t->value))
2515 avio_wb32(pb, 0); /* size */
2516 ffio_wfourcc(pb, "hdlr");
2517 avio_wb32(pb, 0); /* Version & flags */
2518 avio_write(pb, hdlr, 4); /* handler */
2519 ffio_wfourcc(pb, hdlr_type); /* handler type */
2520 avio_wb32(pb, 0); /* reserved */
2521 avio_wb32(pb, 0); /* reserved */
2522 avio_wb32(pb, 0); /* reserved */
2523 if (!track || track->mode == MODE_MOV)
2524 avio_w8(pb, strlen(descr)); /* pascal string */
2525 avio_write(pb, descr, strlen(descr)); /* handler description */
2526 if (track && track->mode != MODE_MOV)
2527 avio_w8(pb, 0); /* c string */
2528 return update_size(pb, pos);
2531 static int mov_write_hmhd_tag(AVIOContext *pb)
2533 /* This atom must be present, but leaving the values at zero
2534 * seems harmless. */
2535 avio_wb32(pb, 28); /* size */
2536 ffio_wfourcc(pb, "hmhd");
2537 avio_wb32(pb, 0); /* version, flags */
2538 avio_wb16(pb, 0); /* maxPDUsize */
2539 avio_wb16(pb, 0); /* avgPDUsize */
2540 avio_wb32(pb, 0); /* maxbitrate */
2541 avio_wb32(pb, 0); /* avgbitrate */
2542 avio_wb32(pb, 0); /* reserved */
2546 static int mov_write_minf_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
2548 int64_t pos = avio_tell(pb);
2551 avio_wb32(pb, 0); /* size */
2552 ffio_wfourcc(pb, "minf");
2553 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO)
2554 mov_write_vmhd_tag(pb);
2555 else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
2556 mov_write_smhd_tag(pb);
2557 else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE) {
2558 if (track->tag == MKTAG('t','e','x','t') || is_clcp_track(track)) {
2559 mov_write_gmhd_tag(pb, track);
2561 mov_write_nmhd_tag(pb);
2563 } else if (track->tag == MKTAG('r','t','p',' ')) {
2564 mov_write_hmhd_tag(pb);
2565 } else if (track->tag == MKTAG('t','m','c','d')) {
2566 if (track->mode != MODE_MOV)
2567 mov_write_nmhd_tag(pb);
2569 mov_write_gmhd_tag(pb, track);
2570 } else if (track->tag == MKTAG('g','p','m','d')) {
2571 mov_write_gmhd_tag(pb, track);
2573 if (track->mode == MODE_MOV) /* FIXME: Why do it for MODE_MOV only ? */
2574 mov_write_hdlr_tag(s, pb, NULL);
2575 mov_write_dinf_tag(pb);
2576 if ((ret = mov_write_stbl_tag(s, pb, mov, track)) < 0)
2578 return update_size(pb, pos);
2581 static int mov_write_mdhd_tag(AVIOContext *pb, MOVMuxContext *mov,
2584 int version = track->track_duration < INT32_MAX ? 0 : 1;
2586 if (track->mode == MODE_ISM)
2589 (version == 1) ? avio_wb32(pb, 44) : avio_wb32(pb, 32); /* size */
2590 ffio_wfourcc(pb, "mdhd");
2591 avio_w8(pb, version);
2592 avio_wb24(pb, 0); /* flags */
2594 avio_wb64(pb, track->time);
2595 avio_wb64(pb, track->time);
2597 avio_wb32(pb, track->time); /* creation time */
2598 avio_wb32(pb, track->time); /* modification time */
2600 avio_wb32(pb, track->timescale); /* time scale (sample rate for audio) */
2601 if (!track->entry && mov->mode == MODE_ISM)
2602 (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
2603 else if (!track->entry)
2604 (version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0);
2606 (version == 1) ? avio_wb64(pb, track->track_duration) : avio_wb32(pb, track->track_duration); /* duration */
2607 avio_wb16(pb, track->language); /* language */
2608 avio_wb16(pb, 0); /* reserved (quality) */
2610 if (version != 0 && track->mode == MODE_MOV) {
2611 av_log(NULL, AV_LOG_ERROR,
2612 "FATAL error, file duration too long for timebase, this file will not be\n"
2613 "playable with quicktime. Choose a different timebase or a different\n"
2614 "container format\n");
2620 static int mov_write_mdia_tag(AVFormatContext *s, AVIOContext *pb,
2621 MOVMuxContext *mov, MOVTrack *track)
2623 int64_t pos = avio_tell(pb);
2626 avio_wb32(pb, 0); /* size */
2627 ffio_wfourcc(pb, "mdia");
2628 mov_write_mdhd_tag(pb, mov, track);
2629 mov_write_hdlr_tag(s, pb, track);
2630 if ((ret = mov_write_minf_tag(s, pb, mov, track)) < 0)
2632 return update_size(pb, pos);
2635 /* transformation matrix
2639 static void write_matrix(AVIOContext *pb, int16_t a, int16_t b, int16_t c,
2640 int16_t d, int16_t tx, int16_t ty)
2642 avio_wb32(pb, a << 16); /* 16.16 format */
2643 avio_wb32(pb, b << 16); /* 16.16 format */
2644 avio_wb32(pb, 0); /* u in 2.30 format */
2645 avio_wb32(pb, c << 16); /* 16.16 format */
2646 avio_wb32(pb, d << 16); /* 16.16 format */
2647 avio_wb32(pb, 0); /* v in 2.30 format */
2648 avio_wb32(pb, tx << 16); /* 16.16 format */
2649 avio_wb32(pb, ty << 16); /* 16.16 format */
2650 avio_wb32(pb, 1 << 30); /* w in 2.30 format */
2653 static int mov_write_tkhd_tag(AVIOContext *pb, MOVMuxContext *mov,
2654 MOVTrack *track, AVStream *st)
2656 int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE,
2657 track->timescale, AV_ROUND_UP);
2658 int version = duration < INT32_MAX ? 0 : 1;
2659 int flags = MOV_TKHD_FLAG_IN_MOVIE;
2663 uint32_t *display_matrix = NULL;
2664 int display_matrix_size, i;
2667 if (mov->per_stream_grouping)
2670 group = st->codecpar->codec_type;
2672 display_matrix = (uint32_t*)av_stream_get_side_data(st, AV_PKT_DATA_DISPLAYMATRIX,
2673 &display_matrix_size);
2674 if (display_matrix && display_matrix_size < 9 * sizeof(*display_matrix))
2675 display_matrix = NULL;
2678 if (track->flags & MOV_TRACK_ENABLED)
2679 flags |= MOV_TKHD_FLAG_ENABLED;
2681 if (track->mode == MODE_ISM)
2684 (version == 1) ? avio_wb32(pb, 104) : avio_wb32(pb, 92); /* size */
2685 ffio_wfourcc(pb, "tkhd");
2686 avio_w8(pb, version);
2687 avio_wb24(pb, flags);
2689 avio_wb64(pb, track->time);
2690 avio_wb64(pb, track->time);
2692 avio_wb32(pb, track->time); /* creation time */
2693 avio_wb32(pb, track->time); /* modification time */
2695 avio_wb32(pb, track->track_id); /* track-id */
2696 avio_wb32(pb, 0); /* reserved */
2697 if (!track->entry && mov->mode == MODE_ISM)
2698 (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
2699 else if (!track->entry)
2700 (version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0);
2702 (version == 1) ? avio_wb64(pb, duration) : avio_wb32(pb, duration);
2704 avio_wb32(pb, 0); /* reserved */
2705 avio_wb32(pb, 0); /* reserved */
2706 avio_wb16(pb, 0); /* layer */
2707 avio_wb16(pb, group); /* alternate group) */
2708 /* Volume, only for audio */
2709 if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
2710 avio_wb16(pb, 0x0100);
2713 avio_wb16(pb, 0); /* reserved */
2715 /* Matrix structure */
2716 #if FF_API_OLD_ROTATE_API
2717 if (st && st->metadata) {
2718 AVDictionaryEntry *rot = av_dict_get(st->metadata, "rotate", NULL, 0);
2719 rotation = (rot && rot->value) ? atoi(rot->value) : 0;
2722 if (display_matrix) {
2723 for (i = 0; i < 9; i++)
2724 avio_wb32(pb, display_matrix[i]);
2725 #if FF_API_OLD_ROTATE_API
2726 } else if (rotation == 90) {
2727 write_matrix(pb, 0, 1, -1, 0, track->par->height, 0);
2728 } else if (rotation == 180) {
2729 write_matrix(pb, -1, 0, 0, -1, track->par->width, track->par->height);
2730 } else if (rotation == 270) {
2731 write_matrix(pb, 0, -1, 1, 0, 0, track->par->width);
2734 write_matrix(pb, 1, 0, 0, 1, 0, 0);
2736 /* Track width and height, for visual only */
2737 if (st && (track->par->codec_type == AVMEDIA_TYPE_VIDEO ||
2738 track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)) {
2739 int64_t track_width_1616;
2740 if (track->mode == MODE_MOV) {
2741 track_width_1616 = track->par->width * 0x10000ULL;
2743 track_width_1616 = av_rescale(st->sample_aspect_ratio.num,
2744 track->par->width * 0x10000LL,
2745 st->sample_aspect_ratio.den);
2746 if (!track_width_1616 ||
2747 track->height != track->par->height ||
2748 track_width_1616 > UINT32_MAX)
2749 track_width_1616 = track->par->width * 0x10000ULL;
2751 if (track_width_1616 > UINT32_MAX) {
2752 av_log(mov->fc, AV_LOG_WARNING, "track width is too large\n");
2753 track_width_1616 = 0;
2755 avio_wb32(pb, track_width_1616);
2756 if (track->height > 0xFFFF) {
2757 av_log(mov->fc, AV_LOG_WARNING, "track height is too large\n");
2760 avio_wb32(pb, track->height * 0x10000U);
2768 static int mov_write_tapt_tag(AVIOContext *pb, MOVTrack *track)
2770 int32_t width = av_rescale(track->par->sample_aspect_ratio.num, track->par->width,
2771 track->par->sample_aspect_ratio.den);
2773 int64_t pos = avio_tell(pb);
2775 avio_wb32(pb, 0); /* size */
2776 ffio_wfourcc(pb, "tapt");
2779 ffio_wfourcc(pb, "clef");
2781 avio_wb32(pb, width << 16);
2782 avio_wb32(pb, track->par->height << 16);
2785 ffio_wfourcc(pb, "prof");
2787 avio_wb32(pb, width << 16);
2788 avio_wb32(pb, track->par->height << 16);
2791 ffio_wfourcc(pb, "enof");
2793 avio_wb32(pb, track->par->width << 16);
2794 avio_wb32(pb, track->par->height << 16);
2796 return update_size(pb, pos);
2799 // This box seems important for the psp playback ... without it the movie seems to hang
2800 static int mov_write_edts_tag(AVIOContext *pb, MOVMuxContext *mov,
2803 int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE,
2804 track->timescale, AV_ROUND_UP);
2805 int version = duration < INT32_MAX ? 0 : 1;
2806 int entry_size, entry_count, size;
2807 int64_t delay, start_ct = track->start_cts;
2808 int64_t start_dts = track->start_dts;
2811 if (start_dts != track->cluster[0].dts || start_ct != track->cluster[0].cts) {
2813 av_log(mov->fc, AV_LOG_DEBUG,
2814 "EDTS using dts:%"PRId64" cts:%d instead of dts:%"PRId64" cts:%"PRId64" tid:%d\n",
2815 track->cluster[0].dts, track->cluster[0].cts,
2816 start_dts, start_ct, track->track_id);
2817 start_dts = track->cluster[0].dts;
2818 start_ct = track->cluster[0].cts;
2822 delay = av_rescale_rnd(start_dts + start_ct, MOV_TIMESCALE,
2823 track->timescale, AV_ROUND_DOWN);
2824 version |= delay < INT32_MAX ? 0 : 1;
2826 entry_size = (version == 1) ? 20 : 12;
2827 entry_count = 1 + (delay > 0);
2828 size = 24 + entry_count * entry_size;
2830 /* write the atom data */
2831 avio_wb32(pb, size);
2832 ffio_wfourcc(pb, "edts");
2833 avio_wb32(pb, size - 8);
2834 ffio_wfourcc(pb, "elst");
2835 avio_w8(pb, version);
2836 avio_wb24(pb, 0); /* flags */
2838 avio_wb32(pb, entry_count);
2839 if (delay > 0) { /* add an empty edit to delay presentation */
2840 /* In the positive delay case, the delay includes the cts
2841 * offset, and the second edit list entry below trims out
2842 * the same amount from the actual content. This makes sure
2843 * that the offset last sample is included in the edit
2844 * list duration as well. */
2846 avio_wb64(pb, delay);
2849 avio_wb32(pb, delay);
2852 avio_wb32(pb, 0x00010000);
2854 /* Avoid accidentally ending up with start_ct = -1 which has got a
2855 * special meaning. Normally start_ct should end up positive or zero
2856 * here, but use FFMIN in case dts is a small positive integer
2857 * rounded to 0 when represented in MOV_TIMESCALE units. */
2858 av_assert0(av_rescale_rnd(start_dts, MOV_TIMESCALE, track->timescale, AV_ROUND_DOWN) <= 0);
2859 start_ct = -FFMIN(start_dts, 0);
2860 /* Note, this delay is calculated from the pts of the first sample,
2861 * ensuring that we don't reduce the duration for cases with
2866 /* For fragmented files, we don't know the full length yet. Setting
2867 * duration to 0 allows us to only specify the offset, including
2868 * the rest of the content (from all future fragments) without specifying
2869 * an explicit duration. */
2870 if (mov->flags & FF_MOV_FLAG_FRAGMENT)
2875 avio_wb64(pb, duration);
2876 avio_wb64(pb, start_ct);
2878 avio_wb32(pb, duration);
2879 avio_wb32(pb, start_ct);
2881 avio_wb32(pb, 0x00010000);
2885 static int mov_write_tref_tag(AVIOContext *pb, MOVTrack *track)
2887 avio_wb32(pb, 20); // size
2888 ffio_wfourcc(pb, "tref");
2889 avio_wb32(pb, 12); // size (subatom)
2890 avio_wl32(pb, track->tref_tag);
2891 avio_wb32(pb, track->tref_id);
2895 // goes at the end of each track! ... Critical for PSP playback ("Incompatible data" without it)
2896 static int mov_write_uuid_tag_psp(AVIOContext *pb, MOVTrack *mov)
2898 avio_wb32(pb, 0x34); /* size ... reports as 28 in mp4box! */
2899 ffio_wfourcc(pb, "uuid");
2900 ffio_wfourcc(pb, "USMT");
2901 avio_wb32(pb, 0x21d24fce);
2902 avio_wb32(pb, 0xbb88695c);
2903 avio_wb32(pb, 0xfac9c740);
2904 avio_wb32(pb, 0x1c); // another size here!
2905 ffio_wfourcc(pb, "MTDT");
2906 avio_wb32(pb, 0x00010012);
2907 avio_wb32(pb, 0x0a);
2908 avio_wb32(pb, 0x55c40000);
2914 static int mov_write_udta_sdp(AVIOContext *pb, MOVTrack *track)
2916 AVFormatContext *ctx = track->rtp_ctx;
2917 char buf[1000] = "";
2920 ff_sdp_write_media(buf, sizeof(buf), ctx->streams[0], track->src_track,
2921 NULL, NULL, 0, 0, ctx);
2922 av_strlcatf(buf, sizeof(buf), "a=control:streamid=%d\r\n", track->track_id);
2925 avio_wb32(pb, len + 24);
2926 ffio_wfourcc(pb, "udta");
2927 avio_wb32(pb, len + 16);
2928 ffio_wfourcc(pb, "hnti");
2929 avio_wb32(pb, len + 8);
2930 ffio_wfourcc(pb, "sdp ");
2931 avio_write(pb, buf, len);
2935 static int mov_write_track_metadata(AVIOContext *pb, AVStream *st,
2936 const char *tag, const char *str)
2938 int64_t pos = avio_tell(pb);
2939 AVDictionaryEntry *t = av_dict_get(st->metadata, str, NULL, 0);
2940 if (!t || !utf8len(t->value))
2943 avio_wb32(pb, 0); /* size */
2944 ffio_wfourcc(pb, tag); /* type */
2945 avio_write(pb, t->value, strlen(t->value)); /* UTF8 string value */
2946 return update_size(pb, pos);
2949 static int mov_write_track_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
2952 AVIOContext *pb_buf;
2959 ret = avio_open_dyn_buf(&pb_buf);
2963 if (mov->mode & MODE_MP4)
2964 mov_write_track_metadata(pb_buf, st, "name", "title");
2966 if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) {
2967 avio_wb32(pb, size + 8);
2968 ffio_wfourcc(pb, "udta");
2969 avio_write(pb, buf, size);
2976 static int mov_write_trak_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov,
2977 MOVTrack *track, AVStream *st)
2979 int64_t pos = avio_tell(pb);
2980 int entry_backup = track->entry;
2981 int chunk_backup = track->chunkCount;
2984 /* If we want to have an empty moov, but some samples already have been
2985 * buffered (delay_moov), pretend that no samples have been written yet. */
2986 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV)
2987 track->chunkCount = track->entry = 0;
2989 avio_wb32(pb, 0); /* size */
2990 ffio_wfourcc(pb, "trak");
2991 mov_write_tkhd_tag(pb, mov, track, st);
2993 av_assert2(mov->use_editlist >= 0);
2995 if (track->start_dts != AV_NOPTS_VALUE) {
2996 if (mov->use_editlist)
2997 mov_write_edts_tag(pb, mov, track); // PSP Movies and several other cases require edts box
2998 else if ((track->entry && track->cluster[0].dts) || track->mode == MODE_PSP || is_clcp_track(track))
2999 av_log(mov->fc, AV_LOG_WARNING,
3000 "Not writing any edit list even though one would have been required\n");
3003 if (track->tref_tag)
3004 mov_write_tref_tag(pb, track);
3006 if ((ret = mov_write_mdia_tag(s, pb, mov, track)) < 0)
3008 if (track->mode == MODE_PSP)
3009 mov_write_uuid_tag_psp(pb, track); // PSP Movies require this uuid box
3010 if (track->tag == MKTAG('r','t','p',' '))
3011 mov_write_udta_sdp(pb, track);
3012 if (track->mode == MODE_MOV) {
3013 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
3014 double sample_aspect_ratio = av_q2d(st->sample_aspect_ratio);
3015 if (st->sample_aspect_ratio.num && 1.0 != sample_aspect_ratio) {
3016 mov_write_tapt_tag(pb, track);
3019 if (is_clcp_track(track) && st->sample_aspect_ratio.num) {
3020 mov_write_tapt_tag(pb, track);
3023 mov_write_track_udta_tag(pb, mov, st);
3024 track->entry = entry_backup;
3025 track->chunkCount = chunk_backup;
3026 return update_size(pb, pos);
3029 static int mov_write_iods_tag(AVIOContext *pb, MOVMuxContext *mov)
3031 int i, has_audio = 0, has_video = 0;
3032 int64_t pos = avio_tell(pb);
3033 int audio_profile = mov->iods_audio_profile;
3034 int video_profile = mov->iods_video_profile;
3035 for (i = 0; i < mov->nb_streams; i++) {
3036 if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
3037 has_audio |= mov->tracks[i].par->codec_type == AVMEDIA_TYPE_AUDIO;
3038 has_video |= mov->tracks[i].par->codec_type == AVMEDIA_TYPE_VIDEO;
3041 if (audio_profile < 0)
3042 audio_profile = 0xFF - has_audio;
3043 if (video_profile < 0)
3044 video_profile = 0xFF - has_video;
3045 avio_wb32(pb, 0x0); /* size */
3046 ffio_wfourcc(pb, "iods");
3047 avio_wb32(pb, 0); /* version & flags */
3048 put_descr(pb, 0x10, 7);
3049 avio_wb16(pb, 0x004f);
3052 avio_w8(pb, audio_profile);
3053 avio_w8(pb, video_profile);
3055 return update_size(pb, pos);
3058 static int mov_write_trex_tag(AVIOContext *pb, MOVTrack *track)
3060 avio_wb32(pb, 0x20); /* size */
3061 ffio_wfourcc(pb, "trex");
3062 avio_wb32(pb, 0); /* version & flags */
3063 avio_wb32(pb, track->track_id); /* track ID */
3064 avio_wb32(pb, 1); /* default sample description index */
3065 avio_wb32(pb, 0); /* default sample duration */
3066 avio_wb32(pb, 0); /* default sample size */
3067 avio_wb32(pb, 0); /* default sample flags */
3071 static int mov_write_mvex_tag(AVIOContext *pb, MOVMuxContext *mov)
3073 int64_t pos = avio_tell(pb);
3075 avio_wb32(pb, 0x0); /* size */
3076 ffio_wfourcc(pb, "mvex");
3077 for (i = 0; i < mov->nb_streams; i++)
3078 mov_write_trex_tag(pb, &mov->tracks[i]);
3079 return update_size(pb, pos);
3082 static int mov_write_mvhd_tag(AVIOContext *pb, MOVMuxContext *mov)
3084 int max_track_id = 1, i;
3085 int64_t max_track_len = 0;
3088 for (i = 0; i < mov->nb_streams; i++) {
3089 if (mov->tracks[i].entry > 0 && mov->tracks[i].timescale) {
3090 int64_t max_track_len_temp = av_rescale_rnd(mov->tracks[i].track_duration,
3092 mov->tracks[i].timescale,
3094 if (max_track_len < max_track_len_temp)
3095 max_track_len = max_track_len_temp;
3096 if (max_track_id < mov->tracks[i].track_id)
3097 max_track_id = mov->tracks[i].track_id;
3100 /* If using delay_moov, make sure the output is the same as if no
3101 * samples had been written yet. */
3102 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
3107 version = max_track_len < UINT32_MAX ? 0 : 1;
3108 avio_wb32(pb, version == 1 ? 120 : 108); /* size */
3110 ffio_wfourcc(pb, "mvhd");
3111 avio_w8(pb, version);
3112 avio_wb24(pb, 0); /* flags */
3114 avio_wb64(pb, mov->time);
3115 avio_wb64(pb, mov->time);
3117 avio_wb32(pb, mov->time); /* creation time */
3118 avio_wb32(pb, mov->time); /* modification time */
3120 avio_wb32(pb, MOV_TIMESCALE);
3121 (version == 1) ? avio_wb64(pb, max_track_len) : avio_wb32(pb, max_track_len); /* duration of longest track */
3123 avio_wb32(pb, 0x00010000); /* reserved (preferred rate) 1.0 = normal */
3124 avio_wb16(pb, 0x0100); /* reserved (preferred volume) 1.0 = normal */
3125 avio_wb16(pb, 0); /* reserved */
3126 avio_wb32(pb, 0); /* reserved */
3127 avio_wb32(pb, 0); /* reserved */
3129 /* Matrix structure */
3130 write_matrix(pb, 1, 0, 0, 1, 0, 0);
3132 avio_wb32(pb, 0); /* reserved (preview time) */
3133 avio_wb32(pb, 0); /* reserved (preview duration) */
3134 avio_wb32(pb, 0); /* reserved (poster time) */
3135 avio_wb32(pb, 0); /* reserved (selection time) */
3136 avio_wb32(pb, 0); /* reserved (selection duration) */
3137 avio_wb32(pb, 0); /* reserved (current time) */
3138 avio_wb32(pb, max_track_id + 1); /* Next track id */
3142 static int mov_write_itunes_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov,
3145 avio_wb32(pb, 33); /* size */
3146 ffio_wfourcc(pb, "hdlr");
3149 ffio_wfourcc(pb, "mdir");
3150 ffio_wfourcc(pb, "appl");
3157 /* helper function to write a data tag with the specified string as data */
3158 static int mov_write_string_data_tag(AVIOContext *pb, const char *data, int lang, int long_style)
3161 int size = 16 + strlen(data);
3162 avio_wb32(pb, size); /* size */
3163 ffio_wfourcc(pb, "data");
3166 avio_write(pb, data, strlen(data));
3170 lang = ff_mov_iso639_to_lang("und", 1);
3171 avio_wb16(pb, strlen(data)); /* string length */
3172 avio_wb16(pb, lang);
3173 avio_write(pb, data, strlen(data));
3174 return strlen(data) + 4;
3178 static int mov_write_string_tag(AVIOContext *pb, const char *name,
3179 const char *value, int lang, int long_style)
3182 if (value && value[0]) {
3183 int64_t pos = avio_tell(pb);
3184 avio_wb32(pb, 0); /* size */
3185 ffio_wfourcc(pb, name);
3186 mov_write_string_data_tag(pb, value, lang, long_style);
3187 size = update_size(pb, pos);
3192 static AVDictionaryEntry *get_metadata_lang(AVFormatContext *s,
3193 const char *tag, int *lang)
3196 AVDictionaryEntry *t, *t2 = NULL;
3201 if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
3204 len = strlen(t->key);
3205 snprintf(tag2, sizeof(tag2), "%s-", tag);
3206 while ((t2 = av_dict_get(s->metadata, tag2, t2, AV_DICT_IGNORE_SUFFIX))) {
3207 len2 = strlen(t2->key);
3208 if (len2 == len + 4 && !strcmp(t->value, t2->value)
3209 && (l = ff_mov_iso639_to_lang(&t2->key[len2 - 3], 1)) >= 0) {
3217 static int mov_write_string_metadata(AVFormatContext *s, AVIOContext *pb,
3218 const char *name, const char *tag,
3222 AVDictionaryEntry *t = get_metadata_lang(s, tag, &lang);
3225 return mov_write_string_tag(pb, name, t->value, lang, long_style);
3228 /* iTunes bpm number */
3229 static int mov_write_tmpo_tag(AVIOContext *pb, AVFormatContext *s)
3231 AVDictionaryEntry *t = av_dict_get(s->metadata, "tmpo", NULL, 0);
3232 int size = 0, tmpo = t ? atoi(t->value) : 0;
3235 avio_wb32(pb, size);
3236 ffio_wfourcc(pb, "tmpo");
3237 avio_wb32(pb, size-8); /* size */
3238 ffio_wfourcc(pb, "data");
3239 avio_wb32(pb, 0x15); //type specifier
3241 avio_wb16(pb, tmpo); // data
3246 /* 3GPP TS 26.244 */
3247 static int mov_write_loci_tag(AVFormatContext *s, AVIOContext *pb)
3250 int64_t pos = avio_tell(pb);
3251 double latitude, longitude, altitude;
3252 int32_t latitude_fix, longitude_fix, altitude_fix;
3253 AVDictionaryEntry *t = get_metadata_lang(s, "location", &lang);
3254 const char *ptr, *place = "";
3256 static const char *astronomical_body = "earth";
3261 longitude = strtod(ptr, &end);
3263 av_log(s, AV_LOG_WARNING, "malformed location metadata\n");
3267 latitude = strtod(ptr, &end);
3269 av_log(s, AV_LOG_WARNING, "malformed location metadata\n");
3273 altitude = strtod(ptr, &end);
3274 /* If no altitude was present, the default 0 should be fine */
3278 latitude_fix = (int32_t) ((1 << 16) * latitude);
3279 longitude_fix = (int32_t) ((1 << 16) * longitude);
3280 altitude_fix = (int32_t) ((1 << 16) * altitude);
3282 avio_wb32(pb, 0); /* size */
3283 ffio_wfourcc(pb, "loci"); /* type */
3284 avio_wb32(pb, 0); /* version + flags */
3285 avio_wb16(pb, lang);
3286 avio_write(pb, place, strlen(place) + 1);
3287 avio_w8(pb, 0); /* role of place (0 == shooting location, 1 == real location, 2 == fictional location) */
3288 avio_wb32(pb, latitude_fix);
3289 avio_wb32(pb, longitude_fix);
3290 avio_wb32(pb, altitude_fix);
3291 avio_write(pb, astronomical_body, strlen(astronomical_body) + 1);
3292 avio_w8(pb, 0); /* additional notes, null terminated string */
3294 return update_size(pb, pos);
3297 /* iTunes track or disc number */
3298 static int mov_write_trkn_tag(AVIOContext *pb, MOVMuxContext *mov,
3299 AVFormatContext *s, int disc)
3301 AVDictionaryEntry *t = av_dict_get(s->metadata,
3302 disc ? "disc" : "track",
3304 int size = 0, track = t ? atoi(t->value) : 0;
3307 char *slash = strchr(t->value, '/');
3309 tracks = atoi(slash + 1);
3310 avio_wb32(pb, 32); /* size */
3311 ffio_wfourcc(pb, disc ? "disk" : "trkn");
3312 avio_wb32(pb, 24); /* size */
3313 ffio_wfourcc(pb, "data");
3314 avio_wb32(pb, 0); // 8 bytes empty
3316 avio_wb16(pb, 0); // empty
3317 avio_wb16(pb, track); // track / disc number
3318 avio_wb16(pb, tracks); // total track / disc number
3319 avio_wb16(pb, 0); // empty
3325 static int mov_write_int8_metadata(AVFormatContext *s, AVIOContext *pb,
3326 const char *name, const char *tag,
3329 AVDictionaryEntry *t = NULL;
3331 int size = 24 + len;
3333 if (len != 1 && len != 4)
3336 if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
3338 num = atoi(t->value);
3340 avio_wb32(pb, size);
3341 ffio_wfourcc(pb, name);
3342 avio_wb32(pb, size - 8);
3343 ffio_wfourcc(pb, "data");
3344 avio_wb32(pb, 0x15);
3346 if (len==4) avio_wb32(pb, num);
3347 else avio_w8 (pb, num);
3352 /* iTunes meta data list */
3353 static int mov_write_ilst_tag(AVIOContext *pb, MOVMuxContext *mov,
3356 int64_t pos = avio_tell(pb);
3357 avio_wb32(pb, 0); /* size */
3358 ffio_wfourcc(pb, "ilst");
3359 mov_write_string_metadata(s, pb, "\251nam", "title" , 1);
3360 mov_write_string_metadata(s, pb, "\251ART", "artist" , 1);
3361 mov_write_string_metadata(s, pb, "aART", "album_artist", 1);
3362 mov_write_string_metadata(s, pb, "\251wrt", "composer" , 1);
3363 mov_write_string_metadata(s, pb, "\251alb", "album" , 1);
3364 mov_write_string_metadata(s, pb, "\251day", "date" , 1);
3365 if (!mov_write_string_metadata(s, pb, "\251too", "encoding_tool", 1)) {
3366 if (!(s->flags & AVFMT_FLAG_BITEXACT))
3367 mov_write_string_tag(pb, "\251too", LIBAVFORMAT_IDENT, 0, 1);
3369 mov_write_string_metadata(s, pb, "\251cmt", "comment" , 1);
3370 mov_write_string_metadata(s, pb, "\251gen", "genre" , 1);
3371 mov_write_string_metadata(s, pb, "\251cpy", "copyright", 1);
3372 mov_write_string_metadata(s, pb, "\251grp", "grouping" , 1);
3373 mov_write_string_metadata(s, pb, "\251lyr", "lyrics" , 1);
3374 mov_write_string_metadata(s, pb, "desc", "description",1);
3375 mov_write_string_metadata(s, pb, "ldes", "synopsis" , 1);
3376 mov_write_string_metadata(s, pb, "tvsh", "show" , 1);
3377 mov_write_string_metadata(s, pb, "tven", "episode_id",1);
3378 mov_write_string_metadata(s, pb, "tvnn", "network" , 1);
3379 mov_write_string_metadata(s, pb, "keyw", "keywords" , 1);
3380 mov_write_int8_metadata (s, pb, "tves", "episode_sort",4);
3381 mov_write_int8_metadata (s, pb, "tvsn", "season_number",4);
3382 mov_write_int8_metadata (s, pb, "stik", "media_type",1);
3383 mov_write_int8_metadata (s, pb, "hdvd", "hd_video", 1);
3384 mov_write_int8_metadata (s, pb, "pgap", "gapless_playback",1);
3385 mov_write_int8_metadata (s, pb, "cpil", "compilation", 1);
3386 mov_write_trkn_tag(pb, mov, s, 0); // track number
3387 mov_write_trkn_tag(pb, mov, s, 1); // disc number
3388 mov_write_tmpo_tag(pb, s);
3389 return update_size(pb, pos);
3392 static int mov_write_mdta_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov,
3395 avio_wb32(pb, 33); /* size */
3396 ffio_wfourcc(pb, "hdlr");
3399 ffio_wfourcc(pb, "mdta");
3407 static int mov_write_mdta_keys_tag(AVIOContext *pb, MOVMuxContext *mov,
3410 AVDictionaryEntry *t = NULL;
3411 int64_t pos = avio_tell(pb);
3412 int64_t curpos, entry_pos;
3415 avio_wb32(pb, 0); /* size */
3416 ffio_wfourcc(pb, "keys");
3418 entry_pos = avio_tell(pb);
3419 avio_wb32(pb, 0); /* entry count */
3421 while (t = av_dict_get(s->metadata, "", t, AV_DICT_IGNORE_SUFFIX)) {
3422 avio_wb32(pb, strlen(t->key) + 8);
3423 ffio_wfourcc(pb, "mdta");
3424 avio_write(pb, t->key, strlen(t->key));
3427 curpos = avio_tell(pb);
3428 avio_seek(pb, entry_pos, SEEK_SET);
3429 avio_wb32(pb, count); // rewrite entry count
3430 avio_seek(pb, curpos, SEEK_SET);
3432 return update_size(pb, pos);
3435 static int mov_write_mdta_ilst_tag(AVIOContext *pb, MOVMuxContext *mov,
3438 AVDictionaryEntry *t = NULL;
3439 int64_t pos = avio_tell(pb);
3440 int count = 1; /* keys are 1-index based */
3442 avio_wb32(pb, 0); /* size */
3443 ffio_wfourcc(pb, "ilst");
3445 while (t = av_dict_get(s->metadata, "", t, AV_DICT_IGNORE_SUFFIX)) {
3446 int64_t entry_pos = avio_tell(pb);
3447 avio_wb32(pb, 0); /* size */
3448 avio_wb32(pb, count); /* key */
3449 mov_write_string_data_tag(pb, t->value, 0, 1);
3450 update_size(pb, entry_pos);
3453 return update_size(pb, pos);
3456 /* meta data tags */
3457 static int mov_write_meta_tag(AVIOContext *pb, MOVMuxContext *mov,
3461 int64_t pos = avio_tell(pb);
3462 avio_wb32(pb, 0); /* size */
3463 ffio_wfourcc(pb, "meta");
3465 if (mov->flags & FF_MOV_FLAG_USE_MDTA) {
3466 mov_write_mdta_hdlr_tag(pb, mov, s);
3467 mov_write_mdta_keys_tag(pb, mov, s);
3468 mov_write_mdta_ilst_tag(pb, mov, s);
3471 /* iTunes metadata tag */
3472 mov_write_itunes_hdlr_tag(pb, mov, s);
3473 mov_write_ilst_tag(pb, mov, s);
3475 size = update_size(pb, pos);
3479 static int mov_write_raw_metadata_tag(AVFormatContext *s, AVIOContext *pb,
3480 const char *name, const char *key)
3483 AVDictionaryEntry *t;
3485 if (!(t = av_dict_get(s->metadata, key, NULL, 0)))
3488 len = strlen(t->value);
3491 avio_wb32(pb, size);
3492 ffio_wfourcc(pb, name);
3493 avio_write(pb, t->value, len);
3499 static int ascii_to_wc(AVIOContext *pb, const uint8_t *b)
3503 GET_UTF8(val, *b++, return -1;)
3506 avio_wb16(pb, 0x00);
3510 static uint16_t language_code(const char *str)
3512 return (((str[0] - 0x60) & 0x1F) << 10) +
3513 (((str[1] - 0x60) & 0x1F) << 5) +
3514 (( str[2] - 0x60) & 0x1F);
3517 static int mov_write_3gp_udta_tag(AVIOContext *pb, AVFormatContext *s,
3518 const char *tag, const char *str)
3520 int64_t pos = avio_tell(pb);
3521 AVDictionaryEntry *t = av_dict_get(s->metadata, str, NULL, 0);
3522 if (!t || !utf8len(t->value))
3524 avio_wb32(pb, 0); /* size */
3525 ffio_wfourcc(pb, tag); /* type */
3526 avio_wb32(pb, 0); /* version + flags */
3527 if (!strcmp(tag, "yrrc"))
3528 avio_wb16(pb, atoi(t->value));
3530 avio_wb16(pb, language_code("eng")); /* language */
3531 avio_write(pb, t->value, strlen(t->value) + 1); /* UTF8 string value */
3532 if (!strcmp(tag, "albm") &&
3533 (t = av_dict_get(s->metadata, "track", NULL, 0)))
3534 avio_w8(pb, atoi(t->value));
3536 return update_size(pb, pos);
3539 static int mov_write_chpl_tag(AVIOContext *pb, AVFormatContext *s)
3541 int64_t pos = avio_tell(pb);
3542 int i, nb_chapters = FFMIN(s->nb_chapters, 255);
3544 avio_wb32(pb, 0); // size
3545 ffio_wfourcc(pb, "chpl");
3546 avio_wb32(pb, 0x01000000); // version + flags
3547 avio_wb32(pb, 0); // unknown
3548 avio_w8(pb, nb_chapters);
3550 for (i = 0; i < nb_chapters; i++) {
3551 AVChapter *c = s->chapters[i];
3552 AVDictionaryEntry *t;
3553 avio_wb64(pb, av_rescale_q(c->start, c->time_base, (AVRational){1,10000000}));
3555 if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
3556 int len = FFMIN(strlen(t->value), 255);
3558 avio_write(pb, t->value, len);
3562 return update_size(pb, pos);
3565 static int mov_write_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
3568 AVIOContext *pb_buf;
3572 ret = avio_open_dyn_buf(&pb_buf);
3576 if (mov->mode & MODE_3GP) {
3577 mov_write_3gp_udta_tag(pb_buf, s, "perf", "artist");
3578 mov_write_3gp_udta_tag(pb_buf, s, "titl", "title");
3579 mov_write_3gp_udta_tag(pb_buf, s, "auth", "author");
3580 mov_write_3gp_udta_tag(pb_buf, s, "gnre", "genre");
3581 mov_write_3gp_udta_tag(pb_buf, s, "dscp", "comment");
3582 mov_write_3gp_udta_tag(pb_buf, s, "albm", "album");
3583 mov_write_3gp_udta_tag(pb_buf, s, "cprt", "copyright");
3584 mov_write_3gp_udta_tag(pb_buf, s, "yrrc", "date");
3585 mov_write_loci_tag(s, pb_buf);
3586 } else if (mov->mode == MODE_MOV && !(mov->flags & FF_MOV_FLAG_USE_MDTA)) { // the title field breaks gtkpod with mp4 and my suspicion is that stuff is not valid in mp4
3587 mov_write_string_metadata(s, pb_buf, "\251ART", "artist", 0);
3588 mov_write_string_metadata(s, pb_buf, "\251nam", "title", 0);
3589 mov_write_string_metadata(s, pb_buf, "\251aut", "author", 0);
3590 mov_write_string_metadata(s, pb_buf, "\251alb", "album", 0);
3591 mov_write_string_metadata(s, pb_buf, "\251day", "date", 0);
3592 mov_write_string_metadata(s, pb_buf, "\251swr", "encoder", 0);
3593 // currently ignored by mov.c
3594 mov_write_string_metadata(s, pb_buf, "\251des", "comment", 0);
3595 // add support for libquicktime, this atom is also actually read by mov.c
3596 mov_write_string_metadata(s, pb_buf, "\251cmt", "comment", 0);
3597 mov_write_string_metadata(s, pb_buf, "\251gen", "genre", 0);
3598 mov_write_string_metadata(s, pb_buf, "\251cpy", "copyright", 0);
3599 mov_write_string_metadata(s, pb_buf, "\251mak", "make", 0);
3600 mov_write_string_metadata(s, pb_buf, "\251mod", "model", 0);
3601 mov_write_string_metadata(s, pb_buf, "\251xyz", "location", 0);
3602 mov_write_string_metadata(s, pb_buf, "\251key", "keywords", 0);
3603 mov_write_raw_metadata_tag(s, pb_buf, "XMP_", "xmp");
3605 /* iTunes meta data */
3606 mov_write_meta_tag(pb_buf, mov, s);
3607 mov_write_loci_tag(s, pb_buf);
3610 if (s->nb_chapters && !(mov->flags & FF_MOV_FLAG_DISABLE_CHPL))
3611 mov_write_chpl_tag(pb_buf, s);
3613 if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) {
3614 avio_wb32(pb, size + 8);
3615 ffio_wfourcc(pb, "udta");
3616 avio_write(pb, buf, size);
3623 static void mov_write_psp_udta_tag(AVIOContext *pb,
3624 const char *str, const char *lang, int type)
3626 int len = utf8len(str) + 1;
3629 avio_wb16(pb, len * 2 + 10); /* size */
3630 avio_wb32(pb, type); /* type */
3631 avio_wb16(pb, language_code(lang)); /* language */
3632 avio_wb16(pb, 0x01); /* ? */
3633 ascii_to_wc(pb, str);
3636 static int mov_write_uuidusmt_tag(AVIOContext *pb, AVFormatContext *s)
3638 AVDictionaryEntry *title = av_dict_get(s->metadata, "title", NULL, 0);
3642 pos = avio_tell(pb);
3643 avio_wb32(pb, 0); /* size placeholder*/
3644 ffio_wfourcc(pb, "uuid");
3645 ffio_wfourcc(pb, "USMT");
3646 avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
3647 avio_wb32(pb, 0xbb88695c);
3648 avio_wb32(pb, 0xfac9c740);
3650 pos2 = avio_tell(pb);
3651 avio_wb32(pb, 0); /* size placeholder*/
3652 ffio_wfourcc(pb, "MTDT");
3656 avio_wb16(pb, 0x0C); /* size */
3657 avio_wb32(pb, 0x0B); /* type */
3658 avio_wb16(pb, language_code("und")); /* language */
3659 avio_wb16(pb, 0x0); /* ? */
3660 avio_wb16(pb, 0x021C); /* data */
3662 if (!(s->flags & AVFMT_FLAG_BITEXACT))
3663 mov_write_psp_udta_tag(pb, LIBAVCODEC_IDENT, "eng", 0x04);
3664 mov_write_psp_udta_tag(pb, title->value, "eng", 0x01);
3665 mov_write_psp_udta_tag(pb, "2006/04/01 11:11:11", "und", 0x03);
3667 update_size(pb, pos2);
3668 return update_size(pb, pos);
3674 static void build_chunks(MOVTrack *trk)
3677 MOVIentry *chunk = &trk->cluster[0];
3678 uint64_t chunkSize = chunk->size;
3679 chunk->chunkNum = 1;
3680 if (trk->chunkCount)
3682 trk->chunkCount = 1;
3683 for (i = 1; i<trk->entry; i++){
3684 if (chunk->pos + chunkSize == trk->cluster[i].pos &&
3685 chunkSize + trk->cluster[i].size < (1<<20)){
3686 chunkSize += trk->cluster[i].size;
3687 chunk->samples_in_chunk += trk->cluster[i].entries;
3689 trk->cluster[i].chunkNum = chunk->chunkNum+1;
3690 chunk=&trk->cluster[i];
3691 chunkSize = chunk->size;
3698 * Assign track ids. If option "use_stream_ids_as_track_ids" is set,
3699 * the stream ids are used as track ids.
3701 * This assumes mov->tracks and s->streams are in the same order and
3702 * there are no gaps in either of them (so mov->tracks[n] refers to
3705 * As an exception, there can be more entries in
3706 * s->streams than in mov->tracks, in which case new track ids are
3707 * generated (starting after the largest found stream id).
3709 static int mov_setup_track_ids(MOVMuxContext *mov, AVFormatContext *s)
3713 if (mov->track_ids_ok)
3716 if (mov->use_stream_ids_as_track_ids) {
3717 int next_generated_track_id = 0;
3718 for (i = 0; i < s->nb_streams; i++) {
3719 if (s->streams[i]->id > next_generated_track_id)
3720 next_generated_track_id = s->streams[i]->id;
3723 for (i = 0; i < mov->nb_streams; i++) {
3724 if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
3727 mov->tracks[i].track_id = i >= s->nb_streams ? ++next_generated_track_id : s->streams[i]->id;
3730 for (i = 0; i < mov->nb_streams; i++) {
3731 if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
3734 mov->tracks[i].track_id = i + 1;
3738 mov->track_ids_ok = 1;
3743 static int mov_write_moov_tag(AVIOContext *pb, MOVMuxContext *mov,
3747 int64_t pos = avio_tell(pb);
3748 avio_wb32(pb, 0); /* size placeholder*/
3749 ffio_wfourcc(pb, "moov");
3751 mov_setup_track_ids(mov, s);
3753 for (i = 0; i < mov->nb_streams; i++) {
3754 if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
3757 mov->tracks[i].time = mov->time;
3759 if (mov->tracks[i].entry)
3760 build_chunks(&mov->tracks[i]);
3763 if (mov->chapter_track)
3764 for (i = 0; i < s->nb_streams; i++) {
3765 mov->tracks[i].tref_tag = MKTAG('c','h','a','p');
3766 mov->tracks[i].tref_id = mov->tracks[mov->chapter_track].track_id;
3768 for (i = 0; i < mov->nb_streams; i++) {
3769 MOVTrack *track = &mov->tracks[i];
3770 if (track->tag == MKTAG('r','t','p',' ')) {
3771 track->tref_tag = MKTAG('h','i','n','t');
3772 track->tref_id = mov->tracks[track->src_track].track_id;
3773 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
3774 int * fallback, size;
3775 fallback = (int*)av_stream_get_side_data(track->st,
3776 AV_PKT_DATA_FALLBACK_TRACK,
3778 if (fallback != NULL && size == sizeof(int)) {
3779 if (*fallback >= 0 && *fallback < mov->nb_streams) {
3780 track->tref_tag = MKTAG('f','a','l','l');
3781 track->tref_id = mov->tracks[*fallback].track_id;
3786 for (i = 0; i < mov->nb_streams; i++) {
3787 if (mov->tracks[i].tag == MKTAG('t','m','c','d')) {
3788 int src_trk = mov->tracks[i].src_track;
3789 mov->tracks[src_trk].tref_tag = mov->tracks[i].tag;
3790 mov->tracks[src_trk].tref_id = mov->tracks[i].track_id;
3791 //src_trk may have a different timescale than the tmcd track
3792 mov->tracks[i].track_duration = av_rescale(mov->tracks[src_trk].track_duration,
3793 mov->tracks[i].timescale,
3794 mov->tracks[src_trk].timescale);
3798 mov_write_mvhd_tag(pb, mov);
3799 if (mov->mode != MODE_MOV && !mov->iods_skip)
3800 mov_write_iods_tag(pb, mov);
3801 for (i = 0; i < mov->nb_streams; i++) {
3802 if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_FRAGMENT) {
3803 int ret = mov_write_trak_tag(s, pb, mov, &(mov->tracks[i]), i < s->nb_streams ? s->streams[i] : NULL);
3808 if (mov->flags & FF_MOV_FLAG_FRAGMENT)
3809 mov_write_mvex_tag(pb, mov); /* QuickTime requires trak to precede this */
3811 if (mov->mode == MODE_PSP)
3812 mov_write_uuidusmt_tag(pb, s);
3814 mov_write_udta_tag(pb, mov, s);
3816 return update_size(pb, pos);
3819 static void param_write_int(AVIOContext *pb, const char *name, int value)
3821 avio_printf(pb, "<param name=\"%s\" value=\"%d\" valuetype=\"data\"/>\n", name, value);
3824 static void param_write_string(AVIOContext *pb, const char *name, const char *value)
3826 avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, value);
3829 static void param_write_hex(AVIOContext *pb, const char *name, const uint8_t *value, int len)
3832 len = FFMIN(sizeof(buf) / 2 - 1, len);
3833 ff_data_to_hex(buf, value, len, 0);
3834 buf[2 * len] = '\0';
3835 avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, buf);
3838 static int mov_write_isml_manifest(AVIOContext *pb, MOVMuxContext *mov, AVFormatContext *s)
3840 int64_t pos = avio_tell(pb);
3842 int64_t manifest_bit_rate = 0;
3843 AVCPBProperties *props = NULL;
3845 static const uint8_t uuid[] = {
3846 0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd,
3847 0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66
3851 ffio_wfourcc(pb, "uuid");
3852 avio_write(pb, uuid, sizeof(uuid));
3855 avio_printf(pb, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
3856 avio_printf(pb, "<smil xmlns=\"http://www.w3.org/2001/SMIL20/Language\">\n");
3857 avio_printf(pb, "<head>\n");
3858 if (!(mov->fc->flags & AVFMT_FLAG_BITEXACT))
3859 avio_printf(pb, "<meta name=\"creator\" content=\"%s\" />\n",
3861 avio_printf(pb, "</head>\n");
3862 avio_printf(pb, "<body>\n");
3863 avio_printf(pb, "<switch>\n");
3865 mov_setup_track_ids(mov, s);
3867 for (i = 0; i < mov->nb_streams; i++) {
3868 MOVTrack *track = &mov->tracks[i];
3870 int track_id = track->track_id;
3871 char track_name_buf[32] = { 0 };
3873 AVStream *st = track->st;
3874 AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0);
3876 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
3878 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
3884 props = (AVCPBProperties*)av_stream_get_side_data(track->st, AV_PKT_DATA_CPB_PROPERTIES, NULL);
3886 if (track->par->bit_rate) {
3887 manifest_bit_rate = track->par->bit_rate;
3889 manifest_bit_rate = props->max_bitrate;
3892 avio_printf(pb, "<%s systemBitrate=\"%"PRId64"\">\n", type,
3894 param_write_int(pb, "systemBitrate", manifest_bit_rate);
3895 param_write_int(pb, "trackID", track_id);
3896 param_write_string(pb, "systemLanguage", lang ? lang->value : "und");
3898 /* Build track name piece by piece: */
3900 av_strlcat(track_name_buf, type, sizeof(track_name_buf));
3901 /* 2. track language, if available */
3903 av_strlcatf(track_name_buf, sizeof(track_name_buf),
3904 "_%s", lang->value);
3905 /* 3. special type suffix */
3906 /* "_cc" = closed captions, "_ad" = audio_description */
3907 if (st->disposition & AV_DISPOSITION_HEARING_IMPAIRED)
3908 av_strlcat(track_name_buf, "_cc", sizeof(track_name_buf));
3909 else if (st->disposition & AV_DISPOSITION_VISUAL_IMPAIRED)
3910 av_strlcat(track_name_buf, "_ad", sizeof(track_name_buf));
3912 param_write_string(pb, "trackName", track_name_buf);
3914 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
3915 if (track->par->codec_id == AV_CODEC_ID_H264) {
3917 int size = track->par->extradata_size;
3918 if (!ff_avc_write_annexb_extradata(track->par->extradata, &ptr,
3920 param_write_hex(pb, "CodecPrivateData",
3921 ptr ? ptr : track->par->extradata,
3925 param_write_string(pb, "FourCC", "H264");
3926 } else if (track->par->codec_id == AV_CODEC_ID_VC1) {
3927 param_write_string(pb, "FourCC", "WVC1");
3928 param_write_hex(pb, "CodecPrivateData", track->par->extradata,
3929 track->par->extradata_size);
3931 param_write_int(pb, "MaxWidth", track->par->width);
3932 param_write_int(pb, "MaxHeight", track->par->height);
3933 param_write_int(pb, "DisplayWidth", track->par->width);
3934 param_write_int(pb, "DisplayHeight", track->par->height);
3936 if (track->par->codec_id == AV_CODEC_ID_AAC) {
3937 switch (track->par->profile)
3939 case FF_PROFILE_AAC_HE_V2:
3940 param_write_string(pb, "FourCC", "AACP");
3942 case FF_PROFILE_AAC_HE:
3943 param_write_string(pb, "FourCC", "AACH");
3946 param_write_string(pb, "FourCC", "AACL");
3948 } else if (track->par->codec_id == AV_CODEC_ID_WMAPRO) {
3949 param_write_string(pb, "FourCC", "WMAP");
3951 param_write_hex(pb, "CodecPrivateData", track->par->extradata,
3952 track->par->extradata_size);
3953 param_write_int(pb, "AudioTag", ff_codec_get_tag(ff_codec_wav_tags,
3954 track->par->codec_id));
3955 param_write_int(pb, "Channels", track->par->channels);
3956 param_write_int(pb, "SamplingRate", track->par->sample_rate);
3957 param_write_int(pb, "BitsPerSample", 16);
3958 param_write_int(pb, "PacketSize", track->par->block_align ?
3959 track->par->block_align : 4);
3961 avio_printf(pb, "</%s>\n", type);
3963 avio_printf(pb, "</switch>\n");
3964 avio_printf(pb, "</body>\n");
3965 avio_printf(pb, "</smil>\n");
3967 return update_size(pb, pos);
3970 static int mov_write_mfhd_tag(AVIOContext *pb, MOVMuxContext *mov)
3973 ffio_wfourcc(pb, "mfhd");
3975 avio_wb32(pb, mov->fragments);
3979 static uint32_t get_sample_flags(MOVTrack *track, MOVIentry *entry)
3981 return entry->flags & MOV_SYNC_SAMPLE ? MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO :
3982 (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC);
3985 static int mov_write_tfhd_tag(AVIOContext *pb, MOVMuxContext *mov,
3986 MOVTrack *track, int64_t moof_offset)
3988 int64_t pos = avio_tell(pb);
3989 uint32_t flags = MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
3990 MOV_TFHD_BASE_DATA_OFFSET;
3991 if (!track->entry) {
3992 flags |= MOV_TFHD_DURATION_IS_EMPTY;
3994 flags |= MOV_TFHD_DEFAULT_FLAGS;
3996 if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET)
3997 flags &= ~MOV_TFHD_BASE_DATA_OFFSET;
3998 if (mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) {
3999 flags &= ~MOV_TFHD_BASE_DATA_OFFSET;
4000 flags |= MOV_TFHD_DEFAULT_BASE_IS_MOOF;
4003 /* Don't set a default sample size, the silverlight player refuses
4004 * to play files with that set. Don't set a default sample duration,
4005 * WMP freaks out if it is set. Don't set a base data offset, PIFF
4006 * file format says it MUST NOT be set. */
4007 if (track->mode == MODE_ISM)
4008 flags &= ~(MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
4009 MOV_TFHD_BASE_DATA_OFFSET);
4011 avio_wb32(pb, 0); /* size placeholder */
4012 ffio_wfourcc(pb, "tfhd");
4013 avio_w8(pb, 0); /* version */
4014 avio_wb24(pb, flags);
4016 avio_wb32(pb, track->track_id); /* track-id */
4017 if (flags & MOV_TFHD_BASE_DATA_OFFSET)
4018 avio_wb64(pb, moof_offset);
4019 if (flags & MOV_TFHD_DEFAULT_DURATION) {
4020 track->default_duration = get_cluster_duration(track, 0);
4021 avio_wb32(pb, track->default_duration);
4023 if (flags & MOV_TFHD_DEFAULT_SIZE) {
4024 track->default_size = track->entry ? track->cluster[0].size : 1;
4025 avio_wb32(pb, track->default_size);
4027 track->default_size = -1;
4029 if (flags & MOV_TFHD_DEFAULT_FLAGS) {
4030 /* Set the default flags based on the second sample, if available.
4031 * If the first sample is different, that can be signaled via a separate field. */
4032 if (track->entry > 1)
4033 track->default_sample_flags = get_sample_flags(track, &track->cluster[1]);
4035 track->default_sample_flags =
4036 track->par->codec_type == AVMEDIA_TYPE_VIDEO ?
4037 (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC) :
4038 MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO;
4039 avio_wb32(pb, track->default_sample_flags);
4042 return update_size(pb, pos);
4045 static int mov_write_trun_tag(AVIOContext *pb, MOVMuxContext *mov,
4046 MOVTrack *track, int moof_size,
4049 int64_t pos = avio_tell(pb);
4050 uint32_t flags = MOV_TRUN_DATA_OFFSET;
4053 for (i = first; i < end; i++) {
4054 if (get_cluster_duration(track, i) != track->default_duration)
4055 flags |= MOV_TRUN_SAMPLE_DURATION;
4056 if (track->cluster[i].size != track->default_size)
4057 flags |= MOV_TRUN_SAMPLE_SIZE;
4058 if (i > first && get_sample_flags(track, &track->cluster[i]) != track->default_sample_flags)
4059 flags |= MOV_TRUN_SAMPLE_FLAGS;
4061 if (!(flags & MOV_TRUN_SAMPLE_FLAGS) && track->entry > 0 &&
4062 get_sample_flags(track, &track->cluster[0]) != track->default_sample_flags)
4063 flags |= MOV_TRUN_FIRST_SAMPLE_FLAGS;
4064 if (track->flags & MOV_TRACK_CTTS)
4065 flags |= MOV_TRUN_SAMPLE_CTS;
4067 avio_wb32(pb, 0); /* size placeholder */
4068 ffio_wfourcc(pb, "trun");
4069 if (mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS)
4070 avio_w8(pb, 1); /* version */
4072 avio_w8(pb, 0); /* version */
4073 avio_wb24(pb, flags);
4075 avio_wb32(pb, end - first); /* sample count */
4076 if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET &&
4077 !(mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) &&
4079 avio_wb32(pb, 0); /* Later tracks follow immediately after the previous one */
4081 avio_wb32(pb, moof_size + 8 + track->data_offset +
4082 track->cluster[first].pos); /* data offset */
4083 if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS)
4084 avio_wb32(pb, get_sample_flags(track, &track->cluster[first]));
4086 for (i = first; i < end; i++) {
4087 if (flags & MOV_TRUN_SAMPLE_DURATION)
4088 avio_wb32(pb, get_cluster_duration(track, i));
4089 if (flags & MOV_TRUN_SAMPLE_SIZE)
4090 avio_wb32(pb, track->cluster[i].size);
4091 if (flags & MOV_TRUN_SAMPLE_FLAGS)
4092 avio_wb32(pb, get_sample_flags(track, &track->cluster[i]));
4093 if (flags & MOV_TRUN_SAMPLE_CTS)
4094 avio_wb32(pb, track->cluster[i].cts);
4097 mov->first_trun = 0;
4098 return update_size(pb, pos);
4101 static int mov_write_tfxd_tag(AVIOContext *pb, MOVTrack *track)
4103 int64_t pos = avio_tell(pb);
4104 static const uint8_t uuid[] = {
4105 0x6d, 0x1d, 0x9b, 0x05, 0x42, 0xd5, 0x44, 0xe6,
4106 0x80, 0xe2, 0x14, 0x1d, 0xaf, 0xf7, 0x57, 0xb2
4109 avio_wb32(pb, 0); /* size placeholder */
4110 ffio_wfourcc(pb, "uuid");
4111 avio_write(pb, uuid, sizeof(uuid));
4114 avio_wb64(pb, track->start_dts + track->frag_start +
4115 track->cluster[0].cts);
4116 avio_wb64(pb, track->end_pts -
4117 (track->cluster[0].dts + track->cluster[0].cts));
4119 return update_size(pb, pos);
4122 static int mov_write_tfrf_tag(AVIOContext *pb, MOVMuxContext *mov,
4123 MOVTrack *track, int entry)
4125 int n = track->nb_frag_info - 1 - entry, i;
4126 int size = 8 + 16 + 4 + 1 + 16*n;
4127 static const uint8_t uuid[] = {
4128 0xd4, 0x80, 0x7e, 0xf2, 0xca, 0x39, 0x46, 0x95,
4129 0x8e, 0x54, 0x26, 0xcb, 0x9e, 0x46, 0xa7, 0x9f
4135 avio_seek(pb, track->frag_info[entry].tfrf_offset, SEEK_SET);
4136 avio_wb32(pb, size);
4137 ffio_wfourcc(pb, "uuid");
4138 avio_write(pb, uuid, sizeof(uuid));
4142 for (i = 0; i < n; i++) {
4143 int index = entry + 1 + i;
4144 avio_wb64(pb, track->frag_info[index].time);
4145 avio_wb64(pb, track->frag_info[index].duration);
4147 if (n < mov->ism_lookahead) {
4148 int free_size = 16 * (mov->ism_lookahead - n);
4149 avio_wb32(pb, free_size);
4150 ffio_wfourcc(pb, "free");
4151 ffio_fill(pb, 0, free_size - 8);
4157 static int mov_write_tfrf_tags(AVIOContext *pb, MOVMuxContext *mov,
4160 int64_t pos = avio_tell(pb);
4162 for (i = 0; i < mov->ism_lookahead; i++) {
4163 /* Update the tfrf tag for the last ism_lookahead fragments,
4164 * nb_frag_info - 1 is the next fragment to be written. */
4165 mov_write_tfrf_tag(pb, mov, track, track->nb_frag_info - 2 - i);
4167 avio_seek(pb, pos, SEEK_SET);
4171 static int mov_add_tfra_entries(AVIOContext *pb, MOVMuxContext *mov, int tracks,
4175 for (i = 0; i < mov->nb_streams; i++) {
4176 MOVTrack *track = &mov->tracks[i];
4177 MOVFragmentInfo *info;
4178 if ((tracks >= 0 && i != tracks) || !track->entry)
4180 track->nb_frag_info++;
4181 if (track->nb_frag_info >= track->frag_info_capacity) {
4182 unsigned new_capacity = track->nb_frag_info + MOV_FRAG_INFO_ALLOC_INCREMENT;
4183 if (av_reallocp_array(&track->frag_info,
4185 sizeof(*track->frag_info)))
4186 return AVERROR(ENOMEM);
4187 track->frag_info_capacity = new_capacity;
4189 info = &track->frag_info[track->nb_frag_info - 1];
4190 info->offset = avio_tell(pb);
4192 // Try to recreate the original pts for the first packet
4193 // from the fields we have stored
4194 info->time = track->start_dts + track->frag_start +
4195 track->cluster[0].cts;
4196 info->duration = track->end_pts -
4197 (track->cluster[0].dts + track->cluster[0].cts);
4198 // If the pts is less than zero, we will have trimmed
4199 // away parts of the media track using an edit list,
4200 // and the corresponding start presentation time is zero.
4201 if (info->time < 0) {
4202 info->duration += info->time;
4205 info->tfrf_offset = 0;
4206 mov_write_tfrf_tags(pb, mov, track);
4211 static void mov_prune_frag_info(MOVMuxContext *mov, int tracks, int max)
4214 for (i = 0; i < mov->nb_streams; i++) {
4215 MOVTrack *track = &mov->tracks[i];
4216 if ((tracks >= 0 && i != tracks) || !track->entry)
4218 if (track->nb_frag_info > max) {
4219 memmove(track->frag_info, track->frag_info + (track->nb_frag_info - max), max * sizeof(*track->frag_info));
4220 track->nb_frag_info = max;
4225 static int mov_write_tfdt_tag(AVIOContext *pb, MOVTrack *track)
4227 int64_t pos = avio_tell(pb);
4229 avio_wb32(pb, 0); /* size */
4230 ffio_wfourcc(pb, "tfdt");
4231 avio_w8(pb, 1); /* version */
4233 avio_wb64(pb, track->frag_start);
4234 return update_size(pb, pos);
4237 static int mov_write_traf_tag(AVIOContext *pb, MOVMuxContext *mov,
4238 MOVTrack *track, int64_t moof_offset,
4241 int64_t pos = avio_tell(pb);
4243 avio_wb32(pb, 0); /* size placeholder */
4244 ffio_wfourcc(pb, "traf");
4246 mov_write_tfhd_tag(pb, mov, track, moof_offset);
4247 if (mov->mode != MODE_ISM)
4248 mov_write_tfdt_tag(pb, track);
4249 for (i = 1; i < track->entry; i++) {
4250 if (track->cluster[i].pos != track->cluster[i - 1].pos + track->cluster[i - 1].size) {
4251 mov_write_trun_tag(pb, mov, track, moof_size, start, i);
4255 mov_write_trun_tag(pb, mov, track, moof_size, start, track->entry);
4256 if (mov->mode == MODE_ISM) {
4257 mov_write_tfxd_tag(pb, track);
4259 if (mov->ism_lookahead) {
4260 int i, size = 16 + 4 + 1 + 16 * mov->ism_lookahead;
4262 if (track->nb_frag_info > 0) {
4263 MOVFragmentInfo *info = &track->frag_info[track->nb_frag_info - 1];
4264 if (!info->tfrf_offset)
4265 info->tfrf_offset = avio_tell(pb);
4267 avio_wb32(pb, 8 + size);
4268 ffio_wfourcc(pb, "free");
4269 for (i = 0; i < size; i++)
4274 return update_size(pb, pos);
4277 static int mov_write_moof_tag_internal(AVIOContext *pb, MOVMuxContext *mov,
4278 int tracks, int moof_size)
4280 int64_t pos = avio_tell(pb);
4283 avio_wb32(pb, 0); /* size placeholder */
4284 ffio_wfourcc(pb, "moof");
4285 mov->first_trun = 1;
4287 mov_write_mfhd_tag(pb, mov);
4288 for (i = 0; i < mov->nb_streams; i++) {
4289 MOVTrack *track = &mov->tracks[i];
4290 if (tracks >= 0 && i != tracks)
4294 mov_write_traf_tag(pb, mov, track, pos, moof_size);
4297 return update_size(pb, pos);
4300 static int mov_write_sidx_tag(AVIOContext *pb,
4301 MOVTrack *track, int ref_size, int total_sidx_size)
4303 int64_t pos = avio_tell(pb), offset_pos, end_pos;
4304 int64_t presentation_time, duration, offset;
4305 int starts_with_SAP, i, entries;
4309 presentation_time = track->start_dts + track->frag_start +
4310 track->cluster[0].cts;
4311 duration = track->end_pts -
4312 (track->cluster[0].dts + track->cluster[0].cts);
4313 starts_with_SAP = track->cluster[0].flags & MOV_SYNC_SAMPLE;
4315 // pts<0 should be cut away using edts
4316 if (presentation_time < 0) {
4317 duration += presentation_time;
4318 presentation_time = 0;
4321 entries = track->nb_frag_info;
4324 presentation_time = track->frag_info[0].time;
4327 avio_wb32(pb, 0); /* size */
4328 ffio_wfourcc(pb, "sidx");
4329 avio_w8(pb, 1); /* version */
4331 avio_wb32(pb, track->track_id); /* reference_ID */
4332 avio_wb32(pb, track->timescale); /* timescale */
4333 avio_wb64(pb, presentation_time); /* earliest_presentation_time */
4334 offset_pos = avio_tell(pb);
4335 avio_wb64(pb, 0); /* first_offset (offset to referenced moof) */
4336 avio_wb16(pb, 0); /* reserved */
4338 avio_wb16(pb, entries); /* reference_count */
4339 for (i = 0; i < entries; i++) {
4340 if (!track->entry) {
4341 if (i > 1 && track->frag_info[i].offset != track->frag_info[i - 1].offset + track->frag_info[i - 1].size) {
4342 av_log(NULL, AV_LOG_ERROR, "Non-consecutive fragments, writing incorrect sidx\n");
4344 duration = track->frag_info[i].duration;
4345 ref_size = track->frag_info[i].size;
4346 starts_with_SAP = 1;
4348 avio_wb32(pb, (0 << 31) | (ref_size & 0x7fffffff)); /* reference_type (0 = media) | referenced_size */
4349 avio_wb32(pb, duration); /* subsegment_duration */
4350 avio_wb32(pb, (starts_with_SAP << 31) | (0 << 28) | 0); /* starts_with_SAP | SAP_type | SAP_delta_time */
4353 end_pos = avio_tell(pb);
4354 offset = pos + total_sidx_size - end_pos;
4355 avio_seek(pb, offset_pos, SEEK_SET);
4356 avio_wb64(pb, offset);
4357 avio_seek(pb, end_pos, SEEK_SET);
4358 return update_size(pb, pos);
4361 static int mov_write_sidx_tags(AVIOContext *pb, MOVMuxContext *mov,
4362 int tracks, int ref_size)
4365 AVIOContext *avio_buf;
4367 for (round = 0; round < 2; round++) {
4368 // First run one round to calculate the total size of all
4370 // This would be much simpler if we'd only write one sidx
4371 // atom, for the first track in the moof.
4373 if ((ret = ffio_open_null_buf(&avio_buf)) < 0)
4378 for (i = 0; i < mov->nb_streams; i++) {
4379 MOVTrack *track = &mov->tracks[i];
4380 if (tracks >= 0 && i != tracks)
4382 // When writing a sidx for the full file, entry is 0, but
4383 // we want to include all tracks. ref_size is 0 in this case,
4384 // since we read it from frag_info instead.
4385 if (!track->entry && ref_size > 0)
4387 total_size -= mov_write_sidx_tag(avio_buf, track, ref_size,
4391 total_size = ffio_close_null_buf(avio_buf);
4396 static int mov_write_moof_tag(AVIOContext *pb, MOVMuxContext *mov, int tracks,
4399 AVIOContext *avio_buf;
4402 if ((ret = ffio_open_null_buf(&avio_buf)) < 0)
4404 mov_write_moof_tag_internal(avio_buf, mov, tracks, 0);
4405 moof_size = ffio_close_null_buf(avio_buf);
4407 if (mov->flags & FF_MOV_FLAG_DASH && !(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX))
4408 mov_write_sidx_tags(pb, mov, tracks, moof_size + 8 + mdat_size);
4410 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX ||
4411 !(mov->flags & FF_MOV_FLAG_SKIP_TRAILER) ||
4412 mov->ism_lookahead) {
4413 if ((ret = mov_add_tfra_entries(pb, mov, tracks, moof_size + 8 + mdat_size)) < 0)
4415 if (!(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) &&
4416 mov->flags & FF_MOV_FLAG_SKIP_TRAILER) {
4417 mov_prune_frag_info(mov, tracks, mov->ism_lookahead + 1);
4421 return mov_write_moof_tag_internal(pb, mov, tracks, moof_size);
4424 static int mov_write_tfra_tag(AVIOContext *pb, MOVTrack *track)
4426 int64_t pos = avio_tell(pb);
4429 avio_wb32(pb, 0); /* size placeholder */
4430 ffio_wfourcc(pb, "tfra");
4431 avio_w8(pb, 1); /* version */
4434 avio_wb32(pb, track->track_id);
4435 avio_wb32(pb, 0); /* length of traf/trun/sample num */
4436 avio_wb32(pb, track->nb_frag_info);
4437 for (i = 0; i < track->nb_frag_info; i++) {
4438 avio_wb64(pb, track->frag_info[i].time);
4439 avio_wb64(pb, track->frag_info[i].offset + track->data_offset);
4440 avio_w8(pb, 1); /* traf number */
4441 avio_w8(pb, 1); /* trun number */
4442 avio_w8(pb, 1); /* sample number */
4445 return update_size(pb, pos);
4448 static int mov_write_mfra_tag(AVIOContext *pb, MOVMuxContext *mov)
4450 int64_t pos = avio_tell(pb);
4453 avio_wb32(pb, 0); /* size placeholder */
4454 ffio_wfourcc(pb, "mfra");
4455 /* An empty mfra atom is enough to indicate to the publishing point that
4456 * the stream has ended. */
4457 if (mov->flags & FF_MOV_FLAG_ISML)
4458 return update_size(pb, pos);
4460 for (i = 0; i < mov->nb_streams; i++) {
4461 MOVTrack *track = &mov->tracks[i];
4462 if (track->nb_frag_info)
4463 mov_write_tfra_tag(pb, track);
4467 ffio_wfourcc(pb, "mfro");
4468 avio_wb32(pb, 0); /* version + flags */
4469 avio_wb32(pb, avio_tell(pb) + 4 - pos);
4471 return update_size(pb, pos);
4474 static int mov_write_mdat_tag(AVIOContext *pb, MOVMuxContext *mov)
4476 avio_wb32(pb, 8); // placeholder for extended size field (64 bit)
4477 ffio_wfourcc(pb, mov->mode == MODE_MOV ? "wide" : "free");
4479 mov->mdat_pos = avio_tell(pb);
4480 avio_wb32(pb, 0); /* size placeholder*/
4481 ffio_wfourcc(pb, "mdat");
4485 /* TODO: This needs to be more general */
4486 static int mov_write_ftyp_tag(AVIOContext *pb, AVFormatContext *s)
4488 MOVMuxContext *mov = s->priv_data;
4489 int64_t pos = avio_tell(pb);
4490 int has_h264 = 0, has_video = 0;
4494 for (i = 0; i < s->nb_streams; i++) {
4495 AVStream *st = s->streams[i];
4496 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
4498 if (st->codecpar->codec_id == AV_CODEC_ID_H264)
4502 avio_wb32(pb, 0); /* size */
4503 ffio_wfourcc(pb, "ftyp");
4505 if (mov->major_brand && strlen(mov->major_brand) >= 4)
4506 ffio_wfourcc(pb, mov->major_brand);
4507 else if (mov->mode == MODE_3GP) {
4508 ffio_wfourcc(pb, has_h264 ? "3gp6" : "3gp4");
4509 minor = has_h264 ? 0x100 : 0x200;
4510 } else if (mov->mode & MODE_3G2) {
4511 ffio_wfourcc(pb, has_h264 ? "3g2b" : "3g2a");
4512 minor = has_h264 ? 0x20000 : 0x10000;
4513 } else if (mov->mode == MODE_PSP)
4514 ffio_wfourcc(pb, "MSNV");
4515 else if (mov->mode == MODE_MP4 && mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)
4516 ffio_wfourcc(pb, "iso5"); // Required when using default-base-is-moof
4517 else if (mov->mode == MODE_MP4 && mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS)
4518 ffio_wfourcc(pb, "iso4");
4519 else if (mov->mode == MODE_MP4)
4520 ffio_wfourcc(pb, "isom");
4521 else if (mov->mode == MODE_IPOD)
4522 ffio_wfourcc(pb, has_video ? "M4V ":"M4A ");
4523 else if (mov->mode == MODE_ISM)
4524 ffio_wfourcc(pb, "isml");
4525 else if (mov->mode == MODE_F4V)
4526 ffio_wfourcc(pb, "f4v ");
4528 ffio_wfourcc(pb, "qt ");
4530 avio_wb32(pb, minor);
4532 if (mov->mode == MODE_MOV)
4533 ffio_wfourcc(pb, "qt ");
4534 else if (mov->mode == MODE_ISM) {
4535 ffio_wfourcc(pb, "piff");
4536 } else if (!(mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)) {
4537 ffio_wfourcc(pb, "isom");
4538 ffio_wfourcc(pb, "iso2");
4540 ffio_wfourcc(pb, "avc1");
4543 // We add tfdt atoms when fragmenting, signal this with the iso6 compatible
4544 // brand. This is compatible with users that don't understand tfdt.
4545 if (mov->flags & FF_MOV_FLAG_FRAGMENT && mov->mode != MODE_ISM)
4546 ffio_wfourcc(pb, "iso6");
4548 if (mov->mode == MODE_3GP)
4549 ffio_wfourcc(pb, has_h264 ? "3gp6":"3gp4");
4550 else if (mov->mode & MODE_3G2)
4551 ffio_wfourcc(pb, has_h264 ? "3g2b":"3g2a");
4552 else if (mov->mode == MODE_PSP)
4553 ffio_wfourcc(pb, "MSNV");
4554 else if (mov->mode == MODE_MP4)
4555 ffio_wfourcc(pb, "mp41");
4557 if (mov->flags & FF_MOV_FLAG_DASH && mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
4558 ffio_wfourcc(pb, "dash");
4560 return update_size(pb, pos);
4563 static int mov_write_uuidprof_tag(AVIOContext *pb, AVFormatContext *s)
4565 AVStream *video_st = s->streams[0];
4566 AVCodecParameters *video_par = s->streams[0]->codecpar;
4567 AVCodecParameters *audio_par = s->streams[1]->codecpar;
4568 int audio_rate = audio_par->sample_rate;
4569 int64_t frame_rate = video_st->avg_frame_rate.den ?
4570 (video_st->avg_frame_rate.num * 0x10000LL) / video_st->avg_frame_rate.den :
4572 int audio_kbitrate = audio_par->bit_rate / 1000;
4573 int video_kbitrate = FFMIN(video_par->bit_rate / 1000, 800 - audio_kbitrate);
4575 if (frame_rate < 0 || frame_rate > INT32_MAX) {
4576 av_log(s, AV_LOG_ERROR, "Frame rate %f outside supported range\n", frame_rate / (double)0x10000);
4577 return AVERROR(EINVAL);
4580 avio_wb32(pb, 0x94); /* size */
4581 ffio_wfourcc(pb, "uuid");
4582 ffio_wfourcc(pb, "PROF");
4584 avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
4585 avio_wb32(pb, 0xbb88695c);
4586 avio_wb32(pb, 0xfac9c740);
4588 avio_wb32(pb, 0x0); /* ? */
4589 avio_wb32(pb, 0x3); /* 3 sections ? */
4591 avio_wb32(pb, 0x14); /* size */
4592 ffio_wfourcc(pb, "FPRF");
4593 avio_wb32(pb, 0x0); /* ? */
4594 avio_wb32(pb, 0x0); /* ? */
4595 avio_wb32(pb, 0x0); /* ? */
4597 avio_wb32(pb, 0x2c); /* size */
4598 ffio_wfourcc(pb, "APRF"); /* audio */
4600 avio_wb32(pb, 0x2); /* TrackID */
4601 ffio_wfourcc(pb, "mp4a");
4602 avio_wb32(pb, 0x20f);
4604 avio_wb32(pb, audio_kbitrate);
4605 avio_wb32(pb, audio_kbitrate);
4606 avio_wb32(pb, audio_rate);
4607 avio_wb32(pb, audio_par->channels);
4609 avio_wb32(pb, 0x34); /* size */
4610 ffio_wfourcc(pb, "VPRF"); /* video */
4612 avio_wb32(pb, 0x1); /* TrackID */
4613 if (video_par->codec_id == AV_CODEC_ID_H264) {
4614 ffio_wfourcc(pb, "avc1");
4615 avio_wb16(pb, 0x014D);
4616 avio_wb16(pb, 0x0015);
4618 ffio_wfourcc(pb, "mp4v");
4619 avio_wb16(pb, 0x0000);
4620 avio_wb16(pb, 0x0103);
4623 avio_wb32(pb, video_kbitrate);
4624 avio_wb32(pb, video_kbitrate);
4625 avio_wb32(pb, frame_rate);
4626 avio_wb32(pb, frame_rate);
4627 avio_wb16(pb, video_par->width);
4628 avio_wb16(pb, video_par->height);
4629 avio_wb32(pb, 0x010001); /* ? */
4634 static int mov_write_identification(AVIOContext *pb, AVFormatContext *s)
4636 MOVMuxContext *mov = s->priv_data;
4639 mov_write_ftyp_tag(pb,s);
4640 if (mov->mode == MODE_PSP) {
4641 int video_streams_nb = 0, audio_streams_nb = 0, other_streams_nb = 0;
4642 for (i = 0; i < s->nb_streams; i++) {
4643 AVStream *st = s->streams[i];
4644 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
4646 else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
4652 if (video_streams_nb != 1 || audio_streams_nb != 1 || other_streams_nb) {
4653 av_log(s, AV_LOG_ERROR, "PSP mode need one video and one audio stream\n");
4654 return AVERROR(EINVAL);
4656 return mov_write_uuidprof_tag(pb, s);
4661 static int mov_parse_mpeg2_frame(AVPacket *pkt, uint32_t *flags)
4664 int i, closed_gop = 0;
4666 for (i = 0; i < pkt->size - 4; i++) {
4667 c = (c << 8) + pkt->data[i];
4668 if (c == 0x1b8) { // gop
4669 closed_gop = pkt->data[i + 4] >> 6 & 0x01;
4670 } else if (c == 0x100) { // pic
4671 int temp_ref = (pkt->data[i + 1] << 2) | (pkt->data[i + 2] >> 6);
4672 if (!temp_ref || closed_gop) // I picture is not reordered
4673 *flags = MOV_SYNC_SAMPLE;
4675 *flags = MOV_PARTIAL_SYNC_SAMPLE;
4682 static void mov_parse_vc1_frame(AVPacket *pkt, MOVTrack *trk)
4684 const uint8_t *start, *next, *end = pkt->data + pkt->size;
4685 int seq = 0, entry = 0;
4686 int key = pkt->flags & AV_PKT_FLAG_KEY;
4687 start = find_next_marker(pkt->data, end);
4688 for (next = start; next < end; start = next) {
4689 next = find_next_marker(start + 4, end);
4690 switch (AV_RB32(start)) {
4691 case VC1_CODE_SEQHDR:
4694 case VC1_CODE_ENTRYPOINT:
4697 case VC1_CODE_SLICE:
4698 trk->vc1_info.slices = 1;
4702 if (!trk->entry && trk->vc1_info.first_packet_seen)
4703 trk->vc1_info.first_frag_written = 1;
4704 if (!trk->entry && !trk->vc1_info.first_frag_written) {
4705 /* First packet in first fragment */
4706 trk->vc1_info.first_packet_seq = seq;
4707 trk->vc1_info.first_packet_entry = entry;
4708 trk->vc1_info.first_packet_seen = 1;
4709 } else if ((seq && !trk->vc1_info.packet_seq) ||
4710 (entry && !trk->vc1_info.packet_entry)) {
4712 for (i = 0; i < trk->entry; i++)
4713 trk->cluster[i].flags &= ~MOV_SYNC_SAMPLE;
4714 trk->has_keyframes = 0;
4716 trk->vc1_info.packet_seq = 1;
4718 trk->vc1_info.packet_entry = 1;
4719 if (!trk->vc1_info.first_frag_written) {
4720 /* First fragment */
4721 if ((!seq || trk->vc1_info.first_packet_seq) &&
4722 (!entry || trk->vc1_info.first_packet_entry)) {
4723 /* First packet had the same headers as this one, readd the
4724 * sync sample flag. */
4725 trk->cluster[0].flags |= MOV_SYNC_SAMPLE;
4726 trk->has_keyframes = 1;
4730 if (trk->vc1_info.packet_seq && trk->vc1_info.packet_entry)
4732 else if (trk->vc1_info.packet_seq)
4734 else if (trk->vc1_info.packet_entry)
4737 trk->cluster[trk->entry].flags |= MOV_SYNC_SAMPLE;
4738 trk->has_keyframes++;
4742 static int mov_flush_fragment_interleaving(AVFormatContext *s, MOVTrack *track)
4744 MOVMuxContext *mov = s->priv_data;
4749 if (!track->mdat_buf)
4751 if (!mov->mdat_buf) {
4752 if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0)
4755 buf_size = avio_close_dyn_buf(track->mdat_buf, &buf);
4756 track->mdat_buf = NULL;
4758 offset = avio_tell(mov->mdat_buf);
4759 avio_write(mov->mdat_buf, buf, buf_size);
4762 for (i = track->entries_flushed; i < track->entry; i++)
4763 track->cluster[i].pos += offset;
4764 track->entries_flushed = track->entry;
4768 static int mov_flush_fragment(AVFormatContext *s, int force)
4770 MOVMuxContext *mov = s->priv_data;
4771 int i, first_track = -1;
4772 int64_t mdat_size = 0;
4774 int has_video = 0, starts_with_key = 0, first_video_track = 1;
4776 if (!(mov->flags & FF_MOV_FLAG_FRAGMENT))
4779 // Try to fill in the duration of the last packet in each stream
4780 // from queued packets in the interleave queues. If the flushing
4781 // of fragments was triggered automatically by an AVPacket, we
4782 // already have reliable info for the end of that track, but other
4783 // tracks may need to be filled in.
4784 for (i = 0; i < s->nb_streams; i++) {
4785 MOVTrack *track = &mov->tracks[i];
4786 if (!track->end_reliable) {
4788 if (!ff_interleaved_peek(s, i, &pkt, 1)) {
4789 if (track->dts_shift != AV_NOPTS_VALUE)
4790 pkt.dts += track->dts_shift;
4791 track->track_duration = pkt.dts - track->start_dts;
4792 if (pkt.pts != AV_NOPTS_VALUE)
4793 track->end_pts = pkt.pts;
4795 track->end_pts = pkt.dts;
4800 for (i = 0; i < mov->nb_streams; i++) {
4801 MOVTrack *track = &mov->tracks[i];
4802 if (track->entry <= 1)
4804 // Sample durations are calculated as the diff of dts values,
4805 // but for the last sample in a fragment, we don't know the dts
4806 // of the first sample in the next fragment, so we have to rely
4807 // on what was set as duration in the AVPacket. Not all callers
4808 // set this though, so we might want to replace it with an
4809 // estimate if it currently is zero.
4810 if (get_cluster_duration(track, track->entry - 1) != 0)
4812 // Use the duration (i.e. dts diff) of the second last sample for
4813 // the last one. This is a wild guess (and fatal if it turns out
4814 // to be too long), but probably the best we can do - having a zero
4815 // duration is bad as well.
4816 track->track_duration += get_cluster_duration(track, track->entry - 2);
4817 track->end_pts += get_cluster_duration(track, track->entry - 2);
4818 if (!mov->missing_duration_warned) {
4819 av_log(s, AV_LOG_WARNING,
4820 "Estimating the duration of the last packet in a "
4821 "fragment, consider setting the duration field in "
4822 "AVPacket instead.\n");
4823 mov->missing_duration_warned = 1;
4827 if (!mov->moov_written) {
4828 int64_t pos = avio_tell(s->pb);
4830 int buf_size, moov_size;
4832 for (i = 0; i < mov->nb_streams; i++)
4833 if (!mov->tracks[i].entry)
4835 /* Don't write the initial moov unless all tracks have data */
4836 if (i < mov->nb_streams && !force)
4839 moov_size = get_moov_size(s);
4840 for (i = 0; i < mov->nb_streams; i++)
4841 mov->tracks[i].data_offset = pos + moov_size + 8;
4843 avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_HEADER);
4844 if (mov->flags & FF_MOV_FLAG_DELAY_MOOV)
4845 mov_write_identification(s->pb, s);
4846 if ((ret = mov_write_moov_tag(s->pb, mov, s)) < 0)
4849 if (mov->flags & FF_MOV_FLAG_DELAY_MOOV) {
4850 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
4851 mov->reserved_header_pos = avio_tell(s->pb);
4853 mov->moov_written = 1;
4857 buf_size = avio_close_dyn_buf(mov->mdat_buf, &buf);
4858 mov->mdat_buf = NULL;
4859 avio_wb32(s->pb, buf_size + 8);
4860 ffio_wfourcc(s->pb, "mdat");
4861 avio_write(s->pb, buf, buf_size);
4864 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
4865 mov->reserved_header_pos = avio_tell(s->pb);
4867 mov->moov_written = 1;
4869 for (i = 0; i < mov->nb_streams; i++) {
4870 if (mov->tracks[i].entry)
4871 mov->tracks[i].frag_start += mov->tracks[i].start_dts +
4872 mov->tracks[i].track_duration -
4873 mov->tracks[i].cluster[0].dts;
4874 mov->tracks[i].entry = 0;
4875 mov->tracks[i].end_reliable = 0;
4881 if (mov->frag_interleave) {
4882 for (i = 0; i < mov->nb_streams; i++) {
4883 MOVTrack *track = &mov->tracks[i];
4885 if ((ret = mov_flush_fragment_interleaving(s, track)) < 0)
4891 mdat_size = avio_tell(mov->mdat_buf);
4894 for (i = 0; i < mov->nb_streams; i++) {
4895 MOVTrack *track = &mov->tracks[i];
4896 if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF || mov->frag_interleave)
4897 track->data_offset = 0;
4899 track->data_offset = mdat_size;
4900 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
4902 if (first_video_track) {
4904 starts_with_key = track->cluster[0].flags & MOV_SYNC_SAMPLE;
4905 first_video_track = 0;
4910 if (track->mdat_buf)
4911 mdat_size += avio_tell(track->mdat_buf);
4912 if (first_track < 0)
4919 avio_write_marker(s->pb,
4920 av_rescale(mov->tracks[first_track].cluster[0].dts, AV_TIME_BASE, mov->tracks[first_track].timescale),
4921 (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);
4923 for (i = 0; i < mov->nb_streams; i++) {
4924 MOVTrack *track = &mov->tracks[i];
4925 int buf_size, write_moof = 1, moof_tracks = -1;
4927 int64_t duration = 0;
4930 duration = track->start_dts + track->track_duration -
4931 track->cluster[0].dts;
4932 if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF) {
4933 if (!track->mdat_buf)
4935 mdat_size = avio_tell(track->mdat_buf);
4938 write_moof = i == first_track;
4944 mov_write_moof_tag(s->pb, mov, moof_tracks, mdat_size);
4947 avio_wb32(s->pb, mdat_size + 8);
4948 ffio_wfourcc(s->pb, "mdat");
4952 track->frag_start += duration;
4954 track->entries_flushed = 0;
4955 track->end_reliable = 0;
4956 if (!mov->frag_interleave) {
4957 if (!track->mdat_buf)
4959 buf_size = avio_close_dyn_buf(track->mdat_buf, &buf);
4960 track->mdat_buf = NULL;
4964 buf_size = avio_close_dyn_buf(mov->mdat_buf, &buf);
4965 mov->mdat_buf = NULL;
4968 avio_write(s->pb, buf, buf_size);
4978 static int mov_auto_flush_fragment(AVFormatContext *s, int force)
4980 MOVMuxContext *mov = s->priv_data;
4981 int had_moov = mov->moov_written;
4982 int ret = mov_flush_fragment(s, force);
4985 // If using delay_moov, the first flush only wrote the moov,
4986 // not the actual moof+mdat pair, thus flush once again.
4987 if (!had_moov && mov->flags & FF_MOV_FLAG_DELAY_MOOV)
4988 ret = mov_flush_fragment(s, force);
4992 static int check_pkt(AVFormatContext *s, AVPacket *pkt)
4994 MOVMuxContext *mov = s->priv_data;
4995 MOVTrack *trk = &mov->tracks[pkt->stream_index];
5000 ref = trk->cluster[trk->entry - 1].dts;
5001 } else if ( trk->start_dts != AV_NOPTS_VALUE
5002 && !trk->frag_discont) {
5003 ref = trk->start_dts + trk->track_duration;
5005 ref = pkt->dts; // Skip tests for the first packet
5007 if (trk->dts_shift != AV_NOPTS_VALUE) {
5008 /* With negative CTS offsets we have set an offset to the DTS,
5009 * reverse this for the check. */
5010 ref -= trk->dts_shift;
5013 duration = pkt->dts - ref;
5014 if (pkt->dts < ref || duration >= INT_MAX) {
5015 av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" / timestamp: %"PRId64" is out of range for mov/mp4 format\n",
5020 pkt->pts = AV_NOPTS_VALUE;
5023 if (pkt->duration < 0 || pkt->duration > INT_MAX) {
5024 av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" is invalid\n", pkt->duration);
5025 return AVERROR(EINVAL);
5030 int ff_mov_write_packet(AVFormatContext *s, AVPacket *pkt)
5032 MOVMuxContext *mov = s->priv_data;
5033 AVIOContext *pb = s->pb;
5034 MOVTrack *trk = &mov->tracks[pkt->stream_index];
5035 AVCodecParameters *par = trk->par;
5036 unsigned int samples_in_chunk = 0;
5037 int size = pkt->size, ret = 0;
5038 uint8_t *reformatted_data = NULL;
5040 ret = check_pkt(s, pkt);
5044 if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
5046 if (mov->moov_written || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
5047 if (mov->frag_interleave && mov->fragments > 0) {
5048 if (trk->entry - trk->entries_flushed >= mov->frag_interleave) {
5049 if ((ret = mov_flush_fragment_interleaving(s, trk)) < 0)
5054 if (!trk->mdat_buf) {
5055 if ((ret = avio_open_dyn_buf(&trk->mdat_buf)) < 0)
5060 if (!mov->mdat_buf) {
5061 if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0)
5068 if (par->codec_id == AV_CODEC_ID_AMR_NB) {
5069 /* We must find out how many AMR blocks there are in one packet */
5070 static const uint16_t packed_size[16] =
5071 {13, 14, 16, 18, 20, 21, 27, 32, 6, 0, 0, 0, 0, 0, 0, 1};
5074 while (len < size && samples_in_chunk < 100) {
5075 len += packed_size[(pkt->data[len] >> 3) & 0x0F];
5078 if (samples_in_chunk > 1) {
5079 av_log(s, AV_LOG_ERROR, "fatal error, input is not a single packet, implement a AVParser for it\n");
5082 } else if (par->codec_id == AV_CODEC_ID_ADPCM_MS ||
5083 par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) {
5084 samples_in_chunk = trk->par->frame_size;
5085 } else if (trk->sample_size)
5086 samples_in_chunk = size / trk->sample_size;
5088 samples_in_chunk = 1;
5090 /* copy extradata if it exists */
5091 if (trk->vos_len == 0 && par->extradata_size > 0 &&
5092 !TAG_IS_AVCI(trk->tag) &&
5093 (par->codec_id != AV_CODEC_ID_DNXHD)) {
5094 trk->vos_len = par->extradata_size;
5095 trk->vos_data = av_malloc(trk->vos_len);
5096 if (!trk->vos_data) {
5097 ret = AVERROR(ENOMEM);
5100 memcpy(trk->vos_data, par->extradata, trk->vos_len);
5103 if (par->codec_id == AV_CODEC_ID_AAC && pkt->size > 2 &&
5104 (AV_RB16(pkt->data) & 0xfff0) == 0xfff0) {
5105 if (!s->streams[pkt->stream_index]->nb_frames) {
5106 av_log(s, AV_LOG_ERROR, "Malformed AAC bitstream detected: "
5107 "use the audio bitstream filter 'aac_adtstoasc' to fix it "
5108 "('-bsf:a aac_adtstoasc' option with ffmpeg)\n");
5111 av_log(s, AV_LOG_WARNING, "aac bitstream error\n");
5113 if (par->codec_id == AV_CODEC_ID_H264 && trk->vos_len > 0 && *(uint8_t *)trk->vos_data != 1 && !TAG_IS_AVCI(trk->tag)) {
5114 /* from x264 or from bytestream H.264 */
5115 /* NAL reformatting needed */
5116 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
5117 ff_avc_parse_nal_units_buf(pkt->data, &reformatted_data,
5119 avio_write(pb, reformatted_data, size);
5121 if (trk->cenc.aes_ctr) {
5122 size = ff_mov_cenc_avc_parse_nal_units(&trk->cenc, pb, pkt->data, size);
5128 size = ff_avc_parse_nal_units(pb, pkt->data, pkt->size);
5131 } else if (par->codec_id == AV_CODEC_ID_HEVC && trk->vos_len > 6 &&
5132 (AV_RB24(trk->vos_data) == 1 || AV_RB32(trk->vos_data) == 1)) {
5133 /* extradata is Annex B, assume the bitstream is too and convert it */
5134 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
5135 ff_hevc_annexb2mp4_buf(pkt->data, &reformatted_data, &size, 0, NULL);
5136 avio_write(pb, reformatted_data, size);
5138 size = ff_hevc_annexb2mp4(pb, pkt->data, pkt->size, 0, NULL);
5140 #if CONFIG_AC3_PARSER
5141 } else if (par->codec_id == AV_CODEC_ID_EAC3) {
5142 size = handle_eac3(mov, pkt, trk);
5147 avio_write(pb, pkt->data, size);
5150 if (trk->cenc.aes_ctr) {
5151 if (par->codec_id == AV_CODEC_ID_H264 && par->extradata_size > 4) {
5152 int nal_size_length = (par->extradata[4] & 0x3) + 1;
5153 ret = ff_mov_cenc_avc_write_nal_units(s, &trk->cenc, nal_size_length, pb, pkt->data, size);
5155 ret = ff_mov_cenc_write_packet(&trk->cenc, pb, pkt->data, size);
5162 avio_write(pb, pkt->data, size);
5166 if ((par->codec_id == AV_CODEC_ID_DNXHD ||
5167 par->codec_id == AV_CODEC_ID_AC3) && !trk->vos_len) {
5168 /* copy frame to create needed atoms */
5169 trk->vos_len = size;
5170 trk->vos_data = av_malloc(size);
5171 if (!trk->vos_data) {
5172 ret = AVERROR(ENOMEM);
5175 memcpy(trk->vos_data, pkt->data, size);
5178 if (trk->entry >= trk->cluster_capacity) {
5179 unsigned new_capacity = 2 * (trk->entry + MOV_INDEX_CLUSTER_SIZE);
5180 if (av_reallocp_array(&trk->cluster, new_capacity,
5181 sizeof(*trk->cluster))) {
5182 ret = AVERROR(ENOMEM);
5185 trk->cluster_capacity = new_capacity;
5188 trk->cluster[trk->entry].pos = avio_tell(pb) - size;
5189 trk->cluster[trk->entry].samples_in_chunk = samples_in_chunk;
5190 trk->cluster[trk->entry].chunkNum = 0;
5191 trk->cluster[trk->entry].size = size;
5192 trk->cluster[trk->entry].entries = samples_in_chunk;
5193 trk->cluster[trk->entry].dts = pkt->dts;
5194 if (!trk->entry && trk->start_dts != AV_NOPTS_VALUE) {
5195 if (!trk->frag_discont) {
5196 /* First packet of a new fragment. We already wrote the duration
5197 * of the last packet of the previous fragment based on track_duration,
5198 * which might not exactly match our dts. Therefore adjust the dts
5199 * of this packet to be what the previous packets duration implies. */
5200 trk->cluster[trk->entry].dts = trk->start_dts + trk->track_duration;
5201 /* We also may have written the pts and the corresponding duration
5202 * in sidx/tfrf/tfxd tags; make sure the sidx pts and duration match up with
5203 * the next fragment. This means the cts of the first sample must
5204 * be the same in all fragments, unless end_pts was updated by
5205 * the packet causing the fragment to be written. */
5206 if ((mov->flags & FF_MOV_FLAG_DASH && !(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)) ||
5207 mov->mode == MODE_ISM)
5208 pkt->pts = pkt->dts + trk->end_pts - trk->cluster[trk->entry].dts;
5210 /* New fragment, but discontinuous from previous fragments.
5211 * Pretend the duration sum of the earlier fragments is
5212 * pkt->dts - trk->start_dts. */
5213 trk->frag_start = pkt->dts - trk->start_dts;
5214 trk->end_pts = AV_NOPTS_VALUE;
5215 trk->frag_discont = 0;
5219 if (!trk->entry && trk->start_dts == AV_NOPTS_VALUE && !mov->use_editlist &&
5220 s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO) {
5221 /* Not using edit lists and shifting the first track to start from zero.
5222 * If the other streams start from a later timestamp, we won't be able
5223 * to signal the difference in starting time without an edit list.
5224 * Thus move the timestamp for this first sample to 0, increasing
5225 * its duration instead. */
5226 trk->cluster[trk->entry].dts = trk->start_dts = 0;
5228 if (trk->start_dts == AV_NOPTS_VALUE) {
5229 trk->start_dts = pkt->dts;
5230 if (trk->frag_discont) {
5231 if (mov->use_editlist) {
5232 /* Pretend the whole stream started at pts=0, with earlier fragments
5233 * already written. If the stream started at pts=0, the duration sum
5234 * of earlier fragments would have been pkt->pts. */
5235 trk->frag_start = pkt->pts;
5236 trk->start_dts = pkt->dts - pkt->pts;
5238 /* Pretend the whole stream started at dts=0, with earlier fragments
5239 * already written, with a duration summing up to pkt->dts. */
5240 trk->frag_start = pkt->dts;
5243 trk->frag_discont = 0;
5244 } else if (pkt->dts && mov->moov_written)
5245 av_log(s, AV_LOG_WARNING,
5246 "Track %d starts with a nonzero dts %"PRId64", while the moov "
5247 "already has been written. Set the delay_moov flag to handle "
5249 pkt->stream_index, pkt->dts);
5251 trk->track_duration = pkt->dts - trk->start_dts + pkt->duration;
5252 trk->last_sample_is_subtitle_end = 0;
5254 if (pkt->pts == AV_NOPTS_VALUE) {
5255 av_log(s, AV_LOG_WARNING, "pts has no value\n");
5256 pkt->pts = pkt->dts;
5258 if (pkt->dts != pkt->pts)
5259 trk->flags |= MOV_TRACK_CTTS;
5260 trk->cluster[trk->entry].cts = pkt->pts - pkt->dts;
5261 trk->cluster[trk->entry].flags = 0;
5262 if (trk->start_cts == AV_NOPTS_VALUE)
5263 trk->start_cts = pkt->pts - pkt->dts;
5264 if (trk->end_pts == AV_NOPTS_VALUE)
5265 trk->end_pts = trk->cluster[trk->entry].dts +
5266 trk->cluster[trk->entry].cts + pkt->duration;
5268 trk->end_pts = FFMAX(trk->end_pts, trk->cluster[trk->entry].dts +
5269 trk->cluster[trk->entry].cts +
5272 if (par->codec_id == AV_CODEC_ID_VC1) {
5273 mov_parse_vc1_frame(pkt, trk);
5274 } else if (pkt->flags & AV_PKT_FLAG_KEY) {
5275 if (mov->mode == MODE_MOV && par->codec_id == AV_CODEC_ID_MPEG2VIDEO &&
5276 trk->entry > 0) { // force sync sample for the first key frame
5277 mov_parse_mpeg2_frame(pkt, &trk->cluster[trk->entry].flags);
5278 if (trk->cluster[trk->entry].flags & MOV_PARTIAL_SYNC_SAMPLE)
5279 trk->flags |= MOV_TRACK_STPS;
5281 trk->cluster[trk->entry].flags = MOV_SYNC_SAMPLE;
5283 if (trk->cluster[trk->entry].flags & MOV_SYNC_SAMPLE)
5284 trk->has_keyframes++;
5287 trk->sample_count += samples_in_chunk;
5288 mov->mdat_size += size;
5290 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams)
5291 ff_mov_add_hinted_packet(s, pkt, trk->hint_track, trk->entry,
5292 reformatted_data, size);
5297 av_free(reformatted_data);
5301 static int mov_write_single_packet(AVFormatContext *s, AVPacket *pkt)
5303 MOVMuxContext *mov = s->priv_data;
5304 MOVTrack *trk = &mov->tracks[pkt->stream_index];
5305 AVCodecParameters *par = trk->par;
5306 int64_t frag_duration = 0;
5307 int size = pkt->size;
5309 int ret = check_pkt(s, pkt);
5313 if (mov->flags & FF_MOV_FLAG_FRAG_DISCONT) {
5315 for (i = 0; i < s->nb_streams; i++)
5316 mov->tracks[i].frag_discont = 1;
5317 mov->flags &= ~FF_MOV_FLAG_FRAG_DISCONT;
5320 if (mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS) {
5321 if (trk->dts_shift == AV_NOPTS_VALUE)
5322 trk->dts_shift = pkt->pts - pkt->dts;
5323 pkt->dts += trk->dts_shift;
5326 if (trk->par->codec_id == AV_CODEC_ID_MP4ALS ||
5327 trk->par->codec_id == AV_CODEC_ID_AAC ||
5328 trk->par->codec_id == AV_CODEC_ID_FLAC) {
5330 uint8_t *side = av_packet_get_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA, &side_size);
5331 if (side && side_size > 0 && (side_size != par->extradata_size || memcmp(side, par->extradata, side_size))) {
5332 void *newextra = av_mallocz(side_size + AV_INPUT_BUFFER_PADDING_SIZE);
5334 return AVERROR(ENOMEM);
5335 av_free(par->extradata);
5336 par->extradata = newextra;
5337 memcpy(par->extradata, side, side_size);
5338 par->extradata_size = side_size;
5339 if (!pkt->size) // Flush packet
5340 mov->need_rewrite_extradata = 1;
5345 if (trk->start_dts == AV_NOPTS_VALUE && trk->frag_discont) {
5346 trk->start_dts = pkt->dts;
5347 if (pkt->pts != AV_NOPTS_VALUE)
5348 trk->start_cts = pkt->pts - pkt->dts;
5353 return 0; /* Discard 0 sized packets */
5356 if (trk->entry && pkt->stream_index < s->nb_streams)
5357 frag_duration = av_rescale_q(pkt->dts - trk->cluster[0].dts,
5358 s->streams[pkt->stream_index]->time_base,
5360 if ((mov->max_fragment_duration &&
5361 frag_duration >= mov->max_fragment_duration) ||
5362 (mov->max_fragment_size && mov->mdat_size + size >= mov->max_fragment_size) ||
5363 (mov->flags & FF_MOV_FLAG_FRAG_KEYFRAME &&
5364 par->codec_type == AVMEDIA_TYPE_VIDEO &&
5365 trk->entry && pkt->flags & AV_PKT_FLAG_KEY)) {
5366 if (frag_duration >= mov->min_fragment_duration) {
5367 // Set the duration of this track to line up with the next
5368 // sample in this track. This avoids relying on AVPacket
5369 // duration, but only helps for this particular track, not
5370 // for the other ones that are flushed at the same time.
5371 trk->track_duration = pkt->dts - trk->start_dts;
5372 if (pkt->pts != AV_NOPTS_VALUE)
5373 trk->end_pts = pkt->pts;
5375 trk->end_pts = pkt->dts;
5376 trk->end_reliable = 1;
5377 mov_auto_flush_fragment(s, 0);
5381 return ff_mov_write_packet(s, pkt);
5384 static int mov_write_subtitle_end_packet(AVFormatContext *s,
5388 uint8_t data[2] = {0};
5391 av_init_packet(&end);
5392 end.size = sizeof(data);
5397 end.stream_index = stream_index;
5399 ret = mov_write_single_packet(s, &end);
5400 av_packet_unref(&end);
5405 static int mov_write_packet(AVFormatContext *s, AVPacket *pkt)
5408 mov_flush_fragment(s, 1);
5412 MOVMuxContext *mov = s->priv_data;
5413 MOVTrack *trk = &mov->tracks[pkt->stream_index];
5416 return mov_write_single_packet(s, pkt); /* Passthrough. */
5419 * Subtitles require special handling.
5421 * 1) For full complaince, every track must have a sample at
5422 * dts == 0, which is rarely true for subtitles. So, as soon
5423 * as we see any packet with dts > 0, write an empty subtitle
5424 * at dts == 0 for any subtitle track with no samples in it.
5426 * 2) For each subtitle track, check if the current packet's
5427 * dts is past the duration of the last subtitle sample. If
5428 * so, we now need to write an end sample for that subtitle.
5430 * This must be done conditionally to allow for subtitles that
5431 * immediately replace each other, in which case an end sample
5432 * is not needed, and is, in fact, actively harmful.
5434 * 3) See mov_write_trailer for how the final end sample is
5437 for (i = 0; i < mov->nb_streams; i++) {
5438 MOVTrack *trk = &mov->tracks[i];
5441 if (trk->par->codec_id == AV_CODEC_ID_MOV_TEXT &&
5442 trk->track_duration < pkt->dts &&
5443 (trk->entry == 0 || !trk->last_sample_is_subtitle_end)) {
5444 ret = mov_write_subtitle_end_packet(s, i, trk->track_duration);
5445 if (ret < 0) return ret;
5446 trk->last_sample_is_subtitle_end = 1;
5450 if (trk->mode == MODE_MOV && trk->par->codec_type == AVMEDIA_TYPE_VIDEO) {
5451 AVPacket *opkt = pkt;
5452 int reshuffle_ret, ret;
5453 if (trk->is_unaligned_qt_rgb) {
5454 int64_t bpc = trk->par->bits_per_coded_sample != 15 ? trk->par->bits_per_coded_sample : 16;
5455 int expected_stride = ((trk->par->width * bpc + 15) >> 4)*2;
5456 reshuffle_ret = ff_reshuffle_raw_rgb(s, &pkt, trk->par, expected_stride);
5457 if (reshuffle_ret < 0)
5458 return reshuffle_ret;
5461 if (trk->par->format == AV_PIX_FMT_PAL8 && !trk->pal_done) {
5462 ret = ff_get_packet_palette(s, opkt, reshuffle_ret, trk->palette);
5467 } else if (trk->par->codec_id == AV_CODEC_ID_RAWVIDEO &&
5468 (trk->par->format == AV_PIX_FMT_GRAY8 ||
5469 trk->par->format == AV_PIX_FMT_MONOBLACK)) {
5470 for (i = 0; i < pkt->size; i++)
5471 pkt->data[i] = ~pkt->data[i];
5473 if (reshuffle_ret) {
5474 ret = mov_write_single_packet(s, pkt);
5477 av_packet_free(&pkt);
5482 return mov_write_single_packet(s, pkt);
5486 // QuickTime chapters involve an additional text track with the chapter names
5487 // as samples, and a tref pointing from the other tracks to the chapter one.
5488 static int mov_create_chapter_track(AVFormatContext *s, int tracknum)
5492 MOVMuxContext *mov = s->priv_data;
5493 MOVTrack *track = &mov->tracks[tracknum];
5494 AVPacket pkt = { .stream_index = tracknum, .flags = AV_PKT_FLAG_KEY };
5497 track->mode = mov->mode;
5498 track->tag = MKTAG('t','e','x','t');
5499 track->timescale = MOV_TIMESCALE;
5500 track->par = avcodec_parameters_alloc();
5502 return AVERROR(ENOMEM);
5503 track->par->codec_type = AVMEDIA_TYPE_SUBTITLE;
5505 // These properties are required to make QT recognize the chapter track
5506 uint8_t chapter_properties[43] = { 0, 0, 0, 0, 0, 0, 0, 1, };
5507 if (ff_alloc_extradata(track->par, sizeof(chapter_properties)))
5508 return AVERROR(ENOMEM);
5509 memcpy(track->par->extradata, chapter_properties, sizeof(chapter_properties));
5511 if (avio_open_dyn_buf(&pb) >= 0) {
5515 /* Stub header (usually for Quicktime chapter track) */
5517 avio_wb32(pb, 0x01); // displayFlags
5518 avio_w8(pb, 0x00); // horizontal justification
5519 avio_w8(pb, 0x00); // vertical justification
5520 avio_w8(pb, 0x00); // bgColourRed
5521 avio_w8(pb, 0x00); // bgColourGreen
5522 avio_w8(pb, 0x00); // bgColourBlue
5523 avio_w8(pb, 0x00); // bgColourAlpha
5525 avio_wb16(pb, 0x00); // defTextBoxTop
5526 avio_wb16(pb, 0x00); // defTextBoxLeft
5527 avio_wb16(pb, 0x00); // defTextBoxBottom
5528 avio_wb16(pb, 0x00); // defTextBoxRight
5530 avio_wb16(pb, 0x00); // startChar
5531 avio_wb16(pb, 0x00); // endChar
5532 avio_wb16(pb, 0x01); // fontID
5533 avio_w8(pb, 0x00); // fontStyleFlags
5534 avio_w8(pb, 0x00); // fontSize
5535 avio_w8(pb, 0x00); // fgColourRed
5536 avio_w8(pb, 0x00); // fgColourGreen
5537 avio_w8(pb, 0x00); // fgColourBlue
5538 avio_w8(pb, 0x00); // fgColourAlpha
5540 avio_wb32(pb, 0x0D); // box size
5541 ffio_wfourcc(pb, "ftab"); // box atom name
5542 avio_wb16(pb, 0x01); // entry count
5544 avio_wb16(pb, 0x01); // font ID
5545 avio_w8(pb, 0x00); // font name length
5547 if ((size = avio_close_dyn_buf(pb, &buf)) > 0) {
5548 track->par->extradata = buf;
5549 track->par->extradata_size = size;
5556 for (i = 0; i < s->nb_chapters; i++) {
5557 AVChapter *c = s->chapters[i];
5558 AVDictionaryEntry *t;
5560 int64_t end = av_rescale_q(c->end, c->time_base, (AVRational){1,MOV_TIMESCALE});
5561 pkt.pts = pkt.dts = av_rescale_q(c->start, c->time_base, (AVRational){1,MOV_TIMESCALE});
5562 pkt.duration = end - pkt.dts;
5564 if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
5565 static const char encd[12] = {
5566 0x00, 0x00, 0x00, 0x0C,
5568 0x00, 0x00, 0x01, 0x00 };
5569 len = strlen(t->value);
5570 pkt.size = len + 2 + 12;
5571 pkt.data = av_malloc(pkt.size);
5573 return AVERROR(ENOMEM);
5574 AV_WB16(pkt.data, len);
5575 memcpy(pkt.data + 2, t->value, len);
5576 memcpy(pkt.data + len + 2, encd, sizeof(encd));
5577 ff_mov_write_packet(s, &pkt);
5578 av_freep(&pkt.data);
5586 static int mov_check_timecode_track(AVFormatContext *s, AVTimecode *tc, int src_index, const char *tcstr)
5590 /* compute the frame number */
5591 ret = av_timecode_init_from_string(tc, find_fps(s, s->streams[src_index]), tcstr, s);
5595 static int mov_create_timecode_track(AVFormatContext *s, int index, int src_index, AVTimecode tc)
5598 MOVMuxContext *mov = s->priv_data;
5599 MOVTrack *track = &mov->tracks[index];
5600 AVStream *src_st = s->streams[src_index];
5601 AVPacket pkt = {.stream_index = index, .flags = AV_PKT_FLAG_KEY, .size = 4};
5602 AVRational rate = find_fps(s, src_st);
5604 /* tmcd track based on video stream */
5605 track->mode = mov->mode;
5606 track->tag = MKTAG('t','m','c','d');
5607 track->src_track = src_index;
5608 track->timescale = mov->tracks[src_index].timescale;
5609 if (tc.flags & AV_TIMECODE_FLAG_DROPFRAME)
5610 track->timecode_flags |= MOV_TIMECODE_FLAG_DROPFRAME;
5612 /* set st to src_st for metadata access*/
5615 /* encode context: tmcd data stream */
5616 track->par = avcodec_parameters_alloc();
5618 return AVERROR(ENOMEM);
5619 track->par->codec_type = AVMEDIA_TYPE_DATA;
5620 track->par->codec_tag = track->tag;
5621 track->st->avg_frame_rate = av_inv_q(rate);
5623 /* the tmcd track just contains one packet with the frame number */
5624 pkt.data = av_malloc(pkt.size);
5626 return AVERROR(ENOMEM);
5627 AV_WB32(pkt.data, tc.start);
5628 ret = ff_mov_write_packet(s, &pkt);
5634 * st->disposition controls the "enabled" flag in the tkhd tag.
5635 * QuickTime will not play a track if it is not enabled. So make sure
5636 * that one track of each type (audio, video, subtitle) is enabled.
5638 * Subtitles are special. For audio and video, setting "enabled" also
5639 * makes the track "default" (i.e. it is rendered when played). For
5640 * subtitles, an "enabled" subtitle is not rendered by default, but
5641 * if no subtitle is enabled, the subtitle menu in QuickTime will be
5644 static void enable_tracks(AVFormatContext *s)
5646 MOVMuxContext *mov = s->priv_data;
5648 int enabled[AVMEDIA_TYPE_NB];
5649 int first[AVMEDIA_TYPE_NB];
5651 for (i = 0; i < AVMEDIA_TYPE_NB; i++) {
5656 for (i = 0; i < s->nb_streams; i++) {
5657 AVStream *st = s->streams[i];
5659 if (st->codecpar->codec_type <= AVMEDIA_TYPE_UNKNOWN ||
5660 st->codecpar->codec_type >= AVMEDIA_TYPE_NB)
5663 if (first[st->codecpar->codec_type] < 0)
5664 first[st->codecpar->codec_type] = i;
5665 if (st->disposition & AV_DISPOSITION_DEFAULT) {
5666 mov->tracks[i].flags |= MOV_TRACK_ENABLED;
5667 enabled[st->codecpar->codec_type]++;
5671 for (i = 0; i < AVMEDIA_TYPE_NB; i++) {
5673 case AVMEDIA_TYPE_VIDEO:
5674 case AVMEDIA_TYPE_AUDIO:
5675 case AVMEDIA_TYPE_SUBTITLE:
5677 mov->per_stream_grouping = 1;
5678 if (!enabled[i] && first[i] >= 0)
5679 mov->tracks[first[i]].flags |= MOV_TRACK_ENABLED;
5685 static void mov_free(AVFormatContext *s)
5687 MOVMuxContext *mov = s->priv_data;
5690 if (mov->chapter_track) {
5691 if (mov->tracks[mov->chapter_track].par)
5692 av_freep(&mov->tracks[mov->chapter_track].par->extradata);
5693 av_freep(&mov->tracks[mov->chapter_track].par);
5696 for (i = 0; i < mov->nb_streams; i++) {
5697 if (mov->tracks[i].tag == MKTAG('r','t','p',' '))
5698 ff_mov_close_hinting(&mov->tracks[i]);
5699 else if (mov->tracks[i].tag == MKTAG('t','m','c','d') && mov->nb_meta_tmcd)
5700 av_freep(&mov->tracks[i].par);
5701 av_freep(&mov->tracks[i].cluster);
5702 av_freep(&mov->tracks[i].frag_info);
5704 if (mov->tracks[i].vos_len)
5705 av_freep(&mov->tracks[i].vos_data);
5707 ff_mov_cenc_free(&mov->tracks[i].cenc);
5710 av_freep(&mov->tracks);
5713 static uint32_t rgb_to_yuv(uint32_t rgb)
5718 r = (rgb >> 16) & 0xFF;
5719 g = (rgb >> 8) & 0xFF;
5722 y = av_clip_uint8(( 16000 + 257 * r + 504 * g + 98 * b)/1000);
5723 cb = av_clip_uint8((128000 - 148 * r - 291 * g + 439 * b)/1000);
5724 cr = av_clip_uint8((128000 + 439 * r - 368 * g - 71 * b)/1000);
5726 return (y << 16) | (cr << 8) | cb;
5729 static int mov_create_dvd_sub_decoder_specific_info(MOVTrack *track,
5732 int i, width = 720, height = 480;
5733 int have_palette = 0, have_size = 0;
5734 uint32_t palette[16];
5735 char *cur = st->codecpar->extradata;
5737 while (cur && *cur) {
5738 if (strncmp("palette:", cur, 8) == 0) {
5740 count = sscanf(cur + 8,
5741 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
5742 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
5743 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
5744 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32"",
5745 &palette[ 0], &palette[ 1], &palette[ 2], &palette[ 3],
5746 &palette[ 4], &palette[ 5], &palette[ 6], &palette[ 7],
5747 &palette[ 8], &palette[ 9], &palette[10], &palette[11],
5748 &palette[12], &palette[13], &palette[14], &palette[15]);
5750 for (i = 0; i < count; i++) {
5751 palette[i] = rgb_to_yuv(palette[i]);
5754 } else if (!strncmp("size:", cur, 5)) {
5755 sscanf(cur + 5, "%dx%d", &width, &height);
5758 if (have_palette && have_size)
5760 cur += strcspn(cur, "\n\r");
5761 cur += strspn(cur, "\n\r");
5764 track->vos_data = av_malloc(16*4);
5765 if (!track->vos_data)
5766 return AVERROR(ENOMEM);
5767 for (i = 0; i < 16; i++) {
5768 AV_WB32(track->vos_data + i * 4, palette[i]);
5770 track->vos_len = 16 * 4;
5772 st->codecpar->width = width;
5773 st->codecpar->height = track->height = height;
5778 static int mov_init(AVFormatContext *s)
5780 MOVMuxContext *mov = s->priv_data;
5781 AVDictionaryEntry *global_tcr = av_dict_get(s->metadata, "timecode", NULL, 0);
5786 /* Default mode == MP4 */
5787 mov->mode = MODE_MP4;
5790 if (!strcmp("3gp", s->oformat->name)) mov->mode = MODE_3GP;
5791 else if (!strcmp("3g2", s->oformat->name)) mov->mode = MODE_3GP|MODE_3G2;
5792 else if (!strcmp("mov", s->oformat->name)) mov->mode = MODE_MOV;
5793 else if (!strcmp("psp", s->oformat->name)) mov->mode = MODE_PSP;
5794 else if (!strcmp("ipod",s->oformat->name)) mov->mode = MODE_IPOD;
5795 else if (!strcmp("ismv",s->oformat->name)) mov->mode = MODE_ISM;
5796 else if (!strcmp("f4v", s->oformat->name)) mov->mode = MODE_F4V;
5799 if (mov->flags & FF_MOV_FLAG_DELAY_MOOV)
5800 mov->flags |= FF_MOV_FLAG_EMPTY_MOOV;
5802 /* Set the FRAGMENT flag if any of the fragmentation methods are
5804 if (mov->max_fragment_duration || mov->max_fragment_size ||
5805 mov->flags & (FF_MOV_FLAG_EMPTY_MOOV |
5806 FF_MOV_FLAG_FRAG_KEYFRAME |
5807 FF_MOV_FLAG_FRAG_CUSTOM))
5808 mov->flags |= FF_MOV_FLAG_FRAGMENT;
5810 /* Set other implicit flags immediately */
5811 if (mov->mode == MODE_ISM)
5812 mov->flags |= FF_MOV_FLAG_EMPTY_MOOV | FF_MOV_FLAG_SEPARATE_MOOF |
5813 FF_MOV_FLAG_FRAGMENT;
5814 if (mov->flags & FF_MOV_FLAG_DASH)
5815 mov->flags |= FF_MOV_FLAG_FRAGMENT | FF_MOV_FLAG_EMPTY_MOOV |
5816 FF_MOV_FLAG_DEFAULT_BASE_MOOF;
5818 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV && s->flags & AVFMT_FLAG_AUTO_BSF) {
5819 av_log(s, AV_LOG_VERBOSE, "Empty MOOV enabled; disabling automatic bitstream filtering\n");
5820 s->flags &= ~AVFMT_FLAG_AUTO_BSF;
5823 if (mov->flags & FF_MOV_FLAG_FASTSTART) {
5824 mov->reserved_moov_size = -1;
5827 if (mov->use_editlist < 0) {
5828 mov->use_editlist = 1;
5829 if (mov->flags & FF_MOV_FLAG_FRAGMENT &&
5830 !(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
5831 // If we can avoid needing an edit list by shifting the
5832 // tracks, prefer that over (trying to) write edit lists
5833 // in fragmented output.
5834 if (s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO ||
5835 s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO)
5836 mov->use_editlist = 0;
5839 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV &&
5840 !(mov->flags & FF_MOV_FLAG_DELAY_MOOV) && mov->use_editlist)
5841 av_log(s, AV_LOG_WARNING, "No meaningful edit list will be written when using empty_moov without delay_moov\n");
5843 if (!mov->use_editlist && s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO)
5844 s->avoid_negative_ts = AVFMT_AVOID_NEG_TS_MAKE_ZERO;
5846 /* Clear the omit_tfhd_offset flag if default_base_moof is set;
5847 * if the latter is set that's enough and omit_tfhd_offset doesn't
5848 * add anything extra on top of that. */
5849 if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET &&
5850 mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)
5851 mov->flags &= ~FF_MOV_FLAG_OMIT_TFHD_OFFSET;
5853 if (mov->frag_interleave &&
5854 mov->flags & (FF_MOV_FLAG_OMIT_TFHD_OFFSET | FF_MOV_FLAG_SEPARATE_MOOF)) {
5855 av_log(s, AV_LOG_ERROR,
5856 "Sample interleaving in fragments is mutually exclusive with "
5857 "omit_tfhd_offset and separate_moof\n");
5858 return AVERROR(EINVAL);
5861 /* Non-seekable output is ok if using fragmentation. If ism_lookahead
5862 * is enabled, we don't support non-seekable output at all. */
5863 if (!(s->pb->seekable & AVIO_SEEKABLE_NORMAL) &&
5864 (!(mov->flags & FF_MOV_FLAG_FRAGMENT) || mov->ism_lookahead)) {
5865 av_log(s, AV_LOG_ERROR, "muxer does not support non seekable output\n");
5866 return AVERROR(EINVAL);
5869 mov->nb_streams = s->nb_streams;
5870 if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters)
5871 mov->chapter_track = mov->nb_streams++;
5873 if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
5874 /* Add hint tracks for each audio and video stream */
5875 for (i = 0; i < s->nb_streams; i++) {
5876 AVStream *st = s->streams[i];
5877 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ||
5878 st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
5884 if ( mov->write_tmcd == -1 && (mov->mode == MODE_MOV || mov->mode == MODE_MP4)
5885 || mov->write_tmcd == 1) {
5886 /* +1 tmcd track for each video stream with a timecode */
5887 for (i = 0; i < s->nb_streams; i++) {
5888 AVStream *st = s->streams[i];
5889 AVDictionaryEntry *t = global_tcr;
5890 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
5891 (t || (t=av_dict_get(st->metadata, "timecode", NULL, 0)))) {
5893 ret = mov_check_timecode_track(s, &tc, i, t->value);
5895 mov->nb_meta_tmcd++;
5899 /* check if there is already a tmcd track to remux */
5900 if (mov->nb_meta_tmcd) {
5901 for (i = 0; i < s->nb_streams; i++) {
5902 AVStream *st = s->streams[i];
5903 if (st->codecpar->codec_tag == MKTAG('t','m','c','d')) {
5904 av_log(s, AV_LOG_WARNING, "You requested a copy of the original timecode track "
5905 "so timecode metadata are now ignored\n");
5906 mov->nb_meta_tmcd = 0;
5911 mov->nb_streams += mov->nb_meta_tmcd;
5914 // Reserve an extra stream for chapters for the case where chapters
5915 // are written in the trailer
5916 mov->tracks = av_mallocz_array((mov->nb_streams + 1), sizeof(*mov->tracks));
5918 return AVERROR(ENOMEM);
5920 if (mov->encryption_scheme_str != NULL && strcmp(mov->encryption_scheme_str, "none") != 0) {
5921 if (strcmp(mov->encryption_scheme_str, "cenc-aes-ctr") == 0) {
5922 mov->encryption_scheme = MOV_ENC_CENC_AES_CTR;
5924 if (mov->encryption_key_len != AES_CTR_KEY_SIZE) {
5925 av_log(s, AV_LOG_ERROR, "Invalid encryption key len %d expected %d\n",
5926 mov->encryption_key_len, AES_CTR_KEY_SIZE);
5927 return AVERROR(EINVAL);
5930 if (mov->encryption_kid_len != CENC_KID_SIZE) {
5931 av_log(s, AV_LOG_ERROR, "Invalid encryption kid len %d expected %d\n",
5932 mov->encryption_kid_len, CENC_KID_SIZE);
5933 return AVERROR(EINVAL);
5936 av_log(s, AV_LOG_ERROR, "unsupported encryption scheme %s\n",
5937 mov->encryption_scheme_str);
5938 return AVERROR(EINVAL);
5942 for (i = 0; i < s->nb_streams; i++) {
5943 AVStream *st= s->streams[i];
5944 MOVTrack *track= &mov->tracks[i];
5945 AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0);
5948 track->par = st->codecpar;
5949 track->language = ff_mov_iso639_to_lang(lang?lang->value:"und", mov->mode!=MODE_MOV);
5950 if (track->language < 0)
5951 track->language = 0;
5952 track->mode = mov->mode;
5953 track->tag = mov_find_codec_tag(s, track);
5955 av_log(s, AV_LOG_ERROR, "Could not find tag for codec %s in stream #%d, "
5956 "codec not currently supported in container\n",
5957 avcodec_get_name(st->codecpar->codec_id), i);
5958 return AVERROR(EINVAL);
5960 /* If hinting of this track is enabled by a later hint track,
5961 * this is updated. */
5962 track->hint_track = -1;
5963 track->start_dts = AV_NOPTS_VALUE;
5964 track->start_cts = AV_NOPTS_VALUE;
5965 track->end_pts = AV_NOPTS_VALUE;
5966 track->dts_shift = AV_NOPTS_VALUE;
5967 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
5968 if (track->tag == MKTAG('m','x','3','p') || track->tag == MKTAG('m','x','3','n') ||
5969 track->tag == MKTAG('m','x','4','p') || track->tag == MKTAG('m','x','4','n') ||
5970 track->tag == MKTAG('m','x','5','p') || track->tag == MKTAG('m','x','5','n')) {
5971 if (st->codecpar->width != 720 || (st->codecpar->height != 608 && st->codecpar->height != 512)) {
5972 av_log(s, AV_LOG_ERROR, "D-10/IMX must use 720x608 or 720x512 video resolution\n");
5973 return AVERROR(EINVAL);
5975 track->height = track->tag >> 24 == 'n' ? 486 : 576;
5977 if (mov->video_track_timescale) {
5978 track->timescale = mov->video_track_timescale;
5980 track->timescale = st->time_base.den;
5981 while(track->timescale < 10000)
5982 track->timescale *= 2;
5984 if (st->codecpar->width > 65535 || st->codecpar->height > 65535) {
5985 av_log(s, AV_LOG_ERROR, "Resolution %dx%d too large for mov/mp4\n", st->codecpar->width, st->codecpar->height);
5986 return AVERROR(EINVAL);
5988 if (track->mode == MODE_MOV && track->timescale > 100000)
5989 av_log(s, AV_LOG_WARNING,
5990 "WARNING codec timebase is very high. If duration is too long,\n"
5991 "file may not be playable by quicktime. Specify a shorter timebase\n"
5992 "or choose different container.\n");
5993 if (track->mode == MODE_MOV &&
5994 track->par->codec_id == AV_CODEC_ID_RAWVIDEO &&
5995 track->tag == MKTAG('r','a','w',' ')) {
5996 enum AVPixelFormat pix_fmt = track->par->format;
5997 if (pix_fmt == AV_PIX_FMT_NONE && track->par->bits_per_coded_sample == 1)
5998 pix_fmt = AV_PIX_FMT_MONOWHITE;
5999 track->is_unaligned_qt_rgb =
6000 pix_fmt == AV_PIX_FMT_RGB24 ||
6001 pix_fmt == AV_PIX_FMT_BGR24 ||
6002 pix_fmt == AV_PIX_FMT_PAL8 ||
6003 pix_fmt == AV_PIX_FMT_GRAY8 ||
6004 pix_fmt == AV_PIX_FMT_MONOWHITE ||
6005 pix_fmt == AV_PIX_FMT_MONOBLACK;
6007 if (track->par->codec_id == AV_CODEC_ID_VP9) {
6008 if (track->mode != MODE_MP4) {
6009 av_log(s, AV_LOG_ERROR, "VP9 only supported in MP4.\n");
6010 return AVERROR(EINVAL);
6013 } else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
6014 track->timescale = st->codecpar->sample_rate;
6015 if (!st->codecpar->frame_size && !av_get_bits_per_sample(st->codecpar->codec_id)) {
6016 av_log(s, AV_LOG_WARNING, "track %d: codec frame size is not set\n", i);
6017 track->audio_vbr = 1;
6018 }else if (st->codecpar->codec_id == AV_CODEC_ID_ADPCM_MS ||
6019 st->codecpar->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
6020 st->codecpar->codec_id == AV_CODEC_ID_ILBC){
6021 if (!st->codecpar->block_align) {
6022 av_log(s, AV_LOG_ERROR, "track %d: codec block align is not set for adpcm\n", i);
6023 return AVERROR(EINVAL);
6025 track->sample_size = st->codecpar->block_align;
6026 }else if (st->codecpar->frame_size > 1){ /* assume compressed audio */
6027 track->audio_vbr = 1;
6029 track->sample_size = (av_get_bits_per_sample(st->codecpar->codec_id) >> 3) * st->codecpar->channels;
6031 if (st->codecpar->codec_id == AV_CODEC_ID_ILBC ||
6032 st->codecpar->codec_id == AV_CODEC_ID_ADPCM_IMA_QT) {
6033 track->audio_vbr = 1;
6035 if (track->mode != MODE_MOV &&
6036 track->par->codec_id == AV_CODEC_ID_MP3 && track->timescale < 16000) {
6037 if (s->strict_std_compliance >= FF_COMPLIANCE_NORMAL) {
6038 av_log(s, AV_LOG_ERROR, "track %d: muxing mp3 at %dhz is not standard, to mux anyway set strict to -1\n",
6039 i, track->par->sample_rate);
6040 return AVERROR(EINVAL);
6042 av_log(s, AV_LOG_WARNING, "track %d: muxing mp3 at %dhz is not standard in MP4\n",
6043 i, track->par->sample_rate);
6046 if (track->par->codec_id == AV_CODEC_ID_FLAC ||
6047 track->par->codec_id == AV_CODEC_ID_OPUS) {
6048 if (track->mode != MODE_MP4) {
6049 av_log(s, AV_LOG_ERROR, "%s only supported in MP4.\n", avcodec_get_name(track->par->codec_id));
6050 return AVERROR(EINVAL);
6052 if (s->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
6053 av_log(s, AV_LOG_ERROR,
6054 "%s in MP4 support is experimental, add "
6055 "'-strict %d' if you want to use it.\n",
6056 avcodec_get_name(track->par->codec_id), FF_COMPLIANCE_EXPERIMENTAL);
6057 return AVERROR_EXPERIMENTAL;
6060 } else if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) {
6061 track->timescale = st->time_base.den;
6062 } else if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA) {
6063 track->timescale = st->time_base.den;
6065 track->timescale = MOV_TIMESCALE;
6068 track->height = st->codecpar->height;
6069 /* The ism specific timescale isn't mandatory, but is assumed by
6070 * some tools, such as mp4split. */
6071 if (mov->mode == MODE_ISM)
6072 track->timescale = 10000000;
6074 avpriv_set_pts_info(st, 64, 1, track->timescale);
6076 if (mov->encryption_scheme == MOV_ENC_CENC_AES_CTR) {
6077 ret = ff_mov_cenc_init(&track->cenc, mov->encryption_key,
6078 track->par->codec_id == AV_CODEC_ID_H264, s->flags & AVFMT_FLAG_BITEXACT);
6088 static int mov_write_header(AVFormatContext *s)
6090 AVIOContext *pb = s->pb;
6091 MOVMuxContext *mov = s->priv_data;
6092 AVDictionaryEntry *t, *global_tcr = av_dict_get(s->metadata, "timecode", NULL, 0);
6093 int i, ret, hint_track = 0, tmcd_track = 0, nb_tracks = s->nb_streams;
6095 if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters)
6098 if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
6099 /* Add hint tracks for each audio and video stream */
6100 hint_track = nb_tracks;
6101 for (i = 0; i < s->nb_streams; i++) {
6102 AVStream *st = s->streams[i];
6103 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ||
6104 st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
6110 if (mov->mode == MODE_MOV || mov->mode == MODE_MP4)
6111 tmcd_track = nb_tracks;
6113 for (i = 0; i < s->nb_streams; i++) {
6115 AVStream *st= s->streams[i];
6116 MOVTrack *track= &mov->tracks[i];
6118 /* copy extradata if it exists */
6119 if (st->codecpar->extradata_size) {
6120 if (st->codecpar->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
6121 mov_create_dvd_sub_decoder_specific_info(track, st);
6122 else if (!TAG_IS_AVCI(track->tag) && st->codecpar->codec_id != AV_CODEC_ID_DNXHD) {
6123 track->vos_len = st->codecpar->extradata_size;
6124 track->vos_data = av_malloc(track->vos_len);
6125 if (!track->vos_data) {
6126 return AVERROR(ENOMEM);
6128 memcpy(track->vos_data, st->codecpar->extradata, track->vos_len);
6132 if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ||
6133 track->par->channel_layout != AV_CH_LAYOUT_MONO)
6136 for (j = 0; j < s->nb_streams; j++) {
6137 AVStream *stj= s->streams[j];
6138 MOVTrack *trackj= &mov->tracks[j];
6142 if (stj->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ||
6143 trackj->par->channel_layout != AV_CH_LAYOUT_MONO ||
6144 trackj->language != track->language ||
6145 trackj->tag != track->tag
6148 track->multichannel_as_mono++;
6152 if (!(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
6153 if ((ret = mov_write_identification(pb, s)) < 0)
6157 if (mov->reserved_moov_size){
6158 mov->reserved_header_pos = avio_tell(pb);
6159 if (mov->reserved_moov_size > 0)
6160 avio_skip(pb, mov->reserved_moov_size);
6163 if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
6164 /* If no fragmentation options have been set, set a default. */
6165 if (!(mov->flags & (FF_MOV_FLAG_FRAG_KEYFRAME |
6166 FF_MOV_FLAG_FRAG_CUSTOM)) &&
6167 !mov->max_fragment_duration && !mov->max_fragment_size)
6168 mov->flags |= FF_MOV_FLAG_FRAG_KEYFRAME;
6170 if (mov->flags & FF_MOV_FLAG_FASTSTART)
6171 mov->reserved_header_pos = avio_tell(pb);
6172 mov_write_mdat_tag(pb, mov);
6175 ff_parse_creation_time_metadata(s, &mov->time, 1);
6177 mov->time += 0x7C25B080; // 1970 based -> 1904 based
6179 if (mov->chapter_track)
6180 if ((ret = mov_create_chapter_track(s, mov->chapter_track)) < 0)
6183 if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
6184 /* Initialize the hint tracks for each audio and video stream */
6185 for (i = 0; i < s->nb_streams; i++) {
6186 AVStream *st = s->streams[i];
6187 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ||
6188 st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
6189 if ((ret = ff_mov_init_hinting(s, hint_track, i)) < 0)
6196 if (mov->nb_meta_tmcd) {
6197 /* Initialize the tmcd tracks */
6198 for (i = 0; i < s->nb_streams; i++) {
6199 AVStream *st = s->streams[i];
6202 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
6205 t = av_dict_get(st->metadata, "timecode", NULL, 0);
6208 if (mov_check_timecode_track(s, &tc, i, t->value) < 0)
6210 if ((ret = mov_create_timecode_track(s, tmcd_track, i, tc)) < 0)
6219 if (mov->flags & FF_MOV_FLAG_ISML)
6220 mov_write_isml_manifest(pb, mov, s);
6222 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV &&
6223 !(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
6224 if ((ret = mov_write_moov_tag(pb, mov, s)) < 0)
6227 mov->moov_written = 1;
6228 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
6229 mov->reserved_header_pos = avio_tell(pb);
6235 static int get_moov_size(AVFormatContext *s)
6238 AVIOContext *moov_buf;
6239 MOVMuxContext *mov = s->priv_data;
6241 if ((ret = ffio_open_null_buf(&moov_buf)) < 0)
6243 if ((ret = mov_write_moov_tag(moov_buf, mov, s)) < 0)
6245 return ffio_close_null_buf(moov_buf);
6248 static int get_sidx_size(AVFormatContext *s)
6252 MOVMuxContext *mov = s->priv_data;
6254 if ((ret = ffio_open_null_buf(&buf)) < 0)
6256 mov_write_sidx_tags(buf, mov, -1, 0);
6257 return ffio_close_null_buf(buf);
6261 * This function gets the moov size if moved to the top of the file: the chunk
6262 * offset table can switch between stco (32-bit entries) to co64 (64-bit
6263 * entries) when the moov is moved to the beginning, so the size of the moov
6264 * would change. It also updates the chunk offset tables.
6266 static int compute_moov_size(AVFormatContext *s)
6268 int i, moov_size, moov_size2;
6269 MOVMuxContext *mov = s->priv_data;
6271 moov_size = get_moov_size(s);
6275 for (i = 0; i < mov->nb_streams; i++)
6276 mov->tracks[i].data_offset += moov_size;
6278 moov_size2 = get_moov_size(s);
6282 /* if the size changed, we just switched from stco to co64 and need to
6283 * update the offsets */
6284 if (moov_size2 != moov_size)
6285 for (i = 0; i < mov->nb_streams; i++)
6286 mov->tracks[i].data_offset += moov_size2 - moov_size;
6291 static int compute_sidx_size(AVFormatContext *s)
6294 MOVMuxContext *mov = s->priv_data;
6296 sidx_size = get_sidx_size(s);
6300 for (i = 0; i < mov->nb_streams; i++)
6301 mov->tracks[i].data_offset += sidx_size;
6306 static int shift_data(AVFormatContext *s)
6308 int ret = 0, moov_size;
6309 MOVMuxContext *mov = s->priv_data;
6310 int64_t pos, pos_end = avio_tell(s->pb);
6311 uint8_t *buf, *read_buf[2];
6312 int read_buf_id = 0;
6314 AVIOContext *read_pb;
6316 if (mov->flags & FF_MOV_FLAG_FRAGMENT)
6317 moov_size = compute_sidx_size(s);
6319 moov_size = compute_moov_size(s);
6323 buf = av_malloc(moov_size * 2);
6325 return AVERROR(ENOMEM);
6327 read_buf[1] = buf + moov_size;
6329 /* Shift the data: the AVIO context of the output can only be used for
6330 * writing, so we re-open the same output, but for reading. It also avoids
6331 * a read/seek/write/seek back and forth. */
6333 ret = s->io_open(s, &read_pb, s->filename, AVIO_FLAG_READ, NULL);
6335 av_log(s, AV_LOG_ERROR, "Unable to re-open %s output file for "
6336 "the second pass (faststart)\n", s->filename);
6340 /* mark the end of the shift to up to the last data we wrote, and get ready
6342 pos_end = avio_tell(s->pb);
6343 avio_seek(s->pb, mov->reserved_header_pos + moov_size, SEEK_SET);
6345 /* start reading at where the new moov will be placed */
6346 avio_seek(read_pb, mov->reserved_header_pos, SEEK_SET);
6347 pos = avio_tell(read_pb);
6349 #define READ_BLOCK do { \
6350 read_size[read_buf_id] = avio_read(read_pb, read_buf[read_buf_id], moov_size); \
6354 /* shift data by chunk of at most moov_size */
6359 n = read_size[read_buf_id];
6362 avio_write(s->pb, read_buf[read_buf_id], n);
6364 } while (pos < pos_end);
6365 ff_format_io_close(s, &read_pb);
6372 static int mov_write_trailer(AVFormatContext *s)
6374 MOVMuxContext *mov = s->priv_data;
6375 AVIOContext *pb = s->pb;
6380 if (mov->need_rewrite_extradata) {
6381 for (i = 0; i < s->nb_streams; i++) {
6382 MOVTrack *track = &mov->tracks[i];
6383 AVCodecParameters *par = track->par;
6385 track->vos_len = par->extradata_size;
6386 track->vos_data = av_malloc(track->vos_len);
6387 if (!track->vos_data)
6388 return AVERROR(ENOMEM);
6389 memcpy(track->vos_data, par->extradata, track->vos_len);
6391 mov->need_rewrite_extradata = 0;
6395 * Before actually writing the trailer, make sure that there are no
6396 * dangling subtitles, that need a terminating sample.
6398 for (i = 0; i < mov->nb_streams; i++) {
6399 MOVTrack *trk = &mov->tracks[i];
6400 if (trk->par->codec_id == AV_CODEC_ID_MOV_TEXT &&
6401 !trk->last_sample_is_subtitle_end) {
6402 mov_write_subtitle_end_packet(s, i, trk->track_duration);
6403 trk->last_sample_is_subtitle_end = 1;
6407 // If there were no chapters when the header was written, but there
6408 // are chapters now, write them in the trailer. This only works
6409 // when we are not doing fragments.
6410 if (!mov->chapter_track && !(mov->flags & FF_MOV_FLAG_FRAGMENT)) {
6411 if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters) {
6412 mov->chapter_track = mov->nb_streams++;
6413 if ((res = mov_create_chapter_track(s, mov->chapter_track)) < 0)
6418 if (!(mov->flags & FF_MOV_FLAG_FRAGMENT)) {
6419 moov_pos = avio_tell(pb);
6421 /* Write size of mdat tag */
6422 if (mov->mdat_size + 8 <= UINT32_MAX) {
6423 avio_seek(pb, mov->mdat_pos, SEEK_SET);
6424 avio_wb32(pb, mov->mdat_size + 8);
6426 /* overwrite 'wide' placeholder atom */
6427 avio_seek(pb, mov->mdat_pos - 8, SEEK_SET);
6428 /* special value: real atom size will be 64 bit value after
6431 ffio_wfourcc(pb, "mdat");
6432 avio_wb64(pb, mov->mdat_size + 16);
6434 avio_seek(pb, mov->reserved_moov_size > 0 ? mov->reserved_header_pos : moov_pos, SEEK_SET);
6436 if (mov->flags & FF_MOV_FLAG_FASTSTART) {
6437 av_log(s, AV_LOG_INFO, "Starting second pass: moving the moov atom to the beginning of the file\n");
6438 res = shift_data(s);
6441 avio_seek(pb, mov->reserved_header_pos, SEEK_SET);
6442 if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
6444 } else if (mov->reserved_moov_size > 0) {
6446 if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
6448 size = mov->reserved_moov_size - (avio_tell(pb) - mov->reserved_header_pos);
6450 av_log(s, AV_LOG_ERROR, "reserved_moov_size is too small, needed %"PRId64" additional\n", 8-size);
6451 return AVERROR(EINVAL);
6453 avio_wb32(pb, size);
6454 ffio_wfourcc(pb, "free");
6455 ffio_fill(pb, 0, size - 8);
6456 avio_seek(pb, moov_pos, SEEK_SET);
6458 if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
6463 mov_auto_flush_fragment(s, 1);
6464 for (i = 0; i < mov->nb_streams; i++)
6465 mov->tracks[i].data_offset = 0;
6466 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) {
6468 av_log(s, AV_LOG_INFO, "Starting second pass: inserting sidx atoms\n");
6469 res = shift_data(s);
6472 end = avio_tell(pb);
6473 avio_seek(pb, mov->reserved_header_pos, SEEK_SET);
6474 mov_write_sidx_tags(pb, mov, -1, 0);
6475 avio_seek(pb, end, SEEK_SET);
6476 avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_TRAILER);
6477 mov_write_mfra_tag(pb, mov);
6478 } else if (!(mov->flags & FF_MOV_FLAG_SKIP_TRAILER)) {
6479 avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_TRAILER);
6480 mov_write_mfra_tag(pb, mov);
6487 static int mov_check_bitstream(struct AVFormatContext *s, const AVPacket *pkt)
6490 AVStream *st = s->streams[pkt->stream_index];
6492 if (st->codecpar->codec_id == AV_CODEC_ID_AAC) {
6493 if (pkt->size > 2 && (AV_RB16(pkt->data) & 0xfff0) == 0xfff0)
6494 ret = ff_stream_add_bitstream_filter(st, "aac_adtstoasc", NULL);
6495 } else if (st->codecpar->codec_id == AV_CODEC_ID_VP9) {
6496 ret = ff_stream_add_bitstream_filter(st, "vp9_superframe", NULL);
6502 static const AVCodecTag codec_3gp_tags[] = {
6503 { AV_CODEC_ID_H263, MKTAG('s','2','6','3') },
6504 { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
6505 { AV_CODEC_ID_MPEG4, MKTAG('m','p','4','v') },
6506 { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
6507 { AV_CODEC_ID_AMR_NB, MKTAG('s','a','m','r') },
6508 { AV_CODEC_ID_AMR_WB, MKTAG('s','a','w','b') },
6509 { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
6510 { AV_CODEC_ID_NONE, 0 },
6513 const AVCodecTag codec_mp4_tags[] = {
6514 { AV_CODEC_ID_MPEG4 , MKTAG('m', 'p', '4', 'v') },
6515 { AV_CODEC_ID_H264 , MKTAG('a', 'v', 'c', '1') },
6516 { AV_CODEC_ID_HEVC , MKTAG('h', 'e', 'v', '1') },
6517 { AV_CODEC_ID_HEVC , MKTAG('h', 'v', 'c', '1') },
6518 { AV_CODEC_ID_MPEG2VIDEO , MKTAG('m', 'p', '4', 'v') },
6519 { AV_CODEC_ID_MPEG1VIDEO , MKTAG('m', 'p', '4', 'v') },
6520 { AV_CODEC_ID_MJPEG , MKTAG('m', 'p', '4', 'v') },
6521 { AV_CODEC_ID_PNG , MKTAG('m', 'p', '4', 'v') },
6522 { AV_CODEC_ID_JPEG2000 , MKTAG('m', 'p', '4', 'v') },
6523 { AV_CODEC_ID_VC1 , MKTAG('v', 'c', '-', '1') },
6524 { AV_CODEC_ID_DIRAC , MKTAG('d', 'r', 'a', 'c') },
6525 { AV_CODEC_ID_TSCC2 , MKTAG('m', 'p', '4', 'v') },
6526 { AV_CODEC_ID_VP9 , MKTAG('v', 'p', '0', '9') },
6527 { AV_CODEC_ID_AAC , MKTAG('m', 'p', '4', 'a') },
6528 { AV_CODEC_ID_MP4ALS , MKTAG('m', 'p', '4', 'a') },
6529 { AV_CODEC_ID_MP3 , MKTAG('m', 'p', '4', 'a') },
6530 { AV_CODEC_ID_MP2 , MKTAG('m', 'p', '4', 'a') },
6531 { AV_CODEC_ID_AC3 , MKTAG('a', 'c', '-', '3') },
6532 { AV_CODEC_ID_EAC3 , MKTAG('e', 'c', '-', '3') },
6533 { AV_CODEC_ID_DTS , MKTAG('m', 'p', '4', 'a') },
6534 { AV_CODEC_ID_FLAC , MKTAG('f', 'L', 'a', 'C') },
6535 { AV_CODEC_ID_OPUS , MKTAG('O', 'p', 'u', 's') },
6536 { AV_CODEC_ID_VORBIS , MKTAG('m', 'p', '4', 'a') },
6537 { AV_CODEC_ID_QCELP , MKTAG('m', 'p', '4', 'a') },
6538 { AV_CODEC_ID_EVRC , MKTAG('m', 'p', '4', 'a') },
6539 { AV_CODEC_ID_DVD_SUBTITLE, MKTAG('m', 'p', '4', 's') },
6540 { AV_CODEC_ID_MOV_TEXT , MKTAG('t', 'x', '3', 'g') },
6541 { AV_CODEC_ID_NONE , 0 },
6544 const AVCodecTag codec_ism_tags[] = {
6545 { AV_CODEC_ID_WMAPRO , MKTAG('w', 'm', 'a', ' ') },
6546 { AV_CODEC_ID_NONE , 0 },
6549 static const AVCodecTag codec_ipod_tags[] = {
6550 { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
6551 { AV_CODEC_ID_MPEG4, MKTAG('m','p','4','v') },
6552 { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
6553 { AV_CODEC_ID_ALAC, MKTAG('a','l','a','c') },
6554 { AV_CODEC_ID_AC3, MKTAG('a','c','-','3') },
6555 { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
6556 { AV_CODEC_ID_MOV_TEXT, MKTAG('t','e','x','t') },
6557 { AV_CODEC_ID_NONE, 0 },
6560 static const AVCodecTag codec_f4v_tags[] = {
6561 { AV_CODEC_ID_MP3, MKTAG('.','m','p','3') },
6562 { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
6563 { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
6564 { AV_CODEC_ID_VP6A, MKTAG('V','P','6','A') },
6565 { AV_CODEC_ID_VP6F, MKTAG('V','P','6','F') },
6566 { AV_CODEC_ID_NONE, 0 },
6569 #if CONFIG_MOV_MUXER
6571 AVOutputFormat ff_mov_muxer = {
6573 .long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
6574 .extensions = "mov",
6575 .priv_data_size = sizeof(MOVMuxContext),
6576 .audio_codec = AV_CODEC_ID_AAC,
6577 .video_codec = CONFIG_LIBX264_ENCODER ?
6578 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
6580 .write_header = mov_write_header,
6581 .write_packet = mov_write_packet,
6582 .write_trailer = mov_write_trailer,
6584 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6585 .codec_tag = (const AVCodecTag* const []){
6586 ff_codec_movvideo_tags, ff_codec_movaudio_tags, 0
6588 .check_bitstream = mov_check_bitstream,
6589 .priv_class = &mov_muxer_class,
6592 #if CONFIG_TGP_MUXER
6594 AVOutputFormat ff_tgp_muxer = {
6596 .long_name = NULL_IF_CONFIG_SMALL("3GP (3GPP file format)"),
6597 .extensions = "3gp",
6598 .priv_data_size = sizeof(MOVMuxContext),
6599 .audio_codec = AV_CODEC_ID_AMR_NB,
6600 .video_codec = AV_CODEC_ID_H263,
6602 .write_header = mov_write_header,
6603 .write_packet = mov_write_packet,
6604 .write_trailer = mov_write_trailer,
6606 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6607 .codec_tag = (const AVCodecTag* const []){ codec_3gp_tags, 0 },
6608 .check_bitstream = mov_check_bitstream,
6609 .priv_class = &tgp_muxer_class,
6612 #if CONFIG_MP4_MUXER
6614 AVOutputFormat ff_mp4_muxer = {
6616 .long_name = NULL_IF_CONFIG_SMALL("MP4 (MPEG-4 Part 14)"),
6617 .mime_type = "video/mp4",
6618 .extensions = "mp4",
6619 .priv_data_size = sizeof(MOVMuxContext),
6620 .audio_codec = AV_CODEC_ID_AAC,
6621 .video_codec = CONFIG_LIBX264_ENCODER ?
6622 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
6624 .write_header = mov_write_header,
6625 .write_packet = mov_write_packet,
6626 .write_trailer = mov_write_trailer,
6628 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6629 .codec_tag = (const AVCodecTag* const []){ codec_mp4_tags, 0 },
6630 .check_bitstream = mov_check_bitstream,
6631 .priv_class = &mp4_muxer_class,
6634 #if CONFIG_PSP_MUXER
6636 AVOutputFormat ff_psp_muxer = {
6638 .long_name = NULL_IF_CONFIG_SMALL("PSP MP4 (MPEG-4 Part 14)"),
6639 .extensions = "mp4,psp",
6640 .priv_data_size = sizeof(MOVMuxContext),
6641 .audio_codec = AV_CODEC_ID_AAC,
6642 .video_codec = CONFIG_LIBX264_ENCODER ?
6643 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
6645 .write_header = mov_write_header,
6646 .write_packet = mov_write_packet,
6647 .write_trailer = mov_write_trailer,
6649 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6650 .codec_tag = (const AVCodecTag* const []){ codec_mp4_tags, 0 },
6651 .check_bitstream = mov_check_bitstream,
6652 .priv_class = &psp_muxer_class,
6655 #if CONFIG_TG2_MUXER
6657 AVOutputFormat ff_tg2_muxer = {
6659 .long_name = NULL_IF_CONFIG_SMALL("3GP2 (3GPP2 file format)"),
6660 .extensions = "3g2",
6661 .priv_data_size = sizeof(MOVMuxContext),
6662 .audio_codec = AV_CODEC_ID_AMR_NB,
6663 .video_codec = AV_CODEC_ID_H263,
6665 .write_header = mov_write_header,
6666 .write_packet = mov_write_packet,
6667 .write_trailer = mov_write_trailer,
6669 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6670 .codec_tag = (const AVCodecTag* const []){ codec_3gp_tags, 0 },
6671 .check_bitstream = mov_check_bitstream,
6672 .priv_class = &tg2_muxer_class,
6675 #if CONFIG_IPOD_MUXER
6677 AVOutputFormat ff_ipod_muxer = {
6679 .long_name = NULL_IF_CONFIG_SMALL("iPod H.264 MP4 (MPEG-4 Part 14)"),
6680 .mime_type = "video/mp4",
6681 .extensions = "m4v,m4a,m4b",
6682 .priv_data_size = sizeof(MOVMuxContext),
6683 .audio_codec = AV_CODEC_ID_AAC,
6684 .video_codec = AV_CODEC_ID_H264,
6686 .write_header = mov_write_header,
6687 .write_packet = mov_write_packet,
6688 .write_trailer = mov_write_trailer,
6690 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6691 .codec_tag = (const AVCodecTag* const []){ codec_ipod_tags, 0 },
6692 .check_bitstream = mov_check_bitstream,
6693 .priv_class = &ipod_muxer_class,
6696 #if CONFIG_ISMV_MUXER
6698 AVOutputFormat ff_ismv_muxer = {
6700 .long_name = NULL_IF_CONFIG_SMALL("ISMV/ISMA (Smooth Streaming)"),
6701 .mime_type = "video/mp4",
6702 .extensions = "ismv,isma",
6703 .priv_data_size = sizeof(MOVMuxContext),
6704 .audio_codec = AV_CODEC_ID_AAC,
6705 .video_codec = AV_CODEC_ID_H264,
6707 .write_header = mov_write_header,
6708 .write_packet = mov_write_packet,
6709 .write_trailer = mov_write_trailer,
6711 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6712 .codec_tag = (const AVCodecTag* const []){
6713 codec_mp4_tags, codec_ism_tags, 0 },
6714 .check_bitstream = mov_check_bitstream,
6715 .priv_class = &ismv_muxer_class,
6718 #if CONFIG_F4V_MUXER
6720 AVOutputFormat ff_f4v_muxer = {
6722 .long_name = NULL_IF_CONFIG_SMALL("F4V Adobe Flash Video"),
6723 .mime_type = "application/f4v",
6724 .extensions = "f4v",
6725 .priv_data_size = sizeof(MOVMuxContext),
6726 .audio_codec = AV_CODEC_ID_AAC,
6727 .video_codec = AV_CODEC_ID_H264,
6729 .write_header = mov_write_header,
6730 .write_packet = mov_write_packet,
6731 .write_trailer = mov_write_trailer,
6733 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH,
6734 .codec_tag = (const AVCodecTag* const []){ codec_f4v_tags, 0 },
6735 .check_bitstream = mov_check_bitstream,
6736 .priv_class = &f4v_muxer_class,