3 * Copyright (c) 2003 Thomas Raivio
4 * Copyright (c) 2004 Gildas Bazin <gbazin at videolan dot org>
5 * Copyright (c) 2009 Baptiste Coudurier <baptiste dot coudurier at gmail dot com>
7 * This file is part of FFmpeg.
9 * FFmpeg is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
14 * FFmpeg is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with FFmpeg; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
29 #include "avio_internal.h"
34 #include "libavcodec/ac3_parser.h"
35 #include "libavcodec/dnxhddata.h"
36 #include "libavcodec/flac.h"
37 #include "libavcodec/get_bits.h"
39 #include "libavcodec/internal.h"
40 #include "libavcodec/put_bits.h"
41 #include "libavcodec/vc1_common.h"
42 #include "libavcodec/raw.h"
44 #include "libavutil/avstring.h"
45 #include "libavutil/intfloat.h"
46 #include "libavutil/mathematics.h"
47 #include "libavutil/libm.h"
48 #include "libavutil/opt.h"
49 #include "libavutil/dict.h"
50 #include "libavutil/pixdesc.h"
51 #include "libavutil/stereo3d.h"
52 #include "libavutil/timecode.h"
53 #include "libavutil/color_utils.h"
59 static const AVOption options[] = {
60 { "movflags", "MOV muxer flags", offsetof(MOVMuxContext, flags), AV_OPT_TYPE_FLAGS, {.i64 = 0}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
61 { "rtphint", "Add RTP hint tracks", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_RTP_HINT}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
62 { "moov_size", "maximum moov size so it can be placed at the begin", offsetof(MOVMuxContext, reserved_moov_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, 0 },
63 { "empty_moov", "Make the initial moov atom empty", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_EMPTY_MOOV}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
64 { "frag_keyframe", "Fragment at video keyframes", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FRAG_KEYFRAME}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
65 { "separate_moof", "Write separate moof/mdat atoms for each track", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_SEPARATE_MOOF}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
66 { "frag_custom", "Flush fragments on caller requests", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FRAG_CUSTOM}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
67 { "isml", "Create a live smooth streaming feed (for pushing to a publishing point)", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_ISML}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
68 { "faststart", "Run a second pass to put the index (moov atom) at the beginning of the file", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FASTSTART}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
69 { "omit_tfhd_offset", "Omit the base data offset in tfhd atoms", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_OMIT_TFHD_OFFSET}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
70 { "disable_chpl", "Disable Nero chapter atom", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_DISABLE_CHPL}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
71 { "default_base_moof", "Set the default-base-is-moof flag in tfhd atoms", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_DEFAULT_BASE_MOOF}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
72 { "dash", "Write DASH compatible fragmented MP4", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_DASH}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
73 { "frag_discont", "Signal that the next fragment is discontinuous from earlier ones", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FRAG_DISCONT}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
74 { "delay_moov", "Delay writing the initial moov until the first fragment is cut, or until the first fragment flush", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_DELAY_MOOV}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
75 { "global_sidx", "Write a global sidx index at the start of the file", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_GLOBAL_SIDX}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
76 { "write_colr", "Write colr atom (Experimental, may be renamed or changed, do not use from scripts)", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_WRITE_COLR}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
77 { "write_gama", "Write deprecated gama atom", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_WRITE_GAMA}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
78 { "use_metadata_tags", "Use mdta atom for metadata.", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_USE_MDTA}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
79 { "skip_trailer", "Skip writing the mfra/tfra/mfro trailer for fragmented files", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_SKIP_TRAILER}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
80 FF_RTP_FLAG_OPTS(MOVMuxContext, rtp_flags),
81 { "skip_iods", "Skip writing iods atom.", offsetof(MOVMuxContext, iods_skip), AV_OPT_TYPE_BOOL, {.i64 = 1}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM},
82 { "iods_audio_profile", "iods audio profile atom.", offsetof(MOVMuxContext, iods_audio_profile), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 255, AV_OPT_FLAG_ENCODING_PARAM},
83 { "iods_video_profile", "iods video profile atom.", offsetof(MOVMuxContext, iods_video_profile), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 255, AV_OPT_FLAG_ENCODING_PARAM},
84 { "frag_duration", "Maximum fragment duration", offsetof(MOVMuxContext, max_fragment_duration), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
85 { "min_frag_duration", "Minimum fragment duration", offsetof(MOVMuxContext, min_fragment_duration), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
86 { "frag_size", "Maximum fragment size", offsetof(MOVMuxContext, max_fragment_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
87 { "ism_lookahead", "Number of lookahead entries for ISM files", offsetof(MOVMuxContext, ism_lookahead), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
88 { "video_track_timescale", "set timescale of all video tracks", offsetof(MOVMuxContext, video_track_timescale), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
89 { "brand", "Override major brand", offsetof(MOVMuxContext, major_brand), AV_OPT_TYPE_STRING, {.str = NULL}, .flags = AV_OPT_FLAG_ENCODING_PARAM },
90 { "use_editlist", "use edit list", offsetof(MOVMuxContext, use_editlist), AV_OPT_TYPE_BOOL, {.i64 = -1}, -1, 1, AV_OPT_FLAG_ENCODING_PARAM},
91 { "fragment_index", "Fragment number of the next fragment", offsetof(MOVMuxContext, fragments), AV_OPT_TYPE_INT, {.i64 = 1}, 1, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
92 { "mov_gamma", "gamma value for gama atom", offsetof(MOVMuxContext, gamma), AV_OPT_TYPE_FLOAT, {.dbl = 0.0 }, 0.0, 10, AV_OPT_FLAG_ENCODING_PARAM},
93 { "frag_interleave", "Interleave samples within fragments (max number of consecutive samples, lower is tighter interleaving, but with more overhead)", offsetof(MOVMuxContext, frag_interleave), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM },
94 { "encryption_scheme", "Configures the encryption scheme, allowed values are none, cenc-aes-ctr", offsetof(MOVMuxContext, encryption_scheme_str), AV_OPT_TYPE_STRING, {.str = NULL}, .flags = AV_OPT_FLAG_ENCODING_PARAM },
95 { "encryption_key", "The media encryption key (hex)", offsetof(MOVMuxContext, encryption_key), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_ENCODING_PARAM },
96 { "encryption_kid", "The media encryption key identifier (hex)", offsetof(MOVMuxContext, encryption_kid), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_ENCODING_PARAM },
97 { "use_stream_ids_as_track_ids", "use stream ids as track ids", offsetof(MOVMuxContext, use_stream_ids_as_track_ids), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM},
98 { "write_tmcd", "force or disable writing tmcd", offsetof(MOVMuxContext, write_tmcd), AV_OPT_TYPE_BOOL, {.i64 = -1}, -1, 1, AV_OPT_FLAG_ENCODING_PARAM},
102 #define MOV_CLASS(flavor)\
103 static const AVClass flavor ## _muxer_class = {\
104 .class_name = #flavor " muxer",\
105 .item_name = av_default_item_name,\
107 .version = LIBAVUTIL_VERSION_INT,\
110 static int get_moov_size(AVFormatContext *s);
112 static int utf8len(const uint8_t *b)
117 GET_UTF8(val, *b++, return -1;)
123 //FIXME support 64 bit variant with wide placeholders
124 static int64_t update_size(AVIOContext *pb, int64_t pos)
126 int64_t curpos = avio_tell(pb);
127 avio_seek(pb, pos, SEEK_SET);
128 avio_wb32(pb, curpos - pos); /* rewrite size */
129 avio_seek(pb, curpos, SEEK_SET);
134 static int co64_required(const MOVTrack *track)
136 if (track->entry > 0 && track->cluster[track->entry - 1].pos + track->data_offset > UINT32_MAX)
141 /* Chunk offset atom */
142 static int mov_write_stco_tag(AVIOContext *pb, MOVTrack *track)
145 int mode64 = co64_required(track); // use 32 bit size variant if possible
146 int64_t pos = avio_tell(pb);
147 avio_wb32(pb, 0); /* size */
149 ffio_wfourcc(pb, "co64");
151 ffio_wfourcc(pb, "stco");
152 avio_wb32(pb, 0); /* version & flags */
153 avio_wb32(pb, track->chunkCount); /* entry count */
154 for (i = 0; i < track->entry; i++) {
155 if (!track->cluster[i].chunkNum)
158 avio_wb64(pb, track->cluster[i].pos + track->data_offset);
160 avio_wb32(pb, track->cluster[i].pos + track->data_offset);
162 return update_size(pb, pos);
165 /* Sample size atom */
166 static int mov_write_stsz_tag(AVIOContext *pb, MOVTrack *track)
169 int i, j, entries = 0, tst = -1, oldtst = -1;
171 int64_t pos = avio_tell(pb);
172 avio_wb32(pb, 0); /* size */
173 ffio_wfourcc(pb, "stsz");
174 avio_wb32(pb, 0); /* version & flags */
176 for (i = 0; i < track->entry; i++) {
177 tst = track->cluster[i].size / track->cluster[i].entries;
178 if (oldtst != -1 && tst != oldtst)
181 entries += track->cluster[i].entries;
183 if (equalChunks && track->entry) {
184 int sSize = track->entry ? track->cluster[0].size / track->cluster[0].entries : 0;
185 sSize = FFMAX(1, sSize); // adpcm mono case could make sSize == 0
186 avio_wb32(pb, sSize); // sample size
187 avio_wb32(pb, entries); // sample count
189 avio_wb32(pb, 0); // sample size
190 avio_wb32(pb, entries); // sample count
191 for (i = 0; i < track->entry; i++) {
192 for (j = 0; j < track->cluster[i].entries; j++) {
193 avio_wb32(pb, track->cluster[i].size /
194 track->cluster[i].entries);
198 return update_size(pb, pos);
201 /* Sample to chunk atom */
202 static int mov_write_stsc_tag(AVIOContext *pb, MOVTrack *track)
204 int index = 0, oldval = -1, i;
205 int64_t entryPos, curpos;
207 int64_t pos = avio_tell(pb);
208 avio_wb32(pb, 0); /* size */
209 ffio_wfourcc(pb, "stsc");
210 avio_wb32(pb, 0); // version & flags
211 entryPos = avio_tell(pb);
212 avio_wb32(pb, track->chunkCount); // entry count
213 for (i = 0; i < track->entry; i++) {
214 if (oldval != track->cluster[i].samples_in_chunk && track->cluster[i].chunkNum) {
215 avio_wb32(pb, track->cluster[i].chunkNum); // first chunk
216 avio_wb32(pb, track->cluster[i].samples_in_chunk); // samples per chunk
217 avio_wb32(pb, 0x1); // sample description index
218 oldval = track->cluster[i].samples_in_chunk;
222 curpos = avio_tell(pb);
223 avio_seek(pb, entryPos, SEEK_SET);
224 avio_wb32(pb, index); // rewrite size
225 avio_seek(pb, curpos, SEEK_SET);
227 return update_size(pb, pos);
230 /* Sync sample atom */
231 static int mov_write_stss_tag(AVIOContext *pb, MOVTrack *track, uint32_t flag)
233 int64_t curpos, entryPos;
235 int64_t pos = avio_tell(pb);
236 avio_wb32(pb, 0); // size
237 ffio_wfourcc(pb, flag == MOV_SYNC_SAMPLE ? "stss" : "stps");
238 avio_wb32(pb, 0); // version & flags
239 entryPos = avio_tell(pb);
240 avio_wb32(pb, track->entry); // entry count
241 for (i = 0; i < track->entry; i++) {
242 if (track->cluster[i].flags & flag) {
243 avio_wb32(pb, i + 1);
247 curpos = avio_tell(pb);
248 avio_seek(pb, entryPos, SEEK_SET);
249 avio_wb32(pb, index); // rewrite size
250 avio_seek(pb, curpos, SEEK_SET);
251 return update_size(pb, pos);
254 static int mov_write_amr_tag(AVIOContext *pb, MOVTrack *track)
256 avio_wb32(pb, 0x11); /* size */
257 if (track->mode == MODE_MOV) ffio_wfourcc(pb, "samr");
258 else ffio_wfourcc(pb, "damr");
259 ffio_wfourcc(pb, "FFMP");
260 avio_w8(pb, 0); /* decoder version */
262 avio_wb16(pb, 0x81FF); /* Mode set (all modes for AMR_NB) */
263 avio_w8(pb, 0x00); /* Mode change period (no restriction) */
264 avio_w8(pb, 0x01); /* Frames per sample */
268 static int mov_write_ac3_tag(AVIOContext *pb, MOVTrack *track)
273 int fscod, bsid, bsmod, acmod, lfeon, frmsizecod;
275 if (track->vos_len < 7)
279 ffio_wfourcc(pb, "dac3");
281 init_get_bits(&gbc, track->vos_data + 4, (track->vos_len - 4) * 8);
282 fscod = get_bits(&gbc, 2);
283 frmsizecod = get_bits(&gbc, 6);
284 bsid = get_bits(&gbc, 5);
285 bsmod = get_bits(&gbc, 3);
286 acmod = get_bits(&gbc, 3);
288 skip_bits(&gbc, 2); // dsurmod
290 if ((acmod & 1) && acmod != 1)
291 skip_bits(&gbc, 2); // cmixlev
293 skip_bits(&gbc, 2); // surmixlev
295 lfeon = get_bits1(&gbc);
297 init_put_bits(&pbc, buf, sizeof(buf));
298 put_bits(&pbc, 2, fscod);
299 put_bits(&pbc, 5, bsid);
300 put_bits(&pbc, 3, bsmod);
301 put_bits(&pbc, 3, acmod);
302 put_bits(&pbc, 1, lfeon);
303 put_bits(&pbc, 5, frmsizecod >> 1); // bit_rate_code
304 put_bits(&pbc, 5, 0); // reserved
306 flush_put_bits(&pbc);
307 avio_write(pb, buf, sizeof(buf));
317 /* Layout of the EC3SpecificBox */
318 /* maximum bitrate */
320 /* number of independent substreams */
323 /* sample rate code (see ff_ac3_sample_rate_tab) 2 bits */
325 /* bit stream identification 5 bits */
327 /* one bit reserved */
328 /* audio service mixing (not supported yet) 1 bit */
329 /* bit stream mode 3 bits */
331 /* audio coding mode 3 bits */
333 /* sub woofer on 1 bit */
335 /* 3 bits reserved */
336 /* number of dependent substreams associated with this substream 4 bits */
338 /* channel locations of the dependent substream(s), if any, 9 bits */
340 /* if there is no dependent substream, then one bit reserved instead */
341 } substream[1]; /* TODO: support 8 independent substreams */
344 #if CONFIG_AC3_PARSER
345 static int handle_eac3(MOVMuxContext *mov, AVPacket *pkt, MOVTrack *track)
348 AC3HeaderInfo tmp, *hdr = &tmp;
349 struct eac3_info *info;
352 if (!track->eac3_priv && !(track->eac3_priv = av_mallocz(sizeof(*info))))
353 return AVERROR(ENOMEM);
354 info = track->eac3_priv;
356 init_get_bits(&gbc, pkt->data, pkt->size * 8);
357 if (avpriv_ac3_parse_header(&gbc, &hdr) < 0) {
358 /* drop the packets until we see a good one */
360 av_log(mov, AV_LOG_WARNING, "Dropping invalid packet from start of the stream\n");
363 return AVERROR_INVALIDDATA;
366 info->data_rate = FFMAX(info->data_rate, hdr->bit_rate / 1000);
367 num_blocks = hdr->num_blocks;
369 if (!info->ec3_done) {
370 /* AC-3 substream must be the first one */
371 if (hdr->bitstream_id <= 10 && hdr->substreamid != 0)
372 return AVERROR(EINVAL);
374 /* this should always be the case, given that our AC-3 parser
375 * concatenates dependent frames to their independent parent */
376 if (hdr->frame_type == EAC3_FRAME_TYPE_INDEPENDENT) {
377 /* substream ids must be incremental */
378 if (hdr->substreamid > info->num_ind_sub + 1)
379 return AVERROR(EINVAL);
381 if (hdr->substreamid == info->num_ind_sub + 1) {
382 //info->num_ind_sub++;
383 avpriv_request_sample(track->par, "Multiple independent substreams");
384 return AVERROR_PATCHWELCOME;
385 } else if (hdr->substreamid < info->num_ind_sub ||
386 hdr->substreamid == 0 && info->substream[0].bsid) {
392 /* fill the info needed for the "dec3" atom */
393 info->substream[hdr->substreamid].fscod = hdr->sr_code;
394 info->substream[hdr->substreamid].bsid = hdr->bitstream_id;
395 info->substream[hdr->substreamid].bsmod = hdr->bitstream_mode;
396 info->substream[hdr->substreamid].acmod = hdr->channel_mode;
397 info->substream[hdr->substreamid].lfeon = hdr->lfe_on;
399 /* Parse dependent substream(s), if any */
400 if (pkt->size != hdr->frame_size) {
401 int cumul_size = hdr->frame_size;
402 int parent = hdr->substreamid;
404 while (cumul_size != pkt->size) {
406 init_get_bits(&gbc, pkt->data + cumul_size, (pkt->size - cumul_size) * 8);
407 if (avpriv_ac3_parse_header(&gbc, &hdr) < 0)
408 return AVERROR_INVALIDDATA;
409 if (hdr->frame_type != EAC3_FRAME_TYPE_DEPENDENT)
410 return AVERROR(EINVAL);
411 cumul_size += hdr->frame_size;
412 info->substream[parent].num_dep_sub++;
414 /* header is parsed up to lfeon, but custom channel map may be needed */
417 /* skip volume control params */
418 for (i = 0; i < (hdr->channel_mode ? 1 : 2); i++) {
419 skip_bits(&gbc, 5); // skip dialog normalization
420 if (get_bits1(&gbc)) {
421 skip_bits(&gbc, 8); // skip compression gain word
424 /* get the dependent stream channel map, if exists */
426 info->substream[parent].chan_loc |= (get_bits(&gbc, 16) >> 5) & 0x1f;
428 info->substream[parent].chan_loc |= hdr->channel_mode;
434 if (!info->num_blocks && num_blocks == 6)
436 else if (info->num_blocks + num_blocks > 6)
437 return AVERROR_INVALIDDATA;
439 if (!info->num_blocks) {
440 int ret = av_packet_ref(&info->pkt, pkt);
443 info->num_blocks = num_blocks;
447 if ((ret = av_grow_packet(&info->pkt, pkt->size)) < 0)
449 memcpy(info->pkt.data + info->pkt.size - pkt->size, pkt->data, pkt->size);
450 info->num_blocks += num_blocks;
451 info->pkt.duration += pkt->duration;
452 if ((ret = av_copy_packet_side_data(&info->pkt, pkt)) < 0)
454 if (info->num_blocks != 6)
456 av_packet_unref(pkt);
457 ret = av_packet_ref(pkt, &info->pkt);
460 av_packet_unref(&info->pkt);
461 info->num_blocks = 0;
468 static int mov_write_eac3_tag(AVIOContext *pb, MOVTrack *track)
472 struct eac3_info *info;
475 if (!track->eac3_priv)
476 return AVERROR(EINVAL);
478 info = track->eac3_priv;
479 size = 2 + 4 * (info->num_ind_sub + 1);
480 buf = av_malloc(size);
482 size = AVERROR(ENOMEM);
486 init_put_bits(&pbc, buf, size);
487 put_bits(&pbc, 13, info->data_rate);
488 put_bits(&pbc, 3, info->num_ind_sub);
489 for (i = 0; i <= info->num_ind_sub; i++) {
490 put_bits(&pbc, 2, info->substream[i].fscod);
491 put_bits(&pbc, 5, info->substream[i].bsid);
492 put_bits(&pbc, 1, 0); /* reserved */
493 put_bits(&pbc, 1, 0); /* asvc */
494 put_bits(&pbc, 3, info->substream[i].bsmod);
495 put_bits(&pbc, 3, info->substream[i].acmod);
496 put_bits(&pbc, 1, info->substream[i].lfeon);
497 put_bits(&pbc, 5, 0); /* reserved */
498 put_bits(&pbc, 4, info->substream[i].num_dep_sub);
499 if (!info->substream[i].num_dep_sub) {
500 put_bits(&pbc, 1, 0); /* reserved */
503 put_bits(&pbc, 9, info->substream[i].chan_loc);
506 flush_put_bits(&pbc);
508 avio_wb32(pb, size + 8);
509 ffio_wfourcc(pb, "dec3");
510 avio_write(pb, buf, size);
515 av_packet_unref(&info->pkt);
516 av_freep(&track->eac3_priv);
522 * This function writes extradata "as is".
523 * Extradata must be formatted like a valid atom (with size and tag).
525 static int mov_write_extradata_tag(AVIOContext *pb, MOVTrack *track)
527 avio_write(pb, track->par->extradata, track->par->extradata_size);
528 return track->par->extradata_size;
531 static int mov_write_enda_tag(AVIOContext *pb)
534 ffio_wfourcc(pb, "enda");
535 avio_wb16(pb, 1); /* little endian */
539 static int mov_write_enda_tag_be(AVIOContext *pb)
542 ffio_wfourcc(pb, "enda");
543 avio_wb16(pb, 0); /* big endian */
547 static void put_descr(AVIOContext *pb, int tag, unsigned int size)
552 avio_w8(pb, (size >> (7 * i)) | 0x80);
553 avio_w8(pb, size & 0x7F);
556 static unsigned compute_avg_bitrate(MOVTrack *track)
560 if (!track->track_duration)
562 for (i = 0; i < track->entry; i++)
563 size += track->cluster[i].size;
564 return size * 8 * track->timescale / track->track_duration;
567 static int mov_write_esds_tag(AVIOContext *pb, MOVTrack *track) // Basic
569 AVCPBProperties *props;
570 int64_t pos = avio_tell(pb);
571 int decoder_specific_info_len = track->vos_len ? 5 + track->vos_len : 0;
572 unsigned avg_bitrate;
574 avio_wb32(pb, 0); // size
575 ffio_wfourcc(pb, "esds");
576 avio_wb32(pb, 0); // Version
579 put_descr(pb, 0x03, 3 + 5+13 + decoder_specific_info_len + 5+1);
580 avio_wb16(pb, track->track_id);
581 avio_w8(pb, 0x00); // flags (= no flags)
583 // DecoderConfig descriptor
584 put_descr(pb, 0x04, 13 + decoder_specific_info_len);
586 // Object type indication
587 if ((track->par->codec_id == AV_CODEC_ID_MP2 ||
588 track->par->codec_id == AV_CODEC_ID_MP3) &&
589 track->par->sample_rate > 24000)
590 avio_w8(pb, 0x6B); // 11172-3
592 avio_w8(pb, ff_codec_get_tag(ff_mp4_obj_type, track->par->codec_id));
594 // the following fields is made of 6 bits to identify the streamtype (4 for video, 5 for audio)
595 // plus 1 bit to indicate upstream and 1 bit set to 1 (reserved)
596 if (track->par->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
597 avio_w8(pb, (0x38 << 2) | 1); // flags (= NeroSubpicStream)
598 else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
599 avio_w8(pb, 0x15); // flags (= Audiostream)
601 avio_w8(pb, 0x11); // flags (= Visualstream)
603 props = (AVCPBProperties*)av_stream_get_side_data(track->st, AV_PKT_DATA_CPB_PROPERTIES,
606 avio_wb24(pb, props ? props->buffer_size / 8 : 0); // Buffersize DB
608 avg_bitrate = compute_avg_bitrate(track);
609 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)
610 avio_wb32(pb, avg_bitrate);
612 if (track->vos_len) {
613 // DecoderSpecific info descriptor
614 put_descr(pb, 0x05, track->vos_len);
615 avio_write(pb, track->vos_data, track->vos_len);
619 put_descr(pb, 0x06, 1);
621 return update_size(pb, pos);
624 static int mov_pcm_le_gt16(enum AVCodecID codec_id)
626 return codec_id == AV_CODEC_ID_PCM_S24LE ||
627 codec_id == AV_CODEC_ID_PCM_S32LE ||
628 codec_id == AV_CODEC_ID_PCM_F32LE ||
629 codec_id == AV_CODEC_ID_PCM_F64LE;
632 static int mov_pcm_be_gt16(enum AVCodecID codec_id)
634 return codec_id == AV_CODEC_ID_PCM_S24BE ||
635 codec_id == AV_CODEC_ID_PCM_S32BE ||
636 codec_id == AV_CODEC_ID_PCM_F32BE ||
637 codec_id == AV_CODEC_ID_PCM_F64BE;
640 static int mov_write_ms_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
643 int64_t pos = avio_tell(pb);
645 avio_wl32(pb, track->tag); // store it byteswapped
646 track->par->codec_tag = av_bswap16(track->tag >> 16);
647 if ((ret = ff_put_wav_header(s, pb, track->par, 0)) < 0)
649 return update_size(pb, pos);
652 static int mov_write_wfex_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
655 int64_t pos = avio_tell(pb);
657 ffio_wfourcc(pb, "wfex");
658 if ((ret = ff_put_wav_header(s, pb, track->st->codecpar, FF_PUT_WAV_HEADER_FORCE_WAVEFORMATEX)) < 0)
660 return update_size(pb, pos);
663 static int mov_write_dfla_tag(AVIOContext *pb, MOVTrack *track)
665 int64_t pos = avio_tell(pb);
667 ffio_wfourcc(pb, "dfLa");
668 avio_w8(pb, 0); /* version */
669 avio_wb24(pb, 0); /* flags */
671 /* Expect the encoder to pass a METADATA_BLOCK_TYPE_STREAMINFO. */
672 if (track->par->extradata_size != FLAC_STREAMINFO_SIZE)
673 return AVERROR_INVALIDDATA;
675 /* TODO: Write other METADATA_BLOCK_TYPEs if the encoder makes them available. */
676 avio_w8(pb, 1 << 7 | FLAC_METADATA_TYPE_STREAMINFO); /* LastMetadataBlockFlag << 7 | BlockType */
677 avio_wb24(pb, track->par->extradata_size); /* Length */
678 avio_write(pb, track->par->extradata, track->par->extradata_size); /* BlockData[Length] */
680 return update_size(pb, pos);
683 static int mov_write_dops_tag(AVIOContext *pb, MOVTrack *track)
685 int64_t pos = avio_tell(pb);
687 ffio_wfourcc(pb, "dOps");
688 avio_w8(pb, 0); /* Version */
689 if (track->par->extradata_size < 19) {
690 av_log(pb, AV_LOG_ERROR, "invalid extradata size\n");
691 return AVERROR_INVALIDDATA;
693 /* extradata contains an Ogg OpusHead, other than byte-ordering and
694 OpusHead's preceeding magic/version, OpusSpecificBox is currently
696 avio_w8(pb, AV_RB8(track->par->extradata + 9)); /* OuputChannelCount */
697 avio_wb16(pb, AV_RL16(track->par->extradata + 10)); /* PreSkip */
698 avio_wb32(pb, AV_RL32(track->par->extradata + 12)); /* InputSampleRate */
699 avio_wb16(pb, AV_RL16(track->par->extradata + 16)); /* OutputGain */
700 /* Write the rest of the header out without byte-swapping. */
701 avio_write(pb, track->par->extradata + 18, track->par->extradata_size - 18);
703 return update_size(pb, pos);
706 static int mov_write_chan_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
708 uint32_t layout_tag, bitmap;
709 int64_t pos = avio_tell(pb);
711 layout_tag = ff_mov_get_channel_layout_tag(track->par->codec_id,
712 track->par->channel_layout,
715 av_log(s, AV_LOG_WARNING, "not writing 'chan' tag due to "
716 "lack of channel information\n");
720 if (track->multichannel_as_mono)
723 avio_wb32(pb, 0); // Size
724 ffio_wfourcc(pb, "chan"); // Type
725 avio_w8(pb, 0); // Version
726 avio_wb24(pb, 0); // Flags
727 avio_wb32(pb, layout_tag); // mChannelLayoutTag
728 avio_wb32(pb, bitmap); // mChannelBitmap
729 avio_wb32(pb, 0); // mNumberChannelDescriptions
731 return update_size(pb, pos);
734 static int mov_write_wave_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
736 int64_t pos = avio_tell(pb);
738 avio_wb32(pb, 0); /* size */
739 ffio_wfourcc(pb, "wave");
741 if (track->par->codec_id != AV_CODEC_ID_QDM2) {
742 avio_wb32(pb, 12); /* size */
743 ffio_wfourcc(pb, "frma");
744 avio_wl32(pb, track->tag);
747 if (track->par->codec_id == AV_CODEC_ID_AAC) {
748 /* useless atom needed by mplayer, ipod, not needed by quicktime */
749 avio_wb32(pb, 12); /* size */
750 ffio_wfourcc(pb, "mp4a");
752 mov_write_esds_tag(pb, track);
753 } else if (mov_pcm_le_gt16(track->par->codec_id)) {
754 mov_write_enda_tag(pb);
755 } else if (mov_pcm_be_gt16(track->par->codec_id)) {
756 mov_write_enda_tag_be(pb);
757 } else if (track->par->codec_id == AV_CODEC_ID_AMR_NB) {
758 mov_write_amr_tag(pb, track);
759 } else if (track->par->codec_id == AV_CODEC_ID_AC3) {
760 mov_write_ac3_tag(pb, track);
761 } else if (track->par->codec_id == AV_CODEC_ID_EAC3) {
762 mov_write_eac3_tag(pb, track);
763 } else if (track->par->codec_id == AV_CODEC_ID_ALAC ||
764 track->par->codec_id == AV_CODEC_ID_QDM2) {
765 mov_write_extradata_tag(pb, track);
766 } else if (track->par->codec_id == AV_CODEC_ID_ADPCM_MS ||
767 track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) {
768 mov_write_ms_tag(s, pb, track);
771 avio_wb32(pb, 8); /* size */
772 avio_wb32(pb, 0); /* null tag */
774 return update_size(pb, pos);
777 static int mov_write_dvc1_structs(MOVTrack *track, uint8_t *buf)
780 const uint8_t *start, *next, *end = track->vos_data + track->vos_len;
781 int unescaped_size, seq_found = 0;
782 int level = 0, interlace = 0;
783 int packet_seq = track->vc1_info.packet_seq;
784 int packet_entry = track->vc1_info.packet_entry;
785 int slices = track->vc1_info.slices;
788 if (track->start_dts == AV_NOPTS_VALUE) {
789 /* No packets written yet, vc1_info isn't authoritative yet. */
790 /* Assume inline sequence and entry headers. */
791 packet_seq = packet_entry = 1;
792 av_log(NULL, AV_LOG_WARNING,
793 "moov atom written before any packets, unable to write correct "
794 "dvc1 atom. Set the delay_moov flag to fix this.\n");
797 unescaped = av_mallocz(track->vos_len + AV_INPUT_BUFFER_PADDING_SIZE);
799 return AVERROR(ENOMEM);
800 start = find_next_marker(track->vos_data, end);
801 for (next = start; next < end; start = next) {
804 next = find_next_marker(start + 4, end);
805 size = next - start - 4;
808 unescaped_size = vc1_unescape_buffer(start + 4, size, unescaped);
809 init_get_bits(&gb, unescaped, 8 * unescaped_size);
810 if (AV_RB32(start) == VC1_CODE_SEQHDR) {
811 int profile = get_bits(&gb, 2);
812 if (profile != PROFILE_ADVANCED) {
814 return AVERROR(ENOSYS);
817 level = get_bits(&gb, 3);
818 /* chromaformat, frmrtq_postproc, bitrtq_postproc, postprocflag,
820 skip_bits_long(&gb, 2 + 3 + 5 + 1 + 2*12);
821 skip_bits(&gb, 1); /* broadcast */
822 interlace = get_bits1(&gb);
823 skip_bits(&gb, 4); /* tfcntrflag, finterpflag, reserved, psf */
828 return AVERROR(ENOSYS);
831 init_put_bits(&pbc, buf, 7);
832 /* VC1DecSpecStruc */
833 put_bits(&pbc, 4, 12); /* profile - advanced */
834 put_bits(&pbc, 3, level);
835 put_bits(&pbc, 1, 0); /* reserved */
836 /* VC1AdvDecSpecStruc */
837 put_bits(&pbc, 3, level);
838 put_bits(&pbc, 1, 0); /* cbr */
839 put_bits(&pbc, 6, 0); /* reserved */
840 put_bits(&pbc, 1, !interlace); /* no interlace */
841 put_bits(&pbc, 1, !packet_seq); /* no multiple seq */
842 put_bits(&pbc, 1, !packet_entry); /* no multiple entry */
843 put_bits(&pbc, 1, !slices); /* no slice code */
844 put_bits(&pbc, 1, 0); /* no bframe */
845 put_bits(&pbc, 1, 0); /* reserved */
848 if (track->st->avg_frame_rate.num > 0 && track->st->avg_frame_rate.den > 0)
849 put_bits32(&pbc, track->st->avg_frame_rate.num / track->st->avg_frame_rate.den);
851 put_bits32(&pbc, 0xffffffff);
853 flush_put_bits(&pbc);
860 static int mov_write_dvc1_tag(AVIOContext *pb, MOVTrack *track)
862 uint8_t buf[7] = { 0 };
865 if ((ret = mov_write_dvc1_structs(track, buf)) < 0)
868 avio_wb32(pb, track->vos_len + 8 + sizeof(buf));
869 ffio_wfourcc(pb, "dvc1");
870 avio_write(pb, buf, sizeof(buf));
871 avio_write(pb, track->vos_data, track->vos_len);
876 static int mov_write_glbl_tag(AVIOContext *pb, MOVTrack *track)
878 avio_wb32(pb, track->vos_len + 8);
879 ffio_wfourcc(pb, "glbl");
880 avio_write(pb, track->vos_data, track->vos_len);
881 return 8 + track->vos_len;
885 * Compute flags for 'lpcm' tag.
886 * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
888 static int mov_get_lpcm_flags(enum AVCodecID codec_id)
891 case AV_CODEC_ID_PCM_F32BE:
892 case AV_CODEC_ID_PCM_F64BE:
894 case AV_CODEC_ID_PCM_F32LE:
895 case AV_CODEC_ID_PCM_F64LE:
897 case AV_CODEC_ID_PCM_U8:
899 case AV_CODEC_ID_PCM_S16BE:
900 case AV_CODEC_ID_PCM_S24BE:
901 case AV_CODEC_ID_PCM_S32BE:
903 case AV_CODEC_ID_PCM_S8:
904 case AV_CODEC_ID_PCM_S16LE:
905 case AV_CODEC_ID_PCM_S24LE:
906 case AV_CODEC_ID_PCM_S32LE:
913 static int get_cluster_duration(MOVTrack *track, int cluster_idx)
917 if (cluster_idx >= track->entry)
920 if (cluster_idx + 1 == track->entry)
921 next_dts = track->track_duration + track->start_dts;
923 next_dts = track->cluster[cluster_idx + 1].dts;
925 next_dts -= track->cluster[cluster_idx].dts;
927 av_assert0(next_dts >= 0);
928 av_assert0(next_dts <= INT_MAX);
933 static int get_samples_per_packet(MOVTrack *track)
935 int i, first_duration;
937 // return track->par->frame_size;
939 /* use 1 for raw PCM */
940 if (!track->audio_vbr)
943 /* check to see if duration is constant for all clusters */
946 first_duration = get_cluster_duration(track, 0);
947 for (i = 1; i < track->entry; i++) {
948 if (get_cluster_duration(track, i) != first_duration)
951 return first_duration;
954 static int mov_write_audio_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
956 int64_t pos = avio_tell(pb);
958 uint32_t tag = track->tag;
960 if (track->mode == MODE_MOV) {
961 if (track->timescale > UINT16_MAX) {
962 if (mov_get_lpcm_flags(track->par->codec_id))
963 tag = AV_RL32("lpcm");
965 } else if (track->audio_vbr || mov_pcm_le_gt16(track->par->codec_id) ||
966 mov_pcm_be_gt16(track->par->codec_id) ||
967 track->par->codec_id == AV_CODEC_ID_ADPCM_MS ||
968 track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
969 track->par->codec_id == AV_CODEC_ID_QDM2) {
974 avio_wb32(pb, 0); /* size */
975 if (mov->encryption_scheme != MOV_ENC_NONE) {
976 ffio_wfourcc(pb, "enca");
978 avio_wl32(pb, tag); // store it byteswapped
980 avio_wb32(pb, 0); /* Reserved */
981 avio_wb16(pb, 0); /* Reserved */
982 avio_wb16(pb, 1); /* Data-reference index, XXX == 1 */
984 /* SoundDescription */
985 avio_wb16(pb, version); /* Version */
986 avio_wb16(pb, 0); /* Revision level */
987 avio_wb32(pb, 0); /* Reserved */
992 avio_wb16(pb, 0xfffe);
994 avio_wb32(pb, 0x00010000);
996 avio_wb64(pb, av_double2int(track->par->sample_rate));
997 avio_wb32(pb, track->par->channels);
998 avio_wb32(pb, 0x7F000000);
999 avio_wb32(pb, av_get_bits_per_sample(track->par->codec_id));
1000 avio_wb32(pb, mov_get_lpcm_flags(track->par->codec_id));
1001 avio_wb32(pb, track->sample_size);
1002 avio_wb32(pb, get_samples_per_packet(track));
1004 if (track->mode == MODE_MOV) {
1005 avio_wb16(pb, track->par->channels);
1006 if (track->par->codec_id == AV_CODEC_ID_PCM_U8 ||
1007 track->par->codec_id == AV_CODEC_ID_PCM_S8)
1008 avio_wb16(pb, 8); /* bits per sample */
1009 else if (track->par->codec_id == AV_CODEC_ID_ADPCM_G726)
1010 avio_wb16(pb, track->par->bits_per_coded_sample);
1013 avio_wb16(pb, track->audio_vbr ? -2 : 0); /* compression ID */
1014 } else { /* reserved for mp4/3gp */
1015 if (track->par->codec_id == AV_CODEC_ID_FLAC ||
1016 track->par->codec_id == AV_CODEC_ID_OPUS) {
1017 avio_wb16(pb, track->par->channels);
1021 if (track->par->codec_id == AV_CODEC_ID_FLAC) {
1022 avio_wb16(pb, track->par->bits_per_raw_sample);
1029 avio_wb16(pb, 0); /* packet size (= 0) */
1030 if (track->par->codec_id == AV_CODEC_ID_OPUS)
1031 avio_wb16(pb, 48000);
1033 avio_wb16(pb, track->par->sample_rate <= UINT16_MAX ?
1034 track->par->sample_rate : 0);
1035 avio_wb16(pb, 0); /* Reserved */
1038 if (version == 1) { /* SoundDescription V1 extended info */
1039 if (mov_pcm_le_gt16(track->par->codec_id) ||
1040 mov_pcm_be_gt16(track->par->codec_id))
1041 avio_wb32(pb, 1); /* must be 1 for uncompressed formats */
1043 avio_wb32(pb, track->par->frame_size); /* Samples per packet */
1044 avio_wb32(pb, track->sample_size / track->par->channels); /* Bytes per packet */
1045 avio_wb32(pb, track->sample_size); /* Bytes per frame */
1046 avio_wb32(pb, 2); /* Bytes per sample */
1049 if (track->mode == MODE_MOV &&
1050 (track->par->codec_id == AV_CODEC_ID_AAC ||
1051 track->par->codec_id == AV_CODEC_ID_AC3 ||
1052 track->par->codec_id == AV_CODEC_ID_EAC3 ||
1053 track->par->codec_id == AV_CODEC_ID_AMR_NB ||
1054 track->par->codec_id == AV_CODEC_ID_ALAC ||
1055 track->par->codec_id == AV_CODEC_ID_ADPCM_MS ||
1056 track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
1057 track->par->codec_id == AV_CODEC_ID_QDM2 ||
1058 (mov_pcm_le_gt16(track->par->codec_id) && version==1) ||
1059 (mov_pcm_be_gt16(track->par->codec_id) && version==1)))
1060 mov_write_wave_tag(s, pb, track);
1061 else if (track->tag == MKTAG('m','p','4','a'))
1062 mov_write_esds_tag(pb, track);
1063 else if (track->par->codec_id == AV_CODEC_ID_AMR_NB)
1064 mov_write_amr_tag(pb, track);
1065 else if (track->par->codec_id == AV_CODEC_ID_AC3)
1066 mov_write_ac3_tag(pb, track);
1067 else if (track->par->codec_id == AV_CODEC_ID_EAC3)
1068 mov_write_eac3_tag(pb, track);
1069 else if (track->par->codec_id == AV_CODEC_ID_ALAC)
1070 mov_write_extradata_tag(pb, track);
1071 else if (track->par->codec_id == AV_CODEC_ID_WMAPRO)
1072 mov_write_wfex_tag(s, pb, track);
1073 else if (track->par->codec_id == AV_CODEC_ID_FLAC)
1074 mov_write_dfla_tag(pb, track);
1075 else if (track->par->codec_id == AV_CODEC_ID_OPUS)
1076 mov_write_dops_tag(pb, track);
1077 else if (track->vos_len > 0)
1078 mov_write_glbl_tag(pb, track);
1080 if (track->mode == MODE_MOV && track->par->codec_type == AVMEDIA_TYPE_AUDIO)
1081 mov_write_chan_tag(s, pb, track);
1083 if (mov->encryption_scheme != MOV_ENC_NONE) {
1084 ff_mov_cenc_write_sinf_tag(track, pb, mov->encryption_kid);
1087 return update_size(pb, pos);
1090 static int mov_write_d263_tag(AVIOContext *pb)
1092 avio_wb32(pb, 0xf); /* size */
1093 ffio_wfourcc(pb, "d263");
1094 ffio_wfourcc(pb, "FFMP");
1095 avio_w8(pb, 0); /* decoder version */
1096 /* FIXME use AVCodecContext level/profile, when encoder will set values */
1097 avio_w8(pb, 0xa); /* level */
1098 avio_w8(pb, 0); /* profile */
1102 static int mov_write_avcc_tag(AVIOContext *pb, MOVTrack *track)
1104 int64_t pos = avio_tell(pb);
1107 ffio_wfourcc(pb, "avcC");
1108 ff_isom_write_avcc(pb, track->vos_data, track->vos_len);
1109 return update_size(pb, pos);
1112 static int mov_write_vpcc_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
1114 int64_t pos = avio_tell(pb);
1117 ffio_wfourcc(pb, "vpcC");
1118 avio_w8(pb, 1); /* version */
1119 avio_wb24(pb, 0); /* flags */
1120 ff_isom_write_vpcc(s, pb, track->par);
1121 return update_size(pb, pos);
1124 static int mov_write_hvcc_tag(AVIOContext *pb, MOVTrack *track)
1126 int64_t pos = avio_tell(pb);
1129 ffio_wfourcc(pb, "hvcC");
1130 if (track->tag == MKTAG('h','v','c','1'))
1131 ff_isom_write_hvcc(pb, track->vos_data, track->vos_len, 1);
1133 ff_isom_write_hvcc(pb, track->vos_data, track->vos_len, 0);
1134 return update_size(pb, pos);
1137 /* also used by all avid codecs (dv, imx, meridien) and their variants */
1138 static int mov_write_avid_tag(AVIOContext *pb, MOVTrack *track)
1143 int display_width = track->par->width;
1145 if (track->vos_data && track->vos_len > 0x29) {
1146 if (ff_dnxhd_parse_header_prefix(track->vos_data) != 0) {
1147 /* looks like a DNxHD bit stream */
1148 interlaced = (track->vos_data[5] & 2);
1149 cid = AV_RB32(track->vos_data + 0x28);
1151 av_log(NULL, AV_LOG_WARNING, "Could not locate DNxHD bit stream in vos_data\n");
1155 av_log(NULL, AV_LOG_WARNING, "Could not locate DNxHD bit stream, vos_data too small\n");
1159 avio_wb32(pb, 24); /* size */
1160 ffio_wfourcc(pb, "ACLR");
1161 ffio_wfourcc(pb, "ACLR");
1162 ffio_wfourcc(pb, "0001");
1163 if (track->par->color_range == AVCOL_RANGE_MPEG || /* Legal range (16-235) */
1164 track->par->color_range == AVCOL_RANGE_UNSPECIFIED) {
1165 avio_wb32(pb, 1); /* Corresponds to 709 in official encoder */
1166 } else { /* Full range (0-255) */
1167 avio_wb32(pb, 2); /* Corresponds to RGB in official encoder */
1169 avio_wb32(pb, 0); /* unknown */
1171 if (track->tag == MKTAG('A','V','d','h')) {
1173 ffio_wfourcc(pb, "ADHR");
1174 ffio_wfourcc(pb, "0001");
1176 avio_wb32(pb, 0); /* unknown */
1177 avio_wb32(pb, 1); /* unknown */
1178 avio_wb32(pb, 0); /* unknown */
1179 avio_wb32(pb, 0); /* unknown */
1183 avio_wb32(pb, 24); /* size */
1184 ffio_wfourcc(pb, "APRG");
1185 ffio_wfourcc(pb, "APRG");
1186 ffio_wfourcc(pb, "0001");
1187 avio_wb32(pb, 1); /* unknown */
1188 avio_wb32(pb, 0); /* unknown */
1190 avio_wb32(pb, 120); /* size */
1191 ffio_wfourcc(pb, "ARES");
1192 ffio_wfourcc(pb, "ARES");
1193 ffio_wfourcc(pb, "0001");
1194 avio_wb32(pb, cid); /* dnxhd cid, some id ? */
1195 if ( track->par->sample_aspect_ratio.num > 0
1196 && track->par->sample_aspect_ratio.den > 0)
1197 display_width = display_width * track->par->sample_aspect_ratio.num / track->par->sample_aspect_ratio.den;
1198 avio_wb32(pb, display_width);
1199 /* values below are based on samples created with quicktime and avid codecs */
1201 avio_wb32(pb, track->par->height / 2);
1202 avio_wb32(pb, 2); /* unknown */
1203 avio_wb32(pb, 0); /* unknown */
1204 avio_wb32(pb, 4); /* unknown */
1206 avio_wb32(pb, track->par->height);
1207 avio_wb32(pb, 1); /* unknown */
1208 avio_wb32(pb, 0); /* unknown */
1209 if (track->par->height == 1080)
1210 avio_wb32(pb, 5); /* unknown */
1212 avio_wb32(pb, 6); /* unknown */
1215 for (i = 0; i < 10; i++)
1221 static int mov_write_dpxe_tag(AVIOContext *pb, MOVTrack *track)
1224 ffio_wfourcc(pb, "DpxE");
1225 if (track->par->extradata_size >= 12 &&
1226 !memcmp(&track->par->extradata[4], "DpxE", 4)) {
1227 avio_wb32(pb, track->par->extradata[11]);
1234 static int mov_get_dv_codec_tag(AVFormatContext *s, MOVTrack *track)
1238 if (track->par->width == 720) { /* SD */
1239 if (track->par->height == 480) { /* NTSC */
1240 if (track->par->format == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','n');
1241 else tag = MKTAG('d','v','c',' ');
1242 }else if (track->par->format == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','p');
1243 else if (track->par->format == AV_PIX_FMT_YUV420P) tag = MKTAG('d','v','c','p');
1244 else tag = MKTAG('d','v','p','p');
1245 } else if (track->par->height == 720) { /* HD 720 line */
1246 if (track->st->time_base.den == 50) tag = MKTAG('d','v','h','q');
1247 else tag = MKTAG('d','v','h','p');
1248 } else if (track->par->height == 1080) { /* HD 1080 line */
1249 if (track->st->time_base.den == 25) tag = MKTAG('d','v','h','5');
1250 else tag = MKTAG('d','v','h','6');
1252 av_log(s, AV_LOG_ERROR, "unsupported height for dv codec\n");
1259 static AVRational find_fps(AVFormatContext *s, AVStream *st)
1261 AVRational rate = st->avg_frame_rate;
1263 #if FF_API_LAVF_AVCTX
1264 FF_DISABLE_DEPRECATION_WARNINGS
1265 rate = av_inv_q(st->codec->time_base);
1266 if (av_timecode_check_frame_rate(rate) < 0) {
1267 av_log(s, AV_LOG_DEBUG, "timecode: tbc=%d/%d invalid, fallback on %d/%d\n",
1268 rate.num, rate.den, st->avg_frame_rate.num, st->avg_frame_rate.den);
1269 rate = st->avg_frame_rate;
1271 FF_ENABLE_DEPRECATION_WARNINGS
1277 static int defined_frame_rate(AVFormatContext *s, AVStream *st)
1279 AVRational rational_framerate = find_fps(s, st);
1281 if (rational_framerate.den != 0)
1282 rate = av_q2d(rational_framerate);
1286 static int mov_get_mpeg2_xdcam_codec_tag(AVFormatContext *s, MOVTrack *track)
1288 int tag = track->par->codec_tag;
1289 int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE;
1290 AVStream *st = track->st;
1291 int rate = defined_frame_rate(s, st);
1294 tag = MKTAG('m', '2', 'v', '1'); //fallback tag
1296 if (track->par->format == AV_PIX_FMT_YUV420P) {
1297 if (track->par->width == 1280 && track->par->height == 720) {
1299 if (rate == 24) tag = MKTAG('x','d','v','4');
1300 else if (rate == 25) tag = MKTAG('x','d','v','5');
1301 else if (rate == 30) tag = MKTAG('x','d','v','1');
1302 else if (rate == 50) tag = MKTAG('x','d','v','a');
1303 else if (rate == 60) tag = MKTAG('x','d','v','9');
1305 } else if (track->par->width == 1440 && track->par->height == 1080) {
1307 if (rate == 24) tag = MKTAG('x','d','v','6');
1308 else if (rate == 25) tag = MKTAG('x','d','v','7');
1309 else if (rate == 30) tag = MKTAG('x','d','v','8');
1311 if (rate == 25) tag = MKTAG('x','d','v','3');
1312 else if (rate == 30) tag = MKTAG('x','d','v','2');
1314 } else if (track->par->width == 1920 && track->par->height == 1080) {
1316 if (rate == 24) tag = MKTAG('x','d','v','d');
1317 else if (rate == 25) tag = MKTAG('x','d','v','e');
1318 else if (rate == 30) tag = MKTAG('x','d','v','f');
1320 if (rate == 25) tag = MKTAG('x','d','v','c');
1321 else if (rate == 30) tag = MKTAG('x','d','v','b');
1324 } else if (track->par->format == AV_PIX_FMT_YUV422P) {
1325 if (track->par->width == 1280 && track->par->height == 720) {
1327 if (rate == 24) tag = MKTAG('x','d','5','4');
1328 else if (rate == 25) tag = MKTAG('x','d','5','5');
1329 else if (rate == 30) tag = MKTAG('x','d','5','1');
1330 else if (rate == 50) tag = MKTAG('x','d','5','a');
1331 else if (rate == 60) tag = MKTAG('x','d','5','9');
1333 } else if (track->par->width == 1920 && track->par->height == 1080) {
1335 if (rate == 24) tag = MKTAG('x','d','5','d');
1336 else if (rate == 25) tag = MKTAG('x','d','5','e');
1337 else if (rate == 30) tag = MKTAG('x','d','5','f');
1339 if (rate == 25) tag = MKTAG('x','d','5','c');
1340 else if (rate == 30) tag = MKTAG('x','d','5','b');
1348 static int mov_get_h264_codec_tag(AVFormatContext *s, MOVTrack *track)
1350 int tag = track->par->codec_tag;
1351 int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE;
1352 AVStream *st = track->st;
1353 int rate = defined_frame_rate(s, st);
1356 tag = MKTAG('a', 'v', 'c', 'i'); //fallback tag
1358 if (track->par->format == AV_PIX_FMT_YUV420P10) {
1359 if (track->par->width == 960 && track->par->height == 720) {
1361 if (rate == 24) tag = MKTAG('a','i','5','p');
1362 else if (rate == 25) tag = MKTAG('a','i','5','q');
1363 else if (rate == 30) tag = MKTAG('a','i','5','p');
1364 else if (rate == 50) tag = MKTAG('a','i','5','q');
1365 else if (rate == 60) tag = MKTAG('a','i','5','p');
1367 } else if (track->par->width == 1440 && track->par->height == 1080) {
1369 if (rate == 24) tag = MKTAG('a','i','5','3');
1370 else if (rate == 25) tag = MKTAG('a','i','5','2');
1371 else if (rate == 30) tag = MKTAG('a','i','5','3');
1373 if (rate == 50) tag = MKTAG('a','i','5','5');
1374 else if (rate == 60) tag = MKTAG('a','i','5','6');
1377 } else if (track->par->format == AV_PIX_FMT_YUV422P10) {
1378 if (track->par->width == 1280 && track->par->height == 720) {
1380 if (rate == 24) tag = MKTAG('a','i','1','p');
1381 else if (rate == 25) tag = MKTAG('a','i','1','q');
1382 else if (rate == 30) tag = MKTAG('a','i','1','p');
1383 else if (rate == 50) tag = MKTAG('a','i','1','q');
1384 else if (rate == 60) tag = MKTAG('a','i','1','p');
1386 } else if (track->par->width == 1920 && track->par->height == 1080) {
1388 if (rate == 24) tag = MKTAG('a','i','1','3');
1389 else if (rate == 25) tag = MKTAG('a','i','1','2');
1390 else if (rate == 30) tag = MKTAG('a','i','1','3');
1392 if (rate == 25) tag = MKTAG('a','i','1','5');
1393 else if (rate == 50) tag = MKTAG('a','i','1','5');
1394 else if (rate == 60) tag = MKTAG('a','i','1','6');
1396 } else if ( track->par->width == 4096 && track->par->height == 2160
1397 || track->par->width == 3840 && track->par->height == 2160
1398 || track->par->width == 2048 && track->par->height == 1080) {
1399 tag = MKTAG('a','i','v','x');
1406 static const struct {
1407 enum AVPixelFormat pix_fmt;
1410 } mov_pix_fmt_tags[] = {
1411 { AV_PIX_FMT_YUYV422, MKTAG('y','u','v','2'), 0 },
1412 { AV_PIX_FMT_YUYV422, MKTAG('y','u','v','s'), 0 },
1413 { AV_PIX_FMT_UYVY422, MKTAG('2','v','u','y'), 0 },
1414 { AV_PIX_FMT_RGB555BE,MKTAG('r','a','w',' '), 16 },
1415 { AV_PIX_FMT_RGB555LE,MKTAG('L','5','5','5'), 16 },
1416 { AV_PIX_FMT_RGB565LE,MKTAG('L','5','6','5'), 16 },
1417 { AV_PIX_FMT_RGB565BE,MKTAG('B','5','6','5'), 16 },
1418 { AV_PIX_FMT_GRAY16BE,MKTAG('b','1','6','g'), 16 },
1419 { AV_PIX_FMT_RGB24, MKTAG('r','a','w',' '), 24 },
1420 { AV_PIX_FMT_BGR24, MKTAG('2','4','B','G'), 24 },
1421 { AV_PIX_FMT_ARGB, MKTAG('r','a','w',' '), 32 },
1422 { AV_PIX_FMT_BGRA, MKTAG('B','G','R','A'), 32 },
1423 { AV_PIX_FMT_RGBA, MKTAG('R','G','B','A'), 32 },
1424 { AV_PIX_FMT_ABGR, MKTAG('A','B','G','R'), 32 },
1425 { AV_PIX_FMT_RGB48BE, MKTAG('b','4','8','r'), 48 },
1428 static int mov_get_dnxhd_codec_tag(AVFormatContext *s, MOVTrack *track)
1430 int tag = MKTAG('A','V','d','n');
1431 if (track->par->profile != FF_PROFILE_UNKNOWN &&
1432 track->par->profile != FF_PROFILE_DNXHD)
1433 tag = MKTAG('A','V','d','h');
1437 static int mov_get_rawvideo_codec_tag(AVFormatContext *s, MOVTrack *track)
1439 int tag = track->par->codec_tag;
1441 enum AVPixelFormat pix_fmt;
1443 for (i = 0; i < FF_ARRAY_ELEMS(mov_pix_fmt_tags); i++) {
1444 if (track->par->format == mov_pix_fmt_tags[i].pix_fmt) {
1445 tag = mov_pix_fmt_tags[i].tag;
1446 track->par->bits_per_coded_sample = mov_pix_fmt_tags[i].bps;
1447 if (track->par->codec_tag == mov_pix_fmt_tags[i].tag)
1452 pix_fmt = avpriv_find_pix_fmt(avpriv_pix_fmt_bps_mov,
1453 track->par->bits_per_coded_sample);
1454 if (tag == MKTAG('r','a','w',' ') &&
1455 track->par->format != pix_fmt &&
1456 track->par->format != AV_PIX_FMT_GRAY8 &&
1457 track->par->format != AV_PIX_FMT_NONE)
1458 av_log(s, AV_LOG_ERROR, "%s rawvideo cannot be written to mov, output file will be unreadable\n",
1459 av_get_pix_fmt_name(track->par->format));
1463 static int mov_get_codec_tag(AVFormatContext *s, MOVTrack *track)
1465 int tag = track->par->codec_tag;
1467 if (!tag || (s->strict_std_compliance >= FF_COMPLIANCE_NORMAL &&
1468 (track->par->codec_id == AV_CODEC_ID_DVVIDEO ||
1469 track->par->codec_id == AV_CODEC_ID_RAWVIDEO ||
1470 track->par->codec_id == AV_CODEC_ID_H263 ||
1471 track->par->codec_id == AV_CODEC_ID_H264 ||
1472 track->par->codec_id == AV_CODEC_ID_DNXHD ||
1473 track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO ||
1474 av_get_bits_per_sample(track->par->codec_id)))) { // pcm audio
1475 if (track->par->codec_id == AV_CODEC_ID_DVVIDEO)
1476 tag = mov_get_dv_codec_tag(s, track);
1477 else if (track->par->codec_id == AV_CODEC_ID_RAWVIDEO)
1478 tag = mov_get_rawvideo_codec_tag(s, track);
1479 else if (track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO)
1480 tag = mov_get_mpeg2_xdcam_codec_tag(s, track);
1481 else if (track->par->codec_id == AV_CODEC_ID_H264)
1482 tag = mov_get_h264_codec_tag(s, track);
1483 else if (track->par->codec_id == AV_CODEC_ID_DNXHD)
1484 tag = mov_get_dnxhd_codec_tag(s, track);
1485 else if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
1486 tag = ff_codec_get_tag(ff_codec_movvideo_tags, track->par->codec_id);
1487 if (!tag) { // if no mac fcc found, try with Microsoft tags
1488 tag = ff_codec_get_tag(ff_codec_bmp_tags, track->par->codec_id);
1490 av_log(s, AV_LOG_WARNING, "Using MS style video codec tag, "
1491 "the file may be unplayable!\n");
1493 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
1494 tag = ff_codec_get_tag(ff_codec_movaudio_tags, track->par->codec_id);
1495 if (!tag) { // if no mac fcc found, try with Microsoft tags
1496 int ms_tag = ff_codec_get_tag(ff_codec_wav_tags, track->par->codec_id);
1498 tag = MKTAG('m', 's', ((ms_tag >> 8) & 0xff), (ms_tag & 0xff));
1499 av_log(s, AV_LOG_WARNING, "Using MS style audio codec tag, "
1500 "the file may be unplayable!\n");
1503 } else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)
1504 tag = ff_codec_get_tag(ff_codec_movsubtitle_tags, track->par->codec_id);
1510 static int mov_find_codec_tag(AVFormatContext *s, MOVTrack *track)
1514 if (track->mode == MODE_MP4 || track->mode == MODE_PSP)
1515 tag = track->par->codec_tag;
1516 else if (track->mode == MODE_ISM)
1517 tag = track->par->codec_tag;
1518 else if (track->mode == MODE_IPOD) {
1519 if (!av_match_ext(s->filename, "m4a") &&
1520 !av_match_ext(s->filename, "m4v") &&
1521 !av_match_ext(s->filename, "m4b"))
1522 av_log(s, AV_LOG_WARNING, "Warning, extension is not .m4a nor .m4v "
1523 "Quicktime/Ipod might not play the file\n");
1524 tag = track->par->codec_tag;
1525 } else if (track->mode & MODE_3GP)
1526 tag = track->par->codec_tag;
1527 else if (track->mode == MODE_F4V)
1528 tag = track->par->codec_tag;
1530 tag = mov_get_codec_tag(s, track);
1535 /** Write uuid atom.
1536 * Needed to make file play in iPods running newest firmware
1537 * goes after avcC atom in moov.trak.mdia.minf.stbl.stsd.avc1
1539 static int mov_write_uuid_tag_ipod(AVIOContext *pb)
1542 ffio_wfourcc(pb, "uuid");
1543 avio_wb32(pb, 0x6b6840f2);
1544 avio_wb32(pb, 0x5f244fc5);
1545 avio_wb32(pb, 0xba39a51b);
1546 avio_wb32(pb, 0xcf0323f3);
1551 static const uint16_t fiel_data[] = {
1552 0x0000, 0x0100, 0x0201, 0x0206, 0x0209, 0x020e
1555 static int mov_write_fiel_tag(AVIOContext *pb, MOVTrack *track, int field_order)
1557 unsigned mov_field_order = 0;
1558 if (field_order < FF_ARRAY_ELEMS(fiel_data))
1559 mov_field_order = fiel_data[field_order];
1563 ffio_wfourcc(pb, "fiel");
1564 avio_wb16(pb, mov_field_order);
1568 static int mov_write_subtitle_tag(AVIOContext *pb, MOVTrack *track)
1570 int64_t pos = avio_tell(pb);
1571 avio_wb32(pb, 0); /* size */
1572 avio_wl32(pb, track->tag); // store it byteswapped
1573 avio_wb32(pb, 0); /* Reserved */
1574 avio_wb16(pb, 0); /* Reserved */
1575 avio_wb16(pb, 1); /* Data-reference index */
1577 if (track->par->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
1578 mov_write_esds_tag(pb, track);
1579 else if (track->par->extradata_size)
1580 avio_write(pb, track->par->extradata, track->par->extradata_size);
1582 return update_size(pb, pos);
1585 static int mov_write_st3d_tag(AVIOContext *pb, AVStereo3D *stereo_3d)
1589 if (stereo_3d->flags != 0) {
1590 av_log(pb, AV_LOG_WARNING, "Unsupported stereo_3d flags %x. st3d not written.\n", stereo_3d->flags);
1594 switch (stereo_3d->type) {
1595 case AV_STEREO3D_2D:
1598 case AV_STEREO3D_TOPBOTTOM:
1601 case AV_STEREO3D_SIDEBYSIDE:
1605 av_log(pb, AV_LOG_WARNING, "Unsupported stereo_3d type %s. st3d not written.\n", av_stereo3d_type_name(stereo_3d->type));
1608 avio_wb32(pb, 13); /* size */
1609 ffio_wfourcc(pb, "st3d");
1610 avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1611 avio_w8(pb, stereo_mode);
1615 static int mov_write_sv3d_tag(AVFormatContext *s, AVIOContext *pb, AVSphericalMapping *spherical_mapping)
1617 int64_t sv3d_pos, svhd_pos, proj_pos;
1618 const char* metadata_source = s->flags & AVFMT_FLAG_BITEXACT ? "Lavf" : LIBAVFORMAT_IDENT;
1620 if (spherical_mapping->projection != AV_SPHERICAL_EQUIRECTANGULAR &&
1621 spherical_mapping->projection != AV_SPHERICAL_EQUIRECTANGULAR_TILE &&
1622 spherical_mapping->projection != AV_SPHERICAL_CUBEMAP) {
1623 av_log(pb, AV_LOG_WARNING, "Unsupported projection %d. sv3d not written.\n", spherical_mapping->projection);
1627 sv3d_pos = avio_tell(pb);
1628 avio_wb32(pb, 0); /* size */
1629 ffio_wfourcc(pb, "sv3d");
1631 svhd_pos = avio_tell(pb);
1632 avio_wb32(pb, 0); /* size */
1633 ffio_wfourcc(pb, "svhd");
1634 avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1635 avio_put_str(pb, metadata_source);
1636 update_size(pb, svhd_pos);
1638 proj_pos = avio_tell(pb);
1639 avio_wb32(pb, 0); /* size */
1640 ffio_wfourcc(pb, "proj");
1642 avio_wb32(pb, 24); /* size */
1643 ffio_wfourcc(pb, "prhd");
1644 avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1645 avio_wb32(pb, spherical_mapping->yaw);
1646 avio_wb32(pb, spherical_mapping->pitch);
1647 avio_wb32(pb, spherical_mapping->roll);
1649 switch (spherical_mapping->projection) {
1650 case AV_SPHERICAL_EQUIRECTANGULAR:
1651 case AV_SPHERICAL_EQUIRECTANGULAR_TILE:
1652 avio_wb32(pb, 28); /* size */
1653 ffio_wfourcc(pb, "equi");
1654 avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1655 avio_wb32(pb, spherical_mapping->bound_top);
1656 avio_wb32(pb, spherical_mapping->bound_bottom);
1657 avio_wb32(pb, spherical_mapping->bound_left);
1658 avio_wb32(pb, spherical_mapping->bound_right);
1660 case AV_SPHERICAL_CUBEMAP:
1661 avio_wb32(pb, 20); /* size */
1662 ffio_wfourcc(pb, "cbmp");
1663 avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1664 avio_wb32(pb, 0); /* layout */
1665 avio_wb32(pb, spherical_mapping->padding); /* padding */
1668 update_size(pb, proj_pos);
1670 return update_size(pb, sv3d_pos);
1673 static int mov_write_pasp_tag(AVIOContext *pb, MOVTrack *track)
1676 av_reduce(&sar.num, &sar.den, track->par->sample_aspect_ratio.num,
1677 track->par->sample_aspect_ratio.den, INT_MAX);
1680 ffio_wfourcc(pb, "pasp");
1681 avio_wb32(pb, sar.num);
1682 avio_wb32(pb, sar.den);
1686 static int mov_write_gama_tag(AVIOContext *pb, MOVTrack *track, double gamma)
1691 gamma = avpriv_get_gamma_from_trc(track->par->color_trc);
1693 av_log(pb, AV_LOG_DEBUG, "gamma value %g\n", gamma);
1696 gama = (uint32_t)lrint((double)(1<<16) * gamma);
1697 av_log(pb, AV_LOG_DEBUG, "writing gama value %"PRId32"\n", gama);
1699 av_assert0(track->mode == MODE_MOV);
1701 ffio_wfourcc(pb, "gama");
1702 avio_wb32(pb, gama);
1706 av_log(pb, AV_LOG_WARNING, "gamma value unknown, unable to write gama atom\n");
1711 static int mov_write_colr_tag(AVIOContext *pb, MOVTrack *track)
1713 // Ref (MOV): https://developer.apple.com/library/mac/technotes/tn2162/_index.html#//apple_ref/doc/uid/DTS40013070-CH1-TNTAG9
1714 // Ref (MP4): ISO/IEC 14496-12:2012
1716 if (track->par->color_primaries == AVCOL_PRI_UNSPECIFIED &&
1717 track->par->color_trc == AVCOL_TRC_UNSPECIFIED &&
1718 track->par->color_space == AVCOL_SPC_UNSPECIFIED) {
1719 if ((track->par->width >= 1920 && track->par->height >= 1080)
1720 || (track->par->width == 1280 && track->par->height == 720)) {
1721 av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming bt709\n");
1722 track->par->color_primaries = AVCOL_PRI_BT709;
1723 } else if (track->par->width == 720 && track->height == 576) {
1724 av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming bt470bg\n");
1725 track->par->color_primaries = AVCOL_PRI_BT470BG;
1726 } else if (track->par->width == 720 &&
1727 (track->height == 486 || track->height == 480)) {
1728 av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming smpte170\n");
1729 track->par->color_primaries = AVCOL_PRI_SMPTE170M;
1731 av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, unable to assume anything\n");
1733 switch (track->par->color_primaries) {
1734 case AVCOL_PRI_BT709:
1735 track->par->color_trc = AVCOL_TRC_BT709;
1736 track->par->color_space = AVCOL_SPC_BT709;
1738 case AVCOL_PRI_SMPTE170M:
1739 case AVCOL_PRI_BT470BG:
1740 track->par->color_trc = AVCOL_TRC_BT709;
1741 track->par->color_space = AVCOL_SPC_SMPTE170M;
1746 /* We should only ever be called by MOV or MP4. */
1747 av_assert0(track->mode == MODE_MOV || track->mode == MODE_MP4);
1749 avio_wb32(pb, 18 + (track->mode == MODE_MP4));
1750 ffio_wfourcc(pb, "colr");
1751 if (track->mode == MODE_MP4)
1752 ffio_wfourcc(pb, "nclx");
1754 ffio_wfourcc(pb, "nclc");
1755 switch (track->par->color_primaries) {
1756 case AVCOL_PRI_BT709: avio_wb16(pb, 1); break;
1757 case AVCOL_PRI_SMPTE170M:
1758 case AVCOL_PRI_SMPTE240M: avio_wb16(pb, 6); break;
1759 case AVCOL_PRI_BT470BG: avio_wb16(pb, 5); break;
1760 default: avio_wb16(pb, 2);
1762 switch (track->par->color_trc) {
1763 case AVCOL_TRC_BT709: avio_wb16(pb, 1); break;
1764 case AVCOL_TRC_SMPTE170M: avio_wb16(pb, 1); break; // remapped
1765 case AVCOL_TRC_SMPTE240M: avio_wb16(pb, 7); break;
1766 default: avio_wb16(pb, 2);
1768 switch (track->par->color_space) {
1769 case AVCOL_SPC_BT709: avio_wb16(pb, 1); break;
1770 case AVCOL_SPC_BT470BG:
1771 case AVCOL_SPC_SMPTE170M: avio_wb16(pb, 6); break;
1772 case AVCOL_SPC_SMPTE240M: avio_wb16(pb, 7); break;
1773 default: avio_wb16(pb, 2);
1776 if (track->mode == MODE_MP4) {
1777 int full_range = track->par->color_range == AVCOL_RANGE_JPEG;
1778 avio_w8(pb, full_range << 7);
1785 static void find_compressor(char * compressor_name, int len, MOVTrack *track)
1787 AVDictionaryEntry *encoder;
1788 int xdcam_res = (track->par->width == 1280 && track->par->height == 720)
1789 || (track->par->width == 1440 && track->par->height == 1080)
1790 || (track->par->width == 1920 && track->par->height == 1080);
1792 if (track->mode == MODE_MOV &&
1793 (encoder = av_dict_get(track->st->metadata, "encoder", NULL, 0))) {
1794 av_strlcpy(compressor_name, encoder->value, 32);
1795 } else if (track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO && xdcam_res) {
1796 int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE;
1797 AVStream *st = track->st;
1798 int rate = defined_frame_rate(NULL, st);
1799 av_strlcatf(compressor_name, len, "XDCAM");
1800 if (track->par->format == AV_PIX_FMT_YUV422P) {
1801 av_strlcatf(compressor_name, len, " HD422");
1802 } else if(track->par->width == 1440) {
1803 av_strlcatf(compressor_name, len, " HD");
1805 av_strlcatf(compressor_name, len, " EX");
1807 av_strlcatf(compressor_name, len, " %d%c", track->par->height, interlaced ? 'i' : 'p');
1809 av_strlcatf(compressor_name, len, "%d", rate * (interlaced + 1));
1813 static int mov_write_video_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
1815 int64_t pos = avio_tell(pb);
1816 char compressor_name[32] = { 0 };
1819 avio_wb32(pb, 0); /* size */
1820 if (mov->encryption_scheme != MOV_ENC_NONE) {
1821 ffio_wfourcc(pb, "encv");
1823 avio_wl32(pb, track->tag); // store it byteswapped
1825 avio_wb32(pb, 0); /* Reserved */
1826 avio_wb16(pb, 0); /* Reserved */
1827 avio_wb16(pb, 1); /* Data-reference index */
1829 avio_wb16(pb, 0); /* Codec stream version */
1830 avio_wb16(pb, 0); /* Codec stream revision (=0) */
1831 if (track->mode == MODE_MOV) {
1832 ffio_wfourcc(pb, "FFMP"); /* Vendor */
1833 if (track->par->codec_id == AV_CODEC_ID_RAWVIDEO) {
1834 avio_wb32(pb, 0); /* Temporal Quality */
1835 avio_wb32(pb, 0x400); /* Spatial Quality = lossless*/
1837 avio_wb32(pb, 0x200); /* Temporal Quality = normal */
1838 avio_wb32(pb, 0x200); /* Spatial Quality = normal */
1841 avio_wb32(pb, 0); /* Reserved */
1842 avio_wb32(pb, 0); /* Reserved */
1843 avio_wb32(pb, 0); /* Reserved */
1845 avio_wb16(pb, track->par->width); /* Video width */
1846 avio_wb16(pb, track->height); /* Video height */
1847 avio_wb32(pb, 0x00480000); /* Horizontal resolution 72dpi */
1848 avio_wb32(pb, 0x00480000); /* Vertical resolution 72dpi */
1849 avio_wb32(pb, 0); /* Data size (= 0) */
1850 avio_wb16(pb, 1); /* Frame count (= 1) */
1852 /* FIXME not sure, ISO 14496-1 draft where it shall be set to 0 */
1853 find_compressor(compressor_name, 32, track);
1854 avio_w8(pb, strlen(compressor_name));
1855 avio_write(pb, compressor_name, 31);
1857 if (track->mode == MODE_MOV && track->par->bits_per_coded_sample)
1858 avio_wb16(pb, track->par->bits_per_coded_sample |
1859 (track->par->format == AV_PIX_FMT_GRAY8 ? 0x20 : 0));
1861 avio_wb16(pb, 0x18); /* Reserved */
1863 if (track->mode == MODE_MOV && track->par->format == AV_PIX_FMT_PAL8) {
1864 int pal_size = 1 << track->par->bits_per_coded_sample;
1866 avio_wb16(pb, 0); /* Color table ID */
1867 avio_wb32(pb, 0); /* Color table seed */
1868 avio_wb16(pb, 0x8000); /* Color table flags */
1869 avio_wb16(pb, pal_size - 1); /* Color table size (zero-relative) */
1870 for (i = 0; i < pal_size; i++) {
1871 uint32_t rgb = track->palette[i];
1872 uint16_t r = (rgb >> 16) & 0xff;
1873 uint16_t g = (rgb >> 8) & 0xff;
1874 uint16_t b = rgb & 0xff;
1876 avio_wb16(pb, (r << 8) | r);
1877 avio_wb16(pb, (g << 8) | g);
1878 avio_wb16(pb, (b << 8) | b);
1881 avio_wb16(pb, 0xffff); /* Reserved */
1883 if (track->tag == MKTAG('m','p','4','v'))
1884 mov_write_esds_tag(pb, track);
1885 else if (track->par->codec_id == AV_CODEC_ID_H263)
1886 mov_write_d263_tag(pb);
1887 else if (track->par->codec_id == AV_CODEC_ID_AVUI ||
1888 track->par->codec_id == AV_CODEC_ID_SVQ3) {
1889 mov_write_extradata_tag(pb, track);
1891 } else if (track->par->codec_id == AV_CODEC_ID_DNXHD) {
1892 mov_write_avid_tag(pb, track);
1894 } else if (track->par->codec_id == AV_CODEC_ID_HEVC)
1895 mov_write_hvcc_tag(pb, track);
1896 else if (track->par->codec_id == AV_CODEC_ID_H264 && !TAG_IS_AVCI(track->tag)) {
1897 mov_write_avcc_tag(pb, track);
1898 if (track->mode == MODE_IPOD)
1899 mov_write_uuid_tag_ipod(pb);
1900 } else if (track->par->codec_id == AV_CODEC_ID_VP9) {
1901 mov_write_vpcc_tag(mov->fc, pb, track);
1902 } else if (track->par->codec_id == AV_CODEC_ID_VC1 && track->vos_len > 0)
1903 mov_write_dvc1_tag(pb, track);
1904 else if (track->par->codec_id == AV_CODEC_ID_VP6F ||
1905 track->par->codec_id == AV_CODEC_ID_VP6A) {
1906 /* Don't write any potential extradata here - the cropping
1907 * is signalled via the normal width/height fields. */
1908 } else if (track->par->codec_id == AV_CODEC_ID_R10K) {
1909 if (track->par->codec_tag == MKTAG('R','1','0','k'))
1910 mov_write_dpxe_tag(pb, track);
1911 } else if (track->vos_len > 0)
1912 mov_write_glbl_tag(pb, track);
1914 if (track->par->codec_id != AV_CODEC_ID_H264 &&
1915 track->par->codec_id != AV_CODEC_ID_MPEG4 &&
1916 track->par->codec_id != AV_CODEC_ID_DNXHD) {
1917 int field_order = track->par->field_order;
1919 #if FF_API_LAVF_AVCTX
1920 FF_DISABLE_DEPRECATION_WARNINGS
1921 if (field_order != track->st->codec->field_order && track->st->codec->field_order != AV_FIELD_UNKNOWN)
1922 field_order = track->st->codec->field_order;
1923 FF_ENABLE_DEPRECATION_WARNINGS
1926 if (field_order != AV_FIELD_UNKNOWN)
1927 mov_write_fiel_tag(pb, track, field_order);
1930 if (mov->flags & FF_MOV_FLAG_WRITE_GAMA) {
1931 if (track->mode == MODE_MOV)
1932 mov_write_gama_tag(pb, track, mov->gamma);
1934 av_log(mov->fc, AV_LOG_WARNING, "Not writing 'gama' atom. Format is not MOV.\n");
1936 if (mov->flags & FF_MOV_FLAG_WRITE_COLR) {
1937 if (track->mode == MODE_MOV || track->mode == MODE_MP4)
1938 mov_write_colr_tag(pb, track);
1940 av_log(mov->fc, AV_LOG_WARNING, "Not writing 'colr' atom. Format is not MOV or MP4.\n");
1943 if (track->mode == MODE_MP4 && mov->fc->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL) {
1944 AVStereo3D* stereo_3d = (AVStereo3D*) av_stream_get_side_data(track->st, AV_PKT_DATA_STEREO3D, NULL);
1945 AVSphericalMapping* spherical_mapping = (AVSphericalMapping*)av_stream_get_side_data(track->st, AV_PKT_DATA_SPHERICAL, NULL);
1948 mov_write_st3d_tag(pb, stereo_3d);
1949 if (spherical_mapping)
1950 mov_write_sv3d_tag(mov->fc, pb, spherical_mapping);
1953 if (track->par->sample_aspect_ratio.den && track->par->sample_aspect_ratio.num) {
1954 mov_write_pasp_tag(pb, track);
1957 if (mov->encryption_scheme != MOV_ENC_NONE) {
1958 ff_mov_cenc_write_sinf_tag(track, pb, mov->encryption_kid);
1961 /* extra padding for avid stsd */
1962 /* https://developer.apple.com/library/mac/documentation/QuickTime/QTFF/QTFFChap2/qtff2.html#//apple_ref/doc/uid/TP40000939-CH204-61112 */
1966 return update_size(pb, pos);
1969 static int mov_write_rtp_tag(AVIOContext *pb, MOVTrack *track)
1971 int64_t pos = avio_tell(pb);
1972 avio_wb32(pb, 0); /* size */
1973 ffio_wfourcc(pb, "rtp ");
1974 avio_wb32(pb, 0); /* Reserved */
1975 avio_wb16(pb, 0); /* Reserved */
1976 avio_wb16(pb, 1); /* Data-reference index */
1978 avio_wb16(pb, 1); /* Hint track version */
1979 avio_wb16(pb, 1); /* Highest compatible version */
1980 avio_wb32(pb, track->max_packet_size); /* Max packet size */
1982 avio_wb32(pb, 12); /* size */
1983 ffio_wfourcc(pb, "tims");
1984 avio_wb32(pb, track->timescale);
1986 return update_size(pb, pos);
1989 static int mov_write_source_reference_tag(AVIOContext *pb, MOVTrack *track, const char *reel_name)
1991 uint64_t str_size =strlen(reel_name);
1992 int64_t pos = avio_tell(pb);
1994 if (str_size >= UINT16_MAX){
1995 av_log(NULL, AV_LOG_ERROR, "reel_name length %"PRIu64" is too large\n", str_size);
1997 return AVERROR(EINVAL);
2000 avio_wb32(pb, 0); /* size */
2001 ffio_wfourcc(pb, "name"); /* Data format */
2002 avio_wb16(pb, str_size); /* string size */
2003 avio_wb16(pb, track->language); /* langcode */
2004 avio_write(pb, reel_name, str_size); /* reel name */
2005 return update_size(pb,pos);
2008 static int mov_write_tmcd_tag(AVIOContext *pb, MOVTrack *track)
2010 int64_t pos = avio_tell(pb);
2014 AVDictionaryEntry *t = NULL;
2016 if (!track->st->avg_frame_rate.num || !track->st->avg_frame_rate.den) {
2017 #if FF_API_LAVF_AVCTX
2018 FF_DISABLE_DEPRECATION_WARNINGS
2019 frame_duration = av_rescale(track->timescale, track->st->codec->time_base.num, track->st->codec->time_base.den);
2020 nb_frames = ROUNDED_DIV(track->st->codec->time_base.den, track->st->codec->time_base.num);
2021 FF_ENABLE_DEPRECATION_WARNINGS
2023 av_log(NULL, AV_LOG_ERROR, "avg_frame_rate not set for tmcd track.\n");
2024 return AVERROR(EINVAL);
2027 frame_duration = av_rescale(track->timescale, track->st->avg_frame_rate.num, track->st->avg_frame_rate.den);
2028 nb_frames = ROUNDED_DIV(track->st->avg_frame_rate.den, track->st->avg_frame_rate.num);
2031 if (nb_frames > 255) {
2032 av_log(NULL, AV_LOG_ERROR, "fps %d is too large\n", nb_frames);
2033 return AVERROR(EINVAL);
2036 avio_wb32(pb, 0); /* size */
2037 ffio_wfourcc(pb, "tmcd"); /* Data format */
2038 avio_wb32(pb, 0); /* Reserved */
2039 avio_wb32(pb, 1); /* Data reference index */
2040 avio_wb32(pb, 0); /* Flags */
2041 avio_wb32(pb, track->timecode_flags); /* Flags (timecode) */
2042 avio_wb32(pb, track->timescale); /* Timescale */
2043 avio_wb32(pb, frame_duration); /* Frame duration */
2044 avio_w8(pb, nb_frames); /* Number of frames */
2045 avio_w8(pb, 0); /* Reserved */
2047 t = av_dict_get(track->st->metadata, "reel_name", NULL, 0);
2048 if (t && utf8len(t->value) && track->mode != MODE_MP4)
2049 mov_write_source_reference_tag(pb, track, t->value);
2051 avio_wb16(pb, 0); /* zero size */
2054 avio_wb32(pb, 0); /* size */
2055 ffio_wfourcc(pb, "tmcd"); /* Data format */
2056 avio_wb32(pb, 0); /* Reserved */
2057 avio_wb32(pb, 1); /* Data reference index */
2058 if (track->par->extradata_size)
2059 avio_write(pb, track->par->extradata, track->par->extradata_size);
2061 return update_size(pb, pos);
2064 static int mov_write_gpmd_tag(AVIOContext *pb, const MOVTrack *track)
2066 int64_t pos = avio_tell(pb);
2067 avio_wb32(pb, 0); /* size */
2068 ffio_wfourcc(pb, "gpmd");
2069 avio_wb32(pb, 0); /* Reserved */
2070 avio_wb16(pb, 0); /* Reserved */
2071 avio_wb16(pb, 1); /* Data-reference index */
2072 avio_wb32(pb, 0); /* Reserved */
2073 return update_size(pb, pos);
2076 static int mov_write_stsd_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
2078 int64_t pos = avio_tell(pb);
2079 avio_wb32(pb, 0); /* size */
2080 ffio_wfourcc(pb, "stsd");
2081 avio_wb32(pb, 0); /* version & flags */
2082 avio_wb32(pb, 1); /* entry count */
2083 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO)
2084 mov_write_video_tag(pb, mov, track);
2085 else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
2086 mov_write_audio_tag(s, pb, mov, track);
2087 else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)
2088 mov_write_subtitle_tag(pb, track);
2089 else if (track->par->codec_tag == MKTAG('r','t','p',' '))
2090 mov_write_rtp_tag(pb, track);
2091 else if (track->par->codec_tag == MKTAG('t','m','c','d'))
2092 mov_write_tmcd_tag(pb, track);
2093 else if (track->par->codec_tag == MKTAG('g','p','m','d'))
2094 mov_write_gpmd_tag(pb, track);
2095 return update_size(pb, pos);
2098 static int mov_write_ctts_tag(AVIOContext *pb, MOVTrack *track)
2100 MOVStts *ctts_entries;
2101 uint32_t entries = 0;
2105 ctts_entries = av_malloc_array((track->entry + 1), sizeof(*ctts_entries)); /* worst case */
2107 return AVERROR(ENOMEM);
2108 ctts_entries[0].count = 1;
2109 ctts_entries[0].duration = track->cluster[0].cts;
2110 for (i = 1; i < track->entry; i++) {
2111 if (track->cluster[i].cts == ctts_entries[entries].duration) {
2112 ctts_entries[entries].count++; /* compress */
2115 ctts_entries[entries].duration = track->cluster[i].cts;
2116 ctts_entries[entries].count = 1;
2119 entries++; /* last one */
2120 atom_size = 16 + (entries * 8);
2121 avio_wb32(pb, atom_size); /* size */
2122 ffio_wfourcc(pb, "ctts");
2123 avio_wb32(pb, 0); /* version & flags */
2124 avio_wb32(pb, entries); /* entry count */
2125 for (i = 0; i < entries; i++) {
2126 avio_wb32(pb, ctts_entries[i].count);
2127 avio_wb32(pb, ctts_entries[i].duration);
2129 av_free(ctts_entries);
2133 /* Time to sample atom */
2134 static int mov_write_stts_tag(AVIOContext *pb, MOVTrack *track)
2136 MOVStts *stts_entries = NULL;
2137 uint32_t entries = -1;
2141 if (track->par->codec_type == AVMEDIA_TYPE_AUDIO && !track->audio_vbr) {
2142 stts_entries = av_malloc(sizeof(*stts_entries)); /* one entry */
2144 return AVERROR(ENOMEM);
2145 stts_entries[0].count = track->sample_count;
2146 stts_entries[0].duration = 1;
2150 stts_entries = av_malloc_array(track->entry, sizeof(*stts_entries)); /* worst case */
2152 return AVERROR(ENOMEM);
2154 for (i = 0; i < track->entry; i++) {
2155 int duration = get_cluster_duration(track, i);
2156 if (i && duration == stts_entries[entries].duration) {
2157 stts_entries[entries].count++; /* compress */
2160 stts_entries[entries].duration = duration;
2161 stts_entries[entries].count = 1;
2164 entries++; /* last one */
2166 atom_size = 16 + (entries * 8);
2167 avio_wb32(pb, atom_size); /* size */
2168 ffio_wfourcc(pb, "stts");
2169 avio_wb32(pb, 0); /* version & flags */
2170 avio_wb32(pb, entries); /* entry count */
2171 for (i = 0; i < entries; i++) {
2172 avio_wb32(pb, stts_entries[i].count);
2173 avio_wb32(pb, stts_entries[i].duration);
2175 av_free(stts_entries);
2179 static int mov_write_dref_tag(AVIOContext *pb)
2181 avio_wb32(pb, 28); /* size */
2182 ffio_wfourcc(pb, "dref");
2183 avio_wb32(pb, 0); /* version & flags */
2184 avio_wb32(pb, 1); /* entry count */
2186 avio_wb32(pb, 0xc); /* size */
2187 //FIXME add the alis and rsrc atom
2188 ffio_wfourcc(pb, "url ");
2189 avio_wb32(pb, 1); /* version & flags */
2194 static int mov_preroll_write_stbl_atoms(AVIOContext *pb, MOVTrack *track)
2198 int16_t roll_distance;
2199 int group_description_index;
2202 struct sgpd_entry *sgpd_entries = NULL;
2207 const int OPUS_SEEK_PREROLL_MS = 80;
2208 int roll_samples = av_rescale_q(OPUS_SEEK_PREROLL_MS,
2209 (AVRational){1, 1000},
2210 (AVRational){1, 48000});
2215 sgpd_entries = av_malloc_array(track->entry, sizeof(*sgpd_entries));
2217 return AVERROR(ENOMEM);
2219 av_assert0(track->par->codec_id == AV_CODEC_ID_OPUS || track->par->codec_id == AV_CODEC_ID_AAC);
2221 if (track->par->codec_id == AV_CODEC_ID_OPUS) {
2222 for (i = 0; i < track->entry; i++) {
2223 int roll_samples_remaining = roll_samples;
2225 for (j = i - 1; j >= 0; j--) {
2226 roll_samples_remaining -= get_cluster_duration(track, j);
2228 if (roll_samples_remaining <= 0)
2231 /* We don't have enough preceeding samples to compute a valid
2232 roll_distance here, so this sample can't be independently
2234 if (roll_samples_remaining > 0)
2236 /* Verify distance is a minimum of 2 (60ms) packets and a maximum of
2237 32 (2.5ms) packets. */
2238 av_assert0(distance == 0 || (distance >= 2 && distance <= 32));
2239 if (i && distance == sgpd_entries[entries].roll_distance) {
2240 sgpd_entries[entries].count++;
2243 sgpd_entries[entries].count = 1;
2244 sgpd_entries[entries].roll_distance = distance;
2245 sgpd_entries[entries].group_description_index = distance ? ++group : 0;
2250 sgpd_entries[entries].count = track->sample_count;
2251 sgpd_entries[entries].roll_distance = 1;
2252 sgpd_entries[entries].group_description_index = ++group;
2257 av_free(sgpd_entries);
2261 /* Write sgpd tag */
2262 avio_wb32(pb, 24 + (group * 2)); /* size */
2263 ffio_wfourcc(pb, "sgpd");
2264 avio_wb32(pb, 1 << 24); /* fullbox */
2265 ffio_wfourcc(pb, "roll");
2266 avio_wb32(pb, 2); /* default_length */
2267 avio_wb32(pb, group); /* entry_count */
2268 for (i = 0; i < entries; i++) {
2269 if (sgpd_entries[i].group_description_index) {
2270 avio_wb16(pb, -sgpd_entries[i].roll_distance); /* roll_distance */
2274 /* Write sbgp tag */
2275 avio_wb32(pb, 20 + (entries * 8)); /* size */
2276 ffio_wfourcc(pb, "sbgp");
2277 avio_wb32(pb, 0); /* fullbox */
2278 ffio_wfourcc(pb, "roll");
2279 avio_wb32(pb, entries); /* entry_count */
2280 for (i = 0; i < entries; i++) {
2281 avio_wb32(pb, sgpd_entries[i].count); /* sample_count */
2282 avio_wb32(pb, sgpd_entries[i].group_description_index); /* group_description_index */
2285 av_free(sgpd_entries);
2289 static int mov_write_stbl_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
2291 int64_t pos = avio_tell(pb);
2294 avio_wb32(pb, 0); /* size */
2295 ffio_wfourcc(pb, "stbl");
2296 mov_write_stsd_tag(s, pb, mov, track);
2297 mov_write_stts_tag(pb, track);
2298 if ((track->par->codec_type == AVMEDIA_TYPE_VIDEO ||
2299 track->par->codec_tag == MKTAG('r','t','p',' ')) &&
2300 track->has_keyframes && track->has_keyframes < track->entry)
2301 mov_write_stss_tag(pb, track, MOV_SYNC_SAMPLE);
2302 if (track->mode == MODE_MOV && track->flags & MOV_TRACK_STPS)
2303 mov_write_stss_tag(pb, track, MOV_PARTIAL_SYNC_SAMPLE);
2304 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO &&
2305 track->flags & MOV_TRACK_CTTS && track->entry) {
2307 if ((ret = mov_write_ctts_tag(pb, track)) < 0)
2310 mov_write_stsc_tag(pb, track);
2311 mov_write_stsz_tag(pb, track);
2312 mov_write_stco_tag(pb, track);
2313 if (track->cenc.aes_ctr) {
2314 ff_mov_cenc_write_stbl_atoms(&track->cenc, pb);
2316 if (track->par->codec_id == AV_CODEC_ID_OPUS || track->par->codec_id == AV_CODEC_ID_AAC) {
2317 mov_preroll_write_stbl_atoms(pb, track);
2319 return update_size(pb, pos);
2322 static int mov_write_dinf_tag(AVIOContext *pb)
2324 int64_t pos = avio_tell(pb);
2325 avio_wb32(pb, 0); /* size */
2326 ffio_wfourcc(pb, "dinf");
2327 mov_write_dref_tag(pb);
2328 return update_size(pb, pos);
2331 static int mov_write_nmhd_tag(AVIOContext *pb)
2334 ffio_wfourcc(pb, "nmhd");
2339 static int mov_write_tcmi_tag(AVIOContext *pb, MOVTrack *track)
2341 int64_t pos = avio_tell(pb);
2342 const char *font = "Lucida Grande";
2343 avio_wb32(pb, 0); /* size */
2344 ffio_wfourcc(pb, "tcmi"); /* timecode media information atom */
2345 avio_wb32(pb, 0); /* version & flags */
2346 avio_wb16(pb, 0); /* text font */
2347 avio_wb16(pb, 0); /* text face */
2348 avio_wb16(pb, 12); /* text size */
2349 avio_wb16(pb, 0); /* (unknown, not in the QT specs...) */
2350 avio_wb16(pb, 0x0000); /* text color (red) */
2351 avio_wb16(pb, 0x0000); /* text color (green) */
2352 avio_wb16(pb, 0x0000); /* text color (blue) */
2353 avio_wb16(pb, 0xffff); /* background color (red) */
2354 avio_wb16(pb, 0xffff); /* background color (green) */
2355 avio_wb16(pb, 0xffff); /* background color (blue) */
2356 avio_w8(pb, strlen(font)); /* font len (part of the pascal string) */
2357 avio_write(pb, font, strlen(font)); /* font name */
2358 return update_size(pb, pos);
2361 static int mov_write_gmhd_tag(AVIOContext *pb, MOVTrack *track)
2363 int64_t pos = avio_tell(pb);
2364 avio_wb32(pb, 0); /* size */
2365 ffio_wfourcc(pb, "gmhd");
2366 avio_wb32(pb, 0x18); /* gmin size */
2367 ffio_wfourcc(pb, "gmin");/* generic media info */
2368 avio_wb32(pb, 0); /* version & flags */
2369 avio_wb16(pb, 0x40); /* graphics mode = */
2370 avio_wb16(pb, 0x8000); /* opColor (r?) */
2371 avio_wb16(pb, 0x8000); /* opColor (g?) */
2372 avio_wb16(pb, 0x8000); /* opColor (b?) */
2373 avio_wb16(pb, 0); /* balance */
2374 avio_wb16(pb, 0); /* reserved */
2377 * This special text atom is required for
2378 * Apple Quicktime chapters. The contents
2379 * don't appear to be documented, so the
2380 * bytes are copied verbatim.
2382 if (track->tag != MKTAG('c','6','0','8')) {
2383 avio_wb32(pb, 0x2C); /* size */
2384 ffio_wfourcc(pb, "text");
2385 avio_wb16(pb, 0x01);
2386 avio_wb32(pb, 0x00);
2387 avio_wb32(pb, 0x00);
2388 avio_wb32(pb, 0x00);
2389 avio_wb32(pb, 0x01);
2390 avio_wb32(pb, 0x00);
2391 avio_wb32(pb, 0x00);
2392 avio_wb32(pb, 0x00);
2393 avio_wb32(pb, 0x00004000);
2394 avio_wb16(pb, 0x0000);
2397 if (track->par->codec_tag == MKTAG('t','m','c','d')) {
2398 int64_t tmcd_pos = avio_tell(pb);
2399 avio_wb32(pb, 0); /* size */
2400 ffio_wfourcc(pb, "tmcd");
2401 mov_write_tcmi_tag(pb, track);
2402 update_size(pb, tmcd_pos);
2403 } else if (track->par->codec_tag == MKTAG('g','p','m','d')) {
2404 int64_t gpmd_pos = avio_tell(pb);
2405 avio_wb32(pb, 0); /* size */
2406 ffio_wfourcc(pb, "gpmd");
2407 avio_wb32(pb, 0); /* version */
2408 update_size(pb, gpmd_pos);
2410 return update_size(pb, pos);
2413 static int mov_write_smhd_tag(AVIOContext *pb)
2415 avio_wb32(pb, 16); /* size */
2416 ffio_wfourcc(pb, "smhd");
2417 avio_wb32(pb, 0); /* version & flags */
2418 avio_wb16(pb, 0); /* reserved (balance, normally = 0) */
2419 avio_wb16(pb, 0); /* reserved */
2423 static int mov_write_vmhd_tag(AVIOContext *pb)
2425 avio_wb32(pb, 0x14); /* size (always 0x14) */
2426 ffio_wfourcc(pb, "vmhd");
2427 avio_wb32(pb, 0x01); /* version & flags */
2428 avio_wb64(pb, 0); /* reserved (graphics mode = copy) */
2432 static int is_clcp_track(MOVTrack *track)
2434 return track->tag == MKTAG('c','7','0','8') ||
2435 track->tag == MKTAG('c','6','0','8');
2438 static int mov_write_hdlr_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
2440 const char *hdlr, *descr = NULL, *hdlr_type = NULL;
2441 int64_t pos = avio_tell(pb);
2445 descr = "DataHandler";
2448 hdlr = (track->mode == MODE_MOV) ? "mhlr" : "\0\0\0\0";
2449 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
2451 descr = "VideoHandler";
2452 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
2454 descr = "SoundHandler";
2455 } else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE) {
2456 if (is_clcp_track(track)) {
2458 descr = "ClosedCaptionHandler";
2460 if (track->tag == MKTAG('t','x','3','g')) {
2462 } else if (track->tag == MKTAG('m','p','4','s')) {
2467 descr = "SubtitleHandler";
2469 } else if (track->par->codec_tag == MKTAG('r','t','p',' ')) {
2471 descr = "HintHandler";
2472 } else if (track->par->codec_tag == MKTAG('t','m','c','d')) {
2474 descr = "TimeCodeHandler";
2475 } else if (track->par->codec_tag == MKTAG('g','p','m','d')) {
2477 descr = "GoPro MET"; // GoPro Metadata
2479 av_log(s, AV_LOG_WARNING,
2480 "Unknown hldr_type for %s, writing dummy values\n",
2481 av_fourcc2str(track->par->codec_tag));
2484 // hdlr.name is used by some players to identify the content title
2485 // of the track. So if an alternate handler description is
2486 // specified, use it.
2487 AVDictionaryEntry *t;
2488 t = av_dict_get(track->st->metadata, "handler", NULL, 0);
2489 if (t && utf8len(t->value))
2494 avio_wb32(pb, 0); /* size */
2495 ffio_wfourcc(pb, "hdlr");
2496 avio_wb32(pb, 0); /* Version & flags */
2497 avio_write(pb, hdlr, 4); /* handler */
2498 ffio_wfourcc(pb, hdlr_type); /* handler type */
2499 avio_wb32(pb, 0); /* reserved */
2500 avio_wb32(pb, 0); /* reserved */
2501 avio_wb32(pb, 0); /* reserved */
2502 if (!track || track->mode == MODE_MOV)
2503 avio_w8(pb, strlen(descr)); /* pascal string */
2504 avio_write(pb, descr, strlen(descr)); /* handler description */
2505 if (track && track->mode != MODE_MOV)
2506 avio_w8(pb, 0); /* c string */
2507 return update_size(pb, pos);
2510 static int mov_write_hmhd_tag(AVIOContext *pb)
2512 /* This atom must be present, but leaving the values at zero
2513 * seems harmless. */
2514 avio_wb32(pb, 28); /* size */
2515 ffio_wfourcc(pb, "hmhd");
2516 avio_wb32(pb, 0); /* version, flags */
2517 avio_wb16(pb, 0); /* maxPDUsize */
2518 avio_wb16(pb, 0); /* avgPDUsize */
2519 avio_wb32(pb, 0); /* maxbitrate */
2520 avio_wb32(pb, 0); /* avgbitrate */
2521 avio_wb32(pb, 0); /* reserved */
2525 static int mov_write_minf_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
2527 int64_t pos = avio_tell(pb);
2530 avio_wb32(pb, 0); /* size */
2531 ffio_wfourcc(pb, "minf");
2532 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO)
2533 mov_write_vmhd_tag(pb);
2534 else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
2535 mov_write_smhd_tag(pb);
2536 else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE) {
2537 if (track->tag == MKTAG('t','e','x','t') || is_clcp_track(track)) {
2538 mov_write_gmhd_tag(pb, track);
2540 mov_write_nmhd_tag(pb);
2542 } else if (track->tag == MKTAG('r','t','p',' ')) {
2543 mov_write_hmhd_tag(pb);
2544 } else if (track->tag == MKTAG('t','m','c','d')) {
2545 if (track->mode != MODE_MOV)
2546 mov_write_nmhd_tag(pb);
2548 mov_write_gmhd_tag(pb, track);
2549 } else if (track->tag == MKTAG('g','p','m','d')) {
2550 mov_write_gmhd_tag(pb, track);
2552 if (track->mode == MODE_MOV) /* FIXME: Why do it for MODE_MOV only ? */
2553 mov_write_hdlr_tag(s, pb, NULL);
2554 mov_write_dinf_tag(pb);
2555 if ((ret = mov_write_stbl_tag(s, pb, mov, track)) < 0)
2557 return update_size(pb, pos);
2560 static int mov_write_mdhd_tag(AVIOContext *pb, MOVMuxContext *mov,
2563 int version = track->track_duration < INT32_MAX ? 0 : 1;
2565 if (track->mode == MODE_ISM)
2568 (version == 1) ? avio_wb32(pb, 44) : avio_wb32(pb, 32); /* size */
2569 ffio_wfourcc(pb, "mdhd");
2570 avio_w8(pb, version);
2571 avio_wb24(pb, 0); /* flags */
2573 avio_wb64(pb, track->time);
2574 avio_wb64(pb, track->time);
2576 avio_wb32(pb, track->time); /* creation time */
2577 avio_wb32(pb, track->time); /* modification time */
2579 avio_wb32(pb, track->timescale); /* time scale (sample rate for audio) */
2580 if (!track->entry && mov->mode == MODE_ISM)
2581 (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
2582 else if (!track->entry)
2583 (version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0);
2585 (version == 1) ? avio_wb64(pb, track->track_duration) : avio_wb32(pb, track->track_duration); /* duration */
2586 avio_wb16(pb, track->language); /* language */
2587 avio_wb16(pb, 0); /* reserved (quality) */
2589 if (version != 0 && track->mode == MODE_MOV) {
2590 av_log(NULL, AV_LOG_ERROR,
2591 "FATAL error, file duration too long for timebase, this file will not be\n"
2592 "playable with quicktime. Choose a different timebase or a different\n"
2593 "container format\n");
2599 static int mov_write_mdia_tag(AVFormatContext *s, AVIOContext *pb,
2600 MOVMuxContext *mov, MOVTrack *track)
2602 int64_t pos = avio_tell(pb);
2605 avio_wb32(pb, 0); /* size */
2606 ffio_wfourcc(pb, "mdia");
2607 mov_write_mdhd_tag(pb, mov, track);
2608 mov_write_hdlr_tag(s, pb, track);
2609 if ((ret = mov_write_minf_tag(s, pb, mov, track)) < 0)
2611 return update_size(pb, pos);
2614 /* transformation matrix
2618 static void write_matrix(AVIOContext *pb, int16_t a, int16_t b, int16_t c,
2619 int16_t d, int16_t tx, int16_t ty)
2621 avio_wb32(pb, a << 16); /* 16.16 format */
2622 avio_wb32(pb, b << 16); /* 16.16 format */
2623 avio_wb32(pb, 0); /* u in 2.30 format */
2624 avio_wb32(pb, c << 16); /* 16.16 format */
2625 avio_wb32(pb, d << 16); /* 16.16 format */
2626 avio_wb32(pb, 0); /* v in 2.30 format */
2627 avio_wb32(pb, tx << 16); /* 16.16 format */
2628 avio_wb32(pb, ty << 16); /* 16.16 format */
2629 avio_wb32(pb, 1 << 30); /* w in 2.30 format */
2632 static int mov_write_tkhd_tag(AVIOContext *pb, MOVMuxContext *mov,
2633 MOVTrack *track, AVStream *st)
2635 int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE,
2636 track->timescale, AV_ROUND_UP);
2637 int version = duration < INT32_MAX ? 0 : 1;
2638 int flags = MOV_TKHD_FLAG_IN_MOVIE;
2642 uint32_t *display_matrix = NULL;
2643 int display_matrix_size, i;
2646 if (mov->per_stream_grouping)
2649 group = st->codecpar->codec_type;
2651 display_matrix = (uint32_t*)av_stream_get_side_data(st, AV_PKT_DATA_DISPLAYMATRIX,
2652 &display_matrix_size);
2653 if (display_matrix && display_matrix_size < 9 * sizeof(*display_matrix))
2654 display_matrix = NULL;
2657 if (track->flags & MOV_TRACK_ENABLED)
2658 flags |= MOV_TKHD_FLAG_ENABLED;
2660 if (track->mode == MODE_ISM)
2663 (version == 1) ? avio_wb32(pb, 104) : avio_wb32(pb, 92); /* size */
2664 ffio_wfourcc(pb, "tkhd");
2665 avio_w8(pb, version);
2666 avio_wb24(pb, flags);
2668 avio_wb64(pb, track->time);
2669 avio_wb64(pb, track->time);
2671 avio_wb32(pb, track->time); /* creation time */
2672 avio_wb32(pb, track->time); /* modification time */
2674 avio_wb32(pb, track->track_id); /* track-id */
2675 avio_wb32(pb, 0); /* reserved */
2676 if (!track->entry && mov->mode == MODE_ISM)
2677 (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
2678 else if (!track->entry)
2679 (version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0);
2681 (version == 1) ? avio_wb64(pb, duration) : avio_wb32(pb, duration);
2683 avio_wb32(pb, 0); /* reserved */
2684 avio_wb32(pb, 0); /* reserved */
2685 avio_wb16(pb, 0); /* layer */
2686 avio_wb16(pb, group); /* alternate group) */
2687 /* Volume, only for audio */
2688 if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
2689 avio_wb16(pb, 0x0100);
2692 avio_wb16(pb, 0); /* reserved */
2694 /* Matrix structure */
2695 #if FF_API_OLD_ROTATE_API
2696 if (st && st->metadata) {
2697 AVDictionaryEntry *rot = av_dict_get(st->metadata, "rotate", NULL, 0);
2698 rotation = (rot && rot->value) ? atoi(rot->value) : 0;
2701 if (display_matrix) {
2702 for (i = 0; i < 9; i++)
2703 avio_wb32(pb, display_matrix[i]);
2704 #if FF_API_OLD_ROTATE_API
2705 } else if (rotation == 90) {
2706 write_matrix(pb, 0, 1, -1, 0, track->par->height, 0);
2707 } else if (rotation == 180) {
2708 write_matrix(pb, -1, 0, 0, -1, track->par->width, track->par->height);
2709 } else if (rotation == 270) {
2710 write_matrix(pb, 0, -1, 1, 0, 0, track->par->width);
2713 write_matrix(pb, 1, 0, 0, 1, 0, 0);
2715 /* Track width and height, for visual only */
2716 if (st && (track->par->codec_type == AVMEDIA_TYPE_VIDEO ||
2717 track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)) {
2718 int64_t track_width_1616;
2719 if (track->mode == MODE_MOV) {
2720 track_width_1616 = track->par->width * 0x10000ULL;
2722 track_width_1616 = av_rescale(st->sample_aspect_ratio.num,
2723 track->par->width * 0x10000LL,
2724 st->sample_aspect_ratio.den);
2725 if (!track_width_1616 ||
2726 track->height != track->par->height ||
2727 track_width_1616 > UINT32_MAX)
2728 track_width_1616 = track->par->width * 0x10000ULL;
2730 if (track_width_1616 > UINT32_MAX) {
2731 av_log(mov->fc, AV_LOG_WARNING, "track width is too large\n");
2732 track_width_1616 = 0;
2734 avio_wb32(pb, track_width_1616);
2735 if (track->height > 0xFFFF) {
2736 av_log(mov->fc, AV_LOG_WARNING, "track height is too large\n");
2739 avio_wb32(pb, track->height * 0x10000U);
2747 static int mov_write_tapt_tag(AVIOContext *pb, MOVTrack *track)
2749 int32_t width = av_rescale(track->par->sample_aspect_ratio.num, track->par->width,
2750 track->par->sample_aspect_ratio.den);
2752 int64_t pos = avio_tell(pb);
2754 avio_wb32(pb, 0); /* size */
2755 ffio_wfourcc(pb, "tapt");
2758 ffio_wfourcc(pb, "clef");
2760 avio_wb32(pb, width << 16);
2761 avio_wb32(pb, track->par->height << 16);
2764 ffio_wfourcc(pb, "prof");
2766 avio_wb32(pb, width << 16);
2767 avio_wb32(pb, track->par->height << 16);
2770 ffio_wfourcc(pb, "enof");
2772 avio_wb32(pb, track->par->width << 16);
2773 avio_wb32(pb, track->par->height << 16);
2775 return update_size(pb, pos);
2778 // This box seems important for the psp playback ... without it the movie seems to hang
2779 static int mov_write_edts_tag(AVIOContext *pb, MOVMuxContext *mov,
2782 int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE,
2783 track->timescale, AV_ROUND_UP);
2784 int version = duration < INT32_MAX ? 0 : 1;
2785 int entry_size, entry_count, size;
2786 int64_t delay, start_ct = track->start_cts;
2787 int64_t start_dts = track->start_dts;
2790 if (start_dts != track->cluster[0].dts || start_ct != track->cluster[0].cts) {
2792 av_log(mov->fc, AV_LOG_DEBUG,
2793 "EDTS using dts:%"PRId64" cts:%d instead of dts:%"PRId64" cts:%"PRId64" tid:%d\n",
2794 track->cluster[0].dts, track->cluster[0].cts,
2795 start_dts, start_ct, track->track_id);
2796 start_dts = track->cluster[0].dts;
2797 start_ct = track->cluster[0].cts;
2801 delay = av_rescale_rnd(start_dts + start_ct, MOV_TIMESCALE,
2802 track->timescale, AV_ROUND_DOWN);
2803 version |= delay < INT32_MAX ? 0 : 1;
2805 entry_size = (version == 1) ? 20 : 12;
2806 entry_count = 1 + (delay > 0);
2807 size = 24 + entry_count * entry_size;
2809 /* write the atom data */
2810 avio_wb32(pb, size);
2811 ffio_wfourcc(pb, "edts");
2812 avio_wb32(pb, size - 8);
2813 ffio_wfourcc(pb, "elst");
2814 avio_w8(pb, version);
2815 avio_wb24(pb, 0); /* flags */
2817 avio_wb32(pb, entry_count);
2818 if (delay > 0) { /* add an empty edit to delay presentation */
2819 /* In the positive delay case, the delay includes the cts
2820 * offset, and the second edit list entry below trims out
2821 * the same amount from the actual content. This makes sure
2822 * that the offset last sample is included in the edit
2823 * list duration as well. */
2825 avio_wb64(pb, delay);
2828 avio_wb32(pb, delay);
2831 avio_wb32(pb, 0x00010000);
2833 /* Avoid accidentally ending up with start_ct = -1 which has got a
2834 * special meaning. Normally start_ct should end up positive or zero
2835 * here, but use FFMIN in case dts is a small positive integer
2836 * rounded to 0 when represented in MOV_TIMESCALE units. */
2837 av_assert0(av_rescale_rnd(start_dts, MOV_TIMESCALE, track->timescale, AV_ROUND_DOWN) <= 0);
2838 start_ct = -FFMIN(start_dts, 0);
2839 /* Note, this delay is calculated from the pts of the first sample,
2840 * ensuring that we don't reduce the duration for cases with
2845 /* For fragmented files, we don't know the full length yet. Setting
2846 * duration to 0 allows us to only specify the offset, including
2847 * the rest of the content (from all future fragments) without specifying
2848 * an explicit duration. */
2849 if (mov->flags & FF_MOV_FLAG_FRAGMENT)
2854 avio_wb64(pb, duration);
2855 avio_wb64(pb, start_ct);
2857 avio_wb32(pb, duration);
2858 avio_wb32(pb, start_ct);
2860 avio_wb32(pb, 0x00010000);
2864 static int mov_write_tref_tag(AVIOContext *pb, MOVTrack *track)
2866 avio_wb32(pb, 20); // size
2867 ffio_wfourcc(pb, "tref");
2868 avio_wb32(pb, 12); // size (subatom)
2869 avio_wl32(pb, track->tref_tag);
2870 avio_wb32(pb, track->tref_id);
2874 // goes at the end of each track! ... Critical for PSP playback ("Incompatible data" without it)
2875 static int mov_write_uuid_tag_psp(AVIOContext *pb, MOVTrack *mov)
2877 avio_wb32(pb, 0x34); /* size ... reports as 28 in mp4box! */
2878 ffio_wfourcc(pb, "uuid");
2879 ffio_wfourcc(pb, "USMT");
2880 avio_wb32(pb, 0x21d24fce);
2881 avio_wb32(pb, 0xbb88695c);
2882 avio_wb32(pb, 0xfac9c740);
2883 avio_wb32(pb, 0x1c); // another size here!
2884 ffio_wfourcc(pb, "MTDT");
2885 avio_wb32(pb, 0x00010012);
2886 avio_wb32(pb, 0x0a);
2887 avio_wb32(pb, 0x55c40000);
2893 static int mov_write_udta_sdp(AVIOContext *pb, MOVTrack *track)
2895 AVFormatContext *ctx = track->rtp_ctx;
2896 char buf[1000] = "";
2899 ff_sdp_write_media(buf, sizeof(buf), ctx->streams[0], track->src_track,
2900 NULL, NULL, 0, 0, ctx);
2901 av_strlcatf(buf, sizeof(buf), "a=control:streamid=%d\r\n", track->track_id);
2904 avio_wb32(pb, len + 24);
2905 ffio_wfourcc(pb, "udta");
2906 avio_wb32(pb, len + 16);
2907 ffio_wfourcc(pb, "hnti");
2908 avio_wb32(pb, len + 8);
2909 ffio_wfourcc(pb, "sdp ");
2910 avio_write(pb, buf, len);
2914 static int mov_write_track_metadata(AVIOContext *pb, AVStream *st,
2915 const char *tag, const char *str)
2917 int64_t pos = avio_tell(pb);
2918 AVDictionaryEntry *t = av_dict_get(st->metadata, str, NULL, 0);
2919 if (!t || !utf8len(t->value))
2922 avio_wb32(pb, 0); /* size */
2923 ffio_wfourcc(pb, tag); /* type */
2924 avio_write(pb, t->value, strlen(t->value)); /* UTF8 string value */
2925 return update_size(pb, pos);
2928 static int mov_write_track_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
2931 AVIOContext *pb_buf;
2938 ret = avio_open_dyn_buf(&pb_buf);
2942 if (mov->mode & MODE_MP4)
2943 mov_write_track_metadata(pb_buf, st, "name", "title");
2945 if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) {
2946 avio_wb32(pb, size + 8);
2947 ffio_wfourcc(pb, "udta");
2948 avio_write(pb, buf, size);
2955 static int mov_write_trak_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov,
2956 MOVTrack *track, AVStream *st)
2958 int64_t pos = avio_tell(pb);
2959 int entry_backup = track->entry;
2960 int chunk_backup = track->chunkCount;
2963 /* If we want to have an empty moov, but some samples already have been
2964 * buffered (delay_moov), pretend that no samples have been written yet. */
2965 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV)
2966 track->chunkCount = track->entry = 0;
2968 avio_wb32(pb, 0); /* size */
2969 ffio_wfourcc(pb, "trak");
2970 mov_write_tkhd_tag(pb, mov, track, st);
2972 av_assert2(mov->use_editlist >= 0);
2974 if (track->start_dts != AV_NOPTS_VALUE) {
2975 if (mov->use_editlist)
2976 mov_write_edts_tag(pb, mov, track); // PSP Movies and several other cases require edts box
2977 else if ((track->entry && track->cluster[0].dts) || track->mode == MODE_PSP || is_clcp_track(track))
2978 av_log(mov->fc, AV_LOG_WARNING,
2979 "Not writing any edit list even though one would have been required\n");
2982 if (track->tref_tag)
2983 mov_write_tref_tag(pb, track);
2985 if ((ret = mov_write_mdia_tag(s, pb, mov, track)) < 0)
2987 if (track->mode == MODE_PSP)
2988 mov_write_uuid_tag_psp(pb, track); // PSP Movies require this uuid box
2989 if (track->tag == MKTAG('r','t','p',' '))
2990 mov_write_udta_sdp(pb, track);
2991 if (track->mode == MODE_MOV) {
2992 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
2993 double sample_aspect_ratio = av_q2d(st->sample_aspect_ratio);
2994 if (st->sample_aspect_ratio.num && 1.0 != sample_aspect_ratio) {
2995 mov_write_tapt_tag(pb, track);
2998 if (is_clcp_track(track) && st->sample_aspect_ratio.num) {
2999 mov_write_tapt_tag(pb, track);
3002 mov_write_track_udta_tag(pb, mov, st);
3003 track->entry = entry_backup;
3004 track->chunkCount = chunk_backup;
3005 return update_size(pb, pos);
3008 static int mov_write_iods_tag(AVIOContext *pb, MOVMuxContext *mov)
3010 int i, has_audio = 0, has_video = 0;
3011 int64_t pos = avio_tell(pb);
3012 int audio_profile = mov->iods_audio_profile;
3013 int video_profile = mov->iods_video_profile;
3014 for (i = 0; i < mov->nb_streams; i++) {
3015 if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
3016 has_audio |= mov->tracks[i].par->codec_type == AVMEDIA_TYPE_AUDIO;
3017 has_video |= mov->tracks[i].par->codec_type == AVMEDIA_TYPE_VIDEO;
3020 if (audio_profile < 0)
3021 audio_profile = 0xFF - has_audio;
3022 if (video_profile < 0)
3023 video_profile = 0xFF - has_video;
3024 avio_wb32(pb, 0x0); /* size */
3025 ffio_wfourcc(pb, "iods");
3026 avio_wb32(pb, 0); /* version & flags */
3027 put_descr(pb, 0x10, 7);
3028 avio_wb16(pb, 0x004f);
3031 avio_w8(pb, audio_profile);
3032 avio_w8(pb, video_profile);
3034 return update_size(pb, pos);
3037 static int mov_write_trex_tag(AVIOContext *pb, MOVTrack *track)
3039 avio_wb32(pb, 0x20); /* size */
3040 ffio_wfourcc(pb, "trex");
3041 avio_wb32(pb, 0); /* version & flags */
3042 avio_wb32(pb, track->track_id); /* track ID */
3043 avio_wb32(pb, 1); /* default sample description index */
3044 avio_wb32(pb, 0); /* default sample duration */
3045 avio_wb32(pb, 0); /* default sample size */
3046 avio_wb32(pb, 0); /* default sample flags */
3050 static int mov_write_mvex_tag(AVIOContext *pb, MOVMuxContext *mov)
3052 int64_t pos = avio_tell(pb);
3054 avio_wb32(pb, 0x0); /* size */
3055 ffio_wfourcc(pb, "mvex");
3056 for (i = 0; i < mov->nb_streams; i++)
3057 mov_write_trex_tag(pb, &mov->tracks[i]);
3058 return update_size(pb, pos);
3061 static int mov_write_mvhd_tag(AVIOContext *pb, MOVMuxContext *mov)
3063 int max_track_id = 1, i;
3064 int64_t max_track_len = 0;
3067 for (i = 0; i < mov->nb_streams; i++) {
3068 if (mov->tracks[i].entry > 0 && mov->tracks[i].timescale) {
3069 int64_t max_track_len_temp = av_rescale_rnd(mov->tracks[i].track_duration,
3071 mov->tracks[i].timescale,
3073 if (max_track_len < max_track_len_temp)
3074 max_track_len = max_track_len_temp;
3075 if (max_track_id < mov->tracks[i].track_id)
3076 max_track_id = mov->tracks[i].track_id;
3079 /* If using delay_moov, make sure the output is the same as if no
3080 * samples had been written yet. */
3081 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
3086 version = max_track_len < UINT32_MAX ? 0 : 1;
3087 avio_wb32(pb, version == 1 ? 120 : 108); /* size */
3089 ffio_wfourcc(pb, "mvhd");
3090 avio_w8(pb, version);
3091 avio_wb24(pb, 0); /* flags */
3093 avio_wb64(pb, mov->time);
3094 avio_wb64(pb, mov->time);
3096 avio_wb32(pb, mov->time); /* creation time */
3097 avio_wb32(pb, mov->time); /* modification time */
3099 avio_wb32(pb, MOV_TIMESCALE);
3100 (version == 1) ? avio_wb64(pb, max_track_len) : avio_wb32(pb, max_track_len); /* duration of longest track */
3102 avio_wb32(pb, 0x00010000); /* reserved (preferred rate) 1.0 = normal */
3103 avio_wb16(pb, 0x0100); /* reserved (preferred volume) 1.0 = normal */
3104 avio_wb16(pb, 0); /* reserved */
3105 avio_wb32(pb, 0); /* reserved */
3106 avio_wb32(pb, 0); /* reserved */
3108 /* Matrix structure */
3109 write_matrix(pb, 1, 0, 0, 1, 0, 0);
3111 avio_wb32(pb, 0); /* reserved (preview time) */
3112 avio_wb32(pb, 0); /* reserved (preview duration) */
3113 avio_wb32(pb, 0); /* reserved (poster time) */
3114 avio_wb32(pb, 0); /* reserved (selection time) */
3115 avio_wb32(pb, 0); /* reserved (selection duration) */
3116 avio_wb32(pb, 0); /* reserved (current time) */
3117 avio_wb32(pb, max_track_id + 1); /* Next track id */
3121 static int mov_write_itunes_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov,
3124 avio_wb32(pb, 33); /* size */
3125 ffio_wfourcc(pb, "hdlr");
3128 ffio_wfourcc(pb, "mdir");
3129 ffio_wfourcc(pb, "appl");
3136 /* helper function to write a data tag with the specified string as data */
3137 static int mov_write_string_data_tag(AVIOContext *pb, const char *data, int lang, int long_style)
3140 int size = 16 + strlen(data);
3141 avio_wb32(pb, size); /* size */
3142 ffio_wfourcc(pb, "data");
3145 avio_write(pb, data, strlen(data));
3149 lang = ff_mov_iso639_to_lang("und", 1);
3150 avio_wb16(pb, strlen(data)); /* string length */
3151 avio_wb16(pb, lang);
3152 avio_write(pb, data, strlen(data));
3153 return strlen(data) + 4;
3157 static int mov_write_string_tag(AVIOContext *pb, const char *name,
3158 const char *value, int lang, int long_style)
3161 if (value && value[0]) {
3162 int64_t pos = avio_tell(pb);
3163 avio_wb32(pb, 0); /* size */
3164 ffio_wfourcc(pb, name);
3165 mov_write_string_data_tag(pb, value, lang, long_style);
3166 size = update_size(pb, pos);
3171 static AVDictionaryEntry *get_metadata_lang(AVFormatContext *s,
3172 const char *tag, int *lang)
3175 AVDictionaryEntry *t, *t2 = NULL;
3180 if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
3183 len = strlen(t->key);
3184 snprintf(tag2, sizeof(tag2), "%s-", tag);
3185 while ((t2 = av_dict_get(s->metadata, tag2, t2, AV_DICT_IGNORE_SUFFIX))) {
3186 len2 = strlen(t2->key);
3187 if (len2 == len + 4 && !strcmp(t->value, t2->value)
3188 && (l = ff_mov_iso639_to_lang(&t2->key[len2 - 3], 1)) >= 0) {
3196 static int mov_write_string_metadata(AVFormatContext *s, AVIOContext *pb,
3197 const char *name, const char *tag,
3201 AVDictionaryEntry *t = get_metadata_lang(s, tag, &lang);
3204 return mov_write_string_tag(pb, name, t->value, lang, long_style);
3207 /* iTunes bpm number */
3208 static int mov_write_tmpo_tag(AVIOContext *pb, AVFormatContext *s)
3210 AVDictionaryEntry *t = av_dict_get(s->metadata, "tmpo", NULL, 0);
3211 int size = 0, tmpo = t ? atoi(t->value) : 0;
3214 avio_wb32(pb, size);
3215 ffio_wfourcc(pb, "tmpo");
3216 avio_wb32(pb, size-8); /* size */
3217 ffio_wfourcc(pb, "data");
3218 avio_wb32(pb, 0x15); //type specifier
3220 avio_wb16(pb, tmpo); // data
3225 /* 3GPP TS 26.244 */
3226 static int mov_write_loci_tag(AVFormatContext *s, AVIOContext *pb)
3229 int64_t pos = avio_tell(pb);
3230 double latitude, longitude, altitude;
3231 int32_t latitude_fix, longitude_fix, altitude_fix;
3232 AVDictionaryEntry *t = get_metadata_lang(s, "location", &lang);
3233 const char *ptr, *place = "";
3235 static const char *astronomical_body = "earth";
3240 longitude = strtod(ptr, &end);
3242 av_log(s, AV_LOG_WARNING, "malformed location metadata\n");
3246 latitude = strtod(ptr, &end);
3248 av_log(s, AV_LOG_WARNING, "malformed location metadata\n");
3252 altitude = strtod(ptr, &end);
3253 /* If no altitude was present, the default 0 should be fine */
3257 latitude_fix = (int32_t) ((1 << 16) * latitude);
3258 longitude_fix = (int32_t) ((1 << 16) * longitude);
3259 altitude_fix = (int32_t) ((1 << 16) * altitude);
3261 avio_wb32(pb, 0); /* size */
3262 ffio_wfourcc(pb, "loci"); /* type */
3263 avio_wb32(pb, 0); /* version + flags */
3264 avio_wb16(pb, lang);
3265 avio_write(pb, place, strlen(place) + 1);
3266 avio_w8(pb, 0); /* role of place (0 == shooting location, 1 == real location, 2 == fictional location) */
3267 avio_wb32(pb, latitude_fix);
3268 avio_wb32(pb, longitude_fix);
3269 avio_wb32(pb, altitude_fix);
3270 avio_write(pb, astronomical_body, strlen(astronomical_body) + 1);
3271 avio_w8(pb, 0); /* additional notes, null terminated string */
3273 return update_size(pb, pos);
3276 /* iTunes track or disc number */
3277 static int mov_write_trkn_tag(AVIOContext *pb, MOVMuxContext *mov,
3278 AVFormatContext *s, int disc)
3280 AVDictionaryEntry *t = av_dict_get(s->metadata,
3281 disc ? "disc" : "track",
3283 int size = 0, track = t ? atoi(t->value) : 0;
3286 char *slash = strchr(t->value, '/');
3288 tracks = atoi(slash + 1);
3289 avio_wb32(pb, 32); /* size */
3290 ffio_wfourcc(pb, disc ? "disk" : "trkn");
3291 avio_wb32(pb, 24); /* size */
3292 ffio_wfourcc(pb, "data");
3293 avio_wb32(pb, 0); // 8 bytes empty
3295 avio_wb16(pb, 0); // empty
3296 avio_wb16(pb, track); // track / disc number
3297 avio_wb16(pb, tracks); // total track / disc number
3298 avio_wb16(pb, 0); // empty
3304 static int mov_write_int8_metadata(AVFormatContext *s, AVIOContext *pb,
3305 const char *name, const char *tag,
3308 AVDictionaryEntry *t = NULL;
3310 int size = 24 + len;
3312 if (len != 1 && len != 4)
3315 if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
3317 num = atoi(t->value);
3319 avio_wb32(pb, size);
3320 ffio_wfourcc(pb, name);
3321 avio_wb32(pb, size - 8);
3322 ffio_wfourcc(pb, "data");
3323 avio_wb32(pb, 0x15);
3325 if (len==4) avio_wb32(pb, num);
3326 else avio_w8 (pb, num);
3331 /* iTunes meta data list */
3332 static int mov_write_ilst_tag(AVIOContext *pb, MOVMuxContext *mov,
3335 int64_t pos = avio_tell(pb);
3336 avio_wb32(pb, 0); /* size */
3337 ffio_wfourcc(pb, "ilst");
3338 mov_write_string_metadata(s, pb, "\251nam", "title" , 1);
3339 mov_write_string_metadata(s, pb, "\251ART", "artist" , 1);
3340 mov_write_string_metadata(s, pb, "aART", "album_artist", 1);
3341 mov_write_string_metadata(s, pb, "\251wrt", "composer" , 1);
3342 mov_write_string_metadata(s, pb, "\251alb", "album" , 1);
3343 mov_write_string_metadata(s, pb, "\251day", "date" , 1);
3344 if (!mov_write_string_metadata(s, pb, "\251too", "encoding_tool", 1)) {
3345 if (!(s->flags & AVFMT_FLAG_BITEXACT))
3346 mov_write_string_tag(pb, "\251too", LIBAVFORMAT_IDENT, 0, 1);
3348 mov_write_string_metadata(s, pb, "\251cmt", "comment" , 1);
3349 mov_write_string_metadata(s, pb, "\251gen", "genre" , 1);
3350 mov_write_string_metadata(s, pb, "\251cpy", "copyright", 1);
3351 mov_write_string_metadata(s, pb, "\251grp", "grouping" , 1);
3352 mov_write_string_metadata(s, pb, "\251lyr", "lyrics" , 1);
3353 mov_write_string_metadata(s, pb, "desc", "description",1);
3354 mov_write_string_metadata(s, pb, "ldes", "synopsis" , 1);
3355 mov_write_string_metadata(s, pb, "tvsh", "show" , 1);
3356 mov_write_string_metadata(s, pb, "tven", "episode_id",1);
3357 mov_write_string_metadata(s, pb, "tvnn", "network" , 1);
3358 mov_write_string_metadata(s, pb, "keyw", "keywords" , 1);
3359 mov_write_int8_metadata (s, pb, "tves", "episode_sort",4);
3360 mov_write_int8_metadata (s, pb, "tvsn", "season_number",4);
3361 mov_write_int8_metadata (s, pb, "stik", "media_type",1);
3362 mov_write_int8_metadata (s, pb, "hdvd", "hd_video", 1);
3363 mov_write_int8_metadata (s, pb, "pgap", "gapless_playback",1);
3364 mov_write_int8_metadata (s, pb, "cpil", "compilation", 1);
3365 mov_write_trkn_tag(pb, mov, s, 0); // track number
3366 mov_write_trkn_tag(pb, mov, s, 1); // disc number
3367 mov_write_tmpo_tag(pb, s);
3368 return update_size(pb, pos);
3371 static int mov_write_mdta_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov,
3374 avio_wb32(pb, 33); /* size */
3375 ffio_wfourcc(pb, "hdlr");
3378 ffio_wfourcc(pb, "mdta");
3386 static int mov_write_mdta_keys_tag(AVIOContext *pb, MOVMuxContext *mov,
3389 AVDictionaryEntry *t = NULL;
3390 int64_t pos = avio_tell(pb);
3391 int64_t curpos, entry_pos;
3394 avio_wb32(pb, 0); /* size */
3395 ffio_wfourcc(pb, "keys");
3397 entry_pos = avio_tell(pb);
3398 avio_wb32(pb, 0); /* entry count */
3400 while (t = av_dict_get(s->metadata, "", t, AV_DICT_IGNORE_SUFFIX)) {
3401 avio_wb32(pb, strlen(t->key) + 8);
3402 ffio_wfourcc(pb, "mdta");
3403 avio_write(pb, t->key, strlen(t->key));
3406 curpos = avio_tell(pb);
3407 avio_seek(pb, entry_pos, SEEK_SET);
3408 avio_wb32(pb, count); // rewrite entry count
3409 avio_seek(pb, curpos, SEEK_SET);
3411 return update_size(pb, pos);
3414 static int mov_write_mdta_ilst_tag(AVIOContext *pb, MOVMuxContext *mov,
3417 AVDictionaryEntry *t = NULL;
3418 int64_t pos = avio_tell(pb);
3419 int count = 1; /* keys are 1-index based */
3421 avio_wb32(pb, 0); /* size */
3422 ffio_wfourcc(pb, "ilst");
3424 while (t = av_dict_get(s->metadata, "", t, AV_DICT_IGNORE_SUFFIX)) {
3425 int64_t entry_pos = avio_tell(pb);
3426 avio_wb32(pb, 0); /* size */
3427 avio_wb32(pb, count); /* key */
3428 mov_write_string_data_tag(pb, t->value, 0, 1);
3429 update_size(pb, entry_pos);
3432 return update_size(pb, pos);
3435 /* meta data tags */
3436 static int mov_write_meta_tag(AVIOContext *pb, MOVMuxContext *mov,
3440 int64_t pos = avio_tell(pb);
3441 avio_wb32(pb, 0); /* size */
3442 ffio_wfourcc(pb, "meta");
3444 if (mov->flags & FF_MOV_FLAG_USE_MDTA) {
3445 mov_write_mdta_hdlr_tag(pb, mov, s);
3446 mov_write_mdta_keys_tag(pb, mov, s);
3447 mov_write_mdta_ilst_tag(pb, mov, s);
3450 /* iTunes metadata tag */
3451 mov_write_itunes_hdlr_tag(pb, mov, s);
3452 mov_write_ilst_tag(pb, mov, s);
3454 size = update_size(pb, pos);
3458 static int mov_write_raw_metadata_tag(AVFormatContext *s, AVIOContext *pb,
3459 const char *name, const char *key)
3462 AVDictionaryEntry *t;
3464 if (!(t = av_dict_get(s->metadata, key, NULL, 0)))
3467 len = strlen(t->value);
3470 avio_wb32(pb, size);
3471 ffio_wfourcc(pb, name);
3472 avio_write(pb, t->value, len);
3478 static int ascii_to_wc(AVIOContext *pb, const uint8_t *b)
3482 GET_UTF8(val, *b++, return -1;)
3485 avio_wb16(pb, 0x00);
3489 static uint16_t language_code(const char *str)
3491 return (((str[0] - 0x60) & 0x1F) << 10) +
3492 (((str[1] - 0x60) & 0x1F) << 5) +
3493 (( str[2] - 0x60) & 0x1F);
3496 static int mov_write_3gp_udta_tag(AVIOContext *pb, AVFormatContext *s,
3497 const char *tag, const char *str)
3499 int64_t pos = avio_tell(pb);
3500 AVDictionaryEntry *t = av_dict_get(s->metadata, str, NULL, 0);
3501 if (!t || !utf8len(t->value))
3503 avio_wb32(pb, 0); /* size */
3504 ffio_wfourcc(pb, tag); /* type */
3505 avio_wb32(pb, 0); /* version + flags */
3506 if (!strcmp(tag, "yrrc"))
3507 avio_wb16(pb, atoi(t->value));
3509 avio_wb16(pb, language_code("eng")); /* language */
3510 avio_write(pb, t->value, strlen(t->value) + 1); /* UTF8 string value */
3511 if (!strcmp(tag, "albm") &&
3512 (t = av_dict_get(s->metadata, "track", NULL, 0)))
3513 avio_w8(pb, atoi(t->value));
3515 return update_size(pb, pos);
3518 static int mov_write_chpl_tag(AVIOContext *pb, AVFormatContext *s)
3520 int64_t pos = avio_tell(pb);
3521 int i, nb_chapters = FFMIN(s->nb_chapters, 255);
3523 avio_wb32(pb, 0); // size
3524 ffio_wfourcc(pb, "chpl");
3525 avio_wb32(pb, 0x01000000); // version + flags
3526 avio_wb32(pb, 0); // unknown
3527 avio_w8(pb, nb_chapters);
3529 for (i = 0; i < nb_chapters; i++) {
3530 AVChapter *c = s->chapters[i];
3531 AVDictionaryEntry *t;
3532 avio_wb64(pb, av_rescale_q(c->start, c->time_base, (AVRational){1,10000000}));
3534 if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
3535 int len = FFMIN(strlen(t->value), 255);
3537 avio_write(pb, t->value, len);
3541 return update_size(pb, pos);
3544 static int mov_write_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
3547 AVIOContext *pb_buf;
3551 ret = avio_open_dyn_buf(&pb_buf);
3555 if (mov->mode & MODE_3GP) {
3556 mov_write_3gp_udta_tag(pb_buf, s, "perf", "artist");
3557 mov_write_3gp_udta_tag(pb_buf, s, "titl", "title");
3558 mov_write_3gp_udta_tag(pb_buf, s, "auth", "author");
3559 mov_write_3gp_udta_tag(pb_buf, s, "gnre", "genre");
3560 mov_write_3gp_udta_tag(pb_buf, s, "dscp", "comment");
3561 mov_write_3gp_udta_tag(pb_buf, s, "albm", "album");
3562 mov_write_3gp_udta_tag(pb_buf, s, "cprt", "copyright");
3563 mov_write_3gp_udta_tag(pb_buf, s, "yrrc", "date");
3564 mov_write_loci_tag(s, pb_buf);
3565 } 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
3566 mov_write_string_metadata(s, pb_buf, "\251ART", "artist", 0);
3567 mov_write_string_metadata(s, pb_buf, "\251nam", "title", 0);
3568 mov_write_string_metadata(s, pb_buf, "\251aut", "author", 0);
3569 mov_write_string_metadata(s, pb_buf, "\251alb", "album", 0);
3570 mov_write_string_metadata(s, pb_buf, "\251day", "date", 0);
3571 mov_write_string_metadata(s, pb_buf, "\251swr", "encoder", 0);
3572 // currently ignored by mov.c
3573 mov_write_string_metadata(s, pb_buf, "\251des", "comment", 0);
3574 // add support for libquicktime, this atom is also actually read by mov.c
3575 mov_write_string_metadata(s, pb_buf, "\251cmt", "comment", 0);
3576 mov_write_string_metadata(s, pb_buf, "\251gen", "genre", 0);
3577 mov_write_string_metadata(s, pb_buf, "\251cpy", "copyright", 0);
3578 mov_write_string_metadata(s, pb_buf, "\251mak", "make", 0);
3579 mov_write_string_metadata(s, pb_buf, "\251mod", "model", 0);
3580 mov_write_string_metadata(s, pb_buf, "\251xyz", "location", 0);
3581 mov_write_string_metadata(s, pb_buf, "\251key", "keywords", 0);
3582 mov_write_raw_metadata_tag(s, pb_buf, "XMP_", "xmp");
3584 /* iTunes meta data */
3585 mov_write_meta_tag(pb_buf, mov, s);
3586 mov_write_loci_tag(s, pb_buf);
3589 if (s->nb_chapters && !(mov->flags & FF_MOV_FLAG_DISABLE_CHPL))
3590 mov_write_chpl_tag(pb_buf, s);
3592 if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) {
3593 avio_wb32(pb, size + 8);
3594 ffio_wfourcc(pb, "udta");
3595 avio_write(pb, buf, size);
3602 static void mov_write_psp_udta_tag(AVIOContext *pb,
3603 const char *str, const char *lang, int type)
3605 int len = utf8len(str) + 1;
3608 avio_wb16(pb, len * 2 + 10); /* size */
3609 avio_wb32(pb, type); /* type */
3610 avio_wb16(pb, language_code(lang)); /* language */
3611 avio_wb16(pb, 0x01); /* ? */
3612 ascii_to_wc(pb, str);
3615 static int mov_write_uuidusmt_tag(AVIOContext *pb, AVFormatContext *s)
3617 AVDictionaryEntry *title = av_dict_get(s->metadata, "title", NULL, 0);
3621 pos = avio_tell(pb);
3622 avio_wb32(pb, 0); /* size placeholder*/
3623 ffio_wfourcc(pb, "uuid");
3624 ffio_wfourcc(pb, "USMT");
3625 avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
3626 avio_wb32(pb, 0xbb88695c);
3627 avio_wb32(pb, 0xfac9c740);
3629 pos2 = avio_tell(pb);
3630 avio_wb32(pb, 0); /* size placeholder*/
3631 ffio_wfourcc(pb, "MTDT");
3635 avio_wb16(pb, 0x0C); /* size */
3636 avio_wb32(pb, 0x0B); /* type */
3637 avio_wb16(pb, language_code("und")); /* language */
3638 avio_wb16(pb, 0x0); /* ? */
3639 avio_wb16(pb, 0x021C); /* data */
3641 if (!(s->flags & AVFMT_FLAG_BITEXACT))
3642 mov_write_psp_udta_tag(pb, LIBAVCODEC_IDENT, "eng", 0x04);
3643 mov_write_psp_udta_tag(pb, title->value, "eng", 0x01);
3644 mov_write_psp_udta_tag(pb, "2006/04/01 11:11:11", "und", 0x03);
3646 update_size(pb, pos2);
3647 return update_size(pb, pos);
3653 static void build_chunks(MOVTrack *trk)
3656 MOVIentry *chunk = &trk->cluster[0];
3657 uint64_t chunkSize = chunk->size;
3658 chunk->chunkNum = 1;
3659 if (trk->chunkCount)
3661 trk->chunkCount = 1;
3662 for (i = 1; i<trk->entry; i++){
3663 if (chunk->pos + chunkSize == trk->cluster[i].pos &&
3664 chunkSize + trk->cluster[i].size < (1<<20)){
3665 chunkSize += trk->cluster[i].size;
3666 chunk->samples_in_chunk += trk->cluster[i].entries;
3668 trk->cluster[i].chunkNum = chunk->chunkNum+1;
3669 chunk=&trk->cluster[i];
3670 chunkSize = chunk->size;
3677 * Assign track ids. If option "use_stream_ids_as_track_ids" is set,
3678 * the stream ids are used as track ids.
3680 * This assumes mov->tracks and s->streams are in the same order and
3681 * there are no gaps in either of them (so mov->tracks[n] refers to
3684 * As an exception, there can be more entries in
3685 * s->streams than in mov->tracks, in which case new track ids are
3686 * generated (starting after the largest found stream id).
3688 static int mov_setup_track_ids(MOVMuxContext *mov, AVFormatContext *s)
3692 if (mov->track_ids_ok)
3695 if (mov->use_stream_ids_as_track_ids) {
3696 int next_generated_track_id = 0;
3697 for (i = 0; i < s->nb_streams; i++) {
3698 if (s->streams[i]->id > next_generated_track_id)
3699 next_generated_track_id = s->streams[i]->id;
3702 for (i = 0; i < mov->nb_streams; i++) {
3703 if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
3706 mov->tracks[i].track_id = i >= s->nb_streams ? ++next_generated_track_id : s->streams[i]->id;
3709 for (i = 0; i < mov->nb_streams; i++) {
3710 if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
3713 mov->tracks[i].track_id = i + 1;
3717 mov->track_ids_ok = 1;
3722 static int mov_write_moov_tag(AVIOContext *pb, MOVMuxContext *mov,
3726 int64_t pos = avio_tell(pb);
3727 avio_wb32(pb, 0); /* size placeholder*/
3728 ffio_wfourcc(pb, "moov");
3730 mov_setup_track_ids(mov, s);
3732 for (i = 0; i < mov->nb_streams; i++) {
3733 if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
3736 mov->tracks[i].time = mov->time;
3738 if (mov->tracks[i].entry)
3739 build_chunks(&mov->tracks[i]);
3742 if (mov->chapter_track)
3743 for (i = 0; i < s->nb_streams; i++) {
3744 mov->tracks[i].tref_tag = MKTAG('c','h','a','p');
3745 mov->tracks[i].tref_id = mov->tracks[mov->chapter_track].track_id;
3747 for (i = 0; i < mov->nb_streams; i++) {
3748 MOVTrack *track = &mov->tracks[i];
3749 if (track->tag == MKTAG('r','t','p',' ')) {
3750 track->tref_tag = MKTAG('h','i','n','t');
3751 track->tref_id = mov->tracks[track->src_track].track_id;
3752 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
3753 int * fallback, size;
3754 fallback = (int*)av_stream_get_side_data(track->st,
3755 AV_PKT_DATA_FALLBACK_TRACK,
3757 if (fallback != NULL && size == sizeof(int)) {
3758 if (*fallback >= 0 && *fallback < mov->nb_streams) {
3759 track->tref_tag = MKTAG('f','a','l','l');
3760 track->tref_id = mov->tracks[*fallback].track_id;
3765 for (i = 0; i < mov->nb_streams; i++) {
3766 if (mov->tracks[i].tag == MKTAG('t','m','c','d')) {
3767 int src_trk = mov->tracks[i].src_track;
3768 mov->tracks[src_trk].tref_tag = mov->tracks[i].tag;
3769 mov->tracks[src_trk].tref_id = mov->tracks[i].track_id;
3770 //src_trk may have a different timescale than the tmcd track
3771 mov->tracks[i].track_duration = av_rescale(mov->tracks[src_trk].track_duration,
3772 mov->tracks[i].timescale,
3773 mov->tracks[src_trk].timescale);
3777 mov_write_mvhd_tag(pb, mov);
3778 if (mov->mode != MODE_MOV && !mov->iods_skip)
3779 mov_write_iods_tag(pb, mov);
3780 for (i = 0; i < mov->nb_streams; i++) {
3781 if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_FRAGMENT) {
3782 int ret = mov_write_trak_tag(s, pb, mov, &(mov->tracks[i]), i < s->nb_streams ? s->streams[i] : NULL);
3787 if (mov->flags & FF_MOV_FLAG_FRAGMENT)
3788 mov_write_mvex_tag(pb, mov); /* QuickTime requires trak to precede this */
3790 if (mov->mode == MODE_PSP)
3791 mov_write_uuidusmt_tag(pb, s);
3793 mov_write_udta_tag(pb, mov, s);
3795 return update_size(pb, pos);
3798 static void param_write_int(AVIOContext *pb, const char *name, int value)
3800 avio_printf(pb, "<param name=\"%s\" value=\"%d\" valuetype=\"data\"/>\n", name, value);
3803 static void param_write_string(AVIOContext *pb, const char *name, const char *value)
3805 avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, value);
3808 static void param_write_hex(AVIOContext *pb, const char *name, const uint8_t *value, int len)
3811 len = FFMIN(sizeof(buf) / 2 - 1, len);
3812 ff_data_to_hex(buf, value, len, 0);
3813 buf[2 * len] = '\0';
3814 avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, buf);
3817 static int mov_write_isml_manifest(AVIOContext *pb, MOVMuxContext *mov, AVFormatContext *s)
3819 int64_t pos = avio_tell(pb);
3821 int64_t manifest_bit_rate = 0;
3822 AVCPBProperties *props = NULL;
3824 static const uint8_t uuid[] = {
3825 0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd,
3826 0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66
3830 ffio_wfourcc(pb, "uuid");
3831 avio_write(pb, uuid, sizeof(uuid));
3834 avio_printf(pb, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
3835 avio_printf(pb, "<smil xmlns=\"http://www.w3.org/2001/SMIL20/Language\">\n");
3836 avio_printf(pb, "<head>\n");
3837 if (!(mov->fc->flags & AVFMT_FLAG_BITEXACT))
3838 avio_printf(pb, "<meta name=\"creator\" content=\"%s\" />\n",
3840 avio_printf(pb, "</head>\n");
3841 avio_printf(pb, "<body>\n");
3842 avio_printf(pb, "<switch>\n");
3844 mov_setup_track_ids(mov, s);
3846 for (i = 0; i < mov->nb_streams; i++) {
3847 MOVTrack *track = &mov->tracks[i];
3849 int track_id = track->track_id;
3850 char track_name_buf[32] = { 0 };
3852 AVStream *st = track->st;
3853 AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0);
3855 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
3857 } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
3863 props = (AVCPBProperties*)av_stream_get_side_data(track->st, AV_PKT_DATA_CPB_PROPERTIES, NULL);
3865 if (track->par->bit_rate) {
3866 manifest_bit_rate = track->par->bit_rate;
3868 manifest_bit_rate = props->max_bitrate;
3871 avio_printf(pb, "<%s systemBitrate=\"%"PRId64"\">\n", type,
3873 param_write_int(pb, "systemBitrate", manifest_bit_rate);
3874 param_write_int(pb, "trackID", track_id);
3875 param_write_string(pb, "systemLanguage", lang ? lang->value : "und");
3877 /* Build track name piece by piece: */
3879 av_strlcat(track_name_buf, type, sizeof(track_name_buf));
3880 /* 2. track language, if available */
3882 av_strlcatf(track_name_buf, sizeof(track_name_buf),
3883 "_%s", lang->value);
3884 /* 3. special type suffix */
3885 /* "_cc" = closed captions, "_ad" = audio_description */
3886 if (st->disposition & AV_DISPOSITION_HEARING_IMPAIRED)
3887 av_strlcat(track_name_buf, "_cc", sizeof(track_name_buf));
3888 else if (st->disposition & AV_DISPOSITION_VISUAL_IMPAIRED)
3889 av_strlcat(track_name_buf, "_ad", sizeof(track_name_buf));
3891 param_write_string(pb, "trackName", track_name_buf);
3893 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
3894 if (track->par->codec_id == AV_CODEC_ID_H264) {
3896 int size = track->par->extradata_size;
3897 if (!ff_avc_write_annexb_extradata(track->par->extradata, &ptr,
3899 param_write_hex(pb, "CodecPrivateData",
3900 ptr ? ptr : track->par->extradata,
3904 param_write_string(pb, "FourCC", "H264");
3905 } else if (track->par->codec_id == AV_CODEC_ID_VC1) {
3906 param_write_string(pb, "FourCC", "WVC1");
3907 param_write_hex(pb, "CodecPrivateData", track->par->extradata,
3908 track->par->extradata_size);
3910 param_write_int(pb, "MaxWidth", track->par->width);
3911 param_write_int(pb, "MaxHeight", track->par->height);
3912 param_write_int(pb, "DisplayWidth", track->par->width);
3913 param_write_int(pb, "DisplayHeight", track->par->height);
3915 if (track->par->codec_id == AV_CODEC_ID_AAC) {
3916 switch (track->par->profile)
3918 case FF_PROFILE_AAC_HE_V2:
3919 param_write_string(pb, "FourCC", "AACP");
3921 case FF_PROFILE_AAC_HE:
3922 param_write_string(pb, "FourCC", "AACH");
3925 param_write_string(pb, "FourCC", "AACL");
3927 } else if (track->par->codec_id == AV_CODEC_ID_WMAPRO) {
3928 param_write_string(pb, "FourCC", "WMAP");
3930 param_write_hex(pb, "CodecPrivateData", track->par->extradata,
3931 track->par->extradata_size);
3932 param_write_int(pb, "AudioTag", ff_codec_get_tag(ff_codec_wav_tags,
3933 track->par->codec_id));
3934 param_write_int(pb, "Channels", track->par->channels);
3935 param_write_int(pb, "SamplingRate", track->par->sample_rate);
3936 param_write_int(pb, "BitsPerSample", 16);
3937 param_write_int(pb, "PacketSize", track->par->block_align ?
3938 track->par->block_align : 4);
3940 avio_printf(pb, "</%s>\n", type);
3942 avio_printf(pb, "</switch>\n");
3943 avio_printf(pb, "</body>\n");
3944 avio_printf(pb, "</smil>\n");
3946 return update_size(pb, pos);
3949 static int mov_write_mfhd_tag(AVIOContext *pb, MOVMuxContext *mov)
3952 ffio_wfourcc(pb, "mfhd");
3954 avio_wb32(pb, mov->fragments);
3958 static uint32_t get_sample_flags(MOVTrack *track, MOVIentry *entry)
3960 return entry->flags & MOV_SYNC_SAMPLE ? MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO :
3961 (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC);
3964 static int mov_write_tfhd_tag(AVIOContext *pb, MOVMuxContext *mov,
3965 MOVTrack *track, int64_t moof_offset)
3967 int64_t pos = avio_tell(pb);
3968 uint32_t flags = MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
3969 MOV_TFHD_BASE_DATA_OFFSET;
3970 if (!track->entry) {
3971 flags |= MOV_TFHD_DURATION_IS_EMPTY;
3973 flags |= MOV_TFHD_DEFAULT_FLAGS;
3975 if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET)
3976 flags &= ~MOV_TFHD_BASE_DATA_OFFSET;
3977 if (mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) {
3978 flags &= ~MOV_TFHD_BASE_DATA_OFFSET;
3979 flags |= MOV_TFHD_DEFAULT_BASE_IS_MOOF;
3982 /* Don't set a default sample size, the silverlight player refuses
3983 * to play files with that set. Don't set a default sample duration,
3984 * WMP freaks out if it is set. Don't set a base data offset, PIFF
3985 * file format says it MUST NOT be set. */
3986 if (track->mode == MODE_ISM)
3987 flags &= ~(MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
3988 MOV_TFHD_BASE_DATA_OFFSET);
3990 avio_wb32(pb, 0); /* size placeholder */
3991 ffio_wfourcc(pb, "tfhd");
3992 avio_w8(pb, 0); /* version */
3993 avio_wb24(pb, flags);
3995 avio_wb32(pb, track->track_id); /* track-id */
3996 if (flags & MOV_TFHD_BASE_DATA_OFFSET)
3997 avio_wb64(pb, moof_offset);
3998 if (flags & MOV_TFHD_DEFAULT_DURATION) {
3999 track->default_duration = get_cluster_duration(track, 0);
4000 avio_wb32(pb, track->default_duration);
4002 if (flags & MOV_TFHD_DEFAULT_SIZE) {
4003 track->default_size = track->entry ? track->cluster[0].size : 1;
4004 avio_wb32(pb, track->default_size);
4006 track->default_size = -1;
4008 if (flags & MOV_TFHD_DEFAULT_FLAGS) {
4009 /* Set the default flags based on the second sample, if available.
4010 * If the first sample is different, that can be signaled via a separate field. */
4011 if (track->entry > 1)
4012 track->default_sample_flags = get_sample_flags(track, &track->cluster[1]);
4014 track->default_sample_flags =
4015 track->par->codec_type == AVMEDIA_TYPE_VIDEO ?
4016 (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC) :
4017 MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO;
4018 avio_wb32(pb, track->default_sample_flags);
4021 return update_size(pb, pos);
4024 static int mov_write_trun_tag(AVIOContext *pb, MOVMuxContext *mov,
4025 MOVTrack *track, int moof_size,
4028 int64_t pos = avio_tell(pb);
4029 uint32_t flags = MOV_TRUN_DATA_OFFSET;
4032 for (i = first; i < end; i++) {
4033 if (get_cluster_duration(track, i) != track->default_duration)
4034 flags |= MOV_TRUN_SAMPLE_DURATION;
4035 if (track->cluster[i].size != track->default_size)
4036 flags |= MOV_TRUN_SAMPLE_SIZE;
4037 if (i > first && get_sample_flags(track, &track->cluster[i]) != track->default_sample_flags)
4038 flags |= MOV_TRUN_SAMPLE_FLAGS;
4040 if (!(flags & MOV_TRUN_SAMPLE_FLAGS) && track->entry > 0 &&
4041 get_sample_flags(track, &track->cluster[0]) != track->default_sample_flags)
4042 flags |= MOV_TRUN_FIRST_SAMPLE_FLAGS;
4043 if (track->flags & MOV_TRACK_CTTS)
4044 flags |= MOV_TRUN_SAMPLE_CTS;
4046 avio_wb32(pb, 0); /* size placeholder */
4047 ffio_wfourcc(pb, "trun");
4048 avio_w8(pb, 0); /* version */
4049 avio_wb24(pb, flags);
4051 avio_wb32(pb, end - first); /* sample count */
4052 if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET &&
4053 !(mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) &&
4055 avio_wb32(pb, 0); /* Later tracks follow immediately after the previous one */
4057 avio_wb32(pb, moof_size + 8 + track->data_offset +
4058 track->cluster[first].pos); /* data offset */
4059 if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS)
4060 avio_wb32(pb, get_sample_flags(track, &track->cluster[first]));
4062 for (i = first; i < end; i++) {
4063 if (flags & MOV_TRUN_SAMPLE_DURATION)
4064 avio_wb32(pb, get_cluster_duration(track, i));
4065 if (flags & MOV_TRUN_SAMPLE_SIZE)
4066 avio_wb32(pb, track->cluster[i].size);
4067 if (flags & MOV_TRUN_SAMPLE_FLAGS)
4068 avio_wb32(pb, get_sample_flags(track, &track->cluster[i]));
4069 if (flags & MOV_TRUN_SAMPLE_CTS)
4070 avio_wb32(pb, track->cluster[i].cts);
4073 mov->first_trun = 0;
4074 return update_size(pb, pos);
4077 static int mov_write_tfxd_tag(AVIOContext *pb, MOVTrack *track)
4079 int64_t pos = avio_tell(pb);
4080 static const uint8_t uuid[] = {
4081 0x6d, 0x1d, 0x9b, 0x05, 0x42, 0xd5, 0x44, 0xe6,
4082 0x80, 0xe2, 0x14, 0x1d, 0xaf, 0xf7, 0x57, 0xb2
4085 avio_wb32(pb, 0); /* size placeholder */
4086 ffio_wfourcc(pb, "uuid");
4087 avio_write(pb, uuid, sizeof(uuid));
4090 avio_wb64(pb, track->start_dts + track->frag_start +
4091 track->cluster[0].cts);
4092 avio_wb64(pb, track->end_pts -
4093 (track->cluster[0].dts + track->cluster[0].cts));
4095 return update_size(pb, pos);
4098 static int mov_write_tfrf_tag(AVIOContext *pb, MOVMuxContext *mov,
4099 MOVTrack *track, int entry)
4101 int n = track->nb_frag_info - 1 - entry, i;
4102 int size = 8 + 16 + 4 + 1 + 16*n;
4103 static const uint8_t uuid[] = {
4104 0xd4, 0x80, 0x7e, 0xf2, 0xca, 0x39, 0x46, 0x95,
4105 0x8e, 0x54, 0x26, 0xcb, 0x9e, 0x46, 0xa7, 0x9f
4111 avio_seek(pb, track->frag_info[entry].tfrf_offset, SEEK_SET);
4112 avio_wb32(pb, size);
4113 ffio_wfourcc(pb, "uuid");
4114 avio_write(pb, uuid, sizeof(uuid));
4118 for (i = 0; i < n; i++) {
4119 int index = entry + 1 + i;
4120 avio_wb64(pb, track->frag_info[index].time);
4121 avio_wb64(pb, track->frag_info[index].duration);
4123 if (n < mov->ism_lookahead) {
4124 int free_size = 16 * (mov->ism_lookahead - n);
4125 avio_wb32(pb, free_size);
4126 ffio_wfourcc(pb, "free");
4127 ffio_fill(pb, 0, free_size - 8);
4133 static int mov_write_tfrf_tags(AVIOContext *pb, MOVMuxContext *mov,
4136 int64_t pos = avio_tell(pb);
4138 for (i = 0; i < mov->ism_lookahead; i++) {
4139 /* Update the tfrf tag for the last ism_lookahead fragments,
4140 * nb_frag_info - 1 is the next fragment to be written. */
4141 mov_write_tfrf_tag(pb, mov, track, track->nb_frag_info - 2 - i);
4143 avio_seek(pb, pos, SEEK_SET);
4147 static int mov_add_tfra_entries(AVIOContext *pb, MOVMuxContext *mov, int tracks,
4151 for (i = 0; i < mov->nb_streams; i++) {
4152 MOVTrack *track = &mov->tracks[i];
4153 MOVFragmentInfo *info;
4154 if ((tracks >= 0 && i != tracks) || !track->entry)
4156 track->nb_frag_info++;
4157 if (track->nb_frag_info >= track->frag_info_capacity) {
4158 unsigned new_capacity = track->nb_frag_info + MOV_FRAG_INFO_ALLOC_INCREMENT;
4159 if (av_reallocp_array(&track->frag_info,
4161 sizeof(*track->frag_info)))
4162 return AVERROR(ENOMEM);
4163 track->frag_info_capacity = new_capacity;
4165 info = &track->frag_info[track->nb_frag_info - 1];
4166 info->offset = avio_tell(pb);
4168 // Try to recreate the original pts for the first packet
4169 // from the fields we have stored
4170 info->time = track->start_dts + track->frag_start +
4171 track->cluster[0].cts;
4172 info->duration = track->end_pts -
4173 (track->cluster[0].dts + track->cluster[0].cts);
4174 // If the pts is less than zero, we will have trimmed
4175 // away parts of the media track using an edit list,
4176 // and the corresponding start presentation time is zero.
4177 if (info->time < 0) {
4178 info->duration += info->time;
4181 info->tfrf_offset = 0;
4182 mov_write_tfrf_tags(pb, mov, track);
4187 static void mov_prune_frag_info(MOVMuxContext *mov, int tracks, int max)
4190 for (i = 0; i < mov->nb_streams; i++) {
4191 MOVTrack *track = &mov->tracks[i];
4192 if ((tracks >= 0 && i != tracks) || !track->entry)
4194 if (track->nb_frag_info > max) {
4195 memmove(track->frag_info, track->frag_info + (track->nb_frag_info - max), max * sizeof(*track->frag_info));
4196 track->nb_frag_info = max;
4201 static int mov_write_tfdt_tag(AVIOContext *pb, MOVTrack *track)
4203 int64_t pos = avio_tell(pb);
4205 avio_wb32(pb, 0); /* size */
4206 ffio_wfourcc(pb, "tfdt");
4207 avio_w8(pb, 1); /* version */
4209 avio_wb64(pb, track->frag_start);
4210 return update_size(pb, pos);
4213 static int mov_write_traf_tag(AVIOContext *pb, MOVMuxContext *mov,
4214 MOVTrack *track, int64_t moof_offset,
4217 int64_t pos = avio_tell(pb);
4219 avio_wb32(pb, 0); /* size placeholder */
4220 ffio_wfourcc(pb, "traf");
4222 mov_write_tfhd_tag(pb, mov, track, moof_offset);
4223 if (mov->mode != MODE_ISM)
4224 mov_write_tfdt_tag(pb, track);
4225 for (i = 1; i < track->entry; i++) {
4226 if (track->cluster[i].pos != track->cluster[i - 1].pos + track->cluster[i - 1].size) {
4227 mov_write_trun_tag(pb, mov, track, moof_size, start, i);
4231 mov_write_trun_tag(pb, mov, track, moof_size, start, track->entry);
4232 if (mov->mode == MODE_ISM) {
4233 mov_write_tfxd_tag(pb, track);
4235 if (mov->ism_lookahead) {
4236 int i, size = 16 + 4 + 1 + 16 * mov->ism_lookahead;
4238 if (track->nb_frag_info > 0) {
4239 MOVFragmentInfo *info = &track->frag_info[track->nb_frag_info - 1];
4240 if (!info->tfrf_offset)
4241 info->tfrf_offset = avio_tell(pb);
4243 avio_wb32(pb, 8 + size);
4244 ffio_wfourcc(pb, "free");
4245 for (i = 0; i < size; i++)
4250 return update_size(pb, pos);
4253 static int mov_write_moof_tag_internal(AVIOContext *pb, MOVMuxContext *mov,
4254 int tracks, int moof_size)
4256 int64_t pos = avio_tell(pb);
4259 avio_wb32(pb, 0); /* size placeholder */
4260 ffio_wfourcc(pb, "moof");
4261 mov->first_trun = 1;
4263 mov_write_mfhd_tag(pb, mov);
4264 for (i = 0; i < mov->nb_streams; i++) {
4265 MOVTrack *track = &mov->tracks[i];
4266 if (tracks >= 0 && i != tracks)
4270 mov_write_traf_tag(pb, mov, track, pos, moof_size);
4273 return update_size(pb, pos);
4276 static int mov_write_sidx_tag(AVIOContext *pb,
4277 MOVTrack *track, int ref_size, int total_sidx_size)
4279 int64_t pos = avio_tell(pb), offset_pos, end_pos;
4280 int64_t presentation_time, duration, offset;
4281 int starts_with_SAP, i, entries;
4285 presentation_time = track->start_dts + track->frag_start +
4286 track->cluster[0].cts;
4287 duration = track->end_pts -
4288 (track->cluster[0].dts + track->cluster[0].cts);
4289 starts_with_SAP = track->cluster[0].flags & MOV_SYNC_SAMPLE;
4291 // pts<0 should be cut away using edts
4292 if (presentation_time < 0) {
4293 duration += presentation_time;
4294 presentation_time = 0;
4297 entries = track->nb_frag_info;
4300 presentation_time = track->frag_info[0].time;
4303 avio_wb32(pb, 0); /* size */
4304 ffio_wfourcc(pb, "sidx");
4305 avio_w8(pb, 1); /* version */
4307 avio_wb32(pb, track->track_id); /* reference_ID */
4308 avio_wb32(pb, track->timescale); /* timescale */
4309 avio_wb64(pb, presentation_time); /* earliest_presentation_time */
4310 offset_pos = avio_tell(pb);
4311 avio_wb64(pb, 0); /* first_offset (offset to referenced moof) */
4312 avio_wb16(pb, 0); /* reserved */
4314 avio_wb16(pb, entries); /* reference_count */
4315 for (i = 0; i < entries; i++) {
4316 if (!track->entry) {
4317 if (i > 1 && track->frag_info[i].offset != track->frag_info[i - 1].offset + track->frag_info[i - 1].size) {
4318 av_log(NULL, AV_LOG_ERROR, "Non-consecutive fragments, writing incorrect sidx\n");
4320 duration = track->frag_info[i].duration;
4321 ref_size = track->frag_info[i].size;
4322 starts_with_SAP = 1;
4324 avio_wb32(pb, (0 << 31) | (ref_size & 0x7fffffff)); /* reference_type (0 = media) | referenced_size */
4325 avio_wb32(pb, duration); /* subsegment_duration */
4326 avio_wb32(pb, (starts_with_SAP << 31) | (0 << 28) | 0); /* starts_with_SAP | SAP_type | SAP_delta_time */
4329 end_pos = avio_tell(pb);
4330 offset = pos + total_sidx_size - end_pos;
4331 avio_seek(pb, offset_pos, SEEK_SET);
4332 avio_wb64(pb, offset);
4333 avio_seek(pb, end_pos, SEEK_SET);
4334 return update_size(pb, pos);
4337 static int mov_write_sidx_tags(AVIOContext *pb, MOVMuxContext *mov,
4338 int tracks, int ref_size)
4341 AVIOContext *avio_buf;
4343 for (round = 0; round < 2; round++) {
4344 // First run one round to calculate the total size of all
4346 // This would be much simpler if we'd only write one sidx
4347 // atom, for the first track in the moof.
4349 if ((ret = ffio_open_null_buf(&avio_buf)) < 0)
4354 for (i = 0; i < mov->nb_streams; i++) {
4355 MOVTrack *track = &mov->tracks[i];
4356 if (tracks >= 0 && i != tracks)
4358 // When writing a sidx for the full file, entry is 0, but
4359 // we want to include all tracks. ref_size is 0 in this case,
4360 // since we read it from frag_info instead.
4361 if (!track->entry && ref_size > 0)
4363 total_size -= mov_write_sidx_tag(avio_buf, track, ref_size,
4367 total_size = ffio_close_null_buf(avio_buf);
4372 static int mov_write_moof_tag(AVIOContext *pb, MOVMuxContext *mov, int tracks,
4375 AVIOContext *avio_buf;
4378 if ((ret = ffio_open_null_buf(&avio_buf)) < 0)
4380 mov_write_moof_tag_internal(avio_buf, mov, tracks, 0);
4381 moof_size = ffio_close_null_buf(avio_buf);
4383 if (mov->flags & FF_MOV_FLAG_DASH && !(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX))
4384 mov_write_sidx_tags(pb, mov, tracks, moof_size + 8 + mdat_size);
4386 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX ||
4387 !(mov->flags & FF_MOV_FLAG_SKIP_TRAILER) ||
4388 mov->ism_lookahead) {
4389 if ((ret = mov_add_tfra_entries(pb, mov, tracks, moof_size + 8 + mdat_size)) < 0)
4391 if (!(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) &&
4392 mov->flags & FF_MOV_FLAG_SKIP_TRAILER) {
4393 mov_prune_frag_info(mov, tracks, mov->ism_lookahead + 1);
4397 return mov_write_moof_tag_internal(pb, mov, tracks, moof_size);
4400 static int mov_write_tfra_tag(AVIOContext *pb, MOVTrack *track)
4402 int64_t pos = avio_tell(pb);
4405 avio_wb32(pb, 0); /* size placeholder */
4406 ffio_wfourcc(pb, "tfra");
4407 avio_w8(pb, 1); /* version */
4410 avio_wb32(pb, track->track_id);
4411 avio_wb32(pb, 0); /* length of traf/trun/sample num */
4412 avio_wb32(pb, track->nb_frag_info);
4413 for (i = 0; i < track->nb_frag_info; i++) {
4414 avio_wb64(pb, track->frag_info[i].time);
4415 avio_wb64(pb, track->frag_info[i].offset + track->data_offset);
4416 avio_w8(pb, 1); /* traf number */
4417 avio_w8(pb, 1); /* trun number */
4418 avio_w8(pb, 1); /* sample number */
4421 return update_size(pb, pos);
4424 static int mov_write_mfra_tag(AVIOContext *pb, MOVMuxContext *mov)
4426 int64_t pos = avio_tell(pb);
4429 avio_wb32(pb, 0); /* size placeholder */
4430 ffio_wfourcc(pb, "mfra");
4431 /* An empty mfra atom is enough to indicate to the publishing point that
4432 * the stream has ended. */
4433 if (mov->flags & FF_MOV_FLAG_ISML)
4434 return update_size(pb, pos);
4436 for (i = 0; i < mov->nb_streams; i++) {
4437 MOVTrack *track = &mov->tracks[i];
4438 if (track->nb_frag_info)
4439 mov_write_tfra_tag(pb, track);
4443 ffio_wfourcc(pb, "mfro");
4444 avio_wb32(pb, 0); /* version + flags */
4445 avio_wb32(pb, avio_tell(pb) + 4 - pos);
4447 return update_size(pb, pos);
4450 static int mov_write_mdat_tag(AVIOContext *pb, MOVMuxContext *mov)
4452 avio_wb32(pb, 8); // placeholder for extended size field (64 bit)
4453 ffio_wfourcc(pb, mov->mode == MODE_MOV ? "wide" : "free");
4455 mov->mdat_pos = avio_tell(pb);
4456 avio_wb32(pb, 0); /* size placeholder*/
4457 ffio_wfourcc(pb, "mdat");
4461 /* TODO: This needs to be more general */
4462 static int mov_write_ftyp_tag(AVIOContext *pb, AVFormatContext *s)
4464 MOVMuxContext *mov = s->priv_data;
4465 int64_t pos = avio_tell(pb);
4466 int has_h264 = 0, has_video = 0;
4470 for (i = 0; i < s->nb_streams; i++) {
4471 AVStream *st = s->streams[i];
4472 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
4474 if (st->codecpar->codec_id == AV_CODEC_ID_H264)
4478 avio_wb32(pb, 0); /* size */
4479 ffio_wfourcc(pb, "ftyp");
4481 if (mov->major_brand && strlen(mov->major_brand) >= 4)
4482 ffio_wfourcc(pb, mov->major_brand);
4483 else if (mov->mode == MODE_3GP) {
4484 ffio_wfourcc(pb, has_h264 ? "3gp6" : "3gp4");
4485 minor = has_h264 ? 0x100 : 0x200;
4486 } else if (mov->mode & MODE_3G2) {
4487 ffio_wfourcc(pb, has_h264 ? "3g2b" : "3g2a");
4488 minor = has_h264 ? 0x20000 : 0x10000;
4489 } else if (mov->mode == MODE_PSP)
4490 ffio_wfourcc(pb, "MSNV");
4491 else if (mov->mode == MODE_MP4 && mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)
4492 ffio_wfourcc(pb, "iso5"); // Required when using default-base-is-moof
4493 else if (mov->mode == MODE_MP4)
4494 ffio_wfourcc(pb, "isom");
4495 else if (mov->mode == MODE_IPOD)
4496 ffio_wfourcc(pb, has_video ? "M4V ":"M4A ");
4497 else if (mov->mode == MODE_ISM)
4498 ffio_wfourcc(pb, "isml");
4499 else if (mov->mode == MODE_F4V)
4500 ffio_wfourcc(pb, "f4v ");
4502 ffio_wfourcc(pb, "qt ");
4504 avio_wb32(pb, minor);
4506 if (mov->mode == MODE_MOV)
4507 ffio_wfourcc(pb, "qt ");
4508 else if (mov->mode == MODE_ISM) {
4509 ffio_wfourcc(pb, "piff");
4510 } else if (!(mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)) {
4511 ffio_wfourcc(pb, "isom");
4512 ffio_wfourcc(pb, "iso2");
4514 ffio_wfourcc(pb, "avc1");
4517 // We add tfdt atoms when fragmenting, signal this with the iso6 compatible
4518 // brand. This is compatible with users that don't understand tfdt.
4519 if (mov->flags & FF_MOV_FLAG_FRAGMENT && mov->mode != MODE_ISM)
4520 ffio_wfourcc(pb, "iso6");
4522 if (mov->mode == MODE_3GP)
4523 ffio_wfourcc(pb, has_h264 ? "3gp6":"3gp4");
4524 else if (mov->mode & MODE_3G2)
4525 ffio_wfourcc(pb, has_h264 ? "3g2b":"3g2a");
4526 else if (mov->mode == MODE_PSP)
4527 ffio_wfourcc(pb, "MSNV");
4528 else if (mov->mode == MODE_MP4)
4529 ffio_wfourcc(pb, "mp41");
4531 if (mov->flags & FF_MOV_FLAG_DASH && mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
4532 ffio_wfourcc(pb, "dash");
4534 return update_size(pb, pos);
4537 static int mov_write_uuidprof_tag(AVIOContext *pb, AVFormatContext *s)
4539 AVStream *video_st = s->streams[0];
4540 AVCodecParameters *video_par = s->streams[0]->codecpar;
4541 AVCodecParameters *audio_par = s->streams[1]->codecpar;
4542 int audio_rate = audio_par->sample_rate;
4543 int64_t frame_rate = video_st->avg_frame_rate.den ?
4544 (video_st->avg_frame_rate.num * 0x10000LL) / video_st->avg_frame_rate.den :
4546 int audio_kbitrate = audio_par->bit_rate / 1000;
4547 int video_kbitrate = FFMIN(video_par->bit_rate / 1000, 800 - audio_kbitrate);
4549 if (frame_rate < 0 || frame_rate > INT32_MAX) {
4550 av_log(s, AV_LOG_ERROR, "Frame rate %f outside supported range\n", frame_rate / (double)0x10000);
4551 return AVERROR(EINVAL);
4554 avio_wb32(pb, 0x94); /* size */
4555 ffio_wfourcc(pb, "uuid");
4556 ffio_wfourcc(pb, "PROF");
4558 avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
4559 avio_wb32(pb, 0xbb88695c);
4560 avio_wb32(pb, 0xfac9c740);
4562 avio_wb32(pb, 0x0); /* ? */
4563 avio_wb32(pb, 0x3); /* 3 sections ? */
4565 avio_wb32(pb, 0x14); /* size */
4566 ffio_wfourcc(pb, "FPRF");
4567 avio_wb32(pb, 0x0); /* ? */
4568 avio_wb32(pb, 0x0); /* ? */
4569 avio_wb32(pb, 0x0); /* ? */
4571 avio_wb32(pb, 0x2c); /* size */
4572 ffio_wfourcc(pb, "APRF"); /* audio */
4574 avio_wb32(pb, 0x2); /* TrackID */
4575 ffio_wfourcc(pb, "mp4a");
4576 avio_wb32(pb, 0x20f);
4578 avio_wb32(pb, audio_kbitrate);
4579 avio_wb32(pb, audio_kbitrate);
4580 avio_wb32(pb, audio_rate);
4581 avio_wb32(pb, audio_par->channels);
4583 avio_wb32(pb, 0x34); /* size */
4584 ffio_wfourcc(pb, "VPRF"); /* video */
4586 avio_wb32(pb, 0x1); /* TrackID */
4587 if (video_par->codec_id == AV_CODEC_ID_H264) {
4588 ffio_wfourcc(pb, "avc1");
4589 avio_wb16(pb, 0x014D);
4590 avio_wb16(pb, 0x0015);
4592 ffio_wfourcc(pb, "mp4v");
4593 avio_wb16(pb, 0x0000);
4594 avio_wb16(pb, 0x0103);
4597 avio_wb32(pb, video_kbitrate);
4598 avio_wb32(pb, video_kbitrate);
4599 avio_wb32(pb, frame_rate);
4600 avio_wb32(pb, frame_rate);
4601 avio_wb16(pb, video_par->width);
4602 avio_wb16(pb, video_par->height);
4603 avio_wb32(pb, 0x010001); /* ? */
4608 static int mov_write_identification(AVIOContext *pb, AVFormatContext *s)
4610 MOVMuxContext *mov = s->priv_data;
4613 mov_write_ftyp_tag(pb,s);
4614 if (mov->mode == MODE_PSP) {
4615 int video_streams_nb = 0, audio_streams_nb = 0, other_streams_nb = 0;
4616 for (i = 0; i < s->nb_streams; i++) {
4617 AVStream *st = s->streams[i];
4618 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
4620 else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
4626 if (video_streams_nb != 1 || audio_streams_nb != 1 || other_streams_nb) {
4627 av_log(s, AV_LOG_ERROR, "PSP mode need one video and one audio stream\n");
4628 return AVERROR(EINVAL);
4630 return mov_write_uuidprof_tag(pb, s);
4635 static int mov_parse_mpeg2_frame(AVPacket *pkt, uint32_t *flags)
4638 int i, closed_gop = 0;
4640 for (i = 0; i < pkt->size - 4; i++) {
4641 c = (c << 8) + pkt->data[i];
4642 if (c == 0x1b8) { // gop
4643 closed_gop = pkt->data[i + 4] >> 6 & 0x01;
4644 } else if (c == 0x100) { // pic
4645 int temp_ref = (pkt->data[i + 1] << 2) | (pkt->data[i + 2] >> 6);
4646 if (!temp_ref || closed_gop) // I picture is not reordered
4647 *flags = MOV_SYNC_SAMPLE;
4649 *flags = MOV_PARTIAL_SYNC_SAMPLE;
4656 static void mov_parse_vc1_frame(AVPacket *pkt, MOVTrack *trk)
4658 const uint8_t *start, *next, *end = pkt->data + pkt->size;
4659 int seq = 0, entry = 0;
4660 int key = pkt->flags & AV_PKT_FLAG_KEY;
4661 start = find_next_marker(pkt->data, end);
4662 for (next = start; next < end; start = next) {
4663 next = find_next_marker(start + 4, end);
4664 switch (AV_RB32(start)) {
4665 case VC1_CODE_SEQHDR:
4668 case VC1_CODE_ENTRYPOINT:
4671 case VC1_CODE_SLICE:
4672 trk->vc1_info.slices = 1;
4676 if (!trk->entry && trk->vc1_info.first_packet_seen)
4677 trk->vc1_info.first_frag_written = 1;
4678 if (!trk->entry && !trk->vc1_info.first_frag_written) {
4679 /* First packet in first fragment */
4680 trk->vc1_info.first_packet_seq = seq;
4681 trk->vc1_info.first_packet_entry = entry;
4682 trk->vc1_info.first_packet_seen = 1;
4683 } else if ((seq && !trk->vc1_info.packet_seq) ||
4684 (entry && !trk->vc1_info.packet_entry)) {
4686 for (i = 0; i < trk->entry; i++)
4687 trk->cluster[i].flags &= ~MOV_SYNC_SAMPLE;
4688 trk->has_keyframes = 0;
4690 trk->vc1_info.packet_seq = 1;
4692 trk->vc1_info.packet_entry = 1;
4693 if (!trk->vc1_info.first_frag_written) {
4694 /* First fragment */
4695 if ((!seq || trk->vc1_info.first_packet_seq) &&
4696 (!entry || trk->vc1_info.first_packet_entry)) {
4697 /* First packet had the same headers as this one, readd the
4698 * sync sample flag. */
4699 trk->cluster[0].flags |= MOV_SYNC_SAMPLE;
4700 trk->has_keyframes = 1;
4704 if (trk->vc1_info.packet_seq && trk->vc1_info.packet_entry)
4706 else if (trk->vc1_info.packet_seq)
4708 else if (trk->vc1_info.packet_entry)
4711 trk->cluster[trk->entry].flags |= MOV_SYNC_SAMPLE;
4712 trk->has_keyframes++;
4716 static int mov_flush_fragment_interleaving(AVFormatContext *s, MOVTrack *track)
4718 MOVMuxContext *mov = s->priv_data;
4723 if (!track->mdat_buf)
4725 if (!mov->mdat_buf) {
4726 if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0)
4729 buf_size = avio_close_dyn_buf(track->mdat_buf, &buf);
4730 track->mdat_buf = NULL;
4732 offset = avio_tell(mov->mdat_buf);
4733 avio_write(mov->mdat_buf, buf, buf_size);
4736 for (i = track->entries_flushed; i < track->entry; i++)
4737 track->cluster[i].pos += offset;
4738 track->entries_flushed = track->entry;
4742 static int mov_flush_fragment(AVFormatContext *s, int force)
4744 MOVMuxContext *mov = s->priv_data;
4745 int i, first_track = -1;
4746 int64_t mdat_size = 0;
4748 int has_video = 0, starts_with_key = 0, first_video_track = 1;
4750 if (!(mov->flags & FF_MOV_FLAG_FRAGMENT))
4753 // Try to fill in the duration of the last packet in each stream
4754 // from queued packets in the interleave queues. If the flushing
4755 // of fragments was triggered automatically by an AVPacket, we
4756 // already have reliable info for the end of that track, but other
4757 // tracks may need to be filled in.
4758 for (i = 0; i < s->nb_streams; i++) {
4759 MOVTrack *track = &mov->tracks[i];
4760 if (!track->end_reliable) {
4762 if (!ff_interleaved_peek(s, i, &pkt, 1)) {
4763 track->track_duration = pkt.dts - track->start_dts;
4764 if (pkt.pts != AV_NOPTS_VALUE)
4765 track->end_pts = pkt.pts;
4767 track->end_pts = pkt.dts;
4772 for (i = 0; i < mov->nb_streams; i++) {
4773 MOVTrack *track = &mov->tracks[i];
4774 if (track->entry <= 1)
4776 // Sample durations are calculated as the diff of dts values,
4777 // but for the last sample in a fragment, we don't know the dts
4778 // of the first sample in the next fragment, so we have to rely
4779 // on what was set as duration in the AVPacket. Not all callers
4780 // set this though, so we might want to replace it with an
4781 // estimate if it currently is zero.
4782 if (get_cluster_duration(track, track->entry - 1) != 0)
4784 // Use the duration (i.e. dts diff) of the second last sample for
4785 // the last one. This is a wild guess (and fatal if it turns out
4786 // to be too long), but probably the best we can do - having a zero
4787 // duration is bad as well.
4788 track->track_duration += get_cluster_duration(track, track->entry - 2);
4789 track->end_pts += get_cluster_duration(track, track->entry - 2);
4790 if (!mov->missing_duration_warned) {
4791 av_log(s, AV_LOG_WARNING,
4792 "Estimating the duration of the last packet in a "
4793 "fragment, consider setting the duration field in "
4794 "AVPacket instead.\n");
4795 mov->missing_duration_warned = 1;
4799 if (!mov->moov_written) {
4800 int64_t pos = avio_tell(s->pb);
4802 int buf_size, moov_size;
4804 for (i = 0; i < mov->nb_streams; i++)
4805 if (!mov->tracks[i].entry)
4807 /* Don't write the initial moov unless all tracks have data */
4808 if (i < mov->nb_streams && !force)
4811 moov_size = get_moov_size(s);
4812 for (i = 0; i < mov->nb_streams; i++)
4813 mov->tracks[i].data_offset = pos + moov_size + 8;
4815 avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_HEADER);
4816 if (mov->flags & FF_MOV_FLAG_DELAY_MOOV)
4817 mov_write_identification(s->pb, s);
4818 if ((ret = mov_write_moov_tag(s->pb, mov, s)) < 0)
4821 if (mov->flags & FF_MOV_FLAG_DELAY_MOOV) {
4822 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
4823 mov->reserved_header_pos = avio_tell(s->pb);
4825 mov->moov_written = 1;
4829 buf_size = avio_close_dyn_buf(mov->mdat_buf, &buf);
4830 mov->mdat_buf = NULL;
4831 avio_wb32(s->pb, buf_size + 8);
4832 ffio_wfourcc(s->pb, "mdat");
4833 avio_write(s->pb, buf, buf_size);
4836 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
4837 mov->reserved_header_pos = avio_tell(s->pb);
4839 mov->moov_written = 1;
4841 for (i = 0; i < mov->nb_streams; i++) {
4842 if (mov->tracks[i].entry)
4843 mov->tracks[i].frag_start += mov->tracks[i].start_dts +
4844 mov->tracks[i].track_duration -
4845 mov->tracks[i].cluster[0].dts;
4846 mov->tracks[i].entry = 0;
4847 mov->tracks[i].end_reliable = 0;
4853 if (mov->frag_interleave) {
4854 for (i = 0; i < mov->nb_streams; i++) {
4855 MOVTrack *track = &mov->tracks[i];
4857 if ((ret = mov_flush_fragment_interleaving(s, track)) < 0)
4863 mdat_size = avio_tell(mov->mdat_buf);
4866 for (i = 0; i < mov->nb_streams; i++) {
4867 MOVTrack *track = &mov->tracks[i];
4868 if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF || mov->frag_interleave)
4869 track->data_offset = 0;
4871 track->data_offset = mdat_size;
4872 if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
4874 if (first_video_track) {
4876 starts_with_key = track->cluster[0].flags & MOV_SYNC_SAMPLE;
4877 first_video_track = 0;
4882 if (track->mdat_buf)
4883 mdat_size += avio_tell(track->mdat_buf);
4884 if (first_track < 0)
4891 avio_write_marker(s->pb,
4892 av_rescale(mov->tracks[first_track].cluster[0].dts, AV_TIME_BASE, mov->tracks[first_track].timescale),
4893 (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);
4895 for (i = 0; i < mov->nb_streams; i++) {
4896 MOVTrack *track = &mov->tracks[i];
4897 int buf_size, write_moof = 1, moof_tracks = -1;
4899 int64_t duration = 0;
4902 duration = track->start_dts + track->track_duration -
4903 track->cluster[0].dts;
4904 if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF) {
4905 if (!track->mdat_buf)
4907 mdat_size = avio_tell(track->mdat_buf);
4910 write_moof = i == first_track;
4916 mov_write_moof_tag(s->pb, mov, moof_tracks, mdat_size);
4919 avio_wb32(s->pb, mdat_size + 8);
4920 ffio_wfourcc(s->pb, "mdat");
4924 track->frag_start += duration;
4926 track->entries_flushed = 0;
4927 track->end_reliable = 0;
4928 if (!mov->frag_interleave) {
4929 if (!track->mdat_buf)
4931 buf_size = avio_close_dyn_buf(track->mdat_buf, &buf);
4932 track->mdat_buf = NULL;
4936 buf_size = avio_close_dyn_buf(mov->mdat_buf, &buf);
4937 mov->mdat_buf = NULL;
4940 avio_write(s->pb, buf, buf_size);
4950 static int mov_auto_flush_fragment(AVFormatContext *s, int force)
4952 MOVMuxContext *mov = s->priv_data;
4953 int had_moov = mov->moov_written;
4954 int ret = mov_flush_fragment(s, force);
4957 // If using delay_moov, the first flush only wrote the moov,
4958 // not the actual moof+mdat pair, thus flush once again.
4959 if (!had_moov && mov->flags & FF_MOV_FLAG_DELAY_MOOV)
4960 ret = mov_flush_fragment(s, force);
4964 static int check_pkt(AVFormatContext *s, AVPacket *pkt)
4966 MOVMuxContext *mov = s->priv_data;
4967 MOVTrack *trk = &mov->tracks[pkt->stream_index];
4972 ref = trk->cluster[trk->entry - 1].dts;
4973 } else if ( trk->start_dts != AV_NOPTS_VALUE
4974 && !trk->frag_discont) {
4975 ref = trk->start_dts + trk->track_duration;
4977 ref = pkt->dts; // Skip tests for the first packet
4979 duration = pkt->dts - ref;
4980 if (pkt->dts < ref || duration >= INT_MAX) {
4981 av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" / timestamp: %"PRId64" is out of range for mov/mp4 format\n",
4986 pkt->pts = AV_NOPTS_VALUE;
4989 if (pkt->duration < 0 || pkt->duration > INT_MAX) {
4990 av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" is invalid\n", pkt->duration);
4991 return AVERROR(EINVAL);
4996 int ff_mov_write_packet(AVFormatContext *s, AVPacket *pkt)
4998 MOVMuxContext *mov = s->priv_data;
4999 AVIOContext *pb = s->pb;
5000 MOVTrack *trk = &mov->tracks[pkt->stream_index];
5001 AVCodecParameters *par = trk->par;
5002 unsigned int samples_in_chunk = 0;
5003 int size = pkt->size, ret = 0;
5004 uint8_t *reformatted_data = NULL;
5006 ret = check_pkt(s, pkt);
5010 if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
5012 if (mov->moov_written || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
5013 if (mov->frag_interleave && mov->fragments > 0) {
5014 if (trk->entry - trk->entries_flushed >= mov->frag_interleave) {
5015 if ((ret = mov_flush_fragment_interleaving(s, trk)) < 0)
5020 if (!trk->mdat_buf) {
5021 if ((ret = avio_open_dyn_buf(&trk->mdat_buf)) < 0)
5026 if (!mov->mdat_buf) {
5027 if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0)
5034 if (par->codec_id == AV_CODEC_ID_AMR_NB) {
5035 /* We must find out how many AMR blocks there are in one packet */
5036 static const uint16_t packed_size[16] =
5037 {13, 14, 16, 18, 20, 21, 27, 32, 6, 0, 0, 0, 0, 0, 0, 1};
5040 while (len < size && samples_in_chunk < 100) {
5041 len += packed_size[(pkt->data[len] >> 3) & 0x0F];
5044 if (samples_in_chunk > 1) {
5045 av_log(s, AV_LOG_ERROR, "fatal error, input is not a single packet, implement a AVParser for it\n");
5048 } else if (par->codec_id == AV_CODEC_ID_ADPCM_MS ||
5049 par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) {
5050 samples_in_chunk = trk->par->frame_size;
5051 } else if (trk->sample_size)
5052 samples_in_chunk = size / trk->sample_size;
5054 samples_in_chunk = 1;
5056 /* copy extradata if it exists */
5057 if (trk->vos_len == 0 && par->extradata_size > 0 &&
5058 !TAG_IS_AVCI(trk->tag) &&
5059 (par->codec_id != AV_CODEC_ID_DNXHD)) {
5060 trk->vos_len = par->extradata_size;
5061 trk->vos_data = av_malloc(trk->vos_len);
5062 if (!trk->vos_data) {
5063 ret = AVERROR(ENOMEM);
5066 memcpy(trk->vos_data, par->extradata, trk->vos_len);
5069 if (par->codec_id == AV_CODEC_ID_AAC && pkt->size > 2 &&
5070 (AV_RB16(pkt->data) & 0xfff0) == 0xfff0) {
5071 if (!s->streams[pkt->stream_index]->nb_frames) {
5072 av_log(s, AV_LOG_ERROR, "Malformed AAC bitstream detected: "
5073 "use the audio bitstream filter 'aac_adtstoasc' to fix it "
5074 "('-bsf:a aac_adtstoasc' option with ffmpeg)\n");
5077 av_log(s, AV_LOG_WARNING, "aac bitstream error\n");
5079 if (par->codec_id == AV_CODEC_ID_H264 && trk->vos_len > 0 && *(uint8_t *)trk->vos_data != 1 && !TAG_IS_AVCI(trk->tag)) {
5080 /* from x264 or from bytestream H.264 */
5081 /* NAL reformatting needed */
5082 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
5083 ff_avc_parse_nal_units_buf(pkt->data, &reformatted_data,
5085 avio_write(pb, reformatted_data, size);
5087 if (trk->cenc.aes_ctr) {
5088 size = ff_mov_cenc_avc_parse_nal_units(&trk->cenc, pb, pkt->data, size);
5094 size = ff_avc_parse_nal_units(pb, pkt->data, pkt->size);
5097 } else if (par->codec_id == AV_CODEC_ID_HEVC && trk->vos_len > 6 &&
5098 (AV_RB24(trk->vos_data) == 1 || AV_RB32(trk->vos_data) == 1)) {
5099 /* extradata is Annex B, assume the bitstream is too and convert it */
5100 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
5101 ff_hevc_annexb2mp4_buf(pkt->data, &reformatted_data, &size, 0, NULL);
5102 avio_write(pb, reformatted_data, size);
5104 size = ff_hevc_annexb2mp4(pb, pkt->data, pkt->size, 0, NULL);
5106 #if CONFIG_AC3_PARSER
5107 } else if (par->codec_id == AV_CODEC_ID_EAC3) {
5108 size = handle_eac3(mov, pkt, trk);
5113 avio_write(pb, pkt->data, size);
5116 if (trk->cenc.aes_ctr) {
5117 if (par->codec_id == AV_CODEC_ID_H264 && par->extradata_size > 4) {
5118 int nal_size_length = (par->extradata[4] & 0x3) + 1;
5119 ret = ff_mov_cenc_avc_write_nal_units(s, &trk->cenc, nal_size_length, pb, pkt->data, size);
5121 ret = ff_mov_cenc_write_packet(&trk->cenc, pb, pkt->data, size);
5128 avio_write(pb, pkt->data, size);
5132 if ((par->codec_id == AV_CODEC_ID_DNXHD ||
5133 par->codec_id == AV_CODEC_ID_AC3) && !trk->vos_len) {
5134 /* copy frame to create needed atoms */
5135 trk->vos_len = size;
5136 trk->vos_data = av_malloc(size);
5137 if (!trk->vos_data) {
5138 ret = AVERROR(ENOMEM);
5141 memcpy(trk->vos_data, pkt->data, size);
5144 if (trk->entry >= trk->cluster_capacity) {
5145 unsigned new_capacity = 2 * (trk->entry + MOV_INDEX_CLUSTER_SIZE);
5146 if (av_reallocp_array(&trk->cluster, new_capacity,
5147 sizeof(*trk->cluster))) {
5148 ret = AVERROR(ENOMEM);
5151 trk->cluster_capacity = new_capacity;
5154 trk->cluster[trk->entry].pos = avio_tell(pb) - size;
5155 trk->cluster[trk->entry].samples_in_chunk = samples_in_chunk;
5156 trk->cluster[trk->entry].chunkNum = 0;
5157 trk->cluster[trk->entry].size = size;
5158 trk->cluster[trk->entry].entries = samples_in_chunk;
5159 trk->cluster[trk->entry].dts = pkt->dts;
5160 if (!trk->entry && trk->start_dts != AV_NOPTS_VALUE) {
5161 if (!trk->frag_discont) {
5162 /* First packet of a new fragment. We already wrote the duration
5163 * of the last packet of the previous fragment based on track_duration,
5164 * which might not exactly match our dts. Therefore adjust the dts
5165 * of this packet to be what the previous packets duration implies. */
5166 trk->cluster[trk->entry].dts = trk->start_dts + trk->track_duration;
5167 /* We also may have written the pts and the corresponding duration
5168 * in sidx/tfrf/tfxd tags; make sure the sidx pts and duration match up with
5169 * the next fragment. This means the cts of the first sample must
5170 * be the same in all fragments, unless end_pts was updated by
5171 * the packet causing the fragment to be written. */
5172 if ((mov->flags & FF_MOV_FLAG_DASH && !(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)) ||
5173 mov->mode == MODE_ISM)
5174 pkt->pts = pkt->dts + trk->end_pts - trk->cluster[trk->entry].dts;
5176 /* New fragment, but discontinuous from previous fragments.
5177 * Pretend the duration sum of the earlier fragments is
5178 * pkt->dts - trk->start_dts. */
5179 trk->frag_start = pkt->dts - trk->start_dts;
5180 trk->end_pts = AV_NOPTS_VALUE;
5181 trk->frag_discont = 0;
5185 if (!trk->entry && trk->start_dts == AV_NOPTS_VALUE && !mov->use_editlist &&
5186 s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO) {
5187 /* Not using edit lists and shifting the first track to start from zero.
5188 * If the other streams start from a later timestamp, we won't be able
5189 * to signal the difference in starting time without an edit list.
5190 * Thus move the timestamp for this first sample to 0, increasing
5191 * its duration instead. */
5192 trk->cluster[trk->entry].dts = trk->start_dts = 0;
5194 if (trk->start_dts == AV_NOPTS_VALUE) {
5195 trk->start_dts = pkt->dts;
5196 if (trk->frag_discont) {
5197 if (mov->use_editlist) {
5198 /* Pretend the whole stream started at pts=0, with earlier fragments
5199 * already written. If the stream started at pts=0, the duration sum
5200 * of earlier fragments would have been pkt->pts. */
5201 trk->frag_start = pkt->pts;
5202 trk->start_dts = pkt->dts - pkt->pts;
5204 /* Pretend the whole stream started at dts=0, with earlier fragments
5205 * already written, with a duration summing up to pkt->dts. */
5206 trk->frag_start = pkt->dts;
5209 trk->frag_discont = 0;
5210 } else if (pkt->dts && mov->moov_written)
5211 av_log(s, AV_LOG_WARNING,
5212 "Track %d starts with a nonzero dts %"PRId64", while the moov "
5213 "already has been written. Set the delay_moov flag to handle "
5215 pkt->stream_index, pkt->dts);
5217 trk->track_duration = pkt->dts - trk->start_dts + pkt->duration;
5218 trk->last_sample_is_subtitle_end = 0;
5220 if (pkt->pts == AV_NOPTS_VALUE) {
5221 av_log(s, AV_LOG_WARNING, "pts has no value\n");
5222 pkt->pts = pkt->dts;
5224 if (pkt->dts != pkt->pts)
5225 trk->flags |= MOV_TRACK_CTTS;
5226 trk->cluster[trk->entry].cts = pkt->pts - pkt->dts;
5227 trk->cluster[trk->entry].flags = 0;
5228 if (trk->start_cts == AV_NOPTS_VALUE)
5229 trk->start_cts = pkt->pts - pkt->dts;
5230 if (trk->end_pts == AV_NOPTS_VALUE)
5231 trk->end_pts = trk->cluster[trk->entry].dts +
5232 trk->cluster[trk->entry].cts + pkt->duration;
5234 trk->end_pts = FFMAX(trk->end_pts, trk->cluster[trk->entry].dts +
5235 trk->cluster[trk->entry].cts +
5238 if (par->codec_id == AV_CODEC_ID_VC1) {
5239 mov_parse_vc1_frame(pkt, trk);
5240 } else if (pkt->flags & AV_PKT_FLAG_KEY) {
5241 if (mov->mode == MODE_MOV && par->codec_id == AV_CODEC_ID_MPEG2VIDEO &&
5242 trk->entry > 0) { // force sync sample for the first key frame
5243 mov_parse_mpeg2_frame(pkt, &trk->cluster[trk->entry].flags);
5244 if (trk->cluster[trk->entry].flags & MOV_PARTIAL_SYNC_SAMPLE)
5245 trk->flags |= MOV_TRACK_STPS;
5247 trk->cluster[trk->entry].flags = MOV_SYNC_SAMPLE;
5249 if (trk->cluster[trk->entry].flags & MOV_SYNC_SAMPLE)
5250 trk->has_keyframes++;
5253 trk->sample_count += samples_in_chunk;
5254 mov->mdat_size += size;
5256 if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams)
5257 ff_mov_add_hinted_packet(s, pkt, trk->hint_track, trk->entry,
5258 reformatted_data, size);
5263 av_free(reformatted_data);
5267 static int mov_write_single_packet(AVFormatContext *s, AVPacket *pkt)
5269 MOVMuxContext *mov = s->priv_data;
5270 MOVTrack *trk = &mov->tracks[pkt->stream_index];
5271 AVCodecParameters *par = trk->par;
5272 int64_t frag_duration = 0;
5273 int size = pkt->size;
5275 int ret = check_pkt(s, pkt);
5279 if (mov->flags & FF_MOV_FLAG_FRAG_DISCONT) {
5281 for (i = 0; i < s->nb_streams; i++)
5282 mov->tracks[i].frag_discont = 1;
5283 mov->flags &= ~FF_MOV_FLAG_FRAG_DISCONT;
5286 if (trk->par->codec_id == AV_CODEC_ID_MP4ALS ||
5287 trk->par->codec_id == AV_CODEC_ID_AAC ||
5288 trk->par->codec_id == AV_CODEC_ID_FLAC) {
5290 uint8_t *side = av_packet_get_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA, &side_size);
5291 if (side && side_size > 0 && (side_size != par->extradata_size || memcmp(side, par->extradata, side_size))) {
5292 void *newextra = av_mallocz(side_size + AV_INPUT_BUFFER_PADDING_SIZE);
5294 return AVERROR(ENOMEM);
5295 av_free(par->extradata);
5296 par->extradata = newextra;
5297 memcpy(par->extradata, side, side_size);
5298 par->extradata_size = side_size;
5299 if (!pkt->size) // Flush packet
5300 mov->need_rewrite_extradata = 1;
5305 if (trk->start_dts == AV_NOPTS_VALUE && trk->frag_discont) {
5306 trk->start_dts = pkt->dts;
5307 if (pkt->pts != AV_NOPTS_VALUE)
5308 trk->start_cts = pkt->pts - pkt->dts;
5313 return 0; /* Discard 0 sized packets */
5316 if (trk->entry && pkt->stream_index < s->nb_streams)
5317 frag_duration = av_rescale_q(pkt->dts - trk->cluster[0].dts,
5318 s->streams[pkt->stream_index]->time_base,
5320 if ((mov->max_fragment_duration &&
5321 frag_duration >= mov->max_fragment_duration) ||
5322 (mov->max_fragment_size && mov->mdat_size + size >= mov->max_fragment_size) ||
5323 (mov->flags & FF_MOV_FLAG_FRAG_KEYFRAME &&
5324 par->codec_type == AVMEDIA_TYPE_VIDEO &&
5325 trk->entry && pkt->flags & AV_PKT_FLAG_KEY)) {
5326 if (frag_duration >= mov->min_fragment_duration) {
5327 // Set the duration of this track to line up with the next
5328 // sample in this track. This avoids relying on AVPacket
5329 // duration, but only helps for this particular track, not
5330 // for the other ones that are flushed at the same time.
5331 trk->track_duration = pkt->dts - trk->start_dts;
5332 if (pkt->pts != AV_NOPTS_VALUE)
5333 trk->end_pts = pkt->pts;
5335 trk->end_pts = pkt->dts;
5336 trk->end_reliable = 1;
5337 mov_auto_flush_fragment(s, 0);
5341 return ff_mov_write_packet(s, pkt);
5344 static int mov_write_subtitle_end_packet(AVFormatContext *s,
5348 uint8_t data[2] = {0};
5351 av_init_packet(&end);
5352 end.size = sizeof(data);
5357 end.stream_index = stream_index;
5359 ret = mov_write_single_packet(s, &end);
5360 av_packet_unref(&end);
5365 static int mov_write_packet(AVFormatContext *s, AVPacket *pkt)
5368 mov_flush_fragment(s, 1);
5372 MOVMuxContext *mov = s->priv_data;
5373 MOVTrack *trk = &mov->tracks[pkt->stream_index];
5376 return mov_write_single_packet(s, pkt); /* Passthrough. */
5379 * Subtitles require special handling.
5381 * 1) For full complaince, every track must have a sample at
5382 * dts == 0, which is rarely true for subtitles. So, as soon
5383 * as we see any packet with dts > 0, write an empty subtitle
5384 * at dts == 0 for any subtitle track with no samples in it.
5386 * 2) For each subtitle track, check if the current packet's
5387 * dts is past the duration of the last subtitle sample. If
5388 * so, we now need to write an end sample for that subtitle.
5390 * This must be done conditionally to allow for subtitles that
5391 * immediately replace each other, in which case an end sample
5392 * is not needed, and is, in fact, actively harmful.
5394 * 3) See mov_write_trailer for how the final end sample is
5397 for (i = 0; i < mov->nb_streams; i++) {
5398 MOVTrack *trk = &mov->tracks[i];
5401 if (trk->par->codec_id == AV_CODEC_ID_MOV_TEXT &&
5402 trk->track_duration < pkt->dts &&
5403 (trk->entry == 0 || !trk->last_sample_is_subtitle_end)) {
5404 ret = mov_write_subtitle_end_packet(s, i, trk->track_duration);
5405 if (ret < 0) return ret;
5406 trk->last_sample_is_subtitle_end = 1;
5410 if (trk->mode == MODE_MOV && trk->par->codec_type == AVMEDIA_TYPE_VIDEO) {
5411 AVPacket *opkt = pkt;
5412 int reshuffle_ret, ret;
5413 if (trk->is_unaligned_qt_rgb) {
5414 int64_t bpc = trk->par->bits_per_coded_sample != 15 ? trk->par->bits_per_coded_sample : 16;
5415 int expected_stride = ((trk->par->width * bpc + 15) >> 4)*2;
5416 reshuffle_ret = ff_reshuffle_raw_rgb(s, &pkt, trk->par, expected_stride);
5417 if (reshuffle_ret < 0)
5418 return reshuffle_ret;
5421 if (trk->par->format == AV_PIX_FMT_PAL8 && !trk->pal_done) {
5422 ret = ff_get_packet_palette(s, opkt, reshuffle_ret, trk->palette);
5427 } else if (trk->par->codec_id == AV_CODEC_ID_RAWVIDEO &&
5428 (trk->par->format == AV_PIX_FMT_GRAY8 ||
5429 trk->par->format == AV_PIX_FMT_MONOBLACK)) {
5430 for (i = 0; i < pkt->size; i++)
5431 pkt->data[i] = ~pkt->data[i];
5433 if (reshuffle_ret) {
5434 ret = mov_write_single_packet(s, pkt);
5437 av_packet_free(&pkt);
5442 return mov_write_single_packet(s, pkt);
5446 // QuickTime chapters involve an additional text track with the chapter names
5447 // as samples, and a tref pointing from the other tracks to the chapter one.
5448 static int mov_create_chapter_track(AVFormatContext *s, int tracknum)
5452 MOVMuxContext *mov = s->priv_data;
5453 MOVTrack *track = &mov->tracks[tracknum];
5454 AVPacket pkt = { .stream_index = tracknum, .flags = AV_PKT_FLAG_KEY };
5457 track->mode = mov->mode;
5458 track->tag = MKTAG('t','e','x','t');
5459 track->timescale = MOV_TIMESCALE;
5460 track->par = avcodec_parameters_alloc();
5462 return AVERROR(ENOMEM);
5463 track->par->codec_type = AVMEDIA_TYPE_SUBTITLE;
5465 // These properties are required to make QT recognize the chapter track
5466 uint8_t chapter_properties[43] = { 0, 0, 0, 0, 0, 0, 0, 1, };
5467 if (ff_alloc_extradata(track->par, sizeof(chapter_properties)))
5468 return AVERROR(ENOMEM);
5469 memcpy(track->par->extradata, chapter_properties, sizeof(chapter_properties));
5471 if (avio_open_dyn_buf(&pb) >= 0) {
5475 /* Stub header (usually for Quicktime chapter track) */
5477 avio_wb32(pb, 0x01); // displayFlags
5478 avio_w8(pb, 0x00); // horizontal justification
5479 avio_w8(pb, 0x00); // vertical justification
5480 avio_w8(pb, 0x00); // bgColourRed
5481 avio_w8(pb, 0x00); // bgColourGreen
5482 avio_w8(pb, 0x00); // bgColourBlue
5483 avio_w8(pb, 0x00); // bgColourAlpha
5485 avio_wb16(pb, 0x00); // defTextBoxTop
5486 avio_wb16(pb, 0x00); // defTextBoxLeft
5487 avio_wb16(pb, 0x00); // defTextBoxBottom
5488 avio_wb16(pb, 0x00); // defTextBoxRight
5490 avio_wb16(pb, 0x00); // startChar
5491 avio_wb16(pb, 0x00); // endChar
5492 avio_wb16(pb, 0x01); // fontID
5493 avio_w8(pb, 0x00); // fontStyleFlags
5494 avio_w8(pb, 0x00); // fontSize
5495 avio_w8(pb, 0x00); // fgColourRed
5496 avio_w8(pb, 0x00); // fgColourGreen
5497 avio_w8(pb, 0x00); // fgColourBlue
5498 avio_w8(pb, 0x00); // fgColourAlpha
5500 avio_wb32(pb, 0x0D); // box size
5501 ffio_wfourcc(pb, "ftab"); // box atom name
5502 avio_wb16(pb, 0x01); // entry count
5504 avio_wb16(pb, 0x01); // font ID
5505 avio_w8(pb, 0x00); // font name length
5507 if ((size = avio_close_dyn_buf(pb, &buf)) > 0) {
5508 track->par->extradata = buf;
5509 track->par->extradata_size = size;
5516 for (i = 0; i < s->nb_chapters; i++) {
5517 AVChapter *c = s->chapters[i];
5518 AVDictionaryEntry *t;
5520 int64_t end = av_rescale_q(c->end, c->time_base, (AVRational){1,MOV_TIMESCALE});
5521 pkt.pts = pkt.dts = av_rescale_q(c->start, c->time_base, (AVRational){1,MOV_TIMESCALE});
5522 pkt.duration = end - pkt.dts;
5524 if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
5525 static const char encd[12] = {
5526 0x00, 0x00, 0x00, 0x0C,
5528 0x00, 0x00, 0x01, 0x00 };
5529 len = strlen(t->value);
5530 pkt.size = len + 2 + 12;
5531 pkt.data = av_malloc(pkt.size);
5533 return AVERROR(ENOMEM);
5534 AV_WB16(pkt.data, len);
5535 memcpy(pkt.data + 2, t->value, len);
5536 memcpy(pkt.data + len + 2, encd, sizeof(encd));
5537 ff_mov_write_packet(s, &pkt);
5538 av_freep(&pkt.data);
5546 static int mov_check_timecode_track(AVFormatContext *s, AVTimecode *tc, int src_index, const char *tcstr)
5550 /* compute the frame number */
5551 ret = av_timecode_init_from_string(tc, find_fps(s, s->streams[src_index]), tcstr, s);
5555 static int mov_create_timecode_track(AVFormatContext *s, int index, int src_index, AVTimecode tc)
5558 MOVMuxContext *mov = s->priv_data;
5559 MOVTrack *track = &mov->tracks[index];
5560 AVStream *src_st = s->streams[src_index];
5561 AVPacket pkt = {.stream_index = index, .flags = AV_PKT_FLAG_KEY, .size = 4};
5562 AVRational rate = find_fps(s, src_st);
5564 /* tmcd track based on video stream */
5565 track->mode = mov->mode;
5566 track->tag = MKTAG('t','m','c','d');
5567 track->src_track = src_index;
5568 track->timescale = mov->tracks[src_index].timescale;
5569 if (tc.flags & AV_TIMECODE_FLAG_DROPFRAME)
5570 track->timecode_flags |= MOV_TIMECODE_FLAG_DROPFRAME;
5572 /* set st to src_st for metadata access*/
5575 /* encode context: tmcd data stream */
5576 track->par = avcodec_parameters_alloc();
5578 return AVERROR(ENOMEM);
5579 track->par->codec_type = AVMEDIA_TYPE_DATA;
5580 track->par->codec_tag = track->tag;
5581 track->st->avg_frame_rate = av_inv_q(rate);
5583 /* the tmcd track just contains one packet with the frame number */
5584 pkt.data = av_malloc(pkt.size);
5586 return AVERROR(ENOMEM);
5587 AV_WB32(pkt.data, tc.start);
5588 ret = ff_mov_write_packet(s, &pkt);
5594 * st->disposition controls the "enabled" flag in the tkhd tag.
5595 * QuickTime will not play a track if it is not enabled. So make sure
5596 * that one track of each type (audio, video, subtitle) is enabled.
5598 * Subtitles are special. For audio and video, setting "enabled" also
5599 * makes the track "default" (i.e. it is rendered when played). For
5600 * subtitles, an "enabled" subtitle is not rendered by default, but
5601 * if no subtitle is enabled, the subtitle menu in QuickTime will be
5604 static void enable_tracks(AVFormatContext *s)
5606 MOVMuxContext *mov = s->priv_data;
5608 int enabled[AVMEDIA_TYPE_NB];
5609 int first[AVMEDIA_TYPE_NB];
5611 for (i = 0; i < AVMEDIA_TYPE_NB; i++) {
5616 for (i = 0; i < s->nb_streams; i++) {
5617 AVStream *st = s->streams[i];
5619 if (st->codecpar->codec_type <= AVMEDIA_TYPE_UNKNOWN ||
5620 st->codecpar->codec_type >= AVMEDIA_TYPE_NB)
5623 if (first[st->codecpar->codec_type] < 0)
5624 first[st->codecpar->codec_type] = i;
5625 if (st->disposition & AV_DISPOSITION_DEFAULT) {
5626 mov->tracks[i].flags |= MOV_TRACK_ENABLED;
5627 enabled[st->codecpar->codec_type]++;
5631 for (i = 0; i < AVMEDIA_TYPE_NB; i++) {
5633 case AVMEDIA_TYPE_VIDEO:
5634 case AVMEDIA_TYPE_AUDIO:
5635 case AVMEDIA_TYPE_SUBTITLE:
5637 mov->per_stream_grouping = 1;
5638 if (!enabled[i] && first[i] >= 0)
5639 mov->tracks[first[i]].flags |= MOV_TRACK_ENABLED;
5645 static void mov_free(AVFormatContext *s)
5647 MOVMuxContext *mov = s->priv_data;
5650 if (mov->chapter_track) {
5651 if (mov->tracks[mov->chapter_track].par)
5652 av_freep(&mov->tracks[mov->chapter_track].par->extradata);
5653 av_freep(&mov->tracks[mov->chapter_track].par);
5656 for (i = 0; i < mov->nb_streams; i++) {
5657 if (mov->tracks[i].tag == MKTAG('r','t','p',' '))
5658 ff_mov_close_hinting(&mov->tracks[i]);
5659 else if (mov->tracks[i].tag == MKTAG('t','m','c','d') && mov->nb_meta_tmcd)
5660 av_freep(&mov->tracks[i].par);
5661 av_freep(&mov->tracks[i].cluster);
5662 av_freep(&mov->tracks[i].frag_info);
5664 if (mov->tracks[i].vos_len)
5665 av_freep(&mov->tracks[i].vos_data);
5667 ff_mov_cenc_free(&mov->tracks[i].cenc);
5670 av_freep(&mov->tracks);
5673 static uint32_t rgb_to_yuv(uint32_t rgb)
5678 r = (rgb >> 16) & 0xFF;
5679 g = (rgb >> 8) & 0xFF;
5682 y = av_clip_uint8(( 16000 + 257 * r + 504 * g + 98 * b)/1000);
5683 cb = av_clip_uint8((128000 - 148 * r - 291 * g + 439 * b)/1000);
5684 cr = av_clip_uint8((128000 + 439 * r - 368 * g - 71 * b)/1000);
5686 return (y << 16) | (cr << 8) | cb;
5689 static int mov_create_dvd_sub_decoder_specific_info(MOVTrack *track,
5692 int i, width = 720, height = 480;
5693 int have_palette = 0, have_size = 0;
5694 uint32_t palette[16];
5695 char *cur = st->codecpar->extradata;
5697 while (cur && *cur) {
5698 if (strncmp("palette:", cur, 8) == 0) {
5700 count = sscanf(cur + 8,
5701 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
5702 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
5703 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
5704 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32"",
5705 &palette[ 0], &palette[ 1], &palette[ 2], &palette[ 3],
5706 &palette[ 4], &palette[ 5], &palette[ 6], &palette[ 7],
5707 &palette[ 8], &palette[ 9], &palette[10], &palette[11],
5708 &palette[12], &palette[13], &palette[14], &palette[15]);
5710 for (i = 0; i < count; i++) {
5711 palette[i] = rgb_to_yuv(palette[i]);
5714 } else if (!strncmp("size:", cur, 5)) {
5715 sscanf(cur + 5, "%dx%d", &width, &height);
5718 if (have_palette && have_size)
5720 cur += strcspn(cur, "\n\r");
5721 cur += strspn(cur, "\n\r");
5724 track->vos_data = av_malloc(16*4);
5725 if (!track->vos_data)
5726 return AVERROR(ENOMEM);
5727 for (i = 0; i < 16; i++) {
5728 AV_WB32(track->vos_data + i * 4, palette[i]);
5730 track->vos_len = 16 * 4;
5732 st->codecpar->width = width;
5733 st->codecpar->height = track->height = height;
5738 static int mov_init(AVFormatContext *s)
5740 MOVMuxContext *mov = s->priv_data;
5741 AVDictionaryEntry *global_tcr = av_dict_get(s->metadata, "timecode", NULL, 0);
5746 /* Default mode == MP4 */
5747 mov->mode = MODE_MP4;
5750 if (!strcmp("3gp", s->oformat->name)) mov->mode = MODE_3GP;
5751 else if (!strcmp("3g2", s->oformat->name)) mov->mode = MODE_3GP|MODE_3G2;
5752 else if (!strcmp("mov", s->oformat->name)) mov->mode = MODE_MOV;
5753 else if (!strcmp("psp", s->oformat->name)) mov->mode = MODE_PSP;
5754 else if (!strcmp("ipod",s->oformat->name)) mov->mode = MODE_IPOD;
5755 else if (!strcmp("ismv",s->oformat->name)) mov->mode = MODE_ISM;
5756 else if (!strcmp("f4v", s->oformat->name)) mov->mode = MODE_F4V;
5759 if (mov->flags & FF_MOV_FLAG_DELAY_MOOV)
5760 mov->flags |= FF_MOV_FLAG_EMPTY_MOOV;
5762 /* Set the FRAGMENT flag if any of the fragmentation methods are
5764 if (mov->max_fragment_duration || mov->max_fragment_size ||
5765 mov->flags & (FF_MOV_FLAG_EMPTY_MOOV |
5766 FF_MOV_FLAG_FRAG_KEYFRAME |
5767 FF_MOV_FLAG_FRAG_CUSTOM))
5768 mov->flags |= FF_MOV_FLAG_FRAGMENT;
5770 /* Set other implicit flags immediately */
5771 if (mov->mode == MODE_ISM)
5772 mov->flags |= FF_MOV_FLAG_EMPTY_MOOV | FF_MOV_FLAG_SEPARATE_MOOF |
5773 FF_MOV_FLAG_FRAGMENT;
5774 if (mov->flags & FF_MOV_FLAG_DASH)
5775 mov->flags |= FF_MOV_FLAG_FRAGMENT | FF_MOV_FLAG_EMPTY_MOOV |
5776 FF_MOV_FLAG_DEFAULT_BASE_MOOF;
5778 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV && s->flags & AVFMT_FLAG_AUTO_BSF) {
5779 av_log(s, AV_LOG_VERBOSE, "Empty MOOV enabled; disabling automatic bitstream filtering\n");
5780 s->flags &= ~AVFMT_FLAG_AUTO_BSF;
5783 if (mov->flags & FF_MOV_FLAG_FASTSTART) {
5784 mov->reserved_moov_size = -1;
5787 if (mov->use_editlist < 0) {
5788 mov->use_editlist = 1;
5789 if (mov->flags & FF_MOV_FLAG_FRAGMENT &&
5790 !(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
5791 // If we can avoid needing an edit list by shifting the
5792 // tracks, prefer that over (trying to) write edit lists
5793 // in fragmented output.
5794 if (s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO ||
5795 s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO)
5796 mov->use_editlist = 0;
5799 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV &&
5800 !(mov->flags & FF_MOV_FLAG_DELAY_MOOV) && mov->use_editlist)
5801 av_log(s, AV_LOG_WARNING, "No meaningful edit list will be written when using empty_moov without delay_moov\n");
5803 if (!mov->use_editlist && s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO)
5804 s->avoid_negative_ts = AVFMT_AVOID_NEG_TS_MAKE_ZERO;
5806 /* Clear the omit_tfhd_offset flag if default_base_moof is set;
5807 * if the latter is set that's enough and omit_tfhd_offset doesn't
5808 * add anything extra on top of that. */
5809 if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET &&
5810 mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)
5811 mov->flags &= ~FF_MOV_FLAG_OMIT_TFHD_OFFSET;
5813 if (mov->frag_interleave &&
5814 mov->flags & (FF_MOV_FLAG_OMIT_TFHD_OFFSET | FF_MOV_FLAG_SEPARATE_MOOF)) {
5815 av_log(s, AV_LOG_ERROR,
5816 "Sample interleaving in fragments is mutually exclusive with "
5817 "omit_tfhd_offset and separate_moof\n");
5818 return AVERROR(EINVAL);
5821 /* Non-seekable output is ok if using fragmentation. If ism_lookahead
5822 * is enabled, we don't support non-seekable output at all. */
5823 if (!(s->pb->seekable & AVIO_SEEKABLE_NORMAL) &&
5824 (!(mov->flags & FF_MOV_FLAG_FRAGMENT) || mov->ism_lookahead)) {
5825 av_log(s, AV_LOG_ERROR, "muxer does not support non seekable output\n");
5826 return AVERROR(EINVAL);
5829 mov->nb_streams = s->nb_streams;
5830 if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters)
5831 mov->chapter_track = mov->nb_streams++;
5833 if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
5834 /* Add hint tracks for each audio and video stream */
5835 for (i = 0; i < s->nb_streams; i++) {
5836 AVStream *st = s->streams[i];
5837 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ||
5838 st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
5844 if ( mov->write_tmcd == -1 && (mov->mode == MODE_MOV || mov->mode == MODE_MP4)
5845 || mov->write_tmcd == 1) {
5846 /* +1 tmcd track for each video stream with a timecode */
5847 for (i = 0; i < s->nb_streams; i++) {
5848 AVStream *st = s->streams[i];
5849 AVDictionaryEntry *t = global_tcr;
5850 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
5851 (t || (t=av_dict_get(st->metadata, "timecode", NULL, 0)))) {
5853 ret = mov_check_timecode_track(s, &tc, i, t->value);
5855 mov->nb_meta_tmcd++;
5859 /* check if there is already a tmcd track to remux */
5860 if (mov->nb_meta_tmcd) {
5861 for (i = 0; i < s->nb_streams; i++) {
5862 AVStream *st = s->streams[i];
5863 if (st->codecpar->codec_tag == MKTAG('t','m','c','d')) {
5864 av_log(s, AV_LOG_WARNING, "You requested a copy of the original timecode track "
5865 "so timecode metadata are now ignored\n");
5866 mov->nb_meta_tmcd = 0;
5871 mov->nb_streams += mov->nb_meta_tmcd;
5874 // Reserve an extra stream for chapters for the case where chapters
5875 // are written in the trailer
5876 mov->tracks = av_mallocz_array((mov->nb_streams + 1), sizeof(*mov->tracks));
5878 return AVERROR(ENOMEM);
5880 if (mov->encryption_scheme_str != NULL && strcmp(mov->encryption_scheme_str, "none") != 0) {
5881 if (strcmp(mov->encryption_scheme_str, "cenc-aes-ctr") == 0) {
5882 mov->encryption_scheme = MOV_ENC_CENC_AES_CTR;
5884 if (mov->encryption_key_len != AES_CTR_KEY_SIZE) {
5885 av_log(s, AV_LOG_ERROR, "Invalid encryption key len %d expected %d\n",
5886 mov->encryption_key_len, AES_CTR_KEY_SIZE);
5887 return AVERROR(EINVAL);
5890 if (mov->encryption_kid_len != CENC_KID_SIZE) {
5891 av_log(s, AV_LOG_ERROR, "Invalid encryption kid len %d expected %d\n",
5892 mov->encryption_kid_len, CENC_KID_SIZE);
5893 return AVERROR(EINVAL);
5896 av_log(s, AV_LOG_ERROR, "unsupported encryption scheme %s\n",
5897 mov->encryption_scheme_str);
5898 return AVERROR(EINVAL);
5902 for (i = 0; i < s->nb_streams; i++) {
5903 AVStream *st= s->streams[i];
5904 MOVTrack *track= &mov->tracks[i];
5905 AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0);
5908 track->par = st->codecpar;
5909 track->language = ff_mov_iso639_to_lang(lang?lang->value:"und", mov->mode!=MODE_MOV);
5910 if (track->language < 0)
5911 track->language = 0;
5912 track->mode = mov->mode;
5913 track->tag = mov_find_codec_tag(s, track);
5915 av_log(s, AV_LOG_ERROR, "Could not find tag for codec %s in stream #%d, "
5916 "codec not currently supported in container\n",
5917 avcodec_get_name(st->codecpar->codec_id), i);
5918 return AVERROR(EINVAL);
5920 /* If hinting of this track is enabled by a later hint track,
5921 * this is updated. */
5922 track->hint_track = -1;
5923 track->start_dts = AV_NOPTS_VALUE;
5924 track->start_cts = AV_NOPTS_VALUE;
5925 track->end_pts = AV_NOPTS_VALUE;
5926 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
5927 if (track->tag == MKTAG('m','x','3','p') || track->tag == MKTAG('m','x','3','n') ||
5928 track->tag == MKTAG('m','x','4','p') || track->tag == MKTAG('m','x','4','n') ||
5929 track->tag == MKTAG('m','x','5','p') || track->tag == MKTAG('m','x','5','n')) {
5930 if (st->codecpar->width != 720 || (st->codecpar->height != 608 && st->codecpar->height != 512)) {
5931 av_log(s, AV_LOG_ERROR, "D-10/IMX must use 720x608 or 720x512 video resolution\n");
5932 return AVERROR(EINVAL);
5934 track->height = track->tag >> 24 == 'n' ? 486 : 576;
5936 if (mov->video_track_timescale) {
5937 track->timescale = mov->video_track_timescale;
5939 track->timescale = st->time_base.den;
5940 while(track->timescale < 10000)
5941 track->timescale *= 2;
5943 if (st->codecpar->width > 65535 || st->codecpar->height > 65535) {
5944 av_log(s, AV_LOG_ERROR, "Resolution %dx%d too large for mov/mp4\n", st->codecpar->width, st->codecpar->height);
5945 return AVERROR(EINVAL);
5947 if (track->mode == MODE_MOV && track->timescale > 100000)
5948 av_log(s, AV_LOG_WARNING,
5949 "WARNING codec timebase is very high. If duration is too long,\n"
5950 "file may not be playable by quicktime. Specify a shorter timebase\n"
5951 "or choose different container.\n");
5952 if (track->mode == MODE_MOV &&
5953 track->par->codec_id == AV_CODEC_ID_RAWVIDEO &&
5954 track->tag == MKTAG('r','a','w',' ')) {
5955 enum AVPixelFormat pix_fmt = track->par->format;
5956 if (pix_fmt == AV_PIX_FMT_NONE && track->par->bits_per_coded_sample == 1)
5957 pix_fmt = AV_PIX_FMT_MONOWHITE;
5958 track->is_unaligned_qt_rgb =
5959 pix_fmt == AV_PIX_FMT_RGB24 ||
5960 pix_fmt == AV_PIX_FMT_BGR24 ||
5961 pix_fmt == AV_PIX_FMT_PAL8 ||
5962 pix_fmt == AV_PIX_FMT_GRAY8 ||
5963 pix_fmt == AV_PIX_FMT_MONOWHITE ||
5964 pix_fmt == AV_PIX_FMT_MONOBLACK;
5966 if (track->par->codec_id == AV_CODEC_ID_VP9) {
5967 if (track->mode != MODE_MP4) {
5968 av_log(s, AV_LOG_ERROR, "VP9 only supported in MP4.\n");
5969 return AVERROR(EINVAL);
5972 } else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
5973 track->timescale = st->codecpar->sample_rate;
5974 if (!st->codecpar->frame_size && !av_get_bits_per_sample(st->codecpar->codec_id)) {
5975 av_log(s, AV_LOG_WARNING, "track %d: codec frame size is not set\n", i);
5976 track->audio_vbr = 1;
5977 }else if (st->codecpar->codec_id == AV_CODEC_ID_ADPCM_MS ||
5978 st->codecpar->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
5979 st->codecpar->codec_id == AV_CODEC_ID_ILBC){
5980 if (!st->codecpar->block_align) {
5981 av_log(s, AV_LOG_ERROR, "track %d: codec block align is not set for adpcm\n", i);
5982 return AVERROR(EINVAL);
5984 track->sample_size = st->codecpar->block_align;
5985 }else if (st->codecpar->frame_size > 1){ /* assume compressed audio */
5986 track->audio_vbr = 1;
5988 track->sample_size = (av_get_bits_per_sample(st->codecpar->codec_id) >> 3) * st->codecpar->channels;
5990 if (st->codecpar->codec_id == AV_CODEC_ID_ILBC ||
5991 st->codecpar->codec_id == AV_CODEC_ID_ADPCM_IMA_QT) {
5992 track->audio_vbr = 1;
5994 if (track->mode != MODE_MOV &&
5995 track->par->codec_id == AV_CODEC_ID_MP3 && track->timescale < 16000) {
5996 if (s->strict_std_compliance >= FF_COMPLIANCE_NORMAL) {
5997 av_log(s, AV_LOG_ERROR, "track %d: muxing mp3 at %dhz is not standard, to mux anyway set strict to -1\n",
5998 i, track->par->sample_rate);
5999 return AVERROR(EINVAL);
6001 av_log(s, AV_LOG_WARNING, "track %d: muxing mp3 at %dhz is not standard in MP4\n",
6002 i, track->par->sample_rate);
6005 if (track->par->codec_id == AV_CODEC_ID_FLAC ||
6006 track->par->codec_id == AV_CODEC_ID_OPUS) {
6007 if (track->mode != MODE_MP4) {
6008 av_log(s, AV_LOG_ERROR, "%s only supported in MP4.\n", avcodec_get_name(track->par->codec_id));
6009 return AVERROR(EINVAL);
6011 if (s->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
6012 av_log(s, AV_LOG_ERROR,
6013 "%s in MP4 support is experimental, add "
6014 "'-strict %d' if you want to use it.\n",
6015 avcodec_get_name(track->par->codec_id), FF_COMPLIANCE_EXPERIMENTAL);
6016 return AVERROR_EXPERIMENTAL;
6019 } else if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) {
6020 track->timescale = st->time_base.den;
6021 } else if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA) {
6022 track->timescale = st->time_base.den;
6024 track->timescale = MOV_TIMESCALE;
6027 track->height = st->codecpar->height;
6028 /* The ism specific timescale isn't mandatory, but is assumed by
6029 * some tools, such as mp4split. */
6030 if (mov->mode == MODE_ISM)
6031 track->timescale = 10000000;
6033 avpriv_set_pts_info(st, 64, 1, track->timescale);
6035 if (mov->encryption_scheme == MOV_ENC_CENC_AES_CTR) {
6036 ret = ff_mov_cenc_init(&track->cenc, mov->encryption_key,
6037 track->par->codec_id == AV_CODEC_ID_H264, s->flags & AVFMT_FLAG_BITEXACT);
6047 static int mov_write_header(AVFormatContext *s)
6049 AVIOContext *pb = s->pb;
6050 MOVMuxContext *mov = s->priv_data;
6051 AVDictionaryEntry *t, *global_tcr = av_dict_get(s->metadata, "timecode", NULL, 0);
6052 int i, ret, hint_track = 0, tmcd_track = 0, nb_tracks = s->nb_streams;
6054 if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters)
6057 if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
6058 /* Add hint tracks for each audio and video stream */
6059 hint_track = nb_tracks;
6060 for (i = 0; i < s->nb_streams; i++) {
6061 AVStream *st = s->streams[i];
6062 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ||
6063 st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
6069 if (mov->mode == MODE_MOV || mov->mode == MODE_MP4)
6070 tmcd_track = nb_tracks;
6072 for (i = 0; i < s->nb_streams; i++) {
6074 AVStream *st= s->streams[i];
6075 MOVTrack *track= &mov->tracks[i];
6077 /* copy extradata if it exists */
6078 if (st->codecpar->extradata_size) {
6079 if (st->codecpar->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
6080 mov_create_dvd_sub_decoder_specific_info(track, st);
6081 else if (!TAG_IS_AVCI(track->tag) && st->codecpar->codec_id != AV_CODEC_ID_DNXHD) {
6082 track->vos_len = st->codecpar->extradata_size;
6083 track->vos_data = av_malloc(track->vos_len);
6084 if (!track->vos_data) {
6085 return AVERROR(ENOMEM);
6087 memcpy(track->vos_data, st->codecpar->extradata, track->vos_len);
6091 if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ||
6092 track->par->channel_layout != AV_CH_LAYOUT_MONO)
6095 for (j = 0; j < s->nb_streams; j++) {
6096 AVStream *stj= s->streams[j];
6097 MOVTrack *trackj= &mov->tracks[j];
6101 if (stj->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ||
6102 trackj->par->channel_layout != AV_CH_LAYOUT_MONO ||
6103 trackj->language != track->language ||
6104 trackj->tag != track->tag
6107 track->multichannel_as_mono++;
6111 if (!(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
6112 if ((ret = mov_write_identification(pb, s)) < 0)
6116 if (mov->reserved_moov_size){
6117 mov->reserved_header_pos = avio_tell(pb);
6118 if (mov->reserved_moov_size > 0)
6119 avio_skip(pb, mov->reserved_moov_size);
6122 if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
6123 /* If no fragmentation options have been set, set a default. */
6124 if (!(mov->flags & (FF_MOV_FLAG_FRAG_KEYFRAME |
6125 FF_MOV_FLAG_FRAG_CUSTOM)) &&
6126 !mov->max_fragment_duration && !mov->max_fragment_size)
6127 mov->flags |= FF_MOV_FLAG_FRAG_KEYFRAME;
6129 if (mov->flags & FF_MOV_FLAG_FASTSTART)
6130 mov->reserved_header_pos = avio_tell(pb);
6131 mov_write_mdat_tag(pb, mov);
6134 ff_parse_creation_time_metadata(s, &mov->time, 1);
6136 mov->time += 0x7C25B080; // 1970 based -> 1904 based
6138 if (mov->chapter_track)
6139 if ((ret = mov_create_chapter_track(s, mov->chapter_track)) < 0)
6142 if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
6143 /* Initialize the hint tracks for each audio and video stream */
6144 for (i = 0; i < s->nb_streams; i++) {
6145 AVStream *st = s->streams[i];
6146 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ||
6147 st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
6148 if ((ret = ff_mov_init_hinting(s, hint_track, i)) < 0)
6155 if (mov->nb_meta_tmcd) {
6156 /* Initialize the tmcd tracks */
6157 for (i = 0; i < s->nb_streams; i++) {
6158 AVStream *st = s->streams[i];
6161 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
6164 t = av_dict_get(st->metadata, "timecode", NULL, 0);
6167 if (mov_check_timecode_track(s, &tc, i, t->value) < 0)
6169 if ((ret = mov_create_timecode_track(s, tmcd_track, i, tc)) < 0)
6178 if (mov->flags & FF_MOV_FLAG_ISML)
6179 mov_write_isml_manifest(pb, mov, s);
6181 if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV &&
6182 !(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
6183 if ((ret = mov_write_moov_tag(pb, mov, s)) < 0)
6186 mov->moov_written = 1;
6187 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
6188 mov->reserved_header_pos = avio_tell(pb);
6194 static int get_moov_size(AVFormatContext *s)
6197 AVIOContext *moov_buf;
6198 MOVMuxContext *mov = s->priv_data;
6200 if ((ret = ffio_open_null_buf(&moov_buf)) < 0)
6202 if ((ret = mov_write_moov_tag(moov_buf, mov, s)) < 0)
6204 return ffio_close_null_buf(moov_buf);
6207 static int get_sidx_size(AVFormatContext *s)
6211 MOVMuxContext *mov = s->priv_data;
6213 if ((ret = ffio_open_null_buf(&buf)) < 0)
6215 mov_write_sidx_tags(buf, mov, -1, 0);
6216 return ffio_close_null_buf(buf);
6220 * This function gets the moov size if moved to the top of the file: the chunk
6221 * offset table can switch between stco (32-bit entries) to co64 (64-bit
6222 * entries) when the moov is moved to the beginning, so the size of the moov
6223 * would change. It also updates the chunk offset tables.
6225 static int compute_moov_size(AVFormatContext *s)
6227 int i, moov_size, moov_size2;
6228 MOVMuxContext *mov = s->priv_data;
6230 moov_size = get_moov_size(s);
6234 for (i = 0; i < mov->nb_streams; i++)
6235 mov->tracks[i].data_offset += moov_size;
6237 moov_size2 = get_moov_size(s);
6241 /* if the size changed, we just switched from stco to co64 and need to
6242 * update the offsets */
6243 if (moov_size2 != moov_size)
6244 for (i = 0; i < mov->nb_streams; i++)
6245 mov->tracks[i].data_offset += moov_size2 - moov_size;
6250 static int compute_sidx_size(AVFormatContext *s)
6253 MOVMuxContext *mov = s->priv_data;
6255 sidx_size = get_sidx_size(s);
6259 for (i = 0; i < mov->nb_streams; i++)
6260 mov->tracks[i].data_offset += sidx_size;
6265 static int shift_data(AVFormatContext *s)
6267 int ret = 0, moov_size;
6268 MOVMuxContext *mov = s->priv_data;
6269 int64_t pos, pos_end = avio_tell(s->pb);
6270 uint8_t *buf, *read_buf[2];
6271 int read_buf_id = 0;
6273 AVIOContext *read_pb;
6275 if (mov->flags & FF_MOV_FLAG_FRAGMENT)
6276 moov_size = compute_sidx_size(s);
6278 moov_size = compute_moov_size(s);
6282 buf = av_malloc(moov_size * 2);
6284 return AVERROR(ENOMEM);
6286 read_buf[1] = buf + moov_size;
6288 /* Shift the data: the AVIO context of the output can only be used for
6289 * writing, so we re-open the same output, but for reading. It also avoids
6290 * a read/seek/write/seek back and forth. */
6292 ret = s->io_open(s, &read_pb, s->filename, AVIO_FLAG_READ, NULL);
6294 av_log(s, AV_LOG_ERROR, "Unable to re-open %s output file for "
6295 "the second pass (faststart)\n", s->filename);
6299 /* mark the end of the shift to up to the last data we wrote, and get ready
6301 pos_end = avio_tell(s->pb);
6302 avio_seek(s->pb, mov->reserved_header_pos + moov_size, SEEK_SET);
6304 /* start reading at where the new moov will be placed */
6305 avio_seek(read_pb, mov->reserved_header_pos, SEEK_SET);
6306 pos = avio_tell(read_pb);
6308 #define READ_BLOCK do { \
6309 read_size[read_buf_id] = avio_read(read_pb, read_buf[read_buf_id], moov_size); \
6313 /* shift data by chunk of at most moov_size */
6318 n = read_size[read_buf_id];
6321 avio_write(s->pb, read_buf[read_buf_id], n);
6323 } while (pos < pos_end);
6324 ff_format_io_close(s, &read_pb);
6331 static int mov_write_trailer(AVFormatContext *s)
6333 MOVMuxContext *mov = s->priv_data;
6334 AVIOContext *pb = s->pb;
6339 if (mov->need_rewrite_extradata) {
6340 for (i = 0; i < s->nb_streams; i++) {
6341 MOVTrack *track = &mov->tracks[i];
6342 AVCodecParameters *par = track->par;
6344 track->vos_len = par->extradata_size;
6345 track->vos_data = av_malloc(track->vos_len);
6346 if (!track->vos_data)
6347 return AVERROR(ENOMEM);
6348 memcpy(track->vos_data, par->extradata, track->vos_len);
6350 mov->need_rewrite_extradata = 0;
6354 * Before actually writing the trailer, make sure that there are no
6355 * dangling subtitles, that need a terminating sample.
6357 for (i = 0; i < mov->nb_streams; i++) {
6358 MOVTrack *trk = &mov->tracks[i];
6359 if (trk->par->codec_id == AV_CODEC_ID_MOV_TEXT &&
6360 !trk->last_sample_is_subtitle_end) {
6361 mov_write_subtitle_end_packet(s, i, trk->track_duration);
6362 trk->last_sample_is_subtitle_end = 1;
6366 // If there were no chapters when the header was written, but there
6367 // are chapters now, write them in the trailer. This only works
6368 // when we are not doing fragments.
6369 if (!mov->chapter_track && !(mov->flags & FF_MOV_FLAG_FRAGMENT)) {
6370 if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters) {
6371 mov->chapter_track = mov->nb_streams++;
6372 if ((res = mov_create_chapter_track(s, mov->chapter_track)) < 0)
6377 if (!(mov->flags & FF_MOV_FLAG_FRAGMENT)) {
6378 moov_pos = avio_tell(pb);
6380 /* Write size of mdat tag */
6381 if (mov->mdat_size + 8 <= UINT32_MAX) {
6382 avio_seek(pb, mov->mdat_pos, SEEK_SET);
6383 avio_wb32(pb, mov->mdat_size + 8);
6385 /* overwrite 'wide' placeholder atom */
6386 avio_seek(pb, mov->mdat_pos - 8, SEEK_SET);
6387 /* special value: real atom size will be 64 bit value after
6390 ffio_wfourcc(pb, "mdat");
6391 avio_wb64(pb, mov->mdat_size + 16);
6393 avio_seek(pb, mov->reserved_moov_size > 0 ? mov->reserved_header_pos : moov_pos, SEEK_SET);
6395 if (mov->flags & FF_MOV_FLAG_FASTSTART) {
6396 av_log(s, AV_LOG_INFO, "Starting second pass: moving the moov atom to the beginning of the file\n");
6397 res = shift_data(s);
6400 avio_seek(pb, mov->reserved_header_pos, SEEK_SET);
6401 if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
6403 } else if (mov->reserved_moov_size > 0) {
6405 if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
6407 size = mov->reserved_moov_size - (avio_tell(pb) - mov->reserved_header_pos);
6409 av_log(s, AV_LOG_ERROR, "reserved_moov_size is too small, needed %"PRId64" additional\n", 8-size);
6410 return AVERROR(EINVAL);
6412 avio_wb32(pb, size);
6413 ffio_wfourcc(pb, "free");
6414 ffio_fill(pb, 0, size - 8);
6415 avio_seek(pb, moov_pos, SEEK_SET);
6417 if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
6422 mov_auto_flush_fragment(s, 1);
6423 for (i = 0; i < mov->nb_streams; i++)
6424 mov->tracks[i].data_offset = 0;
6425 if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) {
6427 av_log(s, AV_LOG_INFO, "Starting second pass: inserting sidx atoms\n");
6428 res = shift_data(s);
6431 end = avio_tell(pb);
6432 avio_seek(pb, mov->reserved_header_pos, SEEK_SET);
6433 mov_write_sidx_tags(pb, mov, -1, 0);
6434 avio_seek(pb, end, SEEK_SET);
6435 avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_TRAILER);
6436 mov_write_mfra_tag(pb, mov);
6437 } else if (!(mov->flags & FF_MOV_FLAG_SKIP_TRAILER)) {
6438 avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_TRAILER);
6439 mov_write_mfra_tag(pb, mov);
6446 static int mov_check_bitstream(struct AVFormatContext *s, const AVPacket *pkt)
6449 AVStream *st = s->streams[pkt->stream_index];
6451 if (st->codecpar->codec_id == AV_CODEC_ID_AAC) {
6452 if (pkt->size > 2 && (AV_RB16(pkt->data) & 0xfff0) == 0xfff0)
6453 ret = ff_stream_add_bitstream_filter(st, "aac_adtstoasc", NULL);
6454 } else if (st->codecpar->codec_id == AV_CODEC_ID_VP9) {
6455 ret = ff_stream_add_bitstream_filter(st, "vp9_superframe", NULL);
6461 static const AVCodecTag codec_3gp_tags[] = {
6462 { AV_CODEC_ID_H263, MKTAG('s','2','6','3') },
6463 { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
6464 { AV_CODEC_ID_MPEG4, MKTAG('m','p','4','v') },
6465 { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
6466 { AV_CODEC_ID_AMR_NB, MKTAG('s','a','m','r') },
6467 { AV_CODEC_ID_AMR_WB, MKTAG('s','a','w','b') },
6468 { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
6469 { AV_CODEC_ID_NONE, 0 },
6472 const AVCodecTag codec_mp4_tags[] = {
6473 { AV_CODEC_ID_MPEG4 , MKTAG('m', 'p', '4', 'v') },
6474 { AV_CODEC_ID_H264 , MKTAG('a', 'v', 'c', '1') },
6475 { AV_CODEC_ID_HEVC , MKTAG('h', 'e', 'v', '1') },
6476 { AV_CODEC_ID_HEVC , MKTAG('h', 'v', 'c', '1') },
6477 { AV_CODEC_ID_MPEG2VIDEO , MKTAG('m', 'p', '4', 'v') },
6478 { AV_CODEC_ID_MPEG1VIDEO , MKTAG('m', 'p', '4', 'v') },
6479 { AV_CODEC_ID_MJPEG , MKTAG('m', 'p', '4', 'v') },
6480 { AV_CODEC_ID_PNG , MKTAG('m', 'p', '4', 'v') },
6481 { AV_CODEC_ID_JPEG2000 , MKTAG('m', 'p', '4', 'v') },
6482 { AV_CODEC_ID_VC1 , MKTAG('v', 'c', '-', '1') },
6483 { AV_CODEC_ID_DIRAC , MKTAG('d', 'r', 'a', 'c') },
6484 { AV_CODEC_ID_TSCC2 , MKTAG('m', 'p', '4', 'v') },
6485 { AV_CODEC_ID_VP9 , MKTAG('v', 'p', '0', '9') },
6486 { AV_CODEC_ID_AAC , MKTAG('m', 'p', '4', 'a') },
6487 { AV_CODEC_ID_MP4ALS , MKTAG('m', 'p', '4', 'a') },
6488 { AV_CODEC_ID_MP3 , MKTAG('m', 'p', '4', 'a') },
6489 { AV_CODEC_ID_MP2 , MKTAG('m', 'p', '4', 'a') },
6490 { AV_CODEC_ID_AC3 , MKTAG('a', 'c', '-', '3') },
6491 { AV_CODEC_ID_EAC3 , MKTAG('e', 'c', '-', '3') },
6492 { AV_CODEC_ID_DTS , MKTAG('m', 'p', '4', 'a') },
6493 { AV_CODEC_ID_FLAC , MKTAG('f', 'L', 'a', 'C') },
6494 { AV_CODEC_ID_OPUS , MKTAG('O', 'p', 'u', 's') },
6495 { AV_CODEC_ID_VORBIS , MKTAG('m', 'p', '4', 'a') },
6496 { AV_CODEC_ID_QCELP , MKTAG('m', 'p', '4', 'a') },
6497 { AV_CODEC_ID_EVRC , MKTAG('m', 'p', '4', 'a') },
6498 { AV_CODEC_ID_DVD_SUBTITLE, MKTAG('m', 'p', '4', 's') },
6499 { AV_CODEC_ID_MOV_TEXT , MKTAG('t', 'x', '3', 'g') },
6500 { AV_CODEC_ID_NONE , 0 },
6503 const AVCodecTag codec_ism_tags[] = {
6504 { AV_CODEC_ID_WMAPRO , MKTAG('w', 'm', 'a', ' ') },
6505 { AV_CODEC_ID_NONE , 0 },
6508 static const AVCodecTag codec_ipod_tags[] = {
6509 { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
6510 { AV_CODEC_ID_MPEG4, MKTAG('m','p','4','v') },
6511 { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
6512 { AV_CODEC_ID_ALAC, MKTAG('a','l','a','c') },
6513 { AV_CODEC_ID_AC3, MKTAG('a','c','-','3') },
6514 { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
6515 { AV_CODEC_ID_MOV_TEXT, MKTAG('t','e','x','t') },
6516 { AV_CODEC_ID_NONE, 0 },
6519 static const AVCodecTag codec_f4v_tags[] = {
6520 { AV_CODEC_ID_MP3, MKTAG('.','m','p','3') },
6521 { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
6522 { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
6523 { AV_CODEC_ID_VP6A, MKTAG('V','P','6','A') },
6524 { AV_CODEC_ID_VP6F, MKTAG('V','P','6','F') },
6525 { AV_CODEC_ID_NONE, 0 },
6528 #if CONFIG_MOV_MUXER
6530 AVOutputFormat ff_mov_muxer = {
6532 .long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
6533 .extensions = "mov",
6534 .priv_data_size = sizeof(MOVMuxContext),
6535 .audio_codec = AV_CODEC_ID_AAC,
6536 .video_codec = CONFIG_LIBX264_ENCODER ?
6537 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
6539 .write_header = mov_write_header,
6540 .write_packet = mov_write_packet,
6541 .write_trailer = mov_write_trailer,
6543 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6544 .codec_tag = (const AVCodecTag* const []){
6545 ff_codec_movvideo_tags, ff_codec_movaudio_tags, 0
6547 .check_bitstream = mov_check_bitstream,
6548 .priv_class = &mov_muxer_class,
6551 #if CONFIG_TGP_MUXER
6553 AVOutputFormat ff_tgp_muxer = {
6555 .long_name = NULL_IF_CONFIG_SMALL("3GP (3GPP file format)"),
6556 .extensions = "3gp",
6557 .priv_data_size = sizeof(MOVMuxContext),
6558 .audio_codec = AV_CODEC_ID_AMR_NB,
6559 .video_codec = AV_CODEC_ID_H263,
6561 .write_header = mov_write_header,
6562 .write_packet = mov_write_packet,
6563 .write_trailer = mov_write_trailer,
6565 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6566 .codec_tag = (const AVCodecTag* const []){ codec_3gp_tags, 0 },
6567 .check_bitstream = mov_check_bitstream,
6568 .priv_class = &tgp_muxer_class,
6571 #if CONFIG_MP4_MUXER
6573 AVOutputFormat ff_mp4_muxer = {
6575 .long_name = NULL_IF_CONFIG_SMALL("MP4 (MPEG-4 Part 14)"),
6576 .mime_type = "video/mp4",
6577 .extensions = "mp4",
6578 .priv_data_size = sizeof(MOVMuxContext),
6579 .audio_codec = AV_CODEC_ID_AAC,
6580 .video_codec = CONFIG_LIBX264_ENCODER ?
6581 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
6583 .write_header = mov_write_header,
6584 .write_packet = mov_write_packet,
6585 .write_trailer = mov_write_trailer,
6587 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6588 .codec_tag = (const AVCodecTag* const []){ codec_mp4_tags, 0 },
6589 .check_bitstream = mov_check_bitstream,
6590 .priv_class = &mp4_muxer_class,
6593 #if CONFIG_PSP_MUXER
6595 AVOutputFormat ff_psp_muxer = {
6597 .long_name = NULL_IF_CONFIG_SMALL("PSP MP4 (MPEG-4 Part 14)"),
6598 .extensions = "mp4,psp",
6599 .priv_data_size = sizeof(MOVMuxContext),
6600 .audio_codec = AV_CODEC_ID_AAC,
6601 .video_codec = CONFIG_LIBX264_ENCODER ?
6602 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
6604 .write_header = mov_write_header,
6605 .write_packet = mov_write_packet,
6606 .write_trailer = mov_write_trailer,
6608 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6609 .codec_tag = (const AVCodecTag* const []){ codec_mp4_tags, 0 },
6610 .check_bitstream = mov_check_bitstream,
6611 .priv_class = &psp_muxer_class,
6614 #if CONFIG_TG2_MUXER
6616 AVOutputFormat ff_tg2_muxer = {
6618 .long_name = NULL_IF_CONFIG_SMALL("3GP2 (3GPP2 file format)"),
6619 .extensions = "3g2",
6620 .priv_data_size = sizeof(MOVMuxContext),
6621 .audio_codec = AV_CODEC_ID_AMR_NB,
6622 .video_codec = AV_CODEC_ID_H263,
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_3gp_tags, 0 },
6630 .check_bitstream = mov_check_bitstream,
6631 .priv_class = &tg2_muxer_class,
6634 #if CONFIG_IPOD_MUXER
6636 AVOutputFormat ff_ipod_muxer = {
6638 .long_name = NULL_IF_CONFIG_SMALL("iPod H.264 MP4 (MPEG-4 Part 14)"),
6639 .mime_type = "video/mp4",
6640 .extensions = "m4v,m4a",
6641 .priv_data_size = sizeof(MOVMuxContext),
6642 .audio_codec = AV_CODEC_ID_AAC,
6643 .video_codec = AV_CODEC_ID_H264,
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_ipod_tags, 0 },
6651 .check_bitstream = mov_check_bitstream,
6652 .priv_class = &ipod_muxer_class,
6655 #if CONFIG_ISMV_MUXER
6657 AVOutputFormat ff_ismv_muxer = {
6659 .long_name = NULL_IF_CONFIG_SMALL("ISMV/ISMA (Smooth Streaming)"),
6660 .mime_type = "video/mp4",
6661 .extensions = "ismv,isma",
6662 .priv_data_size = sizeof(MOVMuxContext),
6663 .audio_codec = AV_CODEC_ID_AAC,
6664 .video_codec = AV_CODEC_ID_H264,
6666 .write_header = mov_write_header,
6667 .write_packet = mov_write_packet,
6668 .write_trailer = mov_write_trailer,
6670 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
6671 .codec_tag = (const AVCodecTag* const []){
6672 codec_mp4_tags, codec_ism_tags, 0 },
6673 .check_bitstream = mov_check_bitstream,
6674 .priv_class = &ismv_muxer_class,
6677 #if CONFIG_F4V_MUXER
6679 AVOutputFormat ff_f4v_muxer = {
6681 .long_name = NULL_IF_CONFIG_SMALL("F4V Adobe Flash Video"),
6682 .mime_type = "application/f4v",
6683 .extensions = "f4v",
6684 .priv_data_size = sizeof(MOVMuxContext),
6685 .audio_codec = AV_CODEC_ID_AAC,
6686 .video_codec = AV_CODEC_ID_H264,
6688 .write_header = mov_write_header,
6689 .write_packet = mov_write_packet,
6690 .write_trailer = mov_write_trailer,
6692 .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH,
6693 .codec_tag = (const AVCodecTag* const []){ codec_f4v_tags, 0 },
6694 .check_bitstream = mov_check_bitstream,
6695 .priv_class = &f4v_muxer_class,